repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
AlexeyVatolin/sentence-transformers
[ "084b80cd351b135a1d48211ec4f4aea37f01a641" ]
[ "sentence_transformers/SentenceTransformer.py" ]
[ "import json\nimport logging\nimport os\nimport shutil\nfrom collections import OrderedDict\nfrom typing import List, Dict, Tuple, Iterable, Type, Union, Callable\nfrom zipfile import ZipFile\nimport requests\nimport numpy as np\nfrom numpy import ndarray\nimport transformers\nimport torch\nfrom torch import nn, Tensor, device\nfrom torch.optim import Optimizer\nfrom torch.optim.swa_utils import AveragedModel, SWALR\nfrom torch.utils.data import DataLoader\nimport torch.multiprocessing as mp\nfrom tqdm.autonotebook import tqdm, trange\nimport math\nimport queue\n\nfrom . import __DOWNLOAD_SERVER__\nfrom .evaluation import SentenceEvaluator\nfrom .util import import_from_string, batch_to_device, http_get\nfrom .models import Transformer, Pooling\nfrom . import __version__\n\ntry:\n import wandb\n\n wandb_available = True\nexcept ImportError:\n wandb_available = False\n\nlogger = logging.getLogger(__name__)\n\n\nclass SentenceTransformer(nn.Sequential):\n \"\"\"\n Loads or create a SentenceTransformer model, that can be used to map sentences / text to embeddings.\n\n :param model_name_or_path: If it is a filepath on disc, it loads the model from that path. If it is not a path, it first tries to download a pre-trained SentenceTransformer model. If that fails, tries to construct a model from Huggingface models repository with that name.\n :param modules: This parameter can be used to create custom SentenceTransformer models from scratch.\n :param device: Device (like 'cuda' / 'cpu') that should be used for computation. If None, checks if a GPU can be used.\n \"\"\"\n\n def __init__(self, model_name_or_path: str = None, modules: Iterable[nn.Module] = None, device: str = None):\n save_model_to = None\n\n if model_name_or_path is not None and model_name_or_path != \"\":\n logger.info(\"Load pretrained SentenceTransformer: {}\".format(model_name_or_path))\n model_path = model_name_or_path\n\n if not os.path.isdir(model_path) and not model_path.startswith('http://') and not model_path.startswith(\n 'https://'):\n logger.info(\"Did not find folder {}\".format(model_path))\n\n if '\\\\' in model_path or model_path.count('/') > 1:\n raise AttributeError(\"Path {} not found\".format(model_path))\n\n model_path = __DOWNLOAD_SERVER__ + model_path + '.zip'\n logger.info(\"Search model on server: {}\".format(model_path))\n\n if model_path.startswith('http://') or model_path.startswith('https://'):\n model_url = model_path\n folder_name = model_url.replace(\"https://\", \"\").replace(\"http://\", \"\").replace(\"/\", \"_\")[:250].rstrip(\n '.zip')\n\n cache_folder = os.getenv('SENTENCE_TRANSFORMERS_HOME')\n if cache_folder is None:\n try:\n from torch.hub import _get_torch_home\n torch_cache_home = _get_torch_home()\n except ImportError:\n torch_cache_home = os.path.expanduser(\n os.getenv('TORCH_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch')))\n\n cache_folder = os.path.join(torch_cache_home, 'sentence_transformers')\n\n model_path = os.path.join(cache_folder, folder_name)\n\n if not os.path.exists(model_path) or not os.listdir(model_path):\n if os.path.exists(model_path):\n os.remove(model_path)\n\n model_url = model_url.rstrip(\"/\")\n logger.info(\"Downloading sentence transformer model from {} and saving it at {}\".format(model_url,\n model_path))\n\n model_path_tmp = model_path.rstrip(\"/\").rstrip(\"\\\\\") + \"_part\"\n try:\n zip_save_path = os.path.join(model_path_tmp, 'model.zip')\n http_get(model_url, zip_save_path)\n with ZipFile(zip_save_path, 'r') as zip:\n zip.extractall(model_path_tmp)\n os.remove(zip_save_path)\n os.rename(model_path_tmp, model_path)\n except requests.exceptions.HTTPError as e:\n shutil.rmtree(model_path_tmp)\n if e.response.status_code == 429:\n raise Exception(\n \"Too many requests were detected from this IP for the model {}. Please contact [email protected] for more information.\".format(\n model_name_or_path))\n\n if e.response.status_code == 404:\n logger.warning(\n 'SentenceTransformer-Model {} not found. Try to create it from scratch'.format(\n model_url))\n logger.warning(\n 'Try to create Transformer Model {} with mean pooling'.format(model_name_or_path))\n\n save_model_to = model_path\n model_path = None\n transformer_model = Transformer(model_name_or_path)\n pooling_model = Pooling(transformer_model.get_word_embedding_dimension())\n modules = [transformer_model, pooling_model]\n else:\n raise e\n except Exception as e:\n shutil.rmtree(model_path)\n raise e\n\n #### Load from disk\n if model_path is not None:\n logger.info(\"Load SentenceTransformer from folder: {}\".format(model_path))\n\n if os.path.exists(os.path.join(model_path, 'config.json')):\n with open(os.path.join(model_path, 'config.json')) as fIn:\n config = json.load(fIn)\n if config['__version__'] > __version__:\n logger.warning(\n \"You try to use a model that was created with version {}, however, your version is {}. This might cause unexpected behavior or errors. In that case, try to update to the latest version.\\n\\n\\n\".format(\n config['__version__'], __version__))\n\n with open(os.path.join(model_path, 'modules.json')) as fIn:\n contained_modules = json.load(fIn)\n\n modules = OrderedDict()\n for module_config in contained_modules:\n module_class = import_from_string(module_config['type'])\n module = module_class.load(os.path.join(model_path, module_config['path']))\n modules[module_config['name']] = module\n\n if modules is not None and not isinstance(modules, OrderedDict):\n modules = OrderedDict([(str(idx), module) for idx, module in enumerate(modules)])\n\n super().__init__(modules)\n if device is None:\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n logger.info(\"Use pytorch device: {}\".format(device))\n\n self._target_device = torch.device(device)\n\n # We created a new model from scratch based on a Transformer model. Save the SBERT model in the cache folder\n if save_model_to is not None:\n self.save(save_model_to)\n\n def encode(self, sentences: Union[str, List[str], List[int]],\n batch_size: int = 32,\n show_progress_bar: bool = None,\n output_value: str = 'sentence_embedding',\n convert_to_numpy: bool = True,\n convert_to_tensor: bool = False,\n is_pretokenized: bool = False,\n device: str = None,\n num_workers: int = 0) -> Union[List[Tensor], ndarray, Tensor]:\n \"\"\"\n Computes sentence embeddings\n\n :param sentences: the sentences to embed\n :param batch_size: the batch size used for the computation\n :param show_progress_bar: Output a progress bar when encode sentences\n :param output_value: Default sentence_embedding, to get sentence embeddings. Can be set to token_embeddings to get wordpiece token embeddings.\n :param convert_to_numpy: If true, the output is a list of numpy vectors. Else, it is a list of pytorch tensors.\n :param convert_to_tensor: If true, you get one large tensor as return. Overwrites any setting from convert_to_numpy\n :param is_pretokenized: DEPRECATED - No longer used, will be removed in the future\n :param device: Which torch.device to use for the computation\n :param num_workers: DEPRECATED - No longer used, will be removed in the future\n\n :return:\n By default, a list of tensors is returned. If convert_to_tensor, a stacked tensor is returned. If convert_to_numpy, a numpy matrix is returned.\n \"\"\"\n self.eval()\n if show_progress_bar is None:\n show_progress_bar = (\n logger.getEffectiveLevel() == logging.INFO or logger.getEffectiveLevel() == logging.DEBUG)\n\n if convert_to_tensor:\n convert_to_numpy = False\n\n input_was_string = False\n if isinstance(sentences, str): # Cast an individual sentence to a list with length 1\n sentences = [sentences]\n input_was_string = True\n\n if device is None:\n device = self._target_device\n\n self.to(device)\n\n all_embeddings = []\n length_sorted_idx = np.argsort([-self._text_length(sen) for sen in sentences])\n sentences_sorted = [sentences[idx] for idx in length_sorted_idx]\n\n for start_index in trange(0, len(sentences), batch_size, desc=\"Batches\", disable=not show_progress_bar):\n sentences_batch = sentences_sorted[start_index:start_index + batch_size]\n features = self.tokenize(sentences_batch)\n features = batch_to_device(features, device)\n\n with torch.no_grad():\n out_features = self.forward(features)\n embeddings = out_features[output_value]\n\n if output_value == 'token_embeddings':\n # Set token embeddings to 0 for padding tokens\n input_mask = out_features['attention_mask']\n input_mask_expanded = input_mask.unsqueeze(-1).expand(embeddings.size()).float()\n embeddings = embeddings * input_mask_expanded\n\n embeddings = embeddings.detach()\n\n # fixes for #522 and #487 to avoid oom problems on gpu with large datasets\n if convert_to_numpy:\n embeddings = embeddings.cpu()\n\n all_embeddings.extend(embeddings)\n\n all_embeddings = [all_embeddings[idx] for idx in np.argsort(length_sorted_idx)]\n\n if convert_to_tensor:\n all_embeddings = torch.stack(all_embeddings)\n elif convert_to_numpy:\n all_embeddings = np.asarray([emb.numpy() for emb in all_embeddings])\n\n if input_was_string:\n all_embeddings = all_embeddings[0]\n\n return all_embeddings\n\n def start_multi_process_pool(self, target_devices: List[str] = None):\n \"\"\"\n Starts multi process to process the encoding with several, independent processes.\n This method is recommended if you want to encode on multiple GPUs. It is advised\n to start only one process per GPU. This method works together with encode_multi_process\n\n :param target_devices: PyTorch target devices, e.g. cuda:0, cuda:1... If None, all available CUDA devices will be used\n :return: Returns a dict with the target processes, an input queue and and output queue.\n \"\"\"\n if target_devices is None:\n if torch.cuda.is_available():\n target_devices = ['cuda:{}'.format(i) for i in range(torch.cuda.device_count())]\n else:\n logger.info(\"CUDA is not available. Start 4 CPU worker\")\n target_devices = ['cpu'] * 4\n\n logger.info(\"Start multi-process pool on devices: {}\".format(', '.join(map(str, target_devices))))\n\n ctx = mp.get_context('spawn')\n input_queue = ctx.Queue()\n output_queue = ctx.Queue()\n processes = []\n\n for cuda_id in target_devices:\n p = ctx.Process(target=SentenceTransformer._encode_multi_process_worker,\n args=(cuda_id, self, input_queue, output_queue), daemon=True)\n p.start()\n processes.append(p)\n\n return {'input': input_queue, 'output': output_queue, 'processes': processes}\n\n @staticmethod\n def stop_multi_process_pool(pool):\n \"\"\"\n Stops all processes started with start_multi_process_pool\n \"\"\"\n for p in pool['processes']:\n p.terminate()\n\n for p in pool['processes']:\n p.join()\n p.close()\n\n pool['input'].close()\n pool['output'].close()\n\n def encode_multi_process(self, sentences: List[str], pool: Dict[str, object], batch_size: int = 32,\n chunk_size: int = None):\n \"\"\"\n This method allows to run encode() on multiple GPUs. The sentences are chunked into smaller packages\n and sent to individual processes, which encode these on the different GPUs. This method is only suitable\n for encoding large sets of sentences\n\n :param sentences: List of sentences\n :param pool: A pool of workers started with SentenceTransformer.start_multi_process_pool\n :param batch_size: Encode sentences with batch size\n :param chunk_size: Sentences are chunked and sent to the individual processes. If none, it determine a sensible size.\n :return: Numpy matrix with all embeddings\n \"\"\"\n\n if chunk_size is None:\n chunk_size = min(math.ceil(len(sentences) / len(pool[\"processes\"]) / 10), 5000)\n\n logger.info(\"Chunk data into packages of size {}\".format(chunk_size))\n\n input_queue = pool['input']\n last_chunk_id = 0\n chunk = []\n\n for sentence in sentences:\n chunk.append(sentence)\n if len(chunk) >= chunk_size:\n input_queue.put([last_chunk_id, batch_size, chunk])\n last_chunk_id += 1\n chunk = []\n\n if len(chunk) > 0:\n input_queue.put([last_chunk_id, batch_size, chunk])\n last_chunk_id += 1\n\n output_queue = pool['output']\n results_list = sorted([output_queue.get() for _ in range(last_chunk_id)], key=lambda x: x[0])\n embeddings = np.concatenate([result[1] for result in results_list])\n return embeddings\n\n @staticmethod\n def _encode_multi_process_worker(target_device: str, model, input_queue, results_queue):\n \"\"\"\n Internal working process to encode sentences in multi-process setup\n \"\"\"\n while True:\n try:\n id, batch_size, sentences = input_queue.get()\n embeddings = model.encode(sentences, device=target_device, show_progress_bar=False,\n convert_to_numpy=True, batch_size=batch_size)\n results_queue.put([id, embeddings])\n except queue.Empty:\n break\n\n def get_max_seq_length(self):\n \"\"\"\n Returns the maximal sequence length for input the model accepts. Longer inputs will be truncated\n \"\"\"\n if hasattr(self._first_module(), 'max_seq_length'):\n return self._first_module().max_seq_length\n\n return None\n\n def tokenize(self, text: str):\n \"\"\"\n Tokenizes the text\n \"\"\"\n return self._first_module().tokenize(text)\n\n def get_sentence_features(self, *features):\n return self._first_module().get_sentence_features(*features)\n\n def get_sentence_embedding_dimension(self):\n for mod in reversed(self._modules.values()):\n sent_embedding_dim_method = getattr(mod, \"get_sentence_embedding_dimension\", None)\n if callable(sent_embedding_dim_method):\n return sent_embedding_dim_method()\n return None\n\n def _first_module(self):\n \"\"\"Returns the first module of this sequential embedder\"\"\"\n return self._modules[next(iter(self._modules))]\n\n def _last_module(self):\n \"\"\"Returns the last module of this sequential embedder\"\"\"\n return self._modules[next(reversed(self._modules))]\n\n def save(self, path):\n \"\"\"\n Saves all elements for this seq. sentence embedder into different sub-folders\n \"\"\"\n if path is None:\n return\n\n os.makedirs(path, exist_ok=True)\n\n logger.info(\"Save model to {}\".format(path))\n contained_modules = []\n\n for idx, name in enumerate(self._modules):\n module = self._modules[name]\n model_path = os.path.join(path, str(idx) + \"_\" + type(module).__name__)\n os.makedirs(model_path, exist_ok=True)\n module.save(model_path)\n contained_modules.append(\n {'idx': idx, 'name': name, 'path': os.path.basename(model_path), 'type': type(module).__module__})\n\n with open(os.path.join(path, 'modules.json'), 'w') as fOut:\n json.dump(contained_modules, fOut, indent=2)\n\n with open(os.path.join(path, 'config.json'), 'w') as fOut:\n json.dump({'__version__': __version__}, fOut, indent=2)\n\n def smart_batching_collate(self, batch):\n \"\"\"\n Transforms a batch from a SmartBatchingDataset to a batch of tensors for the model\n Here, batch is a list of tuples: [(tokens, label), ...]\n\n :param batch:\n a batch from a SmartBatchingDataset\n :return:\n a batch of tensors for the model\n \"\"\"\n num_texts = len(batch[0].texts)\n texts = [[] for _ in range(num_texts)]\n labels = []\n\n for example in batch:\n for idx, text in enumerate(example.texts):\n texts[idx].append(text)\n\n labels.append(example.label)\n\n labels = torch.tensor(labels).to(self._target_device)\n\n sentence_features = []\n for idx in range(num_texts):\n tokenized = self.tokenize(texts[idx])\n batch_to_device(tokenized, self._target_device)\n sentence_features.append(tokenized)\n\n return sentence_features, labels\n\n def _text_length(self, text: Union[List[int], List[List[int]]]):\n \"\"\"\n Help function to get the length for the input text. Text can be either\n a list of ints (which means a single text as input), or a tuple of list of ints\n (representing several text inputs to the model).\n \"\"\"\n if isinstance(text, dict):\n return len(next(iter(text.values())))\n elif len(text) == 0 or isinstance(text[0], int):\n return len(text)\n else:\n return sum([len(t) for t in text])\n\n def fit(self,\n train_objectives: Iterable[Tuple[DataLoader, nn.Module]],\n evaluator: SentenceEvaluator = None,\n epochs: int = 1,\n steps_per_epoch=None,\n scheduler: str = 'WarmupLinear',\n warmup_steps: int = 10000,\n optimizer_class: Type[Optimizer] = transformers.AdamW,\n optimizer_params: Dict[str, object] = {'lr': 2e-5, 'eps': 1e-6, 'correct_bias': False},\n weight_decay: float = 0.01,\n evaluation_steps: int = 0,\n output_path: str = None,\n save_best_model: bool = True,\n max_grad_norm: float = 1,\n use_amp: bool = False,\n callback: Callable[[float, int, int], None] = None,\n show_progress_bar: bool = True,\n log_every: int = 100,\n wandb_project_name: str = None,\n wandb_config: Dict[str, object] = {},\n use_swa: bool = False,\n swa_epochs_start: int = 5,\n swa_anneal_epochs: int = 10,\n swa_lr: float = 0.05,\n ):\n \"\"\"\n Train the model with the given training objective\n Each training objective is sampled in turn for one batch.\n We sample only as many batches from each objective as there are in the smallest one\n to make sure of equal training with each dataset.\n\n :param train_objectives: Tuples of (DataLoader, LossFunction). Pass more than one for multi-task learning\n :param evaluator: An evaluator (sentence_transformers.evaluation) evaluates the model performance during training on held-out dev data. It is used to determine the best model that is saved to disc.\n :param epochs: Number of epochs for training\n :param steps_per_epoch: Number of training steps per epoch. If set to None (default), one epoch is equal the DataLoader size from train_objectives.\n :param scheduler: Learning rate scheduler. Available schedulers: constantlr, warmupconstant, warmuplinear, warmupcosine, warmupcosinewithhardrestarts\n :param warmup_steps: Behavior depends on the scheduler. For WarmupLinear (default), the learning rate is increased from o up to the maximal learning rate. After these many training steps, the learning rate is decreased linearly back to zero.\n :param optimizer_class: Optimizer\n :param optimizer_params: Optimizer parameters\n :param weight_decay: Weight decay for model parameters\n :param evaluation_steps: If > 0, evaluate the model using evaluator after each number of training steps\n :param output_path: Storage path for the model and evaluation files\n :param save_best_model: If true, the best model (according to evaluator) is stored at output_path\n :param max_grad_norm: Used for gradient normalization.\n :param use_amp: Use Automatic Mixed Precision (AMP). Only for Pytorch >= 1.6.0\n :param callback: Callback function that is invoked after each evaluation.\n It must accept the following three parameters in this order:\n `score`, `epoch`, `steps`\n :param show_progress_bar: If True, output a tqdm progress bar\n \"\"\"\n\n if use_amp:\n from torch.cuda.amp import autocast\n scaler = torch.cuda.amp.GradScaler()\n\n self.to(self._target_device)\n\n if output_path is not None:\n os.makedirs(output_path, exist_ok=True)\n\n dataloaders = [dataloader for dataloader, _ in train_objectives]\n\n # Use smart batching\n for dataloader in dataloaders:\n dataloader.collate_fn = self.smart_batching_collate\n\n loss_models = [loss for _, loss in train_objectives]\n for loss_model in loss_models:\n loss_model.to(self._target_device)\n\n self.best_score = -9999999\n\n if steps_per_epoch is None or steps_per_epoch == 0:\n steps_per_epoch = min([len(dataloader) for dataloader in dataloaders])\n\n num_train_steps = int(steps_per_epoch * epochs)\n\n # Prepare logger\n if wandb_available and wandb_project_name:\n if not wandb.setup().settings.sweep_id:\n config = {\n 'epochs': epochs,\n 'steps_per_epoch': steps_per_epoch,\n 'scheduler': scheduler,\n 'warmup_steps': warmup_steps,\n 'weight_decay': weight_decay,\n 'evaluation_steps': evaluation_steps,\n 'output_path': output_path,\n 'save_best_model': save_best_model,\n 'max_grad_norm': max_grad_norm,\n 'use_amp': use_amp,\n }\n wandb.init(project=wandb_project_name, config=config, **wandb_config)\n wandb.watch(self)\n\n # SWA\n if use_swa:\n swa_model = AveragedModel(self)\n\n # Prepare optimizers\n optimizers = []\n schedulers = []\n for loss_model in loss_models:\n param_optimizer = list(loss_model.named_parameters())\n\n no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']\n optimizer_grouped_parameters = [\n {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],\n 'weight_decay': weight_decay},\n {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}\n ]\n\n optimizer = optimizer_class(optimizer_grouped_parameters, **optimizer_params)\n scheduler_obj = self._get_scheduler(optimizer, scheduler=scheduler, warmup_steps=warmup_steps,\n t_total=num_train_steps)\n\n optimizers.append(optimizer)\n schedulers.append(scheduler_obj)\n if use_swa:\n swa_scheduler = SWALR(optimizers[0], swa_lr=swa_lr, anneal_epochs=swa_anneal_epochs, anneal_strategy='linear')\n\n global_step = 0\n data_iterators = [iter(dataloader) for dataloader in dataloaders]\n\n num_train_objectives = len(train_objectives)\n\n skip_scheduler = False\n for epoch in trange(epochs, desc=\"Epoch\", disable=not show_progress_bar):\n training_steps = 0\n\n for loss_model in loss_models:\n loss_model.zero_grad()\n loss_model.train()\n\n for _ in trange(steps_per_epoch, desc=\"Iteration\", smoothing=0.05, disable=not show_progress_bar):\n for train_idx in range(num_train_objectives):\n loss_model = loss_models[train_idx]\n optimizer = optimizers[train_idx]\n scheduler = schedulers[train_idx]\n data_iterator = data_iterators[train_idx]\n\n try:\n data = next(data_iterator)\n except StopIteration:\n data_iterator = iter(dataloaders[train_idx])\n data_iterators[train_idx] = data_iterator\n data = next(data_iterator)\n\n features, labels = data\n\n if use_amp:\n with autocast():\n loss_value = loss_model(features, labels)\n\n scale_before_step = scaler.get_scale()\n scaler.scale(loss_value).backward()\n scaler.unscale_(optimizer)\n torch.nn.utils.clip_grad_norm_(loss_model.parameters(), max_grad_norm)\n scaler.step(optimizer)\n scaler.update()\n\n skip_scheduler = scaler.get_scale() != scale_before_step\n else:\n loss_value = loss_model(features, labels)\n loss_value.backward()\n torch.nn.utils.clip_grad_norm_(loss_model.parameters(), max_grad_norm)\n optimizer.step()\n\n optimizer.zero_grad()\n\n # if wandb init is called\n if wandb_available and wandb.run is not None and (training_steps + 1) % log_every == 0:\n wandb.log(\n {\n loss_model.__class__.__name__: loss_value.item(),\n \"lr\": scheduler.get_last_lr()[0],\n }, step=global_step\n )\n\n if not skip_scheduler:\n scheduler.step()\n\n training_steps += 1\n global_step += 1\n\n if evaluation_steps > 0 and training_steps % evaluation_steps == 0:\n self._eval_during_training(evaluator, output_path, save_best_model, epoch,\n training_steps, global_step, callback)\n for loss_model in loss_models:\n loss_model.zero_grad()\n loss_model.train()\n\n if use_swa and epoch > swa_epochs_start:\n swa_model.update_parameters(self)\n swa_scheduler.step()\n\n self._eval_during_training(evaluator, output_path, save_best_model, epoch, -1, global_step, callback)\n if use_swa:\n return swa_model\n\n def evaluate(self, evaluator: SentenceEvaluator, output_path: str = None):\n \"\"\"\n Evaluate the model\n\n :param evaluator:\n the evaluator\n :param output_path:\n the evaluator can write the results to this path\n \"\"\"\n if output_path is not None:\n os.makedirs(output_path, exist_ok=True)\n return evaluator(self, output_path)\n\n def _eval_during_training(self, evaluator, output_path, save_best_model, epoch, steps, global_step, callback):\n \"\"\"Runs evaluation during the training\"\"\"\n if evaluator is not None:\n score = evaluator(self, output_path=output_path, epoch=epoch, steps=steps, global_step=global_step)\n if callback is not None:\n callback(score, epoch, steps)\n # if wandb_available and wandb.run is not None: # if wandb init is called\n # wandb.log({evaluator.name if evaluator.name else evaluator.__class__.__name__: score}, step=global_step)\n if score > self.best_score:\n self.best_score = score\n if save_best_model:\n self.save(output_path)\n\n @staticmethod\n def _get_scheduler(optimizer, scheduler: str, warmup_steps: int, t_total: int):\n \"\"\"\n Returns the correct learning rate scheduler. Available scheduler: constantlr, warmupconstant, warmuplinear, warmupcosine, warmupcosinewithhardrestarts\n \"\"\"\n scheduler = scheduler.lower()\n if scheduler == 'constantlr':\n return transformers.get_constant_schedule(optimizer)\n elif scheduler == 'warmupconstant':\n return transformers.get_constant_schedule_with_warmup(optimizer, num_warmup_steps=warmup_steps)\n elif scheduler == 'warmuplinear':\n return transformers.get_linear_schedule_with_warmup(optimizer, num_warmup_steps=warmup_steps,\n num_training_steps=t_total)\n elif scheduler == 'warmupcosine':\n return transformers.get_cosine_schedule_with_warmup(optimizer, num_warmup_steps=warmup_steps,\n num_training_steps=t_total)\n elif scheduler == 'warmupcosinewithhardrestarts':\n return transformers.get_cosine_with_hard_restarts_schedule_with_warmup(optimizer,\n num_warmup_steps=warmup_steps,\n num_training_steps=t_total)\n else:\n raise ValueError(\"Unknown scheduler {}\".format(scheduler))\n\n @property\n def device(self) -> device:\n \"\"\"\n Get torch.device from module, assuming that the whole module has one device.\n \"\"\"\n try:\n return next(self.parameters()).device\n except StopIteration:\n # For nn.DataParallel compatibility in PyTorch 1.5\n\n def find_tensor_attributes(module: nn.Module) -> List[Tuple[str, Tensor]]:\n tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)]\n return tuples\n\n gen = self._named_members(get_members_fn=find_tensor_attributes)\n first_tuple = next(gen)\n return first_tuple[1].device\n\n @property\n def tokenizer(self):\n \"\"\"\n Property to get the tokenizer that is used by this model\n \"\"\"\n return self._first_module().tokenizer\n\n @tokenizer.setter\n def tokenizer(self, value):\n \"\"\"\n Property to set the tokenizer that is should used by this model\n \"\"\"\n self._first_module().tokenizer = value\n\n @property\n def max_seq_length(self):\n \"\"\"\n Property to get the maximal input sequence length for the model. Longer inputs will be truncated.\n \"\"\"\n return self._first_module().max_seq_length\n\n @max_seq_length.setter\n def max_seq_length(self, value):\n \"\"\"\n Property to set the maximal input sequence length for the model. Longer inputs will be truncated.\n \"\"\"\n self._first_module().max_seq_length = value\n" ]
[ [ "torch.cuda.device_count", "torch.hub._get_torch_home", "torch.is_tensor", "torch.tensor", "numpy.concatenate", "torch.multiprocessing.get_context", "torch.cuda.amp.GradScaler", "torch.cuda.amp.autocast", "torch.no_grad", "torch.optim.swa_utils.SWALR", "torch.cuda.is_available", "torch.device", "numpy.argsort", "torch.optim.swa_utils.AveragedModel", "torch.stack" ] ]
Bren0Miranda/Udacity-Computer-Vision-Nanodegree-
[ "834bb274c9d514308947544bd819f514b275e167" ]
[ "1_1_Image_Representation/Green Screen Car Streamlit.py" ]
[ "import cv2\nimport numpy as np\nfrom PIL import Image\nimport streamlit as st\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nst.set_option('deprecation.showfileUploaderEncoding', False)\n\nimg_file = st.file_uploader(\"Upload da imagem\", type=[\"png\", \"jpg\", \"jpeg\"])\n\nimg_file_background = st.file_uploader(\"Upload da imagem de fundo\", type=[\"png\", \"jpg\", \"jpeg\"])\n\nif img_file is not None and img_file_background is not None:\n \n image = Image.open(img_file)\n img_array = np.array(image)\n \n image2 = Image.open(img_file_background)\n img_array2 = np.array(image2)\n \n shape = np.shape(img_array) \n img_array2 = img_array2[:shape[0], :shape[1]]\n \n st.image(img_array, caption=\"Imagem original\", use_column_width=True)\n \n st.image(img_array2, caption=\"Imagem de fundo\", use_column_width=True)\n \n r = st.sidebar.slider(\"Red\", 0, 255, (0, 255), 1)\n g = st.sidebar.slider(\"Green\", 0, 255, (0, 255), 1)\n b = st.sidebar.slider(\"Blue\", 0, 255, (0, 255), 1)\n \n lower_green = np.array([r[0], g[0], b[0]]) \n upper_green = np.array([r[1], g[1], b[1]]) \n\n mask = cv2.inRange(img_array, lower_green, upper_green)\n \n st.image(mask, caption=\"Mask\", use_column_width=True)\n \n masked_image = np.copy(img_array)\n\n masked_image[mask != 255] = [0, 0, 0]\n\n img_array2[mask == 255] = [0, 0, 0]\n\n st.image(img_array2, caption=\"Mask\", use_column_width=True)\n\n imgfinal = img_array2+masked_image\n \n st.image(imgfinal, caption=\"Resultado final\", use_column_width=True)" ]
[ [ "numpy.copy", "numpy.array", "numpy.shape" ] ]
fabiomolinar/excel-files-merger
[ "5cbd9c92582e5532fb75f3a095195f76a86bc6ce" ]
[ "source.py" ]
[ "import os\nimport glob\nimport pandas as pd\n\npath_sources = r\"./sources/*.xls\"\npath_output = r\"./output/output.xlsx\"\n\ndata = pd.DataFrame()\nfor file in glob.glob(path_sources):\n df = pd.read_excel(file, header=None)\n data = data.append(df, ignore_index=True, sort=False)\n\ndata = data.dropna(how=\"all\")\n\nif os.path.exists(path_output):\n os.remove(path_output)\nwith pd.ExcelWriter(path_output) as writer:\n data.to_excel(writer, sheet_name=\"merged\")" ]
[ [ "pandas.read_excel", "pandas.DataFrame", "pandas.ExcelWriter" ] ]
RFChallenge/rfchallenge_starter
[ "724a52f68541d3f9c3f460d88fe4e2be9662aa49", "724a52f68541d3f9c3f460d88fe4e2be9662aa49" ]
[ "rfcutils/dataset_helper_fn.py", "example/demod_bitregression/emisig1_supregdemod.py" ]
[ "import os\nimport warnings\nimport numpy as np\nimport pickle\n\nfrom .sigmf_helper_fn import write_sigmf_file, read_sigmf_file\n\ndef load_dataset_sample(idx, dataset_type, sig_type):\n foldername = os.path.join('dataset',dataset_type,sig_type)\n filename = f'{sig_type}_{dataset_type}_{idx:04d}'\n # Special handling for \"Separation\" validation and test set; only using Comm2 vs [sig_type] for this iteration\n if 'sep_' in dataset_type:\n filename = f'CommSignal2_vs_{sig_type}_{dataset_type}_{idx:04d}'\n data, meta = read_sigmf_file(filename=filename, folderpath=foldername)\n return data, meta\n\ndef load_dataset_sample_components(idx, dataset_type, sig_type):\n assert 'train' in dataset_type or 'val' in dataset_type or 'test' in dataset_type, f'Invalid dataset type requested for obtaining components: {dataset_type}'\n \n soi_name = 'Comm2' if 'sep_' in dataset_type else 'QPSK'\n foldername1 = os.path.join('dataset',dataset_type,'Components', sig_type, soi_name)\n filename1 = f'{sig_type}_{dataset_type}_{idx:04d}'\n # Special handling for \"Separation\" validation and test set; only using Comm2 vs [sig_type] for this iteration\n if 'sep_' in dataset_type:\n filename1 = f'CommSignal2_vs_{sig_type}_{dataset_type}_{idx:04d}'\n data1, meta1 = read_sigmf_file(filename=filename1, folderpath=foldername1)\n \n foldername2 = os.path.join('dataset',dataset_type,'Components', sig_type, 'Interference')\n filename2 = f'{sig_type}_{dataset_type}_{idx:04d}'\n # Special handling for \"Separation\" validation and test set; only using Comm2 vs [sig_type] for this iteration\n if 'sep_' in dataset_type:\n filename2 = f'CommSignal2_vs_{sig_type}_{dataset_type}_{idx:04d}'\n data2, meta2 = read_sigmf_file(filename=filename1, folderpath=foldername2)\n \n return data1, meta1, data2, meta2\n\ndef load_dataset_sample_demod_groundtruth(idx, dataset_type, sig_type):\n assert 'train' in dataset_type or 'val' in dataset_type or 'test' in dataset_type, f'Invalid dataset type requested for obtaining components: {dataset_type}'\n assert 'demod_' in dataset_type, f'Invalid dataset type requested for obtaining components: {dataset_type}'\n \n foldername = os.path.join('dataset',dataset_type,'Components',sig_type,'QPSK')\n filename = f'{sig_type}_{dataset_type}_{idx:04d}'\n data, meta = read_sigmf_file(filename=filename, folderpath=foldername)\n\n msg_folder = os.path.join('dataset',dataset_type,'QPSK_Bits',sig_type)\n msg_filename = f'{sig_type}_{dataset_type}_QPSK_bits_{idx:04d}'\n msg_bits, ground_truth_info = pickle.load(open(os.path.join(msg_folder,f'{msg_filename}.pkl'),'rb'))\n return data, meta, msg_bits, ground_truth_info\n\n\ndef demod_check_ber(bit_est, idx, dataset_type, sig_type):\n assert 'demod_' in dataset_type, f'Invalid dataset type requested for obtaining components: {dataset_type}'\n \n msg_folder = os.path.join('dataset',dataset_type,'QPSK_Bits',sig_type)\n msg_filename = f'{sig_type}_{dataset_type}_QPSK_bits_{idx:04d}'\n bit_true, _ = pickle.load(open(os.path.join(msg_folder,f'{msg_filename}.pkl'),'rb'))\n if len(bit_est) != len(bit_true):\n warnings.warn(f'Mismatch in estimated bit message length ({len(bit_est)}) and true bit message length ({len(bit_true)})')\n msg_len = min(len(bit_true), len(bit_est))\n bit_true = bit_true[:msg_len]\n bit_est = bit_est[:msg_len]\n ber = np.sum(np.abs(bit_est-bit_true))/len(bit_true)\n return ber\n", "import os, sys\nimport numpy as np\nimport pickle\nfrom tqdm import tqdm\nimport time\n\nfrom bitregression_model import get_model\n\n# to run this file from within example/demod_bitregression folder\nos.chdir(os.getcwd())\nprint(os.path.abspath(os.curdir))\nsys.path.append(os.curdir)\n\nimport rfcutils\nget_sinr = lambda s, i: 10*np.log10(np.mean(np.abs(s)**2)/np.mean(np.abs(i)**2))\n\nimport random\nrandom.seed(0)\nnp.random.seed(0)\n\nwindow_len = 1024\nn_ch = 2\n \nval_or_test = 'val'\ninterference_sig_type = 'EMISignal1'\n\nmodel = get_model(window_len, n_ch)\nmodel.load_weights(os.path.join('example','demod_bitregression','models',f'demod_regression_{interference_sig_type}_{window_len}'))\n\n\ndef demod_bits(sig_mixture):\n x_in = sig_mixture.reshape(-1, window_len)\n x_in_comp = np.stack((x_in.real, x_in.imag), axis=-1)\n \n bit_probs = model.predict(x_in_comp)\n bit_est = np.array(bit_probs > 0.5).flatten()\n return bit_est\n\ndef main(): \n dataset_type = f'demod_{val_or_test}'\n \n all_ber, all_default_ber, all_sinr = [], [], []\n all_test_idx = np.arange(1100)\n for idx in all_test_idx:\n sig_mixture,meta = rfcutils.load_dataset_sample(idx, dataset_type, interference_sig_type)\n sig1,meta1,sig2,meta2 = rfcutils.load_dataset_sample_components(idx, dataset_type, interference_sig_type)\n \n sinr = get_sinr(sig1, sig2)\n all_sinr.append(sinr)\n ber_ref = rfcutils.demod_check_ber(rfcutils.matched_filter_demod(sig_mixture), idx, dataset_type, interference_sig_type)\n all_default_ber.append(ber_ref)\n \n bit_est1 = demod_bits(sig_mixture)\n ber1 = rfcutils.demod_check_ber(bit_est1, idx, dataset_type, interference_sig_type)\n all_ber.append(ber1)\n \n print(f\"#{idx} -- SINR {sinr:.3f}dB: 1:{ber1} Default:{ber_ref}\")\n \n if len(all_sinr)%100 == 0:\n pickle.dump((all_ber, all_default_ber, all_sinr), open(os.path.join('example','demod_bitregression','output',f'bitregression_{interference_sig_type}_{val_or_test}_demod.pickle'),'wb'))\n pickle.dump((all_ber, all_default_ber, all_sinr), open(os.path.join('example','demod_bitregression','output',f'bitregression_{interference_sig_type}_{val_or_test}_demod.pickle'),'wb'))\n \nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.abs" ], [ "numpy.abs", "numpy.random.seed", "numpy.arange", "numpy.stack", "numpy.array" ] ]
sozand/My-Portfolio
[ "cb644212b277896112db4f1685e01fc4cafe39c5" ]
[ "Deep learning project/Smile detection/train_model_smile.py" ]
[ "# คำสั่ง\n# python train_model_smile.py --dataset ../datasets/SMILEsmileD --model output/lenet.hdf5\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.utils import to_categorical\nfrom pyimagesearch.nn.conv import LeNet\nfrom imutils import paths\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport argparse\nimport imutils\nimport cv2\nimport os\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-d\", \"--dataset\", required=True,\n\thelp=\"path to input dataset of faces\")\nap.add_argument(\"-m\", \"--model\", required=True,\n\thelp=\"path to output model\")\nargs = vars(ap.parse_args())\n\ndata = []\nlabels = []\n\nfor imagePath in sorted(list(paths.list_images(args[\"dataset\"]))):\n\timage = cv2.imread(imagePath)\n\timage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\timage = imutils.resize(image, width=28)\n\timage = img_to_array(image)\n\tdata.append(image)\n\tlabel = imagePath.split(os.path.sep)[-3]\n\tlabel = \"smiling\" if label == \"positives\" else \"not_smiling\"\n\tlabels.append(label)\n\ndata = np.array(data, dtype=\"float\") / 255.0\nlabels = np.array(labels)\n\n\nle = LabelEncoder().fit(labels)\nlabels = to_categorical(le.transform(labels), 2)\n\nclassTotals = labels.sum(axis=0)\nclassWeight = classTotals.max() / classTotals\n\n(trainX, testX, trainY, testY) = train_test_split(data,\n\tlabels, test_size=0.20, stratify=labels, random_state=42)\n\nprint(\"[INFO] compiling model...\")\nmodel = LeNet.build(width=28, height=28, depth=1, classes=2)\nmodel.compile(loss=\"binary_crossentropy\", optimizer=\"adam\",\n\tmetrics=[\"accuracy\"])\n\nprint(\"[INFO] training network...\")\nH = model.fit(trainX, trainY, validation_data=(testX, testY),\n\tclass_weight=classWeight, batch_size=64, epochs=15, verbose=1)\n\nprint(\"[INFO] evaluating network...\")\npredictions = model.predict(testX, batch_size=64)\nprint(classification_report(testY.argmax(axis=1),\n\tpredictions.argmax(axis=1), target_names=le.classes_))\n\nprint(\"[INFO] serializing network...\")\nmodel.save(args[\"model\"])\n\nplt.style.use(\"ggplot\")\nplt.figure()\nplt.plot(np.arange(0, 15), H.history[\"loss\"], label=\"train_loss\")\nplt.plot(np.arange(0, 15), H.history[\"val_loss\"], label=\"val_loss\")\nplt.plot(np.arange(0, 15), H.history[\"accuracy\"], label=\"acc\")\nplt.plot(np.arange(0, 15), H.history[\"val_accuracy\"], label=\"val_acc\")\nplt.title(\"Training Loss and Accuracy\")\nplt.xlabel(\"Epoch #\")\nplt.ylabel(\"Loss/Accuracy\")\nplt.legend()\nplt.show()" ]
[ [ "matplotlib.pyplot.legend", "tensorflow.keras.preprocessing.image.img_to_array", "matplotlib.pyplot.title", "numpy.arange", "sklearn.model_selection.train_test_split", "sklearn.preprocessing.LabelEncoder", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "numpy.array", "matplotlib.pyplot.style.use", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
mattsamson0203/enterprise_extensions
[ "cd2ebe0094f4b315da122e8acf790f056aa1628e" ]
[ "enterprise_extensions/models.py" ]
[ "# -*- coding: utf-8 -*-\nfrom __future__ import (absolute_import, division,\n print_function, unicode_literals)\nimport numpy as np\nimport functools\nfrom collections import OrderedDict\n\nfrom enterprise.signals import parameter\nfrom enterprise.signals import selections\nfrom enterprise.signals import signal_base\nfrom enterprise.signals import white_signals\nfrom enterprise.signals import gp_signals\nfrom enterprise.signals import deterministic_signals\nfrom enterprise import constants as const\n\nfrom enterprise_extensions import model_utils\nfrom enterprise_extensions import deterministic\nfrom enterprise_extensions.timing import timing_block\nfrom enterprise_extensions.blocks import (white_noise_block, red_noise_block,\n dm_noise_block,\n chromatic_noise_block,\n common_red_noise_block)\nfrom enterprise_extensions.chromatic.solar_wind import solar_wind_block\nfrom enterprise_extensions import chromatic as chrom\nfrom enterprise_extensions import dropout as do\n\n\ndef model_singlepsr_noise(psr, tm_var=False, tm_linear=False,\n tmparam_list=None,\n red_var=True, psd='powerlaw', red_select=None,\n noisedict=None, tm_svd=False, tm_norm=True,\n white_vary=True, components=30, upper_limit=False,\n is_wideband=False, use_dmdata=False,\n dmjump_var=False, gamma_val=None, dm_var=False,\n dm_type='gp', dmgp_kernel='diag', dm_psd='powerlaw',\n dm_nondiag_kernel='periodic', dmx_data=None,\n dm_annual=False, gamma_dm_val=None,\n dm_dt=15, dm_df=200,\n chrom_gp=False, chrom_gp_kernel='nondiag',\n chrom_psd='powerlaw', chrom_idx=4, chrom_quad=False,\n chrom_kernel='periodic',\n chrom_dt=15, chrom_df=200,\n dm_expdip=False, dmexp_sign='negative',\n dm_expdip_idx=2,\n dm_expdip_tmin=None, dm_expdip_tmax=None,\n num_dmdips=1, dmdip_seqname=None,\n dm_cusp=False, dm_cusp_sign='negative',\n dm_cusp_idx=2, dm_cusp_sym=False,\n dm_cusp_tmin=None, dm_cusp_tmax=None,\n num_dm_cusps=1, dm_cusp_seqname=None,\n dm_dual_cusp=False, dm_dual_cusp_tmin=None,\n dm_dual_cusp_tmax=None, dm_dual_cusp_sym=False,\n dm_dual_cusp_idx1=2, dm_dual_cusp_idx2=4,\n dm_dual_cusp_sign='negative', num_dm_dual_cusps=1,\n dm_dual_cusp_seqname=None,\n dm_sw_deter=False, dm_sw_gp=False,\n swgp_prior=None, swgp_basis=None,\n coefficients=False, extra_sigs=None,\n psr_model=False, factorized_like=False,\n Tspan=None, fact_like_gamma=13./3, gw_components=10,\n select='backend'):\n \"\"\"\n Single pulsar noise model\n :param psr: enterprise pulsar object\n :param tm_var: explicitly vary the timing model parameters\n :param tm_linear: vary the timing model in the linear approximation\n :param tmparam_list: an explicit list of timing model parameters to vary\n :param red_var: include red noise in the model\n :param psd: red noise psd model\n :param noisedict: dictionary of noise parameters\n :param tm_svd: boolean for svd-stabilised timing model design matrix\n :param tm_norm: normalize the timing model, or provide custom normalization\n :param white_vary: boolean for varying white noise or keeping fixed\n :param components: number of modes in Fourier domain processes\n :param dm_components: number of modes in Fourier domain DM processes\n :param fact_like_comp: number of modes in Fourier domain for a common\n process in a factorized likelihood calculation.\n :param fact_like: Whether to include a factorized likelihood GWB process.\n :param upper_limit: whether to do an upper-limit analysis\n :param is_wideband: whether input TOAs are wideband TOAs; will exclude\n ecorr from the white noise model\n :param use_dmdata: whether to use DM data (WidebandTimingModel) if\n is_wideband\n :param gamma_val: red noise spectral index to fix\n :param dm_var: whether to explicitly model DM-variations\n :param dm_type: gaussian process ('gp') or dmx ('dmx')\n :param dmgp_kernel: diagonal in frequency or non-diagonal\n :param dm_psd: power-spectral density of DM variations\n :param dm_nondiag_kernel: type of time-domain DM GP kernel\n :param dmx_data: supply the DMX data from par files\n :param dm_annual: include an annual DM signal\n :param gamma_dm_val: spectral index of power-law DM variations\n :param dm_dt: time-scale for DM linear interpolation basis (days)\n :param dm_df: frequency-scale for DM linear interpolation basis (MHz)\n :param chrom_gp: include general chromatic noise\n :param chrom_gp_kernel: GP kernel type to use in chrom ['diag','nondiag']\n :param chrom_psd: power-spectral density of chromatic noise\n ['powerlaw','tprocess','free_spectrum']\n :param chrom_idx: frequency scaling of chromatic noise\n :param chrom_kernel: Type of 'nondiag' time-domain chrom GP kernel to use\n ['periodic', 'sq_exp','periodic_rfband', 'sq_exp_rfband']\n :param chrom_quad: Whether to add a quadratic chromatic term. Boolean\n :param chrom_dt: time-scale for chromatic linear interpolation basis (days)\n :param chrom_df: frequency-scale for chromatic linear interpolation basis (MHz)\n :param dm_expdip: inclue a DM exponential dip\n :param dmexp_sign: set the sign parameter for dip\n :param dm_expdip_idx: chromatic index of exponential dip\n :param dm_expdip_tmin: sampling minimum of DM dip epoch\n :param dm_expdip_tmax: sampling maximum of DM dip epoch\n :param num_dmdips: number of dm exponential dips\n :param dmdip_seqname: name of dip sequence\n :param dm_cusp: include a DM exponential cusp\n :param dm_cusp_sign: set the sign parameter for cusp\n :param dm_cusp_idx: chromatic index of exponential cusp\n :param dm_cusp_tmin: sampling minimum of DM cusp epoch\n :param dm_cusp_tmax: sampling maximum of DM cusp epoch\n :param dm_cusp_sym: make exponential cusp symmetric\n :param num_dm_cusps: number of dm exponential cusps\n :param dm_cusp_seqname: name of cusp sequence\n :param dm_dual_cusp: include a DM cusp with two chromatic indices\n :param dm_dual_cusp_tmin: sampling minimum of DM dual cusp epoch\n :param dm_dual_cusp_tmax: sampling maximum of DM dual cusp epoch\n :param dm_dual_cusp_idx1: first chromatic index of DM dual cusp\n :param dm_dual_cusp_idx2: second chromatic index of DM dual cusp\n :param dm_dual_cusp_sym: make dual cusp symmetric\n :param dm_dual_cusp_sign: set the sign parameter for dual cusp\n :param num_dm_dual_cusps: number of DM dual cusps\n :param dm_dual_cusp_seqname: name of dual cusp sequence\n :param dm_scattering: whether to explicitly model DM scattering variations\n :param dm_sw_deter: use the deterministic solar wind model\n :param dm_sw_gp: add a Gaussian process perturbation to the deterministic\n solar wind model.\n :param swgp_prior: prior is currently set automatically\n :param swgp_basis: ['powerlaw', 'periodic', 'sq_exp']\n :param coefficients: explicitly include latent coefficients in model\n :param psr_model: Return the enterprise model instantiated on the pulsar\n rather than an instantiated PTA object, i.e. model(psr) rather than\n PTA(model(psr)).\n :param factorized_like: Whether to run a factorized likelihood analyis Boolean\n Tspan=None, fact_like_gamma=13./3, gw_components=10\n :param extra_sigs: Any additional `enterprise` signals to be added to the\n model.\n\n :return s: single pulsar noise model\n \"\"\"\n amp_prior = 'uniform' if upper_limit else 'log-uniform'\n\n # timing model\n if not tm_var:\n if (is_wideband and use_dmdata):\n if dmjump_var:\n dmjump = parameter.Uniform(pmin=-0.005, pmax=0.005)\n else:\n dmjump = parameter.Constant()\n if white_vary:\n dmefac = parameter.Uniform(pmin=0.1, pmax=10.0)\n log10_dmequad = parameter.Uniform(pmin=-7.0, pmax=0.0)\n #dmjump = parameter.Uniform(pmin=-0.005, pmax=0.005)\n else:\n dmefac = parameter.Constant()\n log10_dmequad = parameter.Constant()\n #dmjump = parameter.Constant()\n s = gp_signals.WidebandTimingModel(dmefac=dmefac,\n log10_dmequad=log10_dmequad, dmjump=dmjump,\n dmefac_selection=selections.Selection(\n selections.by_backend),\n log10_dmequad_selection=selections.Selection(\n selections.by_backend),\n dmjump_selection=selections.Selection(\n selections.by_frontend))\n else:\n s = gp_signals.TimingModel(use_svd=tm_svd, normed=tm_norm,\n coefficients=coefficients)\n else:\n # create new attribute for enterprise pulsar object\n psr.tmparams_orig = OrderedDict.fromkeys(psr.t2pulsar.pars())\n for key in psr.tmparams_orig:\n psr.tmparams_orig[key] = (psr.t2pulsar[key].val,\n psr.t2pulsar[key].err)\n if not tm_linear:\n s = timing_block(tmparam_list=tmparam_list)\n else:\n pass\n\n # red noise\n if red_var and factorized_like:\n if Tspan is None:\n msg = 'Must Timespan to match amongst all pulsars when doing '\n msg += 'a factorized likelihood analysis.'\n raise ValueError(msg)\n\n s += red_noise_block(psd=psd, prior=amp_prior, Tspan=Tspan,\n components=components, gamma_val=gamma_val,\n coefficients=coefficients, select=red_select)\n\n s += common_red_noise_block(psd=psd, prior=amp_prior,\n Tspan=Tspan, components=gw_components,\n gamma_val=fact_like_gamma, delta_val=None,\n orf=None, name='gw',\n coefficients=coefficients,\n pshift=False, pseed=None)\n\n\n elif red_var:\n s += red_noise_block(psd=psd, prior=amp_prior,\n components=components, gamma_val=gamma_val,\n coefficients=coefficients, select=red_select)\n\n # DM variations\n if dm_var:\n if dm_type == 'gp':\n if dmgp_kernel == 'diag':\n s += dm_noise_block(gp_kernel=dmgp_kernel, psd=dm_psd,\n prior=amp_prior, components=components,\n gamma_val=gamma_dm_val,\n coefficients=coefficients)\n elif dmgp_kernel == 'nondiag':\n s += dm_noise_block(gp_kernel=dmgp_kernel,\n nondiag_kernel=dm_nondiag_kernel,\n dt=dm_dt, df=dm_df,\n coefficients=coefficients)\n elif dm_type == 'dmx':\n s += chrom.dmx_signal(dmx_data=dmx_data[psr.name])\n if dm_annual:\n s += chrom.dm_annual_signal()\n if chrom_gp:\n s += chromatic_noise_block(gp_kernel=chrom_gp_kernel,\n psd=chrom_psd, idx=chrom_idx,\n components=components,\n nondiag_kernel=chrom_kernel,\n dt=chrom_dt, df=chrom_df,\n include_quadratic=chrom_quad,\n coefficients=coefficients)\n\n if dm_expdip:\n if dm_expdip_tmin is None and dm_expdip_tmax is None:\n tmin = [psr.toas.min() / const.day for ii in range(num_dmdips)]\n tmax = [psr.toas.max() / const.day for ii in range(num_dmdips)]\n else:\n tmin = (dm_expdip_tmin if isinstance(dm_expdip_tmin,list)\n else [dm_expdip_tmin])\n tmax = (dm_expdip_tmax if isinstance(dm_expdip_tmax,list)\n else [dm_expdip_tmax])\n if dmdip_seqname is not None:\n dmdipname_base = (['dmexp_' + nm for nm in dmdip_seqname]\n if isinstance(dmdip_seqname,list)\n else ['dmexp_' + dmdip_seqname])\n else:\n dmdipname_base = ['dmexp_{0}'.format(ii+1)\n for ii in range(num_dmdips)]\n\n dm_expdip_idx = (dm_expdip_idx if isinstance(dm_expdip_idx,list)\n else [dm_expdip_idx])\n for dd in range(num_dmdips):\n s += chrom.dm_exponential_dip(tmin=tmin[dd], tmax=tmax[dd],\n idx=dm_expdip_idx[dd],\n sign=dmexp_sign,\n name=dmdipname_base[dd])\n if dm_cusp:\n if dm_cusp_tmin is None and dm_cusp_tmax is None:\n tmin = [psr.toas.min() / const.day for ii in range(num_dm_cusps)]\n tmax = [psr.toas.max() / const.day for ii in range(num_dm_cusps)]\n else:\n tmin = (dm_cusp_tmin if isinstance(dm_cusp_tmin,list)\n else [dm_cusp_tmin])\n tmax = (dm_cusp_tmax if isinstance(dm_cusp_tmax,list)\n else [dm_cusp_tmax])\n if dm_cusp_seqname is not None:\n cusp_name_base = 'dm_cusp_'+dm_cusp_seqname+'_'\n else:\n cusp_name_base = 'dm_cusp_'\n dm_cusp_idx = (dm_cusp_idx if isinstance(dm_cusp_idx,list)\n else [dm_cusp_idx])\n dm_cusp_sign = (dm_cusp_sign if isinstance(dm_cusp_sign,list)\n else [dm_cusp_sign])\n for dd in range(1,num_dm_cusps+1):\n s += chrom.dm_exponential_cusp(tmin=tmin[dd-1],\n tmax=tmax[dd-1],\n idx=dm_cusp_idx,\n sign=dm_cusp_sign[dd-1],\n symmetric=dm_cusp_sym,\n name=cusp_name_base+str(dd))\n if dm_dual_cusp:\n if dm_dual_cusp_tmin is None and dm_cusp_tmax is None:\n tmin = psr.toas.min() / const.day\n tmax = psr.toas.max() / const.day\n else:\n tmin = dm_dual_cusp_tmin\n tmax = dm_dual_cusp_tmax\n if dm_dual_cusp_seqname is not None:\n dual_cusp_name_base = 'dm_dual_cusp_'+dm_cusp_seqname+'_'\n else:\n dual_cusp_name_base = 'dm_dual_cusp_'\n for dd in range(1,num_dm_dual_cusps+1):\n s += chrom.dm_dual_exp_cusp(tmin=tmin, tmax=tmax,\n idx1=dm_dual_cusp_idx1,\n idx2=dm_dual_cusp_idx2,\n sign=dm_dual_cusp_sign,\n symmetric=dm_dual_cusp_sym,\n name=dual_cusp_name_base+str(dd))\n if dm_sw_deter:\n Tspan = psr.toas.max() - psr.toas.min()\n s+=solar_wind_block(ACE_prior=True, include_swgp=dm_sw_gp,\n swgp_prior=swgp_prior, swgp_basis=swgp_basis,\n Tspan=Tspan)\n\n if extra_sigs is not None:\n s += extra_sigs\n # adding white-noise, and acting on psr objects\n if 'NANOGrav' in psr.flags['pta'] and not is_wideband:\n s2 = s + white_noise_block(vary=white_vary, inc_ecorr=True,\n select=select)\n model = s2(psr)\n if psr_model:\n Model = s2\n else:\n s3 = s + white_noise_block(vary=white_vary, inc_ecorr=False,\n select=select)\n model = s3(psr)\n if psr_model:\n Model = s3\n\n if psr_model:\n return Model\n else:\n # set up PTA\n pta = signal_base.PTA([model])\n\n # set white noise parameters\n if not white_vary or (is_wideband and use_dmdata):\n if noisedict is None:\n print('No noise dictionary provided!...')\n else:\n noisedict = noisedict\n pta.set_default_params(noisedict)\n\n return pta\n\n\ndef model_1(psrs, psd='powerlaw', noisedict=None, white_vary=False,\n components=30, upper_limit=False, bayesephem=False,\n be_type='orbel', is_wideband=False, use_dmdata=False,\n select='backend'):\n \"\"\"\n Reads in list of enterprise Pulsar instance and returns a PTA\n instantiated with only white and red noise:\n\n per pulsar:\n 1. fixed EFAC per backend/receiver system\n 2. fixed EQUAD per backend/receiver system\n 3. fixed ECORR per backend/receiver system\n 4. Red noise modeled as a power-law with 30 sampling frequencies\n 5. Linear timing model.\n\n global:\n 1. Optional physical ephemeris modeling.\n\n\n :param psd:\n Choice of PSD function [e.g. powerlaw (default), turnover, tprocess]\n :param noisedict:\n Dictionary of pulsar noise properties. Can provide manually,\n or the code will attempt to find it.\n :param white_vary:\n boolean for varying white noise or keeping fixed.\n :param upper_limit:\n Perform upper limit on common red noise amplitude. By default\n this is set to False. Note that when perfoming upper limits it\n is recommended that the spectral index also be fixed to a specific\n value.\n :param bayesephem:\n Include BayesEphem model. Set to False by default\n :param be_type:\n orbel, orbel-v2, setIII\n :param is_wideband:\n Whether input TOAs are wideband TOAs; will exclude ecorr from the white\n noise model.\n :param use_dmdata: whether to use DM data (WidebandTimingModel) if\n is_wideband.\n \"\"\"\n\n amp_prior = 'uniform' if upper_limit else 'log-uniform'\n\n # find the maximum time span to set GW frequency sampling\n Tspan = model_utils.get_tspan(psrs)\n\n # red noise\n s = red_noise_block(psd=psd, prior=amp_prior,\n Tspan=Tspan, components=components)\n\n # ephemeris model\n if bayesephem:\n s += deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True,\n model=be_type)\n\n # timing model\n if (is_wideband and use_dmdata):\n dmjump = parameter.Constant()\n if white_vary:\n dmefac = parameter.Uniform(pmin=0.1, pmax=10.0)\n log10_dmequad = parameter.Uniform(pmin=-7.0, pmax=0.0)\n #dmjump = parameter.Uniform(pmin=-0.005, pmax=0.005)\n else:\n dmefac = parameter.Constant()\n log10_dmequad = parameter.Constant()\n #dmjump = parameter.Constant()\n s += gp_signals.WidebandTimingModel(dmefac=dmefac,\n log10_dmequad=log10_dmequad, dmjump=dmjump,\n dmefac_selection=selections.Selection(selections.by_backend),\n log10_dmequad_selection=selections.Selection(\n selections.by_backend),\n dmjump_selection=selections.Selection(selections.by_frontend))\n else:\n s += gp_signals.TimingModel()\n\n # adding white-noise, and acting on psr objects\n models = []\n for p in psrs:\n if 'NANOGrav' in p.flags['pta'] and not is_wideband:\n s2 = s + white_noise_block(vary=white_vary, inc_ecorr=True,\n select=select)\n models.append(s2(p))\n else:\n s3 = s + white_noise_block(vary=white_vary, inc_ecorr=False,\n select=select)\n models.append(s3(p))\n\n # set up PTA\n pta = signal_base.PTA(models)\n\n # set white noise parameters\n if not white_vary or (is_wideband and use_dmdata):\n if noisedict is None:\n print('No noise dictionary provided!...')\n else:\n noisedict = noisedict\n pta.set_default_params(noisedict)\n\n return pta\n\n\ndef model_2a(psrs, psd='powerlaw', noisedict=None, components=30,\n n_rnfreqs = None, n_gwbfreqs=None, gamma_common=None,\n delta_common=None, upper_limit=False, bayesephem=False,\n be_type='orbel', white_vary=False, is_wideband=False,\n use_dmdata=False, select='backend',\n pshift=False, pseed=None, psr_models=False):\n \"\"\"\n Reads in list of enterprise Pulsar instance and returns a PTA\n instantiated with model 2A from the analysis paper:\n per pulsar:\n 1. fixed EFAC per backend/receiver system\n 2. fixed EQUAD per backend/receiver system\n 3. fixed ECORR per backend/receiver system\n 4. Red noise modeled as a power-law with 30 sampling frequencies\n 5. Linear timing model.\n global:\n 1.Common red noise modeled with user defined PSD with\n 30 sampling frequencies. Available PSDs are\n ['powerlaw', 'turnover' 'spectrum']\n 2. Optional physical ephemeris modeling.\n :param psd:\n PSD to use for common red noise signal. Available options\n are ['powerlaw', 'turnover' 'spectrum']. 'powerlaw' is default\n value.\n :param noisedict:\n Dictionary of pulsar noise properties. Can provide manually,\n or the code will attempt to find it.\n :param white_vary:\n boolean for varying white noise or keeping fixed.\n :param gamma_common:\n Fixed common red process spectral index value. By default we\n vary the spectral index over the range [0, 7].\n :param upper_limit:\n Perform upper limit on common red noise amplitude. By default\n this is set to False. Note that when perfoming upper limits it\n is recommended that the spectral index also be fixed to a specific\n value.\n :param bayesephem:\n Include BayesEphem model. Set to False by default\n :param be_type:\n orbel, orbel-v2, setIII\n :param is_wideband:\n Whether input TOAs are wideband TOAs; will exclude ecorr from the white\n noise model.\n :param use_dmdata: whether to use DM data (WidebandTimingModel) if\n is_wideband.\n :param psr_models:\n Return list of psr models rather than signal_base.PTA object.\n :param n_rnfreqs:\n Number of frequencies to use in achromatic rednoise model.\n :param n_gwbfreqs:\n Number of frequencies to use in the GWB model.\n :param pshift:\n Option to use a random phase shift in design matrix. For testing the\n null hypothesis.\n :param pseed:\n Option to provide a seed for the random phase shift.\n \"\"\"\n\n amp_prior = 'uniform' if upper_limit else 'log-uniform'\n\n # find the maximum time span to set GW frequency sampling\n Tspan = model_utils.get_tspan(psrs)\n\n if n_gwbfreqs is None:\n n_gwbfreqs = components\n\n if n_rnfreqs is None:\n n_rnfreqs = components\n\n # red noise\n s = red_noise_block(prior=amp_prior, Tspan=Tspan, components=n_rnfreqs)\n\n # common red noise block\n s += common_red_noise_block(psd=psd, prior=amp_prior, Tspan=Tspan,\n components=n_gwbfreqs, gamma_val=gamma_common,\n delta_val=delta_common, name='gw',\n pshift=pshift, pseed=pseed)\n\n # ephemeris model\n if bayesephem:\n s += deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True,\n model=be_type)\n\n # timing model\n if (is_wideband and use_dmdata):\n dmjump = parameter.Constant()\n if white_vary:\n dmefac = parameter.Uniform(pmin=0.1, pmax=10.0)\n log10_dmequad = parameter.Uniform(pmin=-7.0, pmax=0.0)\n #dmjump = parameter.Uniform(pmin=-0.005, pmax=0.005)\n else:\n dmefac = parameter.Constant()\n log10_dmequad = parameter.Constant()\n #dmjump = parameter.Constant()\n s += gp_signals.WidebandTimingModel(dmefac=dmefac,\n log10_dmequad=log10_dmequad, dmjump=dmjump,\n dmefac_selection=selections.Selection(selections.by_backend),\n log10_dmequad_selection=selections.Selection(\n selections.by_backend),\n dmjump_selection=selections.Selection(selections.by_frontend))\n else:\n s += gp_signals.TimingModel()\n\n # adding white-noise, and acting on psr objects\n models = []\n for p in psrs:\n if 'NANOGrav' in p.flags['pta'] and not is_wideband:\n s2 = s + white_noise_block(vary=white_vary, inc_ecorr=True,\n select=select)\n models.append(s2(p))\n else:\n s3 = s + white_noise_block(vary=white_vary, inc_ecorr=False,\n select=select)\n models.append(s3(p))\n\n # set up PTA\n pta = signal_base.PTA(models)\n\n if psr_models:\n return models\n else:\n # set up PTA\n pta = signal_base.PTA(models)\n\n # set white noise parameters\n if noisedict is None:\n print('No noise dictionary provided!...')\n else:\n noisedict = noisedict\n pta.set_default_params(noisedict)\n\n return pta\n\n\ndef model_general(psrs, tm_var=False, tm_linear=False, tmparam_list=None,\n tm_svd=False, tm_norm=True, noisedict=None, white_vary=False,\n Tspan=None, modes=None, wgts=None, logfreq=False, nmodes_log=10,\n common_psd='powerlaw', common_components=30, \n log10_A_common=None, gamma_common=None,\n orf='crn', orf_names=None, orf_ifreq=0, leg_lmax=5, \n upper_limit_common=None, upper_limit=False,\n red_var=True, red_psd='powerlaw', red_components=30, upper_limit_red=None,\n red_select=None, red_breakflat=False, red_breakflat_fq=None,\n bayesephem=False, be_type='setIII_1980', is_wideband=False, use_dmdata=False,\n dm_var=False, dm_type='gp', dm_psd='powerlaw', dm_components=30,\n upper_limit_dm=None, dm_annual=False, dm_chrom=False, dmchrom_psd='powerlaw',\n dmchrom_idx=4, gequad=False, coefficients=False, pshift=False,\n select='backend'):\n \"\"\"\n Reads in list of enterprise Pulsar instances and returns a PTA\n object instantiated with user-supplied options.\n\n :param tm_var: boolean to vary timing model coefficients.\n [default = False]\n :param tm_linear: boolean to vary timing model under linear approximation.\n [default = False]\n :param tmparam_list: list of timing model parameters to vary.\n [default = None]\n :param tm_svd: stabilize timing model designmatrix with SVD.\n [default = False]\n :param tm_norm: normalize the timing model design matrix, or provide custom\n normalization. Alternative to 'tm_svd'.\n [default = True]\n :param noisedict: Dictionary of pulsar noise properties. Can provide manually,\n or the code will attempt to find it.\n [default = None]\n :param white_vary: boolean for varying white noise or keeping fixed.\n [default = False]\n :param Tspan: timespan assumed for describing stochastic processes,\n in units of seconds. If None provided will find span of pulsars.\n [default = None]\n :param modes: list of frequencies on which to describe red processes.\n [default = None]\n :param wgts: sqrt summation weights for each frequency bin, i.e. sqrt(delta f).\n [default = None]\n :param logfreq: boolean for including log-spaced bins.\n [default = False]\n :param nmodes_log: number of log-spaced bins below 1/T.\n [default = 10]\n :param common_psd: psd of common process.\n ['powerlaw', 'spectrum', 'turnover', 'turnover_knee,', 'broken_powerlaw']\n [default = 'powerlaw']\n :param common_components: number of frequencies starting at 1/T for common process.\n [default = 30]\n :param log10_A_common: value of fixed log10_A_common parameter for \n fixed amplitude analyses.\n [default = None]\n :param gamma_common: fixed common red process spectral index value. By default we\n vary the spectral index over the range [0, 7].\n [default = None]\n :param orf: comma de-limited string of multiple common processes with different orfs.\n [default = crn]\n :param orf_names: comma de-limited string of process names for different orfs. Manual \n control of these names is useful for embedding model_general within a hypermodel\n analysis for a process with and without hd correlations where we want to avoid \n parameter duplication.\n [default = None]\n :param orf_ifreq:\n Frequency bin at which to start the Hellings & Downs function with \n numbering beginning at 0. Currently only works with freq_hd orf.\n [default = 0]\n :param leg_lmax:\n Maximum multipole of a Legendre polynomial series representation \n of the overlap reduction function. \n [default = 5]\n :param upper_limit_common: perform upper limit on common red noise amplitude. Note\n that when perfoming upper limits it is recommended that the spectral index also\n be fixed to a specific value.\n [default = False]\n :param upper_limit: apply upper limit priors to all red processes.\n [default = False]\n :param red_var: boolean to switch on/off intrinsic red noise.\n [default = True]\n :param red_psd: psd of intrinsic red process.\n ['powerlaw', 'spectrum', 'turnover', 'tprocess', 'tprocess_adapt', 'infinitepower']\n [default = 'powerlaw']\n :param red_components: number of frequencies starting at 1/T for intrinsic red process.\n [default = 30]\n :param upper_limit_red: perform upper limit on intrinsic red noise amplitude. Note\n that when perfoming upper limits it is recommended that the spectral index also\n be fixed to a specific value.\n [default = False]\n :param red_select: selection properties for intrinsic red noise.\n ['backend', 'band', 'band+', None]\n [default = None]\n :param red_breakflat: break red noise spectrum and make flat above certain frequency.\n [default = False]\n :param red_breakflat_fq: break frequency for 'red_breakflat'.\n [default = None]\n :param bayesephem: boolean to include BayesEphem model.\n [default = False]\n :param be_type: flavor of bayesephem model based on how partials are computed.\n ['orbel', 'orbel-v2', 'setIII', 'setIII_1980']\n [default = 'setIII_1980']\n :param is_wideband: boolean for whether input TOAs are wideband TOAs. Will exclude\n ecorr from the white noise model.\n [default = False]\n :param use_dmdata: whether to use DM data (WidebandTimingModel) if is_wideband.\n [default = False]\n :param dm_var: boolean for explicitly searching for DM variations.\n [default = False]\n :param dm_type: type of DM variations.\n ['gp', other choices selected with additional options; see below]\n [default = 'gp']\n :param dm_psd: psd of DM GP.\n ['powerlaw', 'spectrum', 'turnover', 'tprocess', 'tprocess_adapt']\n [default = 'powerlaw']\n :param dm_components: number of frequencies starting at 1/T for DM GP.\n [default = 30]\n :param upper_limit_dm: perform upper limit on DM GP. Note that when perfoming\n upper limits it is recommended that the spectral index also be\n fixed to a specific value.\n [default = False]\n :param dm_annual: boolean to search for an annual DM trend.\n [default = False]\n :param dm_chrom: boolean to search for a generic chromatic GP.\n [default = False]\n :param dmchrom_psd: psd of generic chromatic GP.\n ['powerlaw', 'spectrum', 'turnover']\n [default = 'powerlaw']\n :param dmchrom_idx: spectral index of generic chromatic GP.\n [default = 4]\n :param gequad: boolean to search for a global EQUAD.\n [default = False]\n :param coefficients: boolean to form full hierarchical PTA object;\n (no analytic latent-coefficient marginalization)\n [default = False]\n :param pshift: boolean to add random phase shift to red noise Fourier design\n matrices for false alarm rate studies.\n [default = False]\n\n Default PTA object composition:\n 1. fixed EFAC per backend/receiver system (per pulsar)\n 2. fixed EQUAD per backend/receiver system (per pulsar)\n 3. fixed ECORR per backend/receiver system (per pulsar)\n 4. Red noise modeled as a power-law with 30 sampling frequencies\n (per pulsar)\n 5. Linear timing model (per pulsar)\n 6. Common-spectrum uncorrelated process modeled as a power-law with\n 30 sampling frequencies. (global)\n \"\"\"\n\n amp_prior = 'uniform' if upper_limit else 'log-uniform'\n gp_priors = [upper_limit_red, upper_limit_dm, upper_limit_common]\n if all(ii is None for ii in gp_priors):\n amp_prior_red = amp_prior\n amp_prior_dm = amp_prior\n amp_prior_common = amp_prior\n else:\n amp_prior_red = 'uniform' if upper_limit_red else 'log-uniform'\n amp_prior_dm = 'uniform' if upper_limit_dm else 'log-uniform'\n amp_prior_common = 'uniform' if upper_limit_common else 'log-uniform'\n\n # timing model\n if not tm_var and not use_dmdata:\n s = gp_signals.TimingModel(use_svd=tm_svd, normed=tm_norm,\n coefficients=coefficients)\n elif not tm_var and use_dmdata:\n dmjump = parameter.Constant()\n if white_vary:\n dmefac = parameter.Uniform(pmin=0.1, pmax=10.0)\n log10_dmequad = parameter.Uniform(pmin=-7.0, pmax=0.0)\n #dmjump = parameter.Uniform(pmin=-0.005, pmax=0.005)\n else:\n dmefac = parameter.Constant()\n log10_dmequad = parameter.Constant()\n #dmjump = parameter.Constant()\n s = gp_signals.WidebandTimingModel(dmefac=dmefac,\n log10_dmequad=log10_dmequad, dmjump=dmjump,\n dmefac_selection=selections.Selection(selections.by_backend),\n log10_dmequad_selection=selections.Selection(\n selections.by_backend),\n dmjump_selection=selections.Selection(selections.by_frontend))\n else:\n # create new attribute for enterprise pulsar object\n for p in psrs:\n p.tmparams_orig = OrderedDict.fromkeys(p.t2pulsar.pars())\n for key in p.tmparams_orig:\n p.tmparams_orig[key] = (p.t2pulsar[key].val,\n p.t2pulsar[key].err)\n if not tm_linear:\n s = timing_block(tmparam_list=tmparam_list)\n else:\n pass\n\n # find the maximum time span to set GW frequency sampling\n if Tspan is not None:\n Tspan = Tspan\n else:\n Tspan = model_utils.get_tspan(psrs)\n\n if logfreq:\n fmin = 10.0\n modes, wgts = model_utils.linBinning(Tspan, nmodes_log,\n 1.0 / fmin / Tspan,\n common_components, nmodes_log)\n wgts = wgts**2.0\n\n # red noise\n if red_var:\n s += red_noise_block(psd=red_psd, prior=amp_prior_red, Tspan=Tspan,\n components=red_components, modes=modes, wgts=wgts,\n coefficients=coefficients,\n select=red_select, break_flat=red_breakflat,\n break_flat_fq=red_breakflat_fq)\n\n # common red noise block\n crn = []\n if orf_names is None:\n orf_names = orf\n for elem,elem_name in zip(orf.split(','),orf_names.split(',')):\n if elem == 'zero_diag_bin_orf' or elem == 'zero_diag_legendre_orf':\n log10_A_val = log10_A_common\n else:\n log10_A_val = None\n crn.append(common_red_noise_block(psd=common_psd, prior=amp_prior_common, Tspan=Tspan,\n components=common_components, \n log10_A_val=log10_A_val, gamma_val=gamma_common,\n delta_val=None, orf=elem, name='gw_{}'.format(elem_name),\n orf_ifreq=orf_ifreq, leg_lmax=leg_lmax,\n coefficients=coefficients, pshift=pshift, pseed=None))\n # orf_ifreq only affects freq_hd model. \n # leg_lmax only affects (zero_diag_)legendre_orf model.\n crn = functools.reduce((lambda x,y:x+y), crn)\n s += crn\n\n # DM variations\n if dm_var:\n if dm_type == 'gp':\n s += dm_noise_block(gp_kernel='diag', psd=dm_psd,\n prior=amp_prior_dm,\n components=dm_components, gamma_val=None,\n coefficients=coefficients)\n if dm_annual:\n s += chrom.dm_annual_signal()\n if dm_chrom:\n s += chromatic_noise_block(psd=dmchrom_psd, idx=dmchrom_idx,\n name='chromatic',\n components=dm_components,\n coefficients=coefficients)\n\n # ephemeris model\n if bayesephem:\n s += deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True,\n model=be_type)\n\n # adding white-noise, and acting on psr objects\n models = []\n for p in psrs:\n if 'NANOGrav' in p.flags['pta'] and not is_wideband:\n s2 = s + white_noise_block(vary=white_vary, inc_ecorr=True,\n select=select)\n if gequad:\n s2 += white_signals.EquadNoise(log10_equad=parameter.Uniform(-8.5, -5),\n selection=selections.Selection(selections.no_selection),\n name='gequad')\n if '1713' in p.name and dm_var:\n tmin = p.toas.min() / const.day\n tmax = p.toas.max() / const.day\n s3 = s2 + chrom.dm_exponential_dip(tmin=tmin, tmax=tmax, idx=2,\n sign=False, name='dmexp')\n models.append(s3(p))\n else:\n models.append(s2(p))\n else:\n s4 = s + white_noise_block(vary=white_vary, inc_ecorr=False,\n select=select)\n if gequad:\n s4 += white_signals.EquadNoise(log10_equad=parameter.Uniform(-8.5, -5),\n selection=selections.Selection(selections.no_selection),\n name='gequad')\n if '1713' in p.name and dm_var:\n tmin = p.toas.min() / const.day\n tmax = p.toas.max() / const.day\n s5 = s4 + chrom.dm_exponential_dip(tmin=tmin, tmax=tmax, idx=2,\n sign=False, name='dmexp')\n models.append(s5(p))\n else:\n models.append(s4(p))\n\n # set up PTA\n pta = signal_base.PTA(models)\n\n # set white noise parameters\n if not white_vary or (is_wideband and use_dmdata):\n if noisedict is None:\n print('No noise dictionary provided!...')\n else:\n noisedict = noisedict\n pta.set_default_params(noisedict)\n\n return pta\n\n\ndef model_2b(psrs, psd='powerlaw', noisedict=None, white_vary=False,\n components=30, gamma_common=None, upper_limit=False,\n bayesephem=False, be_type='orbel', is_wideband=False,\n use_dmdata=False, select='backend', pshift=False):\n \"\"\"\n Reads in list of enterprise Pulsar instance and returns a PTA\n instantiated with model 2B from the analysis paper:\n\n per pulsar:\n 1. fixed EFAC per backend/receiver system\n 2. fixed EQUAD per backend/receiver system\n 3. fixed ECORR per backend/receiver system\n 4. Red noise modeled as a power-law with 30 sampling frequencies\n 5. Linear timing model.\n\n global:\n 1. Dipole spatially correlated signal modeled with PSD.\n Default PSD is powerlaw. Available options\n ['powerlaw', 'turnover', 'spectrum']\n 2. Optional physical ephemeris modeling.\n\n :param psd:\n PSD to use for common red noise signal. Available options\n are ['powerlaw', 'turnover' 'spectrum']. 'powerlaw' is default\n value.\n :param noisedict:\n Dictionary of pulsar noise properties. Can provide manually,\n or the code will attempt to find it.\n :param white_vary:\n boolean for varying white noise or keeping fixed.\n :param gamma_common:\n Fixed common red process spectral index value. By default we\n vary the spectral index over the range [0, 7].\n :param upper_limit:\n Perform upper limit on common red noise amplitude. By default\n this is set to False. Note that when perfoming upper limits it\n is recommended that the spectral index also be fixed to a specific\n value.\n :param bayesephem:\n Include BayesEphem model. Set to False by default\n :param be_type:\n orbel, orbel-v2, setIII\n :param is_wideband:\n Whether input TOAs are wideband TOAs; will exclude ecorr from the white\n noise model.\n :param use_dmdata: whether to use DM data (WidebandTimingModel) if\n is_wideband.\n \"\"\"\n\n amp_prior = 'uniform' if upper_limit else 'log-uniform'\n\n # find the maximum time span to set GW frequency sampling\n Tspan = model_utils.get_tspan(psrs)\n\n # red noise\n s = red_noise_block(prior=amp_prior, Tspan=Tspan, components=components)\n\n # dipole\n s += common_red_noise_block(psd=psd, prior=amp_prior, Tspan=Tspan,\n components=components, gamma_val=gamma_common,\n orf='dipole', name='dipole', pshift=pshift)\n\n # ephemeris model\n if bayesephem:\n s += deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True,\n model=be_type)\n\n # timing model\n if (is_wideband and use_dmdata):\n dmjump = parameter.Constant()\n if white_vary:\n dmefac = parameter.Uniform(pmin=0.1, pmax=10.0)\n log10_dmequad = parameter.Uniform(pmin=-7.0, pmax=0.0)\n #dmjump = parameter.Uniform(pmin=-0.005, pmax=0.005)\n else:\n dmefac = parameter.Constant()\n log10_dmequad = parameter.Constant()\n #dmjump = parameter.Constant()\n s += gp_signals.WidebandTimingModel(dmefac=dmefac,\n log10_dmequad=log10_dmequad, dmjump=dmjump,\n dmefac_selection=selections.Selection(selections.by_backend),\n log10_dmequad_selection=selections.Selection(\n selections.by_backend),\n dmjump_selection=selections.Selection(selections.by_frontend))\n else:\n s += gp_signals.TimingModel()\n\n # adding white-noise, and acting on psr objects\n models = []\n for p in psrs:\n if 'NANOGrav' in p.flags['pta'] and not is_wideband:\n s2 = s + white_noise_block(vary=white_vary, inc_ecorr=True,\n select=select)\n models.append(s2(p))\n else:\n s3 = s + white_noise_block(vary=white_vary, inc_ecorr=False,\n select=select)\n models.append(s3(p))\n\n # set up PTA\n pta = signal_base.PTA(models)\n # set white noise parameters\n\n if not white_vary or (is_wideband and use_dmdata):\n if noisedict is None:\n print('No noise dictionary provided!...')\n else:\n noisedict = noisedict\n pta.set_default_params(noisedict)\n\n return pta\n\n\ndef model_2c(psrs, psd='powerlaw', noisedict=None, white_vary=False,\n components=30, gamma_common=None, upper_limit=False,\n bayesephem=False, be_type='orbel', is_wideband=False,\n use_dmdata=False, select='backend'):\n \"\"\"\n Reads in list of enterprise Pulsar instance and returns a PTA\n instantiated with model 2C from the analysis paper:\n\n per pulsar:\n 1. fixed EFAC per backend/receiver system\n 2. fixed EQUAD per backend/receiver system\n 3. fixed ECORR per backend/receiver system\n 4. Red noise modeled as a power-law with 30 sampling frequencies\n 5. Linear timing model.\n\n global:\n 1. Dipole spatially correlated signal modeled with PSD.\n Default PSD is powerlaw. Available options\n ['powerlaw', 'turnover', 'spectrum']\n 2. Monopole spatially correlated signal modeled with PSD.\n Default PSD is powerlaw. Available options\n ['powerlaw', 'turnover', 'spectrum']\n 3. Optional physical ephemeris modeling.\n\n :param psd:\n PSD to use for common red noise signal. Available options\n are ['powerlaw', 'turnover' 'spectrum']. 'powerlaw' is default\n value.\n :param noisedict:\n Dictionary of pulsar noise properties. Can provide manually,\n or the code will attempt to find it.\n :param white_vary:\n boolean for varying white noise or keeping fixed.\n :param gamma_common:\n Fixed common red process spectral index value. By default we\n vary the spectral index over the range [0, 7].\n :param upper_limit:\n Perform upper limit on common red noise amplitude. By default\n this is set to False. Note that when perfoming upper limits it\n is recommended that the spectral index also be fixed to a specific\n value.\n :param bayesephem:\n Include BayesEphem model. Set to False by default\n :param be_type:\n orbel, orbel-v2, setIII\n :param is_wideband:\n Whether input TOAs are wideband TOAs; will exclude ecorr from the white\n noise model.\n :param use_dmdata: whether to use DM data (WidebandTimingModel) if\n is_wideband.\n \"\"\"\n\n amp_prior = 'uniform' if upper_limit else 'log-uniform'\n\n # find the maximum time span to set GW frequency sampling\n Tspan = model_utils.get_tspan(psrs)\n\n # red noise\n s = red_noise_block(prior=amp_prior, Tspan=Tspan, components=components)\n\n # dipole\n s += common_red_noise_block(psd=psd, prior=amp_prior, Tspan=Tspan,\n components=components, gamma_val=gamma_common,\n orf='dipole', name='dipole')\n\n # monopole\n s += common_red_noise_block(psd=psd, prior=amp_prior, Tspan=Tspan,\n components=components, gamma_val=gamma_common,\n orf='monopole', name='monopole')\n\n # ephemeris model\n if bayesephem:\n s += deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True,\n model=be_type)\n\n # timing model\n if (is_wideband and use_dmdata):\n dmjump = parameter.Constant()\n if white_vary:\n dmefac = parameter.Uniform(pmin=0.1, pmax=10.0)\n log10_dmequad = parameter.Uniform(pmin=-7.0, pmax=0.0)\n #dmjump = parameter.Uniform(pmin=-0.005, pmax=0.005)\n else:\n dmefac = parameter.Constant()\n log10_dmequad = parameter.Constant()\n #dmjump = parameter.Constant()\n s += gp_signals.WidebandTimingModel(dmefac=dmefac,\n log10_dmequad=log10_dmequad, dmjump=dmjump,\n dmefac_selection=selections.Selection(selections.by_backend),\n log10_dmequad_selection=selections.Selection(\n selections.by_backend),\n dmjump_selection=selections.Selection(selections.by_frontend))\n else:\n s += gp_signals.TimingModel()\n\n # adding white-noise, and acting on psr objects\n models = []\n for p in psrs:\n if 'NANOGrav' in p.flags['pta'] and not is_wideband:\n s2 = s + white_noise_block(vary=white_vary, inc_ecorr=True,\n select=select)\n models.append(s2(p))\n else:\n s3 = s + white_noise_block(vary=white_vary, inc_ecorr=False,\n select=select)\n models.append(s3(p))\n\n # set up PTA\n pta = signal_base.PTA(models)\n\n # set white noise parameters\n if not white_vary or (is_wideband and use_dmdata):\n if noisedict is None:\n print('No noise dictionary provided!...')\n else:\n noisedict = noisedict\n pta.set_default_params(noisedict)\n\n return pta\n\n\ndef model_2d(psrs, psd='powerlaw', noisedict=None, white_vary=False,\n components=30, gamma_common=None, upper_limit=False,\n bayesephem=False, be_type='orbel', is_wideband=False,\n use_dmdata=False, select='backend', pshift=False):\n \"\"\"\n Reads in list of enterprise Pulsar instance and returns a PTA\n instantiated with model 2D from the analysis paper:\n\n per pulsar:\n 1. fixed EFAC per backend/receiver system\n 2. fixed EQUAD per backend/receiver system\n 3. fixed ECORR per backend/receiver system\n 4. Red noise modeled as a power-law with 30 sampling frequencies\n 5. Linear timing model.\n\n global:\n 1. Monopole spatially correlated signal modeled with PSD.\n Default PSD is powerlaw. Available options\n ['powerlaw', 'turnover', 'spectrum']\n 2. Optional physical ephemeris modeling.\n\n :param psd:\n PSD to use for common red noise signal. Available options\n are ['powerlaw', 'turnover' 'spectrum']. 'powerlaw' is default\n value.\n :param noisedict:\n Dictionary of pulsar noise properties. Can provide manually,\n or the code will attempt to find it.\n :param white_vary:\n boolean for varying white noise or keeping fixed.\n :param gamma_common:\n Fixed common red process spectral index value. By default we\n vary the spectral index over the range [0, 7].\n :param upper_limit:\n Perform upper limit on common red noise amplitude. By default\n this is set to False. Note that when perfoming upper limits it\n is recommended that the spectral index also be fixed to a specific\n value.\n :param bayesephem:\n Include BayesEphem model. Set to False by default\n :param be_type:\n orbel, orbel-v2, setIII\n :param is_wideband:\n Whether input TOAs are wideband TOAs; will exclude ecorr from the white\n noise model.\n :param use_dmdata: whether to use DM data (WidebandTimingModel) if\n is_wideband.\n \"\"\"\n\n amp_prior = 'uniform' if upper_limit else 'log-uniform'\n\n # find the maximum time span to set GW frequency sampling\n Tspan = model_utils.get_tspan(psrs)\n\n # red noise\n s = red_noise_block(prior=amp_prior, Tspan=Tspan, components=components)\n\n # monopole\n s += common_red_noise_block(psd=psd, prior=amp_prior, Tspan=Tspan,\n components=components, gamma_val=gamma_common,\n orf='monopole', name='monopole', pshift=pshift)\n\n # ephemeris model\n if bayesephem:\n s += deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True,\n model=be_type)\n\n # timing model\n if (is_wideband and use_dmdata):\n dmjump = parameter.Constant()\n if white_vary:\n dmefac = parameter.Uniform(pmin=0.1, pmax=10.0)\n log10_dmequad = parameter.Uniform(pmin=-7.0, pmax=0.0)\n #dmjump = parameter.Uniform(pmin=-0.005, pmax=0.005)\n else:\n dmefac = parameter.Constant()\n log10_dmequad = parameter.Constant()\n #dmjump = parameter.Constant()\n s += gp_signals.WidebandTimingModel(dmefac=dmefac,\n log10_dmequad=log10_dmequad, dmjump=dmjump,\n dmefac_selection=selections.Selection(selections.by_backend),\n log10_dmequad_selection=selections.Selection(\n selections.by_backend),\n dmjump_selection=selections.Selection(selections.by_frontend))\n else:\n s += gp_signals.TimingModel()\n\n # adding white-noise, and acting on psr objects\n models = []\n for p in psrs:\n if 'NANOGrav' in p.flags['pta'] and not is_wideband:\n s2 = s + white_noise_block(vary=white_vary, inc_ecorr=True,\n select=select)\n models.append(s2(p))\n else:\n s3 = s + white_noise_block(vary=white_vary, inc_ecorr=False,\n select=select)\n models.append(s3(p))\n\n # set up PTA\n pta = signal_base.PTA(models)\n\n # set white noise parameters\n if not white_vary or (is_wideband and use_dmdata):\n if noisedict is None:\n print('No noise dictionary provided!...')\n else:\n noisedict = noisedict\n pta.set_default_params(noisedict)\n\n return pta\n\n\ndef model_3a(psrs, psd='powerlaw', noisedict=None, white_vary=False,\n components=30, n_rnfreqs = None, n_gwbfreqs=None,\n gamma_common=None, delta_common=None, upper_limit=False,\n bayesephem=False, be_type='orbel', is_wideband=False,\n use_dmdata=False, select='backend',\n correlationsonly=False,\n pshift=False, pseed=None, psr_models=False):\n \"\"\"\n Reads in list of enterprise Pulsar instance and returns a PTA\n instantiated with model 3A from the analysis paper:\n\n per pulsar:\n 1. fixed EFAC per backend/receiver system\n 2. fixed EQUAD per backend/receiver system\n 3. fixed ECORR per backend/receiver system\n 4. Red noise modeled as a power-law with 30 sampling frequencies\n 5. Linear timing model.\n\n global:\n 1. GWB with HD correlations modeled with user defined PSD with\n 30 sampling frequencies. Available PSDs are\n ['powerlaw', 'turnover' 'spectrum']\n 2. Optional physical ephemeris modeling.\n\n :param psd:\n PSD to use for common red noise signal. Available options\n are ['powerlaw', 'turnover' 'spectrum'] 'powerlaw' is default\n value.\n :param noisedict:\n Dictionary of pulsar noise properties. Can provide manually,\n or the code will attempt to find it.\n :param white_vary:\n boolean for varying white noise or keeping fixed.\n :param gamma_common:\n Fixed common red process spectral index value. By default we\n vary the spectral index over the range [0, 7].\n :param gamma_common:\n Fixed common red process spectral index value for higher frequencies in\n broken power law model.\n By default we vary the spectral index over the range [0, 7].\n :param upper_limit:\n Perform upper limit on common red noise amplitude. By default\n this is set to False. Note that when perfoming upper limits it\n is recommended that the spectral index also be fixed to a specific\n value.\n :param bayesephem:\n Include BayesEphem model. Set to False by default\n :param be_type:\n orbel, orbel-v2, setIII\n :param is_wideband:\n Whether input TOAs are wideband TOAs; will exclude ecorr from the white\n noise model.\n :param use_dmdata: whether to use DM data (WidebandTimingModel) if\n is_wideband.\n :param correlationsonly:\n Give infinite power (well, 1e40) to pulsar red noise, effectively\n canceling out also GW diagonal terms\n :param pshift:\n Option to use a random phase shift in design matrix. For testing the\n null hypothesis.\n :param pseed:\n Option to provide a seed for the random phase shift.\n :param psr_models:\n Return list of psr models rather than signal_base.PTA object.\n \"\"\"\n\n amp_prior = 'uniform' if upper_limit else 'log-uniform'\n\n # find the maximum time span to set GW frequency sampling\n Tspan = model_utils.get_tspan(psrs)\n\n if n_gwbfreqs is None:\n n_gwbfreqs = components\n\n if n_rnfreqs is None:\n n_rnfreqs = components\n # red noise\n s = red_noise_block(psd='infinitepower' if correlationsonly else 'powerlaw',\n prior=amp_prior,\n Tspan=Tspan, components=n_rnfreqs)\n\n # common red noise block\n s += common_red_noise_block(psd=psd, prior=amp_prior, Tspan=Tspan,\n components=n_gwbfreqs, gamma_val=gamma_common,\n delta_val=delta_common,\n orf='hd', name='gw', pshift=pshift, pseed=pseed)\n\n # ephemeris model\n if bayesephem:\n s += deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True,\n model=be_type)\n\n # timing model\n if (is_wideband and use_dmdata):\n dmjump = parameter.Constant()\n if white_vary:\n dmefac = parameter.Uniform(pmin=0.1, pmax=10.0)\n log10_dmequad = parameter.Uniform(pmin=-7.0, pmax=0.0)\n #dmjump = parameter.Uniform(pmin=-0.005, pmax=0.005)\n else:\n dmefac = parameter.Constant()\n log10_dmequad = parameter.Constant()\n #dmjump = parameter.Constant()\n s += gp_signals.WidebandTimingModel(dmefac=dmefac,\n log10_dmequad=log10_dmequad, dmjump=dmjump,\n dmefac_selection=selections.Selection(selections.by_backend),\n log10_dmequad_selection=selections.Selection(\n selections.by_backend),\n dmjump_selection=selections.Selection(selections.by_frontend))\n else:\n s += gp_signals.TimingModel()\n\n # adding white-noise, and acting on psr objects\n models = []\n for p in psrs:\n if 'NANOGrav' in p.flags['pta'] and not is_wideband:\n s2 = s + white_noise_block(vary=white_vary, inc_ecorr=True,\n select=select)\n models.append(s2(p))\n else:\n s3 = s + white_noise_block(vary=white_vary, inc_ecorr=False,\n select=select)\n models.append(s3(p))\n\n if psr_models:\n return models\n else:\n # set up PTA\n pta = signal_base.PTA(models)\n\n # set white noise parameters\n if not white_vary or (is_wideband and use_dmdata):\n if noisedict is None:\n print('No noise dictionary provided!...')\n else:\n noisedict = noisedict\n pta.set_default_params(noisedict)\n\n return pta\n\n\ndef model_3b(psrs, psd='powerlaw', noisedict=None, white_vary=False,\n components=30, gamma_common=None, upper_limit=False,\n bayesephem=False, be_type='orbel', is_wideband=False,\n use_dmdata=False, select='backend'):\n \"\"\"\n Reads in list of enterprise Pulsar instance and returns a PTA\n instantiated with model 3B from the analysis paper:\n\n per pulsar:\n 1. fixed EFAC per backend/receiver system\n 2. fixed EQUAD per backend/receiver system\n 3. fixed ECORR per backend/receiver system\n 4. Red noise modeled as a power-law with 30 sampling frequencies\n 5. Linear timing model.\n\n global:\n 1. GWB with HD correlations modeled with user defined PSD with\n 30 sampling frequencies. Available PSDs are\n ['powerlaw', 'turnover' 'spectrum']\n 2. Dipole signal modeled with user defined PSD with\n 30 sampling frequencies. Available PSDs are\n ['powerlaw', 'turnover' 'spectrum']\n 3. Optional physical ephemeris modeling.\n\n :param psd:\n PSD to use for common red noise signal. Available options\n are ['powerlaw', 'turnover' 'spectrum'] 'powerlaw' is default\n value.\n :param noisedict:\n Dictionary of pulsar noise properties. Can provide manually,\n or the code will attempt to find it.\n :param white_vary:\n boolean for varying white noise or keeping fixed.\n :param gamma_common:\n Fixed common red process spectral index value. By default we\n vary the spectral index over the range [0, 7].\n :param upper_limit:\n Perform upper limit on common red noise amplitude. By default\n this is set to False. Note that when perfoming upper limits it\n is recommended that the spectral index also be fixed to a specific\n value.\n :param bayesephem:\n Include BayesEphem model. Set to False by default\n :param be_type:\n orbel, orbel-v2, setIII\n :param is_wideband:\n Whether input TOAs are wideband TOAs; will exclude ecorr from the white\n noise model.\n :param use_dmdata: whether to use DM data (WidebandTimingModel) if\n is_wideband.\n \"\"\"\n\n amp_prior = 'uniform' if upper_limit else 'log-uniform'\n\n # find the maximum time span to set GW frequency sampling\n Tspan = model_utils.get_tspan(psrs)\n\n # red noise\n s = red_noise_block(prior=amp_prior, Tspan=Tspan, components=components)\n\n # common red noise block\n s += common_red_noise_block(psd=psd, prior=amp_prior, Tspan=Tspan,\n components=components, gamma_val=gamma_common,\n orf='hd', name='gw')\n\n # dipole\n s += common_red_noise_block(psd=psd, prior=amp_prior, Tspan=Tspan,\n components=components, gamma_val=gamma_common,\n orf='dipole', name='dipole')\n\n # ephemeris model\n if bayesephem:\n s += deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True,\n model=be_type)\n\n # timing model\n if (is_wideband and use_dmdata):\n dmjump = parameter.Constant()\n if white_vary:\n dmefac = parameter.Uniform(pmin=0.1, pmax=10.0)\n log10_dmequad = parameter.Uniform(pmin=-7.0, pmax=0.0)\n #dmjump = parameter.Uniform(pmin=-0.005, pmax=0.005)\n else:\n dmefac = parameter.Constant()\n log10_dmequad = parameter.Constant()\n #dmjump = parameter.Constant()\n s += gp_signals.WidebandTimingModel(dmefac=dmefac,\n log10_dmequad=log10_dmequad, dmjump=dmjump,\n dmefac_selection=selections.Selection(selections.by_backend),\n log10_dmequad_selection=selections.Selection(\n selections.by_backend),\n dmjump_selection=selections.Selection(selections.by_frontend))\n else:\n s += gp_signals.TimingModel()\n\n # adding white-noise, and acting on psr objects\n models = []\n for p in psrs:\n if 'NANOGrav' in p.flags['pta'] and not is_wideband:\n s2 = s + white_noise_block(vary=white_vary, inc_ecorr=True,\n select=select)\n models.append(s2(p))\n else:\n s3 = s + white_noise_block(vary=white_vary, inc_ecorr=False,\n select=select)\n models.append(s3(p))\n\n # set up PTA\n pta = signal_base.PTA(models)\n\n # set white noise parameters\n if not white_vary or (is_wideband and use_dmdata):\n if noisedict is None:\n print('No noise dictionary provided!...')\n else:\n noisedict = noisedict\n pta.set_default_params(noisedict)\n\n return pta\n\n\ndef model_3c(psrs, psd='powerlaw', noisedict=None, white_vary=False,\n components=30, gamma_common=None, upper_limit=False,\n bayesephem=False, be_type='orbel', is_wideband=False,\n use_dmdata=False, select='backend'):\n \"\"\"\n Reads in list of enterprise Pulsar instance and returns a PTA\n instantiated with model 3C from the analysis paper:\n\n per pulsar:\n 1. fixed EFAC per backend/receiver system\n 2. fixed EQUAD per backend/receiver system\n 3. fixed ECORR per backend/receiver system\n 4. Red noise modeled as a power-law with 30 sampling frequencies\n 5. Linear timing model.\n\n global:\n 1. GWB with HD correlations modeled with user defined PSD with\n 30 sampling frequencies. Available PSDs are\n ['powerlaw', 'turnover' 'spectrum']\n 2. Dipole signal modeled with user defined PSD with\n 30 sampling frequencies. Available PSDs are\n ['powerlaw', 'turnover' 'spectrum']\n 3. Monopole signal modeled with user defined PSD with\n 30 sampling frequencies. Available PSDs are\n ['powerlaw', 'turnover' 'spectrum']\n 4. Optional physical ephemeris modeling.\n\n :param psd:\n PSD to use for common red noise signal. Available options\n are ['powerlaw', 'turnover' 'spectrum'] 'powerlaw' is default\n value.\n :param noisedict:\n Dictionary of pulsar noise properties. Can provide manually,\n or the code will attempt to find it.\n :param white_vary:\n boolean for varying white noise or keeping fixed.\n :param gamma_common:\n Fixed common red process spectral index value. By default we\n vary the spectral index over the range [0, 7].\n :param upper_limit:\n Perform upper limit on common red noise amplitude. By default\n this is set to False. Note that when perfoming upper limits it\n is recommended that the spectral index also be fixed to a specific\n value.\n :param bayesephem:\n Include BayesEphem model. Set to False by default\n :param be_type:\n orbel, orbel-v2, setIII\n :param is_wideband:\n Whether input TOAs are wideband TOAs; will exclude ecorr from the white\n noise model.\n :param use_dmdata: whether to use DM data (WidebandTimingModel) if\n is_wideband.\n \"\"\"\n\n amp_prior = 'uniform' if upper_limit else 'log-uniform'\n\n # find the maximum time span to set GW frequency sampling\n Tspan = model_utils.get_tspan(psrs)\n\n # red noise\n s = red_noise_block(prior=amp_prior, Tspan=Tspan, components=components)\n\n # common red noise block\n s += common_red_noise_block(psd=psd, prior=amp_prior, Tspan=Tspan,\n components=components, gamma_val=gamma_common,\n orf='hd', name='gw')\n\n # dipole\n s += common_red_noise_block(psd=psd, prior=amp_prior, Tspan=Tspan,\n components=components, gamma_val=gamma_common,\n orf='dipole', name='dipole')\n\n # monopole\n s += common_red_noise_block(psd=psd, prior=amp_prior, Tspan=Tspan,\n components=components, gamma_val=gamma_common,\n orf='monopole', name='monopole')\n\n # ephemeris model\n if bayesephem:\n s += deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True,\n model=be_type)\n\n # timing model\n if is_wideband and use_dmdata:\n dmjump = parameter.Constant()\n if white_vary:\n dmefac = parameter.Uniform(pmin=0.1, pmax=10.0)\n log10_dmequad = parameter.Uniform(pmin=-7.0, pmax=0.0)\n #dmjump = parameter.Uniform(pmin=-0.005, pmax=0.005)\n else:\n dmefac = parameter.Constant()\n log10_dmequad = parameter.Constant()\n #dmjump = parameter.Constant()\n s += gp_signals.WidebandTimingModel(dmefac=dmefac,\n log10_dmequad=log10_dmequad, dmjump=dmjump,\n dmefac_selection=selections.Selection(selections.by_backend),\n log10_dmequad_selection=selections.Selection(\n selections.by_backend),\n dmjump_selection=selections.Selection(selections.by_frontend))\n else:\n s += gp_signals.TimingModel()\n\n # adding white-noise, and acting on psr objects\n models = []\n for p in psrs:\n if 'NANOGrav' in p.flags['pta'] and not is_wideband:\n s2 = s + white_noise_block(vary=white_vary, inc_ecorr=True,\n select=select)\n models.append(s2(p))\n else:\n s3 = s + white_noise_block(vary=white_vary, inc_ecorr=False,\n select=select)\n models.append(s3(p))\n\n # set up PTA\n pta = signal_base.PTA(models)\n\n # set white noise parameters\n if not white_vary or (is_wideband and use_dmdata):\n if noisedict is None:\n print('No noise dictionary provided!...')\n else:\n noisedict = noisedict\n pta.set_default_params(noisedict)\n\n return pta\n\n\ndef model_3d(psrs, psd='powerlaw', noisedict=None, white_vary=False,\n components=30, gamma_common=None, upper_limit=False,\n bayesephem=False, be_type='orbel', is_wideband=False,\n use_dmdata=False, select='backend'):\n \"\"\"\n Reads in list of enterprise Pulsar instance and returns a PTA\n instantiated with model 3D from the analysis paper:\n\n per pulsar:\n 1. fixed EFAC per backend/receiver system\n 2. fixed EQUAD per backend/receiver system\n 3. fixed ECORR per backend/receiver system\n 4. Red noise modeled as a power-law with 30 sampling frequencies\n 5. Linear timing model.\n\n global:\n 1. GWB with HD correlations modeled with user defined PSD with\n 30 sampling frequencies. Available PSDs are\n ['powerlaw', 'turnover' 'spectrum']\n 2. Monopole signal modeled with user defined PSD with\n 30 sampling frequencies. Available PSDs are\n ['powerlaw', 'turnover' 'spectrum']\n 3. Optional physical ephemeris modeling.\n\n :param psd:\n PSD to use for common red noise signal. Available options\n are ['powerlaw', 'turnover' 'spectrum'] 'powerlaw' is default\n value.\n :param noisedict:\n Dictionary of pulsar noise properties. Can provide manually,\n or the code will attempt to find it.\n :param white_vary:\n boolean for varying white noise or keeping fixed.\n :param gamma_common:\n Fixed common red process spectral index value. By default we\n vary the spectral index over the range [0, 7].\n :param upper_limit:\n Perform upper limit on common red noise amplitude. By default\n this is set to False. Note that when perfoming upper limits it\n is recommended that the spectral index also be fixed to a specific\n value.\n :param bayesephem:\n Include BayesEphem model. Set to False by default\n :param be_type:\n orbel, orbel-v2, setIII\n :param is_wideband:\n Whether input TOAs are wideband TOAs; will exclude ecorr from the white\n noise model.\n :param use_dmdata: whether to use DM data (WidebandTimingModel) if\n is_wideband.\n \"\"\"\n\n amp_prior = 'uniform' if upper_limit else 'log-uniform'\n\n # find the maximum time span to set GW frequency sampling\n Tspan = model_utils.get_tspan(psrs)\n\n # red noise\n s = red_noise_block(prior=amp_prior, Tspan=Tspan, components=components)\n\n # common red noise block\n s += common_red_noise_block(psd=psd, prior=amp_prior, Tspan=Tspan,\n components=components, gamma_val=gamma_common,\n orf='hd', name='gw')\n\n # monopole\n s += common_red_noise_block(psd=psd, prior=amp_prior, Tspan=Tspan,\n components=components, gamma_val=gamma_common,\n orf='monopole', name='monopole')\n\n # ephemeris model\n if bayesephem:\n s += deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True,\n model=be_type)\n\n # timing model\n if (is_wideband and use_dmdata):\n dmjump = parameter.Constant()\n if white_vary:\n dmefac = parameter.Uniform(pmin=0.1, pmax=10.0)\n log10_dmequad = parameter.Uniform(pmin=-7.0, pmax=0.0)\n #dmjump = parameter.Uniform(pmin=-0.005, pmax=0.005)\n else:\n dmefac = parameter.Constant()\n log10_dmequad = parameter.Constant()\n #dmjump = parameter.Constant()\n s += gp_signals.WidebandTimingModel(dmefac=dmefac,\n log10_dmequad=log10_dmequad, dmjump=dmjump,\n dmefac_selection=selections.Selection(selections.by_backend),\n log10_dmequad_selection=selections.Selection(\n selections.by_backend),\n dmjump_selection=selections.Selection(selections.by_frontend))\n else:\n s += gp_signals.TimingModel()\n\n # adding white-noise, and acting on psr objects\n models = []\n for p in psrs:\n if 'NANOGrav' in p.flags['pta'] and not is_wideband:\n s2 = s + white_noise_block(vary=white_vary, inc_ecorr=True,\n select=select)\n models.append(s2(p))\n else:\n s3 = s + white_noise_block(vary=white_vary, inc_ecorr=False,\n select=select)\n models.append(s3(p))\n\n # set up PTA\n pta = signal_base.PTA(models)\n\n # set white noise parameters\n if not white_vary or (is_wideband and use_dmdata):\n if noisedict is None:\n print('No noise dictionary provided!...')\n else:\n noisedict = noisedict\n pta.set_default_params(noisedict)\n\n return pta\n\n\ndef model_2a_drop_be(psrs, psd='powerlaw', noisedict=None, white_vary=False,\n components=30, gamma_common=None, upper_limit=False,\n is_wideband=False, use_dmdata=False, k_threshold=0.5,\n pshift=False):\n \"\"\"\n Reads in list of enterprise Pulsar instance and returns a PTA\n instantiated with model 2A from the analysis paper:\n\n per pulsar:\n 1. fixed EFAC per backend/receiver system\n 2. fixed EQUAD per backend/receiver system\n 3. fixed ECORR per backend/receiver system\n 4. Red noise modeled as a power-law with 30 sampling frequencies\n 5. Linear timing model.\n\n global:\n 1.Common red noise modeled with user defined PSD with\n 30 sampling frequencies. Available PSDs are\n ['powerlaw', 'turnover' 'spectrum']\n 2. Optional physical ephemeris modeling.\n\n :param psd:\n PSD to use for common red noise signal. Available options\n are ['powerlaw', 'turnover' 'spectrum']. 'powerlaw' is default\n value.\n :param noisedict:\n Dictionary of pulsar noise properties. Can provide manually,\n or the code will attempt to find it.\n :param white_vary:\n boolean for varying white noise or keeping fixed.\n :param gamma_common:\n Fixed common red process spectral index value. By default we\n vary the spectral index over the range [0, 7].\n :param upper_limit:\n Perform upper limit on common red noise amplitude. By default\n this is set to False. Note that when perfoming upper limits it\n is recommended that the spectral index also be fixed to a specific\n value.\n :param is_wideband:\n Whether input TOAs are wideband TOAs; will exclude ecorr from the white\n noise model.\n :param use_dmdata: whether to use DM data (WidebandTimingModel) if\n is_wideband.\n :param k_threshold:\n Define threshold for dropout parameter 'k'.\n \"\"\"\n\n amp_prior = 'uniform' if upper_limit else 'log-uniform'\n\n # find the maximum time span to set GW frequency sampling\n Tspan = model_utils.get_tspan(psrs)\n\n # red noise\n s = red_noise_block(prior=amp_prior, Tspan=Tspan, components=components)\n\n # common red noise block\n s += common_red_noise_block(psd=psd, prior=amp_prior, Tspan=Tspan,\n components=components, gamma_val=gamma_common,\n name='gw', pshift=pshift)\n\n # ephemeris model\n s += do.Dropout_PhysicalEphemerisSignal(use_epoch_toas=True,\n k_threshold=k_threshold)\n\n # timing model\n if (is_wideband and use_dmdata):\n dmjump = parameter.Constant()\n if white_vary:\n dmefac = parameter.Uniform(pmin=0.1, pmax=10.0)\n log10_dmequad = parameter.Uniform(pmin=-7.0, pmax=0.0)\n #dmjump = parameter.Uniform(pmin=-0.005, pmax=0.005)\n else:\n dmefac = parameter.Constant()\n log10_dmequad = parameter.Constant()\n #dmjump = parameter.Constant()\n s += gp_signals.WidebandTimingModel(dmefac=dmefac,\n log10_dmequad=log10_dmequad, dmjump=dmjump,\n dmefac_selection=selections.Selection(selections.by_backend),\n log10_dmequad_selection=selections.Selection(\n selections.by_backend),\n dmjump_selection=selections.Selection(selections.by_frontend))\n else:\n s += gp_signals.TimingModel()\n\n # adding white-noise, and acting on psr objects\n models = []\n for p in psrs:\n if 'NANOGrav' in p.flags['pta'] and not is_wideband:\n s2 = s + white_noise_block(vary=white_vary, inc_ecorr=True)\n models.append(s2(p))\n else:\n s3 = s + white_noise_block(vary=white_vary, inc_ecorr=False)\n models.append(s3(p))\n\n # set up PTA\n pta = signal_base.PTA(models)\n\n # set white noise parameters\n if not white_vary or (is_wideband and use_dmdata):\n if noisedict is None:\n print('No noise dictionary provided!...')\n else:\n noisedict = noisedict\n pta.set_default_params(noisedict)\n\n return pta\n\n\ndef model_2a_drop_crn(psrs, psd='powerlaw', noisedict=None, white_vary=False,\n components=30, gamma_common=None, upper_limit=False,\n bayesephem=False, is_wideband=False, use_dmdata=False,\n k_threshold=0.5, pshift=False):\n \"\"\"\n Reads in list of enterprise Pulsar instance and returns a PTA\n instantiated with model 2A from the analysis paper:\n\n per pulsar:\n 1. fixed EFAC per backend/receiver system\n 2. fixed EQUAD per backend/receiver system\n 3. fixed ECORR per backend/receiver system\n 4. Red noise modeled as a power-law with 30 sampling frequencies\n 5. Linear timing model.\n\n global:\n 1.Common red noise modeled with user defined PSD with\n 30 sampling frequencies. Available PSDs are\n ['powerlaw', 'turnover' 'spectrum']\n 2. Optional physical ephemeris modeling.\n\n :param psd:\n PSD to use for common red noise signal. Available options\n are ['powerlaw', 'turnover' 'spectrum']. 'powerlaw' is default\n value.\n :param noisedict:\n Dictionary of pulsar noise properties. Can provide manually,\n or the code will attempt to find it.\n :param white_vary:\n boolean for varying white noise or keeping fixed.\n :param gamma_common:\n Fixed common red process spectral index value. By default we\n vary the spectral index over the range [0, 7].\n :param upper_limit:\n Perform upper limit on common red noise amplitude. By default\n this is set to False. Note that when perfoming upper limits it\n is recommended that the spectral index also be fixed to a specific\n value.\n :param bayesephem:\n Include BayesEphem model. Set to False by default\n :param is_wideband:\n Whether input TOAs are wideband TOAs; will exclude ecorr from the white\n noise model.\n :param use_dmdata: whether to use DM data (WidebandTimingModel) if\n is_wideband.\n \"\"\"\n\n amp_prior = 'uniform' if upper_limit else 'log-uniform'\n\n # find the maximum time span to set GW frequency sampling\n Tspan = model_utils.get_tspan(psrs)\n\n # red noise\n s = red_noise_block(prior=amp_prior, Tspan=Tspan, components=components)\n\n # common red noise block\n amp_name = '{}_log10_A'.format('gw')\n if amp_prior == 'uniform':\n log10_Agw = parameter.LinearExp(-18, -11)(amp_name)\n elif amp_prior == 'log-uniform' and gamma_common is not None:\n if np.abs(gamma_common - 4.33) < 0.1:\n log10_Agw = parameter.Uniform(-18, -14)(amp_name)\n else:\n log10_Agw = parameter.Uniform(-18, -11)(amp_name)\n else:\n log10_Agw = parameter.Uniform(-18, -11)(amp_name)\n\n gam_name = '{}_gamma'.format('gw')\n if gamma_common is not None:\n gamma_gw = parameter.Constant(gamma_common)(gam_name)\n else:\n gamma_gw = parameter.Uniform(0, 7)(gam_name)\n\n k_drop = parameter.Uniform(0.0, 1.0) # per-pulsar\n\n drop_pl = do.dropout_powerlaw(log10_A=log10_Agw, gamma=gamma_gw,\n k_drop=k_drop, k_threshold=k_threshold)\n crn = gp_signals.FourierBasisGP(drop_pl, components=components,\n Tspan=Tspan, name='gw', pshift=pshift)\n s += crn\n\n # ephemeris model\n s += do.Dropout_PhysicalEphemerisSignal(use_epoch_toas=True)\n\n # timing model\n if (is_wideband and use_dmdata):\n dmjump = parameter.Constant()\n if white_vary:\n dmefac = parameter.Uniform(pmin=0.1, pmax=10.0)\n log10_dmequad = parameter.Uniform(pmin=-7.0, pmax=0.0)\n #dmjump = parameter.Uniform(pmin=-0.005, pmax=0.005)\n else:\n dmefac = parameter.Constant()\n log10_dmequad = parameter.Constant()\n #dmjump = parameter.Constant()\n s += gp_signals.WidebandTimingModel(dmefac=dmefac,\n log10_dmequad=log10_dmequad, dmjump=dmjump,\n dmefac_selection=selections.Selection(selections.by_backend),\n log10_dmequad_selection=selections.Selection(\n selections.by_backend),\n dmjump_selection=selections.Selection(selections.by_frontend))\n else:\n s += gp_signals.TimingModel()\n\n # adding white-noise, and acting on psr objects\n models = []\n for p in psrs:\n if 'NANOGrav' in p.flags['pta'] and not is_wideband:\n s2 = s + white_noise_block(vary=white_vary, inc_ecorr=True)\n models.append(s2(p))\n else:\n s3 = s + white_noise_block(vary=white_vary, inc_ecorr=False)\n models.append(s3(p))\n\n # set up PTA\n pta = signal_base.PTA(models)\n\n # set white noise parameters\n if not white_vary or (is_wideband and use_dmdata):\n if noisedict is None:\n print('No noise dictionary provided!...')\n else:\n noisedict = noisedict\n pta.set_default_params(noisedict)\n\n return pta\n\n\n# Does not yet work with IPTA datasets due to white-noise modeling issues.\ndef model_chromatic(psrs, psd='powerlaw', noisedict=None, white_vary=False,\n components=30, gamma_common=None, upper_limit=False,\n bayesephem=False, is_wideband=False, use_dmdata=False,\n pshift=False, idx=4, chromatic_psd='powerlaw',\n c_psrs=['J1713+0747']):\n \"\"\"\n Reads in list of enterprise Pulsar instance and returns a PTA\n instantiated with model 2A from the analysis paper + additional\n chromatic noise for given pulsars\n\n per pulsar:\n 1. fixed EFAC per backend/receiver system\n 2. fixed EQUAD per backend/receiver system\n 3. fixed ECORR per backend/receiver system\n 4. Red noise modeled as a power-law with 30 sampling frequencies\n 5. Linear timing model.\n 6. Chromatic noise for given pulsar list\n\n global:\n 1.Common red noise modeled with user defined PSD with\n 30 sampling frequencies. Available PSDs are\n ['powerlaw', 'turnover' 'spectrum']\n 2. Optional physical ephemeris modeling.\n\n :param psd:\n PSD to use for common red noise signal. Available options\n are ['powerlaw', 'turnover' 'spectrum']. 'powerlaw' is default\n value.\n :param noisedict:\n Dictionary of pulsar noise properties. Can provide manually,\n or the code will attempt to find it.\n :param white_vary:\n boolean for varying white noise or keeping fixed.\n :param gamma_common:\n Fixed common red process spectral index value. By default we\n vary the spectral index over the range [0, 7].\n :param upper_limit:\n Perform upper limit on common red noise amplitude. By default\n this is set to False. Note that when perfoming upper limits it\n is recommended that the spectral index also be fixed to a specific\n value.\n :param bayesephem:\n Include BayesEphem model. Set to False by default\n :param is_wideband:\n Whether input TOAs are wideband TOAs; will exclude ecorr from the white\n noise model.\n :param use_dmdata: whether to use DM data (WidebandTimingModel) if\n is_wideband.\n :param idx:\n Index of chromatic process (i.e DM is 2, scattering would be 4). If\n set to `vary` then will vary from 0 - 6 (This will be VERY slow!)\n :param chromatic_psd:\n PSD to use for chromatic noise. Available options\n are ['powerlaw', 'turnover' 'spectrum']. 'powerlaw' is default\n value.\n :param c_psrs:\n List of pulsars to use chromatic noise. 'all' will use all pulsars\n \"\"\"\n\n amp_prior = 'uniform' if upper_limit else 'log-uniform'\n\n # find the maximum time span to set GW frequency sampling\n Tspan = model_utils.get_tspan(psrs)\n\n # white noise\n s = white_noise_block(vary=white_vary, inc_ecorr=not is_wideband)\n\n # red noise\n s += red_noise_block(prior=amp_prior, Tspan=Tspan, components=components)\n\n # common red noise block\n s += common_red_noise_block(psd=psd, prior=amp_prior, Tspan=Tspan,\n components=components, gamma_val=gamma_common,\n name='gw', pshift=pshift)\n\n # ephemeris model\n if bayesephem:\n s += deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True)\n\n # timing model\n if (is_wideband and use_dmdata):\n dmjump = parameter.Constant()\n if white_vary:\n dmefac = parameter.Uniform(pmin=0.1, pmax=10.0)\n log10_dmequad = parameter.Uniform(pmin=-7.0, pmax=0.0)\n #dmjump = parameter.Uniform(pmin=-0.005, pmax=0.005)\n else:\n dmefac = parameter.Constant()\n log10_dmequad = parameter.Constant()\n #dmjump = parameter.Constant()\n s += gp_signals.WidebandTimingModel(dmefac=dmefac,\n log10_dmequad=log10_dmequad, dmjump=dmjump,\n dmefac_selection=selections.Selection(selections.by_backend),\n log10_dmequad_selection=selections.Selection(\n selections.by_backend),\n dmjump_selection=selections.Selection(selections.by_frontend))\n else:\n s += gp_signals.TimingModel()\n\n # chromatic noise\n sc = chromatic_noise_block(psd=chromatic_psd, idx=idx)\n if c_psrs == 'all':\n s += sc\n models = [s(psr) for psr in psrs]\n elif len(c_psrs) > 0:\n models = []\n for psr in psrs:\n if psr.name in c_psrs:\n print('Adding chromatic model to PSR {}'.format(psr.name))\n snew = s + sc\n models.append(snew(psr))\n else:\n models.append(s(psr))\n\n # set up PTA\n pta = signal_base.PTA(models)\n\n # set white noise parameters\n if not white_vary or (is_wideband and use_dmdata):\n if noisedict is None:\n print('No noise dictionary provided!...')\n else:\n noisedict = noisedict\n pta.set_default_params(noisedict)\n\n return pta\n\n\ndef model_bwm(psrs, noisedict=None, white_vary=False, tm_svd=False,\n Tmin_bwm=None, Tmax_bwm=None, skyloc=None,\n red_psd='powerlaw', components=30,\n dm_var=False, dm_psd='powerlaw', dm_annual=False,\n upper_limit=False, bayesephem=False, is_wideband=False,\n use_dmdata=False):\n \"\"\"\n Reads in list of enterprise Pulsar instance and returns a PTA\n instantiated with BWM model:\n\n per pulsar:\n 1. fixed EFAC per backend/receiver system\n 2. fixed EQUAD per backend/receiver system\n 3. fixed ECORR per backend/receiver system (if NG channelized)\n 4. Red noise modeled by a specified psd\n 5. Linear timing model.\n 6. Optional DM-variation modeling\n global:\n 1. Deterministic GW burst with memory signal.\n 2. Optional physical ephemeris modeling.\n\n :param psrs:\n list of enterprise.Pulsar objects for PTA\n :param noisedict:\n Dictionary of pulsar noise properties for fixed white noise.\n Can provide manually, or the code will attempt to find it.\n :param white_vary:\n boolean for varying white noise or keeping fixed.\n :param tm_svd:\n boolean for svd-stabilised timing model design matrix\n :param Tmin_bwm:\n Min time to search for BWM (MJD). If omitted, uses first TOA.\n :param Tmax_bwm:\n Max time to search for BWM (MJD). If omitted, uses last TOA.\n :param skyloc:\n Fixed sky location of BWM signal search as [cos(theta), phi].\n Search over sky location if ``None`` given.\n :param red_psd:\n PSD to use for per pulsar red noise. Available options\n are ['powerlaw', 'turnover', tprocess, 'spectrum'].\n :param components:\n number of modes in Fourier domain processes (red noise, DM\n variations, etc)\n :param dm_var:\n include gaussian process DM variations\n :param dm_psd:\n power-spectral density for gp DM variations\n :param dm_annual:\n include a yearly period DM variation\n :param upper_limit:\n Perform upper limit on BWM amplitude. By default this is\n set to False for a 'detection' run.\n :param bayesephem:\n Include BayesEphem model.\n :param is_wideband:\n Whether input TOAs are wideband TOAs; will exclude ecorr from the white\n noise model.\n :param use_dmdata: whether to use DM data (WidebandTimingModel) if\n is_wideband.\n :return: instantiated enterprise.PTA object\n \"\"\"\n\n amp_prior = 'uniform' if upper_limit else 'log-uniform'\n\n # find the maximum time span to set frequency sampling\n tmin = np.min([p.toas.min() for p in psrs])\n tmax = np.max([p.toas.max() for p in psrs])\n Tspan = tmax - tmin\n\n if Tmin_bwm is None:\n Tmin_bwm = tmin/const.day\n if Tmax_bwm is None:\n Tmax_bwm = tmax/const.day\n\n # red noise\n s = red_noise_block(prior=amp_prior, psd=red_psd, Tspan=Tspan, components=components)\n\n # DM variations\n if dm_var:\n s += dm_noise_block(psd=dm_psd, prior=amp_prior, components=components,\n gamma_val=None)\n if dm_annual:\n s += chrom.dm_annual_signal()\n\n # DM exponential dip for J1713's DM event\n dmexp = chrom.dm_exponential_dip(tmin=54500, tmax=54900)\n\n # GW BWM signal block\n s += deterministic.bwm_block(Tmin_bwm, Tmax_bwm,\n amp_prior=amp_prior,\n skyloc=skyloc, name='bwm')\n\n # ephemeris model\n if bayesephem:\n s += deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True)\n\n # timing model\n if (is_wideband and use_dmdata):\n dmjump = parameter.Constant()\n if white_vary:\n dmefac = parameter.Uniform(pmin=0.1, pmax=10.0)\n log10_dmequad = parameter.Uniform(pmin=-7.0, pmax=0.0)\n #dmjump = parameter.Uniform(pmin=-0.005, pmax=0.005)\n else:\n dmefac = parameter.Constant()\n log10_dmequad = parameter.Constant()\n #dmjump = parameter.Constant()\n s += gp_signals.WidebandTimingModel(dmefac=dmefac,\n log10_dmequad=log10_dmequad, dmjump=dmjump,\n dmefac_selection=selections.Selection(selections.by_backend),\n log10_dmequad_selection=selections.Selection(\n selections.by_backend),\n dmjump_selection=selections.Selection(selections.by_frontend))\n else:\n s += gp_signals.TimingModel(use_svd=tm_svd)\n\n # adding white-noise, and acting on psr objects\n models = []\n for p in psrs:\n if 'NANOGrav' in p.flags['pta'] and not is_wideband:\n s2 = s + white_noise_block(vary=white_vary, inc_ecorr=True)\n if dm_var and 'J1713+0747' == p.name:\n s2 += dmexp\n models.append(s2(p))\n else:\n s3 = s + white_noise_block(vary=white_vary, inc_ecorr=False)\n if dm_var and 'J1713+0747' == p.name:\n s3 += dmexp\n models.append(s3(p))\n\n # set up PTA\n pta = signal_base.PTA(models)\n\n # set white noise parameters\n if not white_vary or (is_wideband and use_dmdata):\n if noisedict is None:\n print('No noise dictionary provided!...')\n else:\n noisedict = noisedict\n pta.set_default_params(noisedict)\n\n return pta\n\n\ndef model_cw(psrs, upper_limit=False, rn_psd='powerlaw', noisedict=None,\n white_vary=False, components=30, bayesephem=False, skyloc=None,\n log10_F=None, ecc=False, psrTerm=False, is_wideband=False,\n use_dmdata=False):\n \"\"\"\n Reads in list of enterprise Pulsar instance and returns a PTA\n instantiated with CW model:\n per pulsar:\n 1. fixed EFAC per backend/receiver system\n 2. fixed EQUAD per backend/receiver system\n 3. fixed ECORR per backend/receiver system\n 4. Red noise modeled as a power-law with 30 sampling frequencies\n 5. Linear timing model.\n global:\n 1. Deterministic CW signal.\n 2. Optional physical ephemeris modeling.\n :param upper_limit:\n Perform upper limit on common red noise amplitude. By default\n this is set to False. Note that when perfoming upper limits it\n is recommended that the spectral index also be fixed to a specific\n value.\n :param rn_psd:\n psd to use in red_noise_block()\n :param noisedict:\n Dictionary of pulsar noise properties. Can provide manually,\n or the code will attempt to find it.\n :param white_vary:\n boolean for varying white noise or keeping fixed.\n :param bayesephem:\n Include BayesEphem model. Set to False by default\n :param skyloc:\n Fixed sky location of CW signal search as [cos(theta), phi].\n Search over sky location if ``None`` given.\n :param log10_F:\n Fixed frequency of CW signal search.\n Search over frequency if ``None`` given.\n :param ecc:\n boolean or float\n if boolean: include/exclude eccentricity in search\n if float: use fixed eccentricity with eccentric model\n :psrTerm:\n boolean, include/exclude pulsar term in search\n :param is_wideband:\n Whether input TOAs are wideband TOAs; will exclude ecorr from the white\n noise model.\n :param use_dmdata: whether to use DM data (WidebandTimingModel) if\n is_wideband.\n \"\"\"\n\n amp_prior = 'uniform' if upper_limit else 'log-uniform'\n\n # find the maximum time span to set GW frequency sampling\n tmin = np.min([p.toas.min() for p in psrs])\n tmax = np.max([p.toas.max() for p in psrs])\n Tspan = tmax - tmin\n\n # red noise\n s = red_noise_block(prior=amp_prior,\n psd=rn_psd, Tspan=Tspan, components=components)\n\n # GW CW signal block\n if not ecc:\n s += deterministic.cw_block_circ(amp_prior=amp_prior,\n skyloc=skyloc,\n log10_fgw=log10_F,\n psrTerm=psrTerm, tref=tmin,\n name='cw')\n else:\n if type(ecc) is not float:\n ecc = None\n s += deterministic.cw_block_ecc(amp_prior=amp_prior,\n skyloc=skyloc, log10_F=log10_F,\n ecc=ecc, psrTerm=psrTerm,\n tref=tmin, name='cw')\n\n # ephemeris model\n if bayesephem:\n s += deterministic_signals.PhysicalEphemerisSignal(use_epoch_toas=True)\n\n # timing model\n if (is_wideband and use_dmdata):\n dmjump = parameter.Constant()\n if white_vary:\n dmefac = parameter.Uniform(pmin=0.1, pmax=10.0)\n log10_dmequad = parameter.Uniform(pmin=-7.0, pmax=0.0)\n #dmjump = parameter.Uniform(pmin=-0.005, pmax=0.005)\n else:\n dmefac = parameter.Constant()\n log10_dmequad = parameter.Constant()\n #dmjump = parameter.Constant()\n s += gp_signals.WidebandTimingModel(dmefac=dmefac,\n log10_dmequad=log10_dmequad, dmjump=dmjump,\n dmefac_selection=selections.Selection(selections.by_backend),\n log10_dmequad_selection=selections.Selection(\n selections.by_backend),\n dmjump_selection=selections.Selection(selections.by_frontend))\n else:\n s += gp_signals.TimingModel()\n\n # adding white-noise, and acting on psr objects\n models = []\n for p in psrs:\n if 'NANOGrav' in p.flags['pta'] and not is_wideband:\n s2 = s + white_noise_block(vary=white_vary, inc_ecorr=True,\n gp_ecorr=True)\n models.append(s2(p))\n else:\n s3 = s + white_noise_block(vary=white_vary, inc_ecorr=False)\n models.append(s3(p))\n\n # set up PTA\n pta = signal_base.PTA(models)\n\n # set white noise parameters\n if not white_vary or (is_wideband and use_dmdata):\n if noisedict is None:\n print('No noise dictionary provided!...')\n else:\n noisedict = noisedict\n pta.set_default_params(noisedict)\n\n return pta\n" ]
[ [ "numpy.abs" ] ]
SachitNayak/google-research
[ "2893b06a7a60f243be22a06f975f1eb85702d0fa" ]
[ "grouptesting/simulator.py" ]
[ "# coding=utf-8\n# Copyright 2020 The Google Research 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# Lint as: python3\n\"\"\"Simulates an environment to try Group testing Strategies.\"\"\"\n\nimport time\nfrom typing import Iterable, Union\n\nfrom absl import logging\nimport gin\nimport jax\nimport jax.numpy as np\nimport numpy as onp\nimport pandas as pd\n\nfrom grouptesting import metrics\nfrom grouptesting import policy as group_policy\nfrom grouptesting import state\nfrom grouptesting import wet_lab\nfrom grouptesting.samplers import loopy_belief_propagation as lbp\nfrom grouptesting.samplers import sequential_monte_carlo as smc\n\n\[email protected]\nclass Simulator(object):\n \"\"\"Runs Simulator to assess performance of group testing strategy.\n\n A simulator takes a wetlab that returns can test patients, a policy to select\n groups, a sampler to estimate the posterior probability plus some parameters,\n assesses the quality of a policy w.r.t. the conditions of the simulation.\n\n Attributes:\n metrics: the current metrics of the simulation.\n state: the current state.State of what have been tested in the past.\n sampler: the main sampler of the simulator, since it can have two samplers,\n one only used to compute marginals.\n marginal: the current best guess about the marginal probabilities of each\n patient.\n is_over: (bool) True if the simulation is over, else otherwise.\n \"\"\"\n\n def __init__(self,\n workdir = None,\n wetlab=wet_lab.WetLab(),\n policy=group_policy.Dorfman(),\n sampler=smc.SmcSampler(),\n cheap_sampler=lbp.LbpSampler(),\n num_simulations = 1,\n num_tests_per_cycle = 10,\n max_test_cycles = 5,\n max_group_size = 8,\n prior_specificity = 0.97,\n prior_sensitivity = 0.85,\n prior_infection_rate = 0.05,\n metrics_cls=metrics.Metrics,\n export_metrics_every = 5):\n self._wetlab = wetlab\n self._policy = policy\n self._samplers = [cheap_sampler, sampler]\n\n self._max_test_cycles = max_test_cycles\n self._num_simulations = num_simulations\n self.state = state.State(self._wetlab.num_patients,\n num_tests_per_cycle,\n max_group_size,\n prior_infection_rate,\n prior_specificity,\n prior_sensitivity)\n self.metrics = metrics_cls(\n workdir,\n self._num_simulations,\n self._max_test_cycles,\n self._wetlab.num_patients,\n self.state.num_tests_per_cycle)\n self._export_every = export_metrics_every\n\n def reset(self, rng):\n \"\"\"Resets all objects used in experiment.\"\"\"\n rngs = jax.random.split(rng, 2)\n self.state.reset()\n self._wetlab.reset(rngs[0])\n self._policy.reset()\n for sampler in self._samplers:\n sampler.reset()\n self._resample(rngs[1])\n\n @property\n def sampler(self):\n \"\"\"Returns the main sampler (index 0 is for marginals only).\"\"\"\n return self._samplers[-1]\n\n def run(self, rngkey=None):\n \"\"\"Runs sequentially all simulations.\"\"\"\n if self._num_simulations > 1 and self._wetlab.freeze_diseased:\n logging.warning(\"Running several simulations with the exact same group of\"\n \" patients. You might want to consider using the \"\n \"freeze_diseased=False parameter to the WetLab.\")\n rngkey = int(time.time()) if rngkey is None else rngkey\n rng = jax.random.PRNGKey(rngkey)\n for sim_idx in range(self._num_simulations):\n logging.debug(\"Starting experiment %s\", sim_idx)\n rng, sim_rng = jax.random.split(rng)\n self.run_simulation(sim_rng, sim_idx)\n\n for i in range(self.state.curr_cycle, self._max_test_cycles):\n self._on_iteration_end(sim_idx, i)\n\n if (sim_idx % self._export_every == 0 or\n sim_idx == self._num_simulations - 1):\n self.metrics.export()\n\n @property\n def is_over(self):\n \"\"\"Returns True if the simulation is over, False otherwise.\"\"\"\n return (self.state.curr_cycle >= self._max_test_cycles or\n self.state.all_cleared)\n\n def run_simulation(self, rng, sim_idx):\n \"\"\"Carries out up to max_test_cycles, or less if policy terminates.\"\"\"\n rng, reset_rng = jax.random.split(rng)\n self.reset(reset_rng)\n while not self.is_over:\n rng, cycle_rng = jax.random.split(rng)\n self.run_one_cycle(cycle_rng, sim_idx)\n\n def run_one_cycle(self, rng, sim_idx):\n \"\"\"The policy generates groups, wetlab tests them and the state is updated.\n\n At each testing cycle, policy is called to produce up to num_tests_per_cycle\n groups. They are then tested by wetlab, which produces (possibly noisy)\n test results. These tests are then used to update posterior estimates\n (both particle posterior approximation and marginal), that might\n be used by the policy upon the next cycle. Results (notably the marginal\n approximation, which helps keep track of who is likely to be infected) are\n logged on file.\n\n Args:\n rng: the random key.\n sim_idx: (int) the current index of the simulation.\n \"\"\"\n rngs = jax.random.split(rng, 3)\n new_groups = self.get_new_groups(rngs[0])\n new_tests = self._wetlab.group_tests_outputs(rngs[1], new_groups)\n self.process_tests_results(rngs[2], new_tests)\n self._on_iteration_end(sim_idx, self.state.curr_cycle, new_groups)\n self.state.curr_cycle += 1\n\n @property\n def marginal(self):\n \"\"\"Returns our best guess on the current probability of each patient.\"\"\"\n if self.state.marginals:\n return self.state.marginals[0]\n else:\n return self.sampler.marginal\n\n def process_tests_results(self, rng, new_tests):\n \"\"\"What to do when receiving the tests results.\"\"\"\n self.state.add_test_results(new_tests)\n self._resample(rng)\n\n def get_new_groups(self, rng):\n if self.state.extra_tests_needed > 0:\n self.state = self._policy.act(rng, self.state)\n return self.state.next_groups_to_test()\n\n def _resample(self, rng):\n \"\"\"(Re)Samples posterior/marginals given past test results.\n\n Args:\n rng: random key\n\n Produces and examines first the marginal produced by LBP.\n If that marginal is not valid because LBP did not converge,\n or that posterior samples are needed in the next iteration of the\n simulator by a group selector, we compute both marginals\n and posterior using the more expensive sampler.\n \"\"\"\n # reset marginals\n self.state.marginals = []\n # compute marginal using a cheap LBP sampler.\n lbp_sampler = self._samplers[0]\n lbp_sampler.produce_sample(rng, self.state)\n # if marginal is valid (i.e. LBP has converged), append it to state.\n if not np.any(np.isnan(lbp_sampler.marginal)):\n self.state.marginals.append(lbp_sampler.marginal)\n self.state.update_particles(lbp_sampler)\n # if marginal has not converged, or expensive sampler is needed, use it.\n if (np.any(np.isnan(lbp_sampler.marginal)) or\n (self._policy.next_selector.NEEDS_POSTERIOR and\n self.state.extra_tests_needed > 0 and\n self.state.curr_cycle < self._max_test_cycles - 1)):\n sampler = self._samplers[1]\n sampler.produce_sample(rng, self.state)\n self.state.marginals.append(sampler.marginal)\n self.state.update_particles(sampler)\n\n def _on_iteration_end(self,\n sim_idx,\n cycle_idx,\n new_groups=None,\n new_tests=None):\n \"\"\"Save metrics and ROC data at the end of one iteration.\"\"\"\n self.metrics.update(sim_idx,\n cycle_idx,\n self.state.marginals[0],\n self._wetlab.diseased,\n new_groups,\n new_tests)\n\n def interactive_loop(self, rngkey = None, show_fn=None):\n \"\"\"Runs an interactive loop producing groups and asking for results.\n\n Args:\n rngkey: a random seed for this simulation.\n show_fn: a function that takes 3 arguments and returns None:\n - the group to be displayed as np.ndarray<bool>[num_groups, num_patients]\n - the current marginal as np.ndarray<bool>[num_patients]\n - a state.State of the simulator.\n If show_fn is None, then the 3 inputs are printed.\n \"\"\"\n rngkey = int(time.time()) if rngkey is None else rngkey\n rng = jax.random.PRNGKey(rngkey)\n if show_fn is None:\n pd.options.display.float_format = \"{:.2f}\".format\n\n groups = None\n self.reset(rng)\n while not self.is_over:\n new_tests = None\n\n if groups is not None:\n positive_indices_str = input(\n f\"Cycle {self.state.curr_cycle}: Enter positive groups, as csv: \")\n\n new_tests = onp.zeros((groups.shape[0],))\n if positive_indices_str:\n try:\n indices = [int(x) - 1 for x in positive_indices_str.split(\",\")]\n new_tests[indices] = True\n except (ValueError, IndexError):\n logging.warning(\"Wrong format. Expecting comma-separated values.\"\n \"e.g. 3,2,1,9\")\n continue\n\n rng, *rngs = jax.random.split(rng, 3)\n if new_tests is not None:\n self.process_tests_results(rngs[0], new_tests)\n groups = self.get_new_groups(rngs[1])\n self.state.curr_cycle += 1\n\n if show_fn is not None:\n show_fn(groups, self.marginal, self.state)\n else:\n print(\"{0} Cycle {1} {0}\".format(\"-\" * 10, self.state.curr_cycle))\n df = pd.DataFrame(groups.astype(int),\n index=1 + onp.arange(groups.shape[0]))\n df.columns = 1 + onp.arange(groups.shape[1])\n print(\"Groups\\n\", df)\n print(self.marginal.shape)\n print(\"Marginal\\n\", pd.DataFrame(self.marginal[onp.newaxis, :]))\n" ]
[ [ "numpy.arange", "numpy.zeros", "pandas.DataFrame" ] ]
ttk21/lab_05
[ "916bf12185af9668e7c4d71fa282e1bf95a685cc" ]
[ "ex_4_full_ba.py" ]
[ "import numpy as np\nimport visgeom as vg\n\nfrom camera import PerspectiveCamera\nfrom measurements import PrecalibratedCameraMeasurements\nfrom optim import BundleAdjustmentState, levenberg_marquardt\nfrom visualise_ba import visualise_full\n\n\"\"\"Example 4 - Full Bundle Adjustment\"\"\"\n\n\nclass PrecalibratedFullBAObjective:\n \"\"\"Implements linearisation of the full BA objective function\"\"\"\n\n def __init__(self, measurements, pose1_prior, point1_prior):\n \"\"\"Constructs the objective\n\n :param measurements: A list of PrecalibratedCameraMeasurements objects, one for each camera.\n :param pose1_prior: The prior state of the first pose\n :param point1_prior: The prior state of the first point\n \"\"\"\n self.measurements = measurements\n self.pose1_prior = pose1_prior\n self.point1_prior = point1_prior\n\n @staticmethod\n def extract_measurement_jacobian_wrt_pose(point_index, pose_state_c_w, point_state_w, measurement):\n \"\"\"Computes the measurement Jacobian wrt the pose for a specific point and camera measurement.\n\n :param point_index: Index of current point.\n :param pose_state_c_w: Current pose state given as the pose of the world in the camera frame.\n :param point_state_w: Current point state in the world frame\n :param measurement: The measurement\n :return: The measurement Jacobian\n \"\"\"\n P = measurement.sqrt_inv_covs[point_index] @ \\\n measurement.camera.jac_project_world_to_normalised_wrt_pose_w_c(pose_state_c_w, point_state_w)\n\n return P\n\n @staticmethod\n def extract_measurement_jacobian_wrt_point(point_index, pose_state_c_w, point_state_w, measurement):\n \"\"\"Computes the measurement Jacobian wrt the point for a specific point and camera measurement.\n\n :param point_index: Index of current point.\n :param pose_state_c_w: Current pose state given as the pose of the world in the camera frame.\n :param point_state_w: Current state of a specific world point.\n :param measurement: The measurement\n :return: The measurement Jacobian\n \"\"\"\n S = measurement.sqrt_inv_covs[point_index] @ \\\n measurement.camera.jac_project_world_to_normalised_wrt_x_w(pose_state_c_w, point_state_w)\n\n return S\n\n @staticmethod\n def extract_measurement_error(point_index, pose_state_c_w, point_state_w, measurement):\n \"\"\"Computes the measurement error for a specific point and camera measurement.\n\n :param point_index: Index of current point.\n :param pose_state_c_w: Current pose state given as the pose of the world in the camera frame.\n :param point_state_w: Current state of a specific world point.\n :param measurement: The measurement\n :return: The measurement error\n \"\"\"\n b = measurement.sqrt_inv_covs[point_index] @ \\\n measurement.camera.reprojection_error_normalised(pose_state_c_w * point_state_w,\n measurement.xn[:, [point_index]])\n\n return b\n\n def linearise(self, states):\n \"\"\"Linearises the objective over all states and measurements\n\n :param states: The current pose and point states.\n :return:\n A - The full measurement Jacobian\n b - The full measurement error\n cost - The current cost\n \"\"\"\n num_cameras = states.num_poses\n num_points = states.num_points\n\n A = np.zeros((2 * num_cameras * num_points + 9, 6 * num_cameras + 3 * num_points))\n b = np.zeros((2 * num_cameras * num_points + 9, 1))\n\n for i in range(num_cameras):\n pose_state_c_w = states.get_pose(i).inverse()\n\n for j in range(num_points):\n point_state_w = states.get_point(j)\n\n # Insert submatrix for Jacobian wrt poses.\n rows = slice(i * 2 * num_points + j * 2, i * 2 * num_points + (j + 1) * 2)\n cols = slice(i * 6, (i + 1) * 6)\n A[rows, cols] = self.extract_measurement_jacobian_wrt_pose(j, pose_state_c_w, point_state_w,\n self.measurements[i])\n\n # Insert submatrix for Jacobian wrt points.\n cols = slice(6 * num_cameras + j * 3, 6 * num_cameras + (j + 1) * 3)\n A[rows, cols] = self.extract_measurement_jacobian_wrt_point(j, pose_state_c_w, point_state_w,\n self.measurements[i])\n\n b[rows, :] = self.extract_measurement_error(j, pose_state_c_w, point_state_w, self.measurements[i])\n\n # Add priors.\n A[2 * num_cameras * num_points:2 * num_cameras * num_points + 6, :6] = np.identity(6)\n b[2 * num_cameras * num_points:2 * num_cameras * num_points + 6] = -(states.get_pose(0) - self.pose1_prior)\n\n A[2 * num_cameras * num_points + 6:, 6 * num_cameras:6 * num_cameras + 3] = np.identity(3)\n b[2 * num_cameras * num_points + 6:] = -(states.get_point(0) - self.point1_prior)\n\n return A, b, b.T.dot(b)\n\n\ndef main():\n # World box.\n true_points_w = vg.utils.generate_box()\n\n # Define common camera parameters.\n w = 640\n h = 480\n focal_lengths = 0.75 * h * np.ones((2, 1))\n principal_point = 0.5 * np.array([[w, h]]).T\n camera = PerspectiveCamera(focal_lengths, principal_point)\n\n # Define a set of cameras.\n true_poses_w_c = [\n PerspectiveCamera.looks_at_pose(np.array([[3, -4, 0]]).T, np.zeros((3, 1)), np.array([[0, 0, 1]]).T),\n PerspectiveCamera.looks_at_pose(np.array([[3, 4, 0]]).T, np.zeros((3, 1)), np.array([[0, 0, 1]]).T)]\n\n # Generate a set of camera measurements.\n measurements = [PrecalibratedCameraMeasurements.generate(camera, pose, true_points_w) for pose in true_poses_w_c]\n\n # Construct model from measurements.\n model = PrecalibratedFullBAObjective(measurements, true_poses_w_c[0], true_points_w[:, [0]])\n\n # Perturb camera poses and world points and use as initial state.\n init_poses_wc = [pose + 0.3 * np.random.randn(6, 1) for pose in true_poses_w_c]\n init_points_w = [true_points_w[:, [i]] + 0.3 * np.random.randn(3, 1) for i in range(true_points_w.shape[1])]\n init_state = BundleAdjustmentState(init_poses_wc, init_points_w)\n\n # Estimate pose in the world frame from point correspondences.\n x, cost, A, b = levenberg_marquardt(init_state, model)\n cov_x_final = np.linalg.inv(A.T @ A)\n\n # Print covariance.\n with np.printoptions(precision=3, suppress=True):\n print('Covariance:')\n print(cov_x_final)\n\n # Visualise\n visualise_full(true_poses_w_c, true_points_w, measurements, x, cost)\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.printoptions", "numpy.linalg.inv", "numpy.ones", "numpy.identity", "numpy.random.randn", "numpy.array", "numpy.zeros" ] ]
WeiNingChen/GAPP-image
[ "77b54d2f68c97d5e92e63119a9b3700ffa0f5170" ]
[ "load_genki.py" ]
[ "import os\nimport pickle\nimport cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nSMILE_FOLDER = './genki4k/'\nF_SMILE_FOLDER = './data/smile_data/'\nNUM_SMILE_IMAGE = 4000\nWID_MEAN = 198\nLEN_MEAN = 184\n#SMILE_SIZE = 48\n\ndata = []\nlabels = []\n\nprint(\"Loading data...\")\nwith open(SMILE_FOLDER + \"labels.txt\") as f:\n for i in range(NUM_SMILE_IMAGE):\n fileName = SMILE_FOLDER + \"files/file\" + str(\"%04d\" % (1+i,)) + \".jpg\"\n img = cv2.imread(fileName)\n img = cv2.resize(img, (WID_MEAN, LEN_MEAN), cv2.INTER_AREA) \n #T = np.zeros([SMILE_SIZE, SMILE_SIZE, 1])\n #T[:, :, 0] = img\n l = f.readline()\n label = (int)(l.split()[0])\n data.append(np.array(img))\n labels.append(label)\n\ndata_array = np.array(data)\nprint('data_array shape:')\nprint(data_array.shape)\n\nlabels_array = np.array(labels)\nprint(\"label's shape:\")\nprint(labels_array.shape)\nindices = np.arange(data_array.shape[0])\n\nprint(\"Shuffling dataset...\")\n#for _ in range(10):\n# np.random.shuffle(indices)\n\ndata_array = data_array[indices]\nlabels_array = labels_array[indices]\n\ntrain_X, test_X = data_array[:3000], data_array[3000:]\ntrain_Y, test_Y = labels_array[:3000], labels_array[3000:]\n\ndata_np = {}\ndata_np['X_train'] = train_X\ndata_np['X_test'] = test_X\ndata_np['X_train'] = train_Y\ndata_np['X_test'] = test_Y\n\nprint(\"Saving dataset...\")\n#np.save(F_SMILE_FOLDER + 'data.npy', data_np)\npickle.dump( data_np, open( F_SMILE_FOLDER + \"data.p\", \"wb\" ) )\n" ]
[ [ "numpy.arange", "numpy.array" ] ]
dendisuhubdy/grounded-video-description
[ "2667e216223a63cdc91b616a34f4c046e507a1dc" ]
[ "main.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport torch.optim as optim\n\nimport numpy as np\nimport random\nimport time\nimport os\nimport pickle\nimport torch.backends.cudnn as cudnn\nimport yaml\nimport copy\nimport json\nimport math\n\nimport opts\nfrom misc import utils, AttModel\nfrom collections import defaultdict\n\nimport torchvision.transforms as transforms\nimport pdb\n\n# hack to allow the imports of evaluation repos\n_SCRIPTPATH_ = os.path.dirname(os.path.abspath(__file__))\nimport sys\nsys.path.insert(0, os.path.join(_SCRIPTPATH_, 'tools/densevid_eval'))\nsys.path.insert(0, os.path.join(_SCRIPTPATH_, 'tools/densevid_eval/coco-caption'))\nsys.path.insert(0, os.path.join(_SCRIPTPATH_, 'tools/anet_entities/scripts'))\n\nfrom evaluate import ANETcaptions\nfrom eval_grd_anet_entities import ANetGrdEval\n\n\n# visualization over generated sentences\ndef vis_infer(seg_show, seg_id, caption, att2_weights, proposals, num_box, gt_bboxs, sim_mat, seg_dim_info):\n cap = caption.split()\n output = []\n top_k_prop = 1 # plot the top 1 proposal only\n proposal = proposals[:num_box[1].item()]\n gt_bbox = gt_bboxs[:num_box[2].item()]\n\n sim_mat_val, sim_mat_ind = torch.max(sim_mat, dim=0)\n\n for j in range(len(cap)):\n\n max_att2_weight, top_k_alpha_idx = torch.max(att2_weights[j], dim=0)\n\n idx = top_k_alpha_idx\n target_frm = int(proposal[idx, 4].item())\n seg = copy.deepcopy(seg_show[target_frm, :seg_dim_info[0], :seg_dim_info[1]].numpy())\n seg_text = np.ones((67, int(seg_dim_info[1]), 3))*255\n cv2.putText(seg_text, '%s' % (cap[j]), (50, 50), cv2.FONT_HERSHEY_PLAIN, 3.0, (255, 0, 0), thickness=3)\n\n # draw the proposal box and text\n idx = top_k_alpha_idx\n bbox = proposal[idx, :4]\n bbox = tuple(int(np.round(x)) for x in proposal[idx, :4])\n class_name = opt.itod.get(sim_mat_ind[idx].item(), '__background__')\n cv2.rectangle(seg, bbox[0:2], bbox[2:4],\n (0, 255, 0), 2)\n cv2.putText(seg, '%s: (%.2f)' % (class_name, sim_mat_val[idx]),\n (bbox[0], bbox[1] + 25), cv2.FONT_HERSHEY_PLAIN, 2.0, (0, 0, 255), thickness=2)\n\n output.append(np.concatenate([seg_text, seg], axis=0))\n\n output = np.concatenate(output, axis=1)\n if not os.path.isdir('./vis'):\n os.mkdir('./vis')\n if not os.path.isdir('./vis/'+opt.id):\n os.mkdir('./vis/'+opt.id)\n # print('Visualize segment {} and the generated sentence!'.format(seg_id))\n cv2.imwrite('./vis/'+opt.id+'/'+str(seg_id)+'_generated_sent.jpg', output[:,:,::-1])\n\n\n# compute localization (attention/grounding) accuracy over GT sentences\ndef eval_grounding(opt, vis=None):\n model.eval()\n\n data_iter = iter(dataloader_val)\n cls_pred_lst = []\n cls_accu_score = defaultdict(list)\n att2_output = defaultdict(dict)\n grd_output = defaultdict(dict)\n vocab_in_split = set()\n\n for step in range(len(dataloader_val)):\n data = data_iter.next()\n seg_feat, iseq, gts_seq, num, proposals, bboxs, box_mask, seg_id, region_feat, frm_mask, sample_idx, ppl_mask = data\n\n proposals = proposals[:,:max(int(max(num[:,1])),1),:]\n ppl_mask = ppl_mask[:,:max(int(max(num[:,1])),1)]\n assert(max(int(max(num[:,1])),1) == opt.num_sampled_frm*opt.num_prop_per_frm)\n bboxs = bboxs[:,:max(int(max(num[:,2])),1),:]\n frm_mask = frm_mask[:, :max(int(max(num[:,1])),1), :max(int(max(num[:,2])),1)]\n region_feat = region_feat[:,:max(int(max(num[:,1])),1),:]\n\n segs_feat.resize_(seg_feat.size()).data.copy_(seg_feat)\n input_seqs.resize_(iseq.size()).data.copy_(iseq)\n gt_seqs.resize_(gts_seq.size()).data.copy_(gts_seq)\n input_num.resize_(num.size()).data.copy_(num)\n input_ppls.resize_(proposals.size()).data.copy_(proposals)\n mask_ppls.resize_(ppl_mask.size()).data.copy_(ppl_mask)\n pnt_mask = torch.cat((mask_ppls.new(mask_ppls.size(0), 1).fill_(0), mask_ppls), dim=1)\n gt_bboxs.resize_(bboxs.size()).data.copy_(bboxs) # for region cls eval only\n mask_frms.resize_(frm_mask.size()).data.copy_(frm_mask) # for region cls eval only\n ppls_feat.resize_(region_feat.size()).data.copy_(region_feat)\n sample_idx = Variable(sample_idx.type(input_seqs.type()))\n\n dummy = input_ppls.new(input_ppls.size(0)).byte().fill_(0)\n\n # cls_pred_hm_lst contains a list of tuples (clss_ind, hit/1 or miss/0)\n cls_pred_hm_lst, att2_ind, grd_ind = model(segs_feat, input_seqs, gt_seqs, input_num,\n input_ppls, gt_bboxs, dummy, ppls_feat, mask_frms, sample_idx, pnt_mask, 'GRD')\n\n # save attention/grounding results on GT sentences\n obj_mask = (input_seqs[:,0,1:,0] > opt.vocab_size) # Bx20\n obj_bbox_att2 = torch.gather(input_ppls.view(-1, opt.num_sampled_frm, opt.num_prop_per_frm, 7) \\\n .permute(0, 2, 1, 3).contiguous(), 1, att2_ind.unsqueeze(-1).expand((att2_ind.size(0), \\\n att2_ind.size(1), opt.num_sampled_frm, 7))) # Bx20x10x7\n obj_bbox_grd = torch.gather(input_ppls.view(-1, opt.num_sampled_frm, opt.num_prop_per_frm, 7) \\\n .permute(0, 2, 1, 3).contiguous(), 1, grd_ind.unsqueeze(-1).expand((grd_ind.size(0), \\\n grd_ind.size(1), opt.num_sampled_frm, 7))) # Bx20x10x7\n\n for i in range(obj_mask.size(0)):\n vid_id, seg_idx = seg_id[i].split('_segment_')\n seg_idx = str(int(seg_idx))\n tmp_result_grd = {'clss':[], 'idx_in_sent':[], 'bbox_for_all_frames':[]}\n tmp_result_att2 = {'clss':[], 'idx_in_sent':[], 'bbox_for_all_frames':[]}\n for j in range(obj_mask.size(1)):\n if obj_mask[i, j]:\n cls_name = opt.itod[input_seqs[i,0,j+1,0].item()-opt.vocab_size]\n vocab_in_split.update([cls_name])\n tmp_result_att2['clss'].append(cls_name)\n tmp_result_att2['idx_in_sent'].append(j)\n tmp_result_att2['bbox_for_all_frames'].append(obj_bbox_att2[i, j, :, :4].tolist())\n tmp_result_grd['clss'].append(cls_name)\n tmp_result_grd['idx_in_sent'].append(j)\n tmp_result_grd['bbox_for_all_frames'].append(obj_bbox_grd[i, j, :, :4].tolist())\n att2_output[vid_id][seg_idx] = tmp_result_att2\n grd_output[vid_id][seg_idx] = tmp_result_grd\n\n cls_pred_lst.append(cls_pred_hm_lst)\n\n # write results to file\n attn_file = 'results/attn-gt-sent-results-'+opt.val_split+'-'+opt.id+'.json'\n with open(attn_file, 'w') as f:\n json.dump({'results':att2_output, 'eval_mode':'GT', 'external_data':{'used':True, 'details':'Object detector pre-trained on Visual Genome on object detection task.'}}, f)\n grd_file = 'results/grd-gt-sent-results-'+opt.val_split+'-'+opt.id+'.json'\n with open(grd_file, 'w') as f:\n json.dump({'results':grd_output, 'eval_mode':'GT', 'external_data':{'used':True, 'details':'Object detector pre-trained on Visual Genome on object detection task.'}}, f)\n\n if not opt.test_mode:\n cls_pred_lst = torch.cat(cls_pred_lst, dim=0).cpu()\n cls_accu_lst = torch.cat((cls_pred_lst[:, 0:1], (cls_pred_lst[:, 0:1] == cls_pred_lst[:, 1:2]).long()), dim=1)\n for i in range(cls_accu_lst.size(0)):\n cls_accu_score[cls_accu_lst[i,0].long().item()].append(cls_accu_lst[i,1].item())\n print('Total number of object classes in the split: {}. {} have classification results.'.format(len(vocab_in_split), len(cls_accu_score)))\n cls_accu = np.sum([sum(hm)*1./len(hm) for i,hm in cls_accu_score.items()])*1./len(vocab_in_split)\n\n # offline eval\n evaluator = ANetGrdEval(reference_file=opt.grd_reference, submission_file=attn_file,\n split_file=opt.split_file, val_split=[opt.val_split],\n iou_thresh=0.5)\n\n attn_accu = evaluator.gt_grd_eval()\n evaluator.import_sub(grd_file)\n grd_accu = evaluator.gt_grd_eval()\n\n print('\\nResults Summary (GT sent):')\n print('The averaged attention / grounding box accuracy across all classes is: {:.4f} / {:.4f}'.format(attn_accu, grd_accu))\n print('The averaged classification accuracy across all classes is: {:.4f}\\n'.format(cls_accu))\n\n return attn_accu, grd_accu, cls_accu\n else:\n print('*'*62)\n print('* [WARNING] Grounding eval unavailable for the test set!\\\n *\\n* Please submit your result file named *\\\n \\n* results/grd-gt-sent-*.json to the eval server! *')\n print('*'*62)\n\n return 0, 0, 0\n\n\ndef train(epoch, opt, vis=None, vis_window=None):\n model.train()\n\n data_iter = iter(dataloader)\n nbatches = len(dataloader)\n train_loss = []\n\n lm_loss_temp = []\n att2_loss_temp = []\n ground_loss_temp = []\n cls_loss_temp = []\n start = time.time()\n\n for step in range(len(dataloader)-1):\n data = data_iter.next()\n seg_feat, iseq, gts_seq, num, proposals, bboxs, box_mask, seg_id, region_feat, frm_mask, sample_idx, ppl_mask = data\n proposals = proposals[:,:max(int(max(num[:,1])),1),:]\n ppl_mask = ppl_mask[:,:max(int(max(num[:,1])),1)]\n bboxs = bboxs[:,:max(int(max(num[:,2])),1),:]\n box_mask = box_mask[:,:,:max(int(max(num[:,2])),1),:]\n frm_mask = frm_mask[:,:max(int(max(num[:,1])),1),:max(int(max(num[:,2])),1)]\n region_feat = region_feat[:,:max(int(max(num[:,1])),1),:]\n\n segs_feat.resize_(seg_feat.size()).data.copy_(seg_feat)\n input_seqs.resize_(iseq.size()).data.copy_(iseq)\n gt_seqs.resize_(gts_seq.size()).data.copy_(gts_seq)\n input_num.resize_(num.size()).data.copy_(num)\n input_ppls.resize_(proposals.size()).data.copy_(proposals)\n mask_ppls.resize_(ppl_mask.size()).data.copy_(ppl_mask)\n # pad 1 column from a legacy reason\n pnt_mask = torch.cat((mask_ppls.new(mask_ppls.size(0), 1).fill_(0), mask_ppls), dim=1)\n gt_bboxs.resize_(bboxs.size()).data.copy_(bboxs)\n mask_bboxs.resize_(box_mask.size()).data.copy_(box_mask)\n mask_frms.resize_(frm_mask.size()).data.copy_(frm_mask)\n ppls_feat.resize_(region_feat.size()).data.copy_(region_feat)\n sample_idx = Variable(sample_idx.type(input_seqs.type()))\n\n loss = 0\n lm_loss, att2_loss, ground_loss, cls_loss = model(segs_feat, input_seqs, gt_seqs, input_num,\n input_ppls, gt_bboxs, mask_bboxs, ppls_feat, mask_frms, sample_idx, pnt_mask, 'MLE')\n\n w_att2, w_grd, w_cls = opt.w_att2, opt.w_grd, opt.w_cls\n att2_loss = w_att2*att2_loss.sum()\n ground_loss = w_grd*ground_loss.sum()\n cls_loss = w_cls*cls_loss.sum()\n\n if not opt.disable_caption:\n loss += lm_loss.sum()\n else:\n lm_loss.fill_(0)\n\n if w_att2:\n loss += att2_loss\n if w_grd:\n loss += ground_loss\n if w_cls:\n loss += cls_loss\n\n loss = loss / lm_loss.numel()\n train_loss.append(loss.item())\n\n lm_loss_temp.append(lm_loss.sum().item() / lm_loss.numel())\n att2_loss_temp.append(att2_loss.sum().item() / lm_loss.numel())\n ground_loss_temp.append(ground_loss.sum().item() / lm_loss.numel())\n cls_loss_temp.append(cls_loss.sum().item() / lm_loss.numel())\n\n model.zero_grad()\n loss.backward()\n nn.utils.clip_grad_norm_(model.parameters(), opt.grad_clip)\n optimizer.step()\n\n if step % opt.disp_interval == 0 and step != 0:\n end = time.time()\n\n print(\"step {}/{} (epoch {}), lm_loss = {:.3f}, att2_loss = {:.3f}, ground_loss = {:.3f},cls_los = {:.3f}, lr = {:.5f}, time/batch = {:.3f}\" \\\n .format(step, len(dataloader), epoch, np.mean(lm_loss_temp), np.mean(att2_loss_temp), \\\n np.mean(ground_loss_temp), np.mean(cls_loss_temp), opt.learning_rate, end - start))\n start = time.time()\n\n if opt.enable_visdom:\n if vis_window['iter'] is None:\n vis_window['iter'] = vis.line(\n X=np.tile(np.arange(epoch*nbatches+step, epoch*nbatches+step+1),\n (5,1)).T,\n Y=np.column_stack((np.asarray(np.mean(train_loss)),\n np.asarray(np.mean(lm_loss_temp)),\n np.asarray(np.mean(att2_loss_temp)),\n np.asarray(np.mean(ground_loss_temp)),\n np.asarray(np.mean(cls_loss_temp)))),\n opts=dict(title='Training Loss',\n xlabel='Training Iteration',\n ylabel='Loss',\n legend=['total', 'lm', 'attn', 'grd', 'cls'])\n )\n else:\n vis.line(\n X=np.tile(np.arange(epoch*nbatches+step, epoch*nbatches+step+1),\n (5,1)).T,\n Y=np.column_stack((np.asarray(np.mean(train_loss)),\n np.asarray(np.mean(lm_loss_temp)),\n np.asarray(np.mean(att2_loss_temp)),\n np.asarray(np.mean(ground_loss_temp)),\n np.asarray(np.mean(cls_loss_temp)))),\n opts=dict(title='Training Loss',\n xlabel='Training Iteration',\n ylabel='Loss',\n legend=['total', 'lm', 'attn', 'grd', 'cls']),\n win=vis_window['iter'],\n update='append'\n )\n\n # Write the training loss summary\n if (iteration % opt.losses_log_every == 0):\n loss_history[iteration] = loss.item()\n lr_history[iteration] = opt.learning_rate\n\n\ndef eval(epoch, opt, vis=None, vis_window=None):\n model.eval()\n\n data_iter_val = iter(dataloader_val)\n start = time.time()\n\n num_show = 0\n predictions = defaultdict(list)\n count = 0\n timestamp_file = json.load(open(opt.grd_reference))\n min_value = -1e8\n\n if opt.eval_obj_grounding:\n grd_output = defaultdict(dict)\n\n lemma_det_dict = {opt.wtol[key]:idx for key,idx in opt.wtod.items() if key in opt.wtol}\n print('{} classes have the associated lemma word!'.format(len(lemma_det_dict)))\n\n if opt.eval_obj_grounding or opt.language_eval:\n for step in range(len(dataloader_val)):\n data = data_iter_val.next()\n if opt.vis_attn:\n seg_feat, iseq, gts_seq, num, proposals, bboxs, box_mask, seg_id, seg_show, seg_dim_info, region_feat, frm_mask, sample_idx, ppl_mask = data\n else:\n seg_feat, iseq, gts_seq, num, proposals, bboxs, box_mask, seg_id, region_feat, frm_mask, sample_idx, ppl_mask = data\n\n proposals = proposals[:,:max(int(max(num[:,1])),1),:]\n ppl_mask = ppl_mask[:,:max(int(max(num[:,1])),1)]\n region_feat = region_feat[:,:max(int(max(num[:,1])),1),:]\n\n segs_feat.resize_(seg_feat.size()).data.copy_(seg_feat)\n input_num.resize_(num.size()).data.copy_(num)\n input_ppls.resize_(proposals.size()).data.copy_(proposals)\n mask_ppls.resize_(ppl_mask.size()).data.copy_(ppl_mask)\n pnt_mask = torch.cat((mask_ppls.new(mask_ppls.size(0), 1).fill_(0), mask_ppls), dim=1) # pad 1 column from a legacy reason\n ppls_feat.resize_(region_feat.size()).data.copy_(region_feat)\n sample_idx = Variable(sample_idx.type(input_num.type()))\n\n eval_opt = {'sample_max':1, 'beam_size': opt.beam_size, 'inference_mode' : True}\n dummy = input_ppls.new(input_ppls.size(0)).byte().fill_(0)\n\n batch_size = input_ppls.size(0)\n\n seq, att2_weights, sim_mat = model(segs_feat, dummy, dummy, input_num, \\\n input_ppls, dummy, dummy, ppls_feat, dummy, sample_idx, pnt_mask, 'sample', eval_opt)\n\n # save localization results on generated sentences\n if opt.eval_obj_grounding:\n assert opt.beam_size == 1, 'only support beam_size is 1'\n\n att2_ind = torch.max(att2_weights.view(batch_size, att2_weights.size(1), \\\n opt.num_sampled_frm, opt.num_prop_per_frm), dim=-1)[1]\n obj_bbox_att2 = torch.gather(input_ppls.view(-1, opt.num_sampled_frm, opt.num_prop_per_frm, 7) \\\n .permute(0, 2, 1, 3).contiguous(), 1, att2_ind.unsqueeze(-1).expand((batch_size, \\\n att2_ind.size(1), opt.num_sampled_frm, input_ppls.size(-1)))) # Bx20x10x7\n\n for i in range(seq.size(0)):\n vid_id, seg_idx = seg_id[i].split('_segment_')\n seg_idx = str(int(seg_idx))\n tmp_result = {'clss':[], 'idx_in_sent':[], 'bbox_for_all_frames':[]}\n\n for j in range(seq.size(1)):\n if seq[i,j].item() != 0:\n lemma = opt.wtol[opt.itow[str(seq[i,j].item())]]\n if lemma in lemma_det_dict:\n tmp_result['bbox_for_all_frames'].append(obj_bbox_att2[i, j, :, :4].tolist())\n tmp_result['clss'].append(opt.itod[lemma_det_dict[lemma]])\n tmp_result['idx_in_sent'].append(j) # redundant, for the sake of output format\n else:\n break\n grd_output[vid_id][seg_idx] = tmp_result\n\n sents = utils.decode_sequence(dataset.itow, dataset.itod, dataset.ltow, dataset.itoc, \\\n dataset.wtod, seq.data, opt.vocab_size, opt)\n\n for k, sent in enumerate(sents):\n vid_idx, seg_idx = seg_id[k].split('_segment_')\n seg_idx = str(int(seg_idx))\n\n predictions[vid_idx].append(\n {'sentence':sent,\n 'timestamp':[round(timestamp, 2) for timestamp in timestamp_file[ \\\n 'annotations'][vid_idx]['segments'][seg_idx]['timestamps']]})\n\n if num_show < 20:\n print('segment %s: %s' %(seg_id[k], sent))\n num_show += 1\n\n # visualization\n if opt.vis_attn:\n assert(opt.beam_size == 1) # only support beam_size=1\n att2_weights = F.softmax(att2_weights, dim=2)\n # visualize some selected examples\n if torch.sum(proposals[k]) != 0:\n vis_infer(seg_show[k], seg_id[k], sent, \\\n att2_weights[k].cpu().data, proposals[k], num[k].long(), \\\n bboxs[k], sim_mat[k].cpu().data, seg_dim_info[k])\n\n if count % 2 == 0:\n print(count)\n count += 1\n\n lang_stats = defaultdict(float)\n if opt.language_eval:\n print('Total videos to be evaluated %d' %(len(predictions)))\n\n submission = 'densecap_results/'+'densecap-'+opt.val_split+'-'+opt.id+'.json'\n dense_cap_all = {'version':'VERSION 1.0', 'results':predictions,\n 'external_data':{'used':'true',\n 'details':'Visual Genome for Faster R-CNN pre-training'}}\n with open(submission, 'w') as f:\n json.dump(dense_cap_all, f)\n\n references = opt.densecap_references\n verbose = opt.densecap_verbose\n tious_lst = [0.3, 0.5, 0.7, 0.9]\n evaluator = ANETcaptions(ground_truth_filenames=references,\n prediction_filename=submission,\n tious=tious_lst,\n max_proposals=1000,\n verbose=verbose)\n evaluator.evaluate()\n\n for m,v in evaluator.scores.items():\n lang_stats[m] = np.mean(v)\n\n print('\\nResults Summary (lang eval):')\n print('Printing language evaluation metrics...')\n for m, s in lang_stats.items():\n print('{}: {:.3f}'.format(m, s*100))\n print('\\n')\n\n if opt.eval_obj_grounding:\n # write attention results to file\n attn_file = 'results/attn-gen-sent-results-'+opt.val_split+'-'+opt.id+'.json'\n with open(attn_file, 'w') as f:\n json.dump({'results':grd_output, 'eval_mode':'gen', 'external_data':{'used':True, 'details':'Object detector pre-trained on Visual Genome on object detection task.'}}, f)\n\n if not opt.test_mode:\n # offline eval\n evaluator = ANetGrdEval(reference_file=opt.grd_reference, submission_file=attn_file,\n split_file=opt.split_file, val_split=[opt.val_split],\n iou_thresh=0.5)\n\n print('\\nResults Summary (generated sent):')\n print('Printing attention accuracy on generated sentences, per class and per sentence, respectively...')\n prec_all, recall_all, f1_all, prec_all_per_sent, rec_all_per_sent, f1_all_per_sent = evaluator.grd_eval(mode='all')\n prec_loc, recall_loc, f1_loc, prec_loc_per_sent, rec_loc_per_sent, f1_loc_per_sent = evaluator.grd_eval(mode='loc')\n else:\n print('*'*62)\n print('* [WARNING] Grounding eval unavailable for the test set!\\\n *\\n* Please submit your result file named *\\\n \\n* results/attn-gen-sent-*.json to the eval server!*')\n print('*'*62)\n\n if opt.att_model == 'topdown' and opt.eval_obj_grounding_gt:\n with torch.no_grad():\n box_accu_att, box_accu_grd, cls_accu = eval_grounding(opt) # eval grounding\n else:\n box_accu_att, box_accu_grd, cls_accu = 0, 0, 0\n\n if opt.enable_visdom:\n assert(opt.language_eval)\n if vis_window['score'] is None:\n vis_window['score'] = vis.line(\n X=np.tile(np.arange(epoch, epoch+1),\n (7,1)).T,\n Y=np.column_stack((np.asarray(box_accu_att),\n np.asarray(box_accu_grd),\n np.asarray(cls_accu),\n np.asarray(lang_stats['Bleu_4']),\n np.asarray(lang_stats['METEOR']),\n np.asarray(lang_stats['CIDEr']),\n np.asarray(lang_stats['SPICE']))),\n opts=dict(title='Validation Score',\n xlabel='Validation Epoch',\n ylabel='Score',\n legend=['BA (alpha)', 'BA (beta)', 'CLS Accu', 'Bleu_4', 'METEOR', 'CIDEr', 'SPICE'])\n )\n else:\n vis.line(\n X=np.tile(np.arange(epoch, epoch+1),\n (7,1)).T,\n Y=np.column_stack((np.asarray(box_accu_att),\n np.asarray(box_accu_grd),\n np.asarray(cls_accu),\n np.asarray(lang_stats['Bleu_4']),\n np.asarray(lang_stats['METEOR']),\n np.asarray(lang_stats['CIDEr']),\n np.asarray(lang_stats['SPICE']))),\n opts=dict(title='Validation Score',\n xlabel='Validation Epoch',\n ylabel='Score',\n legend=['BA (alpha)', 'BA (beta)', 'CLS Accu', 'Bleu_4', 'METEOR', 'CIDEr', 'SPICE']),\n win=vis_window['score'],\n update='append'\n )\n\n print('Saving the predictions')\n\n # Write validation result into summary\n val_result_history[iteration] = {'lang_stats': lang_stats, 'predictions': predictions}\n\n return lang_stats\n\n\nif __name__ == '__main__':\n\n opt = opts.parse_opt()\n if opt.path_opt is not None:\n with open(opt.path_opt, 'r') as handle:\n options_yaml = yaml.load(handle)\n utils.update_values(options_yaml, vars(opt))\n opt.test_mode = (opt.val_split in ['testing', 'hidden_test'])\n if opt.enable_BUTD:\n assert opt.att_input_mode == 'region', 'region attention only under the BUTD mode'\n\n # print(opt)\n cudnn.benchmark = True\n\n if opt.enable_visdom:\n import visdom\n vis = visdom.Visdom(server=opt.visdom_server, env=opt.id)\n vis_window={'iter': None, 'score':None}\n\n torch.manual_seed(opt.seed)\n np.random.seed(opt.seed)\n random.seed(opt.seed)\n if opt.cuda:\n torch.cuda.manual_seed_all(opt.seed)\n if opt.vis_attn:\n import cv2\n\n if opt.dataset == 'anet':\n from misc.dataloader_anet import DataLoader\n else:\n raise Exception('only support anet!')\n\n if not os.path.exists(opt.checkpoint_path):\n os.makedirs(opt.checkpoint_path)\n\n # Data Loader\n dataset = DataLoader(opt, split=opt.train_split, seq_per_img=opt.seq_per_img)\n dataloader = torch.utils.data.DataLoader(dataset, batch_size=opt.batch_size,\n shuffle=True, num_workers=opt.num_workers)\n\n dataset_val = DataLoader(opt, split=opt.val_split, seq_per_img=opt.seq_per_img)\n dataloader_val = torch.utils.data.DataLoader(dataset_val, batch_size=opt.batch_size,\n shuffle=False, num_workers=opt.num_workers)\n\n segs_feat = torch.FloatTensor(1)\n input_seqs = torch.LongTensor(1)\n input_ppls = torch.FloatTensor(1)\n mask_ppls = torch.ByteTensor(1)\n gt_bboxs = torch.FloatTensor(1)\n mask_bboxs = torch.ByteTensor(1)\n mask_frms = torch.ByteTensor(1)\n gt_seqs = torch.LongTensor(1)\n input_num = torch.LongTensor(1)\n ppls_feat = torch.FloatTensor(1)\n\n if opt.cuda:\n segs_feat = segs_feat.cuda()\n input_seqs = input_seqs.cuda()\n gt_seqs = gt_seqs.cuda()\n input_num = input_num.cuda()\n input_ppls = input_ppls.cuda()\n mask_ppls = mask_ppls.cuda()\n gt_bboxs = gt_bboxs.cuda()\n mask_bboxs = mask_bboxs.cuda()\n mask_frms = mask_frms.cuda()\n ppls_feat = ppls_feat.cuda()\n\n segs_feat = Variable(segs_feat)\n input_seqs = Variable(input_seqs)\n gt_seqs = Variable(gt_seqs)\n input_num = Variable(input_num)\n input_ppls = Variable(input_ppls)\n mask_ppls = Variable(mask_ppls)\n gt_bboxs = Variable(gt_bboxs)\n mask_bboxs = Variable(mask_bboxs)\n mask_frms = Variable(mask_frms)\n ppls_feat = Variable(ppls_feat)\n\n # Build the Model\n opt.vocab_size = dataset.vocab_size\n opt.detect_size = dataset.detect_size\n opt.seq_length = opt.seq_length\n opt.glove_w = torch.from_numpy(dataset.glove_w).float()\n opt.glove_vg_cls = torch.from_numpy(dataset.glove_vg_cls).float()\n opt.glove_clss = torch.from_numpy(dataset.glove_clss).float()\n\n opt.wtoi = dataset.wtoi\n opt.itow = dataset.itow\n opt.itod = dataset.itod\n opt.ltow = dataset.ltow\n opt.itoc = dataset.itoc\n opt.wtol = dataset.wtol\n opt.wtod = dataset.wtod\n opt.vg_cls = dataset.vg_cls\n\n if opt.att_model == 'topdown':\n model = AttModel.TopDownModel(opt)\n elif opt.att_model == 'transformer':\n model = AttModel.TransformerModel(opt)\n\n infos = {}\n histories = {}\n if opt.start_from is not None:\n if opt.load_best_score == 1:\n model_path = os.path.join(opt.start_from, 'model-best.pth')\n info_path = os.path.join(opt.start_from, 'infos_'+opt.id+'-best.pkl')\n else:\n model_path = os.path.join(opt.start_from, 'model.pth')\n info_path = os.path.join(opt.start_from, 'infos_'+opt.id+'.pkl')\n\n # open old infos and check if models are compatible\n with open(info_path, 'rb') as f:\n infos = pickle.load(f, encoding='latin1') # py2 pickle -> py3\n # infos = pickle.load(f)\n saved_model_opt = infos['opt']\n\n # opt.learning_rate = saved_model_opt.learning_rate\n print('Loading the model %s...' %(model_path))\n model.load_state_dict(torch.load(model_path))\n\n if os.path.isfile(os.path.join(opt.start_from, 'histories_'+opt.id+'.pkl')):\n with open(os.path.join(opt.start_from, 'histories_'+opt.id+'.pkl'), 'rb') as f:\n histories = pickle.load(f, encoding='latin1') # py2 pickle -> py3\n # histories = pickle.load(f)\n\n best_val_score = infos.get('best_val_score', None)\n iteration = infos.get('iter', 0)\n start_epoch = infos.get('epoch', 0)\n\n val_result_history = histories.get('val_result_history', {})\n loss_history = histories.get('loss_history', {})\n lr_history = histories.get('lr_history', {})\n ss_prob_history = histories.get('ss_prob_history', {})\n\n if opt.mGPUs:\n model = nn.DataParallel(model)\n\n if opt.cuda:\n model.cuda()\n\n params = []\n for key, value in dict(model.named_parameters()).items():\n if value.requires_grad:\n if ('ctx2pool_grd' in key) or ('vis_embed' in key):\n print('Finetune param: {}'.format(key))\n params += [{'params':[value], 'lr':opt.learning_rate*0.1, # finetune the fc7 layer\n 'weight_decay':opt.weight_decay, 'betas':(opt.optim_alpha, opt.optim_beta)}]\n else:\n params += [{'params':[value], 'lr':opt.learning_rate,\n 'weight_decay':opt.weight_decay, 'betas':(opt.optim_alpha, opt.optim_beta)}]\n\n print(\"Use %s as optmization method\" %(opt.optim))\n if opt.optim == 'sgd':\n optimizer = optim.SGD(params, momentum=0.9)\n elif opt.optim == 'adam':\n optimizer = optim.Adam(params)\n elif opt.optim == 'adamax':\n \toptimizer = optim.Adamax(params)\n\n for epoch in range(start_epoch, opt.max_epochs):\n if epoch > opt.learning_rate_decay_start and opt.learning_rate_decay_start >= 0:\n if (epoch - opt.learning_rate_decay_start) % opt.learning_rate_decay_every == 0:\n # decay the learning rate.\n utils.set_lr(optimizer, opt.learning_rate_decay_rate)\n opt.learning_rate = opt.learning_rate * opt.learning_rate_decay_rate\n\n if not opt.inference_only:\n if opt.enable_visdom:\n train(epoch, opt, vis, vis_window)\n else:\n train(epoch, opt)\n\n if epoch % opt.val_every_epoch == 0:\n with torch.no_grad():\n if opt.enable_visdom:\n lang_stats = eval(epoch, opt, vis, vis_window)\n else:\n lang_stats = eval(epoch, opt)\n\n if opt.inference_only:\n break\n\n # Save model if is improving on validation result\n current_score = lang_stats['CIDEr']\n\n best_flag = False\n if best_val_score is None or current_score > best_val_score:\n best_val_score = current_score\n best_flag = True\n checkpoint_path = os.path.join(opt.checkpoint_path, 'model.pth')\n if opt.mGPUs:\n torch.save(model.module.state_dict(), checkpoint_path)\n else:\n torch.save(model.state_dict(), checkpoint_path)\n print(\"model saved to {}\".format(checkpoint_path))\n # optimizer_path = os.path.join(opt.checkpoint_path, 'optimizer.pth')\n # torch.save(optimizer.state_dict(), optimizer_path)\n\n # Dump miscalleous informations\n infos['iter'] = iteration\n infos['epoch'] = epoch\n infos['best_val_score'] = best_val_score\n infos['opt'] = opt\n infos['vocab'] = dataset.itow\n\n histories['val_result_history'] = val_result_history\n histories['loss_history'] = loss_history\n histories['lr_history'] = lr_history\n histories['ss_prob_history'] = ss_prob_history\n with open(os.path.join(opt.checkpoint_path, 'infos_'+opt.id+'.pkl'), 'wb') as f:\n pickle.dump(infos, f)\n with open(os.path.join(opt.checkpoint_path, 'histories_'+opt.id+'.pkl'), 'wb') as f:\n pickle.dump(histories, f)\n\n if best_flag:\n checkpoint_path = os.path.join(opt.checkpoint_path, 'model-best.pth')\n if opt.mGPUs:\n torch.save(model.module.state_dict(), checkpoint_path)\n else:\n torch.save(model.state_dict(), checkpoint_path)\n\n print(\"model saved to {} with best cider score {:.3f}\".format(checkpoint_path, best_val_score))\n with open(os.path.join(opt.checkpoint_path, 'infos_'+opt.id+'-best.pkl'), 'wb') as f:\n pickle.dump(infos, f)\n" ]
[ [ "torch.nn.functional.softmax", "torch.max", "torch.load", "torch.cat", "numpy.asarray", "torch.utils.data.DataLoader", "torch.sum", "numpy.concatenate", "numpy.round", "torch.FloatTensor", "numpy.mean", "torch.cuda.manual_seed_all", "torch.no_grad", "torch.autograd.Variable", "numpy.arange", "torch.from_numpy", "torch.optim.SGD", "torch.optim.Adam", "torch.LongTensor", "torch.optim.Adamax", "torch.ByteTensor", "numpy.random.seed", "torch.manual_seed", "torch.nn.DataParallel" ] ]
lorisercole/samos
[ "e0756f341a1f2faf86aa9c1d47d823879be2f084" ]
[ "samos/analysis/rdf.py" ]
[ "# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom scipy.spatial.distance import cdist\nfrom ase import Atoms\nfrom samos.trajectory import Trajectory\nfrom samos.utils.attributed_array import AttributedArray\nfrom samos.lib.rdf import calculate_rdf, calculate_angular_spec\nimport itertools\nfrom abc import ABCMeta, abstractmethod\n\n\nclass BaseAnalyzer(object, metaclass=ABCMeta):\n def __init__(self, **kwargs):\n for key, val in list(kwargs.items()):\n getattr(self, 'set_{}'.format(key))(val)\n def set_trajectory(self, trajectory):\n if not isinstance(trajectory, Trajectory):\n raise TypeError('You need ot pass a {} as trajectory'.format(Trajectory))\n self._trajectory = trajectory\n @abstractmethod\n def run(*args, **kwargs):\n pass\n\nclass RDF(BaseAnalyzer):\n def run_fort(self, radius=None, species_pairs=None, istart=0, istop=None, stepsize=1, nbins=100):\n \"\"\"\n :param float radius: The radius for the calculation of the RDF\n :param float density: The grid density. The number of bins is given by radius/density\n \"\"\"\n raise NotImplemented('This is not fully implemented')\n atoms = self._trajectory.atoms\n volume = atoms.get_volume()\n positions = self._trajectory.get_positions()\n if istop is None:\n istop = len(positions)\n if species_pairs is None:\n species_pairs = list(itertools.combinations_with_replacement(set(atoms.get_chemical_symbols()), 2))\n cell = np.array(atoms.cell.T)\n cellI = np.linalg.inv(cell)\n chem_sym = np.array(atoms.get_chemical_symbols(), dtype=str)\n rdf_res = AttributedArray()\n rdf_res.set_attr('species_pairs', species_pairs)\n for spec1, spec2 in species_pairs:\n ind1 = np.where(chem_sym == spec1)[0] + 1 # +1 for fortran indexing\n ind2 = np.where(chem_sym == spec2)[0] + 1\n density = float(len(ind2)) / volume\n rdf, integral, radii = calculate_rdf(positions, istart, istop, stepsize,\n radius, density, cell,\n cellI, ind1, ind2, nbins)\n rdf_res.set_array('rdf_{}_{}'.format(spec1, spec2), rdf)\n rdf_res.set_array('int_{}_{}'.format(spec1, spec2), integral)\n rdf_res.set_array('radii_{}_{}'.format(spec1, spec2), radii)\n return rdf_res\n\n def run(self, radius=None, species_pairs=None, istart=0, istop=None, stepsize=1, nbins=100):\n def get_indices(spec, chem_sym):\n \"\"\"\n get the indices for specification spec\n \"\"\"\n if isinstance(spec, str):\n return np.where(chem_sym == spec)[0].tolist()\n elif isinstance(spec, int):\n return [spec]\n elif isinstance(spec, (tuple, list)):\n list_ = []\n for item in spec:\n list_ += get_indices(item, chem_sym)\n return list_\n else:\n raise TypeError('{} can not be transformed to index'.format(spec))\n def get_label(spec, ispec):\n \"\"\"\n Get a good label for scpecification spec. If none can befound\n give on based on iteration counter ispec\n \"\"\"\n if isinstance(spec,str):\n return spec\n elif isinstance(spec, (tuple, list)):\n return 'spec_{}'.format(ispec)\n else:\n print( type(spec))\n atoms = self._trajectory.atoms\n volume = atoms.get_volume()\n positions = self._trajectory.get_positions()\n chem_sym = np.array(atoms.get_chemical_symbols(), dtype=str)\n cell = np.array(atoms.cell)\n a, b, c = cell\n range_ = list(range(0,2))\n corners = [i*a+j*b + k*c for i in range_ for j in range_ for k in range_]\n cellI = np.linalg.inv(cell)\n\n if istop is None:\n istop = len(positions)\n if species_pairs is None:\n species_pairs = list(itertools.combinations_with_replacement(set(atoms.get_chemical_symbols()), 2))\n indices_pairs = []\n labels = []\n species_pairs_pruned = []\n for ispec, (spec1, spec2) in enumerate(species_pairs):\n ind_spec1, ind_spec2 = get_indices(spec1, chem_sym), get_indices(spec2, chem_sym)\n # special situation if there's only one atom of a species\n # and we're making the RDF of that species with itself.\n # there will be empty pairs_of_atoms and the code below would crash!\n if ind_spec1==ind_spec2 and len(ind_spec1) ==1:\n continue\n indices_pairs.append((ind_spec1, ind_spec2))\n labels.append('{}_{}'.format(get_label(spec1, ispec), get_label(spec2, ispec)))\n species_pairs_pruned.append((spec1, spec2))\n rdf_res = AttributedArray()\n rdf_res.set_attr('species_pairs', species_pairs_pruned)\n binsize=float(radius)/nbins\n for label, (ind1, ind2) in zip(labels, indices_pairs):\n if ind1==ind2:\n # lists are equal, I will therefore not double calculate\n pairs_of_atoms = [(i,j) for i in ind1 for j in ind2 if i<j]\n pair_factor = 2.0\n else:\n pairs_of_atoms = [(i,j) for i in ind1 for j in ind2 if i!=j]\n pair_factor = 1.0\n # It can happen that pairs_of_atoms\n ind_pair1, ind_pair2 = list(zip(*pairs_of_atoms))\n diff_real_unwrapped = (positions[istart:istop:stepsize, ind_pair2, :] - positions[istart:istop:stepsize, ind_pair1, :]).reshape(-1, 3)\n density = float(len(ind2)) / volume\n diff_crystal_wrapped = np.dot(diff_real_unwrapped, cellI) % 1.0\n diff_real_wrapped = np.dot(diff_crystal_wrapped, cell)\n\n shortest_distances = cdist(diff_real_wrapped, corners).min(axis=1)\n\n hist, bin_edges = np.histogram(shortest_distances, bins=nbins, range=(0,radius))\n radii = 0.5*(bin_edges[:-1]+bin_edges[1:])\n\n # now I need to normalize the histogram, by the number of steps taken, and the number of species1\n hist = hist *pair_factor / float(len(np.arange(istart, istop, stepsize))) / float(len(ind1))\n\n rdf = hist / (4.0 * np.pi * radii**2 * binsize ) / (len(ind2)/volume)\n integral = np.empty(len(rdf))\n sum_ = 0.0\n for i in range(len(integral)):\n sum_ += hist[i]\n integral[i] = sum_\n\n rdf_res.set_array('rdf_{}'.format(label), rdf)\n rdf_res.set_array('int_{}'.format(label), integral)\n rdf_res.set_array('radii_{}'.format(label), radii)\n\n return rdf_res\n\nclass AngularSpectrum(BaseAnalyzer):\n def run(self, radius=None, species_pairs=None, istart=1, istop=None, stepsize=1, nbins=100):\n \"\"\"\n :param float radius: The radius for the calculation of the RDF\n :param float density: The grid density. The number of bins is given by radius/density\n \"\"\"\n atoms = self._trajectory.atoms\n volume = atoms.get_volume()\n positions = self._trajectory.get_positions()\n if istop is None:\n istop = len(positions)\n if species_pairs is None:\n species_pairs = list(itertools.combinations_with_replacement(set(atoms.get_chemical_symbols()), 3))\n cell = np.array(atoms.cell)\n cellI = np.linalg.inv(cell)\n chem_sym = np.array(atoms.get_chemical_symbols(), dtype=str)\n rdf_res = AttributedArray()\n rdf_res.set_attr('species_pairs', species_pairs)\n for spec1, spec2, spec3 in species_pairs:\n ind1 = np.where(chem_sym == spec1)[0] + 1 # +1 for fortran indexing\n ind2 = np.where(chem_sym == spec2)[0] + 1\n ind3 = np.where(chem_sym == spec3)[0] + 1\n angular_spec, angles = calculate_angular_spec(positions, istart, istop, stepsize,\n radius, cell, cellI, ind1, ind2, ind3, nbins)\n rdf_res.set_array('aspec_{}_{}_{}'.format(spec1, spec2, spec3), angular_spec)\n rdf_res.set_array('angles_{}_{}_{}'.format(spec1, spec2, spec3), angles)\n return rdf_res\n" ]
[ [ "numpy.dot", "numpy.linalg.inv", "numpy.arange", "scipy.spatial.distance.cdist", "numpy.array", "numpy.histogram", "numpy.where" ] ]
lcl1026504480/network
[ "cf1175aa0377a4145e9a5dda2031259ef3d662c4" ]
[ "sgd_numpy.py" ]
[ "# -*- coding: utf-8 -*-\n# @Author: lenovouser\n# @Date: 2020-09-30 16:54:52\n# @Last Modified by: lenovouser\n# @Last Modified time: 2020-09-30 16:54:54\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 29 14:42:21 2020\n\n@author: lenovouser\n\"\"\"\nimport numpy as np\n\nfrom matplotlib import pyplot as plt\n\n\nclass nn:\n def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate):\n\n self.innodes = inputnodes\n self.hidnodes = hiddennodes\n self.outnodes = outputnodes\n\n self.train_e = [0]\n self.valid_e = [0]\n\n self.wih = np.random.normal(0, pow(self.hidnodes, -0.5),\n (self.hidnodes, self.innodes))\n\n self.who = np.random.normal(0,\n pow(self.outnodes, -0.5),\n (self.outnodes, self.hidnodes))\n\n self.acfun = lambda x: 1 / (1 + np.exp(-1 * x))\n\n def sgd_train(self, indexs, train_data_list):\n\n dwho = np.zeros([batch_size, self.who.shape[0], self.who.shape[1]])\n dwih = np.zeros([batch_size, self.wih.shape[0], self.wih.shape[1]])\n c = 0\n for l in train_data_list[indexs]:\n\n all_values = l.split(\",\")\n inputs = (np.asfarray(all_values[1:]) / 255 * 0.98) + 0.01\n targets = np.zeros(outputnodes) + 0.01\n targets[int(all_values[0])] = 0.99\n\n inputs = np.array(inputs, ndmin=2).T\n target_list = np.array(targets, ndmin=2).T\n\n hiddeninput = np.dot(self.wih, inputs)\n hidden_output = self.acfun(hiddeninput)\n\n outinput = np.dot(self.who, hidden_output)\n output = self.acfun(outinput)\n\n errors = target_list - output\n herrors = np.dot(self.who.T, errors * output * (1 - output))\n self.train_e[-1] += np.sum(errors**2)\n\n dwho[c] = np.dot(errors * output * (1 - output),\n hidden_output.T)\n\n dwih[c] = np.dot(herrors * hidden_output * (1 - hidden_output),\n inputs.T)\n c += 1\n\n self.who += self.lr * dwho.mean(0)\n self.wih += self.lr * dwih.mean(0)\n\n def query(self, inputs):\n inputs = np.array(inputs, ndmin=2).T\n hiddeninput = np.dot(self.wih, inputs)\n hidden_output = self.acfun(hiddeninput)\n\n outinput = np.dot(self.who, hidden_output)\n output = self.acfun(outinput)\n\n return output\n\n\ninputnodes = 28 * 28\nhiddennodes = 300\noutputnodes = 10\n\nlearningrate = 0.1\nbatch_size = 5\n\nn = nn(inputnodes, hiddennodes, outputnodes, learningrate)\ntrain_data_file = open(\"mnist_train_100.csv\", \"r\")\nnum = 100\ntrain_num = int(num * 0.6)\n\ntrain_data_list = train_data_file.readlines()\ntrain_data_file.close()\n\nepoch = 10\nfor i in range(epoch):\n rn = np.random.permutation(num)\n train_data_list = np.array(train_data_list)\n rn = rn.reshape(-1, batch_size)\n\n n.lr = learningrate * np.exp(-i * 0.1)\n for l in range(train_num // batch_size):\n n.sgd_train(rn[l], train_data_list)\n\n n.train_e.append(0)\n\n for l in train_data_list[rn[train_num // batch_size]]:\n all_values = l.split(\",\")\n inputs = (np.asfarray(all_values[1:]) / 255 * 0.98) + 0.01\n targets = np.zeros(outputnodes) + 0.01\n targets[int(all_values[0])] = 0.99\n\n n.valid_e[-1] += np.sum((targets - n.query(inputs))**2)\n n.valid_e.append(0)\n\nn.train_e = np.array(n.train_e[:epoch]) / train_num * batch_size\nn.valid_e = np.array(n.valid_e[:epoch]) / (num - train_num) * batch_size\nx = list(range(epoch))\n\nplt.plot(x, n.train_e, color='r', label=\"train\")\nplt.plot(x, n.valid_e, color=\"b\", label=\"valid\")\nplt.legend()\nplt.show()\ntest_data_file = open(\"mnist_test_10.csv\", \"r\")\ntest_data_list = test_data_file.readlines()\ntest_data_file.close()\nscore = []\nfor l in test_data_list:\n all_values = l.split(\",\")\n # print(all_values)\n label = int(all_values[0])\n inputs = (np.asfarray(all_values[1:]) / 255 * 0.98) + 0.01\n outputs = n.query(inputs)\n if label == outputs.argmax():\n score.append(1)\n else:\n score.append(0)\nprint(sum(score) / len(score))\n" ]
[ [ "matplotlib.pyplot.legend", "numpy.dot", "matplotlib.pyplot.plot", "numpy.asfarray", "numpy.random.permutation", "numpy.exp", "numpy.array", "numpy.zeros", "numpy.sum", "matplotlib.pyplot.show" ] ]
msteptoe/gcam_vis
[ "b02fa0a2421ef107d03b69bf9361c591f45dd61f" ]
[ "python/mini_kmeans_1.py" ]
[ "import sys\nimport numpy as np\nimport os\nimport warnings\n\nfrom sklearn.cluster import MiniBatchKMeans\nfrom json import dump\n\n\ndef mainFunc(): \n warnings.filterwarnings(\"ignore\")\n\n jobPath = \"jobs\" + os.path.sep + \"test\"\n query = 'Building floorspace' + os.path.sep + 'building' + os.path.sep + 'comm'\n dataType = 'QueryVectors'\n # print(len(sys.argv))\n if len(sys.argv) > 3 and sys.argv[3]:\n dataType = sys.argv[3]\n if len(sys.argv) > 2 and sys.argv[1]:\n jobPath = sys.argv[1]\n query = sys.argv[2]\n\n\n f = open(jobPath + os.path.sep + 'Files.json', 'r')\n files = eval(f.read())\n f.close()\n\n\n X = []\n for f in files:\n fOpen = open(jobPath + os.path.sep + dataType + os.path.sep + query + os.path.sep + f, 'r')\n X.append(eval(fOpen.read()))\n fOpen.close()\n X = np.array(X)\n n_clusters = 8\n kmeans = MiniBatchKMeans(n_clusters=n_clusters, random_state=0).fit(X)\n dump(kmeans.labels_.tolist(), open(jobPath + os.path.sep + 'ClusterAssignments' + os.path.sep + query + os.path.sep + \"k\" + str(n_clusters) + \".json\", \"w\"))\n\nif __name__ == '__main__':\n mainFunc()\n" ]
[ [ "sklearn.cluster.MiniBatchKMeans", "numpy.array" ] ]
Coslate/DataMining_Final
[ "1c2519874b1005c68d97aa1003984b1f3bd936a2" ]
[ "Preprocess_FeatureExtraction_GamePrediction/nbaDataPreprocessing.py" ]
[ "##############################################\n## Author: I-No Liao ##\n## Date of update: 2018/05/15 ##\n## Description: Data Mining Final Project ##\n## - Data Preprocessing ##\n## - Remove NaN ##\n## - Add opponent label ##\n## - Binary encode W/L and Home/Away ##\n## - Pair teams and opponents ##\n## - Check games' validity ##\n## - Rename and concatenate df ##\n##############################################\n\nimport numpy as np\nimport pandas as pd\nimport time\n\n\n\n#-----------------------#\n# Main Function #\n#-----------------------#\n\n# @param: None\n# @return: None\ndef main():\n startTime = time.time()\n \n # Load .csv\n season = pd.read_csv('./team_season_all.csv')\n playoff = pd.read_csv('./team_playoff_all.csv')\n \n # Merge seasona and playoff\n df_all = pd.concat([season, playoff], ignore_index=True)\n \n # Remove NaN\n df_all = cleanDataFrame(df_all)\n df_all = dropNanScore(df_all)\n \n # Add opponent label\n df_all = addOpponentCol(df_all)\n \n # Binary encode W/L and Home/Away\n df_all['W/L'] = df_all['W/L'].map({'W':1, 'L':0})\n df_all['Home/Away'] = df_all['Home/Away'].map({'Home':1, 'Away':0})\n \n # Pair teams and opponents\n df_team, df_oppo, invalid_idx = pairGamePlayers(df_all)\n \n # Check games' validity\n df_team, df_oppo, invalid_idx = checkGameValidity(df_team, df_oppo)\n \n # Rename column: Attributes_A and Attributes_B for team and opponent, respectively\n df_team = df_team.rename(columns=lambda x: x + '_A')\n df_oppo = df_oppo.rename(columns=lambda x: x + '_B')\n \n # Concatenate by column\n df_output = pd.concat([df_team, df_oppo], axis=1)\n \n # Save .csv\n df_output.to_csv('./nba_preprocessed.csv', encoding='utf-8', index=False)\n \n print(\"Execution time =\", time.time() - startTime)\n\n\n\n#-----------------------#\n# Sub-Functions #\n#-----------------------#\n\n# @param df: pandas.DataFrame\n# @return pandas.DataFrame\n# NaN cleaner (Numerical)\ndef cleanDataFrame(df):\n assert isinstance(df, pd.DataFrame), \"df needs to be a pd.DataFrame\"\n df.dropna(inplace=True)\n indices_to_keep = ~df.isin([np.nan, np.inf, -np.inf]).any(1)\n return df[indices_to_keep].reset_index(drop=True)\n\n# @param df: pandas.DataFrame\n# @return pandas.DataFrame\n# Drop objects which are NaN in Score's label (String)\ndef dropNanScore(df):\n index = []\n for idx, score in enumerate(df['Score']):\n if score[:3] == 'NAN' or score[:3] == 'NaN':\n index.append(idx)\n print(\"Number of objects dropped =\", len(index))\n return df.drop(df.index[index]).reset_index(drop=True)\n\n# @param df: pandas.DataFrame\n# @return df: pandas.DataFrame\n# Add opponent label to a game\ndef addOpponentCol(df):\n opponent = [None] * len(df['Score'])\n for idx, score in enumerate(df['Score']):\n opponent[idx] = score[:3]\n df['Opponent'] = opponent\n return df\n\n# @param df: pandas.DataFrame\n# @return df_team, df_oppo: pandas.DataFrame\n# Pair two teams in a single game by searching 'Date' and 'Opponent' labels.\ndef pairGamePlayers(df): \n startTime = time.time()\n invalid_idx = []\n duplicate = 0\n not_found = 0\n # Declare empty dataframe w/ columns from existing dataframe\n df_team = pd.DataFrame(columns = list(df)) # Team attributes\n df_oppo = pd.DataFrame(columns = list(df)) # Opponent attributes\n df_dupl = pd.DataFrame(columns = list(df)) # Duplicated dataframe\n for idx, date, team in zip(df.index.tolist(), df['Date'], df['Team']):\n df_oppo_searched = df.loc[lambda df: df.Date == date, :].loc[lambda df: df.Opponent == team, :]\n if len(df_oppo_searched.index.tolist()) > 1:\n duplicate += 1\n df_dupl = pd.concat([df_dupl, df_oppo_searched], ignore_index=True)\n df_oppo_searched = df_oppo_searched.iloc[0:1, :]\n if not df_oppo_searched.empty:\n df_team = pd.concat([df_team, df.iloc[idx:idx+1, :]], ignore_index=True)\n df_oppo = pd.concat([df_oppo, df_oppo_searched], ignore_index=True)\n else:\n invalid_idx.append(idx)\n not_found += 1\n \n print(\"Duplicate found =\", duplicate)\n print(\"Opponent not found =\", not_found)\n print(\"Team length = \", len(df_team.index.tolist()))\n print(\"Oppo length = \", len(df_oppo.index.tolist()))\n print(\"Execution time =\", time.time() - startTime)\n return df_team, df_oppo, invalid_idx\n\n# @param df_team, df_oppo: pandas.DataFrame\n# @return df_team, df_oppo: pandas.DataFrame\n# Check game validity after pairGamePlayers(df) which pairs two teams in a single game.\ndef checkGameValidity(df_team, df_oppo):\n startTime = time.time()\n err = 0\n invalid_idx = []\n print(\"Team length = \", len(df_team.index.tolist()))\n print(\"Oppo length = \", len(df_oppo.index.tolist()))\n for idx in df_team.index.tolist():\n if df_team.loc[idx]['Date'] != df_oppo.loc[idx]['Date'] or \\\n df_team.loc[idx]['Opponent'] != df_oppo.loc[idx]['Team'] or \\\n df_team.loc[idx]['W/L'] == df_oppo.loc[idx]['W/L'] or \\\n df_team.loc[idx]['Home/Away'] == df_oppo.loc[idx]['Home/Away']:\n err += 1\n invalid_idx.append(idx)\n \n df_team = df_team.drop(df_team.index[invalid_idx]).reset_index(drop=True)\n df_oppo = df_oppo.drop(df_oppo.index[invalid_idx]).reset_index(drop=True)\n \n print(\"Number of invalid games =\", err, \"@\", [x for x in invalid_idx])\n print(\"Execution time =\", time.time() - startTime)\n return df_team, df_oppo, invalid_idx\n\n\n\n#-----------------------#\n# Execution #\n#-----------------------#\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "pandas.concat", "pandas.read_csv" ] ]
ashok-kollipara/multistrike-oi
[ "9ff3a792c22257aad6d5e635e1144a0f18d468a6" ]
[ "tkplot.py" ]
[ "import matplotlib\r\nimport matplotlib.pyplot as plt\r\n#import matplotlib.ticker as ticker\r\nimport matplotlib.animation as animate\r\nfrom matplotlib.figure import Figure\r\nfrom matplotlib.backends.backend_tkagg import (\r\n FigureCanvasTkAgg,\r\n NavigationToolbar2Tk\r\n )\r\n\r\nimport db_actions as db\r\nimport os\r\n\r\n\r\nmatplotlib.use('TkAgg')\r\n\r\nax = None\r\n#expiry_date, contract1, contract2, index = None, None, None, None\r\n\r\n'''\r\ndef init_plot(index, expiry_date, contract1, contract2):\r\n\r\n db.populate_db(index, expiry_date, contract1, contract2)\r\n\r\n time_stamp, strike1_oi, strike2_oi = db.fetch_data()\r\n\r\n ax.plot(time_stamp, strike1_oi, label=f'{contract1}', color='orange')\r\n ax.plot(time_stamp, strike2_oi, label=f'{contract2}', color='purple')\r\n ax.scatter([time_stamp[-1]], [strike1_oi[-1]], marker='o', color='orange')\r\n ax.scatter([time_stamp[-1]], [strike2_oi[-1]], marker='o', color='purple')\r\n ax.legend()\r\n\r\n return\r\n'''\r\n\r\ndef draw_plot(index, expiry_date, contract1, contract2):\r\n\r\n db.populate_db(index, expiry_date, contract1, contract2)\r\n\r\n time_stamp, strike1_oi, strike2_oi= db.fetch_data()\r\n\r\n ax.cla()\r\n\r\n #ax.xaxis.set_major_locator(ticker.MultipleLocator(5))\r\n\r\n ax.tick_params(axis='x', rotation=70)\r\n\r\n ax.plot(time_stamp, strike1_oi, label=f'{contract1}', color='orange')\r\n ax.plot(time_stamp, strike2_oi, label=f'{contract2}', color='purple')\r\n ax.scatter([time_stamp[-1]], [strike1_oi[-1]], marker='o', color='orange')\r\n ax.scatter([time_stamp[-1]], [strike2_oi[-1]], marker='o', color='purple')\r\n\r\n ax.legend()\r\n\r\n return\r\n\r\n\r\ndef main(plotframe, index_chosen, expiry_chosen, strike1, strike2):\r\n\r\n '''\r\n global ax\r\n global contract1\r\n global contract2\r\n global expiry_date\r\n global index\r\n\r\n contract1 = strike_contract1\r\n contract2 = strike_contract2\r\n expiry_date = expiry\r\n index = index_chosen\r\n\r\n # figure size = 5 inches x 5 inches with dpi of 100\r\n # this makes size 900 x 500 pixels\r\n #figure = Figure(figsize=(9,5), dpi=100)\r\n figure = Figure(dpi=100)\r\n\r\n # connect figure to Tkinter Canvas\r\n figure_canvas = FigureCanvasTkAgg(figure, plotframe)\r\n figure_canvas.draw()\r\n\r\n ax = figure.add_subplot(1,1,1)\r\n\r\n #Place navigation tool bar on figure_canvas\r\n #Toggle placement with pack_toolbar argument\r\n toolbar = NavigationToolbar2Tk(figure_canvas, plotframe, pack_toolbar=False)\r\n toolbar.update()\r\n\r\n #place subplot on plotframe\r\n wid = figure_canvas.get_tk_widget()\r\n wid.pack(side='top', fill='both',expand=True)\r\n\r\n file_path= os.getcwd() +'\\\\'+ 'multistrike_oi.db'\r\n\r\n #os.system('cls')\r\n '''\r\n\r\n global ax\r\n\r\n #get the axes of the subplot on figure for manipulation\r\n ax = plt.subplot(1,1,1)\r\n\r\n\r\n #animation for live plotting\r\n ani = animate.FuncAnimation(\r\n plt.gcf(),\r\n lambda _ : draw_plot(\r\n index_chosen,\r\n expiry_chosen,\r\n strike1,\r\n strike2\r\n ),\r\n interval=300000\r\n )\r\n\r\n\r\n plt.show()\r\n #return figure, figure_canvas\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n main(plotframe, expiry, strike_contract1, strike_contract2)\r\n" ]
[ [ "matplotlib.use", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "matplotlib.pyplot.gcf" ] ]
CNES/zcollection
[ "f14616944d92d799cb1e5ee783b44c3819344fc2" ]
[ "zcollection/partitioning/date.py" ]
[ "# Copyright (c) 2022 CNES\n#\n# All rights reserved. Use of this source code is governed by a\n# BSD-style license that can be found in the LICENSE file.\n\"\"\"\nPartitioning by date\n====================\n\"\"\"\nfrom typing import Any, ClassVar, Dict, Iterator, Sequence, Tuple\n\nimport dask.array.core\nimport numpy\n\nfrom . import abc\n\n#: Numpy time units\nRESOLUTION = (\"Y\", \"M\", \"D\", \"h\", \"m\", \"s\")\n\n#: Numpy time unit meanings\nUNITS = (\"year\", \"month\", \"day\", \"hour\", \"minute\", \"second\")\n\n#: Data type for time units\nDATA_TYPES = (\"uint16\", \"uint8\", \"uint8\", \"uint8\", \"uint8\", \"uint8\")\n\n#: Time separation units\nSEPARATORS = dict(year=\"-\",\n month=\"-\",\n day=\"T\",\n hour=\":\",\n minute=\":\",\n second=\".\")\n\n\nclass Date(abc.Partitioning):\n \"\"\"Date partitioning.\n\n Args:\n variables: Variable names used for the partitioning.\n resolution: Time resolution of the partitioning.\n\n Raises:\n ValueError: If the resolution is not in the list of supported\n resolutions or if the partitioning is not performed on a one\n dimensional variable.\n\n Example:\n >>> partitioning = Date(variables=(\"time\", ), resolution=\"Y\")\n \"\"\"\n __slots__ = (\"_attrs\", \"_index\", \"resolution\")\n\n #: The ID of the partitioning scheme\n ID: ClassVar[str] = \"Date\"\n\n def __init__(self, variables: Sequence[str], resolution: str) -> None:\n if len(variables) != 1:\n raise ValueError(\n \"Partitioning on dates is performed on a single variable.\")\n if resolution not in RESOLUTION:\n raise ValueError(\"resolution must be in: \" + \", \".join(RESOLUTION))\n index = RESOLUTION.index(resolution) + 1\n\n #: The time resolution of the partitioning\n self.resolution = resolution\n #: The time parts used for the partitioning\n self._attrs = UNITS[:index + 1]\n #: The indices of the time parts used for the partitioning\n self._index = tuple(range(index))\n super().__init__(variables,\n tuple(DATA_TYPES[ix] for ix in self._index))\n\n def _keys(self) -> Sequence[str]:\n \"\"\"Return the keys of the partitioning scheme.\"\"\"\n return tuple(UNITS[ix] for ix in self._index)\n\n # pylint: disable=arguments-differ\n # False positive: the base method is static.\n def _partition(\n self,\n selection: Tuple[Tuple[str, Any], ...],\n ) -> Tuple[str, ...]:\n \"\"\"Return the partitioning scheme for the given selection.\"\"\"\n _, datetime64 = selection[0]\n datetime = datetime64.astype(\"M8[s]\").item()\n return tuple(UNITS[ix] + \"=\" +\n f\"{getattr(datetime, self._attrs[ix]):02d}\"\n for ix in self._index)\n # pylint: enable=arguments-differ\n\n def _split(\n self,\n variables: Dict[str, dask.array.core.Array],\n ) -> Iterator[abc.Partition]:\n \"\"\"Return the partitioning scheme for the given variables.\"\"\"\n name, values = tuple(variables.items())[0]\n\n if not numpy.issubdtype(values.dtype, numpy.dtype(\"datetime64\")):\n raise TypeError(\"values must be a datetime64 array\")\n\n index, indices = abc.unique(\n values.astype(f\"datetime64[{self.resolution}]\"))\n\n # We don't use here the function `numpy.diff` but `abc.difference` for\n # optimization purposes.\n if not numpy.all(\n abc.difference(index.view(numpy.int64)) >= 0): # type: ignore\n raise ValueError(\"index is not monotonic\")\n\n indices = abc.concatenate_item(indices, values.size)\n\n return ((((name, date), ), slice(start, indices[ix + 1], None))\n for date, (ix, start) in zip(index, enumerate(indices[:-1])))\n\n @staticmethod\n def _stringify(partition: Tuple[Tuple[str, int], ...]) -> str:\n \"\"\"Return a string representation of the partitioning scheme.\"\"\"\n string = \"\".join(f\"{value:02d}\" + SEPARATORS[item]\n for item, value in partition)\n if string[-1] in SEPARATORS.values():\n string = string[:-1]\n return string\n\n @staticmethod\n def join(partition_scheme: Tuple[Tuple[str, int], ...], sep: str) -> str:\n \"\"\"Join a partitioning scheme.\n\n Args:\n partition_scheme: The partitioning scheme to be joined.\n sep: The separator to be used.\n\n Returns:\n The joined partitioning scheme.\n\n Example:\n >>> partitioning = Date(variables=(\"time\", ), resolution=\"D\")\n >>> partitioning.join(((\"year\", 2020), (\"month\", 1), (\"day\", 1)),\n ... \"/\")\n 'year=2020/month=01/day=01'\n \"\"\"\n return sep.join(f\"{k}={v:02d}\" for k, v in partition_scheme)\n\n def encode(\n self,\n partition: Tuple[Tuple[str, int], ...],\n ) -> Tuple[numpy.datetime64]:\n \"\"\"Encode a partitioning scheme.\n\n Args:\n partition: The partitioning scheme to be encoded.\n\n Returns:\n The encoded partitioning scheme.\n\n Example:\n >>> partitioning = Date(variables=(\"time\", ), resolution=\"D\")\n >>> fields = partitioning.parse(\"year=2020/month=01/day=01\")\n >>> fields\n ((\"year\", 2020), (\"month\", 1), (\"day\", 1))\n >>> partitioning.encode(fields)\n (numpy.datetime64('2020-01-01'),)\n \"\"\"\n return tuple((numpy.datetime64(self._stringify(partition)), ))\n\n def decode(\n self,\n values: Tuple[numpy.datetime64],\n ) -> Tuple[Tuple[str, int], ...]:\n \"\"\"Decode a partitioning scheme.\n\n Args:\n values: The partitioning scheme to be decoded.\n\n Returns:\n The decoded partitioning scheme.\n\n Example:\n >>> partitioning = Date(variables=(\"time\", ), resolution=\"D\")\n >>> partitioning.decode((numpy.datetime64('2020-01-01'), ))\n ((\"year\", 2020), (\"month\", 1), (\"day\", 1))\n \"\"\"\n datetime64, = values\n datetime = datetime64.astype(\"M8[s]\").item()\n return tuple((UNITS[ix], getattr(datetime, self._attrs[ix]))\n for ix in self._index)\n" ]
[ [ "numpy.dtype" ] ]
xiaohangcd/PPDM
[ "9b7c9161a3d94a2b57d927b347810da105a74e61" ]
[ "src/lib/models/decode.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nfrom .utils import _gather_feat, _tranpose_and_gather_feat\nimport numpy as np\n\n\ndef _nms(heat, kernel=3):\n pad = (kernel - 1) // 2\n\n hmax = nn.functional.max_pool2d(\n heat, (kernel, kernel), stride=1, padding=pad)\n keep = (hmax == heat).float()\n return heat * keep\n\n\ndef _topk(scores, K=40):\n batch, cat, height, width = scores.size()\n\n topk_scores, topk_inds = torch.topk(scores.view(batch, cat, -1), K)\n\n topk_inds = topk_inds % (height * width)\n topk_ys = (topk_inds / width).int().float()\n topk_xs = (topk_inds % width).int().float()\n\n topk_score, topk_ind = torch.topk(topk_scores.view(batch, -1), K)\n topk_clses = (topk_ind / K).int()\n topk_inds = _gather_feat(\n topk_inds.view(batch, -1, 1), topk_ind).view(batch, K)\n topk_ys = _gather_feat(topk_ys.view(batch, -1, 1), topk_ind).view(batch, K)\n topk_xs = _gather_feat(topk_xs.view(batch, -1, 1), topk_ind).view(batch, K)\n\n return topk_score, topk_inds, topk_clses, topk_ys, topk_xs\n\n\ndef match_rel_box(rel, bbox, K_rel, K_bbox):\n rel = rel.view(K_rel, 1)\n rel = rel.repeat(1, K_bbox)\n bbox = bbox.view(1, K_bbox)\n bbox = bbox.repeat(K_rel, 1)\n dis_mat = abs(rel - bbox)\n return dis_mat\n\n\ndef hoidet_decode(heat_obj, wh, heat_rel, offset_sub, offset_obj, reg=None, corremat=None, K_obj=100, K_human=100,\n K_rel=100, is_sub_verb=0):\n batch, cat_obj, height, width = heat_obj.size()\n heat_obj = _nms(heat_obj)\n heat_rel = _nms(heat_rel)\n heat_human = heat_obj[:, 0, :, :].view(batch, 1, height, width)\n\n scores_obj, inds_obj, clses_obj, ys_obj, xs_obj = _topk(heat_obj, K=K_obj)\n scores_obj = scores_obj.view(batch, K_obj, 1)\n clses_obj = clses_obj.view(batch, K_obj, 1).float()\n\n scores_human, inds_human, clses_human, ys_human, xs_human = _topk(heat_human, K=K_human)\n scores_human = scores_human.view(batch, K_human, 1)\n clses_human = clses_human.view(batch, K_human, 1).float()\n\n scores_rel, inds_rel, clses_rel, ys_rel, xs_rel = _topk(heat_rel, K=K_rel)\n scores_rel = scores_rel.view(batch, K_rel, 1)\n clses_rel = clses_rel.view(batch, K_rel, 1).float()\n\n offset_sub = _tranpose_and_gather_feat(offset_sub, inds_rel)\n offset_sub = offset_sub.view(batch, K_rel, 2)\n dist_sub_xs = xs_rel.view(batch, K_rel, 1) - offset_sub[:, :, 0:1]\n dist_sub_ys = ys_rel.view(batch, K_rel, 1) - offset_sub[:, :, 1:2]\n match_sub_xs = match_rel_box(dist_sub_xs, xs_human.view(batch, K_human, 1), K_rel, K_human)\n match_sub_ys = match_rel_box(dist_sub_ys, ys_human.view(batch, K_human, 1), K_rel, K_human)\n\n offset_obj = _tranpose_and_gather_feat(offset_obj, inds_rel)\n offset_obj = offset_obj.view(batch, K_rel, 2)\n dist_obj_xs = xs_rel.view(batch, K_rel, 1) - offset_obj[:, :, 0:1]\n dist_obj_ys = ys_rel.view(batch, K_rel, 1) - offset_obj[:, :, 1:2]\n match_obj_xs = match_rel_box(dist_obj_xs, xs_obj.view(batch, K_obj, 1), K_rel, K_obj)\n match_obj_ys = match_rel_box(dist_obj_ys, ys_obj.view(batch, K_obj, 1), K_rel, K_obj)\n\n if corremat is not None:\n this_corremat = corremat[clses_rel.view(K_rel).long(), :]\n this_corremat = this_corremat[:, clses_obj.view(K_obj).long()]\n else:\n this_corremat = np.ones((K_rel, K_obj))\n\n dis_sub_score = (1 / (match_sub_xs + 1)) * (1 / (match_sub_ys + 1)) * (\n (scores_human.view(1, K_human).repeat(K_rel, 1)))\n sub_rel_ids = torch.argmax(dis_sub_score, dim=1)\n sub_scores_rel = (scores_human.view(K_human))[sub_rel_ids.long()]\n dis_obj_score = (1 / (match_obj_xs + 1)) * (1 / (match_obj_ys + 1)) * ((scores_obj.view(1, K_obj).repeat(K_rel, 1)))\n dis_obj_score = dis_obj_score * this_corremat\n obj_rel_ids = torch.argmax(dis_obj_score, dim=1)\n obj_scores_rel = (scores_obj.view(K_obj))[obj_rel_ids.long()]\n score_hoi = sub_scores_rel * obj_scores_rel * (scores_rel.view(K_rel))\n hoi_triplet = (torch.cat((sub_rel_ids.view(K_rel, 1).float(), obj_rel_ids.view(K_rel, 1).float(),\n clses_rel.view(K_rel, 1).float(), score_hoi.view(K_rel, 1)), 1)).cpu().numpy()\n hoi_triplet = hoi_triplet[np.argsort(-hoi_triplet[:, -1])]\n _, u_hoi_id = np.unique(hoi_triplet[:, [0, 1, 2]], axis=0, return_index=True)\n rel_triplet = hoi_triplet[u_hoi_id]\n if reg is not None:\n reg_obj = _tranpose_and_gather_feat(reg, inds_obj)\n reg_obj = reg_obj.view(batch, K_obj, 2)\n\n reg_human = _tranpose_and_gather_feat(reg, inds_human)\n reg_human = reg_human.view(batch, K_human, 2)\n\n xs_human = xs_human.view(batch, K_human, 1) + reg_human[:, :, 0:1]\n ys_human = ys_human.view(batch, K_human, 1) + reg_human[:, :, 1:2]\n xs_obj = xs_obj.view(batch, K_obj, 1) + reg_obj[:, :, 0:1]\n ys_obj = ys_obj.view(batch, K_obj, 1) + reg_obj[:, :, 1:2]\n wh_human = _tranpose_and_gather_feat(wh, inds_human)\n wh_obj = _tranpose_and_gather_feat(wh, inds_obj)\n wh_obj = wh_obj.view(batch, K_obj, 2)\n wh_human = wh_human.view(batch, K_human, 2)\n\n obj_bboxes = torch.cat([xs_obj - wh_obj[..., 0:1] / 2,\n ys_obj - wh_obj[..., 1:2] / 2,\n xs_obj + wh_obj[..., 0:1] / 2,\n ys_obj + wh_obj[..., 1:2] / 2], dim=2)\n\n obj_detections = torch.cat([obj_bboxes, scores_obj, clses_obj], dim=2)\n\n human_bboxes = torch.cat([xs_human - wh_human[..., 0:1] / 2,\n ys_human - wh_human[..., 1:2] / 2,\n xs_human + wh_human[..., 0:1] / 2,\n ys_human + wh_human[..., 1:2] / 2], dim=2)\n if is_sub_verb > 0:\n clses_human[:] = 0.0\n human_detections = torch.cat([human_bboxes, scores_human, clses_human], dim=2)\n\n return obj_detections, human_detections, rel_triplet\n" ]
[ [ "numpy.unique", "torch.cat", "numpy.ones", "numpy.argsort", "torch.nn.functional.max_pool2d", "torch.argmax" ] ]
allengueco/message_patterns
[ "0d50550187dad9fd08bacc0ff47da1fffadb1937" ]
[ "generate_graphs.py" ]
[ "import pandas as pd\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nimport seaborn as sns\nimport sys\nimport nltk\nfrom textblob import TextBlob\nfrom wordcloud import WordCloud\n\nif len(sys.argv) != 3:\n print(\"Error: Usage is 'py generate_graphs.py <filename> <context>'\")\n \nPATH_TO_CSV = sys.argv[1]\nCONTEXT = sys.argv[2]\n\nmessages = pd.read_csv(PATH_TO_CSV, index_col=0, parse_dates=['date'])\nreceiver = messages[messages.is_from_me == 0]\nsender = messages[messages.is_from_me == 1]\n\nNUM_PERIODS = (max(messages.date) - min(messages.date)).days // 7 + 2\n\nWEEKLY_DATE_RANGE = pd.date_range(\n start=pd.to_datetime(min(messages['date']).strftime(\"%Y-%m-%d\")), \n periods=NUM_PERIODS,\n freq='W-MON')\n\nplt.style.use(CONTEXT)\n\ndef messages_pchart():\n num_messages = len(messages)\n num_receiver_messages = len(receiver)\n num_sender_messages = len(sender)\n \n def _format_pie_label(pct):\n total = int(pct/100 * num_messages)\n return f\"{total} messages \\n({pct:.2f}%)\"\n \n fig, ax = plt.subplots(figsize=(10,10))\n ax.set_aspect('equal')\n \n ax.pie([num_receiver_messages, num_sender_messages],\n labels=['receiver', 'sender'],\n autopct=lambda num: _format_pie_label(num),\n startangle=90,\n shadow=True)\n ax.set_title(\"Who has sent more messages?\")\n \n return fig\n\ndef weekly_texts():\n\n receiver_wtext = [receiver.week[receiver.week == i].count() for i in range(NUM_PERIODS)]\n sender_wtext = [sender.week[sender.week == i ].count() for i in range(NUM_PERIODS)]\n xlabels = [date.strftime(\"%b %d\") for date in WEEKLY_DATE_RANGE]\n bar_width = 0.4\n\n fig, ax = plt.subplots(figsize=(12,10))\n ax.set_aspect('auto')\n \n rects1 = ax.bar(np.arange(NUM_PERIODS), receiver_wtext, bar_width, label=\"Receiver\")\n rects2 = ax.bar(np.arange(NUM_PERIODS)+bar_width, sender_wtext, bar_width, label=\"Sender\")\n \n ax.set_title(\"When did we text more often?\")\n ax.set_xlabel(\"Week of\")\n ax.set_ylabel(\"Texts sent\")\n ax.set_xticks(np.arange(NUM_PERIODS) + bar_width / 2)\n ax.set_xticklabels(xlabels)\n ax.legend(loc=0)\n \n for rects in [rects1, rects2]:\n for rect in rects:\n height = rect.get_height()\n ax.text(rect.get_x() + rect.get_width()/2, height, \n '%d' % int(height), ha='center', va='bottom',\n rotation=0,\n fontsize='small')\n \n fig.tight_layout()\n fig.autofmt_xdate()\n \n return fig\n\ndef text_length_hist():\n fig, ax = plt.subplots(figsize=(10,8))\n ax.set_aspect('auto')\n ax.set_title(\"Who sends longer texts?\\n(Dist. of text messages)\")\n \n for i, db in enumerate([receiver, sender]): \n db_name = 'Receiver' if i == 0 else 'Sender'\n ax.hist(db.text_length[db.text_length < 800], bins=50,alpha=0.7, label=db_name)\n \n ax.legend(loc=0)\n ax.set_xlabel(\"Text length\")\n \n return fig\n\ndef num_words_hist():\n fig, ax = plt.subplots(1, 1, figsize=(10,8))\n ax.set_aspect('auto')\n ax.set_title(\"Who sends more words per text?\\n(Dist. of number of words/text)\")\n \n for i, db in enumerate([receiver, sender]): \n db_name = 'Receiver' if i == 0 else 'Sender'\n ax.hist(db.num_words[db.num_words < 202], bins=50,alpha=0.7, label=db_name)\n \n ax.legend(loc=0)\n ax.set_xlabel(\"Number of words per text\")\n \n return fig\n\ndef messages_wordcloud(db, color):\n stopwords = set(nltk.corpus.stopwords.words(\"english\")).union(set(['u','ull','youre','ure','i',\"ill\",\"im\"]))\n def _get_texts(db):\n text = [word.lower() for message in db['text'] for word in message.split() if word.lower() not in stopwords]\n return \" \".join(text)\n text = _get_texts(db)\n wc = WordCloud(\n normalize_plurals = True,\n stopwords=stopwords, \n scale=5, # higher the number, the more it renders with high definition\n background_color='white', \n colormap=color).generate(text)\n \n fig, ax = plt.subplots(figsize=(12,12))\n ax.imshow(wc, interpolation=\"bilinear\")\n ax.axis(\"off\")\n ax.set_aspect('equal')\n\n return fig\n\ndef message_positivity_graph():\n \n def _get_message_polarity(db):\n polarities = [TextBlob(message).sentiment.polarity for message in db.text]\n polarities = list(filter(lambda polarity: polarity != 0, polarities))\n return polarities\n \n receiver_polarity = _get_message_polarity(receiver)\n sender_polarity = _get_message_polarity(sender)\n \n MIN = min([len(receiver_polarity), len(sender_polarity)])\n \n receiver_polarity = receiver_polarity[:MIN]\n sender_polarity = sender_polarity[:MIN]\n \n fig, ax = plt.subplots(figsize=(12,12))\n \n ax = sns.kdeplot(receiver_polarity, sender_polarity,\n shade=True, cmap='Purples', ax=ax)\n ax.set_title(\"On a scale of [-1, 1], how positive is our conversation?\\n(bivariate distribution of the polarity of the messages)\")\n ax.set_aspect('equal')\n\n ax.set_xlabel(\"receiver\")\n ax.set_ylabel(\"sender\")\n \n return fig\n\ndef messages_by_day():\n days = [\"\",'Mon','Tues','Wed','Thu','Fri','Sat','Sun']\n \n fig, ax = plt.subplots(figsize=(12,10))\n \n ax.bar(days[1:], [messages[messages.day == d].hourly_bin.count() for d in range(7)])\n \n ax.set_title(\"What days did we send our texts?\")\n ax.set_ylabel(\"Number of texts sent\")\n ax.grid(axis='y')\n \n return fig\n\ndef messages_by_hour():\n days = [\"\",'Mon','Tues','Wed','Thu','Fri','Sat','Sun']\n \n fig, ax = plt.subplots(figsize=(12,10))\n \n ax = sns.violinplot(x='day', y='hourly_bin',\n hue='is_from_me', split=True,\n data=messages,cut=0,\n orient='v', ax=ax)\n ax.get_xaxis().get_label().set_visible(False)\n ax.get_yaxis().get_label().set_visible(False)\n \n legend = ax.legend(bbox_to_anchor=(1.005, 1.005), loc=2)\n labels = ['Receiver', 'Sender']\n \n for text, label in zip(legend.texts, labels):\n text.set_text(label)\n \n ax.set_xticklabels(labels=days[1:])\n ax.yaxis.set_ticks(list(range(0, 24, 3)) + [23])\n ax.yaxis.set_major_formatter(matplotlib.ticker.StrMethodFormatter('{x:,.0f}:00H'))\n ax.grid(axis='y')\n \n ax.set_title(\"What hour did we send our texts?\")\n \n return fig\n\n# save figures\nmessages_by_hour().savefig('messages_by_hour.png', quality=95)\nmessages_by_day().savefig('messages_by_day.png', quality=95)\nmessages_pchart().savefig('pie_chart.png', quality=95)\nweekly_texts().savefig('weekly_messages_sent.png', quality=95)\ntext_length_hist().savefig('text_length_hist.png', quality=95)\nnum_words_hist().savefig('num_words_hist.png', quality=95)\nmessages_wordcloud(receiver, 'Blues_r').savefig('receiver_wordcloud.png', quality=95)\nmessages_wordcloud(sender, 'Greens_r').savefig('sender_wordcloud.png', quality=95)\nmessage_positivity_graph().savefig('positivity_graph.png', quality=95)" ]
[ [ "pandas.read_csv", "matplotlib.ticker.StrMethodFormatter", "numpy.arange", "matplotlib.pyplot.subplots", "matplotlib.pyplot.style.use" ] ]
vbvg2008/ARC
[ "b7b16b907d1e62608ebb079594e953179e6a31ea" ]
[ "model/train_arc.py" ]
[ "import os\nimport pickle\n\nimport cv2\nimport fastestimator as fe\nimport numpy as np\nimport tensorflow as tf\nfrom fastestimator.op.numpyop import Delete\nfrom fastestimator.op.numpyop.meta import Sometimes\nfrom fastestimator.op.tensorop.loss import CrossEntropy\nfrom fastestimator.op.tensorop.model import ModelOp, UpdateOp\nfrom fastestimator.trace.io import ModelSaver\nfrom tensorflow.python.keras import layers\n\n\ndef zscore(data, epsilon=1e-7):\n mean = np.mean(data)\n std = np.std(data)\n data = (data - mean) / max(std, epsilon)\n return data\n\n\ndef load_pickle(pickle_path):\n with open(pickle_path, \"rb\") as f:\n data = pickle.load(f)\n return data\n\n\ndef pad_left_one(data):\n data_length = data.size\n if data_length < 300:\n data = np.pad(data, ((300 - data_length, 0), (0, 0)), mode='constant', constant_values=1.0)\n return data\n\n\ndef pad_left_zero(data):\n data_length = data.size\n if data_length < 300:\n data = np.pad(data, ((300 - data_length, 0), (0, 0)), mode='constant', constant_values=0.0)\n return data\n\n\nclass RemoveValLoss(fe.op.numpyop.NumpyOp):\n def forward(self, data, state):\n val_loss = data\n return np.zeros_like(val_loss)\n\n\nclass MultipleClsBinaryCELoss(fe.op.tensorop.TensorOp):\n def __init__(self, inputs, outputs, pos_labels=[0, 2], neg_labels=[1], mode=None):\n self.pos_labels = pos_labels\n self.neg_labels = neg_labels\n self.all_labels = self.pos_labels + self.neg_labels\n self.missing_labels = list(set([0, 1, 2]) - set(self.all_labels))\n if len(self.missing_labels) == 0:\n self.missing_labels = [-1]\n\n super().__init__(inputs=inputs, outputs=outputs, mode=mode)\n\n def forward(self, data, state):\n cls_pred, cls_label = data\n\n batch_size = cls_label.shape[0]\n binaryCEloss = 0.0\n\n case_count = 0.0\n for idx in range(batch_size):\n if cls_label[idx] != self.missing_labels[0]:\n abnormal_predict = tf.clip_by_value(tf.math.reduce_max([cls_pred[idx][p] for p in self.pos_labels]),\n 1e-4,\n 1.0 - 1e-4)\n\n if cls_label[idx] != self.neg_labels[0]:\n abnormal_label = 1.0\n else:\n abnormal_label = 0.0\n\n binaryCEloss -= (abnormal_label * tf.math.log(abnormal_predict) +\n (1.0 - abnormal_label) * tf.math.log(1.0 - abnormal_predict))\n case_count += 1\n\n return binaryCEloss / case_count\n\n\nclass CombineLoss(fe.op.tensorop.TensorOp):\n def __init__(self, inputs, outputs, weights, mode=None):\n super().__init__(inputs=inputs, outputs=outputs, mode=mode)\n self.weights = weights\n\n def forward(self, data, state):\n return tf.reduce_sum([loss * weight for loss, weight in zip(data, self.weights)])\n\n\nclass CombineData(fe.op.numpyop.NumpyOp):\n def forward(self, data, state):\n x = np.concatenate(data, axis=1)\n return np.float32(x)\n\n\nclass PreprocessTrainLoss(fe.op.numpyop.NumpyOp):\n def forward(self, data, state):\n train_loss = data\n train_loss = zscore(train_loss)\n train_loss = pad_left_zero(train_loss)\n return train_loss\n\n\nclass PreprocessTrainLR(fe.op.numpyop.NumpyOp):\n def forward(self, data, state):\n train_lr = data\n train_lr = train_lr / train_lr[0]\n train_lr = cv2.resize(train_lr, (1, train_lr.size * 100), interpolation=cv2.INTER_NEAREST)\n train_lr = pad_left_one(train_lr)\n return train_lr\n\n\nclass PreprocessValLoss(fe.op.numpyop.NumpyOp):\n def forward(self, data, state):\n val_loss, train_loss = data\n val_loss = zscore(val_loss)\n val_loss = cv2.resize(val_loss, (1, train_loss.size), interpolation=cv2.INTER_NEAREST)\n val_loss = pad_left_zero(val_loss)\n return val_loss\n\n\ndef lstm_stacked(input_shape=(300, 3), num_classes=3):\n model = tf.keras.Sequential()\n model.add(layers.Conv1D(filters=32, kernel_size=5, activation='relu', input_shape=input_shape))\n model.add(layers.MaxPooling1D(pool_size=2))\n model.add(layers.Conv1D(filters=64, kernel_size=5, activation='relu'))\n model.add(layers.MaxPooling1D(pool_size=2))\n model.add(layers.LSTM(64, return_sequences=True))\n model.add(layers.LSTM(64))\n model.add(layers.Dense(32, activation='relu'))\n model.add(layers.Dense(num_classes, activation='softmax'))\n return model\n\n\ndef get_estimator(epochs=300, data_dir=\"../data/offline_data.pkl\", save_dir=\"./\"):\n ckpt_save_dir = os.path.join(save_dir, \"checkpoint\")\n os.makedirs(ckpt_save_dir, exist_ok=True)\n train_ds = fe.dataset.NumpyDataset(data=load_pickle(data_dir))\n pipeline = fe.Pipeline(\n train_data=train_ds,\n batch_size=128,\n ops=[\n PreprocessValLoss(inputs=[\"val_loss\", \"train_loss\"], outputs=\"val_loss\"),\n PreprocessTrainLoss(inputs=\"train_loss\", outputs=\"train_loss\"),\n PreprocessTrainLR(inputs=\"train_lr\", outputs=\"train_lr\"),\n Sometimes(RemoveValLoss(inputs=\"val_loss\", outputs=\"val_loss\", mode=\"train\"), prob=0.5),\n CombineData(inputs=(\"train_loss\", \"val_loss\", \"train_lr\"), outputs=\"x\"),\n Delete(keys=(\"train_loss\", \"val_loss\", \"train_lr\"))\n ])\n model = fe.build(model_fn=lstm_stacked, optimizer_fn=lambda: tf.optimizers.Adam(1e-4))\n network = fe.Network(ops=[\n ModelOp(model=model, inputs=\"x\", outputs=\"y_pred\"),\n CrossEntropy(inputs=(\"y_pred\", \"label\"), outputs=\"ce\"),\n MultipleClsBinaryCELoss(inputs=(\"y_pred\", \"label\"), pos_labels=[0], neg_labels=[2], outputs=\"bnce_0vs2\"),\n CombineLoss(inputs=[\"ce\", \"bnce_0vs2\"], outputs=\"total_loss\", weights=[0.5, 0.5]),\n UpdateOp(model=model, loss_name=\"total_loss\")\n ])\n traces = [ModelSaver(model=model, save_dir=ckpt_save_dir, frequency=1, max_to_keep=1)]\n estimator = fe.Estimator(pipeline=pipeline, network=network, epochs=epochs, traces=traces, log_steps=5)\n return estimator\n" ]
[ [ "tensorflow.python.keras.layers.LSTM", "numpy.pad", "tensorflow.python.keras.layers.Dense", "tensorflow.math.reduce_max", "tensorflow.keras.Sequential", "tensorflow.math.log", "numpy.concatenate", "numpy.std", "numpy.zeros_like", "numpy.mean", "numpy.float32", "tensorflow.python.keras.layers.Conv1D", "tensorflow.optimizers.Adam", "tensorflow.python.keras.layers.MaxPooling1D" ] ]
HaithemH/norfair
[ "04f80dd900ed38c8537344ee07dec6c583ac4834" ]
[ "demos/motmetrics4norfair/motmetrics4norfair.py" ]
[ "import os.path\nimport numpy as np\nimport norfair\nfrom norfair import Detection, Tracker, metrics, video, drawing\nimport argparse\n\nframe_skip_period = 1\ndetection_threshold = 0.01\ndistance_threshold = 0.4\n\nparser = argparse.ArgumentParser(\n description=\"Evaluate a basic tracker on MOTChallenge data. Display on terminal the MOTChallenge metrics results \"\n)\nparser.add_argument(\n \"dataset_path\",\n type=str,\n nargs=\"?\",\n help=\"Path to the MOT Challenge train dataset folder (test dataset doesn't provide labels)\",\n)\nparser.add_argument(\n \"--make_video\",\n action=\"store_true\",\n help=\"Generate an output video, using the frames provided by the MOTChallenge dataset.\",\n)\nparser.add_argument(\n \"--save_pred\",\n action=\"store_true\",\n help=\"Generate a text file with your predictions\",\n)\nparser.add_argument(\n \"--save_metrics\",\n action=\"store_true\",\n help=\"Generate a text file with your MOTChallenge metrics results\",\n)\nparser.add_argument(\n \"--output_path\", type=str, nargs=\"?\", default=\".\", help=\"Output path\"\n)\nparser.add_argument(\n \"--select_sequences\",\n type=str,\n nargs=\"+\",\n help=\"If you want to select a subset of sequences in your dataset path. Insert the names of the sequences you want to process.\",\n)\n\nargs = parser.parse_args()\n\noutput_path = args.output_path\n\nif args.save_metrics:\n print(\"Saving metrics file at \" + os.path.join(output_path, \"metrics.txt\"))\nif args.save_pred:\n print(\"Saving predictions files at \" + os.path.join(output_path, \"predictions/\"))\nif args.make_video:\n print(\"Saving videos at \" + os.path.join(output_path, \"videos/\"))\n\nif args.select_sequences is None:\n sequences_paths = [f.path for f in os.scandir(args.dataset_path) if f.is_dir()]\nelse:\n sequences_paths = [\n os.path.join(args.dataset_path, f) for f in args.select_sequences\n ]\n\naccumulator = metrics.Accumulators()\n\nfor input_path in sequences_paths:\n # Search vertical resolution in seqinfo.ini\n seqinfo_path = os.path.join(input_path, \"seqinfo.ini\")\n info_file = metrics.InformationFile(file_path=seqinfo_path)\n vertical_resolution = info_file.search(variable_name=\"imHeight\")\n\n def keypoints_distance(detected_pose, tracked_pose):\n norm_orders = [1, 2, np.inf]\n distances = 0\n diagonal = 0\n\n hor_min_pt = min(detected_pose.points[:, 0])\n hor_max_pt = max(detected_pose.points[:, 0])\n ver_min_pt = min(detected_pose.points[:, 1])\n ver_max_pt = max(detected_pose.points[:, 1])\n\n # Set keypoint_dist_threshold based on object size, and calculate\n # distance between detections and tracker estimations\n for p in norm_orders:\n distances += np.linalg.norm(\n detected_pose.points - tracked_pose.estimate, ord=p, axis=1\n )\n diagonal += np.linalg.norm(\n [hor_max_pt - hor_min_pt, ver_max_pt - ver_min_pt], ord=p\n )\n\n distances = distances / len(norm_orders)\n\n keypoint_dist_threshold = (\n vertical_resolution * (diagonal < vertical_resolution / 3) / 67\n + diagonal * (diagonal >= vertical_resolution / 3) / 17\n )\n\n match_num = np.count_nonzero(\n (distances < keypoint_dist_threshold)\n * (detected_pose.scores > detection_threshold)\n * (tracked_pose.last_detection.scores > detection_threshold)\n )\n return 1 / (1 + match_num)\n\n all_detections = metrics.DetectionFileParser(\n input_path=input_path, information_file=info_file\n )\n\n if args.save_pred:\n predictions_text_file = metrics.PredictionsTextFile(\n input_path=input_path, save_path=output_path, information_file=info_file\n )\n\n if args.make_video:\n video_file = video.VideoFromFrames(\n input_path=input_path, save_path=output_path, information_file=info_file\n )\n\n tracker = Tracker(\n distance_function=keypoints_distance,\n distance_threshold=distance_threshold,\n detection_threshold=detection_threshold,\n point_transience=2,\n )\n\n # Initialize accumulator for this video\n accumulator.create_accumulator(input_path=input_path, information_file=info_file)\n\n for frame_number, detections in enumerate(all_detections):\n if frame_number % frame_skip_period == 0:\n tracked_objects = tracker.update(\n detections=detections, period=frame_skip_period\n )\n else:\n detections = []\n tracked_objects = tracker.update()\n\n # Draw detection and tracked object boxes on frame\n if args.make_video:\n frame = next(video_file)\n frame = drawing.draw_boxes(frame, detections=detections)\n frame = drawing.draw_tracked_boxes(frame=frame, objects=tracked_objects)\n video_file.update(frame=frame)\n\n # Update output text file\n if args.save_pred:\n predictions_text_file.update(predictions=tracked_objects)\n\n accumulator.update(predictions=tracked_objects)\n\naccumulator.compute_metrics()\naccumulator.print_metrics()\n\nif args.save_metrics:\n accumulator.save_metrics(save_path=output_path)\n" ]
[ [ "numpy.linalg.norm", "numpy.count_nonzero" ] ]
beneisner/partnet_seg_exps
[ "54cd57885ba248fb9a35b42664e1c69c7ef62255" ]
[ "exps/utils/eval_utils.py" ]
[ "import os\nimport sys\nimport h5py\nimport numpy as np\nfrom progressbar import ProgressBar\nfrom commons import check_mkdir\n\ndef load_gt_h5(fn):\n \"\"\" Output: pts B x N x 3 float32\n gt_mask B x K x N bool\n gt_mask_label B x K uint8\n gt_mask_valid B x K bool\n gt_mask_other B x N bool\n All the ground-truth masks are represented as 0/1 mask over the 10k point cloud.\n All the ground-truth masks are disjoint, complete and corresponding to unique semantic labels.\n Different test shapes have different numbers of ground-truth masks, they are at the top in array gt_mask indicated by gt_valid.\n \"\"\"\n with h5py.File(fn, 'r') as fin:\n gt_mask = fin['gt_mask'][:]\n gt_mask_label = fin['gt_mask_label'][:]\n gt_mask_valid = fin['gt_mask_valid'][:]\n gt_mask_other = fin['gt_mask_other'][:]\n return gt_mask, gt_mask_label, gt_mask_valid, gt_mask_other\n\ndef load_pred_h5(fn):\n \"\"\" Output: mask B x K x N bool\n label B x K uint8\n valid B x K bool\n conf B x K float32\n We only evaluate on the part predictions with valid = True.\n We assume no pre-sorting according to confidence score. \n \"\"\"\n with h5py.File(fn, 'r') as fin:\n mask = fin['mask'][:]\n label = fin['label'][:]\n valid = fin['valid'][:]\n conf = fin['conf'][:]\n return mask, label, valid, conf\n\ndef compute_ap(tp, fp, gt_npos, n_bins=100, plot_fn=None):\n assert len(tp) == len(fp), 'ERROR: the length of true_pos and false_pos is not the same!'\n\n tp = np.cumsum(tp)\n fp = np.cumsum(fp)\n\n rec = tp / gt_npos\n prec = tp / (fp + tp)\n\n rec = np.insert(rec, 0, 0.0)\n prec = np.insert(prec, 0, 1.0)\n\n ap = 0.\n delta = 1.0 / n_bins\n \n out_rec = np.arange(0, 1 + delta, delta)\n out_prec = np.zeros((n_bins+1), dtype=np.float32)\n\n for idx, t in enumerate(out_rec):\n prec1 = prec[rec >= t]\n if len(prec1) == 0:\n p = 0.\n else:\n p = max(prec1)\n \n out_prec[idx] = p\n ap = ap + p / (n_bins + 1)\n\n if plot_fn is not None:\n import matplotlib.pyplot as plt\n fig = plt.figure()\n plt.plot(out_rec, out_prec, 'b-')\n plt.title('PR-Curve (AP: %4.2f%%)' % (ap*100))\n plt.xlabel('Recall')\n plt.ylabel('Precision')\n plt.xlim([0, 1])\n plt.ylim([0, 1])\n fig.savefig(plot_fn)\n plt.close(fig)\n\n return ap\n\ndef eval_per_class_ap(stat_fn, gt_dir, pred_dir, iou_threshold=0.5, plot_dir=None):\n \"\"\" Input: stat_fn contains all part ids and names \n gt_dir contains test-xx.h5\n pred_dir contains test-xx.h5\n Output: aps: Average Prediction Scores for each part category, evaluated on all test shapes\n mAP: mean AP\n \"\"\"\n print('Evaluation Start.')\n print('Ground-truth Directory: %s' % gt_dir)\n print('Prediction Directory: %s' % pred_dir)\n\n if plot_dir is not None:\n check_mkdir(plot_dir)\n\n # read stat_fn\n with open(stat_fn, 'r') as fin:\n part_name_list = [item.rstrip().split()[1] for item in fin.readlines()]\n print('Part Name List: ', part_name_list)\n n_labels = len(part_name_list)\n print('Total Number of Semantic Labels: %d' % n_labels)\n\n # check all h5 files\n test_h5_list = []\n for item in os.listdir(gt_dir):\n if item.startswith('test-') and item.endswith('.h5'):\n if not os.path.exists(os.path.join(pred_dir, item)):\n print('ERROR: h5 file %s is in gt directory but not in pred directory.')\n exit(1)\n test_h5_list.append(item)\n\n # read each h5 file and collect per-part-category true_pos, false_pos and confidence scores\n true_pos_list = [[] for item in part_name_list]\n false_pos_list = [[] for item in part_name_list]\n conf_score_list = [[] for item in part_name_list]\n\n gt_npos = np.zeros((n_labels), dtype=np.int32)\n\n for item in test_h5_list:\n print('Testing %s' % item)\n\n gt_mask, gt_mask_label, gt_mask_valid, gt_mask_other = load_gt_h5(os.path.join(gt_dir, item))\n pred_mask, pred_label, pred_valid, pred_conf = load_pred_h5(os.path.join(pred_dir, item))\n\n n_shape = gt_mask.shape[0]\n gt_n_ins = gt_mask.shape[1]\n pred_n_ins = pred_mask.shape[1]\n\n for i in range(n_shape):\n cur_pred_mask = pred_mask[i, ...]\n cur_pred_label = pred_label[i, :]\n cur_pred_conf = pred_conf[i, :]\n cur_pred_valid = pred_valid[i, :]\n \n cur_gt_mask = gt_mask[i, ...]\n cur_gt_label = gt_mask_label[i, :]\n cur_gt_valid = gt_mask_valid[i, :]\n cur_gt_other = gt_mask_other[i, :]\n\n # classify all valid gt masks by part categories\n gt_mask_per_cat = [[] for item in part_name_list]\n for j in range(gt_n_ins):\n if cur_gt_valid[j]:\n sem_id = cur_gt_label[j]\n gt_mask_per_cat[sem_id].append(j)\n gt_npos[sem_id] += 1\n\n # sort prediction and match iou to gt masks\n cur_pred_conf[~cur_pred_valid] = 0.0\n order = np.argsort(-cur_pred_conf)\n\n gt_used = np.zeros((gt_n_ins), dtype=np.bool)\n\n for j in range(pred_n_ins):\n idx = order[j]\n if cur_pred_valid[idx]:\n sem_id = cur_pred_label[idx]\n\n iou_max = 0.0; cor_gt_id = -1;\n for k in gt_mask_per_cat[sem_id]:\n if not gt_used[k]:\n # Remove points with gt label *other* from the prediction\n # We will not evaluate them in the IoU since they can be assigned any label\n clean_cur_pred_mask = (cur_pred_mask[idx, :] & (~cur_gt_other))\n\n intersect = np.sum(cur_gt_mask[k, :] & clean_cur_pred_mask)\n union = np.sum(cur_gt_mask[k, :] | clean_cur_pred_mask)\n iou = intersect * 1.0 / union\n \n if iou > iou_max:\n iou_max = iou\n cor_gt_id = k\n \n if iou_max > iou_threshold:\n gt_used[cor_gt_id] = True\n\n # add in a true positive\n true_pos_list[sem_id].append(True)\n false_pos_list[sem_id].append(False)\n conf_score_list[sem_id].append(cur_pred_conf[idx])\n else:\n # add in a false positive\n true_pos_list[sem_id].append(False)\n false_pos_list[sem_id].append(True)\n conf_score_list[sem_id].append(cur_pred_conf[idx])\n\n # compute per-part-category AP\n aps = np.zeros((n_labels), dtype=np.float32)\n ap_valids = np.ones((n_labels), dtype=np.bool)\n for i in range(n_labels):\n has_pred = (len(true_pos_list[i]) > 0)\n has_gt = (gt_npos[i] > 0)\n\n if not has_gt:\n ap_valids[i] = False\n continue\n\n if has_gt and not has_pred:\n continue\n\n cur_true_pos = np.array(true_pos_list[i], dtype=np.float32)\n cur_false_pos = np.array(false_pos_list[i], dtype=np.float32)\n cur_conf_score = np.array(conf_score_list[i], dtype=np.float32)\n\n # sort according to confidence score again\n order = np.argsort(-cur_conf_score)\n sorted_true_pos = cur_true_pos[order]\n sorted_false_pos = cur_false_pos[order]\n\n out_plot_fn = None\n if plot_dir is not None:\n out_plot_fn = os.path.join(plot_dir, part_name_list[i].replace('/', '-')+'.png')\n\n aps[i] = compute_ap(sorted_true_pos, sorted_false_pos, gt_npos[i], plot_fn=out_plot_fn)\n\n # compute mean AP\n mean_ap = np.sum(aps * ap_valids) / np.sum(ap_valids)\n\n return aps, ap_valids, gt_npos, mean_ap\n\ndef eval_per_shape_mean_ap(stat_fn, gt_dir, pred_dir, iou_threshold=0.5):\n \"\"\" Input: stat_fn contains all part ids and names \n gt_dir contains test-xx.h5\n pred_dir contains test-xx.h5\n Output: mean_aps: per-shape mean aps, which is the mean AP on each test shape,\n for each shape, we only consider the parts that exist in either gt or pred\n shape_valids: If a shape has valid parts to evaluate or not\n mean_mean_ap: mean per-shape mean aps\n \"\"\"\n print('Evaluation Start.')\n print('Ground-truth Directory: %s' % gt_dir)\n print('Prediction Directory: %s' % pred_dir)\n\n # read stat_fn\n with open(stat_fn, 'r') as fin:\n part_name_list = [item.rstrip().split()[1] for item in fin.readlines()]\n print('Part Name List: ', part_name_list)\n n_labels = len(part_name_list)\n print('Total Number of Semantic Labels: %d' % n_labels)\n\n # check all h5 files\n test_h5_list = []\n for item in os.listdir(gt_dir):\n if item.startswith('test-') and item.endswith('.h5'):\n if not os.path.exists(os.path.join(pred_dir, item)):\n print('ERROR: h5 file %s is in gt directory but not in pred directory.')\n exit(1)\n test_h5_list.append(item)\n\n mean_aps = []\n shape_valids = []\n\n # read each h5 file\n for item in test_h5_list:\n print('Testing %s' % item)\n\n gt_mask, gt_mask_label, gt_mask_valid, gt_mask_other = load_gt_h5(os.path.join(gt_dir, item))\n pred_mask, pred_label, pred_valid, pred_conf = load_pred_h5(os.path.join(pred_dir, item))\n\n n_shape = gt_mask.shape[0]\n gt_n_ins = gt_mask.shape[1]\n pred_n_ins = pred_mask.shape[1]\n\n for i in range(n_shape):\n cur_pred_mask = pred_mask[i, ...]\n cur_pred_label = pred_label[i, :]\n cur_pred_conf = pred_conf[i, :]\n cur_pred_valid = pred_valid[i, :]\n \n cur_gt_mask = gt_mask[i, ...]\n cur_gt_label = gt_mask_label[i, :]\n cur_gt_valid = gt_mask_valid[i, :]\n cur_gt_other = gt_mask_other[i, :]\n\n # per-shape evaluation\n true_pos_list = [[] for item in part_name_list]\n false_pos_list = [[] for item in part_name_list]\n gt_npos = np.zeros((n_labels), dtype=np.int32)\n\n # classify all valid gt masks by part categories\n gt_mask_per_cat = [[] for item in part_name_list]\n for j in range(gt_n_ins):\n if cur_gt_valid[j]:\n sem_id = cur_gt_label[j]\n gt_mask_per_cat[sem_id].append(j)\n gt_npos[sem_id] += 1\n\n # sort prediction and match iou to gt masks\n cur_pred_conf[~cur_pred_valid] = 0.0\n order = np.argsort(-cur_pred_conf)\n\n gt_used = np.zeros((gt_n_ins), dtype=np.bool)\n\n # enumerate all pred parts\n for j in range(pred_n_ins):\n idx = order[j]\n if cur_pred_valid[idx]:\n sem_id = cur_pred_label[idx]\n\n iou_max = 0.0; cor_gt_id = -1;\n for k in gt_mask_per_cat[sem_id]:\n if not gt_used[k]:\n # Remove points with gt label *other* from the prediction\n # We will not evaluate them in the IoU since they can be assigned any label\n clean_cur_pred_mask = (cur_pred_mask[idx, :] & (~cur_gt_other))\n\n intersect = np.sum(cur_gt_mask[k, :] & clean_cur_pred_mask)\n union = np.sum(cur_gt_mask[k, :] | clean_cur_pred_mask)\n iou = intersect * 1.0 / union\n \n if iou > iou_max:\n iou_max = iou\n cor_gt_id = k\n \n if iou_max > iou_threshold:\n gt_used[cor_gt_id] = True\n\n # add in a true positive\n true_pos_list[sem_id].append(True)\n false_pos_list[sem_id].append(False)\n else:\n # add in a false positive\n true_pos_list[sem_id].append(False)\n false_pos_list[sem_id].append(True)\n\n # evaluate per-part-category AP for the shape\n aps = np.zeros((n_labels), dtype=np.float32)\n ap_valids = np.zeros((n_labels), dtype=np.bool)\n for j in range(n_labels):\n has_pred = (len(true_pos_list[j]) > 0)\n has_gt = (gt_npos[j] > 0)\n\n if has_pred and has_gt:\n cur_true_pos = np.array(true_pos_list[j], dtype=np.float32)\n cur_false_pos = np.array(false_pos_list[j], dtype=np.float32)\n aps[j] = compute_ap(cur_true_pos, cur_false_pos, gt_npos[j])\n ap_valids[j] = True\n elif has_pred and not has_gt:\n aps[j] = 0.0\n ap_valids[j] = True\n elif not has_pred and has_gt:\n aps[j] = 0.0\n ap_valids[j] = True\n\n # compute mean AP for the current shape\n if np.sum(ap_valids) > 0:\n mean_aps.append(np.sum(aps * ap_valids) / np.sum(ap_valids))\n shape_valids.append(True)\n else:\n mean_aps.append(0.0)\n shape_valids.append(False)\n\n # compute mean mean AP\n mean_aps = np.array(mean_aps, dtype=np.float32)\n shape_valids = np.array(shape_valids, dtype=np.bool)\n\n mean_mean_ap = np.sum(mean_aps * shape_valids) / np.sum(shape_valids)\n\n return mean_aps, shape_valids, mean_mean_ap\n\n\ndef eval_hier_mean_iou(gt_labels, pred_labels, tree_constraint, tree_parents):\n return eval_hier_part_mean_iou(gt_labels, pred_labels, tree_constraint, tree_parents)\n\n\ndef eval_hier_part_mean_iou(gt_labels, pred_labels, tree_constraint, tree_parents):\n \"\"\"\n Input: \n gt_labels B x N x (C+1), boolean\n pred_logits B x N x (C+1), boolean\n tree_constraint T x (C+1), boolean\n tree_parents T, int32\n Output: \n mean_iou Scalar, float32\n part_iou C, float32\n \"\"\"\n assert gt_labels.shape[0] == pred_labels.shape[0], 'ERROR: gt and pred have different num_shape'\n assert gt_labels.shape[1] == pred_labels.shape[1], 'ERROR: gt and pred have different num_point'\n assert gt_labels.shape[2] == pred_labels.shape[2], 'ERROR: gt and pred have different num_class+1'\n\n num_shape = gt_labels.shape[0]\n num_point = gt_labels.shape[1]\n num_class = gt_labels.shape[2] - 1\n \n assert tree_constraint.shape[0] == tree_parents.shape[0], 'ERROR: tree_constraint and tree_parents have different num_constraint'\n assert tree_constraint.shape[1] == num_class + 1 , 'ERROR: tree_constraint.shape[1] != num_class + 1'\n assert len(tree_parents.shape) == 1, 'ERROR: tree_parents is not a 1-dim array'\n\n # make a copy of the prediction\n pred_labels = np.array(pred_labels, dtype=np.bool)\n\n num_constraint = tree_constraint.shape[0]\n\n part_intersect = np.zeros((num_class+1), dtype=np.float32)\n part_union = np.zeros((num_class+1), dtype=np.float32)\n\n part_intersect[1] = np.sum(pred_labels[:, :, 1] & gt_labels[:, :, 1])\n part_union[1] = np.sum(pred_labels[:, :, 1] | gt_labels[:, :, 1])\n\n all_idx = np.arange(num_class+1)\n all_visited = np.zeros((num_class+1), dtype=np.bool)\n\n all_visited[1] = True\n for i in range(num_constraint):\n cur_pid = tree_parents[i]\n if all_visited[cur_pid]:\n cur_cons = tree_constraint[i]\n\n idx = all_idx[cur_cons]\n gt_other = ((np.sum(gt_labels[:, :, idx], axis=-1) == 0) & gt_labels[:, :, cur_pid])\n\n for j in list(idx):\n pred_labels[:, :, j] = (pred_labels[:, :, cur_pid] & pred_labels[:, :, j] & (~gt_other))\n part_intersect[j] += np.sum(pred_labels[:, :, j] & gt_labels[:, :, j])\n part_union[j] += np.sum(pred_labels[:, :, j] | gt_labels[:, :, j])\n all_visited[j] = True\n\n all_valid_part_ids = all_idx[all_visited]\n part_iou = np.divide(part_intersect[all_valid_part_ids], part_union[all_valid_part_ids])\n mean_iou = np.mean(part_iou)\n\n return mean_iou, part_iou, part_intersect[all_valid_part_ids], part_union[all_valid_part_ids]\n\n\ndef eval_hier_shape_mean_iou(gt_labels, pred_labels, tree_constraint, tree_parents):\n \"\"\"\n Input: \n gt_labels B x N x (C+1), boolean\n pred_logits B x N x (C+1), boolean\n tree_constraint T x (C+1), boolean\n tree_parents T, int32\n Output: \n mean_iou Scalar, float32\n part_iou C, float32\n \"\"\"\n assert gt_labels.shape[0] == pred_labels.shape[0], 'ERROR: gt and pred have different num_shape'\n assert gt_labels.shape[1] == pred_labels.shape[1], 'ERROR: gt and pred have different num_point'\n assert gt_labels.shape[2] == pred_labels.shape[2], 'ERROR: gt and pred have different num_class+1'\n\n num_shape = gt_labels.shape[0]\n num_point = gt_labels.shape[1]\n num_class = gt_labels.shape[2] - 1\n \n assert tree_constraint.shape[0] == tree_parents.shape[0], 'ERROR: tree_constraint and tree_parents have different num_constraint'\n assert tree_constraint.shape[1] == num_class + 1 , 'ERROR: tree_constraint.shape[1] != num_class + 1'\n assert len(tree_parents.shape) == 1, 'ERROR: tree_parents is not a 1-dim array'\n\n # make a copy of the prediction\n pred_labels = np.array(pred_labels, dtype=np.bool)\n\n num_constraint = tree_constraint.shape[0]\n\n all_idx = np.arange(num_class+1)\n all_visited = np.zeros((num_class+1), dtype=np.bool)\n\n all_visited[1] = True\n for i in range(num_constraint):\n cur_pid = tree_parents[i]\n if all_visited[cur_pid]:\n cur_cons = tree_constraint[i]\n\n idx = all_idx[cur_cons]\n gt_other = ((np.sum(gt_labels[:, :, idx], axis=-1) == 0) & gt_labels[:, :, cur_pid])\n\n for j in list(idx):\n pred_labels[:, :, j] = (pred_labels[:, :, cur_pid] & pred_labels[:, :, j] & (~gt_other))\n all_visited[j] = True\n\n all_valid_part_ids = all_idx[all_visited]\n\n tot = 0.0; cnt = 0;\n for i in range(num_shape):\n local_tot = 0.0; local_cnt = 0;\n for j in all_valid_part_ids:\n has_gt = (np.sum(gt_labels[i, :, j]) > 0)\n has_pred = (np.sum(pred_labels[i, :, j]) > 0)\n if has_gt or has_pred:\n intersect = np.sum(gt_labels[i, :, j] & pred_labels[i, :, j])\n union = np.sum(gt_labels[i, :, j] | pred_labels[i, :, j])\n iou = intersect * 1.0 / union\n local_tot += iou\n local_cnt += 1\n if local_cnt > 0:\n tot += local_tot / local_cnt\n cnt += 1\n\n return tot / cnt\n\n" ]
[ [ "matplotlib.pyplot.title", "numpy.arange", "matplotlib.pyplot.ylim", "numpy.cumsum", "numpy.ones", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlim", "numpy.mean", "numpy.insert", "matplotlib.pyplot.close", "numpy.argsort", "matplotlib.pyplot.xlabel", "numpy.array", "numpy.zeros", "numpy.sum", "numpy.divide", "matplotlib.pyplot.figure" ] ]
lufovic77/DBx1000
[ "1c2c15e48ca3bb4ee0b58ac1c09945f463f61cc9" ]
[ "scripts/runExpr.py" ]
[ "NUM_TRIALS = 4\n\nimport os.path\nfrom os import path\nimport subprocess\nfrom subprocess import TimeoutExpired\nimport re\nimport sys\nimport os\nimport datetime\nimport socket\nfrom numpy.core.numeric import full\n# from tools.logChecker import num\nfrom numpy.core.shape_base import block\nfrom scipy import optimize\n\nfilterFullSet = [\n 'rundb_ND_YCSB_NOWAIT', 'rundb_ND_TPCC_NOWAIT', # NO_LOGGING\n 'rundb_VD_YCSB_NOWAIT', 'rundb_VD_TPCC_NOWAIT', # PLOVER\n 'rundb_TC_YCSB_NOWAIT', 'rundb_TC_TPCC_NOWAIT', # Taurus Command\n 'rundb_TD_YCSB_NOWAIT', 'rundb_TD_TPCC_NOWAIT', # Taurus Data\n 'rundb_LC_YCSB_NOWAIT', 'rundb_LC_TPCC_NOWAIT', # Taurus Command w/o Locktable\n 'rundb_LD_YCSB_NOWAIT', 'rundb_LD_TPCC_NOWAIT',\n 'rundb_WC_YCSB_NOWAIT', 'rundb_WC_TPCC_NOWAIT', # Taurus recovery classical\n 'rundb_WD_YCSB_NOWAIT', 'rundb_WD_TPCC_NOWAIT',\n 'rundb_SD_YCSB_NOWAIT', 'rundb_SD_TPCC_NOWAIT',\n 'rundb_SC_YCSB_NOWAIT', 'rundb_SC_TPCC_NOWAIT',\n 'rundb_BD_YCSB_SILO', 'rundb_BD_TPCC_SILO',\n 'rundb_ND_YCSB_SILO', 'rundb_ND_TPCC_SILO', # NO_LOGGING\n 'rundb_TC_YCSB_SILO', 'rundb_TC_TPCC_SILO', # Taurus Command\n 'rundb_TD_YCSB_SILO', 'rundb_TD_TPCC_SILO', # Taurus Data\n 'rundb_LC_YCSB_SILO', 'rundb_LC_TPCC_SILO', # Taurus Command w/o Locktable\n 'rundb_LD_YCSB_SILO', 'rundb_LD_TPCC_SILO',\n 'rundb_WC_YCSB_SILO', 'rundb_WC_TPCC_SILO', # Taurus recovery classical\n 'rundb_WD_YCSB_SILO', 'rundb_WD_TPCC_SILO',\n 'rundb_SD_YCSB_SILO', 'rundb_SD_TPCC_SILO',\n 'rundb_SC_YCSB_SILO', 'rundb_SC_TPCC_SILO', \n ]\n\n#filterFullSet = [\n# 'rundb_SD_YCSB_NOWAIT', 'rundb_SD_TPCC_NOWAIT',\n# 'rundb_SC_YCSB_NOWAIT', 'rundb_SC_TPCC_NOWAIT',\n# 'rundb_SD_YCSB_SILO', 'rundb_SD_TPCC_SILO',\n# 'rundb_SC_YCSB_SILO', 'rundb_SC_TPCC_SILO', \n#]\n\ndef filterExclude(rundbList, excludeStr):\n return [x for x in rundbList if excludeStr not in x]\n\ndef filterExcludeMulti(rundbList, excludeStrList):\n ret = [x for x in rundbList]\n for es in excludeStrList:\n ret = filterExclude(ret, es)\n return ret\n\ndef filterInclude(rundbList, includeStrList):\n return [x for x in rundbList if includeStrList in x]\n\ndef getCPUFreq():\n res = subprocess.check_output('lscpu', shell=True).decode().split('@')[1].strip()\n res = float(res.split('GHz')[0])\n print('Using CPU_FREQ', res)\n return res\n\nCPU_FREQ = getCPUFreq()\n\ndef getNUMAConfig():\n res = subprocess.check_output('lscpu', shell=True).decode().split('\\n')\n nodeNum = 1\n corePerSocket = 1\n for line in res:\n if 'Socket' in line:\n nodeNum = int(line.split(':')[1].strip())\n if 'Core(s) per socket' in line:\n corePerSocket = int(line.split(':')[1].strip())\n print(\"NUM_CORES_PER_SLOT %d, NUMA_NODE_NUM %d, HYPER_THREADING_FACTOR %d\" % (corePerSocket, nodeNum, 2))\n return corePerSocket, nodeNum, 2\n\nNUM_CORES_PER_SLOT, NUMA_NODE_NUM, HYPER_THREADING_FACTOR = getNUMAConfig()\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n# AWS i3en.metal best disk parameter\n\n# changes everytime we start the instance\ni3metal_nvme = [104857600, 33554432]\ni3metal_nvme2 = [1048576, 33554432]\nh1_16xlarge_hdd = [104857600, 33554432]\nh1_16xlarge_hdd_raid8 = [262142976, 33554432]\ni3metal_nvme_raid8 = [ 8*x for x in i3metal_nvme2]\n\nsnapShotCreated = []\n\nRAID0_MODE = False\nDEFAULT_LOG_NUM=4\n\nPATH = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + '/../')\nRESPATH = '/home/ubuntu/efs/'\n\nhostname = socket.gethostname()\n\nRUNEXPR_OVERRIDE = int(os.getenv(\"RUNEXPR_OVERRIDE\", '1'))\nRUNEXPR_CLEAN = int(os.getenv(\"RUNEXPR_CLEAN\", '0'))\nRUNEXPR_CMDONLY = int(os.getenv(\"RUNEXPR_CMDONLY\", '0'))\n\nif 'ip' in hostname:\n DROP_CACHE = \"echo 3 > /proc/sys/vm/drop_caches\"\nelse:\n DROP_CACHE = \"/usr/local/bin/drop_caches\"\n\nRETRY_TIMES = 3\nTIMEOUT = None\n\nresultRE = re.compile(r'Throughput:\\s+([\\d\\.\\+e\\-]+)')\nmodification = 'recover_'\n\ndef getResDir(modification):\n label = open(PATH + '/label.txt','r').read().strip()\n # label = subprocess.check_output([\"git\", \"describe\"]).strip()\n res = RESPATH + './results/' + modification + label\n if not os.path.exists(res):\n os.makedirs(res)\n return res\n\nresDir = getResDir(modification)\n\nparamOverride = ''\n\n# test\nglobalFilter = filterFullSet\n\ndef straightThrough(s):\n return s\n\ndef diffGX(cl):\n if 'YCSB' in cl:\n return cl + ' -Gx150000' # YCSB-500 init is slow\n else:\n return cl + ' -Gx1000000'\n\nPARAM_FUNETUNE = diffGX # straightThrough\n\ndef diskCheckHDD(n):\n lsblk = subprocess.check_output(\"lsblk\", shell=True).strip()\n for i in range(n):\n if not \"/data%d\" % i in lsblk:\n print('Disk Sanity Check Fails at /data%d' % i)\n sys.exit(0)\n return True\n\ndef diskCheckRAID(n):\n lsblk = subprocess.check_output(\"lsblk\", shell=True).strip()\n return True\n\ndef fillinName(kwargs):\n workload = ''\n log_type = ''\n log_alg = ''\n cc_alg = ''\n params = ''\n for k, v in sorted(kwargs.items()):\n if k == 'workload':\n workload = v\n elif k == 'log_type':\n log_type = v\n elif k == 'log_alg':\n log_alg = v\n elif k == 'cc_alg':\n cc_alg = v.replace('_', '')\n else:\n params += ' -%s%s' % (k, v)\n localParam = ' '\n \n if log_alg == 'T' and workload == 'TPCC' and cc_alg == 'SILO' and (kwargs['Lr'] == 1 or kwargs['Lr'] == '1'):\n localParam = ' -Lb262144000 ' # improve unscaling issue on t56 ---see diary 13\n\n return 'rundb_%s%s_%s_%s%s' % (log_alg, log_type, workload, cc_alg, params), localParam\n\nfrom shutil import copyfile\n\ndef createSnapshot(resDir):\n if resDir in snapShotCreated:\n return\n print(bcolors.OKGREEN + \"Creating Snapshots...\" + bcolors.ENDC)\n # copy configs\n copyfile('tools/compile.py', resDir + '/compile.py')\n copyfile('scripts/runExpr.py', resDir + '/runExpr.py')\n copyfile('scripts/generateFigures.py', resDir + '/generateFigures.py')\n copyfile('config-std.h', resDir + '/config-std.h')\n open(resDir + '/runExpr_Command.cmd', 'w').write(str(sys.argv))\n\n subprocess.check_output('cp %s/rundb* %s/' % (PATH, resDir), shell=True)\n # copy the executables and configs\n snapShotCreated.append(resDir)\n\ndef checkDisks():\n pass\n\ndef runExpr(xLabel, xRange, resDir=resDir, num_trials=NUM_TRIALS, eval_mode=False, **kwargs):\n \n global DROP_CACHE\n # check Makefile to see if this is unoptimized.\n\n makefileContent = open(PATH + '/Makefile', 'r').read().strip()\n if '-O0' in makefileContent:\n print(bcolors.WARNING, 'Observed -O0 in the Makefile', bcolors.ENDC)\n if eval_mode:\n assert len(xRange) == 1\n if RUNEXPR_CMDONLY == 0:\n createSnapshot(resDir)\n # tune NUMA limit for TPCC\n subprocess.check_output('echo 10485760 > /proc/sys/vm/max_map_count', shell=True)\n\n if isinstance(num_trials, list):\n trialRange = num_trials\n else:\n assert isinstance(num_trials, int)\n trialRange = range(num_trials)\n algP = [[] for _ in range(len(trialRange))]\n preparedLr0 = []\n for k in trialRange: # range(num_trials):\n for x in xRange:\n kw = kwargs\n kw[xLabel] = x\n commandLine, localParameterOverride = fillinName(kw)\n if len(globalFilter) > 0:\n found = False\n for pat in globalFilter:\n if pat in commandLine:\n found = True\n break\n if not found:\n print('Filtered by global filter', commandLine, globalFilter)\n continue\n fullCommand = commandLine + localParameterOverride + paramOverride\n if PARAM_FUNETUNE != None:\n fullCommand = PARAM_FUNETUNE(fullCommand)\n print(bcolors.OKBLUE + datetime.datetime.now().strftime('%Y-%m-%d-%T') + bcolors.ENDC , \"cmd: numactl -i all -- ./\" + fullCommand)\n\n fileName = resDir + '/' + commandLine.replace(' -', '_') + '_%d.txt' % k\n if RAID0_MODE == True:\n assert(kw['log_alg']=='S')\n fileName = fileName.replace('SD', 'SR') # R for RAID\n fileName = fileName.replace('SC', 'SQ') # Q for RAID-C\n print('testing', fileName, RUNEXPR_OVERRIDE)\n if (RUNEXPR_OVERRIDE == 0) and path.exists(fileName):\n fileConfigId = resDir + '/' + commandLine.replace(' -', '_')\n if kw['Lr']==0 and ((x == xRange[0] and kw['Ln']>1) or x == xRange[-1]) and fileConfigId not in preparedLr0 and not path.exists(fileName.replace('Lr0', 'Lr1')) and not 'rundb_ND' in fileName:\n print('Prepare for Lr1...', fileName)\n preparedLr0.append(fileConfigId) # we only prepare once\n else:\n print('Skip', fileName)\n continue\n\n if (RUNEXPR_CLEAN == 1) and path.exists(fileName):\n os.remove(fileName)\n continue\n\n if RUNEXPR_CMDONLY == 1: # we only output the commandline\n continue\n \n subprocess.check_output(DROP_CACHE, shell=True) # drop the cache\n retry = True\n count = 0\n \n while retry:\n count += 1\n try:\n \n ret = subprocess.check_output(\"numactl -i all -- ./\" + fullCommand, shell=True, timeout=TIMEOUT).decode('ascii')\n retry = False\n break\n except TimeoutExpired:\n print('Time out')\n open(\"timeout.log\", \"a+\").write(fullCommand + '\\n')\n retry = True\n if count > RETRY_TIMES:\n ret = 'Throughput: 0\\n Broken' # dummy data\n break\n\n # print(ret)\n \n open(fileName, 'w').write(ret)\n # print ret\n thr = float(resultRE.findall(ret)[0])\n if eval_mode:\n return thr\n algP[k].append((x, thr))\n print(bcolors.WARNING + str((commandLine, x, thr)) + bcolors.ENDC)\n print('Epoch %d finished' % k)\n\n return []\n\ndef test():\n # for temp local test\n for workload in ['TPCC']: # ['YCSB', 'TPCC']:\n for Lr in [0, 1]:\n runExpr('t', [56], './temp', 1,\n workload=workload, log_type='D', log_alg='T', cc_alg='NO_WAIT', Ln=DEFAULT_LOG_NUM, Lr=Lr)\n runExpr('t', [56], './temp', 1,\n workload=workload, log_type='D', log_alg='T', cc_alg='SILO', Ln=DEFAULT_LOG_NUM, Lr=Lr)\n runExpr('t', [56], './temp', 1,\n workload=workload, log_type='D', log_alg='B', cc_alg='SILO', Ln=DEFAULT_LOG_NUM, Lr=Lr)\n sys.exit(0)\n\ndef rm():\n pass\n\ndef LogNum():\n lns = [1, 2, 3] # , 4]\n resDirShort = getResDir('lognum')\n numTrials = 1\n shortX = [12] # [4, 16, 32, 48, 56]\n global paramOverride\n paramOverride = '-R2 -z0.6 -r0.5 -l80003 -Tp0 -Tl30000000 -Ls0.05 -Lb10485760' # normal\n \n for ln in lns:\n runExpr('t', shortX, resDirShort, numTrials,\n workload='YCSB', log_type='C', log_alg='T', cc_alg='NO_WAIT', Ln=ln, Lr=0)\n \n runExpr('t', shortX, resDirShort, numTrials,\n workload='YCSB', log_type='D', log_alg='T', cc_alg='NO_WAIT', Ln=ln, Lr=0)\n return\n\ndef LogNumEC2():\n lns = [4]\n resDirShort = getResDir('lognum')\n numTrials = 1\n shortX = [48] # [4, 16, 32, 48, 56]\n global paramOverride\n paramOverride = '-R2 -z0.6 -r0.5 -l80003 -Tp0 -Tl30000000 -Ls0.05 -Lb10485760 -Gx10000' # normal\n \n for ln in lns:\n \n runExpr('t', shortX, resDirShort, numTrials,\n workload='YCSB', log_type='D', log_alg='T', cc_alg='NO_WAIT', Ln=ln, Lr=0)\n runExpr('t', shortX, resDirShort, numTrials,\n workload='YCSB', log_type='D', log_alg='T', cc_alg='NO_WAIT', Ln=ln, Lr=1)\n \n sys.exit(0)\n\ndef sensitivityHashTableModifier():\n resDirSens = getResDir('hashtable')\n numTrials = 4\n defaultT = 27\n global paramOverride \n lLevel = [100, 200, 400, 800, 1600, 3200, 6400, 12800, 25600, 51200]\n paramOverride = ' -z0.6 -R2 -r0.5 -Tl30000000 -Gx150000 -Lz20 -Lad0 -Lal1 -Tp0 '\n for l in lLevel:\n for Lr in [0, 1]:\n for workload in ['YCSB']:\n runExpr('l', [l], resDirSens, numTrials,\n workload=workload, log_type='D', log_alg ='T', cc_alg='NO_WAIT', Ln=DEFAULT_LOG_NUM, Lr=Lr, t=defaultT)\n runExpr('l', [l], resDirSens, numTrials,\n workload=workload, log_type='C', log_alg ='T', cc_alg='NO_WAIT', Ln=DEFAULT_LOG_NUM, Lr=Lr, t=defaultT)\n sys.exit(0)\n\ndef sensitivityTxnLength():\n resDirSens = getResDir('txnlength')\n numTrials = 4\n defaultT = 27\n global paramOverride \n lLevel = [1, 2, 4, 6, 8, 10, 12, 14, 16]\n paramOverride = ' -z0.6 -r0.5 -Tl30000000 -Gx150000 -Lz20 -Lad0 -Lal1 -Tp0 -Ld16384'\n cc = 'NO_WAIT'\n for l in lLevel:\n for workload in ['YCSB']:\n for Lr in [0, 1]:\n runExpr('R', [l], resDirSens, numTrials, \n workload = workload, log_type='D', log_alg ='S', cc_alg=cc, Ln=1, Lr=Lr, t=defaultT)\n runExpr('R', [l], resDirSens, numTrials, \n workload = workload, log_type='C', log_alg ='S', cc_alg=cc, Ln=1, Lr=Lr, t=defaultT)\n runExpr('R', [l], resDirSens, numTrials, \n workload = workload, log_type='D', log_alg ='B', cc_alg='SILO', Ln=DEFAULT_LOG_NUM, Lr=Lr, t=defaultT)\n runExpr('R', [l], resDirSens, numTrials,\n workload=workload, log_type='D', log_alg ='T', cc_alg=cc, Ln=DEFAULT_LOG_NUM, Lr=Lr, t=defaultT)\n runExpr('R', [l], resDirSens, numTrials,\n workload=workload, log_type='C', log_alg ='T', cc_alg=cc, Ln=DEFAULT_LOG_NUM, Lr=Lr, t=defaultT)\n runExpr('R', [l], resDirSens, numTrials, \n workload = workload, log_type='D', log_alg ='N', cc_alg=cc, Ln=DEFAULT_LOG_NUM, Lr=0, t=defaultT)\n \n sys.exit(0)\n\n\ndef sensitivityCompressionAux8(ln=8):\n resDirSens = getResDir('compressAux')\n numTrials = 1 # 4 # 4 # 4 # 4\n defaultT = 56 # 27\n global paramOverride \n tpLevel = [1000]\n paramOverride = ' -z0.6 -R16 -r0.5 -Tl30000000 -Gx15000 -Lz20 -Lad0 -Lal1 -l1600003 -Lt300000 -Lb102400'\n for tp in tpLevel:\n for Lr in [0]:\n defaultT = 8\n for workload in ['YCSB']:\n \n runExpr('Tp', [tp], resDirSens, numTrials, \n workload=workload, log_type='D', log_alg ='T', cc_alg='NO_WAIT', Ln=ln, Lr=Lr, t=defaultT)\n runExpr('Tp', [tp], resDirSens, numTrials, \n workload=workload, log_type='C', log_alg ='T', cc_alg='NO_WAIT', Ln=ln, Lr=Lr, t=defaultT)\n\ndef sensitivityCompressionAux(ln=DEFAULT_LOG_NUM):\n resDirSens = getResDir('compressAux')\n numTrials = 1 # 4 # 4 # 4 # 4\n defaultT = 28 # 27\n global paramOverride \n tpLevel = [10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000]\n paramOverride = ' -z0.0 -R16 -r0.5 -Tl30000000 -Gx150000 -Lz20 -Lad0 -Lal1 -l1600003 -Lt300000'\n for tp in tpLevel:\n for Lr in [0]: # [0,1]:\n defaultT = 4\n for workload in ['YCSB']: # , 'TPCC']:\n \n runExpr('Tp', [tp], resDirSens, numTrials, \n workload=workload, log_type='D', log_alg ='T', cc_alg='NO_WAIT', Ln=ln, Lr=Lr, t=defaultT)\n runExpr('Tp', [tp], resDirSens, numTrials, \n workload=workload, log_type='C', log_alg ='T', cc_alg='NO_WAIT', Ln=ln, Lr=Lr, t=defaultT)\n\ndef sensitivityCompression8():\n resDirSens = getResDir('compress')\n numTrials = 3 # 4 # 4 # 4 # 4\n defaultT = 56 # 27\n DEFAULT_LOG_NUM = 8\n global paramOverride \n tpLevel = [100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000] \n \n # increase logging frequency\n print('Make Sure BIG_HASH_TABLE_MODE is off!!')\n tpLevel = [10000000]\n paramOverride = ' -z0.6 -R8 -r0.5 -Tl30000000 -Gx150000 -Lz20 -Lad0 -Lal1 -l1003 -Lb2621440'\n for tp in tpLevel:\n for Lr in [0 , 1]: # [0,1]:\n # defaultT = 3 + Lr * 24\n defaultT = 8 + Lr * 48\n for workload in ['YCSB']: # , 'TPCC']:\n runExpr('Tp', [tp], resDirSens, numTrials, \n workload=workload, log_type='D', log_alg ='T', cc_alg='NO_WAIT', Ln=DEFAULT_LOG_NUM, Lr=Lr, t=defaultT)\n runExpr('Tp', [tp], resDirSens, numTrials, \n workload=workload, log_type='C', log_alg ='T', cc_alg='NO_WAIT', Ln=DEFAULT_LOG_NUM, Lr=Lr, t=defaultT)\n \n sys.exit(0)\n\n\ndef sensitivityCompression():\n resDirSens = getResDir('compress')\n numTrials = 4 # 4 # 4 # 4 # 4\n defaultT = 28 # 27\n global paramOverride \n tpLevel = [100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000]\n\n paramOverride = ' -z0.6 -R8 -r0.5 -n16 -Tp0 -l40003 -Gx50000 -Lz20 -Lad0 -Lal1 -Lt30000 -Lb104857600'\n defaultT = 4\n tlLevel =[300, 3000, 30000, 300000, 3000000, 30000000, 300000000]\n for tl in tlLevel:\n for Lr in [0]: # , 1]: # [0,1]:\n defaultT = 8 + Lr * 20 # we want to demonstrate high tlLevel could lead to better parallelism in recovery\n for workload in ['YCSB']: # , 'TPCC']:\n runExpr('Tl', [tl], resDirSens, numTrials, \n workload=workload, log_type='D', log_alg ='T', cc_alg='NO_WAIT', Ln=DEFAULT_LOG_NUM, Lr=Lr, t=defaultT)\n runExpr('Tl', [tl], resDirSens, numTrials, \n workload=workload, log_type='C', log_alg ='T', cc_alg='NO_WAIT', Ln=DEFAULT_LOG_NUM, Lr=Lr, t=defaultT)\n\ndef sweepLBRAID8():\n resDirShort = getResDir('sensLB')\n numTrials = 4\n shortX = [1, 8, 16, 24, 32, 40, 48, 56]\n global paramOverride# parameterOverride\n global RAID0_MODE\n lbLevel = [int(524288000/4**3 * 4**i) for i in range(9)]\n RAID0_MODE = True\n paramOverride = '-R2 -z0.6 -r0.5 -l640003 -Tp0 -Gx1500000 -Tl30000000 -Lz10 -Lw10 -Ls0.05 -Lt0 -Lad0 -Lal1 -s524288000'\n runExpr('Lb', lbLevel, resDirShort, numTrials,\n workload='YCSB', log_type='D', log_alg='S', cc_alg='NO_WAIT', Ln=1, Lr=0, z=0.6, t=56)\n RAID0_MODE = False\n\n\ndef normalizeToLK(x):\n return int(x) * 512 # has to be 512*k\n\ndef optimizeParam(param, bounds, defaultT, numTrials, cc='NO_WAIT', log_type='D', log_alg='T', Ln=16, Lr=1, workload='YCSB', maxiter=20, normalizeInstanceFn=normalizeToLK):\n resDirSens = getResDir('optSensitivity')\n def fTC1(x):\n thr = runExpr(param, [normalizeInstanceFn(x)], resDirSens, numTrials, True,\n workload = workload, log_type=log_type, log_alg=log_alg, cc_alg=cc, Ln=Ln, Lr=Lr, t=defaultT)\n print(x, thr)\n t = -1 * thr # [0][1]\n return t\n result = optimize.minimize_scalar(fTC1, bounds=bounds, method='Bounded', options=dict(maxiter=maxiter))\n return result\n\ndef optimizeReadBlockSize():\n global paramOverride\n paramOverride = '-Ln16 -Lr0 -t64 -z0.6 -R2 -r0.5 -l320003 -Tp0 -Gx150000 -Tl30000000 -Lz10 -Lw10 -Lad0 -Lal1 -s524288000 -LD8 -n64'\n print(optimizeParam('LK', [409600/512, 419430400 / 512], 64, 1))\n\ndef sweepBlocksize16():\n resDirSens = getResDir('sensBS')\n global paramOverride\n paramOverride = '-Ln16 -Lr0 -t64 -z0.6 -R2 -r0.5 -l320003 -Tp0 -Gx150000 -Tl30000000 -Lz10 -Lw10 -Lad0 -Lal1 -s524288000 -LD8 -n64'\n lbLevel = [400 * 1024 * 2**x for x in range(10)]\n\n runExpr('LB', lbLevel, resDirSens, 1, workload='YCSB', log_type='D', log_alg='T', cc_alg='NO_WAIT', Ln=16, Lr=0, t=64)\n\n runExpr('LK', lbLevel, resDirSens, 1, workload='YCSB', log_type='D', log_alg='T', cc_alg='NO_WAIT', Ln=16, Lr=1, t=64)\n\ndef sweepLB8():\n resDirSens = getResDir('sensLB')\n global paramOverride\n paramOverride = '-Ln8 -Lr0 -t56 -z0.6 -R2 -r0.5 -l320003 -Tp0 -Gx1500000 -Tl30000000 -Lz10 -Lw10 -Ls0.05 -Lad0 -Lal1 -s524288000'\n lbLevel = [int(524288000/4**5 * 4**i) for i in range(9)]\n runExpr('Lb', lbLevel, resDirSens, 1, workload='YCSB', log_type='D', log_alg='T', cc_alg='NO_WAIT', Ln=8, Lr=0, t=56)\n\ndef sweepR8Lr0():\n sweepR8([0], Ln=8)\n\ndef sweepR16_F():\n sweepR8(paramOverrideReplacer=chainPO([addDiskNum, changeWH, reduceGx, ycsb500G, addInitLocktableSlot]), dir='sensR16-ycsb500-', defaultT=80, Lrs=[0])\n\ndef sweepR8_F():\n sweepR8(paramOverrideReplacer=chainPO([addDiskNum, changeWH, reduceGx, addInitLocktableSlot]), Ln=8)\n sweepR8(paramOverrideReplacer=chainPO([addDiskNum, changeWH, reduceGx, addInitLocktableSlot]), cc_alg='SILO', Ln=8, defaultT=56)\n\ndef sweepR8(Lrs=[0, 1], cc_alg='NO_WAIT', workload='YCSB', paramOverrideReplacer=straightThrough, blocksize=i3metal_nvme2, Ln=16, dir='sensR', defaultT=64):\n resDirSens = getResDir(dir)\n global paramOverride\n \n rlevel = [2, 20, 200, 2000] # , 20000]\n for rval in rlevel:\n paramOverride = paramOverrideReplacer(' -r0.5 -l320003 -Tp0 -z0.6 -Tl30000000 -Lz10 -Lw10 -Lb32768000 -Lad0 -Lal1 -s524288000 -Gx%d -Ld%d -LB%d -LK%d' % (320003 * 2 / rval, 16384 / 8 * rval, blocksize[0], blocksize[1])) # in case memory full\n for Lr in Lrs:\n runExpr('R', [rval], resDirSens, 1, workload=workload, log_type='D', log_alg='L', cc_alg=cc_alg, Ln=Ln, Lr=Lr, t=defaultT)\n runExpr('R', [rval], resDirSens, 1, workload=workload, log_type='C', log_alg='L', cc_alg=cc_alg, Ln=Ln, Lr=Lr, t=defaultT)\n runExpr('R', [rval], resDirSens, 1, workload=workload, log_type='D', log_alg='V', cc_alg=cc_alg, Ln=Ln, Lr=Lr, t=defaultT)\n runExpr('R', [rval], resDirSens, 1, workload=workload, log_type='D', log_alg='N', cc_alg=cc_alg, Ln=Ln, Lr=0, t=defaultT)\n\ndef optimizeSensitivity():\n resDirSens = getResDir('optSensitivity')\n numTrials = 1\n defaultT = 28\n cc = 'NO_WAIT'\n global paramOverride\n paramOverride = '-R2 -r0.5 -l80003 -Tp0 -Tl30000000 -Ls0.05 -Lb10485760' #normal\n \n def fTC1(x):\n global paramOverride\n paramOverride = '-R2 -r0.5 -l80003 -Tp0 -Tl30000000 -Lz%d -Ls0.05 -Lb10485760' % int(x) # normal\n t = -1 * runExpr('z', [1.6], resDirSens, numTrials, True,\n workload = 'YCSB', log_type='C', log_alg ='T', cc_alg=cc, Ln=1, Lr=1, t=defaultT)\n print(x, t)\n return t\n result = optimize.minimize_scalar(fTC1, bounds=(1, 100000), method='Bounded', maxiter=20)\n print('z1.6', result)\n\ndef sensitivity8(numTrials=1):\n sensitivity(8, 56, paramOverrideReplacer=chainPO([ycsb10G, useGx1500000, changeWH]), blocksize=h1_16xlarge_hdd, numTrials=numTrials)\n\ndef sensitivityRAID8(senFn=sensitivity8, numTrials=1):\n global globalFilter, RAID0_MODE\n globalFilter = ['rundb_SC_YCSB_NOWAIT', 'rundb_SD_YCSB_NOWAIT']\n RAID0_MODE = 1 # translate the result\n sensitivity(8, 56, paramOverrideReplacer=chainPO([ycsb10G, useGx1500000, changeWH]), blocksize=h1_16xlarge_hdd, numTrials=numTrials)\n RAID0_MODE = 0\n\ndef smallerLogBuffer(s):\n return s + ' -Lb32768000'\n\ndef ycsb500G(s):\n return s + ' -s524288000'\n\ndef ycsb10G(s):\n return s + ' -s10485760'\n\ndef smallerLockTable(s):\n return s + ' -l128000'\n\ndef sensitivity16RAID(numTrials=1):\n global RAID0_MODE, globalFilter\n\n globalFilter = ['rundb_SC_YCSB_NOWAIT', 'rundb_SD_YCSB_NOWAIT']\n\n RAID0_MODE = 1\n sensitivity(16, 64, paramOverrideReplacer=chainPO([addDiskNum, changeWH, addInitLocktableSlot, smallerLogBuffer, ycsb10G, smallerLockTable, useGx1000000]), dir='sensitivity16-fixbs-', blocksize=i3metal_nvme_raid8, numTrials=numTrials) # , zLevel1=[0.0, 0.4, 0.6, 0.8, 0.99], zLevel2=[1.2, 1.6])\n RAID0_MODE = 0\n\ndef sensitivity16(numTrials=1):\n sensitivity(16, 64, paramOverrideReplacer=chainPO([addDiskNum, changeWH, reduceGx, addInitLocktableSlot, smallerLogBuffer, ycsb10G, smallerLockTable]), dir='sensitivity16-fixbs-', blocksize=i3metal_nvme2, numTrials=numTrials) # , zLevel1=[0.0, 0.4, 0.6, 0.8, 0.99], zLevel2=[1.2, 1.6])\n\ndef sensitivity(ln=DEFAULT_LOG_NUM, dT=28, paramOverrideReplacer=straightThrough, dir='sensitivity', numTrials=1, blocksize=i3metal_nvme, cc_alg='NO_WAIT', zLevel1 = [0.0, 0.2, 0.4, 0.6, 0.8, 0.9, 0.99], zLevel2 =[1.05, 1.2, 1.4, 1.6] ):\n resDirSens = getResDir(dir)\n defaultT = dT # 27\n cc = cc_alg\n global paramOverride\n global RAID0_MODE\n \n for zl in zLevel1:\n for Lr in [0]: # [0, 1]:\n paramOverride = paramOverrideReplacer('-R2 -r0.5 -l2560003 -Tp0 -Gx1500000 -Tl30000000 -Lz10 -Lw10 -Lb104857600 -Lad0 -Lal1 -LB%d -LK%d' % (blocksize[0], blocksize[1])) # normal\n runExpr('z', [zl], resDirSens, numTrials, \n workload = 'YCSB', log_type='C', log_alg ='S', cc_alg=cc, Ln=1, Lr=Lr, t=defaultT)\n \n runExpr('z', [zl], resDirSens, numTrials, \n workload = 'YCSB', log_type='C', log_alg ='L', cc_alg=cc, Ln=ln, Lr=Lr, t=defaultT)\n\n runExpr('z', [zl], resDirSens, numTrials, \n workload = 'YCSB', log_type='D', log_alg ='B', cc_alg='SILO', Ln=ln, Lr=Lr, t=defaultT)\n \n paramOverride = paramOverrideReplacer('-R2 -r0.5 -l320003 -Tp0 -Gx1500000 -Tl30000000 -Lz10 -Lw10 -Lb104857600 -Lad0 -Lal1 -LB%d -LK%d' % (blocksize[0], blocksize[1]))\n \n runExpr('z', [zl], resDirSens, numTrials, \n workload = 'YCSB', log_type='D', log_alg ='S', cc_alg=cc, Ln=1, Lr=Lr, t=defaultT)\n \n runExpr('z', [zl], resDirSens, numTrials, \n workload = 'YCSB', log_type='D', log_alg ='L', cc_alg=cc, Ln=ln, Lr=Lr, t=defaultT)\n\n runExpr('z', [zl], resDirSens, numTrials, \n workload = 'YCSB', log_type='D', log_alg ='V', cc_alg=cc, Ln=ln, Lr=Lr, t=defaultT)\n for Lr in [1]:\n\n paramOverride = paramOverrideReplacer('-R2 -r0.5 -l160003 -Tp0 -Tl30000000 -Lz10 -Lw10 -Lb262144000 -Lad0 -Lal1 -LB%d -LK%d' % (blocksize[0], blocksize[1])) # normal\n runExpr('z', [zl], resDirSens, numTrials,\n workload = 'YCSB', log_type='C', log_alg ='S', cc_alg=cc, Ln=1, Lr=Lr, t=defaultT)\n \n runExpr('z', [zl], resDirSens, numTrials,\n workload = 'YCSB', log_type='C', log_alg ='L', cc_alg=cc, Ln=ln, Lr=Lr, t=defaultT)\n \n runExpr('z', [zl], resDirSens, numTrials,\n workload = 'YCSB', log_type='C', log_alg ='W', cc_alg=cc, Ln=ln, Lr=Lr, t=defaultT)\n \n runExpr('z', [zl], resDirSens, numTrials,\n workload = 'YCSB', log_type='D', log_alg ='B', cc_alg='SILO', Ln=ln, Lr=Lr, t=defaultT)\n \n paramOverride = paramOverrideReplacer('-R2 -r0.5 -l160003 -Tp0 -Tl30000000 -Gx1500000 -Lz10 -Lw10 -Lb209715200 -Lad0 -Lal1 -LB%d -LK%d' % (blocksize[0], blocksize[1]))\n \n runExpr('z', [zl], resDirSens, numTrials,\n workload = 'YCSB', log_type='D', log_alg ='L', cc_alg=cc, Ln=ln, Lr=Lr, t=defaultT)\n runExpr('z', [zl], resDirSens, numTrials,\n workload = 'YCSB', log_type='D', log_alg ='W', cc_alg=cc, Ln=ln, Lr=Lr, t=defaultT)\n \n runExpr('z', [zl], resDirSens, numTrials,\n workload = 'YCSB', log_type='D', log_alg ='S', cc_alg=cc, Ln=1, Lr=Lr, t=defaultT)\n runExpr('z', [zl], resDirSens, numTrials, \n workload = 'YCSB', log_type='D', log_alg ='V', cc_alg=cc, Ln=ln, Lr=Lr, t=defaultT)\n \n paramOverride = paramOverrideReplacer('-R2 -r0.5 -l320003 -Tp0 -Gx1500000 -Tl30000000 -Lz10 -Lw10 -Lb104857600 -Lad0 -Lal1 -LB%d -LK%d' % (blocksize[0], blocksize[1]))\n runExpr('z', [zl], resDirSens, numTrials, \n workload = 'YCSB', log_type='D', log_alg ='N', cc_alg=cc, Ln=ln, Lr=0, t=defaultT)\n\n for zl in zLevel2:\n for Lr in [0]: # [0, 1]:\n paramOverride = paramOverrideReplacer('-R2 -r0.5 -l320003 -Tp0 -Gx150000 -Tl30000000 -Lz100 -Lw5 -Lb104857600 -Lad0 -Lal1 -LB%d -LK%d' % (blocksize[0], blocksize[1]))\n runExpr('z', [zl], resDirSens, numTrials, \n workload = 'YCSB', log_type='D', log_alg ='S', cc_alg=cc, Ln=1, Lr=Lr, t=defaultT)\n runExpr('z', [zl], resDirSens, numTrials, \n workload = 'YCSB', log_type='D', log_alg ='B', cc_alg='SILO', Ln=ln, Lr=Lr, t=defaultT)\n \n runExpr('z', [zl], resDirSens, numTrials, \n workload = 'YCSB', log_type='D', log_alg ='L', cc_alg=cc, Ln=ln, Lr=Lr, t=defaultT)\n \n runExpr('z', [zl], resDirSens, numTrials, \n workload = 'YCSB', log_type='D', log_alg ='V', cc_alg=cc, Ln=ln, Lr=Lr, t=defaultT)\n paramOverride = paramOverrideReplacer('-R2 -r0.5 -l320003 -Tp0 -Gx150000 -Tl30000000 -Lz2000 -Lw10 -Lb104857600 -Lad0 -Lal1 -LB%d -LK%d' % (blocksize[0], blocksize[1]))\n \n runExpr('z', [zl], resDirSens, numTrials, \n workload = 'YCSB', log_type='C', log_alg ='L', cc_alg=cc, Ln=ln, Lr=Lr, t=defaultT)\n \n runExpr('z', [zl], resDirSens, numTrials, \n workload = 'YCSB', log_type='C', log_alg ='S', cc_alg=cc, Ln=1, Lr=Lr, t=defaultT)\n \n for Lr in [1]:\n\n paramOverride = paramOverrideReplacer('-R2 -r0.5 -l160003 -Tp0 -Tl30000000 -Gx150000 -Lz100 -Lw5 -Lb262144000 -Lad0 -Lal1 -LB%d -LK%d' % (blocksize[0], blocksize[1])) # normal\n runExpr('z', [zl], resDirSens, numTrials,\n workload = 'YCSB', log_type='D', log_alg ='S', cc_alg=cc, Ln=1, Lr=Lr, t=defaultT)\n runExpr('z', [zl], resDirSens, numTrials,\n workload = 'YCSB', log_type='C', log_alg ='S', cc_alg=cc, Ln=1, Lr=Lr, t=defaultT)\n runExpr('z', [zl], resDirSens, numTrials,\n workload = 'YCSB', log_type='D', log_alg ='B', cc_alg='SILO', Ln=ln, Lr=Lr, t=defaultT)\n \n runExpr('z', [zl], resDirSens, numTrials,\n workload = 'YCSB', log_type='D', log_alg ='L', cc_alg=cc, Ln=ln, Lr=Lr, t=defaultT)\n runExpr('z', [zl], resDirSens, numTrials,\n workload = 'YCSB', log_type='C', log_alg ='L', cc_alg=cc, Ln=ln, Lr=Lr, t=defaultT)\n runExpr('z', [zl], resDirSens, numTrials,\n workload = 'YCSB', log_type='D', log_alg ='V', cc_alg=cc, Ln=ln, Lr=Lr, t=defaultT)\n runExpr('z', [zl], resDirSens, numTrials,\n workload = 'YCSB', log_type='D', log_alg ='W', cc_alg=cc, Ln=ln, Lr=Lr, t=defaultT)\n runExpr('z', [zl], resDirSens, numTrials,\n workload = 'YCSB', log_type='C', log_alg ='W', cc_alg=cc, Ln=ln, Lr=Lr, t=defaultT)\n \n paramOverride = paramOverrideReplacer('-R2 -r0.5 -l320003 -Tp0 -Gx150000 -Tl30000000 -Lz2000 -Lw10 -Lb104857600 -Lad0 -Lal1 -LB%d -LK%d' % (blocksize[0], blocksize[1]))\n runExpr('z', [zl], resDirSens, numTrials, \n workload = 'YCSB', log_type='D', log_alg ='N', cc_alg=cc, Ln=ln, Lr=0, t=defaultT)\n return # sys.exit(0)\n\ndef shortEC2RAID_8LF():\n resDirShort = getResDir('shortLF1')\n numTrials = 1 # 4 #[1, 2, 3] # [1, 2] # 4 # 4 # 4 #4# 4\n shortX = [56] # [1, 8, 16, 24, 32, 40, 48, 56] # [32, 40, 48, 56, 60] # [1, 4, 8, 12, 20, 28] # [28] # [1, 3, 6, 9, 12, 15, 18, 21, 24, 27]\n global paramOverride# parameterOverride\n global RAID0_MODE\n for workload in ['YCSB']: # 'TPCC']: # ['YCSB']: # ['YCSB', 'TPCC']:\n for Lr in [0]: # [0, 1]: # [1]: # [0, 1]: # [0, 1]:\n RAID0_MODE = True\n paramOverride = '-R2 -z0.6 -r0.5 -l640003 -Tp0 -Gx1500000 -Tl30000000 -Lz10 -Lw10 -Ls0.05 -Lb125537280 -Lt0 -Lad0 -Lal1'\n if Lr == 1:\n # change Lb\n paramOverride = '-R2 -z0.6 -r0.5 -l1 -Tp0 -Tl30000000 -Gx150000 -Lz10 -Lw10 -Ls0.5 -Lb20971520 -Lad0 -Lal1' # normal \n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='S', cc_alg='NO_WAIT', Ln=1, Lr=Lr, z=0.6, Lf=1)\n RAID0_MODE = False \n return \n\ndef shortEC2RAID_8_t64SD():\n global globalFilter\n globalFilter = ['rundb_SD_TPCC_NOWAIT']\n shortEC2RAID_8(shortX=[64], prefix='short-raid-64')\n\ndef shortEC2RAID_8_t64():\n shortEC2RAID_8(shortX=[64], prefix='short-raid-64')\n\ndef shortEC2RAID_F(numTrials=1):\n shortEC2RAID_8(prefix='short16-fixbs-', shortX=[1, 16, 32, 48, 64, 80], paramOverrideReplacer=chainPO([changeWH, useGx1000000, addInitLocktableSlot]), blocksize=h1_16xlarge_hdd_raid8, numTrials=numTrials)\n\ndef shortEC2RAID_8hdd(numTrials=1):\n shortEC2RAID_8(prefix='short-hdd', paramOverrideReplacer=chainPO([ycsb10G, useGx1500000, addInitLocktableSlot, changeWH]), blocksize=h1_16xlarge_hdd_raid8, numTrials=numTrials)\n\ndef shortEC2RAID_8(shortX = [1, 8, 16, 24, 32, 40, 48, 56], prefix='short', numTrials = 1, paramOverrideReplacer=straightThrough, blocksize=i3metal_nvme_raid8, cc_alg='NO_WAIT'):\n resDirShort = getResDir(prefix)\n \n global paramOverride# parameterOverride\n global RAID0_MODE\n \n for workload in ['YCSB']: \n for Lr in [0, 1]:\n RAID0_MODE = True\n paramOverride = paramOverrideReplacer('-R2 -z0.6 -r0.5 -l640003 -Tp0 -Gx1500000 -Tl30000000 -Lz10 -Lw10 -Lb524288000 -Lt0 -Lad0 -Lal1 -s524288000 -LB262142976 -LB%d -LK%d' % (blocksize[0], blocksize[1]))\n if Lr == 1:\n # change Lb\n paramOverride = paramOverrideReplacer('-R2 -z0.6 -r0.5 -l1 -Tp0 -Tl30000000 -Gx150000 -Lz10 -Lw10 -Lb524288000 -Lad0 -Lal1 -s524288000 -LB262142976 -LB%d -LK%d' % (blocksize[0], blocksize[1])) # normal \n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='S', cc_alg=cc_alg, Ln=1, Lr=Lr, z=0.6)\n\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='S', cc_alg=cc_alg, Ln=1, Lr=Lr, z=0.6)\n \n RAID0_MODE = False\n\n for workload in ['TPCC']:\n for Tm in [0.0, 1.0]:\n for Lr in [0, 1]:\n\n RAID0_MODE = True\n \n paramOverride = paramOverrideReplacer('-R2 -n56 -z0.6 -r0.5 -l80003 -Tp0 -Tl30000000 -Gx1500000 -Lz10 -Lw10 -Lb838860800 -Lt0 -Lad0 -Lal1 -LB262142976 -LB%d -LK%d' % (blocksize[0], blocksize[1])) # normal\n if Lr==1:\n paramOverride = paramOverrideReplacer('-R2 -n56 -z0.6 -r0.5 -l1 -Tp0 -Tl30000000 -Gx150000 -Lz10 -Lw10 -Lb1255372800 -Lad0 -Lal1 -LB262142976 -LB%d -LK%d' % (blocksize[0], blocksize[1])) # normal\n \n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='S', cc_alg=cc_alg, Ln=1, Lr=Lr, Tm=Tm)\n \n # continue\n\n paramOverride = paramOverrideReplacer('-R2 -n56 -z0.6 -r0.5 -l80003 -Tp0 -Tl30000000 -Gx1500000 -Lz10 -Lw10 -Lb838860800 -Lt0 -Lad0 -Lal1 -LB262142976 -LB%d -LK%d' % (blocksize[0], blocksize[1])) # normal\n if Lr==1:\n paramOverride = paramOverrideReplacer('-R2 -n56 -z0.6 -r0.5 -l1 -Tp0 -Tl30000000 -Gx1500000 -Lz10 -Lw10 -Lb20971520 -Lad0 -Lal1 -LB262142976 -LB%d -LK%d' % (blocksize[0], blocksize[1])) # normal\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='S', cc_alg=cc_alg, Ln=1, Lr=Lr, Tm=Tm)\n\n RAID0_MODE = False\n\ndef shortEC2RAID():\n resDirShort = getResDir('short')\n numTrials = 4\n shortX = [32, 40, 48, 56, 60]\n \n ############# NEW\n \n global paramOverride\n global RAID0_MODE\n \n paramOverride = '-R2 -z0.9 -r0.5 -l320003 -Tp0 -Gx1500000 -Tl30000000 -Lz10 -Lw10 -Ls0.05 -Lb838860800 -Lt0 -Lad0 -Lal1'\n \n for workload in ['YCSB']:\n for Lr in [0]:\n RAID0_MODE = True\n if Lr == 1:\n # change Lb\n paramOverride = '-R2 -z0.9 -r0.5 -l1 -Tp0 -Tl30000000 -Gx1500000 -Lz10 -Lw10 -Ls0.5 -Lb2621440 -Lad0 -Lal1' # normal \n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='S', cc_alg='NO_WAIT', Ln=1, Lr=Lr)\n RAID0_MODE = False \n \n # best params so far for TPCC\n paramOverride = '-R2 -n32 -z0.9 -r0.5 -l80003 -Tp0 -Tl30000000 -Gx1500000 -Lz10 -Lw10 -Ls0.05 -Lb838860800 -Lt0 -Lad0 -Lal1' # normal\n \n #################\n\n for workload in ['TPCC']: \n for Tm in [0.0, 1.0]: \n for Lr in [0]:\n RAID0_MODE = True\n if Lr==1:\n paramOverride = '-R2 -n32 -z0.9 -r0.5 -l1 -Tp0 -Tl30000000 -Gx1500000 -Lz10 -Lw10 -Ls0.5 -Lb2621440 -Lad0 -Lal1' # normal\n \n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='S', cc_alg='NO_WAIT', Ln=1, Lr=Lr, Tm=Tm)\n \n RAID0_MODE = False\n\ndef sensBF():\n defaultT = 56\n numTrials = 1\n resDirSens = getResDir('sensBF')\n lbLevel = [int(10485760*2**7 * 2**i) for i in range(10)]\n \n global paramOverride# parameterOverride\n global RAID0_MODE\n paramOverride = '-R2 -n32 -z0.6 -r0.5 -l2560003 -Tp0 -Tl30000000 -Lz10 -Lw10 -Ls0.5 -Lad0 -Lal1' # normal\n runExpr('Lb', lbLevel, resDirSens, numTrials, \n workload = 'YCSB', log_type='D', log_alg ='T', cc_alg='NO_WAIT', Ln=8, Lr=1, t=defaultT) # , Tm=1.0)\n \n\ndef prepareLog():\n pass\n\ndef shortEC2_8Prep():\n shortEC2_8(True)\n\ndef shortEC2Prep():\n shortEC2(True)\n\ndef addDiskNum(s):\n return s + ' -LD8' # + ' -l640003'\n\ndef addInitLocktableSlot(s):\n return s + ' -Li1 '\n\ndef addRamDisk(s):\n return s + ' -LD2 -LR1'\n\ndef changeWH64(s):\n return s + ' -n64'\n\ndef changeWH80(s):\n return s + ' -n80'\n\nchangeWH = changeWH80\n\ndef reduceGx(s):\n return s.replace('-Gx1500000', '-Gx150000')\n\ndef reduceLockTableModifier(s):\n return s + ' -l50003'\n\ndef chainPO(overriderList):\n def foo(s):\n for func in overriderList:\n s = func(s)\n return s\n return foo\n\ndef simd(blocksize=i3metal_nvme2, paramOverrideReplacer=chainPO([addDiskNum, changeWH, reduceGx, ycsb10G]), dir='simd-ycsb10g-'):\n global globalFilter\n global paramOverride\n resDirShort = getResDir(dir)\n globalFilter = ['rundb_LC_YCSB_NOWAIT', 'rundb_UC_YCSB_NOWAIT']\n print(\"Compiling TC with SIMD-on and SIMD-off...\")\n print(subprocess.check_output(\"python3 %s/tools/compile.py LC_YCSB_NOWAIT\" % PATH, shell=True))\n print(subprocess.check_output(\"python3 %s/tools/compile_simd_off.py UC_YCSB_NOWAIT\" % PATH, shell=True))\n \n lns = [1, 2, 4, 8, 12, 16]\n shortX = [64]\n workload = 'YCSB'\n paramOverride = paramOverrideReplacer('-R2 -z0.6 -r0.5 -l1280003 -Tp0 -Gx150000 -Tl30000000 -Lz10 -Lw10 -Lb52428800 -Lad0 -Lal1 -s524288000 -LB%d -LK%d' % (blocksize[0], blocksize[1]))\n numTrials = 1\n for Ln in lns:\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='L', cc_alg='NO_WAIT', Ln=Ln, Lr=0, z=0.6)\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='U', cc_alg='NO_WAIT', Ln=Ln, Lr=0, z=0.6)\n\ndef ycsbR8(x):\n return x + ' -R8'\n\ndef shortEC2_16BD():\n global globalFilter\n globalFilter = ['rundb_BD_YCSB_SILO', 'rundb_BD_TPCC_SILO']\n shortEC2_8(YCSB=True, TPCC=True, TPCC_Tms=[0., 1.], dir='short16-fixbs-', Ln=16, paramOverrideReplacer=chainPO([addDiskNum, changeWH, reduceGx]), shortX=[64]) # [1, 16, 32, 48, 64])\n\ndef shortEC2_16R8():\n global globalFilter\n globalFilter = ['rundb_TD_YCSB_NOWAIT', 'rundb_VD_YCSB_NOWAIT', 'rundb_TC_YCSB_NOWAIT']\n shortEC2_8(YCSB=True, TPCC=True, TPCC_Tms=[0., 1.], dir='short16-fixbs-r8', Ln=16, paramOverrideReplacer=chainPO([addDiskNum, changeWH, reduceGx, ycsbR8]), shortX=[1, 16, 32, 48, 64])\n\ndef shortEC2_16(numTrials=1):\n shortEC2_8(YCSB=True, TPCC=True, TPCC_Tms=[0., 1.], dir='short16-fixbs-', Ln=16, paramOverrideReplacer=chainPO([addDiskNum, changeWH, useGx1000000, addInitLocktableSlot]), shortX=[1, 16, 32, 48, 64, 80], blocksize=i3metal_nvme2, numTrials=numTrials)\n\ndef tuneTCQueue(x):\n return x + ' -Lz2 -Lw1'\n\ndef shortEC2_16Silo(numTrials=1):\n shortEC2_8(YCSB=True, TPCC=True, TPCC_Tms=[0., 1.], dir='short16-fixbs-silo', Ln=16, paramOverrideReplacer=chainPO([addDiskNum, changeWH, useGx1000000, tuneTCQueue]), shortX=[1, 16, 32, 48, 64, 80], cc_alg='SILO', blocksize=i3metal_nvme2, numTrials=numTrials)\n\ndef shortEC2_16NoLogging():\n global globalFilter\n globalFilter = ['rundb_ND_YCSB_NOWAIT', 'rundb_ND_TPCC_NOWAIT']\n shortEC2_16()\n\ndef shortEC2_16TaurusTPCCTM1():\n global globalFilter\n globalFilter = ['rundb_TC_TPCC_NOWAIT']# ['rundb_TD_TPCC_NOWAIT', 'rundb_TC_TPCC_NOWAIT']\n shortEC2_8(YCSB=False, TPCC=True, TPCC_Tms=[1.], dir='short16-aws-', Ln=16, paramOverrideReplacer=chainPO([addDiskNum, changeWH, reduceGx]), shortX=[1, 16, 32, 48, 64])\n\ndef shortEC2_16Taurus():\n global globalFilter\n globalFilter = ['rundb_TD_YCSB_NOWAIT', 'rundb_TC_YCSB_NOWAIT', 'rundb_TD_TPCC_NOWAIT', 'rundb_TC_TPCC_NOWAIT']\n shortEC2_8(YCSB=True, TPCC=True, TPCC_Tms=[0., 1.], dir='short16-aws-', Ln=16, paramOverrideReplacer=chainPO([addDiskNum, changeWH, reduceGx]), shortX=[1, 16, 32, 48, 64])\n\ndef shortEC2_32Taurus():\n global globalFilter\n globalFilter = ['rundb_TD_YCSB_NOWAIT', 'rundb_TC_YCSB_NOWAIT', 'rundb_TD_TPCC_NOWAIT', 'rundb_TC_TPCC_NOWAIT']\n shortEC2_8(YCSB=True, TPCC=True, TPCC_Tms=[0., 1.], dir='short32', Ln=32, paramOverrideReplacer=addDiskNum, shortX=[64])\n\ndef clearRAMDISK():\n try:\n subprocess.check_output('rm /data0/*', shell=True)\n subprocess.check_output('rm /data1/*', shell=True)\n except subprocess.CalledProcessError:\n return\n\ndef shortEC2_16RAMDISKSilo():\n toRun = ['rundb_LC_YCSB_SILO', 'rundb_LD_YCSB_SILO'] # ['rundb_LC_YCSB_SILO', 'rundb_LD_YCSB_SILO', 'rundb_ND_YCSB_SILO', 'rundb_SD_YCSB_SILO', 'rundb_SC_YCSB_SILO', 'rundb_VD_YCSB_SILO'] # ['rundb_LC_YCSB_SILO', 'rundb_LD_YCSB_SILO', 'rundb_ND_YCSB_SILO', 'rundb_SD_YCSB_SILO', 'rundb_SC_YCSB_SILO', 'rundb_BD_YCSB_SILO'] # ['rundb_SD_YCSB_NOWAIT', 'rundb_TD_YCSB_NOWAIT', 'rundb_VD_YCSB_NOWAIT', 'rundb_SD_TPCC_NOWAIT', 'rundb_TD_TPCC_NOWAIT', 'rundb_VD_TPCC_NOWAIT'] # ['rundb_SD_YCSB_NOWAIT', 'rundb_SC_YCSB_NOWAIT', 'rundb_TD_YCSB_NOWAIT', 'rundb_TC_YCSB_NOWAIT', 'rundb_BD_YCSB_NOWAIT', 'rundb_ND_YCSB_NOWAIT', 'rundb_VD_YCSB_NOWAIT']\n\n global globalFilter\n for config in toRun:\n # we don't have much space\n clearRAMDISK()\n\n globalFilter = [config]\n\n shortEC2_8(YCSB=True, TPCC=False, TPCC_Tms=[0., 1.], dir='short16-YCSB-ram', Ln=16, paramOverrideReplacer=chainPO([addDiskNum, changeWH, reduceGx, addRamDisk, addInitLocktableSlot]), numTrials=1, blocksize=i3metal_nvme2, shortX=[1, 16, 32, 48, 64, 80], cc_alg='SILO')\n\ndef fineTuneRAMDISKRec(s):\n return s + ' -Lz250 -Lw100 -Lad1000 '\n\ndef shortEC2_16RAMDISK(numTrials=1):\n toRun = ['rundb_LC_YCSB_NOWAIT', 'rundb_LD_YCSB_NOWAIT', 'rundb_ND_YCSB_NOWAIT', 'rundb_SD_YCSB_NOWAIT', 'rundb_SC_YCSB_NOWAIT', 'rundb_VD_YCSB_NOWAIT'] # , 'rundb_WC_YCSB_NOWAIT', 'rundb_WD_YCSB_NOWAIT'] # ['rundb_LC_YCSB_SILO', 'rundb_LD_YCSB_SILO', 'rundb_ND_YCSB_SILO', 'rundb_SD_YCSB_SILO', 'rundb_SC_YCSB_SILO', 'rundb_BD_YCSB_SILO'] # ['rundb_SD_YCSB_NOWAIT', 'rundb_TD_YCSB_NOWAIT', 'rundb_VD_YCSB_NOWAIT', 'rundb_SD_TPCC_NOWAIT', 'rundb_TD_TPCC_NOWAIT', 'rundb_VD_TPCC_NOWAIT'] # ['rundb_SD_YCSB_NOWAIT', 'rundb_SC_YCSB_NOWAIT', 'rundb_TD_YCSB_NOWAIT', 'rundb_TC_YCSB_NOWAIT', 'rundb_BD_YCSB_NOWAIT', 'rundb_ND_YCSB_NOWAIT', 'rundb_VD_YCSB_NOWAIT']\n global globalFilter\n t = globalFilter\n for config in toRun:\n if config in t:\n # we don't have much space\n clearRAMDISK()\n\n globalFilter = [config]\n\n shortEC2_8(YCSB=True, TPCC=False, TPCC_Tms=[0., 1.], dir='short16-YCSB-ram', Ln=16, paramOverrideReplacer=chainPO([addDiskNum, changeWH, useGx1000000, addRamDisk, addInitLocktableSlot]), numTrials=numTrials, blocksize=i3metal_nvme2, shortX=[1, 16, 32, 48, 64, 80], cc_alg='NO_WAIT')\n globalFilter = t\n\ndef shortEC2_8RAMDISK():\n global globalFilter\n globalFilter = ['rundb_TC_YCSB_NOWAIT', 'rundb_TC_TPCC_NOWAIT', 'rundb_TD_YCSB_NOWAIT', 'rundb_VD_YCSB_NOWAIT','rundb_TD_TPCC_NOWAIT', 'rundb_VD_TPCC_NOWAIT'] # ['rundb_SD_YCSB_NOWAIT', 'rundb_TD_YCSB_NOWAIT', 'rundb_VD_YCSB_NOWAIT', 'rundb_SD_TPCC_NOWAIT', 'rundb_TD_TPCC_NOWAIT', 'rundb_VD_TPCC_NOWAIT'] # ['rundb_SD_YCSB_NOWAIT', 'rundb_SC_YCSB_NOWAIT', 'rundb_TD_YCSB_NOWAIT', 'rundb_TC_YCSB_NOWAIT', 'rundb_BD_YCSB_NOWAIT', 'rundb_ND_YCSB_NOWAIT', 'rundb_VD_YCSB_NOWAIT']\n\n shortEC2_8(YCSB=True, TPCC=True, dir='short-YCSB-ram', paramOverrideReplacer=chainPO([addRamDisk, addInitLocktableSlot]), numTrials=1, blocksize=i3metal_nvme2, shortX=[56])\n\ndef shortEC2_8YCSBTaurus():\n global globalFilter\n globalFilter = ['rundb_TD_YCSB_NOWAIT', 'rundb_TC_YCSB_NOWAIT']\n shortEC2_8(YCSB=True, TPCC=False, dir='short-YCSB')\n\ndef shortEC2_8TPCCTaurus():\n global globalFilter\n globalFilter = ['rundb_TD_TPCC_NOWAIT', 'rundb_TC_TPCC_NOWAIT']\n shortEC2_8TPCCTm1()\n shortEC2_8TPCCTm0()\n\ndef shortEC2_8YCSB():\n global globalFilter\n globalFilter = ['rundb_TD_YCSB_NOWAIT', 'rundb_TC_YCSB_NOWAIT', 'rundb_SD_YCSB_NOWAIT', 'rundb_SC_YCSB_NOWAIT']\n shortEC2_8(YCSB=True, TPCC=False, dir='short-YCSB')\n\ndef shortEC2_8YCSBPrep():\n shortEC2_8(prepareMode=True, YCSB=True, TPCC=False, dir='short')\n\ndef shortEC2_8TPCC():\n global globalFilter\n globalFilter = ['rundb_TD_TPCC_NOWAIT', 'rundb_TC_TPCC_NOWAIT', 'rundb_SD_TPCC_NOWAIT', 'rundb_SC_TPCC_NOWAIT']\n shortEC2_8TPCCTm1()\n shortEC2_8TPCCTm0()\n\ndef shortEC2_8TPCCTm0():\n shortEC2_8(YCSB=False, TPCC=True, TPCC_Tms=[0.], dir='short-Tm0')\n\ndef shortEC2_8TPCCTm0Prep():\n shortEC2_8(prepareMode=True, YCSB=False, TPCC=True, TPCC_Tms=[0.], dir='short')\n\ndef shortEC2_8TPCCTm1():\n shortEC2_8(YCSB=False, TPCC=True, TPCC_Tms=[1.], dir='short-Tm1')\n\ndef shortEC2_8TPCCTm1Prep():\n shortEC2_8(prepareMode=True, YCSB=False, TPCC=True, TPCC_Tms=[1.], dir='short')\n\ndef shortEC2_8TrySIMD():\n global globalFilter\n globalFilter=['TC_YCSB_NOWAIT', 'TC_TPCC_NOWAIT']\n shortEC2_8(YCSB=True, TPCC=True, TPCC_Tms=[1.], dir='short-simd-')\n\ndef useGx1000000(x):\n return x + ' -Gx1000000'\ndef useGx150000(x):\n return x + ' -Gx150000'\ndef useGx1500000(x):\n return x + ' -Gx1500000'\ndef useGx900000(x):\n return x + ' -Gx900000'\n\ndef shortEC2_8hdd(numTrials=1): \n global globalFilter\n globalFilter = filterExcludeMulti(filterFullSet, ['TC', 'TD']) # we use LC and LD instead\n shortEC2_8(dir='short-hdd', paramOverrideReplacer=chainPO([ycsb10G, useGx1000000, changeWH]), blocksize=h1_16xlarge_hdd, numTrials=numTrials)\n\ndef shortEC2_8(prepareMode = False, YCSB=True, TPCC=True, TPCC_Tms=[0.,1.], dir='short-main2x-', Ln=8, paramOverrideReplacer=straightThrough, shortX=[1, 8, 16, 24, 32, 40, 48, 56], numTrials=1, blocksize=i3metal_nvme, cc_alg='NO_WAIT'):\n resDirShort = getResDir(dir)\n\n if prepareMode:\n shortX = [1, 56]\n numTrials = 1\n print('!!!! Prepare Mode !!!!')\n \n global paramOverride\n global RAID0_MODE\n \n if YCSB:\n for workload in ['YCSB']:\n \n for Lr in [0]: \n\n paramOverride = paramOverrideReplacer('-R2 -r0.5 -l320003 -Tp0 -Gx150000 -Tl30000000 -Lz10 -Lw10 -Lb32768000 -Lad0 -Lal1 -s524288000 -LB%d -LK%d' % (blocksize[0], blocksize[1]))\n\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='S', cc_alg=cc_alg, Ln=1, Lr=Lr, z=0.6)\n \n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='T', cc_alg=cc_alg, Ln=Ln, Lr=Lr, z=0.6)\n\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='L', cc_alg=cc_alg, Ln=Ln, Lr=Lr, z=0.6)\n\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='V', cc_alg=cc_alg, Ln=Ln, Lr=Lr, z=0.6)\n\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='B', cc_alg='SILO', Ln=Ln, Lr=Lr, z=0.6)\n \n \n paramOverride = paramOverrideReplacer('-R2 -r0.5 -l1280003 -Tp0 -Gx150000 -Tl30000000 -Lz10 -Lw10 -Lb52428800 -Lad0 -Lal1 -s524288000 -LB%d -LK%d' % (blocksize[0], blocksize[1]))\n \n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='T', cc_alg=cc_alg, Ln=Ln, Lr=Lr, z=0.6)\n\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='L', cc_alg=cc_alg, Ln=Ln, Lr=Lr, z=0.6)\n \n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='S', cc_alg=cc_alg, Ln=1, Lr=Lr, z=0.6)\n \n if prepareMode:\n break # skip recovery'''\n\n for Lr in [1]: \n paramOverride = paramOverrideReplacer('-R2 -r0.5 -l320003 -Tp0 -Tl30000000 -Gx150000 -Lz10 -Lw10 -Lb33554432 -Lad0 -Lal1 -s524288000 -LB%d -LK%d' % (blocksize[0], blocksize[1]))\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='S', cc_alg=cc_alg, Ln=1, Lr=Lr, z=0.6)\n \n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='T', cc_alg=cc_alg, Ln=Ln, Lr=Lr, z=0.6)\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='L', cc_alg=cc_alg, Ln=Ln, Lr=Lr, z=0.6)\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='W', cc_alg=cc_alg, Ln=Ln, Lr=Lr, z=0.6)\n \n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='V', cc_alg=cc_alg, Ln=Ln, Lr=Lr, z=0.6)\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='B', cc_alg='SILO', Ln=Ln, Lr=Lr, z=0.6)\n \n paramOverride = paramOverrideReplacer('-R2 -r0.5 -l160003 -Tp0 -Tl30000000 -Lz10 -Lw10 -Gx150000 -Lb33554432 -Lad0 -Lal1 -s524288000 -LB%d -LK%d' % (blocksize[0], blocksize[1]))\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='T', cc_alg=cc_alg, Ln=Ln, Lr=Lr, z=0.6)\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='L', cc_alg=cc_alg, Ln=Ln, Lr=Lr, z=0.6)\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='W', cc_alg=cc_alg, Ln=Ln, Lr=Lr, z=0.6)\n \n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='S', cc_alg=cc_alg, Ln=1, Lr=Lr, z=0.6)\n \n paramOverride = paramOverrideReplacer('-R2 -r0.5 -l320003 -Tp0 -Tl30000000 -Gx150000 -Lz10 -Lw10 -Lb2621440 -Lad0 -Lal1 -s524288000 -LB%d -LK%d' % (blocksize[0], blocksize[1]))\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='N', cc_alg=cc_alg, Ln=Ln, Lr=0, z=0.6)\n \n if TPCC:\n for workload in ['TPCC']:\n for Tm in TPCC_Tms:\n for Lr in [0]:\n \n paramOverride = paramOverrideReplacer('-R2 -n56 -r0.5 -l50003 -Tp0 -Tl30000000 -Gx1500000 -Lz10 -Lw10 -Lb104857600 -Lt0 -Lad0 -Lal1 -LB%d -LK%d' % (blocksize[0], blocksize[1]))\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='S', cc_alg=cc_alg, Ln=1, Lr=Lr, Tm=Tm)\n\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='T', cc_alg=cc_alg, Ln=Ln, Lr=Lr, Tm=Tm)\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='L', cc_alg=cc_alg, Ln=Ln, Lr=Lr, Tm=Tm)\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='V', cc_alg=cc_alg, Ln=Ln, Lr=Lr, Tm=Tm)\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='B', cc_alg='SILO', Ln=Ln, Lr=Lr, Tm=Tm)\n \n paramOverride = paramOverrideReplacer('-R2 -n56 -r0.5 -l50003 -Tp0 -Tl30000000 -Gx1500000 -Lz10 -Lw10 -Lb104857600 -Lt0 -Lad0 -Lal1 -LB%d -LK%d' % (blocksize[0], blocksize[1]))\n \n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='S', cc_alg=cc_alg, Ln=1, Lr=Lr, Tm=Tm)\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='T', cc_alg=cc_alg, Ln=Ln, Lr=Lr, Tm=Tm)\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='L', cc_alg=cc_alg, Ln=Ln, Lr=Lr, Tm=Tm)\n \n if prepareMode:\n break # skip recovery\n for Lr in [1]:\n paramOverride = paramOverrideReplacer('-R2 -n56 -r0.5 -l320003 -Tp0 -Tl30000000 -Gx150000 -Lz10 -Lw10 -Lb33554432 -Lad0 -Lal1 -LB%d -LK%d' % (blocksize[0], blocksize[1]))\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='S', cc_alg=cc_alg, Ln=1, Lr=Lr, Tm=Tm)\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='T', cc_alg=cc_alg, Ln=Ln, Lr=Lr, Tm=Tm)\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='L', cc_alg=cc_alg, Ln=Ln, Lr=Lr, Tm=Tm)\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='W', cc_alg=cc_alg, Ln=Ln, Lr=Lr, Tm=Tm)\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='V', cc_alg=cc_alg, Ln=Ln, Lr=Lr, Tm=Tm)\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='B', cc_alg='SILO', Ln=Ln, Lr=Lr, Tm=Tm)\n \n paramOverride = paramOverrideReplacer('-R2 -n56 -r0.5 -l1 -Tp0 -Tl30000000 -Gx150000 -Lz10 -Lw10 -Lb33554432 -Lad0 -Lal1 -LB%d -LK%d' % (blocksize[0], blocksize[1]))\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='S', cc_alg=cc_alg, Ln=1, Lr=Lr, Tm=Tm)\n \n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='T', cc_alg=cc_alg, Ln=Ln, Lr=Lr, Tm=Tm)\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='W', cc_alg=cc_alg, Ln=Ln, Lr=Lr, Tm=Tm)\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='C', log_alg='L', cc_alg=cc_alg, Ln=Ln, Lr=Lr, Tm=Tm)\n\n paramOverride = paramOverrideReplacer('-R2 -n56 -r0.5 -l80003 -Tp0 -Tl30000000 -Gx150000 -Lz10 -Lw10 -Lb104857600 -Lt0 -Lad0 -Lal1 -LB%d -LK%d' % (blocksize[0], blocksize[1]))\n runExpr('t', shortX, resDirShort, numTrials,\n workload=workload, log_type='D', log_alg='N', cc_alg=cc_alg, Ln=Ln, Lr=0, Tm=Tm)\n\ndef allhdd():\n import prepareEC2_i3\n import prepareEC2_i3_raid_8\n prepareEC2_i3.run()\n\n all16_numTrials = 1 # 3\n\n global globalFilter\n\n globalFilter = filterExcludeMulti(filterFullSet, ['TC', 'TD']) # we use LC and LD instead\n\n shortEC2_8hdd(all16_numTrials)\n sensitivity8(all16_numTrials)\n\n prepareEC2_i3_raid_8.run()\n\n shortEC2RAID_8hdd(all16_numTrials)\n sensitivityRAID8(numTrials= all16_numTrials)\n\n\ndef all16_3():\n all16(1)\n all16(2)\n all16(3)\n\ndef all16(nt=3):\n # NVMe\n import prepareEC2_i3\n import prepareEC2_i3_raid_8\n import prepareEC2_i3_ramdisk\n import generateFigures\n global globalFilter\n global RAID0_MODE\n\n all16_fullFilter = filterFullSet\n all16_numTrials = nt # 3\n\n prepareEC2_i3.run()\n\n globalFilter = filterExcludeMulti(all16_fullFilter, ['SILO', 'TD', 'TC'])\n\n print(bcolors.OKGREEN + 'Main Result on NVMe...'+ bcolors.ENDC, globalFilter)\n\n if globalFilter != []:\n shortEC2_16(all16_numTrials)\n\n globalFilter = filterExcludeMulti(all16_fullFilter, ['NOWAIT', 'TD', 'TC', 'SD', 'SC'])\n\n print(bcolors.OKGREEN + 'Compare with Silo...' + bcolors.ENDC, globalFilter)\n \n if globalFilter != []:\n shortEC2_16Silo(all16_numTrials)\n\n # ramdisk\n prepareEC2_i3_ramdisk.run()\n\n globalFilter = filterExcludeMulti(all16_fullFilter, ['SILO', 'TD', 'TC', 'SD', 'SC', 'WC', 'WD'])\n\n print(bcolors.OKGREEN + 'RAM Disk...' + bcolors.ENDC)\n\n if globalFilter != []:\n shortEC2_16RAMDISK(all16_numTrials)\n\n # RAID-0\n prepareEC2_i3_raid_8.run()\n \n #globalFilter = ['rundb_SC_YCSB_NOWAIT', 'rundb_SD_YCSB_NOWAIT']\n #RAID0_MODE = 1 # translate the result\n globalFilter = filterExcludeMulti(all16_fullFilter, ['SILO', 'TD', 'TC'])\n\n print(bcolors.OKGREEN + 'RAID Main Result' + bcolors.ENDC)\n\n if globalFilter != []:\n shortEC2RAID_F(all16_numTrials)\n\n return\n\ndef run_all():\n all16()\n allhdd()\n\nimport atexit\nstarttime = datetime.datetime.now()\n\ndef all_done():\n global starttime\n endtime = datetime.datetime.now()\n print('time', endtime - starttime)\n\nif __name__ == '__main__':\n res = subprocess.check_output('mount | grep efs', shell=True).decode('utf-8')\n if not '/home/ubuntu/efs' in res:\n print(\"[!!!!!!!!!!!!!!!!!!!!]\")\n print(bcolors.WARNING + \"Warning: EFS not mounted.\" + bcolors.ENDC)\n input() # warning\n\n if len(sys.argv) > 1:\n if len(sys.argv) > 2:\n paramOverride = ''.join(sys.argv[2:])\n if paramOverride[0] != ' ':\n paramOverride = ' ' + paramOverride\n print('Param overriden:', str(paramOverride))\n atexit.register(all_done)\n eval(sys.argv[1] + '()', globals(), locals())\n \n else:\n # run all the experiments\n short()\n shortSilo()\n sensitivity()\n LogNum()\n sensitivityCompressionAux()\n sensitivityCompression()\n \n\n print('Finished')\n sys.exit(0)\n" ]
[ [ "scipy.optimize.minimize_scalar" ] ]
johntiger1/blog-posts
[ "0d67a598025abbef6dcf9a44fe3ef14c93d9d357" ]
[ "scripts/plot_roc.py" ]
[ "import matplotlib.pyplot as plt\r\nfrom matplotlib.gridspec import GridSpec\r\nfrom sklearn.metrics import confusion_matrix, roc_auc_score, roc_curve\r\nfrom sklearn.metrics import f1_score, roc_auc_score, precision_recall_curve, roc_curve\r\n\r\n\r\ndef plot_conf_matrix_and_roc(estimator, X, y, figure_size=(16, 6)):\r\n \"\"\"\r\n Plot both confusion matrix and ROC curce on the same figure.\r\n\r\n Parameters:\r\n -----------\r\n estimator : sklearn.estimator\r\n model to use for predicting class probabilities.\r\n X : array_like\r\n data to predict class probabilities.\r\n y : array_like\r\n true label vector.\r\n figure_size : tuple (optional)\r\n size of the figure.\r\n\r\n Returns:\r\n --------\r\n plot : matplotlib.pyplot\r\n plot confusion matrix and ROC curve.\r\n \"\"\"\r\n # Compute tpr, fpr, auc and confusion matrix\r\n fpr, tpr, thresholds = roc_curve(y, estimator.predict_proba(X)[:, 1])\r\n auc = roc_auc_score(y, estimator.predict_proba(X)[:, 1])\r\n conf_mat_rf = confusion_matrix(y, estimator.predict(X))\r\n\r\n # Define figure size and figure ratios\r\n plt.figure(figsize=figure_size)\r\n gs = GridSpec(1, 2, width_ratios=(1, 2))\r\n\r\n # Plot confusion matrix\r\n ax0 = plt.subplot(gs[0])\r\n ax0.matshow(conf_mat_rf, cmap=plt.cm.Reds, alpha=0.2)\r\n\r\n for i in range(2):\r\n for j in range(2):\r\n ax0.text(x=j, y=i, s=conf_mat_rf[i, j], ha=\"center\", va=\"center\")\r\n plt.title(\"Confusion matrix\", y=1.1, fontdict={\"fontsize\": 20})\r\n plt.xlabel(\"Predicted\", fontdict={\"fontsize\": 14})\r\n plt.ylabel(\"Actual\", fontdict={\"fontsize\": 14})\r\n\r\n\r\n # Plot ROC curce\r\n ax1 = plt.subplot(gs[1])\r\n ax1.plot(fpr, tpr, label=\"auc = {:.3f}\".format(auc))\r\n plt.title(\"ROC curve\", y=1, fontdict={\"fontsize\": 20})\r\n ax1.plot([0, 1], [0, 1], \"r--\")\r\n plt.xlabel(\"False positive rate\", fontdict={\"fontsize\": 16})\r\n plt.ylabel(\"True positive rate\", fontdict={\"fontsize\": 16})\r\n plt.legend(loc=\"lower right\", fontsize=\"medium\");\r\n\r\n\r\ndef plot_roc(estimators, X, y, figure_size=(16, 6)):\r\n \"\"\"\r\n Plot both confusion matrix and ROC curce on the same figure.\r\n\r\n Parameters:\r\n -----------\r\n estimators : dict\r\n key, value for model name and sklearn.estimator to use for predicting\r\n class probabilities.\r\n X : array_like\r\n data to predict class probabilities.\r\n y : array_like\r\n true label vector.\r\n figure_size : tuple (optional)\r\n size of the figure.\r\n\r\n Returns:\r\n --------\r\n plot : matplotlib.pyplot\r\n plot confusion matrix and ROC curve.\r\n \"\"\"\r\n plt.figure(figsize=figure_size)\r\n for estimator in estimators.keys():\r\n # Compute tpr, fpr, auc and confusion matrix\r\n fpr, tpr, thresholds = roc_curve(y, estimators[estimator].predict_proba(X)[:, 1])\r\n auc = roc_auc_score(y, estimators[estimator].predict_proba(X)[:, 1])\r\n\r\n # Plot ROC curce\r\n plt.plot(fpr, tpr, label=\"{}: auc = {:.3f}\".format(estimator, auc))\r\n plt.title(\"ROC curve\", y=1, fontdict={\"fontsize\": 20})\r\n plt.legend(loc=\"lower right\", fontsize=\"medium\")\r\n\r\n plt.plot([0, 1], [0, 1], \"--\")\r\n plt.xlabel(\"False positive rate\", fontdict={\"fontsize\": 16})\r\n plt.ylabel(\"True positive rate\", fontdict={\"fontsize\": 16});\r\n\r\n\r\ndef plot_roc_and_pr_curves(models, X_train, y_train, X_valid, y_valid, roc_title, pr_title, labels):\r\n \"\"\"\r\n Plot roc and PR curves for all models.\r\n \r\n Arguments\r\n ---------\r\n models : list\r\n list of all models.\r\n X_train : list or 2d-array\r\n 2d-array or list of training data.\r\n y_train : list\r\n 1d-array or list of training labels.\r\n X_valid : list or 2d-array\r\n 2d-array or list of validation data.\r\n y_valid : list\r\n 1d-array or list of validation labels.\r\n roc_title : str\r\n title of ROC curve.\r\n pr_title : str\r\n title of PR curve.\r\n labels : list\r\n label of each model to be displayed on the legend.\r\n \"\"\"\r\n fig, axes = plt.subplots(1, 2, figsize=(14, 6))\r\n \r\n if not isinstance(X_train, list):\r\n for i, model in enumerate(models):\r\n model_fit = model.fit(X_train, y_train)\r\n model_probs = model.predict_proba(X_valid)[:, 1:]\r\n model_preds = model.predict(X_valid)\r\n model_auc_score = roc_auc_score(y_valid, model_probs)\r\n # model_f1_score = f1_score(y_valid, model_preds)\r\n fpr, tpr, _ = roc_curve(y_valid, model_probs)\r\n precision, recall, _ = precision_recall_curve(y_valid, model_probs)\r\n axes[0].plot(fpr, tpr, label=f\"{labels[i]}, auc = {model_auc_score:.3f}\")\r\n axes[1].plot(recall, precision, label=f\"{labels[i]}\")\r\n else:\r\n for i, model in enumerate(models):\r\n model_fit = model.fit(X_train[i], y_train[i])\r\n model_probs = model.predict_proba(X_valid[i])[:, 1:]\r\n model_preds = model.predict(X_valid[i])\r\n model_auc_score = roc_auc_score(y_valid[i], model_probs)\r\n # model_f1_score = f1_score(y_valid[i], model_preds)\r\n fpr, tpr, _ = roc_curve(y_valid[i], model_probs)\r\n precision, recall, _ = precision_recall_curve(y_valid[i], model_probs)\r\n axes[0].plot(fpr, tpr, label=f\"{labels[i]}, auc = {model_auc_score:.3f}\")\r\n axes[1].plot(recall, precision, label=f\"{labels[i]}\")\r\n axes[0].legend(loc=\"lower right\")\r\n axes[0].set_xlabel(\"FPR\")\r\n axes[0].set_ylabel(\"TPR\")\r\n axes[0].set_title(roc_title)\r\n axes[1].legend()\r\n axes[1].set_xlabel(\"recall\")\r\n axes[1].set_ylabel(\"precision\")\r\n axes[1].set_title(pr_title)\r\n plt.tight_layout()" ]
[ [ "matplotlib.pyplot.legend", "sklearn.metrics.roc_auc_score", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.title", "matplotlib.pyplot.subplots", "sklearn.metrics.roc_curve", "sklearn.metrics.precision_recall_curve", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.subplot", "matplotlib.gridspec.GridSpec", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.figure" ] ]
vansweej/tensorrt_demos
[ "f3192204b2aa4f93e5271f499c605b7590d6099b" ]
[ "yolo/plugins.py" ]
[ "\"\"\"plugins.py\n\nI referenced the code from https://github.com/dongfangduoshou123/YoloV3-TensorRT/blob/master/seralizeEngineFromPythonAPI.py\n\"\"\"\n\n\nimport ctypes\n\nimport numpy as np\nimport tensorrt as trt\n\ntry:\n ctypes.cdll.LoadLibrary('../plugins/libyolo_layer.so')\nexcept OSError as e:\n raise SystemExit('ERROR: failed to load ../plugins/libyolo_layer.so. '\n 'Did you forget to do a \"make\" in the \"../plugins/\" '\n 'subdirectory?') from e\n\n\ndef get_input_wh(model_name):\n \"\"\"Get input_width and input_height of the model.\"\"\"\n yolo_dim = model_name.split('-')[-1]\n if 'x' in yolo_dim:\n dim_split = yolo_dim.split('x')\n if len(dim_split) != 2:\n raise ValueError('ERROR: bad yolo_dim (%s)!' % yolo_dim)\n w, h = int(dim_split[0]), int(dim_split[1])\n else:\n h = w = int(yolo_dim)\n if h % 32 != 0 or w % 32 != 0:\n raise ValueError('ERROR: bad yolo_dim (%s)!' % yolo_dim)\n return w, h\n\n\ndef get_yolo_whs(model_name, w, h):\n \"\"\"Get yolo_width and yolo_height for all yolo layers in the model.\"\"\"\n if 'yolov3' in model_name:\n if 'tiny' in model_name:\n return [[w // 32, h // 32], [w // 16, h // 16]]\n else:\n return [[w // 32, h // 32], [w // 16, h // 16], [w // 8, h // 8]]\n elif 'yolov4' in model_name:\n if 'tiny' in model_name:\n return [[w // 32, h // 32], [w // 16, h // 16]]\n else:\n return [[w // 8, h // 8], [w // 16, h // 16], [w // 32, h // 32]]\n else:\n raise ValueError('ERROR: unknown model (%s)!' % args.model)\n\n\ndef verify_classes(model_name, num_classes):\n \"\"\"Verify 'classes=??' in cfg matches user-specified num_classes.\"\"\"\n cfg_file_path = model_name + '.cfg'\n with open(cfg_file_path, 'r') as f:\n cfg_lines = f.readlines()\n classes_lines = [l.strip() for l in cfg_lines if l.startswith('classes')]\n classes = [int(l.split('=')[-1]) for l in classes_lines]\n return all([c == num_classes for c in classes])\n\n\ndef get_anchors(model_name):\n \"\"\"Get anchors of all yolo layers from the cfg file.\"\"\"\n cfg_file_path = model_name + '.cfg'\n with open(cfg_file_path, 'r') as f:\n cfg_lines = f.readlines()\n yolo_lines = [l.strip() for l in cfg_lines if l.startswith('[yolo]')]\n mask_lines = [l.strip() for l in cfg_lines if l.startswith('mask')]\n anch_lines = [l.strip() for l in cfg_lines if l.startswith('anchors')]\n assert len(mask_lines) == len(yolo_lines)\n assert len(anch_lines) == len(yolo_lines)\n anchor_list = eval('[%s]' % anch_lines[0].split('=')[-1])\n mask_strs = [l.split('=')[-1] for l in mask_lines]\n masks = [eval('[%s]' % s) for s in mask_strs]\n anchors = []\n for mask in masks:\n curr_anchors = []\n for m in mask:\n curr_anchors.append(anchor_list[m * 2])\n curr_anchors.append(anchor_list[m * 2 + 1])\n anchors.append(curr_anchors)\n return anchors\n\n\ndef get_scales(model_name):\n \"\"\"Get scale_x_y's of all yolo layers from the cfg file.\"\"\"\n cfg_file_path = model_name + '.cfg'\n with open(cfg_file_path, 'r') as f:\n cfg_lines = f.readlines()\n yolo_lines = [l.strip() for l in cfg_lines if l.startswith('[yolo]')]\n scale_lines = [l.strip() for l in cfg_lines if l.startswith('scale_x_y')]\n if len(scale_lines) == 0:\n return [1.0] * len(yolo_lines)\n else:\n assert len(scale_lines) == len(yolo_lines)\n return [float(l.split('=')[-1]) for l in scale_lines]\n\n\ndef get_plugin_creator(plugin_name, logger):\n \"\"\"Get the TensorRT plugin creator.\"\"\"\n trt.init_libnvinfer_plugins(logger, '')\n plugin_creator_list = trt.get_plugin_registry().plugin_creator_list\n for c in plugin_creator_list:\n if c.name == plugin_name:\n return c\n return None\n\n\ndef add_yolo_plugins(network, model_name, num_classes, logger):\n \"\"\"Add yolo plugins into a TensorRT network.\"\"\"\n input_width, input_height = get_input_wh(model_name)\n yolo_whs = get_yolo_whs(model_name, input_width, input_height)\n if not verify_classes(model_name, num_classes):\n raise ValueError('bad num_classes (%d)' % num_classes)\n anchors = get_anchors(model_name)\n if len(anchors) != len(yolo_whs):\n raise ValueError('bad number of yolo layers: %d vs. %d' %\n (len(anchors), len(yolo_whs)))\n if network.num_outputs != len(anchors):\n raise ValueError('bad number of network outputs: %d vs. %d' %\n (network.num_outputs, len(anchors)))\n scales = get_scales(model_name)\n if any([s < 1.0 for s in scales]):\n raise ValueError('bad scale_x_y: %s' % str(scales))\n\n plugin_creator = get_plugin_creator('YoloLayer_TRT', logger)\n if not plugin_creator:\n raise RuntimeError('cannot get YoloLayer_TRT plugin creator')\n old_tensors = [network.get_output(i) for i in range(network.num_outputs)]\n new_tensors = [None] * network.num_outputs\n for i, old_tensor in enumerate(old_tensors):\n new_tensors[i] = network.add_plugin_v2(\n [old_tensor],\n plugin_creator.create_plugin('YoloLayer_TRT', trt.PluginFieldCollection([\n trt.PluginField(\"yoloWidth\", np.array(yolo_whs[i][0], dtype=np.int32), trt.PluginFieldType.INT32),\n trt.PluginField(\"yoloHeight\", np.array(yolo_whs[i][1], dtype=np.int32), trt.PluginFieldType.INT32),\n trt.PluginField(\"inputWidth\", np.array(input_width, dtype=np.int32), trt.PluginFieldType.INT32),\n trt.PluginField(\"inputHeight\", np.array(input_height, dtype=np.int32), trt.PluginFieldType.INT32),\n trt.PluginField(\"numClasses\", np.array(num_classes, dtype=np.int32), trt.PluginFieldType.INT32),\n trt.PluginField(\"numAnchors\", np.array(len(anchors[i]) // 2, dtype=np.int32), trt.PluginFieldType.INT32),\n trt.PluginField(\"anchors\", np.ascontiguousarray(anchors[i], dtype=np.float32), trt.PluginFieldType.FLOAT32),\n trt.PluginField(\"scaleXY\", np.array(scales[i], dtype=np.float32), trt.PluginFieldType.FLOAT32),\n ]))\n ).get_output(0)\n\n for new_tensor in new_tensors:\n network.mark_output(new_tensor)\n for old_tensor in old_tensors:\n network.unmark_output(old_tensor)\n\n return network\n" ]
[ [ "numpy.ascontiguousarray", "numpy.array" ] ]
mmadsen/axelrod-ct
[ "90ea4319dd571546888c4d2a50255514e7d7fb94" ]
[ "madsenlab/axelrod/analysis/descriptive_stats.py" ]
[ "#!/usr/bin/env python\n# Copyright (c) 2013. Mark E. Madsen <[email protected]>\n#\n# This work is licensed under the terms of the Apache Software License, Version 2.0. See the file LICENSE for details.\n\n\"\"\"\nDescription here\n\n\"\"\"\n\nimport logging as log\nfrom collections import defaultdict\nimport numpy as np\nimport math as m\nimport pprint as pp\n\ndef get_culture_count_map(pop):\n counts = defaultdict(int)\n graph = pop.agentgraph\n for nodename in graph.nodes():\n traits = graph.node[nodename]['traits']\n culture = pop.get_traits_packed(traits)\n counts[culture] += 1\n return counts\n\ndef get_culture_counts_dbformat(pop):\n \"\"\"\n Takes an instance of a \"population\" and counts the distinct trait lists (i.e., cultures in the\n Axelrod model sense) in the population. Cultures are represented by packing the feature/trait list\n into an integer which serves as an identifier for a unique combination of features and traits.\n\n The return value is a dict of culture id, count.\n \"\"\"\n counts = defaultdict(int)\n graph = pop.agentgraph\n for nodename in graph.nodes():\n traits = graph.node[nodename]['traits']\n culture = pop.get_traits_packed(traits)\n counts[culture] += 1\n\n # transform into the list of dicts that's more convenient to stuff into mongodb\n stored_counts = []\n for key,val in counts.items():\n stored_counts.append(dict(cultureid=str(key),count=val))\n #log.debug(\"counts: %s\", stored_counts)\n return stored_counts\n\n\ndef get_num_traits_per_individual_stats(pop):\n \"\"\"\n Takes an instance of a population and returns a tuple with the mean and standard deviation of the\n number of traits per individual. Only useful for the extensible and semantic models.\n\n \"\"\"\n sizes = []\n for nodename in pop.agentgraph.nodes():\n sizes.append(len(pop.agentgraph.node[nodename]['traits']))\n mean = np.mean(np.asarray(sizes))\n sd = m.sqrt(np.var(np.asarray(sizes)))\n return (mean, sd)\n\n\n\ndef diversity_shannon_entropy(freq_list):\n k = len(freq_list)\n sw = 0.0\n for i in range(0, k):\n sw += freq_list[i] * m.log(freq_list[i])\n if sw == 0:\n return 0.0\n else:\n return sw * -1.0\n\n\ndef diversity_iqv(freq_list):\n k = len(freq_list)\n\n if k <= 1:\n return 0.0\n\n isum = 1.0 - _sum_squares(freq_list)\n factor = float(k) / (float(k) - 1.0)\n iqv = factor * isum\n\n #logger.debug(\"k: %s isum: %s factor: %s iqv: %s\", k, isum, factor, iqv)\n return iqv\n\n\ndef _sum_squares(freq_list):\n ss = 0.0\n for p in freq_list:\n ss += p ** 2.0\n return ss\n\n\nclass PopulationTraitFrequencyAnalyzer(object):\n \"\"\"\n Analyzer for trait frequencies across the entire population. At each\n call to calculate_trait_frequencies(), the analyzer looks at the state\n of the agent population and stores frequencies. Subsequent calls to\n get methods will return frequencies, richness, or the Shannon entropy\n measure of evenness for the frequencies.\n\n To use this over time, call calculate_trait_frequencies() when you\n want a sample, and then the various get_* methods to return the\n desired metrics.\n\n \"\"\"\n\n def __init__(self, model):\n self.model = model\n self.total_traits = model.agentgraph.number_of_nodes()\n\n def get_trait_frequencies(self):\n return self.freq\n\n def get_trait_richness(self):\n \"\"\"\n Returns the number of traits with non-zero frequencies\n \"\"\"\n return len( [freq for freq in self.freq.values() if freq > 0] )\n\n def get_trait_evenness_entropy(self):\n return diversity_shannon_entropy(self.freq.values())\n\n def get_trait_spectrum(self):\n return self.spectrum\n\n\n def calculate_trait_frequencies(self):\n self.freq = None\n trait_counts = defaultdict(int)\n\n total = self.model.agentgraph.number_of_nodes()\n\n for agent_id in self.model.agentgraph.nodes():\n agent_traits = self.model.agentgraph.node[agent_id]['traits']\n for trait in agent_traits:\n trait_counts[trait] += 1\n\n #log.debug(\"counts: %s\", pp.pformat(trait_counts))\n\n self.freq = {k : float(v)/float(total) for k,v in trait_counts.items()}\n self.counts = trait_counts.items()\n\n spectrum_count = defaultdict(int)\n # we build the spectrum by counting the number of traits with a particular count\n for trait, count in trait_counts.items():\n spectrum_count[count] += 1\n\n spectra = []\n for popcount, numtraits in spectrum_count.items():\n spectra.append(dict(popcount=popcount,numtraits=numtraits))\n\n self.spectrum = spectra\n\n #log.debug(\"spectrum: %s\", pp.pformat(self.spectrum))\n\n\n\n\n\n\n" ]
[ [ "numpy.asarray" ] ]
QHZSS/SRAWL
[ "7862dea638f989f7ea34c1bcf404a654115c9ec7" ]
[ "code_for_mrc/optimization.py" ]
[ "\n\"\"\"PyTorch optimization for BERT model.\"\"\"\n\nimport math\nimport torch\nfrom torch.optim import Optimizer\nfrom torch.nn.utils import clip_grad_norm_\n\ndef warmup_cosine(x, warmup=0.002):\n if x < warmup:\n return x/warmup\n return 0.5 * (1.0 + torch.cos(math.pi * x))\n\ndef warmup_constant(x, warmup=0.002):\n if x < warmup:\n return x/warmup\n return 1.0\n\ndef warmup_linear(x, warmup=0.002):\n if x < warmup:\n return x/warmup\n return 1.0 - x\n\nSCHEDULES = {\n 'warmup_cosine':warmup_cosine,\n 'warmup_constant':warmup_constant,\n 'warmup_linear':warmup_linear,\n}\n\n\nclass BERTAdam(Optimizer):\n \"\"\"Implements BERT version of Adam algorithm with weight decay fix (and no ).\n Params:\n lr: learning rate\n warmup: portion of t_total for the warmup, -1 means no warmup. Default: -1\n t_total: total number of training steps for the learning\n rate schedule, -1 means constant learning rate. Default: -1\n schedule: schedule to use for the warmup (see above). Default: 'warmup_linear'\n b1: Adams b1. Default: 0.9\n b2: Adams b2. Default: 0.999\n e: Adams epsilon. Default: 1e-6\n weight_decay_rate: Weight decay. Default: 0.01\n max_grad_norm: Maximum norm for the gradients (-1 means no clipping). Default: 1.0\n \"\"\"\n def __init__(self, params, lr, warmup=-1, t_total=-1, schedule='warmup_linear',\n b1=0.9, b2=0.999, e=1e-6, weight_decay_rate=0.01,\n max_grad_norm=1.0):\n if not lr >= 0.0:\n raise ValueError(\"Invalid learning rate: {} - should be >= 0.0\".format(lr))\n if schedule not in SCHEDULES:\n raise ValueError(\"Invalid schedule parameter: {}\".format(schedule))\n if not 0.0 <= warmup < 1.0 and not warmup == -1:\n raise ValueError(\"Invalid warmup: {} - should be in [0.0, 1.0[ or -1\".format(warmup))\n if not 0.0 <= b1 < 1.0:\n raise ValueError(\"Invalid b1 parameter: {} - should be in [0.0, 1.0[\".format(b1))\n if not 0.0 <= b2 < 1.0:\n raise ValueError(\"Invalid b2 parameter: {} - should be in [0.0, 1.0[\".format(b2))\n if not e >= 0.0:\n raise ValueError(\"Invalid epsilon value: {} - should be >= 0.0\".format(e))\n defaults = dict(lr=lr, schedule=schedule, warmup=warmup, t_total=t_total,\n b1=b1, b2=b2, e=e, weight_decay_rate=weight_decay_rate,\n max_grad_norm=max_grad_norm)\n super(BERTAdam, self).__init__(params, defaults)\n\n def get_lr(self):\n lr = []\n for group in self.param_groups:\n for p in group['params']:\n state = self.state[p]\n if len(state) == 0:\n return [0]\n if group['t_total'] != -1:\n schedule_fct = SCHEDULES[group['schedule']]\n lr_scheduled = group['lr'] * schedule_fct(state['step']/group['t_total'], group['warmup'])\n else:\n lr_scheduled = group['lr']\n lr.append(lr_scheduled)\n return lr\n\n def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n if grad.is_sparse:\n raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead')\n\n state = self.state[p]\n\n # State initialization\n if len(state) == 0:\n state['step'] = 0\n # Exponential moving average of gradient values\n state['next_m'] = torch.zeros_like(p.data)\n # Exponential moving average of squared gradient values\n state['next_v'] = torch.zeros_like(p.data)\n\n next_m, next_v = state['next_m'], state['next_v']\n beta1, beta2 = group['b1'], group['b2']\n\n # Add grad clipping\n if group['max_grad_norm'] > 0:\n clip_grad_norm_(p, group['max_grad_norm'])\n\n # Decay the first and second moment running average coefficient\n # In-place operations to update the averages at the same time\n next_m.mul_(beta1).add_(1 - beta1, grad)\n next_v.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n update = next_m / (next_v.sqrt() + group['e'])\n\n # Just adding the square of the weights to the loss function is *not*\n # the correct way of using L2 regularization/weight decay with Adam,\n # since that will interact with the m and v parameters in strange ways.\n #\n # Instead we want ot decay the weights in a manner that doesn't interact\n # with the m/v parameters. This is equivalent to adding the square\n # of the weights to the loss with plain (non-momentum) SGD.\n if group['weight_decay_rate'] > 0.0:\n update += group['weight_decay_rate'] * p.data\n\n if group['t_total'] != -1:\n schedule_fct = SCHEDULES[group['schedule']]\n lr_scheduled = group['lr'] * schedule_fct(state['step']/group['t_total'], group['warmup'])\n else:\n lr_scheduled = group['lr']\n\n update_with_lr = lr_scheduled * update\n p.data.add_(-update_with_lr)\n\n state['step'] += 1\n\n # step_size = lr_scheduled * math.sqrt(bias_correction2) / bias_correction1\n # bias_correction1 = 1 - beta1 ** state['step']\n # bias_correction2 = 1 - beta2 ** state['step']\n\n return loss\n" ]
[ [ "torch.nn.utils.clip_grad_norm_", "torch.zeros_like", "torch.cos" ] ]
wadpac/SleepStageClassification
[ "5b288995e62bbd66faa66bd932b06af8a65f8445" ]
[ "deeplearning/get_resnet_weights.py" ]
[ "import sys,os\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras import Input, Model\nfrom tensorflow.keras.layers import Dense, Lambda, Dropout\nimport tensorflow.keras.backend as K\nfrom tensorflow.keras.constraints import MaxNorm\nfrom tensorflow.keras.initializers import glorot_uniform\nfrom resnet import Resnet\n\ndef main(argv):\n infile = argv[0]\n outfile = argv[1]\n\n seqlen = 1500\n channels = 6\n maxnorm = 20.0\n\n # Create model\n resnet_model = Resnet(input_shape=(seqlen, channels), norm_max=maxnorm)\n samp1 = Input(shape=(seqlen, channels))\n enc_samp1 = resnet_model(samp1)\n samp2 = Input(shape=(seqlen, channels))\n enc_samp2 = resnet_model(samp2)\n diff_layer = Lambda(lambda tensors:K.abs(tensors[0] - tensors[1]))\n diff_enc = diff_layer([enc_samp1, enc_samp2])\n\n dense_out = Dense(50,activation='relu',\n kernel_constraint=MaxNorm(maxnorm,axis=[0,1]),\n bias_constraint=MaxNorm(maxnorm,axis=0),\n kernel_initializer=glorot_uniform(seed=0))(diff_enc)\n dense_out = Dropout(rate=0.2)(dense_out)\n output = Dense(1,activation='sigmoid',\n kernel_constraint=MaxNorm(maxnorm,axis=[0,1]),\n bias_constraint=MaxNorm(maxnorm,axis=0),\n kernel_initializer=glorot_uniform(seed=0))(dense_out)\n model = Model(inputs=[samp1,samp2], outputs=output)\n model.load_weights(infile)\n for layer in model.layers:\n if layer.name == \"model\":\n resnet_model.set_weights(layer.get_weights())\n resnet_model.save_weights(outfile)\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n" ]
[ [ "tensorflow.keras.constraints.MaxNorm", "tensorflow.keras.Input", "tensorflow.keras.Model", "tensorflow.keras.backend.abs", "tensorflow.keras.initializers.glorot_uniform", "tensorflow.keras.layers.Dropout" ] ]
shijieS/OMOTDRecorder
[ "2e28c00d0ec682f4717a15a54da099085d6413b7" ]
[ "recording_utils/draw_utils.py" ]
[ "# Copyright (c) 2019. ShiJie Sun at the Chang'an University\n# This work is licensed under the terms of the MIT license.\n# For a copy, see <https://opensource.org/licenses/MIT>.\n# Author: shijie Sun\n# Email: [email protected]\n# Github: www.github.com/shijieS\nimport numpy as np\nimport cv2\n\ndef cut(d, small, great):\n if d < small:\n return small\n if d > great:\n return great\n return d\n\ndef getTextImg( text,\n textColor = (0, 0, 0),\n bgColor = (255, 0, 0)):\n (text_width, text_height) = cv2.getTextSize(text, cv2.FONT_HERSHEY_PLAIN, fontScale=4, thickness=4)[0]\n offsetX = text_width // 15\n offsetY = text_height // 5\n bg = np.zeros((text_height + 2*offsetY, text_width + 2*offsetX, 3), dtype=np.uint8)\n bg[:, :, :] = bgColor\n cv2.putText(bg, text, (offsetX, text_height+offsetY), cv2.FONT_HERSHEY_PLAIN, fontScale=4, thickness=4, color=textColor)\n return bg\n\ndef putPrettyText(frame, text, font_color, bg_color, box):\n text_img = getTextImg(text, font_color, bg_color)\n th, tw, _ = text_img.shape\n l, t, r, b = box\n w, h = r - l, b - t\n ih, iw, _ = frame.shape\n f = w / 1.5 / tw\n tw, th = int(f*tw+0.5), int(f*th+0.5)\n resized_text_img = cv2.resize(text_img, (tw, th))\n tt, tb, tl, tr = t-th, t, l, l+tw\n\n ttd, tt = cut(tt, 0, ih) - tt, cut(tt, 0, ih)\n tld, tl = cut(tl, 0, iw) - tl, cut(tl, 0, iw)\n tb = cut(tb, 0, ih) + ttd\n tr = cut(tr, 0, iw) + tld\n frame[tt:tb, tl:tr] = resized_text_img\n return frame\n\ndef putPrettyTextPos(frame, text, font_color, bg_color, pos, f):\n text_img = getTextImg(text, font_color, bg_color)\n th, tw, _ = text_img.shape\n ih, iw, _ = frame.shape\n f = iw*f/tw\n tw, th = int(f * tw + 0.5), int(f * th + 0.5)\n resized_text_img = cv2.resize(text_img, (tw, th))\n tt, tb, tl, tr = pos[1], pos[1]+th, pos[0], pos[0] + tw\n ttd, tt = cut(tt, 0, ih) - tt, cut(tt, 0, ih)\n tld, tl = cut(tl, 0, iw) - tl, cut(tl, 0, iw)\n tb = cut(tb, 0, ih) + ttd\n tr = cut(tr, 0, iw) + tld\n frame[tt:tb, tl:tr] = resized_text_img\n return frame\n\n\ndef cv_draw_one_box(frame,\n box,\n color,\n content_color=None,\n alpha=0.5,\n text=\"\",\n font_color=None,\n with_border=True,\n border_color=None):\n \"\"\"\n Draw a box on a frame\n \"\"\"\n h, w, _ = frame.shape\n # draw box content\n if content_color is None:\n content_color = color\n\n (l, t, r, b) = tuple([int(cut(b, 0, m)) for b, m in zip(box, [w, h, w, h])])\n roi = frame[t:b, l:r]\n black_box = np.zeros_like(roi)\n black_box[:, :, :] = content_color\n cv2.addWeighted(roi, alpha, black_box, 1-alpha, 0, roi)\n # draw border\n if with_border:\n if border_color is None:\n border_color = color\n cv2.rectangle(frame, (l, t), (r, b), border_color, 1)\n # put text\n if font_color is None:\n font_color = color\n bg_color = [abs(255 - c) for c in font_color]\n if text is not None and text != \"\":\n frame = putPrettyText(frame, text, font_color, bg_color, (l, t, r, b))\n # textImg = getTextImg(text, font_color, [255 - for c in font_color])\n # cv2.putText(frame, text, (l, t), cv2.FONT_HERSHEY_PLAIN, 1, font_color)\n return frame\n\ndef cv_draw_mult_boxes(frame, boxes, colors=None):\n \"\"\"\n Draw multiple boxes on one frame\n :param frame: the frame to be drawn\n :param boxes: all the boxes, whoes shape is [n, 4]\n :param color: current boxes' color\n :return:\n \"\"\"\n boxes_len = len(boxes)\n if colors is None:\n colors = [get_random_color(i) for i in range(boxes_len)]\n for box, color in zip(boxes, colors):\n frame = cv_draw_one_box(frame, box, color)\n return frame\n\n\n# def cv_draw_one_circle(frame, center, radius, color, alpha, border_color=None, with_border=True):\n# h, w, _ = frame.shape\n# box = int(center[0]-radius), int(center[1]-radius), int(center[0]+radius), int(center[1]+radius)\n# l, t, r, b = tuple([int(cut(b, 0, m)) for b, m in zip(box, [w, h, w, h])])\n# roi = frame[t:b, l:r]\n# black_box = np.zeros_like(roi)\n# cv2.circle(black_box, (int((l+r)/2), int((t+b)/2)),\n# int(min((b-t, r-l))), color, )\n\ndef cv_draw_8_points(frame, datas):\n points = [(int(datas[i*2]), int(datas[i*2+1])) for i in range(8)]\n pairs = [[0, 1], [1, 2], [2, 3], [3, 0],\n [4, 5], [5, 6], [6, 7], [7, 4],\n [0, 4], [1, 5], [2, 6], [3, 7]]\n color = [(255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0),\n (0, 255, 0), (0, 255, 0), (0, 255, 0), (0, 255, 0),\n (0, 0, 255), (0, 0, 255), (0, 0, 255), (0, 0, 255)]\n for i in range(len(pairs)):\n cv2.line(frame, points[pairs[i][0]], points[pairs[i][1]], color[i], 2)\n return frame\n\ndef get_random_color(seed=None):\n \"\"\"\n Get the random color.\n :param seed: if seed is not None, then seed the random value\n :return:\n \"\"\"\n if seed is not None:\n np.random.seed(int(seed))\n return tuple([np.random.randint(0, 255) for i in range(3)])\n\ndef get_random_colors(num, is_seed=True):\n \"\"\"\n Get a set of random color\n :param num: the number of color\n :param is_seed: is the random seeded\n :return: a list of colors, i.e. [(255, 0, 0), (0, 255, 0)]\n \"\"\"\n if is_seed:\n colors = [get_random_color(i) for i in range(num)]\n else:\n colors = [get_random_color() for _ in range(num)]\n return colors\n\n" ]
[ [ "numpy.zeros", "numpy.zeros_like", "numpy.random.randint" ] ]
DawffyddRiv/unifac_liq_vap
[ "1cab5d94e4e699f08c4fa270da51a2ac49d9d06d" ]
[ "iteracionunifac_A.py" ]
[ "import pandas as pd\nimport numpy \nimport time\nprint(\"Modelo UNIFAC by Dawffydd Riv\")\nprint(\"\"\"Este programa estima los coeficientes de actividad para el equilibrio liquido vapor\nde los compuestos capturados en el archivo BBDDCompuestos \"\"\")\n#########################\tEntrada de variables \n\n####\t<<<<<<<<<<<<<<<<<<<Entrada de parámetros para UNIFAC>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\ncompuestos=pd.read_csv('BBDDCompuestos.csv') \n\n#### Parámetros de las sustancias en la mezcla(en numeros naturales)\nprint(compuestos.iloc[1:,0:1])\nielegido=int(input(\"Elige hasta que número será el rango del calculo de la mezcla de compuestos\"\"\\n\")) \nindice=ielegido+1\ndf0=compuestos.iloc[1:indice,1:109]#Aqui el 5 puede ser introducido por otro valor creando una variable mediante input \ndf0x=df0.values \nmatrix0=numpy.array(df0x) \nparametros=matrix0.astype(numpy.float) \n#print(parametros) \n#print(\"Forma de la matriz parametros\"\"\\n\",parametros.shape) \n#### Fin de la matriz con la cantidad de coeficientes en numeros naturales\n\narevol=pd.read_csv('Area y Volumen.csv') \n\n#### Obtención de la mtriz ri (Volumen molar relativo=vmr)\ndf1=arevol.iloc[0:108,2:3] \ndf1x=df1.values \nmatrix1=numpy.array(df1x) \nRi_1=matrix1.astype(numpy.float) \n#print(Ri_1) \n#print(\"Forma de la matriz Ri\"\"\\n\",Ri_1.shape)\nri=numpy.mat(parametros) * numpy.mat(Ri_1) \n#print(\"Volumenes moleculares Relativos\",\"\\n\", ri) \n#### Fin de la matriz ri \n\n#### Obtención de la mtriz qi (Área molar relativa)\ndf2=arevol.iloc[0:108,3:4] \ndf2x=df2.values \nmatrix1=numpy.array(df2x) \nQi_1=matrix1.astype(numpy.float) \nqi=numpy.mat(parametros) * numpy.mat(Qi_1) \n#print(\"Áreas moleculares Relativas\",\"\\n\", qi)\n#### Fin de la matriz qi (Área molar relativa)\n\n#### Obtención de la matriz Gk=Vk*Qi\nqi2=numpy.reshape(Qi_1,(1,108))\nGk=qi2*parametros\n#print(\"La matriz Gk\"\"\\n\",Gk)\n#print(\"Forma de la matriz Gk\"\"\\n\",Gk.shape)\n#### Fin obtendcion de la matriz Gk\n\n#### Definiendo la temperatura de la mezcla\t\nTemp=float(input(\"Introduce la temperatura de la mezcla en grados Kelvin \"\"\\n\"))\n#### Fin de Temperatura\n #### Calculo energia funcional de la mezcla\n\n#T=334.85\ninterac=pd.read_csv('interacciones.csv')\ndfi=interac.iloc[1:109,2:110]\ndfix=dfi.values \nit=numpy.array(dfix) \nitr=it.astype(numpy.float) \nitrx=itr*(-1)\nit=itrx/Temp\nthau=numpy.exp(it)\n#print(\"Forma de la matriz Thau\"\"\\n\",thau.shape)\n#*print(thau)\n#### Fin cálculo de energia funcional de la mezcla\n\n#### Energía \"parcial molar\" por especie (4x119)\nsk=numpy.mat(Gk) * numpy.mat(thau)\n#*print(sk)\n#print(\"Forma de la matriz Sk\"\"\\n\",sk.shape)\n#### Fin del cálculo de la energía \"parcial molar\" por especie\n\n####\t<<<<<<<<<<<<<<<<<<< Fin entrada de constantes para UNIFAC>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n#### <<<<<<<<<<<<<<Obtención de las solubilidades de referencia >>>>>>>>>>>>>\n\n#### Entalpias de fusion para cálculo de solubilidad\ndfe=compuestos.iloc[1:indice,120:121]#Aqui \"1:indice\" es la entrada de la variable índice\ndfent=dfe.values \nmatrixent=numpy.array(dfent) \nentalpias=matrixent.astype(numpy.float) \n#print(entalpias)\n#### Fin entalpias\n\n#### Temperaturas de fusión para cálculo de solubilidad\ndfe=compuestos.iloc[1:indice,121:122]#Aqui \"1:indice\" es la entrada de la variable índice\ndfTx=dfe.values \nmatrixTx=numpy.array(dfTx) \nTempfusion=matrixTx.astype(numpy.float) \n#print(Tempfusion)\n#### Fin temperaturas de fusión\n\nener=(entalpias/(0.008314472*Tempfusion))*((Tempfusion/Temp)-1)\nsolub_1=numpy.exp(ener)\nprint(\"Las solubilidades de referencia para cada componente son\"\"\\n\",solub_1)\n#### <<<<<<<<<<<<<<Fin solubilidades de referencia >>>>>>>>>>>>>\n\n############################### Fin de entrada de variables >>>>>>>>>>>>>>>>>\n\n\n#### Captura de las concentraciones de cada compuesto de la mezcla\nmatrixC=[]\nprint(\"Introduce las concentraciones de los\",ielegido,\"compuestos en la mezcla en su orden de captura\")\nfor i in range(ielegido):\n\t\t#print(\"Introduce las concentraciones del compuesto\")\n\t\tdatos=float(input(\"Da la concentración del compuesto con el indice \" + str(i+1)+\" \"))\n\t\tvalidacion=input(\"Son correctos los datos? \")\n\t\n\t\twhile validacion ==\"no\":\n\t\t\tprint(\"Vuelva a introducir los datos\")\n\t\t\tdatos=float(input(\"Da su cantidad \"))\n\t\t\tvalidacion=input(\"Son correctos los datos? \")\n\t\t\tif validacion != \"no\":\n\t\t\t\t#matrixC.append(datos)\n\t\t\t\tbreak;\n\t\t\n\t\tmatrixC.append(datos)\n\t\nprint(\"\\n\")\t\nconcentraciones=numpy.array(matrixC)\nC0=concentraciones.astype(numpy.float)\nprint(\"Las valores de las concentraciones usadas en forma de matriz serán : \"\"\\n\", C0)\nprint(\"La forma de la matriz de concentraciones es == \",C0.shape)\n#### Fin de captura de las concentraciones de cada compuesto de la mezcla\n\n############ Fin de la entrada de variables\n\n########################################\tAquí empezaría el loop\t#####################\n#>>>>>>>>>>>>>>>\n#dif=numpy.zeros([])\n\n#while numpy.all(C0>=0):\n####>>>>Empiezan calculos\n#### Calculando Ji e Li\n\n##Calculando Ji\nc0xri=numpy.mat(C0) * numpy.mat(ri)\n#print(\"Producto de Concentración por volumen molecular relativo\" \"\\n\",c0xri)\n#print(\"La forma de la matriz c0xri \"\"\\n\",c0xri)\nJi=numpy.mat(ri)/numpy.mat(c0xri)\n#print(\"Los valores de ji son\"\"\\n\",Ji)\n\n##Calculando Li\nc0_xqi=numpy.mat(C0) * numpy.mat(qi)\n#print(\"Producto de Concentración por area molecular relativa\" \"\\n\",c0_xqi)\nLi=numpy.mat(qi)/numpy.mat(c0_xqi)\n#print(\"Los valores de ji son\"\"\\n\",Li)\n#### Fin de calculando Ji e Li\n\n#### Teta o area relativa por especie(Gk*xi)\nteta=numpy.mat(C0) * numpy.mat(Gk)\n#print(\"La matriz teta\"\"\\n\",teta)\n#print(\"Forma de la matriz teta\"\"\\n\",teta.shape)\n#### Fin de la matriz Teta\n\n#### Energía de la mezcla por especie (1x119)\nnuk=numpy.mat(C0) * numpy.mat(sk)\n#print(\"Forma de la matriz nuk\"\"\\n\",nuk.shape)\n#### Fin del cálculo de la mezcla por especie\n\n#### Comenzando la parte final LnRi\na1=numpy.log(sk/nuk)\na2=numpy.multiply(Gk,a1)\na22=numpy.array(a2)\na3=numpy.sum(a22,axis=1, keepdims=True)\n\nb1=(sk/nuk)\nb2=numpy.multiply(teta,b1)\nb22=numpy.array(b2)\nb3=numpy.sum(b22,axis=1, keepdims=True)\n\n\nc1=numpy.log(Li)\nc2=1-c1\nc21=numpy.multiply(qi,c2)\nc22=numpy.array(c21)\nc3=numpy.sum(c22,axis=1, keepdims=True)\nLnRi=c3-(b3-a3)\n#i print(\"El vector resultante LnRi\"\"\\n\" , LnRi)\n#i print(\"La forma de esta matriz LnRi \"\"\\n\",LnRi.shape)\n#### Fin del cálculo de LnRi\n\n#### Comenzando la parte final LnCi\nd1=numpy.log(Ji/Li)\nd2=Ji/Li\nd3=1-d2+d1\nd4=5*numpy.multiply(qi,d3)\nd5=numpy.log(Ji)\nLnCi=1-Ji+d5-d4\n#print(\"El vector resultante LnCi\"\"\\n\" , LnCi)\n#### Fin del cálculo de LnCi\n\n#### Comienzo de Suma de LnRi + LnCi\ne=LnRi+LnCi\nprint(\"La suma de la parte residual y combinatoria es \"\"\\n\",e) \n#### Fin de la suma de LnRi + LnCi\n\n#### Obtención del coeficiente de actividad \ngama=numpy.exp(e)\nprint(\"Los valores del coeficiente de actividad de la mezcla son\"\"\\n\",gama)\n#### Fin del cálculo del coeficiente de actividad\n" ]
[ [ "numpy.log", "pandas.read_csv", "numpy.multiply", "numpy.reshape", "numpy.exp", "numpy.array", "numpy.mat", "numpy.sum" ] ]
umersheikh846/WQMIX
[ "3fbc088273c4ddb6876a352d18f057c50703546c" ]
[ "src/envs/pymarl_wrapper.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom .multiagentenv import MultiAgentEnv\n\nclass Environment(MultiAgentEnv):\n\n def __init__(self, env_name='matthew', seed=None):\n\n self._seed = seed\n self.normalize = True\n self.resource_type = 'all'\n self.obs3neighbors = True\n self.map_name = \"1c3s5z\"\n \n self.env_name = env_name\n if self.env_name == \"matthew\":\n from common.env_matthew import Env\n self.env = Env(self.normalize, self.resource_type, self.obs3neighbors)\n elif self.env_name == \"sumo\":\n from common.env_sumo import Env\n self.env = Env(self.normalize)\n elif self.env_name == \"starcraft\":\n from common.env_starcraft import Env\n self.env = Env(self.map_name)\n elif self.env_name == \"job\":\n from common.env_job import Env\n self.env = Env(self.normalize, self.resource_type)\n else:\n print('Invalid Env')\n \n self.episode_limit = self.env.max_steps\n self.n_agents = self.env.n_agent\n self.n_actions = self.env.n_actions\n\n self._episode_steps = 0\n self.run = 0\n self.last_action = [np.zeros(self.n_actions) for _ in range(self.n_agents)]\n \n self.env.reset()\n super(Environment, self).__init__()\n\n def step(self, actions):\n \"\"\" Returns reward, terminated, info \"\"\"\n self._episode_steps += 1\n actions = [int(a) for a in actions]\n obs, reward, done = self.env.step(actions)\n reward = np.sum(reward)\n terminated = done or self._episode_steps >= self.episode_limit\n info = {}\n\n for agent_id, action in enumerate(actions):\n self.last_action[agent_id] = np.zeros(self.n_actions)\n self.last_action[agent_id][action] = 1.\n\n return reward, terminated, info\n \n def get_obs(self):\n obs_n = self.env._get_obs()\n return obs_n\n \n def get_obs_agent(self, agent_id):\n \"\"\" Returns observation for agent_id \"\"\"\n return self.get_obs()[agent_id]\n\n def get_obs_size(self):\n \"\"\" Returns the shape of the observation \"\"\"\n return len(self.get_obs_agent(0))\n \n def get_state(self):\n return np.concatenate(self.get_obs())\n \n def get_state_size(self):\n \"\"\" Returns the shape of the state\"\"\"\n return (self.get_obs_size() * self.n_agents)\n\n def get_avail_actions(self):\n return [self.get_avail_agent_actions(i) for i in range(self.n_agents)]\n \n def get_avail_agent_actions(self, agent_id):\n \"\"\" Returns the available actions for agent_id \"\"\"\n return np.ones(self.n_actions)\n \n def get_total_actions(self):\n \"\"\" Returns the total number of actions an agent could ever take \"\"\"\n return self.n_actions\n\n def reset(self):\n self._episode_steps = 0\n if self.run == 0:\n print('Game Start')\n self.env.close()\n else:\n self.env.end_episode()\n\n self.run += 1\n self.env.reset()\n self.last_action = [np.zeros(self.n_actions) for _ in range(self.n_agents)]\n return self.get_obs(), self.get_state()\n\n def get_stats(self): \n return None\n\n def render(self):\n for i in range(self.n_agents):\n theta = np.arange(0, 2 * np.pi, 0.01)\n x = self.ant[i][0] + self.size[i] * np.cos(theta)\n y = self.ant[i][1] + self.size[i] * np.sin(theta)\n plt.plot(x, y)\n for i in range(self.n_resource):\n plt.scatter(self.resource[i][0], self.resource[i][1], color='green')\n plt.axis(\"off\")\n plt.axis(\"equal\")\n plt.xlim(0, 1)\n plt.ylim(0, 1)\n plt.ion()\n plt.pause(0.1)\n plt.close()\n\n def close(self):\n self.env.close()\n\n def seed(self):\n return self._seed\n\n def save_replay(self):\n pass\n \n def get_env_info(self):\n env_info = {\"state_shape\": self.get_state_size(),\n \"obs_shape\": self.get_obs_size(),\n \"n_actions\": self.get_total_actions(),\n \"n_agents\": self.n_agents,\n \"episode_limit\": self.episode_limit}\n return env_info\n" ]
[ [ "matplotlib.pyplot.pause", "matplotlib.pyplot.scatter", "matplotlib.pyplot.ylim", "numpy.arange", "numpy.cos", "numpy.ones", "matplotlib.pyplot.plot", "numpy.sin", "matplotlib.pyplot.xlim", "matplotlib.pyplot.close", "matplotlib.pyplot.axis", "matplotlib.pyplot.ion", "numpy.zeros", "numpy.sum" ] ]
Yixin-Cheng/8755Project
[ "6612b606e185bf27d020726817a13f12fa9dd680" ]
[ "Dropout_Prediction/feature_selector.py" ]
[ "\"\"\"\nThis file is for the feature selection based on Genetic Algorithm and SVM\n\"\"\"\n# import required libraries\nimport numpy as np\nfrom sklearn.svm import SVC\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split, cross_validate\n\n\n# ## Step 2: Define settings\n# 1. DNA size: the number of bits in DNA\n# 2. Population size\n# 3. Crossover rate\n# 4. Mutation rate\n# 5. Number of generations\nclass Selector:\n def __init__(self,path,target_path):\n self.target_path=target_path\n self.path=path\n self.df=pd.read_csv(self.path)\n # define GA settings\n self.DNA_SIZE = len(self.df.columns)-3 # number of bits in DNA which equals the number of features(exclude the grade)\n self.POP_SIZE = 1000 # population size\n self.CROSS_RATE = 0.75 # DNA crossover probability\n self.MUTATION_RATE = 0.002 # mutation probability\n self.N_GENERATIONS = 100 # generation size\n self.evolution()\n\n # ## Step 3: Define fitness, select, crossover, mutate functions\n\n def get_fitness(self,pop,path):\n \"\"\"\n This function calculates the fitness (accuracy) in each DNA based on the Support Vector Machine algorithm\n :param pop: population\n :param path: the path is to the preprocessed data set\n :return: a list of accuracy of each DNA\n \"\"\"\n res = []\n for element in pop:\n data = pd.read_csv(path, header=None, index_col=0)\n data.drop(data.columns[0],axis=1)\n droplist = []\n for i in range(len(element)):\n if element[i] == 0:\n droplist.append(i)\n data=data.drop(data.columns[droplist], axis=1)\n print('Individual: ',element)\n X = data.iloc[:, :-1]\n y = data.iloc[:, -1]\n scoring = {'accuracy': 'accuracy',\n 'precision': 'precision',\n 'recall': 'recall',\n 'f1': 'f1'}\n # SVM for fitness computation\n svc = SVC(C=0.4)\n scores = cross_validate(svc, X, y, scoring=scoring, cv=5) #peform 5-fold validaiton\n res_tem = {\"Acc\": np.average(scores['test_accuracy']), \"Recall\": np.average(scores['test_recall']),\n \"Precision\": np.average(scores['test_precision']), \"F1\": np.average(scores['test_f1'])}\n # res['SVC'] = res_tem\n print('Result: ',res_tem)\n res.append(res_tem[\"Acc\"])\n return res\n\n\n # define population select function based on fitness value\n # population with higher fitness value has higher chance to be selected\n def select(self,pop, fitness):\n idx = np.random.choice(np.arange(self.POP_SIZE), size=self.POP_SIZE, replace=True,\n p=fitness / sum(fitness))\n return pop[idx]\n\n\n # define gene crossover function\n def crossover(self,parent, pop):\n if np.random.rand() < self.CROSS_RATE:\n # randomly select another individual from population\n i = np.random.randint(0, self.POP_SIZE, size=1)\n # choose crossover points(bits)\n cross_points = np.random.randint(0, 2, size=self.DNA_SIZE).astype(np.bool)\n # produce one child\n parent[cross_points] = pop[i, cross_points]\n return parent\n\n\n # define mutation function\n def mutate(self,child):\n for point in range(self.DNA_SIZE):\n a = np.random.rand()\n if a < self.MUTATION_RATE:\n # print(a)\n child[point] = 1 if child[point] == 0 else 0\n return child\n\n\n # ## Step 4: Start training GA\n # 1. randomly initialise population\n # 2. determine fitness of population\n # 3. repeat\n # 1. select parents from population\n # 2. perform crossover on parents creating population\n # 3. perform mutation of population\n\n def evolution(self):\n \"\"\"\n the whole process of genetic algorithm\n \"\"\"\n # initialise population DNA\n pop = np.random.randint(0, 2, (self.POP_SIZE, self.DNA_SIZE))\n for t in range(self.N_GENERATIONS):\n # train GA\n # calculate fitness value\n fitness = self.get_fitness(pop,self.path) # translate each NDA into accuracy which is fitness\n # if the generation reaches the max, then abandon the bad performance feature and save the rest of features to a new file\n if t == self.N_GENERATIONS - 1:\n res = pop[np.argmax(fitness), :]\n print(\"Most fitted DNA: \", pop[np.argmax(fitness), :])\n data=pd.read_csv(self.path, header=None, index_col=0)\n data.drop(data.columns[0], axis=1)\n droplist = []\n for i in range(len(res)):\n if res[i] == 0:\n droplist.append(i)\n print(\"Abandoned feature index: \", droplist)\n data=data.drop(data.columns[droplist], axis=1)\n if type(data) is not None:\n data.to_csv(self.target_path, header=None,index=False)\n # select better population as parent 1\n pop = self.select(pop, fitness)\n # make another copy as parent 2\n pop_copy = pop.copy()\n\n for parent in pop:\n # produce a child by crossover operation\n child = self.crossover(parent, pop_copy)\n # mutate child\n child = self.mutate(child)\n # replace parent with its child\n parent[:] = child\n" ]
[ [ "pandas.read_csv", "numpy.arange", "numpy.argmax", "numpy.random.rand", "sklearn.svm.SVC", "sklearn.model_selection.cross_validate", "numpy.average", "numpy.random.randint" ] ]
peter0083/AttnGAN
[ "9f80f32ce288a79ed65b8779c37df751e2802f94" ]
[ "code/datasets.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\n\nfrom nltk.tokenize import RegexpTokenizer\nfrom collections import defaultdict\nfrom miscc.config import cfg\n\nimport torch\nimport torch.utils.data as data\nfrom torch.autograd import Variable\nimport torchvision.transforms as transforms\n\nimport os\nimport sys\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nimport numpy.random as random\nif sys.version_info[0] == 2:\n import cPickle as pickle\nelse:\n import pickle\n\n\ndef prepare_data(data):\n imgs, captions, captions_lens, class_ids, keys = data\n\n # sort data by the length in a decreasing order\n sorted_cap_lens, sorted_cap_indices = \\\n torch.sort(captions_lens, 0, True)\n\n real_imgs = []\n for i in range(len(imgs)):\n imgs[i] = imgs[i][sorted_cap_indices]\n if cfg.CUDA:\n real_imgs.append(Variable(imgs[i]).cuda())\n else:\n real_imgs.append(Variable(imgs[i]))\n\n captions = captions[sorted_cap_indices].squeeze()\n class_ids = class_ids[sorted_cap_indices].numpy()\n # sent_indices = sent_indices[sorted_cap_indices]\n keys = [keys[i] for i in sorted_cap_indices.numpy()]\n # print('keys', type(keys), keys[-1]) # list\n if cfg.CUDA:\n captions = Variable(captions).cuda()\n sorted_cap_lens = Variable(sorted_cap_lens).cuda()\n else:\n captions = Variable(captions)\n sorted_cap_lens = Variable(sorted_cap_lens)\n\n return [real_imgs, captions, sorted_cap_lens,\n class_ids, keys]\n\n\ndef get_imgs(img_path, imsize, bbox=None,\n transform=None, normalize=None):\n img = Image.open(img_path).convert('RGB')\n width, height = img.size\n if bbox is not None:\n r = int(np.maximum(bbox[2], bbox[3]) * 0.75)\n center_x = int((2 * bbox[0] + bbox[2]) / 2)\n center_y = int((2 * bbox[1] + bbox[3]) / 2)\n y1 = np.maximum(0, center_y - r)\n y2 = np.minimum(height, center_y + r)\n x1 = np.maximum(0, center_x - r)\n x2 = np.minimum(width, center_x + r)\n img = img.crop([x1, y1, x2, y2])\n\n if transform is not None:\n img = transform(img)\n\n ret = []\n if cfg.GAN.B_DCGAN:\n ret = [normalize(img)]\n else:\n for i in range(cfg.TREE.BRANCH_NUM):\n # print(imsize[i])\n if i < (cfg.TREE.BRANCH_NUM - 1):\n re_img = transforms.Resize(imsize[i])(img)\n else:\n re_img = img\n ret.append(normalize(re_img))\n\n return ret\n\n\nclass TextDataset(data.Dataset):\n def __init__(self, data_dir, split='train',\n base_size=64,\n transform=None, target_transform=None):\n self.transform = transform\n self.norm = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n self.target_transform = target_transform\n self.embeddings_num = cfg.TEXT.CAPTIONS_PER_IMAGE\n\n self.imsize = []\n for i in range(cfg.TREE.BRANCH_NUM):\n self.imsize.append(base_size)\n base_size = base_size * 2\n\n self.data = []\n self.data_dir = data_dir\n if data_dir.find('birds') != -1:\n self.bbox = self.load_bbox()\n else:\n self.bbox = None\n split_dir = os.path.join(data_dir, split)\n\n self.filenames, self.captions, self.ixtoword, \\\n self.wordtoix, self.n_words = self.load_text_data(data_dir, split)\n\n self.class_id = self.load_class_id(split_dir, len(self.filenames))\n self.number_example = len(self.filenames)\n\n def load_bbox(self):\n data_dir = self.data_dir\n bbox_path = os.path.join(data_dir, 'CUB_200_2011/bounding_boxes.txt')\n df_bounding_boxes = pd.read_csv(bbox_path,\n delim_whitespace=True,\n header=None).astype(int)\n #\n filepath = os.path.join(data_dir, 'CUB_200_2011/images.txt')\n df_filenames = \\\n pd.read_csv(filepath, delim_whitespace=True, header=None)\n filenames = df_filenames[1].tolist()\n print('Total filenames: ', len(filenames), filenames[0])\n #\n filename_bbox = {img_file[:-4]: [] for img_file in filenames}\n numImgs = len(filenames)\n for i in range(0, numImgs):\n # bbox = [x-left, y-top, width, height]\n bbox = df_bounding_boxes.iloc[i][1:].tolist()\n\n key = filenames[i][:-4]\n filename_bbox[key] = bbox\n #\n return filename_bbox\n\n def load_captions(self, data_dir, filenames):\n all_captions = []\n for i in range(len(filenames)):\n cap_path = '%s/text/%s.txt' % (data_dir, filenames[i])\n with open(cap_path, \"r\") as f:\n captions = f.read().decode('utf8').split('\\n')\n cnt = 0\n for cap in captions:\n if len(cap) == 0:\n continue\n cap = cap.replace(\"\\ufffd\\ufffd\", \" \")\n # picks out sequences of alphanumeric characters as tokens\n # and drops everything else\n tokenizer = RegexpTokenizer(r'\\w+')\n tokens = tokenizer.tokenize(cap.lower())\n # print('tokens', tokens)\n if len(tokens) == 0:\n print('cap', cap)\n continue\n\n tokens_new = []\n for t in tokens:\n t = t.encode('ascii', 'ignore').decode('ascii')\n if len(t) > 0:\n tokens_new.append(t)\n all_captions.append(tokens_new)\n cnt += 1\n if cnt == self.embeddings_num:\n break\n if cnt < self.embeddings_num:\n print('ERROR: the captions for %s less than %d'\n % (filenames[i], cnt))\n return all_captions\n\n def build_dictionary(self, train_captions, test_captions):\n word_counts = defaultdict(float)\n captions = train_captions + test_captions\n for sent in captions:\n for word in sent:\n word_counts[word] += 1\n\n vocab = [w for w in word_counts if word_counts[w] >= 0]\n\n ixtoword = {}\n ixtoword[0] = '<end>'\n wordtoix = {}\n wordtoix['<end>'] = 0\n ix = 1\n for w in vocab:\n wordtoix[w] = ix\n ixtoword[ix] = w\n ix += 1\n\n train_captions_new = []\n for t in train_captions:\n rev = []\n for w in t:\n if w in wordtoix:\n rev.append(wordtoix[w])\n # rev.append(0) # do not need '<end>' token\n train_captions_new.append(rev)\n\n test_captions_new = []\n for t in test_captions:\n rev = []\n for w in t:\n if w in wordtoix:\n rev.append(wordtoix[w])\n # rev.append(0) # do not need '<end>' token\n test_captions_new.append(rev)\n\n return [train_captions_new, test_captions_new,\n ixtoword, wordtoix, len(ixtoword)]\n\n def load_text_data(self, data_dir, split):\n filepath = '/Users/peterlin/AttnGAN/data/birds/captions.pickle'\n #filepath = os.path.join(data_dir, 'captions.pickle')\n train_names = self.load_filenames(data_dir, 'train')\n test_names = self.load_filenames(data_dir, 'test')\n if not os.path.isfile(filepath):\n train_captions = self.load_captions(data_dir, train_names)\n test_captions = self.load_captions(data_dir, test_names)\n\n train_captions, test_captions, ixtoword, wordtoix, n_words = \\\n self.build_dictionary(train_captions, test_captions)\n with open(filepath, 'wb') as f:\n pickle.dump([train_captions, test_captions,\n ixtoword, wordtoix], f, protocol=2)\n print('Save to: ', filepath)\n else:\n with open(filepath, 'rb') as f:\n x = pickle.load(f)\n train_captions, test_captions = x[0], x[1]\n ixtoword, wordtoix = x[2], x[3]\n del x\n n_words = len(ixtoword)\n print('Load from: ', filepath)\n if split == 'train':\n # a list of list: each list contains\n # the indices of words in a sentence\n captions = train_captions\n filenames = train_names\n else: # split=='test'\n captions = test_captions\n filenames = test_names\n return filenames, captions, ixtoword, wordtoix, n_words\n\n def load_class_id(self, data_dir, total_num):\n if os.path.isfile(data_dir + '/class_info.pickle'):\n with open(data_dir + '/class_info.pickle', 'rb') as f:\n class_id = pickle.load(f, encoding=\"bytes\")\n else:\n class_id = np.arange(total_num)\n return class_id\n\n def load_filenames(self, data_dir, split):\n filepath = '%s/%s/filenames.pickle' % (data_dir, split)\n if os.path.isfile(filepath):\n with open(filepath, 'rb') as f:\n filenames = pickle.load(f)\n print('Load filenames from: %s (%d)' % (filepath, len(filenames)))\n else:\n filenames = []\n return filenames\n\n def get_caption(self, sent_ix):\n # a list of indices for a sentence\n sent_caption = np.asarray(self.captions[sent_ix]).astype('int64')\n if (sent_caption == 0).sum() > 0:\n print('ERROR: do not need END (0) token', sent_caption)\n num_words = len(sent_caption)\n # pad with 0s (i.e., '<end>')\n x = np.zeros((cfg.TEXT.WORDS_NUM, 1), dtype='int64')\n x_len = num_words\n if num_words <= cfg.TEXT.WORDS_NUM:\n x[:num_words, 0] = sent_caption\n else:\n ix = list(np.arange(num_words)) # 1, 2, 3,..., maxNum\n np.random.shuffle(ix)\n ix = ix[:cfg.TEXT.WORDS_NUM]\n ix = np.sort(ix)\n x[:, 0] = sent_caption[ix]\n x_len = cfg.TEXT.WORDS_NUM\n return x, x_len\n\n def __getitem__(self, index):\n #\n key = self.filenames[index]\n cls_id = self.class_id[index]\n #\n if self.bbox is not None:\n bbox = self.bbox[key]\n data_dir = '%s/CUB_200_2011' % self.data_dir\n else:\n bbox = None\n data_dir = self.data_dir\n #\n img_name = '%s/images/%s.jpg' % (data_dir, key)\n imgs = get_imgs(img_name, self.imsize,\n bbox, self.transform, normalize=self.norm)\n # random select a sentence\n sent_ix = random.randint(0, self.embeddings_num)\n new_sent_ix = index * self.embeddings_num + sent_ix\n caps, cap_len = self.get_caption(new_sent_ix)\n return imgs, caps, cap_len, cls_id, key\n\n\n def __len__(self):\n return len(self.filenames)\n" ]
[ [ "pandas.read_csv", "numpy.minimum", "numpy.maximum", "numpy.asarray", "numpy.arange", "numpy.random.shuffle", "numpy.sort", "numpy.random.randint", "torch.sort", "numpy.zeros", "torch.autograd.Variable" ] ]
Scitator/Run-Skeleton-Run
[ "c8aefbc448f2d78699355eb843c75a78ac5132a4" ]
[ "common/env_wrappers.py" ]
[ "import numpy as np\nimport gym\nfrom gym.spaces import Box\nfrom osim.env import RunEnv\n\nfrom common.state_transform import StateVelCentr\n\n\nclass DdpgWrapper(gym.Wrapper):\n def __init__(self, env, args):\n gym.Wrapper.__init__(self, env)\n self.state_transform = StateVelCentr(\n obstacles_mode='standard',\n exclude_centr=True,\n vel_states=[])\n self.observation_space = Box(-1000, 1000, self.state_transform.state_size)\n self.skip_frames = args.skip_frames\n self.reward_scale = args.reward_scale\n self.fail_reward = args.fail_reward\n # [-1, 1] <-> [0, 1]\n action_mean = .5\n action_std = .5\n self.normalize_action = lambda x: (x - action_mean) / action_std\n self.denormalize_action = lambda x: x * action_std + action_mean\n\n def reset(self, **kwargs):\n return self._reset(**kwargs)\n\n def _reset(self, **kwargs):\n observation = self.env.reset(**kwargs)\n self.env_step = 0\n self.state_transform.reset()\n observation, _ = self.state_transform.process(observation)\n observation = self.observation(observation)\n return observation\n\n def _step(self, action):\n action = self.denormalize_action(action)\n total_reward = 0.\n for _ in range(self.skip_frames):\n observation, reward, done, _ = self.env.step(action)\n observation, obst_rew = self.state_transform.process(observation)\n total_reward += reward + obst_rew\n self.env_step += 1\n if done:\n if self.env_step < 1000: # hardcoded\n total_reward += self.fail_reward\n break\n\n observation = self.observation(observation)\n total_reward *= self.reward_scale\n return observation, total_reward, done, None\n\n def observation(self, observation):\n return self._observation(observation)\n\n def _observation(self, observation):\n observation = np.array(observation, dtype=np.float32)\n return observation\n\n\ndef create_env(args):\n env = RunEnv(visualize=False, max_obstacles=args.max_obstacles)\n\n if hasattr(args, \"baseline_wrapper\") or hasattr(args, \"ddpg_wrapper\"):\n env = DdpgWrapper(env, args)\n\n return env\n\n\ndef create_observation_handler(args):\n\n if hasattr(args, \"baseline_wrapper\") or hasattr(args, \"ddpg_wrapper\"):\n state_transform = StateVelCentr(\n obstacles_mode='standard',\n exclude_centr=True,\n vel_states=[])\n\n def observation_handler(observation, previous_action=None):\n observation = np.array(observation, dtype=np.float32)\n observation, _ = state_transform.process(observation)\n return observation\n else:\n def observation_handler(observation, previous_action=None):\n observation = np.array(observation, dtype=np.float32)\n return observation\n\n return observation_handler\n\n\ndef create_action_handler(args):\n action_mean = .5\n action_std = .5\n action_handler = lambda x: x * action_std + action_mean\n return action_handler\n" ]
[ [ "numpy.array" ] ]
m-rubik/Account-Manager
[ "7438baf402ac471f6da3686d7a01ed9eeb3fba88" ]
[ "src/pytrademl/utilities/plot_utilities.py" ]
[ "import matplotlib.pyplot as plt\nimport numpy as np\nimport pytrademl.utilities.dataframe_utilities as dataframe_utilities\nimport matplotlib.dates as mdates\nfrom matplotlib import style\nfrom pandas.plotting import register_matplotlib_converters\n\nregister_matplotlib_converters()\nstyle.use('ggplot')\n\n\ndef generate_correlation_plot(df, name=\"correlation\", starting_date=None, show=False, save=True):\n \"\"\"\n Generates a correlation plot between all columns in a dataframe.\n Note that in order to get a meaningful correlation, we take the percent change of each column.\n \"\"\"\n\n if starting_date is not None:\n df_corr = df.truncate(before=starting_date).pct_change().corr()\n else:\n df_corr = df.pct_change().corr()\n data = df_corr.values\n\n fig = plt.figure(figsize=(20, 20))\n ax = fig.add_subplot(1, 1, 1) # 1 by 1, plot number 1\n heatmap = ax.pcolor(data, cmap=plt.cm.RdYlGn)\n fig.colorbar(heatmap)\n ax.set_xticks(np.arange(data.shape[0] + 0.5), minor=False)\n ax.set_yticks(np.arange(data.shape[1] + 0.5), minor=False)\n ax.invert_yaxis()\n ax.xaxis.tick_top()\n column_labels = df_corr.columns\n row_lables = df_corr.index\n ax.set_xticklabels(column_labels, fontsize=20)\n ax.set_yticklabels(row_lables, fontsize=20)\n plt.xticks(rotation=90)\n heatmap.set_clim(-1, 1)\n plt.tight_layout()\n\n if save:\n fig.savefig('./figures/'+name+'.png', dpi=100)\n if show:\n plt.show()\n\n\ndef plot_dataframe(df, ticker, name=None, plot=True, starting_date=None):\n\n from mplfinance import candlestick_ohlc\n\n df = dataframe_utilities.add_indicators(df)\n\n if starting_date is not None:\n df = df.truncate(before=starting_date)\n\n # ohlc: open high, low close\n # df_ohlc = df['5. adjusted close'].resample('10D').ohlc()\n # df_ohlc = df['4. close'].resample('10D').ohlc()\n # df_volume = df['6. volume'].resample('10D').sum()\n\n df_ohlc = df.resample(\"D\").agg(\n {'1. open': 'first', '2. high': 'max', '2. low': 'min', '4. close': 'last'})\n # df_ohlc = df_resampled.ohlc()\n df_volume = df['6. volume'].resample(\"D\").sum()\n df_ohlc.reset_index(inplace=True)\n df_ohlc.dropna(inplace=True)\n df_volume.dropna(inplace=True)\n\n df_ohlc['date'] = df_ohlc['date'].map(mdates.date2num)\n\n df_ohlc.head()\n\n fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=4, ncols=1, figsize=(\n 19.2, 10.8), dpi=96, sharex=True, gridspec_kw={'height_ratios': [2, 1, 1, 0.5]})\n\n ax1.xaxis_date()\n\n candlestick_ohlc(ax1, df_ohlc.values, width=1, colorup='#77d879', colordown='#db3f3f')\n ax1.set_xlabel('Time')\n ax1.set_ylabel('Price per Share (USD)')\n titleAX1 = 'Historic Share Price of ' + ticker\n ax1.set_title(titleAX1, horizontalalignment='center',\n verticalalignment='top')\n ax1.plot(df.index, df['volatility_bbh'], color=\"yellow\",\n alpha=0.5, linewidth=1, label=\"Bollinger High\")\n ax1.plot(df.index, df['volatility_bbl'], color=\"red\",\n alpha=0.5, linewidth=1, label=\"Bollinger Low\")\n ax1.fill_between(df.index, y1=df['volatility_bbh'],\n y2=df['volatility_bbl'], color='orange', alpha='0.3')\n ax1.legend(loc=\"lower left\")\n\n ax2.plot(df.index, df['trend_macd'], color='purple',\n linewidth=0.5, label=\"MACD\")\n ax2.plot(df.index, df['trend_macd_signal'], color='orange',\n alpha=0.5, linewidth=1, markersize=1, label=\"MACD Signal\")\n ax2.set_xlabel('Time')\n ax2.set_ylabel('Value')\n ax2.set_ylim([-1, 1])\n titleAX2 = 'MACD of ' + ticker\n ax2.set_title(titleAX2, horizontalalignment='center',\n verticalalignment='top')\n ax2.legend(loc=\"lower left\")\n\n ax3.set_xlabel('Time')\n ax3.set_ylabel('Value')\n titleAX3 = 'Other Indicators of ' + ticker\n ax3.set_title(titleAX3, horizontalalignment='center',\n verticalalignment='top')\n ax3.plot(df.index, df['momentum_rsi'], color='purple',\n alpha=1, linewidth=1, markersize=1, label=\"RSI\")\n ax3.plot(df.index, df['momentum_stoch'], color='black',\n alpha=1, linewidth=1, markersize=1, label=\"Stochastic %K\")\n ax3.plot(df.index, df['momentum_stoch_signal'], color='red',\n alpha=1, linewidth=1, markersize=1, label=\"Stochastic %D\")\n\n horiz_line_data = np.array([30 for i in range(len(df.index))])\n ax3.plot(df.index, horiz_line_data, '--',\n alpha=0.5, linewidth=0.5, label=\"RSI Low\")\n horiz_line_data = np.array([70 for i in range(len(df.index))])\n ax3.plot(df.index, horiz_line_data, '--',\n alpha=0.5, linewidth=0.5, label=\"RSI High\")\n horiz_line_data = np.array([20 for i in range(len(df.index))])\n ax3.plot(df.index, horiz_line_data, '--', alpha=0.5,\n linewidth=0.5, label=\"Stochastic Low\")\n horiz_line_data = np.array([80 for i in range(len(df.index))])\n ax3.plot(df.index, horiz_line_data, '--', alpha=0.5,\n linewidth=0.5, label=\"Stochastic High\")\n ax3.legend(loc=\"lower left\")\n\n ax4.set_xlabel('Time')\n ax4.set_ylabel('Number of Shares')\n titleAX4 = 'Market Share Volume of ' + ticker\n ax4.set_title(titleAX4, horizontalalignment='center',\n verticalalignment='top')\n ax4.fill_between(df_volume.index.map(mdates.date2num),\n df_volume.values, 0, color=\"blue\")\n\n plt.tight_layout()\n\n my_dpi = 96\n\n if name is None:\n name = ticker\n fig.savefig('./figures/{}.png'.format(name),\n dpi=my_dpi*10, bbox_inches='tight')\n\n # if starting_date == None:\n # fig.savefig('./figures/fullhistory/ETF/{}.png'.format(ticker), dpi=my_dpi*10,bbox_inches='tight')\n\n if plot:\n plt.show()\n\n\ndef plot_account_pie(account):\n import pandas as pd\n import datetime\n data = {}\n # If today is a weekend, go back to the friday\n today = datetime.datetime.today()\n weekday = today.weekday()\n if weekday == 5:\n today = datetime.datetime.today() - datetime.timedelta(days=1)\n elif weekday == 6:\n today = datetime.datetime.today() - datetime.timedelta(days=2)\n else:\n pass\n today = today.strftime(\"%Y-%m-%d\")\n for security, quantity in account.securities.items():\n if quantity != 0:\n datafolder = './ETF_dfs/'\n tickerData = datafolder+security+'.csv'\n df = pd.read_csv(tickerData, parse_dates=True, index_col=0)\n data[security] = df.loc[today, \"5. adjusted close\"] * quantity\n\n fig, (ax1, ax2) = plt.subplots(\n nrows=1, ncols=2, figsize=(19.2, 10.8), dpi=96)\n ax1.pie(data.values(), labels=data.keys(),\n autopct='%1.1f%%', startangle=90)\n # Equal aspect ratio ensures that pie is drawn as a circle.\n ax1.axis('equal')\n titleAX1 = 'Holdings by Share Values'\n ax1.set_title(titleAX1, horizontalalignment='center',\n verticalalignment='top')\n ax2.pie([float(v) for v in account.securities.values()],\n labels=account.securities.keys(), autopct='%1.1f%%', startangle=90)\n ax2.axis('equal')\n titleAX2 = 'Holdings by Share Volume'\n ax2.set_title(titleAX2, horizontalalignment='center',\n verticalalignment='top')\n plt.show()\n\n\ndef plot_account(account):\n import pandas as pd\n import datetime\n dfs = {}\n\n # If today is a weekend, go back to the friday\n today = datetime.datetime.today()\n weekday = today.weekday()\n if weekday == 5:\n today = datetime.datetime.today() - datetime.timedelta(days=1)\n elif weekday == 6:\n today = datetime.datetime.today() - datetime.timedelta(days=2)\n else:\n pass\n today = today.strftime(\"%Y-%m-%d\")\n\n for security, quantity in account.securities.items():\n if quantity != 0:\n datafolder = './TSX_dfs/'\n tickerData = datafolder+security+'.csv'\n dfs[security] = pd.read_csv(\n tickerData, parse_dates=True, index_col=0)\n\n fig, (ax1, ax2) = plt.subplots(\n nrows=2, ncols=1, figsize=(19.2, 10.8), dpi=96)\n ax1.xaxis_date()\n ax1.set_xlabel('Time')\n ax1.set_ylabel('Price per Share (CAD)')\n titleAX1 = 'Market History'\n ax1.set_title(titleAX1, horizontalalignment='center',\n verticalalignment='top')\n\n for ticker, df in dfs.items():\n ax1.plot(df.index, df['5. adjusted close'], linewidth=1, label=ticker)\n ax1.legend(loc=\"lower left\")\n\n import pandas as pd\n import datetime\n data = {}\n # If today is a weekend, go back to the friday\n today = datetime.datetime.today()\n weekday = today.weekday()\n if weekday == 5:\n today = datetime.datetime.today() - datetime.timedelta(days=1)\n elif weekday == 6:\n today = datetime.datetime.today() - datetime.timedelta(days=2)\n else:\n pass\n today = today.strftime(\"%Y-%m-%d\")\n for security, quantity in account.securities.items():\n if quantity != 0:\n datafolder = './TSX_dfs/'\n tickerData = datafolder+security+'.csv'\n df = pd.read_csv(tickerData, parse_dates=True, index_col=0)\n data[security] = round(\n df.loc[today, \"5. adjusted close\"] * quantity, 2)\n\n ax2.pie(data.values(), labels=data.keys(),\n autopct='%1.1f%%', startangle=90)\n # Equal aspect ratio ensures that pie is drawn as a circle.\n ax2.axis('equal')\n titleAX2 = 'Holdings by Share Values'\n ax2.set_title(titleAX2, horizontalalignment='center',\n verticalalignment='top')\n\n plt.show()\n\n\ndef plot_account_history(account):\n fig, ax1 = plt.subplots(nrows=1, ncols=1, figsize=(19.2, 10.8), dpi=96)\n ax1.xaxis_date()\n ax1.set_xlabel('Date')\n ax1.set_ylabel('Balance (CAD)')\n titleAX1 = 'Account Balance History'\n ax1.set_title(titleAX1, horizontalalignment='center',\n verticalalignment='top')\n\n for k, v in dict(account.balance_history).items():\n if k is None:\n del account.balance_history[k]\n # sorted by key, return a list of tuples\n lists = sorted(account.balance_history.items())\n x, y = zip(*lists) # unpack a list of pairs into two tuples\n ax1.plot(x, y)\n plt.show()\n\n\ndef plot_confusion_matrix(confusion_matrix):\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n cax = ax.matshow(confusion_matrix, cmap=plt.get_cmap('Blues'))\n plt.title('Confusion matrix of the classifier')\n fig.colorbar(cax)\n if confusion_matrix.shape[0] == 3:\n labels = ['Sell', 'Hold', 'Buy']\n else:\n labels = ['Sell', 'Buy']\n ax.set_xticklabels([''] + labels)\n ax.set_yticklabels([''] + labels)\n plt.xlabel('Predicted')\n plt.ylabel('True')\n for i in range(confusion_matrix.shape[0]):\n for j in range(confusion_matrix.shape[1]):\n ax.text(j, i, format(confusion_matrix[i, j], 'd'),\n ha=\"center\", va=\"center\",\n color=\"black\")\n fig.tight_layout()\n plt.show()\n\n\ndef plot_predictions(predictions, y_test):\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.scatter(range(0, len(predictions)), predictions)\n ax.scatter(range(0, len(y_test)), y_test)\n plt.show()\n\n\nif __name__ == \"__main__\":\n import pytrademl.utilities.dataframe_utilities as dataframe_utilities\n\n # df = dataframe_utilities.generate_adjclose_df()\n # generate_correlation_plot(df=df, name=\"correlation_2019-04-11\", starting_date=\"2019-04-11\", show=True, save=True)\n\n df = dataframe_utilities.import_dataframe(\"XIC\")\n plot_dataframe(df, \"XIC\", \"XIC_test\", True, \"2019-09-03\")\n" ]
[ [ "matplotlib.pyplot.tight_layout", "pandas.read_csv", "matplotlib.pyplot.title", "matplotlib.style.use", "numpy.arange", "matplotlib.pyplot.subplots", "matplotlib.pyplot.get_cmap", "matplotlib.pyplot.ylabel", "pandas.plotting.register_matplotlib_converters", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
GYMS-PKU/Daily-Frequency-Quant
[ "808eda9930efecff04ecf98abf617404cadd0003" ]
[ "QBG/Tester/BackTester.py" ]
[ "# Copyright (c) 2021 Dai HBG\n\n\"\"\"\nBackTester类根据传入信号以及交易逻辑进行交易\n\n开发日志\n2021-09-07\n-- 更新:BackTester类统计pnl序列的平均日收益,最大回撤,标准差,夏普比,最长亏损时间\n\n2021-09-11\n-- 修复:回测时剔除涨停板\n\n2021-09-21\n-- 修复:回测是要根据上一期的持仓确定涨停板是否剔除,有可能涨停的股票是有持仓的\n\"\"\"\nimport numpy as np\nimport datetime\n\n\nclass BackTester:\n def __init__(self, data, signal=None):\n \"\"\"\n :param signal: 信号矩阵\n :param date: Data类\n \"\"\"\n self.signal = signal\n self.data = data\n self.pnl = [] # pnl序列\n self.cumulated_pnl = [] # 累计pnl\n self.market_pnl = [] # 如果纯多头,这里存市场的pnl,以比较超额收益\n self.market_cumulated_pnl = []\n\n self.max_dd = 0 # 统计pnl序列的最大回撤\n self.mean_pnl = 0 # 平均pnl\n self.std = 0 # 统计pnl序列的标准差\n self.sharp_ratio = 0 # 夏普比\n self.max_loss_time = 0 # 最长亏损时间\n\n self.log = [] # 记录每一个具体的交易日给出的股票\n\n def cal_stats(self):\n self.std = np.std(self.pnl)\n self.mean_pnl = np.mean(self.pnl)\n self.sharp_ratio = self.mean_pnl / self.std if self.std > 0 else 0\n\n max_dd = 0\n max_pnl = 0\n max_loss_time = 0\n loss_time = 0\n for i in self.cumulated_pnl:\n if i > max_pnl:\n max_pnl = i\n loss_time = 0\n else:\n if max_pnl - i > max_dd:\n max_dd = max_pnl - i\n loss_time += 1\n if loss_time > max_loss_time:\n max_loss_time = loss_time\n self.max_dd = max_dd\n self.max_loss_time = max_loss_time\n\n def long_short(self, start_date=None, end_date=None, signal=None, n=0): # 多空策略\n \"\"\"\n :param signal: 可传入自定义信号\n :param start_date: 开始日期\n :param end_date: 结束日期\n :param n: 进入股票数量,0表示使用top\n :return:\n \"\"\"\n self.pnl = []\n self.cumulated_pnl = []\n self.market_pnl = []\n self.market_cumulated_pnl = []\n\n if start_date is None:\n start_date = str(self.data.start_date)\n if end_date is None:\n end_date = str(self.data.end_date)\n\n start, end = self.data.get_real_date(start_date, end_date)\n if signal is None:\n signal = self.signal\n\n if n != 0: # 暂时不管\n return\n else:\n for i in range(start, end + 1):\n tmp = signal[i].copy()\n tmp[self.data.top[i]] -= np.mean(tmp[self.data.top[i]])\n tmp[self.data.top[i] & (tmp > 0)] /= np.sum(tmp[self.data.top[i] & (tmp > 0)])\n tmp[self.data.top[i] & (tmp < 0)] /= -np.sum(tmp[self.data.top[i] & (tmp < 0)])\n self.pnl.append(np.sum(tmp[self.data.top[i]] * self.data.ret[i + 1, self.data.top[i]]) / 2)\n if not self.cumulated_pnl:\n self.cumulated_pnl.append(np.sum(tmp[self.data.top[i]] * self.data.ret[i + 1,\n self.data.top[i]]) / 2)\n else:\n self.cumulated_pnl.append(\n self.cumulated_pnl[-1] + np.sum(tmp[self.data.top[i]] * self.data.ret[i + 1,\n self.data.top[i]]) / 2)\n self.cal_stats()\n\n def long(self, start_date=None, end_date=None, n=0, signal=None, zt_filter=False,\n position_mode='weighted'): # 多头策略\n \"\"\"\n :param start_date: 开始日期\n :param end_date: 结束日期\n :param n: 进入股票数量,0表示使用top\n :param signal: 可以传入一个自定义的signal,默认使用自身的signal\n :param zt_filter: 是否过滤涨停\n :param position_mode: 仓位配置模式\n :return:\n \"\"\"\n self.pnl = []\n self.cumulated_pnl = []\n self.market_pnl = []\n self.market_cumulated_pnl = []\n\n if start_date is None:\n start_date = str(self.data.start_date)\n if end_date is None:\n end_date = str(self.data.end_date)\n\n start, end = self.data.get_real_date(start_date, end_date)\n\n if signal is None:\n signal = self.signal.copy()\n\n pos = np.array([i for i in range(len(self.data.top[0]))]) # 记录位置\n last_pos = None # 记录上一次持仓的股票\n if n != 0: # 暂时不管\n return\n else:\n for i in range(start, end + 1):\n tmp = signal[i].copy()\n tmp[self.data.top[i]] -= np.mean(tmp[self.data.top[i]])\n tmp[self.data.top[i] & (tmp < 0)] = 0\n tmp_ret = self.data.ret[i + 1, self.data.top[i] & (tmp > 0)].copy()\n # tmp[self.data.top[i] & (self.data.ret[i] >= 0.099)] = 0 # 剔除涨停板\n tmp[self.data.top[i] & (tmp > 0)] /= np.sum(tmp[self.data.top[i] & (tmp > 0)])\n sig_tmp = tmp[self.data.top[i] & (tmp > 0)].copy()\n this_pos = pos[self.data.top[i] & (tmp > 0)].copy()\n if zt_filter:\n if last_pos is not None:\n for j in range(len(this_pos)):\n if (self.data.ret[i, self.data.top[i] & (tmp > 0)][j] > 0.099) and (this_pos[j]\n not in last_pos):\n sig_tmp[j] = 0\n this_pos[j] = -1\n\n\n else:\n for j in range(len(this_pos)):\n if self.data.ret[i, self.data.top[i] & (tmp > 0)][j] > 0.099:\n sig_tmp[j] = 0\n this_pos[j] = -1\n last_pos = this_pos.copy()\n self.pnl.append(np.sum(sig_tmp * tmp_ret) -\n np.mean(self.data.ret[i + 1, self.data.top[i]]))\n if not self.cumulated_pnl:\n self.cumulated_pnl.append(np.sum(sig_tmp * tmp_ret) -\n np.mean(self.data.ret[i + 1, self.data.top[i]]))\n else:\n self.cumulated_pnl.append(\n self.cumulated_pnl[-1] + np.sum(sig_tmp * tmp_ret) -\n np.mean(self.data.ret[i + 1, self.data.top[i]]))\n self.cal_stats()\n\n def long_top_n(self, start_date=None, end_date=None, n=0, signal=None, zt_filter=True,\n position_mode='weighted'): # 做多预测得分最高的n只股票\n \"\"\"\n :param start_date: 开始日期\n :param end_date: 结束日期\n :param n: 做多多少只股票,默认按照top做多\n :param signal: 可以传入一个自定义的signal,默认使用自身的signal\n :param zt_filter: 是否过滤涨停\n :param position_mode: 仓位配置模式\n :return:\n \"\"\"\n self.pnl = []\n self.cumulated_pnl = []\n self.market_pnl = []\n self.market_cumulated_pnl = []\n\n # 验证用功能:记录每一天具体的给出的股票代码和实际的收益率\n self.log = []\n\n if start_date is None:\n start_date = str(self.data.start_date)\n if end_date is None:\n end_date = str(self.data.end_date)\n\n start, end = self.data.get_real_date(start_date, end_date)\n if signal is None:\n signal = self.signal.copy()\n\n pos = np.array([i for i in range(len(self.data.top[0]))]) # 记录位置\n last_pos = None # 记录上一次持仓的股票\n if n != 0:\n zt = []\n in_zt = []\n zt_ret = []\n zt_w = []\n for i in range(start, end + 1):\n tmp = signal[i].copy()\n tmp[self.data.top[i]] -= np.mean(tmp[self.data.top[i]])\n tmp[self.data.top[i] & (tmp > 0)] /= np.sum(tmp[self.data.top[i] & (tmp > 0)])\n tmp[self.data.top[i] & (tmp < 0)] = 0\n if np.sum(tmp != 0) == 0:\n continue\n a = tmp[self.data.top[i] & (tmp > 0)].argsort()[-n:]\n this_pos = pos[self.data.top[i] & (tmp > 0)][a].copy() # 本次持仓的股票\n '''\n try:\n print(len(list(set(this_pos) & set(last_pos))))\n except TypeError:\n pass\n '''\n self.log.append((self.data.position_date_dic[i],\n self.data.order_code_dic[pos[self.data.top[i] & (tmp > 0)][a][0]]))\n ret_tmp = self.data.ret[i + 1, self.data.top[i] & (tmp > 0)][a].copy()\n sig_tmp = tmp[self.data.top[i] & (tmp > 0)][a].copy()\n sig_tmp /= np.sum(sig_tmp)\n zt_weight = []\n if zt_filter:\n in_z = 0\n if last_pos is not None:\n for j in range(n):\n if (self.data.ret[i, self.data.top[i] & (tmp > 0)][a][j] > 0.099) and (this_pos[j]\n not in last_pos):\n zt_weight.append(sig_tmp[j])\n sig_tmp[j] = 0\n this_pos[j] = -1\n elif self.data.ret[i, self.data.top[i] & (tmp > 0)][j] > 0.099:\n in_z += 1\n\n else:\n for j in range(n):\n if self.data.ret[i, self.data.top[i] & (tmp > 0)][a][j] > 0.099:\n sig_tmp[j] = 0\n zt_weight.append(sig_tmp[j])\n this_pos[j] = -1\n\n # sig_tmp /= np.sum(sig_tmp)\n # print(np.sum(sig_tmp == 0))\n in_zt.append(in_z)\n zt.append(np.sum(sig_tmp == 0)) # 统计涨停总数\n if zt[-1] > 0:\n if position_mode == 'weighted':\n zt_ret.append(np.sum(np.array(zt_weight) * ret_tmp[sig_tmp == 0])) # 统计涨停收益\n else:\n zt_ret.append(np.mean(ret_tmp[sig_tmp == 0])) # * zt[-1] / n)\n zt_w.append(np.sum(zt_weight)) # 涨停权重占比\n else:\n zt_ret.append(0)\n zt_w.append(0)\n last_pos = this_pos.copy()\n if position_mode == 'mean':\n self.pnl.append(np.mean(ret_tmp[sig_tmp != 0]) -\n np.mean(self.data.ret[i + 1, self.data.top[i]]))\n else:\n self.pnl.append(np.sum(sig_tmp * ret_tmp) -\n np.mean(self.data.ret[i + 1, self.data.top[i]])) # 这是按照比例投资,只看纯超额\n if not self.cumulated_pnl:\n \"\"\"\n self.cumulated_pnl.append(np.sum(tmp[self.data.top[i] & (tmp > 0)][a] *\n self.data.ret[i + 1, self.data.top[i] & (tmp > 0)][a]) /\n np.sum(tmp[self.data.top[i] & (tmp > 0)][a]))\n \"\"\"\n # self.cumulated_pnl.append(np.mean(ret_tmp[ret_tmp != 0]))\n self.cumulated_pnl.append(self.pnl[-1]) # 按照比例投资\n self.market_cumulated_pnl.append(np.mean(self.data.ret[i + 1, self.data.top[i]]))\n else:\n \"\"\"\n self.cumulated_pnl.append(np.sum(tmp[self.data.top[i] & (tmp > 0)][a] *\n self.data.ret[i + 1, self.data.top[i] & (tmp > 0)][a]) /\n np.sum(tmp[self.data.top[i] & (tmp > 0)][a]))\n \"\"\"\n # self.cumulated_pnl.append(self.cumulated_pnl[-1] +\n # np.mean(ret_tmp[ret_tmp != 0]))\n self.cumulated_pnl.append(self.cumulated_pnl[-1] + self.pnl[-1])\n\n self.market_cumulated_pnl.append(self.market_cumulated_pnl[-1] +\n np.mean(self.data.ret[i + 1, self.data.top[i]]))\n print(np.mean(zt))\n zt_ret = np.array(zt_ret)\n zt = np.array(zt)\n print(np.mean(zt_ret) * 100)\n print(np.mean(zt_w))\n print(np.mean(in_zt))\n if position_mode == 'mean':\n print(np.corrcoef(zt_ret[zt != 0], zt[zt != 0])[0, 1])\n self.cal_stats()\n return zt_ret, zt\n else:\n for i in range(start, end + 1):\n tmp = self.signal[i].copy()\n tmp[self.data.top[i]] -= np.mean(tmp[self.data.top[i]])\n tmp[self.data.top[i] & (tmp > 0)] /= np.sum(tmp[self.data.top[i] & (tmp > 0)])\n tmp[self.data.top[i] & (tmp < 0)] = 0\n self.pnl.append(np.sum(tmp[self.data.top[i]] * self.data.ret[i + 1, self.data.top[i]]))\n self.market_pnl.append(np.mean(self.data.ret[i + 1, self.data.top[i]]))\n if not self.cumulated_pnl:\n self.cumulated_pnl.append(np.sum(tmp[self.data.top[i]] * self.data.ret[i + 1,\n self.data.top[i]]))\n self.market_cumulated_pnl.append(np.mean(self.data.ret[i + 1, self.data.top[i]]))\n else:\n self.cumulated_pnl.append(\n self.cumulated_pnl[-1] + np.sum(tmp[self.data.top[i]] * self.data.ret[i + 1,\n self.data.top[i]]))\n self.market_cumulated_pnl.append(self.market_cumulated_pnl[-1] +\n np.mean(self.data.ret[i + 1, self.data.top[i]]))\n self.cal_stats()\n return self.log\n\n def long_stock_predict(self, date=None, n=1, signal=None): # 非回测模式,直接预测最新交易日的股票\n \"\"\"\n :param date: 预测的日期,默认是最新的日期\n :param n: 需要预测多少只股票\n :param signal: 可以直接输入signal\n :return: 返回预测的股票代码以及他们的zscore分数\n \"\"\"\n if signal is None:\n signal = self.signal.copy()\n pos = np.array([i for i in range(len(self.data.top[0]))])\n if date is None:\n start, end = self.data.get_real_date(str(self.data.start_date), str(self.data.end_date))\n else:\n start, end = self.data.get_real_date(date, date)\n for i in range(end, end + 1):\n tmp = signal[i].copy()\n tmp[self.data.top[i]] -= np.mean(tmp[self.data.top[i]])\n tmp[self.data.top[i] & (tmp > 0)] /= np.sum(tmp[self.data.top[i] & (tmp > 0)])\n tmp[self.data.top[i] & (tmp < 0)] = 0\n a = tmp[self.data.top[i] & (tmp > 0)].argsort()[-n:]\n return (self.data.position_date_dic[i],\n [self.data.order_code_dic[pos[self.data.top[i] & (tmp > 0)][a][j]] for j in range(n)],\n tmp[self.data.top[i] & (tmp > 0)][a])\n\n def generate_signal(self, model=None, signals_dic=None, start_date=None, end_date=None):\n \"\"\"\n :param model: 一个模型\n :param signals_dic: 使用的原始信号字典\n :param start_date: 得到信号的开始日期\n :param end_date: 得到信号的结束日期\n :return:\n \"\"\"\n # 支持传入模型预测得到signal测试,为了方便必须返回一个形状完全一致的signal矩阵,只不过可以只在对应位置有值\n if start_date is None:\n start_date = str(self.data.start_date)\n if end_date is None:\n end_date = str(self.data.end_date)\n signal = np.zeros(self.data.data_dic['close'].shape)\n\n start, end = self.data.get_real_date(start_date, end_date)\n\n if model is not None:\n for i in range(start, end + 1):\n tmp_x = []\n for j in signals_dic.keys():\n tmp = signals_dic[j][i].copy()\n tmp[np.isnan(tmp)] = 0\n tmp[self.data.top[i]] -= np.mean(tmp[self.data.top[i]])\n if np.sum(tmp[self.data.top[i]] != 0) >= 2:\n tmp[self.data.top[i]] /= np.std(tmp[self.data.top[i]])\n tmp_x.append(tmp)\n tmp_x = np.vstack(tmp_x).T # 用于预测\n signal[i, self.data.top[i]] = model.predict(tmp_x[self.data.top[i], :]) # 只预测需要的部分\n else:\n signal = signals_dic[0].copy()\n self.signal = signal\n\n return signal\n" ]
[ [ "numpy.isnan", "numpy.std", "numpy.mean", "numpy.corrcoef", "numpy.array", "numpy.zeros", "numpy.sum", "numpy.vstack" ] ]
team-sparrow/Vision
[ "e827e5a127cf429bcffb72af2be0c8d1dca001b0" ]
[ "VisionMain/skin_cancer_coreml_model/train_skin_cancer_app.py" ]
[ "\n# coding: utf-8\n\n# In[1]:\n\nfrom sklearn.datasets import load_files \nfrom keras.utils import np_utils\nimport numpy as np\nfrom glob import glob\nimport keras\n\n# define function to load train, test, and validation datasets\ndef load_dataset(path):\n data = load_files(path)\n condition_files = np.array(data['filenames'])\n condition_targets = np_utils.to_categorical(np.array(data['target']), 2)\n return condition_files, condition_targets\n\n# load train, test, and validation datasets\ntrain_files, train_targets = load_dataset('/data/Keras_Transfer_Learning/ISIC_Skin_Cancer/data/train')\nvalid_files, valid_targets = load_dataset('/data/Keras_Transfer_Learning/ISIC_Skin_Cancer/data/validation')\ntest_files, test_targets = load_dataset('/data/Keras_Transfer_Learning/ISIC_Skin_Cancer/data/test')\n\n# load list of labels\ncondition_names = [item[58:-1] for item in sorted(glob(\"/data/Keras_Transfer_Learning/ISIC_Skin_Cancer/data/train/*/\"))]\nprint (condition_names)\n# print statistics about the dataset\nprint('There are %d total categories.' % len(condition_names))\nprint('There are %s total images.\\n' % len(np.hstack([train_files, valid_files, test_files])))\nprint('There are %d training images.' % len(train_files))\nprint('There are %d validation images.' % len(valid_files))\nprint('There are %d test images.'% len(test_files))\n\n\n# In[2]:\n\nfrom keras.preprocessing import image \nfrom tqdm import tqdm\n\ndef path_to_tensor(img_path):\n # loads RGB image as PIL.Image.Image type\n img = image.load_img(img_path, target_size=(224, 224))\n # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)\n x = image.img_to_array(img)\n # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor\n return np.expand_dims(x, axis=0)\n\ndef paths_to_tensor(img_paths):\n list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]\n return np.vstack(list_of_tensors)\n\n\n\nfrom PIL import ImageFile \nImageFile.LOAD_TRUNCATED_IMAGES = True \n\n# pre-process the data for Keras\ntrain_tensors = paths_to_tensor(train_files).astype('float32')/255\nvalid_tensors = paths_to_tensor(valid_files).astype('float32')/255\ntest_tensors = paths_to_tensor(test_files).astype('float32')/255\n\n\n# ### (IMPLEMENTATION) Model Architecture\n# \n\n# In[4]:\nfrom keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D\nfrom keras.layers import Dropout, Flatten, Dense\nfrom keras.models import Sequential\n\nmodel = Sequential()\nmodel.add(Conv2D(32, kernel_size=(3, 3),\n activation='relu',\n input_shape=(224, 224, 3)))\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(2, activation='sigmoid'))\n\nmodel.summary()\n\n\n# ### Compile the Model\n\n# In[ ]:\n#opt = keras.optimizers.Adadelta()\nopt = keras.optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\nmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\n\n# ### Train the Model\n# \n\n# In[ ]:\n\nfrom keras.callbacks import ModelCheckpoint \n\n### TODO: specify the number of epochs that you would like to use to train the model.\n\nepochs = 15\n\ncheckpointer = ModelCheckpoint(filepath='weights.best.from_scratch.6.hdf5', \n verbose=1, save_best_only=True)\n\nmodel.fit(train_tensors, train_targets, \n validation_data=(valid_tensors, valid_targets),\n epochs=epochs, batch_size=10, callbacks=[checkpointer], verbose=1)\n\n# ### Load the Model with the Best Validation Loss\n\n# In[5]:\n\nmodel.load_weights('weights.best.from_scratch.6.hdf5')\n\n\n# ### Test the Model\n# \n\n# In[6]:\n\n# get index of predicted label for each image in test set\ncondition_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]\n\n# report test accuracy\ntest_accuracy = 100*np.sum(np.array(condition_predictions)==np.argmax(test_targets, axis=1))/len(condition_predictions)\nprint('Test accuracy: %.4f%%' % test_accuracy)\n\n" ]
[ [ "numpy.hstack", "numpy.expand_dims", "sklearn.datasets.load_files", "numpy.argmax", "numpy.array", "numpy.vstack" ] ]
xiangyu-xing/pychaotic
[ "4bbe67d0da1d75e6c219115aae37496bf365a59a" ]
[ "lyapunov.py" ]
[ "from typing import NoReturn\nimport numpy\nimport math\nfrom scipy.integrate import odeint\nfrom scipy.linalg import solve_lyapunov\n\n\ndef lyapunov(n, rhs_ext_fcn, fcn_integrator, tstart, stept, tend, ystart):\n \"\"\"\n fcn_integrator: callable\n \"\"\"\n n1 = n\n n2 = n1*(n1+1)\n # number of steps\n nit = round((tend - tstart) / stept)\n # memory allocation\n y = numpy.zeros(n2)\n cum = numpy.zeros(n1)\n y0 = numpy.zeros(n2)\n gsc = numpy.zeros(n1)\n znorm = numpy.zeros(n1)\n # result\n Lexp = []\n Texp = []\n # initial values\n y[0:n] = ystart[:]\n for i in range(n1):\n y[n1*(i+1)+i] = 1\n t = tstart\n for ITERLYAP in range(nit): # main loop\n # solution of extended ode system\n tt = t+stept\n Y = fcn_integrator(rhs_ext_fcn, y, [t, t+stept])\n t += stept\n y = Y[-1]\n #\n for i in range(1, n1+1):\n for j in range(1, n1+1):\n y0[n1*i+j-1] = y[n1*j+i-1]\n #\n znorm[0] = 0\n for j in range(n1):\n # print(n1*(j+1))\n znorm[0] = znorm[0] + y0[n1 * (j+1)]**2\n #\n znorm[0] = math.sqrt(znorm[0])\n for j in range(n1):\n y0[n1*(j+1)] /= znorm[0]\n #\n for j in range(1, n1):\n #\n for k in range(j):\n gsc[k] = 0\n for jj in range(n1):\n gsc[k] = gsc[k] + y0[n1*(jj+1)+j]*y0[n1*(jj+1)+k]\n\n #\n for k in range(n1):\n for jj in range(j):\n y0[n1*(k+1)+j] = y0[n1*(k+1)+j]-gsc[jj]*y0[n1*(k+1)+jj]\n\n #\n znorm[j] = 0\n for k in range(n1):\n znorm[j] += y0[n1*(k+1)+j]**2\n\n znorm[j] = math.sqrt(znorm[j])\n for k in range(n1):\n y0[n1*(k+1)+j] = y0[n1*(k+1)+j]/znorm[j]\n pass\n # updata runing vector magnitudes\n for k in range(n1):\n cum[k] += math.log(znorm[k])\n # normalize exponent\n lp = [0] * n1\n for k in range(n1):\n lp[k] = cum[k]/(t-tstart)\n Lexp.append(lp)\n Texp.append(t)\n for i in range(1, n1+1):\n for j in range(1, n1+1):\n y[n1*j+i-1] = y0[n1*i+j-1]\n return Lexp, Texp\n\n\ndef lorenz_jaco(variables, t):\n \"\"\"Lorenz, Edward N.. \n \"Deterministic Nonperiodic Flow.\" \n Journal of the Atmospheric Sciences 20.2 (1963): 130-141.\n DOI: 10.1175/1520-0469(1963)020<0130:DNF>2.0.CO;2\n \"\"\"\n a = 10\n b = 30\n c = 8/3\n x, y, z = variables[0], variables[1], variables[2]\n Y = [[variables[3], variables[6], variables[9]],\n [variables[4], variables[7], variables[10]],\n [variables[5], variables[8], variables[11]]]\n Y = numpy.array(Y)\n\n dx = numpy.zeros(12)\n dx[0] = -a * (x - y)\n dx[1] = b * x - x * z - y\n dx[2] = -c * z + x * y\n\n jaco = [[-a, a, 0], [b-z, -1, -x], [y, x, -c]]\n jaco = numpy.array(jaco)\n temp = numpy.matmul(jaco, Y)\n dx[3:12] = temp.reshape((9,), order=\"F\")\n return dx\n\n\nif __name__ == \"__main__\":\n res,_ = lyapunov(3, lorenz_jaco, odeint, 0, 0.01, 100, [1, 1, 1])\n" ]
[ [ "numpy.array", "numpy.zeros", "numpy.matmul" ] ]
tamnguyenvan/small_object_detection
[ "526ba8be016dd4781ce45c43848f0dac3924a0ee" ]
[ "model.py" ]
[ "import tensorflow as tf\nimport numpy as np\nimport math\nfrom utils import convert_to_corners, compute_iou\nfrom data_processing import resize_and_pad_image\nfrom tensorflow import keras\n\n\ndef get_backbone(name=\"resnet50\", weight=None):\n \"\"\"Supported backbone: resnet50, resnet101, densenet121\"\"\"\n backbone = None\n if \"resnet\" in name:\n if name == \"resnet50\":\n backbone = keras.applications.ResNet50\n elif name == \"resnet101\":\n backbone = keras.applications.ResNet101\n\n output_layers = [\"conv3_block4_out\", \"conv4_block6_out\", \"conv5_block3_out\"]\n\n elif \"densenet\" in name:\n if name == \"densenet121\":\n backbone = keras.applications.DenseNet121\n output_layers = [\"pool3_conv\", \"pool4_conv\", \"relu\"]\n\n backbone_model = backbone(include_top=False, input_shape=[None, None, 3], weights=weight)\n c3_output, c4_output, c5_output = [\n backbone_model.get_layer(layer_name).output\n for layer_name in output_layers\n ]\n return keras.Model(\n inputs=[backbone_model.inputs], outputs=[c3_output, c4_output, c5_output]\n )\n\n\nclass FeaturePyramid(keras.layers.Layer):\n \"\"\"Builds the Feature Pyramid with the feature maps from the backbone.\n\n Attributes:\n num_classes: Number of classes in the dataset.\n backbone: The backbone to build the feature pyramid from.\n Currently supports ResNet50 only.\n \"\"\"\n\n def __init__(self, backbone=\"resnet50\", weight=None, **kwargs):\n super(FeaturePyramid, self).__init__(name=\"FeaturePyramid\", **kwargs)\n self.backbone = get_backbone(backbone, weight)\n self.conv_c3_1x1 = keras.layers.Conv2D(256, 1, 1, \"same\")\n self.conv_c4_1x1 = keras.layers.Conv2D(256, 1, 1, \"same\")\n self.conv_c5_1x1 = keras.layers.Conv2D(256, 1, 1, \"same\")\n self.conv_c3_3x3 = keras.layers.Conv2D(256, 3, 1, \"same\")\n self.conv_c4_3x3 = keras.layers.Conv2D(256, 3, 1, \"same\")\n self.conv_c5_3x3 = keras.layers.Conv2D(256, 3, 1, \"same\")\n self.conv_c6_3x3 = keras.layers.Conv2D(256, 3, 2, \"same\")\n self.conv_c7_3x3 = keras.layers.Conv2D(256, 3, 2, \"same\")\n\n def call(self, images, training=False):\n c3_output, c4_output, c5_output = self.backbone(images, training=training)\n p3_output = self.conv_c3_1x1(c3_output)\n p4_output = self.conv_c4_1x1(c4_output)\n p5_output = self.conv_c5_1x1(c5_output)\n p4_output = p4_output + keras.layers.UpSampling2D(2)(p5_output)\n p3_output = p3_output + keras.layers.UpSampling2D(2)(p4_output)\n p3_output = self.conv_c3_3x3(p3_output)\n p4_output = self.conv_c4_3x3(p4_output)\n p5_output = self.conv_c5_3x3(p5_output)\n p6_output = self.conv_c6_3x3(c5_output)\n p7_output = self.conv_c7_3x3(tf.nn.relu(p6_output))\n return p3_output, p4_output, p5_output, p6_output, p7_output\n\n\ndef build_head(output_filters, bias_init):\n \"\"\"Builds the class/box predictions head.\n\n Arguments:\n output_filters: Number of convolution filters in the final layer.\n bias_init: Bias Initializer for the final convolution layer.\n\n Returns:\n A keras sequential model representing either the classification\n or the box regression head depending on `output_filters`.\n \"\"\"\n head = keras.Sequential([keras.Input(shape=[None, None, 256])])\n kernel_init = tf.initializers.RandomNormal(0.0, 0.01)\n for _ in range(4):\n head.add(\n keras.layers.Conv2D(256, 3, padding=\"same\", kernel_initializer=kernel_init)\n )\n head.add(keras.layers.ReLU())\n head.add(\n keras.layers.Conv2D(\n output_filters,\n 3,\n 1,\n padding=\"same\",\n kernel_initializer=kernel_init,\n bias_initializer=bias_init,\n )\n )\n return head\n\n\nclass RetinaNet(keras.Model):\n \"\"\"A subclassed Keras model implementing the RetinaNet architecture.\n\n Attributes:\n num_classes: Number of classes in the dataset.\n backbone: The backbone to build the feature pyramid from.\n Currently supports ResNet50 only.\n \"\"\"\n\n def __init__(self, num_classes, backbone=None, weight=None, **kwargs):\n super(RetinaNet, self).__init__(name=\"RetinaNet\", **kwargs)\n self.backbone_name = backbone\n self.fpn = FeaturePyramid(backbone, weight)\n self.num_classes = num_classes\n\n prior_probability = tf.constant_initializer(-np.log((1 - 0.01) / 0.01))\n self.cls_head = build_head(9 * num_classes, prior_probability)\n self.box_head = build_head(9 * 4, \"zeros\")\n\n def call(self, image, training=False):\n features = self.fpn(image, training=True)\n N = tf.shape(image)[0]\n cls_outputs = []\n box_outputs = []\n for feature in features:\n box_outputs.append(tf.reshape(self.box_head(feature), [N, -1, 4]))\n cls_outputs.append(\n tf.reshape(self.cls_head(feature), [N, -1, self.num_classes])\n )\n cls_outputs = tf.concat(cls_outputs, axis=1)\n box_outputs = tf.concat(box_outputs, axis=1)\n return tf.concat([box_outputs, cls_outputs], axis=-1)\n\nclass AnchorBox:\n \"\"\"Generates anchor boxes.\n\n This class has operations to generate anchor boxes for feature maps at\n strides `[8, 16, 32, 64, 128]`. Where each anchor each box is of the\n format `[x, y, width, height]`.\n\n Attributes:\n aspect_ratios: A list of float values representing the aspect ratios of\n the anchor boxes at each location on the feature map\n scales: A list of float values representing the scale of the anchor boxes\n at each location on the feature map.\n num_anchors: The number of anchor boxes at each location on feature map\n areas: A list of float values representing the areas of the anchor\n boxes for each feature map in the feature pyramid.\n strides: A list of float value representing the strides for each feature\n map in the feature pyramid.\n \"\"\"\n\n def __init__(self):\n self.aspect_ratios = [0.5, 1.0, 2.0]\n self.scales = [2 ** x for x in [0, 1 / 3, 2 / 3]]\n\n self._num_anchors = len(self.aspect_ratios) * len(self.scales)\n self._strides = [2 ** i for i in range(3, 8)]\n self._areas = [x ** 2 for x in [32.0, 64.0, 128.0, 256.0, 512.0]]\n self._anchor_dims = self._compute_dims()\n\n def _compute_dims(self):\n \"\"\"Computes anchor box dimensions for all ratios and scales at all levels\n of the feature pyramid.\n \"\"\"\n anchor_dims_all = []\n for area in self._areas:\n anchor_dims = []\n for ratio in self.aspect_ratios:\n anchor_height = tf.math.sqrt(area / ratio)\n anchor_width = area / anchor_height\n dims = tf.reshape(\n tf.stack([anchor_width, anchor_height], axis=-1), [1, 1, 2]\n )\n for scale in self.scales:\n anchor_dims.append(scale * dims)\n anchor_dims_all.append(tf.stack(anchor_dims, axis=-2))\n return anchor_dims_all\n\n def _get_anchors(self, feature_height, feature_width, level):\n \"\"\"Generates anchor boxes for a given feature map size and level\n\n Arguments:\n feature_height: An integer representing the height of the feature map.\n feature_width: An integer representing the width of the feature map.\n level: An integer representing the level of the feature map in the\n feature pyramid.\n\n Returns:\n anchor boxes with the shape\n `(feature_height * feature_width * num_anchors, 4)`\n \"\"\"\n rx = tf.range(feature_width, dtype=tf.float32) + 0.5\n ry = tf.range(feature_height, dtype=tf.float32) + 0.5\n centers = tf.stack(tf.meshgrid(rx, ry), axis=-1) * tf.constant(self._strides[level - 3], tf.float32)\n centers = tf.expand_dims(centers, axis=-2)\n centers = tf.tile(centers, [1, 1, self._num_anchors, 1])\n dims = tf.tile(\n self._anchor_dims[level - 3], [feature_height, feature_width, 1, 1]\n )\n anchors = tf.concat([centers, dims], axis=-1)\n return tf.reshape(\n anchors, [feature_height * feature_width * self._num_anchors, 4]\n )\n\n def get_anchors(self, image_height, image_width):\n \"\"\"Generates anchor boxes for all the feature maps of the feature pyramid.\n\n Arguments:\n image_height: Height of the input image.\n image_width: Width of the input image.\n\n Returns:\n anchor boxes for all the feature maps, stacked as a single tensor\n with shape `(total_anchors, 4)`\n \"\"\"\n anchors = [\n self._get_anchors(\n tf.math.ceil(image_height / 2 ** i),\n tf.math.ceil(image_width / 2 ** i),\n i,\n )\n for i in range(3, 8)\n ]\n return tf.concat(anchors, axis=0)\n\n\nclass DecodePredictions(tf.keras.layers.Layer):\n \"\"\"A Keras layer that decodes predictions of the RetinaNet model.\n\n Attributes:\n num_classes: Number of classes in the dataset\n confidence_threshold: Minimum class probability, below which detections\n are pruned.\n nms_iou_threshold: IOU threshold for the NMS operation\n max_detections_per_class: Maximum number of detections to retain per\n class.\n max_detections: Maximum number of detections to retain across all\n classes.\n box_variance: The scaling factors used to scale the bounding box\n predictions.\n \"\"\"\n\n def __init__(\n self,\n num_classes=80,\n confidence_threshold=0.05,\n nms_iou_threshold=0.5,\n max_detections_per_class=100,\n max_detections=100,\n box_variance=[0.1, 0.1, 0.2, 0.2],\n verbose=0,\n **kwargs\n ):\n super(DecodePredictions, self).__init__(**kwargs)\n self.num_classes = num_classes\n self.verbose = verbose\n self.confidence_threshold = confidence_threshold\n self.nms_iou_threshold = nms_iou_threshold\n self.max_detections_per_class = max_detections_per_class\n self.max_detections = max_detections\n\n self._anchor_box = AnchorBox()\n self._box_variance = tf.convert_to_tensor(\n [0.1, 0.1, 0.2, 0.2], dtype=tf.float32\n )\n\n def _decode_box_predictions(self, anchor_boxes, box_predictions):\n boxes = box_predictions * self._box_variance\n boxes = tf.concat(\n [\n boxes[:, :, :2] * anchor_boxes[:, :, 2:] + anchor_boxes[:, :, :2],\n tf.math.exp(boxes[:, :, 2:]) * anchor_boxes[:, :, 2:],\n ],\n axis=-1,\n )\n boxes_transformed = convert_to_corners(boxes)\n return boxes_transformed\n\n def call(self, images, predictions):\n image_shape = tf.cast(tf.shape(images), dtype=tf.float32)\n anchor_boxes = self._anchor_box.get_anchors(image_shape[1], image_shape[2])\n box_predictions = predictions[:, :, :4]\n cls_predictions = tf.nn.sigmoid(predictions[:, :, 4:])\n boxes = self._decode_box_predictions(anchor_boxes[None, ...], box_predictions)\n return tf.image.combined_non_max_suppression(\n tf.expand_dims(boxes, axis=2),\n cls_predictions,\n self.max_detections_per_class,\n self.max_detections,\n self.nms_iou_threshold,\n self.confidence_threshold,\n clip_boxes=False,\n )\n\n\nclass LabelEncoder:\n \"\"\"Transforms the raw labels into targets for training.\n\n This class has operations to generate targets for a batch of samples which\n is made up of the input images, bounding boxes for the objects present and\n their class ids.\n\n Attributes:\n anchor_box: Anchor box generator to encode the bounding boxes.\n box_variance: The scaling factors used to scale the bounding box targets.\n \"\"\"\n\n def __init__(self):\n self._anchor_box = AnchorBox()\n self._box_variance = tf.convert_to_tensor(\n [0.1, 0.1, 0.2, 0.2], dtype=tf.float32\n )\n\n def _match_anchor_boxes(\n self, anchor_boxes, gt_boxes, match_iou=0.5, ignore_iou=0.4\n ):\n \"\"\"Matches ground truth boxes to anchor boxes based on IOU.\n\n 1. Calculates the pairwise IOU for the M `anchor_boxes` and N `gt_boxes`\n to get a `(M, N)` shaped matrix.\n 2. The ground truth box with the maximum IOU in each row is assigned to\n the anchor box provided the IOU is greater than `match_iou`.\n 3. If the maximum IOU in a row is less than `ignore_iou`, the anchor\n box is assigned with the background class.\n 4. The remaining anchor boxes that do not have any class assigned are\n ignored during training.\n\n Arguments:\n anchor_boxes: A float tensor with the shape `(total_anchors, 4)`\n representing all the anchor boxes for a given input image shape,\n where each anchor box is of the format `[x, y, width, height]`.\n gt_boxes: A float tensor with shape `(num_objects, 4)` representing\n the ground truth boxes, where each box is of the format\n `[x, y, width, height]`.\n match_iou: A float value representing the minimum IOU threshold for\n determining if a ground truth box can be assigned to an anchor box.\n ignore_iou: A float value representing the IOU threshold under which\n an anchor box is assigned to the background class.\n\n Returns:\n matched_gt_idx: Index of the matched object\n positive_mask: A mask for anchor boxes that have been assigned ground\n truth boxes.\n ignore_mask: A mask for anchor boxes that need to by ignored during\n training\n \"\"\"\n iou_matrix = compute_iou(anchor_boxes, gt_boxes)\n max_iou = tf.reduce_max(iou_matrix, axis=1)\n matched_gt_idx = tf.argmax(iou_matrix, axis=1)\n positive_mask = tf.greater_equal(max_iou, match_iou)\n negative_mask = tf.less(max_iou, ignore_iou)\n ignore_mask = tf.logical_not(tf.logical_or(positive_mask, negative_mask))\n return (\n matched_gt_idx,\n tf.cast(positive_mask, dtype=tf.float32),\n tf.cast(ignore_mask, dtype=tf.float32),\n )\n\n def _compute_box_target(self, anchor_boxes, matched_gt_boxes):\n \"\"\"Transforms the ground truth boxes into targets for training\"\"\"\n box_target = tf.concat(\n [\n (matched_gt_boxes[:, :2] - anchor_boxes[:, :2]) / anchor_boxes[:, 2:],\n tf.math.log(matched_gt_boxes[:, 2:] / anchor_boxes[:, 2:]),\n ],\n axis=-1,\n )\n box_target = box_target / self._box_variance\n return box_target\n\n def _encode_sample(self, image_shape, gt_boxes, cls_ids):\n \"\"\"Creates box and classification targets for a single sample\"\"\"\n anchor_boxes = self._anchor_box.get_anchors(image_shape[1], image_shape[2])\n cls_ids = tf.cast(cls_ids, dtype=tf.float32)\n matched_gt_idx, positive_mask, ignore_mask = self._match_anchor_boxes(\n anchor_boxes, gt_boxes\n )\n matched_gt_boxes = tf.gather(gt_boxes, matched_gt_idx)\n box_target = self._compute_box_target(anchor_boxes, matched_gt_boxes)\n matched_gt_cls_ids = tf.gather(cls_ids, matched_gt_idx)\n cls_target = tf.where(\n tf.not_equal(positive_mask, 1.0), -1.0, matched_gt_cls_ids\n )\n cls_target = tf.where(tf.equal(ignore_mask, 1.0), -2.0, cls_target)\n cls_target = tf.expand_dims(cls_target, axis=-1)\n\n label = tf.concat([box_target, cls_target], axis=-1)\n\n return label\n\n def encode_batch(self, batch_images, gt_boxes, cls_ids):\n \"\"\"Creates box and classification targets for a batch\"\"\"\n images_shape = tf.shape(batch_images)\n batch_size = images_shape[0]\n\n labels = tf.TensorArray(dtype=tf.float32, size=batch_size, dynamic_size=True)\n for i in range(batch_size):\n label = self._encode_sample(images_shape, gt_boxes[i], cls_ids[i])\n labels = labels.write(i, label)\n batch_images = tf.keras.applications.resnet.preprocess_input(batch_images)\n return batch_images, labels.stack()\n" ]
[ [ "tensorflow.convert_to_tensor", "tensorflow.concat", "tensorflow.stack", "tensorflow.cast", "tensorflow.equal", "tensorflow.keras.applications.resnet.preprocess_input", "tensorflow.keras.Input", "tensorflow.logical_or", "tensorflow.keras.layers.Conv2D", "tensorflow.keras.layers.UpSampling2D", "tensorflow.gather", "tensorflow.math.ceil", "tensorflow.argmax", "tensorflow.tile", "numpy.log", "tensorflow.nn.sigmoid", "tensorflow.keras.layers.ReLU", "tensorflow.less", "tensorflow.initializers.RandomNormal", "tensorflow.shape", "tensorflow.TensorArray", "tensorflow.keras.Model", "tensorflow.math.exp", "tensorflow.meshgrid", "tensorflow.nn.relu", "tensorflow.reduce_max", "tensorflow.not_equal", "tensorflow.constant", "tensorflow.math.sqrt", "tensorflow.range", "tensorflow.reshape", "tensorflow.expand_dims", "tensorflow.math.log", "tensorflow.greater_equal" ] ]
mmstoll/Ocean569_Code
[ "228cb719f3e82f187f704f343d3b3590a38236d7" ]
[ "MaunaLoa_Code/MaunaLoaFiltering.py" ]
[ "#program to create spectra of MaunaLoa CO2 data\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\nfrom netCDF4 import Dataset\n#\n# read and plot Mauna Loa CO2 data, from a netcdf file\n# \n# define the netcdf reading function\ndef import_data(file_name):\n data_netcdf = Dataset(file_name, mode = 'r')\n data = {}\n for vname in list(data_netcdf.variables):\n data[str(vname)] = data_netcdf.variables[vname][:]\n data_netcdf.close()\n return data\n#\npath_in = '/Users/MMStoll/Python/Data/Ocean569_Data/MaunaLoa_Data/MaunaLoa.nc'\nML_data = import_data(path_in)\n#\nnn=len(ML_data['T'])\nmm=int(nn/2+1)\n#\n# define the data arrays\ntime_meas=np.zeros(nn)\nco2_meas=np.zeros(nn)\ncc=np.zeros(nn)\ncc_detrend=np.zeros(nn)\nfreq=np.zeros(mm)\nr=np.zeros(nn)\n#\n#parse the time, CO2 data from the input file\nfor i in range(0,nn):\n time_meas[i]=(float(ML_data['T'][i])-float(ML_data['T'][0]))\n co2_meas[i]=float(ML_data['co2'][i])\n#\n## find the value of CO2 mean \nco2mean=np.nanmean(co2_meas) #remove nans from mean!!\nprint('The co2 mean is:')\nprint(co2mean)\nco2_meas_nonan = co2_meas[~np.isnan(co2_meas)]\n# \n# remove the CO2 mean from the data\nfor i in range(0,nn):\n cc[i]=co2_meas[i]-co2mean\n# \n# remove NaN values from the dataset \ncc_nonan = cc[~np.isnan(cc)] #remove NaN from dataset!! \n# \n#detrend the CO2 data, remove increase over time \nfor i in range(0,nn):\n r[i] = .1066*i+310.66\n cc_detrend[i]=co2_meas[i]-r[i] #remove line from CO2_meas data \ncc_nonan_detrend = cc_detrend[~np.isnan(cc_detrend)]\n# determine the frequencies for the spectrum\ndelt=1\nT_length=nn\npi=np.pi\nomega0=2.*pi/(T_length*delt)\n#\nfor i in range(0,mm):\n freq[i]=i*omega0\n# \n# compute the fft of the input data (temperature in this case)\n# the fft will yield a set of complex numbers\n# also compute their complex conjugates\n# multiply these together to get the spectrum\nzz=np.fft.rfft(cc_nonan_detrend,n=nn)\nfourier_amp_detrend=np.sqrt((np.real(zz)**2+np.imag(zz)**2))\nfourier_phase=180.*np.arctan2(np.imag(zz),np.real(zz))/pi\nspec_cc_detrend=np.real(zz*np.conj(zz))/(2.*pi*T_length*delt)\nspec_cc_amp_detrend=(np.absolute(zz))**2/(2*pi*T_length*delt)\n\n# =================================================================================\nn_len = 5\nomega_chk = 2.*pi*nn*(1./n_len)\namp = 1./(n_len + 1)\n\ntt = np.zeros(nn)\nyy = np.zeros(nn)\nfreq0=np.zeros(mm)\nfreq1=np.zeros(mm)\nsum_signal = 0.\n\n# ================================================================================\n# Running Mean\nfor i in range(0,nn):\n tt[i] = i\n if i <= n_len//2:\n signal = amp\n else:\n signal = 0.\n yy[i]=signal\n sum_signal+=yy[i]\n\nfor i in range(0,mm):\n freq0[i]=i*omega0\n freq1[i]=freq0[i]*T_length\n\n# carry out the fft\nww = np.fft.rfft(yy,n=nn)\nww_real=ww.real\nww_imag=ww.imag\nww_mag=np.sqrt(ww_real**2+ww_imag**2)\n\nfig1=plt.figure()\nplt.xlabel('Frequency')\nplt.title('Running Mean Filter (5 months)')\n# plt.ylabel()\n# plt.semilogx(freq1,ww_mag)\n# filtered_running_mean = ww_mag*fourier_amp_detrend\nfiltered_running_mean = ww_mag*fourier_amp_detrend\nplt.loglog(freq,filtered_running_mean, color='blue', label='FT Filtered Data')\nplt.loglog(freq,fourier_amp_detrend, color='red', label='FT Actual Data')\nplt.xlabel('$\\omega$ (radians/month)',fontsize=15,ha='center')\nplt.ylabel('Fourier Amplitude (ppm)',fontsize=15)\nplt.legend(loc=3)\nplt.show()\n\nfig2 = plt.figure()\nzz_detrend = np.fft.irfft(filtered_running_mean,n=nn)\n# zz_trend=np.fft.rfft(co2_meas_nonan,n=nn)\n# fourier_amp_trend=np.sqrt((np.real(zz_trend)**2+np.imag(zz_trend)**2))\n# filtered_running_mean_trend = ww_mag*fourier_amp_trend\n# filtered_timeseries = np.fft.irfft(filtered_running_mean_trend,n=nn)\nplt.title('Time Series - Filtered and Actual Data')\nplt.plot(time_meas,zz_detrend, color ='blue', label='Filtered Data')\nplt.plot(time_meas,cc_detrend, color='red', label='Actual Data')\nplt.ylabel('CO2 level Anomalies (ppm)')\nplt.legend(loc=3)\nplt.xlabel('Time (Months since 1956)')\nplt.show()\n# ================================================================================\n# Triangle Filter\nn_len_tri = 5\nomega_chk_tri = 2.*pi*nn*(1./n_len_tri)\namp_tri = 1\n\ntt = np.zeros(nn)\nyy_tri = np.zeros(nn)\nfreq0=np.zeros(mm)\nfreq1=np.zeros(mm)\nsum_signal_tri = 0.\n\nfor i in range(0,nn):\n if i <= n_len_tri//2:\n signal_tri=i*4./(n_len_tri)**2\n if i > n_len_tri//2 and i <= n_len_tri:\n signal_tri=(2./n_len_tri)*(1.-(i-n_len_tri/2)*4/((n_len_tri)**2))\n if i > n_len_tri:\n signal_tri=0.\n yy_tri[i]=signal_tri\n sum_signal+=yy_tri[i]\n\n# carry out the fft\nuu = np.fft.rfft(yy,n=nn)\nuu_real=uu.real\nuu_imag=uu.imag\nuu_mag=np.sqrt(uu_real**2+uu_imag**2)\n\nfig3=plt.figure()\nfiltered_tri = uu_mag*fourier_amp_detrend\nplt.title('Triangle Filter (5 months)')\nplt.xlabel('$\\omega$ (radians/month)',fontsize=15,ha='center')\nplt.ylabel('Fourier Amplitude (ppm)',fontsize=15)\nplt.loglog(freq,filtered_tri, color='blue', label='Filtered FT Data')\nplt.loglog(freq,fourier_amp_detrend, color='red', label='FT Data')\nplt.legend(loc=3)\nplt.show()\n\n# function in pandas module that does these filters for you in the time domain\n" ]
[ [ "matplotlib.pyplot.legend", "numpy.absolute", "numpy.fft.irfft", "numpy.sqrt", "numpy.fft.rfft", "matplotlib.pyplot.title", "numpy.isnan", "numpy.imag", "numpy.conj", "matplotlib.pyplot.loglog", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "numpy.real", "numpy.nanmean", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "numpy.zeros", "matplotlib.pyplot.figure" ] ]
bertsky/cis-ocrd-py
[ "c3fad1a8b04dc5a305460e8bb3c54cb79cd75515" ]
[ "ocrd_cis/ocropy/ocrolib/common.py" ]
[ "# -*- coding: utf-8 -*-\n################################################################\n### common functions for data structures, file name manipulation, etc.\n################################################################\n\n\n\nimport os\nimport os.path\nimport re\nimport sys\nimport sysconfig\nimport unicodedata\nimport inspect\nimport glob\nimport gzip\nimport pickle\nfrom .exceptions import (BadClassLabel, BadInput, FileNotFound,\n OcropusException)\nfrom numpy import (amax, amin, array, bitwise_and, clip, dtype, mean, minimum,\n nan, sin, sqrt, zeros, unique, fromstring)\nfrom scipy.ndimage import morphology, measurements\nimport PIL\n\nfrom . import default\nfrom .default import getlocal\nfrom .toplevel import (checks, LOG, ABINARY2, AINT2, AINT3, BOOL, DARKSEG, GRAYSCALE,\n LIGHTSEG, LINESEG, PAGESEG)\nfrom . import chars\nfrom . import ligatures\nfrom . import lstm\nfrom . import morph\nimport multiprocessing\nfrom . import sl\n\npickle_mode = 2\n\n################################################################\n# text normalization\n################################################################\n\ndef normalize_text(s):\n \"\"\"Apply standard Unicode normalizations for OCR.\n This eliminates common ambiguities and weird unicode\n characters.\"\"\"\n s = str(s)\n s = unicodedata.normalize('NFC',s)\n s = re.sub(r'\\s+(?u)',' ',s)\n s = re.sub(r'\\n(?u)','',s)\n s = re.sub(r'^\\s+(?u)','',s)\n s = re.sub(r'\\s+$(?u)','',s)\n for m,r in chars.replacements:\n s = re.sub(str(m),str(r),s)\n return s\n\ndef project_text(s,kind=\"exact\"):\n \"\"\"Project text onto a smaller subset of characters\n for comparison.\"\"\"\n s = normalize_text(s)\n s = re.sub(r'( *[.] *){4,}','....',s) # dot rows\n s = re.sub(r'[~_]','',s) # dot rows\n if kind==\"exact\":\n return s\n if kind==\"nospace\":\n return re.sub(r'\\s','',s)\n if kind==\"spletdig\":\n return re.sub(r'[^A-Za-z0-9 ]','',s)\n if kind==\"letdig\":\n return re.sub(r'[^A-Za-z0-9]','',s)\n if kind==\"letters\":\n return re.sub(r'[^A-Za-z]','',s)\n if kind==\"digits\":\n return re.sub(r'[^0-9]','',s)\n if kind==\"lnc\":\n s = s.upper()\n return re.sub(r'[^A-Z]','',s)\n raise BadInput(\"unknown normalization: \"+kind)\n\n################################################################\n### Text I/O\n################################################################\n\ndef read_text(fname,nonl=1,normalize=1):\n \"\"\"Read text. This assumes files are in unicode.\n By default, it removes newlines and normalizes the\n text for OCR processing with `normalize_text`\"\"\"\n with open(fname,\"r\", encoding=\"utf-8\") as stream:\n result = stream.read()\n if nonl and len(result)>0 and result[-1]=='\\n':\n result = result.strip('\\n')\n if normalize:\n result = normalize_text(result)\n return result\n\ndef write_text(fname,text,nonl=0,normalize=1):\n \"\"\"Write text. This assumes files are in unicode.\n By default, it removes newlines and normalizes the\n text for OCR processing with `normalize_text`\"\"\"\n if normalize:\n text = normalize_text(text)\n with open(fname,\"w\", encoding=\"utf-8\") as stream:\n stream.write(text)\n if not nonl and (len(text) == 0 or text[-1] != '\\n'):\n stream.write('\\n')\n\n################################################################\n### Image I/O\n################################################################\n\ndef pil2array(im,alpha=0):\n if im.mode==\"L\":\n a = fromstring(im.tobytes(),'B')\n a.shape = im.size[1],im.size[0]\n return a\n if im.mode==\"LA\":\n a = fromstring(im.tobytes(),'B')\n a.shape = im.size[1],im.size[0],2\n if not alpha: a = a[:,:,0]\n return a\n if im.mode==\"RGB\":\n a = fromstring(im.tobytes(),'B')\n a.shape = im.size[1],im.size[0],3\n return a\n if im.mode==\"RGBA\":\n a = fromstring(im.tobytes(),'B')\n a.shape = im.size[1],im.size[0],4\n if not alpha: a = a[:,:,:3]\n return a\n return pil2array(im.convert(\"L\"))\n\ndef array2pil(a):\n if a.dtype==dtype(\"B\"):\n if a.ndim==2:\n return PIL.Image.frombytes(\"L\",(a.shape[1],a.shape[0]),a.tostring())\n elif a.ndim==3:\n modes = {2: \"LA\", 3: \"RGB\", 4: \"RGBA\"}\n return PIL.Image.frombytes(modes[a.shape[-1]],(a.shape[1],a.shape[0]),a.tostring())\n else:\n raise OcropusException(\"bad image rank\")\n elif a.dtype==dtype('float32'):\n return PIL.Image.frombytes(\"F\",(a.shape[1],a.shape[0]),a.tostring())\n else:\n raise OcropusException(\"unknown image type\")\n\ndef isbytearray(a):\n return a.dtype in [dtype('uint8')]\n\ndef isfloatarray(a):\n return a.dtype in [dtype('f'),dtype('float32'),dtype('float64')]\n\ndef isintarray(a):\n return a.dtype in [dtype('B'),dtype('int16'),dtype('int32'),dtype('int64'),dtype('uint16'),dtype('uint32'),dtype('uint64')]\n\ndef isintegerarray(a):\n return a.dtype in [dtype('int32'),dtype('int64'),dtype('uint32'),dtype('uint64')]\n\n@checks(str,pageno=int,_=GRAYSCALE)\ndef read_image_gray(fname,pageno=0):\n \"\"\"Read an image and returns it as a floating point array.\n The optional page number allows images from files containing multiple\n images to be addressed. Byte and short arrays are rescaled to\n the range 0...1 (unsigned) or -1...1 (signed).\"\"\"\n if type(fname)==tuple: fname,pageno = fname\n assert pageno==0\n with PIL.Image.open(fname) as pil:\n a = pil2array(pil)\n if a.dtype==dtype('uint8'):\n a = a/255.0\n if a.dtype==dtype('int8'):\n a = a/127.0\n elif a.dtype==dtype('uint16'):\n a = a/65536.0\n elif a.dtype==dtype('int16'):\n a = a/32767.0\n elif isfloatarray(a):\n pass\n else:\n raise OcropusException(\"unknown image type: \"+a.dtype)\n if a.ndim==3:\n a = mean(a,2)\n return a\n\n\ndef write_image_gray(fname,image,normalize=0,verbose=0):\n \"\"\"Write an image to disk. If the image is of floating point\n type, its values are clipped to the range [0,1],\n multiplied by 255 and converted to unsigned bytes. Otherwise,\n the image must be of type unsigned byte.\"\"\"\n if verbose:\n LOG.info(\"# writing '%s'\", fname)\n if isfloatarray(image):\n image = array(255*clip(image,0.0,1.0),'B')\n assert image.dtype==dtype('B'),\"array has wrong dtype: %s\"%image.dtype\n im = array2pil(image)\n im.save(fname)\n\n@checks(str,_=ABINARY2)\ndef read_image_binary(fname,dtype='i',pageno=0):\n \"\"\"Read an image from disk and return it as a binary image\n of the given dtype.\"\"\"\n if type(fname)==tuple: fname,pageno = fname\n assert pageno==0\n with PIL.Image.open(fname) as pil:\n a = pil2array(pil)\n if a.ndim==3: a = amax(a,axis=2)\n return array(a>0.5*(amin(a)+amax(a)),dtype)\n\n@checks(str,ABINARY2)\ndef write_image_binary(fname,image,verbose=0):\n \"\"\"Write a binary image to disk. This verifies first that the given image\n is, in fact, binary. The image may be of any type, but must consist of only\n two values.\"\"\"\n if verbose:\n LOG.info(\"# writing '%s'\", fname)\n assert image.ndim==2\n image = array(255*(image>midrange(image)),'B')\n im = array2pil(image)\n im.save(fname)\n\n@checks(AINT3,_=AINT2)\ndef rgb2int(a):\n \"\"\"Converts a rank 3 array with RGB values stored in the\n last axis into a rank 2 array containing 32 bit RGB values.\"\"\"\n assert a.ndim==3\n assert a.dtype==dtype('B')\n return array(0xffffff&((0x10000*a[:,:,0])|(0x100*a[:,:,1])|a[:,:,2]),'i')\n\n@checks(AINT2,_=AINT3)\ndef int2rgb(image):\n \"\"\"Converts a rank 3 array with RGB values stored in the\n last axis into a rank 2 array containing 32 bit RGB values.\"\"\"\n assert image.ndim==2\n assert isintarray(image)\n a = zeros(list(image.shape)+[3],'B')\n a[:,:,0] = (image>>16)\n a[:,:,1] = (image>>8)\n a[:,:,2] = image\n return a\n\n@checks(LIGHTSEG,_=DARKSEG)\ndef make_seg_black(image):\n assert isintegerarray(image),\"%s: wrong type for segmentation\"%image.dtype\n image = image.copy()\n image[image==0xffffff] = 0\n return image\n\n@checks(DARKSEG,_=LIGHTSEG)\ndef make_seg_white(image):\n assert isintegerarray(image),\"%s: wrong type for segmentation\"%image.dtype\n image = image.copy()\n image[image==0] = 0xffffff\n return image\n\n@checks(str,_=LINESEG)\ndef read_line_segmentation(fname):\n \"\"\"Reads a line segmentation, that is an RGB image whose values\n encode the segmentation of a text line. Returns an int array.\"\"\"\n with PIL.Image.open(fname) as pil:\n a = pil2array(pil)\n assert a.dtype==dtype('B')\n assert a.ndim==3\n image = rgb2int(a)\n result = make_seg_black(image)\n return result\n\n@checks(str,LINESEG)\ndef write_line_segmentation(fname,image):\n \"\"\"Writes a line segmentation, that is an RGB image whose values\n encode the segmentation of a text line.\"\"\"\n a = int2rgb(make_seg_white(image))\n im = array2pil(a)\n im.save(fname)\n\n@checks(str,_=PAGESEG)\ndef read_page_segmentation(fname):\n \"\"\"Reads a page segmentation, that is an RGB image whose values\n encode the segmentation of a page. Returns an int array.\"\"\"\n with PIL.Image.open(fname) as pil:\n a = pil2array(pil)\n assert a.dtype==dtype('B')\n assert a.ndim==3\n segmentation = rgb2int(a)\n segmentation = make_seg_black(segmentation)\n return segmentation\n\ndef write_page_segmentation(fname,image):\n \"\"\"Writes a page segmentation, that is an RGB image whose values\n encode the segmentation of a page.\"\"\"\n assert image.ndim==2\n assert image.dtype in [dtype('int32'),dtype('int64')]\n a = int2rgb(make_seg_white(image))\n im = array2pil(a)\n im.save(fname)\n\ndef iulib_page_iterator(files):\n for fname in files:\n image = read_image_gray(fname)\n yield image,fname\n\ndef norm_max(a):\n norm = amax(a) # or nanmax?\n if norm:\n return a/norm\n else:\n return a # or 0?\n\ndef pad_by(image,r,dtype=None):\n \"\"\"Symmetrically pad the image by the given amount.\n FIXME: replace by scipy version.\"\"\"\n if dtype is None: dtype = image.dtype\n w,h = image.shape\n result = zeros((w+2*r,h+2*r))\n result[r:(w+r),r:(h+r)] = image\n return result\nclass RegionExtractor:\n \"\"\"A class facilitating iterating over the parts of a segmentation.\"\"\"\n def __init__(self):\n self.cache = {}\n def clear(self):\n del self.cache\n self.cache = {}\n def setImage(self,image):\n return self.setImageMasked(image)\n def setImageMasked(self,image,mask=None,lo=None,hi=None):\n \"\"\"Set the image to be iterated over. This should be an RGB image,\n ndim==3, dtype=='B'. This picks a subset of the segmentation to iterate\n over, using a mask and lo and hi values..\"\"\"\n assert image.dtype==dtype('B') or image.dtype==dtype('i'),\"image must be type B or i\"\n if image.ndim==3: image = rgb2int(image)\n assert image.ndim==2,\"wrong number of dimensions\"\n self.image = image\n labels = image\n if lo is not None: labels[labels<lo] = 0\n if hi is not None: labels[labels>hi] = 0\n if mask is not None: labels = bitwise_and(labels,mask)\n labels,correspondence = morph.renumber_labels_ordered(labels,correspondence=1)\n self.labels = labels\n self.correspondence = correspondence\n self.objects = [None]+morph.find_objects(labels)\n def setPageColumns(self,image):\n \"\"\"Set the image to be iterated over. This should be an RGB image,\n ndim==3, dtype=='B'. This iterates over the columns.\"\"\"\n self.setImageMasked(image,0xff0000,hi=0x800000)\n def setPageParagraphs(self,image):\n \"\"\"Set the image to be iterated over. This should be an RGB image,\n ndim==3, dtype=='B'. This iterates over the paragraphs (if present\n in the segmentation).\"\"\"\n self.setImageMasked(image,0xffff00,hi=0x800000)\n def setPageLines(self,image):\n \"\"\"Set the image to be iterated over. This should be an RGB image,\n ndim==3, dtype=='B'. This iterates over the lines.\"\"\"\n self.setImageMasked(image,0xffffff,hi=0x800000)\n def id(self,i):\n \"\"\"Return the RGB pixel value for this segment.\"\"\"\n return self.correspondence[i]\n def x0(self,i):\n \"\"\"Return x0 (column) for the start of the box.\"\"\"\n return self.bbox(i)[1]\n def x1(self,i):\n \"\"\"Return x0 (column) for the end of the box.\"\"\"\n return self.bbox(i)[3]\n def y0(self,i):\n \"\"\"Return y0 (row) for the start of the box.\"\"\"\n h = self.image.shape[0]\n return h-self.bbox(i)[2]-1\n def y1(self,i):\n \"\"\"Return y0 (row) for the end of the box.\"\"\"\n h = self.image.shape[0]\n return h-self.bbox(i)[0]-1\n def bbox(self,i):\n \"\"\"Return the bounding box in raster coordinates\n (row0,col0,row1,col1).\"\"\"\n r = self.objects[i]\n # print(\"@@@bbox\", i, r)\n return (r[0].start,r[1].start,r[0].stop,r[1].stop)\n def bboxMath(self,i):\n \"\"\"Return the bounding box in math coordinates\n (row0,col0,row1,col1).\"\"\"\n h = self.image.shape[0]\n (y0,x0,y1,x1) = self.bbox(i)\n return (h-y1-1,x0,h-y0-1,x1)\n def length(self):\n \"\"\"Return the number of components.\"\"\"\n return len(self.objects)\n def mask(self,index,margin=0):\n \"\"\"Return the mask for component index.\"\"\"\n b = self.objects[index]\n # print(\"@@@mask\", index, b)\n m = self.labels[b]\n m[m!=index] = 0 # FIXME: This is destructive for labels!\n if margin>0: m = pad_by(m,margin)\n return array(m!=0,'B')\n def extract(self,image,index,margin=0):\n \"\"\"Return the subimage for component index.\"\"\"\n h,w = image.shape[:2]\n (r0,c0,r1,c1) = self.bbox(index)\n # mask = self.mask(index,margin=margin)\n return image[max(0,r0-margin):min(h,r1+margin),max(0,c0-margin):min(w,c1+margin),...]\n def extractMasked(self,image,index,grow=0,bg=None,margin=0,dtype=None):\n \"\"\"Return the masked subimage for component index, elsewhere the bg value.\"\"\"\n if bg is None: bg = amax(image)\n h,w = image.shape[:2]\n mask = self.mask(index,margin=margin)\n # FIXME ... not circular\n if grow>0: mask = morphology.binary_dilation(mask,iterations=grow)\n mh,mw = mask.shape\n box = self.bbox(index)\n r0,c0,r1,c1 = box\n subimage = sl.cut(image,(r0,c0,r0+mh-2*margin,c0+mw-2*margin),margin,bg=bg)\n return where(mask,subimage,bg)\n\n\n\n################################################################\n### Object reading and writing\n### This handles reading and writing zipped files directly,\n### and it also contains workarounds for changed module/class names.\n################################################################\n\ndef save_object(fname,obj,zip=0):\n if zip==0 and fname.endswith(\".gz\"):\n zip = 1\n if zip>0:\n with gzip.GzipFile(fname,\"wb\") as stream:\n #with os.popen(\"gzip -9 > '%s'\"%fname,\"wb\") as stream:\n pickle.dump(obj,stream,2)\n else:\n with open(fname,\"wb\") as stream:\n pickle.dump(obj,stream,2)\n\ndef unpickle_find_global(mname,cname):\n if mname==\"lstm.lstm\":\n return getattr(lstm,cname)\n if not mname in list(sys.modules.keys()):\n exec(\"import \"+mname)\n return getattr(sys.modules[mname],cname)\n\ndef load_object(fname,zip=0,nofind=0,verbose=0):\n \"\"\"Loads an object from disk. By default, this handles zipped files\n and searches in the usual places for OCRopus. It also handles some\n class names that have changed.\"\"\"\n if not nofind:\n fname = ocropus_find_file(fname)\n if verbose:\n LOG.info(\"# loading object '%s'\", fname)\n if zip==0 and fname.endswith(\".gz\"):\n zip = 1\n if zip>0:\n with gzip.GzipFile(fname,\"rb\") as stream:\n #with os.popen(\"gunzip < '%s'\"%fname,\"rb\") as stream:\n #unpickler = pickle.Unpickler(stream)\n #unpickler.find_global = unpickle_find_global\n return pickle.load(stream, encoding='latin1')\n else:\n with open(fname,\"rb\") as stream:\n unpickler = pickle.Unpickler(stream, encoding='latin1')\n #unpickler.find_global = unpickle_find_global\n return unpickler.load()\n\n\n\n################################################################\n### Simple record object.\n################################################################\n\nclass Record:\n \"\"\"A simple record datatype that allows initialization with\n keyword arguments, as in Record(x=3,y=9)\"\"\"\n def __init__(self,**kw):\n self.__dict__.update(kw)\n def like(self,obj):\n self.__dict__.update(obj.__dict__)\n return self\n\n################################################################\n### Histograms\n################################################################\n\ndef chist(l):\n \"\"\"Simple counting histogram. Takes a list of items\n and returns a list of (count,object) tuples.\"\"\"\n counts = {}\n for c in l:\n counts[c] = counts.get(c,0)+1\n hist = [(v,k) for k,v in list(counts.items())]\n return sorted(hist,reverse=1)\n\n################################################################\n### multiprocessing\n################################################################\n\ndef number_of_processors():\n \"\"\"Estimates the number of processors.\"\"\"\n return multiprocessing.cpu_count()\n # return int(os.popen(\"cat /proc/cpuinfo | grep 'processor.*:' | wc -l\").read())\n\ndef parallel_map(fun,jobs,parallel=0,chunksize=1):\n if parallel<2:\n for e in jobs:\n result = fun(e)\n yield result\n else:\n try:\n pool = multiprocessing.Pool(parallel)\n for e in pool.imap_unordered(fun,jobs,chunksize):\n yield e\n finally:\n pool.close()\n pool.join()\n\ndef check_valid_class_label(s):\n \"\"\"Determines whether the given character is a valid class label.\n Control characters and spaces are not permitted.\"\"\"\n if type(s)==str:\n if re.search(r'[\\0-\\x20]',s):\n raise BadClassLabel(s)\n elif type(s)==str:\n if re.search(r'[^\\x21-\\x7e]',s):\n raise BadClassLabel(s)\n else:\n raise BadClassLabel(s)\n\n################################################################\n### file name manipulation\n################################################################\n\n@checks(str,_=str)\ndef findfile(name,error=1):\n result = ocropus_find_file(name)\n return result\n\n@checks(str)\ndef finddir(name):\n \"\"\"Find some OCRopus-related resource by looking in a bunch off standard places.\n (This needs to be integrated better with setup.py and the build system.)\"\"\"\n local = getlocal()\n path = name\n if os.path.exists(path) and os.path.isdir(path): return path\n path = local+name\n if os.path.exists(path) and os.path.isdir(path): return path\n _,tail = os.path.split(name)\n path = tail\n if os.path.exists(path) and os.path.isdir(path): return path\n path = local+tail\n if os.path.exists(path) and os.path.isdir(path): return path\n raise FileNotFound(\"file '\"+path+\"' not found in . or /usr/local/share/ocropus/\")\n\n@checks(str)\ndef allsplitext(path):\n \"\"\"Split all the pathname extensions, so that \"a/b.c.d\" -> \"a/b\", \".c.d\" \"\"\"\n match = re.search(r'((.*/)*[^.]*)([^/]*)',path)\n if not match:\n return path,\"\"\n else:\n return match.group(1),match.group(3)\n\n@checks(str)\ndef base(path):\n return allsplitext(path)[0]\n\n@checks(str,{str,str})\ndef write_text_simple(file,s):\n \"\"\"Write the given string s to the output file.\"\"\"\n with open(file,\"w\") as stream:\n if type(s)==str: s = s.encode(\"utf-8\")\n stream.write(s)\n\n@checks([str])\ndef glob_all(args):\n \"\"\"Given a list of command line arguments, expand all of them with glob.\"\"\"\n result = []\n for arg in args:\n if arg[0]==\"@\":\n with open(arg[1:],\"r\") as stream:\n expanded = stream.read().split(\"\\n\")\n expanded = [s for s in expanded if s!=\"\"]\n else:\n expanded = sorted(glob.glob(arg))\n if len(expanded)<1:\n raise FileNotFound(\"%s: expansion did not yield any files\"%arg)\n result += expanded\n return result\n\n@checks([str])\ndef expand_args(args):\n \"\"\"Given a list of command line arguments, if the\n length is one, assume it's a book directory and expands it.\n Otherwise returns the arguments unchanged.\"\"\"\n if len(args)==1 and os.path.isdir(args[0]):\n return sorted(glob.glob(args[0]+\"/????/??????.png\"))\n else:\n return args\n\n\ndef ocropus_find_file(fname, gz=True):\n \"\"\"Search for `fname` in one of the OCRopus data directories, as well as\n the current directory). If `gz` is True, search also for gzipped files.\n\n Result of searching $fname is the first existing in:\n\n * $base/$fname\n * $base/$fname.gz # if gz\n * $base/model/$fname\n * $base/model/$fname.gz # if gz\n * $base/data/$fname\n * $base/data/$fname.gz # if gz\n * $base/gui/$fname\n * $base/gui/$fname.gz # if gz\n\n $base can be four base paths:\n * `$OCROPUS_DATA` environment variable\n * current working directory\n * ../../../../share/ocropus from this file's install location\n * `/usr/local/share/ocropus`\n * `$PREFIX/share/ocropus` ($PREFIX being the Python installation\n prefix, usually `/usr`)\n \"\"\"\n possible_prefixes = []\n\n if os.getenv(\"OCROPUS_DATA\"):\n possible_prefixes.append(os.getenv(\"OCROPUS_DATA\"))\n\n possible_prefixes.append(os.curdir)\n\n possible_prefixes.append(os.path.normpath(os.path.join(\n os.path.dirname(inspect.getfile(inspect.currentframe())),\n os.pardir, os.pardir, os.pardir, os.pardir, \"share\", \"ocropus\")))\n\n possible_prefixes.append(\"/usr/local/share/ocropus\")\n\n # datarootdir is None in windows so don't add it to search list\n if sysconfig.get_config_var(\"datarootdir\") is not None:\n possible_prefixes.append(os.path.join(\n sysconfig.get_config_var(\"datarootdir\"), \"ocropus\"))\n\n\n # Unique entries with preserved order in possible_prefixes\n # http://stackoverflow.com/a/15637398/201318\n possible_prefixes = [possible_prefixes[i] for i in\n sorted(unique(possible_prefixes, return_index=True)[1])]\n for prefix in possible_prefixes:\n if not os.path.isdir(prefix):\n continue\n for basename in [\".\", \"models\", \"data\", \"gui\"]:\n if not os.path.isdir(os.path.join(prefix, basename)):\n continue\n full = os.path.join(prefix, basename, fname)\n if os.path.exists(full):\n return full\n if gz and os.path.exists(full + \".gz\"):\n return full + \".gz\"\n\n raise FileNotFound(fname)\n\n\ndef fvariant(fname,kind,gt=\"\"):\n \"\"\"Find the file variant corresponding to the given file name.\n Possible fil variants are line (or png), rseg, cseg, fst, costs, and txt.\n Ground truth files have an extra suffix (usually something like \"gt\",\n as in 010001.gt.txt or 010001.rseg.gt.png). By default, the variant\n with the same ground truth suffix is produced. The non-ground-truth\n version can be produced with gt=\"\", the ground truth version can\n be produced with gt=\"gt\" (or some other desired suffix).\"\"\"\n if gt!=\"\": gt = \".\"+gt\n base,ext = allsplitext(fname)\n # text output\n if kind==\"txt\":\n return base+gt+\".txt\"\n assert gt==\"\",\"gt suffix may only be supplied for .txt files (%s,%s,%s)\"%(fname,kind,gt)\n # a text line image\n if kind==\"line\" or kind==\"png\" or kind==\"bin\":\n return base+\".bin.png\"\n if kind==\"nrm\":\n return base+\".nrm.png\"\n # a recognition lattice\n if kind==\"lattice\":\n return base+gt+\".lattice\"\n # raw segmentation\n if kind==\"rseg\":\n return base+\".rseg.png\"\n # character segmentation\n if kind==\"cseg\":\n return base+\".cseg.png\"\n # text specifically aligned with cseg (this may be different from gt or txt)\n if kind==\"aligned\":\n return base+\".aligned\"\n # per character costs\n if kind==\"costs\":\n return base+\".costs\"\n raise BadInput(\"unknown kind: %s\"%kind)\n\n################################################################\n### Utility for setting \"parameters\" on an object: a list of keywords for\n### changing instance variables.\n################################################################\n\ndef set_params(object,kw,warn=1):\n \"\"\"Given an object and a dictionary of keyword arguments,\n set only those object properties that are already instance\n variables of the given object. Returns a new dictionary\n without the key,value pairs that have been used. If\n all keywords have been used, afterwards, len(kw)==0.\"\"\"\n kw = kw.copy()\n for k,v in list(kw.items()):\n if hasattr(object,k):\n setattr(object,k,v)\n del kw[k]\n return kw\n\n################################################################\n### warning and logging\n################################################################\n\ndef caller():\n \"\"\"Just returns info about the caller in string for (for error messages).\"\"\"\n frame = sys._getframe(2)\n info = inspect.getframeinfo(frame)\n result = \"%s:%d (%s)\"%(info.filename,info.lineno,info.function)\n del frame\n return result\n\ndef die(message,*args):\n \"\"\"Die with an error message.\"\"\"\n LOG.critical(caller() + ' ' + message, args)\n sys.exit(1)\n\ndef warn(message,*args):\n \"\"\"Give a warning message.\"\"\"\n LOG.warning(caller() + ' ' + message, args)\n\nalready_warned = {}\n\ndef warn_once(message,*args):\n \"\"\"Give a warning message, but just once.\"\"\"\n c = caller()\n if c in already_warned: return\n already_warned[c] = 1\n LOG.warning(c + ' ' + message, args)\n\ndef quick_check_page_components(page_bin,dpi):\n \"\"\"Quickly check whether the components of page_bin are\n reasonable. Returns a value between 0 and 1; <0.5 means that\n there is probably something wrong.\"\"\"\n return 1.0\n\ndef quick_check_line_components(line_bin,dpi):\n \"\"\"Quickly check whether the components of line_bin are\n reasonable. Returns a value between 0 and 1; <0.5 means that\n there is probably something wrong.\"\"\"\n return 1.0\n\n################################################################\n### conversion functions\n################################################################\n\ndef ustrg2unicode(u,lig=ligatures.lig):\n \"\"\"Convert an iulib ustrg to a Python unicode string; the\n C++ version iulib.ustrg2unicode does weird things for special\n symbols like -3\"\"\"\n result = \"\"\n for i in range(u.length()):\n value = u.at(i)\n if value>=0:\n c = lig.chr(value)\n if c is not None:\n result += c\n else:\n result += \"<%d>\"%value\n return result\n\n################################################################\n### loading and saving components\n################################################################\n\n# This code has to deal with a lot of special cases for all the\n# different formats we have accrued.\n\ndef obinfo(ob):\n \"\"\"A bit of information about the given object. Returns\n the str representation of the object, and if it has a shape,\n also includes the shape.\"\"\"\n result = str(ob)\n if hasattr(ob,\"shape\"):\n result += \" \"\n result += str(ob.shape)\n return result\n\n\ndef binarize_range(image,dtype='B',threshold=0.5):\n \"\"\"Binarize an image by its range.\"\"\"\n threshold = (amax(image)+amin(image))*threshold\n scale = 1\n if dtype=='B': scale = 255\n return array(scale*(image>threshold),dtype=dtype)\n\ndef plotgrid(data,d=10,shape=(30,30)):\n \"\"\"Plot a list of images on a grid.\"\"\"\n from matplotlib.pyplot import ion, gray, clf, subplot, imshow, ginput\n ion()\n gray()\n clf()\n for i in range(min(d*d,len(data))):\n subplot(d,d,i+1)\n row = data[i]\n if shape is not None: row = row.reshape(shape)\n imshow(row)\n ginput(1,timeout=0.1)\n\ndef showrgb(r,g=None,b=None):\n from matplotlib.pyplot import imshow\n if g is None: g = r\n if b is None: b = r\n imshow(array([r,g,b]).transpose([1,2,0]))\n\ndef showgrid(l,cols=None,n=400,titles=None,xlabels=None,ylabels=None,**kw):\n from matplotlib.pyplot import cm, xticks, yticks, subplot, imshow, title, xlabel, ylabel\n if \"cmap\" not in kw: kw[\"cmap\"] = cm.gray\n if \"interpolation\" not in kw: kw[\"interpolation\"] = \"nearest\"\n n = minimum(n,len(l))\n if cols is None: cols = int(sqrt(n))\n rows = (n+cols-1)//cols\n for i in range(n):\n xticks([]) ;yticks([])\n subplot(rows,cols,i+1)\n imshow(l[i],**kw)\n if titles is not None: title(str(titles[i]))\n if xlabels is not None: xlabel(str(xlabels[i]))\n if ylabels is not None: ylabel(str(ylabels[i]))\n\ndef gt_explode(s):\n l = re.split(r'_(.{1,4})_',s)\n result = []\n for i,e in enumerate(l):\n if i%2==0:\n result += [c for c in e]\n else:\n result += [e]\n result = [re.sub(\"\\001\",\"_\",s) for s in result]\n result = [re.sub(\"\\002\",\"\\\\\\\\\",s) for s in result]\n return result\n\ndef gt_implode(l):\n result = []\n for c in l:\n if c==\"_\":\n result.append(\"___\")\n elif len(c)<=1:\n result.append(c)\n elif len(c)<=4:\n result.append(\"_\"+c+\"_\")\n else:\n raise BadInput(\"cannot create ground truth transcription for: %s\"%l)\n return \"\".join(result)\n\n@checks(int,sequence=int,frac=int,_=BOOL)\ndef testset(index,sequence=0,frac=10):\n # this doesn't have to be good, just a fast, somewhat random function\n return sequence==int(abs(sin(index))*1.23456789e6)%frac\n\ndef midrange(image,frac=0.5):\n \"\"\"Computes the center of the range of image values\n (for quick thresholding).\"\"\"\n return frac*(amin(image)+amax(image))\n\ndef remove_noise(line,minsize=8):\n \"\"\"Remove small pixels from an image.\"\"\"\n if minsize==0: return line\n bin = (line>0.5*amax(line))\n labels,n = morph.label(bin)\n sums = measurements.sum(bin,labels,list(range(n+1)))\n sums = sums[labels]\n good = minimum(bin,1-(sums>0)*(sums<minsize))\n return good\n\nclass MovingStats:\n def __init__(self,n=100):\n self.data = []\n self.n = n\n self.count = 0\n def add(self,x):\n self.data += [x]\n self.data = self.data[-self.n:]\n self.count += 1\n def mean(self):\n if len(self.data)==0: return nan\n return mean(self.data)\n" ]
[ [ "numpy.amax", "matplotlib.pyplot.imshow", "numpy.minimum", "scipy.ndimage.morphology.binary_dilation", "numpy.sqrt", "numpy.dtype", "numpy.mean", "matplotlib.pyplot.gray", "numpy.clip", "numpy.unique", "numpy.sin", "matplotlib.pyplot.subplot", "matplotlib.pyplot.ginput", "numpy.zeros", "numpy.amin", "numpy.array", "matplotlib.pyplot.ion", "matplotlib.pyplot.xticks", "numpy.bitwise_and", "matplotlib.pyplot.clf", "matplotlib.pyplot.yticks" ] ]
ca7869/tensorflow
[ "2daf3a3121f0da5cb060dca3958b2fa9c2f5dbc2" ]
[ "tfmodel.py" ]
[ "import os\n\nimport tensorflow as tf\nfrom tensorflow.python import keras\n#import keras\nfrom tensorflow.python.keras.layers import Input, Dense\nfrom tensorflow.python.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.python.keras.preprocessing.text import Tokenizer\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Flatten\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.advanced_activations import LeakyReLU\n#from tensorflow.python.framework import ops\n\nbase_dir = '/home/anoop/Downloads/dogs-vs-cats'\n\ntrain_dir = os.path.join(base_dir, 'train')\n\ntrain_datagen = ImageDataGenerator(rescale=1./255)\ntrain_generator = train_datagen.flow_from_directory(\n\ttrain_dir,\n\ttarget_size = (150,150),\n\tbatch_size = 20,\n\tclass_mode = 'binary'\n\t)\n\n\nmodel = tf.keras.models.Sequential([\n # Note the input shape is the desired size of the image 150x150 with 3 bytes color\n tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(150, 150, 3)),\n tf.keras.layers.MaxPooling2D(2,2),\n tf.keras.layers.Conv2D(32, (3,3), activation='relu'),\n tf.keras.layers.MaxPooling2D(2,2), \n tf.keras.layers.Conv2D(64, (3,3), activation='relu'), \n tf.keras.layers.MaxPooling2D(2,2),\n # Flatten the results to feed into a DNN\n tf.keras.layers.Flatten(), \n # 512 neuron hidden layer\n tf.keras.layers.Dense(512, activation='relu'), \n # Only 1 output neuron. It will contain a value from 0-1 where 0 for 1 class ('cats') and 1 for the other ('dogs')\n tf.keras.layers.Dense(1, activation='sigmoid') \n])" ]
[ [ "tensorflow.python.keras.preprocessing.image.ImageDataGenerator", "tensorflow.keras.layers.Dense", "tensorflow.keras.layers.Conv2D", "tensorflow.keras.layers.MaxPooling2D", "tensorflow.keras.layers.Flatten" ] ]
530824679/YOLOv3
[ "2ea5ccd136f00260b42eb459f5ab0884cb162483" ]
[ "model/ops.py" ]
[ "# -*- coding: utf-8 -*-\n# --------------------------------------\n# @Time : 2020/11/01\n# @Author : Oscar Chen\n# @Email : [email protected]\n# @File : ops.py\n# Description :base operators.\n# --------------------------------------\n\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\n\ndef fixed_padding(inputs, kernel_size):\n pad_total = kernel_size - 1\n pad_beg = pad_total // 2\n pad_end = pad_total - pad_beg\n\n padded_inputs = tf.pad(inputs, [[0, 0], [pad_beg, pad_end], [pad_beg, pad_end], [0, 0]], mode='CONSTANT')\n return padded_inputs\n\ndef leaky_relu(inputs, alpha):\n return tf.nn.leaky_relu(inputs, alpha=alpha, name='leaky_relu')\n\ndef conv2d(inputs, filters, kernel_size, strides=1):\n if strides > 1:\n inputs = fixed_padding(inputs, kernel_size)\n inputs = slim.conv2d(inputs, filters, kernel_size, stride=strides, padding=('SAME' if strides == 1 else 'VALID'))\n return inputs\n\ndef residual_block(inputs, filters):\n shortcut = inputs\n net = conv2d(inputs, filters * 1, 1)\n net = conv2d(net, filters * 2, 3)\n\n net = net + shortcut\n\n return net\n\ndef maxpool(inputs, size=2, stride=2):\n pool = tf.layers.max_pooling2d(inputs, pool_size=size, strides=stride, padding='SAME')\n\n return pool\n\ndef route(previous_output, current_output):\n output = tf.concat([current_output, previous_output], axis=-1)\n\n return output\n\ndef upsample(inputs, method=\"deconv\"):\n assert method in [\"resize\", \"deconv\"]\n\n if method == \"resize\":\n input_shape = tf.shape(inputs)\n output = tf.image.resize_nearest_neighbor(inputs, (input_shape[1] * 2, input_shape[2] * 2))\n\n if method == \"deconv\":\n numm_filter = inputs.shape.as_list()[-1]\n output = tf.layers.conv2d_transpose(inputs, numm_filter, kernel_size=2, padding='same', strides=(2,2), kernel_initializer=tf.random_normal_initializer())\n\n return output" ]
[ [ "tensorflow.concat", "tensorflow.image.resize_nearest_neighbor", "tensorflow.shape", "tensorflow.layers.max_pooling2d", "tensorflow.contrib.slim.conv2d", "tensorflow.pad", "tensorflow.random_normal_initializer", "tensorflow.nn.leaky_relu" ] ]
buptlihang/ESPNetv2
[ "9901d7e8a64cbfb24e5412a496d4ef230ac81093" ]
[ "segmentation/IOUEval.py" ]
[ "import numpy as np\n\n#adapted from https://github.com/shelhamer/fcn.berkeleyvision.org/blob/master/score.py\n\n#============================================\n__author__ = \"Sachin Mehta\"\n__license__ = \"MIT\"\n__maintainer__ = \"Sachin Mehta\"\n#============================================\n\nclass iouEval:\n def __init__(self, nClasses):\n self.nClasses = nClasses\n self.reset()\n\n def reset(self):\n self.overall_acc = 0\n self.per_class_acc = np.zeros(self.nClasses, dtype=np.float32)\n self.per_class_iu = np.zeros(self.nClasses, dtype=np.float32)\n self.mIOU = 0\n self.batchCount = 0\n\n def fast_hist(self, a, b):\n k = (a >= 0) & (a < self.nClasses)\n return np.bincount(self.nClasses * a[k].astype(int) + b[k], minlength=self.nClasses ** 2).reshape(self.nClasses, self.nClasses)\n\n def compute_hist(self, predict, gth):\n hist = self.fast_hist(gth, predict)\n return hist\n\n def addBatch(self, predict, gth):\n predict = predict.cpu().numpy().flatten()\n gth = gth.cpu().numpy().flatten()\n\n epsilon = 0.00000001\n hist = self.compute_hist(predict, gth)\n overall_acc = np.diag(hist).sum() / (hist.sum() + epsilon)\n per_class_acc = np.diag(hist) / (hist.sum(1) + epsilon)\n per_class_iu = np.diag(hist) / (hist.sum(1) + hist.sum(0) - np.diag(hist) + epsilon)\n mIou = np.nanmean(per_class_iu)\n\n self.overall_acc +=overall_acc\n self.per_class_acc += per_class_acc\n self.per_class_iu += per_class_iu\n self.mIOU += mIou\n self.batchCount += 1\n\n def getMetric(self):\n overall_acc = self.overall_acc/self.batchCount\n per_class_acc = self.per_class_acc / self.batchCount\n per_class_iu = self.per_class_iu / self.batchCount\n mIOU = self.mIOU / self.batchCount\n\n return overall_acc, per_class_acc, per_class_iu, mIOU\n" ]
[ [ "numpy.diag", "numpy.zeros", "numpy.nanmean" ] ]
SamuilYu/manim
[ "b726b40089a58a4684725d7216b01d8400ffb2bf" ]
[ "manim/mobject/graph.py" ]
[ "\"\"\"Mobjects used to represent mathematical graphs (think graph theory, not plotting).\"\"\"\n\n__all__ = [\n \"Graph\",\n]\n\nfrom copy import copy\nfrom typing import Hashable, List, Optional, Tuple, Type, Union\n\nimport networkx as nx\nimport numpy as np\n\nfrom ..animation.composition import AnimationGroup\nfrom ..animation.creation import Create, Uncreate\nfrom ..utils.color import BLACK\nfrom .geometry import Dot, LabeledDot, Line\nfrom .mobject import Group, Mobject, override_animate\nfrom .svg.tex_mobject import MathTex\nfrom .types.vectorized_mobject import MetaVMobject\n\n\ndef _determine_graph_layout(\n nx_graph: nx.classes.graph.Graph,\n layout: Union[str, dict] = \"spring\",\n layout_scale: float = 2,\n layout_config: Union[dict, None] = None,\n partitions: Union[List[List[Hashable]], None] = None,\n root_vertex: Union[Hashable, None] = None,\n) -> dict:\n automatic_layouts = {\n \"circular\": nx.layout.circular_layout,\n \"kamada_kawai\": nx.layout.kamada_kawai_layout,\n \"planar\": nx.layout.planar_layout,\n \"random\": nx.layout.random_layout,\n \"shell\": nx.layout.shell_layout,\n \"spectral\": nx.layout.spectral_layout,\n \"partite\": nx.layout.multipartite_layout,\n \"tree\": _tree_layout,\n \"spiral\": nx.layout.spiral_layout,\n \"spring\": nx.layout.spring_layout,\n }\n\n custom_layouts = [\"random\", \"partite\", \"tree\"]\n\n if layout_config is None:\n layout_config = {}\n\n if isinstance(layout, dict):\n return layout\n elif layout in automatic_layouts and layout not in custom_layouts:\n auto_layout = automatic_layouts[layout](\n nx_graph, scale=layout_scale, **layout_config\n )\n return {k: np.append(v, [0]) for k, v in auto_layout.items()}\n elif layout == \"tree\":\n return _tree_layout(\n nx_graph,\n root_vertex=root_vertex,\n scale=layout_scale,\n )\n elif layout == \"partite\":\n if partitions is None or len(partitions) == 0:\n raise ValueError(\n \"The partite layout requires the 'partitions' parameter to contain the partition of the vertices\"\n )\n partition_count = len(partitions)\n for i in range(partition_count):\n for v in partitions[i]:\n if nx_graph.nodes[v] is None:\n raise ValueError(\n \"The partition must contain arrays of vertices in the graph\"\n )\n nx_graph.nodes[v][\"subset\"] = i\n # Add missing vertices to their own side\n for v in nx_graph.nodes:\n if \"subset\" not in nx_graph.nodes[v]:\n nx_graph.nodes[v][\"subset\"] = partition_count\n\n auto_layout = automatic_layouts[\"partite\"](\n nx_graph, scale=layout_scale, **layout_config\n )\n return {k: np.append(v, [0]) for k, v in auto_layout.items()}\n elif layout == \"random\":\n # the random layout places coordinates in [0, 1)\n # we need to rescale manually afterwards...\n auto_layout = automatic_layouts[\"random\"](nx_graph, **layout_config)\n for k, v in auto_layout.items():\n auto_layout[k] = 2 * layout_scale * (v - np.array([0.5, 0.5]))\n return {k: np.append(v, [0]) for k, v in auto_layout.items()}\n else:\n raise ValueError(\n f\"The layout '{layout}' is neither a recognized automatic layout, \"\n \"nor a vertex placement dictionary.\"\n )\n\n\ndef _tree_layout(\n G: nx.classes.graph.Graph,\n root_vertex: Union[Hashable, None],\n scale: float,\n) -> dict:\n result = {root_vertex: np.array([0, 0, 0])}\n\n if not nx.is_tree(G):\n raise ValueError(\"The tree layout must be used with trees\")\n if root_vertex is None:\n raise ValueError(\"The tree layout requires the root_vertex parameter\")\n\n def _recursive_position_for_row(\n G: nx.classes.graph.Graph,\n result: dict,\n two_rows_before: List[Hashable],\n last_row: List[Hashable],\n current_height: float,\n ):\n new_row = []\n for v in last_row:\n for x in G.neighbors(v):\n if x not in two_rows_before:\n new_row.append(x)\n\n new_row_length = len(new_row)\n\n if new_row_length == 0:\n return\n\n if new_row_length == 1:\n result[new_row[0]] = np.array([0, current_height, 0])\n else:\n for i in range(new_row_length):\n result[new_row[i]] = np.array(\n [-1 + 2 * i / (new_row_length - 1), current_height, 0]\n )\n\n _recursive_position_for_row(\n G,\n result,\n two_rows_before=last_row,\n last_row=new_row,\n current_height=current_height + 1,\n )\n\n _recursive_position_for_row(\n G, result, two_rows_before=[], last_row=[root_vertex], current_height=1\n )\n\n height = max(map(lambda v: result[v][1], result))\n\n return {\n v: np.array([pos[0], 1 - 2 * pos[1] / height, pos[2]]) * scale / 2\n for v, pos in result.items()\n }\n\n\nclass Graph(metaclass=MetaVMobject):\n \"\"\"An undirected graph (that is, a collection of vertices connected with edges).\n\n Graphs can be instantiated by passing both a list of (distinct, hashable)\n vertex names, together with list of edges (as tuples of vertex names). See\n the examples below for details.\n\n .. note::\n\n This implementation uses updaters to make the edges move with\n the vertices.\n\n Parameters\n ----------\n\n vertices\n A list of vertices. Must be hashable elements.\n edges\n A list of edges, specified as tuples ``(u, v)`` where both ``u``\n and ``v`` are vertices.\n labels\n Controls whether or not vertices are labeled. If ``False`` (the default),\n the vertices are not labeled; if ``True`` they are labeled using their\n names (as specified in ``vertices``) via :class:`~.MathTex`. Alternatively,\n custom labels can be specified by passing a dictionary whose keys are\n the vertices, and whose values are the corresponding vertex labels\n (rendered via, e.g., :class:`~.Text` or :class:`~.Tex`).\n label_fill_color\n Sets the fill color of the default labels generated when ``labels``\n is set to ``True``. Has no effect for other values of ``labels``.\n layout\n Either one of ``\"spring\"`` (the default), ``\"circular\"``, ``\"kamada_kawai\"``,\n ``\"planar\"``, ``\"random\"``, ``\"shell\"``, ``\"spectral\"``, ``\"spiral\"``, ``\"tree\"``, and ``\"partite\"``\n for automatic vertex positioning using ``networkx``\n (see `their documentation <https://networkx.org/documentation/stable/reference/drawing.html#module-networkx.drawing.layout>`_\n for more details), or a dictionary specifying a coordinate (value)\n for each vertex (key) for manual positioning.\n layout_scale\n The scale of automatically generated layouts: the vertices will\n be arranged such that the coordinates are located within the\n interval ``[-scale, scale]``. Default: 2.\n layout_config\n Only for automatically generated layouts. A dictionary whose entries\n are passed as keyword arguments to the automatic layout algorithm\n specified via ``layout`` of``networkx``.\n vertex_type\n The mobject class used for displaying vertices in the scene.\n vertex_config\n Either a dictionary containing keyword arguments to be passed to\n the class specified via ``vertex_type``, or a dictionary whose keys\n are the vertices, and whose values are dictionaries containing keyword\n arguments for the mobject related to the corresponding vertex.\n vertex_mobjects\n A dictionary whose keys are the vertices, and whose values are\n mobjects to be used as vertices. Passing vertices here overrides\n all other configuration options for a vertex.\n edge_type\n The mobject class used for displaying edges in the scene.\n edge_config\n Either a dictionary containing keyword arguments to be passed\n to the class specified via ``edge_type``, or a dictionary whose\n keys are the edges, and whose values are dictionaries containing\n keyword arguments for the mobject related to the corresponding edge.\n\n Examples\n --------\n\n First, we create a small graph and demonstrate that the edges move\n together with the vertices.\n\n .. manim:: MovingVertices\n\n class MovingVertices(Scene):\n def construct(self):\n vertices = [1, 2, 3, 4]\n edges = [(1, 2), (2, 3), (3, 4), (1, 3), (1, 4)]\n g = Graph(vertices, edges)\n self.play(Create(g))\n self.wait()\n self.play(g[1].animate.move_to([1, 1, 0]),\n g[2].animate.move_to([-1, 1, 0]),\n g[3].animate.move_to([1, -1, 0]),\n g[4].animate.move_to([-1, -1, 0]))\n self.wait()\n\n There are several automatic positioning algorithms to choose from:\n\n .. manim:: GraphAutoPosition\n :save_last_frame:\n\n class GraphAutoPosition(Scene):\n def construct(self):\n vertices = [1, 2, 3, 4, 5, 6, 7, 8]\n edges = [(1, 7), (1, 8), (2, 3), (2, 4), (2, 5),\n (2, 8), (3, 4), (6, 1), (6, 2),\n (6, 3), (7, 2), (7, 4)]\n autolayouts = [\"spring\", \"circular\", \"kamada_kawai\",\n \"planar\", \"random\", \"shell\",\n \"spectral\", \"spiral\"]\n graphs = [Graph(vertices, edges, layout=lt).scale(0.5)\n for lt in autolayouts]\n r1 = VGroup(*graphs[:3]).arrange()\n r2 = VGroup(*graphs[3:6]).arrange()\n r3 = VGroup(*graphs[6:]).arrange()\n self.add(VGroup(r1, r2, r3).arrange(direction=DOWN))\n\n Vertices can also be positioned manually:\n\n .. manim:: GraphManualPosition\n :save_last_frame:\n\n class GraphManualPosition(Scene):\n def construct(self):\n vertices = [1, 2, 3, 4]\n edges = [(1, 2), (2, 3), (3, 4), (4, 1)]\n lt = {1: [0, 0, 0], 2: [1, 1, 0], 3: [1, -1, 0], 4: [-1, 0, 0]}\n G = Graph(vertices, edges, layout=lt)\n self.add(G)\n\n The vertices in graphs can be labeled, and configurations for vertices\n and edges can be modified both by default and for specific vertices and\n edges.\n\n .. note::\n\n In ``edge_config``, edges can be passed in both directions: if\n ``(u, v)`` is an edge in the graph, both ``(u, v)`` as well\n as ``(v, u)`` can be used as keys in the dictionary.\n\n .. manim:: LabeledModifiedGraph\n :save_last_frame:\n\n class LabeledModifiedGraph(Scene):\n def construct(self):\n vertices = [1, 2, 3, 4, 5, 6, 7, 8]\n edges = [(1, 7), (1, 8), (2, 3), (2, 4), (2, 5),\n (2, 8), (3, 4), (6, 1), (6, 2),\n (6, 3), (7, 2), (7, 4)]\n g = Graph(vertices, edges, layout=\"circular\", layout_scale=3,\n labels=True, vertex_config={7: {\"fill_color\": RED}},\n edge_config={(1, 7): {\"stroke_color\": RED},\n (2, 7): {\"stroke_color\": RED},\n (4, 7): {\"stroke_color\": RED}})\n self.add(g)\n\n You can also lay out a partite graph on columns by specifying\n a list of the vertices on each side and choosing the partite layout.\n\n .. note::\n\n All vertices in your graph which are not listed in any of the partitions\n are collected in their own partition and rendered in the rightmost column.\n\n .. manim:: PartiteGraph\n :save_last_frame:\n\n import networkx as nx\n\n class PartiteGraph(Scene):\n def construct(self):\n G = nx.Graph()\n G.add_nodes_from([0, 1, 2, 3])\n G.add_edges_from([(0, 2), (0,3), (1, 2)])\n graph = Graph(list(G.nodes), list(G.edges), layout=\"partite\", partitions=[[0, 1]])\n self.play(Create(graph))\n\n The custom tree layout can be used to show the graph\n by distance from the root vertex. You must pass the root vertex\n of the tree.\n\n .. manim:: Tree\n\n from manim import *\n import networkx as nx\n\n class Tree(Scene):\n def construct(self):\n G = nx.Graph()\n\n G.add_node(\"ROOT\")\n\n for i in range(5):\n G.add_node(\"Child_%i\" % i)\n G.add_node(\"Grandchild_%i\" % i)\n G.add_node(\"Greatgrandchild_%i\" % i)\n\n G.add_edge(\"ROOT\", \"Child_%i\" % i)\n G.add_edge(\"Child_%i\" % i, \"Grandchild_%i\" % i)\n G.add_edge(\"Grandchild_%i\" % i, \"Greatgrandchild_%i\" % i)\n\n self.play(Create(\n Graph(list(G.nodes), list(G.edges), layout=\"tree\", root_vertex=\"ROOT\")))\n \"\"\"\n\n def __init__(\n self,\n vertices: List[Hashable],\n edges: List[Tuple[Hashable, Hashable]],\n labels: bool = False,\n label_fill_color: str = BLACK,\n layout: Union[str, dict] = \"spring\",\n layout_scale: float = 2,\n layout_config: Union[dict, None] = None,\n vertex_type: Type[\"Mobject\"] = Dot,\n vertex_config: Union[dict, None] = None,\n vertex_mobjects: Optional[dict] = None,\n edge_type: Type[\"Mobject\"] = Line,\n partitions: Union[List[List[Hashable]], None] = None,\n root_vertex: Union[Hashable, None] = None,\n edge_config: Union[dict, None] = None,\n ) -> None:\n super().__init__()\n\n nx_graph = nx.Graph()\n nx_graph.add_nodes_from(vertices)\n nx_graph.add_edges_from(edges)\n self._graph = nx_graph\n\n self._layout = _determine_graph_layout(\n nx_graph,\n layout=layout,\n layout_scale=layout_scale,\n layout_config=layout_config,\n partitions=partitions,\n root_vertex=root_vertex,\n )\n\n if isinstance(labels, dict):\n self._labels = labels\n elif isinstance(labels, bool):\n if labels:\n self._labels = {\n v: MathTex(v, fill_color=label_fill_color) for v in vertices\n }\n else:\n self._labels = {}\n\n if self._labels and vertex_type is Dot:\n vertex_type = LabeledDot\n\n if vertex_mobjects is None:\n vertex_mobjects = {}\n\n # build vertex_config\n if vertex_config is None:\n vertex_config = {}\n default_vertex_config = {}\n if vertex_config:\n default_vertex_config = {\n k: v for k, v in vertex_config.items() if k not in vertices\n }\n self._vertex_config = {\n v: vertex_config.get(v, copy(default_vertex_config)) for v in vertices\n }\n self.default_vertex_config = default_vertex_config\n for v, label in self._labels.items():\n self._vertex_config[v][\"label\"] = label\n\n self.vertices = {v: vertex_type(**self._vertex_config[v]) for v in vertices}\n self.vertices.update(vertex_mobjects)\n for v in self.vertices:\n self[v].move_to(self._layout[v])\n\n # build edge_config\n if edge_config is None:\n edge_config = {}\n default_edge_config = {}\n if edge_config:\n default_edge_config = {\n k: v\n for k, v in edge_config.items()\n if k not in edges and k[::-1] not in edges\n }\n self._edge_config = {}\n for e in edges:\n if e in edge_config:\n self._edge_config[e] = edge_config[e]\n elif e[::-1] in edge_config:\n self._edge_config[e] = edge_config[e[::-1]]\n else:\n self._edge_config[e] = copy(default_edge_config)\n\n self.default_edge_config = default_edge_config\n self.edges = {\n (u, v): edge_type(\n self[u].get_center(),\n self[v].get_center(),\n z_index=-1,\n **self._edge_config[(u, v)],\n )\n for (u, v) in edges\n }\n\n self.add(*self.vertices.values())\n self.add(*self.edges.values())\n\n def update_edges(graph):\n for (u, v), edge in graph.edges.items():\n edge.put_start_and_end_on(graph[u].get_center(), graph[v].get_center())\n\n self.add_updater(update_edges)\n\n def __getitem__(self: \"Graph\", v: Hashable) -> \"Mobject\":\n return self.vertices[v]\n\n def __repr__(self: \"Graph\") -> str:\n return f\"Graph on {len(self.vertices)} vertices and {len(self.edges)} edges\"\n\n def _add_vertex(\n self,\n vertex: Hashable,\n position: Optional[np.ndarray] = None,\n label: bool = False,\n label_fill_color: str = BLACK,\n vertex_type: Type[\"Mobject\"] = Dot,\n vertex_config: Optional[dict] = None,\n vertex_mobject: Optional[dict] = None,\n ) -> \"Mobject\":\n \"\"\"Add a vertex to the graph.\n\n Parameters\n ----------\n\n vertex\n A hashable vertex identifier.\n position\n The coordinates where the new vertex should be added. If ``None``, the center\n of the graph is used.\n label\n Controls whether or not the vertex is labeled. If ``False`` (the default),\n the vertex is not labeled; if ``True`` it is labeled using its\n names (as specified in ``vertex``) via :class:`~.MathTex`. Alternatively,\n any :class:`~.Mobject` can be passed to be used as the label.\n label_fill_color\n Sets the fill color of the default labels generated when ``labels``\n is set to ``True``. Has no effect for other values of ``label``.\n vertex_type\n The mobject class used for displaying vertices in the scene.\n vertex_config\n A dictionary containing keyword arguments to be passed to\n the class specified via ``vertex_type``.\n vertex_mobject\n The mobject to be used as the vertex. Overrides all other\n vertex customization options.\n \"\"\"\n if position is None:\n position = self.get_center()\n\n if vertex_config is None:\n vertex_config = {}\n\n if vertex in self.vertices:\n raise ValueError(\n f\"Vertex identifier '{vertex}' is already used for a vertex in this graph.\"\n )\n\n self._graph.add_node(vertex)\n self._layout[vertex] = position\n\n if isinstance(label, Mobject):\n self._labels[vertex] = label\n elif label is True:\n self._labels[vertex] = MathTex(vertex, fill_color=label_fill_color)\n\n base_vertex_config = copy(self.default_vertex_config)\n base_vertex_config.update(vertex_config)\n vertex_config = base_vertex_config\n\n if vertex in self._labels:\n vertex_config[\"label\"] = self._labels[vertex]\n if vertex_type is Dot:\n vertex_type = LabeledDot\n\n self._vertex_config[vertex] = vertex_config\n\n if vertex_mobject is None:\n self.vertices[vertex] = vertex_type(**vertex_config)\n else:\n self.vertices[vertex] = vertex_mobject\n\n self.vertices[vertex].move_to(position)\n self.add(self.vertices[vertex])\n\n return self.vertices[vertex]\n\n def add_vertices(\n self: \"Graph\",\n *vertices: List[Hashable],\n positions: Optional[dict] = None,\n labels: bool = False,\n label_fill_color: str = BLACK,\n vertex_type: Type[\"Mobject\"] = Dot,\n vertex_config: Optional[dict] = None,\n vertex_mobjects: Optional[dict] = None,\n ):\n \"\"\"Add a list of vertices to the graph.\n\n Parameters\n ----------\n\n vertices\n A list of hashable vertex identifiers.\n positions\n A dictionary specifying the coordinates where the new vertices should be added.\n If ``None``, all vertices are created at the center of the graph.\n labels\n Controls whether or not the vertex is labeled. If ``False`` (the default),\n the vertex is not labeled; if ``True`` it is labeled using its\n names (as specified in ``vertex``) via :class:`~.MathTex`. Alternatively,\n any :class:`~.Mobject` can be passed to be used as the label.\n label_fill_color\n Sets the fill color of the default labels generated when ``labels``\n is set to ``True``. Has no effect for other values of ``labels``.\n vertex_type\n The mobject class used for displaying vertices in the scene.\n vertex_config\n A dictionary containing keyword arguments to be passed to\n the class specified via ``vertex_type``.\n vertex_mobjects\n A dictionary whose keys are the vertex identifiers, and whose\n values are mobjects that should be used as vertices. Overrides\n all other vertex customization options.\n \"\"\"\n if positions is None:\n positions = {}\n if vertex_mobjects is None:\n vertex_mobjects = {}\n\n graph_center = self.get_center()\n base_positions = {v: graph_center for v in vertices}\n base_positions.update(positions)\n positions = base_positions\n\n if isinstance(labels, bool):\n labels = {v: labels for v in vertices}\n else:\n assert isinstance(labels, dict)\n base_labels = {v: False for v in vertices}\n base_labels.update(labels)\n labels = base_labels\n\n if vertex_config is None:\n vertex_config = copy(self.default_vertex_config)\n\n assert isinstance(vertex_config, dict)\n base_vertex_config = copy(self.default_vertex_config)\n base_vertex_config.update(\n {key: val for key, val in vertex_config.items() if key not in vertices}\n )\n vertex_config = {\n v: (vertex_config[v] if v in vertex_config else copy(base_vertex_config))\n for v in vertices\n }\n\n return [\n self._add_vertex(\n v,\n position=positions[v],\n label=labels[v],\n label_fill_color=label_fill_color,\n vertex_type=vertex_type,\n vertex_config=vertex_config[v],\n vertex_mobject=vertex_mobjects[v] if v in vertex_mobjects else None,\n )\n for v in vertices\n ]\n\n @override_animate(add_vertices)\n def _add_vertices_animation(self, *args, anim_args=None, **kwargs):\n if anim_args is None:\n anim_args = {}\n\n animation = anim_args.pop(\"animation\", Create)\n\n vertex_mobjects = self.add_vertices(*args, **kwargs)\n return AnimationGroup(*[animation(v, **anim_args) for v in vertex_mobjects])\n\n def _remove_vertex(self, vertex):\n \"\"\"Remove a vertex (as well as all incident edges) from the graph.\n\n Parameters\n ----------\n\n vertex\n The identifier of a vertex to be removed.\n\n Returns\n -------\n\n Group\n A mobject containing all removed objects.\n\n \"\"\"\n if vertex not in self.vertices:\n raise ValueError(\n f\"The graph does not contain a vertex with identifier '{vertex}'\"\n )\n\n self._graph.remove_node(vertex)\n self._layout.pop(vertex)\n if vertex in self._labels:\n self._labels.pop(vertex)\n self._vertex_config.pop(vertex)\n\n edge_tuples = [e for e in self.edges if vertex in e]\n for e in edge_tuples:\n self._edge_config.pop(e)\n to_remove = [self.edges.pop(e) for e in edge_tuples]\n to_remove.append(self.vertices.pop(vertex))\n\n self.remove(*to_remove)\n return self.get_group_class()(*to_remove)\n\n def remove_vertices(self, *vertices):\n \"\"\"Remove several vertices from the graph.\n\n Parameters\n ----------\n\n vertices\n A list of vertices to be removed from the graph.\n\n Examples\n --------\n ::\n\n >>> G = Graph([1, 2, 3], [(1, 2), (2, 3)])\n >>> removed = G.remove_vertices(2, 3); removed\n VGroup(Line, Line, Dot, Dot)\n >>> G\n Graph on 1 vertices and 0 edges\n\n \"\"\"\n mobjects = []\n for v in vertices:\n mobjects.extend(self._remove_vertex(v).submobjects)\n return self.get_group_class()(*mobjects)\n\n @override_animate(remove_vertices)\n def _remove_vertices_animation(self, *vertices, anim_args=None):\n if anim_args is None:\n anim_args = {}\n\n animation = anim_args.pop(\"animation\", Uncreate)\n\n mobjects = self.remove_vertices(*vertices)\n return AnimationGroup(*[animation(mobj, **anim_args) for mobj in mobjects])\n\n def _add_edge(\n self,\n edge: Tuple[Hashable, Hashable],\n edge_type: Type[\"Mobject\"] = Line,\n edge_config: Optional[dict] = None,\n ):\n \"\"\"Add a new edge to the graph.\n\n Parameters\n ----------\n\n edge\n The edge (as a tuple of vertex identifiers) to be added. If a non-existing\n vertex is passed, a new vertex with default settings will be created. Create\n new vertices yourself beforehand to customize them.\n edge_type\n The mobject class used for displaying edges in the scene.\n edge_config\n A dictionary containing keyword arguments to be passed\n to the class specified via ``edge_type``.\n\n Returns\n -------\n Group\n A group containing all newly added vertices and edges.\n\n \"\"\"\n if edge_config is None:\n edge_config = self.default_edge_config.copy()\n added_mobjects = []\n for v in edge:\n if v not in self.vertices:\n added_mobjects.append(self._add_vertex(v))\n u, v = edge\n\n self._graph.add_edge(u, v)\n\n base_edge_config = self.default_edge_config.copy()\n base_edge_config.update(edge_config)\n edge_config = base_edge_config\n self._edge_config[(u, v)] = edge_config\n\n edge_mobject = edge_type(\n self[u].get_center(), self[v].get_center(), z_index=-1, **edge_config\n )\n self.edges[(u, v)] = edge_mobject\n\n self.add(edge_mobject)\n added_mobjects.append(edge_mobject)\n return self.get_group_class()(*added_mobjects)\n\n def add_edges(\n self,\n *edges: List[Tuple[Hashable, Hashable]],\n edge_type: Type[\"Mobject\"] = Line,\n edge_config: Optional[dict] = None,\n ):\n \"\"\"Add new edges to the graph.\n\n Parameters\n ----------\n\n edges\n The edge (as a tuple of vertex identifiers) to be added. If a non-existing\n vertex is passed, a new vertex with default settings will be created. Create\n new vertices yourself beforehand to customize them.\n edge_type\n The mobject class used for displaying edges in the scene.\n edge_config\n A dictionary either containing keyword arguments to be passed\n to the class specified via ``edge_type``, or a dictionary\n whose keys are the edge tuples, and whose values are dictionaries\n containing keyword arguments to be passed for the construction\n of the corresponding edge.\n\n Returns\n -------\n Group\n A group containing all newly added vertices and edges.\n\n \"\"\"\n if edge_config is None:\n edge_config = {}\n non_edge_settings = {k: v for (k, v) in edge_config.items() if k not in edges}\n base_edge_config = self.default_edge_config.copy()\n base_edge_config.update(non_edge_settings)\n base_edge_config = {e: base_edge_config.copy() for e in edges}\n for e in edges:\n base_edge_config[e].update(edge_config.get(e, {}))\n edge_config = base_edge_config\n\n added_mobjects = sum(\n [\n self._add_edge(\n edge, edge_type=edge_type, edge_config=edge_config[edge]\n ).submobjects\n for edge in edges\n ],\n [],\n )\n return self.get_group_class()(*added_mobjects)\n\n @override_animate(add_edges)\n def _add_edges_animation(self, *args, anim_args=None, **kwargs):\n if anim_args is None:\n anim_args = {}\n animation = anim_args.pop(\"animation\", Create)\n\n mobjects = self.add_edges(*args, **kwargs)\n return AnimationGroup(*[animation(mobj, **anim_args) for mobj in mobjects])\n\n def _remove_edge(self, edge: Tuple[Hashable]):\n \"\"\"Remove an edge from the graph.\n\n Parameters\n ----------\n\n edge\n The edge (i.e., a tuple of vertex identifiers) to be removed from the graph.\n\n Returns\n -------\n\n Mobject\n The removed edge.\n\n \"\"\"\n if edge not in self.edges:\n edge = edge[::-1]\n if edge not in self.edges:\n raise ValueError(f\"The graph does not contain a edge '{edge}'\")\n\n edge_mobject = self.edges.pop(edge)\n\n self._graph.remove_edge(*edge)\n self._edge_config.pop(edge, None)\n\n self.remove(edge_mobject)\n return edge_mobject\n\n def remove_edges(self, *edges: List[Tuple[Hashable]]):\n \"\"\"Remove several edges from the graph.\n\n Parameters\n ----------\n edges\n A list of edges to be removed from the graph.\n\n Returns\n -------\n Group\n A group containing all removed edges.\n\n \"\"\"\n edge_mobjects = [self._remove_edge(edge) for edge in edges]\n return self.get_group_class()(*edge_mobjects)\n\n @override_animate(remove_edges)\n def _remove_edges_animation(self, *edges, anim_args=None):\n if anim_args is None:\n anim_args = {}\n\n animation = anim_args.pop(\"animation\", Uncreate)\n\n mobjects = self.remove_edges(*edges)\n return AnimationGroup(*[animation(mobj, **anim_args) for mobj in mobjects])\n\n @staticmethod\n def from_networkx(nxgraph: nx.classes.graph.Graph, **kwargs) -> \"Graph\":\n \"\"\"Build a :class:`~.Graph` from a given ``networkx`` graph.\n\n Parameters\n ----------\n\n nxgraph\n A ``networkx`` graph.\n **kwargs\n Keywords to be passed to the constructor of :class:`~.Graph`.\n\n Examples\n --------\n\n .. manim:: ImportNetworkxGraph\n\n import networkx as nx\n\n nxgraph = nx.erdos_renyi_graph(14, 0.5)\n\n class ImportNetworkxGraph(Scene):\n def construct(self):\n G = Graph.from_networkx(nxgraph, layout=\"spring\", layout_scale=3.5)\n self.play(Create(G))\n self.play(*[G[v].animate.move_to(5*RIGHT*np.cos(ind/7 * PI) +\n 3*UP*np.sin(ind/7 * PI))\n for ind, v in enumerate(G.vertices)])\n self.play(Uncreate(G))\n\n \"\"\"\n return Graph(list(nxgraph.nodes), list(nxgraph.edges), **kwargs)\n\n def change_layout(\n self,\n layout: Union[str, dict] = \"spring\",\n layout_scale: float = 2,\n layout_config: Union[dict, None] = None,\n partitions: Union[List[List[Hashable]], None] = None,\n root_vertex: Union[Hashable, None] = None,\n ) -> \"Graph\":\n \"\"\"Change the layout of this graph.\n\n See the documentation of :class:`~.Graph` for details about the\n keyword arguments.\n\n Examples\n --------\n\n .. manim:: ChangeGraphLayout\n\n class ChangeGraphLayout(Scene):\n def construct(self):\n G = Graph([1, 2, 3, 4, 5], [(1, 2), (2, 3), (3, 4), (4, 5)],\n layout={1: [-2, 0, 0], 2: [-1, 0, 0], 3: [0, 0, 0],\n 4: [1, 0, 0], 5: [2, 0, 0]}\n )\n self.play(Create(G))\n self.play(G.animate.change_layout(\"circular\"))\n self.wait()\n \"\"\"\n self._layout = _determine_graph_layout(\n self._graph,\n layout=layout,\n layout_scale=layout_scale,\n layout_config=layout_config,\n partitions=partitions,\n root_vertex=root_vertex,\n )\n for v in self.vertices:\n self[v].move_to(self._layout[v])\n return self\n" ]
[ [ "numpy.append", "numpy.array" ] ]
KishanGitASU/A3C-RL-baseline-agent-for-Grid2Op-environment
[ "675a559d03d9532505d687e11e3a2922348cc767" ]
[ "AsynchronousActorCritic.py" ]
[ "try:\r\n import grid2op\r\n import threading\r\n import numpy as np\r\n import time\r\n import json\r\n import copy\r\n import os\r\n from grid2op import make\r\n from grid2op.Agent import MLAgent\r\n from grid2op.Environment import Environment\r\n from grid2op.Parameters import Parameters\r\n from grid2op.Reward import L2RPNReward, CombinedReward, CloseToOverflowReward, GameplayReward\r\n\r\n import tensorflow.compat.v1 as tf\r\n tf.disable_v2_behavior()\r\n\r\n from tensorflow.keras.layers import Dense, Input\r\n from tensorflow.keras.models import Model\r\n from tensorflow.keras.optimizers import Adam\r\n import tensorflow.python.keras.backend as K\r\n from l2rpn_baselines.AsynchronousActorCritic.user_environment_make import set_environement\r\n # import user_environment_make\r\nexcept ImportError as exc_:\r\n raise ImportError(\"AsynchronousActorCritic baseline impossible to load the required dependencies for training the model. The error was: \\n {}\".format(exc_))\r\n\r\n\r\n# import user_environment_make\r\n\r\n# Create the Agent instance here that can used with the Runner to test the performance of the trained RL agent.\r\nclass A3CAgent(MLAgent):\r\n # first change: An Agent must derived from grid2op.Agent (in this case MLAgent, because we manipulate vector instead\r\n # of classes) We will use this template to create our desired ML agent with unique neural network configuration.\r\n def __init__(self, state_size, action_size, env_name, action_space, value_multiplier,action_space_lists,\r\n profiles_chronics,EPISODES_train2,time_step_end2,Hyperparameters,Thread_count,train_flag,save_path):\r\n MLAgent.__init__(self, action_space)\r\n # Parameter settings.\r\n # NOTE: MAKE SURE THE FOLLOWING SETTINGS ARE SAME AS THE TRAINED AGENT OR THE WEIGHTS WONT LOAD SUCCESSFULLY.\r\n # get size of state and action\r\n self.state_size = state_size\r\n self.action_size = action_size\r\n # get gym environment name\r\n self.env_name = env_name\r\n self.denominator = value_multiplier\r\n\r\n if train_flag:\r\n # these are hyper parameters for the A3C\r\n self.actor_lr = Hyperparameters[\"actor_learning_rate\"]\r\n self.critic_lr = Hyperparameters[\"critic_learning_rate\"]\r\n self.discount_factor = Hyperparameters[\"discount_factor\"]\r\n self.threads = Thread_count\r\n self.save_path = os.path.abspath(save_path)\r\n if not os.path.exists(self.save_path):\r\n os.mkdir(self.save_path)\r\n else: #evaluating\r\n self.action_list = []\r\n\r\n self.hidden1, self.hidden2 = Hyperparameters[\"size_of_hidden_layer_1\"], Hyperparameters[\"size_of_hidden_layer_2\"]\r\n\r\n # create model for actor and critic network\r\n self.actor, self.critic = self.build_model()\r\n\r\n if train_flag:\r\n # method for training actor and critic network\r\n self.optimizer = [self.actor_optimizer(), self.critic_optimizer()]\r\n\r\n # global variables for threading\r\n global scores\r\n scores = []\r\n global time_step_end\r\n time_step_end = time_step_end2\r\n global EPISODES_train\r\n EPISODES_train = EPISODES_train2\r\n\r\n self.profiles_chronics = profiles_chronics\r\n\r\n # tf will use CPU. Number of GPU devices allowed to access are zero.\r\n self.sess = tf.InteractiveSession(config=tf.ConfigProto(device_count={'GPU': 0}))\r\n K.set_session(self.sess)\r\n self.sess.run(tf.global_variables_initializer())\r\n\r\n self.action_space_lists = action_space_lists\r\n self.gen_action_list = action_space_lists[0]\r\n self.load_action_list = action_space_lists[1]\r\n self.line_or_action_list = action_space_lists[2]\r\n self.line_ex_action_list = action_space_lists[3]\r\n\r\n # approximate policy and value using Neural Network\r\n # actor -> state is input and probability of each action is output of network\r\n # critic -> state is input and value of state is output of network\r\n # actor and critic network share first hidden layer. These neural networks should be same as the neural network\r\n # from \"train.py\".\r\n def build_model(self):\r\n state = Input(batch_shape=(None, self.state_size))\r\n shared = Dense(self.hidden1, input_dim=self.state_size, activation='relu', kernel_initializer='glorot_uniform')(state)\r\n\r\n actor_hidden = Dense(self.hidden2, activation='relu', kernel_initializer='glorot_uniform')(shared)\r\n action_prob = Dense(self.action_size, activation='softmax', kernel_initializer='glorot_uniform')(actor_hidden)\r\n # action_prob = K.softmax(action_intermediate)\r\n\r\n value_hidden = Dense(self.hidden2, activation='relu', kernel_initializer='he_uniform')(shared)\r\n state_value = Dense(1, activation='linear', kernel_initializer='he_uniform')(value_hidden)\r\n\r\n actor = Model(inputs=state, outputs=action_prob)\r\n critic = Model(inputs=state, outputs=state_value)\r\n\r\n actor._make_predict_function()\r\n critic._make_predict_function()\r\n\r\n # actor.summary()\r\n # critic.summary()\r\n\r\n return actor, critic\r\n\r\n def act(self, state_as_dict, reward, done=False):\r\n state = useful_state(state_as_dict,self.denominator)\r\n state = state.reshape([1,state.size])\r\n action_index = self.get_action(state_as_dict,state)\r\n\r\n # Creates the action \"object\". If we use \"print(action)\" then it is readable.\r\n action = self.create_action_dict(self.gen_action_list, self.load_action_list, self.line_or_action_list, self.line_ex_action_list,\r\n action_index,None, None)\r\n # print(action)\r\n # self.action_list.append(action)\r\n return action\r\n\r\n def create_action_dict(self,gen_action_list, load_action_list, line_or_action_list, line_ex_action_list, action_index, episode, flag):\r\n action = self.action_space(\r\n {\"change_bus\": {\"generators_id\": gen_action_list[action_index], \"loads_id\": load_action_list[action_index],\r\n \"lines_or_id\": line_or_action_list[action_index],\r\n \"lines_ex_id\": line_ex_action_list[action_index]}})\r\n return action\r\n\r\n def get_action(self, state_as_dict, state):\r\n with self.sess.as_default():\r\n with self.sess.graph.as_default():\r\n # Predict the action using the internal neural network\r\n policy = self.actor.predict(state,batch_size=1).flatten()\r\n\r\n # Select first 4 best possible actions from the neural nets.\r\n policy_chosen_list = np.random.choice(self.action_size, 4, p=policy)\r\n\r\n # Simulate the impact of these actions and pick the best action that maximizes the reward.\r\n # (one-step lookahead).\r\n action_index = policy_chosen_list[0]\r\n action = self.create_action_dict(self.gen_action_list, self.load_action_list, self.line_or_action_list, self.line_ex_action_list, action_index, None, None)\r\n obs_0, rw_0, done_0, _ = state_as_dict.simulate(action)\r\n\r\n action_index = policy_chosen_list[1]\r\n action = self.create_action_dict(self.gen_action_list, self.load_action_list, self.line_or_action_list, self.line_ex_action_list, action_index, None, None)\r\n obs_1, rw_1, done_1, _ = state_as_dict.simulate(action)\r\n\r\n action_index = policy_chosen_list[2]\r\n action = self.create_action_dict(self.gen_action_list, self.load_action_list, self.line_or_action_list, self.line_ex_action_list, action_index, None, None)\r\n obs_2, rw_2, done_2, _ = state_as_dict.simulate(action)\r\n\r\n action_index = policy_chosen_list[3]\r\n action = self.create_action_dict(self.gen_action_list, self.load_action_list, self.line_or_action_list, self.line_ex_action_list, action_index, None, None)\r\n obs_3, rw_3, done_3, _ = state_as_dict.simulate(action)\r\n\r\n return policy_chosen_list[np.argmax([rw_0,rw_1,rw_2,rw_3])]\r\n\r\n # make loss function for Policy Gradient\r\n # [log(action probability) * advantages] will be input for the back prop\r\n # we add entropy of action probability to loss\r\n def actor_optimizer(self):\r\n action = K.placeholder(shape=(None, self.action_size))\r\n advantages = K.placeholder(shape=(None, ))\r\n\r\n policy = self.actor.output\r\n\r\n good_prob = K.sum(action * policy, axis=1)\r\n eligibility = K.log(good_prob + 1e-10) * K.stop_gradient(advantages)\r\n loss = -K.sum(eligibility)\r\n\r\n entropy = K.sum(policy * K.log(policy + 1e-10), axis=1)\r\n\r\n actor_loss = loss + 0.01*entropy\r\n\r\n optimizer = Adam(lr=self.actor_lr)\r\n # updates = optimizer.get_updates(params=self.actor.trainable_weights, constraints=[],loss=actor_loss)\r\n updates = optimizer.get_updates(params=self.actor.trainable_weights, loss=actor_loss)\r\n train = K.function([self.actor.input, action, advantages], tf.compat.v1.convert_to_tensor([]),updates=updates)\r\n return train\r\n\r\n # make loss function for Value approximation\r\n def critic_optimizer(self):\r\n discounted_reward = K.placeholder(shape=(None, ))\r\n\r\n value = self.critic.output\r\n\r\n loss = K.mean(K.square(discounted_reward - value))\r\n\r\n optimizer = Adam(lr=self.critic_lr)\r\n # updates = optimizer.get_updates(params=self.critic.trainable_weights, constraints=[],loss=loss)\r\n updates = optimizer.get_updates(params=self.critic.trainable_weights, loss=loss)\r\n train = K.function([self.critic.input, discounted_reward], tf.compat.v1.convert_to_tensor([]), updates=updates)\r\n return train\r\n\r\n # make agents(local) and start training\r\n def train(self, nn_weights_name):\r\n agents = [Agent(i, self.actor, self.critic, self.optimizer, self.env_name, self.discount_factor,\r\n self.action_size, self.state_size, self.action_space_lists, self.profiles_chronics, self.sess) for i in range(self.threads)]\r\n\r\n for agent in agents:\r\n agent.start()\r\n\r\n while (len(scores) < EPISODES_train):\r\n time.sleep(200) # main thread saves the model every 200 sec\r\n print(\"len(scores) = \", len(scores))\r\n if (len(scores)>10):\r\n self.save_model(nn_weights_name,self.save_path)\r\n print(\"_______________________________________________________________________________________________________\")\r\n print(\"saved NN model at episode\", episode, \"\\n\")\r\n print(\"_______________________________________________________________________________________________________\")\r\n\r\n def load_model(self, nn_weight_name, load_path):\r\n self.actor.load_weights(os.path.join(load_path,nn_weight_name + \"_actor.h5\"))\r\n self.critic.load_weights(os.path.join(load_path,nn_weight_name + \"_critic.h5\"))\r\n\r\n def save_model(self, nn_weight_name, save_path):\r\n self.actor.save_weights(os.path.join(save_path,nn_weight_name + \"_actor.h5\"))\r\n self.critic.save_weights(os.path.join(save_path,nn_weight_name + \"_critic.h5\"))\r\n\r\n# This is Agent(local) class for threading\r\nclass Agent(threading.Thread):\r\n def __init__(self, index, actor, critic, optimizer, env_name, discount_factor, action_size, state_size, action_space_lists,profiles_chronics,session):\r\n threading.Thread.__init__(self)\r\n\r\n self.states = []\r\n self.rewards = []\r\n self.actions = []\r\n\r\n self.index = index\r\n self.actor = actor\r\n self.critic = critic\r\n self.optimizer = optimizer\r\n self.env_name = env_name\r\n self.discount_factor = discount_factor\r\n self.action_size = action_size\r\n self.state_size = state_size\r\n self.session = session\r\n\r\n self.gen_action_list = action_space_lists[0]\r\n self.load_action_list = action_space_lists[1]\r\n self.line_or_action_list = action_space_lists[2]\r\n self.line_ex_action_list = action_space_lists[3]\r\n self.profiles_chronics = profiles_chronics\r\n\r\n # Thread interactive with environment\r\n def run(self):\r\n global episode\r\n episode = 0\r\n env = set_environement(self.index,self.env_name,self.profiles_chronics)\r\n self.action_space = env.helper_action_player\r\n while episode < EPISODES_train:\r\n state = env.reset()\r\n state_as_dict = copy.deepcopy(state)\r\n # state = copy.deepcopy(np.reshape(state.to_vect(), [1, self.state_size]))\r\n state = useful_state(state_as_dict,env.backend.prod_pu_to_kv)\r\n state = state.reshape([1,state.size])\r\n score = 0\r\n time_step = 0\r\n max_action = 0\r\n non_zero_actions = 0\r\n epsilon = 0.5\r\n while True:\r\n # Decaying epsilon greedy. Not the best one. This agent needs a better exploration strategy to help\r\n # it learn to perform well.\r\n if np.random.random() < epsilon*(1/(episode/400+1)):\r\n action_index = int(np.random.choice(self.action_size))\r\n epison_flag = True\r\n else:\r\n epison_flag = False\r\n if time_step%1 == 0:# or max(state_as_dict.rho)>0.75:\r\n action_index = self.get_action(state_as_dict,state)\r\n else:\r\n action_index = 0\r\n\r\n action = self.create_action_dict(self.gen_action_list, self.load_action_list, self.line_or_action_list, self.line_ex_action_list, action_index, episode, flag=1)\r\n\r\n # print(action)\r\n\r\n next_state, reward, done, flag = env.step(action)\r\n state_as_dict = copy.deepcopy(next_state)\r\n time_hour = state_as_dict.day*10000 + state_as_dict.hour_of_day * 100+ state_as_dict.minute_of_hour\r\n # next_state = np.reshape(next_state.to_vect(), [1, self.state_size]) if not done else np.zeros([1, self.state_size])\r\n next_state = useful_state(next_state,env.backend.prod_pu_to_kv)\r\n next_state = next_state.reshape([1,next_state.size])\r\n # next_state = observation_space.array_to_observation(next_state).as_minimalist().as_array()\r\n # score += (reward-0.1*(next_state[1]*next_state[1]+next_state[3]*next_state[3])) # reducing the reward based on speed...\r\n score += reward if not done else -100*(1+np.sqrt(episode)/10)\r\n non_zero_actions += 0 if action_index==0 else 1\r\n # if flag == None:\r\n # self.memory(state, action, reward)\r\n # else:\r\n # score -= 10 if flag.is_empty else 0\r\n # self.memory(state, action, 0)\r\n self.memory(state, action_index, reward if not done else -100*(1+np.sqrt(episode)/10))\r\n\r\n state = copy.deepcopy(next_state) if not done else np.zeros([1, self.state_size])\r\n\r\n time_step += 1\r\n max_action = max(max_action,action_index)\r\n\r\n if done or time_step > time_step_end:\r\n if done:\r\n print(\"----STOPPED Thread:\", self.index, \"/ train episode: \", episode, \"/ instant reward\",int(reward), \"/ score : \", int(score),\r\n \"/ with final time:\", time_step, \"/ with final action\", action_index,\r\n \"/Random action: \",epison_flag,\"/ number of non-zero actions\", non_zero_actions, \"/ day_hour_min:\", time_hour)\r\n if time_step > time_step_end:\r\n print(\"End Thread:\", self.index, \"/ train episode: \", episode, \"/ instant reward\",int(reward), \"/ score : \", int(score),\r\n \"/ with final time:\", time_step, \"/ with final action\", action_index,\r\n \"/Random action: \",epison_flag,\"/ number of non-zero actions\", non_zero_actions, \"/ day_hour_min:\", time_hour)\r\n # global scores\r\n scores.append(score)\r\n # print(len(scores))\r\n # global episode\r\n episode += 1\r\n # if len(self.states) == 0:\r\n # k = 1\r\n self.train_episode(True) # max score = 80000\r\n break\r\n else:\r\n if time_step % 10 ==0:\r\n print(\"Continue Thread:\", self.index, \"/ train episode: \", episode, \"/ instant reward\",int(reward), \"/ score : \", int(score),\r\n \"/ with recent time:\", time_step, \"/ with recent action\", action_index,\"/Random action: \",epison_flag,\"/ number of non-zero actions\", non_zero_actions, \"/ max_action so far:\", max_action)\r\n self.train_episode(False)\r\n\r\n # In Policy Gradient, Q function is not available.\r\n # Instead agent uses sample returns for evaluating policy\r\n def discount_rewards(self, rewards, done=True):\r\n discounted_rewards = np.zeros_like(rewards)\r\n running_add = 0\r\n if not done:\r\n with self.session.as_default():\r\n with self.session.graph.as_default():\r\n running_add = self.critic.predict(np.reshape(self.states[-1], (1, self.state_size)))[0]\r\n for t in reversed(range(0, len(rewards))):\r\n running_add = running_add * self.discount_factor + rewards[t]\r\n discounted_rewards[t] = running_add\r\n return discounted_rewards\r\n\r\n # save <s, a ,r> of each step\r\n # this is used for calculating discounted rewards\r\n def memory(self, state, action, reward):\r\n self.states.append(state[0])\r\n act = np.zeros(self.action_size)\r\n act[action] = 1\r\n self.actions.append(act)\r\n self.rewards.append(reward)\r\n\r\n # update policy network and value network every episode\r\n def train_episode(self, done):\r\n discounted_rewards = self.discount_rewards(self.rewards, done)\r\n with self.session.as_default():\r\n with self.session.graph.as_default():\r\n values = self.critic.predict(np.array(self.states))[0]\r\n values = np.reshape(values, len(values))\r\n\r\n advantages = discounted_rewards - values\r\n\r\n with self.session.as_default():\r\n with self.session.graph.as_default():\r\n state_as_tensor = tf.compat.v1.convert_to_tensor(np.asarray(self.states))\r\n action_as_tensor = tf.compat.v1.convert_to_tensor(np.asarray(self.actions))\r\n advantage_as_tensor = tf.compat.v1.convert_to_tensor(np.asarray(advantages))\r\n # reshaped_state_as_tensor = tf.compat.v1.reshape(state_as_tensor,self.actor.input.shape.dims)\r\n self.optimizer[0]([state_as_tensor, action_as_tensor, advantage_as_tensor])\r\n self.optimizer[1]([state_as_tensor, discounted_rewards])\r\n self.states, self.actions, self.rewards = [], [], []\r\n\r\n\r\n def get_action(self, state_as_dict, state):\r\n with self.session.as_default():\r\n with self.session.graph.as_default():\r\n # Predict the action using the internal neural network\r\n policy = self.actor.predict(state,batch_size=1).flatten()\r\n\r\n # Select first 4 best possible actions from the neural nets.\r\n policy_chosen_list = np.random.choice(self.action_size, 4, p=policy)\r\n\r\n # Simulate the impact of these actions and pick the best action that maximizes the reward.\r\n # (one-step lookahead).\r\n action_index = policy_chosen_list[0]\r\n action = self.create_action_dict(self.gen_action_list, self.load_action_list, self.line_or_action_list, self.line_ex_action_list, action_index, episode, flag=0)\r\n obs_0, rw_0, done_0, _ = state_as_dict.simulate(action)\r\n\r\n action_index = policy_chosen_list[1]\r\n action = self.create_action_dict(self.gen_action_list, self.load_action_list, self.line_or_action_list, self.line_ex_action_list, action_index, episode, flag=0)\r\n obs_1, rw_1, done_1, _ = state_as_dict.simulate(action)\r\n\r\n action_index = policy_chosen_list[2]\r\n action = self.create_action_dict(self.gen_action_list, self.load_action_list, self.line_or_action_list, self.line_ex_action_list, action_index, episode, flag=0)\r\n obs_2, rw_2, done_2, _ = state_as_dict.simulate(action)\r\n\r\n action_index = policy_chosen_list[3]\r\n action = self.create_action_dict(self.gen_action_list, self.load_action_list, self.line_or_action_list, self.line_ex_action_list, action_index, episode, flag=0)\r\n obs_3, rw_3, done_3, _ = state_as_dict.simulate(action)\r\n\r\n return policy_chosen_list[np.argmax([rw_0,rw_1,rw_2,rw_3])]\r\n\r\n def create_action_dict(self,gen_action_list, load_action_list, line_or_action_list, line_ex_action_list, action_index, episode, flag):\r\n action = self.action_space(\r\n {\"change_bus\": {\"generators_id\": gen_action_list[action_index], \"loads_id\": load_action_list[action_index],\r\n \"lines_or_id\": line_or_action_list[action_index],\r\n \"lines_ex_id\": line_ex_action_list[action_index]}})\r\n # if flag == 1:\r\n # print(\"_______________________________________________________________________________________________________\")\r\n # print(\"thread number \", self.index,\" Executed action index in environment step:\", action_index,\" at episode:\", episode)\r\n # # print(action)\r\n # print(\"_______________________________________________________________________________________________________\")\r\n # else:\r\n # print(\"_______________________________________________________________________________________________________\")\r\n # print(\"thread number \", self.index,\" Executed action index at simulate step:\", action_index,\" at episode:\", episode)\r\n # # print(action)\r\n # print(\"_______________________________________________________________________________________________________\")\r\n return action\r\n\r\n# def set_environement(start_id,env_name,profiles_chronics):\r\n# param = Parameters()\r\n# param.NO_OVERFLOW_DISCONNECTION = True\r\n#\r\n# env = make(env_name,chronics_path= profiles_chronics, reward_class=CombinedReward,param=param)\r\n# # Register custom reward for training\r\n# cr = env.reward_helper.template_reward\r\n# cr.addReward(\"overflow\", CloseToOverflowReward(), 50.0)\r\n# cr.addReward(\"game\", GameplayReward(), 100.0)\r\n# cr.initialize(env)\r\n#\r\n# # Debug prints\r\n# print(\"Debug prints --->:\")\r\n# print(\"Chronics location that being used:\", env.chronics_handler.path)\r\n# print(\"Grid location being used:\", env.init_grid_path)\r\n# print(\"Reward class that is being used:\", env.rewardClass)\r\n# print(\"Action type class being used:\", env.actionClass)\r\n# print(\"Observation type class being used:\", env.observationClass)\r\n# print(\"Backend CSV file key names:\", env.names_chronics_to_backend)\r\n# print(\"Legal action class being used:\", env.legalActClass)\r\n# print(\"Voltage controller class being used:\", env.voltagecontrolerClass)\r\n#\r\n# if start_id != None:\r\n# env.chronics_handler.tell_id(start_id)\r\n# print(\"Thread number:\",start_id,\", ID of chronic current folder:\",env.chronics_handler.real_data.id_chron_folder_current)\r\n# return env\r\n\r\n# This below function reduces the size of the state space.\r\ndef useful_state(obs,value_multiplier):\r\n selected_obs = np.hstack((obs.topo_vect,obs.line_status))\r\n selected_obs = np.hstack((selected_obs,obs.load_p/100))#\r\n selected_obs = np.hstack((selected_obs,obs.load_q/100))\r\n selected_obs = np.hstack((selected_obs,obs.prod_p/100))\r\n selected_obs = np.hstack((selected_obs,obs.prod_v/value_multiplier))\r\n selected_obs = np.hstack((selected_obs,obs.rho))\r\n # selected_obs = np.hstack((selected_obs,obs.day))\r\n selected_obs = np.hstack((selected_obs,obs.hour_of_day/24))\r\n selected_obs = np.hstack((selected_obs,obs.minute_of_hour/60))\r\n # selected_obs = np.hstack((selected_obs,obs.day_of_week/7))\r\n return selected_obs\r\n\r\n\r\n\r\n\r\n" ]
[ [ "numpy.sqrt", "numpy.asarray", "tensorflow.python.keras.backend.placeholder", "numpy.zeros_like", "tensorflow.python.keras.backend.log", "numpy.hstack", "tensorflow.python.keras.backend.square", "numpy.reshape", "tensorflow.python.keras.backend.sum", "numpy.argmax", "numpy.zeros", "tensorflow.keras.models.Model", "numpy.random.choice", "tensorflow.keras.layers.Dense", "tensorflow.python.keras.backend.stop_gradient", "numpy.array", "tensorflow.compat.v1.ConfigProto", "numpy.random.random", "tensorflow.compat.v1.disable_v2_behavior", "tensorflow.compat.v1.global_variables_initializer", "tensorflow.compat.v1.compat.v1.convert_to_tensor", "tensorflow.keras.optimizers.Adam", "tensorflow.python.keras.backend.set_session", "tensorflow.keras.layers.Input" ] ]
VirtualEmbryo/lumen_network
[ "35b1dadccd087c9ef234f12c2735098b82890b34" ]
[ "network/network.py" ]
[ "# Library for the dynamics of a lumen network\n# The lumen are 2 dimensional and symmetric and connected with 1 dimensional tubes\n#\n# Created by A. Mielke, 2018\n# Modified by M. Le Verge--Serandour on 8/04/2019\n\n\"\"\"\n network.py conf.init\n \n Defines the class network and associated functions\n \n Imports\n -------\n Libraries : numpy, os, math\n \n Created by A. Mielke\n Modified by H. Turlier on 8/06/2018\n Modified by M. Le Verge--Serandour on 8/04/2019\n\"\"\"\n\nimport numpy as np\nimport math\nimport os\n\nclass network:\n\n def __init__(self, network_folder, out_path, t_step, tube_radius = 0.01, friction = 1, swelling = False, swelling_rate=0., save_area_dat=False):\n \"\"\"\n Initialization of the object network\n All properties needed for the simulation are read and initialized\n \n Input\n -----\n network_folder : str\n \n out_path : str, path-like\n \n t_step : float\n Time step of the simulation. Note that if the simulation is adaptative, this time step will change.\n tube_radius : float, optional, default = 0.01\n Radius of the tube connecting lumens. Define the condition for empty lumens.\n friction : float, optional, default = 1\n Friction constant for the fluid circulating through pipes.\n swelling : bool, optional, default = False\n Swelling option for the simulation. True if swelling is included, False otherwise.\n swelling_rate : float, optional, default = 0.\n Swelling rate value in case the swelling is considered. Make sure the rate is not to big to avoid non-converging simulations.\n save_area_dat : bool, optional, default = False\n Save area option. True if areas are saved in area.dat, False otherwise.\n \"\"\"\n self.network_folder = network_folder\n \n # Reading properties of the lumen\n self.gamma_lumen, self.gamma_contact, self.area = np.loadtxt(os.path.join(network_folder, 'lumen.dat'), dtype = float, usecols = [0,2,3], unpack = True)\n \n\n # Reading links between two lumen\n self.lumen_lumen = self.read_lumen_lumen(os.path.join(network_folder, 'lumen_lumen.dat'))\n \n # Reading links between bridge and lumen\n self.bridge_lumen, self.num_bridges = self.read_bridge_lumen(os.path.join(network_folder, 'bridge_lumen.dat'))\n\n # Reading links between two bridges\n self.bridge_bridge, self.num_bridges = self.read_bridge_bridge(os.path.join(network_folder, 'bridge_bridge.dat'), self.num_bridges)\n\n # Surface tension ratio\n self.alpha = self.gamma_contact/(2*self.gamma_lumen)\n self.delta = np.full(len(self.alpha), 1) # Possibility of asymmetric lumen is not included\n \n # Resistances\n self.tube_radius = tube_radius # Radius of the tube connecting the lumen and the bridges\n self.friction = friction # Friction coefficient; friction * length = resistance\n \n # Opening angle of the lumen (angle between curvature and tube)\n self.theta = self.set_theta()\n # Area factor for expressing the pressure in terms of the area instead of the radius\n self.area_factor = self.set_area_factor()\n\n\n # Ending time: time at which only one lumen is remaining\n self.end_time = 0\n # Time step for the output of the area evolution\n self.time_step = t_step\n\n # Creating output file for the area evolution, events, error messages\n self.save_area(start = True, out_path = out_path)\n self.save_event('', start = True, out_path = out_path)\n self.save_error('', start = True, out_path = out_path)\n \n # Area distribution after only one lumen is remaining\n self.final_area = []\n \n # Current time step of the simulation\n self.current_time = 0\n \n # List of empty lumen (area < tube_radius **2)\n self.empty_list = np.zeros(len(self.alpha))\n\n # Swelling\n self.swelling_bool = swelling\n self.swelling_rate = swelling_rate\n \n # Save area\n self.save_area_dat = save_area_dat\n\n############################################################################################################################\n########################################################## Dynamics ########################################################\n############################################################################################################################\n\n def flux(self, t, state):\n \"\"\"\n Determines the flux/ area change for each lumen of the network, main function of network.py\n \n Input\n -----\n self : network object\n Needs to be called by a class object\n t : float\n Actual time step (not needed for the calculation of the flux, but required for the used integration method in network_simulation.py\n state : float array\n The current area of the lumens\n \n Returns\n -------\n flux : float array\n Contains the area change for each lumen in dt\n \n \"\"\"\n # Initialization of the array containing the area change (index == lumen ID)\n flux = []\n self.current_time = t\n for i in range(len(self.alpha)):\n flux.append(0)\n \n # If only one lumen remains -> End of simulation, flux is zero (needed as for the integration method used, no dynamic stop is possible)\n if(np.sum(self.empty_list) >= len(self.alpha) - 1):\n if(self.end_time == 0):\n # Setting the end time for the output file area.log\n self.end_time = t\n \n # more than one lumen remaining: calculation of the flux\n else:\n \n # Adapting network to new state: Empty lumen are removed and graph is reconnected\n self.area = state\n self.remove_empty_lumen()\n \n # Area change between directly connected lumen\n flux = self.flux_lumen(flux)\n \n # Calculating artificial pressure at each bridge; linear system of equations, with flux(bridge) = 0, the bridge does not gain or loose area\n pressure_bridges = self.pressure_bridges()\n \n # Area change between lumen-bridges\n flux = self.flux_bridges(flux, pressure_bridges)\n \n # Area change due to swelling\n if self.swelling_bool :\n flux = self.flux_swelling(flux)\n \n # Saving area for the time step given in the configuration file\n if self.save_area_dat :\n self.save_area()\n \n self.t_old = t\n \n \n if(np.abs(np.sum(flux)) > self.tube_radius ** 2):\n error = 'total flux is non-zero: total flux = %f' % (np.sum(flux))\n self.save_error(error)\n\n return flux\n\n def flux_lumen(self,flux):\n \"\"\"\n Determines the flux/ area change for each lumen due to the connection between lumen and lumen\n \n Input\n -----\n self network object\n needs to be called by a class object\n flux float array\n vector containing the area change for each lumen; index = lumen ID\n \n Returns\n -------\n flux float array\n area changes due to lumen-lumen connection added to the vector passed\n \"\"\"\n \n # for each connection between two lumen\n for line in range(len(self.lumen_lumen)):\n lumen_1 = int (self.lumen_lumen[line][0]) # first lumen\n lumen_2 = int (self.lumen_lumen[line][1]) # second lumen\n # flux from lumen 2 to lumen 1\n fl = (self.pressure(lumen_2) - self.pressure(lumen_1))*self.friction/self.lumen_lumen[line][2]\n flux[lumen_1] += fl\n flux[lumen_2] -= fl\n return flux\n \n def pressure_bridges(self):\n \"\"\"\n Determines the pressure at each bridge\n for each bridge the total flux is 0, meaning that the bridge does not gain or loose area\n this gives a linear equation system, which can be solved\n The connections are taken from the files bridge_lumen.dat and bridge_bridge.dat\n For Information about the equations see the documentation to the code\n \n Input\n -----\n self : network object\n Needs to be called by a class object\n \n Returns\n -------\n pressure_bridges : float array\n Pressure at each bridge\n \"\"\"\n \n R_sum = np.zeros(self.num_bridges, dtype = float) # sum of the resistences around one bridge\n P_over_R_sum = np.zeros(self.num_bridges, dtype = float) # sum of pressure over resistance between one bridge and all directly connected lumen\n matrix_bridges = np.zeros([self.num_bridges, self.num_bridges], dtype= float) # matrix to calculate the pressure at each bridge\n \n # For each connection between bridge and lumen\n for line in self.bridge_lumen:\n bridge = int(line[0])\n lumen = int(line[1])\n R_sum[bridge] += 1./line[2]*self.friction\n P_over_R_sum[bridge] += self.pressure(lumen)/line[2]*self.friction\n \n # For each connection between bridge and bridge\n for line in self.bridge_bridge:\n bridge1 = int(line[0])\n bridge2 = int(line[1])\n matrix_bridges[bridge1][bridge2] = 1./line[2]*self.friction\n matrix_bridges[bridge2][bridge1] = 1./line[2]*self.friction\n R_sum[bridge1] += 1./line[2]*self.friction\n R_sum[bridge2] += 1./line[2]*self.friction\n for line in range(self.num_bridges):\n matrix_bridges[line][line] = -R_sum[line]\n \n # Solving linear problem with the pressure at each bridge as solution\n pressure_bridges = np.linalg.solve(matrix_bridges, -P_over_R_sum)\n \n return pressure_bridges;\n\n def flux_bridges(self, flux, pressure_bridges):\n \"\"\"\n Determines the flux/ area change for each lumen due to the connection between lumen and bridge\n \n Input\n -----\n self : network object\n Needs to be called by a class object\n \n Returns\n -------\n flux : float array\n Area changes due to bridge-lumen connection added to the vector passed\n \"\"\"\n \n # Area change in one bridge; should be 0; calculated as control value\n flux_bridge = np.zeros(self.num_bridges, dtype = float)\n \n # For each connection between bridge and bridge\n for line in self.bridge_bridge:\n bridge1 = int(line[0])\n bridge2 = int(line[1])\n fb = (pressure_bridges[bridge2] - pressure_bridges[bridge1])*self.friction/line[2]\n flux_bridge[bridge1] += fb\n flux_bridge[bridge2] -= fb\n \n # For each connection between bridge and lumen\n for line in self.bridge_lumen:\n bridge = int(line[0])\n lumen = int(line[1])\n fl = (pressure_bridges[bridge] - self.pressure(lumen))*self.friction/line[2]\n flux[lumen] += fl\n flux_bridge[bridge] -= fl\n\n for i in range(len(flux_bridge)):\n if (np.abs(flux_bridge[i]) > self.tube_radius ** 2):\n error = 'total flux of bridge %d is non-zero: total flux = %f' % (i,flux_bridge[i])\n self.save_error(error)\n return flux\n\n\n def flux_swelling(self, flux) :\n \"\"\"\n Determines the flux/ area change for each lumen due to sewlling\n\n Input\n -----\n self : network object\n Needs to be called by a class object\n \n Returns\n -------\n flux : float array\n Area changes due to bridge-lumen connection added to the vector passed \n \"\"\"\n \n # for each lumen (lumen is the index of the lumen's area)\n for lumen in range(len(self.area)) :\n # if not empty\n if not self.area[lumen] < 2*self.tube_radius ** 2 :\n # then add the swelling contribution\n flux[lumen] += self.swelling(lumen)\n \n return flux\n\n############################################################################################################################\n###################################################### Removing Functions #####################################################\n############################################################################################################################\n\n def remove_empty_lumen(self):\n \"\"\"\n Determines and removes empty lumen\n Calls a function to obtain a list of empty lumen and passes the list to a function to remove them and reconnect the network\n \n Input\n -----\n self : network object\n Needs to be called by a class object\n \n Returns\n -------\n no return\n \"\"\"\n \n empty_lumen_list = []\n # Creating a list of empty lumen\n empty_lumen_list = self.get_empty_lumen()\n # Removing empty lumen and reconnecting the network\n if (len(empty_lumen_list) > 0 ):\n event = 'empty lumen: ' + ' '.join(map(str, empty_lumen_list))\n #print event\n self.save_event(event)\n self.remove_lumen(empty_lumen_list)\n return;\n \n\n def remove_lumen(self, lumen_to_remove):\n \"\"\"\n Removes the lumen that are passed and connects the neighbors of these lumen\n \n Input\n -----\n self : network object\n Needs to be called by a class object\n lumen_to_remove : int list\n List of lumen to be removed\n \n Returns\n -------\n no return\n \"\"\"\n \n # For each lumen that has to be removed\n for lumen in lumen_to_remove:\n neighbours = self.get_neighbours(lumen) # List of connected lumen\n bridges = self.get_bridges(lumen) # List of connected bridges\n self.save_event('lumen ' + str(lumen) + ' neighbours ' + str(neighbours))\n self.save_event('lumen ' + str(lumen) + ' bridges ' + str(bridges))\n # Lumen had two connections, this means that it disappears and the two connected parts get directly connected, the resistance for the new link is the sum of the resistance of the two previous connections\n test=True\n if(len(neighbours) + len(bridges) == 2):\n # Lumen was connected to two lumen -> new connection between lumen and lumen\n if(len(neighbours) == 2):\n self.create_link([neighbours[0][0], neighbours[1][0], neighbours[0][1] + neighbours[1][1]])\n #print 'lumen_lumen connexion (' + str(neighbours[0][0]) + ', ' + str(neighbours[1][0]) + ')'\n # Lumen was connected to a lumen and a bridge -> new connection between lumen and bridge\n if(len(neighbours) == 1 and len(bridges)==1):\n self.create_bridge_lumen([bridges[0][0], neighbours[0][0], bridges[0][1] + neighbours[0][1]])\n #print 'lumen_bridge connexion (' + str(bridges[0][0]) + ', ' + str(neighbours[0][0]) + ')'\n # Lumen was connected to two bridges -> new connection between bridge and bridge\n if(len(bridges)==2):\n self.create_bridge_bridge([bridges[0][0], bridges[1][0], bridges[0][1] + bridges[1][1]])\n #print 'bridge_bridge connexion (' + str(bridges[0][0]) + ', ' + str(bridges[1][0]) + ')'\n \n self.create_bridge(neighbours, bridges, lumid=lumen)\n \n # Lumen had more than two connections -> becomes a bridge, the resistances remain the same but the connections are changed to connections to a bridge\n if(len(neighbours) + len(bridges) > 2):\n self.create_bridge(neighbours, bridges, lumid=lumen)\n return;\n\n\n def remove_link(self, lumen_1, lumen_2):\n \"\"\"\n Removes a connection between two lumen\n \n Input\n -----\n self : network object\n Needs to be called by a class object\n lumen_1 : int\n First lumen of the connection\n lumen_2 : \n Second lumen of the connection\n \n Returns\n -------\n no return\n \"\"\"\n # Due to data structure first lumen must be smaller than second lumen\n if(lumen_1 > lumen_2):\n n = lumen_1\n lumen_1 = lumen_2\n lumen_2 = n\n\n # Find connection in lumen_lumen file and remove it\n line = 0\n # For each line in lumen_lumen until connection is found\n while (line < len(self.lumen_lumen)):\n # If connection is found removing it\n if(self.lumen_lumen[line][0] == lumen_1 and self.lumen_lumen[line][1] == lumen_2):\n \n event = 'link lumen %d to lumen %d removed' % (lumen_1, lumen_2)\n #print event\n self.save_event(event)\n \n link = [lumen_1, lumen_2, self.lumen_lumen[line][2]]\n self.lumen_lumen.remove(link)\n\n break;\n # Look at next line\n else: line += 1\n\n\n\n############################################################################################################################\n###################################################### Get Functions #####################################################\n############################################################################################################################\n\n def get_empty_lumen(self):\n \"\"\"\n Gets the IDs of the empty lumen\n Empty means that the area is smaller than the tube_radius^2\n \n Input\n -----\n self : network object\n Needs to be called by a class object\n \n Returns\n -------\n empty_lumen_list : int list\n Contains the IDs of the empty lumens\n \"\"\"\n\n empty_lumen_list = []\n # For each lumen ID\n for i in range(len(self.area)):\n # If area is smaller than the treshhold\n if(self.area[i] < self.tube_radius ** 2 and self.empty_list[i] == 0):\n self.empty_list[i] = 1\n self.area[i] = 0\n empty_lumen_list.append(i)\n return empty_lumen_list\n\n\n def get_neighbours(self, lumen):\n \"\"\"\n Gets the lumen that are directly connected to the lumen passed on and deletes the connections\n \n Input\n -----\n self : network object\n Needs to be called by a class object\n lumen : int\n ID of a lumen\n \n Returns\n -------\n neighbour_list : int list\n ID of all lumen that are directly connected to the lumen passed on\n \"\"\"\n neighbour_list = []\n line = 0\n # Going through links in lumen_lumen.dat\n while line < len(self.lumen_lumen) and self.lumen_lumen[line][0] < lumen :\n if self.lumen_lumen[line][1] == lumen :\n neighbour_list.append([self.lumen_lumen[line][0], self.lumen_lumen[line][2]])\n\n event = 'link lumen %d to lumen %d removed' % (self.lumen_lumen[line][0], lumen)\n self.save_event(event)\n \n link = [self.lumen_lumen[line][0], self.lumen_lumen[line][1], self.lumen_lumen[line][2]]\n self.lumen_lumen.remove(link)\n \n else : line += 1\n while line < len(self.lumen_lumen) and self.lumen_lumen[line][0] < lumen : \n line += 1\n while(line < len(self.lumen_lumen) and self.lumen_lumen[line][0] == lumen):\n neighbour_list.append([self.lumen_lumen[line][1], self.lumen_lumen[line][2]])\n\n event = 'link lumen %d to lumen %d removed' % (lumen, self.lumen_lumen[line][1])\n self.save_event(event)\n \n link = [self.lumen_lumen[line][0], self.lumen_lumen[line][1], self.lumen_lumen[line][2]]\n self.lumen_lumen.remove(link)\n\n return neighbour_list\n \n def get_bridges(self, lumen):\n \"\"\"\n Gets the bridges that are directly connected to the lumen passed on\n \n Input\n -----\n self : network object\n Needs to be called by a class object\n lumen : int\n ID of a lumen\n \n Returns\n -------\n neighbour_list : int list\n ID of all lumen that are directly connected to the lumen passed on\n \"\"\"\n bridge_list = []\n line = 0\n # Going through the links in bridge_lumen.dat\n while(line < len(self.bridge_lumen)):\n if (self.bridge_lumen[line][1] == lumen):\n bridge_list.append([self.bridge_lumen[line][0], self.bridge_lumen[line][2]])\n event = 'link bridge %d to lumen %d removed' % (self.bridge_lumen[line][0], lumen)\n self.save_event(event)\n \n self.bridge_lumen.remove(self.bridge_lumen[line])\n else: line += 1\n return bridge_list\n\n############################################################################################################################\n#################################################### Creating Functions ###################################################\n############################################################################################################################\n\n\n\n def create_link(self, link):\n \"\"\"\n Creates a link between two lumen in lumen_lumen.dat\n \n Input\n -----\n self : network object\n Needs to be called by a class object\n link : float array\n [ID lumen1, ID lumen2, length]\n \n Returns\n -------\n no return\n \"\"\"\n # no self-loops allowed\n if(len(link) == 4 and link[0] != link[1]):\n # Ensuring: lumen_1 < lumen_2\n if(link[0] < link[2]):\n lumen_1 = link[0]\n lumen_2 = link[1]\n else:\n lumen_1 = link[1]\n lumen_2 = link[0]\n length = link[2]\n line = 0\n # Finding line in lumen_lumen.dat, to keep the sorting\n while(line < len(self.lumen_lumen) and lumen_1 > self.lumen_lumen[line][0]): line += 1\n if(line < len(self.lumen_lumen) - 1):\n while(line < len(self.lumen_lumen) and lumen_2 > self.lumen_lumen[line][1] and lumen_1 == self.lumen_lumen[line][0]): line += 1\n\n # Creating the link in lumen_lumen.dat\n \n self.lumen_lumen.append([lumen_1,lumen_2, length])\n self.lumen_lumen.sort()\n \n event = 'link lumen %d to lumen %d created' % (lumen_1,lumen_2)\n self.save_event(event)\n return;\n\n def create_bridge_lumen(self, link):\n \"\"\"\n Creates a link between a lumen and a bridge in bridge_lumen.dat\n \n Input\n -----\n self : network object\n Needs to be called by a class object\n link : float array\n [ID bridge, ID lumen, length]\n \n Returns\n -------\n no return\n \"\"\"\n bridge = link[0]\n lumen = link[1]\n length = link[2]\n line = 0\n\n # Creating the link in bridge_lumen.dat\n self.bridge_lumen.append(link)\n \n self.bridge_lumen.sort()\n \n event = 'link bridge %d to lumen %d created' % (bridge,lumen)\n self.save_event(event)\n return;\n\n def create_bridge_bridge(self, link):\n \"\"\"\n Creates a link between two bridges in bridge_bridge.dat\n \n Input\n -----\n self : network object\n Needs to be called by a class object\n link : float array\n [ID bridge1, ID bridge2, length]\n \n Returns\n -------\n no return\n \"\"\"\n if(link[0] == link[1]): return;\n if(link[0] < link[1]):\n bridge_1 = link[0]\n bridge_2 = link[1]\n else:\n bridge_1 = link[1]\n bridge_2 = link[0]\n length = link[2]\n line = 0\n\n # Creating the link in bridge_bridge.dat\n self.bridge_bridge.append([bridge_1,bridge_2, length])\n \n self.bridge_bridge.sort()\n \n event = 'link bridge %d to bridge %d created' % (bridge_1,bridge_2)\n self.save_event(event)\n return;\n\n\n def create_bridge(self, lumen, bridge, lumid):\n \"\"\"\n Creates a new bridge connected with the lumen and bridges passed on\n \n Input\n -----\n self : network object\n Needs to be called by a class object\n lumen : int list\n [[lumen ID, length], [lumen ID, length],.....]\n lumen IDs to which the new bridge should be connected to\n bridge : int list\n [[bridge ID, length], [bridge ID, length],.....]\n bridge IDs to which the new bridge should be connected to\n \n Returns\n -------\n no return\n \"\"\"\n #####\n bridge_conversionfile = os.path.join(self.network_folder,'bridgesconversion.txt')\n \n # ID of the new bridge\n bridge_number = self.num_bridges\n # Bridge ID counter, contains the ID of the next new bridge\n self.num_bridges += 1\n event = 'new bridge %d' % (bridge_number) + ' (' + str(lumid) + ')'\n self.save_event(event)\n line = 0\n lumen.sort()\n bridge.sort()\n \n # For each lumen that should be connected to the new bridge\n for i in range(len(lumen)):\n new_link = [bridge_number, lumen[i][0], lumen[i][1]]\n # Create link in bridge_lumen.dat\n self.create_bridge_lumen(new_link)\n \n # For each lumen that should be connected to the new bridge\n for i in range(len(bridge)):\n new_link = [bridge[i][0], bridge_number, bridge[i][1]]\n # Create link in bridge_bridge.dat\n self.create_bridge_bridge(new_link)\n \n open(bridge_conversionfile, 'a').write(str(bridge_number) + ' ' + str(lumid)+ '\\n')\n return;\n\n\n############################################################################################################################\n################################ Geometric Functions for area and Pressure ###############################################\n############################################################################################################################\n\n def set_theta(self):\n \"\"\"\n Sets the angle theta\n Calculates the angle theta, angle between the lumen and the tube\n \n Input\n -----\n self : network object\n Needs to be called by a class object\n \n Returns\n -------\n theta : float list \n Theta value for each lumen\n \"\"\"\n theta = []\n \n for i in range(len(self.alpha)):\n \n #cos = (2*self.alpha[i]-(4*self.alpha[i]**2-self.delta[i]**2+1)/(4*self.alpha[i]))/self.delta[i] ## Old version, for assymmetric lumen\n #theta.append(math.acos(cos))\n \n theta.append(np.arccos(self.alpha[i]))\n \n return theta;\n \n def set_area_factor(self):\n \"\"\"\n Sets the area factor, needed to express the pressure in terms of the area instead of the curvature radius\n \n Input\n -----\n self : network object\n Needs to be called by a class object\n \n Returns\n -------\n area_factor : float list\n Area factor for each lumen\n \"\"\"\n area_factor = []\n for i in range(len(self.alpha)):\n area_factor.append(np.sqrt((2*self.theta[i]-np.sin(2*self.theta[i]))))\n return area_factor;\n \n def opening_radius(self, lumen):\n \"\"\"\n Calculates the length/2 parallel to the 'tube' where the membrane is not attached for a given lumen\n \n Input\n -----\n lumen : int\n ID of the lumen\n \n Returns\n -------\n radius : float\n Length/2 of the opening radius\n \"\"\"\n return np.sqrt(2*self.area[lumen]/(2*self.theta[lumen]-np.sin(2*self.theta[lumen])))*np.sin(self.theta[lumen])\n\n def get_area(self, lumen):\n \"\"\"\n Calculates the area in one half of the lumen (for symmetric lumen)\n \n Input\n -----\n lumen : int\n ID of the lumen\n \n Returns\n -------\n area : float\n Area/2 of the lumen\n \"\"\"\n area = self.area[lumen]\n return area\n\n def pressure(self,lumen):\n \"\"\"\n Calculates the pressure inside the lumen (for symmetric lumen)\n \n Input\n -----\n lumen : int\n ID of the lumen\n \n Returns\n -------\n pressure : float\n Pressure of the lumen\n \"\"\"\n \n area = self.get_area(lumen)\n # Avoid dividing by zero\n if(area < 0.1 * self.tube_radius**2 ):\n error = 'division by zero in pressure: lumen ID: %d' % (lumen)\n self.save_error(error)\n pressure = self.gamma_lumen[lumen]*self.area_factor[lumen]/np.sqrt(area)\n return pressure\n\n\n############################################################################################################################\n################################################# Reading Functions ########################################################\n############################################################################################################################\n\n def read_lumen_lumen(self, lumen_lumen_file):\n \"\"\"\n Reading the file with links between two lumens\n \n Input\n -----\n lumen_lumen_file : str\n File path to file with the links between two lumens\n \n Returns\n -------\n lumen_lumen : float list [lumen1, lumen2, length]\n Information about the links between two lumens\n \"\"\"\n \n if (os.path.getsize(lumen_lumen_file)>0): # If the file is not empty\n lumen_1, lumen_2 = np.loadtxt(lumen_lumen_file, dtype = int, usecols = [0,1], unpack = True)\n length = np.loadtxt(lumen_lumen_file, dtype = float, usecols = [2])\n lumen_lumen = np.column_stack([lumen_1, lumen_2, length]).tolist()\n \n else:\n lumen_lumen = []\n return lumen_lumen\n\n\n def read_bridge_lumen(self, bridge_lumen_file):\n \"\"\"\n Reading the file with links between bridge and lumen\n \n Input\n -----\n bridge_lumen_file : str\n File path to file with the links between bridge and lumen\n \n Returns\n -------\n bridge_lumen : float list [bridge, lumen, length]\n Information about the links between bridge and lumen\n num_bridges : int\n Number of bridge_lumen links\n \"\"\"\n \n with open(bridge_lumen_file, 'r') as f:\n lines = f.read().splitlines()\n last_line = lines[-1]\n if ('#' in last_line): # If the file is empty\n bridge_lumen = []\n num_bridges = 0 # number of existing bridges\n else:\n bridge, lumen = np.loadtxt(bridge_lumen_file, dtype = int, usecols = [0,1], unpack = True)\n length = np.loadtxt(bridge_lumen_file, dtype = float, usecols = [2])\n bridge_lumen = np.column_stack([bridge, lumen, length]).tolist()\n num_bridges = max(bridge)+1 # number of existing bridges\n return bridge_lumen, num_bridges\n\n def read_bridge_bridge(self, bridge_bridge_file, num_bridges):\n \"\"\"\n Reading the file with links between two bridge\n \n Input\n -----\n bridge_bridge_file : str\n File path to file with the links between two bridge\n \n Returns\n -------\n bridge_bridge : float list [bridge1, bridge2, length]\n Information about the links between two bridge\n num : int\n Number of bridge_bridge links\n \"\"\"\n with open(bridge_bridge_file, 'r') as f:\n lines = f.read().splitlines()\n last_line = lines[-1]\n if ('#' in last_line>0): # If the file is empty\n bridge_bridge = []\n num = num_bridges\n else:\n bridge1, bridge2 = np.loadtxt(bridge_bridge_file, dtype = int, usecols = [0,1], unpack = True)\n length = np.loadtxt(bridge_bridge_file, dtype = float, usecols = [2])\n bridge_bridge = np.column_stack([bridge1, bridge2, length]).tolist()\n if (max(bridge2)+1 > num_bridges): num = max(bridge2)+1\n\n return bridge_bridge, num\n\n############################################################################################################################\n################################################# Output functions #########################################################\n############################################################################################################################\n def save_event(self, event, start = False, out_path = ''):\n \"\"\"\n Saves each event in the output folder in the file event.dat\n Events like a lumen disappearing, reconnections in the graph\n \n Input\n -----\n event : str\n Message of the event\n start : boolean\n True: File is created\n False: the message is stored in the file\n Returns\n ------\n no return\n \"\"\"\n if(start):\n header_event = '# Saves each event during the simulation; event is a disappearing lumen, graph reconnection \\n'\n self.file_event = os.path.join(out_path, 'event.dat')\n fevent = open(self.file_event, 'w')\n fevent.write(header_event)\n fevent.close()\n else:\n fevent = open(self.file_event, 'a')\n fevent.write('%.5f' % self.current_time)\n fevent.write(' ')\n fevent.write(event)\n fevent.write('\\n')\n fevent.close()\n return;\n\n def save_error(self, error, start = False, out_path = ''):\n \"\"\"\n Saves errors in the output folder in the file error.dat\n Errors like volume loss\n \n Input\n -----\n error : string\n Message of the event\n start : boolean\n True: File is created\n False: the message is stored in the file\n Returns\n ------\n no return\n \"\"\"\n if(start):\n header_error = '# Saves each warning like volume loss \\n'\n self.file_error = os.path.join(out_path, 'error.dat')\n ferror = open(self.file_error, 'w')\n ferror.write(header_error)\n ferror.close()\n else:\n ferror = open(self.file_error, 'a')\n ferror.write('%.5f' % self.current_time)\n ferror.write(' ')\n ferror.write(error)\n ferror.write('\\n')\n ferror.close()\n return;\n\n\n def save_area(self, start = False, out_path = ''):\n \"\"\"\n Saves the volume evolution in the output folder in the file area.dat\n \n Input\n -----\n start : boolean\n True: File is created\n False: the message is stored in the file\n Returns\n ------\n no return\n \"\"\"\n if(start):\n header_volume = '# Saves the volume evolution of each lumen for the time step %f \\n' %(self.time_step)\n self.file_area = os.path.join(out_path, 'area.dat')\n farea = open(self.file_area, 'w')\n farea.write(header_volume)\n farea.close()\n self.t_old = 0\n else:\n farea = open(self.file_area, 'a')\n farea.write('%.5f' % self.current_time)\n farea.write(' ')\n farea.write(' '.join(map(str, self.area)))\n farea.write('\\n')\n farea.close()\n return;\n\n\n############################################################################################################################\n################################################# Swelling functions #######################################################\n############################################################################################################################\n\n\n def swelling(self, lumen) :\n \"\"\"\n self.swelling(lumen)\n \n Calculates the input flux for the area fo a given lumen, due to swelling.\n \n Input\n -----\n lumen : int\n Index of the lumen\n \n \"\"\"\n area = self.get_area(lumen)\n theta = self.theta[lumen]\n \n flux_swelling = self.swelling_rate * 4 * theta * np.sqrt(area)/ self.area_factor[lumen]\n #print flux_swelling\n return flux_swelling\n" ]
[ [ "numpy.linalg.solve", "numpy.sqrt", "numpy.abs", "numpy.arccos", "numpy.sin", "numpy.column_stack", "numpy.zeros", "numpy.sum", "numpy.loadtxt" ] ]
clixyz/droidbot
[ "e222af95b1e93f97625c862bbdeed04c0f78b827" ]
[ "droidbot/input_policy2.py" ]
[ "import logging\nimport collections\nimport copy\nimport logging\nimport random\nimport time\nimport math\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.utils.rnn import pad_sequence\n\nfrom .input_event import KeyEvent, IntentEvent, TouchEvent, UIEvent, KillAppEvent\nfrom .input_policy import UtgBasedInputPolicy\n\nlogging.basicConfig(level=logging.INFO, format=\"%(asctime)s %(name)-12s %(levelname)-8s %(message)s\")\nDEBUG = True\nACTION_INEFFECTIVE = 'ineffective'\n\nCLOSER_ACTION_ENCOURAGEMENT = 0.01\nRANDOM_EXPLORE_PROB = 0.4\nN_ACTIONS_TRAINING = 32\n\nMAX_NUM_STEPS_OUTSIDE = 3\nMAX_NUM_STEPS_OUTSIDE_KILL = 5\nMAX_NAV_STEPS = 10\n\n\nclass UIEmbedLSTM(nn.Module):\n def __init__(self):\n super().__init__()\n self.text_encoder = TextEncoder(method='bert')\n input_size = 18 + self.text_encoder.embed_size\n embed_size = 100\n output_size = 50\n self.lstm = nn.LSTM(\n input_size=input_size,\n hidden_size=int(embed_size/2),\n num_layers=2,\n batch_first=True,\n bidirectional=True\n )\n self.fc = nn.Linear(embed_size, output_size)\n # self.fc = nn.Linear(input_size, output_size)\n\n def encode_state(self, state, views):\n return torch.stack([self._encode_view(state, view) for view in views])\n\n def _encode_view(self, state, view):\n # print(view)\n view_children = view['children'] if 'children' in view else []\n is_parent = 1 if len(view_children) > 0 else -1\n view_text = view['text'] if 'text' in view else None\n is_text = 1 if view_text and len(view_text) > 0 else -1\n enabled = 1 if 'enabled' in view and view['enabled'] else -1\n visible = 1 if 'visible' in view and view['visible'] else -1\n clickable = 1 if 'clickable' in view and view['clickable'] else -1\n long_clickable = 1 if 'long_clickable' in view and view['long_clickable'] else -1\n checkable = 1 if 'checkable' in view and view['checkable'] else -1\n checked = 1 if 'checked' in view and view['checked'] else -1\n selected = 1 if 'selected' in view and view['selected'] else -1\n editable = 1 if 'editable' in view and view['editable'] else -1\n is_password = 1 if 'is_password' in view and view['is_password'] else -1\n scrollable = 1 if 'scrollable' in view and view['scrollable'] else -1\n screen_w = state.width\n screen_h = state.height\n [[l,t], [r,b]] = view['bounds'] if 'bounds' in view else [[0,0], [0,0]]\n l, r, t, b = l/screen_w, r/screen_w, t/screen_h, b/screen_h\n view_w = abs(l - r)\n view_h = abs(t - b)\n size = view_w * view_h\n wh_ratio = view_w / (view_h + 0.0001)\n wh_ratio = min(wh_ratio, 10)\n text_emb = self.text_encoder.encode(view_text)\n encoding = np.concatenate([np.array([\n is_parent, is_text, is_password, visible,\n l, r, t, b, size, wh_ratio,\n enabled, checked, selected,\n clickable, long_clickable, checkable, editable, scrollable\n ]), text_emb])\n return torch.Tensor(encoding)\n\n def forward(self, state_encs):\n state_encs = pad_sequence(state_encs, batch_first=True)\n emb, _ = self.lstm(state_encs)\n return F.normalize(self.fc(emb))\n # return F.normalize(self.fc(x))\n\n\nclass TextEncoder:\n def __init__(self, method='spacy'):\n self.method = method\n self.embed_size = -1\n if method == 'spacy':\n import spacy\n self.nlp = spacy.load(\"en_core_web_md\")\n self.embed_size = 300\n if method == 'bert':\n from transformers import BertTokenizer, BertModel\n from torch.nn import TransformerEncoder, TransformerEncoderLayer\n self.tokenizer = BertTokenizer.from_pretrained('bert-base-multilingual-cased')\n self.text_encoder = BertModel.from_pretrained('bert-base-multilingual-cased')\n self.embed_size = 768\n\n def encode(self, text):\n if not text:\n return np.zeros(self.embed_size)\n if self.method == 'spacy':\n doc = self.nlp(text)\n return doc.vector\n if self.method == 'bert':\n encoding = self.tokenizer([text], return_tensors='pt', padding=True, truncation=True)\n input_ids = encoding['input_ids']\n attention_mask = encoding['attention_mask']\n text_encoder_out = self.text_encoder(input_ids, attention_mask=attention_mask)\n text_emb = text_encoder_out['pooler_output'][0]\n return text_emb.detach().cpu().numpy()\n\n\nclass BertLayerNorm(nn.Module):\n def __init__(self, hidden_size, eps=1e-5):\n \"\"\"Construct a layernorm module in the TF style (epsilon inside the square root).\n \"\"\"\n super(BertLayerNorm, self).__init__()\n self.weight = nn.Parameter(torch.ones(hidden_size))\n self.bias = nn.Parameter(torch.zeros(hidden_size))\n self.variance_epsilon = eps\n\n def forward(self, x):\n u = x.mean(-1, keepdim=True)\n s = (x - u).pow(2).mean(-1, keepdim=True)\n x = (x - u) / torch.sqrt(s + self.variance_epsilon)\n return self.weight * x + self.bias\n\n\nclass SinusoidalPositionalEncoding(nn.Module):\n\n def __init__(self, d_model, pos_max=128):\n super().__init__()\n self.d_model = d_model\n self.pos_max = pos_max\n d_model = int(d_model / 4)\n pe = torch.zeros(pos_max, d_model)\n position = torch.arange(0, pos_max).unsqueeze(1)\n div_term = torch.exp((torch.arange(0, d_model, 2, dtype=torch.float) *\n -(math.log(10000.0) / d_model)))\n pe[:, 0::2] = torch.sin(position.float() * div_term)\n pe[:, 1::2] = torch.cos(position.float() * div_term)\n self.pe = pe\n\n def forward(self, pos_enc):\n l = pos_enc[:, 0]\n r = pos_enc[:, 1]\n t = pos_enc[:, 2]\n b = pos_enc[:, 3]\n l_emb, r_emb, t_emb, b_emb = self.pe[l], self.pe[r], self.pe[t], self.pe[b]\n pos_emb = torch.cat([l_emb, r_emb, t_emb, b_emb], dim=1)\n # print(f'pos_enc for {i},{j}: wh={w},{h}')\n return pos_emb\n\n\nclass AbsolutePositionalEncoding(nn.Module):\n def __init__(self, d_model, pos_max=128):\n super().__init__()\n self.pos_max = pos_max\n self.d_model = d_model\n nhid = d_model\n self.x_position_embeddings = nn.Embedding(self.pos_max, nhid)\n self.y_position_embeddings = nn.Embedding(self.pos_max, nhid)\n self.h_position_embeddings = nn.Embedding(self.pos_max, nhid)\n self.w_position_embeddings = nn.Embedding(self.pos_max, nhid)\n\n def forward(self, pos_enc):\n l_emb = self.x_position_embeddings(pos_enc[:, 0])\n r_emb = self.x_position_embeddings(pos_enc[:, 1])\n t_emb = self.y_position_embeddings(pos_enc[:, 2])\n b_emb = self.y_position_embeddings(pos_enc[:, 3])\n w_emb = self.w_position_embeddings(pos_enc[:, 4])\n h_emb = self.h_position_embeddings(pos_enc[:, 5])\n pos_emb = l_emb + r_emb + t_emb + b_emb + w_emb + h_emb\n return pos_emb\n\n\nclass UIEmbedTransformer(nn.Module):\n\n def __init__(self, nhid=64, nhead=2, nlayers=2, dropout=0.8):\n super().__init__()\n self.model_type = 'Transformer'\n # nhid must be divided by 8 if using sinusoidal positional encoding\n from torch.nn import TransformerEncoder, TransformerEncoderLayer\n self.pos_max = 128\n self.text_encoder = TextEncoder(method='bert')\n dim_feedforward = 256\n encoder_layers = TransformerEncoderLayer(nhid, nhead, dim_feedforward, dropout)\n self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers)\n self.meta2hid = nn.Linear(12, nhid)\n self.text2hid = nn.Linear(self.text_encoder.embed_size, nhid)\n self.pos2hid = AbsolutePositionalEncoding(d_model=nhid, pos_max=self.pos_max)\n self.layer_norm = BertLayerNorm(nhid)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, state_encs):\n state_encs, attn_mask = self.encode_state_batch(state_encs)\n output = self.transformer_encoder(state_encs, src_key_padding_mask=attn_mask)\n output = output.permute(1, 0, 2)\n return output\n\n def encode_state(self, state, views):\n meta_enc = torch.stack([self._encode_view_meta(state, view) for view in views])\n pos_enc = torch.stack([self._encode_view_pos(state, view) for view in views])\n text_enc = torch.stack([self._encode_view_text(state, view) for view in views])\n return meta_enc, pos_enc, text_enc\n\n def encode_state_batch(self, state_encs):\n embs = []\n for state_enc in state_encs:\n meta_enc, pos_enc, text_enc = state_enc\n # pos_enc = self.pos_encoder(src)\n meta_emb = self.meta2hid(meta_enc)\n pos_emb = self.pos2hid(pos_enc)\n text_emb = self.text2hid(text_enc)\n # emb = torch.cat([meta_emb, pos_emb, text_emb], dim=1)\n emb = meta_emb + pos_emb + text_emb\n emb = self.layer_norm(emb)\n emb = self.dropout(emb)\n embs.append(emb)\n embs_pad = pad_sequence(embs, batch_first=False)\n attn_mask = embs_pad.sum(axis=2).t() == 0\n return embs_pad, attn_mask\n\n def _encode_view_meta(self, state, view):\n # print(view)\n view_children = view['children'] if 'children' in view else []\n is_parent = 1 if len(view_children) > 0 else -1\n view_text = view['text'] if 'text' in view else None\n is_text = 1 if view_text and len(view_text) > 0 else -1\n enabled = 1 if 'enabled' in view and view['enabled'] else -1\n visible = 1 if 'visible' in view and view['visible'] else -1\n clickable = 1 if 'clickable' in view and view['clickable'] else -1\n long_clickable = 1 if 'long_clickable' in view and view['long_clickable'] else -1\n checkable = 1 if 'checkable' in view and view['checkable'] else -1\n checked = 1 if 'checked' in view and view['checked'] else -1\n selected = 1 if 'selected' in view and view['selected'] else -1\n editable = 1 if 'editable' in view and view['editable'] else -1\n is_password = 1 if 'is_password' in view and view['is_password'] else -1\n scrollable = 1 if 'scrollable' in view and view['scrollable'] else -1\n meta_enc = np.array([\n is_parent, is_text, is_password, visible,\n enabled, checked, selected,\n clickable, long_clickable, checkable, editable, scrollable\n ])\n return torch.Tensor(meta_enc)\n\n def _encode_view_pos(self, state, view):\n screen_w = state.width\n screen_h = state.height\n [[l,t], [r,b]] = view['bounds'] if 'bounds' in view else [[0,0], [0,0]]\n l, r, t, b = l/screen_w, r/screen_w, t/screen_h, b/screen_h\n if l > r:\n tmp = l\n l = r\n r = tmp\n if t > b:\n tmp = t\n t = b\n b = tmp\n l = max(0, min(1, l))\n r = max(0, min(1, r))\n t = max(0, min(1, t))\n b = max(0, min(1, b))\n\n pos_max = self.pos_max - 1\n l, r, t, b = int(pos_max*l), int(pos_max*r), int(pos_max*t), int(pos_max*b)\n w = abs(l - r)\n h = abs(t - b)\n return torch.LongTensor(np.array([l, r, t, b, w, h]))\n\n def _encode_view_text(self, state, view):\n view_text = view['text'] if 'text' in view else None\n emb = self.text_encoder.encode(view_text)\n return torch.Tensor(emb)\n\n\nclass Memory:\n def __init__(self, utg, app):\n self.utg = utg\n self.app = app\n self.known_states = collections.OrderedDict()\n self.known_transitions = collections.OrderedDict()\n self.known_structures = collections.OrderedDict()\n self.model = UIEmbedTransformer()\n\n def _memorize_state(self, state):\n if state.get_app_activity_depth(self.app) != 0:\n return None\n if state.state_str not in self.known_states:\n views = state.views\n views_str = [view['view_str'] for view in views]\n state_enc = self.model.encode_state(state, views)\n embedder = self.model\n embedder.eval()\n with torch.no_grad():\n # state_encs = self.model.encode_state_batch([state_enc])\n views_emb = self.model.forward([state_enc])\n views_emb = views_emb.detach().cpu()[0]\n self.known_states[state.state_str] = {\n 'state': state,\n 'views': views,\n 'views_str': views_str,\n 'state_enc': state_enc,\n 'views_emb': views_emb\n }\n return self.known_states[state.state_str]\n\n def save_transition(self, action, from_state, to_state):\n if not from_state or not to_state:\n return\n from_state_info = self._memorize_state(from_state)\n to_state_info = self._memorize_state(to_state)\n if not isinstance(action, TouchEvent):\n return\n if action.view is None:\n return\n action_str = action.get_event_str(state=from_state)\n if action_str in self.known_transitions and self.known_transitions[action_str]['to_state'] == to_state:\n return\n if from_state_info is None:\n return\n view = action.view\n view_idx = from_state_info['views_str'].index(view['view_str'])\n action_target = ACTION_INEFFECTIVE \\\n if from_state.structure_str == to_state.structure_str \\\n else to_state.structure_str\n # TODO decide how to represent the effect of an action\n # action_effect = f'{from_state.structure_str}->{action_target}'\n action_effect = action_target\n self.known_transitions[action_str] = {\n 'from_state': from_state,\n 'to_state': to_state,\n 'action': action,\n 'view_idx': view_idx,\n 'action_effect': action_effect\n }\n\n def save_structure(self, state):\n structure_str = state.structure_str\n is_new_structure = False\n if structure_str not in self.known_structures:\n self.known_structures[structure_str] = []\n is_new_structure = True\n self.known_structures[structure_str].append(state)\n return is_new_structure\n\n def _select_transitions_for_training(self, size):\n if len(self.known_transitions) <= size:\n return list(self.known_transitions.keys())\n effect2actions = {}\n for k,v in self.known_transitions.items():\n action_effect = v['action_effect']\n if action_effect not in effect2actions:\n effect2actions[action_effect] = []\n effect2actions[action_effect].append(k)\n action_strs = []\n action_probs = []\n prob_per_effect = 1.0 / len(effect2actions)\n for effect in effect2actions:\n prob_per_action = prob_per_effect / len(effect2actions[effect])\n for action_str in effect2actions[effect]:\n action_strs.append(action_str)\n action_probs.append(prob_per_action)\n action_probs = np.array(action_probs) / sum(action_probs)\n selected_actions = np.random.choice(action_strs, size=size, replace=False, p=action_probs)\n return selected_actions\n\n def encode_action_pairs(self, action_strs=None):\n if action_strs is None:\n action_strs = list(self.known_transitions.keys())\n\n state_strs = [self.known_transitions[action_str]['from_state'].state_str for action_str in action_strs]\n state_encs = [self.known_states[state_str]['state_enc'] for state_str in state_strs]\n action_pairs = []\n for i, action_str1 in enumerate(action_strs):\n state_str1 = self.known_transitions[action_str1]['from_state'].state_str\n state_idx1 = state_strs.index(state_str1)\n view_idx1 = self.known_transitions[action_str1]['view_idx']\n for j, action_str2 in enumerate(action_strs[i+1:]):\n state_str2 = self.known_transitions[action_str2]['from_state'].state_str\n state_idx2 = state_strs.index(state_str2)\n view_idx2 = self.known_transitions[action_str2]['view_idx']\n action_effect1 = self.known_transitions[action_str1]['action_effect']\n action_effect2 = self.known_transitions[action_str2]['action_effect']\n # if action_effect1 == ACTION_INEFFECTIVE and action_effect2 == ACTION_INEFFECTIVE:\n # continue\n effect_same = 1 if action_effect1 == action_effect2 else 0\n action_pairs.append((state_idx1, view_idx1, state_idx2, view_idx2, effect_same))\n return state_encs, action_pairs\n \n def get_known_actions_emb(self):\n actions_emb = []\n for action_str in self.known_transitions:\n action_info = self.known_transitions[action_str]\n state_str = action_info['from_state'].state_str\n view_idx = action_info['view_idx']\n if state_str not in self.known_states:\n continue\n action_emb = self.known_states[state_str]['views_emb'][view_idx]\n actions_emb.append(action_emb)\n return torch.stack(actions_emb)\n\n @staticmethod\n def action_info_str(action_info):\n state_activity = action_info['from_state'].foreground_activity\n view_sig = action_info['action'].view['signature']\n action_effect = action_info['action_effect']\n return f'{state_activity}-{view_sig}-{action_effect}'\n\n def train_model(self):\n if len(self.known_transitions.keys()) < 2:\n return\n\n embedder = self.model\n optimizer = torch.optim.Adam(embedder.parameters(), lr=1e-3)\n n_iterations = 10\n\n def compute_loss(ele_embed, action_pairs):\n pos_emb_u = []\n pos_emb_v = []\n neg_emb_u = []\n neg_emb_v = []\n for state_idx1, view_idx1, state_idx2, view_idx2, effect_same in action_pairs:\n emb_u = ele_embed[state_idx1, view_idx1]\n emb_v = ele_embed[state_idx2, view_idx2]\n if effect_same:\n pos_emb_u.append(emb_u)\n pos_emb_v.append(emb_v)\n else:\n neg_emb_u.append(emb_u)\n neg_emb_v.append(emb_v)\n\n pos_score = 0\n neg_score = 0\n if len(pos_emb_u) > 0 and len(pos_emb_v) > 0:\n pos_emb_u = torch.stack(pos_emb_u)\n pos_emb_v = torch.stack(pos_emb_v)\n pos_score = torch.cosine_similarity(pos_emb_u, pos_emb_v)\n pos_score = F.logsigmoid(pos_score).mean()\n if len(neg_emb_u) > 0 and len(neg_emb_v) > 0:\n neg_emb_u = torch.stack(neg_emb_u)\n neg_emb_v = torch.stack(neg_emb_v)\n neg_score = torch.cosine_similarity(neg_emb_u, neg_emb_v)\n neg_score = F.logsigmoid(-neg_score).mean()\n loss = -pos_score - neg_score\n return loss\n\n def train():\n embedder.train()\n action_strs = self._select_transitions_for_training(size=N_ACTIONS_TRAINING)\n state_encs, action_pairs = self.encode_action_pairs(action_strs)\n ele_embed = embedder.forward(state_encs)\n\n loss = compute_loss(ele_embed, action_pairs)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n return loss.item(), len(action_pairs)\n\n for i in range(n_iterations):\n epoch_start_time = time.time()\n loss, n_pairs = train()\n elapsed = time.time() - epoch_start_time\n print(f'| iter: {i:3d} | time: {elapsed:6.2f}s | #pairs: {n_pairs:6d} | loss: {loss:8.4f}')\n\n # update embedding\n with torch.no_grad():\n embedder.eval()\n state_encs = [v['state_enc'] for k,v in self.known_states.items()]\n # state_encs_pad = pad_sequence(state_encs, batch_first=True)\n ele_embed = embedder(state_encs)\n ele_embed = ele_embed.detach().cpu()\n for i, (k,v) in enumerate(self.known_states.items()):\n self.known_states[k]['views_emb'] = ele_embed[i]\n\n def get_unexplored_actions(self, current_state):\n action_strs = set()\n structure_strs = set()\n self._memorize_state(current_state)\n for state_str, state_info in reversed(self.known_states.items()):\n state = state_info['state']\n if state.structure_str in structure_strs:\n continue\n structure_strs.add(state.structure_str)\n for action in state.get_possible_input():\n if not isinstance(action, TouchEvent):\n continue\n action_str = action.get_event_str(state=state)\n if action_str in action_strs:\n continue\n if self.utg.is_event_explored(action, state):\n continue\n action_strs.add(action_str)\n yield state, action\n\n def get_action_emb(self, state, action):\n state_str = state.state_str\n view_str = action.view['view_str']\n view_idx = self.known_states[state_str]['views_str'].index(view_str)\n action_emb = self.known_states[state_str]['views_emb'][view_idx]\n return action_emb\n\n\nclass MemoryGuidedPolicy(UtgBasedInputPolicy):\n def __init__(self, device, app, random_input):\n super(MemoryGuidedPolicy, self).__init__(device, app, random_input)\n self.logger = logging.getLogger(self.__class__.__name__)\n\n self.memory = Memory(utg=self.utg, app=self.app)\n self.num_actions_train = 10\n\n self._nav_steps = []\n self._num_steps_outside = 0\n\n def generate_event_based_on_utg(self):\n \"\"\"\n generate an event based on current UTG\n @return: InputEvent\n \"\"\"\n current_state = self.current_state\n try:\n self.memory.save_transition(self.last_event, self.last_state, current_state)\n except Exception as e:\n self.logger.warning(f'failed to save transition: {e}')\n import traceback\n traceback.print_exc()\n if self.action_count % self.num_actions_train == 0:\n self.memory.train_model()\n # self.logger.info(f'we have {len(self.memory.known_transitions)} transitions now')\n\n if self.last_event is not None:\n self.last_event.log_lines = self.parse_log_lines()\n # interested_apis = self.monitor.get_interested_api()\n # self.monitor.check_env()\n self.logger.debug(\"Current state: %s\" % current_state.state_str)\n\n nav_action = self.navigate(current_state)\n if nav_action:\n return nav_action\n self._nav_steps = [] # if navigation fails, stop navigating\n\n if current_state.get_app_activity_depth(self.app) < 0:\n # If the app is not in the activity stack\n start_app_intent = self.app.get_start_intent()\n self.logger.info(\"starting app\")\n return IntentEvent(intent=start_app_intent)\n elif current_state.get_app_activity_depth(self.app) > 0:\n # If the app is in activity stack but is not in foreground\n self._num_steps_outside += 1\n if self._num_steps_outside > MAX_NUM_STEPS_OUTSIDE:\n # If the app has not been in foreground for too long, try to go back\n if self._num_steps_outside > MAX_NUM_STEPS_OUTSIDE_KILL:\n stop_app_intent = self.app.get_stop_intent()\n go_back_event = IntentEvent(stop_app_intent)\n else:\n start_app_intent = self.app.get_start_intent()\n go_back_event = IntentEvent(intent=start_app_intent)\n self.logger.info(\"going back to the app\")\n return go_back_event\n else:\n # If the app is in foreground\n self._num_steps_outside = 0\n\n # if it is a new structure, try to go back first\n is_structure_new = self.memory.save_structure(current_state)\n if is_structure_new:\n self.logger.info(\"it is a new structure, going back\")\n return KeyEvent(name=\"BACK\")\n\n if self.action_count >= self.num_actions_train \\\n and len(self._nav_steps) == 0 \\\n and np.random.uniform() > RANDOM_EXPLORE_PROB:\n (target_state, target_action), candidates = self.pick_target(current_state)\n if target_state:\n # perform target action or navigate to target action\n if target_state.state_str == current_state.state_str:\n self.logger.info(f\"executing action selected from {len(candidates)} candidates\")\n return target_action\n self._nav_steps = self.get_shortest_nav_steps(current_state, target_state, target_action)\n nav_action = self.navigate(current_state)\n if nav_action:\n return nav_action\n self._nav_steps = [] # if navigation fails, stop navigating\n\n self.logger.info(\"trying random action\")\n possible_events = current_state.get_possible_input()\n possible_events.append(KeyEvent(name=\"BACK\"))\n random.shuffle(possible_events)\n return possible_events[0]\n\n def pick_target(self, current_state):\n state_action_pairs = list(self.memory.get_unexplored_actions(current_state))\n best_target = None, None\n best_score = -np.inf\n known_actions_emb = self.memory.get_known_actions_emb()\n if DEBUG:\n known_actions_str = [Memory.action_info_str(v) for k, v in self.memory.known_transitions.items()]\n scores = []\n for i, (state, action) in enumerate(state_action_pairs):\n action_emb = self.memory.get_action_emb(state, action)\n similarities = torch.cosine_similarity(action_emb.repeat((known_actions_emb.size(0), 1)), known_actions_emb)\n max_sim, max_sim_idx = similarities.max(0)\n score = -max_sim\n if state.state_str == current_state.state_str:\n score += CLOSER_ACTION_ENCOURAGEMENT # encourage actions in current state\n if DEBUG:\n action_info_str = f'{state.foreground_activity}-{action.view[\"signature\"]}'\n scores.append((i, score, action_info_str, similarities, action_emb))\n if score > best_score:\n best_score = score\n best_target = state, action\n return best_target, state_action_pairs\n\n def navigate(self, current_state):\n if self._nav_steps and len(self._nav_steps) > 0:\n nav_state, nav_action = self._nav_steps[0]\n self._nav_steps = self._nav_steps[1:]\n nav_action_ = self._get_nav_action(current_state, nav_state, nav_action)\n if nav_action_:\n self.logger.info(f\"navigating, {len(self._nav_steps)} steps left\")\n return nav_action_\n else:\n self.logger.warning(f\"navigation failed\")\n self.utg.remove_transition(self.last_event, self.last_state, nav_state)\n\n def _get_nav_action(self, current_state, nav_state, nav_action):\n # get the action similar to nav_action in current state\n try:\n if current_state.structure_str != nav_state.structure_str:\n return None\n if not isinstance(nav_action, UIEvent):\n return nav_action\n nav_view = nav_action.view\n nav_view_idx = nav_state.views.index(nav_view)\n new_view = current_state.views[nav_view_idx]\n new_action = copy.deepcopy(nav_action)\n new_action.view = new_view\n return new_action\n except Exception as e:\n self.logger.warning(f'exception during _get_nav_action: {e}')\n return nav_action\n\n def parse_log_lines(self):\n log_lines = self.device.logcat.get_recent_lines()\n filtered_lines = []\n app_pid = self.device.get_app_pid(self.app)\n # print(f'current app_pid: {app_pid}')\n for line in log_lines:\n try:\n seps = line.split()\n if int(seps[2]) == app_pid:\n filtered_lines.append(line)\n except:\n pass\n return filtered_lines\n\n def get_shortest_nav_steps(self, current_state, target_state, target_action):\n normal_nav_steps = self.utg.get_G2_nav_steps(current_state, target_state)\n restart_nav_steps = self.utg.get_G2_nav_steps(self.utg.first_state, target_state)\n normal_nav_steps_len = len(normal_nav_steps) if normal_nav_steps else MAX_NAV_STEPS\n restart_nav_steps_len = len(restart_nav_steps) + 1 if restart_nav_steps else MAX_NAV_STEPS\n if normal_nav_steps_len >= MAX_NAV_STEPS and restart_nav_steps_len >= MAX_NAV_STEPS:\n self.logger.warning(f'cannot find a path to {target_state.structure_str} {target_state.foreground_activity}')\n target_state_str = target_state.state_str\n # forget the unavailable state\n self.memory.known_states.pop(target_state_str)\n action_strs_to_remove = []\n for action_str in self.memory.known_transitions:\n action_from_state = self.memory.known_transitions[action_str]['from_state']\n action_to_state = self.memory.known_transitions[action_str]['to_state']\n if action_from_state.state_str == target_state_str or action_to_state.state_str == target_state_str:\n action_strs_to_remove.append(action_str)\n for action_str in action_strs_to_remove:\n self.memory.known_transitions.pop(action_str)\n return None\n elif normal_nav_steps_len > restart_nav_steps_len:\n nav_steps = [(current_state, KillAppEvent(app=self.app))] + restart_nav_steps\n else:\n nav_steps = normal_nav_steps\n return nav_steps + [(target_state, target_action)]\n\n\n# class InputPolicy2(object):\n# \"\"\"\n# This class is responsible for generating events to stimulate more app behaviour\n# \"\"\"\n#\n# def __init__(self, device, app, random_input=True):\n# self.logger = logging.getLogger(self.__class__.__name__)\n# self.device = device\n# self.app = app\n# self.random_input = random_input\n# self.utg = UTG(device=device, app=app, random_input=random_input)\n# self.input_manager = None\n# self.action_count = 0\n# self.state = None\n#\n# @property\n# def enabled(self):\n# if self.input_manager is None:\n# return False\n# return self.input_manager.enabled and self.action_count < self.input_manager.event_count\n#\n# def perform_action(self, action):\n# self.input_manager.add_event(action)\n# self.action_count += 1\n#\n# def start(self, input_manager):\n# \"\"\"\n# start producing actions\n# :param input_manager: instance of InputManager\n# \"\"\"\n# self.input_manager = input_manager\n# self.action_count = 0\n#\n# episode_i = 0\n# while self.enabled:\n# try:\n# episode_i += 1\n# self.device.send_intent(self.app.get_stop_intent())\n# self.device.key_press('HOME')\n# self.device.send_intent(self.app.get_start_intent())\n# self.state = self.device.current_state()\n# self.start_episode()\n# except KeyboardInterrupt:\n# break\n# except Exception as e:\n# self.logger.warning(f\"exception during episode {episode_i}: {e}\")\n# import traceback\n# traceback.print_exc()\n# continue\n#\n# @abstractmethod\n# def start_episode(self):\n# pass\n\n" ]
[ [ "torch.cat", "torch.zeros", "torch.nn.utils.rnn.pad_sequence", "torch.nn.Embedding", "torch.no_grad", "torch.nn.Dropout", "torch.ones", "torch.sqrt", "torch.nn.TransformerEncoder", "torch.arange", "numpy.zeros", "numpy.random.choice", "torch.nn.functional.logsigmoid", "torch.nn.Linear", "torch.nn.TransformerEncoderLayer", "torch.stack", "numpy.array", "torch.Tensor", "torch.cosine_similarity", "numpy.random.uniform" ] ]
ed-ortizm/anomaly
[ "87d0668133f0536532b9cd61c2a90fa998ec1ad3" ]
[ "src/anomaly/parallelReconstruction.py" ]
[ "\"\"\"process base parallelism to compute reconstruction anomaly scores\"\"\"\nimport itertools\nimport multiprocessing as mp\nfrom multiprocessing.sharedctypes import RawArray\n\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom anomaly.reconstruction import ReconstructionAnomalyScore\nfrom sdss.utils.managefiles import FileDirectory\nfrom autoencoders.ae import AutoEncoder\n\n###############################################################################\ndef to_numpy_array(array: RawArray, array_shape: tuple = None) -> np.array:\n \"\"\"Create a numpy array backed by a shared memory Array.\"\"\"\n\n array = np.ctypeslib.as_array(array)\n\n if array_shape is not None:\n return array.reshape(array_shape)\n\n return array\n\n\n###############################################################################\ndef init_shared_data(\n share_counter: mp.Value,\n share_wave: RawArray,\n share_observation: RawArray,\n data_shape: tuple,\n share_specobj_id: RawArray,\n share_train_id: RawArray,\n share_model_directory: str,\n share_output_directory: str,\n share_cores_per_worker: int,\n share_parser_name: str,\n share_parser_directory: str,\n) -> None:\n \"\"\"\n Initialize worker to train different AEs\n\n PARAMETERS\n\n share_counter:\n share_observation:\n data_shape:\n share_model_directory:\n share_output_directory:\n\n \"\"\"\n global counter\n global wave\n global observation\n global specobj_id\n global train_id\n\n global model_directory\n global output_directory\n\n global cores_per_worker\n\n global parser_name\n global parser_directory\n\n counter = share_counter\n wave = to_numpy_array(share_wave)\n\n observation = to_numpy_array(share_observation, data_shape)\n\n specobj_id = to_numpy_array(share_specobj_id)\n train_id = to_numpy_array(share_train_id)\n\n model_directory = share_model_directory\n output_directory = share_output_directory\n\n cores_per_worker = share_cores_per_worker\n\n parser_name = share_parser_name\n parser_directory = share_parser_directory\n\n\n###############################################################################\ndef compute_anomaly_score(\n metric: str,\n lines: list,\n velocity_filter: float,\n percentage: int,\n relative: bool,\n epsilon: float,\n) -> None:\n \"\"\"\n PARAMETERS\n metric:\n \"\"\"\n ###########################################################################\n # set the number of cores to use per model in each worker\n jobs = cores_per_worker\n config = tf.compat.v1.ConfigProto(\n intra_op_parallelism_threads=jobs,\n inter_op_parallelism_threads=jobs,\n allow_soft_placement=True,\n device_count={\"CPU\": jobs},\n )\n session = tf.compat.v1.Session(config=config)\n ###########################################################################\n # Define reconstruction function\n model = AutoEncoder(reload=True, reload_from=model_directory)\n reconstruct_function = model.reconstruct\n ###########################################################################\n # Define anomaly score class\n anomaly = ReconstructionAnomalyScore(\n reconstruct_function,\n wave,\n lines=lines,\n velocity_filter=velocity_filter,\n percentage=percentage,\n relative=relative,\n epsilon=epsilon,\n )\n\n # define name of score:\n # metric_filter_velocity --> has: rel50, noRel75, ...\n df_name = f\"{metric}\"\n\n have_to_filter = velocity_filter != 0\n\n if have_to_filter is True:\n\n df_name = f\"{df_name}_filter_{velocity_filter}Kms\"\n\n # define name of column that will contain the anomaly in the data_frame\n column_df_name = f\"{percentage}\"\n\n if relative is True:\n\n column_df_name = f\"rel{column_df_name}\"\n\n else:\n\n column_df_name = f\"noRel{column_df_name}\"\n\n # define name of array if score is saved\n score_name = f\"{df_name}_{column_df_name}\"\n ###########################################################################\n # Compute anomaly score\n with counter.get_lock():\n\n print(f\"[{counter.value}] Compute {score_name}\", end=\"\\r\")\n\n counter.value += 1\n\n score = anomaly.score(observation, metric)\n\n score_with_ids = np.hstack(\n (\n specobj_id.reshape(-1, 1),\n train_id.reshape(-1, 1),\n score.reshape(-1, 1),\n )\n )\n save_to = f\"{output_directory}/{df_name}\"\n FileDirectory().check_directory(save_to, exit_program=False)\n\n np.save(f\"{save_to}/{score_name}.npy\", score_with_ids)\n\n # save config file\n with open(f\"{parser_directory}/{parser_name}\", \"r\") as config_file:\n\n config = config_file.read()\n\n with open(f\"{save_to}/{parser_name}\", \"w\") as config_file:\n\n config_file.write(config)\n\n ###########################################################################\n session.close()\n\n\n###############################################################################\ndef get_grid(parameters: dict) -> itertools.product:\n \"\"\"\n PARAMETERS\n parameters:\n\n OUTPUT\n parameters_grid: iterable with the cartesian product\n of input parameters\n \"\"\"\n for key, value in parameters.items():\n\n if isinstance(value, list) is False:\n\n parameters[key] = [value]\n\n grid = itertools.product(\n parameters[\"metric\"],\n [parameters[\"lines\"]], # I need the whole list of lines\n parameters[\"velocity\"],\n parameters[\"percentage\"],\n parameters[\"relative\"],\n parameters[\"epsilon\"],\n )\n\n return grid\n" ]
[ [ "numpy.ctypeslib.as_array", "tensorflow.compat.v1.ConfigProto", "tensorflow.compat.v1.Session", "numpy.save" ] ]
crackedcd/Intern.MT
[ "36398837af377a7e1c4edd7cbb15eabecd2c3103" ]
[ "simple-tensorflow-demo/3.neural network/tf_3rd_3_test.py" ]
[ "import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n## 参数\n# 学习率, 太小则每次optimizer变化很小, 学习速度慢; 太大则可能导致过度学习, 最终结果不准确\nlearning_rate = 0.01\n# 隐藏层深度\ntraining_epochs = 2000\n# 打印的节点层\ndisplay_step = 50\n\n\n## 构造训练数据\n## numpy.asarray将list/turple转成矩阵\ntrain_X = np.asarray([3.3, 4.4, 5.5, 6.71, 6.93, 4.168, 9.779, 6.182, 7.59, 2.167, 7.042, 10.791, 5.313, 7.997, 5.654, 9.27, 3.1])\ntrain_Y = np.asarray([1.7, 2.76, 2.09, 3.19, 1.694, 1.573, 3.366, 2.596, 2.53, 1.221, 2.827, 3.465, 1.65, 2.904, 2.42, 2.94, 1.3])\n## shape得到矩阵每个维的大小, 这里是一维, 所以等同于len(train_X)\nn_samples = train_X.shape[0]\n\n# 绘图\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1) # 3个1分别代表, 将画布分拆成1行, 1列, 图画建立在第1块分拆的部分上.\nplt.plot(train_X, train_Y, 'bo', label='training data') # b是blue, o代表原点, -代表是直线, +代表星星\n#plt.legend()\n#plt.show()\n\n\n## 定义常量\nX = tf.placeholder(\"float\")\nY = tf.placeholder(\"float\")\n\n\n## 定义神经层\ndef add_layer(inputs, activation_function=None):\n\n ## 定义Weight和biases (使用numpy库生成正态分布随机数)\n weights = tf.Variable(np.random.randn(), name=\"weights\")\n biases = tf.Variable(np.random.randn(), name=\"biases\")\n\n ## 模拟的激励函数结果, X * weights + biases\n activation = tf.add(tf.multiply(X, weights), biases)\n\n if activation_function is None:\n outputs = activation\n else:\n outputs = activation_function(activation)\n return outputs\n\n\n## 定义隐藏层, 使用tensorflow自带的激励函数tf.nn.relu\nshadow = add_layer(X, activation_function=tf.nn.relu)\n#shadow = add_layer(X, activation_function=None)\n\n\n## 定义输出层\nprediction = add_layer(shadow, activation_function=None)\n\n\n## 优化每次的误差\n## (激励结果 - Y) ^ 2 / (2 * 矩阵大小)\n## tensorflow.reduce_sum 用于矩阵求和(对tensor的维度求和)\n'''\n根据tensorflow文档, ReductionTensorFlow provides several operations that you can use to perform common math computations that reduce various dimensions of a tensor.\nreduce_xxx, 都是把某一个维度上这一序列的数缩减到一个(求和/求平均值). 也即是使用reduction_indices参数来指定使用某个方法对输入的矩阵进行降维.\n对于二维矩阵输入, reduction_indices=0按列降维, reduction_indices=1按行降维.\n\n# 'x' is [[1, 1, 1]\n# [1, 1, 1]]\ntf.reduce_sum(x) ==> 6\ntf.reduce_sum(x, 0) ==> [2, 2, 2]\ntf.reduce_sum(x, 1) ==> [3, 3]\ntf.reduce_sum(x, 1, keep_dims=True) ==> [[3], [3]]\ntf.reduce_sum(x, [0, 1]) ==> 6\n\n# python console:\na = [1, 1, 1, 1, 1, 1]\nb = np.asarray(a)\nc = tf.reduce_sum(b)\nsess.run(tf.reduce_sum(b)) ==> 6\n'''\n## 这个算法到底是为什么?\ncost = tf.reduce_sum(tf.pow(prediction - Y, 2)) / (2 * n_samples)\n## GradientDescentOptimizer是梯度下降法的优化器, 可查阅\"最速下降法\".\noptimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\n\n## 初始化变量\ninit = tf.global_variables_initializer()\n\n## 进入Session\nwith tf.Session() as sess:\n sess.run(init)\n\n ## 开始训练\n for epoch in range(training_epochs):\n ## zip合并两个turple或list\n # a = [1, 2, 3]\n # b = [\"li\", \"xiong\", \"yu\"]\n # zip(a, b) ==> [(1, 'li'), (2, 'xiong'), (3, 'yu')] 结果是一个zip对象而不是list/turple\n for (x, y) in zip(train_X, train_Y):\n sess.run(optimizer, feed_dict={X: x, Y: y})\n\n ## 分步打印结果\n if epoch % display_step == 0:\n print(\"Epoch: %d, cost=%.9f\" % (epoch + 1, sess.run(cost, feed_dict={X: train_X, Y:train_Y})))\n # 逐次打印新的函数图象\n try:\n ax.lines.remove(lines[0])\n except Exception:\n pass\n prediction_Y = sess.run(prediction, feed_dict={X: train_X})\n lines = ax.plot(train_X, prediction_Y, 'r-', lw = 5)\n plt.pause(1)\n\n print(\"Done!\")\n print(\"cost=%.9f\" % sess.run(cost, feed_dict={X: train_X, Y:train_Y}))\n\n #plt.plot(train_X, sess.run(weights) * train_X + sess.run(biases), label='fitted line')\n\n" ]
[ [ "tensorflow.multiply", "tensorflow.pow", "numpy.asarray", "tensorflow.placeholder", "matplotlib.pyplot.plot", "tensorflow.global_variables_initializer", "tensorflow.train.GradientDescentOptimizer", "numpy.random.randn", "tensorflow.Session", "matplotlib.pyplot.pause", "matplotlib.pyplot.figure" ] ]
makersinchicago/socialraspi
[ "628f2555d4163e68fa97134c8507c3db77e93e7a" ]
[ "socialraspi.py" ]
[ "\"\"\"\n\nat boot, present prompt\n\nwait for user input\n\nat user input, record 1 minute of video and audio using picam\n\nafter recording is done, present prompt. user may play back video or record anew\n\nif the user is satisfied, they may press send to post the video to makersinchicago's twitter timeline, the chimakerfest's ig feed, and the chimakerfest facebook page.\n\nthe is notified that the posts have been uploaded and the prompt is presented for the next user.\n\nthere is a fourth button to enable a safe shutdown, it is located near the power switch.\n\n\"\"\"\n\nimport alsaaudio, wave, numpy\nimport os\nfrom picamera import PiCamera\nfrom time import sleep\nimport picamera.array\nfrom gpiozero import Button\nimport subprocess\n\nfrom keys import (\n image,\n)\n\nsnapButton = Button(27)\nvidButton = Button(23)\nexitButton = Button(17)\n\ntracktime = 2832\n\nwith picamera.PiCamera() as camera:\n camera.resolution = (3280, 2464)\n camera.rotation = 0\n camera.start_preview()\n while True:\n if snapButton.is_pressed:\n print(\"Pic Mode\")\n camera.capture(image)\n camera.stop_preview()\n import twitpic\n import igphoto\n camera.start_preview()\n elif vidButton.is_pressed:\n print(\"vid Mode\")\n camera.stop_preview()\n camera.resolution = (1080, 810)\n camera.rotation = 0\n camera.start_preview()\n inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE)\n inp.setchannels(1)\n inp.setrate(48000)\n inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)\n inp.setperiodsize(1024)\n camera.start_recording('/home/pi/Desktop/capture.h264', format='h264')\n w = wave.open('/home/pi/Desktop/audio.wav', 'w')\n w.setnchannels(1)\n w.setsampwidth(2)\n w.setframerate(48000)\n while tracktime > 0:\n tracktime -= 1\n l, data = inp.read()\n a = numpy.fromstring(data, dtype='int16')\n print(numpy.abs(a).mean())\n w.writeframes(data)\n camera.stop_recording()\n camera.stop_preview()\n cp = subprocess.run([\"ffmpeg -y -i /home/pi/Desktop/audio.wav -codec:a aac /home/pi/Desktop/audio.aac\"],shell=True)\n cp = subprocess.run([\"rm /home/pi/Desktop/capture.mp4\"],shell=True)\n cp = subprocess.run([\"MP4Box -add /home/pi/Desktop/capture.h264:fps=30 -add /home/pi/Desktop/audio.aac /home/pi/Desktop/capture.mp4\"],shell=True)\n cp = subprocess.run([\"rm /home/pi/Desktop/capture.h264\"],shell=True)\n cp = subprocess.run([\"rm /home/pi/Desktop/audio.wav\"],shell=True)\n cp = subprocess.run([\"rm /home/pi/Desktop/audio.mp3\"],shell=True)\n import twigvid\n camera.resolution = (3280, 2464)\n camera.rotation = 0\n camera.start_preview()\n elif exitButton.is_pressed:\n exit()\n else:\n print(\"x\")\n sleep(.1)\n" ]
[ [ "numpy.fromstring", "numpy.abs" ] ]
akeaveny/robo-gym
[ "9ad8cf2e7adf12062b1bc5e62afb2938f70d02a9" ]
[ "scripts/random_agent_sim.py" ]
[ "import gym\nfrom gym.wrappers import TimeLimit\nfrom gym.wrappers import FlattenObservation\n\nimport robo_gym\nfrom robo_gym.wrappers.exception_handling import ExceptionHandling\nfrom robo_gym.wrappers.flatten_action_space import FlattenAction\n\ntarget_machine_ip = 'localhost' # or other machine 'xxx.xxx.xxx.xxx'\n\nimport numpy as np\nimport pprint\n\n#####################\n### robo-gym\n#####################\n\n# robot = 'NoObstacleNavigationMir100Sim-v0'\n# robot = 'EndEffectorPositioningUR10Sim-v0'\n#\n# env = gym.make(robot, ip=target_machine_ip, gui=True)\n# env = ExceptionHandling(env)\n\n#####################\n### UWRT\n#####################\nimport config\n\nrobot = 'UWRTArmSim-v0'\n# robot = 'Gen3Lite2FArmEnv-v0'\n\nenv = FlattenAction(FlattenObservation(gym.make(robot, ip=target_machine_ip, gui=True,\n key_position=config.KEY_POSITION,\n key_orientation=config.KEY_ORIENTATION,\n max_steps=config.MAX_STEPS_PER_EPISODE)))\nenv = ExceptionHandling(env).env\n\n#####################\n#####################\npp = pprint.PrettyPrinter()\nnum_episodes = 10\n\nfor episode in range(num_episodes):\n print()\n print(f'Episode #{episode} Starting!')\n print()\n\n done = False\n initial_observation = env.reset()\n print('Initial Observation:')\n pp.pprint(initial_observation)\n steps = 0\n while not done:\n steps += 1\n # random step in the environment\n action = env.action_space.sample()\n observation, reward, done, info = env.step(np.array(action)) # need flatten action\n\n # print()\n # print('Action:')\n # pp.pprint(action)\n # print('Observation:')\n # pp.pprint(observation)\n # print('Info:')\n # pp.pprint(info)\n # print('Reward:')\n # pp.pprint(reward)\n\n if done:\n print()\n print(f'Episode #{episode} finished after {steps} steps!')\n print(f'Episode #{episode} exit condition was {info[\"sim\"][\"end_condition\"]}')\n print()\n\n break\n\n" ]
[ [ "numpy.array" ] ]
d9w/pyCGP
[ "8f23bda9d653b9def91e108e7fdad61c029178e1" ]
[ "test/test_functions.py" ]
[ "from pycgp import CGP\nfrom pycgp.cgpfunctions import *\nimport numpy as np\n\ndef rand_arg():\n return np.random.rand() * 2.0 - 1\n\ndef build_func_lib():\n return [CGP.CGPFunc(f_sum, 'sum', 2),\n CGP.CGPFunc(f_aminus, 'aminus', 2),\n CGP.CGPFunc(f_mult, 'mult', 2),\n CGP.CGPFunc(f_exp, 'exp', 2),\n CGP.CGPFunc(f_abs, 'abs', 1),\n CGP.CGPFunc(f_sqrt, 'sqrt', 1),\n CGP.CGPFunc(f_sqrtxy, 'sqrtxy', 2),\n CGP.CGPFunc(f_squared, 'squared', 1),\n CGP.CGPFunc(f_pow, 'pow', 2),\n CGP.CGPFunc(f_one, 'one', 0),\n CGP.CGPFunc(f_zero, 'zero', 0),\n CGP.CGPFunc(f_inv, 'inv', 1),\n CGP.CGPFunc(f_gt, 'gt', 2),\n CGP.CGPFunc(f_asin, 'asin', 1),\n CGP.CGPFunc(f_acos, 'acos', 1),\n CGP.CGPFunc(f_atan, 'atan', 1),\n CGP.CGPFunc(f_min, 'min', 2),\n CGP.CGPFunc(f_max, 'max', 2),\n CGP.CGPFunc(f_round, 'round', 1),\n CGP.CGPFunc(f_floor, 'floor', 1),\n CGP.CGPFunc(f_ceil, 'ceil', 1)\n ]\n\ndef test_functions():\n fs = build_func_lib()\n assert len(fs) > 0\n for function in fs:\n f = function.function\n inputs = [rand_arg(), -1, 0, 1]\n for i in inputs:\n out = f([i for i in range(function.arity)])\n assert ~(np.isnan(out))\n assert out <= 1\n assert out >= -1\n" ]
[ [ "numpy.isnan", "numpy.random.rand" ] ]
andreasjansson/DeepBach
[ "588e1965772856b98d0816518c1c6c71fc30b317" ]
[ "DeepBach/data_utils.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: Gaetan Hadjeres\n\"\"\"\n\nimport torch\nfrom DeepBach.helpers import cuda_variable\n\n\ndef mask_entry(tensor, entry_index, dim):\n \"\"\"\n Masks entry entry_index on dim dim\n similar to\n torch.cat((\ttensor[ :entry_index],\ttensor[ entry_index + 1 :], 0)\n but on another dimension\n :param tensor:\n :param entry_index:\n :param dim:\n :return:\n \"\"\"\n idx = [i for i in range(tensor.size(dim)) if not i == entry_index]\n idx = cuda_variable(torch.LongTensor(idx))\n tensor = tensor.index_select(dim, idx)\n return tensor\n\n\ndef reverse_tensor(tensor, dim):\n \"\"\"\n Do tensor[:, ... , -1::-1, :] along dim dim\n :param tensor:\n :param dim:\n :return:\n \"\"\"\n idx = [i for i in range(tensor.size(dim) - 1, -1, -1)]\n idx = cuda_variable(torch.LongTensor(idx))\n tensor = tensor.index_select(dim, idx)\n return tensor\n" ]
[ [ "torch.LongTensor" ] ]
PravyAI/DeepLearning
[ "2f6c32f526e649139b1762f3700db20c0d9bd83a" ]
[ "SimpleMnistClassifier/MNISTclassifier.py" ]
[ "\n# coding: utf-8\n\n# In[1]:\n\n\n# Copyright 2015 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\n\"\"\"A very simple MNIST classifier.\nSee extensive documentation at\nhttps://www.tensorflow.org/get_started/mnist/beginners\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport sys\n\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nimport tensorflow as tf\n\nFLAGS = None\n\n\ndef main(_):\n # Import data\n mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)\n\n # Create the model\n x = tf.placeholder(tf.float32, [None, 784])\n W = tf.Variable(tf.zeros([784, 10]))\n b = tf.Variable(tf.zeros([10]))\n y = tf.matmul(x, W) + b\n\n # Define loss and optimizer\n y_ = tf.placeholder(tf.float32, [None, 10])\n\n # The raw formulation of cross-entropy,\n #\n # tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),\n # reduction_indices=[1]))\n #\n # can be numerically unstable.\n #\n # So here we use tf.nn.softmax_cross_entropy_with_logits on the raw\n # outputs of 'y', and then average across the batch.\n cross_entropy = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n\n sess = tf.InteractiveSession()\n tf.global_variables_initializer().run()\n # Train\n for _ in range(1000): \n batch_xs, batch_ys = mnist.train.next_batch(100)\n sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n\n # Test trained model\n correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n y_: mnist.test.labels}))\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_dir', type=str, default='/tmp/tensorflow/mnist/input_data',\n help='Directory for storing input data')\n FLAGS, unparsed = parser.parse_known_args()\n tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)\n\n" ]
[ [ "tensorflow.matmul", "tensorflow.nn.softmax_cross_entropy_with_logits", "tensorflow.InteractiveSession", "tensorflow.zeros", "tensorflow.cast", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.train.GradientDescentOptimizer", "tensorflow.argmax", "tensorflow.examples.tutorials.mnist.input_data.read_data_sets", "tensorflow.app.run" ] ]
Stelath/geoguessr-ai
[ "08f5ae7ca8d1e50d586ee66222814589f4095a6d" ]
[ "find_best_model.py" ]
[ "import os\nimport argparse\nfrom tqdm import tqdm\nimport numpy as np\nfrom datetime import datetime\n\nimport torch\nimport torch.nn as nn\nimport torch.utils.data\nimport torchvision.models as models\nfrom geoguessr_dataset import GeoGuessrDataset\n\nmodel_names = sorted(name for name in models.__dict__\n if name.islower() and not name.startswith(\"__\")\n and callable(models.__dict__[name]))\n\nparser = argparse.ArgumentParser(description='PyTorch GeoGuessr AI Best Model Locator')\nparser.add_argument('data', metavar='DIR',\n help='path to dataset')\nparser.add_argument('-a', '--arch', metavar='ARCH', default='resnet50',\n choices=model_names,\n help='model architecture: ' +\n ' | '.join(model_names) +\n ' (default: resnet50)')\nparser.add_argument('-j', '--workers', default=4, type=int, metavar='N',\n help='number of data loading workers (default: 4)')\nparser.add_argument('-b', '--batch-size', default=64, type=int,\n metavar='N',\n help='batch size (default: 64), this is the total '\n 'batch size of the GPU')\nparser.add_argument('--models-dir', default='models', type=str)\n\nstart_time = datetime.now().strftime('%Y-%m-%d-%H-%M-%S')\nargs = parser.parse_args()\nall_loss = []\n\ndef fwd_pass(model, data, targets, loss_function, optimizer, train=False):\n data = data.cuda()\n targets = targets.cuda()\n\n if train:\n model.zero_grad()\n \n outputs = model(data)\n matches = [(torch.where(i >= 0.5, 1, 0) == j).all() for i, j in zip(outputs, targets)]\n acc = matches.count(True) / len(matches)\n loss = loss_function(outputs, targets)\n\n if train:\n loss.backward()\n optimizer.step()\n \n return acc, loss\n\ndef test(val_loader, model, loss_function):\n model.eval()\n acc = []\n loss = []\n \n for idx, sample in enumerate(tqdm(val_loader)):\n if idx < 256:\n data, target = sample\n batch_acc, batch_loss = fwd_pass(model, data, target, loss_function, None)\n acc.append(batch_acc)\n loss.append(batch_loss.cpu().detach().numpy())\n \n acc = np.mean(acc)\n loss = np.mean(loss)\n \n val_acc = np.mean(acc)\n val_loss = np.mean(loss)\n return val_acc, val_loss\n\ndef main():\n torch.device(\"cuda\")\n valdir = os.path.join(args.data, 'val')\n val_dataset = GeoGuessrDataset(valdir)\n\n val_loader = torch.utils.data.DataLoader(\n val_dataset, batch_size=args.batch_size, shuffle=False,\n num_workers=args.workers, pin_memory=True)\n \n print(\"=> creating model '{}'\".format(args.arch))\n model = models.__dict__[args.arch](pretrained=False, progress=True, num_classes=142)\n model = nn.Sequential(\n model,\n nn.Sigmoid()\n )\n model.cuda()\n \n loss_function = nn.BCELoss()\n \n for model_path in tqdm(os.listdir(args.models_dir)):\n model_path = os.path.join(args.models_dir, model_path)\n print(\"=> loading model '{}'\".format(model_path))\n checkpoint = torch.load(model_path)\n model.load_state_dict(checkpoint['model_state_dict'])\n print(\"=> loaded model '{}' (epoch {})\".format(model_path, checkpoint['epoch']))\n \n val_acc, val_loss = test(val_loader, model, loss_function)\n all_loss.append(val_loss)\n print(\"=> val_acc: {:.4f}, val_loss: {:.4f}\".format(val_acc, val_loss))\n \n min_value = min(all_loss)\n min_index = all_loss.index(min_value)\n print(\"=> best model: {}, loss: {}\".format(os.listdir(args.models_dir)[min_index], min_value))\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "torch.load", "torch.utils.data.DataLoader", "torch.nn.Sigmoid", "torch.nn.BCELoss", "numpy.mean", "torch.where", "torch.device" ] ]
lucfra/RFHO
[ "e08a36fcc342a46648c5e9d7f64a69cb3d3c6c79" ]
[ "rfho/models.py" ]
[ "# import data\n# import numpy as np\n# working with placeholders\nfrom functools import reduce\n\nimport tensorflow as tf\nfrom rfho.utils import MergedVariable\nimport tensorflow.contrib.graph_editor as ge\nimport rfho.utils as utils\n\ntest = False\ndo_print = False\n\n\ndef calc_mb(_shape, _type=32):\n from functools import reduce\n import operator\n return 1. * reduce(operator.mul, _shape, 1) * _type * 1.25e-7\n\n\ndef pvars(_vars, _tabs=0):\n \"\"\"utility function to print the arg variables\"\"\"\n if do_print:\n\n print('\\t' * _tabs, '-' * 10, 'START', '-' * 10)\n for k, v in _vars.items():\n print('\\t' * _tabs, k, ':', v)\n print('\\t' * _tabs, '-' * 10, 'END', '-' * 10)\n\n\n# layers util funcs ########\n\n\ndef uppool(value, name='uppool'): # TODO TBD??\n \"\"\"N-dimensional version of the unpooling operation from\n https://www.robots.ox.ac.uk/~vgg/rg/papers/Dosovitskiy_Learning_to_Generate_2015_CVPR_paper.pdf\n Note that the only dimension that can be unspecified is the first one (b)\n\n :param name:\n :param value: A Tensor of shape [b, d0, d1, ..., dn, ch]\n :return: A Tensor of shape [b, 2*d0, 2*d1, ..., 2*dn, ch]\n\n \"\"\"\n with tf.name_scope(name) as scope:\n sh = value.get_shape().as_list()\n dim = len(sh[1:-1])\n print(value)\n out = (tf.reshape(value, [-1] + sh[-dim:]))\n for i in range(dim, 0, -1):\n # out = tf.concat(i, [out, tf.zeros_like(out)]) #original implementation added zeros\n out = tf.concat([out, tf.identity(out)], i) # copies values\n out_size = [-1] + [s * 2 for s in sh[1:-1]] + [sh[-1]]\n out = tf.reshape(out, out_size, name=scope)\n return out\n\n\ndef convolutional_layer_2d(init_w=None, init_b=tf.zeros, strides=(1, 1, 1, 1),\n padding='SAME', act=tf.nn.relu):\n \"\"\"\n Helper function for 2d convolutional layer\n\n :param padding:\n :param init_w:\n :param init_b:\n :param strides:\n :param act:\n :return: an initializer\n \"\"\"\n if init_w is None: init_w = lambda shape: tf.truncated_normal(shape, stddev=.1)\n\n def _init(_input, shape):\n _W = create_or_reuse(init_w, shape, name='W')\n _b = create_or_reuse(init_b, [shape[-1]], name='b')\n linear_activation = tf.nn.conv2d(_input, _W, strides=strides, padding=padding, name='linear_activation') + _b\n activation = act(linear_activation)\n return _W, _b, activation\n\n return _init\n\n\ndef convolutional_layer2d_maxpool(init_w=None, init_b=tf.zeros, strides=(1, 1, 1, 1),\n padding='SAME', act=tf.nn.relu, **maxpool_kwargs):\n init_cnv = convolutional_layer_2d(init_w, init_b, strides, padding, act)\n maxpool_kwargs.setdefault('ksize', (1, 1, 1, 1))\n maxpool_kwargs.setdefault('strides', (1, 2, 2, 1))\n maxpool_kwargs.setdefault('padding', 'SAME')\n\n def _init(_input, shape):\n _W, _b, activation = init_cnv(_input, shape)\n return _W, _b, tf.nn.max_pool(activation, **maxpool_kwargs)\n\n return _init\n\n\ndef convolutional_layer2d_uppool(init_w=None, init_b=tf.zeros, strides=(1, 1, 1, 1),\n padding='SAME', act=tf.nn.relu, **uppool_kwargs):\n init_cnv = convolutional_layer_2d(init_w, init_b, strides, padding, act)\n\n def _init(_input, shape):\n _W, _b, activation = init_cnv(_input, shape)\n return _W, _b, uppool(activation, **uppool_kwargs)\n\n return _init\n\n\ndef dropout_activation(_keep_prob, _activ=tf.nn.relu):\n def _int(_v, name='default_name'):\n return tf.nn.dropout(_activ(_v, name), _keep_prob)\n\n return _int\n\n\ndef create_or_reuse(init_or_variable, shape, name='var'):\n \"\"\"\n Creates a variable given a shape or does nothing if `init_or_variable` is already a Variable.\n\n :param init_or_variable:\n :param shape:\n :param name:\n :return:\n \"\"\"\n return init_or_variable if isinstance(init_or_variable, tf.Variable) \\\n else tf.Variable(init_or_variable(shape), name=name)\n\n\ndef mixed_activation(*activations, proportions=None):\n def generate(lin_act, name='mixed_activation'):\n nonlocal proportions, activations\n if proportions: # argument check\n sum_proportions = sum(proportions)\n assert sum_proportions <= 1, \"proportions must sum up to at most 1: instead %d\" % sum_proportions\n if sum_proportions < 1.: proportions += [1. - sum_proportions]\n else:\n proportions = [1 / len(activations)] * len(activations)\n\n N = lin_act.get_shape().as_list()[1]\n\n calculated_partitions = reduce(\n lambda v1, v2: v1 + [sum(v1) + v2],\n [int(N * prp) for prp in proportions],\n [0]\n )\n calculated_partitions[-1] = N\n\n with tf.name_scope(name):\n parts = [act(lin_act[:, d1:d2]) for act, d1, d2\n in zip(activations, calculated_partitions, calculated_partitions[1:])]\n return tf.concat(parts, 1)\n\n return generate\n\n\ndef ffnn_layer(init_w=tf.contrib.layers.xavier_initializer(), # OK\n init_b=tf.zeros,\n activ=tf.nn.relu, benchmark=True):\n \"\"\"\n Helper for fully connected layer\n\n :param init_w:\n :param init_b:\n :param activ:\n :param benchmark:\n :return:\n \"\"\"\n\n def _int(_input, _shape):\n pvars(vars(), 1)\n _W = create_or_reuse(init_w, _shape, name='W')\n _b = create_or_reuse(init_b, [_shape[1]], name='b')\n\n mul = utils.matmul(_input, _W, benchmark=benchmark)\n\n _lin_activ = mul + _b\n _activ = activ(_lin_activ, name='activation')\n return _W, _b, _activ\n\n return _int\n\n\n# def ffnn_lin_out(init_w=tf.zeros, init_b=tf.zeros, benchmark=True):\n# return ffnn_layer(init_w, init_b, tf.identity, benchmark=benchmark)\n\n# standard layers end ##############\n\n\ndef vectorize_model(model_vars, *o_outs, augment=0, suppress_err_out=True):\n \"\"\"\n Function that \"vectorizes\" a model (as a computation graph).\n\n Given a model written in a \"standard way\", i.e. with parameters organized in k-rank tensors as needed\n (matrices and vectors for linearities, 3 or 4 rank tensors for convolutional kernels etc.), returns the same model\n with all the parameters organized in a single vector.\n\n It is believed that having coded the models in this way, it will be much simpler to implement future algorithms,\n especially when relying on the second-order derivatives (Hessian of objective function), since in such a framework,\n the model will be entirely dependent by its single parameter vector and described by the resulting computation\n graph.\n\n Since the the downward process of vectorizing the model does not work, it is\n necessary to modify the computation graph accordingly to have an upward dependence\n from the all weights vector to the single parameters.\n\n SOLVED! { The technical caveat is that the variables must be encapsulated into an op (tf.identity) otherwise,\n for some\n unknown reason, the substitution process is not possible. I've tried in several different ways but they all failed.\n Substantially you need to keep track of the tf.identity(variable) and use the resulting tensor to build up the model\n and then also of the initial value of variable. Probably it is not necessary to keep track of variable itself. }\n\n :param model_vars: list of variables of the model or initializers\n :param o_outs: output_variables, list or tensor. (e.g. model output)\n :param augment: (int: default 0) augment the all weights vector by creating augumented variables (initialized at 0)\n that mirror rank and dimensions of the variables in `model_vars`. The process is repeated\n `augment` times.\n This new variables can be accessed with methods in `MergedVariable`.\n The common usage is to prepare the model to be optimized with optimizers that require states\n such as `MomentumOptimizer` (`augment=1`) or `AdamOptimizer` (`augment=2`).\n :param suppress_err_out: if `True` (default) suppress tensorflow warnings and outputs.\n This might cause system error in very very few cases...\n\n :return: a list which has as first element the `MergedVariable` that represents the all weights vector. Remaining\n elements are the outputs\n in the modified graph. These new outs are the same computed by the initial model\n (by the computation graph in which the model lives) but with dependencies form the all_weight_vector.\n\n \"\"\"\n # assert len(model_vars) == len(model_vars_tensor), 'length of model_vars and model_var_tensor do not match'\n assert len(model_vars) > 0, 'no variables in model_vars!'\n outs = [tf.identity(o) if isinstance(o, tf.Variable) else o for o in o_outs]\n # TODO implement recursive call for nested lists\n with model_vars[0].graph.as_default():\n\n true_w = MergedVariable(model_vars)\n\n if augment:\n augmented_variables = [true_w]\n for k in range(augment):\n with tf.name_scope('augmented_variables'):\n with tf.name_scope(str(k)):\n with tf.name_scope('original_variables'):\n tmp_augmented = [tf.Variable(tf.zeros(v.get_shape().as_list()), name=v.name.split(':')[0])\n for v in model_vars]\n augmented_variables.append(MergedVariable(tmp_augmented))\n\n w = MergedVariable(augmented_variables)\n else:\n w = true_w\n\n # with open(os.devnull, 'w') as dnf:\n # with utils.suppress_stdout_stderr(): # may cause ERROR TOO MANY FILES OPENED!.:((\n\n if suppress_err_out: # FIXME deprecation here on GraphKey usage... now redirecting outs... should fix tf..\n with utils.suppress_stdout_stderr():\n new_outs = ge.graph_replace(outs, w.generate_swap_dict())\n else: new_outs = ge.graph_replace(outs, w.generate_swap_dict())\n\n return [w] + new_outs\n\n\nclass Network(object):\n \"\"\"\n Base object for models\n \"\"\"\n\n def __init__(self, _input, name, deterministic_initialization=False):\n \"\"\"\n Creates an object that represent a network. Important attributes of a Network object are\n\n `var_list`: list of tf.Variables that constitute the parameters of the model\n\n `inp`: list, first element is `_input` and last should be output of the model. Other entries can be\n hidden layers activations.\n\n :param _input: tf.Tensor, input of this model.\n \"\"\"\n super(Network, self).__init__()\n\n self.name = name\n\n self.deterministic_initialization = deterministic_initialization\n self._var_list_initial_values = []\n self._var_init_placeholder = None\n self._assign_int = []\n self._var_initializer_op = None\n\n self.Ws = []\n self.bs = []\n self.inp = [_input]\n self.out = None # for convenience\n self.var_list = []\n\n self.active_gen = []\n self.active_gen_kwargs = []\n\n self.w = None\n\n def _std_collections(self):\n self.var_list = self.Ws + self.bs\n self.out = self.inp[-1]\n [tf.add_to_collection(tf.GraphKeys.WEIGHTS, _v) for _v in self.Ws]\n [tf.add_to_collection(tf.GraphKeys.BIASES, _v) for _v in self.bs]\n [tf.add_to_collection(tf.GraphKeys.GLOBAL_VARIABLES, _v) for _v in self.var_list]\n [tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, _v) for _v in self.inp]\n\n def for_input(self, new_input, new_name=None):\n \"\"\"\n Returns the same model computed on an other input...\n\n :param new_input:\n :param new_name:\n :return:\n \"\"\"\n raise NotImplementedError()\n\n def _for_input_new_activ_kwargs(self):\n new_active_gen_kwargs = []\n for ag_kw, _W, _b in zip(self.active_gen_kwargs, self.Ws, self.bs):\n n_ag_kw = dict(ag_kw)\n n_ag_kw['init_w'] = _W\n n_ag_kw['init_b'] = _b\n new_active_gen_kwargs.append(n_ag_kw)\n return new_active_gen_kwargs\n\n def initialize(self, session=None):\n \"\"\"\n Initialize the model. If `deterministic_initialization` is set to true, \n saves the initial weight in numpy which will be used for subsequent initialization.\n This is because random seed management in tensorflow is rather obscure... and I could not\n find a way to set the same seed across different initialization without exiting the session.\n \n :param session: \n :return: \n \"\"\"\n ss = session or tf.get_default_session()\n assert ss, 'No default session'\n if not self._var_initializer_op:\n self._var_initializer_op = tf.variables_initializer(self.var_list)\n ss.run(self._var_initializer_op)\n if self.deterministic_initialization:\n if self._var_init_placeholder is None:\n self._var_init_placeholder = tf.placeholder(tf.float32)\n self._assign_int = [v.assign(self._var_init_placeholder) for v in self.var_list]\n\n if not self._var_list_initial_values:\n self._var_list_initial_values = ss.run(self.var_list)\n\n else:\n [ss.run(v_op, feed_dict={self._var_init_placeholder: val})\n for v_op, val in zip(self._assign_int, self._var_list_initial_values)]\n\n def vectorize(self, *outs, augment=0):\n \"\"\"\n Calls `vectorize_model` with the variables of this model and specified outputs.\n Moreover it registers this model on the resulting `MergedVariable` and the resulting merged variable \n in the model as the attribute `self.w`.\n (See `vectorize_model` and `mergedVariable`)\n\n :param outs: tensors \n :param augment: \n :return: \n \"\"\"\n res = vectorize_model(self.var_list, *outs, augment=augment)\n res[0].model = self\n self.w = res[0]\n return res\n\n def set_saver(self):\n self.saver = tf.train.Saver(var_list=self.var_list)\n\n def save(self, sess, step):\n self.saver.save(sess, self.name, global_step=step)\n\n def load(self, sess, step):\n self.saver.restore(sess, self.name + \"-\" + str(step))\n\n\nclass LinearModel(Network):\n\n def __init__(self, _input, dim_input, dim_output, name='Linear_Model', deterministic_initialization=False,\n active_gen=ffnn_layer, **activ_gen_kwargs):\n \"\"\"\n Builds a single layer NN, by default with linear activation (this means it's just a linear model!)\n\n :param _input: see `Network`\n :param dim_input: input dimension\n :param dim_output: output dimension\n :param active_gen: callable that genera\n \"\"\"\n # TODO infer input dimensions form _input....\n super(LinearModel, self).__init__(_input, name,\n deterministic_initialization=deterministic_initialization)\n\n self.dims = (dim_input, dim_output)\n\n activ_gen_kwargs.setdefault('activ', tf.identity) # linear model by default\n activ_gen_kwargs.setdefault('init_w', tf.zeros)\n\n with tf.name_scope(name):\n self.active_gen.append(active_gen)\n self.active_gen_kwargs.append(activ_gen_kwargs)\n\n ac_func = active_gen(**activ_gen_kwargs)\n\n _W, _b, _activ = ac_func(self.inp[-1], self.dims)\n self.Ws.append(_W)\n self.bs.append(_b) # put in the lists\n if dim_output == 1:\n self.inp.append(_activ[:, 0])\n else:\n self.inp.append(_activ)\n\n self._std_collections()\n\n def for_input(self, new_input, new_name=None):\n new_active_gen_kwargs = self._for_input_new_activ_kwargs()\n\n return LinearModel(new_input, self.dims[0], self.dims[1], name=new_name or self.name,\n active_gen=self.active_gen[0], **new_active_gen_kwargs[0])\n\n\nclass FFNN(Network):\n def __init__(self, _input, dims, name='FFNN', deterministic_initialization=False,\n active_gen=ffnn_layer, active_gen_kwargs=None\n ):\n \"\"\"\n Creates a feed-forward neural network.\n\n :param _input:\n :param dims:\n :param active_gen:\n :param name:\n \"\"\"\n super(FFNN, self).__init__(_input, name,\n deterministic_initialization=deterministic_initialization)\n\n pvars(vars())\n self.dims = dims\n\n active_gen = utils.as_tuple_or_list(active_gen)\n if len(active_gen) != len(dims) - 1: # assume (hidden, output)\n active_gen = [active_gen[0]] * (len(dims) - 2) + [active_gen[-1]]\n\n active_gen_kwargs = utils.as_tuple_or_list(active_gen_kwargs or {})\n if len(active_gen_kwargs) != len(dims) - 1: # assume (hidden, output)\n active_gen_kwargs = [dict(active_gen_kwargs[0]) if active_gen_kwargs[0] else {}] * (len(dims) - 2) \\\n + [dict(active_gen_kwargs[-1]) if active_gen_kwargs[-1] else {}]\n active_gen_kwargs[-1].setdefault('activ', tf.identity) # sets linear output by default\n active_gen_kwargs[-1].setdefault('init_w', tf.zeros) # sets weight matrix of last layer to zero by default\n\n with tf.name_scope(name):\n for d0, d1, ag, ag_kw, l_num in zip(dims, dims[1:], active_gen, active_gen_kwargs, range(len(dims))):\n with tf.name_scope('layer_' + str(l_num)):\n self.active_gen.append(ag)\n self.active_gen_kwargs.append(ag_kw)\n\n _W, _b, _activ = ag(**ag_kw)(self.inp[-1], [d0, d1])\n\n self.Ws.append(_W)\n self.bs.append(_b) # put in the lists\n self.inp.append(_activ)\n\n self._std_collections()\n\n # noinspection PyTypeChecker\n def for_input(self, new_input, new_name=None):\n new_active_gen_kwargs = self._for_input_new_activ_kwargs()\n return FFNN(new_input, self.dims, name=new_name or self.name, active_gen=self.active_gen,\n active_gen_kwargs=new_active_gen_kwargs)\n\n\nclass SimpleConvolutionalOnly(Network):\n def __init__(self, _input, _dims, conv_gen=convolutional_layer2d_maxpool, deterministic_initialization=False,\n conv_gen_kwargs=None, name='Simple_Convolutional'):\n \"\"\"\n Creates a simple convolutional network, by default 2 dimensional. Only convolutional part! Use\n `SimpleCNN` for an usual CNN classifier.\n\n :param _input:\n :param _dims: in default 2d setting, should be a list of quadruples where each quadruple is given by\n (width, height, # of input channels, # of output channels)\n :param conv_gen:\n :param name:\n \"\"\"\n super(SimpleConvolutionalOnly, self).__init__(_input, name,\n deterministic_initialization=deterministic_initialization)\n pvars(vars())\n\n self.dims = _dims\n\n if not isinstance(conv_gen, (list, tuple)): # assume all identical\n conv_gen = [conv_gen] * len(_dims)\n\n if not isinstance(conv_gen_kwargs, (list, tuple)): # assume all keyword arguments identical\n conv_gen_kwargs = [conv_gen_kwargs or {}] * len(_dims)\n\n with tf.name_scope(name):\n\n for sh, ag, ag_kw, l_num in zip(_dims, conv_gen, conv_gen_kwargs, range(len(_dims))):\n with tf.name_scope('layer_' + str(l_num)):\n self.active_gen.append(ag)\n self.active_gen_kwargs.append(ag_kw)\n\n _W, _b, _out = ag(**ag_kw)(self.inp[-1], sh)\n\n self.Ws.append(_W)\n self.bs.append(_b) # put in the lists\n self.inp.append(_out)\n\n self._std_collections()\n\n # noinspection PyTypeChecker\n def for_input(self, new_input, new_name=None):\n return SimpleConvolutionalOnly(new_input, _dims=self.dims, conv_gen=self.active_gen,\n conv_gen_kwargs=self._for_input_new_activ_kwargs(),\n name=new_name or self.name)\n\n\nclass SimpleCNN(Network):\n\n def __init__(self, _input, conv_part=None, ffnn_part=None, conv_dims=None, ffnn_dims=None,\n conv_gen=convolutional_layer2d_maxpool, conv_gen_kwargs=None,\n activ_gen=ffnn_layer, active_gen_kwargs=None, deterministic_initialization=False,\n name='SimpleCNN'):\n \"\"\"\n Builds a simple convolutional network a la LeNet5.\n\n :param _input: input tensor or placeholder (must be given in the right (2d) shape)\n :param conv_part:\n :param ffnn_part:\n :param conv_dims:\n :param ffnn_dims: dimensions for the feed-forward part.\n :param conv_gen:\n :param conv_gen_kwargs:\n :param activ_gen:\n :param active_gen_kwargs:\n :param name:\n \"\"\"\n assert conv_part or conv_dims\n assert ffnn_part or ffnn_dims\n\n super(SimpleCNN, self).__init__(_input, name,\n deterministic_initialization=deterministic_initialization)\n pvars(vars())\n\n with tf.name_scope(name):\n self.conv_part = conv_part or SimpleConvolutionalOnly(_input, conv_dims,\n conv_gen=conv_gen, conv_gen_kwargs=conv_gen_kwargs,\n name='conv_part')\n self.Ws += self.conv_part.Ws\n self.bs += self.conv_part.bs\n self.inp += self.conv_part.inp\n self.active_gen += self.conv_part.active_gen\n self.active_gen_kwargs += self.conv_part.active_gen_kwargs\n\n if ffnn_dims:\n ffnn_input = tf.reshape(self.inp[-1], [-1, ffnn_dims[0]])\n # ffnn_dims = [ffnn_input.get_shape().as_list()[1]] + ffnn_dims\n self.ffnn_part = FFNN(ffnn_input,\n ffnn_dims, active_gen=activ_gen,\n active_gen_kwargs=active_gen_kwargs, name='ffnn_part')\n else:\n self.ffnn_part = ffnn_part\n\n self.Ws += self.ffnn_part.Ws\n self.bs += self.ffnn_part.bs\n self.inp += self.ffnn_part.inp\n self.active_gen += self.ffnn_part.active_gen\n self.active_gen_kwargs += self.ffnn_part.active_gen_kwargs\n\n self.dims = self.conv_part.dims + self.ffnn_part.dims\n self._std_collections()\n\n def for_input(self, new_input, new_name=None):\n new_conv = self.conv_part.for_input(new_input)\n new_ffnn_input = tf.reshape(self.inp[-1], [-1, self.ffnn_part.dims[0]])\n new_ffnn = self.ffnn_part.for_input(new_ffnn_input)\n return SimpleCNN(new_input, conv_part=new_conv, ffnn_part=new_ffnn,\n name=new_name or self.name)\n\n# class SimpleDeCNN(Network):\n# def __init__(self, _input, ffnn_dims, conv_dims,\n# activ_gen=(ffnn_layer(), ffnn_layer()),\n# conv_gen=(relu_conv_layer2x2_up_pool, conv_layer),\n# name='SimpDeCNN'):\n# \"\"\"_x must be given in the right (2d) shape\n# NOTE: first component of conv_dims must be that of the 2d tensor given as input to the\n# convolutional part of the network\"\"\"\n# super(SimpleDeCNN, self).__init__(_input)\n# pvars(vars())\n#\n# self.dims = ffnn_dims + conv_dims\n#\n# with tf.name_scope(name):\n# ffnn_part = FFNN(_input, ffnn_dims, activ_gen,\n# name='ffnn_part')\n# self.Ws += ffnn_part.Ws\n# self.bs += ffnn_part.bs\n# self.inp += ffnn_part.inp\n#\n# _conv_input = tf.reshape(self.inp[-1], [-1] + conv_dims[0], name='conv_input')\n# if len(conv_gen) != len(conv_dims) - 1: # assume len(conv_gen) == 2\n# conv_gen = [conv_gen[0]]*(len(conv_dims) - 2) + [conv_gen[1]]\n# conv_part = SimpleConvolutionalOnly(_conv_input, conv_dims[1:], conv_gen, name='conv_part')\n# self.Ws += conv_part.Ws\n# self.bs += conv_part.bs\n# self.inp += conv_part.inp\n#\n# self._std_collections()\n\nif __name__ == '__main__':\n pass\n" ]
[ [ "tensorflow.get_default_session", "tensorflow.truncated_normal", "tensorflow.concat", "tensorflow.nn.max_pool", "tensorflow.reshape", "tensorflow.identity", "tensorflow.variables_initializer", "tensorflow.placeholder", "tensorflow.contrib.layers.xavier_initializer", "tensorflow.name_scope", "tensorflow.train.Saver", "tensorflow.add_to_collection", "tensorflow.nn.conv2d" ] ]
karakusc/OpenSeq2Seq
[ "87e9625af99b799808d5d9af8147f8ee4a2c5dbe" ]
[ "open_seq2seq/decoders/fc_decoders.py" ]
[ "# Copyright (c) 2018 NVIDIA Corporation\n\"\"\"This module defines various fully-connected decoders (consisting of one\nfully connected layer).\n\nThese classes are usually used for models that are not really\nsequence-to-sequence and thus should be artificially split into encoder and\ndecoder by cutting, for example, on the last fully-connected layer.\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\nfrom __future__ import unicode_literals\n\nimport os\n\nimport tensorflow as tf\n\nfrom .decoder import Decoder\n\n\nclass FullyConnectedDecoder(Decoder):\n \"\"\"Simple decoder consisting of one fully-connected layer.\n \"\"\"\n @staticmethod\n def get_required_params():\n return dict(Decoder.get_required_params(), **{\n 'output_dim': int,\n })\n\n def __init__(self, params, model,\n name=\"fully_connected_decoder\", mode='train'):\n \"\"\"Fully connected decoder constructor.\n\n See parent class for arguments description.\n\n Config parameters:\n\n * **output_dim** (int) --- output dimension.\n \"\"\"\n super(FullyConnectedDecoder, self).__init__(params, model, name, mode)\n\n def _decode(self, input_dict):\n \"\"\"This method performs linear transformation of input.\n\n Args:\n input_dict (dict): input dictionary that has to contain\n the following fields::\n input_dict = {\n 'encoder_output': {\n 'outputs': output of encoder (shape=[batch_size, num_features])\n }\n }\n\n Returns:\n dict: dictionary with the following tensors::\n\n {\n 'logits': logits with the shape=[batch_size, output_dim]\n 'outputs': [logits] (same as logits but wrapped in list)\n }\n \"\"\"\n inputs = input_dict['encoder_output']['outputs']\n regularizer = self.params.get('regularizer', None)\n\n # activation is linear by default\n logits = tf.layers.dense(\n inputs=inputs,\n units=self.params['output_dim'],\n kernel_regularizer=regularizer,\n name='fully_connected',\n )\n return {'logits': logits, 'outputs': [logits]}\n\n\nclass FullyConnectedTimeDecoder(Decoder):\n \"\"\"Fully connected decoder that operates on inputs with time dimension.\n That is, input shape should be ``[batch size, time length, num features]``.\n \"\"\"\n @staticmethod\n def get_required_params():\n return dict(Decoder.get_required_params(), **{\n 'tgt_vocab_size': int,\n })\n\n @staticmethod\n def get_optional_params():\n return dict(Decoder.get_optional_params(), **{\n 'logits_to_outputs_func': None, # user defined function\n })\n\n def __init__(self, params, model,\n name=\"fully_connected_time_decoder\", mode='train'):\n \"\"\"Fully connected time decoder constructor.\n\n See parent class for arguments description.\n\n Config parameters:\n\n * **tgt_vocab_size** (int) --- target vocabulary size, i.e. number of\n output features.\n * **logits_to_outputs_func** --- function that maps produced logits to\n decoder outputs, i.e. actual text sequences.\n \"\"\"\n super(FullyConnectedTimeDecoder, self).__init__(params, model, name, mode)\n\n def _decode(self, input_dict):\n \"\"\"Creates TensorFlow graph for fully connected time decoder.\n\n Args:\n input_dict (dict): input dictionary that has to contain\n the following fields::\n input_dict = {\n 'encoder_output': {\n \"outputs\": tensor with shape [batch_size, time length, hidden dim]\n \"src_length\": tensor with shape [batch_size]\n }\n }\n\n Returns:\n dict: dictionary with the following tensors::\n\n {\n 'logits': logits with the shape=[time length, batch_size, tgt_vocab_size]\n 'outputs': logits_to_outputs_func(logits, input_dict)\n }\n \"\"\"\n inputs = input_dict['encoder_output']['outputs']\n regularizer = self.params.get('regularizer', None)\n\n batch_size, _, n_hidden = inputs.get_shape().as_list()\n # reshape from [B, T, A] --> [B*T, A].\n # Output shape: [n_steps * batch_size, n_hidden]\n inputs = tf.reshape(inputs, [-1, n_hidden])\n\n # activation is linear by default\n logits = tf.layers.dense(\n inputs=inputs,\n units=self.params['tgt_vocab_size'],\n kernel_regularizer=regularizer,\n name='fully_connected',\n )\n logits = tf.reshape(\n logits,\n [batch_size, -1, self.params['tgt_vocab_size']],\n name=\"logits\",\n )\n # converting to time_major=True shape\n logits = tf.transpose(logits, [1, 0, 2])\n\n if 'logits_to_outputs_func' in self.params:\n outputs = self.params['logits_to_outputs_func'](logits, input_dict)\n return {\n 'outputs': outputs,\n 'logits': logits,\n 'src_length': input_dict['encoder_output']['src_length'],\n }\n return {'logits': logits,\n 'src_length': input_dict['encoder_output']['src_length']}\n\n\nclass FullyConnectedCTCDecoder(FullyConnectedTimeDecoder):\n \"\"\"Fully connected time decoder that provides a CTC-based text\n generation (either with or without language model). If language model is not\n used, ``tf.nn.ctc_greedy_decoder`` will be used as text generation method.\n \"\"\"\n @staticmethod\n def get_required_params():\n return dict(FullyConnectedTimeDecoder.get_required_params(), **{\n 'use_language_model': bool,\n })\n\n @staticmethod\n def get_optional_params():\n return dict(FullyConnectedTimeDecoder.get_optional_params(), **{\n 'decoder_library_path': str,\n 'beam_width': int,\n 'alpha': float,\n 'beta': float,\n 'lm_path': str,\n 'trie_path': str,\n 'alphabet_config_path': str,\n })\n\n def __init__(self, params, model,\n name=\"fully_connected_ctc_decoder\", mode='train'):\n \"\"\"Fully connected CTC decoder constructor.\n\n See parent class for arguments description.\n\n Config parameters:\n\n * **use_language_model** (bool) --- whether to use language model for\n output text generation. If False, other config parameters are not used.\n * **decoder_library_path** (string) --- path to the ctc decoder with\n language model library.\n * **lm_path** (string) --- path to the language model file.\n * **trie_path** (string) --- path to the prefix trie file.\n * **alphabet_config_path** (string) --- path to the alphabet file.\n * **beam_width** (int) --- beam width for beam search.\n * **alpha** (float) --- weight that is assigned to language model\n probabilities.\n * **beta** (float) --- weight that is assigned to the\n word count.\n \"\"\"\n super(FullyConnectedCTCDecoder, self).__init__(params, model, name, mode)\n\n if self.params['use_language_model']:\n # creating decode_with_lm function if it is compiled\n lib_path = self.params['decoder_library_path']\n if not os.path.exists(os.path.abspath(lib_path)):\n raise IOError('Can\\'t find the decoder with language model library. '\n 'Make sure you have built it and '\n 'check that you provide the correct '\n 'path in the --decoder_library_path parameter.')\n\n custom_op_module = tf.load_op_library(lib_path)\n\n def decode_with_lm(logits, decoder_input,\n beam_width=self.params['beam_width'],\n top_paths=1, merge_repeated=False):\n sequence_length = decoder_input['encoder_output']['src_length']\n if logits.dtype.base_dtype != tf.float32:\n logits = tf.cast(logits, tf.float32)\n decoded_ixs, decoded_vals, decoded_shapes, log_probabilities = (\n custom_op_module.ctc_beam_search_decoder_with_lm(\n logits, sequence_length, beam_width=beam_width,\n model_path=self.params['lm_path'], trie_path=self.params['trie_path'],\n alphabet_path=self.params['alphabet_config_path'],\n alpha=self.params['alpha'],\n beta=self.params['beta'],\n top_paths=top_paths, merge_repeated=merge_repeated,\n )\n )\n return [tf.SparseTensor(decoded_ixs[0], decoded_vals[0],\n decoded_shapes[0])]\n\n self.params['logits_to_outputs_func'] = decode_with_lm\n else:\n def decode_without_lm(logits, decoder_input, merge_repeated=True):\n if logits.dtype.base_dtype != tf.float32:\n logits = tf.cast(logits, tf.float32)\n decoded, neg_sum_logits = tf.nn.ctc_greedy_decoder(\n logits, decoder_input['encoder_output']['src_length'],\n merge_repeated,\n )\n return decoded\n\n self.params['logits_to_outputs_func'] = decode_without_lm\n" ]
[ [ "tensorflow.nn.ctc_greedy_decoder", "tensorflow.transpose", "tensorflow.reshape", "tensorflow.cast", "tensorflow.layers.dense", "tensorflow.SparseTensor", "tensorflow.load_op_library" ] ]
technetbytes/CNIC
[ "51b7f92d6e77509167b86643ee8fef44d39e193c" ]
[ "generate_tfrecord.py" ]
[ "\"\"\"\nUsage:\n\n# Create train data:\npython generate_tfrecord.py --label=<LABEL> --csv_input=<PATH_TO_ANNOTATIONS_FOLDER>/train_labels.csv --output_path=<PATH_TO_ANNOTATIONS_FOLDER>/train.record\n\n# Create test data:\npython generate_tfrecord.py --label=<LABEL> --csv_input=<PATH_TO_ANNOTATIONS_FOLDER>/test_labels.csv --output_path=<PATH_TO_ANNOTATIONS_FOLDER>/test.record\n\"\"\"\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nimport os\nimport io\nimport pandas as pd\nimport tensorflow.compat.v1 as tf\nimport sys\nsys.path.append(\"../../models/research\")\n\nfrom PIL import Image\nfrom object_detection.utils import dataset_util\nfrom collections import namedtuple, OrderedDict\n\nflags = tf.app.flags\nflags.DEFINE_string('csv_input', '', 'Path to the CSV input')\nflags.DEFINE_string('output_path', '', 'Path to output TFRecord')\nflags.DEFINE_string('label', '', 'Name of class label')\n# if your image has more labels input them as\n# flags.DEFINE_string('label0', '', 'Name of class[0] label')\n# flags.DEFINE_string('label1', '', 'Name of class[1] label')\n# and so on.\nflags.DEFINE_string('img_path', '', 'Path to images')\nFLAGS = flags.FLAGS\n\n\n# TO-DO replace this with label map\n# for multiple labels add more else if statements\n# def class_text_to_int(row_label):\n# if row_label == FLAGS.label: # 'ship':\n# return 1\n# # comment upper if statement and uncomment these statements for multiple labelling\n# # if row_label == FLAGS.label0:\n# # return 1\n# # elif row_label == FLAGS.label1:\n# # return 0\n# else:\n# None\ndef class_text_to_int(row_label):\n if row_label == 'Front':\n return 1\n elif row_label == 'Name':\n return 2\n elif row_label == 'FatherName':\n return 3\n elif row_label == 'HusbandName':\n return 4\n elif row_label == 'Gender':\n return 5\n elif row_label == 'IdNo':\n return 6\n elif row_label == 'DOB':\n return 7\n elif row_label == 'DOI':\n return 8\n elif row_label == 'DOE':\n return 9 \n else:\n return None\n\n\ndef split(df, group):\n data = namedtuple('data', ['filename', 'object'])\n gb = df.groupby(group)\n return [data(filename, gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)]\n\n\ndef create_tf_example(group, path):\n print(group.filename)\n with tf.gfile.GFile(os.path.join(path, '{}'.format(group.filename)), 'rb') as fid:\n encoded_jpg = fid.read()\n encoded_jpg_io = io.BytesIO(encoded_jpg)\n image = Image.open(encoded_jpg_io)\n width, height = image.size\n\n filename = group.filename.encode('utf8')\n image_format = b'jpg'\n # check if the image format is matching with your images.\n xmins = []\n xmaxs = []\n ymins = []\n ymaxs = []\n classes_text = []\n classes = []\n\n for index, row in group.object.iterrows():\n xmins.append(row['xmin'] / width)\n xmaxs.append(row['xmax'] / width)\n ymins.append(row['ymin'] / height)\n ymaxs.append(row['ymax'] / height)\n classes_text.append(row['class'].encode('utf8'))\n print(row['class'])\n classes.append(class_text_to_int(row['class']))\n\n tf_example = tf.train.Example(features=tf.train.Features(feature={\n 'image/height': dataset_util.int64_feature(height),\n 'image/width': dataset_util.int64_feature(width),\n 'image/filename': dataset_util.bytes_feature(filename),\n 'image/source_id': dataset_util.bytes_feature(filename),\n 'image/encoded': dataset_util.bytes_feature(encoded_jpg),\n 'image/format': dataset_util.bytes_feature(image_format),\n 'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),\n 'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),\n 'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),\n 'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),\n 'image/object/class/text': dataset_util.bytes_list_feature(classes_text),\n 'image/object/class/label': dataset_util.int64_list_feature(classes),\n }))\n return tf_example\n\n\ndef main(_):\n writer = tf.python_io.TFRecordWriter(FLAGS.output_path)\n path = os.path.join(os.getcwd(), FLAGS.img_path)\n examples = pd.read_csv(FLAGS.csv_input)\n grouped = split(examples, 'filename')\n for group in grouped:\n tf_example = create_tf_example(group, path)\n writer.write(tf_example.SerializeToString())\n\n writer.close()\n output_path = os.path.join(os.getcwd(), FLAGS.output_path)\n print('Successfully created the TFRecords: {}'.format(output_path))\n\n\nif __name__ == '__main__':\n tf.app.run()\n" ]
[ [ "tensorflow.compat.v1.python_io.TFRecordWriter", "pandas.read_csv", "tensorflow.compat.v1.app.run" ] ]
zy-song/pysindy
[ "6ed02140c3e255c8bb69b19a7d9452930bd3253d" ]
[ "pysindy/feature_library/polynomial_library.py" ]
[ "from itertools import chain\nfrom itertools import combinations\nfrom itertools import combinations_with_replacement as combinations_w_r\n\nimport numpy as np\nfrom scipy import sparse\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.preprocessing._csr_polynomial_expansion import _csr_polynomial_expansion\nfrom sklearn.utils import check_array\nfrom sklearn.utils.validation import check_is_fitted\nfrom sklearn.utils.validation import FLOAT_DTYPES\n\nfrom .feature_library import BaseFeatureLibrary\n\n\nclass PolynomialLibrary(PolynomialFeatures, BaseFeatureLibrary):\n \"\"\"Generate polynomial and interaction features.\n\n This is the same as :code:`sklearn.preprocessing.PolynomialFeatures`,\n but also adds the option to omit interaction features from the library.\n\n Parameters\n ----------\n degree : integer, optional (default 2)\n The degree of the polynomial features.\n include_interaction : boolean, optional (default True)\n Determines whether interaction features are produced.\n If false, features are all of the form ``x[i] ** k``.\n interaction_only : boolean, optional (default False)\n If true, only interaction features are produced: features that are\n products of at most ``degree`` *distinct* input features (so not\n ``x[1] ** 2``, ``x[0] * x[2] ** 3``, etc.).\n include_bias : boolean, optional (default True)\n If True (default), then include a bias column, the feature in which\n all polynomial powers are zero (i.e. a column of ones - acts as an\n intercept term in a linear model).\n order : str in {'C', 'F'}, optional (default 'C')\n Order of output array in the dense case. 'F' order is faster to\n compute, but may slow down subsequent estimators.\n\n Attributes\n ----------\n powers_ : array, shape (n_output_features, n_input_features)\n powers_[i, j] is the exponent of the jth input in the ith output.\n\n n_input_features_ : int\n The total number of input features.\n\n n_output_features_ : int\n The total number of output features. This number is computed by\n iterating over all appropriately sized combinations of input features.\n \"\"\"\n\n def __init__(\n self,\n degree=2,\n include_interaction=True,\n interaction_only=False,\n include_bias=True,\n order=\"C\",\n ):\n super(PolynomialLibrary, self).__init__(\n degree=degree,\n interaction_only=interaction_only,\n include_bias=include_bias,\n order=order,\n )\n if degree < 0 or not isinstance(degree, int):\n raise ValueError(\"degree must be a nonnegative integer\")\n if (not include_interaction) and interaction_only:\n raise ValueError(\n \"Can't have include_interaction be False and interaction_only\"\n \" be True\"\n )\n self.include_interaction = include_interaction\n\n @staticmethod\n def _combinations(\n n_features, degree, include_interaction, interaction_only, include_bias\n ):\n comb = combinations if interaction_only else combinations_w_r\n start = int(not include_bias)\n if not include_interaction:\n if include_bias:\n return chain(\n [()],\n chain.from_iterable(\n combinations_w_r([j], i)\n for i in range(1, degree + 1)\n for j in range(n_features)\n ),\n )\n else:\n return chain.from_iterable(\n combinations_w_r([j], i)\n for i in range(1, degree + 1)\n for j in range(n_features)\n )\n return chain.from_iterable(\n comb(range(n_features), i) for i in range(start, degree + 1)\n )\n\n @property\n def powers_(self):\n check_is_fitted(self)\n\n combinations = self._combinations(\n self.n_input_features_,\n self.degree,\n self.include_interaction,\n self.interaction_only,\n self.include_bias,\n )\n return np.vstack(\n [np.bincount(c, minlength=self.n_input_features_) for c in combinations]\n )\n\n def get_feature_names(self, input_features=None):\n \"\"\"Return feature names for output features.\n\n Parameters\n ----------\n input_features : list of string, length n_features, optional\n String names for input features if available. By default,\n \"x0\", \"x1\", ... \"xn_features\" is used.\n\n Returns\n -------\n output_feature_names : list of string, length n_output_features\n\n \"\"\"\n powers = self.powers_\n if input_features is None:\n input_features = [\"x%d\" % i for i in range(powers.shape[1])]\n feature_names = []\n for row in powers:\n inds = np.where(row)[0]\n if len(inds):\n name = \" \".join(\n \"%s^%d\" % (input_features[ind], exp)\n if exp != 1\n else input_features[ind]\n for ind, exp in zip(inds, row[inds])\n )\n else:\n name = \"1\"\n feature_names.append(name)\n return feature_names\n\n def fit(self, X, y=None):\n \"\"\"\n Compute number of output features.\n\n Parameters\n ----------\n X : array-like, shape (n_samples, n_features)\n The data.\n Returns\n -------\n self : instance\n \"\"\"\n n_samples, n_features = check_array(X, accept_sparse=True).shape\n combinations = self._combinations(\n n_features,\n self.degree,\n self.include_interaction,\n self.interaction_only,\n self.include_bias,\n )\n self.n_input_features_ = n_features\n self.n_output_features_ = sum(1 for _ in combinations)\n return self\n\n def transform(self, X):\n \"\"\"Transform data to polynomial features.\n\n Parameters\n ----------\n X : array-like or CSR/CSC sparse matrix, shape [n_samples, n_features]\n The data to transform, row by row.\n Prefer CSR over CSC for sparse input (for speed), but CSC is\n required if the degree is 4 or higher. If the degree is less than\n 4 and the input format is CSC, it will be converted to CSR, have\n its polynomial features generated, then converted back to CSC.\n If the degree is 2 or 3, the method described in \"Leveraging\n Sparsity to Speed Up Polynomial Feature Expansions of CSR Matrices\n Using K-Simplex Numbers\" by Andrew Nystrom and John Hughes is\n used, which is much faster than the method used on CSC input. For\n this reason, a CSC input will be converted to CSR, and the output\n will be converted back to CSC prior to being returned, hence the\n preference of CSR.\n\n Returns\n -------\n XP : np.ndarray or CSR/CSC sparse matrix, shape [n_samples, NP]\n The matrix of features, where NP is the number of polynomial\n features generated from the combination of inputs.\n\n \"\"\"\n check_is_fitted(self)\n\n X = check_array(X, order=\"F\", dtype=FLOAT_DTYPES, accept_sparse=(\"csr\", \"csc\"))\n\n n_samples, n_features = X.shape\n\n if n_features != self.n_input_features_:\n raise ValueError(\"X shape does not match training shape\")\n\n if sparse.isspmatrix_csr(X):\n if self.degree > 3:\n return self.transform(X.tocsc()).tocsr()\n to_stack = []\n if self.include_bias:\n to_stack.append(np.ones(shape=(n_samples, 1), dtype=X.dtype))\n to_stack.append(X)\n for deg in range(2, self.degree + 1):\n Xp_next = _csr_polynomial_expansion(\n X.data, X.indices, X.indptr, X.shape[1], self.interaction_only, deg,\n )\n if Xp_next is None:\n break\n to_stack.append(Xp_next)\n XP = sparse.hstack(to_stack, format=\"csr\")\n elif sparse.isspmatrix_csc(X) and self.degree < 4:\n return self.transform(X.tocsr()).tocsc()\n else:\n combinations = self._combinations(\n n_features,\n self.degree,\n self.include_interaction,\n self.interaction_only,\n self.include_bias,\n )\n if sparse.isspmatrix(X):\n columns = []\n for comb in combinations:\n if comb:\n out_col = 1\n for col_idx in comb:\n out_col = X[:, col_idx].multiply(out_col)\n columns.append(out_col)\n else:\n bias = sparse.csc_matrix(np.ones((X.shape[0], 1)))\n columns.append(bias)\n XP = sparse.hstack(columns, dtype=X.dtype).tocsc()\n else:\n XP = np.empty(\n (n_samples, self.n_output_features_),\n dtype=X.dtype,\n order=self.order,\n )\n for i, comb in enumerate(combinations):\n XP[:, i] = X[:, comb].prod(1)\n\n return XP\n" ]
[ [ "scipy.sparse.isspmatrix", "sklearn.preprocessing._csr_polynomial_expansion._csr_polynomial_expansion", "sklearn.utils.validation.check_is_fitted", "sklearn.utils.check_array", "numpy.empty", "numpy.ones", "numpy.bincount", "scipy.sparse.hstack", "scipy.sparse.isspmatrix_csr", "numpy.where", "scipy.sparse.isspmatrix_csc" ] ]
A-suozhang/aw_nas
[ "9feb24974c7b44592e22ee45b98e116603d06eba" ]
[ "aw_nas/rollout/ofa.py" ]
[ "\"\"\"\nDefinitions of mnasnet OFA rollout and search space.\n\"\"\"\n\nimport numpy as np\n\nfrom aw_nas import utils\nfrom aw_nas.rollout.base import Rollout\nfrom aw_nas.common import SearchSpace, genotype_from_str\n\n\nclass MNasNetOFASearchSpace(SearchSpace):\n NAME = \"ofa\"\n SCHEDULABLE_ATTRS = [\"width_choice\", \"depth_choice\", \"kernel_choice\"]\n\n def __init__(\n self,\n width_choice=(4, 5, 6),\n depth_choice=(4, 5, 6),\n kernel_choice=(3, 5, 7),\n num_cell_groups=[1, 4, 4, 4, 4, 4],\n expansions=[1, 6, 6, 6, 6, 6],\n schedule_cfg=None,\n ):\n super(MNasNetOFASearchSpace, self).__init__(schedule_cfg)\n self.genotype_type_name = \"MnasnetOFAGenotype\"\n\n self.num_cell_groups = num_cell_groups\n self.expansions = expansions\n\n self.block_names = sum(\n [[\"cell_{}\".format(i) for i in range(len(num_cell_groups))]]\n + [\n [\n \"cell_{}_block_{}\".format(i, j)\n for j in range(self.num_cell_groups[i])\n ]\n for i in range(len(num_cell_groups))\n ],\n [],\n )\n\n self.genotype_type = utils.namedtuple_with_defaults(\n self.genotype_type_name, self.block_names, []\n )\n self.width_choice = width_choice\n self.depth_choice = depth_choice\n self.kernel_choice = kernel_choice\n\n def __getstate__(self):\n state = super(MNasNetOFASearchSpace, self).__getstate__().copy()\n del state[\"genotype_type\"]\n return state\n\n def __setstate__(self, state):\n super(MNasNetOFASearchSpace, self).__setstate__(state)\n self.genotype_type = utils.namedtuple_with_defaults(\n self.genotype_type_name, self.block_names, []\n )\n\n def genotype(self, arch):\n geno_arch = arch[\"depth\"] + sum(\n [\n list(zip(channels, kernels))\n for channels, kernels in zip(arch[\"width\"], arch[\"kernel\"])\n ],\n [],\n )\n return self.genotype_type(**dict(zip(self.block_names, geno_arch)))\n\n def rollout_from_genotype(self, genotype):\n if isinstance(genotype, str):\n genotype = genotype_from_str(genotype, self)\n genotype_list = list(genotype._asdict().values())\n\n depth = genotype[:len(self.num_cell_groups)]\n width = []\n kernel = []\n ind = len(self.num_cell_groups)\n for i, max_depth in zip(depth, self.num_cell_groups):\n width_list = []\n kernel_list = []\n for j in range(max_depth):\n if j < i:\n try:\n width_list.append(genotype[ind][0])\n kernel_list.append(genotype[ind][1])\n except Exception:\n width_list.append(genotype[ind])\n kernel_list.append(3)\n ind += 1\n width.append(width_list)\n kernel.append(kernel_list)\n arch = {\"depth\": depth, \"width\": width, \"kernel\": kernel}\n return MNasNetOFARollout(arch, {}, self)\n\n def supported_rollout_types(self):\n return [\"ofa\"]\n\n def plot_arch(self, genotypes, filename, label, **kwargs):\n pass\n\n def random_sample(self):\n return MNasNetOFARollout(\n MNasNetOFARollout.random_sample_arch(\n self.expansions,\n self.num_cell_groups,\n self.width_choice,\n self.depth_choice,\n self.kernel_choice,\n ),\n info={},\n search_space=self,\n )\n\n def distance(self, arch1, arch2):\n pass\n\n\nclass MNasNetOFARollout(Rollout):\n NAME = \"ofa\"\n channel = None\n\n @property\n def depth(self):\n return self.arch[\"depth\"]\n\n @property\n def width(self):\n self.channel = self.arch[\"width\"]\n return self.channel\n\n @property\n def kernel(self):\n return self.arch[\"kernel\"]\n\n @classmethod\n def random_sample_arch(\n cls, num_channels, num_cell_groups, width_choice, depth_choice, kernel_choice\n ):\n arch = {}\n arch[\"depth\"] = np.min(\n [\n np.random.choice(depth_choice, size=len(num_cell_groups)),\n num_cell_groups,\n ],\n axis=0,\n ).tolist()\n arch[\"width\"] = [\n np.min(\n [np.random.choice(width_choice, size=c), [num_channels[i]] * c], axis=0\n ).tolist()\n for i, c in enumerate(num_cell_groups)\n ]\n arch[\"kernel\"] = [[3]] + [\n np.random.choice(kernel_choice, size=c).tolist() for c in num_cell_groups[1:]\n ]\n return arch\n" ]
[ [ "numpy.random.choice" ] ]
VandanaAgarwal/SlowFast
[ "7b1271089fbfc0b5a65bf0c322eb6ecfc0391b1d" ]
[ "slowfast/visualization/video_visualizer_colab.py" ]
[ "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\nimport itertools\nimport logging as log\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch\nfrom detectron2.utils.visualizer import Visualizer\n\nimport slowfast.utils.logging as logging\nfrom slowfast.utils.misc import get_class_names\n\n# VA edits begin\nimport face_recognition\nimport cv2 \nimport os\nfrom google.colab.patches import cv2_imshow\nfrom PIL import Image\n\ntrain_folder = '/content/SlowFastData/demo/AVA/face_recog'\ncount = 1 \n\nimages = []\nnames = []\nfor person in os.listdir(train_folder) :\n person_path = os.path.join(train_folder,person)\n\n for filename in os.listdir(person_path) :\n image_path = os.path.join(person_path, filename)\n curr = cv2.imread(image_path)\n images.append(curr)\n names.append(person) # + '_' + filename)\nprint(names)\n\ndef find_encodings(images) :\n encoded_list = []\n count = 1 \n for img, nm in zip(images, names) :\n print(nm)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n encodings = face_recognition.face_encodings(img)\n if encodings :\n encode = face_recognition.face_encodings(img)[0]\n else : continue\n encoded_list.append(encode)\n count += 1\n print('***************', len(encoded_list))\n return encoded_list\n\nencoding_known = find_encodings(images)\n# VA edits end\n\nlogger = logging.get_logger(__name__)\nlog.getLogger(\"matplotlib\").setLevel(log.ERROR)\n\n\ndef _create_text_labels(classes, scores, class_names, ground_truth=False):\n \"\"\"\n Create text labels.\n Args:\n classes (list[int]): a list of class ids for each example.\n scores (list[float] or None): list of scores for each example.\n class_names (list[str]): a list of class names, ordered by their ids.\n ground_truth (bool): whether the labels are ground truth.\n Returns:\n labels (list[str]): formatted text labels.\n \"\"\"\n try:\n labels = [class_names[i] for i in classes]\n except IndexError:\n logger.error(\"Class indices get out of range: {}\".format(classes))\n return None\n\n if ground_truth:\n labels = [\"[{}] {}\".format(\"GT\", label) for label in labels]\n elif scores is not None:\n assert len(classes) == len(scores)\n labels = [\n \"[{:.2f}] {}\".format(s, label) for s, label in zip(scores, labels)\n ]\n return labels\n\n\nclass ImgVisualizer(Visualizer):\n def __init__(self, img_rgb, meta, **kwargs):\n \"\"\"\n See https://github.com/facebookresearch/detectron2/blob/master/detectron2/utils/visualizer.py\n for more details.\n Args:\n img_rgb: a tensor or numpy array of shape (H, W, C), where H and W correspond to\n the height and width of the image respectively. C is the number of\n color channels. The image is required to be in RGB format since that\n is a requirement of the Matplotlib library. The image is also expected\n to be in the range [0, 255].\n meta (MetadataCatalog): image metadata.\n See https://github.com/facebookresearch/detectron2/blob/81d5a87763bfc71a492b5be89b74179bd7492f6b/detectron2/data/catalog.py#L90\n \"\"\"\n super(ImgVisualizer, self).__init__(img_rgb, meta, **kwargs)\n\n def draw_text(\n self,\n text,\n position,\n *,\n font_size=None,\n color=\"w\",\n horizontal_alignment=\"center\",\n vertical_alignment=\"bottom\",\n box_facecolor=\"black\",\n alpha=0.5,\n ):\n \"\"\"\n Draw text at the specified position.\n Args:\n text (str): the text to draw on image.\n position (list of 2 ints): the x,y coordinate to place the text.\n font_size (Optional[int]): font of the text. If not provided, a font size\n proportional to the image width is calculated and used.\n color (str): color of the text. Refer to `matplotlib.colors` for full list\n of formats that are accepted.\n horizontal_alignment (str): see `matplotlib.text.Text`.\n vertical_alignment (str): see `matplotlib.text.Text`.\n box_facecolor (str): color of the box wrapped around the text. Refer to\n `matplotlib.colors` for full list of formats that are accepted.\n alpha (float): transparency level of the box.\n \"\"\"\n if not font_size:\n font_size = self._default_font_size\n x, y = position\n self.output.ax.text(\n x,\n y,\n text,\n size=font_size * self.output.scale,\n family=\"monospace\",\n bbox={\n \"facecolor\": box_facecolor,\n \"alpha\": alpha,\n \"pad\": 0.7,\n \"edgecolor\": \"none\",\n },\n verticalalignment=vertical_alignment,\n horizontalalignment=horizontal_alignment,\n color=color,\n zorder=10,\n )\n\n def draw_multiple_text(\n self,\n text_ls,\n box_coordinate,\n *,\n top_corner=True,\n font_size=None,\n color=\"w\",\n box_facecolors=\"black\",\n alpha=0.5,\n ):\n \"\"\"\n Draw a list of text labels for some bounding box on the image.\n Args:\n text_ls (list of strings): a list of text labels.\n box_coordinate (tensor): shape (4,). The (x_left, y_top, x_right, y_bottom)\n coordinates of the box.\n top_corner (bool): If True, draw the text labels at (x_left, y_top) of the box.\n Else, draw labels at (x_left, y_bottom).\n font_size (Optional[int]): font of the text. If not provided, a font size\n proportional to the image width is calculated and used.\n color (str): color of the text. Refer to `matplotlib.colors` for full list\n of formats that are accepted.\n box_facecolors (str): colors of the box wrapped around the text. Refer to\n `matplotlib.colors` for full list of formats that are accepted.\n alpha (float): transparency level of the box.\n \"\"\"\n if not isinstance(box_facecolors, list):\n box_facecolors = [box_facecolors] * len(text_ls)\n assert len(box_facecolors) == len(\n text_ls\n ), \"Number of colors provided is not equal to the number of text labels.\"\n if not font_size:\n font_size = self._default_font_size\n text_box_width = font_size + font_size // 2\n # If the texts does not fit in the assigned location,\n # we split the text and draw it in another place.\n if top_corner:\n num_text_split = self._align_y_top(\n box_coordinate, len(text_ls), text_box_width\n )\n y_corner = 1\n else:\n num_text_split = len(text_ls) - self._align_y_bottom(\n box_coordinate, len(text_ls), text_box_width\n )\n y_corner = 3\n\n text_color_sorted = sorted(\n zip(text_ls, box_facecolors), key=lambda x: x[0], reverse=True\n )\n if len(text_color_sorted) != 0:\n text_ls, box_facecolors = zip(*text_color_sorted)\n else:\n text_ls, box_facecolors = [], []\n text_ls, box_facecolors = list(text_ls), list(box_facecolors)\n self.draw_multiple_text_upward(\n text_ls[:num_text_split][::-1],\n box_coordinate,\n y_corner=y_corner,\n font_size=font_size,\n color=color,\n box_facecolors=box_facecolors[:num_text_split][::-1],\n alpha=alpha,\n )\n self.draw_multiple_text_downward(\n text_ls[num_text_split:],\n box_coordinate,\n y_corner=y_corner,\n font_size=font_size,\n color=color,\n box_facecolors=box_facecolors[num_text_split:],\n alpha=alpha,\n )\n\n def draw_multiple_text_upward(\n self,\n text_ls,\n box_coordinate,\n *,\n y_corner=1,\n font_size=None,\n color=\"w\",\n box_facecolors=\"black\",\n alpha=0.5,\n ):\n \"\"\"\n Draw a list of text labels for some bounding box on the image in upward direction.\n The next text label will be on top of the previous one.\n Args:\n text_ls (list of strings): a list of text labels.\n box_coordinate (tensor): shape (4,). The (x_left, y_top, x_right, y_bottom)\n coordinates of the box.\n y_corner (int): Value of either 1 or 3. Indicate the index of the y-coordinate of\n the box to draw labels around.\n font_size (Optional[int]): font of the text. If not provided, a font size\n proportional to the image width is calculated and used.\n color (str): color of the text. Refer to `matplotlib.colors` for full list\n of formats that are accepted.\n box_facecolors (str or list of strs): colors of the box wrapped around the text. Refer to\n `matplotlib.colors` for full list of formats that are accepted.\n alpha (float): transparency level of the box.\n \"\"\"\n if not isinstance(box_facecolors, list):\n box_facecolors = [box_facecolors] * len(text_ls)\n assert len(box_facecolors) == len(\n text_ls\n ), \"Number of colors provided is not equal to the number of text labels.\"\n\n assert y_corner in [1, 3], \"Y_corner must be either 1 or 3\"\n if not font_size:\n font_size = self._default_font_size\n\n x, horizontal_alignment = self._align_x_coordinate(box_coordinate)\n y = box_coordinate[y_corner].item()\n for i, text in enumerate(text_ls):\n self.draw_text(\n text,\n (x, y),\n font_size=font_size,\n color=color,\n horizontal_alignment=horizontal_alignment,\n vertical_alignment=\"bottom\",\n box_facecolor=box_facecolors[i],\n alpha=alpha,\n )\n y -= font_size + font_size // 2\n\n def draw_multiple_text_downward(\n self,\n text_ls,\n box_coordinate,\n *,\n y_corner=1,\n font_size=None,\n color=\"w\",\n box_facecolors=\"black\",\n alpha=0.5,\n ):\n \"\"\"\n Draw a list of text labels for some bounding box on the image in downward direction.\n The next text label will be below the previous one.\n Args:\n text_ls (list of strings): a list of text labels.\n box_coordinate (tensor): shape (4,). The (x_left, y_top, x_right, y_bottom)\n coordinates of the box.\n y_corner (int): Value of either 1 or 3. Indicate the index of the y-coordinate of\n the box to draw labels around.\n font_size (Optional[int]): font of the text. If not provided, a font size\n proportional to the image width is calculated and used.\n color (str): color of the text. Refer to `matplotlib.colors` for full list\n of formats that are accepted.\n box_facecolors (str): colors of the box wrapped around the text. Refer to\n `matplotlib.colors` for full list of formats that are accepted.\n alpha (float): transparency level of the box.\n \"\"\"\n if not isinstance(box_facecolors, list):\n box_facecolors = [box_facecolors] * len(text_ls)\n assert len(box_facecolors) == len(\n text_ls\n ), \"Number of colors provided is not equal to the number of text labels.\"\n\n assert y_corner in [1, 3], \"Y_corner must be either 1 or 3\"\n if not font_size:\n font_size = self._default_font_size\n\n x, horizontal_alignment = self._align_x_coordinate(box_coordinate)\n y = box_coordinate[y_corner].item()\n for i, text in enumerate(text_ls):\n self.draw_text(\n text,\n (x, y),\n font_size=font_size,\n color=color,\n horizontal_alignment=horizontal_alignment,\n vertical_alignment=\"top\",\n box_facecolor=box_facecolors[i],\n alpha=alpha,\n )\n y += font_size + font_size // 2\n\n def _align_x_coordinate(self, box_coordinate):\n \"\"\"\n Choose an x-coordinate from the box to make sure the text label\n does not go out of frames. By default, the left x-coordinate is\n chosen and text is aligned left. If the box is too close to the\n right side of the image, then the right x-coordinate is chosen\n instead and the text is aligned right.\n Args:\n box_coordinate (array-like): shape (4,). The (x_left, y_top, x_right, y_bottom)\n coordinates of the box.\n Returns:\n x_coordinate (float): the chosen x-coordinate.\n alignment (str): whether to align left or right.\n \"\"\"\n # If the x-coordinate is greater than 5/6 of the image width,\n # then we align test to the right of the box. This is\n # chosen by heuristics.\n if box_coordinate[0] > (self.output.width * 5) // 6:\n return box_coordinate[2], \"right\"\n\n return box_coordinate[0], \"left\"\n\n def _align_y_top(self, box_coordinate, num_text, textbox_width):\n \"\"\"\n Calculate the number of text labels to plot on top of the box\n without going out of frames.\n Args:\n box_coordinate (array-like): shape (4,). The (x_left, y_top, x_right, y_bottom)\n coordinates of the box.\n num_text (int): the number of text labels to plot.\n textbox_width (float): the width of the box wrapped around text label.\n \"\"\"\n dist_to_top = box_coordinate[1]\n num_text_top = dist_to_top // textbox_width\n\n if isinstance(num_text_top, torch.Tensor):\n num_text_top = int(num_text_top.item())\n\n return min(num_text, num_text_top)\n\n def _align_y_bottom(self, box_coordinate, num_text, textbox_width):\n \"\"\"\n Calculate the number of text labels to plot at the bottom of the box\n without going out of frames.\n Args:\n box_coordinate (array-like): shape (4,). The (x_left, y_top, x_right, y_bottom)\n coordinates of the box.\n num_text (int): the number of text labels to plot.\n textbox_width (float): the width of the box wrapped around text label.\n \"\"\"\n dist_to_bottom = self.output.height - box_coordinate[3]\n num_text_bottom = dist_to_bottom // textbox_width\n\n if isinstance(num_text_bottom, torch.Tensor):\n num_text_bottom = int(num_text_bottom.item())\n\n return min(num_text, num_text_bottom)\n\n\nclass VideoVisualizer:\n def __init__(\n self,\n num_classes,\n class_names_path,\n top_k=1,\n colormap=\"rainbow\",\n thres=0.7,\n lower_thres=0.3,\n common_class_names=None,\n mode=\"top-k\",\n ):\n \"\"\"\n Args:\n num_classes (int): total number of classes.\n class_names_path (str): path to json file that maps class names to ids.\n Must be in the format {classname: id}.\n top_k (int): number of top predicted classes to plot.\n colormap (str): the colormap to choose color for class labels from.\n See https://matplotlib.org/tutorials/colors/colormaps.html\n thres (float): threshold for picking predicted classes to visualize.\n lower_thres (Optional[float]): If `common_class_names` if given,\n this `lower_thres` will be applied to uncommon classes and\n `thres` will be applied to classes in `common_class_names`.\n common_class_names (Optional[list of str(s)]): list of common class names\n to apply `thres`. Class names not included in `common_class_names` will\n have `lower_thres` as a threshold. If None, all classes will have `thres` as a threshold.\n This is helpful for model trained on highly imbalanced dataset.\n mode (str): Supported modes are {\"top-k\", \"thres\"}.\n This is used for choosing predictions for visualization.\n\n \"\"\"\n assert mode in [\"top-k\", \"thres\"], \"Mode {} is not supported.\".format(\n mode\n )\n self.mode = mode\n self.num_classes = num_classes\n self.class_names, _, _ = get_class_names(class_names_path, None, None)\n self.top_k = top_k\n self.thres = thres\n self.lower_thres = lower_thres\n\n if mode == \"thres\":\n self._get_thres_array(common_class_names=common_class_names)\n\n self.color_map = plt.get_cmap(colormap)\n\n def _get_color(self, class_id):\n \"\"\"\n Get color for a class id.\n Args:\n class_id (int): class id.\n \"\"\"\n return self.color_map(class_id / self.num_classes)[:3]\n\n def draw_one_frame(\n self,\n frame,\n preds,\n bboxes=None,\n alpha=0.5,\n text_alpha=0.7,\n ground_truth=False,\n ):\n \"\"\"\n Draw labels and bouding boxes for one image. By default, predicted labels are drawn in\n the top left corner of the image or corresponding bounding boxes. For ground truth labels\n (setting True for ground_truth flag), labels will be drawn in the bottom left corner.\n Args:\n frame (array-like): a tensor or numpy array of shape (H, W, C), where H and W correspond to\n the height and width of the image respectively. C is the number of\n color channels. The image is required to be in RGB format since that\n is a requirement of the Matplotlib library. The image is also expected\n to be in the range [0, 255].\n preds (tensor or list): If ground_truth is False, provide a float tensor of shape (num_boxes, num_classes)\n that contains all of the confidence scores of the model.\n For recognition task, input shape can be (num_classes,). To plot true label (ground_truth is True),\n preds is a list contains int32 of the shape (num_boxes, true_class_ids) or (true_class_ids,).\n bboxes (Optional[tensor]): shape (num_boxes, 4) that contains the coordinates of the bounding boxes.\n alpha (Optional[float]): transparency level of the bounding boxes.\n text_alpha (Optional[float]): transparency level of the box wrapped around text labels.\n ground_truth (bool): whether the prodived bounding boxes are ground-truth.\n \"\"\"\n if isinstance(preds, torch.Tensor):\n if preds.ndim == 1:\n preds = preds.unsqueeze(0)\n n_instances = preds.shape[0]\n elif isinstance(preds, list):\n n_instances = len(preds)\n else:\n logger.error(\"Unsupported type of prediction input.\")\n return\n\n if ground_truth:\n top_scores, top_classes = [None] * n_instances, preds\n\n elif self.mode == \"top-k\":\n top_scores, top_classes = torch.topk(preds, k=self.top_k)\n top_scores, top_classes = top_scores.tolist(), top_classes.tolist()\n elif self.mode == \"thres\":\n top_scores, top_classes = [], []\n for pred in preds:\n mask = pred >= self.thres\n top_scores.append(pred[mask].tolist())\n top_class = torch.squeeze(torch.nonzero(mask), dim=-1).tolist()\n top_classes.append(top_class)\n\n # Create labels top k predicted classes with their scores.\n text_labels = []\n for i in range(n_instances):\n text_labels.append(\n _create_text_labels(\n top_classes[i],\n top_scores[i],\n self.class_names,\n ground_truth=ground_truth,\n )\n )\n frame_visualizer = ImgVisualizer(frame, meta=None)\n font_size = min(\n max(np.sqrt(frame.shape[0] * frame.shape[1]) // 35, 5), 9\n )\n top_corner = not ground_truth\n\n # VA edits begin\n ftemp = open('/content/SlowFast/slowfast/visualization/labels.txt', 'a')\n # VA edits end\n\n if bboxes is not None:\n assert len(preds) == len(\n bboxes\n ), \"Encounter {} predictions and {} bounding boxes\".format(\n len(preds), len(bboxes)\n )\n # VA edits begin\n global count\n # VA edits end\n for i, box in enumerate(bboxes):\n text = text_labels[i]\n\n # VA edits begin\n print('@@@@@@@@@', file=ftemp) ;print('@@@@@@@@@')\n print(text, box, file=ftemp) ;print(text, box)\n '''\n box_coord (tuple): a tuple containing x0, y0, x1, y1 coordinates, where x0 and y0\n are the coordinates of the image's top left corner. x1 and y1 are the\n coordinates of the image's bottom right corner.\n\n box --> x0, y0, x1, y1 = box_coord\n width = x1 - x0\n height = y1 - y0\n '''\n\n x0, y0, x1, y1 = box\n x0 = int(x0.item())\n x1 = int(x1.item())\n y0 = int(y0.item())\n y1 = int(y1.item())\n print('\\n\\nFrame no ---> {0}'.format(count))\n print('!!!!!!!!!!!!---', x0, x1, y0, y1, 'frame sh--->', frame.shape, file=ftemp)\n print('!!!!!!!!!!!!---', x0, x1, y0, y1, 'frame sh--->', frame.shape)\n body = frame[y0:y1, x0:x1]\n\n body_file = \"/content/SlowFast/slowfast/visualization/body\" + str(count) + '.jpg'\n im = Image.fromarray(body)\n im.save(body_file)\n print('\\n\\nSAVING IMAGE to ---> {0}\\n\\ns'.format(body_file))\n count += 1\n #cv2_imshow(body)\n\n img = cv2.resize(body, (0,0), None, 0.5, 0.5)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n faces_current = face_recognition.face_locations(img)\n print('no of faces---', len(faces_current), file=ftemp)\n print('no of faces---', len(faces_current))\n encode_current = face_recognition.face_encodings(img, faces_current)\n print('created encoding')\n\n if len(faces_current) == 1 : input('FOUND FACE...')\n boundaries = []\n person_names = []\n for encodeF, faceLoc in zip(encode_current, faces_current):\n print('---------------------------------', file=ftemp)\n print('---------------------------------')\n matches = face_recognition.compare_faces(encoding_known, encodeF, tolerance=0.5)\n #print(matches)\n #input()\n face_dis = face_recognition.face_distance(encoding_known, encodeF)\n #print(face_dis)\n #input()\n matched_index = np.argmin(face_dis)\n print(matched_index, file=ftemp)\n print(matches[matched_index], file=ftemp)\n\n if matches[matched_index]:\n name = names[matched_index].upper()\n else :\n name = 'unknown'\n\n print(name, file=ftemp) ; print(name)\n top, right, bottom, left = faceLoc\n bndry = left, top, right, bottom\n boundaries.append(bndry)\n person_names.append(name)\n\n for bndry, person in zip(boundaries, person_names) :\n cv2.rectangle(img, (bndry[0], bndry[1]), (bndry[2], bndry[3]), (0, 255, 0), 5)\n cv2.putText(img, person, (bndry[0], bndry[1] - 20), cv2.FONT_HERSHEY_DUPLEX, 1.0, (0, 255, 0), 2)\n\n #plt.imshow(img)\n #plt.show()\n print('@@@@@@@@@', file=ftemp) ;print('@@@@@@@@@')\n # VA edits end\n\n pred_class = top_classes[i]\n colors = [self._get_color(pred) for pred in pred_class]\n\n box_color = \"r\" if ground_truth else \"g\"\n line_style = \"--\" if ground_truth else \"-.\"\n frame_visualizer.draw_box(\n box,\n alpha=alpha,\n edge_color=box_color,\n line_style=line_style,\n )\n frame_visualizer.draw_multiple_text(\n text,\n box,\n top_corner=top_corner,\n font_size=font_size,\n box_facecolors=colors,\n alpha=text_alpha,\n )\n else:\n text = text_labels[0]\n pred_class = top_classes[0]\n colors = [self._get_color(pred) for pred in pred_class]\n frame_visualizer.draw_multiple_text(\n text,\n torch.Tensor([0, 5, frame.shape[1], frame.shape[0] - 5]),\n top_corner=top_corner,\n font_size=font_size,\n box_facecolors=colors,\n alpha=text_alpha,\n )\n\n return frame_visualizer.output.get_image()\n\n def draw_clip_range(\n self,\n frames,\n preds,\n bboxes=None,\n text_alpha=0.5,\n ground_truth=False,\n keyframe_idx=None,\n draw_range=None,\n repeat_frame=1,\n ):\n \"\"\"\n Draw predicted labels or ground truth classes to clip. Draw bouding boxes to clip\n if bboxes is provided. Boxes will gradually fade in and out the clip, centered around\n the clip's central frame, within the provided `draw_range`.\n Args:\n frames (array-like): video data in the shape (T, H, W, C).\n preds (tensor): a tensor of shape (num_boxes, num_classes) that contains all of the confidence scores\n of the model. For recognition task or for ground_truth labels, input shape can be (num_classes,).\n bboxes (Optional[tensor]): shape (num_boxes, 4) that contains the coordinates of the bounding boxes.\n text_alpha (float): transparency label of the box wrapped around text labels.\n ground_truth (bool): whether the prodived bounding boxes are ground-truth.\n keyframe_idx (int): the index of keyframe in the clip.\n draw_range (Optional[list[ints]): only draw frames in range [start_idx, end_idx] inclusively in the clip.\n If None, draw on the entire clip.\n repeat_frame (int): repeat each frame in draw_range for `repeat_frame` time for slow-motion effect.\n \"\"\"\n if draw_range is None:\n draw_range = [0, len(frames) - 1]\n if draw_range is not None:\n draw_range[0] = max(0, draw_range[0])\n left_frames = frames[: draw_range[0]]\n right_frames = frames[draw_range[1] + 1 :]\n\n draw_frames = frames[draw_range[0] : draw_range[1] + 1]\n if keyframe_idx is None:\n keyframe_idx = len(frames) // 2\n\n img_ls = (\n list(left_frames)\n + self.draw_clip(\n draw_frames,\n preds,\n bboxes=bboxes,\n text_alpha=text_alpha,\n ground_truth=ground_truth,\n keyframe_idx=keyframe_idx - draw_range[0],\n repeat_frame=repeat_frame,\n )\n + list(right_frames)\n )\n\n return img_ls\n\n def draw_clip(\n self,\n frames,\n preds,\n bboxes=None,\n text_alpha=0.5,\n ground_truth=False,\n keyframe_idx=None,\n repeat_frame=1,\n ):\n \"\"\"\n Draw predicted labels or ground truth classes to clip. Draw bouding boxes to clip\n if bboxes is provided. Boxes will gradually fade in and out the clip, centered around\n the clip's central frame.\n Args:\n frames (array-like): video data in the shape (T, H, W, C).\n preds (tensor): a tensor of shape (num_boxes, num_classes) that contains all of the confidence scores\n of the model. For recognition task or for ground_truth labels, input shape can be (num_classes,).\n bboxes (Optional[tensor]): shape (num_boxes, 4) that contains the coordinates of the bounding boxes.\n text_alpha (float): transparency label of the box wrapped around text labels.\n ground_truth (bool): whether the prodived bounding boxes are ground-truth.\n keyframe_idx (int): the index of keyframe in the clip.\n repeat_frame (int): repeat each frame in draw_range for `repeat_frame` time for slow-motion effect.\n \"\"\"\n assert repeat_frame >= 1, \"`repeat_frame` must be a positive integer.\"\n\n repeated_seq = range(0, len(frames))\n repeated_seq = list(\n itertools.chain.from_iterable(\n itertools.repeat(x, repeat_frame) for x in repeated_seq\n )\n )\n\n frames, adjusted = self._adjust_frames_type(frames)\n if keyframe_idx is None:\n half_left = len(repeated_seq) // 2\n half_right = (len(repeated_seq) + 1) // 2\n else:\n mid = int((keyframe_idx / len(frames)) * len(repeated_seq))\n half_left = mid\n half_right = len(repeated_seq) - mid\n\n alpha_ls = np.concatenate(\n [\n np.linspace(0, 1, num=half_left),\n np.linspace(1, 0, num=half_right),\n ]\n )\n text_alpha = text_alpha\n frames = frames[repeated_seq]\n img_ls = []\n for alpha, frame in zip(alpha_ls, frames):\n draw_img = self.draw_one_frame(\n frame,\n preds,\n bboxes,\n alpha=alpha,\n text_alpha=text_alpha,\n ground_truth=ground_truth,\n )\n if adjusted:\n draw_img = draw_img.astype(\"float32\") / 255\n\n img_ls.append(draw_img)\n\n return img_ls\n\n def _adjust_frames_type(self, frames):\n \"\"\"\n Modify video data to have dtype of uint8 and values range in [0, 255].\n Args:\n frames (array-like): 4D array of shape (T, H, W, C).\n Returns:\n frames (list of frames): list of frames in range [0, 1].\n adjusted (bool): whether the original frames need adjusted.\n \"\"\"\n assert (\n frames is not None and len(frames) != 0\n ), \"Frames does not contain any values\"\n frames = np.array(frames)\n assert np.array(frames).ndim == 4, \"Frames must have 4 dimensions\"\n adjusted = False\n if frames.dtype in [np.float32, np.float64]:\n frames *= 255\n frames = frames.astype(np.uint8)\n adjusted = True\n\n return frames, adjusted\n\n def _get_thres_array(self, common_class_names=None):\n \"\"\"\n Compute a thresholds array for all classes based on `self.thes` and `self.lower_thres`.\n Args:\n common_class_names (Optional[list of strs]): a list of common class names.\n \"\"\"\n common_class_ids = []\n if common_class_names is not None:\n common_classes = set(common_class_names)\n\n for i, name in enumerate(self.class_names):\n if name in common_classes:\n common_class_ids.append(i)\n else:\n common_class_ids = list(range(self.num_classes))\n\n thres_array = np.full(\n shape=(self.num_classes,), fill_value=self.lower_thres\n )\n thres_array[common_class_ids] = self.thres\n self.thres = torch.from_numpy(thres_array)\n" ]
[ [ "numpy.sqrt", "torch.Tensor", "numpy.linspace", "torch.from_numpy", "matplotlib.pyplot.get_cmap", "numpy.full", "numpy.argmin", "torch.nonzero", "torch.topk", "numpy.array" ] ]
zergmk2/tf_ctpn
[ "f0f20606b3a2e58819cb330ede52b1d9e2c21d31" ]
[ "lib/layer_utils/proposal_layer.py" ]
[ "# --------------------------------------------------------\n# Faster R-CNN\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Ross Girshick and Xinlei Chen\n# --------------------------------------------------------\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nfrom model.config import cfg\nfrom model.bbox_transform import bbox_transform_inv, clip_boxes\nfrom model.nms_wrapper import nms\n\n\ndef proposal_layer(rpn_cls_prob, rpn_bbox_pred, im_info, cfg_key, anchors, num_anchors):\n \"\"\"\n A simplified version compared to fast/er RCNN\n For details please see the technical report\n :param\n rpn_cls_prob: (1, H, W, Ax2) softmax result of rpn scores\n rpn_bbox_pred: (1, H, W, Ax4) 1x1 conv result for rpn bbox\n \"\"\"\n if type(cfg_key) == bytes:\n cfg_key = cfg_key.decode('utf-8')\n pre_nms_topN = cfg[cfg_key].RPN_PRE_NMS_TOP_N\n post_nms_topN = cfg[cfg_key].RPN_POST_NMS_TOP_N\n nms_thresh = cfg[cfg_key].RPN_NMS_THRESH\n\n # Get the scores and bounding boxes for foreground (text)\n # The order in last dim is related to network.py:\n # self._reshape_layer(rpn_cls_prob_reshape, self._num_anchors * 2, \"rpn_cls_prob\")\n # scores = rpn_cls_prob[:, :, :, num_anchors:] # old\n\n height, width = rpn_cls_prob.shape[1:3] # feature-map的高宽\n scores = np.reshape(np.reshape(rpn_cls_prob, [1, height, width, num_anchors, 2])[:, :, :, :, 1],\n [1, height, width, num_anchors])\n\n rpn_bbox_pred = rpn_bbox_pred.reshape((-1, 4))\n scores = scores.reshape((-1, 1))\n proposals = bbox_transform_inv(anchors, rpn_bbox_pred)\n proposals = clip_boxes(proposals, im_info[:2])\n\n # Pick the top region proposals\n order = scores.ravel().argsort()[::-1]\n if pre_nms_topN > 0:\n order = order[:pre_nms_topN]\n proposals = proposals[order, :]\n scores = scores[order]\n\n # Non-maximal suppression\n keep = nms(np.hstack((proposals, scores)), nms_thresh, not cfg.USE_GPU_NMS)\n\n # Pick th top region proposals after NMS\n if post_nms_topN > 0:\n keep = keep[:post_nms_topN]\n proposals = proposals[keep, :]\n scores = scores[keep]\n\n # Only support single image as input\n blob = np.hstack((scores.astype(np.float32, copy=False), proposals.astype(np.float32, copy=False)))\n return blob, scores\n" ]
[ [ "numpy.reshape", "numpy.hstack" ] ]
0xNaN/tinygrad
[ "4bdb524da7696e47cec02a211a1829c14b434cda" ]
[ "tinygrad/gradcheck.py" ]
[ "import numpy as np\n\nfrom tinygrad.utils import mask_like\nfrom tinygrad.tensor import Tensor\n\ndef jacobian(func, input):\n output = func(input)\n\n ji = input.data.reshape(-1).shape[-1]\n jo = output.data.reshape(-1).shape[-1]\n J = np.zeros((jo,ji))\n\n for o in range(jo):\n # tinygrad doesn't support slicing, tiny-hack to select\n # the needed scalar an backpropagate only through it\n o_scalar = Tensor(mask_like(output.data, o, 1.)).mul(output).sum()\n o_scalar.backward()\n\n for i, grad in enumerate(input.grad.reshape(-1)):\n J[o,i] = grad\n return J\n\ndef numerical_jacobian(func, input, eps = 1e-6):\n output = func(input)\n\n ji = input.data.reshape(-1).shape[-1]\n jo = output.data.reshape(-1).shape[-1]\n NJ = np.zeros((jo, ji))\n\n for o in range(jo):\n for i in range(ji):\n\n eps_perturb = mask_like(input.data, i, mask_value = eps)\n output_perturb_add = func(Tensor(input.data + eps_perturb)).data.reshape(-1)[o]\n output_perturb_sub = func(Tensor(input.data - eps_perturb)).data.reshape(-1)[o]\n\n grad_approx = ((output_perturb_add) - (output_perturb_sub)) / (2*eps)\n\n NJ[o,i] = grad_approx\n return NJ\n\ndef gradcheck(func, input, eps = 1e-06, atol = 1e-5, rtol = 0.001):\n NJ = numerical_jacobian(func, input, eps)\n J = jacobian(func, input)\n return np.allclose(J, NJ, atol=atol, rtol=rtol)\n" ]
[ [ "numpy.zeros", "numpy.allclose" ] ]
MathiasPede/Fast-Time-Series-Clustering
[ "dc2d01fe3cfd57a80ba2a1f10d0fc00eaed05f09" ]
[ "tests/singular_values_test.py" ]
[ "import numpy as np\n\nfrom math import floor\nfrom ftsc.singular_values import calculate_best_relative_error_for_all_ranks, calculate_best_relative_error_rank\nfrom tests.plotting_utils import scatter_plot, multiple_scatter_plot\nfrom tests.tests_utils import get_singular_values, get_all_test_dataset_names\n\n\ndef run_best_error_plot(data_name, max=None):\n sing_vals_dtw = get_singular_values(data_name, \"dtw\")\n sing_vals_msm = get_singular_values(data_name, \"msm\")\n sing_vals_ed = get_singular_values(data_name, \"ed\")\n\n if max is None or max > len(sing_vals_dtw):\n max = floor(0.99 * len(sing_vals_dtw))\n\n xas = np.arange(0, max)\n error_dtw = calculate_best_relative_error_for_all_ranks(sing_vals_dtw)[0:max]\n error_msm = calculate_best_relative_error_for_all_ranks(sing_vals_msm)[0:max]\n error_ed = calculate_best_relative_error_for_all_ranks(sing_vals_ed)[0:max]\n\n multiple_scatter_plot((error_dtw, error_msm, error_ed), (xas, xas, xas), colors=[\"blue\", \"red\", \"green\"],\n labels=[\"DTW\", \"MSM\", \"ED\"], xname=\"Rang $k$ van de benadering\",\n yname=\"Relatieve fout $\\eta$\",\n title=\"Beste relatieve fout voor benaderingsrang \" + data_name, marker='o')\n\n\ndef run_singular_values_plot(data_name, func_name, max=None):\n sing_vals = get_singular_values(data_name, \"dtw\")\n\n if max is None:\n max = floor(0.99 * len(sing_vals))\n xas = np.arange(0, max)\n scatter_plot(sing_vals[0:max], xas, yname=\"Singuliere waarden $\\sigma_i$\", xname=\"Index $i$\",\n title=\"Singuliere waarden van \" + func_name + \" matrix \" + data_name, marker='o')\n\n\nif __name__ == '__main__':\n func_name = \"ed\"\n\n # Singular values and errors for 1 dataset\n name = \"Crop\"\n run_singular_values_plot(name, func_name)\n run_best_error_plot(name, max=None)\n\n # Compare all dataset error for certain ranks\n all_datasets = get_all_test_dataset_names()\n size = len(all_datasets)\n ranks = [20, 50, 100, 200]\n\n errors = np.zeros(shape=(size, len(ranks)))\n\n for i in range(size):\n name = all_datasets[i]\n sing_vals = get_singular_values(name, func_name)\n for j in range(len(ranks)):\n errors[i, j] = calculate_best_relative_error_rank(sing_vals, ranks[j])\n\n averages = np.average(errors, axis=0)\n stds = np.std(errors, axis=0)\n max = np.max(errors, axis=0)\n" ]
[ [ "numpy.arange", "numpy.std", "numpy.average", "numpy.max" ] ]
alzaia/improving_neural_nets_python
[ "52cc9c88d895e87d8024e36b86776f644e629634" ]
[ "utils/opt_utils.py" ]
[ "\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport h5py\nimport scipy.io\nimport sklearn\nimport sklearn.datasets\n\ndef sigmoid(x):\n s = 1/(1+np.exp(-x))\n return s\n\ndef relu(x):\n s = np.maximum(0,x)\n return s\n\ndef load_params_and_grads(seed=1):\n np.random.seed(seed)\n W1 = np.random.randn(2,3)\n b1 = np.random.randn(2,1)\n W2 = np.random.randn(3,3)\n b2 = np.random.randn(3,1)\n\n dW1 = np.random.randn(2,3)\n db1 = np.random.randn(2,1)\n dW2 = np.random.randn(3,3)\n db2 = np.random.randn(3,1)\n \n return W1, b1, W2, b2, dW1, db1, dW2, db2\n\n\ndef initialize_parameters(layer_dims):\n\n np.random.seed(3)\n parameters = {}\n L = len(layer_dims) # number of layers in the network\n\n for l in range(1, L):\n parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l-1])* np.sqrt(2 / layer_dims[l-1])\n parameters['b' + str(l)] = np.zeros((layer_dims[l], 1))\n \n assert(parameters['W' + str(l)].shape == layer_dims[l], layer_dims[l-1])\n assert(parameters['W' + str(l)].shape == layer_dims[l], 1)\n \n return parameters\n\n\ndef compute_cost(a3, Y):\n\n m = Y.shape[1]\n \n logprobs = np.multiply(-np.log(a3),Y) + np.multiply(-np.log(1 - a3), 1 - Y)\n cost = 1./m * np.sum(logprobs)\n \n return cost\n\ndef forward_propagation(X, parameters):\n \n # retrieve parameters\n W1 = parameters[\"W1\"]\n b1 = parameters[\"b1\"]\n W2 = parameters[\"W2\"]\n b2 = parameters[\"b2\"]\n W3 = parameters[\"W3\"]\n b3 = parameters[\"b3\"]\n \n # LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID\n z1 = np.dot(W1, X) + b1\n a1 = relu(z1)\n z2 = np.dot(W2, a1) + b2\n a2 = relu(z2)\n z3 = np.dot(W3, a2) + b3\n a3 = sigmoid(z3)\n \n cache = (z1, a1, W1, b1, z2, a2, W2, b2, z3, a3, W3, b3)\n \n return a3, cache\n\ndef backward_propagation(X, Y, cache):\n\n m = X.shape[1]\n (z1, a1, W1, b1, z2, a2, W2, b2, z3, a3, W3, b3) = cache\n \n dz3 = 1./m * (a3 - Y)\n dW3 = np.dot(dz3, a2.T)\n db3 = np.sum(dz3, axis=1, keepdims = True)\n \n da2 = np.dot(W3.T, dz3)\n dz2 = np.multiply(da2, np.int64(a2 > 0))\n dW2 = np.dot(dz2, a1.T)\n db2 = np.sum(dz2, axis=1, keepdims = True)\n \n da1 = np.dot(W2.T, dz2)\n dz1 = np.multiply(da1, np.int64(a1 > 0))\n dW1 = np.dot(dz1, X.T)\n db1 = np.sum(dz1, axis=1, keepdims = True)\n \n gradients = {\"dz3\": dz3, \"dW3\": dW3, \"db3\": db3,\n \"da2\": da2, \"dz2\": dz2, \"dW2\": dW2, \"db2\": db2,\n \"da1\": da1, \"dz1\": dz1, \"dW1\": dW1, \"db1\": db1}\n \n return gradients\n\ndef predict(X, y, parameters):\n \n m = X.shape[1]\n p = np.zeros((1,m), dtype = np.int)\n \n # Forward propagation\n a3, caches = forward_propagation(X, parameters)\n \n # convert probas to 0/1 predictions\n for i in range(0, a3.shape[1]):\n if a3[0,i] > 0.5:\n p[0,i] = 1\n else:\n p[0,i] = 0\n\n # print results\n\n #print (\"predictions: \" + str(p[0,:]))\n #print (\"true labels: \" + str(y[0,:]))\n print(\"Accuracy: \" + str(np.mean((p[0,:] == y[0,:]))))\n \n return p\n\ndef load_2D_dataset():\n data = scipy.io.loadmat('datasets/data.mat')\n train_X = data['X'].T\n train_Y = data['y'].T\n test_X = data['Xval'].T\n test_Y = data['yval'].T\n\n plt.scatter(train_X[0, :], train_X[1, :], c=train_Y, s=40, cmap=plt.cm.Spectral);\n \n return train_X, train_Y, test_X, test_Y\n\ndef plot_decision_boundary(model, X, y):\n # Set min and max values and give it some padding\n x_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1\n y_min, y_max = X[1, :].min() - 1, X[1, :].max() + 1\n h = 0.01\n # Generate a grid of points with distance h between them\n xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\n # Predict the function value for the whole grid\n Z = model(np.c_[xx.ravel(), yy.ravel()])\n Z = Z.reshape(xx.shape)\n # Plot the contour and training examples\n plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)\n plt.ylabel('x2')\n plt.xlabel('x1')\n plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral)\n plt.show()\n \ndef predict_dec(parameters, X):\n \n # Predict using forward propagation and a classification threshold of 0.5\n a3, cache = forward_propagation(X, parameters)\n predictions = (a3 > 0.5)\n return predictions\n\ndef load_dataset():\n np.random.seed(3)\n train_X, train_Y = sklearn.datasets.make_moons(n_samples=300, noise=.2) #300 #0.2 \n # Visualize the data\n plt.scatter(train_X[:, 0], train_X[:, 1], c=train_Y, s=40, cmap=plt.cm.Spectral);\n train_X = train_X.T\n train_Y = train_Y.reshape((1, train_Y.shape[0]))\n \n return train_X, train_Y" ]
[ [ "numpy.dot", "numpy.log", "matplotlib.pyplot.contourf", "numpy.maximum", "numpy.sqrt", "numpy.random.seed", "matplotlib.pyplot.scatter", "sklearn.datasets.make_moons", "numpy.arange", "numpy.int64", "numpy.random.randn", "numpy.mean", "numpy.exp", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "numpy.zeros", "numpy.sum", "matplotlib.pyplot.ylabel" ] ]
GabrielCi77/ProjetInfo2021
[ "ec40c6ae857e895f47c7740f8745dd428b729a24" ]
[ "lib/B23_findCoeff.py" ]
[ "import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.linear_model import Lasso, Ridge\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import r2_score, mean_squared_error\nimport matplotlib.pyplot as plt\n\n\n\n# Fonction qu'on peut tester (toute seule) avec ce fichier\n\ndef findBestCoeff(df_data, model, print_results=False):\n \"\"\" Trouve le meilleur coefficient pour le lasso\n\n Paramètres\n ----------\n df_data : pandas.dataframe\n dictionnaire des paramètres\n model : string\n 'l1' ou 'l2'\n choix du modèle (Lasso ou Ridge)\n\n Retours\n ----------\n alpha : float\n meilleur coefficient dans la liste proposée\n \"\"\"\n \n # On ne garde que les jours où au moins 3 arrivées sont enregistrées\n df_data = df_data[(df_data['A_EU'] + df_data['A_NA'] + df_data['A_AS'] >= 3)]\n \n # On enlève les colonnes non utilisées pour le machine learning\n list_dates = np.array(df_data['Atime'])\n df_data = df_data.drop(columns=['Atime', 'A_AS', 'A_NA'])\n\n X = np.array(df_data.drop(columns=['A_EU']))\n y = np.array(df_data['A_EU'])\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=13)\n\n # On applique un prétraitement aux données afin qu'elles soient centrées réduites\n standard_scaler = StandardScaler()\n standard_scaler.fit(X_train)\n X_train = standard_scaler.transform(X_train)\n X_test = standard_scaler.transform(X_test)\n \n # define model and alpha values to evaluate\n if model == 'l1' :\n predictor = Lasso(random_state=13, max_iter=10000)\n elif model == 'l2' :\n predictor = Ridge(random_state=13, max_iter=10000)\n else :\n print(\"Model unvalid: choose between 'l1' (for Lasso) and 'l2' (for Ridge)\")\n return None\n \n alphas = np.logspace(-4, 0, 30)\n\n # define gridsearch\n tuned_parameters = [{'alpha': alphas}]\n nb_folds = 5\n grid = GridSearchCV(predictor, tuned_parameters, cv=nb_folds, refit=False, verbose=3)\n\n # run gridsearch \n grid.fit(X_train, y_train)\n\n # get R2 (default score with Lasso models)\n scores = grid.cv_results_['mean_test_score']\n scores_std = grid.cv_results_['std_test_score']\n\n # compute standard errors\n std_error = scores_std / np.sqrt(nb_folds)\n\n # get optimal alpha\n i_max = np.argmax(scores)\n best_alpha = alphas[i_max]\n best_score = scores[i_max]\n if print_results :\n print(\"optimal alpha: {0:0.4f}\".format(best_alpha))\n print(\"best R2 (test set): {0:0.4f}\".format(best_score))\n\n return best_alpha\n\n\n\n# Fonction utilisée dans B23_LR.property\n\ndef findBestCoeff2(X, y, model):\n \"\"\" Trouve le meilleur coefficient pour le lasso\n\n Paramètres\n ----------\n X : \n y : \n model : string\n 'l1' ou 'l2'\n choix du modèle (Lasso ou Ridge)\n\n Retours\n ----------\n alpha : float\n meilleur coefficient dans la liste proposée\n \"\"\"\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=13)\n\n # On applique un prétraitement aux données afin qu'elles soient centrées réduites\n standard_scaler = StandardScaler()\n standard_scaler.fit(X_train)\n X_train = standard_scaler.transform(X_train)\n X_test = standard_scaler.transform(X_test)\n \n # define model and alpha values to evaluate\n if model == 'l1' :\n predictor = Lasso(random_state=13, max_iter=10000)\n elif model == 'l2' :\n predictor = Ridge(random_state=13, max_iter=10000)\n else :\n print(\"Model unvalid: choose between 'l1' (for Lasso) and 'l2' (for Ridge)\")\n return None\n \n alphas = np.logspace(-4, 0, 30)\n\n # define gridsearch\n tuned_parameters = [{'alpha': alphas}]\n nb_folds = 5\n grid = GridSearchCV(predictor, tuned_parameters, cv=nb_folds, refit=False, verbose=0)\n\n # run gridsearch \n grid.fit(X_train, y_train)\n\n # get R2 (default score with Lasso models)\n scores = grid.cv_results_['mean_test_score']\n scores_std = grid.cv_results_['std_test_score']\n\n # compute standard errors\n std_error = scores_std / np.sqrt(nb_folds)\n\n # get optimal alpha\n i_max = np.argmax(scores)\n best_alpha = alphas[i_max]\n # best_score = scores[i_max]\n\n return best_alpha\n\n\n\nif __name__ == '__main__':\n df_trips = pd.read_csv('../data/loadAll_agg_all.csv')\n alpha = findBestLassoCoeff(df_trips, 'l1', True)\n" ]
[ [ "sklearn.model_selection.GridSearchCV", "pandas.read_csv", "numpy.sqrt", "numpy.logspace", "sklearn.model_selection.train_test_split", "sklearn.linear_model.Lasso", "sklearn.linear_model.Ridge", "numpy.argmax", "sklearn.preprocessing.StandardScaler", "numpy.array" ] ]
lslll0302/Planner-Carrier
[ "7611a02118f11b06533144c5e034f7938fb90068" ]
[ "src/gentask.py" ]
[ "import pandas as pd\nimport os \nimport re\nimport planner\n#import mysql.connector\n#from mysql.connector import Error\nimport utils\n\n\nlist_benchmarks=os.listdir(utils.BENCHMARK_PATH)\nlist_benchmarks.sort()\n\ndef listdir(path, char_): \n list_ = []\n for file in os.listdir(path):\n file_path = os.path.join(path, file)\n if os.path.isdir(file_path):\n pass \n elif os.path.splitext(file_path)[1] == '.pddl':\n f_name=os.path.splitext(file_path)[0]\n f_name=os.path.split(f_name)[1]\n if char_ in f_name:\n list_.append(file_path)\n \n return list_\n\t \n\n \ndef save_file_path_to_csv(path, i):\n\n domain_path = listdir(path,'d')\n problem_path = listdir(path,'p')\n domain_path.sort()\n problem_path.sort()\n\n csv_list = [domain_path, problem_path]\n\n df = pd.DataFrame(csv_list)\n df=df.T\n df.columns=['domain_path','problem_path']\n df.index += 1 \n benchmark_name = f\"{list_benchmarks[i]}.csv\"\n file_path = os.path.join(utils.DB_PATH_PATH, benchmark_name )\n df.to_csv(file_path, index_label='index')\n\n #print(df)\n return len(problem_path)\n\ndef save_folder_to_csv(problems_sum): \n \n csv_list = [list_benchmarks, problems_sum]\n df = pd.DataFrame(csv_list)\n df=df.T\n df.columns=['domain_name','problem_size']\n df.index += 1 \n \n df.to_csv(utils.DB_BENCHMARKS_PATH, index_label='index')\n\n #print(df) \n\n\n\ndef get_range(input_range,show_str, reverse:bool=False, true_zero: bool=False):\n regex1 = re.compile(r'\\d+') \n regex2 = re.compile(r'\\d+-\\d+') \n if(isinstance(input_range, int)):\n list_input_range = []\n for i in range(1,input_range+1): \n list_input_range.append(i)\n\n while True:\n list_s1=[]\n list_s2=[]\n list_sum = [] \n try:\n input_str = input(show_str) \n #domain_str = input('Please chose which domain you want to test:\\n0.All'+'\\nFrom range'+' 1-'+ str(rowcount)+'\\n') \n \n list_s2 = regex2.findall(input_str)\n for s in list_s2:\n input_str=input_str.replace(s,'')\n s_=[]\n s_=regex1.findall(s)\n if(int(s_[0])<= int(s_[1])):\n a=int(s_[0])\n b=int(s_[1])\n else:\n a=int(s_[1])\n b=int(s_[0])\n for i in range(a,b+1):\n list_sum.append(i) \n \n list_s1 = regex1.findall(input_str)\n\n for s in list_s1:\n #if the input include 0, return all domains\n if(int(s)==0):\n if true_zero:\n list_sum=[]\n else:\n if(isinstance(input_range, int)):\n list_sum = list_input_range \n elif(isinstance(input_range, list)):\n list_sum = input_range\n \n return list_sum\n #else, return selected domains\n else:\n list_sum.append(int(s))\n\n #if reverse==True, return the list not select\n if reverse:\n if(isinstance(input_range, list)):\n list_sum = list(set(input_range) - set(list_sum) ) \n elif(isinstance(input_range, int)):\n list_sum = list(set(list_input_range) - set(list_sum) ) \n else:\n #remove duplicates elements in list\n list_sum = list(set(list_sum))\n list_sum.sort()\n #check selected domains in range\n if(isinstance(input_range, int)):\n if list_sum[-1] in range(1,input_range+1) and list_sum[0] in range(1,input_range+1): \n break\n elif(isinstance(input_range, list)):\n if (set(list_sum).issubset(set(input_range))): \n break\n except (ValueError):\n pass\n print('Wrong input vaule!')\n continue\n \n return list_sum\n\n#get the index of which domain users want to test\ndef get_domain_index(rowcount):\n show_str=('Please choose which domain you want to test:\\n'+\n '0.All\\n'+\n 'a,b-c.From range'+' 1-'+ str(rowcount)+' select a,b-c domains\\n')\n return get_range(rowcount,show_str)\n \n\n\n#get the problem size of all domains\ndef get_prob_size(domain_idxs, prob_sizes, domain_namess):\n new_domain_idxs=[]\n prob_sp=[]\n prob_ep=[]\n show_str = ('Please choose which domain you want to custom problem range of all selected domains:\\n'+ \n '0.All problems for all selected domains\\n'+\n 'a,b-c.Custom specific problems range for selected a,b-c domains'+ ',All problems for remaining domains\\n')\n domain_prob_all = get_range(domain_idxs,show_str, reverse=True)\n domain_prob_spec = list(set(domain_idxs)-set(domain_prob_all))\n domain_prob_spec.sort()\n\n for d in domain_prob_all:\n new_domain_idxs.append(d)\n prob_sp.append(1)\n #print(domain_prob_all)\n #print(prob_sizes)\n prob_ep.append(prob_sizes[domain_idxs.index(d)])\n #print(prob_ep)\n \n show_str1 = ('Please select problems range for testing:\\n'+\n '0.All problems for selected domain\\n'+\n 'a,b-c.Custom specific problems range for selected domain\\n')\n\n \n for d in domain_prob_spec:\n prob_size=[]\n print(f\"\\n{d} {domain_namess[domain_idxs.index(d)]} size:{prob_sizes[domain_idxs.index(d)]}\")\n prob_size = get_range(int(prob_sizes[domain_idxs.index(d)]),show_str1)\n new_domain_idxs.append(d)\n prob_sp.append(prob_size[0])\n for p in prob_size:\n if(prob_size.index(p) == len(prob_size)-1):\n prob_ep.append(p)\n elif(prob_size[prob_size.index(p)+1]-p != 1):\n prob_ep.append(p)\n prob_sp.append(prob_size[prob_size.index(p)+1])\n new_domain_idxs.append(d)\n\n return new_domain_idxs, prob_sp, prob_ep\n\n \n \n#get which planner users want to test \ndef get_planner( d, s, e ):\n d_= []\n s_= []\n e_= []\n show_str = ('\\nPlease select one planner for testing:\\n 1.prp\\n 2.sat\\n'+\n '0.All planners\\n'+\n 'a,b-c.Select specific planners\\n')\n select_planners = get_range(planner.PLANNERS_ID,show_str)\n planners_=[]\n\n for planner_id in select_planners:\n for i in d:\n planners_.append(planner.PLANNERS_NAME[planner.PLANNERS_ID.index(planner_id)]) \n d_ = d_+ d\n s_ = s_+ s\n e_ = e_+ e\n return planners_, d_, s_, e_\n \n \n\n#end program\ndef check_end(input_str):\n while True:\n try:\n input_num = int(input(input_str))\n if input_num in range(1,3): \n if input_num == 1:\n return True\n else: \n return False \n break\n except (ValueError):\n pass\n print('Wrong input vaule!')\n continue\n return False \n \n#the online mysql host \n''' \nhost=\"den1.mysql6.gear.host\",\n user=\"benchmarks\",\n password=\"Mx9G0h8q?9W_\" \n''' \n \n#the local mysql host \n''' \ntry: \n connection = mysql.connector.connect(host='localhost',\n database='planning_benchmarks',\n user='root',\n password='2747')\n\n sql_select_Query = \"select * from benchmarks\"\n cursor = connection.cursor()\n cursor.execute(sql_select_Query)\n records = cursor.fetchall() \n print('MySQL connection is started...')\n print(\"Total number of domains in benchmarks is: \", cursor.rowcount) \n mat = \"{:1}\\t{:28}\\t{:1}\" \n \n while True: \n print(mat.format('\\nIndex','Domain name', '#inst'))\n for row in records: \n print(mat.format(row[0], row[1], row[2]))\n \n domain_index = get_domain_index(cursor.rowcount) \n domain_indexs.append(domain_index)\n\n for row in records: \n if (row[0] == domain_index):\n domain_names.append(row[1])\n inst_size = row[2] \n \n prob_start_point = get_prob_start_point(inst_size) \n if prob_start_point == 0:\n prob_start_point = 1\n prob_end_point = row[2]\n else: \n prob_end_point = get_prob_end_point(prob_start_point, inst_size)\n \n prob_start_points.append(prob_start_point)\n prob_end_points.append(prob_end_point)\n \n planner_id = get_planner()\n chosed_planners.append(planners[planner_id-1])\n \n \n if check_end():\n task_name=input('Please enter a task name for saving your task data into a csv file:\\n')\n break\n \nexcept Error as e:\n print(\"Error reading data from MySQL table\", e)\nfinally:\n if (connection.is_connected()):\n connection.close()\n cursor.close()\n print(\"MySQL connection is closed\")\n'''\nif __name__ == '__main__':\n\n problems_sum = []\n\n domain_names=[]\n prob_start_points = []\n prob_end_points = []\n chosed_planners = []\n\n #clear all database\n list_csv = os.listdir(utils.DB_PATH_PATH)\n for f in list_csv:\n os.remove(os.path.join(utils.DB_PATH_PATH, f))\n\n #update database before create task\n for i in range(len(list_benchmarks)):\n path = os.path.join(\"benchmarks\", list_benchmarks[i])\n \n os.chdir(utils.ROOT_PATH)\n prob_sum = save_file_path_to_csv(path, i)\n problems_sum.append(prob_sum)\n\n save_folder_to_csv(problems_sum)\n\n\n\n #create task\n #the virtual database in local\n bm = pd.read_csv(utils.DB_BENCHMARKS_PATH) \n print('\\n') \n print(bm.to_string(index=False))\n \n domain_indexs = get_domain_index(len(bm)) \n domain_names_ = []\n problem_sizes_ = []\n print(f\"Selected domains are: {domain_indexs}\\n\" ) \n\n \n for i in domain_indexs:\n domain_names_.append(bm['domain_name'][i-1])\n problem_sizes_.append(bm['problem_size'][i-1] )\n\n\n prob_start_points_=[]\n prob_end_points_=[]\n\n (domain_indexs,prob_start_points_,prob_end_points_) = get_prob_size(domain_indexs, problem_sizes_, domain_names_)\n \n \n\n (chosed_planners_,domain_indexs,prob_start_points_,prob_end_points_) = get_planner(domain_indexs, prob_start_points_,prob_end_points_)\n chosed_planners = chosed_planners + chosed_planners_\n\n for i in domain_indexs:\n domain_names.append(bm['domain_name'][i-1])\n prob_start_points = prob_start_points + prob_start_points_\n prob_end_points = prob_end_points + prob_end_points_\n task_name=input('Please enter a task name(exclude \".csv\") for saving your task data into a csv file:\\n')\n \n \n \n\n\n #write task data into csv\n csv_list = [ domain_names, prob_start_points, prob_end_points, chosed_planners]\n csv_list = [[row[i] for row in csv_list] for i in range(len(csv_list[0]))]\n\n df = pd.DataFrame(csv_list, columns=[ 'domain_name', 'start_problem', 'end_problem', 'planner'])\n df.index += 1 \n task_name = f\"{task_name}.csv\"\n task_path = os.path.join(utils.TASK_PATH, task_name)\n df.to_csv(task_path, index_label='index')\n\n print(df)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" ]
[ [ "pandas.read_csv", "pandas.DataFrame" ] ]
thomas-marquis/immo-tools-lib
[ "455d726923ad723b099ee098e8ded7e28942904c" ]
[ "demo.py" ]
[ "import numpy as np\n\nones = np.ones((3, 3))\n" ]
[ [ "numpy.ones" ] ]
qgh1223/SLRDet
[ "f63335e9626067b462ad548c98f986e0d33addf9" ]
[ "mmdet/ops/ops/rotated/rotate_roi_pool.py" ]
[ "import torch\r\nimport torch\r\nfrom torch import nn\r\nfrom torch.autograd import Function\r\nfrom torch.autograd.function import once_differentiable\r\nfrom torch.nn.modules.utils import _pair\r\n\r\nfrom mmdet import _Custom as _C\r\n\r\nfrom apex import amp\r\n\r\nclass _RROIPool(Function):\r\n @staticmethod\r\n def forward(ctx, input, roi, output_size, spatial_scale):\r\n ctx.output_size = _pair(output_size)\r\n ctx.spatial_scale = spatial_scale\r\n ctx.input_shape = input.size()\r\n output, argmax = _C.rotate_roi_pool_forward(\r\n input, roi, spatial_scale, output_size[0], output_size[1]\r\n )\r\n ctx.save_for_backward(input, roi, argmax)\r\n\r\n # return output, argmax # DEBUG ONLY\r\n return output\r\n\r\n @staticmethod\r\n @once_differentiable\r\n def backward(ctx, grad_output):\r\n # def backward(ctx, grad_output, aaa): # DEBUG ONLY\r\n input, rois, argmax = ctx.saved_tensors\r\n output_size = ctx.output_size\r\n spatial_scale = ctx.spatial_scale\r\n bs, ch, h, w = ctx.input_shape\r\n grad_input = _C.rotate_roi_pool_backward(\r\n grad_output,\r\n input,\r\n rois,\r\n argmax,\r\n spatial_scale,\r\n output_size[0],\r\n output_size[1],\r\n bs,\r\n ch,\r\n h,\r\n w,\r\n )\r\n return grad_input, None, None, None\r\n\r\n\r\nrroi_pool = _RROIPool.apply\r\n\r\n\r\nclass RROIPool(nn.Module):\r\n def __init__(self, output_size, spatial_scale):\r\n super(RROIPool, self).__init__()\r\n self.output_size = output_size\r\n self.spatial_scale = spatial_scale\r\n\r\n @amp.float_function\r\n def forward(self, input, rois):\r\n return rroi_pool(input, rois, self.output_size, self.spatial_scale)\r\n\r\n def __repr__(self):\r\n tmpstr = self.__class__.__name__ + \"(\"\r\n tmpstr += \"output_size=\" + str(self.output_size)\r\n tmpstr += \", spatial_scale=\" + str(self.spatial_scale)\r\n tmpstr += \")\"\r\n return tmpstr\r\n" ]
[ [ "torch.nn.modules.utils._pair" ] ]
cloudsTrafton/AwesomeSauce
[ "24d3694ebe47e59b2fbbd405f52ea5542cd3b945" ]
[ "clustering/NoSeekTime.py" ]
[ "# Keep the clustering experiments that involve outliers here\nfrom clustering.KMeansVariations import kMeans_baseline, kMeans_baseline_high_iteration, kMeans_baseline_random_init, \\\n kMeans_baseline_4_clusters, kMeans_baseline_3_clusters, kMeans_baseline_2_clusters, kMeans_baseline_2_clusters_low_iter,\\\n kMeans_baseline_2_clusters_high_iter\nfrom clustering.MultiClusteringExperiments import normalizedLabeledData\nfrom data_processing import MulticlusteringExperimentUtils as expUtils\nfrom clustering import silhouette as sil\nimport pandas as pd\n\n# Run some experiments with the Avg Seek time removed, since Pentel reported a higher correlation between seek time\n# and some of the features in his paper.\n\n# --- Remove all of the outliers for the big features ----\n# average hold time\nfrom data_processing.CleanDataUtils import feature_set\nfrom data_processing.dataUtils import getColumnZScores, removeOutliersByZScore\n\navgSeekTime = 'avgSeekTime'\ndf_no_seek_time = pd.DataFrame(normalizedLabeledData).drop(avgSeekTime)\n\n\n\ndef runExperiment(dataset, kmeans, experiment_name):\n result = kmeans.fit_predict(dataset)\n\n cluster1, cluster2, cluster3, cluster4, cluster5, cluster6 = \\\n expUtils.getClusterBucketsForMultiClustering(feature_set, result)\n\n sil.makeSilhouettePlot(dataset, result, experiment_name)\n\n expUtils.getAverageForAll(cluster1, cluster2, cluster3, cluster4, cluster5, cluster6,\n experiment_name, dataset)\n" ]
[ [ "pandas.DataFrame" ] ]
LingxB/atlx
[ "1230c4f845adb57edb2a91556282af500ef27880" ]
[ "src/utils/file_utils.py" ]
[ "import yaml\nfrom dotenv import load_dotenv, find_dotenv\nimport os\nimport inspect\nfrom src.utils.att_dict import AttributeDict\nfrom src.utils.data_utils import create_symbol_dict\nimport warnings\nimport pandas as pd\nfrom time import time\nfrom datetime import datetime\nimport pickle\n\ndef get_timestamp():\n ts = time()\n ts = datetime.fromtimestamp(ts).strftime('%Y%m%d_%H%M%S')\n return ts\n\ndef read_config(config_file, obj_view=True):\n cfg = read_yaml(config_file + '.yml')\n if obj_view:\n cfg = AttributeDict(**cfg)\n return cfg\n\ndef save_yaml(dict, path, mode='w'):\n with open(path, mode) as outfile:\n yaml.dump(dict, outfile, default_flow_style=False)\n\ndef read_yaml(yaml_file):\n with open(yaml_file, 'r') as ymlfile:\n yml = yaml.load(ymlfile)\n return yml\n\ndef get_envar(key):\n \"\"\"Get environment variable form .env file\"\"\"\n load_dotenv(find_dotenv(raise_error_if_not_found=True, usecwd=True))\n return os.environ.get(key)\n\ndef list_files(path):\n l = list(os.walk(path))\n if l == []:\n return l\n else:\n return l[0][-1]\n\ndef load_symbod_dict_if_exists(load_path):\n warnings.warn('Function is deprecated!')\n try:\n sd = read_yaml(load_path)\n except FileNotFoundError:\n sd = False\n return sd\n\ndef create_dump_symbol_dict(corpus, start_idx, dump_path):\n warnings.warn('Function is deprecated!')\n sd, _ = create_symbol_dict(corpus, start_idx)\n save_yaml(sd, dump_path, 'x')\n return sd\n\ndef __fn__():\n \"\"\"\n Magic function to return the python file/module name where the function is called. If called in console, return\n ``'__main__'``.\n\n Returns\n -------\n str\n File/module name where the function is called, ``'__main__'`` when in console.\n \"\"\"\n frame = inspect.stack()[1]\n module = inspect.getmodule(frame[0])\n try:\n name = os.path.basename(module.__file__)[:-3]\n except AttributeError:\n name = '__main__'\n return name\n\ndef load_corpus(file, **kwargs):\n if isinstance(file, str):\n _df = pd.read_csv(file, **kwargs)\n elif isinstance(file, list):\n _df = pd.concat([pd.read_csv(f, **kwargs) for f in file], ignore_index=True)\n else:\n raise AttributeError('File type not valid, path or list of paths only.')\n return _df\n\ndef load_embedding(file, **kwargs):\n df = pd.read_parquet(file, **kwargs)\n return df\n\ndef mkdir(path):\n if not os.path.exists(path):\n os.makedirs(path)\n\ndef pickle_dump(to_dump, path):\n with open(path, 'wb') as handle:\n pickle.dump(to_dump, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\ndef pickle_load(path):\n with open(path, 'rb') as handle:\n return pickle.load(handle)" ]
[ [ "pandas.read_parquet", "pandas.read_csv" ] ]
wegenmat/python
[ "d3f73197fc5b53fe75b0a0fc6ab88d87d785549d" ]
[ "period-detection-in-power-law-noise/psresp.py" ]
[ "import numpy as np\n\n__all__ = [\n 'psresp',\n]\n\n\ndef _spectrum(x, slope):\n y = x ** slope\n\n return y\n\n\ndef _timmerlc(slope, nt='None', dt='None', mean='None', sigma='None', seed='None'):\n if dt == 'None':\n dt = 1\n if nt == 'None':\n nt = 65536\n if mean == 'None':\n mean = 0\n if sigma == 'None':\n sigma = 1\n if seed == 'None':\n seed = 42\n\n simfreq = np.linspace(1, nt / 2 - 1, num=nt / 2, dtype='float64') / (dt * nt)\n simpsd = _spectrum(simfreq, slope)\n fac = np.sqrt(simpsd)\n\n pos_real = np.random.RandomState(seed).normal(size=int(nt / 2)) * fac\n pos_imag = np.random.RandomState(seed).normal(size=int(nt / 2)) * fac\n\n pos_imag[int(nt / 2) - 1] = 0\n\n if float(nt / 2.) > int(nt / 2):\n neg_real = pos_real[0:int(nt / 2)][::-1]\n neg_imag = -pos_real[0:int(nt / 2)][::-1]\n else:\n neg_real = pos_real[0:int(nt / 2) - 1][::-1]\n neg_imag = -pos_real[0:int(nt / 2) - 1][::-1]\n\n real = np.hstack((0., pos_real, neg_real))\n imag = np.hstack((0., pos_imag, neg_imag))\n\n arg = real + 1j * imag\n rate = np.fft.ifft(arg).real\n time = dt * np.linspace(0, nt - 1, nt, dtype='float')\n\n avg = np.mean(rate)\n std = np.sqrt(np.var(rate))\n\n rate = (rate - avg) * sigma / std + mean\n\n return time, rate\n\n\ndef _periodogram(series):\n series = series - np.mean(series)\n revff = np.fft.ifft(series)\n periodogram_bar = np.zeros(len(revff))\n freqs = np.zeros(len(revff))\n for freq, ff in enumerate(revff):\n if freq == 0:\n continue\n freqs[freq] = freq\n periodogram_bar[freq] = (abs(ff) ** 2)\n\n return freqs, periodogram_bar\n\n\ndef _rebinlc(time, rate, dt):\n # check for finite values\n rate = rate[np.isfinite(time)]\n time = time[np.isfinite(time)]\n\n # rebin lc/psd to evenly spaced time binning, from rebinlc.pro\n t = time\n\n ts = t[0]\n num = int((t[-1] - ts) / dt + 1)\n\n minnum = 1\n\n tn = np.empty([num])\n rn = np.empty([num])\n numperbin = np.empty([num])\n\n tlimit = ts + dt * np.linspace(0, num, num + 1)\n\n k = 0\n for i in range(num):\n tn[k] = tlimit[i]\n index = np.where(np.greater_equal(t, tlimit[i]) & (t < tlimit[i + 1]))\n number = len(t[index])\n\n numperbin[k] = number\n if np.greater_equal(number, minnum):\n rn[k] = np.sum(rate[index]) / number\n k = k + 1\n else:\n rn[k] = 0\n numperbin[k] = 0\n k = k + 1\n\n if k == 0:\n print('Rebinned lightcurve would not contain any data')\n\n if k != num:\n tn = tn[0:k]\n rn = rn[0:k]\n numperbin = numperbin[0:k]\n\n tn = tn[numperbin != 0]\n rn = rn[numperbin != 0]\n\n return tn, rn\n\n\ndef _do_periodogram(y):\n y = y - np.mean(y)\n freq, psd = _periodogram(y)\n\n return freq, psd\n\n\ndef _chi2_obs(norm, obs_pds, avg_pds, pds_err):\n obs_pds = norm * obs_pds\n a = (avg_pds - obs_pds) ** 2.\n b = pds_err ** 2.\n chi_obs = np.sum(a / b)\n\n return chi_obs\n\n\ndef _compare(obs_pds, avg_pds, pds_err, allpds, number_simulations):\n from scipy import optimize\n norm0 = 1.\n chi_obs = optimize.minimize(_chi2_obs, norm0, args=(obs_pds, avg_pds, pds_err), method='SLSQP').fun\n\n chi_dist = np.empty([number_simulations])\n for n in range(number_simulations):\n a = (allpds[n, :] - avg_pds) ** 2\n b = pds_err ** 2\n chi = a / b\n chi_dist[n] = np.sum(chi)\n\n suf = 0\n for i in range(len(chi_dist)):\n if np.greater_equal(chi_dist[i], chi_obs):\n suf = suf + 1\n\n suf = suf / len(chi_dist)\n\n return suf\n\n\ndef _psresp_pro(t, y, dy, slopes, number_simulations, binning, oversampling, df):\n bin = binning\n date, rat, raterr = t, y, dy\n date = date - date[0]\n duration = np.max(date) - np.min(date)\n npoints = int(duration / bin) * number_simulations * oversampling\n params = -slopes\n lc_variance = np.var(rat) - np.var(raterr)\n # observed PDS calculation\n obs_nu, obs_pds = _do_periodogram(rat)\n obs_nu = np.log10(obs_nu)\n\n # normalisation\n obs_pds = (2. * duration) / (np.mean(rat) * np.mean(rat) * len(rat) * len(rat)) * obs_pds\n\n # rebin\n obs_freqs, obs_power = _rebinlc(obs_nu, obs_pds, dt=df)\n obs_power = np.log10(obs_power)\n\n # create fake light curve\n faketime, fakerate = _timmerlc(params, nt=npoints, dt=bin / oversampling)\n\n # calculate level of Poisson noise\n factor = ((len(raterr) / (2. * duration)) - (1. / duration))\n p_noise = np.sum(raterr ** 2.) / (len(raterr) * factor)\n\n # calculate high frequency aliased power\n uplim = 1. / (2. * bin)\n lowlim = 1. / (2. * (bin / 10))\n intfreq = np.empty([int((lowlim - uplim) / uplim) + 2])\n for i in range(len(intfreq)):\n intfreq[i] = uplim * (i + 1)\n intpds = _spectrum(intfreq, params)\n integral = np.trapz(intpds, x=intfreq)\n p_alias = integral / factor\n\n # long light curve is divided and resultant PDS are calculated\n allpds = np.empty([number_simulations, len(obs_freqs)])\n for j in range(number_simulations):\n # print('computing PDS ' + str(j+1))\n\n # indices for each segment\n lobin = int(duration * j / (bin / oversampling))\n hibin = int(duration * j / (bin / oversampling)) + int(duration / (bin / oversampling))\n\n # taken from appropriate section of light curve\n temptime = faketime[lobin:hibin]\n temprate = fakerate[lobin:hibin]\n\n # shift start time to zero\n temptime = temptime - temptime[0]\n\n # set bintime equal to original light curve time\n bintime = date\n binrate = np.interp(date, temptime, temprate)\n\n # rescale simulated LC to the mean and variance of the original\n tempvar = np.sqrt(np.var(binrate))\n binrate = (binrate - np.mean(binrate)) * ((np.sqrt(lc_variance)) / tempvar) + np.mean(rat)\n\n # calculate PDS of simulated light curve\n sim_nu, sim_pds = _do_periodogram(binrate)\n sim_nu = np.log10(sim_nu)\n # sim_pds = sim_pds + p_noise + p_alias\n\n # normalisation\n sim_pds = (2. * (np.max(bintime) - np.min(bintime))) / (np.mean(binrate)\n * np.mean(binrate) * len(binrate) * len(\n binrate)) * sim_pds\n\n # rebin simulated PDS in same manner as observed\n # logfreqs, logpower = binlogPSD(sim_nu, sim_pds, df)\n logfreqs, power = _rebinlc(sim_nu, sim_pds, dt=df)\n logpower = np.log10(power)\n\n # large array for later calculations of mean and rms error\n for k in range(len(logpower)):\n allpds[j, k] = logpower[k]\n\n avg_pds = np.empty([len(obs_freqs)])\n pds_err = np.empty([len(avg_pds)])\n for i in range(len(avg_pds)):\n avg_pds[i] = np.mean(allpds[:, i])\n for i in range(len(pds_err)):\n pds_err[i] = np.sqrt(np.var(allpds[:, i]))\n\n return faketime, fakerate, obs_freqs, obs_power, bintime, binrate, avg_pds, pds_err, allpds\n\n\ndef psresp(t, y, dy, slopes, dt, df, percentile, oversampling=10, number_simulations=100):\n \"\"\"\n Compute power spectral density of a light curve assuming an unbroken power law with the PSRESP method.\n\n The artificial light curves are generated using the algorithm by Timmer and Koenig (1995).\n For an introduction to the PSRESP method, see Uttley (2002).\n\n The function returns a results dictionary with the following content:\n\n - ``slope`` (`float`) -- Mean slope of the power law\n - ``slope_error`` (`float`) -- Error of the slope of the power law\n - ``suf`` (`~numpy.ndarray`) -- Success fraction for each model parameter\n - ``best_parameters`` (`~numpy.ndarray`) -- Parameters satisfying the significance criterion\n - ``statistics`` (`~numpy.ndarray`) -- Data used to calculate the mean slope and its error\n over a grid of ``dt`` and ``df``\n\n - slope with the highest success fraction\n - highest success fraction\n - slope of the lower full width at half maximum for the success fraction distribution\n - slope of the higher full width at half maximum for the success fraction distribution\n\n Parameters\n ----------\n t : `~numpy.ndarray`\n Time array of the light curve\n y : `~numpy.ndarray`\n Flux array of the light curve\n dy : `~numpy.ndarray`\n Flux error array of the light curve\n slopes : `~numpy.ndarray`\n slopes of the power law model\n dt : `~numpy.ndarray`\n bin length for the light curve in units of ``t``\n df : `~numpy.ndarray`\n bin factor for the logarithmic periodogram\n percentile : `float`\n percentile of the distribution of success fraction, `0 < significance < 1`\n oversampling : `int`\n oversampling factor of the simulated light curve, default is 10\n number_simulations : `int`\n number of simulations for each model parameter, default is 10\n\n Returns\n -------\n results : `~collections.OrderedDict`\n Results dictionary (see description above).\n\n References\n ----------\n .. [1] Timmer and Koenig (1995), \"On generating power law noise\",\n `Link <http://adsabs.harvard.edu/abs/1995A%26A...300..707T>`_\n .. [2] Uttley et al, \"Measuring the broad-band power spectra of active galactic nuclei with RXTE\",\n `Link <https://academic.oup.com/mnras/article/332/1/231/974626/Measuring-the-broad-band-power-spectra-of-active>`_\n \"\"\"\n\n from scipy import interpolate\n t_ini, y_ini, dy_ini = t, y, dy\n suf = np.empty([len(slopes), len(dt), len(df)])\n statistics = np.empty([4, len(dt), len(df)])\n for b in range(len(dt)):\n # print('binning: ' + str(dt[b]))\n t, y = _rebinlc(t_ini, y_ini, dt[b])\n t, dy = _rebinlc(t_ini, dy_ini, dt[b])\n for f in range(len(df)):\n # print('df: ' + str(df[f]))\n for s in range(len(slopes)):\n # print('slope: ' + str(slopes[s]))\n\n # psresp\n faketime, fakerate, obs_freqs, obs_power, bintime, binrate, avg_pds, pds_err, allpds = \\\n _psresp_pro(t, y, dy, slopes[s], number_simulations, dt[b], oversampling, df[f])\n\n # do chi2\n suf[s, b, f] = _compare(obs_power, avg_pds, pds_err, allpds, number_simulations)\n\n # find best slope and estimate error\n best_slope = slopes[np.argmax(suf[:, b, f])]\n best_slope_suf = np.max(suf[:, b, f])\n\n slopes_fwhm = interpolate.UnivariateSpline(slopes, suf[:, b, f] - 0.5 * best_slope_suf, s=0).roots()\n if len(slopes_fwhm) == 0:\n slopes_fwhm = [np.nan]\n low_slopes = slopes_fwhm[0]\n high_slopes = slopes_fwhm[-1]\n if low_slopes == high_slopes:\n low_slopes = high_slopes = np.nan\n\n statistics[0, b, f] = best_slope\n statistics[1, b, f] = best_slope_suf\n statistics[2, b, f] = low_slopes\n statistics[3, b, f] = high_slopes\n\n test_significance = np.percentile(statistics[1, :, :], 100 * percentile)\n statistics_test = (np.greater_equal(statistics[1, :, :], test_significance)) & \\\n (np.isfinite(statistics[2, :, :])) & \\\n (np.isfinite(statistics[3, :, :]))\n best_parameters = np.where(statistics_test == True)\n mean_slope = np.sum(statistics[0, :, :][statistics_test] * statistics[1, :, :][statistics_test]) \\\n / (np.sum(statistics_test))\n mean_error = np.abs(np.min(statistics[2, :, :][statistics_test]) - np.max(statistics[3, :, :][statistics_test]))\n\n return dict(slope=mean_slope,\n slope_error=mean_error,\n suf=suf,\n best_parameters=best_parameters,\n statistics=statistics\n )\n" ]
[ [ "numpy.sqrt", "numpy.linspace", "numpy.max", "numpy.mean", "numpy.var", "numpy.where", "numpy.trapz", "numpy.hstack", "scipy.interpolate.UnivariateSpline", "numpy.greater_equal", "numpy.argmax", "numpy.interp", "numpy.min", "numpy.fft.ifft", "numpy.log10", "scipy.optimize.minimize", "numpy.random.RandomState", "numpy.sum", "numpy.isfinite", "numpy.percentile", "numpy.empty" ] ]
bhubesh757/Object_Detection
[ "33e6b07a57e6cfc80d28f9c466e392138399d853" ]
[ "Object_Detection_Using_Opencv/Object_detection_removing_the_duplicates.py" ]
[ "import cv2\r\nimport numpy as np\r\n\r\n# first import the image to check the image whether its checking or not\r\n\r\n#img = cv2.imread('Lenna_(test_image).PNG')\r\n# instead of doing the image we can do the code through the webacam\r\nthres = 0.45\r\n\r\nnms_threshold = 0.2\r\ncam = cv2.VideoCapture(0)\r\ncam.set(3,1288) # 3 is with\r\ncam.set(4,720) # 4 is for height\r\ncam.set(10,150) # this one is for brightness\r\n \r\n\r\n\r\n\r\nclassNames = []\r\nclassFile = 'coco.names'\r\nwith open(classFile, 'rt') as f:\r\n classNames = f.read().rstrip('\\n').split('\\n')\r\n#print(classNames)\r\n\r\nconfigPath = 'ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt'\r\nweightsPath = 'frozen_inference_graph.pb'\r\n\r\nnet = cv2.dnn_DetectionModel(weightsPath,configPath)\r\nnet.setInputSize(320 , 320)\r\nnet.setInputScale(1.0/127.5)\r\nnet.setInputMean((127.5 , 127.5 , 127.5))\r\nnet.setInputSwapRB(True)\r\n\r\n# ot snd the image for predictions\r\na = 1\r\nwhile True:\r\n a = a+1\r\n success , img = cam.read()\r\n classIds , confs , bbox = net.detect(img , confThreshold = thres)\r\n \r\n bbox = list(bbox)\r\n # convert the confidence values\r\n confs = list(np.array(confs).reshape(1,-1)[0]) # [0] removes the extra brackets\r\n confs = list(map(float , confs))\r\n \r\n print(type(confs[0]))\r\n print(confs)\r\n \r\n indices = cv2.dnn.NMSBoxes(bbox , confs ,thres , nms_threshold)\r\n print(indices)\r\n \r\n for i in indices:\r\n i = i[0]\r\n box = bbox[i]\r\n x,w,y,h = box[0] , box[1],box[2],box[3]\r\n cv2.rectangle(img , (x,y) ,(x+w , h+y) , color =(0 , 255 ,0),thickness = 2 )\r\n cv2.putText(img , classNames[classIds[i][0]-1].upper(),(box[0] + 10, box[1]+30),\r\n cv2.FONT_HERSHEY_COMPLEX ,1,(255,255,255) , 2)\r\n #if len(classIds)!=0:\r\n \r\n # for classId , confidence , box in zip(classIds.flatten() , confs.flatten() , bbox):\r\n # cv2.rectangle(img , box , color=(0 , 255 ,0),thickness = 2)\r\n # cv2.putText(img , classNames[classId - 1].upper(),(box[0] + 10, box[1]+30),\r\n # cv2.FONT_HERqSHEY_COMPLEX ,1,(255,255,255) , 2)\r\n # cv2.putText(img , str(round(confidence * 100,2)),(box[0] + 200, box[1]+30),\r\n # cv2.FONT_HERSHEY_COMPLEX ,1,(255,255,255) , 2)\r\n \r\n \r\n cv2.imshow(\"Output\",img)\r\n key = cv2.waitKey(1)\r\n if key == ord('q'):\r\n break\r\ncv2.destroyAllWindows()\r\ncam.release()" ]
[ [ "numpy.array" ] ]
Commoneffort/eos
[ "ed56850f5e7c88b32b4adc27dc8a8c8cc34d2298" ]
[ "tutorials/bios-boot-tutorial/bios-boot-tutorial.py" ]
[ "#!/usr/bin/env python3\n\nimport argparse\nimport json\nimport numpy\nimport os\nimport random\nimport re\nimport subprocess\nimport sys\nimport time\n\nargs = None\nlogFile = None\n\nunlockTimeout = 999999999\nfastUnstakeSystem = './fast.refund/eosio.system/eosio.system.wasm'\n\nsystemAccounts = [\n 'eosio.bpay',\n 'eosio.msig',\n 'eosio.names',\n 'eosio.ram',\n 'eosio.ramfee',\n 'eosio.saving',\n 'eosio.stake',\n 'eosio.token',\n 'eosio.vpay',\n]\n\ndef jsonArg(a):\n return \" '\" + json.dumps(a) + \"' \"\n\ndef run(args):\n print('bios-boot-tutorial.py:', args)\n logFile.write(args + '\\n')\n if subprocess.call(args, shell=True):\n print('bios-boot-tutorial.py: exiting because of error')\n sys.exit(1)\n\ndef retry(args):\n while True:\n print('bios-boot-tutorial.py:', args)\n logFile.write(args + '\\n')\n if subprocess.call(args, shell=True):\n print('*** Retry')\n else:\n break\n\ndef background(args):\n print('bios-boot-tutorial.py:', args)\n logFile.write(args + '\\n')\n return subprocess.Popen(args, shell=True)\n\ndef getOutput(args):\n print('bios-boot-tutorial.py:', args)\n logFile.write(args + '\\n')\n proc = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE)\n return proc.communicate()[0].decode('utf-8')\n\ndef getJsonOutput(args):\n print('bios-boot-tutorial.py:', args)\n logFile.write(args + '\\n')\n proc = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE)\n return json.loads(proc.communicate()[0])\n\ndef sleep(t):\n print('sleep', t, '...')\n time.sleep(t)\n print('resume')\n\ndef startWallet():\n run('rm -rf ' + os.path.abspath(args.wallet_dir))\n run('mkdir -p ' + os.path.abspath(args.wallet_dir))\n background(args.keosd + ' --unlock-timeout %d --http-server-address 127.0.0.1:6666 --wallet-dir %s' % (unlockTimeout, os.path.abspath(args.wallet_dir)))\n sleep(.4)\n run(args.cleos + 'wallet create')\n\ndef importKeys():\n run(args.cleos + 'wallet import ' + args.private_key)\n keys = {}\n for a in accounts:\n key = a['pvt']\n if not key in keys:\n if len(keys) >= args.max_user_keys:\n break\n keys[key] = True\n run(args.cleos + 'wallet import ' + key)\n for i in range(firstProducer, firstProducer + numProducers):\n a = accounts[i]\n key = a['pvt']\n if not key in keys:\n keys[key] = True\n run(args.cleos + 'wallet import ' + key)\n\ndef startNode(nodeIndex, account):\n dir = args.nodes_dir + ('%02d-' % nodeIndex) + account['name'] + '/'\n run('rm -rf ' + dir)\n run('mkdir -p ' + dir)\n otherOpts = ''.join(list(map(lambda i: ' --p2p-peer-address localhost:' + str(9000 + i), range(nodeIndex))))\n if not nodeIndex: otherOpts += (\n ' --plugin eosio::history_plugin'\n ' --plugin eosio::history_api_plugin'\n )\n cmd = (\n args.nodeos +\n ' --max-irreversible-block-age 9999999'\n ' --contracts-console'\n ' --genesis-json ' + os.path.abspath(args.genesis) +\n ' --blocks-dir ' + os.path.abspath(dir) + '/blocks'\n ' --config-dir ' + os.path.abspath(dir) +\n ' --data-dir ' + os.path.abspath(dir) +\n ' --chain-state-db-size-mb 1024'\n ' --http-server-address 127.0.0.1:' + str(8000 + nodeIndex) +\n ' --p2p-listen-endpoint 127.0.0.1:' + str(9000 + nodeIndex) +\n ' --max-clients ' + str(maxClients) +\n ' --p2p-max-nodes-per-host ' + str(maxClients) +\n ' --enable-stale-production'\n ' --producer-name ' + account['name'] +\n ' --private-key \\'[\"' + account['pub'] + '\",\"' + account['pvt'] + '\"]\\''\n ' --plugin eosio::http_plugin'\n ' --plugin eosio::chain_api_plugin'\n ' --plugin eosio::producer_plugin' +\n otherOpts)\n with open(dir + 'stderr', mode='w') as f:\n f.write(cmd + '\\n\\n')\n background(cmd + ' 2>>' + dir + 'stderr')\n\ndef startProducers(b, e):\n for i in range(b, e):\n startNode(i - b + 1, accounts[i])\n\ndef createSystemAccounts():\n for a in systemAccounts:\n run(args.cleos + 'create account eosio ' + a + ' ' + args.public_key)\n\ndef intToCurrency(i):\n return '%d.%04d %s' % (i // 10000, i % 10000, args.symbol)\n\ndef allocateFunds(b, e):\n dist = numpy.random.pareto(1.161, e - b).tolist() # 1.161 = 80/20 rule\n dist.sort()\n dist.reverse()\n factor = 1_000_000_000 / sum(dist)\n total = 0\n for i in range(b, e):\n funds = round(factor * dist[i - b] * 10000)\n if i >= firstProducer and i < firstProducer + numProducers:\n funds = max(funds, round(args.min_producer_funds * 10000))\n total += funds\n accounts[i]['funds'] = funds\n return total\n\ndef createStakedAccounts(b, e):\n ramFunds = round(args.ram_funds * 10000)\n configuredMinStake = round(args.min_stake * 10000)\n maxUnstaked = round(args.max_unstaked * 10000)\n for i in range(b, e):\n a = accounts[i]\n funds = a['funds']\n if funds < ramFunds:\n print('skipping %s: not enough funds to cover ram' % a['name'])\n continue\n minStake = min(funds - ramFunds, configuredMinStake)\n unstaked = min(funds - ramFunds - minStake, maxUnstaked)\n stake = funds - ramFunds - unstaked\n stakeNet = round(stake / 2)\n stakeCpu = stake - stakeNet\n print('%s: total funds=%s, ram=%s, net=%s, cpu=%s, unstaked=%s' % (a['name'], intToCurrency(a['funds']), intToCurrency(ramFunds), intToCurrency(stakeNet), intToCurrency(stakeCpu), intToCurrency(unstaked)))\n assert(funds == ramFunds + stakeNet + stakeCpu + unstaked)\n run(args.cleos + 'system newaccount --transfer eosio %s %s --stake-net \"%s\" --stake-cpu \"%s\" --buy-ram \"%s\" ' % \n (a['name'], a['pub'], intToCurrency(stakeNet), intToCurrency(stakeCpu), intToCurrency(ramFunds)))\n run(args.cleos + 'transfer eosio %s \"%s\"' % (a['name'], intToCurrency(unstaked)))\n\ndef regProducers(b, e):\n for i in range(b, e):\n a = accounts[i]\n retry(args.cleos + 'system regproducer ' + a['name'] + ' ' + a['pub'] + ' https://' + a['name'] + '.com' + '/' + a['pub'])\n\ndef listProducers():\n run(args.cleos + 'system listproducers')\n\ndef vote(b, e):\n for i in range(b, e):\n voter = accounts[i]['name']\n prods = random.sample(range(firstProducer, firstProducer + numProducers), args.num_producers_vote)\n prods = ' '.join(map(lambda x: accounts[x]['name'], prods))\n retry(args.cleos + 'system voteproducer prods ' + voter + ' ' + prods)\n\ndef claimRewards():\n table = getJsonOutput(args.cleos + 'get table eosio eosio producers -l 100')\n times = []\n for row in table['rows']:\n if row['unpaid_blocks'] and not row['last_claim_time']:\n times.append(getJsonOutput(args.cleos + 'system claimrewards -j ' + row['owner'])['processed']['elapsed'])\n print('Elapsed time for claimrewards:', times)\n\ndef vote(b, e):\n for i in range(b, e):\n voter = accounts[i]['name']\n prods = random.sample(range(firstProducer, firstProducer + numProducers), args.num_producers_vote)\n prods = ' '.join(map(lambda x: accounts[x]['name'], prods))\n retry(args.cleos + 'system voteproducer prods ' + voter + ' ' + prods)\n\ndef proxyVotes(b, e):\n vote(firstProducer, firstProducer + 1)\n proxy = accounts[firstProducer]['name']\n retry(args.cleos + 'system regproxy ' + proxy)\n sleep(1.0)\n for i in range(b, e):\n voter = accounts[i]['name']\n retry(args.cleos + 'system voteproducer proxy ' + voter + ' ' + proxy)\n\ndef updateAuth(account, permission, parent, controller):\n run(args.cleos + 'push action eosio updateauth' + jsonArg({\n 'account': account,\n 'permission': permission,\n 'parent': parent,\n 'auth': {\n 'threshold': 1, 'keys': [], 'waits': [],\n 'accounts': [{\n 'weight': 1,\n 'permission': {'actor': controller, 'permission': 'active'}\n }]\n }\n }) + '-p ' + account + '@' + permission)\n\ndef resign(account, controller):\n updateAuth(account, 'owner', '', controller)\n updateAuth(account, 'active', 'owner', controller)\n sleep(1)\n run(args.cleos + 'get account ' + account)\n\ndef randomTransfer(b, e):\n for j in range(20):\n src = accounts[random.randint(b, e - 1)]['name']\n dest = src\n while dest == src:\n dest = accounts[random.randint(b, e - 1)]['name']\n run(args.cleos + 'transfer -f ' + src + ' ' + dest + ' \"0.0001 ' + args.symbol + '\"' + ' || true')\n\ndef msigProposeReplaceSystem(proposer, proposalName):\n requestedPermissions = []\n for i in range(firstProducer, firstProducer + numProducers):\n requestedPermissions.append({'actor': accounts[i]['name'], 'permission': 'active'})\n trxPermissions = [{'actor': 'eosio', 'permission': 'active'}]\n with open(fastUnstakeSystem, mode='rb') as f:\n setcode = {'account': 'eosio', 'vmtype': 0, 'vmversion': 0, 'code': f.read().hex()}\n run(args.cleos + 'multisig propose ' + proposalName + jsonArg(requestedPermissions) + \n jsonArg(trxPermissions) + 'eosio setcode' + jsonArg(setcode) + ' -p ' + proposer)\n\ndef msigApproveReplaceSystem(proposer, proposalName):\n for i in range(firstProducer, firstProducer + numProducers):\n run(args.cleos + 'multisig approve ' + proposer + ' ' + proposalName +\n jsonArg({'actor': accounts[i]['name'], 'permission': 'active'}) +\n '-p ' + accounts[i]['name'])\n\ndef msigExecReplaceSystem(proposer, proposalName):\n retry(args.cleos + 'multisig exec ' + proposer + ' ' + proposalName + ' -p ' + proposer)\n\ndef msigReplaceSystem():\n run(args.cleos + 'push action eosio buyrambytes' + jsonArg(['eosio', accounts[0]['name'], 200000]) + '-p eosio')\n sleep(1)\n msigProposeReplaceSystem(accounts[0]['name'], 'fast.unstake')\n sleep(1)\n msigApproveReplaceSystem(accounts[0]['name'], 'fast.unstake')\n msigExecReplaceSystem(accounts[0]['name'], 'fast.unstake')\n\ndef produceNewAccounts():\n with open('newusers', 'w') as f:\n for i in range(3000, 30000):\n x = getOutput(args.cleos + 'create key')\n r = re.match('Private key: *([^ \\n]*)\\nPublic key: *([^ \\n]*)', x, re.DOTALL | re.MULTILINE)\n name = 'user'\n for j in range(7, -1, -1):\n name += chr(ord('a') + ((i >> (j * 4)) & 15))\n print(i, name)\n f.write(' {\"name\":\"%s\", \"pvt\":\"%s\", \"pub\":\"%s\"},\\n' % (name, r[1], r[2]))\n\ndef stepKillAll():\n run('killall keosd nodeos || true')\n sleep(1.5)\ndef stepStartWallet():\n startWallet()\n importKeys()\ndef stepStartBoot():\n startNode(0, {'name': 'eosio', 'pvt': args.private_key, 'pub': args.public_key})\n sleep(1.5)\ndef stepInstallSystemContracts():\n run(args.cleos + 'set contract eosio.token ' + args.contracts_dir + 'eosio.token/')\n run(args.cleos + 'set contract eosio.msig ' + args.contracts_dir + 'eosio.msig/')\ndef stepCreateTokens():\n run(args.cleos + 'push action eosio.token create \\'[\"eosio\", \"10000000000.0000 %s\"]\\' -p eosio.token' % (args.symbol))\n totalAllocation = allocateFunds(0, len(accounts))\n run(args.cleos + 'push action eosio.token issue \\'[\"eosio\", \"%s\", \"memo\"]\\' -p eosio' % intToCurrency(totalAllocation))\n sleep(1)\ndef stepSetSystemContract():\n retry(args.cleos + 'set contract eosio ' + args.contracts_dir + 'eosio.system/')\n sleep(1)\n run(args.cleos + 'push action eosio setpriv' + jsonArg(['eosio.msig', 1]) + '-p eosio@active')\ndef stepCreateStakedAccounts():\n createStakedAccounts(0, len(accounts))\ndef stepRegProducers():\n regProducers(firstProducer, firstProducer + numProducers)\n sleep(1)\n listProducers()\ndef stepStartProducers():\n startProducers(firstProducer, firstProducer + numProducers)\n sleep(args.producer_sync_delay)\ndef stepVote():\n vote(0, 0 + args.num_voters)\n sleep(1)\n listProducers()\n sleep(5)\ndef stepProxyVotes():\n proxyVotes(0, 0 + args.num_voters)\ndef stepResign():\n resign('eosio', 'eosio.prods')\n for a in systemAccounts:\n resign(a, 'eosio')\ndef stepTransfer():\n while True:\n randomTransfer(0, args.num_senders)\ndef stepLog():\n run('tail -n 60 ' + args.nodes_dir + '00-eosio/stderr')\n\n# Command Line Arguments\n\nparser = argparse.ArgumentParser()\n\ncommands = [\n ('k', 'kill', stepKillAll, True, \"Kill all nodeos and keosd processes\"),\n ('w', 'wallet', stepStartWallet, True, \"Start keosd, create wallet, fill with keys\"),\n ('b', 'boot', stepStartBoot, True, \"Start boot node\"),\n ('s', 'sys', createSystemAccounts, True, \"Create system accounts (eosio.*)\"),\n ('c', 'contracts', stepInstallSystemContracts, True, \"Install system contracts (token, msig)\"),\n ('t', 'tokens', stepCreateTokens, True, \"Create tokens\"),\n ('S', 'sys-contract', stepSetSystemContract, True, \"Set system contract\"),\n ('T', 'stake', stepCreateStakedAccounts, True, \"Create staked accounts\"),\n ('p', 'reg-prod', stepRegProducers, True, \"Register producers\"),\n ('P', 'start-prod', stepStartProducers, True, \"Start producers\"),\n ('v', 'vote', stepVote, True, \"Vote for producers\"),\n ('R', 'claim', claimRewards, True, \"Claim rewards\"),\n ('x', 'proxy', stepProxyVotes, True, \"Proxy votes\"),\n ('q', 'resign', stepResign, True, \"Resign eosio\"),\n ('m', 'msg-replace', msigReplaceSystem, False, \"Replace system contract using msig\"),\n ('X', 'xfer', stepTransfer, False, \"Random transfer tokens (infinite loop)\"),\n ('l', 'log', stepLog, True, \"Show tail of node's log\"),\n]\n\nparser.add_argument('--public-key', metavar='', help=\"EOSIO Public Key\", default='EOS8Znrtgwt8TfpmbVpTKvA2oB8Nqey625CLN8bCN3TEbgx86Dsvr', dest=\"public_key\")\nparser.add_argument('--private-Key', metavar='', help=\"EOSIO Private Key\", default='5K463ynhZoCDDa4RDcr63cUwWLTnKqmdcoTKTHBjqoKfv4u5V7p', dest=\"private_key\")\nparser.add_argument('--cleos', metavar='', help=\"Cleos command\", default='../../build/programs/cleos/cleos --wallet-url http://localhost:6666 ')\nparser.add_argument('--nodeos', metavar='', help=\"Path to nodeos binary\", default='../../build/programs/nodeos/nodeos')\nparser.add_argument('--keosd', metavar='', help=\"Path to keosd binary\", default='../../build/programs/keosd/keosd')\nparser.add_argument('--contracts-dir', metavar='', help=\"Path to contracts directory\", default='../../build/contracts/')\nparser.add_argument('--nodes-dir', metavar='', help=\"Path to nodes directory\", default='./nodes/')\nparser.add_argument('--genesis', metavar='', help=\"Path to genesis.json\", default=\"./genesis.json\")\nparser.add_argument('--wallet-dir', metavar='', help=\"Path to wallet directory\", default='./wallet/')\nparser.add_argument('--log-path', metavar='', help=\"Path to log file\", default='./output.log')\nparser.add_argument('--symbol', metavar='', help=\"The eosio.system symbol\", default='SYS')\nparser.add_argument('--user-limit', metavar='', help=\"Max number of users. (0 = no limit)\", type=int, default=3000)\nparser.add_argument('--max-user-keys', metavar='', help=\"Maximum user keys to import into wallet\", type=int, default=10)\nparser.add_argument('--ram-funds', metavar='', help=\"How much funds for each user to spend on ram\", type=float, default=0.1)\nparser.add_argument('--min-stake', metavar='', help=\"Minimum stake before allocating unstaked funds\", type=float, default=0.9)\nparser.add_argument('--max-unstaked', metavar='', help=\"Maximum unstaked funds\", type=float, default=10)\nparser.add_argument('--producer-limit', metavar='', help=\"Maximum number of producers. (0 = no limit)\", type=int, default=0)\nparser.add_argument('--min-producer-funds', metavar='', help=\"Minimum producer funds\", type=float, default=1000.0000)\nparser.add_argument('--num-producers-vote', metavar='', help=\"Number of producers for which each user votes\", type=int, default=20)\nparser.add_argument('--num-voters', metavar='', help=\"Number of voters\", type=int, default=10)\nparser.add_argument('--num-senders', metavar='', help=\"Number of users to transfer funds randomly\", type=int, default=10)\nparser.add_argument('--producer-sync-delay', metavar='', help=\"Time (s) to sleep to allow producers to sync\", type=int, default=80)\nparser.add_argument('-a', '--all', action='store_true', help=\"Do everything marked with (*)\")\nparser.add_argument('-H', '--http-port', type=int, default=8000, metavar='', help='HTTP port for cleos')\n\nfor (flag, command, function, inAll, help) in commands:\n prefix = ''\n if inAll: prefix += '*'\n if prefix: help = '(' + prefix + ') ' + help\n if flag:\n parser.add_argument('-' + flag, '--' + command, action='store_true', help=help, dest=command)\n else:\n parser.add_argument('--' + command, action='store_true', help=help, dest=command)\n \nargs = parser.parse_args()\n\nargs.cleos += '--url http://localhost:%d ' % args.http_port\n\nlogFile = open(args.log_path, 'a')\n\nlogFile.write('\\n\\n' + '*' * 80 + '\\n\\n\\n')\n\nwith open('accounts.json') as f:\n a = json.load(f)\n if args.user_limit:\n del a['users'][args.user_limit:]\n if args.producer_limit:\n del a['producers'][args.producer_limit:]\n firstProducer = len(a['users'])\n numProducers = len(a['producers'])\n accounts = a['users'] + a['producers']\n\nmaxClients = numProducers + 10\n\nhaveCommand = False\nfor (flag, command, function, inAll, help) in commands:\n if getattr(args, command) or inAll and args.all:\n if function:\n haveCommand = True\n function()\nif not haveCommand:\n print('bios-boot-tutorial.py: Tell me what to do. -a does almost everything. -h shows options.')\n" ]
[ [ "numpy.random.pareto" ] ]
Mr-Elysium/wallstreet
[ "621c2dd966baf1b062ae0af197e0119ae8b6c1f8" ]
[ "wallstreet/blackandscholes.py" ]
[ "import requests\nfrom bs4 import BeautifulSoup\n\nfrom scipy.interpolate import interp1d\nfrom scipy import sqrt, log, exp\nfrom scipy.stats import norm\nfrom scipy.optimize import fsolve\n\nfrom wallstreet.constants import *\n\n\ndef riskfree():\n try:\n r = requests.get(TREASURY_URL)\n soup = BeautifulSoup(r.text, 'html.parser')\n\n table = soup.find(\"table\", attrs={'class' : 't-chart'})\n rows = table.find_all('tr')\n lastrow = len(rows)-1\n cells = rows[lastrow].find_all(\"td\")\n date = cells[0].get_text()\n m1 = float(cells[1].get_text())\n m3 = float(cells[2].get_text())\n m6 = float(cells[3].get_text())\n y1 = float(cells[4].get_text())\n y2 = float(cells[5].get_text())\n y3 = float(cells[6].get_text())\n y5 = float(cells[7].get_text())\n y7 = float(cells[8].get_text())\n y10 = float(cells[9].get_text())\n y20 = float(cells[10].get_text())\n y30 = float(cells[11].get_text())\n\n years = (0, 1/12, 3/12, 6/12, 12/12, 24/12, 36/12, 60/12, 84/12, 120/12, 240/12, 360/12)\n rates = (OVERNIGHT_RATE, m1/100, m3/100, m6/100, y1/100, y2/100, y3/100, y5/100, y7/100, y10/100, y20/100, y30/100)\n return interp1d(years, rates)\n # If scraping treasury data fails use the constant fallback risk free rate\n except Exception:\n return lambda x: FALLBACK_RISK_FREE_RATE\n\n\nclass BlackandScholes:\n\n def __init__(self, S, K, T, price, r, option, q=0):\n self.S, self.K, self.T, self.option, self.q = S, K, T, option, q\n self.r = r\n self.opt_price = price\n self.impvol = self.implied_volatility()\n\n @staticmethod\n def _BlackScholesCall(S, K, T, sigma, r, q):\n d1 = (log(S/K) + (r - q + (sigma**2)/2)*T)/(sigma*sqrt(T))\n d2 = d1 - sigma*sqrt(T)\n return S*exp(-q*T)*norm.cdf(d1) - K*exp(-r*T)*norm.cdf(d2)\n\n @staticmethod\n def _BlackScholesPut(S, K, T, sigma, r, q):\n d1 = (log(S/K) + (r - q + (sigma**2)/2)*T)/(sigma*sqrt(T))\n d2 = d1 - sigma*sqrt(T)\n return K*exp(-r*T)*norm.cdf(-d2) - S*exp(-q*T)*norm.cdf(-d1)\n\n def _fprime(self, sigma):\n logSoverK = log(self.S/self.K)\n n12 = ((self.r + sigma**2/2)*self.T)\n numerd1 = logSoverK + n12\n d1 = numerd1/(sigma*sqrt(self.T))\n return self.S*sqrt(self.T)*norm.pdf(d1)*exp(-self.r*self.T)\n\n def BS(self, S, K, T, sigma, r, q):\n if self.option == 'Call':\n return self._BlackScholesCall(S, K, T, sigma, r, q)\n elif self.option == 'Put':\n return self._BlackScholesPut(S, K, T, sigma, r, q)\n\n def implied_volatility(self):\n impvol = lambda x: self.BS(self.S, self.K, self.T, x, self.r, self.q) - self.opt_price\n iv = fsolve(impvol, SOLVER_STARTING_VALUE, fprime=self._fprime, xtol=IMPLIED_VOLATILITY_TOLERANCE)\n return iv[0]\n\n def delta(self):\n h = DELTA_DIFFERENTIAL\n p1 = self.BS(self.S + h, self.K, self.T, self.impvol, self.r, self.q)\n p2 = self.BS(self.S - h, self.K, self.T, self.impvol, self.r, self.q)\n return (p1-p2)/(2*h)\n\n def gamma(self):\n h = GAMMA_DIFFERENTIAL\n p1 = self.BS(self.S + h, self.K, self.T, self.impvol, self.r, self.q)\n p2 = self.BS(self.S, self.K, self.T, self.impvol, self.r, self.q)\n p3 = self.BS(self.S - h, self.K, self.T, self.impvol, self.r, self.q)\n return (p1 - 2*p2 + p3)/(h**2)\n\n def vega(self):\n h = VEGA_DIFFERENTIAL\n p1 = self.BS(self.S, self.K, self.T, self.impvol + h, self.r, self.q)\n p2 = self.BS(self.S, self.K, self.T, self.impvol - h, self.r, self.q)\n return (p1-p2)/(2*h*100)\n\n def theta(self):\n h = THETA_DIFFERENTIAL\n p1 = self.BS(self.S, self.K, self.T + h, self.impvol, self.r, self.q)\n p2 = self.BS(self.S, self.K, self.T - h, self.impvol, self.r, self.q)\n return (p1-p2)/(2*h*365)\n\n def rho(self):\n h = RHO_DIFFERENTIAL\n p1 = self.BS(self.S, self.K, self.T, self.impvol, self.r + h, self.q)\n p2 = self.BS(self.S, self.K, self.T, self.impvol, self.r - h, self.q)\n return (p1-p2)/(2*h*100)\n" ]
[ [ "scipy.optimize.fsolve", "scipy.log", "scipy.stats.norm.cdf", "scipy.stats.norm.pdf", "scipy.sqrt", "scipy.interpolate.interp1d", "scipy.exp" ] ]
deeplearninc/relaax
[ "a0cf280486dc74dca3857c85ec0e4c34e88d6b2b" ]
[ "relaax/common/rlx_message.py" ]
[ "from builtins import object\n\nimport numpy as np\nfrom PIL import Image\nfrom struct import pack, unpack_from\n\nV = True\n\n\nclass RLXMessageImage(object):\n def __init__(self, image):\n self.image = image\n\n\nclass RLXMessage(object):\n # types: https://docs.python.org/3.5/library/struct.html#struct.pack_into\n TYPE_NONE = 0\n TYPE_NULL = 1\n TYPE_INT4 = 2\n TYPE_STRING_UTF8 = 3\n TYPE_DOUBLE = 4\n TYPE_BOOLEAN = 5\n TYPE_IMAGE = 6\n TYPE_NDARRAY = 7\n TYPE_LIST = 8\n TYPE_UINT4 = 9\n TYPE_INT64 = 10\n TYPE_DICT = 11\n\n pack_info = {\n type(None).__name__: {'id': TYPE_NULL, 'pack_func': lambda cls, *args: cls._pack_null(*args),\n 'unpack_func': lambda cls, *args: cls._unpack_null(*args)},\n int.__name__: {'id': TYPE_INT4, 'pack_func': lambda cls, *args: cls._pack_int(*args),\n 'unpack_func': lambda cls, *args: cls._unpack_int(*args)},\n 'int32': {'id': TYPE_INT4, 'pack_func': lambda cls, *args: cls._pack_int(*args),\n 'unpack_func': lambda cls, *args: cls._unpack_int(*args)},\n 'int64': {'id': TYPE_INT64, 'pack_func': lambda cls, *args: cls._pack_int64(*args),\n 'unpack_func': lambda cls, *args: cls._unpack_int64(*args)},\n str.__name__: {'id': TYPE_STRING_UTF8, 'pack_func': lambda cls, *args: cls._pack_string(*args),\n 'unpack_func': lambda cls, *args: cls._unpack_string(*args)},\n float.__name__: {'id': TYPE_DOUBLE, 'pack_func': lambda cls, *args: cls._pack_double(*args),\n 'unpack_func': lambda cls, *args: cls._unpack_double(*args)},\n 'float64': {'id': TYPE_DOUBLE, 'pack_func': lambda cls, *args: cls._pack_double(*args),\n 'unpack_func': lambda cls, *args: cls._unpack_double(*args)},\n bool.__name__: {'id': TYPE_BOOLEAN, 'pack_func': lambda cls, *args: cls._pack_bool(*args),\n 'unpack_func': lambda cls, *args: cls._unpack_bool(*args)},\n RLXMessageImage.__name__: {'id': TYPE_IMAGE, 'pack_func': lambda cls, *args: cls._pack_image(*args),\n 'unpack_func': lambda cls, *args: cls._unpack_image(*args)},\n np.ndarray.__name__: {'id': TYPE_NDARRAY, 'pack_func': lambda cls, *args: cls._pack_ndarray(*args),\n 'unpack_func': lambda cls, *args: cls._unpack_ndarray(*args)},\n list.__name__: {'id': TYPE_LIST, 'pack_func': lambda cls, *args: cls._pack_list(*args),\n 'unpack_func': lambda cls, *args: cls._unpack_list(*args)},\n dict.__name__: {'id': TYPE_DICT, 'pack_func': lambda cls, *args: cls._pack_dict(*args),\n 'unpack_func': lambda cls, *args: cls._unpack_dict(*args)}\n }\n\n @classmethod\n def _pack_type(cls, type_id, buf, pack_type=True):\n if pack_type:\n buf += pack(\"B\", type_id)\n\n @classmethod\n def _unpack_type(cls, buf, offset):\n return unpack_from(\"B\", buf, offset)[0], offset+1\n\n @classmethod\n def _pack_null(cls, value, buf, pack_type=True):\n cls._pack_type(cls.TYPE_NULL, buf, pack_type)\n\n @classmethod\n def _unpack_null(cls, buf, offset):\n return None, offset\n\n @classmethod\n def _pack_string(cls, value, buf, pack_type=True):\n cls._pack_type(cls.TYPE_STRING_UTF8, buf, pack_type)\n\n bval = bytearray(str(value).encode('UTF-8'))\n buf += pack(\"I\", len(bval))\n buf += bval\n\n @classmethod\n def _unpack_string(cls, buf, offset):\n reslen = unpack_from(\"I\", buf, offset)[0]\n offset += 4\n res = str(buf[offset:offset+reslen].decode('UTF-8'))\n offset += reslen\n\n return res, offset\n\n @classmethod\n def _pack_int(cls, value, buf, pack_type=True):\n cls._pack_type(cls.TYPE_INT4, buf, pack_type)\n buf += pack(\"i\", value)\n\n @classmethod\n def _unpack_int(cls, buf, offset):\n res = unpack_from(\"i\", buf, offset)[0]\n offset += 4\n return res, offset\n\n @classmethod\n def _pack_int64(cls, value, buf, pack_type=True):\n cls._pack_type(cls.TYPE_INT64, buf, pack_type)\n buf += pack(\"q\", value)\n\n @classmethod\n def _unpack_int64(cls, buf, offset):\n res = unpack_from(\"q\", buf, offset)[0]\n offset += 8\n return res, offset\n\n @classmethod\n def _pack_double(cls, value, buf, pack_type=True):\n cls._pack_type(cls.TYPE_DOUBLE, buf, pack_type)\n buf += pack(\"d\", value)\n\n @classmethod\n def _unpack_double(cls, buf, offset):\n res = unpack_from(\"d\", buf, offset)[0]\n offset += 8\n return res, offset\n\n @classmethod\n def _pack_bool(cls, value, buf, pack_type=True):\n cls._pack_type(cls.TYPE_BOOLEAN, buf, pack_type)\n buf += pack(\"B\", 1 if value else 0)\n\n @classmethod\n def _unpack_bool(cls, buf, offset):\n res = unpack_from(\"B\", buf, offset)[0]\n res = res == 1\n offset += 1\n return res, offset\n\n @classmethod\n def _pack_image(cls, value, buf, pack_type=True):\n cls._pack_type(cls.TYPE_IMAGE, buf, pack_type)\n cls._pack_string(value.image.mode, buf, False)\n buf += pack(\"I\", value.image.size[0])\n buf += pack(\"I\", value.image.size[1])\n\n bval = value.image.tobytes()\n buf += pack(\"I\", len(bval))\n buf += bval\n\n @classmethod\n def _unpack_image(cls, buf, offset):\n mode, offset = cls._unpack_string(buf, offset)\n x = unpack_from(\"I\", buf, offset)[0]\n offset += 4\n y = unpack_from(\"I\", buf, offset)[0]\n offset += 4\n\n reslen = unpack_from(\"I\", buf, offset)[0]\n offset += 4\n img = Image.frombytes(mode, (x, y), bytes(buf[offset:offset+reslen])) # .convert(\"RGB\")\n res = np.asarray(img)\n if img.mode in [\"L\", \"RGB\", \"RGBA\", \"CMYK\", \"YCbCr\", \"LAB\", \"HSV\"]:\n res = res.astype(np.float32) * (1.0 / 255.0)\n\n # print(res.shape)\n # res = np.reshape(res, (x, y, 1))\n offset += reslen\n return res, offset\n\n @classmethod\n def _pack_ndarray(cls, value, buf, pack_type=True):\n cls._pack_type(cls.TYPE_NDARRAY, buf, pack_type)\n cls._pack_string(str(value.dtype), buf, False)\n buf += pack(\"I\", len(value.shape))\n for ns in value.shape:\n buf += pack(\"I\", ns)\n\n bval = value.tobytes()\n buf += pack(\"I\", len(bval))\n buf += bval\n\n @classmethod\n def _unpack_ndarray(cls, buf, offset):\n dtype, offset = cls._unpack_string(buf, offset)\n shape_len = unpack_from(\"I\", buf, offset)[0]\n offset += 4\n shape = []\n for i in range(0, shape_len):\n item = unpack_from(\"I\", buf, offset)[0]\n offset += 4\n shape.append(item)\n\n reslen = unpack_from(\"I\", buf, offset)[0]\n offset += 4\n res = np.frombuffer(buf[offset:offset+reslen], dtype=np.dtype(dtype))\n res = res.reshape(shape)\n offset += reslen\n return res, offset\n\n @classmethod\n def _pack_list(cls, value, buf, pack_type=True):\n cls._pack_type(cls.TYPE_LIST, buf, pack_type)\n buf += pack(\"I\", len(value))\n for item in value:\n cls._pack_value(item, buf)\n\n @classmethod\n def _unpack_list(cls, buf, offset):\n reslen = unpack_from(\"I\", buf, offset)[0]\n offset += 4\n res = []\n for i in range(0, reslen):\n (item, offset) = cls._unpack_value(buf, offset)\n res.append(item)\n return res, offset\n\n @classmethod\n def _pack_dict(cls, value, buf, pack_type=True):\n cls._pack_type(cls.TYPE_DICT, buf, pack_type)\n buf += pack(\"I\", len(value))\n\n for key in value:\n cls._pack_string(key, buf, False)\n cls._pack_value(value[key], buf)\n\n @classmethod\n def _unpack_dict(cls, buf, offset):\n reslen = unpack_from(\"I\", buf, offset)[0]\n offset += 4\n res = {}\n for i in range(0, reslen):\n (field_name, offset) = cls._unpack_string(buf, offset)\n (item, offset) = cls._unpack_value(buf, offset)\n res[field_name] = item\n return res, offset\n\n @classmethod\n def _pack_value(cls, value, buf):\n item = cls.pack_info.get(type(value).__name__, None)\n if item is None:\n item = cls.pack_info.get(str.__name__)\n\n item.get('pack_func')(cls, value, buf)\n\n @classmethod\n def _unpack_value(cls, buf, offset):\n valtype, offset = cls._unpack_type(buf, offset)\n for key, item in cls.pack_info.items():\n if item['id'] == valtype:\n return item['unpack_func'](cls, buf, offset)\n\n raise Exception(\"Unknown type:%d\" % valtype)\n\n @classmethod\n def to_wire(cls, data):\n buf = bytearray()\n if V:\n buf += pack(\"I\", 1)\n\n for key in data:\n # print((key, type(data[key]).__name__))\n cls._pack_string(key, buf, False)\n cls._pack_value(data[key], buf)\n\n return buf\n\n @classmethod\n def from_wire(cls, data):\n res = {}\n offset = 0\n if V:\n # read version\n unpack_from(\"I\", data, offset)[0]\n offset += 4\n\n while offset < len(data):\n (field_name, offset) = cls._unpack_string(data, offset)\n (res[field_name], offset) = cls._unpack_value(data, offset)\n\n return res\n" ]
[ [ "numpy.asarray", "numpy.dtype" ] ]
MrAttoAttoAtto/CircuitSimulatorC2
[ "4d821c86404fe3271363fd8c1438e4ca29c17a13" ]
[ "Initial Testing/RLC Test.py" ]
[ "\nimport math\nimport subprocess\nimport time\nfrom copy import deepcopy\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.linalg\n\n\n# Initial guess\ninput_vec = [3, 0, 0, 1e-3]\n\n# Resistance in Ohms\nR = 30\n\n# Capacitance in Farads\nC = 2e-6\n\n# Inductance in Henrys\nL = 20e-3\n\n# Initial current\nI_0 = 0\n\n# Frequency of the AC source in Hertz\nf = 909\n\n# AC peak\nVin_AC_peak = 9*math.sqrt(2)\n\n# DC component\nVin_DC = 0\n\nsin_multiplier = f*2*math.pi\n\n# Combo of AC and DC power source\ndef get_Vin(t):\n return Vin_AC_peak*math.sin(sin_multiplier*t) + Vin_DC\n\n\n# Starting time, and size of time steps\nt = 1e-5\ndelta_t = 1e-5\n\nold_v2 = 0\nold_v3 = 0\n\n# Holds results for plotting\nresults = [[],[],[]]\n\n# Create the Jacobian for this input vector\ng_ind = L*delta_t/2\ng_cap = C/delta_t\njac = np.array([[1/R, -1/R, 0, -1],\n [-1/R, g_ind + 1/R, -g_ind, 0],\n [0, -g_ind, g_ind + g_cap, 0],\n [1, 0, 0, 0]])\n\nstart = time.time()\nwhile True:\n\n # Load the variables from the input vector\n v1 = input_vec[0]\n v2 = input_vec[1]\n v3 = input_vec[2]\n iv = input_vec[3]\n\n # Calculate the values in result vector\n result_vector = [0, 0, 0, 0]\n\n result_vector[0] = -((v1-v2)/R - iv) # Current at 1\n result_vector[1] = -(I_0 + L*delta_t/2*(old_v2+v2-v3-old_v3) - (v1-v2)/R) # Current at 2\n result_vector[2] = -(C*(v3-old_v3)/delta_t - I_0 - L*delta_t/2*(old_v2+v2-v3-old_v3)) # Current at 3\n result_vector[3] = -(v1-get_Vin(t)) # Voltage at 1\n \n '''\n # Calculate the new (better) input vector by doing new x = old x - J(x)^(-1)*F(x), where J(x)^(-1) is the inverse Jacobian of x, and F(x) is the result vector given by x\n inv_jac = lapack_inverse(jac)\n res = np.dot(inv_jac, np.array(result_vector))\n input_vec -= res\n '''\n\n delta_in = scipy.linalg.lapack.dgesv(jac, result_vector)[2]\n input_vec += delta_in\n\n # If the better guess is indistinguishable from the prior guess, we probably have the right value...\n if (abs(delta_in) < 1e-5).all():\n # Updates the variables like time and the \"old\" voltages\n t += delta_t\n old_v2 = v2\n old_v3 = v3\n I_0 = I_0 + delta_t/2*(old_v2+v2-v3-old_v3)\n \n results[0].append(t)\n results[1].append(v3)\n results[2].append(iv)\n\n if t > 60/60:\n print(time.time()-start)\n # Plots nice graph\n fig, ax = plt.subplots(1, 1, figsize=(20, 9))\n ax.scatter(results[0], results[1])\n ax.scatter(results[0], results[2])\n # '''\n plt.show()\n # '''\n\n '''\n plt.savefig(\"fig.svg\", format='svg', dpi=300)\n subprocess.call([\"/usr/bin/open\", \"fig.svg\"])\n '''\n\n break\n" ]
[ [ "numpy.array", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show" ] ]
gift-surg/PySiTK
[ "6bb9419b9e5ec7c20aab443172b86da69a268b9a" ]
[ "tests/simple_itk_helper_test.py" ]
[ "# \\file simple_itk_helper_test.py\n# \\brief Class containing unit tests for module SimpleITKHelper\n#\n# \\author Michael Ebner ([email protected])\n# \\date December 2015\n\n\n# Import libraries\nimport SimpleITK as sitk\nimport itk\nimport numpy as np\nimport unittest\nimport os\nimport sys\n\n# Import modules\nimport pysitk.simple_itk_helper as sitkh\n\nfrom pysitk.definitions import DIR_TEST, DIR_TMP\n\n\ndef get_registration_transform(fixed_sitk,\n moving_sitk,\n transform_type,\n print_info=False):\n\n # Instantiate interface method to the modular ITKv4 registration framework\n registration_method = sitk.ImageRegistrationMethod()\n\n # Select between using the geometrical center (GEOMETRY) of the images or\n # using the center of mass (MOMENTS) given by the image intensities\n # initial_transform = sitk.CenteredTransformInitializer(\n # fixed_sitk,\n # moving_sitk,\n # sitk.Euler3DTransform(),\n # sitk.CenteredTransformInitializerFilter.MOMENTS)\n if transform_type == \"rigid\":\n initial_transform = sitk.Euler3DTransform()\n elif transform_type == \"affine\":\n initial_transform = sitk.AffineTransform(3)\n\n # Set the initial transform and parameters to optimize\n registration_method.SetInitialTransform(initial_transform)\n\n # Set interpolator to use\n registration_method.SetInterpolator(sitk.sitkLinear)\n\n \"\"\"\n similarity metric settings\n \"\"\"\n # Use normalized cross correlation using a small neighborhood for each\n # voxel between two images, with speed optimizations for dense registration\n # registration_method.SetMetricAsANTSNeighborhoodCorrelation(radius=5)\n\n # Use negative normalized cross correlation image metric\n # registration_method.SetMetricAsCorrelation()\n\n # Use demons image metric\n # registration_method.SetMetricAsDemons(intensityDifferenceThreshold=1e-3)\n\n # Use mutual information between two images\n # registration_method.SetMetricAsJointHistogramMutualInformation(\n # numberOfHistogramBins=50,\n # varianceForJointPDFSmoothing=3)\n\n # Use the mutual information between two images to be registered using the\n # method of Mattes2001\n registration_method.SetMetricAsMattesMutualInformation()\n\n # Use negative means squares image metric\n # registration_method.SetMetricAsMeanSquares()\n\n \"\"\"\n optimizer settings\n \"\"\"\n # Set optimizer to Nelder-Mead downhill simplex algorithm\n # registration_method.SetOptimizerAsAmoeba(\n # simplexDelta=0.1,\n # numberOfIterations=100,\n # parametersConvergenceTolerance=1e-8,\n # functionConvergenceTolerance=1e-4,\n # withRestarts=False)\n\n # Conjugate gradient descent optimizer with a golden section line search\n # for nonlinear optimization\n # registration_method.SetOptimizerAsConjugateGradientLineSearch(\n # learningRate=1,\n # numberOfIterations=100,\n # convergenceMinimumValue=1e-8,\n # convergenceWindowSize=10)\n\n # Set the optimizer to sample the metric at regular steps\n # registration_method.SetOptimizerAsExhaustive(numberOfSteps=50,\n # stepLength=1.0)\n\n # Gradient descent optimizer with a golden section line search\n # registration_method.SetOptimizerAsGradientDescentLineSearch(\n # learningRate=1,\n # numberOfIterations=100,\n # convergenceMinimumValue=1e-6,\n # convergenceWindowSize=10)\n\n # Limited memory Broyden Fletcher Goldfarb Shannon minimization with simple\n # bounds\n # registration_method.SetOptimizerAsLBFGSB(\n # gradientConvergenceTolerance=1e-5,\n # maximumNumberOfIterations=500,\n # maximumNumberOfCorrections=5,\n # maximumNumberOfFunctionEvaluations=200,\n # costFunctionConvergenceFactor=1e+7)\n\n # Regular Step Gradient descent optimizer\n registration_method.SetOptimizerAsRegularStepGradientDescent(\n learningRate=1,\n minStep=0.01,\n numberOfIterations=100)\n\n # Estimating scales of transform parameters a step sizes, from the maximum\n # voxel shift in physical space caused by a parameter change (Many more\n # possibilities to estimate scales)\n registration_method.SetOptimizerScalesFromPhysicalShift()\n\n \"\"\"\n setup for the multi-resolution framework\n \"\"\"\n # Set the shrink factors for each level where each level has the same\n # shrink factor for each dimension\n registration_method.SetShrinkFactorsPerLevel(shrinkFactors=[4, 2, 1])\n\n # Set the sigmas of Gaussian used for smoothing at each level\n registration_method.SetSmoothingSigmasPerLevel(smoothingSigmas=[2, 1, 0])\n\n # Enable the smoothing sigmas for each level in physical units (default)\n # or in terms of voxels (then *UnitsOff instead)\n registration_method.SmoothingSigmasAreSpecifiedInPhysicalUnitsOn()\n\n # Connect all of the observers so that we can perform plotting during\n # registration\n # registration_method.AddCommand(sitk.sitkStartEvent, start_plot)\n # registration_method.AddCommand(sitk.sitkEndEvent, end_plot)\n # registration_method.AddCommand(\n # sitk.sitkMultiResolutionIterationEvent, update_multires_iterations)\n # registration_method.AddCommand(\n # sitk.sitkIterationEvent,\n # lambda: plot_values(registration_method))\n\n # print(' Final metric value: {0}'.format(\n # registration_method.GetMetricValue()))\n # print(' Optimizer\\'s stopping condition, {0}'.format(\n # registration_method.GetOptimizerStopConditionDescription()))\n # print(\"\\n\")\n\n # Execute 3D registration\n final_transform_3D_sitk = registration_method.Execute(\n fixed_sitk, moving_sitk)\n if print_info:\n print(\"SimpleITK Image Registration Method (Affine):\")\n print(' Final metric value: {0}'.format(\n registration_method.GetMetricValue()))\n print(' Optimizer\\'s stopping condition, {0}'.format(\n registration_method.GetOptimizerStopConditionDescription()))\n\n if transform_type == \"rigid\":\n return sitk.Euler3DTransform(final_transform_3D_sitk)\n\n return sitk.AffineTransform(final_transform_3D_sitk)\n\n\nclass SimpleItkHelperTest(unittest.TestCase):\n\n def setUp(self):\n self.accuracy = 5\n self.dir_test_data = os.path.join(DIR_TEST, \"BrainWeb\")\n\n self.filename = \"t1_icbm_normal_5mm_pn0_rf0\"\n self.filename_2 = \"t2_icbm_normal_5mm_pn0_rf0\"\n\n self.image_sitk = sitk.ReadImage(os.path.join(\n self.dir_test_data, self.filename + \".nii.gz\"),\n sitk.sitkFloat64)\n self.image_2_sitk = sitk.ReadImage(os.path.join(\n self.dir_test_data, self.filename_2 + \".nii.gz\"),\n sitk.sitkFloat64)\n\n def test_read_write_nifti_image_sitk(self):\n image_sitk = sitk.ReadImage(os.path.join(\n self.dir_test_data, self.filename + \".nii.gz\"))\n foo = os.path.join(DIR_TMP, \"foo.nii.gz\")\n sitkh.write_nifti_image_sitk(image_sitk, foo)\n foo_sitk = sitkh.read_nifti_image_sitk(foo)\n\n nda = sitk.GetArrayFromImage(image_sitk - foo_sitk)\n error = np.linalg.norm(nda)\n self.assertAlmostEqual(error, 0, places=self.accuracy)\n\n def test_get_correct_itk_orientation_from_sitk_image(self):\n\n # Read image via itk\n image_itk = sitkh.read_itk_image(os.path.join(\n self.dir_test_data, self.filename + \".nii.gz\"))\n\n # Change header information of sitk image\n origin = (0, 0, 0)\n direction = (1, 0, 0, 0, 1, 0, 0, 0, 1)\n spacing = (1, 1, 1)\n\n self.image_sitk.SetSpacing(spacing)\n self.image_sitk.SetDirection(direction)\n self.image_sitk.SetOrigin(origin)\n\n # Update header of itk image\n image_itk.SetOrigin(self.image_sitk.GetOrigin())\n image_itk.SetDirection(\n sitkh.get_itk_direction_from_sitk_image(self.image_sitk))\n image_itk.SetSpacing(self.image_sitk.GetSpacing())\n\n # Write itk image and read it again as sitk image\n itk_update = os.path.join(DIR_TMP, \"itk_update.nii.gz\")\n sitkh.write_nifti_image_itk(image_itk, itk_update)\n image_sitk_from_itk = sitk.ReadImage(itk_update)\n\n # Check origin\n self.assertEqual(np.around(np.linalg.norm(\n np.array(image_sitk_from_itk.GetOrigin()) -\n self.image_sitk.GetOrigin()), decimals=self.accuracy), 0)\n\n # Check spacing\n self.assertEqual(np.around(np.linalg.norm(\n np.array(image_sitk_from_itk.GetSpacing()) -\n self.image_sitk.GetSpacing()), decimals=self.accuracy), 0)\n\n # Check direction matrix\n self.assertEqual(np.around(np.linalg.norm(\n np.array(image_sitk_from_itk.GetDirection()) -\n self.image_sitk.GetDirection()), decimals=self.accuracy), 0)\n\n # Test conversion from sitk direction and sitk origin to sitk affine\n # transform\n def test_get_sitk_affine_transform_from_sitk_direction_and_origin(self):\n\n origin = self.image_sitk.GetOrigin()\n direction = self.image_sitk.GetDirection()\n\n affine_transform_ref = sitkh.get_sitk_affine_transform_from_sitk_image(\n self.image_sitk)\n affine_transform = \\\n sitkh.get_sitk_affine_transform_from_sitk_direction_and_origin(\n direction, origin, self.image_sitk)\n\n # Check Fixed Parameters\n self.assertEqual(np.around(np.linalg.norm(\n np.array(affine_transform_ref.GetFixedParameters()) -\n affine_transform.GetFixedParameters()), decimals=self.accuracy), 0)\n\n # Check Parameters\n self.assertEqual(np.around(np.linalg.norm(\n np.array(affine_transform_ref.GetParameters()) -\n affine_transform.GetParameters()), decimals=self.accuracy), 0)\n\n def test_get_sitk_affine_transform_from_sitk_image(self):\n\n # Get indices with intensities greater than 0\n # indices \\in \\R^{dim, N_points}\n indices = np.array(\n np.where(sitk.GetArrayFromImage(self.image_sitk)[::-1] > 0))\n N_points = indices.shape[1]\n\n # Get sitk affine transform from image first (the way it is used in\n # slice.py)\n affine_transform_sitk = \\\n sitkh.get_sitk_affine_transform_from_sitk_image(self.image_sitk)\n\n for i in range(0, N_points):\n index = [int(j) for j in indices[:, i]]\n\n # Check Alignment\n self.assertEqual(np.around(np.linalg.norm(np.array(\n affine_transform_sitk.TransformPoint(index)) -\n self.image_sitk.TransformIndexToPhysicalPoint(index)),\n decimals=self.accuracy), 0)\n\n # Test whether physical position of voxel obtained via affine transform\n # corresponds to the one obtained by the image directly\n def test_computation_point_physical_space_via_affine_transform(self):\n\n # Get indices with intensities greater than 0\n # indices \\in \\R^{dim, N_points}\n indices = np.array(\n np.where(sitk.GetArrayFromImage(self.image_sitk)[::-1] > 0))\n N_points = indices.shape[1]\n\n # Get sitk affine transform from image first\n affine_transform_sitk = \\\n sitkh.get_sitk_affine_transform_from_sitk_image(self.image_sitk)\n\n dim = self.image_sitk.GetDimension()\n A = np.array(affine_transform_sitk.GetMatrix()).reshape(dim, dim)\n t = np.array(affine_transform_sitk.GetTranslation()).reshape(3, 1)\n\n for i in range(0, N_points):\n index = indices[:, i].reshape(dim, 1)\n\n # Check Alignment\n self.assertEqual(np.around(np.linalg.norm(\n (A.dot(index) + t).flatten() -\n self.image_sitk.TransformIndexToPhysicalPoint(\n [int(j) for j in index])), decimals=self.accuracy), 0)\n\n # Test whether \\p get_transformed_sitk_image works correct in the rigid and\n # more general affine case\n def test_get_transformed_sitk_image(self):\n moving_str = self.filename\n fixed_str = self.filename_2\n\n fixed_sitk = self.image_sitk\n moving_sitk = self.image_2_sitk\n\n affine_transform_sitk = get_registration_transform(\n fixed_sitk, moving_sitk, \"affine\")\n rigid_transform_sitk = get_registration_transform(\n fixed_sitk, moving_sitk, \"rigid\")\n\n interpolator = sitk.sitkBSpline\n default_pixel_value = 0.0\n\n # 1) Rigid case\n # Resample based on obtained registration trafo\n moving_rigidly_warped_sitk = sitk.Resample(\n moving_sitk,\n fixed_sitk,\n rigid_transform_sitk,\n interpolator,\n default_pixel_value,\n moving_sitk.GetPixelIDValue())\n\n # Resample after having transformed the moving image manually (inverse\n # transform)\n moving_rigidly_warped_sitkh_sitk = sitkh.get_transformed_sitk_image(\n moving_sitk,\n sitk.Euler3DTransform(rigid_transform_sitk.GetInverse()))\n moving_rigidly_warped_manual_sitk = sitk.Resample(\n moving_rigidly_warped_sitkh_sitk,\n fixed_sitk,\n sitk.Euler3DTransform(),\n interpolator,\n default_pixel_value,\n moving_sitk.GetPixelIDValue())\n\n # Compute difference image\n moving_rigidly_warped_diff_sitk = moving_rigidly_warped_sitk - \\\n moving_rigidly_warped_manual_sitk\n nda_diff_rigid = sitk.GetArrayFromImage(\n moving_rigidly_warped_diff_sitk)\n\n # Check alignment\n self.assertEqual(np.round(np.linalg.norm(\n nda_diff_rigid), decimals=self.accuracy), 0)\n\n # 2) Affine case\n # Resample based on obtained registration trafo\n moving_affinely_warped_sitk = sitk.Resample(\n moving_sitk,\n fixed_sitk,\n affine_transform_sitk,\n interpolator,\n default_pixel_value,\n moving_sitk.GetPixelIDValue())\n\n # Resample after having transformed the moving image manually (inverse\n # transform)\n moving_affinely_warped_sitkh_sitk = sitkh.get_transformed_sitk_image(\n moving_sitk,\n sitk.AffineTransform(affine_transform_sitk.GetInverse()))\n moving_affinely_warped_manual_sitk = sitk.Resample(\n moving_affinely_warped_sitkh_sitk,\n fixed_sitk,\n sitk.Euler3DTransform(),\n interpolator,\n default_pixel_value,\n moving_sitk.GetPixelIDValue())\n\n # Compute difference image\n moving_affinely_warped_diff_sitk = moving_affinely_warped_sitk - \\\n moving_affinely_warped_manual_sitk\n nda_diff_affine = sitk.GetArrayFromImage(\n moving_affinely_warped_diff_sitk)\n\n # Check alignment\n self.assertEqual(np.round(np.linalg.norm(\n nda_diff_affine), decimals=self.accuracy), 0)\n\n def test_get_indices_array_to_flattened_sitk_image(self):\n\n # 3D\n nda = sitk.GetArrayFromImage(self.image_sitk).flatten()\n\n indices = sitkh.get_indices_array_to_flattened_sitk_image_data_array(\n self.image_sitk)\n nda_2 = np.zeros_like(nda)\n for i in range(0, nda_2.size):\n index = [int(j) for j in indices[:, i]]\n nda_2[i] = self.image_sitk.GetPixel(*index)\n\n self.assertEqual(np.round(\n np.linalg.norm(nda_2 - nda),\n decimals=self.accuracy), 0)\n\n # 2D\n self.image_sitk = self.image_sitk[:, :, 5]\n nda = sitk.GetArrayFromImage(self.image_sitk).flatten()\n\n indices = sitkh.get_indices_array_to_flattened_sitk_image_data_array(\n self.image_sitk)\n nda_2 = np.zeros_like(nda)\n for i in range(0, nda_2.size):\n index = [int(j) for j in indices[:, i]]\n nda_2[i] = self.image_sitk.GetPixel(*index)\n\n self.assertEqual(np.round(\n np.linalg.norm(nda_2 - nda),\n decimals=self.accuracy), 0)\n\n\n# nda_rigid = sitk.GetArrayFromImage(moving_rigidly_warped_sitk)\n# nda_rigid_manual = sitk.GetArrayFromImage(moving_rigidly_warped_manual_sitk)\n# norm_diff_rigid = np.linalg.norm(nda_rigid-nda_rigid_manual)\n\n# nda_affine = sitk.GetArrayFromImage(moving_affinely_warped_sitk)\n# nda_affine_manual = sitk.GetArrayFromImage(moving_affinely_warped_manual_sitk)\n# norm_diff_affine = np.linalg.norm(nda_affine-nda_affine_manual)\n\n# print(\"norm_diff_rigid = \" + str(norm_diff_rigid))\n# print(\"norm_diff_affine = \" + str(norm_diff_affine))\n" ]
[ [ "numpy.zeros_like", "numpy.linalg.norm" ] ]
kagemeka/python-algorithms
[ "dface89b8c618845cf524429aa8e97c4b2b10ceb" ]
[ "src/dsalgo_numpy/sieve_of_eratosthenes.py" ]
[ "import numpy as np\n\n\ndef least_prime_factor_np(n: int) -> np.ndarray:\n s = np.arange(n)\n s[:2] = -1\n i = 0\n while i * i < n - 1:\n i += 1\n if s[i] == i:\n np.minimum(s[i * i :: i], i, out=s[i * i :: i])\n return s\n\n\ndef sieve_of_eratosthenes_np(n: int) -> np.ndarray:\n return least_prime_factor_np(n) == np.arange(n)\n\n\ndef greatest_prime_factor_np(n: int) -> np.ndarray:\n s = np.arange(n)\n s[:2] = -1\n i = 0\n while i < n - 1:\n i += 1\n if s[i] == i:\n s[i::i] = i\n return s\n" ]
[ [ "numpy.arange", "numpy.minimum" ] ]
MarcCote/spatial-reasoning
[ "06c57cfafbd1c24b68d6ab634d19806964d867f3", "06c57cfafbd1c24b68d6ab634d19806964d867f3" ]
[ "spatial_reasoning/environment/MDP.py", "spatial_reasoning/models/uvfa_text.py" ]
[ "import numpy as np\n\nclass MDP:\n\n def __init__(self, world, rewards, terminal):\n self.world = world\n self.reward_map = rewards\n self.terminal_map = terminal\n self.shape = self.reward_map.shape\n\n self.M, self.N = self.shape\n self.states = [(i,j) for i in range(self.M) for j in range(self.N)]\n self.children = self.get_children( self.M, self.N )\n\n self.actions = [(-1,0),(1,0),(0,-1),(0,1)]\n self.states = [(i,j) for i in range(self.shape[0]) for j in range(self.shape[1])]\n\n def getActions(self):\n return [i for i in range(len(self.actions))]\n\n def getStates(self):\n return self.states\n\n def transition(self, position, action_ind, fullstate=False):\n action = self.actions[action_ind]\n # print('transitioning: ', action, position)\n candidate = tuple(map(sum, zip(position, action)))\n\n ## if new location is valid,\n ## update the position\n if self.valid(candidate):\n position = candidate\n\n if fullstate:\n state = self.observe(position)\n else:\n state = position\n\n return state\n\n def valid(self, position):\n x, y = position[0], position[1]\n if x >= 0 and x < self.shape[0] and y >= 0 and y < self.shape[1]:\n return True\n else:\n return False\n\n def reward(self, position):\n rew = self.reward_map[position]\n return rew\n\n def terminal(self, position):\n term = self.terminal_map[position]\n return term\n\n def representValues(self, values):\n value_map = np.zeros( self.shape )\n for pos, val in values.items():\n assert(value_map[pos] == 0)\n value_map[pos] = val\n return value_map\n\n # '''\n # start_pos is (i,j)\n # policy is dict from (i,j) --> (delta_i, delta_j)\n # '''\n # def simulate(self, policy, start_pos, num_steps = 100):\n # pos = start_pos\n # visited = set([pos])\n # for step in range(num_steps):\n # # rew = self.reward(pos)\n # term = self.terminal(pos)\n # if term:\n # return 0\n # reachable = policy[pos]\n # selected = 0\n # while selected < len(reachable) and reachable[selected] in visited:\n # # print(' visited ', selected, reachable[selected])\n # selected += 1\n # if selected == len(reachable):\n # selected = 0\n # pos = policy[pos][selected]\n # visited.add(pos)\n # print('position: ', pos)\n # # print(pos, goal)\n # goal = np.argwhere( self.terminal_map ).flatten().tolist()\n # manhattan_dist = abs(pos[0] - goal[0]) + abs(pos[1] - goal[1])\n # return manhattan_dist\n\n '''\n start_pos is (i,j)\n policy is dict from (i,j) --> (delta_i, delta_j)\n '''\n def simulate(self, policy, start_pos, num_steps = 100):\n pos = start_pos\n visited = set([pos])\n for step in range(num_steps):\n # rew = self.reward(pos)\n term = self.terminal(pos)\n if term:\n return step\n reachable = policy[pos]\n selected = 0\n while selected < len(reachable) and reachable[selected] in visited:\n # print(' visited ', selected, reachable[selected])\n selected += 1\n if selected == len(reachable):\n selected = 0\n pos = policy[pos][selected]\n visited.add(pos)\n # print('position: ', pos)\n return step\n\n def get_children(self, M, N):\n children = {}\n for i in range(M):\n for j in range(N):\n pos = (i,j)\n children[pos] = []\n for di in range( max(i-1, 0), min(i+1, M-1)+1 ):\n for dj in range( max(j-1, 0), min(j+1, N-1)+1 ):\n child = (di, dj)\n if pos != child and (i == di or j == dj):\n children[pos].append( child )\n return children\n\n\n '''\n values is M x N map of predicted values\n '''\n def get_policy(self, values):\n policy = {}\n for state in self.states:\n reachable = self.children[state]\n selected = sorted(reachable, key = lambda x: values[x], reverse=True)\n policy[state] = selected\n return policy\n\n\n\nif __name__ == '__main__':\n import pickle, pdb, numpy as np\n info = pickle.load( open('../data/train_10/0.p') )\n print(info.keys())\n mdp = MDP(info['map'], info['rewards'][0], info['terminal'][0])\n print(mdp.world)\n print(mdp.children)\n\n values = np.random.randn(10,10)\n policy = mdp.get_policy(values)\n\n steps = mdp.simulate(policy, (0,0))\n print(steps)\n\n pdb.set_trace()\n\n\n", "## predicts entire value map\n## rather than a single value\n\nimport torch\nimport math, torch.nn as nn, pdb\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport spatial_reasoning.models as models\nimport spatial_reasoning.utils as utils\n\nclass UVFA_text(nn.Module):\n def __init__(self, lstm, state_vocab, object_vocab, args, map_dim = 10, batch_size = 32):\n super(UVFA_text, self).__init__()\n\n self.state_vocab = state_vocab\n self.object_vocab = object_vocab\n self.lstm = lstm\n self.rank = args.rank\n self.map_dim = map_dim\n self.batch_size = batch_size\n self.positions = self.__agent_pos()\n\n ## add one for agent position\n self.state_dim = (self.state_vocab+1) * (map_dim**2)\n # self.state_dim = self.state_vocab * map_dim**2\n self.state_layers = [self.state_dim, 128, 128, args.rank]\n self.state_mlp = models.MLP(self.state_layers)\n\n self.object_dim = self.object_vocab * (map_dim**2)\n self.object_layers = [self.object_dim, 128, 128, args.rank]\n self.object_mlp = models.MLP(self.object_layers)\n\n '''\n returns tensor with one-hot vector encoding\n [1, 2, 3, ..., map_dim] repeated batch_size times\n < batch_size * map_dim, state_vocab >\n '''\n def __agent_pos(self):\n size = self.map_dim**2\n positions = torch.zeros(self.batch_size*size, 100, 1)\n # print(positions.size())\n for ind in range(size):\n # print(ind, ind*self.batch_size, (ind+1)*self.batch_size, ind, positions.size())\n # positions[ind*self.batch_size:(ind+1)*self.batch_size, ind] = 1\n positions[ind:self.batch_size*size:size, ind] = 1\n # pdb.set_trace()\n return Variable( positions.cuda() )\n\n def __repeat_position(self, x):\n if x.size() == 2:\n return x.unsqueeze(1).repeat(1,self.map_dim**2,1)\n else:\n return x.unsqueeze(1).repeat(1,self.map_dim**2,1,1)\n\n '''\n < batch_size x N >\n < batch_size*100 x N >\n '''\n def __construct_inp(self, state, obj, text):\n state = self.__repeat_position(state)\n state = state.view(self.batch_size*self.map_dim**2,self.map_dim**2,self.state_vocab)\n ## add agent position\n state = torch.cat( (state, self.positions), -1)\n ## reshape to (batched) vector for input to MLPs\n state = state.view(-1, self.state_dim)\n\n obj = self.__repeat_position(obj)\n obj = obj.view(self.batch_size*self.map_dim**2,self.map_dim**2,self.object_vocab)\n obj = obj.view(-1, self.object_dim)\n\n instr_length = text.size(1)\n ## < batch x length >\n ## < batch x 100 x length >\n text = self.__repeat_position(text)\n ## < batch*100 x length >\n text = text.view(self.batch_size*self.map_dim**2,instr_length)\n ## < length x batch*100 >\n text = text.transpose(0,1)\n ## < batch*100 x rank >\n\n return state, obj, text\n\n\n def forward(self, inp):\n (state, obj, text) = inp\n batch_size = state.size(0)\n # text = text.transpose(0,1)\n hidden = self.lstm.init_hidden(batch_size * self.map_dim**2)\n\n if batch_size != self.batch_size:\n self.batch_size = batch_size\n self.positions = self.__agent_pos()\n\n ## reshape to (batched) vectors\n ## can't scatter Variables\n state = state.data.view(-1, self.map_dim**2, 1)\n obj = obj.data.view(-1, self.map_dim**2, 1)\n\n ## make state / object indices into one-hot vectors\n state_binary = torch.zeros(batch_size, self.map_dim**2, self.state_vocab).cuda()\n object_binary = torch.zeros(batch_size, self.map_dim**2, self.object_vocab).cuda()\n state_binary.scatter_(2, state, 1)\n object_binary.scatter_(2, obj, 1)\n\n state_binary = Variable( state_binary )\n object_binary = Variable( object_binary )\n\n state_binary, object_binary, text = self.__construct_inp(state_binary, object_binary, text)\n\n # print(state_binary.size(), object_binary.size(), text.size())\n # object_binary = self.__repeat_position(object_binary)\n # object_binary = object_binary.view(self.batch_size*self.map_dim**2,self.map_dim**2,self.object_vocab)\n\n ## add in agent position\n ## < batch x 100 x 2 >\n ## < batch x 100 x 100 x 2 >\n # state_binary = self.__repeat_position(state_binary)\n ## < batch*100 x 100 x 2 >\n # state_binary = state_binary.view(self.batch_size*self.map_dim**2,self.map_dim**2,self.state_vocab)\n\n ## add agent position\n # state_binary = torch.cat( (state_binary, self.positions), -1)\n\n # pdb.set_trace()\n # print(state_binary.size(), object_binary.size())\n\n ## reshape to (batched) vectors for input to MLPs\n ## turn back into Variables for backprop\n # state_binary = state_binary.view(-1, self.state_dim)\n # object_binary = object_binary.view(-1, self.object_dim)\n\n ## < batch*100 x rank >\n state_out = self.state_mlp(state_binary)\n object_out = self.object_mlp(object_binary)\n\n lstm_out = self.lstm.forward(text, hidden)\n\n\n # print(lstm_out.size())\n\n values = state_out * object_out * lstm_out\n map_pred = values.sum(1, keepdim=True).view(self.batch_size, self.map_dim, self.map_dim)\n\n\n return map_pred\n\n # def forward(self, inp):\n # (state, obj, text) = inp\n # batch_size = state.size(0)\n # text = text.transpose(0,1)\n # hidden = self.lstm.init_hidden(batch_size)\n\n # if batch_size != self.batch_size:\n # self.batch_size = batch_size\n # # self.positions = self.__agent_pos()\n\n # ## reshape to (batched) vectors\n # ## can't scatter Variables\n # state = state.data.view(-1, self.map_dim**2, 1)\n # obj = obj.data.view(-1, self.map_dim**2, 1)\n\n # ## make state / object indices into one-hot vectors\n # state_binary = torch.zeros(batch_size, self.map_dim**2, self.state_vocab).cuda()\n # object_binary = torch.zeros(batch_size, self.map_dim**2, self.object_vocab).cuda()\n # state_binary.scatter_(2, state, 1)\n # object_binary.scatter_(2, obj, 1)\n\n # state_binary = Variable( state_binary )\n # object_binary = Variable( object_binary )\n\n # ## add in agent position\n # ## < batch x 100 x 2 >\n # ## < batch x 100 x 100 x 2 >\n # # state_binary = state_binary.unsqueeze(1).repeat(1,self.map_dim**2,1,1)\n # # state_binary = self.__repeat_position(state_binary)\n # ## < batch*100 x 100 x 2 >\n # # state_binary = state_binary.view(self.batch_size*self.map_dim**2,self.map_dim**2,self.state_vocab)\n\n # ## add agent position\n # # state_binary = torch.cat( (state_binary, self.positions), -1)\n\n # # pdb.set_trace()\n # # print(state_binary.size(), object_binary.size())\n\n # ## reshape to (batched) vectors for input to MLPs\n # ## turn back into Variables for backprop\n # state_binary = state_binary.view(-1, self.state_dim)\n # object_binary = object_binary.view(-1, self.object_dim)\n # print('state: ', state_binary.size(), object_binary.size())\n # state_out = self.state_mlp(state_binary)\n # object_out = self.object_mlp(object_binary)\n\n # # print(state_out.size(), object_out.size())\n\n # lstm_out = self.lstm.forward(text, hidden)\n\n # # object_out = self.__repeat_position(object_out).view(-1, self.rank)\n # # lstm_out = self.__repeat_position(lstm_out).view(-1, self.rank)\n\n # # print(state_out.size(), object_out.size(), lstm_out.size())\n\n # values = state_out * object_out * lstm_out\n # # map_pred = values.sum(1).view(self.batch_size, self.map_dim**2)\n # values = values.sum(1)\n # # print(values.size())\n # map_pred = values.unsqueeze(-1).repeat(1,self.map_dim,self.map_dim)\n # print(values.size(), map_pred.size())\n\n # return map_pred\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" ]
[ [ "numpy.random.randn", "numpy.zeros" ], [ "torch.autograd.Variable", "torch.cat", "torch.zeros" ] ]
hthieu166/cs547-final-proj-image-ranking
[ "81c6d3ebccae77df1d2e8421927a1a2684f80c98" ]
[ "src/utils/img_ranking_evaluate.py" ]
[ "import torch \nfrom sklearn.metrics import average_precision_score\nimport ipdb\nimport numpy as np\n\ndef img_ranking_evaluate_tinyImageNet(img_embs, labels, export_result = False):\n #Pair-wise L2 distance between each pair\n c_dist = torch.cdist(img_embs, img_embs)\n #Sort the image id in ascending order by its distance \n img_rank = torch.argsort(c_dist, dim = 1)\n img_label_pred = (labels[img_rank]).squeeze() #shape: N_img x N_img\n labels = labels.unsqueeze(1) #shape: N_img x 1\n #Calculate top K-accuracy:\n correct_pred = img_label_pred == labels\n top_1 = correct_pred[:, 1]\n top_10 = correct_pred[:, 1:11]\n top_49 = correct_pred[:, 1:50]\n top_1 = top_1.to(torch.float).mean()\n top_10 = top_10.to(torch.float).mean()\n top_49 = top_49.to(torch.float).mean()\n ret_res= {\n \"acc_top1\": top_1.cpu().item(),\n \"acc_top10\": top_10.cpu().item(),\n \"acc_top49\": top_49.cpu().item()\n }\n if (export_result):\n ret_res[\"preds\"] = img_rank.cpu().numpy()\n return ret_res\n\ndef calculate_mAP(dist, match):\n aps = []\n scores = 1 / (1 + dist)\n for i in range(len(dist)):\n ap = average_precision_score(match[i], scores[i])\n aps.append(ap)\n return np.mean(aps) \n\n\ndef img_ranking_evaluate_Market1501(\n gal_embs, gal_lbls, que_embs = None, que_lbls = None, export_result = False, same_gal_que = False):\n \n no_que_set = False\n if que_embs == None:\n que_lbls = gal_lbls\n que_embs = gal_embs\n no_que_set = True\n \n #Pair-wise L2 distance between each pair\n c_dist = torch.cdist(que_embs, gal_embs)\n if (no_que_set):\n print(\"No query-set\")\n c_dist.fill_diagonal_(float('inf'))\n \n #Sort the image id in ascending order by its distance \n img_rank = torch.argsort(c_dist, dim = 1)\n img_label_pred = (gal_lbls[img_rank]).squeeze() #shape: N_img x N_img\n labels = que_lbls.unsqueeze(1) #shape: N_img x 1\n \n #Caluclate mAP\n meanAP = calculate_mAP(c_dist.cpu().detach().numpy(), \n (gal_lbls == labels).cpu().detach().numpy())\n\n #Calculate top K-accuracy:\n correct_pred = img_label_pred == labels\n top_1 = correct_pred[:, 0]\n top_5 = correct_pred[:, :5]\n top_10 = correct_pred[:, :10]\n top_49 = correct_pred[:, :49]\n top_1 = top_1.to(torch.float).mean()\n top_10 = top_10.to(torch.float).mean()\n top_49 = top_49.to(torch.float).mean()\n top_5 = top_5.to(torch.float).mean()\n ret_res= {\n \"acc_top1\": top_1.cpu().item(),\n \"acc_top5\": top_5.cpu().item(),\n \"acc_top10\": top_10.cpu().item(),\n \"acc_top49\": top_49.cpu().item(),\n \"mAP\": meanAP\n }\n if (export_result):\n ret_res[\"preds\"] = img_rank.cpu().numpy()\n return ret_res\n\nif __name__ == \"__main__\":\n torch.manual_seed(10)\n n_imgs = 50\n # img_embs = torch.randn(n_imgs, 128)\n # labels = torch.randint(0,10,(n_imgs,1), dtype=torch.int)\n # img_ranking_evaluate(img_embs, labels)\n \n gal_embs = torch.randn(n_imgs, 128)\n que_embs = torch.randn(n_imgs//2, 128)\n gal_lbls = torch.randint(0,10,(n_imgs,1), dtype=torch.int)\n que_lbls = torch.randint(0,10,(n_imgs//2,1), dtype=torch.int)\n print(img_ranking_evaluate_Market1501(gal_embs, gal_lbls, que_embs, que_lbls))" ]
[ [ "torch.randint", "torch.manual_seed", "torch.randn", "torch.cdist", "numpy.mean", "sklearn.metrics.average_precision_score", "torch.argsort" ] ]
zeyademam/active_learning
[ "fc90eaed32ba5aeb88542fa4f6e8fa9d4fdd80ee" ]
[ "src/query_strategies/vae.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.init as init\nimport numpy as np\n\nCROP_H = 64\nCROP_W = 64\n\nclass View(nn.Module):\n def __init__(self, size):\n super(View, self).__init__()\n self.size = size\n\n def forward(self, tensor):\n return tensor.view(self.size)\n\n\nclass VAE(nn.Module):\n \"\"\"Encoder-Decoder architecture for both WAE-MMD and WAE-GAN.\"\"\"\n\n def __init__(self, z_dim=32, nc=3, latent_scale=None):\n super(VAE, self).__init__()\n self.z_dim = z_dim\n self.nc = nc\n ls = int(latent_scale)\n self.encoder = nn.Sequential(nn.Conv2d(nc, 128, 4, 2, 1, bias=False), # B, 128, 32, 32\n nn.BatchNorm2d(128), nn.ReLU(True),\n nn.Conv2d(128, 256, 4, 2, 1, bias=False), # B, 256, 16, 16\n nn.BatchNorm2d(256), nn.ReLU(True),\n nn.Conv2d(256, 512, 4, 2, 1, bias=False), # B, 512, 8, 8\n nn.BatchNorm2d(512), nn.ReLU(True),\n nn.Conv2d(512, 1024, 4, 2, 1, bias=False), # B, 1024, 4, 4\n nn.BatchNorm2d(1024), nn.ReLU(True), View((-1, 1024 * 2 * 2 * ls * ls)),\n # B, 1024*4*4\n )\n\n self.fc_mu = nn.Linear(1024 * 2 * 2 * ls * ls , z_dim) # B, z_dim\n self.fc_logvar = nn.Linear(1024 * 2 * 2 * ls * ls, z_dim) # B, z_dim\n self.decoder = nn.Sequential(nn.Linear(z_dim, 1024 * 4 * 4 * ls * ls), # B, 1024*8*8\n View((-1, 1024, 4 * ls, 4 * ls)), # B, 1024, 8, 8\n nn.ConvTranspose2d(1024, 512, 4, 2, 1, bias=False),\n # B, 512, 16, 16\n nn.BatchNorm2d(512), nn.ReLU(True),\n nn.ConvTranspose2d(512, 256, 4, 2, 1, bias=False),\n # B, 256, 32, 32\n nn.BatchNorm2d(256), nn.ReLU(True),\n nn.ConvTranspose2d(256, 128, 4, 2, 1, bias=False),\n # B, 128, 64, 64\n nn.BatchNorm2d(128), nn.ReLU(True),\n nn.ConvTranspose2d(128, nc, 1), # B, nc, 64, 64\n )\n self.weight_init()\n\n def weight_init(self):\n for block in self._modules:\n try:\n for m in self._modules[block]:\n kaiming_init(m)\n except:\n kaiming_init(block)\n\n def set_crop_seed(self, seed):\n self.crop_seed = seed\n\n def _gen_random_crop_index(self, h, w):\n np.random.seed(self.crop_seed)\n if w < CROP_W and h < CROP_H:\n w_start, w_end = 0, CROP_W\n h_start, h_end = 0, CROP_H\n elif w >= CROP_W and h >= CROP_H:\n w_start = np.random.randint(w - CROP_W + 1)\n w_end = w_start + CROP_W\n h_start = np.random.randint(h - CROP_H + 1)\n h_end = h_start + CROP_H\n else:\n raise ValueError(\"Unimplemented architecture for current image size.\")\n\n return h_start, h_end, w_start, w_end, \n\n def forward(self, x):\n crop_indxs = self._gen_random_crop_index(x.size(2), x.size(3))\n x_random_crop = x[:, :, crop_indxs[0]:crop_indxs[1], crop_indxs[2]:crop_indxs[3]]\n z = self._encode(x_random_crop)\n mu, logvar = self.fc_mu(z), self.fc_logvar(z)\n z = self.reparameterize(mu, logvar)\n x_recon = self._decode(z)\n\n return x_random_crop, x_recon, z, mu, logvar\n\n def reparameterize(self, mu, logvar):\n stds = (0.5 * logvar).exp()\n epsilon = torch.randn(*mu.size())\n if mu.is_cuda:\n stds, epsilon = stds.cuda(), epsilon.cuda()\n latents = epsilon * stds + mu\n return latents\n\n def _encode(self, x):\n return self.encoder(x)\n\n def _decode(self, z):\n return self.decoder(z)\n\n\ndef kaiming_init(m):\n if isinstance(m, (nn.Linear, nn.Conv2d)):\n init.kaiming_normal(m.weight)\n if m.bias is not None:\n m.bias.data.fill_(0)\n elif isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d)):\n m.weight.data.fill_(1)\n if m.bias is not None:\n m.bias.data.fill_(0)\n\n\ndef normal_init(m, mean, std):\n if isinstance(m, (nn.Linear, nn.Conv2d)):\n m.weight.data.normal_(mean, std)\n if m.bias.data is not None:\n m.bias.data.zero_()\n elif isinstance(m, (nn.BatchNorm2d, nn.BatchNorm1d)):\n m.weight.data.fill_(1)\n if m.bias.data is not None:\n m.bias.data.zero_()\n" ]
[ [ "torch.nn.init.kaiming_normal", "numpy.random.seed", "torch.nn.ConvTranspose2d", "torch.nn.Conv2d", "torch.nn.Linear", "torch.nn.BatchNorm2d", "torch.nn.ReLU", "numpy.random.randint" ] ]
neergaard/eegbci-data
[ "d3270d500b5eba452ed6647ec42a9af404e17b0a" ]
[ "eegbci/data_containers/mixins/collatefunction_mixin.py" ]
[ "from typing import TypedDict\n\nimport torch\n\n\nclass CollateFnMixin:\n def collate_fn(self, batch) -> TypedDict:\n\n subject_id_map = [int(x[2][1:4]) - 1 for x in batch]\n\n waveforms = torch.stack([torch.as_tensor(x[0]) for x in batch])\n targets = torch.stack([torch.as_tensor(x[1]) for x in batch])\n global_information = torch.as_tensor(subject_id_map)\n\n return dict(waveform=waveforms, global_information=global_information, targets=targets)\n\n def collate_fn_report(self, batch):\n return self.collate_fn(batch)\n" ]
[ [ "torch.as_tensor" ] ]
YutongWangUMich/tf_multiclass
[ "69f3cd638da87fc0fcad87b732fcb30dde51ce07" ]
[ "utils.py" ]
[ "from tensorflow.keras.utils import to_categorical\nimport tensorflow.keras.backend as K\nimport tensorflow as tf\n\ndef add_constant_column(x,val):\n# return K.concatenate([x,K.constant(val,shape=(x.shape[0],1))],axis=-1)\n# return K.concatenate([x,K.constant(val,shape=(x.shape[0],1))],axis=-1)\n return tf.pad( x, [[0,0],[0,1]], constant_values = val ) # add a column of zeros to z\n\n\n\n\ndef to_t_categorical(y_raw,num_classes=None, dtype='float32'):\n \"\"\"\n convert raw labels \n e.g., [0,1,2,...]\n to trimmed categorical label encodings\n y_raw here refers to the labels that takes values in {0, 1,..., n_classes}\n \"\"\"\n return to_categorical(y_raw, num_classes, dtype)[:,:-1]\n\n\ndef from_t_categorical(y):\n \"\"\" convert trimmed categorical label encodings to raw labels\n \"\"\"\n return K.cast_to_floatx(K.argmax(add_constant_column(y, 0.5),axis=1))\n\n\n\n\ndef predict_classes_from_r_margin(z):\n \"\"\" predict classes from relative margin\n \"\"\"\n return K.cast_to_floatx(K.argmin(add_constant_column(z,0.0),axis=1))\n\n\n\n# def from_t_categorical(y):\n# \"\"\" convert trimmed categorical label encodings to raw labels\n# \"\"\"\n \n# n_classes_m1 = y.shape[1] # number of classes minus 1\n \n# A = K.cast(K.all(y==0,axis=1), K.floatx())\n# return (n_classes_m1)*A + K.cast(K.argmax(y,axis=1), K.floatx())*(1.-A)\n\n\n\n\n# def predict_classes_from_r_margin(z):\n# \"\"\" predict classes from relative margin\n# \"\"\"\n# n_classes_m1 = z.shape[1] # number of classes minus 1\n \n# A = K.cast(K.all(z>=0,axis=1),dtype = K.floatx())\n# return A*n_classes_m1 + (1.-A)*K.cast(K.argmin(z,axis=1),K.floatx())\n" ]
[ [ "tensorflow.keras.utils.to_categorical", "tensorflow.pad" ] ]
AgDude/Adeept_RaspTank
[ "1c22e4681233f859c638716054ac7a9dc394862b" ]
[ "server/FPVtest.py" ]
[ "#!/usr/bin/env/python3\n# File name : server.py\n# Description : for FPV video and OpenCV functions\n# Website\t : www.gewbot.com\n# Author\t : William(Based on Adrian Rosebrock's OpenCV code on pyimagesearch.com)\n# Date\t\t: 2019/08/28\n\nimport time\nimport threading\nimport cv2\nimport zmq\nimport base64\nimport picamera\nfrom picamera.array import PiRGBArray\nimport argparse\nimport imutils\nfrom collections import deque\nimport psutil\nimport os\nimport servo\nimport PID\nimport LED\nimport datetime\nfrom rpi_ws281x import *\nimport move\nimport switch\nimport numpy as np\nimport RPIservo\n\npid = PID.PID()\npid.SetKp(0.5)\npid.SetKd(0)\npid.SetKi(0)\nY_lock = 0\nX_lock = 0\ntor\t= 17\nFindColorMode = 0\nWatchDogMode = 0\nUltraData = 3\nLED = LED.LED()\n\n#2\nCVrun = 1\nFindLineMode = 0\nlinePos_1 = 440\nlinePos_2 = 380\nlineColorSet = 255\nframeRender = 0\nfindLineError = 20\n\ncolorUpper = np.array([44, 255, 255])#1\ncolorLower = np.array([24, 100, 100])#1\n\ncamera = picamera.PiCamera() \ncamera.resolution = (640, 480)\ncamera.framerate = 20\nrawCapture = PiRGBArray(camera, size=(640, 480))\n\nmodeText = 'Select your mode, ARM or PT?'\n\nscGear = RPIservo.ServoCtrl()\nscGear.moveInit()\n\nelements = []\n\ndef findLineCtrl(posInput, setCenter):#2\n\tif posInput:\n\t\tif posInput > (setCenter + findLineError):\n\t\t\tmove.motorStop()\n\t\t\t#turnRight\n\t\t\terror = (posInput-320)/5\n\t\t\toutv = int(round((pid.GenOut(error)),0))\n\t\t\tscGear.moveAngle(0,-outv)\n\t\t\tmove.move(80, 'forward', 'no', 0.5)\n\t\t\ttime.sleep(0.2)\n\t\t\tmove.motorStop()\n\t\t\tpass\n\t\telif posInput < (setCenter - findLineError):\n\t\t\tmove.motorStop()\n\t\t\t#turnLeft\n\t\t\terror = (320-posInput)/5\n\t\t\toutv = int(round((pid.GenOut(error)),0))\n\t\t\tscGear.moveAngle(0,outv)\n\t\t\tmove.move(80, 'forward', 'no', 0.5)\n\t\t\ttime.sleep(0.2)\n\t\t\tmove.motorStop()\n\t\t\tpass\n\t\telse:\n\t\t\tif CVrun:\n\t\t\t\tmove.move(80, 'forward', 'no', 0.5)\n\t\t\t#forward\n\t\t\tpass\n\telse:\n\t\t# if CVrun:\n\t\t# \ttry:\n\t\t# \t\tmove.motorStop()\n\t\t# \texcept Exception as e:\n\t\t# \t\tprint(e)\n\t\t#\tmove.move(80, 'backward', 'no', 0.5)\n\t\tpass\n\n\ndef cvFindLine():#2\n\tglobal frame_findline, camera#3\n\t# camera.exposure_mode = 'off'\n\tframe_findline = cv2.cvtColor(frame_image, cv2.COLOR_BGR2GRAY)\n\tretval, frame_findline = cv2.threshold(frame_findline, 0, 255, cv2.THRESH_OTSU)# 对图片进行二值化处理\n\tframe_findline = cv2.erode(frame_findline, None, iterations=6)# 侵蚀\n\tcolorPos_1 = frame_findline[linePos_1]\n\tcolorPos_2 = frame_findline[linePos_2]\n\ttry:\n\t\tlineColorCount_Pos1 = np.sum(colorPos_1 == lineColorSet)\n\t\tlineColorCount_Pos2 = np.sum(colorPos_2 == lineColorSet)\n\n\t\tlineIndex_Pos1 = np.where(colorPos_1 == lineColorSet)\n\t\tlineIndex_Pos2 = np.where(colorPos_2 == lineColorSet)\n\n\t\tif lineColorCount_Pos1 == 0:\n\t\t\tlineColorCount_Pos1 = 1\n\t\tif lineColorCount_Pos2 == 0:\n\t\t\tlineColorCount_Pos2 = 1\n\n\t\tleft_Pos1 = lineIndex_Pos1[0][lineColorCount_Pos1-1]\n\t\tright_Pos1 = lineIndex_Pos1[0][0]\n\t\tcenter_Pos1 = int((left_Pos1+right_Pos1)/2)\n\n\t\tleft_Pos2 = lineIndex_Pos2[0][lineColorCount_Pos2-1]\n\t\tright_Pos2 = lineIndex_Pos2[0][0]\n\t\tcenter_Pos2 = int((left_Pos2+right_Pos2)/2)\n\n\t\tcenter = int((center_Pos1+center_Pos2)/2)\n\texcept:\n\t\tcenter = None\n\t\tpass\n\n\tfindLineCtrl(center, 320)\n\t# print(center)\n\ttry:\n\t\tif lineColorSet == 255:\n\t\t\tcv2.putText(frame_image,('Following White Line'),(30,50), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(128,255,128),1,cv2.LINE_AA)\n\t\t\tcv2.putText(frame_findline,('Following White Line'),(30,50), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(128,255,128),1,cv2.LINE_AA)\n\t\telse:\n\t\t\tcv2.putText(frame_image,('Following Black Line'),(30,50), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(128,255,128),1,cv2.LINE_AA)\n\t\t\tcv2.putText(frame_findline,('Following Black Line'),(30,50), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(128,255,128),1,cv2.LINE_AA)\n\n\t\tif frameRender:\n\t\t\tcv2.line(frame_image,(left_Pos1,(linePos_1+30)),(left_Pos1,(linePos_1-30)),(255,128,64),1)\n\t\t\tcv2.line(frame_image,(right_Pos1,(linePos_1+30)),(right_Pos1,(linePos_1-30)),(64,128,255),)\n\t\t\tcv2.line(frame_image,(0,linePos_1),(640,linePos_1),(255,255,64),1)\n\n\t\t\tcv2.line(frame_image,(left_Pos2,(linePos_2+30)),(left_Pos2,(linePos_2-30)),(255,128,64),1)\n\t\t\tcv2.line(frame_image,(right_Pos2,(linePos_2+30)),(right_Pos2,(linePos_2-30)),(64,128,255),1)\n\t\t\tcv2.line(frame_image,(0,linePos_2),(640,linePos_2),(255,255,64),1)\n\n\t\t\tcv2.line(frame_image,((center-20),int((linePos_1+linePos_2)/2)),((center+20),int((linePos_1+linePos_2)/2)),(0,0,0),1)\n\t\t\tcv2.line(frame_image,((center),int((linePos_1+linePos_2)/2+20)),((center),int((linePos_1+linePos_2)/2-20)),(0,0,0),1)\n\t\telse:\n\t\t\tcv2.line(frame_findline,(left_Pos1,(linePos_1+30)),(left_Pos1,(linePos_1-30)),(255,128,64),1)\n\t\t\tcv2.line(frame_findline,(right_Pos1,(linePos_1+30)),(right_Pos1,(linePos_1-30)),(64,128,255),1)\n\t\t\tcv2.line(frame_findline,(0,linePos_1),(640,linePos_1),(255,255,64),1)\n\n\t\t\tcv2.line(frame_findline,(left_Pos2,(linePos_2+30)),(left_Pos2,(linePos_2-30)),(255,128,64),1)\n\t\t\tcv2.line(frame_findline,(right_Pos2,(linePos_2+30)),(right_Pos2,(linePos_2-30)),(64,128,255),1)\n\t\t\tcv2.line(frame_findline,(0,linePos_2),(640,linePos_2),(255,255,64),1)\n\n\t\t\tcv2.line(frame_findline,((center-20),int((linePos_1+linePos_2)/2)),((center+20),int((linePos_1+linePos_2)/2)),(0,0,0),1)\n\t\t\tcv2.line(frame_findline,((center),int((linePos_1+linePos_2)/2+20)),((center),int((linePos_1+linePos_2)/2-20)),(0,0,0),1)\n\texcept:\n\t\tpass\n\n\nclass FPV: \n\tdef __init__(self):\n\t\tself.frame_num = 0\n\t\tself.fps = 0\n\n\tdef SetIP(self,invar):\n\t\tself.IP = invar\n\n\tdef colorFindSet(self,invarH, invarS, invarV):#1\n\t\tglobal colorUpper, colorLower\n\t\tHUE_1 = invarH+11\n\t\tHUE_2 = invarH-11\n\t\tif HUE_1>255:HUE_1=255\n\t\tif HUE_2<0:HUE_2=0\n\n\t\tSAT_1 = invarS+170\n\t\tSAT_2 = invarS-20\n\t\tif SAT_1>255:SAT_1=255\n\t\tif SAT_2<0:SAT_2=0\n\n\t\tVAL_1 = invarV+170\n\t\tVAL_2 = invarV-20\n\t\tif VAL_1>255:VAL_1=255\n\t\tif VAL_2<0:VAL_2=0\n\n\t\tcolorUpper = np.array([HUE_1, SAT_1, VAL_1])\n\t\tcolorLower = np.array([HUE_2, SAT_2, VAL_2])\n\t\tprint('HSV_1:%d %d %d'%(HUE_1, SAT_1, VAL_1))\n\t\tprint('HSV_2:%d %d %d'%(HUE_2, SAT_2, VAL_2))\n\n\n\tdef FindColor(self,invar):\n\t\tglobal FindColorMode\n\t\tFindColorMode = invar\n\t\tif not FindColorMode:\n\t\t\tservo.ahead()\n\n\n\tdef WatchDog(self,invar):\n\t\tglobal WatchDogMode\n\t\tWatchDogMode = invar\n\n\n\tdef UltraData(self,invar):\n\t\tglobal UltraData\n\t\tUltraData = invar\n\n\n\tdef setExpCom(self,invar):#Z\n\t\tif invar > 25:\n\t\t\tinvar = 25\n\t\telif invar < -25:\n\t\t\tinvar = -25\n\t\telse:\n\t\t\tcamera.exposure_compensation = invar\n\n\n\tdef defaultExpCom(self):#Z\n\t\tcamera.exposure_compensation = 0\n\n\n\tdef changeMode(self, textPut):\n\t\tglobal modeText\n\t\tmodeText = textPut\n\n\n\tdef capture_thread(self,IPinver):\n\t\tglobal frame_image, camera#Z\n\n\t\tfont = cv2.FONT_HERSHEY_SIMPLEX\n\n\n\n\t\tcontext = zmq.Context()\n\t\tfootage_socket = context.socket(zmq.PUB)\n\t\tprint(IPinver)\n\t\tfootage_socket.connect('tcp://%s:5555'%IPinver)\n\n\t\tavg = None\n\t\tmotionCounter = 0\n\t\t#time.sleep(4)\n\t\tlastMovtionCaptured = datetime.datetime.now()\n\n\t\tfor frame in camera.capture_continuous(rawCapture, format=\"bgr\", use_video_port=True):\n\t\t\tframe_image = frame.array\n\t\t\tcv2.line(frame_image,(300,240),(340,240),(128,255,128),1)\n\t\t\tcv2.line(frame_image,(320,220),(320,260),(128,255,128),1)\n\t\t\ttimestamp = datetime.datetime.now()\n\n\t\t\tif FindLineMode:#2\n\t\t\t\tcvFindLine()\n\t\t\tif FindColorMode:\n\t\t\t\t####>>>OpenCV Start<<<####\n\t\t\t\thsv = cv2.cvtColor(frame_image, cv2.COLOR_BGR2HSV)\n\t\t\t\tmask = cv2.inRange(hsv, colorLower, colorUpper)#1\n\t\t\t\tmask = cv2.erode(mask, None, iterations=2)\n\t\t\t\tmask = cv2.dilate(mask, None, iterations=2)\n\t\t\t\tcnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,\n\t\t\t\t\tcv2.CHAIN_APPROX_SIMPLE)[-2]\n\t\t\t\tcenter = None\n\t\t\t\tif len(cnts) > 0:\n\t\t\t\t\tcv2.putText(frame_image,'Target Detected',(40,60), font, 0.5,(255,255,255),1,cv2.LINE_AA)\n\n\t\t\t\t\tc = max(cnts, key=cv2.contourArea)\n\t\t\t\t\t((x, y), radius) = cv2.minEnclosingCircle(c)\n\t\t\t\t\tM = cv2.moments(c)\n\t\t\t\t\tcenter = (int(M[\"m10\"] / M[\"m00\"]), int(M[\"m01\"] / M[\"m00\"]))\n\t\t\t\t\tX = int(x)\n\t\t\t\t\tY = int(y)\n\t\t\t\t\tif radius > 10:\n\t\t\t\t\t\tcv2.rectangle(frame_image,(int(x-radius),int(y+radius)),(int(x+radius),int(y-radius)),(255,255,255),1)\n\n\t\t\t\t\tif Y < (240-tor):\n\t\t\t\t\t\terror = (240-Y)/5\n\t\t\t\t\t\toutv = int(round((pid.GenOut(error)),0))\n\t\t\t\t\t\tservo.up(outv)\n\t\t\t\t\t\tY_lock = 0\n\t\t\t\t\telif Y > (240+tor):\n\t\t\t\t\t\terror = (Y-240)/5\n\t\t\t\t\t\toutv = int(round((pid.GenOut(error)),0))\n\t\t\t\t\t\tservo.down(outv)\n\t\t\t\t\t\tY_lock = 0\n\t\t\t\t\telse:\n\t\t\t\t\t\tY_lock = 1\n\n\t\t\t\t\t\n\t\t\t\t\tif X < (320-tor*3):\n\t\t\t\t\t\terror = (320-X)/5\n\t\t\t\t\t\toutv = int(round((pid.GenOut(error)),0))\n\t\t\t\t\t\tservo.lookleft(outv)\n\t\t\t\t\t\t#move.move(70, 'no', 'left', 0.6)\n\t\t\t\t\t\tX_lock = 0\n\t\t\t\t\telif X > (330+tor*3):\n\t\t\t\t\t\terror = (X-240)/5\n\t\t\t\t\t\toutv = int(round((pid.GenOut(error)),0))\n\t\t\t\t\t\tservo.lookright(outv)\n\t\t\t\t\t\t#move.move(70, 'no', 'right', 0.6)\n\t\t\t\t\t\tX_lock = 0\n\t\t\t\t\telse:\n\t\t\t\t\t\t#move.motorStop()\n\t\t\t\t\t\tX_lock = 1\n\n\t\t\t\t\tif X_lock == 1 and Y_lock == 1:\n\t\t\t\t\t\tswitch.switch(1,1)\n\t\t\t\t\t\tswitch.switch(2,1)\n\t\t\t\t\t\tswitch.switch(3,1)\n\t\t\t\t\telse:\n\t\t\t\t\t\tswitch.switch(1,0)\n\t\t\t\t\t\tswitch.switch(2,0)\n\t\t\t\t\t\tswitch.switch(3,0)\n\n\t\t\t\t\t\t# if UltraData > 0.5:\n\t\t\t\t\t\t#\t move.move(70, 'forward', 'no', 0.6)\n\t\t\t\t\t\t# elif UltraData < 0.4:\n\t\t\t\t\t\t#\t move.move(70, 'backward', 'no', 0.6)\n\t\t\t\t\t\t#\t print(UltraData)\n\t\t\t\t\t\t# else:\n\t\t\t\t\t\t#\t move.motorStop()\n\t\t\t\t\t\n\n\t\t\t\telse:\n\t\t\t\t\tcv2.putText(frame_image,'Target Detecting',(40,60), font, 0.5,(255,255,255),1,cv2.LINE_AA)\n\t\t\t\t\tmove.motorStop()\n\t\t\t\t\n\n\t\t\tif WatchDogMode:\n\t\t\t\tgray = cv2.cvtColor(frame_image, cv2.COLOR_BGR2GRAY)\n\t\t\t\tgray = cv2.GaussianBlur(gray, (21, 21), 0)\n\n\t\t\t\tif avg is None:\n\t\t\t\t\tprint(\"[INFO] starting background model...\")\n\t\t\t\t\tavg = gray.copy().astype(\"float\")\n\t\t\t\t\trawCapture.truncate(0)\n\t\t\t\t\tcontinue\n\n\t\t\t\tcv2.accumulateWeighted(gray, avg, 0.5)\n\t\t\t\tframeDelta = cv2.absdiff(gray, cv2.convertScaleAbs(avg))\n\n\t\t\t\t# threshold the delta image, dilate the thresholded image to fill\n\t\t\t\t# in holes, then find contours on thresholded image\n\t\t\t\tthresh = cv2.threshold(frameDelta, 5, 255,\n\t\t\t\t\tcv2.THRESH_BINARY)[1]\n\t\t\t\tthresh = cv2.dilate(thresh, None, iterations=2)\n\t\t\t\tcnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,\n\t\t\t\t\tcv2.CHAIN_APPROX_SIMPLE)\n\t\t\t\tcnts = imutils.grab_contours(cnts)\n\n\t\t\t\tfor c in cnts:\n\t\t\t\t\t# if the contour is too small, ignore it\n\t\t\t\t\tif cv2.contourArea(c) < 5000:\n\t\t\t\t\t\tcontinue\n\t\t\t \n\t\t\t\t\t# compute the bounding box for the contour, draw it on the frame,\n\t\t\t\t\t# and update the text\n\t\t\t\t\t(x, y, w, h) = cv2.boundingRect(c)\n\t\t\t\t\tcv2.rectangle(frame_image, (x, y), (x + w, y + h), (128, 255, 0), 1)\n\t\t\t\t\ttext = \"Occupied\"\n\t\t\t\t\tmotionCounter += 1\n\n\t\t\t\t\tLED.colorWipe(Color(255,16,0))\n\t\t\t\t\tlastMovtionCaptured = timestamp\n\t\t\t\t\tswitch.switch(1,1)\n\t\t\t\t\tswitch.switch(2,1)\n\t\t\t\t\tswitch.switch(3,1)\n\n\t\t\t\tif (timestamp - lastMovtionCaptured).seconds >= 0.5:\n\t\t\t\t\tLED.colorWipe(Color(255,255,0))\n\t\t\t\t\tswitch.switch(1,0)\n\t\t\t\t\tswitch.switch(2,0)\n\t\t\t\t\tswitch.switch(3,0)\n\n\t\t\tif FindLineMode and not frameRender:#2\n\t\t\t\tencoded, buffer = cv2.imencode('.jpg', frame_findline)\n\t\t\telse:\n\t\t\t\tcv2.putText(frame_image, modeText,(40,100), font, 0.5,(255,255,255),1,cv2.LINE_AA)\n\t\t\t\tencoded, buffer = cv2.imencode('.jpg', frame_image)\n\t\t\tjpg_as_text = base64.b64encode(buffer)\n\t\t\tfootage_socket.send(jpg_as_text)\n\t\t\tprint(jpg_as_text)\n\n\t\t\trawCapture.truncate(0)\n\n\nif __name__ == '__main__':\n\tfpv=FPV()\n\twhile 1:\n\t\tfpv.capture_thread('192.168.0.110')\n\t\tpass\n\n" ]
[ [ "numpy.array", "numpy.where", "numpy.sum" ] ]
Jsunseri/integrate
[ "900354a1107a0e0170bf64d1560963e3bc8df1a1" ]
[ "integrate/stochastic/monte_carlo.py" ]
[ "\"\"\"\nThis module implements 1d and 2d Monte Carlo integration\n\"\"\"\n\nimport numpy as np\n\n\ndef monte_1d(x, f, trials):\n a = x[0]\n b = x[1]\n d = (b - a) * np.random.rand(1, trials) + a\n y = f(d)\n return (b - a) * np.sum(y) / float(trials)\n\n\ndef monte_2d(f, v, domain, trials):\n area = np.prod(domain[1] - domain[0])\n matrix = np.sqrt(area) * np.random.rand(trials, 2) + np.min(domain)\n v_eval = v(matrix)\n idx = np.where(v_eval < 1.0)\n points_inside = v_eval[idx]\n k = points_inside.size\n return area * k / float(trials)\n" ]
[ [ "numpy.sqrt", "numpy.min", "numpy.random.rand", "numpy.prod", "numpy.where", "numpy.sum" ] ]
tpvt99/rl-course
[ "993db19c2c25ed1c51a4f4fbfff2fa170da27562" ]
[ "hw2/pg2.py" ]
[ "import tensorflow as tf\nimport numpy as np\nimport gym\nimport logz\nimport os\nimport time\nimport inspect\nfrom multiprocessing import Process\n\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.layers import Dense\n\nclass MLP(Model):\n def __init__(self, output_size, scope, n_layers, size, activation = tf.nn.tanh, output_activation = None):\n \"\"\"\n Builds a feedforward neural network\n\n arguments:\n output_size: size of the output layer\n scope: variable scope of the network\n n_layers: number of hidden layers\n size: dimension of the hidden layer\n activation: activation of the hidden layers\n output_activation: activation of the ouput layers\n\n returns:\n output placeholder of the network (the result of a forward pass)\n\n Hint: use tf.layers.dense\n \"\"\"\n super(MLP, self).__init__()\n\n self.layers_lists = []\n for _ in range(n_layers):\n dense = Dense(size, activation = activation)\n self.layers_lists.append(dense)\n if output_activation == None:\n dense = Dense(output_size)\n else:\n dense = Dense(output_size, activation = output_activation)\n self.layers_lists.append(dense)\n\n def call(self, inputs, training = True):\n x = inputs\n for layer in self.layers_lists:\n x = layer(x)\n return x\n\ndef pathlength(path):\n return len(path[\"reward\"])\n\nclass Agent():\n def __init__(self, computation_graph_args, sample_trajectory_args, estimate_return_args):\n super(Agent, self).__init__()\n self.ob_dim = computation_graph_args['ob_dim']\n self.ac_dim = computation_graph_args['ac_dim']\n self.discrete = computation_graph_args['discrete']\n self.size = computation_graph_args['size']\n self.n_layers = computation_graph_args['n_layers']\n self.learning_rate = computation_graph_args['learning_rate']\n\n self.animate = sample_trajectory_args['animate']\n self.max_path_length = sample_trajectory_args['max_path_length']\n self.min_timesteps_per_batch = sample_trajectory_args['min_timesteps_per_batch']\n\n self.gamma = estimate_return_args['gamma']\n self.reward_to_go = estimate_return_args['reward_to_go']\n self.nn_baseline = estimate_return_args['nn_baseline']\n self.normalize_advantages = estimate_return_args['normalize_advantages']\n\n self.update_op = tf.keras.optimizers.Adam(lr=self.learning_rate)\n self.model = MLP(output_size = self.ac_dim, scope=None, n_layers = self.n_layers, size = self.size,\n activation = tf.nn.tanh, output_activation = None)\n\n def policy_forward_pass(self, sy_ob_no):\n \"\"\"\"\n arguments:\n sy_ob_no: (batch_size, self.ob_dim)\n returns:\n sy_logits_na: (batch_size, self.ac_dim)\n \"\"\"\n outputs = self.model(sy_ob_no) # raw probabilities\n if self.discrete:\n sy_logits_na = outputs # raw value, no log\n return sy_logits_na\n\n def sample_action(self, policy_parameters):\n \"\"\"\n arguments:\n sy_logits_na: (batch_size, self.ac_dim)\n returns:\n sy_sampled_ac:\n if discrete: (batch_size,)\n \"\"\"\n if self.discrete:\n sy_sampled_ac = tf.random.categorical(policy_parameters, policy_parameters.shape[0])\n sy_sampled_ac = tf.reshape(sy_sampled_ac, [-1]).numpy()\n return sy_sampled_ac\n\n def get_log_prob(self, policy_parameters, sy_ac_na):\n \"\"\" Constructs a symbolic operation for computing the log probability of a set of actions\n that were actually taken according to the policy\n\n arguments:\n sy_logits_na: (batch_size, self.ac_dim)\n sy_ac_na:\n if discrete: (batch_size,)\n returns:\n sy_logprob_n: (batch_size)\n\n \"\"\"\n if self.discrete:\n sy_ac_na = tf.dtypes.cast(sy_ac_na, tf.int32)\n sy_logprob_n = tf.nn.sparse_softmax_cross_entropy_with_logits(labels = sy_ac_na, logits = policy_parameters)\n return sy_logprob_n\n\n def sample_trajectories(self, itr, env):\n # Collect paths until we have enough timesteps\n timesteps_this_batch = 0\n paths = []\n while True:\n animate_this_episode=(len(paths)==0 and (itr % 10 == 0) and self.animate)\n path = self.sample_trajectory(env, animate_this_episode)\n paths.append(path)\n timesteps_this_batch += pathlength(path)\n if timesteps_this_batch > self.min_timesteps_per_batch:\n break\n return paths, timesteps_this_batch\n\n def sample_trajectory(self, env, animate_this_episode):\n ob = env.reset()\n obs, acs, rewards = [], [], []\n steps = 0\n while True:\n if animate_this_episode:\n env.render()\n time.sleep(0.01)\n obs.append(ob)\n #====================================================================================#\n # ----------PROBLEM 3----------\n #====================================================================================#\n self.policy_parameters = self.policy_forward_pass(ob[None])\n ac = self.sample_action(self.policy_parameters)\n ac = ac[0]\n acs.append(ac)\n ob, rew, done, _ = env.step(ac)\n rewards.append(rew)\n steps += 1\n if done or steps > self.max_path_length:\n break\n path = {\"observation\" : np.array(obs, dtype=np.float32),\n \"reward\" : np.array(rewards, dtype=np.float32),\n \"action\" : np.array(acs, dtype=np.float32)}\n return path\n\n def sum_of_rewards(self, re_n):\n \"\"\"\n Monte Carlo estimation of the Q function.\n\n let sum_of_path_lengths be the sum of the lengths of the paths sampled from\n Agent.sample_trajectories\n let num_paths be the number of paths sampled from Agent.sample_trajectories\n\n arguments:\n re_n: length: num_paths. Each element in re_n is a numpy array\n containing the rewards for the particular path\n\n returns:\n q_n: shape: (sum_of_path_lengths). A single vector for the estimated q values\n whose length is the sum of the lengths of the paths\n\n ----------------------------------------------------------------------------------\n\n Your code should construct numpy arrays for Q-values which will be used to compute\n advantages (which will in turn be fed to the placeholder you defined in\n Agent.define_placeholders).\n\n Recall that the expression for the policy gradient PG is\n\n PG = E_{tau} [sum_{t=0}^T grad log pi(a_t|s_t) * (Q_t - b_t )]\n\n where\n\n tau=(s_0, a_0, ...) is a trajectory,\n Q_t is the Q-value at time t, Q^{pi}(s_t, a_t),\n and b_t is a baseline which may depend on s_t.\n\n You will write code for two cases, controlled by the flag 'reward_to_go':\n\n Case 1: trajectory-based PG\n\n (reward_to_go = False)\n\n Instead of Q^{pi}(s_t, a_t), we use the total discounted reward summed over\n entire trajectory (regardless of which time step the Q-value should be for).\n\n For this case, the policy gradient estimator is\n\n E_{tau} [sum_{t=0}^T grad log pi(a_t|s_t) * Ret(tau)]\n\n where\n\n Ret(tau) = sum_{t'=0}^T gamma^t' r_{t'}.\n\n Thus, you should compute\n\n Q_t = Ret(tau)\n\n Store the Q-values for all timesteps and all trajectories in a variable 'q_n',\n like the 'ob_no' and 'ac_na' above.\n \"\"\"\n # YOUR_CODE_HERE\n\n if self.reward_to_go:\n q_n = []\n for path in re_n:\n temp = 0\n for index, rewards in enumerate(path):\n temp = temp + (self.gamma)**index * rewards\n for index, rewards in enumerate(path):\n if index == 0:\n q_n.append(temp)\n else:\n temp = temp - (self.gamma)**index * rewards\n q_n.append(temp)\n else:\n q_n = []\n for path in re_n:\n temp = 0\n for index, rewards in enumerate(path):\n temp = temp + ((self.gamma)**index) * rewards\n q_n.extend([temp]*len(path))\n\n return np.array(q_n)\n\n def compute_advantage(self, ob_no, q_n):\n \"\"\"\n Computes advantages by (possibly) subtracting a baseline from the estimated Q values\n\n let sum_of_path_lengths be the sum of the lengths of the paths sampled from\n Agent.sample_trajectories\n let num_paths be the number of paths sampled from Agent.sample_trajectories\n\n arguments:\n ob_no: shape: (sum_of_path_lengths, ob_dim)\n q_n: shape: (sum_of_path_lengths). A single vector for the estimated q values\n whose length is the sum of the lengths of the paths\n\n returns:\n adv_n: shape: (sum_of_path_lengths). A single vector for the estimated\n advantages whose length is the sum of the lengths of the paths\n \"\"\"\n #====================================================================================#\n # ----------PROBLEM 6----------\n # Computing Baselines\n #====================================================================================#\n if self.nn_baseline:\n # If nn_baseline is True, use your neural network to predict reward-to-go\n # at each timestep for each trajectory, and save the result in a variable 'b_n'\n # like 'ob_no', 'ac_na', and 'q_n'.\n #\n # Hint #bl1: rescale the output from the nn_baseline to match the statistics\n # (mean and std) of the current batch of Q-values. (Goes with Hint\n # #bl2 in Agent.update_parameters.\n raise NotImplementedError\n b_n = None # YOUR CODE HERE\n adv_n = q_n - b_n\n else:\n adv_n = q_n.copy()\n return adv_n\n\n def estimate_return(self, ob_no, re_n):\n \"\"\"\n Estimates the returns over a set of trajectories.\n\n let sum_of_path_lengths be the sum of the lengths of the paths sampled from\n Agent.sample_trajectories\n let num_paths be the number of paths sampled from Agent.sample_trajectories\n\n arguments:\n ob_no: shape: (sum_of_path_lengths, ob_dim)\n re_n: length: num_paths. Each element in re_n is a numpy array\n containing the rewards for the particular path\n\n returns:\n q_n: shape: (sum_of_path_lengths). A single vector for the estimated q values\n whose length is the sum of the lengths of the paths\n adv_n: shape: (sum_of_path_lengths). A single vector for the estimated\n advantages whose length is the sum of the lengths of the paths\n \"\"\"\n q_n = self.sum_of_rewards(re_n)\n adv_n = self.compute_advantage(ob_no, q_n)\n #====================================================================================#\n # ----------PROBLEM 3----------\n # Advantage Normalization\n #====================================================================================#\n if self.normalize_advantages:\n adv_n = (adv_n - np.mean(adv_n)) / (np.std(adv_n) + 1e-8)\n #re2_n = [((re - np.mean(re)) / (np.std(re) + 1e-10)) for re in re_n]\n return q_n, adv_n\n\n def update_parameters(self, ob_no, ac_na, q_n, adv_n, re_n):\n \"\"\"\n arguments:\n ob_no: shape: (sum_of_path_lengths, ob_dim)\n ac_na: shape: (sum_of_path_lengths).\n q_n: shape: (sum_of_path_lengths). A single vector for the estimated q values\n whose length is the sum of the lengths of the paths\n adv_n: shape: (sum_of_path_lengths). A single vector for the estimated\n advantages whose length is the sum of the lengths of the paths\n \"\"\"\n with tf.GradientTape() as tape:\n policy_parameters = self.model(ob_no)\n loss1 = self.get_log_prob(policy_parameters, ac_na)\n loss1 = tf.reshape(loss1, (-1,1))\n adv_n = tf.reshape(adv_n , (-1,1))\n loss2 = tf.reduce_mean(tf.multiply(loss1, adv_n))\n gradients = tape.gradient(loss2, self.model.trainable_variables)\n self.update_op.apply_gradients(zip(gradients, self.model.trainable_variables))\n print(loss2.numpy())\n\ndef train_PG(\n exp_name,\n env_name,\n n_iter,\n gamma,\n min_timesteps_per_batch,\n max_path_length,\n learning_rate,\n reward_to_go,\n animate,\n logdir,\n normalize_advantages,\n nn_baseline,\n seed,\n n_layers,\n size):\n\n\n # Make the gym environment\n env = gym.make(env_name)\n\n # Maximum length for episodes\n max_path_length = max_path_length or env.spec.max_episode_steps\n\n # Is this env continuous, or self.discrete?\n discrete = isinstance(env.action_space, gym.spaces.Discrete)\n\n # Observation and action sizes\n ob_dim = env.observation_space.shape[0]\n ac_dim = env.action_space.n if discrete else env.action_space.shape[0]\n\n computation_graph_args = {\n 'n_layers': n_layers,\n 'ob_dim': ob_dim,\n 'ac_dim': ac_dim,\n 'discrete': discrete,\n 'size': size,\n 'learning_rate': learning_rate,\n }\n\n sample_trajectory_args = {\n 'animate': animate,\n 'max_path_length': max_path_length,\n 'min_timesteps_per_batch': min_timesteps_per_batch,\n }\n\n estimate_return_args = {\n 'gamma': gamma,\n 'reward_to_go': reward_to_go,\n 'nn_baseline': nn_baseline,\n 'normalize_advantages': normalize_advantages,\n }\n\n agent = Agent(computation_graph_args, sample_trajectory_args, estimate_return_args)\n\n\n total_timesteps = 0\n for itr in range(n_iter):\n print(\"********** Iteration %i ************\"%itr)\n paths, timesteps_this_batch = agent.sample_trajectories(itr, env)\n total_timesteps += timesteps_this_batch\n\n # Build arrays for observation, action for the policy gradient update by concatenating\n # across paths\n ob_no = np.concatenate([path[\"observation\"] for path in paths])\n ac_na = np.concatenate([path[\"action\"] for path in paths])\n re_n = [path[\"reward\"] for path in paths]\n\n q_n, adv_n = agent.estimate_return(ob_no, re_n)\n agent.update_parameters(ob_no, ac_na, q_n, adv_n, re_n)\n\ndef main():\n train_PG(\n exp_name=\"vpg\",\n env_name=\"CartPole-v0\",\n n_iter=100,\n gamma=1.0,\n min_timesteps_per_batch=1000,\n max_path_length=None,\n learning_rate=5e-3,\n reward_to_go=False,\n animate=True,\n logdir=\"\",\n normalize_advantages=True,\n nn_baseline=False,\n seed=1,\n n_layers=2,\n size=64)\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "tensorflow.multiply", "tensorflow.random.categorical", "tensorflow.keras.layers.Dense", "tensorflow.reshape", "numpy.concatenate", "numpy.std", "tensorflow.keras.optimizers.Adam", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "numpy.mean", "numpy.array", "tensorflow.dtypes.cast", "tensorflow.GradientTape" ] ]
Spring-CC/restaurant-native-app
[ "e3ec732a5d9afce1b15d77e799ccbd7e0de90244" ]
[ "recommender/machine.py" ]
[ "import numpy as np\nimport pandas as pd\nfrom pathlib import Path\nfrom ast import literal_eval\nfrom scipy.sparse import csr_matrix\nfrom sklearn.neighbors import NearestNeighbors\nimport scipy\n\n\n# sparse matrix\nswipeddata_df = pd.read_csv(\n 'data/testuser.csv', usecols=[0, 1, 2], index_col=1)\nswipeddata_df.swiped_right = swipeddata_df.swiped_right.apply(literal_eval)\nnew_df = swipeddata_df.explode(\"swiped_right\")\n\n# create sparse matrix\nuser_pivot = new_df.pivot(\n index=\"_id\", columns='swiped_right', values='swiped_right').notna()\nmatrix = scipy.sparse.csr_matrix(user_pivot.values)\n\n\n# KNN algorithm\nknn_recomm = NearestNeighbors(\n n_neighbors=9, algorithm=\"brute\", metric=\"cosine\")\nknn_recomm.fit(matrix)\n\nknn_recomm_df = pd.DataFrame(\n knn_recomm, index=new_df.columns, columns=new_df.columns)\n\n\n# find a recommended user who have\nrandom_user = np.random.choice(user_pivot.shape[0])\ndistances, indices = knn_recomm.kneighbors(\n user_pivot.iloc[random_user].values.reshape(1, -1), n_neighbors=9)\n\n\nfor i in range(0, len(distances.flatten())):\n if i == 0:\n print('Recommendations for user:', random_user)\n else:\n print('{0}: {1}'.format(i, user_pivot.index[indices.flatten()[i]]))\n" ]
[ [ "pandas.read_csv", "numpy.random.choice", "scipy.sparse.csr_matrix", "pandas.DataFrame", "sklearn.neighbors.NearestNeighbors" ] ]
erihsu/vgg16_quantization
[ "677c3c2cabcef68e89149bd74d17f44c0f496749" ]
[ "freeze.py" ]
[ "import os\nimport argparse\nimport tensorflow as tf\n\n\ndef freeze_graph(model_ckpt, output_nodes, rename_nodes=None):\n meta_file = model_ckpt + '.meta'\n if not tf.gfile.Exists(meta_file):\n raise FileNotFoundError('file not found: %s' % meta_file)\n model_dir = \"/\".join(os.path.abspath(model_ckpt).split('/')[:-1])\n output_model = os.path.join(model_dir, \"frozen_model.pb\")\n saver = tf.train.import_meta_graph(meta_file, clear_devices=True)\n\n onames = output_nodes.split(',')\n graph = tf.get_default_graph()\n if rename_nodes is not None:\n rnames = rename_nodes.split(',')\n with graph.as_default():\n for o, n in zip(onames, rnames):\n _out = tf.identity(graph.get_tensor_by_name(o+':0'), name=n)\n onames = rnames\n\n with tf.Session(graph=graph) as sess:\n\n saver.restore(sess, model_ckpt)\n\n output_graph_def = tf.graph_util.convert_variables_to_constants(\n sess,\n graph.as_graph_def(),\n onames # unrelated nodes will be discarded\n )\n\n with tf.gfile.GFile(output_model, \"wb\") as f:\n f.write(output_graph_def.SerializeToString())\n print(\"%d ops in the final graph.\" % len(output_graph_def.node))\n\n return output_graph_def\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--model_ckpt\", type=str, default=None, help=\"ckpt file to export.\")\n parser.add_argument(\"--output_nodes\", type=str, default=None, help=\"comma separated.\")\n parser.add_argument(\"--rename_nodes\", type=str, default=None, help=\"same order as output_nodes\")\n args = parser.parse_args()\n\n freeze_graph(args.model_ckpt, args.output_nodes, args.rename_nodes)" ]
[ [ "tensorflow.gfile.Exists", "tensorflow.gfile.GFile", "tensorflow.train.import_meta_graph", "tensorflow.Session", "tensorflow.get_default_graph" ] ]
crim-ca/thelper
[ "1415144cf70e4492c2ef00f834e2b9a988064a76" ]
[ "thelper/data/geo/ogc.py" ]
[ "\"\"\"Data parsers & utilities module for OGC-related projects.\"\"\"\n\nimport copy\nimport functools\nimport logging\n\nimport cv2 as cv\nimport numpy as np\nimport tqdm\n\nimport thelper.data\nimport thelper.data.geo as geo\nimport thelper.train.utils\n\nlogger = logging.getLogger(__name__)\n\n\nclass TB15D104:\n \"\"\"Wrapper class for OGC Testbed-15 (D104) identifiers.\"\"\"\n\n TYPECE_RIVER = \"10\"\n TYPECE_LAKE = \"21\"\n\n BACKGROUND_ID = 0\n LAKE_ID = 1\n\n\nclass TB15D104Dataset(geo.parsers.VectorCropDataset):\n \"\"\"OGC Testbed-15 dataset parser for D104 (lake/river) segmentation task.\"\"\"\n\n def __init__(self, raster_path, vector_path, px_size=None,\n allow_outlying_vectors=True, clip_outlying_vectors=True,\n lake_area_min=0.0, lake_area_max=float(\"inf\"),\n lake_river_max_dist=float(\"inf\"), feature_buffer=1000,\n master_roi=None, focus_lakes=True, srs_target=\"3857\", force_parse=False,\n reproj_rasters=False, reproj_all_cpus=True, display_debug=False,\n keep_rasters_open=True, parallel=False, transforms=None):\n assert isinstance(lake_river_max_dist, (float, int)) and lake_river_max_dist >= 0, \"unexpected dist type\"\n self.lake_river_max_dist = float(lake_river_max_dist)\n assert isinstance(focus_lakes, bool), \"unexpected flag type\"\n self.focus_lakes = focus_lakes\n assert px_size is None or isinstance(px_size, (float, int)), \"pixel size (resolution) must be float/int\"\n px_size = (1.0, 1.0) if px_size is None else (float(px_size), float(px_size))\n # note: we wrap partial static functions for caching to see when internal parameters are changing\n cleaner = functools.partial(self.lake_cleaner, area_min=lake_area_min, area_max=lake_area_max,\n lake_river_max_dist=lake_river_max_dist, parallel=parallel)\n if self.focus_lakes:\n cropper = functools.partial(self.lake_cropper, px_size=px_size, skew=(0.0, 0.0),\n feature_buffer=feature_buffer, parallel=parallel)\n else:\n # TODO: implement river-focused cropper (i.e. river-length parsing?)\n raise NotImplementedError\n super().__init__(raster_path=raster_path, vector_path=vector_path, px_size=px_size, skew=None,\n allow_outlying_vectors=allow_outlying_vectors, clip_outlying_vectors=clip_outlying_vectors,\n vector_area_min=lake_area_min, vector_area_max=lake_area_max, vector_target_prop=None,\n feature_buffer=feature_buffer, master_roi=master_roi, srs_target=srs_target,\n raster_key=\"lidar\", mask_key=\"hydro\", cleaner=cleaner, cropper=cropper,\n force_parse=force_parse, reproj_rasters=reproj_rasters, reproj_all_cpus=reproj_all_cpus,\n keep_rasters_open=keep_rasters_open, transforms=transforms)\n meta_keys = self.task.meta_keys\n if \"bboxes\" in meta_keys:\n del meta_keys[meta_keys.index(\"bboxes\")] # placed in meta list by base class constr, moved to detect target below\n self.task = thelper.tasks.Detection(class_names={\"background\": TB15D104.BACKGROUND_ID, \"lake\": TB15D104.LAKE_ID},\n input_key=\"input\", bboxes_key=\"bboxes\",\n meta_keys=meta_keys, background=0, color_map={\"lake\": [255, 0, 0]})\n # update all already-created bboxes with new task ref\n for s in self.samples:\n for b in s[\"bboxes\"]:\n b.task = self.task\n self.display_debug = display_debug\n self.parallel = parallel\n\n @staticmethod\n def lake_cleaner(features, area_min, area_max, lake_river_max_dist, parallel=False):\n \"\"\"Flags geometric features as 'clean' based on type and distance to nearest river.\"\"\"\n # note: we use a flag here instead of removing bad features so that end-users can still use them if needed\n for f in features:\n f[\"clean\"] = False # flag every as 'bad' by default, clear just the ones of interest below\n rivers = [f for f in features if f[\"properties\"][\"TYPECE\"] == TB15D104.TYPECE_RIVER]\n lakes = [f for f in features if f[\"properties\"][\"TYPECE\"] == TB15D104.TYPECE_LAKE]\n logger.info(f\"labeling and cleaning {len(lakes)} lakes...\")\n\n def clean_lake(lake):\n if area_min <= lake[\"geometry\"].area <= area_max:\n if lake_river_max_dist == float(\"inf\"):\n return True\n else:\n for river in rivers:\n # note: distance check below seems to be \"intelligent\", i.e. it will\n # first check bbox distance, then check chull distance, and finally use\n # the full geometries (doing these steps here explicitly makes it slower)\n if lake[\"geometry\"].distance(river[\"geometry\"]) < lake_river_max_dist:\n return True\n return False\n\n if parallel:\n if not isinstance(parallel, int):\n import multiprocessing\n parallel = multiprocessing.cpu_count()\n assert parallel > 0, \"unexpected min core count\"\n import joblib\n flags = joblib.Parallel(n_jobs=parallel)(joblib.delayed(\n clean_lake)(lake) for lake in tqdm.tqdm(lakes, desc=\"labeling + cleaning lakes\"))\n for flag, lake in zip(flags, lakes):\n lake[\"clean\"] = flag\n else:\n for lake in tqdm.tqdm(lakes, desc=\"labeling + cleaning lakes\"):\n lake[\"clean\"] = clean_lake(lake)\n return features\n\n @staticmethod\n def lake_cropper(features, rasters_data, coverage, srs_target, px_size, skew, feature_buffer, parallel=False):\n \"\"\"Returns the ROI information for a given feature (may be modified in derived classes).\"\"\"\n srs_target_wkt = srs_target.ExportToWkt()\n\n def crop_feature(feature):\n assert feature[\"clean\"] # should not get here with bad features\n roi, roi_tl, roi_br, crop_width, crop_height = \\\n geo.utils.get_feature_roi(feature[\"geometry\"], px_size, skew, feature_buffer)\n roi_geotransform = (roi_tl[0], px_size[0], skew[0],\n roi_tl[1], skew[1], px_size[1])\n # test all raster regions that touch the selected feature\n raster_hits = []\n for raster_idx, raster_data in enumerate(rasters_data):\n if raster_data[\"target_roi\"].intersects(roi):\n raster_hits.append(raster_idx)\n # make list of all other features that may be included in the roi\n roi_centroid = feature[\"centroid\"]\n roi_radius = np.linalg.norm(np.asarray(roi_tl) - np.asarray(roi_br)) / 2\n roi_features, bboxes = [], []\n # note: the 'image id' is in fact the id of the focal feature in the crop\n image_id = int(feature[\"properties\"][\"OBJECTID\"])\n for f in features:\n # note: here, f may not be 'clean', test anyway\n if f[\"geometry\"].distance(roi_centroid) > roi_radius:\n continue\n inters = f[\"geometry\"].intersection(roi)\n if inters.is_empty:\n continue\n roi_features.append(f)\n if f[\"properties\"][\"TYPECE\"] == TB15D104.TYPECE_RIVER:\n continue\n # only lakes can generate bboxes; make sure to clip them to the roi bounds\n clip = f[\"clipped\"] or not inters.equals(f[\"geometry\"])\n if clip:\n assert inters.geom_type in [\"Polygon\", \"MultiPolygon\"], \"unexpected inters type\"\n corners = []\n if inters.geom_type == \"Polygon\":\n bounds = inters.bounds\n corners.append((bounds[0:2], bounds[2:4]))\n elif inters.geom_type == \"MultiPolygon\":\n for poly in inters:\n bounds = poly.bounds\n corners.append((bounds[0:2], bounds[2:4]))\n else:\n corners = [(f[\"tl\"], f[\"br\"])]\n for c in corners:\n feat_tl_px = geo.utils.get_pxcoord(roi_geotransform, *c[0])\n feat_br_px = geo.utils.get_pxcoord(roi_geotransform, *c[1])\n bbox = [max(0, feat_tl_px[0]), max(0, feat_tl_px[1]),\n min(crop_width - 1, feat_br_px[0]),\n min(crop_height - 1, feat_br_px[1])]\n if bbox[2] - bbox[0] <= 1 or bbox[3] - bbox[1] <= 1:\n continue # skip all bboxes smaller than 1 px (c'mon...)\n # note: lake class id is 1 by definition\n bboxes.append(thelper.tasks.detect.BoundingBox(TB15D104.LAKE_ID,\n bbox=bbox,\n include_margin=False,\n truncated=clip,\n image_id=image_id))\n # prepare actual 'sample' for crop generation at runtime\n return {\n \"features\": roi_features,\n \"bboxes\": bboxes,\n \"focal\": feature,\n \"id\": image_id,\n \"roi\": roi,\n \"roi_tl\": roi_tl,\n \"roi_br\": roi_br,\n \"raster_hits\": raster_hits,\n \"crop_width\": crop_width,\n \"crop_height\": crop_height,\n \"geotransform\": np.asarray(roi_geotransform),\n \"srs\": srs_target_wkt,\n }\n\n clean_feats = [f for f in features if f[\"clean\"]]\n if parallel:\n if not isinstance(parallel, int):\n import multiprocessing\n parallel = multiprocessing.cpu_count()\n assert parallel > 0, \"unexpected min core count\"\n import joblib\n samples = joblib.Parallel(n_jobs=parallel)(joblib.delayed(\n crop_feature)(feat) for feat in tqdm.tqdm(clean_feats, desc=\"preparing crop regions\"))\n else:\n samples = []\n for feature in tqdm.tqdm(clean_feats, desc=\"validating crop candidates\"):\n samples.append(crop_feature(feature))\n return [s for s in samples if s is not None]\n\n def _show_stats_plots(self, show=False, block=False):\n \"\"\"Draws and returns feature stats histograms using pyplot.\"\"\"\n import matplotlib.pyplot as plt\n feature_categories = {}\n for feat in self.features:\n curr_cat = feat[\"properties\"][\"TYPECE\"]\n if curr_cat not in feature_categories:\n feature_categories[curr_cat] = []\n feature_categories[curr_cat].append(feat)\n fig, axes = plt.subplots(len(feature_categories))\n for idx, (cat, features) in enumerate(feature_categories.items()):\n areas = [f[\"geometry\"].area for f in features]\n axes[idx].hist(areas, density=True, bins=30,\n range=(max(self.area_min, min(areas)), min(self.area_max, max(areas))))\n axes[idx].set_xlabel(\"Surface (m^2)\")\n axes[idx].set_title(f\"TYPECE = {cat}\")\n axes[idx].set_xlim(xmin=0)\n if show:\n fig.show()\n if block:\n plt.show(block=block)\n return fig\n plt.pause(0.5)\n return fig, axes\n\n def __getitem__(self, idx):\n \"\"\"Returns the data sample (a dictionary) for a specific (0-based) index.\"\"\"\n if isinstance(idx, slice):\n return self._getitems(idx)\n assert idx < len(self.samples), \"sample index is out-of-range\"\n if idx < 0:\n idx = len(self.samples) + idx\n sample = self.samples[idx]\n crop, mask = self._process_crop(sample)\n assert crop.shape[2] == 1, \"unexpected lidar raster band count\"\n crop = crop[:, :, 0]\n dmap = cv.distanceTransform(np.where(mask, np.uint8(0), np.uint8(255)), cv.DIST_L2, cv.DIST_MASK_PRECISE)\n dmap_inv = cv.distanceTransform(np.where(mask, np.uint8(255), np.uint8(0)), cv.DIST_L2, cv.DIST_MASK_PRECISE)\n dmap = np.where(mask, -dmap_inv, dmap)\n dmap *= self.px_size[0] # constructor enforces same px width/height size\n # dc mask is crop.mask, but most likely lost below\n if self.display_debug:\n crop = cv.normalize(crop, dst=crop, alpha=0, beta=255, norm_type=cv.NORM_MINMAX,\n dtype=cv.CV_8U, mask=(~crop.mask).astype(np.uint8))\n mask = cv.normalize(mask, dst=mask, alpha=0, beta=255, norm_type=cv.NORM_MINMAX, dtype=cv.CV_8U)\n dmap = cv.normalize(dmap, dst=dmap, alpha=0, beta=255, norm_type=cv.NORM_MINMAX, dtype=cv.CV_8U)\n sample = {\n \"input\": np.stack([crop, mask, dmap], axis=-1),\n # note: bboxes are automatically added in the \"cropper\" preprocessing function\n \"hydro\": mask,\n **sample\n }\n if self.transforms:\n sample = self.transforms(sample)\n return sample\n\n\nclass TB15D104TileDataset(geo.parsers.TileDataset):\n \"\"\"OGC Testbed-15 dataset parser for D104 (lake/river) segmentation task.\"\"\"\n\n def __init__(self, raster_path, vector_path, tile_size, tile_overlap,\n px_size=None, allow_outlying_vectors=True, clip_outlying_vectors=True,\n lake_area_min=0.0, lake_area_max=float(\"inf\"), master_roi=None, srs_target=\"3857\",\n force_parse=False, reproj_rasters=False, reproj_all_cpus=True, display_debug=False,\n keep_rasters_open=True, parallel=False, transforms=None):\n assert px_size is None or isinstance(px_size, (float, int)), \"pixel size (resolution) must be float/int\"\n px_size = (1.0, 1.0) if px_size is None else (float(px_size), float(px_size))\n # note: we wrap partial static functions for caching to see when internal parameters are changing\n cleaner = functools.partial(TB15D104Dataset.lake_cleaner, area_min=lake_area_min, area_max=lake_area_max,\n lake_river_max_dist=float(\"inf\"), parallel=parallel)\n super().__init__(raster_path=raster_path, vector_path=vector_path, tile_size=tile_size,\n tile_overlap=tile_overlap, skip_empty_tiles=True, skip_nodata_tiles=False,\n px_size=px_size, allow_outlying_vectors=allow_outlying_vectors,\n clip_outlying_vectors=clip_outlying_vectors, vector_area_min=lake_area_min,\n vector_area_max=lake_area_max, vector_target_prop=None, master_roi=master_roi,\n srs_target=srs_target, raster_key=\"lidar\", mask_key=\"hydro\", cleaner=cleaner,\n force_parse=force_parse, reproj_rasters=reproj_rasters, reproj_all_cpus=reproj_all_cpus,\n keep_rasters_open=keep_rasters_open, transforms=transforms)\n meta_keys = self.task.meta_keys\n self.task = thelper.tasks.Detection(class_names={\"background\": TB15D104.BACKGROUND_ID, \"lake\": TB15D104.LAKE_ID},\n input_key=\"input\", bboxes_key=\"bboxes\",\n meta_keys=meta_keys, background=0, color_map={\"lake\": [255, 0, 0]})\n self.display_debug = display_debug\n self.parallel = parallel\n\n def __getitem__(self, idx):\n \"\"\"Returns the data sample (a dictionary) for a specific (0-based) index.\"\"\"\n if isinstance(idx, slice):\n return self._getitems(idx)\n assert idx < len(self.samples), \"sample index is out-of-range\"\n if idx < 0:\n idx = len(self.samples) + idx\n sample = self.samples[idx]\n crop, mask = self._process_crop(sample)\n assert crop.shape[2] == 1, \"unexpected lidar raster band count\"\n crop = crop[:, :, 0]\n dmap = cv.distanceTransform(np.where(mask, np.uint8(0), np.uint8(255)), cv.DIST_L2, cv.DIST_MASK_PRECISE)\n dmap_inv = cv.distanceTransform(np.where(mask, np.uint8(255), np.uint8(0)), cv.DIST_L2, cv.DIST_MASK_PRECISE)\n dmap = np.where(mask, -dmap_inv, dmap)\n dmap *= self.px_size[0] # constructor enforces same px width/height size\n # dc mask is crop.mask, but most likely lost below\n if self.display_debug:\n crop = cv.normalize(crop, dst=crop, alpha=0, beta=255, norm_type=cv.NORM_MINMAX,\n dtype=cv.CV_8U, mask=(~crop.mask).astype(np.uint8))\n mask = cv.normalize(mask, dst=mask, alpha=0, beta=255, norm_type=cv.NORM_MINMAX, dtype=cv.CV_8U)\n dmap = cv.normalize(dmap, dst=dmap, alpha=0, beta=255, norm_type=cv.NORM_MINMAX, dtype=cv.CV_8U)\n # note1: contrarily to the 'smart' dataset parser above, we need to add bboxes here\n # note2: bboxes should only be added over areas that are not 'nodata'\n bboxes = []\n for f in sample[\"features\"]:\n if f[\"properties\"][\"TYPECE\"] == TB15D104.TYPECE_RIVER:\n continue\n # only lakes can generate bboxes; make sure to clip them to the crop bounds\n inters = f[\"geometry\"].intersection(sample[\"roi\"])\n clip = f[\"clipped\"] or not inters.equals(f[\"geometry\"])\n if clip:\n assert inters.geom_type in [\"Polygon\", \"MultiPolygon\"], \"unexpected inters type\"\n corners = []\n if inters.geom_type == \"Polygon\":\n bounds = inters.bounds\n corners.append((bounds[0:2], bounds[2:4]))\n elif inters.geom_type == \"MultiPolygon\":\n for poly in inters:\n bounds = poly.bounds\n corners.append((bounds[0:2], bounds[2:4]))\n else:\n corners = [(f[\"tl\"], f[\"br\"])]\n for c in corners:\n feat_tl_px = geo.utils.get_pxcoord(sample[\"geotransform\"], *c[0])\n feat_br_px = geo.utils.get_pxcoord(sample[\"geotransform\"], *c[1])\n bbox = [max(0, feat_tl_px[0]), max(0, feat_tl_px[1]),\n min(sample[\"crop_width\"] - 1, feat_br_px[0]),\n min(sample[\"crop_height\"] - 1, feat_br_px[1])]\n if bbox[2] - bbox[0] <= 1 or bbox[3] - bbox[1] <= 1:\n continue # skip all bboxes smaller than 1 px (c'mon...)\n # note: lake class id is 1 by definition\n bboxes.append(thelper.tasks.detect.BoundingBox(TB15D104.LAKE_ID,\n bbox=bbox,\n include_margin=False,\n truncated=clip,\n image_id=sample[\"id\"],\n task=self.task))\n sample = {\n \"input\": np.stack([crop, mask, dmap], axis=-1),\n \"hydro\": mask,\n \"bboxes\": bboxes,\n **sample\n }\n if self.transforms:\n sample = self.transforms(sample)\n return sample\n\n\nclass TB15D104DetectLogger(thelper.train.utils.DetectLogger):\n\n def __init__(self, conf_threshold=0.5):\n super().__init__(conf_threshold=conf_threshold, target_name=\"lake\",\n log_keys=[\"id\", \"geotransform\"], format=\"geojson\")\n\n def report_geojson(self):\n # here, we only care about reporting predictions, we ignore the (possibly missing) gt bboxes\n import shapely\n import geojson\n batch_size = len(self.bbox[0])\n bbox_lists = [bboxes for batch in self.bbox for bboxes in batch] # one list per crop\n if batch_size > 1:\n geotransforms = [np.asarray(geot) for batch in self.meta[\"geotransform\"] for geot in batch]\n else:\n # special check to avoid issues when unpacking (1,6)-dim tensor\n geotransforms = [np.asarray(geot) for geot in self.meta[\"geotransform\"]]\n crop_ids = [id for batch in self.meta[\"id\"] for id in batch]\n output_features = []\n for bboxes, geotransform, id in zip(bbox_lists, geotransforms, crop_ids):\n for bbox in bboxes:\n if geotransform.shape[0] == 1:\n geotransform = geotransform[0]\n bbox_tl = geo.utils.get_geocoord(geotransform, *bbox.top_left)\n bbox_br = geo.utils.get_geocoord(geotransform, *bbox.bottom_right)\n bbox_geom = shapely.geometry.Polygon([bbox_tl, (bbox_br[0], bbox_tl[1]),\n bbox_br, (bbox_tl[0], bbox_br[1])])\n output_features.append(geojson.Feature(geometry=bbox_geom, properties={\n \"image_id\": id, \"confidence\": bbox.confidence}))\n return geojson.dumps(geojson.FeatureCollection(output_features), indent=2)\n\n\ndef postproc_features(input_file, bboxes_srs, orig_geoms_path, output_file,\n final_srs=None, write_shapefile_copy=False):\n \"\"\"Post-processes bounding box detections produced during an evaluation session into a GeoJSON file.\"\"\"\n import ogr\n import osr\n import json\n import geojson\n import shapely\n logger.debug(\"importing bboxes SRS...\")\n assert isinstance(bboxes_srs, (str, int, osr.SpatialReference)), \\\n \"target EPSG SRS must be given as int/str\"\n if isinstance(bboxes_srs, (str, int)):\n if isinstance(bboxes_srs, str):\n bboxes_srs = int(bboxes_srs.replace(\"EPSG:\", \"\"))\n bboxes_srs_obj = osr.SpatialReference()\n bboxes_srs_obj.ImportFromEPSG(bboxes_srs)\n bboxes_srs = bboxes_srs_obj\n logger.debug(\"importing lake bboxes geojson...\")\n with open(input_file) as bboxes_fd:\n bboxes_geoms = thelper.data.geo.utils.parse_geojson(json.load(bboxes_fd))\n logger.debug(\"importing hydro features geojson...\")\n with open(orig_geoms_path) as hydro_fd:\n hydro_geoms = thelper.data.geo.utils.parse_geojson(json.load(hydro_fd), srs_target=bboxes_srs)\n logger.debug(\"computing global cascade of lake bboxes...\")\n detect_roi = shapely.ops.cascaded_union([bbox[\"geometry\"] for bbox in bboxes_geoms])\n output_features = []\n\n def append_poly(feat, props, srs_transform=None):\n if feat.is_empty:\n return\n elif feat.type == \"Polygon\":\n if srs_transform is not None:\n ogr_geometry = ogr.CreateGeometryFromWkb(feat.wkb)\n ogr_geometry.Transform(srs_transform)\n feat = shapely.wkt.loads(ogr_geometry.ExportToWkt())\n output_features.append((geojson.Feature(geometry=feat, properties=props), feat))\n elif feat.type == \"MultiPolygon\" or feat.type == \"GeometryCollection\":\n for f in feat:\n append_poly(f, props)\n\n srs_transform = None\n if final_srs is not None:\n import osr\n logger.debug(\"importing output SRS...\")\n assert isinstance(final_srs, (str, int, osr.SpatialReference)), \\\n \"target EPSG SRS must be given as int/str\"\n if isinstance(final_srs, (str, int)):\n if isinstance(final_srs, str):\n final_srs = int(final_srs.replace(\"EPSG:\", \"\"))\n final_srs_obj = osr.SpatialReference()\n final_srs_obj.ImportFromEPSG(final_srs)\n final_srs = final_srs_obj\n if not bboxes_srs.IsSame(final_srs):\n srs_transform = osr.CoordinateTransformation(bboxes_srs, final_srs)\n logger.debug(\"running hydro feature and lake bboxes intersection loop...\")\n for hydro_feat in tqdm.tqdm(hydro_geoms, desc=\"computing bbox intersections\"):\n # find intersection and append to list of 'lakes'\n intersection = hydro_feat[\"geometry\"].intersection(detect_roi)\n hydro_feat[\"properties\"][\"TYPECE\"] = TB15D104.TYPECE_LAKE\n append_poly(intersection, copy.deepcopy(hydro_feat[\"properties\"]), srs_transform)\n if not intersection.is_empty:\n # subtract bbox region from feature if intersection found (leftovers at end will be 'rivers')\n hydro_feat[\"geometry\"] = hydro_feat[\"geometry\"].difference(detect_roi)\n logger.debug(\"running river cleanup loop...\")\n for hydro_feat in tqdm.tqdm(hydro_geoms, desc=\"appending leftover geometries as rivers\"):\n if not hydro_feat[\"geometry\"].is_empty:\n # remark: hydro features outside the original ROI will appear as rivers despite never being processed\n hydro_feat[\"properties\"][\"TYPECE\"] = TB15D104.TYPECE_RIVER\n append_poly(hydro_feat[\"geometry\"], copy.deepcopy(hydro_feat[\"properties\"]), srs_transform)\n logger.debug(\"exporting final geojson...\")\n with open(output_file, \"w\") as fd:\n out_srs = final_srs if final_srs is not None else bboxes_srs\n fd.write(geo.utils.export_geojson_with_crs([o[0] for o in output_features], srs_target=out_srs))\n if write_shapefile_copy:\n logger.debug(\"exporting final shapefile...\")\n driver = ogr.GetDriverByName(\"ESRI Shapefile\")\n data_source = driver.CreateDataSource(output_file + \".shp\")\n layer = data_source.CreateLayer(\"lakes\", final_srs if final_srs is not None else bboxes_srs, ogr.wkbPolygon)\n for feat_tuple in output_features:\n feature = ogr.Feature(layer.GetLayerDefn())\n point = ogr.CreateGeometryFromWkt(feat_tuple[1].wkt)\n feature.SetGeometry(point)\n layer.CreateFeature(feature)\n feature = None\n data_source = None\n" ]
[ [ "numpy.asarray", "numpy.uint8", "numpy.stack", "matplotlib.pyplot.show", "numpy.where", "matplotlib.pyplot.pause" ] ]
Y-miura-ta/Nyanko
[ "4a6216c68fb727908fa8d296f01dbbb2cbcc2775" ]
[ "LegTrajectory.py" ]
[ "# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ng = 9800 # 単位は [mm/s^2]\n\n# 5次スプラインを求めるための行列は時間軸を正規化するので固定可能\nS_RATE = 1.0\nCmat = np.array([\n [0, 0, 0, 0, 0, 1],\n [S_RATE**5, S_RATE**4, S_RATE**3, S_RATE**2, S_RATE, 1],\n [0, 0, 0, 0, 1, 0],\n [5*S_RATE**4, 4*S_RATE**3, 3*S_RATE**2, 2*S_RATE, 1, 0],\n [0, 0, 0, 2, 0, 0],\n [20*S_RATE**3, 12*S_RATE**2, 6*S_RATE, 2, 0, 0]\n])\nCmat_inv = np.linalg.inv(Cmat)\n\n# 正規化5次関数の係数を計算\ndef calcQuinticFactor(X, V, A):\n Xvec = np.array([\n X[0], X[1], V[0], V[1], A[0], A[1] \n ])\n Avec = Cmat_inv@Xvec\n \n return Avec\n\n# 目標位置と前回位置、現在位置から脚軌道を計算\ndef calcQuinticFactorXYZ(p0, p1, v0, v1, a0, a1, t0, t1):\n eps = t1 - t0\n X = [p0[0]*S_RATE/eps, p1[0]*S_RATE/eps]\n Y = [p0[1]*S_RATE/eps, p1[1]*S_RATE/eps]\n Z = [p0[2]*S_RATE/eps, p1[2]*S_RATE/eps]\n VX = [v0[0], v1[0]]\n VY = [v0[1], v1[1]]\n VZ = [v0[2], v1[2]]\n AX = [a0[0]*eps/S_RATE, a1[0]*eps/S_RATE]\n AY = [a0[1]*eps/S_RATE, a1[1]*eps/S_RATE]\n AZ = [a0[2]*eps/S_RATE, a1[2]*eps/S_RATE]\n fact_x = calcQuinticFactor(X, VX, AX)\n fact_y = calcQuinticFactor(Y, VY, AY)\n fact_z = calcQuinticFactor(Z, VZ, AZ)\n\n return [fact_x, fact_y, fact_z]\n\ndef calcPoint(fact_xyz, t0, t1, t):\n eps = t1 - t0\n S = (t - t0)*S_RATE/eps\n X = fact_xyz[0][0]*S**5 + fact_xyz[0][1]*S**4 + fact_xyz[0][2]*S**3 + fact_xyz[0][3]*S**2 + fact_xyz[0][4]*S + fact_xyz[0][5]\n Y = fact_xyz[1][0]*S**5 + fact_xyz[1][1]*S**4 + fact_xyz[1][2]*S**3 + fact_xyz[1][3]*S**2 + fact_xyz[1][4]*S + fact_xyz[1][5]\n Z = fact_xyz[2][0]*S**5 + fact_xyz[2][1]*S**4 + fact_xyz[2][2]*S**3 + fact_xyz[2][3]*S**2 + fact_xyz[2][4]*S + fact_xyz[2][5]\n x = X*eps/S_RATE\n y = Y*eps/S_RATE\n z = Z*eps/S_RATE\n\n return [x, y, z]\n\ndef calcVelocity(fact_xyz, t0, t1, t):\n eps = t1 - t0\n S = (t - t0)*S_RATE/eps\n # vは正規化前と同じなので普通に計算\n vx = 5*fact_xyz[0][0]*S**4 + 4*fact_xyz[0][1]*S**3 + 3*fact_xyz[0][2]*S**2 + 2*fact_xyz[0][3]*S + fact_xyz[0][4]\n vy = 5*fact_xyz[1][0]*S**4 + 4*fact_xyz[1][1]*S**3 + 3*fact_xyz[1][2]*S**2 + 2*fact_xyz[1][3]*S + fact_xyz[1][4]\n vz = 5*fact_xyz[2][0]*S**4 + 4*fact_xyz[2][1]*S**3 + 3*fact_xyz[2][2]*S**2 + 2*fact_xyz[2][3]*S + fact_xyz[2][4]\n \n return [vx, vy, vz]\n\ndef calcAccele(fact_xyz, t0, t1, t):\n eps = t1 - t0\n S = (t - t0)*S_RATE/eps\n AX = 20*fact_xyz[0][0]*S**3 + 12*fact_xyz[0][1]*S**2 + 6*fact_xyz[0][2]*S + 2*fact_xyz[0][3]\n AY = 20*fact_xyz[1][0]*S**3 + 12*fact_xyz[1][1]*S**2 + 6*fact_xyz[1][2]*S + 2*fact_xyz[1][3]\n AZ = 20*fact_xyz[2][0]*S**3 + 12*fact_xyz[2][1]*S**2 + 6*fact_xyz[2][2]*S + 2*fact_xyz[2][3]\n ax = AX*S_RATE/eps\n ay = AY*S_RATE/eps\n az = AZ*S_RATE/eps\n\n return [ax, ay, az]\n\n# 次回目標位置と理論上の速度を計算\ndef calcNextPVA(p, v, a, t, dt):\n fact_xyz = calcQuinticFactorXYZ(p[0], p[1], v[0], v[1], a[0], a[1], t[0], t[1])\n p_next = calcPoint(fact_xyz, t[0], t[1], t[0]+dt)\n v_next = calcVelocity(fact_xyz, t[0], t[1], t[0]+dt)\n a_next = calcAccele(fact_xyz, t[0], t[1], t[0]+dt)\n\n return p_next, v_next, a_next\n\n# ボディ速度を見て目標位置を決定(ジャイロから計算された擬似的な値を想定しているのでヨー軸の制御は無し)\n# state = [p_xyz, v_xyz, a_xyz, t]\n# h_offsetは立脚期間中でボディ重量により脚が沈み込む分の補正値\ndef calcBalancePVA(state_cur, v_body_tar, v_body_obs, leg_center, body_h, leg_up_h, h_offset, T, dt):\n T_list = [0, T/4, T/2, 3*T/4, T]\n _v_body_tar = np.array(v_body_tar)\n _v_body_obs = np.array(v_body_obs)\n _leg_center = np.array(leg_center)\n _v_leg_stance = -_v_body_tar - 4/T*(_v_body_obs - _v_body_tar)*(body_h/g)**0.5\n alpha = 7.0\n \n if(state_cur[3]>=T_list[0] and state_cur[3]<T_list[1]):\n p_bottom = _leg_center - np.array([0, 0, h_offset])\n a_bottom = [0, 0, 0]\n p = [state_cur[0], p_bottom]\n v = [state_cur[1], _v_leg_stance]\n a = [state_cur[2], a_bottom]\n t = [state_cur[3], T_list[1]]\n # print(\"0 ~ T/4\")\n p_next, v_next, a_next = calcNextPVA(p, v, a, t, dt)\n # 立脚期のxy方向速度は一定なので別で計算して上書き\n # p_next[0] = state_cur[0][0] + _v_leg_stance[0]*dt\n # p_next[1] = state_cur[0][1] + _v_leg_stance[1]*dt\n\n elif(state_cur[3]>=T_list[1] and state_cur[3]<T_list[2]):\n p_up = _leg_center - T/4*_v_body_tar - (_v_body_obs*alpha - _v_body_tar)*(body_h/g)**0.5\n a_up = [0, 0, 0]\n p = [state_cur[0], p_up]\n v = [state_cur[1], _v_leg_stance]\n a = [state_cur[2], a_up]\n t = [state_cur[3], T_list[2]]\n # print(\"T/4 ~ T/2\")\n p_next, v_next, a_next = calcNextPVA(p, v, a, t, dt)\n # 立脚期のxy方向速度は一定なので別で計算して上書き\n # p_next[0] = state_cur[0][0] + _v_leg_stance[0]*dt\n # p_next[1] = state_cur[0][1] + _v_leg_stance[1]*dt\n\n elif(state_cur[3]>=T_list[2] and state_cur[3]<T_list[3]):\n p_top = _leg_center + np.array([0, 0, leg_up_h])\n a_top = [0, 0, 0]\n p = [state_cur[0], p_top]\n v = [state_cur[1], -2*_v_leg_stance]\n a = [state_cur[2], a_top]\n t = [state_cur[3], T_list[3]]\n # print(\"T/2 ~ 3T/4\")\n p_next, v_next, a_next = calcNextPVA(p, v, a, t, dt)\n\n elif(state_cur[3]>=T_list[3] and state_cur[3]<T_list[4]):\n p_touch = _leg_center + T/4*_v_body_tar + (_v_body_obs*alpha - _v_body_tar)*(body_h/g)**0.5\n a_touch = [0, 0, 0]\n p = [state_cur[0], p_touch]\n v = [state_cur[1], _v_leg_stance]\n a = [state_cur[2], a_touch]\n t = [state_cur[3], T_list[4]]\n # print(\"3T/4 ~ T\")\n p_next, v_next, a_next = calcNextPVA(p, v, a, t, dt)\n\n else:\n print(\"Error : Current t = {}\".format(state_cur[3]))\n\n return p_next, v_next, a_next\n\ndef makeTrajectoryList(state_cur, v_body_tar, v_body_obs, leg_center, body_h, leg_up_h, h_offset, T, dt):\n N = int(5*T/dt)\n px_list, py_list, pz_list = [], [], []\n vx_list, vy_list, vz_list = [], [], []\n ax_list, ay_list, az_list = [], [], []\n t_list = []\n for i in range(N):\n p, v, a = calcBalancePVA(state_cur, v_body_tar, v_body_obs, leg_center, body_h, leg_up_h, h_offset, T, dt)\n px_list.append(p[0])\n py_list.append(p[1])\n pz_list.append(p[2])\n vx_list.append(v[0])\n vy_list.append(v[1])\n vz_list.append(v[2])\n ax_list.append(a[0])\n ay_list.append(a[1])\n az_list.append(a[2])\n t_list.append(state_cur[3])\n if(state_cur[3]+dt > T):\n state_cur = [p, v, a, 0]\n else:\n state_cur = [p, v, a, state_cur[3]+dt]\n \n return [[px_list, py_list, pz_list], [vx_list, vy_list, vz_list], [ax_list, ay_list, az_list], t_list]\n\ndef main():\n state_cur = [[0, 0, -95], [0, 0, 0], [0, 0, 0], 0]\n v_body_tar = [200, 200, 0]\n v_body_obs = [90, 10, 0]\n leg_center = [0, 0, -90]\n body_h = 95\n leg_up_h = 40\n h_offset = 3\n T = 0.3\n dt = 0.05 # 最小:0.001\n trj = makeTrajectoryList(state_cur, v_body_tar, v_body_obs, leg_center, body_h, leg_up_h, h_offset, T, dt)\n\n limit = 2000\n ax = plt.axes(projection=\"3d\")\n ax.set_xlim(-limit, limit)\n ax.set_ylim(-limit, limit)\n ax.set_zlim(-limit, limit)\n ax.set_xlabel(\"X\")\n ax.set_ylabel(\"Y\")\n ax.set_zlabel(\"Z\")\n\n plt.plot(trj[0][0], trj[0][1], trj[0][2], marker='o')\n #plt.plot(trj[3], trj[0][2])\n #plt.plot(trj[3], trj[1][2])\n #plt.plot(trj[3], trj[2][2])\n plt.show()\n \nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.linalg.inv", "matplotlib.pyplot.axes", "matplotlib.pyplot.plot", "numpy.array", "matplotlib.pyplot.show" ] ]
stidk/GAM-SSD
[ "4a74ecc6b39d7202f0ca400ec33da1cce1a8c2a0" ]
[ "ppdet/modeling/anchor_heads/yolo_head.py" ]
[ "# Copyright (c) 2019 PaddlePaddle 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\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom paddle import fluid\nfrom paddle.fluid.param_attr import ParamAttr\nfrom paddle.fluid.regularizer import L2Decay\n\nfrom ppdet.modeling.ops import MultiClassNMS, MultiClassSoftNMS, MatrixNMS\nfrom ppdet.modeling.losses.yolo_loss import YOLOv3Loss\nfrom ppdet.core.workspace import register\nfrom ppdet.modeling.ops import DropBlock\nfrom .iou_aware import get_iou_aware_score\ntry:\n from collections.abc import Sequence\nexcept Exception:\n from collections import Sequence\nfrom ppdet.utils.check import check_version\n\n__all__ = ['YOLOv3Head', 'YOLOv4Head']\n\n\n@register\nclass YOLOv3Head(object):\n \"\"\"\n Head block for YOLOv3 network\n\n Args:\n conv_block_num (int): number of conv block in each detection block\n norm_decay (float): weight decay for normalization layer weights\n num_classes (int): number of output classes\n anchors (list): anchors\n anchor_masks (list): anchor masks\n nms (object): an instance of `MultiClassNMS`\n \"\"\"\n __inject__ = ['yolo_loss', 'nms']\n __shared__ = ['num_classes', 'weight_prefix_name']\n\n def __init__(self,\n conv_block_num=2,\n norm_decay=0.,\n num_classes=80,\n anchors=[[10, 13], [16, 30], [33, 23], [30, 61], [62, 45],\n [59, 119], [116, 90], [156, 198], [373, 326]],\n anchor_masks=[[6, 7, 8], [3, 4, 5], [0, 1, 2]],\n drop_block=False,\n coord_conv=False,\n iou_aware=False,\n iou_aware_factor=0.4,\n block_size=3,\n keep_prob=0.9,\n yolo_loss=\"YOLOv3Loss\",\n spp=False,\n nms=MultiClassNMS(\n score_threshold=0.01,\n nms_top_k=1000,\n keep_top_k=100,\n nms_threshold=0.45,\n background_label=-1).__dict__,\n weight_prefix_name='',\n downsample=[32, 16, 8],\n scale_x_y=1.0,\n clip_bbox=True):\n check_version(\"1.8.4\")\n self.conv_block_num = conv_block_num\n self.norm_decay = norm_decay\n self.num_classes = num_classes\n self.anchor_masks = anchor_masks\n self._parse_anchors(anchors)\n self.yolo_loss = yolo_loss\n self.nms = nms\n self.prefix_name = weight_prefix_name\n self.drop_block = drop_block\n self.iou_aware = iou_aware\n self.coord_conv = coord_conv\n self.iou_aware_factor = iou_aware_factor\n self.block_size = block_size\n self.keep_prob = keep_prob\n self.use_spp = spp\n if isinstance(nms, dict):\n self.nms = MultiClassNMS(**nms)\n self.downsample = downsample\n self.scale_x_y = scale_x_y\n self.clip_bbox = clip_bbox\n\n def _create_tensor_from_numpy(self, numpy_array):\n paddle_array = fluid.layers.create_global_var(\n shape=numpy_array.shape, value=0., dtype=numpy_array.dtype)\n fluid.layers.assign(numpy_array, paddle_array)\n return paddle_array\n\n def _add_coord(self, input, is_test=True):\n if not self.coord_conv:\n return input\n\n # NOTE: here is used for exporting model for TensorRT inference,\n # only support batch_size=1 for input shape should be fixed,\n # and we create tensor with fixed shape from numpy array\n if is_test and input.shape[2] > 0 and input.shape[3] > 0:\n batch_size = 1\n grid_x = int(input.shape[3])\n grid_y = int(input.shape[2])\n idx_i = np.array(\n [[i / (grid_x - 1) * 2.0 - 1 for i in range(grid_x)]],\n dtype='float32')\n gi_np = np.repeat(idx_i, grid_y, axis=0)\n gi_np = np.reshape(gi_np, newshape=[1, 1, grid_y, grid_x])\n gi_np = np.tile(gi_np, reps=[batch_size, 1, 1, 1])\n\n x_range = self._create_tensor_from_numpy(gi_np.astype(np.float32))\n x_range.stop_gradient = True\n\n idx_j = np.array(\n [[j / (grid_y - 1) * 2.0 - 1 for j in range(grid_y)]],\n dtype='float32')\n gj_np = np.repeat(idx_j, grid_x, axis=1)\n gj_np = np.reshape(gj_np, newshape=[1, 1, grid_y, grid_x])\n gj_np = np.tile(gi_np, reps=[batch_size, 1, 1, 1])\n y_range = self._create_tensor_from_numpy(gj_np.astype(np.float32))\n y_range.stop_gradient = True\n\n # NOTE: in training mode, H and W is variable for random shape,\n # implement add_coord with shape as Variable\n else:\n input_shape = fluid.layers.shape(input)\n b = input_shape[0]\n h = input_shape[2]\n w = input_shape[3]\n\n x_range = fluid.layers.range(0, w, 1, 'float32') / ((w - 1.) / 2.)\n x_range = x_range - 1.\n x_range = fluid.layers.unsqueeze(x_range, [0, 1, 2])\n x_range = fluid.layers.expand(x_range, [b, 1, h, 1])\n x_range.stop_gradient = True\n\n y_range = fluid.layers.range(0, h, 1, 'float32') / ((h - 1.) / 2.)\n y_range = y_range - 1.\n y_range = fluid.layers.unsqueeze(y_range, [0, 1, 3])\n y_range = fluid.layers.expand(y_range, [b, 1, 1, w])\n y_range.stop_gradient = True\n\n return fluid.layers.concat([input, x_range, y_range], axis=1)\n\n def _conv_bn(self,\n input,\n ch_out,\n filter_size,\n stride,\n padding,\n act='leaky',\n name=None):\n conv = fluid.layers.conv2d(\n input=input,\n num_filters=ch_out,\n filter_size=filter_size,\n stride=stride,\n padding=padding,\n act=None,\n param_attr=ParamAttr(name=name + \".conv.weights\"),\n bias_attr=False)\n\n bn_name = name + \".bn\"\n bn_param_attr = ParamAttr(\n regularizer=L2Decay(self.norm_decay), name=bn_name + '.scale')\n bn_bias_attr = ParamAttr(\n regularizer=L2Decay(self.norm_decay), name=bn_name + '.offset')\n out = fluid.layers.batch_norm(\n input=conv,\n act=None,\n param_attr=bn_param_attr,\n bias_attr=bn_bias_attr,\n moving_mean_name=bn_name + '.mean',\n moving_variance_name=bn_name + '.var')\n\n if act == 'leaky':\n out = fluid.layers.leaky_relu(x=out, alpha=0.1)\n return out\n\n def _spp_module(self, input, name=\"\"):\n output1 = input\n output2 = fluid.layers.pool2d(\n input=output1,\n pool_size=5,\n pool_stride=1,\n pool_padding=2,\n ceil_mode=False,\n pool_type='max')\n output3 = fluid.layers.pool2d(\n input=output1,\n pool_size=9,\n pool_stride=1,\n pool_padding=4,\n ceil_mode=False,\n pool_type='max')\n output4 = fluid.layers.pool2d(\n input=output1,\n pool_size=13,\n pool_stride=1,\n pool_padding=6,\n ceil_mode=False,\n pool_type='max')\n output = fluid.layers.concat(\n input=[output1, output2, output3, output4], axis=1)\n return output\n\n def _detection_block(self,\n input,\n channel,\n conv_block_num=2,\n is_first=False,\n is_test=True,\n name=None):\n assert channel % 2 == 0, \\\n \"channel {} cannot be divided by 2 in detection block {}\" \\\n .format(channel, name)\n\n conv = input\n for j in range(conv_block_num):\n conv = self._add_coord(conv, is_test=is_test)\n conv = self._conv_bn(\n conv,\n channel,\n filter_size=1,\n stride=1,\n padding=0,\n name='{}.{}.0'.format(name, j))\n if self.use_spp and is_first and j == 1:\n conv = self._spp_module(conv, name=\"spp\")\n conv = self._conv_bn(\n conv,\n 512,\n filter_size=1,\n stride=1,\n padding=0,\n name='{}.{}.spp.conv'.format(name, j))\n conv = self._conv_bn(\n conv,\n channel * 2,\n filter_size=3,\n stride=1,\n padding=1,\n name='{}.{}.1'.format(name, j))\n if self.drop_block and j == 0 and not is_first:\n conv = DropBlock(\n conv,\n block_size=self.block_size,\n keep_prob=self.keep_prob,\n is_test=is_test)\n\n if self.drop_block and is_first:\n conv = DropBlock(\n conv,\n block_size=self.block_size,\n keep_prob=self.keep_prob,\n is_test=is_test)\n conv = self._add_coord(conv, is_test=is_test)\n route = self._conv_bn(\n conv,\n channel,\n filter_size=1,\n stride=1,\n padding=0,\n name='{}.2'.format(name))\n new_route = self._add_coord(route, is_test=is_test)\n tip = self._conv_bn(\n new_route,\n channel * 2,\n filter_size=3,\n stride=1,\n padding=1,\n name='{}.tip'.format(name))\n return route, tip\n\n def _upsample(self, input, scale=2, name=None):\n out = fluid.layers.resize_nearest(\n input=input, scale=float(scale), name=name)\n return out\n\n def _parse_anchors(self, anchors):\n \"\"\"\n Check ANCHORS/ANCHOR_MASKS in config and parse mask_anchors\n\n \"\"\"\n self.anchors = []\n self.mask_anchors = []\n\n assert len(anchors) > 0, \"ANCHORS not set.\"\n assert len(self.anchor_masks) > 0, \"ANCHOR_MASKS not set.\"\n\n for anchor in anchors:\n assert len(anchor) == 2, \"anchor {} len should be 2\".format(anchor)\n self.anchors.extend(anchor)\n\n anchor_num = len(anchors)\n for masks in self.anchor_masks:\n self.mask_anchors.append([])\n for mask in masks:\n assert mask < anchor_num, \"anchor mask index overflow\"\n self.mask_anchors[-1].extend(anchors[mask])\n\n def _get_outputs(self, input, is_train=True):\n \"\"\"\n Get YOLOv3 head output\n\n Args:\n input (list): List of Variables, output of backbone stages\n is_train (bool): whether in train or test mode\n\n Returns:\n outputs (list): Variables of each output layer\n \"\"\"\n\n outputs = []\n\n # get last out_layer_num blocks in reverse order\n out_layer_num = len(self.anchor_masks)\n blocks = input[-1:-out_layer_num - 1:-1]\n\n route = None\n for i, block in enumerate(blocks):\n if i > 0: # perform concat in first 2 detection_block\n block = fluid.layers.concat(input=[route, block], axis=1)\n route, tip = self._detection_block(\n block,\n channel=64 * (2**out_layer_num) // (2**i),\n is_first=i == 0,\n is_test=(not is_train),\n conv_block_num=self.conv_block_num,\n name=self.prefix_name + \"yolo_block.{}\".format(i))\n\n # out channel number = mask_num * (5 + class_num)\n if self.iou_aware:\n num_filters = len(self.anchor_masks[i]) * (self.num_classes + 6)\n else:\n num_filters = len(self.anchor_masks[i]) * (self.num_classes + 5)\n with fluid.name_scope('yolo_output'):\n block_out = fluid.layers.conv2d(\n input=tip,\n num_filters=num_filters,\n filter_size=1,\n stride=1,\n padding=0,\n act=None,\n param_attr=ParamAttr(\n name=self.prefix_name +\n \"yolo_output.{}.conv.weights\".format(i)),\n bias_attr=ParamAttr(\n regularizer=L2Decay(0.),\n name=self.prefix_name +\n \"yolo_output.{}.conv.bias\".format(i)))\n outputs.append(block_out)\n\n if i < len(blocks) - 1:\n # do not perform upsample in the last detection_block\n route = self._conv_bn(\n input=route,\n ch_out=256 // (2**i),\n filter_size=1,\n stride=1,\n padding=0,\n name=self.prefix_name + \"yolo_transition.{}\".format(i))\n # upsample\n route = self._upsample(route)\n\n return outputs\n\n def get_loss(self, input, gt_box, gt_label, gt_score, targets):\n \"\"\"\n Get final loss of network of YOLOv3.\n\n Args:\n input (list): List of Variables, output of backbone stages\n gt_box (Variable): The ground-truth boudding boxes.\n gt_label (Variable): The ground-truth class labels.\n gt_score (Variable): The ground-truth boudding boxes mixup scores.\n targets ([Variables]): List of Variables, the targets for yolo\n loss calculatation.\n\n Returns:\n loss (Variable): The loss Variable of YOLOv3 network.\n\n \"\"\"\n outputs = self._get_outputs(input, is_train=True)\n\n return self.yolo_loss(outputs, gt_box, gt_label, gt_score, targets,\n self.anchors, self.anchor_masks,\n self.mask_anchors, self.num_classes,\n self.prefix_name)\n\n def get_prediction(self, input, im_size, exclude_nms=False):\n \"\"\"\n Get prediction result of YOLOv3 network\n\n Args:\n input (list): List of Variables, output of backbone stages\n im_size (Variable): Variable of size([h, w]) of each image\n\n Returns:\n pred (Variable): The prediction result after non-max suppress.\n\n \"\"\"\n\n outputs = self._get_outputs(input, is_train=False)\n\n boxes = []\n scores = []\n for i, output in enumerate(outputs):\n if self.iou_aware:\n output = get_iou_aware_score(output,\n len(self.anchor_masks[i]),\n self.num_classes,\n self.iou_aware_factor)\n scale_x_y = self.scale_x_y if not isinstance(\n self.scale_x_y, Sequence) else self.scale_x_y[i]\n box, score = fluid.layers.yolo_box(\n x=output,\n img_size=im_size,\n anchors=self.mask_anchors[i],\n class_num=self.num_classes,\n conf_thresh=self.nms.score_threshold,\n downsample_ratio=self.downsample[i],\n name=self.prefix_name + \"yolo_box\" + str(i),\n clip_bbox=self.clip_bbox,\n scale_x_y=scale_x_y)\n boxes.append(box)\n scores.append(fluid.layers.transpose(score, perm=[0, 2, 1]))\n\n yolo_boxes = fluid.layers.concat(boxes, axis=1)\n yolo_scores = fluid.layers.concat(scores, axis=2)\n\n # Only for benchmark, postprocess(NMS) is not needed\n if exclude_nms:\n return {'bbox': yolo_scores}\n\n if type(self.nms) is MultiClassSoftNMS:\n yolo_scores = fluid.layers.transpose(yolo_scores, perm=[0, 2, 1])\n pred = self.nms(bboxes=yolo_boxes, scores=yolo_scores)\n return {'bbox': pred}\n\n\n@register\nclass YOLOv4Head(YOLOv3Head):\n \"\"\"\n Head block for YOLOv4 network\n\n Args:\n anchors (list): anchors\n anchor_masks (list): anchor masks\n nms (object): an instance of `MultiClassNMS`\n spp_stage (int): apply spp on which stage.\n num_classes (int): number of output classes\n downsample (list): downsample ratio for each yolo_head\n scale_x_y (list): scale the center point of bbox at each stage\n \"\"\"\n __inject__ = ['nms', 'yolo_loss']\n __shared__ = ['num_classes', 'weight_prefix_name']\n\n def __init__(self,\n anchors=[[12, 16], [19, 36], [40, 28], [36, 75], [76, 55],\n [72, 146], [142, 110], [192, 243], [459, 401]],\n anchor_masks=[[0, 1, 2], [3, 4, 5], [6, 7, 8]],\n nms=MultiClassNMS(\n score_threshold=0.01,\n nms_top_k=-1,\n keep_top_k=-1,\n nms_threshold=0.45,\n background_label=-1).__dict__,\n spp_stage=5,\n num_classes=80,\n weight_prefix_name='',\n downsample=[8, 16, 32],\n scale_x_y=1.0,\n yolo_loss=\"YOLOv3Loss\",\n iou_aware=False,\n iou_aware_factor=0.4,\n clip_bbox=False):\n super(YOLOv4Head, self).__init__(\n anchors=anchors,\n anchor_masks=anchor_masks,\n nms=nms,\n num_classes=num_classes,\n weight_prefix_name=weight_prefix_name,\n downsample=downsample,\n scale_x_y=scale_x_y,\n yolo_loss=yolo_loss,\n iou_aware=iou_aware,\n iou_aware_factor=iou_aware_factor,\n clip_bbox=clip_bbox)\n self.spp_stage = spp_stage\n\n def _upsample(self, input, scale=2, name=None):\n out = fluid.layers.resize_nearest(\n input=input, scale=float(scale), name=name)\n return out\n\n def max_pool(self, input, size):\n pad = [(size - 1) // 2] * 2\n return fluid.layers.pool2d(input, size, 'max', pool_padding=pad)\n\n def spp(self, input):\n branch_a = self.max_pool(input, 13)\n branch_b = self.max_pool(input, 9)\n branch_c = self.max_pool(input, 5)\n out = fluid.layers.concat([branch_a, branch_b, branch_c, input], axis=1)\n return out\n\n def stack_conv(self,\n input,\n ch_list=[512, 1024, 512],\n filter_list=[1, 3, 1],\n stride=1,\n name=None):\n conv = input\n for i, (ch_out, f_size) in enumerate(zip(ch_list, filter_list)):\n padding = 1 if f_size == 3 else 0\n conv = self._conv_bn(\n conv,\n ch_out=ch_out,\n filter_size=f_size,\n stride=stride,\n padding=padding,\n name='{}.{}'.format(name, i))\n return conv\n\n def spp_module(self, input, name=None):\n conv = self.stack_conv(input, name=name + '.stack_conv.0')\n spp_out = self.spp(conv)\n conv = self.stack_conv(spp_out, name=name + '.stack_conv.1')\n return conv\n\n def pan_module(self, input, filter_list, name=None):\n for i in range(1, len(input)):\n ch_out = input[i].shape[1] // 2\n conv_left = self._conv_bn(\n input[i],\n ch_out=ch_out,\n filter_size=1,\n stride=1,\n padding=0,\n name=name + '.{}.left'.format(i))\n ch_out = input[i - 1].shape[1] // 2\n conv_right = self._conv_bn(\n input[i - 1],\n ch_out=ch_out,\n filter_size=1,\n stride=1,\n padding=0,\n name=name + '.{}.right'.format(i))\n conv_right = self._upsample(conv_right)\n pan_out = fluid.layers.concat([conv_left, conv_right], axis=1)\n ch_list = [pan_out.shape[1] // 2 * k for k in [1, 2, 1, 2, 1]]\n input[i] = self.stack_conv(\n pan_out,\n ch_list=ch_list,\n filter_list=filter_list,\n name=name + '.stack_conv.{}'.format(i))\n return input\n\n def _get_outputs(self, input, is_train=True):\n outputs = []\n filter_list = [1, 3, 1, 3, 1]\n spp_stage = len(input) - self.spp_stage\n # get last out_layer_num blocks in reverse order\n out_layer_num = len(self.anchor_masks)\n blocks = input[-1:-out_layer_num - 1:-1]\n blocks[spp_stage] = self.spp_module(\n blocks[spp_stage], name=self.prefix_name + \"spp_module\")\n blocks = self.pan_module(\n blocks,\n filter_list=filter_list,\n name=self.prefix_name + 'pan_module')\n\n # reverse order back to input\n blocks = blocks[::-1]\n\n route = None\n for i, block in enumerate(blocks):\n if i > 0: # perform concat in first 2 detection_block\n route = self._conv_bn(\n route,\n ch_out=route.shape[1] * 2,\n filter_size=3,\n stride=2,\n padding=1,\n name=self.prefix_name + 'yolo_block.route.{}'.format(i))\n block = fluid.layers.concat(input=[route, block], axis=1)\n ch_list = [block.shape[1] // 2 * k for k in [1, 2, 1, 2, 1]]\n block = self.stack_conv(\n block,\n ch_list=ch_list,\n filter_list=filter_list,\n name=self.prefix_name +\n 'yolo_block.stack_conv.{}'.format(i))\n route = block\n\n block_out = self._conv_bn(\n block,\n ch_out=block.shape[1] * 2,\n filter_size=3,\n stride=1,\n padding=1,\n name=self.prefix_name + 'yolo_output.{}.conv.0'.format(i))\n\n if self.iou_aware:\n num_filters = len(self.anchor_masks[i]) * (self.num_classes + 6)\n else:\n num_filters = len(self.anchor_masks[i]) * (self.num_classes + 5)\n block_out = fluid.layers.conv2d(\n input=block_out,\n num_filters=num_filters,\n filter_size=1,\n stride=1,\n padding=0,\n act=None,\n param_attr=ParamAttr(name=self.prefix_name +\n \"yolo_output.{}.conv.1.weights\".format(i)),\n bias_attr=ParamAttr(\n regularizer=L2Decay(0.),\n name=self.prefix_name +\n \"yolo_output.{}.conv.1.bias\".format(i)))\n outputs.append(block_out)\n\n return outputs\n" ]
[ [ "numpy.reshape", "numpy.repeat", "numpy.tile" ] ]
jonaslindemann/compute-course-public
[ "b8f55595ebbd790d79b525efdff17b8517154796" ]
[ "matplotlib/ex20.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 7 14:19:31 2017\n\n@author: Jonas Lindemann\n\"\"\"\n\n\"\"\"\nDemo of the `streamplot` function.\n\nA streamplot, or streamline plot, is used to display 2D vector fields. This\nexample shows a few features of the stream plot function:\n\n * Varying the color along a streamline.\n * Varying the density of streamlines.\n * Varying the line width along a stream line.\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nY, X = np.mgrid[-3:3:100j, -3:3:100j]\nU = -1 - X**2 + Y\nV = 1 + X - Y**2\nspeed = np.sqrt(U*U + V*V)\n\nfig0, ax0 = plt.subplots()\nstrm = ax0.streamplot(X, Y, U, V, color=U, linewidth=2, cmap=plt.cm.autumn)\nfig0.colorbar(strm.lines)\n\nfig1, (ax1, ax2) = plt.subplots(ncols=2)\nax1.streamplot(X, Y, U, V, density=[0.5, 1])\n\nlw = 5*speed / speed.max()\nax2.streamplot(X, Y, U, V, density=0.6, color='k', linewidth=lw)\n\nfig2, (ax3, ax4) = plt.subplots(ncols=2)\nax3.contourf(X, Y, U, cmap=plt.cm.RdBu)\nax4.contourf(X, Y, V, cmap=plt.cm.RdBu)\n\nplt.show()" ]
[ [ "matplotlib.pyplot.subplots", "matplotlib.pyplot.show", "numpy.sqrt" ] ]
MachineLearningBCAM/minimax-risk-classifier
[ "38eb2413de54ee804b0be81781bd65ac4a748ced" ]
[ "venv/lib/python3.6/site-packages/nlp/utils/py_utils.py" ]
[ "# coding=utf-8\n# Copyright 2020 The HuggingFace NLP Authors and the TensorFlow Datasets 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# Lint as: python3\n\"\"\"Some python utils function and classes.\n\n\"\"\"\n\nimport contextlib\nimport functools\nimport itertools\nimport os\nimport types\nfrom io import BytesIO as StringIO\nfrom shutil import disk_usage\nfrom types import CodeType\n\nimport dill\nimport numpy as np\n\n\n# NOTE: When used on an instance method, the cache is shared across all\n# instances and IS NOT per-instance.\n# See\n# https://stackoverflow.com/questions/14946264/python-lru-cache-decorator-per-instance\n# For @property methods, use @memoized_property below.\nmemoize = functools.lru_cache\n\n\ndef map_all_sequences_to_lists(data_struct):\n # Could add support for more exotic data_struct, like OrderedDict\n def sequences_to_list(seq):\n if isinstance(seq, (tuple, np.ndarray)):\n return list(seq)\n else:\n return seq\n\n return map_nested(sequences_to_list, data_struct)\n\n\ndef size_str(size_in_bytes):\n \"\"\"Returns a human readable size string.\n\n If size_in_bytes is None, then returns \"Unknown size\".\n\n For example `size_str(1.5 * nlp.units.GiB) == \"1.50 GiB\"`.\n\n Args:\n size_in_bytes: `int` or `None`, the size, in bytes, that we want to\n format as a human-readable size string.\n \"\"\"\n if not size_in_bytes:\n return \"Unknown size\"\n\n _NAME_LIST = [(\"PiB\", 2 ** 50), (\"TiB\", 2 ** 40), (\"GiB\", 2 ** 30), (\"MiB\", 2 ** 20), (\"KiB\", 2 ** 10)]\n\n size_in_bytes = float(size_in_bytes)\n for (name, size_bytes) in _NAME_LIST:\n value = size_in_bytes / size_bytes\n if value >= 1.0:\n return \"{:.2f} {}\".format(value, name)\n return \"{} {}\".format(int(size_in_bytes), \"bytes\")\n\n\ndef is_notebook():\n \"\"\"Returns True if running in a notebook (Colab, Jupyter) environement.\"\"\"\n # Inspired from the tfdm autonotebook code\n try:\n from IPython import get_ipython # pylint: disable=import-outside-toplevel,g-import-not-at-top\n\n if \"IPKernelApp\" not in get_ipython().config:\n return False # Run in a IPython terminal\n except: # noqa: E722\n return False\n else:\n return True\n\n\[email protected]\ndef temporary_assignment(obj, attr, value):\n \"\"\"Temporarily assign obj.attr to value.\"\"\"\n original = getattr(obj, attr, None)\n setattr(obj, attr, value)\n try:\n yield\n finally:\n setattr(obj, attr, original)\n\n\ndef zip_dict(*dicts):\n \"\"\"Iterate over items of dictionaries grouped by their keys.\"\"\"\n for key in set(itertools.chain(*dicts)): # set merge all keys\n # Will raise KeyError if the dict don't have the same keys\n yield key, tuple(d[key] for d in dicts)\n\n\nclass NonMutableDict(dict):\n \"\"\"Dict where keys can only be added but not modified.\n\n Will raise an error if the user try to overwrite one key. The error message\n can be customized during construction. It will be formatted using {key} for\n the overwritten key.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n self._error_msg = kwargs.pop(\"error_msg\", \"Try to overwrite existing key: {key}\",)\n if kwargs:\n raise ValueError(\"NonMutableDict cannot be initialized with kwargs.\")\n super(NonMutableDict, self).__init__(*args, **kwargs)\n\n def __setitem__(self, key, value):\n if key in self:\n raise ValueError(self._error_msg.format(key=key))\n return super(NonMutableDict, self).__setitem__(key, value)\n\n def update(self, other):\n if any(k in self for k in other):\n raise ValueError(self._error_msg.format(key=set(self) & set(other)))\n return super(NonMutableDict, self).update(other)\n\n\nclass classproperty(property): # pylint: disable=invalid-name\n \"\"\"Descriptor to be used as decorator for @classmethods.\"\"\"\n\n def __get__(self, obj, objtype=None):\n return self.fget.__get__(None, objtype)()\n\n\nclass memoized_property(property): # pylint: disable=invalid-name\n \"\"\"Descriptor that mimics @property but caches output in member variable.\"\"\"\n\n def __get__(self, obj, objtype=None):\n # See https://docs.python.org/3/howto/descriptor.html#properties\n if obj is None:\n return self\n if self.fget is None:\n raise AttributeError(\"unreadable attribute\")\n attr = \"__cached_\" + self.fget.__name__\n cached = getattr(obj, attr, None)\n if cached is None:\n cached = self.fget(obj)\n setattr(obj, attr, cached)\n return cached\n\n\ndef map_nested(function, data_struct, dict_only=False, map_list=True, map_tuple=False, map_numpy=False):\n \"\"\"Apply a function recursively to each element of a nested data struct.\"\"\"\n\n # Could add support for more exotic data_struct, like OrderedDict\n if isinstance(data_struct, dict):\n return {\n k: map_nested(\n function, v, dict_only=dict_only, map_list=map_list, map_tuple=map_tuple, map_numpy=map_numpy\n )\n for k, v in data_struct.items()\n }\n elif not dict_only:\n types = []\n if map_list:\n types.append(list)\n if map_tuple:\n types.append(tuple)\n if map_numpy:\n types.append(np.ndarray)\n if isinstance(data_struct, tuple(types)):\n mapped = [\n map_nested(\n function, v, dict_only=dict_only, map_list=map_list, map_tuple=map_tuple, map_numpy=map_numpy\n )\n for v in data_struct\n ]\n if isinstance(data_struct, list):\n return mapped\n elif isinstance(data_struct, tuple):\n return tuple(mapped)\n else:\n return np.array(mapped)\n # Singleton\n return function(data_struct)\n\n\ndef zip_nested(arg0, *args, **kwargs):\n \"\"\"Zip data struct together and return a data struct with the same shape.\"\"\"\n # Python 2 do not support kwargs only arguments\n dict_only = kwargs.pop(\"dict_only\", False)\n assert not kwargs\n\n # Could add support for more exotic data_struct, like OrderedDict\n if isinstance(arg0, dict):\n return {k: zip_nested(*a, dict_only=dict_only) for k, a in zip_dict(arg0, *args)}\n elif not dict_only:\n if isinstance(arg0, list):\n return [zip_nested(*a, dict_only=dict_only) for a in zip(arg0, *args)]\n # Singleton\n return (arg0,) + args\n\n\ndef flatten_nest_dict(d):\n \"\"\"Return the dict with all nested keys flattened joined with '/'.\"\"\"\n # Use NonMutableDict to ensure there is no collision between features keys\n flat_dict = NonMutableDict()\n for k, v in d.items():\n if isinstance(v, dict):\n flat_dict.update({\"{}/{}\".format(k, k2): v2 for k2, v2 in flatten_nest_dict(v).items()})\n else:\n flat_dict[k] = v\n return flat_dict\n\n\ndef flatten_nested(data_struct):\n \"\"\"Flatten data struct of obj or `list`/`dict` of obj\"\"\"\n if isinstance(data_struct, dict):\n data_struct = list(flatten_nest_dict(data_struct).values())\n if data_struct and isinstance(data_struct[0], (list, tuple)):\n data_struct = [x for sublist in data_struct for x in sublist]\n if isinstance(data_struct, (list, tuple)):\n return data_struct\n # Singleton\n return [data_struct]\n\n\ndef nlp_dir():\n \"\"\"Path to nlp directory.\"\"\"\n return os.path.dirname(os.path.dirname(os.path.dirname(__file__)))\n\n\nclass abstractclassmethod(classmethod): # pylint: disable=invalid-name\n \"\"\"Decorate a method to mark it as an abstract @classmethod.\"\"\"\n\n __isabstractmethod__ = True\n\n def __init__(self, fn):\n fn.__isabstractmethod__ = True\n super(abstractclassmethod, self).__init__(fn)\n\n\ndef get_nlp_path(relative_path):\n \"\"\"Returns absolute path to file given path relative to nlp root.\"\"\"\n path = os.path.join(nlp_dir(), relative_path)\n return path\n\n\ndef has_sufficient_disk_space(needed_bytes, directory=\".\"):\n try:\n free_bytes = disk_usage(os.path.abspath(directory)).free\n except OSError:\n return True\n return needed_bytes < free_bytes\n\n\nclass Pickler(dill.Pickler):\n \"\"\"Same Pickler as the one from dill, but improved for notebooks and shells\"\"\"\n\n dispatch = dill._dill.MetaCatchingDict(dill.Pickler.dispatch.copy())\n\n\ndef dump(obj, file):\n \"\"\"pickle an object to a file\"\"\"\n Pickler(file).dump(obj)\n return\n\n\ndef dumps(obj):\n \"\"\"pickle an object to a string\"\"\"\n file = StringIO()\n dump(obj, file)\n return file.getvalue()\n\n\ndef pklregister(t):\n def proxy(func):\n Pickler.dispatch[t] = func\n return func\n\n return proxy\n\n\n@pklregister(CodeType)\ndef save_code(pickler, obj):\n \"\"\"\n From dill._dill.save_code\n This is a modified version that removes the origin (filename + line no.)\n of functions created in notebooks or shells for example.\n \"\"\"\n dill._dill.log.info(\"Co: %s\" % obj)\n # Filenames of functions created in notebooks or shells start with '<'\n # ex: <ipython-input-13-9ed2afe61d25> for ipython, and <stdin> for shell\n # Only those two lines are different from the original implementation:\n co_filename = \"\" if obj.co_filename.startswith(\"<\") else obj.co_filename\n co_firstlineno = 1 if obj.co_filename.startswith(\"<\") else obj.co_firstlineno\n # The rest is the same as in the original dill implementation\n if dill._dill.PY3:\n if hasattr(obj, \"co_posonlyargcount\"):\n args = (\n obj.co_argcount,\n obj.co_posonlyargcount,\n obj.co_kwonlyargcount,\n obj.co_nlocals,\n obj.co_stacksize,\n obj.co_flags,\n obj.co_code,\n obj.co_consts,\n obj.co_names,\n obj.co_varnames,\n co_filename,\n obj.co_name,\n co_firstlineno,\n obj.co_lnotab,\n obj.co_freevars,\n obj.co_cellvars,\n )\n else:\n args = (\n obj.co_argcount,\n obj.co_kwonlyargcount,\n obj.co_nlocals,\n obj.co_stacksize,\n obj.co_flags,\n obj.co_code,\n obj.co_consts,\n obj.co_names,\n obj.co_varnames,\n co_filename,\n obj.co_name,\n co_firstlineno,\n obj.co_lnotab,\n obj.co_freevars,\n obj.co_cellvars,\n )\n else:\n args = (\n obj.co_argcount,\n obj.co_nlocals,\n obj.co_stacksize,\n obj.co_flags,\n obj.co_code,\n obj.co_consts,\n obj.co_names,\n obj.co_varnames,\n co_filename,\n obj.co_name,\n co_firstlineno,\n obj.co_lnotab,\n obj.co_freevars,\n obj.co_cellvars,\n )\n pickler.save_reduce(CodeType, args, obj=obj)\n dill._dill.log.info(\"# Co\")\n return\n\n\ndef copyfunc(func):\n return types.FunctionType(func.__code__, func.__globals__, func.__name__, func.__defaults__, func.__closure__)\n" ]
[ [ "numpy.array" ] ]
InvokerLiu/DenseNet-Tensorflow
[ "8e171eb3f14a46cc68cdebd3d4db92b1376af698" ]
[ "nets/DenseNet56.py" ]
[ "#! /usr/bin/env python3\r\n# coding=utf-8\r\n\r\n# ================================================================\r\n#\r\n# Editor : PyCharm\r\n# File name : DenseNet56.py\r\n# Author : LiuBo\r\n# Created date: 2019-05-08 19:37\r\n# Description :\r\n#\r\n# ================================================================\r\n\r\nfrom core.layers import conv2d, avg_pool, fc_connect\r\nfrom core.blocks import dense_block, transition_block\r\nimport tensorflow as tf\r\n\r\n\r\nclass DenseNet56(object):\r\n def __init__(self, dense_block_num=3, growth_rate=12, filter_num=32, reduction=0.0,\r\n class_num=6, input_size=56, channels=3, training=True, name=\"dense_net56\",\r\n train_summary_dir=\"\", test_summary_dir=\"\"):\r\n \"\"\"\r\n :param dense_block_num:\r\n :param growth_rate:\r\n :param filter_num:\r\n :param reduction:\r\n :param class_num:\r\n :param input_size:\r\n :param channels:\r\n :param training:\r\n :param name:\r\n :param train_summary_dir:\r\n :param test_summary_dir:\r\n \"\"\"\r\n self.dense_block_num = dense_block_num\r\n self.growth_rate = growth_rate\r\n self.filter_num = filter_num\r\n self.reduction = reduction\r\n self.class_num = class_num\r\n self.input_size = input_size\r\n self.channels = channels\r\n self.layers_num = [3, 6, 4]\r\n self.compression = 1 - reduction\r\n self.training = training\r\n self.deep_features = None\r\n with tf.variable_scope(name):\r\n self.__add_placeholders()\r\n self.__Y = self.__build_graph()\r\n\r\n if training:\r\n self.__loss, self.__accuracy, self.__train_step = self.__build_training_graph()\r\n tf.summary.scalar(\"loss\", self.__loss)\r\n tf.summary.scalar(\"accuracy\", self.__accuracy)\r\n self.__writer_train = tf.summary.FileWriter(train_summary_dir)\r\n self.__writer_test = tf.summary.FileWriter(test_summary_dir)\r\n self.__write_op = tf.summary.merge_all()\r\n else:\r\n self.__loss, self.__accuracy, self.__train_step = self.__build_inference_graph()\r\n self.__saver = tf.train.Saver(max_to_keep=3)\r\n\r\n def __add_placeholders(self):\r\n \"\"\"\r\n :return:\r\n \"\"\"\r\n self.__X = tf.placeholder(tf.float32, [None, self.input_size, self.input_size, self.channels], name=\"input_X\")\r\n self.__Y_ = tf.placeholder(tf.float32, [None, self.class_num], name=\"ground_truth\")\r\n self.__is_training = tf.placeholder(tf.bool, name=\"is_training\")\r\n self.__iter = tf.placeholder(tf.int32, name=\"iteration\")\r\n self.__keep_prob = tf.placeholder(tf.float32, name=\"keep_prob\")\r\n self.__lr = tf.placeholder(tf.float32, name=\"learn_rate\")\r\n\r\n def __build_graph(self):\r\n \"\"\"\r\n :return:\r\n \"\"\"\r\n x = conv2d(self.__X, kernel_size=3, stride=1, filter_num=self.filter_num, padding=\"SAME\", name=\"conv1\")\r\n x = tf.layers.batch_normalization(x, training=self.__is_training)\r\n x = tf.nn.relu(x)\r\n\r\n for block_idx in range(self.dense_block_num - 1):\r\n dense_block_name = \"dense_block\" + str(block_idx + 1)\r\n transition_block_name = \"transition_block\" + str(block_idx + 1)\r\n x, filter_num = dense_block(x, self.layers_num[block_idx], self.filter_num,\r\n self.growth_rate, training=self.__is_training,\r\n name=dense_block_name, keep_prob=self.__keep_prob)\r\n x = transition_block(x, self.filter_num, training=self.__is_training,\r\n name=transition_block_name, keep_prob=self.__keep_prob,\r\n compression=self.compression)\r\n\r\n self.filter_num = int(self.filter_num * self.compression)\r\n dense_block_name = \"dense_block\" + str(self.dense_block_num)\r\n x = conv2d(x, kernel_size=3, stride=1, filter_num=self.filter_num, padding=\"VALID\", name=\"conv2\")\r\n x = tf.layers.batch_normalization(x, training=self.__is_training)\r\n x = tf.nn.relu(x)\r\n x, filter_num = dense_block(x, self.layers_num[-1], self.filter_num, self.growth_rate,\r\n training=self.__is_training, name=dense_block_name,\r\n keep_prob=self.__keep_prob)\r\n\r\n x = tf.layers.batch_normalization(x, training=self.__is_training)\r\n x = tf.nn.relu(x)\r\n x = conv2d(x, kernel_size=3, stride=1, filter_num=self.filter_num, padding=\"VALID\", name=\"conv3\")\r\n x = tf.layers.batch_normalization(x, training=self.__is_training)\r\n x = tf.nn.relu(x)\r\n x = conv2d(x, kernel_size=3, stride=1, filter_num=self.filter_num, padding=\"VALID\", name=\"conv4\")\r\n x = tf.layers.batch_normalization(x, training=self.__is_training)\r\n x = tf.nn.relu(x)\r\n self.deep_features = x\r\n pool_size = x.get_shape()[1]\r\n x = avg_pool(x, kernel_size=pool_size, stride=1, padding=\"VALID\", name=\"avg_pool\")\r\n\r\n input_dim = x.get_shape()[-1]\r\n x = tf.reshape(x, [-1, input_dim])\r\n\r\n x = fc_connect(x, self.class_num, name=\"fc_connect\")\r\n x = tf.nn.softmax(x)\r\n return x\r\n\r\n def __build_training_graph(self):\r\n \"\"\"\r\n :return:\r\n \"\"\"\r\n loss = tf.reduce_mean(-tf.reduce_sum(self.__Y_ * tf.log(self.__Y), reduction_indices=[1]))\r\n correct_prediction = tf.equal(tf.argmax(self.__Y, 1), tf.argmax(self.__Y_, 1))\r\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\r\n opt = tf.train.AdamOptimizer(learning_rate=self.__lr)\r\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\r\n with tf.control_dependencies(update_ops):\r\n train_step = opt.minimize(loss)\r\n return loss, accuracy, train_step\r\n\r\n def __build_inference_graph(self):\r\n \"\"\"\r\n :return:\r\n \"\"\"\r\n loss = tf.reduce_mean(-tf.reduce_sum(self.__Y_ * tf.log(self.__Y), reduction_indices=[1]))\r\n correct_prediction = tf.equal(tf.argmax(self.__Y, 1), tf.argmax(self.__Y_, 1))\r\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\r\n return loss, accuracy, None\r\n\r\n def train_op(self, sess, x, y, iteration, learn_rate, keep_prob=1.0):\r\n \"\"\"\r\n :param sess:\r\n :param x:\r\n :param y:\r\n :param iteration:\r\n :param learn_rate:\r\n :param keep_prob:\r\n :return:\r\n \"\"\"\r\n _, write_data, acc, loss = sess.run([self.__train_step, self.__write_op, self.__accuracy, self.__loss],\r\n feed_dict={self.__X: x,\r\n self.__Y_: y,\r\n self.__iter: iteration,\r\n self.__is_training: True,\r\n self.__lr: learn_rate,\r\n self.__keep_prob: keep_prob})\r\n self.__writer_train.add_summary(write_data, global_step=iteration)\r\n self.__writer_train.flush()\r\n return acc, loss\r\n\r\n def eval_op(self, sess, x, y, iteration=None):\r\n \"\"\"\r\n :param sess:\r\n :param x:\r\n :param y:\r\n :param iteration: the number of iteration, if train, iteration is not None, if inference, iteration is None\r\n :return:\r\n \"\"\"\r\n if iteration is None:\r\n it = 0\r\n else:\r\n it = iteration\r\n\r\n acc, loss = sess.run([self.__accuracy, self.__loss],\r\n feed_dict={self.__X: x,\r\n self.__Y_: y,\r\n self.__iter: it,\r\n self.__is_training: False,\r\n self.__keep_prob: 1.0})\r\n\r\n if self.training:\r\n write_data = sess.run(self.__write_op,\r\n feed_dict={self.__X: x,\r\n self.__Y_: y,\r\n self.__iter: it,\r\n self.__is_training: False,\r\n self.__keep_prob: 1.0})\r\n self.__writer_test.add_summary(write_data, global_step=it)\r\n self.__writer_test.flush()\r\n\r\n return acc, loss\r\n\r\n def infer_op(self, sess, x):\r\n \"\"\"\r\n :param sess:\r\n :param x:\r\n :return:\r\n \"\"\"\r\n y = sess.run(self.__Y, feed_dict={self.__X: x,\r\n self.__iter: 0,\r\n self.__is_training: False,\r\n self.__keep_prob: 1.0})\r\n return y\r\n\r\n def save(self, sess, path, global_step):\r\n \"\"\"\r\n :param sess:\r\n :param path:\r\n :param global_step:\r\n :return:\r\n \"\"\"\r\n self.__saver.save(sess, path, global_step=global_step)\r\n\r\n def restore(self, sess, path):\r\n \"\"\"\r\n :param sess:\r\n :param path:\r\n :return:\r\n \"\"\"\r\n self.__saver.restore(sess, path)\r\n\r\n def get_deep_features(self, sess, input_data):\r\n deep_features = sess.run(self.deep_features, feed_dict={self.__X: input_data,\r\n self.__keep_prob: 1.0,\r\n self.__iter: 0,\r\n self.__is_training: False})\r\n return deep_features\r\n\r\n\r\nif __name__ == \"__main__\":\r\n dense_net = DenseNet56()\r\n variable = [v for v in tf.trainable_variables()]\r\n parm_cnt = 0\r\n for v in variable:\r\n print(\" \", v.name, v.get_shape())\r\n parm_cnt_v = 1\r\n for i in v.get_shape().as_list():\r\n parm_cnt_v *= i\r\n parm_cnt += parm_cnt_v\r\n print(\"[*] Model parameter size: %.4fM\" % (parm_cnt / 1024 / 1024))\r\n" ]
[ [ "tensorflow.nn.relu", "tensorflow.nn.softmax", "tensorflow.layers.batch_normalization", "tensorflow.summary.FileWriter", "tensorflow.control_dependencies", "tensorflow.get_collection", "tensorflow.reshape", "tensorflow.argmax", "tensorflow.placeholder", "tensorflow.cast", "tensorflow.trainable_variables", "tensorflow.summary.merge_all", "tensorflow.log", "tensorflow.train.AdamOptimizer", "tensorflow.variable_scope", "tensorflow.train.Saver", "tensorflow.summary.scalar" ] ]
TomNicholas/pint-xarray
[ "6ee1bf9aff0c6bef51bde2ecf6a62660a9ed6f39" ]
[ "pint_xarray/tests/test_accessors.py" ]
[ "import numpy as np\nimport pint\nimport pytest\nimport xarray as xr\nfrom numpy.testing import assert_array_equal\nfrom pint import Unit, UnitRegistry\n\nfrom .. import accessors, conversion\nfrom .utils import (\n assert_equal,\n assert_identical,\n assert_units_equal,\n raises_regex,\n requires_bottleneck,\n requires_dask_array,\n requires_scipy,\n)\n\npytestmark = [\n pytest.mark.filterwarnings(\"error::pint.UnitStrippedWarning\"),\n]\n\n# make sure scalars are converted to 0d arrays so quantities can\n# always be treated like ndarrays\nunit_registry = UnitRegistry(force_ndarray=True)\nQuantity = unit_registry.Quantity\n\nnan = np.nan\n\n\ndef assert_all_str_or_none(mapping):\n __tracebackhide__ = True\n\n compared = {\n key: isinstance(value, str) or value is None for key, value in mapping.items()\n }\n not_passing = {key: value for key, value in mapping.items() if not compared[key]}\n check = all(compared.values())\n\n assert check, f\"Not all values are str or None: {not_passing}\"\n\n\[email protected]\ndef example_unitless_da():\n array = np.linspace(0, 10, 20)\n x = np.arange(20)\n u = np.linspace(0, 1, 20)\n da = xr.DataArray(\n data=array,\n dims=\"x\",\n coords={\"x\": (\"x\", x), \"u\": (\"x\", u, {\"units\": \"hour\"})},\n attrs={\"units\": \"m\"},\n )\n return da\n\n\[email protected]()\ndef example_quantity_da():\n array = np.linspace(0, 10, 20) * unit_registry.m\n x = np.arange(20)\n u = np.linspace(0, 1, 20) * unit_registry.hour\n return xr.DataArray(data=array, dims=\"x\", coords={\"x\": (\"x\", x), \"u\": (\"x\", u)})\n\n\nclass TestQuantifyDataArray:\n def test_attach_units_from_str(self, example_unitless_da):\n orig = example_unitless_da\n result = orig.pint.quantify(\"m\")\n assert_array_equal(result.data.magnitude, orig.data)\n # TODO better comparisons for when you can't access the unit_registry?\n assert str(result.data.units) == \"meter\"\n\n def test_attach_units_given_registry(self, example_unitless_da):\n orig = example_unitless_da\n ureg = UnitRegistry(force_ndarray=True)\n result = orig.pint.quantify(\"m\", unit_registry=ureg)\n assert_array_equal(result.data.magnitude, orig.data)\n assert result.data.units == ureg.Unit(\"m\")\n\n def test_attach_units_from_attrs(self, example_unitless_da):\n orig = example_unitless_da\n result = orig.pint.quantify()\n assert_array_equal(result.data.magnitude, orig.data)\n assert str(result.data.units) == \"meter\"\n\n remaining_attrs = conversion.extract_unit_attributes(result)\n assert {k: v for k, v in remaining_attrs.items() if v is not None} == {}\n\n def test_attach_units_given_unit_objs(self, example_unitless_da):\n orig = example_unitless_da\n ureg = UnitRegistry(force_ndarray=True)\n result = orig.pint.quantify(ureg.Unit(\"m\"), unit_registry=ureg)\n assert_array_equal(result.data.magnitude, orig.data)\n assert result.data.units == ureg.Unit(\"m\")\n\n def test_error_when_already_units(self, example_quantity_da):\n da = example_quantity_da\n with raises_regex(ValueError, \"already has units\"):\n da.pint.quantify()\n\n def test_error_on_nonsense_units(self, example_unitless_da):\n da = example_unitless_da\n with pytest.raises(ValueError, match=str(da.name)):\n da.pint.quantify(units=\"aecjhbav\")\n\n def test_error_on_nonsense_units_attrs(self, example_unitless_da):\n da = example_unitless_da\n da.attrs[\"units\"] = \"aecjhbav\"\n with pytest.raises(\n ValueError, match=rf\"{da.name}: {da.attrs['units']} \\(attribute\\)\"\n ):\n da.pint.quantify()\n\n def test_parse_integer_inverse(self):\n # Regression test for issue #40\n da = xr.DataArray([10], attrs={\"units\": \"m^-1\"})\n result = da.pint.quantify()\n assert result.pint.units == Unit(\"1 / meter\")\n\n\[email protected](\"formatter\", (\"\", \"P\", \"C\"))\[email protected](\"flags\", (\"\", \"~\", \"#\", \"~#\"))\ndef test_units_to_str_or_none(formatter, flags):\n unit_format = f\"{{:{flags}{formatter}}}\"\n unit_attrs = {None: \"m\", \"a\": \"s\", \"b\": \"degC\", \"c\": \"degF\", \"d\": \"degK\"}\n units = {key: unit_registry.Unit(value) for key, value in unit_attrs.items()}\n\n expected = {key: unit_format.format(value) for key, value in units.items()}\n actual = accessors.units_to_str_or_none(units, unit_format)\n\n assert expected == actual\n assert units == {key: unit_registry.Unit(value) for key, value in actual.items()}\n\n expected = {None: None}\n assert expected == accessors.units_to_str_or_none(expected, unit_format)\n\n\nclass TestDequantifyDataArray:\n def test_strip_units(self, example_quantity_da):\n result = example_quantity_da.pint.dequantify()\n assert isinstance(result.data, np.ndarray)\n assert isinstance(result.coords[\"x\"].data, np.ndarray)\n\n def test_attrs_reinstated(self, example_quantity_da):\n da = example_quantity_da\n result = da.pint.dequantify()\n\n units = conversion.extract_units(da)\n attrs = conversion.extract_unit_attributes(result)\n\n assert units == attrs\n assert_all_str_or_none(attrs)\n\n def test_roundtrip_data(self, example_unitless_da):\n orig = example_unitless_da\n quantified = orig.pint.quantify()\n result = quantified.pint.dequantify()\n assert_equal(result, orig)\n\n\nclass TestPropertiesDataArray:\n def test_magnitude_getattr(self, example_quantity_da):\n da = example_quantity_da\n actual = da.pint.magnitude\n assert not isinstance(actual, Quantity)\n\n def test_magnitude_getattr_unitless(self, example_unitless_da):\n da = example_unitless_da\n xr.testing.assert_duckarray_equal(da.pint.magnitude, da.data)\n\n def test_units_getattr(self, example_quantity_da):\n da = example_quantity_da\n actual = da.pint.units\n assert isinstance(actual, Unit)\n assert actual == unit_registry.m\n\n def test_units_setattr(self, example_quantity_da):\n da = example_quantity_da\n with pytest.raises(ValueError):\n da.pint.units = \"s\"\n\n def test_units_getattr_unitless(self, example_unitless_da):\n da = example_unitless_da\n assert da.pint.units is None\n\n def test_units_setattr_unitless(self, example_unitless_da):\n da = example_unitless_da\n da.pint.units = unit_registry.s\n assert da.pint.units == unit_registry.s\n\n\[email protected]()\ndef example_unitless_ds():\n users = np.linspace(0, 10, 20)\n funds = np.logspace(0, 10, 20)\n t = np.arange(20)\n ds = xr.Dataset(\n data_vars={\"users\": ([\"t\"], users), \"funds\": ([\"t\"], funds)}, coords={\"t\": t}\n )\n ds[\"users\"].attrs[\"units\"] = \"\"\n ds[\"funds\"].attrs[\"units\"] = \"pound\"\n return ds\n\n\[email protected]()\ndef example_quantity_ds():\n users = np.linspace(0, 10, 20) * unit_registry.dimensionless\n funds = np.logspace(0, 10, 20) * unit_registry.pound\n t = np.arange(20)\n ds = xr.Dataset(\n data_vars={\"users\": ([\"t\"], users), \"funds\": ([\"t\"], funds)}, coords={\"t\": t}\n )\n return ds\n\n\nclass TestQuantifyDataSet:\n def test_attach_units_from_str(self, example_unitless_ds):\n orig = example_unitless_ds\n result = orig.pint.quantify()\n assert_array_equal(result[\"users\"].data.magnitude, orig[\"users\"].data)\n assert str(result[\"users\"].data.units) == \"dimensionless\"\n\n def test_attach_units_given_registry(self, example_unitless_ds):\n orig = example_unitless_ds\n orig[\"users\"].attrs.clear()\n result = orig.pint.quantify(\n {\"users\": \"dimensionless\"}, unit_registry=unit_registry\n )\n assert_array_equal(result[\"users\"].data.magnitude, orig[\"users\"].data)\n assert str(result[\"users\"].data.units) == \"dimensionless\"\n\n def test_attach_units_from_attrs(self, example_unitless_ds):\n orig = example_unitless_ds\n orig[\"users\"].attrs.clear()\n result = orig.pint.quantify({\"users\": \"dimensionless\"})\n assert_array_equal(result[\"users\"].data.magnitude, orig[\"users\"].data)\n assert str(result[\"users\"].data.units) == \"dimensionless\"\n\n remaining_attrs = conversion.extract_unit_attributes(result)\n assert {k: v for k, v in remaining_attrs.items() if v is not None} == {}\n\n def test_attach_units_given_unit_objs(self, example_unitless_ds):\n orig = example_unitless_ds\n orig[\"users\"].attrs.clear()\n dimensionless = unit_registry.Unit(\"dimensionless\")\n result = orig.pint.quantify({\"users\": dimensionless})\n assert_array_equal(result[\"users\"].data.magnitude, orig[\"users\"].data)\n assert str(result[\"users\"].data.units) == \"dimensionless\"\n\n def test_error_when_already_units(self, example_quantity_ds):\n with raises_regex(ValueError, \"already has units\"):\n example_quantity_ds.pint.quantify({\"funds\": \"pounds\"})\n\n def test_error_on_nonsense_units(self, example_unitless_ds):\n ds = example_unitless_ds\n with pytest.raises(ValueError):\n ds.pint.quantify(units={\"users\": \"aecjhbav\"})\n\n def test_error_on_nonsense_units_attrs(self, example_unitless_ds):\n ds = example_unitless_ds\n ds.users.attrs[\"units\"] = \"aecjhbav\"\n with pytest.raises(\n ValueError, match=rf\"'users': {ds.users.attrs['units']} \\(attribute\\)\"\n ):\n ds.pint.quantify()\n\n def test_error_indicates_problematic_variable(self, example_unitless_ds):\n ds = example_unitless_ds\n with pytest.raises(ValueError, match=\"'users'\"):\n ds.pint.quantify(units={\"users\": \"aecjhbav\"})\n\n\nclass TestDequantifyDataSet:\n def test_strip_units(self, example_quantity_ds):\n result = example_quantity_ds.pint.dequantify()\n\n assert all(\n isinstance(var.data, np.ndarray) for var in result.variables.values()\n )\n\n def test_attrs_reinstated(self, example_quantity_ds):\n ds = example_quantity_ds\n result = ds.pint.dequantify()\n\n units = conversion.extract_units(ds)\n # workaround for Unit(\"dimensionless\") != str(Unit(\"dimensionless\"))\n units = {\n key: str(value) if isinstance(value, Unit) else value\n for key, value in units.items()\n }\n\n attrs = conversion.extract_unit_attributes(result)\n\n assert units == attrs\n assert_all_str_or_none(attrs)\n\n def test_roundtrip_data(self, example_unitless_ds):\n orig = example_unitless_ds\n quantified = orig.pint.quantify()\n\n result = quantified.pint.dequantify()\n assert_equal(result, orig)\n\n result = quantified.pint.dequantify().pint.quantify()\n assert_equal(quantified, result)\n\n\[email protected](\n [\"obj\", \"units\", \"expected\", \"error\"],\n (\n pytest.param(\n xr.Dataset(\n {\"a\": (\"x\", Quantity([0, 1], \"m\")), \"b\": (\"x\", Quantity([2, 4], \"s\"))}\n ),\n {\"a\": \"mm\", \"b\": \"ms\"},\n xr.Dataset(\n {\n \"a\": (\"x\", Quantity([0, 1000], \"mm\")),\n \"b\": (\"x\", Quantity([2000, 4000], \"ms\")),\n }\n ),\n None,\n id=\"Dataset-compatible units-data\",\n ),\n pytest.param(\n xr.Dataset(\n {\"a\": (\"x\", Quantity([0, 1], \"km\")), \"b\": (\"x\", Quantity([2, 4], \"cm\"))}\n ),\n \"m\",\n xr.Dataset(\n {\n \"a\": (\"x\", Quantity([0, 1000], \"m\")),\n \"b\": (\"x\", Quantity([0.02, 0.04], \"m\")),\n }\n ),\n None,\n id=\"Dataset-compatible units-data-str\",\n ),\n pytest.param(\n xr.Dataset(\n {\"a\": (\"x\", Quantity([0, 1], \"m\")), \"b\": (\"x\", Quantity([2, 4], \"s\"))}\n ),\n {\"a\": \"ms\", \"b\": \"mm\"},\n None,\n ValueError,\n id=\"Dataset-incompatible units-data\",\n ),\n pytest.param(\n xr.Dataset(coords={\"x\": (\"x\", [2, 4], {\"units\": Unit(\"s\")})}),\n {\"x\": \"ms\"},\n xr.Dataset(coords={\"x\": (\"x\", [2000, 4000], {\"units\": Unit(\"ms\")})}),\n None,\n id=\"Dataset-compatible units-dims\",\n ),\n pytest.param(\n xr.Dataset(coords={\"x\": (\"x\", [2, 4], {\"units\": Unit(\"s\")})}),\n {\"x\": \"mm\"},\n None,\n ValueError,\n id=\"Dataset-incompatible units-dims\",\n ),\n pytest.param(\n xr.DataArray(Quantity([0, 1], \"m\"), dims=\"x\"),\n {None: \"mm\"},\n xr.DataArray(Quantity([0, 1000], \"mm\"), dims=\"x\"),\n None,\n id=\"DataArray-compatible units-data\",\n ),\n pytest.param(\n xr.DataArray(Quantity([0, 1], \"m\"), dims=\"x\"),\n \"mm\",\n xr.DataArray(Quantity([0, 1000], \"mm\"), dims=\"x\"),\n None,\n id=\"DataArray-compatible units-data-str\",\n ),\n pytest.param(\n xr.DataArray(Quantity([0, 1], \"m\"), dims=\"x\", name=\"a\"),\n {\"a\": \"mm\"},\n xr.DataArray(Quantity([0, 1000], \"mm\"), dims=\"x\", name=\"a\"),\n None,\n id=\"DataArray-compatible units-data-by name\",\n ),\n pytest.param(\n xr.DataArray(Quantity([0, 1], \"m\"), dims=\"x\"),\n {None: \"ms\"},\n None,\n ValueError,\n id=\"DataArray-incompatible units-data\",\n ),\n pytest.param(\n xr.DataArray(\n [0, 1], dims=\"x\", coords={\"x\": (\"x\", [2, 4], {\"units\": Unit(\"s\")})}\n ),\n {\"x\": \"ms\"},\n xr.DataArray(\n [0, 1],\n dims=\"x\",\n coords={\"x\": (\"x\", [2000, 4000], {\"units\": Unit(\"ms\")})},\n ),\n None,\n id=\"DataArray-compatible units-dims\",\n ),\n pytest.param(\n xr.DataArray(\n [0, 1], dims=\"x\", coords={\"x\": (\"x\", [2, 4], {\"units\": Unit(\"s\")})}\n ),\n {\"x\": \"mm\"},\n None,\n ValueError,\n id=\"DataArray-incompatible units-dims\",\n ),\n ),\n)\ndef test_to(obj, units, expected, error):\n if error is not None:\n with pytest.raises(error):\n obj.pint.to(units)\n else:\n actual = obj.pint.to(units)\n\n assert_units_equal(actual, expected)\n assert_identical(actual, expected)\n\n\[email protected](\n [\"obj\", \"indexers\", \"expected\", \"error\"],\n (\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n {\"x\": Quantity([10, 30], \"dm\"), \"y\": Quantity([60], \"s\")},\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n None,\n id=\"Dataset-identical units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n {\"x\": Quantity([1, 3], \"m\"), \"y\": Quantity([1], \"min\")},\n xr.Dataset(\n {\n \"x\": (\"x\", [1, 3], {\"units\": unit_registry.Unit(\"m\")}),\n \"y\": (\"y\", [1], {\"units\": unit_registry.Unit(\"min\")}),\n }\n ),\n None,\n id=\"Dataset-compatible units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n {\"x\": Quantity([1, 3], \"s\"), \"y\": Quantity([1], \"m\")},\n None,\n KeyError,\n id=\"Dataset-incompatible units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([10, 30], \"dm\"), \"y\": Quantity([60], \"s\")},\n xr.DataArray(\n [[0], [4]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n None,\n id=\"DataArray-identical units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([1, 3], \"m\"), \"y\": Quantity([1], \"min\")},\n xr.DataArray(\n [[0], [4]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [1, 3], {\"units\": unit_registry.Unit(\"m\")}),\n \"y\": (\"y\", [1], {\"units\": unit_registry.Unit(\"min\")}),\n },\n ),\n None,\n id=\"DataArray-compatible units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([10, 30], \"s\"), \"y\": Quantity([60], \"m\")},\n None,\n KeyError,\n id=\"DataArray-incompatible units\",\n ),\n ),\n)\ndef test_sel(obj, indexers, expected, error):\n if error is not None:\n with pytest.raises(error):\n obj.pint.sel(indexers)\n else:\n actual = obj.pint.sel(indexers)\n assert_units_equal(actual, expected)\n assert_identical(actual, expected)\n\n\[email protected](\n [\"obj\", \"indexers\", \"expected\", \"error\"],\n (\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n {\"x\": Quantity([10, 30], \"dm\"), \"y\": Quantity([60], \"s\")},\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n None,\n id=\"Dataset-identical units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n {\"x\": Quantity([1, 3], \"m\"), \"y\": Quantity([1], \"min\")},\n xr.Dataset(\n {\n \"x\": (\"x\", [1, 3], {\"units\": unit_registry.Unit(\"m\")}),\n \"y\": (\"y\", [1], {\"units\": unit_registry.Unit(\"min\")}),\n }\n ),\n None,\n id=\"Dataset-compatible units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n {\"x\": Quantity([1, 3], \"s\"), \"y\": Quantity([1], \"m\")},\n None,\n KeyError,\n id=\"Dataset-incompatible units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([10, 30], \"dm\"), \"y\": Quantity([60], \"s\")},\n xr.DataArray(\n [[0], [4]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n None,\n id=\"DataArray-identical units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([1, 3], \"m\"), \"y\": Quantity([1], \"min\")},\n xr.DataArray(\n [[0], [4]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [1, 3], {\"units\": unit_registry.Unit(\"m\")}),\n \"y\": (\"y\", [1], {\"units\": unit_registry.Unit(\"min\")}),\n },\n ),\n None,\n id=\"DataArray-compatible units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([10, 30], \"s\"), \"y\": Quantity([60], \"m\")},\n None,\n KeyError,\n id=\"DataArray-incompatible units\",\n ),\n ),\n)\ndef test_loc(obj, indexers, expected, error):\n if error is not None:\n with pytest.raises(error):\n obj.pint.loc[indexers]\n else:\n actual = obj.pint.loc[indexers]\n assert_units_equal(actual, expected)\n assert_identical(actual, expected)\n\n\[email protected](\n [\"obj\", \"indexers\", \"values\", \"expected\", \"error\"],\n (\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([10, 30], \"dm\"), \"y\": Quantity([60], \"s\")},\n [[-1], [-2]],\n xr.DataArray(\n [[-1, 1], [2, 3], [-2, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n None,\n id=\"coords-identical units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([1, 3], \"m\"), \"y\": Quantity([1], \"min\")},\n [[-1], [-2]],\n xr.DataArray(\n [[-1, 1], [2, 3], [-2, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n None,\n id=\"coords-compatible units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([1, 3], \"s\"), \"y\": Quantity([1], \"m\")},\n [[-1], [-2]],\n None,\n KeyError,\n id=\"coords-incompatible units\",\n ),\n pytest.param(\n xr.DataArray(\n Quantity([[0, 1], [2, 3], [4, 5]], \"m\"),\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([10, 30], \"dm\"), \"y\": Quantity([60], \"s\")},\n Quantity([[-1], [-2]], \"m\"),\n xr.DataArray(\n Quantity([[-1, 1], [2, 3], [-2, 5]], \"m\"),\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n None,\n id=\"data-identical units\",\n ),\n pytest.param(\n xr.DataArray(\n Quantity([[0, 1], [2, 3], [4, 5]], \"m\"),\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([10, 30], \"dm\"), \"y\": Quantity([60], \"s\")},\n Quantity([[-1], [-2]], \"km\"),\n xr.DataArray(\n Quantity([[-1000, 1], [2, 3], [-2000, 5]], \"m\"),\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n None,\n id=\"data-compatible units\",\n ),\n pytest.param(\n xr.DataArray(\n Quantity([[0, 1], [2, 3], [4, 5]], \"m\"),\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([10, 30], \"dm\"), \"y\": Quantity([60], \"s\")},\n Quantity([[-1], [-2]], \"s\"),\n None,\n pint.DimensionalityError,\n id=\"data-incompatible units\",\n ),\n ),\n)\ndef test_loc_setitem(obj, indexers, values, expected, error):\n if error is not None:\n with pytest.raises(error):\n obj.pint.loc[indexers] = values\n else:\n obj.pint.loc[indexers] = values\n assert_units_equal(obj, expected)\n assert_identical(obj, expected)\n\n\[email protected](\n [\"obj\", \"indexers\", \"expected\", \"error\"],\n (\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n {\"x\": Quantity([10, 30], \"dm\"), \"y\": Quantity([60], \"s\")},\n xr.Dataset(\n {\n \"x\": (\"x\", [20], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n None,\n id=\"Dataset-identical units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n {\"x\": Quantity([1, 3], \"m\"), \"y\": Quantity([1], \"min\")},\n xr.Dataset(\n {\n \"x\": (\"x\", [20], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n None,\n id=\"Dataset-compatible units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n {\"x\": Quantity([1, 3], \"s\"), \"y\": Quantity([1], \"m\")},\n None,\n KeyError,\n id=\"Dataset-incompatible units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n {\"x\": Quantity([10, 30], \"m\"), \"y\": Quantity([60], \"min\")},\n None,\n KeyError,\n id=\"Dataset-compatible units-not found\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([10, 30], \"dm\"), \"y\": Quantity([60], \"s\")},\n xr.DataArray(\n [[3]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [20], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n None,\n id=\"DataArray-identical units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([1, 3], \"m\"), \"y\": Quantity([1], \"min\")},\n xr.DataArray(\n [[3]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [20], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n None,\n id=\"DataArray-compatible units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([10, 30], \"s\"), \"y\": Quantity([60], \"m\")},\n None,\n KeyError,\n id=\"DataArray-incompatible units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([10, 30], \"m\"), \"y\": Quantity([60], \"min\")},\n None,\n KeyError,\n id=\"DataArray-compatible units-not found\",\n ),\n ),\n)\ndef test_drop_sel(obj, indexers, expected, error):\n if error is not None:\n with pytest.raises(error):\n obj.pint.drop_sel(indexers)\n else:\n actual = obj.pint.drop_sel(indexers)\n assert_units_equal(actual, expected)\n assert_identical(actual, expected)\n\n\n@requires_dask_array\[email protected](\n \"obj\",\n (\n pytest.param(\n xr.Dataset(\n {\"a\": (\"x\", np.linspace(0, 1, 11))},\n coords={\"u\": (\"x\", np.arange(11))},\n ),\n id=\"Dataset-no units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"a\": (\n \"x\",\n Quantity(np.linspace(0, 1, 11), \"m\"),\n )\n },\n coords={\n \"u\": (\n \"x\",\n Quantity(np.arange(11), \"m\"),\n )\n },\n ),\n id=\"Dataset-units\",\n ),\n pytest.param(\n xr.DataArray(\n np.linspace(0, 1, 11),\n coords={\n \"u\": (\n \"x\",\n np.arange(11),\n )\n },\n dims=\"x\",\n ),\n id=\"DataArray-no units\",\n ),\n pytest.param(\n xr.DataArray(\n Quantity(np.linspace(0, 1, 11), \"m\"),\n coords={\n \"u\": (\n \"x\",\n Quantity(np.arange(11), \"m\"),\n )\n },\n dims=\"x\",\n ),\n id=\"DataArray-units\",\n ),\n ),\n)\ndef test_chunk(obj):\n actual = obj.pint.chunk({\"x\": 2})\n\n expected = (\n obj.pint.dequantify().chunk({\"x\": 2}).pint.quantify(unit_registry=unit_registry)\n )\n\n assert_units_equal(actual, expected)\n assert_identical(actual, expected)\n\n\[email protected](\n [\"obj\", \"indexers\", \"expected\", \"error\"],\n (\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n {\"x\": Quantity([10, 30, 50], \"dm\"), \"y\": Quantity([0, 120, 240], \"s\")},\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 30, 50], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [0, 120, 240], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n None,\n id=\"Dataset-identical units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n {\"x\": Quantity([0, 1, 3, 5], \"m\"), \"y\": Quantity([0, 2, 4], \"min\")},\n xr.Dataset(\n {\n \"x\": (\"x\", [0, 1, 3, 5], {\"units\": unit_registry.Unit(\"m\")}),\n \"y\": (\"y\", [0, 2, 4], {\"units\": unit_registry.Unit(\"min\")}),\n }\n ),\n None,\n id=\"Dataset-compatible units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n {\"x\": Quantity([1, 3], \"s\"), \"y\": Quantity([1], \"m\")},\n None,\n ValueError,\n id=\"Dataset-incompatible units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"a\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"b\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n {\"a\": Quantity([1, 3], \"s\"), \"b\": Quantity([1], \"m\")},\n None,\n ValueError,\n id=\"Dataset-incompatible units-invalid dims\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([10, 30, 50], \"dm\"), \"y\": Quantity([0, 240], \"s\")},\n xr.DataArray(\n [[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 30, 50], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [0, 240], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n None,\n id=\"DataArray-identical units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([1, 3, 5], \"m\"), \"y\": Quantity([0, 2], \"min\")},\n xr.DataArray(\n [[np.nan, 1], [np.nan, 5], [np.nan, np.nan]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [1, 3, 5], {\"units\": unit_registry.Unit(\"m\")}),\n \"y\": (\"y\", [0, 2], {\"units\": unit_registry.Unit(\"min\")}),\n },\n ),\n None,\n id=\"DataArray-compatible units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([10, 30], \"s\"), \"y\": Quantity([60], \"m\")},\n None,\n ValueError,\n id=\"DataArray-incompatible units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([10, 30], \"s\"), \"y\": Quantity([60], \"m\")},\n None,\n ValueError,\n id=\"DataArray-incompatible units-invalid dims\",\n ),\n ),\n)\ndef test_reindex(obj, indexers, expected, error):\n if error is not None:\n with pytest.raises(error):\n obj.pint.reindex(indexers)\n else:\n actual = obj.pint.reindex(indexers)\n assert_units_equal(actual, expected)\n assert_identical(actual, expected)\n\n\[email protected](\n [\"obj\", \"other\", \"expected\", \"error\"],\n (\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 30, 50], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [0, 120, 240], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 30, 50], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [0, 120, 240], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n None,\n id=\"Dataset-identical units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n xr.Dataset(\n {\n \"x\": (\"x\", [0, 1, 3, 5], {\"units\": unit_registry.Unit(\"m\")}),\n \"y\": (\"y\", [0, 2, 4], {\"units\": unit_registry.Unit(\"min\")}),\n }\n ),\n xr.Dataset(\n {\n \"x\": (\"x\", [0, 1, 3, 5], {\"units\": unit_registry.Unit(\"m\")}),\n \"y\": (\"y\", [0, 2, 4], {\"units\": unit_registry.Unit(\"min\")}),\n }\n ),\n None,\n id=\"Dataset-compatible units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n xr.Dataset(\n {\n \"x\": (\"x\", [1, 3], {\"units\": unit_registry.Unit(\"s\")}),\n \"y\": (\"y\", [1], {\"units\": unit_registry.Unit(\"m\")}),\n }\n ),\n None,\n ValueError,\n id=\"Dataset-incompatible units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 30, 50], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [0, 240], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n xr.DataArray(\n [[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 30, 50], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [0, 240], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n None,\n id=\"DataArray-identical units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n xr.Dataset(\n {\n \"x\": (\"x\", [1, 3, 5], {\"units\": unit_registry.Unit(\"m\")}),\n \"y\": (\"y\", [0, 2], {\"units\": unit_registry.Unit(\"min\")}),\n }\n ),\n xr.DataArray(\n [[np.nan, 1], [np.nan, 5], [np.nan, np.nan]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [1, 3, 5], {\"units\": unit_registry.Unit(\"m\")}),\n \"y\": (\"y\", [0, 2], {\"units\": unit_registry.Unit(\"min\")}),\n },\n ),\n None,\n id=\"DataArray-compatible units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 30], {\"units\": unit_registry.Unit(\"s\")}),\n \"y\": (\"y\", [60], {\"units\": unit_registry.Unit(\"m\")}),\n }\n ),\n None,\n ValueError,\n id=\"DataArray-incompatible units\",\n ),\n ),\n)\ndef test_reindex_like(obj, other, expected, error):\n if error is not None:\n with pytest.raises(error):\n obj.pint.reindex_like(other)\n else:\n actual = obj.pint.reindex_like(other)\n assert_units_equal(actual, expected)\n assert_identical(actual, expected)\n\n\n@requires_scipy\[email protected](\n [\"obj\", \"indexers\", \"expected\", \"error\"],\n (\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n {\"x\": Quantity([10, 30, 50], \"dm\"), \"y\": Quantity([0, 120, 240], \"s\")},\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 30, 50], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [0, 120, 240], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n None,\n id=\"Dataset-identical units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n {\"x\": Quantity([0, 1, 3, 5], \"m\"), \"y\": Quantity([0, 2, 4], \"min\")},\n xr.Dataset(\n {\n \"x\": (\"x\", [0, 1, 3, 5], {\"units\": unit_registry.Unit(\"m\")}),\n \"y\": (\"y\", [0, 2, 4], {\"units\": unit_registry.Unit(\"min\")}),\n }\n ),\n None,\n id=\"Dataset-compatible units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n {\"x\": Quantity([1, 3], \"s\"), \"y\": Quantity([1], \"m\")},\n None,\n ValueError,\n id=\"Dataset-incompatible units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"a\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"b\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n {\"a\": Quantity([1, 3], \"s\"), \"b\": Quantity([1], \"m\")},\n None,\n ValueError,\n id=\"Dataset-incompatible units-invalid dims\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"a\": ((\"x\", \"y\"), Quantity([[0, 1], [2, 3], [4, 5]], \"kg\")),\n \"x\": [10, 20, 30],\n \"y\": [60, 120],\n }\n ),\n {\n \"x\": [15, 25],\n \"y\": [75, 105],\n },\n xr.Dataset(\n {\n \"a\": ((\"x\", \"y\"), Quantity([[1.25, 1.75], [3.25, 3.75]], \"kg\")),\n \"x\": [15, 25],\n \"y\": [75, 105],\n }\n ),\n None,\n id=\"Dataset-data units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([10, 30, 50], \"dm\"), \"y\": Quantity([0, 240], \"s\")},\n xr.DataArray(\n [[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 30, 50], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [0, 240], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n None,\n id=\"DataArray-identical units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([1, 3, 5], \"m\"), \"y\": Quantity([0, 2], \"min\")},\n xr.DataArray(\n [[np.nan, 1], [np.nan, 5], [np.nan, np.nan]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [1, 3, 5], {\"units\": unit_registry.Unit(\"m\")}),\n \"y\": (\"y\", [0, 2], {\"units\": unit_registry.Unit(\"min\")}),\n },\n ),\n None,\n id=\"DataArray-compatible units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([10, 30], \"s\"), \"y\": Quantity([60], \"m\")},\n None,\n ValueError,\n id=\"DataArray-incompatible units\",\n ),\n pytest.param(\n xr.DataArray(\n Quantity([[0, 1], [2, 3], [4, 5]], \"kg\"),\n dims=(\"x\", \"y\"),\n coords={\n \"x\": [10, 20, 30],\n \"y\": [60, 120],\n },\n ),\n {\n \"x\": [15, 25],\n \"y\": [75, 105],\n },\n xr.DataArray(\n Quantity([[1.25, 1.75], [3.25, 3.75]], \"kg\"),\n dims=(\"x\", \"y\"),\n coords={\n \"x\": [15, 25],\n \"y\": [75, 105],\n },\n ),\n None,\n id=\"DataArray-data units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n {\"x\": Quantity([10, 30], \"s\"), \"y\": Quantity([60], \"m\")},\n None,\n ValueError,\n id=\"DataArray-incompatible units-invalid dims\",\n ),\n ),\n)\ndef test_interp(obj, indexers, expected, error):\n if error is not None:\n with pytest.raises(error):\n obj.pint.interp(indexers)\n else:\n actual = obj.pint.interp(indexers)\n assert_units_equal(actual, expected)\n assert_identical(actual, expected)\n\n\n@requires_scipy\[email protected](\n [\"obj\", \"other\", \"expected\", \"error\"],\n (\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 30, 50], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [0, 120, 240], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 30, 50], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [0, 120, 240], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n None,\n id=\"Dataset-identical units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n xr.Dataset(\n {\n \"x\": (\"x\", [0, 1, 3, 5], {\"units\": unit_registry.Unit(\"m\")}),\n \"y\": (\"y\", [0, 2, 4], {\"units\": unit_registry.Unit(\"min\")}),\n }\n ),\n xr.Dataset(\n {\n \"x\": (\"x\", [0, 1, 3, 5], {\"units\": unit_registry.Unit(\"m\")}),\n \"y\": (\"y\", [0, 2, 4], {\"units\": unit_registry.Unit(\"min\")}),\n }\n ),\n None,\n id=\"Dataset-compatible units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n xr.Dataset(\n {\n \"x\": (\"x\", [1, 3], {\"units\": unit_registry.Unit(\"s\")}),\n \"y\": (\"y\", [1], {\"units\": unit_registry.Unit(\"m\")}),\n }\n ),\n None,\n ValueError,\n id=\"Dataset-incompatible units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 30, 50], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [0, 240], {\"units\": unit_registry.Unit(\"s\")}),\n }\n ),\n xr.DataArray(\n [[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 30, 50], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [0, 240], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n None,\n id=\"DataArray-identical units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"a\": ((\"x\", \"y\"), Quantity([[0, 1], [2, 3], [4, 5]], \"kg\")),\n \"x\": [10, 20, 30],\n \"y\": [60, 120],\n }\n ),\n xr.Dataset(\n {\n \"x\": [15, 25],\n \"y\": [75, 105],\n }\n ),\n xr.Dataset(\n {\n \"a\": ((\"x\", \"y\"), Quantity([[1.25, 1.75], [3.25, 3.75]], \"kg\")),\n \"x\": [15, 25],\n \"y\": [75, 105],\n }\n ),\n None,\n id=\"Dataset-data units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n xr.Dataset(\n {\n \"x\": (\"x\", [1, 3, 5], {\"units\": unit_registry.Unit(\"m\")}),\n \"y\": (\"y\", [0, 2], {\"units\": unit_registry.Unit(\"min\")}),\n }\n ),\n xr.DataArray(\n [[np.nan, 1], [np.nan, 5], [np.nan, np.nan]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [1, 3, 5], {\"units\": unit_registry.Unit(\"m\")}),\n \"y\": (\"y\", [0, 2], {\"units\": unit_registry.Unit(\"min\")}),\n },\n ),\n None,\n id=\"DataArray-compatible units\",\n ),\n pytest.param(\n xr.DataArray(\n [[0, 1], [2, 3], [4, 5]],\n dims=(\"x\", \"y\"),\n coords={\n \"x\": (\"x\", [10, 20, 30], {\"units\": unit_registry.Unit(\"dm\")}),\n \"y\": (\"y\", [60, 120], {\"units\": unit_registry.Unit(\"s\")}),\n },\n ),\n xr.Dataset(\n {\n \"x\": (\"x\", [10, 30], {\"units\": unit_registry.Unit(\"s\")}),\n \"y\": (\"y\", [60], {\"units\": unit_registry.Unit(\"m\")}),\n }\n ),\n None,\n ValueError,\n id=\"DataArray-incompatible units\",\n ),\n pytest.param(\n xr.DataArray(\n Quantity([[0, 1], [2, 3], [4, 5]], \"kg\"),\n dims=(\"x\", \"y\"),\n coords={\n \"x\": [10, 20, 30],\n \"y\": [60, 120],\n },\n ),\n xr.Dataset(\n {\n \"x\": [15, 25],\n \"y\": [75, 105],\n }\n ),\n xr.DataArray(\n Quantity([[1.25, 1.75], [3.25, 3.75]], \"kg\"),\n dims=(\"x\", \"y\"),\n coords={\n \"x\": [15, 25],\n \"y\": [75, 105],\n },\n ),\n None,\n id=\"DataArray-data units\",\n ),\n ),\n)\ndef test_interp_like(obj, other, expected, error):\n if error is not None:\n with pytest.raises(error):\n obj.pint.interp_like(other)\n else:\n actual = obj.pint.interp_like(other)\n assert_units_equal(actual, expected)\n assert_identical(actual, expected)\n\n\n@requires_bottleneck\[email protected](\n [\"obj\", \"expected\"],\n (\n pytest.param(\n xr.Dataset(\n {\"a\": (\"x\", [nan, 0, nan, 1, nan, nan, 2, nan])},\n coords={\"u\": (\"x\", [nan, 0, nan, 1, nan, nan, 2, nan])},\n ),\n xr.Dataset(\n {\"a\": (\"x\", [nan, 0, 0, 1, 1, 1, 2, 2])},\n coords={\"u\": (\"x\", [nan, 0, nan, 1, nan, nan, 2, nan])},\n ),\n id=\"Dataset-no units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"a\": (\n \"x\",\n Quantity([nan, 0, nan, 1, nan, nan, 2, nan], \"m\"),\n )\n },\n coords={\n \"u\": (\n \"x\",\n Quantity([nan, 0, nan, 1, nan, nan, 2, nan], \"m\"),\n )\n },\n ),\n xr.Dataset(\n {\"a\": (\"x\", Quantity([nan, 0, 0, 1, 1, 1, 2, 2], \"m\"))},\n coords={\n \"u\": (\n \"x\",\n Quantity([nan, 0, nan, 1, nan, nan, 2, nan], \"m\"),\n )\n },\n ),\n id=\"Dataset-units\",\n ),\n pytest.param(\n xr.DataArray(\n [nan, 0, nan, 1, nan, nan, 2, nan],\n coords={\n \"u\": (\n \"x\",\n [nan, 0, nan, 1, nan, nan, 2, nan],\n )\n },\n dims=\"x\",\n ),\n xr.DataArray(\n [nan, 0, 0, 1, 1, 1, 2, 2],\n coords={\n \"u\": (\n \"x\",\n [nan, 0, nan, 1, nan, nan, 2, nan],\n )\n },\n dims=\"x\",\n ),\n id=\"DataArray-no units\",\n ),\n pytest.param(\n xr.DataArray(\n Quantity([nan, 0, nan, 1, nan, nan, 2, nan], \"m\"),\n coords={\n \"u\": (\n \"x\",\n Quantity([nan, 0, nan, 1, nan, nan, 2, nan], \"m\"),\n )\n },\n dims=\"x\",\n ),\n xr.DataArray(\n Quantity([nan, 0, 0, 1, 1, 1, 2, 2], \"m\"),\n coords={\n \"u\": (\n \"x\",\n Quantity([nan, 0, nan, 1, nan, nan, 2, nan], \"m\"),\n )\n },\n dims=\"x\",\n ),\n id=\"DataArray-units\",\n ),\n ),\n)\ndef test_ffill(obj, expected):\n actual = obj.pint.ffill(dim=\"x\")\n assert_identical(actual, expected)\n assert_units_equal(actual, expected)\n\n\n@requires_bottleneck\[email protected](\n [\"obj\", \"expected\"],\n (\n pytest.param(\n xr.Dataset(\n {\"a\": (\"x\", [nan, 0, nan, 1, nan, nan, 2, nan])},\n coords={\"u\": (\"x\", [nan, 0, nan, 1, nan, nan, 2, nan])},\n ),\n xr.Dataset(\n {\"a\": (\"x\", [0, 0, 1, 1, 2, 2, 2, nan])},\n coords={\"u\": (\"x\", [nan, 0, nan, 1, nan, nan, 2, nan])},\n ),\n id=\"Dataset-no units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"a\": (\n \"x\",\n Quantity([nan, 0, nan, 1, nan, nan, 2, nan], \"m\"),\n )\n },\n coords={\n \"u\": (\n \"x\",\n Quantity([nan, 0, nan, 1, nan, nan, 2, nan], \"m\"),\n )\n },\n ),\n xr.Dataset(\n {\"a\": (\"x\", Quantity([0, 0, 1, 1, 2, 2, 2, nan], \"m\"))},\n coords={\n \"u\": (\n \"x\",\n Quantity([nan, 0, nan, 1, nan, nan, 2, nan], \"m\"),\n )\n },\n ),\n id=\"Dataset-units\",\n ),\n pytest.param(\n xr.DataArray(\n [nan, 0, nan, 1, nan, nan, 2, nan],\n coords={\n \"u\": (\n \"x\",\n [nan, 0, nan, 1, nan, nan, 2, nan],\n )\n },\n dims=\"x\",\n ),\n xr.DataArray(\n [0, 0, 1, 1, 2, 2, 2, nan],\n coords={\n \"u\": (\n \"x\",\n [nan, 0, nan, 1, nan, nan, 2, nan],\n )\n },\n dims=\"x\",\n ),\n id=\"DataArray-no units\",\n ),\n pytest.param(\n xr.DataArray(\n Quantity([nan, 0, nan, 1, nan, nan, 2, nan], \"m\"),\n coords={\n \"u\": (\n \"x\",\n Quantity([nan, 0, nan, 1, nan, nan, 2, nan], \"m\"),\n )\n },\n dims=\"x\",\n ),\n xr.DataArray(\n Quantity([0, 0, 1, 1, 2, 2, 2, nan], \"m\"),\n coords={\n \"u\": (\n \"x\",\n Quantity([nan, 0, nan, 1, nan, nan, 2, nan], \"m\"),\n )\n },\n dims=\"x\",\n ),\n id=\"DataArray-units\",\n ),\n ),\n)\ndef test_bfill(obj, expected):\n actual = obj.pint.bfill(dim=\"x\")\n assert_identical(actual, expected)\n assert_units_equal(actual, expected)\n\n\[email protected](\n [\"obj\", \"expected\"],\n (\n pytest.param(\n xr.Dataset(\n {\"a\": (\"x\", [nan, 0, nan, 1, nan, nan, nan, 2, nan])},\n coords={\"u\": (\"x\", [nan, 0, nan, 1, nan, nan, nan, 2, nan])},\n ),\n xr.Dataset(\n {\"a\": (\"x\", [nan, 0, 0.5, 1, 1.25, 1.5, 1.75, 2, nan])},\n coords={\"u\": (\"x\", [nan, 0, nan, 1, nan, nan, nan, 2, nan])},\n ),\n id=\"Dataset-no units\",\n ),\n pytest.param(\n xr.Dataset(\n {\n \"a\": (\n \"x\",\n Quantity([nan, 0, nan, 1, nan, nan, nan, 2, nan], \"m\"),\n )\n },\n coords={\n \"u\": (\n \"x\",\n Quantity([nan, 0, nan, 1, nan, nan, nan, 2, nan], \"m\"),\n )\n },\n ),\n xr.Dataset(\n {\"a\": (\"x\", Quantity([nan, 0, 0.5, 1, 1.25, 1.5, 1.75, 2, nan], \"m\"))},\n coords={\n \"u\": (\n \"x\",\n Quantity([nan, 0, nan, 1, nan, nan, nan, 2, nan], \"m\"),\n )\n },\n ),\n id=\"Dataset-units\",\n ),\n pytest.param(\n xr.DataArray(\n [nan, 0, nan, 1, nan, nan, nan, 2, nan],\n coords={\n \"u\": (\n \"x\",\n Quantity([nan, 0, nan, 1, nan, nan, nan, 2, nan], \"m\"),\n )\n },\n dims=\"x\",\n ),\n xr.DataArray(\n [nan, 0, 0.5, 1, 1.25, 1.5, 1.75, 2, nan],\n coords={\n \"u\": (\n \"x\",\n Quantity([nan, 0, nan, 1, nan, nan, nan, 2, nan], \"m\"),\n )\n },\n dims=\"x\",\n ),\n id=\"DataArray-units\",\n ),\n pytest.param(\n xr.DataArray(\n Quantity([nan, 0, nan, 1, nan, nan, nan, 2, nan], \"m\"),\n coords={\n \"u\": (\n \"x\",\n Quantity([nan, 0, nan, 1, nan, nan, nan, 2, nan], \"m\"),\n )\n },\n dims=\"x\",\n ),\n xr.DataArray(\n Quantity([nan, 0, 0.5, 1, 1.25, 1.5, 1.75, 2, nan], \"m\"),\n coords={\n \"u\": (\n \"x\",\n Quantity([nan, 0, nan, 1, nan, nan, nan, 2, nan], \"m\"),\n )\n },\n dims=\"x\",\n ),\n id=\"DataArray-units\",\n ),\n ),\n)\ndef test_interpolate_na(obj, expected):\n actual = obj.pint.interpolate_na(dim=\"x\")\n assert_identical(actual, expected)\n assert_units_equal(actual, expected)\n" ]
[ [ "numpy.logspace", "numpy.arange", "numpy.testing.assert_array_equal", "numpy.linspace" ] ]
makutaga/vtksample
[ "4eaea97547355ea87a12f7f1a3283940cda3d2da" ]
[ "twoCharges.py" ]
[ "#!/usr/bin/env python3\n\"\"\"EVTK sample script\n\n空間に正負の電荷を置いたときの周辺の電位,電界分布を計算し,\nvtkファイルで出力する.\n\"\"\"\n\nimport numpy as np\nimport scipy.constants as const\nimport scipy\nimport pyevtk\n\n\ndef main(vtktype='vts'):\n \"\"\" メイン\n\n Args:\n vtktype : vtk ファイルの種類を指定する.(vts | vtr)\n \"\"\"\n\n calc_range = 1.0 # 計算範囲 -calc_range から calc_range\n nsamples = 200 # 分割数\n k = 1/(4 * const.pi * const.epsilon_0)\n\n charge = [\n {'q': -1.0, 'px': -0.2, 'py': 0.0, 'pz': 0.0},\n {'q': 1.0, 'px': 0.2, 'py': 0.0, 'pz': 0.0},\n ]\n\n calc_range_x = [-calc_range, calc_range]\n calc_range_y = [-calc_range, calc_range]\n calc_range_z = [-calc_range, calc_range]\n\n xx = np.linspace(calc_range_x[0], calc_range_x[1], nsamples)\n yy = np.linspace(calc_range_y[0], calc_range_y[1], nsamples)\n zz = np.linspace(calc_range_z[0], calc_range_z[1], nsamples)\n\n # 必ず indexing='ij' を指定する.座標軸が入れ替わらないように\n xxx, yyy, zzz = np.meshgrid(xx, yy, zz, indexing='ij')\n\n potential = np.zeros_like(xxx)\n E_x = np.zeros_like(xxx)\n E_y = np.zeros_like(yyy)\n E_z = np.zeros_like(zzz)\n\n for ch in charge:\n print(ch)\n dx = xxx - ch['px']\n dy = yyy - ch['py']\n dz = zzz - ch['pz']\n r2 = dx ** 2 + dy ** 2 + dz ** 2\n r = np.sqrt(r2)\n a_V = k * ch['q'] / r\n potential = potential + a_V\n\n a_E = k * ch['q'] / r2\n E_x = E_x + a_E * dx / r\n E_y = E_y + a_E * dy / r\n E_z = E_z + a_E * dz / r\n\n print(f\"{dx.shape}\")\n\n # vtk ファイルの書き出し\n filename = './twoCharges'\n if vtktype == 'vts':\n ''' StructuredGrid で書き出す場合'''\n pyevtk.hl.gridToVTK(\n filename, # ファイル名の指定.拡張子は追加される\n xxx, yyy, zzz, # 各格子点の座標\n pointData={ # 格子点上のデータの指定\n 'potential': potential,\n 'efield': (E_x, E_y, E_z),\n },\n )\n elif vtktype == 'vtr':\n ''' RectilinearGrid で書き出す場合'''\n pyevtk.hl.gridToVTK(\n filename, # ファイル名の指定.拡張子は追加される\n xx, yy, zz, # 各座標軸の座標\n pointData={ # 格子点上のデータの指定\n 'potential': potential,\n 'efield': (E_x, E_y, E_z),\n },\n )\n else:\n print(f\"Unsupported vtk fileformat {vtktype}\")\n\n\nif __name__ == \"__main__\":\n main('vts')\n" ]
[ [ "numpy.meshgrid", "numpy.zeros_like", "numpy.sqrt", "numpy.linspace" ] ]
arice84/bootcamp
[ "73a5517bcf282fdb2bd8808eb2bfb839eaceadf1" ]
[ "bootcamp_utils.py" ]
[ "\"\"\"bootcamp utilities a collection of functions that are useful in bootcamp\"\"\"\nimport numpy as np\n\ndef ecdf(data):\n \"\"\"compute x, y values for an empirical distribution function\"\"\"\n x = np.sort(data)\n y = np.arange(1, 1+len(x)) / len(x)\n return x, y\n\ndef plot_ecdf(x, y):\n plt.plot(x, y, marker='.', linestyle='none', markersize=10, alpha=0.5)\n plt.ylabel('eCDF')\n\ndef bootstrap(data_array, np_stat, reps):\n \"\"\"\n calculate bootstrap values for for given data and statistic\n return array of data values\n \"\"\"\n #initalize an empty array for replicates\n bs_reps = np.empty(reps)\n for i in range(reps):\n bs_sample = np.random.choice(data_array, replace=True, size=len(data_array))\n bs_reps[i] = np_stat(bs_sample)\n return bs_reps\n\ndef bs_conf_int(data_array, np_stat, reps=100000, interval=[2.5,97.5]):\n \"\"\"\n calculate confidence interval of bootstrap replicates of given dataset.\n \"\"\"\n bs_reps = bootstrap(data_array, np_stat, reps)\n return np.percentile(bs_reps, interval)\n" ]
[ [ "numpy.empty", "numpy.percentile", "numpy.sort" ] ]
xnox/BLAKE3-specs
[ "06c989589e21fb674606f09ee859eed43e6af75e" ]
[ "benchmarks/thread_benches/plot.py" ]
[ "#! /usr/bin/env python3\n\nimport json\nfrom matplotlib import pyplot\nfrom pathlib import Path\nimport pandas\nimport seaborn\nimport sys\n\nBENCH_NAMES = [\n (\"threads_48\", \"48 threads\"),\n (\"threads_32\", \"32 threads\"),\n (\"threads_16\", \"16 threads\"),\n (\"threads_08\", \"8 threads\"),\n (\"threads_04\", \"4 threads\"),\n (\"threads_02\", \"2 threads\"),\n (\"threads_01\", \"1 thread\"),\n]\n\nSIZES = [\n (2**15, \"32 KiB\"),\n (2**16, \"64 KiB\"),\n (2**17, \"128 KiB\"),\n (2**18, \"256 KiB\"),\n (2**19, \"512 KiB\"),\n (2**20, \"1 MiB\"),\n (2**21, \"2 MiB\"),\n (2**22, \"4 MiB\"),\n (2**23, \"8 MiB\"),\n (2**24, \"16 MiB\"),\n (2**25, \"32 MiB\"),\n (2**26, \"64 MiB\"),\n (2**27, \"128 MiB\"),\n (2**28, \"256 MiB\"),\n (2**29, \"512 MiB\"),\n (2**30, \"1 GiB\"),\n]\n\n\ndef main():\n target = Path(sys.argv[1])\n sizes_map = dict(SIZES)\n bench_names = []\n sizes = []\n ticks = []\n tick_names = []\n throughputs = []\n for bench_name, bench_name_pretty in BENCH_NAMES:\n bench_names.append(bench_name_pretty)\n hash_dir = target / \"bench_group\" / bench_name\n for size_i, size in enumerate(size[0] for size in SIZES):\n estimates_path = hash_dir / str(size) / \"new/estimates.json\"\n try:\n estimates = json.load(estimates_path.open())\n except FileNotFoundError:\n # Some benchmark runs use longer inputs than others, so we\n # ignore missing sizes here.\n continue\n slope = estimates[\"Slope\"]\n point = slope[\"point_estimate\"]\n # upper = slope[\"confidence_interval\"][\"upper_bound\"]\n # lower = slope[\"confidence_interval\"][\"lower_bound\"]\n seconds = point / 1e9\n bps_throughput = size / seconds\n gibps_throughput = bps_throughput / (2 ** 30)\n if len(throughputs) == size_i:\n throughputs.append([])\n sizes.append(size)\n if size in sizes_map:\n ticks.append(size)\n tick_names.append(sizes_map[size])\n throughputs[size_i].append(gibps_throughput)\n dataframe = pandas.DataFrame(throughputs, sizes, bench_names)\n\n seaborn.set()\n # pyplot.rcParams[\"axes.labelsize\"] = 20\n # pyplot.rcParams[\"pgf.rcfonts\"] = False\n # pyplot.rcParams[\"font.family\"] = \"serif\"\n # pyplot.figure(figsize=[20, 10])\n seaborn.set_context(\"paper\")\n # seaborn.set_context(\"talk\")\n dash_styles = [\n \"\", (4, 1.5), (1, 1), (3, 1, 1.5, 1), (5, 1, 1, 1), (5, 1, 2, 1, 2, 1),\n (2, 2, 3, 1.5), (1, 2.5, 3, 1.2), (2, 2)\n ]\n plot = seaborn.lineplot(\n data=dataframe,\n sort=False,\n dashes=dash_styles,\n )\n plot.set(ylabel=\"Throughput (GB/s)\\n\")\n pyplot.ylim(0, 1.1 * max(max(col) for col in throughputs))\n plot.set(xscale=\"log\")\n pyplot.legend(loc=\"best\", framealpha=1)\n # pyplot.legend(loc=\"lower right\", framealpha=1)\n plot.set(xticks=ticks)\n plot.set_xticklabels(tick_names, rotation=270)\n # pyplot.savefig(target.with_suffix(\".pgf\"), bbox_inches=\"tight\")\n pyplot.show()\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.show", "pandas.DataFrame" ] ]
mintiti/efficient-rl
[ "d65e9929ebb47bd2264a49b71088e41712611ff6" ]
[ "utils/wrappers.py" ]
[ "import gym\nfrom gym.wrappers import TimeLimit\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nclass DoneOnSuccessWrapper(gym.Wrapper):\n \"\"\"\n Reset on success and offsets the reward.\n Useful for GoalEnv.\n \"\"\"\n\n def __init__(self, env, reward_offset=1.0):\n super(DoneOnSuccessWrapper, self).__init__(env)\n self.reward_offset = reward_offset\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n done = done or info.get('is_success', False)\n reward += self.reward_offset\n return obs, reward, done, info\n\n def compute_reward(self, achieved_goal, desired_goal, info):\n reward = self.env.compute_reward(achieved_goal, desired_goal, info)\n return reward + self.reward_offset\n\n\nclass TimeFeatureWrapper(gym.Wrapper):\n \"\"\"\n Add remaining time to observation space for fixed length episodes.\n See https://arxiv.org/abs/1712.00378 and https://github.com/aravindr93/mjrl/issues/13.\n\n :param env: (gym.Env)\n :param max_steps: (int) Max number of steps of an episode\n if it is not wrapped in a TimeLimit object.\n :param test_mode: (bool) In test mode, the time feature is constant,\n equal to zero. This allow to check that the agent did not overfit this feature,\n learning a deterministic pre-defined sequence of actions.\n \"\"\"\n\n def __init__(self, env, max_steps=1000, test_mode=False):\n assert isinstance(env.observation_space, gym.spaces.Box)\n # Add a time feature to the observation\n low, high = env.observation_space.low, env.observation_space.high\n low, high = np.concatenate((low, [0])), np.concatenate((high, [1.]))\n env.observation_space = gym.spaces.Box(low=low, high=high, dtype=np.float32)\n\n super(TimeFeatureWrapper, self).__init__(env)\n\n if isinstance(env, TimeLimit):\n self._max_steps = env._max_episode_steps\n else:\n self._max_steps = max_steps\n self._current_step = 0\n self._test_mode = test_mode\n\n def reset(self):\n self._current_step = 0\n return self._get_obs(self.env.reset())\n\n def step(self, action):\n self._current_step += 1\n obs, reward, done, info = self.env.step(action)\n return self._get_obs(obs), reward, done, info\n\n def _get_obs(self, obs):\n \"\"\"\n Concatenate the time feature to the current observation.\n\n :param obs: (np.ndarray)\n :return: (np.ndarray)\n \"\"\"\n # Remaining time is more general\n time_feature = 1 - (self._current_step / self._max_steps)\n if self._test_mode:\n time_feature = 1.0\n # Optionnaly: concatenate [time_feature, time_feature ** 2]\n return np.concatenate((obs, [time_feature]))\n\n\nclass ActionNoiseWrapper(gym.Wrapper):\n \"\"\"\n Add gaussian noise to the action (without telling the agent),\n to test the robustness of the control.\n\n :param env: (gym.Env)\n :param noise_std: (float) Standard deviation of the noise\n \"\"\"\n\n def __init__(self, env, noise_std=0.1):\n super(ActionNoiseWrapper, self).__init__(env)\n self.noise_std = noise_std\n\n def step(self, action):\n noise = np.random.normal(np.zeros_like(action), np.ones_like(action) * self.noise_std)\n noisy_action = action + noise\n return self.env.step(noisy_action)\n\n\nclass DelayedRewardWrapper(gym.Wrapper):\n \"\"\"\n Delay the reward by `delay` steps, it makes the task harder but more realistic.\n The reward is accumulated during those steps.\n\n :param env: (gym.Env)\n :param delay: (int) Number of steps the reward should be delayed.\n \"\"\"\n\n def __init__(self, env, delay=10):\n super(DelayedRewardWrapper, self).__init__(env)\n self.delay = delay\n self.current_step = 0\n self.accumulated_reward = 0.0\n\n def reset(self):\n self.current_step = 0\n self.accumulated_reward = 0.0\n return self.env.reset()\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n\n self.accumulated_reward += reward\n self.current_step += 1\n\n if self.current_step % self.delay == 0 or done:\n reward = self.accumulated_reward\n self.accumulated_reward = 0.0\n else:\n reward = 0.0\n return obs, reward, done, info\n\n\nclass HistoryWrapper(gym.Wrapper):\n \"\"\"\n Delay the reward by `delay` steps, it makes the task harder but more realistic.\n The reward is accumulated during those steps.\n\n :param env: (gym.Env)\n :param horizon: (int) Number of steps to keep in the history.\n \"\"\"\n\n def __init__(self, env, horizon=5):\n assert isinstance(env.observation_space, gym.spaces.Box)\n\n wrapped_obs_space = env.observation_space\n wrapped_action_space = env.action_space\n\n # TODO: double check, it seems wrong when we have different low and highs\n low_obs = np.repeat(wrapped_obs_space.low, horizon, axis=-1)\n high_obs = np.repeat(wrapped_obs_space.high, horizon, axis=-1)\n\n low_action = np.repeat(wrapped_action_space.low, horizon, axis=-1)\n high_action = np.repeat(wrapped_action_space.high, horizon, axis=-1)\n\n low = np.concatenate((low_obs, low_action))\n high = np.concatenate((high_obs, high_action))\n\n # Overwrite the observation space\n env.observation_space = gym.spaces.Box(low=low, high=high, dtype=wrapped_obs_space.dtype)\n\n super(HistoryWrapper, self).__init__(env)\n\n self.horizon = horizon\n self.low_action, self.high_action = low_action, high_action\n self.low_obs, self.high_obs = low_obs, high_obs\n self.low, self.high = low, high\n self.obs_history = np.zeros(low_obs.shape, low_obs.dtype)\n self.action_history = np.zeros(low_action.shape, low_action.dtype)\n\n def _create_obs_from_history(self):\n return np.concatenate((self.obs_history, self.action_history))\n\n def reset(self):\n # Flush the history\n self.obs_history[...] = 0\n self.action_history[...] = 0\n obs = self.env.reset()\n self.obs_history[..., -obs.shape[-1]:] = obs\n return self._create_obs_from_history()\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n last_ax_size = obs.shape[-1]\n\n self.obs_history = np.roll(self.obs_history, shift=-last_ax_size, axis=-1)\n self.obs_history[..., -obs.shape[-1]:] = obs\n\n self.action_history = np.roll(self.action_history, shift=-action.shape[-1], axis=-1)\n self.action_history[..., -action.shape[-1]:] = action\n return self._create_obs_from_history(), reward, done, info\n\n\nclass PlotActionWrapper(gym.Wrapper):\n \"\"\"\n Wrapper for plotting the taken actions.\n Only works with 1D actions for now.\n Optionally, it can be used to plot the observations too.\n\n :param env: (gym.Env)\n :param plot_freq: (int) Plot every `plot_freq` episodes\n :param fft_plot: (bool) Whether to plot the fft plot of the actions\n (to see the frequency) needs some tuning (regarding the sampling frequency)\n \"\"\"\n\n def __init__(self, env, plot_freq=5, fft_plot=False):\n super(PlotActionWrapper, self).__init__(env)\n self.plot_freq = plot_freq\n self.fft_plot = fft_plot\n self.current_episode = 0\n # Observation buffer (Optional)\n # self.observations = []\n # Action buffer\n self.actions = []\n\n def reset(self):\n self.current_episode += 1\n if self.current_episode % self.plot_freq == 0:\n self.plot()\n # Reset\n self.actions = []\n obs = self.env.reset()\n self.actions.append([])\n # self.observations.append(obs)\n return obs\n\n def step(self, action):\n obs, reward, done, info = self.env.step(action)\n\n self.actions[-1].append(action)\n # self.observations.append(obs)\n\n return obs, reward, done, info\n\n def plot(self):\n actions = self.actions\n x = np.arange(sum([len(episode) for episode in actions]))\n plt.figure('Actions')\n plt.title('Actions during exploration', fontsize=14)\n plt.xlabel('Timesteps', fontsize=14)\n plt.ylabel('Action', fontsize=14)\n\n start = 0\n for i in range(len(self.actions)):\n end = start + len(self.actions[i])\n plt.plot(x[start:end], self.actions[i])\n # Clipped actions: real behavior, note that it is between [-2, 2] for the Pendulum\n # plt.scatter(x[start:end], np.clip(self.actions[i], -1, 1), s=1)\n # plt.scatter(x[start:end], self.actions[i], s=1)\n start = end\n\n # Plot Frequency plot\n if self.fft_plot:\n signal = np.concatenate(tuple(self.actions))\n n_samples = len(signal)\n # TODO: change the time_delta to match the real one\n time_delta = 1 / 4e4\n # Sanity check: sinusoidal signal\n # signal = np.sin(10 * 2 * np.pi * np.arange(n_samples) * time_delta)\n signal_fft = np.fft.fft(signal)\n freq = np.fft.fftfreq(n_samples, time_delta)\n plt.figure('FFT')\n plt.plot(freq[:n_samples // 2], np.abs(signal_fft[:n_samples // 2]))\n\n plt.show()\n" ]
[ [ "numpy.ones_like", "numpy.abs", "matplotlib.pyplot.title", "numpy.fft.fft", "numpy.concatenate", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "numpy.zeros_like", "numpy.fft.fftfreq", "matplotlib.pyplot.xlabel", "numpy.repeat", "matplotlib.pyplot.show", "numpy.zeros", "numpy.roll", "matplotlib.pyplot.figure" ] ]