code
stringlengths
17
6.64M
def validationXXreverse(args, model, device, data_loader, batch_size): logger.info('Starting Validation') model.eval() total_loss = 0 total_acc = 0 with torch.no_grad(): for [data, data_r] in data_loader: data = data.float().unsqueeze(1).to(device) data_r = data_r.f...
def validation_spk(args, cdc_model, spk_model, device, data_loader, batch_size, frame_window): logger.info('Starting Validation') cdc_model.eval() spk_model.eval() total_loss = 0 total_acc = 0 with torch.no_grad(): for [data, target] in data_loader: data = data.float().unsq...
def validation(args, model, device, data_loader, batch_size): logger.info('Starting Validation') model.eval() total_loss = 0 total_acc = 0 with torch.no_grad(): for data in data_loader: data = data.float().transpose(1, 2).to(device) hidden = model.init_hidden(len(da...
class DeepSVDDConf(DetectorConfig): _default_transform = MeanVarNormalize() @initializer def __init__(self, net_name='merlion', xp_path='./results/deepsvdd', load_model='./results/deepsvdd/deepsvdd.pkl', objective='one-class', nu=0.1, device='cpu', seed=(- 1), optimizer_name='adam', lr=0.001, n_epochs=30...
class DeepSVDDModule(object): "A class for the Deep SVDD method.\n\n Attributes:\n objective: A string specifying the Deep SVDD objective (either 'one-class' or 'soft-boundary').\n nu: Deep SVDD hyperparameter nu (must be 0 < nu <= 1).\n R: Hypersphere radius R.\n c: Hypersphere cen...
class BaseADDataset(ABC): 'Anomaly detection dataset base class.' def __init__(self, root: str): super().__init__() self.root = root self.n_classes = 2 self.normal_classes = None self.outlier_classes = None self.train_set = None self.test_set = None ...
class BaseNet(nn.Module): 'Base class for all neural networks.' def __init__(self): super().__init__() self.logger = logging.getLogger(self.__class__.__name__) self.rep_dim = None def forward(self, *input): '\n Forward pass logic\n :return: Network output\n ...
class BaseTrainer(ABC): 'Trainer base class.' def __init__(self, optimizer_name: str, lr: float, n_epochs: int, lr_milestones: tuple, batch_size: int, weight_decay: float, device: str, n_jobs_dataloader: int): super().__init__() self.optimizer_name = optimizer_name self.lr = lr ...
class TorchvisionDataset(BaseADDataset): 'TorchvisionDataset class for datasets already implemented in torchvision.datasets.' def __init__(self, root: str): super().__init__(root) def loaders(self, batch_size: int, shuffle_train=True, shuffle_test=False, num_workers: int=0) -> (DataLoader, DataL...
def build_network(config): 'Builds the neural network.' implemented_networks = 'merlion' assert (config.net_name in implemented_networks) net = None if (config.net_name == 'merlion'): net = Merlion_MLP(config) return net
def build_autoencoder(config): 'Builds the corresponding autoencoder network.' implemented_networks = 'merlion' assert (config.net_name in implemented_networks) ae_net = None if (config.net_name == 'merlion'): ae_net = Merlion_MLP_Autoencoder(config) return ae_net
def build_network(config): 'Builds the neural network.' implemented_networks = ('merlion', 'lstmae') assert (config.net_name in implemented_networks) net = None if (config.net_name == 'merlion'): net = Merlion_MLP(config) elif (config.net_name == 'lstmae'): net = LSTMEncoder(co...
def build_autoencoder(config): 'Builds the corresponding autoencoder network.' implemented_networks = ('merlion', 'lstmae') assert (config.net_name in implemented_networks) ae_net = None if (config.net_name == 'merlion'): ae_net = Merlion_MLP_Autoencoder(config) elif (config.net_name =...
class AETrainer(BaseTrainer): def __init__(self, optimizer_name: str='adam', lr: float=0.001, n_epochs: int=150, lr_milestones: tuple=(), batch_size: int=128, weight_decay: float=1e-06, device: str='cpu', n_jobs_dataloader: int=0): super().__init__(optimizer_name, lr, n_epochs, lr_milestones, batch_size,...
class DeepSVDDTrainer(BaseTrainer): def __init__(self, objective, R, c, nu: float, optimizer_name: str='adam', lr: float=0.001, n_epochs: int=150, lr_milestones: tuple=(), batch_size: int=128, weight_decay: float=1e-06, device: str='cuda', n_jobs_dataloader: int=0): super().__init__(optimizer_name, lr, n...
def get_radius(dist: torch.Tensor, nu: float): 'Optimally solve for radius R via the (1-nu)-quantile of distances.' return np.quantile(np.sqrt(dist.clone().data.cpu().numpy()), (1 - nu))
class OCSVMConf(DetectorConfig): _default_transform = MeanVarNormalize() @initializer def __init__(self, kernel='rbf', nu=0.005, degree=3, gamma='scale', sequence_len=32, **kwargs): super(OCSVMConf, self).__init__(**kwargs)
class OCSVM(DetectorBase): '\n The OC-SVM-based time series anomaly detector.\n ' config_class = OCSVMConf def __init__(self, config: OCSVMConf): super().__init__(config) self.kernel = config.kernel self.nu = config.nu self.degree = config.degree self.gamma =...
def set_requires_grad(model, dict_, requires_grad=True): for param in model.named_parameters(): if (param[0] in dict_): param[1].requires_grad = requires_grad
def fix_randomness(SEED): random.seed(SEED) np.random.seed(SEED) torch.manual_seed(SEED) torch.cuda.manual_seed(SEED) torch.backends.cudnn.deterministic = True
def epoch_time(start_time, end_time): elapsed_time = (end_time - start_time) elapsed_mins = int((elapsed_time / 60)) elapsed_secs = int((elapsed_time - (elapsed_mins * 60))) return (elapsed_mins, elapsed_secs)
def _calc_metrics(pred_labels, true_labels, log_dir, home_path): pred_labels = np.array(pred_labels).astype(int) true_labels = np.array(true_labels).astype(int) labels_save_path = os.path.join(log_dir, 'labels') os.makedirs(labels_save_path, exist_ok=True) np.save(os.path.join(labels_save_path, 'p...
def _logger(logger_name, level=logging.DEBUG): '\n Method to return a custom logger with the given name and level\n ' logger = logging.getLogger(logger_name) logger.setLevel(level) format_string = '%(message)s' log_format = logging.Formatter(format_string) console_handler = logging.Strea...
def copy_Files(destination, data_type): destination_dir = os.path.join(destination, 'model_files') os.makedirs(destination_dir, exist_ok=True)
class Config(object): def __init__(self): self.input_channels = 1 self.kernel_size = 8 self.stride = 1 self.final_out_channels = 128 self.num_classes = 2 self.dropout = 0.35 self.features_len = 24 self.num_epoch = 40 self.beta1 = 0.9 ...
class augmentations(object): def __init__(self): self.jitter_scale_ratio = 0.001 self.jitter_ratio = 0.001 self.max_seg = 5
class Context_Cont_configs(object): def __init__(self): self.temperature = 0.2 self.use_cosine_similarity = True
class TC(object): def __init__(self): self.hidden_dim = 100 self.timesteps = 10
class Config(object): def __init__(self): self.input_channels = 9 self.kernel_size = 8 self.stride = 1 self.final_out_channels = 128 self.num_classes = 6 self.dropout = 0.35 self.features_len = 18 self.num_epoch = 40 self.beta1 = 0.9 ...
class augmentations(object): def __init__(self): self.jitter_scale_ratio = 1.1 self.jitter_ratio = 0.8 self.max_seg = 8
class Context_Cont_configs(object): def __init__(self): self.temperature = 0.2 self.use_cosine_similarity = True
class TC(object): def __init__(self): self.hidden_dim = 100 self.timesteps = 6
class Config(object): def __init__(self): self.input_channels = 1 self.kernel_size = 8 self.stride = 1 self.final_out_channels = 32 self.num_classes = 2 self.dropout = 0.35 self.features_len = 4 self.window_size = 18 self.time_step = 18 ...
class augmentations(object): def __init__(self): self.jitter_scale_ratio = 1.1 self.jitter_ratio = 0.8 self.max_seg = 8
class Context_Cont_configs(object): def __init__(self): self.temperature = 0.2 self.use_cosine_similarity = True
class TC(object): def __init__(self): self.hidden_dim = 100 self.timesteps = 2
class Config(object): def __init__(self): self.input_channels = 1 self.kernel_size = 8 self.stride = 1 self.final_out_channels = 8 self.num_classes = 2 self.dropout = 0.35 self.features_len = 4 self.window_size = 18 self.time_step = 18 ...
class augmentations(object): def __init__(self): self.jitter_scale_ratio = 1.1 self.jitter_ratio = 0.8 self.max_seg = 8
class Context_Cont_configs(object): def __init__(self): self.temperature = 0.2 self.use_cosine_similarity = True
class TC(object): def __init__(self): self.hidden_dim = 100 self.timesteps = 2
class Config(object): def __init__(self): self.input_channels = 18 self.kernel_size = 8 self.stride = 1 self.final_out_channels = 128 self.num_classes = 2 self.dropout = 0.35 self.features_len = 7 self.window_size = 18 self.time_step = 1 ...
class augmentations(object): def __init__(self): self.jitter_scale_ratio = 1.1 self.jitter_ratio = 0.8 self.max_seg = 8
class Context_Cont_configs(object): def __init__(self): self.temperature = 0.2 self.use_cosine_similarity = True
class TC(object): def __init__(self): self.hidden_dim = 100 self.timesteps = 2
class Config(object): def __init__(self): self.input_channels = 1 self.kernel_size = 32 self.stride = 4 self.final_out_channels = 128 self.features_len = 162 self.num_classes = 3 self.dropout = 0.35 self.corruption_prob = 0.3 self.num_epoch ...
class augmentations(object): def __init__(self): self.jitter_scale_ratio = 2 self.jitter_ratio = 0.1 self.max_seg = 5
class Context_Cont_configs(object): def __init__(self): self.temperature = 0.2 self.use_cosine_similarity = True
class TC(object): def __init__(self): self.hidden_dim = 64 self.timesteps = 50
class Config(object): def __init__(self): self.input_channels = 1 self.final_out_channels = 128 self.num_classes = 5 self.dropout = 0.35 self.kernel_size = 25 self.stride = 3 self.features_len = 127 self.num_epoch = 40 self.optimizer = 'adam...
class augmentations(object): def __init__(self): self.jitter_scale_ratio = 1.5 self.jitter_ratio = 2 self.max_seg = 12
class Context_Cont_configs(object): def __init__(self): self.temperature = 0.2 self.use_cosine_similarity = True
class TC(object): def __init__(self): self.hidden_dim = 64 self.timesteps = 50
class Load_Dataset(Dataset): def __init__(self, dataset, config, training_mode): super(Load_Dataset, self).__init__() self.training_mode = training_mode X_train = dataset['samples'] y_train = dataset['labels'] if (len(X_train.shape) < 3): X_train = X_train.unsq...
def data_generator(data_path, configs, training_mode): train_dataset = torch.load(os.path.join(data_path, 'train.pt')) valid_dataset = torch.load(os.path.join(data_path, 'val.pt')) test_dataset = torch.load(os.path.join(data_path, 'test.pt')) train_dataset = Load_Dataset(train_dataset, configs, traini...
def data_generator1(time_series, time_series_label, configs, training_mode): time_series = time_series.to_numpy() time_series_label = time_series_label.to_numpy() augments = ts_augmentation(time_series) time_series = np.concatenate([time_series, augments], axis=0) time_series_label = np.concatenat...
def data_generator4(train_data, test_data, train_labels, test_labels, configs, training_mode): train_time_series_ts = train_data test_time_series_ts = test_data mvn = MeanVarNormalize() mvn.train((train_time_series_ts + test_time_series_ts)) (bias, scale) = (mvn.bias, mvn.scale) train_time_ser...
class NTXentLoss(torch.nn.Module): def __init__(self, device, batch_size, temperature, use_cosine_similarity): super(NTXentLoss, self).__init__() self.batch_size = batch_size self.temperature = temperature self.device = device self.softmax = torch.nn.Softmax(dim=(- 1)) ...
class base_Model(nn.Module): def __init__(self, configs): super(base_Model, self).__init__() self.conv_block1 = nn.Sequential(nn.Conv1d(configs.input_channels, 32, kernel_size=configs.kernel_size, stride=configs.stride, bias=False, padding=(configs.kernel_size // 2)), nn.BatchNorm1d(32), nn.ReLU(...
def Trainer(model, model_optimizer, train_dl, val_dl, test_dl, device, logger, config): logger.debug('one-class classfication fine-tune started ....') scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(model_optimizer, 'min') (all_epoch_train_loss, all_epoch_test_loss) = ([], []) center = torch.ze...
def model_train(model, model_optimizer, train_loader, center, length, config, device, epoch): (total_loss, total_f1, total_precision, total_recall) = ([], [], [], []) (all_target, all_predict) = ([], []) model.train() for (batch_idx, (data, target, aug1, aug2)) in enumerate(train_loader): (dat...
def model_evaluate(model, test_dl, center, length, config, device, epoch): model.eval() (total_loss, total_f1, total_precision, total_recall) = ([], [], [], []) (all_target, all_predict) = ([], []) all_projection = [] with torch.no_grad(): for (data, target, aug1, aug2) in test_dl: ...
def train(feature1, center, length, epoch, config, device): center = center.unsqueeze(0) center = F.normalize(center, dim=1) feature1 = F.normalize(feature1, dim=1) distance1 = F.cosine_similarity(feature1, center, eps=1e-06) distance1 = (1 - distance1) score = distance1 if (config.objecti...
def center_c(train_loader, model, device, center, config, eps=0.1): 'Initialize hypersphere center c as the mean from an initial forward pass on the data.' n_samples = 0 c = center model.eval() with torch.no_grad(): for data in train_loader: (data, target, aug1, aug2) = data ...
def get_radius(dist: torch.Tensor, nu: float): 'Optimally solve for radius R via the (1-nu)-quantile of distances.' dist = dist.reshape((- 1)) return np.quantile(dist.clone().data.cpu().numpy(), (1 - nu))
def Trainer(model, temporal_contr_model, model_optimizer, temp_cont_optimizer, train_dl, valid_dl, test_dl, device, logger, config, experiment_log_dir, training_mode): logger.debug('Training started ....') criterion = nn.CrossEntropyLoss() scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(model_optim...
def model_train(model, temporal_contr_model, model_optimizer, temp_cont_optimizer, criterion, train_loader, config, device, training_mode): total_loss = [] total_acc = [] model.train() temporal_contr_model.train() for (batch_idx, (data, target, aug1, aug2)) in enumerate(train_loader): (dat...
def model_evaluate(model, temporal_contr_model, test_dl, device, training_mode): model.eval() temporal_contr_model.eval() total_loss = [] total_acc = [] criterion = nn.CrossEntropyLoss() outs = np.array([]) trgs = np.array([]) with torch.no_grad(): for (data, target, _, _) in t...
def ad_predict(target, scores, mode, nu): if_aff = np.count_nonzero(target) if (if_aff != 0): events_gt = convert_vector_to_events(target) target = TimeSeries.from_pd(pd.DataFrame(target)) scores = np.array(scores) mean = np.mean(scores) std = np.std(scores) if (std != 0): ...
class reasonable_accumulator(): def __init__(self, cnt=0, correct_num=0): self.cnt = cnt self.correct_num = correct_num def __add__(self, acc): kwargs = {'cnt': (self.cnt + acc.cnt), 'correct_num': (self.correct_num + acc.correct_num)} return reasonable_accumulator(**kwargs) ...
def tsad_reasonable(ground_truth, predict, time_step): '\n Computes the components required to compute multiple different types of\n performance metrics for time series anomaly detection.\n\n Anomaly detection metrics for UCR Time Series Anomaly Detection datasets by\n `Lu, Yue, et al. "Matrix Profil...
def get_dataset(dataset_name: str, rootdir: str=None) -> TSADBaseDataset: '\n :param dataset_name: the name of the dataset to load, formatted as\n ``<name>`` or ``<name>_<subset>``, e.g. ``IOPsCompetition``\n or ``NAB_realAWSCloudwatch``\n :param rootdir: the directory where the desired datase...
class TSADBaseDataset(BaseDataset): __doc__ = ((_intro_docstr + _main_fns_docstr) + _extra_note) @property def max_lead_sec(self): '\n The maximum number of seconds an anomaly may be detected early, for\n this dataset. ``None`` signifies no early detections allowed, or that\n ...
class IOpsCompetition(TSADBaseDataset): '\n Wrapper to load the dataset used for the final round of the IOPs competition\n (http://iops.ai/competition_detail/?competition_id=5).\n\n The dataset contains 29 time series of KPIs gathered from large tech\n companies (Alibaba, Sogou, Tencent, Baidu, and eB...
class MSL(TSADBaseDataset): '\n Soil Moisture Active Passive (SMAP) satellite and Mars Science Laboratory (MSL) rover Datasets.\n SMAP and MSL are two realworld public datasets, which are two real-world datasets expert-labeled by NASA.\n\n - source: https://github.com/khundman/telemanom\n ' url = ...
class SMAP(TSADBaseDataset): '\n Soil Moisture Active Passive (SMAP) satellite and Mars Science Laboratory (MSL) rover Datasets.\n SMAP and MSL are two realworld public datasets, which are two real-world datasets expert-labeled by NASA.\n\n - source: https://github.com/khundman/telemanom\n ' url =...
def preprocess(logger, data_folder, dataset): if (os.path.exists(os.path.join(data_folder, f'{dataset}_test_label.pkl')) and os.path.exists(os.path.join(data_folder, f'{dataset}_train.pkl')) and os.path.exists(os.path.join(data_folder, f'{dataset}_test.pkl'))): return logger.info(f'Preprocessing {data...
def load_data(directory, dataset): with open(os.path.join(directory, f'{dataset}_test.pkl'), 'rb') as f: test_data = pickle.load(f) with open(os.path.join(directory, f'{dataset}_test_label.pkl'), 'rb') as f: test_labels = pickle.load(f) with open(os.path.join(directory, f'{dataset}_train.p...
class SMD(TSADBaseDataset): '\n The Server Machine Dataset (SMD) is a new 5-week-long dataset from\n a large Internet company collected and made publicly available.\n It contains data from 28 server machines and each machine is monitored by 33 metrics.\n SMD is divided into training set and testing se...
def combine_train_test_datasets(train_df, test_df, test_labels): train_df.columns = [str(c) for c in train_df.columns] test_df.columns = [str(c) for c in test_df.columns] df = pd.concat([train_df, test_df]).reset_index() if ('index' in df): df.drop(columns=['index'], inplace=True) df.index...
def download(logger, datapath, url, filename): os.makedirs(datapath, exist_ok=True) compressed_file = os.path.join(datapath, f'{filename}.tar.gz') if (not os.path.exists(compressed_file)): logger.info(('Downloading ' + url)) with requests.get(url, stream=True) as r: with open(c...
class Synthetic(TSADBaseDataset): '\n Wrapper to load a sythetically generated dataset.\n The dataset was generated using three base time series, each of which\n was separately injected with shocks, spikes, dips and level shifts, making\n a total of 15 time series (including the base time series witho...
class UCR(TSADBaseDataset): '\n Data loader for the Hexagon ML/UC Riverside Time Series Anomaly Archive.\n\n See `here <https://compete.hexagon-ml.com/practice/competition/39/>`_ for details.\n\n Hoang Anh Dau, Eamonn Keogh, Kaveh Kamgar, Chin-Chia Michael Yeh, Yan Zhu,\n Shaghayegh Gharghabi, Chotira...
class BaseDataset(): __doc__ = (_intro_docstr + _main_fns_docstr) time_series: list '\n A list of all individual time series contained in the dataset. Iterating over\n the dataset will iterate over this list. Note that for some large datasets, \n ``time_series`` may be a list of filenames, which ...
def get_dataset(dataset_name: str, rootdir: str=None) -> BaseDataset: '\n :param dataset_name: the name of the dataset to load, formatted as\n ``<name>`` or ``<name>_<subset>``, e.g. ``EnergyPower`` or ``M4_Hourly``\n :param rootdir: the directory where the desired dataset is stored. Not\n req...
class EnergyPower(BaseDataset): '\n Wrapper to load the open source energy grid power usage dataset.\n\n - source: https://www.kaggle.com/robikscube/hourly-energy-consumption\n - contains one 10-variable time series\n ' def __init__(self, rootdir=None): '\n :param rootdir: The root...
class SeattleTrail(BaseDataset): '\n Wrapper to load the open source Seattle Trail pedestrian/bike traffic\n dataset.\n\n - source: https://www.kaggle.com/city-of-seattle/seattle-burke-gilman-trail\n - contains one 5-variable time series\n ' def __init__(self, rootdir=None): '\n ...
class SolarPlant(BaseDataset): '\n Wrapper to load the open source solar plant power dataset.\n\n - source: https://www.nrel.gov/grid/solar-power-data.html\n - contains one 405-variable time series\n\n .. note::\n\n The loader currently only includes the first 100 (of 405) variables.\n ' ...
class affiliation_accumulator(): def __init__(self, cnt=0, precision=0, recall=0, individual_precision_probabilities=0, individual_recall_probabilities=0, individual_precision_distances=0, individual_recall_distances=0): self.cnt = cnt self.precision = precision self.recall = recall ...
def tsad_affiliation(ground_truth: TimeSeries, predict: TimeSeries): '\n Computes the components required to compute multiple different types of\n performance metrics for time series anomaly detection.\n ' if isinstance(ground_truth, TimeSeries): assert ((ground_truth.dim == 1) and (predict.d...
class reasonable_accumulator(): def __init__(self, cnt=0, correct_num=0): self.cnt = cnt self.correct_num = correct_num def __add__(self, acc): kwargs = {'cnt': (self.cnt + acc.cnt), 'correct_num': (self.correct_num + acc.correct_num)} return reasonable_accumulator(**kwargs) ...
def tsad_reasonable(ground_truth, predict): '\n Computes the components required to compute multiple different types of\n performance metrics for time series anomaly detection.\n ' if (isinstance(ground_truth, TimeSeries) and isinstance(predict, TimeSeries)): assert ((ground_truth.dim == 1) a...
def evaluate_predictions(model_names, dataset, all_model_preds, metric: TSADMetric, pointwise_metric: TSADMetric, point_adj_metric: TSADMetric, tune_on_test=False, unsupervised=False, debug=False): (scores_rpa, scores_pw, scores_pa) = ([], [], []) use_ucr_eval = (isinstance(dataset, UCR) and (unsupervised or ...
def df_to_merlion(df: pd.DataFrame, md: pd.DataFrame, get_ground_truth=False, transform=None) -> TimeSeries: 'Converts a pandas dataframe time series to the Merlion format.' if get_ground_truth: if (False and ('changepoint' in md.keys())): series = (md['anomaly'] | md['changepoint']) ...
def dataset_to_threshold(dataset: TSADBaseDataset, tune_on_test=False): if isinstance(dataset, IOpsCompetition): return 2.25 elif isinstance(dataset, NAB): return 3.5 elif isinstance(dataset, Synthetic): return 2 elif isinstance(dataset, MSL): return 3.0 elif isinst...
def get_model(model_name: str, dataset: TSADBaseDataset, metric: TSADMetric, tune_on_test=False, unsupervised=False) -> Tuple[(DetectorBase, dict)]: with open(CONFIG_JSON, 'r') as f: config_dict = json.load(f) if (model_name not in config_dict): raise NotImplementedError(f'Benchmarking not imp...
def resolve_model_name(model_name: str): with open(CONFIG_JSON, 'r') as f: config_dict = json.load(f) if (model_name not in config_dict): raise NotImplementedError(f'Benchmarking not implemented for model {model_name}. Valid model names are {list(config_dict.keys())}') while ('alias' in co...
def read_model_predictions(dataset: TSADBaseDataset, model_dir: str): "\n Returns a list of lists all_preds, where all_preds[i] is the model's raw\n anomaly scores for time series i in the dataset.\n " csv = os.path.join('results', 'anomaly', model_dir, f'pred_{dataset_to_name(dataset)}.csv.gz') ...
def dataset_to_name(dataset: TSADBaseDataset): if (dataset.subset is not None): return f'{type(dataset).__name__}_{dataset.subset}' return type(dataset).__name__
class ScheduledOptim(object): 'A simple wrapper class for learning rate scheduling' def __init__(self, optimizer, n_warmup_steps): self.optimizer = optimizer self.d_model = 128 self.n_warmup_steps = n_warmup_steps self.n_current_steps = 0 self.delta = 1 def state_...
class Timer(object): def __init__(self): self.__start = time.time() def start(self): self.__start = time.time() def get_time(self, restart=True, format=False): end = time.time() span = (end - self.__start) if restart: self.__start = end if for...