repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
muammar/chemprop
|
[
"c46e511eaa9d07da319571ce6c44bb19effa7c5b"
] |
[
"chemprop/utils.py"
] |
[
"from argparse import Namespace\nimport csv\nfrom datetime import timedelta\nfrom functools import wraps\nimport logging\nimport math\nimport os\nimport pickle\nimport re\nfrom time import time\nfrom typing import Any, Callable, List, Tuple, Union\nimport collections\n\nfrom sklearn.metrics import auc, mean_absolute_error, mean_squared_error, precision_recall_curve, r2_score,\\\n roc_auc_score, accuracy_score, log_loss\nimport torch\nimport torch.nn as nn\nfrom torch.optim import Adam, Optimizer\nfrom torch.optim.lr_scheduler import _LRScheduler\nfrom tqdm import tqdm\n\nfrom chemprop.args import PredictArgs, TrainArgs\nfrom chemprop.data import StandardScaler, MoleculeDataset, preprocess_smiles_columns, get_task_names\nfrom chemprop.models import MoleculeModel\nfrom chemprop.nn_utils import NoamLR\nfrom chemprop.spectra_utils import sid_loss, sid_metric, wasserstein_loss, wasserstein_metric\n\n\ndef makedirs(path: str, isfile: bool = False) -> None:\n \"\"\"\n Creates a directory given a path to either a directory or file.\n\n If a directory is provided, creates that directory. If a file is provided (i.e. :code:`isfile == True`),\n creates the parent directory for that file.\n\n :param path: Path to a directory or file.\n :param isfile: Whether the provided path is a directory or file.\n \"\"\"\n if isfile:\n path = os.path.dirname(path)\n if path != '':\n os.makedirs(path, exist_ok=True)\n\n\ndef save_checkpoint(path: str,\n model: MoleculeModel,\n scaler: StandardScaler = None,\n features_scaler: StandardScaler = None,\n atom_descriptor_scaler: StandardScaler = None,\n bond_feature_scaler: StandardScaler = None,\n args: TrainArgs = None) -> None:\n \"\"\"\n Saves a model checkpoint.\n\n :param model: A :class:`~chemprop.models.model.MoleculeModel`.\n :param scaler: A :class:`~chemprop.data.scaler.StandardScaler` fitted on the data.\n :param features_scaler: A :class:`~chemprop.data.scaler.StandardScaler` fitted on the features.\n :param atom_descriptor_scaler: A :class:`~chemprop.data.scaler.StandardScaler` fitted on the atom descriptors.\n :param bond_feature_scaler: A :class:`~chemprop.data.scaler.StandardScaler` fitted on the bond_fetaures.\n :param args: The :class:`~chemprop.args.TrainArgs` object containing the arguments the model was trained with.\n :param path: Path where checkpoint will be saved.\n \"\"\"\n # Convert args to namespace for backwards compatibility\n if args is not None:\n args = Namespace(**args.as_dict())\n\n state = {\n 'args': args,\n 'state_dict': model.state_dict(),\n 'data_scaler': {\n 'means': scaler.means,\n 'stds': scaler.stds\n } if scaler is not None else None,\n 'features_scaler': {\n 'means': features_scaler.means,\n 'stds': features_scaler.stds\n } if features_scaler is not None else None,\n 'atom_descriptor_scaler': {\n 'means': atom_descriptor_scaler.means,\n 'stds': atom_descriptor_scaler.stds\n } if atom_descriptor_scaler is not None else None,\n 'bond_feature_scaler': {\n 'means': bond_feature_scaler.means,\n 'stds': bond_feature_scaler.stds\n } if bond_feature_scaler is not None else None\n }\n torch.save(state, path)\n\n\ndef load_checkpoint(path: str,\n device: torch.device = None,\n logger: logging.Logger = None) -> MoleculeModel:\n \"\"\"\n Loads a model checkpoint.\n\n :param path: Path where checkpoint is saved.\n :param device: Device where the model will be moved.\n :param logger: A logger for recording output.\n :return: The loaded :class:`~chemprop.models.model.MoleculeModel`.\n \"\"\"\n if logger is not None:\n debug, info = logger.debug, logger.info\n else:\n debug = info = print\n\n # Load model and args\n state = torch.load(path, map_location=lambda storage, loc: storage)\n args = TrainArgs()\n args.from_dict(vars(state['args']), skip_unsettable=True)\n loaded_state_dict = state['state_dict']\n\n if device is not None:\n args.device = device\n\n # Build model\n model = MoleculeModel(args)\n model_state_dict = model.state_dict()\n\n # Skip missing parameters and parameters of mismatched size\n pretrained_state_dict = {}\n for loaded_param_name in loaded_state_dict.keys():\n # Backward compatibility for parameter names\n if re.match(r'(encoder\\.encoder\\.)([Wc])', loaded_param_name):\n param_name = loaded_param_name.replace('encoder.encoder', 'encoder.encoder.0')\n else:\n param_name = loaded_param_name\n\n # Load pretrained parameter, skipping unmatched parameters\n if param_name not in model_state_dict:\n info(f'Warning: Pretrained parameter \"{loaded_param_name}\" cannot be found in model parameters.')\n elif model_state_dict[param_name].shape != loaded_state_dict[loaded_param_name].shape:\n info(f'Warning: Pretrained parameter \"{loaded_param_name}\" '\n f'of shape {loaded_state_dict[loaded_param_name].shape} does not match corresponding '\n f'model parameter of shape {model_state_dict[param_name].shape}.')\n else:\n debug(f'Loading pretrained parameter \"{loaded_param_name}\".')\n pretrained_state_dict[param_name] = loaded_state_dict[loaded_param_name]\n\n # Load pretrained weights\n model_state_dict.update(pretrained_state_dict)\n model.load_state_dict(model_state_dict)\n\n if args.cuda:\n debug('Moving model to cuda')\n model = model.to(args.device)\n\n return model\n\n\ndef overwrite_state_dict(loaded_param_name: str,\n model_param_name: str,\n loaded_state_dict: collections.OrderedDict,\n model_state_dict: collections.OrderedDict,\n logger: logging.Logger = None) -> collections.OrderedDict:\n \"\"\"\n Overwrites a given parameter in the current model with the loaded model.\n :param loaded_param_name: name of parameter in checkpoint model.\n :param model_param_name: name of parameter in current model.\n :param loaded_state_dict: state_dict for checkpoint model.\n :param model_state_dict: state_dict for current model.\n :param logger: A logger.\n :return: The updated state_dict for the current model. \n \"\"\"\n debug = logger.debug if logger is not None else print\n\n \n if model_param_name not in model_state_dict:\n debug(f'Pretrained parameter \"{model_param_name}\" cannot be found in model parameters.')\n \n elif model_state_dict[model_param_name].shape != loaded_state_dict[loaded_param_name].shape:\n debug(f'Pretrained parameter \"{loaded_param_name}\" '\n f'of shape {loaded_state_dict[loaded_param_name].shape} does not match corresponding '\n f'model parameter of shape {model_state_dict[model_param_name].shape}.')\n \n else:\n debug(f'Loading pretrained parameter \"{model_param_name}\".')\n model_state_dict[model_param_name] = loaded_state_dict[loaded_param_name] \n \n return model_state_dict\n\ndef load_frzn_model(model: torch.nn,\n path: str,\n current_args: Namespace = None,\n cuda: bool = None,\n logger: logging.Logger = None) -> MoleculeModel:\n \"\"\"\n Loads a model checkpoint.\n :param path: Path where checkpoint is saved.\n :param current_args: The current arguments. Replaces the arguments loaded from the checkpoint if provided.\n :param cuda: Whether to move model to cuda.\n :param logger: A logger.\n :return: The loaded MoleculeModel.\n \"\"\"\n debug = logger.debug if logger is not None else print\n\n loaded_mpnn_model = torch.load(path, map_location=lambda storage, loc: storage)\n loaded_state_dict = loaded_mpnn_model['state_dict']\n loaded_args = loaded_mpnn_model['args']\n\n model_state_dict = model.state_dict()\n \n if loaded_args.number_of_molecules==1 & current_args.number_of_molecules==1: \n encoder_param_names = ['encoder.encoder.0.W_i.weight', 'encoder.encoder.0.W_h.weight', 'encoder.encoder.0.W_o.weight', 'encoder.encoder.0.W_o.bias']\n if current_args.checkpoint_frzn is not None:\n # Freeze the MPNN\n for param_name in encoder_param_names:\n model_state_dict = overwrite_state_dict(param_name,param_name,loaded_state_dict,model_state_dict)\n \n if current_args.frzn_ffn_layers > 0: \n ffn_param_names = [['ffn.'+str(i*3+1)+'.weight','ffn.'+str(i*3+1)+'.bias'] for i in range(current_args.frzn_ffn_layers)]\n ffn_param_names = [item for sublist in ffn_param_names for item in sublist]\n \n # Freeze MPNN and FFN layers\n for param_name in encoder_param_names+ffn_param_names:\n model_state_dict = overwrite_state_dict(param_name,param_name,loaded_state_dict,model_state_dict) \n \n if current_args.freeze_first_only:\n debug(f'WARNING: --freeze_first_only flag cannot be used with number_of_molecules=1 (flag is ignored)')\n \n elif (loaded_args.number_of_molecules==1) & (current_args.number_of_molecules>1):\n \n if (current_args.checkpoint_frzn is not None) & (current_args.freeze_first_only) & (not (current_args.frzn_ffn_layers > 0)): # Only freeze first MPNN\n encoder_param_names = ['encoder.encoder.0.W_i.weight', 'encoder.encoder.0.W_h.weight', 'encoder.encoder.0.W_o.weight', 'encoder.encoder.0.W_o.bias']\n for param_name in encoder_param_names:\n model_state_dict = overwrite_state_dict(param_name,param_name,loaded_state_dict,model_state_dict)\n \n if (current_args.checkpoint_frzn is not None) & (not current_args.freeze_first_only) & (not (current_args.frzn_ffn_layers > 0)): # Duplicate encoder from frozen checkpoint and overwrite all encoders\n loaded_encoder_param_names = ['encoder.encoder.0.W_i.weight', 'encoder.encoder.0.W_h.weight', 'encoder.encoder.0.W_o.weight', 'encoder.encoder.0.W_o.bias']*current_args.number_of_molecules\n model_encoder_param_names = [['encoder.encoder.'+str(mol_num)+'.W_i.weight', 'encoder.encoder.'+str(mol_num)+'.W_h.weight', 'encoder.encoder.'+str(mol_num)+'.W_o.weight', 'encoder.encoder.'+str(mol_num)+'.W_o.bias'] for mol_num in range(current_args.number_of_molecules)]\n model_encoder_param_names = [item for sublist in model_encoder_param_names for item in sublist]\n for loaded_param_name,model_param_name in zip(loaded_encoder_param_names,model_encoder_param_names):\n model_state_dict = overwrite_state_dict(loaded_param_name,model_param_name,loaded_state_dict,model_state_dict)\n \n if current_args.frzn_ffn_layers > 0: # Duplicate encoder from frozen checkpoint and overwrite all encoders + FFN layers\n raise Exception ('Number of molecules in checkpoint_frzn must be equal to current model for ffn layers to be frozen')\n \n elif (loaded_args.number_of_molecules>1 )& (current_args.number_of_molecules>1):\n if (loaded_args.number_of_molecules) !=( current_args.number_of_molecules):\n raise Exception('Number of molecules in checkpoint_frzn ({}) must match current model ({}) OR equal to 1.'.format(loaded_args.number_of_molecules,current_args.number_of_molecules))\n \n if current_args.freeze_first_only:\n raise Exception('Number of molecules in checkpoint_frzn ({}) must be equal to 1 for freeze_first_only to be used.'.format(loaded_args.number_of_molecules))\n \n if (current_args.checkpoint_frzn is not None) & (not (current_args.frzn_ffn_layers > 0)):\n encoder_param_names = [['encoder.encoder.'+str(mol_num)+'.W_i.weight', 'encoder.encoder.'+str(mol_num)+'.W_h.weight', 'encoder.encoder.'+str(mol_num)+'.W_o.weight', 'encoder.encoder.'+str(mol_num)+'.W_o.bias'] for mol_num in range(current_args.number_of_molecules)]\n encoder_param_names = [item for sublist in encoder_param_names for item in sublist]\n \n for param_name in encoder_param_names:\n model_state_dict = overwrite_state_dict(param_name,param_name,loaded_state_dict,model_state_dict)\n \n if current_args.frzn_ffn_layers > 0:\n \n encoder_param_names = [['encoder.encoder.'+str(mol_num)+'.W_i.weight', 'encoder.encoder.'+str(mol_num)+'.W_h.weight', 'encoder.encoder.'+str(mol_num)+'.W_o.weight', 'encoder.encoder.'+str(mol_num)+'.W_o.bias'] for mol_num in range(current_args.number_of_molecules)]\n encoder_param_names = [item for sublist in encoder_param_names for item in sublist] \n ffn_param_names = [['ffn.'+str(i*3+1)+'.weight','ffn.'+str(i*3+1)+'.bias'] for i in range(current_args.frzn_ffn_layers)]\n ffn_param_names = [item for sublist in ffn_param_names for item in sublist]\n \n for param_name in encoder_param_names + ffn_param_names:\n model_state_dict = overwrite_state_dict(param_name,param_name,loaded_state_dict,model_state_dict) \n \n if current_args.frzn_ffn_layers >= current_args.ffn_num_layers:\n raise Exception('Number of frozen FFN layers must be less than the number of FFN layers')\n \n # Load pretrained weights\n model.load_state_dict(model_state_dict)\n \n return model\n \ndef load_scalers(path: str) -> Tuple[StandardScaler, StandardScaler, StandardScaler, StandardScaler]:\n \"\"\"\n Loads the scalers a model was trained with.\n\n :param path: Path where model checkpoint is saved.\n :return: A tuple with the data :class:`~chemprop.data.scaler.StandardScaler`\n and features :class:`~chemprop.data.scaler.StandardScaler`.\n \"\"\"\n state = torch.load(path, map_location=lambda storage, loc: storage)\n\n scaler = StandardScaler(state['data_scaler']['means'],\n state['data_scaler']['stds']) if state['data_scaler'] is not None else None\n features_scaler = StandardScaler(state['features_scaler']['means'],\n state['features_scaler']['stds'],\n replace_nan_token=0) if state['features_scaler'] is not None else None\n\n if 'atom_descriptor_scaler' in state.keys():\n atom_descriptor_scaler = StandardScaler(state['atom_descriptor_scaler']['means'],\n state['atom_descriptor_scaler']['stds'],\n replace_nan_token=0) if state['atom_descriptor_scaler'] is not None else None\n else:\n atom_descriptor_scaler = None\n\n if 'bond_feature_scaler' in state.keys():\n bond_feature_scaler = StandardScaler(state['bond_feature_scaler']['means'],\n state['bond_feature_scaler']['stds'],\n replace_nan_token=0) if state['bond_feature_scaler'] is not None else None\n else:\n bond_feature_scaler = None\n\n return scaler, features_scaler, atom_descriptor_scaler, bond_feature_scaler\n\n\ndef load_args(path: str) -> TrainArgs:\n \"\"\"\n Loads the arguments a model was trained with.\n\n :param path: Path where model checkpoint is saved.\n :return: The :class:`~chemprop.args.TrainArgs` object that the model was trained with.\n \"\"\"\n args = TrainArgs()\n args.from_dict(vars(torch.load(path, map_location=lambda storage, loc: storage)['args']), skip_unsettable=True)\n\n return args\n\n\ndef load_task_names(path: str) -> List[str]:\n \"\"\"\n Loads the task names a model was trained with.\n\n :param path: Path where model checkpoint is saved.\n :return: A list of the task names that the model was trained with.\n \"\"\"\n return load_args(path).task_names\n\n\ndef get_loss_func(args: TrainArgs) -> nn.Module:\n \"\"\"\n Gets the loss function corresponding to a given dataset type.\n\n :param args: Arguments containing the dataset type (\"classification\", \"regression\", or \"multiclass\").\n :return: A PyTorch loss function.\n \"\"\"\n if args.alternative_loss_function is not None:\n if args.dataset_type == 'spectra' and args.alternative_loss_function == 'wasserstein':\n return wasserstein_loss\n else:\n raise ValueError(f'Alternative loss function {args.alternative_loss_function} not '\n 'supported with dataset type {args.dataset_type}.')\n\n if args.dataset_type == 'classification':\n return nn.BCEWithLogitsLoss(reduction='none')\n\n if args.dataset_type == 'regression':\n return nn.MSELoss(reduction='none')\n\n if args.dataset_type == 'multiclass':\n return nn.CrossEntropyLoss(reduction='none')\n\n if args.dataset_type == 'spectra':\n return sid_loss\n\n raise ValueError(f'Dataset type \"{args.dataset_type}\" not supported.')\n\n\ndef prc_auc(targets: List[int], preds: List[float]) -> float:\n \"\"\"\n Computes the area under the precision-recall curve.\n\n :param targets: A list of binary targets.\n :param preds: A list of prediction probabilities.\n :return: The computed prc-auc.\n \"\"\"\n precision, recall, _ = precision_recall_curve(targets, preds)\n return auc(recall, precision)\n\n\ndef bce(targets: List[int], preds: List[float]) -> float:\n \"\"\"\n Computes the binary cross entropy loss.\n\n :param targets: A list of binary targets.\n :param preds: A list of prediction probabilities.\n :return: The computed binary cross entropy.\n \"\"\"\n # Don't use logits because the sigmoid is added in all places except training itself\n bce_func = nn.BCELoss(reduction='mean')\n loss = bce_func(target=torch.Tensor(targets), input=torch.Tensor(preds)).item()\n\n return loss\n\n\ndef rmse(targets: List[float], preds: List[float]) -> float:\n \"\"\"\n Computes the root mean squared error.\n\n :param targets: A list of targets.\n :param preds: A list of predictions.\n :return: The computed rmse.\n \"\"\"\n return math.sqrt(mean_squared_error(targets, preds))\n\n\ndef mse(targets: List[float], preds: List[float]) -> float:\n \"\"\"\n Computes the mean squared error.\n\n :param targets: A list of targets.\n :param preds: A list of predictions.\n :return: The computed mse.\n \"\"\"\n return mean_squared_error(targets, preds)\n\n\ndef accuracy(targets: List[int], preds: Union[List[float], List[List[float]]], threshold: float = 0.5) -> float:\n \"\"\"\n Computes the accuracy of a binary prediction task using a given threshold for generating hard predictions.\n\n Alternatively, computes accuracy for a multiclass prediction task by picking the largest probability.\n\n :param targets: A list of binary targets.\n :param preds: A list of prediction probabilities.\n :param threshold: The threshold above which a prediction is a 1 and below which (inclusive) a prediction is a 0.\n :return: The computed accuracy.\n \"\"\"\n if type(preds[0]) == list: # multiclass\n hard_preds = [p.index(max(p)) for p in preds]\n else:\n hard_preds = [1 if p > threshold else 0 for p in preds] # binary prediction\n\n return accuracy_score(targets, hard_preds)\n\n\ndef get_metric_func(metric: str) -> Callable[[Union[List[int], List[float]], List[float]], float]:\n r\"\"\"\n Gets the metric function corresponding to a given metric name.\n\n Supports:\n\n * :code:`auc`: Area under the receiver operating characteristic curve\n * :code:`prc-auc`: Area under the precision recall curve\n * :code:`rmse`: Root mean squared error\n * :code:`mse`: Mean squared error\n * :code:`mae`: Mean absolute error\n * :code:`r2`: Coefficient of determination R\\ :superscript:`2`\n * :code:`accuracy`: Accuracy (using a threshold to binarize predictions)\n * :code:`cross_entropy`: Cross entropy\n * :code:`binary_cross_entropy`: Binary cross entropy\n\n :param metric: Metric name.\n :return: A metric function which takes as arguments a list of targets and a list of predictions and returns.\n \"\"\"\n if metric == 'auc':\n return roc_auc_score\n\n if metric == 'prc-auc':\n return prc_auc\n\n if metric == 'rmse':\n return rmse\n\n if metric == 'mse':\n return mse\n\n if metric == 'mae':\n return mean_absolute_error\n\n if metric == 'r2':\n return r2_score\n\n if metric == 'accuracy':\n return accuracy\n\n if metric == 'cross_entropy':\n return log_loss\n\n if metric == 'binary_cross_entropy':\n return bce\n \n if metric == 'sid':\n return sid_metric\n \n if metric == 'wasserstein':\n return wasserstein_metric\n\n raise ValueError(f'Metric \"{metric}\" not supported.')\n\n\ndef build_optimizer(model: nn.Module, args: TrainArgs) -> Optimizer:\n \"\"\"\n Builds a PyTorch Optimizer.\n\n :param model: The model to optimize.\n :param args: A :class:`~chemprop.args.TrainArgs` object containing optimizer arguments.\n :return: An initialized Optimizer.\n \"\"\"\n params = [{'params': model.parameters(), 'lr': args.init_lr, 'weight_decay': 0}]\n\n return Adam(params)\n\n\ndef build_lr_scheduler(optimizer: Optimizer, args: TrainArgs, total_epochs: List[int] = None) -> _LRScheduler:\n \"\"\"\n Builds a PyTorch learning rate scheduler.\n\n :param optimizer: The Optimizer whose learning rate will be scheduled.\n :param args: A :class:`~chemprop.args.TrainArgs` object containing learning rate arguments.\n :param total_epochs: The total number of epochs for which the model will be run.\n :return: An initialized learning rate scheduler.\n \"\"\"\n # Learning rate scheduler\n return NoamLR(\n optimizer=optimizer,\n warmup_epochs=[args.warmup_epochs],\n total_epochs=total_epochs or [args.epochs] * args.num_lrs,\n steps_per_epoch=args.train_data_size // args.batch_size,\n init_lr=[args.init_lr],\n max_lr=[args.max_lr],\n final_lr=[args.final_lr]\n )\n\n\ndef create_logger(name: str, save_dir: str = None, quiet: bool = False) -> logging.Logger:\n \"\"\"\n Creates a logger with a stream handler and two file handlers.\n\n If a logger with that name already exists, simply returns that logger.\n Otherwise, creates a new logger with a stream handler and two file handlers.\n\n The stream handler prints to the screen depending on the value of :code:`quiet`.\n One file handler (:code:`verbose.log`) saves all logs, the other (:code:`quiet.log`) only saves important info.\n\n :param name: The name of the logger.\n :param save_dir: The directory in which to save the logs.\n :param quiet: Whether the stream handler should be quiet (i.e., print only important info).\n :return: The logger.\n \"\"\"\n\n if name in logging.root.manager.loggerDict:\n return logging.getLogger(name)\n\n logger = logging.getLogger(name)\n\n logger.setLevel(logging.DEBUG)\n logger.propagate = False\n\n # Set logger depending on desired verbosity\n ch = logging.StreamHandler()\n if quiet:\n ch.setLevel(logging.INFO)\n else:\n ch.setLevel(logging.DEBUG)\n logger.addHandler(ch)\n\n if save_dir is not None:\n makedirs(save_dir)\n\n fh_v = logging.FileHandler(os.path.join(save_dir, 'verbose.log'))\n fh_v.setLevel(logging.DEBUG)\n fh_q = logging.FileHandler(os.path.join(save_dir, 'quiet.log'))\n fh_q.setLevel(logging.INFO)\n\n logger.addHandler(fh_v)\n logger.addHandler(fh_q)\n\n return logger\n\n\ndef timeit(logger_name: str = None) -> Callable[[Callable], Callable]:\n \"\"\"\n Creates a decorator which wraps a function with a timer that prints the elapsed time.\n\n :param logger_name: The name of the logger used to record output. If None, uses :code:`print` instead.\n :return: A decorator which wraps a function with a timer that prints the elapsed time.\n \"\"\"\n def timeit_decorator(func: Callable) -> Callable:\n \"\"\"\n A decorator which wraps a function with a timer that prints the elapsed time.\n\n :param func: The function to wrap with the timer.\n :return: The function wrapped with the timer.\n \"\"\"\n @wraps(func)\n def wrap(*args, **kwargs) -> Any:\n start_time = time()\n result = func(*args, **kwargs)\n delta = timedelta(seconds=round(time() - start_time))\n info = logging.getLogger(logger_name).info if logger_name is not None else print\n info(f'Elapsed time = {delta}')\n\n return result\n\n return wrap\n\n return timeit_decorator\n\n\ndef save_smiles_splits(data_path: str,\n save_dir: str,\n task_names: List[str] = None,\n features_path: List[str] = None,\n train_data: MoleculeDataset = None,\n val_data: MoleculeDataset = None,\n test_data: MoleculeDataset = None,\n logger: logging.Logger = None,\n smiles_columns: List[str] = None) -> None:\n \"\"\"\n Saves a csv file with train/val/test splits of target data and additional features.\n Also saves indices of train/val/test split as a pickle file. Pickle file does not support repeated entries \n with the same SMILES or entries entered from a path other than the main data path, such as a separate test path.\n\n :param data_path: Path to data CSV file.\n :param save_dir: Path where pickle files will be saved.\n :param task_names: List of target names for the model as from the function get_task_names().\n If not provided, will use datafile header entries.\n :param features_path: List of path(s) to files with additional molecule features.\n :param train_data: Train :class:`~chemprop.data.data.MoleculeDataset`.\n :param val_data: Validation :class:`~chemprop.data.data.MoleculeDataset`.\n :param test_data: Test :class:`~chemprop.data.data.MoleculeDataset`.\n :param smiles_columns: The name of the column containing SMILES. By default, uses the first column.\n :param logger: A logger for recording output.\n \"\"\"\n makedirs(save_dir)\n \n info = logger.info if logger is not None else print\n save_split_indices = True\n\n if not isinstance(smiles_columns, list):\n smiles_columns = preprocess_smiles_columns(path=data_path, smiles_columns=smiles_columns)\n\n with open(data_path) as f:\n reader = csv.DictReader(f)\n\n indices_by_smiles = {}\n for i, row in enumerate(tqdm(reader)):\n smiles = tuple([row[column] for column in smiles_columns])\n if smiles in indices_by_smiles:\n save_split_indices = False\n info('Warning: Repeated SMILES found in data, pickle file of split indices cannot distinguish entries and will not be generated.')\n break\n indices_by_smiles[smiles] = i\n\n if task_names is None:\n task_names = get_task_names(path=data_path, smiles_columns=smiles_columns)\n\n features_header = []\n if features_path is not None:\n for feat_path in features_path:\n with open(feat_path, 'r') as f:\n reader = csv.reader(f)\n feat_header = next(reader)\n features_header.extend(feat_header)\n\n all_split_indices = []\n for dataset, name in [(train_data, 'train'), (val_data, 'val'), (test_data, 'test')]:\n if dataset is None:\n continue\n\n with open(os.path.join(save_dir, f'{name}_smiles.csv'), 'w') as f:\n writer = csv.writer(f)\n if smiles_columns[0] == '':\n writer.writerow(['smiles'])\n else:\n writer.writerow(smiles_columns)\n for smiles in dataset.smiles():\n writer.writerow(smiles)\n\n with open(os.path.join(save_dir, f'{name}_full.csv'), 'w') as f:\n writer = csv.writer(f)\n writer.writerow(smiles_columns + task_names)\n dataset_targets = dataset.targets()\n for i, smiles in enumerate(dataset.smiles()):\n writer.writerow(smiles + dataset_targets[i])\n\n if features_path is not None:\n dataset_features = dataset.features()\n with open(os.path.join(save_dir, f'{name}_features.csv'), 'w') as f:\n writer = csv.writer(f)\n writer.writerow(features_header)\n writer.writerows(dataset_features)\n\n if save_split_indices:\n split_indices = []\n for smiles in dataset.smiles():\n index = indices_by_smiles.get(tuple(smiles))\n if index is None:\n save_split_indices = False\n info(f'Warning: SMILES string in {name} could not be found in data file, and likely came from a secondary data file. '\n 'The pickle file of split indices can only indicate indices for a single file and will not be generated.')\n break\n split_indices.append(index)\n else:\n split_indices.sort()\n all_split_indices.append(split_indices)\n\n if name == 'train':\n data_weights = dataset.data_weights()\n if any([w != 1 for w in data_weights]):\n with open(os.path.join(save_dir, f'{name}_weights.csv'),'w') as f:\n writer=csv.writer(f)\n writer.writerow(['data weights'])\n for weight in data_weights:\n writer.writerow([weight])\n\n if save_split_indices:\n with open(os.path.join(save_dir, 'split_indices.pckl'), 'wb') as f:\n pickle.dump(all_split_indices, f)\n\n\ndef update_prediction_args(predict_args: PredictArgs,\n train_args: TrainArgs,\n missing_to_defaults: bool = True,\n validate_feature_sources: bool = True) -> None:\n \"\"\"\n Updates prediction arguments with training arguments loaded from a checkpoint file.\n If an argument is present in both, the prediction argument will be used.\n\n Also raises errors for situations where the prediction arguments and training arguments\n are different but must match for proper function.\n\n :param predict_args: The :class:`~chemprop.args.PredictArgs` object containing the arguments to use for making predictions.\n :param train_args: The :class:`~chemprop.args.TrainArgs` object containing the arguments used to train the model previously.\n :param missing_to_defaults: Whether to replace missing training arguments with the current defaults for :class: `~chemprop.args.TrainArgs`.\n This is used for backwards compatibility.\n :param validate_feature_sources: Indicates whether the feature sources (from path or generator) are checked for consistency between\n the training and prediction arguments. This is not necessary for fingerprint generation, where molecule features are not used.\n \"\"\"\n for key, value in vars(train_args).items():\n if not hasattr(predict_args, key):\n setattr(predict_args, key, value)\n\n if missing_to_defaults:\n # If a default argument would cause different behavior than occurred in legacy checkpoints before the argument existed,\n # then that argument must be included in the `override_defaults` dictionary to force the legacy behavior.\n override_defaults = {\n 'bond_features_scaling':False,\n 'no_bond_features_scaling':True,\n 'atom_descriptors_scaling':False,\n 'no_atom_descriptors_scaling':True,\n }\n default_train_args=TrainArgs().parse_args(['--data_path', None, '--dataset_type', str(train_args.dataset_type)])\n for key, value in vars(default_train_args).items():\n if not hasattr(predict_args,key):\n setattr(predict_args,key,override_defaults.get(key,value))\n \n # Same number of molecules must be used in training as in making predictions\n if train_args.number_of_molecules != predict_args.number_of_molecules:\n raise ValueError('A different number of molecules was used in training '\n f'model than is specified for prediction, {train_args.number_of_molecules} '\n 'smiles fields must be provided')\n\n # If atom-descriptors were used during training, they must be used when predicting and vice-versa\n if train_args.atom_descriptors != predict_args.atom_descriptors:\n raise ValueError('The use of atom descriptors is inconsistent between training and prediction. If atom descriptors '\n ' were used during training, they must be specified again during prediction using the same type of '\n ' descriptors as before. If they were not used during training, they cannot be specified during prediction.')\n\n # If bond features were used during training, they must be used when predicting and vice-versa\n if (train_args.bond_features_path is None) != (predict_args.bond_features_path is None):\n raise ValueError('The use of bond descriptors is different between training and prediction. If you used bond '\n 'descriptors for training, please specify a path to new bond descriptors for prediction.')\n\n # if atom or bond features were scaled, the same must be done during prediction\n if train_args.features_scaling != predict_args.features_scaling:\n raise ValueError('If scaling of the additional features was done during training, the '\n 'same must be done during prediction.')\n\n # If atom descriptors were used during training, they must be used when predicting and vice-versa\n if train_args.atom_descriptors != predict_args.atom_descriptors:\n raise ValueError('The use of atom descriptors is inconsistent between training and prediction. '\n 'If atom descriptors were used during training, they must be specified again '\n 'during prediction using the same type of descriptors as before. '\n 'If they were not used during training, they cannot be specified during prediction.')\n\n # If bond features were used during training, they must be used when predicting and vice-versa\n if (train_args.bond_features_path is None) != (predict_args.bond_features_path is None):\n raise ValueError('The use of bond descriptors is different between training and prediction. If you used bond'\n 'descriptors for training, please specify a path to new bond descriptors for prediction.')\n\n if validate_feature_sources:\n # If features were used during training, they must be used when predicting\n if (((train_args.features_path is None) != (predict_args.features_path is None))\n or ((train_args.features_generator is None) != (predict_args.features_generator is None))):\n raise ValueError('Features were used during training so they must be specified again during prediction '\n 'using the same type of features as before (with either --features_generator or '\n '--features_path and using --no_features_scaling if applicable).')\n"
] |
[
[
"torch.optim.Adam",
"torch.nn.CrossEntropyLoss",
"torch.Tensor",
"torch.load",
"sklearn.metrics.accuracy_score",
"sklearn.metrics.precision_recall_curve",
"torch.nn.BCELoss",
"sklearn.metrics.mean_squared_error",
"torch.nn.BCEWithLogitsLoss",
"sklearn.metrics.auc",
"torch.nn.MSELoss",
"torch.save"
]
] |
nihlen/bf2-auto-spectator
|
[
"21a50b39f2525bc8bdc3a25071f5bf61637dd5f2"
] |
[
"src/gameinstancemanager.py"
] |
[
"import logging\nimport re\nimport time\n\nimport cv2\nimport numpy as np\nimport pyautogui\nimport win32com.client\nimport win32con\nimport win32gui\n\nfrom exceptions import UnsupportedMapException\nfrom gameinstancestate import GameInstanceState\nfrom helpers import Window, find_window_by_title, get_resolution_window_size, mouse_move_to_game_window_coord, \\\n ocr_screenshot_game_window_region, auto_press_key, screenshot_game_window_region, calc_cv2_hist_from_pil_image, \\\n mouse_reset_legacy, mouse_move_legacy, mouse_click_legacy, is_responding_pid\nimport constants\n\n# Remove the top left corner from pyautogui failsafe points\n# (avoid triggering failsafe exception due to mouse moving to left left during spawn)\ndel pyautogui.FAILSAFE_POINTS[0]\n\n\nclass GameInstanceManager:\n __game_path: str\n __player_name: str\n __player_pass: str\n __histograms: dict\n\n __game_window: Window = None\n __resolution: str\n\n __state: GameInstanceState\n\n def __init__(self, game_path: str, player_name: str, player_pass: str, histograms: dict):\n self.__game_path = game_path\n self.__player_name = player_name\n self.__player_pass = player_pass\n self.__histograms = histograms\n\n # Init game instance state\n self.__state = GameInstanceState()\n\n \"\"\"\n Attribute getters/setters\n \"\"\"\n def get_state(self) -> GameInstanceState:\n return self.__state\n\n def get_game_window(self) -> Window:\n return self.__game_window\n\n \"\"\"\n Functions for launching, finding and destroying/quitting a game instance\n \"\"\"\n def launch_instance(self, resolution: str) -> bool:\n \"\"\"\n Launch a new game instance via a shell (launching via shell \"detaches\" game process from spectator process,\n so that spectator can be restarted without having to restart the game)\n :param resolution: resolution to use for the game window [720p, 900p]\n :return:\n \"\"\"\n # Init shell\n shell = win32com.client.Dispatch(\"WScript.Shell\")\n\n self.__resolution = resolution\n window_size = get_resolution_window_size(self.__resolution)\n\n # Prepare command\n command = f'cmd /c start /b /d \"{self.__game_path}\" {constants.BF2_EXE} +restart 1 ' \\\n f'+playerName \"{self.__player_name}\" +playerPassword \"{self.__player_pass}\" ' \\\n f'+szx {window_size[0]} +szy {window_size[1]} +fullscreen 0 +wx 5 +wy 5 ' \\\n f'+multi 1 +developer 1 +disableShaderCache 1 +ignoreAsserts 1'\n\n # Run command\n shell.Run(command)\n\n # Wait for game window to come up\n game_window_present = False\n check_count = 0\n check_limit = 5\n while not game_window_present and check_count < check_limit:\n game_window_present = self.__find_instance()\n check_count += 1\n time.sleep(4)\n\n # If game window came up, give it some time for login etc.\n if game_window_present:\n time.sleep(6)\n\n return game_window_present\n\n def __find_instance(self) -> bool:\n self.__game_window = find_window_by_title(constants.BF2_WINDOW_TITLE, 'BF2')\n\n window_size = get_resolution_window_size(self.__resolution)\n window_matches_resolution = True\n if self.__game_window is not None and \\\n (self.__game_window.rect[2] - 21, self.__game_window.rect[3] - 44) != window_size:\n logging.error('Existing game window is a different resolution/size than expected')\n window_matches_resolution = False\n\n return self.__game_window is not None and window_matches_resolution\n\n def find_instance(self, resolution: str) -> bool:\n self.__resolution = resolution\n\n return self.__find_instance()\n\n def quit_instance(self) -> bool:\n # Spam press ESC if menu is not already visible\n attempt = 0\n max_attempts = 5\n while 'quit' not in ocr_screenshot_game_window_region(self.__game_window, self.__resolution,\n 'quit-menu-item', True) and attempt < max_attempts:\n auto_press_key(0x01)\n attempt += 1\n time.sleep(1)\n\n # Click quit menu item\n mouse_move_to_game_window_coord(self.__game_window, self.__resolution, 'quit-menu-item')\n time.sleep(.2)\n pyautogui.leftClick()\n\n time.sleep(2)\n\n return not is_responding_pid(self.__game_window.pid)\n\n \"\"\"\n Functions for detecting game state elements\n \"\"\"\n def check_for_game_message(self) -> bool:\n # Get ocr result of game message area\n ocr_result = ocr_screenshot_game_window_region(\n self.__game_window,\n self.__resolution,\n 'game-message-header',\n True\n )\n\n return 'game message' in ocr_result\n\n def ocr_game_message(self) -> str:\n # Get ocr result of game message content region\n ocr_result = ocr_screenshot_game_window_region(\n self.__game_window,\n self.__resolution,\n 'game-message-text',\n True\n )\n\n return ocr_result\n\n def check_if_in_menu(self) -> bool:\n # Get ocr result of quit menu item area\n ocr_result = ocr_screenshot_game_window_region(\n self.__game_window,\n self.__resolution,\n 'quit-menu-item',\n True\n )\n\n return 'quit' in ocr_result\n\n def check_if_round_ended(self) -> bool:\n ocr_result = ocr_screenshot_game_window_region(\n self.__game_window,\n self.__resolution,\n 'eor-header-items',\n True\n )\n\n round_end_labels = ['score list', 'top players', 'top scores', 'map briefing']\n\n return any(round_end_label in ocr_result for round_end_label in round_end_labels)\n\n def check_for_join_game_button(self) -> bool:\n # Get ocr result of bottom left corner where \"join game\"-button would be\n ocr_result = ocr_screenshot_game_window_region(\n self.__game_window,\n self.__resolution,\n 'join-game-button',\n True\n )\n\n return 'join game' in ocr_result\n\n def check_if_map_is_loading(self) -> bool:\n # Check if game is on round end screen\n on_round_end_screen = self.check_if_round_ended()\n\n # Check if join game button is present\n join_game_button_present = self.check_for_join_game_button()\n\n return on_round_end_screen and not join_game_button_present\n\n def check_for_map_briefing(self) -> bool:\n # Get ocr result of top left \"map briefing\" area\n map_briefing_present = 'map briefing' in ocr_screenshot_game_window_region(\n self.__game_window,\n self.__resolution,\n 'map-briefing-header',\n True\n )\n\n return map_briefing_present\n\n def check_if_spawn_menu_visible(self) -> bool:\n # Get ocr result of \"special forces\" class label/name\n ocr_result = ocr_screenshot_game_window_region(\n self.__game_window,\n self.__resolution,\n 'special-forces-class-label',\n True\n )\n\n return 'special forces' in ocr_result\n\n def get_map_name(self) -> str:\n # Screenshot and OCR map name area\n ocr_result = ocr_screenshot_game_window_region(\n self.__game_window,\n self.__resolution,\n 'eor-map-name',\n True\n )\n\n # Replace spaces with dashes\n ocr_result = ocr_result.replace(' ', '-')\n\n map_name = None\n # Make sure map name is valid\n # Also check while replacing first g with q to account for common ocr error\n if ocr_result.lower() in constants.COORDINATES['spawns'].keys():\n map_name = ocr_result.lower()\n elif re.sub(r'^([^g]*?)g(.*)$', '\\\\1q\\\\2', ocr_result.lower()) in constants.COORDINATES['spawns'].keys():\n map_name = re.sub(r'^([^g]*?)g(.*)$', '\\\\1q\\\\2', ocr_result.lower())\n\n return map_name\n\n def get_map_size(self) -> int:\n # Screenshot and OCR map size region\n ocr_result = ocr_screenshot_game_window_region(\n self.__game_window,\n self.__resolution,\n 'eor-map-size',\n True\n )\n\n map_size = -1\n # Make sure ocr result only contains numbers\n if re.match(r'^[0-9]+$', ocr_result):\n map_size = int(ocr_result)\n\n return map_size\n\n def get_player_team(self) -> int:\n # Take team selection screenshots\n team_selection_screenshots = []\n for coord_set in constants.COORDINATES[self.__resolution]['hists']['teams']:\n team_selection_screenshots.append(\n screenshot_game_window_region(self.__game_window,\n coord_set[0], coord_set[1], coord_set[2], coord_set[3])\n )\n\n # Get histograms of screenshots\n team_selection_histograms = []\n for team_selection_screenshot in team_selection_screenshots:\n team_selection_histograms.append(calc_cv2_hist_from_pil_image(team_selection_screenshot))\n\n # Calculate histogram deltas\n histogram_deltas = {\n 'to_usmc_active': cv2.compareHist(team_selection_histograms[0],\n self.__histograms[self.__resolution]['teams']['usmc']['active'],\n cv2.HISTCMP_BHATTACHARYYA),\n 'to_eu_active': cv2.compareHist(team_selection_histograms[0],\n self.__histograms[self.__resolution]['teams']['eu']['active'],\n cv2.HISTCMP_BHATTACHARYYA),\n 'to_china_active': cv2.compareHist(team_selection_histograms[1],\n self.__histograms[self.__resolution]['teams']['china']['active'],\n cv2.HISTCMP_BHATTACHARYYA),\n 'to_mec_active': cv2.compareHist(team_selection_histograms[1],\n self.__histograms[self.__resolution]['teams']['mec']['active'],\n cv2.HISTCMP_BHATTACHARYYA),\n }\n\n # Compare histograms to constant to determine team\n team = None\n if histogram_deltas['to_usmc_active'] < constants.HISTCMP_MAX_DELTA or \\\n histogram_deltas['to_eu_active'] < constants.HISTCMP_MAX_DELTA:\n # Player is on USMC/EU team\n team = 0\n elif histogram_deltas['to_china_active'] < constants.HISTCMP_MAX_DELTA or \\\n histogram_deltas['to_mec_active'] < constants.HISTCMP_MAX_DELTA:\n # Player is on MEC/CHINA team\n team = 1\n\n return team\n\n def is_sufficient_action_on_screen(self, screenshot_count: int = 3, screenshot_sleep: float = .55,\n min_delta: float = .022) -> bool:\n histograms = []\n\n left, top, right, bottom = self.__game_window.rect\n\n # Take screenshots and calculate histograms\n for i in range(0, screenshot_count):\n # Take screenshot\n screenshot = pyautogui.screenshot(region=(left + 168, top + 31, right - left - 336, bottom - top - 40))\n # Calculate histogram\n histograms.append(calc_cv2_hist_from_pil_image(screenshot))\n\n # Sleep before taking next screenshot\n if i + 1 < screenshot_count:\n time.sleep(screenshot_sleep)\n\n histogram_deltas = []\n # Calculate histogram differences\n for j in range(0, len(histograms) - 1):\n histogram_deltas.append(cv2.compareHist(histograms[j], histograms[j + 1], cv2.HISTCMP_BHATTACHARYYA))\n\n # Take average of deltas\n average_delta = np.average(histogram_deltas)\n\n logging.debug(f'Average histogram delta: {average_delta}')\n\n return average_delta > min_delta\n\n \"\"\"\n Functions to interact with the game instance (=change state)\n \"\"\"\n def bring_to_foreground(self) -> None:\n win32gui.ShowWindow(self.__game_window.handle, win32con.SW_SHOW)\n win32gui.SetForegroundWindow(self.__game_window.handle)\n\n def connect_to_server(self, server_ip: str, server_port: str, server_pass: str = None) -> bool:\n # Move cursor onto bfhq menu item and click\n # Required to reset multiplayer menu\n mouse_move_to_game_window_coord(self.__game_window, self.__resolution, 'bfhq-menu-item')\n time.sleep(.2)\n pyautogui.leftClick()\n\n time.sleep(3)\n\n # Move cursor onto multiplayer menu item and click\n mouse_move_to_game_window_coord(self.__game_window, self.__resolution, 'multiplayer-menu-item')\n time.sleep(.2)\n pyautogui.leftClick()\n\n check_count = 0\n check_limit = 10\n connect_to_ip_button_present = False\n while not connect_to_ip_button_present and check_count < check_limit:\n connect_to_ip_button_present = 'connect to ip' in ocr_screenshot_game_window_region(\n self.__game_window,\n self.__resolution,\n 'connect-to-ip-button',\n True\n )\n check_count += 1\n time.sleep(1)\n\n if not connect_to_ip_button_present:\n return False\n\n # Move cursor onto connect to ip button and click\n mouse_move_to_game_window_coord(self.__game_window, self.__resolution, 'connect-to-ip-button')\n time.sleep(.2)\n pyautogui.leftClick()\n\n # Give field popup time to appear\n time.sleep(.3)\n\n # Clear out ip field\n pyautogui.press('backspace', presses=20, interval=.05)\n\n # Write ip\n pyautogui.write(server_ip, interval=.05)\n\n # Hit tab to enter port\n pyautogui.press('tab')\n\n # Clear out port field\n pyautogui.press('backspace', presses=10, interval=.05)\n\n # Write port\n pyautogui.write(server_port, interval=.05)\n\n time.sleep(.3)\n\n # Write password if required\n # Field clears itself, so need to clear manually\n if server_pass is not None:\n pyautogui.press('tab')\n\n pyautogui.write(server_pass, interval=.05)\n\n time.sleep(.3)\n\n # Move cursor onto ok button and click\n mouse_move_to_game_window_coord(self.__game_window, self.__resolution, 'connect-to-ip-ok-button')\n time.sleep(.2)\n pyautogui.leftClick()\n\n # Successfully joining a server means leaving the menu, so wait for menu to disappear\n # (cancel further checks when a game/error message is present)\n check_count = 0\n check_limit = 16\n in_menu = True\n game_message_present = False\n while in_menu and not game_message_present and check_count < check_limit:\n in_menu = self.check_if_in_menu()\n game_message_present = self.check_for_game_message()\n check_count += 1\n time.sleep(1)\n\n return not in_menu\n\n def disconnect_from_server(self) -> None:\n # Press ESC\n auto_press_key(0x01)\n time.sleep(5)\n # Make sure disconnect button is present\n if 'disconnect' in ocr_screenshot_game_window_region(self.__game_window, self.__resolution,\n 'disconnect-button', True):\n # Move cursor onto disconnect button and click\n mouse_move_to_game_window_coord(self.__game_window, self.__resolution, 'disconnect-button')\n time.sleep(.2)\n pyautogui.leftClick()\n\n time.sleep(1.2)\n\n def toggle_hud(self, direction: int) -> None:\n # Open/toggle console\n auto_press_key(0x1d)\n time.sleep(.1)\n\n # Clear out command input\n pyautogui.press('backspace', presses=2, interval=.05)\n\n # Write command\n pyautogui.write(f'renderer.drawHud {str(direction)}', interval=.05)\n time.sleep(.3)\n\n # Hit enter\n pyautogui.press('enter')\n time.sleep(.1)\n\n # X / toggle console\n auto_press_key(0x1d)\n time.sleep(.1)\n\n def open_spawn_menu(self) -> None:\n auto_press_key(0x1c)\n time.sleep(1.5)\n\n def spawn_suicide(self) -> bool:\n # Make sure spawning on map and size is supported\n map_name = self.__state.get_rotation_map_name()\n map_size = str(self.__state.get_rotation_map_size())\n if map_name not in constants.COORDINATES['spawns'].keys() or \\\n map_size not in constants.COORDINATES['spawns'][map_name].keys():\n raise UnsupportedMapException('No coordinates for current map/size')\n\n # Reset mouse to top left corner\n mouse_reset_legacy()\n\n # Select default spawn based on current team\n spawn_coordinates = constants.COORDINATES['spawns'][map_name][str(map_size)][self.__state.get_round_team()]\n mouse_move_legacy(spawn_coordinates[0], spawn_coordinates[1])\n time.sleep(.3)\n mouse_click_legacy()\n\n # Hit enter to spawn\n auto_press_key(0x1c)\n time.sleep(1)\n\n # Hit enter again to re-open spawn menu\n auto_press_key(0x1c)\n time.sleep(.3)\n\n # Reset cursor again\n mouse_reset_legacy()\n\n # De-select spawn point\n mouse_move_to_game_window_coord(self.__game_window, self.__resolution, 'spawnpoint-deselect', True)\n time.sleep(0.3)\n mouse_click_legacy()\n\n # Reset cursor once more\n mouse_reset_legacy()\n\n suicide_button_present = 'suicide' in ocr_screenshot_game_window_region(\n self.__game_window,\n self.__resolution,\n 'suicide-button',\n True\n )\n\n if suicide_button_present:\n # Click suicide button\n mouse_move_to_game_window_coord(self.__game_window, self.__resolution, 'suicide-button', True)\n time.sleep(.3)\n mouse_click_legacy()\n time.sleep(.5)\n\n return suicide_button_present\n\n def rotate_to_next_player(self):\n auto_press_key(0x2e)\n\n def join_game(self) -> None:\n # Move cursor onto join game button and click\n mouse_move_to_game_window_coord(self.__game_window, self.__resolution, 'join-game-button')\n time.sleep(.2)\n pyautogui.leftClick()\n\n def close_game_message(self) -> None:\n # Move cursor onto ok button and click\n mouse_move_to_game_window_coord(self.__game_window, self.__resolution, 'game-message-close-button')\n time.sleep(.2)\n pyautogui.leftClick()\n"
] |
[
[
"numpy.average"
]
] |
Krytic/Takahe
|
[
"6d6bdf234ae7e3cfe8ef40e48d4621dc9a9a2f6c"
] |
[
"takahe/histogram.py"
] |
[
"\"\"\"\n\nHistogram classes to contain event rate data and allow for easy plotting\n\nOriginal author: Max Briel (https://github.com/maxbriel)\nModified by: Sean Richards (https://github.com/Krytic)\n\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pickle\nfrom scipy.stats import iqr\nfrom scipy.stats import multivariate_normal\nimport takahe\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\n\nimport warnings\nfrom uncertainties import ufloat\nfrom uncertainties.umath import log as ulog\nfrom uncertainties.umath import log10 as ulog10\nfrom uncertainties.umath import log as ulog\n\nclass histogram:\n \"\"\"\n A histogram which can contain data and can be manipulated.\n\n Either **xlow**, **xup**, and **nr_bins** is given or **edges**\n\n As per any histogram, the upper edges are non inclusive, except for\n the last bin.\n\n Arguments:\n xlow {float} -- lower bound\n xup {float} -- upper bound\n nr_bins {int} -- the number of bins\n edges {array} -- An array with items defining the edges.\n\n Attributes:\n _xlow {float} -- lower bound of the histogram\n _xup {float} -- upper bound of the histogram\n _nr_bins {int} -- the number of bins in the histogram\n _bin_edges {array} -- An array of bin edges\n _values {array} -- An array of length **_nr_bins**\n containing the value of each bin\n lower_edges {array} -- An array of the lower edges of the bins\n in the histogram\n upper_edges {array} -- An array of the upper edges of the bins\n in the histogram\n _hits {array} -- An array containing the number of times\n each bin has been inserted into.\n\n \"\"\"\n\n def __init__(self, xlow=None, xup=None, nr_bins=None, edges=None):\n if xlow != None and xup != None and nr_bins != None:\n self._xlow = xlow\n self._xup = xup\n self._nr_bins = nr_bins\n self._bin_edges = np.linspace(xlow, xup, nr_bins+1)\n\n elif isinstance(edges, type([])) or isinstance(edges, type(np.array([]))):\n self._xlow = edges[0]\n self._xup = edges[-1]\n self._nr_bins = len(edges)-1\n self._bin_edges = np.array(edges)\n else:\n raise Exception(\"Not given the correct input\")\n\n self._values = np.zeros(self._nr_bins)\n self._hits = np.zeros(self._nr_bins)\n self.lower_edges = self._bin_edges[:-1]\n self.upper_edges = self._bin_edges[1:]\n\n def __len__(self):\n return len(self._values)\n\n def __str__(self):\n return str(self._values)\n\n def __repr__(self):\n return f\"The bins: {self._bin_edges}\\nThe values: {self._values}\"\n\n def __add__(self, other):\n \"\"\"\n Addition\n\n Performs element-wise addition with another histogram or float\n object.\n\n Arguments:\n other {mixed} -- Either another histogram object, or a float\n type object,\n\n Returns:\n {histogram} -- A deep copy of the resultant histogram.\n \"\"\"\n out = self.copy()\n\n if isinstance(other, histogram):\n out._values = self._values + other._values\n else:\n out._values = self._values + other\n\n return out\n\n def __mul__(self, other):\n \"\"\"\n Multiplication\n\n Performs element-wise multiplication with a float type object.\n\n Arguments:\n other {float} -- The multiplier\n\n Returns:\n {histogram} -- A deep copy of the resultant histogram.\n \"\"\"\n out = self.copy()\n out._values = self._values * other\n return out\n\n def __rmul__(self, other):\n return self.__mul__(other)\n\n def __sub__(self, other):\n return self + -1 * other\n\n def __div__(self, other):\n return self.__truediv__(other)\n\n def __truediv__(self, other):\n out = self.copy()\n out._values = self._values / other\n out._hits = self._hits\n return out\n\n def inbounds(self, value):\n \"\"\"\n Determines if a value is within the bounds of the histogram.\n\n Arguments:\n value {float} -- The value to checl\n\n Returns:\n {bool} -- Whether or not the value is within the histogram\n range.\n \"\"\"\n return self._xlow <= value and self._xup >= value\n\n def copy(self):\n \"\"\"\n Creates a copy of the histogram\n\n Returns:\n {histogram} -- An exact (deep) copy of the histogram\n\n \"\"\"\n out = histogram(xlow=self._xlow, xup=self._xup, nr_bins=self._nr_bins)\n out._values = self._values\n out._hits = self._hits\n return out\n\n def fill(self, x, weight = 1):\n \"\"\"\n Fill the histogram with data.\n\n Arguments:\n x {mixed} -- Either a single entry or an array of *N* to\n put into the histogram\n w {mixed} -- The weight of the entry of *N* entries to be\n added to the histogram.\n \"\"\"\n\n def _insert(f, g):\n if f >= self._xup:\n self._values[self._nr_bins-1] += g\n self._hits[self._nr_bins-1] += 1\n elif f <= self._xlow:\n self._values[0] += g\n self._hits[0] += 1\n else:\n bin_nr = np.where(self.lower_edges <= f)[0][-1]\n self._values[bin_nr] += g\n self._hits[bin_nr] += 1\n\n # Data va;odatopm. x can be either a float or an array type.\n # First - is it a float type?\n if not isinstance(x, type(0.0)):\n if isinstance(weight, type(0)):\n for i in range(0, len(x)):\n _insert(x[i], weight)\n elif len(x) != len(weight):\n raise Exception(f\"Weight needs to be as long as x. (x={len(x)}, weight={len(weight)})\")\n else:\n for i in range(0, len(x)):\n _insert(x[i], weight[i])\n # Otherwise assume it is a list type.\n else:\n _insert(x, weight)\n\n return None\n\n def plot(self, with_errors=False, *argv, **kwargs):\n \"\"\"\n Plot the histogram.\n\n Additional arguments (beyond with_errors) will be passed on to to the\n call to plt.hist().\n\n Arguments:\n with_errors {bool} -- Whether or not to plot errors (error bars)\n on the histogram. (default: {False})\n \"\"\"\n\n xobj = self._bin_edges\n\n wobj = self._values\n\n # Sometimes the histogram has one too few values for the y-axis\n # (and sometimes it has one too many). We coerce the histogram\n # into having the right shape in this instance (and fail if it\n # still does not).\n\n if len(self._values) == len(xobj) - 1:\n wobj = np.append(wobj, wobj[-1])\n elif len(self._values) - 1 == len(xobj):\n wobj = wobj[:-1]\n\n entries, edges, _ = plt.hist(xobj,\n self._bin_edges,\n weights=wobj,\n histtype=u'step',\n *argv,\n **kwargs)\n\n if with_errors:\n plt.errorbar(self.getBinCenters(), self._values, yerr=np.sqrt(self._hits), fmt='r.')\n\n return None\n\n def plotLog(self, with_errors=False, *argv, **kwargs):\n \"\"\"\n Plot the histogram with a logged x-axis.\n\n Additional arguments (beyond with_errors) will be passed on to to the\n call to plt.hist().\n\n Arguments:\n with_errors {bool} -- Whether or not to plot errors (error bars)\n on the histogram. (default: {False})\n \"\"\"\n entries, edges, _ = plt.hist(np.log10(self._bin_edges[:-1]),\n np.log10(self._bin_edges),\n weights=self._values,\n histtype=u'step',\n *argv,\n **kwargs)\n\n if with_errors:\n plt.errorbar(self.getBinCenters(), self._values, yerr=np.sqrt(self._hits), fmt='r.')\n\n return None\n\n def getBinCenters(self):\n \"\"\"Gets the center of each bin of the histogram.\"\"\"\n return [self.getBinCenter(i) for i in range(self.getNBins())]\n\n def reregister_hits(self, hits):\n \"\"\"Resets the hit counter of the histogram.\n\n Arguments:\n hits {array} -- The array of new hit values for the\n histogram\n \"\"\"\n assert isinstance(hits, (list, np.ndarray)), \"hits must be arraylike.\"\n\n for i in range(len(self._hits)):\n self._hits[i] = hits[i]\n\n def getUncertainty(self, bin):\n \"\"\"Returns the Poissonian uncertainty of the bin at bin# \"bin\".\n\n Returns the Poissonian uncertainty of the requested bin. Poisson\n uncertainties take error ~ 1/sqrt(N) where N is the number of\n data points in the bin.\n\n Arguments:\n bin {int} -- The bin number\n\n Returns:\n {float} -- The uncertainty in the bin.\n \"\"\"\n\n assert isinstance(bin, np.int)\n\n return 1 / np.sqrt(self._hits[bin])\n\n def get(self, bin):\n \"\"\"Retrieves the ufloat (nominal + uncertainty) of the bin\n\n Arguments:\n bin {int} -- The bin number to request\n\n Returns:\n {ufloat} -- The bin content in the form\n content +- uncertainty\n \"\"\"\n return ufloat(self.getBinContent(bin), self.getUncertainty(bin))\n\n def getLog(self, bin):\n \"\"\"Retrieves the log of the uncertainty for the bin.\n\n Same as histogram.get() but puts through ulog10 first.\n\n Arguments:\n bin {int} -- The bin number to request\n\n Returns:\n {ufloat} -- The bin content in the form\n content +- uncertainty\n \"\"\"\n val = self.get(bin)\n val = ulog10(val)\n return val\n\n def present_value(self, bin, log=False):\n \"\"\"Presents the value in a human readable format.\n\n Formats the value of a bin in a human-readable (LaTeX) format.\n Will present the error to 1 significant figure, and the nominal\n value to the same number of decimal places.\n\n Arguments:\n bin {int} -- The bin number to extract the value from.\n\n Keyword Arguments:\n log {bool} -- Whether to take the log of the value or not.\n (default: {False})\n\n Returns:\n {string} -- The LaTeX-formatted value.\n \"\"\"\n\n assert isinstance(bin, np.integer), \"Expected bin to be an integer.\"\n assert isinstance(bin, bool), \"Expected log to be boolean.\"\n assert bin <= self.getNBins(), (\"Expected bin to be a valid bin. \"\n f\"There are {self.getNBins()} in this \"\n \"histogram, and you have requested \"\n f\"bin number {bin}.\")\n\n if log:\n val = self.getLog(bin)\n else:\n val = self.get(bin)\n\n err = val.s * val.n\n nom = val.n\n\n err_to_1_sf = f\"{err:.1g}\"\n num_dp = len(str(err_to_1_sf).split('.')[1])\n\n return_string = rf\"${nom:.{num_dp}f} \\pm {err_to_1_sf}$\"\n\n return return_string\n\n def to_pickle(self, pickle_path):\n \"\"\"Saves a histogram as a pickle file.\n\n Preserves the edges, values, and hits, of the histogram.\n\n Arguments:\n pickle_path {string} -- The path to save the pickle file at.\n \"\"\"\n assert isinstance(pickle_path, str), (\"Expected pickle_path to be a \"\n \"string.\")\n contents = {\n 'edges': self._bin_edges,\n 'values': self._values,\n 'hits': self._hits\n }\n\n with open(pickle_path, 'wb') as f:\n pickle.dump(contents, f)\n\n def getBinContent(self, bin_nr):\n \"\"\"Return the value of the given bin\n\n Arguments:\n bin_nr {int} -- the bin number to fetch\n\n Returns:\n {float} -- the content of the given bin.\n The bincontent of the bin\n \"\"\"\n\n return self._values[bin_nr]\n\n def getNBins(self):\n \"\"\" Gives the number of bins of the histogram\n\n Returns\n -------\n float\n Return the number of bins in the histogram\n \"\"\"\n return self._nr_bins\n\n def getValues(self):\n \"\"\"Return the values of the histogram\n\n Returns\n -------\n array\n The values stored in the histogram\n\n \"\"\"\n return self._values\n\n def getBinWidth(self, i):\n \"\"\"Returns the width of the given bin\n\n Parameters\n ----------\n i : int\n Bin number\n\n Returns\n -------\n float\n The width of the bin\n\n \"\"\"\n return self.upper_edges[i] - self.lower_edges[i]\n\n def getBinCenter(self, i):\n \"\"\"Returns the center of the bin\n\n Parameters\n ----------\n i : int\n Bin number\n\n Returns\n -------\n float\n The center of bin *i*\n\n \"\"\"\n return (self.upper_edges[i] + self.lower_edges[i])/2\n\n def getBin(self, x):\n \"\"\"Returns the bin number at value **x**\n\n Parameters\n ----------\n x : float\n value where you want to know the bin number\n\n Returns\n -------\n int\n The bin number\n\n \"\"\"\n if x < self._bin_edges[0] or x > self._bin_edges[-1]:\n raise Exception(f\"x={x} outside of range\")\n\n out = np.where(x >= self._bin_edges)[0][-1]\n\n if out == self._nr_bins:\n out = out - 1\n return out\n\n def getBinEdges(self):\n \"\"\"Returns the bin edges of the histogram\n\n Returns\n -------\n array\n An array of all the bin edges\n\n \"\"\"\n return self._bin_edges\n\n\n def sum(self, x1, x2):\n \"\"\"Performs a binwise summation between parameters **x1** and **x2**.\n\n\n Parameters\n ----------\n x1 : float\n lower bound of the summation\n x2 : float\n upper bound of the summation\n\n Returns\n -------\n float\n The summation of the bins between **x1** and **x2**\n\n \"\"\"\n if x1 >= x2:\n raise Exception(\"x2 should be larger than x1\")\n if x1 < self._bin_edges[0]:\n warnings.warn(\"Lower limit is below lowest bin edge\", )\n if x2 > self._bin_edges[-1]:\n warnings.warn(\"Higher limit is above the highest bin edge\")\n\n lower_bin = self.getBin(x1)\n upper_bin = self.getBin(x2)\n\n if lower_bin == upper_bin:\n bin_width = self.getBinWidth(lower_bin)\n return self.getBinContent(lower_bin) * (x2 - x1) / bin_width\n else:\n total = 0\n # get lower bin part\n bin_width = self.getBinWidth(lower_bin)\n total += self.getBinContent(lower_bin) * (self.upper_edges[lower_bin] - x1)/bin_width\n\n # get upper bin part\n bin_width = self.getBinWidth(upper_bin)\n total += self.getBinContent(upper_bin) * (x2 - self.lower_edges[upper_bin])/bin_width\n\n # get the parts in between if they are there\n if (lower_bin + 1) != upper_bin:\n for i in range(lower_bin+1, upper_bin):\n total += self._values[i]\n\n return total\n\n def integral(self, x1, x2):\n \"\"\"Returns the integral of the histogram between **x1** and **x2**.\n\n Parameters\n ----------\n x1 : float\n lower bound of the integration\n x2 : float\n upper bound of the integration\n\n Returns\n -------\n float\n The integral between **x1** and **x2**\n\n \"\"\"\n if x1 >= x2:\n raise Exception(\"x2 should be larger than x1\")\n if x1 < self._bin_edges[0]:\n warnings.warn(\"Lower limit is below lowest bin edge\")\n if x2 > self._bin_edges[-1]:\n warnings.warn(\"Higher limit is above the highest bin edge\")\n lower_bin = self.getBin(x1)\n upper_bin = self.getBin(x2)\n if lower_bin == upper_bin:\n bin_width = self.getBinWidth(lower_bin)\n return self.getBinContent(lower_bin) * (x2 - x1)\n else:\n total = 0\n # get lower bin part\n bin_width = self.getBinWidth(lower_bin)\n total += self.getBinContent(lower_bin) * (self.upper_edges[lower_bin] - x1)\n\n # get upper bin part\n bin_width = self.getBinWidth(upper_bin)\n total += self.getBinContent(upper_bin) * (x2 - self.lower_edges[upper_bin])\n\n # get the parts in between if they are there\n if (lower_bin + 1) != upper_bin:\n for i in range(lower_bin+1, upper_bin):\n total += self._values[i] * self.getBinWidth(i)\n\n return total\n\nclass histogram_2d:\n def __init__(self, x_range=None,\n y_range=None,\n nr_bins_x=0,\n nr_bins_y=0,\n edges_x=None,\n edges_y=None):\n\n linspace = True\n if edges_x is not None and edges_y is not None:\n x_range = (edges_x[0], edges_x[-1])\n y_range = (edges_y[0], edges_y[-1])\n nr_bins_x = len(edges_x)\n nr_bins_y = len(edges_y)\n linspace = False\n\n xlow, xup = x_range[0], x_range[1]\n ylow, yup = y_range[0], y_range[1]\n\n self._xlow = xlow\n self._xup = xup\n self._ylow = ylow\n self._yup = yup\n self._num_x = nr_bins_x\n self._num_y = nr_bins_y\n self._values = np.zeros((nr_bins_x, nr_bins_y))\n self._num_hits = np.zeros((nr_bins_x, nr_bins_y))\n\n if linspace == True:\n self._bin_edges_x = np.linspace(xlow, xup, nr_bins_x)\n self._bin_edges_y = np.linspace(ylow, yup, nr_bins_y)\n else:\n self._bin_edges_x = edges_x\n self._bin_edges_y = edges_y\n\n def sample(self, x, y):\n \"\"\"Samples the histogram at data coordinates (x, y).\n\n Syntactic sugar for self.getBinContent(self.getBin(x, y))\n\n Arguments:\n x {float} -- The x-coordinate to sample at\n y {float} -- The y-coordinate to sample at\n\n Returns:\n {float} -- The content of the bin corresponding to the coordinate (x, y)\n \"\"\"\n i, j = self.getBin(x, y)\n return self.getBinContent(i, j)\n\n def fill(self, insertion_matrix):\n assert self._values.shape == insertion_matrix.shape\n\n self._values = insertion_matrix\n # increment hits by 1 in every cell that contains a value:\n self._num_hits += (insertion_matrix>0).astype(int)\n\n def insert(self, bin_nr_x, bin_nr_y, value):\n self._values[bin_nr_x][bin_nr_y] += value\n self._num_hits[bin_nr_x][bin_nr_y] += 1\n\n def getBin(self, x, y):\n if x < self._xlow or x > self._xup or y < self._ylow or y > self._yup:\n # out of bounds\n return -1, -1\n\n i = np.where(x >= self._bin_edges_x)[0][-1]\n j = np.where(y >= self._bin_edges_y)[0][-1]\n\n return (i,j)\n\n def getBinContent(self, bin_nr_x, bin_nr_y):\n val = self._values[bin_nr_x][bin_nr_y]\n err = np.sqrt(self._num_hits[bin_nr_x][bin_nr_y])\n return ufloat(val, err)\n\n def range(self):\n return np.min(self._values), np.max(self._values)\n\n def to_extent(self):\n x_axis = self._bin_edges_x\n y_axis = self._bin_edges_y\n return x_axis, y_axis\n\n def copy(self):\n x = [self._xlow, self._xup]\n y = [self._ylow, self._yup]\n\n out = histogram_2d(x, y, self._num_x, self._num_y)\n out._values = self._values\n out._num_hits = self._num_hits\n\n return out\n\n def plot(self, *args, **kwargs):\n x = self._bin_edges_x\n y = self._bin_edges_y\n X, Y = np.meshgrid(x, y, indexing='ij')\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n ax.plot_surface(X, Y, self._values, *args, **kwargs)\n\n return ax\n\n def to_pickle(self, pickle_path):\n contents = {\n 'build_params': {\n 'xlow': self._xlow,\n 'xup' : self._xup,\n 'ylow': self._ylow,\n 'yup' : self._yup,\n 'y_nr': self._num_x,\n 'x_nr': self._num_y,\n },\n 'values': self._values,\n 'hits': self._num_hits\n }\n\n with open(pickle_path, 'wb') as f:\n pickle.dump(contents, f)\n\n def likelihood(self, x_obs, y_obs):\n n = len(x_obs)\n IQR_y = iqr(y_obs)\n IQR_x = iqr(x_obs)\n\n m_y = min(np.sqrt(np.var(y_obs)), IQR_y/1.349)\n m_x = min(np.sqrt(np.var(x_obs)), IQR_x/1.349)\n\n b_y = 0.9 * m_y / (n**(1/5))\n b_x = 0.9 * m_x / (n**(1/5))\n\n logL = None\n\n for i in range(len(x_obs)):\n w = self.getBin(x_obs[i], y_obs[i])\n w = self.getBinContent(w[0], w[1]) - 1\n if w.n <= 0: w = 0.0001\n\n mu = np.array([x_obs[i], y_obs[i]])\n sigma = np.matrix([[b_x**2, 0], [0, b_y**2]])\n N = multivariate_normal(mu, sigma)\n\n if logL == None:\n logL = ulog(w * N.pdf([x_obs[i], y_obs[i]]))\n else:\n logL += ulog(w * N.pdf([x_obs[i], y_obs[i]]))\n\n return logL\n\n def __add__(self, other):\n assert isinstance(other, histogram_2d)\n assert self._xlow == other._xlow\n assert self._xup == other._xup\n assert self._ylow == other._ylow\n assert self._yup == other._yup\n assert self._bin_edges_x == other._bin_edges_x\n assert self._bin_edges_y == other._bin_edges_y\n\n self._values = self._values + other._values\n self._num_hits = self._num_hits + other._num_hits\n\nclass pickledHistogram(histogram):\n def __init__(self, pickle_path):\n with open(pickle_path, 'rb') as f:\n contents = pickle.load(f)\n\n super().__init__(edges=contents['edges'])\n\n self._values = contents['values']\n self.reregister_hits(contents['hits'])\n\nclass pickled2dHistogram(histogram_2d):\n def __init__(self, pickle_path):\n with open(pickle_path, 'rb') as f:\n contents = pickle.load(f)\n\n xlow = contents['build_params']['xlow']\n xup = contents['build_params']['xup']\n ylow = contents['build_params']['ylow']\n yup = contents['build_params']['yup']\n\n nr_x = contents['build_params']['x_nr']\n nr_y = contents['build_params']['y_nr']\n\n super().__init__([xlow,xup], [ylow,yup], nr_x, nr_y)\n\n self._values = contents['values']\n self._num_hits = contents['hits']\n\ndef from_pickle(pickle_path, is_2d=False):\n if not is_2d:\n return pickledHistogram(pickle_path)\n if is_2d:\n return pickled2dHistogram(pickle_path)\n"
] |
[
[
"numpy.matrix",
"numpy.sqrt",
"numpy.linspace",
"numpy.min",
"scipy.stats.iqr",
"numpy.append",
"numpy.log10",
"numpy.max",
"scipy.stats.multivariate_normal",
"numpy.where",
"numpy.var",
"numpy.array",
"numpy.meshgrid",
"numpy.zeros",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.figure"
]
] |
zqwei/pyslds
|
[
"058be6e2db4f1361eb8c6b89ce02978ca624fe88"
] |
[
"examples/simple_demo.py"
] |
[
"import numpy as np\nimport numpy.random as npr\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\n\n# Fancy plotting\ntry:\n import seaborn as sns\n from hips.plotting.colormaps import gradient_cmap\n sns.set_style(\"white\")\n sns.set_context(\"paper\")\n\n color_names = [\"red\",\n \"windows blue\",\n \"medium green\",\n \"dusty purple\",\n \"orange\",\n \"amber\",\n \"clay\",\n \"pink\",\n \"greyish\",\n \"light cyan\",\n \"steel blue\",\n \"forest green\",\n \"pastel purple\",\n \"mint\",\n \"salmon\",\n \"dark brown\"]\n colors = sns.xkcd_palette(color_names)\n cmap = gradient_cmap(colors)\nexcept:\n from matplotlib.cm import get_cmap\n colors = ['b', 'r', 'y', 'g', 'purple']\n cmap = get_cmap(\"jet\")\n\n\nfrom pybasicbayes.util.text import progprint_xrange\nfrom pylds.util import random_rotation\nfrom pyslds.models import DefaultSLDS\n\nnpr.seed(0)\n\n# Set parameters\nK = 5\nD_obs = 100\nD_latent = 2\nD_input = 1\nT = 1000\n\n# Make an LDS with known parameters\ntrue_mu_inits = [np.ones(D_latent) for _ in range(K)]\ntrue_sigma_inits = [np.eye(D_latent) for _ in range(K)]\ntrue_As = [.9 * random_rotation(D_latent)\n for k in range(K)]\ntrue_Bs = [3 * npr.randn(D_latent, D_input) for k in range(K)]\ntrue_sigma_states = [np.eye(D_latent) for _ in range(K)]\ntrue_C = np.random.randn(D_obs, D_latent)\ntrue_Ds = np.zeros((D_obs, D_input))\ntrue_sigma_obs = np.eye(D_obs)\ntrue_model = DefaultSLDS(\n K, D_obs, D_latent, D_input=D_input,\n mu_inits=true_mu_inits, sigma_inits=true_sigma_inits,\n As=true_As, Bs=true_Bs, sigma_statess=true_sigma_states,\n Cs=true_C, Ds=true_Ds, sigma_obss=true_sigma_obs)\n\n# Simulate some data with a given discrete state sequence\ninputs = np.ones((T, D_input))\nz = np.arange(K).repeat(T // K)\ny, x, z = true_model.generate(T, inputs=inputs, stateseq=z)\n\n# Fit with another LDS. Give it twice as many states in\n# order to have some flexibility during inference.\ntest_model = DefaultSLDS(2*K, D_obs, D_latent, D_input,\n Cs=npr.randn(D_obs, D_latent),\n Ds=npr.randn(D_obs, D_input))\ntest_model.add_data(y, inputs=inputs)\n\n# Initialize with Gibbs sampler\nprint(\"Initializing with Gibbs\")\nN_gibbs_samples = 1000\ndef initialize(model):\n model.resample_model()\n return model.log_likelihood()\n\ngibbs_lls = [initialize(test_model) for _ in progprint_xrange(N_gibbs_samples)]\n\n# Fit with VBEM\nprint(\"Fitting with VBEM\")\nN_vbem_iters = 10000\ndef update(model):\n model.VBEM_step()\n return model.log_likelihood()\n\ntest_model._init_mf_from_gibbs()\nvbem_lls = [update(test_model) for _ in progprint_xrange(N_vbem_iters)]\n\n# Plot the log likelihoods\nplt.figure(figsize=(5,3))\nplt.plot([0, N_gibbs_samples + N_vbem_iters], true_model.log_likelihood() * np.ones(2), '--k', label=\"true\")\nplt.plot(np.arange(N_gibbs_samples), gibbs_lls, color=colors[0], label=\"gibbs\")\nplt.plot(np.arange(N_gibbs_samples + 1, N_gibbs_samples + N_vbem_iters), vbem_lls[1:], color=colors[1], label=\"vbem\")\nplt.xlim(0, N_gibbs_samples + N_vbem_iters)\nplt.xlabel('iteration')\nplt.ylabel('log likelihood')\nplt.legend(loc=\"lower right\")\nplt.tight_layout()\nplt.savefig(\"aux/demo_ll.png\")\n\n# Smooth the data\nsmoothed_data = test_model.smooth(y, inputs)\n\nfig = plt.figure(figsize=(5,3))\ngs = GridSpec(3, 1, height_ratios=[.1, .1, 1.0])\nax = fig.add_subplot(gs[0,0])\nax.imshow(true_model.states_list[0].stateseq[None,:], vmin=0, vmax=max(len(colors), true_model.num_states)-1,\n cmap=cmap, interpolation=\"nearest\", aspect=\"auto\")\nax.set_xticklabels([])\nax.set_yticks([])\nax.set_title(\"True Discrete States\")\n\nax = fig.add_subplot(gs[1,0])\nax.imshow(test_model.states_list[0].stateseq[None,:], vmin=0, vmax=max(len(colors), test_model.num_states)-1,\n cmap=cmap, interpolation=\"nearest\", aspect=\"auto\")\nax.set_xticklabels([])\nax.set_yticks([])\nax.set_title(\"Inferred Discrete States\")\n\nax = fig.add_subplot(gs[2,0])\nplt.plot(y[:,0], color='k', lw=2, label=\"observed\")\nplt.plot(smoothed_data[:,0], color=colors[0], lw=1, label=\"smoothed\")\nplt.xlabel(\"Time\")\nplt.xlim(0, min(T, 500))\nplt.ylabel(\"Observations\")\nplt.legend(loc=\"upper center\", ncol=2)\nplt.tight_layout()\nplt.savefig(\"aux/demo_smooth.png\")\n\nplt.figure()\nfrom pyhsmm.util.general import rle\nz_rle = rle(z)\noffset = 0\nfor k, dur in zip(*z_rle):\n plt.plot(x[offset:offset+dur,0], x[offset:offset+dur,1], color=colors[k])\n offset += dur\n\nplt.xlabel(\"$x_1$\")\nplt.ylabel(\"$x_2$\")\nplt.title(\"Continuous Latent States\")\nplt.show()\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.tight_layout",
"numpy.random.seed",
"matplotlib.pyplot.title",
"numpy.arange",
"numpy.eye",
"matplotlib.pyplot.savefig",
"numpy.ones",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.ylabel",
"numpy.random.randn",
"matplotlib.gridspec.GridSpec",
"matplotlib.cm.get_cmap",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"numpy.zeros",
"matplotlib.pyplot.figure"
]
] |
kingdavid72/pymol-OpenSource
|
[
"8192e75bf3d4c1072d6bd399b7dacd065bf78a06"
] |
[
"modules/chempy/brick.py"
] |
[
"#A* -------------------------------------------------------------------\n#B* This file contains source code for the PyMOL computer program\n#C* copyright 1998-2000 by Warren Lyford Delano of DeLano Scientific. \n#D* -------------------------------------------------------------------\n#E* It is unlawful to modify or remove this copyright notice.\n#F* -------------------------------------------------------------------\n#G* Please see the accompanying LICENSE file for further information. \n#H* -------------------------------------------------------------------\n#I* Additional authors of this source file include:\n#-* \n#-* \n#-*\n#Z* -------------------------------------------------------------------\n\nimport numpy\n\nclass Brick(object):\n '''\n Map object to load into PyMOL with\n\n >>> pymol.importing.load_brick(brickinstance, \"name\")\n '''\n \n def __init__(self):\n self.valid = None\n\n @classmethod\n def from_numpy(cls, data, grid, origin=(0.0, 0.0, 0.0)):\n '''\n @param data: numpy float array with len(data.shape) == 3\n @param range: 3f sequence\n @param origin: 3f sequence\n '''\n data = numpy.asfarray(data)\n assert len(data.shape) == 3\n\n self = cls()\n self.lvl = data\n self.grid = list(grid)\n self.origin = list(origin)\n\n # redundant information\n self.dim = list(data.shape)\n self.range = [g * (d - 1) for (g, d) in zip(self.grid, self.dim)]\n\n return self\n\n def setup_from_min_max(self,mn,mx,grid,buffer=0.0):\n self.origin = [\n mn[0]-buffer,\n mn[1]-buffer,\n mn[2]-buffer\n ]\n self.range = [\n (mx[0]-mn[0])+2*buffer,\n (mx[1]-mn[1])+2*buffer,\n (mx[2]-mn[2])+2*buffer\n ]\n self.dim = [\n 1 + int(self.range[0]/grid[0]),\n 1 + int(self.range[1]/grid[1]),\n 1 + int(self.range[2]/grid[2])\n ]\n self.grid = list(grid)\n self.lvl = numpy.zeros(self.dim,float)\n \n \n\n"
] |
[
[
"numpy.asfarray",
"numpy.zeros"
]
] |
Eadon999/DeepMatch
|
[
"b37c04f1a6ff687b884dd0935ed0b4de2bdf4a7a"
] |
[
"examples/preprocess.py"
] |
[
"import random\nimport numpy as np\nfrom tqdm import tqdm\nfrom tensorflow.python.keras.preprocessing.sequence import pad_sequences\n\n\ndef gen_data_set(data, negsample=0):\n data.sort_values(\"timestamp\", inplace=True)\n item_ids = data['movie_id'].unique()\n\n train_set = []\n test_set = []\n for reviewerID, hist in tqdm(data.groupby('user_id')):\n pos_list = hist['movie_id'].tolist()\n rating_list = hist['rating'].tolist()\n\n if negsample > 0:\n candidate_set = list(set(item_ids) - set(pos_list))\n neg_list = np.random.choice(candidate_set, size=len(pos_list) * negsample, replace=True)\n for i in range(1, len(pos_list)):\n hist = pos_list[:i]\n if i != len(pos_list) - 1:\n train_set.append((reviewerID, hist[::-1], pos_list[i], 1, len(hist[::-1]), rating_list[i]))\n for negi in range(negsample):\n train_set.append((reviewerID, hist[::-1], neg_list[i * negsample + negi], 0, len(hist[::-1])))\n else:\n test_set.append((reviewerID, hist[::-1], pos_list[i], 1, len(hist[::-1]), rating_list[i]))\n\n random.shuffle(train_set)\n random.shuffle(test_set)\n\n print(len(train_set[0]), len(test_set[0]))\n\n return train_set, test_set\n\n\ndef gen_data_set_sdm(data, seq_short_len=5, seq_prefer_len=50):\n data.sort_values(\"timestamp\", inplace=True)\n train_set = []\n test_set = []\n for reviewerID, hist in tqdm(data.groupby('user_id')):\n pos_list = hist['movie_id'].tolist()\n genres_list = hist['genres'].tolist()\n rating_list = hist['rating'].tolist()\n\n for i in range(1, len(pos_list)):\n print(\"\\n=============reviewerID:{}===================\".format(reviewerID))\n hist = pos_list[:i]\n genres_hist = genres_list[:i]\n print(\"total history:\", pos_list)\n print(\"row sample:\", pos_list[:i])\n print(\"history inverse:\", hist[::-1])\n print(\"train iid:\", pos_list[i])\n long_seq = hist[::-1][seq_short_len:]\n print(\"short:\", hist[::-1][:seq_short_len], \"long:\",\n [0] * seq_prefer_len if len(long_seq) < 1 else long_seq)\n print(\"==================================================\")\n\n if i <= seq_short_len and i != len(pos_list) - 1:\n # short\n '''\n short sample of train_set tuple explain csv:\n feature_index,feature_content,comments\n index_0, train_user_id\n index_1, short_train_seq\n index_2, prefer_train_seq, the same fill value:[0] * seq_prefer_len\n index_3, train_item_id\n index_4, train_label\n index_5, train_short_len\n index_6, train_prefer_len, the same fill value:0\n index_7, 'useless'\n index_8, short_train_seq_genres\n index_9, prefer_train_seq_genres, the same fill value:[0] * seq_prefer_len\n '''\n train_set.append((reviewerID, hist[::-1], [0] * seq_prefer_len, pos_list[i], 1, len(hist[::-1]), 0,\n rating_list[i], genres_hist[::-1], [0] * seq_prefer_len))\n elif i != len(pos_list) - 1:\n # long\n '''\n long sample of train_set tuple explain:\n feature_index,feature_content,comments\n index_0, train_user_id\n index_1, short_train_seq, value is: user's entire short seq\n index_2, prefer_train_seq\n index_3, train_item_id\n index_4, train_label\n index_5, train_short_len\n index_6, train_prefer_len\n index_7, 'useless'\n index_8, short_train_seq_genres, value is: user's entire short prefer_seq\n index_9, prefer_train_seq_genres\n '''\n train_set.append(\n (reviewerID, hist[::-1][:seq_short_len], hist[::-1][seq_short_len:], pos_list[i], 1, seq_short_len,\n len(hist[::-1]) - seq_short_len, rating_list[i], genres_hist[::-1][:seq_short_len],\n genres_hist[::-1][seq_short_len:]))\n elif i <= seq_short_len and i == len(pos_list) - 1:\n # test set short\n test_set.append((reviewerID, hist[::-1], [0] * seq_prefer_len, pos_list[i], 1, len(hist[::-1]), 0,\n rating_list[i], genres_hist[::-1], [0] * seq_prefer_len))\n else:\n # test_set long\n test_set.append(\n (reviewerID, hist[::-1][:seq_short_len], hist[::-1][seq_short_len:], pos_list[i], 1, seq_short_len,\n len(hist[::-1]) - seq_short_len, rating_list[i], genres_hist[::-1][:seq_short_len],\n genres_hist[::-1][seq_short_len:]))\n\n random.shuffle(train_set)\n random.shuffle(test_set)\n\n print(len(train_set[0]), len(test_set[0]))\n\n return train_set, test_set\n\n\ndef gen_model_input(train_set, user_profile, seq_max_len):\n train_uid = np.array([line[0] for line in train_set])\n train_seq = [line[1] for line in train_set]\n train_iid = np.array([line[2] for line in train_set])\n train_label = np.array([line[3] for line in train_set])\n train_hist_len = np.array([line[4] for line in train_set])\n\n train_seq_pad = pad_sequences(train_seq, maxlen=seq_max_len, padding='post', truncating='post', value=0)\n train_model_input = {\"user_id\": train_uid, \"movie_id\": train_iid, \"hist_movie_id\": train_seq_pad,\n \"hist_len\": train_hist_len}\n\n for key in [\"gender\", \"age\", \"occupation\", \"zip\"]:\n train_model_input[key] = user_profile.loc[train_model_input['user_id']][key].values\n\n return train_model_input, train_label\n\n\ndef gen_model_input_sdm(train_set, user_profile, seq_short_len, seq_prefer_len):\n train_uid = np.array([line[0] for line in train_set])\n short_train_seq = [line[1] for line in train_set]\n prefer_train_seq = [line[2] for line in train_set]\n train_iid = np.array([line[3] for line in train_set])\n train_label = np.array([line[4] for line in train_set])\n train_short_len = np.array([line[5] for line in train_set])\n train_prefer_len = np.array([line[6] for line in train_set])\n short_train_seq_genres = np.array([line[8] for line in train_set])\n prefer_train_seq_genres = np.array([line[9] for line in train_set])\n\n train_short_item_pad = pad_sequences(short_train_seq, maxlen=seq_short_len, padding='post', truncating='post',\n value=0)\n train_prefer_item_pad = pad_sequences(prefer_train_seq, maxlen=seq_prefer_len, padding='post', truncating='post',\n value=0)\n train_short_genres_pad = pad_sequences(short_train_seq_genres, maxlen=seq_short_len, padding='post',\n truncating='post',\n value=0)\n train_prefer_genres_pad = pad_sequences(prefer_train_seq_genres, maxlen=seq_prefer_len, padding='post',\n truncating='post',\n value=0)\n\n train_model_input = {\"user_id\": train_uid, \"movie_id\": train_iid, \"short_movie_id\": train_short_item_pad,\n \"prefer_movie_id\": train_prefer_item_pad, \"prefer_sess_length\": train_prefer_len,\n \"short_sess_length\":\n train_short_len, 'short_genres': train_short_genres_pad,\n 'prefer_genres': train_prefer_genres_pad}\n\n for key in [\"gender\", \"age\", \"occupation\", \"zip\"]:\n train_model_input[key] = user_profile.loc[train_model_input['user_id']][key].values\n\n return train_model_input, train_label\n"
] |
[
[
"numpy.array",
"tensorflow.python.keras.preprocessing.sequence.pad_sequences"
]
] |
iremkp/Saber_tmvp4_m4
|
[
"e96c4a3983535122f95455e9cf900ea3fce9200a"
] |
[
"benchmarks-saber.py"
] |
[
"#!/usr/bin/env python3\r\nimport serial\r\nimport sys\r\nimport os\r\nimport subprocess\r\nimport hashlib\r\nimport datetime\r\nimport time\r\nimport numpy as np\r\ndev = serial.Serial(\"/dev/ttyUSB0\", 115200,timeout=10)\r\n\r\ndef benchmarkBinary(binary):\r\n print(\"Flashing {}..\".format(binary))\r\n subprocess.run([\"st-flash\", \"write\", binary, \"0x8000000\"],\r\n stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\r\n print(\"Flashed, now running benchmarks..\".format(binary))\r\n state = 'waiting'\r\n marker = b''\r\n # This parses test vector output starting with a number of leading '=',\r\n # and expects a hashtag '#' after the test vector output.\r\n while True:\r\n x = dev.read()\r\n if x == b'' and state == 'waiting':\r\n print(\"timed out while waiting for the markers\")\r\n return benchmarkBinary(binary)\r\n\r\n if state == 'waiting':\r\n if x == b'=':\r\n marker += x\r\n continue\r\n # If we saw at least 5 equal signs, assume we've probably started\r\n elif marker.count(b'=') > 5:\r\n state = 'beginning'\r\n vector = []\r\n print(\" .. found output marker..\")\r\n if state == 'beginning':\r\n if x == b'=':\r\n continue\r\n else:\r\n state = 'reading'\r\n elif state == 'reading':\r\n if x == b'#':\r\n break\r\n else:\r\n vector.append(x)\r\n lines =b''.join(vector).decode(\"ISO-8859-1\");\r\n lines = lines.split(\"\\n\");\r\n\r\n # sometimes the output markers end up as the first line of the output file\r\n if \"=\" in lines[0]:\r\n return [int(lines[2]), int(lines[5]), int(lines[8])];\r\n else:\r\n return [int(lines[1]), int(lines[4]), int(lines[7])];\r\n\r\ndef printStats(l):\r\n print(\"AVG: {:,}, MIN: {:,}, MAX: {:,}\".format(int(np.mean(l)), min(l), max(l)))\r\n\r\ndef printResults(binary, data):\r\n print(f\"#{binary}\")\r\n print(data)\r\n keygen = [item[0] for item in data]\r\n enc = [item[1] for item in data]\r\n dec = [item[2] for item in data]\r\n print(\"keygen\")\r\n printStats(keygen)\r\n print(\"enc\")\r\n printStats(enc)\r\n print(\"dec\")\r\n printStats(dec)\r\n\r\ndef doBenchmarks():\r\n binaries = [\"benchmark-lightsaber.bin\", \"benchmark-saber.bin\", \"benchmark-firesaber.bin\",\r\n \"stack-lightsaber.bin\", \"stack-saber.bin\", \"stack-firesaber.bin\"\r\n ]\r\n for binary in binaries:\r\n results = []\r\n subprocess.run([\"make\", binary],\r\n stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\r\n for i in range(1):\r\n results.append(benchmarkBinary(binary))\r\n printResults(binary, results)\r\ndoBenchmarks()\r\n"
] |
[
[
"numpy.mean"
]
] |
thiagotei/opentuner
|
[
"a3cd9db06e493302bb89202d4f9513f637f4acb6"
] |
[
"opentuner/search/manipulator.py"
] |
[
"from __future__ import division\n# vim: tabstop=2 shiftwidth=2 softtabstop=2 expandtab autoindent smarttab\nfrom builtins import str\nfrom builtins import map\nfrom builtins import range\nfrom past.utils import old_div\nfrom builtins import object\nimport abc\nimport collections\nimport copy\nimport hashlib\nimport json\nimport logging\nimport math\nimport os\nimport pickle\nimport random\nfrom fn import _\nimport argparse\nfrom datetime import datetime\nimport numpy\nimport inspect\nimport sys\nfrom future.utils import with_metaclass\nfrom functools import reduce\n\nlog = logging.getLogger(__name__)\nargparser = argparse.ArgumentParser(add_help=False)\nargparser.add_argument('--list-params', '-lp',\n help='list available parameter classes')\n\n\nclass ConfigurationManipulatorBase(with_metaclass(abc.ABCMeta, object)):\n \"\"\"\n abstract interface for objects used by search techniques to mutate\n configurations\n \"\"\"\n\n # List of file formats, which can be extended by subclasses. Used in\n # write_to_file() and load_from_file(). Objects in list must define\n # load(fd) and dump(cfg, fd).\n FILE_FORMATS = {'default': json, 'json': json,\n 'pickle': pickle, 'pk': pickle}\n\n def validate(self, config):\n \"\"\"is the given config valid???\"\"\"\n return all(map(_.validate(config), self.parameters(config)))\n\n def normalize(self, config):\n \"\"\"mutate config into canonical form\"\"\"\n for param in self.parameters(config):\n param.normalize(config)\n\n def set_search_driver(self, search_driver):\n \"\"\"called exactly once during setup\"\"\"\n pass\n\n def copy(self, config):\n \"\"\"produce copy of config\"\"\"\n return copy.deepcopy(config)\n\n def parameters_dict(self, config):\n \"\"\"convert self.parameters() to a dictionary by name\"\"\"\n return dict([(p.name, p) for p in self.parameters(config)])\n\n def param_names(self, *args):\n \"\"\"return union of parameter names in args\"\"\"\n return sorted(reduce(set.union,\n [set(map(_.name, self.parameters(cfg)))\n for cfg in args]))\n\n def linear_config(self, a, cfg_a, b, cfg_b, c, cfg_c):\n \"\"\"return a configuration that is a linear combination of 3 other configs\"\"\"\n dst = self.copy(cfg_a)\n dst_params = self.proxy(dst)\n for k in self.param_names(dst, cfg_a, cfg_b, cfg_c):\n dst_params[k].op4_set_linear(cfg_a, cfg_b, cfg_c, a, b, c)\n return dst\n\n def _get_serializer(self, filename, format=None):\n \"\"\"\n Extract the correct file format serializer from self.FILE_FORMATS.\n Guess the format by extension if one is not given.\n \"\"\"\n if format is None:\n format = os.path.splitext(filename)[1].lower().replace('.', '')\n if format not in self.FILE_FORMATS:\n serializer = self.FILE_FORMATS['default']\n if len(self.FILE_FORMATS) > 1:\n log.warning('Unknown file format \"%s\", using \"%s\" instead', format,\n serializer.__name__)\n else:\n serializer = self.FILE_FORMATS[format]\n return serializer\n\n def save_to_file(self, cfg, filename, format=None):\n \"\"\"\n Write cfg to filename. Guess the format by extension if one is not given.\n \"\"\"\n with open(filename, 'wb') as fd:\n self._get_serializer(filename, format).dump(cfg, fd)\n\n def load_from_file(self, filename, format=None):\n \"\"\"\n Read cfg from filename. Guess the format by extension if one is not given.\n \"\"\"\n with open(filename, 'rb') as fd:\n return self._get_serializer(filename, format).load(fd)\n\n def proxy(self, cfg):\n return ManipulatorProxy(self, cfg)\n\n @abc.abstractmethod\n def random(self):\n \"\"\"produce a random initial configuration\"\"\"\n return\n\n @abc.abstractmethod\n def parameters(self, config):\n \"\"\"return a list of of Parameter objects\"\"\"\n return list()\n\n @abc.abstractmethod\n def hash_config(self, config):\n \"\"\"produce unique hash value for the given config\"\"\"\n return\n\n\nclass ConfigurationManipulator(ConfigurationManipulatorBase):\n \"\"\"\n a configuration manipulator using a fixed set of parameters and storing\n configs in a dict-like object\n \"\"\"\n\n def __init__(self, params=None, config_type=dict, seed_config=None, **kwargs):\n if params is None:\n params = []\n self.params = list(params)\n self.config_type = config_type\n self.search_driver = None\n self._seed_config = seed_config\n super(ConfigurationManipulator, self).__init__(**kwargs)\n for p in self.params:\n p.parent = self\n\n def add_parameter(self, p):\n p.set_parent(self)\n self.params.append(p)\n\n #TODO sub parameters should be recursed on\n # not currently an issue since no doubly-nested sub-parameters\n sub_params = p.sub_parameters()\n for sp in sub_params:\n sp.set_parent(p)\n self.params.extend(sub_params)\n\n def set_search_driver(self, search_driver):\n self.search_driver = search_driver\n\n def seed_config(self):\n \"\"\"produce a fixed seed configuration\"\"\"\n if self._seed_config:\n cfg = copy.deepcopy(self._seed_config)\n else:\n cfg = self.config_type()\n for p in self.params:\n if not isinstance(p.name, str) or '/' not in p.name:\n cfg[p.name] = p.seed_value()\n return cfg\n\n def random(self):\n \"\"\"produce a random configuration\"\"\"\n cfg = self.seed_config()\n for p in self.parameters(cfg):\n p.op1_randomize(cfg)\n return cfg\n\n def parameters(self, config):\n \"\"\"return a list of Parameter objects\"\"\"\n if type(config) is not self.config_type:\n log.error(\"wrong type, expected %s got %s\",\n str(self.config_type),\n str(type(config)))\n raise TypeError()\n return self.params\n\n def parameters_to_json(self):\n \"\"\"\n output information about the parameters in this manipulator in json format:\n [ConfigurationManipulator,{pinfo:count,pinfo:count ...}]\n where pinfo has a similar form to describe the parameter's sub-parameters:\n [param_name,{pinfo:count,pinfo:count ...}]\n \"\"\"\n def param_info_to_json(param, sub_parameters):\n \"\"\"\n recursively output information about a parameter and its subparameters in a json format:\n\n [parameter_name, {subparam_info:count,subparam_info:count,...}]\n or if no subparams\n [parameter_name,{}]\n\n where subparam_info are sorted alphabetically. Note we can't directly use json since\n sets/dictionaries aren't always ordered by key\n \"\"\"\n sub_parameter_counts = {}\n # build the string\n if isinstance(param, str):\n param_name = param\n else:\n param_name = param.__class__.__name__\n out = ['[', param_name, ',{']\n\n if len(sub_parameters) > 0:\n # count sub params\n for sp in sub_parameters:\n spout = param_info_to_json(sp, sp.sub_parameters())\n sub_parameter_counts[spout] = sub_parameter_counts.get(spout, 0) + 1\n # add the count map in sorted order\n for sp in sorted(sub_parameter_counts):\n out.append(sp)\n out.append(':')\n out.append(str(sub_parameter_counts[sp]))\n out.append(',')\n out.pop() # remove trailing comma\n\n out.append('}]')\n return ''.join(out)\n\n # filter out subparameters to avoid double counting\n params = [p for p in self.params if p.parent is self]\n return param_info_to_json(self, params)\n\n def hash_config(self, config):\n \"\"\"produce unique hash value for the given config\"\"\"\n m = hashlib.sha256()\n params = list(self.parameters(config))\n params.sort(key=_.name)\n for i, p in enumerate(params):\n m.update(str(p.name).encode())\n m.update(p.hash_value(config))\n m.update(str(i).encode())\n m.update(b\"|\")\n return m.hexdigest()\n\n def search_space_size(self):\n \"\"\"estimate the size of the search space, not precise\"\"\"\n return reduce(_ * _, [x.search_space_size() for x in self.params])\n\n def difference(self, cfg1, cfg2):\n cfg = self.copy(cfg1)\n for param in self.parameters(cfg1):\n if param.is_primitive(cfg1):\n # TODO: check range\n param.set_value(cfg, param.get_value(cfg1) - param.get_value(cfg2))\n else:\n pass\n return cfg\n\n def applySVs(self, cfg, sv_map, args, kwargs):\n \"\"\"\n Apply operators to each parameter according to given map. Updates cfg.\n Parameters with no operators specified are not updated.\n cfg: configuration data\n sv_map: python dict that maps string parameter name to class method name\n arg_map: python dict that maps string parameter name to class method\n arguments\n \"\"\"\n # TODO: check consistency between sv_map and cfg\n param_dict = self.parameters_dict(cfg)\n for pname in self.param_names(cfg):\n param = param_dict[pname]\n getattr(param, sv_map[pname])(cfg, *args[pname], **kwargs[pname])\n\n\nclass Parameter(with_metaclass(abc.ABCMeta, object)):\n \"\"\"\n abstract base class for parameters in a ConfigurationManipulator\n \"\"\"\n\n def __init__(self, name):\n self.name = name\n self.parent = None\n super(Parameter, self).__init__()\n\n def _to_storage_type(self, val):\n \"\"\"hook to support transformation applied while stored\"\"\"\n return val\n\n def _from_storage_type(self, sval):\n \"\"\"hook to support transformation applied while stored\"\"\"\n return sval\n\n def _read_node(self, config):\n \"\"\"hook to support different storage structures\"\"\"\n node = config\n if not isinstance(self.name, str):\n return node, self.name\n name_parts = self.name.split('/')\n for part in name_parts[:-1]:\n if isinstance(node, list):\n part = int(part)\n node = node[part]\n part = name_parts[-1]\n if isinstance(node, list):\n part = int(part)\n return node, part\n\n def _get(self, config):\n \"\"\"hook to support different storage structures\"\"\"\n node, part = self._read_node(config)\n return self._from_storage_type(node[part])\n\n def _set(self, config, v):\n \"\"\"hook to support different storage structures\"\"\"\n node, part = self._read_node(config)\n node[part] = self._to_storage_type(v)\n\n def set_parent(self, manipulator):\n self.parent = manipulator\n\n def validate(self, config):\n \"\"\"is the given config valid???\"\"\"\n return True\n\n def is_primitive(self, ignored=None):\n return isinstance(self, PrimitiveParameter)\n\n def is_permutation(self, ignored=None):\n return isinstance(self, PermutationParameter)\n\n def manipulators(self, config):\n \"\"\"\n a list of manipulator functions to change this value in the config\n manipulators must be functions that take a config and change it in place\n\n default implementation just has op1_randomize as only operation\n \"\"\"\n return [self.op1_randomize]\n\n def normalize(self, config):\n \"\"\"\n mutate this parameter into a canonical form\n \"\"\"\n pass\n\n def sub_parameters(self):\n \"\"\"\n additional parameters added with this parameter\n \"\"\"\n return []\n\n @abc.abstractmethod\n def op1_randomize(self, cfg):\n \"\"\"\n Set this parameter's value in a configuration to a random value\n\n :param config: the configuration to be changed\n \"\"\"\n pass\n\n @abc.abstractmethod\n def seed_value(self):\n \"\"\"some legal value of this parameter (for creating initial configs)\"\"\"\n return\n\n @abc.abstractmethod\n def copy_value(self, src, dst):\n \"\"\"copy the value of this parameter from src to dst config\"\"\"\n pass\n\n @abc.abstractmethod\n def same_value(self, cfg1, cfg2):\n \"\"\"test if cfg1 and cfg2 have the same value of this parameter\"\"\"\n return\n\n @abc.abstractmethod\n def hash_value(self, config):\n \"\"\"produce unique hash for this value in the config\"\"\"\n return\n\n @abc.abstractmethod\n def op4_set_linear(self, cfg, cfg_a, cfg_b, cfg_c, a, b, c):\n \"\"\"\n Sets the parameter value in a configuration to a linear combination of 3\n other configurations: :math:`a*cfg_a + b*cfg_b + c*cfg_c`\n\n :param cfg: the configuration to be changed\n :param cfg_a: a parent configuration\n :param cfg_b: a parent configuration\n :param cfg_c: a parent configuration\n :param a: weight for cfg_a\n :param b: weight for cfg_b\n :param c: weight for cfg_c\n \"\"\"\n pass\n\n def search_space_size(self):\n return 1\n\n def op1_nop(self, cfg):\n \"\"\"\n The 'null' operator. Does nothing.\n\n :param cfg: the configuration to be changed\n \"\"\"\n pass\n\n # Stochastic variators\n def op3_swarm(self, cfg, cfg1, cfg2, c, c1, c2, *args, **kwargs):\n \"\"\"\n Stochastically 'move' the parameter value in a configuration towards those\n in two parent configurations. This is done by calling :py:meth:`opn_stochastic_mix`\n\n :param cfg: the configuration to be changed\n :param cfg1: a parent configuration\n :param cfg2: a parent configuration\n :param c: weight of original configuration\n :param c1: weight for cfg1\n :param c2: weight for cfg2\n \"\"\"\n # default to probabilistic treatment\n self.opn_stochastic_mix(cfg, [cfg, cfg1, cfg2], [c, c1, c2])\n\n def opn_stochastic_mix(self, cfg, cfgs, ratio, *args, **kwargs):\n \"\"\"\n Stochastically recombine a list of parent values into a single result.\n\n This randomly copies a value from a list of parents configurations according\n to a list of weights.\n\n :param cfg: the configuration to be changed\n :param cfgs: a list of parent configurations\n :param ratio: a list of floats representing the weight of each configuration\n in cfgs\n\n \"\"\"\n assert len(cfgs) == len(ratio)\n r = random.random()\n c = old_div(numpy.array(ratio, dtype=float), sum(ratio))\n for i in range(len(c)):\n if r < sum(c[:i + 1]):\n self.copy_value(cfg, cfgs[i])\n break\n\n\nclass PrimitiveParameter(with_metaclass(abc.ABCMeta, Parameter)):\n \"\"\"\n An abstract interface implemented by parameters that represent a single\n dimension in a cartesian space in a legal range\n \"\"\"\n\n def __init__(self, name, value_type=float, **kwargs):\n self.value_type = value_type\n super(PrimitiveParameter, self).__init__(name, **kwargs)\n\n def hash_value(self, config):\n \"\"\"produce unique hash for this value in the config\"\"\"\n self.normalize(config)\n return hashlib.sha256(repr(self.get_value(config)).encode('utf-8')).hexdigest().encode('utf-8')\n\n def copy_value(self, src, dst):\n \"\"\"copy the value of this parameter from src to dst config\"\"\"\n self.set_value(dst, self.get_value(src))\n\n def same_value(self, cfg1, cfg2):\n \"\"\"test if cfg1 and cfg2 have the same value of this parameter\"\"\"\n return self.get_value(cfg1) == self.get_value(cfg2)\n\n def is_integer_type(self):\n \"\"\"true if self.value_type can only represent integers\"\"\"\n return self.value_type(0) == self.value_type(0.1)\n\n def get_unit_value(self, config):\n \"\"\"get_value scaled such that range is between 0.0 and 1.0\"\"\"\n low, high = self.legal_range(config)\n if self.is_integer_type():\n # account for rounding\n low -= 0.4999\n high += 0.4999\n val = self.get_value(config)\n if low < high:\n return old_div(float(val - low), float(high - low))\n else:\n if low > high:\n log.warning('invalid range for parameter %s, %s to %s',\n self.name, low, high)\n # only a single legal value!\n return 0.0\n\n def set_unit_value(self, config, unit_value):\n \"\"\"set_value scaled such that range is between 0.0 and 1.0\"\"\"\n assert 0.0 <= unit_value <= 1.0\n low, high = self.legal_range(config)\n if self.is_integer_type():\n # account for rounding\n low -= 0.4999\n high += 0.4999\n if low < high:\n val = unit_value * float(high - low) + low\n if self.is_integer_type():\n val = round(val)\n val = max(low, min(val, high))\n self.set_value(config, self.value_type(val))\n\n def op1_normal_mutation(self, cfg, sigma=0.1, *args, **kwargs):\n \"\"\"\n apply normally distributed noise to this parameter's value in a\n configuration\n\n :param cfg: The configuration to be changed\n :param sigma: the std. deviation of the normally distributed noise on a unit\n scale\n \"\"\"\n v = self.get_unit_value(cfg)\n v += random.normalvariate(0.0, sigma)\n # handle boundary cases by reflecting off the edge\n if v < 0.0:\n v *= -1.0\n if v > 1.0:\n v = 1.0 - (v % 1)\n self.set_unit_value(cfg, v)\n\n def op4_set_linear(self, cfg, cfg_a, cfg_b, cfg_c, a, b, c):\n \"\"\"\n set the parameter value in a configuration to a linear combination of 3\n other configurations: :math:`a*cfg_a + b*cfg_b + c*cfg_c`\n\n :param cfg: The configuration to be changed\n :param cfg_a: a parent configuration\n :param cfg_b: a parent configuration\n :param cfg_c: a parent configuration\n :param a: weight for cfg_a\n :param b: weight for cfg_b\n :param c: weight for cfg_c\n \"\"\"\n va = self.get_unit_value(cfg_a)\n vb = self.get_unit_value(cfg_b)\n vc = self.get_unit_value(cfg_c)\n v = a * va + b * vb + c * vc\n v = max(0.0, min(v, 1.0))\n\n self.set_unit_value(cfg, v)\n\n def manipulators(self, config):\n \"\"\"\n a list of manipulator functions to change this value in the config\n manipulators must be functions that take a config and change it in place\n\n for primitive params default implementation is uniform random and normal\n \"\"\"\n return [self.op1_randomize, self.op1_normal_mutation]\n\n @abc.abstractmethod\n def set_value(self, config, value):\n \"\"\"assign this value in the given configuration\"\"\"\n pass\n\n @abc.abstractmethod\n def get_value(self, config):\n \"\"\"retrieve this value from the given configuration\"\"\"\n return 0\n\n @abc.abstractmethod\n def legal_range(self, config):\n \"\"\"return the legal range for this parameter, inclusive\"\"\"\n return 0, 1\n\n\nclass NumericParameter(PrimitiveParameter):\n \"\"\"\n A parameter representing a number with a minimum and maximum value\n \"\"\"\n def __init__(self, name, min_value, max_value, **kwargs):\n \"\"\"min/max are inclusive\"\"\"\n assert min_value <= max_value\n super(NumericParameter, self).__init__(name, **kwargs)\n # after super call so self.value_type is initialized\n self.min_value = self.value_type(min_value)\n self.max_value = self.value_type(max_value)\n\n def seed_value(self):\n \"\"\"some legal value of this parameter (for creating initial configs)\"\"\"\n return self.min_value\n\n def set_value(self, config, value):\n assert value >= self.min_value\n assert value <= self.max_value\n self._set(config, value)\n\n def get_value(self, config):\n return self._get(config)\n\n def legal_range(self, config):\n return self.min_value, self.max_value\n\n def op1_randomize(self, config):\n \"\"\"\n Set this parameter's value in a configuration to a random value in its legal\n range\n\n :param config: the configuration to be changed\n \"\"\"\n if self.is_integer_type():\n self.set_value(config, random.randint(*self.legal_range(config)))\n else:\n self.set_value(config, random.uniform(*self.legal_range(config)))\n\n def op1_scale(self, cfg, k):\n \"\"\"\n Scale this parameter's value in a configuration by a constant factor\n\n :param cfg: the configuration to be changed\n :param k: the constant factor to scale the parameter value by\n \"\"\"\n v = self.get_value(cfg) * k\n v = max(self.min_value, min(self.max_value, v))\n self.set_value(cfg, v)\n\n def op3_difference(self, cfg, cfg1, cfg2):\n \"\"\"\n Set this parameter's value in a configuration to the difference between this\n parameter's values in 2 other configs (cfg2 - cfg1)\n\n :param cfg: the configuration to be changed\n :param cfg1: The configuration whose parameter value is being subtracted\n :param cfg2: The configuration whose parameter value is subtracted from\n \"\"\"\n v = self.get_value(cfg2) - self.get_value(cfg1)\n v = max(self.min_value, min(self.max_value, v))\n self.set_value(cfg, v)\n\n def opn_sum(self, cfg, *cfgs):\n \"\"\"\n Set this parameter's value in a configuration to the sum of it's values in a\n list of configurations\n\n :param cfg: the configuration to be changed\n :param cfgs: a list of configurations to sum\n \"\"\"\n v = sum([self.get_value(c) for c in cfgs])\n v = max(self.min_value, min(self.max_value, v))\n self.set_value(cfg, v)\n\n def search_space_size(self):\n if self.value_type is float:\n return 2 ** 32\n else:\n return self.max_value - self.min_value + 1 # inclusive range\n\n\nclass IntegerParameter(NumericParameter):\n \"\"\"\n A parameter representing an integer value in a legal range\n \"\"\"\n def __init__(self, name, min_value, max_value, **kwargs):\n \"\"\"min/max are inclusive\"\"\"\n kwargs['value_type'] = int\n super(IntegerParameter, self).__init__(name, min_value, max_value, **kwargs)\n\n def op3_swarm(self, cfg, cfg1, cfg2, c=1, c1=0.5,\n c2=0.5, velocity=0, sigma=0.2, *args, **kwargs):\n \"\"\"\n Simulates a single update step in particle swarm optimization by updating\n the current position and returning a new velocity.\n\n The new velocity is given by\n\n .. math:: c*velocity + r1*c1*(cfg1-cfg) + r2*c2*(cfg2-cfg)\n\n where r1 and r2 are random values between 0 and 1.\n\n The new current position is the new velocity with gaussian noise added.\n\n :param cfg: the configuration to be changed. Represents the current position\n :param cfg1: a configuration to shift towards. Should be the local best\n position\n :param cfg2: a configuration to shift towards. Should be the global best\n position\n :param c: the weight of the current velocity\n :param c1: weight of cfg1\n :param c2: weight of cfg2\n :param velocity: the old velocity\n :param sigma: standard deviation of the gaussian noise, on a unit-scale\n :return: the new velocity, a float\n\n \"\"\"\n vmin, vmax = self.legal_range(cfg)\n k = vmax - vmin\n # calculate the new velocity\n v = velocity * c + (self.get_value(cfg1) - self.get_value(\n cfg)) * c1 * random.random() + (self.get_value(\n cfg2) - self.get_value(cfg)) * c2 * random.random()\n # Map velocity to continuous space with sigmoid\n s = old_div(k, (1 + numpy.exp(-v))) + vmin\n # Add Gaussian noise\n p = random.gauss(s, sigma * k)\n # Discretize and bound\n p = int(min(vmax, max(round(p), vmin)))\n self.set_value(cfg, p)\n return v\n\n\nclass FloatParameter(NumericParameter):\n def __init__(self, name, min_value, max_value, **kwargs):\n \"\"\"min/max are inclusive\"\"\"\n kwargs['value_type'] = float\n super(FloatParameter, self).__init__(name, min_value, max_value, **kwargs)\n\n def op3_swarm(self, cfg, cfg1, cfg2, c=1, c1=0.5,\n c2=0.5, velocity=0, *args, **kwargs):\n \"\"\"\n\n Simulates a single update step in particle swarm optimization by updating\n the current position and returning a new velocity.\n\n The new velocity is given by\n\n .. math:: c*velocity + r1*c1*(cfg1-cfg) + r2*c2*(cfg2-cfg)\n\n where r1 and r2 are random values between 0 and 1\n\n The new current position is the old current position offset by the new\n velocity:\n\n :param cfg: the configuration to be changed. Represents the current position\n :param cfg1: a configuration to shift towards. Should be the local best\n position\n :param cfg2: a configuration to shift towards. Should be the global best\n position\n :param c: the weight of the current velocity\n :param c1: weight of cfg1\n :param c2: weight of cfg2\n :param velocity: the old velocity\n :return: the new velocity, a float\n\n \"\"\"\n vmin, vmax = self.legal_range(cfg)\n v = velocity * c + (self.get_value(cfg1) - self.get_value(\n cfg)) * c1 * random.random() + (self.get_value(\n cfg2) - self.get_value(cfg)) * c2 * random.random()\n p = self.get_value(cfg) + v\n p = min(vmax, max(p, vmin))\n self.set_value(cfg, p)\n return v\n\n\nclass ScaledNumericParameter(NumericParameter):\n \"\"\"\n A Parameter that is stored in configurations normally, but has a scaled\n value when accessed using 'get_value'.\n Because search techniques interact with Parameters through get_value, these\n parameters are searched on a different scale (e.g. log scale).\n \"\"\"\n\n @abc.abstractmethod\n def _scale(self, v):\n \"\"\"\n called on a value when getting it from it's configuration. Transforms the\n actual value to the scale it is searched on\n \"\"\"\n return v\n\n @abc.abstractmethod\n def _unscale(self, v):\n \"\"\"\n called on a value when storing it. Transforms a value from it's search scale\n to it's actual value\n \"\"\"\n return v\n\n def set_value(self, config, value):\n NumericParameter.set_value(self, config, self._unscale(value))\n\n def get_value(self, config):\n return self._scale(NumericParameter.get_value(self, config))\n\n def legal_range(self, config):\n return list(map(self._scale, NumericParameter.legal_range(self, config)))\n\n\nclass LogIntegerParameter(ScaledNumericParameter, FloatParameter):\n \"\"\"\n an integer value that is searched on a log scale, but stored without scaling\n \"\"\"\n\n def _scale(self, v):\n return math.log(v + 1.0 - self.min_value, 2.0)\n\n def _unscale(self, v):\n v = 2.0 ** v - 1.0 + self.min_value\n v = int(round(v))\n return v\n\n def legal_range(self, config):\n low, high = NumericParameter.legal_range(self, config)\n # increase the bounds account for rounding\n return self._scale(low - 0.4999), self._scale(high + 0.4999)\n\n\nclass LogFloatParameter(ScaledNumericParameter, FloatParameter):\n \"\"\"\n a float parameter that is searched on a log scale, but stored without scaling\n \"\"\"\n\n def _scale(self, v):\n return math.log(v + 1.0 - self.min_value, 2.0)\n\n def _unscale(self, v):\n v = 2.0 ** v - 1.0 + self.min_value\n return v\n\n\nclass PowerOfTwoParameter(ScaledNumericParameter, IntegerParameter):\n \"\"\"\n An integer power of two, with a min and max value. Searched by the exponent\n \"\"\"\n\n def __init__(self, name, min_value, max_value, **kwargs):\n kwargs['value_type'] = int\n assert min_value >= 1\n assert math.log(min_value, 2) % 1 == 0 # must be power of 2\n assert math.log(max_value, 2) % 1 == 0 # must be power of 2\n super(PowerOfTwoParameter, self).__init__(name, min_value, max_value,\n **kwargs)\n\n def _scale(self, v):\n return int(math.log(v, 2))\n\n def _unscale(self, v):\n return 2 ** int(v)\n\n def legal_range(self, config):\n return int(math.log(self.min_value, 2)), int(math.log(self.max_value, 2))\n\n def search_space_size(self):\n return int(math.log(self.max_value,2) - math.log(self.min_value, 2)) + 1\n\n##################\n\nclass ComplexParameter(Parameter):\n \"\"\"\n A non-cartesian parameter that can't be manipulated directly, but has a set\n of user defined manipulation functions\n \"\"\"\n\n def copy_value(self, src, dst):\n \"\"\"copy the value of this parameter from src to dst config\"\"\"\n self._set(dst, copy.deepcopy(self._get(src)))\n\n def same_value(self, cfg1, cfg2):\n \"\"\"test if cfg1 and cfg2 have the same value of this parameter\"\"\"\n return self._get(cfg1) == self._get(cfg2)\n\n def hash_value(self, config):\n \"\"\"produce unique hash for this value in the config\"\"\"\n self.normalize(config)\n return hashlib.sha256(repr(self.get_value(config)).encode('utf-8')).hexdigest().encode('utf-8')\n\n def get_value(self, config):\n return self._get(config)\n\n def set_value(self, config, value):\n self._set(config, value)\n\n def op4_set_linear(self, cfg, cfg_a, cfg_b, cfg_c, a, b, c):\n \"\"\"\n set this value to :math:`a*cfg_a + b*cfg_b + c*cfg_c`\n\n this operation is not possible in general with complex parameters but\n we make an attempt to \"fake\" it for common use cases\n\n basically a call to randomize unless after normalization,\n a = 1.0, b == -c, and cfg_b == cfg_c, in which case nothing is done\n\n :param cfg: the configuration to be changed\n :param cfg_a: a parent configuration\n :param cfg_b: a parent configuration\n :param cfg_c: a parent configuration\n :param a: weight for cfg_a\n :param b: weight for cfg_b\n :param c: weight for cfg_c\n \"\"\"\n # attempt to normalize order, we prefer a==1.0\n if a != 1.0 and b == 1.0: # swap a and b\n a, cfg_a, b, cfg_b = b, cfg_b, a, cfg_a\n if a != 1.0 and c == 1.0: # swap a and c\n a, cfg_a, c, cfg_c = c, cfg_c, a, cfg_a\n\n # attempt to normalize order, we prefer b==-c\n if b < c: # swap b and c\n b, cfg_b, c, cfg_c = c, cfg_c, b, cfg_b\n if b != -c and a == -c: # swap a and c\n a, cfg_a, c, cfg_c = c, cfg_c, a, cfg_a\n\n if a == 1.0 and b == -c:\n self.copy_value(cfg_a, cfg)\n self.add_difference(cfg, b, cfg_b, cfg_c) # TODO inline this logic?\n else:\n # TODO: should handle more cases\n self.op1_randomize(cfg)\n\n def add_difference(self, cfg_dst, scale, cfg_b, cfg_c):\n \"\"\"\n add the difference cfg_b-cfg_c to cfg_dst\n\n this is the key operation used in differential evolution\n and some simplex techniques\n\n this operation is not possible in general with complex parameters but\n we make an attempt to \"fake\" it\n \"\"\"\n if not self.same_value(cfg_b, cfg_c):\n self.op1_randomize(cfg_dst)\n\n @abc.abstractmethod\n def op1_randomize(self, config):\n \"\"\"\n randomize this value without taking into account the current position\n :param config: the configuration to be changed\n \"\"\"\n pass\n\n @abc.abstractmethod\n def seed_value(self):\n \"\"\"some legal value of this parameter (for creating initial configs)\"\"\"\n return\n\n\nclass BooleanParameter(ComplexParameter):\n def manipulators(self, config):\n return [self.op1_flip]\n\n def get_value(self, config):\n return self._get(config)\n\n def set_value(self, config, value):\n self._set(config, value)\n\n def op1_randomize(self, config):\n \"\"\"\n Set this parameter's value in a configuration randomly\n\n :param config: the configuration to be changed\n \"\"\"\n self._set(config, self.seed_value())\n\n def seed_value(self):\n return random.choice((True, False))\n\n def op1_flip(self, config):\n \"\"\"\n Flip this parameter's value in a configuration\n\n :param config: the configuration to be changed\n \"\"\"\n self._set(config, not self._get(config))\n\n def search_space_size(self):\n return 2\n\n def op3_swarm(self, cfg, cfg1, cfg2, c=1, c1=0.5,\n c2=0.5, velocity=0, *args, **kwargs):\n \"\"\"\n Simulates a single update step in particle swarm optimization by updating\n the current position and returning a new velocity.\n\n The new velocity is given by\n\n .. math:: c*velocity + r1*c1*(cfg1-cfg) + r2*c2*(cfg2-cfg)\n\n where r1 and r2 are random values between 0 and 1\n\n The new current position is randomly chosen based on the new velocity\n\n :param cfg: the configuration to be changed. Represents the current position\n :param cfg1: a configuration to shift towards. Should be the local best position\n :param cfg2: a configuration to shift towards. Should be the global best position\n :param c: the weight of the current velocity\n :param c1: weight of cfg1\n :param c2: weight of cfg2\n :param velocity: the old velocity\n :param args:\n :param kwargs:\n :return: the new velocity, a float\n\n \"\"\"\n v = velocity * c + (self.get_value(cfg1) - self.get_value(\n cfg)) * c1 * random.random() + (self.get_value(\n cfg2) - self.get_value(cfg)) * c2 * random.random()\n # Map velocity to continuous space with sigmoid\n s = old_div(1, (1 + numpy.exp(-v)))\n # Decide position randomly\n p = (s - random.random()) > 0\n self.set_value(cfg, p)\n return v\n\n\nclass SwitchParameter(ComplexParameter):\n \"\"\"\n A parameter representing an unordered collection of options with no implied\n correlation between the choices. The choices are range(option_count)\n \"\"\"\n\n def __init__(self, name, option_count):\n self.option_count = option_count\n super(SwitchParameter, self).__init__(name)\n\n def op1_randomize(self, config):\n \"\"\"\n Set this parameter's value in a configuration to a random value\n\n :param config: the configuration to be changed\n \"\"\"\n self._set(config, random.randrange(self.option_count))\n\n def seed_value(self):\n return random.randrange(self.option_count)\n\n def search_space_size(self):\n return max(1, self.option_count)\n\n\nclass EnumParameter(ComplexParameter):\n \"\"\"\n same as a SwitchParameter but choices are taken from an arbitrarily typed list\n \"\"\"\n\n def __init__(self, name, options):\n super(EnumParameter, self).__init__(name)\n self.options = list(options)\n\n def op1_randomize(self, config):\n \"\"\"\n Set this parameter's value in a configuration to a random value\n\n :param config: the configuration to be changed\n \"\"\"\n self._set(config, random.choice(self.options))\n\n def seed_value(self):\n return random.choice(self.options)\n\n def search_space_size(self):\n return max(1, len(self.options))\n\n\nclass PermutationParameter(ComplexParameter):\n \"\"\"\n A parameter representing a permutation (or ordering) as a list of items\n \"\"\"\n def __init__(self, name, items):\n super(PermutationParameter, self).__init__(name)\n self._items = list(items)\n self.size = len(items)\n\n def op1_randomize(self, config):\n \"\"\"\n Set this parameter's value in a configuration to a random value\n\n :param config: the configuration to be changed\n \"\"\"\n random.shuffle(self._get(config))\n self.normalize(config)\n\n def op1_small_random_change(self, config, p=0.25):\n \"\"\"\n Iterates through the list and probabilistically swaps each element with the\n next element\n\n :param p: probability of swapping an element with the next element\n :param config: the configuration to be changed\n \"\"\"\n cfg_item = self._get(config)\n for i in range(1, len(cfg_item)):\n if random.random() < p:\n # swap\n cfg_item[i - 1], cfg_item[i] = cfg_item[i], cfg_item[i - 1]\n self.normalize(config)\n\n def seed_value(self):\n return list(self._items) # copy\n\n def manipulators(self, config):\n return [self.op1_randomize, self.op1_small_random_change]\n\n def get_value(self, config):\n return self._get(config)\n\n def set_value(self, config, value):\n self._set(config, value)\n\n def search_space_size(self):\n return math.factorial(max(1, len(self._items)))\n\n def op3_cross(self, cfg, cfg1, cfg2, xchoice='op3_cross_OX1', strength=0.3,\n *args, **kwargs):\n \"\"\"\n Calls the crossover operator specified by xchoice\n Passes argument d = strength*(size of the permutation)\n\n :param cfg: the configuration to be changed\n :param cfg1: a parent configuration\n :param cfg2: a parent configuration\n :param xchoice: string specifying which crossover operator to use (should start with op3_cross prefix)\n :param strength: the strength of the crossover\n \"\"\"\n dd = int(round(self.size * strength))\n if dd < 1:\n log.warning('Crossover length too small. Cannot create new solution.')\n if dd >= self.size:\n log.warning('Crossover length too big. Cannot create new solution.')\n getattr(self, xchoice)(cfg, cfg1, cfg2, d=dd, *args, **kwargs)\n\n def op3_swarm(self, cfg, cfg1, cfg2, xchoice='op3_cross_OX1', c=0.5,\n c1=0.5, c2=0.5, strength=0.3, velocity=0, *args, **kwargs):\n \"\"\"\n Replacement for particle swarm optimization iterative step for permutations.\n Given a target cfg and 2 parent cfgs, probabilistically performs an\n op3_cross with one of the 2 parents.\n\n :param cfg: the configuration to be changed. Represents the current position\n :param cfg1: a configuration to shift towards. Should be the local best\n position\n :param cfg2: a configuration to shift towards. Should be the global best\n position\n :param xchoice: which crossover operator should be used\n :param c: the probability of not performing a crossover\n :param c1: the probability of performing a crossover with cfg1 (if a\n crossover is performed)\n :param c2: unused\n :param strength: the strength of the crossover\n :param velocity: the old velocity - unused\n \"\"\"\n if random.uniform(0, 1) > c:\n if random.uniform(0, 1) < c1:\n # Select crossover operator\n self.op3_cross(cfg, cfg, cfg1, xchoice, strength)\n else:\n self.op3_cross(cfg, cfg, cfg2, xchoice, strength)\n\n # swap-based operators\n def op2_random_swap(self, cfg, cfg1, *args, **kwargs):\n \"\"\"\n Swap a random pair of items in cfg1 and save the result into cfg\n\n :param cfg: the configuration to be changed\n :param cfg1: the configuration whose PermutationParameter's elements are\n swapped and copied into cfg\n \"\"\"\n p = self.get_value(cfg1)[:]\n r = random.randint(0, len(p) - 1)\n s = random.randint(0, len(p) - 1)\n v1 = p[r]\n v2 = p[s]\n p[r] = v2\n p[s] = v1\n self.set_value(cfg, p)\n\n def op2_random_invert(self, cfg, cfg1, strength=0.3, *args, **kwargs):\n \"\"\"\n Reverse the ordering of a random subsection of size d in cfg1 and save the\n result in cfg where d = strength*total-size\n\n :param cfg: the configuration to be changed\n :param cfg1: the configuration whose PermutationParameter is inverted\n :param strength: the size of the reversed subsection as a fraction of the\n total size\n \"\"\"\n p = self.get_value(cfg1)[:]\n d = int(round(len(p) * strength))\n r = random.randint(0, len(p) - d)\n subpath = p[r:r + d][:]\n subpath.reverse()\n p[r:r + d] = subpath\n self.set_value(cfg, p)\n\n # Crossover operators\n def op3_cross_PX(self, cfg, cfg1, cfg2, d=0):\n \"\"\"\n Partition crossover (Whitley 2009?)\n\n Chooses a random cut point and reorders elements in cfg1 up to the cut point\n according to their order in cfg2.\n\n Saves the result in cfg\n\n :param cfg: the configuration to be changed\n :param cfg1: the first parent configuration. The \"base\" configuration\n :param cfg2: the second parent configuration. Is \"crossed into\" cfg1\n :param d: unused\n \"\"\"\n p1 = self.get_value(cfg1)\n p2 = self.get_value(cfg2)\n c1 = random.randint(2, len(p1))\n self.set_value(cfg, sorted(p1[:c1], key=lambda x: p2.index(x)) + p1[c1:])\n\n def op3_cross_PMX(self, cfg, cfg1, cfg2, d=0):\n \"\"\"\n Partially-mapped crossover Goldberg & Lingle (1985)\n\n Replaces a random section of cfg1 with the corresponding section in cfg2.\n Displaced elements in cfg1 are moved to the old position of the elements\n displacing them\n\n :param cfg: the configuration to be changed\n :param cfg1: the first parent configuration. The \"base\" configuration\n :param cfg2: the second parent configuration. Is \"crossed into\" cfg1\n :param d: the size of the crossover\n \"\"\"\n if d == 0:\n d = max(1, int(round(self.size * 0.3))) # default to 1/3 of permutation size\n p1 = self.get_value(cfg1)[:]\n p2 = self.get_value(cfg2)[:]\n\n r = random.randint(0, len(p1) - d)\n\n c1 = p1[r:r + d]\n c2 = p2[r:r + d]\n\n # get new permutation by crossing over a section of p2 onto p1\n pnew = self.get_value(cfg1)[:]\n pnew[r:r + d] = c2\n # fix conflicts by taking displaced elements in crossed over section\n # displaced = (elements x in c1 where x does not have corresponding value in c2)\n # and putting them where the value that displaced them was\n\n #candidates for displacement\n candidate_indices = set(list(range(r)) + list(range(r+d, len(p1))))\n # Check through displaced elements to find values to swap conflicts to\n while c1 != []:\n n = c1[0]\n #try to match up a value in c1 to the equivalent value in c2\n while c2[0] in c1:\n if n == c2[0]:\n # already match up\n break\n # find position idx of c2[0] in c1\n link_idx = c1.index(c2[0])\n # get value of c2 at idx\n link = c2[link_idx]\n # remove c2[idx] and c1[idx] since they match up when we swap c2[0] with c2[idx] (this avoids an infinite loop)\n del c2[link_idx]\n del c1[link_idx]\n # swap new value into c2[0]\n c2[0] = link\n\n if n != c2[0]:\n # first check if we can swap in the crossed over section still\n if n in c2:\n c2[c2.index(n)] = c2[0]\n else:\n # assign first instance of c2[0] outside of the crossed over section in pnew to c1[0]\n for idx in candidate_indices:\n if pnew[idx] == c2[0]:\n pnew[idx] = c1[0]\n candidate_indices.remove(idx) # make sure we don't override this value now\n break\n # remove first elements\n del c1[0]\n del c2[0]\n self.set_value(cfg, pnew)\n\n def op3_cross_CX(self, cfg, cfg1, cfg2, d=0):\n \"\"\"\n Implementation of a cyclic crossover.\n\n Repeatedly replaces elements of cfg1 with the element at the same index in\n cfg2. This is done until a cycle is reached and cfg1 is valid again. The\n initial replacement is random.\n\n Saves the result in cfg.\n\n :param cfg: the configuration to be changed\n :param cfg1: the first parent configuration. The \"base\" configuration\n :param cfg2: the second parent configuration. Is \"crossed into\" cfg1\n :param d: unused\n \"\"\"\n p1 = self.get_value(cfg1)\n p2 = self.get_value(cfg2)\n p = p1[:]\n\n s = random.randint(0, len(p1) - 1)\n i = s\n indices = set()\n\n while len(indices) < len(p1): # should never exceed this\n indices.add(i)\n val = p1[i]\n i = p2.index(val)\n # deal with duplicate values\n while i in indices:\n if i == s:\n break\n i = p2[i+1:].index(val) + i + 1\n if i == s:\n break\n\n for j in indices:\n p[j] = p2[j]\n\n self.set_value(cfg, p)\n\n def op3_cross_OX1(self, cfg, cfg1, cfg2, d=0):\n \"\"\"\n Ordered Crossover (Davis 1985)\n\n Exchanges a subpath from cfg2 into cfg1 while maintaining the order of the\n remaining elements in cfg1.\n\n Saves the result in cfg.\n\n :param cfg: the configuration to be changed\n :param cfg1: the first parent configuration. The \"base\" configuration\n :param cfg2: the second parent configuration. Is \"crossed into\" cfg1\n :param d: size of the exchanged subpath\n \"\"\"\n if d == 0:\n d = max(1, int(round(self.size * 0.3))) # default to 1/3 of permutation size\n p1 = self.get_value(cfg1)\n p2 = self.get_value(cfg2)\n c1 = p1[:]\n c2 = p2[:]\n # Randomly find cut points\n r = random.randint(0, len(\n p1) - d) # Todo: treat path as circle i.e. allow cross-boundary cuts\n [c1.remove(i) for i in p2[r:int(r + d)]]\n self.set_value(cfg, c1[:r] + p2[r:r + d] + c1[r:])\n\n def op3_cross_OX3(self, cfg, cfg1, cfg2, d=0):\n \"\"\"\n Ordered crossover variation 3 (Deep 2010)\n\n Same as op3_cross_OX1, except the parents have different cut points for\n their subpaths\n\n :param cfg: the configuration to be changed\n :param cfg1: the first parent configuration. The \"base\" configuration\n :param cfg2: the second parent configuration. Is \"crossed into\" cfg1\n :param d: size of the exchanged subpath\n \"\"\"\n if d == 0:\n d = max(1, int(round(self.size * 0.3))) # default to 1/3 of permutation size\n p1 = self.get_value(cfg1)\n p2 = self.get_value(cfg2)\n c1 = p1[:]\n c2 = p2[:]\n # Randomly find cut points\n # Todo: treat path as circle i.e. allow cross-boundary cuts\n r1 = random.randint(0, len(p1) - d)\n r2 = random.randint(0, len(p1) - d)\n [c1.remove(i) for i in p2[r2:r2 + d]]\n self.set_value(cfg, c1[:r1] + p2[r2:r2 + d] + c1[r1:])\n\n def search_space_size(self):\n return math.factorial(max(1, len(self._items)))\n\n\nclass ScheduleParameter(PermutationParameter):\n def __init__(self, name, items, deps):\n super(ScheduleParameter, self).__init__(name, items)\n self.deps = dict((k, set(v)) for k, v in list(deps.items()))\n log.debug(\"ScheduleParameter(%s, %s, %s)\", repr(name), repr(items),\n repr(deps))\n self._expand_deps()\n\n def _expand_deps(self):\n \"\"\"expand self.deps to include recursive dependencies\"\"\"\n fixed_point = False\n while not fixed_point:\n fixed_point = True\n for k in list(self.deps.keys()):\n oldlen = len(self.deps[k])\n for dep in list(self.deps[k]):\n if dep in self.deps:\n self.deps[k].update(self.deps[dep])\n if oldlen != len(self.deps[k]):\n fixed_point = False\n\n # verify schedule is valid\n items = set(self._items)\n for k, v in list(self.deps.items()):\n if k in v:\n raise Exception(\"ScheduleParameter('%s') cycle: %s depends on itself\" %\n (self.name, k))\n\n if v - items:\n raise Exception(\"ScheduleParameter('%s'): %s is unknown\" %\n (self.name, v - items))\n\n if set(self.deps.keys()) - items:\n raise Exception(\"ScheduleParameter('%s'): %s is unknown\" %\n (self.name, set(self.deps.keys()) - items))\n\n def is_topologically_sorted(self, values):\n used = set()\n for v in values:\n if v in self.deps and self.deps[v].union(used):\n return False\n used.add(v)\n return True\n\n def topologically_sorted_depth_first(self, values):\n \"\"\"faster but not stable enough\"\"\"\n if self.is_topologically_sorted(values):\n return values\n sorted_values = []\n used = set()\n deps = dict((k, sorted(v, key=values.index, reverse=True))\n for k, v in list(self.deps.items()))\n\n def visit(v):\n if v in used:\n return\n if v in deps:\n for dv in deps[v]:\n visit(dv)\n used.add(v)\n sorted_values.append(v)\n\n for v in reversed(values):\n visit(v)\n return list(reversed(sorted_values))\n\n def topologically_sorted(self, values):\n if self.is_topologically_sorted(values):\n return values\n deps = copy.deepcopy(self.deps)\n queue = collections.deque(reversed(values))\n sorted_values = []\n while queue:\n v = queue.popleft()\n if v in deps and deps[v]:\n queue.append(v)\n else:\n for k, d in list(deps.items()):\n d.discard(v)\n if not d:\n del deps[k]\n sorted_values.append(v)\n\n return list(reversed(sorted_values))\n\n def normalize(self, cfg):\n self._set(cfg, self.topologically_sorted(self._get(cfg)))\n\n\nclass SelectorParameter(ComplexParameter):\n def __init__(self, name, choices, max_cutoff,\n order_class=PermutationParameter,\n offset_class=LogIntegerParameter):\n super(SelectorParameter, self).__init__(name)\n self.choices = choices\n self.max_cutoff = max_cutoff\n self.order_param = order_class('{0}/order'.format(name), choices)\n self.offset_params = [\n offset_class('{0}/offsets/{1}'.format(name, i), 0, max_cutoff)\n for i in range(len(choices) - 1)]\n\n def sub_parameters(self):\n return [self.order_param] + self.offset_params\n\n def seed_value(self):\n return {'order': self.order_param.seed_value(),\n 'offsets': [co.seed_value() for co in self.offset_params]}\n\n def op1_randomize(self, config):\n random.choice(self.sub_parameters()).op1_randomize(config)\n\n def selector_iter(self, config):\n \"\"\"\n yield (cutoff, choice) pairs\n cutoff will be None on the first value\n \"\"\"\n order = config[self.name]['order']\n yield (None, order[0])\n cutoff = 0\n for n, offset in enumerate(config[self.name]['offsets']):\n if offset > 0:\n cutoff += offset\n yield cutoff, order[n + 1]\n\n\nclass ParameterArray(ComplexParameter):\n \"\"\"\n Represents an array of Parameters\n \"\"\"\n def __init__(self, name, count, element_type, *args, **kwargs):\n super(ParameterArray, self).__init__(name)\n self.count = count\n\n self.sub_params = [\n element_type('{0}/{1}'.format(name, i), *args[i], **kwargs[i])\n for i in range(count)]\n\n def sub_parameters(self):\n return self.sub_params\n\n def seed_value(self):\n return [p.seed_value() for p in self.sub_params]\n\n def op1_randomize(self, config):\n \"\"\"\n randomly selects a sub-parameter and randomizes it\n\n :param config: the configuration to be changed\n \"\"\"\n random.choice(self.sub_parameters()).op1_randomize(config)\n\n\nclass BooleanParameterArray(ParameterArray):\n \"\"\"\n Represents an array of BooleanParameters - currently unimplimented\n \"\"\"\n def __init__(self, name, count):\n super(BooleanParameterArray, self).__init__(name, count, BooleanParameter)\n\n def op3_swarm(self, cfg, cfg1, cfg2, *args, **kwargs):\n # TODO\n pass\n\n def op3_cross(self, cfg, cfg1, cfg2, *args, **kwargs):\n # TODO\n pass\n\n\nclass IntegerParameterArray(ParameterArray):\n \"\"\"\n Represents an array of IntegerParameters - currently unimplemented\n \"\"\"\n def __init__(self, name, min_values, max_values):\n assert len(min_values) == len(max_values)\n super(IntegerParameterArray, self).__init__(name, len(min_values),\n IntegerParameter,\n min_value=min_values,\n max_value=max_values)\n\n def op3_swarm(self, cfg, cfg1, cfg2, *args, **kwargs):\n # TODO\n pass\n\n def op3_cross(self, cfg, cfg1, cfg2, *args, **kwargs):\n # TODO\n pass\n\n\nclass Array(ComplexParameter):\n \"\"\"\n An interface for parameters representing an array of values.\n \"\"\"\n # TODO: constraints? (upper & lower bound etc)\n def __init__(self, name, size):\n super(Array, self).__init__(name)\n self.size = size\n\n def op3_cross(self, cfg, cfg1, cfg2, strength=0.3, *args, **kwargs):\n \"\"\"\n Crosses two arrays by replacing a random subsection of cfg1 with the\n corresponding subsection of cfg2.The size of the chunk is a fixed fraction\n of the total length, given by the strength\n\n Behaves like a specialized 2-point crossover, where the first cut point is\n random and the second cut is a set distance after.\n\n :param cfg: the configuration to be changed\n :param cfg1: the configuration being inserted into\n :param cfg2: the configuration being inserted\n :param strength: the size of the crossover, as a fraction of total array\n length\n \"\"\"\n d = int(round(self.size * strength))\n if d < 1:\n log.debug('Crossover length too small. Cannot create new solution.')\n if d >= self.size:\n log.debug('Crossover length too big. Cannot create new solution.')\n p1 = self.get_value(cfg1)\n p2 = self.get_value(cfg2)\n r = random.randint(0, len(\n p1) - d) # Todo: treat path as circle i.e. allow cross-boundary cuts\n p = numpy.concatenate([p1[:r], p2[r:r + d], p1[r + d:]])\n self.set_value(cfg, p)\n\n def op3_swarm(self, cfg, cfg1, cfg2, c=1, c1=0.5,\n c2=0.5, velocity=0, strength=0.3, *args, **kwargs):\n \"\"\"\n Replacement for a particle swarm optimization iterative step for arrays.\n Given a target cfg and 2 parent cfgs, probabilistically performs an\n :py:meth:`op3_cross` with one of the 2 parents.\n\n :param cfg: the configuration to be changed. Represents the cfg position\n :param cfg1: a configuration to shift towards. Should be the local best\n position\n :param cfg2: a configuration to shift towards. Should be the global best\n position\n :param c: the probability of not performing a crossover\n :param c1: the probability of performing a crossover with cfg1 (if a\n crossover is performed)\n :param c2: unused\n :param velocity: the old velocity - unused\n :param strength: the strength of the crossover\n \"\"\"\n if random.uniform(0, 1) > c:\n if random.uniform(0, 1) < c1:\n # Select crossover operator\n self.op3_cross(cfg, cfg, cfg1, strength)\n else:\n self.op3_cross(cfg, cfg, cfg2, strength)\n\n def get_value(self, config):\n return self._get(config)\n\n def set_value(self, config, value):\n self._set(config, value)\n\n\nclass BooleanArray(Array):\n \"\"\"\n Represents an array of boolean values which are either 0 or 1\n \"\"\"\n def op3_swarm_parallel(self, cfg, cfg1, cfg2, c=1,\n c1=0.5, c2=0.5, velocities=0):\n \"\"\"\n Simulates a single particle swarm optimization step for each element in the\n array by updating each position and returning an array of new velocities.\n\n The new velocities are given by\n\n .. math:: c*velocity + r1*c1*(cfg1-cfg) + r2*c2*(cfg2-cfg)\n\n where r1 and r2 are random values between 0 and 1. In each iteration, r1 and\n r2 are constant across array elements\n\n The new cfg positions are randomly chosen based on the new velocities\n\n :param cfg: the configuration to be changed. This represents the current\n position\n :param cfg1: a configuration to shift towards. Should be the local best\n position\n :param cfg2: a configuration to shift towards. Should be the global best\n position\n :param c: the weight of the current velocities\n :param c1: weight of cfg1\n :param c2: weight of cfg2\n :param velocities: the current velocities\n :return: a numpy array of new velocities\n \"\"\"\n vs = velocities * c + (self.get_value(cfg1) - self.get_value(\n cfg)) * c1 * random.random() + (self.get_value(\n cfg2) - self.get_value(cfg)) * c2 * random.random()\n # Map velocity to continuous space with sigmoid\n ss = old_div(1, (1 + numpy.exp(-vs)))\n # Decide position randomly\n ps = (ss - numpy.random.rand(1, self.size)) > 0\n self.set_value(cfg, ps)\n return vs\n\n def op1_randomize(self, config):\n \"\"\"\n Set this parameter's value in a configuration randomly\n\n :param config: the configuration to be changed\n \"\"\"\n value = numpy.random.rand(1, self.size) > 0.5\n self._set(config, value)\n\n def seed_value(self):\n return numpy.random.rand(1, self.size) > 0.5\n\n\nclass FloatArray(Array):\n \"\"\"\n Represents an array of float values\n \"\"\"\n def __init__(self, name, size, fmax, fmin):\n super(FloatArray, self).__init__(name, size)\n self.fmax = fmax\n self.fmin = fmin\n\n def op1_randomize(self, config):\n \"\"\"\n Set this parameter's value in a configuration randomly\n\n :param config: the configuration to be changed\n \"\"\"\n value = numpy.random.rand(1, self.size) * (\n self.fmax - self.fmin) + self.fmin\n self._set(config, value)\n\n def seed_value(self):\n value = numpy.random.rand(1, self.size) * (\n self.fmax - self.fmin) + self.fmin\n return value\n\n def op3_swarm_parallel(self, cfg, cfg1, cfg2, c=1,\n c1=0.5, c2=0.5, velocities=0):\n \"\"\"\n Simulates a single particle swarm optimization step for each element in the\n array by updating the each position and returning an array of new velocities\n\n The new velocity is given by\n\n .. math:: c*velocity + r1*c1*(cfg1-cfg) + r2*c2*(cfg2-cfg)\n\n where r1 and r2 are random values between 0 and 1. In each iteration, r1 and\n r2 are constant across array elements\n\n The new cfg positions are randomly chosen based on the new velocities\n\n :param cfg: the configuration to be changed. This represents the current\n position\n :param cfg1: a configuration to shift towards. Should be the local best\n position\n :param cfg2: a configuration to shift towards. Should be the global best\n position\n :param c: the weight of the cfg velocities\n :param c1: weight of cfg1\n :param c2: weight of cfg2\n :param velocities: the cfg velocities\n :return: a numpy array of new velocities\n \"\"\"\n vs = velocities * c + (self.get_value(cfg1) - self.get_value(\n cfg)) * c1 * random.random() + (self.get_value(\n cfg2) - self.get_value(cfg)) * c2 * random.random()\n p = self.get_value(cfg) + vs\n p[p > self.fmax] = self.fmax\n p[p < self.fmin] = self.fmin\n self.set_value(cfg, p)\n return vs\n\n\n##################\n\nclass ManipulatorProxy(object):\n \"\"\"\n wrapper around configuration manipulator and config pair\n \"\"\"\n\n def __init__(self, manipulator, cfg):\n self.cfg = cfg\n self.manipulator = manipulator\n self.params = manipulator.parameters_dict(self.cfg)\n\n def keys(self):\n return list(self.params.keys())\n\n def __getitem__(self, k):\n return ParameterProxy(self.params[k], self.cfg)\n\n\nclass ParameterProxy(object):\n \"\"\"\n wrapper aint parameter and config pair, adds config\n as first argument to all method calls to parameter\n \"\"\"\n\n def __init__(self, param, cfg):\n self.cfg = cfg\n self.param = param\n\n def __getattr__(self, key):\n \"\"\"equivalent of self.param.key(self.cfg, ...)\"\"\"\n member = getattr(self.param, key)\n\n def param_method_proxy(*args, **kwargs):\n return member(self.cfg, *args, **kwargs)\n\n if callable(member):\n return param_method_proxy\n else:\n # we should only hit this for key == 'name'\n return member\n\n\n# Inspection Methods\ndef operators(param, num_parents):\n \"\"\"\n Return a list of operators for the given parameter that take the specified\n number of input configurations\n\n :param param: a Parameter class\n :param num_parents: a String specifying number of inputs required by the operator.\n should be one of '1', '2', '3', '4', or 'n'\n \"\"\"\n ops = []\n methods = inspect.getmembers(param, inspect.ismethod)\n for m in methods:\n name, obj = m\n if is_operator(name, num_parents):\n ops.append(name)\n return ops\n\ndef composable_operators(param, min_num_parents):\n \"\"\"\n Return a list of operators for the given parameter that can be programatically composed\n with a composable technique generating min_num_parents.\n\n Programatically composable operators have no non-cfg arguments\n\n :param param: a Parameter class\n :param min_num_parents: the minimum number of parents passed to the operator\n \"\"\"\n if min_num_parents < 1:\n return []\n\n allowed_num_parents = ['n']\n for i in range(1,5):\n if i > min_num_parents:\n break\n allowed_num_parents.append(str(i))\n\n ops = []\n methods = inspect.getmembers(param, inspect.ismethod)\n for m in methods:\n name, obj = m\n argspec = inspect.getargspec(obj)\n numargs = len(argspec.args) - (len(argspec.defaults) if argspec.defaults else 0)\n for num_parents in allowed_num_parents:\n if is_operator(name, num_parents):\n if num_parents == 'n':\n if numargs == 3: # self, cfg, cfgs\n ops.append(name)\n else:\n if numargs == (1 + int(num_parents)):\n ops.append(name)\n break\n return ops\n\n\ndef is_operator(name, num_parents):\n \"\"\"\n Tells whether a method is an operator taking in the specified number of inputs\n from the method name\n\n :param name: the method name\n :param num_parents: a String specifying number of inputs required by the operator.\n should be one of '1', '2', '3', '4', or 'n'\n \"\"\"\n return ('op' + num_parents + '_') == name[:4]\n\ndef all_operators():\n \"\"\"\n Return a dictionary mapping from parameter names to lists of operator function\n names\n \"\"\"\n ops = {}\n for p in all_params():\n name, obj = p\n all_ops = []\n for num in ['1', '2', '3', '4', 'n']:\n all_ops += operators(obj, num)\n ops[name] = all_ops\n return ops\n\ndef all_params():\n params = inspect.getmembers(sys.modules[__name__], lambda x: inspect.isclass(\n x) and x.__module__ == __name__ and issubclass(x, Parameter))\n return params\n\n"
] |
[
[
"numpy.concatenate",
"numpy.array",
"numpy.random.rand",
"numpy.exp"
]
] |
sharinka0715/AISafety
|
[
"1e210dd448a01069aeaba9fa637b68505ad43332"
] |
[
"EvalBox/Attack/attack_eval.py"
] |
[
"# !/usr/bin/env python\n# coding=UTF-8\n\"\"\"\n@Author: WEN Hao\n@LastEditors: WEN Hao\n@Description:\n@Date: 2021-08-23\n@LastEditTime: 2022-04-16\n\n对抗攻击的类,\n主要基于TextAttack的Attacker类进行实现,同时参考了OpenAttack的类AttackEval\n\n\"\"\"\n\nimport collections\nimport logging\nimport multiprocessing as mp\nimport os\nimport queue\nimport random\nimport traceback\nimport warnings\nfrom typing import Optional, Union, List, NoReturn, Deque, Tuple\n\nimport numpy as np\nimport torch\nimport tqdm\n\nfrom .attack_result import ( # noqa: F401\n AttackResult,\n FailedAttackResult,\n MaximizedAttackResult,\n SkippedAttackResult,\n SuccessfulAttackResult,\n)\nfrom .attack import Attack\nfrom .attack_args import AttackArgs\nfrom ...Datasets.base import NLPDataset\nfrom ...utils.attacked_text import AttackedText\nfrom ...utils.checkpoint import AttackCheckpoint\nfrom ...utils.misc import set_seed\nfrom ...utils.strings import ReprMixin, normalize_language, LANGUAGE\n\n\n__all__ = [\n \"AttackEval\",\n]\n\n\nclass AttackEval(ReprMixin):\n \"\"\"\n Class for running attacks on a dataset with specified parameters.\n\n Example\n -------\n ```python\n from text.EvalBox.Attack.attack_eval import AttackEval\n from text.EvalBox.Attack.attack_args import AttackArgs\n from text.EvalBox.Attack.bae import BAE\n from text.Datasets import SST\n\n aa = AttackArgs()\n ae = AttackEval(BAE(language=\"en\"), SST(), aa)\n ```\n \"\"\"\n\n __name__ = \"AttackEval\"\n\n def __init__(\n self,\n attack: Attack,\n dataset: NLPDataset,\n attack_args: Optional[AttackArgs] = None,\n ) -> NoReturn:\n \"\"\"\n @param {\n attack:\n `Attack` used to actually carry out the attack.\n dataset:\n Dataset to attack.\n attack_args:\n Arguments for attacking the dataset.\n }\n @return: None\n \"\"\"\n self.attack = attack\n self.dataset = dataset\n assert (\n self.attack.language == self.dataset._language\n ), f\"languages of attacker ({self.attack.language}) and dataset ({self.dataset._language}) mismatch!\"\n self.language = self.attack.language\n self.attack_args = attack_args or AttackArgs()\n self.attack_log_manager = AttackArgs.create_loggers_from_args(self.attack_args)\n\n # This is to be set if loading from a checkpoint\n self._checkpoint = None\n\n def _get_worklist(\n self, start: int, end: int, num_examples: int, shuffle: bool\n ) -> Tuple[Deque, Deque]:\n if end - start < num_examples:\n warnings.warn(\n f\"Attempting to attack {num_examples} samples when only {end-start} are available.\"\n )\n candidates = list(range(start, end))\n if shuffle:\n random.shuffle(candidates)\n worklist = collections.deque(candidates[:num_examples])\n candidates = collections.deque(candidates[num_examples:])\n assert (len(worklist) + len(candidates)) == (end - start)\n return worklist, candidates\n\n def _attack(\n self, time_out: Optional[float] = None, ignore_errors: bool = False\n ) -> NoReturn:\n \"\"\"Internal method that carries out attack.\n\n No parallel processing is involved.\n\n Args:\n time_out: Timeout in minutes.\n ignore_errors: Whether to ignore errors.\n\n \"\"\"\n if torch.cuda.is_available():\n self.attack.cuda_if_possible_()\n\n if self._checkpoint:\n num_remaining_attacks = self._checkpoint.num_remaining_attacks\n worklist = self._checkpoint.worklist\n worklist_candidates = self._checkpoint.worklist_candidates\n print(\n f\"Recovered from checkpoint previously saved at {self._checkpoint.datetime}.\"\n )\n else:\n if self.attack_args.num_successful_examples:\n num_remaining_attacks = self.attack_args.num_successful_examples\n # We make `worklist` deque (linked-list) for easy pop and append.\n # Candidates are other samples we can attack if we need more samples.\n worklist, worklist_candidates = self._get_worklist(\n self.attack_args.num_examples_offset,\n len(self.dataset),\n self.attack_args.num_successful_examples,\n self.attack_args.shuffle,\n )\n else:\n num_remaining_attacks = self.attack_args.num_examples\n # We make `worklist` deque (linked-list) for easy pop and append.\n # Candidates are other samples we can attack if we need more samples.\n worklist, worklist_candidates = self._get_worklist(\n self.attack_args.num_examples_offset,\n len(self.dataset),\n self.attack_args.num_examples,\n self.attack_args.shuffle,\n )\n\n if not self.attack_args.silent:\n print(self.attack, \"\\n\")\n\n pbar = tqdm.tqdm(total=num_remaining_attacks, smoothing=0, dynamic_ncols=True)\n if self._checkpoint:\n num_results = self._checkpoint.results_count\n num_failures = self._checkpoint.num_failed_attacks\n num_skipped = self._checkpoint.num_skipped_attacks\n num_successes = self._checkpoint.num_successful_attacks\n else:\n num_results = 0\n num_failures = 0\n num_skipped = 0\n num_successes = 0\n\n sample_exhaustion_warned = False\n while worklist:\n idx = worklist.popleft()\n try:\n example, ground_truth_output = self.dataset[idx]\n except IndexError:\n continue\n example = AttackedText(self.language, example)\n if self.dataset.label_names is not None:\n example.attack_attrs[\"label_names\"] = self.dataset.label_names\n try:\n result = self.attack.attack(\n example,\n ground_truth_output,\n time_out=time_out,\n ignore_errors=ignore_errors,\n )\n except Exception as e:\n raise e\n if (\n isinstance(result, SkippedAttackResult) and self.attack_args.attack_n\n ) or (\n not isinstance(result, SuccessfulAttackResult)\n and self.attack_args.num_successful_examples\n ):\n if worklist_candidates:\n next_sample = worklist_candidates.popleft()\n worklist.append(next_sample)\n else:\n if not sample_exhaustion_warned:\n warnings.warn(\"Ran out of samples to attack!\")\n sample_exhaustion_warned = True\n else:\n pbar.update(1)\n\n self.attack_log_manager.log_result(result, self)\n if not self.attack_args.disable_stdout and not self.attack_args.silent:\n print(\"\\n\")\n num_results += 1\n\n if isinstance(result, SkippedAttackResult):\n num_skipped += 1\n if isinstance(result, (SuccessfulAttackResult, MaximizedAttackResult)):\n num_successes += 1\n if isinstance(result, FailedAttackResult):\n num_failures += 1\n pbar.set_description(\n f\"[Succeeded / Failed / Skipped / Total] {num_successes} / {num_failures} / {num_skipped} / {num_results}\"\n )\n\n if (\n self.attack_args.checkpoint_interval\n and len(self.attack_log_manager.results)\n % self.attack_args.checkpoint_interval\n == 0\n ):\n new_checkpoint = AttackCheckpoint(\n self.attack_args,\n self.attack_log_manager,\n worklist,\n worklist_candidates,\n )\n new_checkpoint.save()\n self.attack_log_manager.flush()\n\n pbar.close()\n # Enable summary stdout\n if not self.attack_args.silent and self.attack_args.disable_stdout:\n self.attack_log_manager.enable_stdout()\n if self.attack_args.enable_advance_metrics:\n self.attack_log_manager.enable_advance_metrics = True\n self.attack_log_manager.log_summary()\n self.attack_log_manager.flush()\n\n def _attack_parallel(\n self, time_out: Optional[float] = None, ignore_errors: bool = False\n ) -> NoReturn:\n \"\"\"\n\n Args:\n time_out: Timeout in minutes.\n ignore_errors: If True, errors will be ignored.\n\n \"\"\"\n pytorch_multiprocessing_workaround()\n\n if time_out is None:\n time_out = np.iinfo(np.int32).max\n\n if self._checkpoint:\n num_remaining_attacks = self._checkpoint.num_remaining_attacks\n worklist = self._checkpoint.worklist\n worklist_candidates = self._checkpoint.worklist_candidates\n print(\n f\"Recovered from checkpoint previously saved at {self._checkpoint.datetime}.\"\n )\n else:\n if self.attack_args.num_successful_examples:\n num_remaining_attacks = self.attack_args.num_successful_examples\n # We make `worklist` deque (linked-list) for easy pop and append.\n # Candidates are other samples we can attack if we need more samples.\n worklist, worklist_candidates = self._get_worklist(\n self.attack_args.num_examples_offset,\n len(self.dataset),\n self.attack_args.num_successful_examples,\n self.attack_args.shuffle,\n )\n else:\n num_remaining_attacks = self.attack_args.num_examples\n # We make `worklist` deque (linked-list) for easy pop and append.\n # Candidates are other samples we can attack if we need more samples.\n worklist, worklist_candidates = self._get_worklist(\n self.attack_args.num_examples_offset,\n len(self.dataset),\n self.attack_args.num_examples,\n self.attack_args.shuffle,\n )\n\n in_queue = torch.multiprocessing.Queue()\n out_queue = torch.multiprocessing.Queue()\n for i in worklist:\n try:\n example, ground_truth_output = self.dataset[i]\n example = AttackedText(self.language, example)\n if self.dataset.label_names is not None:\n example.attack_attrs[\"label_names\"] = self.dataset.label_names\n in_queue.put((i, example, ground_truth_output))\n except IndexError:\n raise IndexError(\n f\"Tried to access element at {i} in dataset of size {len(self.dataset)}.\"\n )\n\n # We reserve the first GPU for coordinating workers.\n num_gpus = torch.cuda.device_count()\n num_workers = self.attack_args.num_workers_per_device * num_gpus\n print(f\"Running {num_workers} worker(s) on {num_gpus} GPU(s).\")\n\n # Lock for synchronization\n lock = mp.Lock()\n\n # We move Attacker (and its components) to CPU b/c we don't want models using wrong GPU in worker processes.\n self.attack.cpu_()\n torch.cuda.empty_cache()\n\n # Start workers.\n worker_pool = torch.multiprocessing.Pool(\n num_workers,\n attack_from_queue,\n (\n self.attack,\n self.attack_args,\n num_gpus,\n mp.Value(\"i\", 1, lock=False),\n lock,\n in_queue,\n out_queue,\n ),\n )\n\n # Log results asynchronously and update progress bar.\n if self._checkpoint:\n num_results = self._checkpoint.results_count\n num_failures = self._checkpoint.num_failed_attacks\n num_skipped = self._checkpoint.num_skipped_attacks\n num_successes = self._checkpoint.num_successful_attacks\n else:\n num_results = 0\n num_failures = 0\n num_skipped = 0\n num_successes = 0\n\n print(f\"Worklist size: {len(worklist)}\")\n print(f\"Worklist candidate size: {len(worklist_candidates)}\")\n\n sample_exhaustion_warned = False\n pbar = tqdm.tqdm(total=num_remaining_attacks, smoothing=0, dynamic_ncols=True)\n while worklist:\n idx, result = out_queue.get(block=True) # TODO: add timeout\n worklist.remove(idx)\n\n if isinstance(result, tuple) and isinstance(result[0], Exception):\n # TODO: Handle errors if ignore_errors is True.\n print(f'Exception encountered for input \"{self.dataset[idx][0]}\".')\n error_trace = result[1]\n print(error_trace)\n in_queue.close()\n in_queue.join_thread()\n out_queue.close()\n out_queue.join_thread()\n worker_pool.terminate()\n worker_pool.join()\n return\n elif (\n isinstance(result, SkippedAttackResult) and self.attack_args.attack_n\n ) or (\n not isinstance(result, SuccessfulAttackResult)\n and self.attack_args.num_successful_examples\n ):\n if worklist_candidates:\n next_sample = worklist_candidates.popleft()\n example, ground_truth_output = self.dataset[next_sample]\n example = AttackedText(self.language, example)\n if self.dataset.label_names is not None:\n example.attack_attrs[\"label_names\"] = self.dataset.label_names\n worklist.append(next_sample)\n in_queue.put((next_sample, example, ground_truth_output))\n else:\n if not sample_exhaustion_warned:\n warnings.warn(\"Ran out of samples to attack!\")\n sample_exhaustion_warned = True\n else:\n pbar.update()\n\n self.attack_log_manager.log_result(result, self)\n num_results += 1\n\n if isinstance(result, SkippedAttackResult):\n num_skipped += 1\n if isinstance(result, (SuccessfulAttackResult, MaximizedAttackResult)):\n num_successes += 1\n if isinstance(result, FailedAttackResult):\n num_failures += 1\n pbar.set_description(\n f\"[Succeeded / Failed / Skipped / Total] {num_successes} / {num_failures} / {num_skipped} / {num_results}\"\n )\n\n if (\n self.attack_args.checkpoint_interval\n and len(self.attack_log_manager.results)\n % self.attack_args.checkpoint_interval\n == 0\n ):\n new_checkpoint = AttackCheckpoint(\n self.attack_args,\n self.attack_log_manager,\n worklist,\n worklist_candidates,\n )\n new_checkpoint.save()\n self.attack_log_manager.flush()\n\n # Send sentinel values to worker processes\n for _ in range(num_workers):\n in_queue.put((\"END\", \"END\", \"END\"))\n worker_pool.close()\n worker_pool.join()\n\n pbar.close()\n # Enable summary stdout.\n if not self.attack_args.silent and self.attack_args.disable_stdout:\n self.attack_log_manager.enable_stdout()\n if self.attack_args.enable_advance_metrics:\n self.attack_log_manager.enable_advance_metrics = True\n self.attack_log_manager.log_summary()\n self.attack_log_manager.flush()\n\n def attack_dataset(\n self, time_out: Optional[float] = None, ignore_errors: bool = False\n ) -> List[AttackResult]:\n \"\"\"Attack the dataset.\n\n Args:\n time_out: Timeout in minutes.\n ignore_errors: Whether to ignore errors.\n\n Returns:\n List of `AttackResult` obtained after attacking the given dataset.\n \"\"\"\n # if self.attack_args.silent:\n # logger.setLevel(logging.ERROR)\n\n if self.attack_args.query_budget:\n self.attack.goal_function.query_budget = self.attack_args.query_budget\n\n if not self.attack_log_manager:\n self.attack_log_manager = AttackArgs.create_loggers_from_args(\n self.attack_args\n )\n\n set_seed(self.attack_args.random_seed)\n if self.dataset.shuffled and self.attack_args.checkpoint_interval:\n # Not allowed b/c we cannot recover order of shuffled data\n raise ValueError(\n \"Cannot use `--checkpoint-interval` with dataset that has been internally shuffled.\"\n )\n\n self.attack_args.num_examples = (\n len(self.dataset)\n if self.attack_args.num_examples == -1\n else self.attack_args.num_examples\n )\n if self.attack_args.parallel:\n if torch.cuda.device_count() == 0:\n raise Exception(\n \"Found no GPU on your system. To run attacks in parallel, GPU is required.\"\n )\n self._attack_parallel(time_out=time_out, ignore_errors=ignore_errors)\n else:\n self._attack(time_out=time_out, ignore_errors=ignore_errors)\n\n # if self.attack_args.silent:\n # logger.setLevel(logging.INFO)\n\n return self.attack_log_manager.results\n\n def update_attack_args(self, **kwargs) -> NoReturn:\n \"\"\"To update any attack args, pass the new argument as keyword argument to this function.\n\n Examples::\n\n >>> attacker = #some instance of Attacker\n >>> # To switch to parallel mode and increase checkpoint interval from 100 to 500\n >>> attacker.update_attack_args(parallel=True, checkpoint_interval=500)\n \"\"\"\n for k in kwargs:\n if hasattr(self.attack_args, k):\n self.attack_args.k = kwargs[k]\n else:\n raise ValueError(f\"`AttackArgs` does not have field {k}.\")\n\n @classmethod\n def from_checkpoint(\n cls,\n attack: Attack,\n dataset: NLPDataset,\n checkpoint: Union[str, AttackCheckpoint],\n ) -> \"AttackEval\":\n \"\"\"Resume attacking from a saved checkpoint. Attacker and dataset must\n be recovered by the user again, while attack args are loaded from the\n saved checkpoint.\n\n Args:\n attack:\n Attack object for carrying out the attack.\n dataset:\n Dataset to attack.\n checkpoint:\n Path of saved checkpoint or the actual saved checkpoint.\n \"\"\"\n if isinstance(checkpoint, str):\n checkpoint = AttackCheckpoint.load(checkpoint)\n attack_eval = cls(attack, dataset, checkpoint.attack_args)\n attack_eval.attack_log_manager = checkpoint.attack_log_manager\n attack_eval._checkpoint = checkpoint\n return attack_eval\n\n @staticmethod\n def attack_interactive(attack: Attack, language: Union[str, LANGUAGE]) -> NoReturn:\n print(attack, \"\\n\")\n\n print(\"Running in interactive mode\")\n print(\"----------------------------\")\n\n while True:\n print(\n f\"Enter a sentence in {normalize_language(language).value} to attack or `q` to quit:\"\n )\n text = input()\n\n if text == \"q\":\n break\n\n if not text:\n continue\n\n print(\"Attacking...\")\n\n example = AttackedText(language, text)\n output = attack.goal_function.get_output(example)\n result = attack.attack(example, output)\n print(result.__str__(color_method=\"ansi\") + \"\\n\")\n\n\n#\n# Helper Methods for multiprocess attacks\n#\ndef pytorch_multiprocessing_workaround() -> NoReturn:\n # This is a fix for a known bug\n try:\n torch.multiprocessing.set_start_method(\"spawn\", force=True)\n torch.multiprocessing.set_sharing_strategy(\"file_system\")\n except RuntimeError:\n pass\n\n\ndef set_env_variables(gpu_id: Union[str, int]) -> NoReturn:\n # Disable tensorflow logs, except in the case of an error.\n if \"TF_CPP_MIN_LOG_LEVEL\" not in os.environ:\n os.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\"\n\n # Set sharing strategy to file_system to avoid file descriptor leaks\n torch.multiprocessing.set_sharing_strategy(\"file_system\")\n\n # Only use one GPU, if we have one.\n # For Tensorflow\n # TODO: Using USE with `--parallel` raises similar issue as https://github.com/tensorflow/tensorflow/issues/38518#\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(gpu_id)\n # For PyTorch\n torch.cuda.set_device(gpu_id)\n\n # Fix TensorFlow GPU memory growth\n try:\n import tensorflow as tf\n\n gpus = tf.config.experimental.list_physical_devices(\"GPU\")\n if gpus:\n try:\n # Currently, memory growth needs to be the same across GPUs\n gpu = gpus[gpu_id]\n tf.config.experimental.set_visible_devices(gpu, \"GPU\")\n tf.config.experimental.set_memory_growth(gpu, True)\n except RuntimeError as e:\n print(e)\n except ModuleNotFoundError:\n pass\n\n\ndef attack_from_queue(\n attack: Attack,\n attack_args: AttackArgs,\n num_gpus: int,\n first_to_start: mp.Value,\n lock: mp.Lock,\n in_queue: Deque,\n out_queue: Deque,\n) -> NoReturn:\n \"\"\" \"\"\"\n assert isinstance(\n attack, Attack\n ), f\"`attack` must be of type `Attack`, but got type `{type(attack).__name__}`.\"\n\n gpu_id = (torch.multiprocessing.current_process()._identity[0] - 1) % num_gpus\n set_env_variables(gpu_id)\n set_seed(attack_args.random_seed)\n if torch.multiprocessing.current_process()._identity[0] > 1:\n logging.disable()\n\n attack.cuda_if_possible_()\n\n # Simple non-synchronized check to see if it's the first process to reach this point.\n # This let us avoid waiting for lock.\n if bool(first_to_start.value):\n # If it's first process to reach this step, we first try to acquire the lock to update the value.\n with lock:\n # Because another process could have changed `first_to_start=False` while we wait, we check again.\n if bool(first_to_start.value):\n first_to_start.value = 0\n if not attack_args.silent:\n print(attack, \"\\n\")\n\n while True:\n try:\n i, example, ground_truth_output = in_queue.get(timeout=5)\n if i == \"END\" and example == \"END\" and ground_truth_output == \"END\":\n # End process when sentinel value is received\n break\n else:\n result = attack.attack(example, ground_truth_output)\n out_queue.put((i, result))\n except Exception as e:\n if isinstance(e, queue.Empty):\n continue\n else:\n out_queue.put((i, (e, traceback.format_exc())))\n"
] |
[
[
"torch.multiprocessing.set_start_method",
"torch.multiprocessing.current_process",
"torch.multiprocessing.Queue",
"torch.cuda.set_device",
"tensorflow.config.experimental.set_memory_growth",
"tensorflow.config.experimental.list_physical_devices",
"torch.cuda.empty_cache",
"numpy.iinfo",
"torch.cuda.is_available",
"torch.cuda.device_count",
"tensorflow.config.experimental.set_visible_devices",
"torch.multiprocessing.set_sharing_strategy"
]
] |
JanzenLiu/Elastic-and-Parallel-Rec-System-pipeline
|
[
"3a7be2ffbe423d6421d722141d6ae882422f5c30"
] |
[
"offline/embedding/embedding.py"
] |
[
"from os.path import *\nfrom pyspark.sql import SparkSession, Row\nfrom pyspark import SparkConf\nfrom pyspark.sql.functions import *\nfrom pyspark.sql.types import *\nfrom pyspark.mllib.feature import Word2Vec, Word2VecModel\nfrom pyspark.ml.feature import BucketedRandomProjectionLSH\nfrom pyspark.ml.linalg import Vectors\nimport redis\nimport logging\nimport random\nimport numpy as np\nimport pandas as pd\nfrom typing import List\n\nparams = ()\n\n\nclass Embedding:\n def __init__(self):\n self.redisEndpoint = \"localhost\"\n self.redisPort = 6379\n\n def process_item_sequence(self, spark_session: SparkSession, raw_sample_data_path: str):\n root_dir = dirname(dirname(dirname(abspath(__file__))))\n rating_resource_path = join(root_dir, \"resources\", raw_sample_data_path)\n\n rating_samples = spark_session.read.format(\"csv\").option(\"header\", \"true\").load(rating_resource_path)\n\n schema = StructType([\n StructField(\"userId\", StringType()),\n # StructField(\"timestamp\", StringType()),\n # StructField(\"rating\", StringType()),\n StructField(\"movieIds\", ArrayType(StringType()))\n ])\n\n @pandas_udf(schema, functionType=PandasUDFType.GROUPED_MAP)\n def udf_sort(df):\n result = df.drop(columns=[\"rating\"])\n result = result.groupby(by=\"userId\").apply(lambda x: x.sort_values([\"timestamp\"]))\n result = result.drop(columns=[\"timestamp\"]).reset_index(drop=True)\n result = result.groupby(by=\"userId\").agg(lambda x: tuple(x)).applymap(list).reset_index()\n result = result.rename(columns={\"movieId\": \"movieIds\"})\n return result\n\n rating_samples.show(10)\n user_sequence = rating_samples. \\\n where(\"rating >= 3.5\"). \\\n groupBy(\"userId\"). \\\n apply(udf_sort). \\\n withColumn(\"movieIdStr\", array_join(col(\"movieIds\"), \" \"))\n\n user_sequence.select(\"userId\", \"movieIdStr\").show(10, truncate=False)\n result = user_sequence.select(\"movieIdStr\").rdd.map(lambda x: x[\"movieIdStr\"].split(\" \"))\n\n return result\n\n def embedding_lsh(self, spark_session: SparkSession, movie_emb_map):\n movie_emb_seq = []\n for movieId, vector in movie_emb_map.items():\n movie_emb_seq.append((movieId, Vectors.dense(vector)))\n movie_emb_df = spark.createDataFrame(movie_emb_seq).toDF(\"movieId\", \"emb\")\n\n bucket_projection_lsh = BucketedRandomProjectionLSH().setBucketLength(0.1).setNumHashTables(3).setInputCol(\"emb\").\\\n setOutputCol(\"bucketId\")\n bucket_model = bucket_projection_lsh.fit(movie_emb_df)\n\n emb_bucket_result = bucket_model.transform(movie_emb_df)\n\n print(\"movieId, emb, bucketId schema:\")\n emb_bucket_result.printSchema()\n print(\"movieId, emb, bucketId data result:\")\n emb_bucket_result.show(10, truncate=False)\n\n print(\"Approximately searching for 5 nearest neighbors of the sample embedding:\")\n sampleEmb = Vectors.dense(0.795, 0.583, 1.120, 0.850, 0.174, -0.839, -0.0633, 0.249, 0.673, -0.237)\n bucket_model.approxNearestNeighbors(movie_emb_df, sampleEmb, 5).show(truncate=False)\n\n def train_item_to_vec(self, spark_session: SparkSession, samples, emb_length: int, emb_output_file_name: str,\n save_to_redis: bool, redis_key_prefix: str):\n word2vec = Word2Vec().setVectorSize(emb_length).setWindowSize(5).setNumIterations(10)\n model = word2vec.fit(samples)\n synonyms = model.findSynonyms(\"158\", 20)\n for synonym, cosine_sim in synonyms:\n print(synonym, cosine_sim)\n\n root_dir = dirname(dirname(dirname(abspath(__file__))))\n rating_resource_path = join(root_dir, \"resources\", \"webroot/modeldata/\")\n\n file = open(join(rating_resource_path, emb_output_file_name), \"w\")\n\n for movieId, vector in model.getVectors().items():\n file.write(movieId + \":\" + \" \".join([str(num) for num in vector]) + \"\\n\")\n\n if save_to_redis:\n redis_client = redis.Redis(host=self.redisEndpoint, port=self.redisPort)\n for movieId, vector in model.getVectors().items():\n redis_client.set(redis_key_prefix + \":\" + movieId, \" \".join([str(num) for num in vector]), ex=60*60*24)\n redis_client.close()\n self.embedding_lsh(spark_session, model.getVectors())\n return model\n\n def generate_transition_matrix(self, samples):\n def flat_func(sample):\n pair_seq = []\n previous_item = None\n for element in sample:\n if previous_item is not None:\n pair_seq.append((previous_item, element))\n previous_item = element\n return pair_seq\n\n pair_samples = samples.flatMap(flat_func)\n\n pair_count_map = pair_samples.countByValue()\n pair_total_count = 0\n transition_count_matrix = dict()\n item_count_map = dict()\n\n for pair_items, count in pair_count_map.items():\n if pair_items[0] not in transition_count_matrix:\n transition_count_matrix[pair_items[0]] = dict()\n transition_count_matrix[pair_items[0]][pair_items[1]] = count\n item_count_map[pair_items[0]] = item_count_map.get(pair_items[0], 0) + count\n pair_total_count = pair_total_count + count\n\n transition_matrix = dict()\n item_distribution = dict()\n\n for item_a_id, transition_map in transition_count_matrix.items():\n transition_matrix[item_a_id] = dict()\n for item_b_id, transition_count in transition_map.items():\n transition_matrix[item_a_id][item_b_id] = float(transition_count) / item_count_map[item_a_id]\n\n for item_id, item_count in item_count_map.items():\n item_distribution[item_id] = float(item_count) / pair_total_count\n\n return transition_matrix, item_distribution\n\n def one_random_walk(self, transition_matrix, item_distribution, sample_length: int):\n sample = []\n random_double = random.random()\n first_item = \"\"\n accumulate_prob = 0\n for item, prob in item_distribution.items():\n accumulate_prob += prob\n if accumulate_prob >= random_double:\n first_item = item\n break\n sample.append(first_item)\n cur_element = first_item\n for _ in range(sample_length):\n if cur_element not in item_distribution or cur_element not in transition_matrix:\n break\n prob_distribution = transition_matrix[cur_element]\n random_double = random.random()\n for item, prob in prob_distribution.items():\n if random_double >= prob:\n cur_element = item\n break\n sample.append(cur_element)\n return sample\n\n def random_walk(self, transition_matrix, item_distribution, sample_count: int, sample_length: int):\n samples = []\n for _ in range(sample_count):\n samples.append(self.one_random_walk(transition_matrix, item_distribution, sample_length))\n return samples\n\n def graph_emb(self, samples, spark_session: SparkSession, emb_length: int, emb_output_file_name: str,\n save_to_redis: bool, redis_key_prefix: str):\n transition_matrix, item_distribution = self.generate_transition_matrix(samples)\n\n print(len(transition_matrix))\n print(len(item_distribution))\n\n sampleCount = 20000\n sampleLength = 10\n\n new_samples = self.random_walk(transition_matrix, item_distribution, sampleCount, sampleLength)\n rdd_samples = spark_session.sparkContext.parallelize(new_samples)\n\n return self.train_item_to_vec(spark_session, rdd_samples, emb_length, emb_output_file_name, save_to_redis,\n redis_key_prefix)\n\n def generate_user_emb(self, spark_session: SparkSession, raw_sample_data_path: str, word2vec_model: Word2VecModel,\n emb_length: int, emb_output_file_name: str, save_to_redis: bool, redis_key_prefix: str):\n root_dir = dirname(dirname(dirname(abspath(__file__))))\n rating_resource_path = join(root_dir, \"resources\", raw_sample_data_path)\n\n rating_samples = spark_session.read.format(\"csv\").option(\"header\", \"true\").load(rating_resource_path)\n\n rating_samples.show(10, truncate=False)\n\n user_embeddings_dict = dict()\n movie_keys = word2vec_model.getVectors().keys()\n\n for row in rating_samples.collect():\n user_id = row[\"userId\"]\n movie_id = row[\"movieId\"]\n if movie_id not in movie_keys:\n movie_emb = np.zeros(emb_length)\n else:\n movie_emb = word2vec_model.transform(movie_id).toArray()\n if user_id in user_embeddings_dict:\n user_embeddings_dict[user_id] += np.copy(movie_emb)\n else:\n user_embeddings_dict[user_id] = np.copy(movie_emb)\n\n root_dir = dirname(dirname(dirname(abspath(__file__))))\n rating_resource_path = join(root_dir, \"resources\", \"webroot/modeldata/\")\n\n file = open(join(rating_resource_path, emb_output_file_name), \"w\")\n\n for user_id, user_emb in user_embeddings_dict.items():\n file.write(user_id + \":\" + \" \".join([str(num) for num in user_emb]) + \"\\n\")\n\n if save_to_redis:\n redis_client = redis.Redis(host=self.redisEndpoint, port=self.redisPort)\n for user_id, user_emb in user_embeddings_dict.items():\n redis_client.set(redis_key_prefix + \":\" + user_id, \" \".join([str(num) for num in user_emb]), ex=60*60*24)\n redis_client.close()\n\n\nif __name__ == \"__main__\":\n logging.getLogger(\"org\").setLevel(logging.ERROR)\n conf = SparkConf().setMaster(\"local\").setAppName(\"ctrModel\").set(\"spark.submit.deployMode\", \"client\")\n\n spark = SparkSession.builder.config(conf=conf).getOrCreate()\n\n raw_sample_data_path = \"webroot/sampledata/ratings.csv\"\n\n emb_length = 10\n\n embedding = Embedding()\n\n samples = embedding.process_item_sequence(spark, raw_sample_data_path)\n\n model = embedding.train_item_to_vec(spark, samples, emb_length, \"item2vecEmb.csv\", False, \"i2vEmb\")\n # embedding.graph_emb(samples, spark, emb_length, \"itemGraphEmb.csv\", True, \"graphEmb\")\n # embedding.generate_user_emb(spark, raw_sample_data_path, model, emb_length, \"userEmb.csv\", False, \"uEmb\")\n"
] |
[
[
"numpy.copy",
"numpy.zeros"
]
] |
laserson/numba
|
[
"35546517b27764a9120f6dfcd82eba7f4dd858cb"
] |
[
"numba/cuda/tests/cudapy/test_multigpu.py"
] |
[
"from numba import cuda\nimport numpy as np\nfrom numba import unittest_support as unittest\nimport threading\n\n\nclass TestMultiGPUContext(unittest.TestCase):\n def test_multigpu_context(self):\n @cuda.jit(\"void(float64[:], float64[:])\")\n def copy_plus_1(inp, out):\n i = cuda.grid(1)\n if i < out.size:\n out[i] = inp[i] + 1\n\n def check(inp, out):\n np.testing.assert_equal(inp + 1, out)\n\n\n N = 32\n A = np.arange(N, dtype=np.float64)\n B = np.arange(N, dtype=np.float64)\n\n with cuda.gpus[0]:\n copy_plus_1[1, N](A, B)\n\n print(A, B)\n check(A, B)\n\n copy_plus_1[1, N](A, B)\n print(A, B)\n check(A, B)\n\n print(len(cuda.gpus))\n\n if len(cuda.gpus) >= 2:\n with cuda.gpus[0]:\n A0 = np.arange(N, dtype=np.float64)\n B0 = np.arange(N, dtype=np.float64)\n copy_plus_1[1, N](A0, B0)\n\n with cuda.gpus[1]:\n A1 = np.arange(N, dtype=np.float64)\n B1 = np.arange(N, dtype=np.float64)\n copy_plus_1[1, N](A1, B1)\n\n print(A0, A1)\n print(B0, B1)\n\n check(A0, B0)\n check(A1, B1)\n\n A = np.arange(N, dtype=np.float64)\n B = np.arange(N, dtype=np.float64)\n copy_plus_1[1, N](A, B)\n check(A, B)\n\n def test_multithreaded(self):\n def work(gpu, dA, results, ridx):\n try:\n with gpu:\n arr = dA.copy_to_host()\n\n except BaseException as e:\n results[ridx] = e\n\n else:\n results[ridx] = np.all(arr == np.arange(10))\n\n\n dA = cuda.to_device(np.arange(10))\n\n nthreads = 10\n results = [None] * nthreads\n threads = [threading.Thread(target=work, args=(cuda.gpus.current,\n dA, results, i))\n for i in range(nthreads)]\n for th in threads:\n th.start()\n\n for th in threads:\n th.join()\n\n for r in results:\n if isinstance(r, BaseException):\n raise r\n else:\n self.assertTrue(r)\n\n\nif __name__ == '__main__':\n unittest.main()\n"
] |
[
[
"numpy.arange",
"numpy.testing.assert_equal"
]
] |
YuyangXueEd/MRI_Recon_Tutorial
|
[
"5c235e0831e30528611f492668987caa0f183f80"
] |
[
"Models/unet/pretrained.py"
] |
[
"import argparse\nimport time\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom tqdm import tqdm\n\nimport numpy as np\nimport requests\nimport torch\n\nimport fastmri\nimport fastmri.data.transforms as T\nfrom fastmri.data import SliceDataset\nfrom unet import Unet\n\nUNET_FOLDER = \"https://dl.fbaipublicfiles.com/fastMRI/trained_models/unet/\"\nMODEL_FNAMES = {\n \"unet_knee_sc\": \"knee_sc_leaderboard_state_dict.pt\",\n # \"unet_knee_mc\": \"knee_mc_leaderboard_state_dict.pt\",\n # \"unet_brain_mc\": \"brain_leaderboard_state_dict.pt\",\n}\n\n\ndef download_model(url, fname):\n response = requests.get(url, timeout=10, stream=True)\n # 1MB chunks\n chunk_size = 1 * 1024 * 1024\n total_size_in_bytes = int(response.headers.get(\"content-length\", 0))\n\n progress_bar = tqdm(\n desc=\"Downloading state_dict\",\n total=total_size_in_bytes,\n unit=\"iB\",\n unit_scale=True\n )\n\n with open(fname, \"wb\") as fh:\n for chunk in response.iter_content(chunk_size):\n progress_bar.update(len(chunk))\n fh.write(chunk)\n\n progress_bar.close()\n\n\ndef run_unet_model(batch, model, device):\n image, _, mean, std, fname, slice_num, _ = batch\n output = model(image.to(device).unsqueeze(1)).squeeze(1).cpu()\n\n mean = mean.unsqueeze(1).unsqueeze(2)\n std = std.unsqueeze(1).unsqueeze(2)\n output = (output * std + mean).cpu()\n\n return output, int(slice_num[0]), fname[0]\n\n\ndef run_inference(challenge, state_dict_file, data_path, output_path, device):\n \"\"\"\n\n :param challenge: Model to run\n :param state_dict_file: Device to run\n :param data_path: Path to subsampled\n :param output_path: data Path for saving reconstructions\n :param device: Path to saved state_dict (will download if not provided)\n :return:\n \"\"\"\n\n model = Unet(in_c=1, out_c=1, feats=256, num_pool_layers=4, drop_prob=0.0)\n\n if state_dict_file is None:\n if not Path(MODEL_FNAMES[challenge]).exists():\n download_model(UNET_FOLDER + MODEL_FNAMES[challenge], MODEL_FNAMES[challenge])\n\n state_dict_file = MODEL_FNAMES[challenge]\n\n model.load_state_dict(torch.load(state_dict_file))\n model = model.eval()\n\n # dataloader setup\n\n if \"_sc\" in challenge:\n dataset = SliceDataset(\n root=data_path,\n transform=T.UnetDataTransform(which_challenge=\"singlecoil\"),\n challenge=\"singlecoil\"\n )\n else:\n dataset = SliceDataset(\n root=data_path,\n transform=T.UnetDataTransform(which_challenge=\"multicoil\"),\n challenge=\"multicoil\",\n )\n\n dataloader = torch.utils.data.DataLoader(dataset, num_workers=4)\n\n start_time = time.perf_counter()\n outputs = defaultdict(list)\n model = model.to(device)\n\n for batch in tqdm(dataloader, desc=\"Running inference\"):\n with torch.no_grad():\n output, slice_num, fname = run_unet_model(batch, model, device)\n\n outputs[fname].append((slice_num, output))\n\n for fname in outputs:\n outputs[fname] = np.stack([out for _, out in sorted(outputs[fname])])\n\n \n #fastmri.save_reconstructions(outputs, output_path / \"reconstructions\")\n\n end_time = time.perf_counter()\n\n print(f\"Elapsed time for {len(dataloader)} slices: {end_time - start_time}\")\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n\n parser.add_argument(\"--challenge\",\n default=\"unet_knee_sc\",\n choices=(\n \"unet_knee_sc\",\n \"unet_knee_mc\",\n \"unet_brain_mc\",\n ),\n type=str,\n help=\"Model to run\\n\")\n\n parser.add_argument(\"--device\",\n default=\"cuda\",\n type=str,\n help=\"Device to run\\n\")\n\n parser.add_argument(\"--state_dict_file\",\n default=None,\n type=Path,\n help=\"Path to saved state_dict (will download if not provided)\\n\")\n\n parser.add_argument(\"--data_path\",\n type=Path,\n required=True,\n help=\"Path to subsampled data\\n\")\n\n parser.add_argument(\"--output_path\",\n type=Path,\n required=True,\n help=\"Path for saving reconstructions\\n\")\n\n args = parser.parse_args()\n\n run_inference(\n args.challenge,\n args.state_dict_file,\n args.data_path,\n args.output_path,\n torch.device(args.device),\n )\n\n # download_model(UNET_FOLDER + MODEL_FNAMES.get(\"unet_knee_sc\"), \"unet_knee_sc.pt\")\n"
] |
[
[
"torch.device",
"torch.no_grad",
"torch.utils.data.DataLoader",
"torch.load"
]
] |
taegoobot/models
|
[
"2c54560546b17d3766a12f248e5a57f5e65995a8"
] |
[
"research/object_detection/utils/object_detection_evaluation.py"
] |
[
"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"object_detection_evaluation module.\n\nObjectDetectionEvaluation is a class which manages ground truth information of a\nobject detection dataset, and computes frequently used detection metrics such as\nPrecision, Recall, CorLoc of the provided detection results.\nIt supports the following operations:\n1) Add ground truth information of images sequentially.\n2) Add detection result of images sequentially.\n3) Evaluate detection metrics on already inserted detection results.\n4) Write evaluation result into a pickle file for future processing or\n visualization.\n\nNote: This module operates on numpy boxes and box lists.\n\"\"\"\n\nfrom abc import ABCMeta\nfrom abc import abstractmethod\nimport collections\nimport logging\nimport unicodedata\nimport numpy as np\n\nfrom object_detection.core import standard_fields\nfrom object_detection.utils import label_map_util\nfrom object_detection.utils import metrics\nfrom object_detection.utils import per_image_evaluation\n\n\nclass DetectionEvaluator(object):\n \"\"\"Interface for object detection evalution classes.\n\n Example usage of the Evaluator:\n ------------------------------\n evaluator = DetectionEvaluator(categories)\n\n # Detections and groundtruth for image 1.\n evaluator.add_single_groundtruth_image_info(...)\n evaluator.add_single_detected_image_info(...)\n\n # Detections and groundtruth for image 2.\n evaluator.add_single_groundtruth_image_info(...)\n evaluator.add_single_detected_image_info(...)\n\n metrics_dict = evaluator.evaluate()\n \"\"\"\n __metaclass__ = ABCMeta\n\n def __init__(self, categories):\n \"\"\"Constructor.\n\n Args:\n categories: A list of dicts, each of which has the following keys -\n 'id': (required) an integer id uniquely identifying this category.\n 'name': (required) string representing category name e.g., 'cat', 'dog'.\n \"\"\"\n self._categories = categories\n\n @abstractmethod\n def add_single_ground_truth_image_info(self, image_id, groundtruth_dict):\n \"\"\"Adds groundtruth for a single image to be used for evaluation.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n groundtruth_dict: A dictionary of groundtruth numpy arrays required\n for evaluations.\n \"\"\"\n pass\n\n @abstractmethod\n def add_single_detected_image_info(self, image_id, detections_dict):\n \"\"\"Adds detections for a single image to be used for evaluation.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n detections_dict: A dictionary of detection numpy arrays required\n for evaluation.\n \"\"\"\n pass\n\n def get_estimator_eval_metric_ops(self, eval_dict):\n \"\"\"Returns dict of metrics to use with `tf.estimator.EstimatorSpec`.\n\n Note that this must only be implemented if performing evaluation with a\n `tf.estimator.Estimator`.\n\n Args:\n eval_dict: A dictionary that holds tensors for evaluating an object\n detection model, returned from\n eval_util.result_dict_for_single_example().\n\n Returns:\n A dictionary of metric names to tuple of value_op and update_op that can\n be used as eval metric ops in `tf.estimator.EstimatorSpec`.\n \"\"\"\n pass\n\n @abstractmethod\n def evaluate(self):\n \"\"\"Evaluates detections and returns a dictionary of metrics.\"\"\"\n pass\n\n @abstractmethod\n def clear(self):\n \"\"\"Clears the state to prepare for a fresh evaluation.\"\"\"\n pass\n\n\nclass ObjectDetectionEvaluator(DetectionEvaluator):\n \"\"\"A class to evaluate detections.\"\"\"\n\n def __init__(self,\n categories,\n matching_iou_threshold=0.5,\n evaluate_corlocs=False,\n metric_prefix=None,\n use_weighted_mean_ap=False,\n evaluate_masks=False,\n group_of_weight=0.0):\n \"\"\"Constructor.\n\n Args:\n categories: A list of dicts, each of which has the following keys -\n 'id': (required) an integer id uniquely identifying this category.\n 'name': (required) string representing category name e.g., 'cat', 'dog'.\n matching_iou_threshold: IOU threshold to use for matching groundtruth\n boxes to detection boxes.\n evaluate_corlocs: (optional) boolean which determines if corloc scores\n are to be returned or not.\n metric_prefix: (optional) string prefix for metric name; if None, no\n prefix is used.\n use_weighted_mean_ap: (optional) boolean which determines if the mean\n average precision is computed directly from the scores and tp_fp_labels\n of all classes.\n evaluate_masks: If False, evaluation will be performed based on boxes.\n If True, mask evaluation will be performed instead.\n group_of_weight: Weight of group-of boxes.If set to 0, detections of the\n correct class within a group-of box are ignored. If weight is > 0, then\n if at least one detection falls within a group-of box with\n matching_iou_threshold, weight group_of_weight is added to true\n positives. Consequently, if no detection falls within a group-of box,\n weight group_of_weight is added to false negatives.\n\n Raises:\n ValueError: If the category ids are not 1-indexed.\n \"\"\"\n super(ObjectDetectionEvaluator, self).__init__(categories)\n self._num_classes = max([cat['id'] for cat in categories])\n if min(cat['id'] for cat in categories) < 1:\n raise ValueError('Classes should be 1-indexed.')\n self._matching_iou_threshold = matching_iou_threshold\n self._use_weighted_mean_ap = use_weighted_mean_ap\n self._label_id_offset = 1\n self._evaluate_masks = evaluate_masks\n self._group_of_weight = group_of_weight\n self._evaluation = ObjectDetectionEvaluation(\n num_groundtruth_classes=self._num_classes,\n matching_iou_threshold=self._matching_iou_threshold,\n use_weighted_mean_ap=self._use_weighted_mean_ap,\n label_id_offset=self._label_id_offset,\n group_of_weight=self._group_of_weight)\n self._image_ids = set([])\n self._evaluate_corlocs = evaluate_corlocs\n self._metric_prefix = (metric_prefix + '_') if metric_prefix else ''\n\n def add_single_ground_truth_image_info(self, image_id, groundtruth_dict):\n \"\"\"Adds groundtruth for a single image to be used for evaluation.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n groundtruth_dict: A dictionary containing -\n standard_fields.InputDataFields.groundtruth_boxes: float32 numpy array\n of shape [num_boxes, 4] containing `num_boxes` groundtruth boxes of\n the format [ymin, xmin, ymax, xmax] in absolute image coordinates.\n standard_fields.InputDataFields.groundtruth_classes: integer numpy array\n of shape [num_boxes] containing 1-indexed groundtruth classes for the\n boxes.\n standard_fields.InputDataFields.groundtruth_difficult: Optional length\n M numpy boolean array denoting whether a ground truth box is a\n difficult instance or not. This field is optional to support the case\n that no boxes are difficult.\n standard_fields.InputDataFields.groundtruth_instance_masks: Optional\n numpy array of shape [num_boxes, height, width] with values in {0, 1}.\n\n Raises:\n ValueError: On adding groundtruth for an image more than once. Will also\n raise error if instance masks are not in groundtruth dictionary.\n \"\"\"\n if image_id in self._image_ids:\n raise ValueError('Image with id {} already added.'.format(image_id))\n\n groundtruth_classes = (\n groundtruth_dict[standard_fields.InputDataFields.groundtruth_classes] -\n self._label_id_offset)\n # If the key is not present in the groundtruth_dict or the array is empty\n # (unless there are no annotations for the groundtruth on this image)\n # use values from the dictionary or insert None otherwise.\n if (standard_fields.InputDataFields.groundtruth_difficult in\n groundtruth_dict.keys() and\n (groundtruth_dict[standard_fields.InputDataFields.groundtruth_difficult]\n .size or not groundtruth_classes.size)):\n groundtruth_difficult = groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_difficult]\n else:\n groundtruth_difficult = None\n if not len(self._image_ids) % 1000:\n logging.warn(\n 'image %s does not have groundtruth difficult flag specified',\n image_id)\n groundtruth_masks = None\n if self._evaluate_masks:\n if (standard_fields.InputDataFields.groundtruth_instance_masks not in\n groundtruth_dict):\n raise ValueError('Instance masks not in groundtruth dictionary.')\n groundtruth_masks = groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_instance_masks]\n self._evaluation.add_single_ground_truth_image_info(\n image_key=image_id,\n groundtruth_boxes=groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_boxes],\n groundtruth_class_labels=groundtruth_classes,\n groundtruth_is_difficult_list=groundtruth_difficult,\n groundtruth_masks=groundtruth_masks)\n self._image_ids.update([image_id])\n\n def add_single_detected_image_info(self, image_id, detections_dict):\n \"\"\"Adds detections for a single image to be used for evaluation.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n detections_dict: A dictionary containing -\n standard_fields.DetectionResultFields.detection_boxes: float32 numpy\n array of shape [num_boxes, 4] containing `num_boxes` detection boxes\n of the format [ymin, xmin, ymax, xmax] in absolute image coordinates.\n standard_fields.DetectionResultFields.detection_scores: float32 numpy\n array of shape [num_boxes] containing detection scores for the boxes.\n standard_fields.DetectionResultFields.detection_classes: integer numpy\n array of shape [num_boxes] containing 1-indexed detection classes for\n the boxes.\n standard_fields.DetectionResultFields.detection_masks: uint8 numpy\n array of shape [num_boxes, height, width] containing `num_boxes` masks\n of values ranging between 0 and 1.\n\n Raises:\n ValueError: If detection masks are not in detections dictionary.\n \"\"\"\n detection_classes = (\n detections_dict[standard_fields.DetectionResultFields.detection_classes]\n - self._label_id_offset)\n detection_masks = None\n if self._evaluate_masks:\n if (standard_fields.DetectionResultFields.detection_masks not in\n detections_dict):\n raise ValueError('Detection masks not in detections dictionary.')\n detection_masks = detections_dict[\n standard_fields.DetectionResultFields.detection_masks]\n self._evaluation.add_single_detected_image_info(\n image_key=image_id,\n detected_boxes=detections_dict[\n standard_fields.DetectionResultFields.detection_boxes],\n detected_scores=detections_dict[\n standard_fields.DetectionResultFields.detection_scores],\n detected_class_labels=detection_classes,\n detected_masks=detection_masks)\n\n def evaluate(self):\n \"\"\"Compute evaluation result.\n\n Returns:\n A dictionary of metrics with the following fields -\n\n 1. summary_metrics:\n 'Precision/mAP@<matching_iou_threshold>IOU': mean average precision at\n the specified IOU threshold.\n\n 2. per_category_ap: category specific results with keys of the form\n 'PerformanceByCategory/mAP@<matching_iou_threshold>IOU/category'.\n \"\"\"\n (per_class_ap, mean_ap, _, _, per_class_corloc, mean_corloc) = (\n self._evaluation.evaluate())\n pascal_metrics = {\n self._metric_prefix +\n 'Precision/mAP@{}IOU'.format(self._matching_iou_threshold):\n mean_ap\n }\n if self._evaluate_corlocs:\n pascal_metrics[self._metric_prefix + 'Precision/meanCorLoc@{}IOU'.format(\n self._matching_iou_threshold)] = mean_corloc\n category_index = label_map_util.create_category_index(self._categories)\n for idx in range(per_class_ap.size):\n if idx + self._label_id_offset in category_index:\n category_name = category_index[idx + self._label_id_offset]['name']\n try:\n category_name = str(category_name, 'utf-8')\n except TypeError:\n pass\n category_name = unicodedata.normalize(\n 'NFKD', category_name).encode('ascii', 'ignore')\n display_name = (\n self._metric_prefix + 'PerformanceByCategory/AP@{}IOU/{}'.format(\n self._matching_iou_threshold, category_name))\n pascal_metrics[display_name] = per_class_ap[idx]\n\n # Optionally add CorLoc metrics.classes\n if self._evaluate_corlocs:\n display_name = (\n self._metric_prefix + 'PerformanceByCategory/CorLoc@{}IOU/{}'\n .format(self._matching_iou_threshold, category_name))\n pascal_metrics[display_name] = per_class_corloc[idx]\n\n return pascal_metrics\n\n def clear(self):\n \"\"\"Clears the state to prepare for a fresh evaluation.\"\"\"\n self._evaluation = ObjectDetectionEvaluation(\n num_groundtruth_classes=self._num_classes,\n matching_iou_threshold=self._matching_iou_threshold,\n use_weighted_mean_ap=self._use_weighted_mean_ap,\n label_id_offset=self._label_id_offset)\n self._image_ids.clear()\n\n\nclass PascalDetectionEvaluator(ObjectDetectionEvaluator):\n \"\"\"A class to evaluate detections using PASCAL metrics.\"\"\"\n\n def __init__(self, categories, matching_iou_threshold=0.5):\n super(PascalDetectionEvaluator, self).__init__(\n categories,\n matching_iou_threshold=matching_iou_threshold,\n evaluate_corlocs=False,\n metric_prefix='PascalBoxes',\n use_weighted_mean_ap=False)\n\n\nclass WeightedPascalDetectionEvaluator(ObjectDetectionEvaluator):\n \"\"\"A class to evaluate detections using weighted PASCAL metrics.\n\n Weighted PASCAL metrics computes the mean average precision as the average\n precision given the scores and tp_fp_labels of all classes. In comparison,\n PASCAL metrics computes the mean average precision as the mean of the\n per-class average precisions.\n\n This definition is very similar to the mean of the per-class average\n precisions weighted by class frequency. However, they are typically not the\n same as the average precision is not a linear function of the scores and\n tp_fp_labels.\n \"\"\"\n\n def __init__(self, categories, matching_iou_threshold=0.5):\n super(WeightedPascalDetectionEvaluator, self).__init__(\n categories,\n matching_iou_threshold=matching_iou_threshold,\n evaluate_corlocs=False,\n metric_prefix='WeightedPascalBoxes',\n use_weighted_mean_ap=True)\n\n\nclass PascalInstanceSegmentationEvaluator(ObjectDetectionEvaluator):\n \"\"\"A class to evaluate instance masks using PASCAL metrics.\"\"\"\n\n def __init__(self, categories, matching_iou_threshold=0.5):\n super(PascalInstanceSegmentationEvaluator, self).__init__(\n categories,\n matching_iou_threshold=matching_iou_threshold,\n evaluate_corlocs=False,\n metric_prefix='PascalMasks',\n use_weighted_mean_ap=False,\n evaluate_masks=True)\n\n\nclass WeightedPascalInstanceSegmentationEvaluator(ObjectDetectionEvaluator):\n \"\"\"A class to evaluate instance masks using weighted PASCAL metrics.\n\n Weighted PASCAL metrics computes the mean average precision as the average\n precision given the scores and tp_fp_labels of all classes. In comparison,\n PASCAL metrics computes the mean average precision as the mean of the\n per-class average precisions.\n\n This definition is very similar to the mean of the per-class average\n precisions weighted by class frequency. However, they are typically not the\n same as the average precision is not a linear function of the scores and\n tp_fp_labels.\n \"\"\"\n\n def __init__(self, categories, matching_iou_threshold=0.5):\n super(WeightedPascalInstanceSegmentationEvaluator, self).__init__(\n categories,\n matching_iou_threshold=matching_iou_threshold,\n evaluate_corlocs=False,\n metric_prefix='WeightedPascalMasks',\n use_weighted_mean_ap=True,\n evaluate_masks=True)\n\n\nclass OpenImagesDetectionEvaluator(ObjectDetectionEvaluator):\n \"\"\"A class to evaluate detections using Open Images V2 metrics.\n\n Open Images V2 introduce group_of type of bounding boxes and this metric\n handles those boxes appropriately.\n \"\"\"\n\n def __init__(self,\n categories,\n matching_iou_threshold=0.5,\n evaluate_corlocs=False,\n metric_prefix='OpenImagesV2',\n group_of_weight=0.0):\n \"\"\"Constructor.\n\n Args:\n categories: A list of dicts, each of which has the following keys -\n 'id': (required) an integer id uniquely identifying this category.\n 'name': (required) string representing category name e.g., 'cat', 'dog'.\n matching_iou_threshold: IOU threshold to use for matching groundtruth\n boxes to detection boxes.\n evaluate_corlocs: if True, additionally evaluates and returns CorLoc.\n metric_prefix: Prefix name of the metric.\n group_of_weight: Weight of the group-of bounding box. If set to 0 (default\n for Open Images V2 detection protocol), detections of the correct class\n within a group-of box are ignored. If weight is > 0, then if at least\n one detection falls within a group-of box with matching_iou_threshold,\n weight group_of_weight is added to true positives. Consequently, if no\n detection falls within a group-of box, weight group_of_weight is added\n to false negatives.\n \"\"\"\n super(OpenImagesDetectionEvaluator, self).__init__(\n categories,\n matching_iou_threshold,\n evaluate_corlocs,\n metric_prefix=metric_prefix,\n group_of_weight=group_of_weight)\n\n def add_single_ground_truth_image_info(self, image_id, groundtruth_dict):\n \"\"\"Adds groundtruth for a single image to be used for evaluation.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n groundtruth_dict: A dictionary containing -\n standard_fields.InputDataFields.groundtruth_boxes: float32 numpy array\n of shape [num_boxes, 4] containing `num_boxes` groundtruth boxes of\n the format [ymin, xmin, ymax, xmax] in absolute image coordinates.\n standard_fields.InputDataFields.groundtruth_classes: integer numpy array\n of shape [num_boxes] containing 1-indexed groundtruth classes for the\n boxes.\n standard_fields.InputDataFields.groundtruth_group_of: Optional length\n M numpy boolean array denoting whether a groundtruth box contains a\n group of instances.\n\n Raises:\n ValueError: On adding groundtruth for an image more than once.\n \"\"\"\n if image_id in self._image_ids:\n raise ValueError('Image with id {} already added.'.format(image_id))\n\n groundtruth_classes = (\n groundtruth_dict[standard_fields.InputDataFields.groundtruth_classes] -\n self._label_id_offset)\n # If the key is not present in the groundtruth_dict or the array is empty\n # (unless there are no annotations for the groundtruth on this image)\n # use values from the dictionary or insert None otherwise.\n if (standard_fields.InputDataFields.groundtruth_group_of in\n groundtruth_dict.keys() and\n (groundtruth_dict[standard_fields.InputDataFields.groundtruth_group_of]\n .size or not groundtruth_classes.size)):\n groundtruth_group_of = groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_group_of]\n else:\n groundtruth_group_of = None\n if not len(self._image_ids) % 1000:\n logging.warn(\n 'image %s does not have groundtruth group_of flag specified',\n image_id)\n self._evaluation.add_single_ground_truth_image_info(\n image_id,\n groundtruth_dict[standard_fields.InputDataFields.groundtruth_boxes],\n groundtruth_classes,\n groundtruth_is_difficult_list=None,\n groundtruth_is_group_of_list=groundtruth_group_of)\n self._image_ids.update([image_id])\n\n\nclass OpenImagesDetectionChallengeEvaluator(OpenImagesDetectionEvaluator):\n \"\"\"A class implements Open Images Challenge Detection metrics.\n\n Open Images Challenge Detection metric has two major changes in comparison\n with Open Images V2 detection metric:\n - a custom weight might be specified for detecting an object contained in\n a group-of box.\n - verified image-level labels should be explicitelly provided for\n evaluation: in case in image has neither positive nor negative image level\n label of class c, all detections of this class on this image will be\n ignored.\n \"\"\"\n\n def __init__(self,\n categories,\n matching_iou_threshold=0.5,\n evaluate_corlocs=False,\n group_of_weight=1.0):\n \"\"\"Constructor.\n\n Args:\n categories: A list of dicts, each of which has the following keys -\n 'id': (required) an integer id uniquely identifying this category.\n 'name': (required) string representing category name e.g., 'cat', 'dog'.\n matching_iou_threshold: IOU threshold to use for matching groundtruth\n boxes to detection boxes.\n evaluate_corlocs: if True, additionally evaluates and returns CorLoc.\n group_of_weight: weight of a group-of box. If set to 0, detections of the\n correct class within a group-of box are ignored. If weight is > 0\n (default for Open Images Detection Challenge 2018), then if at least one\n detection falls within a group-of box with matching_iou_threshold,\n weight group_of_weight is added to true positives. Consequently, if no\n detection falls within a group-of box, weight group_of_weight is added\n to false negatives.\n \"\"\"\n super(OpenImagesDetectionChallengeEvaluator, self).__init__(\n categories,\n matching_iou_threshold,\n evaluate_corlocs,\n metric_prefix='OpenImagesChallenge2018',\n group_of_weight=group_of_weight)\n\n self._evaluatable_labels = {}\n\n def add_single_ground_truth_image_info(self, image_id, groundtruth_dict):\n \"\"\"Adds groundtruth for a single image to be used for evaluation.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n groundtruth_dict: A dictionary containing -\n standard_fields.InputDataFields.groundtruth_boxes: float32 numpy array\n of shape [num_boxes, 4] containing `num_boxes` groundtruth boxes of\n the format [ymin, xmin, ymax, xmax] in absolute image coordinates.\n standard_fields.InputDataFields.groundtruth_classes: integer numpy array\n of shape [num_boxes] containing 1-indexed groundtruth classes for the\n boxes.\n standard_fields.InputDataFields.groundtruth_image_classes: integer 1D\n numpy array containing all classes for which labels are verified.\n standard_fields.InputDataFields.groundtruth_group_of: Optional length\n M numpy boolean array denoting whether a groundtruth box contains a\n group of instances.\n\n Raises:\n ValueError: On adding groundtruth for an image more than once.\n \"\"\"\n super(OpenImagesDetectionChallengeEvaluator,\n self).add_single_ground_truth_image_info(image_id, groundtruth_dict)\n groundtruth_classes = (\n groundtruth_dict[standard_fields.InputDataFields.groundtruth_classes] -\n self._label_id_offset)\n self._evaluatable_labels[image_id] = np.unique(\n np.concatenate(((groundtruth_dict.get(\n standard_fields.InputDataFields.groundtruth_image_classes,\n np.array([], dtype=int)) - self._label_id_offset),\n groundtruth_classes)))\n\n def add_single_detected_image_info(self, image_id, detections_dict):\n \"\"\"Adds detections for a single image to be used for evaluation.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n detections_dict: A dictionary containing -\n standard_fields.DetectionResultFields.detection_boxes: float32 numpy\n array of shape [num_boxes, 4] containing `num_boxes` detection boxes\n of the format [ymin, xmin, ymax, xmax] in absolute image coordinates.\n standard_fields.DetectionResultFields.detection_scores: float32 numpy\n array of shape [num_boxes] containing detection scores for the boxes.\n standard_fields.DetectionResultFields.detection_classes: integer numpy\n array of shape [num_boxes] containing 1-indexed detection classes for\n the boxes.\n\n Raises:\n ValueError: If detection masks are not in detections dictionary.\n \"\"\"\n if image_id not in self._image_ids:\n # Since for the correct work of evaluator it is assumed that groundtruth\n # is inserted first we make sure to break the code if is it not the case.\n self._image_ids.update([image_id])\n self._evaluatable_labels[image_id] = np.array([])\n\n detection_classes = (\n detections_dict[standard_fields.DetectionResultFields.detection_classes]\n - self._label_id_offset)\n allowed_classes = np.where(\n np.isin(detection_classes, self._evaluatable_labels[image_id]))\n detection_classes = detection_classes[allowed_classes]\n detected_boxes = detections_dict[\n standard_fields.DetectionResultFields.detection_boxes][allowed_classes]\n detected_scores = detections_dict[\n standard_fields.DetectionResultFields.detection_scores][allowed_classes]\n\n self._evaluation.add_single_detected_image_info(\n image_key=image_id,\n detected_boxes=detected_boxes,\n detected_scores=detected_scores,\n detected_class_labels=detection_classes)\n\n def clear(self):\n \"\"\"Clears stored data.\"\"\"\n\n super(OpenImagesDetectionChallengeEvaluator, self).clear()\n self._evaluatable_labels.clear()\n\n\nObjectDetectionEvalMetrics = collections.namedtuple(\n 'ObjectDetectionEvalMetrics', [\n 'average_precisions', 'mean_ap', 'precisions', 'recalls', 'corlocs',\n 'mean_corloc'\n ])\n\n\nclass ObjectDetectionEvaluation(object):\n \"\"\"Internal implementation of Pascal object detection metrics.\"\"\"\n\n def __init__(self,\n num_groundtruth_classes,\n matching_iou_threshold=0.5,\n nms_iou_threshold=1.0,\n nms_max_output_boxes=10000,\n use_weighted_mean_ap=False,\n label_id_offset=0,\n group_of_weight=0.0):\n if num_groundtruth_classes < 1:\n raise ValueError('Need at least 1 groundtruth class for evaluation.')\n\n self.per_image_eval = per_image_evaluation.PerImageEvaluation(\n num_groundtruth_classes=num_groundtruth_classes,\n matching_iou_threshold=matching_iou_threshold,\n nms_iou_threshold=nms_iou_threshold,\n nms_max_output_boxes=nms_max_output_boxes,\n group_of_weight=group_of_weight)\n self.group_of_weight = group_of_weight\n self.num_class = num_groundtruth_classes\n self.use_weighted_mean_ap = use_weighted_mean_ap\n self.label_id_offset = label_id_offset\n\n self.groundtruth_boxes = {}\n self.groundtruth_class_labels = {}\n self.groundtruth_masks = {}\n self.groundtruth_is_difficult_list = {}\n self.groundtruth_is_group_of_list = {}\n self.num_gt_instances_per_class = np.zeros(self.num_class, dtype=float)\n self.num_gt_imgs_per_class = np.zeros(self.num_class, dtype=int)\n\n self._initialize_detections()\n\n def _initialize_detections(self):\n self.detection_keys = set()\n self.scores_per_class = [[] for _ in range(self.num_class)]\n self.tp_fp_labels_per_class = [[] for _ in range(self.num_class)]\n self.num_images_correctly_detected_per_class = np.zeros(self.num_class)\n self.average_precision_per_class = np.empty(self.num_class, dtype=float)\n self.average_precision_per_class.fill(np.nan)\n self.precisions_per_class = []\n self.recalls_per_class = []\n self.corloc_per_class = np.ones(self.num_class, dtype=float)\n\n def clear_detections(self):\n self._initialize_detections()\n\n def add_single_ground_truth_image_info(self,\n image_key,\n groundtruth_boxes,\n groundtruth_class_labels,\n groundtruth_is_difficult_list=None,\n groundtruth_is_group_of_list=None,\n groundtruth_masks=None):\n \"\"\"Adds groundtruth for a single image to be used for evaluation.\n\n Args:\n image_key: A unique string/integer identifier for the image.\n groundtruth_boxes: float32 numpy array of shape [num_boxes, 4]\n containing `num_boxes` groundtruth boxes of the format\n [ymin, xmin, ymax, xmax] in absolute image coordinates.\n groundtruth_class_labels: integer numpy array of shape [num_boxes]\n containing 0-indexed groundtruth classes for the boxes.\n groundtruth_is_difficult_list: A length M numpy boolean array denoting\n whether a ground truth box is a difficult instance or not. To support\n the case that no boxes are difficult, it is by default set as None.\n groundtruth_is_group_of_list: A length M numpy boolean array denoting\n whether a ground truth box is a group-of box or not. To support\n the case that no boxes are groups-of, it is by default set as None.\n groundtruth_masks: uint8 numpy array of shape\n [num_boxes, height, width] containing `num_boxes` groundtruth masks.\n The mask values range from 0 to 1.\n \"\"\"\n if image_key in self.groundtruth_boxes:\n logging.warn(\n 'image %s has already been added to the ground truth database.',\n image_key)\n return\n\n self.groundtruth_boxes[image_key] = groundtruth_boxes\n self.groundtruth_class_labels[image_key] = groundtruth_class_labels\n self.groundtruth_masks[image_key] = groundtruth_masks\n if groundtruth_is_difficult_list is None:\n num_boxes = groundtruth_boxes.shape[0]\n groundtruth_is_difficult_list = np.zeros(num_boxes, dtype=bool)\n self.groundtruth_is_difficult_list[\n image_key] = groundtruth_is_difficult_list.astype(dtype=bool)\n if groundtruth_is_group_of_list is None:\n num_boxes = groundtruth_boxes.shape[0]\n groundtruth_is_group_of_list = np.zeros(num_boxes, dtype=bool)\n self.groundtruth_is_group_of_list[\n image_key] = groundtruth_is_group_of_list.astype(dtype=bool)\n\n self._update_ground_truth_statistics(\n groundtruth_class_labels,\n groundtruth_is_difficult_list.astype(dtype=bool),\n groundtruth_is_group_of_list.astype(dtype=bool))\n\n def add_single_detected_image_info(self, image_key, detected_boxes,\n detected_scores, detected_class_labels,\n detected_masks=None):\n \"\"\"Adds detections for a single image to be used for evaluation.\n\n Args:\n image_key: A unique string/integer identifier for the image.\n detected_boxes: float32 numpy array of shape [num_boxes, 4]\n containing `num_boxes` detection boxes of the format\n [ymin, xmin, ymax, xmax] in absolute image coordinates.\n detected_scores: float32 numpy array of shape [num_boxes] containing\n detection scores for the boxes.\n detected_class_labels: integer numpy array of shape [num_boxes] containing\n 0-indexed detection classes for the boxes.\n detected_masks: np.uint8 numpy array of shape [num_boxes, height, width]\n containing `num_boxes` detection masks with values ranging\n between 0 and 1.\n\n Raises:\n ValueError: if the number of boxes, scores and class labels differ in\n length.\n \"\"\"\n if (len(detected_boxes) != len(detected_scores) or\n len(detected_boxes) != len(detected_class_labels)):\n raise ValueError('detected_boxes, detected_scores and '\n 'detected_class_labels should all have same lengths. Got'\n '[%d, %d, %d]' % len(detected_boxes),\n len(detected_scores), len(detected_class_labels))\n\n if image_key in self.detection_keys:\n logging.warn(\n 'image %s has already been added to the detection result database',\n image_key)\n return\n\n self.detection_keys.add(image_key)\n if image_key in self.groundtruth_boxes:\n groundtruth_boxes = self.groundtruth_boxes[image_key]\n groundtruth_class_labels = self.groundtruth_class_labels[image_key]\n # Masks are popped instead of look up. The reason is that we do not want\n # to keep all masks in memory which can cause memory overflow.\n groundtruth_masks = self.groundtruth_masks.pop(\n image_key)\n groundtruth_is_difficult_list = self.groundtruth_is_difficult_list[\n image_key]\n groundtruth_is_group_of_list = self.groundtruth_is_group_of_list[\n image_key]\n else:\n groundtruth_boxes = np.empty(shape=[0, 4], dtype=float)\n groundtruth_class_labels = np.array([], dtype=int)\n if detected_masks is None:\n groundtruth_masks = None\n else:\n groundtruth_masks = np.empty(shape=[0, 1, 1], dtype=float)\n groundtruth_is_difficult_list = np.array([], dtype=bool)\n groundtruth_is_group_of_list = np.array([], dtype=bool)\n scores, tp_fp_labels, is_class_correctly_detected_in_image = (\n self.per_image_eval.compute_object_detection_metrics(\n detected_boxes=detected_boxes,\n detected_scores=detected_scores,\n detected_class_labels=detected_class_labels,\n groundtruth_boxes=groundtruth_boxes,\n groundtruth_class_labels=groundtruth_class_labels,\n groundtruth_is_difficult_list=groundtruth_is_difficult_list,\n groundtruth_is_group_of_list=groundtruth_is_group_of_list,\n detected_masks=detected_masks,\n groundtruth_masks=groundtruth_masks))\n\n for i in range(self.num_class):\n if scores[i].shape[0] > 0:\n self.scores_per_class[i].append(scores[i])\n self.tp_fp_labels_per_class[i].append(tp_fp_labels[i])\n self.num_images_correctly_detected_per_class += is_class_correctly_detected_in_image\n\n def _update_ground_truth_statistics(self, groundtruth_class_labels,\n groundtruth_is_difficult_list,\n groundtruth_is_group_of_list):\n \"\"\"Update grouth truth statitistics.\n\n 1. Difficult boxes are ignored when counting the number of ground truth\n instances as done in Pascal VOC devkit.\n 2. Difficult boxes are treated as normal boxes when computing CorLoc related\n statitistics.\n\n Args:\n groundtruth_class_labels: An integer numpy array of length M,\n representing M class labels of object instances in ground truth\n groundtruth_is_difficult_list: A boolean numpy array of length M denoting\n whether a ground truth box is a difficult instance or not\n groundtruth_is_group_of_list: A boolean numpy array of length M denoting\n whether a ground truth box is a group-of box or not\n \"\"\"\n for class_index in range(self.num_class):\n num_gt_instances = np.sum(groundtruth_class_labels[\n ~groundtruth_is_difficult_list\n & ~groundtruth_is_group_of_list] == class_index)\n num_groupof_gt_instances = self.group_of_weight * np.sum(\n groundtruth_class_labels[groundtruth_is_group_of_list] == class_index)\n self.num_gt_instances_per_class[\n class_index] += num_gt_instances + num_groupof_gt_instances\n if np.any(groundtruth_class_labels == class_index):\n self.num_gt_imgs_per_class[class_index] += 1\n\n def evaluate(self):\n \"\"\"Compute evaluation result.\n\n Returns:\n A named tuple with the following fields -\n average_precision: float numpy array of average precision for\n each class.\n mean_ap: mean average precision of all classes, float scalar\n precisions: List of precisions, each precision is a float numpy\n array\n recalls: List of recalls, each recall is a float numpy array\n corloc: numpy float array\n mean_corloc: Mean CorLoc score for each class, float scalar\n \"\"\"\n if (self.num_gt_instances_per_class == 0).any():\n logging.warn(\n 'The following classes have no ground truth examples: %s',\n np.squeeze(np.argwhere(self.num_gt_instances_per_class == 0)) +\n self.label_id_offset)\n\n if self.use_weighted_mean_ap:\n all_scores = np.array([], dtype=float)\n all_tp_fp_labels = np.array([], dtype=bool)\n for class_index in range(self.num_class):\n if self.num_gt_instances_per_class[class_index] == 0:\n continue\n if not self.scores_per_class[class_index]:\n scores = np.array([], dtype=float)\n tp_fp_labels = np.array([], dtype=float)\n else:\n scores = np.concatenate(self.scores_per_class[class_index])\n tp_fp_labels = np.concatenate(self.tp_fp_labels_per_class[class_index])\n if self.use_weighted_mean_ap:\n all_scores = np.append(all_scores, scores)\n all_tp_fp_labels = np.append(all_tp_fp_labels, tp_fp_labels)\n logging.info('Scores and tpfp per class label: %d', class_index)\n logging.info(tp_fp_labels)\n logging.info(scores)\n precision, recall = metrics.compute_precision_recall(\n scores, tp_fp_labels, self.num_gt_instances_per_class[class_index])\n self.precisions_per_class.append(precision)\n self.recalls_per_class.append(recall)\n average_precision = metrics.compute_average_precision(precision, recall)\n self.average_precision_per_class[class_index] = average_precision\n\n self.corloc_per_class = metrics.compute_cor_loc(\n self.num_gt_imgs_per_class,\n self.num_images_correctly_detected_per_class)\n\n if self.use_weighted_mean_ap:\n num_gt_instances = np.sum(self.num_gt_instances_per_class)\n precision, recall = metrics.compute_precision_recall(\n all_scores, all_tp_fp_labels, num_gt_instances)\n mean_ap = metrics.compute_average_precision(precision, recall)\n else:\n mean_ap = np.nanmean(self.average_precision_per_class)\n mean_corloc = np.nanmean(self.corloc_per_class)\n return ObjectDetectionEvalMetrics(\n self.average_precision_per_class, mean_ap, self.precisions_per_class,\n self.recalls_per_class, self.corloc_per_class, mean_corloc)\n"
] |
[
[
"numpy.isin",
"numpy.ones",
"numpy.concatenate",
"numpy.argwhere",
"numpy.append",
"numpy.nanmean",
"numpy.any",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"numpy.empty"
]
] |
berkmancenter/odie_analysis
|
[
"940a1bfad95403cfdc060c786707114efe6ab879"
] |
[
"app/cohort_analysis.py"
] |
[
"import pickle\nimport logging\nfrom pathlib import Path\nfrom collections import defaultdict, Counter\n\nimport pandas as pd\nimport numpy as np\n\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch_dsl import Search\nfrom tqdm import tqdm\nfrom datasketch import MinHash, MinHashLSH\nfrom scattertext.termscoring.ScaledFScore import ScaledFScore\n\nfrom n_grams import tweets_to_n_gram_counts, extract_tweet_text,\\\n tokenize_tweet, tweet_text_to_n_grams\nimport config\n\n\ndef get_cohort_tweet_text(cohort_prefix, timespan):\n client = Elasticsearch(config.ELASTICSEARCH_HOST)\n\n s = Search(using=client, index=f'{cohort_prefix}*').query(\"match_all\")\\\n .filter({\"range\":\n {\"@timestamp\": {\"gte\": timespan[0], \"lte\": timespan[1]}}})\n tweets = (hit.to_dict() for hit in s.scan())\n return extract_tweet_text(tweets)\n\n\ndef get_cohort_tweets(cohort_prefix, timespan):\n client = Elasticsearch(config.ELASTICSEARCH_HOST)\n\n s = Search(using=client, index=f'{cohort_prefix}*').query(\"match_all\")\\\n .filter({\"range\":\n {\"@timestamp\": {\"gte\": timespan[0], \"lte\": timespan[1]}}})\n logging.info(s)\n tweets = {}\n for hit in tqdm(s.scan(), desc='Reading tweets'):\n hit = hit.to_dict()\n tweets[hit['id']] = hit\n return tweets\n\n\ndef tweets_to_lsh(tweet_text):\n # Create LSH index\n lsh = MinHashLSH(threshold=0.95, num_perm=128)\n\n for tweet_id, text in tqdm(\n tweet_text.items(), smoothing=0, desc='Hashing'):\n m1 = MinHash(num_perm=128)\n words = set(tokenize_tweet(text))\n for word in words:\n m1.update(word.encode('utf8'))\n lsh.insert(tweet_id, m1)\n return lsh\n\n\ndef tweets_to_doc_groups(lsh):\n tweet_id_to_group = {}\n for i, hashtable in enumerate(lsh.hashtables):\n for j, (key, tweets) in enumerate(dict(hashtable).items()):\n for tweet in tweets:\n tweet_id_to_group[tweet] = i*j + j\n return tweet_id_to_group\n\n\ndef doc_groups_to_docs(tweet_id_to_group, tweet_text):\n docs = defaultdict(str)\n for tweet_id, group_i in tqdm(\n tweet_id_to_group.items(), desc='Prepping docs'):\n docs[group_i] += f'{tweet_text[tweet_id]}\\n'\n\n group_to_tweet_ids = defaultdict(list)\n for tweet_id, group in tweet_id_to_group.items():\n group_to_tweet_ids[group].append(tweet_id)\n return docs\n\n\ndef tweets_to_docs(tweet_text, lsh_cache_name):\n if Path(lsh_cache_name).exists():\n lsh = pd.read_pickle(lsh_cache_name)\n else:\n lsh = tweets_to_lsh(tweet_text)\n with open(lsh_cache_name, 'wb') as f:\n pickle.dump(lsh, f, protocol=4)\n tweet_id_to_group = tweets_to_doc_groups(lsh)\n docs = doc_groups_to_docs(tweet_id_to_group, tweet_text)\n tokenized_docs = {}\n for i, doc in docs.items():\n tokens = list(tokenize_tweet(doc))\n if len(tokens) > 0:\n tokenized_docs[i] = tokens\n return tokenized_docs, tweet_id_to_group\n\n\ndef calc_top_n_grams(tweets, n_gram_lens=[1, 2, 3], k=50):\n output = defaultdict(Counter)\n for tweet in tqdm(tweets.values(), desc='Tokenizing'):\n for n_gram, tokens in tweet_text_to_n_grams(\n tweet, n_gram_lens).items():\n output[n_gram].update(tokens)\n return {n_gram: output[n_gram].most_common(k) for n_gram in n_gram_lens}\n\n\ndef extract_accts(tweets):\n return set([t['user']['id'] for t in tweets.values()])\n\n\ndef n_gram_counter_to_dict(counter):\n output = {}\n for n_gram, count in dict(counter).items():\n output[' '.join(n_gram)] = count\n return output\n\n\ndef summarize_cohort(cohort_prefix, timespan, top_k=50):\n tweets = get_cohort_tweets(cohort_prefix, timespan)\n n_grams = tweets_to_n_gram_counts(tweets, [1, 2, 3])\n return {\n 'n_accounts': len(extract_accts(tweets)),\n 'n_tweets': len(tweets),\n 'top_unigrams': n_gram_counter_to_dict(n_grams[1].most_common(top_k)),\n 'top_bigrams': n_gram_counter_to_dict(n_grams[2].most_common(top_k)),\n 'top_trigrams': n_gram_counter_to_dict(n_grams[3].most_common(top_k))\n }\n\n\ndef calc_f1_scores(n_grams_a, n_grams_b):\n all_n_grams_a = sum(n_grams_a.values(), Counter())\n all_n_grams_b = sum(n_grams_b.values(), Counter())\n vocab = sorted(list((all_n_grams_a + all_n_grams_b).keys()))\n n_gram_a_counts = [all_n_grams_a[v] for v in vocab]\n n_gram_b_counts = [all_n_grams_b[v] for v in vocab]\n scores = ScaledFScore.get_scores(np.array(n_gram_a_counts),\n np.array(n_gram_b_counts))\n return pd.DataFrame({\n 'cohort_a_count': n_gram_a_counts,\n 'cohort_b_count': n_gram_b_counts,\n 'scaled_f1': scores,\n }, index=vocab).sort_values(\n ['scaled_f1', 'cohort_a_count', 'cohort_b_count'],\n ascending=[True, True, False])\n\n\ndef compare_cohorts(cohort_prefix_a, timespan_a,\n cohort_prefix_b, timespan_b,\n top_k=50):\n tweets_a = get_cohort_tweets(cohort_prefix_a, timespan_a)\n n_grams_a = tweets_to_n_gram_counts(tweets_a, [1, 2, 3])\n accts_a = extract_accts(tweets_a)\n\n tweets_b = get_cohort_tweets(cohort_prefix_b, timespan_b)\n n_grams_b = tweets_to_n_gram_counts(tweets_b, [1, 2, 3])\n accts_b = extract_accts(tweets_b)\n\n f1_scores = calc_f1_scores(n_grams_a, n_grams_b)\n most_characteristic_a = f1_scores.sort_values(\n ['scaled_f1', 'cohort_a_count', 'cohort_b_count'],\n ascending=[False, False, True]).head(top_k)\n most_characteristic_a = list(\n map(lambda x: ' '.join(x), most_characteristic_a.index.values))\n most_characteristic_b = f1_scores.sort_values(\n ['scaled_f1', 'cohort_a_count', 'cohort_b_count'],\n ascending=[True, True, False]).head(top_k)\n most_characteristic_b = list(\n map(lambda x: ' '.join(x), most_characteristic_b.index.values))\n\n return {\n 'summary_a': {\n 'n_accounts': len(accts_a),\n 'n_tweets': len(tweets_a),\n 'top_unigrams':\n n_gram_counter_to_dict(n_grams_a[1].most_common(top_k)),\n 'top_bigrams':\n n_gram_counter_to_dict(n_grams_a[2].most_common(top_k)),\n 'top_trigrams':\n n_gram_counter_to_dict(n_grams_a[3].most_common(top_k))\n },\n 'summary_b': {\n 'n_accounts': len(accts_b),\n 'n_tweets': len(tweets_b),\n 'top_unigrams':\n n_gram_counter_to_dict(n_grams_b[1].most_common(top_k)),\n 'top_bigrams':\n n_gram_counter_to_dict(n_grams_b[2].most_common(top_k)),\n 'top_trigrams':\n n_gram_counter_to_dict(n_grams_b[3].most_common(top_k))\n },\n 'f1_scores': {\n 'most_characteristic_a': most_characteristic_a,\n 'most_characteristic_b': most_characteristic_b,\n }\n }\n"
] |
[
[
"numpy.array",
"pandas.read_pickle",
"pandas.DataFrame"
]
] |
Rnhondova/garage
|
[
"0ff40022a1da0287a45af86c7b8fc9c604c13dd5"
] |
[
"tests/garage/torch/policies/test_categorical_cnn_policy.py"
] |
[
"\"\"\"Test categoricalCNNPolicy in PyTorch.\"\"\"\nimport cloudpickle\nimport pytest\nimport torch\n\nfrom garage.envs import GymEnv\nfrom garage.torch import TransposeImage\nfrom garage.torch.policies import CategoricalCNNPolicy\n\nfrom tests.fixtures.envs.dummy import DummyDictEnv, DummyDiscretePixelEnv\n\n\nclass TestCategoricalCNNPolicy:\n\n def _initialize_obs_env(self, env):\n \"\"\"Initialize observation env depends on observation space type.\n\n If observation space (i.e. akro.Image, gym.spaces.Box) is an image,\n wrap the input of shape (W, H, 3) for PyTorch (N, 3, W, H).\n\n Return:\n Transformed environment (garage.envs).\n \"\"\"\n obs_shape = env.observation_space.shape\n if len(obs_shape) == 3 and obs_shape[2] in [1, 3]:\n env = TransposeImage(env)\n return env\n\n @pytest.mark.parametrize(\n 'hidden_channels, kernel_sizes, strides, hidden_sizes', [\n ((3, ), (3, ), (1, ), (4, )),\n ((3, 3), (3, 3), (1, 1), (4, 4)),\n ((3, 3), (3, 3), (2, 2), (4, 4)),\n ])\n def test_get_action(self, hidden_channels, kernel_sizes, strides,\n hidden_sizes):\n \"\"\"Test get_action function.\"\"\"\n env = GymEnv(DummyDiscretePixelEnv(), is_image=True)\n env = self._initialize_obs_env(env)\n policy = CategoricalCNNPolicy(env=env,\n kernel_sizes=kernel_sizes,\n hidden_channels=hidden_channels,\n strides=strides,\n hidden_sizes=hidden_sizes)\n env.reset()\n obs = env.step(1).observation\n action, _ = policy.get_action(obs)\n assert env.action_space.contains(action)\n\n @pytest.mark.parametrize(\n 'hidden_channels, kernel_sizes, strides, hidden_sizes', [\n ((3, ), (3, ), (1, ), (4, )),\n ((3, 3), (3, 3), (1, 1), (4, 4)),\n ((3, 3), (3, 3), (2, 2), (4, 4)),\n ])\n def test_get_action_img_obs(self, hidden_channels, kernel_sizes, strides,\n hidden_sizes):\n \"\"\"Test get_action function with akro.Image observation space.\"\"\"\n env = GymEnv(DummyDiscretePixelEnv(), is_image=True)\n env = self._initialize_obs_env(env)\n policy = CategoricalCNNPolicy(env=env,\n kernel_sizes=kernel_sizes,\n hidden_channels=hidden_channels,\n strides=strides,\n hidden_sizes=hidden_sizes)\n env.reset()\n obs = env.step(1).observation\n\n action, _ = policy.get_action(obs)\n assert env.action_space.contains(action)\n\n @pytest.mark.parametrize(\n 'hidden_channels, kernel_sizes, strides, hidden_sizes', [\n ((3, ), (3, ), (1, ), (4, )),\n ((3, 3), (3, 3), (1, 1), (4, 4)),\n ((3, 3), (3, 3), (2, 2), (4, 4)),\n ])\n def test_get_actions(self, hidden_channels, kernel_sizes, strides,\n hidden_sizes):\n \"\"\"Test get_actions function with akro.Image observation space.\"\"\"\n env = GymEnv(DummyDiscretePixelEnv(), is_image=True)\n env = self._initialize_obs_env(env)\n policy = CategoricalCNNPolicy(env=env,\n kernel_sizes=kernel_sizes,\n hidden_channels=hidden_channels,\n strides=strides,\n hidden_sizes=hidden_sizes)\n env.reset()\n obs = env.step(1).observation\n\n actions, _ = policy.get_actions([obs, obs, obs])\n for action in actions:\n assert env.action_space.contains(action)\n torch_obs = torch.Tensor(obs)\n actions, _ = policy.get_actions([torch_obs, torch_obs, torch_obs])\n for action in actions:\n assert env.action_space.contains(action)\n\n @pytest.mark.parametrize(\n 'hidden_channels, kernel_sizes, strides, hidden_sizes', [\n ((3, ), (3, ), (1, ), (4, )),\n ((3, 3), (3, 3), (1, 1), (4, 4)),\n ((3, 3), (3, 3), (2, 2), (4, 4)),\n ])\n def test_is_pickleable(self, hidden_channels, kernel_sizes, strides,\n hidden_sizes):\n \"\"\"Test if policy is pickable.\"\"\"\n env = GymEnv(DummyDiscretePixelEnv(), is_image=True)\n env = self._initialize_obs_env(env)\n policy = CategoricalCNNPolicy(env=env,\n kernel_sizes=kernel_sizes,\n hidden_channels=hidden_channels,\n strides=strides,\n hidden_sizes=hidden_sizes)\n env.reset()\n obs = env.step(1).observation\n\n output_action_1, _ = policy.get_action(obs)\n\n p = cloudpickle.dumps(policy)\n policy_pickled = cloudpickle.loads(p)\n output_action_2, _ = policy_pickled.get_action(obs)\n\n assert env.action_space.contains(output_action_1)\n assert env.action_space.contains(output_action_2)\n assert output_action_1.shape == output_action_2.shape\n\n def test_does_not_support_dict_obs_space(self):\n \"\"\"Test that policy raises error if passed a dict obs space.\"\"\"\n env = GymEnv(DummyDictEnv(act_space_type='discrete'))\n with pytest.raises(ValueError,\n match=('CNN policies do not support '\n 'with akro.Dict observation spaces.')):\n CategoricalCNNPolicy(env=env,\n kernel_sizes=(3, ),\n hidden_channels=(3, ))\n\n def test_invalid_action_spaces(self):\n \"\"\"Test that policy raises error if passed a box obs space.\"\"\"\n env = GymEnv(DummyDictEnv(act_space_type='box'))\n with pytest.raises(ValueError):\n CategoricalCNNPolicy(env=env,\n kernel_sizes=(3, ),\n hidden_channels=(3, ))\n\n @pytest.mark.parametrize(\n 'hidden_channels, kernel_sizes, strides, hidden_sizes', [\n ((3, ), (3, ), (1, ), (4, )),\n ((3, 3), (3, 3), (1, 1), (4, 4)),\n ((3, 3), (3, 3), (2, 2), (4, 4)),\n ])\n def test_obs_unflattened(self, hidden_channels, kernel_sizes, strides,\n hidden_sizes):\n \"\"\"Test if a flattened image obs is passed to get_action\n then it is unflattened.\n \"\"\"\n env = GymEnv(DummyDiscretePixelEnv(), is_image=True)\n env = self._initialize_obs_env(env)\n env.reset()\n policy = CategoricalCNNPolicy(env=env,\n kernel_sizes=kernel_sizes,\n hidden_channels=hidden_channels,\n strides=strides,\n hidden_sizes=hidden_sizes)\n obs = env.observation_space.sample()\n action, _ = policy.get_action(env.observation_space.flatten(obs))\n env.step(action)\n"
] |
[
[
"torch.Tensor"
]
] |
tommy19970714/FullSubNetWithASR
|
[
"fbe6b8f1ae83d23b685bb3dae457b58941ee3644"
] |
[
"audio_zen/model/base_model.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.init as init\nfrom torch.nn import functional\nfrom audio_zen.constant import EPSILON\n\n\nclass BaseModel(nn.Module):\n def __init__(self):\n super(BaseModel, self).__init__()\n\n @staticmethod\n def unfold(input, num_neighbor):\n \"\"\"\n Along with the frequency dim, split overlapped sub band units from spectrogram.\n\n Args:\n input: [B, C, F, T]\n num_neighbor:\n\n Returns:\n [B, N, C, F_s, T], F 为子频带的频率轴大小, e.g. [2, 161, 1, 19, 200]\n \"\"\"\n assert input.dim() == 4, f\"The dim of input is {input.dim()}. It should be four dim.\"\n batch_size, num_channels, num_freqs, num_frames = input.size()\n\n if num_neighbor < 1:\n # No change for the input\n return input.permute(0, 2, 1, 3).reshape(batch_size, num_freqs, num_channels, 1, num_frames)\n\n output = input.reshape(batch_size * num_channels, 1, num_freqs, num_frames)\n sub_band_unit_size = num_neighbor * 2 + 1\n\n # Pad to the top and bottom\n output = functional.pad(output, [0, 0, num_neighbor, num_neighbor], mode=\"reflect\")\n\n output = functional.unfold(output, (sub_band_unit_size, num_frames))\n assert output.shape[-1] == num_freqs, f\"n_freqs != N (sub_band), {num_freqs} != {output.shape[-1]}\"\n\n # Split the dim of the unfolded feature\n output = output.reshape(batch_size, num_channels, sub_band_unit_size, num_frames, num_freqs)\n output = output.permute(0, 4, 1, 2, 3).contiguous()\n\n return output\n\n @staticmethod\n def _reduce_complexity_separately(sub_band_input, full_band_output, device):\n \"\"\"\n\n Args:\n sub_band_input: [60, 257, 1, 33, 200]\n full_band_output: [60, 257, 1, 3, 200]\n device:\n\n Notes:\n 1. 255 and 256 freq not able to be trained\n 2. batch size 应该被 3 整除,否则最后一部分 batch 内的频率无法很好的训练\n\n Returns:\n [60, 85, 1, 36, 200]\n \"\"\"\n batch_size = full_band_output.shape[0]\n n_freqs = full_band_output.shape[1]\n sub_batch_size = batch_size // 3\n final_selected = []\n\n for idx in range(3):\n # [0, 60) => [0, 20)\n sub_batch_indices = torch.arange(idx * sub_batch_size, (idx + 1) * sub_batch_size, device=device)\n full_band_output_sub_batch = torch.index_select(full_band_output, dim=0, index=sub_batch_indices)\n sub_band_output_sub_batch = torch.index_select(sub_band_input, dim=0, index=sub_batch_indices)\n\n # Avoid to use padded value (first freq and last freq)\n # i = 0, (1, 256, 3) = [1, 4, ..., 253]\n # i = 1, (2, 256, 3) = [2, 5, ..., 254]\n # i = 2, (3, 256, 3) = [3, 6, ..., 255]\n freq_indices = torch.arange(idx + 1, n_freqs - 1, step=3, device=device)\n full_band_output_sub_batch = torch.index_select(full_band_output_sub_batch, dim=1, index=freq_indices)\n sub_band_output_sub_batch = torch.index_select(sub_band_output_sub_batch, dim=1, index=freq_indices)\n\n # ([30, 85, 1, 33 200], [30, 85, 1, 3, 200]) => [30, 85, 1, 36, 200]\n\n final_selected.append(torch.cat([sub_band_output_sub_batch, full_band_output_sub_batch], dim=-2))\n\n return torch.cat(final_selected, dim=0)\n\n @staticmethod\n def sband_forgetting_norm(input, train_sample_length):\n \"\"\"\n 与 forgetting norm相同,但使用拼接后模型的中间频带来计算均值\n 效果不好\n Args:\n input:\n train_sample_length:\n\n Returns:\n\n \"\"\"\n assert input.ndim == 3\n batch_size, n_freqs, n_frames = input.size()\n\n eps = 1e-10\n alpha = (train_sample_length - 1) / (train_sample_length + 1)\n mu = 0\n mu_list = []\n\n for idx in range(input.shape[-1]):\n if idx < train_sample_length:\n alp = torch.min(torch.tensor([(idx - 1) / (idx + 1), alpha]))\n mu = alp * mu + (1 - alp) * torch.mean(input[:, :, idx], dim=1).reshape(batch_size, 1) # [B, 1]\n else:\n mu = alpha * mu + (1 - alpha) * input[:, (n_freqs // 2 - 1), idx].reshape(batch_size, 1)\n\n mu_list.append(mu)\n\n # print(\"input\", input[:, :, idx].min(), input[:, :, idx].max(), input[:, :, idx].mean())\n # print(f\"alp {idx}: \", alp)\n # print(f\"mu {idx}: {mu[128, 0]}\")\n\n mu = torch.stack(mu_list, dim=-1) # [B, 1, T]\n input = input / (mu + eps)\n return input\n\n @staticmethod\n def forgetting_norm(input, sample_length_in_training):\n \"\"\"\n 输入为三维,通过不断估计邻近的均值来作为当前 norm 时的均值\n\n Args:\n input: [B, F, T]\n sample_length_in_training: 训练时的长度,用于计算平滑因子\n\n Returns:\n\n \"\"\"\n assert input.ndim == 3\n batch_size, n_freqs, n_frames = input.size()\n eps = 1e-10\n mu = 0\n alpha = (sample_length_in_training - 1) / (sample_length_in_training + 1)\n\n mu_list = []\n for idx in range(input.shape[-1]):\n if idx < sample_length_in_training:\n alp = torch.min(torch.tensor([(idx - 1) / (idx + 1), alpha]))\n mu = alp * mu + (1 - alp) * torch.mean(input[:, :, idx], dim=1).reshape(batch_size, 1) # [B, 1]\n else:\n current_frame_mu = torch.mean(input[:, :, idx], dim=1).reshape(batch_size, 1) # [B, 1]\n mu = alpha * mu + (1 - alpha) * current_frame_mu\n\n mu_list.append(mu)\n\n # print(\"input\", input[:, :, idx].min(), input[:, :, idx].max(), input[:, :, idx].mean())\n # print(f\"alp {idx}: \", alp)\n # print(f\"mu {idx}: {mu[128, 0]}\")\n\n mu = torch.stack(mu_list, dim=-1) # [B, 1, T]\n input = input / (mu + eps)\n return input\n\n @staticmethod\n def hybrid_norm(input, sample_length_in_training=192):\n \"\"\"\n Args:\n input: [B, F, T]\n sample_length_in_training:\n\n Returns:\n [B, F, T]\n \"\"\"\n assert input.ndim == 3\n device = input.device\n data_type = input.dtype\n batch_size, n_freqs, n_frames = input.size()\n eps = 1e-10\n\n mu = 0\n alpha = (sample_length_in_training - 1) / (sample_length_in_training + 1)\n mu_list = []\n for idx in range(input.shape[-1]):\n if idx < sample_length_in_training:\n alp = torch.min(torch.tensor([(idx - 1) / (idx + 1), alpha]))\n mu = alp * mu + (1 - alp) * torch.mean(input[:, :, idx], dim=1).reshape(batch_size, 1) # [B, 1]\n mu_list.append(mu)\n else:\n break\n initial_mu = torch.stack(mu_list, dim=-1) # [B, 1, T]\n\n step_sum = torch.sum(input, dim=1) # [B, T]\n cumulative_sum = torch.cumsum(step_sum, dim=-1) # [B, T]\n\n entry_count = torch.arange(n_freqs, n_freqs * n_frames + 1, n_freqs, dtype=data_type, device=device)\n entry_count = entry_count.reshape(1, n_frames) # [1, T]\n entry_count = entry_count.expand_as(cumulative_sum) # [1, T] => [B, T]\n\n cum_mean = cumulative_sum / entry_count # B, T\n\n cum_mean = cum_mean.reshape(batch_size, 1, n_frames) # [B, 1, T]\n\n # print(initial_mu[0, 0, :50])\n # print(\"-\"*60)\n # print(cum_mean[0, 0, :50])\n cum_mean[:, :, :sample_length_in_training] = initial_mu\n\n return input / (cum_mean + eps)\n\n @staticmethod\n def offline_laplace_norm(input):\n \"\"\"\n\n Args:\n input: [B, C, F, T]\n\n Returns:\n [B, C, F, T]\n \"\"\"\n # utterance-level mu\n mu = torch.mean(input, dim=(1, 2, 3), keepdim=True)\n\n normed = input / (mu + 1e-5)\n\n return normed\n\n @staticmethod\n def cumulative_laplace_norm(input):\n \"\"\"\n\n Args:\n input: [B, C, F, T]\n\n Returns:\n\n \"\"\"\n batch_size, num_channels, num_freqs, num_frames = input.size()\n input = input.reshape(batch_size * num_channels, num_freqs, num_frames)\n\n step_sum = torch.sum(input, dim=1) # [B * C, F, T] => [B, T]\n cumulative_sum = torch.cumsum(step_sum, dim=-1) # [B, T]\n\n entry_count = torch.arange(\n num_freqs,\n num_freqs * num_frames + 1,\n num_freqs,\n dtype=input.dtype,\n device=input.device\n )\n entry_count = entry_count.reshape(1, num_frames) # [1, T]\n entry_count = entry_count.expand_as(cumulative_sum) # [1, T] => [B, T]\n\n cumulative_mean = cumulative_sum / entry_count # B, T\n cumulative_mean = cumulative_mean.reshape(batch_size * num_channels, 1, num_frames)\n\n normed = input / (cumulative_mean + EPSILON)\n\n return normed.reshape(batch_size, num_channels, num_freqs, num_frames)\n\n @staticmethod\n def offline_gaussian_norm(input):\n \"\"\"\n Zero-Norm\n Args:\n input: [B, C, F, T]\n\n Returns:\n [B, C, F, T]\n \"\"\"\n mu = torch.mean(input, dim=(1, 2, 3), keepdim=True)\n std = torch.std(input, dim=(1, 2, 3), keepdim=True)\n\n normed = (input - mu) / (std + 1e-5)\n\n return normed\n\n @staticmethod\n def cumulative_layer_norm(input):\n \"\"\"\n Online zero-norm\n\n Args:\n input: [B, C, F, T]\n\n Returns:\n [B, C, F, T]\n \"\"\"\n batch_size, num_channels, num_freqs, num_frames = input.size()\n input = input.reshape(batch_size * num_channels, num_freqs, num_frames)\n\n step_sum = torch.sum(input, dim=1) # [B * C, F, T] => [B, T]\n step_pow_sum = torch.sum(torch.square(input), dim=1)\n\n cumulative_sum = torch.cumsum(step_sum, dim=-1) # [B, T]\n cumulative_pow_sum = torch.cumsum(step_pow_sum, dim=-1) # [B, T]\n\n entry_count = torch.arange(\n num_freqs,\n num_freqs * num_frames + 1,\n num_freqs,\n dtype=input.dtype,\n device=input.device\n )\n entry_count = entry_count.reshape(1, num_frames) # [1, T]\n entry_count = entry_count.expand_as(cumulative_sum) # [1, T] => [B, T]\n\n cumulative_mean = cumulative_sum / entry_count # [B, T]\n cumulative_var = (cumulative_pow_sum - 2 * cumulative_mean * cumulative_sum) / entry_count + cumulative_mean.pow(2) # [B, T]\n cumulative_std = torch.sqrt(cumulative_var + EPSILON) # [B, T]\n\n cumulative_mean = cumulative_mean.reshape(batch_size * num_channels, 1, num_frames)\n cumulative_std = cumulative_std.reshape(batch_size * num_channels, 1, num_frames)\n\n normed = (input - cumulative_mean) / cumulative_std\n\n return normed.reshape(batch_size, num_channels, num_freqs, num_frames)\n\n def norm_wrapper(self, norm_type: str):\n if norm_type == \"offline_laplace_norm\":\n norm = self.offline_laplace_norm\n elif norm_type == \"cumulative_laplace_norm\":\n norm = self.cumulative_laplace_norm\n elif norm_type == \"offline_gaussian_norm\":\n norm = self.offline_gaussian_norm\n elif norm_type == \"cumulative_layer_norm\":\n norm = self.cumulative_layer_norm\n else:\n raise NotImplementedError(\"You must set up a type of Norm. \"\n \"e.g. offline_laplace_norm, cumulative_laplace_norm, forgetting_norm, etc.\")\n return norm\n\n def weight_init(self, m):\n \"\"\"\n Usage:\n model = Model()\n model.apply(weight_init)\n \"\"\"\n if isinstance(m, nn.Conv1d):\n init.normal_(m.weight.data)\n if m.bias is not None:\n init.normal_(m.bias.data)\n elif isinstance(m, nn.Conv2d):\n init.xavier_normal_(m.weight.data)\n if m.bias is not None:\n init.normal_(m.bias.data)\n elif isinstance(m, nn.Conv3d):\n init.xavier_normal_(m.weight.data)\n if m.bias is not None:\n init.normal_(m.bias.data)\n elif isinstance(m, nn.ConvTranspose1d):\n init.normal_(m.weight.data)\n if m.bias is not None:\n init.normal_(m.bias.data)\n elif isinstance(m, nn.ConvTranspose2d):\n init.xavier_normal_(m.weight.data)\n if m.bias is not None:\n init.normal_(m.bias.data)\n elif isinstance(m, nn.ConvTranspose3d):\n init.xavier_normal_(m.weight.data)\n if m.bias is not None:\n init.normal_(m.bias.data)\n elif isinstance(m, nn.BatchNorm1d):\n init.normal_(m.weight.data, mean=1, std=0.02)\n init.constant_(m.bias.data, 0)\n elif isinstance(m, nn.BatchNorm2d):\n init.normal_(m.weight.data, mean=1, std=0.02)\n init.constant_(m.bias.data, 0)\n elif isinstance(m, nn.BatchNorm3d):\n init.normal_(m.weight.data, mean=1, std=0.02)\n init.constant_(m.bias.data, 0)\n elif isinstance(m, nn.Linear):\n init.xavier_normal_(m.weight.data)\n init.normal_(m.bias.data)\n elif isinstance(m, nn.LSTM):\n for param in m.parameters():\n if len(param.shape) >= 2:\n init.orthogonal_(param.data)\n else:\n init.normal_(param.data)\n elif isinstance(m, nn.LSTMCell):\n for param in m.parameters():\n if len(param.shape) >= 2:\n init.orthogonal_(param.data)\n else:\n init.normal_(param.data)\n elif isinstance(m, nn.GRU):\n for param in m.parameters():\n if len(param.shape) >= 2:\n init.orthogonal_(param.data)\n else:\n init.normal_(param.data)\n elif isinstance(m, nn.GRUCell):\n for param in m.parameters():\n if len(param.shape) >= 2:\n init.orthogonal_(param.data)\n else:\n init.normal_(param.data)\n"
] |
[
[
"torch.mean",
"torch.cat",
"torch.sqrt",
"torch.nn.init.constant_",
"torch.sum",
"torch.nn.init.xavier_normal_",
"torch.tensor",
"torch.std",
"torch.square",
"torch.nn.init.normal_",
"torch.nn.init.orthogonal_",
"torch.arange",
"torch.stack",
"torch.nn.functional.unfold",
"torch.cumsum",
"torch.index_select",
"torch.nn.functional.pad"
]
] |
Wilson-G/QUANTAXIS
|
[
"f98d09df834dc0c559ca1cac7a091cf2f26d6ad7"
] |
[
"QUANTAXIS/QAIndicator/base.py"
] |
[
"# coding:utf-8\n#\n# The MIT License (MIT)\n#\n# Copyright (c) 2016-2019 yutiansut/QUANTAXIS\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\nfrom functools import reduce\nimport math\nimport numpy as np\nimport pandas as pd\n\n\n\"\"\"\nSeries 类\n\n这个是下面以DataFrame为输入的基础函数\nreturn pd.Series format\n\"\"\"\n\n\ndef EMA(Series, N):\n return pd.Series.ewm(Series, span=N, min_periods=N - 1, adjust=True).mean()\n\n\ndef MA(Series, N):\n return pd.Series.rolling(Series, N).mean()\n\n# 威廉SMA 参考https://www.joinquant.com/post/867\n\n\ndef SMA(Series, N, M=1):\n \"\"\"\n 威廉SMA算法\n\n 本次修正主要是对于返回值的优化,现在的返回值会带上原先输入的索引index\n 2018/5/3\n @yutiansut\n \"\"\"\n ret = []\n i = 1\n length = len(Series)\n # 跳过X中前面几个 nan 值\n while i < length:\n if np.isnan(Series.iloc[i]):\n i += 1\n else:\n break\n preY = Series.iloc[i] # Y'\n ret.append(preY)\n while i < length:\n Y = (M * Series.iloc[i] + (N - M) * preY) / float(N)\n ret.append(Y)\n preY = Y\n i += 1\n return pd.Series(ret, index=Series.tail(len(ret)).index)\n\n\ndef DIFF(Series, N=1):\n return pd.Series(Series).diff(N)\n\n\ndef HHV(Series, N):\n return pd.Series(Series).rolling(N).max()\n\n\ndef LLV(Series, N):\n return pd.Series(Series).rolling(N).min()\n\n\ndef SUM(Series, N):\n return pd.Series.rolling(Series, N).sum()\n\n\ndef ABS(Series):\n return abs(Series)\n\n\ndef MAX(A, B):\n var = IF(A > B, A, B)\n return var\n\n\ndef MIN(A, B):\n var = IF(A < B, A, B)\n return var\n\n\ndef SINGLE_CROSS(A, B):\n if A.iloc[-2] < B.iloc[-2] and A.iloc[-1] > B.iloc[-1]:\n return True\n else:\n return False\n\n\ndef CROSS(A, B):\n \"\"\"A<B then A>B A上穿B B下穿A\n\n Arguments:\n A {[type]} -- [description]\n B {[type]} -- [description]\n\n Returns:\n [type] -- [description]\n \"\"\"\n\n var = np.where(A < B, 1, 0)\n try:\n index = A.index\n except:\n index = B.index\n return (pd.Series(var, index=index).diff() < 0).apply(int)\n\n\ndef FILTER(COND, N):\n\n k1 = pd.Series(np.where(COND, 1, 0), index=COND.index)\n idx = k1[k1 == 1].index.codes[0]\n needfilter = pd.Series(idx, index=idx)\n afterfilter = needfilter.diff().apply(lambda x: False if x < N else True)\n k1.iloc[afterfilter[afterfilter].index] = 2\n return k1.apply(lambda x: 1 if x == 2 else 0)\n\n\ndef COUNT(COND, N):\n \"\"\"\n 2018/05/23 修改\n\n 参考https://github.com/QUANTAXIS/QUANTAXIS/issues/429\n\n 现在返回的是series\n \"\"\"\n return pd.Series(np.where(COND, 1, 0), index=COND.index).rolling(N).sum()\n\n\ndef IF(COND, V1, V2):\n var = np.where(COND, V1, V2)\n try:\n try:\n index = V1.index\n except:\n index = COND.index\n except:\n index = V2.index\n return pd.Series(var, index=index)\n\n\ndef IFAND(COND1, COND2, V1, V2):\n var = np.where(np.logical_and(COND1, COND2), V1, V2)\n return pd.Series(var, index=V1.index)\n\n\ndef IFOR(COND1, COND2, V1, V2):\n var = np.where(np.logical_or(COND1, COND2), V1, V2)\n return pd.Series(var, index=V1.index)\n\n\ndef REF(Series, N):\n\n return Series.shift(N)\n\n\ndef LAST(COND, N1, N2):\n \"\"\"表达持续性\n 从前N1日到前N2日一直满足COND条件\n\n Arguments:\n COND {[type]} -- [description]\n N1 {[type]} -- [description]\n N2 {[type]} -- [description]\n \"\"\"\n N2 = 1 if N2 == 0 else N2\n assert N2 > 0\n assert N1 > N2\n return COND.iloc[-N1:-N2].all()\n\n\ndef STD(Series, N):\n return pd.Series.rolling(Series, N).std()\n\n\ndef AVEDEV(Series, N):\n \"\"\"\n 平均绝对偏差 mean absolute deviation\n 修正: 2018-05-25 \n\n 之前用mad的计算模式依然返回的是单值\n \"\"\"\n return Series.rolling(N).apply(lambda x: (np.abs(x - x.mean())).mean(), raw=True)\n\n\ndef MACD(Series, FAST, SLOW, MID):\n \"\"\"macd指标 仅适用于Series\n 对于DATAFRAME的应用请使用QA_indicator_macd\n \"\"\"\n EMAFAST = EMA(Series, FAST)\n EMASLOW = EMA(Series, SLOW)\n DIFF = EMAFAST - EMASLOW\n DEA = EMA(DIFF, MID)\n MACD = (DIFF - DEA) * 2\n DICT = {'DIFF': DIFF, 'DEA': DEA, 'MACD': MACD}\n VAR = pd.DataFrame(DICT)\n return VAR\n\n\ndef BBIBOLL(Series, N1, N2, N3, N4, N, M): # 多空布林线\n\n bbiboll = BBI(Series, N1, N2, N3, N4)\n UPER = bbiboll + M * STD(bbiboll, N)\n DOWN = bbiboll - M * STD(bbiboll, N)\n DICT = {'BBIBOLL': bbiboll, 'UPER': UPER, 'DOWN': DOWN}\n VAR = pd.DataFrame(DICT)\n return VAR\n\n\ndef BBI(Series, N1, N2, N3, N4):\n '多空指标'\n\n bbi = (MA(Series, N1) + MA(Series, N2) +\n MA(Series, N3) + MA(Series, N4)) / 4\n DICT = {'BBI': bbi}\n VAR = pd.DataFrame(DICT)\n return VAR\n\n\ndef BARLAST(cond, yes=True):\n \"\"\"支持MultiIndex的cond和DateTimeIndex的cond\n 条件成立 yes= True 或者 yes=1 根据不同的指标自己定\n\n 最后一次条件成立 到 当前到周期数\n\n Arguments:\n cond {[type]} -- [description]\n \"\"\"\n if isinstance(cond.index, pd.MultiIndex):\n return len(cond)-cond.index.levels[0].tolist().index(cond[cond == yes].index[-1][0])-1\n elif isinstance(cond.index, pd.DatetimeIndex):\n return len(cond)-cond.index.tolist().index(cond[cond == yes].index[-1])-1\n\n\ndef BARLAST_EXIST(cond, yes=True):\n \"\"\"\n 上一次条件成立 持续到当前到数量\n\n\n 支持MultiIndex的cond和DateTimeIndex的cond\n 条件成立 yes= True 或者 yes=1 根据不同的指标自己定\n\n Arguments:\n cond {[type]} -- [description]\n \"\"\"\n if isinstance(cond.index, pd.MultiIndex):\n return len(cond)-cond.index.levels[0].tolist().index(cond[cond != yes].index[-1][0])-1\n elif isinstance(cond.index, pd.DatetimeIndex):\n return len(cond)-cond.index.tolist().index(cond[cond != yes].index[-1])-1\n\ndef XARROUND(x, y): return np.round(\n y*(round(x/y-math.floor(x/y)+0.00000000001) + math.floor(x/y)), 2)\n\n\ndef RENKO(Series, N, condensed=True):\n\n last_price = Series[0]\n chart = [last_price]\n for price in Series:\n bricks = math.floor(abs(price-last_price)/N)\n if bricks == 0:\n if condensed:\n chart.append(chart[-1])\n continue\n sign = int(np.sign(price-last_price))\n chart += [sign*(last_price+(sign*N*x)) for x in range(1, bricks+1)]\n last_price = abs(chart[-1])\n\n return pd.Series(chart)\n\n\n\ndef RENKOP(Series, N, condensed=True):\n last_price = Series[0]\n chart = [last_price]\n for price in Series:\n inc = (price-last_price)/last_price\n #print(inc)\n if abs(inc) < N:\n # if condensed:\n # chart.append(chart[-1])\n continue\n\n sign = int(np.sign(price-last_price))\n bricks = math.floor(inc/N)\n #print(bricks)\n #print((N * (price-last_price)) / inc)\n step = math.floor((N * (price-last_price)) / inc)\n print(step)\n #print(sign)\n chart += [sign*(last_price+(sign*step*x))\n for x in range(1, abs(bricks)+1)]\n last_price = abs(chart[-1])\n return pd.Series(chart)"
] |
[
[
"pandas.Series.rolling",
"pandas.Series",
"numpy.isnan",
"pandas.DataFrame",
"numpy.logical_or",
"pandas.Series.ewm",
"numpy.sign",
"numpy.logical_and",
"numpy.where"
]
] |
ppwadhwa/napari
|
[
"25756da88a2ee09e8f6723994685e0aa6fbbb5af"
] |
[
"napari/components/viewer_model.py"
] |
[
"from __future__ import annotations\n\nimport inspect\nimport itertools\nimport os\nimport warnings\nfrom functools import lru_cache\nfrom pathlib import Path\nfrom typing import (\n TYPE_CHECKING,\n Any,\n Dict,\n List,\n Optional,\n Sequence,\n Set,\n Tuple,\n Union,\n)\n\nimport numpy as np\nfrom pydantic import Extra, Field, validator\n\nfrom .. import layers\nfrom ..layers import Image, Layer\nfrom ..layers.image._image_utils import guess_labels\nfrom ..layers.utils.stack_utils import split_channels\nfrom ..types import PathOrPaths\nfrom ..utils._register import create_func as create_add_method\nfrom ..utils.colormaps import ensure_colormap\nfrom ..utils.events import Event, EventedModel, disconnect_events\nfrom ..utils.events.event import WarningEmitter\nfrom ..utils.key_bindings import KeymapProvider\nfrom ..utils.misc import is_sequence\nfrom ..utils.mouse_bindings import MousemapProvider\nfrom ..utils.theme import available_themes\nfrom ..utils.translations import trans\nfrom ._viewer_mouse_bindings import dims_scroll\nfrom .axes import Axes\nfrom .camera import Camera\nfrom .cursor import Cursor\nfrom .dims import Dims\nfrom .grid import GridCanvas\nfrom .layerlist import LayerList\nfrom .scale_bar import ScaleBar\n\nDEFAULT_THEME = 'dark'\nEXCLUDE_DICT = {\n 'keymap',\n '_mouse_wheel_gen',\n '_mouse_drag_gen',\n '_persisted_mouse_event',\n 'mouse_move_callbacks',\n 'mouse_drag_callbacks',\n 'mouse_wheel_callbacks',\n}\nEXCLUDE_JSON = EXCLUDE_DICT.union({'layers', 'active_layer'})\n\nif TYPE_CHECKING:\n from ..types import FullLayerData, LayerData\n\n\n# KeymapProvider & MousemapProvider should eventually be moved off the ViewerModel\nclass ViewerModel(KeymapProvider, MousemapProvider, EventedModel):\n \"\"\"Viewer containing the rendered scene, layers, and controlling elements\n including dimension sliders, and control bars for color limits.\n\n Parameters\n ----------\n title : string\n The title of the viewer window.\n ndisplay : {2, 3}\n Number of displayed dimensions.\n order : tuple of int\n Order in which dimensions are displayed where the last two or last\n three dimensions correspond to row x column or plane x row x column if\n ndisplay is 2 or 3.\n axis_labels : list of str\n Dimension names.\n\n Attributes\n ----------\n window : Window\n Parent window.\n layers : LayerList\n List of contained layers.\n dims : Dimensions\n Contains axes, indices, dimensions and sliders.\n \"\"\"\n\n # Using allow_mutation=False means these attributes aren't settable and don't\n # have an event emitter associated with them\n axes: Axes = Field(default_factory=Axes, allow_mutation=False)\n camera: Camera = Field(default_factory=Camera, allow_mutation=False)\n cursor: Cursor = Field(default_factory=Cursor, allow_mutation=False)\n dims: Dims = Field(default_factory=Dims, allow_mutation=False)\n grid: GridCanvas = Field(default_factory=GridCanvas, allow_mutation=False)\n layers: LayerList = Field(\n default_factory=LayerList, allow_mutation=False\n ) # Need to create custom JSON encoder for layer!\n scale_bar: ScaleBar = Field(default_factory=ScaleBar, allow_mutation=False)\n\n help: str = ''\n status: str = 'Ready'\n theme: str = DEFAULT_THEME\n title: str = 'napari'\n\n # 2-tuple indicating height and width\n _canvas_size: Tuple[int, int] = (600, 800)\n\n def __init__(self, title='napari', ndisplay=2, order=(), axis_labels=()):\n # allow extra attributes during model initialization, useful for mixins\n self.__config__.extra = Extra.allow\n super().__init__(\n title=title,\n dims={\n 'axis_labels': axis_labels,\n 'ndisplay': ndisplay,\n 'order': order,\n },\n )\n self.__config__.extra = Extra.ignore\n\n # Add extra events - ideally these will be removed too!\n self.events.add(layers_change=Event, reset_view=Event)\n\n # Connect events\n self.grid.events.connect(self.reset_view)\n self.grid.events.connect(self._on_grid_change)\n self.dims.events.ndisplay.connect(self._update_layers)\n self.dims.events.ndisplay.connect(self.reset_view)\n self.dims.events.order.connect(self._update_layers)\n self.dims.events.order.connect(self.reset_view)\n self.dims.events.current_step.connect(self._update_layers)\n self.cursor.events.position.connect(self._on_cursor_position_change)\n self.layers.events.inserted.connect(self._on_add_layer)\n self.layers.events.removed.connect(self._on_remove_layer)\n self.layers.events.reordered.connect(self._on_grid_change)\n self.layers.events.reordered.connect(self._on_layers_change)\n self.layers.selection.events.active.connect(self._on_active_layer)\n\n # Add mouse callback\n self.mouse_wheel_callbacks.append(dims_scroll)\n\n self.events.add(\n active_layer=WarningEmitter(\n \"'viewer.events.active_layer' is deprecated and will be \"\n \"removed in napari v0.4.9, use \"\n \"'viewer.layers.selection.events.active' instead\",\n type='active_layer',\n )\n )\n\n @validator('theme')\n def _valid_theme(cls, v):\n themes = available_themes()\n if v not in available_themes():\n raise ValueError(\n f\"Theme '{v}' not found; \" f\"options are {themes}.\"\n )\n return v\n\n def json(self, **kwargs):\n \"\"\"Serialize to json.\"\"\"\n # Manually exclude the layer list and active layer which cannot be serialized at this point\n # and mouse and keybindings don't belong on model\n # https://github.com/samuelcolvin/pydantic/pull/2231\n # https://github.com/samuelcolvin/pydantic/issues/660#issuecomment-642211017\n exclude = kwargs.pop('exclude', set())\n exclude = exclude.union(EXCLUDE_JSON)\n return super().json(exclude=exclude, **kwargs)\n\n def dict(self, **kwargs):\n \"\"\"Convert to a dictionaty.\"\"\"\n # Manually exclude the layer list and active layer which cannot be serialized at this point\n # and mouse and keybindings don't belong on model\n # https://github.com/samuelcolvin/pydantic/pull/2231\n # https://github.com/samuelcolvin/pydantic/issues/660#issuecomment-642211017\n exclude = kwargs.pop('exclude', set())\n exclude = exclude.union(EXCLUDE_DICT)\n return super().dict(exclude=exclude, **kwargs)\n\n def __hash__(self):\n return id(self)\n\n def __str__(self):\n \"\"\"Simple string representation\"\"\"\n return f'napari.Viewer: {self.title}'\n\n @property\n def _sliced_extent_world(self) -> np.ndarray:\n \"\"\"Extent of layers in world coordinates after slicing.\n\n D is either 2 or 3 depending on if the displayed data is 2D or 3D.\n\n Returns\n -------\n sliced_extent_world : array, shape (2, D)\n \"\"\"\n if len(self.layers) == 0 and self.dims.ndim != 2:\n # If no data is present and dims model has not been reset to 0\n # than someone has passed more than two axis labels which are\n # being saved and so default values are used.\n return np.vstack(\n [np.zeros(self.dims.ndim), np.repeat(512, self.dims.ndim)]\n )\n else:\n return self.layers.extent.world[:, self.dims.displayed]\n\n def reset_view(self, event=None):\n \"\"\"Reset the camera view.\"\"\"\n\n extent = self._sliced_extent_world\n scene_size = extent[1] - extent[0]\n corner = extent[0]\n grid_size = list(self.grid.actual_shape(len(self.layers)))\n if len(scene_size) > len(grid_size):\n grid_size = [1] * (len(scene_size) - len(grid_size)) + grid_size\n size = np.multiply(scene_size, grid_size)\n center = np.add(corner, np.divide(size, 2))[-self.dims.ndisplay :]\n center = [0] * (self.dims.ndisplay - len(center)) + list(center)\n self.camera.center = center\n # zoom is definied as the number of canvas pixels per world pixel\n # The default value used below will zoom such that the whole field\n # of view will occupy 95% of the canvas on the most filled axis\n if np.max(size) == 0:\n self.camera.zoom = 0.95 * np.min(self._canvas_size)\n else:\n self.camera.zoom = (\n 0.95 * np.min(self._canvas_size) / np.max(size[-2:])\n )\n self.camera.angles = (0, 0, 90)\n\n # Emit a reset view event, which is no longer used internally, but\n # which maybe useful for building on napari.\n self.events.reset_view(\n center=self.camera.center,\n zoom=self.camera.zoom,\n angles=self.camera.angles,\n )\n\n def _new_labels(self):\n \"\"\"Create new labels layer filling full world coordinates space.\"\"\"\n extent = self.layers.extent.world\n scale = self.layers.extent.step\n scene_size = extent[1] - extent[0]\n corner = extent[0]\n shape = [\n np.round(s / sc).astype('int') + 1 if s > 0 else 1\n for s, sc in zip(scene_size, scale)\n ]\n empty_labels = np.zeros(shape, dtype=int)\n self.add_labels(empty_labels, translate=np.array(corner), scale=scale)\n\n def _update_layers(self, event=None, layers=None):\n \"\"\"Updates the contained layers.\n\n Parameters\n ----------\n layers : list of napari.layers.Layer, optional\n List of layers to update. If none provided updates all.\n \"\"\"\n layers = layers or self.layers\n for layer in layers:\n layer._slice_dims(\n self.dims.point, self.dims.ndisplay, self.dims.order\n )\n\n def _on_active_layer(self, event):\n \"\"\"Update viewer state for a new active layer.\"\"\"\n active_layer = event.value\n if active_layer is None:\n self.help = ''\n self.cursor.style = 'standard'\n self.camera.interactive = True\n else:\n self.help = active_layer.help\n self.cursor.style = active_layer.cursor\n self.cursor.size = active_layer.cursor_size\n self.camera.interactive = active_layer.interactive\n\n @property\n def active_layer(self):\n warnings.warn(\n \"'viewer.active_layer' is deprecated and will be removed in napari\"\n \" v0.4.9. Please use 'viewer.layers.selection.active' instead.\",\n category=FutureWarning,\n stacklevel=2,\n )\n return self.layers.selection.active\n\n def __setattr__(self, name: str, value: Any) -> None:\n # this method is only for the deprecation warning, because pydantic\n # prevents using @active_layer.setter\n if name != 'active_layer':\n return super().__setattr__(name, value)\n\n warnings.warn(\n \"'viewer.active_layer' is deprecated and will be removed in napari\"\n \" v0.4.9. Please use 'viewer.layers.selection.active' instead.\",\n category=FutureWarning,\n stacklevel=2,\n )\n self.layers.selection.active = value\n\n def _on_layers_change(self, event):\n if len(self.layers) == 0:\n self.dims.ndim = 2\n self.dims.reset()\n else:\n extent = self.layers.extent\n world = extent.world\n ss = extent.step\n ndim = world.shape[1]\n self.dims.ndim = ndim\n for i in range(ndim):\n self.dims.set_range(i, (world[0, i], world[1, i], ss[i]))\n self.cursor.position = (0,) * self.dims.ndim\n self.events.layers_change()\n\n def _update_interactive(self, event):\n \"\"\"Set the viewer interactivity with the `event.interactive` bool.\"\"\"\n self.camera.interactive = event.interactive\n\n def _update_cursor(self, event):\n \"\"\"Set the viewer cursor with the `event.cursor` string.\"\"\"\n self.cursor.style = event.cursor\n\n def _update_cursor_size(self, event):\n \"\"\"Set the viewer cursor_size with the `event.cursor_size` int.\"\"\"\n self.cursor.size = event.cursor_size\n\n def _on_cursor_position_change(self, event):\n \"\"\"Set the layer cursor position.\"\"\"\n with warnings.catch_warnings():\n # Catch the deprecation warning on layer.position\n warnings.filterwarnings(\n 'ignore', message='layer.position is deprecated'\n )\n for layer in self.layers:\n layer.position = self.cursor.position\n\n # Update status and help bar based on active layer\n active = self.layers.selection.active\n if active is not None:\n self.status = active.get_status(self.cursor.position, world=True)\n self.help = active.help\n\n def _on_grid_change(self, event):\n \"\"\"Arrange the current layers is a 2D grid.\"\"\"\n extent = self._sliced_extent_world\n n_layers = len(self.layers)\n for i, layer in enumerate(self.layers):\n i_row, i_column = self.grid.position(n_layers - 1 - i, n_layers)\n self._subplot(layer, (i_row, i_column), extent)\n\n def _subplot(self, layer, position, extent):\n \"\"\"Shift a layer to a specified position in a 2D grid.\n\n Parameters\n ----------\n layer : napari.layers.Layer\n Layer that is to be moved.\n position : 2-tuple of int\n New position of layer in grid.\n extent : array, shape (2, D)\n Extent of the world.\n \"\"\"\n scene_shift = extent[1] - extent[0] + 1\n translate_2d = np.multiply(scene_shift[-2:], position)\n translate = [0] * layer.ndim\n translate[-2:] = translate_2d\n layer.translate_grid = translate\n\n @property\n def experimental(self):\n \"\"\"Experimental commands for IPython console.\n\n For example run \"viewer.experimental.cmds.loader.help\".\n \"\"\"\n from .experimental.commands import ExperimentalNamespace\n\n return ExperimentalNamespace(self.layers)\n\n def _on_add_layer(self, event):\n \"\"\"Connect new layer events.\n\n Parameters\n ----------\n event : :class:`napari.layers.Layer`\n Layer to add.\n \"\"\"\n layer = event.value\n\n # Connect individual layer events to viewer events\n # TODO: in a future PR, we should now be able to connect viewer *only*\n # to viewer.layers.events... and avoid direct viewer->layer connections\n layer.events.interactive.connect(self._update_interactive)\n layer.events.cursor.connect(self._update_cursor)\n layer.events.cursor_size.connect(self._update_cursor_size)\n layer.events.data.connect(self._on_layers_change)\n layer.events.scale.connect(self._on_layers_change)\n layer.events.translate.connect(self._on_layers_change)\n layer.events.rotate.connect(self._on_layers_change)\n layer.events.shear.connect(self._on_layers_change)\n layer.events.affine.connect(self._on_layers_change)\n layer.events.name.connect(self.layers._update_name)\n\n # Update dims and grid model\n self._on_layers_change(None)\n self._on_grid_change(None)\n # Slice current layer based on dims\n self._update_layers(layers=[layer])\n\n if len(self.layers) == 1:\n self.reset_view()\n\n def _on_remove_layer(self, event):\n \"\"\"Disconnect old layer events.\n\n Parameters\n ----------\n event : napari.utils.event.Event\n Event which will remove a layer.\n\n Returns\n -------\n layer : :class:`napari.layers.Layer` or list\n The layer that was added (same as input).\n \"\"\"\n layer = event.value\n\n # Disconnect all connections from layer\n disconnect_events(layer.events, self)\n disconnect_events(layer.events, self.layers)\n\n self._on_layers_change(None)\n self._on_grid_change(None)\n\n def add_layer(self, layer: Layer) -> Layer:\n \"\"\"Add a layer to the viewer.\n\n Parameters\n ----------\n layer : :class:`napari.layers.Layer`\n Layer to add.\n\n Returns\n -------\n layer : :class:`napari.layers.Layer` or list\n The layer that was added (same as input).\n \"\"\"\n # Adding additional functionality inside `add_layer`\n # should be avoided to keep full functionality\n # from adding a layer through the `layers.append`\n # method\n self.layers.append(layer)\n return layer\n\n def add_image(\n self,\n data=None,\n *,\n channel_axis=None,\n rgb=None,\n colormap=None,\n contrast_limits=None,\n gamma=1,\n interpolation='nearest',\n rendering='mip',\n iso_threshold=0.5,\n attenuation=0.05,\n name=None,\n metadata=None,\n scale=None,\n translate=None,\n rotate=None,\n shear=None,\n affine=None,\n opacity=1,\n blending=None,\n visible=True,\n multiscale=None,\n ) -> Union[Image, List[Image]]:\n \"\"\"Add an image layer to the layer list.\n\n Parameters\n ----------\n data : array or list of array\n Image data. Can be N dimensional. If the last dimension has length\n 3 or 4 can be interpreted as RGB or RGBA if rgb is `True`. If a\n list and arrays are decreasing in shape then the data is treated as\n a multiscale image.\n channel_axis : int, optional\n Axis to expand image along. If provided, each channel in the data\n will be added as an individual image layer. In channel_axis mode,\n all other parameters MAY be provided as lists, and the Nth value\n will be applied to the Nth channel in the data. If a single value\n is provided, it will be broadcast to all Layers.\n rgb : bool or list\n Whether the image is rgb RGB or RGBA. If not specified by user and\n the last dimension of the data has length 3 or 4 it will be set as\n `True`. If `False` the image is interpreted as a luminance image.\n If a list then must be same length as the axis that is being\n expanded as channels.\n colormap : str, napari.utils.Colormap, tuple, dict, list\n Colormaps to use for luminance images. If a string must be the name\n of a supported colormap from vispy or matplotlib. If a tuple the\n first value must be a string to assign as a name to a colormap and\n the second item must be a Colormap. If a dict the key must be a\n string to assign as a name to a colormap and the value must be a\n Colormap. If a list then must be same length as the axis that is\n being expanded as channels, and each colormap is applied to each\n new image layer.\n contrast_limits : list (2,)\n Color limits to be used for determining the colormap bounds for\n luminance images. If not passed is calculated as the min and max of\n the image. If list of lists then must be same length as the axis\n that is being expanded and then each colormap is applied to each\n image.\n gamma : list, float\n Gamma correction for determining colormap linearity. Defaults to 1.\n If a list then must be same length as the axis that is being\n expanded as channels.\n interpolation : str or list\n Interpolation mode used by vispy. Must be one of our supported\n modes. If a list then must be same length as the axis that is being\n expanded as channels.\n rendering : str or list\n Rendering mode used by vispy. Must be one of our supported\n modes. If a list then must be same length as the axis that is being\n expanded as channels.\n iso_threshold : float or list\n Threshold for isosurface. If a list then must be same length as the\n axis that is being expanded as channels.\n attenuation : float or list\n Attenuation rate for attenuated maximum intensity projection. If a\n list then must be same length as the axis that is being expanded as\n channels.\n name : str or list of str\n Name of the layer. If a list then must be same length as the axis\n that is being expanded as channels.\n metadata : dict or list of dict\n Layer metadata. If a list then must be a list of dicts with the\n same length as the axis that is being expanded as channels.\n scale : tuple of float or list\n Scale factors for the layer. If a list then must be a list of\n tuples of float with the same length as the axis that is being\n expanded as channels.\n translate : tuple of float or list\n Translation values for the layer. If a list then must be a list of\n tuples of float with the same length as the axis that is being\n expanded as channels.\n rotate : float, 3-tuple of float, n-D array or list.\n If a float convert into a 2D rotation matrix using that value as an\n angle. If 3-tuple convert into a 3D rotation matrix, using a yaw,\n pitch, roll convention. Otherwise assume an nD rotation. Angles are\n assumed to be in degrees. They can be converted from radians with\n np.degrees if needed. If a list then must have same length as\n the axis that is being expanded as channels.\n shear : 1-D array or list.\n A vector of shear values for an upper triangular n-D shear matrix.\n If a list then must have same length as the axis that is being\n expanded as channels.\n affine : n-D array or napari.utils.transforms.Affine\n (N+1, N+1) affine transformation matrix in homogeneous coordinates.\n The first (N, N) entries correspond to a linear transform and\n the final column is a lenght N translation vector and a 1 or a napari\n AffineTransform object. If provided then translate, scale, rotate, and\n shear values are ignored.\n opacity : float or list\n Opacity of the layer visual, between 0.0 and 1.0. If a list then\n must be same length as the axis that is being expanded as channels.\n blending : str or list\n One of a list of preset blending modes that determines how RGB and\n alpha values of the layer visual get mixed. Allowed values are\n {'opaque', 'translucent', and 'additive'}. If a list then\n must be same length as the axis that is being expanded as channels.\n visible : bool or list of bool\n Whether the layer visual is currently being displayed.\n If a list then must be same length as the axis that is\n being expanded as channels.\n multiscale : bool\n Whether the data is a multiscale image or not. Multiscale data is\n represented by a list of array like image data. If not specified by\n the user and if the data is a list of arrays that decrease in shape\n then it will be taken to be multiscale. The first image in the list\n should be the largest.\n\n Returns\n -------\n layer : :class:`napari.layers.Image` or list\n The newly-created image layer or list of image layers.\n \"\"\"\n\n if colormap is not None:\n # standardize colormap argument(s) to Colormaps, and make sure they\n # are in AVAILABLE_COLORMAPS. This will raise one of many various\n # errors if the colormap argument is invalid. See\n # ensure_colormap for details\n if isinstance(colormap, list):\n colormap = [ensure_colormap(c) for c in colormap]\n else:\n colormap = ensure_colormap(colormap)\n\n # doing this here for IDE/console autocompletion in add_image function.\n kwargs = {\n 'rgb': rgb,\n 'colormap': colormap,\n 'contrast_limits': contrast_limits,\n 'gamma': gamma,\n 'interpolation': interpolation,\n 'rendering': rendering,\n 'iso_threshold': iso_threshold,\n 'attenuation': attenuation,\n 'name': name,\n 'metadata': metadata,\n 'scale': scale,\n 'translate': translate,\n 'rotate': rotate,\n 'shear': shear,\n 'affine': affine,\n 'opacity': opacity,\n 'blending': blending,\n 'visible': visible,\n 'multiscale': multiscale,\n }\n\n # these arguments are *already* iterables in the single-channel case.\n iterable_kwargs = {\n 'scale',\n 'translate',\n 'rotate',\n 'shear',\n 'affine',\n 'contrast_limits',\n 'metadata',\n }\n\n if channel_axis is None:\n kwargs['colormap'] = kwargs['colormap'] or 'gray'\n kwargs['blending'] = kwargs['blending'] or 'translucent'\n # Helpful message if someone tries to add mulit-channel kwargs,\n # but forget the channel_axis arg\n for k, v in kwargs.items():\n if k not in iterable_kwargs and is_sequence(v):\n raise TypeError(\n f\"Received sequence for argument '{k}', \"\n \"did you mean to specify a 'channel_axis'? \"\n )\n layer = Image(data, **kwargs)\n self.layers.append(layer)\n\n return layer\n else:\n layerdata_list = split_channels(data, channel_axis, **kwargs)\n\n layer_list = list()\n for image, i_kwargs, _ in layerdata_list:\n layer = Image(image, **i_kwargs)\n self.layers.append(layer)\n layer_list.append(layer)\n\n return layer_list\n\n def open_sample(\n self,\n plugin: str,\n sample: str,\n reader_plugin: Optional[str] = None,\n **kwargs,\n ):\n \"\"\"Open `sample` from `plugin` and add it to the viewer.\n\n To see all available samples registered by plugins, use\n :func:`napari.plugins.available_samples`\n\n Parameters\n ----------\n plugin : str\n name of a plugin providing a sample\n sample : str\n name of the sample\n reader_plugin : str, optional\n reader plugin to pass to viewer.open (only used if the sample data\n is a string). by default None.\n\n **kwargs:\n additional kwargs will be passed to the sample data loader provided\n by `plugin`. Use of **kwargs may raise an error if the kwargs do\n not match the sample data loader.\n\n Raises\n ------\n KeyError\n If `plugin` does not provide a sample named `sample`.\n \"\"\"\n from ..plugins import _sample_data, available_samples\n\n try:\n data = _sample_data[plugin][sample]['data']\n except KeyError:\n samples = available_samples()\n msg = trans._(\n f\"Plugin {plugin!r} does not provide sample data \"\n f\"named {sample!r}. \"\n )\n if samples:\n msg += trans._('Available samples include: {samples}').format(\n samples=samples\n )\n else:\n msg += trans._(\"No plugin samples have been registered.\")\n raise KeyError(msg)\n\n if callable(data):\n for datum in data(**kwargs):\n self._add_layer_from_data(*datum)\n elif isinstance(data, (str, Path)):\n self.open(data, plugin=reader_plugin)\n else:\n raise TypeError(\n 'Got unexpected type for sample '\n f'({plugin!r}, {sample!r}): {type(data)}'\n )\n\n def open(\n self,\n path: PathOrPaths,\n *,\n stack: bool = False,\n plugin: Optional[str] = None,\n layer_type: Optional[str] = None,\n **kwargs,\n ) -> List[Layer]:\n \"\"\"Open a path or list of paths with plugins, and add layers to viewer.\n\n A list of paths will be handed one-by-one to the napari_get_reader hook\n if stack is False, otherwise the full list is passed to each plugin\n hook.\n\n Parameters\n ----------\n path : str or list of str\n A filepath, directory, or URL (or a list of any) to open.\n stack : bool, optional\n If a list of strings is passed and ``stack`` is ``True``, then the\n entire list will be passed to plugins. It is then up to individual\n plugins to know how to handle a list of paths. If ``stack`` is\n ``False``, then the ``path`` list is broken up and passed to plugin\n readers one by one. by default False.\n plugin : str, optional\n Name of a plugin to use. If provided, will force ``path`` to be\n read with the specified ``plugin``. If the requested plugin cannot\n read ``path``, an exception will be raised.\n layer_type : str, optional\n If provided, will force data read from ``path`` to be passed to the\n corresponding ``add_<layer_type>`` method (along with any\n additional) ``kwargs`` provided to this function. This *may*\n result in exceptions if the data returned from the path is not\n compatible with the layer_type.\n **kwargs\n All other keyword arguments will be passed on to the respective\n ``add_layer`` method.\n\n Returns\n -------\n layers : list\n A list of any layers that were added to the viewer.\n \"\"\"\n paths = [path] if isinstance(path, (Path, str)) else path\n paths = [os.fspath(path) for path in paths] # PathObjects -> str\n if not isinstance(paths, (tuple, list)):\n raise ValueError(\n \"'path' argument must be a string, list, or tuple\"\n )\n\n if stack:\n return self._add_layers_with_plugins(\n paths, kwargs, plugin=plugin, layer_type=layer_type\n )\n\n added: List[Layer] = [] # for layers that get added\n for _path in paths:\n added.extend(\n self._add_layers_with_plugins(\n _path, kwargs, plugin=plugin, layer_type=layer_type\n )\n )\n return added\n\n def _add_layers_with_plugins(\n self,\n path_or_paths: Union[str, Sequence[str]],\n kwargs: Optional[dict] = None,\n plugin: Optional[str] = None,\n layer_type: Optional[str] = None,\n ) -> List[Layer]:\n \"\"\"Load a path or a list of paths into the viewer using plugins.\n\n This function is mostly called from self.open_path, where the ``stack``\n argument determines whether a list of strings is handed to plugins one\n at a time, or en-masse.\n\n Parameters\n ----------\n path_or_paths : str or list of str\n A filepath, directory, or URL (or a list of any) to open. If a\n list, the assumption is that the list is to be treated as a stack.\n kwargs : dict, optional\n keyword arguments that will be used to overwrite any of those that\n are returned in the meta dict from plugins.\n plugin : str, optional\n Name of a plugin to use. If provided, will force ``path`` to be\n read with the specified ``plugin``. If the requested plugin cannot\n read ``path``, an exception will be raised.\n layer_type : str, optional\n If provided, will force data read from ``path`` to be passed to the\n corresponding ``add_<layer_type>`` method (along with any\n additional) ``kwargs`` provided to this function. This *may*\n result in exceptions if the data returned from the path is not\n compatible with the layer_type.\n\n Returns\n -------\n List[Layer]\n A list of any layers that were added to the viewer.\n \"\"\"\n from ..plugins.io import read_data_with_plugins\n\n layer_data = read_data_with_plugins(path_or_paths, plugin=plugin) or []\n\n # glean layer names from filename. These will be used as *fallback*\n # names, if the plugin does not return a name kwarg in their meta dict.\n filenames = []\n if isinstance(path_or_paths, str):\n filenames = itertools.repeat(path_or_paths)\n elif is_sequence(path_or_paths):\n if len(path_or_paths) == len(layer_data):\n filenames = iter(path_or_paths)\n else:\n # if a list of paths has been returned as a list of layer data\n # without a 1:1 relationship between the two lists we iterate\n # over the first name\n filenames = itertools.repeat(path_or_paths[0])\n\n # add each layer to the viewer\n added: List[Layer] = [] # for layers that get added\n for data, filename in zip(layer_data, filenames):\n basename, ext = os.path.splitext(os.path.basename(filename))\n _data = _unify_data_and_user_kwargs(\n data, kwargs, layer_type, fallback_name=basename\n )\n # actually add the layer\n new = self._add_layer_from_data(*_data)\n # some add_* methods return a List[Layer], others just a Layer\n # we want to always return a list\n added.extend(new if isinstance(new, list) else [new])\n return added\n\n def _add_layer_from_data(\n self, data, meta: dict = None, layer_type: Optional[str] = None\n ) -> Union[Layer, List[Layer]]:\n \"\"\"Add arbitrary layer data to the viewer.\n\n Primarily intended for usage by reader plugin hooks.\n\n Parameters\n ----------\n data : Any\n Data in a format that is valid for the corresponding `add_*` method\n of the specified ``layer_type``.\n meta : dict, optional\n Dict of keyword arguments that will be passed to the corresponding\n `add_*` method. MUST NOT contain any keyword arguments that are\n not valid for the corresponding method.\n layer_type : str\n Type of layer to add. MUST have a corresponding add_* method on\n on the viewer instance. If not provided, the layer is assumed to\n be \"image\", unless data.dtype is one of (np.int32, np.uint32,\n np.int64, np.uint64), in which case it is assumed to be \"labels\".\n\n Raises\n ------\n ValueError\n If ``layer_type`` is not one of the recognized layer types.\n TypeError\n If any keyword arguments in ``meta`` are unexpected for the\n corresponding `add_*` method for this layer_type.\n\n Examples\n --------\n A typical use case might be to upack a tuple of layer data with a\n specified layer_type.\n\n >>> viewer = napari.Viewer()\n >>> data = (\n ... np.random.random((10, 2)) * 20,\n ... {'face_color': 'blue'},\n ... 'points',\n ... )\n >>> viewer._add_layer_from_data(*data)\n\n \"\"\"\n\n layer_type = (layer_type or '').lower()\n\n # assumes that big integer type arrays are likely labels.\n if not layer_type:\n layer_type = guess_labels(data)\n\n if layer_type not in layers.NAMES:\n raise ValueError(\n f\"Unrecognized layer_type: '{layer_type}'. \"\n f\"Must be one of: {layers.NAMES}.\"\n )\n\n try:\n add_method = getattr(self, 'add_' + layer_type)\n except AttributeError:\n raise NotImplementedError(\n f\"Sorry! {layer_type} is a valid layer type, but there is no \"\n f\"viewer.add_{layer_type} available yet.\"\n )\n\n try:\n layer = add_method(data, **(meta or {}))\n except TypeError as exc:\n if 'unexpected keyword argument' in str(exc):\n bad_key = str(exc).split('keyword argument ')[-1]\n raise TypeError(\n \"_add_layer_from_data received an unexpected keyword \"\n f\"argument ({bad_key}) for layer type {layer_type}\"\n ) from exc\n else:\n raise exc\n\n return layer\n\n\ndef _normalize_layer_data(data: 'LayerData') -> 'FullLayerData':\n \"\"\"Accepts any layerdata tuple, and returns a fully qualified tuple.\n\n Parameters\n ----------\n data : LayerData\n 1-, 2-, or 3-tuple with (data, meta, layer_type).\n\n Returns\n -------\n FullLayerData\n 3-tuple with (data, meta, layer_type)\n\n Raises\n ------\n ValueError\n If data has len < 1 or len > 3, or if the second item in ``data`` is\n not a ``dict``, or the third item is not a valid layer_type ``str``\n \"\"\"\n if not isinstance(data, tuple) and 0 < len(data) < 4:\n raise ValueError(\"LayerData must be a 1-, 2-, or 3-tuple\")\n _data = list(data)\n if len(_data) > 1:\n if not isinstance(_data[1], dict):\n raise ValueError(\n \"The second item in a LayerData tuple must be a dict\"\n )\n else:\n _data.append(dict())\n if len(_data) > 2:\n if _data[2] not in layers.NAMES:\n raise ValueError(\n \"The third item in a LayerData tuple must be one of: \"\n f\"{layers.NAMES!r}.\"\n )\n else:\n _data.append(guess_labels(_data[0]))\n return tuple(_data) # type: ignore\n\n\ndef _unify_data_and_user_kwargs(\n data: 'LayerData',\n kwargs: Optional[dict] = None,\n layer_type: Optional[str] = None,\n fallback_name: str = None,\n) -> 'FullLayerData':\n \"\"\"Merge data returned from plugins with options specified by user.\n\n If ``data == (_data, _meta, _type)``. Then:\n\n - ``kwargs`` will be used to update ``_meta``\n - ``layer_type`` will replace ``_type`` and, if provided, ``_meta`` keys\n will be pruned to layer_type-appropriate kwargs\n - ``fallback_name`` is used if ``not _meta.get('name')``\n\n .. note:\n\n If a user specified both layer_type and additional keyword arguments\n to viewer.open(), it is their responsibility to make sure the kwargs\n match the layer_type.\n\n Parameters\n ----------\n data : LayerData\n 1-, 2-, or 3-tuple with (data, meta, layer_type) returned from plugin.\n kwargs : dict, optional\n User-supplied keyword arguments, to override those in ``meta`` supplied\n by plugins.\n layer_type : str, optional\n A user-supplied layer_type string, to override the ``layer_type``\n declared by the plugin.\n fallback_name : str, optional\n A name for the layer, to override any name in ``meta`` supplied by the\n plugin.\n\n Returns\n -------\n FullLayerData\n Fully qualified LayerData tuple with user-provided overrides.\n \"\"\"\n _data, _meta, _type = _normalize_layer_data(data)\n\n if layer_type:\n # the user has explicitly requested this be a certain layer type\n # strip any kwargs from the plugin that are no longer relevant\n _meta = prune_kwargs(_meta, layer_type)\n _type = layer_type\n\n if kwargs:\n # if user provided kwargs, use to override any meta dict values that\n # were returned by the plugin. We only prune kwargs if the user did\n # *not* specify the layer_type. This means that if a user specified\n # both layer_type and additional keyword arguments to viewer.open(),\n # it is their responsibility to make sure the kwargs match the\n # layer_type.\n _meta.update(prune_kwargs(kwargs, _type) if not layer_type else kwargs)\n\n if not _meta.get('name') and fallback_name:\n _meta['name'] = fallback_name\n return (_data, _meta, _type)\n\n\ndef prune_kwargs(kwargs: Dict[str, Any], layer_type: str) -> Dict[str, Any]:\n \"\"\"Return copy of ``kwargs`` with only keys valid for ``add_<layer_type>``\n\n Parameters\n ----------\n kwargs : dict\n A key: value mapping where some or all of the keys are parameter names\n for the corresponding ``Viewer.add_<layer_type>`` method.\n layer_type : str\n The type of layer that is going to be added with these ``kwargs``.\n\n Returns\n -------\n pruned_kwargs : dict\n A key: value mapping where all of the keys are valid parameter names\n for the corresponding ``Viewer.add_<layer_type>`` method.\n\n Raises\n ------\n ValueError\n If ``ViewerModel`` does not provide an ``add_<layer_type>`` method\n for the provided ``layer_type``.\n\n Examples\n --------\n >>> test_kwargs = {\n ... 'scale': (0.75, 1),\n ... 'blending': 'additive',\n ... 'num_colors': 10,\n ... }\n >>> prune_kwargs(test_kwargs, 'image')\n {'scale': (0.75, 1), 'blending': 'additive'}\n\n >>> # only labels has the ``num_colors`` argument\n >>> prune_kwargs(test_kwargs, 'labels')\n {'scale': (0.75, 1), 'blending': 'additive', 'num_colors': 10}\n \"\"\"\n add_method = getattr(ViewerModel, 'add_' + layer_type, None)\n if not add_method or layer_type == 'layer':\n raise ValueError(f\"Invalid layer_type: {layer_type}\")\n\n # get valid params for the corresponding add_<layer_type> method\n valid = valid_add_kwargs()[layer_type]\n return {k: v for k, v in kwargs.items() if k in valid}\n\n\n@lru_cache(maxsize=1)\ndef valid_add_kwargs() -> Dict[str, Set[str]]:\n \"\"\"Return a dict where keys are layer types & values are valid kwargs.\"\"\"\n valid = dict()\n for meth in dir(ViewerModel):\n if not meth.startswith('add_') or meth[4:] == 'layer':\n continue\n params = inspect.signature(getattr(ViewerModel, meth)).parameters\n valid[meth[4:]] = set(params) - {'self', 'kwargs'}\n return valid\n\n\nfor _layer in (\n layers.Labels,\n layers.Points,\n layers.Shapes,\n layers.Surface,\n layers.Tracks,\n layers.Vectors,\n):\n func = create_add_method(_layer)\n setattr(ViewerModel, func.__name__, func)\n"
] |
[
[
"numpy.multiply",
"numpy.min",
"numpy.round",
"numpy.max",
"numpy.repeat",
"numpy.array",
"numpy.zeros",
"numpy.divide"
]
] |
ashish-hacker/klar-EDA
|
[
"32a45854854c92e8e1f642ac31276d6f08daf778"
] |
[
"klar_eda/preprocess/csv_preprocess.py"
] |
[
"# get mean, median, mode, null\r\n# https://scikit-learn.org/stable/modules/preprocessing.html\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom .constants import VIZ_ROOT, NUNIQUE_THRESHOLD\r\nfrom sklearn.preprocessing import OneHotEncoder\r\nfrom scipy import stats\r\nfrom sklearn import preprocessing\r\nimport datetime\r\nimport dateutil.parser\r\n\r\n\r\nclass CSVPreProcess:\r\n\r\n def __init__(self, input, target_col = None, index_column = None, exclude_columns = []):\r\n if type(input)==str:\r\n self.df = pd.read_csv(input, index_col = index_column)\r\n else:\r\n self.df = input\r\n self.df.drop(exclude_columns,inplace=True)\r\n self.col_names = list(self.df.columns)\r\n self.target_column = self.col_names[-1] if target_col == None else target_col\r\n self.df.dropna(subset=[self.target_column], inplace=True)\r\n self.num_cols = len(self.col_names)\r\n self.output_format = 'png'\r\n self.categorical_data_types = ['object','str']\r\n self.categorical_column_list = []\r\n self.populate_categorical_column_list()\r\n self.numerical_column_list = list(self.get_filtered_dataframe(include_type=np.number))\r\n temp_col_list = [num_col for num_col in self.numerical_column_list if self.df[num_col].nunique() < NUNIQUE_THRESHOLD]\r\n self.continuous_column_list = [x for x in self.numerical_column_list if x not in temp_col_list]\r\n self.non_continuous_col_list = self.categorical_column_list + temp_col_list\r\n self.converted_date = ''\r\n\r\n def get_filtered_dataframe(self, include_type = [], exclude_type = []):\r\n\r\n if include_type or exclude_type:\r\n return self.df.select_dtypes(include = include_type, exclude = exclude_type)\r\n else:\r\n return self.df\r\n\r\n def populate_categorical_column_list(self):\r\n\r\n df = self.get_filtered_dataframe(exclude_type=np.number)\r\n if not self.categorical_column_list:\r\n for column in df:\r\n if df[column].nunique() <= NUNIQUE_THRESHOLD:\r\n self.categorical_column_list.append(column)\r\n\r\n def encode_categorical_target(self):\r\n if self.target_column in self.categorical_column_list:\r\n le = preprocessing.LabelEncoder()\r\n y = self.df[self.target_column]\r\n le.fit(y)\r\n self.df[self.target_column] = le.fit_transform(y)\r\n\r\n\r\n def fill_numerical_na(self, ret = False):\r\n\r\n columns = self.df.columns[self.df.isna().any()].tolist()\r\n for col in self.continuous_column_list:\r\n try:\r\n if col in columns:\r\n x = y = self.df[col]\r\n x = x.fillna(self.df[col].mean())\r\n mean_corr = x.corr(self.df[self.target_column])\r\n y = y.fillna(self.df[col].median())\r\n median_corr = y.corr(self.df[self.target_column])\r\n if(abs(mean_corr) > abs(median_corr)):\r\n self.df[col] = x\r\n else:\r\n self.df[col] = y\r\n except Exception as e:\r\n pass\r\n if ret == True:\r\n return self.df\r\n\r\n def fill_categorical_na(self, ret = False):\r\n self.df = self.df.fillna(\"Unknown\")\r\n if ret == True:\r\n return self.df\r\n\r\n def normalize_numerical(self):\r\n for col in self.numerical_column_list:\r\n if col != self.target_column:\r\n self.df[col]=(self.df[col]-self.df[col].min())/(self.df[col].max()-self.df[col].min())\r\n def standardize(self):\r\n \r\n ### Data use cases for Standardization: ###\r\n\r\n # It makes the data with unit variance and zero mean. \r\n # This will be used when the features have different scales , for example if there are two features salary and age , Obviously age will be from 1-100 and salary can be substantially higher than age values. So if we fit the model directly the salary feature will have a larger impact on predicting the target variable. But it may not be the case.\r\n # So It's necessary to standardise the data. \r\n # We should do standardization in case of algorithms where Gradient descent is used for optimizations, for achieving the minima faster. \r\n # Standardisation is also called z-score normalisation.\r\n\r\n for i in df.columns:\r\n self.df[i] = (self.df[i] - self.df[i].mean())/self.df[i].std() # Standardise the data z = (x - mean)/ (standard deviation)\r\n\r\n def mean_normalization(self):\r\n \"\"\" converts x to x' where,\r\n x' = (x - mean(x))/(max(x) - min(x))\r\n \"\"\"\r\n for col in df.columns:\r\n self.df[i] = (self.df[i] - self.df[i].mean())/(self.df[i].max() - self.df[i].min())\r\n\r\n def encode_categorical(self):\r\n enc = OneHotEncoder(handle_unknown='ignore')\r\n self.df.reset_index(drop=True, inplace=True)\r\n for col in self.categorical_column_list:\r\n if col != self.target_column:\r\n enc_df = pd.DataFrame(enc.fit_transform(self.df[[col]]).toarray())\r\n enc_df = enc_df.set_axis(enc.get_feature_names(), axis=1, inplace=False)\r\n del self.df[col]\r\n self.df = pd.concat([self.df,enc_df], axis = 1)#.reset_index()\r\n self.df.reset_index(drop=True, inplace=True)\r\n\r\n\r\n def remove_outliers(self, ret = False):\r\n df = self.df[self.continuous_column_list]\r\n del_list = self.continuous_column_list\r\n self.df = self.df.drop(columns = del_list)\r\n # print(self.df.columns)\r\n z_scores = stats.zscore(df)\r\n abs_z_scores = np.abs(z_scores)\r\n filtered_entries = (abs_z_scores < 3).all(axis=1)\r\n df = df[filtered_entries]\r\n self.df = pd.concat([self.df,df], axis = 1, join='inner')#.reset_index()\r\n if(ret == True):\r\n return self.df\r\n\r\n def remove_non_contributing_features(self):\r\n\r\n cor = self.df.corr()\r\n del_list = []\r\n # Remove related columns\r\n for col1 in self.continuous_column_list:\r\n for col2 in self.continuous_column_list:\r\n if col1 != self.target_column and col2 != self.target_column and col1 != col2:\r\n cor12 = abs(cor[col1][col2])\r\n if(cor12 > 0.85):\r\n if(cor[col1][self.target_column] > cor[col2][self.target_column]):\r\n del_list.append(col2)\r\n else:\r\n del_list.append(col1)\r\n self.df = self.df.drop(columns = del_list, axis = 1)\r\n # Removing unrelated columns\r\n del_list = []\r\n for col in self.continuous_column_list:\r\n if(abs(cor[col][self.target_column]) < 0.1 and col in list(self.df.columns)):\r\n del_list.append(col)\r\n self.df = self.df.drop(columns = del_list, axis = 1)\r\n self.df.to_csv('Preprocess_file.csv')\r\n\r\n def convert_date_format(self, input_date, output_date_format = 'DD/MM/YYYY'):\r\n \"\"\"\r\n Purpose:\r\n ---\r\n Converts the input date into any specified format\r\n\r\n Input Arguments:\r\n ---\r\n `input_date` : str\r\n\r\n `output_date_format` : str\r\n\r\n Returns:\r\n ---\r\n `converted_date` : str\r\n \r\n Example call:\r\n ---\r\n convert_date_format('2021/28/02', 'YYYY-MM-DD')\r\n \"\"\"\r\n output_date_formats = { 'DD/MM/YYYY' : '%d/%m/%Y', 'YYYY/DD/MM': '%Y/%d/%m', 'MM/DD/YYYY': '%m/%d/%Y', \\\r\n 'YYYY/MM/DD' : '%Y/%m/%d', 'DD-MM-YYYY': '%d-%m-%Y', 'YYYY-DD-MM': '%Y-%d-%m', \\\r\n 'MM-DD-YYYY' : '%m-%d-%Y', 'YYYY-MM-DD': '%Y-%m-%d'}\r\n \r\n \r\n parsed_date = dateutil.parser.parse(input_date, dayfirst=True)\r\n self.converted_date = parsed_date.strftime(output_date_formats[output_date_format])\r\n return self.converted_date\r\n"
] |
[
[
"pandas.concat",
"pandas.read_csv",
"numpy.abs",
"sklearn.preprocessing.OneHotEncoder",
"scipy.stats.zscore",
"sklearn.preprocessing.LabelEncoder"
]
] |
adrianschlatter/tanuna
|
[
"c94ecb7d5670a90b1d1058b757c65718dfe55496"
] |
[
"tests/tools.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nStuff that is useful for unittesting.\n\n@author: Adrian Schlatter\n\"\"\"\n\nimport numpy as np\n\n\ndef almostEqual(x, y, tol=1e-10):\n \"\"\"\n Compare 2 array-like objects x and y for \"almost equalness\". This is\n useful for testing numerical computation where you can not expect that\n expected and real results are exactly identical.\n \"\"\"\n\n x = np.array(x)\n y = np.array(y)\n\n if x.shape != y.shape:\n return(False)\n\n return(np.sqrt((np.abs(x - y)**2).sum()) < tol)\n"
] |
[
[
"numpy.array",
"numpy.abs"
]
] |
case547/acconeer-python-exploration
|
[
"e92de2c3bc8b60939276128e1ddca47486cdfb54"
] |
[
"gui/ml/keras_processing_tf2.py"
] |
[
"import os\nimport traceback\n\nimport numpy as np\nimport tensorflow as tf\nfrom keras.utils.layer_utils import count_params\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import class_weight\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras import optimizers as Opt\nfrom tensorflow.keras.callbacks import Callback, EarlyStopping\nfrom tensorflow.keras.layers import Input, TimeDistributed\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.utils import to_categorical\n\nfrom acconeer.exptool import configs\n\nimport gui.ml.layer_definitions as layer_definitions\nimport gui.ml.ml_helper as ml_helper\n\n\nnot_time_distributed = [\n \"GaussianNoise\",\n \"Dropout\",\n \"BatchNormalization\",\n \"LSTM\",\n]\n\n\nclass ACC_ML(ml_helper.KerasBase):\n tf_graph = None\n tf_session = None\n eager_execution = True\n\n def init_model(self):\n input_dim = self.model_data.feature_dimension\n output_dim = self.model_data.output\n\n if not isinstance(input_dim, list):\n input_dim = list(input_dim)\n\n print(\n \"\\nInitiating model with {:d}x{:d} inputs\"\n \" and {:d} outputs\".format(*input_dim, output_dim)\n )\n\n layer_list = self.model_data.layer_list\n if layer_list is None:\n print(\"No layers defined!\")\n return {\"loaded\": False, \"model_message\": \"No Layers defined\"}\n\n nr_layers = len(layer_list)\n layer_callbacks = layer_definitions.get_layers()\n\n lstm_mode = False\n time_series = False\n steps = self.model_data.time_distributed\n print(\"Building model with {} layers...\".format(nr_layers))\n if steps > 1:\n input_dim[-1] = input_dim[-1] - steps + 1\n input_dim = [steps] + input_dim\n lstm_mode = True\n time_series = True\n print(\"Building TimeDistributed model with {} steps!\".format(steps))\n\n # Add single channel dimension\n if input_dim[-1] != 1:\n input_dim = input_dim + [1]\n\n self.model_data.input = input_dim\n\n inputs = Input(shape=input_dim)\n\n x = None\n nr_layers = len(layer_list)\n for idx, layer in enumerate(layer_list):\n if not layer.get(\"is_active\", True):\n continue\n try:\n cb = layer_callbacks[layer[\"name\"]][\"class\"]\n except KeyError:\n print(\"Layer {} not found in layer_definitions.py!\".format(layer[\"name\"]))\n\n # Wrap layers in TimeDistributed until first LSTM layer\n if layer[\"name\"] == \"lstm\":\n lstm_mode = False\n time_series = False\n layer[\"params\"].pop(\"steps\")\n if lstm_mode:\n if layer[\"class\"] not in not_time_distributed:\n time_series = True\n else:\n time_series = False\n\n try:\n options = {}\n if layer[\"params\"] is not None:\n for entry in layer[\"params\"]:\n opt = layer[\"params\"][entry]\n if isinstance(opt, list):\n options[entry] = tuple(opt)\n else:\n options[entry] = opt\n print(\"{}: Adding {} with\\n{}\".format(idx + 1, layer[\"name\"], options))\n if idx == 0 and nr_layers > 1:\n if time_series:\n x = TimeDistributed(cb(**options))(inputs)\n else:\n x = cb(**options)(inputs)\n elif idx > 0 and idx < nr_layers - 1:\n if time_series:\n x = TimeDistributed(cb(**options))(x)\n else:\n x = cb(**options)(x)\n else:\n options.pop(\"units\", None)\n predictions = cb(output_dim, **options)(x)\n except Exception as e:\n traceback.print_exc()\n return {\n \"loaded\": False,\n \"model_message\": \"\\nLayer nr. {} failed.\"\n \" Error adding {}\\n{}\".format(idx + 1, layer[\"name\"], e),\n }\n\n if layer[\"name\"] == \"lstm\":\n layer[\"params\"][\"steps\"] = steps\n\n self.model = Model(inputs=inputs, outputs=predictions)\n\n if self.eager_execution:\n self.model.call = tf.function(self.model.call, experimental_relax_shapes=True)\n\n self.set_optimizer(\"Adam\")\n\n self.count_variables()\n\n return {\"loaded\": True, \"model_message\": \"\"}\n\n def set_optimizer(self, optimizer, loss=\"categorical_crossentropy\"):\n if optimizer.lower() == \"adam\":\n opt_handle = Opt.Adam()\n elif optimizer.lower() == \"adagrad\":\n opt_handle = Opt.Adagrad()\n elif optimizer.lower() == \"adadelta\":\n opt_handle = Opt.Adadelta()\n elif optimizer.lower() == \"rmsprop\":\n opt_handle = Opt.RMSprop()\n else:\n print(\"Unknown optimizer {}. Using Adam!\".format(optimizer))\n opt_handle = Opt.Adam()\n\n print(\"Setting model optimizer to {}\".format(optimizer))\n self.model.compile(\n loss=\"categorical_crossentropy\",\n optimizer=opt_handle,\n metrics=[\"accuracy\"],\n )\n\n def train(self, train_params):\n if self.training_data[\"loaded\"]:\n try:\n x = self.training_data[\"x_data\"]\n y = self.model_data[\"y_labels\"]\n epochs = train_params[\"epochs\"]\n batch_size = train_params[\"batch_size\"]\n except Exception as e:\n print(\"Incorrect training parameters! \", e)\n return False\n else:\n print(\"Training data not loaded!\")\n return False\n\n model = self.model\n run_threaded = False\n if train_params.get(\"threaded\"):\n model = train_params[\"model\"].model\n run_threaded = True\n\n if \"eval_data\" in train_params:\n eval_data = train_params[\"eval_data\"]\n if isinstance(eval_data, float):\n x, xTest, y, yTest = train_test_split(x, y, test_size=eval_data)\n eval_data = (xTest, yTest)\n else:\n eval_data = None\n\n y_ints = [d.argmax() for d in y]\n class_weights = class_weight.compute_class_weight(\"balanced\", np.unique(y_ints), y_ints)\n class_weights = dict(enumerate(class_weights))\n\n cb = []\n plot_cb = train_params.get(\"plot_cb\", None)\n stop_cb = train_params.get(\"stop_cb\", None)\n save_best = train_params.get(\"save_best\", None)\n steps = int(np.ceil(x.shape[0] / batch_size))\n func = TrainCallback(\n plot_cb=plot_cb,\n steps_per_epoch=steps,\n stop_cb=stop_cb,\n save_best=save_best,\n parent=self,\n )\n cb.append(func)\n\n if plot_cb is not None:\n verbose = 0\n else:\n verbose = 1\n\n if \"dropout\" in train_params:\n dropout = train_params[\"dropout\"]\n if isinstance(dropout, dict):\n if dropout[\"monitor\"] in [\"acc\", \"val_acc\", \"loss\", \"val_loss\"]:\n cb_early_stop = EarlyStopping(\n monitor=dropout[\"monitor\"],\n min_delta=dropout[\"min_delta\"],\n patience=dropout[\"patience\"],\n verbose=verbose,\n mode=\"auto\",\n )\n cb.append(cb_early_stop)\n\n optimizer = None\n if train_params.get(\"optimizer\"):\n optimizer = train_params[\"optimizer\"]\n\n if optimizer is not None:\n self.set_optimizer(optimizer)\n if \"learning_rate\" in train_params:\n K.set_value(model.optimizer.lr, train_params[\"learning_rate\"])\n\n history = model.fit(\n x,\n y,\n epochs=epochs,\n batch_size=batch_size,\n callbacks=cb,\n validation_data=eval_data,\n verbose=verbose,\n class_weight=class_weights,\n )\n\n if run_threaded:\n return model, self.get_current_graph(), self.get_current_session()\n else:\n return history\n\n def set_learning_rate(self, rate):\n K.set_value(self.model.optimizer.lr, rate)\n\n def eval(self, x, y):\n test_loss, test_acc = self.model.evaluate(x, y)\n print(\"\\nTest result:\")\n print(\"Loss: \", test_loss, \"Accuracy: \", test_acc)\n\n def predict(self, x=\"internal\"):\n if isinstance(x, str):\n if self.training_data[\"loaded\"]:\n # Predict training data\n x = self.training_data[\"x_data\"]\n else:\n print(\"No training data available!\")\n return None\n\n if len(x.shape) == len(self.model.input_shape) - 1:\n if x.shape[0] == self.model.input_shape[1]:\n x = np.expand_dims(x, 0)\n else:\n x = np.expand_dims(x, -1)\n if len(x.shape) == len(self.model.input_shape) - 2:\n x = np.expand_dims(x, 0)\n x = np.expand_dims(x, -1)\n\n if len(x.shape) != len(self.model.input_shape):\n print(\n \"Wrong data shapes:\\n Model: {}\\n Test: {}\\n\".format(\n self.model.input_shape,\n x.shape,\n )\n )\n return None\n\n if self.eager_execution:\n prediction = self.model(x, training=False)\n else:\n prediction = self.model.predict(x)\n result = list()\n\n num2label = {}\n for key in self.labels_dict:\n num2label[self.labels_dict[key]] = key\n\n for pred in prediction:\n confidence = 0\n prediction_label = \"\"\n res = {}\n category = {}\n for p in range(len(pred)):\n label = num2label[p]\n if pred[p] > confidence:\n prediction_label = label\n confidence = pred[p]\n category[label] = [pred[p], p]\n res[\"label_predictions\"] = category\n res[\"number_labels\"] = len(pred)\n res[\"prediction\"] = prediction_label\n res[\"confidence\"] = confidence\n res[\"label_num\"] = np.argmax(pred)\n result.append(res)\n return result\n\n def save_model(self, file, feature_list=None, sensor_config=None, frame_settings=None):\n if feature_list is None:\n feature_list = self.model_data.feature_list\n if sensor_config is None:\n sensor_config = self.model_data.sensor_config\n if frame_settings is None:\n frame_settings = self.model_data.frame_settings\n\n try:\n filename, file_extension = os.path.splitext(file)\n except Exception as e:\n traceback.print_exc()\n return \"Error saving model:\\n{}\".format(e)\n\n try:\n tf.keras.models.save_model(\n self.model,\n filename,\n overwrite=True,\n include_optimizer=True,\n save_format=\"tf\",\n signatures=None,\n options=None,\n )\n except Exception as e:\n traceback.print_exc()\n return \"Error saving model:\\n{}\".format(e)\n\n ml_info_file = os.path.join(filename, \"ml_info\")\n\n try:\n model_dimensions = {\n \"input\": self.model_data.input,\n \"output\": self.model_data.output,\n \"time_distributed\": self.model_data.time_distributed,\n \"feature_dimension\": self.model_data.feature_dimension,\n }\n info = {\n \"labels_dict\": self.labels_dict,\n \"model_dimensions\": model_dimensions,\n \"feature_list\": feature_list,\n \"sensor_config\": sensor_config._dumps(),\n \"frame_settings\": frame_settings,\n \"nr_of_training_maps\": self.model_data.nr_of_training_maps,\n }\n np.save(ml_info_file, info)\n except Exception as e:\n return \"Error saving model:\\n{}\".format(e)\n else:\n return None\n\n def load_model(self, file):\n self.clear_model()\n try:\n filename, file_extension = os.path.splitext(file)\n print(filename, file_extension)\n self.model = tf.keras.models.load_model(filename)\n except Exception as e:\n traceback.print_exc()\n return \"Error loading model:\\n{}\".format(e)\n\n try:\n ml_info_file = os.path.join(filename, \"ml_info.npy\")\n info = np.load(ml_info_file, allow_pickle=True)\n self.labels_dict = info.item()[\"labels_dict\"]\n model_dimensions = info.item()[\"model_dimensions\"]\n self.label_num = model_dimensions[\"output\"]\n feature_list = info.item()[\"feature_list\"]\n sensor_config = configs.load(info.item()[\"sensor_config\"])\n frame_settings = info.item()[\"frame_settings\"]\n time_distributed = model_dimensions.get(\"time_distributed\", 1)\n feature_dimension = model_dimensions.get(\n \"feature_dimension\",\n model_dimensions[\"input\"][:-1],\n )\n except Exception as e:\n error_text = self.error_to_text(e)\n message = \"Error in load model:\\n{}\".format(error_text)\n return {\"loaded\": False}, message\n else:\n try:\n self.model_data.nr_of_training_maps = info.item()[\"nr_of_training_maps\"]\n except KeyError:\n self.model_data.nr_of_training_maps = 0\n gui_layer_conf = layer_definitions.get_layers()\n layer_list = []\n for l in self.model.layers:\n l_conf = l.get_config()\n l_name = l_conf[\"name\"].rsplit(\"_\", 1)[0]\n if \"time_distributed\" in l_name:\n l_conf = l_conf[\"layer\"][\"config\"]\n l_name = l_name = l_conf[\"name\"].rsplit(\"_\", 1)[0]\n if l_name in gui_layer_conf:\n g_conf = gui_layer_conf[l_name][\"params\"]\n layer = {\n \"name\": l_name,\n \"class\": gui_layer_conf[l_name][\"class_str\"],\n \"params\": {},\n }\n if g_conf is None:\n layer[\"params\"] = None\n else:\n for p in l_conf:\n if p in g_conf:\n if isinstance(l_conf[p], tuple):\n layer[\"params\"][p] = list(l_conf[p])\n else:\n layer[\"params\"][p] = l_conf[p]\n layer_list.append(layer)\n else:\n if l_name != \"input\":\n print(\"Keras layer {} not found in layer_definitions.py!\".format(l_name))\n\n labels = self.get_label_list()\n label_categories = None\n if self.training_data[\"loaded\"]:\n try:\n data_labels = self.label_assignment(\n self.training_data[\"raw_labels\"],\n self.labels_dict,\n )\n label_categories = to_categorical(data_labels, self.label_num)\n except Exception as e:\n print(\"Loaded data incompatible with model data!\\n\", e)\n self.trainning = {\"loaded\": False}\n label_categories = None\n\n model_data = {\n \"loaded\": True,\n \"y_labels\": label_categories,\n \"label_list\": labels,\n \"feature_list\": feature_list,\n \"sensor_config\": sensor_config,\n \"frame_settings\": frame_settings,\n \"layer_list\": layer_list, # GUI format layer list\n \"keras_layer_info\": self.model.layers, # Keras format layer list\n \"input\": model_dimensions[\"input\"],\n \"output\": model_dimensions[\"output\"],\n \"time_distributed\": time_distributed,\n \"feature_dimension\": feature_dimension,\n }\n\n self.set_model_data(model_data)\n self.count_variables()\n\n message = \"Loaded model with:\\n\"\n message += \"input shape :{}\\n\".format(self.model_data.input)\n if self.model_data.time_distributed > 1:\n message += \"time steps :{}\\n\".format(self.model_data.time_distributed)\n message += \"output shape :{}\\n\".format(self.model_data.output)\n message += \"nr of features :{}\\n\".format(len(feature_list))\n message += \"labels :{}\\n\".format(labels)\n message += \"Trained with {} features\".format(\n self.model_data.get(\"nr_of_training_maps\", \"N/A\")\n )\n\n return self.model_data, message\n\n def clear_session(self):\n K.clear_session()\n tf.keras.backend.clear_session()\n\n def clear_model(self, reinit=False):\n if self.model is not None:\n self.clear_session()\n del self.model\n self.model = None\n if not reinit:\n for data in self.model_data:\n if data != \"tf_version\":\n self.model_data[data] = None\n self.model_data.loaded = False\n self.label_num = 0\n self.time_distributed = 1\n self.labels_dict = None\n\n if reinit:\n new_strategy = tf.distribute.MirroredStrategy()\n with new_strategy.scope():\n status = self.init_model()\n if status[\"loaded\"]:\n self.model_data[\"loaded\"] = True\n return status\n else:\n return {\"loaded\": False, \"model_message\": \"Nothing to reinitialize!\"}\n\n def set_model_layers(self, layer_list):\n self.model_data.time_distributed = 1\n for l in layer_list:\n if \"lstm\" in l[\"name\"] and l.get(\"is_active\", True):\n steps = l[\"params\"].get(\"steps\", None)\n if steps is None:\n steps = 1\n print(\"Warning: Missing time steps for LSTM\")\n self.model_data.time_distributed = steps\n self.model_data.layer_list = layer_list\n\n def get_current_session(self, graph=None):\n return self.tf_session\n\n def get_current_graph(self):\n return self.tf_graph\n\n def set_current_session(self, session):\n pass\n\n def count_variables(self):\n if self.model is not None:\n trainable = count_params(self.model.trainable_weights)\n non_trainable = count_params(self.model.non_trainable_weights)\n return {\"trainable\": trainable, \"non_trainable\": non_trainable}\n else:\n return None\n\n def clear_training_data(self):\n self.model_data.y_labels = None\n self.training_data = {\"loaded\": False}\n self.test_data = {\"loaded\": False}\n if not self.model_data.loaded:\n self.label_num = 0\n self.labels_dict = None\n\n def convert_to_categorical(self, labels, label_nr):\n return to_categorical(labels, label_nr)\n\n def enable_eager_execution(self):\n if self.model_data.loaded:\n print(\"This needs to be toggled before a model is created!\")\n return\n tf.compat.v1.enable_eager_execution()\n self.eager_execution = True\n\n def disable_eager_execution(self):\n if self.model_data.loaded:\n print(\"This needs to be toggled before a model is created!\")\n return\n tf.compat.v1.disable_eager_execution()\n self.eager_execution = False\n\n\nclass TrainCallback(Callback):\n def __init__(\n self, plot_cb=None, steps_per_epoch=None, stop_cb=None, save_best=None, parent=None\n ):\n self.parent = parent\n self.plot = plot_cb\n self.stop_cb = stop_cb\n self.steps_per_epoch = steps_per_epoch\n self.epoch = 0\n self.batch = 0\n self.save_best = save_best\n self.val_loss = np.inf\n\n def on_batch_end(self, batch, logs=None):\n self.batch += 1\n self.send_data(logs)\n\n def on_epoch_end(self, epoch, logs=None):\n self.epoch += 1\n self.send_data(logs)\n\n if self.save_best:\n try:\n if logs[\"val_loss\"] < self.val_loss:\n self.val_loss = logs[\"val_loss\"]\n fname = \"model_epoch_{}_val_loss_{:.04f}\".format(self.epoch, self.val_loss)\n fname = os.path.join(self.save_best[\"folder\"], fname)\n self.parent.save_model(\n fname,\n self.save_best[\"feature_list\"],\n self.save_best[\"sensor_config\"],\n self.save_best[\"frame_settings\"],\n )\n except Exception as e:\n print(e)\n\n def send_data(self, data):\n if \"steps_per_epoch\" not in data:\n data[\"steps_per_epoch\"] = self.steps_per_epoch\n\n if self.plot is not None:\n self.plot(data)\n\n if self.stop_cb is not None:\n try:\n stop_training = self.stop_cb()\n if stop_training:\n self.stopped_epoch = self.epoch\n self.model.stop_training = True\n except Exception as e:\n print(\"Failed to call stop callback! \", e)\n pass\n"
] |
[
[
"tensorflow.keras.models.load_model",
"numpy.expand_dims",
"tensorflow.keras.models.save_model",
"tensorflow.compat.v1.enable_eager_execution",
"tensorflow.keras.backend.clear_session",
"numpy.unique",
"tensorflow.keras.optimizers.RMSprop",
"tensorflow.keras.optimizers.Adadelta",
"numpy.save",
"numpy.ceil",
"numpy.argmax",
"numpy.load",
"tensorflow.keras.callbacks.EarlyStopping",
"tensorflow.keras.backend.set_value",
"tensorflow.keras.models.Model",
"sklearn.model_selection.train_test_split",
"tensorflow.function",
"tensorflow.compat.v1.disable_eager_execution",
"tensorflow.keras.layers.Input",
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.optimizers.Adagrad",
"tensorflow.keras.utils.to_categorical",
"tensorflow.distribute.MirroredStrategy"
]
] |
yufeiwang63/bullet3
|
[
"8e5faf69e96e293c0773e24358b9b70ae6a58a9a"
] |
[
"Buggy_cloth_contact/helper.py"
] |
[
"import numpy as np\nimport pybullet as p\n\ndef create_spheres(id, radius=0.01, mass=0.0, batch_positions=[[0, 0, 0]], visual=True, collision=True, rgba=[0, 1, 1, 1]):\n sphere_collision = p.createCollisionShape(shapeType=p.GEOM_SPHERE, radius=radius, physicsClientId=id) if collision else -1\n sphere_visual = p.createVisualShape(shapeType=p.GEOM_SPHERE, radius=radius, rgbaColor=rgba, physicsClientId=id) if visual else -1\n sphere_ids = p.createMultiBody(baseMass=mass, baseCollisionShapeIndex=sphere_collision, baseVisualShapeIndex=sphere_visual, basePosition=[0, 0, 0], useMaximalCoordinates=False, batchPositions=batch_positions, physicsClientId=id)\n return sphere_ids\n\ndef get_quaternion(euler):\n return np.array(p.getQuaternionFromEuler(np.array(euler)))\n"
] |
[
[
"numpy.array"
]
] |
Aaronearlerichardson/Cogan_BIDS
|
[
"612087ff103566ddf7fc1ebc6a494a0650d2b974"
] |
[
"BIDS_converter/data2bids.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nimport argparse\nimport csv\nimport datetime\nimport gc\nimport gzip\nimport json\nimport subprocess\nimport sys\nfrom typing import Union, List\n\nimport nibabel as nib\nimport pandas as pd\nimport pydicom as dicom\nfrom bids import layout\nfrom matgrab import mat2df\nfrom pyedflib import highlevel\nfrom scipy.io import wavfile\n\nfrom utils import *\n\n\ndef get_parser(): # parses flags at onset of command\n parser = argparse.ArgumentParser(\n formatter_class=argparse.RawDescriptionHelpFormatter\n , description=\"\"\"\n Data2bids is a script based on the SIMEXP lab script to convert nifti MRI files into BIDS format. This script has been modified to \n also parse README data as well as include conversion of DICOM files to nifti. The script utilizes Chris Rorden's Dcm2niix program for \n actual conversion. \n\n This script takes one of two formats for conversion. The first is a series of DICOM files in sequence with an optional \\\"medata\\\" folder which\n contains any number of single or multi-echo uncompressed nifti files (.nii). Note that nifti files in this case must also have a corresponding \n DICOM scan run, but not necessarily scan echo (for example, one DICOM scan for run 5 but three nifti files which are echoes 1, 2, and 3 of\n run 5). The other format is a series of nifti files and a README.txt file formatted the same way as it is in the example. Both formats are \n shown in the examples folder.\n\n Both formats use a .json config file that maps either DICOM tags or text within the nifti file name to BIDS metadata. The syntax and formatting of this .json file \n can be found here https://github.com/SIMEXP/Data2Bids#heuristic.\n\n The only thing this script does not account for is event files. If you have the 1D files that's taken care of, but chances are you have some other \n format. If this is the case, I recommend https://bids-specification.readthedocs.io/en/stable/04-modality-specific-files/05-task-events.html\n so that you can make BIDS compliant event files.\n\n Data2bids documentation at https://github.com/SIMEXP/Data2Bids\n Dcm2niix documentation at https://github.com/rordenlab/dcm2niix\"\"\"\n , epilog=\"\"\"\n Made by Aaron Earle-Richardson ([email protected])\n \"\"\")\n\n group = parser.add_mutually_exclusive_group(required=True)\n group.add_argument(\n \"-i\"\n , \"--input_dir\"\n , required=False\n , default=None\n , help=\"\"\"\n Input data directory(ies), must include a readme.txt file formatted like example under examples folder. \n Mutually exclusive with DICOM directory option. Default: current directory\n \"\"\",\n )\n\n parser.add_argument(\n \"-c\"\n , \"--config\"\n , required=False\n , default=None\n , help=\"JSON configuration file (see https://github.com/SIMEXP/Data2Bids/blob/master/example/config.json)\",\n )\n\n parser.add_argument(\n \"-o\"\n , \"--output_dir\"\n , required=False\n , default=None\n , help=\"Output BIDS directory, Default: Inside current directory \",\n )\n\n group.add_argument(\n \"-d\"\n , \"--DICOM_path\"\n , default=None\n , required=False\n , help=\"Optional DICOM directory, Mutually exclusive with input directory option\",\n )\n\n parser.add_argument(\n \"-m\"\n , \"--multi_echo\"\n , nargs='*'\n , type=int\n , required=False\n , help=\"\"\"\n indicator of multi-echo dataset. Only necessary if NOT converting DICOMs. For example, if runs 3-6 were all multi-echo then the flag\n should look like: -m 3 4 5 6 . Additionally, the -m flag may be called by itself if you wish to let data2bids auto-detect multi echo data,\n but it will not be able to tell you if there is a mistake.\"\"\"\n )\n\n parser.add_argument(\n \"-ow\"\n , \"--overwrite\"\n , required=False\n , action='store_true'\n , help=\"overwrite preexisting BIDS file structures in destination location\",\n )\n\n parser.add_argument(\n \"-ch\"\n , \"--channels\"\n , nargs='*'\n , required=False\n , help=\"\"\"\n Indicator of channels to keep from edf files. \n \"\"\"\n )\n\n parser.add_argument(\n \"-s\"\n , \"--stim_dir\"\n , required=False\n , default=None\n , help=\"directory containing stimuli files\",\n )\n\n parser.add_argument(\n \"-v\"\n , \"--verbose\"\n , required=False\n , action='store_true'\n , help=\"verbosity\",\n )\n\n return parser\n\n\nclass Data2Bids: # main conversion and file organization program\n\n def __init__(self, input_dir=None, config=None, output_dir=None, DICOM_path=None, multi_echo=None, overwrite=False,\n stim_dir=None, channels=None, verbose=False):\n # sets the .self globalization for self variables\n self._input_dir = None\n self._config_path = None\n self._config = None\n self._bids_dir = None\n self._bids_version = \"1.6.0\"\n self._dataset_name = None\n self._data_types = {\"anat\": False, \"func\": False, \"ieeg\": False}\n self._ignore = []\n\n self.set_overwrite(overwrite)\n self.set_data_dir(input_dir, DICOM_path)\n self.set_config_path(config)\n self.set_bids_dir(output_dir)\n self.set_DICOM(DICOM_path)\n self.set_multi_echo(multi_echo)\n self.set_verbosity(verbose)\n self.set_stim_dir(stim_dir)\n self.set_channels(channels)\n\n def check_ignore(self, file):\n\n assert os.path.isabs(file), file + \"must be given with the absolute path including root\"\n if not os.path.exists(file):\n raise FileNotFoundError(file + \" does not exist\")\n\n ans = False\n for item in self._ignore:\n if os.path.isfile(item) and Path(file).resolve() == Path(item).resolve():\n ans = True\n elif os.path.isdir(item):\n for root, dirs, files in os.walk(item):\n if os.path.basename(file) in files and Path(root).resolve() == Path(\n os.path.dirname(file)).resolve():\n ans = True\n return ans\n\n def set_stim_dir(self, dir):\n if dir is None:\n if \"stimuli\" in os.listdir(self._data_dir): # data2bids can be called at the parent folder\n dir = os.path.join(self._data_dir, \"stimuli\")\n elif \"stimuli\" in os.listdir(os.path.dirname(self._data_dir)): # or subject folder level\n dir = os.path.join(os.path.dirname(self._data_dir), \"stimuli\")\n else:\n self.stim_dir = None\n return\n if not os.path.isdir(os.path.join(self._bids_dir, \"stimuli\")):\n os.mkdir(os.path.join(self._bids_dir, \"stimuli\"))\n for item in os.listdir(dir):\n shutil.copyfile(os.path.join(dir, item), os.path.join(self._bids_dir, \"stimuli\", item))\n self.stim_dir = dir\n self._ignore.append(dir)\n\n def set_channels(self, channels):\n try:\n headers_dict = self._config[\"ieeg\"][\"headerData\"]\n except KeyError:\n headers_dict = None\n self.channels = {}\n self.sample_rate = {}\n part_match = None\n task_label_match = None\n if self._data_dir:\n for root, _, files in os.walk(self._data_dir):\n # ignore BIDS directories and stimuli\n files[:] = [f for f in files if not self.check_ignore(os.path.join(root, f))]\n i = 1\n while files:\n file = files.pop(0)\n src = os.path.join(root, file)\n if not part_match == match_regexp(self._config[\"partLabel\"], file):\n part_match = match_regexp(self._config[\"partLabel\"], file)\n self.channels[part_match] = []\n part_match_z = self.part_check(part_match)[1]\n df = None\n for name, var in self._config[\"ieeg\"][\"channels\"].items():\n if name in src:\n df = mat2df(src, var)\n if \"highpass_cutoff\" in df.columns.to_list():\n df = df.rename(columns={\"highpass_cutoff\": \"high_cutoff\"})\n if \"lowpass_cutoff\" in df.columns.to_list():\n df = df.rename(columns={\"lowpass_cutoff\": \"low_cutoff\"})\n name_gen = self.generate_names(src, part_match=part_match, verbose=False)\n if name_gen is not None and name_gen[-2] is not None:\n task_label_match = name_gen[-2]\n if df is None:\n continue\n elif task_label_match is None:\n i += 1\n if i > 40:\n raise NameError(\"No tasks could be found in files:\\n\", os.listdir(os.path.dirname(src)))\n else:\n files.append(file)\n continue\n else:\n i = 1\n filename = os.path.join(self._bids_dir, \"sub-\" + part_match_z, \"sub-\" + part_match_z + \"_task-\" +\n task_label_match + \"_channels.tsv\")\n os.mkdir(os.path.dirname(filename))\n df.to_csv(filename, sep=\"\\t\", index=False)\n if part_match not in headers_dict.keys():\n try:\n var = headers_dict[\"default\"]\n if isinstance(var, str):\n var = [var]\n self.channels[part_match] = self.channels[part_match] + [v for v in var if\n v not in self.channels[part_match]]\n except KeyError:\n pass\n for name, var in headers_dict.items():\n if name == part_match:\n if isinstance(var, str):\n var = [var]\n self.channels[part_match] = self.channels[part_match] + [v for v in var if\n v not in self.channels[part_match]]\n elif re.match(\".*?\" + part_match + \".*?\" + name,\n src): # some sort of checking for .mat or txt files?\n if name.endswith(\".mat\") and re.match(\".*?\" + part_match + \".*?\" + name, src):\n self.channels[part_match] = self.channels[part_match] + mat2df(src, var).tolist()\n try:\n self.sample_rate[part_match] = mat2df(src, self._config['ieeg']['sampleRate']).iloc[\n 0]\n except KeyError:\n self.sample_rate[part_match] = None\n except AttributeError:\n raise IndexError(self._config['ieeg']['sampleRate'] + \" not found in \" + src)\n self._ignore.append(src)\n elif name.endswith((\".txt\", \".csv\", \".tsv\")) and re.match(\".*?\" + part_match + \".*?\" + name,\n src):\n f = open(name, 'r')\n content = f.read()\n f.close()\n self.channels[part_match] = self.channels[part_match] + content.split()\n elif name.endswith(tuple(self._config['dataFormat'])) and re.match(\n \".*?\" + part_match + \".*?\" + name, src):\n raise NotImplementedError(src +\n \"\\nthis file format does not yet support {ext} files for \"\n \"channel labels\".format(\n ext=os.path.splitext(src)[1]))\n if isinstance(channels, str) and channels not in channels[part_match]:\n self.channels[part_match] = self.channels[part_match] + [channels]\n elif channels is not None:\n self.channels[part_match] = self.channels[part_match] + [c for c in channels if\n c not in self.channels[part_match]]\n\n def set_overwrite(self, overwrite):\n self._is_overwrite = overwrite\n\n def set_verbosity(self, verbose):\n self._is_verbose = verbose\n\n def set_multi_echo(self, multi_echo): # if -m flag is called\n if multi_echo is None:\n self.is_multi_echo = False\n else:\n self.is_multi_echo = True\n if not multi_echo:\n self._multi_echo = 0\n else:\n self._multi_echo = multi_echo\n\n def set_DICOM(self, ddir): # triggers only if dicom flag is called and therefore _data_dir is None\n if self._data_dir is None:\n self._data_dir = os.path.dirname(self._bids_dir)\n subdirs = [x[0] for x in os.walk(ddir)]\n files = [x[2] for x in os.walk(ddir)]\n sub_num = str(dicom.read_file(os.path.join(subdirs[1], files[1][0]))[0x10, 0x20].value).split(\"_\", 1)[1]\n sub_dir = os.path.join(os.path.dirname(self._bids_dir),\n \"sub-{SUB_NUM}\".format(SUB_NUM=sub_num)) # destination subdirectory\n if os.path.isdir(sub_dir):\n proc = subprocess.Popen(\"rm -rf {file}\".format(file=sub_dir), shell=True, stdout=subprocess.PIPE)\n proc.communicate()\n os.mkdir(sub_dir)\n\n if any(\"medata\" in x for x in subdirs): # copy over and list me data\n melist = [x[2] for x in os.walk(os.path.join(ddir, \"medata\"))][0]\n runlist = []\n for me in melist:\n if me.startswith(\".\"):\n continue\n runmatch = re.match(r\".*run(\\d{2}).*\", me).group(1)\n if str(int(runmatch)) not in runlist:\n runlist.append(str(int(runmatch)))\n shutil.copyfile(os.path.join(ddir, \"medata\", me), os.path.join(sub_dir, me))\n self.is_multi_echo = True # will trigger even if single echo data is in medata folder. Should still\n # be okay\n for subdir in subdirs[1:]: # not including parent folder or /medata, run dcm2niix on non me data\n try:\n fobj = dicom.read_file(os.path.join(subdir, list(os.walk(subdir))[0][2][0]),\n force=True) # first dicom file of the scan\n scan_num = str(int(os.path.basename(subdir))).zfill(2)\n except ValueError:\n continue\n firstfile = [x[2] for x in os.walk(subdir)][0][0]\n # print(str(fobj[0x20, 0x11].value), runlist)\n # running dcm2niix, \n if str(fobj[0x20, 0x11].value) in runlist:\n proc = subprocess.Popen(\n \"dcm2niix -z y -f run{SCAN_NUM}_%p_%t_sub{SUB_NUM} -o {OUTPUT_DIR} -s y -b y {DATA_DIR}\".format(\n OUTPUT_DIR=sub_dir, SUB_NUM=sub_num, DATA_DIR=os.path.join(subdir, firstfile),\n SCAN_NUM=scan_num), shell=True, stdout=subprocess.PIPE)\n # output = proc.stdout.read()\n outs, errs = proc.communicate()\n prefix = re.match(\".*/sub-{SUB_NUM}/(run{SCAN_NUM}\".format(SUB_NUM=sub_num,\n SCAN_NUM=scan_num) + r\"[^ \\(\\\"\\\\n\\.]*).*\",\n str(outs)).group(1)\n for file in os.listdir(sub_dir):\n mefile = re.match(r\"run{SCAN_NUM}(\\.e\\d\\d)\\.nii\".format(SCAN_NUM=scan_num), file)\n if re.match(r\"run{SCAN_NUM}\\.e\\d\\d.nii\".format(SCAN_NUM=scan_num), file):\n shutil.move(os.path.join(sub_dir, file),\n os.path.join(sub_dir, prefix + mefile.group(1) + \".nii\"))\n shutil.copy(os.path.join(sub_dir, prefix + \".json\"),\n os.path.join(sub_dir, prefix + mefile.group(1) + \".json\"))\n os.remove(os.path.join(sub_dir, prefix + \".nii.gz\"))\n os.remove(os.path.join(sub_dir, prefix + \".json\"))\n else:\n proc = subprocess.Popen(\n \"dcm2niix -z y -f run{SCAN_NUM}_%p_%t_sub{SUB_NUM} -o {OUTPUT_DIR} -b y {DATA_DIR}\".format(\n OUTPUT_DIR=sub_dir, SUB_NUM=sub_num, DATA_DIR=subdir, SCAN_NUM=scan_num), shell=True,\n stdout=subprocess.PIPE)\n outs, errs = proc.communicate()\n sys.stdout.write(outs.decode(\"utf-8\"))\n\n self._multi_echo = runlist\n self._data_dir = os.path.join(os.path.dirname(self._bids_dir), \"sub-{SUB_NUM}\".format(SUB_NUM=sub_num))\n self._DICOM_path = ddir\n\n def get_data_dir(self):\n return self._data_dir\n\n def set_data_dir(self, data_dir, DICOM): # check if input dir is listed\n if DICOM is None:\n if data_dir is None:\n self._data_dir = os.getcwd()\n else:\n self._data_dir = data_dir\n self._dataset_name = os.path.basename(self._data_dir)\n else:\n self._data_dir = None\n\n def get_config(self):\n return self._config\n\n def get_config_path(self):\n return self._config_path\n\n def _set_config(self):\n with open(self._config_path, 'r') as fst:\n self._config = json.load(fst)\n\n def set_config(self, config):\n self._config = config\n\n def set_config_path(self, config_path):\n if config_path is None:\n # Checking if a config.json is present\n if os.path.isfile(os.path.join(os.getcwd(), \"config.json\")):\n self._config_path = os.path.join(os.getcwd(), \"config.json\")\n # Otherwise taking the default config\n else:\n self._config_path = os.path.join(os.path.dirname(__file__), \"config.json\")\n else:\n self._config_path = config_path\n\n self._set_config()\n\n def get_bids_dir(self):\n return self._bids_dir\n\n def set_bids_dir(self, bids_dir):\n if bids_dir is None:\n # Creating a new directory for BIDS\n try:\n newdir = self._data_dir + \"/BIDS\"\n except TypeError:\n print(\"Error: Please provide input data directory if no BIDS directory...\")\n\n # deleting old BIDS to make room for new\n elif not os.path.basename(bids_dir) == \"BIDS\":\n newdir = os.path.join(bids_dir, \"BIDS\")\n else:\n newdir = bids_dir\n if not os.path.isdir(newdir):\n os.mkdir(newdir)\n elif self._is_overwrite:\n force_remove(newdir)\n os.mkdir(newdir)\n self._bids_dir = newdir\n self._ignore.append(newdir)\n # as of BIDS ver 1.6.0, CT is not a part of BIDS, so check for CT files and add to .bidsignore\n self.bidsignore(\"*_CT.*\")\n\n def get_bids_version(self):\n return self._bids_version\n\n def bids_validator(self):\n assert self._bids_dir is not None, \"Cannot launch bids-validator without specifying bids directory !\"\n # try:\n subprocess.check_call(['bids-validator', self._bids_dir])\n # except FileNotFoundError:\n # print(\"bids-validator does not appear to be installed\")\n\n def generate_names(self, src_file_path, filename=None,\n # function to run through name text and generate metadata\n part_match=None,\n sess_match=None,\n ce_match=None,\n acq_match=None,\n echo_match=None,\n data_type_match=None,\n task_label_match=None,\n run_match=None,\n verbose=None,\n debug=False):\n if filename is None:\n filename = os.path.basename(src_file_path)\n if part_match is None:\n part_match = match_regexp(self._config[\"partLabel\"], filename)\n if verbose is None:\n verbose = self._is_verbose\n try:\n if re.match(r\"^[^\\d]{1,3}\", part_match):\n part_matches = re.split(r\"([^\\d]{1,3})\", part_match, 1)\n part_match_z = part_matches[1] + str(int(part_matches[2])).zfill(self._config[\"partLabel\"][\"fill\"])\n else:\n part_match_z = str(int(part_match)).zfill(self._config[\"partLabel\"][\"fill\"])\n except KeyError:\n pass\n dst_file_path = self._bids_dir + \"/sub-\" + part_match_z\n new_name = \"/sub-\" + part_match_z\n SeqType = None\n # Matching the session\n try:\n if sess_match is None:\n sess_match = match_regexp(self._config[\"sessLabel\"], filename)\n dst_file_path = dst_file_path + \"/ses-\" + sess_match\n new_name = new_name + \"_ses-\" + sess_match\n except AssertionError:\n if verbose:\n print(\"No session found for %s\" % src_file_path)\n\n # Matching the run number\n try:\n if run_match is None:\n run_match = match_regexp(self._config[\"runIndex\"], filename)\n try:\n if re.match(r\"^[^\\d]{1,3}\", run_match):\n run_matches = re.split(r\"([^\\d]{1,3})\", run_match, 1)\n run_match = run_matches[1] + str(int(run_matches[2])).zfill(self._config[\"runIndex\"][\"fill\"])\n else:\n run_match = str(int(run_match)).zfill(self._config[\"runIndex\"][\"fill\"])\n except KeyError:\n pass\n\n except AssertionError:\n pass\n\n # Matching the anat/fmri data type and task\n try:\n if data_type_match is None:\n data_type_match = match_regexp(self._config[\"anat\"]\n , filename\n , subtype=True)\n dst_file_path = dst_file_path + \"/anat\"\n self._data_types[\"anat\"] = True\n except (AssertionError, KeyError) as e:\n # If no anatomical, trying functionnal\n try:\n if data_type_match is None:\n data_type_match = match_regexp(self._config[\"func\"]\n , filename\n , subtype=True)\n dst_file_path = dst_file_path + \"/func\"\n self._data_types[\"func\"] = True\n # Now trying to match the task\n try:\n if task_label_match is None:\n task_label_match = match_regexp(self._config[\"func.task\"]\n , filename\n , subtype=True)\n new_name = new_name + \"_task-\" + task_label_match\n except AssertionError as e:\n print(\"No task found for %s\" % src_file_path)\n if debug:\n raise e\n return\n\n except (AssertionError, KeyError) as e:\n # no functional or anatomical, try ieeg\n try:\n if data_type_match is None:\n data_type_match = match_regexp(self._config[\"ieeg\"]\n , filename\n , subtype=True)\n dst_file_path = dst_file_path + \"/ieeg\"\n self._data_types[\"ieeg\"] = True\n # Now trying to match the task\n try:\n if task_label_match is None:\n task_label_match = match_regexp(self._config[\"ieeg.task\"]\n , filename\n , subtype=True)\n new_name = new_name + \"_task-\" + task_label_match\n except AssertionError as e:\n print(\"No task found for %s\" % src_file_path)\n if debug:\n raise e\n return\n except AssertionError as e:\n if verbose:\n print(\"No anat, func, or ieeg data type found for %s\" % src_file_path)\n if debug:\n raise e\n return\n except KeyError as e:\n print(\"No anat, func, or ieeg data type found in config file, one of these data types is required\")\n if debug:\n raise e\n return\n\n # if is an MRI\n if dst_file_path.endswith(\"/func\") or dst_file_path.endswith(\"/anat\"):\n try:\n SeqType = str(match_regexp(self._config[\"pulseSequenceType\"], filename, subtype=True))\n except AssertionError:\n if verbose:\n print(\"No pulse sequence found for %s\" % src_file_path)\n except KeyError:\n if verbose:\n print(\"pulse sequence not listed for %s, will look for in file header\" % src_file_path)\n try:\n if echo_match is None:\n echo_match = match_regexp(self._config[\"echo\"], filename)\n new_name = new_name + \"_echo-\" + echo_match\n except AssertionError:\n if verbose:\n print(\"No echo found for %s\" % src_file_path)\n\n # check for optional labels\n try:\n if acq_match is None:\n acq_match = match_regexp(self._config[\"acq\"], filename)\n try:\n if re.match(r\"^[^\\d]{1,3}\", acq_match):\n acq_matches = re.split(r\"([^\\d]{1,3})\", acq_match, 1)\n acq_match = acq_matches[1] + str(int(acq_matches[2])).zfill(self._config[\"acq\"][\"fill\"])\n else:\n acq_match = str(int(acq_match)).zfill(self._config[\"acq\"][\"fill\"])\n except KeyError:\n pass\n\n new_name = new_name + \"_acq-\" + acq_match\n except (AssertionError, KeyError) as e:\n if verbose:\n print(\"no optional labels for %s\" % src_file_path)\n try:\n if ce_match is None:\n ce_match = match_regexp(self._config[\"ce\"]\n , filename)\n new_name = new_name + \"_ce-\" + ce_match\n\n except (AssertionError, KeyError) as e:\n if verbose:\n print(\"no special contrast labels for %s\" % src_file_path)\n\n if run_match is not None:\n new_name = new_name + \"_run-\" + run_match\n\n # Adding the modality to the new filename\n new_name = new_name + \"_\" + data_type_match\n\n return (new_name, dst_file_path, part_match, run_match,\n acq_match, echo_match, sess_match, ce_match,\n data_type_match, task_label_match, SeqType)\n\n def multi_echo_check(self, runnum, src_file=\"\"): # check to see if run is multi echo based on input\n if self.is_multi_echo:\n if int(runnum) in self._multi_echo:\n return (True)\n else:\n if self._multi_echo == 0:\n try:\n match_regexp(self._config[\"echo\"], src_file)\n except AssertionError:\n return (False)\n return (True)\n else:\n return (False)\n else:\n return (False)\n\n def get_params(self, folder, echo_num, run_num): # function to run through DICOMs and get metadata\n # threading?\n if self.is_multi_echo and run_num in self._multi_echo:\n vols_per_time = len(self._config['delayTimeInSec']) - 1\n echo = self._config['delayTimeInSec'][echo_num]\n else:\n vols_per_time = 1\n echo = None\n\n for root, _, dfiles in os.walk(folder, topdown=True):\n dfiles.sort()\n for dfile in dfiles:\n dcm_file_path = os.path.join(root, dfile)\n fobj = dicom.read_file(str(dcm_file_path))\n if echo is None:\n try:\n echo = float(fobj[0x18, 0x81].value) / 1000\n except KeyError:\n echo = self._config['delayTimeInSec'][0]\n ImagesInAcquisition = int(fobj[0x20, 0x1002].value)\n seqlist = []\n for i in list(range(5)):\n try:\n seqlist.append(fobj[0x18, (32 + i)].value)\n if seqlist[i] == 'NONE':\n seqlist[i] = None\n if isinstance(seqlist[i], dicom.multival.MultiValue):\n seqlist[i] = list(seqlist[i])\n if isinstance(seqlist[i], list):\n seqlist[i] = \", \".join(seqlist[i])\n except KeyError:\n seqlist.append(None)\n [ScanningSequence, SequenceVariant, SequenceOptions, AquisitionType, SequenceName] = seqlist\n try:\n timings = []\n except NameError:\n timings = [None] * int(ImagesInAcquisition / vols_per_time)\n\n RepetitionTime = (\n (float(fobj[0x18, 0x80].value) / 1000)) # TR value extracted in milliseconds, converted to seconds\n try:\n acquisition_series = self._config['series']\n except KeyError:\n print(\"default\")\n acquisition_series = \"non-interleaved\"\n if acquisition_series == \"even-interleaved\":\n InstackPositionNumber = 2\n else:\n InStackPositionNumber = 1\n InstanceNumber = 0\n while None in timings:\n if timings[InStackPositionNumber - 1] is None:\n timings[InStackPositionNumber - 1] = slice_time_calc(RepetitionTime, InstanceNumber,\n int(ImagesInAcquisition / vols_per_time),\n echo)\n if acquisition_series == \"odd-interleaved\" or acquisition_series == \"even-interleaved\":\n InStackPositionNumber += 2\n if InStackPositionNumber > ImagesInAcquisition / vols_per_time and acquisition_series == \"odd-interleaved\":\n InStackPositionNumber = 2\n elif InStackPositionNumber > ImagesInAcquisition / vols_per_time and acquisition_series == \"even-interleaved\":\n InStackPositionNumber = 1\n else:\n InStackPositionNumber += 1\n InstanceNumber += 1\n return (timings, echo, ScanningSequence, SequenceVariant, SequenceOptions, SequenceName)\n\n def read_edf(self, file_name, channels=None, extra_arrays=None, extra_signal_headers=None):\n\n [edfname, dst_path, part_match] = self.generate_names(file_name, verbose=False)[0:3]\n # file_name = str(file_name)\n header = highlevel.make_header(patientname=part_match, startdate=datetime.datetime(1, 1, 1))\n edf_name = dst_path + edfname + \".edf\"\n d = {str: [], int: []}\n for i in channels:\n d[type(i)].append(i)\n\n f = EdfReader(file_name)\n chn_nums = d[int] + [i for i, x in enumerate(f.getSignalLabels()) if x in channels]\n f.close()\n chn_nums.sort()\n\n try:\n check_sep = self._config[\"eventFormat\"][\"Sep\"]\n except (KeyError, AssertionError) as e:\n check_sep = None\n\n gc.collect() # helps with memory\n\n if check_sep:\n # read edf\n print(\"Reading \" + file_name + \"...\")\n [array, signal_headers, _] = highlevel.read_edf(file_name, ch_nrs=chn_nums,\n digital=self._config[\"ieeg\"][\"digital\"],\n verbose=True)\n if extra_arrays:\n array = array + extra_arrays\n if extra_signal_headers:\n signal_headers = signal_headers + extra_signal_headers\n\n # replace trigger channels with trigger label (\"DC1\")\n if part_match in self._config[\"ieeg\"][\"headerData\"].keys():\n trig_label = self._config[\"ieeg\"][\"headerData\"][part_match]\n else:\n trig_label = self._config[\"ieeg\"][\"headerData\"][\"default\"]\n for i in range(len(signal_headers)):\n #print(re.match(\".*\\.xls.*\", trig_label))\n if re.match(\".*\\.xls.*\", str(trig_label)):\n xls_df = pd.ExcelFile(trig_label).parse(part_match)\n for column in xls_df:\n if \"Trigger\" in column:\n trig_label = xls_df[column].iloc[0]\n if signal_headers[i][\"label\"] == trig_label:\n signal_headers[i][\"label\"] = \"Trigger\"\n\n return dict(name=file_name, bids_name=edf_name, nsamples=array.shape[1], signal_headers=signal_headers,\n file_header=header, data=array, reader=f)\n elif channels:\n highlevel.drop_channels(file_name, edf_name, channels, verbose=self._is_verbose)\n return None\n else:\n shutil.copy(file_name, edf_name)\n return None\n\n def part_check(self, part_match=None, filename=None):\n # Matching the participant label to determine if\n # there exists therein delete previously created BIDS subject files\n\n assert part_match or filename\n\n if filename:\n\n try:\n part_match = match_regexp(self._config[\"partLabel\"], filename)\n except AssertionError:\n print(\"No participant found for %s\" % filename)\n except KeyError as e:\n print(\"Participant label pattern must be defined\")\n raise e\n\n if re.match(r\"^[^\\d]{1,3}\", part_match):\n part_matches = re.split(r\"([^\\d]{1,3})\", part_match, 1)\n part_match_z = part_matches[1] + str(int(part_matches[2])).zfill(self._config[\"partLabel\"][\"fill\"])\n else:\n part_match_z = str(int(part_match)).zfill(self._config[\"partLabel\"][\"fill\"])\n\n return part_match, part_match_z\n\n def bidsignore(self, string: str):\n if not os.path.isfile(self._bids_dir + \"/.bidsignore\"):\n with open(self._bids_dir + \"/.bidsignore\", 'w') as f:\n f.write(string + \"\\n\")\n else:\n with open(self._bids_dir + \"/.bidsignore\", \"r+\") as f:\n if string not in f.read():\n f.write(string + \"\\n\")\n\n def run(self): # main function\n\n # First we check that every parameters are configured\n if (self._data_dir is not None\n and self._config_path is not None\n and self._config is not None\n and self._bids_dir is not None):\n\n print(\"---- data2bids starting ----\")\n print(self._data_dir)\n print(\"\\n BIDS version:\")\n print(self._bids_version)\n print(\"\\n Config from file :\")\n print(self._config_path)\n print(\"\\n Ouptut BIDS directory:\")\n print(self._bids_dir)\n print(\"\\n\")\n\n # Create the output BIDS directory\n if not os.path.exists(self._bids_dir):\n os.makedirs(self._bids_dir)\n # else\n # shutil.rmtree(self._bids_dir)\n\n # What is the base format to convert to\n curr_ext = self._config[\"dataFormat\"]\n compress = self._config[\"compress\"]\n\n # delay time in TR unit (if delay_time = 1, delay_time = repetition_time)\n repetition_time = self._config[\"repetitionTimeInSec\"]\n delaytime = self._config[\"delayTimeInSec\"]\n\n # dataset_description.json must be included in the folder root foolowing BIDS specs\n if os.path.exists(self._bids_dir + \"/dataset_description.json\"):\n # with open(dst_file_path + new_name + \".json\", 'w') as fst:\n with open(self._bids_dir + \"/dataset_description.json\") as fst:\n filedata = json.load(fst)\n with open(self._bids_dir + \"/dataset_description.json\", 'w') as fst:\n data = {'Name': self._dataset_name,\n 'BIDSVersion': self._bids_version}\n filedata.update(data)\n json.dump(filedata, fst, ensure_ascii=False, indent=4)\n else:\n with open(self._bids_dir + \"/dataset_description.json\", 'w') as fst:\n data = {'Name': self._dataset_name,\n 'BIDSVersion': self._bids_version}\n json.dump(data, fst, ensure_ascii=False, indent=4)\n\n try:\n for key, data in self._config[\"JSON_files\"].items():\n with open(self._bids_dir + '/' + key, 'w') as fst:\n json.dump(data, fst, ensure_ascii=False, indent=4)\n except KeyError:\n pass\n\n # add a README file\n if not os.path.exists(self._bids_dir + \"/README\"):\n with open(self._bids_dir + \"/README\", 'w') as fst:\n data = \"\"\n fst.write(data)\n\n # now we can scan all files and rearrange them\n part_match = None\n part_match_z = None\n for root, _, files in os.walk(self._data_dir,\n topdown=True):\n # each loop is a new participant so long as participant is top level\n files[:] = [f for f in files if not self.check_ignore(os.path.join(root, f))]\n eeg = []\n dst_file_path_list = []\n names_list = []\n mat_list = []\n run_list = []\n tsv_condition_runs = []\n tsv_fso_runs = []\n d_list = []\n txt_df_list = []\n correct = None\n if not files:\n continue\n files.sort()\n part_match = None\n i = 0\n while part_match is None:\n try:\n part_match, part_match_z = self.part_check(filename=files[i])\n except:\n i += 1\n continue\n if self.channels:\n if self._is_verbose and self.channels[part_match] is not None:\n print(\"Channels for participant \" + part_match + \" are\")\n print(self.channels[part_match])\n for i in self._ignore:\n if part_match in i:\n print(\"From \" + i)\n if self._is_verbose:\n print(files)\n while files: # loops over each participant file\n file = files.pop(0)\n if self._is_verbose:\n print(file)\n src_file_path = os.path.join(root, file)\n dst_file_path = self._bids_dir\n data_type_match = None\n new_name = None\n\n if re.match(\".*?\" + \".json\", file):\n try:\n (new_name, dst_file_path, part_match, run_match,\n acq_match, echo_match, sess_match, ce_match,\n data_type_match, task_label_match, SeqType) = self.generate_names(src_file_path,\n part_match=part_match)\n except TypeError:\n continue\n if echo_match is None:\n echo_match = 0\n if new_name in names_list:\n shutil.copy(src_file_path, dst_file_path + new_name + \".json\")\n # finally, if it is a bold experiment, we need to edit the JSON file using DICOM tags\n if os.path.exists(dst_file_path + new_name + \".json\"):\n # https://github.com/nipy/nibabel/issues/712, that is why we take the\n # scanner parameters from the config.json\n # nib_img = nib.load(src_file_path)\n # TR = nib_img.header.get_zooms()[3]\n for foldername in os.listdir(str(self._DICOM_path)):\n if run_match.zfill(4) == foldername.zfill(4):\n DICOM_filepath = os.path.join(self._DICOM_path, foldername)\n slicetimes, echotime, ScanSeq, SeqVar, SeqOpt, SeqName = self.get_params(\n str(DICOM_filepath), int(echo_match), int(run_match))\n\n # with open(dst_file_path + new_name + \".json\", 'w') as fst:\n with open(dst_file_path + new_name + \".json\", 'r+') as fst:\n filedata = json.load(fst)\n with open(dst_file_path + new_name + \".json\", 'w') as fst:\n if data_type_match == \"bold\":\n filedata['TaskName'] = task_label_match\n filedata['SliceTiming'] = slicetimes\n if int(run_match) in self._multi_echo:\n filedata['EchoTime'] = echotime\n else:\n filedata['DelayTime'] = delaytime[0]\n if SeqType is not None:\n filedata['PulseSequenceType'] = SeqType\n if ScanSeq is not None:\n filedata['ScanningSequence'] = ScanSeq\n if SeqVar is not None:\n filedata['SequenceVariant'] = SeqVar\n if SeqOpt is not None:\n filedata['SequenceOption'] = SeqOpt\n if SeqName is not None:\n filedata['SequenceName'] = SeqName\n json.dump(filedata, fst, ensure_ascii=False, indent=4, default=set_default)\n else:\n print(\"Cannot update %s\" % (dst_file_path + new_name + \".json\"))\n elif any(re.search(\"\\\\.nii\", filelist) for filelist in files):\n files.append(src_file_path)\n continue\n elif re.match(\".*?\" + \"EADME.txt\", file): # if README.txt in image list\n with open(src_file_path, 'r') as readmetext:\n for line in readmetext:\n regret_words = [\"Abort\", \"NOTE\"]\n if \". tempAttnAudT\" in line:\n # these lines could and should be improved by\n # linking config[\"func.task\"] instead of literal strings\n prevline = \"con\"\n tsv_condition_runs.append(\n re.search(r'\\d+', line).group()) # save the first number on the line\n elif \". fsoSubLocal\" in line:\n prevline = \"fso\"\n tsv_fso_runs.append(re.search(r'\\d+', line).group())\n elif all(x in line for x in regret_words):\n if prevline == \"con\":\n del tsv_condition_runs[-1]\n elif prevline == \"fso\":\n del tsv_fso_runs[-1]\n prevline = \"\"\n else:\n prevline = \"\"\n if not os.path.exists(\n self._bids_dir + \"/sub-\" + part_match):\n # Writing both a particpant-specific and agnostic README\n # Requires creation of a .bidsignore file for local READMEs\n os.makedirs(self._bids_dir + \"/sub-\" + part_match)\n shutil.copy(src_file_path, self._bids_dir + \"/sub-\" + part_match + \"/README.txt\")\n with open(src_file_path, 'r') as readmetext:\n for line in readmetext:\n if os.path.exists(self._bids_dir + \"/README\"):\n with open(self._bids_dir + \"/README\", 'a') as f:\n f.write(line + \"\\n\")\n else:\n with open(self._bids_dir + \"/README\", 'w') as f:\n f.write(line + \"\\n\")\n continue\n elif re.match(\".*?\" + \"\\\\.1D\", file):\n d_list.append(src_file_path)\n continue\n elif re.match(\".*?\" + \"\\\\.mat\", file):\n mat_list.append(src_file_path)\n continue\n # if the file doesn't match the extension, we skip it\n elif re.match(\".*?\" + \"\\\\.txt\", file):\n if part_match is None:\n files.append(file)\n else:\n try:\n df = pd.read_table(src_file_path, header=None, sep=\"\\s+\")\n e = None\n except Exception as e:\n df = None\n txt_df_list.append(dict(name=file, data=df, error=e))\n continue\n elif not any(re.match(\".*?\" + ext, file) for ext in curr_ext):\n print(\"Warning : Skipping %s\" % src_file_path)\n continue\n if self._is_verbose:\n print(\"trying %s\" % src_file_path)\n try:\n (new_name, dst_file_path, part_match, run_match,\n acq_match, echo_match, sess_match, ce_match,\n data_type_match, task_label_match, _) = self.generate_names(src_file_path,\n part_match=part_match)\n except TypeError as problem: #\n print(\"\\nIssue in generate names\")\n print(\"problem with %s:\" % src_file_path, problem, \"\\n\")\n\n continue\n\n # Creating the directory where to store the new file\n if not os.path.exists(dst_file_path):\n os.makedirs(dst_file_path)\n\n # print(data_type_match)\n # finally, if the file is not nifti\n if dst_file_path.endswith(\"/func\") or dst_file_path.endswith(\"/anat\"):\n # we convert it using nibabel\n if not any(file.endswith(ext) for ext in [\".nii\", \".nii.gz\"]):\n # check if .nii listed in config file, not if file ends with .nii\n # loading the original image\n nib_img = nib.load(src_file_path)\n nib_affine = np.array(nib_img.affine)\n nib_data = np.array(nib_img.dataobj)\n\n # create the nifti1 image\n # if minc format, invert the data and change the affine transformation\n # there is also an issue on minc headers\n if file.endswith(\".mnc\"):\n if len(nib_img.shape) > 3:\n nib_affine[0:3, 0:3] = nib_affine[0:3, 0:3]\n rot_z(np.pi / 2)\n rot_y(np.pi)\n rot_x(np.pi / 2)\n nib_data = nib_data.T\n nib_data = np.swapaxes(nib_data, 0, 1)\n\n nifti_img = nib.Nifti1Image(nib_data, nib_affine, nib_img.header)\n nifti_img.header.set_xyzt_units(xyz=\"mm\", t=\"sec\")\n zooms = np.array(nifti_img.header.get_zooms())\n zooms[3] = repetition_time\n nifti_img.header.set_zooms(zooms)\n elif len(nib_img.shape) == 3:\n nifti_img = nib.Nifti1Image(nib_data, nib_affine, nib_img.header)\n nifti_img.header.set_xyzt_units(xyz=\"mm\")\n else:\n nifti_img = nib.Nifti1Image(nib_data, nib_affine, nib_img.header)\n\n # saving the image\n nib.save(nifti_img, dst_file_path + new_name + \".nii.gz\")\n\n # if it is already a nifti file, no need to convert it so we just copy rename\n if file.endswith(\".nii.gz\"):\n shutil.copy(src_file_path, dst_file_path + new_name + \".nii.gz\")\n elif file.endswith(\".nii\"):\n shutil.copy(src_file_path, dst_file_path + new_name + \".nii\")\n # compression just if .nii files\n if compress is True:\n print(\"zipping \" + file)\n with open(dst_file_path + new_name + \".nii\", 'rb') as f_in:\n with gzip.open(dst_file_path + new_name + \".nii.gz\", 'wb',\n self._config[\"compressLevel\"]) as f_out:\n shutil.copyfileobj(f_in, f_out)\n os.remove(dst_file_path + new_name + \".nii\")\n\n elif dst_file_path.endswith(\"/ieeg\"):\n remove_src_edf = True\n headers_dict = self.channels[part_match]\n if file.endswith(\".edf\"):\n remove_src_edf = False\n elif file.endswith(\".edf.gz\"):\n with gzip.open(src_file_path, 'rb', self._config[\"compressLevel\"]) as f_in:\n with open(src_file_path.rsplit(\".gz\", 1)[0], 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n elif not self._config[\"ieeg\"][\"binary?\"]:\n raise NotImplementedError(\n \"{file} file format not yet supported. If file is binary format, please indicate so \"\n \"and what encoding in the config.json file\".format(\n file=file))\n elif headers_dict and any(\".mat\" in i for i in files) and self.sample_rate[\n part_match] is not None:\n # assume has binary encoding\n try: # open binary file and write decoded numbers as array where rows = channels\n # check if zipped\n if file.endswith(\".gz\"):\n with gzip.open(src_file_path, 'rb', self._config[\"compressLevel\"]) as f:\n data = np.frombuffer(f.read(),\n dtype=np.dtype(self._config[\"ieeg\"][\"binaryEncoding\"]))\n else:\n with open(src_file_path, mode='rb') as f:\n data = np.fromfile(f, dtype=self._config[\"ieeg\"][\"binaryEncoding\"])\n array = np.reshape(data, [len(headers_dict), -1],\n order='F') # byte order is Fortran encoding, dont know why\n signal_headers = highlevel.make_signal_headers(headers_dict,\n sample_rate=self.sample_rate[part_match],\n physical_max=np.amax(array),\n physical_min=(np.amin(array)))\n print(\"converting binary\" + src_file_path + \" to edf\" + os.path.splitext(src_file_path)[\n 0] + \".edf\")\n highlevel.write_edf(os.path.splitext(src_file_path)[0] + \".edf\", array, signal_headers,\n digital=self._config[\"ieeg\"][\"digital\"])\n except OSError as e:\n print(\"eeg file is either not detailed well enough in config file or file type not yet \"\n \"supported\")\n raise e\n else:\n raise FileNotFoundError(\"{file} header could not be found\".format(file=file))\n\n # check for extra channels in data, not working in other file modalities\n f = EdfReader(os.path.splitext(src_file_path)[0] + \".edf\")\n extra_arrays = []\n extra_signal_headers = []\n if any(len(mat2df(os.path.join(root, fname))) == f.samples_in_file(0) for fname in\n [i for i in files if i.endswith(\".mat\")]) or any(\n len(mat2df(os.path.join(root, fname))) == f.samples_in_file(0) for fname in [\n i for i in mat_list if i.endswith(\".mat\")]):\n\n for fname in [i for i in files + mat_list if i.endswith(\".mat\")]:\n sig_len = f.samples_in_file(0)\n if not os.path.isfile(fname):\n fname = os.path.join(root, fname)\n if mat2df(fname) is None:\n continue\n elif len(mat2df(fname)) == sig_len:\n if fname in files:\n files.remove(fname)\n if fname in mat_list:\n mat_list.remove(fname)\n df = pd.DataFrame(mat2df(fname))\n for cols in df.columns:\n extra_arrays = np.vstack([extra_arrays, df[cols]])\n extra_signal_headers.append(highlevel.make_signal_header(\n os.path.splitext(os.path.basename(fname))[0]\n , sample_rate=self.sample_rate[part_match]))\n elif sig_len * 0.99 <= len(mat2df(fname)) <= sig_len * 1.01:\n raise BufferError(\n file + \"of size\" + sig_len + \"is not the same size as\" + fname + \"of size\" +\n len(mat2df(fname)))\n f.close()\n # read edf and either copy data to BIDS file or save data as dict for writing later\n eeg.append(self.read_edf(os.path.splitext(src_file_path)[0] + \".edf\", headers_dict,\n extra_arrays, extra_signal_headers))\n if remove_src_edf:\n if self._is_verbose:\n print(\"Removing \" + os.path.splitext(src_file_path)[0] + \".edf\")\n os.remove(os.path.splitext(src_file_path)[0] + \".edf\")\n\n # move the sidecar from input to output\n names_list.append(new_name)\n dst_file_path_list.append(dst_file_path)\n try:\n if run_match is not None:\n run_list.append(int(run_match))\n except UnboundLocalError:\n pass\n\n if d_list:\n self.convert_1D(run_list, d_list, tsv_fso_runs, tsv_condition_runs, names_list, dst_file_path_list)\n\n if mat_list: # deal with remaining .mat files\n self.mat2tsv(mat_list)\n\n if txt_df_list:\n for txt_df_dict in txt_df_list:\n if self._config[\"coordsystem\"] in txt_df_dict[\"name\"]:\n if txt_df_dict[\"error\"] is not None:\n raise txt_df_dict[\"error\"]\n df = txt_df_dict[\"data\"]\n df.columns = [\"name1\", \"name2\", \"x\", \"y\", \"z\", \"hemisphere\", \"del\"]\n df[\"name\"] = df[\"name1\"] + df[\"name2\"].astype(str).str.zfill(2)\n df[\"hemisphere\"] = df[\"hemisphere\"] + df[\"del\"]\n df = df.drop(columns=[\"name1\", \"name2\", \"del\"])\n df = pd.concat([df[\"name\"], df[\"x\"], df[\"y\"], df[\"z\"], df[\"hemisphere\"]], axis=1)\n df.to_csv(self._bids_dir + \"/sub-\" + part_match_z + \"/sub-\" + part_match_z +\n \"_space-Talairach_electrodes.tsv\", sep=\"\\t\", index=False)\n elif self._config[\"eventFormat\"][\"AudioCorrection\"] in txt_df_dict[\"name\"]:\n if txt_df_dict[\"error\"] is not None:\n raise txt_df_dict[\"error\"]\n correct = txt_df_dict[\"data\"]\n else:\n print(\"skipping \" + txt_df_dict[\"name\"])\n\n # check final file set\n for new_name in names_list:\n print(new_name)\n file_path = dst_file_path_list[names_list.index(new_name)]\n full_name = file_path + new_name + \".edf\"\n task_match = re.match(\".*_task-(\\w*)_.*\", full_name)\n if task_match:\n task_label_match = task_match.group(1)\n # split any edfs according to tsvs\n if new_name.endswith(\"_ieeg\") and any(re.match(new_name.split(\"_ieeg\")[0].split(\"/\", 1)[1] +\n \"(?:\" + \"_acq-\" + self._config[\"acq\"][\"content\"][0] +\n \")?\" + \"_run-\" + self._config[\"runIndex\"][\"content\"][\n 0] + \"_events.tsv\", set_file) for set_file in\n os.listdir(file_path)): # if edf is not yet split\n\n if self._is_verbose:\n print(\"Reading for split... \")\n if full_name in [i[\"bids_name\"] for i in eeg]:\n eeg_dict = eeg[[i[\"bids_name\"] for i in eeg].index(full_name)]\n else:\n raise LookupError(\n \"This error should not have been raised, was edf file \" + full_name + \" ever written?\"\n , [i[\"name\"] for i in eeg])\n [array, signal_headers, header] = [eeg_dict[\"data\"], eeg_dict[\"signal_headers\"],\n eeg_dict[\"file_header\"]]\n start_nums = []\n matches = []\n for file in sorted(os.listdir(file_path)):\n match_tsv = re.match(new_name.split(\"_ieeg\", 1)[0].split(\"/\", 1)[1] +\n \"(?:_acq-\" + self._config[\"acq\"][\"content\"][0] + \")?_run-(\" +\n self._config[\"runIndex\"][\"content\"][0] + \")_events.tsv\", file)\n if match_tsv:\n df = pd.read_csv(os.path.join(file_path, file), sep=\"\\t\", header=0)\n # converting signal start and end to correct sample rate for data\n end_num = str2num(df[self._config[\"eventFormat\"][\"Timing\"][\"end\"]].iloc[-1])\n i = -1\n while not isinstance(end_num, (int, float)):\n print(end_num, type(end_num))\n i -= 1\n end_num = str2num(df[self._config[\"eventFormat\"][\"Timing\"][\"end\"]].iloc[i])\n num_list = [round((float(x) / float(self._config[\"eventFormat\"][\"SampleRate\"])) *\n signal_headers[0][\"sample_rate\"]) for x in (\n df[self._config[\"eventFormat\"][\"Timing\"][\"start\"]][0], end_num)]\n start_nums.append(tuple(num_list))\n matches.append(match_tsv)\n for i in range(len(start_nums)):\n if i == 0:\n start = 0\n practice = os.path.join(file_path, \"practice\" + new_name.split(\"_ieeg\", 1)[0]\n + \"_ieeg.edf\")\n if not os.path.isfile(practice) and self._config[\"split\"][\"practice\"]:\n os.makedirs(os.path.join(file_path, \"practice\"), exist_ok=True)\n highlevel.write_edf(practice, np.split(array, [0, start_nums[0][0]], axis=1)[1],\n signal_headers, header, digital=self._config[\"ieeg\"][\"digital\"])\n self.bidsignore(\"*practice*\")\n else:\n start = start_nums[i - 1][1]\n\n if i == len(start_nums) - 1:\n end = array.shape[1]\n else:\n end = start_nums[i + 1][0]\n new_array = np.split(array, [start, end], axis=1)[1]\n tsv_name: str = os.path.join(file_path, matches[i].string)\n edf_name: str = os.path.join(file_path, matches[i].string.split(\"_events.tsv\", 1)[0]\n + \"_ieeg.edf\")\n full_name = os.path.join(file_path, new_name.split(\"/\", 1)[1] + \".edf\")\n if self._is_verbose:\n print(full_name + \"(Samples[\" + str(start) + \":\" + str(end) + \"]) ---> \" + edf_name)\n highlevel.write_edf(edf_name, new_array, signal_headers, header,\n digital=self._config[\"ieeg\"][\"digital\"])\n df = pd.read_csv(tsv_name, sep=\"\\t\", header=0)\n os.remove(tsv_name)\n # all column manipulation and math in frame2bids\n df_new = self.frame2bids(df, self._config[\"eventFormat\"][\"Events\"],\n self.sample_rate[part_match], correct, start)\n df_new.to_csv(tsv_name, sep=\"\\t\", index=False,\n na_rep=\"n/a\")\n # dont forget .json files!\n self.write_sidecar(edf_name)\n self.write_sidecar(tsv_name)\n continue\n # write JSON file for any missing files\n self.write_sidecar(file_path + new_name)\n\n # write any indicated .json files\n try:\n json_list = self._config[\"JSON_files\"]\n except KeyError:\n json_list = dict()\n for jfile, contents in json_list.items():\n print(part_match_z, task_label_match, jfile)\n file_name = os.path.join(self._bids_dir, \"sub-\" + part_match_z, \"sub-\" + part_match_z + \"_task-\" +\n task_label_match + \"_\" + jfile)\n with open(file_name, \"w\") as fst:\n json.dump(contents, fst)\n # Output\n if self._is_verbose:\n tree(self._bids_dir)\n\n # Finally, we check with bids_validator if everything went alright (This wont work)\n # self.bids_validator()\n\n else:\n print(\"Warning: No parameters are defined !\")\n\n def write_sidecar(self, full_file):\n if full_file.endswith(\".tsv\"): # need to search BIDS specs for list of possible known BIDS columns\n data = dict()\n df = pd.read_csv(full_file, sep=\"\\t\")\n # for col in df.columns:\n # data[col] =\n return\n elif os.path.dirname(full_file).endswith(\"/ieeg\"):\n if not full_file.endswith(\".edf\"):\n full_file = full_file + \".edf\"\n entities = layout.parse_file_entities(full_file)\n f = EdfReader(full_file)\n if f.annotations_in_file == 0:\n description = \"n/a\"\n elif f.getPatientAdditional():\n description = f.getPatientAdditional()\n elif f.getRecordingAdditional():\n description = f.getRecordingAdditional()\n elif any((not i.size == 0) for i in f.readAnnotations()):\n description = [i for i in f.readAnnotations()]\n print(\"description:\", description)\n else:\n raise SyntaxError(full_file + \"was not annotated correctly\")\n signals = [sig for sig in f.getSignalLabels() if \"Trigger\" not in sig]\n data = dict(TaskName=entities['task'],\n InstitutionName=self._config[\"institution\"],\n iEEGReference=description, SamplingFrequency=int(f.getSignalHeader(0)[\"sample_rate\"]),\n PowerLineFrequency=60, SoftwareFilters=\"n/a\", ECOGChannelCount=len(signals),\n TriggerChannelCount=1, RecordingDuration=f.file_duration)\n\n elif os.path.dirname(full_file).endswith(\"/anat\"):\n entities = layout.parse_file_entities(full_file + \".nii.gz\")\n if entities[\"suffix\"] == \"CT\":\n data = {}\n elif entities[\"suffix\"] == \"T1w\":\n data = {}\n else:\n raise NotImplementedError(full_file + \"is not yet accounted for\")\n else:\n data = {}\n if not os.path.isfile(os.path.splitext(full_file)[0] + \".json\"):\n with open(os.path.splitext(full_file)[0] + \".json\", \"w\") as fst:\n json.dump(data, fst)\n\n def frame2bids(self, df: pd.DataFrame, events: Union[dict, List[dict]], data_sample_rate=None, audio_correction=None\n , start_at=0):\n new_df = None\n if isinstance(events, dict):\n events = list(events)\n event_order = 0\n for event in events:\n event_order += 1\n temp_df = pd.DataFrame()\n for key, value in event.items():\n if not re.match(r\"[\\w\\d()_]+[ +\\-/*%]+[\\w\\d()_]+\", value) and value not in df.columns:\n temp_df[key] = value\n else:\n try:\n temp_df[key] = df.eval(value) # pandas eval is the backend equation interpreter\n except TypeError as e:\n if re.match(r\"[\\w\\d()_]+[ +\\-/*%]+[\\w\\d()_]+\", value): # if evaluating a math expression\n for name in [i for i in re.split(r\"[ +\\-/*%]\", value) if i != '']:\n df[name] = pd.to_numeric(df[name], errors=\"coerce\")\n temp_df[key] = df.eval(value)\n else:\n raise e\n if \"trial_num\" not in temp_df.columns:\n temp_df[\"trial_num\"] = [1 + i for i in list(range(temp_df.shape[0]))]\n if \"duration\" not in temp_df.columns:\n if \"stim_file\" in temp_df.columns:\n temp = []\n t_correct = []\n for _, fname in temp_df[\"stim_file\"].iteritems():\n if fname.endswith(\".wav\"):\n if self.stim_dir is not None:\n fname = os.path.join(self.stim_dir, fname)\n dir = self.stim_dir\n else:\n dir = self._data_dir\n try:\n frames, data = wavfile.read(fname)\n except FileNotFoundError as e:\n print(fname + \" not found in current directory or in \" + dir)\n raise e\n if audio_correction is not None:\n correct = audio_correction.set_index(0).squeeze()[os.path.basename(\n os.path.splitext(fname)[0])] * self._config[\"eventFormat\"][\"SampleRate\"]\n else:\n correct = 0\n duration = (data.size / frames) * self._config[\"eventFormat\"][\"SampleRate\"]\n else:\n raise NotImplementedError(\"current build only supports .wav stim files\")\n temp.append(duration)\n t_correct.append(correct)\n temp_df[\"duration\"] = temp\n # audio correction\n if t_correct:\n temp_df[\"correct\"] = t_correct\n temp_df[\"duration\"] = temp_df.eval(\"duration - correct\")\n temp_df[\"onset\"] = temp_df.eval(\"onset + correct\")\n temp_df = temp_df.drop(columns=[\"correct\"])\n else:\n raise LookupError(\"duration of event or copy of audio file required but not found in \" +\n self._config_path)\n temp_df[\"event_order\"] = event_order\n if new_df is None:\n new_df = temp_df\n else:\n new_df = new_df.append(temp_df, ignore_index=True, sort=False)\n\n for name in [\"onset\", \"duration\"]:\n if not (pd.api.types.is_float_dtype(new_df[name]) or pd.api.types.is_integer_dtype(new_df[name])):\n new_df[name] = pd.to_numeric(new_df[name], errors=\"coerce\")\n if data_sample_rate is None:\n # onset is timing of even onset (in seconds)\n new_df[\"onset\"] = new_df[\"onset\"] / self._config[\"eventFormat\"][\"SampleRate\"]\n else:\n # sample is in exact sample of event onset (at eeg sample rate)\n new_df[\"sample\"] = (new_df[\"onset\"] / self._config[\"eventFormat\"][\n \"SampleRate\"] * data_sample_rate) - start_at\n # onset is timing of even onset (in seconds)\n new_df[\"onset\"] = new_df[\"sample\"] / data_sample_rate\n # round sample to nearest frame\n new_df[\"sample\"] = pd.to_numeric(new_df[\"sample\"].round(), errors=\"coerce\", downcast=\"integer\")\n # duration is duration of event (in seconds)\n new_df[\"duration\"] = new_df[\"duration\"] / self._config[\"eventFormat\"][\"SampleRate\"]\n\n if self._is_verbose:\n print(new_df.sort_values([\"trial_num\", \"event_order\"]).drop(columns=\"event_order\"))\n\n return new_df.sort_values([\"trial_num\", \"event_order\"]).drop(columns=\"event_order\")\n\n def mat2tsv(self, mat_files):\n part_match = None\n written = True\n is_separate = None\n for mat_file in mat_files:\n\n if not match_regexp(self._config[\"partLabel\"],\n mat_file) == part_match: # initialize dataframe if new participant\n if written:\n df = pd.DataFrame()\n elif not part_match == match_regexp(self._config[\"partLabel\"], mat_file):\n b_index = [j not in df.columns.values.tolist() for j in self._config[\"eventFormat\"][\"Sep\"]].index(\n True)\n raise FileNotFoundError(\"{config} variable was not found in {part}'s event files\".format(\n config=list(self._config[\"eventFormat\"][\"Sep\"].values())[b_index], part=part_match))\n try:\n part_match = match_regexp(self._config[\"partLabel\"], mat_file)\n except AssertionError:\n raise SyntaxError(\"file: {filename} has no matching {config}\\n\".format(filename=mat_file, config=\n self._config[\"content\"][:][0]))\n df_new = mat2df(mat_file, self._config[\"eventFormat\"][\"Labels\"])\n # check to see if new data is introduced. If not then keep searching\n if isinstance(df_new, pd.Series):\n df_new = pd.DataFrame(df_new)\n if df_new.shape[0] > df.shape[0]:\n df = pd.concat([df[df.columns.difference(df_new.columns)], df_new], axis=1) # auto filters duplicates\n elif df_new.shape[0] == df.shape[0]:\n df = pd.concat([df, df_new[df_new.columns.difference(df.columns)]], axis=1) # auto filters duplicates\n else:\n continue\n written = False\n\n if self._is_verbose:\n print(df)\n try:\n if self._config[\"eventFormat\"][\"IDcol\"] in df.columns.values.tolist(): # test if edfs should be\n # separated by block or not\n if len(df[self._config[\"eventFormat\"][\"IDcol\"]].unique()) == 1 and self._config[\"split\"][\"Sep\"] not \\\n in [\"all\", True] or not self._config[\"split\"][\"Sep\"]:\n # CHANGE this in case literal name doesn't change\n is_separate = False\n print(\"Warning: data may have been lost if file ID didn't change but the recording session did\")\n # construct fake orig data name to run through name generator\n # fix this as well so it works for all data types and modalities\n match_name = mat_file.split(os.path.basename(mat_file))[0] + \\\n df[self._config[\"eventFormat\"][\"IDcol\"]][0] + self._config[\"ieeg\"][\"content\"][0][1]\n else: # this means there was more than one recording session. In this case we will separate each\n # trial block into a separate \"run\"\n is_separate = True\n else:\n continue\n except KeyError:\n match_name = mat_file\n\n # write the tsv from the dataframe\n # if not changed: check to see if there is anything new to write\n if is_separate:\n if not all(j in df.columns.values.tolist() for j in self._config[\"eventFormat\"][\"Sep\"].values()):\n if self._is_verbose:\n print(mat_file)\n continue\n\n # make sure numbers do not repeat when not wanted\n df_unique = df.filter(self._config[\"eventFormat\"][\"Sep\"].values()).drop_duplicates()\n for i in range(df_unique.shape[0])[1:]:\n for j in self._config[\"eventFormat\"][\"Sep\"].keys():\n jval = self._config[\"eventFormat\"][\"Sep\"][j]\n try:\n if self._config[j][\"repeat\"] is False:\n try: # making sure actual key errors get caught\n if df_unique[jval].iat[i] in df_unique[jval].tolist()[:i]:\n df_unique[jval].iat[i] = str(int(max(df_unique[jval].tolist())) + 1)\n except KeyError as e:\n raise ValueError(e)\n else:\n continue\n except KeyError:\n continue\n\n tupelist = list(\n df.filter(self._config[\"eventFormat\"][\"Sep\"].values()).drop_duplicates().itertuples(index=False))\n for i in range(len(tupelist)): # iterate through every block\n nindex = (df.where(\n df.filter(self._config[\"eventFormat\"][\"Sep\"].values()) == tupelist[i]) == df).filter(\n self._config[\"eventFormat\"][\"Sep\"].values()).all(axis=1)\n match_name = mat_file.split(os.path.basename(mat_file))[0] + str(\n df[self._config[\"eventFormat\"][\"IDcol\"]][nindex].iloc[0])\n for k in self._config[\"eventFormat\"][\"Sep\"].keys():\n if k in self._config.keys():\n data = str(df_unique[self._config[\"eventFormat\"][\"Sep\"][k]].iloc[i])\n match_name = match_name + gen_match_regexp(self._config[k], data)\n\n # fix this to check for data type\n match_name = match_name + self._config[\"ieeg\"][\"content\"][0][1]\n item = self.generate_names(match_name, verbose=False)\n if item is not None:\n (new_name, dst_file_path) = item[0:2]\n else:\n self.generate_names(match_name, verbose=True, debug=True)\n raise\n writedf = df.loc[nindex]\n if self._is_verbose:\n print(mat_file, \"--->\", dst_file_path + new_name.split(\"ieeg\")[0] + \"events.tsv\")\n writedf.to_csv(dst_file_path + new_name.split(\"ieeg\")[0] + \"events.tsv\", sep=\"\\t\", index=False)\n else:\n (new_name, dst_file_path) = self.generate_names(match_name, verbose=False)[0:2]\n if self._is_verbose:\n print(mat_file, \"--->\", dst_file_path + new_name.split(\"ieeg\")[0] + \"events.tsv\")\n df.to_csv(dst_file_path + new_name.split(\"ieeg\")[0] + \"events.tsv\", sep=\"\\t\", index=False)\n written = True\n\n def convert_1D(self, run_list, d_list, tsv_fso_runs, tsv_condition_runs, names_list, dst_file_path_list):\n # This section is for converting .1D files to tsv event files. If you have the 1D files that's great,\n # but chances are you have some other format if this is the case,I recommend\n # https://bids-specification.readthedocs.io/en/stable/04-modality-specific-files/05-task-events.html\n # so that you can make BIDS compliant event files\n fields = list(list() for _ in range(max(run_list)))\n categories = list(list() for _ in range(max(run_list)))\n writenames = list(list() for _ in range(max(run_list)))\n n = 0 # creating variables to save and write from\n for d_file in d_list:\n # print(d_file)\n n += 1\n\n try:\n category = re.search(\"-[0-9]{4}-[0-9]{1,2}-(.*)\\\\.1D\", d_file).group(\n 1) # search filename for category label\n except AttributeError:\n try:\n category = re.search(\"-[0-9]{4}-(.{1,2}-?.*)\\\\.1D\", d_file).group(1)\n except AttributeError:\n print(d_file + \" has no pattern matching: -####-(????)\")\n continue\n nfso = 0\n ncon = 0\n with open(d_file) as lines: # loop through .tsv file line by line (each is a different run)\n for line in lines:\n if \"fso-\" in d_file:\n try:\n runnum = int(tsv_fso_runs[nfso])\n nfso += 1\n except IndexError:\n print('Error, index was %s while list was:' % str(nfso))\n print(tsv_fso_runs)\n continue\n elif \"condition-\" in d_file:\n try:\n runnum = int(tsv_condition_runs[ncon])\n ncon += 1\n except IndexError:\n print('Error, index was %s while list was:' % str(ncon))\n print(tsv_condition_runs)\n continue\n else:\n continue\n i = 0\n for name in names_list:\n try:\n if runnum is int(re.search(\"run-([0-9]{2})\", name).group(1)):\n if re.match(\".*?\" + \"_bold\" + \".*?\", name):\n name = name.replace(\"_bold\", \"\")\n if re.match(\".*?\" + \"_echo-[0-9]\" + \".*?\", name):\n name = name.replace(re.search(\"(_echo-[0-9]{2})\", name).group(1), \"\")\n for field in line.strip(\"\\\\n\").split(): # saving the data to variables to write later\n if field != '0' and field != '1':\n fields[runnum - 1].append(float(field))\n categories[runnum - 1].append(category)\n writenames[runnum - 1].append(dst_file_path_list[i] + name)\n break\n i += 1\n except AttributeError:\n print(str(runnum) + \"is not in this list:\")\n for j in range(max(run_list)): # actually writing the file\n if fields[j]:\n # print(len(fields[j]), len(TRfields[j]))\n categories[j] = [categories[j] for _, categories[j] in sorted(zip(fields[j], categories[j]))]\n # TRfields[j] = [TRfields[j] for _,TRfields[j] in sorted(zip(fields[j],TRfields[j]))]\n fields[j].sort()\n for i in range(len(writenames[j]) + 1):\n tsvnames = []\n if self.multi_echo_check(j + 1):\n for k in range((len(self._config[\"delayTimeInSec\"]) - 1)):\n tsvnames.append(\"_echo-\" + str(k + 1).zfill(2) + \"_events.tsv\")\n else:\n tsvnames.append(\"_events.tsv\")\n for ending in tsvnames:\n if i == 0:\n with open(writenames[j][0] + ending, 'a') as out_file:\n tsv_writer = csv.writer(out_file, delimiter='\\t')\n tsv_writer.writerow(['onset', 'duration', 'trial_type']) # ,'TR_condition'])\n else:\n if i < len(writenames[j]):\n duration = float(fields[j][i]) - float(fields[j][i - 1])\n with open(writenames[j][i - 1] + ending, 'a') as out_file:\n tsv_writer = csv.writer(out_file, delimiter='\\t')\n tsv_writer.writerow(\n [fields[j][i - 1], duration, categories[j][i - 1]]) # ,TRfields[j][i-1]])\n\n\ndef main():\n args = get_parser().parse_args()\n data2bids = Data2Bids(**vars(args))\n data2bids.run()\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"pandas.concat",
"pandas.read_csv",
"pandas.api.types.is_float_dtype",
"pandas.DataFrame",
"pandas.read_table",
"pandas.ExcelFile",
"pandas.api.types.is_integer_dtype",
"pandas.to_numeric",
"scipy.io.wavfile.read"
]
] |
NunoEdgarGFlowHub/bsuite
|
[
"a4bfe48721d8ce1136c4913d2f16015439161362"
] |
[
"bsuite/experiments/cartpole/cartpole.py"
] |
[
"# pylint: disable=g-bad-file-header\n# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"The Cartpole reinforcement learning environment.\"\"\"\n\n# Import all packages\n\nimport collections\nfrom bsuite.experiments.cartpole import sweep\nimport dm_env\nfrom dm_env import specs\nimport numpy as np\n\n\nCartpoleState = collections.namedtuple(\n 'CartpoleState', ['x', 'x_dot', 'theta', 'theta_dot', 'time_elapsed'])\n\nCartpoleConfig = collections.namedtuple(\n 'CartpoleConfig',\n ['mass_cart', 'mass_pole', 'length', 'force_mag', 'gravity']\n)\n\n\ndef step_cartpole(action: int,\n timescale: float,\n state: CartpoleState,\n config: CartpoleConfig) -> CartpoleState:\n \"\"\"Helper function to step cartpole state under given config.\"\"\"\n # Unpack variables into \"short\" names for mathematical equation\n force = (action - 1) * config.force_mag\n cos = np.cos(state.theta)\n sin = np.sin(state.theta)\n pl = config.mass_pole * config.length\n l = config.length\n m_pole = config.mass_pole\n m_total = config.mass_cart + config.mass_pole\n g = config.gravity\n\n # Compute the physical evolution\n temp = (force + pl * state.theta_dot**2 * sin) / m_total\n theta_acc = (g * sin - cos * temp) / (l * (4/3 - m_pole * cos**2 / m_total))\n x_acc = temp - pl * theta_acc * cos / m_total\n\n # Update states according to discrete dynamics\n x = state.x + timescale * state.x_dot\n x_dot = state.x_dot + timescale * x_acc\n theta = np.remainder(\n state.theta + timescale * state.theta_dot, 2 * np.pi)\n theta_dot = state.theta_dot + timescale * theta_acc\n time_elapsed = state.time_elapsed + timescale\n\n return CartpoleState(x, x_dot, theta, theta_dot, time_elapsed)\n\n\nclass Cartpole(dm_env.Environment):\n \"\"\"This implements a version of the classic Cart Pole task.\n\n For more information see:\n https://webdocs.cs.ualberta.ca/~sutton/papers/barto-sutton-anderson-83.pdf\n The observation is a vector representing:\n `(x, x_dot, sin(theta), cos(theta), theta_dot, time_elapsed)`\n\n The actions are discrete ['left', 'stay', 'right']. Episodes start with the\n pole close to upright. Episodes end when the pole falls, the cart falls off\n the table, or the max_time is reached.\n \"\"\"\n\n def __init__(self,\n height_threshold: float = 0.8,\n x_threshold: float = 3.,\n timescale: float = 0.01,\n max_time: float = 10.,\n init_range: float = 0.05,\n seed: int = None):\n # Setup.\n self._state = CartpoleState(0, 0, 0, 0, 0)\n self._reset_next_step = True\n self._rng = np.random.RandomState(seed)\n self._init_fn = lambda: self._rng.uniform(low=-init_range, high=init_range)\n\n # Logging info\n self._raw_return = 0.\n self._best_episode = 0.\n self._episode_return = 0.\n\n # Reward/episode logic\n self._height_threshold = height_threshold\n self._x_threshold = x_threshold\n self._timescale = timescale\n self._max_time = max_time\n\n # Problem config\n self._cartpole_config = CartpoleConfig(\n mass_cart=1.,\n mass_pole=0.1,\n length=0.5,\n force_mag=10.,\n gravity=9.8,\n )\n\n # Public attributes.\n self.bsuite_num_episodes = sweep.NUM_EPISODES\n\n def reset(self):\n self._reset_next_step = False\n self._state = CartpoleState(\n x=self._init_fn(),\n x_dot=self._init_fn(),\n theta=self._init_fn(),\n theta_dot=self._init_fn(),\n time_elapsed=0.,\n )\n self._episode_return = 0\n return dm_env.restart(self.observation)\n\n def step(self, action):\n if self._reset_next_step:\n return self.reset()\n\n self._state = step_cartpole(\n action=action,\n timescale=self._timescale,\n state=self._state,\n config=self._cartpole_config,\n )\n\n # Rewards only when the pole is central and balanced\n is_reward = (np.cos(self._state.theta) > self._height_threshold\n and np.abs(self._state.x) < self._x_threshold)\n reward = 1. if is_reward else 0.\n self._raw_return += reward\n self._episode_return += reward\n self._best_episode = max(self._episode_return, self._best_episode)\n\n if self._state.time_elapsed > self._max_time or not is_reward:\n self._reset_next_step = True\n return dm_env.termination(reward=reward, observation=self.observation)\n else: # continuing transition.\n return dm_env.transition(reward=reward, observation=self.observation)\n\n def action_spec(self):\n return specs.DiscreteArray(dtype=np.int, num_values=3, name='action')\n\n def observation_spec(self):\n return specs.Array(shape=(1, 6), dtype=np.float32, name='state')\n\n @property\n def observation(self) -> np.ndarray:\n \"\"\"Approximately normalize output.\"\"\"\n obs = np.zeros((1, 6), dtype=np.float32)\n obs[0, 0] = self._state.x / self._x_threshold\n obs[0, 1] = self._state.x_dot / self._x_threshold\n obs[0, 2] = np.sin(self._state.theta)\n obs[0, 3] = np.cos(self._state.theta)\n obs[0, 4] = self._state.theta_dot\n obs[0, 5] = self._state.time_elapsed / self._max_time\n return obs\n\n def bsuite_info(self):\n return dict(raw_return=self._raw_return,\n best_episode=self._best_episode)\n"
] |
[
[
"numpy.abs",
"numpy.cos",
"numpy.sin",
"numpy.remainder",
"numpy.random.RandomState",
"numpy.zeros"
]
] |
AAbercrombie0492/gdelt_distributed_architecture
|
[
"fd6ab943cbe2e82748c9f74e86d80d4f25498021"
] |
[
"src/data/get_gdelt.py"
] |
[
"#!/usr/bin/python\n'''\nSript to ingest historical gdelt data and save to s3.\n'''\n# pickle.dump(gkg_columns, open('~/gdelt_distributed_architecture/data/interim/gkg_columns.pkl', 'wb'))\n\n\n# Import Dependencies\n\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nimport os\nimport io\nimport sys\nimport time\nimport zipfile\nimport requests\nimport argparse\nimport datetime\nimport pandas as pd\nimport requests\nimport lxml.html as lh\nimport numpy as np\nimport re\nfrom tqdm import tqdm\nimport pickle\nimport fastparquet\nimport datetime\nimport dotenv\nimport logging\n\n\nimport boto3\nimport boto\n# from boto.s3.key import Key\n# from boto.s3.connection import S3Connection\n\n\ndef get_list_of_urls():\n '''\n Gets a list of gdelt archives in the form of URLs.\n INPUT:\n - NA\n OUTPUT:\n - masterlist_urls: List\n URLs to obtain zipped CSVs.\n '''\n # Base directory for gdelt version 2 files\n gdelt_2_events_base_url = 'http://data.gdeltproject.org/gdeltv2/'\n\n # Directory containing all urls of historical data\n masterList_page = requests.get(gdelt_2_events_base_url+'masterfilelist.txt')\n print(type(masterList_page))\n\n # Requests output as text\n masterList = masterList_page.text\n print(len(masterList))\n\n # Extract URLs from text with regex\n masterList_urls = re.findall(r'(http|ftp|https)(://)([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?',\n masterList)\n print(len(masterList_urls))\n\n # Concatenate regex groups to unified url strings\n masterList_urls = list(map(lambda x: ''.join(x), masterList_urls))\n print(masterList_urls[0])\n\n return masterList_urls\n\ndef download_zip_in_chunks(directory, url):\n '''\n Downloads a zipped file in chunks.\n INPUT:\n - directory: String\n Directory to write downloaded file.\n - url: String\n URL of the file to download.\n OUTPUT:\n - local_file: String\n Filepath where contents were written.\n\n '''\n # Unique name of file at the end of a URL\n base_file = os.path.basename(url)\n print('\\n\\nDOWNLOADING {}'.format(base_file))\n\n\n # Path to save output\n temp_path = directory\n\n if base_file in os.listdir(temp_path):\n print(\"FILE EXISTS, CONTINUING...\")\n else:\n try:\n local_file = os.path.join(temp_path, base_file)\n # Connect to url\n req = requests.get(url, stream=True)\n\n # Open local file and write content to it\n with io.open(local_file, 'wb') as fp:\n # Stream data from requests generator in units of 1000\n for chunk in tqdm(req.iter_content(chunk_size=1000)):\n # Write chunk content if found\n if chunk:\n fp.write(chunk)\n # Print errors and corresponding urls\n except Exception as e:\n print(\"ERROR: {}; {}\".format(e, url))\n\ndef unzip_file(directory, zipped_file):\n '''\n Unzips files that have been downloaded locally and stores them in a directory.\n INPUT:\n - directory: String\n Destination to save output.\n - zipped_file: String\n Filepath to find zipped file for unzipping\n OUTPUT:\n - out_path: String\n Filepath where content was written\n '''\n print('\\n\\nUnzipping {}'.format(zipped_file))\n # Try to unzip file\n try:\n # instatiate ZipFile object\n z = zipfile.ZipFile(zipped_file)\n # for each unit in z\n for name in tqdm(z.namelist()):\n # Open file and set output path\n f = z.open(name)\n out_path = os.path.join(directory, name)\n # Open out_path file for writing in utf-8\n with io.open(out_path, 'w', encoding='utf-8') as out_file:\n # Read unzipped content content as utf-8\n content = f.read().decode('utf-8')\n # Write content to output file\n out_file.write(content)\n\n print('Finished Unzippling {}'.format(zipped_file))\n return out_path\n\n # Print errors\n except zipfile.BadZipfile:\n print('Bad zip file for {}, passing on...'.format(zipped_file))\n\ndef make_gdelt_dataframe(csv_path):\n '''\n Takes a filepath, determines what type of gdelt data it is, and returns\n a pandas DataFrame.\n INPUT:\n - csv_path : string\n OUTPUT:\n - pandas dataframe\n '''\n\n if re.search(r'gkg', csv_path):\n columns = pickle.load(open('./gkg_columns.pkl', 'rb'))\n # columns = pickle.load(open(os.path.join(unzip_filepath,\n # 'gkg_columns.pkl'\n # ),\n # 'rb')\n # )\n elif re.search(r'export', csv_path):\n columns = pickle.load(open('./events_columns.pkl', 'rb'))\n\n # columns = pickle.load(open(os.path.join(unzip_filepath,\n # 'events_columns.pkl'\n # ),\n # 'rb')\n # )\n\n elif re.search(r'mentions', csv_path):\n columns = pickle.load(open('./mentions_columns.pkl', 'rb'))\n\n # columns = pickle.load(open(os.path.join(unzip_filepath,\n # 'mentions_columns.pkl'\n # ),\n # 'rb')\n # )\n else:\n return 'NOT A VALID GDELT FILE'\n\n df = pd.read_csv(csv_path, sep='\\t')\n df.columns = columns\n\n return df\n\n\ndef csv_to_parquet(file_path, output_path):\n '''\n Takes a csv path and makes a pandas DataFrame out of it so it can be\n compressed as a parqeut file.\n '''\n print('\\n\\nCONVERTING {} TO PARQUET'.format(file_path))\n\n df = make_gdelt_dataframe(file_path)\n basename = os.path.basename(file_path)\n output_filename = '{}.gzip.parquet'.format(basename)\n if basename in os.listdir(output_path):\n print(\"FILE EXISTS, CONTINUING...\")\n return output_filename\n else:\n output_filepath = os.path.join(output_path, output_filename)\n fastparquet.write(output_filepath, df, compression='GZIP')\n\n return output_filepath\n\ndef parquet_to_s3(parquet_path):\n\n pf = fastparquet.ParquetFile(parquet_path)\n\n # Setup firehose connection\n firehose = boto3.client('firehose', region_name='us-west-2')\n\n firehose.put_record(DeliveryStreamName='gdelt-firehose',\\\n Record={'Data': pf})\n\ndef upload_file_to_s3(csv_path):\n print('\\n\\nUPLOADING {} TO S3'.format(csv_path))\n\n #s3 = boto.connect_s3()\n\n if re.search(r'gkg', csv_path):\n bucket_name = 'gdelt-streaming'\n elif re.search(r'export', csv_path):\n bucket_name = 'gdelt-streaming-events'\n elif re.search(r'mentions', csv_path):\n bucket_name = 'gdelt-streaming-mentions'\n else:\n bucket_name = 'gdelt-streaming'\n\n bucket = s3.lookup(bucket_name)\n\n current_keys = bucket.get_all_keys()\n current_keys = [k.key for k in current_keys]\n\n if os.path.basename(csv_path) in current_keys:\n print('FILE FOUND IN S3, CONTINUING...')\n return\n\n else:\n\n key_name = os.path.basename(csv_path)\n\n key = bucket.new_key(key_name)\n\n now = datetime.datetime.now()\n\n if re.search(r'gkg', csv_path):\n dataset = 'gdelt_gkg'\n elif re.search(r'export', csv_path):\n dataset = 'gdelt_events'\n elif re.search(r'mentions', csv_path):\n dataset = 'gdelt_mentions'\n else:\n dataset = 'other'\n\n metadata = {'dataset': dataset, 'upload_time': str(now)}\n\n key.metadata.update(metadata)\n\n key.set_contents_from_filename(csv_path)\n\n print('{} UPLOAD SUCCESSFUL'.format(key_name))\n #time.sleep(300)\n\n\n\ndef get_most_recent_files_to_s3():\n gdelt_last_15 = requests.get('http://data.gdeltproject.org/gdeltv2/lastupdate.txt').text\n\n urls = re.findall(r'(?P<url>https?://[^\\s]+)', gdelt_last_15)\n\n for f in tqdm(urls):\n\n f_zip_path = download_zip_in_chunks(download_filepath, f)\n\n f_unzip_path = unzip_file(unzip_filepath,\n os.path.join(download_filepath,\n os.path.basename(f)))\n\n df = make_gdelt_dataframe(os.path.join(f_unzip_path))\n\n parquet = csv_to_parquet(f_unzip_path, parquet_filepath)\n\n upload_status = upload_file_to_s3(parquet)\n print(upload_status)\n\n delete_data_after_s3_upload()\ndef delete_data_after_s3_upload():\n raw_path = os.path.join(PROJ_ROOT, 'data/raw')\n interim_path = os.path.join(PROJ_ROOT, 'data/interim')\n parquet_path = os.path.join(PROJ_ROOT, 'data/parquet')\n\n file_paths = [raw_path, interim_path, parquet_path]\n\n print(\"REMOVING LEFTOVER FILES\")\n for p in tqdm(file_paths):\n for f in os.listdir(p):\n os.remove(os.path.join(p, f))\n\n\nif __name__ == '__main__':\n\n log = logging.getLogger(__name__)\n if len(log.handlers) == 0:\n hdlr = logging.FileHandler('get_gdelt_data.log')\n formatter = logging.Formatter('[%(asctime)s] p%(process)s {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s','%m-%d %H:%M:%S')\n hdlr.setFormatter(formatter)\n log.addHandler(hdlr)\n log.setLevel(logging.INFO)\n\n log.info(\"started\")\n PROJ_ROOT = '.'\n #PROJ_ROOT = os.path.join(os.pardir, os.pardir)\n download_filepath = os.path.join(PROJ_ROOT, 'data/raw')\n unzip_filepath = os.path.join(PROJ_ROOT, 'data/interim')\n parquet_filepath = os.path.join(PROJ_ROOT, 'data/parquet')\n\n dotenv_path = os.path.join(PROJ_ROOT, '.env')\n dotenv.load_dotenv(dotenv_path)\n\n AWS_ACCESS_KEY = os.environ.get('AWS_ACCESS_KEY')\n AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')\n host = 's3-us-west-2.amazonaws.com'\n\n s3 = boto.connect_s3(AWS_ACCESS_KEY, AWS_SECRET_ACCESS_KEY)\n\n # url_list = get_list_of_urls()\n # gkg_url = 'http://data.gdeltproject.org/gdeltv2/20150220183000.gkg.csv.zip'\n # gkg_zip_path = download_zip_in_chunks(download_filepath, gkg_url)\n # gkg_unzip_path = unzip_file(unzip_filepath,\n # os.path.join(download_filepath,\n # os.path.basename(gkg_url)\n # )\n # )\n #\n # mentions_url = 'http://data.gdeltproject.org/gdeltv2/20150220184500.mentions.CSV.zip'\n # mentions_zip_path = download_zip_in_chunks(download_filepath, mentions_url)\n # mentions_unzip_path = unzip_file(unzip_filepath,\n # os.path.join(download_filepath,\n # os.path.basename(mentions_url)\n # )\n # )\n #\n # events_url = 'http://data.gdeltproject.org/gdeltv2/20150220184500.export.CSV.zip'\n # events_zip_path = download_zip_in_chunks(download_filepath, events_url)\n # mentions_unzip_path = unzip_file(unzip_filepath,\n # os.path.join(download_filepath,\n # os.path.basename(events_url)\n # )\n # )\n #\n #\n gkg_columns = ['GKGRECORDID', 'DATE', 'SourceCollectionIdentifier',\n 'SourceCommonName', 'DocumentIdentifier', 'Counts',\n 'V2Counts', 'Themes', 'V2Themes', 'Locations',\n 'V2Locations', 'Persons', 'V2Persons', 'Organizations',\n 'V2Organizations', 'V2Tone', 'Dates', 'GCAM',\n 'SharingImage', 'RelatedImages', 'SocialImageEmbeds',\n 'SocialVideoEmbeds', 'Quotations', 'AllNames', 'Amounts',\n 'TranslationInfo', 'Extras']\n\n events_columns = ['GLOBALEVENTID', 'SQLDATE', 'MonthYear', 'Year', 'FractionDate',\n 'Actor1Code', 'Actor1Name', 'Actor1CountryCode',\n 'Actor1KnownGroupCode', 'Actor1EthnicCode', 'Actor1Religion1Code',\n 'Actor1Religion2Code', 'Actor1Type1Code', 'Actor1Type2Code',\n 'Actor1Type3Code', 'Actor2Code', 'Actor2Name', 'Actor2CountryCode',\n 'Actor2KnownGroupCode', 'Actor2EthnicCode', 'Actor2Religion1Code',\n 'Actor2Religion2Code', 'Actor2Type1Code', 'Actor2Type2Code',\n 'Actor2Type3Code', 'IsRootEvent', 'EventCode', 'EventBaseCode',\n 'EventRootCode', 'QuadClass', 'GoldsteinScale', 'NumMentions',\n 'NumSources', 'NumArticles', 'AvgTone', 'Actor1Geo_Type',\n 'Actor1Geo_FullName', 'Actor1Geo_CountryCode', 'Actor1Geo_ADM1Code',\n 'Actor1Geo_ADM2Code',\n 'Actor1Geo_Lat', 'Actor1Geo_Long', 'Actor1Geo_FeatureID',\n 'Actor2Geo_Type', 'Actor2Geo_FullName', 'Actor2Geo_CountryCode',\n 'Actor2Geo_ADM1Code',\n 'Actor2Geo_ADM2Code',\n 'Actor2Geo_Lat', 'Actor2Geo_Long',\n 'Actor2Geo_FeatureID', 'ActionGeo_Type', 'ActionGeo_FullName',\n 'ActionGeo_CountryCode', 'ActionGeo_ADM1Code',\n 'ActionGeo_ADM2Code',\n 'ActionGeo_Lat',\n 'ActionGeo_Long', 'ActionGeo_FeatureID', 'DATEADDED', 'SOURCEURL']\n\n\n mentions_columns = ['GLOBALEVENTID', 'EventTimeDate', 'MentionTimeDate',\n 'MentionType', 'MentionSourceName', 'MentionIdentifier',\n 'SentenceID', 'Actor1CharOffset', 'Actor2CharOffset',\n 'ActionCharOffset', 'InRawText', 'Confidence',\n 'MentionDocLen', 'MentionDocTone',\n 'MentionDocTranslationInfo', 'Extras']\n\n\n pickle.dump(gkg_columns, open('./gkg_columns.pkl', 'wb'))\n\n\n pickle.dump(events_columns, open('./events_columns.pkl', 'wb'))\n\n\n pickle.dump(mentions_columns, open('./mentions_columns.pkl', 'wb'))\n #\n # gkg = make_gdelt_dataframe(os.path.join(PROJ_ROOT, 'data/raw/20150220183000.gkg.csv'))\n # events = make_gdelt_dataframe(os.path.join(PROJ_ROOT, 'data/raw/20150220184500.export.CSV'))\n # mentions = make_gdelt_dataframe(os.path.join(PROJ_ROOT, 'data/raw/20150220184500.mentions.CSV'))\n\n # csv_to_parquet(os.path.join(PROJ_ROOT,'data/raw/20150220183000.gkg.csv'),\n # parquet_filepath)\n #\n # p = '../../data/parquet/20150220183000.gkg.csv.gzip.parquet'\n #\n # csv = '../../data/interim/20150220183000.gkg.csv'\n\n #upload_file_to_s3(p,'gdelt-streaming')\n\n while True:\n log.info(\"started\")\n print('BEGINNING UPLOAD ########### {}'.format(datetime.datetime.now()))\n get_most_recent_files_to_s3()\n print('SLEEPING')\n time.sleep(60)\n"
] |
[
[
"pandas.read_csv"
]
] |
PaParaZz1/DI-engine
|
[
"b38144117c1ebc6eb860d8637ec8866dfbcdf2de"
] |
[
"ding/league/player.py"
] |
[
"from typing import Callable, Optional, List\nfrom collections import namedtuple\nimport numpy as np\nfrom easydict import EasyDict\n\nfrom ding.utils import import_module, PLAYER_REGISTRY\nfrom .algorithm import pfsp\n\n\nclass Player:\n \"\"\"\n Overview:\n Base player class, player is the basic member of a league\n Interfaces:\n __init__\n Property:\n race, payoff, checkpoint_path, player_id, total_agent_step\n \"\"\"\n _name = \"BasePlayer\" # override this variable for sub-class player\n\n def __init__(\n self,\n cfg: EasyDict,\n category: str,\n init_payoff: 'BattleSharedPayoff', # noqa\n checkpoint_path: str,\n player_id: str,\n total_agent_step: int\n ) -> None:\n \"\"\"\n Overview:\n Initialize base player metadata\n Arguments:\n - cfg (:obj:`EasyDict`): Player config dict.\n - category (:obj:`str`): Player category, depending on the game, \\\n e.g. StarCraft has 3 races ['terran', 'protoss', 'zerg'].\n - init_payoff (:obj:`Union[BattleSharedPayoff, SoloSharedPayoff]`): Payoff shared by all players.\n - checkpoint_path (:obj:`str`): The path to load player checkpoint.\n - player_id (:obj:`str`): Player id in string format.\n - total_agent_step (:obj:`int`): For active player, it should be 0; \\\n For historical player, it should be parent player's ``_total_agent_step`` when ``snapshot``.\n \"\"\"\n self._cfg = cfg\n self._category = category\n self._payoff = init_payoff\n self._checkpoint_path = checkpoint_path\n assert isinstance(player_id, str)\n self._player_id = player_id\n assert isinstance(total_agent_step, int), (total_agent_step, type(total_agent_step))\n self._total_agent_step = total_agent_step\n\n @property\n def category(self) -> str:\n return self._category\n\n @property\n def payoff(self) -> 'BattleSharedPayoff': # noqa\n return self._payoff\n\n @property\n def checkpoint_path(self) -> str:\n return self._checkpoint_path\n\n @property\n def player_id(self) -> str:\n return self._player_id\n\n @property\n def total_agent_step(self) -> int:\n return self._total_agent_step\n\n @total_agent_step.setter\n def total_agent_step(self, step: int) -> None:\n self._total_agent_step = step\n\n\n@PLAYER_REGISTRY.register('historical_player')\nclass HistoricalPlayer(Player):\n \"\"\"\n Overview:\n Historical player which is snapshotted from an active player, and is fixed with the checkpoint.\n Have a unique attribute ``parent_id``.\n Property:\n race, payoff, checkpoint_path, player_id, total_agent_step, parent_id\n \"\"\"\n _name = \"HistoricalPlayer\"\n\n def __init__(self, *args, parent_id: str) -> None:\n \"\"\"\n Overview:\n Initialize ``_parent_id`` additionally\n Arguments:\n - parent_id (:obj:`str`): id of historical player's parent, should be an active player\n \"\"\"\n super().__init__(*args)\n self._parent_id = parent_id\n\n @property\n def parent_id(self) -> str:\n return self._parent_id\n\n\nclass ActivePlayer(Player):\n \"\"\"\n Overview:\n Active player can be updated, or snapshotted to a historical player in the league training.\n Interface:\n __init__, is_trained_enough, snapshot, mutate, get_job\n Property:\n race, payoff, checkpoint_path, player_id, total_agent_step\n \"\"\"\n _name = \"ActivePlayer\"\n BRANCH = namedtuple(\"BRANCH\", ['name', 'prob'])\n\n def __init__(self, *args, **kwargs) -> None:\n \"\"\"\n Overview:\n Initialize player metadata, depending on the game\n Note:\n - one_phase_step (:obj:`int`): An active player will be considered trained enough for snapshot \\\n after two phase steps.\n - last_enough_step (:obj:`int`): Player's last step number that satisfies ``_is_trained_enough``.\n - strong_win_rate (:obj:`float`): If win rates between this player and all the opponents are greater than\n this value, this player can be regarded as strong enough to these opponents. \\\n If also already trained for one phase step, this player can be regarded as trained enough for snapshot.\n - branch_probs (:obj:`namedtuple`): A namedtuple of probabilities of selecting different opponent branch.\n \"\"\"\n super().__init__(*args)\n self._one_phase_step = int(float(self._cfg.one_phase_step)) # ``one_phase_step`` is like 1e9\n self._last_enough_step = 0\n self._strong_win_rate = self._cfg.strong_win_rate\n assert isinstance(self._cfg.branch_probs, dict)\n self._branch_probs = [self.BRANCH(k, v) for k, v in self._cfg.branch_probs.items()]\n # self._eval_opponent_difficulty = [\"WEAK\", \"MEDIUM\", \"STRONG\"]\n self._eval_opponent_difficulty = [\"RULE_BASED\"]\n self._eval_opponent_index = 0\n\n def is_trained_enough(self, select_fn: Optional[Callable] = None) -> bool:\n \"\"\"\n Overview:\n Judge whether this player is trained enough for further operations(e.g. snapshot, mutate...)\n according to past step count and overall win rates against opponents.\n If yes, set ``self._last_agent_step`` to ``self._total_agent_step`` and return True; otherwise return False.\n Arguments:\n - select_fn (:obj:`function`): The function to select opponent players.\n Returns:\n - flag (:obj:`bool`): Whether this player is trained enough\n \"\"\"\n if select_fn is None:\n select_fn = lambda x: isinstance(x, HistoricalPlayer) # noqa\n step_passed = self._total_agent_step - self._last_enough_step\n if step_passed < self._one_phase_step:\n return False\n elif step_passed >= 2 * self._one_phase_step:\n # ``step_passed`` is 2 times of ``self._one_phase_step``, regarded as trained enough\n self._last_enough_step = self._total_agent_step\n return True\n else:\n # Get payoff against specific opponents (Different players have different type of opponent players)\n # If min win rate is larger than ``self._strong_win_rate``, then is judged trained enough\n selected_players = self._get_players(select_fn)\n if len(selected_players) == 0: # No such player, therefore no past game\n return False\n win_rates = self._payoff[self, selected_players]\n if win_rates.min() > self._strong_win_rate:\n self._last_enough_step = self._total_agent_step\n return True\n else:\n return False\n\n def snapshot(self) -> HistoricalPlayer:\n \"\"\"\n Overview:\n Generate a snapshot historical player from the current player, called in league's ``_snapshot``.\n Returns:\n - snapshot_player (:obj:`HistoricalPlayer`): new instantiated historical player\n\n .. note::\n This method only generates a historical player object, but without saving the checkpoint, which should be\n done by league.\n \"\"\"\n path = self.checkpoint_path.split('.pth')[0] + '_{}'.format(self._total_agent_step) + '.pth'\n return HistoricalPlayer(\n self._cfg,\n self.category,\n self.payoff,\n path,\n self.player_id + '_{}'.format(int(self._total_agent_step)),\n self._total_agent_step,\n parent_id=self.player_id\n )\n\n def mutate(self, info: dict) -> Optional[str]:\n \"\"\"\n Overview:\n Mutate the current player, called in league's ``_mutate_player``.\n Arguments:\n - info (:obj:`dict`): related information for the mutation\n Returns:\n - mutation_result (:obj:`str`): if the player does the mutation operation then returns the\n corresponding model path, otherwise returns None\n \"\"\"\n pass\n\n def get_job(self, eval_flag: bool = False) -> dict:\n \"\"\"\n Overview:\n Get a dict containing some info about the job to be launched, e.g. the selected opponent.\n Arguments:\n - eval_flag (:obj:`bool`): Whether to select an opponent for evaluator task.\n Returns:\n - ret (:obj:`dict`): The returned dict. Should contain key ['opponent'].\n \"\"\"\n if eval_flag:\n # eval opponent is a str.\n opponent = self._eval_opponent_difficulty[self._eval_opponent_index]\n else:\n # collect opponent is a Player.\n opponent = self._get_collect_opponent()\n return {\n 'opponent': opponent,\n }\n\n def _get_collect_opponent(self) -> Player:\n \"\"\"\n Overview:\n Select an opponent according to the player's ``branch_probs``.\n Returns:\n - opponent (:obj:`Player`): Selected opponent.\n \"\"\"\n p = np.random.uniform()\n L = len(self._branch_probs)\n cum_p = [0.] + [sum([j.prob for j in self._branch_probs[:i + 1]]) for i in range(L)]\n idx = [cum_p[i] <= p < cum_p[i + 1] for i in range(L)].index(True)\n branch_name = '_{}_branch'.format(self._branch_probs[idx].name)\n opponent = getattr(self, branch_name)()\n return opponent\n\n def _get_players(self, select_fn: Callable) -> List[Player]:\n \"\"\"\n Overview:\n Get a list of players in the league (shared_payoff), selected by ``select_fn`` .\n Arguments:\n - select_fn (:obj:`function`): players in the returned list must satisfy this function\n Returns:\n - players (:obj:`list`): a list of players that satisfies ``select_fn``\n \"\"\"\n return [player for player in self._payoff.players if select_fn(player)]\n\n def _get_opponent(self, players: list, p: Optional[np.ndarray] = None) -> Player:\n \"\"\"\n Overview:\n Get one opponent player from list ``players`` according to probability ``p``.\n Arguments:\n - players (:obj:`list`): a list of players that can select opponent from\n - p (:obj:`np.ndarray`): the selection probability of each player, should have the same size as \\\n ``players``. If you don't need it and set None, it would select uniformly by default.\n Returns:\n - opponent_player (:obj:`Player`): a random chosen opponent player according to probability\n \"\"\"\n idx = np.random.choice(len(players), p=p)\n return players[idx]\n\n def increment_eval_difficulty(self) -> bool:\n \"\"\"\n Overview:\n When evaluating, active player will choose a specific builtin opponent difficulty.\n This method is used to increment the difficulty.\n It is usually called after the easier builtin bot is already been beaten by this player.\n Returns:\n - increment_or_not (:obj:`bool`): True means difficulty is incremented; \\\n False means difficulty is already the hardest.\n \"\"\"\n if self._eval_opponent_index < len(self._eval_opponent_difficulty) - 1:\n self._eval_opponent_index += 1\n return True\n else:\n return False\n\n @property\n def checkpoint_path(self) -> str:\n return self._checkpoint_path\n\n @checkpoint_path.setter\n def checkpoint_path(self, path: str) -> None:\n self._checkpoint_path = path\n\n\n@PLAYER_REGISTRY.register('naive_sp_player')\nclass NaiveSpPlayer(ActivePlayer):\n\n def _pfsp_branch(self) -> HistoricalPlayer:\n \"\"\"\n Overview:\n Select prioritized fictitious self-play opponent, should be a historical player.\n Returns:\n - player (:obj:`HistoricalPlayer`): The selected historical player.\n \"\"\"\n historical = self._get_players(lambda p: isinstance(p, HistoricalPlayer))\n win_rates = self._payoff[self, historical]\n # Normal self-play if no historical players\n if win_rates.shape == (0, ):\n return self\n p = pfsp(win_rates, weighting='squared')\n return self._get_opponent(historical, p)\n\n def _sp_branch(self) -> ActivePlayer:\n \"\"\"\n Overview:\n Select normal self-play opponent\n \"\"\"\n return self\n\n\ndef create_player(cfg: EasyDict, player_type: str, *args, **kwargs) -> Player:\n \"\"\"\n Overview:\n Given the key (player_type), create a new player instance if in player_mapping's values,\n or raise an KeyError. In other words, a derived player must first register then call ``create_player``\n to get the instance object.\n Arguments:\n - cfg (:obj:`EasyDict`): player config, necessary keys: [import_names]\n - player_type (:obj:`str`): the type of player to be created\n Returns:\n - player (:obj:`Player`): the created new player, should be an instance of one of \\\n player_mapping's values\n \"\"\"\n import_module(cfg.get('import_names', []))\n return PLAYER_REGISTRY.build(player_type, *args, **kwargs)\n"
] |
[
[
"numpy.random.uniform"
]
] |
bpptkg/bpptkg-meteo
|
[
"8b554c58ffa5bc41377e8bdde7434abaaae49c27"
] |
[
"examples/vaisala/app.py"
] |
[
"import argparse\nimport csv\nimport datetime\nimport io\nimport logging\nimport logging.config\nimport os\nimport sys\nimport tempfile\nfrom urllib.error import URLError\nfrom urllib.parse import urlencode\nfrom urllib.request import urlopen\n\nimport numpy as np\nimport pandas as pd\nimport pytz\nimport sentry_sdk\nfrom decouple import config\nfrom sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.exc import SQLAlchemyError\n\nfrom meteo.db import sessions\nfrom meteo.models import cr6\n\nif sys.platform != 'win32':\n import fcntl\n\nCOLUMNS = [\n 'timestamp',\n 'record_id',\n 'wind_direction',\n 'wind_speed',\n 'air_temperature',\n 'air_humidity',\n 'air_pressure',\n 'rainfall',\n 'amount',\n 'battery_voltage',\n 'power_temperature',\n]\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nDATA_DIR = os.path.join(BASE_DIR, 'data')\nCACHE_DIR = os.path.join(BASE_DIR, 'cache')\nLOG_DIR = os.path.join(BASE_DIR, 'logs')\nLT_FILE = os.path.join(DATA_DIR, 'last')\nLOCKFILE = os.path.join(DATA_DIR, 'vaisala.lock')\n\nDEBUG = config('DEBUG', cast=bool, default=False)\nSENTRY_DSN = config('SENTRY_DSN', default='')\nDATABASE_ENGINE = config('DATABASE_ENGINE', default='')\n\nTIME_ZONE = 'Asia/Jakarta'\nISO_DATE_FORMAT = '%Y-%m-%dT%H:%M:%S'\n\nlogger = logging.getLogger(__name__)\n\n# Initialize sentry integrations.\nsentry_sdk.init(\n dsn=SENTRY_DSN,\n integrations=[SqlalchemyIntegration(), ]\n)\n\n\nclass VaisalaAppError(Exception):\n pass\n\n\ndef force_str(s, encoding='utf-8', errors='strict'):\n \"\"\"\n Force string or bytes s to text string.\n \"\"\"\n if issubclass(type(s), str):\n return s\n try:\n if isinstance(s, bytes):\n s = str(s, encoding, errors)\n else:\n s = str(s)\n except UnicodeDecodeError as e:\n raise e\n return s\n\n\ndef get_current_time():\n \"\"\"\n Get time aware now.\n \"\"\"\n return datetime.datetime.now(pytz.timezone(TIME_ZONE))\n\n\nclass SingleInstanceException(Exception):\n pass\n\n\nclass SingleInstance(object):\n \"\"\"\n A singleton object that can be instantiated once.\n\n It is useful if the script is executed by crontab at small amounts of time.\n\n Reference: https://github.com/pycontribs/tendo/blob/master/tendo/singleton.py\n \"\"\"\n\n def __init__(self, flavor_id='', lockfile=''):\n self.initialized = False\n if lockfile:\n self.lockfile = lockfile\n else:\n basename = os.path.splitext(os.path.abspath(sys.argv[0]))[0].replace(\n \"/\", \"-\").replace(\":\", \"\").replace(\"\\\\\", \"-\") + '-%s' % flavor_id + '.lock'\n self.lockfile = os.path.normpath(\n tempfile.gettempdir() + '/' + basename)\n\n logger.debug('SingleInstance lockfile: %s', self.lockfile)\n if sys.platform == 'win32':\n try:\n if os.path.exists(self.lockfile):\n os.unlink(self.lockfile)\n self.fd = os.open(self.lockfile, os.O_CREAT |\n os.O_EXCL | os.O_RDWR)\n except OSError:\n type, e, tb = sys.exc_info()\n if os.errno == 13:\n logger.error(\n 'Another instance is already running. Quitting.')\n raise SingleInstanceException()\n raise\n else:\n self.fp = open(self.lockfile, 'w')\n self.fp.flush()\n try:\n fcntl.lockf(self.fp, fcntl.LOCK_EX | fcntl.LOCK_NB)\n except (IOError, BlockingIOError):\n logger.error('Another instance is already running. Quitting.')\n raise SingleInstanceException()\n\n self.initialized = True\n\n def __del__(self):\n if not self.initialized:\n return\n try:\n if sys.platform == 'win32':\n if hasattr(self, 'fd'):\n os.close(self.fd)\n os.unlink(self.lockfile)\n else:\n fcntl.lockf(self.fp, fcntl.LOCK_UN)\n if os.path.isfile(self.lockfile):\n os.unlink(self.lockfile)\n except Exception as e:\n if logger:\n logger.error(e)\n else:\n print('Unloggable error: %s', e)\n sys.exit(1)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '-e', '--engine-url',\n dest='engine_url',\n default='',\n help='SQLAlchemy database engine URL to store meteorology data '\n 'e.g. mysql://user:[email protected]/meteo'\n )\n parser.add_argument(\n '-d', '--dry',\n action='store_true',\n help='Do not insert data to database (dry run).'\n )\n parser.add_argument(\n '-v', '--verbose',\n action='store_true',\n help='Run in debugging mode.'\n )\n return parser.parse_args()\n\n\ndef decode_bytes(data):\n try:\n return data.decode('utf-8')\n except (UnicodeDecodeError, AttributeError):\n return data\n\n\ndef to_datetime(date_string, date_format=r'%Y-%m-%d %H:%M:%S'):\n date_obj = datetime.datetime.strptime(date_string, date_format)\n return date_obj\n\n\ndef is_valid_date(date_string, **kwargs):\n try:\n date_obj = to_datetime(date_string, **kwargs)\n if date_obj:\n return True\n return False\n except ValueError:\n return False\n\n\ndef get_meteo_data(start, end):\n \"\"\"\n Get meteorology data from web service.\n\n Web service IP address is 192.168.9.47. We request the data with toa5 format\n (CSV data format) and using data range mode.\n \"\"\"\n params = {\n 'command': 'DataQuery',\n 'uri': 'dl:Table1',\n 'format': 'toa5',\n 'mode': 'date-range',\n 'p1': start,\n 'p2': end\n }\n base_url = 'http://192.168.9.47/'\n url = base_url + '?' + urlencode(params)\n\n logger.debug('Meteorology data web service URL: %s', url)\n\n with urlopen(url) as url:\n response = url.read()\n return response\n\n\ndef parse_data(path):\n \"\"\"\n Parse CSV data from response.\n\n Test the first item in the line if it contains valid date time string. If\n not, ignore the line.\n \"\"\"\n try:\n path_or_buffer = path.decode('utf-8')\n buf = io.StringIO(path_or_buffer)\n lines = []\n while True:\n line = buf.readline()\n if not line:\n break\n date_string = line.split(',')[0].strip('\"')\n if is_valid_date(date_string):\n lines.append(line)\n except (UnicodeDecodeError, AttributeError):\n path_or_buffer = path\n lines = []\n with open(path_or_buffer) as buf:\n while True:\n line = buf.readline()\n if not line:\n break\n date_string = line.split(',')[0].strip('\"')\n if is_valid_date(date_string):\n lines.append(line)\n return ''.join(lines)\n\n\ndef read_csv(path, **kwargs):\n return pd.read_csv(path, **kwargs)\n\n\ndef get_last_timestamp(path):\n \"\"\"\n Get last timestamp from lastfile.\n\n It reads the content of the file and return the content as string.\n \"\"\"\n with open(path) as f:\n date_string = f.read()\n return date_string.rstrip()\n\n\ndef parse_last_timestamp(df):\n \"\"\"\n Parse last timestamp from dataframe.\n\n Add one minute forward to prevent the script from fetching the same value.\n The last timestamp already in database, so we need to fetch the weather data\n one minute forward.\n \"\"\"\n if df.empty:\n return None\n date_string = df['timestamp'].iloc[-1]\n\n # We add one minute forward to prevent data duplication at the edge.\n date_obj = to_datetime(date_string) + datetime.timedelta(minutes=1)\n return date_obj.strftime(ISO_DATE_FORMAT)\n\n\ndef get_last_timestamp_from_buffer(buf):\n df = read_csv(io.StringIO(buf), header=None, names=COLUMNS)\n return parse_last_timestamp(df)\n\n\ndef get_last_timestamp_from_df(df):\n return parse_last_timestamp(df)\n\n\ndef write_last_timestamp(path, date_string):\n with open(path, 'w+') as f:\n f.write(date_string)\n\n\ndef check_ltfile(path):\n \"\"\"\n Check whether lastfile is exists or not. If not exists, create the file with\n empty content.\n \"\"\"\n if not os.path.exists(path):\n logger.debug(\n 'Last timestamp file (LT_FILE) is not exists. Creating LT_FILE...')\n with open(path, 'w+') as f:\n pass\n else:\n logger.debug('Last timestamp file (LT_FILE) already exists.')\n\n\ndef get_csv_from_queue(path):\n with open(path, 'a+') as f:\n data = f.read()\n return data\n\n\ndef erase_file_content(path):\n with open(path, 'w') as f:\n pass\n\n\ndef insert_to_db(url, entries):\n \"\"\"\n Insert weather data to the database.\n\n :param url: SQLAlchemy engine URL.\n :param entries: List of dictionary of weather data.\n :return: True if data successfully inserted to the database,\n otherwise False.\n \"\"\"\n engine = create_engine(url)\n cr6.Base.prepare(engine, reflect=True)\n\n try:\n with sessions.session_scope(engine) as session:\n session.bulk_insert_mappings(cr6.CR6, entries)\n session.commit()\n return True\n except SQLAlchemyError as e:\n logger.error(e)\n return False\n\n\ndef sanitize_nan(entries):\n \"\"\"\n Convert NaN to None for item in entries.\n \"\"\"\n return [\n dict([\n (key, value) if not pd.isna(value) else (key, None)\n for key, value in item.items()\n ])\n for item in entries\n ]\n\n\ndef process_csv(url, buf, **kwargs):\n df = read_csv(io.StringIO(buf), header=None, names=COLUMNS)\n\n # Change non-number (except timestamp) to NaN if any.\n df = df.where(pd.notnull(df), np.nan)\n df.replace('NAN', np.nan, inplace=True)\n\n logger.info('Number of entries: %s', len(df))\n\n logger.debug('First 10 records:')\n logger.debug(df.head())\n logger.debug('Last 10 records:')\n logger.debug(df.tail())\n\n dry = kwargs.get('dry')\n if not dry:\n entries = df.to_dict(orient='records')\n ok = insert_to_db(url, sanitize_nan(entries))\n if ok:\n logger.info('Data successfully inserted to database.')\n\n last = get_last_timestamp_from_df(df)\n if last is None:\n return\n\n logger.info('Last data timestamp (+1 minute from last timestamp '\n 'in database): %s', last)\n logger.info('Writing request end time to LT_FILE...')\n write_last_timestamp(LT_FILE, last)\n else:\n logger.error('Data failed to be inserted to database.')\n else:\n logger.debug('Running in dry mode. Not inserting to database.')\n\n\nclass VaisalaApp(SingleInstance):\n \"\"\"\n Vaisala app class that allow only one instance to be run.\n\n It prevents race condition when running multiple instance of classes. So, we\n only run the instance in one process only. We can make sure that only one\n process write a content to the lastfile.\n \"\"\"\n\n def __init__(self, lastfile='', **kwargs):\n if lastfile:\n self.lastfile = lastfile\n else:\n # TODO(indra): create lastfile in data directory.\n self.lastfile = LT_FILE\n super().__init__(**kwargs)\n\n def run(self):\n args = parse_args()\n\n db_engine_url = args.engine_url or DATABASE_ENGINE\n if not db_engine_url:\n raise VaisalaAppError('Database engine URL is not configured yet')\n\n log_level = 'INFO'\n if args.verbose or DEBUG:\n log_level = 'DEBUG'\n\n logging_config = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'default': {\n 'format': '{asctime} {levelname} {name} {message}',\n 'style': '{',\n },\n 'verbose': {\n 'format': '{asctime} {levelname} {name} {message}',\n 'style': '{',\n },\n },\n 'handlers': {\n 'console': {\n 'level': log_level,\n 'class': 'logging.StreamHandler',\n 'formatter': 'default'\n },\n 'production': {\n 'level': log_level,\n 'class': 'logging.handlers.RotatingFileHandler',\n 'filename': os.path.join(LOG_DIR, 'vaisala.log'),\n 'maxBytes': 1024 * 1024 * 5,\n 'backupCount': 7,\n 'formatter': 'verbose',\n },\n },\n 'loggers': {\n '': {\n 'handlers': ['console', 'production'],\n 'level': log_level,\n },\n '__main__': {\n 'handlers': ['console', 'production'],\n 'level': log_level,\n 'propagate': False,\n }\n }\n }\n\n logging.config.dictConfig(logging_config)\n\n now = get_current_time()\n\n logger.info('-' * 80)\n logger.info('Processing start at: %s',\n get_current_time().strftime(ISO_DATE_FORMAT))\n\n logger.debug('App base directory: %s', BASE_DIR)\n logger.debug('App cache directory: %s', CACHE_DIR)\n logger.debug('App data directory: %s', DATA_DIR)\n logger.debug('App log directory: %s', LOG_DIR)\n logger.debug('Sentry DSN: %s', SENTRY_DSN)\n\n logger.debug('Last timestamp file (LT_FILE): %s', self.lastfile)\n\n check_ltfile(self.lastfile)\n\n end = now.strftime(ISO_DATE_FORMAT)\n start = get_last_timestamp(self.lastfile)\n logger.info('Last time from file: %s', start)\n\n if not start:\n logger.info('Last timestamp will default to one hour ago.')\n one_hour_ago = now - datetime.timedelta(hours=1)\n start = one_hour_ago.strftime(ISO_DATE_FORMAT)\n\n logger.info('Request start time: %s', start)\n logger.info('Request end time: %s', end)\n\n logger.info('Requesting meteo data from web service...')\n try:\n response = get_meteo_data(start, end)\n except URLError as e:\n logger.error(e)\n sys.exit(1)\n\n if not response:\n logger.info('Response is empty. Skipping...')\n sys.exit(1)\n\n buf = parse_data(response)\n process_csv(db_engine_url, buf, dry=args.dry)\n\n logger.info('Processing end at: %s',\n get_current_time().strftime(ISO_DATE_FORMAT))\n logger.info('-' * 80)\n\n\nif __name__ == '__main__':\n try:\n app = VaisalaApp(lastfile=LT_FILE, lockfile=LOCKFILE)\n app.run()\n except SingleInstanceException:\n sys.exit(1)\n"
] |
[
[
"pandas.isna",
"pandas.notnull",
"pandas.read_csv"
]
] |
ll0pez10/transmissao-energia-eletrica
|
[
"56b9616ff1ab39c34aa5af8c44e7b3ffd1a2f82f"
] |
[
"Trabfinal.py"
] |
[
"#!/usr/bin/env python\n# coding: utf-8\n\nfrom linha_transmissao import Linha_transmissao\nfrom metodos_linhas import raio_eq, Pnat, derivacao, quadlinha, compenslinha\nfrom numpy import savetxt\n\nfrom numpy import sqrt\nimport numpy as np\nfrom numpy.linalg import inv\nimport matplotlib.pyplot as plt\n\nnp.set_printoptions(linewidth=500)\n\n#======================================================================================================\n#==================================== Dados do Projeto ================================================\n#======================================================================================================\n\n# Especificacao dos condutores dos condutores\n# Name: (r0,r1,pfase) (raio interno, raio externo, resistividade) ohms/m\nCondutoresEspecs = {\"Bluejay\": (8.702*10**-3, 15.977*10**-3, 29.544*10**-9),\n \"Rail\": (8.702*10**-3, 14.796*10**-3, 29.538*10**-9),\n \"3/8 EHS\": (0, 4.570*10**-3, 276.470*10**-9)}\n\n#------------------------------------------------------------------------------------------------------\n\n#Posicao dos condutores\n#Name: (rext,rint,(Xc-1,Xc0,Xc1),(Yc-1,Yc,Yc+1),(Xpr,Ypr,Xpr2,Ypr2),n)\n# n é o numero de condutores por fase\n# Xc cordenadas dos centros dos condutores equivalentes\n# Yc cordenadas dos centros dos condutores equivalentes PS: na formula subtrai por 2/3 da flecha\n#Pros dois primeiros botei o raio como sendo o db*sqrt(2)/2\nCondutoresPos = {\"Bluejay\": (raio_eq(4, CondutoresEspecs[\"Bluejay\"][1], .475*sqrt(2)/2),\n raio_eq(4, CondutoresEspecs[\"Bluejay\"][0], .475*sqrt(2)/2),\n (-15.85, 0, 15.85),\n (35.9-2*20.9/3, 35.9-2*20.9/3, 35.9-2*20.9/3),\n (-14.45, 45.9-2*14.7/3, 14.45, 45.9-2*14.7/3), 4),\n \"Rail Normal\": (raio_eq(4, CondutoresEspecs[\"Rail\"][1],.475*sqrt(2)/2),\n raio_eq(4, CondutoresEspecs[\"Rail\"][0],.475*sqrt(2)/2),\n (-15, -11, -6, 6, 11, 15),\n (23.2, 33.2, 23.2, 23.2, 33.2, 23.2),\n (-8.8, 42.7, 8.8, 42.7), 4)\n }\n\n\n\n#====================================================================================\n#===================== Calculo da Distancia entre as torres =========================\n#====================================================================================\n\n##distancia minima entre o eixo dos circuitos\n# o eixo seria a linha vertical que corta a torre ao meio\n# referenciar norma tecnica ABNT NBR 5422 NBR5422 Projeto de linhas aéreas de\nL=0\nL=L+0.22+0.01*750000 #distancia minima entre os condutores localizados em circuitos de transmissao distintos\n\n\n#temos que reconstruir a matriz Xc. Yc por sua vez permanece igual\n#Bluejay permanece igual, rail a gnt soma a distancia minima\ndelta1=abs(CondutoresPos[\"Rail Normal\"][2][1]-CondutoresPos[\"Rail Normal\"][2][0])\ndelta2=abs(CondutoresPos[\"Rail Normal\"][2][1]-CondutoresPos[\"Rail Normal\"][2][2])\ndelta3=abs(CondutoresPos[\"Rail Normal\"][2][2]-CondutoresPos[\"Rail Normal\"][2][3])\nrail1=L+CondutoresPos[\"Bluejay\"][2][2]\nrail2=rail1+delta1\nrail3=rail2+delta2\nrail4=rail3+delta3\nrail5=rail4+delta2\nrail6=rail5+delta1\n\n#Condutores\nXc=[]\nfor i in (CondutoresPos[\"Bluejay\"][2]):\n Xc.append(i) \n\nXc=Xc+[rail1,rail2,rail3,rail4,rail5,rail6]\n\nYc=[]\nfor i in (CondutoresPos[\"Bluejay\"][3]):\n Yc.append(i)\nfor i in (CondutoresPos[\"Rail Normal\"][3]):\n Yc.append(i)\n \n\n#Para-raio\nXpr=[]\nYpr=[]\nfor i in range(0,len(CondutoresPos[\"Bluejay\"][4]),2):\n Xpr.append(CondutoresPos[\"Bluejay\"][4][i]) \n \nfor i in range(1,len(CondutoresPos[\"Bluejay\"][4]),2):\n Ypr.append(CondutoresPos[\"Bluejay\"][4][i]) \n\ndelta=abs(CondutoresPos[\"Rail Normal\"][2][0]-CondutoresPos[\"Rail Normal\"][4][0]) #diferenca da distancia do pararaio pro primeiro condutor do rail\nXpr.append(rail1+delta)\nXpr.append(rail6-delta)\n\nfor i in range(1,len(CondutoresPos[\"Rail Normal\"][4]),2):\n Ypr.append(CondutoresPos[\"Rail Normal\"][4][i]) \n\n\n#Xc e Yc sao listas com as coordenadas dos centros dos condutores equivalentes das duas torres\n#Xpr e Ypr sao lista com as coordenadas dos centros dos pararaios dos das duas torres\n\n\n#plt.plot(XcondRail,YcondRail,'bx',Xc[3:],Yc[3:],'ro')\n#plt.show()\n\n\n#=================================================================================================\n#============================= Matrizes de Impedancia e Admitancia ===============================\n#=================================================================================================\n\n#Construcao da matriz de sequencias\na = np.exp(1j * np.deg2rad(120))\na2 = a**2\nA = np.array([[1, 1, 1], [1, a2, a], [1, a, a2]]) #matriz de sequencias\n\nnpr = 2 #numero de pararaios\n\n\n#------------------------------------------ Bluejay -------------------------------------------\ntipo = \"Bluejay\"\nr_ext = CondutoresEspecs[tipo][0]\nr_int = CondutoresEspecs[tipo][1]\nnfase = 3\nxc = np.array(Xc[0:3] + Xpr[0:2]) #vetor com a posicao X de todos os condutores do Bluejay(fase e pararaio)\nyc = np.array(Yc[0:3] + Ypr[0:2]) #vetor com a posicao Y de todos os condutores (fase e pararaio)\nrhoc = CondutoresEspecs[tipo][2]\nrhoc_pr = CondutoresEspecs[\"3/8 EHS\"][2]\nrf = r_ext\nrpr = CondutoresEspecs[\"3/8 EHS\"][1]\n\n#intanciacao do objeto que representa a linha bluejay\nLinhaBluejay = Linha_transmissao(r_int, r_ext, nfase, npr, xc, yc, rhoc, rhoc_pr, r_ext, rpr)\nmat_pot = LinhaBluejay.Mpot()\n#Retiramos as info do pararaio das matrizes atraves da reducao de kron\npot_abc_bluejay = 0j + np.zeros((nfase,nfase))\n\npot_abc_bluejay = mat_pot[0:nfase,0:nfase] - mat_pot[0:nfase,nfase:] @ inv(mat_pot[nfase:,nfase:]) @ mat_pot[nfase:,0:nfase]\nsavetxt('mat_pot.csv', pot_abc_bluejay, delimiter=',')\n\nZ_bluejay = LinhaBluejay.impedancia()\nY_bluejay = LinhaBluejay.admitancia()\nZ_bluejay = Z_bluejay.astype(np.csingle)\nY_bluejay = Y_bluejay.astype(np.csingle)\n\n#Retiramos as info do pararaio das matrizes atraves da reducao de kron\nZabc_bluejay = 0j + np.zeros((nfase,nfase))\nYabc_bluejay = 0j + np.zeros((nfase,nfase))\n\nZabc_bluejay = Z_bluejay[0:nfase,0:nfase] - Z_bluejay[0:nfase,nfase:] @ inv(Z_bluejay[nfase:,nfase:]) @ Z_bluejay[nfase:,0:nfase]\nYabc_bluejay = Y_bluejay[0:nfase,0:nfase] - Y_bluejay[0:nfase,nfase:] @ inv(Y_bluejay[nfase:,nfase:]) @ Y_bluejay[nfase:,0:nfase]\n\nz012_bluejay = inv(A)@Zabc_bluejay@A\ny012_bluejay = inv(A)@Yabc_bluejay@A\n\n#------------------------------------- Rail normal ---------------------------------------\n\n#Atribuimos os valores que serão utilizados para chamar a classe. Raios, numero de condutores, posição espacial dos condutores, rhos\ntipo = \"Rail Normal\"\nr_ext = CondutoresPos[tipo][0]\nr_int = CondutoresPos[tipo][1]\nnfase = 6\nxc = np.array(Xc[3:] + Xpr[2:]) #vetor com a posicao X de todos os condutores do Rail Normal(fase e pararaio)\nyc = np.array(Yc[3:] + Ypr[2:]) #vetor com a posicao Y de todos os condutores do Rail Normal (fase e pararaio)\nrhoc = CondutoresEspecs[\"Rail\"][2]\nrhoc_pr = CondutoresEspecs[\"3/8 EHS\"][2]\nrf = r_ext\nrpr = CondutoresEspecs[\"3/8 EHS\"][1]\n\n#intanciacao do objeto que representa a linha rail normal\nLinhaRail = Linha_transmissao(r_int, r_ext, nfase, npr, xc, yc, rhoc, rhoc_pr, r_ext, rpr)\n\n#Uma vez construida a linha podemos determinar seus parametros de impedancia e admitancia\nZ_rail = LinhaRail.impedancia()\nY_rail = LinhaRail.admitancia()\nZ_rail = Z_rail.astype(np.csingle) #Codigo necessario para o python ler o tipo de variavel \nY_rail = Y_rail.astype(np.csingle)\n#Redução de Kron para eliminar o para-raio\nZabc_rail = 0j + np.zeros((6,6))\nYabc_rail = 0j + np.zeros((6,6))\nZabc_rail = Z_rail[0:nfase,0:nfase] - Z_rail[0:nfase,nfase:] @ inv(Z_rail[nfase:,nfase:]) @ Z_rail[nfase:,0:nfase]\nYabc_rail = Y_rail[0:nfase,0:nfase] - Y_rail[0:nfase,nfase:] @ inv(Y_rail[nfase:,nfase:]) @ Y_rail[nfase:,0:nfase]\n\n#A = [[A, 0] matriz de sequencia precisa ser 6x6 agr\n# [0, A]]\nzero = np.zeros((3,3)) #matriz de zeros auxiliar\naux1 = np.concatenate((A,zero))\naux2 = np.concatenate((zero,A))\nA = np.concatenate((aux1,aux2),axis=1) #matriz de sequencia para o caso 6x6\n\n\nz012_rail = inv(A)@Zabc_rail@A\ny012_rail = inv(A)@Yabc_rail@A\n\n\n#=================================================================================================\n#============================================= Quadripolos =======================================\n#=================================================================================================\nL = 750 #km\nSbase = 300e6 #VA\nVbaseblue = 750e3 #V\nVbaserail = 500e3 #V\nVbasegera = 250e3 #V\nZbaseblue = Sbase/Vbaseblue #ohms\nZbaserail = Sbase/Vbaserail #ohms\n#Ybase = 1/Zbase\nXg = 2.4 #impedancia em pu do gerador\nQg = np.array( [[1,Xg],[0, 1]] ) #quadripolo do gerador\nXt = 3 #impedancia em pu do transformador\nQt = np.array( [[1,Xt],[0, 1]] ) #quadripolo do transformador\n\n#======================================== Bluejay ==============================================\n\n#------ Linha Bluejay (modelo pi) -------\nZ1 = z012_bluejay[1][1]/Zbaseblue*L #impedancia considerando a sequencia positiva\nY1 = y012_bluejay[1][1]*Zbaseblue*L #admitancia considerando a sequencia negativa\n\n#Componentes da matriz de quadripolo\nA1 = 1 + Z1*Y1/2\nA2 = Z1\nA3 = Y1*(1 + Z1*Y1/4)\nA4 = 1 + Z1*Y1/2\n\nQL_b = np.array( [[A1, A2],[A3, A4]] ) #Quadripolo da linha bluejay\n\n\n#-------------- Testes --------------------------\n#fator de potencia unitario na carga\n\nVg = 750e3 #tensao de entrada na linha\nVg = Vg/Vbaseblue\n#Ig = Sg/(np.sqrt(3) * Vg) #corrente no gerador\n#VI_carga = inv(Qg @ QL_b) @ np.array([Vg, Ig])\n\n#Caso 1: Vazio sem compensacao -> Corrente na carga e nula, a segunda coluna do quadripolo e desconsiderada\nprint(\"- Linha em vazio -BLUEJAY \")\nVr = Vg/A1\nIg = A3*Vr\nprint(\"Vr = %.2e < %.2f V = %.2f pu\" % (abs(Vr),np.rad2deg(np.angle(Vr)),abs(Vr)))\nprint(\"Ig = %.2e < %.2f A\" % (abs(Ig),np.rad2deg(np.angle(Ig))))\n\n\n#Caso 2: Vazio com compensacao indutiva em derivacao na fonte e na carga\nY = (1 - A1)/A2 #valor da admitancia de cada reator indutivo adicionado (p. 240 do Fuchs Vol. 1)\n\nA1c = A1 + A2*Y\nA2c = A2\nA3c = A3 + A1*Y + A4*Y + A2*Y*Y\nA4c = A4 + A2*Y\n\nQcomp = np.array( [[A1c, A2c],[A3c, A4c]] ) #Quadripolo equivalente considerando a compensacao\n\nprint(\"\\n\\n- Linha com compensacao -\")\nVr = Vg/A1c\nIg = A3c*Vr\nprint(\"Vr = %.2e < %.2f V = %.2f pu\" % (abs(Vr),np.rad2deg(np.angle(Vr)),abs(Vr/Vg)))\nprint(\"Ig = %.2e < %.2f A\" % (abs(Ig),np.rad2deg(np.angle(Ig))))\n\n\n\n\n\n\n#======================================== Rail Normal ===========================================\n\n\n#------ Linha Rail normal (modelo pi) -------\nZ1 = z012_rail[1][1]/Zbaserail*L #impedancia considerando a sequencia positiva\nY1 = y012_rail[1][1]*Zbaserail*L #admitancia considerando a sequencia negativa\n\n#montagem do quadripolo considerando apenas o modelo pi da linha\nA1 = 1 + Z1*Y1/2\nA2 = Z1\nA3 = Y1*(1 + Z1*Y1/4)\nA4 = 1 + Z1*Y1/2\n\nQL_r = np.array( [[A1, A2],[A3, A4]] ) #quadripolo da linha rail normal\n\n#Caso 1: Vazio sem compensacao -> Corrente na carga e nula, o segunda coluna do quadripolo e desconsiderada\nVg = 500e3 #tensao de entrada na linha\nVg = Vg/Vbaserail\nprint(\"\\n\\n- Linha em vazio - RAIL\")\nVr = Vg/A1\nIg = A3*Vr\nprint(\"Vr = %.2e ang( %.2f ) V = %.2f pu\" % (abs(Vr),np.rad2deg(np.angle(Vr)),abs(Vr)))\nprint(\"Ig = %.2e ang( %.2f ) A\" % (abs(Ig),np.rad2deg(np.angle(Ig))))\n\n#======================================== Grafico da variacao da tensão com a distancia do RAIL ===========================================\n\n#%matplotlib inline\n#O objetivo aqui e ir avancando do ponto inicial da linha ate a outra ponta. Nesse trajeto, quando encontrarmos um ponto em que a tensao\n#ultrapassar 1.05, marcaremos esse ponto para depois colocar uma subestacao. Continuamos as iteracoes, considerando que no ponto que foi\n#marcado a tensao volta ao normal, ate acharmos o proximo ponto que a tensao ultrapassar o limite de 1.05 pu.\nVg = 500e3 #tensao de entrada na linha\nVg = Vg/Vbaserail\ndim=0\nfor l in range(750):\n dist=l-dim\n Z1 = z012_rail[1][1]/Zbaserail*dist #impedancia considerando a sequencia positiva\n Y1 = y012_rail[1][1]*Zbaserail*dist #admitancia considerando a sequencia negativa\n\n A1 = 1 + Z1*Y1/2\n A2 = Z1\n A3 = Y1*(1 + Z1*Y1/4)\n A4 = 1 + Z1*Y1/2\n\n QL_r = np.array( [[A1, A2],[A3, A4]] ) #quadripolo da linha rail normal\n \n #Caso 1: Vazio sem compensacao -> Corrente na carga e nula, o segundda coluna do quadripolo e desconsiderada\n\n Vr = Vg/A1\n Ig = A3*Vr\n \n \n plt.plot(l, Vr, 'o', color='black');\n\nplt.xlabel('Distancia (km)')\nplt.ylabel('tensão (PU)')\nplt.title('Linha sem compensação shunt')\n\ncomp=np.array( [[1, 0],[0.7, 1]] )\n\n\n\nfig2=plt.figure()\n#primeiro a gnt descobre a matriz de quadripolos desse pedaço todo da linha\nl=244\nZ1 = z012_rail[1][1]/Zbaserail*l #impedancia considerando a sequencia positiva\nY1 = y012_rail[1][1]*Zbaserail*l #admitancia considerando a sequencia negativa\n\nA1 = 1 + Z1*Y1/2\nA2 = Z1\nA3 = Y1*(1 + Z1*Y1/4)\nA4 = 1 + Z1*Y1/2\n\n#compensação shunt, pag 240 fuchs \nk=1#quanto queremos compensar, 1 = tudo. Uentrada/Usaida se nao \nY=(k-A1)/A2\n\nfor l in range(750): \n if l < 244:\n Z1 = z012_rail[1][1]/Zbaserail*l #impedancia considerando a sequencia positiva\n Y1 = y012_rail[1][1]*Zbaserail*l #admitancia considerando a sequencia negativa\n \n A1 = 1 + Z1*Y1/2\n A2 = Z1\n A3 = Y1*(1 + Z1*Y1/4)\n A4 = 1 + Z1*Y1/2\n \n #nova matriz de quadripolos originaria da [shunt][quadripolos][shunt]\n A = A1 +A2*Y\n B = A2\n C = A3+A1*Y+A4*Y+A2*Y*Y\n D = A4 + A2*Y\n \n Vr = Vg*A\n plt.plot(l, abs(Vr), 'o', color='black');\n plt.xlabel('Distancia (km)')\n plt.ylabel('tensão (PU)')\n plt.title('Linha com compensação shunt de 100%')\n\n\n#=====================================================================================================\n#============================================= Linha com carga =======================================\n#=====================================================================================================\nVg = 1 #pu\nIg = 1.07 #pu para garantirmos assim a potencia na fonte a principio de 3000 MW, provavelmente teremos que aumentar dps devido as perdas na linha\nP0 = 3*(Vg*np.conj(Ig))\nprint(\"A potencia ativa total do gerador é : {:.2f} GW \\n\" .format(P0.real))\nL1 = 244 #km ate a 1 subestação\nL2 = 267 #km ate a 2 subestação\nL3 = 239 #km ate a 3 subestação\n\n#======================================== Duas Redes em paralelo ==============================================\nx1=0.06 #fator de com pensacao da impedancia\nx2=0.3 #fator de compensacao da admitancia\n\nR = np.array( [ [0,1,0],[0,0,1],[1,0,0] ] ) #matriz de rotacao usada para fazer a transposicao\n\ndef quadparalelo(L,compz,compy):\n#Calcula o quadripolo equivalente dos dois circuitos em paralelo (bluejay e rail)\n\n Z1 = z012_bluejay[1][1]/Zbaseblue*L\n Z1 = complex(Z1.real,Z1.imag*compz) #incluindo a compensacao de impedancia\n Y1 = y012_bluejay[1][1]*Zbaseblue*L\n Y1 = complex(Y1.real,Y1.imag*compy) #incluindo a compensacao de admitancia\n \n #quadripolo bluejay\n A1 = 1 + Z1*Y1/2\n B1 = Z1\n C1 = Y1*(1 + Z1*Y1/4)\n D1 = 1 + Z1*Y1/2\n \n Z1 = z012_rail[1][1]/Zbaserail*L\n Z1 = complex(Z1.real,Z1.imag*compz) #incluindo a compensacao de impedancia\n Y1 = y012_rail[1][1]*Zbaserail*L \n Y1 = complex(Y1.real,Y1.imag*compy) #incluindo a compensacao de admitancia\n\n #quadripolo rail\n A2 = 1 + Z1*Y1/2\n B2 = Z1\n C2 = Y1*(1 + Z1*Y1/4)\n D2 = 1 + Z1*Y1/2\n \n #quadripolo resultado do paralelo entre o bluejay e o rail\n A = (A1*B2+B1*A2)/(B1+B2)\n B = B1*B2/(B1+B2)\n C = C1+C2+((A1-A2)*(D2-D1)/(B1+B2))\n D = (B1*D2+D1*B2)/(B1+B2)\n \n #Calculando o paralelo do circuito equivalente acima com o outro circuito que sobrou da linha dupla\n \n A = (A*B2+B*A2)/(B+B2)\n B = B*B2/(B+B2)\n C = C+C2+((A-A2)*(D2-D)/(B+B2))\n D = (B*D2+D*B2)/(B+B2)\n \n \n return np.array( [[A, B],[C, D]] )\n\n#Quad = trecho de 244 km @ trecho de 267 km @ trecho de 239 km\n\nQuad = quadparalelo(L1,x1,x2) @ quadparalelo(L2,x1,x2)@ quadparalelo(L3,x1,x2)\nprint(\"Matriz de quadripolos\")\nprint(Quad)\n\n#[Vr,Ir] = np.linalg.solve(Quad,[Vg,Ig])\nIr=1\nVr=1\n#Vr=(Vg-Quad[0,1]*Ir)/Quad[0,0]\n#Ig=Quad[1,0]*Vr+Quad[1,1]*Ir\n[Vg,Ig]=np.linalg.solve(inv(Quad),[Vr,Ir])\n\n\nP0= (3*(Vg*np.conj(Ig))).real\nprint(\"Vg = \"+str(abs(Vg))+\" L\"+str(np.rad2deg(np.angle(Vg))))\nprint(\"Ig = \"+str(abs(Ig))+\" L\"+str(np.rad2deg(np.angle(Ig))))\nprint(\"\\nPotencia na carga: %.2f GW\" % (P0))\n\nprint(\"\\n- Linhas em paralelo -\")\nprint(\"Vr = %.2f\" % abs(Vr))\nprint(\"Ir = %.2f\" % abs(Ir))\nprint(\"Vr * Ir = %.2f\" % (Vr*Ir).real)\nP1=(3*(Vr*np.conj(Ir))).real\nprint(\"\\nPotencia na carga: %.2f GW\" % (P1))\nprint(\"\\nPerdas na linha: %.2f Porcentos\" % (100*(-P1+P0)/P0))"
] |
[
[
"numpy.conj",
"matplotlib.pyplot.title",
"numpy.sqrt",
"numpy.linalg.inv",
"matplotlib.pyplot.figure",
"numpy.set_printoptions",
"numpy.concatenate",
"matplotlib.pyplot.plot",
"numpy.deg2rad",
"numpy.savetxt",
"matplotlib.pyplot.xlabel",
"numpy.angle",
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.ylabel"
]
] |
taodav/generalization-rl
|
[
"9aab3147ef93471fb262d65b75a0688ed083d111"
] |
[
"grl/sampling.py"
] |
[
"import json\nfrom pathlib import Path\nimport numpy as np\nfrom typing import List\n\nfrom definitions import ROOT_DIR\n\nP_OFFSET_MAX = 1.0\nP_OFFSET_MIN = -1.0\nV_OFFSET_MAX = 1.0\nV_OFFSET_MIN = -1.0\n\ndef sample_mountaincar_env(seed: int, n: int) -> List[dict]:\n \"\"\"\n Sample n mountain car environment parameters based on generalizations described in\n https://www.cs.utexas.edu/users/pstone/Papers/bib2html-links/ADPRL11-shimon.pdf\n :param seed: Seed for sampling\n :param n: number of environments to sample\n :return:\n \"\"\"\n random_state = np.random.RandomState(seed)\n all_envs = []\n for i in range(n):\n sample_p_offset = random_state.uniform(P_OFFSET_MIN, P_OFFSET_MAX)\n\n sample_v_offset = random_state.uniform(V_OFFSET_MIN, V_OFFSET_MAX)\n\n sample_p_noise_divider = random_state.uniform(5.0, 20.0)\n\n sample_v_noise_divider = random_state.uniform(5.0, 20.0)\n\n sample_accel_bias_mean = random_state.uniform(0.8, 1.2)\n\n # sample_amplitude = random_state.uniform(0.75, 1.75)\n\n # env = MountainCarEnv(accel_bias_mean=sample_accel_bias_mean,\n # p_offset=sample_p_offset, v_offset=sample_v_offset,\n # p_noise_divider=sample_p_noise_divider,\n # v_noise_divider=sample_v_noise_divider)\n\n # all_envs.append(env)\n all_envs.append({\n 'accel_bias_mean': sample_accel_bias_mean,\n 'p_offset': sample_p_offset,\n 'v_offset': sample_v_offset,\n 'p_noise_divider': sample_p_noise_divider,\n 'v_noise_divider': sample_v_noise_divider,\n # 'amplitude': sample_amplitude\n })\n\n return all_envs\n\nif __name__ == \"__main__\":\n params_file = Path(ROOT_DIR, 'experiments', 'reproduce_tuning_params.json')\n\n env_params = sample_mountaincar_env(2020, 25)\n print(f'Saving params to {params_file}')\n\n with open(params_file, 'w') as f:\n json.dump(env_params, f)\n\n\n test_params_file = Path(ROOT_DIR, 'experiments', 'reproduce_testing_params.json')\n\n test_env_params = sample_mountaincar_env(2021, 100)\n print(f'Saving test params to {test_params_file}')\n\n with open(test_params_file, 'w') as f:\n json.dump(test_env_params, f)\n\n\n\n\n"
] |
[
[
"numpy.random.RandomState"
]
] |
aliabdelkader/vkitti3D-dataset
|
[
"f92f86bcb83e376f5ea0d1e978a0469d8ebc9add"
] |
[
"tools/convert_npy_to_csv.py"
] |
[
"import numpy as np\nfrom tqdm import tqdm\nfrom pathlib import Path\nfrom concurrent.futures import ProcessPoolExecutor\nimport argparse\n\n\ndef covert_to_csv(infile):\n\n print(str(infile))\n point_cloud = np.load(str(infile)).reshape(-1, channels)\n file_name = infile.stem\n outfile = output_path / (file_name + '.csv')\n np.savetxt(outfile, point_cloud, delimiter=\",\")\n\n return None\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description=\"convert numpy files to csv\")\n\n parser.add_argument('--input_path', type=str, required=True,\n help='path numpy files')\n\n parser.add_argument('--channels', type=int, required=True,\n help='number of channels in npy file')\n\n parser.add_argument('--output_path', type=str, required=True,\n help='path for output files')\n\n parser.add_argument('--njobs', default=4, type=int,\n help='number of cores used for processing')\n\n args = parser.parse_args()\n\n input_path = Path(args.input_path)\n output_path = Path(args.output_path)\n channels = int(args.channels)\n n_jobs = int(args.njobs)\n\n files_list = input_path.glob(\"**/*.npy\")\n\n with ProcessPoolExecutor(max_workers=n_jobs) as pool:\n futures = [pool.submit(covert_to_csv, infile) for infile in files_list]\n\n"
] |
[
[
"numpy.savetxt"
]
] |
PoCFrance/UberPoC
|
[
"0c99403e47cd2ea7b07029821ac1997363354b61"
] |
[
"RCNN/training/train.py"
] |
[
"#!/usr/bin/env python3\n\nfrom pyimagesearch import config\nfrom imutils import paths\nimport numpy as np\nimport pickle\nimport os\nfrom keras.applications import MobileNetV2\nfrom keras.models import Sequential\nfrom keras.models import Model\nfrom keras.layers import AveragePooling2D\nfrom keras.layers import Dropout\nfrom keras.layers import Dense\nfrom keras.layers import Input\nfrom keras.layers import Flatten\nfrom keras.optimizers import Adam\nfrom keras.applications.mobilenet_v2 import preprocess_input\nfrom keras.preprocessing.image import img_to_array\nfrom keras.preprocessing.image import load_img\nfrom keras.utils import to_categorical\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport matplotlib.pyplot as plt\n\n\nclass RCNN():\n def __init__(self):\n self.init_lr = 1e-4\n self.epochs = 5\n self.bs = 2\n self.baseModel = MobileNetV2(weights=\"imagenet\", include_top=False, input_tensor=Input(shape=(224,224,3)))\n self.model = None\n self.aug = ImageDataGenerator(\n rotation_range=20,\n zoom_range=0.15,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.15,\n horizontal_flip=True,\n fill_mode=\"nearest\"\n )\n self.trainX, self.trainY = None, None\n self.testX, self.testY = None, None\n self.H = None\n self.lb = None\n self.build_model()\n\n def load_dataset(self):\n imagePaths = list(paths.list_images(config.BASE_PATH))\n data = []\n labels = []\n\n for imagePath in imagePaths:\n label = imagePath.split(os.path.sep)[-2]\n image = load_img(imagePath, target_size=config.INPUT_DIMS)\n image = img_to_array(image)\n image = preprocess_input(image)\n\n data.append(image)\n labels.append(label)\n data = np.array(data, dtype=\"float32\")\n labels = np.array(labels)\n self.lb = LabelBinarizer()\n labels = self.lb.fit_transform(labels)\n labels = to_categorical(labels)\n (self.trainX, self.testX, self.trainY, self.testY) = train_test_split(\n data, labels,\n test_size=0.20,\n stratify=labels,\n random_state=42\n )\n return self\n\n def build_model(self):\n headModel = self.baseModel.output\n headModel = AveragePooling2D(pool_size=(7,7))(headModel)\n headModel = Flatten(name=\"flatten\")(headModel)\n headModel = Dense(128, activation=\"relu\")(headModel)\n headModel = Dropout(0.5)(headModel)\n headModel = Dense(len(config.LABELS), activation=\"softmax\")(headModel)\n\n self.model = Model(inputs=self.baseModel.input, outputs=headModel)\n for layer in self.baseModel.layers:\n layer.trainable = False\n return self\n\n def summary(self):\n self.model.summary()\n\n def compile(self):\n print(\"[+] Model is compiling...\")\n opt = Adam(lr=self.init_lr)\n self.model.compile(loss=\"binary_crossentropy\", optimizer=opt, metrics=[\"accuracy\"])\n return self\n\n def train(self):\n print(\"[+] Model is training...\")\n self.H = self.model.fit(\n self.aug.flow(self.trainX, self.trainY, batch_size=self.bs),\n steps_per_epoch=len(self.trainX) // self.bs,\n validation_data=(self.testX, self.testY),\n validation_steps=len(self.testX) // self.bs,\n epochs=self.epochs\n )\n return self\n\n def evaluate(self):\n print(\"[INFO] evaluating network...\")\n predIdxs = self.model.predict(self.testX, batch_size=self.bs)\n\n # for each image in the testing set we need to find the index of the\n # label with corresponding largest predicted probability\n predIdxs = np.argmax(predIdxs, axis=1)\n\n # show a nicely formatted classification report\n print(classification_report(self.testY.argmax(axis=1), predIdxs,\n target_names=self.lb.classes_))\n\n # serialize the model to disk\n print(\"[+] saving mask detector model...\")\n self.model.save(config.MODEL_PATH, save_format=\"h5\")\n\n # serialize the label encoder to disk\n print(\"[+] saving label encoder...\")\n f = open(config.ENCODER_PATH, \"wb\")\n f.write(pickle.dumps(self.lb))\n f.close()\n\n # plot the training loss and accuracy\n N = self.epochs\n plt.style.use(\"ggplot\")\n plt.figure()\n plt.plot(np.arange(0, N), self.H.history[\"loss\"], label=\"train_loss\")\n plt.plot(np.arange(0, N), self.H.history[\"val_loss\"], label=\"val_loss\")\n plt.plot(np.arange(0, N), self.H.history[\"accuracy\"], label=\"train_acc\")\n plt.plot(np.arange(0, N), self.H.history[\"val_accuracy\"], label=\"val_acc\")\n plt.title(\"Training Loss and Accuracy\")\n plt.xlabel(\"Epoch #\")\n plt.ylabel(\"Loss/Accuracy\")\n plt.legend(loc=\"lower left\")\n plt.savefig('test.png')\n\n\nmyRcnn = RCNN()\nmyRcnn.load_dataset()\nmyRcnn.compile()\nmyRcnn.train()\nmyRcnn.evaluate()"
] |
[
[
"matplotlib.pyplot.legend",
"tensorflow.keras.preprocessing.image.ImageDataGenerator",
"matplotlib.pyplot.title",
"numpy.arange",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"numpy.argmax",
"sklearn.preprocessing.LabelBinarizer",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.figure"
]
] |
bronevet-abc/NLPython
|
[
"edb2f2c558215df556449c0fafb717d3442cfd9b"
] |
[
"ch9/make_neural_net/threelayersANN.py"
] |
[
"#The credits for this code go to Ludo Bouan.\n# I've merely created a wrapper to get people started.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport numpy as np\nfrom six.moves import range\nnp.seterr(over='ignore')\n\nclass NeuralNetwork():\n def __init__(self):\n np.random.seed(1) # Seed the random number generator\n self.weights = {} # Create dict to hold weights\n self.num_layers = 1 # Set initial number of layer to one (input layer)\n self.adjustments = {} # Create dict to hold adjustements\n\n def add_layer(self, shape):\n # Create weights with shape specified + biases\n self.weights[self.num_layers] = np.vstack((2 * np.random.random(shape) - 1, 2 * np.random.random((1, shape[1])) - 1))\n # Initialize the adjustements for these weights to zero\n self.adjustments[self.num_layers] = np.zeros(shape)\n self.num_layers += 1\n\n def __sigmoid(self, x):\n return 1 / (1 + np.exp(-x))\n\n def __sigmoid_derivative(self, x):\n return x * (1 - x)\n\n def predict(self, data):\n # Pass data through pretrained network\n for layer in range(1, self.num_layers+1):\n data = np.dot(data, self.weights[layer-1][:, :-1]) + self.weights[layer-1][:, -1] # + self.biases[layer]\n data = self.__sigmoid(data)\n return data\n\n def __forward_propagate(self, data):\n # Progapagate through network and hold values for use in back-propagation\n activation_values = {}\n activation_values[1] = data\n for layer in range(2, self.num_layers+1):\n data = np.dot(data.T, self.weights[layer-1][:-1, :]) + self.weights[layer-1][-1, :].T # + self.biases[layer]\n data = self.__sigmoid(data).T\n activation_values[layer] = data\n return activation_values\n\n def simple_error(self, outputs, targets):\n return targets - outputs\n\n def sum_squared_error(self, outputs, targets):\n return 0.5 * np.mean(np.sum(np.power(outputs - targets, 2), axis=1))\n\n def __back_propagate(self, output, target):\n deltas = {}\n # Delta of output Layer\n deltas[self.num_layers] = output[self.num_layers] - target\n\n # Delta of hidden Layers\n for layer in reversed(range(2, self.num_layers)): # All layers except input/output\n a_val = output[layer]\n weights = self.weights[layer][:-1, :]\n prev_deltas = deltas[layer+1]\n deltas[layer] = np.multiply(np.dot(weights, prev_deltas), self.__sigmoid_derivative(a_val))\n\n # Caclculate total adjustements based on deltas\n for layer in range(1, self.num_layers):\n self.adjustments[layer] += np.dot(deltas[layer+1], output[layer].T).T\n\n def __gradient_descente(self, batch_size, learning_rate):\n # Calculate partial derivative and take a step in that direction\n for layer in range(1, self.num_layers):\n partial_d = (1/batch_size) * self.adjustments[layer]\n self.weights[layer][:-1, :] += learning_rate * -partial_d\n self.weights[layer][-1, :] += learning_rate*1e-3 * -partial_d[-1, :]\n\n\n def train(self, inputs, targets, num_epochs, learning_rate=1, stop_accuracy=1e-5):\n error = []\n for iteration in range(num_epochs):\n for i in range(len(inputs)):\n x = inputs[i]\n y = targets[i]\n # Pass the training set through our neural network\n output = self.__forward_propagate(x)\n\n # Calculate the error\n loss = self.sum_squared_error(output[self.num_layers], y)\n error.append(loss)\n\n # Calculate Adjustements\n self.__back_propagate(output, y)\n\n self.__gradient_descente(i, learning_rate)\n\n # Check if accuarcy criterion is satisfied\n if np.mean(error[-(i+1):]) < stop_accuracy and iteration > 0:\n break\n\n return(np.asarray(error), iteration+1)\n\n\n\nif __name__ == \"__main__\":\n\n # ----------- XOR Function -----------------\n\n # Create instance of a neural network\n nn = NeuralNetwork()\n\n # Add Layers (Input layer is created by default)\n nn.add_layer((2, 9))\n nn.add_layer((9, 1))\n\n # XOR function\n training_data = np.asarray([[0, 0], [0, 1], [1, 0], [1, 1]]).reshape(4, 2, 1)\n training_labels = np.asarray([[0], [1], [1], [0]])\n\n error, iteration = nn.train(training_data, training_labels, 5000)\n print('Error = ', np.mean(error[-4:]))\n print('Epoches needed to train = ', iteration)\n\n # nn.predict(testing_data)"
] |
[
[
"numpy.dot",
"numpy.random.random",
"numpy.random.seed",
"numpy.power",
"numpy.asarray",
"numpy.seterr",
"numpy.mean",
"numpy.exp",
"numpy.zeros"
]
] |
mexxexx/stumpy
|
[
"dcfa14b98aee375da4239363c1d2a6520fb54e80"
] |
[
"stumpy/mpdist.py"
] |
[
"# STUMPY\n# Copyright 2019 TD Ameritrade. Released under the terms of the 3-Clause BSD license.\n# STUMPY is a trademark of TD Ameritrade IP Company, Inc. All rights reserved.\n\nimport numpy as np\nimport math\n\nfrom . import stump, stumped, core\nfrom .core import _mass_distance_matrix\nfrom .aampdist import aampdist, aampdisted\n\n\ndef _compute_P_ABBA(\n T_A, T_B, m, P_ABBA, dask_client=None, device_id=None, mp_func=stump\n):\n \"\"\"\n A convenience function for computing the (unsorted) concatenated matrix profiles\n from an AB-join and BA-join for the two time series, `T_A` and `T_B`. This result\n can then be used to compute the matrix profile distance (MPdist) measure.\n\n The MPdist distance measure considers two time series to be similar if they share\n many subsequences, regardless of the order of matching subsequences. MPdist\n concatenates and sorts the output of an AB-join and a BA-join and returns the value\n of the `k`th smallest number as the reported distance. Note that MPdist is a\n measure and not a metric. Therefore, it does not obey the triangular inequality but\n the method is highly scalable.\n\n Parameters\n ----------\n T_A : ndarray\n The first time series or sequence for which to compute the matrix profile\n\n T_B : ndarray\n The second time series or sequence for which to compute the matrix profile\n\n m : int\n Window size\n\n P_ABBA : ndarray\n The output array to write the concatenated AB-join and BA-join results to\n\n dask_client : client, default None\n A Dask Distributed client that is connected to a Dask scheduler and\n Dask workers. Setting up a Dask distributed cluster is beyond the\n scope of this library. Please refer to the Dask Distributed\n documentation.\n\n device_id : int or list, default None\n The (GPU) device number to use. The default value is `0`. A list of\n valid device ids (int) may also be provided for parallel GPU-STUMP\n computation. A list of all valid device ids can be obtained by\n executing `[device.id for device in numba.cuda.list_devices()]`.\n\n mp_func : object, default stump\n Specify a custom matrix profile function to use for computing matrix profiles\n\n Returns\n -------\n None\n\n Notes\n -----\n `DOI: 10.1109/ICDM.2018.00119 \\\n <https://www.cs.ucr.edu/~eamonn/MPdist_Expanded.pdf>`__\n\n See Section III\n \"\"\"\n n_A = T_A.shape[0]\n partial_mp_func = core._get_partial_mp_func(\n mp_func, dask_client=dask_client, device_id=device_id\n )\n\n P_ABBA[: n_A - m + 1] = partial_mp_func(T_A, m, T_B, ignore_trivial=False)[:, 0]\n P_ABBA[n_A - m + 1 :] = partial_mp_func(T_B, m, T_A, ignore_trivial=False)[:, 0]\n\n\ndef _select_P_ABBA_value(P_ABBA, k, custom_func=None):\n \"\"\"\n A convenience function for returning the `k`th smallest value from the `P_ABBA`\n array or use a custom function to specify what `P_ABBA` value to return.\n\n The MPdist distance measure considers two time series to be similar if they share\n many subsequences, regardless of the order of matching subsequences. MPdist\n concatenates and sorts the output of an AB-join and a BA-join and returns the value\n of the `k`th smallest number as the reported distance. Note that MPdist is a\n measure and not a metric. Therefore, it does not obey the triangular inequality but\n the method is highly scalable.\n\n Parameters\n ----------\n P_ABBA : ndarray\n A pre-sorted array resulting from the concatenation of the outputs from an\n AB-joinand BA-join for two time series, `T_A` and `T_B`\n\n k : int\n Specify the `k`th value in the concatenated matrix profiles to return. This\n parameter is ignored when `k_func` is not None.\n\n custom_func : object, default None\n A custom user defined function for selecting the desired value from the\n sorted `P_ABBA` array. This function may need to leverage `functools.partial`\n and should take `P_ABBA` as its only input parameter and return a single\n `MPdist` value. The `percentage` and `k` parameters are ignored when\n `custom_func` is not None.\n\n Returns\n -------\n MPdist : float\n The matrix profile distance\n \"\"\"\n k = min(int(k), P_ABBA.shape[0] - 1)\n if custom_func is not None:\n MPdist = custom_func(P_ABBA)\n else:\n MPdist = P_ABBA[k]\n if ~np.isfinite(MPdist):\n k = max(0, np.count_nonzero(np.isfinite(P_ABBA[:k])) - 1)\n MPdist = P_ABBA[k]\n\n return MPdist\n\n\ndef _mpdist(\n T_A,\n T_B,\n m,\n percentage=0.05,\n k=None,\n dask_client=None,\n device_id=None,\n mp_func=stump,\n custom_func=None,\n):\n \"\"\"\n A convenience function for computing the matrix profile distance (MPdist) measure\n between any two time series.\n\n The MPdist distance measure considers two time series to be similar if they share\n many subsequences, regardless of the order of matching subsequences. MPdist\n concatenates and sorts the output of an AB-join and a BA-join and returns the value\n of the `k`th smallest number as the reported distance. Note that MPdist is a\n measure and not a metric. Therefore, it does not obey the triangular inequality but\n the method is highly scalable.\n\n Parameters\n ----------\n T_A : ndarray\n The first time series or sequence for which to compute the matrix profile\n\n T_B : ndarray\n The second time series or sequence for which to compute the matrix profile\n\n m : int\n Window size\n\n percentage : float, 0.05\n The percentage of distances that will be used to report `mpdist`. The value\n is between 0.0 and 1.0. This parameter is ignored when `k` is not `None` or when\n `k_func` is not None.\n\n k : int, default None\n Specify the `k`th value in the concatenated matrix profiles to return. When `k`\n is not `None`, then the `percentage` parameter is ignored. This parameter is\n ignored when `k_func` is not None.\n\n dask_client : client, default None\n A Dask Distributed client that is connected to a Dask scheduler and\n Dask workers. Setting up a Dask distributed cluster is beyond the\n scope of this library. Please refer to the Dask Distributed\n documentation.\n\n device_id : int or list, default None\n The (GPU) device number to use. The default value is `0`. A list of\n valid device ids (int) may also be provided for parallel GPU-STUMP\n computation. A list of all valid device ids can be obtained by\n executing `[device.id for device in numba.cuda.list_devices()]`.\n\n mp_func : object, default stump\n Specify a custom matrix profile function to use for computing matrix profiles\n\n custom_func : object, default None\n A custom user defined function for selecting the desired value from the\n sorted `P_ABBA` array. This function may need to leverage `functools.partial`\n and should take `P_ABBA` as its only input parameter and return a single\n `MPdist` value. The `percentage` and `k` parameters are ignored when\n `custom_func` is not None.\n\n Returns\n -------\n MPdist : float\n The matrix profile distance\n\n Notes\n -----\n `DOI: 10.1109/ICDM.2018.00119 \\\n <https://www.cs.ucr.edu/~eamonn/MPdist_Expanded.pdf>`__\n\n See Section III\n \"\"\"\n n_A = T_A.shape[0]\n n_B = T_B.shape[0]\n P_ABBA = np.empty(n_A - m + 1 + n_B - m + 1, dtype=np.float64)\n\n _compute_P_ABBA(T_A, T_B, m, P_ABBA, dask_client, device_id, mp_func)\n P_ABBA.sort()\n\n if k is not None:\n k = min(int(k), P_ABBA.shape[0] - 1)\n else:\n percentage = min(percentage, 1.0)\n percentage = max(percentage, 0.0)\n k = min(math.ceil(percentage * (n_A + n_B)), n_A - m + 1 + n_B - m + 1 - 1)\n\n MPdist = _select_P_ABBA_value(P_ABBA, k, custom_func)\n\n return MPdist\n\n\ndef _mpdist_vect(\n Q,\n T,\n m,\n distance_matrix_func=_mass_distance_matrix,\n percentage=0.05,\n k=None,\n custom_func=None,\n):\n \"\"\"\n Compute the matrix profile distance measure vector between `Q` and each subsequence,\n `T[i : i + len(Q)]`, within `T`.\n\n Parameters\n ----------\n Q : ndarray\n Query array\n\n T : ndarray\n Time series or sequence\n\n m : int\n Window size\n\n distance_matrix_func : object, default _mass_distance_matrix\n The function to use to compute the distance matrix between `Q` and `T`\n\n percentage : float, 0.05\n The percentage of distances that will be used to report `mpdist`. The value\n is between 0.0 and 1.0. This parameter is ignored when `k` is not `None` or when\n `k_func` is not None.\n\n k : int, default None\n Specify the `k`th value in the concatenated matrix profiles to return. When `k`\n is not `None`, then the `percentage` parameter is ignored. This parameter is\n ignored when `k_func` is not None.\n\n custom_func : object, default None\n A custom user defined function for selecting the desired value from the\n sorted `P_ABBA` array. This function may need to leverage `functools.partial`\n and should take `P_ABBA` as its only input parameter and return a single\n `MPdist` value. The `percentage` and `k` parameters are ignored when\n `custom_func` is not None.\n \"\"\"\n j = Q.shape[0] - m + 1 # `k` is reserved for `P_ABBA` selection\n l = T.shape[0] - m + 1\n MPdist_vect = np.empty(T.shape[0] - Q.shape[0] + 1)\n distance_matrix = np.full((j, l), np.inf)\n P_ABBA = np.empty(2 * j)\n\n if k is None:\n percentage = min(percentage, 1.0)\n percentage = max(percentage, 0.0)\n k = min(math.ceil(percentage * (2 * Q.shape[0])), 2 * j - 1)\n\n k = min(int(k), P_ABBA.shape[0] - 1)\n\n distance_matrix_func(Q, T, m, distance_matrix)\n\n rolling_row_min = core.rolling_nanmin(distance_matrix, j)\n col_min = np.nanmin(distance_matrix, axis=0)\n\n for i in range(MPdist_vect.shape[0]):\n P_ABBA[:j] = rolling_row_min[:, i]\n P_ABBA[j:] = col_min[i : i + j]\n P_ABBA.sort()\n MPdist_vect[i] = _select_P_ABBA_value(P_ABBA, k, custom_func)\n\n return MPdist_vect\n\n\[email protected]_normalized(aampdist)\ndef mpdist(T_A, T_B, m, percentage=0.05, k=None, normalize=True):\n \"\"\"\n Compute the z-normalized matrix profile distance (MPdist) measure between any two\n time series\n\n The MPdist distance measure considers two time series to be similar if they share\n many subsequences, regardless of the order of matching subsequences. MPdist\n concatenates and sorts the output of an AB-join and a BA-join and returns the value\n of the `k`th smallest number as the reported distance. Note that MPdist is a\n measure and not a metric. Therefore, it does not obey the triangular inequality but\n the method is highly scalable.\n\n Parameters\n ----------\n T_A : ndarray\n The first time series or sequence for which to compute the matrix profile\n\n T_B : ndarray\n The second time series or sequence for which to compute the matrix profile\n\n m : int\n Window size\n\n percentage : float, default 0.05\n The percentage of distances that will be used to report `mpdist`. The value\n is between 0.0 and 1.0.\n\n normalize : bool, default True\n When set to `True`, this z-normalizes subsequences prior to computing distances.\n Otherwise, this function gets re-routed to its complementary non-normalized\n equivalent set in the `@core.non_normalized` function decorator.\n\n Returns\n -------\n MPdist : float\n The matrix profile distance\n\n Notes\n -----\n `DOI: 10.1109/ICDM.2018.00119 \\\n <https://www.cs.ucr.edu/~eamonn/MPdist_Expanded.pdf>`__\n\n See Section III\n \"\"\"\n return _mpdist(T_A, T_B, m, percentage, k, mp_func=stump)\n\n\[email protected]_normalized(aampdisted)\ndef mpdisted(dask_client, T_A, T_B, m, percentage=0.05, k=None, normalize=True):\n \"\"\"\n Compute the z-normalized matrix profile distance (MPdist) measure between any two\n time series with a distributed dask cluster\n\n The MPdist distance measure considers two time series to be similar if they share\n many subsequences, regardless of the order of matching subsequences. MPdist\n concatenates and sorts the output of an AB-join and a BA-join and returns the value\n of the `k`th smallest number as the reported distance. Note that MPdist is a\n measure and not a metric. Therefore, it does not obey the triangular inequality but\n the method is highly scalable.\n\n Parameters\n ----------\n dask_client : client\n A Dask Distributed client that is connected to a Dask scheduler and\n Dask workers. Setting up a Dask distributed cluster is beyond the\n scope of this library. Please refer to the Dask Distributed\n documentation.\n\n T_A : ndarray\n The first time series or sequence for which to compute the matrix profile\n\n T_B : ndarray\n The second time series or sequence for which to compute the matrix profile\n\n m : int\n Window size\n\n percentage : float, default 0.05\n The percentage of distances that will be used to report `mpdist`. The value\n is between 0.0 and 1.0. This parameter is ignored when `k` is not `None`.\n\n k : int\n Specify the `k`th value in the concatenated matrix profiles to return. When `k`\n is not `None`, then the `percentage` parameter is ignored.\n\n normalize : bool, default True\n When set to `True`, this z-normalizes subsequences prior to computing distances.\n Otherwise, this function gets re-routed to its complementary non-normalized\n equivalent set in the `@core.non_normalized` function decorator.\n\n Returns\n -------\n MPdist : float\n The matrix profile distance\n\n Notes\n -----\n `DOI: 10.1109/ICDM.2018.00119 \\\n <https://www.cs.ucr.edu/~eamonn/MPdist_Expanded.pdf>`__\n\n See Section III\n \"\"\"\n return _mpdist(T_A, T_B, m, percentage, k, dask_client=dask_client, mp_func=stumped)\n"
] |
[
[
"numpy.nanmin",
"numpy.isfinite",
"numpy.empty",
"numpy.full"
]
] |
SungbinChoi/w4c_st1
|
[
"5acdedf3c6278cd7239a6beb605c3e16821f7c86"
] |
[
"test/v2_1/test1.py"
] |
[
"import random\nfrom random import shuffle\nimport numpy as np\nfrom datetime import datetime\nimport time\nimport queue\nimport threading\nimport logging\nfrom PIL import Image\nimport itertools\nimport re\nimport os\nimport glob\nimport shutil\nimport sys\nimport copy\nimport h5py\nfrom netCDF4 import Dataset\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.nn.parallel.data_parallel import data_parallel\nimport torch.utils.checkpoint as cp\nfrom collections import OrderedDict\nfrom torch import Tensor\nfrom typing import Any, List, Tuple\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\ntarget_city = 'R1'\ntarget_out_var_index = 2\nglobal_step_start = 232000\ninitial_checkpoint = 'model' + ('/%09d_model.pth' % (global_step_start))\nout_dir = target_city + '_' + str(target_out_var_index)\ninput_data_folder_path = '../../0_data_heldout/' + target_city \nnum_frame_per_day = 96 \nnum_frame_before = 4 \nnum_frame_out = 32 \nnum_frame_sequence = 36 \nheight=256\nwidth =256\nnum_channel_1 = 9 \nnum_channel_2_src = 16 \nnum_channel_2 = 107 + num_channel_2_src\nnum_channel = (num_channel_1*2 + num_channel_2)\nnum_channel_out= 4 \nNUM_INPUT_CHANNEL = num_channel * num_frame_before\nNUM_OUTPUT_CHANNEL = num_channel_out * num_frame_out\nSEED = 0\nnum_groups = 8\nEPS = 1e-12\nnp.set_printoptions(precision=6)\n\nclass Deconv3x3Block(nn.Sequential):\n def __init__(self, \n in_size: int, \n h_size: int, ) -> None:\n super(Deconv3x3Block, self).__init__()\n self.add_module('deconv', nn.ConvTranspose2d(in_size, h_size, kernel_size=3, stride=2, padding=1, bias=True))\n self.add_module('elu', nn.ELU(inplace=True)) \n self.add_module('norm', nn.GroupNorm(num_groups=num_groups, num_channels=h_size)) \n\nclass Conv1x1Block(nn.Sequential):\n def __init__(self, \n in_size: int, \n h_size: int, ) -> None:\n super(Conv1x1Block, self).__init__()\n self.add_module('conv', nn.Conv2d(in_size, h_size, kernel_size=1, stride=1, padding=0, bias=True))\n\nclass Conv3x3Block(nn.Sequential):\n def __init__(self, \n in_size: int, \n h_size: int, ) -> None:\n super(Conv3x3Block, self).__init__()\n self.add_module('conv', nn.Conv2d(in_size, h_size, kernel_size=3, stride=1, padding=1, bias=True))\n self.add_module('elu', nn.ELU(inplace=True)) \n self.add_module('norm', nn.GroupNorm(num_groups=num_groups, num_channels=h_size)) \n\nclass AvgBlock(nn.Sequential):\n def __init__(self, \n kernel_size: int, \n stride: int, \n padding: int) -> None:\n super(AvgBlock, self).__init__()\n self.add_module('pool', nn.AvgPool2d(kernel_size=kernel_size, stride=stride, padding=padding)) \n \nclass MaxBlock(nn.Sequential):\n def __init__(self, \n kernel_size: int, \n stride: int, \n padding: int) -> None:\n super(MaxBlock, self).__init__()\n self.add_module('pool', nn.MaxPool2d(kernel_size=kernel_size, stride=stride, padding=padding)) \n\nclass DownBlock(nn.Module):\n \n\n def __init__(self, \n in_size: int, \n h_size: int, \n out_size: int, \n do_pool: int = True):\n \n super(DownBlock, self).__init__() \n\n self.do_pool = do_pool\n\n self.pool = None\n if self.do_pool:\n self.pool = AvgBlock(kernel_size=2, stride=2, padding=0)\n\n in_size_cum = in_size \n \n self.conv_1 = Conv3x3Block( in_size=in_size_cum, h_size=h_size)\n in_size_cum += h_size\n \n self.conv_3 = Conv3x3Block( in_size=in_size_cum, h_size=h_size)\n in_size_cum += h_size\n \n self.conv_2 = Conv1x1Block( in_size=in_size_cum, h_size=out_size)\n\n def forward(self, x):\n \n batch_size = len(x)\n\n if self.do_pool:\n x = self.pool(x)\n\n x_list = []\n x_list.append(x)\n \n x = self.conv_1(x)\n x_list.append(x)\n x = torch.cat(x_list, 1)\n \n x = self.conv_3(x)\n x_list.append(x)\n x = torch.cat(x_list, 1)\n \n x = self.conv_2(x)\n\n return x\n\n def cuda(self, ):\n super(DownBlock, self).cuda() \n \n self.conv_1.cuda()\n self.conv_3.cuda()\n self.conv_2.cuda()\n \n return self\n\nclass UpBlock(nn.Module):\n \n\n def __init__(self, \n in_size: int, \n in_size_2: int, \n h_size: int, \n out_size: int, \n ):\n \n super(UpBlock, self).__init__() \n \n self.deconv = Deconv3x3Block( in_size=in_size, h_size=h_size)\n self.out_conv = Conv3x3Block( in_size=h_size + in_size_2, h_size=out_size)\n\n def forward(self, x1, x2):\n\n x1 = self.deconv(x1)\n x1 = F.interpolate(x1, size=x2.size()[2:4], scale_factor=None, mode='bilinear', align_corners=False, recompute_scale_factor=None)\n x = torch.cat([x2, x1], dim=1)\n return self.out_conv(x)\n\n def cuda(self, ):\n super(UpBlock, self).cuda() \n self.deconv.cuda()\n self.out_conv.cuda()\n \n return self\n\nclass NetA(nn.Module):\n\n def __init__(self,):\n super(NetA, self).__init__()\n\n self.block0 = DownBlock(in_size=NUM_INPUT_CHANNEL, h_size=128, out_size=128, do_pool=False)\n self.block1 = DownBlock(in_size=128, h_size=128, out_size=128,)\n self.block2 = DownBlock(in_size=128, h_size=128, out_size=128, )\n self.block3 = DownBlock(in_size=128, h_size=128, out_size=128, )\n self.block4 = DownBlock(in_size=128, h_size=128, out_size=128, )\n self.block5 = DownBlock(in_size=128, h_size=128, out_size=128, )\n self.block6 = DownBlock(in_size=128, h_size=128, out_size=128,)\n \n self.block20 = Conv3x3Block(in_size=128, h_size=128)\n \n self.block15 = UpBlock(in_size=128, in_size_2=128, h_size=128, out_size=128,) \n self.block14 = UpBlock(in_size=128, in_size_2=128, h_size=128, out_size=128,)\n self.block13 = UpBlock(in_size=128, in_size_2=128, h_size=128, out_size=128,) \n self.block12 = UpBlock(in_size=128, in_size_2=128, h_size=128, out_size=128,) \n self.block11 = UpBlock(in_size=128, in_size_2=128 , h_size=128, out_size=128,) \n self.block10 = UpBlock(in_size=128, in_size_2=128 , h_size=128, out_size=128,) \n \n self.out_conv = nn.Sequential(\n nn.Conv2d(128*1, NUM_OUTPUT_CHANNEL, kernel_size=3, stride=1, padding=1, bias=True)\n )\n \n if 1:\n \n for name, m in self.named_modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n nn.init.kaiming_normal_(m.weight)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.GroupNorm):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.Linear):\n nn.init.constant_(m.bias, 0)\n \n def forward(self, x):\n \n batch_size = len(x)\n\n x0 = self.block0(x)\n x1 = self.block1(x0)\n x2 = self.block2(x1)\n x3 = self.block3(x2)\n x4 = self.block4(x3)\n x5 = self.block5(x4)\n x6 = self.block6(x5)\n \n x = self.block20(x6)\n \n x = self.block15(x, x5)\n x = self.block14(x, x4)\n x = self.block13(x, x3)\n x = self.block12(x, x2)\n x = self.block11(x, x1)\n x = self.block10(x, x0) \n\n x = self.out_conv(x)\n x = torch.reshape(x, (batch_size, num_channel_out, 1, num_frame_out, height, width))\n\n return x[:,0,:,:,:,:], x[:,1,:,:,:,:], x[:,2,:,:,:,:], x[:,3,:,:,:,:]\n \n \n\n\n\n def cuda(self, ):\n super(NetA, self).cuda()\n \n self.block0.cuda()\n self.block1.cuda()\n self.block2.cuda()\n self.block3.cuda()\n self.block4.cuda()\n self.block5.cuda()\n self.block6.cuda()\n \n self.block20.cuda()\n \n self.block15.cuda()\n self.block14.cuda()\n self.block13.cuda()\n self.block12.cuda()\n self.block11.cuda()\n self.block10.cuda()\n \n self.out_conv.cuda()\n \n return self \n\ncontinuous_data_info_list = np.zeros((num_channel_1, 3), np.float32)\nif 1:\n \n continuous_data_info_filepath = os.path.join('../0_data', 'continuous_data_info_all.txt')\n \n c=0\n with open(continuous_data_info_filepath) as info_file:\n content = info_file.readlines()\n\n for line in content:\n cols = line.strip().split('\\t')\n \n d_min = int( cols[0])\n d_max = int( cols[1])\n d_avg = float(cols[2])\n continuous_data_info_list[c,:] = (d_min,d_max,d_avg)\n \n c += 1\n \n assert c == num_channel_1 \n\ncontinuous_data_info_list_min = continuous_data_info_list[np.newaxis,:, 0, np.newaxis,np.newaxis,]\ncontinuous_data_info_list_max = continuous_data_info_list[np.newaxis,:, 1, np.newaxis,np.newaxis,]\n\ncontinuous_output_info_list = np.zeros((3, 2), np.float32) \ncontinuous_output_info_list[0,:] = (130, 350) \ncontinuous_output_info_list[1,:] = (0, 50) \ncontinuous_output_info_list[2,:] = (0, 100) \ncontinuous_output_info_list = continuous_output_info_list[np.newaxis, :, :, np.newaxis,np.newaxis,]\n\n \ndiscrete_data_info_list = np.zeros((num_channel_2_src, ), np.uint8)\nif 1:\n discrete_data_info_filepath = os.path.join('../0_data_heldout/', 'discrete_data_info.txt')\n c=0\n with open(discrete_data_info_filepath) as info_file:\n content = info_file.readlines()\n for line in content:\n cols = line.strip().split('\\t')\n num_flag = int(cols[0])\n discrete_data_info_list[c] = (num_flag+1) \n c += 1\n assert c == num_channel_2_src \n assert np.sum(discrete_data_info_list) == num_channel_2\n \ncum_num_flag_list = np.zeros((num_channel_2_src, 2), np.uint8)\ncc = 0\nfor c in range(num_channel_2_src):\n cum_num_flag_list[c,0] = cc\n cc+=discrete_data_info_list[c]\n cum_num_flag_list[c,1] = cc\nassert cc < 256 \n\nif __name__ == '__main__':\n\n \n COMMON_STRING ='@%s: \\n' % os.path.basename(__file__)\n COMMON_STRING += '\\tset random seed\\n'\n COMMON_STRING += '\\t\\tSEED = %d\\n'%SEED\n \n random.seed(SEED)\n np.random.seed(SEED)\n torch.manual_seed(SEED)\n torch.cuda.manual_seed_all(SEED)\n \n torch.backends.cudnn.enabled = True\n torch.backends.cudnn.benchmark = True \n torch.backends.cudnn.deterministic = True\n\n COMMON_STRING += '\\tset cuda environment\\n'\n COMMON_STRING += '\\t\\ttorch.__version__ = %s\\n'%torch.__version__\n COMMON_STRING += '\\t\\ttorch.version.cuda = %s\\n'%torch.version.cuda\n COMMON_STRING += '\\t\\ttorch.backends.cudnn.version() = %s\\n'%torch.backends.cudnn.version()\n try:\n COMMON_STRING += '\\t\\tos[\\'CUDA_VISIBLE_DEVICES\\'] = %s\\n'%os.environ['CUDA_VISIBLE_DEVICES']\n NUM_CUDA_DEVICES = len(os.environ['CUDA_VISIBLE_DEVICES'].split(','))\n except Exception:\n COMMON_STRING += '\\t\\tos[\\'CUDA_VISIBLE_DEVICES\\'] = None\\n'\n NUM_CUDA_DEVICES = 1\n COMMON_STRING += '\\t\\ttorch.cuda.device_count() = %d\\n'%torch.cuda.device_count()\n\n print(COMMON_STRING)\n\n try:\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n except Exception:\n print('out_dir not made')\n exit(-1)\n\n net = NetA().cuda()\n asii_logit_m = -torch.logit(torch.from_numpy(np.array(0.003,np.float32)).float().cuda())\n assert initial_checkpoint is not None\n if 1:\n print('Loading ', initial_checkpoint)\n state_dict_0 = torch.load(initial_checkpoint, map_location=lambda storage, loc: storage)\n net.load_state_dict(state_dict_0, strict=True)\n net.eval() \n \n index_list2 = np.arange(num_frame_before * height * width)\n def get_data(input_data_1, input_data_2):\n\n input_data_out_3 = np.ones((num_frame_before, num_channel_1, height, width), np.float32)\n \n input_data_out_1 = \\\n (input_data_1 \n - continuous_data_info_list_min)\\\n / (continuous_data_info_list_max\n - continuous_data_info_list_min)\n \n input_data_out_1[input_data_1==65535] = 0\n input_data_out_3[input_data_1==65535] = 0\n \n input_data_out_1 = np.moveaxis(input_data_out_1, 1, 0)\n input_data_out_3 = np.moveaxis(input_data_out_3, 1, 0) \n\n input_data_2 = input_data_2.astype(np.uint16)\n input_data_2 += 1\n input_data_2[input_data_2==256] = 0\n \n input_data_2 = input_data_2.astype(np.uint8) \n one_hot_list = np.zeros((num_frame_before * height * width, num_channel_2), np.uint8)\n for c in range(num_channel_2_src):\n one_hot_list[index_list2, cum_num_flag_list[c,0] + input_data_2[:,c,:,:].reshape(-1)] = 1\n input_data_out_2 = np.moveaxis(one_hot_list, -1, 0).reshape(num_channel_2, num_frame_before, height, width) \n input_data_out = np.concatenate([input_data_out_1, input_data_out_3, input_data_out_2, ], axis=0)\n input_data_out = input_data_out.reshape(-1, height, width)\n\n return input_data_out\n\n \n \n asii_frame_file_name_prefix = 'S_NWC_ASII-TF_MSG4_Europe-VISIR_'\n asii_frame_file_name_prefix_len = len(asii_frame_file_name_prefix)\n \n input_folder_path = input_data_folder_path + '/' + 'test'\n num_day_done = 0\n \n for day_folder_name in os.listdir(input_folder_path):\n \n day_folder_path = os.path.join(input_folder_path, day_folder_name)\n if os.path.isdir(day_folder_path) == False:\n continue\n \n day = int(day_folder_name)\n\n frame_file_name_list = []\n for frame_file_name in os.listdir(os.path.join(day_folder_path, 'ASII')):\n if frame_file_name.split('.')[-1] != 'nc': \n continue\n \n assert frame_file_name[asii_frame_file_name_prefix_len-1] == '_'\n assert frame_file_name[asii_frame_file_name_prefix_len+8] == 'T'\n \n frame_file_name_list.append(frame_file_name)\n \n\n assert len(frame_file_name_list) == num_frame_before\n frame_file_name_list = sorted(frame_file_name_list)\n \n min_before = 0\n ymd_list = []\n for frame_file_name in frame_file_name_list:\n ymd = int(frame_file_name[asii_frame_file_name_prefix_len : (asii_frame_file_name_prefix_len+8)]) \n hour = int(frame_file_name[asii_frame_file_name_prefix_len+9 : (asii_frame_file_name_prefix_len+11)]) \n minute = int(frame_file_name[asii_frame_file_name_prefix_len+11 : (asii_frame_file_name_prefix_len+13)]) \n ymd_list.append((ymd, hour, minute))\n \n min_now = (ymd-20190000)*24*60 + hour*60 + minute\n assert min_before < min_now\n min_before = min_now\n \n \n file_list=[] \n for (ymd, hour, minute) in ymd_list:\n file_list.append(\\\n (os.path.join(input_folder_path, str(day), 'CTTH', 'S_NWC_CTTH_MSG4_Europe-VISIR_' + str(ymd) + ('T%02d%02d%02d' % (hour, minute, 0)) + 'Z.nc'),\n os.path.join(input_folder_path, str(day), 'CRR', 'S_NWC_CRR_MSG4_Europe-VISIR_' + str(ymd) + ('T%02d%02d%02d' % (hour, minute, 0)) + 'Z.nc'),\n os.path.join(input_folder_path, str(day), 'ASII', 'S_NWC_ASII-TF_MSG4_Europe-VISIR_' + str(ymd) + ('T%02d%02d%02d' % (hour, minute, 0)) + 'Z.nc'),\n os.path.join(input_folder_path, str(day), 'CMA', 'S_NWC_CMA_MSG4_Europe-VISIR_' + str(ymd) + ('T%02d%02d%02d' % (hour, minute, 0)) + 'Z.nc'),\n os.path.join(input_folder_path, str(day), 'CT', 'S_NWC_CT_MSG4_Europe-VISIR_' + str(ymd) + ('T%02d%02d%02d' % (hour, minute, 0)) + 'Z.nc'),\n ))\n \n \n file_list_2=[] \n for (ymd, hour, minute) in ymd_list:\n file_list_2.append(\\\n (os.path.join(input_folder_path, str(day), 'CTTH', 'S_NWC_CTTH_MSG2_Europe-VISIR_' + str(ymd) + ('T%02d%02d%02d' % (hour, minute, 0)) + 'Z.nc'),\n os.path.join(input_folder_path, str(day), 'CRR', 'S_NWC_CRR_MSG2_Europe-VISIR_' + str(ymd) + ('T%02d%02d%02d' % (hour, minute, 0)) + 'Z.nc'),\n os.path.join(input_folder_path, str(day), 'ASII', 'S_NWC_ASII-TF_MSG2_Europe-VISIR_' + str(ymd) + ('T%02d%02d%02d' % (hour, minute, 0)) + 'Z.nc'),\n os.path.join(input_folder_path, str(day), 'CMA', 'S_NWC_CMA_MSG2_Europe-VISIR_' + str(ymd) + ('T%02d%02d%02d' % (hour, minute, 0)) + 'Z.nc'),\n os.path.join(input_folder_path, str(day), 'CT', 'S_NWC_CT_MSG2_Europe-VISIR_' + str(ymd) + ('T%02d%02d%02d' % (hour, minute, 0)) + 'Z.nc'),\n ))\n\n out_data_1 = np.zeros((num_frame_before, num_channel_1, height, width), np.uint16)\n out_data_2 = np.zeros((num_frame_before, num_channel_2_src, height, width), np.uint8)\n \n out_data_1[:,:,:,:] = 65535\n out_data_2[:,:,:,:] = 255\n \n for f, (filepath_1, filepath_2, filepath_3, filepath_4, filepath_5) in enumerate(file_list):\n\n c1 = 0\n c2 = 0\n \n # CTTH 9\n if 1:\n filepath = filepath_1\n dtype = np.dtype(np.uint16)\n if os.path.exists(filepath) == False:\n filepath = file_list_2[f][0]\n assert os.path.exists(filepath)\n \n ds = Dataset(filepath, 'r')\n #print(ds.variables.keys())\n\n key_list = ['temperature',\n 'ctth_tempe',\n 'ctth_pres',\n 'ctth_alti',\n 'ctth_effectiv',\n 'ctth_method',\n 'ctth_quality',\n 'ishai_skt',\n 'ishai_quality',\n ]\n assert len(key_list) == 9\n \n for key in key_list:\n \n \n d_arr = np.array(ds[key]).astype(dtype) \n \n \n has_flag = False\n flags = None\n try:\n flags = np.array(ds[key].flag_values, dtype)\n has_flag = True\n except:\n pass\n\n if has_flag:\n \n for flag_i, flag in enumerate(flags):\n out_data_2[f, c2, d_arr == flag] = flag_i\n \n assert discrete_data_info_list[c2] == len(flags)+1 \n\n c2 += 1\n \n \n else:\n\n has_scale = False\n has_offset = False\n scale_factor = 1.0\n offset = 0.0\n #\n try:\n scale_factor = ds[key].scale_factor\n has_scale = True\n except:\n pass\n try:\n offset = ds[key].add_offset\n has_offset = True\n except:\n pass\n assert scale_factor != 0\n \n \n \n has_valid_range = False\n valid_min = 0\n valid_max = 0\n try:\n valid_min = ds[key].valid_range[0]\n valid_max = ds[key].valid_range[1]\n has_valid_range = True\n except:\n pass\n \n \n mask_arr = np.ones((height, width), np.uint8)\n mask_arr[d_arr == ds[key]._FillValue] = 0\n \n d_arr_float = d_arr.astype(np.float32)\n if has_offset:\n d_arr_float -= offset\n if has_scale:\n d_arr_float /= scale_factor\n # \n if has_valid_range:\n mask_arr[d_arr_float < valid_min] = 0 \n mask_arr[d_arr_float > valid_max] = 0\n \n \n \n \n is_valid = (mask_arr == 1) \n is_invalid = (mask_arr == 0)\n\n out_data_1[f, c1, :, :] = d_arr \n out_data_1[f, c1, is_invalid] = 65535 \n \n c1 += 1\n\n #CRR 4\n if 1:\n filepath = filepath_2\n dtype = np.dtype(np.uint16)\n if os.path.exists(filepath) == False:\n filepath = file_list_2[f][1]\n assert os.path.exists(filepath)\n \n ds = Dataset(filepath, 'r')\n #print(ds.variables.keys())\n\n\n key_list = ['crr',\n 'crr_intensity',\n 'crr_accum',\n 'crr_quality',\n ]\n assert len(key_list) == 4\n \n for key in key_list:\n \n \n d_arr = np.array(ds[key]).astype(dtype) \n \n \n has_flag = False\n flags = None\n try:\n #print(ds[key].flag_values)\n flags = np.array(ds[key].flag_values, dtype) # []\n has_flag = True\n except:\n pass\n \n\n \n \n if has_flag:\n \n for flag_i, flag in enumerate(flags):\n out_data_2[f, c2, d_arr == flag] = flag_i\n \n assert discrete_data_info_list[c2] == len(flags)+1\n \n c2 += 1\n \n \n else:\n \n has_scale = False\n has_offset = False\n scale_factor = 1.0\n offset = 0.0\n #\n try:\n scale_factor = ds[key].scale_factor\n has_scale = True\n except:\n pass\n try:\n offset = ds[key].add_offset\n has_offset = True\n except:\n pass\n assert scale_factor != 0\n \n \n \n has_valid_range = False\n valid_min = 0\n valid_max = 0\n try:\n valid_min = ds[key].valid_range[0]\n valid_max = ds[key].valid_range[1]\n has_valid_range = True\n except:\n pass\n \n \n \n \n \n \n \n mask_arr = np.ones((height, width), np.uint8)\n mask_arr[d_arr == ds[key]._FillValue] = 0 \n \n d_arr_float = d_arr.astype(np.float32)\n if has_offset:\n d_arr_float -= offset\n if has_scale:\n d_arr_float /= scale_factor\n # \n if has_valid_range:\n mask_arr[d_arr_float < valid_min] = 0 \n mask_arr[d_arr_float > valid_max] = 0\n\n \n is_valid = (mask_arr == 1) \n is_invalid = (mask_arr == 0)\n\n out_data_1[f, c1, :, :] = d_arr \n out_data_1[f, c1, is_invalid] = 65535 \n \n c1 += 1\n \n \n \n #ASII 2\n if 1:\n filepath = filepath_3\n dtype = np.dtype(np.uint8)\n if os.path.exists(filepath) == False:\n filepath = file_list_2[f][2]\n assert os.path.exists(filepath)\n \n ds = Dataset(filepath, 'r')\n #print(ds.variables.keys())\n\n\n key_list = ['asii_turb_trop_prob',\n 'asiitf_quality',\n ]\n assert len(key_list) == 2\n \n for key in key_list:\n \n \n d_arr = np.array(ds[key]).astype(dtype) # [height, width]\n \n \n has_flag = False\n flags = None\n try:\n #print(ds[key].flag_values)\n flags = np.array(ds[key].flag_values, dtype) # []\n has_flag = True\n except:\n pass\n \n\n \n \n if has_flag:\n \n for flag_i, flag in enumerate(flags):\n out_data_2[f, c2, d_arr == flag] = flag_i\n \n assert discrete_data_info_list[c2] == len(flags)+1\n\n c2 += 1\n \n \n else:\n \n \n \n has_scale = False\n has_offset = False\n scale_factor = 1.0\n offset = 0.0\n #\n try:\n scale_factor = ds[key].scale_factor\n has_scale = True\n except:\n pass\n try:\n offset = ds[key].add_offset\n has_offset = True\n except:\n pass\n assert scale_factor != 0\n \n \n \n has_valid_range = False\n valid_min = 0\n valid_max = 0\n try:\n valid_min = ds[key].valid_range[0]\n valid_max = ds[key].valid_range[1]\n has_valid_range = True\n except:\n pass\n \n \n \n \n mask_arr = np.ones((height, width), np.uint8)\n mask_arr[d_arr == ds[key]._FillValue] = 0 \n \n d_arr_float = d_arr.astype(np.float32)\n if has_offset:\n d_arr_float -= offset\n if has_scale:\n d_arr_float /= scale_factor\n # \n if has_valid_range:\n mask_arr[d_arr_float < valid_min] = 0 \n mask_arr[d_arr_float > valid_max] = 0\n \n is_valid = (mask_arr == 1) \n is_invalid = (mask_arr == 0)\n\n out_data_1[f, c1, :, :] = d_arr \n out_data_1[f, c1, is_invalid] = 65535 \n \n c1 += 1\n\n \n #CMA 6\n if 1:\n filepath = filepath_4\n dtype = np.dtype(np.uint8)\n if os.path.exists(filepath) == False:\n filepath = file_list_2[f][3]\n assert os.path.exists(filepath)\n \n ds = Dataset(filepath, 'r')\n #print(ds.variables.keys())\n\n\n key_list = ['cma_cloudsnow',\n 'cma',\n 'cma_dust',\n 'cma_volcanic',\n 'cma_smoke',\n 'cma_quality',\n ]\n assert len(key_list) == 6\n \n for key in key_list:\n \n \n d_arr = np.array(ds[key]).astype(dtype) # [height, width]\n \n \n has_flag = False\n flags = None\n try:\n flags = np.array(ds[key].flag_values, dtype) # []\n has_flag = True\n except:\n pass\n \n\n \n \n if has_flag:\n \n for flag_i, flag in enumerate(flags):\n out_data_2[f, c2, d_arr == flag] = flag_i\n assert discrete_data_info_list[c2] == len(flags)+1\n c2 += 1\n \n \n else:\n \n has_scale = False\n has_offset = False\n scale_factor = 1.0\n offset = 0.0\n #\n try:\n scale_factor = ds[key].scale_factor\n has_scale = True\n except:\n pass\n try:\n offset = ds[key].add_offset\n has_offset = True\n except:\n pass\n assert scale_factor != 0\n \n \n \n has_valid_range = False\n valid_min = 0\n valid_max = 0\n try:\n valid_min = ds[key].valid_range[0]\n valid_max = ds[key].valid_range[1]\n has_valid_range = True\n except:\n pass\n \n \n \n mask_arr = np.ones((height, width), np.uint8)\n mask_arr[d_arr == ds[key]._FillValue] = 0 \n \n d_arr_float = d_arr.astype(np.float32)\n if has_offset:\n d_arr_float -= offset\n if has_scale:\n d_arr_float /= scale_factor\n # \n if has_valid_range:\n mask_arr[d_arr_float < valid_min] = 0 \n mask_arr[d_arr_float > valid_max] = 0\n \n \n \n \n is_valid = (mask_arr == 1) \n is_invalid = (mask_arr == 0)\n\n out_data_1[f, c1, :, :] = d_arr \n out_data_1[f, c1, is_invalid] = 65535 \n \n c1 += 1\n \n \n \n #CT 4\n if 1:\n filepath = filepath_5\n dtype = np.dtype(np.uint8)\n if os.path.exists(filepath) == False:\n filepath = file_list_2[f][4]\n assert os.path.exists(filepath)\n \n ds = Dataset(filepath, 'r')\n #print(ds.variables.keys())\n\n\n key_list = ['ct',\n 'ct_cumuliform',\n 'ct_multilayer',\n 'ct_quality',\n ]\n assert len(key_list) == 4\n \n for key in key_list:\n \n \n d_arr = np.array(ds[key]).astype(dtype) # [height, width]\n \n \n has_flag = False\n flags = None\n try:\n #print(ds[key].flag_values)\n flags = np.array(ds[key].flag_values, dtype) # []\n has_flag = True\n except:\n pass\n \n\n \n \n if has_flag:\n \n for flag_i, flag in enumerate(flags):\n out_data_2[f, c2, d_arr == flag] = flag_i\n \n assert discrete_data_info_list[c2] == len(flags)+1\n c2 += 1\n \n \n else:\n \n \n \n has_scale = False\n has_offset = False\n scale_factor = 1.0\n offset = 0.0\n #\n try:\n scale_factor = ds[key].scale_factor\n has_scale = True\n except:\n pass\n try:\n offset = ds[key].add_offset\n has_offset = True\n except:\n pass\n assert scale_factor != 0\n \n \n \n has_valid_range = False\n valid_min = 0\n valid_max = 0\n try:\n valid_min = ds[key].valid_range[0]\n valid_max = ds[key].valid_range[1]\n has_valid_range = True\n except:\n pass\n \n\n \n mask_arr = np.ones((height, width), np.uint8)\n mask_arr[d_arr == ds[key]._FillValue] = 0 \n \n d_arr_float = d_arr.astype(np.float32)\n if has_offset:\n d_arr_float -= offset\n if has_scale:\n d_arr_float /= scale_factor\n # \n if has_valid_range:\n mask_arr[d_arr_float < valid_min] = 0 \n mask_arr[d_arr_float > valid_max] = 0\n\n is_valid = (mask_arr == 1) \n is_invalid = (mask_arr == 0)\n\n out_data_1[f, c1, :, :] = d_arr \n out_data_1[f, c1, is_invalid] = 65535 \n\n c1 += 1\n \n \n \n \n assert c1 == num_channel_1\n assert c2 == num_channel_2_src\n\n \n test_input_data_one = get_data(out_data_1, out_data_2)\n \n \n \n \n with torch.no_grad():\n input = torch.from_numpy(test_input_data_one[np.newaxis, :, :, :]).float().cuda() \n logit = net(input)[target_out_var_index]\n \n #logit = torch.sigmoid(logit).float()\n #logit = torch.sigmoid(logit).float()\n #logit = (torch.logit(torch.clamp(torch.sigmoid(logit), min=0.003, max=0.997), eps=1e-6) + asii_logit_m) / (asii_logit_m*2),\n logit = torch.clamp(torch.sigmoid(logit), min=0, max=1)\n #logit = (torch.sigmoid(logit)>0.5).float()\n\n prediction = logit.cpu().detach().numpy()[0,:,:,:,:]\n np.savez_compressed(os.path.join(out_dir, day_folder_name), prediction=prediction)\n\n num_day_done += 1\n\n print('num_day_done:', num_day_done, '\\t', )\n exit(1)\n"
] |
[
[
"torch.cat",
"torch.load",
"torch.nn.ELU",
"numpy.dtype",
"numpy.concatenate",
"torch.no_grad",
"torch.cuda.manual_seed_all",
"numpy.moveaxis",
"numpy.arange",
"torch.reshape",
"torch.backends.cudnn.version",
"torch.from_numpy",
"torch.nn.GroupNorm",
"numpy.zeros",
"torch.sigmoid",
"torch.nn.ConvTranspose2d",
"torch.nn.init.constant_",
"torch.nn.Conv2d",
"torch.nn.AvgPool2d",
"torch.cuda.device_count",
"numpy.array",
"numpy.sum",
"numpy.random.seed",
"torch.manual_seed",
"numpy.set_printoptions",
"numpy.ones",
"torch.nn.MaxPool2d",
"torch.nn.init.kaiming_normal_"
]
] |
IBM/dse-do-dashboard
|
[
"30348da5414ef03890e6f3b92a36afc77757a021"
] |
[
"test/pharma/supply_chain/pharma/pharmaplotlymanager.py"
] |
[
"from typing import List, Dict, Tuple, Optional\nimport pandas as pd\n\nfrom supply_chain.pharma.pharmadatamanager import PharmaDataManager\nfrom supply_chain.scnfo.scnfoplotlymanager import ScnfoPlotlyManager\n\nimport plotly.express as px\nimport plotly.graph_objs as go\nimport numpy as np\n\nfrom dse_do_dashboard.utils.dash_common_utils import plotly_figure_exception_handler\n\n#######################################################################################\n# Pharma\n#######################################################################################\n\n\nclass PharmaPlotlyManager(ScnfoPlotlyManager):\n def __init__(self, dm:PharmaDataManager):\n super().__init__(dm)\n # self.line_name_category_orders = ['Abbott_Weesp_Line','Abbott_Olst_Granulate_Line',\n # 'Abbott_Olst_Packaging_Line_5','Abbott_Olst_Packaging_Line_6']\n # self.plant_name_category_orders = ['Abbott_Weesp_Plant', 'Abbott_Olst_Plant']\n\n self.line_name_category_orders = ['API_Line','Granulate_Line', 'Packaging_Line_1','Packaging_Line_2']\n self.plant_name_category_orders = ['API_Plant', 'Packaging_Plant']\n \n def describe_demand(self):\n \"\"\"Print summary of demand statistics.\"\"\"\n super().describe_demand()\n df = (self.dm.demand\n .join(self.dm.products[['productGroup']])\n .reset_index())\n print(f\"Num product types = {len(df.productGroup.unique()):,}\")\n\n # def plotly_demand_bars(self):\n # \"\"\"Product demand over time. Colored by productGroup.\"\"\"\n # product_aggregation_column = 'productGroup'\n # df = (self.dm.demandplotly_production_activities_bars\n # .join(self.dm.products[['productGroup']])\n # ).groupby(['timePeriodSeq', product_aggregation_column]).sum()\n # # display(df.head())\n #\n # labels = {'timePeriodSeq': 'Time Period', 'quantity': 'Demand', 'productName': 'Product Name',\n # 'productGroup': 'Product Group'}\n # fig = px.bar(df.reset_index(), x=\"timePeriodSeq\", y=\"quantity\", color=product_aggregation_column,\n # title='Total Product Demand', labels=labels)\n # fig.update_layout(\n # # title={\n # # 'text': f\"Total product demand\",\n # # # 'y': 0.9,\n # # # 'x': 0.5,\n # # 'xanchor': 'center',\n # # 'yanchor': 'top'},\n # legend={'orientation': 'v'},\n # # legend_title_text=product_aggregation_column,\n # )\n #\n # return fig\n\n def gen_color_col(self, catSeries = None):\n '''Converts a series into a set of color codes\n NEEDS TO BE CALLED ON ENTIRE SERIES, NOT SUBSETTED VERSION\n '''\n\n cmap = [\"#004172\", \"#08539d\", \"#2e64c7\", \"#be35a0\", \"#e32433\", \"#eb6007\",\n \"#fb8b00\", \"#c19f00\", \"#5c9c00\", \"#897500\", \"#cb0049\", \"#7746ba\", \"#0080d1\",\n \"#3192d2\", \"#ac6ac0\", \"#e34862\", \"#c57e00\", \"#71a500\", \"#ad6e00\", \"#b82e2e\",]\n\n color_dict = {\n 'Other': \"#7FB3D5\",\n 'API': \"#B03A2E\",\n ' - API': \"#B03A2E\",\n 'Granulate': \"#1F618D\",\n 'Tablet': \"#117A65\",\n 'Package': \"#B7950B\",\n }\n \n if catSeries is not None:\n catSeries = catSeries.dropna() # some NAs get introduced for some reason\n labels = list(catSeries.unique())\n\n if ' - API' not in labels or 'API' not in labels:\n labels.append(' - API')\n \n \n labels = sorted(labels)\n\n cmap_ix = 0\n\n for ix in range(len(labels)):\n if cmap_ix == len(cmap):\n cmap_ix = 0\n else:\n if 'Granulate' in labels[ix]:\n color_dict[labels[ix]] = \"#1F618D\"\n elif 'Tablet' in labels[ix]:\n color_dict[labels[ix]] = \"#117A65\"\n elif 'Package' in labels[ix]:\n color_dict[labels[ix]] = \"#B7950B\"\n elif 'API' in labels[ix]:\n color_dict[labels[ix]] = \"#B03A2E\"\n\n if labels[ix] not in color_dict:\n color_dict[labels[ix]] = cmap[cmap_ix]\n cmap_ix += 1 \n \n return color_dict\n\n def plotly_demand_bars(self, query=None, title='Total Product Demand', view = \"All\"):\n \"\"\"Product demand over time. Colored by productGroup.\"\"\"\n product_aggregation_column = 'productName'\n \n df = (self.dm.demand\n .join(self.dm.products[['productGroup', 'productCountry']])\n )\n\n # df = (self.dm.demand # will return two dfs\n # .join(self.dm.products[['productGroup', 'productCountry']])\n # )\n\n df = df.reset_index() \n\n df['productCountry'] = np.where(pd.isnull(df.productCountry), '', df.productCountry)\n\n df['location_product'] = df.productCountry + \" - \" + df.productName\n\n color_discrete_map = self.gen_color_col(df.location_product)\n\n if query is not None:\n df = df.query(query).copy()\n\n # Set location_product name\n df = df.reset_index()\n\n df = (df\n .groupby(['timePeriodSeq', 'location_product']).sum()\n .sort_values('quantity', ascending=False)\n )\n\n df['demand_proportion'] = df.groupby(['timePeriodSeq'])['quantity'].apply(lambda x: x/x.sum())\n\n df = df.reset_index()\n\n df['new_labels'] = np.where(df['demand_proportion'] < 0.015, 'Other', df['location_product'])\n\n # cmap = px.colors.qualitative.Light24 \n\n new_labels = df['new_labels'].unique()\n\n labels = {'timePeriodSeq': 'Time Period', 'quantity': 'Demand', 'productName': 'Product Name',\n 'productGroup': 'Product Group'}\n\n if view == \"All\":\n color = \"location_product\"\n elif view == \"Compact\":\n color = \"new_labels\"\n\n fig = px.bar(df.reset_index(), x=\"timePeriodSeq\", y=\"quantity\", \n color= color,\n title=title, labels=labels,\n # color_discrete_sequence=px.colors.qualitative.Light24,\n color_discrete_map=color_discrete_map,\n height=600,\n hover_name=\"location_product\",\n # hover_data=[\"quantity\"]\n )\n\n fig.update_layout(\n legend={\n 'title': f\"Total Product Demand\",\n 'bgcolor':'rgba(0,0,0,0)', # transparent background? not sure if this works\n 'x': 1,\n 'orientation': 'v'},\n margin = {'l':80,'t':50},\n hovermode=\"closest\",\n )\n return fig\n\n def plotly_utilization_multi_facet_bars(self):\n \"\"\"Line utilization colored by groupID.\n Shows which groupIDs claim how much capacity on which lines.\n Could be used to analyze why certain lines cannot produce enough of a given product,\n i.e. that they are busy with other products.\"\"\"\n product_aggregation_column = 'productGroup'\n\n df = (self.dm.production_activities[['line_capacity_utilization']]\n .join(self.dm.products[['productGroup']])\n ).groupby(['timePeriodSeq', 'lineName', product_aggregation_column]).sum()\n \n labels = {'timePeriodSeq': 'Time Period', 'var_name': 'Utilization Type', 'lineName': 'Line Name',\n 'line_capacity_utilization': 'Line Capacity Utilization'}\n\n fig = px.bar(df.reset_index(), x=\"lineName\", y=\"line_capacity_utilization\", color=product_aggregation_column,\n title='Line Utilization', labels=labels,\n facet_col=\"timePeriodSeq\",\n )\n # get rid of duplicated X-axis labels\n for axis in fig.layout:\n if type(fig.layout[axis]) == go.layout.XAxis:\n fig.layout[axis].title.text = '' \n\n # fig.for_each_trace(lambda t: t.update(name=t.name.split()[-1]))\n fig.for_each_annotation(lambda a: a.update(text=a.text.split()[-1]))\n \n fig.update_layout(yaxis=dict(tickformat=\"%\", ))\n fig.update_layout(hovermode=\"closest\") # Is supposed to be the default, but in DE we get multiple. Setting 'closest' explicitly is a work-around\n \n fig.update_layout(\n legend=\n dict( # change legend location\n title = \"Product Group\", \n orientation=\"h\",\n yanchor=\"top\",\n y=1.3,\n xanchor=\"right\",\n x=0.95),\n \n # legend_title_text=None # this doesn't align the legend still\n )\n \n return fig\n \n def plotly_excess_utilization_line_time_bars(self):\n \"\"\"Line utilization bar per line over time, clustered by time-period.\n Excess utilization over 100% is clearly colored as red.\n Good initial view of utilization and excess utilization.\n \"\"\"\n df = (self.dm.line_utilization.copy()\n )\n df['Regular Capacity'] = df.utilization.clip(0, 1)\n df['Over Capacity'] = (df.utilization - 1).clip(0)\n df = df[['Regular Capacity', 'Over Capacity']]\n df = (df.stack()\n .rename_axis(index={None: 'var_name'})\n .to_frame(name='Utilization')\n .reset_index()\n )\n\n labels = {'timePeriodSeq': 'Time Period', 'var_name': 'Utilization Type', 'lineName': 'Line Name'}\n fig = px.bar(df.reset_index(), x=\"timePeriodSeq\", y=\"Utilization\", color='var_name', title='Line Utilization',\n labels=labels,\n facet_row=\"lineName\",\n # width = 2000\n color_discrete_map = {'Regular Capacity':'green', 'Over Capacity':'red'},\n height = 800,\n )\n\n fig.update_layout(\n legend=\n dict( # change legend location\n title = \"Utilization Type\", \n orientation=\"h\",\n yanchor=\"top\",\n y=1.05,\n xanchor=\"right\",\n x=0.95),\n )\n fig.update_layout(hovermode=\"closest\") # Is supposed to be the default, but in DE we get multiple. Setting 'closest' explicitly is a work-around\n\n ### This gets rid of the duplicated Y Axis labels caused by the facet_row argument\n for axis in fig.layout:\n if type(fig.layout[axis]) == go.layout.YAxis:\n fig.layout[axis].title.text = ''\n fig.layout[axis].tickformat = '%'\n\n fig.for_each_annotation(lambda a: a.update(text=a.text.split(\"Line Name=\")[-1]))\n fig.for_each_annotation(lambda a: a.update(text=a.text.replace(\"_\", \" \")))\n fig.for_each_annotation(lambda a: a.update(text=a.text.replace(\"Olst\", \"Olst<br>\")))\n fig.for_each_annotation(lambda a: a.update(x = a.x-1.07, textangle = 270))\n\n fig.update_layout(\n legend=\n dict( # change legend location\n title = \"Product Group\",\n orientation=\"v\",\n x=1.05,\n yanchor=\"top\"\n ),\n margin = {'l' : 130, 't':80}\n )\n return fig\n\n def plotly_utilization_line_time_bars(self):\n \"\"\"Line utilization colored by groupID.\n Shows which groupIDs claim how much capacity on which lines.\n Could be used to analyze why certain lines cannot produce enough of a given product,\n i.e. that they are busy with other products.\"\"\"\n product_aggregation_column = 'productGroup'\n df = (self.dm.production_activities[['line_capacity_utilization']]\n .join(self.dm.products[['productGroup']])\n ).groupby(['timePeriodSeq', 'lineName', product_aggregation_column]).sum()\n\n color_discrete_map = self.gen_color_col()\n\n labels = {'timePeriodSeq': 'Time Period', 'var_name': 'Utilization Type', 'lineName': 'Line Name', \n 'line_capacity_utilization':'Line Capacity Utilization'}\n fig = px.bar(df.reset_index(), x=\"timePeriodSeq\", y=\"line_capacity_utilization\", color=product_aggregation_column,\n title='Line Utilization', labels=labels, facet_row = 'lineName',\n color_discrete_map=color_discrete_map,\n category_orders={\n product_aggregation_column: ['API', 'Granulate', 'Tablet', 'Package'],\n # 'lineName': ['Abbott_Weesp_Line', 'Abbott_Olst_Granulate_Line', \n # 'Abbott_Olst_Packaging_Line_5', 'Abbott_Olst_Packaging_Line_6' ],\n 'lineName' : self.line_name_category_orders,\n 'timePeriodSeq': df.reset_index().timePeriodSeq.sort_values().unique() },\n height=800,\n )\n\n fig.update_layout(\n legend=\n dict( # change legend location\n title = \"Product Group\",\n orientation=\"v\",\n yanchor=\"top\",\n y=1.1,\n xanchor=\"right\",\n x=1.05),\n margin = {'l': 130,'t':80}\n )\n fig.update_layout(hovermode=\"closest\") # Is supposed to be the default, but in DE we get multiple. Setting 'closest' explicitly is a work-around\n \n ### This gets rid of the duplicated Y Axis labels caused by the facet_row argument\n for axis in fig.layout:\n if type(fig.layout[axis]) == go.layout.YAxis:\n fig.layout[axis].title.text = ''\n fig.layout[axis].tickformat = '%'\n\n fig.for_each_annotation(lambda a: a.update(x = a.x -1.07, textangle = 270))\n fig.for_each_annotation(lambda a: a.update(text=a.text.split(\"Line Name=\")[-1]))\n fig.for_each_annotation(lambda a: a.update(text=a.text.replace(\"_\", \" \")))\n fig.for_each_annotation(lambda a: a.update(text=a.text.replace(\"Olst\", \"Olst<br>\")))\n return fig\n\n def plotly_line_utilization_heatmap_v2(self):\n \"\"\"\n Trying multiple traces to see if we can get a more clear color difference for utilization > 100%\n Can't get the hover to work with multiple traces\n \"\"\"\n\n # product_aggregation_column = 'groupID'\n df = ((self.dm.production_activities\n )\n )\n\n df = df.pivot_table(values='line_capacity_utilization', index=['lineName'], columns=['timePeriodSeq'], aggfunc=np.sum)\n\n hovertemplate ='<b>Utilization: %{z:.1%}</b><br>Line: %{y} <br>Time Period: %{x} '\n trace = go.Heatmap(z=df.values, x=df.columns, y=df.index, colorscale='Portland', zmin = 0, zmid =1, hovertemplate=hovertemplate) #colorscale='rdbu',\n fig = go.Figure(data=[trace], layout=go.Layout(width=1000, height=600))\n\n return fig\n \n def plotly_demand_fullfilment(self, mode=None):\n \"\"\"Demand, Fulfilled, Unfulfilled, Backlog, BacklogResupply and Inventory over time, grouped by time-period.\n Colored by groupID.\n Very useful graph since it contains all critical variables at the demand locations. Good for explanation.\n \"\"\"\n \n # Collect transportation activities into a destination location.\n # (later we'll do a left join to only select trnasportation into a demand location and ignore all other transportation activities)\n df0 = (self.dm.transportation_activities[['xTransportationSol']]\n .groupby(['productName', 'destinationLocationName', 'timePeriodSeq']).sum()\n .rename_axis(index={'destinationLocationName': 'locationName'})\n .rename(columns={'xTransportationSol':'Transportation'})\n )\n # display(df0.head())\n \n product_aggregation_column = 'productGroup'\n df = (self.dm.demand_inventories[['quantity','xFulfilledDemandSol','xUnfulfilledDemandSol','xBacklogSol','xBacklogResupplySol','xInvSol']]\n .join(self.dm.products[['productGroup']])\n # .join(self.dm.locations)\n .join(df0, how='left')\n ).groupby(['timePeriodSeq', product_aggregation_column]).sum()\n if 'relative_week' in df.columns: # TODO: remove if not relevant anymore\n df = df.drop(columns=['relative_week'])\n # display(df.head())\n df = (df\n # .drop(columns=['relative_week'])\n .rename(\n columns={'quantity': 'Demand', 'xFulfilledDemandSol': 'Fulfilled', 'xUnfulfilledDemandSol': 'Unfulfilled',\n 'xBacklogSol': 'Backlog', 'xBacklogResupplySol': 'Backlog Resupply', 'xInvSol': 'Inventory'})\n )\n \n df = (df.stack()\n .rename_axis(index={None: 'var_name'})\n .to_frame(name='quantity')\n .reset_index()\n )\n\n labels = {'timePeriodSeq': 'Time Period', 'quantity': 'Demand', 'productName': 'Product Name', 'productGroup':'Product Group',\n 'var_name': 'Var'}\n \n if mode is None: #'bar_subplot_by_time'\n fig = px.bar(df, x=\"var_name\", y=\"quantity\", color=product_aggregation_column, title=\"Demand\", labels=labels,\n facet_col=\"timePeriodSeq\",\n category_orders={\n 'var_name': ['Demand', 'Transportation', 'Fulfilled', 'Unfulfilled', 'Backlog', 'Backlog Resupply',\n 'Inventory']},\n height=700\n )\n elif mode == 'multi_line':\n fig = px.line(df, x=\"timePeriodSeq\", y=\"quantity\", color='var_name', title=\"Demand\", labels=labels,\n facet_row=product_aggregation_column,\n height=700\n )\n elif mode == 'animated_horizontal_bars':\n fig = px.bar(df, y=\"var_name\", x=\"quantity\", color=product_aggregation_column, title=\"Demand\", labels=labels,\n # facet_col=\"timePeriodSeq\",\n animation_frame=\"timePeriodSeq\",\n category_orders={\n 'var_name': ['Demand', 'Transportation', 'Fulfilled', 'Unfulfilled', 'Backlog', 'Backlog Resupply',\n 'Inventory']},\n height=700\n )\n elif mode == 'animated_vertical_bars':\n fig = px.bar(df, x=\"timePeriodSeq\", y=\"quantity\", color=product_aggregation_column, title=\"Demand\", labels=labels,\n # facet_col=\"timePeriodSeq\",\n animation_frame=\"timePeriodSeq\",\n facet_row = 'var_name',\n category_orders={\n 'var_name': ['Demand', 'Transportation', 'Fulfilled', 'Unfulfilled', 'Backlog', 'Backlog Resupply',\n 'Inventory']},\n height=700\n )\n\n fig.update_layout(hovermode=\"closest\") # Is supposed to be the default, but in DE we get multiple. Setting 'closest' explicitly is a work-around\n \n return fig\n\n def plotly_demand_fullfilment_multi_plot(self, mode=None, var_names=None):\n \"\"\"Demand, Fulfilled, Unfulfilled, Backlog, BacklogResupply and Inventory over time, grouped by time-period.\n Colored by groupID.\n Very useful graph since it contains all critical variables at the demand locations. Good for explanation.\n \"\"\"\n\n # Collect transportation activities into a destination location.\n # (later we'll do a left join to only select trnasportation into a demand location and ignore all other transportation activities)\n df0 = (self.dm.transportation_activities[['xTransportationSol']]\n .groupby(['productName', 'destinationLocationName', 'timePeriodSeq']).sum()\n .rename_axis(index={'destinationLocationName': 'locationName'})\n .rename(columns={'xTransportationSol':'Transportation'})\n )\n # display(df0.head())\n\n # print(f\"products in demand = {self.dm.demand_inventories.index.get_level_values('productName').unique()}\")\n # print(f\"products = {self.dm.products[['productGroup', 'productCountry']]}\")\n\n product_aggregation_column = 'productName'\n df = (self.dm.demand_inventories[['quantity','xFulfilledDemandSol','xUnfulfilledDemandSol','xBacklogSol','xBacklogResupplySol','xInvSol']]\n .join(self.dm.products[['productGroup', 'productCountry']], how='left')\n # .join(self.dm.locations)\n .join(df0, how='left')\n ).groupby(['timePeriodSeq', product_aggregation_column, \"productCountry\"]).sum()\n # print(f\"products = {df.index.get_level_values('productName').unique()}\")\n\n if 'relative_week' in df.columns: # TODO: remove if not relevant anymore\n df = df.drop(columns=['relative_week'])\n\n df = (df\n .rename(\n columns={'quantity': 'Demand', 'xFulfilledDemandSol': 'Fulfilled', 'xUnfulfilledDemandSol': 'Unfulfilled',\n 'xBacklogSol': 'Backlog', 'xBacklogResupplySol': 'Backlog Resupply', 'xInvSol': 'Inventory'})\n )\n\n df = (df.stack()\n .rename_axis(index={None: 'var_name'})\n .to_frame(name='quantity')\n .reset_index()\n )\n\n var_name_category_order = ['Demand', 'Transportation', 'Fulfilled', 'Unfulfilled', 'Backlog', 'Backlog Resupply', 'Inventory']\n\n num_vars = 6\n if var_names is not None:\n df = df.query(\"var_name in @var_names\").copy()\n num_vars = len(var_names)\n var_name_category_order = var_names\n\n df['location_product'] = df.productCountry + \" - \" + df.productName\n\n color_discrete_map = self.gen_color_col(df['location_product'])\n # print(f\"color_discrete_map={color_discrete_map}\")\n # print(f\"location_product = {df['location_product'].unique()}\")\n\n labels = {'timePeriodSeq': 'Time Period', 'quantity': 'Quantity', 'productName': 'Product Name', 'productGroup':'Product Group',\n 'var_name': 'Var', 'location_product': 'Product Country'}\n\n active_var_names = []\n\n if mode == 'columns':\n fig = px.bar(df, x=\"timePeriodSeq\", y=\"quantity\", \n # color=product_aggregation_column, \n title=\"Fulfillment\", \n labels=labels,\n facet_col=\"var_name\",\n color = \"location_product\",\n color_discrete_map= color_discrete_map,\n category_orders={\n # 'var_name': ['Demand', 'Transportation', 'Fulfilled', 'Unfulfilled', 'Backlog', 'Backlog Resupply',\n # 'Inventory'],\n 'var_name': var_name_category_order\n },\n height=400\n )\n\n for axis in fig.layout:\n if type(fig.layout[axis]) == go.layout.XAxis:\n fig.layout[axis].title.text = ''\n \n \n\n fig.update_layout(\n # keep the original annotations and add a list of new annotations:\n annotations = list(fig.layout.annotations) + \n [go.layout.Annotation(\n x=0.55,\n y=-0.15,\n font=dict(\n size=14\n ),\n showarrow=False,\n text=\"Time Period\",\n textangle=0,\n xref=\"paper\",\n yref=\"paper\"\n )\n ]\n )\n\n\n else: # e.g. None\n fig = px.bar(df, x=\"timePeriodSeq\", y=\"quantity\", \n # color=product_aggregation_column, \n title=\"Fulfillment\", labels=labels,\n facet_row=\"var_name\",\n color = \"location_product\",\n color_discrete_map= color_discrete_map,\n category_orders={\n # 'var_name': ['Demand', 'Transportation', 'Fulfilled', 'Unfulfilled', 'Backlog', 'Backlog Resupply',\n # 'Inventory'],\n 'var_name': var_name_category_order\n },\n height=250*num_vars\n )\n\n fig.for_each_annotation(lambda a: a.update(x = a.x -1.045, textangle = 270))\n\n # get rid of duplicated Y-axis labels\n for axis in fig.layout:\n if type(fig.layout[axis]) == go.layout.YAxis:\n fig.layout[axis].title.text = '' \n\n\n fig.update_layout(hovermode=\"closest\",legend = {'orientation': 'v'}) # Is supposed to be the default, but in DE we get multiple. Setting 'closest' explicitly is a work-around\n fig.for_each_annotation(lambda a: a.update(text=a.text.split(\"Var=\")[-1]))\n\n fig.update_layout(legend = \n {'orientation': 'v',\n 'x': 1,\n },\n margin = {'l': 75}\n )\n\n # fig.layout.yaxis2.update(matches=None)\n # fig.layout.yaxis3.update(matches=None)\n fig.layout.yaxis4.update(matches=None)\n fig.update_yaxes(showticklabels=True, col=4) #, col=2\n\n fig.update_layout(\n margin={'l': 80, 't': 50, 'r': 20, 'b': 60})\n\n return fig\n\n # def plotly_inventory_days_of_supply_line(self, mode:str='line', query=None):\n # \"\"\"Demand inventory, normalized by days-of-supply.\"\"\"\n # num_days = 2 * 365 # For now assume 2 years. TODO: get from number of time-periods and bucket length\n # df1 = (self.dm.demand[['quantity']]\n # .join(self.dm.products['productGroup'])\n # .groupby(['productGroup','productName','locationName']).sum()\n # )\n # df1['demand_per_day'] = df1.quantity / num_days\n # df1 = df1.drop(columns=['quantity'])\n # # display(df1.head())\n\n # df = (self.dm.demand_inventories[['xInvSol']]\n # .join(df1)\n # .reset_index()\n # .set_index(['locationName','productGroup','productName'])\n # .sort_index()\n # )\n # if query is not None:\n # df = df.query(query).copy()\n\n # df['days_of_supply'] = df.xInvSol / df.demand_per_day\n\n # df = df.reset_index()\n # df['product_location'] = df.locationName + \" - \" + df.productName\n\n # labels = {'timePeriodSeq': 'Time Period', 'quantity': 'Inventory', 'productName': 'Product Name',\n # 'productGroup': 'Product Group', 'days_of_supply': 'Days of Supply'}\n # if mode == 'bar':\n # fig = px.bar(df, x=\"timePeriodSeq\", y=\"days_of_supply\",\n # color='product_location',\n # height=600,\n # title='Demand Inventory (days-of-supply)', labels=labels)\n # else:\n # fig = px.line(df, x=\"timePeriodSeq\", y=\"days_of_supply\",\n # color='product_location',\n # height=600,\n # title='Demand Inventory (days-of-supply)', labels=labels)\n # fig.update_layout(\n # hovermode=\"closest\",\n # # title={\n # # 'text': f\"Total product demand\",\n # # # 'y': 0.9,\n # # # 'x': 0.5,\n # # 'xanchor': 'center',\n # # 'yanchor': 'top'},\n # legend={'orientation': 'v'},\n # # legend_title_text=product_aggregation_column,\n # )\n\n # return fig\n\n def plotly_wh_inventory(self, mode:str='bar', query=None):\n \"\"\"Warehouse inventory stacked bar chart by productName.\n TODO: remove products that have no inventory over the whole time-line.\"\"\"\n df = (self.dm.warehouse_inventories[['xInvSol']]\n # .query(\"xInvSol > 0\")\n .join(self.dm.products[['productGroup', 'productCountry']])\n .sort_index()\n .sort_values(['xInvSol'], ascending=False)\n )\n if query is not None:\n df = df.query(query)\n\n df = df.reset_index()\n\n df['productCountry'] = df['productCountry'].fillna(\"\")\n df['location_product'] = df['productCountry'] + \" - \" + df['productName']\n df['location_product'] = df['location_product'].fillna('API')\n\n color_discrete_map = self.gen_color_col(df['location_product'])\n\n labels = {'timePeriodSeq': 'Time Period', 'days_of_supply':'Days of Supply', 'quantity': 'Inventory', 'productName': 'Product Name',\n 'productGroup': 'Product Group', \n 'location_product': 'Product Location',\n \"xInvSol\": \"Inventory\"}\n\n\n if mode == 'bar':\n fig = px.bar(df, x=\"timePeriodSeq\", y=\"xInvSol\",\n color='location_product',\n color_discrete_map = color_discrete_map, \n height=600,\n title='Warehouse Inventory', labels=labels)\n elif mode == 'area':\n fig = px.area(df, x=\"timePeriodSeq\", y=\"xInvSol\",\n color='location_product',\n color_discrete_map = color_discrete_map, \n height=600,\n title='Warehouse Inventory', labels=labels)\n else:\n fig = px.line(df, x=\"timePeriodSeq\", y=\"xInvSol\",\n color='location_product',\n color_discrete_map = color_discrete_map, \n height=600,\n title='Warehouse Inventory', labels=labels)\n fig.update_layout(\n hovermode=\"closest\",\n legend={'orientation': 'v',\n # 'yanchor': 'middle',\n 'x': 1.05,\n },\n margin = {'l': 80,'t':80}\n # legend_title_text=product_aggregation_column,\n )\n\n return fig\n\n def plotly_plant_inventory(self, mode:str='bar', query=None):\n \"\"\"Plant inventory stacked bar chart by productName.\n TODO: remove products that have no inventory over the whole time-line.\"\"\"\n df = (self.dm.plant_inventories[['xInvSol']]\n # .query(\"xInvSol > 0\") # Doesn't work well: will reduce the number of entries in the horizon\n .join(self.dm.products[['productGroup', 'productCountry']])\n .sort_index()\n .sort_values(['xInvSol'], ascending=False)\n )\n if query is not None:\n df = df.query(query)\n\n df = df.reset_index()\n\n # df = df[df.xInvSol > 0]\n\n df.productCountry = df['productCountry'].fillna(\"\")\n\n df['location_product'] = df['productCountry'] + \" - \" + df['productName']\n\n # df['location_product'] = df['location_product'].fillna('API')\n\n color_discrete_map = self.gen_color_col(df['location_product'])\n\n labels = {'timePeriodSeq': 'Time Period', 'days_of_supply':'Days of Supply', 'quantity': 'Inventory', 'productName': 'Product Name',\n 'productGroup': 'Product Group', \n 'location_product': 'Product Location'}\n\n category_orders = {\n # 'locationName': ['Abbott_Weesp_Plant', 'Abbott_Olst_Plant'],\n 'locationName': self.plant_name_category_orders\n }\n\n if mode == 'bar':\n fig = px.bar(df, x=\"timePeriodSeq\", y=\"xInvSol\",\n facet_row='locationName',\n color='location_product',\n color_discrete_map = color_discrete_map, \n category_orders=category_orders,\n height=600,\n title='Plant Inventory', labels=labels)\n fig.for_each_annotation(lambda a: a.update(x = a.x-1.04, textangle = 270))\n elif mode == 'area':\n fig = px.area(df, x=\"timePeriodSeq\", y=\"xInvSol\",\n facet_row='locationName',\n color='location_product',\n # color='productName',\n color_discrete_map = color_discrete_map, \n category_orders=category_orders,\n height=600,\n title='Plant Inventory', labels=labels)\n fig.for_each_annotation(lambda a: a.update(x = a.x-1.08, textangle = 270))\n else:\n fig = px.line(df, x=\"timePeriodSeq\", y=\"xInvSol\",\n color='location_product',\n color_discrete_map = color_discrete_map, \n category_orders=category_orders,\n height=600,\n title='Plant Inventory', labels=labels)\n\n fig.update_layout(\n hovermode=\"closest\",\n legend={'orientation': 'v',\n 'x': 1.05,},\n margin = {'l': 80, 't':80}\n )\n\n for axis in fig.layout:\n if type(fig.layout[axis]) == go.layout.YAxis:\n fig.layout[axis].title.text = '' \n\n fig.for_each_annotation(lambda a: a.update(text=a.text.split(\"locationName=\")[-1]))\n fig.for_each_annotation(lambda a: a.update(text=a.text.replace(\"_\", \" \")))\n return fig\n\n def plotly_demand_inventory(self, mode:str='bar', query=None):\n \"\"\"Plant inventory stacked bar chart by productName.\n TODO: remove products that have no inventory over the whole time-line.\"\"\"\n df = (self.dm.demand_inventories[['xInvSol']]\n # .query(\"xInvSol > 0\") # Doesn't work well: will reduce the number of entries in the horizon\n .join(self.dm.products[['productGroup', 'productCountry']])\n .sort_index()\n .sort_values(['xInvSol'], ascending=False)\n )\n if query is not None:\n df = df.query(query)\n\n df = df.reset_index()\n df['productCountry'] = df['productCountry'].fillna('')\n df['location_product'] = df.productCountry + \" - \" + df.productName\n\n\n color_discrete_map = self.gen_color_col(df['location_product'])\n\n labels = {'timePeriodSeq': 'Time Period', 'days_of_supply':'Days of Supply', 'quantity': 'Inventory', 'productName': 'Product Name',\n 'productGroup': 'Product Group', 'location_product': 'Product Location', 'xInvSol': 'Inventory'}\n \n if mode == 'bar':\n fig = px.bar(df, x=\"timePeriodSeq\", y=\"xInvSol\",\n color_discrete_map=color_discrete_map,\n color='location_product',\n height=600,\n title='Demand Inventory', labels=labels)\n else:\n fig = px.line(df, x=\"timePeriodSeq\", y=\"xInvSol\",\n color_discrete_map=color_discrete_map,\n color='location_product',\n height=600,\n title='Demand Inventory', labels=labels)\n fig.update_layout(\n hovermode=\"closest\",\n legend={'orientation': 'v',\n 'x': 1.05},\n margin={'l':80,'t':80},\n # legend_title_text=product_aggregation_column,\n )\n\n return fig\n\n def plotly_line_product_capacity_heatmap(self):\n \"\"\"Heatmap of capacity as line vs product. Good insight on line specialization/recipe-properties.\n Input tables: ['RecipeProperties', 'Line', 'Product']\n Output tables: []\n \"\"\"\n df = (self.dm.recipe_properties[['capacity']]\n .join(self.dm.lines)\n .join(self.dm.products[['productGroup']])\n # .join(self.dm.plants.rename(columns={'locationDescr':'plantDescr'}), on='plantName')\n # .join(self.dm.locations, on='locationName')\n ) # .groupby(['lineName','productType']).max()\n df = df.reset_index()\n # display(df.head())\n # df = df.pivot_table(values='capacity', index=['lineDescr'], columns=['productType'], aggfunc=np.max)\n df = df.pivot_table(values='capacity', index=['lineName'], columns=['productGroup'], aggfunc=np.max)\n\n df = df.reset_index()\n\n cols = [\"API\", \"Granulate\", \"Tablet\", \"Package\"]\n df= df[cols]\n\n labels = {'lineName': 'Line', 'productGroup': 'Product Group', 'productName': 'Product Name'}\n labels = dict(x=\"Product Group\", y=\"Line\", color=\"Capacity\")\n \n # labels = dict(x=[\"1\",\"2\",\"3\",\"4\"], y=\"Line\", color=\"Capacity\")\n\n fig = px.imshow(df, labels=labels, width=1000,\n color_continuous_scale='YlOrRd',\n # labels = {\n # 'x':[\"1\",\"2\",\"3\",\"4\"]\n # },\n # y = [\"Abbott Olst<br>Granulate Line\", \"Abbott Olst<br>Packaging Line 5\", \"Abbott Olst<br>Packaging Line 6\", \"Abbott<br>Weesp Line\"],\n y = [\"Granulate Line\", \"Packaging Line 1\", \"Packaging Line 2\", \"API Line\"],\n # y = [\"API Line\", \"Granulate Line\", \"Packaging Line 1\", \"Packaging Line 2\"],\n # x = [\"API\", \"Granulate\", \"Tablet\", \"Package\"],\n # template=\"ggplot2\",\n )\n\n # for i, label in enumerate(['orignal', 'clean', '3', '4']):\n # fig.layout.annotations[i]['text'] = label\n\n # fig.update_xaxes(showticklabels=False).update_yaxes(showticklabels=False)\n\n\n fig.update_layout(\n hovermode=\"closest\",\n title={\n 'text': \"Maximum Line Capacity by Product Type\",\n # 'y': 0.92,\n 'x': 0.5,\n 'xanchor': 'center',\n 'yanchor': 'top'},\n margin = {'l': 60,'t':80,'b':60})\n\n return fig\n\n def plotly_line_package_capacity_heatmap(self):\n \"\"\"Heatmap of capacity as line vs product. Good insight on line specialization/recipe-properties.\n Input tables: ['RecipeProperties', 'Line', 'Product']\n Output tables: []\n \"\"\"\n df = (self.dm.recipe_properties[['capacity']]\n .join(self.dm.lines)\n .join(self.dm.products[['productGroup', 'productCountry']])\n # .join(self.dm.plants.rename(columns={'locationDescr':'plantDescr'}), on='plantName')\n # .join(self.dm.locations, on='locationName')\n .query(\"productGroup == 'Package'\")\n ) # .groupby(['lineName','productType']).max()\n df = df.reset_index()\n\n df.productName = df.productName.astype(str)\n\n df['location_product'] = df['productCountry'] + ' - ' + df['productName']\n df['location_product'] = df['location_product'].fillna('API')\n\n # df = df.pivot_table(values='capacity', index=['lineDescr'], columns=['productType'], aggfunc=np.max)\n df = df.pivot_table(values='capacity', index= ['lineName'], \n columns=['location_product'] , aggfunc=np.max)\n\n labels = {'lineName': 'Line', 'productGroup': 'Product Group', 'productName': 'Product Name',\n }\n labels = dict(x=\"Line\", y=\"Product\" , color=\"Max Capacity\")\n fig = px.imshow(df, \n aspect = 'auto',\n labels=labels,\n # height = 800,\n # width=1000,\n color_continuous_scale='YlOrRd',\n # y = [\"Abbott Olst<br>Packaging Line 5\", \"Abbott Olst<br>Packaging Line 6\"],\n # y = [\"Packaging Line 1\", \"Packaging Line 2\"],\n )\n\n fig.update_layout(\n title={\n 'text': \"Maximum Packaging Line Capacity by Product\",\n # 'y': 0.92,\n 'x': 0.5,\n 'xanchor': 'center',\n 'yanchor': 'top'},\n margin = {'l': 140,'t':40,'b':100})\n\n fig.update_xaxes(tickfont={'size':11})\n\n\n return fig\n\n def plotly_time_product_group_capacity_heatmap(self):\n \"\"\"Heatmap of capacity over time.\n Good to detect and time-variation in capacity.\n Input tables: ['RecipeProperties', 'Line', 'Product']\n Output tables: []\n \"\"\"\n\n df = (self.dm.recipe_properties[['capacity']]\n .join(self.dm.lines)\n .join(self.dm.products[['productGroup']]))\n df = df.reset_index()\n\n \n cols = [\"API\", \"Granulate\", \"Tablet\", \"Package\"]\n # df= df[cols]\n\n df = df.pivot_table(values='capacity', index=['productGroup'], columns=['timePeriodSeq'], aggfunc=np.max)\n\n df= df.reindex(cols)\n # print(df.index)\n \n labels = {'lineName': 'Line', 'productGroup': 'Product Group', 'productName': 'Product Name'}\n labels = dict(x=\"Time Period\", y=\"Product Group\", color=\"Capacity\")\n fig = px.imshow(df, labels=labels,\n color_continuous_scale='YlOrRd',\n # y = [\"API\", \"Granulate\", \"Tablet\", \"Package\"]\n )\n fig.update_layout(\n title={\n 'text': \"Maximum Line Capacity by Product Group and Time Period\",\n 'y': 0.95,\n 'x': 0.5,\n 'xanchor': 'center',\n 'yanchor': 'top'},\n margin = {'l': 90,'t':80,'b':60})\n\n return fig\n\n def plotly_time_package_capacity_heatmap(self):\n \"\"\"Heatmap of capacity over time.\n Good to detect and time-variation in capacity.\n Input tables: ['RecipeProperties', 'Line', 'Product']\n Output tables: []\n \"\"\"\n\n df = (self.dm.recipe_properties[['capacity']]\n .join(self.dm.lines)\n .join(self.dm.products[['productGroup']]))\n df = df.reset_index()\n df = df.query(\"productGroup == 'Package'\")\n # display(df.head())\n df = df.pivot_table(values='capacity', index=['productName'], columns=['timePeriodSeq'], aggfunc=np.max)\n\n labels = {'lineName': 'Line', 'productGroup': 'Product Group', 'productName': 'Product Name'}\n labels = dict(x=\"Time Period\", y=\"Product Name\", color=\"Capacity\")\n fig = px.imshow(df, labels=labels,\n # color_discrete_sequence=px.colors.qualitative.G10 # Doesn't work!\n # color_continuous_scale='Turbo',\n # color_continuous_scale='YlOrBr',\n color_continuous_scale='YlOrRd',\n height = 1000,\n )\n fig.update_layout(\n title={\n 'text': \"Maximum Line Capacity by Product and Time Period\",\n# 'y': 0.95,\n 'x': 0.5,\n 'xanchor': 'center',\n 'yanchor': 'top'},\n margin = {'l': 90,'t':80,'b':60})\n\n return fig\n\n # def plotly_time_product_capacity_bars(self):\n # \"\"\"Heatmap of capacity over time.\n # Good to detect and time-variation in capacity.\n # Input tables: ['RecipeProperties', 'Line', 'Product']\n # Output tables: []\n # \"\"\"\n # df = (self.dm.recipe_properties[['capacity']]\n # .join(self.dm.lines)\n # .join(self.dm.products[['productGroup']]))\n # # display(df.head())\n\n # df = df[['capacity','productGroup']].groupby(['lineName','timePeriodSeq','productName']).max()\n # # display(df.head())\n\n # labels = {'lineName': 'Line', 'productGroup': 'Product Group', 'productName': 'Product Name', 'timePeriodSeq':'Time Period', 'capacity':'Capacity'}\n # # labels = dict(x=\"Time Period\", y=\"Product Group\", color=\"Capacity\")\n # fig = px.bar(df.reset_index(), x='timePeriodSeq', y='capacity', color='productName',labels=labels,\n # facet_col='productGroup',\n # category_orders={\n # \"productGroup\": [\"API\", \"Granulate\", \"Tablet\", \"Package\"]\n # },\n \n # # facet_row = 'lineName',\n # )\n\n # fig.update_layout(\n # hovermode=\"closest\",\n # title={\n # 'text': \"Maximum Line Capacity by Product and Time Period\",\n # 'y': 0.95,\n # 'x': 0.5,\n # 'xanchor': 'center',\n # 'yanchor': 'top'})\n\n # fig.update_layout(legend=dict(\n # yanchor=\"top\",\n # y=0.99,\n # xanchor=\"right\",\n # x=1.15,\n # orientation=\"v\"\n # ))\n # fig.for_each_annotation(lambda a: a.update(text=a.text.split(\"=\")[-1]))\n\n # return fig\n\n def plotly_time_product_group_capacity_bars(self):\n \"\"\"Heatmap of capacity over time.\n Good to detect and time-variation in capacity.\n Input tables: ['RecipeProperties', 'Line', 'Product']\n Output tables: []\n \"\"\"\n df = (self.dm.recipe_properties[['capacity']]\n .join(self.dm.lines)\n .join(self.dm.products[['productGroup']]))\n # display(df.head())\n\n df = df[['capacity','productGroup']].groupby(['lineName','timePeriodSeq','productGroup']).max()\n # display(df.head())\n\n color_discrete_map = self.gen_color_col()\n\n labels = {'lineName': 'Line', 'productGroup': 'Product Group', 'productName': 'Product Name', 'timePeriodSeq':'Time Period', 'capacity':'Capacity'}\n # labels = dict(x=\"Time Period\", y=\"Product Group\", color=\"Capacity\")\n fig = px.bar(df.reset_index(), x='timePeriodSeq', y='capacity', color='productGroup',labels=labels,\n facet_col='productGroup',\n category_orders={\n \"productGroup\": [\"API\", \"Granulate\", \"Tablet\", \"Package\"]\n },\n color_discrete_map= color_discrete_map\n )\n\n fig.update_layout(\n hovermode=\"closest\",\n title={\n 'text': \"Maximum Line Capacity by Product Group and Time Period\",\n 'y': 0.95,\n 'x': 0.5,\n 'xanchor': 'center',\n 'yanchor': 'top'}\n )\n\n fig.update_layout(\n legend=dict(\n yanchor=\"top\",\n y=0.99,\n xanchor=\"right\",\n x=1.15,\n orientation=\"v\"\n ),\n margin = {'l': 60,'t':80,'b':60},\n )\n fig.for_each_annotation(lambda a: a.update(text=a.text.split(\"=\")[-1]))\n\n for axis in fig.layout:\n if type(fig.layout[axis]) == go.layout.XAxis:\n fig.layout[axis].title.text = '' \n\n return fig\n\n\n\n def plotly_demand_inventory_bar_subplot_by_time(self):\n \"\"\"Demand, Fulfilled, Unfulfilled, Backlog, BacklogResupply and Inventory over time, grouped by time-period.\n Colored by groupID.\n Very useful graph since it contains all critical variables at the demand locations. Good for explanation.\n \"\"\"\n # product_aggregation_column = 'groupID'\n # df1 = (self.dm.demand_inventories\n # .join(self.dm.products[['productType', 'subgroupID', 'groupID']])\n # # .join(self.dm.locations)\n # ).groupby(['timePeriodSeq', product_aggregation_column]).sum()\n # if 'relative_week' in df1.columns: # TODO: remove if not relevant anymore\n # df1 = df1.drop(columns=['relative_week'])\n # df1 = (df1\n # # .drop(columns=['relative_week'])\n # .rename(\n # columns={'quantity': 'Demand', 'xFulfilledDemandSol': 'Fulfilled', 'xUnfulfilledDemandSol': 'Unfulfilled',\n # 'xBacklogSol': 'Backlog', 'xBacklogResupplySol': 'Backlog Resupply', 'xDemandInvSol': 'Inventory'})\n # )\n # df1 = (df1.stack()\n # .rename_axis(index={None: 'var_name'})\n # .to_frame(name='quantity')\n # .reset_index()\n # )\n\n # # Inflows from plants:\n # df2 = (self.dm.plant_to_demand_transportation[['xTransportationSol']]\n # .join(self.dm.products[['productType', 'subgroupID', 'groupID']])\n # .groupby(['timePeriodSeq', product_aggregation_column]).sum()\n # .rename(columns={'xTransportationSol': 'Production'})\n # )\n # df2 = (df2.stack()\n # .rename_axis(index={None: 'var_name'})\n # .to_frame(name='quantity')\n # .reset_index()\n # )\n\n # df = pd.concat([df1, df2])\n\n # # print(df.head())\n\n # labels = {'timePeriodSeq': 'Time Period', 'quantity': 'Demand', 'productName': 'Product Name',\n # 'var_name': 'Var'}\n # fig = px.bar(df, x=\"var_name\", y=\"quantity\", color=product_aggregation_column, title=\"Demand\", labels=labels,\n # facet_col=\"timePeriodSeq\",\n # category_orders={\n # 'var_name': ['Demand', 'Production', 'Fulfilled', 'Unfulfilled', 'Backlog', 'Backlog Resupply',\n # 'Inventory']},\n # height=700\n # )\n # fig.update_layout(hovermode=\"closest\") # Is supposed to be the default, but in DE we get multiple. Setting 'closest' explicitly is a work-around\n # return fig\n\n product_aggregation_column = 'groupID'\n df1 = (self.dm.demand_inventories\n .join(self.dm.products[['productType', 'subgroupID', 'groupID']])\n # .join(self.locations)\n ).groupby(['timePeriodSeq', product_aggregation_column]).sum()\n if 'relative_week' in df1.columns: # TODO: remove if not relevant anymore\n df1 = df1.drop(columns=['relative_week'])\n df1 = (df1\n # .drop(columns=['relative_week'])\n .rename(\n columns={'quantity': 'Demand', 'xFulfilledDemandSol': 'Fulfilled', 'xUnfulfilledDemandSol': 'Unfulfilled',\n 'xBacklogSol': 'Backlog', 'xBacklogResupplySol': 'Backlog Resupply', 'xDemandInvSol': 'Inventory'})\n )\n df1 = (df1.stack()\n .rename_axis(index={None: 'var_name'})\n .to_frame(name='quantity')\n .reset_index()\n )\n\n # Inflows from plants:\n df2 = (self.dm.plant_to_demand_transportation[['xTransportationSol']]\n .join(self.dm.products[['productType', 'subgroupID', 'groupID']])\n .groupby(['timePeriodSeq', product_aggregation_column]).sum()\n .rename(columns={'xTransportationSol': 'Production'})\n )\n df2 = (df2.stack()\n .rename_axis(index={None: 'var_name'})\n .to_frame(name='quantity')\n .reset_index()\n )\n\n df = pd.concat([df1, df2])\n\n labels = {'timePeriodSeq': 'Time Period', 'quantity': 'Demand', 'productName': 'Product Name',\n 'var_name': 'Var'}\n\n import plotly.graph_objects as go\n\n fig = go.Figure()\n\n fig.update_layout(\n template=\"simple_white\",\n xaxis=dict(title_text=\"Time\"),\n yaxis=dict(title_text=\"Quantity\"),\n barmode=\"stack\",\n )\n\n colors = [\"#6495ED\", \"#FFBF00\", \"#FF7F50\", \"#DE3163\", \"#9FE2BF\"]\n\n for p, c in zip(df.groupID.unique(), colors):\n plot_df = df[df.groupID == p]\n fig.add_trace(\n go.Bar(x=[plot_df.timePeriodSeq, plot_df.var_name], y=plot_df.quantity, name=p, marker_color=c),\n )\n\n fig.update_xaxes(\n rangeslider_visible=True,\n rangeselector=dict(\n buttons=list([\n dict(count=1, label=\"1m\", step=\"month\", stepmode=\"backward\"),\n dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"),\n dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"),\n dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"),\n dict(step=\"all\")\n ])\n )\n )\n\n fig.update_layout(hovermode=\"closest\") # Is supposed to be the default, but in DE we get multiple. Setting 'closest' explicitly is a work-around\n return fig\n\n #######################################################################################\n # Inventory\n #######################################################################################\n def plotly_inventory_days_of_supply_line(self, mode:str='line', query=None):\n \"\"\"Demand inventory, normalized by days-of-supply.\n Args:\n mode (str): line (default) or bar. Bar will result in a stacked bar.\n\n Input tables: ['Demand', 'Product']\n Output tables: ['DemandInventory]\n \"\"\"\n # num_days = 2 * 365 # For now assume 2 years. TODO: get from number of time-periods and bucket length\n num_days = len(self.dm.demand.index.unique(level='timePeriodSeq')) * 30\n df1 = (self.dm.demand[['quantity']]\n .join(self.dm.products['productGroup'])\n .groupby(['productGroup','productName','locationName']).sum()\n )\n df1['demand_per_day'] = df1.quantity / num_days\n\n df1 = df1.drop(columns=['quantity'])\n\n temp = self.dm.demand_inventories[['xInvSol']].reset_index()\n\n temp = temp[temp.locationName == 'PERU']\n\n df = (self.dm.demand_inventories[['xInvSol']]\n .join(df1)\n .reset_index()\n .set_index(['locationName','productGroup','productName'])\n .sort_index()\n )\n if query is not None:\n df = df.query(query).copy()\n\n df['days_of_supply'] = df.xInvSol / df.demand_per_day\n\n tdf = df.reset_index()\n tdf = tdf[tdf.locationName == 'PERU']\n\n df = df.reset_index()\n\n df['location_product'] = df.locationName + \" - \" + df.productName\n\n color_discrete_map = self.gen_color_col(df['location_product'])\n\n labels = {'timePeriodSeq': 'Time Period', 'quantity': 'Inventory', 'productName': 'Product Name',\n 'productGroup': 'Product Group', \"days_of_supply\": \"Days of Supply\", 'days_of_supply_smoothed': 'Days of Supply'}\n\n df['days_of_supply'] = df['days_of_supply'].clip(upper = 100)\n\n df = df.sort_values('timePeriodSeq')\n\n df['days_of_supply_smoothed'] = df['days_of_supply'].rolling(window=5).mean()\n\n if mode == 'bar':\n fig = px.bar(df, x=\"timePeriodSeq\", y=\"days_of_supply\",\n color='location_product',\n color_discrete_map=color_discrete_map,\n height=600,\n title='Demand Inventory (days-of-supply)', labels=labels)\n else:\n fig = px.line(df, x=\"timePeriodSeq\", y=\"days_of_supply\",\n color='location_product',\n color_discrete_map=color_discrete_map,\n height=600,\n title='Demand Inventory (days-of-supply)', labels=labels)\n fig.update_layout(\n hovermode=\"closest\",\n legend={'orientation': 'v',\n \"title\": 'Product Location',\n 'x': 1.05},\n margin={'l':80,'t':60, 'r':0},\n )\n\n return fig\n\n def plotly_inventory_days_of_supply_slack_line(self, mode:str='line', query=None):\n \"\"\"Demand inventory, days-of-supply slack.\n Args:\n mode (str): line (default) or bar. Bar will result in a stacked bar.\n\n Input tables: ['Demand', 'Product']\n Output tables: ['DemandInventory]\n \"\"\"\n # num_days = 2 * 365 # For now assume 2 years. TODO: get from number of time-periods and bucket length\n num_days = len(self.dm.demand.index.unique(level='timePeriodSeq')) * 30\n df1 = (self.dm.demand[['quantity']]\n .join(self.dm.products['productGroup'])\n .groupby(['productGroup','productName','locationName']).sum()\n )\n df1['demand_per_day'] = df1.quantity / num_days\n df1 = df1.drop(columns=['quantity'])\n\n df = (self.dm.demand_inventories[['xDOSSlackSol']]\n .join(df1)\n .reset_index()\n .set_index(['locationName','productGroup','productName'])\n .sort_index()\n )\n if query is not None:\n df = df.query(query).copy()\n\n df['dosSlack'] = df.xDOSSlackSol / df.demand_per_day\n\n df = df.reset_index()\n\n df['location_product'] = df.locationName + \" - \" + df.productName\n\n color_discrete_map = self.gen_color_col(df['location_product'])\n\n labels = {'timePeriodSeq': 'Time Period', 'quantity': 'Inventory', 'productName': 'Product Name',\n 'productGroup': 'Product Group', \"days_of_supply\": \"Days of Supply\"}\n\n df['dosSlack'] = df['dosSlack'].clip(upper = 100)\n\n if mode == 'bar':\n fig = px.bar(df, x=\"timePeriodSeq\", y=\"dosSlack\",\n color='location_product',\n color_discrete_map=color_discrete_map,\n height=600,\n title='Demand Inventory Slack (days-of-supply)', labels=labels)\n else:\n fig = px.line(df, x=\"timePeriodSeq\", y=\"dosSlack\",\n color='location_product',\n color_discrete_map=color_discrete_map,\n height=600,\n title='Demand Inventory Slack (days-of-supply)', labels=labels)\n\n fig.update_layout(\n hovermode=\"closest\",\n legend={'orientation': 'v',\n \"title\": 'Product Location',\n 'x': 1.05},\n margin={'l': 80, 't': 60, 'r': 0},\n )\n\n return fig\n\n def plotly_wh_inventory_days_of_supply_line(self, mode:str='line', query=None):\n \"\"\"Warehouse inventory, normalized by days-of-supply.\"\"\"\n # num_days = 2 * 365 # For now assume 2 years. TODO: get from number of time-periods and bucket length\n num_days = len(self.dm.demand.index.unique(level='timePeriodSeq')) * 30\n df1 = (self.dm.demand[['quantity']]\n .join(self.dm.products[['productGroup', 'productCountry']])\n .groupby(['productGroup','productName', 'productCountry']).sum()\n )\n\n df1['demand_per_day'] = df1.quantity / num_days\n df1 = df1.drop(columns=['quantity'])\n\n df = (self.dm.warehouse_inventories[['xInvSol']]\n .join(df1)\n .reset_index()\n .set_index(['locationName','productGroup','productName', 'productCountry'])\n .sort_index()\n )\n if query is not None:\n df = df.query(query).copy()\n\n df['days_of_supply'] = (df.xInvSol / df.demand_per_day)\n\n df = df.reset_index()\n\n df.productCountry = df.productCountry.fillna(\"\")\n\n df['location_product'] = df.productCountry + \" - \" + df.productName\n\n df.days_of_supply = df.days_of_supply.clip(upper = 100)\n\n color_discrete_map = self.gen_color_col(df['location_product'])\n\n labels = {'timePeriodSeq': 'Time Period', 'days_of_supply':'Days of Supply', 'quantity': 'Inventory', 'productName': 'Product Name',\n 'productGroup': 'Product Group', 'location_product': 'Product Location', 'xInvSol': 'Inventory'}\n\n if mode == 'bar':\n fig = px.bar(df, x=\"timePeriodSeq\", y=\"days_of_supply\",\n color='location_product',\n color_discrete_map=color_discrete_map,\n height=600,\n title='Warehouse Inventory (days-of-supply)', labels=labels)\n elif mode == 'area':\n fig = px.area(df, x=\"timePeriodSeq\", y=\"xInvSol\",\n color='productName',\n color_discrete_map=color_discrete_map,\n height=600,\n title='Warehouse Inventory', labels=labels)\n else:\n fig = px.line(df, x=\"timePeriodSeq\", y=\"days_of_supply\",\n color='location_product',\n color_discrete_map=color_discrete_map,\n height=600,\n title='Warehouse Inventory (days-of-supply)', \n labels=labels)\n\n fig.update_layout(\n hovermode=\"closest\",\n legend={'orientation': 'v',\n \"x\": 1.05},\n margin={'l': 80, 't': 60, 'r': 0},\n )\n\n return fig\n\n def plotly_package_demand_bars(self, query=None):\n \"\"\"Product demand over time. Colored by productGroup.\n\n Input tables: ['Demand', 'Product']\n Output tables: []\n \"\"\"\n df = (self.dm.demand\n .join(self.dm.products[['productGroup']])\n .query(\"productGroup == 'Package'\")\n )\n if query is not None:\n df = df.query(query)\n\n aggregation_column = 'locationName'\n df = df.groupby(['timePeriodSeq', aggregation_column]).sum()\n\n labels = {'timePeriodSeq': 'Time Period', 'quantity': 'Demand', 'productName': 'Product Name',\n 'productGroup': 'Product Group'}\n fig = px.bar(df.reset_index(), x=\"timePeriodSeq\", y=\"quantity\", color=aggregation_column,\n title='Total Package Demand', labels=labels)\n fig.update_layout(\n hovermode=\"closest\",\n legend={'orientation': 'v'},\n )\n\n return fig\n\n def plotly_package_demand_lines(self, query=None):\n \"\"\"Product demand over time. Colored by productGroup.\n Input tables: ['Demand', 'Product']\n Output tables: []\n \"\"\"\n df = (self.dm.demand\n .join(self.dm.products[['productGroup']])\n .query(\"productGroup == 'Package'\")\n )\n if query is not None:\n df = df.query(query)\n\n aggregation_column = 'locationName'\n df = df.groupby(['timePeriodSeq', aggregation_column]).sum()\n\n labels = {'timePeriodSeq': 'Time Period', 'quantity': 'Demand', 'productName': 'Product Name',\n 'productGroup': 'Product Group'}\n\n fig = px.line(df.reset_index(), x=\"timePeriodSeq\", y=\"quantity\", color=aggregation_column,\n title='Total Package Demand', labels=labels)\n\n fig.update_layout(\n hovermode=\"closest\",\n legend={'orientation': 'v'},\n )\n\n return fig\n\n def plotly_demand_fullfilment_scroll(self):\n \"\"\"Demand, Fulfilled, Unfulfilled, Backlog, BacklogResupply and Inventory over time, grouped by time-period.\n Colored by groupID.\n Very useful graph since it contains all critical variables at the demand locations. Good for explanation.\n \"\"\"\n\n # Collect transportation activities into a destination location.\n # (later we'll do a left join to only select trnasportation into a demand location and ignore all other transportation activities)\n df0 = self.dm.transportation_activities\n df0['destinationTimePeriodSeq'] = df0.index.get_level_values('timePeriodSeq') + df0.transitTime\n df0 = (df0[['xTransportationSol', 'destinationTimePeriodSeq']]\n .groupby(['productName', 'destinationLocationName', 'destinationTimePeriodSeq']).sum()\n .rename_axis(index={'destinationLocationName': 'locationName', 'destinationTimePeriodSeq':'timePeriodSeq'})\n .rename(columns={'xTransportationSol':'Transportation'})\n )\n # display(df0.head())\n\n product_aggregation_column = 'productGroup'\n df = (self.dm.demand_inventories[['quantity','xFulfilledDemandSol','xUnfulfilledDemandSol','xBacklogSol','xBacklogResupplySol','xInvSol']]\n .join(self.dm.products[['productGroup']])\n # .join(self.dm.locations)\n .join(df0, how='left')\n ).groupby(['timePeriodSeq', product_aggregation_column]).sum()\n if 'relative_week' in df.columns: # TODO: remove if not relevant anymore\n df = df.drop(columns=['relative_week'])\n # display(df.head())\n df = (df\n # .drop(columns=['relative_week'])\n .rename(\n columns={'quantity': 'Demand', 'xFulfilledDemandSol': 'Fulfilled', 'xUnfulfilledDemandSol': 'Unfulfilled',\n 'xBacklogSol': 'Backlog', 'xBacklogResupplySol': 'Backlog Resupply', 'xInvSol': 'Inventory'})\n )\n # display(df.head())\n df = (df.stack()\n .rename_axis(index={None: 'var_name'})\n .to_frame(name='quantity')\n .reset_index()\n )\n # display(df.head())\n\n\n labels = {'timePeriodSeq': 'Time Period', 'quantity': 'Demand', 'productName': 'Product Name', 'productGroup':'Product Group',\n 'var_name': 'Var'}\n\n fig = go.Figure()\n fig.update_layout(\n template=\"simple_white\",\n xaxis=dict(title_text=\"Time\"),\n yaxis=dict(title_text=\"Quantity\"),\n barmode=\"stack\",\n height=700\n )\n\n colors = self.gen_color_col()\n\n # Default colors:\n for p in df.productGroup.unique():\n plot_df = df[df.productGroup == p]\n fig.add_trace(go.Bar(x=[plot_df.timePeriodSeq, plot_df.var_name], y=plot_df.quantity, name=p, marker_color = colors[p]))\n\n fig.update_xaxes(\n rangeslider_visible=True,\n rangeselector=dict(\n buttons=list([\n dict(count=1, label=\"1m\", step=\"month\", stepmode=\"backward\"),\n dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"),\n dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"),\n dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"),\n dict(step=\"all\")\n ])\n )\n )\n\n fig.update_layout(hovermode=\"closest\") # Is supposed to be the default, but in DE we get multiple. Setting 'closest' explicitly is a work-around\n\n fig.update_layout(\n xaxis = dict(\n tickfont = dict(size=9)))\n\n fig.update_layout(\n margin={'l': 10, 't': 10, 'r': 0, 'b':10})\n\n return fig\n\n def plotly_demand_fullfilment_scroll_product(self):\n \"\"\"Demand, Fulfilled, Unfulfilled, Backlog, BacklogResupply and Inventory over time, grouped by time-period.\n Colored by groupID.\n Very useful graph since it contains all critical variables at the demand locations. Good for explanation.\n \"\"\"\n\n # Collect transportation activities into a destination location.\n # (later we'll do a left join to only select trnasportation into a demand location and ignore all other transportation activities)\n # df0 = (self.dm.transportation_activities[['xTransportationSol']]\n # .groupby(['productName', 'destinationLocationName', 'timePeriodSeq']).sum()\n # .rename_axis(index={'destinationLocationName': 'locationName'})\n # .rename(columns={'xTransportationSol':'Transportation'})\n # )\n df0 = self.dm.transportation_activities\n df0['destinationTimePeriodSeq'] = df0.index.get_level_values('timePeriodSeq') + df0.transitTime\n df0 = (df0[['xTransportationSol', 'destinationTimePeriodSeq']]\n .groupby(['productName', 'destinationLocationName', 'destinationTimePeriodSeq']).sum()\n .rename_axis(index={'destinationLocationName': 'locationName', 'destinationTimePeriodSeq':'timePeriodSeq'})\n .rename(columns={'xTransportationSol':'Transportation'})\n )\n # display(df0.head())\n\n # product_aggregation_column = 'productGroup'\n product_aggregation_column = 'productName'\n df = (self.dm.demand_inventories[['quantity','xFulfilledDemandSol','xUnfulfilledDemandSol','xBacklogSol','xBacklogResupplySol','xInvSol']]\n .join(self.dm.products[['productGroup', 'productCountry']])\n # .join(self.dm.locations)\n .join(df0, how='left')\n ).groupby(['timePeriodSeq', product_aggregation_column, 'productCountry']).sum()\n # print(df.head())\n if 'relative_week' in df.columns: # TODO: remove if not relevant anymore\n df = df.drop(columns=['relative_week'])\n # display(df.head())\n df = (df\n # .drop(columns=['relative_week'])\n .rename(\n columns={'quantity': 'Demand', 'xFulfilledDemandSol': 'Fulfilled', 'xUnfulfilledDemandSol': 'Unfulfilled',\n 'xBacklogSol': 'Backlog', 'xBacklogResupplySol': 'Backlog Resupply', 'xInvSol': 'Inventory'})\n )\n\n df = (df.stack()\n .rename_axis(index={None: 'var_name'})\n .to_frame(name='quantity')\n .reset_index()\n )\n\n labels = {'timePeriodSeq': 'Time Period', 'quantity': 'Demand', 'productName': 'Product Name', 'productGroup':'Product Group',\n 'var_name': 'Var'}\n\n fig = go.Figure()\n fig.update_layout(\n template=\"simple_white\",\n xaxis=dict(title_text=\"Time\"),\n yaxis=dict(title_text=\"Quantity\"),\n barmode=\"stack\",\n height=900,\n # width = 2000\n )\n\n df = df.reset_index()\n df['location_product'] = df['productCountry'] + ' - ' + df['productName']\n df['location_product'] = df['location_product'].fillna('API')\n\n colors = self.gen_color_col(df['location_product'])\n\n # Default colors:\n # for p in df[product_aggregation_column].unique():\n # print(f\"p = {p}\")\n\n # print(df[product_aggregation_column].unique())\n # print(colors)\n\n # Default colors:\n for p in df['location_product'].unique():\n # print(f\"p = {p}\")\n\n plot_df = df[df['location_product'] == p]\n try:\n fig.add_trace(go.Bar(x=[plot_df.timePeriodSeq, plot_df.var_name], y=plot_df.quantity, name=p, \n marker_color = colors[p]\n ))\n except:\n pass\n\n\n fig.update_xaxes(\n rangeslider_visible=True,\n rangeselector=dict(\n buttons=list([\n dict(count=1, label=\"1m\", step=\"month\", stepmode=\"backward\"),\n dict(count=6, label=\"6m\", step=\"month\", stepmode=\"backward\"),\n dict(count=1, label=\"YTD\", step=\"year\", stepmode=\"todate\"),\n dict(count=1, label=\"1y\", step=\"year\", stepmode=\"backward\"),\n dict(step=\"all\")\n ])\n )\n )\n\n fig.update_layout(hovermode=\"closest\") # Is supposed to be the default, but in DE we get multiple. Setting 'closest' explicitly is a work-around\n\n fig.update_layout(\n xaxis = dict(\n tickfont = dict(size=9)),\n legend = {'orientation': 'v', 'x': 1})\n\n fig.update_layout(\n margin={'l': 10, 't': 10, 'r': 0, 'b': 30})\n \n \n return fig\n\n def plotly_production_activities_bars(self, query=None, title='Production'):\n \"\"\"Production activity over time, colored by productGroup.\n Input tables: ['Product', 'Location']\n Output tables: ['ProductionActivity']\n \"\"\"\n product_aggregation_column = 'productGroup'\n product_aggregation_column = 'productName'\n \n df = (self.dm.production_activities\n .join(self.dm.products[['productGroup', 'productCountry']]))\n \n df = df.reset_index()\n\n df.productCountry = df.productCountry.fillna('')\n df['location_product'] = df.productCountry + \" - \" + df.productName\n\n color_discrete_map = self.gen_color_col(df['location_product'])\n \n if query is not None:\n df = df.query(query)\n\n df = (df \n .reset_index()\n .merge(self.dm.locations.reset_index(), on='locationName')\n ).groupby(['timePeriodSeq', product_aggregation_column, 'lineName', 'location_product']).sum()\n\n active_line_name_category_orders = [l for l in self.line_name_category_orders if l in df.index.unique(level='lineName')] # Avoids empty spaces in Plotly chart\n labels = {'timePeriodSeq': 'Time Period', 'xProdSol': 'Production', 'productName': 'Product Name', 'location_product': 'Product Location'}\n category_orders = {\n # 'lineName' : ['Abbott_Weesp_Line','Abbott_Olst_Granulate_Line', 'Abbott_Olst_Packaging_Line_5','Abbott_Olst_Packaging_Line_6'],\n # 'lineName' : self.line_name_category_orders,\n 'lineName' : active_line_name_category_orders,\n # 'timePeriodSeq': df.reset_index().timePeriodSeq.sort_values().unique(),\n 'timePeriodSeq': df.index.unique(level='timePeriodSeq').sort_values()\n }\n \n fig = px.bar(df.reset_index(), x=\"timePeriodSeq\", y=\"xProdSol\", color='location_product',\n color_discrete_map= color_discrete_map,\n title=title, labels=labels,\n facet_row = 'lineName',\n category_orders=category_orders,\n height=800,\n )\n\n fig.update_layout(legend = \n {'orientation': 'v',\n 'x': 1.05,\n }\n )\n \n fig.update_layout(margin = {'l': 85, 't':80})\n\n fig.for_each_annotation(lambda a: a.update(x = a.x-1.04, textangle = 270))\n fig.for_each_annotation(lambda a: a.update(text=a.text.split(\"lineName=\")[-1]))\n fig.for_each_annotation(lambda a: a.update(text=a.text.replace(\"_\", \" \")))\n fig.for_each_annotation(lambda a: a.update(text=a.text.replace(\"Olst\", \"Olst<br>\")))\n\n # get rid of duplicated X-axis labels\n for axis in fig.layout:\n if type(fig.layout[axis]) == go.layout.YAxis:\n fig.layout[axis].title.text = '' \n \n fig.update_xaxes(type='category')\n fig.update_layout(hovermode=\"closest\",legend = {'orientation': 'v'}) # Is supposed to be the default, but in DE we get multiple. Setting 'closest' explicitly is a work-around\n return fig\n\n def plotly_planned_production_activities_bars(self, query=None, title='Production'):\n \"\"\"Production activity over time, colored by productGroup.\n Input tables: ['Product', 'Location']\n Output tables: ['ProductionActivity']\n \"\"\"\n\n product_aggregation_column = 'productName'\n \n df = (self.dm.planned_production_activity\n .join(self.dm.products[['productGroup', 'productCountry']])\n # .sort_index()\n )\n\n\n df = df.reset_index()\n df['productCountry'] = np.where(pd.isnull(df.productCountry), '', df.productCountry)\n df['location_product'] = df.productCountry + \" - \" + df.productName\n\n color_discrete_map = self.gen_color_col(df['location_product'])\n\n if query is not None:\n df = df.query(query)\n\n df = (df \n ).groupby(['timePeriodSeq', product_aggregation_column, 'lineName', 'productCountry', 'location_product']).sum()\n \n active_line_name_category_orders = [l for l in self.line_name_category_orders if l in df.index.unique(level='lineName')] # Avoids empty spaces in Plotly chart\n labels = {'timePeriodSeq': 'Time Period', 'xProdSol': 'Production', 'productName': 'Product Name', \n 'location_product': 'Product Location'}\n\n # df = (df.reset_index())\n\n category_orders = {\n # 'lineName' : ['Abbott_Weesp_Line','Abbott_Olst_Granulate_Line', 'Abbott_Olst_Packaging_Line_5','Abbott_Olst_Packaging_Line_6'],\n # 'lineName' : self.line_name_category_orders,\n 'lineName' : active_line_name_category_orders,\n # 'timePeriodSeq': df.reset_index().timePeriodSeq.sort_values().unique()\n # 'timePeriodSeq': df.timePeriodSeq.sort_values().unique()\n 'timePeriodSeq': df.index.unique(level='timePeriodSeq').sort_values()\n }\n\n fig = px.bar(df.reset_index(), x=\"timePeriodSeq\", y=\"quantity\", color='location_product',\n color_discrete_map=color_discrete_map,\n title=title, labels=labels,\n facet_row = 'lineName',\n category_orders = category_orders,\n height=800,\n )\n\n fig.update_layout(legend = \n {'orientation': 'v',\n 'x': 1.05,\n }\n )\n \n fig.update_layout(margin = {'l': 90,'t':60})\n # fig.for_each_annotation(lambda a: a.update(x = a.x -1., y = a.y-0.15, textangle = 0, \n # font = {'size':16}\n # ))\n\n fig.for_each_annotation(lambda a: a.update(x = a.x-1.055, textangle = 270))\n fig.for_each_annotation(lambda a: a.update(text=a.text.split(\"lineName=\")[-1]))\n\n fig.for_each_annotation(lambda a: a.update(text=a.text.replace(\"_\", \" \")))\n fig.for_each_annotation(lambda a: a.update(text=a.text.replace(\"Olst\", \"Olst<br>\")))\n\n # get rid of duplicated X-axis labels\n for axis in fig.layout:\n if type(fig.layout[axis]) == go.layout.YAxis:\n fig.layout[axis].title.text = '' \n \n fig.update_xaxes(type='category')\n\n fig.update_layout(hovermode=\"closest\",legend = {'orientation': 'v'})\n\n return fig\n\n def plotly_production_slack_bars(self, query=None, title='Production Slack'):\n \"\"\"Production activity slack over time, colored by productName.\n Input tables: ['Product']\n Output tables: ['ProductionActivity']\n \"\"\"\n product_aggregation_column = 'productName'\n \n df = (self.dm.production_activities\n .join(self.dm.products[['productGroup', 'productCountry']]))\n\n df = df.reset_index()\n df['productCountry'] = np.where(pd.isnull(df.productCountry), '', df.productCountry)\n df['location_product'] = df.productCountry + \" - \" + df.productName\n\n color_discrete_map = self.gen_color_col(df['location_product'])\n\n if query is not None:\n df = df.query(query)\n\n df = (df \n .reset_index()\n # .merge(self.dm.locations.reset_index(), on='locationName')\n ).groupby(['timePeriodSeq', product_aggregation_column, 'lineName', 'productCountry', 'location_product']).sum()\n \n labels = {'timePeriodSeq': 'Time Period', 'xProdSol': 'Production', 'productName': 'Product Name', \n 'location_product': 'Product Location'}\n active_line_name_category_orders = [l for l in self.line_name_category_orders if l in df.index.unique(level='lineName')] # Avoids empty spaces in Plotly chart\n \n category_orders = {\n # 'lineName' : ['Abbott_Weesp_Line','Abbott_Olst_Granulate_Line',\n # 'Abbott_Olst_Packaging_Line_5','Abbott_Olst_Packaging_Line_6'],\n # 'lineName' : self.line_name_category_orders,\n 'lineName' : active_line_name_category_orders,\n # 'timePeriodSeq': df.reset_index().timePeriodSeq.sort_values().unique()\n 'timePeriodSeq': df.index.unique(level='timePeriodSeq').sort_values(),\n }\n fig = px.bar(df.reset_index(), x=\"timePeriodSeq\", y=\"xProdSlackSol\", color='location_product',\n color_discrete_map=color_discrete_map,\n title=title, labels=labels,\n facet_row = 'lineName',\n category_orders=category_orders,\n height=800,\n )\n\n fig.update_layout(legend = \n {'orientation': 'v',\n 'x': 1.05,\n }\n )\n \n fig.update_layout(margin = {'l': 85, 't':60})\n\n fig.for_each_annotation(lambda a: a.update(x = a.x-1.05, textangle = 270))\n fig.for_each_annotation(lambda a: a.update(text=a.text.split(\"lineName=\")[-1]))\n\n fig.for_each_annotation(lambda a: a.update(text=a.text.replace(\"_\", \" \")))\n fig.for_each_annotation(lambda a: a.update(text=a.text.replace(\"Olst\", \"Olst<br>\")))\n \n # get rid of duplicated X-axis labels\n for axis in fig.layout:\n if type(fig.layout[axis]) == go.layout.YAxis:\n fig.layout[axis].title.text = '' \n \n fig.update_xaxes(type='category')\n fig.update_layout(hovermode=\"closest\",legend = {'orientation': 'v'})\n\n return fig\n\n def plotly_production_excess_bars(self, query=None, title='Production Plan Difference', mode = None):\n \"\"\"Production activity excess (compared to plan) over time, colored by productName.\n Default mode returns excess as a substraction, percentage returns as percentage\n Input tables: ['Product', 'PlannedproductionActivity']\n Output tables: ['ProductionActivity']\n \"\"\"\n product_aggregation_column = 'productName'\n\n planned_production = (self.dm.planned_production_activity\n .reset_index()\n # .astype({'planId': int})\n # .query(\"planId == 1\") # HACK!!!! Need to filter on planId\n # .reset_index()\n .set_index(['productName','lineName','timePeriodSeq','recipeId'], verify_integrity = True)\n )\n\n df = (self.dm.production_activities\n .join(self.dm.products[['productGroup', 'productCountry']])\n .join(planned_production, how = 'left') \n .rename(columns={'quantity':'plannedProductionQuantity'})\n )\n df.plannedProductionQuantity = df.plannedProductionQuantity.fillna(0)\n\n if mode == 'percentage':\n df['planExcessQuantity'] = ((df.xProdSol - df.plannedProductionQuantity) / df.plannedProductionQuantity)\n\n else:\n df['planExcessQuantity'] = df.xProdSol - df.plannedProductionQuantity\n\n df = df.reset_index()\n df['productCountry'] = np.where(pd.isnull(df.productCountry), '', df.productCountry)\n df['location_product'] = df.productCountry + \" - \" + df.productName\n\n color_discrete_map = self.gen_color_col(df['location_product'])\n\n if query is not None:\n df = df.query(query)\n\n df = (df \n .reset_index()\n ).groupby(['timePeriodSeq', product_aggregation_column, 'lineName', 'productCountry', 'location_product']).sum()\n \n labels = {'timePeriodSeq': 'Time Period', 'xProdSol': 'Production', 'productName': 'Product Name', \n 'location_product': 'Product Location', 'planExcessQuantity':'Plan Difference'}\n active_line_name_category_orders = [l for l in self.line_name_category_orders if l in df.index.unique(level='lineName')] # Avoids empty spaces in Plotly chart\n \n # df = df.reset_index()\n\n category_orders = {\n # 'lineName' : ['Abbott_Weesp_Line','Abbott_Olst_Granulate_Line',\n # 'Abbott_Olst_Packaging_Line_5','Abbott_Olst_Packaging_Line_6'],\n # 'lineName' : self.line_name_category_orders,\n 'lineName' : active_line_name_category_orders,\n # 'timePeriodSeq': [df.timePeriodSeq.sort_values().unique()]\n 'timePeriodSeq': df.index.unique(level='timePeriodSeq').sort_values()\n }\n \n fig = px.bar(df.reset_index(), x=\"timePeriodSeq\", y=\"planExcessQuantity\", color='location_product',\n color_discrete_map=color_discrete_map,\n title=title, labels=labels,\n facet_row = 'lineName',\n category_orders=category_orders,\n height=800,\n )\n\n fig.update_layout(legend = \n {'orientation': 'v',\n 'x': 1.05,\n }\n )\n\n if mode is not None:\n for axis in fig.layout:\n if type(fig.layout[axis]) == go.layout.YAxis:\n fig.layout[axis].title.text = ''\n fig.layout[axis].tickformat = '%'\n \n fig.update_layout(margin = {'l': 85})\n\n fig.for_each_annotation(lambda a: a.update(x = a.x-1.05, textangle = 270))\n fig.for_each_annotation(lambda a: a.update(text=a.text.split(\"lineName=\")[-1]))\n\n fig.for_each_annotation(lambda a: a.update(text=a.text.replace(\"_\", \" \")))\n fig.for_each_annotation(lambda a: a.update(text=a.text.replace(\"Olst\", \"Olst<br>\")))\n\n fig.update_layout(hovermode=\"closest\") # Is supposed to be the default, but in DE we get multiple. Setting 'closest' explicitly is a work-around\n \n # get rid of duplicated X-axis labels\n for axis in fig.layout:\n if type(fig.layout[axis]) == go.layout.YAxis:\n fig.layout[axis].title.text = '' \n \n fig.update_xaxes(type='category')\n fig.update_layout(hovermode=\"closest\",legend = {'orientation': 'v'},\n margin= {'l':85,'t':60})\n\n return fig\n\n def plotly_inventory_flow_sankey_test(self, include_wip=True):\n \"\"\"Sankey diagram of transportation activities.\n See https://stackoverflow.com/questions/50486767/plotly-how-to-draw-a-sankey-diagram-from-a-dataframe\n \"\"\"\n\n aggregation_column = 'productName'\n\n # Collect inventories (location-product):\n\n # for these groupby productGroup instead of productName\n df1 = self.dm.plant_inventories[[]].groupby(['locationName',aggregation_column]).sum().copy()\n df1['type'] = 'plant'\n df2 = self.dm.warehouse_inventories[[]].groupby(['locationName',aggregation_column]).sum().copy()\n df2['type'] = 'warehouse'\n df3 = self.dm.demand_inventories[[]].groupby(['locationName',aggregation_column]).sum().copy()\n df3['type'] = 'demand'\n df4 = pd.DataFrame([{'locationName':'External',aggregation_column:'None', 'type':'external'}]).set_index(['locationName',aggregation_column])\n df5 = self.dm.WIP[[]].groupby(['locationName',aggregation_column]).sum().copy()\n df5 = df5.reset_index()\n df5['locationName'] = df5.locationName + \"_wip\"\n df5 = df5.set_index(['locationName',aggregation_column])\n df5['type'] = 'wip'\n df6 = self.dm.plant_inventories[[]].groupby(['locationName']).sum().copy()\n df6[aggregation_column] = 'None'\n df6 = df6.reset_index().set_index(['locationName',aggregation_column])\n df6['type'] = 'source'\n product_locations = pd.concat([df5, df4, df1, df2, df3, df6]) # should be same dataframes with same keys\n\n product_locations = product_locations.reset_index()\n product_locations = product_locations.merge(self.dm.products[['productGroup']], on = 'productName')\n\n # Create locationName vs id\n inventory_labels_df = (product_locations.reset_index()\n .reset_index().rename(columns={'index': 'id'})\n )\n inventory_labels_df['label'] = inventory_labels_df.locationName + \" - \" +inventory_labels_df['productGroup']\n \n #Collect inventory flows - transportation\n df1 = (self.dm.transportation_activities[['xTransportationSol']].join(self.dm.products[['productGroup']])\n .query(\"xTransportationSol > 0\")\n .groupby(['originLocationName', 'destinationLocationName','shippingMode','productGroup']).sum()\n .rename(columns={'xTransportationSol':'quantity'})\n )\n\n df1 = df1.reset_index()\n \n df1 = (df1.merge(inventory_labels_df[['locationName','productGroup','id']], left_on=['originLocationName','productGroup'], right_on=['locationName','productGroup'])\n .rename(columns={'id': 'source'})\n .drop(columns=['locationName'])\n )\n\n df1 = (df1.merge(inventory_labels_df[['locationName','productGroup','id']], left_on=['destinationLocationName','productGroup'], right_on=['locationName','productGroup'])\n .rename(columns={'id': 'target'})\n .drop(columns=['locationName'])\n )\n df1['label'] = df1.shippingMode + \" - \" + df1['productGroup'] + \" from \" + df1.originLocationName + \" to \" + df1.destinationLocationName \n df1 = df1.drop(columns=['originLocationName','destinationLocationName','shippingMode'])\n df1['color'] = 'rosybrown' \n \n aggregation_column = 'productGroup'\n #Collect inventory flows - Production\n df2 = (self.dm.production_activities[['xProdSol']].join(self.dm.products[['productGroup']])\n .join(self.dm.bom_items[['quantity']].rename(columns={'quantity':'component_bom_quantity'}), how='left')\n .join(self.dm.lines[['plantName']])\n .join(self.dm.plants[['locationName']], on='plantName')\n .query(\"xProdSol > 0\")\n .reset_index()\n )\n\n df2.componentName.fillna('None',inplace=True) # For any product without components\n df2['component_quantity'] = df2.xProdSol * df2.component_bom_quantity\n df2 = (df2\n .drop(columns=['component_bom_quantity','recipeId','timePeriodSeq'])\n .groupby(['componentName', aggregation_column,'lineName','plantName','locationName']).sum()\n .rename(columns={'xProdSol':'quantity'})\n )\n df2 = df2.reset_index()\n \n df2 = (df2.merge(inventory_labels_df[['locationName',aggregation_column,'id','type']], left_on=['locationName',aggregation_column], right_on=['locationName',aggregation_column])\n .rename(columns={'id': 'target'})\n )\n df2 = (df2.merge(inventory_labels_df[['locationName',aggregation_column,'id','type']], left_on=['locationName','componentName'], right_on=['locationName',aggregation_column], suffixes=[None,'_y'])\n .rename(columns={'id': 'source'})\n .drop(columns=[aggregation_column+'_y'])\n )\n df2['label'] = df2.type + \" - \" + df2.componentName + \" to \" + df2[aggregation_column]\n df2 = df2[[aggregation_column, 'quantity', 'source', 'target', 'label']]\n \n df2['color'] = 'olive' \n \n # Collect inventory flows - WIP\n df3 = (self.dm.WIP[['wipQuantity']].join(self.dm.products[['productGroup']])\n .query(\"wipQuantity > 0\")\n .rename(columns={'wipQuantity':'quantity'})\n )\n df3 = df3.reset_index()\n df3['locationNameWip'] = df3.locationName + '_wip'\n # display(df3.head())\n df3 = (df3.merge(inventory_labels_df[['locationName',aggregation_column,'id']], left_on=['locationName',aggregation_column], right_on=['locationName',aggregation_column])\n .rename(columns={'id': 'target'})\n # .drop(columns=['locationName'])\n )\n df3 = (df3.merge(inventory_labels_df[['locationName',aggregation_column,'id']], left_on=['locationNameWip',aggregation_column], right_on=['locationName',aggregation_column], suffixes=[None,'_y'])\n .rename(columns={'id': 'source'})\n .drop(columns=['locationName_y'])\n )\n # display(df3.head())\n df3['label'] = \"wip - \" + df3[aggregation_column] + \" to \" + df3.locationName \n # df1 = df1.drop(columns=['locationNameWip','locationName','shippingMode'])\n # display(df3.head()) \n df3['color'] = 'lightsalmon' \n \n \n if include_wip:\n df = pd.concat([df1, df2, df3])\n else:\n df = pd.concat([df1, df2])\n\n # df = df.merge(self.dm.products[['productGroup']], on = 'productName')\n \n # Set pop-up text\n \n\n # df['color'] = 'aquamarine' \n fig = go.Figure(data=[go.Sankey(\n # valueformat = \".0f\",\n # valuesuffix = \"TWh\",\n # Define nodes\n node=dict(\n pad=15,\n thickness=15,\n line=dict(color=\"black\", width=0.5),\n label=inventory_labels_df.label.array,\n ),\n # Add links\n link=dict(\n source=df.source.array,\n target=df.target.array,\n value=df.quantity.array,\n label=df.label.array,\n color = df.color.array,\n ))])\n\n fig.update_layout(title_text=\"\",\n font_size=10,\n height=1000)\n return fig\n\n def plotly_inventory_flow_sankey(self, include_wip=True):\n \"\"\"Sankey diagram of transportation activities.\n See https://stackoverflow.com/questions/50486767/plotly-how-to-draw-a-sankey-diagram-from-a-dataframe\n \"\"\"\n # Collect inventories (location-product):\n df1 = self.dm.plant_inventories[[]].groupby(['locationName','productName']).sum().copy()\n df1['type'] = 'plant'\n df2 = self.dm.warehouse_inventories[[]].groupby(['locationName','productName']).sum().copy()\n df2['type'] = 'warehouse'\n df3 = self.dm.demand_inventories[[]].groupby(['locationName','productName']).sum().copy()\n df3['type'] = 'demand'\n df4 = pd.DataFrame([{'locationName':'External','productName':'None', 'type':'external'}]).set_index(['locationName','productName'])\n df5 = self.dm.WIP[[]].groupby(['locationName','productName']).sum().copy()\n df5 = df5.reset_index()\n df5['locationName'] = df5.locationName + \"_wip\"\n df5 = df5.set_index(['locationName','productName'])\n df5['type'] = 'wip'\n df6 = self.dm.plant_inventories[[]].groupby(['locationName']).sum().copy()\n df6['productName'] = 'None'\n df6 = df6.reset_index().set_index(['locationName','productName'])\n df6['type'] = 'source'\n product_locations = pd.concat([df5, df4, df1, df2, df3, df6])\n # display(product_locations.head())\n # Create locationName vs id\n inventory_labels_df = (product_locations.reset_index()\n .reset_index().rename(columns={'index': 'id'})\n )\n inventory_labels_df['label'] = inventory_labels_df.locationName + \" - \" +inventory_labels_df.productName\n # display(inventory_labels_df.head())\n \n #Collect inventory flows - transportation\n df1 = (self.dm.transportation_activities[['xTransportationSol']]\n .query(\"xTransportationSol > 0\")\n .groupby(['originLocationName', 'destinationLocationName','shippingMode','productName']).sum()\n .rename(columns={'xTransportationSol':'quantity'})\n )\n df1 = df1.reset_index()\n # display(df1.head())\n df1 = (df1.merge(inventory_labels_df[['locationName','productName','id']], left_on=['originLocationName','productName'], right_on=['locationName','productName'])\n .rename(columns={'id': 'source'})\n .drop(columns=['locationName'])\n )\n # display(df1.head())\n df1 = (df1.merge(inventory_labels_df[['locationName','productName','id']], left_on=['destinationLocationName','productName'], right_on=['locationName','productName'])\n .rename(columns={'id': 'target'})\n .drop(columns=['locationName'])\n )\n df1['label'] = df1.shippingMode + \" - \" + df1.productName + \" from \" + df1.originLocationName + \" to \" + df1.destinationLocationName \n df1 = df1.drop(columns=['originLocationName','destinationLocationName','shippingMode'])\n df1['color'] = 'rosybrown' \n # display(df1.head())\n \n #Collect inventory flows - Production\n df2 = (self.dm.production_activities[['xProdSol']]\n .join(self.dm.bom_items[['quantity']].rename(columns={'quantity':'component_bom_quantity'}), how='left')\n .join(self.dm.lines[['plantName']])\n .join(self.dm.plants[['locationName']], on='plantName')\n .query(\"xProdSol > 0\")\n .reset_index()\n # .groupby(['locationName', 'plantName','lineName', 'productName']).sum()\n )\n df2.componentName.fillna('None',inplace=True) # For any product without components\n df2['component_quantity'] = df2.xProdSol * df2.component_bom_quantity\n df2 = (df2\n .drop(columns=['component_bom_quantity','recipeId','timePeriodSeq'])\n .groupby(['componentName', 'productName','lineName','plantName','locationName']).sum()\n .rename(columns={'xProdSol':'quantity'})\n )\n df2 = df2.reset_index()\n # display(df2.head())\n df2 = (df2.merge(inventory_labels_df[['locationName','productName','id','type']], left_on=['locationName','productName'], right_on=['locationName','productName'])\n .rename(columns={'id': 'target'})\n )\n df2 = (df2.merge(inventory_labels_df[['locationName','productName','id','type']], left_on=['locationName','componentName'], right_on=['locationName','productName'], suffixes=[None,'_y'])\n .rename(columns={'id': 'source'})\n .drop(columns=['productName_y'])\n )\n df2['label'] = df2.type + \" - \" + df2.componentName + \" to \" + df2.productName\n df2 = df2[['productName', 'quantity', 'source', 'target', 'label']]\n \n df2['color'] = 'olive' \n # display(df2.head())\n \n # Collect inventory flows - WIP\n df3 = (self.dm.WIP[['wipQuantity']]\n .query(\"wipQuantity > 0\")\n .rename(columns={'wipQuantity':'quantity'})\n )\n df3 = df3.reset_index()\n df3['locationNameWip'] = df3.locationName + '_wip'\n # display(df3.head())\n df3 = (df3.merge(inventory_labels_df[['locationName','productName','id']], left_on=['locationName','productName'], right_on=['locationName','productName'])\n .rename(columns={'id': 'target'})\n # .drop(columns=['locationName'])\n )\n df3 = (df3.merge(inventory_labels_df[['locationName','productName','id']], left_on=['locationNameWip','productName'], right_on=['locationName','productName'], suffixes=[None,'_y'])\n .rename(columns={'id': 'source'})\n .drop(columns=['locationName_y'])\n )\n # display(df3.head())\n df3['label'] = \"wip - \" + df3.productName + \" to \" + df3.locationName \n # df1 = df1.drop(columns=['locationNameWip','locationName','shippingMode'])\n # display(df3.head()) \n df3['color'] = 'lightsalmon' \n \n if include_wip:\n df = pd.concat([df1, df2, df3])\n else:\n df = pd.concat([df1, df2])\n \n # Set pop-up text\n \n # display(df.head())\n\n # df['color'] = 'aquamarine' \n fig = go.Figure(data=[go.Sankey(\n # valueformat = \".0f\",\n # valuesuffix = \"TWh\",\n # Define nodes\n node=dict(\n pad=15,\n thickness=15,\n line=dict(color=\"black\", width=0.5),\n label=inventory_labels_df.label.array,\n ),\n # Add links\n link=dict(\n source=df.source.array,\n target=df.target.array,\n value=df.quantity.array,\n label=df.label.array,\n color = df.color.array,\n ))])\n\n fig.update_layout(title_text=\"\",\n font_size=10,\n height=1000,\n margin={'l':40, 'r':40, 't':40})\n return fig\n\n\n\n def plotly_line_product_group_capacity_heatmap(self):\n \"\"\"Heatmap of capacity as line vs product. Good insight on line specialization/recipe-properties.\n Input tables: ['RecipeProperties', 'Line', 'Product']\n Output tables: []\n \"\"\"\n df = (self.dm.recipe_properties[['capacity']]\n .join(self.dm.lines)\n .join(self.dm.products[['productGroup']])\n # .join(self.dm.plants.rename(columns={'locationDescr':'plantDescr'}), on='plantName')\n # .join(self.dm.locations, on='locationName')\n ) # .groupby(['lineName','productType']).max()\n df = df.reset_index()\n # df = df.pivot_table(values='capacity', index=['lineDescr'], columns=['productType'], aggfunc=np.max)\n df = df.pivot_table(values='capacity', index=['lineName'], columns=['productGroup'], aggfunc=np.max)\n\n labels = {'lineName': 'Line', 'productGroup': 'Product Group', 'productName': 'Product Name'}\n labels = dict(x=\"Product Group\", y=\"Line\", color=\"Capacity\")\n fig = px.imshow(df, labels=labels, width=1000,\n color_continuous_scale='YlOrRd',\n # y = [\"Abbott Olst<br>Granulate Line\", \"Abbott Olst<br>Packaging Line 5\", \n # \"Abbott Olst<br>Packaging Line 6\", \"Abbott<br>Weesp Line\"],\n y = [\"Granulate Line\", \"Packaging Line 1\", \"Packaging Line 2\", \"API Line\"],\n x = [\"API\", \"Granulate\", \"Tablet\", \"Package\"],\n )\n\n fig.update_layout(\n title={\n 'text': \"Maximum Line Capacity by Product Type\",\n # 'y': 0.92,\n 'x': 0.5,\n 'xanchor': 'center',\n 'yanchor': 'top'})\n\n return fig\n\n \n\n @plotly_figure_exception_handler\n def plotly_transportation_bar(self, query = None, title = 'Transportation Activity'):\n \"\"\"\n \"\"\"\n df = self.dm.transportation_activities[['xTransportationSol']].query(\"xTransportationSol > 0\")\\\n .join(self.dm.products[['productGroup', 'productCountry']])\\\n .groupby(['timePeriodSeq', 'originLocationName', 'destinationLocationName','shippingMode','productName']).\\\n sum().rename(columns={'xTransportationSol':'quantity'})\n\n if query is not None:\n df = df.query(query).copy()\n # title = \"Departing From: \" + query.split(\"originLocationName == \")[-1].replace(\"_\", \" \").replace(\"'\",\"\")\n else:\n pass\n # title = \"Transportation Activity\"\n\n df = df.join(self.dm.products[['productGroup', 'productCountry']])\n\n df = df.reset_index()\n\n df.productCountry = df.productCountry.fillna(\"\")\n df['location_product'] = df['productCountry'] + \" - \" + df['productName']\n df['location_product'] = df['location_product'].fillna('API')\n\n color_discrete_map = self.gen_color_col(df['location_product'])\n\n labels = {'location_product': 'Product Location', 'timePeriodSeq': 'Time Period', \"quantity\": 'Quantity'}\n\n if len(df.shippingMode.unique()) < 2:\n fct = None\n else:\n fct = \"shippingMode\"\n\n category_orders = {'shippingMode': ['Air', 'Sea', 'Truck', 'Rail']}\n active_shipping_mode_category_orders = [sm for sm in ['Air', 'Sea', 'Truck', 'Rail'] if sm in df.shippingMode.unique()]\n\n fig = px.bar(data_frame = df, x = \"timePeriodSeq\", y = \"quantity\", color = \"location_product\", \n labels = labels,\n facet_col = fct,\n # category_orders = category_orders,\n category_orders = {'shippingMode': active_shipping_mode_category_orders},\n color_discrete_map=color_discrete_map)\n\n fig.update_layout(title = title, legend = {'orientation': 'v', 'x': 1.05},\n margin = {'l':80, 't':80})\n\n if len(df.shippingMode.unique()) > 1:\n fig.for_each_annotation(lambda a: a.update(text=a.text.split(\"shippingMode=\")[-1].capitalize()))\n\n fig.update_layout(hovermode=\"closest\")\n\n return fig\n\n def demand_choropleth_map(self):\n \"\"\"\"\"\"\n df = (self.dm.demand\n .join(self.dm.products[['productGroup', 'productCountry']]))\n\n \n # Set location_product name\n df = df.reset_index()\n df['location_product'] = df.locationName + \" - \" + df.productName\n\n df = (df\n .groupby(['timePeriodSeq', 'location_product', 'productCountry']).sum()\n .sort_values('quantity', ascending=False))\n \n # locs = pd.read_csv('/workspace/geocode_abbott_locations_fixed.csv')\n\n # print(self.dm.locations.head())\n # print(locs.head())\n locs = self.dm.locations.reset_index()\n\n df = df.reset_index()\n df = df.merge(locs[[\"locationName\", \"latitude\", \"longitude\", \"countryIso\"]], left_on = \"productCountry\", right_on = \"locationName\")\n\n df_gby = df.groupby(\"countryIso\")['quantity'].mean().reset_index()\n\n fig = px.choropleth(df_gby, \n locations = \"countryIso\",\n color = \"quantity\",\n width = 1200,\n title = \"Demand Choropleth Map\")\n \n fig.update_layout(paper_bgcolor='#edf3f4',\n geo=dict(bgcolor= '#edf3f4', showframe = False),\n margin = {'b': 0, 't':50},\n title = {'y': 0.95},\n coloraxis_colorbar=dict(title=\"Quantity\")\n )\n return fig\n\n def unfulfilled_demand_choropleth_map(self, animation_col = None):\n \"\"\"\n \"\"\"\n df0 = (self.dm.transportation_activities[['xTransportationSol']]\n .groupby(['productName', 'destinationLocationName', 'timePeriodSeq']).sum()\n .rename_axis(index={'destinationLocationName': 'locationName'})\n .rename(columns={'xTransportationSol':'Transportation'})\n )\n \n product_aggregation_column = 'productName'\n df = (self.dm.demand_inventories[['quantity','xFulfilledDemandSol','xUnfulfilledDemandSol','xBacklogSol','xBacklogResupplySol','xInvSol']]\n .join(self.dm.products[['productGroup', 'productCountry']])\n # .join(self.dm.locations)\n .join(df0, how='left')\n ).groupby(['timePeriodSeq', 'productCountry', product_aggregation_column]).sum()\n\n df = df.reset_index()\n\n # locs = pd.read_csv('/workspace/geocode_abbott_locations_fixed.csv')\n locs = self.dm.locations.reset_index()\n\n df = df.merge(locs[[\"locationName\", \"latitude\", \"longitude\", \"countryIso\"]], left_on = \"productCountry\", right_on = \"locationName\")\n\n if animation_col is not None:\n df_gby = df.groupby([\"countryIso\", animation_col])['xUnfulfilledDemandSol'].mean().reset_index()\n title = \"Animated Unfulfilled Demand Choropleth Map\"\n width = 2000\n else:\n df_gby = df.groupby(\"countryIso\")['xUnfulfilledDemandSol'].mean().reset_index()\n title = \"Unfulfilled Demand Choropleth Map\"\n width = 1000\n\n fig = px.choropleth(df_gby, \n locations = \"countryIso\",\n color = \"xUnfulfilledDemandSol\",\n animation_frame=animation_col,\n animation_group = animation_col,\n# facet_col = \"productGroup\",\n width = width,\n # height = 1000,\n title = title)\n \n fig.update_layout(legend = {'title': 'Quantity'},\n paper_bgcolor='#edf3f4',\n geo=dict(bgcolor= '#edf3f4', showframe = False),\n margin = {'b': 0, 't':50},\n title = {'y': 0.95},\n width = width,\n coloraxis_colorbar=dict(title=\"Quantity\")\n )\n\n return fig\n \n def line_map(self):\n \"\"\"\n \"\"\"\n import math\n import random\n\n aggregation_column = 'productName'\n #Collect inventory flows - transportation\n df1 = (self.dm.transportation_activities[['xTransportationSol']].join(self.dm.products[['productGroup']])\n .query(\"xTransportationSol > 0\")\n .groupby(['originLocationName', 'destinationLocationName','shippingMode','productGroup']).sum()\n .rename(columns={'xTransportationSol':'quantity'})\n )\n df1 = df1.reset_index()\n\n # locs = pd.read_csv('/workspace/geocode_abbott_locations_fixed.csv')\n locs = self.dm.locations.reset_index()\n\n map_locs = df1.drop_duplicates(['originLocationName', 'destinationLocationName', 'shippingMode', 'productGroup', 'quantity'])\n \n df6 = map_locs.merge(locs[[\"locationName\", \"latitude\", \"longitude\", \"countryIso\"]], left_on = \"originLocationName\", right_on = \"locationName\")\n df6 = df6.rename({'latitude': 'origin_lat', 'longitude':'origin_lon', 'countryIso':'origin_iso3'}, axis = 1)\n df6 = df6.merge(locs[[\"locationName\", \"latitude\", \"longitude\", \"countryIso\"]], left_on = \"destinationLocationName\", right_on = \"locationName\")\n df6 = df6.rename({'latitude': 'destination_lat', 'longitude':'destination_lon', 'countryIso':'destination_iso3'}, axis = 1)\n\n fig = go.Figure()\n\n fig = fig.add_trace(go.Scattergeo(\n # locationmode = 'USA-states',\n lon = df6['origin_lon'],\n lat = df6['origin_lat'],\n hoverinfo = 'text',\n text = df6['originLocationName'],\n name = \"Supply Chain Origin\",\n # showlegend = False,\n mode = 'markers',\n marker = dict(\n size = 8,\n color = 'rgb(255, 0, 0)',\n )))\n\n df6 = df6.reset_index().copy()\n # add some jitter to prevent overlays\n random.seed(42)\n df6['destination_lat'] = df6['destination_lat'].apply(lambda x : x + random.uniform(-0.75, 0.75))\n df6['destination_lon'] = df6['destination_lon'].apply(lambda x : x + random.uniform(-0.75, 0.75))\n\n fig = fig.add_trace(go.Scattergeo(\n # locationmode = 'USA-states',\n lon = df6['destination_lon'],\n lat = df6['destination_lat'],\n hoverinfo = 'text',\n text = df6['destinationLocationName'],\n name = \"Supply Chain Destination\",\n mode = 'markers',\n marker = dict(\n size = df6.quantity.apply(math.log).clip(lower = 2)*2,\n color = \"blue\",\n )))\n \n color_dict = {'sea': 'darkblue', 'truck': 'darkgreen', 'air': 'darkred', 'Sea': 'darkblue', 'Truck': 'darkgreen', 'Air':'darkred'\n }\n\n df6['showlegend'] = False\n\n df6['linetype'] = \"solid\"\n\n ix = df6.groupby('shippingMode').first()['index'].values\n for i in ix:\n df6['showlegend'].iloc[i] = True\n\n for i in range(len(df6)):\n fig.add_trace(\n go.Scattergeo(\n lon = [df6['origin_lon'][i], df6['destination_lon'][i]],\n lat = [df6['origin_lat'][i], df6['destination_lat'][i]],\n mode = 'lines',\n name = df6['shippingMode'][i],\n showlegend = bool(df6['showlegend'][i]),\n # showlegend = False,\n line_dash= df6['linetype'][i],\n line = dict(width = 1,color = color_dict[df6['shippingMode'][i]]),\n # opacity = float(df_flight_paths['cnt'][i]) / float(df_flight_paths['cnt'].max()),\n )\n )\n # adding a choropleth on top\n df = (self.dm.demand\n .join(self.dm.products[['productGroup', 'productCountry']])\n )\n \n # Set location_product name\n df = df.reset_index()\n df['location_product'] = df.locationName + \" - \" + df.productName\n\n df = (df\n .groupby(['timePeriodSeq', 'location_product', 'productCountry']).sum()\n .sort_values('quantity', ascending=False))\n\n df = df.reset_index()\n\n df = df.merge(locs[[\"locationName\", \"latitude\", \"longitude\", \"countryIso\"]], left_on = \"productCountry\", right_on = \"locationName\")\n\n df = df.sort_values('timePeriodSeq')\n\n df_gby = df.groupby(\"countryIso\")['quantity'].mean().reset_index()\n\n fig = fig.add_trace(\n go.Choropleth(\n locations = df_gby['countryIso'],\n z = df_gby['quantity'],\n colorscale = \"Reds\",\n colorbar_title = \"Quantity\"\n )\n )\n\n fig.update_layout(coloraxis_colorbar_x=-1)\n\n fig.update_layout(\n width = 1000,\n # height = 1000,\n legend = {\n 'title': 'Transportation Type',\n 'orientation': 'v',\n 'x': 0.85,\n 'y': 0.9,\n },\n title = {'text': \"Supply Chain Overview\", 'y': 0.95},\n margin = {\n 't': 50,\n 'b': 0,\n },\n paper_bgcolor='#edf3f4',\n geo=dict(bgcolor= '#edf3f4', showframe = False),\n )\n\n\n return fig\n \n def percent_unfullfilleddemand(self):\n # product_aggregation_column = 'productGroup' # potentially for further unpacking\n df = (self.dm.demand_inventories[['quantity','xUnfulfilledDemandSol']])\n # .join(self.dm.products[['productGroup']])\n # ).groupby(['timePeriodSeq']).sum()\n\n unfulfilled_demand = df.xUnfulfilledDemandSol.groupby(['timePeriodSeq']).sum()\n num_tp = len(self.dm.demand.index.unique(level='timePeriodSeq'))\n average_monthly_demand = df.quantity.sum()/num_tp\n\n final_df = (unfulfilled_demand/average_monthly_demand).replace([np.inf, -np.inf], np.nan).fillna(0).round(4)*100\n\n # final_df = final_df.groupby('timePeriodSeq').mean()\n\n return final_df\n\n def percent_backlog(self):\n # product_aggregation_column = 'productGroup'\n df = (self.dm.demand_inventories[['quantity','xBacklogSol']])\n # .join(self.dm.products[['productGroup']])\n # ).groupby(['timePeriodSeq']).sum()\n \n backlog = df.xBacklogSol.groupby('timePeriodSeq').sum()\n\n num_tp = len(self.dm.demand.index.unique(level='timePeriodSeq'))\n\n average_monthly_demand = df.quantity.sum()/num_tp\n\n # final_df = (df.xBacklogSol/df.quantity).replace([np.inf, -np.inf], np.nan).fillna(0).round(4)*100\n\n final_df = (backlog / average_monthly_demand).replace([np.inf, -np.inf], np.nan).fillna(0).round(4)*100\n\n # final_df = final_df.groupby('timePeriodSeq').mean()\n\n return final_df\n \n def dos_inv(self):\n # product_aggregation_column = 'productGroup'\n\n # print(self.dm.products)\n\n # can feed it plant or warehouse inventories\n\n df_demand = (self.dm.demand_inventories[['quantity','xFulfilledDemandSol','xUnfulfilledDemandSol','xBacklogSol','xBacklogResupplySol','xInvSol']])\n # .join(self.dm.products[['productGroup']])\n # ).groupby(['timePeriodSeq']).sum()\n\n df_inv = (self.dm.demand_inventories[['quantity','xFulfilledDemandSol','xUnfulfilledDemandSol','xBacklogSol','xBacklogResupplySol','xInvSol']])\n # .join(self.dm.products[['productGroup']])\n # ).groupby(['timePeriodSeq']).sum()\n\n\n final_df = (df_demand.groupby([\"productName\", \"timePeriodSeq\"]).xInvSol.sum()/df_inv.groupby([\"productName\", \"timePeriodSeq\"]).\\\n quantity.sum()).replace([np.inf, -np.inf], np.nan).fillna(0).round(4)\n\n final_df = pd.Series(final_df.groupby('timePeriodSeq').mean().values)\n\n\n t = self.get_demand_location_dos(30).groupby(['timePeriodSeq']).agg({'dosQuantity': 'sum'})\n t = pd.Series(t.reset_index()['dosQuantity'])\n \n final_dos = (final_df/t)\n \n return final_dos\n \n def average_inv(self):\n # product_aggregation_column = 'productGroup'\n # num_timeperiods = self.dm.active_timeperiods.max()\n num_timeperiods = 30\n\n df_inv = (self.dm.demand_inventories[['xInvSol']]\n # .join(self.dm.products[['productGroup']])\n ).groupby(['timePeriodSeq']).sum()\n\n final_df = (df_inv.xInvSol/num_timeperiods).round(4)\n # final_df = final_df.groupby('timePeriodSeq').mean()\n\n return final_df\n\n def get_demand_location_dos(self, dos:int):\n \"\"\"Compute the quantity of product at the end of a time-period that represents the \n Days-Of-Supply computed using the actual demand in the following time-periods.\n The quantity can be used in a days-of-supply inventory constraint or objective.\n For the last time-periods, assume demand remains constant with the value of the last time-period.\n \n Args:\n dos (int): Days-Of-Supply. Number of days.\n \n Note: use dm.demand_inventories. Is has already expanded to all time-periods.\n \"\"\"\n # num_tps = 24 # Number of time-periods\n \n # num_days_tp = 30 # Number of days per time-period. To keep it simple, use 30 per month. HARD-CODED for now. TODO: put in parameter, or add as column in TimePeriods\n num_days_tp = len(self.dm.demand.index.unique(level='timePeriodSeq')) * 30\n # print(self.dm.demand_inventories.head())\n df = (self.dm.demand_inventories[['quantity']]\n .sort_index() # sort index so the shift will work right\n ).fillna(0)\n \n num_tps = len(df.index.unique(level='timePeriodSeq'))-1\n # df['numDays'] = num_days_tp\n df['demandPerDay'] = df.quantity / num_days_tp #df.numDays\n df['nextDemandPerDay'] = df.demandPerDay # Note we are shifting the nextDemandPerDay, so initialize once\n df['dosQuantity'] = 0 # We are incrementing the dosQuantity, so initialize\n \n remaining_dos = dos # Remaining DOS in each iteration, initialize with all DOS\n shift = 0 # Only for debuging\n \n # Iterate over the next time-periods until it covers all requested dos days\n # Sum the DOS quantity\n # Assume demand is constant throughout the time-period\n while remaining_dos > 0:\n # print(remaining_dos)\n shift = shift + 1\n # print(shift)\n next_dos = min(remaining_dos, num_days_tp)\n # print(f\"Shift = {shift}, remaining_dos = {remaining_dos}, next_dos={next_dos}\")\n df['nextDemandPerDay'] = df.groupby(['locationName','productName'])['nextDemandPerDay'].shift(-1) #, fill_value=0) \n # print(df.head())\n # print(num_tps)\n # print(df.loc[pd.IndexSlice[:,:,num_tps],'demandPerDay'])\n df.loc[pd.IndexSlice[:,:,num_tps],'nextDemandPerDay'] = df.loc[pd.IndexSlice[:,:,num_tps],'demandPerDay'] # Fill gap from the shift with last demand\n # print(\"test\")\n df['dosQuantity'] = df.dosQuantity + df.nextDemandPerDay * next_dos\n \n remaining_dos = remaining_dos - next_dos\n # print(\"test\")\n # display(df.query(\"locationName=='NAMIBIA'\").head(24))\n df = df.drop(columns=['demandPerDay', 'nextDemandPerDay'])\n\n # print(df)\n return df\n \n def kpi_heatmap(self):\n '''\n '''\n\n cols = [self.percent_unfullfilleddemand(), self.percent_backlog(), self.dos_kpi(as_time = True), \n self.calc_air_pct(as_time = True), self.utilization_kpi(as_time = True)]\n\n final_df = pd.DataFrame(data= cols).\\\n rename({'xUnfulfilledDemandSol': 'unfulfilled_demand', 'xBacklogSol': 'backlog', 'xInvSol': 'dos_inv', \n 'Unnamed 0': 'air_sea_ratio', 'line_capacity_utilization': 'utilization'}, \n axis = 0)\n \n heatmap_df = final_df.copy()\n\n # make a green zone around 30 days and orange if between 10-20 and 40-50, then red between 0-10 and 50-60\n heatmap_df.loc['dos_inv'] = np.where((heatmap_df.loc['dos_inv'] <= 10) | (heatmap_df.loc['dos_inv'] >= 60), 2, \n np.where((heatmap_df.loc['dos_inv'] >= 40) & (heatmap_df.loc['dos_inv'] < 60), 1,\n np.where((heatmap_df.loc['dos_inv'] >= 20) & (heatmap_df.loc['dos_inv'] < 40), 0, np.nan)))\n\n\n heatmap_df.loc['unfulfilled_demand'] = np.where(heatmap_df.loc['unfulfilled_demand'] > 5, 2, \n np.where(heatmap_df.loc['unfulfilled_demand'] < 2, 0, 1))\n\n heatmap_df.loc['backlog'] = np.where(heatmap_df.loc['backlog'] > 10, 2, \n np.where(heatmap_df.loc['backlog'] < 5, 0, 1))\n \n heatmap_df.loc['air_sea_ratio'] = np.where(heatmap_df.loc['air_sea_ratio'] > 50, 2, \n np.where(heatmap_df.loc['air_sea_ratio'] < 20, 0, 1))\n\n heatmap_df.loc['utilization'] = np.where(heatmap_df.loc['utilization'] > 95, 2, \n np.where(heatmap_df.loc['utilization'] < 85, 0, 1))\n\n # final_df = final_df.apply(lambda x:(x - x.min())/(x.max() - x.min()), axis = 0)\n\n fig = px.imshow(heatmap_df,\n color_continuous_scale =[\"green\", \"orange\", \"red\"],\n y = [\"Unfulfilled Demand %\", \"Backlog %\", \"Inventory<br>Days of Supply\", \"Air Shipping %\", \"Utilization %\"]\n )\n # customdata allows to add an \"invisible\" dataset that is not being plotted but whose values can be used for reference\n fig.update_traces(customdata= final_df,\n hovertemplate = \n \"%{y}: %{customdata: .3f}\"+\n \"<br>Time Period %{x}\"+\n '<extra></extra>')\n\n fig.update(layout_coloraxis_showscale=False)\n fig.update_layout(margin = {'b':40, 'l':140, 'r':10, 't':20}) # hide colorbar\n\n return fig\n \n def make_gauge(self, value: float, title: str, orange_threshold: float, red_threshold: float, max_val: float):\n \"\"\" \n \"\"\"\n steps = [\n {'range': [0, orange_threshold], 'color': 'green'},\n {'range': [orange_threshold, red_threshold], 'color': 'orange'},\n {'range': [red_threshold, max_val], 'color': 'red'},\n ]\n\n fig = go.Figure(go.Indicator(\n mode = \"gauge+number\",\n value = value,\n domain = {'x': [0, 1], 'y': [0, .75]},\n title = {'text': title, 'font': {'color': 'black', 'size': 18}},\n gauge = {'axis': {'range': [None, max_val], 'tickfont': {'color': 'black'}},\n 'threshold' : {'line': {'color': \"darkred\", 'width': 4}, 'thickness': 0.75, 'value': red_threshold},\n 'steps': steps,\n 'bar': {'color': \"darkblue\"},},\n )\n ) \n \n fig.update_layout(font = {'color': 'green' if value < orange_threshold else 'orange' if value > orange_threshold and value < red_threshold else 'red', 'family': \"Arial\"},\n margin={'t':10,'b':30},\n )\n\n return fig\n\n def make_gauge_dos(self, value: float, title: str, max_val: float, type = None):\n ''' Standalone function for the DOS gauge\n '''\n\n steps = [\n {'range': [0, 10], 'color': 'red'},\n {'range': [60, max_val], 'color': 'red'},\n {'range': [10, 20], 'color': 'orange'},\n {'range': [40, 60], 'color': 'orange'},\n {'range': [20, 40], 'color': 'green'},\n ]\n\n fig = go.Figure(go.Indicator(\n mode = \"gauge+number\",\n value = value,\n domain = {'x': [0, 1], 'y': [0, .75]},\n title = {'text': title, 'font': {'color': 'black', 'size': 18}},\n gauge = {'axis': {'range': [None, max_val], 'tickfont': {'color': 'black'}},\n 'threshold' : {'line': {'color': \"darkred\", 'width': 4}, 'thickness': 0.75, 'value': 60},\n 'steps': steps,\n 'bar': {'color': \"darkblue\"},},\n )\n ) \n \n fig.update_layout(font = {'color': 'green' if value < 40 and value > 20 else 'orange' if ((value > 40 and value < 60) or (value > 10 and value < 20)) else 'red', 'family': \"Arial\"},\n margin={'t': 10, 'b': 30})\n\n return fig\n\n \n def calc_air_pct(self, as_time = False):\n \"\"\"\n When setting as_time = True, returns a vector with a value at each time index.\n The issue is that not all time indices have a value for air or sea shipping. \n A hacky solution: create a df initialized to 0 with all combinations of timePeriodSeq and shippingMode (i.e. 21 time periods * 3 shippingModes)\n then iterate over the original df that was grouped by timePeriodSeq and shippingMode, \n check if the grouped data has a value for that time/shippingMode combination, \n if yes then copy/paste that value\n if no, then keep 0 as the value\n TODO: Probably a better way to write that code\n \"\"\"\n import warnings\n warnings.filterwarnings(\"ignore\")\n\n print(pd.__version__)\n\n df = self.dm.transportation_activities[['xTransportationSol']].query(\"xTransportationSol > 0\")\\\n .join(self.dm.products[['productGroup', 'productCountry']])\\\n .groupby(['timePeriodSeq', 'originLocationName', 'destinationLocationName','shippingMode','productName']).\\\n sum().rename(columns={'xTransportationSol':'quantity'})\n \n if not 'Air' in df.index.get_level_values('shippingMode') and as_time:\n num_tp = len(self.dm.demand.index.unique(level='timePeriodSeq'))\n return pd.Series(index = range(num_tp+1), data = 0)\n elif not 'Air' in df.index.get_level_values('shippingMode') and not as_time:\n return 0\n \n if as_time:\n df = df.reset_index()\n from itertools import product\n df_gby = df.groupby(['shippingMode', 'timePeriodSeq']).sum().reset_index()\n\n dft = pd.DataFrame(product(df['shippingMode'].unique(),\n df['timePeriodSeq'].unique()), columns = ['shippingMode', 'timePeriodSeq'])\n\n dft['quantity'] = 0\n\n ### HACK ### probably a better way to write this code\n for i in range(len(dft)):\n sm = dft['shippingMode'].iloc[i]\n ts = dft['timePeriodSeq'].iloc[i]\n if len(df_gby.loc[(df_gby.shippingMode == sm) & (df_gby.timePeriodSeq == ts)]['quantity']) != 0:\n dft['quantity'].iloc[i] = df_gby.loc[(df_gby.shippingMode == sm) & (df_gby.timePeriodSeq == ts)]['quantity']\n else:\n continue\n \n air = dft.loc[dft.shippingMode == 'Air'].quantity.values\n sea = dft.loc[dft.shippingMode == 'Sea'].quantity.values\n\n ratio = pd.Series(air/(air+sea)).replace([np.inf, -np.inf], np.nan).fillna(0).round(3)\n \n else:\n df_gby = df.groupby('shippingMode').sum()\n\n air = df_gby.loc[df_gby.index == 'Air'].quantity.values\n sea = df_gby.loc[df_gby.index == 'Sea'].quantity.values\n\n ratio = air/(sea+air)\n\n ratio = np.round(ratio, 3)\n\n return ratio*100\n \n def utilization_kpi(self, as_time = False):\n \"\"\"\n \"\"\"\n\n product_aggregation_column = 'productGroup'\n df = (self.dm.production_activities[['line_capacity_utilization']]\n .join(self.dm.products[['productGroup']])\n ).groupby(['timePeriodSeq', 'lineName', product_aggregation_column]).sum().reset_index()\n\n # df = df[df['lineName'] == 'Abbott_Olst_Packaging_Line_5']\n df = df[df['lineName'].isin(['Abbott_Olst_Packaging_Line_5', 'Packaging_Line_1'])] # works both for Client and Pharma\n # df = df[df['lineName'] == 'Packaging_Line_1'] # Ony for Pharma\n\n df['line_capacity_utilization'] = (df['line_capacity_utilization'].replace(0, np.nan)*100)\n # VT notes 20211122: why the replace 0 with Nan? Probably to force the mean() to ignore months that have zero utilization?\n # TODO: why not filter?\n # df['line_capacity_utilization'] = (df['line_capacity_utilization']*100)\n\n if as_time:\n return df.set_index('timePeriodSeq')['line_capacity_utilization'].sort_index()\n else:\n return float(df.groupby('lineName')['line_capacity_utilization'].mean())\n \n def dos_kpi(self, as_time = False):\n '''\n '''\n df = self.dm.demand_inventories[['quantity', 'xInvSol']]\n \n num_days = len(self.dm.demand.index.unique(level='timePeriodSeq')) * 30\n\n demand_inv = df.groupby('timePeriodSeq')['xInvSol'].sum()\n\n total_demand = df['quantity'].sum()\n\n demand_dos = demand_inv / (total_demand / num_days)\n\n if as_time:\n return demand_dos\n else:\n return float(demand_dos.mean())\n\n\n\n \n\n"
] |
[
[
"pandas.concat",
"pandas.Series",
"pandas.isnull",
"pandas.DataFrame",
"numpy.round",
"numpy.where"
]
] |
kinlead/Haasoscope
|
[
"9eefa1df383f24ed844bc113bb5e52d963dc34b5"
] |
[
"software/HaasoscopeLibQt.py"
] |
[
"# -*- coding: utf-8 -*-\nimport sys\n\n#print(\"Loading HaasoscopeLibQt.py\")\n\n# You might adjust these, just override them before calling construct()\nnum_board = 1 # Number of Haasoscope boards to read out\nmax_ram_width = 13 # max size of the buffer rams (2*13=8096 bytes)\nmax_slowadc_ram_width = 11 # max size of the adc ram (2*11=2048 bytes)\nram_width = 9 # width in bits of sample ram to use (e.g. 9==512 samples)\nmax10adcchans = []#[(0,110),(0,118),(1,110),(1,118)] #max10adc channels to draw (board, channel on board), channels: 110=ain1, 111=pin6, ..., 118=pin14, 119=temp\nsendincrement=0 # 0 would skip 2**0=1 byte each time, i.e. send all bytes\nnum_chan_per_board = 4 # number of high-speed ADC channels on a Haasoscope board\n\nfrom serial import Serial, SerialException\nfrom struct import unpack\nimport numpy as np\nimport time, json, os\n\nfrom scipy.signal import resample\nimport serial.tools.list_ports\nimport scipy.optimize\nimport multiprocessing\n\nmearm = False\nmewin = False\ntry:\n #print(os.uname())\n if os.uname()[4].startswith(\"arm\") or os.uname()[4].startswith(\"aarch\"):\n print(\"On a raspberry pi?\")\n mearm = True\nexcept AttributeError:\n mewin = True\n #print(\"Not on Linux?\")\n\nenable_ripyl=False # set to True to use ripyl serial decoding... have to get it from https://github.com/kevinpt/ripyl and then install it first!\nif enable_ripyl:\n import ripyl.util.plot as rplot\n from collections import OrderedDict\n import ripyl.streaming as stream\n import ripyl.protocol.uart as uart\n\nenable_fastusb=True # set to True to be able to use the fastusb2 writing\nif enable_fastusb:\n if mewin:\n useftd2xx = True\n #print(\"Using ftd2xx driver on Windows\")\n else:\n useftd2xx = False\n #print(\"Using pyftdi on Linux\")\n useftdi = not useftd2xx\n if useftd2xx:\n import ftd2xx as ftd\n if useftdi:\n from pyftdi.ftdi import Ftdi\n ftdiattempts=300 # number of times to try reading - basically a timeout\n\nclass Haasoscope():\n \n def construct(self):\n self.num_samples = int(pow(2,ram_width)/pow(2,sendincrement)) # num samples per channel, max is pow(2,ram_width)/pow(2,0)=4096\n self.num_bytes = int(self.num_samples*num_chan_per_board) #num bytes per board\n self.nsamp=int(pow(2,min(ram_width,max_slowadc_ram_width))-1) #samples for each max10 adc channel (4095 max (not sure why it's 1 less...))\n print(\"num main ADC and max10adc bytes for all boards = \",self.num_bytes*num_board,\"and\",len(max10adcchans)*2*self.nsamp)\n self.serialdelaytimerwait=100 #150 # 600 # delay (in 2 us steps) between each 32 bytes of serial output (set to 600 for some slow USB serial setups, but 0 normally)\n if mearm: self.serialdelaytimerwait+=600\n self.brate = 1500000 #serial baud rate #1500000 #115200 #921600\n self.sertimeout = 0.25+self.num_bytes*8*11.0/self.brate #time to wait for serial response #3.0, 0.25+self.num_bytes*8*11.0/self.brate, or None\n self.clkrate=125.0 # ADC sample rate in MHz\n self.serport=\"\" # the name of the serial port on your computer, connected to Haasoscope, like /dev/ttyUSB0 or COM8, leave blank to detect automatically!\n self.trigserport=''\n self.usbport=[] # the names of the USB2 ports on your computer, connected to Haasoscope, leave blank to detect automatically!\n self.usbser=[]\n self.usbsern=[]\n self.texts = []\n self.xdata=np.arange(self.num_samples)\n self.xdata2=np.arange(self.num_samples*2) # for oversampling\n self.xdata4=np.arange(self.num_samples*4) # for over-oversampling\n self.ydata = []\n ysampdatat=np.zeros(self.nsamp*len(max10adcchans)); self.ysampdata=np.reshape(ysampdatat,(len(max10adcchans),self.nsamp))\n self.xsampdata=np.arange(self.nsamp)\n self.paused=True\n self.getone=False\n self.rolltrigger=True #roll the trigger\n self.average=False #will average every 2 samples\n self.fallingedge=True #trigger on falling edge\n self.dogrid=True #redraw the grid\n self.chanforscreen=0 #channel to draw on the mini-display\n self.triggertimethresh=1 #samples for which the trigger must be over/under threshold\n self.downsample=2 #adc speed reduction, log 2... so 0 (none), 1(factor 2), 2(factor 4), etc.\n self.dofft=False #drawing the FFT plot\n self.dousb=False #whether to use USB2 output\n self.dofastusb=False #whether to do sync 245 fifo mode on usb2 (need to reprogram ft232h hat) (experimental)\n self.fastusbpadding=4 #number of bytes added total (start and end) to each channel in fastusb mode\n self.fastusbendpadding=2 #number of bytes added to the end of each channel in fastusb mode\n self.dousbparallel=False #whether to tell all board to read out over USB2 in parallel (experimental)\n self.checkfastusbwriting=False #whether to cross-check the writing of fastusb data\n self.sincresample=0 # amount of resampling to do (sinx/x)\n self.dogetotherdata=False # whether to read other calculated data like TDC\n self.tdcdata=0 # TDC data\n self.selectedchannel=0 #what channel some actions apply to\n self.selectedmax10channel=0 #what max10 channel is selected\n self.autorearm=False #whether to automatically rearm the trigger after each event, or wait for a signal from software\n self.dohighres=False #whether to do averaging during downsampling or not (turned on by default during startup, and off again during shutdown)\n self.useexttrig=False #whether to use the external trigger input\n self.autocalibchannel=-1 #which channel we are auto-calibrating\n self.autocalibgainac=0 #which stage of gain and acdc we are auto-calibrating\n self.recordedchannellength=25 #number of events to overlay in the 2d persist plot\n self.ydatarefchan=-1 #the reference channel for each board, whose ydata will be subtracted from other channels' ydata on the board\n self.chtext = \"Ch.\" #the text in the legend for each channel\n self.noselftrig=False\n self.num_logic_inputs=5 #number of active logic analyzer bits on each board\n self.flyingfast = False # to just read as fast as possible\n self.domt=False\n self.db = False #debugging #True #False\n \n self.dolockin=False # read lockin info\n self.dolockinplot=True # plot the lockin info\n self.lockinanalyzedataboard=0 # the board to analyze lockin info from\n self.debuglockin=False #debugging of lockin calculations #True #False\n self.reffreq = 0.008 #MHz of reference signal on chan 3 for lockin calculations\n self.refsinchan = 3 #the channel number of the ref input signal (for auto reffreq calculation via sin fit)\n\n self.xscaling=1.e0 # for the x-axis scale\n self.lowdaclevel=np.ones(num_board*num_chan_per_board)*2050 # these hold the user set levels for each gain combination\n self.highdaclevel=np.ones(num_board*num_chan_per_board)*2800\n self.lowdaclevelsuper=np.ones(num_board*num_chan_per_board)*120\n self.highdaclevelsuper=np.ones(num_board*num_chan_per_board)*50\n self.lowdaclevelac=np.ones(num_board*num_chan_per_board)*2250 # these hold the user set levels for each gain combination in ac coupling mode\n self.highdaclevelac=np.ones(num_board*num_chan_per_board)*4600\n self.lowdaclevelsuperac=np.ones(num_board*num_chan_per_board)*2300\n self.highdaclevelsuperac=np.ones(num_board*num_chan_per_board)*4600\n self.chanlevel=np.ones(num_board*num_chan_per_board)*self.lowdaclevel # the current level for each channel, initially set to lowdaclevel (x1)\n self.gain=np.ones(num_board*num_chan_per_board, dtype=int) # 1 is low gain, 0 is high gain (x10)\n self.supergain=np.ones(num_board*num_chan_per_board, dtype=int) # 1 is normal gain, 0 is super gain (x100)\n self.acdc=np.ones(num_board*num_chan_per_board, dtype=int) # 1 is dc, 0 is ac\n self.trigsactive=np.ones(num_board*num_chan_per_board, dtype=int) # 1 is triggering on that channel, 0 is not triggering on it\n self.dooversample=np.zeros(num_board*num_chan_per_board, dtype=int) # 1 is oversampling, 0 is no oversampling, 9 is over-oversampling\n self.rollingtrigger=True #rolling auto trigger at 5 Hz \n self.dologicanalyzer=False #whether to send logic analyzer data\n self.fitline1=-1 # set to >-1 to draw a risetime fit\n self.logicline1=-1 # to remember which is the first logic analyzer line\n self.domeasure=True # whether to calculate measurements\n self.dodrawing=True # assume we're drawing\n self.Vrms=np.zeros(num_board*num_chan_per_board, dtype=float) # the Vrms for each channel\n self.Vmean=np.zeros(num_board*num_chan_per_board, dtype=float) # the Vmean for each channel\n \n #These hold the state of the IO expanders\n self.a20= int('f0',16) # oversamp (set bits 0,1 to 0 to send 0->2 and 1->3) / gain (set second char to 0 for low gain)\n self.b20= int('0f',16) # shdn (set first char to 0 to turn on) / ac coupling (set second char to f for DC, 0 for AC)\n self.a21= int('00',16) # leds (on is 1)\n self.b21= int('00',16)# free pins\n \n print(\"Construction done\")\n \n def tellrolltrig(self,rt):\n #tell them to roll the trigger (a self-trigger each ~second), or not\n if rt: self.ser.write(bytearray([101])); self.rollingtrigger=True; print(\"rolling trigger\")\n else: self.ser.write(bytearray([102])); self.rollingtrigger=False; print(\"not rolling trigger\")\n\n def tellsamplesmax10adc(self):\n #tell it the number of samples to use for the 1MHz internal Max10 ADC\n self.ser.write(bytearray([120]))\n myb=bytearray.fromhex('{:04x}'.format(self.nsamp))\n self.ser.write(bytearray([myb[0]]))\n self.ser.write(bytearray([myb[1]]))\n if self.db: print(\"Nsamp for max10 ADC is\",256*myb[0]+1*myb[1])\n \n def settriggerpoint(self,tp):\n #tell it the trigger point\n self.ser.write(bytearray([121]))\n myb=bytearray.fromhex('{:04x}'.format(tp))\n self.ser.write(bytearray([myb[0]]))\n self.ser.write(bytearray([myb[1]]))\n #print \"Trigger point is\",256*myb[0]+1*myb[1]\n\n def tellsamplessend(self):\n #tell it the number of samples to send\n self.ser.write(bytearray([122]))\n myb=bytearray.fromhex('{:04x}'.format(int(self.num_samples*pow(2,sendincrement)))) # or 0 for all, or num_samples*pow(2,sendincrement)\n self.ser.write(bytearray([myb[0]]))\n self.ser.write(bytearray([myb[1]]))\n print(\"num samples is\",256*myb[0]+1*myb[1])\n \n def telllockinnumtoshift(self,numtoshift):\n #tell it the number of samples to shift when calculating 90deg outofphase sum for lockin\n self.ser.write(bytearray([138]))\n myb=bytearray.fromhex('{:04x}'.format(numtoshift))\n self.ser.write(bytearray([myb[0]]))\n self.ser.write(bytearray([myb[1]]))\n if self.db: print(\"lockinnumtoshift is\",256*myb[0]+1*myb[1])\n \n def tellserialdelaytimerwait(self):\n #tell it the number of microseconds to wait between every 32 (64?) bytes of serial output (for some slow USB serial setups)\n self.ser.write(bytearray([135]))\n myb=bytearray.fromhex('{:04x}'.format(self.serialdelaytimerwait))\n self.ser.write(bytearray([myb[0]]))\n self.ser.write(bytearray([myb[1]]))\n print(\"serialdelaytimerwait is\",256*myb[0]+1*myb[1])\n \n def tellbytesskip(self):\n #tell it the number of bytes to skip after each send, log2\n self.ser.write(bytearray([123]))\n self.ser.write(bytearray([sendincrement]))\n print(\"send increment is\",sendincrement)\n \n def togglelogicanalyzer(self):\n #tell it start/stop doing logic analyzer\n self.dologicanalyzer = not self.dologicanalyzer\n self.ser.write(bytearray([145]))\n if self.dologicanalyzer: \n self.ser.write(bytearray([5]))\n #if len(self.lines)>=8+self.logicline1: # check that we're drawing\n # for l in np.arange(8): self.lines[l+self.logicline1].set_visible(True)\n if useftdi and self.dofastusb and not self.domt:\n for usb in range(len(self.usbser)):\n self.usbser[usb].read_data_set_chunksize( int((self.num_bytes + self.fastusbpadding*num_chan_per_board) * 514/512 * 5/4 + 100) )\n else:\n self.ser.write(bytearray([4]))\n #if len(self.lines)>=8+self.logicline1: # check that we're drawing\n # for l in np.arange(8): self.lines[l+self.logicline1].set_visible(False)\n if useftdi and self.dofastusb and not self.domt:\n for usb in range(len(self.usbser)):\n self.usbser[usb].read_data_set_chunksize( int((self.num_bytes + self.fastusbpadding*num_chan_per_board) * 514/512 + 100) )\n print(\"dologicanalyzer is now\",self.dologicanalyzer)\n\n def toggle_fastusb(self):\n self.ser.write(bytearray([58]))\n print(\"toggled fast usb writing\")\n\n def toggle_checkfastusbwriting(self):\n self.ser.write(bytearray([59]))\n self.checkfastusbwriting = not self.checkfastusbwriting\n print(\"toggled checkfastusbwriting to\",self.checkfastusbwriting)\n\n minfirmwareversion=255\n def getfirmwareversion(self, board):\n #get the firmware version of a board\n oldtime=time.time()\n if board<10:\n self.ser.write(bytearray([30 + board])) #can't do bytearray([53, board]) because it might be firmware<17 # make the next board active (serial_passthrough 0)\n else:\n if self.minfirmwareversion>=17: # first 10 boards were firmware >=17\n self.ser.write(bytearray([53, board]))\n else:\n print(\"boards with firmware <17 detected, but you're trying to do a board with id 10!\")\n return 0\n self.ser.write(bytearray([147])) #request the firmware version byte\n self.ser.timeout=0.1; rslt = self.ser.read(1); self.ser.timeout=self.sertimeout # reduce the serial timeout temporarily, since the old firmware versions will return nothing for command 147\n byte_array = unpack('%dB'%len(rslt),rslt)\n firmwareversion=0\n if len(byte_array)>0: firmwareversion=byte_array[0]\n tookms = (time.time()-oldtime)*1000.\n print(\"got firmwareversion\",firmwareversion,\"for board\",board,\"in\",round(tookms,2),\"ms\")\n if firmwareversion==0 and tookms>50:\n print(\"Could not read firmware version - Exiting!\")\n sys.exit(-7)\n return firmwareversion # is 0 if not found (firmware version <5)\n \n def telltickstowait(self):\n #tell it the number of clock ticks to wait, log2, between sending bytes\n if self.dousb: ds=self.downsample-2\n else: ds=self.downsample-3\n if ds<1: ds=1\n if self.minfirmwareversion>=5:\n ds=1\n else:\n if ds>8:\n ds=8 # otherwise we timeout upon readout\n if self.num_samples>10: self.settriggerpoint(self.num_samples-10) # set trigger way to the right, so we can capture full event - NOTE - screws up mini-screen!\n #self.otherlines[0].set_visible(False) # don't draw trigger time position line, to indicate it's not really set anymore\n self.ser.write(bytearray([125]))\n self.ser.write(bytearray([ds]))\n if self.db: print(\"clockbitstowait is\",ds)\n \n def tellminidisplaychan(self,ch):\n #tell it the channel to show on the mini-display\n self.ser.write(bytearray([126]))\n self.ser.write(bytearray([ch]))\n self.chanforscreen=ch\n print(\"chanforscreen is\",ch)\n \n def settriggerthresh(self,tp):\n #tell it the trigger threshold\n self.ser.write(bytearray([127]))\n tp=255-tp # need to flip it due to op amp\n self.ser.write(bytearray([tp]))\n #print \"Trigger threshold is\",tp\n \n def settriggerthresh2(self,tp):\n #tell it the high trigger threshold (must be below this to trigger)\n self.ser.write(bytearray([140]))\n tp=255-tp # need to flip it due to op amp\n self.ser.write(bytearray([tp]))\n print(\"Trigger high threshold is\",tp)\n \n def settriggertype(self,tp):\n #tell it the trigger type: rising edge, falling edge, either, ...\n self.ser.write(bytearray([128]))\n self.ser.write(bytearray([tp]))\n if self.db: print(\"Trigger type is\",tp)\n \n def settriggertime(self,ttt):\n #tell it the trigger time over/under threshold required\n if ttt>self.num_samples and ttt>10:\n print(\"trigger time over/under thresh can't be bigger than num samples\",self.num_samples); return\n usedownsamplefortriggertot=True\n if usedownsamplefortriggertot: ttt+=pow(2,max_ram_width) #set bit [ram_width] (max) = 1\n self.ser.write(bytearray([129]))\n myb=bytearray.fromhex('{:04x}'.format(ttt))\n self.ser.write(bytearray([myb[0]]))\n self.ser.write(bytearray([myb[1]]))\n print(\"trigger time over/under thresh now\",256*myb[0]+1*myb[1]-pow(2,max_ram_width),\"and usedownsamplefortriggertot is\",usedownsamplefortriggertot)\n\n def settrigcoin(self,coin):\n #set the number of coincidence trigger channels required\n if coin<0 or coin>3:\n print(\"must require 0-3 coincident additional channels\")\n return\n if self.minfirmwareversion<20:\n print(\"must have firmware 20 or above to set N coincident channels\")\n return\n self.ser.write(bytearray([148]))\n self.ser.write(bytearray([coin]))\n print(\"Requiring\", coin, \"coincident additional channels to trigger\")\n def settrigcointime(self,cointime):\n #set the time self triggers are fired for (for coincidence purposes)\n if cointime<1 or cointime>255:\n print(\"must fire for 1-255 samples\")\n return\n if self.minfirmwareversion<20:\n print(\"must have firmware 20 or above to set coincidence time\")\n return\n self.ser.write(bytearray([149]))\n self.ser.write(bytearray([cointime]))\n print(\"Setting\", cointime, \"samples for coincident channels to fire in\")\n\n def writefirmchan(self,chan):\n theboard = num_board-1-int(chan/num_chan_per_board)\n chanonboard = chan%num_chan_per_board\n self.ser.write(bytearray([theboard*num_chan_per_board+chanonboard])) # the channels are numbered differently in the firmware\n\n def set_ext_trig_delay(self,delay):\n self.ser.write(bytearray([56,delay]))\n print(\"Set ext trig delay to\",delay)\n\n def donoselftrig(self):\n self.ser.write(bytearray([57]))\n self.noselftrig = not self.noselftrig\n print(\"Toggled no self trig for boards to\",self.noselftrig)\n\n def setdaclevelforchan(self,chan,level):\n if level>4096*2-1: \n print(\"level can't be bigger than 2**13-1=4096*2-1\")\n level=4096*2-1\n if level<0: \n print(\"level can't be less than 0\")\n level=0\n theboard = num_board-1-int(chan/num_chan_per_board)\n chanonboard = chan%num_chan_per_board\n self.setdac(chanonboard,level,theboard)\n self.chanlevel[chan]=level\n if self.db: print(\"DAC level set for channel\",chan,\"to\",level,\"which is chan\",chanonboard,\"on board\",theboard)\n \n def tellSPIsetup(self,what):\n time.sleep(.01) #pause to make sure other SPI writng is done\n self.ser.write(bytearray([131]))\n myb=bytearray.fromhex('06 10') #default \n #SPIsenddata[14:8]=7'h08;//Common mode bias voltages\n #SPIsenddata[7:0]=8'b00000000;//off //0x00\n #SPIsenddata[7:0]=8'b11111111;//on 0.45V //0xff\n #SPIsenddata[7:0]=8'b11001100;//on 0.9V //0xcc\n #SPIsenddata[7:0]=8'b10111011;//on 1.35V //0xbb\n if what==0: myb=bytearray.fromhex('08 00') #not connected, 0.9V\n if what==1: myb=bytearray.fromhex('08 ff') #0.45V\n if what==2: myb=bytearray.fromhex('08 dd') #0.75V\n if what==3: myb=bytearray.fromhex('08 cc') #0.9V\n if what==4: myb=bytearray.fromhex('08 99') #1.05V\n if what==5: myb=bytearray.fromhex('08 aa') #1.2V\n if what==6: myb=bytearray.fromhex('08 bb') #1.35V \n #SPIsenddata[14:8]=7'h06; //Clock Divide/Data Format/Test Pattern\n #SPIsenddata[7:0]=8'b01010000;//do test pattern in offset binary // 0x50\n #SPIsenddata[7:0]=8'b00010000;//do offset binary //0x10\n if what==10: myb=bytearray.fromhex('06 50') #test pattern output\n if what==11: myb=bytearray.fromhex('06 10') #offset binary output + no clock divide\n if what==12: myb=bytearray.fromhex('06 11') #offset binary output + divide clock by 2\n if what==13: myb=bytearray.fromhex('06 12') #offset binary output + divide clock by 4 \n if what==20: myb=bytearray.fromhex('04 00') #50 Ohm termination chA (default)\n if what==21: myb=bytearray.fromhex('05 00') #50 Ohm termination chB (default) \n if what==22: myb=bytearray.fromhex('04 1b') #150 Ohm termination chA\n if what==23: myb=bytearray.fromhex('05 1b') #150 Ohm termination chB\n if what==24: myb=bytearray.fromhex('04 24') #300 Ohm termination chA\n if what==25: myb=bytearray.fromhex('05 24') #300 Ohm termination chB\n if what==30: myb=bytearray.fromhex('01 02') #multiplexed, with chA first\n if what==31: myb=bytearray.fromhex('01 06') #multiplexed, with chB first\n if what==32: myb=bytearray.fromhex('01 00') # not multiplexed output \n self.ser.write(bytearray([myb[0]])) #write it!\n self.ser.write(bytearray([myb[1]])) #write it!\n print(\"tell SPI setup: 131 \",myb[0],myb[1])\n time.sleep(.01) #pause to make sure other SPI writng is done\n \n # testBit() returns a nonzero result, 2**offset, if the bit at 'offset' is one.\n def testBit(self,int_type, offset):\n mask = 1 << offset\n return(int_type & mask)\n # setBit() returns an integer with the bit at 'offset' set to 1.\n def setBit(self,int_type, offset):\n mask = 1 << offset\n return(int_type | mask)\n # clearBit() returns an integer with the bit at 'offset' cleared.\n def clearBit(self,int_type, offset):\n mask = ~(1 << offset)\n return(int_type & mask)\n # toggleBit() returns an integer with the bit at 'offset' inverted, 0 -> 1 and 1 -> 0.\n def toggleBit(self,int_type, offset):\n mask = 1 << offset\n return(int_type ^ mask)\n \n def sendi2c(self,whattosend,board=200):\n db2=False\n time.sleep(.02)\n myb=bytearray.fromhex(whattosend)\n self.ser.write(bytearray([136]))\n if db2: print(\" sendi2c: 136\")\n datacounttosend=len(myb)-1 #number of bytes of info to send, not counting the address\n self.ser.write(bytearray([datacounttosend]))\n if db2: print(datacounttosend)\n for b in np.arange(len(myb)): \n self.ser.write(bytearray([myb[b]]))\n if db2: print(myb[b])\n for b in np.arange(4-len(myb)): \n self.ser.write(bytearray([255])) # pad with extra bytes since the command expects a total of 5 bytes (numtosend, addr, and 3 more bytes)\n if db2: print(\"255\")\n self.ser.write(bytearray([int(board)])) #200 (default) will address message to all boards, otherwise only the given board ID will listen\n if db2: print(board,\"\\n\")\n if self.db or db2: print(\"Tell i2c:\",\"bytestosend:\",datacounttosend,\" and address/data:\",whattosend,\"for board\",board)\n time.sleep(.02)\n \n def setupi2c(self):\n self.sendi2c(\"20 00 00\") #port A on IOexp 1 are outputs\n self.sendi2c(\"20 01 00\") #port B on IOexp 1 are outputs\n self.sendi2c(\"21 00 00\") #port A on IOexp 2 are outputs\n self.sendi2c(\"20 12 \"+ ('%0*x' % (2,self.a20)) ) #port A of IOexp 1\n self.sendi2c(\"20 13 \"+ ('%0*x' % (2,self.b20)) ) #port B of IOexp 1\n self.sendi2c(\"21 12 \"+ ('%0*x' % (2,self.a21)) ) #port A of IOexp 2\n if self.minfirmwareversion<15:\n self.sendi2c(\"21 01 00\") #port B on IOexp 2 are outputs\n self.sendi2c(\"21 13 \"+ ('%0*x' % (2,self.b21)) ) #port B of IOexp 2\n else:\n self.sendi2c(\"21 01 ff\") #port B on IOexp 2 are inputs!\n self.sendi2c(\"21 0d ff\") #port B on IOexp 2 enable pull-up resistors!\n #print \"portB on IOexp2 are inputs now\"\n #print \"initialized all i2c ports and set to starting values\"\n \n def setdac(self,chan,val,board): \n if chan==0: c=\"50\"\n elif chan==1: c=\"52\"\n elif chan==2: c=\"54\"\n elif chan==3: c=\"56\"\n else:\n print(\"channel\",chan,\"out of range 0-3\")\n return \n if val>4096*2-1 or val<0:\n print(\"value\",val,\"out of range 0-(4096*2-1)\")\n return\n #d=\"0\" # Vdd ref (0-3.3V, but noisy?)\n d=\"8\" #internal ref, gain=1 (0-2V)\n if val>4095:\n d=\"9\" #internal ref, gain=2 (0-4V)\n val=int(val/2)\n self.sendi2c(\"60 \"+c+d+('%0*x' % (3,int(val))), int(board)) #DAC, can go from 000 to 0fff in last 12 bits, and only send to the selected board\n \n # example:\n # channel 0 , board 0 calib\n # 136, 3, // header for i2c command with 3 bytes of data\n # 96, // i2c address of dac\n # 80, // channel 80,82,84,86 for chan 0,1,2,3\n # 136, 22, // high 4 bits can be 8 or 9 (internal ref 2V or 4V, respectively), next 12 bits are the 0-4095 level\n # 0 // send to board 0 (200 for all boards)\n \n def shutdownadcs(self):\n self.b20= int('ff',16) # shdn (set first char to f to turn off) / ac coupling (?)\n self.sendi2c(\"20 13 \"+ ('%0*x' % (2,self.b20)) ) #port B of IOexp 1\n print(\"shut down adcs\")\n \n def testi2c(self):\n print(\"test i2c\")\n dotest=3 # what to test\n if dotest==0:\n # IO expander 1 \n self.sendi2c(\"20 12 ff\") #turn on all port A of IOexp 1 (12 means A, ff is which of the 8 bits to turn on)\n self.sendi2c(\"20 13 ff\") #turn on all port B of IOexp 1 (13 means B, ff is which of the 8 bits to turn on)\n time.sleep(3)\n self.sendi2c(\"20 12 00\") #turn off all port A of IOexp 1\n self.sendi2c(\"20 13 00\") #turn off all port B of IOexp 1\n elif dotest==1:\n #Test the DAC\n self.setdac(0,0,0)\n time.sleep(3)\n self.setdac(0,1200,0)\n elif dotest==2:\n #toggle led 3, at 0x21 a0\n self.a21=self.toggleBit(self.a21,3); self.sendi2c(\"21 12 \"+ ('%0*x' % (2,self.a21)) )\n elif dotest==3:\n #toggle pin E24 B7, at 0x21 b7\n self.b21=self.toggleBit(self.b21,7); self.sendi2c(\"21 13 \"+ ('%0*x' % (2,self.b21)) )\n \n def toggledousb(self):#toggle whether to read over FT232H USB or not\n if len(self.usbser)==0:\n self.dousb=False\n print(\"usb2 connection not available\")\n else:\n if self.dofastusb and self.minfirmwareversion<=17:\n print(\"Need firmware >17 for fastusb! Exiting!\")\n sys.exit(-17)\n self.dousb = not self.dousb\n self.ser.write(bytearray([137]))\n print(\"dousb toggled to\",self.dousb,\"and dofastusb is\",self.dofastusb,\"and dousbparallel is\",self.dousbparallel)\n self.telltickstowait()\n \n def togglehighres(self):#toggle whether to do highres averaging during downsampling or not\n self.ser.write(bytearray([143]))\n self.dohighres = not self.dohighres\n print(\"do highres is\",self.dohighres)\n \n def toggleuseexttrig(self):#toggle whether to use the external trigger input or not\n self.ser.write(bytearray([144]))\n self.useexttrig = not self.useexttrig\n print(\"useexttrig is\",self.useexttrig)\n \n def toggletriggerchan(self,tp):\n #tell it to trigger or not trigger on a given channel\n self.ser.write(bytearray([130]))\n self.writefirmchan(tp)\n self.trigsactive[tp] = not self.trigsactive[tp]\n if self.db: print(\"Trigger toggled for channel\",tp)\n\n def toggleautorearm(self):\n #tell it to toggle the auto rearm of the tirgger after readout\n self.ser.write(bytearray([139]))\n self.autorearm = not self.autorearm\n print(\"Trigger auto rearm now\",self.autorearm)\n if self.db: print(time.time()-self.oldtime,\"priming trigger\")\n self.ser.write(bytearray([100])) # prime the trigger one last time\n\n def toggle_clk_last(self):\n self.ser.write(bytearray([54]))\n print(\"Toggled clock output from the last board\")\n\n def toggle_allow_same_chan_coin(self):\n if self.minfirmwareversion<21:\n print(\"Need firmware 21 or greater to toggle allowance of same channel coincidence!\")\n self.ser.write(bytearray([150]))\n print(\"Toggled allow same channel coincidence\")\n\n def increment_clk_phase(self, board, times=1):\n if self.minfirmwareversion<17:\n print(\"incrementing clock phase requires firmware >=17\")\n return\n self.ser.write(bytearray([53,board]))\n for t in range(times): self.ser.write(bytearray([55]))\n print(\"Incremented clock phase on board\",board,times,\"time(s)\")\n\n def getIDs(self):\n debug3=True\n self.uniqueID=[]\n for board in range(num_board):\n if self.minfirmwareversion>=17:\n self.ser.write(bytearray([53, board])) # make the next board active (serial_passthrough 0)\n else:\n self.ser.write(bytearray([30 + board])) # make the next board active (serial_passthrough 0)\n self.ser.write(bytearray([142])) #request the unique ID\n num_other_bytes = 8\n rslt = self.ser.read(num_other_bytes)\n if len(rslt)==num_other_bytes:\n byte_array = unpack('%dB'%len(rslt),rslt) #Convert serial data to array of numbers\n self.uniqueID.append( ''.join(format(x, '02x') for x in byte_array) )\n if debug3: print(\"got uniqueID\",self.uniqueID[board],\"for board\",board,\", len is now\",len(self.uniqueID))\n else:\n print(\"getID asked for\",num_other_bytes,\"bytes and got\",len(rslt),\"from board\",board,\" - Exiting!\")\n sys.exit(-4)\n \n def togglesupergainchan(self,chan):\n if self.supergain[chan]==1:\n self.supergain[chan]=0 #x100 super gain on!\n else:\n self.supergain[chan]=1 #normal gain\n self.selectedchannel=chan\n self.setdacvalue()\n print(\"Supergain switched for channel\",chan,\"to\",self.supergain[chan])\n \n def tellswitchgain(self,chan):\n #tell it to switch the gain of a channel\n self.ser.write(bytearray([134]))\n self.writefirmchan(chan)\n if self.gain[chan]==1:\n self.gain[chan]=0 # x10 gain on!\n else:\n self.gain[chan]=1 #low gain\n self.selectedchannel=chan # needed for setdacvalue\n self.setdacvalue()\n print(\"Gain switched for channel\",chan,\"to\",self.gain[chan])\n\n def oversamp(self,chan):\n #tell it to toggle oversampling for this channel\n chanonboard = chan%num_chan_per_board\n if chanonboard>1: \n print(\"oversampling only allowed on channels 0 and 1 of a board\")\n return -1\n if chanonboard==1 and self.dooversample[chan] and self.dooversample[chan-1]==9:\n print(\"first disable over-oversampling on channel\",chan-1)\n return -2\n self.dooversample[chan] = not self.dooversample[chan]\n print(\"oversampling is now\",self.dooversample[chan],\"for channel\",chan)\n if self.dooversample[chan] and self.downsample>0: self.telldownsample(0) # must be in max sampling mode for oversampling to make sense\n self.ser.write(bytearray([141]))\n self.writefirmchan(chan)\n return 1\n \n def overoversamp(self):\n if self.selectedchannel%4: \n print(\"over-oversampling only for channel 0 of a board!\")\n return -1\n elif self.dooversample[self.selectedchannel]==0 or self.dooversample[self.selectedchannel+1]==0:\n print(\"for over-oversampling, first do oversampling on channels 0 and 1 of the board\")\n return -2\n elif self.dooversample[self.selectedchannel]==1:\n self.dooversample[self.selectedchannel]=9\n print(\"over-oversampling\")\n return 0\n elif self.dooversample[self.selectedchannel]==9:\n self.dooversample[self.selectedchannel]=1\n print(\"no more over-oversampling\")\n return 0\n\n def resetchans(self):\n for chan in np.arange(num_board*num_chan_per_board):\n if self.gain[chan]==0:\n self.tellswitchgain(chan) # set all gains back to low gain\n if self.trigsactive[chan]==0:\n self.toggletriggerchan(chan) # set all trigger channels back to active\n if self.dooversample[chan]: \n self.oversamp(chan) # set all channels back to no oversampling\n \n def setbacktoserialreadout(self):\n if self.dousb: \n self.ser.write(bytearray([137]))\n self.dousb=False\n print(\"dousb set back to\",self.dousb)\n \n def telldownsample(self,ds):\n #tell it the amount to downsample, log2... so 0 (none), 1(factor 2), 2(factor 4), etc.\n if self.dolockin and ds<2: print(\"downsample can't be <2 in lockin mode !\"); return False\n if ds<-8: print(\"downsample can't be <-8... that's too fast !\"); return False\n if ds<0: # negative downsample means just scale/zoom the data, don't actually change the sampling done on the board\n self.downsample=ds\n else:\n if max(self.dooversample)>0 and ds>0: print(\"can't change sampling rate while oversampling - must be fastest!\"); return False\n if ds>self.maxdownsample: print(\"downsample >\",self.maxdownsample,\"doesn't work well... I get bored running that slow!\"); return False \n self.ser.write(bytearray([124]))\n self.ser.write(bytearray([ds]))\n self.downsample=ds\n if self.db: print(\"downsample is\",self.downsample) \n if self.dolockin:\n twoforoversampling=1\n uspersample=(1.0/self.clkrate)*pow(2,self.downsample)/twoforoversampling # us per sample = 10 ns * 2^downsample\n numtoshiftf= 1.0/self.reffreq/4.0 / uspersample\n print(\"would like to shift by\",round(numtoshiftf,4),\"samples, and uspersample is\",uspersample)\n self.numtoshift = int(round(numtoshiftf,0))+0 # shift by 90 deg\n self.telllockinnumtoshift(self.numtoshift)\n else:\n self.telllockinnumtoshift(0) # tells the FPGA to not send lockin info \n self.telltickstowait()\n self.setxaxis()\n return True # successful (parameter within OK range)\n\n def setxaxis(self):\n self.xscale = self.num_samples/2.0*(1000.0*pow(2,self.downsample)/self.clkrate)\n if self.xscale<1e3: \n self.xlabel=\"Time (ns)\"\n self.min_x = -self.xscale\n self.max_x = self.xscale\n self.xscaling=1.e0\n elif self.xscale<1e6: \n self.xlabel=\"Time (us)\"\n self.min_x = -self.xscale/1.e3\n self.max_x = self.xscale/1.e3\n self.xscaling=1.e3\n else:\n self.xlabel=\"Time (ms)\"\n self.min_x = -self.xscale/1.e6\n self.max_x = self.xscale/1.e6\n self.xscaling=1.e6\n #print \"xscaling\",self.xscaling\n \n def setyaxis(self):\n #self.ax.set_ylim(self.min_y, self.max_y)\n self.ylabel=\"Volts\" #(\"ADC value\")\n \n def chantext(self):\n text =\"Channel: \"+str(self.selectedchannel)\n if self.ydatarefchan>=0: text += \" - ref \"+str(int(self.ydatarefchan))\n if self.domeasure and self.dodrawing:\n if abs(self.Vmean[self.selectedchannel])>.9: text +=\"\\nMean={0:1.3g} V\".format(self.Vmean[self.selectedchannel])\n else: text +=\"\\nMean={0:1.3g} mV\".format(1000.*self.Vmean[self.selectedchannel])\n if abs(self.Vrms[self.selectedchannel])>.9: text +=\"\\nRMS={0:1.3g} V\".format(self.Vrms[self.selectedchannel])\n else: text +=\"\\nRMS={0:1.3g} mV\".format(1000.*self.Vrms[self.selectedchannel]) \n if self.dogetotherdata:\n text+=\"\\nTDC: \"+str(self.tdcdata)\n return text\n \n def pickline(self,theline):\n # on the pick event, find the orig line corresponding to the\n # legend proxy line, and toggle the visibility\n origline,legline,channum = self.lined[theline]\n if self.db: print(\"picked\",theline,\"for channum\",channum)\n if hasattr(self,'selectedlegline'): \n if self.selectedorigline.get_visible(): self.selectedlegline.set_linewidth(2.0)\n else: self.selectedlegline.set_linewidth(1.0)\n legline.set_linewidth(4.0)\n self.selectedlegline=legline; self.selectedorigline=origline # remember them so we can set it back to normal later when we pick something else\n if channum < num_board*num_chan_per_board: # it's an ADC channel (not a max10adc channel or other thing)\n if self.db: print(\"picked a real ADC channel\")\n self.selectedchannel=channum\n if self.keyShift: self.toggletriggerchan(channum)\n else:\n if self.db: print(\"picked a max10 ADC channel\")\n self.selectedmax10channel=channum - num_board*num_chan_per_board\n \n def adjustvertical(self,up,amount=10): \n #print \"amount is\",amount\n if self.gain[self.selectedchannel]: amount*=10 #low gain\n if self.supergain[self.selectedchannel]==0 and self.acdc[self.selectedchannel]: amount=max(1,int(amount/10)) #super gain\n #print \"now amount is\",amount\n if up:\n self.chanlevel[self.selectedchannel] = self.chanlevel[self.selectedchannel] - amount\n else:\n self.chanlevel[self.selectedchannel] = self.chanlevel[self.selectedchannel] + amount\n self.rememberdacvalue()\n self.setdacvalue()\n \n def rememberdacvalue(self):\n #remember current dac level for the future to the right daclevel, depending on other settings\n if self.gain[self.selectedchannel]: # low gain\n if self.supergain[self.selectedchannel]: \n if self.acdc[self.selectedchannel]: self.lowdaclevel[self.selectedchannel]=self.chanlevel[self.selectedchannel]\n else: self.lowdaclevelac[self.selectedchannel]=self.chanlevel[self.selectedchannel]\n else: #supergain\n if self.acdc[self.selectedchannel]: self.lowdaclevelsuper[self.selectedchannel]=self.chanlevel[self.selectedchannel] #dc super gain\n else: self.lowdaclevelsuperac[self.selectedchannel]=self.chanlevel[self.selectedchannel]\n else: # high gain\n if self.supergain[self.selectedchannel]: \n if self.acdc[self.selectedchannel]: self.highdaclevel[self.selectedchannel]=self.chanlevel[self.selectedchannel]\n else: self.highdaclevelac[self.selectedchannel]=self.chanlevel[self.selectedchannel]\n else: #supergain\n if self.acdc[self.selectedchannel]: self.highdaclevelsuper[self.selectedchannel]=self.chanlevel[self.selectedchannel] #dc super gain\n else: self.highdaclevelsuperac[self.selectedchannel]=self.chanlevel[self.selectedchannel]\n \n def setdacvalue(self):\n #set current dac level to the remembered value, depending on other settings\n if self.gain[self.selectedchannel]: # low gain\n if self.supergain[self.selectedchannel]: \n if self.acdc[self.selectedchannel]: self.setdaclevelforchan(self.selectedchannel,self.lowdaclevel[self.selectedchannel])\n else: self.setdaclevelforchan(self.selectedchannel,self.lowdaclevelac[self.selectedchannel])\n else: #supergain\n if self.acdc[self.selectedchannel]: self.setdaclevelforchan(self.selectedchannel,self.lowdaclevelsuper[self.selectedchannel]) #dc super gain\n else: self.setdaclevelforchan(self.selectedchannel,self.lowdaclevelsuperac[self.selectedchannel])\n else: # high gain\n if self.supergain[self.selectedchannel]: \n if self.acdc[self.selectedchannel]: self.setdaclevelforchan(self.selectedchannel,self.highdaclevel[self.selectedchannel])\n else: self.setdaclevelforchan(self.selectedchannel,self.highdaclevelac[self.selectedchannel])\n else: #supergain\n if self.acdc[self.selectedchannel]: self.setdaclevelforchan(self.selectedchannel,self.highdaclevelsuper[self.selectedchannel]) #dc super gain\n else: self.setdaclevelforchan(self.selectedchannel,self.highdaclevelsuperac[self.selectedchannel])\n \n def setacdc(self):\n chan=self.selectedchannel\n theboard = num_board-1-int(chan/num_chan_per_board)\n chanonboard = chan%num_chan_per_board\n print(\"toggling acdc for chan\",chan,\"which is chan\",chanonboard,\"on board\",theboard)\n self.acdc[int(chan)] = not self.acdc[int(chan)]\n self.b20= int('00',16) # shdn (set first char to 0 to turn on) / ac coupling (set second char to f for DC, 0 for AC)\n for c in range(0,3):\n realchan = (num_board-1-theboard)*num_chan_per_board+c\n if self.acdc[int(realchan)]: \n self.b20 = self.toggleBit(self.b20,int(c)) # 1 is dc, 0 is ac\n if self.db: print(\"toggling bit\",c,\"for chan\",realchan)\n self.sendi2c(\"20 13 \"+ ('%0*x' % (2,self.b20)), theboard) #port B of IOexp 1, only for the selected board\n self.setdacvalue()\n \n def setdacvalues(self,sc):\n oldchan=self.selectedchannel\n for chan in range(sc,sc+4):\n self.selectedchannel=chan\n self.setdacvalue()\n self.selectedchannel=oldchan\n \n def storecalib(self):\n cwd = os.getcwd()\n print(\"current directory is\",cwd)\n for board in range(0,num_board):\n self.storecalibforboard(board)\n def storecalibforboard(self,board):\n sc = board*num_chan_per_board\n print(\"storing calibrations for board\",board,\", channels\",sc,\"-\",sc+4)\n c = dict(\n boardID=self.uniqueID[board],\n lowdaclevels=self.lowdaclevel[sc : sc+4].tolist(),\n highdaclevels=self.highdaclevel[sc : sc+4].tolist(),\n lowdaclevelssuper=self.lowdaclevelsuper[sc : sc+4].tolist(),\n highdaclevelssuper=self.highdaclevelsuper[sc : sc+4].tolist(),\n lowdaclevelsac=self.lowdaclevelac[sc : sc+4].tolist(),\n highdaclevelsac=self.highdaclevelac[sc : sc+4].tolist(),\n lowdaclevelssuperac=self.lowdaclevelsuperac[sc : sc+4].tolist(),\n highdaclevelssuperac=self.highdaclevelsuperac[sc : sc+4].tolist(),\n firmwareversion=self.minfirmwareversion\n )\n #print json.dumps(c,indent=4)\n fname = \"calib/calib_\"+self.uniqueID[board]+\".json.txt\"\n json.dump(c,open(fname,'w'),indent=4)\n print(\"wrote\",fname)\n \n def readcalib(self):\n cwd = os.getcwd()\n print(\"current directory is\",cwd)\n for board in range(0,num_board):\n self.readcalibforboard(board)\n def readcalibforboard(self,board):\n sc = board*num_chan_per_board\n if len(self.uniqueID)<=board:\n print(\"failed to get board ID for board\",board)\n self.setdacvalues(sc) #will load in defaults\n return\n print(\"reading calibrations for board\",board,\", channels\",sc,\"-\",sc+4)\n fname = \"calib/calib_\"+self.uniqueID[board]+\".json.txt\"\n try:\n c = json.load(open(fname))\n print(\"read\",fname)\n assert c['boardID']==self.uniqueID[board]\n self.lowdaclevel[sc : sc+4] = c['lowdaclevels']\n self.highdaclevel[sc : sc+4] = c['highdaclevels']\n self.lowdaclevelsuper[sc : sc+4] = c['lowdaclevelssuper']\n self.highdaclevelsuper[sc : sc+4] = c['highdaclevelssuper']\n self.lowdaclevelac[sc : sc+4] = c['lowdaclevelsac']\n self.highdaclevelac[sc : sc+4] = c['highdaclevelsac']\n self.lowdaclevelsuperac[sc : sc+4] = c['lowdaclevelssuperac']\n self.highdaclevelsuperac[sc : sc+4] = c['highdaclevelssuperac']\n if \"firmwareversion\" in c:\n print(\"calib was written using firmware version\",c[\"firmwareversion\"])\n else:\n print(\"calib was written using unknown firmware version\")\n self.setdacvalues(sc) #and use the new levels right away\n except IOError:\n print(\"No calib file found for board\",board,\"at file\",fname)\n self.setdacvalues(sc) #will load in defaults\n \n def decode(self):\n if not enable_ripyl:\n print(\"ripyl not enabled - install it and then set enable_ripyl to True at the top of HaasoscopeLibQt.py\")\n return\n raw_samples = self.xydata[self.selectedchannel][1] #ydata\n sample_period = (1e-6/self.clkrate)*pow(2,self.downsample)\n txd = stream.samples_to_sample_stream(raw_samples, sample_period)\n bits = 8 # anything, not just restricted to the standard 5,6,7,8,9\n parity = None # or 'odd' or None\n stop_bits = 1 # can be 1, 1.5, 2 or any non-standard value greater than 0.5\n polarity = uart.UARTConfig.IdleHigh # logic level when there's no data\n baud=1500000 # 115200 # baud rate -- can set to None if you want to try to determine it automatically!\n levels=(1.0,1.5) # the low and high logic levels\n dohex = False # print as hex (otherwise print as decimal)\n resulttext = []\n resultstart = []\n resultend = []\n try:\n records_it = uart.uart_decode(txd, bits, parity, stop_bits, polarity, baud_rate=baud, use_std_baud=False, logic_levels=levels)\n records = list(records_it) # This consumes the iterator and completes the decode\n for rec in records:\n if rec.nested_status() == stream.StreamStatus.Ok:\n #print(\"good chan\", self.selectedchannel, \"serial data found: \", rec.data)\n #print(rec.start_time, rec.end_time)\n if dohex: resulttext.append(hex(rec.data))\n else: resulttext.append(str(rec.data))\n resultstart.append(rec.start_time)\n resultend.append(rec.end_time)\n except stream.StreamError:\n print(\"No UART data found for channel\",self.selectedchannel)\n return resulttext,resultstart,resultend\n\n def on_running(self, theydata, board): #update data for main plot for a board\n if board<0: #hack to tell it the max10adc channel\n chantodraw=-board-1 #draw chan 0 first (when board=-1)\n posi=chantodraw+num_board*num_chan_per_board\n if self.db: print(time.time()-self.oldtime,\"drawing line\",posi)\n #if self.db: print \"ydata[0]=\",theydata[0]\n xdatanew=(self.xsampdata*((self.num_samples-1)/self.nsamp)-self.num_samples/2.+1)*(1000.0*pow(2,max(self.downsample,0))/self.clkrate/self.xscaling) #downsample isn't less than 0 for xscaling\n ydatanew=theydata*(3.3/256)#full scale is 3.3V\n self.xydataslow[chantodraw][0]=xdatanew\n self.xydataslow[chantodraw][1]=ydatanew\n else:\n if self.dologicanalyzer and self.logicline1>=0 and hasattr(self,\"ydatalogic\"): #this draws logic analyzer info\n xlogicshift=12.0/pow(2,max(self.downsample,0)) # shift the logic analyzer data to the right by this number of samples (to account for the ADC delay) #downsample isn't less than 0 for xscaling\n xdatanew = (self.xdata+xlogicshift-self.num_samples/2.)*(1000.0*pow(2,max(self.downsample,0))/self.clkrate/self.xscaling) #downsample isn't less than 0 for xscaling\n theboard = num_board - 1 - int(self.selectedchannel / num_chan_per_board)\n self.xydatalogicraw[theboard] = self.ydatalogic\n if board==theboard and self.dodrawing:\n b = np.unpackbits(self.ydatalogic)\n for l in np.arange(self.num_logic_inputs):\n bl=b[7-l::8] # every 8th bit, starting at 7-l\n ydatanew = bl*.3 + (l+1)*3.2/8. # scale it and shift it\n self.xydatalogic[l][0]=xdatanew\n self.xydatalogic[l][1]=ydatanew\n for l in np.arange(num_chan_per_board): #this draws the 4 fast ADC data channels for each board\n thechan=l+(num_board-board-1)*num_chan_per_board\n #if self.db: print time.time()-self.oldtime,\"drawing adc line\",thechan\n if len(theydata)<=l: print(\"don't have channel\",l,\"on board\",board); return\n showoversampled=True\n if self.dooversample[thechan]==1 and showoversampled: # account for oversampling\n xdatanew = (self.xdata2-self.num_samples)*(1000.0*pow(2,max(self.downsample,0))/self.clkrate/self.xscaling/2.) #downsample isn't less than 0 for xscaling\n theydata2=np.concatenate([theydata[l],theydata[l+2]]) # concatenate the 2 lists\n ydatanew=(127-theydata2)*(self.yscale/256.) # got to flip it, since it's a negative feedback op amp\n elif self.dooversample[thechan]==9 and showoversampled: # account for over-oversampling\n xdatanew = (self.xdata4-self.num_samples*2)*(1000.0*pow(2,max(self.downsample,0))/self.clkrate/self.xscaling/4.) #downsample isn't less than 0 for xscaling\n theydata4=np.concatenate([theydata[l],theydata[l+1],theydata[l+2],theydata[l+3]]) # concatenate the 4 lists\n ydatanew=(127-theydata4)*(self.yscale/256.) # got to flip it, since it's a negative feedback op amp\n else: # no oversampling\n xboardshift=(11.0*board/8.0)/pow(2,max(self.downsample,0)) # shift the board data to the right by this number of samples (to account for the readout delay) #downsample isn't less than 0 for xscaling\n xdatanew = (self.xdata-xboardshift-self.num_samples/2.)*(1000.0*pow(2,max(self.downsample,0))/self.clkrate/self.xscaling) #downsample isn't less than 0 for xscaling\n ydatanew=(127-theydata[l])*(self.yscale/256.) # got to flip it, since it's a negative feedback op amp\n if self.ydatarefchan>=0: ydatanew -= (127-theydata[self.ydatarefchan])*(self.yscale/256.) # subtract the board's reference channel ydata from this channel's ydata\n if self.average:\n numsamplestoaverage = 2\n ydatanew = np.repeat(\n np.mean(ydatanew.reshape(-1, numsamplestoaverage), axis=1),\n numsamplestoaverage)\n if self.sincresample>0:\n (ydatanew,xdatanew) = resample(ydatanew, len(xdatanew)*self.sincresample, t = xdatanew)\n xdatanew = xdatanew[1*self.sincresample:len(xdatanew)*self.sincresample]\n ydatanew = ydatanew[1*self.sincresample:len(ydatanew)*self.sincresample]\n else:\n xdatanew = xdatanew[1:len(xdatanew)]\n ydatanew = ydatanew[1:len(ydatanew)]\n if self.dooversample[thechan]==1 and showoversampled: # account for oversampling, take the middle-most section\n if self.sincresample>0:\n self.xydata[thechan][0]=xdatanew[self.sincresample+int(self.num_samples*self.sincresample/2):int(3*self.num_samples*self.sincresample/2):1] # for printing out or other analysis\n self.xydata[thechan][1]=ydatanew[self.sincresample+int(self.num_samples*self.sincresample/2):int(3*self.num_samples*self.sincresample/2):1]\n else:\n self.xydata[thechan][0]=xdatanew[int(1+self.num_samples/2):int(3*self.num_samples/2):1] # for printing out or other analysis\n self.xydata[thechan][1]=ydatanew[int(1+self.num_samples/2):int(3*self.num_samples/2):1]\n elif self.dooversample[thechan]==9 and showoversampled: # account for over-oversampling, take the middle-most section\n if self.sincresample>0:\n self.xydata[thechan][0]=xdatanew[self.sincresample+int(3*self.num_samples*self.sincresample/2):int(5*self.num_samples*self.sincresample/2):1] # for printing out or other analysis\n self.xydata[thechan][1]=ydatanew[self.sincresample+int(3*self.num_samples*self.sincresample/2):int(5*self.num_samples*self.sincresample/2):1]\n else:\n self.xydata[thechan][0]=xdatanew[int(1+3*self.num_samples/2):int(5*self.num_samples/2):1] # for printing out or other analysis\n self.xydata[thechan][1]=ydatanew[int(1+3*self.num_samples/2):int(5*self.num_samples/2):1]\n else: # the full data is stored\n self.xydata[thechan][0]=xdatanew # for printing out or other analysis\n self.xydata[thechan][1]=ydatanew\n if self.domeasure and self.dodrawing:\n self.Vmean[thechan] = np.mean(ydatanew)\n self.Vrms[thechan] = np.sqrt(np.mean((ydatanew-self.Vmean[thechan])**2))\n gain=1\n if self.gain[thechan]==0: gain*=10\n if self.supergain[thechan]==0: gain*=100\n if gain>1:\n self.Vmean[thechan]/=gain\n self.Vrms[thechan]/=gain \n if self.fitline1>-1 and thechan==0: # optional risetime fit for channel 0\n def fit_rise(x,a,bottom,b,top): # a function for fitting to find risetime\n val=bottom+(x-a)*(top-bottom)/(b-a)\n inbottom=(x<=a)\n val[inbottom]=bottom\n intop=(x>=b)\n val[intop]=top\n return val\n try:\n x2=xdatanew[(xdatanew>-.1) & (xdatanew<.1)] # only fit in range -.1 to .1 (us)\n y2=ydatanew[(xdatanew>-.1) & (xdatanew<.1)]\n popt, pcov = scipy.optimize.curve_fit(fit_rise,x2,y2,bounds=([-.1,-4,-0.05,0],[0.05,0,.1,4])) #and note these bounds - top must be>0 and bottom<0 !\n self.lines[self.fitline1].set_xdata(x2)\n self.lines[self.fitline1].set_ydata( fit_rise(x2, *popt) )\n print(\"risetime = \",1000*0.8*(popt[2]-popt[0]),\"ns\") # from 10-90% is 0.8 on the line - don't forget to correct for x2 or x4 oversampling!\n except:\n print(\"fit exception!\")\n if self.doxyplot and (thechan==self.xychan or thechan==(self.xychan+1)): self.drawxyplot(xdatanew,ydatanew,thechan)# the xy plot\n if self.recorddata and thechan==self.recorddatachan: self.dopersistplot(xdatanew,ydatanew)# the persist shaded plot\n if thechan==self.refsinchan-1 and self.reffreq==0: self.oldchanphase=-1.; self.fittosin(xdatanew, ydatanew, thechan) # first fit the previous channel, for comparison\n elif thechan==self.refsinchan and self.reffreq==0: self.reffreq = self.fittosin(xdatanew, ydatanew, thechan) # then fit for the ref freq and store the result\n if self.autocalibchannel>=0 and thechan==self.autocalibchannel: self.autocalibrate(thechan,ydatanew)\n \n def fittosin(self,xdatanew, ydatanew, chan):\n res = self.fit_sin(xdatanew, ydatanew)\n phase=res['phase']*180./np.pi\n if res['amp']<0.: phase+=180.\n print(\"Chan:\",chan, \"cov=\",res['maxcov'], \"amp=\",abs(res['amp']), \"phase=\",phase, \"offset=\", res['offset'], res['freq']*1000000./self.xscaling,'kHz')\n if res['maxcov']<1e-4:\n if self.oldchanphase>=0.: \n diff=phase-self.oldchanphase\n if diff<0: diff+=360\n print(\"phase diff=\",diff)\n self.oldchanphase=phase\n return res['freq']\n else: print(\"sin fit failed!\"); return 0;\n \n #For finding the frequency of a reference sin wave signal, for lockin calculations\n def fit_sin(self,tt, yy):\n '''Fit sin to the input time sequence, and return fitting parameters \"amp\", \"omega\", \"phase\", \"offset\", \"freq\", \"period\" and \"fitfunc\"'''\n tt = np.array(tt)\n yy = np.array(yy)\n ff = np.fft.fftfreq(len(tt), (tt[1]-tt[0])) # assume uniform spacing\n Fyy = abs(np.fft.fft(yy))\n guess_freq = abs(ff[np.argmax(Fyy[1:])+1]) # excluding the zero frequency \"peak\", which is related to offset\n guess_amp = np.std(yy) * 2.**0.5\n guess_offset = np.mean(yy)\n guess = np.array([guess_amp, 2.*np.pi*guess_freq, 0., guess_offset])\n \n def sinfunc(t, A, w, p, c): return A * np.sin(w*t + p) + c\n popt, pcov = scipy.optimize.curve_fit(sinfunc, tt, yy, p0=guess)\n A, w, p, c = popt\n f = w/(2.*np.pi)\n fitfunc = lambda t: A * np.sin(w*t + p) + c\n return {\"amp\": A, \"omega\": w, \"phase\": p, \"offset\": c, \"freq\": f, \"period\": 1./f, \"fitfunc\": fitfunc, \"maxcov\": np.max(pcov), \"rawres\": (guess,popt,pcov)}\n \n def autocalibrate(self,thechan,ydatanew):\n self.selectedchannel=thechan\n avg = np.average(ydatanew)\n #print avg\n gotonext=False\n tol = 1.0\n tol2 = 0.25\n if self.supergain[self.selectedchannel] or self.gain[self.selectedchannel]: # normal gain or low gain\n tol = 0.3\n tol2 = 0.02\n if avg>0+tol: \n self.adjustvertical(False,10)\n elif avg<0-tol:\n self.adjustvertical(True,10)\n elif avg>0+tol2:\n self.adjustvertical(False,1)\n elif avg<0-tol2:\n self.adjustvertical(True,1)\n else: gotonext=True\n if self.chanlevel[self.selectedchannel]==0: gotonext=True\n if gotonext:\n #go to the next channel, unless we're at the end of all channels\n self.autocalibchannel=self.autocalibchannel+1\n if self.autocalibchannel==num_chan_per_board*num_board:\n self.autocalibgainac=self.autocalibgainac+1\n if self.autocalibgainac==1:\n self.autocalibchannel=0\n for chan in range(num_chan_per_board*num_board):\n self.selectedchannel=chan\n self.setacdc()\n elif self.autocalibgainac==2:\n self.autocalibchannel=0\n for chan in range(num_chan_per_board*num_board):\n self.selectedchannel=chan\n self.tellswitchgain(chan)\n elif self.autocalibgainac==3:\n self.autocalibchannel=0\n for chan in range(num_chan_per_board*num_board):\n self.selectedchannel=chan\n self.setacdc()\n else:\n self.autocalibchannel=-1 #all done\n self.autocalibgainac=0\n for chan in range(num_chan_per_board*num_board):\n self.selectedchannel=chan\n self.tellswitchgain(chan)\n if self.minfirmwareversion<15: self.togglesupergainchan(chan)\n print(\"done with autocalibration \\a\") # beep!\n \n doxyplot=False\n drawnxy=False\n xychan=0\n def drawxyplot(self,xdatanew,ydatanew,thechan):\n if thechan==self.xychan: self.xydataforxaxis=ydatanew #the first channel will define the info on the x-axis\n if thechan==(self.xychan+1):\n if not self.drawnxy: # got to make the plot window the first time\n #self.figxy, self.axxy = plt.subplots(1,1)\n self.figxy.canvas.mpl_connect('close_event', self.handle_xy_close)\n self.drawnxy=True\n self.figxy.set_size_inches(6, 6, forward=True)\n self.xyplot, = self.axxy.plot(self.xydataforxaxis,ydatanew) #scatter\n self.figxy.canvas.set_window_title('XY display of channels '+str(self.xychan)+' and '+str(self.xychan+1))\n self.axxy.set_xlabel('Channel '+str(self.xychan)+' Volts')\n self.axxy.set_ylabel('Channel '+str(self.xychan+1)+' Volts')\n self.axxy.set_xlim(self.min_y, self.max_y)\n self.axxy.set_ylim(self.min_y, self.max_y)\n self.axxy.grid()\n #redraw the plot\n self.figxy.canvas.set_window_title('XY display of channels '+str(self.xychan)+' and '+str(self.xychan+1))\n self.axxy.set_xlabel('Channel '+str(self.xychan)+' Volts')\n self.axxy.set_ylabel('Channel '+str(self.xychan+1)+' Volts')\n self.xyplot.set_data(self.xydataforxaxis, ydatanew)\n self.figxy.canvas.draw()\n \n recorddata=False\n recordindex=0 # for recording data, the last N events, for the shaded persist display window\n recordedchannel=[]\n def dopersistplot(self,xdatanew,ydatanew):\n self.min_x=xdatanew[0]; self.max_x=xdatanew[-1]\n if len(self.recordedchannel)<=self.recordindex: self.recordedchannel.append(ydatanew)\n else: self.recordedchannel[self.recordindex]=ydatanew\n self.recordindex+=1\n self.recorded2d,xaxes,yaxes = np.histogram2d( np.tile(xdatanew,len(self.recordedchannel)), np.concatenate(tuple(self.recordedchannel)), bins=[int(self.num_samples-1),int(256)], range=[[self.min_x,self.max_x],[self.min_y,self.max_y]] )\n if self.recordindex>=self.recordedchannellength:\n self.recordindex=0\n \n def plot_fft(self,bn): # pass in the board number\n channumonboard = self.fftchan%num_chan_per_board # this is what channel (0--3) we want to draw fft from for the board\n chanonboardnum = num_board - int(self.fftchan/num_chan_per_board) - 1 # this is what board (0 -- (num_board-1)) we want to draw that fft channel from\n if bn==chanonboardnum: # select the right board check that the channel data is really there\n twoforoversampling=1\n if self.dooversample[self.fftchan]==1: twoforoversampling=2\n if self.dooversample[self.fftchan]==9: twoforoversampling=4\n y = self.xydata[self.fftchan][1] # channel signal to take fft of\n n = len(y) # length of the signal\n k = np.arange(n)\n uspersample=(1.0/self.clkrate)*pow(2,max(self.downsample,0))/twoforoversampling # us per sample = 10 ns * 2^downsample, #downsample isn't less than 0 for xscaling\n #t = np.arange(0,1,1.0/n) * (n*uspersample) # time vector in us\n frq = (k/uspersample)[list(range(int(n/2)))]/n # one side frequency range up to Nyquist\n Y = np.fft.fft(y)[list(range(int(n/2)))]/n # fft computing and normalization\n Y[0]=0 # to suppress DC\n if np.max(frq)<.001:\n self.fftfreqplot_xdata = frq*1000000.0\n self.fftax_xlabel = 'Freq (Hz)'\n self.fftax_xlim = 1000000.0*frq[int(n/2)-1]\n elif np.max(frq)<1.0:\n self.fftfreqplot_xdata = frq*1000.0\n self.fftax_xlabel = 'Freq (kHz)'\n self.fftax_xlim = 1000.0*frq[int(n/2)-1]\n else:\n self.fftfreqplot_xdata = frq\n self.fftax_xlabel = 'Freq (MHz)'\n self.fftax_xlim = frq[int(n/2)-1]\n self.fftfreqplot_ydata = abs(Y)\n self.fftfreqplot_ydatamax = np.max(abs(Y))\n\n lockindrawn=False\n def plot_lockin(self):\n trange=100\n t=np.arange(trange)\n if not self.lockindrawn: # just the first time, do some setup\n self.lockiny1=np.zeros(trange)\n self.lockiny2=np.zeros(trange)\n if self.debuglockin: self.lockiny1o=np.zeros(trange) # offline float calculation\n if self.debuglockin: self.lockiny2o=np.zeros(trange) # offline float calculation\n self.lockindrawn=True\n #self.lockinfig, self.lockinax = plt.subplots(2,1)\n self.lockinfig.canvas.set_window_title('Lockin of channel '+str(2)+\" wrt \"+str(3))\n self.lockinfig.canvas.mpl_connect('close_event', self.handle_lockin_close)\n\n self.lockinamplplot, = self.lockinax[0].plot(t,self.lockiny1) # plotting the amplitude\n self.lockinax[0].set_xlabel(' ')\n self.lockinax[0].set_ylabel('Amplitude')\n self.lockinphaseplot, = self.lockinax[1].plot(t,self.lockiny2) # plotting the phase\n self.lockinax[1].set_xlabel(' ')\n self.lockinax[1].set_ylabel('Phase')\n if self.debuglockin:\n self.lockinamplploto, = self.lockinax[0].plot(t,self.lockiny1o)# offline float calculation\n self.lockinphaseploto, = self.lockinax[1].plot(t,self.lockiny2o)# offline float calculation\n self.lockinfig.tight_layout()\n else: # redrawing\n self.lockiny1=np.roll(self.lockiny1,-1)\n self.lockiny2=np.roll(self.lockiny2,-1)\n if hasattr(self,'lockinamp'):\n self.lockiny1[trange-1]=self.lockinamp\n self.lockiny2[trange-1]=self.lockinphase\n if self.debuglockin:\n self.lockiny1o=np.roll(self.lockiny1o,-1)\n self.lockiny2o=np.roll(self.lockiny2o,-1)\n self.lockiny1o[trange-1]=self.lockinampo\n self.lockiny2o[trange-1]=self.lockinphaseo\n self.lockinamplploto.set_ydata(self.lockiny1o)\n self.lockinphaseploto.set_ydata(self.lockiny2o)\n self.lockinamplplot.set_xdata(t)\n self.lockinphaseplot.set_xdata(t)\n self.lockinamplplot.set_ydata(self.lockiny1)\n self.lockinphaseplot.set_ydata(self.lockiny2)\n self.lockinfig.canvas.set_window_title('Lockin of channel '+str(2)+\" wrt \"+str(3))\n\n def getotherdata(self,board):\n debug3=False\n self.ser.write(bytearray([132])) #delay counter\n num_other_bytes = 1\n rslt = self.ser.read(num_other_bytes)\n if len(rslt)==num_other_bytes:\n byte_array = unpack('%dB'%len(rslt),rslt) #Convert serial data to array of numbers\n if debug3: print(\"\\n delay counter data\",byte_array[0],\"from board\",board)\n self.tdcdata=byte_array[0]\n #if debug3: print \"other data\",bin(byte_array[0])\n else: print(\"getotherdata asked for\",num_other_bytes,\"delay counter bytes and got\",len(rslt))\n self.ser.write(bytearray([133])) #carry counter\n num_other_bytes = 1\n rslt = self.ser.read(num_other_bytes)\n if len(rslt)==num_other_bytes:\n byte_array = unpack('%dB'%len(rslt),rslt) #Convert serial data to array of numbers\n if debug3: print(\" carry counter data\",byte_array[0],\"from board\",board)\n #if debug3: print \"other data\",bin(byte_array[0])\n else: print(\"getotherdata asked for\",num_other_bytes,\"carry counter bytes and got\",len(rslt))\n \n def to_int(self,n): # takes a 32 bit decimal number in two's complement and converts to a binary and then to a signed integer\n bin = '{0:32b}'.format(n)\n x = int(bin, 2)\n if bin[0] == '1': # \"sign bit\", big-endian\n x -= 2**len(bin)\n return x\n \n def lockinanalyzedata(self,board):\n if self.lockinanalyzedataboard!=board: return False\n y2 = self.ydata[2] # channel 2 signal\n y3 = self.ydata[3] # channel 3 signal\n meany2=np.sum(y2)/self.num_samples\n meany3=np.sum(y3)/self.num_samples\n y2 = y2-meany2\n y3 = y3-meany3\n y3shifted = np.roll(y3,self.numtoshift)\n res1=y2*y3\n res2=y2*y3shifted\n r1m=np.sum(res1)\n r2m=np.sum(res2)\n #print r1m,r2m\n r1m/=4096.\n r2m/=4096.\n ampl = np.sqrt(r1m*r1m+r2m*r2m)\n phase = 180.*np.arctan2(r2m,r1m)/np.pi\n if self.debuglockin:\n print(\"no window: \",r1m.round(2), r2m.round(2), self.numtoshift, meany2.round(1),meany3.round(1))\n print(ampl.round(2), phase.round(2), \"<------ offline no window\")\n lowerwindowedge = self.numtoshift+1\n upperwindowedge = self.num_samples-self.numtoshift\n if self.debuglockin:\n self.ydata[0]= y3shifted+127 # to see on screen, alter self.ydata here\n self.ydata[0][0:lowerwindowedge] = np.zeros((lowerwindowedge,), dtype=np.int)+127\n self.ydata[0][upperwindowedge:self.num_samples] = np.zeros((self.num_samples-upperwindowedge,), dtype=np.int)+127\n y2window = y2[lowerwindowedge:upperwindowedge]\n y3window = y3[lowerwindowedge:upperwindowedge]\n y3shiftedwindow = y3shifted[lowerwindowedge:upperwindowedge]\n res1window=y2window*y3window\n res2window=y2window*y3shiftedwindow\n r1mwindow=np.sum(res1window)\n r2mwindow=np.sum(res2window)\n if self.debuglockin: print(\"window:\",r1mwindow,r2mwindow)\n r1mwindow/=4096.\n r2mwindow/=4096.\n amplwindow = np.sqrt(r1mwindow*r1mwindow+r2mwindow*r2mwindow)\n phasewindow = 180.*np.arctan2(r2mwindow,r1mwindow)/np.pi\n if self.debuglockin:\n print(\"with window:\",r1mwindow.round(2), r2mwindow.round(2), self.numtoshift, meany2.round(1),meany3.round(1))\n print(amplwindow.round(2), phasewindow.round(2), \"<------ offline with window\")\n meany2float=np.mean(self.ydata[2])\n meany3float=np.mean(self.ydata[3])\n y3shiftedfloat = np.roll(self.ydata[3]-meany3float,self.numtoshift)\n y2windowfloat = self.ydata[2][lowerwindowedge:upperwindowedge]-meany2float\n y3windowfloat = self.ydata[3][lowerwindowedge:upperwindowedge]-meany3float\n y3shiftedwindowfloat = y3shiftedfloat[lowerwindowedge:upperwindowedge]\n res1windowfloat=y2windowfloat*y3windowfloat\n res2windowfloat=y2windowfloat*y3shiftedwindowfloat\n r1mwindowfloat=np.sum(res1windowfloat)\n r2mwindowfloat=np.sum(res2windowfloat)\n #print \"windowfloat:\",r1mwindowfloat,r2mwindowfloat\n r1mwindowfloat/=4096.\n r2mwindowfloat/=4096.\n amplwindowfloat = np.sqrt(r1mwindowfloat*r1mwindowfloat+r2mwindowfloat*r2mwindowfloat)\n phasewindowfloat = 180.*np.arctan2(r2mwindowfloat,r1mwindowfloat)/np.pi\n if self.debuglockin:\n print(\"float with window:\",r1mwindowfloat.round(2), r2mwindowfloat.round(2), self.numtoshift, meany2.round(1),meany3.round(1))\n print(amplwindowfloat.round(2), phasewindowfloat.round(2), \"<------ offline with window float\\n\")\n self.lockinampo = amplwindowfloat\n self.lockinphaseo = phasewindowfloat\n\n def getlockindata(self,board):\n rslt = self.ser.read(16)\n byte_array = unpack('%dB'%len(rslt),rslt) #Convert serial data to array of numbers\n if len(rslt)==16:\n r1_fpga = (256*256*256*byte_array[3]+256*256*byte_array[2]+256*byte_array[1]+byte_array[0])\n r2_fpga = (256*256*256*byte_array[7]+256*256*byte_array[6]+256*byte_array[5]+byte_array[4])\n r1_fpga = self.to_int(r1_fpga)\n r2_fpga = self.to_int(r2_fpga)\n mean_c2 = (256*256*256*byte_array[11]+256*256*byte_array[10]+256*byte_array[9]+byte_array[8])\n mean_c3 = (256*256*256*byte_array[15]+256*256*byte_array[14]+256*byte_array[13]+byte_array[12])\n if self.debuglockin:\n print(byte_array[0:4], r1_fpga)\n print(byte_array[4:8], r2_fpga)\n print(byte_array[8:12], mean_c2)\n print(byte_array[12:16], mean_c3)\n r1_fpga/=4096.\n r2_fpga/=4096.\n ampl_fpga = np.sqrt(r1_fpga*r1_fpga+r2_fpga*r2_fpga)\n phase_fpga = 180.*np.arctan2(r2_fpga,r1_fpga)/np.pi\n if self.lockinanalyzedataboard==board:\n self.lockinamp = ampl_fpga\n self.lockinphase = phase_fpga\n if False:\n print(ampl_fpga.round(2), phase_fpga.round(2), \"<------ fpga \")\n else: print(\"getlockindata asked for\",16,\"lockin bytes and got\",len(rslt),\"from board\",board)\n\n usbsermap=[]\n def makeusbsermap(self): # figure out which board is connected to which USB 2 connection\n self.usbsermap= -1 * np.ones(num_board, dtype=int)\n if len(self.usbser)<num_board:\n print(\"There are only\",len(self.usbser),\"USB2 connections but\",num_board,\"boards requested!\")\n return False\n if self.dofastusb: padding = self.fastusbpadding\n else: padding = 0\n if len(self.usbser)>0:\n for usb in np.arange(len(self.usbser)):\n if self.dofastusb and useftd2xx: self.usbser[usb].setTimeouts(50,1000)\n else: self.usbser[usb].timeout=.25 # lower the timeout on the connections, temporarily\n foundusbs=[]\n self.ser.write(bytearray([100])) # prime the trigger (for all boards)\n for bn in range(num_board):\n if self.minfirmwareversion>=17:\n self.ser.write(bytearray([51,bn]))\n else:\n self.ser.write(bytearray([10+bn]))\n foundit=False\n time.sleep(0.25) #wait for an event to happen, which should be 0.2s (5 Hz rolling trigger)\n for usb in range(len(self.usbser)):\n if not usb in foundusbs: # it's not already known that this usb connection is assigned to a board\n try:\n #print(time.time() - self.oldtime, \"trying usb\", usb)\n bwant = self.num_bytes+padding*num_chan_per_board\n if useftd2xx or not self.dofastusb: rslt = self.usbser[usb].read(bwant) # try to get data from the board\n elif useftdi: rslt = self.usbser[usb].read_data_bytes(bwant, ftdiattempts)\n except ftd.DeviceError as msgnum:\n print(\"Error reading from USB2\", usb, msgnum)\n return\n if len(rslt)==self.num_bytes+padding*num_chan_per_board:\n print(time.time() - self.oldtime,\" got the right nbytes for board\",bn,\"from usb\",usb)\n self.usbsermap[bn]=usb\n foundusbs.append(usb) # remember that we already have figured out which board this usb connection is for, so we don't bother trying again for another board\n foundit=True\n if self.domt:\n self.usbser[usb].close()\n #print(\"sending usb number to process\")\n self.parent_conn[bn].send(self.usbsern[usb])\n #print(\"waiting for response from process\")\n msg = self.parent_conn[bn].recv()\n if msg != \"OK\": print(\"pro_\", bn, \"said\", msg)\n if self.checkfastusbwriting:\n rsltslow = self.ser.read(int(self.num_bytes)) # to cross-check the readout\n print(\"got\", len(rsltslow), \"bytes from slow serial readout\")\n break # already found which board this usb connection is used for, so bail out\n #else: print(time.time() - self.oldtime,\" got the wrong nbytes\",len(rslt),\"for board\",bn,\"from usb\",usb)\n #else: print(\" already know what usb\",usb,\"is for\")\n if not foundit:\n print(\"could not find usb2 connection for board\",bn)\n return False\n if not self.domt:\n for usb in range(len(self.usbser)):\n if self.dofastusb and useftd2xx: self.usbser[usb].setTimeouts(1000, 1000)\n else: self.usbser[usb].timeout=self.sertimeout # put back the timeout on the connections\n print(\"usbsermap is\",self.usbsermap)\n return True\n\n timedout = False\n def getdata(self,board):\n if not self.dousb or not self.dousbparallel:\n if self.minfirmwareversion>=17:\n self.ser.write(bytearray([51,board]))\n else:\n self.ser.write(bytearray([10 + board]))\n if self.db: print(time.time()-self.oldtime,\"asked for data from board\",board)\n if self.dolockin: self.getlockindata(board)\n padding = 0\n endpadding = 0\n if self.dousb:\n try:\n #self.ser.write(bytearray([40+board])) # for debugging timing, does nuttin\n if self.dofastusb:\n padding = self.fastusbpadding\n endpadding = self.fastusbendpadding\n nb=int((self.num_bytes+padding*num_chan_per_board))\n #for n in range(0,4):\n if self.db: print(time.time() - self.oldtime, \"read data from board\",board,\"nb\",nb)\n if useftd2xx: rslt = self.usbser[self.usbsermap[board]].read(nb)#,cache=True)\n elif useftdi: rslt = self.usbser[self.usbsermap[board]].read_data_bytes(nb,ftdiattempts)\n if self.db: print(time.time() - self.oldtime, \"read data from board\",board,\"done\")\n if not self.dologicanalyzer and useftd2xx and not self.flyingfast:\n nq = self.usbser[self.usbsermap[board]].getQueueStatus()\n if nq > 0:\n print(nq, \"bytes still available for usb on board\", board, \"...purging\")\n if useftd2xx: self.usbser[self.usbsermap[board]].purge(ftd.defines.PURGE_RX)\n elif useftdi: self.usbser[self.usbsermap[board]].purge_rx_buffer()\n if self.checkfastusbwriting:\n rsltslow = self.ser.read(int(self.num_bytes)) # to cross-check the readout\n #print(\"got\",len(rsltslow),\"bytes from slow serial readout\")\n else:\n rslt = self.usbser[self.usbsermap[board]].read(self.num_bytes)\n # self.ser.write(bytearray([40+board])) # for debugging timing, does nuttin\n except ftd.DeviceError as msgnum:\n print(\"Error reading from USB2\", self.usbsermap[board], msgnum)\n return\n else:\n rslt = self.ser.read(int(self.num_bytes))\n if self.flyingfast: return\n if self.db: print(time.time()-self.oldtime,\"getdata wanted\",self.num_bytes+padding*num_chan_per_board,\"bytes and got\",len(rslt),\"from board\",board)\n if len(rslt)==self.num_bytes+padding*num_chan_per_board:\n self.timedout = False\n #byte_arrayold = unpack('%dB' % len(rslt), rslt) # Convert serial data to array of numbers\n #self.ydataold=np.reshape(byte_arrayold,(num_chan_per_board,self.num_samples)) #slow!\n self.ydata=[ np.frombuffer(rslt,dtype=np.int8,count=self.num_samples,offset=0*self.num_samples+1*padding-endpadding), #need the int8 type because we'll later subtract it from 127 to flip it over\n np.frombuffer(rslt,dtype=np.int8,count=self.num_samples,offset=1*self.num_samples+2*padding-endpadding),\n np.frombuffer(rslt,dtype=np.int8,count=self.num_samples,offset=2*self.num_samples+3*padding-endpadding),\n np.frombuffer(rslt,dtype=np.int8,count=self.num_samples,offset=3*self.num_samples+4*padding-endpadding) ]\n if self.checkfastusbwriting:\n self.yrsltslow = [np.frombuffer(rsltslow, dtype=np.int8, count=self.num_samples,offset=0 * self.num_samples),\n np.frombuffer(rsltslow, dtype=np.int8, count=self.num_samples,offset=1 * self.num_samples),\n np.frombuffer(rsltslow, dtype=np.int8, count=self.num_samples,offset=2 * self.num_samples),\n np.frombuffer(rsltslow, dtype=np.int8, count=self.num_samples,offset=3 * self.num_samples)]\n for c in range(num_chan_per_board):\n if (self.ydata[c][1:len(self.ydata[c])] == self.yrsltslow[c][1:len(self.yrsltslow[c])]).all():\n pass\n #print(\"yrsltslow crosscheck for channel\",c,\"passed\")\n else:\n print(\"yrsltslow crosscheck for channel\",c,\"failed!\")\n print(self.ydata[c])\n print(self.yrsltslow[c])\n #print(127-self.ydataold[0])\n #print(127-self.ydata[0])\n #self.ser.write(bytearray([40 + board])) # for debugging timing, does nuttin\n if self.dooversample[num_chan_per_board*(num_board-board-1)]: self.oversample(0,2)\n if self.dooversample[num_chan_per_board*(num_board-board-1)+1]: self.oversample(1,3)\n if self.dooversample[num_chan_per_board*(num_board-board-1)]==9: self.overoversample(0,1)\n else:\n self.timedout = True\n if not self.db and self.rollingtrigger: print(\"getdata asked for\",self.num_bytes,\"bytes and got\",len(rslt),\"from board\",board)\n if self.dologicanalyzer:\n #get extra logic analyzer data, if needed\n logicbytes=int(self.num_bytes/num_chan_per_board)\n if self.dousb:\n try:\n if self.dofastusb:\n padding = self.fastusbpadding\n endpadding = self.fastusbendpadding\n nb = logicbytes + padding\n if useftd2xx: rslt = self.usbser[self.usbsermap[board]].read(nb)#,cache=True)\n elif useftdi: rslt = self.usbser[self.usbsermap[board]].read_data_bytes(nb,ftdiattempts)\n if useftd2xx:\n nq = self.usbser[self.usbsermap[board]].getQueueStatus()\n if nq > 0:\n print(nq, \"bytes still available for usb on board\", board, \"...purging\")\n self.usbser[self.usbsermap[board]].purge(ftd.defines.PURGE_RX)\n else:\n rslt = self.usbser[self.usbsermap[board]].read(logicbytes)\n except ftd.DeviceError as msgnum:\n print(\"Error reading from USB2\", self.usbsermap[board], msgnum)\n return\n else:\n rslt = self.ser.read(logicbytes)\n if self.db: print(time.time()-self.oldtime,\"getdata wanted\",logicbytes,\"logic bytes and got\",len(rslt),\"from board\",board)\n if len(rslt)==logicbytes+padding:\n self.ydatalogic=np.frombuffer(rslt,dtype=np.uint8,count=self.num_samples,offset=padding-endpadding)\n else:\n if not self.db and self.rollingtrigger: print(\"getdata asked for\",logicbytes,\"logic bytes and got\",len(rslt),\"from board\",board)\n\n def oversample(self,c1,c2):\n tempc1=127-self.ydata[c1]\n tempc2=127-self.ydata[c2]\n adjustmeanandrms=True\n if adjustmeanandrms:\n mean_c1 = np.mean(tempc1)\n rms_c1 = np.sqrt(np.mean((tempc1-mean_c1)**2))\n mean_c2 = np.mean(tempc2)\n rms_c2 = np.sqrt(np.mean((tempc2-mean_c2)**2))\n meanmean=(mean_c1+mean_c2)/2.\n if rms_c1>0. and rms_c2>0.:\n meanrms=(rms_c1+rms_c2)/2.\n tempc1=meanrms*(tempc1-mean_c1)/rms_c1 + meanmean\n tempc2=meanrms*(tempc2-mean_c2)/rms_c2 + meanmean\n else:\n tempc1 = (tempc1 - mean_c1) + meanmean\n tempc2 = (tempc2 - mean_c2) + meanmean\n #print(mean_c1, mean_c2, rms_c1, rms_c2)\n tempc1 = -(tempc1 - 127) #flip back over\n tempc2 = -(tempc2 - 127) #flip back over\n ns=self.num_samples\n mergedsamps=np.empty(ns*2,dtype=np.int8)\n mergedsamps[0:ns*2:2]=tempc2 # a little tricky which is 0 and which is 1 (i.e. which is sampled first!)\n mergedsamps[1:ns*2:2]=tempc1\n self.ydata[c1]=mergedsamps[0:ns]\n self.ydata[c2]=mergedsamps[ns:ns*2]\n \n def overoversample(self,c1,c2): # TODO: probably needs similar flipping of data as in oversample()\n tempc1=np.concatenate([self.ydata[c1],self.ydata[c1+2]])\n tempc2=np.concatenate([self.ydata[c2],self.ydata[c2+2]])\n adjustmeanandrms=True\n if adjustmeanandrms:\n mean_c1 = np.mean(tempc1)\n rms_c1 = np.sqrt(np.mean((tempc1-mean_c1)**2))\n mean_c2 = np.mean(tempc2)\n rms_c2 = np.sqrt(np.mean((tempc2-mean_c2)**2))\n meanmean=(mean_c1+mean_c2)/2.\n meanrms=(rms_c1+rms_c2)/2.\n tempc1=meanrms*(tempc1-mean_c1)/rms_c1 + meanmean\n tempc2=meanrms*(tempc2-mean_c2)/rms_c2 + meanmean\n #print(mean_c1, mean_c2, rms_c1, rms_c2)\n ns=int(2*self.num_samples)\n mergedsamps=np.empty(ns*2,dtype=np.int8)\n mergedsamps[0:ns*2:2]=tempc2 # a little tricky which is 0 and which is 1 (i.e. which is sampled first!)\n mergedsamps[1:ns*2:2]=tempc1\n self.ydata[c1]=mergedsamps[0:int(ns/2)]\n self.ydata[c2]=mergedsamps[int(ns/2):ns]\n self.ydata[c1+2]=mergedsamps[ns:int(3*ns/2)]\n self.ydata[c2+2]=mergedsamps[int(3*ns/2):(ns*2)]\n \n def getmax10adc(self,bn):\n chansthisboard = [(x,y) for (x,y) in max10adcchans if x==bn]\n if self.db: print(time.time()-self.oldtime,\"getting\",chansthisboard)\n for chans in chansthisboard:\n chan=chans[1]\n #chan: 110=ain1, 111=pin6, ..., 118=pin14, 119=temp\n self.ser.write(bytearray([chan]))\n if self.db: print(time.time()-self.oldtime,\"getting max10adc chan\",chan,\"for bn\",bn)\n rslt = self.ser.read(self.nsamp*2) #read N bytes (2 per sample)\n if self.db: print(time.time()-self.oldtime,\"getmax10adc got bytes:\",len(rslt))\n if len(rslt)!=(self.nsamp*2): \n print(time.time()-self.oldtime,\"getmax10adc got bytes:\",len(rslt),\"for board\",bn,\"and chan\",chan)\n return\n byte_array = unpack('%dB'%len(rslt),rslt) #Convert serial data to array of numbers\n db2=False #True #False\n self.ysampdata[self.max10adcchan-1]=np.add(np.multiply(256,byte_array[1:2*self.nsamp:2]),byte_array[0:2*self.nsamp:2])\n self.ysampdata[self.max10adcchan-1]/=16\n if db2:\n for samp in np.arange(10):\n code=256*byte_array[1+2*samp]+byte_array[2*samp]\n self.ysampdata[self.max10adcchan-1][samp]=code/16\n if chan==119:\n temp=-3.056e-4*code*code+1.763*code-2325.049\n print(samp,chan,code,round(temp,1),\"C\",round(temp*1.8+32,1),\"F\")\n else: print(samp,chan,code,round( (3.3*code)/pow(2,12) ,4),\"V\")\n self.on_running(self.ysampdata[self.max10adcchan-1], -self.max10adcchan)\n self.max10adcchan+=1\n\n oldtime=time.time()\n oldtime2=time.time()\n def getchannels(self):\n if self.db: print(time.time() - self.oldtime, \"getchannels\")\n if self.dousb and self.dousbparallel:\n if self.minfirmwareversion>=17:\n self.ser.write(bytearray([100,51,255])) # prime, then get data... 255 gets data from ALL boards\n else:\n print(\"You need firmware >17 for USBparallel reading!\")\n if self.db: print(time.time()-self.oldtime,\"asked for data from all boards\")\n elif not self.autorearm:\n if self.db: print(time.time()-self.oldtime,\"priming trigger\")\n self.ser.write(bytearray([100]))\n status = 0\n self.max10adcchan=1\n if self.domt:\n for bn in range(num_board):\n if self.db: print(time.time()-self.oldtime,\"getting board\",bn)\n try:\n self.parent_conn[bn].send([self.num_samples, self.fastusbpadding, self.fastusbendpadding, self.yscale, self.dologicanalyzer, self.rollingtrigger])\n except:\n print(\"could not send message to receiver\",bn,\"- Exiting!\")\n sys.exit(-3)\n xboardshift=(11.0*bn/8.0)/pow(2,max(self.downsample,0)) # shift the board data to the right by this number of samples (to account for the readout delay) #downsample isn't less than 0 for xscaling\n xdatanew = (self.xdata-xboardshift-self.num_samples/2.)*(1000.0*pow(2,max(self.downsample,0))/self.clkrate/self.xscaling) #downsample isn't less than 0 for xscaling\n xdatanew = xdatanew[1:len(xdatanew)]\n for l in range(num_chan_per_board): self.xydata[bn*num_chan_per_board+l][0]=xdatanew # for printing out or other analysis\n if self.db: print(time.time()-self.oldtime,\"done with board\",bn)\n for bn in range(num_board):\n msg = self.parent_conn[bn].recv()\n if msg != \"OK\": print(\"pro_\", bn, \"said\", msg)\n self.getmax10adc(bn) # get data from 1 MHz Max10 ADC channels\n if self.dogetotherdata: self.getotherdata(bn) # get other data, like TDC info, or other bytes\n if self.dofft: self.plot_fft(bn) # do the FFT plot\n if self.dologicanalyzer:\n xlogicshift=12.0/pow(2,max(self.downsample,0)) # shift the logic analyzer data to the right by this number of samples (to account for the ADC delay) #downsample isn't less than 0 for xscaling\n xdatanew = (self.xdata+xlogicshift-self.num_samples/2.)*(1000.0*pow(2,max(self.downsample,0))/self.clkrate/self.xscaling) #downsample isn't less than 0 for xscaling\n theboard = num_board - 1 - int(self.selectedchannel / num_chan_per_board)\n if bn==theboard and self.dodrawing:\n b = np.unpackbits(self.xydatalogicraw)\n for l in np.arange(self.num_logic_inputs):\n bl=b[7-l::8] # every 8th bit, starting at 7-l\n ydatanew = bl*.3 + (l+1)*3.2/8. # scale it and shift it\n self.xydatalogic[l][0]=xdatanew\n self.xydatalogic[l][1]=ydatanew\n else: # not mt\n for bn in np.arange(num_board):\n if self.db: print(time.time()-self.oldtime,\"getting board\",bn)\n self.getdata(bn) #this sets all boards before this board into serial passthrough mode, so this and following calls for data will go to this board and then travel back over serial\n if self.db: print(time.time() - self.oldtime, \"got data from board\",bn)\n if self.flyingfast: continue # to test flying fast\n self.getmax10adc(bn) # get data from 1 MHz Max10 ADC channels\n if self.dogetotherdata: self.getotherdata(bn) # get other data, like TDC info, or other bytes\n if self.dofft: self.plot_fft(bn) #do the FFT plot\n if self.dolockin and self.debuglockin:\n if sendincrement==0: self.lockinanalyzedata(bn)\n else: print(\"you need to set sendincrement = 0 first before debugging lockin info\"); return False\n if self.dolockin and self.dolockinplot: self.plot_lockin()\n self.on_running(self.ydata, bn) #update data in main window\n if self.db: print(time.time()-self.oldtime,\"done with board\",bn)\n status=1\n if self.minfirmwareversion>=15 and self.dodrawing: #v9.0 and up\n thetime2=time.time()\n elapsedtime=thetime2-self.oldtime2\n if elapsedtime>1.0:\n if not self.havereadswitchdata: self.switchpos = [0] * num_board\n for b in range(num_board): self.getswitchdata(b) #gets the dpdt switch positions\n self.havereadswitchdata=True\n self.oldtime2=thetime2\n status=2\n return status\n\n #get the positions of the dpdt switches from IO expander 2B, and then take action (v9.0 and up!)\n havereadswitchdata=False\n def getswitchdata(self,board):\n if self.minfirmwareversion>=17:\n self.ser.write(bytearray([53,board])) # make the next board active (serial_passthrough 0)\n else:\n self.ser.write(bytearray([30+board])) #make the next board active (serial_passthrough 0)\n self.ser.write(bytearray([146])) #request the IO expander data - takes about 2ms to send the command and read the i2c data\n self.ser.write(bytearray([33])) # from 2B\n self.ser.write(bytearray([19])) # from 2B\n self.ser.write(bytearray([board])) # for board number...\n rslt = self.ser.read(1)\n if len(rslt)>0:# and i==1:\n byte_array = unpack('%dB'%len(rslt),rslt)\n #print(\"i2c data from board\",board,\"IO 2B\",bin(byte_array[0]))\n newswitchpos=byte_array[0]\n if newswitchpos!=self.switchpos[board] or not self.havereadswitchdata:\n for b in range(8):\n if self.testBit(newswitchpos,b) != self.testBit(self.switchpos[board],b) or not self.havereadswitchdata:\n #print \"switch\",b,\"is now\",self.testBit(newswitchpos,b)\n #switch 0-3 is 50/1M Ohm termination on channels 0-3, on is 1M, off is 50\n #switch 4-7 is super/normal gain on channels 0-3, on is super, off is normal\n if b>=4:\n thechan=b-4+(num_board-board-1)*num_chan_per_board\n if self.supergain[thechan] and self.testBit(newswitchpos,b)>0:\n self.togglesupergainchan(thechan)\n if not self.supergain[thechan] and not self.testBit(newswitchpos,b)>0:\n self.togglesupergainchan(thechan)\n self.switchpos[board] = newswitchpos\n \n #initialization\n def init(self):\n if num_board>10: # you'd better have firmware >=17 for this!\n self.ser.write(bytearray([50, 0])) # tell them their IDs... first one gets 0, next gets 1, ...\n self.ser.write(bytearray([52, (num_board - 1)])) # tell them which is the last board\n else:\n self.ser.write(bytearray([0])) # tell them their IDs... first one gets 0, next gets 1, ...\n self.ser.write(bytearray([20 + (num_board - 1)])) # tell them which is the last board\n for b in range(num_board):\n firmwareversion = self.getfirmwareversion(b)\n if firmwareversion<self.minfirmwareversion: self.minfirmwareversion=firmwareversion\n print(\"minimum firmwareversion of all boards is\",self.minfirmwareversion)\n self.maxdownsample=15 # slowest I can run\n if self.minfirmwareversion>=5: #updated firmware\n self.maxdownsample=min(15 +(max_ram_width-ram_width), 18) # can add max_ram_width-ram_width when using newer firmware, but not more than 22\n self.yscale = 7.5 # Vpp for full scale\n if self.minfirmwareversion>=15: #v9.0 boards\n self.yscale*=1.1 # if we used 10M / 1.1M / 11k input resistors\n self.min_y = -self.yscale/2. #-4.0 #0 ADC\n self.max_y = self.yscale/2. #4.0 #256 ADC\n self.tellrolltrig(self.rolltrigger)\n #self.donoselftrig()\n #self.toggle_checkfastusbwriting()\n self.tellsamplesmax10adc()\n self.tellsamplessend()\n self.tellbytesskip()\n self.telldownsample(self.downsample)\n self.togglehighres()\n self.settriggertime(self.triggertimethresh)\n self.tellserialdelaytimerwait()\n self.tellSPIsetup(0) #0.9V CM but not connected\n self.tellSPIsetup(11) #offset binary output\n self.tellSPIsetup(22) #20:50 #22:150 #24:300 Ohm termination ChA\n self.tellSPIsetup(23) #21:50 #23:150 #25:300 Ohm termination ChB\n #self.tellSPIsetup(30) # multiplexed output\n self.tellSPIsetup(32) # non-multiplexed output (less noise)\n self.setupi2c() # sets all ports to be outputs\n if self.dofastusb: self.toggle_fastusb()\n self.toggledousb() # switch to USB2 connection for readout of events, if available\n self.xydata=np.empty([int(num_chan_per_board*num_board),2,int(self.num_samples-1)],dtype=float)\n self.xydataslow=np.empty([len(max10adcchans),2,int(self.nsamp)],dtype=float)\n self.xydatalogic=np.empty([8,2,int(self.num_samples)],dtype=float)\n self.xydatalogicraw=np.empty([num_board,int(self.num_samples)],dtype=np.uint8) # the raw 8 digital input bits from each board for each sample - the x time values are in self.xydatalogic[0][0]\n if self.domt:\n self.xydata_array = multiprocessing.RawArray(\"f\", self.xydata.size * 2) # a float is 2 bytes\n self.xydata = np.frombuffer(self.xydata_array, dtype=float).reshape(self.xydata.shape)\n self.xydatalogicraw_array = multiprocessing.RawArray(\"B\", self.xydatalogicraw.size) # a byte is 1 byte\n self.xydatalogicraw = np.frombuffer(self.xydatalogicraw_array, dtype=np.uint8).reshape(self.xydatalogicraw.shape)\n self.parent_conn=[]\n multiprocessing.set_start_method('spawn')\n for bn in range(num_board):\n parent_conn, child_conn = multiprocessing.Pipe()\n self.parent_conn.append(parent_conn)\n pro = multiprocessing.Process(target=receiver, args=(bn, child_conn,\n self.fastusbpadding,self.num_samples,\n self.xydata.shape,self.xydata_array,\n self.xydatalogicraw.shape,self.xydatalogicraw_array))\n print(\" starting process\",bn)\n pro.start()\n if self.dousb:\n if not self.makeusbsermap(): return False # figure out which usb connection has which board's data\n self.getIDs() # get the unique ID of each board, for calibration etc.\n self.readcalib() # get the calibrated DAC values for each board; if it fails then use defaults\n return True\n \n #cleanup\n def cleanup(self):\n try:\n self.setbacktoserialreadout()\n self.resetchans()\n if self.noselftrig: self.donoselftrig()\n if self.autorearm: self.toggleautorearm()\n if self.dohighres: self.togglehighres()\n if self.useexttrig: self.toggleuseexttrig()\n if self.dologicanalyzer: self.togglelogicanalyzer()\n if self.dofastusb: self.toggle_fastusb()\n if self.checkfastusbwriting: self.toggle_checkfastusbwriting()\n if self.serport!=\"\" and hasattr(self,'ser'):\n self.shutdownadcs()\n if not self.domt:\n for p in self.usbser: p.close()\n self.ser.close()\n except SerialException:\n print(\"failed to talk to board when cleaning up!\")\n if self.domt:\n for bn in range(num_board): self.parent_conn[bn].send(\"END\")\n print(\"bye bye!\")\n \n #For setting up serial and USB connections\n def setup_connections(self):\n adjustedbrate=1./(1./self.brate+2.*self.serialdelaytimerwait*1.e-6/(32.*11.)) # delay of 2*serialdelaytimerwait microseconds every 32*11 bits\n serialrate=adjustedbrate/11./(self.num_bytes*num_board+len(max10adcchans)*2*self.nsamp) #including start+2stop bits\n print(\"rate theoretically\",round(serialrate,2),\"Hz over serial\")\n ports = list(serial.tools.list_ports.comports()); ports.sort(reverse=True)\n autofindusbports = len(self.usbport)==0 and not self.dofastusb\n if self.serport==\"\" or True:\n for port_no, description, address in ports:\n print(port_no,\":\",description,\":\",address)\n if self.serport==\"\":\n if '1A86:7523' in address or '1a86:7523' in address: self.serport = port_no\n if self.trigserport==\"\":\n if '10C4:EA60' in address or '10c4:ea60' in address or 'CP2102 USB to UART Bridge Controller' in description: self.trigserport = port_no\n if autofindusbports:\n if \"Haasoscope\" in description or \"0403:6014\" in address: self.usbport.append(port_no)\n if self.serport!=\"\":\n try:\n self.ser = Serial(self.serport,self.brate,timeout=self.sertimeout,stopbits=2)\n except SerialException:\n print(\"Could not open\",self.serport,\"!\"); return False\n print(\"connected serial to\",self.serport,\", timeout\",self.sertimeout,\"seconds\")\n else: self.ser=\"\"\n for p in self.usbport:\n try:\n self.usbser.append(Serial(p,8*4000000,timeout=self.sertimeout))\n except SerialException:\n print(\"Could not open\",p,\"!\"); return False\n print(\"connected USBserial to\",p,\", 32Mb/s, timeout\",self.sertimeout,\"seconds\")\n if self.dofastusb and useftd2xx and ftd.listDevices():\n for ftd_n in range(len(ftd.listDevices())):\n if str(ftd.getDeviceInfoDetail(ftd_n)[\"description\"]).find(\"Haasoscope\")>=0:\n ftd_d = ftd.open(ftd_n)\n print(\"Adding ftd usb2 device:\",ftd_d.getDeviceInfo())\n ftd_d.setTimeouts(1000, 1000)\n ftd_d.setBitMode(0xff, 0x40)\n ftd_d.setUSBParameters(0x10000, 0x10000)\n ftd_d.setLatencyTimer(1)\n ftd_d.purge(ftd.defines.PURGE_RX)\n ftd_d.purge(ftd.defines.PURGE_TX)\n self.usbser.append(ftd_d)\n self.usbsern.append(ftd_n)\n elif self.dofastusb and useftdi:\n for devi in Ftdi.list_devices():\n if str(devi[0].description).find(\"Haasoscope\") >= 0:\n ftd_n = devi[0].sn\n ftd_d = Ftdi.create_from_url(\"ftdi://::\"+ftd_n+\"/1\")\n print(\"Adding ftdi usb2 device:\", ftd_n)\n ftd_d.reset()\n # ftd_d.ftdi_fn.setTimeouts(1000, 1000)\n ftd_d.set_bitmode(0xff,Ftdi.BitMode.SYNCFF)\n ftd_d.read_data_set_chunksize( int((self.num_bytes + self.fastusbpadding*num_chan_per_board) * 514/512 + 100) )\n ftd_d.set_latency_timer(1)\n ftd_d.purge_buffers()\n self.usbser.append(ftd_d)\n self.usbsern.append(ftd_n)\n if self.serport==\"\": print(\"No serial COM port opened!\"); return False\n return True\n\ndef receiver(name, conn, padding,num_samples,xydata_shape,xydata_array,xydatalogicraw_shape,xydatalogicraw_array):\n usb = None\n board=name\n num_chan_per_board=4\n xydata=np.frombuffer(xydata_array, dtype=float).reshape(xydata_shape)\n xydatalogicraw = np.frombuffer(xydatalogicraw_array, dtype=np.dtype('b')).reshape(xydatalogicraw_shape)\n olddologic=False\n num_bytes = num_samples*num_chan_per_board\n fastusbpadding=padding\n print(\" receiver for board\", name)\n while True:\n msg = conn.recv()\n #print(\" received message:\", msg)\n if msg == \"END\":\n if usb!=None:\n usb.close()\n break\n\n returnmsg = \"OK\"\n if usb == None:\n if useftd2xx:\n ftd_d = ftd.open(msg)\n print(\" adding ftd usb2 device:\", ftd_d.getDeviceInfo())\n ftd_d.setTimeouts(1000, 1000)\n ftd_d.setBitMode(0xff, 0x40)\n ftd_d.setUSBParameters(0x10000, 0x10000)\n ftd_d.setLatencyTimer(1)\n ftd_d.purge(ftd.defines.PURGE_RX)\n ftd_d.purge(ftd.defines.PURGE_TX)\n usb=ftd_d\n elif useftdi:\n ftd_n = str(msg)\n print(\"Adding ftdi usb2 device:\", ftd_n)\n ftd_d = Ftdi.create_from_url(\"ftdi://::\" + ftd_n + \"/1\")\n ftd_d.reset()\n # ftd_d.ftdi_fn.setTimeouts(1000, 1000)\n ftd_d.set_bitmode(0xff, Ftdi.BitMode.SYNCFF)\n ftd_d.read_data_set_chunksize( int((num_bytes + fastusbpadding*num_chan_per_board) * 514/512 + 100) )\n ftd_d.set_latency_timer(1)\n ftd_d.purge_buffers()\n usb=ftd_d\n else:\n num_samples = int(msg[0])\n padding = int(msg[1])\n endpadding = int(msg[2])\n yscale = float(msg[3])\n dologicanalyzer = int(msg[4])\n rollingtrigger = int(msg[5])\n num_bytes = num_samples * num_chan_per_board\n timedout = False\n if useftdi:\n if dologicanalyzer and dologicanalyzer!=olddologic:\n olddologic=dologicanalyzer\n usb.read_data_set_chunksize( int((num_bytes + fastusbpadding*num_chan_per_board) * 514/512 * 5/4 + 100) )\n elif not dologicanalyzer and dologicanalyzer!=olddologic:\n olddologic=dologicanalyzer\n usb.read_data_set_chunksize( int((num_bytes + fastusbpadding*num_chan_per_board) * 514/512 + 100) )\n try:\n nb = num_bytes+padding*num_chan_per_board\n if useftd2xx: rslt = usb.read(nb)#,cache=True)\n elif useftdi: rslt = usb.read_data_bytes(nb, ftdiattempts)\n if not dologicanalyzer and useftd2xx:\n nq = usb.getQueueStatus()\n if nq > 0:\n print(nq, \"bytes still available for usb on board\", board, \"...purging\")\n if useftd2xx: usb.purge(ftd.defines.PURGE_RX)\n elif useftdi: usb.purge_rx_buffer()\n except ftd.DeviceError as msgnum:\n print(\"Error reading from USB2 on board\", board, msgnum)\n returnmsg = \"read err\"\n if len(rslt)==num_bytes+padding*num_chan_per_board:\n timedout = False\n ydata=[ np.frombuffer(rslt,dtype=np.int8,count=num_samples,offset=0*num_samples+1*padding-endpadding), #need the int8 type because we'll later subtract it from 127 to flip it over\n np.frombuffer(rslt,dtype=np.int8,count=num_samples,offset=1*num_samples+2*padding-endpadding),\n np.frombuffer(rslt,dtype=np.int8,count=num_samples,offset=2*num_samples+3*padding-endpadding),\n np.frombuffer(rslt,dtype=np.int8,count=num_samples,offset=3*num_samples+4*padding-endpadding) ]\n #if dooversample[num_chan_per_board*(num_board-board-1)]: oversample(0,2)\n #if dooversample[num_chan_per_board*(num_board-board-1)+1]: oversample(1,3)\n #if dooversample[num_chan_per_board*(num_board-board-1)]==9: overoversample(0,1)\n else:\n timedout = True\n if rollingtrigger:\n print(\"getdata asked for\",num_bytes+padding*num_chan_per_board,\"bytes and got\",len(rslt),\"from board\",board)\n returnmsg = \"read timeout\"\n if dologicanalyzer and not timedout:\n #get extra logic analyzer data, if needed\n logicbytes=int(num_bytes/num_chan_per_board)\n try:\n nb= logicbytes + padding\n if useftd2xx: rslt = usb.read(nb) # ,cache=True)\n elif useftdi: rslt = usb.read_data_bytes(nb, ftdiattempts)\n if useftd2xx:\n nq = usb.getQueueStatus()\n if nq > 0:\n print(nq, \"bytes still available for usb on board\", board, \"...purging\")\n usb.purge(ftd.defines.PURGE_RX)\n except ftd.DeviceError as msgnum:\n print(\"Error reading from USB2 on board\", board, msgnum)\n returnmsg = \"read err\"\n if len(rslt)==logicbytes+padding:\n ydatalogic=np.frombuffer(rslt,dtype=np.uint8,count=num_samples,offset=padding-endpadding)\n else:\n if rollingtrigger:\n print(\"getdata asked for\",logicbytes+padding,\"logic bytes and got\",len(rslt),\"from board\",board)\n returnmsg = \"read timeout\"\n\n for l in range(4): #this draws the 4 fast ADC data channels for each board\n ydatanew=(127-ydata[l])*(yscale/256.) # got to flip it, since it's a negative feedback op amp\n ydatanew = ydatanew[1:len(ydatanew)]\n xydata[l + board*num_chan_per_board][1]=ydatanew\n\n if dologicanalyzer:\n xydatalogicraw[board] = ydatalogic\n\n #print(\" sending\",returnmsg)\n conn.send(returnmsg)\n"
] |
[
[
"numpy.sqrt",
"numpy.dtype",
"numpy.concatenate",
"numpy.max",
"numpy.arctan2",
"numpy.mean",
"numpy.roll",
"numpy.arange",
"numpy.sin",
"numpy.frombuffer",
"numpy.std",
"numpy.argmax",
"numpy.zeros",
"numpy.multiply",
"numpy.array",
"numpy.sum",
"numpy.fft.fft",
"numpy.ones",
"numpy.average",
"numpy.empty",
"numpy.unpackbits"
]
] |
cnlab/cnlab_pipeline
|
[
"979e2fcdfe9113deec1bc9bad17c2624c1e516bb"
] |
[
"archive/first_level.py"
] |
[
"\n# coding: utf-8\n\n# # Building first level models using `nipype` and `SPM` with parametric modulation\n# \n# ## Parametric modulator setup from BIDS events tsv for _megameta_ tasks\n# \n# ### Multiple run task setup (testing on P1 Image Task)\n# \n# -------\n# #### History\n# \n# * 1/21/19 mbod - modify notebook from P1 Banner task with pmod for megameta project\n# * 1/22/19 mbod - adjust functions for pmod and modelspec for two runs-single model for image_task\n# * 2/2/19 mbod - incorporate JSON model spec with `get_subject_info()` function\n# * 2/6/19 mbod - test with likeme rating pmod\n# * 2/19/19 mbod - extract code into a module for cleaner import\n# -----\n# \n# ### Description\n# \n# * Set up a nipype workflow to use SPM12 to make first level models for _Project 1_ banner task data (preprocessed using `batch8` SPM8 scripts) in BIDS derivative format\n# \n# * Workflow has steps (for each subject in subject list):\n# 1. get subject NIFTI file\n# 2. preparation steps\n# a. gunzip\n# b. resample to specified resolution (downsample or upsample)\n# c. smooth using specific kernel size(s)\n# 3. call the `get_subject_info()` function to get spec data and the realignment confounds for run\n# 4. create design matrix\n# 5. estimate model (output betas)\n# 6. estimate conditions (output conn files)\n# 7. estimate constrasts (output spmT)\n# \n# \n# \n# * **NOTES**\n# \n# * Mask specified in the model is `/data00/tools/spm8/apriori/brainmask_th25.nii` \n# * Crashes of workflow produce a lot of logged data and usually a path to a `.pklz` file. In a terminal you can view this with:\n# * `nipypecli crash <PATH TO LOG>`\n# * e.g.\n# \n# ```\n# nipypecli crash /fmriNASTest/data00/projects/drisc/scripts/jupyter/GLM_models/crash-20180914-214850-mbod%40asc.upenn.edu-selectfiles.a0-f01ed26e-9f10-4520-8df5-94e2195b02a0.pklz \n# \n# ```\n\n# ### Setup\n# \n# * import required modules and define parameters\n\n\nimport os # system functions\n\n# NIYPE FUNCTIONS\nimport nipype.interfaces.io as nio # Data i/o\nimport nipype.interfaces.spm as spm # spm\nimport nipype.interfaces.matlab as mlab # how to run matlab\nimport nipype.interfaces.utility as util # utility\nimport nipype.pipeline.engine as pe # pypeline engine\nimport nipype.algorithms.modelgen as model # model specification\nfrom nipype.interfaces.base import Bunch\nfrom nipype.algorithms.misc import Gunzip\n\nfrom itertools import combinations\n\nfrom nilearn import plotting, image\nfrom nistats import thresholding\nimport matplotlib.pyplot as plt\n\nimport scipy.io as sio\nimport numpy as np\nimport json\nimport pandas as pd\n\n\nDEBUG=True\n\nJSON_MODEL_PATH=None\n\n# #### Matlab path\n# \n\n\n# Set the way matlab should be called\nmlab.MatlabCommand.set_default_matlab_cmd(\"matlab -nodesktop -nosplash\")\n# If SPM is not in your MATLAB path you should add it here\nmlab.MatlabCommand.set_default_paths('/fmriNASTest/data00/tools/spm12')\n\n\n# ### Parameters\n# \n# * These need to be reformatted to be consistent\n# * as data is not smoothed commented out the `fwhm_size` param - but data probably has a value\n\n# #### Load JSON model config\n\n\ndef load_model_config(model_path):\n '''\n load the JSON model file and return dictionary\n '''\n JSON_MODEL_PATH=model_path\n \n with open(model_path) as fh:\n model_def = json.load(fh)\n return model_def\n\n\n\ndef setup_folders(output_dir, working_dir):\n '''\n check to see if output and work directories exist and create if needed\n '''\n\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n if not os.path.exists(working_dir):\n os.makedirs(working_dir)\n\n\n# ### Utility functions for subject info and contrasts\n\n# ### Setup design matrix data for subject\n# \n# * need a function to set up the nipype `Bunch` format used\n# * https://nipype.readthedocs.io/en/latest/users/model_specification.html\n# * read the onsets/dur/conditions from task logs and extract needed data\n\ndef get_subject_info(subject_id, model_path):\n '''\n 1. load model specification from JSON spec file\n 2. get confound file for subject for task to add to design matrix \n 3. get task spec CSV for subject for task\n 4. setup subject info structure\n '''\n \n import os\n import pandas as pd\n import json\n \n from nipype.interfaces.base import Bunch\n \n \n def make_pmod(df, conditions, pmods={}):\n \n pmod = []\n \n for cond in conditions:\n \n \n if not pmods.get(cond):\n pmod.append(None)\n else:\n df2 = df[df.trial_type==cond]\n \n pmod_name = pmods.get(cond)\n \n #pmod = [pmod] if not type(pmods) is list else pmod\n \n if df2[pmod_name].var()==0:\n df2[pmod_name]+=0.001\n\n pmod.append(Bunch(name=[pmod_name],\n param=[df2[pmod_name].values.tolist()\n ],\n poly=[1]\n ))\n \n return pmod\n \n \n\n def map_spec_to_model(spec_df,model):\n \"\"\"\n Maps spec trial names to model contrast trials.\n\n Args:\n spec: the events.tsv spec file\n model: the model.json file\n\n Returns:\n pandas dataframe object\n \"\"\"\n\n spec=spec_df.copy()\n\n for con in model['Conditions']:\n spec_trials = model['Conditions'][con]\n spec.loc[spec.trial_type.isin(spec_trials),'trial_type'] = con\n spec.onset.sort_values()\n\n cols_to_drop=[]\n for pmidx, (cond, colname) in enumerate(model['Modulators'].items(),1):\n #pmod=\"pmod{}_{}\".format(pmidx,colname)\n pmod=colname\n\n spec.loc[spec.trial_type==cond,pmod] = spec[colname]\n cols_to_drop.append(colname)\n #spec.drop(columns=cols_to_drop,inplace=True)\n\n return spec\n \n \n with open(model_path) as fh:\n model_def = json.load(fh)\n \n \n PROJECT_DIR = '/data00/projects/megameta/project1'\n SUBJ_DIR = os.path.join(PROJECT_DIR,'derivatives', 'batch8')\n \n realign_files = []\n subject_info = []\n \n TASK_NAME = model_def['TaskName']\n TASK_RUNS = model_def['Runs']\n MODEL_NAME = model_def['ModelName']\n \n # check to see which runs exist for subject\n # by looking for appropriate events.tsv files\n # this could (should?) also include looking for the nifti file?\n runs_for_subj = [run for run in TASK_RUNS\n if \n os.path.exists(os.path.join(SUBJ_DIR, subject_id, 'func',\n '{}_task-{}_run-0{}_events.tsv'.format(subject_id, \n TASK_NAME,\n run)))\n ]\n \n for run_num, _ in enumerate(runs_for_subj,1):\n \n \n events_df = pd.read_csv(os.path.join(SUBJ_DIR, subject_id, 'func',\n '{}_task-{}_run-0{}_events.tsv'.format(subject_id, \n TASK_NAME,\n run_num)),\n sep='\\t')\n\n\n onsets_df = map_spec_to_model(events_df, model_def)\n \n \n realign_file = os.path.join(PROJECT_DIR, 'working','nipype',\n 'workingdir_model_{}_{}'.format(TASK_NAME.upper(),MODEL_NAME),\n '{}-run-0{}-realign.txt'.format(subject_id, run_num))\n\n confound_file=os.path.join(SUBJ_DIR, subject_id, 'func',\n '{}_task-{}_run-0{}_desc-confounds-regressors.tsv'.format(subject_id, \n TASK_NAME,\n run_num)\n )\n\n confound_df = pd.read_csv(confound_file, sep='\\t')\n\n cols_to_use = [ 'TransX','TransY', 'TransZ', 'RotX', 'RotY', 'RotZ']\n\n confound_df[cols_to_use].to_csv(realign_file, \n header=False, \n index=False,\n sep='\\t')\n\n realign_files.append(realign_file)\n\n onsets = []\n dur = []\n for cond in model_def['Conditions']:\n onsets.append(onsets_df[onsets_df.trial_type==cond].onset.values)\n dur.append(onsets_df[onsets_df.trial_type==cond].duration.values)\n\n \n #condition_names = list(onsets_df.trial_type.unique())\n condition_names = list(model_def['Conditions'].keys())\n \n #pmod = make_pmod(rdf, condition_names) \n pmod = make_pmod(onsets_df, condition_names, \n pmods=model_def['Modulators'])\n\n \n \n \n subject_info.append(Bunch(conditions=condition_names,\n onsets=onsets,\n durations=dur,\n amplitudes=None,\n tmod=None,\n pmod=pmod,\n regressor_names=None,\n regressors=None))\n \n \n DM_regressors = []\n for cond in condition_names:\n DM_regressors.append(cond)\n if model_def['Modulators'].get(cond):\n DM_regressors.append('{}x{}^1'.format(cond, model_def['Modulators'].get(cond)))\n \n \n return subject_info, realign_files, DM_regressors\n\n\n# ### Set up contrasts\n# \n# * This part of the template needs work to provide a cleaner way to specify contrasts\n# * Could use the same vector contrasts approach as we have in batch8 and then have a function to convert this into the list of list data structure that nipype spm contrasts node looks for\n\n\ndef make_contrast_list(subject_id, condition_names):\n condition_names.append('constant')\n\n cont = []\n for idx, cname in enumerate(condition_names):\n ccode = [0 if pos!=idx else 1 for pos in range(len(condition_names))]\n cont.append([cname, 'T', condition_names, ccode])\n\n\n return cont\n\n\n\n# ## Set up processing nodes for modeling workflow\n\ndef set_up_nodes(node_dict={}, TR=2.0):\n '''\n define needed nodes and return in a dictionary\n '''\n\n\n # #### Specify model node\n\n\n # SpecifyModel - Generates SPM-specific Model\n node_dict['modelspec'] = pe.Node(model.SpecifySPMModel(concatenate_runs=False,\n input_units='secs',\n output_units='secs',\n time_repetition=TR,\n high_pass_filter_cutoff=128),\n output_units = 'scans',\n name=\"modelspec\") \n\n if DEBUG:\n print('modelspec node defined\\n\\t', node_dict['modelspec'])\n\n # #### Level 1 Design node\n # \n # ** TODO -- get the right matching template file for fmriprep **\n # \n # * ??do we need a different mask than:\n # \n # `'/data00/tools/spm8/apriori/brainmask_th25.nii'`\n\n\n\n # Level1Design - Generates an SPM design matrix\n node_dict['level1design'] = pe.Node(spm.Level1Design(bases={'hrf': {'derivs': [0, 0]}},\n timing_units='secs',\n interscan_interval=TR,\n model_serial_correlations='none', #'AR(1)',\n mask_image = '/data00/tools/spm8/apriori/brainmask_th25.nii',\n global_intensity_normalization='none'\n ),\n name=\"level1design\")\n\n if DEBUG:\n print('level1design node defined\\n\\t', node_dict['level1design'])\n\n\n # EstimateModel - estimate the parameters of the model\n node_dict['level1estimate'] = pe.Node(spm.EstimateModel(estimation_method={'Classical': 1}),\n name=\"level1estimate\")\n\n if DEBUG:\n print('level1estimate node defined\\n\\t', node_dict['level1estimate'])\n\n\n # #### Estimate Contrasts node\n\n # EstimateContrast - estimates contrasts\n node_dict['conestimate'] = pe.Node(spm.EstimateContrast(), name=\"conestimate\")\n\n if DEBUG:\n print('conestimate node defined\\n\\t', node_dict['conestimate'])\n\n \n # Initiation of the 1st-level analysis workflow\n l1analysis = pe.Workflow(name='l1analysis')\n\n # Connect up the 1st-level analysis components\n l1analysis.connect([(node_dict['modelspec'], node_dict['level1design'], [('session_info',\n 'session_info')]),\n \n (node_dict['level1design'], node_dict['level1estimate'], \n [('spm_mat_file', 'spm_mat_file')]),\n \n (node_dict['level1estimate'], node_dict['conestimate'], [('spm_mat_file',\n 'spm_mat_file'),\n ('beta_images',\n 'beta_images'),\n ('residual_image',\n 'residual_image')])\n\n ])\n \n node_dict['l1analysis']=l1analysis\n \n if DEBUG:\n print('l1analysis workflow defined with:\\n\\tmodelspec\\n\\tlevel1design\\n\\tlevel1estimate\\n\\tconestimate\\n\\n\\tnodes\\n')\n\n \n # Get Subject Info - get subject specific condition information\n node_dict['getsubjectinfo'] = pe.Node(util.Function(input_names=['subject_id', 'model_path'],\n output_names=['subject_info', 'realign_params', 'condition_names'],\n function=get_subject_info),\n name='getsubjectinfo')\n\n\n\n\n node_dict['makecontrasts'] = pe.Node(util.Function(input_names=['subject_id', 'condition_names'],\n output_names=['contrasts'],\n function=make_contrast_list),\n name='makecontrasts')\n \n \n # Infosource - a function free node to iterate over the list of subject names\n node_dict['infosource'] = pe.Node(util.IdentityInterface(fields=['subject_id', 'model_path']\n ),\n name=\"infosource\")\n\n node_dict['infosource'].iterables = [('subject_id', subject_list),\n ('model_path', [JSON_MODEL_FILE]*len(subject_list))\n\n ]\n \n \n \n return node_dict\n\n\n\ndef OTHER_NODES():\n\n\n\n\n\n # ### `selectfiles` node\n # \n # * match template to find source files (functional) for use in subsequent parts of pipeline\n\n # In[60]:\n\n # SelectFiles - to grab the data (alternativ to DataGrabber)\n\n\n ## TODO: here need to figure out how to incorporate the run number and task name in call\n templates = {'func': '{subject_id}/func/{subject_id}_task-image_run-0*_space-MNI152-T1-1mm_desc-preproc_bold.nii.gz'} \n\n\n selectfiles = pe.Node(nio.SelectFiles(templates,\n base_directory='/data00/projects/megameta/project1/derivatives/batch8'),\n working_dir=working_dir,\n name=\"selectfiles\")\n\n\n # ## Unzip and smoothing steps\n # \n # * BIDS derivatives folders contain unsmoothed functional NIFTI files in zipped (.nii.gz) format\n # * This subflow adds three nodes:\n # 1. gunzip\n # 2. resample\n # 3. smooth\n\n # #### Specify unzip node\n # \n # * transform `.nii.gz` to `.nii`\n\n # In[61]:\n\n gunzip = pe.MapNode(Gunzip(),name=\"gunzip\", iterfield=['in_file'])\n\n\n # #### Specify smoothing node\n\n # In[62]:\n\n smooth = pe.Node(interface=spm.Smooth(), name=\"smooth\")\n fwhmlist = [4,6,8]\n smooth.iterables = ('fwhm', fwhmlist)\n\n\n # #### Specify resampling node\n\n # In[63]:\n\n resample = pe.Node(interface=spm.utils.ResliceToReference(), name='resample')\n\n\n # In[64]:\n\n resample.inputs.target = '/data00/projects/project1/data/subjs/P100/BOLD/argue_run01/wad_argue_run01.nii'\n\n\n # In[65]:\n\n unzip_resample_and_smooth = pe.Workflow(name='unzip_resample_and_smooth')\n\n unzip_resample_and_smooth.base_dir = os.path.join(SUBJ_DIR, working_dir)\n\n unzip_resample_and_smooth.connect(\n [\n #(gunzip, resample, [('out_file', 'in_files')]),\n #(resample, smooth, [('out_files', 'in_files')])\n (gunzip, smooth, [('out_file', 'in_files')])\n ]\n )\n\n\n # In[66]:\n\n Image(unzip_resample_and_smooth.write_graph(graph2use='flat', simple_form=False))\n\n\n # ### Specify datasink node\n # \n # * copy files to keep from various working folders to output folder for model for subject\n\n\n\n # In[68]:\n\n # Datasink - creates output folder for important outputs\n datasink = pe.Node(nio.DataSink(base_directory=SUBJ_DIR,\n parameterization=True, \n #container=output_dir \n ),\n name=\"datasink\")\n\n datasink.inputs.base_directory = output_dir\n\n # Use the following DataSink output substitutions\n substitutions = []\n subjFolders = [('_subject_id_%s/_fwhm_%s' % (sub,f), 'fwhm_%s' % (f))\n for f in fwhmlist\n for sub in subject_list]\n substitutions.extend(subjFolders)\n datasink.inputs.substitutions = substitutions\n\n\n\ndef create_workflow(nd, workflow_name, working_dir):\n # ---------\n\n # ## Set up workflow for whole process\n\n\n workflow = pe.Workflow(name=workflow_name)\n workflow.base_dir = working_dir\n\n\n workflow.connect([(nd['infosource'], nd['selectfiles'], [('subject_id', 'subject_id')]),\n (nd['infosource'], md['getsubjectinfo'], [('subject_id', 'subject_id'),\n ('model_path', 'model_path')\n ]),\n (nd['infosource'], nd['makecontrasts'], [('subject_id', 'subject_id')]),\n (nd['getsubjectinfo'], nd['makecontrasts'], [('condition_names', 'condition_names')]),\n\n (nd['getsubjectinfo'], nd['l1analysis'], [('subject_info',\n 'modelspec.subject_info'),\n ('realign_params',\n 'modelspec.realignment_parameters')]),\n (nd['makecontrasts'], nd['l1analysis'], [('contrasts',\n 'conestimate.contrasts')]),\n\n\n (nd['aselectfiles'], nd['gunzip'], [('func','in_file')]),\n\n #(gunzip, resample, [('out_file', 'in_files')]),\n\n #(resample, smooth, [('out_files', 'in_files')]),\n\n (gunzip, smooth, [('out_file', 'in_files')]),\n\n\n (smooth, l1analysis, [('smoothed_files',\n 'modelspec.functional_runs')]),\n\n\n (infosource, datasink, [('subject_id','container')]),\n (l1analysis, datasink, [('conestimate.spm_mat_file','@spm'),\n ('level1estimate.beta_images','@betas'),\n ('level1estimate.mask_image','@mask'),\n ('conestimate.spmT_images','@spmT'),\n ('conestimate.con_images','@con'),\n ('conestimate.spmF_images','@spmF')\n ])\n ]\n )\n\n\n return workflow\n\n \n\ndef show_design_matrix(spm_mat_path):\n '''\n '''\n \n\n spm_mat=sio.loadmat(spm_mat_path,\n struct_as_record=False, squeeze_me=True)\n\n\n regressor_labels=spm_mat['SPM'].xX.name\n\n\n # use nistats.reporting plot function and a pandas data frame\n\n\n\n\n"
] |
[
[
"pandas.read_csv",
"scipy.io.loadmat"
]
] |
yeongjoonJu/Occlusion-Robust-3D-Face-CFR-GAN
|
[
"1966faf9bfe8d8afd6bc2cea88e5400ce3be54d5"
] |
[
"renderer.py"
] |
[
"#!/usr/bin/python\n# -*- encoding: utf-8 -*-\nfrom ctypes import ArgumentError\nimport os ; import sys \nos.chdir( os.path.split( os.path.realpath( sys.argv[0] ) )[0] ) \n\nfrom mmRegressor.network.resnet50_task import *\nfrom mmRegressor.preprocess_img import Preprocess\nfrom mmRegressor.load_data import *\nfrom mmRegressor.reconstruct_mesh import Reconstruction, Compute_rotation_matrix, _need_const\n\nimport torch\nimport numpy as np\nimport torchvision.transforms as transforms\nimport torch.nn.functional as F\nimport cv2\n# from torchsummary import summary\nfrom pytorch3d.structures import Meshes\nfrom pytorch3d.renderer import Textures\nfrom pytorch3d.renderer import (\n look_at_view_transform,\n cameras, lighting,\n PointLights, HardPhongShader,\n RasterizationSettings,\n BlendParams,\n MeshRenderer, MeshRasterizer\n)\n\n# Retina Face\nif os.path.exists('Pytorch_Retinaface'):\n from Pytorch_Retinaface.layers.functions.prior_box import PriorBox\n from Pytorch_Retinaface.utils.nms.py_cpu_nms import py_cpu_nms\n from Pytorch_Retinaface.utils.box_utils import decode, decode_landm\n\nclass Estimator3D(object):\n def __init__(self, is_cuda=True, batch_size=1, render_size=224, test=True, model_path=None, back_white=False, cuda_id=0, det_net=None):\n self.is_cuda = is_cuda\n self.render_size = render_size\n self.cuda_id = cuda_id\n # Network, cfg\n if det_net is not None:\n self.det_net = det_net[0]\n self.det_cfg = det_net[1]\n\n # load models\n if model_path is None:\n print('Load pretrained weights')\n else:\n print('Load {}'.format(model_path))\n self.load_3dmm_models(model_path, test)\n self.to_tensor = transforms.Compose([\n transforms.ToTensor(),\n ])\n \n self.argmax = lambda i, c: c[i]\n self.thresholding = torch.nn.Threshold(0.3, 0.0)\n\n tri = self.face_model.tri\n tri = np.expand_dims(tri, 0)\n self.tri = torch.FloatTensor(tri).repeat(batch_size, 1, 1)\n\n self.skin_mask = -1*self.face_model.skin_mask.unsqueeze(-1)\n \n if is_cuda:\n device = torch.device('cuda:'+str(cuda_id))\n self.tri = self.tri.cuda(cuda_id)\n else:\n device = torch.device('cpu')\n\n # Camera and renderer settings\n blend_params = BlendParams(background_color=(0.0,0.0,0.0))\n if back_white:\n blend_params= BlendParams(background_color=(1.0,1.0,1.0))\n\n self.R, self.T = look_at_view_transform(eye=[[0,0,10]], at=[[0,0,0]], up=[[0,1,0]], device=device)\n camera = cameras.FoVPerspectiveCameras(znear=0.01, zfar=50.0, aspect_ratio=1.0, fov=12.5936, R=self.R, T=self.T, device=device)\n lights = PointLights(ambient_color=[[1.0,1.0,1.0]], device=device, location=[[0.0,0.0,1e-5]])\n self.phong_renderer = MeshRenderer(\n rasterizer=MeshRasterizer(\n cameras=camera,\n raster_settings=RasterizationSettings(\n image_size=render_size,\n blur_radius=0.0,\n faces_per_pixel=1,\n cull_backfaces=True\n )\n ),\n shader=HardPhongShader(cameras=camera, device=device, lights=lights, blend_params=blend_params)\n )\n\n def load_3dmm_models(self, model_path, test=True):\n # read face model\n face_model = BFM('mmRegressor/BFM/BFM_model_80.mat', self.cuda_id)\n\n self.face_model = face_model\n\n # read standard landmarks for preprocessing images\n self.lm3D = face_model.load_lm3d(\"mmRegressor/BFM/similarity_Lm3D_all.mat\")\n \n regressor = resnet50_use()\n if model_path is None:\n regressor.load_state_dict(torch.load(\"mmRegressor/network/th_model_params.pth\"))\n else:\n regressor.load_state_dict(torch.load(model_path, map_location='cuda:'+str(self.cuda_id)))\n\n if test:\n regressor.eval()\n if self.is_cuda:\n regressor = regressor.cuda(self.cuda_id)\n if test:\n for param in regressor.parameters():\n param.requires_grad = False\n\n self.regressor = regressor\n\n def regress_3dmm(self, img):\n arr_coef = self.regressor(img)\n coef = torch.cat(arr_coef, 1)\n\n return coef\n\n\n def reconstruct(self, coef, test=False):\n # reconstruct 3D face with output coefficients and face model\n face_shape, _, face_color, _,face_projection,_,gamma = Reconstruction(coef,self.face_model)\n verts_rgb = face_color[...,[2,1,0]]\n mesh = Meshes(verts=face_shape, faces=self.tri[:face_shape.shape[0],...], textures=Textures(verts_rgb=verts_rgb))\n\n rendered = self.phong_renderer(meshes_world=mesh, R=self.R, T=self.T)\n rendered = torch.clamp(rendered, 0.0, 1.0)\n\n landmarks_2d = torch.zeros_like(face_projection).cuda(self.cuda_id)\n landmarks_2d[...,0] = torch.clamp(face_projection[...,0].clone(), 0, self.render_size-1)\n landmarks_2d[...,1] = torch.clamp(face_projection[...,1].clone(), 0, self.render_size-1)\n landmarks_2d[...,1] = self.render_size - landmarks_2d[...,1].clone() - 1\n landmarks_2d = landmarks_2d[:,self.face_model.keypoints,:]\n\n if test:\n return rendered, landmarks_2d\n\n tex_mean = torch.sum(face_color*self.skin_mask) / torch.sum(self.skin_mask)\n ref_loss = torch.sum(torch.square((face_color - tex_mean)*self.skin_mask)) / (face_color.shape[0]*torch.sum(self.skin_mask))\n\n gamma = gamma.view(-1,3,9) \n gamma_mean = torch.mean(gamma, dim=1, keepdim=True)\n gamma_loss = torch.mean(torch.square(gamma - gamma_mean))\n\n return rendered, landmarks_2d, ref_loss, gamma_loss\n\n\n def estimate_and_reconstruct(self, img):\n coef = self.regress_3dmm(img)\n return self.reconstruct(coef, test=True)\n\n \n def estimate_five_landmarks(self, img):\n # Detect and align\n img_raw = np.array(img)\n ori_h, ori_w, _ = img_raw.shape\n img = np.float32(cv2.resize(img_raw, (320, 320), cv2.INTER_CUBIC))\n im_height, im_width, _ = img.shape\n scale = torch.Tensor([img.shape[1], img.shape[0], img.shape[1], img.shape[0]])\n img -= (104, 117, 123)\n img = img.transpose(2,0,1)\n img = torch.from_numpy(img).unsqueeze(0)\n img = img.to(self.cuda_id)\n scale = scale.to(self.cuda_id)\n \n loc, conf, landms = self.det_net(img)\n priorbox = PriorBox(self.det_cfg, image_size=(im_height, im_width))\n priors = priorbox.forward()\n priors = priors.to(self.cuda_id)\n prior_data = priors.data\n boxes = decode(loc.data.squeeze(0), prior_data, self.det_cfg['variance'])\n boxes = boxes * scale\n boxes = boxes.cpu().numpy()\n scores = conf.squeeze(0).data.cpu().numpy()[:, 1]\n landms = decode_landm(landms.data.squeeze(0), prior_data, self.det_cfg['variance'])\n scale1 = torch.Tensor([img.shape[3], img.shape[2], img.shape[3], img.shape[2],\n img.shape[3], img.shape[2], img.shape[3], img.shape[2],\n img.shape[3], img.shape[2]])\n scale1 = scale1.to(self.cuda_id)\n landms = landms * scale1\n landms = landms.cpu().numpy()\n\n # ignore low scores\n inds = np.where(scores > 0.1)[0]\n boxes = boxes[inds]\n landms = landms[inds]\n scores = scores[inds]\n\n # keep top-K before NMS\n # order = scores.argsort()[::-1][:args.top_k]\n order = scores.argsort()[::-1]\n boxes = boxes[order]\n landms = landms[order]\n scores = scores[order]\n\n # do NMS\n dets = np.hstack((boxes, scores[:, np.newaxis])).astype(np.float32, copy=False)\n keep = py_cpu_nms(dets, 0.4)\n dets = dets[keep, :]\n landms = landms[keep]\n landm = np.array(landms[0])\n \n landm = np.reshape(landm, (-1, 2))\n landm[:,0] *= ori_w/320\n landm[:,1] *= ori_h/320\n\n return landm\n\n\n def align_convert2tensor(self, img_list, aligned=False):\n if not aligned and self.det_net is None:\n raise ArgumentError('Detection network is None!')\n\n input_img = []\n for filename in img_list:\n if aligned:\n img = cv2.imread(filename)\n if img.shape[0]!= self.render_size:\n img = cv2.resize(img, (self.render_size,self.render_size), cv2.INTER_AREA)\n if img.shape[2]==4:\n img = img[...,:3]\n else:\n img = Image.open(filename)\n lm = self.estimate_five_landmarks(img)\n img, _ = Preprocess(img, lm, self.lm3D, render_size=self.render_size)\n img = img[0].copy()\n \n img = self.to_tensor(img)\n input_img.append(img.unsqueeze(0))\n\n input_img = torch.cat(input_img)\n if self.is_cuda:\n input_img = input_img.type(torch.FloatTensor).cuda(self.cuda_id)\n \n return input_img\n\n\n def reconstruct2obj(self, img_list, save_path):\n input_imgs = []\n for filename in img_list:\n img = Image.open(filename)\n lm = self.estimate_five_landmarks(img)\n img, _ = Preprocess(img, lm, self.lm3D, render_size=self.render_size)\n img = img[0].copy()\n \n img = self.to_tensor(img)\n input_imgs.append(img.unsqueeze(0))\n \n input_imgs = torch.cat(input_imgs)\n if self.is_cuda:\n input_imgs = input_imgs.type(torch.FloatTensor).cuda(self.cuda_id)\n \n coef = self.regress_3dmm(input_imgs)\n\n # reconstruct 3D face with output coefficients and face model\n face_shape,_,face_color,tri,_,_,_ = Reconstruction(coef, self.face_model)\n \n for i, filename in enumerate(img_list):\n shape = face_shape.cpu()[i]\n color = face_color.cpu()[i]\n save_obj(os.path.join(save_path,os.path.basename(filename)[:-4]+'_mesh.obj'),shape,tri+1,np.clip(color,0,1))\n\n \n def render_and_estimate_landmarks(self, coef):\n face_shape, _, face_color, _,face_projection,_,_ = Reconstruction(coef,self.face_model)\n verts_rgb = face_color[...,[2,1,0]]\n mesh = Meshes(verts=face_shape, faces=self.tri[:face_shape.shape[0],...], textures=Textures(verts_rgb=verts_rgb))\n\n rendered = self.phong_renderer(meshes_world=mesh, R=self.R, T=self.T)\n rendered = torch.clamp(rendered, 0.0, 1.0)\n landmarks_2d = torch.zeros_like(face_projection).cuda(self.cuda_id)\n landmarks_2d[...,0] = torch.clamp(face_projection[...,0].clone(), 0, self.render_size-1)\n landmarks_2d[...,1] = torch.clamp(face_projection[...,1].clone(), 0, self.render_size-1)\n landmarks_2d[...,1] = self.render_size - landmarks_2d[...,1].clone() - 1\n landmarks_2d = landmarks_2d[:,self.face_model.keypoints,:]\n return rendered, landmarks_2d"
] |
[
[
"torch.mean",
"numpy.hstack",
"numpy.expand_dims",
"torch.Tensor",
"torch.cat",
"numpy.reshape",
"torch.load",
"numpy.clip",
"torch.sum",
"torch.zeros_like",
"torch.from_numpy",
"torch.square",
"torch.FloatTensor",
"torch.device",
"torch.clamp",
"numpy.array",
"torch.nn.Threshold",
"numpy.where"
]
] |
ericauuu/get_the_foodies
|
[
"2abfae6a0f69a264866f10b8e9177e5b45681222"
] |
[
"app.py"
] |
[
"from waitress import serve\n\nimport matplotlib\nmatplotlib.use('Agg')\nfrom flask import Flask, render_template, request\nimport matplotlib.pyplot as plt\nfrom python.functions import result_f1scr, result_table\n\napp = Flask(__name__, static_url_path=\"/static\")\n\[email protected](\"/\")\ndef index():\n \"\"\"Return the main page.\"\"\"\n\n restaurants = [\"amelie_nyc\", \"lovemama_nyc\", \"upstate_nyc\"]\n\n return render_template(\"index.html\", restaurants=restaurants)\n\[email protected](\"/get_results\", methods=[\"POST\"])\ndef get_results():\n data = request.form\n print(data)\n\n restaurant_a = data[\"restaurant\"]\n table = result_table(restaurant_a).to_html()\n f1 = result_f1scr(restaurant_a)\n\n return render_template('results.html', restaurant = restaurant_a, table=table, f1=f1)\n\nif __name__ == \"__main__\":\n serve(app, host='0.0.0.0', port=5000)\n\n"
] |
[
[
"matplotlib.use"
]
] |
GuilinZ/PF-Net-Point-Fractal-Network
|
[
"80322cc2fb330c9820eb8540de75ca28e3fe64c4"
] |
[
"Train_PFNet.py"
] |
[
"import os\nimport sys\nimport argparse\nimport random\nimport torch\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.utils.data\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\nimport utils\nfrom utils import PointLoss\nfrom utils import distance_squre\nimport data_utils as d_utils\nimport ModelNet40Loader\nimport shapenet_part_loader\nfrom model_PFNet import _netlocalD,_netG\n\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--dataroot', default='dataset/train', help='path to dataset')\nparser.add_argument('--workers', type=int,default=8, help='number of data loading workers')\nparser.add_argument('--batchSize', type=int, default=32, help='input batch size')\nparser.add_argument('--pnum', type=int, default=2048, help='the point number of a sample')\nparser.add_argument('--crop_point_num',type=int,default=512,help='0 means do not use else use with this weight')\nparser.add_argument('--nc', type=int, default=3)\nparser.add_argument('--niter', type=int, default=150, help='number of epochs to train for')\nparser.add_argument('--weight_decay', type=float, default=0.001)\nparser.add_argument('--learning_rate', default=0.0002, type=float, help='learning rate in training')\nparser.add_argument('--beta1', type=float, default=0.9, help='beta1 for adam. default=0.9')\nparser.add_argument('--cuda', type = bool, default = False, help='enables cuda')\nparser.add_argument('--ngpu', type=int, default=1, help='number of GPUs to use')\nparser.add_argument('--D_choose',type=int, default=1, help='0 not use D-net,1 use D-net')\nparser.add_argument('--netG', default='', help=\"path to netG (to continue training)\")\nparser.add_argument('--netD', default='', help=\"path to netD (to continue training)\")\nparser.add_argument('--manualSeed', type=int, help='manual seed')\nparser.add_argument('--drop',type=float,default=0.2)\nparser.add_argument('--num_scales',type=int,default=3,help='number of scales')\nparser.add_argument('--point_scales_list',type=list,default=[2048,1024,512],help='number of points in each scales')\nparser.add_argument('--each_scales_size',type=int,default=1,help='each scales size')\nparser.add_argument('--wtl2',type=float,default=0.95,help='0 means do not use else use with this weight')\nparser.add_argument('--cropmethod', default = 'random_center', help = 'random|center|random_center')\nopt = parser.parse_args()\nprint(opt)\n\nblue = lambda x: '\\033[94m' + x + '\\033[0m'\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nUSE_CUDA = True\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\npoint_netG = _netG(opt.num_scales,opt.each_scales_size,opt.point_scales_list,opt.crop_point_num)\npoint_netD = _netlocalD(opt.crop_point_num)\ncudnn.benchmark = True\nresume_epoch=0\n\ndef weights_init_normal(m):\n classname = m.__class__.__name__\n if classname.find(\"Conv2d\") != -1:\n torch.nn.init.normal_(m.weight.data, 0.0, 0.02)\n elif classname.find(\"Conv1d\") != -1:\n torch.nn.init.normal_(m.weight.data, 0.0, 0.02)\n elif classname.find(\"BatchNorm2d\") != -1:\n torch.nn.init.normal_(m.weight.data, 1.0, 0.02)\n torch.nn.init.constant_(m.bias.data, 0.0)\n elif classname.find(\"BatchNorm1d\") != -1:\n torch.nn.init.normal_(m.weight.data, 1.0, 0.02)\n torch.nn.init.constant_(m.bias.data, 0.0) \n\nif USE_CUDA: \n print(\"Let's use\", torch.cuda.device_count(), \"GPUs!\")\n # point_netG = torch.nn.DataParallel(point_netG)\n # point_netD = torch.nn.DataParallel(point_netD)\n point_netG.to(device) \n point_netG.apply(weights_init_normal)\n point_netD.to(device)\n point_netD.apply(weights_init_normal)\nif opt.netG != '' :\n point_netG.load_state_dict(torch.load(opt.netG,map_location=lambda storage, location: storage)['state_dict'])\n resume_epoch = torch.load(opt.netG)['epoch']\nif opt.netD != '' :\n point_netD.load_state_dict(torch.load(opt.netD,map_location=lambda storage, location: storage)['state_dict'])\n resume_epoch = torch.load(opt.netD)['epoch']\n\n \nif opt.manualSeed is None:\n opt.manualSeed = random.randint(1, 10000)\nprint(\"Random Seed: \", opt.manualSeed)\nrandom.seed(opt.manualSeed)\ntorch.manual_seed(opt.manualSeed)\nif opt.cuda:\n torch.cuda.manual_seed_all(opt.manualSeed)\n\n\ntransforms = transforms.Compose(\n [\n d_utils.PointcloudToTensor(),\n ]\n)\n# dset = shapenet_part_loader.PartDataset( root='./dataset/shapenetcore_partanno_segmentation_benchmark_v0/',classification=True, class_choice=None, npoints=opt.pnum, split='train')\n# assert dset\n# dataloader = torch.utils.data.DataLoader(dset, batch_size=opt.batchSize,\n# shuffle=True,num_workers = int(opt.workers))\n#\n#\n# test_dset = shapenet_part_loader.PartDataset( root='./dataset/shapenetcore_partanno_segmentation_benchmark_v0/',classification=True, class_choice=None, npoints=opt.pnum, split='test')\n# test_dataloader = torch.utils.data.DataLoader(test_dset, batch_size=opt.batchSize,\n# shuffle=True,num_workers = int(opt.workers))\n\ndset = ModelNet40Loader.ModelNet40Cls(opt.pnum, train=True, transforms=transforms, download = False)\nassert dset\ndataloader = torch.utils.data.DataLoader(dset, batch_size=opt.batchSize,\n shuffle=True,num_workers = int(opt.workers))\n\n\ntest_dset = ModelNet40Loader.ModelNet40Cls(opt.pnum, train=False, transforms=transforms, download = False)\ntest_dataloader = torch.utils.data.DataLoader(test_dset, batch_size=opt.batchSize,\n shuffle=True,num_workers = int(opt.workers))\n\n# pointcls_net.apply(weights_init)\nprint(point_netG)\nprint(point_netD)\n\ncriterion = torch.nn.BCEWithLogitsLoss().to(device)\ncriterion_PointLoss = PointLoss().to(device)\n\n# setup optimizer\noptimizerD = torch.optim.Adam(point_netD.parameters(), lr=0.0001,betas=(0.9, 0.999),eps=1e-05,weight_decay=opt.weight_decay)\noptimizerG = torch.optim.Adam(point_netG.parameters(), lr=0.0001,betas=(0.9, 0.999),eps=1e-05 ,weight_decay=opt.weight_decay)\nschedulerD = torch.optim.lr_scheduler.StepLR(optimizerD, step_size=40, gamma=0.2)\nschedulerG = torch.optim.lr_scheduler.StepLR(optimizerG, step_size=40, gamma=0.2)\n\nreal_label = 1\nfake_label = 0\n\ncrop_point_num = int(opt.crop_point_num)\ninput_cropped1 = torch.FloatTensor(opt.batchSize, opt.pnum, 3)\nlabel = torch.FloatTensor(opt.batchSize)\n\n\nnum_batch = len(dset) / opt.batchSize\n###########################\n# G-NET and T-NET\n########################## \nif opt.D_choose == 1:\n for epoch in range(resume_epoch,opt.niter):\n if epoch<30:\n alpha1 = 0.01\n alpha2 = 0.02\n elif epoch<80:\n alpha1 = 0.05\n alpha2 = 0.1\n else:\n alpha1 = 0.1\n alpha2 = 0.2\n \n for i, data in enumerate(dataloader, 0):\n \n real_point, target = data\n \n \n batch_size = real_point.size()[0]\n real_center = torch.FloatTensor(batch_size, 1, opt.crop_point_num, 3) \n input_cropped1 = torch.FloatTensor(batch_size, opt.pnum, 3)\n input_cropped1 = input_cropped1.data.copy_(real_point)\n real_point = torch.unsqueeze(real_point, 1)\n input_cropped1 = torch.unsqueeze(input_cropped1,1)\n p_origin = [0,0,0]\n if opt.cropmethod == 'random_center':\n #Set viewpoints\n choice = [torch.Tensor([1,0,0]),torch.Tensor([0,0,1]),torch.Tensor([1,0,1]),torch.Tensor([-1,0,0]),torch.Tensor([-1,1,0])]\n for m in range(batch_size):\n index = random.sample(choice,1)#Random choose one of the viewpoint\n distance_list = []\n p_center = index[0]\n for n in range(opt.pnum):\n distance_list.append(distance_squre(real_point[m,0,n],p_center))\n distance_order = sorted(enumerate(distance_list), key = lambda x:x[1])\n \n for sp in range(opt.crop_point_num):\n input_cropped1.data[m,0,distance_order[sp][0]] = torch.FloatTensor([0,0,0])\n real_center.data[m,0,sp] = real_point[m,0,distance_order[sp][0]]\n label.resize_([batch_size,1]).fill_(real_label)\n real_point = real_point.to(device)\n real_center = real_center.to(device)\n input_cropped1 = input_cropped1.to(device)\n label = label.to(device)\n ############################\n # (1) data prepare\n ########################### \n real_center = Variable(real_center,requires_grad=True)\n real_center = torch.squeeze(real_center,1)\n real_center_key1_idx = utils.farthest_point_sample(real_center,64,RAN = False)\n real_center_key1 = utils.index_points(real_center,real_center_key1_idx)\n real_center_key1 =Variable(real_center_key1,requires_grad=True)\n\n real_center_key2_idx = utils.farthest_point_sample(real_center,128,RAN = True)\n real_center_key2 = utils.index_points(real_center,real_center_key2_idx)\n real_center_key2 =Variable(real_center_key2,requires_grad=True)\n\n input_cropped1 = torch.squeeze(input_cropped1,1)\n input_cropped2_idx = utils.farthest_point_sample(input_cropped1,opt.point_scales_list[1],RAN = True)\n input_cropped2 = utils.index_points(input_cropped1,input_cropped2_idx)\n input_cropped3_idx = utils.farthest_point_sample(input_cropped1,opt.point_scales_list[2],RAN = False)\n input_cropped3 = utils.index_points(input_cropped1,input_cropped3_idx)\n input_cropped1 = Variable(input_cropped1,requires_grad=True)\n input_cropped2 = Variable(input_cropped2,requires_grad=True)\n input_cropped3 = Variable(input_cropped3,requires_grad=True)\n input_cropped2 = input_cropped2.to(device)\n input_cropped3 = input_cropped3.to(device) \n input_cropped = [input_cropped1,input_cropped2,input_cropped3]\n point_netG = point_netG.train()\n point_netD = point_netD.train()\n ############################\n # (2) Update D network\n ########################### \n point_netD.zero_grad()\n real_center = torch.unsqueeze(real_center,1) \n output = point_netD(real_center)\n errD_real = criterion(output,label)\n errD_real.backward()\n fake_center1,fake_center2,fake =point_netG(input_cropped)\n fake = torch.unsqueeze(fake,1)\n label.data.fill_(fake_label)\n output = point_netD(fake.detach())\n errD_fake = criterion(output, label)\n errD_fake.backward()\n errD = errD_real + errD_fake\n optimizerD.step()\n ############################\n # (3) Update G network: maximize log(D(G(z)))\n ###########################\n point_netG.zero_grad()\n label.data.fill_(real_label)\n output = point_netD(fake)\n errG_D = criterion(output, label)\n errG_l2 = 0\n CD_LOSS = criterion_PointLoss(torch.squeeze(fake,1),torch.squeeze(real_center,1))\n \n errG_l2 = criterion_PointLoss(torch.squeeze(fake,1),torch.squeeze(real_center,1))\\\n +alpha1*criterion_PointLoss(fake_center1,real_center_key1)\\\n +alpha2*criterion_PointLoss(fake_center2,real_center_key2)\n \n errG = (1-opt.wtl2) * errG_D + opt.wtl2 * errG_l2\n errG.backward()\n optimizerG.step()\n print('[%d/%d][%d/%d] Loss_D: %.4f Loss_G: %.4f / %.4f / %.4f/ %.4f'\n % (epoch, opt.niter, i, len(dataloader), \n errD.data, errG_D.data,errG_l2,errG,CD_LOSS))\n f=open('loss_PFNet.txt','a')\n f.write('\\n'+'[%d/%d][%d/%d] Loss_D: %.4f Loss_G: %.4f / %.4f / %.4f /%.4f'\n % (epoch, opt.niter, i, len(dataloader), \n errD.data, errG_D.data,errG_l2,errG,CD_LOSS))\n \n \n if i % 100 ==0:\n print('After, ',i,'-th batch')\n f.write('\\n'+'After, '+str(i)+'-th batch')\n for i, data in enumerate(test_dataloader, 0):\n real_point, target = data\n \n \n batch_size = real_point.size()[0]\n real_center = torch.FloatTensor(batch_size, 1, opt.crop_point_num, 3)\n input_cropped1 = torch.FloatTensor(batch_size, opt.pnum, 3)\n input_cropped1 = input_cropped1.data.copy_(real_point)\n real_point = torch.unsqueeze(real_point, 1)\n input_cropped1 = torch.unsqueeze(input_cropped1,1)\n \n p_origin = [0,0,0]\n \n if opt.cropmethod == 'random_center':\n choice = [torch.Tensor([1,0,0]),torch.Tensor([0,0,1]),torch.Tensor([1,0,1]),torch.Tensor([-1,0,0]),torch.Tensor([-1,1,0])]\n \n for m in range(batch_size):\n index = random.sample(choice,1)\n distance_list = []\n p_center = index[0]\n for n in range(opt.pnum):\n distance_list.append(distance_squre(real_point[m,0,n],p_center))\n distance_order = sorted(enumerate(distance_list), key = lambda x:x[1]) \n for sp in range(opt.crop_point_num):\n input_cropped1.data[m,0,distance_order[sp][0]] = torch.FloatTensor([0,0,0])\n real_center.data[m,0,sp] = real_point[m,0,distance_order[sp][0]] \n real_center = real_center.to(device)\n real_center = torch.squeeze(real_center,1)\n input_cropped1 = input_cropped1.to(device) \n input_cropped1 = torch.squeeze(input_cropped1,1)\n input_cropped2_idx = utils.farthest_point_sample(input_cropped1,opt.point_scales_list[1],RAN = True)\n input_cropped2 = utils.index_points(input_cropped1,input_cropped2_idx)\n input_cropped3_idx = utils.farthest_point_sample(input_cropped1,opt.point_scales_list[2],RAN = False)\n input_cropped3 = utils.index_points(input_cropped1,input_cropped3_idx)\n input_cropped1 = Variable(input_cropped1,requires_grad=False)\n input_cropped2 = Variable(input_cropped2,requires_grad=False)\n input_cropped3 = Variable(input_cropped3,requires_grad=False)\n input_cropped2 = input_cropped2.to(device)\n input_cropped3 = input_cropped3.to(device) \n input_cropped = [input_cropped1,input_cropped2,input_cropped3]\n point_netG.eval()\n fake_center1,fake_center2,fake =point_netG(input_cropped)\n CD_loss = criterion_PointLoss(torch.squeeze(fake,1),torch.squeeze(real_center,1))\n print('test result:',CD_loss)\n f.write('\\n'+'test result: %.4f'%(CD_loss))\n break\n f.close()\n\n schedulerD.step()\n schedulerG.step()\n if epoch% 10 == 0 or epoch == opt.niter - 1:\n torch.save({'epoch':epoch+1,\n 'state_dict':point_netG.state_dict()},\n 'Trained_Model/point_netG'+str(epoch)+'.pth' )\n torch.save({'epoch':epoch+1,\n 'state_dict':point_netD.state_dict()},\n 'Trained_Model/point_netD'+str(epoch)+'.pth' ) \n\n#\n#############################\n## ONLY G-NET\n############################ \nelse:\n for epoch in range(resume_epoch,opt.niter):\n if epoch<30:\n alpha1 = 0.01\n alpha2 = 0.02\n elif epoch<80:\n alpha1 = 0.05\n alpha2 = 0.1\n else:\n alpha1 = 0.1\n alpha2 = 0.2\n \n for i, data in enumerate(dataloader, 0):\n \n real_point, target = data\n \n \n batch_size = real_point.size()[0]\n real_center = torch.FloatTensor(batch_size, 1, opt.crop_point_num, 3) \n input_cropped1 = torch.FloatTensor(batch_size, opt.pnum, 3)\n input_cropped1 = input_cropped1.data.copy_(real_point)\n real_point = torch.unsqueeze(real_point, 1)\n input_cropped1 = torch.unsqueeze(input_cropped1,1)\n p_origin = [0,0,0]\n if opt.cropmethod == 'random_center':\n choice = [torch.Tensor([1,0,0]),torch.Tensor([0,0,1]),torch.Tensor([1,0,1]),torch.Tensor([-1,0,0]),torch.Tensor([-1,1,0])]\n for m in range(batch_size):\n index = random.sample(choice,1)\n distance_list = []\n p_center = index[0]\n for n in range(opt.pnum):\n distance_list.append(distance_squre(real_point[m,0,n],p_center))\n distance_order = sorted(enumerate(distance_list), key = lambda x:x[1])\n \n for sp in range(opt.crop_point_num):\n input_cropped1.data[m,0,distance_order[sp][0]] = torch.FloatTensor([0,0,0])\n real_center.data[m,0,sp] = real_point[m,0,distance_order[sp][0]]\n real_point = real_point.to(device)\n real_center = real_center.to(device)\n input_cropped1 = input_cropped1.to(device)\n ############################\n # (1) data prepare\n ########################### \n real_center = Variable(real_center,requires_grad=True)\n real_center = torch.squeeze(real_center,1)\n real_center_key1_idx = utils.farthest_point_sample(real_center,64,RAN = False)\n real_center_key1 = utils.index_points(real_center,real_center_key1_idx)\n real_center_key1 =Variable(real_center_key1,requires_grad=True)\n\n real_center_key2_idx = utils.farthest_point_sample(real_center,128,RAN = True)\n real_center_key2 = utils.index_points(real_center,real_center_key2_idx)\n real_center_key2 =Variable(real_center_key2,requires_grad=True)\n \n input_cropped1 = torch.squeeze(input_cropped1,1)\n input_cropped2_idx = utils.farthest_point_sample(input_cropped1,opt.point_scales_list[1],RAN = True)\n input_cropped2 = utils.index_points(input_cropped1,input_cropped2_idx)\n input_cropped3_idx = utils.farthest_point_sample(input_cropped1,opt.point_scales_list[2],RAN = False)\n input_cropped3 = utils.index_points(input_cropped1,input_cropped3_idx)\n input_cropped1 = Variable(input_cropped1,requires_grad=True)\n input_cropped2 = Variable(input_cropped2,requires_grad=True)\n input_cropped3 = Variable(input_cropped3,requires_grad=True)\n input_cropped2 = input_cropped2.to(device)\n input_cropped3 = input_cropped3.to(device) \n input_cropped = [input_cropped1,input_cropped2,input_cropped3]\n point_netG = point_netG.train()\n point_netG.zero_grad()\n fake_center1,fake_center2,fake =point_netG(input_cropped)\n fake = torch.unsqueeze(fake,1)\n ############################\n # (3) Update G network: maximize log(D(G(z)))\n ###########################\n \n CD_LOSS = criterion_PointLoss(torch.squeeze(fake,1),torch.squeeze(real_center,1))\n \n errG_l2 = criterion_PointLoss(torch.squeeze(fake,1),torch.squeeze(real_center,1))\\\n +alpha1*criterion_PointLoss(fake_center1,real_center_key1)\\\n +alpha2*criterion_PointLoss(fake_center2,real_center_key2)\n\n errG_l2.backward()\n optimizerG.step()\n print('[%d/%d][%d/%d] Loss_G: %.4f / %.4f '\n % (epoch, opt.niter, i, len(dataloader), \n errG_l2,CD_LOSS))\n f=open('loss_PFNet.txt','a')\n f.write('\\n'+'[%d/%d][%d/%d] Loss_G: %.4f / %.4f '\n % (epoch, opt.niter, i, len(dataloader), \n errG_l2,CD_LOSS))\n f.close()\n schedulerD.step()\n schedulerG.step()\n \n if epoch% 10 == 0 or epoch == opt.niter - 1:\n torch.save({'epoch':epoch+1,\n 'state_dict':point_netG.state_dict()},\n 'Checkpoint/point_netG'+str(epoch)+'.pth' )\n \n\n \n \n"
] |
[
[
"torch.Tensor",
"torch.load",
"torch.nn.init.constant_",
"torch.manual_seed",
"torch.unsqueeze",
"torch.autograd.Variable",
"torch.nn.BCEWithLogitsLoss",
"torch.FloatTensor",
"torch.nn.init.normal_",
"torch.cuda.is_available",
"torch.cuda.manual_seed_all",
"torch.cuda.device_count",
"torch.squeeze",
"torch.optim.lr_scheduler.StepLR"
]
] |
lanl/nubhlight
|
[
"6c0f2abc05884538fe8e4e2e70a021b7c48a72c2"
] |
[
"script/analysis/check_transformation_matrices.py"
] |
[
"# ======================================================================\n# copyright 2020. Triad National Security, LLC. All rights\n# reserved. This program was produced under U.S. Government contract\n# 89233218CNA000001 for Los Alamos National Laboratory (LANL), which\n# is operated by Triad National Security, LLC for the U.S. Department\n# of Energy/National Nuclear Security Administration. All rights in\n# the program are reserved by Triad National Security, LLC, and the\n# U.S. Department of Energy/National Nuclear Security\n# Administration. The Government is granted for itself and others\n# acting on its behalf a nonexclusive, paid-up, irrevocable worldwide\n# license in this material to reproduce, prepare derivative works,\n# distribute copies to the public, perform publicly and display\n# publicly, and to permit others to do so.\n# ======================================================================\n\n# Authors: Oleg Korobkin ([email protected])\n# Purpose:\n# Provides a check of whether a coordinate transformation of the metric\n# from code coordinates to Kerr-Schild coordinates produces correct \n# metric, consistent with the closed form (as in e.g. Eq.(3)\n# McKinney & Gammie 2004, https://arxiv.org/abs/astro-ph/0404512)\n#\n# Functions:\n# - print_matrix\n# - check_transformation_matrices\n# \n\nfrom math import *\nimport numpy as np\n\ndef print_matrix(matrix,fmt=\"%19.11e\",tostdout=True) -> str:\n \"\"\"Pretty-prints a matrix to a string (optinally, to stdout)\n\n Parameters\n ----------\n matrix : numpy.array([N,M])\n matrix to print\n fmt : str\n C-style format of each element (default: \"%19.11e\")\n tostdout : bool\n output to stdout (default: true)\n\n Returns\n -------\n str\n formatted output string\n \"\"\"\n N = matrix.shape[0]\n M = matrix.shape[1]\n s = \"[\"\n for i in range(N):\n s+= \"[\"\n for j in range(M):\n s+= (fmt % matrix[i,j])\n if j < M - 1: s += \", \"\n s+= \"]\"\n if i < N - 1: s += \",\\n \"\n s+=\"]\"\n if tostdout: print(s)\n return s\n\n\ndef check_transformation_matrices(geom, a, ir, jth,\n verbose=True, tol=1e-12) -> bool:\n \"\"\"Transforms the metric to spherical KS and compares with analytic formula\n\n Test 1: covariant metric, gcov, at A = {ir, jth}\n 1.1 sample gcov and Lambda_h2bl_cov at A\n 1.2 transform gcov to gks using transofmration matrices\n 1.3 compare to expected values at {r,th} at A\n\n Parameters\n ----------\n geom : dictionary\n nubhlight geom object\n a : Float\n dimensionless Kerr spin parameter\n ir : Integer\n index of sample point in radial direction\n jth : Integer\n index of sample point in angular theta-direction\n verbose : bool\n output steps to stdout\n tol : Float\n tolerance to relative error (wrt det g)\n\n Returns\n -------\n bool\n True if all checks passed\n\n Examples\n --------\n import hdf5_to_dict as io\n hdr = io.load_hdr(\"dump_00000010.h5\")\n geom = io.load_geom(hdr,recalc=True)\n check_transformation_matrices(geom, -1, 64)\n \"\"\"\n # sample gcov and h2bl at point A\n gcov_A = geom['gcov'][ir,jth]\n h2bl_A = geom['Lambda_h2bl_cov'][ir,jth]\n\n # sample r and theta, compute BL metric-related quantities\n r = geom['r'][ir,jth,0]; r2 = r*r\n a2 = a*a\n th= geom['th'][ir,jth,0]\n sth2= sin(th)**2\n Delta= r2 - 2*r + a2\n Sigma= r2 + a2*cos(th)**2\n A = (r2 + a2)**2 - a2*Delta*sin(th)**2\n\n if verbose:\n print (\"r = %19.11e\" % r)\n print (\"theta = %19.11e\" % th)\n print (\"a = %19.11e\" % a)\n print (\"Delta = %19.11e\" % Delta)\n print (\"Sigma = %19.11e\" % Sigma)\n print (\"A = %19.11e\" % A)\n\n # output metric\n print (\"gcov_A = \")\n print_matrix (gcov_A)\n print (\"\")\n\n # output transformation matrix\n print (\"h2bl_A = \")\n print_matrix (h2bl_A)\n print (\"\")\n\n # compute BL metric at A\n gks_A = np.zeros([4,4])\n\n for i in range(4):\n for j in range(4):\n for k in range(4):\n for l in range(4):\n gks_A[i,j] = gks_A[i,j] + h2bl_A[k,i]*h2bl_A[l,j]*gcov_A[k,l]\n if verbose:\n print (\"gks_A = \")\n print_matrix (gks_A)\n print(\"\")\n\n # expected values at {r, th}\n g_tt = -1. + 2.*r/Sigma\n g_rr = 1. + 2.*r/Sigma\n g_ff = sth2*(Sigma + a2*g_rr*sth2)\n g_thth = Sigma\n\n g_tr = 2*r/Sigma\n g_tf = -2*a*r*sth2/Sigma\n g_rf = -a*g_rr*sth2\n det_g = -Sigma**2*sth2\n\n if verbose:\n print (\"Expected:\")\n print (\" g_tt = %19.11e\" % g_tt )\n print (\" g_rr = %19.11e\" % g_rr )\n print (\" g_thth = %19.11e\" % g_thth)\n print (\" g_ff = %19.11e\" % g_ff )\n print (\" g_tr = %19.11e\" % g_tr )\n print (\" g_rf = %19.11e\" % g_rf )\n print (\" g_tf = %19.11e\" % g_tf )\n print (\"\")\n\n # check gks_A\n gks_expected = np.array(\n [[ g_tt, g_tr, 0.0, g_tf],\n [ g_tr, g_rr, 0.0, g_rf],\n [ 0.0, 0.0, g_thth, 0.0],\n [ g_tf, g_rf, 0.0, g_ff]]\n )\n\n passed = True\n for i in range(4):\n for j in range(4):\n if abs(gks_A[i,j] - gks_expected[i,j])/abs(det_g) > tol:\n passed = False\n if verbose:\n print (f\"WARNING: Significant mismatch in gks_A[{i},{j}]:\")\n print (\" -- expected: %19.11e\" % gks_expected[i,j])\n print (\" -- actual: %19.11e\" % gks_A[i,j])\n\n return passed\n"
] |
[
[
"numpy.array",
"numpy.zeros"
]
] |
almostdutch/mortgage-payment-optimization
|
[
"9aeb9037ceb4383fe679f0e210bbfc06a828cee8"
] |
[
"demo_mortgage_payment_optimization.py"
] |
[
"\"\"\"\ndemo_mortgage_payment_optimization.py\n\nNumerical optimization to find the optimum way for the quickest reduction in the mortage debt \\\n while keeping the monthly payments as low as possible.\n \nSet lambda1 and lambda2 according to your priorities.\n\nmortgage_amount = initial mortgage amount \nN_months = number of months\n\nX_debt = mortgage debt remaining after each month\nlambda1 = regularization for X_debt\n\nX_repayment = mortgage monthly payment after each month\nlambda2 = regularization for X_repayment\n\ninterest = annual interest [%]\n\nminimize: \n f(X_debt, X_repayment) = 1 / 2 * (lambda1 * X_debt.T @ X_debt + lambda2 * X_repayment.T @ X_repayment); \nsubject to: \n X_debt(new) = (1 + interest / (100 * 12)) * X_debt(old) - X_repayment;\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nmortgage_amount = 200000;\ninterest = 2;\nlambda1 = 1.0; \nlambda2 = 2000.0;\nN_months = 12 * 30; \nfontsize = 24;\nlabelsize = 24;\n\ntemp1 = lambda1 * np.eye(N_months, N_months);\ntemp2 = np.zeros((N_months, N_months));\ntemp3 = np.zeros((N_months, N_months));\ntemp4 = lambda2 * np.eye(N_months, N_months);\ntemp12 = np.concatenate((temp1, temp2), axis = 0);\ntemp34 = np.concatenate((temp3, temp4), axis = 0);\nE = np.concatenate((temp12, temp34), axis = 1);\n\nb = -1.0; \ntemp1 = np.diag(np.repeat(-(1 + interest / (100 * 12)), N_months - 1), k = -1) + np.eye(N_months, N_months);\ntemp2 = -b * np.eye(N_months, N_months);\nA = np.concatenate((temp1, temp2), axis = 1);\n\nB = np.zeros((N_months, 1));\nB[0] = (1 + interest / (100 * 12)) * mortgage_amount;\n\nEinv = np.linalg.inv(E);\nX = Einv @ A.T @ np.linalg.inv(A @ Einv @ A.T) @ B;\n\nX_debt = X[0:N_months];\nX_repayment = X[N_months:]; \nmonths = np.arange(1, N_months + 1);\n\nfig_width, fig_height = 15, 10;\nfig, ((ax1, ax2)) = plt.subplots(nrows=1, ncols=2, figsize=(fig_width, fig_height));\n\nax1.plot(months, X_debt)\nax1.set_title(\"Mortgage remaining debt\", fontsize = fontsize)\nax1.tick_params(axis='both', which='major', labelsize = labelsize)\nax1.tick_params(axis='both', which='minor', labelsize = labelsize)\nax1.set_xlabel('Month #', fontsize = fontsize)\nax1.set_ylabel('Amount', fontsize = fontsize)\nax1.set_xlim([0, N_months])\nax1.set_ylim([0, mortgage_amount])\n\nax2.plot(months, X_repayment)\nax2.set_title(\"Mortgage monthly repayment\", fontsize = fontsize)\nax2.tick_params(axis='both', which='major', labelsize = labelsize)\nax2.tick_params(axis='both', which='minor', labelsize = labelsize)\nax2.set_xlabel('Month #', fontsize = fontsize)\nax2.set_ylabel('Amount', fontsize = fontsize)\nax2.set_xlim([0, N_months])\nax2.set_ylim([0, X_repayment.max()])\nplt.tight_layout()\n"
] |
[
[
"matplotlib.pyplot.tight_layout",
"numpy.linalg.inv",
"numpy.arange",
"numpy.eye",
"matplotlib.pyplot.subplots",
"numpy.concatenate",
"numpy.repeat",
"numpy.zeros"
]
] |
lialzm/akshare
|
[
"5bc7f0ddcb540f4290c37a89b23feba3fceddf18",
"5bc7f0ddcb540f4290c37a89b23feba3fceddf18"
] |
[
"akshare/index/index_zh_em.py",
"akshare/stock/stock_info_em.py"
] |
[
"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\"\"\"\nDate: 2022/2/2 23:26\nDesc: 东方财富网-行情首页-沪深京 A 股\n\"\"\"\nimport requests\nimport pandas as pd\n\n\ndef index_code_id_map_em() -> dict:\n \"\"\"\n 东方财富-股票和市场代码\n http://quote.eastmoney.com/center/gridlist.html#hs_a_board\n :return: 股票和市场代码\n :rtype: dict\n \"\"\"\n url = \"http://80.push2.eastmoney.com/api/qt/clist/get\"\n params = {\n \"pn\": \"1\",\n \"pz\": \"5000\",\n \"po\": \"1\",\n \"np\": \"1\",\n \"ut\": \"bd1d9ddb04089700cf9c27f6f7426281\",\n \"fltt\": \"2\",\n \"invt\": \"2\",\n \"fid\": \"f3\",\n \"fs\": \"m:1 t:2,m:1 t:23\",\n \"fields\": \"f12\",\n \"_\": \"1623833739532\",\n }\n r = requests.get(url, params=params)\n data_json = r.json()\n if not data_json[\"data\"][\"diff\"]:\n return dict()\n temp_df = pd.DataFrame(data_json[\"data\"][\"diff\"])\n temp_df[\"market_id\"] = 1\n temp_df.columns = [\"sh_code\", \"sh_id\"]\n code_id_dict = dict(zip(temp_df[\"sh_code\"], temp_df[\"sh_id\"]))\n params = {\n \"pn\": \"1\",\n \"pz\": \"5000\",\n \"po\": \"1\",\n \"np\": \"1\",\n \"ut\": \"bd1d9ddb04089700cf9c27f6f7426281\",\n \"fltt\": \"2\",\n \"invt\": \"2\",\n \"fid\": \"f3\",\n \"fs\": \"m:0 t:6,m:0 t:80\",\n \"fields\": \"f12\",\n \"_\": \"1623833739532\",\n }\n r = requests.get(url, params=params)\n data_json = r.json()\n if not data_json[\"data\"][\"diff\"]:\n return dict()\n temp_df_sz = pd.DataFrame(data_json[\"data\"][\"diff\"])\n temp_df_sz[\"sz_id\"] = 0\n code_id_dict.update(dict(zip(temp_df_sz[\"f12\"], temp_df_sz[\"sz_id\"])))\n params = {\n \"pn\": \"1\",\n \"pz\": \"5000\",\n \"po\": \"1\",\n \"np\": \"1\",\n \"ut\": \"bd1d9ddb04089700cf9c27f6f7426281\",\n \"fltt\": \"2\",\n \"invt\": \"2\",\n \"fid\": \"f3\",\n \"fs\": \"m:0 t:81 s:2048\",\n \"fields\": \"f12\",\n \"_\": \"1623833739532\",\n }\n r = requests.get(url, params=params)\n data_json = r.json()\n if not data_json[\"data\"][\"diff\"]:\n return dict()\n temp_df_sz = pd.DataFrame(data_json[\"data\"][\"diff\"])\n temp_df_sz[\"bj_id\"] = 0\n code_id_dict.update(dict(zip(temp_df_sz[\"f12\"], temp_df_sz[\"bj_id\"])))\n code_id_dict = {\n key: value - 1 if value == 1 else value + 1\n for key, value in code_id_dict.items()\n }\n return code_id_dict\n\n\ndef index_zh_a_hist(\n symbol: str = \"399282\",\n period: str = \"daily\",\n start_date: str = \"19700101\",\n end_date: str = \"22220101\",\n) -> pd.DataFrame:\n \"\"\"\n 东方财富网-中国股票指数-行情数据\n http://quote.eastmoney.com/concept/sh603777.html?from=classic\n :param symbol: 指数代码\n :type symbol: str\n :param period: choice of {'daily', 'weekly', 'monthly'}\n :type period: str\n :param start_date: 开始日期\n :type start_date: str\n :param end_date: 结束日期\n :type end_date: str\n :return: 行情数据\n :rtype: pandas.DataFrame\n \"\"\"\n code_id_dict = index_code_id_map_em()\n period_dict = {\"daily\": \"101\", \"weekly\": \"102\", \"monthly\": \"103\"}\n url = \"http://push2his.eastmoney.com/api/qt/stock/kline/get\"\n try:\n params = {\n \"secid\": f\"{code_id_dict[symbol]}.{symbol}\",\n \"ut\": \"7eea3edcaed734bea9cbfc24409ed989\",\n \"fields1\": \"f1,f2,f3,f4,f5,f6\",\n \"fields2\": \"f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61\",\n \"klt\": period_dict[period],\n \"fqt\": \"0\",\n \"beg\": \"0\",\n \"end\": \"20500000\",\n \"_\": \"1623766962675\",\n }\n except KeyError:\n params = {\n \"secid\": f\"1.{symbol}\",\n \"ut\": \"7eea3edcaed734bea9cbfc24409ed989\",\n \"fields1\": \"f1,f2,f3,f4,f5,f6\",\n \"fields2\": \"f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61\",\n \"klt\": period_dict[period],\n \"fqt\": \"0\",\n \"beg\": \"0\",\n \"end\": \"20500000\",\n \"_\": \"1623766962675\",\n }\n r = requests.get(url, params=params)\n data_json = r.json()\n if data_json[\"data\"] is None:\n params = {\n \"secid\": f\"0.{symbol}\",\n \"ut\": \"7eea3edcaed734bea9cbfc24409ed989\",\n \"fields1\": \"f1,f2,f3,f4,f5,f6\",\n \"fields2\": \"f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61\",\n \"klt\": period_dict[period],\n \"fqt\": \"0\",\n \"beg\": \"0\",\n \"end\": \"20500000\",\n \"_\": \"1623766962675\",\n }\n\n r = requests.get(url, params=params)\n data_json = r.json()\n temp_df = pd.DataFrame([item.split(\",\") for item in data_json[\"data\"][\"klines\"]])\n temp_df.columns = [\n \"日期\",\n \"开盘\",\n \"收盘\",\n \"最高\",\n \"最低\",\n \"成交量\",\n \"成交额\",\n \"振幅\",\n \"涨跌幅\",\n \"涨跌额\",\n \"换手率\",\n ]\n temp_df.index = pd.to_datetime(temp_df[\"日期\"])\n temp_df = temp_df[start_date:end_date]\n temp_df.reset_index(inplace=True, drop=True)\n temp_df[\"开盘\"] = pd.to_numeric(temp_df[\"开盘\"])\n temp_df[\"收盘\"] = pd.to_numeric(temp_df[\"收盘\"])\n temp_df[\"最高\"] = pd.to_numeric(temp_df[\"最高\"])\n temp_df[\"最低\"] = pd.to_numeric(temp_df[\"最低\"])\n temp_df[\"成交量\"] = pd.to_numeric(temp_df[\"成交量\"])\n temp_df[\"成交额\"] = pd.to_numeric(temp_df[\"成交额\"])\n temp_df[\"振幅\"] = pd.to_numeric(temp_df[\"振幅\"])\n temp_df[\"涨跌幅\"] = pd.to_numeric(temp_df[\"涨跌幅\"])\n temp_df[\"涨跌额\"] = pd.to_numeric(temp_df[\"涨跌额\"])\n temp_df[\"换手率\"] = pd.to_numeric(temp_df[\"换手率\"])\n return temp_df\n\n\ndef index_zh_a_hist_min_em(\n symbol: str = \"000016\",\n period: str = \"5\",\n start_date: str = \"1979-09-01 09:32:00\",\n end_date: str = \"2222-01-01 09:32:00\",\n) -> pd.DataFrame:\n \"\"\"\n 东方财富网-指数数据-每日分时行情\n http://quote.eastmoney.com/concept/sh603777.html?from=classic\n :param symbol: 股票代码\n :type symbol: str\n :param period: choice of {'1', '5', '15', '30', '60'}\n :type period: str\n :param start_date: 开始日期\n :type start_date: str\n :param end_date: 结束日期\n :type end_date: str\n :return: 每日分时行情\n :rtype: pandas.DataFrame\n \"\"\"\n code_id_dict = index_code_id_map_em()\n if period == \"1\":\n url = \"http://push2his.eastmoney.com/api/qt/stock/trends2/get\"\n try:\n params = {\n \"fields1\": \"f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13\",\n \"fields2\": \"f51,f52,f53,f54,f55,f56,f57,f58\",\n \"ut\": \"fa5fd1943c7b386f172d6893dbfba10b\",\n \"iscr\": \"0\",\n \"ndays\": \"5\",\n \"secid\": f\"{code_id_dict[symbol]}.{symbol}\",\n \"_\": \"1623766962675\",\n }\n except KeyError:\n params = {\n \"fields1\": \"f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13\",\n \"fields2\": \"f51,f52,f53,f54,f55,f56,f57,f58\",\n \"ut\": \"fa5fd1943c7b386f172d6893dbfba10b\",\n \"iscr\": \"0\",\n \"ndays\": \"5\",\n \"secid\": f\"1.{symbol}\",\n \"_\": \"1623766962675\",\n }\n r = requests.get(url, params=params)\n data_json = r.json()\n if data_json[\"data\"] is None:\n params = {\n \"fields1\": \"f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13\",\n \"fields2\": \"f51,f52,f53,f54,f55,f56,f57,f58\",\n \"ut\": \"fa5fd1943c7b386f172d6893dbfba10b\",\n \"iscr\": \"0\",\n \"ndays\": \"5\",\n \"secid\": f\"0.{symbol}\",\n \"_\": \"1623766962675\",\n }\n r = requests.get(url, params=params)\n data_json = r.json()\n temp_df = pd.DataFrame(\n [item.split(\",\") for item in data_json[\"data\"][\"trends\"]]\n )\n temp_df.columns = [\n \"时间\",\n \"开盘\",\n \"收盘\",\n \"最高\",\n \"最低\",\n \"成交量\",\n \"成交额\",\n \"最新价\",\n ]\n temp_df.index = pd.to_datetime(temp_df[\"时间\"])\n temp_df = temp_df[start_date:end_date]\n temp_df.reset_index(drop=True, inplace=True)\n temp_df[\"开盘\"] = pd.to_numeric(temp_df[\"开盘\"])\n temp_df[\"收盘\"] = pd.to_numeric(temp_df[\"收盘\"])\n temp_df[\"最高\"] = pd.to_numeric(temp_df[\"最高\"])\n temp_df[\"最低\"] = pd.to_numeric(temp_df[\"最低\"])\n temp_df[\"成交量\"] = pd.to_numeric(temp_df[\"成交量\"])\n temp_df[\"成交额\"] = pd.to_numeric(temp_df[\"成交额\"])\n temp_df[\"最新价\"] = pd.to_numeric(temp_df[\"最新价\"])\n temp_df[\"时间\"] = pd.to_datetime(temp_df[\"时间\"]).astype(str)\n return temp_df\n else:\n url = \"http://push2his.eastmoney.com/api/qt/stock/kline/get\"\n params = {\n \"secid\": f\"{code_id_dict[symbol]}.{symbol}\",\n \"ut\": \"7eea3edcaed734bea9cbfc24409ed989\",\n \"fields1\": \"f1,f2,f3,f4,f5,f6\",\n \"fields2\": \"f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61\",\n \"klt\": period,\n \"fqt\": \"1\",\n \"beg\": \"0\",\n \"end\": \"20500000\",\n \"_\": \"1630930917857\",\n }\n r = requests.get(url, params=params)\n data_json = r.json()\n temp_df = pd.DataFrame(\n [item.split(\",\") for item in data_json[\"data\"][\"klines\"]]\n )\n temp_df.columns = [\n \"时间\",\n \"开盘\",\n \"收盘\",\n \"最高\",\n \"最低\",\n \"成交量\",\n \"成交额\",\n \"振幅\",\n \"涨跌幅\",\n \"涨跌额\",\n \"换手率\",\n ]\n temp_df.index = pd.to_datetime(temp_df[\"时间\"])\n temp_df = temp_df[start_date:end_date]\n temp_df.reset_index(drop=True, inplace=True)\n temp_df[\"开盘\"] = pd.to_numeric(temp_df[\"开盘\"])\n temp_df[\"收盘\"] = pd.to_numeric(temp_df[\"收盘\"])\n temp_df[\"最高\"] = pd.to_numeric(temp_df[\"最高\"])\n temp_df[\"最低\"] = pd.to_numeric(temp_df[\"最低\"])\n temp_df[\"成交量\"] = pd.to_numeric(temp_df[\"成交量\"])\n temp_df[\"成交额\"] = pd.to_numeric(temp_df[\"成交额\"])\n temp_df[\"振幅\"] = pd.to_numeric(temp_df[\"振幅\"])\n temp_df[\"涨跌幅\"] = pd.to_numeric(temp_df[\"涨跌幅\"])\n temp_df[\"涨跌额\"] = pd.to_numeric(temp_df[\"涨跌额\"])\n temp_df[\"换手率\"] = pd.to_numeric(temp_df[\"换手率\"])\n temp_df[\"时间\"] = pd.to_datetime(temp_df[\"时间\"]).astype(str)\n temp_df = temp_df[\n [\n \"时间\",\n \"开盘\",\n \"收盘\",\n \"最高\",\n \"最低\",\n \"涨跌幅\",\n \"涨跌额\",\n \"成交量\",\n \"成交额\",\n \"振幅\",\n \"换手率\",\n ]\n ]\n return temp_df\n\n\nif __name__ == \"__main__\":\n index_zh_a_hist_df = index_zh_a_hist(\n symbol=\"000003\",\n period=\"daily\",\n start_date=\"19700101\",\n end_date=\"22220101\",\n )\n print(index_zh_a_hist_df)\n\n index_zh_a_hist_min_em_df = index_zh_a_hist_min_em(\n symbol=\"000016\",\n period=\"1\",\n start_date=\"1979-09-01 09:32:00\",\n end_date=\"2222-01-01 09:32:00\",\n )\n print(index_zh_a_hist_min_em_df)\n",
"# -*- coding:utf-8 -*-\n# !/usr/bin/env python\n\"\"\"\nDate: 2022/1/7 16:21\nDesc: 东方财富网-个股-股票信息\nhttp://quote.eastmoney.com/concept/sh603777.html?from=classic\n\"\"\"\nimport pandas as pd\nimport requests\n\nfrom akshare.stock_feature.stock_hist_em import code_id_map_em\n\n\ndef stock_individual_info_em(symbol: str = \"603777\") -> pd.DataFrame:\n \"\"\"\n 东方财富-个股-股票信息\n http://quote.eastmoney.com/concept/sh603777.html?from=classic\n :param symbol: 股票代码\n :type symbol: str\n :return: 股票信息\n :rtype: pandas.DataFrame\n \"\"\"\n code_id_dict = code_id_map_em()\n url = \"http://push2.eastmoney.com/api/qt/stock/get\"\n params = {\n 'ut': 'fa5fd1943c7b386f172d6893dbfba10b',\n 'fltt': '2',\n 'invt': '2',\n 'fields': 'f120,f121,f122,f174,f175,f59,f163,f43,f57,f58,f169,f170,f46,f44,f51,f168,f47,f164,f116,f60,f45,f52,f50,f48,f167,f117,f71,f161,f49,f530,f135,f136,f137,f138,f139,f141,f142,f144,f145,f147,f148,f140,f143,f146,f149,f55,f62,f162,f92,f173,f104,f105,f84,f85,f183,f184,f185,f186,f187,f188,f189,f190,f191,f192,f107,f111,f86,f177,f78,f110,f262,f263,f264,f267,f268,f255,f256,f257,f258,f127,f199,f128,f198,f259,f260,f261,f171,f277,f278,f279,f288,f152,f250,f251,f252,f253,f254,f269,f270,f271,f272,f273,f274,f275,f276,f265,f266,f289,f290,f286,f285,f292,f293,f294,f295',\n \"secid\": f\"{code_id_dict[symbol]}.{symbol}\",\n '_': '1640157544804',\n }\n r = requests.get(url, params=params)\n data_json = r.json()\n temp_df = pd.DataFrame(data_json)\n temp_df.reset_index(inplace=True)\n del temp_df['rc']\n del temp_df['rt']\n del temp_df['svr']\n del temp_df['lt']\n del temp_df['full']\n code_name_map = {\n 'f57': '股票代码',\n 'f58': '股票简称',\n 'f84': '总股本',\n 'f85': '流通股',\n 'f127': '行业',\n 'f116': '总市值',\n 'f117': '流通市值',\n 'f189': '上市时间',\n }\n temp_df['index'] = temp_df['index'].map(code_name_map)\n temp_df = temp_df[pd.notna(temp_df['index'])]\n temp_df.columns = [\n 'item',\n 'value',\n ]\n temp_df.reset_index(inplace=True, drop=True)\n return temp_df\n\n\nif __name__ == '__main__':\n stock_individual_info_em_df = stock_individual_info_em(symbol=\"601816\")\n print(stock_individual_info_em_df)\n"
] |
[
[
"pandas.to_datetime",
"pandas.to_numeric",
"pandas.DataFrame"
],
[
"pandas.notna",
"pandas.DataFrame"
]
] |
Brinks0211/cognitive_paradigms_patients_data_analysis
|
[
"c9a231cb5e1ec321f11b99a3bacb0ed80b2c4bac",
"c9a231cb5e1ec321f11b99a3bacb0ed80b2c4bac"
] |
[
"11_Time_Perception.py",
"9_Simple_Guessing_Task.py"
] |
[
"import csv\r\nimport numpy\r\nimport tkinter as tk\r\nfrom tkinter.filedialog import askopenfilename\r\nreacttime = []\r\ncorratio = []\r\nStandard_Deviation = []\r\n\r\n# GUI\r\nroot = tk.Tk()\r\nroot.wm_title(\"11_Time_Perception\")\r\nroot.geometry(\"700x200\")\r\npath=tk.StringVar()\r\nw0=tk.Label(root, text='11_Time_Perception',width=40)\r\nw0.place(x=190,y=10)\r\nw1=tk.Label(root, text='姓名:').place(x=10, y=60)\r\nname=tk.Entry(root, width=60)\r\nname.place(x=100,y=60)\r\nw2=tk.Label(root, text=\"时间:\").place(x=10, y=90)\r\ntime=tk.Entry(root, width=60)\r\ntime.place(x=100, y=90)\r\nw3=tk.Label(root, text='文件路径:').place(x=10, y=120)\r\npath1=tk.Entry(root, textvariable=path, width=60)\r\npath1.place(x=100, y=120)\r\ndef selectpath():\r\n path_ = askopenfilename()\r\n path.set(path_)\r\ndef filepathget():\r\n global filename,time,name\r\n name=name.get()\r\n time=time.get()\r\n filename=path1.get()\r\n # print(filename)\r\n root.withdraw()\r\n root.destroy()\r\nb1 = tk.Button(root, text='确定', font=('Arial', 12), width=10,command=filepathget)\r\nb1.place(x=300, y=150)\r\nb2 = tk.Button(root,text=\"选择文件\",font=('Arial', 10),width=7, height=1, command=selectpath)\r\nb2.place(x=530, y=120)\r\nroot.mainloop()\r\n\r\nprint(\"文件开始处理。\")\r\n# 文件数据读取\r\nf = open(filename, 'r', encoding='utf-8')\r\nfilereader = csv.reader(f)\r\naudio_rt=[]\r\nimage_rt=[]\r\ntimespan=[]\r\nfor i,line in enumerate(filereader):\r\n if i==0:\r\n for j in range(len(line)):\r\n if line[j] == 'key_resp_12.rt':\r\n audio_num=j\r\n if line[j] == 'key_resp_10.rt':\r\n image_num=j\r\n if line[j]=='key_resp_12.keys':\r\n switch1=j\r\n if line[j] == 'key_resp_10.keys':\r\n switch2=j\r\n if line[switch1] == 'right':\r\n audio_rt.append(float(str(line[audio_num]).strip())-float(str(line[0]).strip()))\r\n if line[switch2] == 'right':\r\n image_rt.append(float(str(line[image_num]).strip()) - float(str(line[0]).strip()))\r\n# print(audio_rt)\r\n# print(image_rt)\r\n# print(len(audio_rt)+len(image_rt))\r\n\r\n# 求正确率\r\ndef correct(data):\r\n right=0\r\n total=0\r\n for i in range(len(data)):\r\n if data[i] =='1':\r\n total += 1\r\n right += 1\r\n else :\r\n total += 1\r\n ratio=right/total\r\n ratio=ratio*100\r\n return ratio\r\n\r\n# 求反应时平均值及方差\r\ndef aver(data):\r\n raw_rt=[]\r\n for i in range(len(data)):\r\n raw_rt.append(float(data[i]))\r\n aver=numpy.mean(raw_rt)\r\n std1=numpy.std(raw_rt)\r\n return aver,std1\r\n\r\n# 计算结果\r\ntotal_rt=[audio_rt,image_rt]\r\nfor i in range(len(total_rt)):\r\n aver_con,std=aver(total_rt[i])\r\n reacttime.append(aver_con)\r\n Standard_Deviation.append(std)\r\n# print(reacttime)\r\n# print(Standard_Deviation)\r\ntotal=['听觉','视觉']\r\n\r\n# # 数据输出\r\n# print(\"—————————————————————————————\")\r\n# print(\" 知觉 误差 标准差\")\r\n# print(\"—————————————————————————————\")\r\n# for i in range(0,2):\r\n# print(\" {} {:.5f} {:.5f}\".format(total[i],reacttime[i],Standard_Deviation[i]))\r\n# print(\"—————————————————————————————\")\r\n\r\n# 绘图\r\nimport matplotlib.pyplot as plt\r\nplt.style.use('ggplot')\r\n#解决中文显示问题\r\nplt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默认字体\r\nplt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题\r\n# 平均反应时\r\nfig=plt.figure()\r\nax1=fig.add_subplot(1,1,1)\r\nax1.bar(total, reacttime, align='center', color='darkblue',width=0.3)\r\nax1.errorbar(x=total,y=reacttime,yerr=Standard_Deviation,ecolor='grey',capsize=4,color='black',fmt='o')\r\n# ax1.bar(expression,corratio,align='center',color='red')\r\nax1.xaxis.set_ticks_position(\"bottom\")\r\nax1.yaxis.set_ticks_position(\"left\")\r\nplt.xlabel('Time_Perception')\r\nplt.ylabel('时间(秒)')\r\nplt.title('图1:误差时间(秒)')\r\nplt.savefig('reaction_time.png',dpi=400,bbox_inches='tight')\r\nplt.show()\r\n\r\n# 绘制pdf文档\r\nfrom fpdf import FPDF\r\npdf = FPDF('p','mm','A4')\r\npdf.add_page()\r\npdf.add_font('hei','',fname=r'C:\\Windows\\Fonts\\simhei.ttf',uni=True)\r\npdf.set_font(\"hei\", size=18)\r\npdf.cell(180, 20, txt=\"电脑认知测试十一:视觉和听觉的时间知觉能力\", ln=1, align=\"C\")\r\npdf.set_font('hei',size=12)\r\npdf.cell(180,13,txt='姓名:'+name,ln=1)\r\npdf.cell(180,13,txt='时间:'+time,ln=1)\r\npdf.cell(180,7,txt='———————————————————————',ln=1,align=\"C\")\r\npdf.cell(180,7,txt='知觉 误差时间(秒) 标准差',ln=1,align='C')\r\npdf.cell(180,7,txt='———————————————————————',ln=1,align='C')\r\nfor i in range(0,2):\r\n text=\"{} {:.5f} {:.5f}\".format(total[i],reacttime[i],Standard_Deviation[i])\r\n pdf.cell(180,7,txt=text,ln=1,align=\"C\")\r\npdf.cell(180,7,txt='———————————————————————',ln=1,align='C')\r\npdf.image('reaction_time.png',x=50,y=160,w=100,h=86)\r\npdf.output(\"11_Time_Perception.pdf\")\r\n\r\nprint(\"文件处理完成。\")",
"import csv\r\nimport numpy\r\nimport tkinter as tk\r\nfrom tkinter.filedialog import askopenfilename\r\nreacttime = []\r\ncorratio = []\r\nStandard_Deviation = []\r\n\r\n# GUI\r\nroot = tk.Tk()\r\nroot.wm_title(\"9_Simple_Guessing_Task\")\r\nroot.geometry(\"700x200\")\r\npath=tk.StringVar()\r\nw0=tk.Label(root, text='9_Simple_Guessing_Task',width=40)\r\nw0.place(x=190,y=10)\r\nw1=tk.Label(root, text='姓名:').place(x=10, y=60)\r\nname=tk.Entry(root, width=60)\r\nname.place(x=100,y=60)\r\nw2=tk.Label(root, text=\"时间:\").place(x=10, y=90)\r\ntime=tk.Entry(root, width=60)\r\ntime.place(x=100, y=90)\r\nw3=tk.Label(root, text='文件路径:').place(x=10, y=120)\r\npath1=tk.Entry(root, textvariable=path, width=60)\r\npath1.place(x=100, y=120)\r\ndef selectpath():\r\n path_ = askopenfilename()\r\n path.set(path_)\r\ndef filepathget():\r\n global filename,time,name\r\n name=name.get()\r\n time=time.get()\r\n filename=path1.get()\r\n # print(filename)\r\n root.withdraw()\r\n root.destroy()\r\nb1 = tk.Button(root, text='确定', font=('Arial', 12), width=10,command=filepathget)\r\nb1.place(x=300, y=150)\r\nb2 = tk.Button(root,text=\"选择文件\",font=('Arial', 10),width=7, height=1, command=selectpath)\r\nb2.place(x=530, y=120)\r\nroot.mainloop()\r\n\r\nprint(\"文件开始处理。\")\r\n# 文件数据读取\r\nf = open(filename, 'r', encoding='utf-8')\r\nfilereader = csv.reader(f)\r\nsentence=[]\r\nrt=[]\r\nfor i,line in enumerate(filereader):\r\n if i==0:\r\n for j in range(len(line)):\r\n if line[j] == 'fdb2':\r\n sentence_num=j\r\n if line[j] == 'key_resp_formal1.rt':\r\n rt_num=j\r\n if line[sentence_num] =='恭喜你,猜对了!' or line[sentence_num] == '很遗憾,你猜错了。':\r\n sentence.append(str(line[sentence_num]).strip())\r\n try :\r\n rt.append(eval(str(line[rt_num]).strip()))\r\n except:\r\n pass\r\n# print(sentence)\r\n# print(rt)\r\n# print(len(sentence)+len(rt))\r\n\r\n# 求反应时平均值及方差\r\ndef aver(data):\r\n raw_rt=[]\r\n for i in range(len(data)):\r\n raw_rt.append(float(data[i]))\r\n aver=numpy.mean(raw_rt)\r\n std1=numpy.std(raw_rt)\r\n return aver,std1\r\n\r\n\r\ndef chunks(arr, n):\r\n return [arr[i:i+n] for i in range(0, len(arr), n)]\r\nrt=chunks(rt,16)\r\nsentence=chunks(sentence,16)\r\ndef select(sen_data,rt_data):\r\n rt_right=[]\r\n rt_wrong=[]\r\n for i in range(len(sen_data)-1):\r\n if sen_data[i] == '恭喜你,猜对了!':\r\n rt_right.append(rt_data[i+1])\r\n if sen_data[i] == '很遗憾,你猜错了。':\r\n rt_wrong.append(rt_data[i+1])\r\n aver_right,std_right=aver(rt_right)\r\n aver_wrong,std_wrong=aver(rt_wrong)\r\n return aver_right,std_right,aver_wrong,std_wrong\r\n\r\nreacttime_right=[]\r\nreacttime_wrong=[]\r\nstd_right=[]\r\nstd_wrong=[]\r\n\r\nfor i in range(len(sentence)):\r\n aver1,std1,aver2,std2=select(sentence[i],rt[i])\r\n reacttime_right.append(aver1)\r\n reacttime_wrong.append(aver2)\r\n std_right.append(std1)\r\n std_wrong.append(std2)\r\n\r\ntotal=['阶段1','阶段2','阶段3','阶段4']\r\ntotal_right=['阶段1获利','阶段2获利','阶段3获利','阶段4获利']\r\ntotal_wrong=['阶段1损失','阶段2损失','阶段3损失',\"阶段4损失\"]\r\nx=range(len(total))\r\n\r\n# 绘图\r\nimport matplotlib.pyplot as plt\r\ntotal_index=len(total)\r\nplt.style.use('ggplot')\r\n\r\n#解决中文显示问题\r\nplt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默认字体\r\nplt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题\r\n\r\n# 平均反应时\r\nfig=plt.figure()\r\nbar_width=' '\r\naver_s=numpy.array(reacttime_right)\r\naver_o=numpy.array(reacttime_wrong)\r\nax1=fig.add_subplot(1,1,1)\r\nax1.bar(x,aver_s,width=0.4, color='darkblue',label='获利后下次反应时')\r\nax1.errorbar(x,y=aver_s,yerr=std_right,ecolor='grey',capsize=4,color='black',fmt='o')\r\nax1.bar([i+0.4 for i in x],aver_o,width=0.4,color='red',label='损失后下次反应时')\r\nax1.errorbar([i+0.4 for i in x],y=aver_o,yerr=std_wrong,ecolor='grey',capsize=4,color='black',fmt='o')\r\n# ax1.bar(expression,corratio,align='center',color='red')\r\nplt.xticks([i+0.2 for i in x],total,fontsize=10)\r\nax1.xaxis.set_ticks_position(\"bottom\")\r\nax1.yaxis.set_ticks_position(\"left\")\r\nplt.xlabel('不同阶段')\r\nplt.ylabel('时间(秒)')\r\nplt.title('图1:平均反应时间(秒)')\r\nplt.legend()\r\nplt.savefig('reaction_time.png',dpi=400,bbox_inches='tight')\r\nplt.show()\r\n\r\n# 绘制pdf文档\r\nfrom fpdf import FPDF\r\npdf = FPDF('p','mm','A4')\r\npdf.add_page()\r\npdf.add_font('hei','',fname=r'C:\\Windows\\Fonts\\simhei.ttf',uni=True)\r\npdf.set_font(\"hei\", size=18)\r\npdf.cell(180, 20, txt=\"电脑认知测试九:奖赏反应情况\", ln=1, align=\"C\")\r\npdf.set_font('hei',size=12)\r\npdf.cell(180,13,txt='姓名:'+name,ln=1)\r\npdf.cell(180,13,txt='时间:'+time,ln=1)\r\npdf.cell(180,7,txt='—————————————————————————',ln=1,align=\"C\")\r\npdf.cell(180,7,txt=' 不同阶段 反应时(秒) 标准差',ln=1,align='C')\r\npdf.cell(180,7,txt='—————————————————————————',ln=1,align='C')\r\nfor i in range(0,4):\r\n text1=\"{} {:.5f} {:.5f}\".format(total_right[i],reacttime_right[i],std_right[i])\r\n text2=\"{} {:.5f} {:.5f}\".format(total_wrong[i],reacttime_wrong[i],std_wrong[i])\r\n pdf.cell(180,7,txt=text1,ln=2,align=\"C\")\r\n pdf.cell(180,7,txt=text2,ln=2,align=\"C\")\r\npdf.cell(180,7,txt='—————————————————————————',ln=1,align='C')\r\npdf.image('reaction_time.png',x=50,y=160,w=100,h=86)\r\npdf.output(\"9_Simple_Guessing_Task.pdf\")\r\n\r\nprint(\"文件处理完成。\")"
] |
[
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.savefig",
"numpy.std",
"numpy.mean",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.ylabel"
],
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"numpy.std",
"numpy.mean",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.xticks",
"numpy.array",
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
phww/Study-Model-Myself
|
[
"f7cb97899c6711b0105b9e4c7ad0eecdda2ad0b4"
] |
[
"R-CNN/utils/template.py"
] |
[
"#!/usr/bin/env python\n# _*_ coding: utf-8 _*_\n# @Time : 2021/5/14 下午4:59\n# @Author : PH\n# @Version:V 0.1\n# @File : template.py\n# @desc :\nimport torch\nimport os\nimport os.path as osp\n\n\nclass TemplateModel:\n def __init__(self):\n # tensorboard\n self.writer = None\n # 训练状态\n self.global_step = 0\n self.epoch = 0\n self.best_acc = 0.0\n # 模型架构\n self.model = None\n self.optimizer = None\n self.criterion = None\n self.metric = None # 可没有\n # 数据集\n self.train_loader = None\n self.test_loader = None\n # 运行设备\n self.device = None\n # check_point 目录\n self.ckpt_dir = None\n # 训练时print的间隔\n self.log_per_step = None\n\n def check_init(self):\n assert self.model\n assert self.optimizer\n assert self.criterion\n assert self.metric\n assert self.train_loader\n assert self.test_loader\n assert self.device\n assert self.ckpt_dir\n assert self.log_per_step\n torch.cuda.empty_cache()\n if not osp.exists(self.ckpt_dir):\n os.mkdir(self.ckpt_dir)\n\n def load_state(self, fname, optim=True):\n state = torch.load(fname)\n\n if isinstance(self.model, torch.nn.DataParallel): # 多卡训练\n self.model.module.load_state_dict(state['model'])\n else: # 非多卡训练\n self.model.load_state_dict(state['model'])\n # 恢复一些状态参数\n if optim and 'optimizer' in state:\n self.optimizer.load_state_dict(state['optimizer'])\n self.global_step = state['global_step']\n self.epoch = state['epoch']\n self.best_acc = state['best_acc']\n print('load model from {}'.format(fname))\n\n def save_state(self, fname, optim=True):\n state = {}\n\n if isinstance(self.model, torch.nn.DataParallel):\n state['model'] = self.model.module.state_dict()\n else:\n state['model'] = self.model.state_dict()\n # 除了保存模型的参数外,还要保存当前训练的状态:optim中的参数、epoch、step等\n if optim:\n state['optimizer'] = self.optimizer.state_dict()\n state['global_step'] = self.global_step\n state['epoch'] = self.epoch\n state['best_acc'] = self.best_acc\n torch.save(state, fname)\n print('save model at {}'.format(fname))\n\n def train_loop(self):\n self.model.train()\n self.epoch += 1\n running_loss = 0.0\n for step, batch in enumerate(self.train_loader):\n self.global_step += 1\n self.optimizer.zero_grad()\n loss = self.train_loss(batch)\n loss.backward()\n self.optimizer.step()\n running_loss += loss.item()\n if step % self.log_per_step == 0:\n # 记录每一批loss的平均loss\n avg_loss = running_loss / (self.log_per_step * len(batch))\n self.writer.add_scalar('loss', avg_loss, self.global_step)\n print(\n f\"loss:{avg_loss : .5f}\\tcur:[{(step + 1) * self.train_loader.batch_size}]\\[{len(self.train_loader.dataset)}]\")\n\n # 记录参数和梯度\n for tag, value in self.model.named_parameters():\n tag = tag.replace('.', '/')\n self.writer.add_histogram('weights/' + tag, value.data.cpu().numpy())\n if value.grad is not None: # 在FineTurn时有些参数被冻结了,没有梯度。也就不用记录了\n self.writer.add_histogram('grads/' + tag, value.grad.data.cpu().numpy())\n\n running_loss = 0.0\n\n def train_loss(self, batch):\n x, y = batch\n x = x.to(self.device)\n y = y.unsqueeze(dim=1).to(self.device, dtype=torch.float)\n\n pred = self.model(x)\n loss = self.criterion(pred, y)\n return loss\n\n def eval(self, save_per_eval=True):\n self.model.eval()\n # 如果要使用一些其他的性能指标,就要设置self.metric成员。然后返回一个有关指标的字典\n # 比如使用sklearn中的f1_score, recall...\n scores = self.eval_scores()\n for key in scores.keys():\n self.writer.add_scalar(f\"{key}\", scores[key].item(), self.epoch)\n if scores[\"acc\"] >= self.best_acc:\n self.best_acc = scores[\"acc\"]\n self.save_state(osp.join(self.ckpt_dir, f'best.pth'), False)\n if save_per_eval: # 每次评估都保存当前模型?\n self.save_state(osp.join(self.ckpt_dir, f'epoch{self.epoch}.pth'))\n print('epoch:{}\\tACC {:.5f}'.format(self.epoch, scores[\"acc\"]))\n return scores[\"acc\"]\n\n def eval_scores(self):\n xs, ys, preds = [], [], []\n # temp = {}\n for batch in self.test_loader:\n x, y = batch\n x = x.to(self.device)\n y = y.to(self.device)\n pred = self.model(x)\n\n # 下面的注释可以分批获取metric,但是要改metric()的实现\n # scores = self.metric(pred.cpu(), y.cpu())\n # for key in scores.keys():\n # temp[key] += scores[key]\n\n xs.append(x.cpu())\n ys.append(y.cpu())\n preds.append(pred.cpu())\n # 将所有pred和label全部获取后才送入metric()计算性能指标的方法要小心内存不够...\n # 分批计算metric的方法要改metric的实现,目前还不想改...\n xs = torch.cat(xs, dim=0)\n ys = torch.cat(ys, dim=0)\n preds = torch.cat(preds, dim=0)\n scores = self.metric(preds, ys)\n return scores\n\n def inference(self, x):\n x = x.to(self.device)\n return self.model(x)\n\n def num_parameters(self):\n return sum([p.data.nelement() for p in self.model.parameters()])\n"
] |
[
[
"torch.save",
"torch.cuda.empty_cache",
"torch.cat",
"torch.load"
]
] |
dreamer121121/U-2-Net
|
[
"99fbfbab1126677f8596ea04fa40c5baadea73db"
] |
[
"u2net_test.py"
] |
[
"import os\nfrom skimage import io, transform\nimport torch\nimport torchvision\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms#, utils\n# import torch.optim as optim\n\nimport numpy as np\nfrom PIL import Image\nimport glob\n\nfrom data_loader import RescaleT\nfrom data_loader import ToTensor\nfrom data_loader import ToTensorLab\nfrom data_loader import SalObjDataset\n\nfrom model import U2NET # full size version 173.6 MB\nfrom model import U2NETP # small version u2net 4.7 MB\n\n# normalize the predicted SOD probability map\ndef normPRED(d):\n ma = torch.max(d)\n mi = torch.min(d)\n\n dn = (d-mi)/(ma-mi)\n\n return dn\n\ndef save_output(image_name,pred,d_dir):\n\n predict = pred\n predict = predict.squeeze()\n predict_np = predict.cpu().data.numpy()\n\n im = Image.fromarray(predict_np*255).convert('RGB')\n img_name = image_name.split(os.sep)[-1]\n image = io.imread(image_name)\n imo = im.resize((image.shape[1],image.shape[0]),resample=Image.BILINEAR)\n #print('-----image.shape-----',image.shape) \n\n pb_np = np.array(imo)\n\n aaa = img_name.split(\".\")\n bbb = aaa[0:-1]\n imidx = bbb[0]\n for i in range(1,len(bbb)):\n imidx = imidx + \".\" + bbb[i]\n\n imo.save(d_dir+imidx+'.png')\n\ndef main():\n\n # --------- 1. get image path and name ---------\n model_name='u2netp'#u2netp\n\n\n\n image_dir = os.path.join(os.getcwd(), 'test_data', 'im_aug')\n prediction_dir = os.path.join(os.getcwd(), 'test_data', model_name + '_results' + os.sep)\n model_dir = os.path.join(os.getcwd(), 'saved_models', model_name, model_name + '.pth')\n\n img_name_list = glob.glob(image_dir + os.sep + '*')\n print(img_name_list)\n\n # --------- 2. dataloader ---------\n #1. dataloader\n test_salobj_dataset = SalObjDataset(img_name_list = img_name_list,\n lbl_name_list = [],\n transform=transforms.Compose([RescaleT(320),\n ToTensorLab(flag=0)])\n )\n test_salobj_dataloader = DataLoader(test_salobj_dataset,\n batch_size=1,\n shuffle=False,\n num_workers=1)\n\n # --------- 3. model define ---------\n if(model_name=='u2net'):\n print(\"...load U2NET---173.6 MB\")\n net = U2NET(3,1)\n elif(model_name=='u2netp'):\n print(\"...load U2NEP---4.7 MB\")\n net = U2NETP(3,1)\n\n if torch.cuda.is_available():\n net.load_state_dict(torch.load(model_dir))\n net.cuda()\n else:\n net.load_state_dict(torch.load(model_dir, map_location='cpu'))\n net.eval()\n import datetime\n #start = datetime.datetime.now()\n total = datetime.datetime(1999,1,1)\n cnt = 1\n # --------- 4. inference for each image ---------\n for i_test, data_test in enumerate(test_salobj_dataloader):\n\n print(\"inferencing:\",img_name_list[i_test].split(os.sep)[-1])\n\n inputs_test = data_test['image']\n inputs_test = inputs_test.type(torch.FloatTensor)\n\n if torch.cuda.is_available():\n inputs_test = Variable(inputs_test.cuda())\n else:\n inputs_test = Variable(inputs_test)\n start = datetime.datetime.now()\n d1,d2,d3,d4,d5,d6,d7= net(inputs_test)\n total += datetime.datetime.now()-start\n print((total-datetime.datetime(1999,1,1))/cnt)\n # normalization\n pred = d1[:,0,:,:]\n pred = normPRED(pred)\n\n # save results to test_results folder\n if not os.path.exists(prediction_dir):\n os.makedirs(prediction_dir, exist_ok=True)\n save_output(img_name_list[i_test],pred,prediction_dir)\n #print((datetime.datetime.now()-start)/(i_test+1))\n cnt += 1\n del d1,d2,d3,d4,d5,d6,d7\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"torch.max",
"torch.load",
"torch.min",
"torch.utils.data.DataLoader",
"torch.cuda.is_available",
"numpy.array",
"torch.autograd.Variable"
]
] |
Srujan35007/My-GANs
|
[
"7953c859169134a0a84ac3cd674f629af9942465"
] |
[
"Simple GAN/train.py"
] |
[
"import torch \nimport torch.nn as nn \nimport torch.nn.functional as F \nimport torch.optim as optim \nimport numpy as np \nimport random\nfrom networks import Generator, Discriminator\nimport matplotlib.pyplot as plt \nprint('Imports complete')\n\n\ndef normalize(array, original_range, target_range):\n min_array,max_array = original_range\n target_min,target_max = target_range\n normalized = target_min+((target_max-target_min)*(array-min_array))/(max_array-min_array)\n return normalized\n\n\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\ncpu = torch.device('cpu')\nnetG = Generator(max_resolution=32,latent_dims=128,max_channels=256,min_channels=16).to(device)\nnetD = Discriminator(max_resolution=32,max_channels=256,min_channels=16).to(device)\noptimG = optim.Adam(netG.parameters(),lr=0.00015,betas=(0.5,0.999))\noptimD = optim.Adam(netD.parameters(),lr=0.00015,betas=(0.5,0.999))\nloss_fn = nn.BCELoss()\n\n# Hyper-params\nBATCH_SIZE = 10\nn_epochs = 100\n\n# Fetch Training data\ntrain_data = []\ntrain_loader = torch.utils.data.DataLoader(train_data, batch_size=BATCH_SIZE, shuffle=True)\n\nepoch_count = 0\nwhile epoch_count < n_epochs:\n for data in tqdm(train_loader): \n real_label = normalize(torch.rand(BATCH_SIZE),(0,1),(0.9,1)).float()\n fake_label = normalize(torch.rand(BATCH_SIZE),(0,1),(0,0.1)).float()\n temp = torch.empty(BATCH_SIZE,128).normal_(0,0.5)\n noise = normalize(temp,(torch.min(temp),torch.max(temp)),(-1,1)).float()\n\n fake_image_batch = netG(noise)\n real_image_batch = normalize(data, (0,1),(-1,1))\n # Optimize Discriminator\n netD.zero_grad()\n D_fake_batch = D(fake_image_batch.detach())\n D_real_batch = D(real_image_batch)\n D_real_loss = loss_fn(D_real_batch, real_label)\n D_fake_loss = loss_fn(D_fake_batch, fake_label)\n D_loss = (D_real_loss + D_fake_loss)\n D_loss.backward()\n optimD.step()\n # Optimize Generator\n netG.zero_grad()\n D_out = netD(fake_image_batch)\n G_loss = loss_fn(D_out, real_label)\n G_loss.backward()\n optimG.step()\n \n epoch_count += 1\n"
] |
[
[
"torch.empty",
"torch.max",
"torch.min",
"torch.utils.data.DataLoader",
"torch.nn.BCELoss",
"torch.rand",
"torch.cuda.is_available",
"torch.device"
]
] |
temuller/cosmo_phot
|
[
"011333f84486614cb9339d3874dc072c45ebed23"
] |
[
"src/hostphot/local_photometry.py"
] |
[
"# Check the following urls for more info about Pan-STARRS:\n#\n# https://outerspace.stsci.edu/display/PANSTARRS/PS1+Image+Cutout+Service#PS1ImageCutoutService-ImportantFITSimageformat,WCS,andflux-scalingnotes\n# https://outerspace.stsci.edu/display/PANSTARRS/PS1+Stack+images#PS1Stackimages-Photometriccalibration\n#\n# For DES:\n#\n# https://des.ncsa.illinois.edu/releases/dr1/dr1-docs/processing\n#\n# For SDSS:\n#\n# https://www.sdss.org/dr12/algorithms/fluxcal/#SDSStoAB\n# https://data.sdss.org/datamodel/files/BOSS_PHOTOOBJ/frames/RERUN/RUN/CAMCOL/frame.html\n#\n# Some parts of this notebook are based on https://github.com/djones1040/PS1_surface_brightness/blob/master/Surface%20Brightness%20Tutorial.ipynb and codes from Lluís Galbany\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport sep\nfrom photutils import CircularAperture\nfrom photutils import aperture_photometry\n\nfrom astropy.io import fits\nfrom astropy import units as u, wcs\nfrom astropy.cosmology import FlatLambdaCDM\n\nfrom hostphot._constants import __workdir__\nfrom hostphot.utils import (get_survey_filters, check_survey_validity,\n check_filters_validity, calc_sky_unc,\n survey_pixel_scale, survey_zp, get_image_gain,\n get_image_readnoise, check_work_dir)\nfrom hostphot.image_cleaning import remove_nan\nfrom hostphot.dust import calc_extinction\n\nH0 = 70\nOm0 = 0.3\n__cosmo__ = FlatLambdaCDM(H0, Om0)\nsep.set_sub_object_limit(1e4)\n\n#----------------------------------------\ndef _choose_workdir(workdir):\n \"\"\"Updates the work directory.\n\n Parameters\n ----------\n workdir: str\n Path to the work directory.\n \"\"\"\n global __workdir__\n __workdir__ = workdir\n\ndef choose_cosmology(cosmo):\n \"\"\"Updates the cosmology used to calculate the aperture size.\n\n Parameters\n ----------\n cosmo: `astropy.cosmology` object\n Cosmological model. E.g. :func:`FlatLambdaCDM(70, 0.3)`.\n \"\"\"\n global __cosmo__\n __cosmo__ = cosmo\n\n#-------------------------------\ndef calc_aperture_size(z, ap_radius):\n \"\"\"Calculates the size of the aperture in arsec,\n for aperture photometry, given a physical size.\n\n Parameters\n ----------\n z: float\n Redshift.\n ap_radius: float\n Physical aperture size in kpc.\n\n Returns\n -------\n radius_arcsec: float\n Aperture size in arcsec.\n \"\"\"\n ap_radius = ap_radius*u.kpc\n\n # transverse separations\n transv_sep_per_arcmin = __cosmo__.kpc_proper_per_arcmin(z)\n transv_sep_per_arcsec = transv_sep_per_arcmin.to(u.kpc/u.arcsec)\n\n radius_arcsec = ap_radius/transv_sep_per_arcsec\n\n return radius_arcsec.value\n\ndef extract_aperture_flux(data, error, px, py, radius):\n \"\"\"Extracts aperture photometry of a single image.\n\n Parameters\n ----------\n data: array\n Image data in a 2D numpy array.\n error: array\n Errors of ``data``.\n px: float\n x-axis pixel coordinate of the aperture center.\n py: float\n y-axis pixel coordinate of the aperture center.\n radius: float\n Aperture radius in pixels.\n\n Returns\n -------\n raw_flux: float\n Aperture photometry (\"raw\" flux).\n raw_flux_err: float\n Uncertainty on the aperture photometry.\n \"\"\"\n aperture = CircularAperture((px, py), r=radius)\n ap_results = aperture_photometry(data, aperture,\n error=error)\n raw_flux = ap_results['aperture_sum'][0]\n raw_flux_err = ap_results['aperture_sum_err'][0]\n\n return raw_flux, raw_flux_err\n\ndef plot_aperture(data, px, py, radius_pix, outfile=None):\n \"\"\"Plots the aperture for the given parameters.\n\n Parameters\n ----------\n data: 2D array\n Data of an image.\n px: float\n X-axis center of the aperture in pixels.\n py: float\n Y-axis center of the aperture in pixels.\n radius_pix: float\n Aperture radius in pixels.\n outfile: str, default ``None``\n If given, path where to save the output figure.\n \"\"\"\n fig, ax = plt.subplots(figsize=(8, 8))\n m, s = np.nanmean(data), np.nanstd(data)\n im = ax.imshow(data, interpolation='nearest',\n cmap='gray',\n vmin=m-s, vmax=m+s,\n origin='lower')\n\n circle = plt.Circle((px, py), radius_pix, color='r', fill=False)\n ax.add_patch(circle)\n\n if outfile:\n plt.tight_layout()\n plt.savefig(outfile)\n plt.close(fig)\n else:\n plt.show()\n\ndef photometry(name, ra, dec, z, filt, survey, ap_radii=1, bkg_sub=False,\n use_mask=True, save_plots=True):\n \"\"\"Calculates the local aperture photometry in a given radius.\n\n Parameters\n ----------\n name: str\n Name of the object to find the path of the fits file.\n ra: float\n Right Ascensions in degrees to center the aperture.\n dec: float\n Declinations in degrees to center the aperture.\n z: float\n Redshift of the object to estimate the physical calculate\n of the aperture.\n filt: str\n Filter to use to load the fits file.\n survey: str\n Survey to use for the zero-points and pixel scale.\n ap_radii: float or list-like, default ``1``\n Physical size of the aperture in kpc.\n bkg_sub: bool, default ``False``\n If ``True``, the image gets background subtracted.\n use_mask: bool, default ``True``\n If ``True``, the masked fits files are used. These must have\n been created beforehand.\n save_plots: bool, default ``True``\n If ``True``, the a figure with the aperture is saved.\n\n Returns\n -------\n mags: list\n List of aperture magnitudes for the given aperture radii.\n mags_err: list\n List of aperture magnitude errors for the given aperture radii.\n \"\"\"\n check_survey_validity(survey)\n check_work_dir(__workdir__)\n obj_dir = os.path.join(__workdir__, name)\n if use_mask:\n suffix = 'masked_'\n else:\n suffix = ''\n fits_file = os.path.join(obj_dir, f'{suffix}{survey}_{filt}.fits')\n\n img = fits.open(fits_file)\n img = remove_nan(img)\n\n header = img[0].header\n data = img[0].data\n exptime = float(header['EXPTIME'])\n gain = get_image_gain(header, survey)\n readnoise = get_image_readnoise(header, survey)\n img_wcs = wcs.WCS(header, naxis=2)\n\n data = data.astype(np.float64)\n bkg = sep.Background(data)\n bkg_rms = bkg.globalrms\n if bkg_sub:\n data_sub = np.copy(data - bkg)\n else:\n data_sub = np.copy(data)\n\n # turn float into a list\n if isinstance(ap_radii, float):\n ap_radii = [ap_radii]\n\n mags, mags_err = [], []\n for ap_radius in ap_radii:\n # aperture photometry\n radius_arcsec = calc_aperture_size(z, ap_radius)\n pixel_scale = survey_pixel_scale(survey)\n radius_pix = radius_arcsec/pixel_scale\n\n px, py = img_wcs.wcs_world2pix(ra, dec, 1)\n error = calc_sky_unc(data_sub, exptime)\n\n flux, flux_err = extract_aperture_flux(data_sub, error,\n px, py, radius_pix)\n\n zp = survey_zp(survey)\n if survey=='PS1':\n zp += 2.5*np.log10(exptime)\n\n mag = -2.5*np.log10(flux) + zp\n mag_err = 2.5/np.log(10)*flux_err/flux\n\n # correct extinction\n A_ext = calc_extinction(filt, survey, ra, dec)\n mag -= A_ext\n\n # error budget\n # 1.0857 = 2.5/ln(10)\n if survey!='SDSS':\n ap_area = 2*np.pi*(radius_pix**2)\n extra_err = 1.0857*np.sqrt(ap_area*(readnoise**2) + flux/gain)/flux\n mag_err = np.sqrt(mag_err**2 + extra_err**2)\n\n mags.append(mag)\n mags_err.append(mag_err)\n\n if save_plots:\n outfile = os.path.join(obj_dir,\n f'local_{survey}_{filt}_{ap_radius}kpc.jpg')\n plot_aperture(data_sub, px, py, radius_pix, outfile)\n\n return mags, mags_err\n\ndef multi_band_phot(name, ra, dec, z, filters=None, survey='PS1', ap_radii=1,\n bkg_sub=False, use_mask=True, save_plots=True):\n \"\"\"Calculates the local aperture photometry for multiple filters.\n\n Parameters\n ----------\n name: str\n Name of the object to find the path of the fits file.\n ra: float\n Right Ascensions in degrees to center the aperture.\n dec: float\n Declinations in degrees to center the aperture.\n z: float\n Redshift of the object to estimate the physical calculate\n of the aperture.\n filters: str, default, ``None``\n Filters to use to load the fits files. If ``None`` use all\n the filters of the given survey.\n survey: str, default ``PS1``\n Survey to use for the zero-points and pixel scale.\n ap_radii: float or list-like, default ``1``\n Physical size of the aperture in kpc.\n bkg_sub: bool, default ``False``\n If ``True``, the image gets background subtracted.\n use_mask: bool, default ``True``\n If ``True``, the masked fits files are used. These must have\n been created beforehand.\n save_plots: bool, default ``True``\n If ``True``, the a figure with the aperture is saved.\n\n Returns\n -------\n results_dict: dict\n Dictionary with the object's photometry and other info.\n \"\"\"\n check_survey_validity(survey)\n if filters is None:\n filters = get_survey_filters(survey)\n else:\n check_filters_validity(filters, survey)\n\n # turn float into a list\n if isinstance(ap_radii, float):\n ap_radii = [ap_radii]\n\n results_dict = {'name':name, 'ra':ra, 'dec':dec,\n 'zspec':z, 'survey':survey}\n\n for filt in filters:\n mags, mags_err = photometry(name, ra, dec, z, filt, survey,\n ap_radii, bkg_sub, use_mask,\n save_plots)\n for i, ap in enumerate(ap_radii):\n results_dict[f'{filt}{ra}'] = mags[i]\n results_dict[f'{filt}{ra}_err'] = mags_err[i]\n\n return results_dict\n"
] |
[
[
"numpy.log",
"matplotlib.pyplot.tight_layout",
"numpy.sqrt",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.Circle",
"numpy.copy",
"numpy.log10",
"numpy.nanmean",
"matplotlib.pyplot.close",
"numpy.nanstd",
"matplotlib.pyplot.show"
]
] |
ahmadjubair33/qiskit-finance
|
[
"63822defdc5d12798009c7d98e82f515ca81249b"
] |
[
"qiskit_finance/circuit/library/probability_distributions/normal.py"
] |
[
"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017, 2022.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"A circuit that encodes a discretized normal probability distribution in qubit amplitudes.\"\"\"\n\nfrom typing import Tuple, Union, List, Optional, Any\nimport numpy as np\nfrom qiskit.circuit import QuantumCircuit\n\n\nclass NormalDistribution(QuantumCircuit):\n r\"\"\"A circuit to encode a discretized normal distribution in qubit amplitudes.\n\n The probability density function of the normal distribution is defined as\n\n .. math::\n\n \\mathbb{P}(X = x) = \\frac{1}{\\sqrt{2\\pi\\sigma^2}} e^{-\\frac{(x - \\mu)^2}{\\sigma^2}}\n\n .. note::\n\n The parameter ``sigma`` in this class equals the **variance**, :math:`\\sigma^2` and not the\n standard deviation. This is for consistency with multivariate distributions, where the\n uppercase sigma, :math:`\\Sigma`, is associated with the covariance.\n\n This circuit considers the discretized version of the normal distribution on\n ``2 ** num_qubits`` equidistant points, :math:`x_i`, truncated to ``bounds``.\n For a one-dimensional random variable, meaning `num_qubits` is a single integer, it applies\n the operation\n\n .. math::\n\n \\mathcal{P}_X |0\\rangle^n = \\sum_{i=0}^{2^n - 1} \\sqrt{\\mathbb{P}(x_i)} |i\\rangle\n\n where :math:`n` is `num_qubits`.\n\n .. note::\n\n The circuit loads the **square root** of the probabilities into the qubit amplitudes such\n that the sampling probability, which is the square of the amplitude, equals the\n probability of the distribution.\n\n In the multi-dimensional case, the distribution is defined as\n\n .. math::\n\n \\mathbb{P}(X = x) = \\frac{\\Sigma^{-1}}{\\sqrt{2\\pi}} e^{-\\frac{(x - \\mu)^2}{\\Sigma}}\n\n where :math:`\\Sigma` is the covariance. To specify a multivariate normal distribution,\n ``num_qubits`` is a list of integers, each specifying how many\n qubits are used to discretize the respective dimension. The arguments ``mu`` and ``sigma``\n in this case are a vector and square matrix.\n If for instance, ``num_qubits = [2, 3]`` then ``mu`` is a 2d vector and ``sigma`` is the\n :math:`2 \\times 2` covariance matrix. The first dimension is discretized using 2 qubits, hence\n on 4 points, and the second dimension on 3 qubits, hence 8 points. Therefore the random variable\n is discretized on :math:`4 \\times 8 = 32` points.\n\n Since, in general, it is not yet known how to efficiently prepare the qubit amplitudes to\n represent a normal distribution, this class computes the expected amplitudes and then uses\n the ``QuantumCircuit.initialize`` method to construct the corresponding circuit.\n\n This circuit is for example used in amplitude estimation applications, such as finance [1, 2],\n where customer demand or the return of a portfolio could be modeled using a normal\n distribution.\n\n Examples:\n\n >>> from qiskit_finance.circuit.library.probability_distributions import NormalDistribution\n >>> circuit = NormalDistribution(3, mu=1, sigma=1, bounds=(0, 2))\n >>> circuit.decompose().draw()\n »\n q_0: ───────────────────────────────────────────────────»\n ┌────────────────────────┐»\n q_1: ─────────────────────────┤0 ├»\n ┌───────────────────────┐│ multiplex2_reverse_dg │»\n q_2: ┤ multiplex1_reverse_dg ├┤1 ├»\n └───────────────────────┘└────────────────────────┘»\n « ┌────────────────────────┐\n «q_0: ┤0 ├\n « │ │\n «q_1: ┤1 multiplex3_reverse_dg ├\n « │ │\n «q_2: ┤2 ├\n « └────────────────────────┘\n\n >>> mu = [1, 0.9]\n >>> sigma = [[1, -0.2], [-0.2, 1]]\n >>> circuit = NormalDistribution([2, 3], mu, sigma)\n >>> circuit.num_qubits\n 5\n\n >>> import os\n >>> from qiskit import QuantumCircuit\n >>> mu = [1, 0.9]\n >>> sigma = [[1, -0.2], [-0.2, 1]]\n >>> bounds = [(0, 1), (-1, 1)]\n >>> p_x = NormalDistribution([2, 3], mu, sigma, bounds)\n >>> circuit = QuantumCircuit(6)\n >>> _ = circuit.append(p_x, list(range(5)))\n >>> for i in range(5):\n ... _ = circuit.cry(2 ** i, i, 5)\n >>> # strip trailing white spaces to match the expected output\n >>> print(os.linesep.join([s.rstrip() for s in circuit.draw().lines()]))\n ┌───────┐\n q_0: ┤0 ├────■─────────────────────────────────────────\n │ │ │\n q_1: ┤1 ├────┼────────■────────────────────────────────\n │ │ │ │\n q_2: ┤2 P(X) ├────┼────────┼────────■───────────────────────\n │ │ │ │ │\n q_3: ┤3 ├────┼────────┼────────┼────────■──────────────\n │ │ │ │ │ │\n q_4: ┤4 ├────┼────────┼────────┼────────┼────────■─────\n └───────┘┌───┴───┐┌───┴───┐┌───┴───┐┌───┴───┐┌───┴────┐\n q_5: ─────────┤ Ry(1) ├┤ Ry(2) ├┤ Ry(4) ├┤ Ry(8) ├┤ Ry(16) ├\n └───────┘└───────┘└───────┘└───────┘└────────┘\n\n References:\n [1]: Gacon, J., Zoufal, C., & Woerner, S. (2020).\n Quantum-Enhanced Simulation-Based Optimization.\n `arXiv:2005.10780 <http://arxiv.org/abs/2005.10780>`_\n\n [2]: Woerner, S., & Egger, D. J. (2018).\n Quantum Risk Analysis.\n `arXiv:1806.06893 <http://arxiv.org/abs/1806.06893>`_\n\n \"\"\"\n\n def __init__(\n self,\n num_qubits: Union[int, List[int]],\n mu: Optional[Union[float, List[float]]] = None,\n sigma: Optional[Union[float, List[float]]] = None,\n bounds: Optional[Union[Tuple[float, float], List[Tuple[float, float]]]] = None,\n upto_diag: bool = False,\n name: str = \"P(X)\",\n ) -> None:\n r\"\"\"\n Args:\n num_qubits: The number of qubits used to discretize the random variable. For a 1d\n random variable, ``num_qubits`` is an integer, for multiple dimensions a list\n of integers indicating the number of qubits to use in each dimension.\n mu: The parameter :math:`\\mu`, which is the expected value of the distribution.\n Can be either a float for a 1d random variable or a list of floats for a higher\n dimensional random variable. Defaults to 0.\n sigma: The parameter :math:`\\sigma^2` or :math:`\\Sigma`, which is the variance or\n covariance matrix. Default to the identity matrix of appropriate size.\n bounds: The truncation bounds of the distribution as tuples. For multiple dimensions,\n ``bounds`` is a list of tuples ``[(low0, high0), (low1, high1), ...]``.\n If ``None``, the bounds are set to ``(-1, 1)`` for each dimension.\n upto_diag: If True, load the square root of the probabilities up to multiplication\n with a diagonal for a more efficient circuit.\n name: The name of the circuit.\n \"\"\"\n _check_dimensions_match(num_qubits, mu, sigma, bounds)\n _check_bounds_valid(bounds)\n\n # set default arguments\n dim = 1 if isinstance(num_qubits, int) else len(num_qubits)\n if mu is None:\n mu = 0 if dim == 1 else [0] * dim\n\n if sigma is None:\n sigma = 1 if dim == 1 else np.eye(dim) # type: ignore[assignment]\n\n if bounds is None:\n bounds = (-1, 1) if dim == 1 else [(-1, 1)] * dim\n\n if isinstance(num_qubits, int): # univariate case\n inner = QuantumCircuit(num_qubits, name=name)\n\n x = np.linspace(bounds[0], bounds[1], num=2**num_qubits) # type: Any\n else: # multivariate case\n inner = QuantumCircuit(sum(num_qubits), name=name)\n\n # compute the evaluation points using numpy.meshgrid\n # indexing 'ij' yields the \"column-based\" indexing\n meshgrid = np.meshgrid(\n *[\n np.linspace(bound[0], bound[1], num=2 ** num_qubits[i]) # type: ignore\n for i, bound in enumerate(bounds)\n ],\n indexing=\"ij\",\n )\n # flatten into a list of points\n x = list(zip(*[grid.flatten() for grid in meshgrid]))\n\n from scipy.stats import multivariate_normal\n\n # compute the normalized, truncated probabilities\n probabilities = multivariate_normal.pdf(x, mu, sigma)\n normalized_probabilities = probabilities / np.sum(probabilities)\n\n # store the values, probabilities and bounds to make them user accessible\n self._values = x\n self._probabilities = normalized_probabilities\n self._bounds = bounds\n\n super().__init__(*inner.qregs, name=name)\n\n # use default the isometry (or initialize w/o resets) algorithm to construct the circuit\n # pylint: disable=no-member\n if upto_diag:\n inner.isometry(np.sqrt(normalized_probabilities), inner.qubits, None)\n self.append(inner.to_instruction(), inner.qubits) # Isometry is not a Gate\n else:\n from qiskit.extensions import Initialize # pylint: disable=cyclic-import\n\n initialize = Initialize(np.sqrt(normalized_probabilities))\n circuit = initialize.gates_to_uncompute().inverse()\n inner.compose(circuit, inplace=True)\n self.append(inner.to_gate(), inner.qubits)\n\n @property\n def values(self) -> np.ndarray:\n \"\"\"Return the discretized points of the random variable.\"\"\"\n return self._values\n\n @property\n def probabilities(self) -> np.ndarray:\n \"\"\"Return the sampling probabilities for the values.\"\"\"\n return self._probabilities\n\n @property\n def bounds(self) -> Union[Tuple[float, float], List[Tuple[float, float]]]:\n \"\"\"Return the bounds of the probability distribution.\"\"\"\n return self._bounds\n\n\ndef _check_dimensions_match(num_qubits, mu, sigma, bounds):\n num_qubits = [num_qubits] if not isinstance(num_qubits, (list, np.ndarray)) else num_qubits\n dim = len(num_qubits)\n\n if mu is not None:\n mu = [mu] if not isinstance(mu, (list, np.ndarray)) else mu\n if len(mu) != dim:\n raise ValueError(\n f\"Dimension of mu ({len(mu)}) does not match the dimension of the \"\n f\"random variable specified by the number of qubits ({dim})\"\n )\n\n if sigma is not None:\n sigma = [[sigma]] if not isinstance(sigma, (list, np.ndarray)) else sigma\n if len(sigma) != dim or len(sigma[0]) != dim:\n raise ValueError(\n f\"Dimension of sigma ({len(sigma)} x {len(sigma[0])}) does not match the dimension of \"\n f\"the random variable specified by the number of qubits ({dim})\"\n )\n\n if bounds is not None:\n # bit differently to cover the case the users might pass `bounds` as a single list,\n # e.g. [0, 1], instead of a tuple\n bounds = [bounds] if not isinstance(bounds[0], tuple) else bounds\n if len(bounds) != dim:\n raise ValueError(\n f\"Dimension of bounds ({len(bounds)}) does not match the dimension of the \"\n f\"random variable specified by the number of qubits ({dim})\"\n )\n\n\ndef _check_bounds_valid(bounds):\n if bounds is None:\n return\n\n bounds = [bounds] if not isinstance(bounds[0], tuple) else bounds\n\n for i, bound in enumerate(bounds):\n if not bound[1] - bound[0] > 0:\n raise ValueError(\n f\"Dimension {i} of the bounds are invalid, must be a non-empty \"\n \"interval where the lower bounds is smaller than the upper bound.\"\n )\n"
] |
[
[
"numpy.sqrt",
"numpy.linspace",
"numpy.eye",
"numpy.sum",
"scipy.stats.multivariate_normal.pdf"
]
] |
cclauss/episodic-curiosity
|
[
"3c406964473d98fb977b1617a170a447b3c548fd"
] |
[
"episodic_curiosity/environments/dmlab_utils.py"
] |
[
"# coding=utf-8\n# Copyright 2019 Google LLC.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Helper functions to facilitate running DMLab env.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport copy\nimport os\nimport tempfile\nfrom absl import flags\nfrom episodic_curiosity import oracle\nfrom third_party.baselines import logger\nfrom third_party.baselines.bench import Monitor\nfrom third_party.baselines.common.vec_env.subproc_vec_env import SubprocVecEnv\nimport gym\nimport numpy as np\nimport gin.tf\nimport deepmind_lab\nimport cv2\n\nFLAGS = flags.FLAGS\n\nDEFAULT_RENDERER = 'hardware'\n\nflags.DEFINE_enum(\n 'renderer', DEFAULT_RENDERER, ['software', 'hardware'],\n 'DMLab renderer. Make sure you have GPU if you use '\n '\"hardware\".')\n\n\ndef create_env_settings(level_name, homepath='', width=96, height=72, seed=0,\n main_observation='RGB_INTERLEAVED'):\n \"\"\"Creates environment settings.\"\"\"\n env_settings = {\n 'seed':\n seed,\n # See available levels:\n # https://github.com/deepmind/lab/tree/master/game_scripts/levels\n 'levelName':\n level_name,\n 'width':\n width,\n 'height':\n height,\n # Documentation about the available observations:\n # https://github.com/deepmind/lab/blob/master/docs/users/python_api.md\n 'observationFormat': [\n main_observation,\n 'DEBUG.POS.TRANS',\n 'MAP_FRAME_NUMBER',\n 'DEBUG.MAZE.LAYOUT',\n 'DEBUG.POS.ROT',\n 'DEBUG.PLAYERS.VELOCITY',\n ],\n 'homepath':\n homepath,\n 'renderer':\n FLAGS.renderer,\n }\n return env_settings\n\n\n# A set of allowed actions.\nDEFAULT_ACTION_SET = (\n (0, 0, 0, 1, 0, 0, 0), # Forward\n (0, 0, 0, -1, 0, 0, 0), # Backward\n (0, 0, -1, 0, 0, 0, 0), # Strafe Left\n (0, 0, 1, 0, 0, 0, 0), # Strafe Right\n (-20, 0, 0, 0, 0, 0, 0), # Look Left\n (20, 0, 0, 0, 0, 0, 0), # Look Right\n (-20, 0, 0, 1, 0, 0, 0), # Look Left + Forward\n (20, 0, 0, 1, 0, 0, 0), # Look Right + Forward\n (0, 0, 0, 0, 1, 0, 0), # Fire.\n)\n\nDEFAULT_ACTION_SET_WITH_IDLE = (\n (0, 0, 0, 1, 0, 0, 0), # Forward\n (0, 0, 0, -1, 0, 0, 0), # Backward\n (0, 0, -1, 0, 0, 0, 0), # Strafe Left\n (0, 0, 1, 0, 0, 0, 0), # Strafe Right\n (-20, 0, 0, 0, 0, 0, 0), # Look Left\n (20, 0, 0, 0, 0, 0, 0), # Look Right\n (-20, 0, 0, 1, 0, 0, 0), # Look Left + Forward\n (20, 0, 0, 1, 0, 0, 0), # Look Right + Forward\n (0, 0, 0, 0, 1, 0, 0), # Fire.\n (0, 0, 0, 0, 0, 0, 0), # Idle.\n)\n\n# Default set without \"Fire\".\nDEFAULT_ACTION_SET_WITHOUT_FIRE = (\n (0, 0, 0, 1, 0, 0, 0), # Forward\n (0, 0, 0, -1, 0, 0, 0), # Backward\n (0, 0, -1, 0, 0, 0, 0), # Strafe Left\n (0, 0, 1, 0, 0, 0, 0), # Strafe Right\n (-20, 0, 0, 0, 0, 0, 0), # Look Left\n (20, 0, 0, 0, 0, 0, 0), # Look Right\n (-20, 0, 0, 1, 0, 0, 0), # Look Left + Forward\n (20, 0, 0, 1, 0, 0, 0), # Look Right + Forward\n)\n\n# A small action set.\nACTION_SET_SMALL = (\n (0, 0, 0, 1, 0, 0, 0), # Forward\n (-20, 0, 0, 0, 0, 0, 0), # Look Left\n (20, 0, 0, 0, 0, 0, 0), # Look Right\n)\n\n\n# Another set of actions with idle.\nACTION_SET_WITH_IDLE = (\n (0, 0, 0, 1, 0, 0, 0), # Forward\n (0, 0, 0, -1, 0, 0, 0), # Backward\n (0, 0, -1, 0, 0, 0, 0), # Strafe Left\n (0, 0, 1, 0, 0, 0, 0), # Strafe Right\n (-20, 0, 0, 0, 0, 0, 0), # Look Left\n (20, 0, 0, 0, 0, 0, 0), # Look Right\n (0, 0, 0, 0, 0, 0, 0), # Idle.\n)\n\n\nACTION_SET_SMALL_WITH_BACK = (\n (0, 0, 0, 1, 0, 0, 0), # Forward\n (0, 0, 0, -1, 0, 0, 0), # Backward\n (-20, 0, 0, 0, 0, 0, 0), # Look Left\n (20, 0, 0, 0, 0, 0, 0), # Look Right\n)\n\n\[email protected]\nclass DMLabWrapper(gym.Env):\n \"\"\"A wrapper around DMLab environment to make it compatible with OpenAI\n Baseline's training.\n \"\"\"\n\n def __init__(self, platform, args,\n action_set=DEFAULT_ACTION_SET,\n main_observation='RGB_INTERLEAVED',\n action_repeat=4,\n noise_type='',\n tv_num_images=30):\n \"\"\"Creates a DMLabWrapper.\n\n Args:\n platform: Typically 'dmlab'.\n args: The environment settings.\n action_set: The set of discrete actions.\n main_observation: The observation returned at every time step.\n action_repeat: Maximum number of times to repeat an action.\n This can be less at the end of an episode.\n noise_type: if not empty defines what type of noise to add to the\n observation. Possible values: image_action, image, noise_action, noise.\n tv_num_images: number of distinct images to be used for TV purposes.\n \"\"\"\n homepath = args.pop('homepath')\n level_name = args.pop('levelName')\n observation_format = args.pop('observationFormat')\n renderer = args.pop('renderer')\n seed = args.pop('seed')\n string_args = {key: str(value) for key, value in args.items()}\n if homepath:\n deepmind_lab.set_runfiles_path(os.path.join(\n homepath,\n ))\n self._env = deepmind_lab.Lab(\n level_name, observation_format, string_args, renderer)\n\n self._random_state = np.random.RandomState(seed=seed)\n self._env.reset(seed=self._random_state.randint(0, 2 ** 31 - 1))\n\n self._action_set = action_set\n self._action_repeat = action_repeat\n self.width = args['width']\n self.height = args['height']\n\n self._main_observation = main_observation\n self._transform_observation = lambda x: x\n if main_observation == 'DEBUG.CAMERA.PLAYER_VIEW_NO_RETICLE':\n # This observation format is (RGB, height, width).\n # Convert it to (height, width, RGB).\n self._transform_observation = lambda x: np.moveaxis(x, 0, -1)\n\n # Build a list of all the possible actions.\n self._action_list = []\n for action in action_set:\n self._action_list.append(np.array(action, dtype=np.intc))\n\n self._noise_type = noise_type\n self._images_for_noise = []\n if self._noise_type:\n if 'action' in self._noise_type:\n assert action_set in [DEFAULT_ACTION_SET_WITH_IDLE, DEFAULT_ACTION_SET]\n for image in range(1, tv_num_images + 1):\n image_path = '/cns/vz-d/home/raveman/images/%d.jpeg' % image\n tmp_path = os.path.join(tempfile.gettempdir(),\n os.path.basename(image_path))\n image = cv2.imread(tmp_path, flags=cv2.IMREAD_COLOR)\n image = cv2.resize(image, (int(self.width/2), int(self.height/2)),\n interpolation=cv2.INTER_AREA)\n # imread returns BGR not RGB\n image = image[Ellipsis, ::-1]\n self._images_for_noise.append(image)\n\n @property\n def action_space(self):\n return gym.spaces.Discrete(len(self._action_set))\n\n @property\n def observation_space(self):\n return gym.spaces.Box(low=0, high=255, shape=(self.height, self.width, 3),\n dtype=np.uint8)\n\n def add_noise(self, observation, action):\n # Last action is used as \"switch TV\" action. Ideally it should be defined as\n # \"idle\", so it would not do anything else.\n if (action + 1 == len(self._action_list) or\n 'action' not in self._noise_type):\n\n if 'image' in self._noise_type:\n self._current_noise = self._images_for_noise[\n self._random_state.randint(0, len(self._images_for_noise))]\n\n if 'noise' in self._noise_type:\n self._current_noise = self._random_state.randint(\n 0, 255, (int(observation.shape[0]/2), int(observation.shape[1]/2),\n observation.shape[2]))\n\n observation[int(observation.shape[0]/2):,\n int(observation.shape[1]/2):, :] = self._current_noise\n return observation\n\n def reset(self):\n self._current_noise = np.zeros((int(self.observation_space.shape[0]/2),\n int(self.observation_space.shape[1]/2),\n self.observation_space.shape[2]))\n self._env.reset(seed=self._random_state.randint(0, 2 ** 31 - 1))\n time_step = self._env.observations()\n main_observation = self._transform_observation(\n time_step[self._main_observation])\n if self._noise_type:\n main_observation = self.add_noise(main_observation, -1)\n return main_observation\n\n def close(self):\n self._env.close()\n\n def step(self, action):\n \"\"\"Performs one step in the environment.\n\n Args:\n action: which action to take\n Returns:\n A tuple (observation, reward, done, metadata)\n \"\"\"\n reward = self._env.step(self._action_list[action],\n num_steps=self._action_repeat)\n done = np.array(not self._env.is_running())\n if done:\n self.reset()\n time_step = self._env.observations()\n main_observation = self._transform_observation(\n time_step[self._main_observation])\n if self._noise_type:\n main_observation = self.add_noise(main_observation, action)\n metadata = {\n 'position': time_step['DEBUG.POS.TRANS'],\n 'frame_num': time_step['MAP_FRAME_NUMBER'],\n 'maze_layout': time_step['DEBUG.MAZE.LAYOUT'],\n 'rotation': time_step['DEBUG.POS.ROT'],\n 'velocity': time_step['DEBUG.PLAYERS.VELOCITY'],\n }\n return (main_observation, reward, done, metadata)\n\n\nclass OracleRewardWrapper(gym.Wrapper):\n \"\"\"Replaces reward in the environment with reward for visiting new states.\"\"\"\n\n def __init__(self, env):\n \"\"\"Creates a new oracle to compute the exploration reward.\"\"\"\n gym.Wrapper.__init__(self, env)\n self._oracle_exploration_reward = oracle.OracleExplorationReward()\n\n def reset(self):\n self._oracle_exploration_reward.reset()\n return self.env.reset()\n\n def step(self, action):\n observation, reward, done, info = self.env.step(action)\n return observation, self.reward(reward, info['position']), done, info\n\n def reward(self, reward, agent_position):\n return self._oracle_exploration_reward.update_position(agent_position)\n\n\nclass EndEpisodeOnRespawn(gym.Wrapper):\n \"\"\"Wrappers that end episodes on respawn.\"\"\"\n\n def __init__(self, env):\n \"\"\"Creates a new wrapper that terminates episodes on respawn.\"\"\"\n gym.Wrapper.__init__(self, env)\n self._last_frame_num = 0\n\n def reset(self):\n self._last_frame_num = 0\n return self.env.reset()\n\n def step(self, action):\n observation, reward, done, info = self.env.step(action)\n\n frame_num = info['frame_num']\n if done:\n # Set the last frame num to 0 so that the next step is not\n # considered as a respawn.\n self._last_frame_num = 0\n else:\n if frame_num < self._last_frame_num:\n # A frame number that is decreasing means there was a respawn.\n # Set the done flag and resets the underlying environment.\n print('Respawn detected fn: ', frame_num, ' lfn: ',\n self._last_frame_num, ' reward:', reward)\n self.reset()\n done = True\n else:\n self._last_frame_num = frame_num\n\n return observation, reward, done, info\n\n\ndef make_dmlab_env(env_settings, num_env=8, small_action_set=False,\n oracle_reward=False, use_monitor=True):\n \"\"\"Creates a DMLab environment.\"\"\"\n def make_env(seed):\n def _thunk():\n tmp_settings = copy.deepcopy(env_settings)\n tmp_settings['seed'] = seed\n action_set = ACTION_SET_SMALL if small_action_set else DEFAULT_ACTION_SET\n env = DMLabWrapper('dmlab', tmp_settings, action_set=action_set)\n if oracle_reward:\n env = OracleRewardWrapper(env)\n if use_monitor:\n env = Monitor(env, logger.get_dir() and os.path.join(logger.get_dir(),\n str(seed)))\n return env\n return _thunk\n\n return SubprocVecEnv([make_env(1 + i) for i in range(num_env)])\n"
] |
[
[
"numpy.array",
"numpy.random.RandomState",
"numpy.moveaxis"
]
] |
AnH0ang/big-data-challenge
|
[
"aa9ba92e2355bc2838a037219d20d387e2eefdbb"
] |
[
"src/app/utils.py"
] |
[
"from copy import deepcopy\n\nimport numpy as np\nimport optuna\nimport pandas as pd\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport streamlit as st\nfrom optuna.study import Study\nfrom sklearn.metrics import (\n accuracy_score,\n auc,\n f1_score,\n log_loss,\n roc_auc_score,\n roc_curve,\n)\nfrom universal_data_catalog.data_catalog import DataCatalog\n\nfrom src.elo.system import EloSystem, sigmoid\n\nhash_funcs = {\n pd.DataFrame: lambda df: hash(tuple(df.iloc[0].items())) * len(df),\n EloSystem: hash,\n}\n\n\[email protected](allow_output_mutation=True)\ndef load_study() -> Study:\n study = optuna.create_study(\n load_if_exists=True,\n study_name=\"elo_system_study\",\n storage=\"sqlite:///data/05_model/optuna.db\",\n )\n return study\n\n\[email protected]\ndef load_history() -> pd.DataFrame:\n catalog = DataCatalog(\"conf/catalog/default.yaml\", \".\")\n history_df: pd.DataFrame = catalog.load(\"history\")\n return history_df\n\n\[email protected]\ndef load_race_df() -> pd.DataFrame:\n catalog = DataCatalog(\"conf/catalog/default.yaml\", \".\")\n race_df: pd.DataFrame = catalog.load(\"race_processed\")\n return race_df\n\n\[email protected](allow_output_mutation=True)\ndef load_elo_system() -> EloSystem:\n catalog = DataCatalog(\"conf/catalog/default.yaml\", \".\")\n elo_system: EloSystem = catalog.load(\"elo_system\")\n return elo_system\n\n\[email protected]\ndef load_players_list() -> pd.DataFrame:\n catalog = DataCatalog(\"conf/catalog/default.yaml\", \".\")\n player_info_df: pd.DataFrame = catalog.load(\"player_info\")\n return player_info_df\n\n\[email protected]\ndef load_player_stats(history_df: pd.DataFrame, player_id: int) -> pd.DataFrame:\n player_df = history_df.query(\"challenger == @player_id\").copy()\n return player_df\n\n\[email protected](allow_output_mutation=True)\ndef load_elo_df() -> pd.DataFrame:\n catalog = DataCatalog(\"conf/catalog/default.yaml\", \".\")\n elo_df = catalog.load(\"elo_results\")\n return elo_df\n\n\[email protected]\ndef _calc_longest_winstreak(player_df: pd.DataFrame) -> float:\n # Longest Win Streak\n is_winning = (player_df[\"winner\"] == player_df[\"challenger\"]).astype(bool).values\n\n longest_streak = 0\n current_streak = 0\n for i in range(1, len(is_winning)):\n if is_winning[i] and (is_winning[i] == is_winning[i - 1]):\n current_streak += 1\n else:\n current_streak = 0\n\n if current_streak > longest_streak:\n longest_streak = current_streak\n\n return longest_streak\n\n\[email protected](hash_funcs=hash_funcs)\ndef _calc_win_rate(player_df: pd.DataFrame) -> float:\n win_rate = (player_df[\"winner\"] == player_df[\"challenger\"]).mean()\n return win_rate\n\n\[email protected](hash_funcs=hash_funcs)\ndef _calc_money_won(player_df: pd.DataFrame) -> float:\n is_winning = (player_df[\"winner\"] == player_df[\"challenger\"]).astype(bool).values\n money_won = (\n player_df[is_winning][\"money\"].sum() - player_df[~is_winning][\"money\"].sum() # type: ignore\n )\n return money_won\n\n\[email protected](hash_funcs=hash_funcs, allow_output_mutation=True)\ndef _plot_elo_history(player_df: pd.DataFrame):\n player_df = player_df.sort_values(\"race_driven\")\n is_winning = (player_df[\"winner\"] == player_df[\"challenger\"]).astype(bool).values\n\n fig = go.Figure()\n # px.line(player_df, x='race_driven', y=\"elo_challenger_after\", title=\"Elo Developement\")\n fig.add_trace(\n go.Scatter(\n mode=\"markers\",\n x=player_df[\"race_driven\"][~is_winning], # type: ignore\n y=player_df[\"elo_challenger_after\"][~is_winning], # type: ignore\n name=\"losses\",\n line_color=\"red\",\n )\n )\n fig.add_trace(\n go.Scatter(\n mode=\"markers\",\n x=player_df[\"race_driven\"][is_winning], # type: ignore\n y=player_df[\"elo_challenger_after\"][is_winning], # type: ignore\n name=\"wins\",\n line_color=\"green\",\n )\n )\n fig.add_trace(\n go.Scatter(\n x=player_df[\"race_driven\"],\n y=player_df[\"elo_challenger_after\"],\n line_color=\"black\",\n name=\"Elo\",\n )\n )\n fig.update_xaxes(title_text=\"Race Date\") # type: ignore\n fig.update_yaxes(title_text=\"Elo\") # type: ignore\n return fig\n\n\ndef _plot_win_proba(proba):\n labels = [\"Challenger\", \"Opponent\"]\n probas = [proba, 1 - proba]\n fig = go.Figure(data=[go.Pie(labels=labels, values=probas, hole=0.4)])\n winner = \"Winner: \" + (\"Challenger\" if (proba > 0.5) else \"Opponent\")\n fig.update_layout(\n title=\"Win Probability\",\n showlegend=True,\n annotations=[dict(text=winner, x=0.5, y=0.5, font_size=12, showarrow=False)],\n )\n return fig\n\n\[email protected](hash_funcs=hash_funcs)\ndef _plot_waterfall(elo_system, challenger_id, opponent_id, track_id):\n challenger_base_elo = elo_system.id2player[challenger_id].elo[0]\n challenger_track_elo = elo_system.id2player[challenger_id].elo[track_id]\n a = elo_system.rater.a\n\n opponent_base_elo = elo_system.id2player[opponent_id].elo[0]\n opponent_track_elo = elo_system.id2player[opponent_id].elo[track_id]\n\n challenger_elo_list = [challenger_base_elo, challenger_track_elo, a / 2, 0]\n opponent_elo_list = [opponent_base_elo, opponent_track_elo, -a / 2, 0]\n\n fig = go.Figure()\n fig.add_trace(\n go.Waterfall(\n name=\"challenger elo\",\n orientation=\"v\",\n measure=[\"relative\", \"relative\", \"relative\", \"total\"],\n x=[\"base elo\", \"track elo\", \"challenger advantage\", \"total\"],\n textposition=\"inside\",\n text=[f\"{i:.2f}\" for i in challenger_elo_list[:-1]] + [\"Challenger\"],\n y=challenger_elo_list,\n connector={\"line\": {\"color\": \"rgb(63, 63, 63)\"}},\n )\n )\n\n fig.add_trace(\n go.Waterfall(\n name=\"opponent elo\",\n orientation=\"v\",\n measure=[\"relative\", \"relative\", \"relative\", \"total\"],\n x=[\"base elo\", \"track elo\", \"challenger advantage\", \"total\"],\n textposition=\"inside\",\n text=[f\"{i:.2f}\" for i in opponent_elo_list[:-1]] + [\"Opponent\"],\n y=opponent_elo_list,\n connector={\"line\": {\"color\": \"rgb(63, 63, 63)\"}},\n )\n )\n\n fig.update_layout(\n title=\"Elo Split\",\n showlegend=True,\n waterfallgroupgap=0.2,\n )\n return fig\n\n\[email protected](hash_funcs=hash_funcs)\ndef _calc_track_df(player_df, elo_system, player_id) -> pd.DataFrame:\n def track_metrics(df):\n return pd.Series(\n {\"nb_games\": len(df), \"win_rate\": (df[\"winner\"] == df[\"challenger\"]).mean()}\n )\n\n base_elo = elo_system.id2player[player_id].elo[0]\n track_elo = pd.Series(\n {\n track_id: base_elo + elo_system.id2player[player_id].elo[track_id] # type: ignore\n for track_id in range(1, 13)\n }\n )\n track_df = player_df.groupby(\"track_id\").apply(track_metrics)\n track_df[\"elo\"] = track_elo\n track_df[\"nb_games\"] = track_df[\"nb_games\"].astype(int)\n return track_df.reset_index()[[\"track_id\", \"elo\", \"win_rate\", \"nb_games\"]]\n\n\[email protected](hash_funcs=hash_funcs)\ndef _plot_track_elo(elo_system, player_id):\n base_elo = elo_system.id2player[player_id].elo[0]\n track2elo = {\n track_id: base_elo + elo_system.id2player[player_id].elo[track_id]\n for track_id in range(1, 13)\n }\n\n elo_list = list(track2elo.values())\n track_list = list(f\"{i}\" for i in track2elo.keys())\n\n fig = px.bar(x=track_list, y=elo_list)\n fig.add_hline(y=base_elo, line_dash=\"dash\", line_color=\"red\", name=\"Base Elo\")\n fig.update_xaxes(title_text=\"Track\") # type: ignore\n fig.update_yaxes(title_text=\"Elo\") # type: ignore\n return fig\n\n\[email protected](hash_funcs=hash_funcs)\ndef _calc_elo_metrics(elo_df):\n y_pred = (elo_df[\"win_probability\"] >= 0.5).astype(int)\n y_proba = elo_df[\"win_probability\"]\n y_true = elo_df[\"challenger_is_winning\"]\n\n logit = log_loss(y_true, y_proba)\n accuracy = accuracy_score(y_true, y_pred)\n f1 = f1_score(y_true, y_pred)\n auc_score = roc_auc_score(y_true, y_proba)\n return logit, accuracy, f1, auc_score\n\n\[email protected](hash_funcs=hash_funcs)\ndef _plot_roc_curve(elo_df):\n y_proba = elo_df[\"win_probability\"]\n y_true = elo_df[\"challenger_is_winning\"]\n\n fpr, tpr, thresholds = roc_curve(y_true, y_proba)\n\n fig = px.area(\n x=fpr,\n y=tpr,\n title=f\"ROC Curve (AUC={auc(fpr, tpr):.4f})\",\n labels=dict(x=\"False Positive Rate\", y=\"True Positive Rate\"),\n width=700,\n height=500,\n )\n fig.add_shape(type=\"line\", line=dict(dash=\"dash\"), x0=0, x1=1, y0=0, y1=1)\n\n fig.update_yaxes(scaleanchor=\"x\", scaleratio=1)\n fig.update_xaxes(constrain=\"domain\")\n return fig\n\n\[email protected](hash_funcs=hash_funcs)\ndef _calc_hyperparameter_df(elo_system):\n hyperparameter_df = (\n pd.Series(\n {\n k: v\n for k, v in elo_system.rater.__dict__.items()\n if k not in [\"Omega\", \"nb_tracks\"]\n }\n )\n .to_frame(\"value\")\n .reset_index()\n .rename(columns={\"index\": \"hyperparameter\"})\n )\n return hyperparameter_df\n\n\[email protected](hash_funcs=hash_funcs)\ndef _plot_slice(study: Study, parameter: str):\n study_ = deepcopy(study)\n fig = optuna.visualization.plot_slice(\n study_, params=[parameter], target_name=\"Negative Log Likelihood\"\n )\n return fig\n\n\[email protected](hash_funcs=hash_funcs)\ndef _plot_cdf(elo_system, results_df):\n a = elo_system.rater.a\n alpha = elo_system.rater.alpha\n\n results_df[\"elo_diff\"] = (\n results_df[\"elo_challenger_before\"] - results_df[\"elo_opponent_before\"] + a\n )\n fig = go.Figure()\n\n sample_df = results_df.sample(50)\n fig.add_trace(\n go.Scatter(\n x=sample_df[\"elo_diff\"],\n y=sample_df[\"challenger_is_winning\"].astype(int),\n name=\"Samples\",\n mode=\"markers\",\n )\n )\n\n x = np.linspace(-1500, 1500, 200)\n y = sigmoid(alpha * x)\n fig.add_trace(go.Scatter(x=x, y=y, name=\"Modelled CDF\"))\n\n count, bins_count = np.histogram(results_df[\"elo_diff\"], bins=50)\n pdf = count / sum(count)\n cdf = np.cumsum(pdf)\n fig.add_trace(go.Scatter(x=bins_count[1:], y=cdf, name=\"CDF on Test Data\"))\n\n fig.update_xaxes(title_text=\"Elo Difference\") # type: ignore\n fig.update_yaxes(title_text=\"Win Probability\") # type: ignore\n\n return fig\n"
] |
[
[
"sklearn.metrics.roc_auc_score",
"numpy.linspace",
"numpy.cumsum",
"sklearn.metrics.roc_curve",
"sklearn.metrics.log_loss",
"sklearn.metrics.auc",
"sklearn.metrics.f1_score",
"numpy.histogram",
"sklearn.metrics.accuracy_score"
]
] |
lopez86/DataTools
|
[
"573419f3a40ddeb5e9eaf5ced8ea8dbf41c8a65e"
] |
[
"data_tools/tf/feed_dict.py"
] |
[
"import funcy\r\nimport numpy as np\r\n\r\n\r\ndef make_simple_feed_builder(\r\n istrain_str='is_train',\r\n sparse=None\r\n):\r\n builder = funcy.partial(\r\n simple_feed_builder,\r\n istrain_str=istrain_str,\r\n sparse=sparse\r\n )\r\n return builder\r\n\r\n\r\ndef simple_feed_builder(\r\n data,\r\n is_train,\r\n istrain_str='is_train',\r\n sparse=None\r\n):\r\n \"\"\"Build a tensorflow feed-dict.\r\n\r\n Args:\r\n data: Dataset instance\r\n is_train: bool, whether this is a training batch or not\r\n istrain_str: str, name of the tensor identifying a training batch\r\n sparse: Maybe(dict), should have the same keys as the inputs\r\n When true, treat as a sparse input\r\n\r\n Returns:\r\n dict, a feed dict to use as input to a Tensorflow session\r\n \"\"\"\r\n if data is None:\r\n return None\r\n\r\n if sparse is None:\r\n sparse = {key: False for key in data.inputs.keys()}\r\n\r\n feed_dict = {}\r\n for key, input_data in data.inputs.items():\r\n input_dict = _make_input_dict(key, input_data, sparse=sparse[key])\r\n feed_dict.update(input_dict)\r\n\r\n if data.outputs is not None:\r\n for key, output_data in data.outputs.items():\r\n output_dict = _make_input_dict(key, output_data, sparse=False)\r\n feed_dict.update(output_dict)\r\n\r\n feed_dict[istrain_str + ':0'] = is_train\r\n\r\n return feed_dict\r\n\r\n\r\ndef _make_input_dict(name, input_data, sparse=False):\r\n \"\"\"Create a Tensorflow feed-dict for a particular data array.\r\n\r\n Args:\r\n name: str, the name of the corresponding tensorflow variable\r\n input_data: Array-like, typically a numpy array\r\n sparse: bool, if True, create a dict for a Tensorflow sparse\r\n tensor.\r\n\r\n Returns:\r\n dict\r\n \"\"\"\r\n if not sparse:\r\n feed_dict = {name + ':0': input_data}\r\n else:\r\n input_coo = input_data.tocoo()\r\n indices = np.mat([input_coo.row, input_coo.col]).transpose()\r\n feed_dict = {\r\n name + '/indices:0': indices,\r\n name + '/values:0': input_coo.data,\r\n name + '/shape:0': input_coo.shape\r\n }\r\n\r\n return feed_dict\r\n"
] |
[
[
"numpy.mat"
]
] |
pahn04/PPConv
|
[
"395957b919786bb5b603f37a94ccf9173afce085"
] |
[
"fpconv_code/models/ppcnn/modules/se.py"
] |
[
"import torch.nn as nn\n\n__all__ = ['SE']\n\n\nclass SE(nn.Module):\n def __init__(self, channel, reduction=8):\n super().__init__()\n self.fc = nn.Sequential(\n nn.Linear(channel, channel // reduction, bias=False),\n nn.ReLU(inplace=True),\n nn.Linear(channel // reduction, channel, bias=False),\n nn.Sigmoid()\n )\n\n def forward(self, inputs):\n return inputs * self.fc(inputs.mean(-1).mean(-1)).view(inputs.shape[0], inputs.shape[1], 1, 1)\n"
] |
[
[
"torch.nn.Linear",
"torch.nn.ReLU",
"torch.nn.Sigmoid"
]
] |
QuinnQiao/pytorch-CycleGAN-and-pix2pix
|
[
"1f293d1f7c357002ef963ed0cbdbf87c9ba970f5"
] |
[
"data/colorization_dataset.py"
] |
[
"import os.path\nfrom data.base_dataset import BaseDataset, get_params, get_transform\nfrom data.image_folder import make_dataset\nfrom skimage import color # require skimage\nfrom PIL import Image\nimport numpy as np\nimport torchvision.transforms as transforms\n\n\nclass ColorizationDataset(BaseDataset):\n \"\"\"This dataset class can load a set of natural images in RGB, and convert RGB format into (L, ab) pairs in Lab color space.\n\n This dataset is required by pix2pix-based colorization model ('--model colorization')\n \"\"\"\n @staticmethod\n def modify_commandline_options(parser, is_train):\n \"\"\"Add new dataset-specific options, and rewrite default values for existing options.\n\n Parameters:\n parser -- original option parser\n is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.\n\n Returns:\n the modified parser.\n\n By default, the number of channels for input image is 1 (L) and\n the nubmer of channels for output image is 2 (ab). The direction is from A to B\n \"\"\"\n parser.set_defaults(input_nc=1, output_nc=2, direction='AtoB')\n return parser\n\n def __init__(self, opt):\n \"\"\"Initialize this dataset class.\n\n Parameters:\n opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions\n \"\"\"\n BaseDataset.__init__(self, opt)\n self.dir = os.path.join(opt.dataroot)\n self.AB_paths = sorted(make_dataset(self.dir, opt.max_dataset_size))\n assert(opt.input_nc == 1 and opt.output_nc == 2 and opt.direction == 'AtoB')\n\n def __getitem__(self, index):\n \"\"\"Return a data point and its metadata information.\n\n Parameters:\n index - - a random integer for data indexing\n\n Returns a dictionary that contains A, B, A_paths and B_paths\n A (tensor) - - the L channel of an image\n B (tensor) - - the ab channels of the same image\n A_paths (str) - - image paths\n B_paths (str) - - image paths (same as A_paths)\n \"\"\"\n path = self.AB_paths[index]\n im = Image.open(path).convert('RGB')\n transform_params = get_params(self.opt, im.size)\n transform = get_transform(self.opt, transform_params, convert=False)\n im = transform(im)\n im = np.array(im)\n lab = color.rgb2lab(im).astype(np.float32)\n lab_t = transforms.ToTensor()(lab)\n A = lab_t[[0], ...] / 50.0 - 1.0\n B = lab_t[[1, 2], ...] / 110.0\n return {'A': A, 'B': B, 'A_paths': path, 'B_paths': path}\n\n def __len__(self):\n \"\"\"Return the total number of images in the dataset.\"\"\"\n return len(self.AB_paths)\n"
] |
[
[
"numpy.array"
]
] |
EllonLi/faster-rcnn-pytorch
|
[
"577a5062f3643b2667d9d28018b07e255dbf7551"
] |
[
"lib/model/faster_rcnn/resnet.py"
] |
[
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom model.utils.config import cfg\nfrom model.faster_rcnn.faster_rcnn import _fasterRCNN\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport math\nimport torch.utils.model_zoo as model_zoo\nimport pdb\n\n__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',\n 'resnet152']\n\n\nmodel_urls = {\n 'resnet18': 'https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth',\n 'resnet34': 'https://s3.amazonaws.com/pytorch/models/resnet34-333f7ec4.pth',\n 'resnet50': 'https://s3.amazonaws.com/pytorch/models/resnet50-19c8e357.pth',\n 'resnet101': 'https://s3.amazonaws.com/pytorch/models/resnet101-5d3b4d8f.pth',\n 'resnet152': 'https://s3.amazonaws.com/pytorch/models/resnet152-b121ed2d.pth',\n}\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"3x3 convolution with padding\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm2d(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, bias=False) # change\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, # change\n padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes * 4)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n def __init__(self, block, layers, num_classes=1000):\n self.inplanes = 64\n super(ResNet, self).__init__()\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,\n bias=False)\n self.bn1 = nn.BatchNorm2d(64)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=0, ceil_mode=True) # change\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2)\n # it is slightly better whereas slower to set stride = 1\n # self.layer4 = self._make_layer(block, 512, layers[3], stride=1)\n self.avgpool = nn.AvgPool2d(7)\n self.fc = nn.Linear(512 * block.expansion, num_classes)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n\n return x\n\nclass ResNet_2(nn.Module):\n # resnet_model_18_1 在resnet-18的基础之上修改网络\n # 1. 在第2个block之后依次加一个1*1conv,一个avgpool\n # 2. 在第3个block之后加一个1*1conv\n # 3. 去掉第4个block\n # 4. 将最后一个avgpool化改为maxpool\n\n def __init__(self, block, layers, num_classes=1000):\n self.inplanes = 64\n super(ResNet_2, self).__init__()\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2,\n bias=False)\n self.bn1 = nn.BatchNorm2d(64)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2) # 28*28*128\n\n self.conv2 = nn.Conv2d(128, 256, kernel_size=1, stride=1, bias=False) #add 1*1*256 conv, out 28*28*256\n self.avgpool2 = nn.AvgPool2d(kernel_size=2, stride=2) #out 14*14*256\n\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n # self.layer3 = self._make_layer(block, 512, layers[2], stride=2)\n self.conv3 = nn.Conv2d(256, 512, kernel_size=1) #add 1*1 conv\n\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2)\n # self.avgpool = nn.AvgPool2d(7, stride=1)\n self.maxpool2 = nn.MaxPool2d(kernel_size=7, stride=1)\n self.fc = nn.Linear(512 * block.expansion, num_classes)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n \n return nn.Sequential(*layers)\n #Sequential是一个顺序容器,按照在构造函数中的传递的顺序添加到其中。\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x) #out 28*28*128\n\n x = self.conv2(x) #out 28*28*256\n x = self.avgpool2(x) # out 14*14*256\n\n # x = self.layer3(x)\n # x = self.conv3(x)\n x = self.layer4(x)\n\n # x = self.avgpool(x)\n x = self.maxpool2(x)\n # 将前面多维度的tensor展平成一维,x是包含batchsize维度为4的tensor,即(batchsize,channels,x,y),\n # view()函数的功能根reshape类似,用来转换size大小\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n\n return x\n\n\ndef resnet18(pretrained=False):\n \"\"\"Constructs a ResNet-18 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(BasicBlock, [2, 2, 2, 2])\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))\n return model\n\ndef resnet18_2(pretrained=False):\n \"\"\"Constructs a ResNet-18 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet_2(BasicBlock, [2, 2, 2, 2])\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))\n return model\n\n\ndef resnet34(pretrained=False):\n \"\"\"Constructs a ResNet-34 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(BasicBlock, [3, 4, 6, 3])\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet34']))\n return model\n\n\ndef resnet50(pretrained=False):\n \"\"\"Constructs a ResNet-50 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(Bottleneck, [3, 4, 6, 3])\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))\n return model\n\n\ndef resnet101(pretrained=False):\n \"\"\"Constructs a ResNet-101 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(Bottleneck, [3, 4, 23, 3])\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet101']))\n return model\n\n\ndef resnet152(pretrained=False):\n \"\"\"Constructs a ResNet-152 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(Bottleneck, [3, 8, 36, 3])\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))\n return model\n\nclass resnet(_fasterRCNN):\n def __init__(self, classes, num_layers=18,pretrained=False, class_agnostic=False):\n self.model_path = 'data/pretrained_model/resnet{}_caffe.pth'.format(str(num_layers))\n self.num_layers=num_layers\n if num_layers==18 or num_layers==19 or num_layers==34: \n self.dout_base_model = 256\n self.fc_channels=512\n elif num_layers==50 or num_layers==101 or num_layers==152:\n self.dout_base_model=1024\n self.fc_channels=2048\n self.pretrained = pretrained\n self.class_agnostic = class_agnostic\n \n\n _fasterRCNN.__init__(self, classes, class_agnostic)\n\n def _init_modules(self):\n if self.num_layers==18:\n resnet = resnet18()\n elif self.num_layers==19:\n resnet=resnet18_2()\n elif self.num_layers==34:\n resnet=resnet34()\n elif self.num_layers==50:\n resnet=resnet50()\n elif self.num_layers==101:\n resnet=resnet101()\n elif self.num_layers==152:\n resnet=resnet152()\n if self.pretrained == True:\n print(\"Loading pretrained weights from %s\" %(self.model_path))\n state_dict = torch.load(self.model_path)\n resnet.load_state_dict({k:v for k,v in state_dict.items() if k in resnet.state_dict()})\n\n # Build resnet.\n self.RCNN_base = nn.Sequential(resnet.conv1, resnet.bn1,resnet.relu,\n resnet.maxpool,resnet.layer1,resnet.layer2,resnet.layer3)\n #res18,输出是256,与vgg16相同\n self.RCNN_top = nn.Sequential(resnet.layer4)\n\n self.RCNN_cls_score = nn.Linear(self.fc_channels, self.n_classes)\n if self.class_agnostic:\n self.RCNN_bbox_pred = nn.Linear(self.fc_channels, 4)\n else:\n self.RCNN_bbox_pred = nn.Linear(self.fc_channels, 4 * self.n_classes)\n\n # Fix blocks\n for p in self.RCNN_base[0].parameters(): p.requires_grad=False\n for p in self.RCNN_base[1].parameters(): p.requires_grad=False\n\n assert (0 <= cfg.RESNET.FIXED_BLOCKS < 4)\n if cfg.RESNET.FIXED_BLOCKS >= 3:\n for p in self.RCNN_base[6].parameters(): p.requires_grad=False\n if cfg.RESNET.FIXED_BLOCKS >= 2:\n for p in self.RCNN_base[5].parameters(): p.requires_grad=False\n if cfg.RESNET.FIXED_BLOCKS >= 1:\n for p in self.RCNN_base[4].parameters(): p.requires_grad=False\n\n def set_bn_fix(m):\n classname = m.__class__.__name__\n if classname.find('BatchNorm') != -1:\n for p in m.parameters(): p.requires_grad=False\n\n self.RCNN_base.apply(set_bn_fix)\n self.RCNN_top.apply(set_bn_fix)\n\n def train(self, mode=True):\n # Override train so that the training mode is set as we want\n nn.Module.train(self, mode)\n if mode:\n # Set fixed blocks to be in eval mode\n self.RCNN_base.eval()\n self.RCNN_base[5].train()\n self.RCNN_base[6].train()\n\n def set_bn_eval(m):\n classname = m.__class__.__name__\n if classname.find('BatchNorm') != -1:\n m.eval()\n\n self.RCNN_base.apply(set_bn_eval)\n self.RCNN_top.apply(set_bn_eval)\n\n def _head_to_tail(self, pool5):\n fc7 = self.RCNN_top(pool5).mean(3).mean(2)\n return fc7\n"
] |
[
[
"torch.nn.Sequential",
"torch.load",
"torch.nn.init.constant_",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.nn.AvgPool2d",
"torch.nn.Linear",
"torch.nn.Module.train",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.utils.model_zoo.load_url",
"torch.nn.init.kaiming_normal_"
]
] |
Psychedelic-Engineering/sleep-machine
|
[
"2fcb486b3735fc8ec1d3d29e75c6c9bb60c7d2a7"
] |
[
"hardware/channel.py"
] |
[
"from collections import deque\nimport math\nimport numpy as np\nfrom scipy import signal\n\n\nclass Channel:\n\n\tdef __init__(self, name, min, max, maxNum, offset=0.0):\n\t\tself.name = name\n\t\tself.min = min\n\t\tself.max = max\n\t\tself.num = 0\n\t\tself.sum = 0\n\t\tself.buffersum = 0\n\t\tself.size = maxNum\n\t\tself.buffer = deque(maxlen=maxNum)\n\t\tself.offset = offset\n\n\t\tself.npBufferSize = 800\n\t\tself.npBufferPos = 0\n\t\tself.npBuffer = np.zeros(self.npBufferSize)\n\n\t\tself.lastVal = 0\n\n\tdef __repr__(self):\n\t\treturn \"%s (%.1f-%.1f)\" % (self.name, self.min, self.max)\n\n\tdef calibrate(self):\n\t\tself.offset = -self.buffersum / min(self.size, self.num)\n\n\tdef smooth(self, x,beta):\n\t\twindow_len=50\n\t\tsampleRate = 10\n\t\tcutOff = 0.01\n\t\tfir_coeff = signal.firwin(window_len, cutOff)\n\t\tsmoothed = signal.lfilter(fir_coeff, 1.0, self.npBuffer)\n\t\treturn smoothed\n\n\tdef putValue(self, value):\n\t\t# deque buffer\n\t\tif self.num >= self.size:\n\t\t\tself.buffersum -= self.buffer[0]\n\t\tnewValue = value\n\t\tself.buffersum += newValue\n\t\tself.buffer.append(newValue)\n\t\tself.num += 1\n\t\tself.sum += newValue\n\t\t\"\"\"\n\t\t# numpy buffer\n\t\tself.npBufferPos += 1\n\t\tif self.npBufferPos >= self.npBufferSize:\n\t\t\tself.npBufferPos = 0\n\t\t\tself.smoothed = self.smooth(self.npBuffer, 1)\n\t\t\tself.gradient = np.diff(self.npBuffer)\n\t\t\ttry:\n\t\t\t\tself.onUpdate(self)\n\t\t\texcept:\n\t\t\t\t#raise\n\t\t\t\tpass\n\t\tself.npBuffer[self.npBufferPos] = value\n\t\t\"\"\"\n\t\t# Auto Calibration\n\t\t#if self.num % 100 == 0:\n\t\t#\tself.calibrate()\n\n\tdef calibrate(self):\n\t\tself.offset = -self.buffer[-1]\n\n\tdef getValue(self):\n\t\t#if self.num > 0:\n\t\treturn self.buffer[-1] + self.offset\n\n\tdef getAvg(self):\n\t\treturn self.sum / self.num + self.offset\n\n\tdef getBufferAvg(self):\n\t\tval = self.buffer[-1] # current value\n\t\tavg = self.buffersum / min(self.size, self.num) # moving average\n\t\tmix = 0.5 * val + 0.5 * avg # weighted average\n\t\tdif = math.pow((val - avg) / 20, 5) # differential\n\t\trng = 0\n\t\t#for i in self.buffer:\n\t\t#\trng = max(abs(avg-i), rng)\n\t\t#return rng\n\t\treturn avg + self.offset\n\t\tif dif > 50:\n\t\t\t#self.buffersum = val * self.size\n\t\t\treturn val + self.offset\n\t\telse:\n\t\t\treturn avg + self.offset\n\n\tdef getRng(self):\n\t\trng = 0\n\t\tder = 0\n\t\tavg = self.buffersum / min(self.size, self.num)\n\t\tfor i in self.buffer:\n\t\t\t#rng = 0.01 * max(pow(avg - i, 4), rng)\n\t\t\tder = der + pow((avg - i) / 4, 2)\n\t\t\t#der = der + abs(avg-i)\n\t\tder /= self.size\n\t\treturn der\n\n\tdef getDeriv(self):\n\t\tval = self.buffer[-1] # current value\n\t\tavg = self.buffersum / min(self.size, self.num) # moving average\n\t\tmix = 0.5 * val + 0.5 * avg # weighted average\n\t\tdif = avg - val\n\t\t#dif = 5 * math.pow(dif / 20, 6) # differential\n\t\treturn dif\n\n\tdef getDiff(self):\n\t\tavg = self.buffersum / min(self.size, self.num)\n\t\tresult = avg - self.lastVal\n\t\tself.lastVal = avg\n\t\t#return math.pow(result, 2)\n\t\tif self.num>2:\n\t\t\tresult = self.buffer[-1] - self.buffer[-2]\n\t\telse:\n\t\t\tresult = 0\n\t\treturn math.pow(result, 4)"
] |
[
[
"scipy.signal.lfilter",
"numpy.zeros",
"scipy.signal.firwin"
]
] |
satejsoman/matplotlib2tikz
|
[
"583a66f6842d236ee42d85485de9c6a503585893"
] |
[
"test/test_scatter.py"
] |
[
"# -*- coding: utf-8 -*-\n#\nfrom helpers import assert_equality\n\n\ndef plot():\n from matplotlib import pyplot as plt\n import numpy as np\n\n fig = plt.figure()\n with plt.style.context((\"fivethirtyeight\")):\n np.random.seed(123)\n plt.scatter(\n np.linspace(0, 100, 101),\n np.linspace(0, 100, 101) + 15 * np.random.rand(101),\n )\n return fig\n\n\ndef test():\n assert_equality(plot, __file__[:-3] + \"_reference.tex\")\n return\n\n\nif __name__ == \"__main__\":\n import helpers\n\n helpers.compare_mpl_latex(plot)\n # helpers.print_tree(plot())\n"
] |
[
[
"numpy.linspace",
"numpy.random.seed",
"matplotlib.pyplot.style.context",
"numpy.random.rand",
"matplotlib.pyplot.figure"
]
] |
jjd9/RobotMapping_SLAM_Assignments_In_Cpp
|
[
"4810a5dbb9ec8f07c8412d27049426a384ef3120"
] |
[
"UKF_Slam/C++/plot.py"
] |
[
"import matplotlib.pyplot as plt\nimport pandas as pd\n\ndata = pd.read_csv(\"SLAM_estimates.csv\").values\n\nrobot = data[:,:2]\nplt.plot(robot[:,0],robot[:,1],'k-o',label='robot')\n\nfor j, i in enumerate(range(3,data.shape[1],2)):\n print(i)\n plt.plot(data[:,i],data[:,i+1],'o', label = 'landmark: '+ str(j))\n\nplt.grid()\nplt.xlabel(\"X Coord\")\nplt.ylabel(\"Y Coord\")\nplt.legend()\nplt.show()\n"
] |
[
[
"matplotlib.pyplot.legend",
"pandas.read_csv",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] |
Mattio89/visualization
|
[
"562f231c887e7328cd098a3a675cf5b99bec8aaa"
] |
[
"find_tweets.py"
] |
[
"#Tweet Finding\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom matplotlib.dates import DateFormatter\nimport matplotlib.ticker as mtick\nimport numpy as np\nimport datetime\n\ndforlando = pd.read_csv(\"ORLANDO_Full.csv\", usecols=[3,4], header=0, names=['url', 'text'], nrows=89999, parse_dates=True)\ndfmallet = pd.read_csv(\"mallet15.txt\", delim_whitespace=True, header=0, usecols=[1, 2], dtype='object', names=['File', 'Topic'], nrows=89999)\n#removed pulling in the file #, can add it again if you want but it'll probably be another set of code. \n\ndfmalletseries = dfmallet['File'].str.replace('\\D+', ' ')\ndfmallettrue = dfmallet.merge(dfmalletseries.to_frame(), left_index=True, right_index=True)\ndf2 = pd.to_numeric(dfmallettrue['File_y'])\ndfmalletorder = dfmallettrue.merge(df2.to_frame(), left_index=True, right_index=True)\ndf3 = dfmalletorder.sort_values(['File_y_y'])\n\ndf_final = df3.join(dforlando, on=['File_y_y'])\n\n\ntopic0 = df_final.loc[df_final['Topic'] == '0']\ntopic1 = df_final.loc[df_final['Topic'] == '1']\ntopic2 = df_final.loc[df_final['Topic'] == '2']\ntopic3 = df_final.loc[df_final['Topic'] == '3']\ntopic4 = df_final.loc[df_final['Topic'] == '4']\ntopic5 = df_final.loc[df_final['Topic'] == '5']\ntopic6 = df_final.loc[df_final['Topic'] == '6']\ntopic7 = df_final.loc[df_final['Topic'] == '7']\ntopic8 = df_final.loc[df_final['Topic'] == '8']\ntopic9 = df_final.loc[df_final['Topic'] == '9']\ntopic10 = df_final.loc[df_final['Topic'] == '10']\ntopic11 = df_final.loc[df_final['Topic'] == '11']\ntopic12 = df_final.loc[df_final['Topic'] == '12']\ntopic13 = df_final.loc[df_final['Topic'] == '13']\ntopic14 = df_final.loc[df_final['Topic'] == '14']\n\n\n#Change this to the topic you want to output to csv.\ntopic7.to_csv(r'exemplars7.csv')\n"
] |
[
[
"pandas.read_csv",
"pandas.to_numeric"
]
] |
Leviyu/EQVirSa
|
[
"7727ae6b504f2e903dedafe79767f4c171e69bf8"
] |
[
"code_dir/get_AVE_SNR_of_file.py"
] |
[
"import numpy as np\nimport sys \nimport os\n\n\n\n\nfile_name = sys.argv[1]\n\ndt_array = []\n\nwith open(file_name,\"r\") as f:\n for line in f.readlines():\n value = float(line.strip())\n #print(value)\n dt_array.append(value)\n\n\n\n#print(dt_array)\nmean = np.mean(dt_array)\nstd = np.std(dt_array)\nprint(\"{} {}\".format(mean.round(2),std.round(2)))\n\n\n"
] |
[
[
"numpy.std",
"numpy.mean"
]
] |
huangming6220/news_mining
|
[
"83389fcc8598a7b934fad0ac4b4db141ce26e7d9"
] |
[
"step2-2-2_clean_news_more.py"
] |
[
"# coding: utf-8\n\n###################################################################\n# Step 2-2-1: further clean news\n###################################################################\n\n# Libraries:\n# ==========\n\nimport re\nimport pandas as pd\n\n# Functions:\n# ==========\n\n### clean data\ndef clean_message_more(msg):\n imsg = True\n if msg.strip():\n # remove heading\n if msg[0] == '*':\n if imsg: print(msg)\n msg = re.sub('\\(reuters\\) - ', '. ', msg)\n if imsg: print(msg)\n else:\n if re.search('^.*?\\(reuters.*?\\) -', msg):\n if imsg: print(msg)\n msg = re.sub('^.*?\\(reuters.*?\\) - ', '', msg)\n if imsg: print(msg)\n if re.search('^\\(the following.*?(agency|company)\\)', msg):\n msg = re.sub('^\\(the following.*?(agency|company)\\)', '', msg)\n if imsg: print(msg)\n\n if re.search('^multimedia versions of reuters', msg):\n if imsg: print(msg)\n msg = re.sub('^multimedia versions of reuters.*top stories \\>', '', msg)\n msg = re.sub('page editor:.*\\.', '', msg)\n if imsg: print(msg)\n if 'note to subscribers' in msg:\n if imsg: print(msg)\n msg = re.sub('^note to subscribers.*top stories \\>', '', msg)\n if imsg: print(msg)\n if 'msg terminated multimedia' in msg:\n if imsg: print(msg)\n msg = re.sub('^msg terminated multimedia.*top stories \\>', '', msg)\n if imsg: print(msg)\n if 'click on the codes in brackets' in msg:\n if imsg: print(msg)\n msg = re.sub('click on the codes in brackets.*latest stories > ', '', msg)\n if imsg: print(msg)\n\n if 'for latest top breaking news across all markets' in msg:\n if imsg: print(msg)\n msg = re.sub('for latest top breaking news across all markets.*$','',msg)\n if imsg: print(msg)\n if 'top news summaries on other subjects' in msg:\n if imsg: print(msg)\n msg = re.sub('top news summaries on other subjects.*$','',msg)\n if imsg: print(msg)\n if re.search('\\(?(additonal|additional)?(\\s|\\()?(report|edit|writ)ing.*by.*$', msg):\n if imsg: print(msg)\n msg = re.sub('\\(?(additonal|additional)?(\\s|\\()?(report|edit|writ)ing by.*$','',msg)\n if imsg: print(msg)\n if re.search('\\(for full', msg):\n if imsg: print(msg)\n msg = re.sub('\\(for full.*$','',msg)\n if imsg: print(msg)\n\n # replace\n if ' > ' in msg:\n msg = msg.replace(' > ', '. ')\n if imsg: print(msg)\n if '*' in msg[0]:\n if '*' == msg[0]:\n msg = msg[1:].replace(' * ', '. ')\n else:\n msg = msg.replace(' * ', '. ')\n if imsg: print(msg)\n if ' * ' in msg:\n msg = msg.replace(' * ', '. ')\n msg = msg.replace(\":.\", \": \")\n\n # remove tailing\n return msg\n\n# Program:\n# ========\nnews_name = 'news'\nnews_func = clean_message_more\n# input\nnews_clean_path = 'input/{0}_clean.pickle'.format(news_name)\n# output\nnews_ready_path = 'input/{0}_ready.pickle'.format(news_name)\nprint(news_name)\nprint(news_func.__name__)\n\nnews_clean_df = pd.read_pickle(news_clean_path)\nnews_clean_df['message_story_clean'] = news_clean_df['message_story_clean'].apply(lambda x: news_func(x))\nnews_clean_df.to_pickle(news_ready_path)\nnews_clean_df.to_excel(\"input/selected_news.xlsx\")\nprint('news_ready', len(news_clean_df))\n\n# ### test\n# msg = \"\"\"hong kong, jan 3 (reuters) - two international studies of a new drug, telbivudine, have produced potentially good news for hepatitis b patients, showing that it suppresses the virus that damages the liver faster and better than other treatments. chronically infected people are at high risk of death from cirrhosis of the liver and liver cancer, diseases that kill about one million people a year, the world health organisation says. reducing the amount of hepatitis b virus in the blood is critical to limiting the adverse effects of chronic hepatitis b, which affects at least 360 million people and is the 10th leading cause of death worldwide. '(the drug) would actually hopefully help to decrease the number of people who are already suffering from hepatitis b from dying from the disease,' said professor c.l. lai, chair of hepatology at the university of hong kong medical school. hepatitis b is preventable by vaccination, but 25-40 percent of people suffering from chronic infection eventually die of liver cancer or cirrhosis, which is scarring of the liver, lai said. symptoms of hepatitis b, such as jaundice, fatigue, abdominal pain, loss of appetite, nausea and joint pain might not surface in 30 percent of all cases, and they are less common in children. almost all chronic hepatitis b sufferers were infected before they were born or when they were very young and nearly 80 percent are in asia. lai estimated that 10 percent or fewer hepatitis b sufferers worldwide took medication. one study, involving 1,367 hepatitis b patients from 20 countries, compared a group treated with telbivudine to another treated with the drug lamivudine. it showed that telbivudine, produced jointly by novartis ag and idenix pharmaceuticals , reduced the virus more quickly and after 52 weeks, those taking telbivudine achieved 10 times more reduction of the virus per millilitre of blood than those using lamivudine. in addition, a higher percentage of patients in the telbivudine group achieved non-detectable hepatitis b dna level in blood serum than the group taking lamivudine, which is made by galaxosmithklein plc . the results were published in the december issue of the new england journal of medicine. a separate study published in the december issue of annals of internal medicine compared 135 hepatitis b patients from eight countries taking telbivudine or another drug commonly prescribed for hepatitis b, adefovir, or both. again, the telbivudine group had more reduction in mean serum hepatitis b dna virus than that of the adefovir group in early, middle and late stages of the test, results showed. telbivudine was also found to effectively reduce the virus in patients who switched. adefovir is made by gilead sciences inc. (reporting by john ruwitch; editing by david fogarty) keywords: hepatitis drug/ hong kong, jan 3 (reuters) - two international studies of a new drug, telbivudine, have produced potentially good news for hepatitis b patients, showing that it suppresses the virus that damages the liver faster and better than other treatments. chronically infected people are at high risk of death from cirrhosis of the liver and liver cancer, diseases that kill about one million people a year, the world hea\",5201, new drug found better at suppressing hep b virus\"\"\"\n# clean_message_more(msg)\n"
] |
[
[
"pandas.read_pickle"
]
] |
robert-g-butler/python_reference_guide
|
[
"b9945ef645699c8676660a7c76eabe5a99bf9298"
] |
[
"module_scikit-learn/linear_regression.py"
] |
[
"'''\nThis script contains examples of Linear Regression analysis, using the SciKit-\nLearn library.\n\nLinear regression is useful when trying to predict from a set of continuous\ndata.\n'''\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.datasets import load_boston\n\nboston = load_boston()\ndf = pd.DataFrame(data=boston['data'], columns=boston['feature_names'])\ndf['target'] = pd.Series(boston['target'])\n\ndf.columns\ndf.info()\ndf.describe()\ndf.head()\n\nsns.pairplot(df)\nplt.show()\n\nsns.distplot(df['target']); plt.show()\nsns.heatmap(df.corr(), annot=True, cmap='viridis'); plt.show()\n\n# Set X and y\nX = df[['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX',\n 'PTRATIO', 'B', 'LSTAT']]\ny = df['target']\n\n# Split for test and train ----------------------------------------------------\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.4,\n random_state=101)\n\n# Make and fit the model ------------------------------------------------------\nfrom sklearn.linear_model import LinearRegression\n\nlm = LinearRegression()\nlm.fit(X=X_train, y=y_train)\n\n# Check out the intercept & coefficients of each variable.\nlm.intercept_\nlm.coef_\n\ndf_coef = pd.DataFrame(data=lm.coef_, index=X_train.columns, columns=['coef'])\ndf_coef\n\n# Check predictions\npredictions = lm.predict(X=X_test)\n\nplt.scatter(y_test, predictions)\nplt.show()\n\n# Check residuals (Normally distributed residuals means that the model was the correct choice for the data)\nsns.distplot((y_test-predictions))\nplt.show()\n\n# Evaluation Metrics (Try to minimize all of these) ---------------------------\n\n# 1. Mean Absolute Error (MAE) - Simple straight error\n# 2. Mean Squared Error (MSE) - Squares means that outliers are more visible\n# 3. Root Mean Squared Error (RMSE) - Allows RMSE results to be interpreted in \"y\" units.\n\nfrom sklearn import metrics\n\nmetrics.mean_absolute_error(y_true=y_test, y_pred=predictions)\nmetrics.mean_squared_error(y_true=y_test, y_pred=predictions)\nnp.sqrt(metrics.mean_squared_error(y_true=y_test, y_pred=predictions))\n\n# Check the R^2 score.\nmetrics.explained_variance_score(y_true=y_test, y_pred=predictions)\n\nlm.score(X=X_test, y=y_test)\n\n\n"
] |
[
[
"sklearn.metrics.explained_variance_score",
"pandas.Series",
"matplotlib.pyplot.scatter",
"sklearn.metrics.mean_absolute_error",
"sklearn.model_selection.train_test_split",
"pandas.DataFrame",
"sklearn.metrics.mean_squared_error",
"sklearn.linear_model.LinearRegression",
"sklearn.datasets.load_boston",
"matplotlib.pyplot.show"
]
] |
surajkothawade/mmdetection
|
[
"a148d8a9079c6d88ad6eddee929d577388c8182c"
] |
[
"mmdet/datasets/builder.py"
] |
[
"import copy\nimport platform\nimport random\nfrom functools import partial\n\nimport numpy as np\nfrom mmcv.parallel import collate\nfrom mmcv.runner import get_dist_info\nfrom mmcv.utils import Registry, build_from_cfg\nfrom torch.utils.data import DataLoader\n\nfrom .samplers import DistributedGroupSampler, DistributedSampler, GroupSampler, ActiveLearningSampler\n\nif platform.system() != 'Windows':\n # https://github.com/pytorch/pytorch/issues/973\n import resource\n rlimit = resource.getrlimit(resource.RLIMIT_NOFILE)\n hard_limit = rlimit[1]\n soft_limit = min(4096, hard_limit)\n resource.setrlimit(resource.RLIMIT_NOFILE, (soft_limit, hard_limit))\n\nDATASETS = Registry('dataset')\nPIPELINES = Registry('pipeline')\n\n\ndef _concat_dataset(cfg, default_args=None):\n from .dataset_wrappers import ConcatDataset\n ann_files = cfg['ann_file']\n img_prefixes = cfg.get('img_prefix', None)\n seg_prefixes = cfg.get('seg_prefix', None)\n proposal_files = cfg.get('proposal_file', None)\n separate_eval = cfg.get('separate_eval', True)\n\n datasets = []\n num_dset = len(ann_files)\n for i in range(num_dset):\n data_cfg = copy.deepcopy(cfg)\n # pop 'separate_eval' since it is not a valid key for common datasets.\n if 'separate_eval' in data_cfg:\n data_cfg.pop('separate_eval')\n data_cfg['ann_file'] = ann_files[i]\n if isinstance(img_prefixes, (list, tuple)):\n data_cfg['img_prefix'] = img_prefixes[i]\n if isinstance(seg_prefixes, (list, tuple)):\n data_cfg['seg_prefix'] = seg_prefixes[i]\n if isinstance(proposal_files, (list, tuple)):\n data_cfg['proposal_file'] = proposal_files[i]\n datasets.append(build_dataset(data_cfg, default_args))\n\n return ConcatDataset(datasets, separate_eval)\n\n\ndef build_dataset(cfg, default_args=None):\n from .dataset_wrappers import (ConcatDataset, RepeatDataset,\n ClassBalancedDataset)\n if isinstance(cfg, (list, tuple)):\n dataset = ConcatDataset([build_dataset(c, default_args) for c in cfg])\n elif cfg['type'] == 'ConcatDataset':\n dataset = ConcatDataset(\n [build_dataset(c, default_args) for c in cfg['datasets']],\n cfg.get('separate_eval', True))\n elif cfg['type'] == 'RepeatDataset':\n dataset = RepeatDataset(\n build_dataset(cfg['dataset'], default_args), cfg['times'])\n elif cfg['type'] == 'ClassBalancedDataset':\n dataset = ClassBalancedDataset(\n build_dataset(cfg['dataset'], default_args), cfg['oversample_thr'])\n elif isinstance(cfg.get('ann_file'), (list, tuple)):\n dataset = _concat_dataset(cfg, default_args)\n else:\n dataset = build_from_cfg(cfg, DATASETS, default_args)\n\n return dataset\n\n\ndef build_dataloader(dataset,\n samples_per_gpu,\n workers_per_gpu,\n num_gpus=1,\n dist=True,\n shuffle=True,\n seed=None,\n **kwargs):\n \"\"\"Build PyTorch DataLoader.\n\n In distributed training, each GPU/process has a dataloader.\n In non-distributed training, there is only one dataloader for all GPUs.\n\n Args:\n dataset (Dataset): A PyTorch dataset.\n samples_per_gpu (int): Number of training samples on each GPU, i.e.,\n batch size of each GPU.\n workers_per_gpu (int): How many subprocesses to use for data loading\n for each GPU.\n num_gpus (int): Number of GPUs. Only used in non-distributed training.\n dist (bool): Distributed training/test or not. Default: True.\n shuffle (bool): Whether to shuffle the data at every epoch.\n Default: True.\n kwargs: any keyword argument to be used to initialize DataLoader\n\n Returns:\n DataLoader: A PyTorch dataloader.\n \"\"\"\n #delta changes\n if 'indices_file' in kwargs:\n indicesFile= kwargs['indices_file']\n del kwargs['indices_file']\n else:\n indicesFile=None\n #end of delta changes\n rank, world_size = get_dist_info()\n if dist:\n # DistributedGroupSampler will definitely shuffle the data to satisfy\n # that images on each GPU are in the same group\n if shuffle:\n sampler = DistributedGroupSampler(\n dataset, samples_per_gpu, world_size, rank, seed=seed)\n else:\n sampler = DistributedSampler(\n dataset, world_size, rank, shuffle=False, seed=seed)\n batch_size = samples_per_gpu\n num_workers = workers_per_gpu\n #delta changes\n elif indicesFile:\n sampler = ActiveLearningSampler(dataset, indicesFile, samples_per_gpu) if shuffle else None\n batch_size = num_gpus * samples_per_gpu\n num_workers = num_gpus * workers_per_gpu\n #end of delta change\n else:\n sampler = GroupSampler(dataset, samples_per_gpu) if shuffle else None\n batch_size = num_gpus * samples_per_gpu\n num_workers = num_gpus * workers_per_gpu\n\n init_fn = partial(\n worker_init_fn, num_workers=num_workers, rank=rank,\n seed=seed) if seed is not None else None\n\n data_loader = DataLoader(\n dataset,\n batch_size=batch_size,\n sampler=sampler,\n num_workers=num_workers,\n collate_fn=partial(collate, samples_per_gpu=samples_per_gpu),\n pin_memory=False,\n worker_init_fn=init_fn,\n **kwargs)\n\n return data_loader\n\n\ndef worker_init_fn(worker_id, num_workers, rank, seed):\n # The seed of each worker equals to\n # num_worker * rank + worker_id + user_seed\n worker_seed = num_workers * rank + worker_id + seed\n np.random.seed(worker_seed)\n random.seed(worker_seed)\n"
] |
[
[
"numpy.random.seed"
]
] |
glennpow/glearn
|
[
"e50046cb76173668fec12c20b446be7457482528"
] |
[
"glearn/viewers/discrete_env_viewer.py"
] |
[
"import queue\nimport numpy as np\nfrom .advanced_viewer import AdvancedViewer\n\n\nclass DiscreteEnvViewer(AdvancedViewer):\n def __init__(self, config, **kwargs):\n super().__init__(config, **kwargs)\n\n def prepare(self, trainer):\n super().prepare(trainer)\n\n self.trainer.add_fetch(\"Q_values\", self.trainer.policy.Q)\n gamma = self.trainer.gamma\n\n # HACK - more generic way to set these...\n is_frozen = \"Frozen\" in trainer.env.name\n if is_frozen:\n from gym.envs.toy_text.frozen_lake import LEFT, DOWN, RIGHT, UP\n self.render_Q = True\n else:\n from gym.envs.toy_text.cliffwalking import LEFT, DOWN, RIGHT, UP\n self.render_Q = False\n self.LEFT, self.DOWN, self.RIGHT, self.UP = LEFT, DOWN, RIGHT, UP\n\n self.optimal_Q, self.optimal_A, self.optimal_V = self._calculate_optimal_QAV(gamma)\n self._add_QAV_maps()\n\n def _calculate_optimal_QAV(self, gamma):\n # begin with done states\n P = self.env.unwrapped.P\n naction = self.env.unwrapped.action_space.n\n Q = {s: np.full((naction), np.NINF) for s in P.keys()}\n target_rew = {s: np.zeros((naction)) for s in P.keys()}\n fifo = queue.Queue()\n rev_ts = {s: [] for s in P.keys()}\n for s, actions in P.items():\n for action, transitions in actions.items():\n for transition in transitions:\n prob, ns, rew, done = transition\n full_t = (s, action, *transition)\n\n target_rew[s][action] = rew\n\n rev_ts[ns].append(full_t)\n\n if done:\n Q[ns][:] = np.zeros((naction))\n if ns != s:\n fifo.put(full_t)\n\n # calculate optimal Q-values\n while not fifo.empty():\n s, action, prob, ns, rew, done = fifo.get()\n row = int(s / 12) # HACK\n col = int(s % 12) # HACK\n\n previous_states = rev_ts[s]\n if len(previous_states) == 0:\n # print(f\"Ignore unreachable state: s=({row},{col}) : {Q[s][action]}\")\n continue\n\n new_Q = target_rew[s][action] + gamma * np.amax(Q[ns])\n\n if new_Q > Q[s][action]:\n # print(f\"Process transition: s=({row},{col}) + a={action} : {Q[s][action]} := {new_Q}\")\n\n Q[s][action] = new_Q\n for rev_t in rev_ts[s]:\n fifo.put(rev_t)\n # else:\n # print(f\"Maintain transition: s=({row},{col}) + a={action} : {Q[s][action]} >= {new_Q}\")\n\n # calculate optimal actions and V-values\n A = {s: np.argmax(actions) for s, actions in Q.items()}\n V = {s: np.amax(actions) for s, actions in Q.items()}\n\n return Q, A, V\n\n def _add_QAV_maps(self):\n # calculate actual Q-map\n naction = self.env.unwrapped.action_space.n\n nrow, ncol = self.env.unwrapped.shape\n optimal_Q_map = np.zeros((nrow, ncol, naction))\n for row in range(nrow):\n for col in range(ncol):\n s = row * ncol + col\n for action in range(naction):\n optimal_Q_map[row, col, action] = self.optimal_Q[s][action]\n\n # render optimal AV-map\n self._add_AV_map_label(\"optimal-AV-map\", self.optimal_A, self.optimal_V, x=80, y=10)\n\n # render optimal Q-map\n if self.render_Q:\n self._add_map_label(\"optimal-Q-map\", optimal_Q_map, x=220, y=10)\n\n def prepare_render(self):\n # gather environment info\n naction = self.output.size\n nrow, ncol = self.env.unwrapped.shape\n\n # render ansi env output\n result = self.trainer.env_render_results\n if result is not None:\n self.add_label(\"map\", result, x=10, y=10, width=self.viewer.get_size()[0],\n multiline=True, font_name=\"Courier New\", font_size=8)\n\n # build predicted Q-value map\n Q_map = np.zeros((nrow, ncol, naction))\n A = {}\n V = {}\n for row in range(nrow):\n for col in range(ncol):\n # get state representation\n state = row * ncol + col\n\n # fetch Q-values for state\n results = self.trainer.run(\"Q_values\", {\"X\": [state]})\n Q_values = results[\"Q_values\"]\n\n # store Q-values for state\n Q_map[row, col, :] = Q_values\n A[state] = np.argmax(Q_values)\n V[state] = np.amax(Q_values)\n\n # render AV-map\n self._add_AV_map_label(\"AV-map\", A, V, x=80, y=210)\n\n # render Q-map\n if self.render_Q:\n self._add_map_label(\"Q-map\", Q_map, x=220, y=210)\n\n def _add_map_label(self, name, values, x, y):\n if len(values.shape) == 2:\n font_size = 12\n if values.dtype == np.float32 or values.dtype == np.float64:\n values = np.array([[f\"{v:.2f}\" for v in line] for line in values])\n map_str = \"\\n\".join([\" \".join(line) for line in values])\n elif len(values.shape) == 3:\n font_size = 10\n col_width = 16\n map_str = \"\"\n for line in values:\n qvs = [\"\"] * 3\n for v in line:\n qvs[0] += f\" {v[self.UP]:.2f}\".ljust(col_width)\n qvs[1] += f\"{v[self.LEFT]:.2f} <> {v[self.RIGHT]:.2f}\".ljust(col_width)\n qvs[2] += f\" {v[self.DOWN]:.2f}\".ljust(col_width)\n map_str += \"\\n\".join(qvs) + \"\\n\\n\"\n\n view_width = self.get_size()[0]\n self.add_label(name, map_str, x=x, y=y, width=view_width,\n multiline=True, font_name=\"Courier New\", font_size=font_size)\n\n def _add_AV_map_label(self, name, A, V, x, y):\n action_chars = {self.LEFT: \"<\", self.DOWN: \"v\", self.RIGHT: \">\", self.UP: \"^\"}\n\n nrow, ncol = self.env.unwrapped.shape\n A_map = np.empty((nrow, ncol), dtype=np.object)\n V_map = np.zeros((nrow, ncol))\n for row in range(nrow):\n for col in range(ncol):\n s = row * ncol + col\n A_map[row, col] = action_chars[A[s]]\n V_map[row, col] = V[s]\n\n AV_map = np.array([[f\"{A_map[r, c]}:{V_map[r, c]:.2f}\"\n for c in range(ncol)] for r in range(nrow)])\n self._add_map_label(name, AV_map, x=x, y=y)\n"
] |
[
[
"numpy.amax",
"numpy.full",
"numpy.argmax",
"numpy.array",
"numpy.zeros",
"numpy.empty"
]
] |
chatipat/ivac
|
[
"c4673a8b5e425bc1841415763190996794e48a1e"
] |
[
"src/ivac/nonlinear.py"
] |
[
"import numpy as np\nimport torch\nimport pytorch_lightning as pl\nfrom .linear import LinearVAC, LinearIVAC\n\n\nclass NonlinearIVAC:\n \"\"\"Solve nonlinear IVAC using a neural network basis.\n\n Parameters\n ----------\n minlag : int\n Minimum IVAC lag time in units of frames.\n maxlag : int, optional\n Maximum IVAC lag time (inclusive) in units of frames.\n If None, this is set to minlag.\n nevecs : int\n Number of eigenvectors (including the trivial eigenvector)\n to find.\n batch_size : int\n Number of samples to draw at each training iteration.\n val_batch_size : int, optional\n Number of samples to draw at each validation iteration.\n val_every : int, optional\n Number of training iterations between validation iterations.\n hidden_widths : list of int, optional\n Number of hidden features at each hidden layer.\n The length of this list is the number of hidden layers.\n activation : torch.nn.Module, optional\n Activation function to use in the neural network.\n batchnorm : bool, optional\n If True, use batch normalization in the neural network.\n standardize : bool, optional\n If True, remove the mean of the output\n and set its standard deviation to 1.\n score : str, optional\n Score function to maximize.\n This can currently be 'VAMP1' or 'VAMP2'.\n lr : float, optional\n Learning rate for optimization.\n patience : int, optional\n Patience parameter for early stopping.\n maxiter : int, optional\n Maximum number of optimization iterations to perform.\n dtype : torch.dtype, optional\n Data type to use for the neural network.\n device : torch.device, optional\n Device to use to optimize the neural network.\n linear_method : str, optional\n Method to use for solving linear IVAC\n using the optimized neural network basis set.\n Currently, 'direct' and 'fft' are supported.\n\n \"\"\"\n\n def __init__(\n self,\n minlag,\n maxlag=None,\n nevecs=None,\n batch_size=None,\n val_batch_size=None,\n val_every=1,\n hidden_widths=[],\n activation=torch.nn.Tanh,\n batchnorm=False,\n standardize=False,\n score=\"VAMP1\",\n lr=0.001,\n patience=None,\n maxiter=None,\n dtype=torch.float,\n device=\"cpu\",\n linear_method=\"direct\",\n ):\n if nevecs is None:\n raise ValueError(\"nevecs must be specified\")\n if batch_size is None:\n raise ValueError(\"batch_size must be specified\")\n if val_batch_size is None:\n val_batch_size = batch_size\n if maxiter is None:\n raise ValueError(\"maxiter must be specified\")\n\n self.minlag = minlag\n self.maxlag = maxlag\n self.nevecs = nevecs\n self.batch_size = batch_size\n self.val_batch_size = val_batch_size\n self.val_every = val_every\n self.hidden_widths = hidden_widths\n self.activation = activation\n self.batchnorm = batchnorm\n self.standardize = standardize\n self.score = score\n self.lr = lr\n self.patience = patience\n self.maxiter = maxiter\n self.dtype = dtype\n self.device = device\n\n if maxlag is None:\n self.linear = LinearVAC(minlag, addones=True)\n else:\n self.linear = LinearIVAC(\n minlag, maxlag, addones=True, method=linear_method\n )\n\n def _make_dataloader(self, trajs, batch_size):\n \"\"\"Prepare the data for training.\"\"\"\n dataset = TimeLaggedPairDataset(\n trajs,\n batch_size,\n self.minlag,\n self.maxlag,\n dtype=self.dtype,\n device=self.device,\n )\n return torch.utils.data.DataLoader(dataset, batch_size=None)\n\n def fit(self, train_trajs, val_trajs=None, save_dir=None):\n \"\"\"Train the neural network using the input trajectories.\n\n Parameters\n ----------\n train_trajs : list of (n_frames[i], n_features)\n Featurized trajectories for the training dataset.\n val_trajs : list of (n_frames[j], n_features), optional\n Featurized trajectories for the validation dataset.\n These do not need to have the same number of frames\n as the training trajectories.\n If None, use the training data for validation.\n save_dir : str, optional\n Directory for saving training output.\n Uses the current directory by default.\n\n \"\"\"\n if val_trajs is None:\n val_trajs = train_trajs\n train_dataloader = self._make_dataloader(train_trajs, self.batch_size)\n val_dataloader = self._make_dataloader(val_trajs, self.val_batch_size)\n\n self.basis = NonlinearBasis(\n nfeatures=np.shape(train_trajs[0])[-1],\n nbasis=self.nevecs - 1,\n hidden_widths=self.hidden_widths,\n activation=self.activation,\n batchnorm=self.batchnorm,\n standardize=self.standardize,\n score=self.score,\n lr=self.lr,\n )\n\n if self.patience is None:\n early_stop_callback = False\n else:\n early_stop_callback = pl.callbacks.EarlyStopping(\n patience=self.patience, mode=\"min\"\n )\n\n if self.device == \"cpu\":\n gpus = 0\n elif self.device == \"cuda\":\n gpus = 1\n else:\n _, gpu_id = self.device.split(\":\")\n gpus = [int(gpu_id)]\n precision = {torch.float16: 16, torch.float32: 32, torch.float64: 64}\n\n trainer = pl.Trainer(\n val_check_interval=1,\n check_val_every_n_epoch=self.val_every,\n default_root_dir=save_dir,\n early_stop_callback=early_stop_callback,\n gpus=gpus,\n limit_train_batches=1,\n limit_val_batches=1,\n max_epochs=self.maxiter,\n precision=precision[self.dtype],\n )\n trainer.fit(self.basis, train_dataloader, val_dataloader)\n\n self.linear.fit(self.transform_basis(train_trajs))\n self.evals = self.linear.evals\n self.its = self.linear.its\n\n def transform(self, trajs):\n \"\"\"Compute IVAC eigenvectors at each frame of the trajectories.\n\n Parameters\n ----------\n trajs : list of (n_frames[i], n_features) array-like\n List of featurized trajectories.\n\n Returns\n -------\n list of (n_frames[i], n_evecs) ndarray\n IVAC eigenvectors at each frame of the trajectories.\n\n \"\"\"\n return self.linear.transform(self.transform_basis(trajs))\n\n def transform_basis(self, trajs):\n \"\"\"Apply the nonlinear combinations to the input features.\n\n Parameters\n ----------\n trajs : list of (n_frames[i], n_features) array-like\n List of featurized trajectories.\n\n Returns\n -------\n list of (n_frames[i], n_evecs - 1) ndarray\n Nonlinear combinations of input features.\n\n \"\"\"\n features = []\n for traj in trajs:\n traj = torch.as_tensor(traj, dtype=self.dtype, device=self.device)\n features.append(self.basis(traj).detach().cpu().numpy())\n return features\n\n\nclass NonlinearBasis(pl.LightningModule):\n \"\"\"Neural network for taking nonlinear combinations of features.\n\n This is meant to be used with a PyTorch Lightning Trainer.\n\n Parameters\n ----------\n nfeatures : int\n Number of input features.\n hidden_widths : list of int, optional\n Number of hidden features at each hidden layer.\n The length of this list is the number of hidden layers.\n activation : torch.nn.Module, optional\n Activation function to use in the neural network.\n batchnorm : bool, optional\n If True, use batch normalization in the neural network.\n standardize : bool, optional\n If True, remove the mean of the output\n and set its standard deviation to 1.\n score : str, optional\n Score function to maximize.\n This can currently be 'VAMP1' or 'VAMP2'.\n lr : float, optional\n Learning rate for optimization.\n\n \"\"\"\n\n def __init__(\n self,\n nfeatures,\n nbasis,\n hidden_widths=[],\n activation=torch.nn.Tanh,\n batchnorm=False,\n standardize=False,\n score=\"VAMP1\",\n lr=0.001,\n ):\n super().__init__()\n\n layers = []\n last_features = nfeatures\n for hidden_features in hidden_widths:\n layers.append(torch.nn.Linear(last_features, hidden_features))\n if batchnorm:\n layers.append(torch.nn.BatchNorm1d(hidden_features))\n layers.append(activation())\n last_features = hidden_features\n layers.append(torch.nn.Linear(last_features, nbasis))\n if standardize:\n layers.append(torch.nn.BatchNorm1d(nbasis, affine=False))\n self.model = torch.nn.Sequential(*layers)\n\n if score == \"VAMP1\":\n self.score = VAMPScore(score=1, addones=True)\n elif score == \"VAMP2\":\n self.score = VAMPScore(score=2, addones=True)\n else:\n raise ValueError(\"score must be 'VAMP1' or 'VAMP2'\")\n\n self.lr = lr\n\n def forward(self, x):\n \"\"\"Apply the nonlinear combinations to input features.\"\"\"\n return self.model(x)\n\n def configure_optimizers(self):\n \"\"\"Configure the optimizer for training.\"\"\"\n return torch.optim.AdamW(self.parameters(), lr=self.lr)\n\n def training_step(self, batch, batch_idx):\n \"\"\"Compute the training loss.\"\"\"\n x, y = batch\n xy = torch.cat([x, y])\n xy = self(xy)\n x, y = xy[: len(x)], xy[len(x) :]\n loss = -self.score(x, y)\n result = pl.TrainResult(minimize=loss)\n result.log(\"train_loss\", loss)\n return result\n\n def validation_step(self, batch, batch_idx):\n \"\"\"Compute the validation loss.\"\"\"\n x, y = batch\n xy = torch.cat([x, y])\n xy = self(xy)\n x, y = xy[: len(x)], xy[len(x) :]\n loss = -self.score(x, y)\n result = pl.EvalResult(checkpoint_on=loss, early_stop_on=loss)\n result.log(\"val_loss\", loss)\n return result\n\n\nclass TimeLaggedPairDataset(torch.utils.data.IterableDataset):\n r\"\"\"Dataset yielding time lagged pairs from trajectories.\n\n For a single trajectory :math:`x_0, x_1, \\ldots, x_{T-1}`,\n this class samples pairs :math:`(x_t, x_{t+\\tau})`.\n For each pair, :math:`\\tau` is uniformly drawn from the set\n {minlag, minlag + 1, ..., maxlag}.\n\n Parameters\n ----------\n trajs : list of (n_frames[i], n_features) array-like\n List of featurized trajectories.\n num : int\n Number of pairs to sample and return at each iteration.\n minlag : int\n Minimum lag time in units of frames.\n maxlag : int, optional\n Maximum lag time in units of frames.\n If None, this is set to the minimum lag time.\n dtype : torch.dtype\n Data type of output tensor.\n device : torch.device\n Device of output tensor.\n\n \"\"\"\n\n def __init__(\n self,\n trajs,\n num,\n minlag,\n maxlag=None,\n dtype=torch.float32,\n device=\"cpu\",\n ):\n super().__init__()\n self.sampler = TimeLaggedPairSampler(trajs, dtype=dtype, device=device)\n self.num = num\n self.minlag = minlag\n self.maxlag = maxlag\n\n def __iter__(self):\n \"\"\"Yields batches of sampled time lagged pairs indefinitely.\n\n Yields\n -------\n x, y : (n_samples, n_features) torch.Tensor\n Time lagged pairs.\n\n \"\"\"\n while True:\n yield self.sampler(self.num, self.minlag, self.maxlag)\n\n\nclass TimeLaggedPairSampler:\n r\"\"\"Sample time lagged pairs from trajectories.\n\n For a single trajectory :math:`x_0, x_1, \\ldots, x_{T-1}`,\n this class samples pairs :math:`(x_t, x_{t+\\tau})`.\n For each pair, :math:`\\tau` is uniformly drawn from the set\n {minlag, minlag + 1, ..., maxlag}.\n\n To draw n_samples pairs from trajectories trajs:\n\n .. code-block::\n\n sampler = TimeLaggedPairSampler(trajs)\n x, y = sampler(n_samples, minlag, maxlag)\n\n Parameters\n ----------\n trajs : list of (n_frames[i], n_features) array-like\n List of featurized trajectories.\n dtype : torch.dtype\n Data type of output tensor.\n device : torch.device\n Device of output tensor.\n\n \"\"\"\n\n def __init__(\n self,\n trajs,\n dtype=torch.float32,\n device=\"cpu\",\n ):\n self.dtype = dtype\n self.device = device\n\n features = []\n maxlags = []\n for traj in trajs:\n traj = torch.as_tensor(traj, dtype=dtype, device=device)\n features.append(traj)\n maxlags.append(torch.arange(len(traj) - 1, -1, -1, device=device))\n features = torch.cat(features, dim=0)\n maxlags = torch.cat(maxlags)\n lags = torch.arange(torch.max(maxlags) + 1, device=device)\n self.features = features\n self.indices = torch.argsort(maxlags)\n self.offsets = torch.bucketize(lags, maxlags[self.indices], right=True)\n self.lengths = len(features) - self.offsets\n\n def __call__(self, num, minlag, maxlag=None):\n \"\"\"Sample time lagged pairs from trajectories.\n\n Parameters\n ----------\n num : int\n Number of pairs to sample.\n minlag : int\n Minimum lag time in units of frames.\n maxlag : int, optional\n Maximum lag time in units of frames.\n If None, this is set to the minimum lag time.\n\n Returns\n -------\n x, y : (n_samples, n_features) torch.Tensor\n Time lagged pairs.\n\n \"\"\"\n if maxlag is None:\n maxlag = minlag\n lags = torch.randint(minlag, maxlag + 1, (num,), device=self.device)\n i = self.offsets[lags] + torch.floor(\n self.lengths[lags] * torch.rand(num, device=self.device)\n ).to(dtype=lags.dtype)\n ix = self.indices[i]\n iy = ix + lags\n return self.features[ix], self.features[iy]\n\n\nclass VAMPScore:\n r\"\"\"Compute reversible VAMP scores.\n\n The VAMP-:math:`k` score is defined as\n\n .. math::\n\n \\sum_i \\lvert \\lambda_i \\rvert^k\n\n where :math:`\\lambda_i` are the eigenvalues of the estimated\n (integrated) transition operator.\n\n This class assumes that dynamics are reversible and that the\n constant feature is contained within the feature space.\n If the constant feature is not within the feature space,\n center=True or addones=True (or both) should be set.\n This class can be used as\n\n .. code-block::\n\n score_fn = VAMPScore(score=1, addones=True)\n score = score_fn(x, y)\n\n Parameters\n ----------\n score : int, optional\n VAMP score to compute. Currently, only 1 and 2 are supported.\n center : bool, optional\n If True, remove the mean from each feature before calculating\n the VAMP score, and adjust the resulting score appropriately.\n addones : bool, optional\n If True, adds a feature of all ones before computing the\n VAMP score.\n minlag, maxlag, lagstep : int, optional\n IVAC parameters. If specified, scales the VAMP score to conform\n with the integrated (rather than averaged) covariance matrix.\n\n \"\"\"\n\n def __init__(\n self,\n score=1,\n center=False,\n addones=False,\n minlag=None,\n maxlag=None,\n lagstep=1,\n ):\n self.score = score\n self.center = center\n self.addones = addones\n self.minlag = minlag\n self.maxlag = maxlag\n self.lagstep = lagstep\n\n self._factor = 1.0\n if minlag is not None or maxlag is not None:\n if minlag is None or maxlag is None:\n raise ValueError(\"both minlag and maxlag must be specified\")\n if (maxlag - minlag) % lagstep != 0:\n raise ValueError(\n \"lag time interval must be a multiple of lagstep\"\n )\n self._factor = ((maxlag - minlag) // lagstep + 1.0) ** score\n\n def __call__(self, x, y):\n \"\"\"Evaluate VAMP score on input features.\n\n Parameters\n ----------\n x, y : (n_frames, n_features) torch.Tensor\n Tensor of features.\n\n Returns\n -------\n () torch.Tensor\n VAMP score.\n\n \"\"\"\n if self.center:\n mean = 0.5 * (torch.mean(x, dim=0) + torch.mean(y, dim=0))\n x = x - mean\n y = y - mean\n if self.addones:\n x = _addones(x)\n y = _addones(y)\n\n c0 = x.t() @ x + y.t() @ y\n ct = x.t() @ y + y.t() @ x\n op = torch.inverse(c0) @ ct\n if self.score == 1:\n score = torch.trace(op)\n elif self.score == 2:\n score = torch.trace(op @ op)\n else:\n raise ValueError(\"score must be 1 or 2\")\n\n if self.center and not self.addones:\n score += 1.0\n return self._factor * score\n\n\ndef _addones(x):\n \"\"\"Add a feature of all ones.\n\n Parameters\n ----------\n x : (n_frames, n_features) torch.Tensor\n Tensor of features.\n\n Returns\n -------\n (n_frames, n_features + 1) torch.Tensor\n Input tensor with an additional feature of all ones.\n\n \"\"\"\n ones = torch.ones(len(x), 1, dtype=x.dtype, device=x.device)\n return torch.cat([ones, x], dim=-1)\n"
] |
[
[
"torch.nn.Sequential",
"torch.nn.BatchNorm1d",
"torch.mean",
"torch.randint",
"torch.max",
"torch.cat",
"torch.trace",
"torch.utils.data.DataLoader",
"torch.inverse",
"torch.nn.Linear",
"numpy.shape",
"torch.rand",
"torch.argsort",
"torch.bucketize",
"torch.as_tensor"
]
] |
criteo-dexter/deepr
|
[
"4de9cb8afc09cb3d2f7c42da248a966bfea5fc83"
] |
[
"deepr/layers/lstm.py"
] |
[
"# pylint: disable=no-value-for-parameter,unexpected-keyword-arg\n\"\"\"LSTM layers.\"\"\"\n\nimport tensorflow as tf\n\nfrom deepr.layers import base\n\n\[email protected](n_in=2, n_out=3)\ndef LSTM(tensors, num_units: int, bidirectional: bool = False, **kwargs):\n \"\"\"LSTM layer.\"\"\"\n words, nwords = tensors\n t = tf.transpose(words, perm=[1, 0, 2])\n lstm_cell_fw = tf.contrib.rnn.LSTMBlockFusedCell(num_units=num_units, **kwargs)\n outputs_fw, (hidden_fw, output_fw) = lstm_cell_fw(t, dtype=tf.float32, sequence_length=nwords)\n\n if bidirectional:\n lstm_cell_bw = tf.contrib.rnn.LSTMBlockFusedCell(num_units=num_units, **kwargs)\n lstm_cell_bw = tf.contrib.rnn.TimeReversedFusedRNN(lstm_cell_bw)\n outputs_bw, (hidden_bw, output_bw) = lstm_cell_bw(t, dtype=tf.float32, sequence_length=nwords)\n outputs = tf.concat([outputs_fw, outputs_bw], axis=-1)\n hidden = tf.concat([hidden_fw, hidden_bw], axis=-1)\n output = tf.concat([output_fw, output_bw], axis=-1)\n else:\n outputs = outputs_fw\n hidden = hidden_fw\n output = output_fw\n\n outputs = tf.transpose(outputs, perm=[1, 0, 2])\n return (outputs, hidden, output)\n"
] |
[
[
"tensorflow.concat",
"tensorflow.contrib.rnn.TimeReversedFusedRNN",
"tensorflow.contrib.rnn.LSTMBlockFusedCell",
"tensorflow.transpose"
]
] |
wonderseen/OVC-MMT
|
[
"b982038ea1295cc038b8dcbca11aa81d318f7a49"
] |
[
"OVC_train.py"
] |
[
"'''\nOur implementation of our proposed OVC refers to the original data pipeline of VAG-NMT\nand modifications were done, including:\n1. Preprocess all object-level features and detect translation-relevant/irrelevant objects\n in Multi30K, which needs lots of prep work, which costs around 1-2 days.\n2. Preprocess all vision-weighted weights using pretrained LM checkpoints in the CPU mode,\n which costs about several hours.\n3. Modificate the data pipeline to match the data flow of several OVC variants.\n4. Rewrite our own OVC and its variants.\n5. Each run for training a OVC model costs around 4 hours on 2 2080Ti GPUs.\n\n\n## To run the model using the shell command\n=> [activate the Pytorch enviroments, particularly we used Pytorch-1.2]\n=> . run_ovc_training.sh\n\n## To test the model using a better beam_size using the shell command\n=> . run_ovc_evaluation.sh.\n\n'''\n\nimport torch\nfrom torch import optim, nn\nimport time\nimport argparse\nimport numpy as np\nimport os\nfrom preprocessing import *\nfrom machine_translation_vision.meteor.meteor import Meteor\nfrom machine_translation_vision.user_loss import *\nfrom machine_translation_vision.models import NMT_AttentionImagine_Seq2Seq_Beam_V16 as OVC\nfrom train import *\nfrom bleu import *\n\n\nstandard_exp = True # False: source-degradation, True: standard\nmix = False # For mixed reimplementation\nportion = 1.0 if mix else 0.0 \n\n\nuse_cuda = torch.cuda.is_available()\nassert use_cuda, \"pls use CUDA.\"\n\n## Initialize the terms from argparse\nPARSER = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nPARSER.add_argument('--data_path', required=True, help='path to multimodal machine translation dataset')\nPARSER.add_argument('--trained_model_path', required=True, help='path to save the trained model and output')\nPARSER.add_argument('--sr', type=str, required=True, help='the source language')\nPARSER.add_argument('--tg', type=str, required=True, help='the target language')\n# Network Structure\nPARSER.add_argument('--imagine_attn', type=str, default='dot', help='attntion type for imagine_attn module. Options can be dot|mlp')\nPARSER.add_argument('--activation_vse', action='store_false', help='whether using tanh after embedding layers')\nPARSER.add_argument('--embedding_size', type=int, default=256, help='embedding layer size for both encoder and decoder')\nPARSER.add_argument('--hidden_size', type=int, default=512, help='hidden state size for both encoder and decoder')\nPARSER.add_argument('--shared_embedding_size', type=int, default=512, help='the shared space size to project decoder/encoder hidden state and image features')\nPARSER.add_argument('--n_layers', type=int, default=1, help='number of stacked layer for encoder and decoder')\nPARSER.add_argument('--tied_emb', action='store_false', help='whether to tie the embdding layers weights to the output layer')\n\n# Dropout\nPARSER.add_argument('--dropout_im_emb', type=float, default=0.2, help='the dropout applied to im_emb layer')\nPARSER.add_argument('--dropout_txt_emb', type=float, default=0.4, help='the dropout applied to the text_emb layer')\nPARSER.add_argument('--dropout_rnn_enc', type=float, default=0.0, help='the dropout applied to the rnn encoder layer')\nPARSER.add_argument('--dropout_rnn_dec', type=float, default=0.0, help='the dropout applied to the rnn decoder layer')\nPARSER.add_argument('--dropout_emb', type=float, default=0.3, help='the dropout applied ot the embedding layer of encoder embedidng state')\nPARSER.add_argument('--dropout_ctx', type=float, default=0.5, help='the dropout applied to the context vectors of encoder')\nPARSER.add_argument('--dropout_out', type=float, default=0.5, help='the dropout applied to the output layer of the decoder')\n\n# Training Settingx\nPARSER.add_argument('--batch_size', type=int, default=32, help='batch size during training')\nPARSER.add_argument('--eval_batch_size', type=int, default=32, help='batch size during evaluation')\nPARSER.add_argument('--learning_rate_mt', type=float, default=0.001, help='learning rate for machien translation task')\nPARSER.add_argument('--learning_rate_vse', type=float, default=0., help='learning rate for VSE learning')\nPARSER.add_argument('--weight_decay', type=float, default=0.00001, help='weight decay applied to optimizer')\nPARSER.add_argument('--loss_w', type=float, default=0.9, help='is using the mixed objective, this assigns the weight for mt and vse objective function separate.')\nPARSER.add_argument('--p_mt', type=float, default=0.9, help='The probability to run machine translation task instead of vse task, when we train the tasks separately')\nPARSER.add_argument('--beam_size', type=int, default=8, help='The beam size for beam search')\nPARSER.add_argument('--n_epochs', type=int, default=100, help='maximum number of epochs to run')\nPARSER.add_argument('--print_every', type=int, default=100, help='print frequency')\nPARSER.add_argument('--eval_every', type=int, default=1000, help='evaluation frequency')\nPARSER.add_argument('--save_every', type=int, default=10000, help='model save frequency')\nPARSER.add_argument('--vse_separate', action='store_true', help='with mixed opjective functioin, do we apply different learning rate for different modules')\nPARSER.add_argument('--vse_loss_type', type=str, default='pairwise', help='the type of vse loss which can be picked from pairwise|imageretrieval')\nPARSER.add_argument('--teacher_force_ratio', type=float, default=0.8, help='whether to apply teacher_force_ratio during trianing')\nPARSER.add_argument('--clip', type=float, default=1.0, help='gradient clip applied duing optimization')\nPARSER.add_argument('--margin_size', type=float, default=0.1, help='default margin size applied to vse learning loss')\nPARSER.add_argument('--patience', type=int, default=10, help='early_stop_patience')\nPARSER.add_argument('--init_split', type=float, default=0.5, help='init_split_ratio to initialize the decoder')\n\n## Get all the argument\nARGS = PARSER.parse_args()\n\n## Helper Functions to Print Time Elapsed and Estimated Time Remaining, give the current time and progress\ndef as_minutes(s):\n m = math.floor(s / 60)\n s -= m * 60\n return '%dm %ds' % (m, s)\n\n\ndef time_since(since, percent):\n now = time.time()\n s = now - since\n es = s / (percent)\n rs = es - s\n return '%s (- %s)' % (as_minutes(s), as_minutes(rs))\n\n\n############################################################# Load the Dataset #######################################################\nMAX_LENGTH = 80 # abandon any sentence that is longer than this length\ndata_path = ARGS.data_path\ntrained_model_output_path = ARGS.trained_model_path\nsource_language = ARGS.sr\ntarget_language = ARGS.tg\nBPE_dataset_suffix = '.norm.tok.lc'\ndataset_suffix = '.norm.tok.lc'\ndataset_im_suffix = '.norm.tok.lc.10000bpe_ims'\n\n## Initilalize a Meteor Scorer\nMeteor_Scorer = Meteor(target_language)\n\n## Create the directory for the trained_model_output_path\nif not os.path.isdir(trained_model_output_path):\n os.mkdir(trained_model_output_path)\n\n## weights of Lv for each token\nif source_language != 'en':\n vi_suffix = '.obj2' + target_language\nelse:\n vi_suffix = '.' + source_language + '2' + target_language\n\n## experiment type\nif standard_exp:\n val = 'val'\n test = 'test'\n train = 'train'\n source_presuffix = '.10000bpe.'\nelse: # deep mask\n val = 'val'\n test = 'val'\n train = 'train'\n back_source_language = source_language\n source_language = source_language + '.ambiguous'\n source_presuffix = '.'\n\n## Load the training dataset\ntrain_source = load_data(os.path.join(data_path, f\"{train}{BPE_dataset_suffix}{source_presuffix}{source_language}\"))\ntrain_target = load_data(os.path.join(data_path, f\"{train}{BPE_dataset_suffix}.10000bpe.{target_language}\"))\ntrain_target_VI = load_VI(os.path.join(data_path, 'VI', f\"{train}.{target_language}{vi_suffix}\"), train_target)\n\nif mix:\n additional_number = int(len(train_source) * portion)\n additonal_train_source = load_data(os.path.join(data_path, f\"{train}{BPE_dataset_suffix}{source_presuffix}{back_source_language}\"))\n additonal_train_target = load_data(os.path.join(data_path, f\"{train}{BPE_dataset_suffix}.10000bpe.{target_language}\"))\n additonal_train_target_VI = load_VI(os.path.join(data_path, 'VI', f\"{train}.{target_language}{vi_suffix}\"), train_target)\n train_source = train_source[:additional_number] + additonal_train_source\n train_target = train_target[:additional_number] + additonal_train_target\n train_target_VI = train_target_VI[:additional_number] + additonal_train_target_VI\nprint(f\"The size of Training Source and Training Target is: {len(train_source)} <=> {len(train_target)}\")\n\n## Load the validation dataset\nval_source = load_data(os.path.join(data_path, f\"{val}{BPE_dataset_suffix}{source_presuffix}{source_language}\"))\nval_target = load_data(os.path.join(data_path, f\"{val}{BPE_dataset_suffix}.10000bpe.{target_language}\"))\n\nval_target_VI = load_VI(os.path.join(data_path, 'VI', f\"{val}.{target_language}{vi_suffix}\"), val_target)\nprint(f\"The size of Validation Source and Validation Target is: {len(val_source)} <=> {len(val_target)}\")\n\n## Load the test dataset\ntest_source = load_data(os.path.join(data_path, f\"{test}{BPE_dataset_suffix}{source_presuffix}{source_language}\"))\ntest_target = load_data(os.path.join(data_path, f\"{test}{BPE_dataset_suffix}.10000bpe.{target_language}\"))\ntest_target_VI = load_VI(os.path.join(data_path, 'VI', f\"{test}.{target_language}{vi_suffix}\"), test_target)\nprint(f\"The size of Test Source and Test Target is: {len(test_source)} <=> {len(test_target)}\")\n\n## Load the original validation dataset\nval_ori_source = load_data(os.path.join(data_path, f\"{val}{dataset_suffix}.{source_language}\"))\nval_ori_target = load_data(os.path.join(data_path, f\"{val}{dataset_suffix}.{target_language}\"))\n\n## Load the original test dataset\ntest_ori_source = load_data(os.path.join(data_path, f\"{test}{dataset_suffix}.{source_language}\"))\ntest_ori_target = load_data(os.path.join(data_path, f\"{test}{dataset_suffix}.{target_language}\"))\n\n## Creating List of pairs in the format of [[en_1, de_1], [en_2, de_2], ....[en_3, de_3]]\ntrain_data = [[x.strip(), y.strip(), vi] for x, y, vi in zip(train_source, train_target, train_target_VI)]\nval_data = [[x.strip(), y.strip(), vi] for x, y, vi in zip(val_source, val_target, val_target_VI)]\ntest_data = [[x.strip(), y.strip(), vi] for x, y, vi in zip(test_source, test_target, test_target_VI)]\n\n## Creating List of pairs in the format of [[en_1, de_1], [en_2, de_2], ....[en_3, de_3]] for original data\nval_ori_data = [[x.strip(), y.strip()] for x, y in zip(val_ori_source, val_ori_target)]\ntest_ori_data = [[x.strip(), y.strip()] for x, y in zip(test_ori_source, test_ori_target)]\n\n\n## Filter the data\ntrain_data = data_filter(train_data, MAX_LENGTH)\nval_data = data_filter(val_data, MAX_LENGTH)\ntest_data = data_filter(test_data, MAX_LENGTH)\n\n## Filter the original data\nval_ori_data = data_filter(val_ori_data, MAX_LENGTH)\ntest_ori_data = data_filter(test_ori_data, MAX_LENGTH)\n\nprint(f\"The size of Training Data after filtering: {len(train_data)}\")\nprint(f\"The size of Val Data after filtering: {len(val_data)}\")\nprint(f\"The size of Test Data after filtering: {len(test_data)}\")\n\n## Load the Vocabulary File and Create Word2Id and Id2Word dictionaries for translation\nvocab_source = load_data(os.path.join(data_path, f'vocab.{source_language}')) if not mix \\\n else load_data(os.path.join(data_path, f'vocab.{back_source_language}.mix')) \nvocab_target = load_data(os.path.join(data_path, f'vocab.{target_language}'))\n\n## Construct the source_word2id, source_id2word, target_word2id, target_id2word dictionaries\ns_word2id, s_id2word = construct_vocab_dic(vocab_source)\nt_word2id, t_id2word = construct_vocab_dic(vocab_target)\n\nprint(\"The vocabulary size for soruce language: {}\".format(len(s_word2id)))\nprint(\"The vocabulary size for target language: {}\".format(len(t_word2id)))\n\n## Generate Train, Val and Test Indexes pairs\ntrain_data_index = create_data_index_VI(train_data, s_word2id, t_word2id)\nval_data_index = create_data_index_VI(val_data, s_word2id, t_word2id)\ntest_data_index = create_data_index_VI(test_data, s_word2id, t_word2id)\n\nval_y_ref = [[d[1].split()] for d in val_ori_data]\ntest_y_ref = [[d[1].split()] for d in test_ori_data]\n\n## Define val_y_ref_meteor and test_y_ref_meteor\nval_y_ref_meteor = dict((key, [value[1]]) for key, value in enumerate(val_ori_data))\ntest_y_ref_meteor = dict((key, [value[1]]) for key, value in enumerate(test_ori_data))\n\n## Load the Vision Features\ntrain_im_feats = np.load(os.path.join(data_path, train+dataset_im_suffix+'.npy'))\nif mix: train_im_feats = np.concatenate((train_im_feats[:additional_number], train_im_feats), axis=0)\nval_im_feats = np.load(os.path.join(data_path, val+dataset_im_suffix+'.npy'))\ntest_im_feats = np.load(os.path.join(data_path, test+dataset_im_suffix+'.npy'))\n\n## Load the bottom-up and top-down attention vision features\n# train_bta_im_feats = np.load(os.path.join(data_path, train+dataset_im_suffix+'_bta_sort_with_original_similarity.npy'),\ntrain_bta_im_feats = np.load(os.path.join(data_path, train+dataset_im_suffix+'_bta_sort.npy'),\n allow_pickle=True)\nif mix: train_bta_im_feats = np.concatenate((train_bta_im_feats[:additional_number], train_bta_im_feats), axis=0)\nval_bta_im_feats = np.load(os.path.join(data_path, val+dataset_im_suffix+'_bta_sort.npy'),\n allow_pickle=True)\ntest_bta_im_feats = np.load(os.path.join(data_path, test+dataset_im_suffix+'_bta_sort.npy'),\n allow_pickle=True)\n\n## Verify the size of the train_im_features\nprint(\"Training Image Feature Size is: {}\".format(train_im_feats.shape))\nprint(\"Validation Image Feature Size is: {}\".format(val_im_feats.shape))\nprint(\"Testing Image Feature Size is: {}\".format(test_im_feats.shape))\nassert train_bta_im_feats.shape[0] == train_im_feats.shape[0], (train_bta_im_feats.shape, train_im_feats.shape)\nassert val_bta_im_feats.shape[0] == val_im_feats.shape[0], (val_bta_im_feats.shape, val_im_feats.shape)\nassert test_bta_im_feats.shape[0] == test_im_feats.shape[0], (test_bta_im_feats.shape, test_im_feats.shape)\n\n############################## Define Model and Training Structure ##################################\n## Network Structure\nimagine_attn = ARGS.imagine_attn\nactivation_vse = ARGS.activation_vse\nembedding_size = ARGS.embedding_size\nhidden_size = ARGS.hidden_size\nshared_embedding_size = ARGS.shared_embedding_size\nn_layers = ARGS.n_layers\ntied_emb = ARGS.tied_emb\n\n## Dropout\ndropout_im_emb = ARGS.dropout_im_emb\ndropout_txt_emb = ARGS.dropout_txt_emb\ndropout_rnn_enc = ARGS.dropout_rnn_enc\ndropout_rnn_dec = ARGS.dropout_rnn_dec\ndropout_emb = ARGS.dropout_emb\ndropout_ctx = ARGS.dropout_ctx\ndropout_out = ARGS.dropout_out\n\n## Training Setting\nbatch_size = ARGS.batch_size\neval_batch_size = ARGS.eval_batch_size\nbatch_num = math.floor(len(train_data_index) / batch_size)\nlearning_rate = ARGS.learning_rate_mt\nweight_decay = ARGS.weight_decay\nloss_w= ARGS.loss_w\nbeam_size = ARGS.beam_size\nn_epochs = ARGS.n_epochs\nprint_every = ARGS.print_every\neval_every = ARGS.eval_every\nsave_every = ARGS.save_every\nvse_separate = ARGS.vse_separate\nvse_loss_type = ARGS.vse_loss_type\n\n## Define the teacher force_ratio\nteacher_force_ratio = ARGS.teacher_force_ratio\nclip = ARGS.clip\n\n## Define the margin size\nmargin_size = ARGS.margin_size\npatience = ARGS.patience\n\n## Initialize models\ninput_size = len(s_word2id) + 1\noutput_size = len(t_word2id) + 1\n\n## Definet eh init_split\ninit_split = ARGS.init_split\n\n## Define the model\nimagine_model = OVC(input_size, \n output_size,\n train_im_feats.shape[1],\n train_bta_im_feats.shape[2],\n embedding_size, \n embedding_size, \n hidden_size, \n shared_embedding_size, \n loss_w, \n activation_vse=activation_vse, \n attn_model=imagine_attn, \n dropout_ctx=dropout_ctx, \n dropout_emb=dropout_emb, \n dropout_out=dropout_out, \n dropout_rnn_enc=dropout_rnn_enc, \n dropout_rnn_dec=dropout_rnn_dec, \n dropout_im_emb=dropout_im_emb, \n dropout_txt_emb=dropout_txt_emb, \n tied_emb=tied_emb,\n init_split=init_split)\n\nif use_cuda: imagine_model.cuda()\n## Use Multiple GPUs if they are available\n\"\"\"\nif torch.cuda.device_count() > 1:\n print(\"Let's use\", torch.cuda.device_count(), \"GPUs!\")\n baseline_model = nn.DataParallel(baseline_model)\n\"\"\"\n\n## Define the loss criterion\nvocab_mask = torch.ones(output_size)\nvocab_mask[0] = 0\nif use_cuda:\n vocab_mask = vocab_mask.cuda()\n\n# criterion_mt = FocalLoss(reduction='none', with_logits=False)#, smooth_eps=0.1)\ncriterion_mt = nn.NLLLoss(weight=vocab_mask, reduce=False)\nif use_cuda: criterion_mt = criterion_mt.cuda()\n\n# criterion_vse = nn.HingeEmbeddingLoss(margin=margin_size, size_average=False)\n# if vse_loss_type == \"pairwise\":\n# criterion_vse = PairwiseRankingLoss(margin=margin_size)\n# if vse_loss_type == \"imageretrieval\":\n# criterion_vse = ImageRetrievalRankingLoss(margin=margin_size)\n# if use_cuda: criterion_vse = criterion_vse.cuda()\ncriterion_vse = None\n \n\n\nif not vse_separate:\n ## Define the optimizer\n # optimizer = optim.Adam(imagine_model.parameters(), lr=learning_rate, weight_decay=weight_decay)\n weight_group = {\n 'params': [p for n, p in list(filter(lambda p: p[1].requires_grad, imagine_model.named_parameters())) if 'bias' not in n],\n 'weight_decay': weight_decay,\n }\n bias_group = {\n 'params': [p for n, p in list(filter(lambda p: p[1].requires_grad, imagine_model.named_parameters())) if 'bias' in n],\n }\n param_groups = [weight_group, bias_group]\nelse:\n mt_weight_group = {\n 'params': [p for n, p in list(filter(lambda p: p[1].requires_grad, imagine_model.named_parameters())) if 'bias' not in n and 'vse_imagine' not in n],\n 'weight_decay': weight_decay,\n }\n mt_bias_group = {\n 'params': [p for n, p in list(filter(lambda p: p[1].requires_grad, imagine_model.named_parameters())) if 'bias' in n and 'vse_imagine' not in n],\n }\n vse_weight_group = {\n 'params': [p for n, p in list(filter(lambda p: p[1].requires_grad, imagine_model.named_parameters())) if 'bias' not in n and 'vse_imagine' in n],\n 'weight_decay': weight_decay,\n 'lr': learning_rate / 2,\n }\n vse_bias_group = {\n 'params': [p for n, p in list(filter(lambda p: p[1].requires_grad, imagine_model.named_parameters())) if 'bias' in n and 'vse_imagine' in n],\n 'lr': learning_rate / 2,\n }\n param_groups = [mt_weight_group, mt_bias_group, vse_weight_group, vse_bias_group]\n\n## Define Optimizer\noptimizer = optim.Adam(param_groups, lr=learning_rate) # Optimize the parameters\n\n## Define a learning rate optimizer\nlr_decay_scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, factor=0.2, patience=10)\n\n################################ Print the configuration settings #################################\nprint(\"Configurations:\\n\")\nprint(\"######## Network Structure #########\")\nprint(\"embedding_size: {}\".format(embedding_size))\nprint(\"hidden_size: {}\".format(hidden_size))\nprint(\"shared_embedding_size: {}\".format(shared_embedding_size))\nprint(\"n_layers: {}\".format(n_layers))\nprint(\"tied_emb: {}\".format(tied_emb))\nprint('\\n')\nprint(\"####### Dropout #######\")\nprint(\"dropout_im_emb: {}\".format(dropout_im_emb))\nprint(\"dropout_txt_emb: {}\".format(dropout_txt_emb))\nprint(\"dropout_rnn_enc: {}\".format(dropout_rnn_enc))\nprint(\"dropout_rnn_dec: {}\".format(dropout_rnn_dec))\nprint(\"dropout_emb: {}\".format(dropout_emb))\nprint(\"dropout_ctx: {}\".format(dropout_ctx))\nprint(\"dropout_out: {}\".format(dropout_out))\nprint('\\n')\nprint(\"####### Training Setting #######\")\nprint(\"batch_size: {}\".format(batch_size))\nprint(\"eval_batch_size: {}\".format(eval_batch_size))\nprint(\"learning_rate: {}\".format(learning_rate))\nprint(\"weight_decay: {}\".format(weight_decay))\nprint(\"loss_w: {}\".format(loss_w))\nprint(\"beam_size: {}\".format(beam_size))\nprint(\"n_epochs: {}\".format(n_epochs))\nprint(\"print_every: {}\".format(print_every))\nprint(\"eval_every: {}\".format(eval_every))\nprint(\"save_every: {}\".format(save_every))\nprint(\"vse_separate: {}\".format(vse_separate))\nprint(\"teacher_force_ratio: {}\".format(teacher_force_ratio))\nprint(\"clip: {}\".format(clip))\nprint(\"input_size: {}\".format(input_size))\nprint(\"output_size: {}\".format(output_size))\nprint(\"vse_margin: {}\".format(margin_size))\nprint(\"vse_loss_type: {}\".format(vse_loss_type))\nprint(\"init_split: {}\".format(init_split))\nprint('\\n')\n\n########################################## Begin Training ###########################################\nprint_mt_loss = 0\nprint_vse_loss = 0\nprint_loss = 0\n\n## Start Training\nprint(\"Begin Training\")\niter_count = 0\nbest_bleu = 0\nbest_meteor = 0\nbest_loss = 10000000\nearly_stop = patience\n\nstart = time.time()\nprint(f\"\\n\\nportion = {portion}\") \nprint(\"source_language -> target_language\", source_language, target_language)\nprint(f\"Trained_model_output_path{trained_model_output_path}\\n\\n\")\nfor epoch in range(1, n_epochs + 1):\n # for batch_x, batch_y, batch_vi, batch_im, batch_bta_im, batch_x_lengths, batch_y_lengths in data_generator_tl_mtv_bta_vi_shuffle(\n for batch_x, batch_y, batch_vi, batch_im, batch_bta_im, batch_x_lengths, batch_y_lengths in data_generator_tl_mtv_bta_vi(\n train_data_index,\n train_im_feats,\n train_bta_im_feats,\n batch_size):\n\n ## Run the train function\n train_loss, train_loss_mt, train_loss_vse = train_imagine_beam_bta_vi(\n batch_x, batch_y, batch_vi,\n batch_im, batch_bta_im,\n batch_x_lengths,\n imagine_model,\n optimizer,\n criterion_mt, criterion_vse,\n loss_w,\n teacher_force_ratio,\n clip=clip)\n \n print_loss += train_loss\n\n # if use_cuda:\n # torch.cuda.empty_cache()\n\n ## Update translation loss and vse loss\n print_mt_loss += train_loss_mt\n print_vse_loss += train_loss_vse\n \n if iter_count == 0: \n iter_count += 1\n continue\n \n if iter_count % print_every == 0:\n print_loss_avg = print_loss / print_every\n print_mt_loss_avg = print_mt_loss / print_every\n print_vse_loss_avg = print_vse_loss / print_every\n # Reset the print_loss, print_mt_loss and print_vse_loss\n print_loss = 0\n print_mt_loss = 0\n print_vse_loss = 0\n \n print_summary = \"%s (%d %d%%) train_loss: %.4f, train_mt_loss: %.4f, train_vse_loss: %.4f\" % (\n time_since(start, iter_count / n_epochs / batch_num),\n iter_count,\n iter_count / n_epochs / batch_num * 100,\n print_loss_avg,\n print_mt_loss_avg,\n print_vse_loss_avg)\n print(print_summary)\n \n if iter_count % eval_every == 0:\n ## Convert model into eval phase\n imagine_model.eval()\n val_translations = []\n\n ## Compute Val Loss\n ## Print the Bleu Score and loss for Dev Dataset\n val_print_loss = 0\n val_print_mt_loss = 0\n val_print_vse_loss = 0\n eval_iters = 0\n for val_x, val_y, val_vi, val_im, val_bta_im, val_x_lengths, val_y_lengths in data_generator_tl_mtv_bta_vi(\n val_data_index,\n val_im_feats,\n val_bta_im_feats,\n batch_size):\n val_loss, val_mt_loss, val_vse_loss = imagine_model(\n val_x,\n val_x_lengths,\n val_y,\n val_vi,\n val_im,\n val_bta_im,\n teacher_force_ratio,\n criterion_mt=criterion_mt,\n criterion_vse=criterion_vse)\n val_print_loss += val_loss.item()\n val_print_mt_loss += val_mt_loss.item()\n val_print_vse_loss += val_vse_loss.item()\n eval_iters += 1\n ## Compute the Average Losses\n val_loss_mean = val_print_loss / eval_iters\n val_mt_loss_mean = val_print_mt_loss / eval_iters\n val_vse_loss_mean = val_print_vse_loss / eval_iters\n\n ## Check the val_mt_loss_mean\n lr_decay_scheduler.step(val_mt_loss_mean)\n\n ## Save the model when it reaches the best validation loss or best BLEU score\n if val_mt_loss_mean < best_loss:\n torch.save(imagine_model, os.path.join(trained_model_output_path, 'nmt_trained_imagine_model_best_loss.pt'))\n ## update the best_loss\n best_loss = val_mt_loss_mean\n print(f\"dev_loss: {val_loss_mean}, dev_mt_loss: {val_mt_loss_mean}, dev_vse_loss: {val_vse_loss_mean}\")\n\n\n ## Generate translation\n for val_x, val_y, val_im, val_bta_im, val_x_lengths, val_y_lengths, val_sorted_index in data_generator_bta_mtv(\n val_data_index,\n val_im_feats,\n val_bta_im_feats,\n eval_batch_size):\n with torch.no_grad():\n val_translation, _ = imagine_model.beamsearch_decode(\n val_x,\n val_x_lengths,\n val_im,\n val_bta_im,\n beam_size,\n max_length=MAX_LENGTH) # Optimize to take in the Image Variables\n\n # Reorder val_translations and convert them back to words\n val_translation_reorder = translation_reorder_BPE(val_translation, val_sorted_index, t_id2word) \n val_translations += val_translation_reorder\n \n ## Compute the BLEU Score\n val_bleu = compute_bleu(val_y_ref, val_translations)\n\n ## Compute the METEOR Score\n val_translations_meteor = dict((key, [' '.join(value)]) for key, value in enumerate(val_translations))\n val_meteor = Meteor_Scorer.compute_score(val_y_ref_meteor, val_translations_meteor)\n\n print(f\"dev_bleu: {val_bleu[0]}, dev_meteor: {val_meteor[0]}\")\n\n ## Randomly Pick a sentence and translate it to the target language. \n sample_source, sample_ref, sample_output = random_sample_display(val_ori_data, val_translations)\n print(\"An example demo:\")\n print(\"src: {}\".format(sample_source))\n print(\"ref: {}\".format(sample_ref))\n print(\"pred: {}\".format(sample_output))\n \n if val_bleu[0] > best_bleu:\n torch.save(imagine_model, os.path.join(trained_model_output_path, 'nmt_trained_imagine_model_best_BLEU.pt'))\n ## update the best_bleu score\n best_bleu = val_bleu[0]\n early_stop = patience\n else:\n early_stop -= 1\n\n if val_meteor[0] > best_meteor:\n torch.save(imagine_model, os.path.join(trained_model_output_path, 'nmt_trained_imagine_model_best_METEOR.pt'))\n ## update the best_bleu score\n best_meteor = val_meteor[0]\n\n ## Print out the best loss and best BLEU so far\n print(f\"Current Early_Stop Counting: {early_stop}\")\n print(f\"Best Loss so far is: {best_loss}\")\n print(f\"Best BLEU so far is: {best_bleu}\")\n print(f\"Best METEOR so far is: {best_meteor}\")\n if iter_count % save_every == 0:\n ## Save the model every save_every iterations.\n torch.save(imagine_model, os.path.join(trained_model_output_path, f'nmt_trained_imagine_model_{iter_count}.pt'))\n \n if early_stop == 0:\n break\n \n ## Update the Iteration\n iter_count += 1\n \n if early_stop == 0:\n break\n\nprint(\"Training is done.\")\nprint(\"Evalute the Test Result\")\n\n\n######################### Use the best BLEU Model to Evaluate #####################################################\n## Load the Best BLEU Model\nbest_model = torch.load(os.path.join(trained_model_output_path, 'nmt_trained_imagine_model_best_BLEU.pt'))\nif use_cuda:\n best_model.cuda()\n\n## Convert best_model to eval phase\nbest_model.eval()\n\ntest_translations = []\nfor test_x, test_y, test_im, test_bta_im, test_x_lengths, test_y_lengths, test_sorted_index in data_generator_bta_mtv(\n test_data_index,\n test_im_feats,\n test_bta_im_feats,\n eval_batch_size):\n with torch.no_grad():\n test_translation, _ = best_model.beamsearch_decode(\n test_x,\n test_x_lengths,\n test_im,\n test_bta_im,\n beam_size,\n MAX_LENGTH)\n\n ## Reorder val_translations and convert them back to words\n test_translation_reorder = translation_reorder_BPE(test_translation, test_sorted_index, t_id2word) \n test_translations += test_translation_reorder\n\n\n## Compute the test bleu score\ntest_bleu = compute_bleu(test_y_ref, test_translations)\n\n## Compute the METEOR Score\ntest_translations_meteor = dict((key,[' '.join(value)]) for key, value in enumerate(test_translations))\ntest_meteor = Meteor_Scorer.compute_score(test_y_ref_meteor, test_translations_meteor)\n\nprint(f\"Test BLEU score from the best BLEU model: {test_bleu[0]}\")\nprint(f\"Test METEOR score from the best BLEU model: {test_meteor[0]}\")\nprint(\"\\n\")\n## Save the translation prediction to the trained_model_path\ntest_prediction_path = os.path.join(trained_model_output_path, f'test_2017_prediction_best_BLEU.{target_language}')\n\nwith open(test_prediction_path, 'w') as f:\n for x in test_translations:\n f.write(' '.join(x)+'\\n')\n\n\n########################### Use the best METEOR Model to Evaluate #############################################\n## Load the Best METEOR Model\nbest_meteor_model = torch.load(os.path.join(trained_model_output_path, 'nmt_trained_imagine_model_best_METEOR.pt'))\nif use_cuda:\n best_meteor_model.cuda()\n\n## Convert best_model to eval phase\nbest_meteor_model.eval()\n\ntest_translations = []\nfor test_x, test_y, test_im, test_bta_im, test_x_lengths, test_y_lengths, test_sorted_index in data_generator_bta_mtv(\n test_data_index,\n test_im_feats,\n test_bta_im_feats,\n eval_batch_size):\n with torch.no_grad():\n test_translation, _ = best_meteor_model.beamsearch_decode(\n test_x,\n test_x_lengths,\n test_im,\n test_bta_im,\n beam_size,\n MAX_LENGTH)\n\n # Reorder val_translations and convert them back to words\n test_translation_reorder = translation_reorder_BPE(test_translation, test_sorted_index, t_id2word) \n test_translations += test_translation_reorder\n\n\n## Compute the test bleu score\ntest_bleu = compute_bleu(test_y_ref, test_translations)\n\n## Compute the METEOR Score\ntest_translations_meteor = dict((key, [' '.join(value)]) for key, value in enumerate(test_translations))\ntest_meteor = Meteor_Scorer.compute_score(test_y_ref_meteor, test_translations_meteor)\n\nprint(f\"Test BLEU score from the best METEOR model: {test_bleu[0]}\")\nprint(f\"Test METEOR score from the best METEOR model: {test_meteor[0]}\")\n\n## Save the translation prediction to the trained_model_path\ntest_prediction_path = os.path.join(trained_model_output_path, f'test_2017_prediction_best_METEOR.{target_language}')\n\nwith open(test_prediction_path, 'w') as f:\n for x in test_translations:\n f.write(' '.join(x)+'\\n')\n\n\n########################### Use the best loss Model to Evaluate #############################################\n## Load the Best Model\nbest_loss_model = torch.load(os.path.join(trained_model_output_path, 'nmt_trained_imagine_model_best_loss.pt'))\nif use_cuda:\n best_loss_model.cuda()\n \n## Convert best_model to eval phase\nbest_loss_model.eval()\ntest_translations = []\nfor test_x, test_y, test_im, test_bta_im, test_x_lengths, test_y_lengths, test_sorted_index in data_generator_bta_mtv(\n test_data_index,\n test_im_feats,\n test_bta_im_feats,\n eval_batch_size):\n with torch.no_grad():\n test_translation, _ = best_loss_model.beamsearch_decode(\n test_x,\n test_x_lengths,\n test_im,\n test_bta_im,\n beam_size,\n MAX_LENGTH)\n # Reorder val_translations and convert them back to words\n test_translation_reorder = translation_reorder_BPE(test_translation, test_sorted_index, t_id2word) \n test_translations += test_translation_reorder\n\n## Compute the test bleu score\ntest_bleu = compute_bleu(test_y_ref, test_translations)\n\n## Compute the METEOR Score\ntest_translations_meteor = dict((key, [' '.join(value)]) for key, value in enumerate(test_translations))\ntest_meteor = Meteor_Scorer.compute_score(test_y_ref_meteor, test_translations_meteor)\nprint(f\"\\nTest BLEU score from the best loss model: {test_bleu[0]}\")\nprint(f\"Test METEOR score from the best loss model: {test_meteor[0]}\")\n\n## Save the translation prediction to the trained_model_path\ntest_prediction_path = os.path.join(trained_model_output_path, f'test_2017_prediction_best_loss.{target_language}')\nwith open(test_prediction_path, 'w') as f:\n for x in test_translations:\n f.write(' '.join(x)+'\\n')\n"
] |
[
[
"torch.optim.Adam",
"torch.nn.NLLLoss",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"torch.ones",
"numpy.concatenate",
"torch.no_grad",
"torch.cuda.is_available"
]
] |
vznncv/vznncv-signal-generator
|
[
"d5fe9a4effa19e4f1af01ab52e782790af11afad"
] |
[
"src/vznncv/signal/generator/onedim/_generator.py"
] |
[
"\"\"\"\nMain module to generate one dimensional random process.\n\"\"\"\nimport logging\nfrom typing import Iterable\n\nimport numpy as np\n\nfrom vznncv.signal.generator.onedim._window import calculate_linear_window_size, linear_window\nfrom ._utils import get_random_state, UnaryFunction, BinaryFunction, TrendFunction\n\n_DEFAULT_DTYPE = np.float64\n\nlogger = logging.getLogger(__name__)\n\n\nclass _BaseFrameGenerator:\n \"\"\"\n Fixed length random process generator, that is based on the FFT.\n \"\"\"\n _DOUBLE_PI = 2 * np.pi\n\n def __init__(self, frame_size, fs=1.0, dtype=_DEFAULT_DTYPE, random_state=None):\n self.freq = np.fft.rfftfreq(frame_size, 1 / fs).astype(dtype)\n self._random = get_random_state(random_state)\n self._fs = fs\n\n self._harmonics = np.empty_like(self.freq, dtype=np.result_type(dtype, np.complex64))\n self._a = np.empty_like(self.freq, dtype=dtype)\n\n def generate(self, s):\n if s.shape != self.freq.shape:\n raise ValueError(\"Invalid s shape {}. Expected {}\".format(s.shape, self.freq.shape))\n\n self._harmonics.real = self._random.randn(self.freq.size)\n self._harmonics.imag = self._random.randn(self.freq.size)\n # get harmonic amplitudes from one side psd\n s = np.sqrt(s)\n np.divide(s, np.sqrt(2), out=self._a)\n self._a *= np.sqrt(self._fs / 2)\n\n self._harmonics *= self._a\n\n frame = np.fft.irfft(self._harmonics, norm='ortho')\n return frame.real\n\n\n#: minimal window size, when \"auto\" option is used\n_MINIMAL_WINDOW_SIZE = 8192\n\n\ndef _build_f_psd(f_psd, fs):\n if f_psd is None:\n new_f_psd = lambda f, t: np.full_like(f, 1)\n new_f_psd.stationary = True\n elif isinstance(f_psd, UnaryFunction):\n new_f_psd = lambda f, t: f_psd(np.abs(f))\n new_f_psd.stationary = True\n elif isinstance(f_psd, BinaryFunction):\n new_f_psd = lambda f, t: f_psd(np.abs(f), t)\n new_f_psd.stationary = False\n else:\n raise ValueError(\"f_psd isn't None, unary or binary function: {}\".format(f_psd))\n return new_f_psd\n\n\ndef _iterate_time_frames(frame_size, t_0=0.0, fs=1.0, dtype=_DEFAULT_DTYPE):\n dt = 1.0 / fs\n frame = np.arange(frame_size, dtype=dtype) * dt + t_0\n d_frame = np.full_like(frame, fill_value=dt * len(frame))\n while True:\n yield frame\n frame += d_frame\n\n\ndef generate_process_realization(*, f_psd=None, f_m=None, f_std=None, fs=1.0,\n dtype=_DEFAULT_DTYPE, random=None,\n precision=0.99, window_size='auto') -> Iterable[np.array]:\n \"\"\"\n Generate random process with a given power spectral density, mean, and standard derivation.\n\n The function yields successive array of the same realizations. A length of the result blocks is undefined,\n but it's guarantee that all blocks has the same length.\n\n Parameters\n ----------\n\n f_psd\n power spectral density function that can be the following:\n - ``None`` - the white noise psd will be used;\n - ``f_psd(f)`` - the function with one positional argument. In this case ``f_psd`` isn't changed\n over time;\n - ``f_psd(f, t) - the function with two positional arguments. In this case ``f_psd`` can be changed\n over time.\n For last 2 cases ``f_psd`` should be defined for ``0 <= f <= fs/2``. The ``f`` argument is numpy\n array, ``t`` - scalar.\n f_m\n mean value function:\n - ``None`` - mean will be zero.\n - scalar - mean is specified constant and isn't changed over time.\n - ``f_m(t)`` - mean value is changed over time according this function. The function should accept\n numpy array\n - ``f_m(t, out)`` - like previous option, but it has an ``out`` parameter for an output array\n for a memory optimization\n f_std\n standard derivation function:\n - ``None`` - standard derivation will be set by the ``f_psd``.\n - scalar - the ``f_psd`` will be normalized, and standard derivation will have a defined value.\n - ``f_std(t)`` - the ``f_psd`` will be normalized, and standard derivation will be changed according\n ``f_std`` function.\n - ``f_std(t, out)`` - like previous option, but has an ``out`` parameter for an output array\n for a memory optimization\n fs\n sampling frequency\n dtype\n result type\n random\n :class:`numpy.random.RandomState` object or its seed\n precision\n expected precision of the random characteristics\n\n Returns\n -------\n Iterable[np.array]\n generator of the random process realization blocks\n\n\n Notes\n -----\n\n The generator efficiently creates a realization of any length using gluing of independent random process\n implementations with 50% overlapping. It reduces a memory consumption, but adds distortion into a\n power spectral density (PSD) of a result process.\n\n The acceptable PSD precision for a stationary spectrum is specified with ``precision`` parameter.\n The precision can be set only if ``window_size`` is set to ``'auto'``.\n\n If ``window_size`` is set to positive number or PSD is changed over time, the specified ``precision`` isn't\n guaranteed.\n \"\"\"\n # check f_m\n f_m = TrendFunction(f_m, default_value=0.0)\n\n # check f_std\n normalize_psd = f_std is not None\n f_std = TrendFunction(f_std, default_value=1.0)\n\n # check f_psd\n f_psd = _build_f_psd(f_psd, fs)\n\n # calculate minimal window size\n if window_size == 'auto':\n window_size = calculate_linear_window_size(\n f_psd=lambda f: f_psd(f, 0),\n precision=precision,\n fs=fs\n )\n\n # increase window size for efficiency\n if window_size < _MINIMAL_WINDOW_SIZE:\n window_size = _MINIMAL_WINDOW_SIZE\n # make window size even to simplify frame overlap\n if window_size % 2 == 1:\n window_size += 1\n\n logger.debug(\"Set window_size to {}\".format(window_size))\n\n # create window to glue frames\n window = linear_window(window_size)\n\n # initialize base frame generator\n base_frame_generator = _BaseFrameGenerator(frame_size=len(window), fs=fs, dtype=dtype, random_state=random)\n freq = base_frame_generator.freq\n\n # normalize f_std if it's needed\n if normalize_psd:\n original_f_psd = f_psd\n\n def normalized_f_psd(f, t):\n s = original_f_psd(f, t)\n # note: ``f`` is ``freq``\n s_pow = np.trapz(s, freq)\n return s / s_pow\n\n normalized_f_psd.stationary = f_psd.stationary\n f_psd = normalized_f_psd\n\n # optimization for a stationary psd\n if f_psd.stationary:\n s = f_psd(freq, 0)\n f_psd = lambda f, t: s\n f_psd.stationary = True\n\n # generate realizations\n s = f_psd(freq, 0)\n prev_weighted_frame = base_frame_generator.generate(s)\n prev_weighted_frame *= window\n curr_weighted_frame = None\n frame_size = window_size // 2\n m_frame = np.empty(frame_size, dtype=dtype)\n std_frame = np.empty(frame_size, dtype=dtype)\n\n for time_frame in _iterate_time_frames(frame_size, fs=fs, dtype=dtype):\n s = f_psd(freq, time_frame[-1])\n curr_weighted_frame = base_frame_generator.generate(s)\n curr_weighted_frame *= window\n\n output_frame = prev_weighted_frame[frame_size:]\n output_frame += curr_weighted_frame[:frame_size]\n\n f_std(time_frame, out=std_frame)\n f_m(time_frame, out=m_frame)\n output_frame *= f_std(time_frame)\n output_frame += m_frame\n\n yield output_frame\n\n prev_weighted_frame = curr_weighted_frame\n\n\ndef create_process_realization(*, size: int, **kwargs):\n \"\"\"\n The version of the :func:`generate_process_realization` that returns a realization of the specified size ``size``.\n\n See :func:`generate_process_realization` for more details.\n \"\"\"\n frame_iter = generate_process_realization(**kwargs)\n frames = []\n total_size = 0\n while total_size < size:\n frame = next(frame_iter)\n total_size += len(frame)\n frames.append(frame)\n\n return np.hstack(tuple(frames))[:size]\n"
] |
[
[
"numpy.fft.irfft",
"numpy.sqrt",
"numpy.abs",
"numpy.fft.rfftfreq",
"numpy.empty_like",
"numpy.arange",
"numpy.full_like",
"numpy.result_type",
"numpy.trapz",
"numpy.empty"
]
] |
jamiesweeney/matrixmagic
|
[
"4c7674232643fa8b7524f0febdefd49f7950c62f"
] |
[
"compare_complex.py"
] |
[
"'''\n Jamie Sweeney\n April 2018\n\n Some more complex examples\n\n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport sys\nimport math\n\n\n\n# Example 1\n#-- Take RGB image convert to greyscale\nRGB_BINS = [0.299, 0.587, 0.114]\n\n# Iterative version of turning to greyscale\ndef gsIterative(img):\n\n gs_img = np.zeros((img.shape[0],img.shape[1]))\n j = 0\n for y in img[:]:\n i = 0\n for x in y[:]:\n gs_val = 0\n k = 0\n for v in x[:]:\n gs_val = gs_val + v*RGB_BINS[k]\n k += 1\n gs_img[j,i] = gs_val\n i += 1\n j += 1\n\n return gs_img\n\n# Vecor version\ndef gsVector(img):\n\n gs_img = np.zeros((img.shape[0],img.shape[1]))\n\n gs_img = img*RGB_BINS # applies co-eff to each RGB val\n f_img = gs_img[:,:,0] + gs_img[:,:,1] + gs_img[:,:,2] # sum the spliced matrices\n\n return f_img\n\n# Compares iterative and vector versions for (y,x) sized random RGB image\ndef compareGS(y, x, print_b):\n\n img = np.random.rand(y,x,3) * 255\n\n # Run iterative\n start = time.time()\n res_iter = gsIterative(img)\n t_iter = time.time() - start\n\n # Run vector\n start = time.time()\n res_vec = gsVector(img)\n t_vec = time.time() - start\n\n # Give output\n if (print_b == True):\n print (\"Iterative : %.3f seconds.\" % t_iter)\n print (\"Vector : %.3f seconds.\" % t_vec)\n print (np.array_equiv(res_iter, res_vec))\n\n return (t_iter, t_vec)\n\n\n\n# Compares iterative and vector versions for all shapes of random RGB image\ndef compareGSMultiple(shapes, print_b):\n # Arrays for holding results, and axis\n r1 = np.array(()).reshape(0,1)\n r2 = np.array(()).reshape(0,1)\n s_axis = np.array(()).reshape(0,1)\n\n # Collect results for all shapes\n for shape in shapes:\n res = compareGS(shape[0], shape[1], print_b)\n\n r1 = np.vstack([r1, res[0]])\n r2 = np.vstack([r2, res[1]])\n\n # Adds log2(no. of elements)\n n = 1\n for s in shape:\n n = n*s\n s_axis = np.vstack([s_axis, math.log2(n)])\n\n # Plot the results\n plt.plot(s_axis, r1, label='Iterative')\n plt.plot(s_axis, r2, label='Vector')\n plt.ylabel('Time (s)')\n plt.xlabel('log2(size)')\n plt.legend()\n plt.show()\n\n# Produces a set of matrix shapes\nshapes = (())\nnum = 1\nwhile num < 5000:\n shapes = shapes + ((num, num),)\n num = num*2\n\ncompareGSMultiple(shapes,True)\n"
] |
[
[
"matplotlib.pyplot.legend",
"numpy.array_equiv",
"matplotlib.pyplot.plot",
"numpy.random.rand",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.show",
"numpy.zeros",
"numpy.vstack",
"matplotlib.pyplot.ylabel"
]
] |
dkaramit/OpSDE
|
[
"c20bfbc17b905408aebcc8e32e6265f32738a285"
] |
[
"Optimizers/Gradient-Descent/python/GD/NAdamGD.py"
] |
[
"from numpy import sqrt as np_sqrt\nfrom numpy import abs as np_abs\n\nfrom .GradientDescent import GradientDescent\n\nclass NAdamGD(GradientDescent):\n '''Implementation of NAdam.'''\n def __init__(self,loss,beta_m=1-1e-1,beta_v=1-1e-3,epsilon=1e-8,alpha=1e-2):\n '''\n loss: the loss function\n beta_m: decay parameter for the average m\n beta_v: decay parameter for the average v \n epsilon: safety parameter (to avoid division by 0)\n alpha: a learning rate that multiplies the rate of AdaDelta. \n '''\n GradientDescent.__init__(self,loss)\n\n self.beta_m=beta_m\n self.beta_v=beta_v\n self.epsilon=epsilon\n self.alpha=alpha\n \n #The \"bias corrected\" m and v need beta^iteration, so I need something like this\n self.beta_m_ac=beta_m\n self.beta_v_ac=beta_v\n\n # counters for the decaying means of the gradient \n self.mE=[0 for _ in self.Q.model.w]\n self.vE=[0 for _ in self.Q.model.w]\n \n #lists to store the changes in w \n self.dw=[0 for _ in self.Q.model.w]\n\n def update(self,abs_tol=1e-5, rel_tol=1e-3):\n '''\n update should return a number that when it is smaller than 1\n the main loop stops. Here I choose this number to be:\n sqrt(1/dim*sum_{i=0}^{dim}(grad/(abs_tol+x*rel_tol))_i^2)\n '''\n\n # accumulate the decay rates, in order to correct the averages \n self.beta_m_ac*=self.beta_m_ac\n self.beta_v_ac*=self.beta_v_ac\n \n _w2=0\n _check=0\n \n\n self.Q.averageGrad()\n\n for i in range(self.dim):\n\n self.mE[i]=self.beta_m*self.mE[i] + (1-self.beta_m)*self.Q.grad[i]\n self.vE[i]=self.beta_v*self.vE[i] + (1-self.beta_v)*self.Q.grad[i]**2\n\n dw=self.alpha/(np_sqrt(self.vE[i]/(1-self.beta_v_ac)) + self.epsilon)\n dw*=(self.beta_m*self.mE[i] + (1-self.beta_m)*self.Q.grad[i])/(1-self.beta_m_ac)\n self.Q.model.w[i]=self.Q.model.w[i] - dw\n \n _w2=abs_tol + np_abs(self.Q.model.w[i]) * rel_tol\n _check+=(dw/_w2)*(dw/_w2)\n\n self.Q.grad[i]=0\n\n _check=np_sqrt(1./self.dim *_check)\n \n return _check\n"
] |
[
[
"numpy.abs",
"numpy.sqrt"
]
] |
snehasharma0707/License-Plate-Recognition
|
[
"433251795c5fdef06ab07497d5d13537a89c1a41",
"433251795c5fdef06ab07497d5d13537a89c1a41"
] |
[
"GenData.py",
"Main_.py"
] |
[
"# This file is used for training character recognition and the output of this file is classifications.txt and flattened_images.txt\n\nimport sys\nimport numpy as np\nimport cv2\nimport os\n\nMIN_CONTOUR_AREA = 100\n\nRESIZED_IMAGE_WIDTH = 20\nRESIZED_IMAGE_HEIGHT = 30\n\n\ndef main():\n imgTrainingNumbers = cv2.imread(\"training_chars.png\") # read the training characters image\n\n if imgTrainingNumbers is None: # if image was not read successfully\n print(\"error: image not read from file \\n\\n\")\n os.system(\"pause\")\n return\n # end if\n\n imgGray = cv2.cvtColor(imgTrainingNumbers, cv2.COLOR_BGR2GRAY) # get grayscale image\n imgBlurred = cv2.GaussianBlur(imgGray, (5,5), 0) # blur\n\n # filter image from grayscale to black and white\n imgThresh = cv2.adaptiveThreshold(imgBlurred,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY_INV,11,2)\n\n cv2.imshow(\"imgThresh\", imgThresh)\n\n imgThreshCopy = imgThresh.copy()\n\n npaContours, npaHierarchy = cv2.findContours(imgThreshCopy,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)\n\n # declare empty numpy array, we will use this to write to file later\n # zero rows, enough cols to hold all image data\n npaFlattenedImages = np.empty((0, RESIZED_IMAGE_WIDTH * RESIZED_IMAGE_HEIGHT))\n\n intClassifications = [] # declare empty classifications list, this will be our list of how we are classifying our chars from user input, we will write to file at the end\n\n # possible chars we are interested in are digits 0 through 9, put these in list intValidChars\n intValidChars = [ord('0'), ord('1'), ord('2'), ord('3'), ord('4'), ord('5'), ord('6'), ord('7'), ord('8'), ord('9'),\n ord('A'), ord('B'), ord('C'), ord('D'), ord('E'), ord('F'), ord('G'), ord('H'), ord('I'), ord('J'),\n ord('K'), ord('L'), ord('M'), ord('N'), ord('O'), ord('P'), ord('Q'), ord('R'), ord('S'), ord('T'),\n ord('U'), ord('V'), ord('W'), ord('X'), ord('Y'), ord('Z')]\n\n for npaContour in npaContours: # for each contour\n if cv2.contourArea(npaContour) > MIN_CONTOUR_AREA: # if contour is big enough to consider\n [intX, intY, intW, intH] = cv2.boundingRect(npaContour) # get and break out bounding rect\n\n # draw rectangle around each contour as we ask user for input\n cv2.rectangle(imgTrainingNumbers,(intX, intY),(intX+intW,intY+intH),(0, 0, 255),2)\n\n imgROI = imgThresh[intY:intY+intH, intX:intX+intW] # crop char out of threshold image\n imgROIResized = cv2.resize(imgROI, (RESIZED_IMAGE_WIDTH, RESIZED_IMAGE_HEIGHT)) # resize image, this will be more consistent for recognition and storage\n\n cv2.imshow(\"imgROI\", imgROI) # show cropped out char for reference\n cv2.imshow(\"imgROIResized\", imgROIResized) # show resized image for reference\n cv2.imshow(\"training_numbers.png\", imgTrainingNumbers) # show training numbers image, this will now have red rectangles drawn on it\n\n intChar = cv2.waitKey(0) # get key press\n\n if intChar == 27: # if esc key was pressed\n sys.exit() # exit program\n elif intChar in intValidChars: # else if the char is in the list of chars we are looking for . . .\n\n intClassifications.append(intChar) # append classification char to integer list of chars (we will convert to float later before writing to file)\n\n npaFlattenedImage = imgROIResized.reshape((1, RESIZED_IMAGE_WIDTH * RESIZED_IMAGE_HEIGHT))\n npaFlattenedImages = np.append(npaFlattenedImages, npaFlattenedImage, 0)\n\n\n fltClassifications = np.array(intClassifications, np.float32) # convert classifications list of ints to numpy array of floats\n\n npaClassifications = fltClassifications.reshape((fltClassifications.size, 1)) # flatten numpy array of floats to 1d so we can write to file later\n print(\"\\n\\ntraining complete !!\\n\")\n\n np.savetxt(\"classifications.txt\", npaClassifications) # write classifications\n np.savetxt(\"flattened_images.txt\", npaFlattenedImages) # write flattened images\n\n cv2.destroyAllWindows() # remove windows from memory\n\n return\n\n###################################################################################################\nif __name__ == \"__main__\":\n main()\n# end if\n\n\n\n\n",
"import cv2\nimport numpy as np\nimport os\nfrom skimage import io\nimport requests\nimport random\nimport numpy as np # linear algebra\nimport pandas as pd # data processing\nfrom tqdm import tqdm\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport urllib3\nimport json\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nfrom urllib.request import urlopen\nimport scipy.misc\n\n\nimport Detect_Char\nimport Detect_Plate\nimport PossiblePlates\n\n# module level variables ##########################################################################\nSCALAR_BLACK = (0.0, 0.0, 0.0)\nSCALAR_WHITE = (255.0, 255.0, 255.0)\nSCALAR_YELLOW = (0.0, 255.0, 255.0)\nSCALAR_GREEN = (0.0, 255.0, 0.0)\nSCALAR_RED = (0.0, 0.0, 255.0)\n\n\n\nshowSteps = False\n\n###################################################################################################\ndef main():\n\n blnKNNTrainingSuccessful = Detect_Char.loadKNNDataAndTrainKNN() # attempt KNN training\n\n if blnKNNTrainingSuccessful == False: # if KNN training was not successful\n print(\"\\nerror: KNN traning was not successful\\n\") # show error message\n return # and exit program\n # end if\n\n # Reading data from the dataset\n data = pd.read_json(r'C:\\Users\\Sneha Sharma\\Desktop\\vehicle-number-plate-detection Datasets (2)\\Indian_Number_plates.json',lines=True)\n pd.set_option('display.max_colwidth', -1) #to set the list as it was\n\n # Delete the empty column\n del data['extras']\n #Delete the annotation info\n del data['annotation']\n\n\n URL = [] #list to store the array of URLs\n\n def downloadTraining(df): #function to download the training data\n\n for index, row in df.head(n=10).iterrows(): #for loop to extract the dataset head(n=5) constricts the for loop to only 10 data entries\n url=row[0]\n URL.append(url)\n print(\"done\")\n\n downloadTraining(data) #calling the dataset extraction function\n print(\"complete\")\n\n url=URL[6] #############IMPORTANT::::: EXTRACTING THE 8th ELEMENT OF THE DATASET\n imgOriginalScene = io.imread(url) # open image\n\n if imgOriginalScene is None: # if image was not read successfully\n print(\"\\nerror: image not read from file \\n\\n\") # print error message to std out\n os.system(\"pause\") # pause so user can see error message\n return # and exit program\n # end if\n\n listOfPossiblePlates = Detect_Plate.detectPlatesInScene(imgOriginalScene) # detect plates\n\n listOfPossiblePlates = Detect_Char.detectCharsInPlates(listOfPossiblePlates) # detect chars in plates\n\n cv2.imshow(\"imgOriginalScene\", imgOriginalScene) # show scene image\n\n if len(listOfPossiblePlates) == 0: # if no plates were found\n print(\"\\nno license plates were detected\\n\")\n else: # else\n\n listOfPossiblePlates.sort(key = lambda possiblePlate: len(possiblePlate.strChars), reverse = True) # sort the list of possible plates in descending order\n licPlate = listOfPossiblePlates[0] # suppose the plate with the most recognized chars (the first plate in sorted by string length descending order) is the actual plate\n\n cv2.imshow(\"imgPlate\", licPlate.imgPlate) # show crop of plate and threshold of plate\n cv2.imshow(\"imgThresh\", licPlate.imgThresh)\n\n if len(licPlate.strChars) == 0: # if no chars were found in the plate\n print(\"\\nno characters were detected\\n\\n\") # show message\n return # and exit program\n # end if\n\n drawRedRectangleAroundPlate(imgOriginalScene, licPlate) # draw red rectangle around plate\n\n print(\"\\nlicense plate read from image = \" + licPlate.strChars + \"\\n\") # write license plate text to std out\n print(\"----------------------------------------\")\n\n writeLicensePlateCharsOnImage(imgOriginalScene, licPlate) # write license plate text on the image\n\n cv2.imshow(\"imgOriginalScene\", imgOriginalScene) # re-show scene image\n\n cv2.imwrite(\"imgOriginalScene.png\", imgOriginalScene) # write image out to file\n\n # end if else\n\n cv2.waitKey(0)\t\t\t\t\t# hold windows open until user presses a key\n\n return\n# end main\n\n###################################################################################################\ndef drawRedRectangleAroundPlate(imgOriginalScene, licPlate):\n\n p2fRectPoints = cv2.boxPoints(licPlate.rrLocationOfPlateInScene) # get 4 vertices of rotated rect\n\n cv2.line(imgOriginalScene, tuple(p2fRectPoints[0]), tuple(p2fRectPoints[1]), SCALAR_RED, 2) # draw 4 red lines\n cv2.line(imgOriginalScene, tuple(p2fRectPoints[1]), tuple(p2fRectPoints[2]), SCALAR_RED, 2)\n cv2.line(imgOriginalScene, tuple(p2fRectPoints[2]), tuple(p2fRectPoints[3]), SCALAR_RED, 2)\n cv2.line(imgOriginalScene, tuple(p2fRectPoints[3]), tuple(p2fRectPoints[0]), SCALAR_RED, 2)\n# end function\n\n###################################################################################################\ndef writeLicensePlateCharsOnImage(imgOriginalScene, licPlate):\n ptCenterOfTextAreaX = 0 # this will be the center of the area the text will be written to\n ptCenterOfTextAreaY = 0\n\n ptLowerLeftTextOriginX = 0 # this will be the bottom left of the area that the text will be written to\n ptLowerLeftTextOriginY = 0\n\n sceneHeight, sceneWidth, sceneNumChannels = imgOriginalScene.shape\n plateHeight, plateWidth, plateNumChannels = licPlate.imgPlate.shape\n\n intFontFace = cv2.FONT_HERSHEY_SIMPLEX # choose a plain jane font\n fltFontScale = float(plateHeight) / 30.0 # base font scale on height of plate area\n intFontThickness = int(round(fltFontScale * 1.5)) # base font thickness on font scale\n\n textSize, baseline = cv2.getTextSize(licPlate.strChars, intFontFace, fltFontScale, intFontThickness) # call getTextSize\n\n # unpack roatated rect into center point, width and height, and angle\n ( (intPlateCenterX, intPlateCenterY), (intPlateWidth, intPlateHeight), fltCorrectionAngleInDeg ) = licPlate.rrLocationOfPlateInScene\n\n intPlateCenterX = int(intPlateCenterX) # make sure center is an integer\n intPlateCenterY = int(intPlateCenterY)\n\n ptCenterOfTextAreaX = int(intPlateCenterX) # the horizontal location of the text area is the same as the plate\n\n if intPlateCenterY < (sceneHeight * 0.75): # if the license plate is in the upper 3/4 of the image\n ptCenterOfTextAreaY = int(round(intPlateCenterY)) + int(round(plateHeight * 1.6)) # write the chars in below the plate\n else: # else if the license plate is in the lower 1/4 of the image\n ptCenterOfTextAreaY = int(round(intPlateCenterY)) - int(round(plateHeight * 1.6)) # write the chars in above the plate\n # end if\n\n textSizeWidth, textSizeHeight = textSize # unpack text size width and height\n\n ptLowerLeftTextOriginX = int(ptCenterOfTextAreaX - (textSizeWidth / 2)) # calculate the lower left origin of the text area\n ptLowerLeftTextOriginY = int(ptCenterOfTextAreaY + (textSizeHeight / 2)) # based on the text area center, width, and height\n\n # write the text on the image\n cv2.putText(imgOriginalScene, licPlate.strChars, (ptLowerLeftTextOriginX, ptLowerLeftTextOriginY), intFontFace, fltFontScale, SCALAR_YELLOW, intFontThickness)\n\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
] |
[
[
"numpy.savetxt",
"numpy.append",
"numpy.array",
"numpy.empty"
],
[
"pandas.set_option",
"pandas.read_json"
]
] |
ebubae/adversarial-robustness-toolbox
|
[
"55efab2c1a60ae14c37b72fe84778355314396ea"
] |
[
"art/classifiers/keras.py"
] |
[
"# MIT License\n#\n# Copyright (C) IBM Corporation 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nThis module implements the classifier `KerasClassifier` for Keras models.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport logging\n\nimport numpy as np\nimport six\n\nfrom art.classifiers.classifier import Classifier\n\nlogger = logging.getLogger(__name__)\n\n\nclass KerasClassifier(Classifier):\n \"\"\"\n Wrapper class for importing Keras models. The supported backends for Keras are TensorFlow and Theano.\n \"\"\"\n\n def __init__(self, model, use_logits=False, channel_index=3, clip_values=None, defences=None, preprocessing=(0, 1),\n input_layer=0, output_layer=0, custom_activation=False):\n \"\"\"\n Create a `Classifier` instance from a Keras model. Assumes the `model` passed as argument is compiled.\n\n :param model: Keras model\n :type model: `keras.models.Model`\n :param use_logits: True if the output of the model are the logits.\n :type use_logits: `bool`\n :param channel_index: Index of the axis in data containing the color channels or features.\n :type channel_index: `int`\n :param clip_values: Tuple of the form `(min, max)` of floats or `np.ndarray` representing the minimum and\n maximum values allowed for features. If floats are provided, these will be used as the range of all\n features. If arrays are provided, each value will be considered the bound for a feature, thus\n the shape of clip values needs to match the total number of features.\n :type clip_values: `tuple`\n :param defences: Defences to be activated with the classifier.\n :type defences: :class:`.Preprocessor` or `list(Preprocessor)` instances\n :param preprocessing: Tuple of the form `(substractor, divider)` of floats or `np.ndarray` of values to be\n used for data preprocessing. The first value will be substracted from the input. The input will then\n be divided by the second one.\n :type preprocessing: `tuple`\n :param input_layer: Which layer to consider as the Input when the model has multple input layers.\n :type input_layer: `int`\n :param output_layer: Which layer to consider as the Output when the model has multiple output layers.\n :type output_layer: `int`\n :param custom_activation: True if the model uses the last activation other than softmax and requires to use the\n output probability rather than the logits by attacks.\n :type custom_activation: `bool`\n \"\"\"\n super(KerasClassifier, self).__init__(clip_values=clip_values, channel_index=channel_index, defences=defences,\n preprocessing=preprocessing)\n\n self._model = model\n self._input_layer = input_layer\n self._output_layer = output_layer\n\n self._initialize_params(model, use_logits, input_layer, output_layer, custom_activation)\n\n def _initialize_params(self, model, use_logits, input_layer, output_layer, custom_activation):\n \"\"\"\n Initialize most parameters of the classifier. This is a convenience function called by `__init__` and\n `__setstate__` to avoid code duplication.\n\n :param model: Keras model\n :type model: `keras.models.Model`\n :param use_logits: True if the output of the model are the logits.\n :type use_logits: `bool`\n :param input_layer: Which layer to consider as the Input when the model has multple input layers.\n :type input_layer: `int`\n :param output_layer: Which layer to consider as the Output when the model has multiple output layers.\n :type output_layer: `int`\n :param custom_activation: True if the model uses the last activation other than softmax and requires to use the\n output probability rather than the logits by attacks.\n :type custom_activation: `bool`\n \"\"\"\n import keras.backend as k\n\n if hasattr(model, 'inputs'):\n self._input_layer = input_layer\n self._input = model.inputs[input_layer]\n else:\n self._input = model.input\n self._input_layer = 0\n\n if hasattr(model, 'outputs'):\n self._output = model.outputs[output_layer]\n self._output_layer = output_layer\n else:\n self._output = model.output\n self._output_layer = 0\n\n _, self._nb_classes = k.int_shape(self._output)\n self._input_shape = k.int_shape(self._input)[1:]\n self._custom_activation = custom_activation\n logger.debug('Inferred %i classes and %s as input shape for Keras classifier.', self.nb_classes,\n str(self.input_shape))\n\n # Get predictions and loss function\n label_ph = k.placeholder(shape=self._output.shape)\n if not hasattr(self._model, 'loss'):\n logger.warning('Keras model has no loss set. Trying to use `k.sparse_categorical_crossentropy`.')\n loss_function = k.sparse_categorical_crossentropy\n else:\n if isinstance(self._model.loss, six.string_types):\n loss_function = getattr(k, self._model.loss)\n else:\n loss_function = getattr(k, self._model.loss.__name__)\n\n self._use_logits = use_logits\n if not use_logits:\n if k.backend() == 'tensorflow':\n if custom_activation:\n preds = self._output\n loss_ = loss_function(label_ph, preds, from_logits=False)\n else:\n # We get a list of tensors that comprise the final \"layer\" -> take the last element\n preds = self._output.op.inputs[-1]\n loss_ = loss_function(label_ph, preds, from_logits=True)\n else:\n loss_ = loss_function(label_ph, self._output, from_logits=use_logits)\n\n # Convert predictions to logits for consistency with the other cases\n eps = 10e-8\n preds = k.log(k.clip(self._output, eps, 1. - eps))\n else:\n preds = self._output\n loss_ = loss_function(label_ph, self._output, from_logits=use_logits)\n if preds == self._input: # recent Tensorflow version does not allow a model with an output same as the input.\n preds = k.identity(preds)\n loss_grads = k.gradients(loss_, self._input)\n\n if k.backend() == 'tensorflow':\n loss_grads = loss_grads[0]\n elif k.backend() == 'cntk':\n raise NotImplementedError('Only TensorFlow and Theano support is provided for Keras.')\n\n # Set loss, grads and prediction functions\n self._preds_op = preds\n self._loss = loss_\n self._loss_grads = k.function([self._input, label_ph], [loss_grads])\n self._preds = k.function([self._input], [preds])\n\n # Set check for the shape of y for loss functions that do not take labels in one-hot encoding\n self._reduce_labels = (hasattr(self._loss.op, 'inputs') and\n not all(len(input_.shape) == len(self._loss.op.inputs[0].shape)\n for input_ in self._loss.op.inputs))\n\n # Get the internal layer\n self._layer_names = self._get_layers()\n\n def loss_gradient(self, x, y, **kwargs):\n \"\"\"\n Compute the gradient of the loss function w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :type x: `np.ndarray`\n :param y: Correct labels, one-vs-rest encoding.\n :type y: `np.ndarray`\n :return: Array of gradients of the same shape as `x`.\n :rtype: `np.ndarray`\n \"\"\"\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=False)\n\n # Adjust the shape of y for loss functions that do not take labels in one-hot encoding\n if self._reduce_labels:\n y_preprocessed = np.argmax(y_preprocessed, axis=1)\n\n # Compute gradients\n grads = self._loss_grads([x_preprocessed, y_preprocessed])[0]\n grads = self._apply_preprocessing_gradient(x, grads)\n assert grads.shape == x_preprocessed.shape\n\n return grads\n\n def class_gradient(self, x, label=None, logits=False, **kwargs):\n \"\"\"\n Compute per-class derivatives w.r.t. `x`.\n\n :param x: Sample input with shape as expected by the model.\n :type x: `np.ndarray`\n :param label: Index of a specific per-class derivative. If an integer is provided, the gradient of that class\n output is computed for all samples. If multiple values as provided, the first dimension should\n match the batch size of `x`, and each value will be used as target for its corresponding sample in\n `x`. If `None`, then gradients for all classes will be computed for each sample.\n :type label: `int` or `list`\n :param logits: `True` if the prediction should be done at the logits layer.\n :type logits: `bool`\n :return: Array of gradients of input features w.r.t. each class in the form\n `(batch_size, nb_classes, input_shape)` when computing for all classes, otherwise shape becomes\n `(batch_size, 1, input_shape)` when `label` parameter is specified.\n :rtype: `np.ndarray`\n \"\"\"\n # Check value of label for computing gradients\n if not (label is None or (isinstance(label, (int, np.integer)) and label in range(self.nb_classes))\n or (isinstance(label, np.ndarray) and len(label.shape) == 1 and (label < self.nb_classes).all()\n and label.shape[0] == x.shape[0])):\n raise ValueError('Label %s is out of range.' % str(label))\n\n self._init_class_grads(label=label, logits=logits)\n\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n if label is None:\n # Compute the gradients w.r.t. all classes\n if logits:\n grads = np.swapaxes(np.array(self._class_grads_logits([x_preprocessed])), 0, 1)\n else:\n grads = np.swapaxes(np.array(self._class_grads([x_preprocessed])), 0, 1)\n\n elif isinstance(label, (int, np.integer)):\n # Compute the gradients only w.r.t. the provided label\n if logits:\n grads = np.swapaxes(np.array(self._class_grads_logits_idx[label]([x_preprocessed])), 0, 1)\n else:\n grads = np.swapaxes(np.array(self._class_grads_idx[label]([x_preprocessed])), 0, 1)\n\n assert grads.shape == (x_preprocessed.shape[0], 1) + self.input_shape\n\n else:\n # For each sample, compute the gradients w.r.t. the indicated target class (possibly distinct)\n unique_label = list(np.unique(label))\n if logits:\n grads = np.array([self._class_grads_logits_idx[l]([x_preprocessed]) for l in unique_label])\n else:\n grads = np.array([self._class_grads_idx[l]([x_preprocessed]) for l in unique_label])\n grads = np.swapaxes(np.squeeze(grads, axis=1), 0, 1)\n lst = [unique_label.index(i) for i in label]\n grads = np.expand_dims(grads[np.arange(len(grads)), lst], axis=1)\n\n grads = self._apply_preprocessing_gradient(x, grads)\n\n return grads\n\n def predict(self, x, logits=False, batch_size=128, **kwargs):\n \"\"\"\n Perform prediction for a batch of inputs.\n\n :param x: Test set.\n :type x: `np.ndarray`\n :param logits: `True` if the prediction should be done at the logits layer.\n :type logits: `bool`\n :param batch_size: Size of batches.\n :type batch_size: `int`\n :return: Array of predictions of shape `(nb_inputs, self.nb_classes)`.\n :rtype: `np.ndarray`\n \"\"\"\n from art import NUMPY_DTYPE\n\n # Apply defences\n x_preprocessed, _ = self._apply_preprocessing(x, y=None, fit=False)\n\n # Run predictions with batching\n preds = np.zeros((x_preprocessed.shape[0], self.nb_classes), dtype=NUMPY_DTYPE)\n for batch_index in range(int(np.ceil(x_preprocessed.shape[0] / float(batch_size)))):\n begin, end = batch_index * batch_size, min((batch_index + 1) * batch_size, x_preprocessed.shape[0])\n preds[begin:end] = self._preds([x_preprocessed[begin:end]])[0]\n\n if not logits and not self._custom_activation:\n exp = np.exp(preds[begin:end] - np.max(preds[begin:end], axis=1, keepdims=True))\n preds[begin:end] = exp / np.sum(exp, axis=1, keepdims=True)\n\n return preds\n\n def fit(self, x, y, batch_size=128, nb_epochs=20, **kwargs):\n \"\"\"\n Fit the classifier on the training set `(x, y)`.\n\n :param x: Training data.\n :type x: `np.ndarray`\n :param y: Labels, one-vs-rest encoding.\n :type y: `np.ndarray`\n :param batch_size: Size of batches.\n :type batch_size: `int`\n :param nb_epochs: Number of epochs to use for training.\n :type nb_epochs: `int`\n :param kwargs: Dictionary of framework-specific arguments. These should be parameters supported by the\n `fit_generator` function in Keras and will be passed to this function as such. Including the number of\n epochs or the number of steps per epoch as part of this argument will result in as error.\n :type kwargs: `dict`\n :return: `None`\n \"\"\"\n # Apply preprocessing\n x_preprocessed, y_preprocessed = self._apply_preprocessing(x, y, fit=True)\n\n # Adjust the shape of y for loss functions that do not take labels in one-hot encoding\n if self._reduce_labels:\n y_preprocessed = np.argmax(y_preprocessed, axis=1)\n\n gen = generator_fit(x_preprocessed, y_preprocessed, batch_size)\n self._model.fit_generator(gen, steps_per_epoch=x_preprocessed.shape[0] / batch_size, epochs=nb_epochs, **kwargs)\n\n def fit_generator(self, generator, nb_epochs=20, **kwargs):\n \"\"\"\n Fit the classifier using the generator that yields batches as specified.\n\n :param generator: Batch generator providing `(x, y)` for each epoch. If the generator can be used for native\n training in Keras, it will.\n :type generator: :class:`.DataGenerator`\n :param nb_epochs: Number of epochs to use for training.\n :type nb_epochs: `int`\n :param kwargs: Dictionary of framework-specific arguments. These should be parameters supported by the\n `fit_generator` function in Keras and will be passed to this function as such. Including the number of\n epochs as part of this argument will result in as error.\n :type kwargs: `dict`\n :return: `None`\n \"\"\"\n from art.data_generators import KerasDataGenerator\n\n # Try to use the generator as a Keras native generator, otherwise use it through the `DataGenerator` interface\n if isinstance(generator, KerasDataGenerator) and not hasattr(self, 'defences'):\n try:\n self._model.fit_generator(generator.generator, epochs=nb_epochs, **kwargs)\n except ValueError:\n logger.info('Unable to use data generator as Keras generator. Now treating as framework-independent.')\n super(KerasClassifier, self).fit_generator(generator, nb_epochs=nb_epochs, **kwargs)\n else:\n super(KerasClassifier, self).fit_generator(generator, nb_epochs=nb_epochs, **kwargs)\n\n @property\n def layer_names(self):\n \"\"\"\n Return the hidden layers in the model, if applicable.\n\n :return: The hidden layers in the model, input and output layers excluded.\n :rtype: `list`\n\n .. warning:: `layer_names` tries to infer the internal structure of the model.\n This feature comes with no guarantees on the correctness of the result.\n The intended order of the layers tries to match their order in the model, but this is not\n guaranteed either.\n \"\"\"\n return self._layer_names\n\n def get_activations(self, x, layer, batch_size=128):\n \"\"\"\n Return the output of the specified layer for input `x`. `layer` is specified by layer index (between 0 and\n `nb_layers - 1`) or by name. The number of layers can be determined by counting the results returned by\n calling `layer_names`.\n\n :param x: Input for computing the activations.\n :type x: `np.ndarray`\n :param layer: Layer for computing the activations\n :type layer: `int` or `str`\n :param batch_size: Size of batches.\n :type batch_size: `int`\n :return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.\n :rtype: `np.ndarray`\n \"\"\"\n import keras.backend as k\n from art import NUMPY_DTYPE\n\n if isinstance(layer, six.string_types):\n if layer not in self._layer_names:\n raise ValueError('Layer name %s is not part of the graph.' % layer)\n layer_name = layer\n elif isinstance(layer, int):\n if layer < 0 or layer >= len(self._layer_names):\n raise ValueError('Layer index %d is outside of range (0 to %d included).'\n % (layer, len(self._layer_names) - 1))\n layer_name = self._layer_names[layer]\n else:\n raise TypeError('Layer must be of type `str` or `int`.')\n\n layer_output = self._model.get_layer(layer_name).output\n output_func = k.function([self._input], [layer_output])\n\n if x.shape == self.input_shape:\n x_expanded = np.expand_dims(x, 0)\n else:\n x_expanded = x\n\n # Apply preprocessing\n x_preprocessed, _ = self._apply_preprocessing(x=x_expanded, y=None, fit=False)\n\n assert len(x_preprocessed.shape) == 4\n\n # Determine shape of expected output and prepare array\n output_shape = output_func([x_preprocessed[0][None, ...]])[0].shape\n activations = np.zeros((x_preprocessed.shape[0],) + output_shape[1:], dtype=NUMPY_DTYPE)\n\n # Get activations with batching\n for batch_index in range(int(np.ceil(x_preprocessed.shape[0] / float(batch_size)))):\n begin, end = batch_index * batch_size, min((batch_index + 1) * batch_size, x_preprocessed.shape[0])\n activations[begin:end] = output_func([x_preprocessed[begin:end]])[0]\n\n return activations\n\n def _init_class_grads(self, label=None, logits=False):\n import keras.backend as k\n\n if len(self._output.shape) == 2:\n nb_outputs = self._output.shape[1]\n else:\n raise ValueError('Unexpected output shape for classification in Keras model.')\n\n if label is None:\n logger.debug('Computing class gradients for all %i classes.', self.nb_classes)\n if logits:\n if not hasattr(self, '_class_grads_logits'):\n class_grads_logits = [k.gradients(self._preds_op[:, i], self._input)[0]\n for i in range(nb_outputs)]\n self._class_grads_logits = k.function([self._input], class_grads_logits)\n else:\n if not hasattr(self, '_class_grads'):\n class_grads = [k.gradients(k.softmax(self._preds_op)[:, i], self._input)[0]\n for i in range(nb_outputs)]\n self._class_grads = k.function([self._input], class_grads)\n\n else:\n if isinstance(label, int):\n unique_labels = [label]\n logger.debug('Computing class gradients for class %i.', label)\n else:\n unique_labels = np.unique(label)\n logger.debug('Computing class gradients for classes %s.', str(unique_labels))\n\n if logits:\n if not hasattr(self, '_class_grads_logits_idx'):\n self._class_grads_logits_idx = [None for _ in range(nb_outputs)]\n\n for current_label in unique_labels:\n if self._class_grads_logits_idx[current_label] is None:\n class_grads_logits = [k.gradients(self._preds_op[:, current_label], self._input)[0]]\n self._class_grads_logits_idx[current_label] = k.function([self._input], class_grads_logits)\n else:\n if not hasattr(self, '_class_grads_idx'):\n self._class_grads_idx = [None for _ in range(nb_outputs)]\n\n for current_label in unique_labels:\n if self._class_grads_idx[current_label] is None:\n class_grads = [k.gradients(k.softmax(self._preds_op)[:, current_label], self._input)[0]]\n self._class_grads_idx[current_label] = k.function([self._input], class_grads)\n\n def _get_layers(self):\n \"\"\"\n Return the hidden layers in the model, if applicable.\n\n :return: The hidden layers in the model, input and output layers excluded.\n :rtype: `list`\n \"\"\"\n from keras.engine.topology import InputLayer\n\n layer_names = [layer.name for layer in self._model.layers[:-1] if not isinstance(layer, InputLayer)]\n logger.info('Inferred %i hidden layers on Keras classifier.', len(layer_names))\n\n return layer_names\n\n def set_learning_phase(self, train):\n \"\"\"\n Set the learning phase for the backend framework.\n\n :param train: True to set the learning phase to training, False to set it to prediction.\n :type train: `bool`\n \"\"\"\n import keras.backend as k\n\n if isinstance(train, bool):\n self._learning_phase = train\n k.set_learning_phase(int(train))\n\n def save(self, filename, path=None):\n \"\"\"\n Save a model to file in the format specific to the backend framework. For Keras, .h5 format is used.\n\n :param filename: Name of the file where to store the model.\n :type filename: `str`\n :param path: Path of the folder where to store the model. If no path is specified, the model will be stored in\n the default data location of the library `DATA_PATH`.\n :type path: `str`\n :return: None\n \"\"\"\n import os\n\n if path is None:\n from art import DATA_PATH\n full_path = os.path.join(DATA_PATH, filename)\n else:\n full_path = os.path.join(path, filename)\n folder = os.path.split(full_path)[0]\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n self._model.save(str(full_path))\n logger.info('Model saved in path: %s.', full_path)\n\n def __getstate__(self):\n \"\"\"\n Use to ensure `KerasClassifier` can be pickled.\n\n :return: State dictionary with instance parameters.\n :rtype: `dict`\n \"\"\"\n import time\n\n state = self.__dict__.copy()\n\n # Remove the unpicklable entries\n del state['_model']\n del state['_input']\n del state['_output']\n del state['_preds_op']\n del state['_loss']\n del state['_loss_grads']\n del state['_preds']\n del state['_layer_names']\n\n model_name = str(time.time()) + '.h5'\n state['model_name'] = model_name\n self.save(model_name)\n return state\n\n def __setstate__(self, state):\n \"\"\"\n Use to ensure `KerasClassifier` can be unpickled.\n\n :param state: State dictionary with instance parameters to restore.\n :type state: `dict`\n \"\"\"\n self.__dict__.update(state)\n\n # Load and update all functionality related to Keras\n import os\n from art import DATA_PATH\n from keras.models import load_model\n\n full_path = os.path.join(DATA_PATH, state['model_name'])\n model = load_model(str(full_path))\n\n self._model = model\n self._initialize_params(model, state['_use_logits'], state['_input_layer'], state['_output_layer'],\n state['_custom_activation'])\n\n def __repr__(self):\n repr_ = \"%s(model=%r, use_logits=%r, channel_index=%r, clip_values=%r, defences=%r, preprocessing=%r, \" \\\n \"input_layer=%r, output_layer=%r, custom_activation=%r)\" \\\n % (self.__module__ + '.' + self.__class__.__name__,\n self._model, self._use_logits, self.channel_index, self.clip_values, self.defences,\n self.preprocessing, self._input_layer, self._output_layer, self._custom_activation)\n\n return repr_\n\n\ndef generator_fit(x, y, batch_size=128):\n \"\"\"\n Minimal data generator for randomly batching large datasets.\n\n :param x: The data sample to batch.\n :type x: `np.ndarray`\n :param y: The labels for `x`. The first dimension has to match the first dimension of `x`.\n :type y: `np.ndarray`\n :param batch_size: The size of the batches to produce.\n :type batch_size: `int`\n :return: A batch of size `batch_size` of random samples from `(x, y)`\n :rtype: `tuple(np.ndarray, np.ndarray)`\n \"\"\"\n while True:\n indices = np.random.randint(x.shape[0], size=batch_size)\n yield x[indices], y[indices]\n"
] |
[
[
"numpy.expand_dims",
"numpy.unique",
"numpy.squeeze",
"numpy.max",
"numpy.argmax",
"numpy.zeros",
"numpy.sum",
"numpy.random.randint"
]
] |
pythonist2/marketpy
|
[
"50df49337012cc4049c395b4ed672e2710f22514"
] |
[
"big_data_prepartion.py"
] |
[
"from marketpy.preprocessing import *\nimport pandas as pd\nimport os\n\n\ndf_all = pd.DataFrame()\nfor file_name in os.listdir(\"data/indicies\"):\n df = pd.read_csv(\"data/indicies/\" + file_name)\n X, y =prepare_data_from_stooq(df)\n X, _, y, _ = train_test_split(X,y, test_size = 0.2)\n\n columns = ['open','high','low','close']\n\n df = pd.DataFrame(X, columns = columns)\n\n df['5_day_return'] = y\n\n df['indice'] = file_name[:-4]\n df_all = pd.concat([df_all,df])\n df_all.reset_index(inplace=True, drop=True)\n\n\ndef prepare_data_for_lstm(X,y, time_step = 20):\n \"\"\"\n\n\n \"\"\"\n V = np.empty([X.shape[0] - time_step, time_step, X.shape[1]])\n for i in range(time_step, X.shape[0]):\n V[i - time_step, :, X.shape[1]]\n y = y[time_step:]\n return V, y\n\nprepare_data_for_lstm(X, y)\n"
] |
[
[
"pandas.concat",
"pandas.read_csv",
"pandas.DataFrame"
]
] |
MijungTheGatsbyPostdoc/SimSiam
|
[
"d8dd2b01f493d094dca1e7634d3b7c00857b5224"
] |
[
"dc_gan_cifar.py"
] |
[
"# originally code is from https://github.com/Ksuryateja/DCGAN-CIFAR10-pytorch/blob/master/gan_cifar.py\n# I am taking its generator for cifar10 dataset (nov 18, 2021)\n\n# used these are parameters in pycharm\n# --data_dir ../Data/ --log_dir ../logs/ -c configs/train_gen_cifar10_to_cifar10.yaml --ckpt_dir ~/.cache/ --hide_progress\n\nimport random\nimport torch\nimport torch.nn as nn\nfrom arguments import get_args\nfrom augmentations import get_aug\nfrom models import get_model, get_backbone\nfrom tools import AverageMeter\nfrom datasets import get_dataset\nfrom optimizers import get_optimizer, LR_Scheduler\nfrom mmd2_estimator import get_real_mmd_loss\nfrom torch import optim\nimport torchvision.utils as vutils\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom torch.optim.lr_scheduler import StepLR\nimport meddistance\n\n# custom weights initialization called on netG\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n m.weight.data.normal_(0.0, 0.02)\n elif classname.find('BatchNorm') != -1:\n m.weight.data.normal_(1.0, 0.02)\n m.bias.data.fill_(0)\n\n\nclass Generator(nn.Module):\n # modify this generator such that we also produce labels.\n def __init__(self, nz, ngf, nc, n_labels):\n super(Generator, self).__init__()\n self.d_code = nz\n self.n_labels = n_labels\n\n # self.ngpu = ngpu\n # this architecture is from\n # https://colab.research.google.com/github/ssundar6087/vision-and-words/blob/master/_notebooks/2020-05-01-DCGAN-CIFAR10.ipynb#scrollTo=i7cwX82GuHRS\n self.main = nn.Sequential(\n nn.ConvTranspose2d(nz, ngf * 8, 4, 1, 0, bias=False),\n nn.BatchNorm2d(ngf * 8),\n nn.ReLU(True),\n nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf * 4),\n nn.ReLU(True),\n nn.ConvTranspose2d(ngf * 4, ngf * 2, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf * 2),\n nn.ReLU(True),\n nn.ConvTranspose2d(ngf * 2, nc, 4, 2, 1, bias=False),\n nn.Tanh()\n )\n\n def forward(self, input):\n # if input.is_cuda and self.ngpu > 1:\n # output = nn.parallel.data_parallel(self.main, input, range(self.ngpu))\n # else:\n output = self.main(input)\n\n return output\n\n def get_code(self, batch_size, device):\n # generate labels uniformly at random\n labels = torch.randint(self.n_labels, (batch_size,), device=device)\n # code = torch.randn(batch_size, self.d_code, device=device)\n code = torch.randn(batch_size, self.d_code, 1, 1, device=device)\n return code, labels\n\n\n\ndef save_images(gen, how_many, data_real_loader, epoch_num, device):\n # after training is over, store syn images\n with torch.no_grad():\n gen_code, gen_labels = gen.get_code(how_many, device)\n syn = gen(gen_code) # batch_size x 3 x 32 x 32\n syn_images = syn.detach().cpu()\n\n # visualize real and syn data\n # Grab a batch of real images from the dataloader\n real_batch = next(iter(data_real_loader))\n\n # Plot the real images\n plt.figure(figsize=(15, 15))\n plt.subplot(1, 2, 1)\n plt.axis(\"off\")\n plt.title(\"Real Images\")\n plt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:how_many], padding=5, normalize=True).cpu(), (1, 2, 0)))\n\n # Plot the fake images from the last epoch\n plt.subplot(1, 2, 2)\n plt.axis(\"off\")\n plt.title(\"Fake Images\")\n plt.imshow(np.transpose(vutils.make_grid(syn_images[:how_many], padding=5, normalize=True), (1, 2, 0)))\n # plt.savefig(str(epoch_num)+'th_generated_images_ch_wise.png')\n plt.savefig(str(epoch_num) + 'th_generated_images_pt1.png')\n # plt.show()\n\n\n\n\ndef main(args):\n\n torch.set_printoptions(precision=10)\n\n # set manual seed to a constant get a consistent output\n manualSeed = random.randint(1, 10000)\n print(\"Random Seed: \", manualSeed)\n random.seed(manualSeed)\n torch.manual_seed(manualSeed)# set manual seed to a constant get a consistent output\n\n ###### (1) load data ######\n train_loader = torch.utils.data.DataLoader(\n dataset=get_dataset(\n transform=get_aug(train=False, train_classifier=True, **args.aug_kwargs),\n train=True,\n **args.dataset_kwargs\n ),\n batch_size=args.eval.batch_size,\n shuffle=True,\n **args.dataloader_kwargs\n )\n test_loader = torch.utils.data.DataLoader(\n dataset=get_dataset(\n transform=get_aug(train=False, train_classifier=False, **args.aug_kwargs),\n train=False,\n **args.dataset_kwargs\n ),\n batch_size=args.eval.batch_size,\n shuffle=False,\n **args.dataloader_kwargs\n )\n\n ###### (2) load backbone ######\n model = get_backbone(args.model.backbone)\n\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n print('device is', device)\n args.device = device # manually added this\n\n # Load the pre-trained backbone\n args.eval_from = '/ubc/cs/home/m/mijungp/.cache/simsiam-cifar10-experiment-resnet18_cifar_variant1_1118022103.pth'\n # args.eval_from = '/home/mijungp/.cache/simsiam-cifar10-experiment-resnet18_cifar_variant1_1118022103.pth'\n assert args.eval_from is not None\n save_dict = torch.load(args.eval_from, map_location='cpu')\n msg = model.load_state_dict({k[9:]: v for k, v in save_dict['state_dict'].items() if k.startswith('backbone.')},\n strict=True)\n\n # print(msg)\n model = model.to(args.device)\n model = torch.nn.DataParallel(model) # because it was trained with DataParallel mode\n # Freeze all the parameters in backbone\n for param in model.parameters():\n param.requires_grad = False\n\n ###### (3) define a generator ######\n # ngpu = torch.cuda.device_count()\n nz = 100 # input noise dimension\n ngf = 64 # number of generator filters\n nc = 3 # number of channels\n n_labels = len(train_loader.dataset.classes) # 10 for CIFAR10 dataset\n n_train_data = len(train_loader.dataset.data) # 50,000 for CIFAR10\n netG = Generator(nz, ngf, nc, n_labels).to(device)\n # netG = torch.nn.DataParallel(netG)\n netG.apply(weights_init)\n print(netG)\n\n optimizer = torch.optim.Adam(list(netG.parameters()), lr=args.eval.base_lr)\n scheduler = StepLR(optimizer, step_size=1, gamma=0.9)\n\n ### median heuristic for both kernels on pixel and latent space ###\n\n # set the scale length\n num_iter = n_train_data/args.eval.batch_size\n sigma2_arr = np.zeros(int(num_iter))\n sigma2_arr_pxl = np.zeros(int(num_iter))\n sigma2_arr_pxl_ch1 = np.zeros(int(num_iter))\n sigma2_arr_pxl_ch2 = np.zeros(int(num_iter))\n sigma2_arr_pxl_ch3 = np.zeros(int(num_iter))\n\n for batch_idx, (data, labels) in enumerate(train_loader):\n # unpack data\n data, labels = data.to(device), labels.to(device)\n # print(' size of data ', data.shape)\n\n # median for features\n data_feat = model(data)\n med = meddistance.meddistance(data_feat.detach().cpu().numpy())\n sigma2 = med**2\n sigma2_arr[batch_idx] = sigma2\n\n # median for data\n data_flattened = torch.reshape(data[:,0,:,:], (args.eval.batch_size, -1))\n med = meddistance.meddistance(data_flattened.detach().cpu().numpy())\n sigma2 = med**2\n sigma2_arr_pxl_ch1[batch_idx] = sigma2\n\n data_flattened = torch.reshape(data[:,1,:,:], (args.eval.batch_size, -1))\n med = meddistance.meddistance(data_flattened.detach().cpu().numpy())\n sigma2 = med**2\n sigma2_arr_pxl_ch2[batch_idx] = sigma2\n\n data_flattened = torch.reshape(data[:,2,:,:], (args.eval.batch_size, -1))\n med = meddistance.meddistance(data_flattened.detach().cpu().numpy())\n sigma2 = med**2\n sigma2_arr_pxl_ch3[batch_idx] = sigma2\n\n\n # median for each channel\n\n # print(sigma2)\n\n rff_sigma2 = torch.tensor(np.mean(sigma2_arr))\n print('length scale (latent)', rff_sigma2)\n # rff_sigma2_pxl = torch.tensor(np.mean(sigma2_arr_pxl))\n # print('length scale (pixel)', rff_sigma2_pxl)\n\n rff_sigma2_pxl_ch1 = torch.tensor(np.mean(sigma2_arr_pxl_ch1))\n print('length scale (ch1)', rff_sigma2_pxl_ch1)\n\n rff_sigma2_pxl_ch2 = torch.tensor(np.mean(sigma2_arr_pxl_ch2))\n print('length scale (ch2)', rff_sigma2_pxl_ch2)\n\n rff_sigma2_pxl_ch3 = torch.tensor(np.mean(sigma2_arr_pxl_ch3))\n print('length scale (ch3)', rff_sigma2_pxl_ch3)\n\n\n\n\n mmd2loss_feat = get_real_mmd_loss(rff_sigma2, n_labels, args.eval.batch_size)\n # mmd2loss_pixel = get_real_mmd_loss(rff_sigma2_pxl, n_labels, args.eval.batch_size)\n mmd2loss_pixel_ch1 = get_real_mmd_loss(rff_sigma2_pxl_ch1, n_labels, args.eval.batch_size)\n mmd2loss_pixel_ch2 = get_real_mmd_loss(rff_sigma2_pxl_ch2, n_labels, args.eval.batch_size)\n mmd2loss_pixel_ch3 = get_real_mmd_loss(rff_sigma2_pxl_ch3, n_labels, args.eval.batch_size)\n\n # Start training\n for epoch in range(1, args.eval.num_epochs + 1):\n\n # model.eval()\n # netG.train()\n\n for idx, (images, labels) in enumerate(train_loader):\n\n ##########################\n # with torch.no_grad():\n feature_real = model(images.to(args.device)) # size(images) = batch_size x 3 x 32 x 32\n # print('feature shape real', feature_real.shape)\n ##########################\n\n ##########################\n optimizer.zero_grad()\n gen_code, gen_labels = netG.get_code(args.eval.batch_size, device)\n # noise = torch.randn(args.eval.batch_size, nz, 1, 1, device=device)\n syn = netG(gen_code) # batch_size x 3 x 32 x 32\n feature_syn = model(syn) # unsure if I can do this, but let's check later.\n # print('feature shape syn', feature_syn.shape)\n ##########################\n\n # when we compute MMD, we also input the labels.\n loss_latent = mmd2loss_feat(feature_real, labels.to(args.device), feature_syn, gen_labels)\n # loss_pixel = mmd2loss_pixel(torch.reshape(images.to(args.device), (args.eval.batch_size,-1)), labels.to(args.device), torch.reshape(syn, (args.eval.batch_size,-1)), gen_labels)\n\n loss_pixel_ch1 = mmd2loss_pixel_ch1(torch.reshape(images[:,0,:,:].to(args.device), (args.eval.batch_size, -1)),\n labels.to(args.device), torch.reshape(syn[:,0,:,:], (args.eval.batch_size, -1)),\n gen_labels)\n loss_pixel_ch2 = mmd2loss_pixel_ch2(torch.reshape(images[:,1,:,:].to(args.device), (args.eval.batch_size, -1)),\n labels.to(args.device), torch.reshape(syn[:,1,:,:], (args.eval.batch_size, -1)),\n gen_labels)\n loss_pixel_ch3 = mmd2loss_pixel_ch3(torch.reshape(images[:,2,:,:].to(args.device), (args.eval.batch_size, -1)),\n labels.to(args.device), torch.reshape(syn[:,2,:,:], (args.eval.batch_size, -1)),\n gen_labels)\n\n # To-Do: add a hyperparameter to loss_pixel to match the strength of two losses\n # loss = loss_latent + loss_pixel\n\n lamb = 0.1 # pixel loss can be 10 times larger than latent loss, or latent loss is 10 times more sensitive than pixel loss\n loss = loss_latent + lamb * ( loss_pixel_ch1 + loss_pixel_ch2 + loss_pixel_ch3 )\n\n loss.backward()\n optimizer.step()\n\n\n ## sanity check\n # for param_G in netG.parameters():\n # print('parameters of G requires grad: ', param_G.requires_grad)\n # for param in model.parameters():\n # print('parameters of backbone requires grad: ', param.requires_grad)\n\n\n scheduler.step()\n print('Train Epoch: {} [{}/{}]\\tLoss: {:.6f}'.format(epoch, idx * len(images), n_train_data, loss.item()))\n print('loss', loss)\n print('loss_latent', loss_latent)\n # print('loss_pixel', loss_pixel)\n print('loss_pixel_ch1', loss_pixel_ch1)\n print('loss_pixel_ch2', loss_pixel_ch2)\n print('loss_pixel_ch3', loss_pixel_ch3)\n\n # check if parameters of backbone are updated during training.\n # print('PARAMS In BACKBONE')\n # for param in model.parameters():\n # print(torch.sum(param.data))\n\n # print('PARAMS In netG')\n # for param in netG.parameters():\n # print(torch.sum(param.data))\n\n ### Save generated images ###\n if (epoch % 50 ==0)&(epoch!=0):\n save_images(netG, 64, train_loader, epoch, device)\n\n\n\n\n\n\nif __name__ == \"__main__\":\n main(args=get_args())\n\n"
] |
[
[
"torch.randint",
"torch.load",
"torch.no_grad",
"numpy.mean",
"torch.cuda.is_available",
"torch.randn",
"torch.reshape",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.axis",
"torch.optim.lr_scheduler.StepLR",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"torch.nn.ConvTranspose2d",
"torch.set_printoptions",
"torch.nn.DataParallel",
"torch.nn.BatchNorm2d",
"torch.manual_seed",
"torch.nn.Tanh",
"torch.nn.ReLU"
]
] |
TabeaSonnenschein/Spatial-Agent-based-Modeling-of-Urban-Health-Interventions
|
[
"23a207fe74005e45e6349853cdde516ce66647e0"
] |
[
"Natural Language Processing Bibliometrics/CrossRef_XML_mining.py"
] |
[
"import urllib.request\nimport os\nimport pandas as pd\nimport requests\nimport numpy as np\nimport itertools\nimport elsapy\n\nos.chdir(r\"C:\\Users\\Tabea\\Documents\\PhD EXPANSE\\Literature\\WOS_ModalChoice_Ref\")\npaper_DOIs = pd.read_csv(\"WOS_references_search5_metareviews_DOIs.csv\")\nprint(paper_DOIs.iloc[:,0])\n\n\n# ## Load configuration\n# con_file = open(\"config.json\")\n# config = json.load(con_file)\n# con_file.close()\n#\n# ## Initialize client\n# client = ElsClient(config['b4392aff9fe5150839817eb72bc2b70b'])\n# client.inst_token = config['insttoken']\n#\n# ## ScienceDirect (full-text) document example using DOI\n# doi_doc = FullDoc(doi = '10.1016/S1525-1578(10)60571-5')\n# if doi_doc.read(client):\n# print (\"doi_doc.title: \", doi_doc.title)\n# doi_doc.write()\n# else:\n# print (\"Read document failed.\")\n#\n# doi=10.1016/S0014-5793(01)03313-0&httpAccept=text/html&apiKey=b4392aff9fe5150839817eb72bc2b70b\n# token=760D92F8EE4F3B8D114DC8BF760C9EC781A25C0739D519AE653F97CE8BED11B9C65401E6212228C7E0C62989491C07CE\n\npaperLinks = []\nrequiredlicenses = []\nfor paper in paper_DOIs.iloc[:,0]:\n opener = urllib.request.build_opener()\n opener.addheaders = [('Accept', 'application/vnd.crossref.unixsd+xml')]\n try:\n r = opener.open('http://dx.doi.org/' + str(paper))\n except urllib.error.HTTPError or TimeoutError:\n print(\"cannot find: \" + str(paper ))\n else:\n pass\n paperLinks.append(r.info()['Link'])\n array = np.char.split(np.array(r.info()['Link'], dtype=str), sep = \";\").tolist()\n print(array)\n if any(\"xml\" in s for s in array):\n print(\"has xml\")\n xmlLink = np.char.split(np.array([s for s in array if \"xml\" in s][0]), sep = \",\").tolist()[1]\n xmlLink = xmlLink.replace(\"<\", \"\").replace(\">\", \"\")\n if any(\"elsevier\" in s for s in array):\n xmlLink= (xmlLink+\"&apiKey=b4392aff9fe5150839817eb72bc2b70b&insttoken=6ec21df6f452c6f1e466640cd0b51bfd\")\n print(xmlLink)\n xmldoc = requests.get(xmlLink)\n paper_file = (paper.replace(\"/\", \"_\") + '.txt')\n# with open(os.path.join(os.getcwd(),'CrossrefResults/xml/', paper_file), 'wb') as f:\n# f.write(xmldoc.content)\n if any(\"pdf\" in s for s in array):\n print(\"has pdf\")\n if any(\"creativecommons\" in s for s in array):\n pdfLink = np.char.split(np.array([s for s in [s for s in array if \"pdf\" in s] if \"http\" in s]), sep=\",\").tolist()[0][1]\n pdfLink = pdfLink.replace(\"<\", \"\").replace(\">\", \"\")\n print(pdfLink)\n pdf = requests.get(pdfLink)\n paper_file = (paper.replace(\"/\", \"_\") + '.pdf')\n with open(os.path.join(os.getcwd(),'CrossrefResults/pdf/', paper_file), 'wb') as f:\n f.write(pdf.content)\n else:\n license = np.array([s for s in np.array([s for s in array if \"license\" in s]) if \"http\" in s])\n requiredlicenses.append(license)\n print(\"required lincese: \" + str(license))\n if any(\"elsevier\" in s for s in array):\n pdfLink= xmlLink.replace(\"text/xml\", \"application/pdf\")\n print(pdfLink)\n pdf = requests.get(pdfLink)\n paper_file = (paper.replace(\"/\", \"_\") + '.pdf')\n with open(os.path.join(os.getcwd(), 'CrossrefResults/pdf/', paper_file), 'wb') as f:\n f.write(pdf.content)\n\n# csv = os.path.join(os.getcwd(),\"paperlinks.csv\")\n# pd.DataFrame(paperLinks).to_csv(csv)\n\n"
] |
[
[
"numpy.array",
"pandas.read_csv"
]
] |
iOsnaaente/Faculdade_ECA-UFSM
|
[
"aea8b8d66169b073c439b47ad990e45695cbe953",
"aea8b8d66169b073c439b47ad990e45695cbe953"
] |
[
"DeepLearning/01-Backpropagation/BackpropagationMNIST.py",
"Metodos_numericos/MetodosDeGauss/GaussJacobi.py"
] |
[
"# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom struct import unpack\n\ndef read_imgs(img_filename):\n ''' Esta função lê o arquivo de imagens\n da base de dados MNIST\n '''\n\n # Abre o arquivo\n img_file = open(img_filename,'rb')\n\n # Lê o cabeçalho do arquivo\n magic = unpack('>i', img_file.read(4))[0]\n total = unpack('>i', img_file.read(4))[0]\n height = unpack('>i', img_file.read(4))[0]\n width = unpack('>i', img_file.read(4))[0]\n\n # Verifica se o arquivo passa no teste\n # básico (este número deve ser sempre 2051)\n if magic != 2051:\n print('Erro, este arquivo não parece ser um arquivo de imagens MNIST')\n\n # Aqui criamos a array do NumPy que armazenará\n # as imagens\n imgs = np.zeros((total,height,width))\n\n # Nesse laço vamos lendo cada pixel e preenchendo\n # no array\n for k in range(total): # Cada amostra k\n for i in range(height): # Cada linha i\n for j in range(width): # Cada coluna j\n imgs[k,i,j] = ord(img_file.read(1)) # Lemos 1 byte\n \n # Retornamos o array preenchido\n return imgs\n\n\"\"\"De forma semelhante ao realizado acima, aqui abaixo definimos as funções auxiliares para leitura do arquivo de rótulos.\"\"\"\n\ndef read_labels(labels_filename):\n ''' Esta função lê o arquivo de rótulos\n da base de dados MNIST\n '''\n\n # Abre o arquivo\n labels_file = open(labels_filename,'rb')\n\n # Lê o cabeçalho do arquivo\n magic = unpack('>i', labels_file.read(4))[0]\n total = unpack('>i', labels_file.read(4))[0]\n\n # Verifica se o arquivo passa no teste\n # básico (este número deve ser sempre 2051)\n if magic != 2049:\n print('Erro, este arquivo não parece ser um arquivo de imagens MNIST')\n\n # Aqui criamos a array do NumPy que armazenará\n # as imagens\n labels = np.zeros((total))\n\n # Nesse laço vamos lendo cada label e preenchendo\n # no array\n for k in range(total): # Cada amostra k\n labels[k] = ord(labels_file.read(1)) # Lemos 1 byte\n \n # Retornamos o array preenchido\n return labels\n\n\"\"\"Nas linhas abaixo chamamos as função de leitura para carregar as imagens e os respectivos rótulos\"\"\"\n\n# Lê dados de treinamento\nimgs = read_imgs('train-images-idx3-ubyte')\nlabels = read_labels('train-labels-idx1-ubyte')\n\n# Lê dados de validação\nimgs_val = read_imgs('t10k-images-idx3-ubyte')\nlabels_val = read_labels('t10k-labels-idx1-ubyte')\n\nprint('Imagens de treinamento',imgs.shape)\nprint('Etiquetas de treinamento', labels.shape)\nprint('Imagens de validação',imgs_val.shape)\nprint('Etiquetas de validação', labels_val.shape)\n\n\nprint('labels =',labels,'é um array de',len(labels),'elementos')\nprint('labels_val =',labels_val,'é um array de',len(labels_val),'elementos')\n\n\nfrom matplotlib import pyplot as plt\n\n# No laço abaixo sorteamos três amostras aleatórias\n# e mostramos a etiqueta e a respectiva imagem.\nfor _ in range(3):\n # Sorteamos uma amostra\n i = np.random.randint(0,60000)\n # Imprimimos a etiqueta e a respectiva imagem\n print('A imagem abaixo mostra o dígito', labels[i])\n plt.imshow(imgs[i,:,:],cmap='gray')\n plt.show()\n\n\n# Escreva aqui seu código para embaralhar\n# os pares de treinamento. Mantenha os mesmos\n# nomes de variáveis originais.\n\nfrom random import shuffle\n\naux = []\n\nfor i in range(len(imgs)):\n aux.append((imgs[i], labels[i]))\n\nshuffle(aux)\n\n# Importante manter as dimensões das variáveis usadas \nimgs = np.zeros(imgs.shape)\nlabels = np.zeros(labels.shape)\n\nfor i in range(len(imgs)):\n imgs[i] = aux[i][0]\n labels[i] = aux[i][1]\n\n# Escreva aqui seu código para normalizar\n# as imagens dos dados de treinamento, colocando\n# os valores no intervalo de 0 a 1\n\n# Se a imagem tiver mais que 8 bits pode ser passado o parametro de bits\nnorm = lambda pos, bits=8 : pos/((2**bits)-1) \n\n# Normalização dos valores de imgs\nfor i in range(len(imgs)):\n for l in range(len(imgs[i])):\n for w in range(len(imgs[i])):\n imgs[i][l][w] = norm(imgs[i][l][w])\n\n# Normalização dos valores de imgs_val\nfor i in range(len(imgs_val)):\n for l in range(len(imgs_val[i])):\n for w in range(len(imgs_val[i])):\n imgs_val[i][l][w] = norm(imgs_val[i][l][w])\n\n\n# Escreva aqui o código que converte os\n# arrays labels e labels_val para o formato\n# one-hot\n\nZERO = [0,0,0,0,0,0,0,0,0,0]\n\nlab = np.zeros( (len(labels), 10) )\nlab_val = np.zeros( (len(labels_val), 10) )\n\ndef oneHot(pos):\n aux = ZERO.copy()\n aux[int(pos)] = 1\n return aux\n\nfor i in range(len(lab)):\n lab[i] = oneHot( labels[i] )\n\nfor j in range(len(lab_val)):\n lab_val[j] = oneHot(labels_val[j])\n\nlabels = lab.copy()\nlabels_val = lab_val.copy()\n\n\n# Implemente aqui a função softmax\n\nfrom numpy import exp\n\ndef softmax(x): \n return exp(x)/np.sum(exp(x))\n\n\n# Implemente aqui a função sigmoide\n\ndef sigmoid(x):\n return np.array([1/(1+exp(-i)) for i in x])\n\n\n# Implemente aqui, passo a passo, a classe de sua rede neural\n\nclass Perceptron():\n\n def __init__(self):\n \n # Pesos (width) \n self.W1 = np.random.random((256,784)) * 2 - 1\n self.W2 = np.random.random((64, 256)) * 2 - 1\n self.W3 = np.random.random((10, 64 )) * 2 - 1\n \n #Bias\n self.b1 = np.random.random((256,1)) * 2 - 1\n self.b2 = np.random.random((64,1)) * 2 - 1\n self.b3 = np.random.random((10 ,1)) * 2 - 1 \n \n # Passo\n self.eta = 0.001\n \n def forward(self, inputs):\n\n # Garante vetor coluna\n inputs = np.reshape(inputs, (len(inputs),1))\n \n # Sinapse Hidden 1 camada = Entrada * Pesos Input w1 + bias b1\n self.s1 = np.dot(self.W1, inputs) + self.b1\n self.z1 = sigmoid(self.s1)\n\n # Sinapse Hidden 2 camada = saida z1 * Pesos w2 + bias b2\n self.s2 = np.dot(self.W2, self.z1) + self.b2\n self.z2 = sigmoid(self.s2)\n\n # Sinapse Output = Saida z2 * Pesos w3 + bias b3\n self.s3 = np.dot(self.W3, self.z2) + self.b3\n self.z3 = softmax(self.s3)\n \n return self.z3\n\n \n # Implementação do backpropagation \n def backprop(self, X, Y_des ):\n \n self.y = self.forward(X)\n\n # Delta da camada de saida usando Cross Entropy \n # δL = y - y_des\n self.d3 = self.y - Y_des\n\n # δl=W(l+1).T *δ(l+1) ⊙ σ′(sl)\n # σ′(sl) = zl(1−zl)\n \n self.d2 = np.dot(self.W3.T, self.d3) * self.z2 *(1-self.z2)\n self.d1 = np.dot(self.W2.T, self.d2) * self.z1 *(1-self.z1)\n\n\n # Calculo das derivadas parciais de W[n.m] e B[n]\n self.dW3 = np.dot(self.d3, self.z2.T)\n self.db3 = self.d3\n\n self.dW2 = np.dot(self.d2, self.z1.T)\n self.db2 = self.d2\n\n self.dW1 = np.dot(self.d1, X.T)\n self.db1 = self.d1\n\n\n # Passo \n self.eta = 0.1 \n\n # Optimização dos pesos e biases\n self.W1 = self.W1 - self.eta * self.dW1 \n self.W2 = self.W2 - self.eta * self.dW2 \n self.W3 = self.W3 - self.eta * self.dW3 \n \n self.b1 = self.b1 - self.eta * self.db1 \n self.b2 = self.b2 - self.eta * self.db2\n self.b3 = self.b3 - self.eta * self.db3\n\n # Cross Entropy \n self.ce = -np.sum(Y_des * np.log(self.y))\n\n return self.ce\n\n\ndef train_batch(p, X, Y_desired, batch_size=250):\n ''' Esta função faz o treinamento da rede\n neural, percorrendo todo dataset, por\n lotes de 250 amostras\n\n PS.: Aqui os lotes não importam muito\n pois ajustamos os pesos um pouco\n a para cada amostra individual.\n '''\n\n # Total de amostras\n total = X.shape[0]\n\n # Erro global vai ser somado aqui\n Err = 0.0\n\n # Vamos percorrer as amostras em lotes\n for i in range(0,total,batch_size):\n\n # Erro de cada lote\n err_batch = 0.0\n\n # Aqui neste laço vamos treinar o lote\n for j in range(i,i+batch_size):\n\n # Separamos os dados de entrada\n x = np.reshape(X[j,:,:],(784,1))\n\n # Separamos os dados de treinamento correspondentes\n y_desired = np.reshape(Y_desired[j,:],(10,1))\n\n # Calculamos o fator de correção dos pesos e biases\n ce = p.backprop(x, y_desired)\n\n # Computamos o erro do lote\n err_batch += ce\n\n # Normalização do erro do lote\n err_batch /= batch_size\n\n # Soma do erro do lote ao erro global\n # já com fator de normalização\n Err += err_batch / (total/batch_size)\n\n return Err\n\n\nimport time\n\n# Aqui criamos a rede neural\np = Perceptron()\n\n# Nesta lista gravaremos a evolução do erro\n# para plotar num gráfico mais tarde\nErrs = []\n\n# Treinaremos 10 épocas (cada época demora em torno de 2 min)\nfor i in range(10):\n\n # Marcamos o tempo de início para computar o tempo\n # que demoramos para treinar cada época (isso ajuda\n # a estimar o tempo total)\n start_time = time.time()\n\n # Aqui fazemos o treinamento\n Err = train_batch(p, imgs, labels)\n\n # Mostramos os resultados parciais na tela\n print('Elapsed time:', time.time() - start_time, 's', \\\n 'Err:', Err)\n \n # Guardamos o erro calculado em cada época para\n # plotar no gráfico em seguida\n Errs.append(Err)\n\n\"\"\"# Avaliação dos Resultados\"\"\"\n\n# Plotamos o gráfico da evolução do erro\n# no tempo. Esta é a chamada \"curva de\n# aprendizagem\"\n\nplt.plot(Errs)\nplt.show()\n\n\"\"\"A função abaixo serve para calcular a taxa de acerto dessa rede neural\"\"\"\n\ndef accuracy(p, X, Y):\n ''' Esta função vai calcular a taxa\n de acerto da rede neural p\n nos dados fornecidos\n '''\n\n # Contador de acertos\n correct_count = 0\n\n # Total de amostras\n total = X.shape[0]\n\n # Laço vai percorrer todas amostras\n for k in range(total):\n\n # Esta é a resposta que desejamos\n correct_answer = np.argmax(Y[k,:])\n\n # Esta é a resposta encontrada\n guess = np.argmax(p.forward(np.reshape(X[k,:,:],(784,1))))\n\n # Se ambas estiverem corretas\n if correct_answer == guess:\n\n # Contabilizamos como resposta correta\n correct_count += 1\n\n # Aqui retornamos o resultado\n return correct_count / total\n\nprint('Taxa de acerto nos dados de treinamento:', \\\n 100*accuracy(p, imgs, labels), '%')\n\nprint('Taxa de acerto nos dados de validação:', \\\n 100*accuracy(p, imgs_val, labels_val), '%')",
"from numpy import zeros, linspace, array\nfrom numpy.linalg import norm\n\ndef gaussJacobi(A, B, Ap, e):\n C = zeros((len(A), len(A)))\n g = zeros((len(B),1))\n\n # Construir as matrizes C e g \n for i in range(len(A)):\n g[i] = B[i]/A[i][i]\n for j in range(len(A)):\n if i == j :\n C[i][j] = -A[i][j]/A[i][i]\n \n # Testando a condição de parada \n if norm(C, 1) < 1:\n erro = 1 \n # Se quisermos saber quantas iterações foram feitas \n #n = 0\n while erro > e:\n An = C*Ap + g\n erro = norm(An-Ap)/norm(An)\n Ap = An\n #n = n + 1\n \n return Ap \n\n else:\n return None\n\n\nif __name__ == '__main__':\n\n '''\n t = int(input(\"Tamanho M da matriz A[MxM]:\"))\n \n A = [(map(float,input(\"linha \"+str(x+1)+\":\").split())) for i in range(t)]\n A = array(A)\n \n B = [[x] for x in list(map(float,input('Digite os valores do vetor B [Mx1]: ').split()))]\n B = array(B)\n\n Ap = array([x for x in list(map(float,input('Digite os valores do vetor X[Mx1]: ').split()))]) \n \n e = input(\"Entre com o erro máximo tolerado: \")\n '''\n\n t = 8\n A = array([[-10,1,-2,0], [-1,11,-1,3], [2,-1,10,-1], [0,3,-1,8]])\n B = array([-6,25,-11,15])\n Ap = array([0,0,0,0])\n e = 0.001 \n \n valores = gaussJacobi(A, B, Ap, e)\n\n if valores is not None:\n \n print('Os valores convergem no ponto ', end='')\n str_append = ''\n soma = 0 \n\n for i in range (len(valores)):\n str_append = str_append + \"x%i: %10.8f\" %(i, A[0][i]*valores[i])\n soma = soma + A[0][i]*valores[i]\n \n print(' y(x)=%10.8f onde:' %soma)\n print(str_append)\n \n else:\n print('Não há convergência!!!')"
] |
[
[
"numpy.dot",
"matplotlib.pyplot.imshow",
"numpy.log",
"numpy.random.random",
"numpy.reshape",
"matplotlib.pyplot.plot",
"numpy.argmax",
"numpy.exp",
"matplotlib.pyplot.show",
"numpy.zeros",
"numpy.random.randint"
],
[
"numpy.array",
"numpy.linalg.norm"
]
] |
0shimax/chainer-feedbacknet
|
[
"0a4660ca194ad2a1bd26f3b3728fa332b7a50811"
] |
[
"src/common/image_processor/feature_extractor/nucleus_diamiters.py"
] |
[
"import sys, os\nsys.path.append('./src/common/image_processor/feature_extractor')\nimport cv2\nimport numpy as np\nimport pandas as pd\nfrom operator import itemgetter\nfrom collections import defaultdict\nfrom feature_extractor_utils import (show_image,\n smooth_contour,\n compute_erosioned_image)\n\n\ndef judge_max_min(max_val, min_val, candidate_val):\n if candidate_val is not None:\n max_val = candidate_val if candidate_val>max_val else max_val\n min_val = candidate_val if candidate_val<min_val else min_val\n return min_val, max_val\n\n\ndef judge_min(min_val, candidate_val):\n if candidate_val is not None:\n min_val = candidate_val if candidate_val<min_val else min_val\n return min_val\n\n\ndef vertex(major_axis):\n if major_axis<100:\n return 5\n else:\n return 10\n\n\ndef calculate_ellipse_axis(contour):\n ellipse = cv2.fitEllipse(contour)\n major_axis = max(ellipse[1][0], ellipse[1][1])\n minor_axis = min(ellipse[1][0], ellipse[1][1])\n return minor_axis, major_axis\n\n\ndef compute_max_min_diamiter(scanning_axis, measure_axis, scan_gap=10):\n left_top = (scanning_axis.min(), measure_axis.min())\n right_bottom = (scanning_axis.max(), measure_axis.max())\n mergin = (right_bottom[0] - left_top[0])//10\n pre_point = None\n max_val, min_val = 0, float('inf')\n for x in range(left_top[0]+mergin, right_bottom[0]-mergin+1):\n idx = np.where((scanning_axis>=x-scan_gap)&(scanning_axis<=x+scan_gap))[0]\n if len(idx)%2!=0: continue\n for i_idx in range(0, len(idx),2):\n start, end = idx[i_idx], idx[i_idx+1]\n val = np.abs(measure_axis[start]-measure_axis[end])\n if val<10: continue\n min_val, max_val = judge_max_min(max_val, min_val, val)\n return min_val, max_val,\n\n\ndef calculate_one_cnt_diameter(min_v, max_v, contour, major_axis_sub, \\\n low_threshold, high_threshold, src_image=None):\n cnt_size = contour.size\n if cnt_size < 10: # specification of openCV\n return min_v, max_v\n\n try:\n contour = smooth_contour(contour)\n # fitting\n minor_axis, major_axis = calculate_ellipse_axis(contour)\n except:\n # fitting\n minor_axis, major_axis = calculate_ellipse_axis(contour)\n return int(minor_axis), int(major_axis)\n\n # excluding axis too small or too big\n if major_axis<low_threshold-major_axis_sub or \\\n major_axis>high_threshold:\n return min_v, max_v\n\n contour = contour.reshape((contour.shape[0], 2))\n if src_image is not None:\n cv2.drawContours(src_image,[contour],-1,(0,255,0),3)\n show_image(src_image)\n x_len = max(contour[:,0]) - min(contour[:,0])\n y_len = max(contour[:,1]) - min(contour[:,1])\n if y_len >= x_len:\n contour_y = np.array(sorted(contour, key=itemgetter(1,0)))\n # t_min_v, t_max_v = compute_max_min_diamiter(contour_y, scan_axis='x')\n t_min_v, t_max_v = compute_max_min_diamiter(contour_y[:,1], contour_y[:,0])\n else:\n contour_x = np.array(sorted(contour, key=itemgetter(0,1)))\n # t_min_v, t_max_v = compute_max_min_diamiter(contour_x, scan_axis='y')\n t_min_v, t_max_v = compute_max_min_diamiter(contour_x[:,0], contour_x[:,1])\n min_v, max_v = judge_max_min(max_v, min_v, t_min_v)\n min_v, max_v = judge_max_min(max_v, min_v, t_max_v)\n return min_v, max_v\n\n\ndef compute_diameter(img, src_image=None, threshold_schale=100,\n low_threshold=95, high_threshold=300):\n h, w = img.shape\n # find corner\n contours = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[1]\n\n # filtered with area over (all area / 100 )\n area_th = h*w/threshold_schale\n contours_large = list(filter(lambda c:cv2.contourArea(c) > area_th, contours))\n\n result = src_image.copy() if src_image is not None else None\n min_v, max_v = float('inf'), 0\n major_axis_sub = 0\n while max_v==0 and major_axis_sub<low_threshold-1:\n for contour in contours_large:\n min_v, max_v = calculate_one_cnt_diameter(min_v, max_v, contour, \\\n major_axis_sub, low_threshold, \\\n high_threshold, src_image=src_image)\n major_axis_sub += 10\n max_diamiter = max(max_v, min_v)\n if max_diamiter==float('inf'):\n max_diamiter = 0\n min_diamiter = min(max_v, min_v)\n return min_diamiter, max_diamiter,\n\n\ndef compute_nucleus_diameter(src_image, threshold_schale=100, debug=False):\n image = compute_erosioned_image(src_image, threshold_schale, debug)\n if debug:\n return compute_diameter(image, src_image, threshold_schale=threshold_schale)\n else:\n return compute_diameter(image, threshold_schale=threshold_schale)\n\nif __name__=='__main__':\n import subprocess\n\n image_dir = './data/6k_rivised'\n # image_dir = './data/20170117_revised_13000_Images'\n # image_dir = './data/sys_val400'\n # image_dir = './data/sys_val28'\n\n cmd = 'find {} -name \"*.jpg\"'.format(image_dir)\n process = subprocess.Popen(cmd,\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,)\n b_out, _ = process.communicate()\n out = b_out.decode('utf-8').rstrip().split('\\n')\n\n dict_results = defaultdict(list)\n for image_path in out:\n # print(image_path)\n label = image_path.split('/')[-1].split('_')[0]\n image = cv2.imread(image_path)\n min_diam, max_diam = \\\n compute_nucleus_diameter(image, threshold_schale=100, debug=False)\n dict_results['label'].append(label)\n dict_results['min_diam'].append(min_diam)\n dict_results['max_diam'].append(max_diam)\n # print(label, min_diam, max_diam)\n\n data = pd.DataFrame(dict_results)\n print(data.groupby('label').agg([np.mean, np.median]))\n"
] |
[
[
"numpy.where",
"numpy.abs",
"pandas.DataFrame"
]
] |
AzNOAOTares/plasticc
|
[
"03f8995673b6f09156783d35c7d63f34729d0610"
] |
[
"plasticc/get_data.py"
] |
[
"# -*- coding: UTF-8 -*-\n\"\"\"\nGet PLASTICC data from SQL database\n\"\"\"\nimport sys\nimport os\nimport numpy as np\nimport warnings\nimport argparse\nimport pandas as pd\nimport astropy.table as at\nimport astropy.io.fits as afits\nfrom collections import OrderedDict\nimport database\nimport helpers\n\nROOT_DIR = os.getenv('PLASTICC_DIR')\nDATA_DIR = os.path.join(ROOT_DIR, 'plasticc_data')\n\n\ndef parse_getdata_options(argv=None):\n if argv is None:\n argv = sys.argv[1:]\n\n def str2bool(v):\n return v.lower() in (\"yes\", \"true\", \"t\", \"1\")\n\n def_sql_wildcard = '%'\n parser = argparse.ArgumentParser(description=\"Get options to the GetData structure\")\n group = parser.add_mutually_exclusive_group(required=False)\n parser.register('type', 'bool', str2bool)\n parser.add_argument('--data_release', required=True, help='PLAsTiCC data release index table to process')\n field_choices = ('WFD', 'DDF', '%')\n parser.add_argument('--field', required=False, default='DDF', type=str.upper, choices=field_choices, \\\n help='PLAsTiCC field to process')\n\n type_mapping = GetData.get_sntypes()\n inverse_mapping = {v: k for k, v in type_mapping.items()}\n\n model_choices = list(type_mapping.keys()).append('%')\n model_name_choices = list(type_mapping.values()).append('%')\n group.add_argument('--model', required=False, action=\"store\", default=def_sql_wildcard, choices=model_choices, \\\n help='PLAsTiCC model to process')\n group.add_argument('--model_name', required=False, action=\"store\", default=def_sql_wildcard,\n choices=model_name_choices, \\\n help='PLAsTiCC model name to process')\n parser.add_argument('--base', required=False, default=def_sql_wildcard,\n help='PLAsTiCC model base filename (probably not a good idea to touch this)')\n parser.add_argument('--snid', required=False, default=def_sql_wildcard,\n help='PLAsTiCC object ID number (useful for debugging/testing)')\n parser.add_argument('--limit', required=False, type=int, default=None,\n help='Limit the number of returned results from the MySQL index')\n parser.add_argument('--shuffle', required=False, type=\"bool\", default=\"False\",\n help='Shuffle the returned results from the MySQL index')\n parser.add_argument('--sort', required=False, type=\"bool\", default=\"True\",\n help='Sort the returned results from the MySQL index')\n parser.add_argument('--survey', required=False, default=\"LSST\", \n help=\"Specify the survey to process\")\n parser.add_argument('--offset', required=False, default=None, type=int,\n help='Return the MySQL results AFTER offset rows')\n parser.add_argument('--extrasql', required=False, default=None,\n help='Extra SQL for the selection function - enter as quoted string - used as is')\n args = parser.parse_args(args=argv)\n\n out = vars(args)\n model_name = out.pop('model_name')\n model = out.pop('model')\n if model_name == '%':\n if model == '%':\n out['model'] = '%'\n else:\n out['model'] = model\n else:\n this_model = inverse_mapping.get(model_name)\n if model == '%':\n out['model'] = this_model\n else:\n if this_model == model:\n out['model'] = this_model\n else:\n out['model'] = model\n return out\n\n\nclass GetData(object):\n \"\"\"\n Class to access the ANTARES parsed PLaSTiCC index and light curve data\n \"\"\"\n\n def __init__(self, data_release):\n self.data_release = \"release_{}\".format(data_release)\n self.phot_fields = ['MJD', 'FLT', 'FLUXCAL', 'FLUXCALERR', 'ZEROPT', 'PHOTFLAG']\n self.phot_fields_dtypes = {'FLT': np.str_, 'PHOTFLAG': np.int_}\n\n def get_phot_fields(self):\n \"\"\"\n list of the photometry column names and a dictionary of NON-FLOAT\n columns\n\n For the default columns, this is only FLT\n \"\"\"\n return list(self.phot_fields), dict(self.phot_fields_dtypes)\n\n def set_phot_fields(self, fields, dtypes):\n \"\"\"\n set the list of photometry column fields to retrieve and a dictionary\n of data types for NON-FLOAT columns hashed by column name in the PHOT.FITS\n\n i.e. if your column is a float, don't even bother listing it\n\n Can be used to retrieve custom columns from the PHOT.FITS\n Kinda kludgey - se with caution\n \"\"\"\n self.phot_fields = list(fields)\n self.phot_fields_dtypes = dict(dtypes)\n\n def get_object_ids(self):\n \"\"\" Get list of all object ids \"\"\"\n obj_ids = database.exec_sql_query(\"SELECT objid FROM {0};\".format(self.data_release))\n return obj_ids\n\n def get_column_for_sntype(self, column_name, sntype, field='%'):\n \"\"\" Get an sql column for a particular sntype class\n\n Parameters\n ----------\n column_name : str\n column name. E.g. column_name='peakmjd'\n sntype : int\n sntype number. E.g. sntype=4\n field : str, optional\n The field name. E.g. field='DDF' or field='WFD'. The default is '%' indicating that all fields will be included.\n\n Return\n -------\n column_out: list\n A list containing all the entire column for a particular sntype class\n \"\"\"\n try:\n column_out = database.exec_sql_query(\n \"SELECT {0} FROM {1} WHERE objid LIKE '{2}%' AND sntype={3};\".format(column_name, self.data_release,\n field, sntype))\n column_out = np.array(column_out)[:, 0]\n except IndexError:\n print(\"No data in the database satisfy the given arguments. field: {}, sntype: {}\".format(field, sntype))\n return []\n return column_out\n\n def get_photfile_for_objid(self, objid):\n \"\"\"\n Returns the phot file for the object ID\n \"\"\"\n field, model, base, snid = objid.split('_')\n if field == 'IDEAL':\n filename = \"{0}_MODEL{1}/{0}_{2}_PHOT.FITS\".format(field, model, base)\n elif field == 'MSIP':\n filename = \"ZTF_{0}_MODEL{1}/ZTF_{0}_{2}_PHOT.FITS\".format(field, model, base)\n else:\n filename = \"LSST_{0}_MODEL{1}/LSST_{0}_{2}_PHOT.FITS\".format(field, model, base)\n phot_file = os.path.join(DATA_DIR, self.data_release.replace('release_', ''), filename)\n if not os.path.exists(phot_file):\n phot_file = phot_file + '.gz'\n return phot_file\n\n\n\n def get_light_curve(self, objid, ptrobs_min, ptrobs_max, standard_zpt=27.5):\n \"\"\" Get lightcurve from fits file\n\n Parameters\n ----------\n objid : str\n The object ID. E.g. objid='DDF_04_NONIa-0004_87287'\n ptrobs_min : int\n Min index of object in _PHOT.FITS.\n ptrobs_max : int\n Max index of object in _PHOT.FITS.\n\n Return\n -------\n phot_out: pandas DataFrame\n A DataFrame containing the MJD, FLT, FLUXCAL, FLUXCALERR, ZEROPT seperated by each filter.\n E.g. Access the magnitude in the z filter with phot_out['z']['MAG'].\n \"\"\"\n phot_file = self.get_photfile_for_objid(objid)\n\n try:\n phot_HDU = afits.open(phot_file, memmap=True)\n except Exception as e:\n message = f'Could not open photometry file {phot_file}'\n raise RuntimeError(message)\n\n phot_data = phot_HDU[1].data[ptrobs_min - 1:ptrobs_max]\n\n phot_dict = OrderedDict()\n filters = list(set(phot_data['FLT'])) # e.g. ['i', 'r', 'Y', 'u', 'g', 'z']\n dtypes = dict(self.phot_fields_dtypes)\n for f in filters:\n fIndexes = np.where(phot_data['FLT'] == f)[0]\n phot_dict[f] = OrderedDict()\n for pfield in self.phot_fields:\n if pfield == 'ZEROPT':\n phot_dict[f][pfield] = np.repeat(standard_zpt, len(fIndexes))\n elif pfield == 'FLT':\n true_zpt = phot_data['ZEROPT'][fIndexes]\n nobs = len(true_zpt)\n phot_dict[f][pfield] = np.repeat(f.strip(), nobs)\n else:\n phot_dict[f][pfield] = phot_data[pfield][fIndexes]\n\n if not pfield in dtypes:\n dtypes[pfield] = np.float64\n\n phot_out = pd.DataFrame(phot_dict)\n phot_HDU.close()\n del phot_HDU[1].data\n return phot_out\n\n def get_light_curve_array(self, objid, ptrobs_min, ptrobs_max, standard_zpt=27.5):\n \"\"\" Get lightcurve from fits file as an array - avoid some Pandas overhead\n\n Parameters\n ----------\n objid : str\n The object ID. E.g. objid='DDF_04_NONIa-0004_87287'\n ptrobs_min : int\n Min index of object in _PHOT.FITS.\n ptrobs_max : int\n Max index of object in _PHOT.FITS.\n\n Return\n -------\n phot_out: pandas DataFrame\n A DataFrame containing the MJD, FLT, FLUXCAL, FLUXCALERR, ZEROPT seperated by each filter.\n E.g. Access the magnitude in the z filter with phot_out['z']['MAG'].\n \"\"\"\n phot_file = self.get_photfile_for_objid(objid)\n\n try:\n phot_HDU = afits.open(phot_file, memmap=True)\n except Exception as e:\n message = f'Could not open photometry file {phot_file}'\n raise RuntimeError(message)\n\n phot_data = phot_HDU[1].data[ptrobs_min - 1:ptrobs_max]\n phot_data = at.Table(phot_data)\n return phot_data\n\n\n @staticmethod\n def convert_pandas_lc_to_recarray_lc(phot, passbands=('u', 'g', 'r', 'i', 'z', 'Y')):\n \"\"\"\n ANTARES_object not Pandas format broken up by passband\n TODO: This is ugly - just have an option for get_lcs_data to return one or the other\n \"\"\"\n pbs = passbands\n # name mapping for the defaults in phot_fields\n # any other column is going to become just lowercase it's current name\n name_map = {'FLUXCAL': 'flux', 'FLUXCALERR': 'dflux', 'ZEROPT': 'zpt',\\\n 'FLT': 'pb', 'MJD': 'mjd', 'PHOTFLAG': 'photflag'}\n\n out = None\n out_names = None\n\n for this_pb in phot:\n # do we know what this passband is\n # this is just a sanity test in case we accidentally retrieve dummy entries with passband = -9\n if this_pb not in pbs:\n continue\n\n this_pb_lc = phot.get(this_pb)\n if this_pb_lc is None:\n continue\n\n if out is None:\n out = np.rec.fromarrays(list(this_pb_lc))\n if out_names is None:\n out_names = list(this_pb_lc.axes[0])\n out_names = [name_map.get(x, x.lower()) for x in out_names]\n else:\n temp = np.rec.fromarrays(list(this_pb_lc))\n out = np.concatenate((out, temp), axis=-1)\n\n out.dtype.names = out_names\n return out\n\n @staticmethod\n def get_sntypes():\n return helpers.get_sntypes()\n\n @staticmethod\n def aggregate_sntypes(reverse=False):\n return helpers.aggregate_sntypes(reverse=reverse)\n\n def get_avail_sntypes(self):\n \"\"\" Returns a list of the different transient classes in the database. \"\"\"\n sntypes = database.exec_sql_query(\"SELECT DISTINCT sntype FROM {};\".format(self.data_release))\n sntypes_map = self.get_sntypes()\n return sorted([sntype[0] for sntype in sntypes]), sntypes_map\n\n def get_lcs_headers(self, columns=None, field='%', model='%', base='%', snid='%', extrasql='', survey='LSST',\n get_num_lightcurves=False, limit=None, shuffle=False, sort=True, offset=0, big=False):\n \"\"\" Gets the header data given specific conditions.\n\n Parameters\n ----------\n columns : list\n A list of strings of the names of the columns you want to retrieve from the database.\n You must at least include ['objid', 'ptrobs_min', 'ptrobs_max'] at the beginning of the input list.\n E.g. columns=['objid', 'ptrobs_min', 'ptrobs_max', 'sntype', 'peakmjd'].\n field : str, optional\n The field name. E.g. field='DDF' or field='WFD'. The default is '%' indicating that all fields will be included.\n model : str, optional\n The model number. E.g. model='04'. The default is '%' indicating that all model numbers will be included.\n base : str, optional\n The base name. E.g. base='NONIa'. The default is '%' indicating that all base names will be included.\n snid : str, optional\n The transient id. E.g. snid='87287'. The default is '%' indicating that all snids will be included.\n get_num_lightcurves : boolean, optional\n If this is True, then the return value is just a single iteration generator stating the number of\n light curves that satisfied the given conditions.\n limit : int, optional \n Limit the results to this number (> 0)\n shuffle : bool, optional\n Randomize the order of the results - not allowed with `sort`\n sort : bool, optional\n Order the results by objid - overrides `shuffle` if both are set\n offset : int, optional\n Start returning MySQL results from this row number offset\n big : bool, optional\n If True, use a generator to retrieve results - cannot be used with\n get_num_lightcurves since generators have no length\n Return\n -------\n result: tuple or int\n \"\"\"\n if columns is None:\n columns = ['objid', 'ptrobs_min', 'ptrobs_max']\n\n if get_num_lightcurves:\n columns = ['COUNT(objid)', ]\n big = False\n\n try:\n limit = int(limit)\n if limit <= 0:\n raise RuntimeError('prat')\n except Exception as e:\n limit = None\n\n try:\n offset = int(offset)\n if offset <= 0:\n raise RuntimeError('prat')\n except Exception as e:\n offset = None\n\n if limit is not None and shuffle is False and sort is False:\n sort = True\n\n extrasql_command = '' if extrasql is None else extrasql\n limit_command = '' if limit is None else \" LIMIT {}\".format(limit)\n offset_command = '' if offset is None else \" OFFSET {}\".format(offset)\n if model != '%':\n model = \"{:02n}\".format(int(model))\n\n if sort is True and shuffle is True:\n message = 'Cannot sort and shuffle at the same time! That makes no sense!'\n shuffle = False\n warnings.warn(message, RuntimeWarning)\n\n shuffle_command = '' if shuffle is False else \" ORDER BY RAND()\"\n sort_command = '' if sort is False else ' ORDER BY objid'\n extra_command = ''.join([extrasql_command, sort_command, shuffle_command, limit_command, offset_command])\n\n query = \"SELECT {} FROM {} WHERE objid LIKE '{}_{}_{}_{}' {};\".format(', '.join(columns), \\\n self.data_release, field, model, base,\n snid, extra_command)\n if big:\n for result in database.exec_big_sql_query(query):\n yield result\n else:\n header = database.exec_sql_query(query)\n if get_num_lightcurves:\n num_lightcurves = int(header[0][0])\n yield num_lightcurves\n else:\n num_lightcurves = len(header)\n\n if num_lightcurves > 0:\n for result in header:\n yield result\n else:\n print(\"No light curves in the database satisfy the given arguments. \"\n \"field: {}, model: {}, base: {}, snid: {}\".format(field, model, base, snid))\n return\n\n def get_lcs_data(self, columns=None, field='%', model='%', base='%', snid='%', survey='LSST',\\\n limit=None, shuffle=False, sort=True, offset=0, big=False, extrasql=''):\n \"\"\" Gets the light curve and header data given specific conditions. Returns a generator of LC info.\n\n Parameters\n ----------\n columns : list\n A list of strings of the names of the columns you want to retrieve from the database.\n You must at least include ['objid', 'ptrobs_min', 'ptrobs_max'] at the beginning of the input list.\n E.g. columns=['objid', 'ptrobs_min', 'ptrobs_max', 'peakmjd'].\n field : str, optional\n The field name. E.g. field='DDF' or field='WFD'. The default is '%' indicating that all fields will be included.\n model : str, optional\n The model number. E.g. model='04'. The default is '%' indicating that all model numbers will be included.\n base : str, optional\n The base name. E.g. base='NONIa'. The default is '%' indicating that all base names will be included.\n snid : str, optional\n The transient id. E.g. snid='87287'. The default is '%' indicating that all snids will be included.\n limit : int, optional \n Limit the results to this number (> 0)\n shuffle : bool, optional\n Randomize the order of the results - not allowed with `sort`\n sort : bool, optional\n Order the results by objid - overrides `shuffle` if both are set\n offset : int, optional\n Start returning MySQL results from this row number offset (> 0)\n big : bool, optional\n If True, use a generator to retrieve results - cannot be used with\n get_num_lightcurves since generators have no length\n \n\n Return\n -------\n result: tuple\n A generator tuple containing (objid, ptrobs_min, ptrobs_max, mwebv, mwebv_err, z, zerr, peak_mjd)\n phot_data : pandas DataFrame\n A generator containing a DataFrame with the MJD, FLT, MAG, MAGERR as rows and the the filter names as columns.\n E.g. Access the magnitude in the z filter with phot_data['z']['MAG'].\n \"\"\"\n\n header = self.get_lcs_headers(columns=columns, field=field, \\\n model=model, base=base, snid=snid, \\\n limit=limit, sort=sort, shuffle=shuffle, offset=offset, \\\n big=big, extrasql=extrasql)\n\n for h in header:\n objid, ptrobs_min, ptrobs_max = h[0:3]\n phot_data = self.get_light_curve(objid, ptrobs_min, ptrobs_max)\n yield h, phot_data\n\n"
] |
[
[
"numpy.concatenate",
"numpy.array",
"numpy.where",
"pandas.DataFrame"
]
] |
pastas/pastastore
|
[
"82eaf25ade96e1a09871390745b3cf441f8ef264"
] |
[
"tests/test_005_benchmark.py"
] |
[
"import numpy as np\nimport pandas as pd\nimport pastastore as pst\nimport pytest\n\n# %% write\n\n# data\ndata = np.random.random_sample(int(1e5))\ns = pd.Series(index=pd.date_range(\"1970\", periods=1e5, freq=\"H\"),\n data=data)\nmetadata = {\"x\": 100000., \"y\": 300000.}\n\n\ndef series_write(conn):\n conn.add_oseries(s, \"oseries1\", metadata=metadata, overwrite=True)\n\n\n# @pytest.mark.benchmark(group=\"write_series\")\n# def test_benchmark_write_series_dict(benchmark):\n# conn = pst.DictConnector(\"test\")\n# _ = benchmark(series_write, conn=conn)\n# return\n\n\[email protected](group=\"write_series\")\ndef test_benchmark_write_series_pas(benchmark):\n conn = pst.PasConnector(\"test\", \"./tests/data/pas\")\n _ = benchmark(series_write, conn=conn)\n return\n\n\[email protected](group=\"write_series\")\ndef test_benchmark_write_series_pystore(benchmark):\n path = \"./tests/data/pystore\"\n conn = pst.PystoreConnector(\"test\", path)\n _ = benchmark(series_write, conn=conn)\n return\n\n\[email protected](group=\"write_series\")\ndef test_benchmark_write_series_arctic(benchmark):\n connstr = \"mongodb://localhost:27017/\"\n conn = pst.ArcticConnector(\"test\", connstr)\n _ = benchmark(series_write, conn=conn)\n return\n\n# %% read\n\n\ndef series_read(conn):\n _ = conn.get_oseries(\"oseries1\")\n\n# @pytest.mark.benchmark(group=\"read_series\")\n# def test_benchmark_write_series_dict(benchmark):\n# conn = pst.DictConnector(\"test\")\n# _ = benchmark(series_read, conn=conn)\n# return\n\n\[email protected](group=\"read_series\")\ndef test_benchmark_read_series_pas(benchmark):\n conn = pst.PasConnector(\"test\", \"./tests/data/pas\")\n _ = benchmark(series_read, conn=conn)\n return\n\n\[email protected](group=\"read_series\")\ndef test_benchmark_read_series_pystore(benchmark):\n path = \"./tests/data/pystore\"\n conn = pst.PystoreConnector(\"test\", path)\n _ = benchmark(series_read, conn=conn)\n return\n\n\[email protected](group=\"read_series\")\ndef test_benchmark_read_series_arctic(benchmark):\n connstr = \"mongodb://localhost:27017/\"\n conn = pst.ArcticConnector(\"test\", connstr)\n _ = benchmark(series_read, conn=conn)\n return\n\n\n# %% write model\n\ndef build_model(conn):\n\n store = pst.PastaStore(\"test\", conn)\n\n # oseries nb1\n if \"oseries_nb1\" not in store.oseries.index:\n o = pd.read_csv(\"./tests/data/head_nb1.csv\", index_col=0,\n parse_dates=True)\n store.add_oseries(o, \"oseries_nb1\", metadata={\"x\": 100300,\n \"y\": 400400})\n\n # prec nb1\n if \"prec_nb1\" not in store.stresses.index:\n s = pd.read_csv(\"./tests/data/rain_nb1.csv\",\n index_col=0, parse_dates=True)\n store.add_stress(s, \"prec_nb1\", kind=\"prec\", metadata={\"x\": 100300,\n \"y\": 400400})\n\n # evap nb1\n if \"evap_nb1\" not in store.stresses.index:\n s = pd.read_csv(\"./tests/data/evap_nb1.csv\",\n index_col=0, parse_dates=True)\n store.add_stress(s, \"evap_nb1\", kind=\"evap\", metadata={\"x\": 100300,\n \"y\": 400400})\n\n ml = store.create_model(\"oseries_nb1\", add_recharge=True)\n\n return ml\n\n\ndef write_model(conn, ml):\n conn.add_model(ml, overwrite=True)\n\n\n# @pytest.mark.benchmark(group=\"write_model\")\n# def test_benchmark_write_model_dict(benchmark):\n# conn = pst.DictConnector(\"test\")\n# ml = build_model(conn)\n# _ = benchmark(write_model, conn=conn, ml=ml)\n# return\n\n\[email protected](group=\"write_model\")\ndef test_benchmark_write_model_pas(benchmark):\n conn = pst.PasConnector(\"test\", \"./tests/data/pas\")\n ml = build_model(conn)\n _ = benchmark(write_model, conn=conn, ml=ml)\n return\n\n\[email protected](group=\"write_model\")\ndef test_benchmark_write_model_pystore(benchmark):\n path = \"./tests/data/pystore\"\n conn = pst.PystoreConnector(\"test\", path)\n ml = build_model(conn)\n _ = benchmark(write_model, conn=conn, ml=ml)\n return\n\n\[email protected](group=\"write_model\")\ndef test_benchmark_write_model_arctic(benchmark):\n connstr = \"mongodb://localhost:27017/\"\n conn = pst.ArcticConnector(\"test\", connstr)\n ml = build_model(conn)\n _ = benchmark(write_model, conn=conn, ml=ml)\n return\n\n# %%\n\n\ndef write_model_checkts(conn, ml):\n conn.check_model_series_values = True\n conn.add_model(ml, overwrite=True)\n\n\[email protected](group=\"write_model\")\ndef test_benchmark_write_model_checkts_pas(benchmark):\n conn = pst.PasConnector(\"test\", \"./tests/data/pas\")\n ml = build_model(conn)\n _ = benchmark(write_model_checkts, conn=conn, ml=ml)\n return\n\n\[email protected](group=\"write_model\")\ndef test_benchmark_write_model_checkts_pystore(benchmark):\n path = \"./tests/data/pystore\"\n conn = pst.PystoreConnector(\"test\", path)\n ml = build_model(conn)\n _ = benchmark(write_model_checkts, conn=conn, ml=ml)\n return\n\n\[email protected](group=\"write_model\")\ndef test_benchmark_write_model_checkts_arctic(benchmark):\n connstr = \"mongodb://localhost:27017/\"\n conn = pst.ArcticConnector(\"test\", connstr)\n ml = build_model(conn)\n _ = benchmark(write_model_checkts, conn=conn, ml=ml)\n return\n# %% read model\n\n\ndef read_model(conn):\n ml = conn.get_models(\"oseries_nb1\")\n return ml\n\n# @pytest.mark.benchmark(group=\"read_model\")\n# def test_benchmark_read_model_dict(benchmark):\n# conn = pst.DictConnector(\"test\")\n# _ = benchmark(read_model, conn=conn, ml=ml)\n# return\n\n\[email protected](group=\"read_model\")\ndef test_benchmark_read_model_pas(benchmark):\n conn = pst.PasConnector(\"test\", \"./tests/data/pas\")\n _ = benchmark(read_model, conn=conn)\n pst.util.delete_pas_connector(conn)\n return\n\n\[email protected](group=\"read_model\")\ndef test_benchmark_read_model_pystore(benchmark):\n path = \"./tests/data/pystore\"\n conn = pst.PystoreConnector(\"test\", path)\n _ = benchmark(read_model, conn=conn)\n pst.util.delete_pystore_connector(conn=conn)\n return\n\n\[email protected](group=\"read_model\")\ndef test_benchmark_read_model_arctic(benchmark):\n connstr = \"mongodb://localhost:27017/\"\n conn = pst.ArcticConnector(\"test\", connstr)\n _ = benchmark(read_model, conn=conn)\n pst.util.delete_arctic_connector(conn=conn)\n return\n"
] |
[
[
"pandas.read_csv",
"pandas.date_range"
]
] |
PRIS-CV/BSNet
|
[
"993ce867aadc73aea33139751fd4454033cde9dd"
] |
[
"methods/meta_template.py"
] |
[
"import backbone\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport numpy as np\nimport torch.nn.functional as F\nimport utils\nfrom abc import abstractmethod\n\nclass MetaTemplate(nn.Module):\n def __init__(self, model_func, n_way, n_support, change_way = True):\n super(MetaTemplate, self).__init__()\n self.n_way = n_way\n self.n_support = n_support\n self.n_query = -1 #(change depends on input) \n self.feature = model_func()\n self.feat_dim = self.feature.final_feat_dim\n self.change_way = change_way #some methods allow different_way classification during training and test\n\n @abstractmethod\n def set_forward(self,x,is_feature):\n pass\n\n @abstractmethod\n def set_forward_loss(self, x):\n pass\n\n def forward(self,x):\n out = self.feature.forward(x)\n return out\n\n def parse_feature(self,x,is_feature):\n x = Variable(x.cuda())\n if is_feature:\n z_all = x\n else:\n x = x.contiguous().view( self.n_way * (self.n_support + self.n_query), *x.size()[2:]) \n z_all = self.feature.forward(x)\n z_all = z_all.view( self.n_way, self.n_support + self.n_query, -1)\n z_support = z_all[:, :self.n_support]\n z_query = z_all[:, self.n_support:]\n\n return z_support, z_query\n\n def correct(self, x): \n\n if self.__class__.__name__ == \"OurNet\":\n relation_score, cosine = self.set_forward(x)\n scores = (relation_score + cosine)/2.\n\n else:\n scores = self.set_forward(x)\n\n\n y_query = np.repeat(range( self.n_way ), self.n_query )\n\n topk_scores, topk_labels = scores.data.topk(1, 1, True, True)\n topk_ind = topk_labels.cpu().numpy()\n top1_correct = np.sum(topk_ind[:,0] == y_query)\n return float(top1_correct), len(y_query)\n\n def train_loop(self, epoch, train_loader, optimizer ):\n print_freq = 10\n\n avg_loss=0\n for i, (x,_ ) in enumerate(train_loader):\n self.n_query = x.size(1) - self.n_support \n if self.change_way:\n self.n_way = x.size(0)\n optimizer.zero_grad()\n loss = self.set_forward_loss( x )\n loss.backward()\n optimizer.step()\n avg_loss = avg_loss+loss.item()\n\n if i % print_freq==0:\n #print(optimizer.state_dict()['param_groups'][0]['lr'])\n print('Epoch {:d} | Batch {:d}/{:d} | Loss {:f}'.format(epoch, i, len(train_loader), avg_loss/float(i+1)))\n\n def test_loop(self, test_loader, record = None):\n correct =0\n count = 0\n acc_all = []\n \n iter_num = len(test_loader) \n for i, (x,_) in enumerate(test_loader):\n self.n_query = x.size(1) - self.n_support\n if self.change_way:\n self.n_way = x.size(0)\n correct_this, count_this = self.correct(x)\n acc_all.append(correct_this/ count_this*100 )\n\n acc_all = np.asarray(acc_all)\n acc_mean = np.mean(acc_all)\n acc_std = np.std(acc_all)\n print('%d Test Acc = %4.2f%% +- %4.2f%%' %(iter_num, acc_mean, 1.96* acc_std/np.sqrt(iter_num)))\n\n return acc_mean\n\n\n"
] |
[
[
"numpy.sqrt",
"numpy.asarray",
"numpy.std",
"numpy.mean",
"numpy.sum"
]
] |
partha-ghosh/pyeffects
|
[
"b941e9b09c9889c01b103d758707d36c3520de2a"
] |
[
"elements/latex.py"
] |
[
"import hashlib\nimport os\n\nimport bs4\nimport numpy as np\n\nfrom .group import Group\nfrom .path import Path\nfrom .shapes import Rectangle\n\n\nclass TexConfig:\n main_font = None\n mono_font = None\n sans_font = None\n margin = 5.5\n scale_factor = 8\n fill = [255, 255, 255]\n stroke = [255, 255, 255]\n stroke_width = 1\n\n @staticmethod\n def text_box(width=None, scale_factor=None, margin=None):\n TexConfig.margin = round((594.691842 - (width/scale_factor)) / 56.76466 if width and scale_factor \\\n else TexConfig.margin if margin is None else margin, 2)\n TexConfig.scale_factor = round(width / (594.691842 - margin * 56.76466) if width and margin \\\n else TexConfig.scale_factor if scale_factor is None else scale_factor, 2)\n\n\ndef Tex(expr):\n filename = hashlib.md5(bytes(f\"{expr, TexConfig.main_font, TexConfig.mono_font, TexConfig.sans_font, TexConfig.margin}\", encoding=\"utf-8\")).hexdigest()\n if not os.path.exists(f\"/tmp/{filename}.tex\"):\n with open(f'/tmp/{filename}.tex', 'w') as f:\n f.write(f'''\n\\\\documentclass{{article}}\n\\\\usepackage{{amsmath}}\n\\\\usepackage{{amssymb}}\n\\\\usepackage{{amsfonts}}\n\\\\usepackage{{tikz}}\n\\\\usepackage[none]{{hyphenat}}\n\\\\usepackage[a4paper, margin={TexConfig.margin}cm]{{geometry}}\n\\\\usepackage{{fontspec}}\n''' + (f\"\\\\setmainfont{{{TexConfig.main_font}}}\" if TexConfig.main_font else \"\")\n + (f\"\\\\setmonofont{{{TexConfig.mono_font}}}\" if TexConfig.mono_font else \"\")\n + (f\"\\\\setsansfont{{{TexConfig.sans_font}}}\" if TexConfig.sans_font else \"\")\n+ f'''\\\\thispagestyle{{empty}}\n\\\\begin{{document}}\n{expr}\n\\\\end{{document}}''')\n\n os.system(f\"cd /tmp && xelatex -no-pdf {filename}.tex > /dev/null 2>&1 && dvisvgm -e -n {filename}.xdv > /dev/null 2>&1\")\n\n with open(f'/tmp/{filename}.svg', 'r') as f:\n soup = bs4.BeautifulSoup(f, 'xml')\n\n uses = soup.find_all('use')\n rects = soup.find_all('rect')\n\n def transform_tex_point(point, x, y):\n return complex(point.real + x, -point.imag - y)\n\n chars = Group()\n fx = float(uses[0].attrs['x'])\n fy = float(uses[0].attrs['y'])\n for use in uses:\n path = soup.find(id=use.attrs['xlink:href'][1:]).attrs['d']\n x = float(use.attrs['x']) - fx\n y = float(use.attrs['y']) - fy\n path = Path(path)\n path.matrix(np.array([[1, 0, 0, x], [0, -1, 0, -y], [0, 0, 1, 0], [0, 0, 0, 1.0]]))\n chars.add(path)\n for rect in rects:\n x = float(rect.attrs['x']) - fx\n y = float(rect.attrs['y']) - fy\n width = float(rect.attrs['width'])\n height = float(rect.attrs['height'])\n r = Rectangle(0, 0, width, height)\n r.matrix(np.array([[1, 0, 0, x], [0, -1, 0, -y], [0, 0, 1, 0], [0, 0, 0, 1.0]]))\n chars.add(r)\n\n chars.fill(TexConfig.fill).stroke(TexConfig.stroke).stroke_width(TexConfig.stroke_width)\n chars.scale(TexConfig.scale_factor, TexConfig.scale_factor)\n return chars\n"
] |
[
[
"numpy.array"
]
] |
zzz1515151/self-supervised_learning_sketch
|
[
"4253986afc92a1f30ee5caadbc074acb297f43b0"
] |
[
"train_tcn.py"
] |
[
"from __future__ import print_function\nimport sys\nsys.path.append(\"../\")\nimport argparse\nimport os\nimport torch \nimport time\nimport imp\nimport numpy as np\nimport datetime\nfrom tensorboardX import SummaryWriter\nfrom tqdm import tqdm\nfrom torch import nn, optim\nfrom torch.nn.utils import clip_grad_norm_\nfrom utils.AverageMeter import AverageMeter\nfrom utils.logger import logger \n\nfrom TCN import TCN\nfrom dataloader.dataloader_stroke import RNNDataset, DataLoader\n\nparser = argparse.ArgumentParser(description='traning TCN')\nparser.add_argument(\"--exp\", type = str, default = \"\", help = \"experiment\")\nparser.add_argument(\"--num_workers\", type = int, default = 4, help = \"num_workers\")\nparser.add_argument(\"--checkpoint\", type = int, default = 0, help = \"load checkpoint\")\nparser.add_argument('--gpu', type = str, default = \"0\", help = 'choose GPU')\nargs = parser.parse_args()\n\nexp_config = os.path.join(\".\", \"config\", args.exp + \".py\")\nexp_dir = os.path.join(\"./exp\", \"experiments\", args.exp)\nexp_log_dir = os.path.join(exp_dir, \"log\")\nif not os.path.exists(exp_log_dir):\n os.makedirs(exp_log_dir)\nexp_visual_dir = os.path.join(exp_dir, \"visual\")\nif not os.path.exists(exp_visual_dir):\n os.makedirs(exp_visual_dir)\n\n\nconfig = imp.load_source(\"\", exp_config).config\n#tensorboard && logger\nnow_str = datetime.datetime.now().__str__().replace(' ','_')\nwriter_path = os.path.join(exp_visual_dir, now_str)\nwriter = SummaryWriter(writer_path)\n\nlogger_path = os.path.join(exp_log_dir, now_str + \".log\")\nlogger = logger(logger_path).get_logger()\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu\n\ntorch.manual_seed(0)\ntorch.cuda.manual_seed_all(0)\nnp.random.seed(0)\n\ndata_train_opt = config['data_train_opt']\ndata_test_opt = config['data_test_opt']\n\n# init dataloader \nsignal_type = config['signal_type']\n\nlogger.info(\"initing dataloader\")\n\ntrain_dataset = RNNDataset(root = data_train_opt[\"root\"], split = data_train_opt[\"split\"])\ntrainloader = DataLoader(dataset = train_dataset, \n signal_type = signal_type,\n batch_size = data_train_opt[\"batch_size\"], \\\n num_workers = args.num_workers, shuffle = True)\n\ntest_dataset = RNNDataset(root = data_test_opt[\"root\"], split = data_test_opt[\"split\"])\ntestloader = DataLoader(dataset = test_dataset, \n signal_type = signal_type,\n batch_size = data_test_opt[\"batch_size\"], \\\n num_workers = args.num_workers, \n shuffle = False)\nlogger.info(\"dataloader OK!\")\n\n\nnetwork = TCN(config[\"net_opt\"])\nif args.checkpoint > 0 :\n net_checkpoint_name = args.exp + \"_net_epoch\" + args.checkpoint\n net_checkpoint_path = os.path.join(exp_dir, net_checkpoint_name)\n assert(os.path.exists(net_checkpoint_path))\n try: \n checkpoint = torch.load(net_checkpoint_path)\n network.load_state_dict(checkpoint[\"network\"])\n logger.info(\"Load net checkpoint epoch {}\".format(args.checkpoint))\n except:\n logger.info(\"Can not load checkpoint from {}\".format(net_checkpoint_path))\n\nnetwork = network.cuda()\n\noptim_opt = config[\"optim_opt\"]\nif optim_opt[\"name\"] == \"Adam\":\n optimizer = optim.Adam(network.parameters(), lr = optim_opt[\"lr\"])\nelif optim_opt['name'] == 'SGD':\n optimizer = optim.SGD(network.parameters(), lr = optim_opt[\"lr\"], \\\n momentum = optim_opt[\"momentum\"], \\\n nesterov = optim_opt[\"nesterov\"] if ('nesterov' in optim_opt) else False,\\\n weight_decay=optim_opt['weight_decay'])\nelse:\n raise ValueError(\"Don't surport optimizer:{}\".format(optim_opt[\"name\"]))\n\nif args.checkpoint > 0 :\n optim_checkpoint_name = args.exp + \"_optim_epoch\" + args.checkpoint\n optim_checkpoint_path = os.path.join(exp_dir, optim_checkpoint_name)\n assert(os.path.exists(optim_checkpoint_path))\n try:\n checkpoint = torch.load(optim_checkpoint_path)\n optimizer.load_state_dict(checkpoint[\"optimizer\"])\n logger.info(\"Load optimizer checkpoint epoch {}\".format(args.checkpoint))\n except:\n logger.info(\"Can not load checkpoint from {}\".format(optim_checkpoint_path))\n\n\nlr_protocol = optim_opt[\"lr_protocol\"]\nloss = nn.CrossEntropyLoss()\n\ndef accuracy(output, target, topk=(1,)):\n \"\"\"Computes the precision@k for the specified values of k\"\"\"\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0)\n res.append(correct_k.mul_(100.0 / batch_size))\n return res\n\ntrain_model_loss = AverageMeter()\ntrain_acc = AverageMeter()\ntest_model_loss = AverageMeter()\ntest_acc = AverageMeter()\n\n\ndef train(epoch): \n train_model_loss.reset()\n train_acc.reset()\n network.train()\n \n lr = next((lr for (max_epoch, lr) in lr_protocol if max_epoch>epoch), lr_protocol[-1][1]) \n for param_group in optimizer.param_groups:\n param_group['lr'] = lr \n logger.info(\"Setting learning rate to: {}\".format(lr))\n \n for idx, batch in enumerate(tqdm(trainloader(epoch))):\n #start = time.time()\n \n data = batch[0].cuda()\n target = batch[1].cuda()\n \n optimizer.zero_grad()\n \n output = network(data)\n #fc_output = network(data, [\"fc_block\"])\n #writer.add_histogram(\"train\", fc_output.data, epoch * len(dloader_train) + idx)\n \n loss_total = loss(output, target)\n \n loss_total.backward() \n \n optimizer.step()\n \n train_model_loss.update(loss_total.item())\n train_acc.update(accuracy(output, target, topk = (1,))[0][0]) \n if (idx+1) % config[\"display_step\"] == 0: \n logger.info(\"==> Iteration [{}][{}/{}]:\".format(epoch+1, idx+1, len(trainloader)))\n logger.info(\"current loss:{}\".format(loss_total.item()))\n #logger.info(\"grad norm:{}\".format(total_grad_norm))\n logger.info(\"loss: {} acc: {}\".format(train_model_loss.avg, train_acc.avg)) \n logger.info(\"Begin Evaluating\") \n test(epoch)\n writer.add_scalars(\"loss\", {\n \"train_loss\":train_model_loss.avg,\n \"test_loss\":test_model_loss.avg\n }, epoch+1)\n writer.add_scalars(\"acc\", {\n \"train_acc\":train_acc.avg,\n \"test_acc\":test_acc.avg\n }, epoch+1)\n\ndef test(epoch):\n test_model_loss.reset()\n test_acc.reset()\n network.eval()\n for idx, batch in enumerate(tqdm(testloader(epoch))):\n data = batch[0].cuda()\n target = batch[1].cuda()\n output = network(data)\n #fc_output = network(data, [\"fc_block\"]) \n #writer.add_histogram(\"test\", fc_output.data, epoch * len(dloader_test) + idx) \n loss_total = loss(output, target)\n test_model_loss.update(loss_total.item())\n test_acc.update(accuracy(output, target, topk = (1,))[0][0]) \n logger.info(\"==> Evaluation Result: \")\n logger.info(\"loss: {} acc:{}\".format(test_model_loss.avg, test_acc.avg))\n\nbest_test_acc = 0\nbest_epoch = None\n\nlogger.info(\"training Status: \") \nlogger.info(config) \nassert(args.checkpoint < config['num_epochs'])\nfor epoch in range(args.checkpoint, config['num_epochs']):\n logger.info(\"Experiment:{}\".format(args.exp))\n logger.info(\"Begin training epoch {}\".format(epoch+1))\n train(epoch) \n #save checkpoint\n net_checkpoint_name = args.exp + \"_net_epoch\" + str(epoch+1)\n net_checkpoint_path = os.path.join(exp_dir, net_checkpoint_name)\n net_state = {\"epoch\": epoch+1, \"network\": network.state_dict()}\n torch.save(net_state, net_checkpoint_path)\n\n optim_checkpoint_name = args.exp + \"_optim_epoch\" + str(epoch+1)\n optim_checkpoint_path = os.path.join(exp_dir, optim_checkpoint_name)\n optim_state = {\"epoch\": epoch+1, \"optimizer\": optimizer.state_dict()}\n torch.save(optim_state, optim_checkpoint_path)\n #delete previous checkpoint\n\n if not epoch == args.checkpoint:\n #net_checkpoint_name_del = args.exp + \"_net_epoch\" + str(epoch)\n #net_checkpoint_path_del = os.path.join(exp_dir, net_checkpoint_name_del)\n optim_checkpoint_name_del = args.exp + \"_optim_epoch\" + str(epoch)\n optim_checkpoint_path_del = os.path.join(exp_dir, optim_checkpoint_name_del)\n '''\n if os.path.exists(net_checkpoint_path_del):\n os.remove(net_checkpoint_path_del)\n '''\n if os.path.exists(optim_checkpoint_path_del):\n os.remove(optim_checkpoint_path_del)\n\n #save best model and delete previous best model\n if test_acc.avg > best_test_acc:\n if not best_epoch == None:\n net_best_name_del = args.exp + \"_net_epoch\" + str(best_epoch+1) + \".best\"\n net_best_path_del = os.path.join(exp_dir, net_best_name_del)\n if os.path.exists(net_best_path_del):\n os.remove(net_best_path_del)\n best_epoch = epoch\n best_test_acc = test_acc.avg\n net_best_name = args.exp + \"_net_epoch\" + str(epoch+1) + \".best\"\n net_best_path = os.path.join(exp_dir, net_best_name)\n net_best_state = {\"epoch\": epoch+1, \"best_acc\": best_test_acc, \\\n \"network\": network.state_dict()}\n torch.save(net_best_state, net_best_path)\n logger.info(\"Saving model best with acc:{}\".format(best_test_acc))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
] |
[
[
"torch.nn.CrossEntropyLoss",
"numpy.random.seed",
"torch.load",
"torch.manual_seed",
"torch.cuda.manual_seed_all",
"torch.save"
]
] |
sujanshahi050/Disaster-Response-Classifier
|
[
"fb8a9a28eeba7f9e8f1d63bff85ee45ca43892ab"
] |
[
"app/run.py"
] |
[
"import json\nimport plotly\nimport pandas as pd\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.tokenize import word_tokenize\n\nfrom flask import Flask\nfrom flask import render_template, request, jsonify\nfrom plotly.graph_objs import Bar\nfrom sklearn.externals import joblib\nfrom sqlalchemy import create_engine\n\n\napp = Flask(__name__)\n\ndef tokenize(text):\n \"\"\"\n Function that takes a text(str) as an input, cleans it and returns a lemmatized list of tokens(words)\n \n INPUT: text (str) : Text to be cleaned and tokenized and lemmatized\n OUTPUT: clean_tokens(list): List of clean tokens extracted from the text.\n \"\"\"\n tokens = word_tokenize(text)\n lemmatizer = WordNetLemmatizer()\n\n clean_tokens = []\n for tok in tokens:\n clean_tok = lemmatizer.lemmatize(tok).lower().strip()\n clean_tokens.append(clean_tok)\n\n return clean_tokens\n\n# load data\nengine = create_engine('sqlite:///../data/DisasterResponse.db')\ndf = pd.read_sql_table('disaster_messages_table', engine)\n\n# load model\nmodel = joblib.load(\"../models/classifier.pkl\")\n\n\n# index webpage displays cool visuals and receives user input text for model\[email protected]('/')\[email protected]('/index')\ndef index():\n \n # extract data needed for visuals\n # TODO: Below is an example - modify to extract data for your own visuals\n genre_counts = df.groupby('genre').count()['message']\n genre_names = list(genre_counts.index)\n \n # Distribution of categoires\n categories = df.iloc[:,4:].sum().sort_values().reset_index()\n categories.columns = ['category','count']\n categories_labels = categories['category'].values.tolist()\n categories_values = categories['count'].values.tolist()\n \n # \n \n \n # create visuals\n # TODO: Below is an example - modify to create your own visuals\n graphs = [ \n # Graph data for distribution of messages genres\n {'data':[\n Bar(\n x = genre_names,\n y = genre_counts \n )\n \n ],\n 'layout':{'title': 'Distribution of Messages Genre',\n 'yaxis':{\n 'title': \"Count\"\n },\n 'xaxis':{\n 'title': \"genre\"\n }\n }\n },\n \n # Graph data for Messages Categories Distribution\n {\n 'data': [\n Bar(\n x=categories_labels,\n y=categories_values,\n )\n ],\n\n 'layout': {\n 'title': 'Distribution of Message Categories',\n 'yaxis': {\n 'title': \"Count\"\n },\n 'xaxis': {\n 'title': \"Category\"\n }\n }\n }\n \n ]\n \n # encode plotly graphs in JSON\n ids = [\"graph-{}\".format(i) for i, _ in enumerate(graphs)]\n graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)\n \n # render web page with plotly graphs\n return render_template('master.html', ids=ids, graphJSON=graphJSON)\n\n\n# web page that handles user query and displays model results\[email protected]('/go')\ndef go():\n # save user input in query\n query = request.args.get('query', '') \n\n # use model to predict classification for query\n classification_labels = model.predict([query])[0]\n classification_results = dict(zip(df.columns[4:], classification_labels))\n\n # This will render the go.html Please see that file. \n return render_template(\n 'go.html',\n query=query,\n classification_result=classification_results\n )\n\[email protected]('/about')\ndef about():\n return render_template(\n 'about.html'\n )\n\ndef main():\n app.run(host='0.0.0.0', port=3001, debug=True)\n\n\nif __name__ == '__main__':\n main()"
] |
[
[
"pandas.read_sql_table",
"sklearn.externals.joblib.load"
]
] |
cnrpman/HBMP
|
[
"ae47bd737d88657f7f9284b2dd1adc96e535bbd9"
] |
[
"test.py"
] |
[
"import numpy as np\nimport sys\nfrom argparse import ArgumentParser\nimport torch\nimport random\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nfrom torchtext import data\nfrom torchtext import datasets\nfrom corpora import MultiNLI, SciTail, StanfordNLI, AllNLI, BreakingNLI\n\nparser = ArgumentParser(description='Helsinki NLI System')\nparser.add_argument('--model_path',\n type=str,\n default='results/model.pt')\nparser.add_argument(\"--corpus\",\n type=str,\n choices=['snli', 'breaking_nli', 'all_nli', 'multinli_matched', 'multinli_mismatched', 'scitail'],\n default='snli')\nparser.add_argument('--batch_size',\n type=int,\n default=64)\nparser.add_argument('--seed',\n type=int,\n default=1234)\nparser.add_argument('--gpu',\n type=int,\n default=0)\nparser.add_argument('--preserve_case',\n action='store_false',\n dest='lower')\n\n\ndef main():\n\n config = parser.parse_args()\n\n np.random.seed(config.seed)\n torch.manual_seed(config.seed)\n torch.cuda.manual_seed(config.seed)\n random.seed(config.seed)\n\n inputs = data.Field(lower=config.lower, tokenize='spacy')\n labels = data.Field(sequential=False, unk_token=None)\n category_field = data.Field(sequential=False)\n id_field = data.Field(sequential=False, unk_token=None)\n\n if config.corpus == 'multinli_matched':\n train, dev, test = MultiNLI.splits_matched(inputs, labels, id_field)\n id_field.build_vocab(train, dev, test)\n f = open(config.corpus+'_kaggle_test.csv', 'w+')\n elif config.corpus == 'multinli_mismatched':\n train, dev, test = MultiNLI.splits_mismatched(inputs, labels, id_field)\n id_field.build_vocab(train, dev, test)\n f = open(config.corpus+'_kaggle_test.csv', 'w+')\n elif config.corpus == 'scitail':\n train, dev, test = SciTail.splits(inputs, labels)\n elif config.corpus == 'all_nli':\n train, dev, test = AllNLI.splits(inputs, labels)\n id_field.build_vocab(train, dev, test)\n elif config.corpus == 'breaking_nli':\n train, dev, test = BreakingNLI.splits(inputs, labels, category_field)\n category_field.build_vocab(test)\n else:\n train, dev, test = StanfordNLI.splits(inputs, labels)\n\n inputs.build_vocab(train, dev, test)\n labels.build_vocab(train)\n\n train_iter, dev_iter, test_iter = data.BucketIterator.splits((train, dev, test),\n batch_size=config.batch_size,\n device=config.gpu)\n\n # Loss\n criterion = nn.CrossEntropyLoss()\n\n test_model = torch.load(config.model_path)\n\n # Switch model to evaluation mode\n test_model.eval()\n test_iter.init_epoch()\n\n # Calculate Accuracy\n n_test_correct = 0\n test_loss = 0\n test_losses = []\n\n if config.corpus == 'multinli_mismatched' or config.corpus == 'multinli_matched':\n f.write('pairID,gold_label\\n')\n\n print('ID | PREMISE | HYPOTHESIS | PREDICTION | RESULT | GOLD LABEL')\n for test_batch_idx, test_batch in enumerate(test_iter):\n # Make predictions\n answer = test_model(test_batch)\n # Keep track of location. Start form first item of the batch\n uid = 1+test_batch_idx*config.batch_size\n # Print the premise\n for i in range(test_batch.batch_size):\n if config.corpus == 'scitail' or config.corpus == 'breaking_nli':\n print('{} |'.format(i+uid), end=' ')\n else:\n print('{} |'.format(id_field.vocab.itos[test_batch.pair_id[i].data[0]]), end=' ')\n for prem in test_batch.premise.transpose(0,1)[i]:\n x = prem.data[0]\n if not inputs.vocab.itos[x] == '<pad>':\n print(inputs.vocab.itos[x], end=' ')\n print('|', end=' ')\n # Print the hypothesis\n for hypo in test_batch.hypothesis.transpose(0,1)[i]:\n y = hypo.data[0]\n if not inputs.vocab.itos[y] == '<pad>':\n print(inputs.vocab.itos[y], end=' ')\n print('|', end=' ')\n # Compare the prediction with the gold label and print\n for j, label in enumerate(answer[i]):\n if label.data[0] == torch.max(answer[i]).data[0]:\n if config.corpus == 'multinli_mismatched' or config.corpus == 'multinli_matched':\n f.write('{},{}\\n'.format(id_field.vocab.itos[test_batch.pair_id[i].data[0]], labels.vocab.itos[j]))\n print(labels.vocab.itos[j], end=' ')\n if j == test_batch.label[i].data[0]:\n print('| CORRECT |', end=' ')\n print(labels.vocab.itos[test_batch.label[i].data[0]], end=' ')\n else:\n print('| INCORRECT |', end=' ')\n print(labels.vocab.itos[test_batch.label[i].data[0]], end=' ')\n if config.corpus == 'breaking_nli':\n print('| {}'.format(category_field.vocab.itos[test_batch.category[i].data[0]]))\n else:\n print('')\n\n\n # Calculate the accuracy\n n_test_correct += (torch.max(answer, 1)[1].view(test_batch.label.size()).data == \\\n test_batch.label.data).sum()\n test_loss = criterion(answer, test_batch.label)\n test_losses.append(test_loss.data[0])\n\n\n if config.corpus == 'multinli_mismatched' or config.corpus == 'multinli_matched':\n f.close()\n test_acc = 100. * n_test_correct / len(test)\n\n print('\\nLoss: {:.4f} / Accuracy: {:.4f}\\n'.format(round(np.mean(test_losses), 2), test_acc))\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.max",
"torch.cuda.manual_seed",
"numpy.random.seed",
"torch.load",
"torch.manual_seed",
"numpy.mean"
]
] |
dylancromer/coolplots
|
[
"58ddfed2090af14d0ce42e93a35c93339e9c619f"
] |
[
"coolplots/data.py"
] |
[
"import matplotlib.pyplot as plt\nimport numpy as np\n\ndef plot1d(xdata, ydata, outfile=None, xdata_label=None, ydata_label=None, caption=None):\n plt.gcf().clear()\n with plt.xkcd():\n fig = plt.figure()\n ax = fig.add_axes((0.1, 0.2, 0.8, 0.7))\n\n ax.spines['right'].set_color('none')\n ax.spines['top'].set_color('none')\n\n plt.plot(xdata, ydata)\n\n plt.xlabel(xdata_label)\n plt.ylabel(ydata_label)\n fig.text(\n 0.5, 0.05,\n caption,\n ha='center')\n\n fig.tight_layout()\n\n if outfile is not None:\n fig.savefig(outfile)\n\ndef dryrun_plot1d():\n xdata = np.linspace(0, 3, 100)\n ydata = np.exp(-xdata**2)\n plot1d(xdata, ydata, outfile='test.svg', xdata_label='time', ydata_label='power spectrum', caption='A cool plot')\n\ndef plotpoints1d(xdata, ydata, outfile=None, xdata_label=None, ydata_label=None, caption=None):\n plt.gcf().clear()\n with plt.xkcd():\n fig = plt.figure()\n ax = fig.add_axes((0.1, 0.2, 0.8, 0.7))\n\n ax.spines['right'].set_color('none')\n ax.spines['top'].set_color('none')\n\n plt.scatter(xdata, ydata)\n\n plt.xlabel(xdata_label)\n plt.ylabel(ydata_label)\n fig.text(\n 0.5, 0.05,\n caption,\n ha='center')\n fig.tight_layout()\n\n if outfile is not None:\n fig.savefig(outfile)\n\ndef dryrun_plotpoints1d():\n xdata = np.linspace(0, 3, 100)\n ydata = np.exp(-xdata**2) + np.random.rand(xdata.size)\n plotpoints(xdata, ydata, outfile='test.pdf', xdata_label='time', ydata_label='power spectrum', caption='A cool plot')\n\nif __name__ == '__main__':\n print(\"This module is not meant to be run as a script\")\n"
] |
[
[
"matplotlib.pyplot.xkcd",
"numpy.linspace",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylabel",
"numpy.random.rand",
"matplotlib.pyplot.xlabel",
"numpy.exp",
"matplotlib.pyplot.figure"
]
] |
serge-m/omicron_ai_pilot_keras
|
[
"c9f0459ecd880ff685ba852eccd24685ab73623e"
] |
[
"src/ai_driver.py"
] |
[
"#!/usr/bin/env python3\nimport threading\n\nimport rospy\nfrom ackermann_msgs.msg import AckermannDriveStamped\nfrom sensor_msgs.msg import CompressedImage\n\nimport tensorflow as tf\nfrom tensorflow.python.keras.models import load_model\nfrom keras_preprocessing.image.utils import load_img, img_to_array\n\nfrom io import BytesIO\nimport numpy as np\nimport sys\nimport os\n\nimport tensorflow.keras as K\n\nfrom PIL import Image, ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\n\nclass TFModel:\n def __init__(self, path):\n self.path = path\n self.model = load_model(self.path)\n image = np.zeros([1, 120, 160, 3])\n # warm-up run to prepare for multi-threading\n self.model.predict(image)\n self.session = K.backend.get_session()\n self.graph = tf.get_default_graph()\n self.graph.finalize() # finalize\n\n def predict(self, image):\n with self.session.as_default():\n with self.graph.as_default():\n prediction = self.model.predict(image)\n return prediction\n\n\ndef create_message(speed, angle):\n message = AckermannDriveStamped()\n message.drive.speed = speed\n message.drive.steering_angle = angle\n return message\n\n\nclass FixedAIDriver:\n def __init__(self, path):\n rospy.init_node('ai_driver')\n self.model = TFModel(path)\n rospy.Subscriber('raspicam_node/image/compressed',\n CompressedImage, self.receive_compressed_image)\n self.ai_driver_publisher = rospy.Publisher('ackermann_cmd', AckermannDriveStamped,\n queue_size=10)\n\n def start(self):\n rospy.loginfo(\"AI driver start\")\n while not rospy.is_shutdown():\n rospy.spin()\n rospy.loginfo(\"AI driver finished\")\n\n def image_to_array(self, img):\n pil_img = Image.open(BytesIO(img)).convert('RGB').resize((160,120), Image.BILINEAR)\n return img_to_array(pil_img)\n\n def receive_compressed_image(self, img):\n rospy.logdebug(\"PID %d, thread %d, img size %d\",\n os.getpid(), threading.get_ident(), len(img.data))\n image = self.image_to_array(img.data)[np.newaxis]\n pred_angle, pred_throttle = self.model.predict(image / 255.)\n angle = pred_angle.flat[0]\n speed = pred_throttle.flat[0]\n\n rospy.loginfo(\"prediction %2.4f %2.4f\", speed, angle)\n self.ai_driver_publisher.publish(\n create_message(speed=speed, angle=angle))\n\n\nif __name__ == '__main__':\n try:\n path_model = sys.argv[1]\n except IndexError:\n path_model = '/tmp/model'\n\n package = FixedAIDriver(path_model)\n package.start()\n"
] |
[
[
"tensorflow.keras.backend.get_session",
"tensorflow.get_default_graph",
"numpy.zeros",
"tensorflow.python.keras.models.load_model"
]
] |
huschen/kaggle_nips17_adversarial
|
[
"aa619d937a77ef5f2efee6475b573aea652cf3cf"
] |
[
"models_targeted_attacks/target_mng/attack_target_mng.py"
] |
[
"\"\"\"Implementation of target attack.\n Three models (base_incep, adv_incep, res_incep) are used.\n The models are ensembled using mean norm gradient methrod.\n The inferstructure code is based on\n https://github.com/tensorflow/cleverhans/cleverhans/tree/master/\n examples/nips17_adversarial_competition/sample_targeted_attacks/iter_target_class\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport time\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib import slim\n\nfrom lib_adv import utils, attack\n\n\ntf.flags.DEFINE_string(\n 'output_dir',\n '../../intermediate_results/targeted_attacks_output/target_mng',\n 'Output directory with images.')\n\ntf.flags.DEFINE_string(\n 'input_dir', '../../dataset/images_4/', 'Input directory with images.')\n\ntf.flags.DEFINE_string(\n 'checkpoint_path', 'mul_inception_v1.ckpt',\n 'Path to checkpoint for inception network.')\n\ntf.flags.DEFINE_string(\n 'model_names',\n 'base_inception,base_incpt_resnet,adv_inception,adv_incpt_resnet',\n 'names of the multiple models, no space!')\n\ntf.flags.DEFINE_string(\n 'master', '', 'The address of the TensorFlow master to use.')\n\ntf.flags.DEFINE_integer('image_width', 299, 'Width of each input images.')\ntf.flags.DEFINE_integer('image_height', 299, 'Height of each input images.')\ntf.flags.DEFINE_integer('image_depth', 3, 'Depth of each input images.')\ntf.flags.DEFINE_integer('num_classes', 1001, 'Number of classes.')\ntf.flags.DEFINE_integer('num_iter', 20, 'Number of iterations.')\n\ntf.flags.DEFINE_integer('batch_size', 4, '#images process at one time.')\ntf.flags.DEFINE_float('max_epsilon', 16.0, 'Max size of perturbation.')\ntf.flags.DEFINE_integer('norm_ord', 1, 'order of norm to use')\ntf.flags.DEFINE_string('labels_file', 'target_class.csv', 'target classes')\n\n\nclass ModelAttacker():\n \"\"\"A target attacker model, multi-model ensembled.\"\"\"\n def __init__(self, num_classes, image_pixels, model_names, max_epsilon,\n norm_ord, batch_shape):\n \"\"\"Constructs a `ModelAttacker`.\n Set the parameters and build the base and adversarial graph\"\"\"\n prev = time.time()\n\n # image_factor is model dependent\n # Images for inception classifier are normalized to be in [-1, 1] interval\n # scale from [0, 255], range 255 to [-1, 1), range 2\n image_factor = 2.0 / 255.0\n\n list_mnames = model_names.split(',')\n eps, alpha = attack.parameters(max_epsilon, image_factor,\n image_pixels, norm_ord)\n\n utils.logger.debug('norm_ord = %d, alpha = %.3f, models: %s' % (\n norm_ord, alpha, list_mnames))\n\n # Prepare graph\n self._batch_shape = batch_shape\n self._x_input = tf.placeholder(tf.float32, shape=batch_shape)\n self._x_ref = tf.placeholder(tf.float32, shape=batch_shape)\n self._target_labels = tf.placeholder(tf.int32, shape=[batch_shape[0]])\n\n _, pred_labels, logits_w = attack.graph_base(self._x_input,\n num_classes,\n list_mnames)\n self._x_adv, _ = attack.graph_adv(self._x_input, num_classes,\n self._x_ref, self._target_labels,\n pred_labels, logits_w,\n alpha, eps, norm_ord)\n\n utils.logger.debug('graph init: %.3f seconds' % (time.time() - prev))\n\n def run(self, checkpoint_path, master, input_dir, labels_file, output_dir,\n num_iter):\n \"\"\"Run the computation and generate adversarial images\"\"\"\n saver = tf.train.Saver(slim.get_model_variables())\n session_creator = tf.train.ChiefSessionCreator(\n scaffold=tf.train.Scaffold(saver=saver),\n checkpoint_filename_with_path=checkpoint_path,\n master=master)\n\n with tf.train.MonitoredSession(session_creator=session_creator) as sess:\n for filenames, images, labels in utils.load_images(input_dir,\n self._batch_shape,\n labels_file):\n adv_images = np.copy(images)\n for _ in range(num_iter):\n adv_images = sess.run(\n self._x_adv,\n feed_dict={\n self._x_input: adv_images,\n self._x_ref: images,\n self._target_labels: labels})\n utils.save_images(adv_images, filenames, output_dir)\n\n\ndef main(_):\n tf.logging.set_verbosity(tf.logging.INFO)\n prev = time.time()\n\n FLG = tf.flags.FLAGS\n batch_shape = [FLG.batch_size, FLG.image_height, FLG.image_width,\n FLG.image_depth]\n image_pixels = FLG.image_height * FLG.image_width * FLG.image_depth\n\n with tf.Graph().as_default():\n attacker = ModelAttacker(FLG.num_classes, image_pixels, FLG.model_names,\n FLG.max_epsilon, FLG.norm_ord, batch_shape)\n attacker.run(FLG.checkpoint_path, FLG.master, FLG.input_dir,\n FLG.labels_file, FLG.output_dir, FLG.num_iter)\n\n utils.logger.debug('%.3f seconds' % (time.time() - prev))\n\n\nif __name__ == '__main__':\n tf.app.run()\n"
] |
[
[
"tensorflow.Graph",
"tensorflow.train.Scaffold",
"tensorflow.contrib.slim.get_model_variables",
"tensorflow.flags.DEFINE_string",
"tensorflow.train.MonitoredSession",
"tensorflow.placeholder",
"numpy.copy",
"tensorflow.logging.set_verbosity",
"tensorflow.flags.DEFINE_float",
"tensorflow.flags.DEFINE_integer",
"tensorflow.app.run"
]
] |
KEHANG/chemprop
|
[
"98e7da830e766311a70318bd8393cbc24cc5e9fd"
] |
[
"chemprop/args.py"
] |
[
"import json\nimport os\nfrom tempfile import TemporaryDirectory\nimport pickle\nfrom typing import List, Optional, Tuple\nfrom typing_extensions import Literal\n\nimport torch\nfrom tap import Tap # pip install typed-argument-parser (https://github.com/swansonk14/typed-argument-parser)\n\nfrom chemprop.features import get_available_features_generators\n\n\ndef get_checkpoint_paths(checkpoint_dir: Optional[str],\n checkpoint_path: Optional[str], ext: str = '.pt') -> Optional[List[str]]:\n \"\"\"\n Gets a list of checkpoint paths.\n\n If checkpoint_dir is provided, walks the directory and collects all checkpoints.\n If checkpoint_path is provided, only collects that one checkpoint.\n A checkpoint is any file ending in the extension ext.\n\n :param checkpoint_dir: Path to a directory containing checkpoints.\n :param checkpoint_path: Path to a checkpoint.\n :param ext: The extension which defines a checkpoint file.\n :return: A list of paths to checkpoints or None if both checkpoint_dir and checkpoint_path are None.\n \"\"\"\n if checkpoint_dir is not None and checkpoint_path is not None:\n raise ValueError('Can only specify one of checkpoint_dir and checkpoint_path')\n\n if checkpoint_path is not None:\n return [checkpoint_path]\n\n if checkpoint_dir is not None:\n checkpoint_paths = []\n\n for root, _, files in os.walk(checkpoint_dir):\n for fname in files:\n if fname.endswith(ext):\n checkpoint_paths.append(os.path.join(root, fname))\n\n if len(checkpoint_paths) == 0:\n raise ValueError(f'Failed to find any checkpoints with extension \"{ext}\" in directory \"{checkpoint_dir}\"')\n\n return checkpoint_paths\n\n return None\n\n\nclass CommonArgs(Tap):\n \"\"\"CommonArgs contains arguments that are used in both TrainArgs and PredictArgs.\"\"\"\n\n smiles_column: str = None # Name of the column containing SMILES strings. By default, uses the first column.\n checkpoint_dir: str = None # Directory from which to load model checkpoints (walks directory and ensembles all models that are found)\n checkpoint_path: str = None # Path to model checkpoint (.pt file)\n no_cuda: bool = False # Turn off cuda (i.e. use CPU instead of GPU)\n gpu: int = None # Which GPU to use\n features_generator: List[str] = None # Method(s) of generating additional features\n features_path: List[str] = None # Path(s) to features to use in FNN (instead of features_generator)\n no_features_scaling: bool = False # Turn off scaling of features\n max_data_size: int = None # Maximum number of data points to load\n num_workers: int = 8 # Number of workers for the parallel data loading (0 means sequential)\n batch_size: int = 50 # Batch size\n\n def __init__(self, *args, **kwargs) -> None:\n super(CommonArgs, self).__init__(*args, **kwargs)\n self._checkpoint_paths = None\n\n @property\n def device(self) -> torch.device:\n if not self.cuda:\n return torch.device('cpu')\n\n return torch.device('cuda', self.gpu)\n\n @device.setter\n def device(self, device: torch.device) -> None:\n self.cuda = device.type == 'cuda'\n self.gpu = device.index\n\n @property\n def cuda(self) -> bool:\n return not self.no_cuda and torch.cuda.is_available()\n\n @cuda.setter\n def cuda(self, cuda: bool) -> None:\n self.no_cuda = not cuda\n\n @property\n def features_scaling(self) -> bool:\n return not self.no_features_scaling\n\n @property\n def checkpoint_paths(self) -> List[str]:\n return self._checkpoint_paths\n\n @checkpoint_paths.setter\n def checkpoint_paths(self, checkpoint_paths: str) -> None:\n self._checkpoint_paths = checkpoint_paths\n\n def add_arguments(self) -> None:\n self.add_argument('--gpu', choices=list(range(torch.cuda.device_count())))\n self.add_argument('--features_generator', choices=get_available_features_generators())\n\n def process_args(self) -> None:\n # Load checkpoint paths\n self.checkpoint_paths = get_checkpoint_paths(\n checkpoint_dir=self.checkpoint_dir,\n checkpoint_path=self.checkpoint_path\n )\n\n # Validate features\n if self.features_generator is not None and 'rdkit_2d_normalized' in self.features_generator and self.features_scaling:\n raise ValueError('When using rdkit_2d_normalized features, --no_features_scaling must be specified.')\n\n\nclass TrainArgs(CommonArgs):\n \"\"\"TrainArgs includes CommonArgs along with additional arguments used for training a chemprop model.\"\"\"\n\n # General arguments\n data_path: str # Path to data CSV file\n target_columns: List[str] = None # Name of the columns containing target values. By default, uses all columns except the SMILES column.\n dataset_type: Literal['regression', 'classification', 'multiclass'] # Type of dataset. This determines the loss function used during training.\n multiclass_num_classes: int = 3 # Number of classes when running multiclass classification\n separate_val_path: str = None # Path to separate val set, optional\n separate_test_path: str = None # Path to separate test set, optional\n split_type: Literal['random', 'scaffold_balanced', 'predetermined', 'crossval', 'index_predetermined'] = 'random' # Method of splitting the data into train/val/test\n split_sizes: Tuple[float, float, float] = (0.8, 0.1, 0.1) # Split proportions for train/validation/test sets\n num_folds: int = 1 # Number of folds when performing cross validation\n folds_file: str = None # Optional file of fold labels\n val_fold_index: int = None # Which fold to use as val for leave-one-out cross val\n test_fold_index: int = None # Which fold to use as test for leave-one-out cross val\n crossval_index_dir: str = None # Directory in which to find cross validation index files\n crossval_index_file: str = None # Indices of files to use as train/val/test. Overrides --num_folds and --seed.\n seed: int = 0 # Random seed to use when splitting data into train/val/test sets. When `num_folds` > 1, the first fold uses this seed and all subsequent folds add 1 to the seed.\n pytorch_seed: int = 0 # Seed for PyTorch randomness (e.g. random initial weights)\n metric: Literal['auc', 'prc-auc', 'rmse', 'mae', 'mse', 'r2', 'accuracy', 'cross_entropy'] = None # Metric to use during evaluation. Defaults to \"auc\" for classification and \"rmse\" for regression.\n save_dir: str = None # Directory where model checkpoints will be saved\n save_smiles_splits: bool = False # Save smiles for each train/val/test splits for prediction convenience later\n test: bool = False # Whether to skip training and only test the model\n quiet: bool = False # Skip non-essential print statements\n log_frequency: int = 10 # The number of batches between each logging of the training loss\n show_individual_scores: bool = False # Show all scores for individual targets, not just average, at the end\n cache_cutoff: int = 10000 # Maximum number of molecules in dataset to allow caching. Below this number, caching is used and data loading is sequential. Above this number, caching is not used and data loading is parallel.\n\n # Model arguments\n bias: bool = False # Whether to add bias to linear layers\n hidden_size: int = 300 # Dimensionality of hidden layers in MPN\n depth: int = 3 # Number of message passing steps\n dropout: float = 0.0 # Dropout probability\n activation: Literal['ReLU', 'LeakyReLU', 'PReLU', 'tanh', 'SELU', 'ELU'] = 'ReLU' # Activation function\n atom_messages: bool = False # Centers messages on atoms instead of on bonds\n undirected: bool = False # Undirected edges (always sum the two relevant bond vectors)\n ffn_hidden_size: int = None # Hidden dim for higher-capacity FFN (defaults to hidden_size)\n ffn_num_layers: int = 2 # Number of layers in FFN after MPN encoding\n features_only: bool = False # Use only the additional features in an FFN, no graph network\n separate_val_features_path: List[str] = None # Path to file with features for separate val set\n separate_test_features_path: List[str] = None # Path to file with features for separate test set\n config_path: str = None # Path to a .json file containing arguments. Any arguments present in the config file will override arguments specified via the command line or by the defaults.\n ensemble_size: int = 1 # Number of models in ensemble\n\n # Training arguments\n epochs: int = 30 # Number of epochs to run\n warmup_epochs: float = 2.0 # Number of epochs during which learning rate increases linearly from init_lr to max_lr. Afterwards, learning rate decreases exponentially from max_lr to final_lr.\n init_lr: float = 1e-4 # Initial learning rate\n max_lr: float = 1e-3 # Maximum learning rate\n final_lr: float = 1e-4 # Final learning rate\n class_balance: bool = False # Trains with an equal number of positives and negatives in each batch (only for single task classification)\n\n def __init__(self, *args, **kwargs) -> None:\n super(TrainArgs, self).__init__(*args, **kwargs)\n self._task_names = None\n self._checkpoint_paths = None\n self._crossval_index_sets = None\n self._task_names = None\n self._num_tasks = None\n self._features_size = None\n self._train_data_size = None\n\n @property\n def minimize_score(self) -> bool:\n return self.metric in {'rmse', 'mae', 'mse', 'cross_entropy'}\n\n @property\n def use_input_features(self) -> bool:\n return self.features_generator is not None or self.features_path is not None\n\n @property\n def num_lrs(self) -> int:\n return 1 # Number of learning rates\n\n @property\n def crossval_index_sets(self) -> List[List[List[int]]]:\n return self._crossval_index_sets\n\n @property\n def task_names(self) -> List[str]:\n return self._task_names\n\n @task_names.setter\n def task_names(self, task_names: List[str]) -> None:\n self._task_names = task_names\n\n @property\n def num_tasks(self) -> int:\n return self._num_tasks\n\n @num_tasks.setter\n def num_tasks(self, num_tasks: int) -> None:\n self._num_tasks = num_tasks\n\n @property\n def features_size(self) -> int:\n return self._features_size\n\n @features_size.setter\n def features_size(self, features_size: int) -> None:\n self._features_size = features_size\n\n @property\n def train_data_size(self) -> int:\n return self._train_data_size\n\n @train_data_size.setter\n def train_data_size(self, train_data_size: int) -> None:\n self._train_data_size = train_data_size\n\n def process_args(self) -> None:\n super(TrainArgs, self).process_args()\n\n global temp_dir # Prevents the temporary directory from being deleted upon function return\n\n # Load config file\n if self.config_path is not None:\n with open(self.config_path) as f:\n config = json.load(f)\n for key, value in config.items():\n setattr(self, key, value)\n\n # Create temporary directory as save directory if not provided\n if self.save_dir is None:\n temp_dir = TemporaryDirectory()\n self.save_dir = temp_dir.name\n\n # Fix ensemble size if loading checkpoints\n if self.checkpoint_paths is not None and len(self.checkpoint_paths) > 0:\n self.ensemble_size = len(self.checkpoint_paths)\n\n # Process and validate metric and loss function\n if self.metric is None:\n if self.dataset_type == 'classification':\n self.metric = 'auc'\n elif self.dataset_type == 'multiclass':\n self.metric = 'cross_entropy'\n else:\n self.metric = 'rmse'\n\n if not ((self.dataset_type == 'classification' and self.metric in ['auc', 'prc-auc', 'accuracy']) or\n (self.dataset_type == 'regression' and self.metric in ['rmse', 'mae', 'mse', 'r2']) or\n (self.dataset_type == 'multiclass' and self.metric in ['cross_entropy', 'accuracy'])):\n raise ValueError(f'Metric \"{self.metric}\" invalid for dataset type \"{self.dataset_type}\".')\n\n # Validate class balance\n if self.class_balance and self.dataset_type != 'classification':\n raise ValueError('Class balance can only be applied if the dataset type is classification.')\n\n # Validate features\n if self.features_only and not (self.features_generator or self.features_path):\n raise ValueError('When using features_only, a features_generator or features_path must be provided.')\n\n # Handle FFN hidden size\n if self.ffn_hidden_size is None:\n self.ffn_hidden_size = self.hidden_size\n\n # Handle MPN variants\n if self.atom_messages and self.undirected:\n raise ValueError('Undirected is unnecessary when using atom_messages '\n 'since atom_messages are by their nature undirected.')\n\n # Validate split type settings\n if not (self.split_type == 'predetermined') == (self.folds_file is not None) == (self.test_fold_index is not None):\n raise ValueError('When using predetermined split type, must provide folds_file and test_fold_index.')\n\n if not (self.split_type == 'crossval') == (self.crossval_index_dir is not None):\n raise ValueError('When using crossval split type, must provide crossval_index_dir.')\n\n if not (self.split_type in ['crossval', 'index_predetermined']) == (self.crossval_index_file is not None):\n raise ValueError('When using crossval or index_predetermined split type, must provide crossval_index_file.')\n\n if self.split_type in ['crossval', 'index_predetermined']:\n with open(self.crossval_index_file, 'rb') as rf:\n self._crossval_index_sets = pickle.load(rf)\n self.num_folds = len(self.crossval_index_sets)\n self.seed = 0\n\n # Test settings\n if self.test:\n self.epochs = 0\n\n\nclass PredictArgs(CommonArgs):\n \"\"\"PredictArgs includes CommonArgs along with additional arguments used for predicting with a chemprop model.\"\"\"\n\n test_path: str # Path to CSV file containing testing data for which predictions will be made\n preds_path: str # Path to CSV file where predictions will be saved\n\n @property\n def ensemble_size(self) -> int:\n return len(self._checkpoint_paths)\n\n def process_args(self) -> None:\n super(PredictArgs, self).process_args()\n\n if self.checkpoint_paths is None or len(self.checkpoint_paths) == 0:\n raise ValueError('Found no checkpoints. Must specify --checkpoint_path <path> or '\n '--checkpoint_dir <dir> containing at least one checkpoint.')\n\n\nclass InterpretArgs(CommonArgs):\n \"\"\"InterpretArgs includes CommonArgs along with additional arguments used for interpreting a trained chemprop model.\"\"\"\n data_path: str # Path to data CSV file\n batch_size: int = 500 # Batch size\n property_id: int = 1 # Index of the property of interest in the trained model\n rollout: int = 20 # Number of rollout steps\n c_puct: float = 10.0 # Constant factor in MCTS\n max_atoms: int = 20 # Maximum number of atoms in rationale\n min_atoms: int = 8 # Minimum number of atoms in rationale\n prop_delta: float = 0.5 # Minimum score to count as positive\n\n def process_args(self) -> None:\n super(InterpretArgs, self).process_args()\n\n if self.features_path is not None:\n raise ValueError('Cannot use --features_path <path> for interpretation since features '\n 'need to be computed dynamically for molecular substructures. '\n 'Please specify --features_generator <generator>.')\n\n if self.checkpoint_paths is None or len(self.checkpoint_paths) == 0:\n raise ValueError('Found no checkpoints. Must specify --checkpoint_path <path> or '\n '--checkpoint_dir <dir> containing at least one checkpoint.')\n\n\nclass HyperoptArgs(TrainArgs):\n \"\"\"HyperoptArgs includes TrainArgs along with additional arguments used for optimizing chemprop hyperparameters.\"\"\"\n\n num_iters: int = 20 # Number of hyperparameter choices to try\n config_save_path: str # Path to .json file where best hyperparameter settings will be written\n log_dir: str = None # (Optional) Path to a directory where all results of the hyperparameter optimization will be written\n\n\nclass SklearnTrainArgs(TrainArgs):\n \"\"\"SklearnTrainArgs includes TrainArgs along with additional arguments for training a scikit-learn model.\"\"\"\n\n model_type: Literal['random_forest', 'svm'] # scikit-learn model to use\n class_weight: Literal['balanced'] = None # How to weight classes (None means no class balance)\n single_task: bool = False # Whether to run each task separately (needed when dataset has null entries)\n radius: int = 2 # Morgan fingerprint radius\n num_bits: int = 2048 # Number of bits in morgan fingerprint\n num_trees: int = 500 # Number of random forest trees\n\n\nclass SklearnPredictArgs(Tap):\n \"\"\"SklearnPredictArgs contains arguments used for predicting with a trained scikit-learn model.\"\"\"\n\n test_path: str # Path to CSV file containing testing data for which predictions will be made\n smiles_column: str = None # Name of the column containing SMILES strings. By default, uses the first column.\n preds_path: str # Path to CSV file where predictions will be saved\n dataset_type: Literal['classification', 'regression'] # Type of dataset\n model_type: Literal['random_forest', 'svm'] # scikit-learn model to use\n checkpoint_dir: str = None # Path to directory containing model checkpoints (.pkl file)\n checkpoint_path: str = None # Path to model checkpoint (.pkl file)\n radius: int = 2 # Morgan fingerprint radius\n num_bits: int = 2048 # Number of bits in morgan fingerprint\n num_tasks: int # Number of tasks the trained model makes predictions for\n\n def __init__(self, *args, **kwargs) -> None:\n super(SklearnPredictArgs, self).__init__(*args, **kwargs)\n self._checkpoint_paths = None\n\n @property\n def checkpoint_paths(self) -> List[str]:\n return self._checkpoint_paths\n\n @checkpoint_paths.setter\n def checkpoint_paths(self, checkpoint_paths: str) -> None:\n self._checkpoint_paths = checkpoint_paths\n\n def process_args(self) -> None:\n # Load checkpoint paths\n self.checkpoint_paths = get_checkpoint_paths(\n checkpoint_dir=self.checkpoint_dir,\n checkpoint_path=self.checkpoint_path,\n ext='.pkl'\n )\n"
] |
[
[
"torch.device",
"torch.cuda.device_count",
"torch.cuda.is_available"
]
] |
devhliu/dlaais-data
|
[
"790c497ab8e1c39524d37f924a72ea52343a01a8"
] |
[
"proj_temp/step_04.02_batch_check_rigid_registration_site005.py"
] |
[
"\nimport os\nimport ants\nimport shutil\nimport nibabel as nib\nimport numpy as np\nimport pandas as pd\n\nfrom glob import glob\n\nworking_root = '/data/public/data/003_STROKE_CTP/002_NIIX_SITE005'\nclinical_root = '/data/public/data/003_STROKE_CTP/003_CLINICAL_SITE005'\noutput_xlsx_filename = '002_NIIX_SITE005_CTP_mean_mc_mni'\n\nCTP_nii_files = glob(os.path.join(working_root, 'PID*PNAME*', '20*', 'CTP_1mm_mc_mni.nii.gz'))\nfailed_cases = []\ntags = {'Name':[], 'Date':[], 'CTP_P01':[], 'CTP_P02':[], 'CTP_P03':[], 'CTP_P04':[], 'CTP_P05':[],\n 'CTP_P06':[], 'CTP_P07':[], 'CTP_P08':[], 'CTP_P09':[], 'CTP_P10':[], 'CTP_P11':[], 'CTP_P12':[],\n 'CTP_P13':[], 'CTP_P14':[], 'CTP_P15':[], 'CTP_P16':[], 'CTP_P17':[], 'CTP_P18':[], 'CTP_P19':[],\n 'CTP_P20':[], 'CTP_P21':[], 'CTP_P22':[], 'CTP_P23':[], 'CTP_P24':[], 'CTP_P25':[], 'CTP_P26':[],\n 'CTP_P27':[], 'CTP_P28':[], 'CTP_P29':[], 'CTP_P30':[], 'CTP_P31':[], 'CTP_P32':[], 'CTP_P33':[],\n 'CTP_P34':[], 'CTP_P35':[], 'CTP_P36':[], 'CTP_P37':[], 'CTP_P38':[], 'CTP_P39':[], 'CTP_P40':[]}\nfor CTP_nii_file in CTP_nii_files:\n series_root = os.path.dirname(CTP_nii_file)\n date = os.path.basename(series_root)\n pname = os.path.basename(os.path.dirname(series_root))\n \n try:\n if not os.path.exists(CTP_nii_file): continue\n else:\n print('working on %s - %s'%(pname, date))\n nib_ctp = nib.load(CTP_nii_file)\n np_ctp = nib_ctp.get_fdata()\n tags['Name'].append(pname)\n tags['Date'].append(date)\n k1 = min(40, np_ctp.shape[3])\n k2 = max(40, np_ctp.shape[3])\n for i in range(k1):\n tagkey = 'CTP_P{:02d}'.format(i+1)\n tags[tagkey].append(np.mean(np_ctp[:,:,:,i]))\n for i in range(abs(k2 - k1)):\n tagkey = 'CTP_P{:02d}'.format(i+k1+1)\n tags[tagkey].append(0.0)\n except:\n failed_cases.append(pname)\n\ndf = pd.DataFrame(tags)\ndf.to_excel(os.path.join(clinical_root, output_xlsx_filename + '.xlsx'))\nprint(failed_cases)"
] |
[
[
"numpy.mean",
"pandas.DataFrame"
]
] |
wtabib/extrinsics_calibrator
|
[
"b0957e45e9c1c09e60ec115c1ec94991a0b338a0"
] |
[
"nodes/centered_mocap_rebroadcaster.py"
] |
[
"#!/usr/bin/env python2.7\nfrom __future__ import division\nimport roslib\nimport rospy\nimport tf\nfrom nav_msgs.msg import Odometry\nfrom nav_msgs.msg import Path\nfrom geometry_msgs.msg import PoseStamped\nimport numpy as np\n\n\nclass GT_cleaner:\n\n def __init__(self):\n\n self.last_time = rospy.Time.now()\n self.init = False\n self.broadcaster = tf.TransformBroadcaster()\n self.clean_pub = rospy.Publisher(\n '/gt_clean_odom', Odometry, queue_size=10)\n self.sub = rospy.Subscriber(\n \"/mocap/odom\", Odometry, self.callback)\n self.first_quat = None\n self.first_pos = np.array([0, 0, 0])\n self.prev_frame = np.eye(4)\n\n def callback(self, msg):\n q = msg.pose.pose.orientation\n p = msg.pose.pose.position\n quat = np.array([q.x, q.y, q.z, q.w])\n pos = np.array([p.x, p.y, p.z])\n if self.init == False:\n self.last_time = msg.header.stamp\n self.init = True\n\n self.first_frame = tf.transformations.quaternion_matrix(quat)\n self.first_frame[:3, 3] = pos\n self.first_frame_inv = np.linalg.inv(self.first_frame)\n\n return\n\n dt = (msg.header.stamp - self.last_time).to_sec()\n self.last_time = msg.header.stamp\n frame = tf.transformations.quaternion_matrix(quat)\n frame[:3, 3] = pos\n\n frame_in_first = np.dot(self.first_frame_inv, frame)\n\n # add to path\n odom = Odometry()\n\n odom.header.frame_id = msg.header.frame_id\n odom.pose.pose.position.x = frame_in_first[0, 3]\n odom.pose.pose.position.y = frame_in_first[1, 3]\n odom.pose.pose.position.z = frame_in_first[2, 3]\n q = tf.transformations.quaternion_from_matrix(frame_in_first)\n odom.pose.pose.orientation.x = q[0]\n odom.pose.pose.orientation.y = q[1]\n odom.pose.pose.orientation.z = q[2]\n odom.pose.pose.orientation.w = q[3]\n odom.header.stamp = msg.header.stamp\n\n #Now time for the velocities\n # Get the delta transform to obtain the velocities\n delta_frame = np.dot(np.linalg.inv(self.prev_frame), frame_in_first)\n self.prev_frame = frame_in_first\n # Linear part is easy\n odom.twist.twist.linear.x = delta_frame[0,3]/dt\n odom.twist.twist.linear.y = delta_frame[1,3]/dt\n odom.twist.twist.linear.z = delta_frame[2,3]/dt\n # For the angular velocity, we compute the angle axis\n result = tf.transformations.rotation_from_matrix(delta_frame)\n angle = result[0]\n direction = result[1]\n omega = direction * angle/dt\n odom.twist.twist.angular.x = omega[0]\n odom.twist.twist.angular.y = omega[1]\n odom.twist.twist.angular.z = omega[2]\n\n\n self.clean_pub.publish(odom)\n\n #Just for lolz publish the body fixed level frame\n level_frame= np.eye(4)\n level_frame[:3,:3] = frame[:3,:3]\n #Only set the rotation to be a rotation about z; so zero out any cross component wrt z\n # level_frame[2,:3] = [0,0,1]\n # level_frame[:3,2] = [0,0,1]\n # Normalize the first two columns\n # level_frame[:3,0] /= np.linalg.norm(level_frame[:3,0])\n # level_frame[:3,1] /= np.linalg.norm(level_frame[:3,1])\n \n # q = tf.transformations.quaternion_from_matrix(level_frame)\n\n # print level_frame\n level_q = quat\n # Zero out rotation about x and y\n level_q[0] = 0\n level_q[1] = 0\n level_q /= np.linalg.norm(level_q)\n self.broadcaster.sendTransform(frame[:3,3], level_q , msg.header.stamp, 'level', 'world')\n\n\nif __name__ == '__main__':\n rospy.init_node('gt_cleaner', anonymous=True)\n cleaner_obj = GT_cleaner()\n rospy.spin()\n"
] |
[
[
"numpy.dot",
"numpy.linalg.inv",
"numpy.eye",
"numpy.linalg.norm",
"numpy.array"
]
] |
y0ast/uncertainty-baselines
|
[
"8d32c77ba0803ed715c1406378adf10ebd61ab74",
"b9c6b870790034c1a2303246f887fd2cf53bff38"
] |
[
"baselines/jft/heteroscedastic_test.py",
"uncertainty_baselines/models/criteo_mlp_test.py"
] |
[
"# coding=utf-8\n# Copyright 2021 The Uncertainty Baselines Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for the heteroscedastic ViT on JFT-300M model script.\"\"\"\nimport os.path\nimport pathlib\nimport tempfile\n\nfrom absl import flags\nfrom absl import logging\nfrom absl.testing import flagsaver\nfrom absl.testing import parameterized\nimport jax\n# import ml_collections\nimport tensorflow as tf\nimport tensorflow_datasets as tfds\nimport checkpoint_utils # local file import from baselines.jft\nimport heteroscedastic # local file import from baselines.jft\nimport test_utils # local file import from baselines.jft\n\nFLAGS = flags.FLAGS\n\n\nclass HeteroscedasticTest(parameterized.TestCase, tf.test.TestCase):\n\n def setUp(self):\n super().setUp()\n baseline_root_dir = pathlib.Path(__file__).parents[1]\n self.data_dir = os.path.join(baseline_root_dir, 'testing_data')\n\n @parameterized.parameters(\n ('imagenet2012', 'token', 2, 796.28296, 714.6410047743055, 0.78, False),\n ('imagenet2012', 'token', 2, 796.28296, 714.6410047743055, 0.78, True),\n ('imagenet2012', 'token', None, 607.0116, 526.2057562934028, 1.11, False),\n ('imagenet2012', 'gap', 2, 668.09924, 645.5431043836805, 0.67, False),\n ('imagenet2012', 'gap', None, 663.7328, 638.9838460286459, 1.11, False),\n ('imagenet2012', 'gap', None, 663.7328, 638.9838460286459, 1.11, True),\n )\n @flagsaver.flagsaver\n def test_heteroscedastic_script(self, dataset_name, classifier,\n representation_size, correct_train_loss,\n correct_val_loss, correct_fewshot_acc_sum,\n simulate_failure):\n data_dir = self.data_dir\n config = test_utils.get_config(\n dataset_name=dataset_name,\n classifier=classifier,\n representation_size=representation_size)\n output_dir = tempfile.mkdtemp(dir=self.get_temp_dir())\n config.dataset_dir = data_dir\n num_examples = config.batch_size * config.total_steps\n\n if not simulate_failure:\n # Check for any errors.\n with tfds.testing.mock_data(num_examples=num_examples, data_dir=data_dir):\n train_loss, val_loss, fewshot_results = heteroscedastic.main(\n config, output_dir)\n else:\n # Check for the ability to restart from a previous checkpoint (after\n # failure, etc.).\n output_dir = tempfile.mkdtemp(dir=self.get_temp_dir())\n # NOTE: Use this flag to simulate failing at a certain step.\n config.testing_failure_step = config.total_steps - 1\n config.checkpoint_steps = config.testing_failure_step\n config.keep_checkpoint_steps = config.checkpoint_steps\n with tfds.testing.mock_data(num_examples=num_examples, data_dir=data_dir):\n heteroscedastic.main(config, output_dir)\n\n checkpoint_path = os.path.join(output_dir, 'checkpoint.npz')\n self.assertTrue(os.path.exists(checkpoint_path))\n checkpoint = checkpoint_utils.load_checkpoint(None, checkpoint_path)\n self.assertEqual(\n int(checkpoint['opt']['state']['step']),\n config.testing_failure_step)\n\n # This should resume from the failed step.\n del config.testing_failure_step\n with tfds.testing.mock_data(num_examples=num_examples, data_dir=data_dir):\n train_loss, val_loss, fewshot_results = heteroscedastic.main(\n config, output_dir)\n\n # Check for reproducibility.\n fewshot_acc_sum = sum(jax.tree_util.tree_flatten(fewshot_results)[0])\n logging.info('(train_loss, val_loss, fewshot_acc_sum) = %s, %s, %s',\n train_loss, val_loss['val'], fewshot_acc_sum)\n self.assertAllClose(train_loss, correct_train_loss)\n self.assertAllClose(val_loss['val'], correct_val_loss)\n\n @parameterized.parameters(\n ('imagenet2012', 'token', 2, 519.76855, 401.4379611, 0.55, 'imagenet'),\n )\n @flagsaver.flagsaver\n def test_loading_pretrained_model(self, dataset_name, classifier,\n representation_size, correct_train_loss,\n correct_val_loss, correct_fewshot_acc_sum,\n finetune_dataset_name):\n data_dir = self.data_dir\n config = test_utils.get_config(\n dataset_name=dataset_name,\n classifier=classifier,\n representation_size=representation_size)\n output_dir = tempfile.mkdtemp(dir=self.get_temp_dir())\n config.dataset_dir = data_dir\n num_examples = config.batch_size * config.total_steps\n\n # Run to save a checkpoint, then use that as a pretrained model.\n output_dir = tempfile.mkdtemp(dir=self.get_temp_dir())\n with tfds.testing.mock_data(num_examples=num_examples, data_dir=data_dir):\n heteroscedastic.main(config, output_dir)\n\n checkpoint_path = os.path.join(output_dir, 'checkpoint.npz')\n self.assertTrue(os.path.exists(checkpoint_path))\n\n output_dir = tempfile.mkdtemp(dir=self.get_temp_dir())\n config.model_init = checkpoint_path\n config.model.representation_size = None\n if finetune_dataset_name == 'cifar':\n config.dataset = 'cifar10'\n config.val_split = f'train[:{num_examples}]'\n config.train_split = f'train[{num_examples}:{num_examples*2}]'\n config.num_classes = 10\n config.ood_datasets = ['cifar100']\n config.ood_num_classes = [100]\n config.ood_split = f'test[{num_examples*2}:{num_examples*3}]'\n config.ood_methods = ['maha', 'entropy', 'rmaha', 'msp']\n config.eval_on_cifar_10h = True\n config.cifar_10h_split = f'test[:{num_examples}]'\n config.pp_eval_cifar_10h = (\n 'decode|resize(384)|value_range(-1, 1)|keep([\"image\", \"labels\"])')\n elif finetune_dataset_name == 'imagenet':\n config.dataset = 'imagenet2012'\n config.val_split = f'train[:{num_examples}]'\n config.train_split = f'train[{num_examples}:{num_examples*2}]'\n config.num_classes = 1000\n config.eval_on_imagenet_real = True\n config.imagenet_real_split = f'validation[:{num_examples}]'\n config.pp_eval_imagenet_real = (\n 'decode|resize(384)|value_range(-1, 1)|keep([\"image\", \"labels\"])')\n pp_common = '|value_range(-1, 1)'\n pp_common += f'|onehot({config.num_classes}, key=\"label\", key_result=\"labels\")' # pylint: disable=line-too-long\n pp_common += '|keep([\"image\", \"labels\"])'\n config.pp_train = 'decode|resize_small(512)|random_crop(384)' + pp_common\n config.pp_eval = 'decode|resize(384)' + pp_common\n config.fewshot.pp_train = 'decode|resize_small(512)|central_crop(384)|value_range(-1,1)|drop(\"segmentation_mask\")'\n config.fewshot.pp_eval = 'decode|resize(384)|value_range(-1,1)|drop(\"segmentation_mask\")'\n if config.get('ood_num_classes'):\n pp_eval_ood = []\n for num_classes in config.ood_num_classes:\n pp_eval_ood.append(\n config.pp_eval.replace(f'onehot({config.num_classes}',\n f'onehot({num_classes}'))\n config.pp_eval_ood = pp_eval_ood\n\n with tfds.testing.mock_data(num_examples=num_examples, data_dir=data_dir):\n train_loss, val_loss, fewshot_results = heteroscedastic.main(\n config, output_dir)\n\n fewshot_acc_sum = sum(jax.tree_util.tree_flatten(fewshot_results)[0])\n logging.info('(train_loss, val_loss, fewshot_acc_sum) = %s, %s, %s',\n train_loss, val_loss['val'], fewshot_acc_sum)\n # TODO(dusenberrymw,jjren): Add a reproducibility test for OOD eval.\n self.assertAllClose(train_loss, correct_train_loss)\n self.assertAllClose(val_loss['val'], correct_val_loss)\n\n\nif __name__ == '__main__':\n tf.test.main()\n",
"# coding=utf-8\n# Copyright 2021 The Uncertainty Baselines Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for uncertainty_baselines.models.criteo_mlp.\"\"\"\n\nimport tensorflow as tf\nimport uncertainty_baselines as ub\n\n\nclass CriteoMlpTest(tf.test.TestCase):\n\n def testCreateModel(self):\n model = ub.models.criteo_mlp(31)\n self.assertLen(model.layers, 47)\n\n\nif __name__ == '__main__':\n tf.test.main()\n"
] |
[
[
"tensorflow.test.main"
],
[
"tensorflow.test.main"
]
] |
jypkkjj/rqalpha
|
[
"f88be1112369c765054ba54512d1f7de3bc2ed47"
] |
[
"strategy/github/chougoushi_1.0.py"
] |
[
"# 可以自己import我们平台支持的第三方python模块,比如pandas、numpy等。\r\n#存在问题:如果一只股票已经买入了,但是被剔除出股票池,以后就不会再操作它。\r\n#目标收益6%:4年累计25.958%\r\n#\r\nimport talib\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n# 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。\r\ndef init(context):\r\n # 在context中保存全局变量\r\n # context.s1 = \"600600.XSHG\"\r\n context.SHORTPERIOD = 5\r\n context.LONGPERIOD = 90\r\n # 选择我们感兴趣的股票\r\n # context.s1 = \"002001.XSHE\"\r\n # context.s2 = \"601988.XSHG\"\r\n # context.s3 = \"000068.XSHE\"\r\n # context.stocks = [context.s1]\r\n context.stocks = index_components('000300.XSHG')\r\n # 实时打印日志\r\n logger.info(\"RunInfo: {}\".format(context.run_info))\r\n\r\n fundamental_df = get_fundamentals(\r\n\r\n query(fundamentals.eod_derivative_indicator.pe_ratio, # 市盈率\r\n fundamentals.financial_indicator.inc_gross_profit, # 营业利润同比\r\n fundamentals.financial_indicator.inc_operating_revenue # 营业收入同比\r\n ).filter(\r\n fundamentals.financial_indicator.stockcode.in_(context.stocks) # 在原股票池中\r\n ).filter(\r\n fundamentals.eod_derivative_indicator.pe_ratio < 50\r\n ).filter(\r\n fundamentals.financial_indicator.inc_gross_profit > 1.0\r\n ).filter(\r\n fundamentals.financial_indicator.inc_operating_revenue > 1.0\r\n )\r\n )\r\n context.fundamental_df = fundamental_df\r\n\r\n\r\n# before_trading此函数会在每天策略交易开始前被调用,当天只会被调用一次\r\ndef before_trading(context):\r\n fundamental_df = get_fundamentals(\r\n\r\n query(fundamentals.eod_derivative_indicator.pe_ratio, # 市盈率\r\n fundamentals.financial_indicator.inc_gross_profit, # 营业利润同比\r\n fundamentals.financial_indicator.inc_operating_revenue # 营业收入同比\r\n ).filter(\r\n fundamentals.financial_indicator.stockcode.in_(context.stocks) # 在原股票池中\r\n ).filter(\r\n fundamentals.eod_derivative_indicator.pe_ratio < 50\r\n ).filter(\r\n fundamentals.financial_indicator.inc_gross_profit > 1.0\r\n ).filter(\r\n fundamentals.financial_indicator.inc_operating_revenue > 1.0\r\n )\r\n )\r\n update_universe(context.fundamental_df.columns.values)\r\n logger.info(context.fundamental_df.columns.values)\r\n logger.info(context.portfolio.positions)\r\n # context.stocks = context.fundamental_df.columns.values\r\n\r\n\r\n# 你选择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新\r\ndef handle_bar(context, bar_dict):\r\n # 开始编写你的主要的算法逻辑\r\n\r\n # bar_dict[order_book_id] 可以拿到某个证券的bar信息\r\n # context.portfolio 可以拿到现在的投资组合信息\r\n\r\n # 使用order_shares(id_or_ins, amount)方法进行落单\r\n\r\n # TODO: 开始编写你的算法吧!\r\n # 因为策略需要用到均线,所以需要读取历史数据\r\n #做成交量低迷排名\r\n ranking_list = pd.DataFrame(columns=[\"code\",\"volume_division\"]) #columes: \"code\",“volume_division”, rows:每个股票占一行\r\n for stock in context.fundamental_df.columns.values:\r\n volumes = history_bars(stock, context.LONGPERIOD + 1, '1d', 'volume')\r\n volumes = [float(f) for f in volumes]\r\n volumes = np.array(volumes)\r\n # 使用talib计算长短两根均线,均线以array的格式表达\r\n short_avg = talib.SMA(volumes, context.SHORTPERIOD)\r\n long_avg = talib.SMA(volumes, context.LONGPERIOD)\r\n plot(\"short avg\", short_avg[-1])\r\n plot(\"long avg\", long_avg[-1])\r\n volume_division = long_avg[-1] / short_avg[-1] #越大越无人问津 \r\n ranking_list = ranking_list.append({\"code\":stock,\"volume_division\":volume_division},ignore_index=True)\r\n ranking_list = ranking_list.sort([\"volume_division\"],ascending=False)\r\n logger.info(ranking_list)\r\n for i in range(0,10):\r\n stock = ranking_list.iloc[i,0]\r\n # 计算现在portfolio中股票的仓位\r\n cur_position = context.portfolio.positions[stock].quantity\r\n # 首次买入条件,应该添加只买业绩好的\r\n if (cur_position == 0 and ranking_list.iloc[i,1] > 3):\r\n # 买入\r\n # 计算现在portfolio中的现金可以购买多少股票\r\n if (context.portfolio.cash > 10000.0):\r\n shares = 10000 / bar_dict[stock].close\r\n else:\r\n shares = context.portfolio.cash / bar_dict[stock].close\r\n order_shares(stock, shares)\r\n \r\n for stock in context.portfolio.positions:\r\n volumes = history_bars(stock, context.LONGPERIOD + 1, '1d', 'volume')\r\n volumes = [float(f) for f in volumes]\r\n volumes = np.array(volumes)\r\n # 使用talib计算长短两根均线,均线以array的格式表达\r\n short_avg = talib.SMA(volumes, context.SHORTPERIOD)\r\n long_avg = talib.SMA(volumes, context.LONGPERIOD)\r\n plot(\"short avg\", short_avg[-1])\r\n plot(\"long avg\", long_avg[-1])\r\n\r\n # 计算现在portfolio中股票的仓位\r\n cur_position = context.portfolio.positions[stock].quantity\r\n # 清仓条件:\r\n # 成交量太多或者达到止盈条件\r\n try:\r\n if ((2*long_avg[-1] < short_avg[-1] or context.portfolio.positions[stock].market_value /\r\n context.portfolio.positions[stock].quantity / context.portfolio.positions[\r\n stock].avg_price > 1.06 or context.portfolio.positions[stock].market_value>13000) and cur_position > 0):\r\n # 进行清仓\r\n order_target_value(stock, 0)\r\n except:\r\n pass\r\n # 持仓时买入条件,做T\r\n try:\r\n if (cur_position > 0 and context.portfolio.positions[stock].market_value<14000 and context.portfolio.positions[stock].market_value / context.portfolio.positions[\r\n stock].quantity / context.portfolio.positions[stock].avg_price < 0.92):\r\n # 买入\r\n if (context.portfolio.cash > 5000.0):\r\n shares = 5000 / bar_dict[stock].close\r\n else:\r\n shares = context.portfolio.cash / bar_dict[stock].close\r\n order_shares(stock, shares)\r\n except:\r\n pass\r\n\r\n\r\n# after_trading函数会在每天交易结束后被调用,当天只会被调用一次\r\ndef after_trading(context):\r\n pass"
] |
[
[
"numpy.array",
"pandas.DataFrame"
]
] |
0lidaxiang/IR
|
[
"e4a7213f43e7aa2e332057b2b4b2bd98ceabf5be"
] |
[
"homework3-EM/code/em_algorithms.py"
] |
[
"#!/usr/bin/python3\n# coding: utf-8\n\nimport numpy as np\nimport math\nfrom datetime import datetime\n\nimport dictionary\nimport document\nimport wordDocsCount\nimport wordDocsNoCount\n\nstartInitial = datetime.now()\n\ndocList = document.getFilesName()\nwordList = dictionary.getDictionary()\nwNumber = len(wordList)\ndNumber = len(docList) # 2265\ntopicNum = 10\nP_d = np.random.dirichlet(np.ones(dNumber),size=1).tolist()[0]\nP_w_T = np.random.dirichlet(np.ones(topicNum),size= wNumber)\nP_T_d = np.random.dirichlet(np.ones(dNumber),size= topicNum)\nP_T_wd = np.zeros(shape=(topicNum * dNumber,wNumber))\ncount_w_d = wordDocsCount.getWordDocCount()\nnoCount_w_d = wordDocsNoCount.getWordDocNoCount()\ndict_DocCountWord = wordDocsCount.getDict_DocCountWord()\n\nprint(\"initial time: \" , str(datetime.now()-startInitial).split(':', 3)[2], \"(sec)\")\n\n# -------------------- EM algorithm -----------------------------\ndef e_step():\n for k in range(topicNum):\n for d in range(dNumber):\n now_doc_WordIndex = noCount_w_d[d]\n d_noCount_w_dNum = len(now_doc_WordIndex)\n for ni in range(d_noCount_w_dNum):\n i = int(now_doc_WordIndex[ni][1])\n sum_w_t_d = 0\n for kk in range(topicNum):\n sum_w_t_d += P_w_T[i][kk] * P_T_d[kk][d]\n if sum_w_t_d <= 0:\n sum_w_t_d = 1e-6\n\n P_w_T_i_k = P_w_T[i][k]\n P_T_d_k_d = P_T_d[k][d]\n index = index = d * (k+1)\n P_T_wd[index][i] = (P_w_T_i_k * P_T_d_k_d) / sum_w_t_d\ndef m_step():\n for k in range(topicNum):\n # denominator\n w_T_denominator = 0\n for i in range(wNumber):\n for j in range(len(dict_DocCountWord[i])):\n w_T_denominator += dict_DocCountWord[i][j][1]\n\n # compute P_w_T , all words\n for i in range(wNumber):\n molecular = 0\n # all documents\n for j in range(len(dict_DocCountWord[i])):\n d = dict_DocCountWord[i][j][0]\n\n index = d * (k+1)\n para1 = int(dict_DocCountWord[i][j][1])\n para2 = P_T_wd[index][i]\n # molecular\n molecular += para1 * para2\n\n if w_T_denominator <= 0:\n w_T_denominator = 1e-6\n P_w_T[i][k] = molecular / w_T_denominator\n\n # compute P_T_d , all documents\n for d in range(dNumber):\n molecular = 0\n denominator = 0\n now_doc_WordIndex = noCount_w_d[d]\n wIndex_in_now_doc_WordIndex = -1\n\n # all words in a document\n for dd in range(len(now_doc_WordIndex)):\n _i = int(now_doc_WordIndex[dd][1])\n index = d * (k+1)\n mole_para1 = int(count_w_d[ d ][dd][1])\n mole_para2 = P_T_wd[index][_i]\n\n molecular += mole_para1 * mole_para2\n denominator += mole_para1\n\n if denominator <= 0:\n denominator = 1e-6\n P_T_d[k][d] = molecular / denominator\n\nlog_likelihood = 0\ndef compute_log_likelihood():\n log_likelihood = 0\n\n for i in range(wNumber):\n for j in range(len(dict_DocCountWord[i])):\n P_wT_Td = 0\n for k in range(topicNum):\n P_wT_Td += P_w_T[i][k] * P_T_d[k][dict_DocCountWord[i][j][0]]\n log_likelihood += int(dict_DocCountWord[i][j][1]) * math.log10(P_d[j] * P_wT_Td)\n return log_likelihood\n\ndef train():\n fname = \"../log_likelihood_\" + str(datetime.now().strftime('%Y-%m-%d')) + \".log\"\n f = open(fname, 'w')\n for i in range(1, 50):\n startOneTrain = datetime.now()\n\n e_step()\n m_step()\n log_likelihood = compute_log_likelihood()\n\n nowTime = datetime.now()\n f.write('{:<4d} {:20s} log_likelihood = {:9f}\\n'.format(i, nowTime.strftime('%Y-%m-%d %H:%M:%S'), log_likelihood))\n print('{:<4d} excuteTime: {:9s}(sec) , log_likelihood = {:9f}'.format(i, str(nowTime - startOneTrain).split(':', 3)[2], log_likelihood))\n f.close()\n\n\nprint(\"\\n -------------------- train start -------------------- \\n\")\nstartTrain = datetime.now()\ntrain()\nprint(\"\\n -------------------- train finished -------------------- \\n\")\nprint(\"train excution time is \", str(datetime.now()-startTrain).split('.', 3)[0])\n"
] |
[
[
"numpy.zeros",
"numpy.ones"
]
] |
UofSC-QDEVS/shipsys
|
[
"d01a8c8273aac916a1772a3d37db35faff68ea83"
] |
[
"python/qdlpy3/QdlPy/funcss.py"
] |
[
"\"\"\"Delegate function-based State Space Framework.\n\"\"\"\n\nimport lti\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass FuncSystem(object):\n\n def __init__(self, num_states, num_inputs, num_outputs):\n\n self.n = num_states\n self.m = num_inputs\n self.p = num_outputs\n\n self.x = FuncVector(self.n)\n self.u = FuncVector(self.m)\n self.y = FuncVector(self.p)\n\n self.a = FuncMatrix(self.n, self.n)\n self.b = FuncMatrix(self.n, self.m)\n self.c = FuncMatrix(self.p, self.n)\n self.d = FuncMatrix(self.p, self.m)\n\n def compute_row(self, irow):\n\n val = 0.0\n for jcol in range(self.n):\n val += self.a.get_coef(irow, jcol) * self.x.get_coef(jcol)\n\n for jcol in range(self.m):\n val += self.b.get_coef(irow, jcol) * self.u.get_coef(jcol)\n\n return val\n\n def build_ss(self):\n\n self.a.update_numeric()\n self.b.update_numeric()\n self.c.update_numeric()\n self.d.update_numeric()\n self.u.update_numeric()\n\n self.ss = lti.StateSpace(self.a.numeric, self.b.numeric,\n self.c.numeric, self.d.numeric,\n u0=self.u.numeric)\n\n def run_to(self, dt, tstop):\n\n self.build_ss()\n self.ss.initialize(dt)\n return self.ss.run_to(tstop)\n\n\nclass FuncMatrix(object):\n\n def __init__(self, nrows, mcols):\n\n self.nrows = nrows\n self.mcols = mcols\n\n self.funcs = x = [[None for i in range(mcols)] for i in range(nrows)]\n self.callers = [[None for i in range(mcols)] for i in range(nrows)]\n self.is_func = [[False for i in range(mcols)] for i in range(nrows)]\n self.coefs = np.zeros((self.nrows, self.mcols))\n self.numeric = np.zeros((self.nrows, self.mcols))\n\n def set_cell_func(self, irow, jcol, func, caller=None):\n\n self.is_func[irow][jcol] = True\n self.callers[irow][jcol] = caller\n self.funcs[irow][jcol] = func\n\n def set_cell_coef(self, irow, jcol, coef):\n\n self.is_func[irow][jcol] = False\n self.coefs[irow][jcol] = coef\n\n def get_coef(self, irow, jcol):\n\n if self.is_func[irow][jcol]:\n if self.callers[irow][jcol]: \n return self.callers[irow][jcol].funcs[irow][jcol]()\n else:\n return self.funcs[irow][jcol]()\n else:\n return self.coefs[irow][jcol]\n\n def update_numeric(self):\n\n for irow in range(self.nrows):\n for jcol in range(self.mcols):\n self.numeric[irow][jcol] = self.get_coef(irow, jcol)\n\n\nclass FuncVector(object):\n\n def __init__(self, nrows):\n\n self.nrows = nrows\n\n self.funcs = [None]*nrows\n self.callers = [None]*nrows\n self.is_func = [False]*nrows\n self.coefs = np.zeros((self.nrows, 1))\n self.numeric = np.zeros((self.nrows, 1))\n\n def set_cell_func(self, irow, func, caller=None):\n\n self.is_func[irow] = True\n self.callers[irow] = caller\n self.funcs[irow] = func\n \n def set_cell_coef(self, irow, coef):\n\n self.is_func[irow] = False\n self.coefs[irow] = coef\n\n def get_coef(self, irow):\n\n if self.is_func[irow]:\n if self.callers[irow]: \n return self.callers[irow].funcs[irow]()\n else:\n return self.funcs[irow]()\n else:\n return self.coefs[irow]\n\n def update_numeric(self):\n\n for irow in range(self.nrows):\n self.numeric[irow] = self.get_coef(irow)\n\n\ndef test1():\n\n def a00(): return -1.0\n def a01(): return 1.0\n def a10(): return -1.0\n def a11(): return -1.0\n\n def b00(): return 1.0\n def b01(): return 0.0\n def b10(): return 0.0\n def b11(): return 1.0\n\n def c00(): return 1.0\n def c01(): return 0.0\n def c10(): return 0.0\n def c11(): return 1.0\n\n def d00(): return 0.0\n def d01(): return 0.0\n def d10(): return 0.0\n def d11(): return 0.0\n\n def u0(): return 1.0\n def u1(): return 1.0\n\n sys = FuncSystem(2, 2, 2)\n\n sys.a.set_cell_func(0, 0, a00)\n sys.a.set_cell_func(0, 1, a01)\n sys.a.set_cell_func(1, 0, a10)\n sys.a.set_cell_func(1, 1, a11)\n\n sys.b.set_cell_func(0, 0, b00)\n sys.b.set_cell_func(0, 1, b01)\n sys.b.set_cell_func(1, 0, b10)\n sys.b.set_cell_func(1, 1, b11)\n\n sys.c.set_cell_func(0, 0, c00)\n sys.c.set_cell_func(0, 1, c01)\n sys.c.set_cell_func(1, 0, c10)\n sys.c.set_cell_func(1, 1, c11)\n\n sys.d.set_cell_func(0, 0, d00)\n sys.d.set_cell_func(0, 1, d01)\n sys.d.set_cell_func(1, 0, d10)\n sys.d.set_cell_func(1, 1, d11)\n\n sys.u.set_cell_func(0, u0)\n sys.u.set_cell_func(1, u1)\n\n t, y = sys.run_to(1e-3, 10.0)\n\n plt.plot(t, y[0][:], label=\"x0\")\n plt.plot(t, y[1][:], label=\"x1\")\n plt.legend()\n plt.show()\n\n\n\nif __name__ == \"__main__\":\n\n test1()\n #test2()\n "
] |
[
[
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show",
"numpy.zeros"
]
] |
hougeaaa/HappyDay
|
[
"60e226d380862db30b3c6abc1d7d7fbbcddd04a0"
] |
[
"Study_NumPy/6.py"
] |
[
"import numpy as np\n\n# 数组的 dtype 为 int8(一个字节)\nx = np.array([1, 2, 3, 4, 5], dtype=np.int8)\nprint(x.itemsize)\n\n# 数组的 dtype 现在为 float64(八个字节)\ny = np.array([1, 2, 3, 4, 5], dtype=np.float64)\nprint(y.itemsize)"
] |
[
[
"numpy.array"
]
] |
yilmazbaysal/Fashion-Classifier
|
[
"79cced68c83c32bda275a003a55b1a7cfdbc845a"
] |
[
"src/feature_extractor.py"
] |
[
"import cv2\nimport numpy as np\nfrom keras import Model\nfrom keras.applications import VGG16\nfrom keras.preprocessing import image\nfrom keras.applications.vgg16 import preprocess_input\n\n\nclass FeatureExtractor:\n\n def __init__(self):\n self.model = VGG16(weights='imagenet', include_top=True)\n\n def extract_features(self, image_path):\n img_array = image.img_to_array(cv2.resize(cv2.imread(image_path), (224, 224)))\n img_array = np.expand_dims(img_array, axis=0)\n img_array = preprocess_input(img_array)\n\n # Get pre-last layer\n model_extract_features = Model(inputs=self.model.inputs, outputs=self.model.get_layer('fc2').output)\n\n # Extract features\n fc2_features = model_extract_features.predict(img_array)\n\n # Reshape the output\n fc2_features = [f[0] for f in fc2_features.reshape((4096, 1))]\n\n return fc2_features\n"
] |
[
[
"numpy.expand_dims"
]
] |
shjwudp/fastmoe_shen
|
[
"b861e928000ddf1a94bb5f795e6286769e743bd9"
] |
[
"examples/transformer-xl/mem_transformer.py"
] |
[
"import sys\nimport math\nimport functools\n\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nsys.path.append('utils')\nfrom proj_adaptive_softmax import ProjectedAdaptiveLogSoftmax, Projection\nfrom log_uniform_sampler import LogUniformSampler, sample_logits\n\nclass PositionalEmbedding(nn.Module):\n def __init__(self, demb):\n super(PositionalEmbedding, self).__init__()\n\n self.demb = demb\n\n inv_freq = 1 / (10000 ** (torch.arange(0.0, demb, 2.0) / demb))\n self.register_buffer('inv_freq', inv_freq)\n\n def forward(self, pos_seq, bsz=None):\n sinusoid_inp = torch.ger(pos_seq, self.inv_freq)\n pos_emb = torch.cat([sinusoid_inp.sin(), sinusoid_inp.cos()], dim=-1)\n\n if bsz is not None:\n return pos_emb[:,None,:].expand(-1, bsz, -1)\n else:\n return pos_emb[:,None,:]\n\n\nclass PositionwiseFF(nn.Module):\n def __init__(self, d_model, d_inner, dropout, pre_lnorm=False):\n super(PositionwiseFF, self).__init__()\n\n self.d_model = d_model\n self.d_inner = d_inner\n self.dropout = dropout\n\n self.CoreNet = nn.Sequential(\n nn.Linear(d_model, d_inner), nn.ReLU(inplace=True),\n nn.Dropout(dropout),\n nn.Linear(d_inner, d_model),\n nn.Dropout(dropout),\n )\n\n self.layer_norm = nn.LayerNorm(d_model)\n\n self.pre_lnorm = pre_lnorm\n\n def forward(self, inp):\n if self.pre_lnorm:\n ##### layer normalization + positionwise feed-forward\n core_out = self.CoreNet(self.layer_norm(inp))\n\n ##### residual connection\n output = core_out + inp\n else:\n ##### positionwise feed-forward\n core_out = self.CoreNet(inp)\n\n ##### residual connection + layer normalization\n output = self.layer_norm(inp + core_out)\n\n return output\n\nclass MultiHeadAttn(nn.Module):\n def __init__(self, n_head, d_model, d_head, dropout, dropatt=0,\n pre_lnorm=False):\n super(MultiHeadAttn, self).__init__()\n\n self.n_head = n_head\n self.d_model = d_model\n self.d_head = d_head\n self.dropout = dropout\n\n self.q_net = nn.Linear(d_model, n_head * d_head, bias=False)\n self.kv_net = nn.Linear(d_model, 2 * n_head * d_head, bias=False)\n\n self.drop = nn.Dropout(dropout)\n self.dropatt = nn.Dropout(dropatt)\n self.o_net = nn.Linear(n_head * d_head, d_model, bias=False)\n\n self.layer_norm = nn.LayerNorm(d_model)\n\n self.scale = 1 / (d_head ** 0.5)\n\n self.pre_lnorm = pre_lnorm\n\n def forward(self, h, attn_mask=None, mems=None):\n ##### multihead attention\n # [hlen x bsz x n_head x d_head]\n\n if mems is not None:\n c = torch.cat([mems, h], 0)\n else:\n c = h\n\n if self.pre_lnorm:\n ##### layer normalization\n c = self.layer_norm(c)\n\n head_q = self.q_net(h)\n head_k, head_v = torch.chunk(self.kv_net(c), 2, -1)\n\n head_q = head_q.view(h.size(0), h.size(1), self.n_head, self.d_head)\n head_k = head_k.view(c.size(0), c.size(1), self.n_head, self.d_head)\n head_v = head_v.view(c.size(0), c.size(1), self.n_head, self.d_head)\n\n # [qlen x klen x bsz x n_head]\n attn_score = torch.einsum('ibnd,jbnd->ijbn', (head_q, head_k))\n attn_score.mul_(self.scale)\n if attn_mask is not None and attn_mask.any().item():\n if attn_mask.dim() == 2:\n attn_score.masked_fill_(attn_mask[None,:,:,None].bool(), -float('inf'))\n elif attn_mask.dim() == 3:\n attn_score.masked_fill_(attn_mask[:,:,:,None].bool(), -float('inf'))\n\n # [qlen x klen x bsz x n_head]\n attn_prob = F.softmax(attn_score, dim=1)\n attn_prob = self.dropatt(attn_prob)\n\n # [qlen x klen x bsz x n_head] + [klen x bsz x n_head x d_head] -> [qlen x bsz x n_head x d_head]\n attn_vec = torch.einsum('ijbn,jbnd->ibnd', (attn_prob, head_v))\n attn_vec = attn_vec.contiguous().view(\n attn_vec.size(0), attn_vec.size(1), self.n_head * self.d_head)\n\n ##### linear projection\n attn_out = self.o_net(attn_vec)\n attn_out = self.drop(attn_out)\n\n if self.pre_lnorm:\n ##### residual connection\n output = h + attn_out\n else:\n ##### residual connection + layer normalization\n output = self.layer_norm(h + attn_out)\n\n return output\n\nclass RelMultiHeadAttn(nn.Module):\n def __init__(self, n_head, d_model, d_head, dropout, dropatt=0,\n tgt_len=None, ext_len=None, mem_len=None, pre_lnorm=False,\n moe=False, moe_num_expert=64, moe_top_k=2):\n super(RelMultiHeadAttn, self).__init__()\n\n self.n_head = n_head\n self.d_model = d_model\n self.d_head = d_head\n self.dropout = dropout\n\n self.qkv_net = nn.Linear(d_model, 3 * n_head * d_head, bias=False)\n\n self.drop = nn.Dropout(dropout)\n self.dropatt = nn.Dropout(dropatt)\n self.o_net = nn.Linear(n_head * d_head, d_model, bias=False)\n\n self.layer_norm = nn.LayerNorm(d_model)\n\n self.scale = 1 / (d_head ** 0.5)\n\n self.pre_lnorm = pre_lnorm\n\n def _parallelogram_mask(self, h, w, left=False):\n mask = torch.ones((h, w)).byte()\n m = min(h, w)\n mask[:m,:m] = torch.triu(mask[:m,:m])\n mask[-m:,-m:] = torch.tril(mask[-m:,-m:])\n\n if left:\n return mask\n else:\n return mask.flip(0)\n\n def _shift(self, x, qlen, klen, mask, left=False):\n if qlen > 1:\n zero_pad = torch.zeros((x.size(0), qlen-1, x.size(2), x.size(3)),\n device=x.device, dtype=x.dtype)\n else:\n zero_pad = torch.zeros(0, device=x.device, dtype=x.dtype)\n\n if left:\n mask = mask.flip(1)\n x_padded = torch.cat([zero_pad, x], dim=1).expand(qlen, -1, -1, -1)\n else:\n x_padded = torch.cat([x, zero_pad], dim=1).expand(qlen, -1, -1, -1)\n\n x = x_padded.masked_select(mask[:,:,None,None]) \\\n .view(qlen, klen, x.size(2), x.size(3))\n\n return x\n\n def _rel_shift(self, x, zero_triu=False):\n zero_pad = torch.zeros((x.size(0), 1, *x.size()[2:]),\n device=x.device, dtype=x.dtype)\n x_padded = torch.cat([zero_pad, x], dim=1)\n\n x_padded = x_padded.view(x.size(1) + 1, x.size(0), *x.size()[2:])\n\n x = x_padded[1:].view_as(x)\n\n if zero_triu:\n ones = torch.ones((x.size(0), x.size(1)))\n x = x * torch.tril(ones, x.size(1) - x.size(0))[:,:,None,None]\n\n return x\n\n def forward(self, w, r, attn_mask=None, mems=None):\n raise NotImplementedError\n\nclass RelPartialLearnableMultiHeadAttn(RelMultiHeadAttn):\n def __init__(self, *args, **kwargs):\n super(RelPartialLearnableMultiHeadAttn, self).__init__(*args, **kwargs)\n\n self.r_net = nn.Linear(self.d_model, self.n_head * self.d_head, bias=False)\n\n def forward(self, w, r, r_w_bias, r_r_bias, attn_mask=None, mems=None):\n qlen, rlen, bsz = w.size(0), r.size(0), w.size(1)\n\n if mems is not None:\n cat = torch.cat([mems, w], 0)\n if self.pre_lnorm:\n w_heads = self.qkv_net(self.layer_norm(cat))\n else:\n w_heads = self.qkv_net(cat)\n r_head_k = self.r_net(r)\n\n w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1)\n w_head_q = w_head_q[-qlen:]\n else:\n if self.pre_lnorm:\n w_heads = self.qkv_net(self.layer_norm(w))\n else:\n w_heads = self.qkv_net(w)\n r_head_k = self.r_net(r)\n\n w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1)\n\n klen = w_head_k.size(0)\n\n w_head_q = w_head_q.view(qlen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head\n w_head_k = w_head_k.view(klen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head\n w_head_v = w_head_v.view(klen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head\n\n r_head_k = r_head_k.view(rlen, self.n_head, self.d_head) # qlen x n_head x d_head\n\n #### compute attention score\n rw_head_q = w_head_q + r_w_bias # qlen x bsz x n_head x d_head\n AC = torch.einsum('ibnd,jbnd->ijbn', (rw_head_q, w_head_k)) # qlen x klen x bsz x n_head\n\n rr_head_q = w_head_q + r_r_bias\n BD = torch.einsum('ibnd,jnd->ijbn', (rr_head_q, r_head_k)) # qlen x klen x bsz x n_head\n BD = self._rel_shift(BD)\n\n # [qlen x klen x bsz x n_head]\n attn_score = AC + BD\n attn_score.mul_(self.scale)\n\n #### compute attention probability\n if attn_mask is not None and attn_mask.any().item():\n if attn_mask.dim() == 2:\n attn_score = attn_score.float().masked_fill(\n attn_mask[None,:,:,None].bool(), -float('inf')).type_as(attn_score)\n elif attn_mask.dim() == 3:\n attn_score = attn_score.float().masked_fill(\n attn_mask[:,:,:,None].bool(), -float('inf')).type_as(attn_score)\n\n # [qlen x klen x bsz x n_head]\n attn_prob = F.softmax(attn_score, dim=1)\n attn_prob = self.dropatt(attn_prob)\n\n #### compute attention vector\n attn_vec = torch.einsum('ijbn,jbnd->ibnd', (attn_prob, w_head_v))\n\n # [qlen x bsz x n_head x d_head]\n attn_vec = attn_vec.contiguous().view(\n attn_vec.size(0), attn_vec.size(1), self.n_head * self.d_head)\n\n ##### linear projection\n attn_out = self.o_net(attn_vec)\n attn_out = self.drop(attn_out)\n\n if self.pre_lnorm:\n ##### residual connection\n output = w + attn_out\n else:\n ##### residual connection + layer normalization\n output = self.layer_norm(w + attn_out)\n\n return output\n\nclass RelLearnableMultiHeadAttn(RelMultiHeadAttn):\n def __init__(self, *args, **kwargs):\n super(RelLearnableMultiHeadAttn, self).__init__(*args, **kwargs)\n\n def forward(self, w, r_emb, r_w_bias, r_bias, attn_mask=None, mems=None):\n # r_emb: [klen, n_head, d_head], used for term B\n # r_w_bias: [n_head, d_head], used for term C\n # r_bias: [klen, n_head], used for term D\n\n qlen, bsz = w.size(0), w.size(1)\n\n if mems is not None:\n cat = torch.cat([mems, w], 0)\n if self.pre_lnorm:\n w_heads = self.qkv_net(self.layer_norm(cat))\n else:\n w_heads = self.qkv_net(cat)\n w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1)\n\n w_head_q = w_head_q[-qlen:]\n else:\n if self.pre_lnorm:\n w_heads = self.qkv_net(self.layer_norm(w))\n else:\n w_heads = self.qkv_net(w)\n w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1)\n\n klen = w_head_k.size(0)\n\n w_head_q = w_head_q.view(qlen, bsz, self.n_head, self.d_head)\n w_head_k = w_head_k.view(klen, bsz, self.n_head, self.d_head)\n w_head_v = w_head_v.view(klen, bsz, self.n_head, self.d_head)\n\n if klen > r_emb.size(0):\n r_emb_pad = r_emb[0:1].expand(klen-r_emb.size(0), -1, -1)\n r_emb = torch.cat([r_emb_pad, r_emb], 0)\n r_bias_pad = r_bias[0:1].expand(klen-r_bias.size(0), -1)\n r_bias = torch.cat([r_bias_pad, r_bias], 0)\n else:\n r_emb = r_emb[-klen:]\n r_bias = r_bias[-klen:]\n\n #### compute attention score\n rw_head_q = w_head_q + r_w_bias[None] # qlen x bsz x n_head x d_head\n\n AC = torch.einsum('ibnd,jbnd->ijbn', (rw_head_q, w_head_k)) # qlen x klen x bsz x n_head\n B_ = torch.einsum('ibnd,jnd->ijbn', (w_head_q, r_emb)) # qlen x klen x bsz x n_head\n D_ = r_bias[None, :, None] # 1 x klen x 1 x n_head\n BD = self._rel_shift(B_ + D_)\n\n # [qlen x klen x bsz x n_head]\n attn_score = AC + BD\n attn_score.mul_(self.scale)\n\n #### compute attention probability\n if attn_mask is not None and attn_mask.any().item():\n if attn_mask.dim() == 2:\n attn_score.masked_fill_(attn_mask[None,:,:,None].bool(), -float('inf'))\n elif attn_mask.dim() == 3:\n attn_score.masked_fill_(attn_mask[:,:,:,None].bool(), -float('inf'))\n\n # [qlen x klen x bsz x n_head]\n attn_prob = F.softmax(attn_score, dim=1)\n attn_prob = self.dropatt(attn_prob)\n\n #### compute attention vector\n attn_vec = torch.einsum('ijbn,jbnd->ibnd', (attn_prob, w_head_v))\n\n # [qlen x bsz x n_head x d_head]\n attn_vec = attn_vec.contiguous().view(\n attn_vec.size(0), attn_vec.size(1), self.n_head * self.d_head)\n\n ##### linear projection\n attn_out = self.o_net(attn_vec)\n attn_out = self.drop(attn_out)\n\n if self.pre_lnorm:\n ##### residual connection\n output = w + attn_out\n else:\n ##### residual connection + layer normalization\n output = self.layer_norm(w + attn_out)\n\n return output\n\nfrom fmoe import FMoETransformerMLP\nclass CustomizedMoEPositionwiseFF(FMoETransformerMLP):\n def __init__(self, d_model, d_inner, dropout, pre_lnorm=False, moe_num_expert=64, moe_top_k=2):\n activation = nn.Sequential(\n nn.ReLU(),\n nn.Dropout(dropout)\n )\n super().__init__(num_expert=moe_num_expert, d_model=d_model, d_hidden=d_inner, top_k=moe_top_k,\n activation=activation)\n\n self.pre_lnorm = pre_lnorm\n self.layer_norm = nn.LayerNorm(d_model)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, inp):\n if self.pre_lnorm:\n ##### layer normalization + positionwise feed-forward\n core_out = super().forward(self.layer_norm(inp))\n core_out = self.dropout(core_out)\n\n ##### residual connection\n output = core_out + inp\n else:\n ##### positionwise feed-forward\n core_out = super().forward(inp)\n core_out = self.dropout(core_out)\n\n ##### residual connection + layer normalization\n output = self.layer_norm(inp + core_out)\n\n return output\n\nclass DecoderLayer(nn.Module):\n def __init__(self, n_head, d_model, d_head, d_inner, dropout, **kwargs):\n super(DecoderLayer, self).__init__()\n\n self.dec_attn = MultiHeadAttn(n_head, d_model, d_head, dropout, **kwargs)\n if kwargs.get('moe') is False:\n self.pos_ff = PositionwiseFF(d_model, d_inner, dropout, \n pre_lnorm=kwargs.get('pre_lnorm'))\n else:\n self.pos_ff = CustomizedMoEPositionwiseFF(d_model, d_inner, dropout,\n pre_lnorm=kwargs.get('pre_lnorm'), \n moe_num_expert=kwargs.get('moe_num_expert'),\n moe_top_k=kwargs.get('moe_top_k'))\n\n def forward(self, dec_inp, dec_attn_mask=None, mems=None):\n\n output = self.dec_attn(dec_inp, attn_mask=dec_attn_mask,\n mems=mems)\n output = self.pos_ff(output)\n\n return output\n\nclass RelLearnableDecoderLayer(nn.Module):\n def __init__(self, n_head, d_model, d_head, d_inner, dropout,\n **kwargs):\n super(RelLearnableDecoderLayer, self).__init__()\n\n self.dec_attn = RelLearnableMultiHeadAttn(n_head, d_model, d_head, dropout,\n **kwargs)\n\n if kwargs.get('moe') is False:\n self.pos_ff = PositionwiseFF(d_model, d_inner, dropout, \n pre_lnorm=kwargs.get('pre_lnorm'))\n else:\n self.pos_ff = CustomizedMoEPositionwiseFF(d_model, d_inner, dropout,\n pre_lnorm=kwargs.get('pre_lnorm'),\n moe_num_expert=kwargs.get('moe_num_expert'),\n moe_top_k=kwargs.get('moe_top_k'))\n\n def forward(self, dec_inp, r_emb, r_w_bias, r_bias, dec_attn_mask=None, mems=None):\n\n output = self.dec_attn(dec_inp, r_emb, r_w_bias, r_bias,\n attn_mask=dec_attn_mask,\n mems=mems)\n output = self.pos_ff(output)\n\n return output\n\nclass RelPartialLearnableDecoderLayer(nn.Module):\n def __init__(self, n_head, d_model, d_head, d_inner, dropout,\n **kwargs):\n super(RelPartialLearnableDecoderLayer, self).__init__()\n\n self.dec_attn = RelPartialLearnableMultiHeadAttn(n_head, d_model,\n d_head, dropout, **kwargs)\n\n if kwargs.get('moe') is False:\n self.pos_ff = PositionwiseFF(d_model, d_inner, dropout, \n pre_lnorm=kwargs.get('pre_lnorm'))\n else:\n self.pos_ff = CustomizedMoEPositionwiseFF(d_model, d_inner, dropout,\n pre_lnorm=kwargs.get('pre_lnorm'),\n moe_num_expert=kwargs.get('moe_num_expert'),\n moe_top_k=kwargs.get('moe_top_k'))\n\n def forward(self, dec_inp, r, r_w_bias, r_r_bias, dec_attn_mask=None, mems=None):\n\n output = self.dec_attn(dec_inp, r, r_w_bias, r_r_bias,\n attn_mask=dec_attn_mask,\n mems=mems)\n output = self.pos_ff(output)\n\n return output\n\n\nclass AdaptiveEmbedding(nn.Module):\n def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1,\n sample_softmax=False):\n super(AdaptiveEmbedding, self).__init__()\n\n self.n_token = n_token\n self.d_embed = d_embed\n\n self.cutoffs = cutoffs + [n_token]\n self.div_val = div_val\n self.d_proj = d_proj\n\n self.emb_scale = d_proj ** 0.5\n\n self.cutoff_ends = [0] + self.cutoffs\n\n self.emb_layers = nn.ModuleList()\n self.emb_projs = nn.ModuleList()\n\n if div_val == 1:\n self.emb_layers.append(\n nn.Embedding(n_token, d_embed, sparse=sample_softmax>0)\n )\n if d_proj != d_embed:\n self.emb_projs.append(Projection(d_proj, d_embed))\n else:\n for i in range(len(self.cutoffs)):\n l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i+1]\n d_emb_i = d_embed // (div_val ** i)\n self.emb_layers.append(nn.Embedding(r_idx-l_idx, d_emb_i))\n self.emb_projs.append(Projectio(d_proj, d_emb_i))\n\n def forward(self, inp):\n if self.div_val == 1:\n embed = self.emb_layers[0](inp)\n if self.d_proj != self.d_embed:\n embed = F.linear(embed, self.emb_projs[0].weight)\n else:\n param = next(self.parameters())\n inp_flat = inp.view(-1)\n emb_flat = torch.zeros([inp_flat.size(0), self.d_proj],\n dtype=param.dtype, device=param.device)\n for i in range(len(self.cutoffs)):\n l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]\n\n mask_i = (inp_flat >= l_idx) & (inp_flat < r_idx)\n indices_i = mask_i.nonzero().squeeze()\n\n if indices_i.numel() == 0:\n continue\n\n inp_i = inp_flat.index_select(0, indices_i) - l_idx\n emb_i = self.emb_layers[i](inp_i)\n emb_i = F.linear(emb_i, self.emb_projs[i].weight)\n\n emb_flat.index_copy_(0, indices_i, emb_i)\n\n embed = emb_flat.view(*inp.size(), self.d_proj)\n\n embed.mul_(self.emb_scale)\n\n return embed\n\nclass MemTransformerLM(nn.Module):\n def __init__(self, n_token, n_layer, n_head, d_model, d_head, d_inner,\n dropout, dropatt, tie_weight=True, d_embed=None,\n div_val=1, tie_projs=[False], pre_lnorm=False,\n tgt_len=None, ext_len=None, mem_len=None,\n cutoffs=[], adapt_inp=False,\n same_length=False, attn_type=0, clamp_len=-1,\n sample_softmax=-1, moe=False, moe_num_expert=64, moe_top_k=2):\n super(MemTransformerLM, self).__init__()\n self.n_token = n_token\n\n d_embed = d_model if d_embed is None else d_embed\n self.d_embed = d_embed\n self.d_model = d_model\n self.n_head = n_head\n self.d_head = d_head\n\n self.word_emb = AdaptiveEmbedding(n_token, d_embed, d_model, cutoffs,\n div_val=div_val)\n\n self.drop = nn.Dropout(dropout)\n\n self.n_layer = n_layer\n\n self.tgt_len = tgt_len\n self.mem_len = mem_len\n self.ext_len = ext_len\n self.max_klen = tgt_len + ext_len + mem_len\n\n self.attn_type = attn_type\n\n self.layers = nn.ModuleList()\n if attn_type == 0: # the default attention\n for i in range(n_layer):\n self.layers.append(\n RelPartialLearnableDecoderLayer(\n n_head, d_model, d_head, d_inner, dropout,\n tgt_len=tgt_len, ext_len=ext_len, mem_len=mem_len,\n dropatt=dropatt, pre_lnorm=pre_lnorm, \n moe=moe, moe_num_expert=moe_num_expert, moe_top_k=moe_top_k)\n )\n elif attn_type == 1: # learnable embeddings\n for i in range(n_layer):\n self.layers.append(\n RelLearnableDecoderLayer(\n n_head, d_model, d_head, d_inner, dropout,\n tgt_len=tgt_len, ext_len=ext_len, mem_len=mem_len,\n dropatt=dropatt, pre_lnorm=pre_lnorm,\n moe=moe, moe_num_expert=moe_num_expert, moe_top_k=moe_top_k)\n )\n elif attn_type in [2, 3]: # absolute embeddings\n for i in range(n_layer):\n self.layers.append(\n DecoderLayer(\n n_head, d_model, d_head, d_inner, dropout,\n dropatt=dropatt, pre_lnorm=pre_lnorm,\n moe=moe, moe_num_expert=moe_num_expert, moe_top_k=moe_top_k)\n )\n\n self.sample_softmax = sample_softmax\n # use sampled softmax\n if sample_softmax > 0:\n self.out_layer = nn.Linear(d_model, n_token)\n if tie_weight:\n self.out_layer.weight = self.word_emb.weight\n self.tie_weight = tie_weight\n self.sampler = LogUniformSampler(n_token, sample_softmax)\n\n # use adaptive softmax (including standard softmax)\n else:\n self.crit = ProjectedAdaptiveLogSoftmax(n_token, d_embed, d_model,\n cutoffs, div_val=div_val)\n\n if tie_weight:\n for i in range(len(self.crit.out_layers)):\n self.crit.out_layers[i].weight = self.word_emb.emb_layers[i].weight\n\n if tie_projs:\n for i, tie_proj in enumerate(tie_projs):\n if tie_proj and div_val == 1 and d_model != d_embed:\n self.crit.out_projs[i].weight = self.word_emb.emb_projs[0].weight\n elif tie_proj and div_val != 1:\n self.crit.out_projs[i].weight = self.word_emb.emb_projs[i].weight\n\n self.same_length = same_length\n self.clamp_len = clamp_len\n\n self._create_params()\n\n def backward_compatible(self):\n self.sample_softmax = -1\n\n def _create_params(self):\n if self.attn_type == 0: # default attention\n self.pos_emb = PositionalEmbedding(self.d_model)\n self.r_w_bias = nn.Parameter(torch.Tensor(self.n_head, self.d_head))\n self.r_r_bias = nn.Parameter(torch.Tensor(self.n_head, self.d_head))\n elif self.attn_type == 1: # learnable\n self.r_emb = nn.Parameter(torch.Tensor(\n self.n_layer, self.max_klen, self.n_head, self.d_head))\n self.r_w_bias = nn.Parameter(torch.Tensor(\n self.n_layer, self.n_head, self.d_head))\n self.r_bias = nn.Parameter(torch.Tensor(\n self.n_layer, self.max_klen, self.n_head))\n elif self.attn_type == 2: # absolute standard\n self.pos_emb = PositionalEmbedding(self.d_model)\n elif self.attn_type == 3: # absolute deeper SA\n self.r_emb = nn.Parameter(torch.Tensor(\n self.n_layer, self.max_klen, self.n_head, self.d_head))\n\n def reset_length(self, tgt_len, ext_len, mem_len):\n self.tgt_len = tgt_len\n self.mem_len = mem_len\n self.ext_len = ext_len\n\n def init_mems(self, x):\n if self.mem_len > 0:\n mems = []\n for i in range(self.n_layer+1):\n empty = torch.empty(0, dtype=x.dtype, device=x.device)\n mems.append(empty)\n\n return mems\n else:\n return None\n\n def _update_mems(self, hids, mems, qlen, mlen):\n # does not deal with None\n if mems is None: return None\n\n # mems is not None\n assert len(hids) == len(mems), 'len(hids) != len(mems)'\n\n # There are `mlen + qlen` steps that can be cached into mems\n # For the next step, the last `ext_len` of the `qlen` tokens\n # will be used as the extended context. Hence, we only cache\n # the tokens from `mlen + qlen - self.ext_len - self.mem_len`\n # to `mlen + qlen - self.ext_len`.\n with torch.no_grad():\n new_mems = []\n end_idx = mlen + max(0, qlen - 0 - self.ext_len)\n beg_idx = max(0, end_idx - self.mem_len)\n for i in range(len(hids)):\n\n cat = torch.cat([mems[i], hids[i]], dim=0)\n new_mems.append(cat[beg_idx:end_idx].detach())\n\n return new_mems\n\n def _forward(self, dec_inp, mems=None):\n qlen, bsz = dec_inp.size()\n\n word_emb = self.word_emb(dec_inp)\n\n mlen = mems[0].size(0) if mems is not None else 0\n klen = mlen + qlen\n if self.same_length:\n all_ones = word_emb.new_ones(qlen, klen)\n mask_len = klen - self.mem_len\n if mask_len > 0:\n mask_shift_len = qlen - mask_len\n else:\n mask_shift_len = qlen\n dec_attn_mask = (torch.triu(all_ones, 1+mlen)\n + torch.tril(all_ones, -mask_shift_len)).byte()[:, :, None] # -1\n else:\n dec_attn_mask = torch.triu(\n word_emb.new_ones(qlen, klen), diagonal=1+mlen).byte()[:,:,None]\n\n hids = []\n if self.attn_type == 0: # default\n pos_seq = torch.arange(klen-1, -1, -1.0, device=word_emb.device,\n dtype=word_emb.dtype)\n if self.clamp_len > 0:\n pos_seq.clamp_(max=self.clamp_len)\n pos_emb = self.pos_emb(pos_seq)\n\n core_out = self.drop(word_emb)\n pos_emb = self.drop(pos_emb)\n\n hids.append(core_out)\n for i, layer in enumerate(self.layers):\n mems_i = None if mems is None else mems[i]\n core_out = layer(core_out, pos_emb, self.r_w_bias,\n self.r_r_bias, dec_attn_mask=dec_attn_mask, mems=mems_i)\n hids.append(core_out)\n elif self.attn_type == 1: # learnable\n core_out = self.drop(word_emb)\n hids.append(core_out)\n for i, layer in enumerate(self.layers):\n if self.clamp_len > 0:\n r_emb = self.r_emb[i][-self.clamp_len :]\n r_bias = self.r_bias[i][-self.clamp_len :]\n else:\n r_emb, r_bias = self.r_emb[i], self.r_bias[i]\n\n mems_i = None if mems is None else mems[i]\n core_out = layer(core_out, r_emb, self.r_w_bias[i],\n r_bias, dec_attn_mask=dec_attn_mask, mems=mems_i)\n hids.append(core_out)\n elif self.attn_type == 2: # absolute\n pos_seq = torch.arange(klen - 1, -1, -1.0, device=word_emb.device,\n dtype=word_emb.dtype)\n if self.clamp_len > 0:\n pos_seq.clamp_(max=self.clamp_len)\n pos_emb = self.pos_emb(pos_seq)\n\n core_out = self.drop(word_emb + pos_emb[-qlen:])\n\n hids.append(core_out)\n for i, layer in enumerate(self.layers):\n mems_i = None if mems is None else mems[i]\n if mems_i is not None and i == 0:\n mems_i += pos_emb[:mlen]\n core_out = layer(core_out, dec_attn_mask=dec_attn_mask,\n mems=mems_i)\n hids.append(core_out)\n elif self.attn_type == 3:\n core_out = self.drop(word_emb)\n\n hids.append(core_out)\n for i, layer in enumerate(self.layers):\n mems_i = None if mems is None else mems[i]\n if mems_i is not None and mlen > 0:\n cur_emb = self.r_emb[i][:-qlen]\n cur_size = cur_emb.size(0)\n if cur_size < mlen:\n cur_emb_pad = cur_emb[0:1].expand(mlen-cur_size, -1, -1)\n cur_emb = torch.cat([cur_emb_pad, cur_emb], 0)\n else:\n cur_emb = cur_emb[-mlen:]\n mems_i += cur_emb.view(mlen, 1, -1)\n core_out += self.r_emb[i][-qlen:].view(qlen, 1, -1)\n\n core_out = layer(core_out, dec_attn_mask=dec_attn_mask,\n mems=mems_i)\n hids.append(core_out)\n\n core_out = self.drop(core_out)\n\n new_mems = self._update_mems(hids, mems, mlen, qlen)\n\n return core_out, new_mems\n\n def forward(self, data, target, *mems):\n # nn.DataParallel does not allow size(0) tensors to be broadcasted.\n # So, have to initialize size(0) mems inside the model forward.\n # Moreover, have to return new_mems to allow nn.DataParallel to piece\n # them together.\n if not mems: mems = self.init_mems(data)\n\n tgt_len = target.size(0)\n hidden, new_mems = self._forward(data, mems=mems)\n\n pred_hid = hidden[-tgt_len:]\n if self.sample_softmax > 0 and self.training:\n assert self.tie_weight\n logit = sample_logits(self.word_emb,\n self.out_layer.bias, target, pred_hid, self.sampler)\n loss = -F.log_softmax(logit, -1)[:, :, 0]\n else:\n loss = self.crit(pred_hid.view(-1, pred_hid.size(-1)), target.contiguous().view(-1))\n loss = loss.view(tgt_len, -1)\n\n if new_mems is None:\n return [loss]\n else:\n return [loss] + new_mems\n\nif __name__ == '__main__':\n import argparse\n\n parser = argparse.ArgumentParser(description='unit test')\n\n parser.add_argument('--n_layer', type=int, default=4, help='')\n parser.add_argument('--n_rel_layer', type=int, default=4, help='')\n parser.add_argument('--n_head', type=int, default=2, help='')\n parser.add_argument('--d_head', type=int, default=2, help='')\n parser.add_argument('--d_model', type=int, default=200, help='')\n parser.add_argument('--d_embed', type=int, default=200, help='')\n parser.add_argument('--d_inner', type=int, default=200, help='')\n parser.add_argument('--dropout', type=float, default=0.0, help='')\n parser.add_argument('--cuda', action='store_true', help='')\n parser.add_argument('--seed', type=int, default=1111, help='')\n parser.add_argument('--multi_gpu', action='store_true', help='')\n\n args = parser.parse_args()\n\n device = torch.device(\"cuda\" if args.cuda else \"cpu\")\n\n B = 4\n tgt_len, mem_len, ext_len = 36, 36, 0\n data_len = tgt_len * 20\n args.n_token = 10000\n\n import data_utils\n\n data = torch.LongTensor(data_len*B).random_(0, args.n_token).to(device)\n diter = data_utils.LMOrderedIterator(data, B, tgt_len, device=device, ext_len=ext_len)\n\n cutoffs = [args.n_token // 2]\n tie_projs = [False] + [True] * len(cutoffs)\n\n for div_val in [1, 2]:\n for d_embed in [200, 100]:\n model = MemTransformerLM(args.n_token, args.n_layer, args.n_head,\n args.d_model, args.d_head, args.d_inner, args.dropout,\n dropatt=args.dropout, tie_weight=True,\n d_embed=d_embed, div_val=div_val,\n tie_projs=tie_projs, pre_lnorm=True,\n tgt_len=tgt_len, ext_len=ext_len, mem_len=mem_len,\n cutoffs=cutoffs, attn_type=0).to(device)\n\n print(sum(p.numel() for p in model.parameters()))\n\n mems = tuple()\n for idx, (inp, tgt, seqlen) in enumerate(diter):\n print('batch {}'.format(idx))\n out = model(inp, tgt, *mems)\n mems = out[1:]\n"
] |
[
[
"torch.nn.functional.softmax",
"torch.cat",
"torch.zeros",
"torch.nn.Embedding",
"torch.no_grad",
"torch.device",
"torch.triu",
"torch.nn.Dropout",
"torch.ones",
"torch.einsum",
"torch.tril",
"torch.arange",
"torch.nn.functional.linear",
"torch.LongTensor",
"torch.empty",
"torch.nn.ModuleList",
"torch.nn.Linear",
"torch.Tensor",
"torch.nn.functional.log_softmax",
"torch.nn.LayerNorm",
"torch.chunk",
"torch.nn.ReLU",
"torch.ger"
]
] |
sanowar-raihan/meta-neus
|
[
"de58a303498423b674f0b03c4682b11e995c3064"
] |
[
"models/rendering.py"
] |
[
"import torch\nimport torch.nn as nn\nfrom models.networks import GeometryNet, AppearanceNet, SDensity\n\n\nclass NeuSRenderer(nn.Module):\n \"\"\"\n Neural Renderer according to NeuS \n https://arxiv.org/abs/2106.10689\n \"\"\"\n def __init__(self,\n geometry_net,\n appearance_net,\n s_density,\n num_samples,\n perturb,\n white_bkgd):\n \"\"\"\n Args:\n geometry_net (nn.Module): geoemtry network\n appearance_net (nn.Module): appearance network\n s_density (nn.Module): single parameter s_density network\n num_samples (int): number of points to sample along each ray\n perturb (bool): if True, use randomized stratified sampling\n white_bkgd (bool): if True, assume white background\n \"\"\"\n super().__init__()\n\n self.geometry_net = geometry_net\n self.appearance_net = appearance_net\n self.s_density = s_density\n self.num_samples = num_samples\n self.perturb = perturb\n self.white_bkgd = white_bkgd\n\n def forward(self, rays_o, rays_d):\n \"\"\"\n Given a camera ray, render its color\n\n Inputs:\n rays_o [batch_size, 3]: ray origins\n rays_d [batch_size, 3]: ray directions\n \"\"\"\n near, far = self.near_far(rays_o, rays_d)\n t_vals, points = self.sample_points(rays_o, rays_d, near, far) # [batch_size, num_samples+1],\n # [batch_size, num_samples, 3]\n rays_d = rays_d[..., None, :].expand_as(points) # [batch_size, num_samples, 3]\n\n sdf, geometric_feature = self.geometry_net(points) # [batch_size, num_samples],\n # [batch_size, num_samples, feature_dim]\n sdf_grad = self.geometry_net.gradient(sdf, points) # [batch_size, num_samples, 3]\n \n rgb = self.appearance_net(points, rays_d, sdf_grad, geometric_feature) # [batch_size, num_samples, 3]\n \n dists = t_vals[..., 1:] - t_vals[..., :-1] # [batch_size, num_samples]\n grad_proj = torch.einsum(\"ijk, ijk -> ij\", sdf_grad, rays_d) # [batch_size, num_samples]\n\n prev_sdf = sdf - 0.5 * grad_proj * dists # [batch_size, num_samples]\n next_sdf = sdf + 0.5 * grad_proj * dists # [batch_size, num_samples]\n\n inv_s = self.s_density().clip(1e-7, 1e7)\n prev_cdf = torch.sigmoid(prev_sdf * inv_s) # [batch_size, num_samples]\n next_cdf = torch.sigmoid(next_sdf * inv_s) # [batch_size, num_samples]\n alpha = (prev_cdf - next_cdf) / (prev_cdf + 1e-7) # [batch_size, num_samples]\n alpha = alpha.clip(0.0, 1.0)\n\n transparency = torch.cat([\n torch.ones_like(alpha[:, :1]),\n torch.cumprod(1 - alpha[:, :-1] + 1e-7, dim=-1)\n ], dim=-1) # [batch_size, num_samples]\n weight = alpha * transparency # [batch_size, num_samples]\n weight_sum = weight.sum(dim=-1, keepdim=True) # [batch_size, 1]\n\n color = torch.einsum(\"bnc, bn -> bc\", rgb, weight) # [batch_size, 3]\n if self.white_bkgd:\n color = color + (1 - weight_sum)\n \n return {\n \"color\": color,\n \"sdf_grad\": sdf_grad,\n \"weight_sum\": weight_sum\n }\n\n def near_far(self, rays_o, rays_d):\n \"\"\"\n For each ray, find the nearest point on the ray to the origin (with depth mid).\n Then define the near and far bounds as mid-1 and mid+1.\n https://github.com/Totoro97/NeuS/issues/11\n \n Inputs:\n rays_o [batch_size, 3]: ray origins\n rays_d [batch_size, 3]: ray directions\n Outputs:\n near [batch_size, 1]: near bound of the rays\n far [batch_size, 1]: far bound of the rays\n \"\"\"\n mid = -torch.einsum(\"ij, ij -> i\", rays_o, rays_d)\n near, far = mid - 1.0, mid + 1.0\n\n return near[..., None], far[..., None]\n\n def sample_points(self, rays_o, rays_d, near, far):\n \"\"\"\n Sample points along the ray\n\n Inputs:\n rays_o [batch_size, 3]: ray origins\n rays_d [batch_size, 3]: ray directions\n near [batch_size, 1]: near bound of the rays\n far [batch_size, 1]: far bound of the rays\n Outputs:\n t_vals [batch_size, num_samples+1]: sampled t values\n points [batch_size, num_samples, 3]: coordinate of the sampled points\n \"\"\"\n t_vals = torch.linspace(0., 1., self.num_samples+1,\n device=rays_o.device) # [num_samples+1]\n t_vals = near + (far - near) * t_vals[None, ...] # [batch_size, num_samples+1]\n t_mids = 0.5 * (t_vals[..., :-1] + t_vals[..., 1:]) # [batch_size, num_samples]\n if self.perturb:\n rand = torch.rand_like(t_mids) - 0.5\n t_mids = t_mids + rand * 2.0/self.num_samples\n \n points = rays_o[..., None, :] + rays_d[..., None, :] * t_mids[..., None] # [batch_size, num_samples, 3]\n\n return t_vals, points\n\n\ndef build_neus(conf):\n \"\"\"\n Build NeuS Renderer from config\n \"\"\"\n geometry_net = GeometryNet(**conf[\"geometry_net\"])\n appearance_net = AppearanceNet(**conf[\"appearance_net\"])\n s_density = SDensity(**conf[\"s_density\"])\n\n model = NeuSRenderer(geometry_net,\n appearance_net,\n s_density,\n **conf[\"neus\"])\n return model\n"
] |
[
[
"torch.linspace",
"torch.sigmoid",
"torch.rand_like",
"torch.einsum",
"torch.cumprod",
"torch.ones_like"
]
] |
boeleman/scipy
|
[
"e8212863a7c09e047e78a9a8f983527ad01c69fc"
] |
[
"scipy/stats/tests/test_discrete_basic.py"
] |
[
"import numpy.testing as npt\nimport numpy as np\nimport pytest\n\nfrom scipy import stats\nfrom .common_tests import (check_normalization, check_moment, check_mean_expect,\n check_var_expect, check_skew_expect,\n check_kurt_expect, check_entropy,\n check_private_entropy, check_edge_support,\n check_named_args, check_random_state_property,\n check_pickling, check_rvs_broadcast, check_freezing,\n check_deprecation_warning_gh5982_moment,\n check_deprecation_warning_gh5982_interval)\nfrom scipy.stats._distr_params import distdiscrete, invdistdiscrete\n\nvals = ([1, 2, 3, 4], [0.1, 0.2, 0.3, 0.4])\ndistdiscrete += [[stats.rv_discrete(values=vals), ()]]\n\n# For these distributions, test_discrete_basic only runs with test mode full\ndistslow = {'zipfian', 'nhypergeom'}\n\n\ndef cases_test_discrete_basic():\n seen = set()\n for distname, arg in distdiscrete:\n if distname in distslow:\n yield pytest.param(distname, arg, distname, marks=pytest.mark.slow)\n else:\n yield distname, arg, distname not in seen\n seen.add(distname)\n\n\[email protected]('distname,arg,first_case', cases_test_discrete_basic())\ndef test_discrete_basic(distname, arg, first_case):\n try:\n distfn = getattr(stats, distname)\n except TypeError:\n distfn = distname\n distname = 'sample distribution'\n np.random.seed(9765456)\n rvs = distfn.rvs(size=2000, *arg)\n supp = np.unique(rvs)\n m, v = distfn.stats(*arg)\n check_cdf_ppf(distfn, arg, supp, distname + ' cdf_ppf')\n\n check_pmf_cdf(distfn, arg, distname)\n check_oth(distfn, arg, supp, distname + ' oth')\n check_edge_support(distfn, arg)\n check_deprecation_warning_gh5982_moment(distfn, arg, distname)\n check_deprecation_warning_gh5982_interval(distfn, arg, distname)\n\n alpha = 0.01\n check_discrete_chisquare(distfn, arg, rvs, alpha,\n distname + ' chisquare')\n\n if first_case:\n locscale_defaults = (0,)\n meths = [distfn.pmf, distfn.logpmf, distfn.cdf, distfn.logcdf,\n distfn.logsf]\n # make sure arguments are within support\n # for some distributions, this needs to be overridden\n spec_k = {'randint': 11, 'hypergeom': 4, 'bernoulli': 0,\n 'nchypergeom_wallenius': 6}\n k = spec_k.get(distname, 1)\n check_named_args(distfn, k, arg, locscale_defaults, meths)\n if distname != 'sample distribution':\n check_scale_docstring(distfn)\n check_random_state_property(distfn, arg)\n check_pickling(distfn, arg)\n check_freezing(distfn, arg)\n\n # Entropy\n check_entropy(distfn, arg, distname)\n if distfn.__class__._entropy != stats.rv_discrete._entropy:\n check_private_entropy(distfn, arg, stats.rv_discrete)\n\n\[email protected]('distname,arg', distdiscrete)\ndef test_moments(distname, arg):\n try:\n distfn = getattr(stats, distname)\n except TypeError:\n distfn = distname\n distname = 'sample distribution'\n m, v, s, k = distfn.stats(*arg, moments='mvsk')\n check_normalization(distfn, arg, distname)\n\n # compare `stats` and `moment` methods\n check_moment(distfn, arg, m, v, distname)\n check_mean_expect(distfn, arg, m, distname)\n check_var_expect(distfn, arg, m, v, distname)\n check_skew_expect(distfn, arg, m, v, s, distname)\n if distname not in ['zipf', 'yulesimon']:\n check_kurt_expect(distfn, arg, m, v, k, distname)\n\n # frozen distr moments\n check_moment_frozen(distfn, arg, m, 1)\n check_moment_frozen(distfn, arg, v+m*m, 2)\n\n\[email protected]('dist,shape_args', distdiscrete)\ndef test_rvs_broadcast(dist, shape_args):\n # If shape_only is True, it means the _rvs method of the\n # distribution uses more than one random number to generate a random\n # variate. That means the result of using rvs with broadcasting or\n # with a nontrivial size will not necessarily be the same as using the\n # numpy.vectorize'd version of rvs(), so we can only compare the shapes\n # of the results, not the values.\n # Whether or not a distribution is in the following list is an\n # implementation detail of the distribution, not a requirement. If\n # the implementation the rvs() method of a distribution changes, this\n # test might also have to be changed.\n shape_only = dist in ['betabinom', 'skellam', 'yulesimon', 'dlaplace',\n 'nchypergeom_fisher', 'nchypergeom_wallenius']\n\n try:\n distfunc = getattr(stats, dist)\n except TypeError:\n distfunc = dist\n dist = 'rv_discrete(values=(%r, %r))' % (dist.xk, dist.pk)\n loc = np.zeros(2)\n nargs = distfunc.numargs\n allargs = []\n bshape = []\n # Generate shape parameter arguments...\n for k in range(nargs):\n shp = (k + 3,) + (1,)*(k + 1)\n param_val = shape_args[k]\n allargs.append(np.full(shp, param_val))\n bshape.insert(0, shp[0])\n allargs.append(loc)\n bshape.append(loc.size)\n # bshape holds the expected shape when loc, scale, and the shape\n # parameters are all broadcast together.\n check_rvs_broadcast(distfunc, dist, allargs, bshape, shape_only, [np.int_])\n\n\[email protected]('dist,args', distdiscrete)\ndef test_ppf_with_loc(dist, args):\n try:\n distfn = getattr(stats, dist)\n except TypeError:\n distfn = dist\n #check with a negative, no and positive relocation.\n np.random.seed(1942349)\n re_locs = [np.random.randint(-10, -1), 0, np.random.randint(1, 10)]\n _a, _b = distfn.support(*args)\n for loc in re_locs:\n npt.assert_array_equal(\n [_a-1+loc, _b+loc],\n [distfn.ppf(0.0, *args, loc=loc), distfn.ppf(1.0, *args, loc=loc)]\n )\n\n\[email protected]('dist, args', distdiscrete)\ndef test_isf_with_loc(dist, args):\n try:\n distfn = getattr(stats, dist)\n except TypeError:\n distfn = dist\n # check with a negative, no and positive relocation.\n np.random.seed(1942349)\n re_locs = [np.random.randint(-10, -1), 0, np.random.randint(1, 10)]\n _a, _b = distfn.support(*args)\n for loc in re_locs:\n expected = _b + loc, _a - 1 + loc\n res = distfn.isf(0., *args, loc=loc), distfn.isf(1., *args, loc=loc)\n npt.assert_array_equal(expected, res)\n # test broadcasting behaviour\n re_locs = [np.random.randint(-10, -1, size=(5, 3)),\n np.zeros((5, 3)),\n np.random.randint(1, 10, size=(5, 3))]\n _a, _b = distfn.support(*args)\n for loc in re_locs:\n expected = _b + loc, _a - 1 + loc\n res = distfn.isf(0., *args, loc=loc), distfn.isf(1., *args, loc=loc)\n npt.assert_array_equal(expected, res)\n\n\ndef check_cdf_ppf(distfn, arg, supp, msg):\n # cdf is a step function, and ppf(q) = min{k : cdf(k) >= q, k integer}\n npt.assert_array_equal(distfn.ppf(distfn.cdf(supp, *arg), *arg),\n supp, msg + '-roundtrip')\n npt.assert_array_equal(distfn.ppf(distfn.cdf(supp, *arg) - 1e-8, *arg),\n supp, msg + '-roundtrip')\n\n if not hasattr(distfn, 'xk'):\n _a, _b = distfn.support(*arg)\n supp1 = supp[supp < _b]\n npt.assert_array_equal(distfn.ppf(distfn.cdf(supp1, *arg) + 1e-8, *arg),\n supp1 + distfn.inc, msg + ' ppf-cdf-next')\n # -1e-8 could cause an error if pmf < 1e-8\n\n\ndef check_pmf_cdf(distfn, arg, distname):\n if hasattr(distfn, 'xk'):\n index = distfn.xk\n else:\n startind = int(distfn.ppf(0.01, *arg) - 1)\n index = list(range(startind, startind + 10))\n cdfs = distfn.cdf(index, *arg)\n pmfs_cum = distfn.pmf(index, *arg).cumsum()\n\n atol, rtol = 1e-10, 1e-10\n if distname == 'skellam': # ncx2 accuracy\n atol, rtol = 1e-5, 1e-5\n npt.assert_allclose(cdfs - cdfs[0], pmfs_cum - pmfs_cum[0],\n atol=atol, rtol=rtol)\n\n\ndef check_moment_frozen(distfn, arg, m, k):\n npt.assert_allclose(distfn(*arg).moment(k), m,\n atol=1e-10, rtol=1e-10)\n\n\ndef check_oth(distfn, arg, supp, msg):\n # checking other methods of distfn\n npt.assert_allclose(distfn.sf(supp, *arg), 1. - distfn.cdf(supp, *arg),\n atol=1e-10, rtol=1e-10)\n\n q = np.linspace(0.01, 0.99, 20)\n npt.assert_allclose(distfn.isf(q, *arg), distfn.ppf(1. - q, *arg),\n atol=1e-10, rtol=1e-10)\n\n median_sf = distfn.isf(0.5, *arg)\n npt.assert_(distfn.sf(median_sf - 1, *arg) > 0.5)\n npt.assert_(distfn.cdf(median_sf + 1, *arg) > 0.5)\n\n\ndef check_discrete_chisquare(distfn, arg, rvs, alpha, msg):\n \"\"\"Perform chisquare test for random sample of a discrete distribution\n\n Parameters\n ----------\n distname : string\n name of distribution function\n arg : sequence\n parameters of distribution\n alpha : float\n significance level, threshold for p-value\n\n Returns\n -------\n result : bool\n 0 if test passes, 1 if test fails\n\n \"\"\"\n wsupp = 0.05\n\n # construct intervals with minimum mass `wsupp`.\n # intervals are left-half-open as in a cdf difference\n _a, _b = distfn.support(*arg)\n lo = int(max(_a, -1000))\n high = int(min(_b, 1000)) + 1\n distsupport = range(lo, high)\n last = 0\n distsupp = [lo]\n distmass = []\n for ii in distsupport:\n current = distfn.cdf(ii, *arg)\n if current - last >= wsupp - 1e-14:\n distsupp.append(ii)\n distmass.append(current - last)\n last = current\n if current > (1 - wsupp):\n break\n if distsupp[-1] < _b:\n distsupp.append(_b)\n distmass.append(1 - last)\n distsupp = np.array(distsupp)\n distmass = np.array(distmass)\n\n # convert intervals to right-half-open as required by histogram\n histsupp = distsupp + 1e-8\n histsupp[0] = _a\n\n # find sample frequencies and perform chisquare test\n freq, hsupp = np.histogram(rvs, histsupp)\n chis, pval = stats.chisquare(np.array(freq), len(rvs)*distmass)\n\n npt.assert_(pval > alpha,\n 'chisquare - test for %s at arg = %s with pval = %s' %\n (msg, str(arg), str(pval)))\n\n\ndef check_scale_docstring(distfn):\n if distfn.__doc__ is not None:\n # Docstrings can be stripped if interpreter is run with -OO\n npt.assert_('scale' not in distfn.__doc__)\n\n\[email protected]('method', ['pmf', 'logpmf', 'cdf', 'logcdf',\n 'sf', 'logsf', 'ppf', 'isf'])\[email protected]('distname, args', distdiscrete)\ndef test_methods_with_lists(method, distname, args):\n # Test that the discrete distributions can accept Python lists\n # as arguments.\n try:\n dist = getattr(stats, distname)\n except TypeError:\n return\n if method in ['ppf', 'isf']:\n z = [0.1, 0.2]\n else:\n z = [0, 1]\n p2 = [[p]*2 for p in args]\n loc = [0, 1]\n result = dist.pmf(z, *p2, loc=loc)\n npt.assert_allclose(result,\n [dist.pmf(*v) for v in zip(z, *p2, loc)],\n rtol=1e-15, atol=1e-15)\n\n\[email protected]('distname, args', invdistdiscrete)\ndef test_cdf_gh13280_regression(distname, args):\n # Test for nan output when shape parameters are invalid\n dist = getattr(stats, distname)\n x = np.arange(-2, 15)\n vals = dist.cdf(x, *args)\n expected = np.nan\n npt.assert_equal(vals, expected)\n"
] |
[
[
"numpy.testing.assert_equal",
"numpy.histogram",
"numpy.linspace",
"numpy.random.seed",
"numpy.unique",
"numpy.arange",
"numpy.full",
"numpy.testing.assert_array_equal",
"numpy.testing.assert_",
"numpy.testing.assert_allclose",
"numpy.array",
"numpy.zeros",
"scipy.stats.rv_discrete",
"numpy.random.randint"
]
] |
suoluowan/AMANet-pytorch
|
[
"9981447a284bde8e76744928f0feba34f2a5cd6f"
] |
[
"detectron2/engine/defaults.py"
] |
[
"# -*- coding: utf-8 -*-\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\n\"\"\"\nThis file contains components with some default boilerplate logic user may need\nin training / testing. They will not work for everyone, but many users may find them useful.\n\nThe behavior of functions/classes in this file is subject to change,\nsince they are meant to represent the \"common default behavior\" people need in their projects.\n\"\"\"\n\nimport argparse\nimport logging\nimport os\nfrom collections import OrderedDict\nimport torch\nfrom fvcore.common.file_io import PathManager\nfrom fvcore.nn.precise_bn import get_bn_modules\nfrom torch.nn.parallel import DistributedDataParallel\n\nimport detectron2.data.transforms as T\nfrom detectron2.checkpoint import DetectionCheckpointer\nfrom detectron2.data import (\n MetadataCatalog,\n build_detection_test_loader,\n build_detection_train_loader,\n)\nfrom detectron2.evaluation import (\n DatasetEvaluator,\n inference_on_dataset,\n print_csv_format,\n verify_results,\n)\nfrom detectron2.modeling import build_model\nfrom detectron2.solver import build_lr_scheduler, build_optimizer\nfrom detectron2.utils import comm\nfrom detectron2.utils.collect_env import collect_env_info\nfrom detectron2.utils.env import seed_all_rng\nfrom detectron2.utils.events import CommonMetricPrinter, JSONWriter, TensorboardXWriter\nfrom detectron2.utils.logger import setup_logger\n\nfrom . import hooks\nfrom .train_loop import SimpleTrainer\n\n__all__ = [\"default_argument_parser\", \"default_setup\", \"DefaultPredictor\", \"DefaultTrainer\"]\n\n\ndef default_argument_parser():\n \"\"\"\n Create a parser with some common arguments used by detectron2 users.\n\n Returns:\n argparse.ArgumentParser:\n \"\"\"\n parser = argparse.ArgumentParser(description=\"Detectron2 Training\")\n parser.add_argument(\"--config-file\", default=\"/home/wangxuanhan/research/project/detectron2-master/projects/DensePose/configs/densepose_R_50_FPN_s1x.yaml\", metavar=\"FILE\", help=\"path to config file\")\n parser.add_argument(\n \"--resume\",\n # action=\"store_true\",\n help=\"whether to attempt to resume from the checkpoint directory\",\n type=bool,\n default=False\n )\n parser.add_argument(\"--eval-only\", action=\"store_true\", help=\"perform evaluation only\")\n parser.add_argument(\"--num-gpus\", type=int, default=1, help=\"number of gpus *per machine*\")\n parser.add_argument(\"--num-machines\", type=int, default=1)\n parser.add_argument(\n \"--machine-rank\", type=int, default=0, help=\"the rank of this machine (unique per machine)\"\n )\n\n # PyTorch still may leave orphan processes in multi-gpu training.\n # Therefore we use a deterministic way to obtain port,\n # so that users are aware of orphan processes by seeing the port occupied.\n port = 2 ** 15 + 2 ** 14 + hash(os.getuid()) % 2 ** 14\n parser.add_argument(\"--dist-url\", default=\"tcp://127.0.0.1:{}\".format(port))\n parser.add_argument(\n \"opts\",\n help=\"Modify config options using the command-line\",\n default=None,\n nargs=argparse.REMAINDER,\n )\n return parser\n\n\ndef default_setup(cfg, args):\n \"\"\"\n Perform some basic common setups at the beginning of a job, including:\n\n 1. Set up the detectron2 logger\n 2. Log basic information about environment, cmdline arguments, and config\n 3. Backup the config to the output directory\n\n Args:\n cfg (CfgNode): the full config to be used\n args (argparse.NameSpace): the command line arguments to be logged\n \"\"\"\n output_dir = cfg.OUTPUT_DIR\n if comm.is_main_process() and output_dir:\n PathManager.mkdirs(output_dir)\n\n rank = comm.get_rank()\n setup_logger(output_dir, distributed_rank=rank, name=\"fvcore\")\n logger = setup_logger(output_dir, distributed_rank=rank)\n\n logger.info(\"Rank of current process: {}. World size: {}\".format(rank, comm.get_world_size()))\n logger.info(\"Environment info:\\n\" + collect_env_info())\n\n logger.info(\"Command line arguments: \" + str(args))\n if hasattr(args, \"config_file\"):\n logger.info(\n \"Contents of args.config_file={}:\\n{}\".format(\n args.config_file, PathManager.open(args.config_file, \"r\").read()\n )\n )\n\n logger.info(\"Running with full config:\\n{}\".format(cfg))\n if comm.is_main_process() and output_dir:\n # Note: some of our scripts may expect the existence of\n # config.yaml in output directory\n path = os.path.join(output_dir, \"config.yaml\")\n with PathManager.open(path, \"w\") as f:\n f.write(cfg.dump())\n logger.info(\"Full config saved to {}\".format(os.path.abspath(path)))\n\n # make sure each worker has a different, yet deterministic seed if specified\n seed_all_rng(None if cfg.SEED < 0 else cfg.SEED + rank)\n\n # cudnn benchmark has large overhead. It shouldn't be used considering the small size of\n # typical validation set.\n if not (hasattr(args, \"eval_only\") and args.eval_only):\n torch.backends.cudnn.benchmark = cfg.CUDNN_BENCHMARK\n\n\nclass DefaultPredictor:\n \"\"\"\n Create a simple end-to-end predictor with the given config.\n The predictor takes an BGR image and produce a dict of predictions.\n\n Attributes:\n metadata (Metadata): the metadata of the underlying dataset, obtained from\n cfg.DATASETS.TEST.\n \"\"\"\n\n def __init__(self, cfg):\n self.cfg = cfg.clone() # cfg can be modified by model\n self.model = build_model(self.cfg)\n self.model.eval()\n self.metadata = MetadataCatalog.get(cfg.DATASETS.TEST[0])\n\n checkpointer = DetectionCheckpointer(self.model)\n checkpointer.load(cfg.MODEL.WEIGHTS)\n\n self.transform_gen = T.ResizeShortestEdge(\n [cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST], cfg.INPUT.MAX_SIZE_TEST\n )\n\n self.input_format = cfg.INPUT.FORMAT\n assert self.input_format in [\"RGB\", \"BGR\"], self.input_format\n\n @torch.no_grad()\n def __call__(self, original_image):\n \"\"\"\n Args:\n original_image (np.ndarray): an image of shape (H, W, C) (in BGR order).\n\n Returns:\n predictions (dict): the output of the model\n \"\"\"\n # Apply pre-processing to image.\n if self.input_format == \"RGB\":\n # whether the model expects BGR inputs or RGB\n original_image = original_image[:, :, ::-1]\n height, width = original_image.shape[:2]\n image = self.transform_gen.get_transform(original_image).apply_image(original_image)\n image = torch.as_tensor(image.astype(\"float32\").transpose(2, 0, 1))\n\n inputs = {\"image\": image, \"height\": height, \"width\": width}\n predictions = self.model([inputs])[0]\n return predictions\n\n\nclass DefaultTrainer(SimpleTrainer):\n \"\"\"\n A trainer with default training logic. Compared to `SimpleTrainer`, it\n contains the following logic in addition:\n\n 1. Create model, optimizer, scheduler, dataloader from the given config.\n 2. Load a checkpoint or `cfg.MODEL.WEIGHTS`, if exists.\n 3. Register a few common hooks.\n\n It is created to simplify the **standard model training workflow** and reduce code boilerplate\n for users who only need the standard training workflow, with standard features.\n It means this class makes *many assumptions* about your training logic that\n may easily become invalid in a new research. In fact, any assumptions beyond those made in the\n :class:`SimpleTrainer` are too much for research.\n\n The code of this class has been annotated about restrictive assumptions it mades.\n When they do not work for you, you're encouraged to write your own training logic.\n\n Also note that the behavior of this class, like other functions/classes in\n this file, is not stable, since it is meant to represent the \"common default behavior\".\n It is only guaranteed to work well with the standard models and training workflow in detectron2.\n To obtain more stable behavior, write your own training logic with other public APIs.\n\n Attributes:\n scheduler:\n checkpointer (DetectionCheckpointer):\n cfg (CfgNode):\n \"\"\"\n\n def __init__(self, cfg):\n \"\"\"\n Args:\n cfg (CfgNode):\n \"\"\"\n # Assume these objects must be constructed in this order.\n model = self.build_model(cfg)\n optimizer = self.build_optimizer(cfg, model)\n data_loader = self.build_train_loader(cfg)\n\n # For training, wrap with DDP. But don't need this for inference.\n if comm.get_world_size() > 1:\n model = DistributedDataParallel(\n model, device_ids=[comm.get_local_rank()], broadcast_buffers=False\n )\n super().__init__(model, data_loader, optimizer)\n\n self.scheduler = self.build_lr_scheduler(cfg, optimizer)\n # Assume no other objects need to be checkpointed.\n # We can later make it checkpoint the stateful hooks\n self.checkpointer = DetectionCheckpointer(\n # Assume you want to save checkpoints together with logs/statistics\n model,\n cfg.OUTPUT_DIR,\n optimizer=optimizer,\n scheduler=self.scheduler,\n )\n self.start_iter = 0\n self.max_iter = cfg.SOLVER.MAX_ITER\n self.cfg = cfg\n\n self.register_hooks(self.build_hooks())\n\n def resume_or_load(self, resume=True):\n \"\"\"\n If `resume==True`, and last checkpoint exists, resume from it.\n\n Otherwise, load a model specified by the config.\n\n Args:\n resume (bool): whether to do resume or not\n \"\"\"\n # The checkpoint stores the training iteration that just finished, thus we start\n # at the next iteration (or iter zero if there's no checkpoint).\n self.start_iter = (\n self.checkpointer.resume_or_load(self.cfg.MODEL.WEIGHTS, resume=resume).get(\n \"iteration\", -1\n )\n + 1\n )\n\n def build_hooks(self):\n \"\"\"\n Build a list of default hooks.\n\n Returns:\n list[HookBase]:\n \"\"\"\n cfg = self.cfg.clone()\n cfg.defrost()\n cfg.DATALOADER.NUM_WORKERS = 0 # save some memory and time for PreciseBN\n\n ret = [\n hooks.IterationTimer(),\n hooks.LRScheduler(self.optimizer, self.scheduler),\n hooks.PreciseBN(\n # Run at the same freq as (but before) evaluation.\n cfg.TEST.EVAL_PERIOD,\n self.model,\n # Build a new data loader to not affect training\n self.build_train_loader(cfg),\n cfg.TEST.PRECISE_BN.NUM_ITER,\n )\n if cfg.TEST.PRECISE_BN.ENABLED and get_bn_modules(self.model)\n else None,\n ]\n\n # Do PreciseBN before checkpointer, because it updates the model and need to\n # be saved by checkpointer.\n # This is not always the best: if checkpointing has a different frequency,\n # some checkpoints may have more precise statistics than others.\n if comm.is_main_process():\n ret.append(hooks.PeriodicCheckpointer(self.checkpointer, cfg.SOLVER.CHECKPOINT_PERIOD))\n\n def test_and_save_results():\n self._last_eval_results = self.test(self.cfg, self.model)\n return self._last_eval_results\n\n # Do evaluation after checkpointer, because then if it fails,\n # we can use the saved checkpoint to debug.\n ret.append(hooks.EvalHook(cfg.TEST.EVAL_PERIOD, test_and_save_results))\n\n if comm.is_main_process():\n # run writers in the end, so that evaluation metrics are written\n ret.append(hooks.PeriodicWriter(self.build_writers()))\n return ret\n\n def build_writers(self):\n \"\"\"\n Build a list of default writers, that write metrics to the screen,\n a json file, and a tensorboard event file respectively.\n\n Returns:\n list[Writer]: a list of objects that have a ``.write`` method.\n \"\"\"\n # Assume the default print/log frequency.\n return [\n # It may not always print what you want to see, since it prints \"common\" metrics only.\n CommonMetricPrinter(self.max_iter),\n JSONWriter(os.path.join(self.cfg.OUTPUT_DIR, \"metrics.json\")),\n TensorboardXWriter(self.cfg.OUTPUT_DIR),\n ]\n\n def train(self):\n \"\"\"\n Run training.\n\n Returns:\n OrderedDict of results, if evaluation is enabled. Otherwise None.\n \"\"\"\n super().train(self.start_iter, self.max_iter)\n if hasattr(self, \"_last_eval_results\") and comm.is_main_process():\n verify_results(self.cfg, self._last_eval_results)\n return self._last_eval_results\n\n @classmethod\n def build_model(cls, cfg):\n \"\"\"\n Returns:\n torch.nn.Module:\n \"\"\"\n model = build_model(cfg)\n logger = logging.getLogger(__name__)\n logger.info(\"Model:\\n{}\".format(model))\n return model\n\n @classmethod\n def build_optimizer(cls, cfg, model):\n \"\"\"\n Returns:\n torch.optim.Optimizer:\n \"\"\"\n return build_optimizer(cfg, model)\n\n @classmethod\n def build_lr_scheduler(cls, cfg, optimizer):\n return build_lr_scheduler(cfg, optimizer)\n\n @classmethod\n def build_train_loader(cls, cfg):\n \"\"\"\n Returns:\n iterable\n \"\"\"\n return build_detection_train_loader(cfg)\n\n @classmethod\n def build_test_loader(cls, cfg, dataset_name):\n \"\"\"\n Returns:\n iterable\n \"\"\"\n return build_detection_test_loader(cfg, dataset_name)\n\n @classmethod\n def build_evaluator(cls, cfg, dataset_name):\n \"\"\"\n Returns:\n DatasetEvaluator\n \"\"\"\n raise NotImplementedError\n\n @classmethod\n def test(cls, cfg, model, evaluators=None):\n \"\"\"\n Args:\n cfg (CfgNode):\n model (nn.Module):\n evaluators (list[DatasetEvaluator] or None): if None, will call\n :meth:`build_evaluator`. Otherwise, must have the same length as\n `cfg.DATASETS.TEST`.\n\n Returns:\n dict: a dict of result metrics\n \"\"\"\n logger = logging.getLogger(__name__)\n if isinstance(evaluators, DatasetEvaluator):\n evaluators = [evaluators]\n if evaluators is not None:\n assert len(cfg.DATASETS.TEST) == len(evaluators), \"{} != {}\".format(\n len(cfg.DATASETS.TEST), len(evaluators)\n )\n\n results = OrderedDict()\n for idx, dataset_name in enumerate(cfg.DATASETS.TEST):\n data_loader = cls.build_test_loader(cfg, dataset_name)\n # When evaluators are passed in as arguments,\n # implicitly assume that evaluators can be created before data_loader.\n evaluator = (\n evaluators[idx]\n if evaluators is not None\n else cls.build_evaluator(cfg, dataset_name)\n )\n results_i = inference_on_dataset(model, data_loader, evaluator)\n results[dataset_name] = results_i\n if comm.is_main_process():\n assert isinstance(\n results_i, dict\n ), \"Evaluator must return a dict on the main process. Got {} instead.\".format(\n results_i\n )\n logger.info(\"Evaluation results for {} in csv format:\".format(dataset_name))\n print_csv_format(results_i)\n\n if len(results) == 1:\n results = list(results.values())[0]\n return results\n"
] |
[
[
"torch.no_grad"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.