code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
# -*- coding: utf-8 -*- """ Helper functions for HDF5 Created on Tue Jun 2 12:37:50 2020 :copyright: <NAME> (<EMAIL>) :license: MIT """ # ============================================================================= # Imports # ============================================================================= from collections.abc import Iterable import inspect import numpy as np import h5py import gc from mth5.utils.mth5_logger import setup_logger logger = setup_logger(__name__) # ============================================================================= # Acceptable compressions # ============================================================================= COMPRESSION = ["lzf", "gzip", "szip", None] COMPRESSION_LEVELS = { "lzf": [None], "gzip": range(10), "szip": ["ec-8", "ee-10", "nn-8", "nn-10"], None: [None], } def validate_compression(compression, level): """ validate that the input compression is supported. :param compression: type of lossless compression :type compression: string, [ 'lzf' | 'gzip' | 'szip' | None ] :param level: compression level if supported :type level: string for 'szip' or int for 'gzip' :return: compression type :rtype: string :return: compressiong level :rtype: string for 'szip' or int for 'gzip' :raises: ValueError if comporession or level are not supported :raises: TypeError if compression level is not a string """ if compression is None: return None, None if not isinstance(compression, (str, type(None))): msg = "compression type must be a string, not {0}".format(type(compression)) logger.error(msg) raise TypeError(msg) if not compression in COMPRESSION: msg = ( f"Compression type {compression} not supported. " + f"Supported options are {COMPRESSION}" ) logger.error(msg) raise ValueError(msg) if compression == "lzf": level = COMPRESSION_LEVELS["lzf"][0] elif compression == " gzip": if not isinstance(level, (int)): msg = "Level type for gzip must be an int, not {0}.".format( type(level) + f" Options are {0}".format(COMPRESSION_LEVELS["gzip"]) ) logger.error(msg) raise TypeError(msg) elif compression == " szip": if not isinstance(level, (str)): msg = "Level type for szip must be an str, not {0}.".format( type(level) ) + " Options are {0}".format(COMPRESSION_LEVELS["szip"]) logger.error(msg) raise TypeError(msg) if not level in COMPRESSION_LEVELS[compression]: msg = ( f"compression level {level} not supported for {compression}." + " Options are {0}".format(COMPRESSION_LEVELS[compression]) ) logger.error(msg) raise ValueError(msg) return compression, level def recursive_hdf5_tree(group, lines=[]): if isinstance(group, (h5py._hl.group.Group, h5py._hl.files.File)): for key, value in group.items(): lines.append("-{0}: {1}".format(key, value)) recursive_hdf5_tree(value, lines) elif isinstance(group, h5py._hl.dataset.Dataset): for key, value in group.attrs.items(): lines.append("\t-{0}: {1}".format(key, value)) return "\n".join(lines) def close_open_files(): for obj in gc.get_objects(): try: if isinstance(obj, h5py.File): msg = "Found HDF5 File object " print(msg) try: msg = "{0}, ".format(obj.filename) obj.flush() obj.close() msg += "Closed File" logger.info(msg) except: msg += "File already closed." logger.info(msg) except: print("Object {} does not have __class__") def get_tree(parent): """ Simple function to recursively print the contents of an hdf5 group Parameters ---------- parent : :class:`h5py.Group` HDF5 (sub-)tree to print """ lines = ["{0}:".format(parent.name), "=" * 20] if not isinstance(parent, (h5py.File, h5py.Group)): raise TypeError("Provided object is not a h5py.File or h5py.Group " "object") def fancy_print(name, obj): # lines.append(name) spacing = " " * 4 * (name.count("/") + 1) group_name = name[name.rfind("/") + 1 :] if isinstance(obj, h5py.Group): lines.append("{0}|- Group: {1}".format(spacing, group_name)) lines.append("{0}{1}".format(spacing, (len(group_name) + 10) * "-")) elif isinstance(obj, h5py.Dataset): lines.append("{0}--> Dataset: {1}".format(spacing, group_name)) lines.append("{0}{1}".format(spacing, (len(group_name) + 15) * ".")) # lines.append(parent.name) parent.visititems(fancy_print) return "\n".join(lines) def to_numpy_type(value): """ Need to make the attributes friendly with Numpy and HDF5. For numbers and bool this is straight forward they are automatically mapped in h5py to a numpy type. But for strings this can be a challenge, especially a list of strings. HDF5 should only deal with ASCII characters or Unicode. No binary data is allowed. """ if value is None: return "none" # For now turn references into a generic string if isinstance(value, h5py.h5r.Reference): value = str(value) if isinstance( value, ( str, np.str_, int, float, bool, complex, np.int_, np.float_, np.bool_, np.complex_, ), ): return value if isinstance(value, Iterable): if np.any([type(x) in [str, bytes, np.str_] for x in value]): return np.array(value, dtype="S") else: return np.array(value) else: raise TypeError("Type {0} not understood".format(type(value))) # ============================================================================= # # ============================================================================= def inherit_doc_string(cls): for base in inspect.getmro(cls): if base.__doc__ is not None: cls.__doc__ = base.__doc__ break return cls
[ "gc.get_objects", "mth5.utils.mth5_logger.setup_logger", "inspect.getmro", "numpy.array" ]
[((476, 498), 'mth5.utils.mth5_logger.setup_logger', 'setup_logger', (['__name__'], {}), '(__name__)\n', (488, 498), False, 'from mth5.utils.mth5_logger import setup_logger\n'), ((3440, 3456), 'gc.get_objects', 'gc.get_objects', ([], {}), '()\n', (3454, 3456), False, 'import gc\n'), ((6379, 6398), 'inspect.getmro', 'inspect.getmro', (['cls'], {}), '(cls)\n', (6393, 6398), False, 'import inspect\n'), ((6012, 6038), 'numpy.array', 'np.array', (['value'], {'dtype': '"""S"""'}), "(value, dtype='S')\n", (6020, 6038), True, 'import numpy as np\n'), ((6072, 6087), 'numpy.array', 'np.array', (['value'], {}), '(value)\n', (6080, 6087), True, 'import numpy as np\n')]
import os import random import numpy as np import torch def set_seed(seed=None): if seed is None: return None random.seed(seed) os.environ['PYTHONHASHSEED'] = ("%s" % seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.benchmark = False torch.backends.deterministic = True class AverageMeter(object): """Computes and stores the average and current value. Code imported from https://github.com/pytorch/examples/blob/master/imagenet/main.py#L247-L262 """ def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count
[ "numpy.random.seed", "torch.manual_seed", "torch.cuda.manual_seed", "torch.cuda.manual_seed_all", "random.seed" ]
[((129, 146), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (140, 146), False, 'import random\n'), ((200, 220), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (214, 220), True, 'import numpy as np\n'), ((225, 248), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (242, 248), False, 'import torch\n'), ((253, 281), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['seed'], {}), '(seed)\n', (275, 281), False, 'import torch\n'), ((286, 318), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['seed'], {}), '(seed)\n', (312, 318), False, 'import torch\n')]
"""Answer to Exercise 1.3 Author: <NAME> Email : <EMAIL> """ from __future__ import print_function import numpy as np import keras.backend as K # create variable w, b and x w = K.placeholder(shape=(2,), dtype=np.float32) # note that b is not a scalar b = K.placeholder(shape=(1,), dtype=np.float32) x = K.placeholder(shape=(2,), dtype=np.float32) # compute the sum a = K.sum(w*x+b) # compute the function f y = 1./(1+K.exp(-a)) # compile the function fun = K.function(inputs=[x, w, b], outputs=[y]) # Test function # compute y = f(2*x_1+3*x_2+0.5) W = np.array([2, 3], dtype=np.float32) B = np.array([0.5], dtype=np.float32) X = np.array([1, 2], dtype=np.float32) print (fun([X, W, B])[0])
[ "keras.backend.placeholder", "keras.backend.exp", "keras.backend.function", "keras.backend.sum", "numpy.array" ]
[((180, 223), 'keras.backend.placeholder', 'K.placeholder', ([], {'shape': '(2,)', 'dtype': 'np.float32'}), '(shape=(2,), dtype=np.float32)\n', (193, 223), True, 'import keras.backend as K\n'), ((258, 301), 'keras.backend.placeholder', 'K.placeholder', ([], {'shape': '(1,)', 'dtype': 'np.float32'}), '(shape=(1,), dtype=np.float32)\n', (271, 301), True, 'import keras.backend as K\n'), ((306, 349), 'keras.backend.placeholder', 'K.placeholder', ([], {'shape': '(2,)', 'dtype': 'np.float32'}), '(shape=(2,), dtype=np.float32)\n', (319, 349), True, 'import keras.backend as K\n'), ((373, 389), 'keras.backend.sum', 'K.sum', (['(w * x + b)'], {}), '(w * x + b)\n', (378, 389), True, 'import keras.backend as K\n'), ((462, 503), 'keras.backend.function', 'K.function', ([], {'inputs': '[x, w, b]', 'outputs': '[y]'}), '(inputs=[x, w, b], outputs=[y])\n', (472, 503), True, 'import keras.backend as K\n'), ((559, 593), 'numpy.array', 'np.array', (['[2, 3]'], {'dtype': 'np.float32'}), '([2, 3], dtype=np.float32)\n', (567, 593), True, 'import numpy as np\n'), ((598, 631), 'numpy.array', 'np.array', (['[0.5]'], {'dtype': 'np.float32'}), '([0.5], dtype=np.float32)\n', (606, 631), True, 'import numpy as np\n'), ((636, 670), 'numpy.array', 'np.array', (['[1, 2]'], {'dtype': 'np.float32'}), '([1, 2], dtype=np.float32)\n', (644, 670), True, 'import numpy as np\n'), ((421, 430), 'keras.backend.exp', 'K.exp', (['(-a)'], {}), '(-a)\n', (426, 430), True, 'import keras.backend as K\n')]
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch from lottery.branch import base import models.registry from pruning.mask import Mask from pruning.pruned_model import PrunedModel from training import train from utils.tensor_utils import generate_mask_active, erank, shuffle_tensor, mutual_coherence,\ gradient_mean, activation_mean, activation import datasets.registry import numpy as np import copy from platforms.platform import get_platform from foundations import paths from tqdm import tqdm erank_frobenius_coeff = 0.75 class Branch(base.Branch): def branch_function(self, seed: int, property: str, trials: int, top: int = 1): # Randomize the mask. orig_mask = Mask.load(self.level_root) best_mask = Mask() start_step = self.lottery_desc.str_to_step('0ep') # Use level 0 model for dense pre-pruned model if not get_platform().is_primary_process: return base_model = models.registry.load(self.level_root.replace(f'level_{self.level}', 'level_0'), start_step, self.lottery_desc.model_hparams) orig_model = PrunedModel(base_model, Mask.ones_like(base_model)) model_graduate = copy.deepcopy(orig_model) model = copy.deepcopy(orig_model) # Randomize while keeping the same layerwise proportions as the original mask. prunable_tensors = set(orig_model.prunable_layer_names) - set(orig_model.prunable_conv_names) tensors = {k[6:]: v.clone() for k, v in orig_model.state_dict().items() if k[6:] in prunable_tensors} train_loader = datasets.registry.get(self.lottery_desc.dataset_hparams, train=True) input = list(train_loader)[0][0] if property == 'activation' or property == 'gradient_mean' or property == 'loss' or property == 'accuracy' or property == 'labels_entropy': input, labels = list(train_loader)[0] input, labels = input.cuda(), labels.cuda() # features = orig_model.intermediate(input) # features.insert(0, input) properties = np.zeros((len(tensors), trials)) for i, (name, param) in enumerate(tensors.items()): curr_mask = Mask() for t in tqdm(range(trials)): curr_mask[name] = shuffle_tensor(orig_mask[name], seed=seed+t).int() if property == 'weight_erank': properties[i, t] = erank(param * curr_mask[name]) if property == 'weight_min_singular': s = torch.linalg.svdvals(param * curr_mask[name]) properties[i, t] = s[-1] elif property == 'weight_mutual_coherence': properties[i, t] = -mutual_coherence(param * curr_mask[name]) elif property == 'weight_frobenius': properties[i, t] = (param * curr_mask[name]).norm().item() elif property == 'weight_kaiming': kaiming_std = torch.sqrt(torch.tensor(2.) / param.size(1)) # for fc only! properties[i, t] = -torch.abs(param[curr_mask[name] > 0].std() - kaiming_std) elif property == 'features_erank': model = copy.deepcopy(model_graduate) model.register_buffer(PrunedModel.to_mask_name(name), curr_mask[name].float()) # model[name].data = param * curr_mask[name] features_for_prop = model.intermediate(input) properties[i, t] = erank(features_for_prop[i]) elif property == 'features_erank_frobenius': model = copy.deepcopy(model_graduate) model.register_buffer(PrunedModel.to_mask_name(name), curr_mask[name].float()) # model[name].data = param * curr_mask[name] with torch.no_grad(): features_for_prop = model.intermediate(input) properties[i, t] = erank_frobenius_coeff * erank(features_for_prop[i]) +\ (1- erank_frobenius_coeff) * features_for_prop[i].norm().item() elif property == 'features_mutual_coherence': model = copy.deepcopy(model_graduate) model.register_buffer(PrunedModel.to_mask_name(name), curr_mask[name].float()) # model[name].data = param * curr_mask[name] features_for_prop = model.intermediate(input) properties[i, t] = -mutual_coherence(features_for_prop[i]) elif property == 'features_frobenius': model = copy.deepcopy(model_graduate) model.register_buffer(PrunedModel.to_mask_name(name), curr_mask[name].float()) # model[name].data = param * curr_mask[name] features_for_prop = model.intermediate(input) properties[i, t] = features_for_prop[i].norm().item() elif property == 'features_stable_rank': model = copy.deepcopy(model_graduate) model.register_buffer(PrunedModel.to_mask_name(name), curr_mask[name].float()) # model[name].data = param * curr_mask[name] features_for_prop = model.intermediate(input) properties[i, t] = (torch.linalg.norm(features_for_prop[-1], ord='fro') / torch.linalg.norm(features_for_prop[-1],ord=2)).item() elif property == 'features_nuclear': model = copy.deepcopy(model_graduate) model.register_buffer(PrunedModel.to_mask_name(name), curr_mask[name].float()) # model[name].data = param * curr_mask[name] features_for_prop = model.intermediate(input) properties[i, t] = features_for_prop[i].norm(p=1).item() elif property == 'min_singular': model = copy.deepcopy(model_graduate) model.register_buffer(PrunedModel.to_mask_name(name), curr_mask[name].float()) # model[name].data = param * curr_mask[name] features_for_prop = model.intermediate(input) _, s, _ = torch.svd(features_for_prop[i], compute_uv=False) properties[i, t] = s[-1] elif property == 'activation': if i < len(tensors) - 1: model = copy.deepcopy(model_graduate) model.register_buffer(PrunedModel.to_mask_name(name), curr_mask[name].float()) model.cuda() properties[i, t] = activation(model, input)[i] else: properties[i, t] = 0 elif property == 'gradient_mean': model = copy.deepcopy(model_graduate) model.register_buffer(PrunedModel.to_mask_name(name), curr_mask[name].float()) model.cuda() properties[i, t] = gradient_mean(model, input, labels)[i] elif property == 'loss': model = copy.deepcopy(model_graduate) model.register_buffer(PrunedModel.to_mask_name(name), curr_mask[name].float()) model.cuda() loss = model.loss_criterion(model(input), labels) properties[i, t] = -loss elif property == 'accuracy': model = copy.deepcopy(model_graduate) model.register_buffer(PrunedModel.to_mask_name(name), curr_mask[name].float()) model.cuda() output = model(input) _, predicted = torch.max(output.data, 1) total = labels.size(0) correct = (predicted == labels).sum().item() properties[i, t] = correct / total elif property == 'labels_entropy': model = copy.deepcopy(model_graduate) model.register_buffer(PrunedModel.to_mask_name(name), curr_mask[name].float()) model.cuda() output = model(input) _, predicted = torch.max(output.data, 1) total = labels.size(0) p = predicted.histc(bins=10) / total properties[i, t] = -torch.sum(p[p > 0] * p[p > 0].log()).item() best_mask[name] = shuffle_tensor(orig_mask[name], int(seed + np.argmax(properties[i, :]))).int() model_graduate.register_buffer(PrunedModel.to_mask_name(name), best_mask[name].float()) # Save the properties. with open(paths.properties(self.branch_root, property), 'wb') as f: np.save(f, properties) for t in range(1,top+1): # bug fixed, one of them is chosen with the worst property value curr_model = copy.deepcopy(base_model) best_mask[name] = shuffle_tensor(orig_mask[name], int(seed + np.argsort(properties[i, :])[-t])).int() best_mask.save(f'{self.branch_root}_top_{t}') if not get_platform().exists(f'{self.branch_root}_top_{t}'): get_platform().makedirs(f'{self.branch_root}_top_{t}') # Train the model with the new mask. pruned_model = PrunedModel(curr_model, best_mask) train.standard_train(pruned_model, f'{self.branch_root}_top_{t}', self.lottery_desc.dataset_hparams, self.lottery_desc.training_hparams, start_step=start_step, verbose=self.verbose) @staticmethod def description(): return "Randomly active prune the model with max property." @staticmethod def name(): return 'max_random'
[ "pruning.mask.Mask", "numpy.argmax", "utils.tensor_utils.mutual_coherence", "utils.tensor_utils.gradient_mean", "numpy.argsort", "torch.no_grad", "pruning.pruned_model.PrunedModel.to_mask_name", "utils.tensor_utils.shuffle_tensor", "torch.linalg.norm", "pruning.mask.Mask.load", "utils.tensor_utils.erank", "copy.deepcopy", "numpy.save", "torch.svd", "utils.tensor_utils.activation", "torch.max", "training.train.standard_train", "torch.linalg.svdvals", "foundations.paths.properties", "pruning.pruned_model.PrunedModel", "platforms.platform.get_platform", "torch.tensor", "pruning.mask.Mask.ones_like" ]
[((834, 860), 'pruning.mask.Mask.load', 'Mask.load', (['self.level_root'], {}), '(self.level_root)\n', (843, 860), False, 'from pruning.mask import Mask\n'), ((881, 887), 'pruning.mask.Mask', 'Mask', ([], {}), '()\n', (885, 887), False, 'from pruning.mask import Mask\n'), ((1344, 1369), 'copy.deepcopy', 'copy.deepcopy', (['orig_model'], {}), '(orig_model)\n', (1357, 1369), False, 'import copy\n'), ((1386, 1411), 'copy.deepcopy', 'copy.deepcopy', (['orig_model'], {}), '(orig_model)\n', (1399, 1411), False, 'import copy\n'), ((1291, 1317), 'pruning.mask.Mask.ones_like', 'Mask.ones_like', (['base_model'], {}), '(base_model)\n', (1305, 1317), False, 'from pruning.mask import Mask\n'), ((2328, 2334), 'pruning.mask.Mask', 'Mask', ([], {}), '()\n', (2332, 2334), False, 'from pruning.mask import Mask\n'), ((8981, 9003), 'numpy.save', 'np.save', (['f', 'properties'], {}), '(f, properties)\n', (8988, 9003), True, 'import numpy as np\n'), ((9128, 9153), 'copy.deepcopy', 'copy.deepcopy', (['base_model'], {}), '(base_model)\n', (9141, 9153), False, 'import copy\n'), ((9532, 9566), 'pruning.pruned_model.PrunedModel', 'PrunedModel', (['curr_model', 'best_mask'], {}), '(curr_model, best_mask)\n', (9543, 9566), False, 'from pruning.pruned_model import PrunedModel\n'), ((9579, 9769), 'training.train.standard_train', 'train.standard_train', (['pruned_model', 'f"""{self.branch_root}_top_{t}"""', 'self.lottery_desc.dataset_hparams', 'self.lottery_desc.training_hparams'], {'start_step': 'start_step', 'verbose': 'self.verbose'}), "(pruned_model, f'{self.branch_root}_top_{t}', self.\n lottery_desc.dataset_hparams, self.lottery_desc.training_hparams,\n start_step=start_step, verbose=self.verbose)\n", (9599, 9769), False, 'from training import train\n'), ((1016, 1030), 'platforms.platform.get_platform', 'get_platform', ([], {}), '()\n', (1028, 1030), False, 'from platforms.platform import get_platform\n'), ((8804, 8834), 'pruning.pruned_model.PrunedModel.to_mask_name', 'PrunedModel.to_mask_name', (['name'], {}), '(name)\n', (8828, 8834), False, 'from pruning.pruned_model import PrunedModel\n'), ((8911, 8955), 'foundations.paths.properties', 'paths.properties', (['self.branch_root', 'property'], {}), '(self.branch_root, property)\n', (8927, 8955), False, 'from foundations import paths\n'), ((2548, 2578), 'utils.tensor_utils.erank', 'erank', (['(param * curr_mask[name])'], {}), '(param * curr_mask[name])\n', (2553, 2578), False, 'from utils.tensor_utils import generate_mask_active, erank, shuffle_tensor, mutual_coherence, gradient_mean, activation_mean, activation\n'), ((2657, 2702), 'torch.linalg.svdvals', 'torch.linalg.svdvals', (['(param * curr_mask[name])'], {}), '(param * curr_mask[name])\n', (2677, 2702), False, 'import torch\n'), ((2411, 2457), 'utils.tensor_utils.shuffle_tensor', 'shuffle_tensor', (['orig_mask[name]'], {'seed': '(seed + t)'}), '(orig_mask[name], seed=seed + t)\n', (2425, 2457), False, 'from utils.tensor_utils import generate_mask_active, erank, shuffle_tensor, mutual_coherence, gradient_mean, activation_mean, activation\n'), ((9346, 9360), 'platforms.platform.get_platform', 'get_platform', ([], {}), '()\n', (9358, 9360), False, 'from platforms.platform import get_platform\n'), ((9400, 9414), 'platforms.platform.get_platform', 'get_platform', ([], {}), '()\n', (9412, 9414), False, 'from platforms.platform import get_platform\n'), ((2848, 2889), 'utils.tensor_utils.mutual_coherence', 'mutual_coherence', (['(param * curr_mask[name])'], {}), '(param * curr_mask[name])\n', (2864, 2889), False, 'from utils.tensor_utils import generate_mask_active, erank, shuffle_tensor, mutual_coherence, gradient_mean, activation_mean, activation\n'), ((8725, 8752), 'numpy.argmax', 'np.argmax', (['properties[i, :]'], {}), '(properties[i, :])\n', (8734, 8752), True, 'import numpy as np\n'), ((3344, 3373), 'copy.deepcopy', 'copy.deepcopy', (['model_graduate'], {}), '(model_graduate)\n', (3357, 3373), False, 'import copy\n'), ((3643, 3670), 'utils.tensor_utils.erank', 'erank', (['features_for_prop[i]'], {}), '(features_for_prop[i])\n', (3648, 3670), False, 'from utils.tensor_utils import generate_mask_active, erank, shuffle_tensor, mutual_coherence, gradient_mean, activation_mean, activation\n'), ((9227, 9255), 'numpy.argsort', 'np.argsort', (['properties[i, :]'], {}), '(properties[i, :])\n', (9237, 9255), True, 'import numpy as np\n'), ((3118, 3135), 'torch.tensor', 'torch.tensor', (['(2.0)'], {}), '(2.0)\n', (3130, 3135), False, 'import torch\n'), ((3416, 3446), 'pruning.pruned_model.PrunedModel.to_mask_name', 'PrunedModel.to_mask_name', (['name'], {}), '(name)\n', (3440, 3446), False, 'from pruning.pruned_model import PrunedModel\n'), ((3760, 3789), 'copy.deepcopy', 'copy.deepcopy', (['model_graduate'], {}), '(model_graduate)\n', (3773, 3789), False, 'import copy\n'), ((3832, 3862), 'pruning.pruned_model.PrunedModel.to_mask_name', 'PrunedModel.to_mask_name', (['name'], {}), '(name)\n', (3856, 3862), False, 'from pruning.pruned_model import PrunedModel\n'), ((3979, 3994), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3992, 3994), False, 'import torch\n'), ((4353, 4382), 'copy.deepcopy', 'copy.deepcopy', (['model_graduate'], {}), '(model_graduate)\n', (4366, 4382), False, 'import copy\n'), ((4129, 4156), 'utils.tensor_utils.erank', 'erank', (['features_for_prop[i]'], {}), '(features_for_prop[i])\n', (4134, 4156), False, 'from utils.tensor_utils import generate_mask_active, erank, shuffle_tensor, mutual_coherence, gradient_mean, activation_mean, activation\n'), ((4425, 4455), 'pruning.pruned_model.PrunedModel.to_mask_name', 'PrunedModel.to_mask_name', (['name'], {}), '(name)\n', (4449, 4455), False, 'from pruning.pruned_model import PrunedModel\n'), ((4653, 4691), 'utils.tensor_utils.mutual_coherence', 'mutual_coherence', (['features_for_prop[i]'], {}), '(features_for_prop[i])\n', (4669, 4691), False, 'from utils.tensor_utils import generate_mask_active, erank, shuffle_tensor, mutual_coherence, gradient_mean, activation_mean, activation\n'), ((4775, 4804), 'copy.deepcopy', 'copy.deepcopy', (['model_graduate'], {}), '(model_graduate)\n', (4788, 4804), False, 'import copy\n'), ((4847, 4877), 'pruning.pruned_model.PrunedModel.to_mask_name', 'PrunedModel.to_mask_name', (['name'], {}), '(name)\n', (4871, 4877), False, 'from pruning.pruned_model import PrunedModel\n'), ((5194, 5223), 'copy.deepcopy', 'copy.deepcopy', (['model_graduate'], {}), '(model_graduate)\n', (5207, 5223), False, 'import copy\n'), ((5266, 5296), 'pruning.pruned_model.PrunedModel.to_mask_name', 'PrunedModel.to_mask_name', (['name'], {}), '(name)\n', (5290, 5296), False, 'from pruning.pruned_model import PrunedModel\n'), ((5724, 5753), 'copy.deepcopy', 'copy.deepcopy', (['model_graduate'], {}), '(model_graduate)\n', (5737, 5753), False, 'import copy\n'), ((5796, 5826), 'pruning.pruned_model.PrunedModel.to_mask_name', 'PrunedModel.to_mask_name', (['name'], {}), '(name)\n', (5820, 5826), False, 'from pruning.pruned_model import PrunedModel\n'), ((6138, 6167), 'copy.deepcopy', 'copy.deepcopy', (['model_graduate'], {}), '(model_graduate)\n', (6151, 6167), False, 'import copy\n'), ((6428, 6477), 'torch.svd', 'torch.svd', (['features_for_prop[i]'], {'compute_uv': '(False)'}), '(features_for_prop[i], compute_uv=False)\n', (6437, 6477), False, 'import torch\n'), ((5494, 5545), 'torch.linalg.norm', 'torch.linalg.norm', (['features_for_prop[-1]'], {'ord': '"""fro"""'}), "(features_for_prop[-1], ord='fro')\n", (5511, 5545), False, 'import torch\n'), ((5588, 5635), 'torch.linalg.norm', 'torch.linalg.norm', (['features_for_prop[-1]'], {'ord': '(2)'}), '(features_for_prop[-1], ord=2)\n', (5605, 5635), False, 'import torch\n'), ((6210, 6240), 'pruning.pruned_model.PrunedModel.to_mask_name', 'PrunedModel.to_mask_name', (['name'], {}), '(name)\n', (6234, 6240), False, 'from pruning.pruned_model import PrunedModel\n'), ((6647, 6676), 'copy.deepcopy', 'copy.deepcopy', (['model_graduate'], {}), '(model_graduate)\n', (6660, 6676), False, 'import copy\n'), ((7037, 7066), 'copy.deepcopy', 'copy.deepcopy', (['model_graduate'], {}), '(model_graduate)\n', (7050, 7066), False, 'import copy\n'), ((6723, 6753), 'pruning.pruned_model.PrunedModel.to_mask_name', 'PrunedModel.to_mask_name', (['name'], {}), '(name)\n', (6747, 6753), False, 'from pruning.pruned_model import PrunedModel\n'), ((6860, 6884), 'utils.tensor_utils.activation', 'activation', (['model', 'input'], {}), '(model, input)\n', (6870, 6884), False, 'from utils.tensor_utils import generate_mask_active, erank, shuffle_tensor, mutual_coherence, gradient_mean, activation_mean, activation\n'), ((7109, 7139), 'pruning.pruned_model.PrunedModel.to_mask_name', 'PrunedModel.to_mask_name', (['name'], {}), '(name)\n', (7133, 7139), False, 'from pruning.pruned_model import PrunedModel\n'), ((7238, 7273), 'utils.tensor_utils.gradient_mean', 'gradient_mean', (['model', 'input', 'labels'], {}), '(model, input, labels)\n', (7251, 7273), False, 'from utils.tensor_utils import generate_mask_active, erank, shuffle_tensor, mutual_coherence, gradient_mean, activation_mean, activation\n'), ((7346, 7375), 'copy.deepcopy', 'copy.deepcopy', (['model_graduate'], {}), '(model_graduate)\n', (7359, 7375), False, 'import copy\n'), ((7418, 7448), 'pruning.pruned_model.PrunedModel.to_mask_name', 'PrunedModel.to_mask_name', (['name'], {}), '(name)\n', (7442, 7448), False, 'from pruning.pruned_model import PrunedModel\n'), ((7696, 7725), 'copy.deepcopy', 'copy.deepcopy', (['model_graduate'], {}), '(model_graduate)\n', (7709, 7725), False, 'import copy\n'), ((7935, 7960), 'torch.max', 'torch.max', (['output.data', '(1)'], {}), '(output.data, 1)\n', (7944, 7960), False, 'import torch\n'), ((7768, 7798), 'pruning.pruned_model.PrunedModel.to_mask_name', 'PrunedModel.to_mask_name', (['name'], {}), '(name)\n', (7792, 7798), False, 'from pruning.pruned_model import PrunedModel\n'), ((8203, 8232), 'copy.deepcopy', 'copy.deepcopy', (['model_graduate'], {}), '(model_graduate)\n', (8216, 8232), False, 'import copy\n'), ((8442, 8467), 'torch.max', 'torch.max', (['output.data', '(1)'], {}), '(output.data, 1)\n', (8451, 8467), False, 'import torch\n'), ((8275, 8305), 'pruning.pruned_model.PrunedModel.to_mask_name', 'PrunedModel.to_mask_name', (['name'], {}), '(name)\n', (8299, 8305), False, 'from pruning.pruned_model import PrunedModel\n')]
# -*- coding: utf-8 -*- """ Tic Toe Using pygame , numpy and sys with Graphical User Interface """ import pygame import sys from pygame.locals import * import numpy as np # ------ # constants # ------- width = 800 height = 800 #row and columns board_rows = 3 board_columns = 3 cross_width = 25 square_size = width//board_columns # colors in RGB format line_Width = 15 red = (255, 0, 0) bg_color = (28, 170, 156) line_color = (23, 145, 135) circle_color = (239, 231, 200) cross_color = (66, 66, 66) space = square_size//4 # circle circle_radius = square_size//3 circle_width = 14 pygame.init() screen = pygame.display.set_mode((height, width)) pygame.display.set_caption('Tic Tac Toe!') screen.fill(bg_color) # color to display restart white = (255, 255, 255) green = (0, 255, 0) blue = (0, 0, 128) font = pygame.font.Font('freesansbold.ttf', 25) # create a text suface object, # on which text is drawn on it. text = font.render('Press R to restart', True, green, blue) Won = font.render(" Won", True, blue, green) leave = font.render("Press X to Exit", True, white, red) # create a rectangular object for the # text surface object leaveRect = text.get_rect() textRect = text.get_rect() winRect = Won.get_rect() winRect.center = (100, 30) textRect.center = (width-400, 30) leaveRect.center = (width-120, 30) board = np.zeros((board_rows, board_columns)) # print(board) #pygame.draw.line( screen ,red ,(10,10),(300,300),10) def draw_figures(): for row in range(board_rows): for col in range(board_columns): if board[row][col] == 1: pygame.draw.circle(screen, circle_color, (int(col*square_size + square_size//2), int( row*square_size + square_size//2)), circle_radius, circle_width) elif board[row][col] == 2: pygame.draw.line(screen, cross_color, (col*square_size + space, row*square_size + square_size - space), (col*square_size+square_size - space, row*square_size + space), cross_width) pygame.draw.line(screen, cross_color, (col*square_size + space, row*square_size + space), (col*square_size + square_size - space, row*square_size + square_size - space), cross_width) def draw_lines(): pygame.draw.line(screen, line_color, (0, square_size), (width, square_size), line_Width) # 2nd horizontal line pygame.draw.line(screen, line_color, (0, 2*square_size), (width, 2*square_size), line_Width) # 1st verticle pygame.draw.line(screen, line_color, (square_size, 0), (square_size, height), line_Width) # 2nd verticle pygame.draw.line(screen, line_color, (2*square_size, 0), (2*square_size, height), line_Width) # To mark which square player has chosen def mark_square(row, col, player): board[row][col] = player # TO check the availablity of a square def available_square(row, col): return board[row][col] == 0 # check board full or not def is_board_full(): k = False for row in range(board_rows): for col in range(board_columns): if board[row][col] == 0: k = False else: k = True return k def check_win(player): # check verticle win for col in range(board_columns): if board[0][col] == player and board[1][col] == player and board[2][col] == player: draw_vertical_winning_line(col, player) return True # check Horizontal win for row in range(board_rows): if board[row][0] == player and board[row][1] == player and board[row][2] == player: draw_horizontal_winning_line(row, player) return True # check for asc win if board[2][0] == player and board[1][1] == player and board[0][2] == player: draw_asc_diagonal(player) return True if board[0][0] == player and board[1][1] == player and board[2][2] == player: draw_des_diagonal(player) return True def draw_horizontal_winning_line(row, player): posY = row*square_size + square_size//2 if(player == 1): color = circle_color else: color = cross_color pygame.draw.line(screen, color, (15, posY), (width-15, posY), 15) def draw_vertical_winning_line(col, player): posX = col*square_size + square_size//2 if(player == 1): color = circle_color else: color = cross_color pygame.draw.line(screen, color, (posX, 15), (posX, width-15), 15) def draw_asc_diagonal(player): if(player == 1): color = circle_color else: color = cross_color pygame.draw.line(screen, color, (15, height-15), (width-15, 15), 15) def draw_des_diagonal(player): if(player == 1): color = circle_color else: color = cross_color pygame.draw.line(screen, color, (15, 15), (width-15, height-15), 15) def restart(): screen.fill(bg_color) draw_lines() player = 1 for row in range(board_rows): for col in range(board_columns): board[row][col] = 0 draw_lines() # player player = 1 game_over = False while True: # main game loop for event in pygame.event.get(): # constantly looks for the event if event.type == pygame.QUIT: # if user clicks exit pygame.QUIT and sys exits pygame.quit() sys.exit() board_full = is_board_full() if board_full and not game_over: Won = font.render(" It's a Tie ", True, blue, green) screen.blit(Won, winRect) screen.blit(text, textRect) screen.blit(leave, leaveRect) if event.type == pygame.MOUSEBUTTONDOWN and not game_over: mouseX = event.pos[0] # x mouseY = event.pos[1] # y clicked_row = int(mouseY // square_size) clicked_column = int(mouseX // square_size) if available_square(clicked_row, clicked_column): mark_square(clicked_row, clicked_column, player) if(check_win(player)): game_over = True Won = font.render("Player"+str(player) + " Won ", True, blue, green) screen.blit(Won, winRect) screen.blit(text, textRect) screen.blit(leave, leaveRect) player = player % 2 + 1 if not game_over and not board_full: Won = font.render("Player"+str(player) + " Turn ", True, blue, green) screen.blit(Won, winRect) draw_figures() # to restart the game if event.type == pygame.KEYDOWN: if event.key == pygame.K_r: restart() game_over = False elif event.key == pygame.K_x: pygame.quit() sys.exit() # print(board) pygame.display.update()
[ "pygame.quit", "pygame.draw.line", "pygame.event.get", "pygame.display.set_mode", "numpy.zeros", "pygame.init", "pygame.display.update", "pygame.font.Font", "pygame.display.set_caption", "sys.exit" ]
[((608, 621), 'pygame.init', 'pygame.init', ([], {}), '()\n', (619, 621), False, 'import pygame\n'), ((632, 672), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(height, width)'], {}), '((height, width))\n', (655, 672), False, 'import pygame\n'), ((674, 716), 'pygame.display.set_caption', 'pygame.display.set_caption', (['"""Tic Tac Toe!"""'], {}), "('Tic Tac Toe!')\n", (700, 716), False, 'import pygame\n'), ((844, 884), 'pygame.font.Font', 'pygame.font.Font', (['"""freesansbold.ttf"""', '(25)'], {}), "('freesansbold.ttf', 25)\n", (860, 884), False, 'import pygame\n'), ((1372, 1409), 'numpy.zeros', 'np.zeros', (['(board_rows, board_columns)'], {}), '((board_rows, board_columns))\n', (1380, 1409), True, 'import numpy as np\n'), ((2344, 2436), 'pygame.draw.line', 'pygame.draw.line', (['screen', 'line_color', '(0, square_size)', '(width, square_size)', 'line_Width'], {}), '(screen, line_color, (0, square_size), (width, square_size),\n line_Width)\n', (2360, 2436), False, 'import pygame\n'), ((2487, 2587), 'pygame.draw.line', 'pygame.draw.line', (['screen', 'line_color', '(0, 2 * square_size)', '(width, 2 * square_size)', 'line_Width'], {}), '(screen, line_color, (0, 2 * square_size), (width, 2 *\n square_size), line_Width)\n', (2503, 2587), False, 'import pygame\n'), ((2627, 2721), 'pygame.draw.line', 'pygame.draw.line', (['screen', 'line_color', '(square_size, 0)', '(square_size, height)', 'line_Width'], {}), '(screen, line_color, (square_size, 0), (square_size, height\n ), line_Width)\n', (2643, 2721), False, 'import pygame\n'), ((2764, 2865), 'pygame.draw.line', 'pygame.draw.line', (['screen', 'line_color', '(2 * square_size, 0)', '(2 * square_size, height)', 'line_Width'], {}), '(screen, line_color, (2 * square_size, 0), (2 * square_size,\n height), line_Width)\n', (2780, 2865), False, 'import pygame\n'), ((4377, 4444), 'pygame.draw.line', 'pygame.draw.line', (['screen', 'color', '(15, posY)', '(width - 15, posY)', '(15)'], {}), '(screen, color, (15, posY), (width - 15, posY), 15)\n', (4393, 4444), False, 'import pygame\n'), ((4635, 4702), 'pygame.draw.line', 'pygame.draw.line', (['screen', 'color', '(posX, 15)', '(posX, width - 15)', '(15)'], {}), '(screen, color, (posX, 15), (posX, width - 15), 15)\n', (4651, 4702), False, 'import pygame\n'), ((4834, 4906), 'pygame.draw.line', 'pygame.draw.line', (['screen', 'color', '(15, height - 15)', '(width - 15, 15)', '(15)'], {}), '(screen, color, (15, height - 15), (width - 15, 15), 15)\n', (4850, 4906), False, 'import pygame\n'), ((5036, 5108), 'pygame.draw.line', 'pygame.draw.line', (['screen', 'color', '(15, 15)', '(width - 15, height - 15)', '(15)'], {}), '(screen, color, (15, 15), (width - 15, height - 15), 15)\n', (5052, 5108), False, 'import pygame\n'), ((5404, 5422), 'pygame.event.get', 'pygame.event.get', ([], {}), '()\n', (5420, 5422), False, 'import pygame\n'), ((7233, 7256), 'pygame.display.update', 'pygame.display.update', ([], {}), '()\n', (7254, 7256), False, 'import pygame\n'), ((5559, 5572), 'pygame.quit', 'pygame.quit', ([], {}), '()\n', (5570, 5572), False, 'import pygame\n'), ((5586, 5596), 'sys.exit', 'sys.exit', ([], {}), '()\n', (5594, 5596), False, 'import sys\n'), ((1867, 2065), 'pygame.draw.line', 'pygame.draw.line', (['screen', 'cross_color', '(col * square_size + space, row * square_size + square_size - space)', '(col * square_size + square_size - space, row * square_size + space)', 'cross_width'], {}), '(screen, cross_color, (col * square_size + space, row *\n square_size + square_size - space), (col * square_size + square_size -\n space, row * square_size + space), cross_width)\n', (1883, 2065), False, 'import pygame\n'), ((2099, 2297), 'pygame.draw.line', 'pygame.draw.line', (['screen', 'cross_color', '(col * square_size + space, row * square_size + space)', '(col * square_size + square_size - space, row * square_size + square_size -\n space)', 'cross_width'], {}), '(screen, cross_color, (col * square_size + space, row *\n square_size + space), (col * square_size + square_size - space, row *\n square_size + square_size - space), cross_width)\n', (2115, 2297), False, 'import pygame\n'), ((7154, 7167), 'pygame.quit', 'pygame.quit', ([], {}), '()\n', (7165, 7167), False, 'import pygame\n'), ((7185, 7195), 'sys.exit', 'sys.exit', ([], {}), '()\n', (7193, 7195), False, 'import sys\n')]
import random import numpy as np import heapq as hp import time from k_shortest_path import k_shortest_path_algorithm, k_shortest_path_all_destination def simulated_annealing_unsplittable_flows(graph, commodity_list, nb_iterations=10**5, nb_k_shortest_paths=10, verbose=0): nb_nodes = len(graph) nb_commodities = len(commodity_list) # Set the initial/final temperature and the temperature decrement T = T_init = 200 T_final = 1 dT = (T_final/T_init)**(1/nb_iterations) all_distances = compute_all_distances(graph) log_values = - np.log(1 - np.arange(0, 1, 0.001)) use_graph = [{neighbor : 0 for neighbor in graph[node]} for node in range(nb_nodes)] # Will contain the total flow used on each arc # Compute the k-shortest paths for each commodity and store them in possible_paths_per_commodity shortest_paths_per_origin = {} possible_paths_per_commodity = [] for commodity_index, commodity in enumerate(commodity_list): origin, destination, demand = commodity if origin not in shortest_paths_per_origin: shortest_paths_per_origin[origin] = k_shortest_path_all_destination(graph, origin, nb_k_shortest_paths) path_and_cost_list = shortest_paths_per_origin[origin][destination] possible_paths_per_commodity.append([remove_cycle_from_path(path) for path, cost in path_and_cost_list]) solution = [] fitness = 0 # Create an intial solution for commodity_index, commodity in enumerate(commodity_list): new_path_index = np.random.choice(len(possible_paths_per_commodity[commodity_index])) new_path = possible_paths_per_commodity[commodity_index][new_path_index] solution.append(new_path) fitness += update_fitness_and_use_graph(use_graph, graph, [], new_path, commodity[2]) # Main loop for iter_index in range(nb_iterations): if verbose and iter_index %1000 == 0: print(iter_index, fitness, end=' \r') commodity_index = random.randint(0, nb_commodities - 1) # Choose the commodity which will change its path during the iteration commodity = commodity_list[commodity_index] nb_possible_paths = len(possible_paths_per_commodity[commodity_index]) if nb_possible_paths < 5 or random.random() < 0.: if nb_possible_paths >= 10: index_to_remove = np.random.choice(len(possible_paths_per_commodity[commodity_index])) possible_paths_per_commodity[commodity_index].pop(index_to_remove) # Create a new possible path for the commodity : this procedure considers the current overflow of the arcs new_path = get_new_path(graph, use_graph, commodity, log_values, all_distances, T=3) possible_paths_per_commodity[commodity_index].append(new_path) else: # Choose a random new_path for the commodity new_path_index = np.random.choice(len(possible_paths_per_commodity[commodity_index])) new_path = possible_paths_per_commodity[commodity_index][new_path_index] # Change the path used by the commodity and modify the fitness accordingly new_fitness = fitness + update_fitness_and_use_graph(use_graph, graph, solution[commodity_index], new_path, commodity[2]) old_path = solution[commodity_index] solution[commodity_index] = new_path proba = np.exp((fitness - new_fitness) / T) T = T * dT # Keep the new solution according to the simulated annealing rule or return to the old solution if new_fitness <= fitness or random.random() < proba: fitness = new_fitness else: solution[commodity_index] = old_path update_fitness_and_use_graph(use_graph, graph, new_path, old_path, commodity[2]) # Modify use_graph return solution, fitness def update_fitness_and_use_graph(use_graph, graph, old_path, new_path, commodity_demand): # This function makes the updates necessary to reflect the fact that a commodity uses new_path instead of old_path # To do so, it updates use_graph (total flow going through eahc arc) and computes in delta_fitness delta_fitness = 0 for i in range(len(old_path) - 1): node1 = old_path[i] node2 = old_path[i+1] old_overload = max(use_graph[node1][node2] - graph[node1][node2], 0) use_graph[node1][node2] -= commodity_demand delta_fitness += max(use_graph[node1][node2] - graph[node1][node2], 0) - old_overload for i in range(len(new_path) - 1): node1 = new_path[i] node2 = new_path[i+1] old_overload = max(use_graph[node1][node2] - graph[node1][node2], 0) use_graph[node1][node2] += commodity_demand delta_fitness += max(use_graph[node1][node2] - graph[node1][node2], 0) - old_overload return delta_fitness def get_new_path(graph, use_graph, commodity, log_values, all_distances, T=1, overload_coeff=10**-2): # This functions create a random path for a commodity biased toward short path and arcs with a low overflow # To do so, an A* algorithm is applied with random arc cost and a penalisation of the overflow origin, destination, demand = commodity priority_q = [(0, origin, None)] # Priority queue storing the nodes to explore : encode with a binary tree parent_list = [None] * len(graph) distances = [None] * len(graph) while priority_q: value, current_node, parent_node = hp.heappop(priority_q) if distances[current_node] is None: parent_list[current_node] = parent_node distances[current_node] = value if current_node == destination: break for neighbor in graph[current_node]: if distances[neighbor] is None: arc_cost = 1 # Each arc has length 1 to guide toward shorter paths arc_cost += overload_coeff * max(0, demand + use_graph[current_node][neighbor] - graph[current_node][neighbor]) # Penalize the arc with high overflow arc_cost += log_values[int(random.random() * 1000)] # Add some randomness to the arc cost arc_cost += all_distances[neighbor][destination] # A* heuristic : distance to the target node hp.heappush(priority_q, (value + arc_cost, neighbor, current_node)) # Compute a reverse path according to parent_list path = [destination] current_node = destination while current_node != origin: current_node = parent_list[current_node] path.append(current_node) path.reverse() return path def get_new_path_2(graph, use_graph, commodity, all_distances, T=1, overload_coeff=None): origin, destination, demand = commodity current_node = origin new_path = [current_node] if overload_coeff is None: overload_coeff = 10**-3 i = 0 while current_node != destination: i+=1 if i%20==0: overload_coeff /= 10 neighbor_list = list(graph[current_node].keys()) arc_efficiency_list = [] l = [] for neighbor in neighbor_list: if True or neighbor in graph[current_node] and graph[current_node][neighbor] > 0: arc_efficiency_list.append(all_distances[neighbor][destination] + 1 + overload_coeff * max(0, demand + use_graph[current_node][neighbor] - graph[current_node][neighbor])) l.append(neighbor) arc_efficiency_list = np.array(arc_efficiency_list) neighbor_list = l proba = np.exp(- arc_efficiency_list * T) proba = proba/sum(proba) current_node = np.random.choice(neighbor_list, p=proba) new_path.append(current_node) return new_path def compute_all_distances(graph): nb_nodes = len(graph) all_distances = [] unitary_graph = [{neighbor : 1 for neighbor in graph[node]} for node in range(nb_nodes)] for initial_node in range(nb_nodes): parent_list, distances = dijkstra(unitary_graph, initial_node) for i in range(len(distances)): if distances[i] is None: distances[i] = 10.**10 all_distances.append(distances) return all_distances def dijkstra(graph, initial_node, destination_node=None): priority_q = [(0, initial_node, None)] parent_list = [None] * len(graph) distances = [None] * len(graph) while priority_q: value, current_node, parent_node = hp.heappop(priority_q) if distances[current_node] is None: parent_list[current_node] = parent_node distances[current_node] = value if current_node == destination_node: return parent_list, distances for neighbor in graph[current_node]: if distances[neighbor] is None: hp.heappush(priority_q, (value + graph[current_node][neighbor], neighbor, current_node)) return parent_list, distances def remove_cycle_from_path(path): is_in_path = set() new_path = [] for node in path: if node in is_in_path: while new_path[-1] != node: node_to_remove = new_path.pop() is_in_path.remove(node_to_remove) else: is_in_path.add(node) new_path.append(node) return new_path if __name__ == "__main__": pass
[ "random.randint", "heapq.heappush", "k_shortest_path.k_shortest_path_all_destination", "heapq.heappop", "random.random", "numpy.array", "numpy.exp", "numpy.arange", "numpy.random.choice" ]
[((2006, 2043), 'random.randint', 'random.randint', (['(0)', '(nb_commodities - 1)'], {}), '(0, nb_commodities - 1)\n', (2020, 2043), False, 'import random\n'), ((3400, 3435), 'numpy.exp', 'np.exp', (['((fitness - new_fitness) / T)'], {}), '((fitness - new_fitness) / T)\n', (3406, 3435), True, 'import numpy as np\n'), ((5476, 5498), 'heapq.heappop', 'hp.heappop', (['priority_q'], {}), '(priority_q)\n', (5486, 5498), True, 'import heapq as hp\n'), ((7501, 7530), 'numpy.array', 'np.array', (['arc_efficiency_list'], {}), '(arc_efficiency_list)\n', (7509, 7530), True, 'import numpy as np\n'), ((7574, 7606), 'numpy.exp', 'np.exp', (['(-arc_efficiency_list * T)'], {}), '(-arc_efficiency_list * T)\n', (7580, 7606), True, 'import numpy as np\n'), ((7665, 7705), 'numpy.random.choice', 'np.random.choice', (['neighbor_list'], {'p': 'proba'}), '(neighbor_list, p=proba)\n', (7681, 7705), True, 'import numpy as np\n'), ((8481, 8503), 'heapq.heappop', 'hp.heappop', (['priority_q'], {}), '(priority_q)\n', (8491, 8503), True, 'import heapq as hp\n'), ((1126, 1193), 'k_shortest_path.k_shortest_path_all_destination', 'k_shortest_path_all_destination', (['graph', 'origin', 'nb_k_shortest_paths'], {}), '(graph, origin, nb_k_shortest_paths)\n', (1157, 1193), False, 'from k_shortest_path import k_shortest_path_algorithm, k_shortest_path_all_destination\n'), ((577, 599), 'numpy.arange', 'np.arange', (['(0)', '(1)', '(0.001)'], {}), '(0, 1, 0.001)\n', (586, 599), True, 'import numpy as np\n'), ((2284, 2299), 'random.random', 'random.random', ([], {}), '()\n', (2297, 2299), False, 'import random\n'), ((3597, 3612), 'random.random', 'random.random', ([], {}), '()\n', (3610, 3612), False, 'import random\n'), ((6305, 6372), 'heapq.heappush', 'hp.heappush', (['priority_q', '(value + arc_cost, neighbor, current_node)'], {}), '(priority_q, (value + arc_cost, neighbor, current_node))\n', (6316, 6372), True, 'import heapq as hp\n'), ((8858, 8950), 'heapq.heappush', 'hp.heappush', (['priority_q', '(value + graph[current_node][neighbor], neighbor, current_node)'], {}), '(priority_q, (value + graph[current_node][neighbor], neighbor,\n current_node))\n', (8869, 8950), True, 'import heapq as hp\n'), ((6108, 6123), 'random.random', 'random.random', ([], {}), '()\n', (6121, 6123), False, 'import random\n')]
import sys import os from mpl_toolkits import mplot3d import numpy as np import matplotlib.pyplot as plt filePath_gt = sys.argv[1] filePath_results = sys.argv[2] gt = np.genfromtxt(filePath_gt, delimiter=",", names=["x", "y", "timestamp"]) results = np.genfromtxt(filePath_results, delimiter=",", names=["x", "y", "timestamp"]) COM_pix = np.genfromtxt("COM_pix.csv", delimiter=",", names=["v", "timestamp"]) COM_meter = np.genfromtxt("COM_robot.csv", delimiter=",", names=["y", "timestamp"]) fig1 = plt.figure() plt.plot(gt['timestamp'], gt['y'], 'b', label='ground truth') plt.plot(results['timestamp'], results['y'], 'r', label='tracker results', linewidth=3) plt.xlim(5000, 40000) plt.legend() plt.title('Tracker Validation') plt.xlabel('Time [ms]') plt.ylabel('y CoM [pixels]') plt.show() fig2 = plt.figure() plt.plot(gt['timestamp'], gt['x'], 'b', label='ground truth') plt.plot(results['timestamp'], results['x'], 'r', label='tracker results', linewidth=3) plt.xlim(5000, 40000) plt.legend() plt.title('Tracker Validation') plt.xlabel('Time [ms]') plt.ylabel('x CoM [pixels]') plt.show() fig3 = plt.figure() plt.plot(COM_pix['timestamp'], COM_pix['v'], 'g') plt.title('y CoM visual space') plt.xlim([30, 40]) plt.xlabel('Time [ms]') plt.ylabel('y CoM [pixels]') plt.show() fig4 = plt.figure() plt.plot(COM_meter['timestamp'], COM_meter['y'], 'k') plt.title('y CoM wrt robot frame') plt.xlim([30, 40]) plt.xlabel('Time [ms]') plt.ylabel('y CoM [meters]') plt.show() # ax = plt.axes(projection='3d') # ax.plot3D(x, y, timestamps, 'r')
[ "matplotlib.pyplot.title", "matplotlib.pyplot.xlim", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "matplotlib.pyplot.legend", "numpy.genfromtxt", "matplotlib.pyplot.figure", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel" ]
[((171, 243), 'numpy.genfromtxt', 'np.genfromtxt', (['filePath_gt'], {'delimiter': '""","""', 'names': "['x', 'y', 'timestamp']"}), "(filePath_gt, delimiter=',', names=['x', 'y', 'timestamp'])\n", (184, 243), True, 'import numpy as np\n'), ((254, 331), 'numpy.genfromtxt', 'np.genfromtxt', (['filePath_results'], {'delimiter': '""","""', 'names': "['x', 'y', 'timestamp']"}), "(filePath_results, delimiter=',', names=['x', 'y', 'timestamp'])\n", (267, 331), True, 'import numpy as np\n'), ((342, 411), 'numpy.genfromtxt', 'np.genfromtxt', (['"""COM_pix.csv"""'], {'delimiter': '""","""', 'names': "['v', 'timestamp']"}), "('COM_pix.csv', delimiter=',', names=['v', 'timestamp'])\n", (355, 411), True, 'import numpy as np\n'), ((424, 495), 'numpy.genfromtxt', 'np.genfromtxt', (['"""COM_robot.csv"""'], {'delimiter': '""","""', 'names': "['y', 'timestamp']"}), "('COM_robot.csv', delimiter=',', names=['y', 'timestamp'])\n", (437, 495), True, 'import numpy as np\n'), ((504, 516), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (514, 516), True, 'import matplotlib.pyplot as plt\n'), ((517, 578), 'matplotlib.pyplot.plot', 'plt.plot', (["gt['timestamp']", "gt['y']", '"""b"""'], {'label': '"""ground truth"""'}), "(gt['timestamp'], gt['y'], 'b', label='ground truth')\n", (525, 578), True, 'import matplotlib.pyplot as plt\n'), ((579, 670), 'matplotlib.pyplot.plot', 'plt.plot', (["results['timestamp']", "results['y']", '"""r"""'], {'label': '"""tracker results"""', 'linewidth': '(3)'}), "(results['timestamp'], results['y'], 'r', label='tracker results',\n linewidth=3)\n", (587, 670), True, 'import matplotlib.pyplot as plt\n'), ((667, 688), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(5000)', '(40000)'], {}), '(5000, 40000)\n', (675, 688), True, 'import matplotlib.pyplot as plt\n'), ((689, 701), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (699, 701), True, 'import matplotlib.pyplot as plt\n'), ((702, 733), 'matplotlib.pyplot.title', 'plt.title', (['"""Tracker Validation"""'], {}), "('Tracker Validation')\n", (711, 733), True, 'import matplotlib.pyplot as plt\n'), ((734, 757), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time [ms]"""'], {}), "('Time [ms]')\n", (744, 757), True, 'import matplotlib.pyplot as plt\n'), ((758, 786), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""y CoM [pixels]"""'], {}), "('y CoM [pixels]')\n", (768, 786), True, 'import matplotlib.pyplot as plt\n'), ((787, 797), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (795, 797), True, 'import matplotlib.pyplot as plt\n'), ((807, 819), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (817, 819), True, 'import matplotlib.pyplot as plt\n'), ((820, 881), 'matplotlib.pyplot.plot', 'plt.plot', (["gt['timestamp']", "gt['x']", '"""b"""'], {'label': '"""ground truth"""'}), "(gt['timestamp'], gt['x'], 'b', label='ground truth')\n", (828, 881), True, 'import matplotlib.pyplot as plt\n'), ((882, 973), 'matplotlib.pyplot.plot', 'plt.plot', (["results['timestamp']", "results['x']", '"""r"""'], {'label': '"""tracker results"""', 'linewidth': '(3)'}), "(results['timestamp'], results['x'], 'r', label='tracker results',\n linewidth=3)\n", (890, 973), True, 'import matplotlib.pyplot as plt\n'), ((970, 991), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(5000)', '(40000)'], {}), '(5000, 40000)\n', (978, 991), True, 'import matplotlib.pyplot as plt\n'), ((992, 1004), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1002, 1004), True, 'import matplotlib.pyplot as plt\n'), ((1005, 1036), 'matplotlib.pyplot.title', 'plt.title', (['"""Tracker Validation"""'], {}), "('Tracker Validation')\n", (1014, 1036), True, 'import matplotlib.pyplot as plt\n'), ((1037, 1060), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time [ms]"""'], {}), "('Time [ms]')\n", (1047, 1060), True, 'import matplotlib.pyplot as plt\n'), ((1061, 1089), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""x CoM [pixels]"""'], {}), "('x CoM [pixels]')\n", (1071, 1089), True, 'import matplotlib.pyplot as plt\n'), ((1090, 1100), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1098, 1100), True, 'import matplotlib.pyplot as plt\n'), ((1109, 1121), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1119, 1121), True, 'import matplotlib.pyplot as plt\n'), ((1122, 1171), 'matplotlib.pyplot.plot', 'plt.plot', (["COM_pix['timestamp']", "COM_pix['v']", '"""g"""'], {}), "(COM_pix['timestamp'], COM_pix['v'], 'g')\n", (1130, 1171), True, 'import matplotlib.pyplot as plt\n'), ((1172, 1203), 'matplotlib.pyplot.title', 'plt.title', (['"""y CoM visual space"""'], {}), "('y CoM visual space')\n", (1181, 1203), True, 'import matplotlib.pyplot as plt\n'), ((1204, 1222), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[30, 40]'], {}), '([30, 40])\n', (1212, 1222), True, 'import matplotlib.pyplot as plt\n'), ((1223, 1246), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time [ms]"""'], {}), "('Time [ms]')\n", (1233, 1246), True, 'import matplotlib.pyplot as plt\n'), ((1247, 1275), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""y CoM [pixels]"""'], {}), "('y CoM [pixels]')\n", (1257, 1275), True, 'import matplotlib.pyplot as plt\n'), ((1276, 1286), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1284, 1286), True, 'import matplotlib.pyplot as plt\n'), ((1295, 1307), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1305, 1307), True, 'import matplotlib.pyplot as plt\n'), ((1308, 1361), 'matplotlib.pyplot.plot', 'plt.plot', (["COM_meter['timestamp']", "COM_meter['y']", '"""k"""'], {}), "(COM_meter['timestamp'], COM_meter['y'], 'k')\n", (1316, 1361), True, 'import matplotlib.pyplot as plt\n'), ((1362, 1396), 'matplotlib.pyplot.title', 'plt.title', (['"""y CoM wrt robot frame"""'], {}), "('y CoM wrt robot frame')\n", (1371, 1396), True, 'import matplotlib.pyplot as plt\n'), ((1397, 1415), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[30, 40]'], {}), '([30, 40])\n', (1405, 1415), True, 'import matplotlib.pyplot as plt\n'), ((1416, 1439), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time [ms]"""'], {}), "('Time [ms]')\n", (1426, 1439), True, 'import matplotlib.pyplot as plt\n'), ((1440, 1468), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""y CoM [meters]"""'], {}), "('y CoM [meters]')\n", (1450, 1468), True, 'import matplotlib.pyplot as plt\n'), ((1469, 1479), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1477, 1479), True, 'import matplotlib.pyplot as plt\n')]
""" Module for guiding construction of the Wavelength Image .. include common links, assuming primary doc root is up one directory .. include:: ../links.rst """ import inspect import numpy as np import os from pypeit import msgs from pypeit import utils from pypeit import datamodel from IPython import embed class WaveImage(datamodel.DataContainer): version = '1.0.0' # I/O output_to_disk = None #('WVTILTS_IMAGE', 'WVTILTS_FULLMASK', 'WVTILTS_DETECTOR_CONTAINER') hdu_prefix = None # Master fun master_type = 'Wave' master_file_format = 'fits' datamodel = { 'image': dict(otype=np.ndarray, atype=np.floating, desc='2D Wavelength image'), 'PYP_SPEC': dict(otype=str, desc='PypeIt spectrograph name'), } def __init__(self, image, PYP_SPEC=None): # Parse args, _, _, values = inspect.getargvalues(inspect.currentframe()) d = dict([(k,values[k]) for k in args[1:]]) # Setup the DataContainer datamodel.DataContainer.__init__(self, d=d) class BuildWaveImage(object): """ Class to generate the Wavelength Image Args: slits (:class:`pypeit.edgetrace.SlitTraceSet`): Object holding the slit edge locations tilts (np.ndarray or None): Tilt image wv_calib (dict or None): wavelength solution dictionary Parameters are read from wv_calib['par'] spectrograph (:class:`pypeit.spectrographs.spectrograph.Spectrograph`): The `Spectrograph` instance that sets the instrument used to take the observations. Used to set :attr:`spectrograph`. det (int or None): Attributes: image (np.ndarray): Wavelength image steps (list): List of the processing steps performed """ master_type = 'Wave' # @classmethod # def from_master_file(cls, master_file): # """ # # Args: # master_file (str): # # Returns: # waveimage.WaveImage: # # """ # # Spectrograph # spectrograph, extras = masterframe.items_from_master_file(master_file) # head0 = extras[0] # # Master info # master_dir = head0['MSTRDIR'] # master_key = head0['MSTRKEY'] # # Instantiate # slf = cls(None, None, None, spectrograph, None, master_dir=master_dir, # master_key=master_key, reuse_masters=True) # slf.image = slf.load(ifile=master_file) # # Return # return slf # TODO: Is maskslits ever anything besides slits.mask? (e.g., see calibrations.py call) def __init__(self, slits, tilts, wv_calib, spectrograph, det): # MasterFrame #masterframe.MasterFrame.__init__(self, self.master_type, master_dir=master_dir, # master_key=master_key, reuse_masters=reuse_masters) # Required parameters self.spectrograph = spectrograph self.det = det # TODO: Do we need to assign slits to self? self.slits = slits self.tilts = tilts self.wv_calib = wv_calib if self.slits is None: self.slitmask = None self.slit_spat_pos = None else: # NOTE: This uses the pad defined by EdgeTraceSetPar self.slitmask = self.slits.slit_img() # This selects the coordinates for the tweaked edges if # they exist, original otherwise. self.slit_spat_pos = self.slits.spatial_coordinates() # For echelle order, primarily # TODO: only echelle is ever used. Do we need to keep the whole # thing? self.par = wv_calib['par'] if wv_calib is not None else None # Main output self.image = None self.steps = [] def build_wave(self): """ Main algorithm to build the wavelength image Returns: `numpy.ndarray`_: The wavelength image. """ # Loop on slits ok_slits = np.where(np.invert(self.slits.mask))[0] self.image = np.zeros_like(self.tilts) nspec = self.slitmask.shape[0] # Error checking on the wv_calib #if (nspec-1) != int(self.wv_calib[str(0)]['fmax']): # msgs.error('Your wavelength fits used inconsistent normalization. Something is wrong!') # If this is echelle print out a status message and do some error checking if self.par['echelle']: msgs.info('Evaluating 2-d wavelength solution for echelle....') if len(self.wv_calib['fit2d']['orders']) != len(ok_slits): msgs.error('wv_calib and ok_slits do not line up. Something is very wrong!') # Unpack some 2-d fit parameters if this is echelle for slit in ok_slits: thismask = (self.slitmask == slit) if self.par['echelle']: # TODO: Put this in `SlitTraceSet`? order, indx = self.spectrograph.slit2order(self.slit_spat_pos[slit]) # evaluate solution self.image[thismask] = utils.func_val(self.wv_calib['fit2d']['coeffs'], self.tilts[thismask], self.wv_calib['fit2d']['func2d'], x2=np.ones_like(self.tilts[thismask])*order, minx=self.wv_calib['fit2d']['min_spec'], maxx=self.wv_calib['fit2d']['max_spec'], minx2=self.wv_calib['fit2d']['min_order'], maxx2=self.wv_calib['fit2d']['max_order']) self.image[thismask] /= order else: iwv_calib = self.wv_calib[str(slit)] self.image[thismask] = utils.func_val(iwv_calib['fitc'], self.tilts[thismask], iwv_calib['function'], minx=iwv_calib['fmin'], maxx=iwv_calib['fmax']) # Return self.steps.append(inspect.stack()[0][3]) return WaveImage(self.image, PYP_SPEC=self.spectrograph.spectrograph) def __repr__(self): # Generate sets string txt = '<{:s}: >'.format(self.__class__.__name__) return txt
[ "numpy.zeros_like", "numpy.ones_like", "numpy.invert", "pypeit.msgs.error", "pypeit.datamodel.DataContainer.__init__", "pypeit.utils.func_val", "inspect.currentframe", "inspect.stack", "pypeit.msgs.info" ]
[((997, 1040), 'pypeit.datamodel.DataContainer.__init__', 'datamodel.DataContainer.__init__', (['self'], {'d': 'd'}), '(self, d=d)\n', (1029, 1040), False, 'from pypeit import datamodel\n'), ((4079, 4104), 'numpy.zeros_like', 'np.zeros_like', (['self.tilts'], {}), '(self.tilts)\n', (4092, 4104), True, 'import numpy as np\n'), ((879, 901), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (899, 901), False, 'import inspect\n'), ((4476, 4539), 'pypeit.msgs.info', 'msgs.info', (['"""Evaluating 2-d wavelength solution for echelle...."""'], {}), "('Evaluating 2-d wavelength solution for echelle....')\n", (4485, 4539), False, 'from pypeit import msgs\n'), ((4027, 4053), 'numpy.invert', 'np.invert', (['self.slits.mask'], {}), '(self.slits.mask)\n', (4036, 4053), True, 'import numpy as np\n'), ((4627, 4703), 'pypeit.msgs.error', 'msgs.error', (['"""wv_calib and ok_slits do not line up. Something is very wrong!"""'], {}), "('wv_calib and ok_slits do not line up. Something is very wrong!')\n", (4637, 4703), False, 'from pypeit import msgs\n'), ((5949, 6080), 'pypeit.utils.func_val', 'utils.func_val', (["iwv_calib['fitc']", 'self.tilts[thismask]', "iwv_calib['function']"], {'minx': "iwv_calib['fmin']", 'maxx': "iwv_calib['fmax']"}), "(iwv_calib['fitc'], self.tilts[thismask], iwv_calib[\n 'function'], minx=iwv_calib['fmin'], maxx=iwv_calib['fmax'])\n", (5963, 6080), False, 'from pypeit import utils\n'), ((6285, 6300), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (6298, 6300), False, 'import inspect\n'), ((5363, 5397), 'numpy.ones_like', 'np.ones_like', (['self.tilts[thismask]'], {}), '(self.tilts[thismask])\n', (5375, 5397), True, 'import numpy as np\n')]
#!/usr/bin/env python from ATK.Core import DoubleInPointerFilter, DoubleOutPointerFilter from ATK.Delay import DoubleUniversalVariableDelayLineFilter from ATK.EQ import DoubleSecondOrderLowPassFilter from ATK.Tools import DoubleWhiteNoiseGeneratorFilter import matplotlib.pyplot as plt sample_rate = 96000 def filter(input, blend=0, feedback=0, feedforward=1): import numpy as np output = np.zeros(input.shape, dtype=np.float64) infilter = DoubleInPointerFilter(input, False) infilter.set_input_sampling_rate(sample_rate) noisefilter = DoubleWhiteNoiseGeneratorFilter() noisefilter.set_input_sampling_rate(sample_rate) noisefilter.set_offset(50e-3 * sample_rate) noisefilter.set_volume(25e-3 * sample_rate) lownoisefilter = DoubleSecondOrderLowPassFilter() lownoisefilter.set_input_sampling_rate(sample_rate) lownoisefilter.set_cut_frequency(5) lownoisefilter.set_input_port(0, noisefilter, 0) delayfilter = DoubleUniversalVariableDelayLineFilter(5000) delayfilter.set_input_sampling_rate(sample_rate) delayfilter.set_input_port(0, infilter, 0) delayfilter.set_input_port(1, lownoisefilter, 0) delayfilter.set_blend(blend) delayfilter.set_feedback(feedback) delayfilter.set_feedforward(feedforward) outfilter = DoubleOutPointerFilter(output, False) outfilter.set_input_sampling_rate(sample_rate) outfilter.set_input_port(0, delayfilter, 0) outfilter.process(input.shape[1]) return output if __name__ == "__main__": import numpy as np size = 960000 x = np.arange(size, dtype=np.float64).reshape(1, -1) / sample_rate d = np.sin(x * 2 * np.pi * 1000) np.savetxt("input.txt", d) out = filter(d, feedforward=1, blend=0.7, feedback=-0.7) np.savetxt("output.txt", out)
[ "ATK.Core.DoubleInPointerFilter", "ATK.Delay.DoubleUniversalVariableDelayLineFilter", "ATK.EQ.DoubleSecondOrderLowPassFilter", "ATK.Core.DoubleOutPointerFilter", "ATK.Tools.DoubleWhiteNoiseGeneratorFilter", "numpy.zeros", "numpy.savetxt", "numpy.sin", "numpy.arange" ]
[((397, 436), 'numpy.zeros', 'np.zeros', (['input.shape'], {'dtype': 'np.float64'}), '(input.shape, dtype=np.float64)\n', (405, 436), True, 'import numpy as np\n'), ((451, 486), 'ATK.Core.DoubleInPointerFilter', 'DoubleInPointerFilter', (['input', '(False)'], {}), '(input, False)\n', (472, 486), False, 'from ATK.Core import DoubleInPointerFilter, DoubleOutPointerFilter\n'), ((552, 585), 'ATK.Tools.DoubleWhiteNoiseGeneratorFilter', 'DoubleWhiteNoiseGeneratorFilter', ([], {}), '()\n', (583, 585), False, 'from ATK.Tools import DoubleWhiteNoiseGeneratorFilter\n'), ((753, 785), 'ATK.EQ.DoubleSecondOrderLowPassFilter', 'DoubleSecondOrderLowPassFilter', ([], {}), '()\n', (783, 785), False, 'from ATK.EQ import DoubleSecondOrderLowPassFilter\n'), ((948, 992), 'ATK.Delay.DoubleUniversalVariableDelayLineFilter', 'DoubleUniversalVariableDelayLineFilter', (['(5000)'], {}), '(5000)\n', (986, 992), False, 'from ATK.Delay import DoubleUniversalVariableDelayLineFilter\n'), ((1268, 1305), 'ATK.Core.DoubleOutPointerFilter', 'DoubleOutPointerFilter', (['output', '(False)'], {}), '(output, False)\n', (1290, 1305), False, 'from ATK.Core import DoubleInPointerFilter, DoubleOutPointerFilter\n'), ((1597, 1625), 'numpy.sin', 'np.sin', (['(x * 2 * np.pi * 1000)'], {}), '(x * 2 * np.pi * 1000)\n', (1603, 1625), True, 'import numpy as np\n'), ((1629, 1655), 'numpy.savetxt', 'np.savetxt', (['"""input.txt"""', 'd'], {}), "('input.txt', d)\n", (1639, 1655), True, 'import numpy as np\n'), ((1717, 1746), 'numpy.savetxt', 'np.savetxt', (['"""output.txt"""', 'out'], {}), "('output.txt', out)\n", (1727, 1746), True, 'import numpy as np\n'), ((1528, 1561), 'numpy.arange', 'np.arange', (['size'], {'dtype': 'np.float64'}), '(size, dtype=np.float64)\n', (1537, 1561), True, 'import numpy as np\n')]
import cv2 import numpy as np import skfmm import skimage from numpy import ma def get_mask(sx, sy, scale, step_size): size = int(step_size // scale) * 2 + 1 mask = np.zeros((size, size)) for i in range(size): for j in range(size): if ((i + 0.5) - (size // 2 + sx)) ** 2 + \ ((j + 0.5) - (size // 2 + sy)) ** 2 <= \ step_size ** 2 \ and ((i + 0.5) - (size // 2 + sx)) ** 2 + \ ((j + 0.5) - (size // 2 + sy)) ** 2 > \ (step_size - 1) ** 2: mask[i, j] = 1 mask[size // 2, size // 2] = 1 return mask def get_dist(sx, sy, scale, step_size): size = int(step_size // scale) * 2 + 1 mask = np.zeros((size, size)) + 1e-10 for i in range(size): for j in range(size): if ((i + 0.5) - (size // 2 + sx)) ** 2 + \ ((j + 0.5) - (size // 2 + sy)) ** 2 <= \ step_size ** 2: mask[i, j] = max(5, (((i + 0.5) - (size // 2 + sx)) ** 2 + ((j + 0.5) - (size // 2 + sy)) ** 2) ** 0.5) return mask class FMMPlanner(): def __init__(self, traversible, scale=1, step_size=5): self.scale = scale self.step_size = step_size if scale != 1.: self.traversible = cv2.resize(traversible, (traversible.shape[1] // scale, traversible.shape[0] // scale), interpolation=cv2.INTER_NEAREST) self.traversible = np.rint(self.traversible) else: self.traversible = traversible self.du = int(self.step_size / (self.scale * 1.)) self.fmm_dist = None def set_goal(self, goal, auto_improve=False): traversible_ma = ma.masked_values(self.traversible * 1, 0) goal_x, goal_y = int(goal[0] / (self.scale * 1.)), \ int(goal[1] / (self.scale * 1.)) if self.traversible[goal_x, goal_y] == 0. and auto_improve: goal_x, goal_y = self._find_nearest_goal([goal_x, goal_y]) traversible_ma[goal_x, goal_y] = 0 dd = skfmm.distance(traversible_ma, dx=1) dd = ma.filled(dd, np.max(dd) + 1) self.fmm_dist = dd return def set_multi_goal(self, goal_map): traversible_ma = ma.masked_values(self.traversible * 1, 0) traversible_ma[goal_map == 1] = 0 dd = skfmm.distance(traversible_ma, dx=1) dd = ma.filled(dd, np.max(dd) + 1) self.fmm_dist = dd return def get_short_term_goal(self, state): scale = self.scale * 1. state = [x / scale for x in state] dx, dy = state[0] - int(state[0]), state[1] - int(state[1]) mask = get_mask(dx, dy, scale, self.step_size) dist_mask = get_dist(dx, dy, scale, self.step_size) state = [int(x) for x in state] dist = np.pad(self.fmm_dist, self.du, 'constant', constant_values=self.fmm_dist.shape[0] ** 2) subset = dist[state[0]:state[0] + 2 * self.du + 1, state[1]:state[1] + 2 * self.du + 1] assert subset.shape[0] == 2 * self.du + 1 and \ subset.shape[1] == 2 * self.du + 1, \ "Planning error: unexpected subset shape {}".format(subset.shape) subset *= mask subset += (1 - mask) * self.fmm_dist.shape[0] ** 2 distance = subset[self.du,self.du] if subset[self.du, self.du] < 0.25 * 100 / 5.: # 25cm stop = True else: stop = False subset -= subset[self.du, self.du] ratio1 = subset / dist_mask subset[ratio1 < -1.5] = 1 (stg_x, stg_y) = np.unravel_index(np.argmin(subset), subset.shape) #print(subset[stg_x,stg_y]) if subset[stg_x, stg_y] > -0.0001: replan = True else: replan = False return (stg_x + state[0] - self.du) * scale, \ (stg_y + state[1] - self.du) * scale, distance, stop def _find_nearest_goal(self, goal): traversible = skimage.morphology.binary_dilation( np.zeros(self.traversible.shape), skimage.morphology.disk(2)) != True traversible = traversible * 1. planner = FMMPlanner(traversible) planner.set_goal(goal) mask = self.traversible dist_map = planner.fmm_dist * mask dist_map[dist_map == 0] = dist_map.max() goal = np.unravel_index(dist_map.argmin(), dist_map.shape) return goal
[ "numpy.pad", "numpy.ma.masked_values", "skfmm.distance", "numpy.zeros", "skimage.morphology.disk", "numpy.argmin", "numpy.rint", "numpy.max", "cv2.resize" ]
[((175, 197), 'numpy.zeros', 'np.zeros', (['(size, size)'], {}), '((size, size))\n', (183, 197), True, 'import numpy as np\n'), ((737, 759), 'numpy.zeros', 'np.zeros', (['(size, size)'], {}), '((size, size))\n', (745, 759), True, 'import numpy as np\n'), ((1898, 1939), 'numpy.ma.masked_values', 'ma.masked_values', (['(self.traversible * 1)', '(0)'], {}), '(self.traversible * 1, 0)\n', (1914, 1939), False, 'from numpy import ma\n'), ((2243, 2279), 'skfmm.distance', 'skfmm.distance', (['traversible_ma'], {'dx': '(1)'}), '(traversible_ma, dx=1)\n', (2257, 2279), False, 'import skfmm\n'), ((2431, 2472), 'numpy.ma.masked_values', 'ma.masked_values', (['(self.traversible * 1)', '(0)'], {}), '(self.traversible * 1, 0)\n', (2447, 2472), False, 'from numpy import ma\n'), ((2528, 2564), 'skfmm.distance', 'skfmm.distance', (['traversible_ma'], {'dx': '(1)'}), '(traversible_ma, dx=1)\n', (2542, 2564), False, 'import skfmm\n'), ((3008, 3100), 'numpy.pad', 'np.pad', (['self.fmm_dist', 'self.du', '"""constant"""'], {'constant_values': '(self.fmm_dist.shape[0] ** 2)'}), "(self.fmm_dist, self.du, 'constant', constant_values=self.fmm_dist.\n shape[0] ** 2)\n", (3014, 3100), True, 'import numpy as np\n'), ((1372, 1497), 'cv2.resize', 'cv2.resize', (['traversible', '(traversible.shape[1] // scale, traversible.shape[0] // scale)'], {'interpolation': 'cv2.INTER_NEAREST'}), '(traversible, (traversible.shape[1] // scale, traversible.shape[0\n ] // scale), interpolation=cv2.INTER_NEAREST)\n', (1382, 1497), False, 'import cv2\n'), ((1651, 1676), 'numpy.rint', 'np.rint', (['self.traversible'], {}), '(self.traversible)\n', (1658, 1676), True, 'import numpy as np\n'), ((3830, 3847), 'numpy.argmin', 'np.argmin', (['subset'], {}), '(subset)\n', (3839, 3847), True, 'import numpy as np\n'), ((2307, 2317), 'numpy.max', 'np.max', (['dd'], {}), '(dd)\n', (2313, 2317), True, 'import numpy as np\n'), ((2592, 2602), 'numpy.max', 'np.max', (['dd'], {}), '(dd)\n', (2598, 2602), True, 'import numpy as np\n'), ((4244, 4276), 'numpy.zeros', 'np.zeros', (['self.traversible.shape'], {}), '(self.traversible.shape)\n', (4252, 4276), True, 'import numpy as np\n'), ((4290, 4316), 'skimage.morphology.disk', 'skimage.morphology.disk', (['(2)'], {}), '(2)\n', (4313, 4316), False, 'import skimage\n')]
from CNS_UDP_FAST import CNS import numpy as np import time import random class ENVCNS(CNS): def __init__(self, Name, IP, PORT, Monitoring_ENV=None): super(ENVCNS, self).__init__(threrad_name=Name, CNS_IP=IP, CNS_Port=PORT, Remote_IP='192.168.0.29', Remote_Port=PORT, Max_len=10) self.Monitoring_ENV = Monitoring_ENV self.Name = Name # = id self.AcumulatedReward = 0 self.ENVStep = 0 self.LoggerPath = 'DB' self.want_tick = 5 # 1sec self.Loger_txt = '' self.input_info = [ # (para, x_round, x_min, x_max), (x_min=0, x_max=0 is not normalized.) ('BHV142', 1, 0, 0), # Letdown(HV142) ] self.action_space = 1 self.observation_space = len(self.input_info) # ENV Logger def ENVlogging(self, s): cr_time = time.strftime('%c', time.localtime(time.time())) if self.ENVStep == 0: with open(f'{self.Name}.txt', 'a') as f: f.write('==' * 20 + '\n') f.write(f'[{cr_time}]\n') f.write('==' * 20 + '\n') else: with open(f'{self.Name}.txt', 'a') as f: f.write(f'[{cr_time}] {self.Loger_txt}\n') def normalize(self, x, x_round, x_min, x_max): if x_max == 0 and x_min == 0: # It means X value is not normalized. x = x / x_round else: x = x_max if x >= x_max else x x = x_min if x <= x_min else x x = (x - x_min) / (x_max - x_min) return x def get_state(self): state = [] for para, x_round, x_min, x_max in self.input_info: if para in self.mem.keys(): state.append(self.normalize(self.mem[para]['Val'], x_round, x_min, x_max)) else: # ADD logic ----- 계산된 값을 사용하고 싶을 때 pass # state = [self.mem[para]['Val'] / Round_val for para, Round_val in self.input_info] self.Loger_txt += f'{state}\t' return np.array(state) def get_reward(self): """ R => _ :return: """ r = 0 self.Loger_txt += f'R:{r}\t' return r def get_done(self, r): V = { 'Dumy': 0 } r = self.normalize(r, 1, 0, 2) d = False self.Loger_txt += f'{d}\t' return d, self.normalize(r, 1, 0, 2) def _send_control_save(self, zipParaVal): super(ENVCNS, self)._send_control_save(para=zipParaVal[0], val=zipParaVal[1]) def send_act(self, A): """ A 에 해당하는 액션을 보내고 나머지는 자동 E.x) self._send_control_save(['KSWO115'], [0]) ... self._send_control_to_cns() :param A: A 액션 [0, 0, 0] <- act space에 따라서 :return: AMod: 수정된 액션 """ AMod = A V = { 'CNSTime': self.mem['KCNTOMS']['Val'], 'Delta_T': self.mem['TDELTA']['Val'], 'ChargingVV': self.mem['BFV122']['Val'], 'ChargingVM': self.mem['KLAMPO95']['Val'], # 1 m 0 a 'LetDownSet': self.mem['ZINST36']['Val'], } ActOrderBook = { 'ChargingValveOpen': (['KSWO101', 'KSWO102'], [0, 1]), 'ChargingValveStay': (['KSWO101', 'KSWO102'], [0, 0]), 'ChargingValveClase': (['KSWO101', 'KSWO102'], [1, 0]), 'ChargingEdit': (['BFV122'], [0.12]), 'LetdownValveOpen': (['KSWO231', 'KSWO232'], [0, 1]), 'LetdownValveStay': (['KSWO231', 'KSWO232'], [0, 0]), 'LetdownValveClose': (['KSWO231', 'KSWO232'], [1, 0]), 'PZRBackHeaterOff': (['KSWO125'], [0]), 'PZRBackHeaterOn': (['KSWO125'], [1]), 'PZRProHeaterMan': (['KSWO120'], [1]), 'PZRProHeaterAuto': (['KSWO120'], [0]), 'PZRProHeaterDown': (['KSWO121', 'KSWO122'], [1, 0]), 'PZRProHeaterStay': (['KSWO121', 'KSWO122'], [0, 0]), 'PZRProHeaterUp': (['KSWO121', 'KSWO122'], [0, 1]), 'LetDownSetDown': (['KSWO90', 'KSWO91'], [1, 0]), 'LetDownSetStay': (['KSWO90', 'KSWO91'], [0, 0]), 'LetDownSetUP': (['KSWO90', 'KSWO91'], [0, 1]), 'ChangeDelta': (['TDELTA'], [1.0]), 'ChargingAuto': (['KSWO100'], [0]) } # Delta # if V['Delta_T'] != 1: self._send_control_save(ActOrderBook['ChangeDelta']) # Done Act self._send_control_to_cns() return AMod def SkipAct(self): ActOrderBook = { 'Dumy': (['Dumy_para'], [0]), } # Skip or Reset Act # self._send_control_save(ActOrderBook['LetdownValveStay']) # Done Act self._send_control_to_cns() return 0 def step(self, A, mean_, std_): """ A를 받고 1 step 전진 :param A: [Act], numpy.ndarry, Act는 numpy.float32 :return: 최신 state와 reward done 반환 """ # Old Data (time t) --------------------------------------- AMod = self.send_act(A) self.want_tick = int(10) if self.Monitoring_ENV is not None: self.Monitoring_ENV.push_ENV_val(i=self.Name, Dict_val={f'{Para}': self.mem[f'{Para}']['Val'] for Para in ['BHV142', 'BFV122', 'ZINST65', 'ZINST63']} ) self.Monitoring_ENV.push_ENV_ActDis(i=self.Name, Dict_val={'Mean': mean_, 'Std': std_} ) # New Data (time t+1) ------------------------------------- super(ENVCNS, self).step() self._append_val_to_list() self.ENVStep += 1 reward = self.get_reward() done, reward = self.get_done(reward) if self.Monitoring_ENV is not None: self.Monitoring_ENV.push_ENV_reward(i=self.Name, Dict_val={'R': reward, 'AcuR': self.AcumulatedReward, 'Done': done}) next_state = self.get_state() # ---------------------------------------------------------- self.ENVlogging(s=self.Loger_txt) # self.Loger_txt = f'{next_state}\t' self.Loger_txt = '' return next_state, reward, done, AMod def reset(self, file_name): # 1] CNS 상태 초기화 및 초기화된 정보 메모리에 업데이트 super(ENVCNS, self).reset(initial_nub=1, mal=True, mal_case=35, mal_opt=1, mal_time=450, file_name=file_name) # 2] 업데이트된 'Val'를 'List'에 추가 및 ENVLogging 초기화 self._append_val_to_list() self.ENVlogging('') # 3] 'Val'을 상태로 제작후 반환 state = self.get_state() # 4] 보상 누적치 및 ENVStep 초기화 self.AcumulatedReward = 0 self.ENVStep = 0 if self.Monitoring_ENV is not None: self.Monitoring_ENV.init_ENV_val(self.Name) # 5] FIX RADVAL self.FixedRad = random.randint(0, 20) * 5 self.FixedTime = 0 self.FixedTemp = 0 return state if __name__ == '__main__': # ENVCNS TEST env = ENVCNS(Name='Env1', IP='192.168.0.101', PORT=int(f'7101')) # Run for _ in range(1, 2): env.reset(file_name=f'Ep{_}') start = time.time() for _ in range(0, 300): A = 0 next_state, reward, done, AMod = env.step(A, std_=1, mean_=0) if done: print(f'END--{start}->{time.time()} [{time.time()-start}]') break
[ "numpy.array", "random.randint", "time.time" ]
[((2121, 2136), 'numpy.array', 'np.array', (['state'], {}), '(state)\n', (2129, 2136), True, 'import numpy as np\n'), ((7354, 7365), 'time.time', 'time.time', ([], {}), '()\n', (7363, 7365), False, 'import time\n'), ((7046, 7067), 'random.randint', 'random.randint', (['(0)', '(20)'], {}), '(0, 20)\n', (7060, 7067), False, 'import random\n'), ((967, 978), 'time.time', 'time.time', ([], {}), '()\n', (976, 978), False, 'import time\n'), ((7550, 7561), 'time.time', 'time.time', ([], {}), '()\n', (7559, 7561), False, 'import time\n'), ((7565, 7576), 'time.time', 'time.time', ([], {}), '()\n', (7574, 7576), False, 'import time\n')]
import argparse import math import os from datetime import datetime import h5py import numpy as np import plyfile from matplotlib import cm import rospy import rospkg import ros_numpy import math import sys import cv2 from sensor_msgs.msg import PointCloud from geometry_msgs.msg import Point32 import sensor_msgs.point_cloud2 as pc2 import pcl from pcl_helper import * from std_msgs.msg import Header class datasetVis(object): def __init__(self): rospy.init_node('tutorial', anonymous=True) self.rate = rospy.Rate(10) self.pub = rospy.Publisher("/kitti_dataset", PointCloud2, queue_size=1) default_data_dir = '/home/usrg/Dataset/LidarDetection/niro' default_output_dir = 'data/s3dis/pointcnn' parser = argparse.ArgumentParser() parser.add_argument('-d', '--data', dest='data_dir', default=default_data_dir, help=f'Path to S3DIS data (default is {default_data_dir})') parser.add_argument('-f', '--folder', dest='output_dir', default=default_output_dir, help=f'Folder to write labels (default is {default_output_dir})') parser.add_argument('--max_num_points', '-m', help='Max point number of each sample', type=int, default=230400) parser.add_argument('--block_size', '-b', help='Block size', type=float, default=1.5) parser.add_argument('--grid_size', '-g', help='Grid size', type=float, default=0.03) parser.add_argument('--save_ply', '-s', help='Convert .pts to .ply', action='store_true') args = parser.parse_args() self.visualize(data_dir=args.data_dir, output_dir=args.output_dir) def visualize(self, data_dir, output_dir): object_dict = { 'Pedestrian': 0, 'Car': 1, 'Cyclist': 2, 'Van': 1, 'Truck': -3, 'Person_sitting': 0, 'Tram': -99, 'Misc': -99, 'DontCare': -1 } training_path = os.path.join(data_dir, 'training') if not os.path.isdir(training_path): print("No such directory.") return # pc_path_dir = os.path.join(training_path, 'velodyne') # kitti # label_path_dir = os.path.join(training_path, 'label_2') # kitti pc_path_dir = os.path.join(training_path, 'lidar') #niro label_path_dir = os.path.join(training_path, 'label') # niro pc_dir = os.listdir(pc_path_dir) pc_dir = sorted(pc_dir) # label_objects = os.listdir(label_path_dir) print(len(pc_dir)) xyz_room = np.zeros((1, 6)) label_room = np.zeros((1, 1)) for pc_buf in pc_dir: pc_ind = pc_buf.split('.', 1)[0] # pc_path = os.path.join(pc_path_dir, pc_ind + '.bin') # kitti pc_path = os.path.join(pc_path_dir, pc_ind + '.npy') # niro label_path = os.path.join(label_path_dir, pc_ind + '.txt') print(pc_path, label_path) # xyzi_arr = np.fromfile(pc_path, dtype=np.float32).reshape(-1, 4) #kitti xyzi_arr = np.load(pc_path).reshape(-1, 4) #niro xyzi_arr = np.array(xyzi_arr[:, :3]) # ori_pc = pcl.PointCloud(xyzi_arr) header = Header() header.stamp = rospy.Time.now() header.frame_id = 'velodyne' # fields = [PointField('x', 0, PointField.FLOAT32, 1), # PointField('y', 4, PointField.FLOAT32, 1), # PointField('z', 8, PointField.FLOAT32, 1), # PointField('intensity', 12, PointField.FLOAT32, 1)] # ros_msg = pc2.create_cloud(header, fields, xyzi_arr) ros_msg = pc2.create_cloud_xyz32(header, xyzi_arr) num_channel = int(xyzi_arr.shape[0] / 64) print('# of channel : ', num_channel, ', shape: ', xyzi_arr.shape) self.pub.publish(ros_msg) self.rate.sleep() def main(): vis = datasetVis() if __name__ == '__main__': main()
[ "numpy.load", "argparse.ArgumentParser", "rospy.Time.now", "std_msgs.msg.Header", "os.path.isdir", "numpy.zeros", "rospy.Publisher", "rospy.Rate", "sensor_msgs.point_cloud2.create_cloud_xyz32", "numpy.array", "rospy.init_node", "os.path.join", "os.listdir" ]
[((465, 508), 'rospy.init_node', 'rospy.init_node', (['"""tutorial"""'], {'anonymous': '(True)'}), "('tutorial', anonymous=True)\n", (480, 508), False, 'import rospy\n'), ((530, 544), 'rospy.Rate', 'rospy.Rate', (['(10)'], {}), '(10)\n', (540, 544), False, 'import rospy\n'), ((564, 624), 'rospy.Publisher', 'rospy.Publisher', (['"""/kitti_dataset"""', 'PointCloud2'], {'queue_size': '(1)'}), "('/kitti_dataset', PointCloud2, queue_size=1)\n", (579, 624), False, 'import rospy\n'), ((763, 788), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (786, 788), False, 'import argparse\n'), ((2010, 2044), 'os.path.join', 'os.path.join', (['data_dir', '"""training"""'], {}), "(data_dir, 'training')\n", (2022, 2044), False, 'import os\n'), ((2319, 2355), 'os.path.join', 'os.path.join', (['training_path', '"""lidar"""'], {}), "(training_path, 'lidar')\n", (2331, 2355), False, 'import os\n'), ((2387, 2423), 'os.path.join', 'os.path.join', (['training_path', '"""label"""'], {}), "(training_path, 'label')\n", (2399, 2423), False, 'import os\n'), ((2449, 2472), 'os.listdir', 'os.listdir', (['pc_path_dir'], {}), '(pc_path_dir)\n', (2459, 2472), False, 'import os\n'), ((2605, 2621), 'numpy.zeros', 'np.zeros', (['(1, 6)'], {}), '((1, 6))\n', (2613, 2621), True, 'import numpy as np\n'), ((2643, 2659), 'numpy.zeros', 'np.zeros', (['(1, 1)'], {}), '((1, 1))\n', (2651, 2659), True, 'import numpy as np\n'), ((2060, 2088), 'os.path.isdir', 'os.path.isdir', (['training_path'], {}), '(training_path)\n', (2073, 2088), False, 'import os\n'), ((2838, 2880), 'os.path.join', 'os.path.join', (['pc_path_dir', "(pc_ind + '.npy')"], {}), "(pc_path_dir, pc_ind + '.npy')\n", (2850, 2880), False, 'import os\n'), ((2913, 2958), 'os.path.join', 'os.path.join', (['label_path_dir', "(pc_ind + '.txt')"], {}), "(label_path_dir, pc_ind + '.txt')\n", (2925, 2958), False, 'import os\n'), ((3182, 3207), 'numpy.array', 'np.array', (['xyzi_arr[:, :3]'], {}), '(xyzi_arr[:, :3])\n', (3190, 3207), True, 'import numpy as np\n'), ((3280, 3288), 'std_msgs.msg.Header', 'Header', ([], {}), '()\n', (3286, 3288), False, 'from std_msgs.msg import Header\n'), ((3316, 3332), 'rospy.Time.now', 'rospy.Time.now', ([], {}), '()\n', (3330, 3332), False, 'import rospy\n'), ((3759, 3799), 'sensor_msgs.point_cloud2.create_cloud_xyz32', 'pc2.create_cloud_xyz32', (['header', 'xyzi_arr'], {}), '(header, xyzi_arr)\n', (3781, 3799), True, 'import sensor_msgs.point_cloud2 as pc2\n'), ((3121, 3137), 'numpy.load', 'np.load', (['pc_path'], {}), '(pc_path)\n', (3128, 3137), True, 'import numpy as np\n')]
import numpy as np import pandas as pd def mrd(a, b, M): ''' Calculate the Multiresolution Decomposition for a given timeseries of two variables Howell and Mahrt, 1997; Vickers and Mahrt, 2003; Vickers and Mahrt 2006 Args: a (array) : Array for timeseries "a" b (array) : Array for timeseries "b" M (int) : Number of points in the MRD (2^M points) Returns: D (array) : Decomposition array T (array) : Time array ''' # Pre-allocate time and decomposition arrays T = np.zeros(M) D = np.zeros(M) # Loop through 0 - M values (reversed) for m in np.flip(np.arange(M + 1)): ms = M - m # M - m in Vickers and Mahrt 2003 L = 2 ** ms sum_ab = 0. # Split arrays into m equal slices arr_list_a = np.split(a, L) arr_list_b = np.split(b, L) for i, (temp_a, temp_b) in enumerate(zip(arr_list_a, arr_list_b)): # Get the mean for each segment, then calculate cumulative sum mean_a = temp_a.mean() mean_b = temp_b.mean() sum_ab += np.sum(mean_a * mean_b) # Subtract mean if number of segments < number of values if arr_list_a[0].shape[0] > 1: arr_list_a[i] = temp_a - mean_a arr_list_b[i] = temp_b - mean_b # Write out decomposition and time values (ignoring m = M) if arr_list_a[0].shape[0] < 2 ** M: T[ms - 1] = L D[ms - 1] = sum_ab * (1 / 2 ** (ms)) # Write out new means to original arrays a = np.array(arr_list_a).flatten() b = np.array(arr_list_b).flatten() return T, np.flip(D) def mrd_tau(a, b, M, dt): ''' Return '''
[ "numpy.sum", "numpy.flip", "numpy.zeros", "numpy.split", "numpy.arange", "numpy.array" ]
[((542, 553), 'numpy.zeros', 'np.zeros', (['M'], {}), '(M)\n', (550, 553), True, 'import numpy as np\n'), ((562, 573), 'numpy.zeros', 'np.zeros', (['M'], {}), '(M)\n', (570, 573), True, 'import numpy as np\n'), ((639, 655), 'numpy.arange', 'np.arange', (['(M + 1)'], {}), '(M + 1)\n', (648, 655), True, 'import numpy as np\n'), ((819, 833), 'numpy.split', 'np.split', (['a', 'L'], {}), '(a, L)\n', (827, 833), True, 'import numpy as np\n'), ((855, 869), 'numpy.split', 'np.split', (['b', 'L'], {}), '(b, L)\n', (863, 869), True, 'import numpy as np\n'), ((1685, 1695), 'numpy.flip', 'np.flip', (['D'], {}), '(D)\n', (1692, 1695), True, 'import numpy as np\n'), ((1114, 1137), 'numpy.sum', 'np.sum', (['(mean_a * mean_b)'], {}), '(mean_a * mean_b)\n', (1120, 1137), True, 'import numpy as np\n'), ((1596, 1616), 'numpy.array', 'np.array', (['arr_list_a'], {}), '(arr_list_a)\n', (1604, 1616), True, 'import numpy as np\n'), ((1639, 1659), 'numpy.array', 'np.array', (['arr_list_b'], {}), '(arr_list_b)\n', (1647, 1659), True, 'import numpy as np\n')]
""" python3 py/compare_pdfs.py -f data/test_pdfs/00026_04_fda-K071597_test_data.pdf data/test_pdfs/small_test/copied_data.pdf """ import os import re import sys import json import math import pickle import hashlib import time import unicodedata import datetime import itertools import subprocess from pathlib import Path import numpy as np from itertools import groupby from itertools import combinations from operator import itemgetter from random import randint import sklearn # from scipy.stats import chisquare # PyMuPDF import fitz fitz.TOOLS.mupdf_display_errors(False) import warnings warnings.filterwarnings("ignore") from pydivsufsort import divsufsort, kasai import argparse VERSION = "1.3.1" TEXT_SEP = '^_^' PAGE_SEP = '@@@' #------------------------------------------------------------------------------- # UTILS #------------------------------------------------------------------------------- def get_datadir(): currdir = os.path.dirname(os.path.realpath(__file__)) parentdir = str(Path(currdir).parent) return parentdir + os.path.sep + 'data' def list_of_unique_dicts(L): # https://stackoverflow.com/questions/11092511/python-list-of-unique-dictionaries return list({json.dumps(v, sort_keys=True): v for v in L}.values()) def find_common_substrings(text1, text2, min_len): # Find all common non-overlapping substrings between two strings. # minLen is the minimum acceptable length of resulting common substrings. # # findCommonSubstrings("abcde", "bcbcd", 2) # -> ["bcd"] # Note: "bc" and "cd" are also common substrings, but they are substrings # of "bcd" and therefore do not count. # # combined: "abcdebcbcd" # suffix array: [0 5 7 1 6 8 2 9 3 4] # suffixes: # - abcdebcbcd # - bcbcd # - bcd # - bcdebcbcd # - cbcd # - cd # - cdebcbcd # - d # - debcbcd # - ebcbcd # LCP array: [0 0 2 3 0 1 2 0 1 0] # # Iterating through LCP we check to see if the LCP value is greater than # minLen (meaning the overlap is long enough), and if the overlap occurs # in both texts. # We get some candidates: # - bc # - bcd # - cd # # We sort the candidates by length and remove those that are substrings of # any previous candidate. Thus we are left with "bcd". text_combined = text1 + TEXT_SEP + text2 sa = divsufsort(text_combined) lcp = kasai(text_combined, sa) lcp = list(lcp) lcp = np.array(lcp[:-1]) # Collect candidates candidates = [] l = len(text1) j1s = np.array(sa[:-1]) j2s = np.array(sa[1:]) j_min = np.minimum(j1s, j2s) j_max = np.maximum(j1s, j2s) is_long_enough = lcp > min_len is_in_both = (j_min < l) & (j_max > l) does_not_cross = ~((j_min < l) & (j_min + lcp > l)) is_ok = is_long_enough & is_in_both & does_not_cross my_jmin = j_min[is_ok] my_jmax = j_max[is_ok] my_h = lcp[is_ok] # Remove candidates that are a substring of other candidates # Sort by length, descending sorted_idxs = np.argsort(-my_h) my_jmin = my_jmin[sorted_idxs] my_jmax = my_jmax[sorted_idxs] my_h = my_h[sorted_idxs] # Go through and take out overlapping substrings def is_subset_of_any_existing(new, existing): new_start, new_end = new for j1, _, h in existing: ex_start = j1 ex_end = j1 + h if ex_start <= new_start and new_end <= ex_end: return True return False offset = l+len(TEXT_SEP) # What to substract to get index of occurrence in text2 non_overlapping = [] LIMIT = 100000 for j1, j2, h in zip(my_jmin[:LIMIT], my_jmax[:LIMIT], my_h[:LIMIT]): start = j1 end = j1 + h if not is_subset_of_any_existing(new=(start, end), existing=non_overlapping): non_overlapping.append((j1, j2-offset, h)) result = [] for k1, k2, h in non_overlapping: substr = text1[k1:k1+h] if len(substr.strip()) > min_len: result.append((substr, k1, k2, h)) return result #------------------------------------------------------------------------------- # READING FILES #------------------------------------------------------------------------------- # def get_page_texts(filename): # texts = [] # with fitz.open(filename) as doc: # for page in doc: # page_text = page.get_text() # page_text_ascii = ''.join(c if c.isascii() else ' ' for c in page_text) # texts.append((page.number+1, page_text_ascii)) # return texts def get_page_image_hashes(filename): hashes = [] with fitz.open(filename) as doc: for page in doc: page_images = page.get_image_info(hashes=True) page_hashes = [] for img in page_images: hash_ = img['digest'].hex() if img['height'] > 200 and img['width'] > 200: page_hashes.append(hash_) hashes.append((page.number+1, page_hashes)) return hashes def read_blocks_and_hashes(filename): if filename[-4:] != '.pdf': raise Exception('Fitz cannot read non-PDF file', filename) text_blocks = [] image_hashes = [] with fitz.open(filename) as doc: n_pages = 0 cum_block_len = 0 for page in doc: n_pages += 1 # t0 = time.time() # page_d = page.get_text('dict') page_blocks = page.get_text('blocks') page_images = page.get_image_info(hashes=True) w = page.rect.width h = page.rect.height # print(time.time()-t0, 'get text dict') # t0 = time.time() for img in page_images: hash_ = img['digest'].hex() x0, y0, x1, y1 = img['bbox'] bbox = (x0/w, y0/h, x1/w, y1/h) # Relative to page size if img['height'] > 200 and img['width'] > 200: image_hashes.append((hash_, bbox, page.number+1)) for raw_block in page_blocks: x0, y0, x1, y1, block_text, n, typ = raw_block bbox = (x0/w, y0/h, x1/w, y1/h) # Relative to page size if typ == 0: # Only look at text blocks block_text = block_text.strip() block_text = block_text.encode("ascii", errors="ignore").decode() text_blocks.append((block_text, cum_block_len, bbox, page.number+1)) cum_block_len += len(block_text) # print(time.time()-t0, 'other stuff') return text_blocks, image_hashes, n_pages def is_compatible(v_current, v_cache): """ v_current and v_cache are strings like 1.1.1 compare first two digits """ int_cur = int(''.join(v_current.split('.')[:2])) int_cache = int(''.join(v_cache.split('.')[:2])) return int_cur == int_cache def get_file_data(filenames, regen_cache): data = [] for i, full_filename in enumerate(filenames): blocks_text, image_hashes, n_pages = None, None, None # Check if cached exists next to PDF cached_filename = full_filename + '.jsoncached' try: if os.path.exists(cached_filename) and not regen_cache: with open(cached_filename, 'rb') as f: cached = json.load(f) if is_compatible(VERSION, cached['version']): blocks_text, image_hashes, n_pages = cached['data'] blocks_text = [(t, c, tuple(b), p) for t, c, b, p in blocks_text] # Sadly JSON doesnt understand tuples except: pass if not blocks_text and not image_hashes and not n_pages: # if True: blocks_text, image_hashes, n_pages = read_blocks_and_hashes(full_filename) # And cache the data with open(cached_filename, 'w') as f: json.dump({ 'version': VERSION, 'data': [blocks_text, image_hashes, n_pages], }, f) path_to_file = (os.path.sep).join(full_filename.split(os.path.sep)[:-1]) filename = full_filename.split(os.path.sep)[-1] # blocks_text_lengths = [len(t) for t, b, p in blocks_text] blocks_digits = [] cum = 0 for t, c, b, p in blocks_text: ds = get_digits(t) blocks_digits.append((ds, cum, b, p)) cum += len(ds) # blocks_digits_lengths = [len(t) for t, b, p in blocks_digits] full_text = ''.join(t for t, c, bbx, p in blocks_text) full_digits = ''.join(t for t, c, bbx, p in blocks_digits) file_data = { 'path_to_file': path_to_file, 'filename': filename, 'file_index': i, 'blocks_text': blocks_text, # 'blocks_text_lengths': blocks_text_lengths, 'blocks_digits': blocks_digits, # 'blocks_digits_lengths': blocks_digits_lengths, 'full_text': full_text, 'full_digits': full_digits, 'image_hashes': image_hashes, 'n_pages': n_pages, } data.append(file_data) return data #------------------------------------------------------------------------------- # COMPARISON #------------------------------------------------------------------------------- def get_digits(text): result = ''.join(c for c in text if c.isnumeric()) return result def compare_images(hash_info_a, hash_info_b): # hash_info_a and hash_info_b are lists of tuples # (img_hash, bbox, page_number) # Create these dicts so that we can look up info later info_a = {hsh: (bbx, p) for hsh, bbx, p in hash_info_a} info_b = {hsh: (bbx, p) for hsh, bbx, p in hash_info_b} hashes_a = set(info_a) hashes_b = set(info_b) common_hashes = hashes_a.intersection(hashes_b) common_hash_info = [] for h in common_hashes: result = (h, info_a[h], info_b[h]) common_hash_info.append(result) return common_hash_info def benford_test(text): """ Check distribution of leading digits against benford distribution. The input text string here will typically be a paragraph. """ if len(text) < 140: return 1.0 n_digits = sum(c.isnumeric() for c in text) n_letters = sum(c.isalpha() for c in text) try: if n_digits / n_letters < 0.5: return 1.0 except ZeroDivisionError: pass # First replace decimals and commas page_text2 = text.replace('.', '') page_text2 = page_text2.replace(',', '') # Then iterate thru and get lead digits leading_digits = [] for prev, cur in zip(' '+page_text2[:-1], page_text2): if cur.isnumeric() and not prev.isnumeric(): leading_digits.append(cur) # print('Leading digits:', leading_digits) if not leading_digits: return 1.0 # Get counts counts = [leading_digits.count(str(d)) for d in range(1, 10)] percentages = [100*c/sum(counts) for c in counts] # print('Percentages:', percentages) # Benford's Law percentages for leading digits 1-9 BENFORD = [30.1, 17.6, 12.5, 9.7, 7.9, 6.7, 5.8, 5.1, 4.6] # Chi square test p = chisquare(percentages, f_exp=BENFORD).pvalue return p def combine_bboxes(bboxes, threshold=0.6): """ If the bboxes are close together, combine them into one. We check this by comparing the sum of areas over the area of the combined bbox. If it's over a threshold, we go ahead and combine. Inputs: bboxes - list of (x0, y0, x1, y1) thresold - area threshold to combine """ sum_areas = sum((x1-x0) * (y1-y0) for x0, y0, x1, y1 in bboxes) cx0 = min(x0 for x0, y0, x1, y1 in bboxes) cx1 = max(x1 for x0, y0, x1, y1 in bboxes) cy0 = min(y0 for x0, y0, x1, y1 in bboxes) cy1 = max(y1 for x0, y0, x1, y1 in bboxes) new_area = (cx1-cx0) * (cy1-cy0) if sum_areas / new_area > threshold: return [(cx0, cy0, cx1, cy1)] else: return bboxes def find_blocks_of_sus_substr(blocks, sus_start, h): """ Inputs: blocks - list of tups (text, cum_txt_len, bbox, page_num) sus_start - int index of occurrence of substring h - length of sus substr Returns (page number int, bbox tup) """ blocks_covered = [] for block in blocks: text, block_start, bbox, page_num = block block_end = block_start + len(text) # block_start comes from len() and so is IN the block # block_end is NOT in the block is_left = sus_start < block_start and sus_start+h < block_start is_right = block_end <= sus_start and block_end <= sus_start+h if not (is_left or is_right): blocks_covered.append(block) return blocks_covered def get_bboxes_by_page(sus_str, blocks1, blocks2, j1, j2, h): """ Inputs: sus_str - the suspiciuos str blocks1 - list of tups (text, cum_txt_len, bbox, page_num) blocks in text1 where the string is located blocks2 - list of tups (text, cum_txt_len, bbox, page_num) blocks in text2 where the string is located j1 - index of occurrence in text 1 j2 - index of occurrence in text 2 h - length of suspicious string Outputs: list of tups (sus_substr, page_a, bbox_a, page_b, bbox_b) """ def get_page_str_block_str(blocks, j, h): pages = [] block_idxs = [] block_i = 0 for txt, cum, box, p in blocks: pages += [p]*len(txt) block_idxs += [block_i]*len(txt) block_i += 1 # trim pad_start = j - blocks[0][1] # How many chars until we see the sus string pad_end = (blocks[-1][1]+len(blocks[-1][0])) - (j+h) # Extra chars at the end if pad_end == 0: # because [-0] index works weirdly pages = pages[pad_start:] block_idxs = block_idxs[pad_start:] else: pages = pages[pad_start:-pad_end] block_idxs = block_idxs[pad_start:-pad_end] return pages, block_idxs pages1, block_idxs_1 = get_page_str_block_str(blocks1, j1, h) pages2, block_idxs_2 = get_page_str_block_str(blocks2, j2, h) assert len(pages1) == len(pages2) # Should be same bc the common substring is same uniq_page_blocks = {} for i in range(len(pages1)): page_pair = (pages1[i], pages2[i]) try: block_1_i = blocks1[block_idxs_1[i]] block_2_i = blocks2[block_idxs_2[i]] uniq_page_blocks[page_pair]['blocks1'][block_1_i] = 0 uniq_page_blocks[page_pair]['blocks2'][block_2_i] = 0 uniq_page_blocks[page_pair]['str_len'] += 1 except KeyError: uniq_page_blocks[page_pair] = { 'blocks1': {block_1_i: 0}, 'blocks2': {block_2_i: 0}, 'str_len': 1 } result = [] for page_pair, block_dict in uniq_page_blocks.items(): page_a, page_b = page_pair bbox_a = [box for txt, cum, box, p in block_dict['blocks1']] bbox_b = [box for txt, cum, box, p in block_dict['blocks2']] bbox_a = combine_bboxes(bbox_a) bbox_b = combine_bboxes(bbox_b) page_str = ''.join(txt for txt, cum, box, p in block_dict['blocks1']) if sus_str in page_str: result.append((sus_str, page_a, bbox_a, page_b, bbox_b)) elif page_str in sus_str: result.append((page_str, page_a, bbox_a, page_b, bbox_b)) else: # Try from start from_start = page_str[:block_dict['str_len']] from_end = page_str[-block_dict['str_len']:] if from_start in sus_str: result.append((from_start, page_a, bbox_a, page_b, bbox_b)) elif from_end in sus_str: result.append((from_end, page_a, bbox_a, page_b, bbox_b)) else: print(page_str, sus_str, block_dict['str_len']) raise Exception('Cant get substring') return result def find_page_of_sus_image(pages, sus_hash): for page_num, page_hashes in pages: if sus_hash in page_hashes: return page_num return 'Page not found' def filter_sus_pairs(suspicious_pairs): common_text_sus_pairs = [] all_other_pairs = [] for p in suspicious_pairs: if p['type'] == 'Common text string': common_text_sus_pairs.append(p) else: all_other_pairs.append(p) if not common_text_sus_pairs: return suspicious_pairs datadir = get_datadir() with open(f'{datadir}/vectorizer.p', 'rb') as f: vectorizer = pickle.load(f) with open(f'{datadir}/text_clf.p', 'rb') as f: clf = pickle.load(f) text_strs = [p['string'] for p in common_text_sus_pairs] X = vectorizer.transform(text_strs) y_pred = clf.predict(X) # Go through and identify whether text pairs are good or bad. # Save which pages have insignificant (bad) text pairs and remember those, # we will ignore other matches from those pages as well. significant_text_pairs = [] bad_pages = set() for pair, prediction in zip(common_text_sus_pairs, y_pred): if prediction==1: significant_text_pairs.append(pair) else: bad_page_1 = (pair['pages'][0]['file_index'], pair['pages'][0]['page']) bad_page_2 = (pair['pages'][1]['file_index'], pair['pages'][1]['page']) bad_pages.add(bad_page_1) bad_pages.add(bad_page_2) significant_other_pairs = [] for pair in all_other_pairs: page1 = (pair['pages'][0]['file_index'], pair['pages'][0]['page']) page2 = (pair['pages'][1]['file_index'], pair['pages'][1]['page']) if page1 in bad_pages or page2 in bad_pages: continue else: significant_other_pairs.append(pair) return significant_text_pairs + significant_other_pairs def compare_texts(data_a, data_b, text_suffix, min_len, comparison_type_name): """ Inputs: data_a - data for first PDF data_b - data for second PDF text_suffix - suffix to determine which data field to use (text or digits) min_len - minimum acceptable length of duplicate text comparison_type_name - what to put in the output for "type" """ results = [] common_substrings = find_common_substrings( text1=data_a[f'full_{text_suffix}'], text2=data_b[f'full_{text_suffix}'], min_len=min_len ) if any(common_substrings): for sus_str, j1, j2, h in common_substrings: blocks_a = find_blocks_of_sus_substr(data_a[f'blocks_{text_suffix}'], j1, h) blocks_b = find_blocks_of_sus_substr(data_b[f'blocks_{text_suffix}'], j2, h) bboxes = get_bboxes_by_page(sus_str, blocks_a, blocks_b, j1, j2, h) for sus_substr, page_a, bbox_a, page_b, bbox_b in bboxes: str_preview = sus_substr if len(str_preview) > 97: str_preview = str_preview[:97].replace('\n', ' ')+'...' sus_result = { 'type': comparison_type_name, 'string': sus_substr, 'string_preview': str_preview, 'length': len(sus_substr), 'pages': [ { 'file_index': data_a['file_index'], 'page': page_a, 'bbox': bbox_a, }, { 'file_index': data_b['file_index'], 'page': page_b, 'bbox': bbox_b, }, ] } results.append(sus_result) return results #------------------------------------------------------------------------------- # GATHERING RESULTS #------------------------------------------------------------------------------- def get_file_info(file_data, suspicious_pairs): # Set of suspicious pages for filename sus_page_sets = [set() for i in file_data] for pair in suspicious_pairs: pages = pair['pages'] for page in pages: sus_page_sets[page['file_index']].add(page['page']) file_info = [] for i, data in enumerate(file_data): file_sus_pages = list(sus_page_sets[i]) fi = { 'filename': data['filename'], 'path_to_file': data['path_to_file'], 'n_pages': data['n_pages'], 'n_suspicious_pages': len(file_sus_pages), 'suspicious_pages': file_sus_pages, } file_info.append(fi) return file_info def get_similarity_scores(file_data, suspicious_pairs, methods_run): METHOD_NAMES = [ ('Common digit sequence', 'digits'), ('Common text string', 'text'), ('Identical image', 'images'), ] # Reorganize the suspicious pairs so we can efficiently access when looping reorg_sus_pairs = {} for sus in suspicious_pairs: file_a, file_b = [p['file_index'] for p in sus['pages']] method = sus['type'] if file_a not in reorg_sus_pairs: reorg_sus_pairs[file_a] = {} if file_b not in reorg_sus_pairs[file_a]: reorg_sus_pairs[file_a][file_b] = {} if method not in reorg_sus_pairs[file_a][file_b]: reorg_sus_pairs[file_a][file_b][method] = [] reorg_sus_pairs[file_a][file_b][method].append(sus) # Only upper triangle not incl. diagonal of cross matrix similarity_scores = {} for a in range(len(file_data)-1): for b in range(a+1, len(file_data)): if a not in similarity_scores: similarity_scores[a] = {} if b not in similarity_scores[a]: similarity_scores[a][b] = {} for method_long, method_short in METHOD_NAMES: if method_short in methods_run: try: suspairs = reorg_sus_pairs[a][b].get(method_long, []) except KeyError: suspairs = [] if method_long == 'Common digit sequence': intersect = sum(s['length'] for s in suspairs) a_clean = file_data[a]['full_digits'] b_clean = file_data[b]['full_digits'] union = len(a_clean) + len(b_clean) - intersect elif method_long == 'Common text string': intersect = sum(s['length'] for s in suspairs) a_clean = file_data[a]['full_text'] b_clean = file_data[b]['full_text'] union = len(a_clean) + len(b_clean) - intersect elif method_long == 'Identical image': intersect = len(suspairs) union = (len(file_data[a]['image_hashes']) + len(file_data[b]['image_hashes']) - intersect) if union == 0: jaccard = 'Undefined' else: jaccard = intersect / union similarity_scores[a][b][method_long] = jaccard else: similarity_scores[a][b][method_long] = 'Not run' return similarity_scores def get_version(): # repo = Repo() # ver = repo.git.describe('--always') # currdir = os.path.dirname(os.path.realpath(__file__)) # ver = subprocess.check_output(["git", "describe", "--always"], cwd=currdir).strip() # return ver.decode("utf-8") return VERSION #------------------------------------------------------------------------------- # MAIN #------------------------------------------------------------------------------- def main(filenames, methods, pretty_print, verbose=False, regen_cache=False): t0 = time.time() assert len(filenames) >= 2, 'Must have at least 2 files to compare!' if not methods: if verbose: print('Methods not specified, using default (all).') methods = ['digits', 'images', 'text'] if verbose: print('Using methods:', ', '.join(methods)) suspicious_pairs = [] if verbose: print('Reading files...') file_data = get_file_data(filenames, regen_cache) for i in range(len(filenames)-1): for j in range(i+1, len(filenames)): # i always less than j a = file_data[i] b = file_data[j] # Compare numbers if 'digits' in methods: if verbose: print('Comparing digits...') digit_results = compare_texts( data_a=a, data_b=b, text_suffix='digits', min_len=30, comparison_type_name='Common digit sequence' ) suspicious_pairs.extend(digit_results) # Compare texts if 'text' in methods: if verbose: print('Comparing texts...') text_results = compare_texts( data_a=a, data_b=b, text_suffix='text', min_len=280, comparison_type_name='Common text string' ) suspicious_pairs.extend(text_results) # Compare images if 'images' in methods: if verbose: print('Comparing images...') identical_images = compare_images( a['image_hashes'], b['image_hashes'], ) any_images_are_sus = len(identical_images) > 0 if any_images_are_sus: for img_hash, info_a, info_b in identical_images: bbox_a, sus_page_a = info_a bbox_b, sus_page_b = info_b sus_result = { 'type': 'Identical image', 'image_hash': img_hash, 'pages': [ { 'file_index': a['file_index'], 'page': sus_page_a, 'bbox': [bbox_a], }, { 'file_index': b['file_index'], 'page': sus_page_b, 'bbox': [bbox_b], }, ] } suspicious_pairs.append(sus_result) # Remove duplicate suspicious pairs (this might happen if a page has # multiple common substrings with another page) if verbose: print('Removing duplicate sus pairs...') suspicious_pairs = list_of_unique_dicts(suspicious_pairs) # Filter out irrelevant sus pairs if verbose: print('Removing irrelevant pairs...') suspicious_pairs = filter_sus_pairs(suspicious_pairs) # Calculate some more things for the final output if verbose: print('Gathering output...') if verbose: print('\tGet file info...') file_info = get_file_info(file_data, suspicious_pairs) if verbose: print('\tGet total pages...') total_page_pairs = sum(f['n_pages'] for f in file_info) if verbose: print('\tGet similarity score...') similarity_scores = get_similarity_scores(file_data, suspicious_pairs, methods) if verbose: print('\tGet version...') version = get_version() if verbose: print('\tResults gathered.') dt = time.time() - t0 if dt == 0: pages_per_second = -1 else: pages_per_second = total_page_pairs/dt result = { 'files': file_info, 'suspicious_pairs': suspicious_pairs, 'num_suspicious_pairs': len(suspicious_pairs), 'elapsed_time_sec': dt, 'pages_per_second': pages_per_second, 'similarity_scores': similarity_scores, 'version': version, 'time': datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ") } if pretty_print: print(json.dumps(result, indent=2), file=sys.stdout) else: print(json.dumps(result), file=sys.stdout) return if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '-f', '--filenames', help='PDF filenames to compare', nargs='+', ) parser.add_argument( '-m', '--methods', help='Which of the three comparison methods to use: text, digits, images', nargs='+', ) parser.add_argument( '-p', '--pretty_print', help='Pretty print output', action='store_true' ) parser.add_argument( '-c', '--regen_cache', help='Ignore and overwrite cached data', action='store_true' ) parser.add_argument( '-v', '--verbose', help='Print things while running', action='store_true' ) parser.add_argument( '--version', help='Print version', action='store_true' ) args = parser.parse_args() if args.version: print(VERSION) else: main( filenames=args.filenames, methods=args.methods, pretty_print=args.pretty_print, verbose=args.verbose, regen_cache=args.regen_cache ) # Within-file tests: # - Benford's Law # for file in filenames: # a = file_data[file.split('/')[-1]] # for page_num, page_text in a['page_texts']: # paragraphs = re.split(r'[ \n]{4,}', page_text) # for paragraph in paragraphs: # p = benford_test(paragraph) # if p < 0.05: # sus_result = { # 'type': 'Failed Benford Test', # 'p_value': p, # 'pages': [ # {'filename': a['filename'], 'page': page_num}, # {'filename': a['filename'], 'page': page_num}, # ] # }
[ "numpy.maximum", "argparse.ArgumentParser", "json.dumps", "numpy.argsort", "pathlib.Path", "pickle.load", "os.path.exists", "datetime.datetime.now", "json.dump", "numpy.minimum", "os.path.realpath", "fitz.open", "pydivsufsort.kasai", "json.load", "warnings.filterwarnings", "time.time", "fitz.TOOLS.mupdf_display_errors", "numpy.array", "pydivsufsort.divsufsort" ]
[((566, 604), 'fitz.TOOLS.mupdf_display_errors', 'fitz.TOOLS.mupdf_display_errors', (['(False)'], {}), '(False)\n', (597, 604), False, 'import fitz\n'), ((623, 656), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (646, 656), False, 'import warnings\n'), ((2506, 2531), 'pydivsufsort.divsufsort', 'divsufsort', (['text_combined'], {}), '(text_combined)\n', (2516, 2531), False, 'from pydivsufsort import divsufsort, kasai\n'), ((2543, 2567), 'pydivsufsort.kasai', 'kasai', (['text_combined', 'sa'], {}), '(text_combined, sa)\n', (2548, 2567), False, 'from pydivsufsort import divsufsort, kasai\n'), ((2600, 2618), 'numpy.array', 'np.array', (['lcp[:-1]'], {}), '(lcp[:-1])\n', (2608, 2618), True, 'import numpy as np\n'), ((2699, 2716), 'numpy.array', 'np.array', (['sa[:-1]'], {}), '(sa[:-1])\n', (2707, 2716), True, 'import numpy as np\n'), ((2728, 2744), 'numpy.array', 'np.array', (['sa[1:]'], {}), '(sa[1:])\n', (2736, 2744), True, 'import numpy as np\n'), ((2758, 2778), 'numpy.minimum', 'np.minimum', (['j1s', 'j2s'], {}), '(j1s, j2s)\n', (2768, 2778), True, 'import numpy as np\n'), ((2792, 2812), 'numpy.maximum', 'np.maximum', (['j1s', 'j2s'], {}), '(j1s, j2s)\n', (2802, 2812), True, 'import numpy as np\n'), ((3216, 3233), 'numpy.argsort', 'np.argsort', (['(-my_h)'], {}), '(-my_h)\n', (3226, 3233), True, 'import numpy as np\n'), ((24901, 24912), 'time.time', 'time.time', ([], {}), '()\n', (24910, 24912), False, 'import time\n'), ((29448, 29473), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (29471, 29473), False, 'import argparse\n'), ((1011, 1037), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (1027, 1037), False, 'import os\n'), ((4866, 4885), 'fitz.open', 'fitz.open', (['filename'], {}), '(filename)\n', (4875, 4885), False, 'import fitz\n'), ((5482, 5501), 'fitz.open', 'fitz.open', (['filename'], {}), '(filename)\n', (5491, 5501), False, 'import fitz\n'), ((17376, 17390), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (17387, 17390), False, 'import pickle\n'), ((17458, 17472), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (17469, 17472), False, 'import pickle\n'), ((28728, 28739), 'time.time', 'time.time', ([], {}), '()\n', (28737, 28739), False, 'import time\n'), ((1060, 1073), 'pathlib.Path', 'Path', (['currdir'], {}), '(currdir)\n', (1064, 1073), False, 'from pathlib import Path\n'), ((29278, 29306), 'json.dumps', 'json.dumps', (['result'], {'indent': '(2)'}), '(result, indent=2)\n', (29288, 29306), False, 'import json\n'), ((29351, 29369), 'json.dumps', 'json.dumps', (['result'], {}), '(result)\n', (29361, 29369), False, 'import json\n'), ((7517, 7548), 'os.path.exists', 'os.path.exists', (['cached_filename'], {}), '(cached_filename)\n', (7531, 7548), False, 'import os\n'), ((8282, 8367), 'json.dump', 'json.dump', (["{'version': VERSION, 'data': [blocks_text, image_hashes, n_pages]}", 'f'], {}), "({'version': VERSION, 'data': [blocks_text, image_hashes, n_pages]}, f\n )\n", (8291, 8367), False, 'import json\n'), ((29177, 29200), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (29198, 29200), False, 'import datetime\n'), ((1266, 1295), 'json.dumps', 'json.dumps', (['v'], {'sort_keys': '(True)'}), '(v, sort_keys=True)\n', (1276, 1295), False, 'import json\n'), ((7656, 7668), 'json.load', 'json.load', (['f'], {}), '(f)\n', (7665, 7668), False, 'import json\n')]
# encoding: utf-8 import numpy as np from scipy.special import expit from keras.datasets import mnist from keras.utils import to_categorical np.random.seed(7) inputs_units = 784 hidden_units = 256 output_units = 10 class MlpNumpy(object): def __init__(self): self.__hidden_weight = np.random.randn(hidden_units, inputs_units) self.__output_weight = np.random.randn(output_units, hidden_units) def forward(self, images_x): hidden_z = np.dot(self.__hidden_weight, images_x) hidden_a = expit(hidden_z) output_z = np.dot(self.__output_weight, hidden_a) output_a = expit(output_z) print(output_a) return hidden_z, hidden_a, output_z, output_a def backward(self, images_x, labels_y): """ :param images_x: (inputs_units, batch_size) :param labels_y: :return: """ # hidden_z, hidden_a (hidden_units, batch_size) # output_z, output_a (output_units, batch_size) hidden_z, hidden_a, output_z, output_a = self.forward(images_x) print("loss: {:.5f}".format(np.square(labels_y - output_a).mean().sum())) # delta_output (output_units, batch_size) delta_output = - (labels_y - output_a) * expit(output_z) * (1 - expit(output_z)) # gradi_output_weight (output_units, hidden_units) gradi_output_weight = np.dot(delta_output, hidden_a.T) # hidden layer # delta_hidden (hidden_units, batch_size) delta_hidden = expit(hidden_z) * (1 - expit(hidden_z)) * np.dot(self.__output_weight.T, delta_output) # gradi_output_weight (hidden_units, inputs_units) gradi_hidden_weight = np.dot(delta_hidden, images_x.T) return gradi_output_weight, gradi_hidden_weight def train(self, epochs): (images_x, labels_y), (_, _) = mnist.load_data() images_x = images_x.reshape(784, -1) images_x = images_x.astype(np.float32) images_x = images_x / 255 labels_y = to_categorical(labels_y, 10) labels_y = labels_y.reshape(10, -1) images_x = images_x[:, :256] labels_y = labels_y[:, :256] for _ in range(epochs): gradi_output_weight, gradi_hidden_weight = self.backward(images_x, labels_y) self.__output_weight -= 1e-2 * gradi_output_weight self.__hidden_weight -= 1e-2 * gradi_hidden_weight if __name__ == "__main__": mn = MlpNumpy() mn.train(epochs=1000)
[ "numpy.random.seed", "numpy.random.randn", "keras.datasets.mnist.load_data", "numpy.square", "scipy.special.expit", "numpy.dot", "keras.utils.to_categorical" ]
[((142, 159), 'numpy.random.seed', 'np.random.seed', (['(7)'], {}), '(7)\n', (156, 159), True, 'import numpy as np\n'), ((298, 341), 'numpy.random.randn', 'np.random.randn', (['hidden_units', 'inputs_units'], {}), '(hidden_units, inputs_units)\n', (313, 341), True, 'import numpy as np\n'), ((373, 416), 'numpy.random.randn', 'np.random.randn', (['output_units', 'hidden_units'], {}), '(output_units, hidden_units)\n', (388, 416), True, 'import numpy as np\n'), ((470, 508), 'numpy.dot', 'np.dot', (['self.__hidden_weight', 'images_x'], {}), '(self.__hidden_weight, images_x)\n', (476, 508), True, 'import numpy as np\n'), ((528, 543), 'scipy.special.expit', 'expit', (['hidden_z'], {}), '(hidden_z)\n', (533, 543), False, 'from scipy.special import expit\n'), ((563, 601), 'numpy.dot', 'np.dot', (['self.__output_weight', 'hidden_a'], {}), '(self.__output_weight, hidden_a)\n', (569, 601), True, 'import numpy as np\n'), ((621, 636), 'scipy.special.expit', 'expit', (['output_z'], {}), '(output_z)\n', (626, 636), False, 'from scipy.special import expit\n'), ((1375, 1407), 'numpy.dot', 'np.dot', (['delta_output', 'hidden_a.T'], {}), '(delta_output, hidden_a.T)\n', (1381, 1407), True, 'import numpy as np\n'), ((1681, 1713), 'numpy.dot', 'np.dot', (['delta_hidden', 'images_x.T'], {}), '(delta_hidden, images_x.T)\n', (1687, 1713), True, 'import numpy as np\n'), ((1840, 1857), 'keras.datasets.mnist.load_data', 'mnist.load_data', ([], {}), '()\n', (1855, 1857), False, 'from keras.datasets import mnist\n'), ((2005, 2033), 'keras.utils.to_categorical', 'to_categorical', (['labels_y', '(10)'], {}), '(labels_y, 10)\n', (2019, 2033), False, 'from keras.utils import to_categorical\n'), ((1547, 1591), 'numpy.dot', 'np.dot', (['self.__output_weight.T', 'delta_output'], {}), '(self.__output_weight.T, delta_output)\n', (1553, 1591), True, 'import numpy as np\n'), ((1246, 1261), 'scipy.special.expit', 'expit', (['output_z'], {}), '(output_z)\n', (1251, 1261), False, 'from scipy.special import expit\n'), ((1269, 1284), 'scipy.special.expit', 'expit', (['output_z'], {}), '(output_z)\n', (1274, 1284), False, 'from scipy.special import expit\n'), ((1505, 1520), 'scipy.special.expit', 'expit', (['hidden_z'], {}), '(hidden_z)\n', (1510, 1520), False, 'from scipy.special import expit\n'), ((1528, 1543), 'scipy.special.expit', 'expit', (['hidden_z'], {}), '(hidden_z)\n', (1533, 1543), False, 'from scipy.special import expit\n'), ((1100, 1130), 'numpy.square', 'np.square', (['(labels_y - output_a)'], {}), '(labels_y - output_a)\n', (1109, 1130), True, 'import numpy as np\n')]
import numpy as np from flow.core import rewards from flow.core.util import calculate_human_rl_timesteps_spent_in_simulation from flow.envs import BottleneckEnv from flow.envs.multiagent import MultiEnv from gym.spaces import Box MAX_LANES = 4 # base number of largest number of lanes in the network EDGE_LIST = ["1", "2", "3", "4", "5"] # Edge 1 is before the toll booth EDGE_BEFORE_TOLL = "1" # Specifies which edge number is before toll booth TB_TL_ID = "2" EDGE_AFTER_TOLL = "2" # Specifies which edge number is after toll booth NUM_TOLL_LANES = MAX_LANES TOLL_BOOTH_AREA = 10 # how far into the edge lane changing is disabled RED_LIGHT_DIST = 50 # how close for the ramp meter to start going off EDGE_BEFORE_RAMP_METER = "2" # Specifies which edge is before ramp meter EDGE_AFTER_RAMP_METER = "3" # Specifies which edge is after ramp meter NUM_RAMP_METERS = MAX_LANES RAMP_METER_AREA = 80 # Area occupied by ramp meter MEAN_NUM_SECONDS_WAIT_AT_FAST_TRACK = 3 # Average waiting time at fast track MEAN_NUM_SECONDS_WAIT_AT_TOLL = 15 # Average waiting time at toll BOTTLE_NECK_LEN = 280 # Length of bottleneck NUM_VEHICLE_NORM = 20 # Keys for RL experiments ADDITIONAL_RL_ENV_PARAMS = { # velocity to use in reward functions "target_velocity": 30, } class BottleneckMultiAgentEnv(MultiEnv, BottleneckEnv): """BottleneckMultiAgentEnv. Environment used to train vehicles to effectively pass through a bottleneck. States An observation is the edge position, speed, lane, and edge number of the AV, the distance to and velocity of the vehicles in front and behind the AV for all lanes. Actions The action space 1 value for acceleration and 1 for lane changing Rewards The reward is the average speed of the edge the agent is currently in combined with the speed of the agent. With some discount for lane changing. Termination A rollout is terminated once the time horizon is reached. """ def __init__(self, env_params, sim_params, network, simulator='traci'): """Initialize BottleneckMultiAgentEnv.""" for p in ADDITIONAL_RL_ENV_PARAMS.keys(): if p not in env_params.additional_params: raise KeyError( 'Environment parameter "{}" not supplied'.format(p)) super().__init__(env_params, sim_params, network, simulator) self.max_speed = self.k.network.max_speed() @property def observation_space(self): """See class definition.""" num_obs = 4 * MAX_LANES * self.scaling + 4 return Box(low=0, high=1, shape=(num_obs,), dtype=np.float32) def get_state(self): """See class definition.""" obs = {} headway_scale = 1000 for rl_id in self.k.vehicle.get_rl_ids(): # Get own normalized x location, speed, lane and edge edge_num = self.k.vehicle.get_edge(rl_id) if edge_num is None or edge_num == '' or edge_num[0] == ':': edge_num = -1 else: edge_num = int(edge_num) / 6 self_observation = [ self.k.vehicle.get_x_by_id(rl_id) / 1000, (self.k.vehicle.get_speed(rl_id) / self.max_speed), (self.k.vehicle.get_lane(rl_id) / MAX_LANES), edge_num ] # Get relative normalized ... num_lanes = MAX_LANES * self.scaling headway = np.asarray([1000] * num_lanes) / headway_scale tailway = np.asarray([1000] * num_lanes) / headway_scale vel_in_front = np.asarray([0] * num_lanes) / self.max_speed vel_behind = np.asarray([0] * num_lanes) / self.max_speed lane_leaders = self.k.vehicle.get_lane_leaders(rl_id) lane_followers = self.k.vehicle.get_lane_followers(rl_id) lane_headways = self.k.vehicle.get_lane_headways(rl_id) lane_tailways = self.k.vehicle.get_lane_tailways(rl_id) headway[0:len(lane_headways)] = ( np.asarray(lane_headways) / headway_scale) tailway[0:len(lane_tailways)] = ( np.asarray(lane_tailways) / headway_scale) for i, lane_leader in enumerate(lane_leaders): if lane_leader != '': vel_in_front[i] = (self.k.vehicle.get_speed(lane_leader) / self.max_speed) for i, lane_follower in enumerate(lane_followers): if lane_followers != '': vel_behind[i] = (self.k.vehicle.get_speed(lane_follower) / self.max_speed) relative_observation = np.concatenate((headway, tailway, vel_in_front, vel_behind)) obs.update({rl_id: np.concatenate((self_observation, relative_observation))}) return obs def compute_reward(self, rl_actions, **kwargs): return_rewards = {} # in the warmup steps, rl_actions is None if rl_actions: # for rl_id, actions in rl_actions.items(): for rl_id in self.k.vehicle.get_rl_ids(): reward = 0 # If there is a collision all agents get no reward if not kwargs['fail']: # Reward desired velocity in own edge edge_num = self.k.vehicle.get_edge(rl_id) reward += rewards.desired_velocity(self, fail=kwargs['fail'], edge_list=[edge_num], use_only_rl_ids=True) # Punish own lane changing if rl_id in rl_actions: reward -= abs(rl_actions[rl_id][1]) return_rewards[rl_id] = reward return return_rewards @property def action_space(self): """ :return: A box defining the size and bounds of the output layer of the network used for rl learning """ max_decel = self.env_params.additional_params["max_decel"] max_accel = self.env_params.additional_params["max_accel"] lb = [-abs(max_decel), -1] # * self.num_rl ub = [max_accel, 1] # * self.num_rl return Box(np.array(lb), np.array(ub), dtype=np.float32) def _apply_rl_actions(self, rl_actions): """ This function applies the actions the every reinforcement agent in the simulation :param rl_actions: The output of the PPO network based on the last steps observation per agent """ rl_ids = self.k.vehicle.get_rl_ids() if rl_actions: # in the warmup steps, rl_actions is None for rl_id, actions in rl_actions.items(): if rl_id not in rl_ids: continue self.k.vehicle.apply_acceleration(rl_id, actions[0]) if self.time_counter <= self.env_params.additional_params['lane_change_duration'] \ + self.k.vehicle.get_last_lc(rl_id): self.k.vehicle.apply_lane_change(str(rl_id), round(actions[1])) class BottleneckMultiAgentEnvFinal(BottleneckMultiAgentEnv): @property def observation_space(self): """See class definition.""" lb = [0] * 4 + [-1] * 18 ub = [1] * 4 + [1] * 18 return Box(np.array(lb), np.array(ub), dtype=np.float32) def get_state(self): """See class definition.""" obs = {} headway_scale = 1000 rl_ids = self.k.vehicle.get_rl_ids() for rl_id in rl_ids: # Get own normalized x location, speed, lane and edge edge_num = self.k.vehicle.get_edge(rl_id) if edge_num is None or edge_num == '' or edge_num[0] == ':': edge_num = -1 else: edge_num = int(edge_num) / 6 self_lane = self.k.vehicle.get_lane(rl_id) # Some SUMO versions sometimes return a wrong lane id if self_lane > MAX_LANES or self_lane < 0: print("SUMO returned bad lane id") self_lane = 0 self_observation = [ self.k.vehicle.get_x_by_id(rl_id) / 1000, (self.k.vehicle.get_speed(rl_id) / self.max_speed), (self_lane / MAX_LANES), edge_num ] # First normalize the features for all lanes lane_headways = np.array(self.k.vehicle.get_lane_headways(rl_id)) / headway_scale lane_tailways = np.array(self.k.vehicle.get_lane_tailways(rl_id)) / headway_scale vel_in_front = np.array(self.k.vehicle.get_lane_leaders_speed(rl_id)) / self.max_speed vel_behind = np.array(self.k.vehicle.get_lane_followers_speed(rl_id)) / self.max_speed type_of_vehicles_in_front = np.array([.5 if car_id in rl_ids else 1. for car_id in self.k.vehicle.get_lane_leaders(rl_id)]) type_of_vehicles_behind = np.array([.5 if car_id in rl_ids else 1. for car_id in self.k.vehicle.get_lane_followers(rl_id)]) # Pad the normalized features with -1s lane_headways = np.concatenate(([-1], lane_headways, [-1])) lane_tailways = np.concatenate(([-1], lane_tailways, [-1])) vel_in_front = np.concatenate(([-1], vel_in_front, [-1])) vel_behind = np.concatenate(([-1], vel_behind, [-1])) type_of_vehicles_in_front = np.concatenate(([-1], type_of_vehicles_in_front, [-1])) type_of_vehicles_behind = np.concatenate(([-1], type_of_vehicles_behind, [-1])) # Selecting the three closest lanes self_lane += 1 # Because we padded the lanes with 0s lane_headways = lane_headways[self_lane - 1:self_lane + 2] lane_tailways = lane_tailways[self_lane - 1:self_lane + 2] vel_in_front = vel_in_front[self_lane - 1:self_lane + 2] vel_behind = vel_behind[self_lane - 1:self_lane + 2] type_of_vehicles_in_front = type_of_vehicles_in_front[self_lane - 1:self_lane + 2] type_of_vehicles_behind = type_of_vehicles_behind[self_lane - 1:self_lane + 2] relative_observation = np.concatenate((lane_headways, lane_tailways, vel_in_front, vel_behind, type_of_vehicles_in_front, type_of_vehicles_behind)) obs.update({rl_id: np.concatenate((self_observation, relative_observation))}) obs.update({rl_id: np.array([0] * 22) for rl_id in self.k.vehicle.get_arrived_rl_ids()}) return obs def compute_evaluation_reward(self): if self.time_counter == self.env_params.horizon: outflow_all = self.k.vehicle.get_outflow_rate(500) outflow_rl = self.k.vehicle.get_rl_outflow_rate(500) outflow_human = outflow_all - outflow_rl # average timesteps spent in simulation rl_times, human_times = calculate_human_rl_timesteps_spent_in_simulation(self.k.vehicle._departed_ids, self.k.vehicle._arrived_ids) with open("result", "a") as f: f.write("{} + {} = {} {:.2f}% {:.2f} {:.2f}\n".format(outflow_rl, outflow_human, outflow_all, outflow_rl / outflow_all * 100, np.mean(rl_times), np.mean(human_times))) return {rl_id: outflow_rl / outflow_all for rl_id in self.k.vehicle.get_rl_ids()} else: return {rl_id: 0 for rl_id in self.k.vehicle.get_rl_ids()} def compute_reward(self, rl_actions, **kwargs): """ :param rl_actions: The output of the PPO network based on the last steps observation per agent :param kwargs: Can contain fail, to indicate that a crash happened :return: The individual reward for every agent """ rl_agent_rewards = {} rl_ids = self.k.vehicle.get_rl_ids() if rl_actions and rl_ids: # Some reward function based on the speed of the recently arrived AVs - constant punishment for time new_reward = (self.k.vehicle.get_new_reward() / len(rl_ids)) - 0.006 # More punishment for the amount if AVs in the simulation new_reward -= 0.003 * len(rl_ids) rl_agent_rewards = {rl_id: new_reward for rl_id in rl_ids} # Colliders get punished if kwargs['fail']: for collider_id in self.k.vehicle.get_collided_ids(): if collider_id in rl_agent_rewards: rl_agent_rewards[collider_id] -= 10 # Reward agent that made it to the exit arrived_rl_ids = self.k.vehicle.get_arrived_rl_ids() if arrived_rl_ids: for arrived_agent_id, time in zip(arrived_rl_ids, self.k.vehicle.timed_rl_arrived[-1]): rl_agent_rewards[arrived_agent_id] = 200 / time if self.env_params.evaluate: return self.compute_evaluation_reward() return rl_agent_rewards class BottleneckThijsMultiAgentEnv(BottleneckMultiAgentEnvFinal): """ For backwards compatibility """ pass class BottleneckMultiAgentEnvOld(BottleneckMultiAgentEnv): """BottleneckMultiAgentEnv. Environment used to train vehicles to effectively pass through a bottleneck. States An observation is the edge position, speed, lane, and edge number of the AV, the distance to and velocity of the vehicles in front and behind the AV for all lanes. Actions The action space 1 value for acceleration and 1 for lane changing Rewards The reward is the average speed of the edge the agent is currently in combined with the speed of the agent. With some discount for lane changing. Termination A rollout is terminated once the time horizon is reached. """ def __init__(self, env_params, sim_params, network, simulator='traci'): super().__init__(env_params, sim_params, network, simulator) self.nr_self_perc_features = 3 # Nr of features an rl car perceives from itself self.perc_lanes_around = 1 # Nr of lanes the car perceives around its own lane self.features_per_car = 3 # Nr of features the rl car observes per other car @property def observation_space(self): """Returns size of input tensor passed to RL network. 2 = headway + tailway // left + right""" perceived_lanes = 2 * self.perc_lanes_around + 1 # 2*sides + own lane perceived_cars = 2 * perceived_lanes # front + back perceived_features_others = perceived_cars * self.features_per_car # nr of cars * (nr of features/other car) total_features = perceived_features_others + self.nr_self_perc_features return Box(low=-2000, high=2000, shape=(total_features,), dtype=np.float32) def get_label(self, veh_id): if 'rl' in veh_id: return 2. elif 'human' in veh_id or 'flow' in veh_id: return 1. return 0. def get_state(self): """Returns state representation per RL vehicle.""" obs = {} for veh_id in self.k.vehicle.get_rl_ids(): edge = self.k.vehicle.get_edge(veh_id) lane = self.k.vehicle.get_lane(veh_id) veh_x_pos = self.k.vehicle.get_x_by_id(veh_id) # Infos the car stores about itself: self_representation = [veh_x_pos, # Car's current x-position along the road self.k.vehicle.get_speed(veh_id), # Car's current speed self.k.network.speed_limit(edge)] # How fast car may drive (reference value) others_representation = [] # Representation of surrounding vehicles ### Headway ### # Returned ids sorted by lane index leading_cars_ids = self.k.vehicle.get_lane_leaders(veh_id) leading_cars_dist = [self.k.vehicle.get_x_by_id(lead_id) - veh_x_pos for lead_id in leading_cars_ids] leading_cars_labels = [self.get_label(leading_id) for leading_id in leading_cars_ids] leading_cars_speed = self.k.vehicle.get_speed(leading_cars_ids, error=float(self.k.network.max_speed())) leading_cars_lanes = self.k.vehicle.get_lane(leading_cars_ids) # Sorted increasingly by lane from 0 to nr of lanes headway_cars_map = list(zip(leading_cars_lanes, leading_cars_labels, leading_cars_dist, leading_cars_speed)) for l in range(lane-self.perc_lanes_around, lane+self.perc_lanes_around+1): # Interval +/- 1 around rl car's lane if 0 <= l < self.k.network.num_lanes(edge): # Valid lane value (=lane value inside set of existing lanes) if headway_cars_map[l][0] == l: # There is a car on this lane in front since lane-value in map is not equal to error-code others_representation.extend(headway_cars_map[l][1:]) # Add [idX, distX, speedX] else: # There is no car in respective lane in front of rl car since lane-value == error-code others_representation.extend([0., 1000, float(self.k.network.max_speed())]) else: # Lane to left/right does not exist. Pad values with -1.'s others_representation.extend([-1.] * self.features_per_car) ### Tailway ### # Sorted by lane index if not mistaken... following_cars_ids = self.k.vehicle.get_lane_followers(veh_id) following_cars_dist = [self.k.vehicle.get_x_by_id(follow_id) - veh_x_pos if not follow_id == '' else -1000 for follow_id in following_cars_ids] following_cars_labels = [self.get_label(following_id) for following_id in following_cars_ids] following_cars_speed = self.k.vehicle.get_speed(following_cars_ids, error=0) following_cars_lanes = self.k.vehicle.get_lane(following_cars_ids, error=-1001) tailway_cars_map = list(zip(following_cars_lanes, following_cars_labels, following_cars_dist, following_cars_speed)) for l in range(lane-self.perc_lanes_around, lane+self.perc_lanes_around+1): # Interval +/- 1 around rl car's lane if 0 <= l < self.k.network.num_lanes(edge): # Valid lane value (=lane value inside set of existing lanes) if tailway_cars_map[l][0] == l: # There is a car on this lane behind since lane-value in map is not equal to error-code others_representation.extend(tailway_cars_map[l][1:]) # Add [idX, distX, speedX] else: # There is no car in respective lane behind rl car since lane-value == error-code others_representation.extend([0., -1000, 0]) else: # Lane to left/right does not exist. Pad values with -1.'s others_representation.extend([-1.] * self.features_per_car) # Merge two lists (self-representation & representation of surrounding lanes/cars) and transform to array self_representation.extend(others_representation) observation_arr = np.asarray(self_representation, dtype=float) obs[veh_id] = observation_arr # Assign representation about self and surrounding cars to car's observation return obs def compute_reward(self, rl_actions, **kwargs): """ :param rl_actions: The output of the PPO network based on the last steps observation per agent :param kwargs: Can contain fail, to indicate that a crash happened :return: The individual reward for every agent """ # if a crash occurred everybody gets 0 if kwargs['fail']: return {rl_id: 0 for rl_id in self.k.vehicle.get_rl_ids()} # Average outflow over last 10 steps, divided 2000 * scaling. # TODO: NEXT: try own reward computation outflow_reward = 2/3 * self.k.vehicle.get_rl_outflow_rate(10 * self.sim_step) / (2000.0 * self.scaling) rl_agent_rewards = {} if rl_actions: for rl_id in self.k.vehicle.get_rl_ids(): # Reward desired velocity in own edge + the total outflow edge_num = self.k.vehicle.get_edge(rl_id) rl_agent_rewards[rl_id] = 1/3 * rewards.desired_velocity(self, edge_list=[edge_num], use_only_rl_ids=True) + outflow_reward return rl_agent_rewards
[ "flow.core.rewards.desired_velocity", "numpy.asarray", "flow.core.util.calculate_human_rl_timesteps_spent_in_simulation", "numpy.mean", "numpy.array", "gym.spaces.Box", "numpy.concatenate" ]
[((2644, 2698), 'gym.spaces.Box', 'Box', ([], {'low': '(0)', 'high': '(1)', 'shape': '(num_obs,)', 'dtype': 'np.float32'}), '(low=0, high=1, shape=(num_obs,), dtype=np.float32)\n', (2647, 2698), False, 'from gym.spaces import Box\n'), ((15147, 15215), 'gym.spaces.Box', 'Box', ([], {'low': '(-2000)', 'high': '(2000)', 'shape': '(total_features,)', 'dtype': 'np.float32'}), '(low=-2000, high=2000, shape=(total_features,), dtype=np.float32)\n', (15150, 15215), False, 'from gym.spaces import Box\n'), ((4696, 4756), 'numpy.concatenate', 'np.concatenate', (['(headway, tailway, vel_in_front, vel_behind)'], {}), '((headway, tailway, vel_in_front, vel_behind))\n', (4710, 4756), True, 'import numpy as np\n'), ((6224, 6236), 'numpy.array', 'np.array', (['lb'], {}), '(lb)\n', (6232, 6236), True, 'import numpy as np\n'), ((6238, 6250), 'numpy.array', 'np.array', (['ub'], {}), '(ub)\n', (6246, 6250), True, 'import numpy as np\n'), ((7315, 7327), 'numpy.array', 'np.array', (['lb'], {}), '(lb)\n', (7323, 7327), True, 'import numpy as np\n'), ((7329, 7341), 'numpy.array', 'np.array', (['ub'], {}), '(ub)\n', (7337, 7341), True, 'import numpy as np\n'), ((9224, 9267), 'numpy.concatenate', 'np.concatenate', (['([-1], lane_headways, [-1])'], {}), '(([-1], lane_headways, [-1]))\n', (9238, 9267), True, 'import numpy as np\n'), ((9296, 9339), 'numpy.concatenate', 'np.concatenate', (['([-1], lane_tailways, [-1])'], {}), '(([-1], lane_tailways, [-1]))\n', (9310, 9339), True, 'import numpy as np\n'), ((9367, 9409), 'numpy.concatenate', 'np.concatenate', (['([-1], vel_in_front, [-1])'], {}), '(([-1], vel_in_front, [-1]))\n', (9381, 9409), True, 'import numpy as np\n'), ((9435, 9475), 'numpy.concatenate', 'np.concatenate', (['([-1], vel_behind, [-1])'], {}), '(([-1], vel_behind, [-1]))\n', (9449, 9475), True, 'import numpy as np\n'), ((9516, 9571), 'numpy.concatenate', 'np.concatenate', (['([-1], type_of_vehicles_in_front, [-1])'], {}), '(([-1], type_of_vehicles_in_front, [-1]))\n', (9530, 9571), True, 'import numpy as np\n'), ((9610, 9663), 'numpy.concatenate', 'np.concatenate', (['([-1], type_of_vehicles_behind, [-1])'], {}), '(([-1], type_of_vehicles_behind, [-1]))\n', (9624, 9663), True, 'import numpy as np\n'), ((10277, 10405), 'numpy.concatenate', 'np.concatenate', (['(lane_headways, lane_tailways, vel_in_front, vel_behind,\n type_of_vehicles_in_front, type_of_vehicles_behind)'], {}), '((lane_headways, lane_tailways, vel_in_front, vel_behind,\n type_of_vehicles_in_front, type_of_vehicles_behind))\n', (10291, 10405), True, 'import numpy as np\n'), ((11030, 11142), 'flow.core.util.calculate_human_rl_timesteps_spent_in_simulation', 'calculate_human_rl_timesteps_spent_in_simulation', (['self.k.vehicle._departed_ids', 'self.k.vehicle._arrived_ids'], {}), '(self.k.vehicle.\n _departed_ids, self.k.vehicle._arrived_ids)\n', (11078, 11142), False, 'from flow.core.util import calculate_human_rl_timesteps_spent_in_simulation\n'), ((20092, 20136), 'numpy.asarray', 'np.asarray', (['self_representation'], {'dtype': 'float'}), '(self_representation, dtype=float)\n', (20102, 20136), True, 'import numpy as np\n'), ((3519, 3549), 'numpy.asarray', 'np.asarray', (['([1000] * num_lanes)'], {}), '([1000] * num_lanes)\n', (3529, 3549), True, 'import numpy as np\n'), ((3588, 3618), 'numpy.asarray', 'np.asarray', (['([1000] * num_lanes)'], {}), '([1000] * num_lanes)\n', (3598, 3618), True, 'import numpy as np\n'), ((3662, 3689), 'numpy.asarray', 'np.asarray', (['([0] * num_lanes)'], {}), '([0] * num_lanes)\n', (3672, 3689), True, 'import numpy as np\n'), ((3732, 3759), 'numpy.asarray', 'np.asarray', (['([0] * num_lanes)'], {}), '([0] * num_lanes)\n', (3742, 3759), True, 'import numpy as np\n'), ((4116, 4141), 'numpy.asarray', 'np.asarray', (['lane_headways'], {}), '(lane_headways)\n', (4126, 4141), True, 'import numpy as np\n'), ((4225, 4250), 'numpy.asarray', 'np.asarray', (['lane_tailways'], {}), '(lane_tailways)\n', (4235, 4250), True, 'import numpy as np\n'), ((10571, 10589), 'numpy.array', 'np.array', (['([0] * 22)'], {}), '([0] * 22)\n', (10579, 10589), True, 'import numpy as np\n'), ((4789, 4845), 'numpy.concatenate', 'np.concatenate', (['(self_observation, relative_observation)'], {}), '((self_observation, relative_observation))\n', (4803, 4845), True, 'import numpy as np\n'), ((5416, 5515), 'flow.core.rewards.desired_velocity', 'rewards.desired_velocity', (['self'], {'fail': "kwargs['fail']", 'edge_list': '[edge_num]', 'use_only_rl_ids': '(True)'}), "(self, fail=kwargs['fail'], edge_list=[edge_num],\n use_only_rl_ids=True)\n", (5440, 5515), False, 'from flow.core import rewards\n'), ((10485, 10541), 'numpy.concatenate', 'np.concatenate', (['(self_observation, relative_observation)'], {}), '((self_observation, relative_observation))\n', (10499, 10541), True, 'import numpy as np\n'), ((11552, 11569), 'numpy.mean', 'np.mean', (['rl_times'], {}), '(rl_times)\n', (11559, 11569), True, 'import numpy as np\n'), ((11642, 11662), 'numpy.mean', 'np.mean', (['human_times'], {}), '(human_times)\n', (11649, 11662), True, 'import numpy as np\n'), ((21253, 21327), 'flow.core.rewards.desired_velocity', 'rewards.desired_velocity', (['self'], {'edge_list': '[edge_num]', 'use_only_rl_ids': '(True)'}), '(self, edge_list=[edge_num], use_only_rl_ids=True)\n', (21277, 21327), False, 'from flow.core import rewards\n')]
import yaml import numpy as np def load(path): with open('config/default_values.yaml', 'r') as f: default_cfg = yaml.load(f, yaml.FullLoader) with open(path, 'r') as f: cfg = yaml.load(f, yaml.FullLoader) default_cfg.update(cfg) cfg = default_cfg cfg['data_bounding_box'] = np.array(cfg['data_bounding_box']) cfg['data_bounding_box_str'] = ",".join(str(x) for x in cfg['data_bounding_box']) return cfg
[ "yaml.load", "numpy.array" ]
[((314, 348), 'numpy.array', 'np.array', (["cfg['data_bounding_box']"], {}), "(cfg['data_bounding_box'])\n", (322, 348), True, 'import numpy as np\n'), ((125, 154), 'yaml.load', 'yaml.load', (['f', 'yaml.FullLoader'], {}), '(f, yaml.FullLoader)\n', (134, 154), False, 'import yaml\n'), ((201, 230), 'yaml.load', 'yaml.load', (['f', 'yaml.FullLoader'], {}), '(f, yaml.FullLoader)\n', (210, 230), False, 'import yaml\n')]
import pickle import numpy as np import pandas as pd from collections import Counter def get_xy(dist, normed=False): counter = Counter(dist) x=[];y=[] for xval in sorted(counter.keys()): x.append(xval) y.append(counter[xval]) y = np.array(y) if normed: y = y/y.sum() return x, y print("Reading shipping distances.", flush=True) shipping_dist = dict() with open('/home/larock.t/git/shipping/data/port_shipping_distances.csv', 'r') as fin: for line in fin: u,v,dist = line.strip().split(',') shipping_dist[(u,v)] = float(dist) print("Computing filtered path stats.", flush=True) scratch_base = '/scratch/larock.t/shipping/results/interpolated_paths/' ## Filtered paths filtered_stats = { 'num_paths':[], 'route_lengths':[], 'path_lengths':[], 'distances':[], 'routes_per_path':[] } filtered_paths = dict() import sys argv = sys.argv if len(argv) > 1: rt_thresh = float(sys.argv[1]) dt_thresh = float(sys.argv[2]) else: rt_thresh = 1.0 dt_thresh = 1.5 dt_thresh = 'detour' with open(scratch_base + f'iterative_paths_filtered_dt-{dt_thresh}_rt-{rt_thresh}.txt', 'r') as fin: pair_counter = 0 total_pairs = 0 prev_pair = (-1,-1) first = True for line in fin: path, mr_dist, route_dist, *routes = line.strip().split('|') path = path.strip().split(',') dist = int(mr_dist) pair = (path[0], path[-1]) filtered_paths.setdefault(pair, dict()) filtered_paths[pair][tuple(path)] = dist filtered_stats['distances'].append(float(route_dist)) filtered_stats['routes_per_path'].append(len(routes)) if pair != prev_pair and not first: num_paths = len(filtered_paths[prev_pair]) filtered_stats['num_paths'].append(num_paths) ## Compute over _all_ paths (same for all 4 path datasets) route_lengths = [p for p in filtered_paths[prev_pair].values()] filtered_stats['route_lengths'] += route_lengths path_lengths = [len(p)-1 for p in filtered_paths[prev_pair].keys()] filtered_stats['path_lengths'] += path_lengths pair_counter += 1 total_pairs += 1 if pair_counter == 50_000: print(f"{total_pairs} pairs processed.", flush=True) pair_counter = 0 prev_pair = pair if first: first = False ## Do the last pair! num_paths = len(filtered_paths[prev_pair]) filtered_stats['num_paths'].append(num_paths) route_lengths = list(filtered_paths[prev_pair].values()) filtered_stats['route_lengths'] += route_lengths path_lengths = [len(p)-1 for p in filtered_paths[prev_pair].keys()] filtered_stats['path_lengths'] += path_lengths import pickle with open(scratch_base + f'iterative_paths_filtered_dt-{dt_thresh}_rt-{rt_thresh}_stats.pickle', 'wb') as fpickle: pickle.dump(filtered_stats, fpickle) print("Computing clique path stats.", flush=True) ## Clique paths clique_stats = { 'num_paths':[], 'route_lengths':[], 'path_lengths':[], 'distances':[] } with open(scratch_base + 'shortest_paths_clique.pickle', 'rb') as fpickle: paper_paths_dict = pickle.load(fpickle) gwdata = pd.read_csv('../data/original/Nodes_2015_country_degree_bc_B_Z_P.csv', encoding='latin-1' ) ## Just need to get id to name mapping port_mapping = dict(zip(gwdata.id.values,gwdata.port.values)) with open(scratch_base + 'clique_minroute_paths.pickle', 'rb') as fpickle: minimum_routes_sp = pickle.load(fpickle) for pair in paper_paths_dict: num_paths = len(paper_paths_dict[pair]) #num_paths_dist_cg.append(num_paths) clique_stats['num_paths'].append(num_paths) mpair = (port_mapping[pair[0]], port_mapping[pair[1]]) if mpair in minimum_routes_sp: route_lengths = [p for p in minimum_routes_sp[mpair].values()] clique_stats['route_lengths'] += route_lengths #path_lengths = [len(next(iter(paper_paths_dict[pair])))-1]*len(paper_paths_dict[pair]) #clique_stats['path_lengths'] += path_lengths # get shipping distance for *ALL* shortest paths for path in paper_paths_dict[pair]: clique_stats['path_lengths'].append(len(path)) # Real distance d = 0.0 for i in range(1, len(path)): mpair = (port_mapping[path[i-1]], port_mapping[path[i]]) d += shipping_dist[mpair] clique_stats['distances'].append(d) #for pair in minimum_routes_sp: # # To make all inset histograms have the same number of points, # # I should change this to paper_paths_dict instead. # for path in minimum_routes_sp[pair]: # ## Real distance # d = 0.0 # for i in range(1, len(path)): # d += shipping_dist[path[i-1], path[i]] # clique_stats['distances'].append(d) ## coroute graph paths print("Computing coroute path stats.", flush=True) coroute_stats = { 'num_paths':[], 'route_lengths':[], 'path_lengths':[], 'distances':[] } with open(scratch_base + 'shortest_paths_coroute.pickle', 'rb') as fpickle: coroute_paths = pickle.load(fpickle) with open(scratch_base + 'coroute_minroute_paths.pickle', 'rb') as fpickle: minimum_routes = pickle.load(fpickle) for pair in coroute_paths: num_paths = len(coroute_paths[pair]) coroute_stats['num_paths'].append(num_paths) if pair in minimum_routes: route_lengths = [p for p in minimum_routes[pair].values()] coroute_stats['route_lengths'] += route_lengths #coroute_lengths = [len(next(iter(coroute_paths[pair])))-1]*len(coroute_paths[pair]) #coroute_stats['path_lengths'] += coroute_lengths for path in coroute_paths[pair]: coroute_stats['path_lengths'].append(len(path)-1) ## Real distance d = 0.0 for i in range(1, len(path)): d += shipping_dist[path[i-1], path[i]] coroute_stats['distances'].append(d) #for pair in minimum_routes: # for path in minimum_routes[pair]: # ## Real distance # d = 0.0 # for i in range(1, len(path)): # d += shipping_dist[path[i-1], path[i]] # coroute_stats['distances'].append(d) ## Path graph paths print("Computing path path stats.", flush=True) path_stats = { 'num_paths':[], 'route_lengths':[], 'path_lengths':[], 'distances':[] } with open(scratch_base + 'shortest_paths_pathrep.pickle', 'rb') as fpickle: pg_paths = pickle.load(fpickle) with open(scratch_base + 'sp_pathrep_minroutes.pickle', 'rb') as fpickle: minimum_routes = pickle.load(fpickle) for pair in pg_paths: num_paths = len(pg_paths[pair]) path_stats['num_paths'].append(num_paths) route_lengths = [p for p in minimum_routes[pair].values()] path_stats['route_lengths'] += route_lengths path_lengths = [len(next(iter(pg_paths[pair])))-1]*len(pg_paths[pair]) path_stats['path_lengths'] += path_lengths for path in pg_paths[pair]: ## Real distance d = 0.0 for i in range(1, len(path)): d += shipping_dist[path[i-1], path[i]] path_stats['distances'].append(d) print("Dumping stats.", flush=True) with open(scratch_base + f'path_comparison_stats_dt-{dt_thresh}_rt-{rt_thresh}_alldists.pickle', 'wb') as fpickle: pickle.dump((filtered_stats, clique_stats, coroute_stats, path_stats), fpickle)
[ "pickle.dump", "pandas.read_csv", "pickle.load", "numpy.array", "collections.Counter" ]
[((3245, 3339), 'pandas.read_csv', 'pd.read_csv', (['"""../data/original/Nodes_2015_country_degree_bc_B_Z_P.csv"""'], {'encoding': '"""latin-1"""'}), "('../data/original/Nodes_2015_country_degree_bc_B_Z_P.csv',\n encoding='latin-1')\n", (3256, 3339), True, 'import pandas as pd\n'), ((133, 146), 'collections.Counter', 'Counter', (['dist'], {}), '(dist)\n', (140, 146), False, 'from collections import Counter\n'), ((264, 275), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (272, 275), True, 'import numpy as np\n'), ((2908, 2944), 'pickle.dump', 'pickle.dump', (['filtered_stats', 'fpickle'], {}), '(filtered_stats, fpickle)\n', (2919, 2944), False, 'import pickle\n'), ((3215, 3235), 'pickle.load', 'pickle.load', (['fpickle'], {}), '(fpickle)\n', (3226, 3235), False, 'import pickle\n'), ((3537, 3557), 'pickle.load', 'pickle.load', (['fpickle'], {}), '(fpickle)\n', (3548, 3557), False, 'import pickle\n'), ((5121, 5141), 'pickle.load', 'pickle.load', (['fpickle'], {}), '(fpickle)\n', (5132, 5141), False, 'import pickle\n'), ((5239, 5259), 'pickle.load', 'pickle.load', (['fpickle'], {}), '(fpickle)\n', (5250, 5259), False, 'import pickle\n'), ((6463, 6483), 'pickle.load', 'pickle.load', (['fpickle'], {}), '(fpickle)\n', (6474, 6483), False, 'import pickle\n'), ((6579, 6599), 'pickle.load', 'pickle.load', (['fpickle'], {}), '(fpickle)\n', (6590, 6599), False, 'import pickle\n'), ((7301, 7380), 'pickle.dump', 'pickle.dump', (['(filtered_stats, clique_stats, coroute_stats, path_stats)', 'fpickle'], {}), '((filtered_stats, clique_stats, coroute_stats, path_stats), fpickle)\n', (7312, 7380), False, 'import pickle\n')]
''' .. module:: skrf.plotting ======================================== plotting (:mod:`skrf.plotting`) ======================================== This module provides general plotting functions. Plots and Charts ------------------ .. autosummary:: :toctree: generated/ smith plot_smith plot_rectangular plot_polar plot_complex_rectangular plot_complex_polar Misc Functions ----------------- .. autosummary:: :toctree: generated/ save_all_figs add_markers_to_lines legend_off func_on_all_figs scrape_legend ''' import pylab as plb import numpy as npy from matplotlib.patches import Circle # for drawing smith chart from matplotlib.pyplot import quiver from matplotlib import rcParams #from matplotlib.lines import Line2D # for drawing smith chart def smith(smithR=1, chart_type = 'z', draw_labels = False, border=False, ax=None, ref_imm = 1.0, draw_vswr=None): ''' plots the smith chart of a given radius Parameters ----------- smithR : number radius of smith chart chart_type : ['z','y','zy', 'yz'] Contour type. Possible values are * *'z'* : lines of constant impedance * *'y'* : lines of constant admittance * *'zy'* : lines of constant impedance stronger than admittance * *'yz'* : lines of constant admittance stronger than impedance draw_labels : Boolean annotate real and imaginary parts of impedance on the chart (only if smithR=1) border : Boolean draw a rectangular border with axis ticks, around the perimeter of the figure. Not used if draw_labels = True ax : matplotlib.axes object existing axes to draw smith chart on ref_imm : number Reference immittance for center of Smith chart. Only changes labels, if printed. draw_vswr : list of numbers, Boolean or None draw VSWR circles. If True, default values are used. ''' ##TODO: fix this function so it doesnt suck if ax == None: ax1 = plb.gca() else: ax1 = ax # contour holds matplotlib instances of: pathes.Circle, and lines.Line2D, which # are the contours on the smith chart contour = [] # these are hard-coded on purpose,as they should always be present rHeavyList = [0,1] xHeavyList = [1,-1] #TODO: fix this # these could be dynamically coded in the future, but work good'nuff for now if not draw_labels: rLightList = plb.logspace(3,-5,9,base=.5) xLightList = plb.hstack([plb.logspace(2,-5,8,base=.5), -1*plb.logspace(2,-5,8,base=.5)]) else: rLightList = plb.array( [ 0.2, 0.5, 1.0, 2.0, 5.0 ] ) xLightList = plb.array( [ 0.2, 0.5, 1.0, 2.0 , 5.0, -0.2, -0.5, -1.0, -2.0, -5.0 ] ) # vswr lines if isinstance(draw_vswr, (tuple,list)): vswrVeryLightList = draw_vswr elif draw_vswr is True: # use the default I like vswrVeryLightList = [1.5, 2.0, 3.0, 5.0] else: vswrVeryLightList = [] # cheap way to make a ok-looking smith chart at larger than 1 radii if smithR > 1: rMax = (1.+smithR)/(1.-smithR) rLightList = plb.hstack([ plb.linspace(0,rMax,11) , rLightList ]) if chart_type.startswith('y'): y_flip_sign = -1 else: y_flip_sign = 1 # draw impedance and/or admittance both_charts = chart_type in ('zy', 'yz') # loops through Verylight, Light and Heavy lists and draws circles using patches # for analysis of this see <NAME> notes (from uva) superLightColor = dict(ec='whitesmoke', fc='none') veryLightColor = dict(ec='lightgrey', fc='none') lightColor = dict(ec='grey', fc='none') heavyColor = dict(ec='black', fc='none') # vswr circules verylight for vswr in vswrVeryLightList: radius = (vswr-1.0) / (vswr+1.0) contour.append( Circle((0, 0), radius, **veryLightColor)) # impedance/admittance circles for r in rLightList: center = (r/(1.+r)*y_flip_sign,0 ) radius = 1./(1+r) if both_charts: contour.insert(0, Circle((-center[0], center[1]), radius, **superLightColor)) contour.append(Circle(center, radius, **lightColor)) for x in xLightList: center = (1*y_flip_sign,1./x) radius = 1./x if both_charts: contour.insert(0, Circle( (-center[0], center[1]), radius, **superLightColor)) contour.append(Circle(center, radius, **lightColor)) for r in rHeavyList: center = (r/(1.+r)*y_flip_sign,0 ) radius = 1./(1+r) contour.append(Circle(center, radius, **heavyColor)) for x in xHeavyList: center = (1*y_flip_sign,1./x) radius = 1./x contour.append(Circle(center, radius, **heavyColor)) # clipping circle clipc = Circle( [0,0], smithR, ec='k',fc='None',visible=True) ax1.add_patch( clipc) #draw x and y axis ax1.axhline(0, color='k', lw=.1, clip_path=clipc) ax1.axvline(1*y_flip_sign, color='k', clip_path=clipc) ax1.grid(0) # Set axis limits by plotting white points so zooming works properly ax1.plot(smithR*npy.array([-1.1, 1.1]), smithR*npy.array([-1.1, 1.1]), 'w.', markersize = 0) ax1.axis('image') # Combination of 'equal' and 'tight' if not border: ax1.yaxis.set_ticks([]) ax1.xaxis.set_ticks([]) for loc, spine in ax1.spines.items(): spine.set_color('none') if draw_labels: #Clear axis ax1.yaxis.set_ticks([]) ax1.xaxis.set_ticks([]) for loc, spine in ax1.spines.items(): spine.set_color('none') # Make annotations only if the radius is 1 if smithR is 1: #Make room for annotation ax1.plot(npy.array([-1.25, 1.25]), npy.array([-1.1, 1.1]), 'w.', markersize = 0) ax1.axis('image') #Annotate real part for value in rLightList: # Set radius of real part's label; offset slightly left (Z # chart, y_flip_sign == 1) or right (Y chart, y_flip_sign == -1) # so label doesn't overlap chart's circles rho = (value - 1)/(value + 1) - y_flip_sign*0.01 if y_flip_sign is 1: halignstyle = "right" else: halignstyle = "left" ax1.annotate(str(value*ref_imm), xy=(rho*smithR, 0.01), xytext=(rho*smithR, 0.01), ha = halignstyle, va = "baseline") #Annotate imaginary part radialScaleFactor = 1.01 # Scale radius of label position by this # factor. Making it >1 places the label # outside the Smith chart's circle for value in xLightList: #Transforms from complex to cartesian S = (1j*value - 1) / (1j*value + 1) S *= smithR * radialScaleFactor rhox = S.real rhoy = S.imag * y_flip_sign # Choose alignment anchor point based on label's value if ((value == 1.0) or (value == -1.0)): halignstyle = "center" elif (rhox < 0.0): halignstyle = "right" else: halignstyle = "left" if (rhoy < 0): valignstyle = "top" else: valignstyle = "bottom" #Annotate value ax1.annotate(str(value*ref_imm) + 'j', xy=(rhox, rhoy), xytext=(rhox, rhoy), ha = halignstyle, va = valignstyle) #Annotate 0 and inf ax1.annotate('0.0', xy=(-1.02, 0), xytext=(-1.02, 0), ha = "right", va = "center") ax1.annotate('$\infty$', xy=(radialScaleFactor, 0), xytext=(radialScaleFactor, 0), ha = "left", va = "center") # annotate vswr circles for vswr in vswrVeryLightList: rhoy = (vswr-1.0) / (vswr+1.0) ax1.annotate(str(vswr), xy=(0, rhoy*smithR), xytext=(0, rhoy*smithR), ha="center", va="bottom", color='grey', size='smaller') # loop though contours and draw them on the given axes for currentContour in contour: cc=ax1.add_patch(currentContour) cc.set_clip_path(clipc) def plot_rectangular(x, y, x_label=None, y_label=None, title=None, show_legend=True, axis='tight', ax=None, *args, **kwargs): ''' plots rectangular data and optionally label axes. Parameters ------------ z : array-like, of complex data data to plot x_label : string x-axis label y_label : string y-axis label title : string plot title show_legend : Boolean controls the drawing of the legend ax : :class:`matplotlib.axes.AxesSubplot` object axes to draw on *args,**kwargs : passed to pylab.plot ''' if ax is None: ax = plb.gca() my_plot = ax.plot(x, y, *args, **kwargs) if x_label is not None: ax.set_xlabel(x_label) if y_label is not None: ax.set_ylabel(y_label) if title is not None: ax.set_title(title) if show_legend: # only show legend if they provide a label if 'label' in kwargs: ax.legend() if axis is not None: ax.autoscale(True, 'x', True) ax.autoscale(True, 'y', False) if plb.isinteractive(): plb.draw() return my_plot def plot_polar(theta, r, x_label=None, y_label=None, title=None, show_legend=True, axis_equal=False, ax=None, *args, **kwargs): ''' plots polar data on a polar plot and optionally label axes. Parameters ------------ theta : array-like data to plot r : array-like x_label : string x-axis label y_label : string y-axis label title : string plot title show_legend : Boolean controls the drawing of the legend ax : :class:`matplotlib.axes.AxesSubplot` object axes to draw on *args,**kwargs : passed to pylab.plot See Also ---------- plot_rectangular : plots rectangular data plot_complex_rectangular : plot complex data on complex plane plot_polar : plot polar data plot_complex_polar : plot complex data on polar plane plot_smith : plot complex data on smith chart ''' if ax is None: ax = plb.gca(polar=True) ax.plot(theta, r, *args, **kwargs) if x_label is not None: ax.set_xlabel(x_label) if y_label is not None: ax.set_ylabel(y_label) if title is not None: ax.set_title(title) if show_legend: # only show legend if they provide a label if 'label' in kwargs: ax.legend() if axis_equal: ax.axis('equal') if plb.isinteractive(): plb.draw() def plot_complex_rectangular(z, x_label='Real', y_label='Imag', title='Complex Plane', show_legend=True, axis='equal', ax=None, *args, **kwargs): ''' plot complex data on the complex plane Parameters ------------ z : array-like, of complex data data to plot x_label : string x-axis label y_label : string y-axis label title : string plot title show_legend : Boolean controls the drawing of the legend ax : :class:`matplotlib.axes.AxesSubplot` object axes to draw on *args,**kwargs : passed to pylab.plot See Also ---------- plot_rectangular : plots rectangular data plot_complex_rectangular : plot complex data on complex plane plot_polar : plot polar data plot_complex_polar : plot complex data on polar plane plot_smith : plot complex data on smith chart ''' x = npy.real(z) y = npy.imag(z) plot_rectangular(x=x, y=y, x_label=x_label, y_label=y_label, title=title, show_legend=show_legend, axis=axis, ax=ax, *args, **kwargs) def plot_complex_polar(z, x_label=None, y_label=None, title=None, show_legend=True, axis_equal=False, ax=None, *args, **kwargs): ''' plot complex data in polar format. Parameters ------------ z : array-like, of complex data data to plot x_label : string x-axis label y_label : string y-axis label title : string plot title show_legend : Boolean controls the drawing of the legend ax : :class:`matplotlib.axes.AxesSubplot` object axes to draw on *args,**kwargs : passed to pylab.plot See Also ---------- plot_rectangular : plots rectangular data plot_complex_rectangular : plot complex data on complex plane plot_polar : plot polar data plot_complex_polar : plot complex data on polar plane plot_smith : plot complex data on smith chart ''' theta = npy.angle(z) r = npy.abs(z) plot_polar(theta=theta, r=r, x_label=x_label, y_label=y_label, title=title, show_legend=show_legend, axis_equal=axis_equal, ax=ax, *args, **kwargs) def plot_smith(s, smith_r=1, chart_type='z', x_label='Real', y_label='Imaginary', title='Complex Plane', show_legend=True, axis='equal', ax=None, force_chart = False, draw_vswr=None, *args, **kwargs): ''' plot complex data on smith chart Parameters ------------ s : complex array-like reflection-coeffient-like data to plot smith_r : number radius of smith chart chart_type : ['z','y'] Contour type for chart. * *'z'* : lines of constant impedance * *'y'* : lines of constant admittance x_label : string x-axis label y_label : string y-axis label title : string plot title show_legend : Boolean controls the drawing of the legend axis_equal: Boolean sets axis to be equal increments (calls axis('equal')) force_chart : Boolean forces the re-drawing of smith chart ax : :class:`matplotlib.axes.AxesSubplot` object axes to draw on *args,**kwargs : passed to pylab.plot See Also ---------- plot_rectangular : plots rectangular data plot_complex_rectangular : plot complex data on complex plane plot_polar : plot polar data plot_complex_polar : plot complex data on polar plane plot_smith : plot complex data on smith chart ''' if ax is None: ax = plb.gca() # test if smith chart is already drawn if not force_chart: if len(ax.patches) == 0: smith(ax=ax, smithR = smith_r, chart_type=chart_type, draw_vswr=draw_vswr) plot_complex_rectangular(s, x_label=x_label, y_label=y_label, title=title, show_legend=show_legend, axis=axis, ax=ax, *args, **kwargs) ax.axis(smith_r*npy.array([-1.1, 1.1, -1.1, 1.1])) if plb.isinteractive(): plb.draw() def subplot_params(ntwk, param='s', proj='db', size_per_port=4, newfig=True, add_titles=True, keep_it_tight=True, subplot_kw={}, *args, **kw): ''' Plot all networks parameters individually on subplots Parameters -------------- ''' if newfig: f,axs= plb.subplots(ntwk.nports,ntwk.nports, figsize =(size_per_port*ntwk.nports, size_per_port*ntwk.nports ), **subplot_kw) else: f = plb.gcf() axs = npy.array(f.get_axes()) for ports,ax in zip(ntwk.port_tuples, axs.flatten()): plot_func = ntwk.__getattribute__('plot_%s_%s'%(param, proj)) plot_func(m=ports[0], n=ports[1], ax=ax,*args, **kw) if add_titles: ax.set_title('%s%i%i'%(param.upper(),ports[0]+1, ports[1]+1)) if keep_it_tight: plb.tight_layout() return f,axs def shade_bands(edges, y_range=None,cmap='prism', **kwargs): ''' Shades frequency bands. when plotting data over a set of frequency bands it is nice to have each band visually separated from the other. The kwarg `alpha` is useful. Parameters -------------- edges : array-like x-values separating regions of a given shade y_range : tuple y-values to shade in cmap : str see matplotlib.cm or matplotlib.colormaps for acceptable values \*\* : key word arguments passed to `matplotlib.fill_between` Examples ----------- >>> rf.shade_bands([325,500,750,1100], alpha=.2) ''' cmap = plb.cm.get_cmap(cmap) y_range=plb.gca().get_ylim() axis = plb.axis() for k in range(len(edges)-1): plb.fill_between( [edges[k],edges[k+1]], y_range[0], y_range[1], color = cmap(1.0*k/len(edges)), **kwargs) plb.axis(axis) def save_all_figs(dir = './', format=None, replace_spaces = True, echo = True): ''' Save all open Figures to disk. Parameters ------------ dir : string path to save figures into format : None, or list of strings the types of formats to save figures as. The elements of this list are passed to :matplotlib:`savefig`. This is a list so that you can save each figure in multiple formats. echo : bool True prints filenames as they are saved ''' if dir[-1] != '/': dir = dir + '/' for fignum in plb.get_fignums(): fileName = plb.figure(fignum).get_axes()[0].get_title() if replace_spaces: fileName = fileName.replace(' ','_') if fileName == '': fileName = 'unnamedPlot' if format is None: plb.savefig(dir+fileName) if echo: print((dir+fileName)) else: for fmt in format: plb.savefig(dir+fileName+'.'+fmt, format=fmt) if echo: print((dir+fileName+'.'+fmt)) saf = save_all_figs def add_markers_to_lines(ax=None,marker_list=['o','D','s','+','x'], markevery=10): ''' adds markers to existing lings on a plot this is convinient if you have already have a plot made, but then need to add markers afterwards, so that it can be interpreted in black and white. The markevery argument makes the markers less frequent than the data, which is generally what you want. Parameters ----------- ax : matplotlib.Axes axis which to add markers to, defaults to gca() marker_list : list of marker characters see matplotlib.plot help for possible marker characters markevery : int markevery number of points with a marker. ''' if ax is None: ax=plb.gca() lines = ax.get_lines() if len(lines) > len (marker_list ): marker_list *= 3 [k[0].set_marker(k[1]) for k in zip(lines, marker_list)] [line.set_markevery(markevery) for line in lines] def legend_off(ax=None): ''' turn off the legend for a given axes. if no axes is given then it will use current axes. Parameters ----------- ax : matplotlib.Axes object axes to operate on ''' if ax is None: plb.gca().legend_.set_visible(0) else: ax.legend_.set_visible(0) def scrape_legend(n=None, ax=None): ''' scrapes a legend with redundant labels Given a legend of m entries of n groups, this will remove all but every m/nth entry. This is used when you plot many lines representing the same thing, and only want one label entry in the legend for the whole ensemble of lines ''' if ax is None: ax = plb.gca() handles, labels = ax.get_legend_handles_labels() if n is None: n =len ( set(labels)) if n>len(handles): raise ValueError('number of entries is too large') k_list = [int(k) for k in npy.linspace(0,len(handles)-1,n)] ax.legend([handles[k] for k in k_list], [labels[k] for k in k_list]) def func_on_all_figs(func, *args, **kwargs): ''' runs a function after making all open figures current. useful if you need to change the properties of many open figures at once, like turn off the grid. Parameters ---------- func : function function to call \*args, \*\*kwargs : pased to func Examples ---------- >>> rf.func_on_all_figs(grid,alpha=.3) ''' for fig_n in plb.get_fignums(): fig = plb.figure(fig_n) for ax_n in fig.axes: fig.add_axes(ax_n) # trick to make axes current func(*args, **kwargs) plb.draw() foaf = func_on_all_figs def plot_vector(a, off=0+0j, *args, **kwargs): ''' plot a 2d vector ''' return quiver(off.real,off.imag,a.real,a.imag,scale_units ='xy', angles='xy',scale=1, *args, **kwargs) def colors(): return rcParams['axes.color_cycle']
[ "pylab.isinteractive", "numpy.abs", "numpy.angle", "matplotlib.pyplot.quiver", "numpy.imag", "pylab.subplots", "pylab.tight_layout", "pylab.figure", "pylab.linspace", "pylab.gcf", "pylab.cm.get_cmap", "pylab.get_fignums", "pylab.draw", "numpy.real", "pylab.array", "matplotlib.patches.Circle", "pylab.savefig", "pylab.logspace", "pylab.axis", "numpy.array", "pylab.gca" ]
[((4918, 4973), 'matplotlib.patches.Circle', 'Circle', (['[0, 0]', 'smithR'], {'ec': '"""k"""', 'fc': '"""None"""', 'visible': '(True)'}), "([0, 0], smithR, ec='k', fc='None', visible=True)\n", (4924, 4973), False, 'from matplotlib.patches import Circle\n'), ((9732, 9751), 'pylab.isinteractive', 'plb.isinteractive', ([], {}), '()\n', (9749, 9751), True, 'import pylab as plb\n'), ((11165, 11184), 'pylab.isinteractive', 'plb.isinteractive', ([], {}), '()\n', (11182, 11184), True, 'import pylab as plb\n'), ((12114, 12125), 'numpy.real', 'npy.real', (['z'], {}), '(z)\n', (12122, 12125), True, 'import numpy as npy\n'), ((12134, 12145), 'numpy.imag', 'npy.imag', (['z'], {}), '(z)\n', (12142, 12145), True, 'import numpy as npy\n'), ((13187, 13199), 'numpy.angle', 'npy.angle', (['z'], {}), '(z)\n', (13196, 13199), True, 'import numpy as npy\n'), ((13208, 13218), 'numpy.abs', 'npy.abs', (['z'], {}), '(z)\n', (13215, 13218), True, 'import numpy as npy\n'), ((15167, 15186), 'pylab.isinteractive', 'plb.isinteractive', ([], {}), '()\n', (15184, 15186), True, 'import pylab as plb\n'), ((16870, 16891), 'pylab.cm.get_cmap', 'plb.cm.get_cmap', (['cmap'], {}), '(cmap)\n', (16885, 16891), True, 'import pylab as plb\n'), ((16936, 16946), 'pylab.axis', 'plb.axis', ([], {}), '()\n', (16944, 16946), True, 'import pylab as plb\n'), ((17150, 17164), 'pylab.axis', 'plb.axis', (['axis'], {}), '(axis)\n', (17158, 17164), True, 'import pylab as plb\n'), ((17765, 17782), 'pylab.get_fignums', 'plb.get_fignums', ([], {}), '()\n', (17780, 17782), True, 'import pylab as plb\n'), ((20815, 20832), 'pylab.get_fignums', 'plb.get_fignums', ([], {}), '()\n', (20830, 20832), True, 'import pylab as plb\n'), ((21135, 21239), 'matplotlib.pyplot.quiver', 'quiver', (['off.real', 'off.imag', 'a.real', 'a.imag', '*args'], {'scale_units': '"""xy"""', 'angles': '"""xy"""', 'scale': '(1)'}), "(off.real, off.imag, a.real, a.imag, *args, scale_units='xy', angles=\n 'xy', scale=1, **kwargs)\n", (21141, 21239), False, 'from matplotlib.pyplot import quiver\n'), ((2127, 2136), 'pylab.gca', 'plb.gca', ([], {}), '()\n', (2134, 2136), True, 'import pylab as plb\n'), ((2574, 2606), 'pylab.logspace', 'plb.logspace', (['(3)', '(-5)', '(9)'], {'base': '(0.5)'}), '(3, -5, 9, base=0.5)\n', (2586, 2606), True, 'import pylab as plb\n'), ((2731, 2767), 'pylab.array', 'plb.array', (['[0.2, 0.5, 1.0, 2.0, 5.0]'], {}), '([0.2, 0.5, 1.0, 2.0, 5.0])\n', (2740, 2767), True, 'import pylab as plb\n'), ((2793, 2859), 'pylab.array', 'plb.array', (['[0.2, 0.5, 1.0, 2.0, 5.0, -0.2, -0.5, -1.0, -2.0, -5.0]'], {}), '([0.2, 0.5, 1.0, 2.0, 5.0, -0.2, -0.5, -1.0, -2.0, -5.0])\n', (2802, 2859), True, 'import pylab as plb\n'), ((9256, 9265), 'pylab.gca', 'plb.gca', ([], {}), '()\n', (9263, 9265), True, 'import pylab as plb\n'), ((9761, 9771), 'pylab.draw', 'plb.draw', ([], {}), '()\n', (9769, 9771), True, 'import pylab as plb\n'), ((10743, 10762), 'pylab.gca', 'plb.gca', ([], {'polar': '(True)'}), '(polar=True)\n', (10750, 10762), True, 'import pylab as plb\n'), ((11194, 11204), 'pylab.draw', 'plb.draw', ([], {}), '()\n', (11202, 11204), True, 'import pylab as plb\n'), ((14750, 14759), 'pylab.gca', 'plb.gca', ([], {}), '()\n', (14757, 14759), True, 'import pylab as plb\n'), ((15196, 15206), 'pylab.draw', 'plb.draw', ([], {}), '()\n', (15204, 15206), True, 'import pylab as plb\n'), ((15527, 15651), 'pylab.subplots', 'plb.subplots', (['ntwk.nports', 'ntwk.nports'], {'figsize': '(size_per_port * ntwk.nports, size_per_port * ntwk.nports)'}), '(ntwk.nports, ntwk.nports, figsize=(size_per_port * ntwk.nports,\n size_per_port * ntwk.nports), **subplot_kw)\n', (15539, 15651), True, 'import pylab as plb\n'), ((15771, 15780), 'pylab.gcf', 'plb.gcf', ([], {}), '()\n', (15778, 15780), True, 'import pylab as plb\n'), ((16136, 16154), 'pylab.tight_layout', 'plb.tight_layout', ([], {}), '()\n', (16152, 16154), True, 'import pylab as plb\n'), ((19067, 19076), 'pylab.gca', 'plb.gca', ([], {}), '()\n', (19074, 19076), True, 'import pylab as plb\n'), ((20018, 20027), 'pylab.gca', 'plb.gca', ([], {}), '()\n', (20025, 20027), True, 'import pylab as plb\n'), ((20848, 20865), 'pylab.figure', 'plb.figure', (['fig_n'], {}), '(fig_n)\n', (20858, 20865), True, 'import pylab as plb\n'), ((3973, 4013), 'matplotlib.patches.Circle', 'Circle', (['(0, 0)', 'radius'], {}), '((0, 0), radius, **veryLightColor)\n', (3979, 4013), False, 'from matplotlib.patches import Circle\n'), ((4282, 4318), 'matplotlib.patches.Circle', 'Circle', (['center', 'radius'], {}), '(center, radius, **lightColor)\n', (4288, 4318), False, 'from matplotlib.patches import Circle\n'), ((4543, 4579), 'matplotlib.patches.Circle', 'Circle', (['center', 'radius'], {}), '(center, radius, **lightColor)\n', (4549, 4579), False, 'from matplotlib.patches import Circle\n'), ((4699, 4735), 'matplotlib.patches.Circle', 'Circle', (['center', 'radius'], {}), '(center, radius, **heavyColor)\n', (4705, 4735), False, 'from matplotlib.patches import Circle\n'), ((4845, 4881), 'matplotlib.patches.Circle', 'Circle', (['center', 'radius'], {}), '(center, radius, **heavyColor)\n', (4851, 4881), False, 'from matplotlib.patches import Circle\n'), ((5244, 5266), 'numpy.array', 'npy.array', (['[-1.1, 1.1]'], {}), '([-1.1, 1.1])\n', (5253, 5266), True, 'import numpy as npy\n'), ((5275, 5297), 'numpy.array', 'npy.array', (['[-1.1, 1.1]'], {}), '([-1.1, 1.1])\n', (5284, 5297), True, 'import numpy as npy\n'), ((15125, 15158), 'numpy.array', 'npy.array', (['[-1.1, 1.1, -1.1, 1.1]'], {}), '([-1.1, 1.1, -1.1, 1.1])\n', (15134, 15158), True, 'import numpy as npy\n'), ((16904, 16913), 'pylab.gca', 'plb.gca', ([], {}), '()\n', (16911, 16913), True, 'import pylab as plb\n'), ((18027, 18054), 'pylab.savefig', 'plb.savefig', (['(dir + fileName)'], {}), '(dir + fileName)\n', (18038, 18054), True, 'import pylab as plb\n'), ((21002, 21012), 'pylab.draw', 'plb.draw', ([], {}), '()\n', (21010, 21012), True, 'import pylab as plb\n'), ((2636, 2668), 'pylab.logspace', 'plb.logspace', (['(2)', '(-5)', '(8)'], {'base': '(0.5)'}), '(2, -5, 8, base=0.5)\n', (2648, 2668), True, 'import pylab as plb\n'), ((3281, 3306), 'pylab.linspace', 'plb.linspace', (['(0)', 'rMax', '(11)'], {}), '(0, rMax, 11)\n', (3293, 3306), True, 'import pylab as plb\n'), ((4199, 4257), 'matplotlib.patches.Circle', 'Circle', (['(-center[0], center[1])', 'radius'], {}), '((-center[0], center[1]), radius, **superLightColor)\n', (4205, 4257), False, 'from matplotlib.patches import Circle\n'), ((4459, 4517), 'matplotlib.patches.Circle', 'Circle', (['(-center[0], center[1])', 'radius'], {}), '((-center[0], center[1]), radius, **superLightColor)\n', (4465, 4517), False, 'from matplotlib.patches import Circle\n'), ((5891, 5915), 'numpy.array', 'npy.array', (['[-1.25, 1.25]'], {}), '([-1.25, 1.25])\n', (5900, 5915), True, 'import numpy as npy\n'), ((5917, 5939), 'numpy.array', 'npy.array', (['[-1.1, 1.1]'], {}), '([-1.1, 1.1])\n', (5926, 5939), True, 'import numpy as npy\n'), ((18173, 18224), 'pylab.savefig', 'plb.savefig', (["(dir + fileName + '.' + fmt)"], {'format': 'fmt'}), "(dir + fileName + '.' + fmt, format=fmt)\n", (18184, 18224), True, 'import pylab as plb\n'), ((2669, 2701), 'pylab.logspace', 'plb.logspace', (['(2)', '(-5)', '(8)'], {'base': '(0.5)'}), '(2, -5, 8, base=0.5)\n', (2681, 2701), True, 'import pylab as plb\n'), ((19552, 19561), 'pylab.gca', 'plb.gca', ([], {}), '()\n', (19559, 19561), True, 'import pylab as plb\n'), ((17803, 17821), 'pylab.figure', 'plb.figure', (['fignum'], {}), '(fignum)\n', (17813, 17821), True, 'import pylab as plb\n')]
import os import torch from itertools import combinations import six import collections from tqdm import tqdm, trange import numpy as np np.set_printoptions(threshold=10010) def check_uniqueness(iterable_list): flag = 0 for array1, array2 in combinations(iterable_list, 2): for i in range(len(array1)): for j in range(len(array2)): if array1[i] == array2[j]: print("Ouch! ", i, "th element of array 1 with value ", str(array1[i]), " and ", str(j), "th element of array 2 with value ", str(array2[j])) flag += 1 if flag == 0: print("All is well!") if flag != 0: print(str(flag) + " repetitions... Reformulate data points!") def flatten_grad(grad): tuple_to_list = [] for tensor in grad: tuple_to_list.append(tensor.view(-1)) all_flattened = torch.cat(tuple_to_list) return all_flattened def find_hessian(loss, model): grad1 = torch.autograd.grad(loss, model.parameters(), create_graph=True) #create graph important for the gradients grad1 = flatten_grad(grad1) list_length = grad1.size(0) hessian = torch.zeros(list_length, list_length) for idx in trange(list_length, desc="Calculating hessian"): grad2rd = torch.autograd.grad(grad1[idx], model.parameters(), create_graph=True) cnt = 0 for g in grad2rd: g2 = g.contiguous().view(-1) if cnt == 0 else torch.cat([g2, g.contiguous().view(-1)]) cnt = 1 hessian[idx] = g2.detach().cpu() del g2 H = hessian.cpu().data.numpy() # calculate every element separately -> detach after calculating all 2ndgrad from this 1grad return H def find_heigenvalues(loss, model): H = find_hessian(loss, model) eigenvalues = np.linalg.eigvalsh(H) return eigenvalues def save_to_file(list, filename, folder_name = None): if folder_name is None: folder_name = 'tmp' if isinstance(list, torch.Tensor): if list.requires_grad is True: list = list.detach().numpy() list_to_string = np.array2string(np.asarray(list), separator=' ', max_line_width=np.inf) list_wo_brackets = list_to_string.translate({ord(i): None for i in '[]'}) file = open(folder_name + '/' + filename, 'w') file.write(list_wo_brackets) file.close() def append_to_file(list, filename, folder_name = None, delimiter = ' '): if folder_name is None: folder_name = 'tmp' if isinstance(list, torch.Tensor): if list.requires_grad is True: list = list.detach().numpy() list_to_string = np.array2string(np.asarray(list), separator=delimiter, max_line_width=np.inf) list_wo_brackets = list_to_string.translate({ord(i): None for i in '[]'}) file = open(folder_name + '/' + filename, 'a') file.write("\n") file.close() file = open(folder_name + '/' + filename, 'a') file.write(list_wo_brackets) file.close() def remove_slash(path): return path[:-1] if path[-1] == '/' else path # nD list to 1D list def flatten(list): if isinstance(list, collections.Iterable): return [a for i in list for a in flatten(i)] else: return [list]
[ "numpy.set_printoptions", "tqdm.trange", "numpy.asarray", "torch.cat", "numpy.linalg.eigvalsh", "itertools.combinations", "torch.zeros" ]
[((138, 174), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': '(10010)'}), '(threshold=10010)\n', (157, 174), True, 'import numpy as np\n'), ((252, 282), 'itertools.combinations', 'combinations', (['iterable_list', '(2)'], {}), '(iterable_list, 2)\n', (264, 282), False, 'from itertools import combinations\n'), ((872, 896), 'torch.cat', 'torch.cat', (['tuple_to_list'], {}), '(tuple_to_list)\n', (881, 896), False, 'import torch\n'), ((1152, 1189), 'torch.zeros', 'torch.zeros', (['list_length', 'list_length'], {}), '(list_length, list_length)\n', (1163, 1189), False, 'import torch\n'), ((1206, 1253), 'tqdm.trange', 'trange', (['list_length'], {'desc': '"""Calculating hessian"""'}), "(list_length, desc='Calculating hessian')\n", (1212, 1253), False, 'from tqdm import tqdm, trange\n'), ((1824, 1845), 'numpy.linalg.eigvalsh', 'np.linalg.eigvalsh', (['H'], {}), '(H)\n', (1842, 1845), True, 'import numpy as np\n'), ((2138, 2154), 'numpy.asarray', 'np.asarray', (['list'], {}), '(list)\n', (2148, 2154), True, 'import numpy as np\n'), ((2661, 2677), 'numpy.asarray', 'np.asarray', (['list'], {}), '(list)\n', (2671, 2677), True, 'import numpy as np\n')]
"""3D Bar plot of a TOF camera with hexagonal pixels""" from vedo import * import numpy as np settings.defaultFont = "Glasgo" settings.useParallelProjection = True vals = np.abs(np.random.randn(4*6)) # pixel heights cols = colorMap(vals, "summer") k = 0 items = [__doc__] for i in range(4): for j in range(6): val, col= vals[k], cols[k] x, y, z = [i+j%2/2, j/1.155, val+0.01] zbar= Polygon([x,y,0], nsides=6, r=0.55, c=col).extrude(val) line= Polygon([x,y,z], nsides=6, r=0.55, c='k').wireframe().lw(2) txt = Text3D(f"{i}/{j}", [x,y,z], s=.15, c='k', justify='center') items += [zbar, line, txt] k += 1 show(items, axes=7)
[ "numpy.random.randn" ]
[((180, 202), 'numpy.random.randn', 'np.random.randn', (['(4 * 6)'], {}), '(4 * 6)\n', (195, 202), True, 'import numpy as np\n')]
""" Implements ZOO (Zero-Order Optimization) Attack. This code is based on the L2-attack from the original implementation of the attack: https://github.com/huanzhang12/ZOO-Attack/blob/master/l2_attack_black.py Usage: >>> import json >>> from code_soup.ch5.models.zoo_attack import ZOOAttack >>> config = json.load(open('./code-soup/ch5/models/configs/zoo_attack.json')) >>> attack = ZOOAttack(model, config, input_image_shape=[28, 28, 3], device = 'cpu') >>> adv_img, const = attack.attack(orig_img, target) """ from typing import Dict, List import cv2 import numpy as np import torch import torch.nn.functional as F from PIL import Image class ZooAttack: """ Implements the ZooAttack class. """ def __init__( self, model: torch.nn.Module, config: Dict, input_image_shape: List[int], device: str, ): """Initializes the ZooAttack class. Args: model (torch.nn.Module): A PyTorch model. config (Dict): A dictionary containing the configuration for the attack. input_image_shape (List[int]): A tuple of ints containing the shape of the input image. device (str): The device to perform the attack on. Raises: NotImplementedError: If `use_tanh` is `False` and `use_resize` is `True`. """ assert len(input_image_shape) == 3, "`input_image_shape` must be of length 3" self.config = config if self.config["use_tanh"] is False and self.config["use_resize"] is True: # NOTE: self.up and self.down need to be updated dynamically to match the modifier shape. # Original Implementation is possibly flawed in this aspect. raise NotImplementedError( "Current implementation does not support `use_tanh` as `False` and `use_resize` as `True` at the same time." ) if self.config["early_stop_iters"] == 0: self.config["early_stop_iters"] = self.config["max_iterations"] // 10 self.device = device self.input_image_shape = input_image_shape # Put model in eval mode self.model = model.to(device) self.model.eval() # DUMMIES - Values will be reset during attack var_size = np.prod(input_image_shape) # width * height * num_channels self.var_list = np.array(range(0, var_size), dtype=np.int32) # Initialize Adam optimizer values self.mt_arr = np.zeros(var_size, dtype=np.float32) self.vt_arr = np.zeros(var_size, dtype=np.float32) self.adam_epochs = np.ones(var_size, dtype=np.int64) # Sampling Probabilities self.sample_prob = np.ones(var_size, dtype=np.float32) / var_size def get_perturbed_image(self, orig_img: torch.tensor, modifier: np.ndarray): """Calculates the perturbed image given `orig_img` and `modifier`. Args: orig_img (torch.tensor): The original image with a batch dimension. Expected batch size is 1. Using any other batch size may lead to unexpected behavior. modifier (np.ndarray): A numpy array with modifier(s) for the image. Returns: torch.tensor: The perturbed image from original image and modifier. """ assert orig_img.ndim == 4, "`orig_img` must be a 4D tensor" assert modifier.ndim == 4, "`modifier` must be a 4D tensor" b = modifier.shape[0] x = orig_img.shape[1] y = orig_img.shape[2] z = orig_img.shape[3] new_modifier = np.zeros((b, x, y, z), dtype=np.float32) if x != modifier.shape[1] or y != modifier.shape[2]: for k, v in enumerate(modifier): new_modifier[k, :, :, :] = cv2.resize( modifier[k, :, :, :], (x, y), interpolation=cv2.INTER_LINEAR, ) else: new_modifier = modifier if self.config["use_tanh"]: return torch.tanh(orig_img + new_modifier) / 2 else: return orig_img + new_modifier def l2_distance_loss(self, orig_img: torch.tensor, new_img: torch.tensor): """Calculates the L2 loss between the image and the new images. Args: orig_img (torch.tensor): The original image tensor. new_img (torch.tensor): The tensor containing the perturbed images from the original image. Returns: np.ndarray: The numpy array containing the L2 loss between the original image and the perturbed images. """ # assert orig_img.shape == new_img.shape, "Images must be the same shape" assert new_img.ndim == 4, "`new_img` must be a 4D tensor" dim = (1, 2, 3) if self.config["use_tanh"]: return ( torch.sum(torch.square(new_img - torch.tanh(orig_img) / 2), dim=dim) .detach() .cpu() .numpy() ) else: return ( torch.sum(torch.square(new_img - orig_img), dim=dim) .detach() .cpu() .numpy() ) def confidence_loss(self, new_img: torch.tensor, target: torch.tensor): """Calculate the confidence loss between the perturbed images and target. Args: new_img (torch.tensor): A 4D tensor containing the perturbed images. target (torch.tensor): A 2D tensor containing the target labels. Returns: np.ndarray: A numpy array containing the confidence loss between the perturbed images and target. """ assert new_img.ndim == 4, "`new_img` must be of shape (N, H, W, C)" assert ( target.ndim == 2 ), "`target` must be of shape (N,L) where L is number of classes" new_img = new_img.permute(0, 3, 1, 2) model_output = self.model(new_img) if self.config["use_log"]: model_output = F.softmax(model_output, dim=1) real = torch.sum(target * model_output, dim=1) other = torch.max((1 - target) * model_output - (target * 10000), dim=1)[0] if self.config["use_log"]: real = torch.log(real + 1e-30) other = torch.log(other + 1e-30) confidence = torch.tensor(self.config["confidence"], device=self.device).type( torch.float64 ) if self.config["targeted"]: # If targetted, optimize for making the other class most likely output = ( torch.max(torch.zeros_like(real), other - real + confidence) .detach() .cpu() .numpy() ) else: # If untargetted, optimize for making this class least likely. output = ( torch.max(torch.zeros_like(real), real - other + confidence) .detach() .cpu() .numpy() ) return output, model_output def total_loss( self, orig_img: torch.tensor, new_img: torch.tensor, target: torch.tensor, const: int, ): """Calculate the total loss for the original image and the perturbed images. Args: orig_img (torch.tensor): A 4D tensor containing the original image. new_img (torch.tensor): A 4D tensor containing the perturbed images. target (torch.tensor): A 2D tensor containing the target labels. const (int): The constant to be used in calculating the loss, with which confidence loss is scaled. Returns: np.ndarray: A numpy array containing the total loss for the original image and the perturbed images. """ l2_loss = self.l2_distance_loss(orig_img, new_img) confidence_loss, model_output = self.confidence_loss(new_img, target) return ( l2_loss + const * confidence_loss, l2_loss, confidence_loss, model_output, ) # Adapted from original code def max_pooling(self, modifier: np.ndarray, patch_size: int): """Max pooling operation on a single-channel modifier with a given patch size. The array remains the same size after the operation, only the patches have max value throughout. Args: modifier (np.ndarray): A numpy array containing a channel of the perturbation. patch_size (int): The size of the patches to be max pooled. Returns: np.ndarray: A 2D modifier array containing the max pooled patches. """ assert modifier.ndim == 2, "`modifier` must be a 2D array" img_pool = np.copy(modifier) img_x = modifier.shape[0] img_y = modifier.shape[1] for i in range(0, img_x, patch_size): for j in range(0, img_y, patch_size): img_pool[i : i + patch_size, j : j + patch_size] = np.max( modifier[i : i + patch_size, j : j + patch_size] ) return img_pool def zero_order_gradients(self, losses: np.ndarray): """Calculate the zero order gradients for the losses. Args: losses (np.ndarray): A numpy array containing the losses with length - 2 * batch_size + 1 Returns: np.ndarray: A numpy array containing the zero order gradients for the losses. """ grad = np.zeros(self.config["batch_size"]) for i in range(self.config["batch_size"]): grad[i] = (losses[i * 2 + 1] - losses[i * 2 + 2]) / 0.0002 return grad def coordinate_adam( self, indices: np.ndarray, grad: np.ndarray, modifier: np.ndarray, proj: bool ): """Perform inplace coordinate-wise Adam update on modifier. Args: indices (np.ndarray): A numpy array containing the indices of the coordinates to be updated. grad (np.ndarray): A numpy array containing the gradients. modifier (np.ndarray): A numpy array containing the current modifier/perturbation. proj (bool): Whether to limit the new values of the modifier between up and down limits. """ # First moment mt = self.mt_arr[indices] mt = self.config["adam_beta1"] * mt + (1 - self.config["adam_beta1"]) * grad self.mt_arr[indices] = mt # Second moment vt = self.vt_arr[indices] vt = self.config["adam_beta2"] * vt + (1 - self.config["adam_beta2"]) * ( grad * grad ) self.vt_arr[indices] = vt epochs = self.adam_epochs[indices] # Bias Correction mt_hat = mt / (1 - np.power(self.config["adam_beta1"], epochs)) vt_hat = vt / (1 - np.power(self.config["adam_beta2"], epochs)) m = modifier.reshape(-1) old_val = m[indices] old_val -= ( self.config["learning_rate"] * mt_hat / (np.sqrt(vt_hat) + self.config["adam_eps"]) ) if proj: old_val = np.maximum( np.minimum(old_val, self.up[indices]), self.down[indices] ) m[indices] = old_val self.adam_epochs[indices] = epochs + 1 # return m.reshape(modifier.shape) # Adapted from original code def get_new_prob( self, modifier: np.ndarray, max_pooling_ratio: int = 8, gen_double: bool = False ): """ Calculate the new probabilities by performing max pooling on the modifier. Args: modifier (np.ndarray): A numpy array containing the perturbation. max_pooling_ratio (int): The ratio of the size of the patches to be max pooled. gen_double (bool): Whether to double the size of the perturbation after max pooling. Returns: np.ndarray: A numpy array containing the new probabilities. """ modifier = np.squeeze(modifier) old_shape = modifier.shape if gen_double: new_shape = (old_shape[0] * 2, old_shape[1] * 2, old_shape[2]) else: new_shape = old_shape prob = np.empty(shape=new_shape, dtype=np.float32) for i in range(modifier.shape[2]): image = np.abs(modifier[:, :, i]) image_pool = self.max_pooling(image, old_shape[0] // max_pooling_ratio) if gen_double: prob[:, :, i] = np.array( Image.fromarray(image_pool).resize( (new_shape[0], new_shape[1]), Image.NEAREST ) ) else: prob[:, :, i] = image_pool # NOTE: This is here to handle all zeros input if np.sum(prob) != 0: prob /= np.sum(prob) else: # pragma: no cover prob = np.ones(shape=new_shape, dtype=np.float32) prob /= np.sum(prob) return prob # Adapted from original code def resize_img( self, small_x: int, small_y: int, num_channels: int, modifier: np.ndarray, max_pooling_ratio: int = 8, reset_only: bool = False, ): """ Resize the image to the specified size. Args: small_x (int): The new x size of the image. small_y (int): The new y size of the image. num_channels (int): The number of channels in the image. modifier (np.ndarray): A numpy array containing the perturbation. max_pooling_ratio (int): The ratio of the size of the patches to be max pooled. reset_only (bool): Whether to only reset the image, or to resize and crop as well. """ small_single_shape = (small_x, small_y, num_channels) new_modifier = np.zeros((1,) + small_single_shape, dtype=np.float32) if not reset_only: # run the resize_op once to get the scaled image assert modifier.ndim == 4, "Expected 4D array as modifier" prev_modifier = np.copy(modifier) for k, v in enumerate(modifier): new_modifier[k, :, :, :] = cv2.resize( modifier[k, :, :, :], (small_x, small_y), interpolation=cv2.INTER_LINEAR, ) # prepare the list of all valid variables var_size = np.prod(small_single_shape) self.var_list = np.array(range(0, var_size), dtype=np.int32) # ADAM status self.mt_arr = np.zeros(var_size, dtype=np.float32) self.vt_arr = np.zeros(var_size, dtype=np.float32) self.adam_epochs = np.ones(var_size, dtype=np.int32) # update sample probability if reset_only: self.sample_prob = np.ones(var_size, dtype=np.float32) / var_size else: self.sample_prob = self.get_new_prob(prev_modifier, max_pooling_ratio, True) self.sample_prob = self.sample_prob.reshape(var_size) return new_modifier def single_step( self, modifier: np.ndarray, orig_img: torch.tensor, target: torch.tensor, const: int, max_pooling_ratio: int = 8, var_indice: list = None, ): """ Perform a single step of optimization. Args: modifier (np.ndarray): A numpy array containing the perturbation. orig_img (torch.tensor): The original image. target (torch.tensor): The target image. const (int): The constant to be used in the loss function. max_pooling_ratio (int): The ratio of the size of the patches to be max pooled. var_indice (list): The indices of the coordinates to be optimized. Returns: (float, float, float, np.ndarray, torch.tensor): The total loss, the L2 loss, the confidence loss, model output on perturbed image, the perturbed image. """ assert modifier.ndim == 4, "Expected 4D array as modifier" assert modifier.shape[0] == 1, "Expected 1 batch for modifier" assert target.ndim == 2, "Expected 2D tensor as target" var = np.repeat(modifier, self.config["batch_size"] * 2 + 1, axis=0) var_size = modifier.size # Select indices for current iteration if var_indice is None: if self.config["use_importance"]: var_indice = np.random.choice( self.var_list.size, self.config["batch_size"], replace=False, p=self.sample_prob, ) else: var_indice = np.random.choice( self.var_list.size, self.config["batch_size"], replace=False ) indices = self.var_list[var_indice] for i in range(self.config["batch_size"]): var[i * 2 + 1].reshape(-1)[indices[i]] += 0.0001 var[i * 2 + 2].reshape(-1)[indices[i]] -= 0.0001 new_img = self.get_perturbed_image(orig_img, var) losses, l2_losses, confidence_losses, model_output = self.total_loss( orig_img, new_img, target, const ) if modifier.shape[1] > self.config["init_size"]: self.sample_prob = self.get_new_prob( modifier, max_pooling_ratio=max_pooling_ratio ) self.sample_prob = self.sample_prob.reshape(var_size) grad = self.zero_order_gradients(losses) # Modifier is updated here, so is adam epochs, mt_arr, and vt_arr self.coordinate_adam(indices, grad, modifier, not self.config["use_tanh"]) return ( losses[0], l2_losses[0], confidence_losses[0], model_output[0].detach().numpy(), new_img[0], ) def attack( self, orig_img: np.ndarray, target: np.ndarray, modifier_init: np.ndarray = None, max_pooling_ratio: int = 8, ): """ Perform the attack on coordinate-batches. Args: orig_img (np.ndarray): The original image. target (np.ndarray): The target image. modifier_init (np.ndarray): The initial modifier. Default is `None`. max_pooling_ratio (int): The ratio of the size of the patches to be max pooled. Returns: (np.ndarray, np.ndarray): The best perturbed image and best constant for scaling confidence loss. """ def compare(x, y): if not isinstance(x, (float, int, np.int64)): x = np.copy(x) if self.config["targeted"]: x[y] -= self.config["confidence"] else: x[y] += self.config["confidence"] x = np.argmax(x) if self.config["targeted"]: return x == y else: return x != y assert orig_img.ndim == 3, "Expected 3D array as image" assert target.ndim == 1, "Expected 1D array as target" if modifier_init is not None: assert modifier_init.ndim == 3, "Expected 3D array as modifier" modifier = modifier_init.copy() else: if self.config["use_resize"]: modifier = self.resize_img( self.config["init_size"], self.config["init_size"], 3, modifier_init, max_pooling_ratio, reset_only=True, ) else: modifier = np.zeros(orig_img.shape, dtype=np.float32) if self.config["use_tanh"]: orig_img = np.arctanh(orig_img * 1.999999) var_size = np.prod(orig_img.shape) # width * height * num_channels self.var_list = np.array(range(0, var_size), dtype=np.int32) # Initialize Adam optimizer values self.mt_arr = np.zeros(var_size, dtype=np.float32) self.vt_arr = np.zeros(var_size, dtype=np.float32) self.adam_epochs = np.ones(var_size, dtype=np.int64) self.up = np.zeros(var_size, dtype=np.float32) self.down = np.zeros(var_size, dtype=np.float32) # Sampling Probabilities self.sample_prob = np.ones(var_size, dtype=np.float32) / var_size low = 0.0 mid = self.config["initial_const"] high = 1e10 if not self.config["use_tanh"]: self.up = 0.5 - orig_img.reshape(-1) self.down = -0.5 - orig_img.reshape(-1) outer_best_const = mid outer_best_l2 = 1e10 outer_best_score = -1 outer_best_adv = orig_img # Make Everything 4D and Tensorize orig_img = torch.from_numpy(orig_img).unsqueeze(0).to(self.device) target = torch.from_numpy(target).unsqueeze(0).to(self.device) modifier = modifier.reshape((-1,) + modifier.shape) for outer_step in range(self.config["binary_search_steps"]): best_l2 = 1e10 best_score = -1 # NOTE: In the original implemenation there is a step to move mid to high # at last step with some condition prev = 1e6 last_confidence_loss = 1.0 if modifier_init is not None: assert modifier_init.ndim == 3, "Expected 3D array as modifier" modifier = modifier_init.copy() modifier = modifier.reshape((-1,) + modifier.shape) else: if self.config["use_resize"]: modifier = self.resize_img( self.config["init_size"], self.config["init_size"], 3, modifier_init, max_pooling_ratio, reset_only=True, ) else: modifier = np.zeros(orig_img.shape, dtype=np.float32) self.mt_arr.fill(0.0) self.vt_arr.fill(0.0) self.adam_epochs.fill(1) stage = 0 eval_costs = 0 # NOTE: Original code allows for a custom start point in iterations for iter in range(0, self.config["max_iterations"]): if self.config["use_resize"]: if iter == self.config["resize_iter_1"]: modifier = self.resize_img( self.config["init_size"] * 2, self.config["init_size"] * 2, 3, modifier, max_pooling_ratio, ) if iter == self.config["resize_iter_2"]: modifier = self.resize_img( self.config["init_size"] * 4, self.config["init_size"] * 4, 3, modifier, max_pooling_ratio, ) if iter % (self.config["max_iterations"] // 10) == 0: new_img = self.get_perturbed_image(orig_img, modifier) ( total_losses, l2_losses, confidence_losses, model_output, ) = self.total_loss(orig_img, new_img, target, mid) print( f"iter = {iter}, cost = {eval_costs}, size = {modifier.shape}, " f"total_loss = {total_losses[0]:.5g}, l2_loss = {l2_losses[0]:.5g}, " f"confidence_loss = {confidence_losses[0]:.5g}" ) ( total_loss, l2_loss, confidence_loss, model_output, adv_img, ) = self.single_step( modifier, orig_img, target, mid, max_pooling_ratio=max_pooling_ratio ) eval_costs += self.config["batch_size"] if ( confidence_loss == 0.0 and last_confidence_loss != 0.0 and stage == 0 ): if self.config["reset_adam_after_found"]: print("Resetting Adam") self.mt_arr.fill(0.0) self.vt_arr.fill(0.0) self.adam_epochs.fill(1) print("Setting Stage to 1") stage = 1 last_confidence_loss = confidence_loss if ( self.config["abort_early"] and iter % self.config["early_stop_iters"] == 0 ): if total_loss > prev * 0.9999: print("Early stopping because there is no improvement") break prev = total_loss if l2_loss < best_l2 and compare(model_output, np.argmax(target[0])): best_l2 = l2_loss best_score = np.argmax(model_output) if l2_loss < outer_best_l2 and compare( model_output, np.argmax(target[0]) ): outer_best_l2 = l2_loss outer_best_score = np.argmax(model_output) outer_best_adv = adv_img outer_best_const = mid if compare(best_score, np.argmax(target[0])) and best_score != -1: print("Old Constant: ", mid) high = min(high, mid) if high < 1e9: mid = (low + high) / 2 print("New Constant: ", mid) else: print("Old Constant: ", mid) low = max(low, mid) if high < 1e9: # pragma: no cover mid = (low + high) / 2 else: # pragma: no cover mid *= 10 print("new constant: ", mid) return outer_best_adv, outer_best_const
[ "numpy.abs", "numpy.sum", "numpy.argmax", "numpy.empty", "numpy.ones", "numpy.prod", "torch.square", "numpy.arctanh", "numpy.copy", "numpy.power", "numpy.max", "numpy.random.choice", "torch.log", "cv2.resize", "numpy.repeat", "numpy.minimum", "torch.zeros_like", "torch.max", "numpy.squeeze", "torch.sum", "torch.tanh", "torch.from_numpy", "numpy.zeros", "torch.nn.functional.softmax", "PIL.Image.fromarray", "torch.tensor", "numpy.sqrt" ]
[((2303, 2329), 'numpy.prod', 'np.prod', (['input_image_shape'], {}), '(input_image_shape)\n', (2310, 2329), True, 'import numpy as np\n'), ((2498, 2534), 'numpy.zeros', 'np.zeros', (['var_size'], {'dtype': 'np.float32'}), '(var_size, dtype=np.float32)\n', (2506, 2534), True, 'import numpy as np\n'), ((2557, 2593), 'numpy.zeros', 'np.zeros', (['var_size'], {'dtype': 'np.float32'}), '(var_size, dtype=np.float32)\n', (2565, 2593), True, 'import numpy as np\n'), ((2621, 2654), 'numpy.ones', 'np.ones', (['var_size'], {'dtype': 'np.int64'}), '(var_size, dtype=np.int64)\n', (2628, 2654), True, 'import numpy as np\n'), ((3590, 3630), 'numpy.zeros', 'np.zeros', (['(b, x, y, z)'], {'dtype': 'np.float32'}), '((b, x, y, z), dtype=np.float32)\n', (3598, 3630), True, 'import numpy as np\n'), ((6083, 6122), 'torch.sum', 'torch.sum', (['(target * model_output)'], {'dim': '(1)'}), '(target * model_output, dim=1)\n', (6092, 6122), False, 'import torch\n'), ((8774, 8791), 'numpy.copy', 'np.copy', (['modifier'], {}), '(modifier)\n', (8781, 8791), True, 'import numpy as np\n'), ((9514, 9549), 'numpy.zeros', 'np.zeros', (["self.config['batch_size']"], {}), "(self.config['batch_size'])\n", (9522, 9549), True, 'import numpy as np\n'), ((12004, 12024), 'numpy.squeeze', 'np.squeeze', (['modifier'], {}), '(modifier)\n', (12014, 12024), True, 'import numpy as np\n'), ((12221, 12264), 'numpy.empty', 'np.empty', ([], {'shape': 'new_shape', 'dtype': 'np.float32'}), '(shape=new_shape, dtype=np.float32)\n', (12229, 12264), True, 'import numpy as np\n'), ((13867, 13920), 'numpy.zeros', 'np.zeros', (['((1,) + small_single_shape)'], {'dtype': 'np.float32'}), '((1,) + small_single_shape, dtype=np.float32)\n', (13875, 13920), True, 'import numpy as np\n'), ((14448, 14475), 'numpy.prod', 'np.prod', (['small_single_shape'], {}), '(small_single_shape)\n', (14455, 14475), True, 'import numpy as np\n'), ((14589, 14625), 'numpy.zeros', 'np.zeros', (['var_size'], {'dtype': 'np.float32'}), '(var_size, dtype=np.float32)\n', (14597, 14625), True, 'import numpy as np\n'), ((14648, 14684), 'numpy.zeros', 'np.zeros', (['var_size'], {'dtype': 'np.float32'}), '(var_size, dtype=np.float32)\n', (14656, 14684), True, 'import numpy as np\n'), ((14712, 14745), 'numpy.ones', 'np.ones', (['var_size'], {'dtype': 'np.int32'}), '(var_size, dtype=np.int32)\n', (14719, 14745), True, 'import numpy as np\n'), ((16255, 16317), 'numpy.repeat', 'np.repeat', (['modifier', "(self.config['batch_size'] * 2 + 1)"], {'axis': '(0)'}), "(modifier, self.config['batch_size'] * 2 + 1, axis=0)\n", (16264, 16317), True, 'import numpy as np\n'), ((19860, 19883), 'numpy.prod', 'np.prod', (['orig_img.shape'], {}), '(orig_img.shape)\n', (19867, 19883), True, 'import numpy as np\n'), ((20052, 20088), 'numpy.zeros', 'np.zeros', (['var_size'], {'dtype': 'np.float32'}), '(var_size, dtype=np.float32)\n', (20060, 20088), True, 'import numpy as np\n'), ((20111, 20147), 'numpy.zeros', 'np.zeros', (['var_size'], {'dtype': 'np.float32'}), '(var_size, dtype=np.float32)\n', (20119, 20147), True, 'import numpy as np\n'), ((20175, 20208), 'numpy.ones', 'np.ones', (['var_size'], {'dtype': 'np.int64'}), '(var_size, dtype=np.int64)\n', (20182, 20208), True, 'import numpy as np\n'), ((20227, 20263), 'numpy.zeros', 'np.zeros', (['var_size'], {'dtype': 'np.float32'}), '(var_size, dtype=np.float32)\n', (20235, 20263), True, 'import numpy as np\n'), ((20284, 20320), 'numpy.zeros', 'np.zeros', (['var_size'], {'dtype': 'np.float32'}), '(var_size, dtype=np.float32)\n', (20292, 20320), True, 'import numpy as np\n'), ((2716, 2751), 'numpy.ones', 'np.ones', (['var_size'], {'dtype': 'np.float32'}), '(var_size, dtype=np.float32)\n', (2723, 2751), True, 'import numpy as np\n'), ((6036, 6066), 'torch.nn.functional.softmax', 'F.softmax', (['model_output'], {'dim': '(1)'}), '(model_output, dim=1)\n', (6045, 6066), True, 'import torch.nn.functional as F\n'), ((6139, 6201), 'torch.max', 'torch.max', (['((1 - target) * model_output - target * 10000)'], {'dim': '(1)'}), '((1 - target) * model_output - target * 10000, dim=1)\n', (6148, 6201), False, 'import torch\n'), ((6262, 6285), 'torch.log', 'torch.log', (['(real + 1e-30)'], {}), '(real + 1e-30)\n', (6271, 6285), False, 'import torch\n'), ((6306, 6330), 'torch.log', 'torch.log', (['(other + 1e-30)'], {}), '(other + 1e-30)\n', (6315, 6330), False, 'import torch\n'), ((12328, 12353), 'numpy.abs', 'np.abs', (['modifier[:, :, i]'], {}), '(modifier[:, :, i])\n', (12334, 12353), True, 'import numpy as np\n'), ((12799, 12811), 'numpy.sum', 'np.sum', (['prob'], {}), '(prob)\n', (12805, 12811), True, 'import numpy as np\n'), ((12838, 12850), 'numpy.sum', 'np.sum', (['prob'], {}), '(prob)\n', (12844, 12850), True, 'import numpy as np\n'), ((12904, 12946), 'numpy.ones', 'np.ones', ([], {'shape': 'new_shape', 'dtype': 'np.float32'}), '(shape=new_shape, dtype=np.float32)\n', (12911, 12946), True, 'import numpy as np\n'), ((12967, 12979), 'numpy.sum', 'np.sum', (['prob'], {}), '(prob)\n', (12973, 12979), True, 'import numpy as np\n'), ((14108, 14125), 'numpy.copy', 'np.copy', (['modifier'], {}), '(modifier)\n', (14115, 14125), True, 'import numpy as np\n'), ((19808, 19839), 'numpy.arctanh', 'np.arctanh', (['(orig_img * 1.999999)'], {}), '(orig_img * 1.999999)\n', (19818, 19839), True, 'import numpy as np\n'), ((20382, 20417), 'numpy.ones', 'np.ones', (['var_size'], {'dtype': 'np.float32'}), '(var_size, dtype=np.float32)\n', (20389, 20417), True, 'import numpy as np\n'), ((3781, 3853), 'cv2.resize', 'cv2.resize', (['modifier[k, :, :, :]', '(x, y)'], {'interpolation': 'cv2.INTER_LINEAR'}), '(modifier[k, :, :, :], (x, y), interpolation=cv2.INTER_LINEAR)\n', (3791, 3853), False, 'import cv2\n'), ((4039, 4074), 'torch.tanh', 'torch.tanh', (['(orig_img + new_modifier)'], {}), '(orig_img + new_modifier)\n', (4049, 4074), False, 'import torch\n'), ((6353, 6412), 'torch.tensor', 'torch.tensor', (["self.config['confidence']"], {'device': 'self.device'}), "(self.config['confidence'], device=self.device)\n", (6365, 6412), False, 'import torch\n'), ((9023, 9075), 'numpy.max', 'np.max', (['modifier[i:i + patch_size, j:j + patch_size]'], {}), '(modifier[i:i + patch_size, j:j + patch_size])\n', (9029, 9075), True, 'import numpy as np\n'), ((10763, 10806), 'numpy.power', 'np.power', (["self.config['adam_beta1']", 'epochs'], {}), "(self.config['adam_beta1'], epochs)\n", (10771, 10806), True, 'import numpy as np\n'), ((10835, 10878), 'numpy.power', 'np.power', (["self.config['adam_beta2']", 'epochs'], {}), "(self.config['adam_beta2'], epochs)\n", (10843, 10878), True, 'import numpy as np\n'), ((11041, 11056), 'numpy.sqrt', 'np.sqrt', (['vt_hat'], {}), '(vt_hat)\n', (11048, 11056), True, 'import numpy as np\n'), ((11161, 11198), 'numpy.minimum', 'np.minimum', (['old_val', 'self.up[indices]'], {}), '(old_val, self.up[indices])\n', (11171, 11198), True, 'import numpy as np\n'), ((14214, 14303), 'cv2.resize', 'cv2.resize', (['modifier[k, :, :, :]', '(small_x, small_y)'], {'interpolation': 'cv2.INTER_LINEAR'}), '(modifier[k, :, :, :], (small_x, small_y), interpolation=cv2.\n INTER_LINEAR)\n', (14224, 14303), False, 'import cv2\n'), ((14836, 14871), 'numpy.ones', 'np.ones', (['var_size'], {'dtype': 'np.float32'}), '(var_size, dtype=np.float32)\n', (14843, 14871), True, 'import numpy as np\n'), ((16506, 16609), 'numpy.random.choice', 'np.random.choice', (['self.var_list.size', "self.config['batch_size']"], {'replace': '(False)', 'p': 'self.sample_prob'}), "(self.var_list.size, self.config['batch_size'], replace=\n False, p=self.sample_prob)\n", (16522, 16609), True, 'import numpy as np\n'), ((16751, 16829), 'numpy.random.choice', 'np.random.choice', (['self.var_list.size', "self.config['batch_size']"], {'replace': '(False)'}), "(self.var_list.size, self.config['batch_size'], replace=False)\n", (16767, 16829), True, 'import numpy as np\n'), ((18693, 18703), 'numpy.copy', 'np.copy', (['x'], {}), '(x)\n', (18700, 18703), True, 'import numpy as np\n'), ((18898, 18910), 'numpy.argmax', 'np.argmax', (['x'], {}), '(x)\n', (18907, 18910), True, 'import numpy as np\n'), ((19705, 19747), 'numpy.zeros', 'np.zeros', (['orig_img.shape'], {'dtype': 'np.float32'}), '(orig_img.shape, dtype=np.float32)\n', (19713, 19747), True, 'import numpy as np\n'), ((22028, 22070), 'numpy.zeros', 'np.zeros', (['orig_img.shape'], {'dtype': 'np.float32'}), '(orig_img.shape, dtype=np.float32)\n', (22036, 22070), True, 'import numpy as np\n'), ((25310, 25333), 'numpy.argmax', 'np.argmax', (['model_output'], {}), '(model_output)\n', (25319, 25333), True, 'import numpy as np\n'), ((25548, 25571), 'numpy.argmax', 'np.argmax', (['model_output'], {}), '(model_output)\n', (25557, 25571), True, 'import numpy as np\n'), ((25696, 25716), 'numpy.argmax', 'np.argmax', (['target[0]'], {}), '(target[0])\n', (25705, 25716), True, 'import numpy as np\n'), ((20841, 20867), 'torch.from_numpy', 'torch.from_numpy', (['orig_img'], {}), '(orig_img)\n', (20857, 20867), False, 'import torch\n'), ((20914, 20938), 'torch.from_numpy', 'torch.from_numpy', (['target'], {}), '(target)\n', (20930, 20938), False, 'import torch\n'), ((25216, 25236), 'numpy.argmax', 'np.argmax', (['target[0]'], {}), '(target[0])\n', (25225, 25236), True, 'import numpy as np\n'), ((25425, 25445), 'numpy.argmax', 'np.argmax', (['target[0]'], {}), '(target[0])\n', (25434, 25445), True, 'import numpy as np\n'), ((12527, 12554), 'PIL.Image.fromarray', 'Image.fromarray', (['image_pool'], {}), '(image_pool)\n', (12542, 12554), False, 'from PIL import Image\n'), ((5083, 5115), 'torch.square', 'torch.square', (['(new_img - orig_img)'], {}), '(new_img - orig_img)\n', (5095, 5115), False, 'import torch\n'), ((6617, 6639), 'torch.zeros_like', 'torch.zeros_like', (['real'], {}), '(real)\n', (6633, 6639), False, 'import torch\n'), ((6894, 6916), 'torch.zeros_like', 'torch.zeros_like', (['real'], {}), '(real)\n', (6910, 6916), False, 'import torch\n'), ((4898, 4918), 'torch.tanh', 'torch.tanh', (['orig_img'], {}), '(orig_img)\n', (4908, 4918), False, 'import torch\n')]
import numpy as np import pickle as pkl import scipy.sparse as sp no_of_graphs = int(input(" no. pf graphs ")) start = int(input(" starting point of graphs ")) #total_type_edges = int(input(" type of edges \n")) total_type_edges = 4 data_folder = "./data/custom/" for graph_num in range(start,no_of_graphs): print("--------------------------------------") num_nodes = int(input(" no. of nodes \n")) A = [np.zeros((num_nodes,num_nodes)) for _ in range(total_type_edges)] X = np.zeros(num_nodes) labels = np.zeros(num_nodes) num_of_edges = int(input(" no. of edges \n")) print(" enter the edges : 0 moving across , 1 moving ahead , 2 no movement , 3 diagonall") for edges in range(num_of_edges): print("Edge # {}of{}".format(edges,num_of_edges)) x = int(input("edge details : X : ")) y = int(input("edge details : Y : ")) e = int(input("edge details : E : ")) A[e][x,y] = 1 A[e][y,x] = 1 #node_type = int(input(" no. of edges \n")) print(" node type : 0 car,1 pole , 2 marker") print(" Labels : 0 moving , 1 static " ) for e in range(num_nodes): X[e] = int(input(" node {} type :".format(e))) labels[e] = int(input(" labels for node {} : ".format(e))) ## dump stuff here X = sp.csr_matrix(X) A = [ sp.csr_matrix(a) for a in A ] pkl.dump(labels,open(data_folder + "labels" + str(graph_num).zfill(4) + ".pkl","wb")) pkl.dump(A,open(data_folder + "A" + str(graph_num).zfill(4) + ".pkl","wb")) pkl.dump(X,open(data_folder + "X" + str(graph_num).zfill(4) + ".pkl","wb"))
[ "scipy.sparse.csr_matrix", "numpy.zeros" ]
[((498, 517), 'numpy.zeros', 'np.zeros', (['num_nodes'], {}), '(num_nodes)\n', (506, 517), True, 'import numpy as np\n'), ((531, 550), 'numpy.zeros', 'np.zeros', (['num_nodes'], {}), '(num_nodes)\n', (539, 550), True, 'import numpy as np\n'), ((1312, 1328), 'scipy.sparse.csr_matrix', 'sp.csr_matrix', (['X'], {}), '(X)\n', (1325, 1328), True, 'import scipy.sparse as sp\n'), ((424, 456), 'numpy.zeros', 'np.zeros', (['(num_nodes, num_nodes)'], {}), '((num_nodes, num_nodes))\n', (432, 456), True, 'import numpy as np\n'), ((1339, 1355), 'scipy.sparse.csr_matrix', 'sp.csr_matrix', (['a'], {}), '(a)\n', (1352, 1355), True, 'import scipy.sparse as sp\n')]
import numpy as np # Variables controlling flow of the program mode_globals = 2 save_history_globals = True load_recording_globals = False # Variables used for physical simulation dt_main_simulation_globals = 0.020 speedup_globals = 1.0 # MPC dt_mpc_simulation_globals = 0.20 mpc_horizon_globals = 20 # Parameters of the CartPole m_globals = 2.0 # mass of pend, kg M_globals = 1.0 # mass of cart, kg L_globals = 1.0 # half length of pend, m u_max_globals = 200.0 # max cart force, N M_fric_globals = 0.0 # 1.0, # cart friction, N/m/s J_fric_globals = 0.0 # 10.0, # friction coefficient on angular velocity, Nm/rad/s v_max_globals = 10.0 # max DC motor speed, m/s, in absense of friction, used for motor back EMF model controlDisturbance_globals = 0.0 # 0.01, # disturbance, as factor of u_max sensorNoise_globals = 0.0 # 0.01, # noise, as factor of max values g_globals = 9.81 # gravity, m/s^2 k_globals = 4.0 / 3.0 # Dimensionless factor, for moment of inertia of the pend (with L being half if the length) # Variables for random trace generation N_globals = 10 # Complexity of the random trace, number of random points used for interpolation random_length_globals = 1e2 # Number of points in the random length trece # def cartpole_dyncamic(position,): def cartpole_integration(s, dt): position = s.position + s.positionD * dt positionD = s.positionD + s.positionDD * dt angle = s.angle + s.angleD * dt angleD = s.angleD + s.angleDD * dt return position, positionD, angle, angleD def cartpole_ode(p, s, u): ca = np.cos(s.angle) sa = np.sin(s.angle) A = (p.k + 1) * (p.M + p.m) - p.m * (ca ** 2) angleDD = (p.g * (p.m + p.M) * sa - ((p.J_fric * (p.m + p.M) * s.angleD) / (p.L * p.m)) - ca * (p.m * p.L * (s.angleD ** 2) * sa + p.M_fric * s.positionD) + ca * u) / (A * p.L) positionDD = ( p.m * p.g * sa * ca - ((p.J_fric * s.angleD * ca) / (p.L)) - (p.k + 1) * (p.m * p.L * (s.angleD ** 2) * sa + p.M_fric * s.positionD) + (p.k + 1) * u ) / A return angleDD, positionDD def Q2u(Q, p): u = p.u_max * Q + p.controlDisturbance * np.random.normal() * p.u_max # Q is drive -1:1 range, add noise on control return u
[ "numpy.sin", "numpy.random.normal", "numpy.cos" ]
[((1563, 1578), 'numpy.cos', 'np.cos', (['s.angle'], {}), '(s.angle)\n', (1569, 1578), True, 'import numpy as np\n'), ((1588, 1603), 'numpy.sin', 'np.sin', (['s.angle'], {}), '(s.angle)\n', (1594, 1603), True, 'import numpy as np\n'), ((2289, 2307), 'numpy.random.normal', 'np.random.normal', ([], {}), '()\n', (2305, 2307), True, 'import numpy as np\n')]
import torch import random import numpy as np from pathlib import Path from typing import Any, List, Tuple, Dict, Optional, Callable from torch.utils.data import DataLoader from torch.utils.data.sampler import SubsetRandomSampler from image_classification.utils import import_class, import_object import wandb import logging log = logging.getLogger(__name__) class Trainer: def __init__(self, config: dict): self.config = config self.set_seed(config.seed) self.data_dir = Path(config.data_dir)/config.dataset.class_name self.data_dir.mkdir(parents=True, exist_ok=True) self.output_dir = Path(config.output_dir)/wandb.run.id self.output_dir.mkdir(parents=True, exist_ok=True) self.ckpt_dir = Path(self.config.checkpoint_dir) self.ckpt_dir.mkdir(parents=True, exist_ok=True) self.load_data() self.load_model() def set_seed(self, seed: int): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False log.info(f"Setting seed: {seed}") def load_data(self): config = self.config.dataset train_preprocessor = import_object(config.train_preprocessor, "preprocessor") test_preprocessor = import_object(config.test_preprocessor, "preprocessor") dataset_class = import_class(config.module, config.class_name) train_dataset = dataset_class( is_train=True, transform=train_preprocessor, data_dir=self.data_dir, download_data=config.download ) eval_dataset = dataset_class( is_train=True, transform=test_preprocessor, data_dir=self.data_dir, download_data=config.download ) test_dataset = dataset_class( is_train=False, transform=test_preprocessor, data_dir=self.data_dir, download_data=config.download ) indices = range(len(train_dataset)) train_indices = indices[:config.train_eval_split] eval_indices = indices[config.train_eval_split:] train_sampler = SubsetRandomSampler(train_indices) eval_sampler = SubsetRandomSampler(eval_indices) self.train_dl = DataLoader(train_dataset, config.batch_size, sampler=train_sampler) self.eval_dl = DataLoader(eval_dataset, config.batch_size*2, sampler=eval_sampler) self.test_dl = DataLoader(test_dataset, config.batch_size*2, shuffle=False) log.info( f"Loaded datasets: " f"train[{len(train_dataset)}] " f"eval[{len(eval_dataset)}] " f"test[{len(test_dataset)}] " ) def load_model(self): config = self.config.model device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model_class = import_class(config.module, config.class_name) self.model = model_class(**config, device=device) log.info(f"Loaded {config.class_name} on {device}")
[ "torch.utils.data.sampler.SubsetRandomSampler", "numpy.random.seed", "torch.utils.data.DataLoader", "torch.manual_seed", "pathlib.Path", "random.seed", "torch.cuda.is_available", "image_classification.utils.import_class", "image_classification.utils.import_object", "logging.getLogger" ]
[((333, 360), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (350, 360), False, 'import logging\n'), ((756, 788), 'pathlib.Path', 'Path', (['self.config.checkpoint_dir'], {}), '(self.config.checkpoint_dir)\n', (760, 788), False, 'from pathlib import Path\n'), ((945, 962), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (956, 962), False, 'import random\n'), ((971, 991), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (985, 991), True, 'import numpy as np\n'), ((1000, 1023), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (1017, 1023), False, 'import torch\n'), ((1255, 1311), 'image_classification.utils.import_object', 'import_object', (['config.train_preprocessor', '"""preprocessor"""'], {}), "(config.train_preprocessor, 'preprocessor')\n", (1268, 1311), False, 'from image_classification.utils import import_class, import_object\n'), ((1340, 1395), 'image_classification.utils.import_object', 'import_object', (['config.test_preprocessor', '"""preprocessor"""'], {}), "(config.test_preprocessor, 'preprocessor')\n", (1353, 1395), False, 'from image_classification.utils import import_class, import_object\n'), ((1420, 1466), 'image_classification.utils.import_class', 'import_class', (['config.module', 'config.class_name'], {}), '(config.module, config.class_name)\n', (1432, 1466), False, 'from image_classification.utils import import_class, import_object\n'), ((2164, 2198), 'torch.utils.data.sampler.SubsetRandomSampler', 'SubsetRandomSampler', (['train_indices'], {}), '(train_indices)\n', (2183, 2198), False, 'from torch.utils.data.sampler import SubsetRandomSampler\n'), ((2222, 2255), 'torch.utils.data.sampler.SubsetRandomSampler', 'SubsetRandomSampler', (['eval_indices'], {}), '(eval_indices)\n', (2241, 2255), False, 'from torch.utils.data.sampler import SubsetRandomSampler\n'), ((2280, 2347), 'torch.utils.data.DataLoader', 'DataLoader', (['train_dataset', 'config.batch_size'], {'sampler': 'train_sampler'}), '(train_dataset, config.batch_size, sampler=train_sampler)\n', (2290, 2347), False, 'from torch.utils.data import DataLoader\n'), ((2371, 2440), 'torch.utils.data.DataLoader', 'DataLoader', (['eval_dataset', '(config.batch_size * 2)'], {'sampler': 'eval_sampler'}), '(eval_dataset, config.batch_size * 2, sampler=eval_sampler)\n', (2381, 2440), False, 'from torch.utils.data import DataLoader\n'), ((2462, 2524), 'torch.utils.data.DataLoader', 'DataLoader', (['test_dataset', '(config.batch_size * 2)'], {'shuffle': '(False)'}), '(test_dataset, config.batch_size * 2, shuffle=False)\n', (2472, 2524), False, 'from torch.utils.data import DataLoader\n'), ((2878, 2924), 'image_classification.utils.import_class', 'import_class', (['config.module', 'config.class_name'], {}), '(config.module, config.class_name)\n', (2890, 2924), False, 'from image_classification.utils import import_class, import_object\n'), ((505, 526), 'pathlib.Path', 'Path', (['config.data_dir'], {}), '(config.data_dir)\n', (509, 526), False, 'from pathlib import Path\n'), ((636, 659), 'pathlib.Path', 'Path', (['config.output_dir'], {}), '(config.output_dir)\n', (640, 659), False, 'from pathlib import Path\n'), ((2818, 2843), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2841, 2843), False, 'import torch\n')]
from pandas import DataFrame, read_hdf import numpy as np import os import matplotlib.pyplot as plt # parameters directories = ["/data/u_rgast_software/PycharmProjects/BrainNetworks/BasalGanglia/stn_gpe_healthy_opt2/PopulationDrops"] fid = "PopulationDrop" params = ['eta_e', 'eta_p', 'eta_a', 'delta_e', 'delta_p', 'delta_a', 'tau_e', 'tau_p', 'tau_a', 'k_ee', 'k_pe', 'k_ae', 'k_ep', 'k_pp', 'k_ap', 'k_pa', 'k_aa', 'k_ps', 'k_as'] result_vars = ['results', 'fitness', 'sigma'] # load data into frame df = DataFrame(data=np.zeros((1, len(params) + len(result_vars))), columns=result_vars + params) for d in directories: for fn in os.listdir(d): if fn.startswith(fid) and fn.endswith(".h5"): df = df.append(read_hdf(f"{d}/{fn}")) df = df.iloc[1:, :] # plot histograms of conditions winner = df.nlargest(n=1, columns='fitness') fig, ax = plt.subplots() labels = ['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7'] model_rates = np.round(winner['results'].iloc[0][1], decimals=1) target_rates = [60.0, 40.0, 70.0, 100.0, 30.0, 60.0, 100.0] x = np.arange(len(labels)) # the label locations width = 0.35 # the width of the bars rects1 = ax.bar(x - width / 2, model_rates, width, label='model') rects2 = ax.bar(x + width / 2, target_rates, width, label='target') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('GPe firing rate') ax.set_title('Comparison between model fit and target firing rates') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() def autolabel(rects): """Attach a text label above each bar in *rects*, displaying its height.""" for rect in rects: height = rect.get_height() ax.annotate('{}'.format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3), # 3 points vertical offset textcoords="offset points", ha='center', va='bottom') autolabel(rects1) autolabel(rects2) fig.tight_layout() plt.show()
[ "matplotlib.pyplot.show", "pandas.read_hdf", "matplotlib.pyplot.subplots", "numpy.round", "os.listdir" ]
[((875, 889), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (887, 889), True, 'import matplotlib.pyplot as plt\n'), ((957, 1007), 'numpy.round', 'np.round', (["winner['results'].iloc[0][1]"], {'decimals': '(1)'}), "(winner['results'].iloc[0][1], decimals=1)\n", (965, 1007), True, 'import numpy as np\n'), ((2010, 2020), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2018, 2020), True, 'import matplotlib.pyplot as plt\n'), ((648, 661), 'os.listdir', 'os.listdir', (['d'], {}), '(d)\n', (658, 661), False, 'import os\n'), ((744, 765), 'pandas.read_hdf', 'read_hdf', (['f"""{d}/{fn}"""'], {}), "(f'{d}/{fn}')\n", (752, 765), False, 'from pandas import DataFrame, read_hdf\n')]
import random import numpy as np import pytest from pandas import DataFrame from tests.utils import assert_dataframes_equals from weaverbird.backends.pandas_executor.steps.rank import execute_rank from weaverbird.pipeline.steps import RankStep @pytest.fixture def sample_df(): return DataFrame( {'COUNTRY': ['France'] * 3 + ['USA'] * 4, 'VALUE': [10, 20, 30, 10, 40, 30, 50]} ) def test_rank(sample_df: DataFrame): step = RankStep( name='rank', valueCol='VALUE', order='asc', method='standard', ) df_result = execute_rank(step, sample_df) expected_result = DataFrame( { 'COUNTRY': ['France', 'USA', 'France', 'France', 'USA', 'USA', 'USA'], 'VALUE': [10, 10, 20, 30, 30, 40, 50], 'VALUE_RANK': [1, 1, 3, 4, 4, 6, 7], } ) assert_dataframes_equals(df_result, expected_result) def test_rank_with_groups(sample_df: DataFrame): step = RankStep( name='rank', valueCol='VALUE', groupby=['COUNTRY'], order='desc', method='dense', newColumnName='rank', ) df_result = execute_rank(step, sample_df) expected_result = DataFrame( { 'COUNTRY': ['France', 'USA', 'France', 'USA', 'France', 'USA', 'USA'], 'VALUE': [30, 50, 20, 40, 10, 30, 10], 'rank': [1, 1, 2, 2, 3, 3, 4], } ) assert_dataframes_equals(df_result, expected_result) def test_benchmark_rank(benchmark): groups = ['group_1', 'group_2'] df = DataFrame( { 'value': np.random.random(1000), 'id': list(range(1000)), 'group': [random.choice(groups) for _ in range(1000)], } ) step = RankStep( name='rank', valueCol='value', groupby=['group'], order='desc', method='dense', newColumnName='rank', ) benchmark(execute_rank, step, df)
[ "pandas.DataFrame", "weaverbird.backends.pandas_executor.steps.rank.execute_rank", "random.choice", "tests.utils.assert_dataframes_equals", "numpy.random.random", "weaverbird.pipeline.steps.RankStep" ]
[((292, 388), 'pandas.DataFrame', 'DataFrame', (["{'COUNTRY': ['France'] * 3 + ['USA'] * 4, 'VALUE': [10, 20, 30, 10, 40, 30, 50]\n }"], {}), "({'COUNTRY': ['France'] * 3 + ['USA'] * 4, 'VALUE': [10, 20, 30, \n 10, 40, 30, 50]})\n", (301, 388), False, 'from pandas import DataFrame\n'), ((448, 519), 'weaverbird.pipeline.steps.RankStep', 'RankStep', ([], {'name': '"""rank"""', 'valueCol': '"""VALUE"""', 'order': '"""asc"""', 'method': '"""standard"""'}), "(name='rank', valueCol='VALUE', order='asc', method='standard')\n", (456, 519), False, 'from weaverbird.pipeline.steps import RankStep\n'), ((575, 604), 'weaverbird.backends.pandas_executor.steps.rank.execute_rank', 'execute_rank', (['step', 'sample_df'], {}), '(step, sample_df)\n', (587, 604), False, 'from weaverbird.backends.pandas_executor.steps.rank import execute_rank\n'), ((628, 795), 'pandas.DataFrame', 'DataFrame', (["{'COUNTRY': ['France', 'USA', 'France', 'France', 'USA', 'USA', 'USA'],\n 'VALUE': [10, 10, 20, 30, 30, 40, 50], 'VALUE_RANK': [1, 1, 3, 4, 4, 6, 7]}"], {}), "({'COUNTRY': ['France', 'USA', 'France', 'France', 'USA', 'USA',\n 'USA'], 'VALUE': [10, 10, 20, 30, 30, 40, 50], 'VALUE_RANK': [1, 1, 3, \n 4, 4, 6, 7]})\n", (637, 795), False, 'from pandas import DataFrame\n'), ((852, 904), 'tests.utils.assert_dataframes_equals', 'assert_dataframes_equals', (['df_result', 'expected_result'], {}), '(df_result, expected_result)\n', (876, 904), False, 'from tests.utils import assert_dataframes_equals\n'), ((967, 1083), 'weaverbird.pipeline.steps.RankStep', 'RankStep', ([], {'name': '"""rank"""', 'valueCol': '"""VALUE"""', 'groupby': "['COUNTRY']", 'order': '"""desc"""', 'method': '"""dense"""', 'newColumnName': '"""rank"""'}), "(name='rank', valueCol='VALUE', groupby=['COUNTRY'], order='desc',\n method='dense', newColumnName='rank')\n", (975, 1083), False, 'from weaverbird.pipeline.steps import RankStep\n'), ((1151, 1180), 'weaverbird.backends.pandas_executor.steps.rank.execute_rank', 'execute_rank', (['step', 'sample_df'], {}), '(step, sample_df)\n', (1163, 1180), False, 'from weaverbird.backends.pandas_executor.steps.rank import execute_rank\n'), ((1204, 1365), 'pandas.DataFrame', 'DataFrame', (["{'COUNTRY': ['France', 'USA', 'France', 'USA', 'France', 'USA', 'USA'],\n 'VALUE': [30, 50, 20, 40, 10, 30, 10], 'rank': [1, 1, 2, 2, 3, 3, 4]}"], {}), "({'COUNTRY': ['France', 'USA', 'France', 'USA', 'France', 'USA',\n 'USA'], 'VALUE': [30, 50, 20, 40, 10, 30, 10], 'rank': [1, 1, 2, 2, 3, \n 3, 4]})\n", (1213, 1365), False, 'from pandas import DataFrame\n'), ((1422, 1474), 'tests.utils.assert_dataframes_equals', 'assert_dataframes_equals', (['df_result', 'expected_result'], {}), '(df_result, expected_result)\n', (1446, 1474), False, 'from tests.utils import assert_dataframes_equals\n'), ((1756, 1870), 'weaverbird.pipeline.steps.RankStep', 'RankStep', ([], {'name': '"""rank"""', 'valueCol': '"""value"""', 'groupby': "['group']", 'order': '"""desc"""', 'method': '"""dense"""', 'newColumnName': '"""rank"""'}), "(name='rank', valueCol='value', groupby=['group'], order='desc',\n method='dense', newColumnName='rank')\n", (1764, 1870), False, 'from weaverbird.pipeline.steps import RankStep\n'), ((1600, 1622), 'numpy.random.random', 'np.random.random', (['(1000)'], {}), '(1000)\n', (1616, 1622), True, 'import numpy as np\n'), ((1683, 1704), 'random.choice', 'random.choice', (['groups'], {}), '(groups)\n', (1696, 1704), False, 'import random\n')]
import numpy as np import matplotlib.pyplot as plt from sklearn import decomposition from matplotlib import pylab from matplotlib.patches import Rectangle from pylab import cm from prettytable import PrettyTable class DataPlotting: # singleton instance = None def __init__(self, calibration_data): self.pca = None # compute dimension reduction if needed if calibration_data.shape[1] > 2: self.pca = decomposition.PCA(n_components=2) self.pca.fit(calibration_data) # add singleton reference DataPlotting.instance = self def dim_reduction(self, input_data): if self.pca is not None: input_data = self.pca.transform(input_data) return input_data # apply dimension reduction if needed if input_data.shape[1] > 2: self.pca = decomposition.PCA(n_components=2) self.pca.fit(input_data) return input_data def plot_text(self, info): # get reference to current plot and hide axis plot_ref = plt.gca() plot_ref.get_xaxis().set_visible(False) plot_ref.axes.get_yaxis().set_visible(False) plt.setp(plot_ref, frame_on=False) plt.axis([0, 1, 0, 1]) plt.text(0, 1, info, horizontalalignment='left', verticalalignment='top', transform=plot_ref.axes.transAxes) def plot_clusters(self, input_data, labels, show_axes, title, sub_title, fixed_coord=None, show_legend=False): # generate colors for labels cluster_no = len(set(labels)) color_map = cm.get_cmap("rainbow", cluster_no) #rainbow, jet colors = np.array([color_map(int(x)) for x in labels]) # apply dimension reduction if needed input_data = self.dim_reduction(input_data) # resolve axis if fixed_coord is not None: min_x = fixed_coord[0] max_x = fixed_coord[1] min_y = fixed_coord[2] max_y = fixed_coord[3] plt.axis([min_x, max_x, min_y, max_y]) else: min_x = input_data[:, 0].min() max_x = input_data[:, 0].max() min_y = input_data[:, 1].min() max_y = input_data[:, 1].max() plt.axis([min_x - max_x/5, max_x + max_x/5, min_y - max_y/5, max_y + max_y/5]) # get reference to current plot and hide axis plot_ref = plt.gca() if not show_axes: plot_ref.get_xaxis().set_visible(False) plot_ref.axes.get_yaxis().set_visible(False) # plot text, top and bottom plt.text(0, 1, title, horizontalalignment='left', verticalalignment='bottom', transform=plot_ref.axes.transAxes) plt.text(0, 0, '\n' + sub_title, horizontalalignment='left', verticalalignment='top', transform=plot_ref.axes.transAxes) else: # plot text, top and bottom plt.text(0, 1, title, horizontalalignment='left', verticalalignment='bottom', transform=plot_ref.axes.transAxes) plt.text(0, 0, '\n\n' + sub_title, horizontalalignment='left', verticalalignment='top', transform=plot_ref.axes.transAxes) new_lines = sub_title.count("\n") + 1 plt.gcf().subplots_adjust(bottom=new_lines * 0.06) # plot data, one scatter cmd for each cluster designating also the label labels = np.array(labels) for label_no in range(cluster_no): idxs = np.where(labels == label_no) plt.scatter(input_data[idxs][:, 0], input_data[idxs][:, 1], c=colors[idxs], s=50, label="C" + str(label_no)) if show_legend is True: plt.legend(loc='lower left', bbox_to_anchor=(1.1, 0), ncol=5) def plot_self_cells(self, points): self.plot_points(points, 'x', 'red') def plot_ab_boxes(self, box_list): # get reference to current plot plot_ref = plt.gca() for box in box_list: x = box[0][0] y = box[0][1] w = box[1][0] - x h = box[1][1] - y plot_ref.add_patch(Rectangle((x,y), w, h, color='blue', alpha=0.2)) def plot_points(self, points, marker, color): if len(points) == 0: return # apply dimension reduction if needed points = self.dim_reduction(points) # http://matplotlib.org/api/artist_api.html#matplotlib.lines.Line2D.set_marker if points.shape[0] > 0: plt.scatter(points[:, 0], points[:, 1], marker=marker, c=color) @staticmethod def plot_snapshot(temp_data, temp_labels, temp_bounding_boxes, temp_self_points, snapshot_info, fixed_coord=None, plt_idx=1): # start new figure plt.figure(num=None, figsize=(14, 6), dpi=80, facecolor='w', edgecolor='k') # plot points pylab.subplot(1, 2, 1) plt_idx += 1 DataPlotting.instance.plot_clusters(temp_data, temp_labels, title="", sub_title="", show_axes=True, fixed_coord=fixed_coord, show_legend=True) DataPlotting.instance.plot_self_cells(temp_self_points) # plot Ab boundingBox DataPlotting.instance.plot_ab_boxes(temp_bounding_boxes) # plot text pylab.subplot(1, 2, 2) plt_idx += 1 DataPlotting.instance.plot_text(snapshot_info) pylab.show() class DataPrinter: def tabular(self, dct): # construct table data table_data = [] alg_list = set() for input_data in dct: row_data = [] row_data.append(input_data) for alg in dct[input_data]: row_data.append(dct[input_data][alg]) alg_list.add(alg) table_data.append(row_data) table_data = np.array(table_data).ravel() col_no = len(alg_list) + 1 table_data.shape = (len(table_data)/col_no, col_no) # construct table table = PrettyTable() table.add_column("Input Data", table_data[:, 0]) table.align["Input Data"] = "l" col_idx = 1 for alg in alg_list: table.add_column(alg, table_data[:, col_idx]) col_idx += 1 # print the ascii table print(table)
[ "matplotlib.pylab.subplot", "matplotlib.patches.Rectangle", "matplotlib.pyplot.gca", "matplotlib.pyplot.scatter", "matplotlib.pyplot.legend", "matplotlib.pyplot.setp", "matplotlib.pyplot.axis", "matplotlib.pyplot.text", "matplotlib.pyplot.figure", "numpy.where", "numpy.array", "prettytable.PrettyTable", "sklearn.decomposition.PCA", "pylab.cm.get_cmap", "matplotlib.pyplot.gcf", "matplotlib.pylab.show" ]
[((1104, 1113), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (1111, 1113), True, 'import matplotlib.pyplot as plt\n'), ((1226, 1260), 'matplotlib.pyplot.setp', 'plt.setp', (['plot_ref'], {'frame_on': '(False)'}), '(plot_ref, frame_on=False)\n', (1234, 1260), True, 'import matplotlib.pyplot as plt\n'), ((1272, 1294), 'matplotlib.pyplot.axis', 'plt.axis', (['[0, 1, 0, 1]'], {}), '([0, 1, 0, 1])\n', (1280, 1294), True, 'import matplotlib.pyplot as plt\n'), ((1304, 1416), 'matplotlib.pyplot.text', 'plt.text', (['(0)', '(1)', 'info'], {'horizontalalignment': '"""left"""', 'verticalalignment': '"""top"""', 'transform': 'plot_ref.axes.transAxes'}), "(0, 1, info, horizontalalignment='left', verticalalignment='top',\n transform=plot_ref.axes.transAxes)\n", (1312, 1416), True, 'import matplotlib.pyplot as plt\n'), ((1629, 1663), 'pylab.cm.get_cmap', 'cm.get_cmap', (['"""rainbow"""', 'cluster_no'], {}), "('rainbow', cluster_no)\n", (1640, 1663), False, 'from pylab import cm\n'), ((2463, 2472), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (2470, 2472), True, 'import matplotlib.pyplot as plt\n'), ((3449, 3465), 'numpy.array', 'np.array', (['labels'], {}), '(labels)\n', (3457, 3465), True, 'import numpy as np\n'), ((3982, 3991), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (3989, 3991), True, 'import matplotlib.pyplot as plt\n'), ((4803, 4878), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'num': 'None', 'figsize': '(14, 6)', 'dpi': '(80)', 'facecolor': '"""w"""', 'edgecolor': '"""k"""'}), "(num=None, figsize=(14, 6), dpi=80, facecolor='w', edgecolor='k')\n", (4813, 4878), True, 'import matplotlib.pyplot as plt\n'), ((4911, 4933), 'matplotlib.pylab.subplot', 'pylab.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (4924, 4933), False, 'from matplotlib import pylab\n'), ((5302, 5324), 'matplotlib.pylab.subplot', 'pylab.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (5315, 5324), False, 'from matplotlib import pylab\n'), ((5412, 5424), 'matplotlib.pylab.show', 'pylab.show', ([], {}), '()\n', (5422, 5424), False, 'from matplotlib import pylab\n'), ((6025, 6038), 'prettytable.PrettyTable', 'PrettyTable', ([], {}), '()\n', (6036, 6038), False, 'from prettytable import PrettyTable\n'), ((465, 498), 'sklearn.decomposition.PCA', 'decomposition.PCA', ([], {'n_components': '(2)'}), '(n_components=2)\n', (482, 498), False, 'from sklearn import decomposition\n'), ((894, 927), 'sklearn.decomposition.PCA', 'decomposition.PCA', ([], {'n_components': '(2)'}), '(n_components=2)\n', (911, 927), False, 'from sklearn import decomposition\n'), ((2064, 2102), 'matplotlib.pyplot.axis', 'plt.axis', (['[min_x, max_x, min_y, max_y]'], {}), '([min_x, max_x, min_y, max_y])\n', (2072, 2102), True, 'import matplotlib.pyplot as plt\n'), ((2307, 2398), 'matplotlib.pyplot.axis', 'plt.axis', (['[min_x - max_x / 5, max_x + max_x / 5, min_y - max_y / 5, max_y + max_y / 5]'], {}), '([min_x - max_x / 5, max_x + max_x / 5, min_y - max_y / 5, max_y + \n max_y / 5])\n', (2315, 2398), True, 'import matplotlib.pyplot as plt\n'), ((2667, 2784), 'matplotlib.pyplot.text', 'plt.text', (['(0)', '(1)', 'title'], {'horizontalalignment': '"""left"""', 'verticalalignment': '"""bottom"""', 'transform': 'plot_ref.axes.transAxes'}), "(0, 1, title, horizontalalignment='left', verticalalignment=\n 'bottom', transform=plot_ref.axes.transAxes)\n", (2675, 2784), True, 'import matplotlib.pyplot as plt\n'), ((2793, 2917), 'matplotlib.pyplot.text', 'plt.text', (['(0)', '(0)', "('\\n' + sub_title)"], {'horizontalalignment': '"""left"""', 'verticalalignment': '"""top"""', 'transform': 'plot_ref.axes.transAxes'}), "(0, 0, '\\n' + sub_title, horizontalalignment='left',\n verticalalignment='top', transform=plot_ref.axes.transAxes)\n", (2801, 2917), True, 'import matplotlib.pyplot as plt\n'), ((2983, 3100), 'matplotlib.pyplot.text', 'plt.text', (['(0)', '(1)', 'title'], {'horizontalalignment': '"""left"""', 'verticalalignment': '"""bottom"""', 'transform': 'plot_ref.axes.transAxes'}), "(0, 1, title, horizontalalignment='left', verticalalignment=\n 'bottom', transform=plot_ref.axes.transAxes)\n", (2991, 3100), True, 'import matplotlib.pyplot as plt\n'), ((3109, 3235), 'matplotlib.pyplot.text', 'plt.text', (['(0)', '(0)', "('\\n\\n' + sub_title)"], {'horizontalalignment': '"""left"""', 'verticalalignment': '"""top"""', 'transform': 'plot_ref.axes.transAxes'}), "(0, 0, '\\n\\n' + sub_title, horizontalalignment='left',\n verticalalignment='top', transform=plot_ref.axes.transAxes)\n", (3117, 3235), True, 'import matplotlib.pyplot as plt\n'), ((3530, 3558), 'numpy.where', 'np.where', (['(labels == label_no)'], {}), '(labels == label_no)\n', (3538, 3558), True, 'import numpy as np\n'), ((3729, 3790), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower left"""', 'bbox_to_anchor': '(1.1, 0)', 'ncol': '(5)'}), "(loc='lower left', bbox_to_anchor=(1.1, 0), ncol=5)\n", (3739, 3790), True, 'import matplotlib.pyplot as plt\n'), ((4550, 4613), 'matplotlib.pyplot.scatter', 'plt.scatter', (['points[:, 0]', 'points[:, 1]'], {'marker': 'marker', 'c': 'color'}), '(points[:, 0], points[:, 1], marker=marker, c=color)\n', (4561, 4613), True, 'import matplotlib.pyplot as plt\n'), ((4170, 4218), 'matplotlib.patches.Rectangle', 'Rectangle', (['(x, y)', 'w', 'h'], {'color': '"""blue"""', 'alpha': '(0.2)'}), "((x, y), w, h, color='blue', alpha=0.2)\n", (4179, 4218), False, 'from matplotlib.patches import Rectangle\n'), ((5853, 5873), 'numpy.array', 'np.array', (['table_data'], {}), '(table_data)\n', (5861, 5873), True, 'import numpy as np\n'), ((3296, 3305), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (3303, 3305), True, 'import matplotlib.pyplot as plt\n')]
#!/usr/bin/env python import numpy as np import cPickle as pk import tensorflow as tf from keras import backend as K from time import time from variables import DTYPE, EPSILON from utils import convert_type, discount, LinearVF, gauss_log_prob, numel, dot_not_flat from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() DISTRIBUTED = size > 1 def dprint(*args, **kwargs): if DISTRIBUTED and not rank == 0: return else: print(args) def sync_list(arrays, avg=True): buffs = [np.copy(a) for a in arrays] for a, b in zip(arrays, buffs): comm.Allreduce(a, b, MPI.SUM) if avg: b /= float(size) return buffs class TRPO(object): """ TRPO Implementation Args: env: a Gym environment policy: a differentiable tf function optimizer: an optimizer delta: max KL penalty gamma: discounting factor """ def __init__(self, env, policy=None, optimizer=None, delta=0.01, gamma=0.99, update_freq=100, gae=True, gae_lam=0.97, cg_damping=0.1, momentum=0.0): self.env = env self.policy = policy self.optimizer = optimizer self.delta = delta self.gamma = gamma self.update_freq = update_freq self.step = 0 self.episodes = 0 self.vf = LinearVF() self.gae = gae self.gae_lam = gae_lam self.cg_damping = cg_damping self.momentum = momentum self._reset_iter() self.np_action_logstd_param = convert_type(0.01 * np.random.randn(1, policy.out_dim)) self.action_logstd_param = K.variable(self.np_action_logstd_param) self.previous = [0.0 for _ in self.params] self.stats = { 'avg_reward': [], 'total_steps': [], 'total_ep': [], 'total_time': [], 'kl_div': [], 'surr_loss': [], 'entropy': [], } self.build_computational_graphs() self.start_time = time() if DISTRIBUTED: params = K.batch_get_value(self.params) params = sync_list(params) self.set_params(params) @property def n_iterations(self): return self.step // self.update_freq @property def params(self): return [self.action_logstd_param, ] + self.policy.params def build_computational_graphs(self): # Build loss graphs a = K.placeholder(ndim=2, name='actions') s = K.placeholder(ndim=2, name='states') a_means = K.placeholder(ndim=2, name='action_means') a_logstds = K.placeholder(ndim=2, name='actions_logstds') advantages = K.placeholder(ndim=2, name='advantage_values') new_logstds_shape = K.placeholder(ndim=2, name='logstds_shape') # Just a 0-valued tensor of the right shape inputs = [a, s, a_means, a_logstds, advantages, new_logstds_shape] self.surrogate, self.surr_graph, self.grads_surr_graph = self.build_surrogate(inputs) self.entropy, self.ent_graph, self.grads_ent_graph = self.build_entropy(inputs) self.kl, self.kl_graph, self.grads_kl_graph = self.build_kl(inputs) self.losses = K.function(inputs, [self.surr_graph, self.ent_graph, self.kl_graph]) # TODO: Clean the following scrap tangents = [K.placeholder(shape=K.get_value(p).shape) for p in self.params] new_a_means = self.policy.model(s) new_a_logstds = new_logstds_shape + self.action_logstd_param stop_means, stop_logstds = K.stop_gradient(new_a_means), K.stop_gradient(new_a_logstds) # NOTE: Following seems fishy. (cf: Sutskever's code, utils.py:gauss_selfKL_firstfixed()) stop_var = K.exp(2 * stop_logstds) var = K.exp(2 * new_a_logstds) temp = (stop_var + (stop_means - new_a_means)**2) / (2*var) kl_first_graph = K.mean(new_a_logstds - stop_logstds + temp - 0.5) grads_kl_first = K.gradients(kl_first_graph, self.params) gvp_graph = [K.sum(g * t) for g, t in zip(grads_kl_first, tangents)] grads_gvp_graph = K.gradients(gvp_graph, self.params) # self.grads_gvp = K.function(inputs + tangents + self.params, [kl_first_graph, ]) self.grads_gvp = K.function(inputs + tangents + self.params, grads_gvp_graph) def _reset_iter(self): self.iter_reward = 0 self.iter_n_ep = 0 self.iter_actions = [[], ] self.iter_states = [[], ] self.iter_rewards = [[], ] self.iter_action_mean = [[], ] self.iter_action_logstd = [[], ] self.iter_done = [] def _remove_episode(self, ep): """ ep: int or list of ints. Index of episodes to be remove from current iteration. """ self.iter_rewards = np.delete(self.iter_rewards, ep, 0) self.iter_actions = np.delete(self.iter_actions, ep, 0) self.iter_states = np.delete(self.iter_states, ep, 0) self.iter_action_mean = np.delete(self.iter_action_mean, ep, 0) self.iter_action_logstd = np.delete(self.iter_action_logstd, ep, 0) self.iter_done = np.delete(self.iter_done, ep, 0) if isinstance(ep, list): self.iter_n_ep -= len(ep) self.episodes -= len(ep) else: self.iter_n_ep -= 1 self.episodes -= 1 def act(self, s): """ Sample from the policy, where the outputs of the net are the mean and the param self.action_logstd_param gives you the logstd. """ s = convert_type(s) s = s.reshape((1, -1)) action_mean = convert_type(self.policy(s)) out = np.copy(action_mean) out += (np.exp(self.np_action_logstd_param) * np.random.randn(*self.np_action_logstd_param.shape)) return out[0], {'action_mean': action_mean, 'action_logstd': self.np_action_logstd_param} def new_episode(self, terminated=False): """ terminated: whether the episode was terminated by the env (True), or manually (False). """ self.iter_done.append(terminated) if not terminated or self.step % self.update_freq != 0: self.iter_n_ep += 1 self.episodes += 1 self.iter_actions.append([]) self.iter_states.append([]) self.iter_rewards.append([]) self.iter_action_mean.append([]) self.iter_action_logstd.append([]) def learn(self, s0, a, r, s1, end_ep, action_info=None): ep = self.iter_n_ep self.iter_actions[ep].append(a) self.iter_states[ep].append(s0) self.iter_rewards[ep].append(r) if action_info is not None: self.iter_action_mean[ep].append(action_info['action_mean']) self.iter_action_logstd[ep].append(action_info['action_logstd']) self.step += 1 self.iter_reward += r if self.step % self.update_freq == 0: self.update() def update(self): """ Performs the TRPO update of the parameters. """ returns = [] advantages = [] # Compute advantage for ep in xrange(self.iter_n_ep+1): r = discount(self.iter_rewards[ep], self.gamma) b = self.vf(self.iter_states[ep]) if self.gae and len(b) > 0: terminated = len(self.iter_done) != ep and self.iter_done[ep] b1 = np.append(b, 0 if terminated else b[-1]) deltas = self.iter_rewards[ep] + self.gamma*b1[1:] - b1[:-1] adv = discount(deltas, self.gamma * self.gae_lam) else: adv = r - b returns.append(r) advantages.append(adv) # Fit baseline for next iter self.vf.learn(self.iter_states, returns) states = np.concatenate(self.iter_states) actions = np.concatenate(self.iter_actions) actions = convert_type(actions) means = np.concatenate(self.iter_action_mean).reshape(states.shape[0], -1) logstds = np.concatenate(self.iter_action_logstd).reshape(states.shape[0], -1) # Standardize A() to have mean=0, std=1 advantage = np.concatenate(advantages).reshape(states.shape[0], -1) advantage -= advantage.mean() advantage /= (advantage.std() + EPSILON) advantage = convert_type(advantage) inputs = [actions, states, means, logstds, advantage] # TODO: The following is to be cleaned, most of it can be made into a graph #Begin of CG surr_loss, surr_gradients = self.surrogate(*inputs) def fisher_vec_prod(vectors): a_logstds = np.zeros(means.shape, dtype=DTYPE) + logstds new_logstds = np.zeros(means.shape, dtype=DTYPE) args = [actions, states, means, a_logstds, advantage, new_logstds] res = self.grads_gvp(args + vectors) # GRAPH: directly get grads_graph and extend it with the following return [r + (p * self.cg_damping) for r, p in zip(res, vectors)] def conjgrad(fvp, grads, cg_iters=10, residual_tol=1e-10): p = [np.copy(g) for g in grads] r = [np.copy(g) for g in grads] x = [np.zeros_like(g) for g in grads] # GRAPH: extend fvp, control with tf.cond, inputs are p, r, x rdotr = dot_not_flat(r, r) # rdotr = dot_not_flat(grads, grads) for i in xrange(cg_iters): z = fvp(p) pdotz = np.sum([np.sum(a*b) for a, b in zip(p, z)]) v = rdotr / pdotz x = [a + (v*b) for a, b in zip(x, p)] r = [a - (v*b) for a, b in zip(r, z)] newrdotr = np.sum([np.sum(g**2) for g in grads]) mu = newrdotr / rdotr p = [a + mu * b for a, b in zip(r, p)] rdotr = newrdotr if rdotr < residual_tol: break return x grads = [-g for g in surr_gradients] stepdir = conjgrad(fisher_vec_prod, grads) # GRAPH: stepdir is a graph, extend it to shs shs = 0.5 * dot_not_flat(stepdir, fisher_vec_prod(stepdir)) assert shs > 0 lm = np.sqrt(shs / self.delta) fullstep = [s / lm for s in stepdir] neggdotdir = dot_not_flat(grads, stepdir) # GRAPH: All 5 lines above can be converted to a graph # End of CG # Begin Linesearch def loss(params): self.set_params(params) return self.surrogate(*inputs)[0] def linesearch(loss, params, fullstep, exp_improve_rate): # GRAPH: graph the following with tf.cond accept_ratio = 0.1 max_backtracks = 10 loss_val = loss(params) for (i, stepfrac) in enumerate(0.5 ** np.arange(max_backtracks)): update = [(stepfrac * f) for f in fullstep] new_params = [p + u for p, u in zip(params, update)] # new_params = [a + (stepfrac * b) for a, b in zip(params, fullstep)] new_loss_val = loss(new_params) actual_improve = loss_val - new_loss_val exp_improve = stepfrac * exp_improve_rate ratio = actual_improve / exp_improve if ratio > accept_ratio and actual_improve > 0: return update # return new_params return [0 for f in fullstep] # return params params = K.batch_get_value(self.params) # Apply momentum pre-linesearch: # params = [p + self.momentum * prev # for p, prev in zip(params, self.previous)] update = linesearch(loss, params, fullstep, neggdotdir / lm) update = [u + f for f, u in zip(fullstep, update)] if DISTRIBUTED: update = sync_list(update, avg=True) # fullstep = sync_list(fullstep, avg=True) self.previous = [self.momentum * prev + u for prev, u in zip(self.previous, update)] # Apply momentum pre-linesearch: # new_params = [p + u for p, u in zip(params, update)] # Apply momentum post-linesearch: new_params = [p + u for p, u in zip(params, self.previous)] self.set_params(new_params) # End Linesearch a_logstds = np.zeros(means.shape, dtype=DTYPE) + logstds new_logstds = np.zeros(means.shape, dtype=DTYPE) args = [actions, states, means, a_logstds, advantage, new_logstds] surr, ent, kl = self.losses(args) stats = { 'avg_reward': self.iter_reward / float(max(self.iter_n_ep, 1)), 'total_steps': self.step, 'total_ep': int(self.episodes), 'total_time': time() - self.start_time, 'kl_div': float(kl), 'surr_loss': float(surr), 'entropy': float(ent), } dprint('*' * 20, 'Iteration ' + str(self.n_iterations), '*' * 20) dprint('Average Reward on Iteration:', stats['avg_reward']) dprint('Total Steps: ', self.step) dprint('Total Epsiodes: ', self.episodes) dprint('Time Elapsed: ', stats['total_time']) dprint('KL Divergence: ', kl) dprint('Surrogate Loss: ', surr) dprint('Entropy: ', ent) dprint('\n') self.stats['avg_reward'].append(stats['avg_reward']) self.stats['total_steps'].append(stats['total_steps']) self.stats['total_ep'].append(stats['total_ep']) self.stats['total_time'].append(stats['total_time']) self.stats['kl_div'].append(stats['kl_div']) self.stats['surr_loss'].append(stats['surr_loss']) self.stats['entropy'].append(stats['entropy']) self._reset_iter() def done(self): return False # return self.iter_reward >= self.env.solved_threshold * 1.1 def load(self, path): with open(path, 'wb') as f: params = pk.load(f) self.set_params(params) def save(self, path): params = K.batch_get_value(self.params) with open(path, 'wb') as f: pk.dump(params, f) def set_params(self, params): K.batch_set_value(zip(self.params, params)) self.np_action_logstd_param = K.get_value(self.action_logstd_param) def update_params(self, updates): for p, u in zip(self.params, updates): K.set_value(p, K.get_value(p) + u) self.np_action_logstd_param = K.get_value(self.action_logstd_param) def build_surrogate(self, variables): # Build graph of surrogate loss a, s, a_means, a_logstds, advantages, new_logstds_shape = variables # Computes the gauss_log_prob on sampled data. old_log_p_n = gauss_log_prob(a_means, a_logstds, a) # Here we compute the gauss_log_prob, but wrt current params new_a_means = self.policy.model(s) new_a_logstds = new_logstds_shape + self.action_logstd_param new_log_p_n = gauss_log_prob(new_a_means, new_a_logstds, a) # Compute the actual surrogate ratio = K.exp(new_log_p_n - old_log_p_n) advantages = K.reshape(advantages, (-1, )) surr_graph = -K.mean(ratio * advantages) grad_surr_graph = K.gradients(surr_graph, self.params) inputs = variables + self.params graph = K.function(inputs, [surr_graph, ] + grad_surr_graph) # graph = K.function(inputs, [surr_graph, ]) def surrogate(actions, states, action_means, action_logstds, advantages): # TODO: Allocating new np.arrays might be slow. logstds = np.zeros(action_means.shape, dtype=DTYPE) + action_logstds new_logstds = np.zeros(action_means.shape, dtype=DTYPE) args = [actions, states, action_means, logstds, advantages, new_logstds] res = graph(args) return res[0], res[1:] return surrogate, surr_graph, grad_surr_graph def build_kl(self, variables): a, s, a_means, a_logstds, advantages, new_logstds_shape = variables new_a_means = self.policy.model(s) new_a_logstds = new_logstds_shape + self.action_logstd_param # NOTE: Might be fishy. (cf: Sutskever's code, utils.py:gauss_KL()) old_var = K.exp(2 * a_logstds) new_var = K.exp(2 * new_a_logstds) temp = (old_var + (a_means - new_a_means)**2) / (2 * new_var) kl_graph = K.mean(new_a_logstds - a_logstds + temp - 0.5) grad_kl_graph = K.gradients(kl_graph, self.params) inputs = variables + self.params # graph = K.function(inputs, [kl_graph, ] + grad_kl_graph) graph = K.function(inputs, [kl_graph, ]) def kl(actions, states, action_means, action_logstds, advantages): logstds = np.zeros(action_means.shape, dtype=DTYPE) + action_logstds new_logstds = np.zeros(action_means.shape, dtype=DTYPE) args = [actions, states, action_means, logstds, advantages, new_logstds] res = graph(args) return res[0], res[1:] return kl, kl_graph, grad_kl_graph def build_entropy(self, variables): a, s, a_means, a_logstds, advantages, new_logstds_shape = variables new_a_logstds = new_logstds_shape + self.action_logstd_param ent_graph = K.mean(new_a_logstds + 0.5 * np.log(2*np.pi*np.e)) grad_ent_graph = K.gradients(ent_graph, self.params) inputs = variables + self.params # graph = K.function(inputs, [ent_graph, ] + grad_ent_graph) graph = K.function(inputs, [ent_graph, ]) def entropy(actions, states, action_means, action_logstds, advantages): logstds = np.zeros(action_means.shape, dtype=DTYPE) + action_logstds new_logstds = np.zeros(action_means.shape, dtype=DTYPE) args = [actions, states, action_means, logstds, advantages, new_logstds] res = graph(args) return res[0], res[1:] return entropy, ent_graph, grad_ent_graph
[ "numpy.sum", "cPickle.load", "numpy.arange", "keras.backend.stop_gradient", "numpy.exp", "keras.backend.placeholder", "numpy.zeros_like", "numpy.copy", "numpy.random.randn", "keras.backend.reshape", "numpy.append", "utils.discount", "keras.backend.gradients", "keras.backend.batch_get_value", "utils.gauss_log_prob", "keras.backend.exp", "utils.dot_not_flat", "keras.backend.function", "keras.backend.get_value", "utils.LinearVF", "numpy.delete", "numpy.concatenate", "numpy.log", "numpy.zeros", "keras.backend.sum", "time.time", "utils.convert_type", "cPickle.dump", "keras.backend.mean", "keras.backend.variable", "numpy.sqrt" ]
[((543, 553), 'numpy.copy', 'np.copy', (['a'], {}), '(a)\n', (550, 553), True, 'import numpy as np\n'), ((1383, 1393), 'utils.LinearVF', 'LinearVF', ([], {}), '()\n', (1391, 1393), False, 'from utils import convert_type, discount, LinearVF, gauss_log_prob, numel, dot_not_flat\n'), ((1674, 1713), 'keras.backend.variable', 'K.variable', (['self.np_action_logstd_param'], {}), '(self.np_action_logstd_param)\n', (1684, 1713), True, 'from keras import backend as K\n'), ((2069, 2075), 'time.time', 'time', ([], {}), '()\n', (2073, 2075), False, 'from time import time\n'), ((2501, 2538), 'keras.backend.placeholder', 'K.placeholder', ([], {'ndim': '(2)', 'name': '"""actions"""'}), "(ndim=2, name='actions')\n", (2514, 2538), True, 'from keras import backend as K\n'), ((2551, 2587), 'keras.backend.placeholder', 'K.placeholder', ([], {'ndim': '(2)', 'name': '"""states"""'}), "(ndim=2, name='states')\n", (2564, 2587), True, 'from keras import backend as K\n'), ((2606, 2648), 'keras.backend.placeholder', 'K.placeholder', ([], {'ndim': '(2)', 'name': '"""action_means"""'}), "(ndim=2, name='action_means')\n", (2619, 2648), True, 'from keras import backend as K\n'), ((2669, 2714), 'keras.backend.placeholder', 'K.placeholder', ([], {'ndim': '(2)', 'name': '"""actions_logstds"""'}), "(ndim=2, name='actions_logstds')\n", (2682, 2714), True, 'from keras import backend as K\n'), ((2736, 2782), 'keras.backend.placeholder', 'K.placeholder', ([], {'ndim': '(2)', 'name': '"""advantage_values"""'}), "(ndim=2, name='advantage_values')\n", (2749, 2782), True, 'from keras import backend as K\n'), ((2811, 2854), 'keras.backend.placeholder', 'K.placeholder', ([], {'ndim': '(2)', 'name': '"""logstds_shape"""'}), "(ndim=2, name='logstds_shape')\n", (2824, 2854), True, 'from keras import backend as K\n'), ((3255, 3323), 'keras.backend.function', 'K.function', (['inputs', '[self.surr_graph, self.ent_graph, self.kl_graph]'], {}), '(inputs, [self.surr_graph, self.ent_graph, self.kl_graph])\n', (3265, 3323), True, 'from keras import backend as K\n'), ((3777, 3800), 'keras.backend.exp', 'K.exp', (['(2 * stop_logstds)'], {}), '(2 * stop_logstds)\n', (3782, 3800), True, 'from keras import backend as K\n'), ((3815, 3839), 'keras.backend.exp', 'K.exp', (['(2 * new_a_logstds)'], {}), '(2 * new_a_logstds)\n', (3820, 3839), True, 'from keras import backend as K\n'), ((3933, 3982), 'keras.backend.mean', 'K.mean', (['(new_a_logstds - stop_logstds + temp - 0.5)'], {}), '(new_a_logstds - stop_logstds + temp - 0.5)\n', (3939, 3982), True, 'from keras import backend as K\n'), ((4008, 4048), 'keras.backend.gradients', 'K.gradients', (['kl_first_graph', 'self.params'], {}), '(kl_first_graph, self.params)\n', (4019, 4048), True, 'from keras import backend as K\n'), ((4153, 4188), 'keras.backend.gradients', 'K.gradients', (['gvp_graph', 'self.params'], {}), '(gvp_graph, self.params)\n', (4164, 4188), True, 'from keras import backend as K\n'), ((4305, 4365), 'keras.backend.function', 'K.function', (['(inputs + tangents + self.params)', 'grads_gvp_graph'], {}), '(inputs + tangents + self.params, grads_gvp_graph)\n', (4315, 4365), True, 'from keras import backend as K\n'), ((4848, 4883), 'numpy.delete', 'np.delete', (['self.iter_rewards', 'ep', '(0)'], {}), '(self.iter_rewards, ep, 0)\n', (4857, 4883), True, 'import numpy as np\n'), ((4912, 4947), 'numpy.delete', 'np.delete', (['self.iter_actions', 'ep', '(0)'], {}), '(self.iter_actions, ep, 0)\n', (4921, 4947), True, 'import numpy as np\n'), ((4975, 5009), 'numpy.delete', 'np.delete', (['self.iter_states', 'ep', '(0)'], {}), '(self.iter_states, ep, 0)\n', (4984, 5009), True, 'import numpy as np\n'), ((5042, 5081), 'numpy.delete', 'np.delete', (['self.iter_action_mean', 'ep', '(0)'], {}), '(self.iter_action_mean, ep, 0)\n', (5051, 5081), True, 'import numpy as np\n'), ((5116, 5157), 'numpy.delete', 'np.delete', (['self.iter_action_logstd', 'ep', '(0)'], {}), '(self.iter_action_logstd, ep, 0)\n', (5125, 5157), True, 'import numpy as np\n'), ((5183, 5215), 'numpy.delete', 'np.delete', (['self.iter_done', 'ep', '(0)'], {}), '(self.iter_done, ep, 0)\n', (5192, 5215), True, 'import numpy as np\n'), ((5604, 5619), 'utils.convert_type', 'convert_type', (['s'], {}), '(s)\n', (5616, 5619), False, 'from utils import convert_type, discount, LinearVF, gauss_log_prob, numel, dot_not_flat\n'), ((5716, 5736), 'numpy.copy', 'np.copy', (['action_mean'], {}), '(action_mean)\n', (5723, 5736), True, 'import numpy as np\n'), ((7926, 7958), 'numpy.concatenate', 'np.concatenate', (['self.iter_states'], {}), '(self.iter_states)\n', (7940, 7958), True, 'import numpy as np\n'), ((7977, 8010), 'numpy.concatenate', 'np.concatenate', (['self.iter_actions'], {}), '(self.iter_actions)\n', (7991, 8010), True, 'import numpy as np\n'), ((8029, 8050), 'utils.convert_type', 'convert_type', (['actions'], {}), '(actions)\n', (8041, 8050), False, 'from utils import convert_type, discount, LinearVF, gauss_log_prob, numel, dot_not_flat\n'), ((8453, 8476), 'utils.convert_type', 'convert_type', (['advantage'], {}), '(advantage)\n', (8465, 8476), False, 'from utils import convert_type, discount, LinearVF, gauss_log_prob, numel, dot_not_flat\n'), ((10339, 10364), 'numpy.sqrt', 'np.sqrt', (['(shs / self.delta)'], {}), '(shs / self.delta)\n', (10346, 10364), True, 'import numpy as np\n'), ((10431, 10459), 'utils.dot_not_flat', 'dot_not_flat', (['grads', 'stepdir'], {}), '(grads, stepdir)\n', (10443, 10459), False, 'from utils import convert_type, discount, LinearVF, gauss_log_prob, numel, dot_not_flat\n'), ((11633, 11663), 'keras.backend.batch_get_value', 'K.batch_get_value', (['self.params'], {}), '(self.params)\n', (11650, 11663), True, 'from keras import backend as K\n'), ((12551, 12585), 'numpy.zeros', 'np.zeros', (['means.shape'], {'dtype': 'DTYPE'}), '(means.shape, dtype=DTYPE)\n', (12559, 12585), True, 'import numpy as np\n'), ((14193, 14223), 'keras.backend.batch_get_value', 'K.batch_get_value', (['self.params'], {}), '(self.params)\n', (14210, 14223), True, 'from keras import backend as K\n'), ((14416, 14453), 'keras.backend.get_value', 'K.get_value', (['self.action_logstd_param'], {}), '(self.action_logstd_param)\n', (14427, 14453), True, 'from keras import backend as K\n'), ((14625, 14662), 'keras.backend.get_value', 'K.get_value', (['self.action_logstd_param'], {}), '(self.action_logstd_param)\n', (14636, 14662), True, 'from keras import backend as K\n'), ((14900, 14937), 'utils.gauss_log_prob', 'gauss_log_prob', (['a_means', 'a_logstds', 'a'], {}), '(a_means, a_logstds, a)\n', (14914, 14937), False, 'from utils import convert_type, discount, LinearVF, gauss_log_prob, numel, dot_not_flat\n'), ((15142, 15187), 'utils.gauss_log_prob', 'gauss_log_prob', (['new_a_means', 'new_a_logstds', 'a'], {}), '(new_a_means, new_a_logstds, a)\n', (15156, 15187), False, 'from utils import convert_type, discount, LinearVF, gauss_log_prob, numel, dot_not_flat\n'), ((15244, 15276), 'keras.backend.exp', 'K.exp', (['(new_log_p_n - old_log_p_n)'], {}), '(new_log_p_n - old_log_p_n)\n', (15249, 15276), True, 'from keras import backend as K\n'), ((15298, 15326), 'keras.backend.reshape', 'K.reshape', (['advantages', '(-1,)'], {}), '(advantages, (-1,))\n', (15307, 15326), True, 'from keras import backend as K\n'), ((15404, 15440), 'keras.backend.gradients', 'K.gradients', (['surr_graph', 'self.params'], {}), '(surr_graph, self.params)\n', (15415, 15440), True, 'from keras import backend as K\n'), ((15499, 15549), 'keras.backend.function', 'K.function', (['inputs', '([surr_graph] + grad_surr_graph)'], {}), '(inputs, [surr_graph] + grad_surr_graph)\n', (15509, 15549), True, 'from keras import backend as K\n'), ((16443, 16463), 'keras.backend.exp', 'K.exp', (['(2 * a_logstds)'], {}), '(2 * a_logstds)\n', (16448, 16463), True, 'from keras import backend as K\n'), ((16482, 16506), 'keras.backend.exp', 'K.exp', (['(2 * new_a_logstds)'], {}), '(2 * new_a_logstds)\n', (16487, 16506), True, 'from keras import backend as K\n'), ((16596, 16642), 'keras.backend.mean', 'K.mean', (['(new_a_logstds - a_logstds + temp - 0.5)'], {}), '(new_a_logstds - a_logstds + temp - 0.5)\n', (16602, 16642), True, 'from keras import backend as K\n'), ((16667, 16701), 'keras.backend.gradients', 'K.gradients', (['kl_graph', 'self.params'], {}), '(kl_graph, self.params)\n', (16678, 16701), True, 'from keras import backend as K\n'), ((16827, 16857), 'keras.backend.function', 'K.function', (['inputs', '[kl_graph]'], {}), '(inputs, [kl_graph])\n', (16837, 16857), True, 'from keras import backend as K\n'), ((17584, 17619), 'keras.backend.gradients', 'K.gradients', (['ent_graph', 'self.params'], {}), '(ent_graph, self.params)\n', (17595, 17619), True, 'from keras import backend as K\n'), ((17747, 17778), 'keras.backend.function', 'K.function', (['inputs', '[ent_graph]'], {}), '(inputs, [ent_graph])\n', (17757, 17778), True, 'from keras import backend as K\n'), ((2121, 2151), 'keras.backend.batch_get_value', 'K.batch_get_value', (['self.params'], {}), '(self.params)\n', (2138, 2151), True, 'from keras import backend as K\n'), ((3598, 3626), 'keras.backend.stop_gradient', 'K.stop_gradient', (['new_a_means'], {}), '(new_a_means)\n', (3613, 3626), True, 'from keras import backend as K\n'), ((3628, 3658), 'keras.backend.stop_gradient', 'K.stop_gradient', (['new_a_logstds'], {}), '(new_a_logstds)\n', (3643, 3658), True, 'from keras import backend as K\n'), ((4071, 4083), 'keras.backend.sum', 'K.sum', (['(g * t)'], {}), '(g * t)\n', (4076, 4083), True, 'from keras import backend as K\n'), ((5754, 5789), 'numpy.exp', 'np.exp', (['self.np_action_logstd_param'], {}), '(self.np_action_logstd_param)\n', (5760, 5789), True, 'import numpy as np\n'), ((5808, 5859), 'numpy.random.randn', 'np.random.randn', (['*self.np_action_logstd_param.shape'], {}), '(*self.np_action_logstd_param.shape)\n', (5823, 5859), True, 'import numpy as np\n'), ((7296, 7339), 'utils.discount', 'discount', (['self.iter_rewards[ep]', 'self.gamma'], {}), '(self.iter_rewards[ep], self.gamma)\n', (7304, 7339), False, 'from utils import convert_type, discount, LinearVF, gauss_log_prob, numel, dot_not_flat\n'), ((8840, 8874), 'numpy.zeros', 'np.zeros', (['means.shape'], {'dtype': 'DTYPE'}), '(means.shape, dtype=DTYPE)\n', (8848, 8874), True, 'import numpy as np\n'), ((9460, 9478), 'utils.dot_not_flat', 'dot_not_flat', (['r', 'r'], {}), '(r, r)\n', (9472, 9478), False, 'from utils import convert_type, discount, LinearVF, gauss_log_prob, numel, dot_not_flat\n'), ((12484, 12518), 'numpy.zeros', 'np.zeros', (['means.shape'], {'dtype': 'DTYPE'}), '(means.shape, dtype=DTYPE)\n', (12492, 12518), True, 'import numpy as np\n'), ((14102, 14112), 'cPickle.load', 'pk.load', (['f'], {}), '(f)\n', (14109, 14112), True, 'import cPickle as pk\n'), ((14272, 14290), 'cPickle.dump', 'pk.dump', (['params', 'f'], {}), '(params, f)\n', (14279, 14290), True, 'import cPickle as pk\n'), ((15351, 15377), 'keras.backend.mean', 'K.mean', (['(ratio * advantages)'], {}), '(ratio * advantages)\n', (15357, 15377), True, 'from keras import backend as K\n'), ((15856, 15897), 'numpy.zeros', 'np.zeros', (['action_means.shape'], {'dtype': 'DTYPE'}), '(action_means.shape, dtype=DTYPE)\n', (15864, 15897), True, 'import numpy as np\n'), ((17043, 17084), 'numpy.zeros', 'np.zeros', (['action_means.shape'], {'dtype': 'DTYPE'}), '(action_means.shape, dtype=DTYPE)\n', (17051, 17084), True, 'import numpy as np\n'), ((17969, 18010), 'numpy.zeros', 'np.zeros', (['action_means.shape'], {'dtype': 'DTYPE'}), '(action_means.shape, dtype=DTYPE)\n', (17977, 18010), True, 'import numpy as np\n'), ((1603, 1637), 'numpy.random.randn', 'np.random.randn', (['(1)', 'policy.out_dim'], {}), '(1, policy.out_dim)\n', (1618, 1637), True, 'import numpy as np\n'), ((7526, 7566), 'numpy.append', 'np.append', (['b', '(0 if terminated else b[-1])'], {}), '(b, 0 if terminated else b[-1])\n', (7535, 7566), True, 'import numpy as np\n'), ((7666, 7709), 'utils.discount', 'discount', (['deltas', '(self.gamma * self.gae_lam)'], {}), '(deltas, self.gamma * self.gae_lam)\n', (7674, 7709), False, 'from utils import convert_type, discount, LinearVF, gauss_log_prob, numel, dot_not_flat\n'), ((8067, 8104), 'numpy.concatenate', 'np.concatenate', (['self.iter_action_mean'], {}), '(self.iter_action_mean)\n', (8081, 8104), True, 'import numpy as np\n'), ((8152, 8191), 'numpy.concatenate', 'np.concatenate', (['self.iter_action_logstd'], {}), '(self.iter_action_logstd)\n', (8166, 8191), True, 'import numpy as np\n'), ((8290, 8316), 'numpy.concatenate', 'np.concatenate', (['advantages'], {}), '(advantages)\n', (8304, 8316), True, 'import numpy as np\n'), ((8769, 8803), 'numpy.zeros', 'np.zeros', (['means.shape'], {'dtype': 'DTYPE'}), '(means.shape, dtype=DTYPE)\n', (8777, 8803), True, 'import numpy as np\n'), ((9245, 9255), 'numpy.copy', 'np.copy', (['g'], {}), '(g)\n', (9252, 9255), True, 'import numpy as np\n'), ((9289, 9299), 'numpy.copy', 'np.copy', (['g'], {}), '(g)\n', (9296, 9299), True, 'import numpy as np\n'), ((9333, 9349), 'numpy.zeros_like', 'np.zeros_like', (['g'], {}), '(g)\n', (9346, 9349), True, 'import numpy as np\n'), ((12907, 12913), 'time.time', 'time', ([], {}), '()\n', (12911, 12913), False, 'from time import time\n'), ((15771, 15812), 'numpy.zeros', 'np.zeros', (['action_means.shape'], {'dtype': 'DTYPE'}), '(action_means.shape, dtype=DTYPE)\n', (15779, 15812), True, 'import numpy as np\n'), ((16958, 16999), 'numpy.zeros', 'np.zeros', (['action_means.shape'], {'dtype': 'DTYPE'}), '(action_means.shape, dtype=DTYPE)\n', (16966, 16999), True, 'import numpy as np\n'), ((17884, 17925), 'numpy.zeros', 'np.zeros', (['action_means.shape'], {'dtype': 'DTYPE'}), '(action_means.shape, dtype=DTYPE)\n', (17892, 17925), True, 'import numpy as np\n'), ((10949, 10974), 'numpy.arange', 'np.arange', (['max_backtracks'], {}), '(max_backtracks)\n', (10958, 10974), True, 'import numpy as np\n'), ((14567, 14581), 'keras.backend.get_value', 'K.get_value', (['p'], {}), '(p)\n', (14578, 14581), True, 'from keras import backend as K\n'), ((17537, 17561), 'numpy.log', 'np.log', (['(2 * np.pi * np.e)'], {}), '(2 * np.pi * np.e)\n', (17543, 17561), True, 'import numpy as np\n'), ((3407, 3421), 'keras.backend.get_value', 'K.get_value', (['p'], {}), '(p)\n', (3418, 3421), True, 'from keras import backend as K\n'), ((9626, 9639), 'numpy.sum', 'np.sum', (['(a * b)'], {}), '(a * b)\n', (9632, 9639), True, 'import numpy as np\n'), ((9839, 9853), 'numpy.sum', 'np.sum', (['(g ** 2)'], {}), '(g ** 2)\n', (9845, 9853), True, 'import numpy as np\n')]
#!/usr/bin/python # The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt # # This example program shows how you can use dlib to make an object # detector for things like object, pedestrians, and any other semi-rigid # object. In particular, we go though the steps to train the kind of sliding # window object detector first published by <NAME> in 2005 in the # paper Histograms of Oriented Gradients for Human Detection. # # # COMPILING/INSTALLING THE DLIB PYTHON INTERFACE # You can install dlib using the command: # pip install dlib # # Alternatively, if you want to compile dlib yourself then go into the dlib # root folder and run: # python setup.py install # or # python setup.py install --yes USE_AVX_INSTRUCTIONS # if you have a CPU that supports AVX instructions, since this makes some # things run faster. # # Compiling dlib should work on any operating system so long as you have # CMake and boost-python installed. On Ubuntu, this can be done easily by # running the command: # sudo apt-get install libboost-python-dev cmake # # Also note that this example requires scikit-image which can be installed # via the command: # pip install scikit-image # Or downloaded from http://scikit-image.org/download.html. import os import sys import glob import cv2 import dlib from skimage import io import cv2 import matplotlib.pyplot as plt import numpy as np current_dir = os.path.abspath(os.curdir) print(current_dir) # In this example we are going to train a face detector based on the small # object dataset in the examples/object directory. This means you need to supply # the path to this object folder as a command line argument so we will know # where it is. if len(sys.argv) < 2: print( "Give the path to the examples/object directory as the argument to this " "program. For example, if you are in the python_examples folder then " "execute this program by running:\n" " ./train_object_detector.py ../examples/object") exit() ip_folder = sys.argv[1] random_check_folder = sys.argv[2] options = dlib.shape_predictor_training_options() # Now make the object responsible for training the model. # This algorithm has a bunch of parameters you can mess with. The # documentation for the shape_predictor_trainer explains all of them. # You should also read Kazemi's paper which explains all the parameters # in great detail. However, here I'm just setting three of them # differently than their default values. I'm doing this because we # have a very small dataset. In particular, setting the oversampling # to a high amount (300) effectively boosts the training set size, so # that helps this example. options.oversampling_amount = 300 # I'm also reducing the capacity of the model by explicitly increasing # the regularization (making nu smaller) and by using trees with # smaller depths. options.nu = 0.05 options.tree_depth = 2 options.be_verbose = True print(ip_folder) ip_folder = os.path.abspath(ip_folder) training_xml_path = os.path.abspath(os.path.join(ip_folder, "training","training.xml")) testing_xml_path = os.path.abspath(os.path.join(ip_folder, "testing","testing.xml")) print(training_xml_path,testing_xml_path) # This function does the actual training. It will save the final detector to # detector.dat. The input is an XML file that lists the images in the training # dataset and also contains the positions of the face boxes. To create your # own XML files you can use the imglab tool which can be found in the # tools/imglab folder. It is a simple graphical tool for labeling objects in # images with boxes. To see how to use it read the tools/imglab/README.txt # file. But for this example, we just use the training.xml file included with # dlib. if not os.path.exists(os.path.join(ip_folder,"detector.dat")): os.chdir(os.path.dirname(training_xml_path)) dlib.train_shape_predictor("training.xml", os.path.join(ip_folder,"detector.dat"), options) # Now that we have a face detector we can test it. The first statement tests # it on the training data. It will print(the precision, recall, and then) # average precision. print("") # Print blank line to create gap from previous output os.chdir(os.path.dirname(training_xml_path)) train_test = dlib.test_shape_predictor("training.xml", os.path.join(ip_folder,"detector.dat").replace("\\","/")) print("Training accuracy: {}".format(train_test)) # However, to get an idea if it really worked without overfitting we need to # run it on images it wasn't trained on. The next line does this. Happily, we # see that the object detector works perfectly on the testing images. #print("Testing accuracy: {}".format(dlib.test_simple_object_detector(testing_xml_path, os.path.join(current_dir,"detector.dat"))) os.chdir(os.path.dirname(testing_xml_path)) true_test = dlib.test_shape_predictor("testing.xml", os.path.join(ip_folder,"detector.dat").replace("\\","/")) print("Testing accuracy: {}".format(true_test)) os.chdir(current_dir) # Now let's use the detector as you would in a normal application. First we # will load it from disk. predictor = dlib.shape_predictor(os.path.join(ip_folder,"detector.dat").replace("\\","/")) detector = dlib.simple_object_detector(os.path.join(ip_folder,"detector.svm").replace("\\","/")) # We can look at the HOG filter we learned. It should look like a face. Neat! #win_det = dlib.image_window() #win_det.set_image(detector) # Now let's run the detector over the images in the object folder and display the # results. #win = dlib.image_window() print("Showing detections on the images in the object folder...") verify_files = glob.glob(os.path.join(random_check_folder, "*.JPG")) tot_verify_files = len(verify_files) positive_verify = 0 for f in verify_files: print("Processing file: {}".format(f)) img = io.imread(f) orig_img = img.copy() dets = detector(img) print("Number of object detected: {}".format(len(dets))) #win.clear_overlay() #win.set_image(img) #win.add_overlay(dets) #dlib.hit_enter_to_continue() if len(dets)>0: for k, d in enumerate(dets): print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format( k, d.left(), d.top(), d.right(), d.bottom())) xmin = d.left() ymin = d.top() xmax = d.right() ymax = d.bottom() cv2.rectangle(img,(xmin,ymin),(xmax,ymax),(255,0,0),5) # Get the landmarks/parts for the face in box d. shape = predictor(img, d) #print("Part 0: {}, Part 1: {} ...".format(shape.part(0), # shape.part(1))) print(shape) if len(shape.parts())>0: parts = [] positive_verify = positive_verify + 1 for part in enumerate(shape.parts()): print(part) parts.append([part[1].x,part[1].y]) nparts = np.array(parts, np.int32) print(nparts) cv2.polylines(img, np.int32([nparts]),True,(0,255,0)) fig = plt.figure(figsize = (15,15)) ax1 = fig.add_subplot(211) ax1.set_xticks([]) ax1.set_yticks([]) ax1.set_title('Original Image') ax1.imshow(orig_img) #plt.show() ax2 = fig.add_subplot(212) ax2.set_xticks([]) ax2.set_yticks([]) ax2.set_title('Image with Detections') ax2.imshow(img) plt.show() print("% of Image Shapes Detected:",int(positive_verify*100/tot_verify_files))
[ "os.path.abspath", "matplotlib.pyplot.show", "os.path.dirname", "matplotlib.pyplot.figure", "numpy.array", "dlib.shape_predictor_training_options", "numpy.int32", "cv2.rectangle", "os.path.join", "os.chdir", "skimage.io.imread" ]
[((1480, 1506), 'os.path.abspath', 'os.path.abspath', (['os.curdir'], {}), '(os.curdir)\n', (1495, 1506), False, 'import os\n'), ((2154, 2193), 'dlib.shape_predictor_training_options', 'dlib.shape_predictor_training_options', ([], {}), '()\n', (2191, 2193), False, 'import dlib\n'), ((3046, 3072), 'os.path.abspath', 'os.path.abspath', (['ip_folder'], {}), '(ip_folder)\n', (3061, 3072), False, 'import os\n'), ((5055, 5076), 'os.chdir', 'os.chdir', (['current_dir'], {}), '(current_dir)\n', (5063, 5076), False, 'import os\n'), ((3109, 3160), 'os.path.join', 'os.path.join', (['ip_folder', '"""training"""', '"""training.xml"""'], {}), "(ip_folder, 'training', 'training.xml')\n", (3121, 3160), False, 'import os\n'), ((3196, 3245), 'os.path.join', 'os.path.join', (['ip_folder', '"""testing"""', '"""testing.xml"""'], {}), "(ip_folder, 'testing', 'testing.xml')\n", (3208, 3245), False, 'import os\n'), ((4294, 4328), 'os.path.dirname', 'os.path.dirname', (['training_xml_path'], {}), '(training_xml_path)\n', (4309, 4328), False, 'import os\n'), ((4860, 4893), 'os.path.dirname', 'os.path.dirname', (['testing_xml_path'], {}), '(testing_xml_path)\n', (4875, 4893), False, 'import os\n'), ((5721, 5763), 'os.path.join', 'os.path.join', (['random_check_folder', '"""*.JPG"""'], {}), "(random_check_folder, '*.JPG')\n", (5733, 5763), False, 'import os\n'), ((5899, 5911), 'skimage.io.imread', 'io.imread', (['f'], {}), '(f)\n', (5908, 5911), False, 'from skimage import io\n'), ((7201, 7229), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 15)'}), '(figsize=(15, 15))\n', (7211, 7229), True, 'import matplotlib.pyplot as plt\n'), ((7530, 7540), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7538, 7540), True, 'import matplotlib.pyplot as plt\n'), ((3856, 3895), 'os.path.join', 'os.path.join', (['ip_folder', '"""detector.dat"""'], {}), "(ip_folder, 'detector.dat')\n", (3868, 3895), False, 'import os\n'), ((3910, 3944), 'os.path.dirname', 'os.path.dirname', (['training_xml_path'], {}), '(training_xml_path)\n', (3925, 3944), False, 'import os\n'), ((3994, 4033), 'os.path.join', 'os.path.join', (['ip_folder', '"""detector.dat"""'], {}), "(ip_folder, 'detector.dat')\n", (4006, 4033), False, 'import os\n'), ((4385, 4424), 'os.path.join', 'os.path.join', (['ip_folder', '"""detector.dat"""'], {}), "(ip_folder, 'detector.dat')\n", (4397, 4424), False, 'import os\n'), ((4948, 4987), 'os.path.join', 'os.path.join', (['ip_folder', '"""detector.dat"""'], {}), "(ip_folder, 'detector.dat')\n", (4960, 4987), False, 'import os\n'), ((5213, 5252), 'os.path.join', 'os.path.join', (['ip_folder', '"""detector.dat"""'], {}), "(ip_folder, 'detector.dat')\n", (5225, 5252), False, 'import os\n'), ((5310, 5349), 'os.path.join', 'os.path.join', (['ip_folder', '"""detector.svm"""'], {}), "(ip_folder, 'detector.svm')\n", (5322, 5349), False, 'import os\n'), ((6461, 6523), 'cv2.rectangle', 'cv2.rectangle', (['img', '(xmin, ymin)', '(xmax, ymax)', '(255, 0, 0)', '(5)'], {}), '(img, (xmin, ymin), (xmax, ymax), (255, 0, 0), 5)\n', (6474, 6523), False, 'import cv2\n'), ((7064, 7089), 'numpy.array', 'np.array', (['parts', 'np.int32'], {}), '(parts, np.int32)\n', (7072, 7089), True, 'import numpy as np\n'), ((7155, 7173), 'numpy.int32', 'np.int32', (['[nparts]'], {}), '([nparts])\n', (7163, 7173), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Tue Oct 13 17:15:16 2020 @author: JAVIER """ import numpy as np import pandas as pd import pickle from .. import bci_architectures as athena from . import bci_penalty_plugin as bci_penalty from .. import load_brain_data as lb from Fancy_aggregations import penalties as pn from Fancy_aggregations import binary_parser as bp quasi_similarities = [pn._cuadratic_cost, pn._realistic_optimistic_cost, pn._huber_cost, pn._realistic_pesimistic_cost] quasi_dis = [pn._anti_cuadratic_cost] quasi_total = quasi_similarities + quasi_dis quasisim_name = ['Quadratic', 'Optimistic', 'Huber', 'Pessimistic'] quasidis_name = ['Anti-Quadratic'] names_total = quasisim_name + quasidis_name def generate_combination(cost1, cost2): ''' Returns a lambda of the two cost combined according to the appropiate mixing function. :param cost1: index of cost 1 in the quasi_total vector ''' if (cost1 < len(quasi_similarities)) and (cost2 < len(quasi_similarities)): comb_function = pn._convex_comb else: comb_function = pn._convex_quasi_comb return comb_function(quasi_total[cost1], quasi_total[cost2]) # ============================================================================= # BINARY CLASSIFICATION GRADIENT FOR THE AGGREGATION MFF # ============================================================================= def binary_cross_entropy_loss(output, y): return np.log(y * output + (1 - y) * output) def binary_update_alpha(X, cost, alpha, y): forward_logits = multi_alpha_forward(X, cost, alpha) loss = binary_cross_entropy_loss(forward_logits[:,0], y) update_alpha = loss * X return update_alpha def binary_train_loop(X, cost, alpha, y, learning_rate=0.01): ''' ''' loss = np.inf new_loss = 0 while new_loss >= loss: loss = new_loss alpha += binary_update_alpha(X, cost, alpha, y) forward_logits = multi_alpha_forward(X, cost, alpha) new_loss = binary_cross_entropy_loss(forward_logits, y) return alpha, new_loss multi_cost_names = ['R2+Opt', 'hub+Opt','Anti+Opt', 'Hub+Anti'] uni_cost_names = ['R2', 'opt', 'Anti-consensus', 'Huber', 'Pes'] # ============================================================================= # DYNAMIC ALPHA LEARNING METHOD # ============================================================================= def logistic_alpha_forward(X, cost_convex, clf): ''' X shape: (bandas, samples, clases) out shape: (samples, clases) ''' reformed_X = np.swapaxes(X, 0, 1) reformed_X = reformed_X.reshape((reformed_X.shape[0], reformed_X.shape[1]*reformed_X.shape[2])) alphas = clf.predict(reformed_X) result = np.zeros((X.shape[1], X.shape[2])) for sample in range(X.shape[1]): alpha_cost = lambda real, yhat, axis: cost_convex(real, yhat, axis, alphas[sample]) result[sample] = pn.penalty_aggregation(X[:, sample, :], [bp.parse(x) for x in athena.classical_aggregations], axis=0, keepdims=False, cost=alpha_cost) return result def multimodal_alpha_forward(X, cost, cost2, alpha): ''' X shape: list of n arrays (bandas, samples, clases) clfs: list of alphas. out shape: (samples, clases) ''' david_played_and_it_pleased_the_lord = [bp.parse(x) for x in athena.agg_functions_names] agg_phase_1 = lambda X0, alpha, keepdims=False, axis=0: pn.penalty_aggregation(X0, david_played_and_it_pleased_the_lord, axis=axis, keepdims=keepdims, cost=lambda real, yhat, axis: cost(real, yhat, axis, alpha=alpha)) agg_phase_2 = lambda X0, alpha, keepdims=False, axis=0: pn.penalty_aggregation(X0, david_played_and_it_pleased_the_lord, axis=axis, keepdims=keepdims, cost=lambda real, yhat, axis: cost2(real, yhat, axis, alpha=alpha)) return mpa_aggregation(X, agg_phase_1, agg_phase_2, alpha, keepdims=False) def generate_real_alpha(X, y, aggs, cost, opt=1): a = None b = None for alpha in np.arange(0.01, 1.01, 0.1): alpha_cost = lambda X, yhat, axis: cost(X, yhat, axis, alpha) pagg = pn.penalty_aggregation(X, [bp.parse(x) for x in aggs], axis=0, keepdims=False, cost=alpha_cost) if np.argmax(pagg) == y: if a is None: a = alpha else: b = alpha if a is None: a = 0.5 if b is None: b = 0.5 d1 = np.abs(a - 0.5) d2 = np.abs(b - 0.5) if opt == 1: if d1 <= d2: return a else: return b elif opt == 2: return (a + b) / 2 def generate_train_data_alpha(logits, labels, aggs=athena.classical_aggregations, cost=pn.cost_functions[0], opt=1): bands, samples, classes = logits.shape y = np.zeros((samples,)) for sample in range(samples): y[sample] = generate_real_alpha(logits[:,sample,:], labels[sample], aggs, cost, opt=opt) return y def gen_all_good_alpha_trad(cost, aggs=athena.classical_aggregations, opt=1, multi_class=False): ''' Learn the logistic regression for the whole set of datasets. (Trad framework) ''' import sklearn.linear_model from sklearn.model_selection import KFold n_splits = 5 kf = KFold(n_splits=n_splits) all_data = carmen_penalty_cache_logits(mff=False, multi_class=multi_class) all_logits_train, all_y_train, all_logits_test, all_y_test = all_data clfs = [] for logits_train, y_train, logits_test, y_test in zip(all_logits_train, all_y_train, all_logits_test, all_y_test): if opt == 1 or opt == 2: logits_reshaped = np.swapaxes(logits_train, 0, 1) logits_reshaped = logits_reshaped.reshape((logits_reshaped.shape[0], logits_reshaped.shape[1]*logits_reshaped.shape[2])) y_alpha = generate_train_data_alpha(logits_train, y_train, aggs=aggs, cost=cost, opt=opt) clf = sklearn.linear_model.LinearRegression().fit(logits_reshaped, y_alpha) elif opt == 'classic': def func_opt(alphita): acc = lambda x_data, y : np.mean(np.equal(y, np.argmax( pn.penalty_aggregation(x_data, [bp.parse(x) for x in aggs], axis=0, keepdims=False, cost=lambda X, yhat, axis: cost(X, yhat, axis, alpha=alphita)), axis=1))) acum_acc = 0 for train_index, test_index in kf.split(logits_train[0,:,:]): _, X_test = logits_train[:, train_index, :], logits_train[:, test_index, :] _, y_test = y_train[train_index], y_train[test_index] acum_acc += acc(X_test, y_test) return 1 - acum_acc / n_splits #Rememeber: we are minimizing clf = athena.my_optimization(func_opt) clfs.append(clf) return clfs # ============================================================================= # MULTIMODAL ALPHA OPTIMIZATION # ============================================================================= def eval_alpha(alpha_v, y_hat, y): ''' Returns ------- None. ''' alpha_score = np.mean(np.minimum(alpha_v, 1 - alpha_v)) acc_score = np.mean(np.equal(y_hat, y)) return (alpha_score + acc_score) / 2 def mpa_aggregation(logits, agg1, agg2, alpha, keepdims=False): n_2 = len(logits) n_1, samples, clases = logits[0].shape res = np.zeros((n_2, samples, clases)) for ix, logit in enumerate(logits): res[ix, :, :] = agg1(logit, axis=0, keepdims=False, alpha=alpha[ix]) return agg2(res, axis=0, keepdims=keepdims, alpha=alpha[-1]) def eval_conf(X, alpha, y, agg1, agg2): ''' Computes the mpa agg for X, and returns the optimization score. Parameters ---------- X : TYPE DESCRIPTION. alpha : TYPE DESCRIPTION. y : TYPE DESCRIPTION. agg1 : TYPE DESCRIPTION. agg2 : TYPE DESCRIPTION. Returns ------- TYPE DESCRIPTION. ''' y_hat = np.argmax(mpa_aggregation(X, agg1, agg2, alpha), axis=1) return eval_alpha(alpha, y_hat, y) def gen_all_good_alpha_mff(cost, cost2, aggs=athena.agg_functions_names, opt=1, four_class=False): ''' Learn the logistic regression for the whole set of datasets. ''' from scipy.optimize import least_squares all_data = carmen_penalty_cache_logits(mff=True, multi_class=four_class) all_logits_train, all_y_train, all_logits_test, all_y_test = all_data datasets = [] agg_phase_1 = lambda X, alpha, keepdims=False, axis=0: pn.penalty_aggregation(X, aggs, axis=axis, keepdims=keepdims, cost=lambda real, yhat, axis: cost(real, yhat, axis, alpha=alpha)) agg_phase_2 = lambda X, alpha, keepdims=False, axis=0: pn.penalty_aggregation(X, aggs, axis=axis, keepdims=keepdims, cost=lambda real, yhat, axis: cost2(real, yhat, axis, alpha=alpha)) for logits_train, y_train, logits_test, y_test in zip(all_logits_train, all_y_train, all_logits_test, all_y_test): optimize_lambda = lambda alpha: -eval_conf(logits_train, alpha, y_train, agg_phase_1, agg_phase_2) #Remember we are minimizng x0_alpha = np.array([0.5] * len(logits_train) + [0.5]) res_1 = least_squares(optimize_lambda, x0_alpha, bounds=[0.0001, 0.9999]) datasets.append(res_1.x) return datasets # ============================================================================= # SAVE AND LOAD CLFS # ============================================================================= def save_clfs(cost, cost_name, mff=False, four_classes=False, opt=1): if mff: clfs = gen_all_good_alpha_mff(cost, cost, [bp.parse(x) for x in athena.mff_aggregations], opt=opt, four_class=four_classes) else: clfs = gen_all_good_alpha_trad(cost, athena.classical_aggregations, opt=opt, multi_class=four_classes) ending = '' if not mff: ending += '_trad' else: ending += '_mff' if four_classes: ending += '_tonguefoot' else: ending += '_binary' ending += '_' + str(opt) if (opt == 1) or (opt == 2): with open('./regression_models/lclfs_' + cost_name + ending + '.pckl', 'wb') as f: pickle.dump(clfs, f) elif opt == 'classic': with open('./classic_alpha_models/alpha_' + cost_name + ending + '.pckl', 'wb') as f: pickle.dump(clfs, f) def load_clfs(cost_name, mff=False, four_classes=False, opt=1): import pickle ending = '' if not mff: ending += '_trad' else: ending += '_mff' if four_classes or four_classes == '_4_class': ending += '_tonguefoot' else: ending += '_binary' ending += '_' + str(opt) if (opt == 1) or (opt == 2): with open('./regression_models/lclfs_' + cost_name + ending + '.pckl', 'rb') as f: clfs = pickle.load(f) elif opt == 'classic': with open('./classic_alpha_models/alpha_' + cost_name + ending + '.pckl', 'rb') as f: clfs = pickle.load(f) return clfs def compute_accuracy_logistic_alpha(cost_convex, cost_name, mff=True, four_classes=False, opt=1): accuracy = lambda yhat, yreal: np.mean(np.equal(yhat, yreal)) clfs = load_clfs(cost_name, mff, four_classes, opt) all_logits_train, all_y_train, all_logits_test, all_y_test = carmen_penalty_cache_logits(mff=mff, multi_class=four_classes) train_accuracies = np.zeros((len(all_y_train))) test_accuracies = np.zeros((len(all_y_test))) ix = 0 for logits_train, y_train, logits_test, y_test in zip(all_logits_train, all_y_train, all_logits_test, all_y_test): if mff: agg_logits = multimodal_alpha_forward(logits_train, cost_convex, cost_convex, clfs[ix]) agg_logits_test = multimodal_alpha_forward(logits_test, cost_convex, cost_convex, clfs[ix]) else: if (opt == 1) or (opt == 2): agg_logits = logistic_alpha_forward(logits_train, cost_convex, clfs[ix]) agg_logits_test = logistic_alpha_forward(logits_test, cost_convex, clfs[ix]) elif opt == 'classic': alpha_cost = lambda X, yhat, axis: cost_convex(X, yhat, axis, alpha=clfs[ix]) agg_logits = bci_penalty._forward_penalty(logits_train, alpha_cost) agg_logits_test = bci_penalty._forward_penalty(logits_test, alpha_cost) yhat_train = np.argmax(agg_logits, axis=1) yhat_test = np.argmax(agg_logits_test, axis=1) train_accuracies[ix] = accuracy(yhat_train, y_train) test_accuracies[ix] = accuracy(yhat_test, y_test) ix+= 1 return train_accuracies, test_accuracies # ============================================================================= # FORWARD AND MISCELLANIOUS # ============================================================================= def carmen_penalty_cache_logits(mff=True, multi_class=False): if mff: framework='mff' archi = athena.bci_achitecture.emf_carmen_penalty_architecture else: framework='trad' archi = athena.bci_achitecture.trad_carmen_penalty_architecture if multi_class or (multi_class == '_4_class'): class_mode = '4_class' elif not multi_class or (multi_class == '_binary'): class_mode = 'binary' try: with open('logits_' + framework + '_carmen_' + class_mode + '_train.pckl', 'rb') as f: logits_train = pickle.load(f) with open('logits_' + framework + '_carmen_'+ class_mode +'_test.pckl', 'rb') as f: logits_test = pickle.load(f) with open('logits_' + framework + '_carmen_'+ class_mode +'_train_y.pckl', 'rb') as f: y_train = pickle.load(f) with open('logits_' + framework + '_carmen_'+ class_mode +'_test_y.pckl', 'rb') as f: y_test = pickle.load(f) except (IOError, EOFError) as e: print('Recomputing logits...', e) logits_train, y_train, logits_test, y_test = carmen_best_alpha_2a_all_logits(archi, 0, verbose=False, agregacion=pn.base_cost_functions[0], mff=mff, four_clases=multi_class) return logits_train, y_train, logits_test, y_test def multi_alpha_forward(X, cost_convex, alpha): try: multiple_alpha = len(alpha) > 1 except: multiple_alpha = False agg_logits = np.zeros((len(X), X[0].shape[1], X[0].shape[2])) for wave in range(len(X)): if not multiple_alpha: alpha_cost = lambda real, yhat, axis: cost_convex(real, yhat, axis, alpha[0]) else: alpha_cost = lambda real, yhat, axis: cost_convex(real, yhat, axis, alpha[wave]) agg_logits[wave] = pn.penalty_aggregation(X[wave], [bp.parse(x) for x in athena.mff_aggregations], axis=0, keepdims=False, cost=alpha_cost) if multiple_alpha: alpha_cost = lambda real, yhat, axis: cost_convex(real, yhat, axis, alpha[-1]) else: alpha_cost = lambda real, yhat, axis: cost_convex(real, yhat, axis, alpha) return pn.penalty_aggregation(agg_logits, [bp.parse(x) for x in athena.mff_aggregations], axis=0, keepdims=False, cost=alpha_cost) def _alpha_learn(X, y, cost, mff=False): def compute_accuracy(yhat, y): return np.mean(np.equal(yhat, y)) def optimize_function(X, y, cost_convex, alpha): alpha_cost = lambda real, yhat, axis: cost_convex(real, yhat, axis, alpha) agg_logits = pn.penalty_aggregation(X, [bp.parse(x) for x in athena.classical_aggregations], axis=0, keepdims=False, cost=alpha_cost) yhat = np.argmax(agg_logits, axis=1) return 1 - compute_accuracy(yhat, y) def optimize_function_mff(X, y, cost_convex, alpha): agg_logits = multi_alpha_forward(X, cost_convex, alpha) yhat = np.argmax(agg_logits, axis=1) return 1 - compute_accuracy(yhat, y) if mff: function_alpha = lambda a: optimize_function_mff(X, y, cost, a) x0 = [0.5] * 5 else: function_alpha = lambda a: optimize_function(X, y, cost, a) x0 = [0.5] res = athena.my_optimization(function_alpha, x0=x0, niter=100, mode='montecarlo') alpha_value = res if hasattr(alpha_value, 'len'): alpha_value = alpha_value[0] return lambda real, yhatf, axis: cost(real, yhatf, axis, alpha_value), alpha_value def study_alpha(architecture, x_test, y_test, cost, mff=False): lgts = architecture.csp_pass(x_test) alpha_f, alpha = _alpha_learn(lgts, y_test, cost, mff=mff) aggregation_set = athena.classical_aggregations if not mff else athena.mff_aggregations if not mff: agg_logits = pn.penalty_aggregation(lgts, [bp.parse(x) for x in aggregation_set], axis=0, keepdims=False, cost=alpha_f) else: agg_logits = multi_alpha_forward(lgts, cost, alpha) yhat = np.argmax(agg_logits, axis=1) return np.mean(np.equal(y_test, yhat)) def carmen_train_2a_all(architecture, derivate=0, verbose=False, agregacion=None, four_clases=False, opt=False): accuracies = [] for dataset_train, dataset_test in zip(lb.all_carmen_datasets_partitions(full_tasks=four_clases, opt=opt), lb.all_carmen_datasets_partitions(full_tasks=four_clases, test=True, opt=opt)): X_train, y_train = dataset_train X_test, y_test = dataset_test X_train = np.transpose(X_train, (2, 1, 0)) X_test = np.transpose(X_test, (2, 1, 0)) my_architecture = athena.bci_achitecture() if agregacion is None: architecture(my_architecture, X_train, y_train, verbose) else: architecture(my_architecture, X_train, y_train, verbose, agregacion) accuracies.append(np.mean(np.equal(my_architecture.forward(X_test), y_test))) if verbose: print('N-th accuracy: ' + str(np.mean(np.equal(my_architecture.forward(X_test), y_test))), 'Actual mean: ' + str(np.mean(accuracies))) return accuracies, my_architecture def carmen_best_alpha_2a_all(architecture, cost, derivate=0, verbose=False, agregacion=None, four_clases=False, opt=False, mff=False): accuracies = [] for dataset_train, dataset_test in zip(lb.all_carmen_datasets_partitions(full_tasks=four_clases, opt=opt), lb.all_carmen_datasets_partitions(full_tasks=four_clases, test=True, opt=opt)): X_train, y_train = dataset_train X_test, y_test = dataset_test X_train = np.transpose(X_train, (2, 1, 0)) X_test = np.transpose(X_test, (2, 1, 0)) my_architecture = athena.bci_achitecture() if agregacion is None: architecture(my_architecture, X_train, y_train, verbose) else: architecture(my_architecture, X_train, y_train, verbose, agregacion) accuracies.append(study_alpha(my_architecture, X_test, y_test, agregacion, mff)) if verbose: print('N-th accuracy: ' + str(np.mean(np.equal(my_architecture.forward(X_test), y_test))), 'Actual mean: ' + str(np.mean(accuracies))) return accuracies, my_architecture def carmen_best_alpha_2a_all_logits(architecture, cost, derivate=0, verbose=False, agregacion=None, four_clases=False, opt=False, mff=False): logits_train = [] logits_test = [] all_y_train = [] all_y_test = [] n_partitions = 20 for dataset_train, dataset_test in zip(lb.all_carmen_datasets_partitions(full_tasks=four_clases, opt=opt, n_partition=n_partitions), lb.all_carmen_datasets_partitions(full_tasks=four_clases, test=True, opt=opt, n_partition=n_partitions)): X_train, y_train = dataset_train X_test, y_test = dataset_test X_train = np.transpose(X_train, (2, 1, 0)) X_test = np.transpose(X_test, (2, 1, 0)) my_architecture = athena.bci_achitecture() if agregacion is None: architecture(my_architecture, X_train, y_train, verbose) else: architecture(my_architecture, X_train, y_train, verbose, agregacion) logits_train.append(my_architecture.logits) logits_test.append(my_architecture.csp_pass(X_test)) all_y_train.append(y_train) all_y_test.append(y_test) import pickle framework = 'mff' if mff else 'trad' class_mode = 'binary' if not four_clases else '4_class' with open('logits_' + framework + '_carmen_' + class_mode + '_train.pckl', 'wb') as f: pickle.dump(logits_train, f) with open('logits_' + framework + '_carmen_' + class_mode + '_train_y.pckl', 'wb') as f: pickle.dump(all_y_train, f) with open('logits_' + framework + '_carmen_' + class_mode + '_test.pckl', 'wb') as f: pickle.dump(logits_test, f) with open('logits_' + framework + '_carmen_' + class_mode + '_test_y.pckl', 'wb') as f: pickle.dump(all_y_test, f) return logits_train, all_y_train, logits_test, all_y_test def classifier_new_alpha(nombre, coste, multi_class=False, reload=True, mff=False, opt=1): if reload: save_clfs(coste, nombre, mff, four_classes=multi_class, opt=opt) train_acc, test_acc = compute_accuracy_logistic_alpha(coste, nombre, mff, multi_class, opt) return train_acc, test_acc def accuracy_report(cost_names, cost_funcs, mff, reload, multi_class, opt): accuracies_df = pd.DataFrame(np.zeros((len(cost_names), 1)), index=cost_names, columns=['Accuracy']) for ix, cost_func in enumerate(cost_funcs): accuracies_train, accuracies_test = classifier_new_alpha(cost_names[ix], cost_func, mff=mff, reload=reload, multi_class=multi_class, opt=opt) accuracies_df.iloc[ix,0] = np.mean(accuracies_test) return accuracies_df def accuracy_report_dual(mff, reload, multi_class_bool, opt): ''' Igual que accuracy report pero en una table de coste x coste ''' accuracies_df = pd.DataFrame(np.zeros((len(names_total), len(names_total))), index=names_total, columns=names_total) for ix, cost_func in enumerate(quasi_total): for jx, cost_func2 in enumerate(quasi_total): cost = generate_combination(ix, jx) accuracies_train, accuracies_test = classifier_new_alpha(names_total[ix] + '+' + names_total[jx], cost, mff=mff, reload=reload, multi_class=multi_class_bool, opt=opt) acc_test_df = pd.DataFrame(accuracies_test) mff_str = 'mff' if mff else 'trad' multi_class = 'four_classes' if multi_class_bool else 'binary' acc_test_df.to_csv('./carmen_results/' + mff_str + '_' + multi_class + '_' + str(opt) + '_' + names_total[ix].replace(' ','_') + '_' + names_total[jx].replace(' ','_') + '.csv') accuracies_df.iloc[ix,jx] = np.mean(accuracies_test) return accuracies_df def bin_alpha(opt=1, cost_names=multi_cost_names, cost_funcs=(pn.cost_functions[0], pn.cost_functions[1], pn.cost_functions[2], pn.cost_functions[3]), multi_class=False, mff=False, reload=True): framework = 'mff' if mff else 'trad' opt_str = '_' + str(opt) multiclass_str = '_4_class' if multi_class else '_binary' accuracy_report(cost_names, cost_funcs, mff, reload, multi_class, opt).to_csv('carmen_' + framework + '_penalty_costs_accuracies_best_alpha' + opt_str + multiclass_str + '.csv') def bin_alpha_dual(opt=1, multi_class=False, mff=False, reload=True): framework = 'mff' if mff else 'trad' opt_str = '_' + str(opt) multiclass_str = '_4_class' if multi_class else '_binary' accuracy_report_dual(mff, reload, multi_class, opt).to_csv('carmen_' + framework + '_penalty_costs_accuracies_best_alpha' + opt_str + multiclass_str + '.csv') def convert_to_tex(path_df): ''' ''' load_df = pd.read_csv(path_df, index_col=0) load_df.values[[np.arange(load_df.shape[0])]*2] = 0 max_value = load_df.max().max() n_cols = len(load_df.columns) def normal_format(val): return val def max_bold(val): max_string = '$ %.4f $' if val != max_value else '{$ \\mathbf{%.4f} $}' return max_string % val load_df.to_latex(open(path_df.replace('.csv', '.tex'), 'w'), formatters=[max_bold]*n_cols, column_format='l' + 'c'*n_cols, escape=False) def carmen_main(mode, args=None): print('Carmen bci plugin, mode: ', mode) # ============================================================================= # CARMEN CSP PENALTY DATA EXPERIMENTS # ============================================================================= if str(mode) == 'study_new_alpha_costs_binary': bin_alpha_dual(opt='classic', multi_class=False, mff=False, reload=True) bin_alpha_dual(opt=1, multi_class=False, mff=False, reload=True) elif str(mode) == 'study_new_alpha_costs_full_class': bin_alpha_dual(opt='classic', multi_class=True, mff=False, reload=True) bin_alpha_dual(opt=1, multi_class=True, mff=False, reload=True) elif str(mode) == 'study_new_alpha_costs_binary_mff': bin_alpha_dual(opt=1, multi_class=False, mff=True, reload=True) elif str(mode) == 'study_new_alpha_costs_full_class_mff': bin_alpha_dual(opt=1, multi_class=True, mff=True, reload=True) else: return 0 return 1 if __name__ == '__main__': carmen_main('study_new_alpha_costs_binary_mff')
[ "Fancy_aggregations.binary_parser.parse", "pandas.DataFrame", "pickle.dump", "numpy.minimum", "numpy.abs", "numpy.log", "numpy.argmax", "pandas.read_csv", "numpy.zeros", "numpy.transpose", "sklearn.model_selection.KFold", "numpy.equal", "scipy.optimize.least_squares", "numpy.mean", "numpy.arange", "numpy.swapaxes", "pickle.load" ]
[((1445, 1482), 'numpy.log', 'np.log', (['(y * output + (1 - y) * output)'], {}), '(y * output + (1 - y) * output)\n', (1451, 1482), True, 'import numpy as np\n'), ((2555, 2575), 'numpy.swapaxes', 'np.swapaxes', (['X', '(0)', '(1)'], {}), '(X, 0, 1)\n', (2566, 2575), True, 'import numpy as np\n'), ((2727, 2761), 'numpy.zeros', 'np.zeros', (['(X.shape[1], X.shape[2])'], {}), '((X.shape[1], X.shape[2]))\n', (2735, 2761), True, 'import numpy as np\n'), ((3971, 3997), 'numpy.arange', 'np.arange', (['(0.01)', '(1.01)', '(0.1)'], {}), '(0.01, 1.01, 0.1)\n', (3980, 3997), True, 'import numpy as np\n'), ((4389, 4404), 'numpy.abs', 'np.abs', (['(a - 0.5)'], {}), '(a - 0.5)\n', (4395, 4404), True, 'import numpy as np\n'), ((4414, 4429), 'numpy.abs', 'np.abs', (['(b - 0.5)'], {}), '(b - 0.5)\n', (4420, 4429), True, 'import numpy as np\n'), ((4744, 4764), 'numpy.zeros', 'np.zeros', (['(samples,)'], {}), '((samples,))\n', (4752, 4764), True, 'import numpy as np\n'), ((5213, 5237), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'n_splits'}), '(n_splits=n_splits)\n', (5218, 5237), False, 'from sklearn.model_selection import KFold\n'), ((7309, 7341), 'numpy.zeros', 'np.zeros', (['(n_2, samples, clases)'], {}), '((n_2, samples, clases))\n', (7317, 7341), True, 'import numpy as np\n'), ((16802, 16831), 'numpy.argmax', 'np.argmax', (['agg_logits'], {'axis': '(1)'}), '(agg_logits, axis=1)\n', (16811, 16831), True, 'import numpy as np\n'), ((23558, 23591), 'pandas.read_csv', 'pd.read_csv', (['path_df'], {'index_col': '(0)'}), '(path_df, index_col=0)\n', (23569, 23591), True, 'import pandas as pd\n'), ((3301, 3312), 'Fancy_aggregations.binary_parser.parse', 'bp.parse', (['x'], {}), '(x)\n', (3309, 3312), True, 'from Fancy_aggregations import binary_parser as bp\n'), ((7048, 7080), 'numpy.minimum', 'np.minimum', (['alpha_v', '(1 - alpha_v)'], {}), '(alpha_v, 1 - alpha_v)\n', (7058, 7080), True, 'import numpy as np\n'), ((7106, 7124), 'numpy.equal', 'np.equal', (['y_hat', 'y'], {}), '(y_hat, y)\n', (7114, 7124), True, 'import numpy as np\n'), ((9133, 9198), 'scipy.optimize.least_squares', 'least_squares', (['optimize_lambda', 'x0_alpha'], {'bounds': '[0.0001, 0.9999]'}), '(optimize_lambda, x0_alpha, bounds=[0.0001, 0.9999])\n', (9146, 9198), False, 'from scipy.optimize import least_squares\n'), ((12321, 12350), 'numpy.argmax', 'np.argmax', (['agg_logits'], {'axis': '(1)'}), '(agg_logits, axis=1)\n', (12330, 12350), True, 'import numpy as np\n'), ((12371, 12405), 'numpy.argmax', 'np.argmax', (['agg_logits_test'], {'axis': '(1)'}), '(agg_logits_test, axis=1)\n', (12380, 12405), True, 'import numpy as np\n'), ((15548, 15577), 'numpy.argmax', 'np.argmax', (['agg_logits'], {'axis': '(1)'}), '(agg_logits, axis=1)\n', (15557, 15577), True, 'import numpy as np\n'), ((15761, 15790), 'numpy.argmax', 'np.argmax', (['agg_logits'], {'axis': '(1)'}), '(agg_logits, axis=1)\n', (15770, 15790), True, 'import numpy as np\n'), ((16851, 16873), 'numpy.equal', 'np.equal', (['y_test', 'yhat'], {}), '(y_test, yhat)\n', (16859, 16873), True, 'import numpy as np\n'), ((17299, 17331), 'numpy.transpose', 'np.transpose', (['X_train', '(2, 1, 0)'], {}), '(X_train, (2, 1, 0))\n', (17311, 17331), True, 'import numpy as np\n'), ((17349, 17380), 'numpy.transpose', 'np.transpose', (['X_test', '(2, 1, 0)'], {}), '(X_test, (2, 1, 0))\n', (17361, 17380), True, 'import numpy as np\n'), ((18361, 18393), 'numpy.transpose', 'np.transpose', (['X_train', '(2, 1, 0)'], {}), '(X_train, (2, 1, 0))\n', (18373, 18393), True, 'import numpy as np\n'), ((18411, 18442), 'numpy.transpose', 'np.transpose', (['X_test', '(2, 1, 0)'], {}), '(X_test, (2, 1, 0))\n', (18423, 18442), True, 'import numpy as np\n'), ((19571, 19603), 'numpy.transpose', 'np.transpose', (['X_train', '(2, 1, 0)'], {}), '(X_train, (2, 1, 0))\n', (19583, 19603), True, 'import numpy as np\n'), ((19621, 19652), 'numpy.transpose', 'np.transpose', (['X_test', '(2, 1, 0)'], {}), '(X_test, (2, 1, 0))\n', (19633, 19652), True, 'import numpy as np\n'), ((20304, 20332), 'pickle.dump', 'pickle.dump', (['logits_train', 'f'], {}), '(logits_train, f)\n', (20315, 20332), False, 'import pickle\n'), ((20434, 20461), 'pickle.dump', 'pickle.dump', (['all_y_train', 'f'], {}), '(all_y_train, f)\n', (20445, 20461), False, 'import pickle\n'), ((20560, 20587), 'pickle.dump', 'pickle.dump', (['logits_test', 'f'], {}), '(logits_test, f)\n', (20571, 20587), False, 'import pickle\n'), ((20688, 20714), 'pickle.dump', 'pickle.dump', (['all_y_test', 'f'], {}), '(all_y_test, f)\n', (20699, 20714), False, 'import pickle\n'), ((21502, 21526), 'numpy.mean', 'np.mean', (['accuracies_test'], {}), '(accuracies_test)\n', (21509, 21526), True, 'import numpy as np\n'), ((4192, 4207), 'numpy.argmax', 'np.argmax', (['pagg'], {}), '(pagg)\n', (4201, 4207), True, 'import numpy as np\n'), ((5589, 5620), 'numpy.swapaxes', 'np.swapaxes', (['logits_train', '(0)', '(1)'], {}), '(logits_train, 0, 1)\n', (5600, 5620), True, 'import numpy as np\n'), ((10124, 10144), 'pickle.dump', 'pickle.dump', (['clfs', 'f'], {}), '(clfs, f)\n', (10135, 10144), False, 'import pickle\n'), ((10771, 10785), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (10782, 10785), False, 'import pickle\n'), ((11100, 11121), 'numpy.equal', 'np.equal', (['yhat', 'yreal'], {}), '(yhat, yreal)\n', (11108, 11121), True, 'import numpy as np\n'), ((13406, 13420), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (13417, 13420), False, 'import pickle\n'), ((13548, 13562), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (13559, 13562), False, 'import pickle\n'), ((13689, 13703), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (13700, 13703), False, 'import pickle\n'), ((13828, 13842), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (13839, 13842), False, 'import pickle\n'), ((15045, 15056), 'Fancy_aggregations.binary_parser.parse', 'bp.parse', (['x'], {}), '(x)\n', (15053, 15056), True, 'from Fancy_aggregations import binary_parser as bp\n'), ((15234, 15251), 'numpy.equal', 'np.equal', (['yhat', 'y'], {}), '(yhat, y)\n', (15242, 15251), True, 'import numpy as np\n'), ((22173, 22202), 'pandas.DataFrame', 'pd.DataFrame', (['accuracies_test'], {}), '(accuracies_test)\n', (22185, 22202), True, 'import pandas as pd\n'), ((22555, 22579), 'numpy.mean', 'np.mean', (['accuracies_test'], {}), '(accuracies_test)\n', (22562, 22579), True, 'import numpy as np\n'), ((2959, 2970), 'Fancy_aggregations.binary_parser.parse', 'bp.parse', (['x'], {}), '(x)\n', (2967, 2970), True, 'from Fancy_aggregations import binary_parser as bp\n'), ((4111, 4122), 'Fancy_aggregations.binary_parser.parse', 'bp.parse', (['x'], {}), '(x)\n', (4119, 4122), True, 'from Fancy_aggregations import binary_parser as bp\n'), ((9569, 9580), 'Fancy_aggregations.binary_parser.parse', 'bp.parse', (['x'], {}), '(x)\n', (9577, 9580), True, 'from Fancy_aggregations import binary_parser as bp\n'), ((10278, 10298), 'pickle.dump', 'pickle.dump', (['clfs', 'f'], {}), '(clfs, f)\n', (10289, 10298), False, 'import pickle\n'), ((10926, 10940), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (10937, 10940), False, 'import pickle\n'), ((14705, 14716), 'Fancy_aggregations.binary_parser.parse', 'bp.parse', (['x'], {}), '(x)\n', (14713, 14716), True, 'from Fancy_aggregations import binary_parser as bp\n'), ((15439, 15450), 'Fancy_aggregations.binary_parser.parse', 'bp.parse', (['x'], {}), '(x)\n', (15447, 15450), True, 'from Fancy_aggregations import binary_parser as bp\n'), ((16643, 16654), 'Fancy_aggregations.binary_parser.parse', 'bp.parse', (['x'], {}), '(x)\n', (16651, 16654), True, 'from Fancy_aggregations import binary_parser as bp\n'), ((23612, 23639), 'numpy.arange', 'np.arange', (['load_df.shape[0]'], {}), '(load_df.shape[0])\n', (23621, 23639), True, 'import numpy as np\n'), ((17853, 17872), 'numpy.mean', 'np.mean', (['accuracies'], {}), '(accuracies)\n', (17860, 17872), True, 'import numpy as np\n'), ((18918, 18937), 'numpy.mean', 'np.mean', (['accuracies'], {}), '(accuracies)\n', (18925, 18937), True, 'import numpy as np\n'), ((6114, 6125), 'Fancy_aggregations.binary_parser.parse', 'bp.parse', (['x'], {}), '(x)\n', (6122, 6125), True, 'from Fancy_aggregations import binary_parser as bp\n')]
import matplotlib.image as mpimg import numpy as np import pickle from test_feature_exrtact import * from lesson_functions import * color_space = 'YCrCb' orient = 9 pix_per_cell = 8 cell_per_block = 2 hog_channel = 'ALL' spatial_size = (32, 32) hist_bins = 32 spatial_feat = True hist_feat = True hog_feat = True scale = 1.5 t = time.time() n_samples = 1000 random_ids = np.random.randint(0, len(car_images), n_samples) test_cars = np.array(car_images)[random_ids] test_noncars = np.array(noncar_images)[random_ids] car_features = extract_features(car_images, color_space=color_space, spatial_size=spatial_size, hist_bins=hist_bins, orient=orient, pix_per_cell=pix_per_cell, cell_per_block=cell_per_block, hog_channel=hog_channel, spatial_feat=spatial_feat, hist_feat=hist_feat, hog_feat=hog_feat) noncar_features = extract_features(noncar_images, color_space=color_space, spatial_size=spatial_size, hist_bins=hist_bins, orient=orient, pix_per_cell=pix_per_cell, cell_per_block=cell_per_block, hog_channel=hog_channel, spatial_feat=spatial_feat, hist_feat=hist_feat, hog_feat=hog_feat) print (time.time()-t, 'Seconds to compute features..') X = np.vstack((car_features, noncar_features)).astype(np.float64) X_scaler = StandardScaler().fit(X) scaled_X = X_scaler.transform(X) y = np.hstack((np.ones(len(car_features)), np.zeros(len(noncar_features)))) rand_state = np.random.randint(0,100) X_train, X_test, y_train, y_test = train_test_split(scaled_X, y, test_size=0.1, random_state=rand_state) print('Using: ', orient, 'orientations, ', pix_per_cell, 'pixels per cell,', cell_per_block, 'cells per block,', hist_bins, 'histogram bins, and', spatial_size, 'spatial sampling') print('Feature vector length: ', len(X_train[0])) svc = LinearSVC(C=0.01) t = time.time() svc.fit(X_train, y_train) print(round(time.time()-t, 2), 'Seconds to train SVC...') print('accuracy: ', round(svc.score(X_test, y_test), 4)) #trained_svc_pickle = {} #trained_svc_pickle["svc"] = svc #trained_svc_pickle["x_scaler"] = X_scaler #trained_svc_pickle["scale"] = scale #trained_svc_pickle["orient"] = orient #trained_svc_pickle["pix_per_cell"] = pix_per_cell #trained_svc_pickle["cell_per_block"] = cell_per_block #trained_svc_pickle["spatial_size"] = spatial_size #trained_svc_pickle["hist_bins"] = hist_bins #trained_svc_pickle["color_space"] = color_space #pickle.dump(trained_svc_pickle, open('./trained_svc_pickle.p', 'wb'))
[ "numpy.random.randint", "numpy.array", "numpy.vstack" ]
[((2090, 2115), 'numpy.random.randint', 'np.random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (2107, 2115), True, 'import numpy as np\n'), ((461, 481), 'numpy.array', 'np.array', (['car_images'], {}), '(car_images)\n', (469, 481), True, 'import numpy as np\n'), ((510, 533), 'numpy.array', 'np.array', (['noncar_images'], {}), '(noncar_images)\n', (518, 533), True, 'import numpy as np\n'), ((1859, 1901), 'numpy.vstack', 'np.vstack', (['(car_features, noncar_features)'], {}), '((car_features, noncar_features))\n', (1868, 1901), True, 'import numpy as np\n')]
""" dlc2kinematics © <NAME> https://github.com/AdaptiveMotorControlLab/dlc2kinematics/ """ import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib import gridspec from mpl_toolkits.mplot3d import Axes3D from sklearn.decomposition import PCA from dlc2kinematics.utils import auxiliaryfunctions def plot_velocity(df, df_velocity, start=None, end=None): """ Plots the computed velocities with the original X, Y data Parameters ---------- df: the .h5 file 2d or 3d from DeepLabCut that you loaded during dlc2kinematics.load_data df_velocity: Pandas dataframe of computed velocities. Computed with dlc2kinematics.compute_velocity start: int Optional. Integer specifying the start of frame index to select. Default is set to 0. end: int Optional. Integer specifying the end of frame index to select. Default is set to length of dataframe. Example ------- >>> dlc2kinematics.plot_velocity(df, df_velocity, start=1,end=500) """ try: df_velocity = pd.read_hdf(df_velocity, "df_with_missing") except: pass if start == None: start = 0 if end == None: end = len(df_velocity) ax = df_velocity[start:end].plot(kind="line") plt.xlabel("Frame numbers") plt.ylabel("velocity (AU)") ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) plt.title("Computed Velocity", loc="left") plt.legend(loc="center left", bbox_to_anchor=(1, 0.5)) plt.show() ax1 = df[start:end].plot(kind="line") plt.xlabel("Frame numbers") plt.ylabel("position") ax1.spines["right"].set_visible(False) ax1.spines["top"].set_visible(False) plt.title("Loaded Position Data", loc="left") plt.legend(loc="center left", bbox_to_anchor=(1, 0.5)) plt.show() def plot_joint_angles(joint_angle, angles=[None], start=None, end=None): """ Plots the joint angles Parameters ---------- joint_angle: Pandas dataframe of joint angles. angles: list Optional. List of angles to plot start: int Optional. Integer specifying the start of frame index to select. Default is set to 0. end: int Optional. Integer specifying the end of frame index to select. Default is set to length of dataframe. Example ------- >>> dlc2kinematics.plot_joint_angles(joint_angle) """ try: joint_angle = pd.read_hdf(joint_angle, "df_with_missing") except: pass if start == None: start = 0 if end == None: end = len(joint_angle) if angles[0] == None: angles = list(joint_angle.columns.get_level_values(0)) ax = joint_angle[angles][start:end].plot(kind="line") # plt.tight_layout() plt.ylim([0, 180]) plt.xlabel("Frame numbers") plt.ylabel("Joint angle in degrees") ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) plt.title("Joint Angles", loc="left") plt.legend(loc="center left", bbox_to_anchor=(1, 0.5)) plt.show() def visualize_synergies(data_reconstructed): ncols, _, nrows = data_reconstructed.shape fig, axes = plt.subplots(nrows, ncols, sharex=True, sharey=True, figsize=(10, 8)) for row in range(nrows): for col in range(ncols): ax = axes[row, col] ax.plot(data_reconstructed[col, :, row]) if row == 0: ax.set_title(f"Synergy {col + 1}") ax.tick_params(axis="both", which="both", bottom=False, left=False) def pca_plot( num, v, fig, k, df_projected, variance_explained, n_comps, bodyparts2plot, bp_to_connect, ): """ customized PCA plot. """ gs = gridspec.GridSpec(1, num) cmap = "cividis_r" alphaValue = 0.7 color = plt.cm.get_cmap(cmap, len(bodyparts2plot)) scorer = df_projected.columns.get_level_values(0)[0] axes2 = fig.add_subplot(gs[0, v], projection="3d") # row 0, col 1 fig.tight_layout() plt.cla() axes2.cla() xdata_3d = [] ydata_3d = [] zdata_3d = [] xdata_3d_pca = [] ydata_3d_pca = [] zdata_3d_pca = [] xRight_3d = [] yRight_3d = [] zRight_3d = [] xRight_3d_pca = [] yRight_3d_pca = [] zRight_3d_pca = [] axes2.view_init(113, 270) axes2.set_xlim3d([4, 10]) # [4,9] axes2.set_ylim3d([1, -3]) # 1,-5 axes2.set_zlim3d([14, 10]) axes2.set_xticklabels([]) axes2.set_yticklabels([]) axes2.set_zticklabels([]) axes2.xaxis.grid(False) # Need a loop for drawing skeleton for right_bp in bp_to_connect: xRight_3d_pca.append(df_projected.iloc[k][scorer][right_bp]["x"]) yRight_3d_pca.append(df_projected.iloc[k][scorer][right_bp]["y"]) zRight_3d_pca.append(df_projected.iloc[k][scorer][right_bp]["z"]) for bpindex, bp in enumerate(bodyparts2plot): xdata_3d_pca.append(df_projected.iloc[k][scorer][bp]["x"]) ydata_3d_pca.append(df_projected.iloc[k][scorer][bp]["y"]) zdata_3d_pca.append(df_projected.iloc[k][scorer][bp]["z"]) p2 = axes2.scatter( df_projected[scorer][bp]["x"][k], df_projected[scorer][bp]["y"][k], df_projected[scorer][bp]["z"][k], marker="o", ) # c=color(bodyparts2plot.index(bp)) axes2.plot( xRight_3d_pca, yRight_3d_pca, zRight_3d_pca, color="black", alpha=alphaValue ) axes2.set_title( "Reconstructed with %s PCs and %s%% EV" % (n_comps, round(variance_explained * 100, 2)) ) return plt def plot_3d_pca_reconstruction( df, n_components, framenumber, bodyparts2plot, bp_to_connect ): """ Computes and plots a 3D reconstruction of various pc's. Parameters ---------- df: Pandas dataframe of either original bodypart 3d file, or outputs from compute_joint_velocity, or compute_joint_acceleration. n_components: int how many principal components to use framenumer: int which frame do you want to display? Example ------- >>> dlc2kinematics.plot_3d_pca_reconstruction(joint_velocity, n_components=10, frame=1) """ # pca = PCA(n_components=n_components, svd_solver="full").fit(df) comp = [n_components, 1] num = len(comp) fig = plt.figure(figsize=(9, 5)) fig.tight_layout() scorer = df.columns.get_level_values(0)[0] k = framenumber # a specific frame the user wants to show. for v in range(len(comp)): p = PCA(comp[v]).fit(df) n_comps = p.n_components_ # n_components components = p.transform(df) projected = p.inverse_transform(components) variance_explained = np.cumsum(p.explained_variance_ratio_)[-1] df_projected = auxiliaryfunctions.create_empty_df(df) bodyparts = list(df.columns.get_level_values(1))[0::3] projected_reshape = projected.reshape(len(projected), len(bodyparts), 3) for idx, bp in enumerate(bodyparts): df_projected.loc(axis=1)[scorer, bp] = projected_reshape[:, idx] pca_plot( num, v, fig, k, df_projected, variance_explained, n_comps, bodyparts2plot, bp_to_connect, ) plt.show() def plot_umap(Y, size=5, alpha=1, color="indigo", figsize=(10, 6)): """ Computes and plots a 3D reconstruction of various pc's. Parameters ---------- Y: fitted data from dlc2kinematics.compute_umap. n_fitted_samples x number_components size: int size of each individual datapoint alpha: int alpha blending value, transparent - opaque color: Depending on what you want to color, the color input can be a matrix of size n_fitted_samples x number_components Example ------- >>> c = np.random.rand(Y.shape[0],3) >>> dlc2kinematics.plot_umap(Y, 5, 1, c) """ fig = plt.figure(figsize=figsize) ax = Axes3D(fig) ax.view_init(0, 20) ax.dist = 8 ax.scatter(Y[:, 0], Y[:, 2], Y[:, 1], alpha=alpha, s=size, c=color)
[ "matplotlib.pyplot.title", "matplotlib.pyplot.show", "mpl_toolkits.mplot3d.Axes3D", "pandas.read_hdf", "matplotlib.pyplot.ylim", "matplotlib.pyplot.legend", "numpy.cumsum", "matplotlib.pyplot.figure", "matplotlib.pyplot.cla", "sklearn.decomposition.PCA", "dlc2kinematics.utils.auxiliaryfunctions.create_empty_df", "matplotlib.pyplot.ylabel", "matplotlib.gridspec.GridSpec", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.subplots" ]
[((1270, 1297), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Frame numbers"""'], {}), "('Frame numbers')\n", (1280, 1297), True, 'import matplotlib.pyplot as plt\n'), ((1302, 1329), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""velocity (AU)"""'], {}), "('velocity (AU)')\n", (1312, 1329), True, 'import matplotlib.pyplot as plt\n'), ((1416, 1458), 'matplotlib.pyplot.title', 'plt.title', (['"""Computed Velocity"""'], {'loc': '"""left"""'}), "('Computed Velocity', loc='left')\n", (1425, 1458), True, 'import matplotlib.pyplot as plt\n'), ((1463, 1517), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""center left"""', 'bbox_to_anchor': '(1, 0.5)'}), "(loc='center left', bbox_to_anchor=(1, 0.5))\n", (1473, 1517), True, 'import matplotlib.pyplot as plt\n'), ((1522, 1532), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1530, 1532), True, 'import matplotlib.pyplot as plt\n'), ((1580, 1607), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Frame numbers"""'], {}), "('Frame numbers')\n", (1590, 1607), True, 'import matplotlib.pyplot as plt\n'), ((1612, 1634), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""position"""'], {}), "('position')\n", (1622, 1634), True, 'import matplotlib.pyplot as plt\n'), ((1723, 1768), 'matplotlib.pyplot.title', 'plt.title', (['"""Loaded Position Data"""'], {'loc': '"""left"""'}), "('Loaded Position Data', loc='left')\n", (1732, 1768), True, 'import matplotlib.pyplot as plt\n'), ((1773, 1827), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""center left"""', 'bbox_to_anchor': '(1, 0.5)'}), "(loc='center left', bbox_to_anchor=(1, 0.5))\n", (1783, 1827), True, 'import matplotlib.pyplot as plt\n'), ((1832, 1842), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1840, 1842), True, 'import matplotlib.pyplot as plt\n'), ((2788, 2806), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0, 180]'], {}), '([0, 180])\n', (2796, 2806), True, 'import matplotlib.pyplot as plt\n'), ((2811, 2838), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Frame numbers"""'], {}), "('Frame numbers')\n", (2821, 2838), True, 'import matplotlib.pyplot as plt\n'), ((2843, 2879), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Joint angle in degrees"""'], {}), "('Joint angle in degrees')\n", (2853, 2879), True, 'import matplotlib.pyplot as plt\n'), ((2966, 3003), 'matplotlib.pyplot.title', 'plt.title', (['"""Joint Angles"""'], {'loc': '"""left"""'}), "('Joint Angles', loc='left')\n", (2975, 3003), True, 'import matplotlib.pyplot as plt\n'), ((3008, 3062), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""center left"""', 'bbox_to_anchor': '(1, 0.5)'}), "(loc='center left', bbox_to_anchor=(1, 0.5))\n", (3018, 3062), True, 'import matplotlib.pyplot as plt\n'), ((3067, 3077), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3075, 3077), True, 'import matplotlib.pyplot as plt\n'), ((3188, 3257), 'matplotlib.pyplot.subplots', 'plt.subplots', (['nrows', 'ncols'], {'sharex': '(True)', 'sharey': '(True)', 'figsize': '(10, 8)'}), '(nrows, ncols, sharex=True, sharey=True, figsize=(10, 8))\n', (3200, 3257), True, 'import matplotlib.pyplot as plt\n'), ((3757, 3782), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['(1)', 'num'], {}), '(1, num)\n', (3774, 3782), False, 'from matplotlib import gridspec\n'), ((4037, 4046), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (4044, 4046), True, 'import matplotlib.pyplot as plt\n'), ((6332, 6358), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(9, 5)'}), '(figsize=(9, 5))\n', (6342, 6358), True, 'import matplotlib.pyplot as plt\n'), ((7327, 7337), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7335, 7337), True, 'import matplotlib.pyplot as plt\n'), ((7985, 8012), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (7995, 8012), True, 'import matplotlib.pyplot as plt\n'), ((8022, 8033), 'mpl_toolkits.mplot3d.Axes3D', 'Axes3D', (['fig'], {}), '(fig)\n', (8028, 8033), False, 'from mpl_toolkits.mplot3d import Axes3D\n'), ((1055, 1098), 'pandas.read_hdf', 'pd.read_hdf', (['df_velocity', '"""df_with_missing"""'], {}), "(df_velocity, 'df_with_missing')\n", (1066, 1098), True, 'import pandas as pd\n'), ((2447, 2490), 'pandas.read_hdf', 'pd.read_hdf', (['joint_angle', '"""df_with_missing"""'], {}), "(joint_angle, 'df_with_missing')\n", (2458, 2490), True, 'import pandas as pd\n'), ((6792, 6830), 'dlc2kinematics.utils.auxiliaryfunctions.create_empty_df', 'auxiliaryfunctions.create_empty_df', (['df'], {}), '(df)\n', (6826, 6830), False, 'from dlc2kinematics.utils import auxiliaryfunctions\n'), ((6726, 6764), 'numpy.cumsum', 'np.cumsum', (['p.explained_variance_ratio_'], {}), '(p.explained_variance_ratio_)\n', (6735, 6764), True, 'import numpy as np\n'), ((6537, 6549), 'sklearn.decomposition.PCA', 'PCA', (['comp[v]'], {}), '(comp[v])\n', (6540, 6549), False, 'from sklearn.decomposition import PCA\n')]
import numpy as np from scipy import stats data = np.array([1,2,3,4]) ans = np.median(data) print(ans)
[ "numpy.median", "numpy.array" ]
[((51, 73), 'numpy.array', 'np.array', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (59, 73), True, 'import numpy as np\n'), ((77, 92), 'numpy.median', 'np.median', (['data'], {}), '(data)\n', (86, 92), True, 'import numpy as np\n')]
#!/usr/bin/env python # test_processors.py # # Copyright (C) 2020-2021 <NAME> # All rights reserved. # # This software may be modified and distributed under the terms of the # BSD license. See the LICENSE file for details. from os.path import getsize import numpy as np import pytest from PIL import Image from shared import ( esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode, ) from pipescaler.common import temporary_filename from pipescaler.processors import ( AppleScriptExternalProcessor, AutomatorExternalProcessor, CropProcessor, ESRGANProcessor, ExpandProcessor, HeightToNormalProcessor, ModeProcessor, PngquantExternalProcessor, PotraceExternalProcessor, ResizeProcessor, SolidColorProcessor, TexconvExternalProcessor, ThresholdProcessor, WaifuExternalProcessor, XbrzProcessor, ) # region Fixtures @pytest.fixture() def apple_script_external_processor(request) -> AppleScriptExternalProcessor: return AppleScriptExternalProcessor(**request.param) @pytest.fixture() def automator_external_processor(request) -> AutomatorExternalProcessor: return AutomatorExternalProcessor(**request.param) @pytest.fixture() def crop_processor(request) -> CropProcessor: return CropProcessor(**request.param) @pytest.fixture() def esrgan_processor(request) -> ESRGANProcessor: return ESRGANProcessor(**request.param) @pytest.fixture() def expand_processor(request) -> ExpandProcessor: return ExpandProcessor(**request.param) @pytest.fixture() def height_to_normal_processor(request) -> HeightToNormalProcessor: return HeightToNormalProcessor(**request.param) @pytest.fixture() def mode_processor(request) -> ModeProcessor: return ModeProcessor(**request.param) @pytest.fixture() def potrace_external_processor(request) -> PotraceExternalProcessor: return PotraceExternalProcessor(**request.param) @pytest.fixture() def pngquant_external_processor(request) -> PngquantExternalProcessor: return PngquantExternalProcessor(**request.param) @pytest.fixture() def resize_processor(request) -> ResizeProcessor: return ResizeProcessor(**request.param) @pytest.fixture() def solid_color_processor(request) -> SolidColorProcessor: return SolidColorProcessor(**request.param) @pytest.fixture() def texconv_external_processor(request) -> TexconvExternalProcessor: return TexconvExternalProcessor(**request.param) @pytest.fixture() def threshold_processor(request) -> ThresholdProcessor: return ThresholdProcessor(**request.param) @pytest.fixture() def waifu_external_processor(request) -> WaifuExternalProcessor: return WaifuExternalProcessor(**request.param) @pytest.fixture() def xbrz_processor(request) -> XbrzProcessor: return XbrzProcessor(**request.param) # endregion @pytest.mark.serial @pytest.mark.parametrize( ("infile", "apple_script_external_processor"), [ xfail_if_platform({"Linux", "Windows"})( infiles["RGB"], {"script": "pixelmator/ml_super_resolution.scpt", "args": "2"}, ), xfail_if_platform({"Linux", "Windows"})( infiles["RGBA"], {"script": "pixelmator/ml_super_resolution.scpt", "args": "2"}, ), ], indirect=["apple_script_external_processor"], ) def test_apple_script_external( infile: str, apple_script_external_processor: AppleScriptExternalProcessor ) -> None: with temporary_filename(".png") as outfile: apple_script_external_processor(infile, outfile) with Image.open(infile) as input_image, Image.open(outfile) as output_image: assert output_image.mode == input_image.mode assert output_image.size == ( input_image.size[0] * int(apple_script_external_processor.args), input_image.size[1] * int(apple_script_external_processor.args), ) @pytest.mark.serial @pytest.mark.parametrize( ("infile", "automator_external_processor"), [ xfail_if_platform({"Linux", "Windows"})( infiles["RGB"], {"workflow": "pixelmator/denoise.workflow"}, ), xfail_if_platform({"Linux", "Windows"})( infiles["RGBA"], {"workflow": "pixelmator/denoise.workflow"}, ), ], indirect=["automator_external_processor"], ) def test_automator_external( infile: str, automator_external_processor: AutomatorExternalProcessor ) -> None: with temporary_filename(".png") as outfile: automator_external_processor(infile, outfile) with Image.open(infile) as input_image, Image.open(outfile) as output_image: assert output_image.mode == input_image.mode assert output_image.size == input_image.size @pytest.mark.parametrize( ("infile", "crop_processor"), [ (infiles["L"], {"pixels": (4, 4, 4, 4)}), (infiles["LA"], {"pixels": (4, 4, 4, 4)}), (infiles["RGB"], {"pixels": (4, 4, 4, 4)}), (infiles["RGBA"], {"pixels": (4, 4, 4, 4)}), (infiles["PL"], {"pixels": (4, 4, 4, 4)}), (infiles["PLA"], {"pixels": (4, 4, 4, 4)}), (infiles["PRGB"], {"pixels": (4, 4, 4, 4)}), (infiles["PRGBA"], {"pixels": (4, 4, 4, 4)}), ], indirect=["crop_processor"], ) def test_crop(infile: str, crop_processor: CropProcessor) -> None: with temporary_filename(".png") as outfile: crop_processor(infile, outfile) with Image.open(infile) as input_image, Image.open(outfile) as output_image: assert output_image.mode == input_image.mode assert output_image.size == ( input_image.size[0] - crop_processor.left - crop_processor.right, input_image.size[1] - crop_processor.top - crop_processor.bottom, ) @pytest.mark.serial @pytest.mark.parametrize( ("infile", "esrgan_processor"), [ skip_if_ci()(infiles["L"], {"model_infile": esrgan_models["1x_BC1-smooth2"]}), skip_if_ci()(infiles["PL"], {"model_infile": esrgan_models["1x_BC1-smooth2"]}), skip_if_ci()( infiles["PRGB"], {"model_infile": esrgan_models["1x_BC1-smooth2"]} ), skip_if_ci()(infiles["RGB"], {"model_infile": esrgan_models["1x_BC1-smooth2"]}), skip_if_ci()(infiles["RGB"], {"model_infile": esrgan_models["RRDB_ESRGAN_x4"]}), skip_if_ci()( infiles["RGB"], {"model_infile": esrgan_models["RRDB_ESRGAN_x4_old_arch"]} ), skip_if_ci(xfail_unsupported_mode())( infiles["LA"], {"model_infile": esrgan_models["1x_BC1-smooth2"]} ), skip_if_ci(xfail_unsupported_mode())( infiles["PLA"], {"model_infile": esrgan_models["1x_BC1-smooth2"]} ), skip_if_ci(xfail_unsupported_mode())( infiles["PRGBA"], {"model_infile": esrgan_models["1x_BC1-smooth2"]} ), skip_if_ci(xfail_unsupported_mode())( infiles["RGBA"], {"model_infile": esrgan_models["1x_BC1-smooth2"]} ), ], indirect=["esrgan_processor"], ) def test_esrgan(infile: str, esrgan_processor: ESRGANProcessor) -> None: with temporary_filename(".png") as outfile: esrgan_processor(infile, outfile) with Image.open(infile) as input_image, Image.open(outfile) as output_image: assert output_image.mode == expected_output_mode(input_image) @pytest.mark.parametrize( ("infile", "expand_processor"), [ (infiles["L"], {"pixels": (4, 4, 4, 4)}), (infiles["LA"], {"pixels": (4, 4, 4, 4)}), (infiles["RGB"], {"pixels": (4, 4, 4, 4)}), (infiles["RGBA"], {"pixels": (4, 4, 4, 4)}), (infiles["PL"], {"pixels": (4, 4, 4, 4)}), (infiles["PLA"], {"pixels": (4, 4, 4, 4)}), (infiles["PRGB"], {"pixels": (4, 4, 4, 4)}), (infiles["PRGBA"], {"pixels": (4, 4, 4, 4)}), ], indirect=["expand_processor"], ) def test_expand(infile: str, expand_processor: ExpandProcessor) -> None: with temporary_filename(".png") as outfile: expand_processor(infile, outfile) with Image.open(infile) as input_image, Image.open(outfile) as output_image: assert output_image.mode == input_image.mode assert output_image.size == ( input_image.size[0] + expand_processor.left + expand_processor.right, input_image.size[1] + expand_processor.top + expand_processor.bottom, ) @pytest.mark.parametrize( ("infile", "height_to_normal_processor"), [ (infiles["L"], {"sigma": 0.5}), (infiles["L"], {"sigma": 1.0}), xfail_unsupported_mode()(infiles["LA"], {"sigma": 1.0}), (infiles["PL"], {"sigma": 1.0}), xfail_unsupported_mode()(infiles["PLA"], {"sigma": 1.0}), xfail_unsupported_mode()(infiles["PRGB"], {"sigma": 1.0}), xfail_unsupported_mode()(infiles["PRGBA"], {"sigma": 1.0}), xfail_unsupported_mode()(infiles["RGB"], {"sigma": 1.0}), xfail_unsupported_mode()(infiles["RGBA"], {"sigma": 1.0}), ], indirect=["height_to_normal_processor"], ) def test_height_to_normal( infile: str, height_to_normal_processor: HeightToNormalProcessor ) -> None: with temporary_filename(".png") as outfile: height_to_normal_processor(infile, outfile) with Image.open(infile) as input_image, Image.open(outfile) as output_image: output_datum = np.array(output_image) assert output_image.mode == "RGB" assert output_image.size == input_image.size assert np.min(output_datum[:, :, 2] >= 128) @pytest.mark.parametrize( ("infile", "mode_processor"), [ (infiles["L"], {"mode": "L"}), (infiles["L"], {"mode": "LA"}), (infiles["L"], {"mode": "RGB"}), (infiles["L"], {"mode": "RGBA"}), (infiles["LA"], {"mode": "L"}), (infiles["LA"], {"mode": "LA"}), (infiles["LA"], {"mode": "RGB"}), (infiles["LA"], {"mode": "RGBA"}), (infiles["RGB"], {"mode": "L"}), (infiles["RGB"], {"mode": "LA"}), (infiles["RGB"], {"mode": "RGB"}), (infiles["RGB"], {"mode": "RGBA"}), (infiles["RGBA"], {"mode": "L"}), (infiles["RGBA"], {"mode": "LA"}), (infiles["RGBA"], {"mode": "RGB"}), (infiles["RGBA"], {"mode": "RGBA"}), (infiles["PL"], {"mode": "RGBA"}), (infiles["PLA"], {"mode": "RGBA"}), (infiles["PRGB"], {"mode": "RGBA"}), (infiles["PRGBA"], {"mode": "RGBA"}), ], indirect=["mode_processor"], ) def test_mode(infile: str, mode_processor: ModeProcessor) -> None: with temporary_filename(".png") as outfile: mode_processor(infile, outfile) with Image.open(infile) as input_image, Image.open(outfile) as output_image: assert output_image.size == input_image.size assert output_image.mode == mode_processor.mode @pytest.mark.parametrize( ("infile", "pngquant_external_processor"), [ (infiles["L"], {}), (infiles["LA"], {}), (infiles["RGB"], {}), (infiles["RGBA"], {}), (infiles["PL"], {}), (infiles["PRGB"], {}), (infiles["PRGBA"], {}), (infiles["PLA"], {}), ], indirect=["pngquant_external_processor"], ) def test_pngquant_external( infile: str, pngquant_external_processor: PngquantExternalProcessor ) -> None: with temporary_filename(".png") as outfile: pngquant_external_processor(infile, outfile) with Image.open(infile) as input_image, Image.open(outfile) as output_image: assert output_image.mode in (input_image.mode, "P") assert output_image.size == input_image.size assert getsize(outfile) <= getsize(infile) @pytest.mark.parametrize( ("infile", "potrace_external_processor"), [ (infiles["L"], {}), (infiles["L"], {"scale": 2}), xfail_unsupported_mode()(infiles["LA"], {}), (infiles["PL"], {}), xfail_unsupported_mode()(infiles["PLA"], {}), xfail_unsupported_mode()(infiles["PRGB"], {}), xfail_unsupported_mode()(infiles["PRGBA"], {}), xfail_unsupported_mode()(infiles["RGB"], {}), xfail_unsupported_mode()(infiles["RGBA"], {}), ], indirect=["potrace_external_processor"], ) def test_potrace_external( infile: str, potrace_external_processor: PotraceExternalProcessor ) -> None: with temporary_filename(".png") as outfile: potrace_external_processor(infile, outfile) with Image.open(infile) as input_image, Image.open(outfile) as output_image: assert output_image.mode == "L" assert output_image.size == ( input_image.size[0] * potrace_external_processor.scale, input_image.size[1] * potrace_external_processor.scale, ) @pytest.mark.parametrize( ("infile", "resize_processor"), [ (infiles["L"], {"scale": 2}), (infiles["LA"], {"scale": 2}), (infiles["RGB"], {"scale": 2}), (infiles["RGBA"], {"scale": 2}), (infiles["PL"], {"scale": 2}), (infiles["PLA"], {"scale": 2}), (infiles["PRGB"], {"scale": 2}), (infiles["PRGBA"], {"scale": 2}), ], indirect=["resize_processor"], ) def test_resize(infile: str, resize_processor: ResizeProcessor) -> None: with temporary_filename(".png") as outfile: resize_processor(infile, outfile) with Image.open(infile) as input_image, Image.open(outfile) as output_image: assert output_image.mode == expected_output_mode(input_image) assert output_image.size == ( input_image.size[0] * resize_processor.scale, input_image.size[1] * resize_processor.scale, ) @pytest.mark.parametrize( ("infile", "solid_color_processor"), [ (infiles["L"], {}), (infiles["LA"], {}), (infiles["RGB"], {}), (infiles["RGBA"], {}), (infiles["PL"], {}), (infiles["PLA"], {}), (infiles["PRGB"], {}), (infiles["PRGBA"], {}), ], indirect=["solid_color_processor"], ) def test_solid_color(infile: str, solid_color_processor: SolidColorProcessor) -> None: with temporary_filename(".png") as outfile: solid_color_processor(infile, outfile) with Image.open(infile) as input_image, Image.open(outfile) as output_image: assert output_image.mode == expected_output_mode(input_image) assert output_image.size == input_image.size assert len(output_image.getcolors()) == 1 @pytest.mark.parametrize( ("infile", "texconv_external_processor"), [ xfail_if_platform({"Darwin", "Linux"})(infiles["L"], {}), xfail_if_platform({"Darwin", "Linux"})(infiles["LA"], {}), xfail_if_platform({"Darwin", "Linux"})(infiles["RGB"], {}), xfail_if_platform({"Darwin", "Linux"})(infiles["RGBA"], {}), xfail_if_platform({"Darwin", "Linux"})(infiles["PL"], {}), xfail_if_platform({"Darwin", "Linux"})(infiles["PLA"], {}), xfail_if_platform({"Darwin", "Linux"})(infiles["PRGB"], {}), xfail_if_platform({"Darwin", "Linux"})(infiles["PRGBA"], {}), ], indirect=["texconv_external_processor"], ) def test_texconv_external( infile: str, texconv_external_processor: TexconvExternalProcessor ) -> None: with temporary_filename(".png") as outfile: texconv_external_processor(infile, outfile) with Image.open(infile) as input_image, Image.open(outfile) as output_image: assert output_image.mode == "RGBA" assert output_image.size == input_image.size @pytest.mark.parametrize( ("infile", "threshold_processor"), [ (infiles["L"], {}), (infiles["L"], {"denoise": True}), xfail_unsupported_mode()(infiles["LA"], {}), (infiles["PL"], {}), xfail_unsupported_mode()(infiles["PLA"], {}), xfail_unsupported_mode()(infiles["PRGB"], {}), xfail_unsupported_mode()(infiles["PRGBA"], {}), xfail_unsupported_mode()(infiles["RGB"], {}), xfail_unsupported_mode()(infiles["RGBA"], {}), ], indirect=["threshold_processor"], ) def test_threshold(infile: str, threshold_processor: ThresholdProcessor) -> None: with temporary_filename(".png") as outfile: threshold_processor(infile, outfile) with Image.open(infile) as input_image, Image.open(outfile) as output_image: output_datum = np.array(output_image) assert output_image.mode == "L" assert output_image.size == input_image.size assert np.logical_or(output_datum == 0, output_datum == 255).all() @pytest.mark.serial @pytest.mark.parametrize( ("infile", "waifu_external_processor"), [ skip_if_ci()(infiles["L"], {"imagetype": "a", "denoise": 0, "scale": 2}), skip_if_ci()(infiles["PL"], {"imagetype": "a", "denoise": 0, "scale": 2}), skip_if_ci()(infiles["PRGB"], {"imagetype": "a", "denoise": 0, "scale": 2}), skip_if_ci()(infiles["RGB"], {"imagetype": "a", "denoise": 0, "scale": 2}), skip_if_ci()(infiles["RGB"], {"imagetype": "a", "denoise": 3, "scale": 2}), skip_if_ci(xfail_unsupported_mode())( infiles["LA"], {"imagetype": "a", "denoise": 0, "scale": 2} ), skip_if_ci(xfail_unsupported_mode())( infiles["PLA"], {"imagetype": "a", "denoise": 0, "scale": 2} ), skip_if_ci(xfail_unsupported_mode())( infiles["PRGBA"], {"imagetype": "a", "denoise": 0, "scale": 2} ), skip_if_ci(xfail_unsupported_mode())( infiles["RGBA"], {"imagetype": "a", "denoise": 0, "scale": 2} ), ], indirect=["waifu_external_processor"], ) def test_waifu_external( infile: str, waifu_external_processor: WaifuExternalProcessor ) -> None: with temporary_filename(".png") as outfile: waifu_external_processor(infile, outfile) with Image.open(infile) as input_image, Image.open(outfile) as output_image: assert output_image.mode == expected_output_mode(input_image) assert output_image.size == ( input_image.size[0] * waifu_external_processor.scale, input_image.size[1] * waifu_external_processor.scale, ) @pytest.mark.parametrize( ("infile", "xbrz_processor"), [ (infiles["L"], {"scale": 2}), (infiles["LA"], {"scale": 2}), (infiles["RGB"], {"scale": 2}), (infiles["RGBA"], {"scale": 2}), (infiles["PL"], {"scale": 2}), (infiles["PLA"], {"scale": 2}), (infiles["PRGB"], {"scale": 2}), (infiles["PRGBA"], {"scale": 2}), ], indirect=["xbrz_processor"], ) def test_xbrz(infile: str, xbrz_processor: XbrzProcessor) -> None: with temporary_filename(".png") as outfile: xbrz_processor(infile, outfile) with Image.open(infile) as input_image, Image.open(outfile) as output_image: assert output_image.mode == expected_output_mode(input_image) assert output_image.size == ( input_image.size[0] * xbrz_processor.scale, input_image.size[1] * xbrz_processor.scale, )
[ "pipescaler.processors.ThresholdProcessor", "pipescaler.processors.XbrzProcessor", "pipescaler.processors.ESRGANProcessor", "pipescaler.processors.AppleScriptExternalProcessor", "pipescaler.processors.SolidColorProcessor", "pytest.mark.parametrize", "pipescaler.processors.CropProcessor", "shared.xfail_if_platform", "pipescaler.processors.PotraceExternalProcessor", "pipescaler.processors.ResizeProcessor", "shared.xfail_unsupported_mode", "pipescaler.common.temporary_filename", "os.path.getsize", "pytest.fixture", "shared.skip_if_ci", "numpy.min", "pipescaler.processors.WaifuExternalProcessor", "pipescaler.processors.TexconvExternalProcessor", "pipescaler.processors.AutomatorExternalProcessor", "pipescaler.processors.ExpandProcessor", "pipescaler.processors.HeightToNormalProcessor", "PIL.Image.open", "pipescaler.processors.ModeProcessor", "shared.expected_output_mode", "numpy.array", "numpy.logical_or", "pipescaler.processors.PngquantExternalProcessor" ]
[((958, 974), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (972, 974), False, 'import pytest\n'), ((1113, 1129), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1127, 1129), False, 'import pytest\n'), ((1261, 1277), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1275, 1277), False, 'import pytest\n'), ((1369, 1385), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1383, 1385), False, 'import pytest\n'), ((1483, 1499), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1497, 1499), False, 'import pytest\n'), ((1597, 1613), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1611, 1613), False, 'import pytest\n'), ((1737, 1753), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1751, 1753), False, 'import pytest\n'), ((1845, 1861), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1859, 1861), False, 'import pytest\n'), ((1987, 2003), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (2001, 2003), False, 'import pytest\n'), ((2132, 2148), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (2146, 2148), False, 'import pytest\n'), ((2246, 2262), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (2260, 2262), False, 'import pytest\n'), ((2373, 2389), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (2387, 2389), False, 'import pytest\n'), ((2515, 2531), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (2529, 2531), False, 'import pytest\n'), ((2638, 2654), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (2652, 2654), False, 'import pytest\n'), ((2774, 2790), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (2788, 2790), False, 'import pytest\n'), ((4842, 5307), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["('infile', 'crop_processor')", "[(infiles['L'], {'pixels': (4, 4, 4, 4)}), (infiles['LA'], {'pixels': (4, 4,\n 4, 4)}), (infiles['RGB'], {'pixels': (4, 4, 4, 4)}), (infiles['RGBA'],\n {'pixels': (4, 4, 4, 4)}), (infiles['PL'], {'pixels': (4, 4, 4, 4)}), (\n infiles['PLA'], {'pixels': (4, 4, 4, 4)}), (infiles['PRGB'], {'pixels':\n (4, 4, 4, 4)}), (infiles['PRGBA'], {'pixels': (4, 4, 4, 4)})]"], {'indirect': "['crop_processor']"}), "(('infile', 'crop_processor'), [(infiles['L'], {\n 'pixels': (4, 4, 4, 4)}), (infiles['LA'], {'pixels': (4, 4, 4, 4)}), (\n infiles['RGB'], {'pixels': (4, 4, 4, 4)}), (infiles['RGBA'], {'pixels':\n (4, 4, 4, 4)}), (infiles['PL'], {'pixels': (4, 4, 4, 4)}), (infiles[\n 'PLA'], {'pixels': (4, 4, 4, 4)}), (infiles['PRGB'], {'pixels': (4, 4, \n 4, 4)}), (infiles['PRGBA'], {'pixels': (4, 4, 4, 4)})], indirect=[\n 'crop_processor'])\n", (4865, 5307), False, 'import pytest\n'), ((7470, 7939), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["('infile', 'expand_processor')", "[(infiles['L'], {'pixels': (4, 4, 4, 4)}), (infiles['LA'], {'pixels': (4, 4,\n 4, 4)}), (infiles['RGB'], {'pixels': (4, 4, 4, 4)}), (infiles['RGBA'],\n {'pixels': (4, 4, 4, 4)}), (infiles['PL'], {'pixels': (4, 4, 4, 4)}), (\n infiles['PLA'], {'pixels': (4, 4, 4, 4)}), (infiles['PRGB'], {'pixels':\n (4, 4, 4, 4)}), (infiles['PRGBA'], {'pixels': (4, 4, 4, 4)})]"], {'indirect': "['expand_processor']"}), "(('infile', 'expand_processor'), [(infiles['L'], {\n 'pixels': (4, 4, 4, 4)}), (infiles['LA'], {'pixels': (4, 4, 4, 4)}), (\n infiles['RGB'], {'pixels': (4, 4, 4, 4)}), (infiles['RGBA'], {'pixels':\n (4, 4, 4, 4)}), (infiles['PL'], {'pixels': (4, 4, 4, 4)}), (infiles[\n 'PLA'], {'pixels': (4, 4, 4, 4)}), (infiles['PRGB'], {'pixels': (4, 4, \n 4, 4)}), (infiles['PRGBA'], {'pixels': (4, 4, 4, 4)})], indirect=[\n 'expand_processor'])\n", (7493, 7939), False, 'import pytest\n'), ((9690, 10510), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["('infile', 'mode_processor')", "[(infiles['L'], {'mode': 'L'}), (infiles['L'], {'mode': 'LA'}), (infiles[\n 'L'], {'mode': 'RGB'}), (infiles['L'], {'mode': 'RGBA'}), (infiles['LA'\n ], {'mode': 'L'}), (infiles['LA'], {'mode': 'LA'}), (infiles['LA'], {\n 'mode': 'RGB'}), (infiles['LA'], {'mode': 'RGBA'}), (infiles['RGB'], {\n 'mode': 'L'}), (infiles['RGB'], {'mode': 'LA'}), (infiles['RGB'], {\n 'mode': 'RGB'}), (infiles['RGB'], {'mode': 'RGBA'}), (infiles['RGBA'],\n {'mode': 'L'}), (infiles['RGBA'], {'mode': 'LA'}), (infiles['RGBA'], {\n 'mode': 'RGB'}), (infiles['RGBA'], {'mode': 'RGBA'}), (infiles['PL'], {\n 'mode': 'RGBA'}), (infiles['PLA'], {'mode': 'RGBA'}), (infiles['PRGB'],\n {'mode': 'RGBA'}), (infiles['PRGBA'], {'mode': 'RGBA'})]"], {'indirect': "['mode_processor']"}), "(('infile', 'mode_processor'), [(infiles['L'], {\n 'mode': 'L'}), (infiles['L'], {'mode': 'LA'}), (infiles['L'], {'mode':\n 'RGB'}), (infiles['L'], {'mode': 'RGBA'}), (infiles['LA'], {'mode': 'L'\n }), (infiles['LA'], {'mode': 'LA'}), (infiles['LA'], {'mode': 'RGB'}),\n (infiles['LA'], {'mode': 'RGBA'}), (infiles['RGB'], {'mode': 'L'}), (\n infiles['RGB'], {'mode': 'LA'}), (infiles['RGB'], {'mode': 'RGB'}), (\n infiles['RGB'], {'mode': 'RGBA'}), (infiles['RGBA'], {'mode': 'L'}), (\n infiles['RGBA'], {'mode': 'LA'}), (infiles['RGBA'], {'mode': 'RGB'}), (\n infiles['RGBA'], {'mode': 'RGBA'}), (infiles['PL'], {'mode': 'RGBA'}),\n (infiles['PLA'], {'mode': 'RGBA'}), (infiles['PRGB'], {'mode': 'RGBA'}),\n (infiles['PRGBA'], {'mode': 'RGBA'})], indirect=['mode_processor'])\n", (9713, 10510), False, 'import pytest\n'), ((11008, 11314), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["('infile', 'pngquant_external_processor')", "[(infiles['L'], {}), (infiles['LA'], {}), (infiles['RGB'], {}), (infiles[\n 'RGBA'], {}), (infiles['PL'], {}), (infiles['PRGB'], {}), (infiles[\n 'PRGBA'], {}), (infiles['PLA'], {})]"], {'indirect': "['pngquant_external_processor']"}), "(('infile', 'pngquant_external_processor'), [(\n infiles['L'], {}), (infiles['LA'], {}), (infiles['RGB'], {}), (infiles[\n 'RGBA'], {}), (infiles['PL'], {}), (infiles['PRGB'], {}), (infiles[\n 'PRGBA'], {}), (infiles['PLA'], {})], indirect=[\n 'pngquant_external_processor'])\n", (11031, 11314), False, 'import pytest\n'), ((12952, 13315), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["('infile', 'resize_processor')", "[(infiles['L'], {'scale': 2}), (infiles['LA'], {'scale': 2}), (infiles[\n 'RGB'], {'scale': 2}), (infiles['RGBA'], {'scale': 2}), (infiles['PL'],\n {'scale': 2}), (infiles['PLA'], {'scale': 2}), (infiles['PRGB'], {\n 'scale': 2}), (infiles['PRGBA'], {'scale': 2})]"], {'indirect': "['resize_processor']"}), "(('infile', 'resize_processor'), [(infiles['L'], {\n 'scale': 2}), (infiles['LA'], {'scale': 2}), (infiles['RGB'], {'scale':\n 2}), (infiles['RGBA'], {'scale': 2}), (infiles['PL'], {'scale': 2}), (\n infiles['PLA'], {'scale': 2}), (infiles['PRGB'], {'scale': 2}), (\n infiles['PRGBA'], {'scale': 2})], indirect=['resize_processor'])\n", (12975, 13315), False, 'import pytest\n'), ((13889, 14176), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["('infile', 'solid_color_processor')", "[(infiles['L'], {}), (infiles['LA'], {}), (infiles['RGB'], {}), (infiles[\n 'RGBA'], {}), (infiles['PL'], {}), (infiles['PLA'], {}), (infiles[\n 'PRGB'], {}), (infiles['PRGBA'], {})]"], {'indirect': "['solid_color_processor']"}), "(('infile', 'solid_color_processor'), [(infiles['L'],\n {}), (infiles['LA'], {}), (infiles['RGB'], {}), (infiles['RGBA'], {}),\n (infiles['PL'], {}), (infiles['PLA'], {}), (infiles['PRGB'], {}), (\n infiles['PRGBA'], {})], indirect=['solid_color_processor'])\n", (13912, 14176), False, 'import pytest\n'), ((18466, 18825), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["('infile', 'xbrz_processor')", "[(infiles['L'], {'scale': 2}), (infiles['LA'], {'scale': 2}), (infiles[\n 'RGB'], {'scale': 2}), (infiles['RGBA'], {'scale': 2}), (infiles['PL'],\n {'scale': 2}), (infiles['PLA'], {'scale': 2}), (infiles['PRGB'], {\n 'scale': 2}), (infiles['PRGBA'], {'scale': 2})]"], {'indirect': "['xbrz_processor']"}), "(('infile', 'xbrz_processor'), [(infiles['L'], {\n 'scale': 2}), (infiles['LA'], {'scale': 2}), (infiles['RGB'], {'scale':\n 2}), (infiles['RGBA'], {'scale': 2}), (infiles['PL'], {'scale': 2}), (\n infiles['PLA'], {'scale': 2}), (infiles['PRGB'], {'scale': 2}), (\n infiles['PRGBA'], {'scale': 2})], indirect=['xbrz_processor'])\n", (18489, 18825), False, 'import pytest\n'), ((1064, 1109), 'pipescaler.processors.AppleScriptExternalProcessor', 'AppleScriptExternalProcessor', ([], {}), '(**request.param)\n', (1092, 1109), False, 'from pipescaler.processors import AppleScriptExternalProcessor, AutomatorExternalProcessor, CropProcessor, ESRGANProcessor, ExpandProcessor, HeightToNormalProcessor, ModeProcessor, PngquantExternalProcessor, PotraceExternalProcessor, ResizeProcessor, SolidColorProcessor, TexconvExternalProcessor, ThresholdProcessor, WaifuExternalProcessor, XbrzProcessor\n'), ((1214, 1257), 'pipescaler.processors.AutomatorExternalProcessor', 'AutomatorExternalProcessor', ([], {}), '(**request.param)\n', (1240, 1257), False, 'from pipescaler.processors import AppleScriptExternalProcessor, AutomatorExternalProcessor, CropProcessor, ESRGANProcessor, ExpandProcessor, HeightToNormalProcessor, ModeProcessor, PngquantExternalProcessor, PotraceExternalProcessor, ResizeProcessor, SolidColorProcessor, TexconvExternalProcessor, ThresholdProcessor, WaifuExternalProcessor, XbrzProcessor\n'), ((1335, 1365), 'pipescaler.processors.CropProcessor', 'CropProcessor', ([], {}), '(**request.param)\n', (1348, 1365), False, 'from pipescaler.processors import AppleScriptExternalProcessor, AutomatorExternalProcessor, CropProcessor, ESRGANProcessor, ExpandProcessor, HeightToNormalProcessor, ModeProcessor, PngquantExternalProcessor, PotraceExternalProcessor, ResizeProcessor, SolidColorProcessor, TexconvExternalProcessor, ThresholdProcessor, WaifuExternalProcessor, XbrzProcessor\n'), ((1447, 1479), 'pipescaler.processors.ESRGANProcessor', 'ESRGANProcessor', ([], {}), '(**request.param)\n', (1462, 1479), False, 'from pipescaler.processors import AppleScriptExternalProcessor, AutomatorExternalProcessor, CropProcessor, ESRGANProcessor, ExpandProcessor, HeightToNormalProcessor, ModeProcessor, PngquantExternalProcessor, PotraceExternalProcessor, ResizeProcessor, SolidColorProcessor, TexconvExternalProcessor, ThresholdProcessor, WaifuExternalProcessor, XbrzProcessor\n'), ((1561, 1593), 'pipescaler.processors.ExpandProcessor', 'ExpandProcessor', ([], {}), '(**request.param)\n', (1576, 1593), False, 'from pipescaler.processors import AppleScriptExternalProcessor, AutomatorExternalProcessor, CropProcessor, ESRGANProcessor, ExpandProcessor, HeightToNormalProcessor, ModeProcessor, PngquantExternalProcessor, PotraceExternalProcessor, ResizeProcessor, SolidColorProcessor, TexconvExternalProcessor, ThresholdProcessor, WaifuExternalProcessor, XbrzProcessor\n'), ((1693, 1733), 'pipescaler.processors.HeightToNormalProcessor', 'HeightToNormalProcessor', ([], {}), '(**request.param)\n', (1716, 1733), False, 'from pipescaler.processors import AppleScriptExternalProcessor, AutomatorExternalProcessor, CropProcessor, ESRGANProcessor, ExpandProcessor, HeightToNormalProcessor, ModeProcessor, PngquantExternalProcessor, PotraceExternalProcessor, ResizeProcessor, SolidColorProcessor, TexconvExternalProcessor, ThresholdProcessor, WaifuExternalProcessor, XbrzProcessor\n'), ((1811, 1841), 'pipescaler.processors.ModeProcessor', 'ModeProcessor', ([], {}), '(**request.param)\n', (1824, 1841), False, 'from pipescaler.processors import AppleScriptExternalProcessor, AutomatorExternalProcessor, CropProcessor, ESRGANProcessor, ExpandProcessor, HeightToNormalProcessor, ModeProcessor, PngquantExternalProcessor, PotraceExternalProcessor, ResizeProcessor, SolidColorProcessor, TexconvExternalProcessor, ThresholdProcessor, WaifuExternalProcessor, XbrzProcessor\n'), ((1942, 1983), 'pipescaler.processors.PotraceExternalProcessor', 'PotraceExternalProcessor', ([], {}), '(**request.param)\n', (1966, 1983), False, 'from pipescaler.processors import AppleScriptExternalProcessor, AutomatorExternalProcessor, CropProcessor, ESRGANProcessor, ExpandProcessor, HeightToNormalProcessor, ModeProcessor, PngquantExternalProcessor, PotraceExternalProcessor, ResizeProcessor, SolidColorProcessor, TexconvExternalProcessor, ThresholdProcessor, WaifuExternalProcessor, XbrzProcessor\n'), ((2086, 2128), 'pipescaler.processors.PngquantExternalProcessor', 'PngquantExternalProcessor', ([], {}), '(**request.param)\n', (2111, 2128), False, 'from pipescaler.processors import AppleScriptExternalProcessor, AutomatorExternalProcessor, CropProcessor, ESRGANProcessor, ExpandProcessor, HeightToNormalProcessor, ModeProcessor, PngquantExternalProcessor, PotraceExternalProcessor, ResizeProcessor, SolidColorProcessor, TexconvExternalProcessor, ThresholdProcessor, WaifuExternalProcessor, XbrzProcessor\n'), ((2210, 2242), 'pipescaler.processors.ResizeProcessor', 'ResizeProcessor', ([], {}), '(**request.param)\n', (2225, 2242), False, 'from pipescaler.processors import AppleScriptExternalProcessor, AutomatorExternalProcessor, CropProcessor, ESRGANProcessor, ExpandProcessor, HeightToNormalProcessor, ModeProcessor, PngquantExternalProcessor, PotraceExternalProcessor, ResizeProcessor, SolidColorProcessor, TexconvExternalProcessor, ThresholdProcessor, WaifuExternalProcessor, XbrzProcessor\n'), ((2333, 2369), 'pipescaler.processors.SolidColorProcessor', 'SolidColorProcessor', ([], {}), '(**request.param)\n', (2352, 2369), False, 'from pipescaler.processors import AppleScriptExternalProcessor, AutomatorExternalProcessor, CropProcessor, ESRGANProcessor, ExpandProcessor, HeightToNormalProcessor, ModeProcessor, PngquantExternalProcessor, PotraceExternalProcessor, ResizeProcessor, SolidColorProcessor, TexconvExternalProcessor, ThresholdProcessor, WaifuExternalProcessor, XbrzProcessor\n'), ((2470, 2511), 'pipescaler.processors.TexconvExternalProcessor', 'TexconvExternalProcessor', ([], {}), '(**request.param)\n', (2494, 2511), False, 'from pipescaler.processors import AppleScriptExternalProcessor, AutomatorExternalProcessor, CropProcessor, ESRGANProcessor, ExpandProcessor, HeightToNormalProcessor, ModeProcessor, PngquantExternalProcessor, PotraceExternalProcessor, ResizeProcessor, SolidColorProcessor, TexconvExternalProcessor, ThresholdProcessor, WaifuExternalProcessor, XbrzProcessor\n'), ((2599, 2634), 'pipescaler.processors.ThresholdProcessor', 'ThresholdProcessor', ([], {}), '(**request.param)\n', (2617, 2634), False, 'from pipescaler.processors import AppleScriptExternalProcessor, AutomatorExternalProcessor, CropProcessor, ESRGANProcessor, ExpandProcessor, HeightToNormalProcessor, ModeProcessor, PngquantExternalProcessor, PotraceExternalProcessor, ResizeProcessor, SolidColorProcessor, TexconvExternalProcessor, ThresholdProcessor, WaifuExternalProcessor, XbrzProcessor\n'), ((2731, 2770), 'pipescaler.processors.WaifuExternalProcessor', 'WaifuExternalProcessor', ([], {}), '(**request.param)\n', (2753, 2770), False, 'from pipescaler.processors import AppleScriptExternalProcessor, AutomatorExternalProcessor, CropProcessor, ESRGANProcessor, ExpandProcessor, HeightToNormalProcessor, ModeProcessor, PngquantExternalProcessor, PotraceExternalProcessor, ResizeProcessor, SolidColorProcessor, TexconvExternalProcessor, ThresholdProcessor, WaifuExternalProcessor, XbrzProcessor\n'), ((2848, 2878), 'pipescaler.processors.XbrzProcessor', 'XbrzProcessor', ([], {}), '(**request.param)\n', (2861, 2878), False, 'from pipescaler.processors import AppleScriptExternalProcessor, AutomatorExternalProcessor, CropProcessor, ESRGANProcessor, ExpandProcessor, HeightToNormalProcessor, ModeProcessor, PngquantExternalProcessor, PotraceExternalProcessor, ResizeProcessor, SolidColorProcessor, TexconvExternalProcessor, ThresholdProcessor, WaifuExternalProcessor, XbrzProcessor\n'), ((3517, 3543), 'pipescaler.common.temporary_filename', 'temporary_filename', (['""".png"""'], {}), "('.png')\n", (3535, 3543), False, 'from pipescaler.common import temporary_filename\n'), ((4546, 4572), 'pipescaler.common.temporary_filename', 'temporary_filename', (['""".png"""'], {}), "('.png')\n", (4564, 4572), False, 'from pipescaler.common import temporary_filename\n'), ((5441, 5467), 'pipescaler.common.temporary_filename', 'temporary_filename', (['""".png"""'], {}), "('.png')\n", (5459, 5467), False, 'from pipescaler.common import temporary_filename\n'), ((7226, 7252), 'pipescaler.common.temporary_filename', 'temporary_filename', (['""".png"""'], {}), "('.png')\n", (7244, 7252), False, 'from pipescaler.common import temporary_filename\n'), ((8079, 8105), 'pipescaler.common.temporary_filename', 'temporary_filename', (['""".png"""'], {}), "('.png')\n", (8097, 8105), False, 'from pipescaler.common import temporary_filename\n'), ((9301, 9327), 'pipescaler.common.temporary_filename', 'temporary_filename', (['""".png"""'], {}), "('.png')\n", (9319, 9327), False, 'from pipescaler.common import temporary_filename\n'), ((10723, 10749), 'pipescaler.common.temporary_filename', 'temporary_filename', (['""".png"""'], {}), "('.png')\n", (10741, 10749), False, 'from pipescaler.common import temporary_filename\n'), ((11501, 11527), 'pipescaler.common.temporary_filename', 'temporary_filename', (['""".png"""'], {}), "('.png')\n", (11519, 11527), False, 'from pipescaler.common import temporary_filename\n'), ((12528, 12554), 'pipescaler.common.temporary_filename', 'temporary_filename', (['""".png"""'], {}), "('.png')\n", (12546, 12554), False, 'from pipescaler.common import temporary_filename\n'), ((13465, 13491), 'pipescaler.common.temporary_filename', 'temporary_filename', (['""".png"""'], {}), "('.png')\n", (13483, 13491), False, 'from pipescaler.common import temporary_filename\n'), ((14346, 14372), 'pipescaler.common.temporary_filename', 'temporary_filename', (['""".png"""'], {}), "('.png')\n", (14364, 14372), False, 'from pipescaler.common import temporary_filename\n'), ((15498, 15524), 'pipescaler.common.temporary_filename', 'temporary_filename', (['""".png"""'], {}), "('.png')\n", (15516, 15524), False, 'from pipescaler.common import temporary_filename\n'), ((16417, 16443), 'pipescaler.common.temporary_filename', 'temporary_filename', (['""".png"""'], {}), "('.png')\n", (16435, 16443), False, 'from pipescaler.common import temporary_filename\n'), ((18018, 18044), 'pipescaler.common.temporary_filename', 'temporary_filename', (['""".png"""'], {}), "('.png')\n", (18036, 18044), False, 'from pipescaler.common import temporary_filename\n'), ((18969, 18995), 'pipescaler.common.temporary_filename', 'temporary_filename', (['""".png"""'], {}), "('.png')\n", (18987, 18995), False, 'from pipescaler.common import temporary_filename\n'), ((3627, 3645), 'PIL.Image.open', 'Image.open', (['infile'], {}), '(infile)\n', (3637, 3645), False, 'from PIL import Image\n'), ((3662, 3681), 'PIL.Image.open', 'Image.open', (['outfile'], {}), '(outfile)\n', (3672, 3681), False, 'from PIL import Image\n'), ((3006, 3045), 'shared.xfail_if_platform', 'xfail_if_platform', (["{'Linux', 'Windows'}"], {}), "({'Linux', 'Windows'})\n", (3023, 3045), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((3170, 3209), 'shared.xfail_if_platform', 'xfail_if_platform', (["{'Linux', 'Windows'}"], {}), "({'Linux', 'Windows'})\n", (3187, 3209), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((4653, 4671), 'PIL.Image.open', 'Image.open', (['infile'], {}), '(infile)\n', (4663, 4671), False, 'from PIL import Image\n'), ((4688, 4707), 'PIL.Image.open', 'Image.open', (['outfile'], {}), '(outfile)\n', (4698, 4707), False, 'from PIL import Image\n'), ((4084, 4123), 'shared.xfail_if_platform', 'xfail_if_platform', (["{'Linux', 'Windows'}"], {}), "({'Linux', 'Windows'})\n", (4101, 4123), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((4229, 4268), 'shared.xfail_if_platform', 'xfail_if_platform', (["{'Linux', 'Windows'}"], {}), "({'Linux', 'Windows'})\n", (4246, 4268), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((5534, 5552), 'PIL.Image.open', 'Image.open', (['infile'], {}), '(infile)\n', (5544, 5552), False, 'from PIL import Image\n'), ((5569, 5588), 'PIL.Image.open', 'Image.open', (['outfile'], {}), '(outfile)\n', (5579, 5588), False, 'from PIL import Image\n'), ((7321, 7339), 'PIL.Image.open', 'Image.open', (['infile'], {}), '(infile)\n', (7331, 7339), False, 'from PIL import Image\n'), ((7356, 7375), 'PIL.Image.open', 'Image.open', (['outfile'], {}), '(outfile)\n', (7366, 7375), False, 'from PIL import Image\n'), ((5981, 5993), 'shared.skip_if_ci', 'skip_if_ci', ([], {}), '()\n', (5991, 5993), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((6068, 6080), 'shared.skip_if_ci', 'skip_if_ci', ([], {}), '()\n', (6078, 6080), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((6156, 6168), 'shared.skip_if_ci', 'skip_if_ci', ([], {}), '()\n', (6166, 6168), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((6268, 6280), 'shared.skip_if_ci', 'skip_if_ci', ([], {}), '()\n', (6278, 6280), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((6357, 6369), 'shared.skip_if_ci', 'skip_if_ci', ([], {}), '()\n', (6367, 6369), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((6446, 6458), 'shared.skip_if_ci', 'skip_if_ci', ([], {}), '()\n', (6456, 6458), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((8174, 8192), 'PIL.Image.open', 'Image.open', (['infile'], {}), '(infile)\n', (8184, 8192), False, 'from PIL import Image\n'), ((8209, 8228), 'PIL.Image.open', 'Image.open', (['outfile'], {}), '(outfile)\n', (8219, 8228), False, 'from PIL import Image\n'), ((9406, 9424), 'PIL.Image.open', 'Image.open', (['infile'], {}), '(infile)\n', (9416, 9424), False, 'from PIL import Image\n'), ((9441, 9460), 'PIL.Image.open', 'Image.open', (['outfile'], {}), '(outfile)\n', (9451, 9460), False, 'from PIL import Image\n'), ((9505, 9527), 'numpy.array', 'np.array', (['output_image'], {}), '(output_image)\n', (9513, 9527), True, 'import numpy as np\n'), ((9650, 9686), 'numpy.min', 'np.min', (['(output_datum[:, :, 2] >= 128)'], {}), '(output_datum[:, :, 2] >= 128)\n', (9656, 9686), True, 'import numpy as np\n'), ((8699, 8723), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (8721, 8723), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((8805, 8829), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (8827, 8829), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((8871, 8895), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (8893, 8895), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((8938, 8962), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (8960, 8962), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((9006, 9030), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (9028, 9030), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((9072, 9096), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (9094, 9096), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((10816, 10834), 'PIL.Image.open', 'Image.open', (['infile'], {}), '(infile)\n', (10826, 10834), False, 'from PIL import Image\n'), ((10851, 10870), 'PIL.Image.open', 'Image.open', (['outfile'], {}), '(outfile)\n', (10861, 10870), False, 'from PIL import Image\n'), ((11607, 11625), 'PIL.Image.open', 'Image.open', (['infile'], {}), '(infile)\n', (11617, 11625), False, 'from PIL import Image\n'), ((11642, 11661), 'PIL.Image.open', 'Image.open', (['outfile'], {}), '(outfile)\n', (11652, 11661), False, 'from PIL import Image\n'), ((12633, 12651), 'PIL.Image.open', 'Image.open', (['infile'], {}), '(infile)\n', (12643, 12651), False, 'from PIL import Image\n'), ((12668, 12687), 'PIL.Image.open', 'Image.open', (['outfile'], {}), '(outfile)\n', (12678, 12687), False, 'from PIL import Image\n'), ((12009, 12033), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (12031, 12033), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((12091, 12115), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (12113, 12115), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((12145, 12169), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (12167, 12169), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((12200, 12224), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (12222, 12224), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((12256, 12280), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (12278, 12280), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((12310, 12334), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (12332, 12334), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((13560, 13578), 'PIL.Image.open', 'Image.open', (['infile'], {}), '(infile)\n', (13570, 13578), False, 'from PIL import Image\n'), ((13595, 13614), 'PIL.Image.open', 'Image.open', (['outfile'], {}), '(outfile)\n', (13605, 13614), False, 'from PIL import Image\n'), ((14446, 14464), 'PIL.Image.open', 'Image.open', (['infile'], {}), '(infile)\n', (14456, 14464), False, 'from PIL import Image\n'), ((14481, 14500), 'PIL.Image.open', 'Image.open', (['outfile'], {}), '(outfile)\n', (14491, 14500), False, 'from PIL import Image\n'), ((15603, 15621), 'PIL.Image.open', 'Image.open', (['infile'], {}), '(infile)\n', (15613, 15621), False, 'from PIL import Image\n'), ((15638, 15657), 'PIL.Image.open', 'Image.open', (['outfile'], {}), '(outfile)\n', (15648, 15657), False, 'from PIL import Image\n'), ((14791, 14829), 'shared.xfail_if_platform', 'xfail_if_platform', (["{'Darwin', 'Linux'}"], {}), "({'Darwin', 'Linux'})\n", (14808, 14829), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((14857, 14895), 'shared.xfail_if_platform', 'xfail_if_platform', (["{'Darwin', 'Linux'}"], {}), "({'Darwin', 'Linux'})\n", (14874, 14895), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((14924, 14962), 'shared.xfail_if_platform', 'xfail_if_platform', (["{'Darwin', 'Linux'}"], {}), "({'Darwin', 'Linux'})\n", (14941, 14962), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((14992, 15030), 'shared.xfail_if_platform', 'xfail_if_platform', (["{'Darwin', 'Linux'}"], {}), "({'Darwin', 'Linux'})\n", (15009, 15030), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((15061, 15099), 'shared.xfail_if_platform', 'xfail_if_platform', (["{'Darwin', 'Linux'}"], {}), "({'Darwin', 'Linux'})\n", (15078, 15099), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((15128, 15166), 'shared.xfail_if_platform', 'xfail_if_platform', (["{'Darwin', 'Linux'}"], {}), "({'Darwin', 'Linux'})\n", (15145, 15166), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((15196, 15234), 'shared.xfail_if_platform', 'xfail_if_platform', (["{'Darwin', 'Linux'}"], {}), "({'Darwin', 'Linux'})\n", (15213, 15234), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((15265, 15303), 'shared.xfail_if_platform', 'xfail_if_platform', (["{'Darwin', 'Linux'}"], {}), "({'Darwin', 'Linux'})\n", (15282, 15303), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((16515, 16533), 'PIL.Image.open', 'Image.open', (['infile'], {}), '(infile)\n', (16525, 16533), False, 'from PIL import Image\n'), ((16550, 16569), 'PIL.Image.open', 'Image.open', (['outfile'], {}), '(outfile)\n', (16560, 16569), False, 'from PIL import Image\n'), ((16614, 16636), 'numpy.array', 'np.array', (['output_image'], {}), '(output_image)\n', (16622, 16636), True, 'import numpy as np\n'), ((15931, 15955), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (15953, 15955), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((16013, 16037), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (16035, 16037), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((16067, 16091), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (16089, 16091), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((16122, 16146), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (16144, 16146), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((16178, 16202), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (16200, 16202), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((16232, 16256), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (16254, 16256), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((18121, 18139), 'PIL.Image.open', 'Image.open', (['infile'], {}), '(infile)\n', (18131, 18139), False, 'from PIL import Image\n'), ((18156, 18175), 'PIL.Image.open', 'Image.open', (['outfile'], {}), '(outfile)\n', (18166, 18175), False, 'from PIL import Image\n'), ((16923, 16935), 'shared.skip_if_ci', 'skip_if_ci', ([], {}), '()\n', (16933, 16935), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((17005, 17017), 'shared.skip_if_ci', 'skip_if_ci', ([], {}), '()\n', (17015, 17017), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((17088, 17100), 'shared.skip_if_ci', 'skip_if_ci', ([], {}), '()\n', (17098, 17100), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((17173, 17185), 'shared.skip_if_ci', 'skip_if_ci', ([], {}), '()\n', (17183, 17185), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((17257, 17269), 'shared.skip_if_ci', 'skip_if_ci', ([], {}), '()\n', (17267, 17269), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((19062, 19080), 'PIL.Image.open', 'Image.open', (['infile'], {}), '(infile)\n', (19072, 19080), False, 'from PIL import Image\n'), ((19097, 19116), 'PIL.Image.open', 'Image.open', (['outfile'], {}), '(outfile)\n', (19107, 19116), False, 'from PIL import Image\n'), ((7433, 7466), 'shared.expected_output_mode', 'expected_output_mode', (['input_image'], {}), '(input_image)\n', (7453, 7466), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((6577, 6601), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (6599, 6601), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((6711, 6735), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (6733, 6735), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((6846, 6870), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (6868, 6870), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((6983, 7007), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (7005, 7007), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((11819, 11835), 'os.path.getsize', 'getsize', (['outfile'], {}), '(outfile)\n', (11826, 11835), False, 'from os.path import getsize\n'), ((11839, 11854), 'os.path.getsize', 'getsize', (['infile'], {}), '(infile)\n', (11846, 11854), False, 'from os.path import getsize\n'), ((13672, 13705), 'shared.expected_output_mode', 'expected_output_mode', (['input_image'], {}), '(input_image)\n', (13692, 13705), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((14558, 14591), 'shared.expected_output_mode', 'expected_output_mode', (['input_image'], {}), '(input_image)\n', (14578, 14591), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((18233, 18266), 'shared.expected_output_mode', 'expected_output_mode', (['input_image'], {}), '(input_image)\n', (18253, 18266), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((17352, 17376), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (17374, 17376), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((17481, 17505), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (17503, 17505), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((17611, 17635), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (17633, 17635), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((17743, 17767), 'shared.xfail_unsupported_mode', 'xfail_unsupported_mode', ([], {}), '()\n', (17765, 17767), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((19174, 19207), 'shared.expected_output_mode', 'expected_output_mode', (['input_image'], {}), '(input_image)\n', (19194, 19207), False, 'from shared import esrgan_models, expected_output_mode, infiles, skip_if_ci, xfail_if_platform, xfail_unsupported_mode\n'), ((16757, 16810), 'numpy.logical_or', 'np.logical_or', (['(output_datum == 0)', '(output_datum == 255)'], {}), '(output_datum == 0, output_datum == 255)\n', (16770, 16810), True, 'import numpy as np\n')]
#!/usr/bin/env python # # A noddy example to exercise most of the features in the "eb" module. # Demonstrates how I recommend filling in the parameter vector - this # way internal rearrangements of the vector as the model evolves won't # break all of your scripts. # import numpy import eb import matplotlib.pyplot as plt # Allocate main parameter vector, init to zero. parm = numpy.zeros(eb.NPAR, dtype=numpy.double) # These are the basic parameters of the model. parm[eb.PAR_J] = 0.799853 # J surface brightness ratio parm[eb.PAR_RASUM] = 0.015548 # (R_1+R_2)/a parm[eb.PAR_RR] = 0.785989 # R_2/R_1 parm[eb.PAR_COSI] = 0.004645 # cos i # Mass ratio is used only for computing ellipsoidal variation and # light travel time. Set to zero to disable ellipsoidal. parm[eb.PAR_Q] = 0.6904 # Light travel time coefficient. ktot = 55.602793 # K_1+K_2 in km/s cltt = 1000*ktot / eb.LIGHT # Set to zero if you don't need light travel correction (it's fairly slow # and can often be neglected). parm[eb.PAR_CLTT] = cltt # ktot / c # Radiative properties of star 1. parm[eb.PAR_LDLIN1] = 0.2094 # u1 star 1 parm[eb.PAR_LDNON1] = 0.6043 # u2 star 1 parm[eb.PAR_GD1] = 0.32 # gravity darkening, std. value parm[eb.PAR_REFL1] = 0.4 # albedo, std. value # Spot model. Assumes spots on star 1 and not eclipsed. parm[eb.PAR_ROT1] = 0.636539 # rotation parameter (1 = sync.) parm[eb.PAR_FSPOT1] = 0.0 # fraction of spots eclipsed parm[eb.PAR_OOE1O] = 0.0 # base spottedness out of eclipse parm[eb.PAR_OOE11A] = 0.006928 # *sin parm[eb.PAR_OOE11B] = 0.005088 # *cos # PAR_OOE12* are sin(2*rot*omega) on star 1, # PAR_OOE2* are for spots on star 2. # Assume star 2 is the same as star 1 but without spots. parm[eb.PAR_LDLIN2] = parm[eb.PAR_LDLIN1] parm[eb.PAR_LDNON2] = parm[eb.PAR_LDNON1] parm[eb.PAR_GD2] = parm[eb.PAR_GD1] parm[eb.PAR_REFL2] = parm[eb.PAR_REFL1] # Orbital parameters. parm[eb.PAR_ECOSW] = 0.152408 # ecosw parm[eb.PAR_ESINW] = 0.182317 # esinw parm[eb.PAR_P] = 41.032363 # period parm[eb.PAR_T0] = 2455290.046183 # T0 (epoch of primary eclipse) # OTHER NOTES: # # To do standard transit models (a'la Mandel & Agol), # set J=0, q=0, cltt=0, albedo=0. # This makes the secondary dark, and disables ellipsoidal and reflection. # # The strange parameterization of radial velocity is to retain the # flexibility to be able to model just light curves, SB1s, or SB2s. # # For improved precision, it's best to subtract most of the "DC offset" # from T0 and the time array (e.g. take off the nominal value of T0 or # the midtime of the data array) and add it back on at the end when # printing parm[eb.PAR_T0] and vder[eb.PAR_TSEC]. Likewise the period # can cause scaling problems in minimization routines (because it has # to be so much more precise than the other parameters), and may need # similar treatment. # Simple (but not astronomer friendly) dump of model parameters. print("Model parameters:") for name, value, unit in zip(eb.parnames, parm, eb.parunits): print("{0:<10} {1:14.6f} {2}".format(name, value, unit)) # Derived parameters. vder = eb.getvder(parm, -61.070553, ktot) print("Derived parameters:") for name, value, unit in zip(eb.dernames, vder, eb.derunits): print("{0:<10} {1:14.6f} {2}".format(name, value, unit)) # Phases of contact points. (ps, pe, ss, se) = eb.phicont(parm) if ps > 0.5: ps -= 1.0 # Use max(duration) for sampling range. pdur=pe-ps sdur=se-ss if pdur > sdur: mdur = pdur else: mdur = sdur # ...centered on the average of start and end points. pa=0.5*(ps+pe) sa=0.5*(ss+se) # Generate phase array: primary, secondary, and out of eclipse # in leading dimension. phi = numpy.empty([3, 1000], dtype=numpy.double) phi[0] = numpy.linspace(pa-mdur, pa+mdur, phi.shape[1]) phi[1] = numpy.linspace(sa-mdur, sa+mdur, phi.shape[1]) phi[2] = numpy.linspace(-0.25, 1.25, phi.shape[1]) # All magnitudes. typ = numpy.empty_like(phi, dtype=numpy.uint8) typ.fill(eb.OBS_MAG) # These calls both do the same thing. First, phase. y = eb.model(parm, phi, typ, eb.FLAG_PHI) # Alternative using time. #t = parm[eb.PAR_T0] + phi*parm[eb.PAR_P] #y = eb.model(parm, t, typ) # Plot eclipses in top 2 panels. Manual y range, forced same on # both plots. x range is already guaranteed to be the same above. ymin = y.min() ymax = y.max() yrange = ymax - ymin plt.subplot(2, 2, 1) plt.ylim(ymax+0.05*yrange, ymin-0.05*yrange) plt.plot(phi[0], y[0]) plt.plot([ps, ps], [ymax, ymin], linestyle='--') plt.plot([pe, pe], [ymax, ymin], linestyle='--') plt.subplot(2, 2, 2) plt.ylim(ymax+0.05*yrange, ymin-0.05*yrange) plt.plot(phi[1], y[1]) plt.plot([ss, ss], [ymax, ymin], linestyle='--') plt.plot([se, se], [ymax, ymin], linestyle='--') # Out of eclipse plot across the bottom with 5*sigma clipping, robust # MAD estimator. median = numpy.median(y[2]) adiff = numpy.absolute(y[2]-median) sigma = 1.48*numpy.median(adiff) tmp = numpy.compress(adiff < 5*sigma, y[2]) ymin = tmp.min() ymax = tmp.max() yrange = ymax - ymin plt.subplot(2, 1, 2) plt.ylim(ymax+0.05*yrange, ymin-0.05*yrange) plt.plot(phi[2], y[2]) plt.show()
[ "matplotlib.pyplot.subplot", "numpy.absolute", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "eb.phicont", "matplotlib.pyplot.ylim", "numpy.empty", "numpy.median", "numpy.compress", "numpy.zeros", "numpy.empty_like", "numpy.linspace", "eb.getvder", "eb.model" ]
[((379, 419), 'numpy.zeros', 'numpy.zeros', (['eb.NPAR'], {'dtype': 'numpy.double'}), '(eb.NPAR, dtype=numpy.double)\n', (390, 419), False, 'import numpy\n'), ((3170, 3204), 'eb.getvder', 'eb.getvder', (['parm', '(-61.070553)', 'ktot'], {}), '(parm, -61.070553, ktot)\n', (3180, 3204), False, 'import eb\n'), ((3405, 3421), 'eb.phicont', 'eb.phicont', (['parm'], {}), '(parm)\n', (3415, 3421), False, 'import eb\n'), ((3739, 3781), 'numpy.empty', 'numpy.empty', (['[3, 1000]'], {'dtype': 'numpy.double'}), '([3, 1000], dtype=numpy.double)\n', (3750, 3781), False, 'import numpy\n'), ((3791, 3841), 'numpy.linspace', 'numpy.linspace', (['(pa - mdur)', '(pa + mdur)', 'phi.shape[1]'], {}), '(pa - mdur, pa + mdur, phi.shape[1])\n', (3805, 3841), False, 'import numpy\n'), ((3847, 3897), 'numpy.linspace', 'numpy.linspace', (['(sa - mdur)', '(sa + mdur)', 'phi.shape[1]'], {}), '(sa - mdur, sa + mdur, phi.shape[1])\n', (3861, 3897), False, 'import numpy\n'), ((3903, 3944), 'numpy.linspace', 'numpy.linspace', (['(-0.25)', '(1.25)', 'phi.shape[1]'], {}), '(-0.25, 1.25, phi.shape[1])\n', (3917, 3944), False, 'import numpy\n'), ((3970, 4010), 'numpy.empty_like', 'numpy.empty_like', (['phi'], {'dtype': 'numpy.uint8'}), '(phi, dtype=numpy.uint8)\n', (3986, 4010), False, 'import numpy\n'), ((4090, 4127), 'eb.model', 'eb.model', (['parm', 'phi', 'typ', 'eb.FLAG_PHI'], {}), '(parm, phi, typ, eb.FLAG_PHI)\n', (4098, 4127), False, 'import eb\n'), ((4409, 4429), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(1)'], {}), '(2, 2, 1)\n', (4420, 4429), True, 'import matplotlib.pyplot as plt\n'), ((4430, 4482), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(ymax + 0.05 * yrange)', '(ymin - 0.05 * yrange)'], {}), '(ymax + 0.05 * yrange, ymin - 0.05 * yrange)\n', (4438, 4482), True, 'import matplotlib.pyplot as plt\n'), ((4475, 4497), 'matplotlib.pyplot.plot', 'plt.plot', (['phi[0]', 'y[0]'], {}), '(phi[0], y[0])\n', (4483, 4497), True, 'import matplotlib.pyplot as plt\n'), ((4499, 4547), 'matplotlib.pyplot.plot', 'plt.plot', (['[ps, ps]', '[ymax, ymin]'], {'linestyle': '"""--"""'}), "([ps, ps], [ymax, ymin], linestyle='--')\n", (4507, 4547), True, 'import matplotlib.pyplot as plt\n'), ((4548, 4596), 'matplotlib.pyplot.plot', 'plt.plot', (['[pe, pe]', '[ymax, ymin]'], {'linestyle': '"""--"""'}), "([pe, pe], [ymax, ymin], linestyle='--')\n", (4556, 4596), True, 'import matplotlib.pyplot as plt\n'), ((4598, 4618), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(2)'], {}), '(2, 2, 2)\n', (4609, 4618), True, 'import matplotlib.pyplot as plt\n'), ((4619, 4671), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(ymax + 0.05 * yrange)', '(ymin - 0.05 * yrange)'], {}), '(ymax + 0.05 * yrange, ymin - 0.05 * yrange)\n', (4627, 4671), True, 'import matplotlib.pyplot as plt\n'), ((4664, 4686), 'matplotlib.pyplot.plot', 'plt.plot', (['phi[1]', 'y[1]'], {}), '(phi[1], y[1])\n', (4672, 4686), True, 'import matplotlib.pyplot as plt\n'), ((4688, 4736), 'matplotlib.pyplot.plot', 'plt.plot', (['[ss, ss]', '[ymax, ymin]'], {'linestyle': '"""--"""'}), "([ss, ss], [ymax, ymin], linestyle='--')\n", (4696, 4736), True, 'import matplotlib.pyplot as plt\n'), ((4737, 4785), 'matplotlib.pyplot.plot', 'plt.plot', (['[se, se]', '[ymax, ymin]'], {'linestyle': '"""--"""'}), "([se, se], [ymax, ymin], linestyle='--')\n", (4745, 4785), True, 'import matplotlib.pyplot as plt\n'), ((4883, 4901), 'numpy.median', 'numpy.median', (['y[2]'], {}), '(y[2])\n', (4895, 4901), False, 'import numpy\n'), ((4910, 4939), 'numpy.absolute', 'numpy.absolute', (['(y[2] - median)'], {}), '(y[2] - median)\n', (4924, 4939), False, 'import numpy\n'), ((4977, 5016), 'numpy.compress', 'numpy.compress', (['(adiff < 5 * sigma)', 'y[2]'], {}), '(adiff < 5 * sigma, y[2])\n', (4991, 5016), False, 'import numpy\n'), ((5072, 5092), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(1)', '(2)'], {}), '(2, 1, 2)\n', (5083, 5092), True, 'import matplotlib.pyplot as plt\n'), ((5093, 5145), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(ymax + 0.05 * yrange)', '(ymin - 0.05 * yrange)'], {}), '(ymax + 0.05 * yrange, ymin - 0.05 * yrange)\n', (5101, 5145), True, 'import matplotlib.pyplot as plt\n'), ((5138, 5160), 'matplotlib.pyplot.plot', 'plt.plot', (['phi[2]', 'y[2]'], {}), '(phi[2], y[2])\n', (5146, 5160), True, 'import matplotlib.pyplot as plt\n'), ((5162, 5172), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5170, 5172), True, 'import matplotlib.pyplot as plt\n'), ((4951, 4970), 'numpy.median', 'numpy.median', (['adiff'], {}), '(adiff)\n', (4963, 4970), False, 'import numpy\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 15 23:00:51 2020 @author: zf """ # import pycocotools.coco as coco from pycocotools.coco import COCO import os import shutil from tqdm import tqdm import skimage.io as io import matplotlib.pyplot as plt import cv2 from PIL import Image, ImageDraw import numpy as np import sys sys.path.append('/home/zf/0tools') from py_cpu_nms import py_cpu_nms, py_cpu_label_nms from r_nms_cpu import nms_rotate_cpu from DataFunction import write_rotate_xml from All_Class_NAME_LABEL import NAME_LABEL_MAP_USnavy_20,NAME_LONG_MAP_USnavy,NAME_STD_MAP_USnavy,LABEL_NAME_MAP_USnavy_20 from Rotatexml2DotaTxT import eval_rotatexml def get_label_name_map(NAME_LABEL_MAP): reverse_dict = {} for name, label in NAME_LABEL_MAP.items(): reverse_dict[label] = name return reverse_dict def id2name(coco): classes=dict() for cls in coco.dataset['categories']: classes[cls['id']]=cls['name'] return classes def show_rotate_box(src_img,rotateboxes,name=None): cx, cy, w,h,Angle=rotateboxes[:,0], rotateboxes[:,1], rotateboxes[:,2], rotateboxes[:,3], rotateboxes[:,4] p_rotate=[] for i in range(rotateboxes.shape[0]): RotateMatrix=np.array([ [np.cos(Angle[i]),-np.sin(Angle[i])], [np.sin(Angle[i]),np.cos(Angle[i])]]) rhead,r1,r2,r3,r4=np.transpose([0,-h/2]),np.transpose([-w[i]/2,-h[i]/2]),np.transpose([w[i]/2,-h[i]/2]),np.transpose([w[i]/2,h[i]/2]),np.transpose([-w[i]/2,h[i]/2]) rhead=np.transpose(np.dot(RotateMatrix, rhead))+[cx[i],cy[i]] p1=np.transpose(np.dot(RotateMatrix, r1))+[cx[i],cy[i]] p2=np.transpose(np.dot(RotateMatrix, r2))+[cx[i],cy[i]] p3=np.transpose(np.dot(RotateMatrix, r3))+[cx[i],cy[i]] p4=np.transpose(np.dot(RotateMatrix, r4))+[cx[i],cy[i]] p_rotate_=np.int32(np.vstack((p1,p2,p3,p4))) p_rotate.append(p_rotate_) cv2.polylines(src_img,np.array(p_rotate),True,(0,255,255)) cv2.imshow('rotate_box',src_img.astype('uint8')) cv2.waitKey(0) cv2.destroyAllWindows() def result2rotatebox_cvbox(coco,dataset,img,classes,cls_id,show=True): annIds = coco.getAnnIds(imgIds=img['id'], catIds=cls_id, iscrowd=None) anns = coco.loadAnns(annIds) result_=np.zeros((0,7)) for ann in anns: class_name=classes[ann['category_id']] bbox=ann['bbox'] xmin = int(bbox[0]) ymin = int(bbox[1]) xmax = int(bbox[2] + bbox[0]) ymax = int(bbox[3] + bbox[1]) ang=bbox[4] score=ann['score'] if score>score_threshold: res_array=np.array([xmin,ymin,xmax,ymax,ang,score,NAME_LABEL_MAP[class_name]]).T result_=np.vstack((result_,res_array)) result = result_ cx, cy, w,h=(result[:,0]+result[:,2])/2 ,(result[:,1]+result[:,3])/2 ,(result[:,2]-result[:,0]) ,(result[:,3]-result[:,1]) ang=result[:,4]/180*np.pi center=np.vstack((cx,cy)).T#中心坐标 rotateboxes=np.vstack((cx, cy, w,h,ang,result[:,6],result[:,5])).T p_cv=[] cvboxes=np.zeros_like(rotateboxes) for i in range(rotateboxes.shape[0]): angle_cv=rotateboxes[i,4]/np.pi*180 if angle_cv>0: angle_cv=angle_cv cv_h=rotateboxes[i,3] cv_w=rotateboxes[i,2] else: angle_cv=angle_cv+90 cv_h=rotateboxes[i,2] cv_w=rotateboxes[i,3] cvboxes[i,:]=[rotateboxes[i,0],rotateboxes[i,1],cv_w,cv_h,angle_cv,result[i,6],result[i,5]] return cvboxes,rotateboxes def merge_json2rotatexml(gtFile, annFile, merge_xmldir, NAME_LABEL_MAP, NAME_LONG_MAP, NAME_STD_MAP, std_scale, score_threshold): classes_names = [] for name, label in NAME_LABEL_MAP.items(): classes_names.append(name) if not os.path.exists(merge_xmldir): os.mkdir(merge_xmldir) LABEl_NAME_MAP = get_label_name_map(NAME_LABEL_MAP) #COCO API for initializing annotated data coco = COCO(gtFile) # coco_o=COCO(gtFile) coco_res=coco.loadRes(annFile) #show all classes in coco classes = id2name(coco) print(classes) classes_ids = coco.getCatIds(catNms=classes_names) print(classes_ids) #Get ID number of this class img_ids=coco.getImgIds() print('len of dataset:{}'.format(len(img_ids))) # imgIds=img_ids[0:10] img_name_ori='' result=np.zeros((0,8)) name_det={} for imgId in tqdm(img_ids): img = coco_res.loadImgs(imgId)[0] # Img_fullname='%s/%s/%s'%(dataDir,dataset,img['file_name']) filename = img['file_name'] str_num=filename.replace('.jpg','').strip().split('__') img_name=str_num[0] scale=np.float(str_num[1]) ww_=np.int(str_num[2]) hh_=np.int(str_num[3]) cvboxes,rotateboxes=result2rotatebox_cvbox(coco_res, 'val2017', img, classes,classes_ids,show=True) xml_dir='/home/zf/CenterNet/exp/ctdet/CenR_usnavy512_dla_2x/rotatexml' write_rotate_xml(xml_dir, img["file_name"], [1024, 1024, 3], 0.5, 'USnavy', rotateboxes, LABEl_NAME_MAP, rotateboxes[:,6]) #size,gsd,imagesource # img_dir='/home/zf/CenterNet/data/coco/val2017' # src_img=cv2.imread(os.path.join(img_dir,img["file_name"])) # show_rotate_box(src_img,rotateboxes) # result_[:, 0:4]=(result_[:, 0:4]+ww_)/scale # if not img_name in name_det : # name_det[img_name]= result_ # else: # name_det[img_name]= np.vstack((name_det[img_name],result_)) # # # # #将所有检测结果综合起来 #正框mns # for img_name, result in name_det.items(): # # if std_scale==0: # # inx = py_cpu_nms(dets=np.array(result, np.float32),thresh=nms_threshold,max_output_size=500) # # result=result[inx] # # else: # # inx ,scores= py_cpu_label_nms(dets=np.array(result, np.float32),thresh=nms_threshold,max_output_size=500, # # LABEL_NAME_MAP=LABEL_NAME_MAP_USnavy_20, # # NAME_LONG_MAP=NAME_LONG_MAP_USnavy,std_scale=std_scale) # # result=result[inx] # # result[:, 4]=scores[inx] # cvrboxes,rotateboxes=result2rotatebox_cvbox(img,result) # #斜框NMS # if cvrboxes.size>0: # keep = nms_rotate_cpu(cvrboxes,cvrboxes[:,6],rnms_threshold, 200) #这里可以改 # rotateboxes=rotateboxes[keep] # # #去掉过小的目标 # # keep=[] # # for i in range(rotateboxes.shape[0]): # # box=rotateboxes[i,:] # # actual_long=box[3]*scale # # standad_long=NAME_LONG_MAP[LABEl_NAME_MAP[box[5]]] # # STD_long=NAME_STD_MAP[LABEl_NAME_MAP[box[5]]] # # if np.abs(actual_long-standad_long)/standad_long < STD_long *1.2 and box[2]>16: # # keep.append(i) # # else: # # print('{} hh:{} ww:{}'.format(img_name,hh_,ww_)) # # print('{} th label {} is wrong,long is {} normal long is {} width is {}'.format(i+1,LABEl_NAME_MAP[box[5]],actual_long,standad_long,box[3])) # # rotateboxes=rotateboxes[keep] # #保存检测结果 为比赛格式 # # image_dir,image_name=os.path.split(img_path) # # gt_box=rotateboxes[:,0:5] # # label=rotateboxes[:,6] # write_rotate_xml(merge_xmldir, '{}.jpg'.format(img_name), # [1024, 1024, 3], 0.5, 'USnavy', rotateboxes, # LABEl_NAME_MAP, rotateboxes[:, # 6]) #size,gsd,imagesource if __name__ == '__main__': #Store annotations and train2014/val2014/... in this folder annFile = '/home/zf/CenterNet/exp/ctdet/CenR_usnavy512_dla_2x/results.json' gtFile='/home/zf/Dataset/US_Navy_train_square/annotations/person_keypoints_val2017.json' #the path you want to save your results for coco to voc merge_xmldir = '/home/zf/Dataset/USnavy_test_gt/CenR_DLA34' txt_dir_h = '/media/zf/E/Dataset/US_Navy_train_square/eval/0/' annopath = '/media/zf/E/Dataset/US_Navy_train_square/eval/GT20_TxT/' #GT_angle0_TxT#GT20_TxT nms_threshold=0.9#0.8 rnms_threshold=0.15#0.1 score_threshold=0.1 std_scale=0.4 score_threshold_2=0.05 NAME_LABEL_MAP = NAME_LABEL_MAP_USnavy_20 NAME_LONG_MAP = NAME_LONG_MAP_USnavy NAME_STD_MAP = NAME_STD_MAP_USnavy merge_json2rotatexml(gtFile,annFile, merge_xmldir, NAME_LABEL_MAP, NAME_LONG_MAP, NAME_STD_MAP, std_scale, score_threshold) eval_rotatexml(merge_xmldir, txt_dir_h, annopath, NAME_LABEL_MAP=NAME_LABEL_MAP, file_ext='.xml', flag='test')
[ "os.mkdir", "DataFunction.write_rotate_xml", "numpy.sin", "sys.path.append", "numpy.zeros_like", "os.path.exists", "numpy.transpose", "numpy.int", "cv2.destroyAllWindows", "tqdm.tqdm", "Rotatexml2DotaTxT.eval_rotatexml", "cv2.waitKey", "numpy.float", "numpy.cos", "numpy.dot", "numpy.vstack", "numpy.zeros", "pycocotools.coco.COCO", "numpy.array" ]
[((348, 382), 'sys.path.append', 'sys.path.append', (['"""/home/zf/0tools"""'], {}), "('/home/zf/0tools')\n", (363, 382), False, 'import sys\n'), ((2090, 2104), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (2101, 2104), False, 'import cv2\n'), ((2109, 2132), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (2130, 2132), False, 'import cv2\n'), ((2328, 2344), 'numpy.zeros', 'np.zeros', (['(0, 7)'], {}), '((0, 7))\n', (2336, 2344), True, 'import numpy as np\n'), ((3107, 3133), 'numpy.zeros_like', 'np.zeros_like', (['rotateboxes'], {}), '(rotateboxes)\n', (3120, 3133), True, 'import numpy as np\n'), ((4059, 4071), 'pycocotools.coco.COCO', 'COCO', (['gtFile'], {}), '(gtFile)\n', (4063, 4071), False, 'from pycocotools.coco import COCO\n'), ((4460, 4476), 'numpy.zeros', 'np.zeros', (['(0, 8)'], {}), '((0, 8))\n', (4468, 4476), True, 'import numpy as np\n'), ((4509, 4522), 'tqdm.tqdm', 'tqdm', (['img_ids'], {}), '(img_ids)\n', (4513, 4522), False, 'from tqdm import tqdm\n'), ((8632, 8747), 'Rotatexml2DotaTxT.eval_rotatexml', 'eval_rotatexml', (['merge_xmldir', 'txt_dir_h', 'annopath'], {'NAME_LABEL_MAP': 'NAME_LABEL_MAP', 'file_ext': '""".xml"""', 'flag': '"""test"""'}), "(merge_xmldir, txt_dir_h, annopath, NAME_LABEL_MAP=\n NAME_LABEL_MAP, file_ext='.xml', flag='test')\n", (8646, 8747), False, 'from Rotatexml2DotaTxT import eval_rotatexml\n'), ((1996, 2014), 'numpy.array', 'np.array', (['p_rotate'], {}), '(p_rotate)\n', (2004, 2014), True, 'import numpy as np\n'), ((2986, 3005), 'numpy.vstack', 'np.vstack', (['(cx, cy)'], {}), '((cx, cy))\n', (2995, 3005), True, 'import numpy as np\n'), ((3028, 3086), 'numpy.vstack', 'np.vstack', (['(cx, cy, w, h, ang, result[:, 6], result[:, 5])'], {}), '((cx, cy, w, h, ang, result[:, 6], result[:, 5]))\n', (3037, 3086), True, 'import numpy as np\n'), ((3885, 3913), 'os.path.exists', 'os.path.exists', (['merge_xmldir'], {}), '(merge_xmldir)\n', (3899, 3913), False, 'import os\n'), ((3923, 3945), 'os.mkdir', 'os.mkdir', (['merge_xmldir'], {}), '(merge_xmldir)\n', (3931, 3945), False, 'import os\n'), ((4777, 4797), 'numpy.float', 'np.float', (['str_num[1]'], {}), '(str_num[1])\n', (4785, 4797), True, 'import numpy as np\n'), ((4810, 4828), 'numpy.int', 'np.int', (['str_num[2]'], {}), '(str_num[2])\n', (4816, 4828), True, 'import numpy as np\n'), ((4841, 4859), 'numpy.int', 'np.int', (['str_num[3]'], {}), '(str_num[3])\n', (4847, 4859), True, 'import numpy as np\n'), ((5055, 5182), 'DataFunction.write_rotate_xml', 'write_rotate_xml', (['xml_dir', "img['file_name']", '[1024, 1024, 3]', '(0.5)', '"""USnavy"""', 'rotateboxes', 'LABEl_NAME_MAP', 'rotateboxes[:, 6]'], {}), "(xml_dir, img['file_name'], [1024, 1024, 3], 0.5, 'USnavy',\n rotateboxes, LABEl_NAME_MAP, rotateboxes[:, 6])\n", (5071, 5182), False, 'from DataFunction import write_rotate_xml\n'), ((1409, 1434), 'numpy.transpose', 'np.transpose', (['[0, -h / 2]'], {}), '([0, -h / 2])\n', (1421, 1434), True, 'import numpy as np\n'), ((1432, 1468), 'numpy.transpose', 'np.transpose', (['[-w[i] / 2, -h[i] / 2]'], {}), '([-w[i] / 2, -h[i] / 2])\n', (1444, 1468), True, 'import numpy as np\n'), ((1464, 1499), 'numpy.transpose', 'np.transpose', (['[w[i] / 2, -h[i] / 2]'], {}), '([w[i] / 2, -h[i] / 2])\n', (1476, 1499), True, 'import numpy as np\n'), ((1495, 1529), 'numpy.transpose', 'np.transpose', (['[w[i] / 2, h[i] / 2]'], {}), '([w[i] / 2, h[i] / 2])\n', (1507, 1529), True, 'import numpy as np\n'), ((1525, 1560), 'numpy.transpose', 'np.transpose', (['[-w[i] / 2, h[i] / 2]'], {}), '([-w[i] / 2, h[i] / 2])\n', (1537, 1560), True, 'import numpy as np\n'), ((1909, 1936), 'numpy.vstack', 'np.vstack', (['(p1, p2, p3, p4)'], {}), '((p1, p2, p3, p4))\n', (1918, 1936), True, 'import numpy as np\n'), ((2763, 2794), 'numpy.vstack', 'np.vstack', (['(result_, res_array)'], {}), '((result_, res_array))\n', (2772, 2794), True, 'import numpy as np\n'), ((1583, 1610), 'numpy.dot', 'np.dot', (['RotateMatrix', 'rhead'], {}), '(RotateMatrix, rhead)\n', (1589, 1610), True, 'import numpy as np\n'), ((1650, 1674), 'numpy.dot', 'np.dot', (['RotateMatrix', 'r1'], {}), '(RotateMatrix, r1)\n', (1656, 1674), True, 'import numpy as np\n'), ((1714, 1738), 'numpy.dot', 'np.dot', (['RotateMatrix', 'r2'], {}), '(RotateMatrix, r2)\n', (1720, 1738), True, 'import numpy as np\n'), ((1778, 1802), 'numpy.dot', 'np.dot', (['RotateMatrix', 'r3'], {}), '(RotateMatrix, r3)\n', (1784, 1802), True, 'import numpy as np\n'), ((1842, 1866), 'numpy.dot', 'np.dot', (['RotateMatrix', 'r4'], {}), '(RotateMatrix, r4)\n', (1848, 1866), True, 'import numpy as np\n'), ((2672, 2746), 'numpy.array', 'np.array', (['[xmin, ymin, xmax, ymax, ang, score, NAME_LABEL_MAP[class_name]]'], {}), '([xmin, ymin, xmax, ymax, ang, score, NAME_LABEL_MAP[class_name]])\n', (2680, 2746), True, 'import numpy as np\n'), ((1278, 1294), 'numpy.cos', 'np.cos', (['Angle[i]'], {}), '(Angle[i])\n', (1284, 1294), True, 'import numpy as np\n'), ((1346, 1362), 'numpy.sin', 'np.sin', (['Angle[i]'], {}), '(Angle[i])\n', (1352, 1362), True, 'import numpy as np\n'), ((1363, 1379), 'numpy.cos', 'np.cos', (['Angle[i]'], {}), '(Angle[i])\n', (1369, 1379), True, 'import numpy as np\n'), ((1296, 1312), 'numpy.sin', 'np.sin', (['Angle[i]'], {}), '(Angle[i])\n', (1302, 1312), True, 'import numpy as np\n')]
#!/usr/bin/env python # coding: utf-8 import sys sys.path.append('../../') import os import numpy as np import torch import scipy as sc import dill from core.dynamics import RoboticDynamics from koopman_core.util import run_experiment, evaluate_ol_pred from koopman_core.dynamics import BilinearLiftedDynamics from koopman_core.learning import KoopDnn, KoopmanNetCtrl from ray import tune from ray.tune.suggest.bohb import TuneBOHB from ray.tune.schedulers import HyperBandForBOHB, ASHAScheduler import matplotlib.pyplot as plt class FiniteDimKoopSys(RoboticDynamics): def __init__(self, lambd, mu, c): RoboticDynamics.__init__(self, 2, 2) self.params = lambd, mu, c def D(self, q): return np.array([[1, 0], [0, (q[0] + 1) ** (-1)]]) def C(self, q, q_dot): labmd, mu, c = self.params return -np.array([[lambd, 0], [(q[0] + 1) ** (-1) * (2 * lambd - mu) * c * q_dot[0], (q[0] + 1) ** (-1) * mu]]) def G(self, q): return np.array([0, 0]) def B(self, q): return np.array([[1, 0], [0, 1]]) # Define system and system linearization: sys_name = 'bilinearizable_sys' n, m = 4, 2 lambd, mu, c = .3, .2, -.5 system = FiniteDimKoopSys(lambd, mu, c) A_lin = np.array([[0, 0, 1, 0], [0, 0, 0, 1], [0, 0, lambd, 0], [0, 0, 0, mu]]) B_lin = np.array([[0, 0], [0, 0], [1, 0], [0, 1]]) # Define LQR controller for data collection: q_dc, r_dc = 5e2, 1 # State and actuation penalty values, data collection Q_dc = q_dc * np.identity(n) # State penalty matrix, data collection R_dc = r_dc*np.identity(m) # Actuation penalty matrix, data collection P_dc = sc.linalg.solve_continuous_are(A_lin, B_lin, Q_dc, R_dc) # Algebraic Ricatti equation solution, data collection K_dc = np.linalg.inv(R_dc)@B_lin.T@P_dc # LQR feedback gain matrix, data collection K_dc_p = K_dc[:,:int(n/2)] # Proportional control gains, data collection K_dc_d = K_dc[:,int(n/2):] # Derivative control gains, data collection # Data collection parameters: collect_data = True test_frac = 0.2 val_frac = 0.2 dt = 1.0e-2 # Time step length traj_length_dc = 2. # Trajectory length, data collection n_pred_dc = int(traj_length_dc/dt) # Number of time steps, data collection t_eval = dt * np.arange(n_pred_dc + 1) # Simulation time points n_traj_train = 250 # Number of trajectories to execute, data collection n_traj_test = 100 # Number of trajectories to execute, data collection noise_var = 5. # Exploration noise to perturb controller, data collection x0_max = np.array([1., 1., 1., 1.]) # Initial value limits directory = os.path.abspath("working_files/bkeedmd/") # Path to save learned models # Model configuration parameters: net_params = {} net_params['state_dim'] = n net_params['ctrl_dim'] = m net_params['first_obs_const'] = True net_params['override_kinematics'] = True net_params['dt'] = dt net_params['data_dir'] = directory + '/data' net_params['n_multistep'] = 1 # DNN architecture parameters: net_params['encoder_hidden_dim'] = [20, 20, 20] net_params['encoder_output_dim'] = 10 net_params['epochs'] = 200 net_params['optimizer'] = 'adam' # DNN tunable parameters: net_params['lr'] = tune.loguniform(1e-5, 1e-2) net_params['l2_reg'] = tune.loguniform(1e-6, 1e-1) net_params['l1_reg'] = tune.loguniform(1e-6, 1e-1) net_params['batch_size'] = tune.choice([16, 32, 64, 128]) net_params['lin_loss_penalty'] = tune.uniform(0, 1) # Hyperparameter tuning parameters: num_samples = -1 time_budget_s = 120#3*60*60 # Time budget for tuning process for each n_multistep value n_multistep_lst = [1, 5, 10, 30] if torch.cuda.is_available(): resources_cpu = 2 resources_gpu = 0.2 else: resources_cpu = 1 resources_gpu = 0 # Collect/load datasets: if collect_data: xs_train, us_train, t_eval_train = run_experiment(system, n, n_traj_train, n_pred_dc, t_eval, x0_max, m=m, K_p=K_dc_p, K_d=K_dc_d, noise_var=noise_var) xs_test, us_test, t_eval_test = run_experiment(system, n, n_traj_test, n_pred_dc, t_eval, x0_max, m=m, K_p=K_dc_p, K_d=K_dc_d, noise_var=noise_var) data_list = [xs_train, us_train, t_eval_train, n_traj_train, xs_test, us_test, t_eval_test, n_traj_test] outfile = open(directory + '/data/' + sys_name + '_data.pickle', 'wb') dill.dump(data_list, outfile) outfile.close() else: infile = open(directory + '/data/' + sys_name + '_data.pickle', 'rb') xs_train, us_train, t_eval_train, n_traj_train, xs_test, us_test, t_eval_test, n_traj_test = dill.load(infile) infile.close() # Define Koopman DNN model: net = KoopmanNetCtrl(net_params) model_kdnn = KoopDnn(net) model_kdnn.set_datasets(xs_train, us_train, t_eval_train) # Set up hyperparameter tuning: trainable = lambda config: model_kdnn.model_pipeline(config, print_epoch=False, tune_run=True) tune.register_trainable('trainable_pipeline', trainable) best_trial_lst, best_config_lst = [], [] for n_multistep in n_multistep_lst: net_params['n_multistep'] = n_multistep scheduler = ASHAScheduler( time_attr='training_iteration', metric='loss', mode='min', max_t=net_params['epochs'], grace_period=30, ) result = tune.run( 'trainable_pipeline', config=net_params, checkpoint_at_end=True, num_samples=num_samples, time_budget_s=time_budget_s, scheduler=scheduler, resources_per_trial={'cpu': resources_cpu, 'gpu': resources_gpu}, verbose=1 ) # algo = TuneBOHB(metric='loss', mode='min') # bohb = HyperBandForBOHB( # metric='loss', # mode='min', # max_t=net_params['epochs'], # time_attr='training_iteration' # ) # result = tune.run( # 'trainable_pipeline', # config=net_params, # checkpoint_at_end=True, # num_samples=num_samples, # time_budget_s=time_budget_s, # scheduler=bohb, # search_alg=algo, # resources_per_trial={'cpu': resources_cpu, 'gpu': resources_gpu}, # verbose=3 # ) best_trial_lst.append(result.get_best_trial("loss", "min", "last")) best_config_lst.append(result.get_best_config("loss", "min")) # Analyze the results: val_loss = [] test_loss = [] open_loop_mse = [] open_loop_std = [] for best_trial in best_trial_lst: # Extract validation loss: val_loss.append(best_trial.last_result["loss"]) # Calculate test loss: best_model = KoopDnn(best_trial.config) checkpoint_path = os.path.join(best_trial.checkpoint.value, 'checkpoint') model_state, optimizer_state = torch.load(checkpoint_path) best_model.koopman_net.load_state_dict(model_state) test_loss.append(best_model.test_loss(xs_test, us_test, t_eval_test)) # Calculate open loop mse and std: n_tot = net_params['state_dim'] + net_params['encoder_output_dim'] + int(net_params['first_obs_const']) best_model.construct_koopman_model() sys_kdnn = BilinearLiftedDynamics(n_tot, m, best_model.A, best_model.B, best_model.C, best_model.basis_encode, continuous_mdl=False, dt=dt) mse, std = evaluate_ol_pred(sys_kdnn, xs_test, us_test, t_eval_test) open_loop_mse.append(mse) open_loop_std.append(std) plt.figure() plt.plot(n_multistep_lst, val_loss, label='validation loss') plt.plot(n_multistep_lst, test_loss, label='test loss') plt.plot(n_multistep_lst, open_loop_mse, label='open loop mse') plt.plot(n_multistep_lst, open_loop_std, label='open loop std') plt.xlabel('# of multistep prediction steps') plt.ylabel('Loss') plt.title('Best tuned model performance VS multistep horizon') plt.legend() plt.savefig(directory + '/figures/' + 'tuning_summary_' + sys_name + '.pdf') outfile = open(directory + '/data/' + sys_name + '_best_params.pickle', 'wb') data_list_tuning = [best_config_lst, val_loss, test_loss, open_loop_mse, open_loop_std] dill.dump(data_list_tuning, outfile) outfile.close()
[ "koopman_core.learning.KoopDnn", "ray.tune.uniform", "matplotlib.pyplot.title", "matplotlib.pyplot.figure", "numpy.arange", "koopman_core.util.evaluate_ol_pred", "os.path.join", "sys.path.append", "os.path.abspath", "koopman_core.dynamics.BilinearLiftedDynamics", "koopman_core.learning.KoopmanNetCtrl", "torch.load", "numpy.identity", "koopman_core.util.run_experiment", "dill.load", "ray.tune.run", "matplotlib.pyplot.legend", "scipy.linalg.solve_continuous_are", "torch.cuda.is_available", "ray.tune.schedulers.ASHAScheduler", "numpy.linalg.inv", "matplotlib.pyplot.ylabel", "dill.dump", "matplotlib.pyplot.plot", "ray.tune.register_trainable", "ray.tune.choice", "numpy.array", "core.dynamics.RoboticDynamics.__init__", "ray.tune.loguniform", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.savefig" ]
[((49, 74), 'sys.path.append', 'sys.path.append', (['"""../../"""'], {}), "('../../')\n", (64, 74), False, 'import sys\n'), ((1229, 1300), 'numpy.array', 'np.array', (['[[0, 0, 1, 0], [0, 0, 0, 1], [0, 0, lambd, 0], [0, 0, 0, mu]]'], {}), '([[0, 0, 1, 0], [0, 0, 0, 1], [0, 0, lambd, 0], [0, 0, 0, mu]])\n', (1237, 1300), True, 'import numpy as np\n'), ((1363, 1405), 'numpy.array', 'np.array', (['[[0, 0], [0, 0], [1, 0], [0, 1]]'], {}), '([[0, 0], [0, 0], [1, 0], [0, 1]])\n', (1371, 1405), True, 'import numpy as np\n'), ((1855, 1911), 'scipy.linalg.solve_continuous_are', 'sc.linalg.solve_continuous_are', (['A_lin', 'B_lin', 'Q_dc', 'R_dc'], {}), '(A_lin, B_lin, Q_dc, R_dc)\n', (1885, 1911), True, 'import scipy as sc\n'), ((3169, 3199), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0, 1.0]'], {}), '([1.0, 1.0, 1.0, 1.0])\n', (3177, 3199), True, 'import numpy as np\n'), ((3264, 3305), 'os.path.abspath', 'os.path.abspath', (['"""working_files/bkeedmd/"""'], {}), "('working_files/bkeedmd/')\n", (3279, 3305), False, 'import os\n'), ((3890, 3918), 'ray.tune.loguniform', 'tune.loguniform', (['(1e-05)', '(0.01)'], {}), '(1e-05, 0.01)\n', (3905, 3918), False, 'from ray import tune\n'), ((3941, 3968), 'ray.tune.loguniform', 'tune.loguniform', (['(1e-06)', '(0.1)'], {}), '(1e-06, 0.1)\n', (3956, 3968), False, 'from ray import tune\n'), ((3992, 4019), 'ray.tune.loguniform', 'tune.loguniform', (['(1e-06)', '(0.1)'], {}), '(1e-06, 0.1)\n', (4007, 4019), False, 'from ray import tune\n'), ((4047, 4077), 'ray.tune.choice', 'tune.choice', (['[16, 32, 64, 128]'], {}), '([16, 32, 64, 128])\n', (4058, 4077), False, 'from ray import tune\n'), ((4111, 4129), 'ray.tune.uniform', 'tune.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (4123, 4129), False, 'from ray import tune\n'), ((4345, 4370), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (4368, 4370), False, 'import torch\n'), ((5415, 5441), 'koopman_core.learning.KoopmanNetCtrl', 'KoopmanNetCtrl', (['net_params'], {}), '(net_params)\n', (5429, 5441), False, 'from koopman_core.learning import KoopDnn, KoopmanNetCtrl\n'), ((5455, 5467), 'koopman_core.learning.KoopDnn', 'KoopDnn', (['net'], {}), '(net)\n', (5462, 5467), False, 'from koopman_core.learning import KoopDnn, KoopmanNetCtrl\n'), ((5654, 5710), 'ray.tune.register_trainable', 'tune.register_trainable', (['"""trainable_pipeline"""', 'trainable'], {}), "('trainable_pipeline', trainable)\n", (5677, 5710), False, 'from ray import tune\n'), ((8076, 8088), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (8086, 8088), True, 'import matplotlib.pyplot as plt\n'), ((8089, 8149), 'matplotlib.pyplot.plot', 'plt.plot', (['n_multistep_lst', 'val_loss'], {'label': '"""validation loss"""'}), "(n_multistep_lst, val_loss, label='validation loss')\n", (8097, 8149), True, 'import matplotlib.pyplot as plt\n'), ((8150, 8205), 'matplotlib.pyplot.plot', 'plt.plot', (['n_multistep_lst', 'test_loss'], {'label': '"""test loss"""'}), "(n_multistep_lst, test_loss, label='test loss')\n", (8158, 8205), True, 'import matplotlib.pyplot as plt\n'), ((8206, 8269), 'matplotlib.pyplot.plot', 'plt.plot', (['n_multistep_lst', 'open_loop_mse'], {'label': '"""open loop mse"""'}), "(n_multistep_lst, open_loop_mse, label='open loop mse')\n", (8214, 8269), True, 'import matplotlib.pyplot as plt\n'), ((8270, 8333), 'matplotlib.pyplot.plot', 'plt.plot', (['n_multistep_lst', 'open_loop_std'], {'label': '"""open loop std"""'}), "(n_multistep_lst, open_loop_std, label='open loop std')\n", (8278, 8333), True, 'import matplotlib.pyplot as plt\n'), ((8334, 8379), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""# of multistep prediction steps"""'], {}), "('# of multistep prediction steps')\n", (8344, 8379), True, 'import matplotlib.pyplot as plt\n'), ((8380, 8398), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Loss"""'], {}), "('Loss')\n", (8390, 8398), True, 'import matplotlib.pyplot as plt\n'), ((8399, 8461), 'matplotlib.pyplot.title', 'plt.title', (['"""Best tuned model performance VS multistep horizon"""'], {}), "('Best tuned model performance VS multistep horizon')\n", (8408, 8461), True, 'import matplotlib.pyplot as plt\n'), ((8462, 8474), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (8472, 8474), True, 'import matplotlib.pyplot as plt\n'), ((8475, 8551), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(directory + '/figures/' + 'tuning_summary_' + sys_name + '.pdf')"], {}), "(directory + '/figures/' + 'tuning_summary_' + sys_name + '.pdf')\n", (8486, 8551), True, 'import matplotlib.pyplot as plt\n'), ((8719, 8755), 'dill.dump', 'dill.dump', (['data_list_tuning', 'outfile'], {}), '(data_list_tuning, outfile)\n', (8728, 8755), False, 'import dill\n'), ((1642, 1656), 'numpy.identity', 'np.identity', (['n'], {}), '(n)\n', (1653, 1656), True, 'import numpy as np\n'), ((1748, 1762), 'numpy.identity', 'np.identity', (['m'], {}), '(m)\n', (1759, 1762), True, 'import numpy as np\n'), ((2705, 2729), 'numpy.arange', 'np.arange', (['(n_pred_dc + 1)'], {}), '(n_pred_dc + 1)\n', (2714, 2729), True, 'import numpy as np\n'), ((4550, 4671), 'koopman_core.util.run_experiment', 'run_experiment', (['system', 'n', 'n_traj_train', 'n_pred_dc', 't_eval', 'x0_max'], {'m': 'm', 'K_p': 'K_dc_p', 'K_d': 'K_dc_d', 'noise_var': 'noise_var'}), '(system, n, n_traj_train, n_pred_dc, t_eval, x0_max, m=m, K_p\n =K_dc_p, K_d=K_dc_d, noise_var=noise_var)\n', (4564, 4671), False, 'from koopman_core.util import run_experiment, evaluate_ol_pred\n'), ((4757, 4877), 'koopman_core.util.run_experiment', 'run_experiment', (['system', 'n', 'n_traj_test', 'n_pred_dc', 't_eval', 'x0_max'], {'m': 'm', 'K_p': 'K_dc_p', 'K_d': 'K_dc_d', 'noise_var': 'noise_var'}), '(system, n, n_traj_test, n_pred_dc, t_eval, x0_max, m=m, K_p=\n K_dc_p, K_d=K_dc_d, noise_var=noise_var)\n', (4771, 4877), False, 'from koopman_core.util import run_experiment, evaluate_ol_pred\n'), ((5116, 5145), 'dill.dump', 'dill.dump', (['data_list', 'outfile'], {}), '(data_list, outfile)\n', (5125, 5145), False, 'import dill\n'), ((5343, 5360), 'dill.load', 'dill.load', (['infile'], {}), '(infile)\n', (5352, 5360), False, 'import dill\n'), ((5850, 5971), 'ray.tune.schedulers.ASHAScheduler', 'ASHAScheduler', ([], {'time_attr': '"""training_iteration"""', 'metric': '"""loss"""', 'mode': '"""min"""', 'max_t': "net_params['epochs']", 'grace_period': '(30)'}), "(time_attr='training_iteration', metric='loss', mode='min',\n max_t=net_params['epochs'], grace_period=30)\n", (5863, 5971), False, 'from ray.tune.schedulers import HyperBandForBOHB, ASHAScheduler\n'), ((6028, 6266), 'ray.tune.run', 'tune.run', (['"""trainable_pipeline"""'], {'config': 'net_params', 'checkpoint_at_end': '(True)', 'num_samples': 'num_samples', 'time_budget_s': 'time_budget_s', 'scheduler': 'scheduler', 'resources_per_trial': "{'cpu': resources_cpu, 'gpu': resources_gpu}", 'verbose': '(1)'}), "('trainable_pipeline', config=net_params, checkpoint_at_end=True,\n num_samples=num_samples, time_budget_s=time_budget_s, scheduler=\n scheduler, resources_per_trial={'cpu': resources_cpu, 'gpu':\n resources_gpu}, verbose=1)\n", (6036, 6266), False, 'from ray import tune\n'), ((7269, 7295), 'koopman_core.learning.KoopDnn', 'KoopDnn', (['best_trial.config'], {}), '(best_trial.config)\n', (7276, 7295), False, 'from koopman_core.learning import KoopDnn, KoopmanNetCtrl\n'), ((7318, 7373), 'os.path.join', 'os.path.join', (['best_trial.checkpoint.value', '"""checkpoint"""'], {}), "(best_trial.checkpoint.value, 'checkpoint')\n", (7330, 7373), False, 'import os\n'), ((7409, 7436), 'torch.load', 'torch.load', (['checkpoint_path'], {}), '(checkpoint_path)\n', (7419, 7436), False, 'import torch\n'), ((7771, 7903), 'koopman_core.dynamics.BilinearLiftedDynamics', 'BilinearLiftedDynamics', (['n_tot', 'm', 'best_model.A', 'best_model.B', 'best_model.C', 'best_model.basis_encode'], {'continuous_mdl': '(False)', 'dt': 'dt'}), '(n_tot, m, best_model.A, best_model.B, best_model.C,\n best_model.basis_encode, continuous_mdl=False, dt=dt)\n', (7793, 7903), False, 'from koopman_core.dynamics import BilinearLiftedDynamics\n'), ((7957, 8014), 'koopman_core.util.evaluate_ol_pred', 'evaluate_ol_pred', (['sys_kdnn', 'xs_test', 'us_test', 't_eval_test'], {}), '(sys_kdnn, xs_test, us_test, t_eval_test)\n', (7973, 8014), False, 'from koopman_core.util import run_experiment, evaluate_ol_pred\n'), ((616, 652), 'core.dynamics.RoboticDynamics.__init__', 'RoboticDynamics.__init__', (['self', '(2)', '(2)'], {}), '(self, 2, 2)\n', (640, 652), False, 'from core.dynamics import RoboticDynamics\n'), ((724, 765), 'numpy.array', 'np.array', (['[[1, 0], [0, (q[0] + 1) ** -1]]'], {}), '([[1, 0], [0, (q[0] + 1) ** -1]])\n', (732, 765), True, 'import numpy as np\n'), ((987, 1003), 'numpy.array', 'np.array', (['[0, 0]'], {}), '([0, 0])\n', (995, 1003), True, 'import numpy as np\n'), ((1040, 1066), 'numpy.array', 'np.array', (['[[1, 0], [0, 1]]'], {}), '([[1, 0], [0, 1]])\n', (1048, 1066), True, 'import numpy as np\n'), ((1978, 1997), 'numpy.linalg.inv', 'np.linalg.inv', (['R_dc'], {}), '(R_dc)\n', (1991, 1997), True, 'import numpy as np\n'), ((847, 951), 'numpy.array', 'np.array', (['[[lambd, 0], [(q[0] + 1) ** -1 * (2 * lambd - mu) * c * q_dot[0], (q[0] + 1\n ) ** -1 * mu]]'], {}), '([[lambd, 0], [(q[0] + 1) ** -1 * (2 * lambd - mu) * c * q_dot[0], \n (q[0] + 1) ** -1 * mu]])\n', (855, 951), True, 'import numpy as np\n')]
import sys import pandas as pd import re import numpy as np from sqlalchemy import create_engine from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from nltk.stem.porter import PorterStemmer from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.multioutput import MultiOutputClassifier from sklearn.ensemble import GradientBoostingClassifier from sklearn.metrics import classification_report from joblib import dump import pickle def load_data(database_filepath): ''' INPUT - database_filepath OUTPUT: X - features DataFrame y - responses DataFrame category_names - list of features available in feature DataFrame This function reads the table 'categorized_message' from a database db-file. This db-file is the output of the script 'process_data.py' and returns the X and y df and the list of features. ''' engine = create_engine('sqlite:///'+database_filepath) df = pd.read_sql_table('categorized_messages', engine) X = df['message'] y = df.drop(columns=['id','message','original','genre', 'child_alone']) category_names = y.columns.tolist() return X, y, category_names def tokenize(text): ''' INPUT - text (string) OUTPUT - tokenized and cleansed text (string) This function tokenizes and cleanses a string by the following steps: 1. any url will be replaced by the string 'urlplaceholder' 2. any puctuation and capitalization will be removed 3. the text will be tokenized 4. any stopword will be removed 5. each word will be first lemmatized and then stemmed ''' # get list of all urls using regex url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+' detected_urls = re.findall(url_regex, text) # replace each url in text string with placeholder for url in detected_urls: text = text.replace(url, 'urlplaceholder') # Remove punctuation characters text = re.sub(r'[^a-zA-Z0-9äöüÄÖÜß ]', '', text.lower()) # tokenize tokens = word_tokenize(text) # Remove stop words tokens = [tok for tok in tokens if tok not in stopwords.words("english")] # instantiate lemmatizer and stemmer lemmatizer = WordNetLemmatizer() # lemmatize and stemm clean_tokens = [] for tok in tokens: clean_tok = lemmatizer.lemmatize(tok).lower().strip() clean_tokens.append(clean_tok) return clean_tokens def build_model(): ''' INPUT: None OUTPUT: GridSearchCV object This functions instantiates the model pipeline and performs a GridSearch Classifier: Gradient Boosting classifier GridSearch Parameters: learning_rate = [.05, .1] n_estimators = [50, 200] ''' pipeline = Pipeline([ ('vect', CountVectorizer(tokenizer = tokenize)), ('tfidf', TfidfTransformer()), ('clf', MultiOutputClassifier(GradientBoostingClassifier())) ]) params_gbc = {'clf__estimator__n_estimators': [50, 200], 'clf__estimator__learning_rate': [.05, .1] } cv = GridSearchCV(pipeline, param_grid=params_gbc, verbose=3, return_train_score=True) return cv def evaluate_model(model, X_test, y_test, category_names): ''' INPUT: model - trained model X_test - a np-array of testing features y_train - a np-array of testing responses category_names - a list of column names of the features df OUTPUT: a classification report for each feature will be printed out. ''' #predicting y_test y_pred = pd.DataFrame(model.predict(X_test), columns=category_names) y_test = pd.DataFrame(y_test, columns=category_names) print(model) print() print(classification_report(y_test.melt().value, y_pred.melt().value, zero_division=0)) print('_______________________________________________________________________________________') print('Detailed classification report per feature') for col in category_names: print('{}\n{}'.format(col, classification_report(y_test[col], y_pred[col], zero_division=0))) print('____________________________________________________________________________________\n') def save_model(model, model_filepath): # Save to file in the current working directory joblib_file = model_filepath dump(model, joblib_file, protocol=pickle.HIGHEST_PROTOCOL) def main(): if len(sys.argv) == 3: database_filepath, model_filepath = sys.argv[1:] print('Loading data...\n DATABASE: {}'.format(database_filepath)) X, Y, category_names = load_data(database_filepath) X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2) X_train, X_test = np.array(X_train), np.array(X_test) Y_train, Y_test = np.array(Y_train), np.array(Y_test) print('Building model...') model = build_model() print('Training model - this might take a while...') model.fit(X_train, Y_train) print('Evaluating model...') evaluate_model(model, X_test, Y_test, category_names) print('Saving model...\n MODEL: {}'.format(model_filepath)) save_model(model, model_filepath) print('Trained model saved!') else: print('Please provide the filepath of the disaster messages database '\ 'as the first argument and the filepath of the pickle file to '\ 'save the model to as the second argument. \n\nExample: python '\ 'train_classifier.py ../data/DisasterResponse.db classifier.pkl') if __name__ == '__main__': main()
[ "pandas.DataFrame", "sklearn.model_selection.GridSearchCV", "sklearn.feature_extraction.text.CountVectorizer", "nltk.stem.WordNetLemmatizer", "sklearn.model_selection.train_test_split", "joblib.dump", "sklearn.metrics.classification_report", "sklearn.ensemble.GradientBoostingClassifier", "pandas.read_sql_table", "re.findall", "numpy.array", "nltk.corpus.stopwords.words", "sqlalchemy.create_engine", "sklearn.feature_extraction.text.TfidfTransformer", "nltk.tokenize.word_tokenize" ]
[((1068, 1115), 'sqlalchemy.create_engine', 'create_engine', (["('sqlite:///' + database_filepath)"], {}), "('sqlite:///' + database_filepath)\n", (1081, 1115), False, 'from sqlalchemy import create_engine\n'), ((1123, 1172), 'pandas.read_sql_table', 'pd.read_sql_table', (['"""categorized_messages"""', 'engine'], {}), "('categorized_messages', engine)\n", (1140, 1172), True, 'import pandas as pd\n'), ((1959, 1986), 're.findall', 're.findall', (['url_regex', 'text'], {}), '(url_regex, text)\n', (1969, 1986), False, 'import re\n'), ((2251, 2270), 'nltk.tokenize.word_tokenize', 'word_tokenize', (['text'], {}), '(text)\n', (2264, 2270), False, 'from nltk.tokenize import word_tokenize\n'), ((2433, 2452), 'nltk.stem.WordNetLemmatizer', 'WordNetLemmatizer', ([], {}), '()\n', (2450, 2452), False, 'from nltk.stem import WordNetLemmatizer\n'), ((3303, 3389), 'sklearn.model_selection.GridSearchCV', 'GridSearchCV', (['pipeline'], {'param_grid': 'params_gbc', 'verbose': '(3)', 'return_train_score': '(True)'}), '(pipeline, param_grid=params_gbc, verbose=3, return_train_score\n =True)\n', (3315, 3389), False, 'from sklearn.model_selection import train_test_split, GridSearchCV\n'), ((3855, 3899), 'pandas.DataFrame', 'pd.DataFrame', (['y_test'], {'columns': 'category_names'}), '(y_test, columns=category_names)\n', (3867, 3899), True, 'import pandas as pd\n'), ((4543, 4601), 'joblib.dump', 'dump', (['model', 'joblib_file'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(model, joblib_file, protocol=pickle.HIGHEST_PROTOCOL)\n', (4547, 4601), False, 'from joblib import dump\n'), ((4879, 4916), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'Y'], {'test_size': '(0.2)'}), '(X, Y, test_size=0.2)\n', (4895, 4916), False, 'from sklearn.model_selection import train_test_split, GridSearchCV\n'), ((4944, 4961), 'numpy.array', 'np.array', (['X_train'], {}), '(X_train)\n', (4952, 4961), True, 'import numpy as np\n'), ((4963, 4979), 'numpy.array', 'np.array', (['X_test'], {}), '(X_test)\n', (4971, 4979), True, 'import numpy as np\n'), ((5006, 5023), 'numpy.array', 'np.array', (['Y_train'], {}), '(Y_train)\n', (5014, 5023), True, 'import numpy as np\n'), ((5025, 5041), 'numpy.array', 'np.array', (['Y_test'], {}), '(Y_test)\n', (5033, 5041), True, 'import numpy as np\n'), ((2346, 2372), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (2361, 2372), False, 'from nltk.corpus import stopwords\n'), ((2996, 3031), 'sklearn.feature_extraction.text.CountVectorizer', 'CountVectorizer', ([], {'tokenizer': 'tokenize'}), '(tokenizer=tokenize)\n', (3011, 3031), False, 'from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\n'), ((3054, 3072), 'sklearn.feature_extraction.text.TfidfTransformer', 'TfidfTransformer', ([], {}), '()\n', (3070, 3072), False, 'from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\n'), ((4246, 4310), 'sklearn.metrics.classification_report', 'classification_report', (['y_test[col]', 'y_pred[col]'], {'zero_division': '(0)'}), '(y_test[col], y_pred[col], zero_division=0)\n', (4267, 4310), False, 'from sklearn.metrics import classification_report\n'), ((3113, 3141), 'sklearn.ensemble.GradientBoostingClassifier', 'GradientBoostingClassifier', ([], {}), '()\n', (3139, 3141), False, 'from sklearn.ensemble import GradientBoostingClassifier\n')]
# * This code is provided solely for the personal and private use of students # * taking the CSC401 course at the University of Toronto. Copying for purposes # * other than this use is expressly prohibited. All forms of distribution of # * this code, including but not limited to public repositories on GitHub, # * GitLab, Bitbucket, or any other online platform, whether as given or with # * any changes, are expressly prohibited. # # * All of the files in this directory and all subdirectories are: # * Copyright (c) 2020 <NAME> import os import argparse from scipy.stats import ttest_rel from sklearn.feature_selection import f_classif from sklearn.feature_selection import SelectKBest from sklearn.ensemble import AdaBoostClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import confusion_matrix from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPClassifier from sklearn.naive_bayes import GaussianNB from sklearn.linear_model import SGDClassifier from sklearn.model_selection import KFold # set the random state for reproducibility import numpy as np np.random.seed(401) CLF_DICT = { 0: SGDClassifier, 1: GaussianNB, 2: RandomForestClassifier, 3: MLPClassifier, 4: AdaBoostClassifier } def accuracy(c): """ Compute accuracy given Numpy array confusion matrix C. Returns a floating point value. """ n, _ = c.shape return sum([c[i, i] for i in range(n)]) / sum([c[i, j] for i in range(n) for j in range(n)]) def recall(c): """ Compute recall given Numpy array confusion matrix C. Returns a list of floating point values. """ n, _ = c.shape return [(c[k, k] / sum([c[k, j] for j in range(n)])) for k in range(n)] def precision(c): """ Compute precision given Numpy array confusion matrix C. Returns a list of floating point values """ n, _ = c.shape return [(c[k, k] / sum([c[i, k] for i in range(n)])) for k in range(n)] def class31(output_dir, X_train, X_test, y_train, y_test): """ This function performs experiment 3.1 Parameters output_dir: path of directory to write output to Returns: i: int, the index of the supposed best classifier """ print('Section 3.1') # 1. SGDClassifier: support vector machine with a linear kernel. sgd = SGDClassifier() sgd.fit(X_train, y_train) # 2. GaussianNB: a Gaussian naive Bayes classifier. gnb = GaussianNB() gnb.fit(X_train, y_train) # 3. RandomForestClassifier: with a maximum depth of 5, and 10 estimators. rf = RandomForestClassifier(max_depth=5, n_estimators=10) rf.fit(X_train, y_train) # 4. MLPClassifier: A feed-forward neural network, with α = 0.05. mlp = MLPClassifier(alpha=0.05) mlp.fit(X_train, y_train) # 5. AdaBoostClassifier: with the default hyper-parameters. ada = AdaBoostClassifier() ada.fit(X_train, y_train) scores = [] with open(f"{output_dir}/a1_3.1.txt", "w") as out_f: # For each classifier, compute results and write the following output: for clf in [sgd, gnb, rf, mlp, ada]: c = confusion_matrix(y_test, clf.predict(X_test)) acc = accuracy(c) scores.append(acc) out_f.write(f'Results for {str(clf)}:\n') # Classifier name out_f.write(f'\tAccuracy: {acc:.4f}\n') out_f.write(f'\tRecall: {[round(item, 4) for item in recall(c)]}\n') out_f.write(f'\tPrecision: {[round(item, 4) for item in precision(c)]}\n') out_f.write(f'\tConfusion Matrix: \n{c}\n\n') return int(np.argmax(scores)) def class32(output_dir, X_train, X_test, y_train, y_test, iBest): """ This function performs experiment 3.2 Parameters: output_dir: path of directory to write output to iBest: int, the index of the supposed best classifier (from task 3.1) Returns: X_1k: numPy array, just 1K rows of X_train y_1k: numPy array, just 1K rows of y_train """ print('Section 3.2') clf = CLF_DICT[iBest]() with open(f"{output_dir}/a1_3.2.txt", "w") as out_f: # For each number of training examples, compute results and write for num_train in map(int, [1e4, 5e4, 1e5, 15e4, 2e5]): # 1K, 5K, 10K, 15K, and 20K clf.fit(X_train[:num_train], y_train[:num_train]) c = confusion_matrix(y_test, clf.predict(X_test)) acc = accuracy(c) out_f.write(f'{num_train}: {acc:.4f}\n') return X_train[:1000], y_train[:1000] def class33(output_dir, X_train, X_test, y_train, y_test, i, X_1k, y_1k): """ This function performs experiment 3.3 Parameters: output_dir: path of directory to write output to i: int, the index of the supposed best classifier (from task 3.1) X_1k: numPy array, just 1K rows of X_train (from task 3.2) y_1k: numPy array, just 1K rows of y_train (from task 3.2) """ print('Section 3.3') with open(f"{output_dir}/a1_3.3.txt", "w") as out_f: # Prepare the variables with corresponding names, then uncomment this, so it writes them to outf. """ 1. For the 32k training set and each number of features k = {5, 50}, find the best k features according to this approach. Write the associated p-values to a1 3.3.txt using the format strings provided. """ for k in [5, 50]: # For each number of features k_feat, write the p-values for that number of features: selector = SelectKBest(k=k) selector.fit(X_train, y_train) pp = selector.pvalues_[np.argpartition(selector.scores_, -k)[-k:]] out_f.write(f'{k} p-values: {[format(pval) for pval in pp]}\n') """ 2. Train the best classifier from section 3.1 for each of the 1K training set and the 32K training set, using only the best k = 5 features. Write the accuracies on the full test set of both classifiers to a1 3.3.txt using the format strings provided. """ selector = SelectKBest(k=5) X_new = selector.fit_transform(X_train, y_train) X_test_new = selector.transform(X_test) clf = CLF_DICT[i]() clf.fit(X_new[:1000], y_train[:1000]) c = confusion_matrix(y_test, clf.predict(X_test_new)) accuracy_1k = accuracy(c) out_f.write(f'Accuracy for 1k: {accuracy_1k:.4f}\n') clf = CLF_DICT[i]() clf.fit(X_new, y_train) c = confusion_matrix(y_test, clf.predict(X_test_new)) accuracy_full = accuracy(c) out_f.write(f'Accuracy for full dataset: {accuracy_full:.4f}\n') """ 3. Extract the indices of the top k = 5 features using the 1K training set and take the intersection with the k = 5 features using the 32K training set. Write using the format strings provided. """ top_1k_selector = SelectKBest(k=5) top_1k_selector.fit(X_train[:1000], y_train[:1000]) top_1k_index = set(np.argpartition(top_1k_selector.scores_, -5)[-5:]) top_all_selector = SelectKBest(k=5) top_all_selector.fit(X_train, y_train) top_all_index = set(np.argpartition(top_all_selector.scores_, -5)[-5:]) feature_intersection = top_1k_index.intersection(top_all_index) out_f.write(f'Chosen feature intersection: {feature_intersection}\n') """ 4. Format the top k = 5 feature indices extracted from the 32K training set to file using the format string provided. """ out_f.write(f'Top-5 at higher: {top_all_index}\n') def class34(output_dir, X_train, X_test, y_train, y_test, i): """ This function performs experiment 3.4 Parameters output_dir: path of directory to write output to i: int, the index of the supposed best classifier (from task 3.1) """ print('Section 3.4') with open(f"{output_dir}/a1_3.4.txt", "w") as outf: # Prepare kfold_accuracies, then uncomment this, so it writes them to outf. sgd = SGDClassifier() gnb = GaussianNB() rf = RandomForestClassifier(max_depth=5, n_estimators=10) mlp = MLPClassifier(alpha=0.05) ada = AdaBoostClassifier() kfold_accuracies = [] for clf in [sgd, gnb, rf, mlp, ada]: kf = KFold(n_splits=5, random_state=None, shuffle=False) kfold_accs = [] for train_index, test_index in kf.split(X_train): X_train_s, X_test_s = X_train[train_index], X_train[test_index] y_train_s, y_test_s = y_train[train_index], y_train[test_index] clf.fit(X_train_s, y_train_s) kfold_accs.append(accuracy(confusion_matrix(y_test_s, clf.predict(X_test_s)))) kfold_accuracies.append(int(np.mean(kfold_accs))) outf.write(f'Kfold Accuracies: {[round(acc, 4) for acc in kfold_accuracies]}\n') # outf.write(f'p-values: {[format(pval) for pval in p_values]}\n') if __name__ == "__main__": """ python a1_classify.py -i feats.npz -o . """ parser = argparse.ArgumentParser() parser.add_argument("-i", "--input", help="the input npz file from Task 2", required=True) parser.add_argument("-o", "--output_dir", help="The directory to write a1_3.X.txt files to.", default=os.path.dirname(os.path.dirname(__file__))) args = parser.parse_args() """ Load data and split into train and test. """ with np.load(args.input) as npz_f: feat = npz_f["arr_0"] x, y = feat[:, :-1], feat[:, -1] X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) """ Complete each classification experiment, in sequence. """ i_best = class31(args.output_dir, X_train, X_test, y_train, y_test) x_1k, y_1k = class32(args.output_dir, X_train, X_test, y_train, y_test, i_best) class33(args.output_dir, X_train, X_test, y_train, y_test, i_best, x_1k, y_1k) class34(args.output_dir, X_train, X_test, y_train, y_test, i_best)
[ "sklearn.ensemble.RandomForestClassifier", "sklearn.naive_bayes.GaussianNB", "sklearn.ensemble.AdaBoostClassifier", "numpy.random.seed", "argparse.ArgumentParser", "sklearn.linear_model.SGDClassifier", "numpy.argmax", "numpy.load", "sklearn.model_selection.train_test_split", "os.path.dirname", "sklearn.model_selection.KFold", "numpy.argpartition", "numpy.mean", "sklearn.neural_network.MLPClassifier", "sklearn.feature_selection.SelectKBest" ]
[((1143, 1162), 'numpy.random.seed', 'np.random.seed', (['(401)'], {}), '(401)\n', (1157, 1162), True, 'import numpy as np\n'), ((2351, 2366), 'sklearn.linear_model.SGDClassifier', 'SGDClassifier', ([], {}), '()\n', (2364, 2366), False, 'from sklearn.linear_model import SGDClassifier\n'), ((2464, 2476), 'sklearn.naive_bayes.GaussianNB', 'GaussianNB', ([], {}), '()\n', (2474, 2476), False, 'from sklearn.naive_bayes import GaussianNB\n'), ((2596, 2648), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'max_depth': '(5)', 'n_estimators': '(10)'}), '(max_depth=5, n_estimators=10)\n', (2618, 2648), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((2759, 2784), 'sklearn.neural_network.MLPClassifier', 'MLPClassifier', ([], {'alpha': '(0.05)'}), '(alpha=0.05)\n', (2772, 2784), False, 'from sklearn.neural_network import MLPClassifier\n'), ((2890, 2910), 'sklearn.ensemble.AdaBoostClassifier', 'AdaBoostClassifier', ([], {}), '()\n', (2908, 2910), False, 'from sklearn.ensemble import AdaBoostClassifier\n'), ((9128, 9153), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (9151, 9153), False, 'import argparse\n'), ((9677, 9714), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x', 'y'], {'test_size': '(0.2)'}), '(x, y, test_size=0.2)\n', (9693, 9714), False, 'from sklearn.model_selection import train_test_split\n'), ((3628, 3645), 'numpy.argmax', 'np.argmax', (['scores'], {}), '(scores)\n', (3637, 3645), True, 'import numpy as np\n'), ((6098, 6114), 'sklearn.feature_selection.SelectKBest', 'SelectKBest', ([], {'k': '(5)'}), '(k=5)\n', (6109, 6114), False, 'from sklearn.feature_selection import SelectKBest\n'), ((6940, 6956), 'sklearn.feature_selection.SelectKBest', 'SelectKBest', ([], {'k': '(5)'}), '(k=5)\n', (6951, 6956), False, 'from sklearn.feature_selection import SelectKBest\n'), ((7123, 7139), 'sklearn.feature_selection.SelectKBest', 'SelectKBest', ([], {'k': '(5)'}), '(k=5)\n', (7134, 7139), False, 'from sklearn.feature_selection import SelectKBest\n'), ((8080, 8095), 'sklearn.linear_model.SGDClassifier', 'SGDClassifier', ([], {}), '()\n', (8093, 8095), False, 'from sklearn.linear_model import SGDClassifier\n'), ((8110, 8122), 'sklearn.naive_bayes.GaussianNB', 'GaussianNB', ([], {}), '()\n', (8120, 8122), False, 'from sklearn.naive_bayes import GaussianNB\n'), ((8136, 8188), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'max_depth': '(5)', 'n_estimators': '(10)'}), '(max_depth=5, n_estimators=10)\n', (8158, 8188), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((8203, 8228), 'sklearn.neural_network.MLPClassifier', 'MLPClassifier', ([], {'alpha': '(0.05)'}), '(alpha=0.05)\n', (8216, 8228), False, 'from sklearn.neural_network import MLPClassifier\n'), ((8243, 8263), 'sklearn.ensemble.AdaBoostClassifier', 'AdaBoostClassifier', ([], {}), '()\n', (8261, 8263), False, 'from sklearn.ensemble import AdaBoostClassifier\n'), ((9541, 9560), 'numpy.load', 'np.load', (['args.input'], {}), '(args.input)\n', (9548, 9560), True, 'import numpy as np\n'), ((5571, 5587), 'sklearn.feature_selection.SelectKBest', 'SelectKBest', ([], {'k': 'k'}), '(k=k)\n', (5582, 5587), False, 'from sklearn.feature_selection import SelectKBest\n'), ((8357, 8408), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': '(5)', 'random_state': 'None', 'shuffle': '(False)'}), '(n_splits=5, random_state=None, shuffle=False)\n', (8362, 8408), False, 'from sklearn.model_selection import KFold\n'), ((7044, 7088), 'numpy.argpartition', 'np.argpartition', (['top_1k_selector.scores_', '(-5)'], {}), '(top_1k_selector.scores_, -5)\n', (7059, 7088), True, 'import numpy as np\n'), ((7215, 7260), 'numpy.argpartition', 'np.argpartition', (['top_all_selector.scores_', '(-5)'], {}), '(top_all_selector.scores_, -5)\n', (7230, 7260), True, 'import numpy as np\n'), ((9419, 9444), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (9434, 9444), False, 'import os\n'), ((5667, 5704), 'numpy.argpartition', 'np.argpartition', (['selector.scores_', '(-k)'], {}), '(selector.scores_, -k)\n', (5682, 5704), True, 'import numpy as np\n'), ((8840, 8859), 'numpy.mean', 'np.mean', (['kfold_accs'], {}), '(kfold_accs)\n', (8847, 8859), True, 'import numpy as np\n')]
import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split import utils from methods import methods from visualization import plots FILENAME = 'datasets/ILThermo_Tm.csv' MODEL = 'mlp_regressor' DIRNAME = 'my_test' descs = sys.argv[1:] if len(sys.argv) > 1 else None # Get X matrix and response vector y df, y_error = utils.read_data(FILENAME) X, y = utils.molecular_descriptors(df,descs) Y = np.empty((y.shape[0],2)) Y[:,0] = y.ravel() Y[:,1] = y_error.ravel() X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.10) y_train = Y_train[:,0] y_test = Y_test[:,0] e_train = Y_train[:,1] e_test = Y_test[:,1] # Normalize testing data using training data X_train, X_mean, X_std = utils.normalization(X_train) X_test, trash, trash = utils.normalization(X_test, X_mean, X_std) # Do machine_learning call if (MODEL.lower() == 'mlp_regressor'): obj = methods.do_MLP_regressor(X_train, y_train.ravel()) elif (MODEL.lower() == 'lasso'): obj = methods.do_lasso(X_train, y_train.ravel()) elif (MODEL.lower() == 'svr'): obj = methods.do_svr(X_train, y_train.ravel()) else: raise ValueError("Model not supported") #Plots simple_parity_plot = plots.parity_plot(y_train, obj.predict(X_train)) #Creates a prediction and experimental values plot predict_train = np.zeros(X_train.shape[0]) predict_test = np.zeros(X_test.shape[0]) predict_train, predict_test = plots.error_values(np.copy(X_train),np.copy(X_test),np.copy(y_train),np.copy(y_test)) plot = False if plot: #Creates a plot for the training data set plt.figure(figsize=(10,8)) plt.subplot(1,2,1) plt.scatter(y_train,predict_train,s=0.5,color='blue') plt.title('Prediction on training data') plt.plot(np.linspace(0,12,1000),np.linspace(0,12,1000),color='black') plt.xlim((0,12)) plt.ylim((0,12)) plt.xlabel("Experiment($S*m^2/mol$)") plt.ylabel("Prediction($S*m^2/mol$)") #Creates a plot for the testing data set plt.subplot(1,2,2) plt.scatter(y_test,predict_test,s=2,color='blue') plt.title('Prediction on test data') plt.xlim((0,12)) plt.ylim((0,12)) plt.xlabel("Experiment($S*m^2/mol$)") plt.ylabel("Prediction($S*m^2/mol$)") plt.plot(np.linspace(0,12,1000),np.linspace(0,12,1000),color='black') plt.show() #Creates a plot for the experimental and predicted data to the experimental error provided by the ILThermo database fig = plt.figure(figsize=(10,8)) ax = fig.add_subplot(111) ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212) #Set up the training data set plot result = pd.DataFrame(columns=['Experiment','Prediction','error']) result.Experiment = y_train result.Prediction = predict_train result.error = e_train result = result.sort_values(['Experiment','Prediction'],ascending=[1,1]) print(result) import sys sys.exit() #Creates a subplot for the training data set size=0.2 ax1.set_xlim((0,2300)) ax1.set_ylim((-1,13)) ax1.scatter(np.arange(X_train.shape[0]),result.Experiment,color="blue",s=size,label='Experiment') ax1.scatter(np.arange(X_train.shape[0]),result.Prediction,color="red",s=size,label='Prediction') ax1.scatter(np.arange(X_train.shape[0]),result.Experiment+result.error,color="green",s=size,label='Experiment Error') ax1.scatter(np.arange(X_train.shape[0]),result.Experiment-result.error,color="green",s=size) ax1.set_title('Prediction on Training data') ax1.legend(loc='upper left') #Setting up the test data set plot result = pd.DataFrame(columns=['Experiment','Prediction','error']) result.Experiment = y_test result.Prediction = predict_test result.error = e_test result = result.sort_values(['Experiment','Prediction'],ascending=[1,1]) #Creates a subplot for the testing data set size=2 ax2.set_xlim((0,260)) ax2.set_ylim((-1,13)) ax2.scatter(np.arange(X_test.shape[0]),result.Experiment,color="blue",s=size,label='Experiment') ax2.scatter(np.arange(X_test.shape[0]),result.Prediction,color="red",s=size,label='Prediction') ax2.scatter(np.arange(X_test.shape[0]),result.Experiment+result.error,color="green",s=size,label='Experiment Error') ax2.scatter(np.arange(X_test.shape[0]),result.Experiment-result.error,color="green",s=size) ax2.set_title('Prediction on test data') ax2.legend(loc='upper left') #Personal preference additions to the plot ax.set_xlabel('Data points') ax.set_ylabel('Conductivity($S*m^2/mol$)') ax.spines['top'].set_color('none') ax.spines['bottom'].set_color('none') ax.spines['left'].set_color('none') ax.spines['right'].set_color('none') ax.tick_params(labelcolor='w', top='off', bottom='off', left='off', right='off') fig.tight_layout() plt.show()
[ "matplotlib.pyplot.title", "numpy.empty", "sklearn.model_selection.train_test_split", "utils.molecular_descriptors", "matplotlib.pyplot.figure", "numpy.arange", "pandas.DataFrame", "utils.normalization", "numpy.copy", "numpy.linspace", "matplotlib.pyplot.show", "matplotlib.pyplot.ylim", "matplotlib.pyplot.ylabel", "sys.exit", "matplotlib.pyplot.subplot", "matplotlib.pyplot.xlim", "matplotlib.pyplot.scatter", "utils.read_data", "numpy.zeros", "matplotlib.pyplot.xlabel" ]
[((398, 423), 'utils.read_data', 'utils.read_data', (['FILENAME'], {}), '(FILENAME)\n', (413, 423), False, 'import utils\n'), ((431, 469), 'utils.molecular_descriptors', 'utils.molecular_descriptors', (['df', 'descs'], {}), '(df, descs)\n', (458, 469), False, 'import utils\n'), ((474, 499), 'numpy.empty', 'np.empty', (['(y.shape[0], 2)'], {}), '((y.shape[0], 2))\n', (482, 499), True, 'import numpy as np\n'), ((576, 613), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'Y'], {'test_size': '(0.1)'}), '(X, Y, test_size=0.1)\n', (592, 613), False, 'from sklearn.model_selection import train_test_split\n'), ((773, 801), 'utils.normalization', 'utils.normalization', (['X_train'], {}), '(X_train)\n', (792, 801), False, 'import utils\n'), ((825, 867), 'utils.normalization', 'utils.normalization', (['X_test', 'X_mean', 'X_std'], {}), '(X_test, X_mean, X_std)\n', (844, 867), False, 'import utils\n'), ((1360, 1386), 'numpy.zeros', 'np.zeros', (['X_train.shape[0]'], {}), '(X_train.shape[0])\n', (1368, 1386), True, 'import numpy as np\n'), ((1402, 1427), 'numpy.zeros', 'np.zeros', (['X_test.shape[0]'], {}), '(X_test.shape[0])\n', (1410, 1427), True, 'import numpy as np\n'), ((2647, 2706), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['Experiment', 'Prediction', 'error']"}), "(columns=['Experiment', 'Prediction', 'error'])\n", (2659, 2706), True, 'import pandas as pd\n'), ((2889, 2899), 'sys.exit', 'sys.exit', ([], {}), '()\n', (2897, 2899), False, 'import sys\n'), ((3525, 3584), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['Experiment', 'Prediction', 'error']"}), "(columns=['Experiment', 'Prediction', 'error'])\n", (3537, 3584), True, 'import pandas as pd\n'), ((4668, 4678), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4676, 4678), True, 'import matplotlib.pyplot as plt\n'), ((1477, 1493), 'numpy.copy', 'np.copy', (['X_train'], {}), '(X_train)\n', (1484, 1493), True, 'import numpy as np\n'), ((1494, 1509), 'numpy.copy', 'np.copy', (['X_test'], {}), '(X_test)\n', (1501, 1509), True, 'import numpy as np\n'), ((1510, 1526), 'numpy.copy', 'np.copy', (['y_train'], {}), '(y_train)\n', (1517, 1526), True, 'import numpy as np\n'), ((1527, 1542), 'numpy.copy', 'np.copy', (['y_test'], {}), '(y_test)\n', (1534, 1542), True, 'import numpy as np\n'), ((1618, 1645), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 8)'}), '(figsize=(10, 8))\n', (1628, 1645), True, 'import matplotlib.pyplot as plt\n'), ((1649, 1669), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (1660, 1669), True, 'import matplotlib.pyplot as plt\n'), ((1672, 1728), 'matplotlib.pyplot.scatter', 'plt.scatter', (['y_train', 'predict_train'], {'s': '(0.5)', 'color': '"""blue"""'}), "(y_train, predict_train, s=0.5, color='blue')\n", (1683, 1728), True, 'import matplotlib.pyplot as plt\n'), ((1730, 1770), 'matplotlib.pyplot.title', 'plt.title', (['"""Prediction on training data"""'], {}), "('Prediction on training data')\n", (1739, 1770), True, 'import matplotlib.pyplot as plt\n'), ((1849, 1866), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0, 12)'], {}), '((0, 12))\n', (1857, 1866), True, 'import matplotlib.pyplot as plt\n'), ((1870, 1887), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0, 12)'], {}), '((0, 12))\n', (1878, 1887), True, 'import matplotlib.pyplot as plt\n'), ((1891, 1928), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Experiment($S*m^2/mol$)"""'], {}), "('Experiment($S*m^2/mol$)')\n", (1901, 1928), True, 'import matplotlib.pyplot as plt\n'), ((1933, 1970), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Prediction($S*m^2/mol$)"""'], {}), "('Prediction($S*m^2/mol$)')\n", (1943, 1970), True, 'import matplotlib.pyplot as plt\n'), ((2023, 2043), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (2034, 2043), True, 'import matplotlib.pyplot as plt\n'), ((2046, 2098), 'matplotlib.pyplot.scatter', 'plt.scatter', (['y_test', 'predict_test'], {'s': '(2)', 'color': '"""blue"""'}), "(y_test, predict_test, s=2, color='blue')\n", (2057, 2098), True, 'import matplotlib.pyplot as plt\n'), ((2100, 2136), 'matplotlib.pyplot.title', 'plt.title', (['"""Prediction on test data"""'], {}), "('Prediction on test data')\n", (2109, 2136), True, 'import matplotlib.pyplot as plt\n'), ((2141, 2158), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0, 12)'], {}), '((0, 12))\n', (2149, 2158), True, 'import matplotlib.pyplot as plt\n'), ((2162, 2179), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0, 12)'], {}), '((0, 12))\n', (2170, 2179), True, 'import matplotlib.pyplot as plt\n'), ((2183, 2220), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Experiment($S*m^2/mol$)"""'], {}), "('Experiment($S*m^2/mol$)')\n", (2193, 2220), True, 'import matplotlib.pyplot as plt\n'), ((2225, 2262), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Prediction($S*m^2/mol$)"""'], {}), "('Prediction($S*m^2/mol$)')\n", (2235, 2262), True, 'import matplotlib.pyplot as plt\n'), ((2341, 2351), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2349, 2351), True, 'import matplotlib.pyplot as plt\n'), ((2483, 2510), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 8)'}), '(figsize=(10, 8))\n', (2493, 2510), True, 'import matplotlib.pyplot as plt\n'), ((3011, 3038), 'numpy.arange', 'np.arange', (['X_train.shape[0]'], {}), '(X_train.shape[0])\n', (3020, 3038), True, 'import numpy as np\n'), ((3109, 3136), 'numpy.arange', 'np.arange', (['X_train.shape[0]'], {}), '(X_train.shape[0])\n', (3118, 3136), True, 'import numpy as np\n'), ((3206, 3233), 'numpy.arange', 'np.arange', (['X_train.shape[0]'], {}), '(X_train.shape[0])\n', (3215, 3233), True, 'import numpy as np\n'), ((3324, 3351), 'numpy.arange', 'np.arange', (['X_train.shape[0]'], {}), '(X_train.shape[0])\n', (3333, 3351), True, 'import numpy as np\n'), ((3846, 3872), 'numpy.arange', 'np.arange', (['X_test.shape[0]'], {}), '(X_test.shape[0])\n', (3855, 3872), True, 'import numpy as np\n'), ((3943, 3969), 'numpy.arange', 'np.arange', (['X_test.shape[0]'], {}), '(X_test.shape[0])\n', (3952, 3969), True, 'import numpy as np\n'), ((4039, 4065), 'numpy.arange', 'np.arange', (['X_test.shape[0]'], {}), '(X_test.shape[0])\n', (4048, 4065), True, 'import numpy as np\n'), ((4156, 4182), 'numpy.arange', 'np.arange', (['X_test.shape[0]'], {}), '(X_test.shape[0])\n', (4165, 4182), True, 'import numpy as np\n'), ((1784, 1808), 'numpy.linspace', 'np.linspace', (['(0)', '(12)', '(1000)'], {}), '(0, 12, 1000)\n', (1795, 1808), True, 'import numpy as np\n'), ((1807, 1831), 'numpy.linspace', 'np.linspace', (['(0)', '(12)', '(1000)'], {}), '(0, 12, 1000)\n', (1818, 1831), True, 'import numpy as np\n'), ((2276, 2300), 'numpy.linspace', 'np.linspace', (['(0)', '(12)', '(1000)'], {}), '(0, 12, 1000)\n', (2287, 2300), True, 'import numpy as np\n'), ((2299, 2323), 'numpy.linspace', 'np.linspace', (['(0)', '(12)', '(1000)'], {}), '(0, 12, 1000)\n', (2310, 2323), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- from pcompile import ureg from math import floor from numpy.random import random from copy import copy class NameRegistry(object): def __init__(self, names=set()): self.names=names assert isinstance(self.names, set) def new(self, tag=None): '''Generate a potentially unique name and check if its in the name registry. If not, return it. If so, keep generating names.''' max_iterations = 100 i = 0 while i < max_iterations: name = self.generate(tag) if name not in self.names: self.names.add(name) return name i += 1 return None def generate(self, tag=None): if tag is None or len(tag) == 0: name = 'unlabeled_container_' else: name = str(tag) + "_" name += str(int(floor(random()*1e6))) return name _PCR_96 = {'ctype':'96-pcr', 'children':[], 'child_ctype':'96-pcr', 'free':True, 'parent_only':True, 'children_free':96, 'name':None, 'max_volume': 200 * ureg.microliter, 'container_ref':None, 'well_ref':None} _PCR_96_WELL = {'ctype':'96-pcr', 'parent_name':None, 'free':True, 'max_volume':200 * ureg.microliter, 'parent_index':None} for i in range(0,96): well = copy(_PCR_96_WELL) well['parent_index'] = i _PCR_96['children'].append(well) _MICRO_15 = {'ctype':'micro-1.5', 'children':[ {'ctype':'96-pcr', 'parent_name':None, 'free':True, 'max_volume':200 * ureg.microliter, 'parent_index':0} ], 'name':'', 'child_ctype':'micro-1.5', 'free':True, 'parent_only':True, 'children_free':1, 'max_volume':1500 * ureg.microliter, 'container_ref':None, 'well_ref':None} _CONTAINERS = {'96-pcr': _PCR_96, 'micro-1.5': _MICRO_15} class Items(object): def __init__(self, containers=[], name_registry=NameRegistry()): self.containers = containers self.name_registry = name_registry def allocate(self, env, ctype): '''Find an instance of ctype in self.containers and return it. Note: This way of representing container relationships is wildly unecessary and will be updated to use the container > well > solution model in place of the current parent = container > child = well > solution model. ''' for i,c in enumerate(self.containers): if c['ctype'] == ctype: #print 'found a container of the right ctype' #print c['free'] if c['free']: #print 'container is free' if ('parent_only' not in c) or (not c['parent_only']): #print 'is right ctype, is free, does not have children' c['free'] = False # Container ref should have already been created c['well_ref'] = c['container_ref'].well(0) return c elif ('child_ctype' in c and c['child_ctype'] == ctype): #print 'examining containers contained by parent' for j,ch in enumerate(c['children']): if ch['free']: ch['free'] = False # If this was the last well in the parent plate if ch['parent_index'] == len(c['children']): c['free'] = False ch['container_ref'] = c['container_ref'] ch['well_ref'] = ch['container_ref'].well(ch['parent_index']) return ch #print 'couldnt allocate within existing items, allocatig a new container' # Didn't find a free container in the stack of existing containers, # let's try to allocate one. if ctype in _CONTAINERS.keys(): new = copy(_CONTAINERS[ctype]) name = self.name_registry.new() new['name'] = name ref = env.protocol.ref(name, cont_type=ctype, storage='cold_4') new['container_ref'] = ref self.containers.append(new) if ('parent_only' in new) and (new['parent_only'] is True): ch = new['children'][0] ch['free'] = False ch['container_ref'] = ref ch['well_ref'] = ref.well(0) return ch else: return new else: return None class Container(object): #effectively this just imposes a particular #structure on a dict. nothing special about it otherwise. def __init__(self, ctype=None, location=None): self.ctype = ctype self.location = location self.max_volume = max_volume(ctype) def max_volume(ctype): if ctype in _CONTAINERS.keys(): return _CONTAINERS[ctype]['max_volume'] else: return None def min_container_type(vol): hit = None for c in _CONTAINERS.values(): if c['max_volume'] > vol: if (hit is None) or (hit['max_volume'] > c['max_volume']): hit = c if hit is not None: return hit['ctype'] else: return None
[ "numpy.random.random", "copy.copy" ]
[((1403, 1421), 'copy.copy', 'copy', (['_PCR_96_WELL'], {}), '(_PCR_96_WELL)\n', (1407, 1421), False, 'from copy import copy\n'), ((4235, 4259), 'copy.copy', 'copy', (['_CONTAINERS[ctype]'], {}), '(_CONTAINERS[ctype])\n', (4239, 4259), False, 'from copy import copy\n'), ((922, 930), 'numpy.random.random', 'random', ([], {}), '()\n', (928, 930), False, 'from numpy.random import random\n')]
import torch import torch.nn.functional as F from tensorboardX import SummaryWriter from sklearn.metrics import roc_auc_score import numpy as np import time from tqdm import tqdm import os from utlis.utils import model_name, select_model from utlis.utils import get_optimizer, make_dataLoader, LoadModel, lr_schedule, make_dataLoader_chexpert from utlis.utils import weighted_BCELoss, SaveModel, make_dataLoader_binary, get_loss device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def training(model, args): """ This function trains the multi-label model. model: PyTorch model with model args: configuration file (argparse) return: train the returned the model """ writer = SummaryWriter(log_dir=os.path.join(args.log_dir, model_name(args))) writer.add_text('log', str(args), 0) if args.backbone == 'resnet50_wildcat': params = model.get_config_optim(args.lr, 0.5) else: params = model.parameters() optimizer = get_optimizer(params, args) if args.dataset == "NIH": dataloaders, dataset_sizes, class_names = make_dataLoader(args) elif args.dataset == 'ChesXpert': dataloaders, dataset_sizes, class_names = make_dataLoader_chexpert(args) else: assert "Wrong dataset" if not os.path.exists(args.model_save_dir): os.makedirs(args.model_save_dir) best_auc_ave = 0.0 # to check if best validation accuracy epoch_inti = 1 # epoch starts from here best_model_wts = model.state_dict() best_auc = [] iter_num = 0 # Prepare checkpoint file and model file to save and load from checkpoint_file = os.path.join(args.model_save_dir, str(model_name(args) + '_' + "checkpoint.pth")) bestmodel_file = os.path.join(args.model_save_dir, str(model_name(args) + '_' + "best_model.pth")) ''' Check for existing training results. If it existst, and the configuration is set to resume `config.resume_TIRG==True`, resume from previous training. If not, delete existing checkpoint.''' if os.path.exists(checkpoint_file): if args.resume: model, optimizer, epoch_inti, best_auc_ave = LoadModel(checkpoint_file, model, optimizer, epoch_inti, best_auc_ave) print("Checkpoint found! Resuming") else: pass print(model) since = time.time() for epoch in range(epoch_inti, args.epochs + 1): print('Epoch {}/{}'.format(epoch, args.epochs)) print('-' * 10) iter_num = 0 for phase in ['train','val']: # Only Validation in every 5 cycles if (phase == 'val') : model.train(False) elif phase == 'train': model.train(True) # Set model to training mode running_loss = 0.0 output_list = [] label_list = [] loss_list = [] # Iterate over data. for idx, data in enumerate(tqdm(dataloaders[phase])): # if iter_num > 100 and phase == 'train': # break images, labels, names = data images = images.to(device) labels = labels.to(device) mask = 1 * (labels >= 0) mask = mask.to(device) if phase == 'train': torch.set_grad_enabled(True) else: torch.set_grad_enabled(False) # calculate weight for loss P = 0 N = 0 for label in labels: for v in label: if int(v) == 1: P += 1 else: N += 1 if P != 0 and N != 0: BP = (P + N) / P BN = (P + N) / N weights = torch.tensor([BP, BN], dtype=torch.float).to(device) else: weights = None # zero the parameter gradients optimizer.zero_grad() # Predicting output outputs = model(images) # classification loss if args.weighted_loss: loss = weighted_BCELoss(outputs, labels, weights=weights) else: loss_func = torch.nn.BCELoss(reduction='none') loss = loss_func(outputs[:, 0].unsqueeze(dim=-1), torch.tensor(labels[:, 0].unsqueeze(dim=-1), dtype=torch.float)) loss = torch.where((labels >= 0)[:, 0].unsqueeze(axis=-1), loss, torch.zeros_like(loss)).mean() for index in range(1, args.num_classes): loss_temp = loss_func(outputs[:, index].unsqueeze(dim=-1), torch.tensor(labels[:, index].unsqueeze(dim=-1), dtype=torch.float)) loss_temp = torch.where((labels >= 0)[:, index].unsqueeze(axis=-1), loss_temp, torch.zeros_like(loss_temp)).mean() loss += loss_temp # backward + optimize only if in training phase if phase == 'train': loss.backward() optimizer.step() iter_num += 1 running_loss += loss.item() loss_list.append(loss.item()) outputs = outputs.detach().to('cpu').numpy() labels = labels.detach().to('cpu').numpy() for i in range(outputs.shape[0]): output_list.append(np.where(labels[i] >= 0, outputs[i], 0).tolist()) label_list.append(np.where(labels[i] >= 0, labels[i], 0).tolist()) # Saving logs if idx % 100 == 0 and idx != 0: if phase == 'train': writer.add_scalar('loss/train_batch', loss.item() / outputs.shape[0], iter_num) try: auc = roc_auc_score(np.array(label_list[-100 * args.batch_size:]), np.array(output_list[-100 * args.batch_size:])) writer.add_scalar('auc/train_batch', auc, iter_num) print('\nAUC/Train', auc) print('Batch Loss', sum(loss_list) / len(loss_list)) except: pass epoch_loss = running_loss / dataset_sizes[phase] # Computing AUC try: epoch_auc_ave = roc_auc_score(np.array(label_list), np.array(output_list)) epoch_auc = roc_auc_score(np.array(label_list), np.array(output_list), average=None) except ValueError: epoch_auc_ave = roc_auc_score(np.array(label_list)[:, :12], np.array(output_list)[:, :12]) * (12 / 13) + \ roc_auc_score(np.array(label_list)[:, 13], np.array(output_list)[:, 13]) * (1 / 13) epoch_auc = roc_auc_score(np.array(label_list)[:, :12], np.array(output_list)[:, :12], average=None) epoch_auc = np.append(epoch_auc, 0) epoch_auc = np.append(epoch_auc, roc_auc_score(np.array(label_list)[:, 13], np.array(output_list)[:, 13], average=None)) except: epoch_auc_ave = 0 epoch_auc = [0 for _ in range(len(class_names))] if phase == 'val': writer.add_scalar('loss/validation', epoch_loss, epoch) writer.add_scalar('auc/validation', epoch_auc_ave, epoch) if phase == 'train': writer.add_scalar('loss/train', epoch_loss, epoch) writer.add_scalar('auc/train', epoch_auc_ave, epoch) log_str = '' log_str += 'Loss: {:.4f} AUC: {:.4f} \n\n'.format( epoch_loss, epoch_auc_ave) for i, c in enumerate(class_names): log_str += '{}: {:.4f} \n'.format(c, epoch_auc[i]) log_str += '\n' if phase == 'val': print("\n\nValidation Phase ") else: print("\n\nTraining Phase ") print(log_str) writer.add_text('log', log_str, iter_num) print("Best validation average AUC :", best_auc_ave) print("Average AUC of current epoch :", epoch_auc_ave) # save model with best validation AUC if phase == 'val' and epoch_auc_ave > best_auc_ave: best_auc = epoch_auc print("Rewriting model with AUROC :", round(best_auc_ave, 4), " by model with AUROC : ", round(epoch_auc_ave, 4)) best_auc_ave = epoch_auc_ave print('Model saved to %s' % bestmodel_file) print("Saving the best checkpoint") SaveModel(epoch, model, optimizer, best_auc_ave, bestmodel_file) if phase == 'train' and epoch % 1 == 0: SaveModel(epoch, model, optimizer, best_auc_ave, checkpoint_file) print() time_elapsed = time.time() - since print('Training complete in {:.0f}m {:.0f}s'.format( time_elapsed // 60, time_elapsed % 60)) print('Best val AUC: {:4f}'.format(best_auc_ave)) print() try: for i, c in enumerate(class_names): print('{}: {:.4f} '.format(c, best_auc[i])) except: for i, c in enumerate(class_names): print('{}: {:.4f} '.format(c, epoch_auc[i])) # load best model weights to return model.load_state_dict(best_model_wts) return model def training_abnormal(model, args): """ Train the binary classification model. model: PyTorch model with model args: configuration file (argparse) return: train the returned the model """ print("____________________________________________") print("__________Binary Classification_____________") print("____________________________________________") writer = SummaryWriter(log_dir=os.path.join(args.log_dir, model_name(args))) optimizer = get_optimizer(model.parameters(), args) dataloaders, dataset_sizes, class_names = make_dataLoader_binary(args) criterion = torch.nn.BCELoss() if not os.path.exists(args.model_save_dir): os.makedirs(args.model_save_dir) best_auc_ave = 0.0 # to check if best validation accuracy epoch_inti = 1 # epoch starts from here best_model_wts = model.state_dict() iter_num = 0 # Prepare checkpoint file and model file to save and load from checkpoint_file = os.path.join(args.model_save_dir, str(model_name(args) + '_' + "checkpoint.pth")) bestmodel_file = os.path.join(args.model_save_dir, str(model_name(args) + '_' + "best_model.pth")) ''' Check for existing training results. If it existst, and the configuration is set to resume `config.resume_TIRG==True`, resume from previous training. If not, delete existing checkpoint.''' if os.path.exists(checkpoint_file): if args.resume: model, optimizer, epoch_inti, best_auc_ave = LoadModel(checkpoint_file, model, optimizer, epoch_inti, best_auc_ave) print("Checkpoint found! Resuming") else: pass since = time.time() for epoch in range(epoch_inti, args.epochs): print('Epoch {}/{}'.format(epoch, args.epochs - 1)) print('-' * 10) # Each epoch has a training and validation phase for phase in ['train', 'val']: # Only Validation in every 5 cycles if (phase == 'val') and (epoch % 1 != 0): continue if phase == 'train': model.train(True) # Set model to training mode else: model.train(False) # Set model to evaluate mode running_loss = 0.0 output_list = [] label_list = [] loss_list = [] # Iterate over data. for idx, data in enumerate(tqdm(dataloaders[phase])): images, labels, names = data images = images.to(device) labels = labels.to(device) labels = labels.unsqueeze(axis=1) # if labels.sum() == 0: # continue # calculate weight for loss P, N = 0, 0 for label in labels: for v in label: if int(v) == 1: P += 1 else: N += 1 if P != 0 and N != 0: BP = (P + N) / P BN = (P + N) / N weights = torch.tensor([BP, BN], dtype=torch.float).to(device) else: weights = None if phase == 'train': torch.set_grad_enabled(True) else: torch.set_grad_enabled(False) # zero the parameter gradients optimizer.zero_grad() outputs = model(images) # classification loss loss = weighted_BCELoss(outputs, labels, weights=weights) # loss = criterion(outputs, labels.type(torch.cuda.FloatTensor)) # backward + optimize only if in training phase if phase == 'train': loss.backward() optimizer.step() iter_num += 1 running_loss += loss.item() loss_list.append(loss.item()) outputs = outputs.detach().to('cpu').numpy() labels = labels.detach().to('cpu').numpy() for i in range(outputs.shape[0]): output_list.append(outputs[i].tolist()) label_list.append(labels[i].tolist()) if idx % 10 == 0: if phase == 'train': writer.add_scalar('Loss/Train', loss.item() / outputs.shape[0], iter_num) if idx % 100 == 0 and idx != 0: if phase == 'train': try: auc = roc_auc_score(np.array(label_list[-100 * args.batch_size:]), np.array(output_list[-100 * args.batch_size:])) print('\nAUC/Train', auc) print('Batch Loss', sum(loss_list) / len(loss_list)) print('Batch Accuracy', ((((np.array(output_list) > 0.5) * 1) == np.array(label_list)) * 1).mean()) loss_list = [] writer.add_scalar('AUC/Train', auc, iter_num) except: pass epoch_loss = running_loss / dataset_sizes[phase] epoch_auc_ave = roc_auc_score(np.array(label_list), np.array(output_list)) if phase == 'val': writer.add_scalar('Loss/Validation', epoch_loss, iter_num) writer.add_scalar('AUC/Validation', epoch_auc_ave, iter_num) log_str = '' log_str += 'Loss: {:.4f} AUC: {:.4f} \n\n'.format(epoch_loss, epoch_auc_ave) log_str += '\n' if phase == 'val': print("\n\nValidation Phase ") else: print("\n\nTraining Phase ") print(log_str) writer.add_text('log', log_str, iter_num) print("Best average AUC :", best_auc_ave) print("Average AUC of current epoch", epoch_auc_ave) # save model for validation if phase == 'val' and epoch_auc_ave > best_auc_ave: print("Rewriting model with accuracy", round(best_auc_ave, 4), " by ", round(epoch_auc_ave, 4)) best_auc_ave = epoch_auc_ave print('Model saved to %s' % bestmodel_file) print("Saving the best checkpoint") SaveModel(epoch, model, optimizer, best_auc_ave, bestmodel_file) writer.add_text('log', 'Model saved to %s\n\n' % (args.model_save_dir), iter_num) if phase == 'train' and epoch % 1 == 0: SaveModel(epoch, model, optimizer, best_auc_ave, checkpoint_file) print() time_elapsed = time.time() - since print('Training complete in {:.0f}m {:.0f}s'.format( time_elapsed // 60, time_elapsed % 60)) print('Best val AUC: {:4f}'.format(best_auc_ave)) print() # load best model weights model.load_state_dict(best_model_wts) return model def training_PCAM(model, args): """ Train the PCAM model. model: PyTorch model with model args: configuration file (argparse) return: train the returned the model """ writer = SummaryWriter(log_dir=os.path.join(args.log_dir, model_name(args))) writer.add_text('log', str(args), 0) if args.backbone == 'resnet50_wildcat': params = model.get_config_optim(args.lr, 0.5) else: params = model.parameters() optimizer = get_optimizer(params, args) dataloaders, dataset_sizes, class_names = make_dataLoader(args) if not os.path.exists(args.model_save_dir): os.makedirs(args.model_save_dir) best_auc_ave = 0.0 # to check if best validation accuracy epoch_inti = 1 # epoch starts from here best_model_wts = model.state_dict() best_auc = [] iter_num = 0 # Prepare checkpoint file and model file to save and load from checkpoint_file = os.path.join(args.model_save_dir, str(model_name(args) + '_' + "checkpoint.pth")) bestmodel_file = os.path.join(args.model_save_dir, str(model_name(args) + '_' + "best_model.pth")) ''' Check for existing training results. If it existst, and the configuration is set to resume `config.resume_TIRG==True`, resume from previous training. If not, delete existing checkpoint.''' if os.path.exists(checkpoint_file): if args.resume: model, optimizer, epoch_inti, best_auc_ave = LoadModel(checkpoint_file, model, optimizer, epoch_inti, best_auc_ave) print("Checkpoint found! Resuming") else: pass print(model) since = time.time() for epoch in range(epoch_inti, args.epochs + 1): print('Epoch {}/{}'.format(epoch, args.epochs)) print('-' * 10) for phase in ['train', 'val']: # Only Validation in every 5 cycles if (phase == 'val') and (epoch % 1 != 0): continue if phase == 'train': model.train(True) # Set model to training mode else: model.train(False) # Set model to evaluate mode running_loss = 0.0 output_list = [] label_list = [] lr = lr_schedule(args.lr, 0.1, epoch, [4, 8, 12]) for param_group in optimizer.param_groups: param_group['lr'] = lr # Iterate over data. for idx, data in enumerate(tqdm(dataloaders[phase])): images, labels, names = data images = images.to(device) labels = labels.to(device) if phase == 'train': torch.set_grad_enabled(True) else: torch.set_grad_enabled(False) # zero the parameter gradients optimizer.zero_grad() outputs, logit_map = model(images) # classification loss loss = 0 for t in range(args.num_classes): loss_t, acc_t = get_loss(outputs, labels, t, device, args) loss += loss_t # backward + optimize only if in training phase if phase == 'train': loss.backward() optimizer.step() iter_num += 1 running_loss += loss.item() outputs = outputs.detach().to('cpu').numpy() labels = labels.detach().to('cpu').numpy() for i in range(outputs.shape[0]): output_list.append(outputs[i].tolist()) label_list.append(labels[i].tolist()) if idx % 100 == 0 and idx != 0: if phase == 'train': writer.add_scalar('loss/train_batch', loss.item() / outputs.shape[0], iter_num) try: auc = roc_auc_score(np.array(label_list[-100 * args.batch_size:]), np.array(output_list[-100 * args.batch_size:])) writer.add_scalar('auc/train_batch', auc, iter_num) except: pass epoch_loss = running_loss / dataset_sizes[phase] try: epoch_auc_ave = roc_auc_score(np.array(label_list), np.array(output_list)) epoch_auc = roc_auc_score(np.array(label_list), np.array(output_list), average=None) except: epoch_auc_ave = 0 epoch_auc = [0 for _ in range(len(class_names))] if phase == 'val': writer.add_scalar('loss/validation', epoch_loss, epoch) writer.add_scalar('auc/validation', epoch_auc_ave, epoch) if phase == 'train': writer.add_scalar('loss/train', epoch_loss, epoch) writer.add_scalar('auc/train', epoch_auc_ave, epoch) log_str = '' log_str += 'Loss: {:.4f} AUC: {:.4f} \n\n'.format( epoch_loss, epoch_auc_ave) for i, c in enumerate(class_names): log_str += '{}: {:.4f} \n'.format(c, epoch_auc[i]) log_str += '\n' if phase == 'val': print("\n\nValidation Phase ") else: print("\n\nTraining Phase ") print(log_str) writer.add_text('log', log_str, iter_num) print("Best validation average AUC :", best_auc_ave) print("Average AUC of current epoch :", epoch_auc_ave) # save model for validation if phase == 'val' and epoch_auc_ave > best_auc_ave: best_auc = epoch_auc print("Rewriting model with AUROC :", round(best_auc_ave, 4), " by model with AUROC : ", round(epoch_auc_ave, 4)) best_auc_ave = epoch_auc_ave print('Model saved to %s' % bestmodel_file) print("Saving the best checkpoint") SaveModel(epoch, model, optimizer, best_auc_ave, bestmodel_file) if phase == 'train' and epoch % 1 == 0: SaveModel(epoch, model, optimizer, best_auc_ave, checkpoint_file) print() time_elapsed = time.time() - since print('Training complete in {:.0f}m {:.0f}s'.format( time_elapsed // 60, time_elapsed % 60)) print('Best val AUC: {:4f}'.format(best_auc_ave)) print() for i, c in enumerate(class_names): print('{}: {:.4f} '.format(c, best_auc[i])) # load best model weights model.load_state_dict(best_model_wts) return model
[ "utlis.utils.get_optimizer", "utlis.utils.LoadModel", "utlis.utils.SaveModel", "utlis.utils.model_name", "torch.nn.BCELoss", "os.path.exists", "numpy.append", "utlis.utils.make_dataLoader_chexpert", "utlis.utils.get_loss", "tqdm.tqdm", "torch.zeros_like", "utlis.utils.make_dataLoader_binary", "torch.cuda.is_available", "torch.set_grad_enabled", "utlis.utils.lr_schedule", "os.makedirs", "time.time", "utlis.utils.weighted_BCELoss", "numpy.where", "numpy.array", "utlis.utils.make_dataLoader", "torch.tensor" ]
[((995, 1022), 'utlis.utils.get_optimizer', 'get_optimizer', (['params', 'args'], {}), '(params, args)\n', (1008, 1022), False, 'from utlis.utils import get_optimizer, make_dataLoader, LoadModel, lr_schedule, make_dataLoader_chexpert\n'), ((2051, 2082), 'os.path.exists', 'os.path.exists', (['checkpoint_file'], {}), '(checkpoint_file)\n', (2065, 2082), False, 'import os\n'), ((2412, 2423), 'time.time', 'time.time', ([], {}), '()\n', (2421, 2423), False, 'import time\n'), ((10394, 10422), 'utlis.utils.make_dataLoader_binary', 'make_dataLoader_binary', (['args'], {}), '(args)\n', (10416, 10422), False, 'from utlis.utils import weighted_BCELoss, SaveModel, make_dataLoader_binary, get_loss\n'), ((10439, 10457), 'torch.nn.BCELoss', 'torch.nn.BCELoss', ([], {}), '()\n', (10455, 10457), False, 'import torch\n'), ((11202, 11233), 'os.path.exists', 'os.path.exists', (['checkpoint_file'], {}), '(checkpoint_file)\n', (11216, 11233), False, 'import os\n'), ((11546, 11557), 'time.time', 'time.time', ([], {}), '()\n', (11555, 11557), False, 'import time\n'), ((17450, 17477), 'utlis.utils.get_optimizer', 'get_optimizer', (['params', 'args'], {}), '(params, args)\n', (17463, 17477), False, 'from utlis.utils import get_optimizer, make_dataLoader, LoadModel, lr_schedule, make_dataLoader_chexpert\n'), ((17524, 17545), 'utlis.utils.make_dataLoader', 'make_dataLoader', (['args'], {}), '(args)\n', (17539, 17545), False, 'from utlis.utils import get_optimizer, make_dataLoader, LoadModel, lr_schedule, make_dataLoader_chexpert\n'), ((18309, 18340), 'os.path.exists', 'os.path.exists', (['checkpoint_file'], {}), '(checkpoint_file)\n', (18323, 18340), False, 'import os\n'), ((18670, 18681), 'time.time', 'time.time', ([], {}), '()\n', (18679, 18681), False, 'import time\n'), ((464, 489), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (487, 489), False, 'import torch\n'), ((1104, 1125), 'utlis.utils.make_dataLoader', 'make_dataLoader', (['args'], {}), '(args)\n', (1119, 1125), False, 'from utlis.utils import get_optimizer, make_dataLoader, LoadModel, lr_schedule, make_dataLoader_chexpert\n'), ((1298, 1333), 'os.path.exists', 'os.path.exists', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (1312, 1333), False, 'import os\n'), ((1343, 1375), 'os.makedirs', 'os.makedirs', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (1354, 1375), False, 'import os\n'), ((9308, 9319), 'time.time', 'time.time', ([], {}), '()\n', (9317, 9319), False, 'import time\n'), ((10470, 10505), 'os.path.exists', 'os.path.exists', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (10484, 10505), False, 'import os\n'), ((10515, 10547), 'os.makedirs', 'os.makedirs', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (10526, 10547), False, 'import os\n'), ((16695, 16706), 'time.time', 'time.time', ([], {}), '()\n', (16704, 16706), False, 'import time\n'), ((17558, 17593), 'os.path.exists', 'os.path.exists', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (17572, 17593), False, 'import os\n'), ((17603, 17635), 'os.makedirs', 'os.makedirs', (['args.model_save_dir'], {}), '(args.model_save_dir)\n', (17614, 17635), False, 'import os\n'), ((23368, 23379), 'time.time', 'time.time', ([], {}), '()\n', (23377, 23379), False, 'import time\n'), ((1214, 1244), 'utlis.utils.make_dataLoader_chexpert', 'make_dataLoader_chexpert', (['args'], {}), '(args)\n', (1238, 1244), False, 'from utlis.utils import get_optimizer, make_dataLoader, LoadModel, lr_schedule, make_dataLoader_chexpert\n'), ((2165, 2235), 'utlis.utils.LoadModel', 'LoadModel', (['checkpoint_file', 'model', 'optimizer', 'epoch_inti', 'best_auc_ave'], {}), '(checkpoint_file, model, optimizer, epoch_inti, best_auc_ave)\n', (2174, 2235), False, 'from utlis.utils import get_optimizer, make_dataLoader, LoadModel, lr_schedule, make_dataLoader_chexpert\n'), ((11316, 11386), 'utlis.utils.LoadModel', 'LoadModel', (['checkpoint_file', 'model', 'optimizer', 'epoch_inti', 'best_auc_ave'], {}), '(checkpoint_file, model, optimizer, epoch_inti, best_auc_ave)\n', (11325, 11386), False, 'from utlis.utils import get_optimizer, make_dataLoader, LoadModel, lr_schedule, make_dataLoader_chexpert\n'), ((18423, 18493), 'utlis.utils.LoadModel', 'LoadModel', (['checkpoint_file', 'model', 'optimizer', 'epoch_inti', 'best_auc_ave'], {}), '(checkpoint_file, model, optimizer, epoch_inti, best_auc_ave)\n', (18432, 18493), False, 'from utlis.utils import get_optimizer, make_dataLoader, LoadModel, lr_schedule, make_dataLoader_chexpert\n'), ((19268, 19312), 'utlis.utils.lr_schedule', 'lr_schedule', (['args.lr', '(0.1)', 'epoch', '[4, 8, 12]'], {}), '(args.lr, 0.1, epoch, [4, 8, 12])\n', (19279, 19312), False, 'from utlis.utils import get_optimizer, make_dataLoader, LoadModel, lr_schedule, make_dataLoader_chexpert\n'), ((775, 791), 'utlis.utils.model_name', 'model_name', (['args'], {}), '(args)\n', (785, 791), False, 'from utlis.utils import model_name, select_model\n'), ((3024, 3048), 'tqdm.tqdm', 'tqdm', (['dataloaders[phase]'], {}), '(dataloaders[phase])\n', (3028, 3048), False, 'from tqdm import tqdm\n'), ((9071, 9135), 'utlis.utils.SaveModel', 'SaveModel', (['epoch', 'model', 'optimizer', 'best_auc_ave', 'bestmodel_file'], {}), '(epoch, model, optimizer, best_auc_ave, bestmodel_file)\n', (9080, 9135), False, 'from utlis.utils import weighted_BCELoss, SaveModel, make_dataLoader_binary, get_loss\n'), ((9205, 9270), 'utlis.utils.SaveModel', 'SaveModel', (['epoch', 'model', 'optimizer', 'best_auc_ave', 'checkpoint_file'], {}), '(epoch, model, optimizer, best_auc_ave, checkpoint_file)\n', (9214, 9270), False, 'from utlis.utils import weighted_BCELoss, SaveModel, make_dataLoader_binary, get_loss\n'), ((10273, 10289), 'utlis.utils.model_name', 'model_name', (['args'], {}), '(args)\n', (10283, 10289), False, 'from utlis.utils import model_name, select_model\n'), ((12285, 12309), 'tqdm.tqdm', 'tqdm', (['dataloaders[phase]'], {}), '(dataloaders[phase])\n', (12289, 12309), False, 'from tqdm import tqdm\n'), ((13449, 13499), 'utlis.utils.weighted_BCELoss', 'weighted_BCELoss', (['outputs', 'labels'], {'weights': 'weights'}), '(outputs, labels, weights=weights)\n', (13465, 13499), False, 'from utlis.utils import weighted_BCELoss, SaveModel, make_dataLoader_binary, get_loss\n'), ((15255, 15275), 'numpy.array', 'np.array', (['label_list'], {}), '(label_list)\n', (15263, 15275), True, 'import numpy as np\n'), ((15277, 15298), 'numpy.array', 'np.array', (['output_list'], {}), '(output_list)\n', (15285, 15298), True, 'import numpy as np\n'), ((16360, 16424), 'utlis.utils.SaveModel', 'SaveModel', (['epoch', 'model', 'optimizer', 'best_auc_ave', 'bestmodel_file'], {}), '(epoch, model, optimizer, best_auc_ave, bestmodel_file)\n', (16369, 16424), False, 'from utlis.utils import weighted_BCELoss, SaveModel, make_dataLoader_binary, get_loss\n'), ((16592, 16657), 'utlis.utils.SaveModel', 'SaveModel', (['epoch', 'model', 'optimizer', 'best_auc_ave', 'checkpoint_file'], {}), '(epoch, model, optimizer, best_auc_ave, checkpoint_file)\n', (16601, 16657), False, 'from utlis.utils import weighted_BCELoss, SaveModel, make_dataLoader_binary, get_loss\n'), ((17230, 17246), 'utlis.utils.model_name', 'model_name', (['args'], {}), '(args)\n', (17240, 17246), False, 'from utlis.utils import model_name, select_model\n'), ((19508, 19532), 'tqdm.tqdm', 'tqdm', (['dataloaders[phase]'], {}), '(dataloaders[phase])\n', (19512, 19532), False, 'from tqdm import tqdm\n'), ((23131, 23195), 'utlis.utils.SaveModel', 'SaveModel', (['epoch', 'model', 'optimizer', 'best_auc_ave', 'bestmodel_file'], {}), '(epoch, model, optimizer, best_auc_ave, bestmodel_file)\n', (23140, 23195), False, 'from utlis.utils import weighted_BCELoss, SaveModel, make_dataLoader_binary, get_loss\n'), ((23265, 23330), 'utlis.utils.SaveModel', 'SaveModel', (['epoch', 'model', 'optimizer', 'best_auc_ave', 'checkpoint_file'], {}), '(epoch, model, optimizer, best_auc_ave, checkpoint_file)\n', (23274, 23330), False, 'from utlis.utils import weighted_BCELoss, SaveModel, make_dataLoader_binary, get_loss\n'), ((1690, 1706), 'utlis.utils.model_name', 'model_name', (['args'], {}), '(args)\n', (1700, 1706), False, 'from utlis.utils import model_name, select_model\n'), ((1793, 1809), 'utlis.utils.model_name', 'model_name', (['args'], {}), '(args)\n', (1803, 1809), False, 'from utlis.utils import model_name, select_model\n'), ((3409, 3437), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(True)'], {}), '(True)\n', (3431, 3437), False, 'import torch\n'), ((3480, 3509), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (3502, 3509), False, 'import torch\n'), ((4331, 4381), 'utlis.utils.weighted_BCELoss', 'weighted_BCELoss', (['outputs', 'labels'], {'weights': 'weights'}), '(outputs, labels, weights=weights)\n', (4347, 4381), False, 'from utlis.utils import weighted_BCELoss, SaveModel, make_dataLoader_binary, get_loss\n'), ((4436, 4470), 'torch.nn.BCELoss', 'torch.nn.BCELoss', ([], {'reduction': '"""none"""'}), "(reduction='none')\n", (4452, 4470), False, 'import torch\n'), ((6771, 6791), 'numpy.array', 'np.array', (['label_list'], {}), '(label_list)\n', (6779, 6791), True, 'import numpy as np\n'), ((6793, 6814), 'numpy.array', 'np.array', (['output_list'], {}), '(output_list)\n', (6801, 6814), True, 'import numpy as np\n'), ((6858, 6878), 'numpy.array', 'np.array', (['label_list'], {}), '(label_list)\n', (6866, 6878), True, 'import numpy as np\n'), ((6880, 6901), 'numpy.array', 'np.array', (['output_list'], {}), '(output_list)\n', (6888, 6901), True, 'import numpy as np\n'), ((7332, 7355), 'numpy.append', 'np.append', (['epoch_auc', '(0)'], {}), '(epoch_auc, 0)\n', (7341, 7355), True, 'import numpy as np\n'), ((10842, 10858), 'utlis.utils.model_name', 'model_name', (['args'], {}), '(args)\n', (10852, 10858), False, 'from utlis.utils import model_name, select_model\n'), ((10945, 10961), 'utlis.utils.model_name', 'model_name', (['args'], {}), '(args)\n', (10955, 10961), False, 'from utlis.utils import model_name, select_model\n'), ((13161, 13189), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(True)'], {}), '(True)\n', (13183, 13189), False, 'import torch\n'), ((13232, 13261), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (13254, 13261), False, 'import torch\n'), ((17948, 17964), 'utlis.utils.model_name', 'model_name', (['args'], {}), '(args)\n', (17958, 17964), False, 'from utlis.utils import model_name, select_model\n'), ((18051, 18067), 'utlis.utils.model_name', 'model_name', (['args'], {}), '(args)\n', (18061, 18067), False, 'from utlis.utils import model_name, select_model\n'), ((19725, 19753), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(True)'], {}), '(True)\n', (19747, 19753), False, 'import torch\n'), ((19796, 19825), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (19818, 19825), False, 'import torch\n'), ((20113, 20155), 'utlis.utils.get_loss', 'get_loss', (['outputs', 'labels', 't', 'device', 'args'], {}), '(outputs, labels, t, device, args)\n', (20121, 20155), False, 'from utlis.utils import weighted_BCELoss, SaveModel, make_dataLoader_binary, get_loss\n'), ((21418, 21438), 'numpy.array', 'np.array', (['label_list'], {}), '(label_list)\n', (21426, 21438), True, 'import numpy as np\n'), ((21440, 21461), 'numpy.array', 'np.array', (['output_list'], {}), '(output_list)\n', (21448, 21461), True, 'import numpy as np\n'), ((21505, 21525), 'numpy.array', 'np.array', (['label_list'], {}), '(label_list)\n', (21513, 21525), True, 'import numpy as np\n'), ((21527, 21548), 'numpy.array', 'np.array', (['output_list'], {}), '(output_list)\n', (21535, 21548), True, 'import numpy as np\n'), ((3954, 3995), 'torch.tensor', 'torch.tensor', (['[BP, BN]'], {'dtype': 'torch.float'}), '([BP, BN], dtype=torch.float)\n', (3966, 3995), False, 'import torch\n'), ((7229, 7249), 'numpy.array', 'np.array', (['label_list'], {}), '(label_list)\n', (7237, 7249), True, 'import numpy as np\n'), ((7259, 7280), 'numpy.array', 'np.array', (['output_list'], {}), '(output_list)\n', (7267, 7280), True, 'import numpy as np\n'), ((12993, 13034), 'torch.tensor', 'torch.tensor', (['[BP, BN]'], {'dtype': 'torch.float'}), '([BP, BN], dtype=torch.float)\n', (13005, 13034), False, 'import torch\n'), ((4728, 4750), 'torch.zeros_like', 'torch.zeros_like', (['loss'], {}), '(loss)\n', (4744, 4750), False, 'import torch\n'), ((5757, 5796), 'numpy.where', 'np.where', (['(labels[i] >= 0)', 'outputs[i]', '(0)'], {}), '(labels[i] >= 0, outputs[i], 0)\n', (5765, 5796), True, 'import numpy as np\n'), ((5845, 5883), 'numpy.where', 'np.where', (['(labels[i] >= 0)', 'labels[i]', '(0)'], {}), '(labels[i] >= 0, labels[i], 0)\n', (5853, 5883), True, 'import numpy as np\n'), ((6195, 6240), 'numpy.array', 'np.array', (['label_list[-100 * args.batch_size:]'], {}), '(label_list[-100 * args.batch_size:])\n', (6203, 6240), True, 'import numpy as np\n'), ((6290, 6336), 'numpy.array', 'np.array', (['output_list[-100 * args.batch_size:]'], {}), '(output_list[-100 * args.batch_size:])\n', (6298, 6336), True, 'import numpy as np\n'), ((7419, 7439), 'numpy.array', 'np.array', (['label_list'], {}), '(label_list)\n', (7427, 7439), True, 'import numpy as np\n'), ((7448, 7469), 'numpy.array', 'np.array', (['output_list'], {}), '(output_list)\n', (7456, 7469), True, 'import numpy as np\n'), ((14509, 14554), 'numpy.array', 'np.array', (['label_list[-100 * args.batch_size:]'], {}), '(label_list[-100 * args.batch_size:])\n', (14517, 14554), True, 'import numpy as np\n'), ((14604, 14650), 'numpy.array', 'np.array', (['output_list[-100 * args.batch_size:]'], {}), '(output_list[-100 * args.batch_size:])\n', (14612, 14650), True, 'import numpy as np\n'), ((21005, 21050), 'numpy.array', 'np.array', (['label_list[-100 * args.batch_size:]'], {}), '(label_list[-100 * args.batch_size:])\n', (21013, 21050), True, 'import numpy as np\n'), ((21100, 21146), 'numpy.array', 'np.array', (['output_list[-100 * args.batch_size:]'], {}), '(output_list[-100 * args.batch_size:])\n', (21108, 21146), True, 'import numpy as np\n'), ((5169, 5196), 'torch.zeros_like', 'torch.zeros_like', (['loss_temp'], {}), '(loss_temp)\n', (5185, 5196), False, 'import torch\n'), ((6994, 7014), 'numpy.array', 'np.array', (['label_list'], {}), '(label_list)\n', (7002, 7014), True, 'import numpy as np\n'), ((7024, 7045), 'numpy.array', 'np.array', (['output_list'], {}), '(output_list)\n', (7032, 7045), True, 'import numpy as np\n'), ((7117, 7137), 'numpy.array', 'np.array', (['label_list'], {}), '(label_list)\n', (7125, 7137), True, 'import numpy as np\n'), ((7146, 7167), 'numpy.array', 'np.array', (['output_list'], {}), '(output_list)\n', (7154, 7167), True, 'import numpy as np\n'), ((14934, 14954), 'numpy.array', 'np.array', (['label_list'], {}), '(label_list)\n', (14942, 14954), True, 'import numpy as np\n'), ((14843, 14864), 'numpy.array', 'np.array', (['output_list'], {}), '(output_list)\n', (14851, 14864), True, 'import numpy as np\n')]
''' 1、借鉴老师代码V1 2、解读他的代码思路 - trian_labels.csv 的读取 - 3、我未曾用过的库 - glob - 可使用相对路径的库?| 可按照Unix终端所使用的那般规则来查询文件等 ''' import os import pdb import cv2 import time import codecs import random import argparse import numpy as np import pandas as pd import seaborn as sns from tqdm import tqdm from loguru import logger from colorama import Fore, Back, Style r_ = Fore.WHITE import torch from torch import nn, optim from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter import torchvision from torchvision import transforms from efficientnet_pytorch import EfficientNet, utils from sklearn import metrics from sklearn.model_selection import StratifiedKFold import plotly.express as px import plotly.graph_objects as go import plotly.figure_factory as ff from plotly.offline import iplot from plotly.subplots import make_subplots # from skimage import color, data # from skimage.util import random_noise # from skimage.exposure import adjust_gamma # from skimage.io import imshow, imread, imsave # from skimage.transform import rotate, AffineTransform, warp, rescale, resize, downscale_local_mean from snippets_dataset import SnippetsDataset, SnippetsDatasetTest logger.add('/home/alben/code/kaggle_SETI_search_ET/log/train.log', rotation="1 day") device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") def set_seed(seed=123): '''Sets the seed of the entire notebook so results are the same every time we run. This is for REPRODUCIBILITY.''' np.random.seed(seed) random_state = np.random.RandomState(seed) random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False os.environ['PYTHONHASHSEED'] = str(seed) return random_state random_state = set_seed() class EfficientNetV2(nn.Module): def __init__(self, backbone, out_dim): super(EfficientNetV2, self).__init__() self.efficientnet = EfficientNet.from_pretrained(backbone) fc_in_feature = self.efficientnet._fc.in_features self.efficientnet._fc = nn.Linear(fc_in_feature, out_dim) self.conv1_6_3 = nn.Conv2d(6, 3, kernel_size=3, stride=1, padding=3, bias=False) def forward(self, x): x = self.conv1_6_3(x) x = self.efficientnet(x) return x def mixup_data(x, y, alpha=1.0, use_cuda=True): ''' Returns mixed inputs, pairs of targets, and lambda ''' if alpha > 0: lam = np.random.beta(alpha, alpha) else: lam = 1 batch_size = x.size()[0] index = torch.randperm(batch_size) if use_cuda: index = index.cuda() mixed_x = lam * x + (1 - lam) * x[index, :] y_a, y_b = y, y[index] return mixed_x, y_a, y_b, lam def mixup_criterion(criterion, pred, y_a, y_b, lam): return lam * criterion(pred, y_a.view(-1, 1)) + (1 - lam) * criterion(pred, y_b.view(-1, 1)) def train(epoch, model, train_loader, optimizer, loss_fn, lr_scheduler): losses_train, accuracy_train = [], [] Y, y_pred = [], [] model.train() for i, data in enumerate(train_loader): s_t = time.time() images, labels = data images, labels = images.type(torch.FloatTensor), labels.type(torch.FloatTensor) images, labels = images.to(device), labels.to(device) batch_n, crops_n, C, H, W = images.shape images = images.view(-1, C, H, W) labels = labels.repeat_interleave(crops_n) outputs = model(images).squeeze(1) optimizer.zero_grad() loss = loss_fn(outputs, labels) loss.backward() optimizer.step() losses_train.append(loss.item()) Y.extend(labels.detach().cpu().numpy().tolist()) y_pred.extend(outputs.detach().cpu().numpy().tolist()) if (i + 1) % PRINT_INTERVAL == 0: logger.info(f'Train - Epoch = {epoch:3}; Iteration = {i:3}; Len = {len(train_loader):3}; Loss = {np.mean(losses_train):8.4}; Acc = {metrics.roc_auc_score(Y, y_pred):8.4}; Interval = {time.time() - s_t:8.4}') lr_scheduler.step() return losses_train, metrics.roc_auc_score(Y, y_pred) def valid(epoch, model, valide_loader): losses_valid, accuracy_valid = [], [] Y, y_pred = [], [] model.eval() with torch.no_grad(): for i, data in enumerate(valide_loader): s_t = time.time() images, labels = data images, labels = images.type(torch.FloatTensor), labels.type(torch.FloatTensor) images, labels = images.to(device), labels.to(device) batch_n, crops_n, C, H, W = images.shape images = images.view(-1, C, H, W) outputs = model(images).squeeze(1) outputs_avg = outputs.view(batch_n, crops_n).mean(1) loss = loss_fn(outputs_avg, labels) losses_valid.append(loss.item()) Y.extend(labels.detach().cpu().numpy().tolist()) y_pred.extend(outputs_avg.detach().cpu().numpy().tolist()) logger.info(f'Valid - Epoch = {epoch:3}; Iteration = {i:3}; Len = {len(valide_loader):3}; Loss = {np.mean(losses_valid):8.4}; Acc = {metrics.roc_auc_score(Y, y_pred):8.4}; Interval = {time.time() - s_t:8.4}') return losses_valid, metrics.roc_auc_score(Y, y_pred) def test(epoch, model, test_loader, writer): flag = 0 model.eval() with torch.no_grad(): for i, data in enumerate(test_loader): images = data images = images.type(torch.FloatTensor) images = images.to(device) batch_n, crops_n, C, H, W = images.shape grid_images = images[:, 0, :, :, :] images = images.view(-1, C, H, W) outputs = model(images) outputs_avg = outputs.view(batch_n, crops_n).mean(1) if flag == 0: grid_images = grid_images.contiguous().view(-1, 1, grid_images.shape[-2], grid_images.shape[-1]) grid = torchvision.utils.make_grid(grid_images, nrow=6) writer.add_image(f'test_{epoch}_{i}', grid) flag = 1 logger.info(f'Test - Epoch = {epoch:3}; predict = {outputs_avg}') def transforms_(data): data = torch.from_numpy(data) ten_datas = transforms.TenCrop(224, vertical_flip=False)(data) return torch.stack(ten_datas) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--ver', type=str, help='procedure ver', default='0') parser.add_argument('--comment', type=str, help='version comment', default='first_version') args = parser.parse_args() ver = args.ver comment = args.comment logger.info(f'{"*" * 25} version = {ver}; comment = {comment} {"*" * 25}') EPOCH = 4 BATCH_SIZE = 10 PRINT_INTERVAL = 1000 TRAIN_DATA_PATH = '/home/alben/data/cv_listen_2021_06/train' TEST_DATA_PATH = '/home/alben/data/cv_listen_2021_06/test' LABELS_CSV = '/home/alben/data/cv_listen_2021_06/train_labels.csv' BOARD_PATH = '/home/alben/code/kaggle_SETI_search_ET/board/train' MODEL_SAVE_PATH = '/home/alben/code/kaggle_SETI_search_ET/model_state' LR = 0.01 LR_DECAY_STEP = 6 NUM_CLASSES = 1 baseline_name = 'efficientnet-b3' normalize_mean, normalize_std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225] IMG_H_W = (273, 256) writer = SummaryWriter(log_dir=BOARD_PATH, flush_secs=60) train_data = SnippetsDataset(TRAIN_DATA_PATH, LABELS_CSV, 'train', transforms_) train_loader = DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True) valid_data = SnippetsDataset(TRAIN_DATA_PATH, LABELS_CSV, 'valid', transforms_) valid_loader = DataLoader(dataset=valid_data, batch_size=BATCH_SIZE, shuffle=True) test_data = SnippetsDatasetTest(TEST_DATA_PATH, transforms_) test_loader = DataLoader(dataset=test_data, batch_size=len(test_data)) # model = EfficientNet.from_pretrained(baseline_name) # model._conv_stem = first_layer # fc_in_feature = model._fc.in_features # model._fc = nn.Linear(fc_in_feature, NUM_CLASSES, bias=True) model = EfficientNetV2(baseline_name, NUM_CLASSES) model.to(device) loss_fn = nn.BCEWithLogitsLoss() optimizer = optim.SGD(model.parameters(), lr=LR, momentum=0.9) lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=LR_DECAY_STEP, gamma=0.5) for epoch in tqdm(range(EPOCH)): losses_train, acc_train = train(epoch, model, train_loader, optimizer, loss_fn, lr_scheduler) losses_valid, acc_valid = valid(epoch, model, valid_loader) writer.add_scalars(f'loss_{ver}', {'train': np.mean(losses_train), 'valid': np.mean(losses_valid)}, epoch) writer.add_scalars(f'accuracy_{ver}', {'train': acc_train, 'valid': acc_valid}, epoch) test(epoch, model, test_loader, writer) torch.save(model.state_dict(), f'{MODEL_SAVE_PATH}/vggnet_cat_dog_0525_{epoch}.pth') logger.info(f'Summary - Epoch = {epoch:3}; loss_train = {np.mean(losses_train):8.4}; loss_valid = {np.mean(losses_valid):8.4}; acc_train = {acc_train:8.4}; acc_valid = {acc_valid:8.4}') writer.close()
[ "numpy.random.seed", "argparse.ArgumentParser", "torch.optim.lr_scheduler.StepLR", "numpy.mean", "torch.no_grad", "loguru.logger.add", "torch.utils.data.DataLoader", "numpy.random.RandomState", "random.seed", "torch.utils.tensorboard.SummaryWriter", "torch.nn.Linear", "torch.nn.BCEWithLogitsLoss", "efficientnet_pytorch.EfficientNet.from_pretrained", "numpy.random.beta", "torch.manual_seed", "torch.nn.Conv2d", "torch.cuda.manual_seed", "sklearn.metrics.roc_auc_score", "torch.randperm", "snippets_dataset.SnippetsDataset", "torch.cuda.is_available", "torch.from_numpy", "torchvision.transforms.TenCrop", "torch.stack", "time.time", "torchvision.utils.make_grid", "loguru.logger.info", "snippets_dataset.SnippetsDatasetTest" ]
[((1197, 1286), 'loguru.logger.add', 'logger.add', (['"""/home/alben/code/kaggle_SETI_search_ET/log/train.log"""'], {'rotation': '"""1 day"""'}), "('/home/alben/code/kaggle_SETI_search_ET/log/train.log', rotation\n ='1 day')\n", (1207, 1286), False, 'from loguru import logger\n'), ((1507, 1527), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (1521, 1527), True, 'import numpy as np\n'), ((1547, 1574), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (1568, 1574), True, 'import numpy as np\n'), ((1579, 1596), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (1590, 1596), False, 'import random\n'), ((1601, 1624), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (1618, 1624), False, 'import torch\n'), ((1629, 1657), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['seed'], {}), '(seed)\n', (1651, 1657), False, 'import torch\n'), ((2605, 2631), 'torch.randperm', 'torch.randperm', (['batch_size'], {}), '(batch_size)\n', (2619, 2631), False, 'import torch\n'), ((6225, 6247), 'torch.from_numpy', 'torch.from_numpy', (['data'], {}), '(data)\n', (6241, 6247), False, 'import torch\n'), ((6326, 6348), 'torch.stack', 'torch.stack', (['ten_datas'], {}), '(ten_datas)\n', (6337, 6348), False, 'import torch\n'), ((6391, 6416), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (6414, 6416), False, 'import argparse\n'), ((6816, 6890), 'loguru.logger.info', 'logger.info', (['f"""{\'*\' * 25} version = {ver}; comment = {comment} {\'*\' * 25}"""'], {}), '(f"{\'*\' * 25} version = {ver}; comment = {comment} {\'*\' * 25}")\n', (6827, 6890), False, 'from loguru import logger\n'), ((7510, 7558), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', ([], {'log_dir': 'BOARD_PATH', 'flush_secs': '(60)'}), '(log_dir=BOARD_PATH, flush_secs=60)\n', (7523, 7558), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((7577, 7643), 'snippets_dataset.SnippetsDataset', 'SnippetsDataset', (['TRAIN_DATA_PATH', 'LABELS_CSV', '"""train"""', 'transforms_'], {}), "(TRAIN_DATA_PATH, LABELS_CSV, 'train', transforms_)\n", (7592, 7643), False, 'from snippets_dataset import SnippetsDataset, SnippetsDatasetTest\n'), ((7663, 7730), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'train_data', 'batch_size': 'BATCH_SIZE', 'shuffle': '(True)'}), '(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)\n', (7673, 7730), False, 'from torch.utils.data import DataLoader\n'), ((7809, 7875), 'snippets_dataset.SnippetsDataset', 'SnippetsDataset', (['TRAIN_DATA_PATH', 'LABELS_CSV', '"""valid"""', 'transforms_'], {}), "(TRAIN_DATA_PATH, LABELS_CSV, 'valid', transforms_)\n", (7824, 7875), False, 'from snippets_dataset import SnippetsDataset, SnippetsDatasetTest\n'), ((7895, 7962), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'valid_data', 'batch_size': 'BATCH_SIZE', 'shuffle': '(True)'}), '(dataset=valid_data, batch_size=BATCH_SIZE, shuffle=True)\n', (7905, 7962), False, 'from torch.utils.data import DataLoader\n'), ((8040, 8088), 'snippets_dataset.SnippetsDatasetTest', 'SnippetsDatasetTest', (['TEST_DATA_PATH', 'transforms_'], {}), '(TEST_DATA_PATH, transforms_)\n', (8059, 8088), False, 'from snippets_dataset import SnippetsDataset, SnippetsDatasetTest\n'), ((8491, 8513), 'torch.nn.BCEWithLogitsLoss', 'nn.BCEWithLogitsLoss', ([], {}), '()\n', (8511, 8513), False, 'from torch import nn, optim\n'), ((8600, 8678), 'torch.optim.lr_scheduler.StepLR', 'torch.optim.lr_scheduler.StepLR', (['optimizer'], {'step_size': 'LR_DECAY_STEP', 'gamma': '(0.5)'}), '(optimizer, step_size=LR_DECAY_STEP, gamma=0.5)\n', (8631, 8678), False, 'import torch\n'), ((1316, 1341), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1339, 1341), False, 'import torch\n'), ((1996, 2034), 'efficientnet_pytorch.EfficientNet.from_pretrained', 'EfficientNet.from_pretrained', (['backbone'], {}), '(backbone)\n', (2024, 2034), False, 'from efficientnet_pytorch import EfficientNet, utils\n'), ((2125, 2158), 'torch.nn.Linear', 'nn.Linear', (['fc_in_feature', 'out_dim'], {}), '(fc_in_feature, out_dim)\n', (2134, 2158), False, 'from torch import nn, optim\n'), ((2184, 2247), 'torch.nn.Conv2d', 'nn.Conv2d', (['(6)', '(3)'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(3)', 'bias': '(False)'}), '(6, 3, kernel_size=3, stride=1, padding=3, bias=False)\n', (2193, 2247), False, 'from torch import nn, optim\n'), ((2508, 2536), 'numpy.random.beta', 'np.random.beta', (['alpha', 'alpha'], {}), '(alpha, alpha)\n', (2522, 2536), True, 'import numpy as np\n'), ((3157, 3168), 'time.time', 'time.time', ([], {}), '()\n', (3166, 3168), False, 'import time\n'), ((4129, 4161), 'sklearn.metrics.roc_auc_score', 'metrics.roc_auc_score', (['Y', 'y_pred'], {}), '(Y, y_pred)\n', (4150, 4161), False, 'from sklearn import metrics\n'), ((4296, 4311), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4309, 4311), False, 'import torch\n'), ((5265, 5297), 'sklearn.metrics.roc_auc_score', 'metrics.roc_auc_score', (['Y', 'y_pred'], {}), '(Y, y_pred)\n', (5286, 5297), False, 'from sklearn import metrics\n'), ((5384, 5399), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (5397, 5399), False, 'import torch\n'), ((6264, 6308), 'torchvision.transforms.TenCrop', 'transforms.TenCrop', (['(224)'], {'vertical_flip': '(False)'}), '(224, vertical_flip=False)\n', (6282, 6308), False, 'from torchvision import transforms\n'), ((4380, 4391), 'time.time', 'time.time', ([], {}), '()\n', (4389, 4391), False, 'import time\n'), ((6123, 6188), 'loguru.logger.info', 'logger.info', (['f"""Test - Epoch = {epoch:3}; predict = {outputs_avg}"""'], {}), "(f'Test - Epoch = {epoch:3}; predict = {outputs_avg}')\n", (6134, 6188), False, 'from loguru import logger\n'), ((5977, 6025), 'torchvision.utils.make_grid', 'torchvision.utils.make_grid', (['grid_images'], {'nrow': '(6)'}), '(grid_images, nrow=6)\n', (6004, 6025), False, 'import torchvision\n'), ((8939, 8960), 'numpy.mean', 'np.mean', (['losses_train'], {}), '(losses_train)\n', (8946, 8960), True, 'import numpy as np\n'), ((9014, 9035), 'numpy.mean', 'np.mean', (['losses_valid'], {}), '(losses_valid)\n', (9021, 9035), True, 'import numpy as np\n'), ((5129, 5150), 'numpy.mean', 'np.mean', (['losses_valid'], {}), '(losses_valid)\n', (5136, 5150), True, 'import numpy as np\n'), ((5164, 5196), 'sklearn.metrics.roc_auc_score', 'metrics.roc_auc_score', (['Y', 'y_pred'], {}), '(Y, y_pred)\n', (5185, 5196), False, 'from sklearn import metrics\n'), ((9393, 9414), 'numpy.mean', 'np.mean', (['losses_train'], {}), '(losses_train)\n', (9400, 9414), True, 'import numpy as np\n'), ((9435, 9456), 'numpy.mean', 'np.mean', (['losses_valid'], {}), '(losses_valid)\n', (9442, 9456), True, 'import numpy as np\n'), ((3969, 3990), 'numpy.mean', 'np.mean', (['losses_train'], {}), '(losses_train)\n', (3976, 3990), True, 'import numpy as np\n'), ((4004, 4036), 'sklearn.metrics.roc_auc_score', 'metrics.roc_auc_score', (['Y', 'y_pred'], {}), '(Y, y_pred)\n', (4025, 4036), False, 'from sklearn import metrics\n'), ((5215, 5226), 'time.time', 'time.time', ([], {}), '()\n', (5224, 5226), False, 'import time\n'), ((4055, 4066), 'time.time', 'time.time', ([], {}), '()\n', (4064, 4066), False, 'import time\n')]
import glob import os.path as pth import numpy as np import collections import matplotlib.pylab as plt import keras.utils class RgbdSetElement(object): def __init__(self, npz_path): self.npz_path = npz_path self.npz_file = pth.basename(npz_path) self.set_name = self.npz_file.split("_", maxsplit=1)[0] self.image_cnt = self.__image_count_from_file(npz_path) self.current_rbgd_ary = False def __image_count_from_file(self, npz_path): with np.load(npz_path) as f: rgbd_ary = f["rgbd_ary"] return rgbd_ary.shape[0] def read_next_batch(self, batch_size): if isinstance(self.current_rbgd_ary, bool) and not self.current_rbgd_ary: f = np.load(self.npz_path) self.current_rbgd_ary = f["rgbd_ary"] self.current_batch_idx = 0 try: current_batch = self.current_rbgd_ary[self.current_batch_idx*batch_size:(self.current_batch_idx + 1)*batch_size, :, :, :] if (current_batch.shape[0] < batch_size): raise ValueError() self.current_batch_idx += 1 return current_batch except: self.current_rbgd_ary = False self.current_batch_idx = False return False class RgbdSet(object): def __init__(self): self.set_name = False self.elements = list() @property def image_count(self): if not self.set_name or not self.elements: raise ValueError("Invalid state, set has no name or no elements") return sum([e.image_cnt for e in self.elements]) def append(self, set_el): if not self.set_name: self.set_name = set_el.set_name if self.set_name != set_el.set_name: raise ValueError("Set name and element set name does not match") self.elements.append(set_el) return self class RgbdSetSequence(keras.utils.Sequence): def __init__(self, rgbd_set:RgbdSet, batch_size, validation_split=0.2, is_validation=False, max_len=25000): self.rgbd_set = rgbd_set self.batch_size = batch_size self.validation_split = validation_split self.is_validation = is_validation self.max_len = max_len self.image_cnt = self.__calculate_image_count() self.element_queue = self.__copy_elements(rgbd_set, validation_split, is_validation) def __calculate_image_count(self): N = min(self.rgbd_set.image_count, self.max_len) if self.is_validation: return N * self.validation_split else: return N * (1. - self.validation_split) def __len__(self): return int(np.ceil(self.image_cnt / float(self.batch_size))) @property def current_element(self): return self.element_queue[0] if self.element_queue else False def __getitem__(self, idx): if not self.current_element: return False next_batch = self.current_element.read_next_batch(self.batch_size) if isinstance(next_batch, bool) and next_batch == False: self.element_queue.pop() return self.__getitem__(idx) return next_batch def __copy_elements(self, rgbd_set, validation_split, is_validation): all_els = reversed(rgbd_set.elements) if is_validation else rgbd_set.elements cpy_els = [] M = 0 for el in all_els: if M >= self.image_cnt: break M += el.image_cnt cpy_els.append(el) return collections.deque(cpy_els) class RgbdSeq(keras.utils.Sequence): def __init__(self, all_sets_dict, batch_size, validation_split=0.2, is_validation=False, max_per_set_len=25000): self.sets_dict = all_sets_dict self.seqs_dict = dict([(k, RgbdSetSequence(s, batch_size, validation_split, is_validation, max_per_set_len)) for k, s in all_sets_dict.items()]) def __len__(self): return sum(len(s) for s in self.seqs_dict.values()) def __getitem__(self, idx): seq_idx = idx % len(self.seqs_dict) seq_els = list(self.seqs_dict.values()) return seq_els[seq_idx][idx] def plot_image_count_hist(self): plt.figure() plt.bar(self.sets_dict.keys(), [v.image_count for v in self.sets_dict.values()]) plt.show() def create_rgbdseq_from_files(glob_pattern="data/*.npz", is_validation=False, batch_size=250): rgbd_sets = collections.defaultdict(RgbdSet) for npz_path in glob.glob(glob_pattern): print("Loading %s" % npz_path) set_el = RgbdSetElement(npz_path) rgbd_sets[set_el.set_name].append(set_el) seq = RgbdSeq(rgbd_sets, is_validation=is_validation, batch_size=batch_size) return seq
[ "numpy.load", "matplotlib.pylab.show", "os.path.basename", "collections.defaultdict", "glob.glob", "collections.deque", "matplotlib.pylab.figure" ]
[((4473, 4505), 'collections.defaultdict', 'collections.defaultdict', (['RgbdSet'], {}), '(RgbdSet)\n', (4496, 4505), False, 'import collections\n'), ((4526, 4549), 'glob.glob', 'glob.glob', (['glob_pattern'], {}), '(glob_pattern)\n', (4535, 4549), False, 'import glob\n'), ((245, 267), 'os.path.basename', 'pth.basename', (['npz_path'], {}), '(npz_path)\n', (257, 267), True, 'import os.path as pth\n'), ((3542, 3568), 'collections.deque', 'collections.deque', (['cpy_els'], {}), '(cpy_els)\n', (3559, 3568), False, 'import collections\n'), ((4239, 4251), 'matplotlib.pylab.figure', 'plt.figure', ([], {}), '()\n', (4249, 4251), True, 'import matplotlib.pylab as plt\n'), ((4349, 4359), 'matplotlib.pylab.show', 'plt.show', ([], {}), '()\n', (4357, 4359), True, 'import matplotlib.pylab as plt\n'), ((497, 514), 'numpy.load', 'np.load', (['npz_path'], {}), '(npz_path)\n', (504, 514), True, 'import numpy as np\n'), ((737, 759), 'numpy.load', 'np.load', (['self.npz_path'], {}), '(self.npz_path)\n', (744, 759), True, 'import numpy as np\n')]
import os import os.path as path import pandas as pd import numpy as np from scipy import stats def read_data_sets(file_path): column_names = ['timestamp','x-axis', 'y-axis', 'z-axis','x1-axis', 'y1-axis', 'z1-axis','x2-axis', 'y2-axis', 'z2-axis','activity'] data = pd.read_csv(file_path,header = None, names = column_names) return data def feature_normalize(dataset): mu = np.mean(dataset,axis = 0) sigma = np.std(dataset,axis = 0) return mu,sigma def windows(data, size): start = 0 while start < data.count(): yield int(start), int(start + size) start += (size/2) def segment_signal(data,window_size,num_channels): segments = np.empty((0,window_size,num_channels)) labels = np.empty((0)) for (start, end) in windows(data["timestamp"], window_size): x = data["x-axis"][start:end] y = data["y-axis"][start:end] z = data["z-axis"][start:end] x1 = data["x1-axis"][start:end] y1 = data["y1-axis"][start:end] z1 = data["z1-axis"][start:end] x2 = data["x2-axis"][start:end] y2 = data["y2-axis"][start:end] z2 = data["z2-axis"][start:end] if(len(data["timestamp"][start:end]) == window_size): # segments = np.vstack([segments,np.dstack([x,y,z,x1,y1,z1])]) segments = np.vstack([segments,np.dstack([x,y,z,x1,y1,z1,x2,y2,z2])]) labels = np.append(labels,stats.mode(data["activity"][start:end])[0][0]) return segments, labels def preprocess_data(dataset,valset,testset,input_height,input_width,num_channels): dataset.dropna(axis=0, how='any', inplace= True) testset.dropna(axis=0, how='any', inplace= True) valset.dropna(axis=0,how='any',inplace=True) xmu,xsigma=feature_normalize(dataset['x-axis']) dataset['x-axis'] = (dataset['x-axis']-xmu)/xsigma valset['x-axis'] = (valset['x-axis']-xmu)/xsigma testset['x-axis']= (testset['x-axis']-xmu)/xsigma ymu,ysigma=feature_normalize(dataset['y-axis']) dataset['y-axis'] = (dataset['y-axis']-ymu)/ysigma valset['y-axis'] = (valset['y-axis']-ymu)/ysigma testset['y-axis']= (testset['y-axis']-ymu)/ysigma zmu,zsigma=feature_normalize(dataset['z-axis']) dataset['z-axis'] = (dataset['z-axis']-zmu)/zsigma valset['z-axis']= (valset['z-axis']-zmu)/zsigma testset['z-axis']= (testset['z-axis']-zmu)/zsigma xmu1,xsigma1=feature_normalize(dataset['x1-axis']) dataset['x1-axis'] = (dataset['x1-axis']-xmu1)/xsigma1 valset['x1-axis']= (valset['x1-axis']-xmu1)/xsigma1 testset['x1-axis']= (testset['x1-axis']-xmu1)/xsigma1 ymu1,ysigma1=feature_normalize(dataset['y1-axis']) dataset['y1-axis'] = (dataset['y1-axis']-ymu1)/ysigma1 valset['y1-axis'] = (valset['y1-axis']-ymu1)/ysigma1 testset['y1-axis']= (testset['y1-axis']-ymu1)/ysigma1 zmu1,zsigma1=feature_normalize(dataset['z1-axis']) dataset['z1-axis'] = (dataset['z1-axis']-zmu1)/zsigma1 valset['z1-axis']= (valset['z1-axis']-zmu1)/zsigma1 testset['z1-axis']= (testset['z1-axis']-zmu1)/zsigma1 xmu2,xsigma2=feature_normalize(dataset['x2-axis']) dataset['x2-axis'] = (dataset['x2-axis']-xmu2)/xsigma2 valset['x2-axis']= (valset['x2-axis']-xmu2)/xsigma2 testset['x2-axis']= (testset['x2-axis']-xmu2)/xsigma2 ymu2,ysigma2=feature_normalize(dataset['y2-axis']) dataset['y2-axis'] = (dataset['y2-axis']-ymu2)/ysigma2 valset['y2-axis'] = (valset['y2-axis']-ymu2)/ysigma2 testset['y2-axis']= (testset['y2-axis']-ymu2)/ysigma2 zmu2,zsigma2=feature_normalize(dataset['z2-axis']) dataset['z2-axis'] = (dataset['z2-axis']-zmu2)/zsigma2 valset['z2-axis']= (valset['z2-axis']-zmu2)/zsigma2 testset['z2-axis']= (testset['z2-axis']-zmu2)/zsigma2 print(xmu,' ',xsigma) print(ymu,' ',ysigma) print(zmu,' ',zsigma) print(xmu1,' ',xsigma1) print(ymu1,' ',ysigma1) print(zmu1,' ',zsigma1) print(xmu2,' ',xsigma2) print(ymu2,' ',ysigma2) print(zmu2,' ',zsigma2) train_x, train_y = segment_signal(data=dataset,window_size=input_width,num_channels=num_channels) val_x,val_y=segment_signal(data=valset,window_size=input_width,num_channels=num_channels) test_x,test_y=segment_signal(data=testset,window_size=input_width,num_channels=num_channels) train_y = np.asarray(pd.get_dummies(train_y), dtype = np.int8) val_y=np.asarray(pd.get_dummies(val_y), dtype = np.int8) test_y=np.asarray(pd.get_dummies(test_y), dtype = np.int8) train_x = train_x.reshape(len(train_x), input_width, num_channels, input_height) val_x = val_x.reshape(len(val_x), input_width, num_channels, input_height) test_x = test_x.reshape(len(test_x), input_width, num_channels, input_height) return train_x,train_y,val_x,val_y,test_x,test_y input_height = 1 window_size = 50 num_channels = 9 # num_channels = 6 #These files are copied by all of the raw data in train_set, valid_set and test_set respectively. dataset = read_data_sets(file_path='Datasets/TotalSet/trainSet.txt') valset= read_data_sets(file_path='Datasets/TotalSet/validationSet.txt') testset= read_data_sets(file_path='Datasets/TotalSet/testSet.txt') x_train, y_train, x_val, y_val,x_test,y_test=preprocess_data(dataset=dataset,valset=valset,testset=testset,input_height=input_height,input_width=window_size,num_channels=num_channels) idx = np.random.permutation(len(x_train)) x_train,y_train = x_train[idx], y_train[idx] idx = np.random.permutation(len(x_test)) x_test,y_test = x_test[idx], y_test[idx] np.save('Datasets/OutSet_AddMagnetic/x_train',x_train) np.save('Datasets/OutSet_AddMagnetic/y_train',y_train) np.save('Datasets/OutSet_AddMagnetic/x_valid',x_val) np.save('Datasets/OutSet_AddMagnetic/y_valid',y_val) np.save('Datasets/OutSet_AddMagnetic/x_test',x_test) np.save('Datasets/OutSet_AddMagnetic/y_test',y_test)
[ "numpy.dstack", "numpy.save", "scipy.stats.mode", "pandas.read_csv", "numpy.empty", "numpy.std", "pandas.get_dummies", "numpy.mean" ]
[((5542, 5597), 'numpy.save', 'np.save', (['"""Datasets/OutSet_AddMagnetic/x_train"""', 'x_train'], {}), "('Datasets/OutSet_AddMagnetic/x_train', x_train)\n", (5549, 5597), True, 'import numpy as np\n'), ((5597, 5652), 'numpy.save', 'np.save', (['"""Datasets/OutSet_AddMagnetic/y_train"""', 'y_train'], {}), "('Datasets/OutSet_AddMagnetic/y_train', y_train)\n", (5604, 5652), True, 'import numpy as np\n'), ((5652, 5705), 'numpy.save', 'np.save', (['"""Datasets/OutSet_AddMagnetic/x_valid"""', 'x_val'], {}), "('Datasets/OutSet_AddMagnetic/x_valid', x_val)\n", (5659, 5705), True, 'import numpy as np\n'), ((5705, 5758), 'numpy.save', 'np.save', (['"""Datasets/OutSet_AddMagnetic/y_valid"""', 'y_val'], {}), "('Datasets/OutSet_AddMagnetic/y_valid', y_val)\n", (5712, 5758), True, 'import numpy as np\n'), ((5758, 5811), 'numpy.save', 'np.save', (['"""Datasets/OutSet_AddMagnetic/x_test"""', 'x_test'], {}), "('Datasets/OutSet_AddMagnetic/x_test', x_test)\n", (5765, 5811), True, 'import numpy as np\n'), ((5811, 5864), 'numpy.save', 'np.save', (['"""Datasets/OutSet_AddMagnetic/y_test"""', 'y_test'], {}), "('Datasets/OutSet_AddMagnetic/y_test', y_test)\n", (5818, 5864), True, 'import numpy as np\n'), ((275, 330), 'pandas.read_csv', 'pd.read_csv', (['file_path'], {'header': 'None', 'names': 'column_names'}), '(file_path, header=None, names=column_names)\n', (286, 330), True, 'import pandas as pd\n'), ((392, 416), 'numpy.mean', 'np.mean', (['dataset'], {'axis': '(0)'}), '(dataset, axis=0)\n', (399, 416), True, 'import numpy as np\n'), ((430, 453), 'numpy.std', 'np.std', (['dataset'], {'axis': '(0)'}), '(dataset, axis=0)\n', (436, 453), True, 'import numpy as np\n'), ((692, 732), 'numpy.empty', 'np.empty', (['(0, window_size, num_channels)'], {}), '((0, window_size, num_channels))\n', (700, 732), True, 'import numpy as np\n'), ((744, 755), 'numpy.empty', 'np.empty', (['(0)'], {}), '(0)\n', (752, 755), True, 'import numpy as np\n'), ((4342, 4365), 'pandas.get_dummies', 'pd.get_dummies', (['train_y'], {}), '(train_y)\n', (4356, 4365), True, 'import pandas as pd\n'), ((4405, 4426), 'pandas.get_dummies', 'pd.get_dummies', (['val_y'], {}), '(val_y)\n', (4419, 4426), True, 'import pandas as pd\n'), ((4467, 4489), 'pandas.get_dummies', 'pd.get_dummies', (['test_y'], {}), '(test_y)\n', (4481, 4489), True, 'import pandas as pd\n'), ((1357, 1401), 'numpy.dstack', 'np.dstack', (['[x, y, z, x1, y1, z1, x2, y2, z2]'], {}), '([x, y, z, x1, y1, z1, x2, y2, z2])\n', (1366, 1401), True, 'import numpy as np\n'), ((1434, 1473), 'scipy.stats.mode', 'stats.mode', (["data['activity'][start:end]"], {}), "(data['activity'][start:end])\n", (1444, 1473), False, 'from scipy import stats\n')]
from bokeh.plotting import figure, curdoc, vplot, hplot from bokeh.models.widgets import Button, Toggle, Slider, VBoxForm, HBox, VBox, CheckboxGroup from bokeh.driving import linear import numpy as np # Forward & reverse propagating waves. Use global variables to pass values into function. def forward_wave(): return np.exp(-alpha*(z - zmin)) * np.cos(twopi * (current_time - z_norm)) def reverse_wave(): return (np.exp(-alpha*(z[-1] - zmin)) * reflection_coef) * \ np.exp(alpha*z) * np.cos(twopi * (current_time + z_norm)) def standing_wave(): return np.sqrt(1.0 + 2*reflection_coef*np.cos(2.0*twopi*z_norm) + reflection_coef**2) # Initializations freq_Hz = 100e6 velocity_mps = 2e8 wavelength_m = velocity_mps / freq_Hz twopi = 2.0*np.pi n_samp_one_temporal_cycle = 60 alpha = 0.0 reflection_coef = 1.0 current_time = 0.0 zmin = -20 zmax = 0 numpnts = 500 periodic_callback_time_ms = 16 z = np.linspace(zmin,zmax,numpnts) z_norm = z/wavelength_m color_forward_wave = 'blue' color_reverse_wave = 'red' alpha_forward_reverse_waves = 0.5 color_sum_wave = 'black' alpha_sum_wave = 0.3 v1 = forward_wave() v2 = reverse_wave() vsum = v1 + v2 color_standing_wave = 'green' alpha_standing_wave = 0.3 vstanding = standing_wave() ii = 0 # Set up plot p = figure(plot_width=600, plot_height=400, x_range=(zmin,zmax), y_range=(-2.1,2.1), \ title="Forward & Reverse Sinusoidal Voltages", \ tools="pan,box_zoom,save,reset") l_forward = p.line(z, v1, line_width=2, color=color_forward_wave, line_alpha=alpha_forward_reverse_waves) l_reverse = p.line(z, v2, line_width=2, color=color_reverse_wave, line_alpha=alpha_forward_reverse_waves) l_sum = p.line(z, vsum, line_width=2, color=color_sum_wave, line_alpha=0.0) l_standing = p.line(z, vstanding, line_width=2, color=color_standing_wave, line_alpha=0.0) #l_sum.glyph.visible = False p.xaxis.axis_label = "z (m)" p.yaxis.axis_label = "Voltage (V)" t1 = p.text(zmin+1.5, 1.5, text=['f = {} MHz'.format(freq_Hz/1.e6)], text_align="left", text_font_size="10pt") t2 = p.text(zmin+1.5, 1.3, text=['\u03BB = u/f = {} m'.format(wavelength_m)], text_align="left", text_font_size="10pt") t3 = p.text(zmin+1.5, 1.7, text=['u = {:.1e} m/s'.format(velocity_mps)], text_align="left", text_font_size="10pt") # Set up toggle button & callback function def toggle_handler(active): if active: toggle.label = 'Stop' checkbox_group.disabled = True #t3.data_source.data["text"] = ['Running'] curdoc().add_periodic_callback(update, periodic_callback_time_ms) else: toggle.label = 'Start' checkbox_group.disabled = False #t3.data_source.data["text"] = ['Stopped'] curdoc().remove_periodic_callback(update) toggle = Toggle(label="Start", type="success") toggle.on_click(toggle_handler) toggle.active = False # Set up reset button def reset_handler(): global ii, current_time ii = 0 current_time = 0 l_forward.data_source.data["y"] = forward_wave() l_reverse.data_source.data["y"] = reverse_wave() l_sum.data_source.data["y"] = l_forward.data_source.data["y"] + \ l_reverse.data_source.data["y"] #t2.data_source.data["text"] = ['t = {:.3f} s'.format(current_time)] button_reset = Button(label="Reset", type="success") button_reset.on_click(reset_handler) # Set up checkboxes to show/hide forward & reverse propagating waves def checkbox_group_handler(active): global alpha, alpha_slider if 0 in active: #l_forward.glyph.visible = True l_forward.glyph.line_alpha = alpha_forward_reverse_waves else: #l_forward.glyph.visible = False l_forward.glyph.line_alpha = 0.0 if 1 in active: #l_reverse.glyph.visible = True l_reverse.glyph.line_alpha = alpha_forward_reverse_waves else: #l_reverse.glyph.visible = False l_reverse.glyph.line_alpha = 0.0 if 2 in active: #l_sum.glyph.visible = True l_sum.glyph.line_alpha = alpha_sum_wave else: #l_sum.glyph.visible = False l_sum.glyph.line_alpha = 0.0 if 3 in active: alpha = 0.0 alpha_slider.value = 0.0 alpha_slider.disabled = True l_standing.glyph.line_alpha = alpha_standing_wave else: alpha_slider.disabled = False l_standing.glyph.line_alpha = 0.0 #t1.data_source.data["text"] = ['{} {}'.format(l_forward.glyph.line_alpha,l_reverse.glyph.line_alpha)] checkbox_group = CheckboxGroup( labels=["Forward Propagating Wave", "Reverse Propagating Wave", "Sum of Waves", "Standing Wave (valid only for \u03B1=0)"], active=[0, 1]) checkbox_group.on_click(checkbox_group_handler) # Set up slider & callback function def update_alpha(attrname, old, new): global alpha alpha = alpha_slider.value if not toggle.active: l_forward.data_source.data["y"] = forward_wave() l_reverse.data_source.data["y"] = reverse_wave() l_sum.data_source.data["y"] = l_forward.data_source.data["y"] + \ l_reverse.data_source.data["y"] alpha_slider = Slider(title="Attenuation Constant, \u03B1 (1/m)", value=0.0, start=0.0, end=0.25, step=0.005) alpha_slider.on_change('value', update_alpha) # Set up slider & callback function for reflection_coef def update_gamma(attrname, old, new): global reflection_coef reflection_coef = gamma_slider.value if not toggle.active: l_forward.data_source.data["y"] = forward_wave() l_reverse.data_source.data["y"] = reverse_wave() l_sum.data_source.data["y"] = l_forward.data_source.data["y"] + \ l_reverse.data_source.data["y"] l_standing.data_source.data["y"] = standing_wave() gamma_slider = Slider(title="Reflection Coefficient, \u0393", value=reflection_coef, start=-1.0, end=1.0, step=0.01) gamma_slider.on_change('value', update_gamma) # Set up layout layout = hplot(p, VBox(toggle, button_reset, checkbox_group, alpha_slider, gamma_slider, height=580), width=980) # Create callback function for periodic callback def update(): global ii, current_time if toggle.active: ii += 1 current_time = ii / n_samp_one_temporal_cycle l_forward.data_source.data["y"] = forward_wave() l_reverse.data_source.data["y"] = reverse_wave() l_sum.data_source.data["y"] = l_forward.data_source.data["y"] + \ l_reverse.data_source.data["y"] l_standing.data_source.data["y"] = standing_wave()
[ "bokeh.plotting.figure", "bokeh.models.widgets.CheckboxGroup", "bokeh.models.widgets.VBox", "numpy.exp", "numpy.linspace", "numpy.cos", "bokeh.models.widgets.Slider", "bokeh.plotting.curdoc", "bokeh.models.widgets.Toggle", "bokeh.models.widgets.Button" ]
[((921, 953), 'numpy.linspace', 'np.linspace', (['zmin', 'zmax', 'numpnts'], {}), '(zmin, zmax, numpnts)\n', (932, 953), True, 'import numpy as np\n'), ((1277, 1448), 'bokeh.plotting.figure', 'figure', ([], {'plot_width': '(600)', 'plot_height': '(400)', 'x_range': '(zmin, zmax)', 'y_range': '(-2.1, 2.1)', 'title': '"""Forward & Reverse Sinusoidal Voltages"""', 'tools': '"""pan,box_zoom,save,reset"""'}), "(plot_width=600, plot_height=400, x_range=(zmin, zmax), y_range=(-2.1,\n 2.1), title='Forward & Reverse Sinusoidal Voltages', tools=\n 'pan,box_zoom,save,reset')\n", (1283, 1448), False, 'from bokeh.plotting import figure, curdoc, vplot, hplot\n'), ((2766, 2803), 'bokeh.models.widgets.Toggle', 'Toggle', ([], {'label': '"""Start"""', 'type': '"""success"""'}), "(label='Start', type='success')\n", (2772, 2803), False, 'from bokeh.models.widgets import Button, Toggle, Slider, VBoxForm, HBox, VBox, CheckboxGroup\n'), ((3292, 3329), 'bokeh.models.widgets.Button', 'Button', ([], {'label': '"""Reset"""', 'type': '"""success"""'}), "(label='Reset', type='success')\n", (3298, 3329), False, 'from bokeh.models.widgets import Button, Toggle, Slider, VBoxForm, HBox, VBox, CheckboxGroup\n'), ((4508, 4663), 'bokeh.models.widgets.CheckboxGroup', 'CheckboxGroup', ([], {'labels': "['Forward Propagating Wave', 'Reverse Propagating Wave', 'Sum of Waves',\n 'Standing Wave (valid only for α=0)']", 'active': '[0, 1]'}), "(labels=['Forward Propagating Wave',\n 'Reverse Propagating Wave', 'Sum of Waves',\n 'Standing Wave (valid only for α=0)'], active=[0, 1])\n", (4521, 4663), False, 'from bokeh.models.widgets import Button, Toggle, Slider, VBoxForm, HBox, VBox, CheckboxGroup\n'), ((5156, 5250), 'bokeh.models.widgets.Slider', 'Slider', ([], {'title': '"""Attenuation Constant, α (1/m)"""', 'value': '(0.0)', 'start': '(0.0)', 'end': '(0.25)', 'step': '(0.005)'}), "(title='Attenuation Constant, α (1/m)', value=0.0, start=0.0, end=\n 0.25, step=0.005)\n", (5162, 5250), False, 'from bokeh.models.widgets import Button, Toggle, Slider, VBoxForm, HBox, VBox, CheckboxGroup\n'), ((5818, 5918), 'bokeh.models.widgets.Slider', 'Slider', ([], {'title': '"""Reflection Coefficient, Γ"""', 'value': 'reflection_coef', 'start': '(-1.0)', 'end': '(1.0)', 'step': '(0.01)'}), "(title='Reflection Coefficient, Γ', value=reflection_coef, start=-1.0,\n end=1.0, step=0.01)\n", (5824, 5918), False, 'from bokeh.models.widgets import Button, Toggle, Slider, VBoxForm, HBox, VBox, CheckboxGroup\n'), ((6001, 6087), 'bokeh.models.widgets.VBox', 'VBox', (['toggle', 'button_reset', 'checkbox_group', 'alpha_slider', 'gamma_slider'], {'height': '(580)'}), '(toggle, button_reset, checkbox_group, alpha_slider, gamma_slider,\n height=580)\n', (6005, 6087), False, 'from bokeh.models.widgets import Button, Toggle, Slider, VBoxForm, HBox, VBox, CheckboxGroup\n'), ((325, 352), 'numpy.exp', 'np.exp', (['(-alpha * (z - zmin))'], {}), '(-alpha * (z - zmin))\n', (331, 352), True, 'import numpy as np\n'), ((353, 392), 'numpy.cos', 'np.cos', (['(twopi * (current_time - z_norm))'], {}), '(twopi * (current_time - z_norm))\n', (359, 392), True, 'import numpy as np\n'), ((507, 546), 'numpy.cos', 'np.cos', (['(twopi * (current_time + z_norm))'], {}), '(twopi * (current_time + z_norm))\n', (513, 546), True, 'import numpy as np\n'), ((489, 506), 'numpy.exp', 'np.exp', (['(alpha * z)'], {}), '(alpha * z)\n', (495, 506), True, 'import numpy as np\n'), ((425, 456), 'numpy.exp', 'np.exp', (['(-alpha * (z[-1] - zmin))'], {}), '(-alpha * (z[-1] - zmin))\n', (431, 456), True, 'import numpy as np\n'), ((2509, 2517), 'bokeh.plotting.curdoc', 'curdoc', ([], {}), '()\n', (2515, 2517), False, 'from bokeh.plotting import figure, curdoc, vplot, hplot\n'), ((2715, 2723), 'bokeh.plotting.curdoc', 'curdoc', ([], {}), '()\n', (2721, 2723), False, 'from bokeh.plotting import figure, curdoc, vplot, hplot\n'), ((611, 639), 'numpy.cos', 'np.cos', (['(2.0 * twopi * z_norm)'], {}), '(2.0 * twopi * z_norm)\n', (617, 639), True, 'import numpy as np\n')]
""" Particular class of real traffic network @author: <NAME> """ import configparser import logging import numpy as np import matplotlib.pyplot as plt import os import seaborn as sns import time from envs.env import PhaseMap, PhaseSet, TrafficSimulator from real_net.data.build_file import gen_rou_file sns.set_color_codes() STATE_NAMES = ['wave'] # node: (phase key, neighbor list) NODES = {'10026': ('6.0', ['9431', '9561', 'cluster_9563_9597', '9531']), '8794': ('4.0', ['cluster_8985_9609', '9837', '9058', 'cluster_9563_9597']), '8940': ('2.1', ['9007', '9429']), '8996': ('2.2', ['cluster_9389_9689', '9713']), '9007': ('2.3', ['9309', '8940']), '9058': ('4.0', ['cluster_8985_9609', '8794', 'joinedS_0']), '9153': ('2.0', ['9643']), '9309': ('4.0', ['9466', '9007', 'cluster_9043_9052']), '9413': ('2.3', ['9721', '9837']), '9429': ('5.0', ['cluster_9043_9052', 'joinedS_1', '8940']), '9431': ('2.4', ['9721', '9884', '9561', '10026']), '9433': ('2.5', ['joinedS_1']), '9466': ('4.0', ['9309', 'joinedS_0', 'cluster_9043_9052']), '9480': ('2.3', ['8996', '9713']), '9531': ('2.6', ['joinedS_1', '10026']), '9561': ('4.0', ['cluster_9389_9689', '10026', '9431', '9884']), '9643': ('2.3', ['9153']), '9713': ('3.0', ['9721', '9884', '8996']), '9721': ('6.0', ['9431', '9713', '9413']), '9837': ('3.1', ['9413', '8794', 'cluster_8985_9609']), '9884': ('2.7', ['9713', '9431', 'cluster_9389_9689', '9561']), 'cluster_8751_9630': ('4.0', ['cluster_9389_9689']), 'cluster_8985_9609': ('4.0', ['9837', '8794', '9058']), 'cluster_9043_9052': ('4.1', ['cluster_9563_9597', '9466', '9309', '10026', 'joinedS_1']), 'cluster_9389_9689': ('4.0', ['9884', '9561', 'cluster_8751_9630', '8996']), 'cluster_9563_9597': ('4.2', ['10026', '8794', 'joinedS_0', 'cluster_9043_9052']), 'joinedS_0': ('6.1', ['9058', 'cluster_9563_9597', '9466']), 'joinedS_1': ('3.2', ['9531', '9429'])} PHASES = {'4.0': ['GGgrrrGGgrrr', 'rrrGGgrrrGGg', 'rrGrrrrrGrrr', 'rrrrrGrrrrrG'], '4.1': ['GGgrrGGGrrr', 'rrGrrrrrrrr', 'rrrGgrrrGGg', 'rrrrGrrrrrG'], '4.2': ['GGGGrrrrrrrr', 'GGggrrGGggrr', 'rrrGGGGrrrrr', 'grrGGggrrGGg'], '2.0': ['GGrrr', 'ggGGG'], '2.1': ['GGGrrr', 'rrGGGg'], '2.2': ['Grr', 'gGG'], '2.3': ['GGGgrr', 'GrrrGG'], '2.4': ['GGGGrr', 'rrrrGG'], '2.5': ['Gg', 'rG'], '2.6': ['GGGg', 'rrrG'], '2.7': ['GGg', 'rrG'], '3.0': ['GGgrrrGGg', 'rrGrrrrrG', 'rrrGGGGrr'], '3.1': ['GgrrGG', 'rGrrrr', 'rrGGGr'], '3.2': ['GGGGrrrGG', 'rrrrGGGGr', 'GGGGrrGGr'], '5.0': ['GGGGgrrrrGGGggrrrr', 'grrrGrrrrgrrGGrrrr', 'GGGGGrrrrrrrrrrrrr', 'rrrrrrrrrGGGGGrrrr', 'rrrrrGGggrrrrrggGg'], '6.0': ['GGGgrrrGGGgrrr', 'rrrGrrrrrrGrrr', 'GGGGrrrrrrrrrr', 'rrrrrrrrrrGGGG', 'rrrrGGgrrrrGGg', 'rrrrrrGrrrrrrG'], '6.1': ['GGgrrGGGrrrGGGgrrrGGGg', 'rrGrrrrrrrrrrrGrrrrrrG', 'GGGrrrrrGGgrrrrGGgrrrr', 'GGGrrrrrrrGrrrrrrGrrrr', 'rrrGGGrrrrrrrrrrrrGGGG', 'rrrGGGrrrrrGGGgrrrGGGg']} class RealNetPhase(PhaseMap): def __init__(self): self.phases = {} for key, val in PHASES.items(): self.phases[key] = PhaseSet(val) class RealNetController: def __init__(self, node_names, nodes): self.name = 'greedy' self.node_names = node_names self.nodes = nodes def forward(self, obs): actions = [] for ob, node_name in zip(obs, self.node_names): actions.append(self.greedy(ob, node_name)) return actions def greedy(self, ob, node_name): # get the action space phases = PHASES[NODES[node_name][0]] flows = [] node = self.nodes[node_name] # get the green waves for phase in phases: wave = 0 visited_ilds = set() for i, signal in enumerate(phase): if signal == 'G': # find controlled lane lane = node.lanes_in[i] # ild = 'ild:' + lane ild = lane # if it has not been counted, add the wave if ild not in visited_ilds: j = node.ilds_in.index(ild) wave += ob[j] visited_ilds.add(ild) flows.append(wave) return np.argmax(np.array(flows)) class RealNetEnv(TrafficSimulator): def __init__(self, config, port=0, output_path='', is_record=False, record_stat=False): self.flow_rate = config.getint('flow_rate') super().__init__(config, output_path, is_record, record_stat, port=port) def _get_node_phase_id(self, node_name): return self.phase_node_map[node_name] def _init_neighbor_map(self): return dict([(key, val[1]) for key, val in NODES.items()]) def _init_map(self): self.neighbor_map = self._init_neighbor_map() self.phase_map = RealNetPhase() self.phase_node_map = dict([(key, val[0]) for key, val in NODES.items()]) self.state_names = STATE_NAMES def _init_sim_config(self, seed): # comment out to call build_file.py return gen_rou_file(self.data_path, self.flow_rate, seed=seed, thread=self.sim_thread) def plot_stat(self, rewards): self.state_stat['reward'] = rewards for name, data in self.state_stat.items(): fig = plt.figure(figsize=(8, 6)) plot_cdf(data) plt.ylabel(name) fig.savefig(self.output_path + self.name + '_' + name + '.png') def plot_cdf(X, c='b', label=None): sorted_data = np.sort(X) yvals = np.arange(len(sorted_data))/float(len(sorted_data)-1) plt.plot(sorted_data, yvals, color=c, label=label) if __name__ == '__main__': logging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s', level=logging.INFO) config = configparser.ConfigParser() config.read('./config/config_test_real.ini') base_dir = './output_result/' if not os.path.exists(base_dir): os.mkdir(base_dir) env = RealNetEnv(config['ENV_CONFIG'], 2, base_dir, is_record=True, record_stat=True) env.train_mode = False time.sleep(1) # ob = env.reset(gui=True) controller = RealNetController(env.node_names, env.nodes) env.init_test_seeds(list(range(10000, 100001, 10000))) rewards = [] for i in range(10): ob = env.reset(test_ind=i) global_rewards = [] cur_step = 0 while True: next_ob, reward, done, global_reward = env.step(controller.forward(ob)) # for node_name, node_ob in zip(env.node_names, next_ob): # logging.info('%d, %s:%r\n' % (cur_step, node_name, node_ob)) global_rewards.append(global_reward) rewards += list(reward) cur_step += 1 if done: break ob = next_ob env.terminate() logging.info('step: %d, avg reward: %.2f' % (cur_step, np.mean(global_rewards))) time.sleep(1) env.plot_stat(np.array(rewards)) env.terminate() time.sleep(2) env.collect_tripinfo() env.output_data()
[ "os.mkdir", "logging.basicConfig", "matplotlib.pyplot.plot", "seaborn.set_color_codes", "os.path.exists", "real_net.data.build_file.gen_rou_file", "time.sleep", "numpy.sort", "matplotlib.pyplot.figure", "numpy.mean", "numpy.array", "matplotlib.pyplot.ylabel", "configparser.ConfigParser", "envs.env.PhaseSet" ]
[((305, 326), 'seaborn.set_color_codes', 'sns.set_color_codes', ([], {}), '()\n', (324, 326), True, 'import seaborn as sns\n'), ((5980, 5990), 'numpy.sort', 'np.sort', (['X'], {}), '(X)\n', (5987, 5990), True, 'import numpy as np\n'), ((6061, 6111), 'matplotlib.pyplot.plot', 'plt.plot', (['sorted_data', 'yvals'], {'color': 'c', 'label': 'label'}), '(sorted_data, yvals, color=c, label=label)\n', (6069, 6111), True, 'import matplotlib.pyplot as plt\n'), ((6145, 6239), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s [%(levelname)s] %(message)s"""', 'level': 'logging.INFO'}), "(format='%(asctime)s [%(levelname)s] %(message)s', level\n =logging.INFO)\n", (6164, 6239), False, 'import logging\n'), ((6272, 6299), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (6297, 6299), False, 'import configparser\n'), ((6568, 6581), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (6578, 6581), False, 'import time\n'), ((7487, 7500), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (7497, 7500), False, 'import time\n'), ((5453, 5532), 'real_net.data.build_file.gen_rou_file', 'gen_rou_file', (['self.data_path', 'self.flow_rate'], {'seed': 'seed', 'thread': 'self.sim_thread'}), '(self.data_path, self.flow_rate, seed=seed, thread=self.sim_thread)\n', (5465, 5532), False, 'from real_net.data.build_file import gen_rou_file\n'), ((6394, 6418), 'os.path.exists', 'os.path.exists', (['base_dir'], {}), '(base_dir)\n', (6408, 6418), False, 'import os\n'), ((6428, 6446), 'os.mkdir', 'os.mkdir', (['base_dir'], {}), '(base_dir)\n', (6436, 6446), False, 'import os\n'), ((7412, 7425), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (7422, 7425), False, 'import time\n'), ((7444, 7461), 'numpy.array', 'np.array', (['rewards'], {}), '(rewards)\n', (7452, 7461), True, 'import numpy as np\n'), ((3452, 3465), 'envs.env.PhaseSet', 'PhaseSet', (['val'], {}), '(val)\n', (3460, 3465), False, 'from envs.env import PhaseMap, PhaseSet, TrafficSimulator\n'), ((4640, 4655), 'numpy.array', 'np.array', (['flows'], {}), '(flows)\n', (4648, 4655), True, 'import numpy as np\n'), ((5765, 5791), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 6)'}), '(figsize=(8, 6))\n', (5775, 5791), True, 'import matplotlib.pyplot as plt\n'), ((5831, 5847), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['name'], {}), '(name)\n', (5841, 5847), True, 'import matplotlib.pyplot as plt\n'), ((7378, 7401), 'numpy.mean', 'np.mean', (['global_rewards'], {}), '(global_rewards)\n', (7385, 7401), True, 'import numpy as np\n')]
import numpy as np import torch import gym import argparse import os import utils import TD3 import kerbal_rl.env as envs def generate_input(obs) : mean_altitude = obs[1].mean_altitude speed = obs[1].vertical_speed dry_mass = obs[0].dry_mass mass = obs[0].mass max_thrust = obs[0].max_thrust thrust = obs[0].thrust goal = obs[2] input = ((mean_altitude, speed, dry_mass, mass, max_thrust, thrust, goal)) return input # Runs policy for X episodes and returns average reward def evaluate_policy(policy, eval_episodes=1): avg_reward = 0. for _ in range(eval_episodes): obs = env.reset() done = False input = generate_input(obs) while not done: action = policy.select_action(np.array(input)) obs, reward, done, _ = env.step(action) avg_reward += reward avg_reward /= eval_episodes print ("---------------------------------------") print ("Evaluation over %d episodes: %f" % (eval_episodes, avg_reward)) print ("---------------------------------------") return avg_reward if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--policy_name", default="TD3") # Policy name parser.add_argument("--seed", default=0, type=int) # Sets Gym, PyTorch and Numpy seeds parser.add_argument("--start_timesteps", default=2e4, type=int) # How many time steps purely random policy is run for parser.add_argument("--eval_freq", default=5e2, type=float) # How often (time steps) we evaluate parser.add_argument("--max_timesteps", default=1e6, type=float) # Max time steps to run environment for parser.add_argument("--save_models", action="store_true") # Whether or not models are saved parser.add_argument("--expl_noise", default=0.1, type=float) # Std of Gaussian exploration noise parser.add_argument("--batch_size", default=200, type=int) # Batch size for both actor and critic parser.add_argument("--discount", default=0.99, type=float) # Discount factor parser.add_argument("--tau", default=0.005, type=float) # Target network update rate parser.add_argument("--policy_noise", default=0.2, type=float) # Noise added to target policy during critic update parser.add_argument("--noise_clip", default=0.5, type=float) # Range to clip target policy noise parser.add_argument("--policy_freq", default=2, type=int) # Frequency of delayed policy updates args = parser.parse_args() file_name = "%s_%s_%s" % (args.policy_name, 'hover_v0', str(args.seed)) print ("---------------------------------------") print ("Settings: %s" % (file_name)) print ("---------------------------------------") if not os.path.exists("./results"): os.makedirs("./results") if args.save_models and not os.path.exists("./pytorch_models"): os.makedirs("./pytorch_models") # env = kerbal_rl.make('hover_v0') env = envs.hover_v0() # Set seeds torch.manual_seed(args.seed) np.random.seed(args.seed) state_dim = 7 # custom action_dim = 1 max_action = env.action_max # Initialize policy policy = TD3.TD3(state_dim, action_dim, max_action) replay_buffer = utils.ReplayBuffer() # Evaluate untrained policy evaluations = [evaluate_policy(policy)] total_timesteps = 0 timesteps_since_eval = 0 episode_num = 0 done = True while total_timesteps < args.max_timesteps: if done: if total_timesteps != 0: print('Total T : ', total_timesteps, ' Episode Num : ', episode_num, ' Episode : ', episode_timesteps, ' Reward : ', episode_reward) policy.train(replay_buffer, episode_timesteps, args.batch_size, args.discount, args.tau, args.policy_noise, args.noise_clip, args.policy_freq) # Evaluate episode if timesteps_since_eval >= args.eval_freq: timesteps_since_eval %= args.eval_freq evaluations.append(evaluate_policy(policy)) if args.save_models: policy.save(file_name, directory="./pytorch_models") np.save("./results/%s" % (file_name), evaluations) # Reset environment obs = env.reset() done = False episode_reward = 0 episode_timesteps = 0 episode_num += 1 obs = generate_input(obs) # Select action randomly or according to policy if total_timesteps < args.start_timesteps: action = env.sample_action_space() else: action = policy.select_action(np.array(obs)) if args.expl_noise != 0: action = (action + np.random.normal(0, args.expl_noise, size=env.action_space)).clip(env.action_min, env.action_max) # Perform action new_obs, reward, done, _ = env.step(action) new_obs = generate_input(new_obs) done_bool = float(done) episode_reward += reward # Store data in replay buffer replay_buffer.add((obs, new_obs, action, reward, done_bool)) obs = new_obs print('goal : ', obs[6]) episode_timesteps += 1 total_timesteps += 1 timesteps_since_eval += 1 # Final evaluation evaluations.append(evaluate_policy(policy)) if args.save_models: policy.save("%s" % (file_name), directory="./pytorch_models") np.save("./results/%s" % (file_name), evaluations)
[ "numpy.save", "numpy.random.seed", "argparse.ArgumentParser", "os.makedirs", "kerbal_rl.env.hover_v0", "torch.manual_seed", "os.path.exists", "TD3.TD3", "numpy.array", "numpy.random.normal", "utils.ReplayBuffer" ]
[((1050, 1075), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1073, 1075), False, 'import argparse\n'), ((2795, 2810), 'kerbal_rl.env.hover_v0', 'envs.hover_v0', ([], {}), '()\n', (2808, 2810), True, 'import kerbal_rl.env as envs\n'), ((2825, 2853), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (2842, 2853), False, 'import torch\n'), ((2855, 2880), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (2869, 2880), True, 'import numpy as np\n'), ((2985, 3027), 'TD3.TD3', 'TD3.TD3', (['state_dim', 'action_dim', 'max_action'], {}), '(state_dim, action_dim, max_action)\n', (2992, 3027), False, 'import TD3\n'), ((3045, 3065), 'utils.ReplayBuffer', 'utils.ReplayBuffer', ([], {}), '()\n', (3063, 3065), False, 'import utils\n'), ((4919, 4967), 'numpy.save', 'np.save', (["('./results/%s' % file_name)", 'evaluations'], {}), "('./results/%s' % file_name, evaluations)\n", (4926, 4967), True, 'import numpy as np\n'), ((2596, 2623), 'os.path.exists', 'os.path.exists', (['"""./results"""'], {}), "('./results')\n", (2610, 2623), False, 'import os\n'), ((2627, 2651), 'os.makedirs', 'os.makedirs', (['"""./results"""'], {}), "('./results')\n", (2638, 2651), False, 'import os\n'), ((2719, 2750), 'os.makedirs', 'os.makedirs', (['"""./pytorch_models"""'], {}), "('./pytorch_models')\n", (2730, 2750), False, 'import os\n'), ((2681, 2715), 'os.path.exists', 'os.path.exists', (['"""./pytorch_models"""'], {}), "('./pytorch_models')\n", (2695, 2715), False, 'import os\n'), ((700, 715), 'numpy.array', 'np.array', (['input'], {}), '(input)\n', (708, 715), True, 'import numpy as np\n'), ((3841, 3889), 'numpy.save', 'np.save', (["('./results/%s' % file_name)", 'evaluations'], {}), "('./results/%s' % file_name, evaluations)\n", (3848, 3889), True, 'import numpy as np\n'), ((4228, 4241), 'numpy.array', 'np.array', (['obs'], {}), '(obs)\n', (4236, 4241), True, 'import numpy as np\n'), ((4295, 4354), 'numpy.random.normal', 'np.random.normal', (['(0)', 'args.expl_noise'], {'size': 'env.action_space'}), '(0, args.expl_noise, size=env.action_space)\n', (4311, 4354), True, 'import numpy as np\n')]
import numpy as np def fdr(pvalues, alpha=0.05): """ Calculate the p-value cut-off to control for the false discovery rate (FDR) for multiple testing. If by controlling for FDR, all of n null hypotheses are rejected, the conservative Bonferroni bound (alpha/n) is returned instead. Arguments --------- pvalues : array (n, ), p values for n multiple tests. alpha : float, optional Significance level. Default is 0.05. Returns ------- : float Adjusted criterion for rejecting the null hypothesis. If by controlling for FDR, all of n null hypotheses are rejected, the conservative Bonferroni bound (alpha/n) is returned. Notes ----- For technical details see :cite:`Benjamini:2001` and :cite:`Castro:2006tz`. Examples -------- >>> import pysal.lib >>> import numpy as np >>> np.random.seed(10) >>> w = pysal.lib.io.open(pysal.lib.examples.get_path("stl.gal")).read() >>> f = pysal.lib.io.open(pysal.lib.examples.get_path("stl_hom.txt")) >>> y = np.array(f.by_col['HR8893']) >>> from pysal.explore.esda.moran import Moran_Local >>> from pysal.explore.esda import fdr >>> lm = Moran_Local(y, w, transformation = "r", permutations = 999) >>> fdr(lm.p_sim, 0.1) 0.002564102564102564 >>> fdr(lm.p_sim, 0.05) #return the conservative Bonferroni bound 0.000641025641025641 """ n = len(pvalues) p_sort = np.sort(pvalues)[::-1] index = np.arange(n, 0, -1) p_fdr = index * alpha / n search = p_sort < p_fdr sig_all = np.where(search)[0] if len(sig_all) == 0: return alpha/n else: return p_fdr[sig_all[0]]
[ "numpy.sort", "numpy.where", "numpy.arange" ]
[((1609, 1628), 'numpy.arange', 'np.arange', (['n', '(0)', '(-1)'], {}), '(n, 0, -1)\n', (1618, 1628), True, 'import numpy as np\n'), ((1574, 1590), 'numpy.sort', 'np.sort', (['pvalues'], {}), '(pvalues)\n', (1581, 1590), True, 'import numpy as np\n'), ((1701, 1717), 'numpy.where', 'np.where', (['search'], {}), '(search)\n', (1709, 1717), True, 'import numpy as np\n')]
import os import json import logging import azure.functions as func from flass.model import load_mlflow_model import flass import numpy as np CACHED_MODEL = None def main(req: func.HttpRequest) -> func.HttpResponse: logging.info(f"Flass is at {flass.__file__}") logging.info("Python HTTP trigger function processed a request to Flass func.") model_location = os.getenv("MLFLOW_MODEL_LOCATION") connection_string = os.getenv("AZURE_STORAGE_CONNECTION_STRING") connection_string_length = len(connection_string) if connection_string else 0 response = f"Welcome to Flass. Model location is {model_location}\n" response += ( f"Lenght of model storage connection string is {connection_string_length}\n" ) global CACHED_MODEL if CACHED_MODEL: logging.info("Model found in cache, using this") trained_model = CACHED_MODEL else: logging.info(f"Model not found in cache, loading from {model_location}") trained_model = load_mlflow_model(model_location) CACHED_MODEL = trained_model logging.info(f"Model loaded successfully") payload_from_param = req.params.get("payload") if payload_from_param: logging.info( f"Trying to param payload of type {type(payload_from_param)} " f"and value {payload_from_param} into json" ) payload = json.loads(payload_from_param) else: try: req_body = req.get_json() except ValueError: payload = None else: payload = req_body.get("payload") if payload: logging.info( f"Trying to load payload of type {type(payload)} " f"and value {payload} into numpy array" ) try: np_array = np.array(payload) except Exception as e: logging.error(f"Failed to parse, error: {e}") logging.info(f"Arryay loaded, dimensions {np_array.shape}") result = trained_model.predict(payload) return func.HttpResponse(json.dumps(result.tolist())) else: return func.HttpResponse( response + "\nPlease pass data in the key 'payload' on the query string " "or in the request body", status_code=400, )
[ "logging.error", "flass.model.load_mlflow_model", "json.loads", "logging.info", "numpy.array", "azure.functions.HttpResponse", "os.getenv" ]
[((237, 282), 'logging.info', 'logging.info', (['f"""Flass is at {flass.__file__}"""'], {}), "(f'Flass is at {flass.__file__}')\n", (249, 282), False, 'import logging\n'), ((288, 367), 'logging.info', 'logging.info', (['"""Python HTTP trigger function processed a request to Flass func."""'], {}), "('Python HTTP trigger function processed a request to Flass func.')\n", (300, 367), False, 'import logging\n'), ((392, 426), 'os.getenv', 'os.getenv', (['"""MLFLOW_MODEL_LOCATION"""'], {}), "('MLFLOW_MODEL_LOCATION')\n", (401, 426), False, 'import os\n'), ((452, 496), 'os.getenv', 'os.getenv', (['"""AZURE_STORAGE_CONNECTION_STRING"""'], {}), "('AZURE_STORAGE_CONNECTION_STRING')\n", (461, 496), False, 'import os\n'), ((824, 872), 'logging.info', 'logging.info', (['"""Model found in cache, using this"""'], {}), "('Model found in cache, using this')\n", (836, 872), False, 'import logging\n'), ((931, 1003), 'logging.info', 'logging.info', (['f"""Model not found in cache, loading from {model_location}"""'], {}), "(f'Model not found in cache, loading from {model_location}')\n", (943, 1003), False, 'import logging\n'), ((1029, 1062), 'flass.model.load_mlflow_model', 'load_mlflow_model', (['model_location'], {}), '(model_location)\n', (1046, 1062), False, 'from flass.model import load_mlflow_model\n'), ((1110, 1152), 'logging.info', 'logging.info', (['f"""Model loaded successfully"""'], {}), "(f'Model loaded successfully')\n", (1122, 1152), False, 'import logging\n'), ((1421, 1451), 'json.loads', 'json.loads', (['payload_from_param'], {}), '(payload_from_param)\n', (1431, 1451), False, 'import json\n'), ((1964, 2023), 'logging.info', 'logging.info', (['f"""Arryay loaded, dimensions {np_array.shape}"""'], {}), "(f'Arryay loaded, dimensions {np_array.shape}')\n", (1976, 2023), False, 'import logging\n'), ((2165, 2308), 'azure.functions.HttpResponse', 'func.HttpResponse', (['(response +\n """\nPlease pass data in the key \'payload\' on the query string or in the request body"""\n )'], {'status_code': '(400)'}), '(response +\n """\nPlease pass data in the key \'payload\' on the query string or in the request body"""\n , status_code=400)\n', (2182, 2308), True, 'import azure.functions as func\n'), ((1844, 1861), 'numpy.array', 'np.array', (['payload'], {}), '(payload)\n', (1852, 1861), True, 'import numpy as np\n'), ((1907, 1952), 'logging.error', 'logging.error', (['f"""Failed to parse, error: {e}"""'], {}), "(f'Failed to parse, error: {e}')\n", (1920, 1952), False, 'import logging\n')]
from typing import Tuple import torch from scipy.ndimage.interpolation import map_coordinates from scipy.ndimage.filters import gaussian_filter import numpy as np class Augmentation(object): """ Super class for all augmentations. """ def __init__(self) -> None: """ Constructor method """ pass def need_labels(self) -> None: """ Method should return if the labels are needed for the augmentation """ raise NotImplementedError() def __call__(self, *args, **kwargs) -> None: """ Call method is used to apply the augmentation :param args: Will be ignored :param kwargs: Will be ignored """ raise NotImplementedError() class VerticalFlip(Augmentation): """ This class implements vertical flipping for instance segmentation. """ def __init__(self) -> None: """ Constructor method """ # Call super constructor super(VerticalFlip, self).__init__() def need_labels(self) -> bool: """ Method returns that the labels are needed for the augmentation :return: (Bool) True will be returned """ return True def __call__(self, input: torch.tensor, instances: torch.tensor, bounding_boxes: torch.tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Flipping augmentation (only horizontal) :param image: (torch.Tensor) Input image of shape [channels, height, width] :param instances: (torch.Tenor) Instances segmentation maps of shape [instances, height, width] :param bounding_boxes: (torch.Tensor) Bounding boxes of shape [instances, 4 (x1, y1, x2, y2)] :return: (Tuple[torch.Tensor, torch.Tensor, torch.Tensor]) Input flipped, instances flipped & BBs flipped """ # Flip input input_flipped = input.flip(dims=(2,)) # Flip instances instances_flipped = instances.flip(dims=(2,)) # Flip bounding boxes image_center = torch.tensor((input.shape[2] // 2, input.shape[1] // 2)) bounding_boxes[:, [0, 2]] += 2 * (image_center - bounding_boxes[:, [0, 2]]) bounding_boxes_w = torch.abs(bounding_boxes[:, 0] - bounding_boxes[:, 2]) bounding_boxes[:, 0] -= bounding_boxes_w bounding_boxes[:, 2] += bounding_boxes_w return input_flipped, instances_flipped, bounding_boxes class ElasticDeformation(Augmentation): """ This class implement random elastic deformation of a given input image """ def __init__(self, alpha: float = 125, sigma: float = 20) -> None: """ Constructor method :param alpha: (float) Alpha coefficient which represents the scaling :param sigma: (float) Sigma coefficient which represents the elastic factor """ # Call super constructor super(ElasticDeformation, self).__init__() # Save parameters self.alpha = alpha self.sigma = sigma def need_labels(self) -> bool: """ Method returns that the labels are needed for the augmentation :return: (Bool) True will be returned """ return False def __call__(self, image: torch.Tensor) -> torch.Tensor: """ Method applies the random elastic deformation :param image: (torch.Tensor) Input image :return: (torch.Tensor) Transformed input image """ # Convert torch tensor to numpy array for scipy image = image.numpy() # Save basic shape shape = image.shape[1:] # Sample offsets dx = gaussian_filter((np.random.rand(*shape) * 2 - 1), self.sigma, mode="constant", cval=0) * self.alpha dy = gaussian_filter((np.random.rand(*shape) * 2 - 1), self.sigma, mode="constant", cval=0) * self.alpha x, y = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]), indexing='ij') indices = np.reshape(x + dx, (-1, 1)), np.reshape(y + dy, (-1, 1)) # Perform deformation for index in range(image.shape[0]): image[index] = map_coordinates(image[index], indices, order=1).reshape(shape) return torch.from_numpy(image) class NoiseInjection(Augmentation): """ This class implements vertical flipping for instance segmentation. """ def __init__(self, mean: float = 0.0, std: float = 0.25) -> None: """ Constructor method :param mean: (Optional[float]) Mean of the gaussian noise :param std: (Optional[float]) Standard deviation of the gaussian noise """ # Call super constructor super(NoiseInjection, self).__init__() # Save parameter self.mean = mean self.std = std def need_labels(self) -> bool: """ Method returns that the labels are needed for the augmentation :return: (Bool) False will be returned """ return False def __call__(self, input: torch.Tensor) -> torch.Tensor: """ Method injects gaussian noise to the given input image :param image: (torch.Tensor) Input image :return: (torch.Tensor) Transformed input image """ # Get noise noise = self.mean + torch.randn_like(input) * self.std # Apply nose to image input = input + noise return input
[ "torch.randn_like", "scipy.ndimage.interpolation.map_coordinates", "numpy.arange", "numpy.reshape", "numpy.random.rand", "torch.abs", "torch.tensor", "torch.from_numpy" ]
[((2083, 2139), 'torch.tensor', 'torch.tensor', (['(input.shape[2] // 2, input.shape[1] // 2)'], {}), '((input.shape[2] // 2, input.shape[1] // 2))\n', (2095, 2139), False, 'import torch\n'), ((2251, 2305), 'torch.abs', 'torch.abs', (['(bounding_boxes[:, 0] - bounding_boxes[:, 2])'], {}), '(bounding_boxes[:, 0] - bounding_boxes[:, 2])\n', (2260, 2305), False, 'import torch\n'), ((4226, 4249), 'torch.from_numpy', 'torch.from_numpy', (['image'], {}), '(image)\n', (4242, 4249), False, 'import torch\n'), ((3915, 3934), 'numpy.arange', 'np.arange', (['shape[0]'], {}), '(shape[0])\n', (3924, 3934), True, 'import numpy as np\n'), ((3936, 3955), 'numpy.arange', 'np.arange', (['shape[1]'], {}), '(shape[1])\n', (3945, 3955), True, 'import numpy as np\n'), ((3990, 4017), 'numpy.reshape', 'np.reshape', (['(x + dx)', '(-1, 1)'], {}), '(x + dx, (-1, 1))\n', (4000, 4017), True, 'import numpy as np\n'), ((4019, 4046), 'numpy.reshape', 'np.reshape', (['(y + dy)', '(-1, 1)'], {}), '(y + dy, (-1, 1))\n', (4029, 4046), True, 'import numpy as np\n'), ((5296, 5319), 'torch.randn_like', 'torch.randn_like', (['input'], {}), '(input)\n', (5312, 5319), False, 'import torch\n'), ((4148, 4195), 'scipy.ndimage.interpolation.map_coordinates', 'map_coordinates', (['image[index]', 'indices'], {'order': '(1)'}), '(image[index], indices, order=1)\n', (4163, 4195), False, 'from scipy.ndimage.interpolation import map_coordinates\n'), ((3692, 3714), 'numpy.random.rand', 'np.random.rand', (['*shape'], {}), '(*shape)\n', (3706, 3714), True, 'import numpy as np\n'), ((3805, 3827), 'numpy.random.rand', 'np.random.rand', (['*shape'], {}), '(*shape)\n', (3819, 3827), True, 'import numpy as np\n')]
from tqdm import tqdm import numpy as np import argparse parser = argparse.ArgumentParser( description='Binarize dense extreme prediction data sets.') parser.add_argument('input', help='Path to input file') parser.add_argument( '-f', '--filter', help='Path to file containing indices to filter by.') parser.add_argument( '-o', '--out', required=True, help='Path to output file.') args = parser.parse_args() with open(args.input) as in_file: n, d = (int(i) for i in in_file.readline().split(' ')) dense = np.empty((n, d), dtype=np.float32) for i in tqdm(range(n)): dense[i, :] = [np.float32(j) for j in in_file.readline().split(' ')] # Make sure that we've reached EOF assert len(in_file.read(1)) == 0 if args.filter is not None: with open(args.filter) as filter_file: n, = np.fromfile(filter_file, dtype=np.int32, count=1) idxs = np.fromfile(filter_file, dtype=np.int32, count=n) # Make sure that we've reached EOF assert len(filter_file.read(1)) == 0 dense = dense[idxs, :] print('Saving to "%s" ... ' % args.out, end='') with open(args.out, 'wb') as out_file: np.array(dense.shape, dtype=np.int32).tofile(out_file) dense.tofile(out_file) print('done.')
[ "argparse.ArgumentParser", "numpy.fromfile", "numpy.empty", "numpy.float32", "numpy.array" ]
[((67, 155), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Binarize dense extreme prediction data sets."""'}), "(description=\n 'Binarize dense extreme prediction data sets.')\n", (90, 155), False, 'import argparse\n'), ((527, 561), 'numpy.empty', 'np.empty', (['(n, d)'], {'dtype': 'np.float32'}), '((n, d), dtype=np.float32)\n', (535, 561), True, 'import numpy as np\n'), ((830, 879), 'numpy.fromfile', 'np.fromfile', (['filter_file'], {'dtype': 'np.int32', 'count': '(1)'}), '(filter_file, dtype=np.int32, count=1)\n', (841, 879), True, 'import numpy as np\n'), ((895, 944), 'numpy.fromfile', 'np.fromfile', (['filter_file'], {'dtype': 'np.int32', 'count': 'n'}), '(filter_file, dtype=np.int32, count=n)\n', (906, 944), True, 'import numpy as np\n'), ((614, 627), 'numpy.float32', 'np.float32', (['j'], {}), '(j)\n', (624, 627), True, 'import numpy as np\n'), ((1152, 1189), 'numpy.array', 'np.array', (['dense.shape'], {'dtype': 'np.int32'}), '(dense.shape, dtype=np.int32)\n', (1160, 1189), True, 'import numpy as np\n')]
import os from enum import Enum import numpy as np from PIL import Image from tensorflow.keras.applications.imagenet_utils import preprocess_input from keras_preprocessing import image from tensorflow.python.keras.models import load_model DATASET_PATH = os.environ['DATASET_PATH'] TARGET_RESOLUTION = (64, 64) class Classes(Enum): CARNIVAL = 0 FACE = 1 MASK = 2 def load_dataset(): Ximgs = [] y_train = [] for file in os.listdir(f'{DATASET_PATH}/Train/Carnaval/'): Ximgs.append( np.array( Image.open(f'{DATASET_PATH}/Train/Carnaval/{file}').resize(TARGET_RESOLUTION).convert('RGB')) / 255.0) y_train.append([1, 0, 0]) for file in os.listdir(f'{DATASET_PATH}/Train/Face/'): Ximgs.append( np.array(Image.open(f'{DATASET_PATH}/Train/Face/{file}').resize(TARGET_RESOLUTION).convert('RGB')) / 255.0) y_train.append([0, 1, 0]) for file in os.listdir(f'{DATASET_PATH}/Train/Mask/'): Ximgs.append( np.array(Image.open(f'{DATASET_PATH}/Train/Mask/{file}').resize(TARGET_RESOLUTION).convert('RGB')) / 255.0) y_train.append([0, 0, 1]) Ximgs_test = [] y_test = [] for file in os.listdir(f'{DATASET_PATH}/Test/Carnaval/'): Ximgs_test.append( np.array( Image.open(f'{DATASET_PATH}/Test/Carnaval/{file}').resize(TARGET_RESOLUTION).convert('RGB')) / 255.0) y_test.append([1, 0, 0]) for file in os.listdir(f'{DATASET_PATH}/Test/Face/'): Ximgs_test.append( np.array(Image.open(f'{DATASET_PATH}/Test/Face/{file}').resize(TARGET_RESOLUTION).convert('RGB')) / 255.0) y_test.append([0, 1, 0]) for file in os.listdir(f'{DATASET_PATH}/Test/Mask/'): Ximgs_test.append( np.array(Image.open(f'{DATASET_PATH}/Test/Mask/{file}').resize(TARGET_RESOLUTION).convert('RGB')) / 255.0) y_test.append([0, 0, 1]) x_train = np.array(Ximgs) y_train = np.array(y_train) x_test = np.array(Ximgs_test) y_test = np.array(y_test) return (x_train, y_train), (x_test, y_test) def load_linear_model(file): model = load_model(f'./models/linear_model.keras') # model.summary() img = Image.open(file).resize(TARGET_RESOLUTION) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) images = np.vstack([x]) # print(f'Linear model : {Classes(model.predict_classes(images, batch_size=64))}') return Classes(model.predict_classes(images, batch_size=64)).name def load_mlp_model(file: str): model = load_model(f'./models/mlp_model.keras') # model.summary() img = Image.open(file).resize(TARGET_RESOLUTION) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) images = np.vstack([x]) # print(f'MLP model : {Classes(model.predict_classes(images, batch_size=64))}') return Classes(model.predict_classes(images, batch_size=64)).name def load_cnn_model(file: str): model = load_model(f'./models/cnn_model.keras') # model.summary() img = Image.open(file).resize(TARGET_RESOLUTION) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) images = np.vstack([x]) # print(f'CNN model : {Classes(model.predict_classes(images, batch_size=64))}') return Classes(model.predict_classes(images, batch_size=64)).name def load_resnet_model(file: str): model = load_model(f'./models/resnet_model.keras') # model.summary() img = Image.open(file).resize(TARGET_RESOLUTION) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) res = model.predict(x) return Classes(np.argmax(res, axis=1)).name # print(f'Test Acc : {Classes(model.predict(images, batch_size=10))}') def load_custom_model(file: str, path: str): model = load_model(f'./models/{path}') # model.summary() img = Image.open(file).resize(TARGET_RESOLUTION) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) res = model.predict(x) return Classes(np.argmax(res, axis=1)).name # print(f'Test Acc : {Classes(model.predict(images, batch_size=10))}')
[ "tensorflow.python.keras.models.load_model", "tensorflow.keras.applications.imagenet_utils.preprocess_input", "numpy.argmax", "numpy.expand_dims", "keras_preprocessing.image.img_to_array", "PIL.Image.open", "numpy.array", "os.listdir", "numpy.vstack" ]
[((449, 494), 'os.listdir', 'os.listdir', (['f"""{DATASET_PATH}/Train/Carnaval/"""'], {}), "(f'{DATASET_PATH}/Train/Carnaval/')\n", (459, 494), False, 'import os\n'), ((709, 750), 'os.listdir', 'os.listdir', (['f"""{DATASET_PATH}/Train/Face/"""'], {}), "(f'{DATASET_PATH}/Train/Face/')\n", (719, 750), False, 'import os\n'), ((944, 985), 'os.listdir', 'os.listdir', (['f"""{DATASET_PATH}/Train/Mask/"""'], {}), "(f'{DATASET_PATH}/Train/Mask/')\n", (954, 985), False, 'import os\n'), ((1215, 1259), 'os.listdir', 'os.listdir', (['f"""{DATASET_PATH}/Test/Carnaval/"""'], {}), "(f'{DATASET_PATH}/Test/Carnaval/')\n", (1225, 1259), False, 'import os\n'), ((1477, 1517), 'os.listdir', 'os.listdir', (['f"""{DATASET_PATH}/Test/Face/"""'], {}), "(f'{DATASET_PATH}/Test/Face/')\n", (1487, 1517), False, 'import os\n'), ((1714, 1754), 'os.listdir', 'os.listdir', (['f"""{DATASET_PATH}/Test/Mask/"""'], {}), "(f'{DATASET_PATH}/Test/Mask/')\n", (1724, 1754), False, 'import os\n'), ((1949, 1964), 'numpy.array', 'np.array', (['Ximgs'], {}), '(Ximgs)\n', (1957, 1964), True, 'import numpy as np\n'), ((1979, 1996), 'numpy.array', 'np.array', (['y_train'], {}), '(y_train)\n', (1987, 1996), True, 'import numpy as np\n'), ((2010, 2030), 'numpy.array', 'np.array', (['Ximgs_test'], {}), '(Ximgs_test)\n', (2018, 2030), True, 'import numpy as np\n'), ((2044, 2060), 'numpy.array', 'np.array', (['y_test'], {}), '(y_test)\n', (2052, 2060), True, 'import numpy as np\n'), ((2152, 2194), 'tensorflow.python.keras.models.load_model', 'load_model', (['f"""./models/linear_model.keras"""'], {}), "(f'./models/linear_model.keras')\n", (2162, 2194), False, 'from tensorflow.python.keras.models import load_model\n'), ((2278, 2301), 'keras_preprocessing.image.img_to_array', 'image.img_to_array', (['img'], {}), '(img)\n', (2296, 2301), False, 'from keras_preprocessing import image\n'), ((2310, 2335), 'numpy.expand_dims', 'np.expand_dims', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (2324, 2335), True, 'import numpy as np\n'), ((2349, 2363), 'numpy.vstack', 'np.vstack', (['[x]'], {}), '([x])\n', (2358, 2363), True, 'import numpy as np\n'), ((2567, 2606), 'tensorflow.python.keras.models.load_model', 'load_model', (['f"""./models/mlp_model.keras"""'], {}), "(f'./models/mlp_model.keras')\n", (2577, 2606), False, 'from tensorflow.python.keras.models import load_model\n'), ((2690, 2713), 'keras_preprocessing.image.img_to_array', 'image.img_to_array', (['img'], {}), '(img)\n', (2708, 2713), False, 'from keras_preprocessing import image\n'), ((2722, 2747), 'numpy.expand_dims', 'np.expand_dims', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (2736, 2747), True, 'import numpy as np\n'), ((2761, 2775), 'numpy.vstack', 'np.vstack', (['[x]'], {}), '([x])\n', (2770, 2775), True, 'import numpy as np\n'), ((2976, 3015), 'tensorflow.python.keras.models.load_model', 'load_model', (['f"""./models/cnn_model.keras"""'], {}), "(f'./models/cnn_model.keras')\n", (2986, 3015), False, 'from tensorflow.python.keras.models import load_model\n'), ((3099, 3122), 'keras_preprocessing.image.img_to_array', 'image.img_to_array', (['img'], {}), '(img)\n', (3117, 3122), False, 'from keras_preprocessing import image\n'), ((3131, 3156), 'numpy.expand_dims', 'np.expand_dims', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (3145, 3156), True, 'import numpy as np\n'), ((3170, 3184), 'numpy.vstack', 'np.vstack', (['[x]'], {}), '([x])\n', (3179, 3184), True, 'import numpy as np\n'), ((3388, 3430), 'tensorflow.python.keras.models.load_model', 'load_model', (['f"""./models/resnet_model.keras"""'], {}), "(f'./models/resnet_model.keras')\n", (3398, 3430), False, 'from tensorflow.python.keras.models import load_model\n'), ((3514, 3537), 'keras_preprocessing.image.img_to_array', 'image.img_to_array', (['img'], {}), '(img)\n', (3532, 3537), False, 'from keras_preprocessing import image\n'), ((3546, 3571), 'numpy.expand_dims', 'np.expand_dims', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (3560, 3571), True, 'import numpy as np\n'), ((3580, 3599), 'tensorflow.keras.applications.imagenet_utils.preprocess_input', 'preprocess_input', (['x'], {}), '(x)\n', (3596, 3599), False, 'from tensorflow.keras.applications.imagenet_utils import preprocess_input\n'), ((3812, 3842), 'tensorflow.python.keras.models.load_model', 'load_model', (['f"""./models/{path}"""'], {}), "(f'./models/{path}')\n", (3822, 3842), False, 'from tensorflow.python.keras.models import load_model\n'), ((3926, 3949), 'keras_preprocessing.image.img_to_array', 'image.img_to_array', (['img'], {}), '(img)\n', (3944, 3949), False, 'from keras_preprocessing import image\n'), ((3958, 3983), 'numpy.expand_dims', 'np.expand_dims', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (3972, 3983), True, 'import numpy as np\n'), ((3992, 4011), 'tensorflow.keras.applications.imagenet_utils.preprocess_input', 'preprocess_input', (['x'], {}), '(x)\n', (4008, 4011), False, 'from tensorflow.keras.applications.imagenet_utils import preprocess_input\n'), ((2227, 2243), 'PIL.Image.open', 'Image.open', (['file'], {}), '(file)\n', (2237, 2243), False, 'from PIL import Image\n'), ((2639, 2655), 'PIL.Image.open', 'Image.open', (['file'], {}), '(file)\n', (2649, 2655), False, 'from PIL import Image\n'), ((3048, 3064), 'PIL.Image.open', 'Image.open', (['file'], {}), '(file)\n', (3058, 3064), False, 'from PIL import Image\n'), ((3463, 3479), 'PIL.Image.open', 'Image.open', (['file'], {}), '(file)\n', (3473, 3479), False, 'from PIL import Image\n'), ((3648, 3670), 'numpy.argmax', 'np.argmax', (['res'], {'axis': '(1)'}), '(res, axis=1)\n', (3657, 3670), True, 'import numpy as np\n'), ((3875, 3891), 'PIL.Image.open', 'Image.open', (['file'], {}), '(file)\n', (3885, 3891), False, 'from PIL import Image\n'), ((4060, 4082), 'numpy.argmax', 'np.argmax', (['res'], {'axis': '(1)'}), '(res, axis=1)\n', (4069, 4082), True, 'import numpy as np\n'), ((556, 607), 'PIL.Image.open', 'Image.open', (['f"""{DATASET_PATH}/Train/Carnaval/{file}"""'], {}), "(f'{DATASET_PATH}/Train/Carnaval/{file}')\n", (566, 607), False, 'from PIL import Image\n'), ((795, 842), 'PIL.Image.open', 'Image.open', (['f"""{DATASET_PATH}/Train/Face/{file}"""'], {}), "(f'{DATASET_PATH}/Train/Face/{file}')\n", (805, 842), False, 'from PIL import Image\n'), ((1030, 1077), 'PIL.Image.open', 'Image.open', (['f"""{DATASET_PATH}/Train/Mask/{file}"""'], {}), "(f'{DATASET_PATH}/Train/Mask/{file}')\n", (1040, 1077), False, 'from PIL import Image\n'), ((1326, 1376), 'PIL.Image.open', 'Image.open', (['f"""{DATASET_PATH}/Test/Carnaval/{file}"""'], {}), "(f'{DATASET_PATH}/Test/Carnaval/{file}')\n", (1336, 1376), False, 'from PIL import Image\n'), ((1567, 1613), 'PIL.Image.open', 'Image.open', (['f"""{DATASET_PATH}/Test/Face/{file}"""'], {}), "(f'{DATASET_PATH}/Test/Face/{file}')\n", (1577, 1613), False, 'from PIL import Image\n'), ((1804, 1850), 'PIL.Image.open', 'Image.open', (['f"""{DATASET_PATH}/Test/Mask/{file}"""'], {}), "(f'{DATASET_PATH}/Test/Mask/{file}')\n", (1814, 1850), False, 'from PIL import Image\n')]
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """MelGAN eval""" import os import numpy as np from scipy.io.wavfile import write from mindspore import Model from mindspore.train.serialization import load_checkpoint, load_param_into_net from mindspore.common.tensor import Tensor import mindspore.context as context from src.model import Generator from src.model_utils.config import config as cfg context.set_context(mode=context.GRAPH_MODE, device_target="Ascend") if __name__ == '__main__': context.set_context(device_id=cfg.device_id) if not os.path.exists(cfg.output_path): os.mkdir(cfg.output_path) net_G = Generator(alpha=cfg.leaky_alpha) net_G.set_train(False) # load checkpoint param_dict = load_checkpoint(cfg.eval_model_path) load_param_into_net(net_G, param_dict) print('load model done !') model = Model(net_G) # get list mel_path = cfg.eval_data_path data_list = os.listdir(mel_path) for data_name in data_list: melpath = os.path.join(mel_path, data_name) # data preprocessing meldata = np.load(melpath) meldata = (meldata + 5.0) / 5.0 pad_node = 0 if meldata.shape[1] < cfg.eval_length: pad_node = cfg.eval_length - meldata.shape[1] meldata = np.pad(meldata, ((0, 0), (0, pad_node)), mode='constant', constant_values=0.0) meldata_s = meldata[np.newaxis, :, 0:cfg.eval_length] # first frame wav_data = np.array([]) output = model.predict(Tensor(meldata_s)).asnumpy().ravel() wav_data = np.concatenate((wav_data, output)) # initialization parameters repeat_frame = cfg.eval_length // 8 i = cfg.eval_length - repeat_frame length = cfg.eval_length num_weights = i interval = (cfg.hop_size*repeat_frame) // num_weights weights = np.linspace(0.0, 1.0, num_weights) while i < meldata.shape[1]: # data preprocessing meldata_s = meldata[:, i:i+length] if meldata_s.shape[1] != cfg.eval_length: pad_node = cfg.hop_size * (cfg.eval_length-meldata_s.shape[1]) meldata_s = np.pad(meldata_s, ((0, 0), (0, cfg.eval_length-meldata_s.shape[1])), mode='edge') meldata_s = meldata_s[np.newaxis, :, :] # i-th frame output = model.predict(Tensor(meldata_s)).asnumpy().ravel() print('output{}={}'.format(i, output)) lenwav = cfg.hop_size*repeat_frame lenout = 0 # overlap for j in range(num_weights-1): wav_data[-lenwav:-lenwav+interval] = weights[-j-1] * wav_data[-lenwav:-lenwav+interval] +\ weights[j] * output[lenout:lenout+interval] lenwav = lenwav - interval lenout = lenout + interval wav_data[-lenwav:] = weights[-num_weights] * wav_data[-lenwav:] +\ weights[num_weights-1] * output[lenout:lenout+lenwav] wav_data = np.concatenate((wav_data, output[cfg.hop_size*repeat_frame:])) i = i + length - repeat_frame if pad_node != 0: wav_data = wav_data[:-pad_node] # save as wav file wav_data = 32768.0 * wav_data out_path = os.path.join(cfg.output_path, 'restruction_' + data_name.replace('npy', 'wav')) write(out_path, cfg.sample, wav_data.astype('int16')) print('{} done!'.format(data_name))
[ "numpy.pad", "mindspore.context.set_context", "os.mkdir", "numpy.load", "mindspore.Model", "os.path.exists", "mindspore.common.tensor.Tensor", "numpy.array", "mindspore.train.serialization.load_checkpoint", "numpy.linspace", "src.model.Generator", "os.path.join", "os.listdir", "numpy.concatenate", "mindspore.train.serialization.load_param_into_net" ]
[((1019, 1087), 'mindspore.context.set_context', 'context.set_context', ([], {'mode': 'context.GRAPH_MODE', 'device_target': '"""Ascend"""'}), "(mode=context.GRAPH_MODE, device_target='Ascend')\n", (1038, 1087), True, 'import mindspore.context as context\n'), ((1121, 1165), 'mindspore.context.set_context', 'context.set_context', ([], {'device_id': 'cfg.device_id'}), '(device_id=cfg.device_id)\n', (1140, 1165), True, 'import mindspore.context as context\n'), ((1257, 1289), 'src.model.Generator', 'Generator', ([], {'alpha': 'cfg.leaky_alpha'}), '(alpha=cfg.leaky_alpha)\n', (1266, 1289), False, 'from src.model import Generator\n'), ((1357, 1393), 'mindspore.train.serialization.load_checkpoint', 'load_checkpoint', (['cfg.eval_model_path'], {}), '(cfg.eval_model_path)\n', (1372, 1393), False, 'from mindspore.train.serialization import load_checkpoint, load_param_into_net\n'), ((1398, 1436), 'mindspore.train.serialization.load_param_into_net', 'load_param_into_net', (['net_G', 'param_dict'], {}), '(net_G, param_dict)\n', (1417, 1436), False, 'from mindspore.train.serialization import load_checkpoint, load_param_into_net\n'), ((1481, 1493), 'mindspore.Model', 'Model', (['net_G'], {}), '(net_G)\n', (1486, 1493), False, 'from mindspore import Model\n'), ((1560, 1580), 'os.listdir', 'os.listdir', (['mel_path'], {}), '(mel_path)\n', (1570, 1580), False, 'import os\n'), ((1177, 1208), 'os.path.exists', 'os.path.exists', (['cfg.output_path'], {}), '(cfg.output_path)\n', (1191, 1208), False, 'import os\n'), ((1218, 1243), 'os.mkdir', 'os.mkdir', (['cfg.output_path'], {}), '(cfg.output_path)\n', (1226, 1243), False, 'import os\n'), ((1633, 1666), 'os.path.join', 'os.path.join', (['mel_path', 'data_name'], {}), '(mel_path, data_name)\n', (1645, 1666), False, 'import os\n'), ((1715, 1731), 'numpy.load', 'np.load', (['melpath'], {}), '(melpath)\n', (1722, 1731), True, 'import numpy as np\n'), ((2103, 2115), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2111, 2115), True, 'import numpy as np\n'), ((2203, 2237), 'numpy.concatenate', 'np.concatenate', (['(wav_data, output)'], {}), '((wav_data, output))\n', (2217, 2237), True, 'import numpy as np\n'), ((2499, 2533), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)', 'num_weights'], {}), '(0.0, 1.0, num_weights)\n', (2510, 2533), True, 'import numpy as np\n'), ((1920, 1998), 'numpy.pad', 'np.pad', (['meldata', '((0, 0), (0, pad_node))'], {'mode': '"""constant"""', 'constant_values': '(0.0)'}), "(meldata, ((0, 0), (0, pad_node)), mode='constant', constant_values=0.0)\n", (1926, 1998), True, 'import numpy as np\n'), ((3710, 3774), 'numpy.concatenate', 'np.concatenate', (['(wav_data, output[cfg.hop_size * repeat_frame:])'], {}), '((wav_data, output[cfg.hop_size * repeat_frame:]))\n', (3724, 3774), True, 'import numpy as np\n'), ((2812, 2900), 'numpy.pad', 'np.pad', (['meldata_s', '((0, 0), (0, cfg.eval_length - meldata_s.shape[1]))'], {'mode': '"""edge"""'}), "(meldata_s, ((0, 0), (0, cfg.eval_length - meldata_s.shape[1])), mode\n ='edge')\n", (2818, 2900), True, 'import numpy as np\n'), ((2147, 2164), 'mindspore.common.tensor.Tensor', 'Tensor', (['meldata_s'], {}), '(meldata_s)\n', (2153, 2164), False, 'from mindspore.common.tensor import Tensor\n'), ((3007, 3024), 'mindspore.common.tensor.Tensor', 'Tensor', (['meldata_s'], {}), '(meldata_s)\n', (3013, 3024), False, 'from mindspore.common.tensor import Tensor\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- # ============================================================================= ## @file ostap/math/primes.py # Get prime numbers # @code # np = primes ( 1000 )## get all prime numbers that are smaller than 1000 # @endcode # The function <code>primes</code> use sieve algorithm to get # the prime numbers and it could be relatively slow.e.g. for N>2**32 # A bit more effecient version with reusage of the prime numbers # is by using of the class Primes: # @code # p = Primes ( 1000000 ) # for n in p : ... # @endcode # The class <code>Primes</code> stores and reuses the prime numbers when possible, # thus allowing a bit more CPU efficient treatment. # # @see https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/3035188#3035188 # @author <NAME> <EMAIL> # @date 2016-07-15 # ============================================================================= """ Get prime numbers """ # ============================================================================= __author__ = "<NAME> <EMAIL>" __date__ = "2009-09-12" __version__ = "Version $Revision:$" # ============================================================================= __all__ = ( 'primes' , ## function to get an array of prime numbers , 'Primes' , ## class to store/reuse/handle the prime numbers ) # ============================================================================= # logging # ============================================================================= from ostap.logger.logger import getLogger if '__main__' == __name__ : logger = getLogger ( 'ostap.math.primes' ) else : logger = getLogger ( __name__ ) # ============================================================================= import bisect , random from builtins import range # ============================================================================= try : import numpy atype = numpy.uint64 # ========================================================================= ## get the array of prime numbers that do not exceed <code>n</code> # - <code>numpy</code> (fast?) version # @code # nums = primes ( 1000) # @endcode # @param n the upper edge # @return the array o fprime numbers that do not exceed <code>n</code> # @see https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/3035188#3035188 def primes(n): """ Get the array of prime numbers that do not exceed n - numpy (fast?) version >>> nums = primes ( 1000) - see https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/3035188#3035188 """ if n == 2 : return numpy.array ([] , dtype = atype ) elif n <= 3 : numpy.array ([2] , dtype = atype ) elif n <= 5 : numpy.array ([2,3] , dtype = atype ) sieve = numpy.ones(n//3 + (n%6==2), dtype=numpy.bool) for i in range(1,int(n**0.5)//3+1): if sieve[i]: k=3*i+1|1 sieve[ k*k//3 ::2*k] = False sieve[k*(k-2*(i&1)+4)//3::2*k] = False return numpy.r_[2,3,((3*numpy.nonzero(sieve)[0][1:]+1)|1)] except ImportError : # ========================================================================= ## get the array of prime numbers that do not exceed <code>n</code> # - pure python (slow?) version # @code # nums = primes ( 1000) # @endcode # @param n the upper edge # @return the array o fprime numbers that do not exceed <code>n</code> # @see https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/3035188#3035188 def primes ( n ): """ Get the array of prime numbers that do not exceed n - pure python (slow?) version >>> nums = primes ( 1000) - see https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/3035188#3035188 """ if n == 2 : return [] elif n <= 3 : return [2] elif n <= 5 : return [2,3] n, correction = n-n%6+6, 2-(n%6>1) sieve = [True] * (n//3) for i in range(1,int(n**0.5)//3+1): if sieve[i]: k=3*i+1|1 sieve[ k*k//3 ::2*k] = [False] * ((n//6-k*k//6-1)//k+1) sieve[k*(k-2*(i&1)+4)//3::2*k] = [False] * ((n//6-k*(k-2*(i&1)+4)//6-1)//k+1) return [2,3] + [3*i+1|1 for i in range(1,n//3-correction) if sieve[i]] logger.warning ("primes: Numpy can't be imported, pure python/(slow?) version will be used") # ============================================================================= ## @class Primes # produce and store the primary numbers # @code # p = Primes(1000) # for q in p : print q ## loop over all primes # for q in p.range ( 500 , 700 ) : print q ## loop over primes betee 500 and 700 # qs = p[:20] ## get teh first twenty primes # qs = p[10:20] ## get the range of primes # q = p.choice ( 300 , 800 ) ## get random prime betwewn 300 and 800 # @endcode class Primes(object) : """Produce and store the primary numbers >>> p = Primes(1000) >>> for q in p : print q ## loop over all primes >>> for q in p.range ( 500 , 700 ) : print q ## loop over primes betee 500 and 700 >>> qs = p[:20] ## get teh first twenty primes >>> qs = p[10:20] ## get the range of primes >>> q = p.choice ( 300 , 800 ) ## get random prime betwewn 300 and 800 """ __primes = [] ## the storage of prime numbers __last = 0 ## the (current) upper edge # ========================================================================= ## create the instance # Note, that the actual storage of prime numbers is shared between # the instances,. allowing to reuse already calculated numbers def __init__ ( self , n = 1000000 ) : if not self.__primes or self.__last < n : self.__primes = primes ( n ) self.__last = n self.__N = n # ========================================================================= @property def primes ( self ) : """``primes'' : currently known array of primes""" return self.__primes # ========================================================================= @property def upper ( self ) : """``last'' : get the upper edge for produced prime numbers""" return self.__last # ========================================================================= @property def N ( self ) : """``N'' : get the current boundary of the prime numbers""" return self.__N # ========================================================================= ## iterator over primary numbers # @code # primes = Primes ( 1000 ) # for n in primes : ... # @endcode def __iter__ ( self ) : """Iterator over primary numbers between [2,N] >>> primes = Primes ( 1000 ) >>> for n in primes : ... """ for n in self.__primes : if n < self.__N : yield n else : break # ========================================================================= ## iterator over the range of primary numbers in the range (min,max) # @code # primes = Primes ( 10000 ) # for n in primes.range ( 300 , 500 ) : ... # @endcode def range ( self , min , max ) : """Iterator over primary numbers between [min,max] >>> primes = Primes ( 10000 ) >>> for n in primes.range ( 300 , 500 ) : ... """ bmin = bisect.bisect_left ( self.__primes , min ) bmax = bisect.bisect_left ( self.__primes , max ) for i in range ( bmin , bmax ) : yield self.__primes[i] # ========================================================================= ## Get random primary number in the specified range # @code # primes = Primes ( 10000 ) # p = primes.choice() # p = primes.choice( min = 300 ) # p = primes.choice( min = 300 , max = 500 ) # @endcode def choice ( self , min = None , max = None ) : """Get random primary number in the specified range >>> primes = Primes ( 10000 ) >>> p = primes.choice() >>> p = primes.choice( min = 300 ) >>> p = primes.choice( min = 300 , max = 500 ) """ if ( min is None or min <= self.__primes[0] ) and \ ( max is None or max > self.__primes [-1] ) : return random.choice ( self.__primes ) if min is None : bmin = 0 else : bmin = bisect.bisect_left ( self.__primes , min ) bmax = bisect.bisect_left ( self.__primes , max ) return random.choice ( self [ bmin : bmax] ) # ========================================================================= ## get primary number with certain index or slice # @code # p = Primes ( 4000 ) # n = p[100] # s = p[-5:] # @endcode def __getitem__ ( self , index ) : """Get primary number with certain index or slice >>> primes = Primes ( 4000 ) >>> n = primes [100] >>> s = primes [-5:] """ return self.__primes [ index ] # ============================================================================= if '__main__' == __name__ : from ostap.utils.docme import docme docme ( __name__ , logger = logger ) # ============================================================================= ## The END # =============================================================================
[ "ostap.logger.logger.getLogger", "builtins.range", "numpy.ones", "random.choice", "numpy.nonzero", "numpy.array", "ostap.utils.docme.docme", "bisect.bisect_left" ]
[((1641, 1671), 'ostap.logger.logger.getLogger', 'getLogger', (['"""ostap.math.primes"""'], {}), "('ostap.math.primes')\n", (1650, 1671), False, 'from ostap.logger.logger import getLogger\n'), ((1713, 1732), 'ostap.logger.logger.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (1722, 1732), False, 'from ostap.logger.logger import getLogger\n'), ((9728, 9758), 'ostap.utils.docme.docme', 'docme', (['__name__'], {'logger': 'logger'}), '(__name__, logger=logger)\n', (9733, 9758), False, 'from ostap.utils.docme import docme\n'), ((2976, 3027), 'numpy.ones', 'numpy.ones', (['(n // 3 + (n % 6 == 2))'], {'dtype': 'numpy.bool'}), '(n // 3 + (n % 6 == 2), dtype=numpy.bool)\n', (2986, 3027), False, 'import numpy\n'), ((7845, 7883), 'bisect.bisect_left', 'bisect.bisect_left', (['self.__primes', 'min'], {}), '(self.__primes, min)\n', (7863, 7883), False, 'import bisect, random\n'), ((7904, 7942), 'bisect.bisect_left', 'bisect.bisect_left', (['self.__primes', 'max'], {}), '(self.__primes, max)\n', (7922, 7942), False, 'import bisect, random\n'), ((7966, 7983), 'builtins.range', 'range', (['bmin', 'bmax'], {}), '(bmin, bmax)\n', (7971, 7983), False, 'from builtins import range\n'), ((8984, 9022), 'bisect.bisect_left', 'bisect.bisect_left', (['self.__primes', 'max'], {}), '(self.__primes, max)\n', (9002, 9022), False, 'import bisect, random\n'), ((9043, 9073), 'random.choice', 'random.choice', (['self[bmin:bmax]'], {}), '(self[bmin:bmax])\n', (9056, 9073), False, 'import bisect, random\n'), ((2796, 2824), 'numpy.array', 'numpy.array', (['[]'], {'dtype': 'atype'}), '([], dtype=atype)\n', (2807, 2824), False, 'import numpy\n'), ((8809, 8837), 'random.choice', 'random.choice', (['self.__primes'], {}), '(self.__primes)\n', (8822, 8837), False, 'import bisect, random\n'), ((8917, 8955), 'bisect.bisect_left', 'bisect.bisect_left', (['self.__primes', 'min'], {}), '(self.__primes, min)\n', (8935, 8955), False, 'import bisect, random\n'), ((2853, 2882), 'numpy.array', 'numpy.array', (['[2]'], {'dtype': 'atype'}), '([2], dtype=atype)\n', (2864, 2882), False, 'import numpy\n'), ((2917, 2949), 'numpy.array', 'numpy.array', (['[2, 3]'], {'dtype': 'atype'}), '([2, 3], dtype=atype)\n', (2928, 2949), False, 'import numpy\n'), ((4572, 4601), 'builtins.range', 'range', (['(1)', '(n // 3 - correction)'], {}), '(1, n // 3 - correction)\n', (4577, 4601), False, 'from builtins import range\n'), ((3259, 3279), 'numpy.nonzero', 'numpy.nonzero', (['sieve'], {}), '(sieve)\n', (3272, 3279), False, 'import numpy\n')]
import numpy as np # from scipy.fft import fft, ifft from numpy.fft import fft, ifft, fftfreq, fftshift import matplotlib.pyplot as plt f = np.array([ 1, 2-1j, -1j, -1+2j ]) print(f"The vector of values if {f}") F = fft(f) print(f"The fourier transform is {F}") f_hat = ifft(F) error = np.abs(f - f_hat) print(f"The returned values are {f_hat}") print(f"The error between the values is {error}") w = fftfreq(f.size) fig, ax = plt.subplots() # same for NumPy and for Python ax.plot(fftshift(w), fftshift(f.real)) # To get a real component ax.plot(fftshift(w), fftshift(f.imag)) # To get an imaginary component plt.show()
[ "numpy.fft.ifft", "numpy.abs", "matplotlib.pyplot.show", "numpy.fft.fft", "numpy.fft.fftfreq", "numpy.fft.fftshift", "numpy.array", "matplotlib.pyplot.subplots" ]
[((141, 182), 'numpy.array', 'np.array', (['[1, 2 - 1.0j, -1.0j, -1 + 2.0j]'], {}), '([1, 2 - 1.0j, -1.0j, -1 + 2.0j])\n', (149, 182), True, 'import numpy as np\n'), ((223, 229), 'numpy.fft.fft', 'fft', (['f'], {}), '(f)\n', (226, 229), False, 'from numpy.fft import fft, ifft, fftfreq, fftshift\n'), ((278, 285), 'numpy.fft.ifft', 'ifft', (['F'], {}), '(F)\n', (282, 285), False, 'from numpy.fft import fft, ifft, fftfreq, fftshift\n'), ((294, 311), 'numpy.abs', 'np.abs', (['(f - f_hat)'], {}), '(f - f_hat)\n', (300, 311), True, 'import numpy as np\n'), ((409, 424), 'numpy.fft.fftfreq', 'fftfreq', (['f.size'], {}), '(f.size)\n', (416, 424), False, 'from numpy.fft import fft, ifft, fftfreq, fftshift\n'), ((436, 450), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (448, 450), True, 'import matplotlib.pyplot as plt\n'), ((621, 631), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (629, 631), True, 'import matplotlib.pyplot as plt\n'), ((491, 502), 'numpy.fft.fftshift', 'fftshift', (['w'], {}), '(w)\n', (499, 502), False, 'from numpy.fft import fft, ifft, fftfreq, fftshift\n'), ((504, 520), 'numpy.fft.fftshift', 'fftshift', (['f.real'], {}), '(f.real)\n', (512, 520), False, 'from numpy.fft import fft, ifft, fftfreq, fftshift\n'), ((557, 568), 'numpy.fft.fftshift', 'fftshift', (['w'], {}), '(w)\n', (565, 568), False, 'from numpy.fft import fft, ifft, fftfreq, fftshift\n'), ((570, 586), 'numpy.fft.fftshift', 'fftshift', (['f.imag'], {}), '(f.imag)\n', (578, 586), False, 'from numpy.fft import fft, ifft, fftfreq, fftshift\n')]
import os import numpy as np from tqdm import tqdm import copy import shutil from data_info.data_info import DataInfo from heatmap_generator.anisotropic_laplace_heatmap_generator import AnisotropicLaplaceHeatmapGenerator class DatasetGenerator: @classmethod def generate_dataset(cls): print('\nStep 1: Generate gt numpy file\n') cls.generate_gt_numpy() print('\nStep 2: Generate original image folder\n') cls.generate_image_folder() print('\nStep 3: Generate GT image file\n') cls.generate_heatmap() @classmethod def generate_gt_numpy(cls): r""" 랜드마크 좌표를 GT 폴더에 landmark_point_gt_numpy로 저장 0~149: train 데이터 150~299: test1 데이터 300~399: test2 데이터 """ # 랜드마크 좌표를 저장할 numpy 배열 junior_numpy = np.zeros((400, 19, 2)) senior_numpy = np.zeros((400, 19, 2)) average_numpy = np.zeros((400, 19, 2)) # 원본 데이터 폴더 junior_senior_folders = os.listdir(DataInfo.original_gt_folder_path) junior_senior_folders.sort() # 원본 데이터 폴더에서 txt 파일을 읽어 numpy 배열로 저장 # class는 저장하지 않고 건너뜀 for junior_senior_folder in junior_senior_folders: original_files = os.listdir(os.path.join(DataInfo.original_gt_folder_path, junior_senior_folder)) original_files.sort() points_numpy = np.zeros((400, 19, 2)) for original_file_index, original_file in enumerate(original_files): file = open(os.path.join(DataInfo.original_gt_folder_path, junior_senior_folder, original_file)) file_lines = file.readlines() file.close() for i, line in enumerate(file_lines): if i < 19: x, y = line.split(',') x = int(x) y = int(y) points_numpy[original_file_index][i][0] = x points_numpy[original_file_index][i][1] = y else: pass if junior_senior_folder[junior_senior_folder.index('_') + 1:] == "junior": junior_numpy = copy.deepcopy(points_numpy) else: senior_numpy = copy.deepcopy(points_numpy) # junior과 senior의 평균 구해서 numpy 배열로 저장 for gt_file_index, [junior_points, senior_points] in enumerate(zip(junior_numpy, senior_numpy)): for landmark_index, [junior_point, senior_point] in enumerate(zip(junior_points, senior_points)): average_point_x = (junior_point[0] + senior_point[0]) / 2 average_point_y = (junior_point[1] + senior_point[1]) / 2 average_point = np.array([average_point_x, average_point_y]) average_numpy[gt_file_index][landmark_index] = average_point # save os.makedirs(DataInfo.landmark_gt_numpy_folder_path, exist_ok=True) np.save(DataInfo.landmark_gt_numpy_path, average_numpy) @classmethod def generate_image_folder(cls): r""" 원본 이미지를 train_test_data 폴더의 train, test 폴더에 복사 """ # 원본 이미지 폴더(test1, test2, train) 경로를 리스트로 저장 images_folders = os.listdir(DataInfo.raw_image_folder_path) images_folders.sort() # 이미지를 이동시킬 폴더 if not os.path.exists(DataInfo.train_test_image_folder_path): os.makedirs(DataInfo.train_test_image_folder_path) for images_folder in images_folders: # Test1, Test2, Train 폴더 각각 생성 data_type = images_folder[:5].lower() input_image_folder_path = os.path.join(DataInfo.train_test_image_folder_path, data_type, 'input', 'no_label') if not os.path.exists(input_image_folder_path): os.makedirs(input_image_folder_path) images = os.listdir(os.path.join(DataInfo.raw_image_folder_path, images_folder)) images.sort() # 이미지 복사 for image in images: shutil.copy(os.path.join(DataInfo.raw_image_folder_path, images_folder, image), os.path.join(input_image_folder_path, image)) @classmethod def generate_heatmap(cls): r""" generate gt image at 'train_test_image/ - gt 이미지를 train, test1, test2 폴더에 랜드마크별로 저장 params: new_size: 새로 생성할 GT 이미지 크기. [W, H] landmark_point = [W, H] landmark_gt_numpy: 0~149: train 데이터 150~299: test1 데이터 300~399: test2 데이터 """ heatmap_generator = AnisotropicLaplaceHeatmapGenerator() landmark_gt_numpy = np.load(DataInfo.landmark_gt_numpy_path) data_type_and_numpy_zip = zip(['train', 'test1', 'test2'], [landmark_gt_numpy[0:150], landmark_gt_numpy[150:300], landmark_gt_numpy[300:400]]) for data_type, gt_numpy in data_type_and_numpy_zip: image_path = os.path.join(DataInfo.train_test_image_folder_path, data_type) for i, gt in enumerate(tqdm(gt_numpy)): for j, landmark_point in enumerate(gt): heatmap_img = heatmap_generator.get_heatmap_image(landmark_point) landmark_gt_path = os.path.join(image_path, 'heatmap', "{:0>2d}".format(j + 1)) os.makedirs(landmark_gt_path, exist_ok=True) image_name = str(i + 1).zfill(5) heatmap_img.save(os.path.join(landmark_gt_path, image_name + '.png'))
[ "numpy.load", "numpy.save", "copy.deepcopy", "os.makedirs", "tqdm.tqdm", "numpy.zeros", "os.path.exists", "heatmap_generator.anisotropic_laplace_heatmap_generator.AnisotropicLaplaceHeatmapGenerator", "numpy.array", "os.path.join", "os.listdir" ]
[((838, 860), 'numpy.zeros', 'np.zeros', (['(400, 19, 2)'], {}), '((400, 19, 2))\n', (846, 860), True, 'import numpy as np\n'), ((884, 906), 'numpy.zeros', 'np.zeros', (['(400, 19, 2)'], {}), '((400, 19, 2))\n', (892, 906), True, 'import numpy as np\n'), ((931, 953), 'numpy.zeros', 'np.zeros', (['(400, 19, 2)'], {}), '((400, 19, 2))\n', (939, 953), True, 'import numpy as np\n'), ((1007, 1051), 'os.listdir', 'os.listdir', (['DataInfo.original_gt_folder_path'], {}), '(DataInfo.original_gt_folder_path)\n', (1017, 1051), False, 'import os\n'), ((2896, 2962), 'os.makedirs', 'os.makedirs', (['DataInfo.landmark_gt_numpy_folder_path'], {'exist_ok': '(True)'}), '(DataInfo.landmark_gt_numpy_folder_path, exist_ok=True)\n', (2907, 2962), False, 'import os\n'), ((2971, 3026), 'numpy.save', 'np.save', (['DataInfo.landmark_gt_numpy_path', 'average_numpy'], {}), '(DataInfo.landmark_gt_numpy_path, average_numpy)\n', (2978, 3026), True, 'import numpy as np\n'), ((3243, 3285), 'os.listdir', 'os.listdir', (['DataInfo.raw_image_folder_path'], {}), '(DataInfo.raw_image_folder_path)\n', (3253, 3285), False, 'import os\n'), ((4680, 4716), 'heatmap_generator.anisotropic_laplace_heatmap_generator.AnisotropicLaplaceHeatmapGenerator', 'AnisotropicLaplaceHeatmapGenerator', ([], {}), '()\n', (4714, 4716), False, 'from heatmap_generator.anisotropic_laplace_heatmap_generator import AnisotropicLaplaceHeatmapGenerator\n'), ((4746, 4786), 'numpy.load', 'np.load', (['DataInfo.landmark_gt_numpy_path'], {}), '(DataInfo.landmark_gt_numpy_path)\n', (4753, 4786), True, 'import numpy as np\n'), ((1396, 1418), 'numpy.zeros', 'np.zeros', (['(400, 19, 2)'], {}), '((400, 19, 2))\n', (1404, 1418), True, 'import numpy as np\n'), ((3355, 3408), 'os.path.exists', 'os.path.exists', (['DataInfo.train_test_image_folder_path'], {}), '(DataInfo.train_test_image_folder_path)\n', (3369, 3408), False, 'import os\n'), ((3422, 3472), 'os.makedirs', 'os.makedirs', (['DataInfo.train_test_image_folder_path'], {}), '(DataInfo.train_test_image_folder_path)\n', (3433, 3472), False, 'import os\n'), ((3650, 3737), 'os.path.join', 'os.path.join', (['DataInfo.train_test_image_folder_path', 'data_type', '"""input"""', '"""no_label"""'], {}), "(DataInfo.train_test_image_folder_path, data_type, 'input',\n 'no_label')\n", (3662, 3737), False, 'import os\n'), ((5140, 5202), 'os.path.join', 'os.path.join', (['DataInfo.train_test_image_folder_path', 'data_type'], {}), '(DataInfo.train_test_image_folder_path, data_type)\n', (5152, 5202), False, 'import os\n'), ((1264, 1332), 'os.path.join', 'os.path.join', (['DataInfo.original_gt_folder_path', 'junior_senior_folder'], {}), '(DataInfo.original_gt_folder_path, junior_senior_folder)\n', (1276, 1332), False, 'import os\n'), ((2202, 2229), 'copy.deepcopy', 'copy.deepcopy', (['points_numpy'], {}), '(points_numpy)\n', (2215, 2229), False, 'import copy\n'), ((2279, 2306), 'copy.deepcopy', 'copy.deepcopy', (['points_numpy'], {}), '(points_numpy)\n', (2292, 2306), False, 'import copy\n'), ((2749, 2793), 'numpy.array', 'np.array', (['[average_point_x, average_point_y]'], {}), '([average_point_x, average_point_y])\n', (2757, 2793), True, 'import numpy as np\n'), ((3753, 3792), 'os.path.exists', 'os.path.exists', (['input_image_folder_path'], {}), '(input_image_folder_path)\n', (3767, 3792), False, 'import os\n'), ((3810, 3846), 'os.makedirs', 'os.makedirs', (['input_image_folder_path'], {}), '(input_image_folder_path)\n', (3821, 3846), False, 'import os\n'), ((3880, 3939), 'os.path.join', 'os.path.join', (['DataInfo.raw_image_folder_path', 'images_folder'], {}), '(DataInfo.raw_image_folder_path, images_folder)\n', (3892, 3939), False, 'import os\n'), ((5238, 5252), 'tqdm.tqdm', 'tqdm', (['gt_numpy'], {}), '(gt_numpy)\n', (5242, 5252), False, 'from tqdm import tqdm\n'), ((1528, 1615), 'os.path.join', 'os.path.join', (['DataInfo.original_gt_folder_path', 'junior_senior_folder', 'original_file'], {}), '(DataInfo.original_gt_folder_path, junior_senior_folder,\n original_file)\n', (1540, 1615), False, 'import os\n'), ((4050, 4116), 'os.path.join', 'os.path.join', (['DataInfo.raw_image_folder_path', 'images_folder', 'image'], {}), '(DataInfo.raw_image_folder_path, images_folder, image)\n', (4062, 4116), False, 'import os\n'), ((4146, 4190), 'os.path.join', 'os.path.join', (['input_image_folder_path', 'image'], {}), '(input_image_folder_path, image)\n', (4158, 4190), False, 'import os\n'), ((5517, 5561), 'os.makedirs', 'os.makedirs', (['landmark_gt_path'], {'exist_ok': '(True)'}), '(landmark_gt_path, exist_ok=True)\n', (5528, 5561), False, 'import os\n'), ((5653, 5704), 'os.path.join', 'os.path.join', (['landmark_gt_path', "(image_name + '.png')"], {}), "(landmark_gt_path, image_name + '.png')\n", (5665, 5704), False, 'import os\n')]
# -*- coding: utf-8 -*- # # Copyright (C) 2019 Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG), # acting on behalf of its Max Planck Institute for Intelligent Systems and the # Max Planck Institute for Biological Cybernetics. All rights reserved. # # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is holder of all proprietary rights # on this computer program. You can only use this computer program if you have closed a license agreement # with MPG or you get the right to use the computer program from someone who is authorized to grant you that right. # Any use of the computer program without a valid license is prohibited and liable to prosecution. # Contact: <EMAIL> # # # If you use this code in a research publication please consider citing the following: # # Expressive Body Capture: 3D Hands, Face, and Body from a Single Image <https://arxiv.org/abs/1904.05866> # # # Code Developed by: # <NAME> <https://www.linkedin.com/in/nghorbani/> # # 2018.12.13 import numpy as np import torch import torch.nn as nn from smplx.lbs import lbs class BodyModel(nn.Module): def __init__(self, bm_path, model_type, params =None, num_betas = 10, batch_size = 1, num_dmpls = None, path_dmpl = None, num_expressions = 10, use_posedirs = True, dtype = torch.float32): super(BodyModel, self).__init__() ''' :param bm_path: path to a SMPL model as pkl file :param num_betas: number of shape parameters to include. if betas are provided in params, num_betas would be overloaded with number of thoes betas :param batch_size: number of smpl vertices to get :param device: default on gpu :param dtype: float precision of the compuations :return: verts, trans, pose, betas ''' # Todo: if params the batchsize should be read from one of the params self.dtype = dtype self.model_type = model_type assert self.model_type in ['smpl', 'smplh', 'smplhf', 'mano_left', 'mano_right'], ValueError('model_type should be in smpl/smplh/smplhf/mano_left/mano_right.') if params is None: params = {} # -- Load SMPL params -- if '.npz' in bm_path: smpl_dict = np.load(bm_path, encoding = 'latin1') else: raise ValueError('bm_path should be either a .pkl nor .npz file') if num_dmpls is not None and path_dmpl is None: raise (ValueError('path_dmpl should be provided when using dmpls!')) use_dmpl = False if num_dmpls is not None and path_dmpl is not None: use_dmpl = True # Mean template vertices v_template = np.repeat(smpl_dict['v_template'][np.newaxis], batch_size, axis=0) self.register_buffer('v_template', torch.tensor(v_template, dtype=dtype)) self.register_buffer('f', torch.tensor(smpl_dict['f'].astype(np.int32), dtype=torch.int32)) if len(params): if 'betas' in params.keys(): num_betas = params['betas'].shape[1] if 'dmpls' in params.keys(): num_dmpls = params['dmpls'].shape[1] num_total_betas = smpl_dict['shapedirs'].shape[-1] if num_betas < 1: num_betas = num_total_betas shapedirs = smpl_dict['shapedirs'][:, :, :num_betas] self.register_buffer('shapedirs', torch.tensor(shapedirs, dtype=dtype)) if model_type == 'smplhf': exprdirs = smpl_dict['shapedirs'][:, :, 300:(300+num_expressions)] self.register_buffer('exprdirs', torch.tensor(exprdirs, dtype=dtype)) expression = torch.tensor(np.zeros((batch_size, num_expressions)), dtype=dtype, requires_grad=True) self.register_parameter('expression', nn.Parameter(expression, requires_grad=True)) if use_dmpl: raise NotImplementedError('DMPL loader not yet developed for python 3.7') # # Todo: I have changed this without testing # with open(path_dmpl, 'r') as f: # dmpl_shapedirs = pickle.load(f) # # dmpl_shapedirs = dmpl_shapedirs[:, :, :num_dmpls] # self.register_buffer('dmpl_shapedirs', torch.tensor(dmpl_shapedirs, dtype=dtype)) # Regressor for joint locations given shape - 6890 x 24 self.register_buffer('J_regressor', torch.tensor(smpl_dict['J_regressor'], dtype=dtype)) # Pose blend shape basis: 6890 x 3 x 207, reshaped to 6890*30 x 207 if use_posedirs: posedirs = smpl_dict['posedirs'] posedirs = posedirs.reshape([posedirs.shape[0] * 3, -1]).T self.register_buffer('posedirs', torch.tensor(posedirs, dtype=dtype)) else: self.posedirs = None # indices of parents for each joints kintree_table = smpl_dict['kintree_table'].astype(np.int32) self.register_buffer('kintree_table', torch.tensor(kintree_table, dtype=torch.int32)) # LBS weights # weights = np.repeat(smpl_dict['weights'][np.newaxis], batch_size, axis=0) weights = smpl_dict['weights'] self.register_buffer('weights', torch.tensor(weights, dtype=dtype)) if 'trans' in params.keys(): trans = params['trans'] else: trans = torch.tensor(np.zeros((batch_size, 3)), dtype=dtype, requires_grad = True) self.register_parameter('trans', nn.Parameter(trans, requires_grad=True)) #root_orient # if model_type in ['smpl', 'smplh']: root_orient = torch.tensor(np.zeros((batch_size, 3)), dtype=dtype, requires_grad=True) self.register_parameter('root_orient', nn.Parameter(root_orient, requires_grad=True)) #pose_body if model_type in ['smpl', 'smplh', 'smplhf']: pose_body = torch.tensor(np.zeros((batch_size, 63)), dtype=dtype, requires_grad=True) self.register_parameter('pose_body', nn.Parameter(pose_body, requires_grad=True)) # pose_hand if 'pose_hand' in params.keys(): pose_hand = params['pose_hand'] else: if model_type in ['smpl']: pose_hand = torch.tensor(np.zeros((batch_size, 1 * 3 * 2)), dtype=dtype, requires_grad=True) elif model_type in ['smplh', 'smplhf']: pose_hand = torch.tensor(np.zeros((batch_size, 15 * 3 * 2)), dtype=dtype, requires_grad=True) elif model_type in ['mano_left', 'mano_right']: pose_hand = torch.tensor(np.zeros((batch_size, 15 * 3)), dtype=dtype, requires_grad=True) self.register_parameter('pose_hand', nn.Parameter(pose_hand, requires_grad=True)) # face poses if model_type == 'smplhf': pose_jaw = torch.tensor(np.zeros((batch_size, 1 * 3)), dtype=dtype, requires_grad=True) self.register_parameter('pose_jaw', nn.Parameter(pose_jaw, requires_grad=True)) pose_eye = torch.tensor(np.zeros((batch_size, 2 * 3)), dtype=dtype, requires_grad=True) self.register_parameter('pose_eye', nn.Parameter(pose_eye, requires_grad=True)) if 'betas' in params.keys(): betas = params['betas'] else: betas = torch.tensor(np.zeros((batch_size, num_betas)), dtype=dtype, requires_grad=True) self.register_parameter('betas', nn.Parameter(betas, requires_grad=True)) if use_dmpl: if 'dmpls' in params.keys(): dmpls = params['dmpls'] else: dmpls = torch.tensor(np.zeros((batch_size, num_dmpls)), dtype=dtype, requires_grad=True) self.register_parameter('dmpls', nn.Parameter(dmpls, requires_grad=True)) self.batch_size = batch_size def r(self): from human_body_prior.tools.omni_tools import copy2cpu as c2c return c2c(self.forward().v) def forward(self, root_orient=None, pose_body = None, pose_hand=None, pose_jaw=None, pose_eye=None, betas = None, trans = None, **kwargs): ''' :param root_orient: Nx3 :param pose_body: :param pose_hand: :param pose_jaw: :param pose_eye: :param kwargs: :return: ''' assert self.model_type in ['smpl', 'smplh', 'smplhf', 'mano_left', 'mano_right'], ValueError('model_type should be in smpl/smplh/smplhf/mano_left/mano_right.') if root_orient is None: root_orient = self.root_orient if self.model_type in ['smplh', 'smpl']: if pose_body is None: pose_body = self.pose_body if pose_hand is None: pose_hand = self.pose_hand elif self.model_type == 'smplhf': if pose_body is None: pose_body = self.pose_body if pose_hand is None: pose_hand = self.pose_hand if pose_jaw is None: pose_jaw = self.pose_jaw if pose_eye is None: pose_eye = self.pose_eye elif self.model_type in ['mano_left', 'mano_right']: if pose_hand is None: pose_hand = self.pose_hand if trans is None: trans = self.trans if betas is None: betas = self.betas if self.model_type in ['smplh', 'smpl']: full_pose = torch.cat([root_orient, pose_body, pose_hand], dim=1) elif self.model_type == 'smplhf': full_pose = torch.cat([root_orient, pose_body, pose_jaw, pose_eye, pose_hand], dim=1) # orient:3, body:63, jaw:3, eyel:3, eyer:3, handl, handr elif self.model_type in ['mano_left', 'mano_right']: full_pose = torch.cat([root_orient, pose_hand], dim=1) if self.model_type == 'smplhf': shape_components = torch.cat([betas, self.expression], dim=-1) shapedirs = torch.cat([self.shapedirs, self.exprdirs], dim=-1) else: shape_components = betas shapedirs = self.shapedirs verts, joints = lbs(betas=shape_components, pose=full_pose, v_template=self.v_template, shapedirs=shapedirs, posedirs=self.posedirs, J_regressor=self.J_regressor, parents=self.kintree_table[0].long(), lbs_weights=self.weights, dtype=self.dtype) Jtr = joints + trans.unsqueeze(dim=1) verts = verts + trans.unsqueeze(dim=1) class result_meta(object): pass res = result_meta() res.v = verts res.f = self.f res.betas = self.betas res.Jtr = Jtr #Todo: ik can be made with vposer if self.model_type == 'smpl': res.pose_body = pose_body elif self.model_type == 'smplh': res.pose_body = pose_body res.pose_hand = pose_hand elif self.model_type == 'smplhf': res.pose_body = pose_body res.pose_hand = pose_hand res.pose_jaw = pose_jaw res.pose_eye = pose_eye elif self.model_type in ['mano_left', 'mano_right']: res.pose_hand = pose_hand res.full_pose = full_pose return res class BodyModelWithPoser(BodyModel): def __init__(self, poser_type, smpl_exp_dir='0020_06', mano_exp_dir=None, **kwargs): ''' :param poser_type: vposer/gposer :param kwargs: ''' super(BodyModelWithPoser, self).__init__(**kwargs) self.poser_type = poser_type if self.poser_type == 'vposer': self.has_gravity = True if '003' in smpl_exp_dir else False if self.model_type == 'smpl': from human_body_prior.tools.model_loader import load_vposer as poser_loader self.poser_body_pt, self.poser_body_ps = poser_loader(smpl_exp_dir) self.poser_body_pt.to(self.trans.device) poZ_body = torch.tensor(np.zeros([self.batch_size, self.poser_body_ps.latentD]), requires_grad=True, dtype=self.trans.dtype) self.register_parameter('poZ_body', nn.Parameter(poZ_body, requires_grad=True)) self.pose_body.requires_grad = False elif self.model_type in ['smplh', 'smplhf']: # from experiments.nima.body_prior.tools_pt.load_vposer import load_vposer as poser_loader from human_body_prior.tools.model_loader import load_vposer as poser_loader # body self.poser_body_pt, self.poser_body_ps = poser_loader(smpl_exp_dir) self.poser_body_pt.to(self.trans.device) poZ_body = self.pose_body.new(np.zeros([self.batch_size, self.poser_body_ps.latentD])) self.register_parameter('poZ_body', nn.Parameter(poZ_body, requires_grad=True)) self.pose_body.requires_grad = False # hand left self.poser_handL_pt, self.poser_handL_ps = poser_loader(mano_exp_dir) self.poser_handL_pt.to(self.trans.device) poZ_handL = self.pose_hand.new(np.zeros([self.batch_size, self.poser_handL_ps.latentD])) self.register_parameter('poZ_handL', nn.Parameter(poZ_handL, requires_grad=True)) # hand right self.poser_handR_pt, self.poser_handR_ps = poser_loader(mano_exp_dir) self.poser_handR_pt.to(self.trans.device) poZ_handR = self.pose_hand.new(np.zeros([self.batch_size, self.poser_handR_ps.latentD])) self.register_parameter('poZ_handR', nn.Parameter(poZ_handR, requires_grad=True)) self.pose_hand.requires_grad = False elif self.model_type in ['mano_left', 'mano_right']: from human_body_prior.tools.model_loader import load_vposer as poser_loader self.poser_hand_pt, self.poser_hand_ps = poser_loader(mano_exp_dir) self.poser_hand_pt.to(self.trans.device) poZ_hand = self.pose_hand.new(np.zeros([self.batch_size, self.poser_hand_ps.latentD])) self.register_parameter('poZ_hand', nn.Parameter(poZ_hand, requires_grad=True)) self.pose_hand.requires_grad = False def forward(self, **kwargs): if self.poser_type == 'vposer': if self.model_type == 'smpl': pose_body = self.poser_body_pt.decode(self.poZ_body, output_type='aa').view(self.batch_size, -1) new_body = super(BodyModelWithPoser, self).forward(pose_body=pose_body, **kwargs) new_body.poZ_body = self.poZ_body elif self.model_type in ['smplh', 'smplhf']: pose_body = self.poser_body_pt.decode(self.poZ_body, output_type='aa').view(self.batch_size, -1) pose_handL = self.poser_handL_pt.decode(self.poZ_handL, output_type='aa').view(self.batch_size, -1) pose_handR = self.poser_handR_pt.decode(self.poZ_handR, output_type='aa').view(self.batch_size, -1) pose_hand = torch.cat([pose_handL, pose_handR], dim=1) # new_body = BodyModel.forward(self, pose_body=pose_body, pose_hand=pose_hand) new_body = super(BodyModelWithPoser, self).forward(pose_body=pose_body, pose_hand=pose_hand, **kwargs) elif self.model_type in ['mano_left', 'mano_right']: pose_hand = self.poser_hand_pt.decode(self.poZ_hand, output_type='aa').view(self.batch_size, -1) # new_body = BodyModel.forward(self, pose_hand=pose_hand) new_body = super(BodyModelWithPoser, self).forward(pose_hand=pose_hand, **kwargs) else: new_body = BodyModel.forward(self) return new_body def randomize_pose(self): if self.poser_type == 'vposer': if self.model_type == 'smpl': with torch.no_grad(): self.poZ_body.data[:] = self.poZ_body.new(np.random.randn(*list(self.poZ_body.shape))).detach() self.pose_body.data[:] = self.poser_body_pt.decode(self.poZ_body, output_type='aa').view(self.batch_size, -1) elif self.model_type in ['smplh', 'smplhf']: with torch.no_grad(): self.poZ_body.data[:] = self.poZ_body.new(np.random.randn(*list(self.poZ_body.shape))).detach() self.poZ_handL.data[:] = self.poZ_handL.new(np.random.randn(*list(self.poZ_handL.shape))).detach() self.poZ_handR.data[:] = self.poZ_handR.new(np.random.randn(*list(self.poZ_handR.shape))).detach() self.pose_body.data[:] = self.poser_body_pt.decode(self.poZ_body, output_type='aa').view(self.batch_size, -1) pose_handL = self.poser_handL_pt.decode(self.poZ_handL, output_type='aa').view(self.batch_size, -1) pose_handR = self.poser_handR_pt.decode(self.poZ_handR, output_type='aa').view(self.batch_size, -1) self.pose_hand.data[:] = torch.cat([pose_handL, pose_handR], dim=1)
[ "torch.nn.Parameter", "numpy.load", "human_body_prior.tools.model_loader.load_vposer", "numpy.zeros", "torch.cat", "torch.no_grad", "torch.tensor", "numpy.repeat" ]
[((2797, 2863), 'numpy.repeat', 'np.repeat', (["smpl_dict['v_template'][np.newaxis]", 'batch_size'], {'axis': '(0)'}), "(smpl_dict['v_template'][np.newaxis], batch_size, axis=0)\n", (2806, 2863), True, 'import numpy as np\n'), ((2384, 2419), 'numpy.load', 'np.load', (['bm_path'], {'encoding': '"""latin1"""'}), "(bm_path, encoding='latin1')\n", (2391, 2419), True, 'import numpy as np\n'), ((2907, 2944), 'torch.tensor', 'torch.tensor', (['v_template'], {'dtype': 'dtype'}), '(v_template, dtype=dtype)\n', (2919, 2944), False, 'import torch\n'), ((3490, 3526), 'torch.tensor', 'torch.tensor', (['shapedirs'], {'dtype': 'dtype'}), '(shapedirs, dtype=dtype)\n', (3502, 3526), False, 'import torch\n'), ((4479, 4530), 'torch.tensor', 'torch.tensor', (["smpl_dict['J_regressor']"], {'dtype': 'dtype'}), "(smpl_dict['J_regressor'], dtype=dtype)\n", (4491, 4530), False, 'import torch\n'), ((5039, 5085), 'torch.tensor', 'torch.tensor', (['kintree_table'], {'dtype': 'torch.int32'}), '(kintree_table, dtype=torch.int32)\n', (5051, 5085), False, 'import torch\n'), ((5273, 5307), 'torch.tensor', 'torch.tensor', (['weights'], {'dtype': 'dtype'}), '(weights, dtype=dtype)\n', (5285, 5307), False, 'import torch\n'), ((5533, 5572), 'torch.nn.Parameter', 'nn.Parameter', (['trans'], {'requires_grad': '(True)'}), '(trans, requires_grad=True)\n', (5545, 5572), True, 'import torch.nn as nn\n'), ((5677, 5702), 'numpy.zeros', 'np.zeros', (['(batch_size, 3)'], {}), '((batch_size, 3))\n', (5685, 5702), True, 'import numpy as np\n'), ((5784, 5829), 'torch.nn.Parameter', 'nn.Parameter', (['root_orient'], {'requires_grad': '(True)'}), '(root_orient, requires_grad=True)\n', (5796, 5829), True, 'import torch.nn as nn\n'), ((6738, 6781), 'torch.nn.Parameter', 'nn.Parameter', (['pose_hand'], {'requires_grad': '(True)'}), '(pose_hand, requires_grad=True)\n', (6750, 6781), True, 'import torch.nn as nn\n'), ((7454, 7493), 'torch.nn.Parameter', 'nn.Parameter', (['betas'], {'requires_grad': '(True)'}), '(betas, requires_grad=True)\n', (7466, 7493), True, 'import torch.nn as nn\n'), ((9317, 9370), 'torch.cat', 'torch.cat', (['[root_orient, pose_body, pose_hand]'], {'dim': '(1)'}), '([root_orient, pose_body, pose_hand], dim=1)\n', (9326, 9370), False, 'import torch\n'), ((9772, 9815), 'torch.cat', 'torch.cat', (['[betas, self.expression]'], {'dim': '(-1)'}), '([betas, self.expression], dim=-1)\n', (9781, 9815), False, 'import torch\n'), ((9840, 9890), 'torch.cat', 'torch.cat', (['[self.shapedirs, self.exprdirs]'], {'dim': '(-1)'}), '([self.shapedirs, self.exprdirs], dim=-1)\n', (9849, 9890), False, 'import torch\n'), ((3688, 3723), 'torch.tensor', 'torch.tensor', (['exprdirs'], {'dtype': 'dtype'}), '(exprdirs, dtype=dtype)\n', (3700, 3723), False, 'import torch\n'), ((3764, 3803), 'numpy.zeros', 'np.zeros', (['(batch_size, num_expressions)'], {}), '((batch_size, num_expressions))\n', (3772, 3803), True, 'import numpy as np\n'), ((3888, 3932), 'torch.nn.Parameter', 'nn.Parameter', (['expression'], {'requires_grad': '(True)'}), '(expression, requires_grad=True)\n', (3900, 3932), True, 'import torch.nn as nn\n'), ((4795, 4830), 'torch.tensor', 'torch.tensor', (['posedirs'], {'dtype': 'dtype'}), '(posedirs, dtype=dtype)\n', (4807, 4830), False, 'import torch\n'), ((5430, 5455), 'numpy.zeros', 'np.zeros', (['(batch_size, 3)'], {}), '((batch_size, 3))\n', (5438, 5455), True, 'import numpy as np\n'), ((5942, 5968), 'numpy.zeros', 'np.zeros', (['(batch_size, 63)'], {}), '((batch_size, 63))\n', (5950, 5968), True, 'import numpy as np\n'), ((6052, 6095), 'torch.nn.Parameter', 'nn.Parameter', (['pose_body'], {'requires_grad': '(True)'}), '(pose_body, requires_grad=True)\n', (6064, 6095), True, 'import torch.nn as nn\n'), ((6876, 6905), 'numpy.zeros', 'np.zeros', (['(batch_size, 1 * 3)'], {}), '((batch_size, 1 * 3))\n', (6884, 6905), True, 'import numpy as np\n'), ((6988, 7030), 'torch.nn.Parameter', 'nn.Parameter', (['pose_jaw'], {'requires_grad': '(True)'}), '(pose_jaw, requires_grad=True)\n', (7000, 7030), True, 'import torch.nn as nn\n'), ((7068, 7097), 'numpy.zeros', 'np.zeros', (['(batch_size, 2 * 3)'], {}), '((batch_size, 2 * 3))\n', (7076, 7097), True, 'import numpy as np\n'), ((7180, 7222), 'torch.nn.Parameter', 'nn.Parameter', (['pose_eye'], {'requires_grad': '(True)'}), '(pose_eye, requires_grad=True)\n', (7192, 7222), True, 'import torch.nn as nn\n'), ((7345, 7378), 'numpy.zeros', 'np.zeros', (['(batch_size, num_betas)'], {}), '((batch_size, num_betas))\n', (7353, 7378), True, 'import numpy as np\n'), ((7766, 7805), 'torch.nn.Parameter', 'nn.Parameter', (['dmpls'], {'requires_grad': '(True)'}), '(dmpls, requires_grad=True)\n', (7778, 7805), True, 'import torch.nn as nn\n'), ((9441, 9514), 'torch.cat', 'torch.cat', (['[root_orient, pose_body, pose_jaw, pose_eye, pose_hand]'], {'dim': '(1)'}), '([root_orient, pose_body, pose_jaw, pose_eye, pose_hand], dim=1)\n', (9450, 9514), False, 'import torch\n'), ((11845, 11871), 'human_body_prior.tools.model_loader.load_vposer', 'poser_loader', (['smpl_exp_dir'], {}), '(smpl_exp_dir)\n', (11857, 11871), True, 'from human_body_prior.tools.model_loader import load_vposer as poser_loader\n'), ((6297, 6330), 'numpy.zeros', 'np.zeros', (['(batch_size, 1 * 3 * 2)'], {}), '((batch_size, 1 * 3 * 2))\n', (6305, 6330), True, 'import numpy as np\n'), ((7653, 7686), 'numpy.zeros', 'np.zeros', (['(batch_size, num_dmpls)'], {}), '((batch_size, num_dmpls))\n', (7661, 7686), True, 'import numpy as np\n'), ((9657, 9699), 'torch.cat', 'torch.cat', (['[root_orient, pose_hand]'], {'dim': '(1)'}), '([root_orient, pose_hand], dim=1)\n', (9666, 9699), False, 'import torch\n'), ((11970, 12025), 'numpy.zeros', 'np.zeros', (['[self.batch_size, self.poser_body_ps.latentD]'], {}), '([self.batch_size, self.poser_body_ps.latentD])\n', (11978, 12025), True, 'import numpy as np\n'), ((12163, 12205), 'torch.nn.Parameter', 'nn.Parameter', (['poZ_body'], {'requires_grad': '(True)'}), '(poZ_body, requires_grad=True)\n', (12175, 12205), True, 'import torch.nn as nn\n'), ((12598, 12624), 'human_body_prior.tools.model_loader.load_vposer', 'poser_loader', (['smpl_exp_dir'], {}), '(smpl_exp_dir)\n', (12610, 12624), True, 'from human_body_prior.tools.model_loader import load_vposer as poser_loader\n'), ((13023, 13049), 'human_body_prior.tools.model_loader.load_vposer', 'poser_loader', (['mano_exp_dir'], {}), '(mano_exp_dir)\n', (13035, 13049), True, 'from human_body_prior.tools.model_loader import load_vposer as poser_loader\n'), ((13401, 13427), 'human_body_prior.tools.model_loader.load_vposer', 'poser_loader', (['mano_exp_dir'], {}), '(mano_exp_dir)\n', (13413, 13427), True, 'from human_body_prior.tools.model_loader import load_vposer as poser_loader\n'), ((15105, 15147), 'torch.cat', 'torch.cat', (['[pose_handL, pose_handR]'], {'dim': '(1)'}), '([pose_handL, pose_handR], dim=1)\n', (15114, 15147), False, 'import torch\n'), ((15934, 15949), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (15947, 15949), False, 'import torch\n'), ((6458, 6492), 'numpy.zeros', 'np.zeros', (['(batch_size, 15 * 3 * 2)'], {}), '((batch_size, 15 * 3 * 2))\n', (6466, 6492), True, 'import numpy as np\n'), ((12729, 12784), 'numpy.zeros', 'np.zeros', (['[self.batch_size, self.poser_body_ps.latentD]'], {}), '([self.batch_size, self.poser_body_ps.latentD])\n', (12737, 12784), True, 'import numpy as np\n'), ((12838, 12880), 'torch.nn.Parameter', 'nn.Parameter', (['poZ_body'], {'requires_grad': '(True)'}), '(poZ_body, requires_grad=True)\n', (12850, 12880), True, 'import torch.nn as nn\n'), ((13156, 13212), 'numpy.zeros', 'np.zeros', (['[self.batch_size, self.poser_handL_ps.latentD]'], {}), '([self.batch_size, self.poser_handL_ps.latentD])\n', (13164, 13212), True, 'import numpy as np\n'), ((13267, 13310), 'torch.nn.Parameter', 'nn.Parameter', (['poZ_handL'], {'requires_grad': '(True)'}), '(poZ_handL, requires_grad=True)\n', (13279, 13310), True, 'import torch.nn as nn\n'), ((13534, 13590), 'numpy.zeros', 'np.zeros', (['[self.batch_size, self.poser_handR_ps.latentD]'], {}), '([self.batch_size, self.poser_handR_ps.latentD])\n', (13542, 13590), True, 'import numpy as np\n'), ((13645, 13688), 'torch.nn.Parameter', 'nn.Parameter', (['poZ_handR'], {'requires_grad': '(True)'}), '(poZ_handR, requires_grad=True)\n', (13657, 13688), True, 'import torch.nn as nn\n'), ((13959, 13985), 'human_body_prior.tools.model_loader.load_vposer', 'poser_loader', (['mano_exp_dir'], {}), '(mano_exp_dir)\n', (13971, 13985), True, 'from human_body_prior.tools.model_loader import load_vposer as poser_loader\n'), ((16276, 16291), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (16289, 16291), False, 'import torch\n'), ((17063, 17105), 'torch.cat', 'torch.cat', (['[pose_handL, pose_handR]'], {'dim': '(1)'}), '([pose_handL, pose_handR], dim=1)\n', (17072, 17105), False, 'import torch\n'), ((6628, 6658), 'numpy.zeros', 'np.zeros', (['(batch_size, 15 * 3)'], {}), '((batch_size, 15 * 3))\n', (6636, 6658), True, 'import numpy as np\n'), ((14090, 14145), 'numpy.zeros', 'np.zeros', (['[self.batch_size, self.poser_hand_ps.latentD]'], {}), '([self.batch_size, self.poser_hand_ps.latentD])\n', (14098, 14145), True, 'import numpy as np\n'), ((14199, 14241), 'torch.nn.Parameter', 'nn.Parameter', (['poZ_hand'], {'requires_grad': '(True)'}), '(poZ_hand, requires_grad=True)\n', (14211, 14241), True, 'import torch.nn as nn\n')]
# -*- coding: utf-8 -*- """System transmission plots. This code creates transmission line and interface plots. @author: <NAME>, <NAME> """ import os import logging import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.colors as mcolors import matplotlib.dates as mdates import marmot.config.mconfig as mconfig from marmot.plottingmodules.plotutils.plot_library import PlotLibrary from marmot.plottingmodules.plotutils.plot_data_helper import PlotDataHelper from marmot.plottingmodules.plotutils.plot_exceptions import (MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData) class MPlot(PlotDataHelper): """transmission MPlot class. All the plotting modules use this same class name. This class contains plotting methods that are grouped based on the current module name. The transmission.py module contains methods that are related to the transmission network. MPlot inherits from the PlotDataHelper class to assist in creating figures. """ def __init__(self, argument_dict: dict): """ Args: argument_dict (dict): Dictionary containing all arguments passed from MarmotPlot. """ # iterate over items in argument_dict and set as properties of class # see key_list in Marmot_plot_main for list of properties for prop in argument_dict: self.__setattr__(prop, argument_dict[prop]) # Instantiation of MPlotHelperFunctions super().__init__(self.Marmot_Solutions_folder, self.AGG_BY, self.ordered_gen, self.PLEXOS_color_dict, self.Scenarios, self.ylabels, self.xlabels, self.gen_names_dict, self.TECH_SUBSET, Region_Mapping=self.Region_Mapping) self.logger = logging.getLogger('marmot_plot.'+__name__) self.font_defaults = mconfig.parser("font_settings") def line_util(self, **kwargs): """Creates a timeseries line plot of transmission lineflow utilization for each region. Utilization is plotted between 0 and 1 on the y-axis. The plot will default to showing the 10 highest utilized lines. A Line category can also be passed instead, using the property field in the Marmot_plot_select.csv Each scenarios is plotted on a separate Facet plot. This methods calls _util() to create the figure. Returns: dict: Dictionary containing the created plot and its data table. """ outputs = self._util(**kwargs) return outputs def line_hist(self, **kwargs): """Creates a histogram of transmission lineflow utilization for each region. Utilization is plotted between 0 and 1 on the x-axis, with # lines on the y-axis. Each bar is equal to a 0.05 utilization rate The plot will default to showing all lines. A Line category can also be passed instead using the property field in the Marmot_plot_select.csv Each scenarios is plotted on a separate Facet plot. This methods calls _util() and passes the hist=True argument to create the figure. Returns: dict: Dictionary containing the created plot and its data table. """ outputs = self._util(hist=True, **kwargs) return outputs def _util(self, hist: bool = False, prop: str = None, start_date_range: str = None, end_date_range: str = None, **_): """Creates utilization plots, line plot and histograms This methods is called from line_util() and line_hist() Args: hist (bool, optional): If True creates a histogram of utilization. Defaults to False. prop (str, optional): Optional PLEXOS line category to display. Defaults to None. start_date_range (str, optional): Defines a start date at which to represent data from. Defaults to None. end_date_range (str, optional): Defines a end date at which to represent data to. Defaults to None. Returns: dict: Dictionary containing the created plot and its data table. """ outputs = {} # List of properties needed by the plot, properties are a set of tuples and contain 3 parts: # required True/False, property name and scenarios required, scenarios must be a list. properties = [(True,"line_Flow",self.Scenarios), (True,"line_Import_Limit",self.Scenarios)] # Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary # with all required properties, returns a 1 if required data is missing check_input_data = self.get_formatted_data(properties) if 1 in check_input_data: return MissingInputData() # sets up x, y dimensions of plot ncols, nrows = self.set_facet_col_row_dimensions(facet=True, multi_scenario=self.Scenarios) grid_size = ncols*nrows # Used to calculate any excess axis to delete plot_number = len(self.Scenarios) excess_axs = grid_size - plot_number for zone_input in self.Zones: self.logger.info(f"For all lines touching Zone = {zone_input}") mplt = PlotLibrary(nrows, ncols, sharey=True, squeeze=False, ravel_axs=True) fig, axs = mplt.get_figure() plt.subplots_adjust(wspace=0.1, hspace=0.25) data_table=[] for n, scenario in enumerate(self.Scenarios): self.logger.info(f"Scenario = {str(scenario)}") # gets correct metadata based on area aggregation if self.AGG_BY=='zone': zone_lines = self.meta.zone_lines(scenario) else: zone_lines = self.meta.region_lines(scenario) try: zone_lines = zone_lines.set_index([self.AGG_BY]) except: self.logger.warning("Column to Aggregate by is missing") continue try: zone_lines = zone_lines.xs(zone_input) zone_lines=zone_lines['line_name'].unique() except KeyError: self.logger.warning('No data to plot for scenario') outputs[zone_input] = MissingZoneData() continue flow = self["line_Flow"].get(scenario).copy() #Limit to only lines touching to this zone flow = flow[flow.index.get_level_values('line_name').isin(zone_lines)] if self.shift_leapday == True: flow = self.adjust_for_leapday(flow) limits = self["line_Import_Limit"].get(scenario).copy() limits = limits.droplevel('timestamp').drop_duplicates() limits.mask(limits[0]==0.0,other=0.01,inplace=True) #if limit is zero set to small value # This checks for a nan in string. If no scenario selected, do nothing. if pd.notna(prop): self.logger.info(f"Line category = {str(prop)}") line_relations = self.meta.lines(scenario).rename(columns={"name":"line_name"}).set_index(["line_name"]) flow=pd.merge(flow,line_relations, left_index=True, right_index=True) flow=flow[flow["category"] == prop] flow=flow.drop('category',axis=1) flow = pd.merge(flow,limits[0].abs(),on = 'line_name',how='left') flow['Util']=(flow['0_x'].abs()/flow['0_y']).fillna(0) #If greater than 1 because exceeds flow limit, report as 1 flow['Util'][flow['Util'] > 1] = 1 annual_util=flow['Util'].groupby(["line_name"]).mean().rename(scenario) # top annual utilized lines top_utilization = annual_util.nlargest(10, keep='first') color_dict = dict(zip(self.Scenarios,self.color_list)) if hist == True: mplt.histogram(annual_util, color_dict,label=scenario, sub_pos=n) else: for line in top_utilization.index.get_level_values(level='line_name').unique(): duration_curve = flow.loc[line].sort_values(by='Util', ascending=False).reset_index(drop=True) mplt.lineplot(duration_curve, 'Util' ,label=line, sub_pos=n) axs[n].set_ylim((0,1.1)) data_table.append(annual_util) mplt.add_legend() #Remove extra axes mplt.remove_excess_axs(excess_axs,grid_size) # add facet labels mplt.add_facet_labels(xlabels=self.xlabels, ylabels = self.ylabels) if hist == True: if pd.notna(prop): prop_name = 'All Lines' else: prop_name = prop plt.ylabel('Number of lines', color='black', rotation='vertical', labelpad=30) plt.xlabel(f'Line Utilization: {prop_name}', color='black', rotation='horizontal', labelpad=30) else: if pd.notna(prop): prop_name ='Top 10 Lines' else: prop_name = prop plt.ylabel(f'Line Utilization: {prop_name}', color='black', rotation='vertical', labelpad=60) plt.xlabel('Intervals', color='black', rotation='horizontal', labelpad=20) if mconfig.parser("plot_title_as_region"): mplt.add_main_title(zone_input) try: del annual_util, except: continue Data_Out = pd.concat(data_table) outputs[zone_input] = {'fig': fig,'data_table':Data_Out} return outputs def int_flow_ind(self, figure_name: str = None, prop: str = None, start_date_range: str = None, end_date_range: str = None, **_): """Creates a line plot of interchange flows and their import and export limits. Each interchange is potted on a separate facet plot. The plot includes every interchange that originates or ends in the aggregation zone. This can be adjusted by passing a comma separated string of interchanges to the property input. The code will create either a timeseries or duration curve depending on if the word 'duration_curve' is in the figure_name. To make a duration curve, ensure the word 'duration_curve' is found in the figure_name. Args: figure_name (str, optional): User defined figure output name. Defaults to None. prop (str, optional): Comma separated string of interchanges. Defaults to None. start_date_range (str, optional): Defines a start date at which to represent data from. Defaults to None. end_date_range (str, optional): Defines a end date at which to represent data to. Defaults to None. Returns: dict: dictionary containing the created plot and its data table """ duration_curve=False if 'duration_curve' in figure_name: duration_curve = True # List of properties needed by the plot, properties are a set of tuples and contain 3 parts: # required True/False, property name and scenarios required, scenarios must be a list. properties = [(True,"interface_Flow",self.Scenarios), (True,"interface_Import_Limit",self.Scenarios), (True,"interface_Export_Limit",self.Scenarios)] # Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary # with all required properties, returns a 1 if required data is missing check_input_data = self.get_formatted_data(properties) if 1 in check_input_data: return MissingInputData() scenario = self.Scenarios[0] outputs = {} if pd.notna(start_date_range): self.logger.info(f"Plotting specific date range: \ {str(start_date_range)} to {str(end_date_range)}") for zone_input in self.Zones: self.logger.info(f"For all interfaces touching Zone = {zone_input}") Data_Table_Out = pd.DataFrame() # gets correct metadata based on area aggregation if self.AGG_BY=='zone': zone_lines = self.meta.zone_lines(scenario) else: zone_lines = self.meta.region_lines(scenario) try: zone_lines = zone_lines.set_index([self.AGG_BY]) except: self.logger.info("Column to Aggregate by is missing") continue zone_lines = zone_lines.xs(zone_input) zone_lines = zone_lines['line_name'].unique() #Map lines to interfaces all_ints = self.meta.interface_lines(scenario) #Map lines to interfaces all_ints.index = all_ints.line ints = all_ints.loc[all_ints.index.intersection(zone_lines)] #flow = flow[flow.index.get_level_values('interface_name').isin(ints.interface)] #Limit to only interfaces touching to this zone #flow = flow.droplevel('interface_category') export_limits = self["interface_Export_Limit"].get(scenario).copy().droplevel('timestamp') export_limits.mask(export_limits[0]==0.0,other=0.01,inplace=True) #if limit is zero set to small value export_limits = export_limits[export_limits.index.get_level_values('interface_name').isin(ints.interface)] export_limits = export_limits[export_limits[0].abs() < 99998] #Filter out unenforced interfaces. #Drop unnecessary columns. export_limits.reset_index(inplace = True) export_limits.drop(columns=['interface_category', 'units'], inplace=True) export_limits.set_index('interface_name',inplace = True) import_limits = self["interface_Import_Limit"].get(scenario).copy().droplevel('timestamp') import_limits.mask(import_limits[0]==0.0,other=0.01,inplace=True) #if limit is zero set to small value import_limits = import_limits[import_limits.index.get_level_values('interface_name').isin(ints.interface)] import_limits = import_limits[import_limits[0].abs() < 99998] #Filter out unenforced interfaces. reported_ints = import_limits.index.get_level_values('interface_name').unique() #Drop unnecessary columns. import_limits.reset_index(inplace = True) import_limits.drop(columns=['interface_category', 'units'], inplace=True) import_limits.set_index('interface_name',inplace = True) #Extract time index ti = self["interface_Flow"][self.Scenarios[0]].index.get_level_values('timestamp').unique() if pd.notna(prop): interf_list = prop.split(',') self.logger.info('Plotting only interfaces specified in Marmot_plot_select.csv') self.logger.info(interf_list) else: interf_list = reported_ints.copy() self.logger.info('Plotting full time series results.') xdim,ydim = self.set_x_y_dimension(len(interf_list)) mplt = PlotLibrary(ydim, xdim, squeeze=False, ravel_axs=True) fig, axs = mplt.get_figure() grid_size = xdim * ydim excess_axs = grid_size - len(interf_list) plt.subplots_adjust(wspace=0.05, hspace=0.2) missing_ints = 0 chunks = [] n = -1 for interf in interf_list: n += 1 #Remove leading spaces if interf[0] == ' ': interf = interf[1:] if interf in reported_ints: chunks_interf = [] single_exp_lim = export_limits.loc[interf] / 1000 #TODO: Use auto unit converter single_imp_lim = import_limits.loc[interf] / 1000 #Check if all hours have the same limit. check = single_exp_lim.to_numpy() identical = check[0] == check.all() limits = pd.concat([single_exp_lim,single_imp_lim],axis = 1) limits.columns = ['export limit','import limit'] limits.index = ti for scenario in self.Scenarios: flow = self["interface_Flow"].get(scenario) single_int = flow.xs(interf, level='interface_name') / 1000 single_int.index = single_int.index.droplevel(['interface_category','units']) single_int.columns = [interf] single_int = single_int.reset_index().set_index('timestamp') limits = limits.reset_index().set_index('timestamp') if self.shift_leapday == True: single_int = self.adjust_for_leapday(single_int) if pd.notna(start_date_range): single_int = single_int[start_date_range : end_date_range] limits = limits[start_date_range : end_date_range] if duration_curve: single_int = self.sort_duration(single_int,interf) mplt.lineplot(single_int, interf, label=f"{scenario}\n interface flow", sub_pos=n) # Only print limits if it doesn't change monthly or if you are plotting a time series. # Otherwise the limit lines could be misleading. if not duration_curve or identical[0]: if scenario == self.Scenarios[-1]: #Only plot limits for last scenario. limits_color_dict = {'export limit': 'red', 'import limit': 'green'} mplt.lineplot(limits, 'export limit', label='export limit', color=limits_color_dict, linestyle='--', sub_pos=n) mplt.lineplot(limits, 'import limit', label='import limit', color=limits_color_dict, linestyle='--', sub_pos=n) #For output time series .csv scenario_names = pd.Series([scenario] * len(single_int), name='Scenario') single_int_out = single_int.set_index([scenario_names], append=True) chunks_interf.append(single_int_out) Data_out_line = pd.concat(chunks_interf,axis = 0) Data_out_line.columns = [interf] chunks.append(Data_out_line) else: self.logger.warning(f"{interf} not found in results. Have you tagged " "it with the 'Must Report' property in PLEXOS?") excess_axs += 1 missing_ints += 1 continue axs[n].set_title(interf) if not duration_curve: mplt.set_subplot_timeseries_format(sub_pos=n) if missing_ints == len(interf_list): outputs = MissingInputData() return outputs Data_Table_Out = pd.concat(chunks,axis = 1) Data_Table_Out = Data_Table_Out.reset_index() index_name = 'level_0' if duration_curve else 'timestamp' Data_Table_Out = Data_Table_Out.pivot(index = index_name,columns = 'Scenario') #Limits_Out = pd.concat(limits_chunks,axis = 1) #Limits_Out.index = ['Export Limit','Import Limit'] # Data_Table_Out = Data_Table_Out.reset_index() # Data_Table_Out = Data_Table_Out.groupby(Data_Table_Out.index // 24).mean() # Data_Table_Out.index = pd.date_range(start = '1/1/2024',end = '12/31/2024',freq = 'D') mplt.add_legend() plt.ylabel('Flow (GW)', color='black', rotation='vertical', labelpad=30) if duration_curve: plt.xlabel('Sorted hour of the year', color='black', labelpad=30) plt.tight_layout(rect=[0, 0.03, 1, 0.97]) if mconfig.parser("plot_title_as_region"): mplt.add_main_title(zone_input) outputs[zone_input] = {'fig': fig, 'data_table': Data_Table_Out} #Limits_Out.to_csv(os.path.join(self.Marmot_Solutions_folder, 'Figures_Output',self.AGG_BY + '_transmission','Individual_Interface_Limits.csv')) return outputs def int_flow_ind_seasonal(self, figure_name: str = None, prop: str = None, start_date_range: str = None, end_date_range: str = None, **_): """#TODO: Finish Docstring Args: figure_name (str, optional): User defined figure output name. Defaults to None. prop (str, optional): Comma separated string of interchanges. Defaults to None. start_date_range (str, optional): Defines a start date at which to represent data from. Defaults to None. end_date_range (str, optional): Defines a end date at which to represent data to. Defaults to None. Returns: dict: dictionary containing the created plot and its data table """ #TODO: Use auto unit converter in method duration_curve=False if 'duration_curve' in figure_name: duration_curve = True # List of properties needed by the plot, properties are a set of tuples and contain 3 parts: # required True/False, property name and scenarios required, scenarios must be a list. properties = [(True,"interface_Flow",self.Scenarios), (True,"interface_Import_Limit",self.Scenarios), (True,"interface_Export_Limit",self.Scenarios)] # Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary # with all required properties, returns a 1 if required data is missing check_input_data = self.get_formatted_data(properties) if 1 in check_input_data: return MissingInputData() scenario = self.Scenarios[0] outputs = {} for zone_input in self.Zones: self.logger.info("For all interfaces touching Zone = "+zone_input) Data_Table_Out = pd.DataFrame() # gets correct metadata based on area aggregation if self.AGG_BY=='zone': zone_lines = self.meta.zone_lines(scenario) else: zone_lines = self.meta.region_lines(scenario) try: zone_lines = zone_lines.set_index([self.AGG_BY]) except: self.logger.info("Column to Aggregate by is missing") continue zone_lines = zone_lines.xs(zone_input) zone_lines = zone_lines['line_name'].unique() #Map lines to interfaces all_ints = self.meta.interface_lines(scenario) #Map lines to interfaces all_ints.index = all_ints.line ints = all_ints.loc[all_ints.index.intersection(zone_lines)] #flow = flow[flow.index.get_level_values('interface_name').isin(ints.interface)] #Limit to only interfaces touching to this zone #flow = flow.droplevel('interface_category') export_limits = self["interface_Export_Limit"].get(scenario).droplevel('timestamp') export_limits.mask(export_limits[0]==0.0,other=0.01,inplace=True) #if limit is zero set to small value export_limits = export_limits[export_limits.index.get_level_values('interface_name').isin(ints.interface)] export_limits = export_limits[export_limits[0].abs() < 99998] #Filter out unenforced interfaces. #Drop unnecessary columns. export_limits.reset_index(inplace = True) export_limits.drop(columns = 'interface_category',inplace = True) export_limits.set_index('interface_name',inplace = True) import_limits = self["interface_Import_Limit"].get(scenario).droplevel('timestamp') import_limits.mask(import_limits[0]==0.0,other=0.01,inplace=True) #if limit is zero set to small value import_limits = import_limits[import_limits.index.get_level_values('interface_name').isin(ints.interface)] import_limits = import_limits[import_limits[0].abs() < 99998] #Filter out unenforced interfaces. reported_ints = import_limits.index.get_level_values('interface_name').unique() #Drop unnecessary columns. import_limits.reset_index(inplace = True) import_limits.drop(columns = 'interface_category',inplace = True) import_limits.set_index('interface_name',inplace = True) #Extract time index ti = self["interface_Flow"][self.Scenarios[0]].index.get_level_values('timestamp').unique() if prop != '': interf_list = prop.split(',') self.logger.info('Plotting only interfaces specified in Marmot_plot_select.csv') self.logger.info(interf_list) else: interf_list = reported_ints.copy() self.logger.info('Carving out season from ' + start_date_range + ' to ' + end_date_range) #Remove missing interfaces from the list. for interf in interf_list: #Remove leading spaces if interf[0] == ' ': interf = interf[1:] if interf not in reported_ints: self.logger.warning(interf + ' not found in results.') interf_list.remove(interf) if not interf_list: outputs = MissingInputData() return outputs xdim = 2 ydim = len(interf_list) mplt = PlotLibrary(ydim, xdim, squeeze=False) fig, axs = mplt.get_figure() grid_size = xdim * ydim excess_axs = grid_size - len(interf_list) plt.subplots_adjust(wspace=0.05, hspace=0.2) missing_ints = 0 chunks = [] limits_chunks = [] n = -1 for interf in interf_list: n += 1 #Remove leading spaces if interf[0] == ' ': interf = interf[1:] chunks_interf = [] single_exp_lim = export_limits.loc[interf] / 1000 single_imp_lim = import_limits.loc[interf] / 1000 #Check if all hours have the same limit. check = single_exp_lim.to_numpy() identical = check[0] == check.all() limits = pd.concat([single_exp_lim,single_imp_lim],axis = 1) limits.columns = ['export limit','import limit'] limits.index = ti for scenario in self.Scenarios: flow = self["interface_Flow"].get(scenario) single_int = flow.xs(interf,level = 'interface_name') / 1000 single_int.index = single_int.index.droplevel('interface_category') single_int.columns = [interf] if self.shift_leapday == True: single_int = self.adjust_for_leapday(single_int) summer = single_int[start_date_range:end_date_range] winter = single_int.drop(summer.index) summer_lim = limits[start_date_range:end_date_range] winter_lim = limits.drop(summer.index) if duration_curve: summer = self.sort_duration(summer,interf) winter = self.sort_duration(winter,interf) summer_lim = self.sort_duration(summer_lim,'export limit') winter_lim = self.sort_duration(winter_lim,'export limit') axs[n,0].plot(summer[interf],linewidth = 1,label = scenario + '\n interface flow') axs[n,1].plot(winter[interf],linewidth = 1,label = scenario + '\n interface flow') if scenario == self.Scenarios[-1]: for col in summer_lim: limits_color_dict = {'export limit': 'red', 'import limit': 'green'} axs[n,0].plot(summer_lim[col], linewidth=1, linestyle='--', color=limits_color_dict[col], label=col) axs[n,1].plot(winter_lim[col], linewidth=1, linestyle='--', color=limits_color_dict[col], label=col) #For output time series .csv scenario_names = pd.Series([scenario] * len(single_int), name='Scenario') single_int_out = single_int.set_index([scenario_names], append=True) chunks_interf.append(single_int_out) Data_out_line = pd.concat(chunks_interf,axis = 0) Data_out_line.columns = [interf] chunks.append(Data_out_line) axs[n,0].set_title(interf) axs[n,1].set_title(interf) if not duration_curve: locator = mdates.AutoDateLocator(minticks=4, maxticks=8) formatter = mdates.ConciseDateFormatter(locator) formatter.formats[2] = '%d\n %b' formatter.zero_formats[1] = '%b\n %Y' formatter.zero_formats[2] = '%d\n %b' formatter.zero_formats[3] = '%H:%M\n %d-%b' formatter.offset_formats[3] = '%b %Y' formatter.show_offset = False axs[n,0].xaxis.set_major_locator(locator) axs[n,0].xaxis.set_major_formatter(formatter) axs[n,1].xaxis.set_major_locator(locator) axs[n,1].xaxis.set_major_formatter(formatter) mplt.add_legend() Data_Table_Out = pd.concat(chunks,axis = 1) #Limits_Out = pd.concat(limits_chunks,axis = 1) #Limits_Out.index = ['Export Limit','Import Limit'] plt.ylabel('Flow (GW)', color='black', rotation='vertical', labelpad=30) if duration_curve: plt.xlabel('Sorted hour of the year', color = 'black', labelpad = 30) fig.text(0.15,0.98,'Summer (' + start_date_range + ' to ' + end_date_range + ')',fontsize = 16) fig.text(0.58,0.98,'Winter',fontsize = 16) plt.tight_layout(rect=[0, 0.03, 1, 0.97]) if mconfig.parser("plot_title_as_region"): mplt.add_main_title(zone_input) outputs[zone_input] = {'fig': fig, 'data_table': Data_Table_Out} #Limits_Out.to_csv(os.path.join(self.Marmot_Solutions_folder, 'Figures_Output',self.AGG_BY + '_transmission','Individual_Interface_Limits.csv')) return outputs #TODO: re-organize parameters (self vs. not self) def int_flow_ind_diff(self, figure_name: str = None, **_): """Plot under development This method plots the hourly difference in interface flow between two scenarios for individual interfaces, with a facet for each interface. The two scenarios are defined in the "Scenario_Diff" row of Marmot_user_defined_inputs. The interfaces are specified in the plot properties field of Marmot_plot_select.csv (column 4). The figure and data tables are saved within the module. Returns: UnderDevelopment(): Exception class, plot is not functional. """ return UnderDevelopment() # TODO: add new get_data method duration_curve=False if 'duration_curve' in figure_name: duration_curve = True check_input_data = [] Flow_Collection = {} Import_Limit_Collection = {} Export_Limit_Collection = {} check_input_data.extend([get_data(Flow_Collection,"interface_Flow",self.Marmot_Solutions_folder, self.Scenarios)]) check_input_data.extend([get_data(Import_Limit_Collection,"interface_Import_Limit",self.Marmot_Solutions_folder, self.Scenarios)]) check_input_data.extend([get_data(Export_Limit_Collection,"interface_Export_Limit",self.Marmot_Solutions_folder, self.Scenarios)]) if 1 in check_input_data: outputs = MissingInputData() return outputs scenario = self.Scenarios[0] outputs = {} if not pd.isnull(self.start_date): self.logger.info("Plotting specific date range: \ {} to {}".format(str(self.start_date),str(self.end_date))) for zone_input in self.Zones: self.logger.info("For all interfaces touching Zone = "+zone_input) Data_Table_Out = pd.DataFrame() # gets correct metadata based on area aggregation if self.AGG_BY=='zone': zone_lines = self.meta.zone_lines(scenario) else: zone_lines = self.meta.region_lines(scenario) try: zone_lines = zone_lines.set_index([self.AGG_BY]) except: self.logger.info("Column to Aggregate by is missing") continue zone_lines = zone_lines.xs(zone_input) zone_lines = zone_lines['line_name'].unique() #Map lines to interfaces all_ints = self.meta.interface_lines(scenario) #Map lines to interfaces all_ints.index = all_ints.line ints = all_ints.loc[all_ints.index.intersection(zone_lines)] #flow = flow[flow.index.get_level_values('interface_name').isin(ints.interface)] #Limit to only interfaces touching to this zone #flow = flow.droplevel('interface_category') export_limits = Export_Limit_Collection.get(scenario).droplevel('timestamp') export_limits.mask(export_limits[0]==0.0,other=0.01,inplace=True) #if limit is zero set to small value export_limits = export_limits[export_limits.index.get_level_values('interface_name').isin(ints.interface)] export_limits = export_limits[export_limits[0].abs() < 99998] #Filter out unenforced interfaces. #Drop unnecessary columns. export_limits.reset_index(inplace = True) export_limits.drop(columns = 'interface_category',inplace = True) export_limits.set_index('interface_name',inplace = True) import_limits = Import_Limit_Collection.get(scenario).droplevel('timestamp') import_limits.mask(import_limits[0]==0.0,other=0.01,inplace=True) #if limit is zero set to small value import_limits = import_limits[import_limits.index.get_level_values('interface_name').isin(ints.interface)] import_limits = import_limits[import_limits[0].abs() < 99998] #Filter out unenforced interfaces. reported_ints = import_limits.index.get_level_values('interface_name').unique() #Drop unnecessary columns. import_limits.reset_index(inplace = True) import_limits.drop(columns = 'interface_category',inplace = True) import_limits.set_index('interface_name',inplace = True) #Extract time index ti = Flow_Collection[self.Scenarios[0]].index.get_level_values('timestamp').unique() if self.prop != '': interf_list = self.prop.split(',') self.logger.info('Plotting only interfaces specified in Marmot_plot_select.csv') self.logger.info(interf_list) else: interf_list = reported_ints.copy() self.logger.info('Plotting full time series results.') xdim,ydim = self.set_x_y_dimension(len(interf_list)) mplt = PlotLibrary(nrows, ncols, squeeze=False, ravel_axs=True) fig, axs = mplt.get_figure() grid_size = xdim * ydim excess_axs = grid_size - len(interf_list) plt.subplots_adjust(wspace=0.05, hspace=0.2) missing_ints = 0 chunks = [] limits_chunks = [] n = -1 for interf in interf_list: n += 1 #Remove leading spaces if interf[0] == ' ': interf = interf[1:] if interf in reported_ints: chunks_interf = [] single_exp_lim = export_limits.loc[interf] / 1000 #TODO: Use auto unit converter in method single_imp_lim = import_limits.loc[interf] / 1000 #Check if all hours have the same limit. check = single_exp_lim.to_numpy() identical = check[0] == check.all() limits = pd.concat([single_exp_lim,single_imp_lim],axis = 1) limits.columns = ['export limit','import limit'] limits.index = ti for scenario in self.Scenarios: flow = Flow_Collection.get(scenario) single_int = flow.xs(interf,level = 'interface_name') / 1000 single_int.index = single_int.index.droplevel('interface_category') single_int.columns = [interf] if self.shift_leapday == True: single_int = self.adjust_for_leapday(single_int) single_int = single_int.reset_index().set_index('timestamp') limits = limits.reset_index().set_index('timestamp') if not pd.isnull(self.start_date): single_int = single_int[self.start_date : self.end_date] limits = limits[self.start_date : self.end_date] if duration_curve: single_int = self.sort_duration(single_int,interf) mplt.lineplot(single_int,interf,label = scenario + '\n interface flow', sub_pos = n) #Only print limits if it doesn't change monthly or if you are plotting a time series. Otherwise the limit lines could be misleading. if not duration_curve or identical[0]: if scenario == self.Scenarios[-1]: #Only plot limits for last scenario. limits_color_dict = {'export limit': 'red', 'import limit': 'green'} mplt.lineplot(limits,'export limit',label = 'export limit',color = limits_color_dict,linestyle = '--', sub_pos = n) mplt.lineplot(limits,'import limit',label = 'import limit',color = limits_color_dict,linestyle = '--', sub_pos = n) #For output time series .csv scenario_names = pd.Series([scenario] * len(single_int),name = 'Scenario') single_int_out = single_int.set_index([scenario_names],append = True) chunks_interf.append(single_int_out) Data_out_line = pd.concat(chunks_interf,axis = 0) Data_out_line.columns = [interf] chunks.append(Data_out_line) else: self.logger.warning(interf + ' not found in results. Have you tagged it with the "Must Report" property in PLEXOS?') excess_axs += 1 missing_ints += 1 continue axs[n].set_title(interf) handles, labels = axs[n].get_legend_handles_labels() if not duration_curve: self.set_subplot_timeseries_format(axs, sub_pos=n) if n == len(interf_list) - 1: axs[n].legend(loc='lower left',bbox_to_anchor=(1.05,-0.2)) if missing_ints == len(interf_list): outputs = MissingInputData() return outputs Data_Table_Out = pd.concat(chunks,axis = 1) Data_Table_Out = Data_Table_Out.reset_index() index_name = 'level_0' if duration_curve else 'timestamp' Data_Table_Out = Data_Table_Out.pivot(index = index_name,columns = 'Scenario') #Limits_Out = pd.concat(limits_chunks,axis = 1) #Limits_Out.index = ['Export Limit','Import Limit'] # Data_Table_Out = Data_Table_Out.reset_index() # Data_Table_Out = Data_Table_Out.groupby(Data_Table_Out.index // 24).mean() # Data_Table_Out.index = pd.date_range(start = '1/1/2024',end = '12/31/2024',freq = 'D') plt.ylabel('Flow (GW)', color='black', rotation='vertical', labelpad=30) if duration_curve: plt.xlabel('Sorted hour of the year', color = 'black', labelpad = 30) plt.tight_layout(rect=[0, 0.03, 1, 0.97]) if mconfig.parser("plot_title_as_region"): mplt.add_main_title(zone_input) outputs[zone_input] = {'fig': fig, 'data_table': Data_Table_Out} #Limits_Out.to_csv(os.path.join(self.Marmot_Solutions_folder, 'Figures_Output',self.AGG_BY + '_transmission','Individual_Interface_Limits.csv')) return outputs def line_flow_ind(self, figure_name: str = None, prop: str = None, **_): """ #TODO: Finish Docstring This method plots flow, import and export limit, for individual transmission lines, with a facet for each line. The lines are specified in the plot properties field of Marmot_plot_select.csv (column 4). The plot includes every interchange that originates or ends in the aggregation zone. Figures and data tables are returned to plot_main Args: figure_name (str, optional): [description]. Defaults to None. prop (str, optional): [description]. Defaults to None. Returns: [type]: [description] """ #TODO: Use auto unit converter in method duration_curve=False if 'duration_curve' in figure_name: duration_curve = True # List of properties needed by the plot, properties are a set of tuples and contain 3 parts: # required True/False, property name and scenarios required, scenarios must be a list. properties = [(True,"line_Flow",self.Scenarios), (True,"line_Import_Limit",self.Scenarios), (True,"line_Export_Limit",self.Scenarios)] # Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary # with all required properties, returns a 1 if required data is missing check_input_data = self.get_formatted_data(properties) if 1 in check_input_data: return MissingInputData() #Select only lines specified in Marmot_plot_select.csv. select_lines = prop.split(",") if select_lines == None: return InputSheetError() self.logger.info('Plotting only lines specified in Marmot_plot_select.csv') self.logger.info(select_lines) scenario = self.Scenarios[0] #Select single scenario for purpose of extracting limits. export_limits = self["line_Export_Limit"].get(scenario).droplevel('timestamp') export_limits.mask(export_limits[0]==0.0,other=0.01,inplace=True) #if limit is zero set to small value export_limits = export_limits[export_limits[0].abs() < 99998] #Filter out unenforced lines. import_limits = self["line_Import_Limit"].get(scenario).droplevel('timestamp') import_limits.mask(import_limits[0]==0.0,other=0.01,inplace=True) #if limit is zero set to small value import_limits = import_limits[import_limits[0].abs() < 99998] #Filter out unenforced lines. flows = self["line_Flow"][scenario] # limited_lines = [] # i = 0 # all_lines = flows.index.get_level_values('line_name').unique() # for line in all_lines: # i += 1 # print(line) # print(i / len(all_lines)) # exp = export_limits.loc[line].squeeze()[0] # imp = import_limits.loc[line].squeeze()[0] # flow = flows.xs(line,level = 'line_name')[0].tolist() # if exp in flow or imp in flow: # limited_lines.append(line) # print(limited_lines) # pd.DataFrame(limited_lines).to_csv('/Users/mschwarz/OR OSW local/Solutions/Figures_Output/limited_lines.csv') xdim,ydim = self.set_x_y_dimension(len(select_lines)) grid_size = xdim * ydim excess_axs = grid_size - len(select_lines) mplt = PlotLibrary(ydim, xdim, squeeze=False, ravel_axs=True) fig, axs = mplt.get_figure() reported_lines = self["line_Flow"][self.Scenarios[0]].index.get_level_values('line_name').unique() n = -1 missing_lines = 0 chunks = [] limits_chunks = [] for line in select_lines: n += 1 #Remove leading spaces if line[0] == ' ': line = line[1:] if line in reported_lines: chunks_line = [] single_exp_lim = export_limits.loc[line] single_imp_lim = import_limits.loc[line] limits = pd.concat([single_exp_lim,single_imp_lim]) limits_chunks.append(limits) single_exp_lim = single_exp_lim.squeeze() single_imp_lim = single_imp_lim.squeeze() # If export/import limits were pulled as an interval property, take the average. if len(single_exp_lim) > 1: single_exp_lim = single_exp_lim.mean() single_imp_lim = single_imp_lim.mean() limits = pd.Series([single_exp_lim,single_imp_lim],name = line) limits_chunks.append(limits) for scenario in self.Scenarios: flow = self["line_Flow"][scenario] single_line = flow.xs(line,level = 'line_name') single_line = single_line.droplevel('units') single_line.columns = [line] if self.shift_leapday == True: single_line = self.adjust_for_leapday(single_line) single_line_out = single_line.copy() if duration_curve: single_line = self.sort_duration(single_line,line) mplt.lineplot(single_line, line, label = scenario + '\n line flow', sub_pos=n) #Add %congested number to plot. if scenario == self.Scenarios[0]: viol_exp = single_line[single_line[line] > single_exp_lim].count() viol_imp = single_line[single_line[line] < single_imp_lim].count() viol_perc = 100 * (viol_exp + viol_imp) / len(single_line) viol_perc = round(viol_perc.squeeze(),3) axs[n].annotate('Violation = ' + str(viol_perc) + '% of hours', xy = (0.1,0.15),xycoords='axes fraction') cong_exp = single_line[single_line[line] == single_exp_lim].count() cong_imp = single_line[single_line[line] == single_imp_lim].count() cong_perc = 100 * (cong_exp + cong_imp) / len(single_line) cong_perc = round(cong_perc.squeeze(),0) axs[n].annotate('Congestion = ' + str(cong_perc) + '% of hours', xy = (0.1,0.1),xycoords='axes fraction') #For output time series .csv scenario_names = pd.Series([scenario] * len(single_line_out),name = 'Scenario') single_line_out = single_line_out.set_index([scenario_names],append = True) chunks_line.append(single_line_out) Data_out_line = pd.concat(chunks_line,axis = 0) chunks.append(Data_out_line) else: self.logger.warning(line + ' not found in results. Have you tagged it with the "Must Report" property in PLEXOS?') excess_axs += 1 missing_lines += 1 continue mplt.remove_excess_axs(excess_axs,grid_size) axs[n].axhline(y = single_exp_lim, ls = '--',label = 'Export Limit',color = 'red') axs[n].axhline(y = single_imp_lim, ls = '--',label = 'Import Limit', color = 'green') axs[n].set_title(line) if not duration_curve: mplt.set_subplot_timeseries_format(sub_pos=n) if missing_lines == len(select_lines): outputs = MissingInputData() return outputs Data_Table_Out = pd.concat(chunks,axis = 1) #Limits_Out = pd.concat(limits_chunks,axis = 1) #Limits_Out.index = ['Export Limit','Import Limit'] mplt.add_legend() plt.ylabel('Flow (MW)', color='black', rotation='vertical', labelpad=30) #plt.tight_layout(rect=[0, 0.03, 1, 0.97]) plt.tight_layout() fn_suffix = '_duration_curve' if duration_curve else '' fig.savefig(os.path.join(self.Marmot_Solutions_folder, 'Figures_Output',self.AGG_BY + '_transmission',figure_name + fn_suffix + '.svg'), dpi=600, bbox_inches='tight') Data_Table_Out.to_csv(os.path.join(self.Marmot_Solutions_folder, 'Figures_Output',self.AGG_BY + '_transmission',figure_name + fn_suffix + '.csv')) # Limits_Out.to_csv(os.path.join(self.Marmot_Solutions_folder, 'Figures_Output',self.AGG_BY + '_transmission',figure_name + 'limits.csv')) outputs = DataSavedInModule() return outputs def line_flow_ind_diff(self, figure_name: str = None, prop: str = None, **_): """ #TODO: Finish Docstring This method plots the flow difference for individual transmission lines, with a facet for each line. The scenarios are specified in the "Scenario_Diff_plot" field of Marmot_user_defined_inputs.csv. The lines are specified in the plot properties field of Marmot_plot_select.csv (column 4). Figures and data tables are saved in the module. Args: figure_name (str, optional): [description]. Defaults to None. prop (str, optional): [description]. Defaults to None. Returns: [type]: [description] """ #TODO: Use auto unit converter in method duration_curve=False if 'duration_curve' in figure_name: duration_curve = True # List of properties needed by the plot, properties are a set of tuples and contain 3 parts: # required True/False, property name and scenarios required, scenarios must be a list. properties = [(True,"line_Flow",self.Scenarios)] # Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary # with all required properties, returns a 1 if required data is missing check_input_data = self.get_formatted_data(properties) if 1 in check_input_data: outputs = MissingInputData() return outputs #Select only lines specified in Marmot_plot_select.csv. select_lines = prop.split(",") if select_lines == None: outputs = InputSheetError() return outputs self.logger.info('Plotting only lines specified in Marmot_plot_select.csv') self.logger.info(select_lines) flow_diff = self["line_Flow"].get(self.Scenario_Diff[1]) - self["line_Flow"].get(self.Scenario_Diff[0]) xdim,ydim = self.set_x_y_dimension(len(select_lines)) grid_size = xdim * ydim excess_axs = grid_size - len(select_lines) mplt = PlotLibrary(ydim, xdim, squeeze=False, ravel_axs=True) fig, axs = mplt.get_figure() plt.subplots_adjust(wspace=0.05, hspace=0.2) reported_lines = self["line_Flow"].get(self.Scenarios[0]).index.get_level_values('line_name').unique() n = -1 missing_lines = 0 chunks = [] for line in select_lines: n += 1 #Remove leading spaces if line[0] == ' ': line = line[1:] if line in reported_lines: single_line = flow_diff.xs(line,level = 'line_name') single_line.columns = [line] if self.shift_leapday == True: single_line = self.adjust_for_leapday(single_line) single_line_out = single_line.copy() if duration_curve: single_line = self.sort_duration(single_line,line) #mplt.lineplot(single_line,line, label = self.Scenario_Diff[1] + ' - \n' + self.Scenario_Diff[0] + '\n line flow', sub_pos = n) mplt.lineplot(single_line,line, label = 'BESS - no BESS \n line flow', sub_pos=n) else: self.logger.warning(line + ' not found in results. Have you tagged it with the "Must Report" property in PLEXOS?') excess_axs += 1 missing_lines += 1 continue mplt.remove_excess_axs(excess_axs,grid_size) axs[n].set_title(line) if not duration_curve: mplt.set_subplot_timeseries_format(sub_pos=n) chunks.append(single_line_out) if missing_lines == len(select_lines): outputs = MissingInputData() return outputs Data_Table_Out = pd.concat(chunks,axis = 1) mplt.add_legend() plt.ylabel('Flow difference (MW)', color='black', rotation='vertical', labelpad=30) plt.tight_layout() fn_suffix = '_duration_curve' if duration_curve else '' fig.savefig(os.path.join(self.Marmot_Solutions_folder, 'Figures_Output',self.AGG_BY + '_transmission',figure_name + fn_suffix + '.svg'), dpi=600, bbox_inches='tight') Data_Table_Out.to_csv(os.path.join(self.Marmot_Solutions_folder, 'Figures_Output',self.AGG_BY + '_transmission',figure_name + fn_suffix + '.csv')) outputs = DataSavedInModule() return outputs def line_flow_ind_seasonal(self, figure_name: str = None, prop: str = None, start_date_range: str = None, end_date_range: str = None, **_): """TODO: Finish Docstring. This method differs from the previous method, in that it plots seasonal line limits. To use this method, line import/export must be an "interval" property, not a "year" property. This can be selected in "plexos_properties.csv". Re-run the formatter if necessary, it will overwrite the existing properties in "*_formatted.h5" This method plots flow, import and export limit, for individual transmission lines, with a facet for each line. The lines are specified in the plot properties field of Marmot_plot_select.csv (column 4). The plot includes every interchange that originates or ends in the aggregation zone. Figures and data tables saved in the module. Args: figure_name (str, optional): [description]. Defaults to None. prop (str, optional): [description]. Defaults to None. start_date_range (str, optional): [description]. Defaults to None. end_date_range (str, optional): [description]. Defaults to None. Returns: [type]: [description] """ #TODO: Use auto unit converter in method if pd.isna(start_date_range): self.logger.warning('You are attempting to plot a time series facetted by two seasons,\n\ but you are missing a value in the "Start Date" column of "Marmot_plot_select.csv" \ Please enter dates in "Start Date" and "End Date". These will define the bounds of \ one of your two seasons. The other season will be comprised of the rest of the year.') return MissingInputData() duration_curve=False if 'duration_curve' in figure_name: duration_curve = True # List of properties needed by the plot, properties are a set of tuples and contain 3 parts: # required True/False, property name and scenarios required, scenarios must be a list. properties = [(True,"line_Flow",self.Scenarios), (True,"line_Import_Limit",self.Scenarios), (True,"line_Export_Limit",self.Scenarios)] # Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary # with all required properties, returns a 1 if required data is missing check_input_data = self.get_formatted_data(properties) if 1 in check_input_data: return MissingInputData() #Select only lines specified in Marmot_plot_select.csv. select_lines = prop.split(",") if select_lines == None: return InputSheetError() self.logger.info('Plotting only lines specified in Marmot_plot_select.csv') self.logger.info(select_lines) scenario = self.Scenarios[0] #Line limits are seasonal. export_limits = self["line_Export_Limit"].get(scenario).droplevel('timestamp') export_limits.mask(export_limits[0]==0.0,other=0.01,inplace=True) #if limit is zero set to small value export_limits = export_limits[export_limits[0].abs() < 99998] #Filter out unenforced lines. import_limits = self["line_Import_Limit"].get(scenario).droplevel('timestamp') import_limits.mask(import_limits[0]==0.0,other=0.01,inplace=True) #if limit is zero set to small value import_limits = import_limits[import_limits[0].abs() < 99998] #Filter out unenforced lines. #Extract time index ti = self["line_Flow"][self.Scenarios[0]].index.get_level_values('timestamp').unique() reported_lines = self["line_Flow"][self.Scenarios[0]].index.get_level_values('line_name').unique() self.logger.info('Carving out season from ' + start_date_range + ' to ' + end_date_range) #Remove missing interfaces from the list. for line in select_lines: #Remove leading spaces if line[0] == ' ': line = line[1:] if line not in reported_lines: self.logger.warning(line + ' not found in results.') select_lines.remove(line) if not select_lines: outputs = MissingInputData() return outputs xdim = 2 ydim = len(select_lines) grid_size = xdim * ydim excess_axs = grid_size - len(select_lines) mplt = PlotLibrary(ydim, xdim, squeeze=False) fig, axs = mplt.get_figure() i = -1 missing_lines = 0 chunks = [] limits_chunks = [] for line in select_lines: i += 1 #Remove leading spaces if line[0] == ' ': line = line[1:] chunks_line = [] single_exp_lim = export_limits.loc[line] single_exp_lim.index = ti single_imp_lim = import_limits.loc[line] single_imp_lim.index = ti limits = pd.concat([single_exp_lim,single_imp_lim],axis = 1) limits.columns = ['export limit','import limit'] limits.index = ti limits_chunks.append(limits) for scenario in self.Scenarios: flow = self["line_Flow"][scenario] single_line = flow.xs(line,level = 'line_name') single_line = single_line.droplevel('units') single_line_out = single_line.copy() single_line.columns = [line] if self.shift_leapday == True: single_line = self.adjust_for_leapday(single_line) #Split into seasons. summer = single_line[start_date_range : end_date_range] winter = single_line.drop(summer.index) summer_lim = limits[start_date_range:end_date_range] winter_lim = limits.drop(summer.index) if duration_curve: summer = self.sort_duration(summer,line) winter = self.sort_duration(winter,line) summer_lim = self.sort_duration(summer_lim,'export limit') winter_lim = self.sort_duration(winter_lim,'export limit') axs[i,0].plot(summer[line],linewidth = 1,label = scenario + '\n line flow') axs[i,1].plot(winter[line],linewidth = 1,label = scenario + '\n line flow') if scenario == self.Scenarios[-1]: for col in summer_lim: limits_color_dict = {'export limit': 'red', 'import limit': 'green'} axs[i,0].plot(summer_lim[col],linewidth = 1,linestyle = '--',color = limits_color_dict[col],label = col) axs[i,1].plot(winter_lim[col],linewidth = 1,linestyle = '--',color = limits_color_dict[col],label = col) for j in [0,1]: axs[i,j].spines['right'].set_visible(False) axs[i,j].spines['top'].set_visible(False) axs[i,j].tick_params(axis='y', which='major', length=5, width=1) axs[i,j].tick_params(axis='x', which='major', length=5, width=1) axs[i,j].set_title(line) if i == len(select_lines) - 1: axs[i,j].legend(loc = 'lower left',bbox_to_anchor=(1.05,0),facecolor='inherit', frameon=True) #For output time series .csv scenario_names = pd.Series([scenario] * len(single_line_out),name = 'Scenario') single_line_out.columns = [line] single_line_out = single_line_out.set_index([scenario_names],append = True) chunks_line.append(single_line_out) Data_out_line = pd.concat(chunks_line,axis = 0) chunks.append(Data_out_line) if missing_lines == len(select_lines): outputs = MissingInputData() return outputs Data_Table_Out = pd.concat(chunks,axis = 1) #Limits_Out = pd.concat(limits_chunks,axis = 1) #Limits_Out.index = ['Export Limit','Import Limit'] fig.text(0.3,1,'Summer (Jun - Sep)') fig.text(0.6,1,'Winter (Jan - Mar,Oct - Dec)') plt.ylabel('Flow (MW)', color='black', rotation='vertical', labelpad=30) plt.tight_layout() fn_suffix = '_duration_curve' if duration_curve else '' fig.savefig(os.path.join(self.Marmot_Solutions_folder, 'Figures_Output',self.AGG_BY + '_transmission','Individual_Line_Flow' + fn_suffix + '_seasonal.svg'), dpi=600, bbox_inches='tight') Data_Table_Out.to_csv(os.path.join(self.Marmot_Solutions_folder, 'Figures_Output',self.AGG_BY + '_transmission','Individual_Line_Flow' + fn_suffix + '_seasonal.csv')) #Limits_Out.to_csv(os.path.join(self.Marmot_Solutions_folder, 'Figures_Output',self.AGG_BY + '_transmission','Individual_Line_Limits.csv')) outputs = DataSavedInModule() return outputs def extract_tx_cap(self, **_): """Plot under development Returns: UnderDevelopment(): Exception class, plot is not functional. """ return UnderDevelopment() #TODO: Needs finishing # List of properties needed by the plot, properties are a set of tuples and contain 3 parts: # required True/False, property name and scenarios required, scenarios must be a list. properties = [(True,"interface_Import_Limit",self.Scenarios), (True,"interface_Export_Limit",self.Scenarios), (True,"line_Import_Limit",self.Scenarios), (True,"line_Export_Limit",self.Scenarios)] # Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary # with all required properties, returns a 1 if required data is missing check_input_data = self.get_formatted_data(properties) if 1 in check_input_data: return MissingInputData() for scenario in self.Scenarios: self.logger.info(scenario) for zone_input in self.Zones: #Lines # lines = self.meta.region_interregionallines(scenario) # if scenario == 'ADS': # zone_input = zone_input.split('_WI')[0] # lines = self.meta_ADS.region_interregionallines() # lines = lines[lines['region'] == zone_input] # import_lim = self["line_Import_Limit"][scenario].reset_index() # export_lim = self["line_Export_Limit"][scenario].reset_index() # lines = lines.merge(import_lim,how = 'inner',on = 'line_name') # lines = lines[['line_name',0]] # lines.columns = ['line_name','import_limit'] # lines = lines.merge(export_lim, how = 'inner',on = 'line_name') # lines = lines[['line_name','import_limit',0]] # lines.columns = ['line_name','import_limit','export_limit'] # fn = os.path.join(self.Marmot_Solutions_folder, 'NARIS', 'Figures_Output',self.AGG_BY + '_transmission','Individual_Interregional_Line_Limits_' + scenario + '.csv') # lines.to_csv(fn) # lines = self.meta.region_intraregionallines(scenario) # if scenario == 'ADS': # lines = self.meta_ADS.region_intraregionallines() # lines = lines[lines['region'] == zone_input] # import_lim = self["line_Import_Limit"][scenario].reset_index() # export_lim = self["line_Export_Limit"][scenario].reset_index() # lines = lines.merge(import_lim,how = 'inner',on = 'line_name') # lines = lines[['line_name',0]] # lines.columns = ['line_name','import_limit'] # lines = lines.merge(export_lim, how = 'inner',on = 'line_name') # lines = lines[['line_name','import_limit',0]] # lines.columns = ['line_name','import_limit','export_limit'] # fn = os.path.join(self.Marmot_Solutions_folder, 'NARIS', 'Figures_Output',self.AGG_BY + '_transmission','Individual_Intraregional_Line_Limits_' + scenario + '.csv') # lines.to_csv(fn) #Interfaces PSCo_ints = ['P39 TOT 5_WI','P40 TOT 7_WI'] int_import_lim = self["interface_Import_Limit"][scenario].reset_index() int_export_lim = self["interface_Export_Limit"][scenario].reset_index() if scenario == 'NARIS': last_timestamp = int_import_lim['timestamp'].unique()[-1] #Last because ADS uses the last timestamp. int_import_lim = int_import_lim[int_import_lim['timestamp'] == last_timestamp] int_export_lim = int_export_lim[int_export_lim['timestamp'] == last_timestamp] lines2ints = self.meta_ADS.interface_lines() else: lines2ints = self.meta.interface_lines(scenario) fn = os.path.join(self.Marmot_Solutions_folder, 'NARIS', 'Figures_Output',self.AGG_BY + '_transmission','test_meta_' + scenario + '.csv') lines2ints.to_csv(fn) ints = pd.merge(int_import_lim,int_export_lim,how = 'inner', on = 'interface_name') ints.rename(columns = {'0_x':'import_limit','0_y': 'export_limit'},inplace = True) all_lines_in_ints = lines2ints['line'].unique() test = [line for line in lines['line_name'].unique() if line in all_lines_in_ints] ints = ints.merge(lines2ints, how = 'inner', left_on = 'interface_name',right_on = 'interface') def region_region_interchange_all_scenarios(self, **kwargs): """ #TODO: Finish Docstring This method creates a timeseries line plot of interchange flows between the selected region to each connecting region. If there are more than 4 total interchanges, all other interchanges are aggregated into an 'other' grouping Each scenarios is plotted on a separate Facet plot. Figures and data tables are returned to plot_main """ outputs = self._region_region_interchange(self.Scenarios, **kwargs) return outputs def region_region_interchange_all_regions(self, **kwargs): """ #TODO: Finish Docstring This method creates a timeseries line plot of interchange flows between the selected region to each connecting region. All regions are plotted on a single figure with each focus region placed on a separate facet plot If there are more than 4 total interchanges, all other interchanges are aggregated into an 'other' grouping This figure only plots a single scenario that is defined by Main_scenario_plot in user_defined_inputs.csv. Figures and data tables are saved within method """ outputs = self._region_region_interchange([self.Scenarios[0]],plot_scenario=False, **kwargs) return outputs def _region_region_interchange(self, scenario_type: str, plot_scenario: bool = True, timezone: str = "", **_): """#TODO: Finish Docstring Args: scenario_type (str): [description] plot_scenario (bool, optional): [description]. Defaults to True. timezone (str, optional): [description]. Defaults to "". Returns: [type]: [description] """ outputs = {} if self.AGG_BY == 'zone': agg = 'zone' else: agg = 'region' # List of properties needed by the plot, properties are a set of tuples and contain 3 parts: # required True/False, property name and scenarios required, scenarios must be a list. properties = [(True,f"{agg}_{agg}s_Net_Interchange",scenario_type)] # Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary # with all required properties, returns a 1 if required data is missing check_input_data = self.get_formatted_data(properties) if 1 in check_input_data: return MissingInputData() for zone_input in self.Zones: self.logger.info(f"Zone = {zone_input}") ncols, nrows = self.set_facet_col_row_dimensions(multi_scenario=scenario_type) mplt = PlotLibrary(nrows, ncols, sharey=True, squeeze=False, ravel_axs=True) fig, axs = mplt.get_figure() plt.subplots_adjust(wspace=0.6, hspace=0.3) data_table_chunks=[] n=0 for scenario in scenario_type: rr_int = self[f"{agg}_{agg}s_Net_Interchange"].get(scenario) if self.shift_leapday == True: rr_int = self.adjust_for_leapday(rr_int) # For plot_main handeling - need to find better solution if plot_scenario == False: outputs={} for zone_input in self.Zones: outputs[zone_input] = pd.DataFrame() if self.AGG_BY != 'region' and self.AGG_BY != 'zone': agg_region_mapping = self.Region_Mapping[['region',self.AGG_BY]].set_index('region').to_dict()[self.AGG_BY] # Checks if keys all aggregate to a single value, this plot requires multiple values to work if len(set(agg_region_mapping.values())) == 1: return UnsupportedAggregation() rr_int = rr_int.reset_index() rr_int['parent'] = rr_int['parent'].map(agg_region_mapping) rr_int['child'] = rr_int['child'].map(agg_region_mapping) rr_int_agg = rr_int.groupby(['timestamp','parent','child'],as_index=True).sum() rr_int_agg.rename(columns = {0:'flow (MW)'}, inplace = True) rr_int_agg = rr_int_agg.reset_index() # If plotting all regions update plot setup if plot_scenario == False: #Make a facet plot, one panel for each parent zone. parent_region = rr_int_agg['parent'].unique() plot_number = len(parent_region) ncols, nrows = self.set_x_y_dimension(plot_number) mplt = PlotLibrary(nrows, ncols, squeeze=False, ravel_axs=True) fig, axs = mplt.get_figure() plt.subplots_adjust(wspace=0.6, hspace=0.7) else: parent_region = [zone_input] plot_number = len(scenario_type) grid_size = ncols*nrows excess_axs = grid_size - plot_number for parent in parent_region: single_parent = rr_int_agg[rr_int_agg['parent'] == parent] single_parent = single_parent.pivot(index = 'timestamp',columns = 'child',values = 'flow (MW)') single_parent = single_parent.loc[:,(single_parent != 0).any(axis = 0)] #Remove all 0 columns (uninteresting). if (parent in single_parent.columns): single_parent = single_parent.drop(columns = [parent]) #Remove columns if parent = child #Neaten up lines: if more than 4 total interchanges, aggregated all but the highest 3. if len(single_parent.columns) > 4: # Set the "three highest zonal interchanges" for all three scenarios. cols_dontagg = single_parent.max().abs().sort_values(ascending = False)[0:3].index df_dontagg = single_parent[cols_dontagg] df_toagg = single_parent.drop(columns = cols_dontagg) agged = df_toagg.sum(axis = 1) df_dontagg.insert(len(df_dontagg.columns),'Other',agged) single_parent = df_dontagg.copy() #Convert units if n == 0: unitconversion = self.capacity_energy_unitconversion(single_parent) single_parent = single_parent / unitconversion['divisor'] for column in single_parent.columns: mplt.lineplot(single_parent, column, label=column, sub_pos=n) axs[n].set_title(parent) axs[n].margins(x=0.01) mplt.set_subplot_timeseries_format(sub_pos=n) axs[n].hlines(y = 0, xmin = axs[n].get_xlim()[0], xmax = axs[n].get_xlim()[1], linestyle = ':') #Add horizontal line at 0. axs[n].legend(loc='lower left',bbox_to_anchor=(1,0)) n+=1 # Create data table for each scenario scenario_names = pd.Series([scenario]*len(single_parent),name='Scenario') data_table = single_parent.add_suffix(f" ({unitconversion['units']})") data_table = data_table.set_index([scenario_names],append=True) data_table_chunks.append(data_table) # if plotting all scenarios add facet labels if plot_scenario == True: mplt.add_facet_labels(xlabels=self.xlabels, ylabels = self.ylabels) #Remove extra axes mplt.remove_excess_axs(excess_axs, grid_size) plt.xlabel(timezone, color='black', rotation='horizontal',labelpad = 30) plt.ylabel(f"Net Interchange ({unitconversion['units']})", color='black', rotation='vertical', labelpad = 40) # If plotting all regions save output and return none plot_main if plot_scenario == False: # Location to save to Data_Table_Out = rr_int_agg save_figures = os.path.join(self.figure_folder, self.AGG_BY + '_transmission') fig.savefig(os.path.join(save_figures, "Region_Region_Interchange_{}.svg".format(self.Scenarios[0])), dpi=600, bbox_inches='tight') Data_Table_Out.to_csv(os.path.join(save_figures, "Region_Region_Interchange_{}.csv".format(self.Scenarios[0]))) outputs = DataSavedInModule() return outputs Data_Out = pd.concat(data_table_chunks, copy=False, axis=0) # if plotting all scenarios return figures to plot_main outputs[zone_input] = {'fig': fig,'data_table':Data_Out} return outputs def region_region_checkerboard(self, **_): """Creates a checkerboard/heatmap figure showing total interchanges between regions/zones. Each scenario is plotted on its own facet plot. Plots and Data are saved within the module. Returns: DataSavedInModule: DataSavedInModule exception. """ outputs = {} if self.AGG_BY == 'zone': agg = 'zone' else: agg = 'region' # List of properties needed by the plot, properties are a set of tuples and contain 3 parts: # required True/False, property name and scenarios required, scenarios must be a list. properties = [(True,f"{agg}_{agg}s_Net_Interchange",self.Scenarios)] # Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary # with all required properties, returns a 1 if required data is missing check_input_data = self.get_formatted_data(properties) if 1 in check_input_data: return MissingInputData() ncols, nrows = self.set_x_y_dimension(len(self.Scenarios)) grid_size = ncols*nrows excess_axs = grid_size - len(self.Scenarios) mplt = PlotLibrary(nrows, ncols, squeeze=False, ravel_axs=True) fig, axs = mplt.get_figure() plt.subplots_adjust(wspace=0.02, hspace=0.4) max_flow_group = [] Data_Out = [] n=0 for scenario in self.Scenarios: rr_int = self[f"{agg}_{agg}s_Net_Interchange"].get(scenario) if self.shift_leapday == True: rr_int = self.adjust_for_leapday(rr_int) if self.AGG_BY != 'region' and self.AGG_BY != 'zone': agg_region_mapping = self.Region_Mapping[['region',self.AGG_BY]].set_index('region').to_dict()[self.AGG_BY] # Checks if keys all aggregate to a single value, this plot requires multiple values to work if len(set(agg_region_mapping.values())) == 1: return UnsupportedAggregation() rr_int = rr_int.reset_index() rr_int['parent'] = rr_int['parent'].map(agg_region_mapping) rr_int['child'] = rr_int['child'].map(agg_region_mapping) rr_int_agg = rr_int.groupby(['parent','child'],as_index=True).sum() rr_int_agg.rename(columns = {0:'flow (MW)'}, inplace = True) rr_int_agg=rr_int_agg.loc[rr_int_agg['flow (MW)']>0.01] # Keep only positive flows rr_int_agg.sort_values(ascending=False,by='flow (MW)') rr_int_agg = rr_int_agg/1000 # MWh -> GWh data_out = rr_int_agg.copy() data_out.rename(columns={'flow (MW)':'{} flow (GWh)'.format(scenario)},inplace=True) max_flow = max(rr_int_agg['flow (MW)']) rr_int_agg = rr_int_agg.unstack('child') rr_int_agg = rr_int_agg.droplevel(level = 0, axis = 1) current_cmap = plt.cm.get_cmap() current_cmap.set_bad(color='grey') axs[n].imshow(rr_int_agg) axs[n].set_xticks(np.arange(rr_int_agg.shape[1])) axs[n].set_yticks(np.arange(rr_int_agg.shape[0])) axs[n].set_xticklabels(rr_int_agg.columns) axs[n].set_yticklabels(rr_int_agg.index) axs[n].set_title(scenario.replace('_',' '),fontweight='bold') # Rotate the tick labels and set their alignment. plt.setp(axs[n].get_xticklabels(), rotation=30, ha="right", rotation_mode="anchor") #Delineate the boxes and make room at top and bottom axs[n].set_xticks(np.arange(rr_int_agg.shape[1]+1)-.5, minor=True) axs[n].set_yticks(np.arange(rr_int_agg.shape[0]+1)-.5, minor=True) axs[n].grid(which="minor", color="k", linestyle='-', linewidth=1) axs[n].tick_params(which="minor", bottom=False, left=False) max_flow_group.append(max_flow) Data_Out.append(data_out) n+=1 #Remove extra axes mplt.remove_excess_axs(excess_axs,grid_size) cmap = cm.inferno norm = mcolors.Normalize(vmin=0, vmax=max(max_flow_group)) cax = plt.axes([0.90, 0.1, 0.035, 0.8]) fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), cax=cax, label='Total Net Interchange [GWh]') plt.xlabel('To Region', color='black', rotation='horizontal', labelpad=40) plt.ylabel('From Region', color='black', rotation='vertical', labelpad=40) Data_Table_Out = pd.concat(Data_Out,axis=1) save_figures = os.path.join(self.figure_folder, f"{self.AGG_BY}_transmission") fig.savefig(os.path.join(save_figures, "region_region_checkerboard.svg"), dpi=600, bbox_inches='tight') Data_Table_Out.to_csv(os.path.join(save_figures, "region_region_checkerboard.csv")) outputs = DataSavedInModule() return outputs def line_violations_timeseries(self, **kwargs): """Creates a timeseries line plot of lineflow violations for each region. The magnitude of each violation is plotted on the y-axis Each sceanrio is plotted as a separate line. This methods calls _violations() to create the figure. Returns: dict: Dictionary containing the created plot and its data table. """ outputs = self._violations(**kwargs) return outputs def line_violations_totals(self, **kwargs): """Creates a barplot of total lineflow violations for each region. Each sceanrio is plotted as a separate bar. This methods calls _violations() and passes the total_violations=True argument to create the figure. Returns: dict: Dictionary containing the created plot and its data table. """ outputs = self._violations(total_violations=True, **kwargs) return outputs def _violations(self, total_violations: bool = False, timezone: str = "", start_date_range: str = None, end_date_range: str = None, **_): """Creates line violation plots, line plot and barplots This methods is called from line_violations_timeseries() and line_violations_totals() Args: total_violations (bool, optional): If True finds the sum of violations. Used to create barplots. Defaults to False. timezone (str, optional): The timezone to display on the x-axes. Defaults to "". start_date_range (str, optional): Defines a start date at which to represent data from. Defaults to None. end_date_range (str, optional): Defines a end date at which to represent data to. Defaults to None. Returns: dict: dictionary containing the created plot and its data table """ outputs = {} # List of properties needed by the plot, properties are a set of tuples and contain 3 parts: # required True/False, property name and scenarios required, scenarios must be a list. properties = [(True,"line_Violation",self.Scenarios)] # Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary # with all required properties, returns a 1 if required data is missing check_input_data = self.get_formatted_data(properties) if 1 in check_input_data: return MissingInputData() for zone_input in self.Zones: self.logger.info(f'Zone = {zone_input}') all_scenarios = pd.DataFrame() for scenario in self.Scenarios: self.logger.info(f"Scenario = {str(scenario)}") if self.AGG_BY == 'zone': lines = self.meta.zone_lines(scenario) else: lines = self.meta.region_lines(scenario) line_v = self["line_Violation"].get(scenario) line_v = line_v.reset_index() viol = line_v.merge(lines,on = 'line_name',how = 'left') if self.AGG_BY == 'zone': viol = viol.groupby(["timestamp", "zone"]).sum() else: viol = viol.groupby(["timestamp", self.AGG_BY]).sum() one_zone = viol.xs(zone_input, level = self.AGG_BY) one_zone = one_zone.rename(columns = {0 : scenario}) one_zone = one_zone.abs() #We don't care the direction of the violation all_scenarios = pd.concat([all_scenarios,one_zone], axis = 1) all_scenarios.columns = all_scenarios.columns.str.replace('_',' ') #remove columns that are all equal to 0 all_scenarios = all_scenarios.loc[:, (all_scenarios != 0).any(axis=0)] if all_scenarios.empty: outputs[zone_input] = MissingZoneData() continue unitconversion = self.capacity_energy_unitconversion(all_scenarios) all_scenarios = all_scenarios/unitconversion['divisor'] Data_Table_Out = all_scenarios.add_suffix(f" ({unitconversion['units']})") #Make scenario/color dictionary. color_dict = dict(zip(all_scenarios.columns,self.color_list)) mplt = PlotLibrary() fig, ax = mplt.get_figure() if total_violations==True: all_scenarios_tot = all_scenarios.sum() all_scenarios_tot.plot.bar(stacked=False, rot=0, color=[color_dict.get(x, '#333333') for x in all_scenarios_tot.index], linewidth='0.1', width=0.35, ax=ax) else: for column in all_scenarios: mplt.lineplot(all_scenarios,column,color=color_dict,label=column) ax.margins(x=0.01) mplt.set_subplot_timeseries_format(minticks=6,maxticks=12) ax.set_xlabel(timezone, color='black', rotation='horizontal') mplt.add_legend() if mconfig.parser("plot_title_as_region"): fig.set_title(zone_input) ax.set_ylabel(f"Line violations ({unitconversion['units']})", color='black', rotation='vertical') outputs[zone_input] = {'fig': fig,'data_table':Data_Table_Out} return outputs def net_export(self, timezone: str = "", start_date_range: str = None, end_date_range: str = None, **_): """creates a timeseries net export line graph. Scenarios are plotted as separate lines. Args: timezone (str, optional): The timezone to display on the x-axes. Defaults to "". start_date_range (str, optional): Defines a start date at which to represent data from. Defaults to None. end_date_range (str, optional): Defines a end date at which to represent data to. Defaults to None. Returns: dict: dictionary containing the created plot and its data table """ if self.AGG_BY == 'zone': agg = 'zone' else: agg = 'region' # List of properties needed by the plot, properties are a set of tuples and contain 3 parts: # required True/False, property name and scenarios required, scenarios must be a list. properties = [(True,f"{agg}_Net_Interchange",self.Scenarios)] # Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary # with all required properties, returns a 1 if required data is missing check_input_data = self.get_formatted_data(properties) if 1 in check_input_data: return MissingInputData() outputs = {} for zone_input in self.Zones: self.logger.info(f"{self.AGG_BY} = {zone_input}") net_export_all_scenarios = pd.DataFrame() for scenario in self.Scenarios: self.logger.info(f"Scenario = {scenario}") net_export_read = self[f"{agg}_Net_Interchange"].get(scenario) if self.shift_leapday == True: net_export_read = self.adjust_for_leapday(net_export_read) net_export = net_export_read.xs(zone_input, level = self.AGG_BY) net_export = net_export.groupby("timestamp").sum() net_export.columns = [scenario] if pd.notna(start_date_range): self.logger.info(f"Plotting specific date range: \ {str(start_date_range)} to {str(end_date_range)}") net_export = net_export[start_date_range : end_date_range] net_export_all_scenarios = pd.concat([net_export_all_scenarios,net_export], axis = 1) net_export_all_scenarios.columns = net_export_all_scenarios.columns.str.replace('_', ' ') unitconversion = self.capacity_energy_unitconversion(net_export_all_scenarios) net_export_all_scenarios = net_export_all_scenarios/unitconversion["divisor"] # Data table of values to return to main program Data_Table_Out = net_export_all_scenarios.add_suffix(f" ({unitconversion['units']})") #Make scenario/color dictionary. color_dict = dict(zip(net_export_all_scenarios.columns,self.color_list)) mplt = PlotLibrary() fig, ax = mplt.get_figure() plt.subplots_adjust(wspace=0.05, hspace=0.2) if net_export_all_scenarios.empty: out = MissingZoneData() outputs[zone_input] = out continue for column in net_export_all_scenarios: mplt.lineplot(net_export_all_scenarios,column,color_dict, label=column) ax.set_ylabel(f'Net exports ({unitconversion["units"]})', color='black', rotation='vertical') ax.set_xlabel(timezone, color='black', rotation='horizontal') ax.margins(x=0.01) ax.hlines(y=0, xmin=ax.get_xlim()[0], xmax=ax.get_xlim()[1], linestyle=':') mplt.set_subplot_timeseries_format() mplt.add_legend(reverse_legend=True) if mconfig.parser("plot_title_as_region"): mplt.add_main_title(zone_input) outputs[zone_input] = {'fig': fig, 'data_table': Data_Table_Out} return outputs def zonal_interchange(self, figure_name: str = None, start_date_range: str = None, end_date_range: str = None, **_): """Creates a line plot of the net interchange between each zone, with a facet for each zone. The method will only work if agg_by = "zone". The code will create either a timeseries or duration curve depending on if the word 'duration_curve' is in the figure_name. To make a duration curve, ensure the word 'duration_curve' is found in the figure_name. Args: figure_name (str, optional): User defined figure output name. Defaults to None. start_date_range (str, optional): Defines a start date at which to represent data from. Defaults to None. end_date_range (str, optional): Defines a end date at which to represent data to. Defaults to None. Returns: dict: dictionary containing the created plot and its data table """ if self.AGG_BY not in ["zone", "zones", "Zone", "Zones"]: self.logger.warning("This plot only supports aggregation zone") return UnsupportedAggregation() duration_curve=False if 'duration_curve' in figure_name: duration_curve = True # List of properties needed by the plot, properties are a set of tuples and contain 3 parts: # required True/False, property name and scenarios required, scenarios must be a list. properties = [(True,"line_Flow",self.Scenarios)] # Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary # with all required properties, returns a 1 if required data is missing check_input_data = self.get_formatted_data(properties) if 1 in check_input_data: return MissingInputData() outputs = {} # sets up x, y dimensions of plot ncols, nrows = self.set_facet_col_row_dimensions(multi_scenario=self.Scenarios) grid_size = ncols*nrows # Used to calculate any excess axis to delete plot_number = len(self.Scenarios) excess_axs = grid_size - plot_number for zone_input in self.Zones: self.logger.info(f"{self.AGG_BY} = {zone_input}") mplt = PlotLibrary(nrows, ncols, sharey=True, squeeze=False, ravel_axs=True) fig, axs = mplt.get_figure() plt.subplots_adjust(wspace=0.1, hspace=0.5) net_exports_all = [] for n, scenario in enumerate(self.Scenarios): net_exports = [] exp_lines = self.meta.zone_exporting_lines(scenario) imp_lines = self.meta.zone_importing_lines(scenario) if exp_lines.empty or imp_lines.empty: return MissingMetaData() exp_lines.columns = ['region','line_name'] imp_lines.columns = ['region','line_name'] #Find list of lines that connect each region. exp_oz = exp_lines[exp_lines['region'] == zone_input] imp_oz = imp_lines[imp_lines['region'] == zone_input] other_zones = self.meta.zones(scenario).name.tolist() try: other_zones.remove(zone_input) except: self.logger.warning("Are you sure you set agg_by = zone?") self.logger.info(f"Scenario = {str(scenario)}") flow = self["line_Flow"][scenario].copy() if self.shift_leapday == True: flow = self.adjust_for_leapday(flow) flow = flow.reset_index() for other_zone in other_zones: exp_other_oz = exp_lines[exp_lines['region'] == other_zone] imp_other_oz = imp_lines[imp_lines['region'] == other_zone] exp_pair = pd.merge(exp_oz, imp_other_oz, left_on='line_name', right_on='line_name') imp_pair = pd.merge(imp_oz, exp_other_oz, left_on='line_name', right_on='line_name') #Swap columns for importing lines imp_pair = imp_pair.reindex(columns=['region_from', 'line_name', 'region_to']) export = flow[flow['line_name'].isin(exp_pair['line_name'])] imports = flow[flow['line_name'].isin(imp_pair['line_name'])] export = export.groupby(['timestamp']).sum() imports = imports.groupby(['timestamp']).sum() #Check for situations where there are only exporting or importing lines for this zonal pair. if imports.empty: net_export = export elif export.empty: net_export = -imports else: net_export = export - imports net_export.columns = [other_zone] if pd.notna(start_date_range): if other_zone == [other_zones[0]]: self.logger.info(f"Plotting specific date range: \ {str(start_date_range)} to {str(end_date_range)}") net_export = net_export[start_date_range : end_date_range] if duration_curve: net_export = self.sort_duration(net_export,other_zone) net_exports.append(net_export) net_exports = pd.concat(net_exports,axis = 1) net_exports = net_exports.dropna(axis = 'columns') net_exports.index = pd.to_datetime(net_exports.index) net_exports['Net export'] = net_exports.sum(axis = 1) # unitconversion based off peak export hour, only checked once if zone_input == self.Zones[0] and scenario == self.Scenarios[0]: unitconversion = self.capacity_energy_unitconversion(net_exports) net_exports = net_exports / unitconversion['divisor'] if duration_curve: net_exports = net_exports.reset_index().drop(columns = 'index') for column in net_exports: linestyle = '--' if column == 'Net export' else 'solid' mplt.lineplot(net_exports, column=column, label=column, sub_pos=n, linestyle=linestyle) axs[n].margins(x=0.01) #Add horizontal line at 0. axs[n].hlines(y=0, xmin=axs[n].get_xlim()[0], xmax=axs[n].get_xlim()[1], linestyle=':') if not duration_curve: mplt.set_subplot_timeseries_format(sub_pos=n) #Add scenario column to output table. scenario_names = pd.Series([scenario] * len(net_exports), name='Scenario') net_exports = net_exports.add_suffix(f" ({unitconversion['units']})") net_exports = net_exports.set_index([scenario_names], append=True) net_exports_all.append(net_exports) mplt.add_facet_labels(xlabels=self.xlabels, ylabels = self.ylabels) mplt.add_legend() #Remove extra axes mplt.remove_excess_axs(excess_axs,grid_size) if mconfig.parser("plot_title_as_region"): mplt.add_main_title(zone_input) plt.ylabel(f"Net export ({unitconversion['units']})", color='black', rotation='vertical', labelpad=40) if duration_curve: plt.xlabel('Sorted hour of the year', color='black', labelpad=30) Data_Table_Out = pd.concat(net_exports_all) # if plotting all scenarios return figures to plot_main outputs[zone_input] = {'fig': fig,'data_table' : Data_Table_Out} return outputs def zonal_interchange_total(self, start_date_range: str = None, end_date_range: str = None, **_): """Creates a barplot of the net interchange between each zone, separated by positive and negative flows. The method will only work if agg_by = "zone". Args: start_date_range (str, optional): Defines a start date at which to represent data from. Defaults to None. end_date_range (str, optional): Defines a end date at which to represent data to. Defaults to None. Returns: dict: dictionary containing the created plot and its data table """ if self.AGG_BY not in ["zone", "zones", "Zone", "Zones"]: self.logger.warning("This plot only supports aggregation zone") return UnsupportedAggregation() # List of properties needed by the plot, properties are a set of tuples and contain 3 parts: # required True/False, property name and scenarios required, scenarios must be a list. properties = [(True,"line_Flow",self.Scenarios)] # Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary # with all required properties, returns a 1 if required data is missing check_input_data = self.get_formatted_data(properties) if 1 in check_input_data: return MissingInputData() outputs = {} for zone_input in self.Zones: self.logger.info(f"{self.AGG_BY} = {zone_input}") mplt = PlotLibrary() fig, ax = mplt.get_figure() plt.subplots_adjust(wspace=0.05, hspace=0.2) net_exports_all = [] # Holds each scenario output table data_out_chunk = [] for n, scenario in enumerate(self.Scenarios): exp_lines = self.meta.zone_exporting_lines(scenario) imp_lines = self.meta.zone_importing_lines(scenario) if exp_lines.empty or imp_lines.empty: return MissingMetaData() exp_lines.columns = ['region', 'line_name'] imp_lines.columns = ['region', 'line_name'] #Find list of lines that connect each region. exp_oz = exp_lines[exp_lines['region'] == zone_input] imp_oz = imp_lines[imp_lines['region'] == zone_input] other_zones = self.meta.zones(scenario).name.tolist() other_zones.remove(zone_input) net_exports = [] self.logger.info(f"Scenario = {str(scenario)}") flow = self["line_Flow"][scenario] flow = flow.reset_index() for other_zone in other_zones: exp_other_oz = exp_lines[exp_lines['region'] == other_zone] imp_other_oz = imp_lines[imp_lines['region'] == other_zone] exp_pair = pd.merge(exp_oz, imp_other_oz, left_on='line_name', right_on='line_name') imp_pair = pd.merge(imp_oz, exp_other_oz, left_on='line_name', right_on='line_name') #Swap columns for importing lines imp_pair = imp_pair.reindex(columns=['region_from', 'line_name', 'region_to']) export = flow[flow['line_name'].isin(exp_pair['line_name'])] imports = flow[flow['line_name'].isin(imp_pair['line_name'])] export = export.groupby(['timestamp']).sum() imports = imports.groupby(['timestamp']).sum() #Check for situations where there are only exporting or importing lines for this zonal pair. if imports.empty: net_export = export elif export.empty: net_export = -imports else: net_export = export - imports net_export.columns = [other_zone] if pd.notna(start_date_range): if other_zone == other_zones[0]: self.logger.info(f"Plotting specific date range: \ {str(start_date_range)} to {str(end_date_range)}") net_export = net_export[start_date_range : end_date_range] net_exports.append(net_export) net_exports = pd.concat(net_exports, axis=1) net_exports = net_exports.dropna(axis='columns') net_exports.index = pd.to_datetime(net_exports.index) net_exports['Net Export'] = net_exports.sum(axis=1) positive = net_exports.agg(lambda x: x[x>0].sum()) negative = net_exports.agg(lambda x: x[x<0].sum()) both = pd.concat([positive,negative], axis=1) both.columns = ["Total Export", "Total Import"] # unitconversion based off peak export hour, only checked once if scenario == self.Scenarios[0]: unitconversion = self.capacity_energy_unitconversion(both) both = both / unitconversion['divisor'] net_exports_all.append(both) #Add scenario column to output table. scenario_names = pd.Series([scenario] * len(both), name='Scenario') data_table = both.set_index([scenario_names], append=True) data_table = data_table.add_suffix(f" ({unitconversion['units']})") data_out_chunk.append(data_table) Data_Table_Out = pd.concat(data_out_chunk) #Make scenario/color dictionary. color_dict = dict(zip(self.Scenarios, self.color_list)) mplt.clustered_stacked_barplot(net_exports_all, labels=self.Scenarios, color_dict=color_dict) ax.hlines(y=0, xmin=ax.get_xlim()[0], xmax=ax.get_xlim()[1], linestyle=':') ax.set_ylabel(f"Interchange ({unitconversion['units']}h)", color='black', rotation='vertical') if mconfig.parser("plot_title_as_region"): mplt.add_main_title(zone_input) outputs[zone_input] = {'fig': fig,'data_table': Data_Table_Out} return outputs def total_int_flow_ind(self, prop: str = None, start_date_range: str = None, end_date_range: str = None, **_): """Creates a clustered barplot of the total flow for a specific interface, separated by positive and negative flows. Specify the interface(s) of interest by providing a comma separated string to the property entry. Scenarios are clustered together as different colored bars. If multiple interfaces are provided, each will be plotted as a separate group of clustered bar. Args: prop (str, optional): Comma separated string of interfaces to plot. Defaults to None. start_date_range (str, optional): Defines a start date at which to represent data from. Defaults to None. end_date_range (str, optional): Defines a end date at which to represent data to. Defaults to None. Returns: DataSavedInModule: DataSavedInModule exception. """ # List of properties needed by the plot, properties are a set of tuples and contain 3 parts: # required True/False, property name and scenarios required, scenarios must be a list. properties = [(True,"interface_Flow",self.Scenarios)] # Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary # with all required properties, returns a 1 if required data is missing check_input_data = self.get_formatted_data(properties) if 1 in check_input_data: return MissingInputData() #Select only interfaces specified in Marmot_plot_select.csv. select_ints = prop.split(",") if select_ints == None: return InputSheetError() self.logger.info('Plotting only the interfaces specified in Marmot_plot_select.csv') self.logger.info(select_ints) mplt = PlotLibrary() fig, ax = mplt.get_figure() plt.subplots_adjust(wspace=0.05, hspace=0.2) net_flows_all = [] # Holds each scenario output table data_out_chunk = [] for i, scenario in enumerate(self.Scenarios): self.logger.info(f"Scenario = {str(scenario)}") flow_all = self["interface_Flow"][scenario] pos = pd.Series(name='Total Export') neg = pd.Series(name='Total Import') available_inter = select_ints.copy() for inter in select_ints: if inter not in flow_all.index.get_level_values('interface_name'): self.logger.info(f'{inter} Not in Data') available_inter.remove(inter) continue #Remove leading spaces if inter[0] == ' ': inter = inter[1:] flow = flow_all.xs(inter, level='interface_name') flow = flow.reset_index() if pd.notna(start_date_range): self.logger.info("Plotting specific date range: \ {} to {}".format(str(start_date_range), str(end_date_range))) flow = flow[start_date_range : end_date_range] flow = flow[0] pos_sing = pd.Series(flow.where(flow > 0).sum()) pos = pos.append(pos_sing) neg_sing = pd.Series(flow.where(flow < 0).sum()) neg = neg.append(neg_sing) both = pd.concat([pos,neg],axis = 1) both.columns = ['Total Export','Total Import'] if scenario == self.Scenarios[0]: unitconversion = self.capacity_energy_unitconversion(both) both = both / unitconversion['divisor'] both.index = available_inter net_flows_all.append(both) #Add scenario column to output table. scenario_names = pd.Series([scenario] * len(both),name = 'Scenario') data_table = both.set_index([scenario_names],append = True) data_table = data_table.add_suffix(f" ({unitconversion['units']})") data_out_chunk.append(data_table) Data_Table_Out = pd.concat(data_out_chunk) #Make scenario/color dictionary. color_dict = dict(zip(self.Scenarios, self.color_list)) mplt.clustered_stacked_barplot(net_flows_all, labels=self.Scenarios, color_dict=color_dict) ax.hlines(y=0, xmin=ax.get_xlim()[0], xmax=ax.get_xlim()[1], linestyle=':') ax.set_ylabel('Flow ({}h)'.format(unitconversion['units']), color='black', rotation='vertical') ax.set_xlabel('') fig.savefig(os.path.join(self.Marmot_Solutions_folder, "Figures_Output", f"{self.AGG_BY }_transmission", "Individual_Interface_Total_Flow.svg"), dpi=600, bbox_inches='tight') Data_Table_Out.to_csv(os.path.join(self.Marmot_Solutions_folder, "Figures_Output", f"{self.AGG_BY }_transmission", "Individual_Interface_Total_Flow.csv")) outputs = DataSavedInModule() return outputs ### Archived Code #### # def line_util_agged(self): # self["line_Flow"] = {} # interface_flow_collection = {} # line_limit_collection = {} # interface_limit_collection = {} # #Load data # self._getdata(self["line_Flow"],"line_Flow") # self._getdata(interface_flow_collection,"interface_Flow") # self._getdata(line_limit_collection,"line_Export_Limit") # self._getdata(interface_limit_collection,"interface_Export_Limit") # outputs = {} # for zone_input in self.Zones: # self.logger.info('Zone = ' + str(zone_input)) # all_scenarios = pd.DataFrame() # for scenario in self.Scenarios: # self.logger.info("Scenario = " + str(scenario)) # lineflow = self["line_Flow"].get(scenario) # linelim = line_limit_collection.get(scenario) # linelim = linelim.reset_index().drop('timestamp', axis = 1).set_index('line_name') # #Calculate utilization. # alllines = pd.merge(lineflow,linelim,left_index=True,right_index=True) # alllines = alllines.rename(columns = {'0_x':'flow','0_y':'capacity'}) # alllines['flow'] = abs(alllines['flow']) # #Merge in region ID and aggregate by region. # if self.AGG_BY == 'region': # line2region = self.region_lines # elif self.AGG_BY == 'zone': # line2region = self.zone_lines # alllines = alllines.reset_index() # alllines = alllines.merge(line2region, on = 'line_name') # #Extract ReEDS expansion lines for next section. # reeds_exp = alllines.merge((self.lines.rename(columns={"name":"line_name"})), on = 'line_name') # reeds_exp = reeds_exp[reeds_exp['category'] == 'ReEDS_Expansion'] # reeds_agg = reeds_exp.groupby(['timestamp',self.AGG_BY],as_index = False).sum() # #Subset only enforced lines. This will subset to only EI lines. # enforced = pd.read_csv('/projects/continental/pcm/Results/enforced_lines.csv') # enforced.columns = ['line_name'] # lineutil = pd.merge(enforced,alllines, on = 'line_name') # lineutil['line util'] = lineutil['flow'] / lineutil['capacity'] # lineutil = lineutil[lineutil.capacity < 10000] # #Drop duplicates if AGG_BY == Interconnection. # #Aggregate by region, merge in region mapping. # agg = alllines.groupby(['timestamp',self.AGG_BY],as_index = False).sum() # agg['util'] = agg['flow'] / agg['capacity'] # agg = agg.rename(columns = {'util' : scenario}) # onezone = agg[agg[self.AGG_BY] == zone_input] # onezone = onezone.set_index('timestamp')[scenario] # #If zone_input is in WI or ERCOT, the dataframe will be empty here. Lines are not enforced here. Instead, use interfaces. # if onezone.empty: # #Start with interface flow. # intflow = interface_flow_collection.get(scenario) # intlim = interface_limit_collection.get(scenario) # allint = pd.merge(intflow,intlim,left_index=True,right_index=True) # allint = allint.rename(columns = {'0_x':'flow','0_y':'capacity'}) # allint = allint.reset_index() # #Merge in interface/line/region mapping. # line2int = self.interface_lines # line2int = line2int.rename(columns = {'line' : 'line_name','interface' : 'interface_name'}) # allint = allint.merge(line2int, on = 'interface_name', how = 'inner') # allint = allint.merge(line2region, on = 'line_name') # allint = allint.merge(self.Region_Mapping, on = 'region') # allint = allint.drop(columns = 'line_name') # allint = allint.drop_duplicates() #Merging in line info duplicated most of the interfaces. # agg = allint.groupby(['timestamp',self.AGG_BY],as_index = False).sum() # agg = pd.concat([agg,reeds_agg]) #Add in ReEDS expansion lines, re-aggregate. # agg = agg.groupby(['timestamp',self.AGG_BY],as_index = False).sum() # agg['util'] = agg['flow'] / agg['capacity'] # agg = agg.rename(columns = {'util' : scenario}) # onezone = agg[agg[self.AGG_BY] == zone_input] # onezone = onezone.set_index('timestamp')[scenario] # if (prop != prop) == False: #Show only subset category of lines. # reeds_agg = reeds_agg.groupby('timestamp',as_index = False).sum() # reeds_agg['util'] = reeds_agg['flow'] / reeds_agg['capacity'] # onezone = reeds_agg.rename(columns = {'util' : scenario}) # onezone = onezone.set_index('timestamp')[scenario] # all_scenarios = pd.concat([all_scenarios,onezone], axis = 1) # # Data table of values to return to main program # Data_Table_Out = all_scenarios.copy() # #Make scenario/color dictionary. # scenario_color_dict = {} # for idx,column in enumerate(all_scenarios.columns): # dictionary = {column : self.color_list[idx]} # scenario_color_dict.update(dictionary) # all_scenarios.index = pd.to_datetime(all_scenarios.index) # fig, ax = plt.subplots(figsize=(9,6)) # for idx,column in enumerate(all_scenarios.columns): # ax.plot(all_scenarios.index.values,all_scenarios[column], linewidth=2, color = scenario_color_dict.get(column,'#333333'),label=column) # ax.set_ylabel('Transmission utilization (%)', color='black', rotation='vertical') # ax.set_xlabel(timezone, color='black', rotation='horizontal') # ax.spines['right'].set_visible(False) # ax.spines['top'].set_visible(False) # ax.tick_params(axis='y', which='major', length=5, width=1) # ax.tick_params(axis='x', which='major', length=5, width=1) # ax.margins(x=0.01) # locator = mdates.AutoDateLocator(minticks=6, maxticks=12) # formatter = mdates.ConciseDateFormatter(locator) # formatter.formats[2] = '%d\n %b' # formatter.zero_formats[1] = '%b\n %Y' # formatter.zero_formats[2] = '%d\n %b' # formatter.zero_formats[3] = '%H:%M\n %d-%b' # formatter.offset_formats[3] = '%b %Y' # formatter.show_offset = False # ax.xaxis.set_major_locator(locator) # ax.xaxis.set_major_formatter(formatter) # ax.yaxis.set_major_formatter(mtick.PercentFormatter(1.0)) # ax.hlines(y = 1, xmin = ax.get_xlim()[0], xmax = ax.get_xlim()[1], linestyle = ':') #Add horizontal line at 100%. # handles, labels = ax.get_legend_handles_labels() # #Legend 1 # leg1 = ax.legend(reversed(handles), reversed(labels), loc='best',facecolor='inherit', frameon=True) # # Manually add the first legend back # ax.add_artist(leg1) # outputs[zone_input] = {'fig': fig, 'data_table': Data_Table_Out} # return outputs # def region_region_duration(self): # rr_int = pd.read_hdf(os.path.join(self.Marmot_Solutions_folder,self.Scenarios[0],"Processed_HDF5_folder", self.Scenarios[0] + "_formatted.h5"),"region_regions_Net_Interchange") # agg_region_mapping = self.Region_Mapping[['region',self.AGG_BY]].set_index('region').to_dict()[self.AGG_BY] # rr_int = rr_int.reset_index() # rr_int['parent'] = rr_int['parent'].map(agg_region_mapping) # rr_int['child'] = rr_int['child'].map(agg_region_mapping) # rr_int_agg = rr_int.groupby(['parent','child'],as_index=True).sum() # Determine annual net flow between regions. # rr_int_agg.rename(columns = {0:'flow (MW)'}, inplace = True) # rr_int_agg = rr_int_agg.reset_index(['parent','child']) # rr_int_agg=rr_int_agg.loc[rr_int_agg['flow (MW)']>0.01] # Keep only positive flows # # rr_int_agg.set_index(['parent','child'],inplace=True) # rr_int_agg['path']=rr_int_agg['parent']+"_"+rr_int_agg['child'] # if (prop!=prop)==False: # This checks for a nan in string. If a number of paths is selected only plot those # pathlist=rr_int_agg.sort_values(ascending=False,by='flow (MW)')['path'][1:int(prop)+1] #list of top paths based on number selected # else: # pathlist=rr_int_agg['path'] #List of paths # rr_int_hr = rr_int.groupby(['timestamp','parent','child'],as_index=True).sum() # Hourly flow # rr_int_hr.rename(columns = {0:'flow (MW)'}, inplace = True) # rr_int_hr.reset_index(['timestamp','parent','child'],inplace=True) # rr_int_hr['path']=rr_int_hr['parent']+"_"+rr_int_hr['child'] # rr_int_hr.set_index(['path'],inplace=True) # rr_int_hr['Abs MW']=abs(rr_int_hr['flow (MW)']) # rr_int_hr['Abs MW'].sum() # rr_int_hr.loc[pathlist]['Abs MW'].sum()*2 # Check that the sum of the absolute value of flows is the same. i.e. only redundant flows were eliminated. # rr_int_hr=rr_int_hr.loc[pathlist].drop(['Abs MW'],axis=1) # ## Plot duration curves # fig, ax3 = plt.subplots(figsize=(9,6)) # for i in pathlist: # duration_curve = rr_int_hr.loc[i].sort_values(ascending=False,by='flow (MW)').reset_index() # plt.plot(duration_curve['flow (MW)'],label=i) # del duration_curve # ax3.set_ylabel('flow MW', color='black', rotation='vertical') # ax3.set_xlabel('Intervals', color='black', rotation='horizontal') # ax3.spines['right'].set_visible(False) # ax3.spines['top'].set_visible(False) # # if (prop!=prop)==False: # This checks for a nan in string. If no limit selected, do nothing # ax3.legend(loc='best') # # plt.lim((0,int(prop))) # Data_Table_Out = rr_int_hr # return {'fig': fig, 'data_table': Data_Table_Out}
[ "marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData", "matplotlib.pyplot.axes", "marmot.plottingmodules.plotutils.plot_exceptions.InputSheetError", "marmot.plottingmodules.plotutils.plot_exceptions.UnsupportedAggregation", "numpy.arange", "marmot.plottingmodules.plotutils.plot_exceptions.DataSavedInModule", "os.path.join", "matplotlib.pyplot.tight_layout", "pandas.DataFrame", "matplotlib.cm.ScalarMappable", "pandas.merge", "marmot.config.mconfig.parser", "pandas.isna", "pandas.concat", "marmot.plottingmodules.plotutils.plot_library.PlotLibrary", "matplotlib.dates.ConciseDateFormatter", "pandas.to_datetime", "pandas.Series", "marmot.plottingmodules.plotutils.plot_exceptions.MissingMetaData", "matplotlib.pyplot.subplots_adjust", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.cm.get_cmap", "pandas.notna", "pandas.isnull", "marmot.plottingmodules.plotutils.plot_exceptions.UnderDevelopment", "matplotlib.dates.AutoDateLocator", "marmot.plottingmodules.plotutils.plot_exceptions.MissingZoneData", "matplotlib.pyplot.xlabel", "logging.getLogger" ]
[((1941, 1985), 'logging.getLogger', 'logging.getLogger', (["('marmot_plot.' + __name__)"], {}), "('marmot_plot.' + __name__)\n", (1958, 1985), False, 'import logging\n'), ((2013, 2044), 'marmot.config.mconfig.parser', 'mconfig.parser', (['"""font_settings"""'], {}), "('font_settings')\n", (2027, 2044), True, 'import marmot.config.mconfig as mconfig\n'), ((12724, 12750), 'pandas.notna', 'pd.notna', (['start_date_range'], {}), '(start_date_range)\n', (12732, 12750), True, 'import pandas as pd\n'), ((33180, 33198), 'marmot.plottingmodules.plotutils.plot_exceptions.UnderDevelopment', 'UnderDevelopment', ([], {}), '()\n', (33196, 33198), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((46521, 46575), 'marmot.plottingmodules.plotutils.plot_library.PlotLibrary', 'PlotLibrary', (['ydim', 'xdim'], {'squeeze': '(False)', 'ravel_axs': '(True)'}), '(ydim, xdim, squeeze=False, ravel_axs=True)\n', (46532, 46575), False, 'from marmot.plottingmodules.plotutils.plot_library import PlotLibrary\n'), ((50685, 50710), 'pandas.concat', 'pd.concat', (['chunks'], {'axis': '(1)'}), '(chunks, axis=1)\n', (50694, 50710), True, 'import pandas as pd\n'), ((50863, 50935), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Flow (MW)"""'], {'color': '"""black"""', 'rotation': '"""vertical"""', 'labelpad': '(30)'}), "('Flow (MW)', color='black', rotation='vertical', labelpad=30)\n", (50873, 50935), True, 'import matplotlib.pyplot as plt\n'), ((50996, 51014), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (51012, 51014), True, 'import matplotlib.pyplot as plt\n'), ((51576, 51595), 'marmot.plottingmodules.plotutils.plot_exceptions.DataSavedInModule', 'DataSavedInModule', ([], {}), '()\n', (51593, 51595), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((53751, 53805), 'marmot.plottingmodules.plotutils.plot_library.PlotLibrary', 'PlotLibrary', (['ydim', 'xdim'], {'squeeze': '(False)', 'ravel_axs': '(True)'}), '(ydim, xdim, squeeze=False, ravel_axs=True)\n', (53762, 53805), False, 'from marmot.plottingmodules.plotutils.plot_library import PlotLibrary\n'), ((53879, 53923), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.05)', 'hspace': '(0.2)'}), '(wspace=0.05, hspace=0.2)\n', (53898, 53923), True, 'import matplotlib.pyplot as plt\n'), ((55588, 55613), 'pandas.concat', 'pd.concat', (['chunks'], {'axis': '(1)'}), '(chunks, axis=1)\n', (55597, 55613), True, 'import pandas as pd\n'), ((55650, 55737), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Flow difference (MW)"""'], {'color': '"""black"""', 'rotation': '"""vertical"""', 'labelpad': '(30)'}), "('Flow difference (MW)', color='black', rotation='vertical',\n labelpad=30)\n", (55660, 55737), True, 'import matplotlib.pyplot as plt\n'), ((55743, 55761), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (55759, 55761), True, 'import matplotlib.pyplot as plt\n'), ((56177, 56196), 'marmot.plottingmodules.plotutils.plot_exceptions.DataSavedInModule', 'DataSavedInModule', ([], {}), '()\n', (56194, 56196), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((57627, 57652), 'pandas.isna', 'pd.isna', (['start_date_range'], {}), '(start_date_range)\n', (57634, 57652), True, 'import pandas as pd\n'), ((60804, 60842), 'marmot.plottingmodules.plotutils.plot_library.PlotLibrary', 'PlotLibrary', (['ydim', 'xdim'], {'squeeze': '(False)'}), '(ydim, xdim, squeeze=False)\n', (60815, 60842), False, 'from marmot.plottingmodules.plotutils.plot_library import PlotLibrary\n'), ((64336, 64361), 'pandas.concat', 'pd.concat', (['chunks'], {'axis': '(1)'}), '(chunks, axis=1)\n', (64345, 64361), True, 'import pandas as pd\n'), ((64588, 64660), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Flow (MW)"""'], {'color': '"""black"""', 'rotation': '"""vertical"""', 'labelpad': '(30)'}), "('Flow (MW)', color='black', rotation='vertical', labelpad=30)\n", (64598, 64660), True, 'import matplotlib.pyplot as plt\n'), ((64670, 64688), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (64686, 64688), True, 'import matplotlib.pyplot as plt\n'), ((65292, 65311), 'marmot.plottingmodules.plotutils.plot_exceptions.DataSavedInModule', 'DataSavedInModule', ([], {}), '()\n', (65309, 65311), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((65524, 65542), 'marmot.plottingmodules.plotutils.plot_exceptions.UnderDevelopment', 'UnderDevelopment', ([], {}), '()\n', (65540, 65542), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((80411, 80467), 'marmot.plottingmodules.plotutils.plot_library.PlotLibrary', 'PlotLibrary', (['nrows', 'ncols'], {'squeeze': '(False)', 'ravel_axs': '(True)'}), '(nrows, ncols, squeeze=False, ravel_axs=True)\n', (80422, 80467), False, 'from marmot.plottingmodules.plotutils.plot_library import PlotLibrary\n'), ((80543, 80587), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.02)', 'hspace': '(0.4)'}), '(wspace=0.02, hspace=0.4)\n', (80562, 80587), True, 'import matplotlib.pyplot as plt\n'), ((83463, 83495), 'matplotlib.pyplot.axes', 'plt.axes', (['[0.9, 0.1, 0.035, 0.8]'], {}), '([0.9, 0.1, 0.035, 0.8])\n', (83471, 83495), True, 'import matplotlib.pyplot as plt\n'), ((83621, 83695), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""To Region"""'], {'color': '"""black"""', 'rotation': '"""horizontal"""', 'labelpad': '(40)'}), "('To Region', color='black', rotation='horizontal', labelpad=40)\n", (83631, 83695), True, 'import matplotlib.pyplot as plt\n'), ((83723, 83797), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""From Region"""'], {'color': '"""black"""', 'rotation': '"""vertical"""', 'labelpad': '(40)'}), "('From Region', color='black', rotation='vertical', labelpad=40)\n", (83733, 83797), True, 'import matplotlib.pyplot as plt\n'), ((83844, 83871), 'pandas.concat', 'pd.concat', (['Data_Out'], {'axis': '(1)'}), '(Data_Out, axis=1)\n', (83853, 83871), True, 'import pandas as pd\n'), ((83894, 83957), 'os.path.join', 'os.path.join', (['self.figure_folder', 'f"""{self.AGG_BY}_transmission"""'], {}), "(self.figure_folder, f'{self.AGG_BY}_transmission')\n", (83906, 83957), False, 'import os\n'), ((84203, 84222), 'marmot.plottingmodules.plotutils.plot_exceptions.DataSavedInModule', 'DataSavedInModule', ([], {}), '()\n', (84220, 84222), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((110774, 110787), 'marmot.plottingmodules.plotutils.plot_library.PlotLibrary', 'PlotLibrary', ([], {}), '()\n', (110785, 110787), False, 'from marmot.plottingmodules.plotutils.plot_library import PlotLibrary\n'), ((110832, 110876), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.05)', 'hspace': '(0.2)'}), '(wspace=0.05, hspace=0.2)\n', (110851, 110876), True, 'import matplotlib.pyplot as plt\n'), ((113122, 113147), 'pandas.concat', 'pd.concat', (['data_out_chunk'], {}), '(data_out_chunk)\n', (113131, 113147), True, 'import pandas as pd\n'), ((114170, 114189), 'marmot.plottingmodules.plotutils.plot_exceptions.DataSavedInModule', 'DataSavedInModule', ([], {}), '()\n', (114187, 114189), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((5012, 5030), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (5028, 5030), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((5548, 5617), 'marmot.plottingmodules.plotutils.plot_library.PlotLibrary', 'PlotLibrary', (['nrows', 'ncols'], {'sharey': '(True)', 'squeeze': '(False)', 'ravel_axs': '(True)'}), '(nrows, ncols, sharey=True, squeeze=False, ravel_axs=True)\n', (5559, 5617), False, 'from marmot.plottingmodules.plotutils.plot_library import PlotLibrary\n'), ((5704, 5748), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.1)', 'hspace': '(0.25)'}), '(wspace=0.1, hspace=0.25)\n', (5723, 5748), True, 'import matplotlib.pyplot as plt\n'), ((10129, 10167), 'marmot.config.mconfig.parser', 'mconfig.parser', (['"""plot_title_as_region"""'], {}), "('plot_title_as_region')\n", (10143, 10167), True, 'import marmot.config.mconfig as mconfig\n'), ((10337, 10358), 'pandas.concat', 'pd.concat', (['data_table'], {}), '(data_table)\n', (10346, 10358), True, 'import pandas as pd\n'), ((12633, 12651), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (12649, 12651), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((13032, 13046), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (13044, 13046), True, 'import pandas as pd\n'), ((15667, 15681), 'pandas.notna', 'pd.notna', (['prop'], {}), '(prop)\n', (15675, 15681), True, 'import pandas as pd\n'), ((16106, 16160), 'marmot.plottingmodules.plotutils.plot_library.PlotLibrary', 'PlotLibrary', (['ydim', 'xdim'], {'squeeze': '(False)', 'ravel_axs': '(True)'}), '(ydim, xdim, squeeze=False, ravel_axs=True)\n', (16117, 16160), False, 'from marmot.plottingmodules.plotutils.plot_library import PlotLibrary\n'), ((16336, 16380), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.05)', 'hspace': '(0.2)'}), '(wspace=0.05, hspace=0.2)\n', (16355, 16380), True, 'import matplotlib.pyplot as plt\n'), ((20551, 20576), 'pandas.concat', 'pd.concat', (['chunks'], {'axis': '(1)'}), '(chunks, axis=1)\n', (20560, 20576), True, 'import pandas as pd\n'), ((21214, 21286), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Flow (GW)"""'], {'color': '"""black"""', 'rotation': '"""vertical"""', 'labelpad': '(30)'}), "('Flow (GW)', color='black', rotation='vertical', labelpad=30)\n", (21224, 21286), True, 'import matplotlib.pyplot as plt\n'), ((21437, 21478), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {'rect': '[0, 0.03, 1, 0.97]'}), '(rect=[0, 0.03, 1, 0.97])\n', (21453, 21478), True, 'import matplotlib.pyplot as plt\n'), ((21494, 21532), 'marmot.config.mconfig.parser', 'mconfig.parser', (['"""plot_title_as_region"""'], {}), "('plot_title_as_region')\n", (21508, 21532), True, 'import marmot.config.mconfig as mconfig\n'), ((23565, 23583), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (23581, 23583), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((23791, 23805), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (23803, 23805), True, 'import pandas as pd\n'), ((27335, 27373), 'marmot.plottingmodules.plotutils.plot_library.PlotLibrary', 'PlotLibrary', (['ydim', 'xdim'], {'squeeze': '(False)'}), '(ydim, xdim, squeeze=False)\n', (27346, 27373), False, 'from marmot.plottingmodules.plotutils.plot_library import PlotLibrary\n'), ((27518, 27562), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.05)', 'hspace': '(0.2)'}), '(wspace=0.05, hspace=0.2)\n', (27537, 27562), True, 'import matplotlib.pyplot as plt\n'), ((31541, 31566), 'pandas.concat', 'pd.concat', (['chunks'], {'axis': '(1)'}), '(chunks, axis=1)\n', (31550, 31566), True, 'import pandas as pd\n'), ((31705, 31777), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Flow (GW)"""'], {'color': '"""black"""', 'rotation': '"""vertical"""', 'labelpad': '(30)'}), "('Flow (GW)', color='black', rotation='vertical', labelpad=30)\n", (31715, 31777), True, 'import matplotlib.pyplot as plt\n'), ((32072, 32113), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {'rect': '[0, 0.03, 1, 0.97]'}), '(rect=[0, 0.03, 1, 0.97])\n', (32088, 32113), True, 'import matplotlib.pyplot as plt\n'), ((32129, 32167), 'marmot.config.mconfig.parser', 'mconfig.parser', (['"""plot_title_as_region"""'], {}), "('plot_title_as_region')\n", (32143, 32167), True, 'import marmot.config.mconfig as mconfig\n'), ((33949, 33967), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (33965, 33967), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((34079, 34105), 'pandas.isnull', 'pd.isnull', (['self.start_date'], {}), '(self.start_date)\n', (34088, 34105), True, 'import pandas as pd\n'), ((34396, 34410), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (34408, 34410), True, 'import pandas as pd\n'), ((37442, 37498), 'marmot.plottingmodules.plotutils.plot_library.PlotLibrary', 'PlotLibrary', (['nrows', 'ncols'], {'squeeze': '(False)', 'ravel_axs': '(True)'}), '(nrows, ncols, squeeze=False, ravel_axs=True)\n', (37453, 37498), False, 'from marmot.plottingmodules.plotutils.plot_library import PlotLibrary\n'), ((37673, 37717), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.05)', 'hspace': '(0.2)'}), '(wspace=0.05, hspace=0.2)\n', (37692, 37717), True, 'import matplotlib.pyplot as plt\n'), ((41800, 41825), 'pandas.concat', 'pd.concat', (['chunks'], {'axis': '(1)'}), '(chunks, axis=1)\n', (41809, 41825), True, 'import pandas as pd\n'), ((42434, 42506), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Flow (GW)"""'], {'color': '"""black"""', 'rotation': '"""vertical"""', 'labelpad': '(30)'}), "('Flow (GW)', color='black', rotation='vertical', labelpad=30)\n", (42444, 42506), True, 'import matplotlib.pyplot as plt\n'), ((42637, 42678), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {'rect': '[0, 0.03, 1, 0.97]'}), '(rect=[0, 0.03, 1, 0.97])\n', (42653, 42678), True, 'import matplotlib.pyplot as plt\n'), ((42694, 42732), 'marmot.config.mconfig.parser', 'mconfig.parser', (['"""plot_title_as_region"""'], {}), "('plot_title_as_region')\n", (42708, 42732), True, 'import marmot.config.mconfig as mconfig\n'), ((44638, 44656), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (44654, 44656), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((44813, 44830), 'marmot.plottingmodules.plotutils.plot_exceptions.InputSheetError', 'InputSheetError', ([], {}), '()\n', (44828, 44830), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((50613, 50631), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (50629, 50631), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((51101, 51230), 'os.path.join', 'os.path.join', (['self.Marmot_Solutions_folder', '"""Figures_Output"""', "(self.AGG_BY + '_transmission')", "(figure_name + fn_suffix + '.svg')"], {}), "(self.Marmot_Solutions_folder, 'Figures_Output', self.AGG_BY +\n '_transmission', figure_name + fn_suffix + '.svg')\n", (51113, 51230), False, 'import os\n'), ((51286, 51415), 'os.path.join', 'os.path.join', (['self.Marmot_Solutions_folder', '"""Figures_Output"""', "(self.AGG_BY + '_transmission')", "(figure_name + fn_suffix + '.csv')"], {}), "(self.Marmot_Solutions_folder, 'Figures_Output', self.AGG_BY +\n '_transmission', figure_name + fn_suffix + '.csv')\n", (51298, 51415), False, 'import os\n'), ((53102, 53120), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (53118, 53120), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((53307, 53324), 'marmot.plottingmodules.plotutils.plot_exceptions.InputSheetError', 'InputSheetError', ([], {}), '()\n', (53322, 53324), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((55516, 55534), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (55532, 55534), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((55848, 55977), 'os.path.join', 'os.path.join', (['self.Marmot_Solutions_folder', '"""Figures_Output"""', "(self.AGG_BY + '_transmission')", "(figure_name + fn_suffix + '.svg')"], {}), "(self.Marmot_Solutions_folder, 'Figures_Output', self.AGG_BY +\n '_transmission', figure_name + fn_suffix + '.svg')\n", (55860, 55977), False, 'import os\n'), ((56033, 56162), 'os.path.join', 'os.path.join', (['self.Marmot_Solutions_folder', '"""Figures_Output"""', "(self.AGG_BY + '_transmission')", "(figure_name + fn_suffix + '.csv')"], {}), "(self.Marmot_Solutions_folder, 'Figures_Output', self.AGG_BY +\n '_transmission', figure_name + fn_suffix + '.csv')\n", (56045, 56162), False, 'import os\n'), ((58068, 58086), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (58084, 58086), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((58901, 58919), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (58917, 58919), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((59076, 59093), 'marmot.plottingmodules.plotutils.plot_exceptions.InputSheetError', 'InputSheetError', ([], {}), '()\n', (59091, 59093), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((60608, 60626), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (60624, 60626), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((61355, 61406), 'pandas.concat', 'pd.concat', (['[single_exp_lim, single_imp_lim]'], {'axis': '(1)'}), '([single_exp_lim, single_imp_lim], axis=1)\n', (61364, 61406), True, 'import pandas as pd\n'), ((64120, 64150), 'pandas.concat', 'pd.concat', (['chunks_line'], {'axis': '(0)'}), '(chunks_line, axis=0)\n', (64129, 64150), True, 'import pandas as pd\n'), ((64264, 64282), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (64280, 64282), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((64776, 64925), 'os.path.join', 'os.path.join', (['self.Marmot_Solutions_folder', '"""Figures_Output"""', "(self.AGG_BY + '_transmission')", "('Individual_Line_Flow' + fn_suffix + '_seasonal.svg')"], {}), "(self.Marmot_Solutions_folder, 'Figures_Output', self.AGG_BY +\n '_transmission', 'Individual_Line_Flow' + fn_suffix + '_seasonal.svg')\n", (64788, 64925), False, 'import os\n'), ((64981, 65130), 'os.path.join', 'os.path.join', (['self.Marmot_Solutions_folder', '"""Figures_Output"""', "(self.AGG_BY + '_transmission')", "('Individual_Line_Flow' + fn_suffix + '_seasonal.csv')"], {}), "(self.Marmot_Solutions_folder, 'Figures_Output', self.AGG_BY +\n '_transmission', 'Individual_Line_Flow' + fn_suffix + '_seasonal.csv')\n", (64993, 65130), False, 'import os\n'), ((66351, 66369), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (66367, 66369), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((72682, 72700), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (72698, 72700), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((72905, 72974), 'marmot.plottingmodules.plotutils.plot_library.PlotLibrary', 'PlotLibrary', (['nrows', 'ncols'], {'sharey': '(True)', 'squeeze': '(False)', 'ravel_axs': '(True)'}), '(nrows, ncols, sharey=True, squeeze=False, ravel_axs=True)\n', (72916, 72974), False, 'from marmot.plottingmodules.plotutils.plot_library import PlotLibrary\n'), ((73070, 73113), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.6)', 'hspace': '(0.3)'}), '(wspace=0.6, hspace=0.3)\n', (73089, 73113), True, 'import matplotlib.pyplot as plt\n'), ((78074, 78145), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['timezone'], {'color': '"""black"""', 'rotation': '"""horizontal"""', 'labelpad': '(30)'}), "(timezone, color='black', rotation='horizontal', labelpad=30)\n", (78084, 78145), True, 'import matplotlib.pyplot as plt\n'), ((78160, 78271), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['f"""Net Interchange ({unitconversion[\'units\']})"""'], {'color': '"""black"""', 'rotation': '"""vertical"""', 'labelpad': '(40)'}), '(f"Net Interchange ({unitconversion[\'units\']})", color=\'black\',\n rotation=\'vertical\', labelpad=40)\n', (78170, 78271), True, 'import matplotlib.pyplot as plt\n'), ((78941, 78989), 'pandas.concat', 'pd.concat', (['data_table_chunks'], {'copy': '(False)', 'axis': '(0)'}), '(data_table_chunks, copy=False, axis=0)\n', (78950, 78989), True, 'import pandas as pd\n'), ((80223, 80241), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (80239, 80241), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((82213, 82230), 'matplotlib.pyplot.cm.get_cmap', 'plt.cm.get_cmap', ([], {}), '()\n', (82228, 82230), True, 'import matplotlib.pyplot as plt\n'), ((83518, 83557), 'matplotlib.cm.ScalarMappable', 'cm.ScalarMappable', ([], {'norm': 'norm', 'cmap': 'cmap'}), '(norm=norm, cmap=cmap)\n', (83535, 83557), True, 'import matplotlib.cm as cm\n'), ((83978, 84038), 'os.path.join', 'os.path.join', (['save_figures', '"""region_region_checkerboard.svg"""'], {}), "(save_figures, 'region_region_checkerboard.svg')\n", (83990, 84038), False, 'import os\n'), ((84122, 84182), 'os.path.join', 'os.path.join', (['save_figures', '"""region_region_checkerboard.csv"""'], {}), "(save_figures, 'region_region_checkerboard.csv')\n", (84134, 84182), False, 'import os\n'), ((86833, 86851), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (86849, 86851), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((86972, 86986), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (86984, 86986), True, 'import pandas as pd\n'), ((88710, 88723), 'marmot.plottingmodules.plotutils.plot_library.PlotLibrary', 'PlotLibrary', ([], {}), '()\n', (88721, 88723), False, 'from marmot.plottingmodules.plotutils.plot_library import PlotLibrary\n'), ((89508, 89546), 'marmot.config.mconfig.parser', 'mconfig.parser', (['"""plot_title_as_region"""'], {}), "('plot_title_as_region')\n", (89522, 89546), True, 'import marmot.config.mconfig as mconfig\n'), ((91237, 91255), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (91253, 91255), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((91418, 91432), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (91430, 91432), True, 'import pandas as pd\n'), ((92927, 92940), 'marmot.plottingmodules.plotutils.plot_library.PlotLibrary', 'PlotLibrary', ([], {}), '()\n', (92938, 92940), False, 'from marmot.plottingmodules.plotutils.plot_library import PlotLibrary\n'), ((92993, 93037), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.05)', 'hspace': '(0.2)'}), '(wspace=0.05, hspace=0.2)\n', (93012, 93037), True, 'import matplotlib.pyplot as plt\n'), ((93825, 93863), 'marmot.config.mconfig.parser', 'mconfig.parser', (['"""plot_title_as_region"""'], {}), "('plot_title_as_region')\n", (93839, 93863), True, 'import marmot.config.mconfig as mconfig\n'), ((95263, 95287), 'marmot.plottingmodules.plotutils.plot_exceptions.UnsupportedAggregation', 'UnsupportedAggregation', ([], {}), '()\n', (95285, 95287), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((95972, 95990), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (95988, 95990), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((96440, 96509), 'marmot.plottingmodules.plotutils.plot_library.PlotLibrary', 'PlotLibrary', (['nrows', 'ncols'], {'sharey': '(True)', 'squeeze': '(False)', 'ravel_axs': '(True)'}), '(nrows, ncols, sharey=True, squeeze=False, ravel_axs=True)\n', (96451, 96509), False, 'from marmot.plottingmodules.plotutils.plot_library import PlotLibrary\n'), ((96594, 96637), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.1)', 'hspace': '(0.5)'}), '(wspace=0.1, hspace=0.5)\n', (96613, 96637), True, 'import matplotlib.pyplot as plt\n'), ((101642, 101680), 'marmot.config.mconfig.parser', 'mconfig.parser', (['"""plot_title_as_region"""'], {}), "('plot_title_as_region')\n", (101656, 101680), True, 'import marmot.config.mconfig as mconfig\n'), ((101742, 101848), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['f"""Net export ({unitconversion[\'units\']})"""'], {'color': '"""black"""', 'rotation': '"""vertical"""', 'labelpad': '(40)'}), '(f"Net export ({unitconversion[\'units\']})", color=\'black\',\n rotation=\'vertical\', labelpad=40)\n', (101752, 101848), True, 'import matplotlib.pyplot as plt\n'), ((102024, 102050), 'pandas.concat', 'pd.concat', (['net_exports_all'], {}), '(net_exports_all)\n', (102033, 102050), True, 'import pandas as pd\n'), ((103068, 103092), 'marmot.plottingmodules.plotutils.plot_exceptions.UnsupportedAggregation', 'UnsupportedAggregation', ([], {}), '()\n', (103090, 103092), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((103657, 103675), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (103673, 103675), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((103832, 103845), 'marmot.plottingmodules.plotutils.plot_library.PlotLibrary', 'PlotLibrary', ([], {}), '()\n', (103843, 103845), False, 'from marmot.plottingmodules.plotutils.plot_library import PlotLibrary\n'), ((103898, 103942), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.05)', 'hspace': '(0.2)'}), '(wspace=0.05, hspace=0.2)\n', (103917, 103942), True, 'import matplotlib.pyplot as plt\n'), ((107974, 107999), 'pandas.concat', 'pd.concat', (['data_out_chunk'], {}), '(data_out_chunk)\n', (107983, 107999), True, 'import pandas as pd\n'), ((108595, 108633), 'marmot.config.mconfig.parser', 'mconfig.parser', (['"""plot_title_as_region"""'], {}), "('plot_title_as_region')\n", (108609, 108633), True, 'import marmot.config.mconfig as mconfig\n'), ((110429, 110447), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (110445, 110447), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((110607, 110624), 'marmot.plottingmodules.plotutils.plot_exceptions.InputSheetError', 'InputSheetError', ([], {}), '()\n', (110622, 110624), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((111194, 111224), 'pandas.Series', 'pd.Series', ([], {'name': '"""Total Export"""'}), "(name='Total Export')\n", (111203, 111224), True, 'import pandas as pd\n'), ((111243, 111273), 'pandas.Series', 'pd.Series', ([], {'name': '"""Total Import"""'}), "(name='Total Import')\n", (111252, 111273), True, 'import pandas as pd\n'), ((112414, 112443), 'pandas.concat', 'pd.concat', (['[pos, neg]'], {'axis': '(1)'}), '([pos, neg], axis=1)\n', (112423, 112443), True, 'import pandas as pd\n'), ((113730, 113864), 'os.path.join', 'os.path.join', (['self.Marmot_Solutions_folder', '"""Figures_Output"""', 'f"""{self.AGG_BY}_transmission"""', '"""Individual_Interface_Total_Flow.svg"""'], {}), "(self.Marmot_Solutions_folder, 'Figures_Output',\n f'{self.AGG_BY}_transmission', 'Individual_Interface_Total_Flow.svg')\n", (113742, 113864), False, 'import os\n'), ((113976, 114110), 'os.path.join', 'os.path.join', (['self.Marmot_Solutions_folder', '"""Figures_Output"""', 'f"""{self.AGG_BY}_transmission"""', '"""Individual_Interface_Total_Flow.csv"""'], {}), "(self.Marmot_Solutions_folder, 'Figures_Output',\n f'{self.AGG_BY}_transmission', 'Individual_Interface_Total_Flow.csv')\n", (113988, 114110), False, 'import os\n'), ((7390, 7404), 'pandas.notna', 'pd.notna', (['prop'], {}), '(prop)\n', (7398, 7404), True, 'import pandas as pd\n'), ((9314, 9328), 'pandas.notna', 'pd.notna', (['prop'], {}), '(prop)\n', (9322, 9328), True, 'import pandas as pd\n'), ((9449, 9527), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Number of lines"""'], {'color': '"""black"""', 'rotation': '"""vertical"""', 'labelpad': '(30)'}), "('Number of lines', color='black', rotation='vertical', labelpad=30)\n", (9459, 9527), True, 'import matplotlib.pyplot as plt\n'), ((9573, 9673), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['f"""Line Utilization: {prop_name}"""'], {'color': '"""black"""', 'rotation': '"""horizontal"""', 'labelpad': '(30)'}), "(f'Line Utilization: {prop_name}', color='black', rotation=\n 'horizontal', labelpad=30)\n", (9583, 9673), True, 'import matplotlib.pyplot as plt\n'), ((9735, 9749), 'pandas.notna', 'pd.notna', (['prop'], {}), '(prop)\n', (9743, 9749), True, 'import pandas as pd\n'), ((9872, 9970), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['f"""Line Utilization: {prop_name}"""'], {'color': '"""black"""', 'rotation': '"""vertical"""', 'labelpad': '(60)'}), "(f'Line Utilization: {prop_name}', color='black', rotation=\n 'vertical', labelpad=60)\n", (9882, 9970), True, 'import matplotlib.pyplot as plt\n'), ((10010, 10084), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Intervals"""'], {'color': '"""black"""', 'rotation': '"""horizontal"""', 'labelpad': '(20)'}), "('Intervals', color='black', rotation='horizontal', labelpad=20)\n", (10020, 10084), True, 'import matplotlib.pyplot as plt\n'), ((21359, 21424), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Sorted hour of the year"""'], {'color': '"""black"""', 'labelpad': '(30)'}), "('Sorted hour of the year', color='black', labelpad=30)\n", (21369, 21424), True, 'import matplotlib.pyplot as plt\n'), ((27207, 27225), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (27223, 27225), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((28199, 28250), 'pandas.concat', 'pd.concat', (['[single_exp_lim, single_imp_lim]'], {'axis': '(1)'}), '([single_exp_lim, single_imp_lim], axis=1)\n', (28208, 28250), True, 'import pandas as pd\n'), ((30482, 30514), 'pandas.concat', 'pd.concat', (['chunks_interf'], {'axis': '(0)'}), '(chunks_interf, axis=0)\n', (30491, 30514), True, 'import pandas as pd\n'), ((31826, 31891), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Sorted hour of the year"""'], {'color': '"""black"""', 'labelpad': '(30)'}), "('Sorted hour of the year', color='black', labelpad=30)\n", (31836, 31891), True, 'import matplotlib.pyplot as plt\n'), ((42555, 42620), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Sorted hour of the year"""'], {'color': '"""black"""', 'labelpad': '(30)'}), "('Sorted hour of the year', color='black', labelpad=30)\n", (42565, 42620), True, 'import matplotlib.pyplot as plt\n'), ((47200, 47243), 'pandas.concat', 'pd.concat', (['[single_exp_lim, single_imp_lim]'], {}), '([single_exp_lim, single_imp_lim])\n', (47209, 47243), True, 'import pandas as pd\n'), ((47690, 47744), 'pandas.Series', 'pd.Series', (['[single_exp_lim, single_imp_lim]'], {'name': 'line'}), '([single_exp_lim, single_imp_lim], name=line)\n', (47699, 47744), True, 'import pandas as pd\n'), ((49841, 49871), 'pandas.concat', 'pd.concat', (['chunks_line'], {'axis': '(0)'}), '(chunks_line, axis=0)\n', (49850, 49871), True, 'import pandas as pd\n'), ((69483, 69622), 'os.path.join', 'os.path.join', (['self.Marmot_Solutions_folder', '"""NARIS"""', '"""Figures_Output"""', "(self.AGG_BY + '_transmission')", "('test_meta_' + scenario + '.csv')"], {}), "(self.Marmot_Solutions_folder, 'NARIS', 'Figures_Output', self.\n AGG_BY + '_transmission', 'test_meta_' + scenario + '.csv')\n", (69495, 69622), False, 'import os\n'), ((69679, 69753), 'pandas.merge', 'pd.merge', (['int_import_lim', 'int_export_lim'], {'how': '"""inner"""', 'on': '"""interface_name"""'}), "(int_import_lim, int_export_lim, how='inner', on='interface_name')\n", (69687, 69753), True, 'import pandas as pd\n'), ((78500, 78563), 'os.path.join', 'os.path.join', (['self.figure_folder', "(self.AGG_BY + '_transmission')"], {}), "(self.figure_folder, self.AGG_BY + '_transmission')\n", (78512, 78563), False, 'import os\n'), ((78866, 78885), 'marmot.plottingmodules.plotutils.plot_exceptions.DataSavedInModule', 'DataSavedInModule', ([], {}), '()\n', (78883, 78885), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((82347, 82377), 'numpy.arange', 'np.arange', (['rr_int_agg.shape[1]'], {}), '(rr_int_agg.shape[1])\n', (82356, 82377), True, 'import numpy as np\n'), ((82409, 82439), 'numpy.arange', 'np.arange', (['rr_int_agg.shape[0]'], {}), '(rr_int_agg.shape[0])\n', (82418, 82439), True, 'import numpy as np\n'), ((87930, 87974), 'pandas.concat', 'pd.concat', (['[all_scenarios, one_zone]'], {'axis': '(1)'}), '([all_scenarios, one_zone], axis=1)\n', (87939, 87974), True, 'import pandas as pd\n'), ((88278, 88295), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingZoneData', 'MissingZoneData', ([], {}), '()\n', (88293, 88295), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((91977, 92003), 'pandas.notna', 'pd.notna', (['start_date_range'], {}), '(start_date_range)\n', (91985, 92003), True, 'import pandas as pd\n'), ((92270, 92327), 'pandas.concat', 'pd.concat', (['[net_export_all_scenarios, net_export]'], {'axis': '(1)'}), '([net_export_all_scenarios, net_export], axis=1)\n', (92279, 92327), True, 'import pandas as pd\n'), ((93108, 93125), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingZoneData', 'MissingZoneData', ([], {}), '()\n', (93123, 93125), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((99761, 99791), 'pandas.concat', 'pd.concat', (['net_exports'], {'axis': '(1)'}), '(net_exports, axis=1)\n', (99770, 99791), True, 'import pandas as pd\n'), ((99896, 99929), 'pandas.to_datetime', 'pd.to_datetime', (['net_exports.index'], {}), '(net_exports.index)\n', (99910, 99929), True, 'import pandas as pd\n'), ((101916, 101981), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Sorted hour of the year"""'], {'color': '"""black"""', 'labelpad': '(30)'}), "('Sorted hour of the year', color='black', labelpad=30)\n", (101926, 101981), True, 'import matplotlib.pyplot as plt\n'), ((106789, 106819), 'pandas.concat', 'pd.concat', (['net_exports'], {'axis': '(1)'}), '(net_exports, axis=1)\n', (106798, 106819), True, 'import pandas as pd\n'), ((106921, 106954), 'pandas.to_datetime', 'pd.to_datetime', (['net_exports.index'], {}), '(net_exports.index)\n', (106935, 106954), True, 'import pandas as pd\n'), ((107182, 107221), 'pandas.concat', 'pd.concat', (['[positive, negative]'], {'axis': '(1)'}), '([positive, negative], axis=1)\n', (107191, 107221), True, 'import pandas as pd\n'), ((111886, 111912), 'pandas.notna', 'pd.notna', (['start_date_range'], {}), '(start_date_range)\n', (111894, 111912), True, 'import pandas as pd\n'), ((7625, 7690), 'pandas.merge', 'pd.merge', (['flow', 'line_relations'], {'left_index': '(True)', 'right_index': '(True)'}), '(flow, line_relations, left_index=True, right_index=True)\n', (7633, 7690), True, 'import pandas as pd\n'), ((17089, 17140), 'pandas.concat', 'pd.concat', (['[single_exp_lim, single_imp_lim]'], {'axis': '(1)'}), '([single_exp_lim, single_imp_lim], axis=1)\n', (17098, 17140), True, 'import pandas as pd\n'), ((19795, 19827), 'pandas.concat', 'pd.concat', (['chunks_interf'], {'axis': '(0)'}), '(chunks_interf, axis=0)\n', (19804, 19827), True, 'import pandas as pd\n'), ((20467, 20485), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (20483, 20485), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((30767, 30813), 'matplotlib.dates.AutoDateLocator', 'mdates.AutoDateLocator', ([], {'minticks': '(4)', 'maxticks': '(8)'}), '(minticks=4, maxticks=8)\n', (30789, 30813), True, 'import matplotlib.dates as mdates\n'), ((30846, 30882), 'matplotlib.dates.ConciseDateFormatter', 'mdates.ConciseDateFormatter', (['locator'], {}), '(locator)\n', (30873, 30882), True, 'import matplotlib.dates as mdates\n'), ((38474, 38525), 'pandas.concat', 'pd.concat', (['[single_exp_lim, single_imp_lim]'], {'axis': '(1)'}), '([single_exp_lim, single_imp_lim], axis=1)\n', (38483, 38525), True, 'import pandas as pd\n'), ((40887, 40919), 'pandas.concat', 'pd.concat', (['chunks_interf'], {'axis': '(0)'}), '(chunks_interf, axis=0)\n', (40896, 40919), True, 'import pandas as pd\n'), ((41716, 41734), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (41732, 41734), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((74919, 74975), 'marmot.plottingmodules.plotutils.plot_library.PlotLibrary', 'PlotLibrary', (['nrows', 'ncols'], {'squeeze': '(False)', 'ravel_axs': '(True)'}), '(nrows, ncols, squeeze=False, ravel_axs=True)\n', (74930, 74975), False, 'from marmot.plottingmodules.plotutils.plot_library import PlotLibrary\n'), ((75085, 75128), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.6)', 'hspace': '(0.7)'}), '(wspace=0.6, hspace=0.7)\n', (75104, 75128), True, 'import matplotlib.pyplot as plt\n'), ((81270, 81294), 'marmot.plottingmodules.plotutils.plot_exceptions.UnsupportedAggregation', 'UnsupportedAggregation', ([], {}), '()\n', (81292, 81294), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((82895, 82929), 'numpy.arange', 'np.arange', (['(rr_int_agg.shape[1] + 1)'], {}), '(rr_int_agg.shape[1] + 1)\n', (82904, 82929), True, 'import numpy as np\n'), ((82975, 83009), 'numpy.arange', 'np.arange', (['(rr_int_agg.shape[0] + 1)'], {}), '(rr_int_agg.shape[0] + 1)\n', (82984, 83009), True, 'import numpy as np\n'), ((96986, 97003), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingMetaData', 'MissingMetaData', ([], {}), '()\n', (97001, 97003), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((98081, 98154), 'pandas.merge', 'pd.merge', (['exp_oz', 'imp_other_oz'], {'left_on': '"""line_name"""', 'right_on': '"""line_name"""'}), "(exp_oz, imp_other_oz, left_on='line_name', right_on='line_name')\n", (98089, 98154), True, 'import pandas as pd\n'), ((98226, 98299), 'pandas.merge', 'pd.merge', (['imp_oz', 'exp_other_oz'], {'left_on': '"""line_name"""', 'right_on': '"""line_name"""'}), "(imp_oz, exp_other_oz, left_on='line_name', right_on='line_name')\n", (98234, 98299), True, 'import pandas as pd\n'), ((99230, 99256), 'pandas.notna', 'pd.notna', (['start_date_range'], {}), '(start_date_range)\n', (99238, 99256), True, 'import pandas as pd\n'), ((104337, 104354), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingMetaData', 'MissingMetaData', ([], {}), '()\n', (104352, 104354), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((105228, 105301), 'pandas.merge', 'pd.merge', (['exp_oz', 'imp_other_oz'], {'left_on': '"""line_name"""', 'right_on': '"""line_name"""'}), "(exp_oz, imp_other_oz, left_on='line_name', right_on='line_name')\n", (105236, 105301), True, 'import pandas as pd\n'), ((105374, 105447), 'pandas.merge', 'pd.merge', (['imp_oz', 'exp_other_oz'], {'left_on': '"""line_name"""', 'right_on': '"""line_name"""'}), "(imp_oz, exp_other_oz, left_on='line_name', right_on='line_name')\n", (105382, 105447), True, 'import pandas as pd\n'), ((106379, 106405), 'pandas.notna', 'pd.notna', (['start_date_range'], {}), '(start_date_range)\n', (106387, 106405), True, 'import pandas as pd\n'), ((6669, 6686), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingZoneData', 'MissingZoneData', ([], {}), '()\n', (6684, 6686), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((17932, 17958), 'pandas.notna', 'pd.notna', (['start_date_range'], {}), '(start_date_range)\n', (17940, 17958), True, 'import pandas as pd\n'), ((73637, 73651), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (73649, 73651), True, 'import pandas as pd\n'), ((74063, 74087), 'marmot.plottingmodules.plotutils.plot_exceptions.UnsupportedAggregation', 'UnsupportedAggregation', ([], {}), '()\n', (74085, 74087), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, DataSavedInModule, UnderDevelopment, InputSheetError, MissingMetaData, UnsupportedAggregation, MissingZoneData\n'), ((39306, 39332), 'pandas.isnull', 'pd.isnull', (['self.start_date'], {}), '(self.start_date)\n', (39315, 39332), True, 'import pandas as pd\n')]
import os import numpy as np import h5py import lsst.sims.photUtils as photUtils import GCRCatalogs from GCR import GCRQuery import time import argparse import multiprocessing def validate_chunk(data_in, in_dir, healpix, read_lock, write_lock, output_dict): galaxy_id = data_in['galaxy_id'] redshift = data_in['redshift'] mag_in = {} for bp in 'ugrizy': mag_in[bp] = data_in['mag_true_%s_lsst' % bp] eps = 1.0e-20 disk_to_bulge = {} for bp in 'ugrizy': disk_name = 'LSST_filters/diskLuminositiesStellar:' disk_name += 'LSST_%s:observed:dustAtlas' % bp bulge_name = 'LSST_filters/spheroidLuminositiesStellar:' bulge_name += 'LSST_%s:observed:dustAtlas' % bp denom = np.where(data_in[bulge_name]>0.0, data_in[bulge_name], eps) disk_to_bulge[bp] = data_in[disk_name]/denom assert np.isfinite(disk_to_bulge[bp]).sum()==len(disk_to_bulge[bp]) sed_dir = os.environ['SIMS_SED_LIBRARY_DIR'] tot_bp_dict = photUtils.BandpassDict.loadTotalBandpassesFromFiles() fit_file = os.path.join(in_dir, 'sed_fit_%d.h5' % healpix) assert os.path.isfile(fit_file) with read_lock: with h5py.File(fit_file, 'r') as in_file: sed_names = in_file['sed_names'][()] galaxy_id_fit = in_file['galaxy_id'][()] valid = np.in1d(galaxy_id_fit, galaxy_id) galaxy_id_fit = galaxy_id_fit[valid] np.testing.assert_array_equal(galaxy_id_fit, galaxy_id) disk_magnorm = in_file['disk_magnorm'][()][:,valid] disk_av = in_file['disk_av'][()][valid] disk_rv = in_file['disk_rv'][()][valid] disk_sed = in_file['disk_sed'][()][valid] bulge_magnorm = in_file['bulge_magnorm'][()][:,valid] bulge_av = in_file['bulge_av'][()][valid] bulge_rv = in_file['bulge_rv'][()][valid] bulge_sed = in_file['bulge_sed'][()][valid] sed_names = [name.decode() for name in sed_names] local_worst = {} local_worst_ratio = {} ccm_w = None dummy_sed = photUtils.Sed() for i_obj in range(len(disk_av)): for i_bp, bp in enumerate('ugrizy'): d_sed = photUtils.Sed() fname = os.path.join(sed_dir, sed_names[disk_sed[i_obj]]) d_sed.readSED_flambda(fname) fnorm = photUtils.getImsimFluxNorm(d_sed, disk_magnorm[i_bp][i_obj]) d_sed.multiplyFluxNorm(fnorm) if ccm_w is None or not np.array_equal(d_sed.wavelen, ccm_w): ccm_w = np.copy(d_sed.wavelen) ax, bx = d_sed.setupCCM_ab() d_sed.addDust(ax, bx, R_v=disk_rv[i_obj], A_v=disk_av[i_obj]) d_sed.redshiftSED(redshift[i_obj], dimming=True) d_flux = d_sed.calcFlux(tot_bp_dict[bp]) b_sed = photUtils.Sed() fname = os.path.join(sed_dir, sed_names[bulge_sed[i_obj]]) b_sed.readSED_flambda(fname) fnorm = photUtils.getImsimFluxNorm(b_sed, bulge_magnorm[i_bp][i_obj]) b_sed.multiplyFluxNorm(fnorm) if ccm_w is None or not np.array_equal(b_sed.wavelen, ccm_w): ccm_w = np.copy(b_sed.wavelen) ax, bx = b_sed.setupCCM_ab() b_sed.addDust(ax, bx, R_v=bulge_rv[i_obj], A_v=bulge_av[i_obj]) b_sed.redshiftSED(redshift[i_obj], dimming=True) b_flux = b_sed.calcFlux(tot_bp_dict[bp]) flux_ratio = d_flux/max(b_flux, eps) if flux_ratio<1.0e3 or disk_to_bulge[bp][i_obj]<1.0e3: delta_ratio = np.abs(flux_ratio-disk_to_bulge[bp][i_obj]) if disk_to_bulge[bp][i_obj]>eps: delta_ratio /= disk_to_bulge[bp][i_obj] if bp not in local_worst_ratio or delta_ratio>local_worst_ratio[bp]: local_worst_ratio[bp] = delta_ratio tot_flux = b_flux + d_flux true_flux = dummy_sed.fluxFromMag(mag_in[bp][i_obj]) delta_flux = np.abs(1.0-tot_flux/true_flux) if bp not in local_worst or delta_flux>local_worst[bp]: local_worst[bp] = delta_flux with write_lock: for bp in 'ugrizy': if bp not in output_dict or local_worst[bp]>output_dict[bp]: output_dict[bp] = local_worst[bp] ratio_name = '%s_ratio' % bp if (ratio_name not in output_dict or local_worst_ratio[bp]>output_dict[ratio_name]): output_dict[ratio_name] = local_worst_ratio[bp] if __name__ == "__main__": t_start = time.time() parser = argparse.ArgumentParser() parser.add_argument('--healpix', type=int, default=None) parser.add_argument('--in_dir', type=str, default=None) parser.add_argument('--seed', type=int, default=None) parser.add_argument('--nsamples', type=int, default=1000000) parser.add_argument('--n_threads', type=int, default=10) parser.add_argument('--d_gal', type=int, default=10000) args = parser.parse_args() if args.healpix is None: raise RuntimeError("must specify healpix") if args.in_dir is None or not os.path.isdir(args.in_dir): raise RuntimeError("invalid in_dir") if args.seed is None: raise RuntimeError("must specify seed") cache_dir = os.path.join(os.environ['HOME'],'workspace','sed_cache') photUtils.cache_LSST_seds(wavelen_min=0.0, wavelen_max=1500.0, cache_dir=cache_dir) mgr = multiprocessing.Manager() read_lock = mgr.Lock() write_lock = mgr.Lock() output_dict = mgr.dict() col_names = ['galaxy_id', 'redshift'] for bp in 'ugrizy': col_names.append('mag_true_%s_lsst' % bp) col_names.append('LSST_filters/diskLuminositiesStellar:' 'LSST_%s:observed:dustAtlas' % bp) col_names.append('LSST_filters/spheroidLuminositiesStellar:' 'LSST_%s:observed:dustAtlas' % bp) print('loading catalog') cat = GCRCatalogs.load_catalog('cosmoDC2_v1.1.4_image') h_query = GCRQuery('healpix_pixel==%d' % args.healpix) data = cat.get_quantities(col_names, native_filters=[h_query]) print('got catalog') if args.nsamples>0: rng = np.random.RandomState(args.seed) sub_dexes = rng.choice(np.arange(len(data['galaxy_id']), dtype=int), size=args.nsamples, replace=False) for k in data.keys(): data[k] = data[k][sub_dexes] sorted_dex = np.argsort(data['galaxy_id']) for k in data.keys(): data[k] = data[k][sorted_dex] print('n galaxies %e' % len(data['galaxy_id'])) p_list = [] ct = 0 for i_start in range(0,len(data['galaxy_id']), args.d_gal): sub_sample = slice(i_start, i_start+args.d_gal) sub_data = {} for k in data: sub_data[k] = data[k][sub_sample] p = multiprocessing.Process(target=validate_chunk, args=(sub_data, args.in_dir, args.healpix, read_lock, write_lock, output_dict)) p.start() p_list.append(p) while len(p_list)>=args.n_threads: exit_list = [] for p in p_list: exit_list.append(p.exitcode) was_popped = False for ii in range(len(p_list)-1,-1,-1): if exit_list[ii] is not None: p_list.pop(ii) ct += args.d_gal was_popped = True #if was_popped: # duration = (time.time()-t_start)/3600.0 # per = duration/ct # pred = len(data['galaxy_id'])*per # print('checked %d in %.2e; pred %.2e' % (ct, duration, pred)) for p in p_list: p.join() for bp in output_dict.keys(): print('hp %d %s %e' % (args.healpix, bp, output_dict[bp])) print('hp %d that took %.2e hrs' % (args.healpix, (time.time()-t_start)/3600.0))
[ "numpy.abs", "argparse.ArgumentParser", "numpy.argsort", "os.path.isfile", "os.path.join", "numpy.copy", "GCR.GCRQuery", "lsst.sims.photUtils.Sed", "numpy.isfinite", "numpy.random.RandomState", "h5py.File", "numpy.testing.assert_array_equal", "lsst.sims.photUtils.getImsimFluxNorm", "GCRCatalogs.load_catalog", "multiprocessing.Process", "os.path.isdir", "multiprocessing.Manager", "lsst.sims.photUtils.cache_LSST_seds", "time.time", "numpy.where", "numpy.array_equal", "lsst.sims.photUtils.BandpassDict.loadTotalBandpassesFromFiles", "numpy.in1d" ]
[((1044, 1097), 'lsst.sims.photUtils.BandpassDict.loadTotalBandpassesFromFiles', 'photUtils.BandpassDict.loadTotalBandpassesFromFiles', ([], {}), '()\n', (1095, 1097), True, 'import lsst.sims.photUtils as photUtils\n'), ((1114, 1161), 'os.path.join', 'os.path.join', (['in_dir', "('sed_fit_%d.h5' % healpix)"], {}), "(in_dir, 'sed_fit_%d.h5' % healpix)\n", (1126, 1161), False, 'import os\n'), ((1173, 1197), 'os.path.isfile', 'os.path.isfile', (['fit_file'], {}), '(fit_file)\n', (1187, 1197), False, 'import os\n'), ((2132, 2147), 'lsst.sims.photUtils.Sed', 'photUtils.Sed', ([], {}), '()\n', (2145, 2147), True, 'import lsst.sims.photUtils as photUtils\n'), ((4728, 4739), 'time.time', 'time.time', ([], {}), '()\n', (4737, 4739), False, 'import time\n'), ((4754, 4779), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (4777, 4779), False, 'import argparse\n'), ((5455, 5513), 'os.path.join', 'os.path.join', (["os.environ['HOME']", '"""workspace"""', '"""sed_cache"""'], {}), "(os.environ['HOME'], 'workspace', 'sed_cache')\n", (5467, 5513), False, 'import os\n'), ((5516, 5604), 'lsst.sims.photUtils.cache_LSST_seds', 'photUtils.cache_LSST_seds', ([], {'wavelen_min': '(0.0)', 'wavelen_max': '(1500.0)', 'cache_dir': 'cache_dir'}), '(wavelen_min=0.0, wavelen_max=1500.0, cache_dir=\n cache_dir)\n', (5541, 5604), True, 'import lsst.sims.photUtils as photUtils\n'), ((5641, 5666), 'multiprocessing.Manager', 'multiprocessing.Manager', ([], {}), '()\n', (5664, 5666), False, 'import multiprocessing\n'), ((6162, 6211), 'GCRCatalogs.load_catalog', 'GCRCatalogs.load_catalog', (['"""cosmoDC2_v1.1.4_image"""'], {}), "('cosmoDC2_v1.1.4_image')\n", (6186, 6211), False, 'import GCRCatalogs\n'), ((6226, 6270), 'GCR.GCRQuery', 'GCRQuery', (["('healpix_pixel==%d' % args.healpix)"], {}), "('healpix_pixel==%d' % args.healpix)\n", (6234, 6270), False, 'from GCR import GCRQuery\n'), ((786, 847), 'numpy.where', 'np.where', (['(data_in[bulge_name] > 0.0)', 'data_in[bulge_name]', 'eps'], {}), '(data_in[bulge_name] > 0.0, data_in[bulge_name], eps)\n', (794, 847), True, 'import numpy as np\n'), ((6432, 6464), 'numpy.random.RandomState', 'np.random.RandomState', (['args.seed'], {}), '(args.seed)\n', (6453, 6464), True, 'import numpy as np\n'), ((6731, 6760), 'numpy.argsort', 'np.argsort', (["data['galaxy_id']"], {}), "(data['galaxy_id'])\n", (6741, 6760), True, 'import numpy as np\n'), ((7139, 7269), 'multiprocessing.Process', 'multiprocessing.Process', ([], {'target': 'validate_chunk', 'args': '(sub_data, args.in_dir, args.healpix, read_lock, write_lock, output_dict)'}), '(target=validate_chunk, args=(sub_data, args.in_dir,\n args.healpix, read_lock, write_lock, output_dict))\n', (7162, 7269), False, 'import multiprocessing\n'), ((1231, 1255), 'h5py.File', 'h5py.File', (['fit_file', '"""r"""'], {}), "(fit_file, 'r')\n", (1240, 1255), False, 'import h5py\n'), ((1390, 1423), 'numpy.in1d', 'np.in1d', (['galaxy_id_fit', 'galaxy_id'], {}), '(galaxy_id_fit, galaxy_id)\n', (1397, 1423), True, 'import numpy as np\n'), ((1485, 1540), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['galaxy_id_fit', 'galaxy_id'], {}), '(galaxy_id_fit, galaxy_id)\n', (1514, 1540), True, 'import numpy as np\n'), ((2251, 2266), 'lsst.sims.photUtils.Sed', 'photUtils.Sed', ([], {}), '()\n', (2264, 2266), True, 'import lsst.sims.photUtils as photUtils\n'), ((2287, 2336), 'os.path.join', 'os.path.join', (['sed_dir', 'sed_names[disk_sed[i_obj]]'], {}), '(sed_dir, sed_names[disk_sed[i_obj]])\n', (2299, 2336), False, 'import os\n'), ((2398, 2458), 'lsst.sims.photUtils.getImsimFluxNorm', 'photUtils.getImsimFluxNorm', (['d_sed', 'disk_magnorm[i_bp][i_obj]'], {}), '(d_sed, disk_magnorm[i_bp][i_obj])\n', (2424, 2458), True, 'import lsst.sims.photUtils as photUtils\n'), ((2923, 2938), 'lsst.sims.photUtils.Sed', 'photUtils.Sed', ([], {}), '()\n', (2936, 2938), True, 'import lsst.sims.photUtils as photUtils\n'), ((2959, 3009), 'os.path.join', 'os.path.join', (['sed_dir', 'sed_names[bulge_sed[i_obj]]'], {}), '(sed_dir, sed_names[bulge_sed[i_obj]])\n', (2971, 3009), False, 'import os\n'), ((3071, 3132), 'lsst.sims.photUtils.getImsimFluxNorm', 'photUtils.getImsimFluxNorm', (['b_sed', 'bulge_magnorm[i_bp][i_obj]'], {}), '(b_sed, bulge_magnorm[i_bp][i_obj])\n', (3097, 3132), True, 'import lsst.sims.photUtils as photUtils\n'), ((4150, 4184), 'numpy.abs', 'np.abs', (['(1.0 - tot_flux / true_flux)'], {}), '(1.0 - tot_flux / true_flux)\n', (4156, 4184), True, 'import numpy as np\n'), ((5291, 5317), 'os.path.isdir', 'os.path.isdir', (['args.in_dir'], {}), '(args.in_dir)\n', (5304, 5317), False, 'import os\n'), ((2646, 2668), 'numpy.copy', 'np.copy', (['d_sed.wavelen'], {}), '(d_sed.wavelen)\n', (2653, 2668), True, 'import numpy as np\n'), ((3320, 3342), 'numpy.copy', 'np.copy', (['b_sed.wavelen'], {}), '(b_sed.wavelen)\n', (3327, 3342), True, 'import numpy as np\n'), ((3726, 3771), 'numpy.abs', 'np.abs', (['(flux_ratio - disk_to_bulge[bp][i_obj])'], {}), '(flux_ratio - disk_to_bulge[bp][i_obj])\n', (3732, 3771), True, 'import numpy as np\n'), ((914, 944), 'numpy.isfinite', 'np.isfinite', (['disk_to_bulge[bp]'], {}), '(disk_to_bulge[bp])\n', (925, 944), True, 'import numpy as np\n'), ((2584, 2620), 'numpy.array_equal', 'np.array_equal', (['d_sed.wavelen', 'ccm_w'], {}), '(d_sed.wavelen, ccm_w)\n', (2598, 2620), True, 'import numpy as np\n'), ((3258, 3294), 'numpy.array_equal', 'np.array_equal', (['b_sed.wavelen', 'ccm_w'], {}), '(b_sed.wavelen, ccm_w)\n', (3272, 3294), True, 'import numpy as np\n'), ((8267, 8278), 'time.time', 'time.time', ([], {}), '()\n', (8276, 8278), False, 'import time\n')]
import numpy as np def bb_iou(a, b): a_x_tl = a[2] a_y_tl = a[3] a_x_br = a[0] a_y_br = a[1] b_x_tl = b[2] b_y_tl = b[3] b_x_br = b[0] b_y_br = b[1] # a_x_tl = a[0]-a[2] # a_y_tl = a[1]-a[3] # a_x_br = a[0] # a_y_br = a[1] # # b_x_tl = b[0]-b[2] # b_y_tl = b[1]-b[3] # b_x_br = b[0] # b_y_br = b[1] x1 = max(a_x_tl, b_x_tl) y1 = max(a_y_tl, b_y_tl) x2 = min(a_x_br, b_x_br) y2 = min(a_y_br, b_y_br) w = x2 - x1 + 1 h = y2 - y1 + 1 # set invalid entries to 0 overlap if w <= 0 or h <= 0: o = 0 else: inter = w * h aarea = (a_x_br-a_x_tl+1)*(a_y_br-a_y_tl+1) barea = (b_x_br-b_x_tl+1)*(b_y_br-b_y_tl+1) # intersection over union overlap o = inter/ (aarea + barea - inter) return o def box_iou(gt_bboxes, pre_bboxes, pre_bb_images, thresh_iou=0.5): nrof_images = np.shape(gt_bboxes)[0] pre_bboxes_iou = [] pre_bboxes_confidence = [] pre_bboxes_label = [] gt_recall_bboxes_idx = [] pre_iou_images = [] for i in range(nrof_images): # print(i) # if i == 32599: # print("stop") gt_bb_per_image = gt_bboxes[i] pre_bb_per_image = pre_bboxes[i] nrof_gt_bboxes = len(gt_bb_per_image) nrof_pre_bboxes = len(pre_bb_per_image) for j in range(nrof_pre_bboxes): pre_bb = pre_bb_per_image[j] for k in range(nrof_gt_bboxes): gt_bb = gt_bb_per_image[k] pre_bb_iou=bb_iou(gt_bb, pre_bb) if pre_bb_iou > thresh_iou: label = 1 else: label = 0 pre_bboxes_iou.append(pre_bb_iou) pre_bboxes_confidence.append(pre_bb[4]) pre_bboxes_label.append(label) gt_recall_bboxes_idx.append([i,k]) pre_iou_images.append(pre_bb_images[i]) ### Normalisation the cofidence of the bounding boxes confi_max = max(pre_bboxes_confidence) confi_min = min(pre_bboxes_confidence) pre_bboxes_confidence_norm = [(x-confi_min)/(confi_max-confi_min) for x in pre_bboxes_confidence] return pre_bboxes_iou, pre_bboxes_confidence_norm, pre_bboxes_label, gt_recall_bboxes_idx, pre_iou_images def label_pre_bboxes(pre_bboxes_iou, thresh_iou=0.5): labels_pre_bboxes = [] for pre_bb_iou in pre_bboxes_iou: if pre_bb_iou[0]>thresh_iou: label = 1 else: label = 0 labels_pre_bboxes.append(label) return labels_pre_bboxes
[ "numpy.shape" ]
[((928, 947), 'numpy.shape', 'np.shape', (['gt_bboxes'], {}), '(gt_bboxes)\n', (936, 947), True, 'import numpy as np\n')]
import sys sys.path.append('..') import numpy as np import math from geneticalgorithm import geneticalgorithm as ga def f(X): dim = len(X) OF = 0 for i in range (0, dim): OF+=(X[i]**2)-10*math.cos(2*math.pi*X[i])+10 return OF def test_rastrigin(): parameters={'max_num_iteration': 1000, 'population_size':200, 'mutation_probability':0.1, 'elit_ratio': 0.02, 'crossover_probability': 0.5, 'parents_portion': 0.3, 'crossover_type':'two_point', 'max_iteration_without_improv':None, 'multiprocessing_ncpus': 4, 'multiprocessing_engine': None, } varbound = np.array([[-5.12, 5.12]]*2) model = ga(function=f, dimension=2, variable_type='real', variable_boundaries=varbound, algorithm_parameters=parameters) model.run() assert model.best_function < 1e-6 if __name__ == '__main__': test_rastrigin()
[ "sys.path.append", "numpy.array", "math.cos", "geneticalgorithm.geneticalgorithm" ]
[((11, 32), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (26, 32), False, 'import sys\n'), ((749, 778), 'numpy.array', 'np.array', (['([[-5.12, 5.12]] * 2)'], {}), '([[-5.12, 5.12]] * 2)\n', (757, 778), True, 'import numpy as np\n'), ((790, 907), 'geneticalgorithm.geneticalgorithm', 'ga', ([], {'function': 'f', 'dimension': '(2)', 'variable_type': '"""real"""', 'variable_boundaries': 'varbound', 'algorithm_parameters': 'parameters'}), "(function=f, dimension=2, variable_type='real', variable_boundaries=\n varbound, algorithm_parameters=parameters)\n", (792, 907), True, 'from geneticalgorithm import geneticalgorithm as ga\n'), ((211, 239), 'math.cos', 'math.cos', (['(2 * math.pi * X[i])'], {}), '(2 * math.pi * X[i])\n', (219, 239), False, 'import math\n')]
import numpy as np from glip.math import mat4 def test_is_similarity(): assert mat4.is_similarity(mat4.translate(4.0, 56.7, 2.3)) assert mat4.is_similarity(mat4.rotate_axis_angle(0, 1, 0, 0.453)) assert mat4.is_similarity(mat4.scale(1, -1, 1)) assert not mat4.is_similarity(mat4.scale(2, 1, 1)) assert not mat4.is_similarity(mat4.affine(A=np.random.randn(3, 3)))
[ "glip.math.mat4.translate", "numpy.random.randn", "glip.math.mat4.rotate_axis_angle", "glip.math.mat4.scale" ]
[((104, 134), 'glip.math.mat4.translate', 'mat4.translate', (['(4.0)', '(56.7)', '(2.3)'], {}), '(4.0, 56.7, 2.3)\n', (118, 134), False, 'from glip.math import mat4\n'), ((166, 204), 'glip.math.mat4.rotate_axis_angle', 'mat4.rotate_axis_angle', (['(0)', '(1)', '(0)', '(0.453)'], {}), '(0, 1, 0, 0.453)\n', (188, 204), False, 'from glip.math import mat4\n'), ((236, 256), 'glip.math.mat4.scale', 'mat4.scale', (['(1)', '(-1)', '(1)'], {}), '(1, -1, 1)\n', (246, 256), False, 'from glip.math import mat4\n'), ((293, 312), 'glip.math.mat4.scale', 'mat4.scale', (['(2)', '(1)', '(1)'], {}), '(2, 1, 1)\n', (303, 312), False, 'from glip.math import mat4\n'), ((362, 383), 'numpy.random.randn', 'np.random.randn', (['(3)', '(3)'], {}), '(3, 3)\n', (377, 383), True, 'import numpy as np\n')]
import numpy as np import copy import pickle # Data loading related def load_from_pickle(filename, n_jets): jets = [] fd = open(filename, "rb") for i in range(n_jets): jet = pickle.load(fd) jets.append(jet) fd.close() return jets # Jet related def _pt(v): pz = v[2] p = (v[0:3] ** 2).sum() ** 0.5 eta = 0.5 * (np.log(p + pz) - np.log(p - pz)) pt = p / np.cosh(eta) return pt def permute_by_pt(jet, root_id=None): # ensure that the left sub-jet has always a larger pt than the right if root_id is None: root_id = jet["root_id"] if jet["tree"][root_id][0] != -1: left = jet["tree"][root_id][0] right = jet["tree"][root_id][1] pt_left = _pt(jet["content"][left]) pt_right = _pt(jet["content"][right]) if pt_left < pt_right: jet["tree"][root_id][0] = right jet["tree"][root_id][1] = left permute_by_pt(jet, left) permute_by_pt(jet, right) return jet def rewrite_content(jet): jet = copy.deepcopy(jet) if jet["content"].shape[1] == 5: pflow = jet["content"][:, 4].copy() content = jet["content"] tree = jet["tree"] def _rec(i): if tree[i, 0] == -1: pass else: _rec(tree[i, 0]) _rec(tree[i, 1]) c = content[tree[i, 0]] + content[tree[i, 1]] content[i] = c _rec(jet["root_id"]) if jet["content"].shape[1] == 5: jet["content"][:, 4] = pflow return jet def extract(jet, pflow=False): # per node feature extraction jet = copy.deepcopy(jet) s = jet["content"].shape if not pflow: content = np.zeros((s[0], 7)) else: # pflow value will be one-hot encoded content = np.zeros((s[0], 7+4)) for i in range(len(jet["content"])): px = jet["content"][i, 0] py = jet["content"][i, 1] pz = jet["content"][i, 2] p = (jet["content"][i, 0:3] ** 2).sum() ** 0.5 eta = 0.5 * (np.log(p + pz) - np.log(p - pz)) theta = 2 * np.arctan(np.exp(-eta)) pt = p / np.cosh(eta) phi = np.arctan2(py, px) content[i, 0] = p content[i, 1] = eta if np.isfinite(eta) else 0.0 content[i, 2] = phi content[i, 3] = jet["content"][i, 3] content[i, 4] = (jet["content"][i, 3] / jet["content"][jet["root_id"], 3]) content[i, 5] = pt if np.isfinite(pt) else 0.0 content[i, 6] = theta if np.isfinite(theta) else 0.0 if pflow: if jet["content"][i, 4] >= 0: content[i, 7+int(jet["content"][i, 4])] = 1.0 jet["content"] = content return jet def randomize(jet): # build a random tree jet = copy.deepcopy(jet) leaves = np.where(jet["tree"][:, 0] == -1)[0] nodes = [n for n in leaves] content = [jet["content"][n] for n in nodes] nodes = [i for i in range(len(nodes))] tree = [[-1, -1] for n in nodes] pool = [n for n in nodes] next_id = len(nodes) while len(pool) >= 2: i = np.random.randint(len(pool)) left = pool[i] del pool[i] j = np.random.randint(len(pool)) right = pool[j] del pool[j] nodes.append(next_id) c = (content[left] + content[right]) if len(c) == 5: c[-1] = -1 content.append(c) tree.append([left, right]) pool.append(next_id) next_id += 1 jet["content"] = np.array(content) jet["tree"] = np.array(tree).astype(int) jet["root_id"] = len(jet["tree"]) - 1 return jet def sequentialize_by_pt(jet, reverse=False): # transform the tree into a sequence ordered by pt jet = copy.deepcopy(jet) leaves = np.where(jet["tree"][:, 0] == -1)[0] nodes = [n for n in leaves] content = [jet["content"][n] for n in nodes] nodes = [i for i in range(len(nodes))] tree = [[-1, -1] for n in nodes] pool = sorted([n for n in nodes], key=lambda n: _pt(content[n]), reverse=reverse) next_id = len(pool) while len(pool) >= 2: right = pool[-1] left = pool[-2] del pool[-1] del pool[-1] nodes.append(next_id) c = (content[left] + content[right]) if len(c) == 5: c[-1] = -1 content.append(c) tree.append([left, right]) pool.append(next_id) next_id += 1 jet["content"] = np.array(content) jet["tree"] = np.array(tree).astype(int) jet["root_id"] = len(jet["tree"]) - 1 return jet
[ "copy.deepcopy", "numpy.arctan2", "numpy.log", "numpy.zeros", "numpy.isfinite", "pickle.load", "numpy.array", "numpy.where", "numpy.exp", "numpy.cosh" ]
[((1061, 1079), 'copy.deepcopy', 'copy.deepcopy', (['jet'], {}), '(jet)\n', (1074, 1079), False, 'import copy\n'), ((1631, 1649), 'copy.deepcopy', 'copy.deepcopy', (['jet'], {}), '(jet)\n', (1644, 1649), False, 'import copy\n'), ((2803, 2821), 'copy.deepcopy', 'copy.deepcopy', (['jet'], {}), '(jet)\n', (2816, 2821), False, 'import copy\n'), ((3543, 3560), 'numpy.array', 'np.array', (['content'], {}), '(content)\n', (3551, 3560), True, 'import numpy as np\n'), ((3777, 3795), 'copy.deepcopy', 'copy.deepcopy', (['jet'], {}), '(jet)\n', (3790, 3795), False, 'import copy\n'), ((4530, 4547), 'numpy.array', 'np.array', (['content'], {}), '(content)\n', (4538, 4547), True, 'import numpy as np\n'), ((198, 213), 'pickle.load', 'pickle.load', (['fd'], {}), '(fd)\n', (209, 213), False, 'import pickle\n'), ((413, 425), 'numpy.cosh', 'np.cosh', (['eta'], {}), '(eta)\n', (420, 425), True, 'import numpy as np\n'), ((1717, 1736), 'numpy.zeros', 'np.zeros', (['(s[0], 7)'], {}), '((s[0], 7))\n', (1725, 1736), True, 'import numpy as np\n'), ((1811, 1834), 'numpy.zeros', 'np.zeros', (['(s[0], 7 + 4)'], {}), '((s[0], 7 + 4))\n', (1819, 1834), True, 'import numpy as np\n'), ((2175, 2193), 'numpy.arctan2', 'np.arctan2', (['py', 'px'], {}), '(py, px)\n', (2185, 2193), True, 'import numpy as np\n'), ((2836, 2869), 'numpy.where', 'np.where', (["(jet['tree'][:, 0] == -1)"], {}), "(jet['tree'][:, 0] == -1)\n", (2844, 2869), True, 'import numpy as np\n'), ((3810, 3843), 'numpy.where', 'np.where', (["(jet['tree'][:, 0] == -1)"], {}), "(jet['tree'][:, 0] == -1)\n", (3818, 3843), True, 'import numpy as np\n'), ((367, 381), 'numpy.log', 'np.log', (['(p + pz)'], {}), '(p + pz)\n', (373, 381), True, 'import numpy as np\n'), ((384, 398), 'numpy.log', 'np.log', (['(p - pz)'], {}), '(p - pz)\n', (390, 398), True, 'import numpy as np\n'), ((2148, 2160), 'numpy.cosh', 'np.cosh', (['eta'], {}), '(eta)\n', (2155, 2160), True, 'import numpy as np\n'), ((2252, 2268), 'numpy.isfinite', 'np.isfinite', (['eta'], {}), '(eta)\n', (2263, 2268), True, 'import numpy as np\n'), ((2489, 2504), 'numpy.isfinite', 'np.isfinite', (['pt'], {}), '(pt)\n', (2500, 2504), True, 'import numpy as np\n'), ((2547, 2565), 'numpy.isfinite', 'np.isfinite', (['theta'], {}), '(theta)\n', (2558, 2565), True, 'import numpy as np\n'), ((3579, 3593), 'numpy.array', 'np.array', (['tree'], {}), '(tree)\n', (3587, 3593), True, 'import numpy as np\n'), ((4566, 4580), 'numpy.array', 'np.array', (['tree'], {}), '(tree)\n', (4574, 4580), True, 'import numpy as np\n'), ((2054, 2068), 'numpy.log', 'np.log', (['(p + pz)'], {}), '(p + pz)\n', (2060, 2068), True, 'import numpy as np\n'), ((2071, 2085), 'numpy.log', 'np.log', (['(p - pz)'], {}), '(p - pz)\n', (2077, 2085), True, 'import numpy as np\n'), ((2117, 2129), 'numpy.exp', 'np.exp', (['(-eta)'], {}), '(-eta)\n', (2123, 2129), True, 'import numpy as np\n')]
import sklearn import numpy as np import sklearn.datasets as skdata from matplotlib import pyplot as plt boston_housing_data = skdata.load_boston() print(boston_housing_data) x = boston_housing_data.data feat_names = boston_housing_data.feature_names print(feat_names) #print(boston_housing_data.DESCR) y = boston_housing_data.target #print(y[0],y[0, :]) crime_rate = x[:, 0] fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.scatter(crime_rate, y) #plt.show() ''' fig.suptitle('Boston Housing Data') ax = fig.add_subplot(1, 1, 1) ax.set_ylabel('Housing Price') ax.set_xlabel('Crime Rate ({})'.format(feat_names[0])) ax.scatter(crime_rate, y) #plt.show() ''' ''' ax1 = fig.add_subplot(2, 1, 1) ax1.set_title("Per Capita Crime rate") ax1.set_ylabel('Housing Price') ax1.set_xlabel('Crime Rate ({})'.format(feat_names[0])) ax.scatter(crime_rate, y) nitric_oxide = x[:, 4] ax2 = fig.add_subplot(2, 1, 2) ax2.set_title("Nitric Oxide Concentration (PP 10M)") ax2.set_ylabel('Housing Price') ax2.set_xlabel('Nitric Oxide ({})'.format(feat_names[4])) ax2.scatter(nitric_oxide, y) plt.show() ''' ''' #VISUALIZING DATA PAGE 1 fig = plt.figure() fig.suptitle('Boston Housing Data') ax1 = fig.add_subplot(2, 1, 1) ax1.set_title("Per Capita Crime Rate") ax1.set_ylabel('Housing Price') ax1.set_xlabel('Crime Rate ({})'.format(feat_names[0])) ax1.scatter(crime_rate,y) ''' nitric_oxide = x[:, 4] ax2 = fig.add_subplot(2, 1, 2) ax2.set_title("Nitric Oxide Concentration (PP 10M") ax2.set_ylabel('Housing Price') ax2.set_xlabel('Nitric Oxide ({})'.format(feat_names[4])) ax2.scatter(nitric_oxide, y) #plt.show() ''' #VISUALIZING DATA PAGE 2 fig = plt.figure() fig.suptitle('Boston Housing Data') ax = fig.add_subplot(1, 1, 1) ax.set_ylabel('Housing Price') ax.set_xlabel('Features') ''' observations = (crime_rate, nitric_oxide) targets = (y, y,) colors = ("blue", "red") # Crime rate will be blue and nitric oxide will be red labels = (feat_names[0], feat_names[4]) markers =('o', '^') for obs, tgt, col, lab, m in zip(observations, targets, colors, labels, markers): ax.scatter(obs, tgt, c=col, label=lab, marker=m) ax.legend(loc='upper right') #plt.show() def min_max_norm(x): return (x-np.min(x))/(np.max(x)-np.min(x)) crime_rate_minmax = min_max_norm(crime_rate) nitric_oxide_minmax = min_max_norm(nitric_oxide) print(np.min(crime_rate_minmax), np.max(crime_rate_minmax)) print(np.min(nitric_oxide_minmax), np.max(nitric_oxide_minmax)) #MIN-MAX NORMALIZATION fig = plt.figure() fig.suptitle('Boston Housing Data') ax = fig.add_subplot(1, 1, 1) ax.set_ylabel('Housing Price') ax.set_xlabel('Min-Max Norm Features') observations_minmax = (crime_rate_minmax, nitric_oxide_minmax) for obs, tgt, col, lab, m in zip(observations, targets, colors, labels, markers): ax.scatter(obs, tgt, c=col, label=lab, marker=m) ax.legend(loc='upper right') plt.show()
[ "matplotlib.pyplot.show", "sklearn.datasets.load_boston", "matplotlib.pyplot.figure", "numpy.max", "numpy.min" ]
[((128, 148), 'sklearn.datasets.load_boston', 'skdata.load_boston', ([], {}), '()\n', (146, 148), True, 'import sklearn.datasets as skdata\n'), ((390, 402), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (400, 402), True, 'from matplotlib import pyplot as plt\n'), ((2491, 2503), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2501, 2503), True, 'from matplotlib import pyplot as plt\n'), ((2872, 2882), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2880, 2882), True, 'from matplotlib import pyplot as plt\n'), ((2341, 2366), 'numpy.min', 'np.min', (['crime_rate_minmax'], {}), '(crime_rate_minmax)\n', (2347, 2366), True, 'import numpy as np\n'), ((2368, 2393), 'numpy.max', 'np.max', (['crime_rate_minmax'], {}), '(crime_rate_minmax)\n', (2374, 2393), True, 'import numpy as np\n'), ((2401, 2428), 'numpy.min', 'np.min', (['nitric_oxide_minmax'], {}), '(nitric_oxide_minmax)\n', (2407, 2428), True, 'import numpy as np\n'), ((2430, 2457), 'numpy.max', 'np.max', (['nitric_oxide_minmax'], {}), '(nitric_oxide_minmax)\n', (2436, 2457), True, 'import numpy as np\n'), ((2208, 2217), 'numpy.min', 'np.min', (['x'], {}), '(x)\n', (2214, 2217), True, 'import numpy as np\n'), ((2220, 2229), 'numpy.max', 'np.max', (['x'], {}), '(x)\n', (2226, 2229), True, 'import numpy as np\n'), ((2230, 2239), 'numpy.min', 'np.min', (['x'], {}), '(x)\n', (2236, 2239), True, 'import numpy as np\n')]
import pandas as pd import numpy as np import sklearn import warnings import sys # sys.path.append('Feature Comparison/Basic.py') from sklearn.naive_bayes import GaussianNB from sklearn.naive_bayes import MultinomialNB from sklearn.svm import SVC from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import cross_val_score from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline Basic_Feature_path = 'Feature Comparison/Basic_FeatureSet.npy' Botnet_Feature_path = 'Feature Comparison/Botnet_FeatureSet.npy' Blacklist_Feature_path = 'Feature Comparison/Blacklist_FeatureSet.npy' Whois_Feature_path = 'Feature Comparison/Whois_FeatureSet.npy' Hostbased_Feature_path = 'Feature Comparison/Host_based_FeatureSet.npy' Lexical_Feature_path = 'Feature Comparison/Lexical_FeatureSet.npy' Full_ex_wb_path = 'Feature Comparison/Full_except_WB.npy' warnings.filterwarnings("ignore", category=FutureWarning, module="sklearn", lineno=196) warnings.filterwarnings("ignore", category=FutureWarning, module="sklearn", lineno=433) warnings.filterwarnings("ignore", category=RuntimeWarning, module="sklearn", lineno=436) warnings.filterwarnings("ignore", category=RuntimeWarning, module="sklearn", lineno=438) pd.set_option('display.max_columns', 10000) pd.set_option('display.max_rows', 10000) pd.set_option('display.max_colwidth', 10000) pd.set_option('display.width',1000) blacklist_path = 'Data/url_blacklists.txt' dataset_path = 'Data/train_dataset.csv' ### Read the training Dataset file df = pd.read_csv(dataset_path, header=0) label = df['Lable'].values # print(label.shape) # (7000,) # print(df.head(20)) ### Read the blackurls blacklist = [] with open(blacklist_path,'r') as f: for i in f.readlines(): blacklist.append(i) # print('len(blacklist) = ',len(blacklist)) ### Feature Selection ## 1. Basic Feature set Basic_Feature = np.load(Basic_Feature_path).astype(int) df_Basic = pd.DataFrame(data=Basic_Feature, columns=['Total dot','Is IP in hostname','Creation date','Is Creation date']) # print('### Basic Feature Set ###') # print(df_Basic.head(10)) # print('\n') ## 2. Botnet Feature set Botnet_Feature = np.load(Botnet_Feature_path).astype(int) df_Botnet = pd.DataFrame(data=Botnet_Feature, columns=['Is client','is server','Is IP in hostname','Is PTR','Is PTR resolved']) # print('### Botnet Feature Set ###') # print(df_Botnet.head(10)) # print('\n') ## 3. Blacklist Feature set Blacklist_Feature = np.load(Blacklist_Feature_path).astype(int).reshape(7000,1) df_Blacklist = pd.DataFrame(data=Blacklist_Feature, columns=['Is in blacklist']) # print('### Blacklist Feature Set ###') # print(df_Blacklist.head(10)) # print('\n') ## 4. Whois Feature set Whois_Feature = np.load(Whois_Feature_path).astype(int) df_Whois = pd.DataFrame(data=Whois_Feature, columns=['Creation date','Last updated','Expiration date','Is registarar','Is registrant']) # print('### Whois Feature Set ###') # print(df_Whois.head(10)) # print('\n') ## 5. Host-based Feature set Hostbased_Feature = np.load(Hostbased_Feature_path).astype(int) df_Hostbased = pd.DataFrame(data=Hostbased_Feature, columns=['Is in blacklist','Creation date','Last updated','Expiration date','Is registarar','Is registrant','Is client','is server','Is IP in hostname','Is PTR','Is PTR resolved','Is DNS record','TTL record']) # print(df_Hostbased.columns) # print('### Hostbased Feature Set ###') # print(df_Hostbased.head(10)) # print('\n') ## 6. Lexical Feature set Lexical_Feature = np.load(Lexical_Feature_path).astype(int) df_Lexical = pd.DataFrame(data=Lexical_Feature, columns=['Total delims','Total hyphens','URL len','Dot num','Host token','Path_token']) # print(df_Lexical.head(10)) ## 7. Lexical + Host-based Feature set Full_Feature = np.hstack((Lexical_Feature,Hostbased_Feature)).astype(int) df_Full = pd.DataFrame(data=Full_Feature, columns=['Total delims','Total hyphens','URL len','Dot num','Host token','Path_token','Is in blacklist','Creation date','Last updated','Expiration date','Is registarar','Is registrant','Is client','is server','Is IP in hostname','Is PTR','Is PTR resolved','Is DNS record','TTL record']) print(len(df_Full.columns)) # 19 # print(df_Full.head(10)) ## 8. Full except Whois + Blacklist Feature set Full_ex_wb = np.load(Full_ex_wb_path).astype(int) df_Full_except = pd.DataFrame(data=Full_ex_wb, columns=['Total delims','Total hyphens','URL len','Dot num','Host token','Path_token','Is client','is server','Is IP in hostname','Is PTR','Is PTR resolved','Is DNS record','TTL record']) # print(df_Full_except.head(10)) print(len(df_Full_except.columns)) ## 9. Blacklist+Botnet Feature set Blk_Bot_Feature = np.hstack((Blacklist_Feature,Botnet_Feature)).astype(int) df_Blk_Bot = pd.DataFrame(data=Blk_Bot_Feature, columns=['Is in blacklist','Is client','is server','Is IP in hostname','Is PTR','Is PTR resolved']) # print(df_Blk_Bot.head(10)) def Classification_Process(Featureset,label): ## 1. [0-1] Normalization scaler = MinMaxScaler() ## 2. Split training and testing dataset X_train, X_test, y_train, y_test = train_test_split(Featureset.astype(float), label, test_size=0.2, random_state=123) X_train = scaler.fit_transform(X_train) X_test = scaler.fit_transform(X_test) ## 3. Algorithm G_NB = GaussianNB() M_NB = MultinomialNB() linear_svm = SVC(kernel='linear') rbf_svm = SVC(kernel='rbf') LR = LogisticRegression(penalty='l1') ## 4. Cross validation print('####### Cross validation #######') print('G_NB cross value: ', cross_val_score(G_NB, X_train, y_train, cv=5, scoring='accuracy').mean()) print('M_NB cross value: ', cross_val_score(M_NB, X_train, y_train, cv=5, scoring='accuracy').mean()) print('linear svm cross value: ', cross_val_score(linear_svm, X_train, y_train, cv=5, scoring='accuracy').mean()) print('rbf svm cross value: ', cross_val_score(rbf_svm, X_train, y_train, cv=5, scoring='accuracy').mean()) print('LR cross value: ', cross_val_score(LR, X_train, y_train, cv=5, scoring='accuracy').mean()) print('\n') ## 5. Prediction y_pred_gnb = G_NB.fit(X_train, y_train).predict(X_test) y_pred_mnb = M_NB.fit(X_train, y_train).predict(X_test) y_pred_l_svm = linear_svm.fit(X_train, y_train).predict(X_test) y_pred_r_svm = rbf_svm.fit(X_train, y_train).predict(X_test) y_pred_lr = LR.fit(X_train, y_train).predict(X_test) print('######### Prediction ###########') print('Gaussian Naive Bayes prediction: ', accuracy_score(y_test, y_pred_gnb)) print('Multinomial Naive Bayes prediction: ', accuracy_score(y_test, y_pred_mnb)) print('Linear SVM prediction: ', accuracy_score(y_test, y_pred_l_svm)) print('RBF SVM prediction: ', accuracy_score(y_test, y_pred_r_svm)) print('L1-Logistic Regression prediction: ', accuracy_score(y_test, y_pred_lr)) return 0 ############ Classification ########### print('##### 1. Basic Feature Classification Results #####') Classification_Process(Basic_Feature,label) print('\n') print('##### 2. Botnet Feature Set Classification Results #####') Classification_Process(Botnet_Feature,label) print('\n') print('##### 3. Blacklist Feature Set Classification Results ######') Classification_Process(Blacklist_Feature,label) print('\n') print('##### 4. Blacklist+Botnet Feature Set Classification Results ######') Classification_Process(Blk_Bot_Feature,label) print('\n') print('##### 5. Whois Feature Set Classification Results ######') Classification_Process(Whois_Feature,label) print('\n') print('##### 6. Host-based Feature Set Classification Results #####') Classification_Process(Hostbased_Feature,label) print('\n') print('##### 7. Lexica Feature Set Classification Results #####') Classification_Process(Lexical_Feature,label) print('\n') print('##### 8. Full(Lexica + Host-based) Feature Set Classification Results #####') Classification_Process(Full_Feature,label) print('\n') print('##### 9. Full except Whois+Blacklist Feature Set Classification Results #####') Classification_Process(Full_ex_wb,label) print('\n')
[ "pandas.DataFrame", "sklearn.naive_bayes.GaussianNB", "numpy.load", "sklearn.naive_bayes.MultinomialNB", "warnings.filterwarnings", "pandas.read_csv", "sklearn.model_selection.cross_val_score", "sklearn.metrics.accuracy_score", "sklearn.preprocessing.MinMaxScaler", "numpy.hstack", "sklearn.linear_model.LogisticRegression", "sklearn.svm.SVC", "pandas.set_option" ]
[((1042, 1133), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'FutureWarning', 'module': '"""sklearn"""', 'lineno': '(196)'}), "('ignore', category=FutureWarning, module='sklearn',\n lineno=196)\n", (1065, 1133), False, 'import warnings\n'), ((1130, 1221), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'FutureWarning', 'module': '"""sklearn"""', 'lineno': '(433)'}), "('ignore', category=FutureWarning, module='sklearn',\n lineno=433)\n", (1153, 1221), False, 'import warnings\n'), ((1218, 1310), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'RuntimeWarning', 'module': '"""sklearn"""', 'lineno': '(436)'}), "('ignore', category=RuntimeWarning, module='sklearn',\n lineno=436)\n", (1241, 1310), False, 'import warnings\n'), ((1307, 1399), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'RuntimeWarning', 'module': '"""sklearn"""', 'lineno': '(438)'}), "('ignore', category=RuntimeWarning, module='sklearn',\n lineno=438)\n", (1330, 1399), False, 'import warnings\n'), ((1398, 1441), 'pandas.set_option', 'pd.set_option', (['"""display.max_columns"""', '(10000)'], {}), "('display.max_columns', 10000)\n", (1411, 1441), True, 'import pandas as pd\n'), ((1442, 1482), 'pandas.set_option', 'pd.set_option', (['"""display.max_rows"""', '(10000)'], {}), "('display.max_rows', 10000)\n", (1455, 1482), True, 'import pandas as pd\n'), ((1483, 1527), 'pandas.set_option', 'pd.set_option', (['"""display.max_colwidth"""', '(10000)'], {}), "('display.max_colwidth', 10000)\n", (1496, 1527), True, 'import pandas as pd\n'), ((1528, 1564), 'pandas.set_option', 'pd.set_option', (['"""display.width"""', '(1000)'], {}), "('display.width', 1000)\n", (1541, 1564), True, 'import pandas as pd\n'), ((1691, 1726), 'pandas.read_csv', 'pd.read_csv', (['dataset_path'], {'header': '(0)'}), '(dataset_path, header=0)\n', (1702, 1726), True, 'import pandas as pd\n'), ((2100, 2217), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'Basic_Feature', 'columns': "['Total dot', 'Is IP in hostname', 'Creation date', 'Is Creation date']"}), "(data=Basic_Feature, columns=['Total dot', 'Is IP in hostname',\n 'Creation date', 'Is Creation date'])\n", (2112, 2217), True, 'import pandas as pd\n'), ((2385, 2508), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'Botnet_Feature', 'columns': "['Is client', 'is server', 'Is IP in hostname', 'Is PTR', 'Is PTR resolved']"}), "(data=Botnet_Feature, columns=['Is client', 'is server',\n 'Is IP in hostname', 'Is PTR', 'Is PTR resolved'])\n", (2397, 2508), True, 'import pandas as pd\n'), ((2705, 2770), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'Blacklist_Feature', 'columns': "['Is in blacklist']"}), "(data=Blacklist_Feature, columns=['Is in blacklist'])\n", (2717, 2770), True, 'import pandas as pd\n'), ((2949, 3081), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'Whois_Feature', 'columns': "['Creation date', 'Last updated', 'Expiration date', 'Is registarar',\n 'Is registrant']"}), "(data=Whois_Feature, columns=['Creation date', 'Last updated',\n 'Expiration date', 'Is registarar', 'Is registrant'])\n", (2961, 3081), True, 'import pandas as pd\n'), ((3261, 3531), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'Hostbased_Feature', 'columns': "['Is in blacklist', 'Creation date', 'Last updated', 'Expiration date',\n 'Is registarar', 'Is registrant', 'Is client', 'is server',\n 'Is IP in hostname', 'Is PTR', 'Is PTR resolved', 'Is DNS record',\n 'TTL record']"}), "(data=Hostbased_Feature, columns=['Is in blacklist',\n 'Creation date', 'Last updated', 'Expiration date', 'Is registarar',\n 'Is registrant', 'Is client', 'is server', 'Is IP in hostname',\n 'Is PTR', 'Is PTR resolved', 'Is DNS record', 'TTL record'])\n", (3273, 3531), True, 'import pandas as pd\n'), ((3724, 3855), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'Lexical_Feature', 'columns': "['Total delims', 'Total hyphens', 'URL len', 'Dot num', 'Host token',\n 'Path_token']"}), "(data=Lexical_Feature, columns=['Total delims', 'Total hyphens',\n 'URL len', 'Dot num', 'Host token', 'Path_token'])\n", (3736, 3855), True, 'import pandas as pd\n'), ((4000, 4352), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'Full_Feature', 'columns': "['Total delims', 'Total hyphens', 'URL len', 'Dot num', 'Host token',\n 'Path_token', 'Is in blacklist', 'Creation date', 'Last updated',\n 'Expiration date', 'Is registarar', 'Is registrant', 'Is client',\n 'is server', 'Is IP in hostname', 'Is PTR', 'Is PTR resolved',\n 'Is DNS record', 'TTL record']"}), "(data=Full_Feature, columns=['Total delims', 'Total hyphens',\n 'URL len', 'Dot num', 'Host token', 'Path_token', 'Is in blacklist',\n 'Creation date', 'Last updated', 'Expiration date', 'Is registarar',\n 'Is registrant', 'Is client', 'is server', 'Is IP in hostname',\n 'Is PTR', 'Is PTR resolved', 'Is DNS record', 'TTL record'])\n", (4012, 4352), True, 'import pandas as pd\n'), ((4494, 4735), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'Full_ex_wb', 'columns': "['Total delims', 'Total hyphens', 'URL len', 'Dot num', 'Host token',\n 'Path_token', 'Is client', 'is server', 'Is IP in hostname', 'Is PTR',\n 'Is PTR resolved', 'Is DNS record', 'TTL record']"}), "(data=Full_ex_wb, columns=['Total delims', 'Total hyphens',\n 'URL len', 'Dot num', 'Host token', 'Path_token', 'Is client',\n 'is server', 'Is IP in hostname', 'Is PTR', 'Is PTR resolved',\n 'Is DNS record', 'TTL record'])\n", (4506, 4735), True, 'import pandas as pd\n'), ((4905, 5048), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'Blk_Bot_Feature', 'columns': "['Is in blacklist', 'Is client', 'is server', 'Is IP in hostname', 'Is PTR',\n 'Is PTR resolved']"}), "(data=Blk_Bot_Feature, columns=['Is in blacklist', 'Is client',\n 'is server', 'Is IP in hostname', 'Is PTR', 'Is PTR resolved'])\n", (4917, 5048), True, 'import pandas as pd\n'), ((5162, 5176), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), '()\n', (5174, 5176), False, 'from sklearn.preprocessing import MinMaxScaler\n'), ((5463, 5475), 'sklearn.naive_bayes.GaussianNB', 'GaussianNB', ([], {}), '()\n', (5473, 5475), False, 'from sklearn.naive_bayes import GaussianNB\n'), ((5487, 5502), 'sklearn.naive_bayes.MultinomialNB', 'MultinomialNB', ([], {}), '()\n', (5500, 5502), False, 'from sklearn.naive_bayes import MultinomialNB\n'), ((5520, 5540), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""linear"""'}), "(kernel='linear')\n", (5523, 5540), False, 'from sklearn.svm import SVC\n'), ((5555, 5572), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""rbf"""'}), "(kernel='rbf')\n", (5558, 5572), False, 'from sklearn.svm import SVC\n'), ((5582, 5614), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'penalty': '"""l1"""'}), "(penalty='l1')\n", (5600, 5614), False, 'from sklearn.linear_model import LogisticRegression\n'), ((2049, 2076), 'numpy.load', 'np.load', (['Basic_Feature_path'], {}), '(Basic_Feature_path)\n', (2056, 2076), True, 'import numpy as np\n'), ((2332, 2360), 'numpy.load', 'np.load', (['Botnet_Feature_path'], {}), '(Botnet_Feature_path)\n', (2339, 2360), True, 'import numpy as np\n'), ((2898, 2925), 'numpy.load', 'np.load', (['Whois_Feature_path'], {}), '(Whois_Feature_path)\n', (2905, 2925), True, 'import numpy as np\n'), ((3202, 3233), 'numpy.load', 'np.load', (['Hostbased_Feature_path'], {}), '(Hostbased_Feature_path)\n', (3209, 3233), True, 'import numpy as np\n'), ((3669, 3698), 'numpy.load', 'np.load', (['Lexical_Feature_path'], {}), '(Lexical_Feature_path)\n', (3676, 3698), True, 'import numpy as np\n'), ((3931, 3978), 'numpy.hstack', 'np.hstack', (['(Lexical_Feature, Hostbased_Feature)'], {}), '((Lexical_Feature, Hostbased_Feature))\n', (3940, 3978), True, 'import numpy as np\n'), ((4440, 4464), 'numpy.load', 'np.load', (['Full_ex_wb_path'], {}), '(Full_ex_wb_path)\n', (4447, 4464), True, 'import numpy as np\n'), ((4834, 4880), 'numpy.hstack', 'np.hstack', (['(Blacklist_Feature, Botnet_Feature)'], {}), '((Blacklist_Feature, Botnet_Feature))\n', (4843, 4880), True, 'import numpy as np\n'), ((6675, 6709), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_test', 'y_pred_gnb'], {}), '(y_test, y_pred_gnb)\n', (6689, 6709), False, 'from sklearn.metrics import accuracy_score\n'), ((6761, 6795), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_test', 'y_pred_mnb'], {}), '(y_test, y_pred_mnb)\n', (6775, 6795), False, 'from sklearn.metrics import accuracy_score\n'), ((6834, 6870), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_test', 'y_pred_l_svm'], {}), '(y_test, y_pred_l_svm)\n', (6848, 6870), False, 'from sklearn.metrics import accuracy_score\n'), ((6906, 6942), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_test', 'y_pred_r_svm'], {}), '(y_test, y_pred_r_svm)\n', (6920, 6942), False, 'from sklearn.metrics import accuracy_score\n'), ((6993, 7026), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_test', 'y_pred_lr'], {}), '(y_test, y_pred_lr)\n', (7007, 7026), False, 'from sklearn.metrics import accuracy_score\n'), ((2630, 2661), 'numpy.load', 'np.load', (['Blacklist_Feature_path'], {}), '(Blacklist_Feature_path)\n', (2637, 2661), True, 'import numpy as np\n'), ((5721, 5786), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['G_NB', 'X_train', 'y_train'], {'cv': '(5)', 'scoring': '"""accuracy"""'}), "(G_NB, X_train, y_train, cv=5, scoring='accuracy')\n", (5736, 5786), False, 'from sklearn.model_selection import cross_val_score\n'), ((5827, 5892), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['M_NB', 'X_train', 'y_train'], {'cv': '(5)', 'scoring': '"""accuracy"""'}), "(M_NB, X_train, y_train, cv=5, scoring='accuracy')\n", (5842, 5892), False, 'from sklearn.model_selection import cross_val_score\n'), ((5939, 6010), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['linear_svm', 'X_train', 'y_train'], {'cv': '(5)', 'scoring': '"""accuracy"""'}), "(linear_svm, X_train, y_train, cv=5, scoring='accuracy')\n", (5954, 6010), False, 'from sklearn.model_selection import cross_val_score\n'), ((6054, 6122), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['rbf_svm', 'X_train', 'y_train'], {'cv': '(5)', 'scoring': '"""accuracy"""'}), "(rbf_svm, X_train, y_train, cv=5, scoring='accuracy')\n", (6069, 6122), False, 'from sklearn.model_selection import cross_val_score\n'), ((6161, 6224), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['LR', 'X_train', 'y_train'], {'cv': '(5)', 'scoring': '"""accuracy"""'}), "(LR, X_train, y_train, cv=5, scoring='accuracy')\n", (6176, 6224), False, 'from sklearn.model_selection import cross_val_score\n')]
from pylightnix import ( RRef, Build, rref2path, rref2dref, match_some, realizeMany, match_latest, store_buildtime, store_buildelta, store_context, BuildArgs, mkdrv, build_wrapper, match_only, build_setoutpaths, readjson ) from stagedml.stages.all import * from stagedml.stages.bert_finetune_glue import ( Model as BertClsModel, build as bert_finetune_build ) from stagedml.types import ( Dict, Union, Optional, List, Any ) from stagedml.core import ( protocol_rref_metric ) from stagedml.imports.sys import ( read_csv, OrderedDict, DataFrame, makedirs, json_dump, environ, contextmanager) from stagedml.imports.tf import ( FullTokenizer, MakeNdarray, ScalarEvent, TensorEvent, Features, Feature, Example, Dataset ) from stagedml.utils.tf import ( tensorboard_tags, tensorboard_tensors, te2float ) from official.nlp.bert.classifier_data_lib import ( InputExample, InputFeatures, convert_single_example ) from altair import Chart from altair_saver import save as altair_save import numpy as np import tensorflow as tf @contextmanager def prepare_markdown_image(image_filename:str, alt:str='', attrs:str=''): genimgdir=environ['REPOUT'] repimgdir=environ.get('REPIMG',genimgdir) makedirs(genimgdir, exist_ok=True) yield join(genimgdir,image_filename) print("![%s](%s){%s}"%(alt, join(repimgdir,image_filename), attrs)) def altair_print(chart:Chart, png_filename:str, alt:str='', attrs:str='')->None: with prepare_markdown_image(png_filename, alt, attrs) as path: altair_save(chart, path) class Runner: def __init__(self, rref:RRef): self.rref=rref self.tokenizer=FullTokenizer( vocab_file=mklens(rref).tfrecs.bert_vocab.syspath, do_lower_case=mklens(rref).tfrecs.lower_case.val) self.max_seq_length=mklens(rref).max_seq_length.val self.model=BertClsModel( BuildArgs(rref2dref(rref), store_context(rref), None, {}, {})) bert_finetune_build(self.model) self.model.model.load_weights(mklens(rref).checkpoint_full.syspath) def eval(self, sentences:List[str], batch_size:int=10)->List[List[float]]: @tf.function def _tf_step(inputs): return self.model.model_eval(inputs, training=False) def _step(inputs:List[Tuple[Any,Any,Any]]): return _tf_step((tf.constant([i[0] for i in inputs], dtype=tf.int64), tf.constant([i[1] for i in inputs], dtype=tf.int64), tf.constant([i[2] for i in inputs], dtype=tf.int64)))\ .numpy().tolist() buf=[] outs:List[List[float]]=[] for i,s in enumerate(sentences): ie=InputExample(guid=f"eval_{i:04d}", text_a=s, label='dummy') f=convert_single_example( 10, ie, ['dummy'], self.max_seq_length, self.tokenizer) buf.append((f.input_ids, f.input_mask, f.segment_ids)) if len(buf)>=batch_size: outs.extend(_step(buf)) buf=[] outs.extend(_step(buf)) return outs # runner ends learning_rates=[2e-5, 5e-5, 1e-4] def all_multibert_finetune_rusentiment1(m:Manager, lr:Optional[float]=None): lr_ = lr if lr is not None else learning_rates[0] def _nc(c): mklens(c).name.val='rusent-pretrained' mklens(c).train_batch_size.val=8 mklens(c).train_epoches.val=5 mklens(c).lr.val=lr_ return redefine(all_multibert_finetune_rusentiment, new_config=_nc)(m) # end1 def all_multibert_finetune_rusentiment0(m:Manager): def _nc(c): mklens(c).name.val='rusent-random' mklens(c).bert_ckpt_in.val=None return redefine(all_multibert_finetune_rusentiment1, new_config=_nc)(m) #end0 def bert_rusentiment_evaluation(m:Manager, stage:Stage)->DRef: def _realize(b:Build): build_setoutpaths(b,1) r=Runner(mklens(b).model.rref) df=read_csv(mklens(b).model.tfrecs.refdataset.output_tests.syspath) labels=sorted(df['label'].value_counts().keys()) df['pred']=[labels[np.argmax(probs)] for probs in r.eval(list(df['text']))] confusion={l:{l2:0.0 for l2 in labels} for l in labels} for i,row in df.iterrows(): confusion[row['label']][row['pred']]+=1.0 confusion={l:{l2:i/sum(items.values()) for l2,i in items.items()} \ for l,items in confusion.items()} with open(mklens(b).confusion_matrix.syspath,'w') as f: json_dump(confusion,f,indent=4) df.to_csv(mklens(b).prediction.syspath) return mkdrv(m, matcher=match_only(), realizer=build_wrapper(_realize), config=mkconfig({ 'name':'confusion_matrix', 'model':stage(m), 'confusion_matrix':[promise, 'confusion_matrix.json'], 'prediction':[promise, 'prediction.csv'], 'version':2, })) # eval ends if __name__== '__main__': for lr in learning_rates: print(realize(instantiate(all_multibert_finetune_rusentiment1, lr=lr))) print(realize(instantiate(all_multibert_finetune_rusentiment0))) stage=partial(all_multibert_finetune_rusentiment1, lr=min(learning_rates)) print(realize(instantiate(bert_rusentiment_evaluation, stage)))
[ "stagedml.imports.sys.environ.get", "official.nlp.bert.classifier_data_lib.convert_single_example", "numpy.argmax", "official.nlp.bert.classifier_data_lib.InputExample", "pylightnix.store_context", "tensorflow.constant", "pylightnix.build_wrapper", "stagedml.imports.sys.json_dump", "stagedml.stages.bert_finetune_glue.build", "pylightnix.build_setoutpaths", "pylightnix.match_only", "altair_saver.save", "pylightnix.rref2dref", "stagedml.imports.sys.makedirs" ]
[((1178, 1210), 'stagedml.imports.sys.environ.get', 'environ.get', (['"""REPIMG"""', 'genimgdir'], {}), "('REPIMG', genimgdir)\n", (1189, 1210), False, 'from stagedml.imports.sys import read_csv, OrderedDict, DataFrame, makedirs, json_dump, environ, contextmanager\n'), ((1212, 1246), 'stagedml.imports.sys.makedirs', 'makedirs', (['genimgdir'], {'exist_ok': '(True)'}), '(genimgdir, exist_ok=True)\n', (1220, 1246), False, 'from stagedml.imports.sys import read_csv, OrderedDict, DataFrame, makedirs, json_dump, environ, contextmanager\n'), ((1508, 1532), 'altair_saver.save', 'altair_save', (['chart', 'path'], {}), '(chart, path)\n', (1519, 1532), True, 'from altair_saver import save as altair_save\n'), ((1905, 1936), 'stagedml.stages.bert_finetune_glue.build', 'bert_finetune_build', (['self.model'], {}), '(self.model)\n', (1924, 1936), True, 'from stagedml.stages.bert_finetune_glue import Model as BertClsModel, build as bert_finetune_build\n'), ((3661, 3684), 'pylightnix.build_setoutpaths', 'build_setoutpaths', (['b', '(1)'], {}), '(b, 1)\n', (3678, 3684), False, 'from pylightnix import RRef, Build, rref2path, rref2dref, match_some, realizeMany, match_latest, store_buildtime, store_buildelta, store_context, BuildArgs, mkdrv, build_wrapper, match_only, build_setoutpaths, readjson\n'), ((2588, 2647), 'official.nlp.bert.classifier_data_lib.InputExample', 'InputExample', ([], {'guid': 'f"""eval_{i:04d}"""', 'text_a': 's', 'label': '"""dummy"""'}), "(guid=f'eval_{i:04d}', text_a=s, label='dummy')\n", (2600, 2647), False, 'from official.nlp.bert.classifier_data_lib import InputExample, InputFeatures, convert_single_example\n'), ((2656, 2734), 'official.nlp.bert.classifier_data_lib.convert_single_example', 'convert_single_example', (['(10)', 'ie', "['dummy']", 'self.max_seq_length', 'self.tokenizer'], {}), "(10, ie, ['dummy'], self.max_seq_length, self.tokenizer)\n", (2678, 2734), False, 'from official.nlp.bert.classifier_data_lib import InputExample, InputFeatures, convert_single_example\n'), ((4251, 4284), 'stagedml.imports.sys.json_dump', 'json_dump', (['confusion', 'f'], {'indent': '(4)'}), '(confusion, f, indent=4)\n', (4260, 4284), False, 'from stagedml.imports.sys import read_csv, OrderedDict, DataFrame, makedirs, json_dump, environ, contextmanager\n'), ((4354, 4366), 'pylightnix.match_only', 'match_only', ([], {}), '()\n', (4364, 4366), False, 'from pylightnix import RRef, Build, rref2path, rref2dref, match_some, realizeMany, match_latest, store_buildtime, store_buildelta, store_context, BuildArgs, mkdrv, build_wrapper, match_only, build_setoutpaths, readjson\n'), ((4377, 4400), 'pylightnix.build_wrapper', 'build_wrapper', (['_realize'], {}), '(_realize)\n', (4390, 4400), False, 'from pylightnix import RRef, Build, rref2path, rref2dref, match_some, realizeMany, match_latest, store_buildtime, store_buildelta, store_context, BuildArgs, mkdrv, build_wrapper, match_only, build_setoutpaths, readjson\n'), ((1848, 1863), 'pylightnix.rref2dref', 'rref2dref', (['rref'], {}), '(rref)\n', (1857, 1863), False, 'from pylightnix import RRef, Build, rref2path, rref2dref, match_some, realizeMany, match_latest, store_buildtime, store_buildelta, store_context, BuildArgs, mkdrv, build_wrapper, match_only, build_setoutpaths, readjson\n'), ((1865, 1884), 'pylightnix.store_context', 'store_context', (['rref'], {}), '(rref)\n', (1878, 1884), False, 'from pylightnix import RRef, Build, rref2path, rref2dref, match_some, realizeMany, match_latest, store_buildtime, store_buildelta, store_context, BuildArgs, mkdrv, build_wrapper, match_only, build_setoutpaths, readjson\n'), ((3867, 3883), 'numpy.argmax', 'np.argmax', (['probs'], {}), '(probs)\n', (3876, 3883), True, 'import numpy as np\n'), ((2262, 2313), 'tensorflow.constant', 'tf.constant', (['[i[0] for i in inputs]'], {'dtype': 'tf.int64'}), '([i[0] for i in inputs], dtype=tf.int64)\n', (2273, 2313), True, 'import tensorflow as tf\n'), ((2338, 2389), 'tensorflow.constant', 'tf.constant', (['[i[1] for i in inputs]'], {'dtype': 'tf.int64'}), '([i[1] for i in inputs], dtype=tf.int64)\n', (2349, 2389), True, 'import tensorflow as tf\n'), ((2414, 2465), 'tensorflow.constant', 'tf.constant', (['[i[2] for i in inputs]'], {'dtype': 'tf.int64'}), '([i[2] for i in inputs], dtype=tf.int64)\n', (2425, 2465), True, 'import tensorflow as tf\n')]
from kepler import * import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import streamlit as st import streamlit.components.v1 as components test = keplerCalc() el = test.ellipse() x = el[0] y = el[1] def update_line(i, x,y ,line): ax.patches = [] x = x[i] y = y[i] circle = plt.Circle(([x], [y]),(1/23454.8)*100,color = 'red') l = ax.add_patch(circle) #line.center(x,y) return l, fig = plt.figure() ax = fig.subplots() # Fixing random state for reproducibility #np.random.seed(19680801) #data = keplerCalc() data = np.random.rand(2,25) circle = plt.Circle(([1], [0]),(1/23454.8)*100,color = 'red') l = ax.add_patch(circle) plt.xlim(-2, 2) plt.ylim(-2, 2) plt.xlabel('x') plt.title('test') line_ani = animation.FuncAnimation(fig, update_line, 100, fargs=(x,y, l), interval=50, blit=True) st.title("Embed Matplotlib animation in Streamlit") #st.markdown("https://matplotlib.org/gallery/animation/basic_example.html") components.html(line_ani.to_jshtml(), height=1000)
[ "matplotlib.pyplot.title", "matplotlib.pyplot.xlim", "matplotlib.pyplot.ylim", "streamlit.title", "matplotlib.animation.FuncAnimation", "matplotlib.pyplot.figure", "matplotlib.pyplot.Circle", "numpy.random.rand", "matplotlib.pyplot.xlabel" ]
[((456, 468), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (466, 468), True, 'import matplotlib.pyplot as plt\n'), ((586, 607), 'numpy.random.rand', 'np.random.rand', (['(2)', '(25)'], {}), '(2, 25)\n', (600, 607), True, 'import numpy as np\n'), ((616, 670), 'matplotlib.pyplot.Circle', 'plt.Circle', (['([1], [0])', '(1 / 23454.8 * 100)'], {'color': '"""red"""'}), "(([1], [0]), 1 / 23454.8 * 100, color='red')\n", (626, 670), True, 'import matplotlib.pyplot as plt\n'), ((694, 709), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-2)', '(2)'], {}), '(-2, 2)\n', (702, 709), True, 'import matplotlib.pyplot as plt\n'), ((710, 725), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-2)', '(2)'], {}), '(-2, 2)\n', (718, 725), True, 'import matplotlib.pyplot as plt\n'), ((726, 741), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""x"""'], {}), "('x')\n", (736, 741), True, 'import matplotlib.pyplot as plt\n'), ((742, 759), 'matplotlib.pyplot.title', 'plt.title', (['"""test"""'], {}), "('test')\n", (751, 759), True, 'import matplotlib.pyplot as plt\n'), ((771, 862), 'matplotlib.animation.FuncAnimation', 'animation.FuncAnimation', (['fig', 'update_line', '(100)'], {'fargs': '(x, y, l)', 'interval': '(50)', 'blit': '(True)'}), '(fig, update_line, 100, fargs=(x, y, l), interval=50,\n blit=True)\n', (794, 862), True, 'import matplotlib.animation as animation\n'), ((859, 910), 'streamlit.title', 'st.title', (['"""Embed Matplotlib animation in Streamlit"""'], {}), "('Embed Matplotlib animation in Streamlit')\n", (867, 910), True, 'import streamlit as st\n'), ((331, 385), 'matplotlib.pyplot.Circle', 'plt.Circle', (['([x], [y])', '(1 / 23454.8 * 100)'], {'color': '"""red"""'}), "(([x], [y]), 1 / 23454.8 * 100, color='red')\n", (341, 385), True, 'import matplotlib.pyplot as plt\n')]
from __future__ import annotations import numpy as np import pandas as pd from sklearn import datasets from IMLearn.metrics import mean_square_error from IMLearn.utils import split_train_test from IMLearn.model_selection import cross_validate from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, RidgeRegression from sklearn.linear_model import Lasso from utils import * import plotly.graph_objects as go from plotly.subplots import make_subplots def select_polynomial_degree(n_samples: int = 100, noise: float = 5): """ Simulate data from a polynomial model and use cross-validation to select the best fitting degree Parameters ---------- n_samples: int, default=100 Number of samples to generate noise: float, default = 5 Noise level to simulate in responses """ # Question 1 - Generate dataset for model f(x)=(x+3)(x+2)(x+1)(x-1)(x-2) + eps for eps Gaussian noise # and split into training- and testing portions f_true = lambda x: (x+3)*(x+2)*(x+1)*(x-1)*(x-2) def epsilon(x): if type(x) == np.number: return np.random.normal(0, noise) return np.random.normal(0, noise, x.shape) f = lambda x: (f_true(x) + epsilon(x)) X = pd.DataFrame({"x": np.random.uniform(-1.2, 2, n_samples)}) y = f(X)["x"] y.name = "y" train_X, train_y, test_X, test_y = split_train_test(X, y, train_proportion=(2/3)) fig = go.Figure() sorted_x = X["x"].sort_values() fig.add_traces([ go.Scatter(x=sorted_x, y=f_true(sorted_x), name="True values", line=dict(color='black', width=1.5)), go.Scatter(x=train_X, y=train_y, name="Train set", mode='markers', marker=dict(color='royalblue', symbol="x")), go.Scatter(x=test_X, y=test_y, name="Test set", mode='markers', marker=dict(color='firebrick', symbol="circle")), ]) fig.update_layout(title=f"Train and test sets compared to true Model. {n_samples} samples with noise {noise}", xaxis_title="x", yaxis_title="y") fig.show() # Question 2 - Perform CV for polynomial fitting with degrees 0,1,...,10 loss_by_degree_train = [] loss_by_degree_validation = [] for k in range(11): estimator = PolynomialFitting(k) t, v = cross_validate(estimator, train_X, train_y, mean_square_error, 5) loss_by_degree_train.append(t) loss_by_degree_validation.append(v) fig = go.Figure() fig.add_traces([ go.Scatter(x=np.arange(11), y=loss_by_degree_train, name="Train error", mode='lines+markers', marker=dict(color='royalblue', symbol="x"), line=dict(color='royalblue', width=1.5)), go.Scatter(x=np.arange(11), y=loss_by_degree_validation, name="Validation error", mode='lines+markers', marker=dict(color='firebrick', symbol="circle"), line=dict(color='firebrick', width=1.5)) ]) fig.update_layout(title=f"Calculated loss from 5-fold cross validation on train set. {n_samples} samples with noise {noise}", xaxis_title="Polynomial degree", yaxis_title="Loss") fig.show() # Question 3 - Using best value of k, fit a k-degree polynomial model and report test error k_star = np.argmin(loss_by_degree_validation) estimator = PolynomialFitting(k_star) estimator.fit(train_X, train_y) print(f" {n_samples} samples with noise {noise}:") print("Optimal polynomial degree: %d" % k_star) print("Mean validation error: %.2f" % loss_by_degree_validation[k_star]) print("Test error: %.2f" % estimator.loss(test_X, test_y)) def select_regularization_parameter(n_samples: int = 50, n_evaluations: int = 500): """ Using sklearn's diabetes dataset use cross-validation to select the best fitting regularization parameter values for Ridge and Lasso regressions Parameters ---------- n_samples: int, default=50 Number of samples to generate n_evaluations: int, default = 500 Number of regularization parameter values to evaluate for each of the algorithms """ # Question 6 - Load diabetes dataset and split into training and testing portions X, y = datasets.load_diabetes(return_X_y=True) train_X = X[:n_samples] test_X = X[n_samples:] train_y = y[:n_samples] test_y = y[n_samples:] # Question 7 - Perform CV for different values of the regularization parameter for Ridge and Lasso regressions lambdas = np.linspace(0.01, 2.5, n_evaluations) best_lamda = {} for name, model in zip(["ridge", "lasso"], [RidgeRegression, Lasso]): loss_by_lambda_train = [] loss_by_lambda_validation = [] for lam in lambdas: estimator = model(lam) t, v = cross_validate(estimator, train_X, train_y, mean_square_error, 5) loss_by_lambda_train.append(t) loss_by_lambda_validation.append(v) best_lamda[name] = lambdas[np.argmin(loss_by_lambda_validation)] fig = go.Figure() fig.add_traces([ go.Scatter(x=lambdas, y=loss_by_lambda_train, name="Train error", mode='markers', marker=dict(color='royalblue', symbol="x")), go.Scatter(x=lambdas, y=loss_by_lambda_validation, name="Validation error", mode='markers', marker=dict(color='firebrick', symbol="circle")) ]) fig.update_layout(title=f"Loss from 5-fold cross validation on {name} regression model", xaxis_title="Lambda", yaxis_title="Loss") fig.show() # Question 8 - Compare best Ridge model, best Lasso model and Least Squares model for m, l in best_lamda.items(): print(f"Best lambda for {m} is: {l}") ridge = RidgeRegression(best_lamda["ridge"]) lasso = Lasso(best_lamda["lasso"]) least_squares = LinearRegression() ridge.fit(train_X, train_y) lasso.fit(train_X, train_y) least_squares.fit(train_X, train_y) for name, model in zip(["ridge", "lasso", "least squares"], [ridge, lasso, least_squares]): print(f"Test loss for {name} is: {mean_square_error(test_y, model.predict(test_X))}") if __name__ == '__main__': np.random.seed(0) select_polynomial_degree() select_polynomial_degree(100, 0) select_polynomial_degree(1500, 10) select_regularization_parameter()
[ "numpy.random.uniform", "numpy.random.seed", "IMLearn.learners.regressors.RidgeRegression", "plotly.graph_objects.Figure", "sklearn.datasets.load_diabetes", "numpy.argmin", "IMLearn.learners.regressors.PolynomialFitting", "IMLearn.model_selection.cross_validate", "IMLearn.utils.split_train_test", "numpy.arange", "numpy.linspace", "numpy.random.normal", "IMLearn.learners.regressors.LinearRegression", "sklearn.linear_model.Lasso" ]
[((1383, 1429), 'IMLearn.utils.split_train_test', 'split_train_test', (['X', 'y'], {'train_proportion': '(2 / 3)'}), '(X, y, train_proportion=2 / 3)\n', (1399, 1429), False, 'from IMLearn.utils import split_train_test\n'), ((1440, 1451), 'plotly.graph_objects.Figure', 'go.Figure', ([], {}), '()\n', (1449, 1451), True, 'import plotly.graph_objects as go\n'), ((2414, 2425), 'plotly.graph_objects.Figure', 'go.Figure', ([], {}), '()\n', (2423, 2425), True, 'import plotly.graph_objects as go\n'), ((3153, 3189), 'numpy.argmin', 'np.argmin', (['loss_by_degree_validation'], {}), '(loss_by_degree_validation)\n', (3162, 3189), True, 'import numpy as np\n'), ((3206, 3231), 'IMLearn.learners.regressors.PolynomialFitting', 'PolynomialFitting', (['k_star'], {}), '(k_star)\n', (3223, 3231), False, 'from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, RidgeRegression\n'), ((4095, 4134), 'sklearn.datasets.load_diabetes', 'datasets.load_diabetes', ([], {'return_X_y': '(True)'}), '(return_X_y=True)\n', (4117, 4134), False, 'from sklearn import datasets\n'), ((4375, 4412), 'numpy.linspace', 'np.linspace', (['(0.01)', '(2.5)', 'n_evaluations'], {}), '(0.01, 2.5, n_evaluations)\n', (4386, 4412), True, 'import numpy as np\n'), ((5586, 5622), 'IMLearn.learners.regressors.RidgeRegression', 'RidgeRegression', (["best_lamda['ridge']"], {}), "(best_lamda['ridge'])\n", (5601, 5622), False, 'from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, RidgeRegression\n'), ((5635, 5661), 'sklearn.linear_model.Lasso', 'Lasso', (["best_lamda['lasso']"], {}), "(best_lamda['lasso'])\n", (5640, 5661), False, 'from sklearn.linear_model import Lasso\n'), ((5682, 5700), 'IMLearn.learners.regressors.LinearRegression', 'LinearRegression', ([], {}), '()\n', (5698, 5700), False, 'from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, RidgeRegression\n'), ((6029, 6046), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (6043, 6046), True, 'import numpy as np\n'), ((1163, 1198), 'numpy.random.normal', 'np.random.normal', (['(0)', 'noise', 'x.shape'], {}), '(0, noise, x.shape)\n', (1179, 1198), True, 'import numpy as np\n'), ((2218, 2238), 'IMLearn.learners.regressors.PolynomialFitting', 'PolynomialFitting', (['k'], {}), '(k)\n', (2235, 2238), False, 'from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, RidgeRegression\n'), ((2254, 2319), 'IMLearn.model_selection.cross_validate', 'cross_validate', (['estimator', 'train_X', 'train_y', 'mean_square_error', '(5)'], {}), '(estimator, train_X, train_y, mean_square_error, 5)\n', (2268, 2319), False, 'from IMLearn.model_selection import cross_validate\n'), ((4907, 4918), 'plotly.graph_objects.Figure', 'go.Figure', ([], {}), '()\n', (4916, 4918), True, 'import plotly.graph_objects as go\n'), ((1121, 1147), 'numpy.random.normal', 'np.random.normal', (['(0)', 'noise'], {}), '(0, noise)\n', (1137, 1147), True, 'import numpy as np\n'), ((1269, 1306), 'numpy.random.uniform', 'np.random.uniform', (['(-1.2)', '(2)', 'n_samples'], {}), '(-1.2, 2, n_samples)\n', (1286, 1306), True, 'import numpy as np\n'), ((4663, 4728), 'IMLearn.model_selection.cross_validate', 'cross_validate', (['estimator', 'train_X', 'train_y', 'mean_square_error', '(5)'], {}), '(estimator, train_X, train_y, mean_square_error, 5)\n', (4677, 4728), False, 'from IMLearn.model_selection import cross_validate\n'), ((4855, 4891), 'numpy.argmin', 'np.argmin', (['loss_by_lambda_validation'], {}), '(loss_by_lambda_validation)\n', (4864, 4891), True, 'import numpy as np\n'), ((2468, 2481), 'numpy.arange', 'np.arange', (['(11)'], {}), '(11)\n', (2477, 2481), True, 'import numpy as np\n'), ((2656, 2669), 'numpy.arange', 'np.arange', (['(11)'], {}), '(11)\n', (2665, 2669), True, 'import numpy as np\n')]
import threading import unittest import tensorflow as tf import numpy as np import fedlearner.common.fl_logging as logging from fedlearner.fedavg import train_from_keras_model (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() x_train = x_train.reshape(x_train.shape[0], -1).astype(np.float32) / 255.0 y_train = y_train.astype(np.int32) x_test = x_test.reshape(x_test.shape[0], -1).astype(np.float32) / 255.0 y_test = y_test.astype(np.int32) def create_model(): model = tf.keras.Sequential([ tf.keras.layers.Dense(200, activation='relu', input_shape=(784, )), tf.keras.layers.Dense(200, activation='relu'), tf.keras.layers.Dense(10, activation='softmax'), ]) model.compile(optimizer=tf.keras.optimizers.SGD(0.01), loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=['acc']) return model class TestFedavgTrain(unittest.TestCase): def setUp(self): super(TestFedavgTrain, self).__init__() self._fl_cluster = { "leader": { "name": "leader", "address": "0.0.0.0:20050" }, "followers": [{ "name": "follower" }] } self._batch_size = 64 self._epochs = 1 self._steps_per_sync = 10 self._l_eval_result = None self._f_eval_result = None def _train_leader(self): x = x_train[:len(x_train) // 2] y = y_train[:len(y_train) // 2] model = create_model() train_from_keras_model(model, x, y, batch_size=self._batch_size, epochs=self._epochs, fl_name="leader", fl_cluster=self._fl_cluster, steps_per_sync=self._steps_per_sync) self._l_eval_result = model.evaluate(x_test, y_test) def _train_follower(self): x = x_train[len(x_train) // 2:] y = y_train[len(y_train) // 2:] model = create_model() train_from_keras_model(model, x, y, batch_size=self._batch_size, epochs=self._epochs, fl_name="follower", fl_cluster=self._fl_cluster, steps_per_sync=self._steps_per_sync) self._f_eval_result = model.evaluate(x_test, y_test) def test_train(self): l_thread = threading.Thread(target=self._train_leader) f_thread = threading.Thread(target=self._train_follower) l_thread.start() f_thread.start() l_thread.join() f_thread.join() assert len(self._l_eval_result) == 2 assert len(self._f_eval_result) == 2 for v1, v2 in zip(self._l_eval_result, self._f_eval_result): assert np.isclose(v1, v2) if __name__ == '__main__': logging.set_level("debug") unittest.main()
[ "unittest.main", "threading.Thread", "fedlearner.fedavg.train_from_keras_model", "tensorflow.keras.losses.SparseCategoricalCrossentropy", "tensorflow.keras.layers.Dense", "tensorflow.keras.optimizers.SGD", "tensorflow.keras.datasets.mnist.load_data", "numpy.isclose", "fedlearner.common.fl_logging.set_level" ]
[((216, 251), 'tensorflow.keras.datasets.mnist.load_data', 'tf.keras.datasets.mnist.load_data', ([], {}), '()\n', (249, 251), True, 'import tensorflow as tf\n'), ((3083, 3109), 'fedlearner.common.fl_logging.set_level', 'logging.set_level', (['"""debug"""'], {}), "('debug')\n", (3100, 3109), True, 'import fedlearner.common.fl_logging as logging\n'), ((3114, 3129), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3127, 3129), False, 'import unittest\n'), ((1549, 1727), 'fedlearner.fedavg.train_from_keras_model', 'train_from_keras_model', (['model', 'x', 'y'], {'batch_size': 'self._batch_size', 'epochs': 'self._epochs', 'fl_name': '"""leader"""', 'fl_cluster': 'self._fl_cluster', 'steps_per_sync': 'self._steps_per_sync'}), "(model, x, y, batch_size=self._batch_size, epochs=\n self._epochs, fl_name='leader', fl_cluster=self._fl_cluster,\n steps_per_sync=self._steps_per_sync)\n", (1571, 1727), False, 'from fedlearner.fedavg import train_from_keras_model\n'), ((2148, 2328), 'fedlearner.fedavg.train_from_keras_model', 'train_from_keras_model', (['model', 'x', 'y'], {'batch_size': 'self._batch_size', 'epochs': 'self._epochs', 'fl_name': '"""follower"""', 'fl_cluster': 'self._fl_cluster', 'steps_per_sync': 'self._steps_per_sync'}), "(model, x, y, batch_size=self._batch_size, epochs=\n self._epochs, fl_name='follower', fl_cluster=self._fl_cluster,\n steps_per_sync=self._steps_per_sync)\n", (2170, 2328), False, 'from fedlearner.fedavg import train_from_keras_model\n'), ((2645, 2688), 'threading.Thread', 'threading.Thread', ([], {'target': 'self._train_leader'}), '(target=self._train_leader)\n', (2661, 2688), False, 'import threading\n'), ((2708, 2753), 'threading.Thread', 'threading.Thread', ([], {'target': 'self._train_follower'}), '(target=self._train_follower)\n', (2724, 2753), False, 'import threading\n'), ((532, 597), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(200)'], {'activation': '"""relu"""', 'input_shape': '(784,)'}), "(200, activation='relu', input_shape=(784,))\n", (553, 597), True, 'import tensorflow as tf\n'), ((608, 653), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(200)'], {'activation': '"""relu"""'}), "(200, activation='relu')\n", (629, 653), True, 'import tensorflow as tf\n'), ((663, 710), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(10)'], {'activation': '"""softmax"""'}), "(10, activation='softmax')\n", (684, 710), True, 'import tensorflow as tf\n'), ((747, 776), 'tensorflow.keras.optimizers.SGD', 'tf.keras.optimizers.SGD', (['(0.01)'], {}), '(0.01)\n', (770, 776), True, 'import tensorflow as tf\n'), ((801, 848), 'tensorflow.keras.losses.SparseCategoricalCrossentropy', 'tf.keras.losses.SparseCategoricalCrossentropy', ([], {}), '()\n', (846, 848), True, 'import tensorflow as tf\n'), ((3031, 3049), 'numpy.isclose', 'np.isclose', (['v1', 'v2'], {}), '(v1, v2)\n', (3041, 3049), True, 'import numpy as np\n')]
#! /usr/bin/env python3 import os import time import matplotlib.pyplot as plt import numpy as np from scipy.stats import norm from sklearn.datasets import make_blobs from lib_dist_app import plt_data, nns # ### do a loop for the number of dimensions and the values of p. ti = time.time() np.random.seed(0) N = 601 nn = [50] pp = [2*i/10 for i in range(1,5)]+[2, 3] # n_proc = 20 # n_features = 50 # processes = np.empty((n_proc, n_features)) # # # for proc in processes: # # proc[:] = np.random.normal(loc=np.random.randint(100), size=n_features) # # # plt.figure() # # for point in processes: # # plt.plot(point) # # plt.show() # # plt.close() # # # # data = np.empty((N, n_features)) # # plt.figure() # for point in data: # i = np.random.randint(low=15, high=20) # point[:] = np.sum(processes[:i, :], axis=0) # plt.plot(point) # # plt.show() # plt.close() ## outliers # ## wave data # # data = np.genfromtxt('wave_data.csv', delimiter=',', dtype='float32', filling_values=0.0) # # # # print(np.count_nonzero(np.isnan(data))) ##NNs # n_neighbors = data.shape[0] # # for p in pp: # # dd, idxx = nns(data=data[:], n_neighbors=n_neighbors, p=p) # print(dd.shape) # rr = [10]#[1, 50, 100, 200, 400, 600] # # for r in rr: # # fig, ax = plt.subplots(figsize=(10,5)) # # d_r = np.mean(dd[:, :r], axis=1) # # print(np.count_nonzero(np.isnan(d_r)),np.max(d_r)) # d_r /= np.max(d_r) # # ax.hist(d_r, bins=100) # plt.tight_layout() # # fig.savefig(f'./gaussians/nns_{r}_n_{data.shape[1]}_p_{p}_outlier_score.png') # # plt.close() ## intuition data # inliers n_samples = [100, 100, 100, 100, 150, 51] # nn_samples = [10*i for i in n_samples] # nn_samples[-1] -= -9 centers = [ [5, 5], [5, 9], [9, 5], [5, 1], [2, 5], [-5, -2] ] cluster_std = [0.25, 0.5, 1, 1.5, 3, 0.25] data, y= make_blobs(n_samples=n_samples, centers=centers, cluster_std=cluster_std, random_state=1) plt_data(data=data, fname='data_distribution', face_color = False) # data, y= make_blobs(n_samples=nn_samples, centers=centers, cluster_std=cluster_std, random_state=1) # plt_data(data=data, fname='data_distribution', alpha=0.05, face_color = True) ##NNs p = 2 n_neighbors = data.shape[0] dd, idxx = nns(data=data, n_neighbors=n_neighbors, p=p, n_jobs=None) # np.save(f'distances_p_{p}.npy', dd) rr = [1, 50, 100, 200, 400, 600] # rr = [1, 500, 1000, 2000, 4000, 6000] for r in rr: fig, ax = plt.subplots(figsize=(10,5)) d_r = np.mean(dd[:, :r], axis=1) d_r /= np.max(d_r) ax.hist(d_r, bins=100) plt.tight_layout() fig.savefig(f'./intuition/nns_{r}_p_{p}_o_score.png') plt.close() # # fig, ax = plt.subplots(figsize=(12, 8)) # dd_sorted = np.sort(dd) # ax.hist(dd_sorted[:1_000], bins=100) # plt.tight_layout() # # fig.savefig('hist_outlier_intuitive.pdf') # fig.savefig('hist_outlier_intuitive.png', facecolor='none') # # silly example # X = np.array([[1, 1], [2, 1], [3, 2]]) # # dd, idxx = nns(data=X, nns=3, p=2) # # print(X, '\n', dd, '\n', idxx, '\n') ############################################################################# # n_points = 40 # mm = np.array([1, 0, -1, 2]) # x = np.linspace(0, 1, n_points) # features = [['a', 'b'], ['i', 'j'], ['m', 'n'], ['x', 'y']] # for idx, m in enumerate(mm): # # if m == 2: # x = np.random.random(size=n_points) # y = np.random.random(size=n_points) # A = [x[n_points//3], y[n_points//3]] # B = [2*x[n_points//3], 2*y[n_points//3]] # else: # y = m*x + np.random.normal(loc=0, scale=0.2, size=n_points) # if m == 1: # A = [x[-3], y[-3] - 1.5] # B = [x[10], y[10]] # elif m == -1: # A = [x[10], y[10]] # B = [x[-3], y[-3] + 1.5] # else: # A = [x[10], y[10]] # B = [x[-3], y[-3]] # fig, ax = plt.subplots(figsize=(10, 5)) # # ax.axis('equal') # # ax.set_xlim((-0.3, 1.3)) # # ax.set_xlim((-0.3, 1.3)) # # ax.set_xticklabels([]) # ax.set_yticklabels([]) # ax.set_xlabel(f'Feature {features[idx][0]}', fontsize='xx-large') # ax.set_ylabel(f'Feature {features[idx][1]}', fontsize='xx-large') # ax.scatter(x, y) # ax.scatter(A[0], A[1], s=150, label='A') # ax.scatter(B[0], B[1], s=150, label='B') # ax.legend(loc='upper left') # # plt.tight_layout() # fig.savefig(f'{path}/{idx}_projection_approach.png') # fig.savefig(f'{path}/{idx}_projection_approach.pdf') # #################################################### # path = './pics_generative_approach' # np.random.seed(0) # # n_points = 10_000 # # mus = np.array([2, 3, 5, 7]) # sigmas = np.random.random(size=mus.size) # x = np.linspace(0, 9, n_points) # models = np.empty((sigmas.size, n_points)) # # fig, ax = plt.subplots(figsize=(10, 5)) # ax.set_xlabel('Observables', fontsize='xx-large') # ax.set_ylabel('Measurements', fontsize='xx-large') # ax.set_yticklabels([]) # ax.set_xticklabels([]) # # lines = [] # for idx, mu in enumerate(mus): # models[idx, :] = norm.pdf(x, loc=mu, scale=sigmas[idx]) # model_line, = ax.plot(x, models[idx, :], alpha=0.12) # # lines.append(model_line) # # legends = [f'Model {idx+1}' for idx in range(len(lines))] # # # Final model # model = np.sum(models, axis=0) # line, = ax.plot(x, model, color='black', alpha=5) # lines.append(line) # legends.append('Generative process') # # ax.legend(lines, legends, loc='upper right', shadow=True) # # # Deviations # # noise = 0.5 - np.random.random(size=n_points) # data = model + noise*0.7 # idx = np.random.randint(0, n_points, int(n_points*0.015)) # # ax.scatter(x[idx], data[idx], s=2.) # plt.tight_layout() # fig.savefig(f'{path}/generative_models.png') # fig.savefig(f'{path}/generative_models.pdf') tf = time.time() print(f'Running time: {tf-ti:.2f}')
[ "matplotlib.pyplot.tight_layout", "numpy.random.seed", "lib_dist_app.nns", "matplotlib.pyplot.close", "sklearn.datasets.make_blobs", "time.time", "lib_dist_app.plt_data", "numpy.mean", "numpy.max", "matplotlib.pyplot.subplots" ]
[((280, 291), 'time.time', 'time.time', ([], {}), '()\n', (289, 291), False, 'import time\n'), ((292, 309), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (306, 309), True, 'import numpy as np\n'), ((1880, 1973), 'sklearn.datasets.make_blobs', 'make_blobs', ([], {'n_samples': 'n_samples', 'centers': 'centers', 'cluster_std': 'cluster_std', 'random_state': '(1)'}), '(n_samples=n_samples, centers=centers, cluster_std=cluster_std,\n random_state=1)\n', (1890, 1973), False, 'from sklearn.datasets import make_blobs\n'), ((1970, 2034), 'lib_dist_app.plt_data', 'plt_data', ([], {'data': 'data', 'fname': '"""data_distribution"""', 'face_color': '(False)'}), "(data=data, fname='data_distribution', face_color=False)\n", (1978, 2034), False, 'from lib_dist_app import plt_data, nns\n'), ((2273, 2330), 'lib_dist_app.nns', 'nns', ([], {'data': 'data', 'n_neighbors': 'n_neighbors', 'p': 'p', 'n_jobs': 'None'}), '(data=data, n_neighbors=n_neighbors, p=p, n_jobs=None)\n', (2276, 2330), False, 'from lib_dist_app import plt_data, nns\n'), ((5817, 5828), 'time.time', 'time.time', ([], {}), '()\n', (5826, 5828), False, 'import time\n'), ((2472, 2501), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(10, 5)'}), '(figsize=(10, 5))\n', (2484, 2501), True, 'import matplotlib.pyplot as plt\n'), ((2512, 2538), 'numpy.mean', 'np.mean', (['dd[:, :r]'], {'axis': '(1)'}), '(dd[:, :r], axis=1)\n', (2519, 2538), True, 'import numpy as np\n'), ((2550, 2561), 'numpy.max', 'np.max', (['d_r'], {}), '(d_r)\n', (2556, 2561), True, 'import numpy as np\n'), ((2594, 2612), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2610, 2612), True, 'import matplotlib.pyplot as plt\n'), ((2677, 2688), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2686, 2688), True, 'import matplotlib.pyplot as plt\n')]
from __future__ import print_function import numpy as np c0prop = np.array([4, -2, 0, 0, 5]) # Frosting c1prop = np.array([0, 5, -1, 0, 8]) # Candy c2prop = np.array([-1, 0, 5, 0, 6]) # Butterscotch c3prop = np.array([0, 0, -2, 2, 1]) # Sugar max_score = 0 max_500_score = 0 for c0 in range(101): for c1 in range(0, 101-c0): remain = 100 - c0 - c1 c2 = np.arange(remain + 1) c3 = remain - c2 sums_of_prop = (c0*c0prop + c1*c1prop + np.outer(c2, c2prop) + np.outer(c3, c3prop)) calories = sums_of_prop[:, -1] sums_of_prop = sums_of_prop[:, :-1] # remove calories sums_of_prop[sums_of_prop < 0] = 0 # replace negatives with zeros max_score = max(np.prod(sums_of_prop, axis=1).max(), max_score) # part B, find all the cookies with 500 calories cal_500_prop = sums_of_prop[calories == 500] if len(cal_500_prop) == 0: continue max_500_score = max(np.prod(cal_500_prop, axis=1).max(), max_500_score) print(max_score) print(max_500_score)
[ "numpy.outer", "numpy.array", "numpy.arange", "numpy.prod" ]
[((67, 93), 'numpy.array', 'np.array', (['[4, -2, 0, 0, 5]'], {}), '([4, -2, 0, 0, 5])\n', (75, 93), True, 'import numpy as np\n'), ((116, 142), 'numpy.array', 'np.array', (['[0, 5, -1, 0, 8]'], {}), '([0, 5, -1, 0, 8])\n', (124, 142), True, 'import numpy as np\n'), ((162, 188), 'numpy.array', 'np.array', (['[-1, 0, 5, 0, 6]'], {}), '([-1, 0, 5, 0, 6])\n', (170, 188), True, 'import numpy as np\n'), ((215, 241), 'numpy.array', 'np.array', (['[0, 0, -2, 2, 1]'], {}), '([0, 0, -2, 2, 1])\n', (223, 241), True, 'import numpy as np\n'), ((383, 404), 'numpy.arange', 'np.arange', (['(remain + 1)'], {}), '(remain + 1)\n', (392, 404), True, 'import numpy as np\n'), ((526, 546), 'numpy.outer', 'np.outer', (['c3', 'c3prop'], {}), '(c3, c3prop)\n', (534, 546), True, 'import numpy as np\n'), ((503, 523), 'numpy.outer', 'np.outer', (['c2', 'c2prop'], {}), '(c2, c2prop)\n', (511, 523), True, 'import numpy as np\n'), ((751, 780), 'numpy.prod', 'np.prod', (['sums_of_prop'], {'axis': '(1)'}), '(sums_of_prop, axis=1)\n', (758, 780), True, 'import numpy as np\n'), ((994, 1023), 'numpy.prod', 'np.prod', (['cal_500_prop'], {'axis': '(1)'}), '(cal_500_prop, axis=1)\n', (1001, 1023), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 12 12:07:33 2020 @author: student """ import numpy as np import tensorflow as tf from base_functions import one_one # File path for saving the tfrecords files path = '/home/student/Work/Keras/GAN/mySRGAN/new_implementation/multiGPU_datasetAPI/custom_train_loop_function_method/DATA_FOR_AAAI/code/' ############################################################################### # Documentation: # https://www.tensorflow.org/tutorials/load_data/tfrecord # https://www.tensorflow.org/guide/data # How to shard a large dataset: # https://jkjung-avt.github.io/tfrecords-for-keras/ # https://github.com/jkjung-avt/keras_imagenet # https://github.com/jkjung-avt/keras_imagenet/blob/master/data/build_imagenet_data.py <- this one builds the dataset # Working example (partially adapted to produce this code): # https://stackoverflow.com/questions/57717004/tensorflow-modern-way-to-load-large-data # Another working example: # https://stackoverflow.com/questions/50955798/keras-model-fit-with-tf-dataset-api-validation-data#50979587 # Some benefits to working with tf.data.Dataset as opposed to a numpy array: # https://stackoverflow.com/questions/47732186/tensorflow-tf-record-too-large-to-be-loaded-into-an-np-array-at-once?rq=1 ############################################################################### """ First, download the fashion-MNIST dataset, preprocess, and convert to numpy. """ # Load training and validation (test) data using built-in TF function. ((x_train, y_train), (x_val, y_val)) = tf.keras.datasets.fashion_mnist.load_data() # Expand dims to include depth dimension x_train = np.expand_dims(x_train, -1) x_val = np.expand_dims(x_val, -1) # Convert from uint8 to float32 x_train = x_train.astype(np.float32) x_val = x_val.astype(np.float32) # By default, the intensities are in [0,255]. Rescale to [-1,1]. Do this SEPARATELY for the training and validation sets. x_train = one_one(x_train) x_val = one_one(x_val) # Set aside the first example from each class as a "demo" dataset, for tracking changes in the model outputs during training. indices = [19,2,1,13,6,8,4,9,18,0] x_demo = np.zeros((10,28,28,1)) for i in range(10): x_demo[i] = x_val[indices[i]] # Make a set of 4 "demo" z vectors. # They will be very long, and can be adapted to any reasonable z_dim by simply chopping off the extra dimensions. z_demo = np.random.randn(4,1000,1) # The x data have now been preprocessed for conversion to tfrecords files. # We are not doing anything with the class labels, but for the sake of completeness, here is the conversion: y_train = tf.keras.utils.to_categorical(y_train, num_classes=10, dtype='float32') y_val = tf.keras.utils.to_categorical(y_val, num_classes=10, dtype='float32') ############################################################################### """ FUNCTION DEFINITIONS """ def _bytes_feature(value): """Returns a bytes_list from a string / byte.""" return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def _float_feature(value): """Returns a float_list from a float (32 or 64 precision).""" return tf.train.Feature(float_list=tf.train.FloatList(value=[value])) def _int64_feature(value): """ Returns an int64_list from bool / enum / int / uint.""" return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def _convert_img_to_str(img): """ Convert an image in numpy array format, shape (1, height, width, depth), to a string. Depth is 1 for grayscale, 3 for RGB. Returns: img_string height width depth """ # height, width, and depth are all going to be features in the serialized example (just the same as the class label will be). height = img.shape[1] width = img.shape[2] depth = img.shape[3] img_string = img.tostring() return img_string, height, width, depth def _convert_1hot_to_str(one_hot): """ Convert a one-hot class label vector, shape (1, num_classes), to a string. Returns: one_hot_string """ one_hot_string = one_hot.tostring() return one_hot_string def _convert_to_example(img_string, height, width, depth, one_hot_string): """ Serialize an example with a single image and corresponding one-hot class label. This creates a tf.Example message ready to be written to a file. Args: img_string: string, image in array of shape (1, height, width, depth). height: integer, image height in pixels. width: integer, image width in pixels. depth: integer, image depth in pixels. one_hot_string: string, one-hot vector that identifies the ground truth label. Returns: Example proto """ # Create a dictionary mapping the feature name to the tf.Example-compatible data type. feature = {'img': _bytes_feature(img_string), 'height': _int64_feature(height), 'width': _int64_feature(width), 'depth': _int64_feature(depth), 'label': _bytes_feature(one_hot_string)} # Create a Features message using tf.train.Example. example_proto = tf.train.Example(features=tf.train.Features(feature=feature)) return example_proto def _make_TFRecord(x, y, output_file): """ Processes and saves an array of image data and array of label data as a TFRecord. Args: x: numpy array of images. Has shape (num_examples, height, width, depth). y: numpy array of one-hot class labels. Has shape (num_examples, num_classes) output_file: string, filename for the saved TFRecord file. """ # Open the file writer. All of the examples will be written here. writer = tf.io.TFRecordWriter(output_file) for i in range(x.shape[0]): # Get the image and corresponding label for one example. img = x[i:i+1] label = y[i:i+1] # Convert the image to a string and obtain the image dimensions. (img_string, height, width, depth) = _convert_img_to_str(img) # Convert the one-hot class label to a string. one_hot_string = _convert_1hot_to_str(label) # Put all the features into the example. example = _convert_to_example(img_string, height, width, depth, one_hot_string) # Write the example into the TFRecords file. writer.write(example.SerializeToString()) print(f'Created example {i} of {x.shape[0]}.') writer.close() print(f'Saved TFRecord to {output_file}.') def _parse_example(serialized_example): """ Takes a single serialized example and converts it back into an image (AS A TENSOR OBJECT) and the corresponding label. """ features = {'img': tf.io.FixedLenFeature([], tf.string), 'height': tf.io.FixedLenFeature([], tf.int64), 'width': tf.io.FixedLenFeature([], tf.int64), 'depth': tf.io.FixedLenFeature([], tf.int64), 'label': tf.io.FixedLenFeature([], tf.string)} parsed_example = tf.io.parse_single_example(serialized=serialized_example, features=features) # Get the class label. label = parsed_example['label'] label = tf.io.decode_raw(label, tf.float32) # Get the image dimensions. height = parsed_example['height'] width = parsed_example['width'] depth = parsed_example['depth'] # Get the raw byte string and convert it to a tensor object. img = parsed_example['img'] img = tf.io.decode_raw(img, tf.float32) # The tensor object is 1-dimensional, so reshape it using the image dimensions we obtained earlier. img = tf.reshape(img, shape=(height, width, depth)) return img, label ############################################################################### def make_TFRecords(): """ Function that creates training and validation tfrecords files using the above functions. """ _make_TFRecord(x_train, y_train, path + 'xy_train_fMNIST.tfrecords') _make_TFRecord(x_val, y_val, path + 'xy_val_fMNIST.tfrecords') np.save(path + 'x_demo.npy', x_demo) np.save(path + 'z_demo.npy', z_demo) def verify_TFRecords(path): """ Function that verifies that the tfrecords files were created properly. Args: path: location of xy_train.tfrecords and xy_val.tfrecords Plots several images from the validation set and prints the corresponding labels. """ import matplotlib.pyplot as plt xy_val = path + 'xy_val_fMNIST.tfrecords' xy_val = tf.data.TFRecordDataset(xy_val) # Check the first 5 examples from the dataset. xy_val = xy_val.take(5).map(_parse_example) plt.close('all') # Each example looks like (img, label) for ex in xy_val: img = ex[0].numpy() label = ex[1].numpy() plt.figure() plt.imshow(img[:,:,0], cmap='gray', vmin=-1, vmax=1) print(label)
[ "tensorflow.train.Int64List", "tensorflow.reshape", "matplotlib.pyplot.figure", "tensorflow.train.FloatList", "numpy.random.randn", "matplotlib.pyplot.close", "matplotlib.pyplot.imshow", "tensorflow.io.decode_raw", "base_functions.one_one", "tensorflow.train.BytesList", "numpy.save", "tensorflow.keras.utils.to_categorical", "tensorflow.train.Features", "tensorflow.io.TFRecordWriter", "tensorflow.keras.datasets.fashion_mnist.load_data", "tensorflow.data.TFRecordDataset", "numpy.zeros", "numpy.expand_dims", "tensorflow.io.parse_single_example", "tensorflow.io.FixedLenFeature" ]
[((1597, 1640), 'tensorflow.keras.datasets.fashion_mnist.load_data', 'tf.keras.datasets.fashion_mnist.load_data', ([], {}), '()\n', (1638, 1640), True, 'import tensorflow as tf\n'), ((1693, 1720), 'numpy.expand_dims', 'np.expand_dims', (['x_train', '(-1)'], {}), '(x_train, -1)\n', (1707, 1720), True, 'import numpy as np\n'), ((1754, 1779), 'numpy.expand_dims', 'np.expand_dims', (['x_val', '(-1)'], {}), '(x_val, -1)\n', (1768, 1779), True, 'import numpy as np\n'), ((2039, 2055), 'base_functions.one_one', 'one_one', (['x_train'], {}), '(x_train)\n', (2046, 2055), False, 'from base_functions import one_one\n'), ((2064, 2078), 'base_functions.one_one', 'one_one', (['x_val'], {}), '(x_val)\n', (2071, 2078), False, 'from base_functions import one_one\n'), ((2250, 2275), 'numpy.zeros', 'np.zeros', (['(10, 28, 28, 1)'], {}), '((10, 28, 28, 1))\n', (2258, 2275), True, 'import numpy as np\n'), ((2486, 2513), 'numpy.random.randn', 'np.random.randn', (['(4)', '(1000)', '(1)'], {}), '(4, 1000, 1)\n', (2501, 2513), True, 'import numpy as np\n'), ((2707, 2778), 'tensorflow.keras.utils.to_categorical', 'tf.keras.utils.to_categorical', (['y_train'], {'num_classes': '(10)', 'dtype': '"""float32"""'}), "(y_train, num_classes=10, dtype='float32')\n", (2736, 2778), True, 'import tensorflow as tf\n'), ((2867, 2936), 'tensorflow.keras.utils.to_categorical', 'tf.keras.utils.to_categorical', (['y_val'], {'num_classes': '(10)', 'dtype': '"""float32"""'}), "(y_val, num_classes=10, dtype='float32')\n", (2896, 2936), True, 'import tensorflow as tf\n'), ((6124, 6157), 'tensorflow.io.TFRecordWriter', 'tf.io.TFRecordWriter', (['output_file'], {}), '(output_file)\n', (6144, 6157), True, 'import tensorflow as tf\n'), ((7849, 7925), 'tensorflow.io.parse_single_example', 'tf.io.parse_single_example', ([], {'serialized': 'serialized_example', 'features': 'features'}), '(serialized=serialized_example, features=features)\n', (7875, 7925), True, 'import tensorflow as tf\n'), ((8050, 8085), 'tensorflow.io.decode_raw', 'tf.io.decode_raw', (['label', 'tf.float32'], {}), '(label, tf.float32)\n', (8066, 8085), True, 'import tensorflow as tf\n'), ((8366, 8399), 'tensorflow.io.decode_raw', 'tf.io.decode_raw', (['img', 'tf.float32'], {}), '(img, tf.float32)\n', (8382, 8399), True, 'import tensorflow as tf\n'), ((8541, 8586), 'tensorflow.reshape', 'tf.reshape', (['img'], {'shape': '(height, width, depth)'}), '(img, shape=(height, width, depth))\n', (8551, 8586), True, 'import tensorflow as tf\n'), ((9124, 9160), 'numpy.save', 'np.save', (["(path + 'x_demo.npy')", 'x_demo'], {}), "(path + 'x_demo.npy', x_demo)\n", (9131, 9160), True, 'import numpy as np\n'), ((9177, 9213), 'numpy.save', 'np.save', (["(path + 'z_demo.npy')", 'z_demo'], {}), "(path + 'z_demo.npy', z_demo)\n", (9184, 9213), True, 'import numpy as np\n'), ((9609, 9640), 'tensorflow.data.TFRecordDataset', 'tf.data.TFRecordDataset', (['xy_val'], {}), '(xy_val)\n', (9632, 9640), True, 'import tensorflow as tf\n'), ((9746, 9762), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (9755, 9762), True, 'import matplotlib.pyplot as plt\n'), ((7305, 7341), 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['[]', 'tf.string'], {}), '([], tf.string)\n', (7326, 7341), True, 'import tensorflow as tf\n'), ((7414, 7449), 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['[]', 'tf.int64'], {}), '([], tf.int64)\n', (7435, 7449), True, 'import tensorflow as tf\n'), ((7524, 7559), 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['[]', 'tf.int64'], {}), '([], tf.int64)\n', (7545, 7559), True, 'import tensorflow as tf\n'), ((7633, 7668), 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['[]', 'tf.int64'], {}), '([], tf.int64)\n', (7654, 7668), True, 'import tensorflow as tf\n'), ((7742, 7778), 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['[]', 'tf.string'], {}), '([], tf.string)\n', (7763, 7778), True, 'import tensorflow as tf\n'), ((9896, 9908), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (9906, 9908), True, 'import matplotlib.pyplot as plt\n'), ((9917, 9971), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img[:, :, 0]'], {'cmap': '"""gray"""', 'vmin': '(-1)', 'vmax': '(1)'}), "(img[:, :, 0], cmap='gray', vmin=-1, vmax=1)\n", (9927, 9971), True, 'import matplotlib.pyplot as plt\n'), ((3244, 3277), 'tensorflow.train.BytesList', 'tf.train.BytesList', ([], {'value': '[value]'}), '(value=[value])\n', (3262, 3277), True, 'import tensorflow as tf\n'), ((3412, 3445), 'tensorflow.train.FloatList', 'tf.train.FloatList', ([], {'value': '[value]'}), '(value=[value])\n', (3430, 3445), True, 'import tensorflow as tf\n'), ((3578, 3611), 'tensorflow.train.Int64List', 'tf.train.Int64List', ([], {'value': '[value]'}), '(value=[value])\n', (3596, 3611), True, 'import tensorflow as tf\n'), ((5525, 5559), 'tensorflow.train.Features', 'tf.train.Features', ([], {'feature': 'feature'}), '(feature=feature)\n', (5542, 5559), True, 'import tensorflow as tf\n')]
from scipy import linalg import numpy as np def error_norm(theta_star, theta_hat, norm='frobenius', scaling=True, squared=True): """ sklearn Graphical LASSO """ # compute the error error = theta_star - theta_hat # compute the error norm if norm == "frobenius": squared_norm = np.sum(error ** 2) elif norm == "spectral": squared_norm = np.amax(linalg.svdvals(np.dot(error.T, error))) else: raise NotImplementedError( "Only spectral and frobenius norms are implemented") # optionally scale the error norm if scaling: squared_norm = squared_norm / error.shape[0] # finally get either the squared norm or the norm if squared: result = squared_norm else: result = np.sqrt(squared_norm) return result
[ "numpy.dot", "numpy.sum", "numpy.sqrt" ]
[((306, 324), 'numpy.sum', 'np.sum', (['(error ** 2)'], {}), '(error ** 2)\n', (312, 324), True, 'import numpy as np\n'), ((769, 790), 'numpy.sqrt', 'np.sqrt', (['squared_norm'], {}), '(squared_norm)\n', (776, 790), True, 'import numpy as np\n'), ((400, 422), 'numpy.dot', 'np.dot', (['error.T', 'error'], {}), '(error.T, error)\n', (406, 422), True, 'import numpy as np\n')]
""" Script that trains Tensorflow multitask models on PCBA dataset. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals import os import numpy as np import shutil from pcba_datasets import load_pcba from deepchem.utils.save import load_from_disk from deepchem.data import Dataset from deepchem import metrics from deepchem.metrics import Metric from deepchem.metrics import to_one_hot from deepchem.utils.evaluate import Evaluator from deepchem.models.tensorflow_models.fcnet import TensorflowMultiTaskClassifier np.random.seed(123) pcba_tasks, pcba_datasets, transformers = load_pcba() (train_dataset, valid_dataset, test_dataset) = pcba_datasets metric = Metric(metrics.roc_auc_score, np.mean, mode="classification") n_features = train_dataset.get_data_shape()[0] model_dir = None model = TensorflowMultiTaskClassifier( len(pcba_tasks), n_features, model_dir, dropouts=[.25], learning_rate=0.001, weight_init_stddevs=[.1], batch_size=64, verbosity="high") # Fit trained model model.fit(train_dataset) model.save() train_evaluator = Evaluator( model, train_dataset, transformers, verbosity=verbosity) train_scores = train_evaluator.compute_model_performance([metric]) print("Train scores") print(train_scores) valid_evaluator = Evaluator( model, valid_dataset, transformers, verbosity=verbosity) valid_scores = valid_evaluator.compute_model_performance([metric]) print("Validation scores") print(valid_scores)
[ "pcba_datasets.load_pcba", "deepchem.utils.evaluate.Evaluator", "numpy.random.seed", "deepchem.metrics.Metric" ]
[((577, 596), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (591, 596), True, 'import numpy as np\n'), ((640, 651), 'pcba_datasets.load_pcba', 'load_pcba', ([], {}), '()\n', (649, 651), False, 'from pcba_datasets import load_pcba\n'), ((723, 784), 'deepchem.metrics.Metric', 'Metric', (['metrics.roc_auc_score', 'np.mean'], {'mode': '"""classification"""'}), "(metrics.roc_auc_score, np.mean, mode='classification')\n", (729, 784), False, 'from deepchem.metrics import Metric\n'), ((1135, 1201), 'deepchem.utils.evaluate.Evaluator', 'Evaluator', (['model', 'train_dataset', 'transformers'], {'verbosity': 'verbosity'}), '(model, train_dataset, transformers, verbosity=verbosity)\n', (1144, 1201), False, 'from deepchem.utils.evaluate import Evaluator\n'), ((1336, 1402), 'deepchem.utils.evaluate.Evaluator', 'Evaluator', (['model', 'valid_dataset', 'transformers'], {'verbosity': 'verbosity'}), '(model, valid_dataset, transformers, verbosity=verbosity)\n', (1345, 1402), False, 'from deepchem.utils.evaluate import Evaluator\n')]
import numpy as np import pandas as pd def table_atm(h, parametr): """ Cтандартная атмосфера для высот h = -2000 м ... 80000 м (ГОСТ 4401-81) arguments: h высота [м], parametr: 1 - температура [К]; 2 - давление [Па]; 3 - плотность [кг/м^3]; 4 - местная скорость звука [м/с]; 5 - динамическая вязкость [Па*с] 6 - кинематическая вязкость [м^2*с]; return: значение выбранного параметра на высоте h """ table = pd.read_csv('data_constants/table_atm.csv', names=['h', 'p', 'rho', 'T'], sep=',') table_h = table['h'] table_p = table['p'] table_T = table['T'] table_rho = table['rho'] if parametr == 1: return np.interp(h, table_h, table_T) elif parametr == 2: return np.interp(h, table_h, table_p) elif parametr == 3: return np.interp(h, table_h, table_rho) elif parametr == 4: p_h = np.interp(h, table_h, table_p) rho_h = np.interp(h, table_h, table_rho) k_x = 1.4 a_h = np.sqrt(k_x * p_h / rho_h) return a_h elif parametr == 5: T_h = np.interp(h, table_h, table_T) rho_h = np.interp(h, table_h, table_rho) betta_s = 1.458*1e-6 S = 110.4 myu = betta_s * T_h**(3/2) / (T_h + S) return myu elif parametr == 6: T_h = np.interp(h, table_h, table_T) rho_h = np.interp(h, table_h, table_rho) betta_s = 1.458*1e-6 S = 110.4 myu = betta_s * T_h**(3/2) / (T_h + S) nyu = myu / rho_h return nyu else: print("Ошибка: неверное значение при выборе параметра") def Cx43(Mah): """ Ф-ция закона сопротивления 1943 года arguments: число Маха return: коэф-т лобового сопротивления Cx """ table = pd.read_csv('data_constants/table_cx43.csv', names=['mah', 'cx'], sep=',') table_mah = table['mah'] table_cx = table['cx'] return np.interp(Mah, table_mah, table_cx)
[ "pandas.read_csv", "numpy.interp", "numpy.sqrt" ]
[((611, 697), 'pandas.read_csv', 'pd.read_csv', (['"""data_constants/table_atm.csv"""'], {'names': "['h', 'p', 'rho', 'T']", 'sep': '""","""'}), "('data_constants/table_atm.csv', names=['h', 'p', 'rho', 'T'],\n sep=',')\n", (622, 697), True, 'import pandas as pd\n'), ((1934, 2008), 'pandas.read_csv', 'pd.read_csv', (['"""data_constants/table_cx43.csv"""'], {'names': "['mah', 'cx']", 'sep': '""","""'}), "('data_constants/table_cx43.csv', names=['mah', 'cx'], sep=',')\n", (1945, 2008), True, 'import pandas as pd\n'), ((2086, 2121), 'numpy.interp', 'np.interp', (['Mah', 'table_mah', 'table_cx'], {}), '(Mah, table_mah, table_cx)\n', (2095, 2121), True, 'import numpy as np\n'), ((837, 867), 'numpy.interp', 'np.interp', (['h', 'table_h', 'table_T'], {}), '(h, table_h, table_T)\n', (846, 867), True, 'import numpy as np\n'), ((907, 937), 'numpy.interp', 'np.interp', (['h', 'table_h', 'table_p'], {}), '(h, table_h, table_p)\n', (916, 937), True, 'import numpy as np\n'), ((977, 1009), 'numpy.interp', 'np.interp', (['h', 'table_h', 'table_rho'], {}), '(h, table_h, table_rho)\n', (986, 1009), True, 'import numpy as np\n'), ((1048, 1078), 'numpy.interp', 'np.interp', (['h', 'table_h', 'table_p'], {}), '(h, table_h, table_p)\n', (1057, 1078), True, 'import numpy as np\n'), ((1095, 1127), 'numpy.interp', 'np.interp', (['h', 'table_h', 'table_rho'], {}), '(h, table_h, table_rho)\n', (1104, 1127), True, 'import numpy as np\n'), ((1160, 1186), 'numpy.sqrt', 'np.sqrt', (['(k_x * p_h / rho_h)'], {}), '(k_x * p_h / rho_h)\n', (1167, 1186), True, 'import numpy as np\n'), ((1244, 1274), 'numpy.interp', 'np.interp', (['h', 'table_h', 'table_T'], {}), '(h, table_h, table_T)\n', (1253, 1274), True, 'import numpy as np\n'), ((1291, 1323), 'numpy.interp', 'np.interp', (['h', 'table_h', 'table_rho'], {}), '(h, table_h, table_rho)\n', (1300, 1323), True, 'import numpy as np\n'), ((1475, 1505), 'numpy.interp', 'np.interp', (['h', 'table_h', 'table_T'], {}), '(h, table_h, table_T)\n', (1484, 1505), True, 'import numpy as np\n'), ((1522, 1554), 'numpy.interp', 'np.interp', (['h', 'table_h', 'table_rho'], {}), '(h, table_h, table_rho)\n', (1531, 1554), True, 'import numpy as np\n')]
from tensorflow.keras import models import numpy as np # for using PIL, we have to add "Pillow" to requirements.txt from PIL import Image import io from flask import jsonify, make_response import json import base64 import cv2 as cv from google.cloud import storage # Xception Fine Tuning モデルを読み込む( Global variable として定義) def loadCustomModel(): # 'gs://kagawa-ai-lesson/model_4.hdf5' storage_client = storage.Client() bucket = storage_client.get_bucket('kagawa-ai-lesson') #blob = bucket.blob('model_4.hdf5') blob = bucket.blob('model_8.hdf5') blob.download_to_filename('/tmp/tmp.hdf5') return models.load_model('/tmp/tmp.hdf5') # Xception Fine Tuning モデルを読み込む( Global variable として定義) model = loadCustomModel() # ポケモン画像を予測する( HTTP トリガーで呼び出されるメソッド) def predictPokemon(request): """Responds to any HTTP request. Args: request (flask.Request): HTTP request object. Returns: The response text or any set of values that can be turned into a Response object using `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`. """ # Set CORS headers for the preflight request if request.method == 'OPTIONS': # Allows GET requests from any origin with the Content-Type # header and caches preflight response for an 3600s headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Max-Age': '3600' } return ('', 204, headers) #if not request.files['captured']: # data = dict(success=False, message='request.file["captured"] were not found.') # return jsonify(data) #img = request.files['captured'].read() #img = Image.open(io.BytesIO(img)) #img = img.resize((196, 196)) #img.save('captured.jpg') request_json = request.get_json() captured = request_json['captured'] image_decoded = base64.b64decode(captured.split(',')[1]) # remove header #image_obj = Image.open(io.BytesIO(image_decoded)) #image_array = np.asarray(image_obj) #image_array = np.delete(image_array, 3, 2) # (196, 196, 4) -> (196, 196, 3) temp_array = np.fromstring(image_decoded, np.uint8) image_obj = cv.imdecode(temp_array, cv.IMREAD_COLOR) image_array = np.array(image_obj).reshape(196, 196, 3) image_array = image_array / 255.0 image_array = np.expand_dims(image_array, axis=0) print('#### image_array shape') print(image_array.shape) pred = model.predict(image_array) pokemon_names = [ "Abra", "Aerodactyl", "Alakazam", "Arbok", "Arcanine", "Articuno", "Beedrill", "Bellsprout", "Blastoise", "Bulbasaur", "Butterfree", "Caterpie", "Chansey", "Charizard", "Charmander", "Charmeleon", "Clefable", "Clefairy", "Cloyster", "Cubone", "Dewgong", "Diglett", "Ditto", "Dodrio", "Doduo", "Dragonair", "Dragonite", "Dratini", "Drowzee", "Dugtrio", "Eevee", "Ekans", "Electabuzz", "Electrode", "Exeggcute", "Exeggutor", "Farfetchd", "Fearow", "Flareon", "Gastly", "Gengar", "Geodude", "Gloom", "Golbat", "Goldeen", "Golduck", "Golem", "Graveler", "Grimer", "Growlithe", "Gyarados", "Haunter", "Hitmonchan", "Hitmonlee", "Horsea", "Hypno", "Ivysaur", "Jigglypuff", "Jolteon", "Jynx", "Kabuto", "Kabutops", "Kadabra", "Kakuna", "Kangaskhan", "Kingler", "Koffing", "Krabby", "Lapras", "Lickitung", "Machamp", "Machoke", "Machop", "Magikarp", "Magmar", "Magnemite", "Magneton", "Mankey", "Marowak", "Meowth", "Metapod", "Mew", "Mewtwo", "Moltres", "MrMime", "Muk", "Nidoking", "Nidoqueen", "Nidorina", "Nidorino", "Ninetales", "Oddish", "Omanyte", "Omastar", "Onix", "Paras", "Parasect", "Persian", "Pidgeot", "Pidgeotto", "Pidgey", "Pikachu", "Pinsir", "Poliwag", "Poliwhirl", "Poliwrath", "Ponyta", "Porygon", "Primeape", "Psyduck", "Raichu", "Rapidash", "Raticate", "Rattata", "Rhydon", "Rhyhorn", "Sandshrew", "Sandslash", "Scyther", "Seadra", "Seaking", "Seel", "Shellder", "Slowbro", "Slowpoke", "Snorlax", "Spearow", "Squirtle", "Starmie", "Staryu", "Tangela", "Tauros", "Tentacool", "Tentacruel", "Vaporeon", "Venomoth", "Venonat", "Venusaur", "Victreebel", "Vileplume", "Voltorb", "Vulpix", "Wartortle", "Weedle", "Weepinbell", "Weezing", "Wigglytuff", "Zapdos", "Zubat" ] pokemon_names_jp = { "Abra": "ケーシィ", "Aerodactyl": "プテラ", "Alakazam": "フーディン", "Arbok": "アーボック", "Arcanine": "ウインディ", "Articuno": "フリーザー", "Beedrill": "スピアー", "Bellsprout": "マダツボミ", "Blastoise": "カメックス", "Bulbasaur": "フシギダネ", "Butterfree": "バタフリー", "Caterpie": "キャタピー", "Chansey": "ラッキー", "Charizard": "リザードン", "Charmander": "ヒトカゲ", "Charmeleon": "リザード", "Clefable": "ピクシー", "Clefairy": "ピッピ", "Cloyster": "パルシェン", "Cubone": "カラカラ", "Dewgong": "ジュゴン", "Diglett": "ディグダ", "Ditto": "メタモン", "Dodrio": "ドードリオ", "Doduo": "ドードー", "Dragonair": "ハクリュー", "Dragonite": "カイリュー", "Dratini": "ミニリュウ", "Drowzee": "スリープ", "Dugtrio": "ダグトリオ", "Eevee": "イーブイ", "Ekans": "アーボ", "Electabuzz": "エレブー", "Electrode": "マルマイン", "Exeggcute": "タマタマ", "Exeggutor": "ナッシー", "Farfetchd": "カモネギ", "Fearow": "オニドリル", "Flareon": "ブースター", "Gastly": "ゴース", "Gengar": "ゲンガー", "Geodude": "イシツブテ", "Gloom": "クサイハナ", "Golbat": "ゴルバット", "Goldeen": "トサキント", "Golduck": "ゴルダック", "Golem": "ゴローニャ", "Graveler": "ゴローン", "Grimer": "ベトベター", "Growlithe": "ガーディ", "Gyarados": "ギャラドス", "Haunter": "ゴースト", "Hitmonchan": "エビワラー", "Hitmonlee": "サワムラー", "Horsea": "タッツー", "Hypno": "スリーパー", "Ivysaur": "フシギソウ", "Jigglypuff": "プリン", "Jolteon": "サンダース", "Jynx": "ルージュラ", "Kabuto": "カブト", "Kabutops": "カブトプス", "Kadabra": "ユンゲラー", "Kakuna": "コクーン", "Kangaskhan": "ガルーラ", "Kingler": "キングラー", "Koffing": "ドガース", "Krabby": "クラブ", "Lapras": "ラプラス", "Lickitung": "ベロリンガ", "Machamp": "カイリキー", "Machoke": "ゴーリキー", "Machop": "ワンリキー", "Magikarp": "コイキング", "Magmar": "ブーバー", "Magnemite": "コイル", "Magneton": "レアコイル", "Mankey": "マンキー", "Marowak": "ガラガラ", "Meowth": "ニャース", "Metapod": "トランセル", "Mew": "ミュウ", "Mewtwo": "ミュウツー", "Moltres": "ファイヤー", "MrMime": "バリヤード", "Muk": "ベトベトン", "Nidoking": "ニドキング", "Nidoqueen": "ニドクイン", "Nidorina": "ニドリーナ", "Nidorino": "ニドリーノ", "Ninetales": "キュウコン", "Oddish": "ナゾノクサ", "Omanyte": "オムナイト", "Omastar": "オムスター", "Onix": "イワーク", "Paras": "パラス", "Parasect": "パラセクト", "Persian": "ペルシアン", "Pidgeot": "ピジョット", "Pidgeotto": "ピジョン", "Pidgey": "ポッポ", "Pikachu": "ピカチュウ", "Pinsir": "カイロス", "Poliwag": "ニョロモ", "Poliwhirl": "ニョロゾ", "Poliwrath": "ニョロボン", "Ponyta": "ポニータ", "Porygon": "ポリゴン", "Primeape": "オコリザル", "Psyduck": "コダック", "Raichu": "ライチュウ", "Rapidash": "ギャロップ", "Raticate": "ラッタ", "Rattata": "コラッタ", "Rhydon": "サイドン", "Rhyhorn": "サイホーン", "Sandshrew": "サンド", "Sandslash": "サンドパン", "Scyther": "ストライク", "Seadra": "シードラ", "Seaking": "アズマオウ", "Seel": "パウワウ", "Shellder": "シェルダー", "Slowbro": "ヤドラン", "Slowpoke": "ヤドン", "Snorlax": "カビゴン", "Spearow": "オニスズメ", "Squirtle": "ゼニガメ", "Starmie": "スターミー", "Staryu": "ヒトデマン", "Tangela": "モンジャラ", "Tauros": "ケンタロス", "Tentacool": "メノクラゲ", "Tentacruel": "ドククラゲ", "Vaporeon": "シャワーズ", "Venomoth": "モルフォン", "Venonat": "コンパン", "Venusaur": "フシギバナ", "Victreebel": "ウツボット", "Vileplume": "ラフレシア", "Voltorb": "ビリリダマ", "Vulpix": "ロコン", "Wartortle": "カメール", "Weedle": "ビードル", "Weepinbell": "ウツドン", "Weezing": "マタドガス", "Wigglytuff": "プクリン", "Zapdos": "サンダー", "Zubat": "ズバット" } confidence = str(round(max(pred[0]), 3)) predicted_pokemon_name = pokemon_names[np.argmax(pred)] # Translate pokemon name to japanese predicted_pokemon_name_jp = pokemon_names_jp[predicted_pokemon_name] data = dict(success=True, predicted=predicted_pokemon_name, predicted_jp=predicted_pokemon_name_jp, confidence=confidence) ## return jsonify(data) #response = make_response(json.dumps(data, ensure_ascii=False)) #response.headers['Access-Control-Allow-Origin'] = 'https://kagawa-ai-lesson.firebaseapp.com, http://localhost:8080' #response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, PATCH, DELETE, OPTIONS' #response.headers['Access-Control-Allow-Headers'] = 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' #response.headers['Access-Control-Expose-Headers'] = 'Content-Length,Content-Range' #return response # Set CORS headers for the main request headers = { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json' } return (json.dumps(data, ensure_ascii=False), 200, headers)
[ "tensorflow.keras.models.load_model", "numpy.argmax", "cv2.imdecode", "numpy.expand_dims", "json.dumps", "google.cloud.storage.Client", "numpy.array", "numpy.fromstring" ]
[((409, 425), 'google.cloud.storage.Client', 'storage.Client', ([], {}), '()\n', (423, 425), False, 'from google.cloud import storage\n'), ((622, 656), 'tensorflow.keras.models.load_model', 'models.load_model', (['"""/tmp/tmp.hdf5"""'], {}), "('/tmp/tmp.hdf5')\n", (639, 656), False, 'from tensorflow.keras import models\n'), ((2263, 2301), 'numpy.fromstring', 'np.fromstring', (['image_decoded', 'np.uint8'], {}), '(image_decoded, np.uint8)\n', (2276, 2301), True, 'import numpy as np\n'), ((2318, 2358), 'cv2.imdecode', 'cv.imdecode', (['temp_array', 'cv.IMREAD_COLOR'], {}), '(temp_array, cv.IMREAD_COLOR)\n', (2329, 2358), True, 'import cv2 as cv\n'), ((2475, 2510), 'numpy.expand_dims', 'np.expand_dims', (['image_array'], {'axis': '(0)'}), '(image_array, axis=0)\n', (2489, 2510), True, 'import numpy as np\n'), ((10361, 10376), 'numpy.argmax', 'np.argmax', (['pred'], {}), '(pred)\n', (10370, 10376), True, 'import numpy as np\n'), ((11365, 11401), 'json.dumps', 'json.dumps', (['data'], {'ensure_ascii': '(False)'}), '(data, ensure_ascii=False)\n', (11375, 11401), False, 'import json\n'), ((2377, 2396), 'numpy.array', 'np.array', (['image_obj'], {}), '(image_obj)\n', (2385, 2396), True, 'import numpy as np\n')]
import sys, os sys.path.append(os.path.abspath(__file__).split('test')[0]) import pandas as pd import numpy as np from pyml.supervised.linear_regression.LinearRegression import LinearRegression """ ------------------------------------------------------------------------------------------------------------------------ SIMPLE LINEAR REGRESSION ------------------------------------------------------------------------------------------------------------------------ """ #----------------------------------------------------------------------------------------------------------------------- #---------------------------------------------- OBTENCION DATOS -------------------------------------------------------- #----------------------------------------------------------------------------------------------------------------------- data = pd.read_csv('../../../data/ex1data1.txt', sep=",", header=None) #Cargamos los datos data.columns = ["population", "profit"] print("\n--------------------------------------------") print("--------------------------------------------") print(" SIMPLE LINEAR REGRESSION ") print("--------------------------------------------") print("--------------------------------------------\n") print(data.head()) #Imprimimos los datos print(data.describe()) num_col = data.shape[0] #Numero de columnas: numero de ejemplos num_filas = data.shape[1] #Numero de filas: numero de features X = np.matrix([np.ones(num_col), data['population']]).T #Cada fila es un ejemplo, cada columna es un feature del ejemplo y = np.matrix(data['profit']).T #Vector columna #----------------------------------------------------------------------------------------------------------------------- #---------------------------------------------------- TEST ------------------------------------------------------------- #----------------------------------------------------------------------------------------------------------------------- norm_linear_regression = LinearRegression(X, y, axis=1) norm_linear_regression.norm_equation() print("\n--------------------------------------------") print(" RESULTADOS ") print("--------------------------------------------\n") print("\nMinimizacion parámetros theta: ", norm_linear_regression.theta) print("Dimension theta: ", norm_linear_regression.theta.shape) print("Theta como array: ", np.ravel(norm_linear_regression.theta)) print("Prueba prediccion de: ", 6.1101, " con nuestro modelo de Linear Regression: ", norm_linear_regression.prediccion(np.matrix([1, 6.1101]).T)) norm_linear_regression.plot_regression("Plot sin division", "Poblacion", "Beneficio") #----------------------------------------------------------------------------------------------------------------------- #---------------------------------------------- DIVISION Y TEST -------------------------------------------------------- #----------------------------------------------------------------------------------------------------------------------- norm_linear_regression = LinearRegression(X, y, axis=1, split=0.2) norm_linear_regression.norm_equation() norm_linear_regression.plot_regression("Training set", "Poblacion", "Beneficio") norm_linear_regression.plot_regression_test("Test set", "Poblacion", "Beneficio") """ ------------------------------------------------------------------------------------------------------------------------ EJEMPLO SALARIOS ------------------------------------------------------------------------------------------------------------------------ """ #----------------------------------------------------------------------------------------------------------------------- #---------------------------------------------- OBTENCION DATOS -------------------------------------------------------- #----------------------------------------------------------------------------------------------------------------------- data_salarios = pd.read_csv("../../../data/Salary_Data.csv", sep=",") print("\n--------------------------------------------") print(" SALARIOS ") print("--------------------------------------------\n") print(data_salarios.head()) print(data_salarios.describe()) num_filas = data_salarios.values.shape[0] num_col = data_salarios.values.shape[1] X_salarios = np.matrix([np.ones(num_filas), np.ravel(data_salarios.iloc[:, :-1].values)]).T y_salarios = np.matrix(data_salarios.iloc[:, -1].values).T #----------------------------------------------------------------------------------------------------------------------- #---------------------------------------------- DIVISION Y TEST -------------------------------------------------------- #----------------------------------------------------------------------------------------------------------------------- norm_linear_regression = LinearRegression(X_salarios, y_salarios, axis=1, split=0.2) norm_linear_regression.norm_equation() norm_linear_regression.plot_regression("Training set", "Experiencia", "Salario") norm_linear_regression.plot_regression_test("Test set", "Experiencia", "Salario") """ ------------------------------------------------------------------------------------------------------------------------ MULTIPLE LINEAR REGRESSION ------------------------------------------------------------------------------------------------------------------------ """ print("\n--------------------------------------------") print("--------------------------------------------") print(" MULTIPLE LINEAR REGRESSION ") print("--------------------------------------------") print("--------------------------------------------\n") #----------------------------------------------------------------------------------------------------------------------- #---------------------------------------------- OBTENCION DATOS -------------------------------------------------------- #----------------------------------------------------------------------------------------------------------------------- data = pd.read_csv('../../../data/ex1data2.txt', sep=",", header=None) #Cargamos los datos data.columns = ["size", "n_bedrooms", "price"] print(data.head()) #Imprimimos los datos print(data.describe()) num_col = data.shape[0] #Numero de columnas: numero de ejemplos num_filas = data.shape[1] #Numero de filas: numero de features X = np.matrix([np.ones(num_col), data['size'], data['n_bedrooms']]).T #Cada fila es un ejemplo, cada columna es un feature del ejemplo y = np.matrix(data['price']).T #Vector columna #----------------------------------------------------------------------------------------------------------------------- #---------------------------------------------------- TEST ------------------------------------------------------------- #----------------------------------------------------------------------------------------------------------------------- print("\n--------------------------------------------") print(" RESULTADOS CON FEATURE NORMALIZATION ") print("--------------------------------------------\n") norm_linear_regression = LinearRegression(X, y, axis=1) norm_linear_regression.aplicar_feature_normalization(include_y=True) norm_linear_regression.norm_equation() print("\nMinimizacion parámetros theta: ", norm_linear_regression.theta) print("Dimension theta: ", norm_linear_regression.theta.shape) print("Theta como array: ", np.ravel(norm_linear_regression.theta)) print("Prueba prediccion de: ", 2104, " size y ", 3, " numero de camas, con nuestro modelo de Linear Regression: " , norm_linear_regression.prediccion(np.matrix([np.ones(1), np.matrix([2104]), np.matrix([3])])), ", valor real: ", y[0]) print("\n--------------------------------------------") print(" RESULTADOS SIN FEATURE NORMALIZATION ") print("--------------------------------------------\n") norm_linear_regression = LinearRegression(X, y, axis=1) norm_linear_regression.norm_equation() print("\nMinimizacion parámetros theta: ", norm_linear_regression.theta) print("Dimension theta: ", norm_linear_regression.theta.shape) print("Theta como array: ", np.ravel(norm_linear_regression.theta)) print("Prueba prediccion de: ", 2104, " size y ", 3, " numero de camas, con nuestro modelo de Linear Regression: " , norm_linear_regression.prediccion(np.matrix([np.ones(1), np.matrix([2104]), np.matrix([3])])), ", valor real: ", y[0]) """ ------------------------------------------------------------------------------------------------------------------------ EJEMPLO REAL STATE ------------------------------------------------------------------------------------------------------------------------ """ #----------------------------------------------------------------------------------------------------------------------- #---------------------------------------------- OBTENCION DATOS -------------------------------------------------------- #----------------------------------------------------------------------------------------------------------------------- data = pd.read_csv("../../../data/50_Startups.csv", sep=",") print("\n--------------------------------------------") print(" REAL STATE ") print("--------------------------------------------\n") print(data.head()) print(data.describe()) data_encoded = pd.get_dummies(data) num_filas = data_encoded.values.shape[0] num_col = data_encoded.values.shape[1] X = np.matrix([np.ones(num_filas)]) X = np.concatenate((X, data_encoded.loc[:, data_encoded.columns != 'Profit'].values.T)).T y = np.matrix(data_encoded['Profit'].values).T #----------------------------------------------------------------------------------------------------------------------- #---------------------------------------------------- TEST ------------------------------------------------------------- #----------------------------------------------------------------------------------------------------------------------- print("\n--------------------------------------------") print(" RESULTADOS SIN FEATURE NORMALIZATION ") print("--------------------------------------------\n") norm_linear_regression = LinearRegression(X, y, axis=1) norm_linear_regression.norm_equation() print("\nMinimizacion parámetros theta: ", norm_linear_regression.theta) print("Dimension theta: ", norm_linear_regression.theta.shape) print("Theta como array: ", np.ravel(norm_linear_regression.theta)) print("Prueba prediccion: ", norm_linear_regression.prediccion(X[0, :].T), ", valor real: ", y[0])
[ "numpy.matrix", "os.path.abspath", "numpy.concatenate", "numpy.ravel", "pandas.read_csv", "pandas.get_dummies", "numpy.ones", "pyml.supervised.linear_regression.LinearRegression.LinearRegression" ]
[((894, 957), 'pandas.read_csv', 'pd.read_csv', (['"""../../../data/ex1data1.txt"""'], {'sep': '""","""', 'header': 'None'}), "('../../../data/ex1data1.txt', sep=',', header=None)\n", (905, 957), True, 'import pandas as pd\n'), ((2303, 2333), 'pyml.supervised.linear_regression.LinearRegression.LinearRegression', 'LinearRegression', (['X', 'y'], {'axis': '(1)'}), '(X, y, axis=1)\n', (2319, 2333), False, 'from pyml.supervised.linear_regression.LinearRegression import LinearRegression\n'), ((3370, 3411), 'pyml.supervised.linear_regression.LinearRegression.LinearRegression', 'LinearRegression', (['X', 'y'], {'axis': '(1)', 'split': '(0.2)'}), '(X, y, axis=1, split=0.2)\n', (3386, 3411), False, 'from pyml.supervised.linear_regression.LinearRegression import LinearRegression\n'), ((4317, 4370), 'pandas.read_csv', 'pd.read_csv', (['"""../../../data/Salary_Data.csv"""'], {'sep': '""","""'}), "('../../../data/Salary_Data.csv', sep=',')\n", (4328, 4370), True, 'import pandas as pd\n'), ((5215, 5274), 'pyml.supervised.linear_regression.LinearRegression.LinearRegression', 'LinearRegression', (['X_salarios', 'y_salarios'], {'axis': '(1)', 'split': '(0.2)'}), '(X_salarios, y_salarios, axis=1, split=0.2)\n', (5231, 5274), False, 'from pyml.supervised.linear_regression.LinearRegression import LinearRegression\n'), ((6465, 6528), 'pandas.read_csv', 'pd.read_csv', (['"""../../../data/ex1data2.txt"""'], {'sep': '""","""', 'header': 'None'}), "('../../../data/ex1data2.txt', sep=',', header=None)\n", (6476, 6528), True, 'import pandas as pd\n'), ((7776, 7806), 'pyml.supervised.linear_regression.LinearRegression.LinearRegression', 'LinearRegression', (['X', 'y'], {'axis': '(1)'}), '(X, y, axis=1)\n', (7792, 7806), False, 'from pyml.supervised.linear_regression.LinearRegression import LinearRegression\n'), ((8562, 8592), 'pyml.supervised.linear_regression.LinearRegression.LinearRegression', 'LinearRegression', (['X', 'y'], {'axis': '(1)'}), '(X, y, axis=1)\n', (8578, 8592), False, 'from pyml.supervised.linear_regression.LinearRegression import LinearRegression\n'), ((9775, 9828), 'pandas.read_csv', 'pd.read_csv', (['"""../../../data/50_Startups.csv"""'], {'sep': '""","""'}), "('../../../data/50_Startups.csv', sep=',')\n", (9786, 9828), True, 'import pandas as pd\n'), ((10044, 10064), 'pandas.get_dummies', 'pd.get_dummies', (['data'], {}), '(data)\n', (10058, 10064), True, 'import pandas as pd\n'), ((10884, 10914), 'pyml.supervised.linear_regression.LinearRegression.LinearRegression', 'LinearRegression', (['X', 'y'], {'axis': '(1)'}), '(X, y, axis=1)\n', (10900, 10914), False, 'from pyml.supervised.linear_regression.LinearRegression import LinearRegression\n'), ((1819, 1844), 'numpy.matrix', 'np.matrix', (["data['profit']"], {}), "(data['profit'])\n", (1828, 1844), True, 'import numpy as np\n'), ((2704, 2742), 'numpy.ravel', 'np.ravel', (['norm_linear_regression.theta'], {}), '(norm_linear_regression.theta)\n', (2712, 2742), True, 'import numpy as np\n'), ((4777, 4820), 'numpy.matrix', 'np.matrix', (['data_salarios.iloc[:, -1].values'], {}), '(data_salarios.iloc[:, -1].values)\n', (4786, 4820), True, 'import numpy as np\n'), ((7119, 7143), 'numpy.matrix', 'np.matrix', (["data['price']"], {}), "(data['price'])\n", (7128, 7143), True, 'import numpy as np\n'), ((8080, 8118), 'numpy.ravel', 'np.ravel', (['norm_linear_regression.theta'], {}), '(norm_linear_regression.theta)\n', (8088, 8118), True, 'import numpy as np\n'), ((8798, 8836), 'numpy.ravel', 'np.ravel', (['norm_linear_regression.theta'], {}), '(norm_linear_regression.theta)\n', (8806, 8836), True, 'import numpy as np\n'), ((10186, 10274), 'numpy.concatenate', 'np.concatenate', (["(X, data_encoded.loc[:, data_encoded.columns != 'Profit'].values.T)"], {}), "((X, data_encoded.loc[:, data_encoded.columns != 'Profit'].\n values.T))\n", (10200, 10274), True, 'import numpy as np\n'), ((10276, 10316), 'numpy.matrix', 'np.matrix', (["data_encoded['Profit'].values"], {}), "(data_encoded['Profit'].values)\n", (10285, 10316), True, 'import numpy as np\n'), ((11120, 11158), 'numpy.ravel', 'np.ravel', (['norm_linear_regression.theta'], {}), '(norm_linear_regression.theta)\n', (11128, 11158), True, 'import numpy as np\n'), ((10161, 10179), 'numpy.ones', 'np.ones', (['num_filas'], {}), '(num_filas)\n', (10168, 10179), True, 'import numpy as np\n'), ((1685, 1701), 'numpy.ones', 'np.ones', (['num_col'], {}), '(num_col)\n', (1692, 1701), True, 'import numpy as np\n'), ((2864, 2886), 'numpy.matrix', 'np.matrix', (['[1, 6.1101]'], {}), '([1, 6.1101])\n', (2873, 2886), True, 'import numpy as np\n'), ((4696, 4714), 'numpy.ones', 'np.ones', (['num_filas'], {}), '(num_filas)\n', (4703, 4714), True, 'import numpy as np\n'), ((4716, 4759), 'numpy.ravel', 'np.ravel', (['data_salarios.iloc[:, :-1].values'], {}), '(data_salarios.iloc[:, :-1].values)\n', (4724, 4759), True, 'import numpy as np\n'), ((6985, 7001), 'numpy.ones', 'np.ones', (['num_col'], {}), '(num_col)\n', (6992, 7001), True, 'import numpy as np\n'), ((31, 56), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (46, 56), False, 'import sys, os\n'), ((8288, 8298), 'numpy.ones', 'np.ones', (['(1)'], {}), '(1)\n', (8295, 8298), True, 'import numpy as np\n'), ((8300, 8317), 'numpy.matrix', 'np.matrix', (['[2104]'], {}), '([2104])\n', (8309, 8317), True, 'import numpy as np\n'), ((8319, 8333), 'numpy.matrix', 'np.matrix', (['[3]'], {}), '([3])\n', (8328, 8333), True, 'import numpy as np\n'), ((9006, 9016), 'numpy.ones', 'np.ones', (['(1)'], {}), '(1)\n', (9013, 9016), True, 'import numpy as np\n'), ((9018, 9035), 'numpy.matrix', 'np.matrix', (['[2104]'], {}), '([2104])\n', (9027, 9035), True, 'import numpy as np\n'), ((9037, 9051), 'numpy.matrix', 'np.matrix', (['[3]'], {}), '([3])\n', (9046, 9051), True, 'import numpy as np\n')]
import unittest import sys sys.path.append('..') from scipy.stats import hypergeom, fisher_exact import numpy as np from server.from_uniprot_get_go import create_all_go_map from server.go_processing import process_ontology from server.add_go_from_higherup import enrich_cnag_map from server.cnag_list_to_go import find_enriched_groups class BaseTestCase(unittest.TestCase): def test_create_all_go_map(self): '''Creates a dictionary of all GOs from the Uniprot file as keys and a dictionary of all CNAG IDs as keys''' GO_map, CNAG_map = create_all_go_map("test/test_uniprot.txt", "test/uniprot_output.txt") test_go_map = {'GO:0005886': {'CNAG_07636'}, 'GO:0008047': {'CNAG_07636'}, 'GO:0005774': {'CNAG_00025'}, 'GO:0015369': {'CNAG_00025'}} test_cnag_map = {'CNAG_07636': {'GO:0008047', 'GO:0005886'}, 'CNAG_00025': {'GO:0005774', 'GO:0015369'}} self.assertEqual(GO_map, test_go_map) self.assertEqual(CNAG_map, test_cnag_map) def test_create_all_go_map_one_go(self): '''Creates a dictionary of all GOs from the Uniprot file as keys and a dictionary of all CNAG IDs as keys''' GO_map, CNAG_map = create_all_go_map("test/test_go_uniprot.txt", "test/uniprot_output.txt") test_go_map = {'GO:0000001': {'CNAG_07636'}, 'GO:0006594': {'CNAG_00025'}, 'GO:0006871': {'CNAG_07724'}, 'GO:0048308': {'CNAG_05655'}, 'GO:0048311': {'CNAG_05449'}, 'GO:0000002': {'CNAG_00156'}, 'GO:0007005': {'CNAG_07701'}} test_cnag_map = {'CNAG_07636': {'GO:0000001'}, 'CNAG_00025': {'GO:0006594'}, 'CNAG_07724': {'GO:0006871'}, 'CNAG_05655': {'GO:0048308'}, 'CNAG_05449': {'GO:0048311'}, 'CNAG_00156': {'GO:0000002'}, 'CNAG_07701': {'GO:0007005'}} self.assertEqual(GO_map, test_go_map) self.assertEqual(CNAG_map, test_cnag_map) def test_process_onthology(self): '''Processes go-basic.obo file to extract higher GO terms''' GO_association = process_ontology("test/test_go.txt", "test/test_go_association.txt") test = {'GO:0000001': {'GO:0048311', 'GO:0048308'}, 'GO:0006594': {'GO:0048311', 'GO:0048308'}, 'GO:0006871': {'GO:0048311', 'GO:0048308'}, 'GO:0000002': {'GO:0007005'}} self.assertEqual(GO_association, test) def test_enrich_cnag_map(self): '''Creates a dictionary and a file with CNAG IDs as keys and GO terms as values; includes higher GO categories. Returns CNAG_map['CNAG_XXXXX'] = (GO1, GO2...)''' go_basic = "test/test_go.txt" uniprot_proteome = "test/test_go_uniprot.txt" CNAG_to_func = "test/test_cnag_to_func.txt" CNAG_to_GO = "test/test_cnag_to_go.txt" GO_to_CNAG = "test/test_go_to_cnag.txt" go_association = "test/test_go_association.txt" GO_map, CNAG_map = enrich_cnag_map(go_basic, uniprot_proteome, CNAG_to_func, CNAG_to_GO, GO_to_CNAG, go_association) test_cnag_map = {'CNAG_07636': {'GO:0048308', 'GO:0000001', 'GO:0048311'}, 'CNAG_00025': {'GO:0048308', 'GO:0048311', 'GO:0006594'}, 'CNAG_07724': {'GO:0006871', 'GO:0048308', 'GO:0048311'}, 'CNAG_05655': {'GO:0048308'}, 'CNAG_05449': {'GO:0048311'}, 'CNAG_00156': {'GO:0000002', 'GO:0007005'}, 'CNAG_07701': {'GO:0007005'}} test_go_map = {'GO:0048311': {'CNAG_05449', 'CNAG_07724', 'CNAG_07636', 'CNAG_00025'}, 'GO:0000001': {'CNAG_07636'}, 'GO:0048308': {'CNAG_07724', 'CNAG_07636', 'CNAG_05655', 'CNAG_00025'}, 'GO:0006594': {'CNAG_00025'}, 'GO:0006871': {'CNAG_07724'}, 'GO:0000002': {'CNAG_00156'}, 'GO:0007005': {'CNAG_07701', 'CNAG_00156'}} self.assertEqual(test_cnag_map, CNAG_map) self.assertEqual(test_go_map, GO_map) def test_find_enriched_groups(self): sample_test = 8 sample_control = 2 number_of_test_annotations = 1 number_of_control_annotations = 5 _, p = fisher_exact(np.array([[sample_test, sample_control],[number_of_test_annotations, number_of_control_annotations]])) self.assertEqual(round(p, 4), 0.035) # https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.fisher_exact.html#scipy.stats.fisher_exact if __name__ == "__main__": unittest.main()
[ "sys.path.append", "unittest.main", "server.go_processing.process_ontology", "numpy.array", "server.add_go_from_higherup.enrich_cnag_map", "server.from_uniprot_get_go.create_all_go_map" ]
[((28, 49), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (43, 49), False, 'import sys\n'), ((4986, 5001), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4999, 5001), False, 'import unittest\n'), ((576, 645), 'server.from_uniprot_get_go.create_all_go_map', 'create_all_go_map', (['"""test/test_uniprot.txt"""', '"""test/uniprot_output.txt"""'], {}), "('test/test_uniprot.txt', 'test/uniprot_output.txt')\n", (593, 645), False, 'from server.from_uniprot_get_go import create_all_go_map\n'), ((1286, 1358), 'server.from_uniprot_get_go.create_all_go_map', 'create_all_go_map', (['"""test/test_go_uniprot.txt"""', '"""test/uniprot_output.txt"""'], {}), "('test/test_go_uniprot.txt', 'test/uniprot_output.txt')\n", (1303, 1358), False, 'from server.from_uniprot_get_go import create_all_go_map\n'), ((2335, 2403), 'server.go_processing.process_ontology', 'process_ontology', (['"""test/test_go.txt"""', '"""test/test_go_association.txt"""'], {}), "('test/test_go.txt', 'test/test_go_association.txt')\n", (2351, 2403), False, 'from server.go_processing import process_ontology\n'), ((3218, 3319), 'server.add_go_from_higherup.enrich_cnag_map', 'enrich_cnag_map', (['go_basic', 'uniprot_proteome', 'CNAG_to_func', 'CNAG_to_GO', 'GO_to_CNAG', 'go_association'], {}), '(go_basic, uniprot_proteome, CNAG_to_func, CNAG_to_GO,\n GO_to_CNAG, go_association)\n', (3233, 3319), False, 'from server.add_go_from_higherup import enrich_cnag_map\n'), ((4647, 4753), 'numpy.array', 'np.array', (['[[sample_test, sample_control], [number_of_test_annotations,\n number_of_control_annotations]]'], {}), '([[sample_test, sample_control], [number_of_test_annotations,\n number_of_control_annotations]])\n', (4655, 4753), True, 'import numpy as np\n')]
""" Test the CONMIN optimizer component """ import unittest import numpy # pylint: disable=F0401,E0611 from openmdao.main.api import Assembly, Component, VariableTree, set_as_top, Driver from openmdao.main.datatypes.api import Float, Array, Str, VarTree from openmdao.lib.casehandlers.api import ListCaseRecorder from openmdao.main.interfaces import IHasParameters, implements from openmdao.main.hasparameters import HasParameters from openmdao.util.decorators import add_delegate from openmdao.lib.drivers.conmindriver import CONMINdriver from openmdao.util.testutil import assert_rel_error class OptRosenSuzukiComponent(Component): """ From the CONMIN User's Manual: EXAMPLE 1 - CONSTRAINED ROSEN-SUZUKI FUNCTION. NO GRADIENT INFORMATION. MINIMIZE OBJ = X(1)**2 - 5*X(1) + X(2)**2 - 5*X(2) + 2*X(3)**2 - 21*X(3) + X(4)**2 + 7*X(4) + 50 Subject to: G(1) = X(1)**2 + X(1) + X(2)**2 - X(2) + X(3)**2 + X(3) + X(4)**2 - X(4) - 8 .LE.0 G(2) = X(1)**2 - X(1) + 2*X(2)**2 + X(3)**2 + 2*X(4)**2 - X(4) - 10 .LE.0 G(3) = 2*X(1)**2 + 2*X(1) + X(2)**2 - X(2) + X(3)**2 - X(4) - 5 .LE.0 This problem is solved beginning with an initial X-vector of X = (1.0, 1.0, 1.0, 1.0) The optimum design is known to be OBJ = 6.000 and the corresponding X-vector is X = (0.0, 1.0, 2.0, -1.0) """ x = Array(iotype='in', low=-10, high=99) g = Array([1., 1., 1.], iotype='out') result = Float(iotype='out') obj_string = Str(iotype='out') opt_objective = Float(iotype='out') # pylint: disable=C0103 def __init__(self): super(OptRosenSuzukiComponent, self).__init__() self.x = numpy.array([1., 1., 1., 1.], dtype=float) self.result = 0. self.opt_objective = 6.*10.0 self.opt_design_vars = [0., 1., 2., -1.] def execute(self): """calculate the new objective value""" x = self.x self.result = (x[0]**2 - 5.*x[0] + x[1]**2 - 5.*x[1] + 2.*x[2]**2 - 21.*x[2] + x[3]**2 + 7.*x[3] + 50) self.obj_string = "Bad" #print "rosen", self.x self.g[0] = (x[0]**2 + x[0] + x[1]**2 - x[1] + x[2]**2 + x[2] + x[3]**2 - x[3] - 8) self.g[1] = (x[0]**2 - x[0] + 2*x[1]**2 + x[2]**2 + 2*x[3]**2 - x[3] - 10) self.g[2] = (2*x[0]**2 + 2*x[0] + x[1]**2 - x[1] + x[2]**2 - x[3] - 5) #print self.x, self.g class RosenSuzuki2D(Component): """ RosenSuzuki with 2D input. """ x = Array(iotype='in', low=-10, high=99) result = Float(iotype='out') opt_objective = Float(iotype='out') # pylint: disable=C0103 def __init__(self): super(RosenSuzuki2D, self).__init__() self.x = numpy.array([[1., 1.], [1., 1.]], dtype=float) self.result = 0. self.opt_objective = 6.*10.0 self.opt_design_vars = [0., 1., 2., -1.] def execute(self): """calculate the new objective value""" self.result = (self.x[0][0]**2 - 5.*self.x[0][0] + self.x[0][1]**2 - 5.*self.x[0][1] + 2.*self.x[1][0]**2 - 21.*self.x[1][0] + self.x[1][1]**2 + 7.*self.x[1][1] + 50) class RosenSuzukiMixed(Component): """ RosenSuzuki with mixed scalar and 1D inputs. """ x0 = Float(iotype='in', low=-10, high=99) x12 = Array(iotype='in', low=-10, high=99) x3 = Float(iotype='in', low=-10, high=99) result = Float(iotype='out') opt_objective = Float(iotype='out') # pylint: disable=C0103 def __init__(self): super(RosenSuzukiMixed, self).__init__() self.x0 = 1. self.x12 = numpy.array([1., 1.], dtype=float) self.x3 = 1. self.result = 0. self.opt_objective = 6.*10.0 self.opt_design_vars = [0., 1., 2., -1.] def execute(self): """calculate the new objective value""" self.result = (self.x0**2 - 5.*self.x0 + self.x12[0]**2 - 5.*self.x12[0] + 2.*self.x12[1]**2 - 21.*self.x12[1] + self.x3**2 + 7.*self.x3 + 50) class CONMINdriverTestCase(unittest.TestCase): """test CONMIN optimizer component""" def setUp(self): self.top = set_as_top(Assembly()) self.top.add('driver', CONMINdriver()) self.top.add('comp', OptRosenSuzukiComponent()) self.top.driver.workflow.add('comp') self.top.driver.iprint = 0 self.top.driver.itmax = 30 def test_opt1(self): # Run with scalar parameters, scalar constraints, and OpenMDAO gradient. self.top.driver.add_objective('10*comp.result') # pylint: disable=C0301 map(self.top.driver.add_parameter, ['comp.x[0]', 'comp.x[1]', 'comp.x[2]', 'comp.x[3]']) map(self.top.driver.add_constraint, [ 'comp.x[0]**2+comp.x[0]+comp.x[1]**2-comp.x[1]+comp.x[2]**2+comp.x[2]+comp.x[3]**2-comp.x[3] < 8', 'comp.x[0]**2-comp.x[0]+2*comp.x[1]**2+comp.x[2]**2+2*comp.x[3]**2-comp.x[3] < 10', '2*comp.x[0]**2+2*comp.x[0]+comp.x[1]**2-comp.x[1]+comp.x[2]**2-comp.x[3] < 5']) self.top.recorders = [ListCaseRecorder()] self.top.driver.iprint = 0 self.top.run() # pylint: disable=E1101 assert_rel_error(self, self.top.comp.opt_objective, self.top.driver.eval_objective(), 0.01) assert_rel_error(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.comp.x[0], 0.05) assert_rel_error(self, self.top.comp.opt_design_vars[1], self.top.comp.x[1], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[2], self.top.comp.x[2], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[3], self.top.comp.x[3], 0.05) cases = self.top.recorders[0].get_iterator() end_case = cases[-1] self.assertEqual(self.top.comp.x[1], end_case.get_input('comp.x[1]')) self.assertEqual(10*self.top.comp.result, end_case.get_output('_pseudo_0.out0')) def test_opt1_a(self): # Run with scalar parameters, 1D constraint, and OpenMDAO gradient. self.top.driver.add_objective('10*comp.result') # pylint: disable=C0301 map(self.top.driver.add_parameter, ['comp.x[0]', 'comp.x[1]', 'comp.x[2]', 'comp.x[3]']) self.top.driver.add_constraint('comp.g <= 0') self.top.driver.iprint = 0 self.top.run() # pylint: disable=E1101 assert_rel_error(self, self.top.comp.opt_objective, self.top.driver.eval_objective(), 0.01) assert_rel_error(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.comp.x[0], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[1], self.top.comp.x[1], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[2], self.top.comp.x[2], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[3], self.top.comp.x[3], 0.05) def test_opt1_with_CONMIN_gradient(self): # Note: all other tests use OpenMDAO gradient self.top.driver.add_objective('10*comp.result') self.top.driver.add_parameter('comp.x[0]', fd_step=.00001) self.top.driver.add_parameter('comp.x[1]', fd_step=.00001) self.top.driver.add_parameter('comp.x[2]', fd_step=.00001) self.top.driver.add_parameter('comp.x[3]', fd_step=.00001) # pylint: disable=C0301 map(self.top.driver.add_constraint, [ 'comp.x[0]**2+comp.x[0]+comp.x[1]**2-comp.x[1]+comp.x[2]**2+comp.x[2]+comp.x[3]**2-comp.x[3] < 8', 'comp.x[0]**2-comp.x[0]+2*comp.x[1]**2+comp.x[2]**2+2*comp.x[3]**2-comp.x[3] < 10', '2*comp.x[0]**2+2*comp.x[0]+comp.x[1]**2-comp.x[1]+comp.x[2]**2-comp.x[3] < 5']) self.top.driver.conmin_diff = True self.top.run() # pylint: disable=E1101 assert_rel_error(self, self.top.comp.opt_objective, self.top.driver.eval_objective(), 0.01) assert_rel_error(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.comp.x[0], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[1], self.top.comp.x[1], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[2], self.top.comp.x[2], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[3], self.top.comp.x[3], 0.05) def test_opt1_with_CONMIN_gradient_a(self): # Scalar parameters, array constraint, CONMIN gradient. # Note: all other tests use OpenMDAO gradient self.top.driver.add_objective('10*comp.result') self.top.driver.add_parameter('comp.x[0]', fd_step=.00001) self.top.driver.add_parameter('comp.x[1]', fd_step=.00001) self.top.driver.add_parameter('comp.x[2]', fd_step=.00001) self.top.driver.add_parameter('comp.x[3]', fd_step=.00001) self.top.driver.add_constraint('comp.g <= 0') self.top.driver.conmin_diff = True self.top.run() # pylint: disable=E1101 assert_rel_error(self, self.top.comp.opt_objective, self.top.driver.eval_objective(), 0.01) assert_rel_error(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.comp.x[0], 0.05) assert_rel_error(self, self.top.comp.opt_design_vars[1], self.top.comp.x[1], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[2], self.top.comp.x[2], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[3], self.top.comp.x[3], 0.05) def test_opt1_flippedconstraints(self): self.top.driver.add_objective('10*comp.result') map(self.top.driver.add_parameter, ['comp.x[0]', 'comp.x[1]', 'comp.x[2]', 'comp.x[3]']) # pylint: disable=C0301 map(self.top.driver.add_constraint, [ '8 > comp.x[0]**2+comp.x[0]+comp.x[1]**2-comp.x[1]+comp.x[2]**2+comp.x[2]+comp.x[3]**2-comp.x[3]', '10 > comp.x[0]**2-comp.x[0]+2*comp.x[1]**2+comp.x[2]**2+2*comp.x[3]**2-comp.x[3]', '5 > 2*comp.x[0]**2+2*comp.x[0]+comp.x[1]**2-comp.x[1]+comp.x[2]**2-comp.x[3]']) self.top.run() # pylint: disable=E1101 assert_rel_error(self, self.top.comp.opt_objective, self.top.driver.eval_objective(), 0.01) assert_rel_error(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.comp.x[0], 0.05) assert_rel_error(self, self.top.comp.opt_design_vars[1], self.top.comp.x[1], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[2], self.top.comp.x[2], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[3], self.top.comp.x[3], 0.05) def test_gradient_step_size_large(self): # Test that a larger value of fd step-size is less acurate self.top.driver.add_objective('10*comp.result') map(self.top.driver.add_parameter, ['comp.x[0]', 'comp.x[1]', 'comp.x[2]', 'comp.x[3]']) # pylint: disable=C0301 map(self.top.driver.add_constraint, [ 'comp.x[0]**2+comp.x[0]+comp.x[1]**2-comp.x[1]+comp.x[2]**2+comp.x[2]+comp.x[3]**2-comp.x[3] < 8.', 'comp.x[0]**2-comp.x[0]+2*comp.x[1]**2+comp.x[2]**2+2*comp.x[3]**2-comp.x[3] < 10.', '2*comp.x[0]**2+2*comp.x[0]+comp.x[1]**2-comp.x[1]+comp.x[2]**2-comp.x[3] < 5.']) self.top.driver.conmin_diff = True self.top.driver.fdch = 1.0e-6 self.top.driver.fdchm = 1.0e-6 self.top.run() baseerror = abs(self.top.comp.opt_objective - self.top.driver.eval_objective()) self.top.driver.fdch = .3 self.top.driver.fdchm = .3 self.top.comp.x = numpy.array([1., 1., 1., 1.], dtype=float) self.top.run() newerror = abs(self.top.comp.opt_objective - self.top.driver.eval_objective()) # pylint: disable=E1101 if baseerror > newerror: self.fail("Coarsening CONMIN gradient step size did not make the objective worse.") def test_linear_constraint_specification(self): # Note, just testing problem specification and setup self.top.driver.add_objective('comp.result') map(self.top.driver.add_parameter, ['comp.x[0]', 'comp.x[1]', 'comp.x[2]', 'comp.x[3]']) self.top.driver.add_constraint('comp.x[1] + 3.0*comp.x[2] > 3.0', linear=True) self.top.driver.add_constraint('comp.x[2] + comp.x[3] > 13.0', linear=True) self.top.driver.add_constraint('comp.x[1] - 0.73*comp.x[3]*comp.x[2] > -12.0', linear=False) self.top.driver.itmax = 1 self.top.run() self.assertEqual(self.top.driver._cons_is_linear[0], 1, 1e-6) self.assertEqual(self.top.driver._cons_is_linear[1], 1, 1e-6) self.assertEqual(self.top.driver._cons_is_linear[2], 0, 1e-6) lcons = self.top.driver.get_constraints(linear=True) self.assertTrue(len(lcons) == 2) self.assertTrue('comp.x[2]+comp.x[3]>13.0' in lcons) self.assertTrue('comp.x[1]-0.73*comp.x[3]*comp.x[2]>-12.0' not in lcons) lcons = self.top.driver.get_constraints(linear=False) self.assertTrue(len(lcons) == 1) self.assertTrue('comp.x[2]+comp.x[3]>13.0' not in lcons) self.assertTrue('comp.x[1]-0.73*comp.x[3]*comp.x[2]>-12.0' in lcons) def test_max_iteration(self): self.top.driver.add_objective('comp.result') map(self.top.driver.add_parameter, ['comp.x[0]', 'comp.x[1]', 'comp.x[2]', 'comp.x[3]']) self.top.driver.nscal = -1 self.top.driver.itmax = 2 # pylint: disable=C0301 self.top.run() # pylint: disable=E1101 self.assertEqual(self.top.driver.iter_count, 2) def test_remove(self): self.top.driver.add_objective('comp.result') map(self.top.driver.add_parameter, ['comp.x[0]', 'comp.x[1]', 'comp.x[2]', 'comp.x[3]']) # pylint: disable=C0301 map(self.top.driver.add_constraint, [ 'comp.x[0]**2+comp.x[0]+comp.x[1]**2-comp.x[1]+comp.x[2]**2+comp.x[2]+comp.x[3]**2-comp.x[3] < 8', 'comp.x[0]**2-comp.x[0]+2*comp.x[1]**2+comp.x[2]**2+2*comp.x[3]**2-comp.x[3] < 10', '2*comp.x[0]**2+2*comp.x[0]+comp.x[1]**2-comp.x[1]+comp.x[2]**2-comp.x[3] < 5']) self.top.remove('comp') self.assertEqual(self.top.driver.list_param_targets(), []) self.assertEqual(self.top.driver.list_constraints(), []) self.assertEqual(self.top.driver.get_objectives(), {}) def test_initial_run(self): # Test the fix that put run_iteration at the top # of the start_iteration method class MyComp(Component): x = Float(0.0, iotype='in', low=-10, high=10) xx = Float(0.0, iotype='in', low=-10, high=10) f_x = Float(iotype='out') y = Float(iotype='out') def execute(self): if self.xx != 1.0: self.raise_exception("Lazy", RuntimeError) self.f_x = 2.0*self.x self.y = self.x @add_delegate(HasParameters) class SpecialDriver(Driver): implements(IHasParameters) def execute(self): self.set_parameters([1.0]) top = set_as_top(Assembly()) top.add('comp', MyComp()) top.add('driver', CONMINdriver()) top.add('subdriver', SpecialDriver()) top.driver.workflow.add('subdriver') top.subdriver.workflow.add('comp') top.subdriver.add_parameter('comp.xx') top.driver.add_parameter('comp.x') top.driver.add_constraint('comp.y > 1.0') top.driver.add_objective('comp.f_x') top.run() class TestContainer(VariableTree): dummy1 = Float(desc='default value of 0.0') #this value is being grabbed by the optimizer dummy2 = Float(11.0) class TestComponent(Component): dummy_data = VarTree(TestContainer(), iotype='in') x = Float(iotype='out') def execute(self): self.x = (self.dummy_data.dummy1-3)**2 - self.dummy_data.dummy2 class TestAssembly(Assembly): def configure(self): self.add('dummy_top', TestContainer()) self.add('comp', TestComponent()) self.add('driver', CONMINdriver()) self.driver.workflow.add(['comp']) #self.driver.iprint = 4 #debug verbosity self.driver.add_objective('comp.x') self.driver.add_parameter('comp.dummy_data.dummy1', low=-10.0, high=10.0) class CONMINdriverTestCase2(unittest.TestCase): def test_vartree_opt(self): blah = set_as_top(TestAssembly()) blah.run() self.assertAlmostEqual(blah.comp.dummy_data.dummy1, 3.0, 1) #3.0 should be minimum class TestCase1D(unittest.TestCase): """Test using 1D array connections and 1D array constraint.""" def setUp(self): self.top = set_as_top(Assembly()) self.top.add('comp', OptRosenSuzukiComponent()) driver = self.top.add('driver', CONMINdriver()) driver.workflow.add('comp') driver.iprint = 0 driver.itmax = 30 driver.add_objective('10*comp.result') driver.add_parameter('comp.x') def test_conmin_gradient_a(self): # Run with 1D parameter, 1D constraint, and CONMIN gradient. self.top.driver.add_constraint('comp.g <= 0') self.top.driver.conmin_diff = True self.top.driver.fdch = .000001 self.top.driver.fdchm = .000001 self.top.run() # pylint: disable=E1101 assert_rel_error(self, self.top.comp.opt_objective, self.top.driver.eval_objective(), 0.01) assert_rel_error(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.comp.x[0], 0.05) assert_rel_error(self, self.top.comp.opt_design_vars[1], self.top.comp.x[1], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[2], self.top.comp.x[2], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[3], self.top.comp.x[3], 0.05) def test_conmin_gradient_s(self): # Run with 1D parameter, scalar constraints, and CONMIN gradient. # pylint: disable=C0301 map(self.top.driver.add_constraint, [ 'comp.x[0]**2+comp.x[0]+comp.x[1]**2-comp.x[1]+comp.x[2]**2+comp.x[2]+comp.x[3]**2-comp.x[3] < 8', 'comp.x[0]**2-comp.x[0]+2*comp.x[1]**2+comp.x[2]**2+2*comp.x[3]**2-comp.x[3] < 10', '2*comp.x[0]**2+2*comp.x[0]+comp.x[1]**2-comp.x[1]+comp.x[2]**2-comp.x[3] < 5']) self.top.driver.conmin_diff = True self.top.driver.fdch = .000001 self.top.driver.fdchm = .000001 self.top.run() # pylint: disable=E1101 assert_rel_error(self, self.top.driver.eval_objective(), self.top.comp.opt_objective, 0.01) assert_rel_error(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.comp.x[0], 0.05) assert_rel_error(self, self.top.comp.opt_design_vars[1], self.top.comp.x[1], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[2], self.top.comp.x[2], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[3], self.top.comp.x[3], 0.05) def test_openmdao_gradient_a(self): # Run with 1D parameter, 1D constraint, and OpenMDAO gradient. self.top.driver.add_constraint('comp.g <= 0') self.top.driver.conmin_diff = False self.top.run() # pylint: disable=E1101 assert_rel_error(self, self.top.comp.opt_objective, self.top.driver.eval_objective(), 0.01) assert_rel_error(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.comp.x[0], 0.05) assert_rel_error(self, self.top.comp.opt_design_vars[1], self.top.comp.x[1], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[2], self.top.comp.x[2], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[3], self.top.comp.x[3], 0.05) def test_openmdao_gradient_s(self): # Run with 1D parameter, scalar constraints, and OpenMDAO gradient. # pylint: disable=C0301 map(self.top.driver.add_constraint, [ 'comp.x[0]**2+comp.x[0]+comp.x[1]**2-comp.x[1]+comp.x[2]**2+comp.x[2]+comp.x[3]**2-comp.x[3] < 8', 'comp.x[0]**2-comp.x[0]+2*comp.x[1]**2+comp.x[2]**2+2*comp.x[3]**2-comp.x[3] < 10', '2*comp.x[0]**2+2*comp.x[0]+comp.x[1]**2-comp.x[1]+comp.x[2]**2-comp.x[3] < 5']) self.top.driver.conmin_diff = False self.top.run() # pylint: disable=E1101 assert_rel_error(self, self.top.comp.opt_objective, self.top.driver.eval_objective(), 0.01) assert_rel_error(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.comp.x[0], 0.05) assert_rel_error(self, self.top.comp.opt_design_vars[1], self.top.comp.x[1], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[2], self.top.comp.x[2], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[3], self.top.comp.x[3], 0.05) class TestCase2D(unittest.TestCase): """Test using 2D array connections.""" def setUp(self): self.top = set_as_top(Assembly()) self.top.add('comp', RosenSuzuki2D()) driver = self.top.add('driver', CONMINdriver()) driver.workflow.add('comp') driver.iprint = 0 driver.itmax = 30 driver.add_objective('10*comp.result') driver.add_parameter('comp.x') # pylint: disable=C0301 map(driver.add_constraint, [ 'comp.x[0][0]**2+comp.x[0][0]+comp.x[0][1]**2-comp.x[0][1]+comp.x[1][0]**2+comp.x[1][0]+comp.x[1][1]**2-comp.x[1][1] < 8', 'comp.x[0][0]**2-comp.x[0][0]+2*comp.x[0][1]**2+comp.x[1][0]**2+2*comp.x[1][1]**2-comp.x[1][1] < 10', '2*comp.x[0][0]**2+2*comp.x[0][0]+comp.x[0][1]**2-comp.x[0][1]+comp.x[1][0]**2-comp.x[1][1] < 5']) def test_conmin_gradient(self): # Run with 2D parameter and CONMIN gradient. self.top.driver.conmin_diff = True self.top.run() # pylint: disable=E1101 assert_rel_error(self, self.top.comp.opt_objective, self.top.driver.eval_objective(), 0.01) assert_rel_error(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.comp.x[0][0], 0.05) assert_rel_error(self, self.top.comp.opt_design_vars[1], self.top.comp.x[0][1], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[2], self.top.comp.x[1][0], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[3], self.top.comp.x[1][1], 0.05) def test_openmdao_gradient(self): # Run with 2D parameter and OpenMDAO gradient. self.top.driver.conmin_diff = False self.top.run() # pylint: disable=E1101 assert_rel_error(self, self.top.comp.opt_objective, self.top.driver.eval_objective(), 0.01) assert_rel_error(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.comp.x[0][0], 0.05) assert_rel_error(self, self.top.comp.opt_design_vars[1], self.top.comp.x[0][1], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[2], self.top.comp.x[1][0], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[3], self.top.comp.x[1][1], 0.05) class TestCaseMixed(unittest.TestCase): """Test using mixed scalar and 1D connections.""" def setUp(self): self.top = set_as_top(Assembly()) self.top.add('comp', RosenSuzukiMixed()) driver = self.top.add('driver', CONMINdriver()) driver.workflow.add('comp') driver.iprint = 0 driver.itmax = 30 driver.add_objective('10*comp.result') map(driver.add_parameter, ['comp.x0', 'comp.x12', 'comp.x3']) # pylint: disable=C0301 map(driver.add_constraint, [ 'comp.x0**2+comp.x0+comp.x12[0]**2-comp.x12[0]+comp.x12[1]**2+comp.x12[1]+comp.x3**2-comp.x3 < 8', 'comp.x0**2-comp.x0+2*comp.x12[0]**2+comp.x12[1]**2+2*comp.x3**2-comp.x3 < 10', '2*comp.x0**2+2*comp.x0+comp.x12[0]**2-comp.x12[0]+comp.x12[1]**2-comp.x3 < 5']) def test_conmin_gradient(self): # Run with mixed parameters and CONMIN gradient. self.top.driver.conmin_diff = True self.top.run() # pylint: disable=E1101 assert_rel_error(self, self.top.comp.opt_objective, self.top.driver.eval_objective(), 0.01) assert_rel_error(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.comp.x0, 0.05) assert_rel_error(self, self.top.comp.opt_design_vars[1], self.top.comp.x12[0], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[2], self.top.comp.x12[1], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[3], self.top.comp.x3, 0.05) def test_openmdao_gradient(self): # Run with mixed parameters and OpenMDAO gradient. self.top.driver.conmin_diff = False self.top.run() # pylint: disable=E1101 assert_rel_error(self, self.top.comp.opt_objective, self.top.driver.eval_objective(), 0.01) assert_rel_error(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.comp.x0, 0.05) assert_rel_error(self, self.top.comp.opt_design_vars[1], self.top.comp.x12[0], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[2], self.top.comp.x12[1], 0.06) assert_rel_error(self, self.top.comp.opt_design_vars[3], self.top.comp.x3, 0.05) if __name__ == "__main__": unittest.main()
[ "unittest.main", "openmdao.main.api.Assembly", "openmdao.main.datatypes.api.Str", "openmdao.util.testutil.assert_rel_error", "openmdao.main.interfaces.implements", "openmdao.main.datatypes.api.Float", "openmdao.util.decorators.add_delegate", "openmdao.main.datatypes.api.Array", "numpy.array", "openmdao.lib.drivers.conmindriver.CONMINdriver", "openmdao.lib.casehandlers.api.ListCaseRecorder" ]
[((1529, 1565), 'openmdao.main.datatypes.api.Array', 'Array', ([], {'iotype': '"""in"""', 'low': '(-10)', 'high': '(99)'}), "(iotype='in', low=-10, high=99)\n", (1534, 1565), False, 'from openmdao.main.datatypes.api import Float, Array, Str, VarTree\n'), ((1574, 1610), 'openmdao.main.datatypes.api.Array', 'Array', (['[1.0, 1.0, 1.0]'], {'iotype': '"""out"""'}), "([1.0, 1.0, 1.0], iotype='out')\n", (1579, 1610), False, 'from openmdao.main.datatypes.api import Float, Array, Str, VarTree\n'), ((1621, 1640), 'openmdao.main.datatypes.api.Float', 'Float', ([], {'iotype': '"""out"""'}), "(iotype='out')\n", (1626, 1640), False, 'from openmdao.main.datatypes.api import Float, Array, Str, VarTree\n'), ((1658, 1675), 'openmdao.main.datatypes.api.Str', 'Str', ([], {'iotype': '"""out"""'}), "(iotype='out')\n", (1661, 1675), False, 'from openmdao.main.datatypes.api import Float, Array, Str, VarTree\n'), ((1696, 1715), 'openmdao.main.datatypes.api.Float', 'Float', ([], {'iotype': '"""out"""'}), "(iotype='out')\n", (1701, 1715), False, 'from openmdao.main.datatypes.api import Float, Array, Str, VarTree\n'), ((2717, 2753), 'openmdao.main.datatypes.api.Array', 'Array', ([], {'iotype': '"""in"""', 'low': '(-10)', 'high': '(99)'}), "(iotype='in', low=-10, high=99)\n", (2722, 2753), False, 'from openmdao.main.datatypes.api import Float, Array, Str, VarTree\n'), ((2767, 2786), 'openmdao.main.datatypes.api.Float', 'Float', ([], {'iotype': '"""out"""'}), "(iotype='out')\n", (2772, 2786), False, 'from openmdao.main.datatypes.api import Float, Array, Str, VarTree\n'), ((2807, 2826), 'openmdao.main.datatypes.api.Float', 'Float', ([], {'iotype': '"""out"""'}), "(iotype='out')\n", (2812, 2826), False, 'from openmdao.main.datatypes.api import Float, Array, Str, VarTree\n'), ((3522, 3558), 'openmdao.main.datatypes.api.Float', 'Float', ([], {'iotype': '"""in"""', 'low': '(-10)', 'high': '(99)'}), "(iotype='in', low=-10, high=99)\n", (3527, 3558), False, 'from openmdao.main.datatypes.api import Float, Array, Str, VarTree\n'), ((3569, 3605), 'openmdao.main.datatypes.api.Array', 'Array', ([], {'iotype': '"""in"""', 'low': '(-10)', 'high': '(99)'}), "(iotype='in', low=-10, high=99)\n", (3574, 3605), False, 'from openmdao.main.datatypes.api import Float, Array, Str, VarTree\n'), ((3615, 3651), 'openmdao.main.datatypes.api.Float', 'Float', ([], {'iotype': '"""in"""', 'low': '(-10)', 'high': '(99)'}), "(iotype='in', low=-10, high=99)\n", (3620, 3651), False, 'from openmdao.main.datatypes.api import Float, Array, Str, VarTree\n'), ((3665, 3684), 'openmdao.main.datatypes.api.Float', 'Float', ([], {'iotype': '"""out"""'}), "(iotype='out')\n", (3670, 3684), False, 'from openmdao.main.datatypes.api import Float, Array, Str, VarTree\n'), ((3705, 3724), 'openmdao.main.datatypes.api.Float', 'Float', ([], {'iotype': '"""out"""'}), "(iotype='out')\n", (3710, 3724), False, 'from openmdao.main.datatypes.api import Float, Array, Str, VarTree\n'), ((16557, 16591), 'openmdao.main.datatypes.api.Float', 'Float', ([], {'desc': '"""default value of 0.0"""'}), "(desc='default value of 0.0')\n", (16562, 16591), False, 'from openmdao.main.datatypes.api import Float, Array, Str, VarTree\n'), ((16651, 16662), 'openmdao.main.datatypes.api.Float', 'Float', (['(11.0)'], {}), '(11.0)\n', (16656, 16662), False, 'from openmdao.main.datatypes.api import Float, Array, Str, VarTree\n'), ((16761, 16780), 'openmdao.main.datatypes.api.Float', 'Float', ([], {'iotype': '"""out"""'}), "(iotype='out')\n", (16766, 16780), False, 'from openmdao.main.datatypes.api import Float, Array, Str, VarTree\n'), ((27171, 27186), 'unittest.main', 'unittest.main', ([], {}), '()\n', (27184, 27186), False, 'import unittest\n'), ((1842, 1888), 'numpy.array', 'numpy.array', (['[1.0, 1.0, 1.0, 1.0]'], {'dtype': 'float'}), '([1.0, 1.0, 1.0, 1.0], dtype=float)\n', (1853, 1888), False, 'import numpy\n'), ((2943, 2993), 'numpy.array', 'numpy.array', (['[[1.0, 1.0], [1.0, 1.0]]'], {'dtype': 'float'}), '([[1.0, 1.0], [1.0, 1.0]], dtype=float)\n', (2954, 2993), False, 'import numpy\n'), ((3867, 3903), 'numpy.array', 'numpy.array', (['[1.0, 1.0]'], {'dtype': 'float'}), '([1.0, 1.0], dtype=float)\n', (3878, 3903), False, 'import numpy\n'), ((5625, 5720), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', '(1 + self.top.comp.opt_design_vars[0])', '(1 + self.top.comp.x[0])', '(0.05)'], {}), '(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.\n comp.x[0], 0.05)\n', (5641, 5720), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((5749, 5835), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[1]', 'self.top.comp.x[1]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[1], self.top.comp.x[1],\n 0.06)\n', (5765, 5835), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((5865, 5951), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[2]', 'self.top.comp.x[2]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[2], self.top.comp.x[2],\n 0.06)\n', (5881, 5951), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((5981, 6067), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[3]', 'self.top.comp.x[3]', '(0.05)'], {}), '(self, self.top.comp.opt_design_vars[3], self.top.comp.x[3],\n 0.05)\n', (5997, 6067), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((6970, 7065), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', '(1 + self.top.comp.opt_design_vars[0])', '(1 + self.top.comp.x[0])', '(0.06)'], {}), '(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.\n comp.x[0], 0.06)\n', (6986, 7065), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((7094, 7180), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[1]', 'self.top.comp.x[1]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[1], self.top.comp.x[1],\n 0.06)\n', (7110, 7180), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((7210, 7296), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[2]', 'self.top.comp.x[2]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[2], self.top.comp.x[2],\n 0.06)\n', (7226, 7296), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((7326, 7412), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[3]', 'self.top.comp.x[3]', '(0.05)'], {}), '(self, self.top.comp.opt_design_vars[3], self.top.comp.x[3],\n 0.05)\n', (7342, 7412), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((8471, 8566), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', '(1 + self.top.comp.opt_design_vars[0])', '(1 + self.top.comp.x[0])', '(0.06)'], {}), '(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.\n comp.x[0], 0.06)\n', (8487, 8566), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((8595, 8681), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[1]', 'self.top.comp.x[1]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[1], self.top.comp.x[1],\n 0.06)\n', (8611, 8681), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((8711, 8797), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[2]', 'self.top.comp.x[2]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[2], self.top.comp.x[2],\n 0.06)\n', (8727, 8797), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((8827, 8913), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[3]', 'self.top.comp.x[3]', '(0.05)'], {}), '(self, self.top.comp.opt_design_vars[3], self.top.comp.x[3],\n 0.05)\n', (8843, 8913), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((9714, 9809), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', '(1 + self.top.comp.opt_design_vars[0])', '(1 + self.top.comp.x[0])', '(0.05)'], {}), '(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.\n comp.x[0], 0.05)\n', (9730, 9809), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((9838, 9924), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[1]', 'self.top.comp.x[1]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[1], self.top.comp.x[1],\n 0.06)\n', (9854, 9924), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((9954, 10040), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[2]', 'self.top.comp.x[2]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[2], self.top.comp.x[2],\n 0.06)\n', (9970, 10040), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((10070, 10156), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[3]', 'self.top.comp.x[3]', '(0.05)'], {}), '(self, self.top.comp.opt_design_vars[3], self.top.comp.x[3],\n 0.05)\n', (10086, 10156), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((10955, 11050), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', '(1 + self.top.comp.opt_design_vars[0])', '(1 + self.top.comp.x[0])', '(0.05)'], {}), '(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.\n comp.x[0], 0.05)\n', (10971, 11050), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((11079, 11165), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[1]', 'self.top.comp.x[1]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[1], self.top.comp.x[1],\n 0.06)\n', (11095, 11165), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((11195, 11281), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[2]', 'self.top.comp.x[2]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[2], self.top.comp.x[2],\n 0.06)\n', (11211, 11281), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((11311, 11397), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[3]', 'self.top.comp.x[3]', '(0.05)'], {}), '(self, self.top.comp.opt_design_vars[3], self.top.comp.x[3],\n 0.05)\n', (11327, 11397), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((12440, 12486), 'numpy.array', 'numpy.array', (['[1.0, 1.0, 1.0, 1.0]'], {'dtype': 'float'}), '([1.0, 1.0, 1.0, 1.0], dtype=float)\n', (12451, 12486), False, 'import numpy\n'), ((15873, 15900), 'openmdao.util.decorators.add_delegate', 'add_delegate', (['HasParameters'], {}), '(HasParameters)\n', (15885, 15900), False, 'from openmdao.util.decorators import add_delegate\n'), ((18451, 18546), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', '(1 + self.top.comp.opt_design_vars[0])', '(1 + self.top.comp.x[0])', '(0.05)'], {}), '(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.\n comp.x[0], 0.05)\n', (18467, 18546), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((18575, 18661), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[1]', 'self.top.comp.x[1]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[1], self.top.comp.x[1],\n 0.06)\n', (18591, 18661), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((18691, 18777), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[2]', 'self.top.comp.x[2]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[2], self.top.comp.x[2],\n 0.06)\n', (18707, 18777), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((18807, 18893), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[3]', 'self.top.comp.x[3]', '(0.05)'], {}), '(self, self.top.comp.opt_design_vars[3], self.top.comp.x[3],\n 0.05)\n', (18823, 18893), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((19743, 19838), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', '(1 + self.top.comp.opt_design_vars[0])', '(1 + self.top.comp.x[0])', '(0.05)'], {}), '(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.\n comp.x[0], 0.05)\n', (19759, 19838), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((19867, 19953), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[1]', 'self.top.comp.x[1]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[1], self.top.comp.x[1],\n 0.06)\n', (19883, 19953), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((19983, 20069), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[2]', 'self.top.comp.x[2]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[2], self.top.comp.x[2],\n 0.06)\n', (19999, 20069), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((20099, 20185), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[3]', 'self.top.comp.x[3]', '(0.05)'], {}), '(self, self.top.comp.opt_design_vars[3], self.top.comp.x[3],\n 0.05)\n', (20115, 20185), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((20606, 20701), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', '(1 + self.top.comp.opt_design_vars[0])', '(1 + self.top.comp.x[0])', '(0.05)'], {}), '(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.\n comp.x[0], 0.05)\n', (20622, 20701), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((20730, 20816), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[1]', 'self.top.comp.x[1]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[1], self.top.comp.x[1],\n 0.06)\n', (20746, 20816), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((20846, 20932), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[2]', 'self.top.comp.x[2]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[2], self.top.comp.x[2],\n 0.06)\n', (20862, 20932), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((20962, 21048), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[3]', 'self.top.comp.x[3]', '(0.05)'], {}), '(self, self.top.comp.opt_design_vars[3], self.top.comp.x[3],\n 0.05)\n', (20978, 21048), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((21799, 21894), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', '(1 + self.top.comp.opt_design_vars[0])', '(1 + self.top.comp.x[0])', '(0.05)'], {}), '(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.\n comp.x[0], 0.05)\n', (21815, 21894), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((21923, 22009), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[1]', 'self.top.comp.x[1]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[1], self.top.comp.x[1],\n 0.06)\n', (21939, 22009), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((22039, 22125), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[2]', 'self.top.comp.x[2]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[2], self.top.comp.x[2],\n 0.06)\n', (22055, 22125), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((22155, 22241), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[3]', 'self.top.comp.x[3]', '(0.05)'], {}), '(self, self.top.comp.opt_design_vars[3], self.top.comp.x[3],\n 0.05)\n', (22171, 22241), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((23437, 23535), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', '(1 + self.top.comp.opt_design_vars[0])', '(1 + self.top.comp.x[0][0])', '(0.05)'], {}), '(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.\n comp.x[0][0], 0.05)\n', (23453, 23535), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((23564, 23654), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[1]', 'self.top.comp.x[0][1]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[1], self.top.comp.x[0]\n [1], 0.06)\n', (23580, 23654), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((23683, 23773), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[2]', 'self.top.comp.x[1][0]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[2], self.top.comp.x[1]\n [0], 0.06)\n', (23699, 23773), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((23802, 23892), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[3]', 'self.top.comp.x[1][1]', '(0.05)'], {}), '(self, self.top.comp.opt_design_vars[3], self.top.comp.x[1]\n [1], 0.05)\n', (23818, 23892), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((24240, 24338), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', '(1 + self.top.comp.opt_design_vars[0])', '(1 + self.top.comp.x[0][0])', '(0.05)'], {}), '(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.\n comp.x[0][0], 0.05)\n', (24256, 24338), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((24367, 24457), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[1]', 'self.top.comp.x[0][1]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[1], self.top.comp.x[0]\n [1], 0.06)\n', (24383, 24457), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((24486, 24576), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[2]', 'self.top.comp.x[1][0]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[2], self.top.comp.x[1]\n [0], 0.06)\n', (24502, 24576), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((24605, 24695), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[3]', 'self.top.comp.x[1][1]', '(0.05)'], {}), '(self, self.top.comp.opt_design_vars[3], self.top.comp.x[1]\n [1], 0.05)\n', (24621, 24695), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((25879, 25972), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', '(1 + self.top.comp.opt_design_vars[0])', '(1 + self.top.comp.x0)', '(0.05)'], {}), '(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.\n comp.x0, 0.05)\n', (25895, 25972), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((26001, 26090), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[1]', 'self.top.comp.x12[0]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[1], self.top.comp.x12[\n 0], 0.06)\n', (26017, 26090), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((26119, 26208), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[2]', 'self.top.comp.x12[1]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[2], self.top.comp.x12[\n 1], 0.06)\n', (26135, 26208), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((26237, 26322), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[3]', 'self.top.comp.x3', '(0.05)'], {}), '(self, self.top.comp.opt_design_vars[3], self.top.comp.x3, 0.05\n )\n', (26253, 26322), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((26674, 26767), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', '(1 + self.top.comp.opt_design_vars[0])', '(1 + self.top.comp.x0)', '(0.05)'], {}), '(self, 1 + self.top.comp.opt_design_vars[0], 1 + self.top.\n comp.x0, 0.05)\n', (26690, 26767), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((26796, 26885), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[1]', 'self.top.comp.x12[0]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[1], self.top.comp.x12[\n 0], 0.06)\n', (26812, 26885), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((26914, 27003), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[2]', 'self.top.comp.x12[1]', '(0.06)'], {}), '(self, self.top.comp.opt_design_vars[2], self.top.comp.x12[\n 1], 0.06)\n', (26930, 27003), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((27032, 27117), 'openmdao.util.testutil.assert_rel_error', 'assert_rel_error', (['self', 'self.top.comp.opt_design_vars[3]', 'self.top.comp.x3', '(0.05)'], {}), '(self, self.top.comp.opt_design_vars[3], self.top.comp.x3, 0.05\n )\n', (27048, 27117), False, 'from openmdao.util.testutil import assert_rel_error\n'), ((4470, 4480), 'openmdao.main.api.Assembly', 'Assembly', ([], {}), '()\n', (4478, 4480), False, 'from openmdao.main.api import Assembly, Component, VariableTree, set_as_top, Driver\n'), ((4513, 4527), 'openmdao.lib.drivers.conmindriver.CONMINdriver', 'CONMINdriver', ([], {}), '()\n', (4525, 4527), False, 'from openmdao.lib.drivers.conmindriver import CONMINdriver\n'), ((5381, 5399), 'openmdao.lib.casehandlers.api.ListCaseRecorder', 'ListCaseRecorder', ([], {}), '()\n', (5397, 5399), False, 'from openmdao.lib.casehandlers.api import ListCaseRecorder\n'), ((15488, 15529), 'openmdao.main.datatypes.api.Float', 'Float', (['(0.0)'], {'iotype': '"""in"""', 'low': '(-10)', 'high': '(10)'}), "(0.0, iotype='in', low=-10, high=10)\n", (15493, 15529), False, 'from openmdao.main.datatypes.api import Float, Array, Str, VarTree\n'), ((15547, 15588), 'openmdao.main.datatypes.api.Float', 'Float', (['(0.0)'], {'iotype': '"""in"""', 'low': '(-10)', 'high': '(10)'}), "(0.0, iotype='in', low=-10, high=10)\n", (15552, 15588), False, 'from openmdao.main.datatypes.api import Float, Array, Str, VarTree\n'), ((15607, 15626), 'openmdao.main.datatypes.api.Float', 'Float', ([], {'iotype': '"""out"""'}), "(iotype='out')\n", (15612, 15626), False, 'from openmdao.main.datatypes.api import Float, Array, Str, VarTree\n'), ((15643, 15662), 'openmdao.main.datatypes.api.Float', 'Float', ([], {'iotype': '"""out"""'}), "(iotype='out')\n", (15648, 15662), False, 'from openmdao.main.datatypes.api import Float, Array, Str, VarTree\n'), ((15951, 15977), 'openmdao.main.interfaces.implements', 'implements', (['IHasParameters'], {}), '(IHasParameters)\n', (15961, 15977), False, 'from openmdao.main.interfaces import IHasParameters, implements\n'), ((16079, 16089), 'openmdao.main.api.Assembly', 'Assembly', ([], {}), '()\n', (16087, 16089), False, 'from openmdao.main.api import Assembly, Component, VariableTree, set_as_top, Driver\n'), ((16151, 16165), 'openmdao.lib.drivers.conmindriver.CONMINdriver', 'CONMINdriver', ([], {}), '()\n', (16163, 16165), False, 'from openmdao.lib.drivers.conmindriver import CONMINdriver\n'), ((17051, 17065), 'openmdao.lib.drivers.conmindriver.CONMINdriver', 'CONMINdriver', ([], {}), '()\n', (17063, 17065), False, 'from openmdao.lib.drivers.conmindriver import CONMINdriver\n'), ((17678, 17688), 'openmdao.main.api.Assembly', 'Assembly', ([], {}), '()\n', (17686, 17688), False, 'from openmdao.main.api import Assembly, Component, VariableTree, set_as_top, Driver\n'), ((17786, 17800), 'openmdao.lib.drivers.conmindriver.CONMINdriver', 'CONMINdriver', ([], {}), '()\n', (17798, 17800), False, 'from openmdao.lib.drivers.conmindriver import CONMINdriver\n'), ((22396, 22406), 'openmdao.main.api.Assembly', 'Assembly', ([], {}), '()\n', (22404, 22406), False, 'from openmdao.main.api import Assembly, Component, VariableTree, set_as_top, Driver\n'), ((22494, 22508), 'openmdao.lib.drivers.conmindriver.CONMINdriver', 'CONMINdriver', ([], {}), '()\n', (22506, 22508), False, 'from openmdao.lib.drivers.conmindriver import CONMINdriver\n'), ((24864, 24874), 'openmdao.main.api.Assembly', 'Assembly', ([], {}), '()\n', (24872, 24874), False, 'from openmdao.main.api import Assembly, Component, VariableTree, set_as_top, Driver\n'), ((24965, 24979), 'openmdao.lib.drivers.conmindriver.CONMINdriver', 'CONMINdriver', ([], {}), '()\n', (24977, 24979), False, 'from openmdao.lib.drivers.conmindriver import CONMINdriver\n')]
# _SequenceGenerator.py __module_name__ = "_SequenceGenerator.py" __author__ = ", ".join(["<NAME>"]) __email__ = ", ".join(["<EMAIL>",]) # package imports # # --------------- # import numpy as np def _set_weight_simplex(A=1, C=1, G=1, T=1): """ Change the composition of weights for sampling bases at random. Parameters: ---------- N {A, C, G, T} proportions of bases to be sampled. simplex. Returns: ------- Initializes self.Gene and creates/modifies self.SeqGen Notes: ------ (1) As an example, if A=2, the simplex vector would appear as: [0.4, 0.2, 0.2, 0.2] """ bases = np.array([A, C, G, T]) return bases / bases.sum() class _SequenceGenerator: def __init__(self, A=1, C=1, G=1, T=1,): """ Initialize random sequence generator. Parameters: ---------- N {A, C, G, T} proportions of bases to be sampled. simplex. Returns: ------- self.bases Array of available bases. type: numpy.ndarray self.weights Weights to be passed for base selection. type: numpy.ndarray Notes: ------ (1) As an example, if A=2, the simplex vector would appear as: [0.4, 0.2, 0.2, 0.2] """ self.bases = np.array(["A", "C", "G", "T"]) self.weights = _set_weight_simplex(A, C, G, T) def simulate(self, n_bases, return_seq=True): """" Simulate a DNA sequence of arbitrary length. Parameters: ----------- n_bases Number of bases to be selected. return_seq Indicates if the generated sequence should be returned directly. Saved as a subclass object by default. type: bool default: True Returns: -------- [ optional ] self.seq Generated sequence of length(n_bases) type: str Notes: ------ """ self.seq = "".join(np.random.choice(self.bases, n_bases, p=self.weights)) if return_seq: return self.seq
[ "numpy.array", "numpy.random.choice" ]
[((653, 675), 'numpy.array', 'np.array', (['[A, C, G, T]'], {}), '([A, C, G, T])\n', (661, 675), True, 'import numpy as np\n'), ((1359, 1389), 'numpy.array', 'np.array', (["['A', 'C', 'G', 'T']"], {}), "(['A', 'C', 'G', 'T'])\n", (1367, 1389), True, 'import numpy as np\n'), ((2134, 2187), 'numpy.random.choice', 'np.random.choice', (['self.bases', 'n_bases'], {'p': 'self.weights'}), '(self.bases, n_bases, p=self.weights)\n', (2150, 2187), True, 'import numpy as np\n')]
#!/usr/bin/env python import sys import argparse import matplotlib import numpy as np import pandas as pd matplotlib.use('Agg') from pathlib import Path import matplotlib.pyplot as plt def get_ase(ase_fname): """parse the ASE TSV for the top n most promising str-tissue pairs""" ase = pd.read_csv( ase_fname, sep="\t", header=0, index_col=['str', 'tissue'], usecols=[ 'str', 'tissue', 'chrom', 'str_pos', 'str_a1', 'str_a2', 'distance', 'variant_annotation', 'gene', 'ase', 'allelic_ratio' ] ) ase['repeat_ratio'] = ase['str_a1'].str.len()/ase['str_a2'].str.len() return ase def plot(ase, out, n=None): """make plots for each str-tissue pair in the ase table""" str_tissue_pairs = ase.index.unique() if n is None: n = len(str_tissue_pairs) for STR in str_tissue_pairs: if n <= 0: break plt.figure() vals = ase[['repeat_ratio','allelic_ratio']].loc[STR].to_numpy() #'ase': ase[['repeat_ratio','ase']].loc[STR].to_numpy() x = vals[:,0] y = vals[:,1] # perform a simple linear regression p = np.polyfit(x, y, 1) r_squared = 1 - ( sum((y - (p[0]*x+p[1]))**2) / ((len(y) - 1) * np.var(y, ddof=1)) ) p = np.poly1d(p) # plot the points and the line plt.scatter(x, y, color='r', label="_nolegend_") plt.plot( x, p(x), label="{}\nr-squared: {}\nn = {}".format(p, round(r_squared, 2), len(x)) ) # TODO: include information about distance, tissue, gene?, variant_annotation? plt.xlabel("Ratio of STR Lengths") plt.ylabel("Allelic Expression Ratio") plt.legend(frameon=False, loc='lower right') plt.tight_layout() plt.savefig(str(out)+"/"+"-".join(STR)+".png", bbox_inches='tight') plt.clf() n -= 1 def get_args(): """parse the arguments to this script using argparse""" parser = argparse.ArgumentParser(description= "Plot linear associations between ASE and STR repeat number." ) parser.add_argument( '-n', '--num-plots', default=None, type=int, help='Only create plots for the first n STRs' ) parser.add_argument( 'out', type=Path, help='Path to a directory in which to place each plot' # TODO: describe the structure of this tsv file better ) parser.add_argument( 'ase', default=sys.stdin, nargs='?', help=""" A TSV containing ASE for each STR. The columns of this TSV must have names: str, tissue, chrom, str_pos, str_a1, str_a2, distance, variant_annotation, gene, ase If this argument is not provided, it will be read from stdin """ ) args = parser.parse_args() return args def main(args): # create the output directory if it doesn't exist yet args.out.mkdir(exist_ok=True) plot(get_ase(args.ase), args.out, args.num_plots) if __name__ == "__main__": main(get_args())
[ "numpy.poly1d", "argparse.ArgumentParser", "numpy.polyfit", "pandas.read_csv", "matplotlib.pyplot.scatter", "matplotlib.pyplot.legend", "matplotlib.pyplot.clf", "numpy.var", "matplotlib.pyplot.figure", "matplotlib.use", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.tight_layout" ]
[((106, 127), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (120, 127), False, 'import matplotlib\n'), ((296, 508), 'pandas.read_csv', 'pd.read_csv', (['ase_fname'], {'sep': '"""\t"""', 'header': '(0)', 'index_col': "['str', 'tissue']", 'usecols': "['str', 'tissue', 'chrom', 'str_pos', 'str_a1', 'str_a2', 'distance',\n 'variant_annotation', 'gene', 'ase', 'allelic_ratio']"}), "(ase_fname, sep='\\t', header=0, index_col=['str', 'tissue'],\n usecols=['str', 'tissue', 'chrom', 'str_pos', 'str_a1', 'str_a2',\n 'distance', 'variant_annotation', 'gene', 'ase', 'allelic_ratio'])\n", (307, 508), True, 'import pandas as pd\n'), ((1999, 2102), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Plot linear associations between ASE and STR repeat number."""'}), "(description=\n 'Plot linear associations between ASE and STR repeat number.')\n", (2022, 2102), False, 'import argparse\n'), ((903, 915), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (913, 915), True, 'import matplotlib.pyplot as plt\n'), ((1154, 1173), 'numpy.polyfit', 'np.polyfit', (['x', 'y', '(1)'], {}), '(x, y, 1)\n', (1164, 1173), True, 'import numpy as np\n'), ((1299, 1311), 'numpy.poly1d', 'np.poly1d', (['p'], {}), '(p)\n', (1308, 1311), True, 'import numpy as np\n'), ((1359, 1407), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'y'], {'color': '"""r"""', 'label': '"""_nolegend_"""'}), "(x, y, color='r', label='_nolegend_')\n", (1370, 1407), True, 'import matplotlib.pyplot as plt\n'), ((1637, 1671), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Ratio of STR Lengths"""'], {}), "('Ratio of STR Lengths')\n", (1647, 1671), True, 'import matplotlib.pyplot as plt\n'), ((1680, 1718), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Allelic Expression Ratio"""'], {}), "('Allelic Expression Ratio')\n", (1690, 1718), True, 'import matplotlib.pyplot as plt\n'), ((1727, 1771), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'frameon': '(False)', 'loc': '"""lower right"""'}), "(frameon=False, loc='lower right')\n", (1737, 1771), True, 'import matplotlib.pyplot as plt\n'), ((1780, 1798), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1796, 1798), True, 'import matplotlib.pyplot as plt\n'), ((1883, 1892), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1890, 1892), True, 'import matplotlib.pyplot as plt\n'), ((1258, 1275), 'numpy.var', 'np.var', (['y'], {'ddof': '(1)'}), '(y, ddof=1)\n', (1264, 1275), True, 'import numpy as np\n')]
import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from ez_torch.base_module import Module from ez_torch.utils import get_uv_grid def leaky(slope=0.2): return nn.LeakyReLU(slope, inplace=True) def conv_block(i, o, ks, s, p, a=leaky(), d=1, bn=True): block = [nn.Conv2d(i, o, kernel_size=ks, stride=s, padding=p, dilation=d)] if bn: block.append(nn.BatchNorm2d(o)) if a is not None: block.append(a) return nn.Sequential(*block) def deconv_block(i, o, ks, s, p, a=leaky(), d=1, bn=True): block = [ nn.ConvTranspose2d( i, o, kernel_size=ks, stride=s, padding=p, dilation=d, ) ] if bn: block.append(nn.BatchNorm2d(o)) if a is not None: block.append(a) if len(block) == 1: return block[0] return nn.Sequential(*block) def dense(i, o, a=leaky()): l = nn.Linear(i, o) return l if a is None else nn.Sequential(l, a) class Reshape(nn.Module): def __init__(self, *shape): super().__init__() self.shape = shape def forward(self, x): return x.reshape(self.shape) class Lambda(nn.Module): def __init__(self, forward): super().__init__() self.forward = forward def forward(self, *args): return self.forward(*args) class SpatialLinearTransformer(nn.Module): def __init__(self, i, num_channels, only_translations=False): super().__init__() self.only_translations = only_translations self.num_channels = num_channels self.locator = nn.Sequential( nn.Linear(i, num_channels * 2 * 3), Reshape(-1, 2, 3), ) self.device = self.locator[0].bias.device # Taken from the pytorch spatial transformer tutorial. self.locator[0].weight.data.zero_() self.locator[0].bias.data.copy_( torch.tensor( [1, 0, 0, 0, 1, 0] * num_channels, dtype=torch.float, ).to(self.device) ) def forward(self, x): param_features, input_to_transform = x theta = self.locator(param_features) _, C, H, W = input_to_transform.shape if self.only_translations: theta[:, :, :-1] = ( torch.tensor( [[1, 0], [0, 1]], dtype=torch.float, ) .to(self.device) .unsqueeze_(0) ) grid = F.affine_grid( theta, (theta.size(dim=0), 1, H, W), align_corners=True, ) input_to_transform = input_to_transform.reshape(-1, 1, H, W) input_to_transform = F.grid_sample( input_to_transform, grid, align_corners=True, ) return input_to_transform.reshape(-1, C, H, W) class SpatialUVTransformer(nn.Module): def __init__(self, i, uv_resolution_shape): super().__init__() self.uv_resolution_shape = uv_resolution_shape self.infer_uv = nn.Sequential( nn.Linear(i, np.prod(self.uv_resolution_shape) * 2), Reshape(-1, 2, *self.uv_resolution_shape), nn.Sigmoid(), Lambda(lambda x: x * 2 - 1), # range in [-1, 1] ) def forward(self, x): inp, tensor_3d = x uv_map = self.infer_uv(inp) H, W = tensor_3d.shape[-2:] uv_map = uv_map.ez.resize(H, W).raw.permute(0, 2, 3, 1) tensor_3d = F.grid_sample( tensor_3d, uv_map, align_corners=True, ) return tensor_3d class SpatialUVOffsetTransformer(nn.Module): def __init__(self, inp, uv_resolution_shape, weight_mult_factor=0.5): super().__init__() self.uv_resolution_shape = uv_resolution_shape self.infer_offset = nn.Sequential( nn.Linear(inp, np.prod(self.uv_resolution_shape) * 2), Reshape(-1, 2, *self.uv_resolution_shape), nn.Sigmoid(), Lambda(lambda x: x * 2 - 1), # range in [-1, 1] ) self.id_uv_map = nn.parameter.Parameter( get_uv_grid(*uv_resolution_shape), requires_grad=False, ) self.infer_offset[0].weight.data *= weight_mult_factor self.infer_offset[0].bias.data.fill_(0) def forward(self, x): inp, tensor_3d = x offset_map = self.infer_offset(inp) + self.id_uv_map H, W = tensor_3d.shape[-2:] offset_map = offset_map.ez.resize(H, W).raw.permute(0, 2, 3, 1) tensor_3d = F.grid_sample( tensor_3d, offset_map, align_corners=True, ).clamp(0, 1) return tensor_3d class TimeDistributed(nn.Module): def __init__(self, module): super().__init__() self.module = module def forward(self, input): shape = input[0].size() if type(input) is list else input.size() bs = shape[0] seq_len = shape[1] if type(input) is list: input = [i.reshape(-1, *i.shape[2:]) for i in input] else: input = input.reshape(-1, *shape[2:]) out = self.module(input) out = out.view(bs, seq_len, *out.shape[1:]) return out
[ "torch.nn.ConvTranspose2d", "torch.nn.functional.grid_sample", "torch.nn.Sequential", "torch.nn.Conv2d", "numpy.prod", "torch.nn.BatchNorm2d", "ez_torch.utils.get_uv_grid", "torch.nn.Linear", "torch.nn.LeakyReLU", "torch.tensor", "torch.nn.Sigmoid" ]
[((212, 245), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['slope'], {'inplace': '(True)'}), '(slope, inplace=True)\n', (224, 245), True, 'import torch.nn as nn\n'), ((493, 514), 'torch.nn.Sequential', 'nn.Sequential', (['*block'], {}), '(*block)\n', (506, 514), True, 'import torch.nn as nn\n'), ((920, 941), 'torch.nn.Sequential', 'nn.Sequential', (['*block'], {}), '(*block)\n', (933, 941), True, 'import torch.nn as nn\n'), ((980, 995), 'torch.nn.Linear', 'nn.Linear', (['i', 'o'], {}), '(i, o)\n', (989, 995), True, 'import torch.nn as nn\n'), ((318, 382), 'torch.nn.Conv2d', 'nn.Conv2d', (['i', 'o'], {'kernel_size': 'ks', 'stride': 's', 'padding': 'p', 'dilation': 'd'}), '(i, o, kernel_size=ks, stride=s, padding=p, dilation=d)\n', (327, 382), True, 'import torch.nn as nn\n'), ((598, 671), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['i', 'o'], {'kernel_size': 'ks', 'stride': 's', 'padding': 'p', 'dilation': 'd'}), '(i, o, kernel_size=ks, stride=s, padding=p, dilation=d)\n', (616, 671), True, 'import torch.nn as nn\n'), ((1027, 1046), 'torch.nn.Sequential', 'nn.Sequential', (['l', 'a'], {}), '(l, a)\n', (1040, 1046), True, 'import torch.nn as nn\n'), ((2789, 2848), 'torch.nn.functional.grid_sample', 'F.grid_sample', (['input_to_transform', 'grid'], {'align_corners': '(True)'}), '(input_to_transform, grid, align_corners=True)\n', (2802, 2848), True, 'import torch.nn.functional as F\n'), ((3590, 3642), 'torch.nn.functional.grid_sample', 'F.grid_sample', (['tensor_3d', 'uv_map'], {'align_corners': '(True)'}), '(tensor_3d, uv_map, align_corners=True)\n', (3603, 3642), True, 'import torch.nn.functional as F\n'), ((416, 433), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['o'], {}), '(o)\n', (430, 433), True, 'import torch.nn as nn\n'), ((794, 811), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['o'], {}), '(o)\n', (808, 811), True, 'import torch.nn as nn\n'), ((1690, 1724), 'torch.nn.Linear', 'nn.Linear', (['i', '(num_channels * 2 * 3)'], {}), '(i, num_channels * 2 * 3)\n', (1699, 1724), True, 'import torch.nn as nn\n'), ((3295, 3307), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (3305, 3307), True, 'import torch.nn as nn\n'), ((4096, 4108), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (4106, 4108), True, 'import torch.nn as nn\n'), ((4242, 4275), 'ez_torch.utils.get_uv_grid', 'get_uv_grid', (['*uv_resolution_shape'], {}), '(*uv_resolution_shape)\n', (4253, 4275), False, 'from ez_torch.utils import get_uv_grid\n'), ((4676, 4732), 'torch.nn.functional.grid_sample', 'F.grid_sample', (['tensor_3d', 'offset_map'], {'align_corners': '(True)'}), '(tensor_3d, offset_map, align_corners=True)\n', (4689, 4732), True, 'import torch.nn.functional as F\n'), ((1978, 2044), 'torch.tensor', 'torch.tensor', (['([1, 0, 0, 0, 1, 0] * num_channels)'], {'dtype': 'torch.float'}), '([1, 0, 0, 0, 1, 0] * num_channels, dtype=torch.float)\n', (1990, 2044), False, 'import torch\n'), ((3188, 3221), 'numpy.prod', 'np.prod', (['self.uv_resolution_shape'], {}), '(self.uv_resolution_shape)\n', (3195, 3221), True, 'import numpy as np\n'), ((3989, 4022), 'numpy.prod', 'np.prod', (['self.uv_resolution_shape'], {}), '(self.uv_resolution_shape)\n', (3996, 4022), True, 'import numpy as np\n'), ((2369, 2418), 'torch.tensor', 'torch.tensor', (['[[1, 0], [0, 1]]'], {'dtype': 'torch.float'}), '([[1, 0], [0, 1]], dtype=torch.float)\n', (2381, 2418), False, 'import torch\n')]
import tensorflow as tf import numpy as np x_data = np.array([ [0,0] , [0,1], [1,0], [1,1] ]) y_data = np.array([ [1,0], #0 [1,0], #0 [1,0], #0 [0,1] #1 ]) X = tf.placeholder(tf.float32) Y = tf.placeholder(tf.float32) W = tf.Variable(tf.random_uniform([2, 2], -1., 1.)) b = tf.Variable(tf.zeros([2])) model = tf.nn.softmax(tf.matmul(X, W) + b) cost = -tf.reduce_mean(Y*tf.log(model) + (1-Y)*tf.log(1-model)) optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.1) train_op = optimizer.minimize(cost) init = tf.global_variables_initializer() correct_prediction = tf.equal(tf.floor(model + 0.5), Y) accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) sess = tf.Session() sess.run(init) for step in range(10000): sess.run(train_op, feed_dict={X: x_data, Y: y_data}) c = sess.run(cost, feed_dict={X:x_data, Y:y_data}) if c < 0.01: print("step : ", step) break if (step + 1) % 10 == 0: print(step+1, c) #prediction = tf.argmax(model, 1) #target = tf.argmax(Y, 1) #print("predict : ", sess.run(prediction, feed_dict={X: x_data})) #print("real : ", sess.run(target, feed_dict={Y: y_data})) print("accuracy : " , sess.run(accuracy, feed_dict={X: x_data, Y: y_data}))
[ "tensorflow.random_uniform", "tensorflow.global_variables_initializer", "tensorflow.Session", "tensorflow.placeholder", "tensorflow.floor", "tensorflow.zeros", "numpy.array", "tensorflow.cast", "tensorflow.matmul", "tensorflow.log", "tensorflow.train.GradientDescentOptimizer" ]
[((54, 96), 'numpy.array', 'np.array', (['[[0, 0], [0, 1], [1, 0], [1, 1]]'], {}), '([[0, 0], [0, 1], [1, 0], [1, 1]])\n', (62, 96), True, 'import numpy as np\n'), ((108, 150), 'numpy.array', 'np.array', (['[[1, 0], [1, 0], [1, 0], [0, 1]]'], {}), '([[1, 0], [1, 0], [1, 0], [0, 1]])\n', (116, 150), True, 'import numpy as np\n'), ((172, 198), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (186, 198), True, 'import tensorflow as tf\n'), ((203, 229), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (217, 229), True, 'import tensorflow as tf\n'), ((436, 488), 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', ([], {'learning_rate': '(0.1)'}), '(learning_rate=0.1)\n', (469, 488), True, 'import tensorflow as tf\n'), ((535, 568), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (566, 568), True, 'import tensorflow as tf\n'), ((698, 710), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (708, 710), True, 'import tensorflow as tf\n'), ((247, 283), 'tensorflow.random_uniform', 'tf.random_uniform', (['[2, 2]', '(-1.0)', '(1.0)'], {}), '([2, 2], -1.0, 1.0)\n', (264, 283), True, 'import tensorflow as tf\n'), ((299, 312), 'tensorflow.zeros', 'tf.zeros', (['[2]'], {}), '([2])\n', (307, 312), True, 'import tensorflow as tf\n'), ((600, 621), 'tensorflow.floor', 'tf.floor', (['(model + 0.5)'], {}), '(model + 0.5)\n', (608, 621), True, 'import tensorflow as tf\n'), ((652, 688), 'tensorflow.cast', 'tf.cast', (['correct_prediction', '"""float"""'], {}), "(correct_prediction, 'float')\n", (659, 688), True, 'import tensorflow as tf\n'), ((337, 352), 'tensorflow.matmul', 'tf.matmul', (['X', 'W'], {}), '(X, W)\n', (346, 352), True, 'import tensorflow as tf\n'), ((384, 397), 'tensorflow.log', 'tf.log', (['model'], {}), '(model)\n', (390, 397), True, 'import tensorflow as tf\n'), ((406, 423), 'tensorflow.log', 'tf.log', (['(1 - model)'], {}), '(1 - model)\n', (412, 423), True, 'import tensorflow as tf\n')]
# This file is part of the P3IV Simulator (https://github.com/fzi-forschungszentrum-informatik/P3IV), # copyright by FZI Forschungszentrum Informatik, licensed under the BSD-3 license (see LICENSE file in main directory) from __future__ import division import numpy as np import warnings import random from .external.dataset_types import Track from p3iv_types.motion import MotionState from p3iv_core.bindings.dataset import DataConverterInterface from p3iv_core.bindings.interaction_dataset.track_reader import track_reader class DatasetValueError(Exception): repr("Value not present in dataset") class DataConverter(DataConverterInterface): def __init__(self, configurations): self.configurations = configurations self._tracks = track_reader( configurations["map"], configurations["dataset"], configurations["track_file_number"] ) def fill_environment(self, environment, timestamp): """Fill environment model with data from the dataset. Parameters ---------- environment: EnvironmentModel Environmnet model object to be filled. timestamp: int Integer that of current timestamp. """ assert isinstance(timestamp, int) for t_id, track in list(self._tracks.items()): state = self.get_state(timestamp, t_id) if state: environment.add_object(t_id, self.get_color(t_id), track.length, track.width, state) return environment def get_state(self, timestamp, track_id): """Read from dataset in VehicleState-format. Extract only current timestamp state.""" assert isinstance(track_id, int) assert isinstance(timestamp, int) if not track_id in self._tracks: raise DatasetValueError track = self._tracks[track_id] try: data = self._read_track_at_timestamp(track, timestamp) state = self.state(*data[1:]) except DatasetValueError: state = None return state def read_track_at_timestamp(self, track_id, timestamp): if not track_id in self._tracks: return None return self._read_track_at_timestamp(self._tracks[track_id], timestamp) @staticmethod def _read_track_at_timestamp(track, timestamp): """Read track data at provided timestamp. Protected, as it serves as a helper func. """ assert isinstance(timestamp, (int, np.int, np.int64)) assert isinstance(track, Track) if not (track.time_stamp_ms_first <= timestamp <= track.time_stamp_ms_last): raise DatasetValueError data = np.empty(6) data[0] = timestamp data[1] = track.motion_states[timestamp].x data[2] = track.motion_states[timestamp].y data[3] = track.motion_states[timestamp].psi_rad data[4] = track.motion_states[timestamp].vx data[5] = track.motion_states[timestamp].vy return data
[ "p3iv_core.bindings.interaction_dataset.track_reader.track_reader", "numpy.empty" ]
[((761, 864), 'p3iv_core.bindings.interaction_dataset.track_reader.track_reader', 'track_reader', (["configurations['map']", "configurations['dataset']", "configurations['track_file_number']"], {}), "(configurations['map'], configurations['dataset'],\n configurations['track_file_number'])\n", (773, 864), False, 'from p3iv_core.bindings.interaction_dataset.track_reader import track_reader\n'), ((2686, 2697), 'numpy.empty', 'np.empty', (['(6)'], {}), '(6)\n', (2694, 2697), True, 'import numpy as np\n')]
#!python # -*- coding: utf-8 -*- # # This software and supporting documentation are distributed by # Institut Federatif de Recherche 49 # CEA/NeuroSpin, Batiment 145, # 91191 Gif-sur-Yvette cedex # France # # This software is governed by the CeCILL license version 2 under # French law and abiding by the rules of distribution of free software. # You can use, modify and/or redistribute the software under the # terms of the CeCILL license version 2 as circulated by CEA, CNRS # and INRIA at the following URL "http://www.cecill.info". # # As a counterpart to the access to the source code and rights to copy, # modify and redistribute granted by the license, users are provided only # with a limited warranty and the software's author, the holder of the # economic rights, and the successive licensors have only limited # liability. # # In this respect, the user's attention is drawn to the risks associated # with loading, using, modifying and/or developing or reproducing the # software by the user in light of its specific status of free software, # that may mean that it is complicated to manipulate, and that also # therefore means that it is reserved for developers and experienced # professionals having in-depth computer knowledge. Users are therefore # encouraged to load and test the software's suitability as regards their # requirements in conditions enabling the security of their systems and/or # data to be ensured and, more generally, to use and operate it in the # same conditions as regards security. # # The fact that you are presently reading this means that you have had # knowledge of the CeCILL license version 2 and that you accept its terms. """Write skeletons from graph files Typical usage ------------- You can use this program by first entering in the brainvisa environment (here brainvisa 5.0.0 installed with singurity) and launching the script from the terminal: >>> bv bash >>> python write_skeleton.py """ import sys import glob import os import re import argparse from pqdm.processes import pqdm from joblib import cpu_count from soma import aims import numpy as np def define_njobs(): """Returns number of cpus used by main loop """ nb_cpus = cpu_count() return max(nb_cpus-2, 1) def parse_args(argv): """Parses command-line arguments Args: argv: a list containing command line arguments Returns: args """ # Parse command line arguments parser = argparse.ArgumentParser( prog='write_skeleton.py', description='Generates bucket files converted from volume files') parser.add_argument( "-s", "--src_dir", type=str, required=True, help='Source directory where the graph data lies.') parser.add_argument( "-t", "--tgt_dir", type=str, required=True, help='Output directory where to put skeleton files.') parser.add_argument( "-i", "--side", type=str, required=True, help='Hemisphere side (either L or R).') args = parser.parse_args(argv) return args class GraphConvert2Skeleton: """ """ def __init__(self, src_dir, tgt_dir, side): self.src_dir = src_dir self.tgt_dir = tgt_dir self.side = side # self.graph_dir = "t1mri/default_acquisition/default_analysis/folds/3.1/default_session_auto/" self.graph_dir = "t1mri/default_acquisition/default_analysis/folds/3.1/default_session_*" def write_skeleton(self, subject): """ """ # graph_file = f"{self.side}{subject}*.arg" graph_file = glob.glob(f"{self.src_dir}/{subject}*/{self.graph_dir}/{self.side}{subject}*.arg")[0] graph = aims.read(graph_file) skeleton_filename = f"{self.tgt_dir}/{self.side}skeleton_{subject}_generated.nii.gz" voxel_size = graph['voxel_size'][:3] # Adds 1 for each x,y,z dimension dimensions = [i+j for i, j in zip(graph['boundingbox_max'], [1,1,1,0])] vol = aims.Volume(dimensions, dtype='S16') vol.header()['voxel_size'] = voxel_size if 'transformations' in graph.keys(): vol.header()['transformations'] = graph['transformations'] if 'referentials' in graph.keys(): vol.header()['referentials'] = graph['referentials'] if 'referential' in graph.keys(): vol.header()['referential'] = graph['referential'] arr = np.asarray(vol) for edge in graph.edges(): for bucket_name, value in {'aims_junction':110, 'aims_plidepassage':120}.items(): bucket = edge.get(bucket_name) if bucket is not None: voxels = np.array(bucket[0].keys()) if voxels.shape == (0,): continue for i,j,k in voxels: arr[i,j,k] = value for vertex in graph.vertices(): for bucket_name, value in {'aims_bottom': 30, 'aims_ss': 60, 'aims_other': 100}.items(): bucket = vertex.get(bucket_name) if bucket is not None: voxels = np.array(bucket[0].keys()) if voxels.shape == (0,): continue for i,j,k in voxels: arr[i,j,k] = value aims.write(vol, skeleton_filename) def write_loop(self): filenames = glob.glob(f"{self.src_dir}/*/") list_subjects = [re.search('([ae\d]{5,6})', filename).group(0) for filename in filenames] pqdm(list_subjects, self.write_skeleton, n_jobs=define_njobs()) # self.write_skeleton(list_subjects[0]) def main(argv): """ """ # Parsing arguments args = parse_args(argv) conversion = GraphConvert2Skeleton(args.src_dir, args.tgt_dir, args.side) conversion.write_loop() if __name__ == '__main__': # This permits to call main also from another python program # without having to make system calls # src_dir = "/neurospin/lnao/Panabase/lborne/data/ACCpatterns/tissier_2018/subjects" # tgt_dir = "/neurospin/dico/data/deep_folding/datasets/ACC_patterns/tissier" # args = "-i R -s " + src_dir + " -t " + tgt_dir # argv = args.split(' ') # main(argv=argv) main(argv=sys.argv[1:])
[ "argparse.ArgumentParser", "soma.aims.Volume", "joblib.cpu_count", "numpy.asarray", "soma.aims.write", "soma.aims.read", "glob.glob", "re.search" ]
[((2251, 2262), 'joblib.cpu_count', 'cpu_count', ([], {}), '()\n', (2260, 2262), False, 'from joblib import cpu_count\n'), ((2502, 2622), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""write_skeleton.py"""', 'description': '"""Generates bucket files converted from volume files"""'}), "(prog='write_skeleton.py', description=\n 'Generates bucket files converted from volume files')\n", (2525, 2622), False, 'import argparse\n'), ((3710, 3731), 'soma.aims.read', 'aims.read', (['graph_file'], {}), '(graph_file)\n', (3719, 3731), False, 'from soma import aims\n'), ((4009, 4045), 'soma.aims.Volume', 'aims.Volume', (['dimensions'], {'dtype': '"""S16"""'}), "(dimensions, dtype='S16')\n", (4020, 4045), False, 'from soma import aims\n'), ((4438, 4453), 'numpy.asarray', 'np.asarray', (['vol'], {}), '(vol)\n', (4448, 4453), True, 'import numpy as np\n'), ((5345, 5379), 'soma.aims.write', 'aims.write', (['vol', 'skeleton_filename'], {}), '(vol, skeleton_filename)\n', (5355, 5379), False, 'from soma import aims\n'), ((5428, 5459), 'glob.glob', 'glob.glob', (['f"""{self.src_dir}/*/"""'], {}), "(f'{self.src_dir}/*/')\n", (5437, 5459), False, 'import glob\n'), ((3608, 3695), 'glob.glob', 'glob.glob', (['f"""{self.src_dir}/{subject}*/{self.graph_dir}/{self.side}{subject}*.arg"""'], {}), "(\n f'{self.src_dir}/{subject}*/{self.graph_dir}/{self.side}{subject}*.arg')\n", (3617, 3695), False, 'import glob\n'), ((5485, 5522), 're.search', 're.search', (['"""([ae\\\\d]{5,6})"""', 'filename'], {}), "('([ae\\\\d]{5,6})', filename)\n", (5494, 5522), False, 'import re\n')]
#!/usr/bin/python3 import sys from nuscenes.nuscenes import NuScenes import nuscenes.utils.geometry_utils as geoutils from pyquaternion import Quaternion import numpy as np import os import numpy.linalg as la if __name__ == "__main__": if len(sys.argv) < 3: print("Usage: ./nuscenes2kitti.py <dataset_folder> <output_folder> [<scene_name>]") exit(1) dataroot = sys.argv[1] nusc = NuScenes(version = 'v1.0-mini', dataroot = dataroot, verbose = True) name2id = {scene["name"]:id for id, scene in enumerate(nusc.scene)} scenes2parse = [] if len(sys.argv) > 3: if sys.argv[3] not in name2id: print("No scene with name {} found.".format(sys.argv[2])) print("Available scenes: {}".format(" ".join(name2id.keys()))) exit(1) scenes2parse.append(sys.argv[3]) else: scenes2parse = name2id.keys() for scene_name in scenes2parse: print("Converting {} ...".format(scene_name)) output_folder = os.path.join(sys.argv[2], scene_name) velodyne_folder = os.path.join(output_folder, "velodyne/") first_lidar = nusc.get('sample', nusc.scene[name2id[scene_name]]["first_sample_token"])["data"]["LIDAR_TOP"] last_lidar = nusc.get('sample', nusc.scene[name2id[scene_name]]["last_sample_token"])["data"]["LIDAR_TOP"] current_lidar = first_lidar lidar_filenames = [] poses = [] if not os.path.exists(velodyne_folder): print("Creating output folder: {}".format(output_folder)) os.makedirs(velodyne_folder) original = [] while current_lidar != "": lidar_data = nusc.get('sample_data', current_lidar) calib_data = nusc.get("calibrated_sensor", lidar_data["calibrated_sensor_token"]) egopose_data = nusc.get('ego_pose', lidar_data["ego_pose_token"]) car_to_velo = geoutils.transform_matrix(calib_data["translation"], Quaternion(calib_data["rotation"])) pose_car = geoutils.transform_matrix(egopose_data["translation"], Quaternion(egopose_data["rotation"])) pose = np.dot(pose_car, car_to_velo) scan = np.fromfile(os.path.join(dataroot, lidar_data["filename"]), dtype=np.float32) points = scan.reshape((-1, 5))[:, :4] # ensure that remission is in [0,1] max_remission = np.max(points[:, 3]) min_remission = np.min(points[:, 3]) points[:, 3] = (points[:, 3] - min_remission) / (max_remission - min_remission) output_filename = os.path.join(velodyne_folder, "{:05d}.bin".format(len(lidar_filenames))) points.tofile(output_filename) original.append(("{:05d}.bin".format(len(lidar_filenames)), lidar_data["filename"])) poses.append(pose) lidar_filenames.append(os.path.join(dataroot, lidar_data["filename"])) current_lidar = lidar_data["next"] ref = la.inv(poses[0]) pose_file = open(os.path.join(output_folder, "poses.txt"), "w") for pose in poses: pose_str = [str(v) for v in (np.dot(ref, pose))[:3,:4].flatten()] pose_file.write(" ".join(pose_str)) pose_file.write("\n") print("{} scans read.".format(len(lidar_filenames))) pose_file.close() # write dummy calibration. calib_file = open(os.path.join(output_folder, "calib.txt"), "w") calib_file.write("P0: 1 0 0 0 0 1 0 0 0 0 1 0\n") calib_file.write("P1: 1 0 0 0 0 1 0 0 0 0 1 0\n") calib_file.write("P2: 1 0 0 0 0 1 0 0 0 0 1 0\n") calib_file.write("P3: 1 0 0 0 0 1 0 0 0 0 1 0\n") calib_file.write("Tr: 1 0 0 0 0 1 0 0 0 0 1 0\n") calib_file.close() original_file = open(os.path.join(output_folder, "original.txt"), "w") for pair in original: original_file.write(pair[0] + ":" + pair[1] + "\n") original_file.close()
[ "os.makedirs", "nuscenes.nuscenes.NuScenes", "os.path.exists", "numpy.max", "numpy.min", "numpy.linalg.inv", "pyquaternion.Quaternion", "numpy.dot", "os.path.join" ]
[((414, 476), 'nuscenes.nuscenes.NuScenes', 'NuScenes', ([], {'version': '"""v1.0-mini"""', 'dataroot': 'dataroot', 'verbose': '(True)'}), "(version='v1.0-mini', dataroot=dataroot, verbose=True)\n", (422, 476), False, 'from nuscenes.nuscenes import NuScenes\n'), ((1018, 1055), 'os.path.join', 'os.path.join', (['sys.argv[2]', 'scene_name'], {}), '(sys.argv[2], scene_name)\n', (1030, 1055), False, 'import os\n'), ((1082, 1122), 'os.path.join', 'os.path.join', (['output_folder', '"""velodyne/"""'], {}), "(output_folder, 'velodyne/')\n", (1094, 1122), False, 'import os\n'), ((3063, 3079), 'numpy.linalg.inv', 'la.inv', (['poses[0]'], {}), '(poses[0])\n', (3069, 3079), True, 'import numpy.linalg as la\n'), ((1457, 1488), 'os.path.exists', 'os.path.exists', (['velodyne_folder'], {}), '(velodyne_folder)\n', (1471, 1488), False, 'import os\n'), ((1572, 1600), 'os.makedirs', 'os.makedirs', (['velodyne_folder'], {}), '(velodyne_folder)\n', (1583, 1600), False, 'import os\n'), ((2173, 2202), 'numpy.dot', 'np.dot', (['pose_car', 'car_to_velo'], {}), '(pose_car, car_to_velo)\n', (2179, 2202), True, 'import numpy as np\n'), ((2440, 2460), 'numpy.max', 'np.max', (['points[:, 3]'], {}), '(points[:, 3])\n', (2446, 2460), True, 'import numpy as np\n'), ((2489, 2509), 'numpy.min', 'np.min', (['points[:, 3]'], {}), '(points[:, 3])\n', (2495, 2509), True, 'import numpy as np\n'), ((3105, 3145), 'os.path.join', 'os.path.join', (['output_folder', '"""poses.txt"""'], {}), "(output_folder, 'poses.txt')\n", (3117, 3145), False, 'import os\n'), ((3490, 3530), 'os.path.join', 'os.path.join', (['output_folder', '"""calib.txt"""'], {}), "(output_folder, 'calib.txt')\n", (3502, 3530), False, 'import os\n'), ((3884, 3927), 'os.path.join', 'os.path.join', (['output_folder', '"""original.txt"""'], {}), "(output_folder, 'original.txt')\n", (3896, 3927), False, 'import os\n'), ((1989, 2023), 'pyquaternion.Quaternion', 'Quaternion', (["calib_data['rotation']"], {}), "(calib_data['rotation'])\n", (1999, 2023), False, 'from pyquaternion import Quaternion\n'), ((2103, 2139), 'pyquaternion.Quaternion', 'Quaternion', (["egopose_data['rotation']"], {}), "(egopose_data['rotation'])\n", (2113, 2139), False, 'from pyquaternion import Quaternion\n'), ((2247, 2293), 'os.path.join', 'os.path.join', (['dataroot', "lidar_data['filename']"], {}), "(dataroot, lidar_data['filename'])\n", (2259, 2293), False, 'import os\n'), ((2939, 2985), 'os.path.join', 'os.path.join', (['dataroot', "lidar_data['filename']"], {}), "(dataroot, lidar_data['filename'])\n", (2951, 2985), False, 'import os\n'), ((3220, 3237), 'numpy.dot', 'np.dot', (['ref', 'pose'], {}), '(ref, pose)\n', (3226, 3237), True, 'import numpy as np\n')]
""" Test the various utilities in serpentTools/utils.py """ from unittest import TestCase from numpy import arange, ndarray, array, ones, ones_like, zeros_like from numpy.testing import assert_array_equal from serpentTools.utils import ( convertVariableName, splitValsUncs, str2vec, getCommonKeys, directCompare, getOverlaps, splitDictByKeys, DC_STAT_GOOD, DC_STAT_LE_LOWER, DC_STAT_MID, DC_STAT_GE_UPPER, DC_STAT_NOT_IDENTICAL, DC_STAT_NOT_IMPLEMENTED, DC_STAT_DIFF_TYPES, DC_STAT_DIFF_SHAPES, formatPlot, ) from tests import plotTest, plotAttrTest class VariableConverterTester(TestCase): """Class for testing our variable name conversion function.""" def test_variableConversion(self): """ Verify the variable name conversion function.""" testCases = { "VERSION": "version", "INF_KINF": "infKinf", "ADJ_PERT_KEFF_SENS": "adjPertKeffSens", } for serpentStyle, expected in testCases.items(): actual = convertVariableName(serpentStyle) self.assertEqual(expected, actual, msg=serpentStyle) class VectorConverterTester(TestCase): """Class for testing the str2vec function""" @classmethod def setUpClass(cls): cls.testCases = ("0 1 2 3", [0, 1, 2, 3], (0, 1, 2, 3), arange(4)) def test_str2Arrays(self): """Verify that the str2vec converts to arrays.""" expected = arange(4) for case in self.testCases: actual = str2vec(case) assert_array_equal(expected, actual, err_msg=case) def test_listOfInts(self): """Verify that a list of ints can be produced with str2vec.""" expected = [0, 1, 2, 3] self._runConversionTest(int, expected, list) def test_vecOfStr(self): """Verify a single word can be converted with str2vec""" key = 'ADF' expected = array('ADF') actual = str2vec(key) assert_array_equal(expected, actual) def _runConversionTest(self, valType, expected, outType=None): if outType is None: outType = array compareType = ndarray else: compareType = outType for case in self.testCases: actual = str2vec(case, dtype=valType, out=outType) self.assertIsInstance(actual, compareType, msg=case) ofRightType = [isinstance(xx, valType) for xx in actual] self.assertTrue(all(ofRightType), msg="{} -> {}, {}".format(case, actual, type(actual))) self.assertEqual(expected, actual, msg=case) class SplitValsTester(TestCase): """Class that tests splitValsUncs.""" @classmethod def setUp(cls): cls.input = arange(4) def test_splitVals(self): """Verify the basic functionality.""" expectedV = array([0, 2]) expectedU = array([1, 3]) actualV, actualU = splitValsUncs(self.input) assert_array_equal(expectedV, actualV, err_msg="Values") assert_array_equal(expectedU, actualU, err_msg="Uncertainties") def test_splitCopy(self): """Verfiy that a copy, not a view, is returned when copy=True""" viewV, viewU = splitValsUncs(self.input) copyV, copyU = splitValsUncs(self.input, copy=True) for view, copy, msg in zip( (viewV, viewU), (copyV, copyU), ('value', 'uncertainty')): assert_array_equal(view, copy, err_msg=msg) self.assertFalse(view is copy, msg=msg) def test_splitAtCols(self): """Verify that the splitValsUncs works for 2D arrays.""" mat = self.input.reshape(2, 2) expectedV = array([[0], [2]]) expectedU = array([[1], [3]]) actualV, actualU = splitValsUncs(mat) assert_array_equal(expectedV, actualV, err_msg="Values") assert_array_equal(expectedU, actualU, err_msg="Uncertainties") class CommonKeysTester(TestCase): """Class that tests getCommonKeys""" def test_goodKeys_dict(self): """Verify a complete set of keys is returned from getCommonKeys""" d0 = {1: None, '2': None, (1, 2, 3): "tuple"} expected = set(d0.keys()) actual = getCommonKeys(d0, d0, 'identical dictionary') self.assertSetEqual(expected, actual, msg="Passed two dictionaries") actual = getCommonKeys(d0, expected, 'dictionary and set') self.assertSetEqual(expected, actual, msg="Passed dictionary and set") def test_getKeys_missing(self): """Verify that missing keys are properly notified.""" log = [] d0 = {1, 2, 3} emptyS = set() desc0 = "xObj0x" desc1 = "xObj1x" common = getCommonKeys(d0, emptyS, 'missing keys', desc0, desc1, herald=log.append) self.assertSetEqual(emptyS, common) self.assertEqual(len(log), 1, msg="Failed to append warning message") warnMsg = log[0] self.assertIsInstance(warnMsg, str, msg="Log messages is not string") for desc in (desc0, desc1): errMsg = "Description {} missing from warning message\n{}" self.assertIn(desc, warnMsg, msg=errMsg.format(desc, warnMsg)) class DirectCompareTester(TestCase): """Class for testing utils.directCompare.""" NUMERIC_ITEMS = ( [0, 0.001], [1E-8, 0], [array([1, 1, ]), array([1, 1.0001])], ) def checkStatus(self, expected, obj0, obj1, lower, upper, msg=None): """Wrapper around directCompare with ``args``. Pass ``kwargs`` to assertEqual.""" actual = directCompare(obj0, obj1, lower, upper) self.assertEqual(expected, actual, msg=msg) def test_badTypes(self): """Verify that two objects of different types return -1.""" status = DC_STAT_DIFF_TYPES value = 1 for otherType in (bool, str): self.checkStatus(status, value, otherType(value), 0, 1, msg=str(otherType)) asIterable = [value, ] for otherType in (list, set, tuple, array): self.checkStatus(status, value, otherType(asIterable), 0, 1, msg=str(otherType)) def test_identicalString(self): """Verify that identical strings return 0.""" msg = obj = 'identicalStrings' status = DC_STAT_GOOD self.checkStatus(status, obj, obj, 0, 1, msg=msg) def test_dissimilarString(self): """Verify returns the proper code for dissimilar strings.""" msg = "dissimilarStrings" status = DC_STAT_NOT_IDENTICAL self.checkStatus(status, 'item0', 'item1', 0, 1, msg=msg) def _testNumericsForItems(self, status, lower, upper): msg = "lower: {lower}, upper: {upper}\n{}\n{}" for (obj0, obj1) in self.NUMERIC_ITEMS: self.checkStatus(status, obj0, obj1, lower, upper, msg=msg.format(obj0, obj1, lower=lower, upper=upper)) def test_acceptableLow(self): """Verify returns the proper code for close numerics.""" lower = 5 upper = 1E4 self._testNumericsForItems(DC_STAT_LE_LOWER, lower, upper) def test_acceptableHigh(self): """Verify returns the proper code for close but not quite values.""" lower = 0 upper = 1E4 self._testNumericsForItems(DC_STAT_MID, lower, upper) def test_outsideTols(self): """Verify returns the proper code for values outside tolerances.""" lower = 1E-8 upper = 1E-8 self._testNumericsForItems(DC_STAT_GE_UPPER, lower, upper) def test_notImplemented(self): """Check the not-implemented cases.""" self.checkStatus(DC_STAT_NOT_IMPLEMENTED, {'hello': 'world'}, {'hello': 'world'}, 0, 0, msg="testing on dictionaries") def test_stringArrays(self): """Verify the function handles string arrays properly.""" stringList = ['hello', 'world', '1', '-1'] vec0 = array(stringList) self.checkStatus(DC_STAT_GOOD, vec0, vec0, 0, 0, msg='Identical string arrays') vec1 = array(stringList) vec1[-1] = 'foobar' self.checkStatus(DC_STAT_NOT_IDENTICAL, vec0, vec1, 0, 0, msg='Dissimilar string arrays') def test_diffShapes(self): """ Verify that that directCompare fails for arrays of different shape. """ vec0 = [0, 1, 2, 3, 4] vec1 = [0, 1] mat0 = [[0, 1], [1, 2]] mat1 = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] self.checkStatus(DC_STAT_DIFF_SHAPES, vec0, vec1, 0, 0, msg="Compare two vectors.") self.checkStatus(DC_STAT_DIFF_SHAPES, vec0, mat0, 0, 0, msg="Compare vector and array.") self.checkStatus(DC_STAT_DIFF_SHAPES, mat0, mat1, 0, 0, msg="Compare vector and array.") class OverlapTester(TestCase): """Class for testing the Overlapping uncertainties function.""" a0 = ones(4) a1 = ones(4) * 0.5 u0 = array([0, 0.2, 0.1, 0.2]) u1 = array([1, 0.55, 0.25, 0.4]) expected = array([True, True, False, True]) sigma = 1 relative = False _errMsg = "Sigma:{}\na0:\n{}\nu0:\n{}\na1:\n{}\nu1:\n{}" def _test(self, expected, a0, a1, u0, u1, sigma, relative): """Symmetric test on the data by switching the order of arguments.""" assert_array_equal(expected, getOverlaps(a0, a1, u0, u1, sigma, relative), err_msg=self._errMsg.format(a0, u0, a1, u1, sigma)) assert_array_equal(expected, getOverlaps(a1, a0, u1, u0, sigma, relative), err_msg=self._errMsg.format(sigma, a1, u1, a0, u0)) def _testWithReshapes(self, expected, a0, a1, u0, u1, sigma, shape, relative): """Call symmetric test twice, using reshaped arrays the second time.""" self._test(expected, a0, a1, u0, u1, sigma, relative) ra0, ra1, ru0, ru1 = [arg.reshape(*shape) for arg in [a0, a1, u0, u1]] self._test(expected.reshape(*shape), ra0, ra1, ru0, ru1, sigma, relative) def test_overlap_absolute(self): """Verify the getOverlaps works using absolute uncertainties.""" self._testWithReshapes(self.expected, self.a0, self.a1, self.u0, self.u1, self.sigma, (2, 2), False) def test_overlap_relative(self): """Verify the getOverlaps works using relative uncertainties.""" u0 = self.u0 / self.a0 u1 = self.u1 / self.a1 self._testWithReshapes(self.expected, self.a0, self.a1, u0, u1, self.sigma, (2, 2), True) @staticmethod def _setupIdentical(nItems, shape=None): arr = arange(nItems) if shape is not None: arr = arr.reshape(*shape) unc = zeros_like(arr) expected = ones_like(arr, dtype=bool) return arr, unc, expected def test_overlap_identical_1D(self): """ Verify that all positions are found to overlap for identical arrays. """ vec, unc, expected = self._setupIdentical(8) self._test(expected, vec, vec, unc, unc, 1, False) def test_overlap_identical_2D(self): """ Verify that all positions are found to overlap for identical arrays. """ vec, unc, expected = self._setupIdentical(8, (2, 4)) self._test(expected, vec, vec, unc, unc, 1, False) def test_overlap_identical_3D(self): """ Verify that all positions are found to overlap for identical arrays. """ vec, unc, expected = self._setupIdentical(8, (2, 2, 2)) self._test(expected, vec, vec, unc, unc, 1, False) def test_overlap_badshapes(self): """Verify IndexError is raised for bad shapes.""" vec = arange(4) mat = vec.reshape(2, 2) with self.assertRaises(IndexError): getOverlaps(vec, mat, vec, mat, 1) class SplitDictionaryTester(TestCase): """Class for testing utils.splitDictByKeys.""" @classmethod def setUpClass(cls): cls.map0 = { 'hello': 'world', 'missingFrom1': True, 'infKeff': arange(2), 'float': 0.24, 'absKeff': arange(2), 'anaKeff': arange(6), 'notBool': 1, } cls.map1 = { 'hello': 'world', 'infKeff': arange(2), 'float': 0.24, 'missingFrom0': True, 'notBool': False, 'anaKeff': arange(2), 'absKeff': arange(2), } cls.badTypes = {'notBool': (int, bool)} cls.badShapes = {'anaKeff': ((6, ), (2, )), } cls.goodKeys = {'hello', 'absKeff', 'float', 'infKeff', } def callTest(self, keySet=None): return splitDictByKeys(self.map0, self.map1, keySet) def test_noKeys(self): """Verify that splitDictByKeys works when keySet is None.""" m0, m1, badTypes, badShapes, goodKeys = self.callTest(None) self.assertSetEqual({'missingFrom0', }, m0) self.assertSetEqual({'missingFrom1', }, m1) self.assertDictEqual(self.badTypes, badTypes) self.assertDictEqual(self.badShapes, badShapes) self.assertSetEqual(self.goodKeys, goodKeys) def test_keySet_all(self): """Verify that splitDictByKeys works when keySet is all keys.""" keys = set(self.map0.keys()) keys.update(set(self.map1.keys())) keys.add('NOT IN ANY MAP') missing0 = set() missing1 = set() for key in keys: if key not in self.map0: missing0.add(key) if key not in self.map1: missing1.add(key) m0, m1, badTypes, badShapes, goodKeys = self.callTest(keys) self.assertSetEqual(missing0, m0) self.assertSetEqual(missing1, m1) self.assertDictEqual(self.badTypes, badTypes) self.assertDictEqual(self.badShapes, badShapes) self.assertSetEqual(self.goodKeys, goodKeys) class PlotTestTester(TestCase): """Class to test the validity of the plot test utils""" XLABEL = "Test x label" YLABEL = "Test y label" def buildPlot(self): from matplotlib.pyplot import gca ax = gca() ax.plot([1, 2, 3], label=1) ax.legend() ax.set_ylabel(self.YLABEL) ax.set_xlabel(self.XLABEL) return ax @plotTest def test_plotAttrs_gca(self): """Test the plotAttrTest without passing an axes object""" self.buildPlot() plotAttrTest(self, xlabel=self.XLABEL, ylabel=self.YLABEL) @plotTest def test_plotAttrs_fail(self): """Test the failure modes of the plotAttrTest function""" ax = self.buildPlot() with self.assertRaisesRegex(AssertionError, 'xlabel'): plotAttrTest(self, ax, xlabel="Bad label") with self.assertRaisesRegex(AssertionError, 'ylabel'): plotAttrTest(self, ax, ylabel="Bad label") with self.assertRaisesRegex(AssertionError, 'xscale'): plotAttrTest(self, ax, xscale="log") with self.assertRaisesRegex(AssertionError, 'yscale'): plotAttrTest(self, ax, yscale="log") with self.assertRaisesRegex(AssertionError, 'legend text'): plotAttrTest(self, ax, legendLabels='bad text') with self.assertRaisesRegex(AssertionError, 'legend text'): plotAttrTest(self, ax, legendLabels=['1', '2']) with self.assertRaisesRegex(AssertionError, 'title'): plotAttrTest(self, ax, title='Bad title') @plotTest def test_formatPlot(self): """Test the capabilities of the formatPlot function""" ax = self.buildPlot() newX = 'new x label' newY = 'new y label' title = 'plot title' formatPlot(ax, xlabel=newX, ylabel=newY, loglog=True, title=title) plotAttrTest(self, ax, xlabel=newX, ylabel=newY, xscale='log', yscale='log', title=title)
[ "numpy.zeros_like", "numpy.ones_like", "serpentTools.utils.formatPlot", "numpy.testing.assert_array_equal", "serpentTools.utils.splitValsUncs", "numpy.ones", "serpentTools.utils.directCompare", "tests.plotAttrTest", "serpentTools.utils.getOverlaps", "serpentTools.utils.getCommonKeys", "serpentTools.utils.splitDictByKeys", "numpy.arange", "numpy.array", "serpentTools.utils.str2vec", "matplotlib.pyplot.gca", "serpentTools.utils.convertVariableName" ]
[((9305, 9312), 'numpy.ones', 'ones', (['(4)'], {}), '(4)\n', (9309, 9312), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((9345, 9370), 'numpy.array', 'array', (['[0, 0.2, 0.1, 0.2]'], {}), '([0, 0.2, 0.1, 0.2])\n', (9350, 9370), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((9380, 9407), 'numpy.array', 'array', (['[1, 0.55, 0.25, 0.4]'], {}), '([1, 0.55, 0.25, 0.4])\n', (9385, 9407), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((9423, 9455), 'numpy.array', 'array', (['[True, True, False, True]'], {}), '([True, True, False, True])\n', (9428, 9455), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((1477, 1486), 'numpy.arange', 'arange', (['(4)'], {}), '(4)\n', (1483, 1486), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((1943, 1955), 'numpy.array', 'array', (['"""ADF"""'], {}), "('ADF')\n", (1948, 1955), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((1973, 1985), 'serpentTools.utils.str2vec', 'str2vec', (['key'], {}), '(key)\n', (1980, 1985), False, 'from serpentTools.utils import convertVariableName, splitValsUncs, str2vec, getCommonKeys, directCompare, getOverlaps, splitDictByKeys, DC_STAT_GOOD, DC_STAT_LE_LOWER, DC_STAT_MID, DC_STAT_GE_UPPER, DC_STAT_NOT_IDENTICAL, DC_STAT_NOT_IMPLEMENTED, DC_STAT_DIFF_TYPES, DC_STAT_DIFF_SHAPES, formatPlot\n'), ((1994, 2030), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['expected', 'actual'], {}), '(expected, actual)\n', (2012, 2030), False, 'from numpy.testing import assert_array_equal\n'), ((2845, 2854), 'numpy.arange', 'arange', (['(4)'], {}), '(4)\n', (2851, 2854), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((2952, 2965), 'numpy.array', 'array', (['[0, 2]'], {}), '([0, 2])\n', (2957, 2965), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((2986, 2999), 'numpy.array', 'array', (['[1, 3]'], {}), '([1, 3])\n', (2991, 2999), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((3027, 3052), 'serpentTools.utils.splitValsUncs', 'splitValsUncs', (['self.input'], {}), '(self.input)\n', (3040, 3052), False, 'from serpentTools.utils import convertVariableName, splitValsUncs, str2vec, getCommonKeys, directCompare, getOverlaps, splitDictByKeys, DC_STAT_GOOD, DC_STAT_LE_LOWER, DC_STAT_MID, DC_STAT_GE_UPPER, DC_STAT_NOT_IDENTICAL, DC_STAT_NOT_IMPLEMENTED, DC_STAT_DIFF_TYPES, DC_STAT_DIFF_SHAPES, formatPlot\n'), ((3061, 3117), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['expectedV', 'actualV'], {'err_msg': '"""Values"""'}), "(expectedV, actualV, err_msg='Values')\n", (3079, 3117), False, 'from numpy.testing import assert_array_equal\n'), ((3126, 3189), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['expectedU', 'actualU'], {'err_msg': '"""Uncertainties"""'}), "(expectedU, actualU, err_msg='Uncertainties')\n", (3144, 3189), False, 'from numpy.testing import assert_array_equal\n'), ((3317, 3342), 'serpentTools.utils.splitValsUncs', 'splitValsUncs', (['self.input'], {}), '(self.input)\n', (3330, 3342), False, 'from serpentTools.utils import convertVariableName, splitValsUncs, str2vec, getCommonKeys, directCompare, getOverlaps, splitDictByKeys, DC_STAT_GOOD, DC_STAT_LE_LOWER, DC_STAT_MID, DC_STAT_GE_UPPER, DC_STAT_NOT_IDENTICAL, DC_STAT_NOT_IMPLEMENTED, DC_STAT_DIFF_TYPES, DC_STAT_DIFF_SHAPES, formatPlot\n'), ((3366, 3402), 'serpentTools.utils.splitValsUncs', 'splitValsUncs', (['self.input'], {'copy': '(True)'}), '(self.input, copy=True)\n', (3379, 3402), False, 'from serpentTools.utils import convertVariableName, splitValsUncs, str2vec, getCommonKeys, directCompare, getOverlaps, splitDictByKeys, DC_STAT_GOOD, DC_STAT_LE_LOWER, DC_STAT_MID, DC_STAT_GE_UPPER, DC_STAT_NOT_IDENTICAL, DC_STAT_NOT_IMPLEMENTED, DC_STAT_DIFF_TYPES, DC_STAT_DIFF_SHAPES, formatPlot\n'), ((3779, 3796), 'numpy.array', 'array', (['[[0], [2]]'], {}), '([[0], [2]])\n', (3784, 3796), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((3817, 3834), 'numpy.array', 'array', (['[[1], [3]]'], {}), '([[1], [3]])\n', (3822, 3834), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((3862, 3880), 'serpentTools.utils.splitValsUncs', 'splitValsUncs', (['mat'], {}), '(mat)\n', (3875, 3880), False, 'from serpentTools.utils import convertVariableName, splitValsUncs, str2vec, getCommonKeys, directCompare, getOverlaps, splitDictByKeys, DC_STAT_GOOD, DC_STAT_LE_LOWER, DC_STAT_MID, DC_STAT_GE_UPPER, DC_STAT_NOT_IDENTICAL, DC_STAT_NOT_IMPLEMENTED, DC_STAT_DIFF_TYPES, DC_STAT_DIFF_SHAPES, formatPlot\n'), ((3889, 3945), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['expectedV', 'actualV'], {'err_msg': '"""Values"""'}), "(expectedV, actualV, err_msg='Values')\n", (3907, 3945), False, 'from numpy.testing import assert_array_equal\n'), ((3954, 4017), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['expectedU', 'actualU'], {'err_msg': '"""Uncertainties"""'}), "(expectedU, actualU, err_msg='Uncertainties')\n", (3972, 4017), False, 'from numpy.testing import assert_array_equal\n'), ((4310, 4355), 'serpentTools.utils.getCommonKeys', 'getCommonKeys', (['d0', 'd0', '"""identical dictionary"""'], {}), "(d0, d0, 'identical dictionary')\n", (4323, 4355), False, 'from serpentTools.utils import convertVariableName, splitValsUncs, str2vec, getCommonKeys, directCompare, getOverlaps, splitDictByKeys, DC_STAT_GOOD, DC_STAT_LE_LOWER, DC_STAT_MID, DC_STAT_GE_UPPER, DC_STAT_NOT_IDENTICAL, DC_STAT_NOT_IMPLEMENTED, DC_STAT_DIFF_TYPES, DC_STAT_DIFF_SHAPES, formatPlot\n'), ((4478, 4527), 'serpentTools.utils.getCommonKeys', 'getCommonKeys', (['d0', 'expected', '"""dictionary and set"""'], {}), "(d0, expected, 'dictionary and set')\n", (4491, 4527), False, 'from serpentTools.utils import convertVariableName, splitValsUncs, str2vec, getCommonKeys, directCompare, getOverlaps, splitDictByKeys, DC_STAT_GOOD, DC_STAT_LE_LOWER, DC_STAT_MID, DC_STAT_GE_UPPER, DC_STAT_NOT_IDENTICAL, DC_STAT_NOT_IMPLEMENTED, DC_STAT_DIFF_TYPES, DC_STAT_DIFF_SHAPES, formatPlot\n'), ((4864, 4938), 'serpentTools.utils.getCommonKeys', 'getCommonKeys', (['d0', 'emptyS', '"""missing keys"""', 'desc0', 'desc1'], {'herald': 'log.append'}), "(d0, emptyS, 'missing keys', desc0, desc1, herald=log.append)\n", (4877, 4938), False, 'from serpentTools.utils import convertVariableName, splitValsUncs, str2vec, getCommonKeys, directCompare, getOverlaps, splitDictByKeys, DC_STAT_GOOD, DC_STAT_LE_LOWER, DC_STAT_MID, DC_STAT_GE_UPPER, DC_STAT_NOT_IDENTICAL, DC_STAT_NOT_IMPLEMENTED, DC_STAT_DIFF_TYPES, DC_STAT_DIFF_SHAPES, formatPlot\n'), ((5769, 5808), 'serpentTools.utils.directCompare', 'directCompare', (['obj0', 'obj1', 'lower', 'upper'], {}), '(obj0, obj1, lower, upper)\n', (5782, 5808), False, 'from serpentTools.utils import convertVariableName, splitValsUncs, str2vec, getCommonKeys, directCompare, getOverlaps, splitDictByKeys, DC_STAT_GOOD, DC_STAT_LE_LOWER, DC_STAT_MID, DC_STAT_GE_UPPER, DC_STAT_NOT_IDENTICAL, DC_STAT_NOT_IMPLEMENTED, DC_STAT_DIFF_TYPES, DC_STAT_DIFF_SHAPES, formatPlot\n'), ((8252, 8269), 'numpy.array', 'array', (['stringList'], {}), '(stringList)\n', (8257, 8269), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((8398, 8415), 'numpy.array', 'array', (['stringList'], {}), '(stringList)\n', (8403, 8415), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((9322, 9329), 'numpy.ones', 'ones', (['(4)'], {}), '(4)\n', (9326, 9329), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((11181, 11195), 'numpy.arange', 'arange', (['nItems'], {}), '(nItems)\n', (11187, 11195), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((11278, 11293), 'numpy.zeros_like', 'zeros_like', (['arr'], {}), '(arr)\n', (11288, 11293), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((11313, 11339), 'numpy.ones_like', 'ones_like', (['arr'], {'dtype': 'bool'}), '(arr, dtype=bool)\n', (11322, 11339), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((12269, 12278), 'numpy.arange', 'arange', (['(4)'], {}), '(4)\n', (12275, 12278), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((13262, 13307), 'serpentTools.utils.splitDictByKeys', 'splitDictByKeys', (['self.map0', 'self.map1', 'keySet'], {}), '(self.map0, self.map1, keySet)\n', (13277, 13307), False, 'from serpentTools.utils import convertVariableName, splitValsUncs, str2vec, getCommonKeys, directCompare, getOverlaps, splitDictByKeys, DC_STAT_GOOD, DC_STAT_LE_LOWER, DC_STAT_MID, DC_STAT_GE_UPPER, DC_STAT_NOT_IDENTICAL, DC_STAT_NOT_IMPLEMENTED, DC_STAT_DIFF_TYPES, DC_STAT_DIFF_SHAPES, formatPlot\n'), ((14724, 14729), 'matplotlib.pyplot.gca', 'gca', ([], {}), '()\n', (14727, 14729), False, 'from matplotlib.pyplot import gca\n'), ((15023, 15081), 'tests.plotAttrTest', 'plotAttrTest', (['self'], {'xlabel': 'self.XLABEL', 'ylabel': 'self.YLABEL'}), '(self, xlabel=self.XLABEL, ylabel=self.YLABEL)\n', (15035, 15081), False, 'from tests import plotTest, plotAttrTest\n'), ((16294, 16360), 'serpentTools.utils.formatPlot', 'formatPlot', (['ax'], {'xlabel': 'newX', 'ylabel': 'newY', 'loglog': '(True)', 'title': 'title'}), '(ax, xlabel=newX, ylabel=newY, loglog=True, title=title)\n', (16304, 16360), False, 'from serpentTools.utils import convertVariableName, splitValsUncs, str2vec, getCommonKeys, directCompare, getOverlaps, splitDictByKeys, DC_STAT_GOOD, DC_STAT_LE_LOWER, DC_STAT_MID, DC_STAT_GE_UPPER, DC_STAT_NOT_IDENTICAL, DC_STAT_NOT_IMPLEMENTED, DC_STAT_DIFF_TYPES, DC_STAT_DIFF_SHAPES, formatPlot\n'), ((16388, 16481), 'tests.plotAttrTest', 'plotAttrTest', (['self', 'ax'], {'xlabel': 'newX', 'ylabel': 'newY', 'xscale': '"""log"""', 'yscale': '"""log"""', 'title': 'title'}), "(self, ax, xlabel=newX, ylabel=newY, xscale='log', yscale='log',\n title=title)\n", (16400, 16481), False, 'from tests import plotTest, plotAttrTest\n'), ((1061, 1094), 'serpentTools.utils.convertVariableName', 'convertVariableName', (['serpentStyle'], {}), '(serpentStyle)\n', (1080, 1094), False, 'from serpentTools.utils import convertVariableName, splitValsUncs, str2vec, getCommonKeys, directCompare, getOverlaps, splitDictByKeys, DC_STAT_GOOD, DC_STAT_LE_LOWER, DC_STAT_MID, DC_STAT_GE_UPPER, DC_STAT_NOT_IDENTICAL, DC_STAT_NOT_IMPLEMENTED, DC_STAT_DIFF_TYPES, DC_STAT_DIFF_SHAPES, formatPlot\n'), ((1357, 1366), 'numpy.arange', 'arange', (['(4)'], {}), '(4)\n', (1363, 1366), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((1544, 1557), 'serpentTools.utils.str2vec', 'str2vec', (['case'], {}), '(case)\n', (1551, 1557), False, 'from serpentTools.utils import convertVariableName, splitValsUncs, str2vec, getCommonKeys, directCompare, getOverlaps, splitDictByKeys, DC_STAT_GOOD, DC_STAT_LE_LOWER, DC_STAT_MID, DC_STAT_GE_UPPER, DC_STAT_NOT_IDENTICAL, DC_STAT_NOT_IMPLEMENTED, DC_STAT_DIFF_TYPES, DC_STAT_DIFF_SHAPES, formatPlot\n'), ((1570, 1620), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['expected', 'actual'], {'err_msg': 'case'}), '(expected, actual, err_msg=case)\n', (1588, 1620), False, 'from numpy.testing import assert_array_equal\n'), ((2294, 2335), 'serpentTools.utils.str2vec', 'str2vec', (['case'], {'dtype': 'valType', 'out': 'outType'}), '(case, dtype=valType, out=outType)\n', (2301, 2335), False, 'from serpentTools.utils import convertVariableName, splitValsUncs, str2vec, getCommonKeys, directCompare, getOverlaps, splitDictByKeys, DC_STAT_GOOD, DC_STAT_LE_LOWER, DC_STAT_MID, DC_STAT_GE_UPPER, DC_STAT_NOT_IDENTICAL, DC_STAT_NOT_IMPLEMENTED, DC_STAT_DIFF_TYPES, DC_STAT_DIFF_SHAPES, formatPlot\n'), ((3526, 3569), 'numpy.testing.assert_array_equal', 'assert_array_equal', (['view', 'copy'], {'err_msg': 'msg'}), '(view, copy, err_msg=msg)\n', (3544, 3569), False, 'from numpy.testing import assert_array_equal\n'), ((5536, 5549), 'numpy.array', 'array', (['[1, 1]'], {}), '([1, 1])\n', (5541, 5549), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((5553, 5571), 'numpy.array', 'array', (['[1, 1.0001]'], {}), '([1, 1.0001])\n', (5558, 5571), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((9733, 9777), 'serpentTools.utils.getOverlaps', 'getOverlaps', (['a0', 'a1', 'u0', 'u1', 'sigma', 'relative'], {}), '(a0, a1, u0, u1, sigma, relative)\n', (9744, 9777), False, 'from serpentTools.utils import convertVariableName, splitValsUncs, str2vec, getCommonKeys, directCompare, getOverlaps, splitDictByKeys, DC_STAT_GOOD, DC_STAT_LE_LOWER, DC_STAT_MID, DC_STAT_GE_UPPER, DC_STAT_NOT_IDENTICAL, DC_STAT_NOT_IMPLEMENTED, DC_STAT_DIFF_TYPES, DC_STAT_DIFF_SHAPES, formatPlot\n'), ((9944, 9988), 'serpentTools.utils.getOverlaps', 'getOverlaps', (['a1', 'a0', 'u1', 'u0', 'sigma', 'relative'], {}), '(a1, a0, u1, u0, sigma, relative)\n', (9955, 9988), False, 'from serpentTools.utils import convertVariableName, splitValsUncs, str2vec, getCommonKeys, directCompare, getOverlaps, splitDictByKeys, DC_STAT_GOOD, DC_STAT_LE_LOWER, DC_STAT_MID, DC_STAT_GE_UPPER, DC_STAT_NOT_IDENTICAL, DC_STAT_NOT_IMPLEMENTED, DC_STAT_DIFF_TYPES, DC_STAT_DIFF_SHAPES, formatPlot\n'), ((12367, 12401), 'serpentTools.utils.getOverlaps', 'getOverlaps', (['vec', 'mat', 'vec', 'mat', '(1)'], {}), '(vec, mat, vec, mat, 1)\n', (12378, 12401), False, 'from serpentTools.utils import convertVariableName, splitValsUncs, str2vec, getCommonKeys, directCompare, getOverlaps, splitDictByKeys, DC_STAT_GOOD, DC_STAT_LE_LOWER, DC_STAT_MID, DC_STAT_GE_UPPER, DC_STAT_NOT_IDENTICAL, DC_STAT_NOT_IMPLEMENTED, DC_STAT_DIFF_TYPES, DC_STAT_DIFF_SHAPES, formatPlot\n'), ((12645, 12654), 'numpy.arange', 'arange', (['(2)'], {}), '(2)\n', (12651, 12654), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((12706, 12715), 'numpy.arange', 'arange', (['(2)'], {}), '(2)\n', (12712, 12715), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((12740, 12749), 'numpy.arange', 'arange', (['(6)'], {}), '(6)\n', (12746, 12749), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((12861, 12870), 'numpy.arange', 'arange', (['(2)'], {}), '(2)\n', (12867, 12870), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((12986, 12995), 'numpy.arange', 'arange', (['(2)'], {}), '(2)\n', (12992, 12995), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((13020, 13029), 'numpy.arange', 'arange', (['(2)'], {}), '(2)\n', (13026, 13029), False, 'from numpy import arange, ndarray, array, ones, ones_like, zeros_like\n'), ((15303, 15345), 'tests.plotAttrTest', 'plotAttrTest', (['self', 'ax'], {'xlabel': '"""Bad label"""'}), "(self, ax, xlabel='Bad label')\n", (15315, 15345), False, 'from tests import plotTest, plotAttrTest\n'), ((15421, 15463), 'tests.plotAttrTest', 'plotAttrTest', (['self', 'ax'], {'ylabel': '"""Bad label"""'}), "(self, ax, ylabel='Bad label')\n", (15433, 15463), False, 'from tests import plotTest, plotAttrTest\n'), ((15539, 15575), 'tests.plotAttrTest', 'plotAttrTest', (['self', 'ax'], {'xscale': '"""log"""'}), "(self, ax, xscale='log')\n", (15551, 15575), False, 'from tests import plotTest, plotAttrTest\n'), ((15651, 15687), 'tests.plotAttrTest', 'plotAttrTest', (['self', 'ax'], {'yscale': '"""log"""'}), "(self, ax, yscale='log')\n", (15663, 15687), False, 'from tests import plotTest, plotAttrTest\n'), ((15768, 15815), 'tests.plotAttrTest', 'plotAttrTest', (['self', 'ax'], {'legendLabels': '"""bad text"""'}), "(self, ax, legendLabels='bad text')\n", (15780, 15815), False, 'from tests import plotTest, plotAttrTest\n'), ((15896, 15943), 'tests.plotAttrTest', 'plotAttrTest', (['self', 'ax'], {'legendLabels': "['1', '2']"}), "(self, ax, legendLabels=['1', '2'])\n", (15908, 15943), False, 'from tests import plotTest, plotAttrTest\n'), ((16018, 16059), 'tests.plotAttrTest', 'plotAttrTest', (['self', 'ax'], {'title': '"""Bad title"""'}), "(self, ax, title='Bad title')\n", (16030, 16059), False, 'from tests import plotTest, plotAttrTest\n')]
# Filename: ahrs.py # -*- coding: utf-8 -*- # pylint: disable=locally-disabled """ AHRS calibration. """ import io from collections import defaultdict import time import xml.etree.ElementTree as ET import km3db import numpy as np from numpy import cos, sin, arctan2 import km3pipe as kp from km3pipe.tools import timed_cache from km3pipe.io.daq import TMCHData __author__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Development" log = kp.logger.get_logger(__name__) # pylint: disable=C0103 # log.setLevel("DEBUG") class AHRSCalibrator(kp.Module): """Calculates AHRS yaw, pitch and roll from median A and H of an interval. Parameters ---------- det_id: int The detector ID, e.g. 29) Other Parameters ---------------- interval: int (accumulation interval in [sec], default: 10s) Notes ----- Writes 'AHRSCalibration' in the blob with: dict: key=dom_id, value=tuple: (timestamp, du, floor, yaw, pitch, roll) """ def configure(self): det_id = self.require("det_id") self.interval = self.get("interval") or 10 # in sec self.A = defaultdict(list) self.H = defaultdict(list) self.detector = kp.hardware.Detector(det_id=det_id) self.clbmap = km3db.CLBMap(det_id) self.timestamp = time.time() def process(self, blob): tmch_data = TMCHData(io.BytesIO(blob["CHData"])) dom_id = tmch_data.dom_id try: du, floor, _ = self.detector.doms[dom_id] except KeyError: # base CLB return blob self.A[dom_id].append(tmch_data.A) self.H[dom_id].append(tmch_data.H) if time.time() - self.timestamp > self.interval: self.timestamp = time.time() calib = self.calibrate() blob["AHRSCalibration"] = calib return blob def calibrate(self): """Calculate yaw, pitch and roll from the median of A and H. After successful calibration, the `self.A` and `self.H` are reset. DOMs with missing AHRS pre-calibration data are skipped. Returns ------- dict: key=dom_id, value=tuple: (timestamp, du, floor, yaw, pitch, roll) """ now = time.time() dom_ids = self.A.keys() print("Calibrating AHRS from median A and H for {} DOMs.".format(len(dom_ids))) calibrations = {} for dom_id in dom_ids: print("Calibrating DOM ID {}".format(dom_id)) clb_upi = self.clbmap.doms_ids[dom_id].clb_upi ahrs_calib = get_latest_ahrs_calibration(clb_upi) if ahrs_calib is None: log.warning("AHRS calibration missing for '{}'".format(dom_id)) continue du, floor, _ = self.detector.doms[dom_id] A = np.median(self.A[dom_id], axis=0) H = np.median(self.H[dom_id], axis=0) cyaw, cpitch, croll = fit_ahrs(A, H, *ahrs_calib) calibrations[dom_id] = (now, du, floor, cyaw, cpitch, croll) self.A = defaultdict(list) self.H = defaultdict(list) return calibrations def fit_ahrs(A, H, Aoff, Arot, Hoff, Hrot): """Calculate yaw, pitch and roll for given A/H and calibration set. Author: <NAME> Parameters ---------- A: list, tuple or numpy.array of shape (3,) H: list, tuple or numpy.array of shape (3,) Aoff: numpy.array of shape(3,) Arot: numpy.array of shape(3, 3) Hoff: numpy.array of shape(3,) Hrot: numpy.array of shape(3, 3) Returns ------- yaw, pitch, roll """ Acal = np.dot(A - Aoff, Arot) Hcal = np.dot(H - Hoff, Hrot) # invert axis for DOM upside down for i in (1, 2): Acal[i] = -Acal[i] Hcal[i] = -Hcal[i] roll = arctan2(-Acal[1], -Acal[2]) pitch = arctan2(Acal[0], np.sqrt(Acal[1] * Acal[1] + Acal[2] * Acal[2])) yaw = arctan2( Hcal[2] * sin(roll) - Hcal[1] * cos(roll), sum( ( Hcal[0] * cos(pitch), Hcal[1] * sin(pitch) * sin(roll), Hcal[2] * sin(pitch) * cos(roll), ) ), ) yaw = np.degrees(yaw) while yaw < 0: yaw += 360 # yaw = (yaw + magnetic_declination + 360 ) % 360 roll = np.degrees(roll) pitch = np.degrees(pitch) return yaw, pitch, roll @timed_cache(hours=1, maxsize=None, typed=False) def get_latest_ahrs_calibration(clb_upi, max_version=3): """Retrieve the latest AHRS calibration data for a given CLB Parameters ---------- clb_upi: str max_version: int, maximum version to check, optional Returns ------- Aoff: numpy.array with shape(3,) Arot: numpy.array with shape(3,3) Hoff: numpy.array with shape(3,) Hrot: numpy.array with shape(3,3) or None if no calibration found. """ ahrs_upi = km3db.tools.clbupi2compassupi(clb_upi) db = km3db.DBManager() datasets = [] for version in range(max_version, 0, -1): for n in range(1, 100): log.debug("Iteration #{} to get the calib data".format(n)) url = ( "show_product_test.htm?upi={0}&" "testtype=AHRS-CALIBRATION-v{1}&n={2}&out=xml".format( ahrs_upi, version, n ) ) log.debug("AHRS calib DB URL: {}".format(url)) _raw_data = db.get(url).replace("\n", "") log.debug("What I got back as AHRS calib: {}".format(_raw_data)) if len(_raw_data) == 0: break try: xroot = ET.parse(io.StringIO(_raw_data)).getroot() except ET.ParseError: continue else: datasets.append(xroot) if len(datasets) == 0: return None latest_dataset = _get_latest_dataset(datasets) return _extract_calibration(latest_dataset) def _get_latest_dataset(datasets): """Find the latest valid AHRS calibration dataset""" return sorted(datasets, key=lambda d: d.findall(".//EndTime")[0].text)[-1] def _extract_calibration(xroot): """Extract AHRS calibration information from XML root. Parameters ---------- xroot: XML root Returns ------- Aoff: numpy.array with shape(3,) Arot: numpy.array with shape(3,3) Hoff: numpy.array with shape(3,) Hrot: numpy.array with shape(3,3) """ names = [c.text for c in xroot.findall(".//Name")] val = [[i.text for i in c] for c in xroot.findall(".//Values")] # The fields has to be reindeced, these are the index mappings col_ic = [int(v) for v in val[names.index("AHRS_Matrix_Column")]] try: row_ic = [int(v) for v in val[names.index("AHRS_Matrix_Row")]] except ValueError: row_ic = [2, 2, 2, 1, 1, 1, 0, 0, 0] try: vec_ic = [int(v) for v in val[names.index("AHRS_Vector_Index")]] except ValueError: vec_ic = [2, 1, 0] Aoff_ix = names.index("AHRS_Acceleration_Offset") Arot_ix = names.index("AHRS_Acceleration_Rotation") Hrot_ix = names.index("AHRS_Magnetic_Rotation") Aoff = np.array(val[Aoff_ix])[vec_ic].astype(float) Arot = ( np.array(val[Arot_ix]).reshape(3, 3)[col_ic, row_ic].reshape(3, 3).astype(float) ) Hrot = ( np.array(val[Hrot_ix]).reshape(3, 3)[col_ic, row_ic].reshape(3, 3).astype(float) ) Hoff = [] for q in "XYZ": values = [] for t in ("Min", "Max"): ix = names.index("AHRS_Magnetic_{}{}".format(q, t)) values.append(float(val[ix][0])) Hoff.append(sum(values) / 2.0) Hoff = np.array(Hoff) return Aoff, Arot, Hoff, Hrot
[ "km3db.CLBMap", "io.BytesIO", "numpy.arctan2", "io.StringIO", "numpy.degrees", "numpy.median", "km3pipe.logger.get_logger", "km3db.DBManager", "collections.defaultdict", "time.time", "km3pipe.tools.timed_cache", "numpy.sin", "numpy.array", "numpy.cos", "km3db.tools.clbupi2compassupi", "numpy.dot", "km3pipe.hardware.Detector", "numpy.sqrt" ]
[((444, 474), 'km3pipe.logger.get_logger', 'kp.logger.get_logger', (['__name__'], {}), '(__name__)\n', (464, 474), True, 'import km3pipe as kp\n'), ((4368, 4415), 'km3pipe.tools.timed_cache', 'timed_cache', ([], {'hours': '(1)', 'maxsize': 'None', 'typed': '(False)'}), '(hours=1, maxsize=None, typed=False)\n', (4379, 4415), False, 'from km3pipe.tools import timed_cache\n'), ((3606, 3628), 'numpy.dot', 'np.dot', (['(A - Aoff)', 'Arot'], {}), '(A - Aoff, Arot)\n', (3612, 3628), True, 'import numpy as np\n'), ((3640, 3662), 'numpy.dot', 'np.dot', (['(H - Hoff)', 'Hrot'], {}), '(H - Hoff, Hrot)\n', (3646, 3662), True, 'import numpy as np\n'), ((3789, 3816), 'numpy.arctan2', 'arctan2', (['(-Acal[1])', '(-Acal[2])'], {}), '(-Acal[1], -Acal[2])\n', (3796, 3816), False, 'from numpy import cos, sin, arctan2\n'), ((4171, 4186), 'numpy.degrees', 'np.degrees', (['yaw'], {}), '(yaw)\n', (4181, 4186), True, 'import numpy as np\n'), ((4290, 4306), 'numpy.degrees', 'np.degrees', (['roll'], {}), '(roll)\n', (4300, 4306), True, 'import numpy as np\n'), ((4319, 4336), 'numpy.degrees', 'np.degrees', (['pitch'], {}), '(pitch)\n', (4329, 4336), True, 'import numpy as np\n'), ((4880, 4918), 'km3db.tools.clbupi2compassupi', 'km3db.tools.clbupi2compassupi', (['clb_upi'], {}), '(clb_upi)\n', (4909, 4918), False, 'import km3db\n'), ((4929, 4946), 'km3db.DBManager', 'km3db.DBManager', ([], {}), '()\n', (4944, 4946), False, 'import km3db\n'), ((7651, 7665), 'numpy.array', 'np.array', (['Hoff'], {}), '(Hoff)\n', (7659, 7665), True, 'import numpy as np\n'), ((1129, 1146), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1140, 1146), False, 'from collections import defaultdict\n'), ((1164, 1181), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1175, 1181), False, 'from collections import defaultdict\n'), ((1206, 1241), 'km3pipe.hardware.Detector', 'kp.hardware.Detector', ([], {'det_id': 'det_id'}), '(det_id=det_id)\n', (1226, 1241), True, 'import km3pipe as kp\n'), ((1264, 1284), 'km3db.CLBMap', 'km3db.CLBMap', (['det_id'], {}), '(det_id)\n', (1276, 1284), False, 'import km3db\n'), ((1310, 1321), 'time.time', 'time.time', ([], {}), '()\n', (1319, 1321), False, 'import time\n'), ((2235, 2246), 'time.time', 'time.time', ([], {}), '()\n', (2244, 2246), False, 'import time\n'), ((3050, 3067), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (3061, 3067), False, 'from collections import defaultdict\n'), ((3085, 3102), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (3096, 3102), False, 'from collections import defaultdict\n'), ((3846, 3892), 'numpy.sqrt', 'np.sqrt', (['(Acal[1] * Acal[1] + Acal[2] * Acal[2])'], {}), '(Acal[1] * Acal[1] + Acal[2] * Acal[2])\n', (3853, 3892), True, 'import numpy as np\n'), ((1381, 1407), 'io.BytesIO', 'io.BytesIO', (["blob['CHData']"], {}), "(blob['CHData'])\n", (1391, 1407), False, 'import io\n'), ((1745, 1756), 'time.time', 'time.time', ([], {}), '()\n', (1754, 1756), False, 'import time\n'), ((2813, 2846), 'numpy.median', 'np.median', (['self.A[dom_id]'], {'axis': '(0)'}), '(self.A[dom_id], axis=0)\n', (2822, 2846), True, 'import numpy as np\n'), ((2863, 2896), 'numpy.median', 'np.median', (['self.H[dom_id]'], {'axis': '(0)'}), '(self.H[dom_id], axis=0)\n', (2872, 2896), True, 'import numpy as np\n'), ((1670, 1681), 'time.time', 'time.time', ([], {}), '()\n', (1679, 1681), False, 'import time\n'), ((3931, 3940), 'numpy.sin', 'sin', (['roll'], {}), '(roll)\n', (3934, 3940), False, 'from numpy import cos, sin, arctan2\n'), ((3953, 3962), 'numpy.cos', 'cos', (['roll'], {}), '(roll)\n', (3956, 3962), False, 'from numpy import cos, sin, arctan2\n'), ((7143, 7165), 'numpy.array', 'np.array', (['val[Aoff_ix]'], {}), '(val[Aoff_ix])\n', (7151, 7165), True, 'import numpy as np\n'), ((4017, 4027), 'numpy.cos', 'cos', (['pitch'], {}), '(pitch)\n', (4020, 4027), False, 'from numpy import cos, sin, arctan2\n'), ((4068, 4077), 'numpy.sin', 'sin', (['roll'], {}), '(roll)\n', (4071, 4077), False, 'from numpy import cos, sin, arctan2\n'), ((4118, 4127), 'numpy.cos', 'cos', (['roll'], {}), '(roll)\n', (4121, 4127), False, 'from numpy import cos, sin, arctan2\n'), ((4055, 4065), 'numpy.sin', 'sin', (['pitch'], {}), '(pitch)\n', (4058, 4065), False, 'from numpy import cos, sin, arctan2\n'), ((4105, 4115), 'numpy.sin', 'sin', (['pitch'], {}), '(pitch)\n', (4108, 4115), False, 'from numpy import cos, sin, arctan2\n'), ((5626, 5648), 'io.StringIO', 'io.StringIO', (['_raw_data'], {}), '(_raw_data)\n', (5637, 5648), False, 'import io\n'), ((7209, 7231), 'numpy.array', 'np.array', (['val[Arot_ix]'], {}), '(val[Arot_ix])\n', (7217, 7231), True, 'import numpy as np\n'), ((7317, 7339), 'numpy.array', 'np.array', (['val[Hrot_ix]'], {}), '(val[Hrot_ix])\n', (7325, 7339), True, 'import numpy as np\n')]
import topas2numpy as t2np import numpy as np import os ###################### os.chdir("/home/ethanb/TOPAS/Linac_Model/output/PDD") ###################### cyl1 = t2np.BinnedResult("../../mac/PDDCyl.csv") depth = np.flip(cyl1.dimensions[2].get_bin_centers()) files = {} for filename in os.listdir(): print(filename,os.stat(filename )) if filename.endswith('.csv') & os.stat(filename).st_size > 0: file_contents = t2np.BinnedResult(filename) files[filename] = file_contents print(filename) elif filename == 'pdd_combined.csv': pass sum_dose = np.zeros(len(np.squeeze(cyl1.data["Mean"]))) counts_in_bin = np.zeros(len(np.squeeze(cyl1.data["Count_in_Bin"]))) count = 0 for file in files: sum_dose += np.squeeze(files[file].data["Sum"]) counts_in_bin += np.squeeze(files[file].data["Count_in_Bin"]) count +=1 comb_array = np.asarray([depth,sum_dose,counts_in_bin]) np.savetxt('pdd_combined.csv',comb_array,delimiter=',')
[ "topas2numpy.BinnedResult", "os.stat", "numpy.asarray", "numpy.savetxt", "os.chdir", "numpy.squeeze", "os.listdir" ]
[((81, 134), 'os.chdir', 'os.chdir', (['"""/home/ethanb/TOPAS/Linac_Model/output/PDD"""'], {}), "('/home/ethanb/TOPAS/Linac_Model/output/PDD')\n", (89, 134), False, 'import os\n'), ((167, 208), 'topas2numpy.BinnedResult', 't2np.BinnedResult', (['"""../../mac/PDDCyl.csv"""'], {}), "('../../mac/PDDCyl.csv')\n", (184, 208), True, 'import topas2numpy as t2np\n'), ((292, 304), 'os.listdir', 'os.listdir', ([], {}), '()\n', (302, 304), False, 'import os\n'), ((893, 937), 'numpy.asarray', 'np.asarray', (['[depth, sum_dose, counts_in_bin]'], {}), '([depth, sum_dose, counts_in_bin])\n', (903, 937), True, 'import numpy as np\n'), ((938, 995), 'numpy.savetxt', 'np.savetxt', (['"""pdd_combined.csv"""', 'comb_array'], {'delimiter': '""","""'}), "('pdd_combined.csv', comb_array, delimiter=',')\n", (948, 995), True, 'import numpy as np\n'), ((762, 797), 'numpy.squeeze', 'np.squeeze', (["files[file].data['Sum']"], {}), "(files[file].data['Sum'])\n", (772, 797), True, 'import numpy as np\n'), ((819, 863), 'numpy.squeeze', 'np.squeeze', (["files[file].data['Count_in_Bin']"], {}), "(files[file].data['Count_in_Bin'])\n", (829, 863), True, 'import numpy as np\n'), ((325, 342), 'os.stat', 'os.stat', (['filename'], {}), '(filename)\n', (332, 342), False, 'import os\n'), ((442, 469), 'topas2numpy.BinnedResult', 't2np.BinnedResult', (['filename'], {}), '(filename)\n', (459, 469), True, 'import topas2numpy as t2np\n'), ((615, 644), 'numpy.squeeze', 'np.squeeze', (["cyl1.data['Mean']"], {}), "(cyl1.data['Mean'])\n", (625, 644), True, 'import numpy as np\n'), ((676, 713), 'numpy.squeeze', 'np.squeeze', (["cyl1.data['Count_in_Bin']"], {}), "(cyl1.data['Count_in_Bin'])\n", (686, 713), True, 'import numpy as np\n'), ((387, 404), 'os.stat', 'os.stat', (['filename'], {}), '(filename)\n', (394, 404), False, 'import os\n')]
# -*- coding: utf-8 -*- # Copyright (c) 2020 <NAME> # Licensed under the MIT License """Main module for applying zreion function.""" import warnings import numpy as np import pyfftw from . import _zreion # define constants b0 = 1.0 / 1.686 def tophat(x): """ Compute spherical tophat Fourier window function. Compute the window function of a Fourier tophat window function W_R(k), where R is the characteristic radius of the tophat in real space and k is the amplitude of the Fourier vector. As can be shown, the tophat function has the form: W_R(k) = 3 * (sin(R * k) - (R * k) * cos(R * k)) / (R * k)**3. For small values of R*k, we use the Taylor series approximation, which is: W_R(k) ~ 1 - (R * k)**2 / 10. Note that this function itself does not handle a potential RuntimeWarning arising from arguments that cause division by zero. However, np.where statement handles this cases appropriately, so it can be generally be ignored by the user for typical arguments. Parameters ---------- x : ndarray An array containing the arguments R*k. Returns ------- ndarray An array of the same size containing the tophat applied to each element. """ return np.where( np.abs(x) > 1e-6, 3 * (np.sin(x) - x * np.cos(x)) / x ** 3, 1 - x ** 2 / 10.0 ) def sinc(x): """ Compute sinc(x) = sin(x) / x function. Compute the sinc function sin(x) / x, which is necessary for deconvolving the cloud-in-cell (CIC) window function typically used to deposit particles onto a grid. For small values of x, we use the Taylor series appriximation, which is: sinc(x) ~ 1 - x**2 / 6. Note that this function itself does not handle a potential RuntimeWarning arising from arguments that cause division by zero. However, np.where statement handles this cases appropriately, so it can be generally be ignored by the user for typical arguments. Parameters ---------- x : ndarray An array containing the arguments x. Returns ------- ndarray An array of the same size containing sinc applied to each element. """ return np.where(np.abs(x) > 1e-6, np.sin(x) / x, 1 - x ** 2 / 6.0) def _fft3d(array, data_shape, direction="f"): """ Apply an FFT using pyFFTW. Parameters ---------- array : ndarray The array to apply the transform to. data_shape : 3-ple of int The shape of the input data array. Used for determining the size of the output array for a forward transform and the target shape for a backward one. direction : str The direction of the transform. Must be either "f" (for forward) or "b" (for backward). Returns ------- ndarray An ndarray of the resulting transform. """ if direction.lower() not in ["f", "b"]: raise ValueError(f'"direction" must be "f" or "b", got "{direction}"') dtype = array.dtype.type if direction.lower() == "f": if dtype is np.float32: precision = "single" elif dtype is np.float64: precision = "double" else: raise ValueError( "a forward transform requires input have np.float32 or np.float64 " "datatype" ) else: # "b" if dtype is np.complex64: precision = "single" elif dtype is np.complex128: precision = "double" else: raise ValueError( "a backward transform requires input to have np.complex64 or " "np.complex128 datatype" ) if precision == "single": input_dtype = "float32" output_dtype = "complex64" else: # "double" input_dtype = "float64" output_dtype = "complex128" # define size of FFTW arrays if len(array.shape) != 3: raise ValueError("input array must be a 3-dimensional array") if len(data_shape) != 3: raise ValueError("data_shape must have 3 dimensions") padded_shape = (data_shape[0], data_shape[1], 2 * (data_shape[2] // 2 + 1)) full_array = pyfftw.empty_aligned( padded_shape, input_dtype, n=pyfftw.simd_alignment ) # make input and output arrays real_input = full_array[:, :, : data_shape[2]] complex_output = full_array.view(output_dtype) if direction == "f": fftw_obj = pyfftw.FFTW(real_input, complex_output, axes=(0, 1, 2)) real_input[:] = array else: fftw_obj = pyfftw.FFTW( complex_output, real_input, axes=(0, 1, 2), direction="FFTW_BACKWARD" ) complex_output[:] = array # perform computation and return return fftw_obj() def apply_zreion(density, zmean, alpha, k0, boxsize, rsmooth=1.0, deconvolve=True): """ Apply zreion ionization history to density field. Parameters ---------- density : numpy array A numpy array of rank 3 holding the density field. Note this should be the overdensity field delta = (rho - <rho>)/<rho>, where <rho> is the average density value. This quantity has a mean of 0 and a minimum value of -1. zmean : float The mean redshift of reionization. alpha : float The alpha value of the bias parameter. k0 : float The k0 value of the bais parameter, in units of h/Mpc. boxsize : float or array of floats The physical extent of the box along each dimension. If a single value, this is assumed to be the same for each axis. rsmooth: float, optional The smoothing length of the reionziation field, in Mpc/h. Defaults to 1 Mpc/h. deconvolve : bool, optional Whether to deconvolve the CIC particle deposition window. If density grid is derived in Eulerian space directly, this step is not needed. Returns ------- zreion : numpy array A numpy array of rank 3 containing the redshift corresponding to when that portion of the volume was reionized. """ # check that parameters make sense if len(density.shape) != 3: raise ValueError("density must be a 3d array") if isinstance(boxsize, (int, float, np.float_)): boxsize = np.asarray([np.float64(boxsize)]) else: # assume it's an array of length 1 or 3 if len(boxsize) not in (1, 3): raise ValueError( "boxsize must be either a single number or an array of length 3" ) # compute FFT of density field density_fft = np.fft.rfftn(density) # compute spherical k-indices for cells nx, ny, nz = density.shape if len(boxsize) == 1: lx = ly = lz = boxsize[0] else: lx, ly, lz = boxsize dx = lx / (2 * np.pi * nx) dy = ly / (2 * np.pi * ny) dz = lz / (2 * np.pi * nz) kx = np.fft.fftfreq(nx, d=dx) ky = np.fft.fftfreq(ny, d=dy) kz = np.fft.rfftfreq(nz, d=dz) # note we're using rfftfreq! # compute bias factor kkx, kky, kkz = np.meshgrid(kx, ky, kz, indexing="ij") spherical_k = np.sqrt(kkx ** 2 + kky ** 2 + kkz ** 2) bias_val = b0 / (1 + spherical_k / k0) ** alpha # compute smoothing factor # turn off numpy errors that come from near-zero values with warnings.catch_warnings(): warnings.simplefilter("ignore") smoothing_window = tophat(spherical_k * rsmooth) if deconvolve: # compute deconvolution window in grid units kkx *= lx / nx kky *= ly / ny kkz *= lz / nz # turn off numpy errors that come from near-zero values with warnings.catch_warnings(): warnings.simplefilter("ignore") deconv_window = (sinc(kkx / 2) * sinc(kky / 2) * sinc(kkz / 2)) ** 2 else: deconv_window = np.ones_like(density_fft, dtype=np.float64) assert ( bias_val.shape == density_fft.shape ), "Bias and density grids are not compatible" assert ( smoothing_window.shape == density_fft.shape ), "Smoothing window and density grids are not compatible" assert ( deconv_window.shape == density_fft.shape ), "Deconvolution window and density grids are not compatible" # apply transformations to Fourier field density_fft *= bias_val density_fft *= smoothing_window density_fft /= deconv_window # inverse FFT zreion = np.fft.irfftn(density_fft, density.shape) # finish computing zreion field zreion *= 1 + zmean zreion += zmean return zreion def apply_zreion_fast(density, zmean, alpha, k0, boxsize, rsmooth=1.0, deconvolve=True): """ Use as a fast, drop-in replacement for apply_zreion. The speedups are accomplished by using pyfftw for FFT computation, and parallelized cython code for most of the rest of the calculation. As an added benefit, this version requires significantly less memory. Parameters ---------- density : numpy array A numpy array of rank 3 holding the density field. Note this should be the overdensity field delta = (rho - <rho>)/<rho>, where <rho> is the average density value. This quantity has a mean of 0 and a minimum value of -1. zmean : float The mean redshift of reionization. alpha : float The alpha value of the bias parameter. k0 : float The k0 value of the bais parameter, in units of h/Mpc. boxsize : float or array of floats The physical extent of the box along each dimension. If a single value, this is assumed to be the same for each axis. rsmooth: float, optional The smoothing length of the reionziation field, in Mpc/h. Defaults to 1 Mpc/h. deconvolve : bool, optional Whether to deconvolve the CIC particle deposition window. If density grid is derived in Eulerian space directly, this step is not needed. Returns ------- zreion : numpy array A numpy array of rank 3 containing the redshift corresponding to when that portion of the volume was reionized. """ # check that parameters make sense if len(density.shape) != 3: raise ValueError("density must be a 3d array") if isinstance(boxsize, (int, float, np.float_)): boxsize = np.asarray([np.float64(boxsize)]) else: # assume it's an array of length 1 or 3 if len(boxsize) not in (1, 3): raise ValueError( "boxsize must be either a single number or an array of length 3" ) # save input type input_type = density.dtype # unpack boxsize argument if len(boxsize) == 1: lx = ly = lz = boxsize[0] else: lx, ly, lz = boxsize # save input array shape array_shape = density.shape # perform fft density_fft = _fft3d(density, array_shape, direction="f") # cast to required type density_fft = density_fft.astype(np.complex64) # call cython funtion for applying bias relation # need to tell function if last dimension has an odd number of elements odd_nz = density.shape[2] % 2 == 1 density_fft = np.asarray( _zreion._apply_zreion( density_fft, alpha, k0, lx, ly, lz, rsmooth, deconvolve, odd_nz ) ) # perform inverse fft density = _fft3d(density_fft, array_shape, direction="b") # finish computing zreion field density *= 1 + zmean density += zmean return density.astype(input_type)
[ "numpy.meshgrid", "numpy.ones_like", "warnings.simplefilter", "numpy.abs", "numpy.fft.irfftn", "numpy.fft.rfftn", "pyfftw.empty_aligned", "numpy.fft.rfftfreq", "numpy.fft.fftfreq", "numpy.sin", "warnings.catch_warnings", "pyfftw.FFTW", "numpy.cos", "numpy.float64", "numpy.sqrt" ]
[((4212, 4284), 'pyfftw.empty_aligned', 'pyfftw.empty_aligned', (['padded_shape', 'input_dtype'], {'n': 'pyfftw.simd_alignment'}), '(padded_shape, input_dtype, n=pyfftw.simd_alignment)\n', (4232, 4284), False, 'import pyfftw\n'), ((6634, 6655), 'numpy.fft.rfftn', 'np.fft.rfftn', (['density'], {}), '(density)\n', (6646, 6655), True, 'import numpy as np\n'), ((6933, 6957), 'numpy.fft.fftfreq', 'np.fft.fftfreq', (['nx'], {'d': 'dx'}), '(nx, d=dx)\n', (6947, 6957), True, 'import numpy as np\n'), ((6967, 6991), 'numpy.fft.fftfreq', 'np.fft.fftfreq', (['ny'], {'d': 'dy'}), '(ny, d=dy)\n', (6981, 6991), True, 'import numpy as np\n'), ((7001, 7026), 'numpy.fft.rfftfreq', 'np.fft.rfftfreq', (['nz'], {'d': 'dz'}), '(nz, d=dz)\n', (7016, 7026), True, 'import numpy as np\n'), ((7104, 7142), 'numpy.meshgrid', 'np.meshgrid', (['kx', 'ky', 'kz'], {'indexing': '"""ij"""'}), "(kx, ky, kz, indexing='ij')\n", (7115, 7142), True, 'import numpy as np\n'), ((7161, 7200), 'numpy.sqrt', 'np.sqrt', (['(kkx ** 2 + kky ** 2 + kkz ** 2)'], {}), '(kkx ** 2 + kky ** 2 + kkz ** 2)\n', (7168, 7200), True, 'import numpy as np\n'), ((8468, 8509), 'numpy.fft.irfftn', 'np.fft.irfftn', (['density_fft', 'density.shape'], {}), '(density_fft, density.shape)\n', (8481, 8509), True, 'import numpy as np\n'), ((4482, 4537), 'pyfftw.FFTW', 'pyfftw.FFTW', (['real_input', 'complex_output'], {'axes': '(0, 1, 2)'}), '(real_input, complex_output, axes=(0, 1, 2))\n', (4493, 4537), False, 'import pyfftw\n'), ((4597, 4684), 'pyfftw.FFTW', 'pyfftw.FFTW', (['complex_output', 'real_input'], {'axes': '(0, 1, 2)', 'direction': '"""FFTW_BACKWARD"""'}), "(complex_output, real_input, axes=(0, 1, 2), direction=\n 'FFTW_BACKWARD')\n", (4608, 4684), False, 'import pyfftw\n'), ((7354, 7379), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (7377, 7379), False, 'import warnings\n'), ((7389, 7420), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (7410, 7420), False, 'import warnings\n'), ((7883, 7926), 'numpy.ones_like', 'np.ones_like', (['density_fft'], {'dtype': 'np.float64'}), '(density_fft, dtype=np.float64)\n', (7895, 7926), True, 'import numpy as np\n'), ((1288, 1297), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (1294, 1297), True, 'import numpy as np\n'), ((2230, 2239), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (2236, 2239), True, 'import numpy as np\n'), ((2248, 2257), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (2254, 2257), True, 'import numpy as np\n'), ((7697, 7722), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (7720, 7722), False, 'import warnings\n'), ((7736, 7767), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (7757, 7767), False, 'import warnings\n'), ((6336, 6355), 'numpy.float64', 'np.float64', (['boxsize'], {}), '(boxsize)\n', (6346, 6355), True, 'import numpy as np\n'), ((10378, 10397), 'numpy.float64', 'np.float64', (['boxsize'], {}), '(boxsize)\n', (10388, 10397), True, 'import numpy as np\n'), ((1311, 1320), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (1317, 1320), True, 'import numpy as np\n'), ((1327, 1336), 'numpy.cos', 'np.cos', (['x'], {}), '(x)\n', (1333, 1336), True, 'import numpy as np\n')]
import tensorflow as tf import tensorflow_probability as tfp import numpy as np import src.utils as utils def gaussian_d(x, y): """ A conceptual lack of understanding here. Do I need a dx to calculate this over? Doesnt make sense for a single point!? """ d = tf.norm(x - y, axis=1) return tf.exp(-0.5*d)/(tf.sqrt(2*tf.constant(np.pi))) class SparseAE(): def __init__(self, n_hidden, width, depth, stddev=0.0001): """ Args: """ self.n_hidden = n_hidden self.width = width self.depth = depth self.n_channels = 1 self.stddev = stddev self.e = 1e-1 self.prior = tfp.distributions.RelaxedBernoulli(1e-1, logits=tf.get_variable(name='prior_params'), shape=[16, 1, 1, n_hidden]) self.construct() def construct(self): """ Constructs: encoder (tf.keras.Model): encode the gradient into the hidden space decoder (tf.keras.Model): decodes a hidden state into an image """ layers = [] layers.append(tf.keras.layers.Conv2D(self.width, 4, strides=(2, 2), padding='same', # input_shape=(28,28,1) )) layers.append(tf.keras.layers.Activation(tf.keras.activations.selu)) for i in range(self.depth): layers.append(tf.keras.layers.Conv2D(self.width, 4, strides=(2, 2), padding='same'),) layers.append(tf.keras.layers.Activation(tf.keras.activations.selu)) layers.append(tf.keras.layers.Conv2D(self.n_hidden, 1, strides=(1, 1), padding='same')) self.encoder = tf.keras.Sequential(layers) # decoder layers = [] layers.append(tf.keras.layers.Conv2DTranspose(self.width, 4, strides=(2, 2), padding='same', # input_shape=(1,1,self.n_hidden) )) layers.append(tf.keras.layers.Activation(tf.keras.activations.selu)) for _ in range(self.depth): layers.append(tf.keras.layers.Conv2DTranspose(self.width, 4, strides=(2, 2), padding='same')) layers.append(tf.keras.layers.Activation(tf.keras.activations.selu)) layers.append(tf.keras.layers.Conv2DTranspose(self.n_channels, 1, strides=(1, 1), padding='same')) self.decoder = tf.keras.Sequential(layers) def __call__(self, x): """ Args: x (tf.tensor): the input shape is [None, width, height, channels], dtype is tf.float32 """ with tf.name_scope('sparseae'): self.h = self.encoder(x) self.z = tf.nn.relu(self.h + self.e) - tf.nn.relu(-self.h-self.e) self.y = self.decoder(self.z) return self.y def make_losses(self, x, y=None): self.x = x if y is None: print('...') y = self.__call__(self.x) with tf.name_scope('loss'): recon_loss = tf.losses.mean_squared_error(x, y) latent_loss = tf.reduce_mean(tf.reduce_sum(tf.abs(self.z), axis=[1])) # or could use a distribution over discrete vals and entropy!? return recon_loss, latent_loss def estimate_density(self, x): x_ = self.__call__(x) return gaussian_d(self.z, tf.zeros_like(self.z)) @staticmethod def preprocess(x): im = np.reshape(x, [-1, 28, 28, 1]) im = np.round(im).astype(np.float32) # NOTE important !? return np.pad(im, [(0,0), (2,2), (2,2), (0,0)], 'constant', constant_values=0) if __name__ == '__main__': tf.enable_eager_execution() x = tf.random_normal((100, 32, 32, 1)) nn = SparseAE(12, 16, 4) x_ = nn(x) loss = nn.make_losses(x) assert x_.shape == x.shape
[ "numpy.pad", "tensorflow.nn.relu", "tensorflow.keras.layers.Conv2D", "tensorflow.abs", "tensorflow.losses.mean_squared_error", "tensorflow.enable_eager_execution", "tensorflow.zeros_like", "tensorflow.constant", "tensorflow.keras.layers.Activation", "tensorflow.exp", "tensorflow.random_normal", "numpy.reshape", "tensorflow.keras.Sequential", "tensorflow.keras.layers.Conv2DTranspose", "numpy.round", "tensorflow.name_scope", "tensorflow.norm", "tensorflow.get_variable" ]
[((284, 306), 'tensorflow.norm', 'tf.norm', (['(x - y)'], {'axis': '(1)'}), '(x - y, axis=1)\n', (291, 306), True, 'import tensorflow as tf\n'), ((4033, 4060), 'tensorflow.enable_eager_execution', 'tf.enable_eager_execution', ([], {}), '()\n', (4058, 4060), True, 'import tensorflow as tf\n'), ((4069, 4103), 'tensorflow.random_normal', 'tf.random_normal', (['(100, 32, 32, 1)'], {}), '((100, 32, 32, 1))\n', (4085, 4103), True, 'import tensorflow as tf\n'), ((318, 334), 'tensorflow.exp', 'tf.exp', (['(-0.5 * d)'], {}), '(-0.5 * d)\n', (324, 334), True, 'import tensorflow as tf\n'), ((1987, 2014), 'tensorflow.keras.Sequential', 'tf.keras.Sequential', (['layers'], {}), '(layers)\n', (2006, 2014), True, 'import tensorflow as tf\n'), ((2754, 2781), 'tensorflow.keras.Sequential', 'tf.keras.Sequential', (['layers'], {}), '(layers)\n', (2773, 2781), True, 'import tensorflow as tf\n'), ((3817, 3847), 'numpy.reshape', 'np.reshape', (['x', '[-1, 28, 28, 1]'], {}), '(x, [-1, 28, 28, 1])\n', (3827, 3847), True, 'import numpy as np\n'), ((3929, 4004), 'numpy.pad', 'np.pad', (['im', '[(0, 0), (2, 2), (2, 2), (0, 0)]', '"""constant"""'], {'constant_values': '(0)'}), "(im, [(0, 0), (2, 2), (2, 2), (0, 0)], 'constant', constant_values=0)\n", (3935, 4004), True, 'import numpy as np\n'), ((1131, 1200), 'tensorflow.keras.layers.Conv2D', 'tf.keras.layers.Conv2D', (['self.width', '(4)'], {'strides': '(2, 2)', 'padding': '"""same"""'}), "(self.width, 4, strides=(2, 2), padding='same')\n", (1153, 1200), True, 'import tensorflow as tf\n'), ((1355, 1408), 'tensorflow.keras.layers.Activation', 'tf.keras.layers.Activation', (['tf.keras.activations.selu'], {}), '(tf.keras.activations.selu)\n', (1381, 1408), True, 'import tensorflow as tf\n'), ((1794, 1866), 'tensorflow.keras.layers.Conv2D', 'tf.keras.layers.Conv2D', (['self.n_hidden', '(1)'], {'strides': '(1, 1)', 'padding': '"""same"""'}), "(self.n_hidden, 1, strides=(1, 1), padding='same')\n", (1816, 1866), True, 'import tensorflow as tf\n'), ((2076, 2154), 'tensorflow.keras.layers.Conv2DTranspose', 'tf.keras.layers.Conv2DTranspose', (['self.width', '(4)'], {'strides': '(2, 2)', 'padding': '"""same"""'}), "(self.width, 4, strides=(2, 2), padding='same')\n", (2107, 2154), True, 'import tensorflow as tf\n'), ((2346, 2399), 'tensorflow.keras.layers.Activation', 'tf.keras.layers.Activation', (['tf.keras.activations.selu'], {}), '(tf.keras.activations.selu)\n', (2372, 2399), True, 'import tensorflow as tf\n'), ((2646, 2734), 'tensorflow.keras.layers.Conv2DTranspose', 'tf.keras.layers.Conv2DTranspose', (['self.n_channels', '(1)'], {'strides': '(1, 1)', 'padding': '"""same"""'}), "(self.n_channels, 1, strides=(1, 1), padding\n ='same')\n", (2677, 2734), True, 'import tensorflow as tf\n'), ((2992, 3017), 'tensorflow.name_scope', 'tf.name_scope', (['"""sparseae"""'], {}), "('sparseae')\n", (3005, 3017), True, 'import tensorflow as tf\n'), ((3359, 3380), 'tensorflow.name_scope', 'tf.name_scope', (['"""loss"""'], {}), "('loss')\n", (3372, 3380), True, 'import tensorflow as tf\n'), ((3407, 3441), 'tensorflow.losses.mean_squared_error', 'tf.losses.mean_squared_error', (['x', 'y'], {}), '(x, y)\n', (3435, 3441), True, 'import tensorflow as tf\n'), ((3738, 3759), 'tensorflow.zeros_like', 'tf.zeros_like', (['self.z'], {}), '(self.z)\n', (3751, 3759), True, 'import tensorflow as tf\n'), ((344, 362), 'tensorflow.constant', 'tf.constant', (['np.pi'], {}), '(np.pi)\n', (355, 362), True, 'import tensorflow as tf\n'), ((747, 783), 'tensorflow.get_variable', 'tf.get_variable', ([], {'name': '"""prior_params"""'}), "(name='prior_params')\n", (762, 783), True, 'import tensorflow as tf\n'), ((1472, 1541), 'tensorflow.keras.layers.Conv2D', 'tf.keras.layers.Conv2D', (['self.width', '(4)'], {'strides': '(2, 2)', 'padding': '"""same"""'}), "(self.width, 4, strides=(2, 2), padding='same')\n", (1494, 1541), True, 'import tensorflow as tf\n'), ((1717, 1770), 'tensorflow.keras.layers.Activation', 'tf.keras.layers.Activation', (['tf.keras.activations.selu'], {}), '(tf.keras.activations.selu)\n', (1743, 1770), True, 'import tensorflow as tf\n'), ((2463, 2541), 'tensorflow.keras.layers.Conv2DTranspose', 'tf.keras.layers.Conv2DTranspose', (['self.width', '(4)'], {'strides': '(2, 2)', 'padding': '"""same"""'}), "(self.width, 4, strides=(2, 2), padding='same')\n", (2494, 2541), True, 'import tensorflow as tf\n'), ((2569, 2622), 'tensorflow.keras.layers.Activation', 'tf.keras.layers.Activation', (['tf.keras.activations.selu'], {}), '(tf.keras.activations.selu)\n', (2595, 2622), True, 'import tensorflow as tf\n'), ((3077, 3104), 'tensorflow.nn.relu', 'tf.nn.relu', (['(self.h + self.e)'], {}), '(self.h + self.e)\n', (3087, 3104), True, 'import tensorflow as tf\n'), ((3107, 3135), 'tensorflow.nn.relu', 'tf.nn.relu', (['(-self.h - self.e)'], {}), '(-self.h - self.e)\n', (3117, 3135), True, 'import tensorflow as tf\n'), ((3861, 3873), 'numpy.round', 'np.round', (['im'], {}), '(im)\n', (3869, 3873), True, 'import numpy as np\n'), ((3497, 3511), 'tensorflow.abs', 'tf.abs', (['self.z'], {}), '(self.z)\n', (3503, 3511), True, 'import tensorflow as tf\n')]
# =============================================================================== # Copyright 2014 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # =============================================================================== # ============= enthought library imports ======================= from __future__ import absolute_import import os from numpy import array from traits.api import HasTraits, Instance # ============= standard library imports ======================== # ============= local library imports ========================== from pychron.core.helpers.filetools import fileiter from pychron.graph.graph import Graph from pychron.graph.time_series_graph import TimeSeriesStackedGraph from pychron.paths import paths class ScanInspector(HasTraits): graph = Instance(Graph) def activated(self): p = os.path.join(paths.spectrometer_scans_dir, 'scan-005.txt') g = self.graph with open(p, 'r') as rfile: fi = fileiter(rfile, strip=True) fi.next().split(',') plot = g.new_plot(padding=[60, 5, 5, 50]) g.set_y_title('Intensity (fA)') data = [line.split(',') for line in fi] data = array(data, dtype=float).T xs = data[0] for ys in data[1:]: g.new_series(x=xs, y=ys) plot.value_scale = 'log' def _graph_default(self): g = TimeSeriesStackedGraph() # g.new_plot() return g # ============= EOF =============================================
[ "pychron.graph.time_series_graph.TimeSeriesStackedGraph", "traits.api.Instance", "numpy.array", "os.path.join", "pychron.core.helpers.filetools.fileiter" ]
[((1282, 1297), 'traits.api.Instance', 'Instance', (['Graph'], {}), '(Graph)\n', (1290, 1297), False, 'from traits.api import HasTraits, Instance\n'), ((1336, 1394), 'os.path.join', 'os.path.join', (['paths.spectrometer_scans_dir', '"""scan-005.txt"""'], {}), "(paths.spectrometer_scans_dir, 'scan-005.txt')\n", (1348, 1394), False, 'import os\n'), ((1910, 1934), 'pychron.graph.time_series_graph.TimeSeriesStackedGraph', 'TimeSeriesStackedGraph', ([], {}), '()\n', (1932, 1934), False, 'from pychron.graph.time_series_graph import TimeSeriesStackedGraph\n'), ((1471, 1498), 'pychron.core.helpers.filetools.fileiter', 'fileiter', (['rfile'], {'strip': '(True)'}), '(rfile, strip=True)\n', (1479, 1498), False, 'from pychron.core.helpers.filetools import fileiter\n'), ((1704, 1728), 'numpy.array', 'array', (['data'], {'dtype': 'float'}), '(data, dtype=float)\n', (1709, 1728), False, 'from numpy import array\n')]
import os import torch import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from torch.utils.tensorboard import SummaryWriter import matplotlib.pyplot as plt import pandas as pd import numpy as np import seaborn as sns import sklearn from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") #device = "cpu" #print("USING DEVICE: ", device) DIRNAME = os.path.abspath(__file__ + "/../vis_data/") BATCH_SIZE = 5 EPOCHS = 10000 LEARNING_RATE = 0.0001 MOMENTUM = 0.9 NLAYERS = 3 LAYERDIMS = [3, 100, 50, 1] class VisDataset(Dataset): """ Pytorch dataset for the visibility uncertainty values X: relative position of obstacles y: the visibility error """ def __init__(self, X_data, y_data): self.X_data = X_data self.y_data = y_data def __getitem__(self, idx): return self.X_data[idx], self.y_data[idx] def __len__(self): return len(self.X_data) class VisNet(torch.nn.Module): """ Neural net for regression on visibility uncertainty based on vehicle relative position (x, y, z) """ def __init__(self): super(VisNet, self).__init__() self.linears = torch.nn.ModuleList([]) for i in range(NLAYERS): layer = torch.nn.Linear(LAYERDIMS[i], LAYERDIMS[i + 1]) self.linears.append(layer) self.relu = torch.nn.LeakyReLU() # linear(3, 30), relu, linear(30, 15), relu, linear(15, 1) def forward(self, x): for i in range(NLAYERS - 1): x = self.relu(self.linears[i](x)) x = self.linears[NLAYERS - 1](x) # no relu on last layer # add last layer (sigmoid): x -> 0 - 1 #x = torch.sigmoid(x) return x def normalize_data(X_train, X_test, y_train, y_test): xscaler = MinMaxScaler(feature_range=(-1, 1)) X_train = xscaler.fit_transform(X_train) X_test = xscaler.transform(X_test) return X_train, X_test, y_train, y_test def split_data(X, y, test_fraction): X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_fraction) #X_train, X_test, y_train, y_test = normalize_data(X_train, X_test, y_train, y_test) X_train, y_train = np.array(X_train), np.array(y_train) X_test, y_test = np.array(X_test), np.array(y_test) X_train, X_test, y_train, y_test = X_train.astype(float), X_test.astype(float), \ y_train.astype(float), y_test.astype(float) return X_train, X_test, y_train, y_test def process_df(df): THRESHOLD = 1000 def squash_01(row): """ Squeezes a row's vis error value into 0.001 (close to zero) or 1 (far away) """ if (row['ERROR'] > THRESHOLD): return 1 else: return 0 #df['ERROR'] = df.apply(squash_01, axis=1) df = df[df.ERROR < 1000.0] # temporary? ignores all rows with high errors to avoid df = df[df.CAMERA == 'FRONT-eval'] df.reset_index(drop=True) # df = df[df.CAMERA == 'BACK-eval'] return df def prepare_data(filename): """ Reads the visibility data (in csv format) from the filename inside vis_data folder Returns a pandas dataframe split into train (70) and test (30) normalize inputs/outputs? or no? """ filepath = os.path.join(DIRNAME, filename) df = pd.read_csv(filepath) df = process_df(df) X = df.iloc[:1000, -4:-1] y = df.iloc[:1000, -1] print(X) return split_data(X, y, 0.3) def get_datasets(X_train, X_test, y_train, y_test): train_dataset = VisDataset(torch.from_numpy(X_train).float(), torch.from_numpy(y_train).float()) test_dataset = VisDataset(torch.from_numpy(X_test).float(), torch.from_numpy(y_test).float()) return train_dataset, test_dataset def get_dataloader(dataset, batch_size): loader = DataLoader(dataset=dataset, batch_size=batch_size, num_workers=2) return loader def run_nn(writer, trainloader, testloader): # define neural net architecture net = VisNet().to(device) print(net) criterion = torch.nn.MSELoss() # (y - yhat)^2 #criterion = torch.nn.BCELoss() # binary loss optimizer = torch.optim.Adam(net.parameters(), lr=LEARNING_RATE) print("============== BEGIN TRAINING =================") # train the neural net for epoch in range(EPOCHS): trainloss = 0 valloss = 0 # training for step, data in enumerate(trainloader): # find X, y X_batch, y_batch = data y_batch = torch.clamp(y_batch, 0, 100) X_batch = X_batch.to(device) y_batch = y_batch.to(device) optimizer.zero_grad() # zero the optim gradients prediction = net(X_batch) y_batch = y_batch.view(-1, 1) loss = criterion(prediction, y_batch) loss.backward() # backprop optimizer.step() # apply gradients trainloss += loss avg_trainloss = trainloss / len(trainloader) writer.add_scalar("Loss/train", avg_trainloss, epoch) ################################################################## # compute validation loss for step, data in enumerate(testloader): # find X, y X_batch, y_batch = data y_batch = torch.clamp(y_batch, 0, 100) X_batch = X_batch.to(device) y_batch = y_batch.to(device) prediction = net(X_batch) y_batch = y_batch.view(-1, 1) loss = criterion(prediction, y_batch) valloss += loss avg_valloss = valloss / len(testloader) writer.add_scalar("Loss/validation", avg_valloss, epoch) print("EPOCH: {:2d}, TRAIN LOSS: {:.4f}, VAL LOSS: {:.4f}".format(epoch, avg_trainloss, avg_valloss)) def train(filename, log_msg=None): X_train, X_test, y_train, y_test = prepare_data(filename) print("X TRAINING") print(X_train) print("Y TRAINING") print(y_train) train_dataset, test_dataset = get_datasets(X_train, X_test, y_train, y_test) train_loader = get_dataloader(train_dataset, BATCH_SIZE) test_loader = get_dataloader(test_dataset, BATCH_SIZE) if (log_msg is not None): logdir = "runs/" + log_msg writer = SummaryWriter(log_dir=logdir) else: writer = SummaryWriter() run_nn(writer, train_loader, test_loader) writer.flush() writer.close() def debug(continuous=True, log_msg=None): """ continuous: boolean (true if continuous fake data, false if discrete fake data) """ if (continuous): filename = "fakecont.csv" else: filename = "fakedis.csv" train(filename, log_msg) if __name__ == "__main__": train("vis00.csv", "moreneurons2") #debug(True) # continuous #debug(False, "FAKEBCE2") # discrete pass
[ "os.path.abspath", "torch.nn.MSELoss", "torch.utils.data.DataLoader", "torch.nn.ModuleList", "pandas.read_csv", "sklearn.model_selection.train_test_split", "sklearn.preprocessing.MinMaxScaler", "torch.clamp", "torch.cuda.is_available", "numpy.array", "torch.utils.tensorboard.SummaryWriter", "torch.nn.Linear", "torch.nn.LeakyReLU", "os.path.join", "torch.from_numpy" ]
[((497, 540), 'os.path.abspath', 'os.path.abspath', (["(__file__ + '/../vis_data/')"], {}), "(__file__ + '/../vis_data/')\n", (512, 540), False, 'import os\n'), ((1918, 1953), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {'feature_range': '(-1, 1)'}), '(feature_range=(-1, 1))\n', (1930, 1953), False, 'from sklearn.preprocessing import MinMaxScaler\n'), ((2160, 2207), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': 'test_fraction'}), '(X, y, test_size=test_fraction)\n', (2176, 2207), False, 'from sklearn.model_selection import train_test_split\n'), ((3418, 3449), 'os.path.join', 'os.path.join', (['DIRNAME', 'filename'], {}), '(DIRNAME, filename)\n', (3430, 3449), False, 'import os\n'), ((3459, 3480), 'pandas.read_csv', 'pd.read_csv', (['filepath'], {}), '(filepath)\n', (3470, 3480), True, 'import pandas as pd\n'), ((4021, 4086), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'dataset', 'batch_size': 'batch_size', 'num_workers': '(2)'}), '(dataset=dataset, batch_size=batch_size, num_workers=2)\n', (4031, 4086), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((4298, 4316), 'torch.nn.MSELoss', 'torch.nn.MSELoss', ([], {}), '()\n', (4314, 4316), False, 'import torch\n'), ((399, 424), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (422, 424), False, 'import torch\n'), ((1304, 1327), 'torch.nn.ModuleList', 'torch.nn.ModuleList', (['[]'], {}), '([])\n', (1323, 1327), False, 'import torch\n'), ((1490, 1510), 'torch.nn.LeakyReLU', 'torch.nn.LeakyReLU', ([], {}), '()\n', (1508, 1510), False, 'import torch\n'), ((2322, 2339), 'numpy.array', 'np.array', (['X_train'], {}), '(X_train)\n', (2330, 2339), True, 'import numpy as np\n'), ((2341, 2358), 'numpy.array', 'np.array', (['y_train'], {}), '(y_train)\n', (2349, 2358), True, 'import numpy as np\n'), ((2380, 2396), 'numpy.array', 'np.array', (['X_test'], {}), '(X_test)\n', (2388, 2396), True, 'import numpy as np\n'), ((2398, 2414), 'numpy.array', 'np.array', (['y_test'], {}), '(y_test)\n', (2406, 2414), True, 'import numpy as np\n'), ((6531, 6560), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', ([], {'log_dir': 'logdir'}), '(log_dir=logdir)\n', (6544, 6560), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((6588, 6603), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', ([], {}), '()\n', (6601, 6603), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((1382, 1429), 'torch.nn.Linear', 'torch.nn.Linear', (['LAYERDIMS[i]', 'LAYERDIMS[i + 1]'], {}), '(LAYERDIMS[i], LAYERDIMS[i + 1])\n', (1397, 1429), False, 'import torch\n'), ((4766, 4794), 'torch.clamp', 'torch.clamp', (['y_batch', '(0)', '(100)'], {}), '(y_batch, 0, 100)\n', (4777, 4794), False, 'import torch\n'), ((5564, 5592), 'torch.clamp', 'torch.clamp', (['y_batch', '(0)', '(100)'], {}), '(y_batch, 0, 100)\n', (5575, 5592), False, 'import torch\n'), ((3694, 3719), 'torch.from_numpy', 'torch.from_numpy', (['X_train'], {}), '(X_train)\n', (3710, 3719), False, 'import torch\n'), ((3761, 3786), 'torch.from_numpy', 'torch.from_numpy', (['y_train'], {}), '(y_train)\n', (3777, 3786), False, 'import torch\n'), ((3826, 3850), 'torch.from_numpy', 'torch.from_numpy', (['X_test'], {}), '(X_test)\n', (3842, 3850), False, 'import torch\n'), ((3892, 3916), 'torch.from_numpy', 'torch.from_numpy', (['y_test'], {}), '(y_test)\n', (3908, 3916), False, 'import torch\n')]
import sys import random import numpy as np from numpy.random import randn sys.path.append('../DescriptiveStatisticsFunction') sys.path.append('../HelperFunctions') from HelperFunctions.HelperFunctions import lib_mean from HelperFunctions.HelperFunctions import lib_median from HelperFunctions.HelperFunctions import lib_mode from HelperFunctions.HelperFunctions import lib_variance from HelperFunctions.HelperFunctions import lib_standard_deviation from HelperFunctions.HelperFunctions import lib_skewness from HelperFunctions.HelperFunctions import lib_sample_correlation from HelperFunctions.HelperFunctions import lib_zscore from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_mean from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_median from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_mode from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_variance1 from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_variance2 from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_standard_deviation from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_quartile from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_skewness from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_sample_correlation from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_population_correlation from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_zscore from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_mean_deviation from DescriptiveStatisticsFunction import DescriptiveStatisticsFunction from HelperFunctions import HelperFunctions import unittest class MyTestCase(unittest.TestCase): def setUp(self) -> None: self.val_int = random.sample(range(1,100), 13) # self.libStat = HelperFunctions # self.createStat = DescriptiveStatisticsFunction self.mode_data = random.choices(range(10), k= 10) self.quartile_data = [10, 20, 30, 40, 50, 60, 70] self.datax = np.array(20*randn(10) + 100).tolist() self.datay = self.datax + (10*randn(10) + 50) def test_mean_calculator(self): self.assertEqual(created_mean(self.val_int), lib_mean(self.val_int)) def test_median_calculator(self): self.assertEqual(created_median(self.val_int), lib_median(self.val_int)) def test_mode_calculator(self): self.assertEqual(created_mode(self.val_int), lib_mode(self.val_int)) def test_variance_calculator(self): self.assertEqual(created_variance1(self.val_int), lib_variance(self.val_int)) def test_stdev_calculator(self): self.assertEqual(created_standard_deviation(self.val_int), lib_standard_deviation(self.val_int)) def test_quartile_calculator(self): self.assertEqual(created_quartile(self.quartile_data), [20, 40, 60]) def test_skewness_calculator(self): self.assertEqual(created_skewness(self.val_int), lib_skewness(self.val_int)) def test_correlation_calculator(self): created_correlation = created_sample_correlation(self.datax, self.datay) lib_correlation = lib_sample_correlation(self.datax, self.datay) self.assertEqual(created_correlation, "{0:.2f}".format(round(lib_correlation[0],2))) def test_zscore(self): self.assertEqual(created_zscore(self.datax), lib_zscore(self.datax)) if __name__ == '__main__': unittest.main()
[ "DescriptiveStatisticsFunction.DescriptiveStatisticsFunction.created_median", "DescriptiveStatisticsFunction.DescriptiveStatisticsFunction.created_quartile", "DescriptiveStatisticsFunction.DescriptiveStatisticsFunction.created_skewness", "HelperFunctions.HelperFunctions.lib_zscore", "DescriptiveStatisticsFunction.DescriptiveStatisticsFunction.created_standard_deviation", "HelperFunctions.HelperFunctions.lib_sample_correlation", "sys.path.append", "unittest.main", "numpy.random.randn", "DescriptiveStatisticsFunction.DescriptiveStatisticsFunction.created_mean", "DescriptiveStatisticsFunction.DescriptiveStatisticsFunction.created_zscore", "DescriptiveStatisticsFunction.DescriptiveStatisticsFunction.created_sample_correlation", "HelperFunctions.HelperFunctions.lib_median", "DescriptiveStatisticsFunction.DescriptiveStatisticsFunction.created_mode", "DescriptiveStatisticsFunction.DescriptiveStatisticsFunction.created_variance1", "HelperFunctions.HelperFunctions.lib_variance", "HelperFunctions.HelperFunctions.lib_mean", "HelperFunctions.HelperFunctions.lib_standard_deviation", "HelperFunctions.HelperFunctions.lib_mode", "HelperFunctions.HelperFunctions.lib_skewness" ]
[((75, 126), 'sys.path.append', 'sys.path.append', (['"""../DescriptiveStatisticsFunction"""'], {}), "('../DescriptiveStatisticsFunction')\n", (90, 126), False, 'import sys\n'), ((127, 164), 'sys.path.append', 'sys.path.append', (['"""../HelperFunctions"""'], {}), "('../HelperFunctions')\n", (142, 164), False, 'import sys\n'), ((3608, 3623), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3621, 3623), False, 'import unittest\n'), ((3252, 3302), 'DescriptiveStatisticsFunction.DescriptiveStatisticsFunction.created_sample_correlation', 'created_sample_correlation', (['self.datax', 'self.datay'], {}), '(self.datax, self.datay)\n', (3278, 3302), False, 'from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_sample_correlation\n'), ((3329, 3375), 'HelperFunctions.HelperFunctions.lib_sample_correlation', 'lib_sample_correlation', (['self.datax', 'self.datay'], {}), '(self.datax, self.datay)\n', (3351, 3375), False, 'from HelperFunctions.HelperFunctions import lib_sample_correlation\n'), ((2378, 2404), 'DescriptiveStatisticsFunction.DescriptiveStatisticsFunction.created_mean', 'created_mean', (['self.val_int'], {}), '(self.val_int)\n', (2390, 2404), False, 'from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_mean\n'), ((2406, 2428), 'HelperFunctions.HelperFunctions.lib_mean', 'lib_mean', (['self.val_int'], {}), '(self.val_int)\n', (2414, 2428), False, 'from HelperFunctions.HelperFunctions import lib_mean\n'), ((2494, 2522), 'DescriptiveStatisticsFunction.DescriptiveStatisticsFunction.created_median', 'created_median', (['self.val_int'], {}), '(self.val_int)\n', (2508, 2522), False, 'from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_median\n'), ((2524, 2548), 'HelperFunctions.HelperFunctions.lib_median', 'lib_median', (['self.val_int'], {}), '(self.val_int)\n', (2534, 2548), False, 'from HelperFunctions.HelperFunctions import lib_median\n'), ((2612, 2638), 'DescriptiveStatisticsFunction.DescriptiveStatisticsFunction.created_mode', 'created_mode', (['self.val_int'], {}), '(self.val_int)\n', (2624, 2638), False, 'from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_mode\n'), ((2640, 2662), 'HelperFunctions.HelperFunctions.lib_mode', 'lib_mode', (['self.val_int'], {}), '(self.val_int)\n', (2648, 2662), False, 'from HelperFunctions.HelperFunctions import lib_mode\n'), ((2730, 2761), 'DescriptiveStatisticsFunction.DescriptiveStatisticsFunction.created_variance1', 'created_variance1', (['self.val_int'], {}), '(self.val_int)\n', (2747, 2761), False, 'from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_variance1\n'), ((2763, 2789), 'HelperFunctions.HelperFunctions.lib_variance', 'lib_variance', (['self.val_int'], {}), '(self.val_int)\n', (2775, 2789), False, 'from HelperFunctions.HelperFunctions import lib_variance\n'), ((2854, 2894), 'DescriptiveStatisticsFunction.DescriptiveStatisticsFunction.created_standard_deviation', 'created_standard_deviation', (['self.val_int'], {}), '(self.val_int)\n', (2880, 2894), False, 'from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_standard_deviation\n'), ((2896, 2932), 'HelperFunctions.HelperFunctions.lib_standard_deviation', 'lib_standard_deviation', (['self.val_int'], {}), '(self.val_int)\n', (2918, 2932), False, 'from HelperFunctions.HelperFunctions import lib_standard_deviation\n'), ((3000, 3036), 'DescriptiveStatisticsFunction.DescriptiveStatisticsFunction.created_quartile', 'created_quartile', (['self.quartile_data'], {}), '(self.quartile_data)\n', (3016, 3036), False, 'from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_quartile\n'), ((3118, 3148), 'DescriptiveStatisticsFunction.DescriptiveStatisticsFunction.created_skewness', 'created_skewness', (['self.val_int'], {}), '(self.val_int)\n', (3134, 3148), False, 'from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_skewness\n'), ((3150, 3176), 'HelperFunctions.HelperFunctions.lib_skewness', 'lib_skewness', (['self.val_int'], {}), '(self.val_int)\n', (3162, 3176), False, 'from HelperFunctions.HelperFunctions import lib_skewness\n'), ((3522, 3548), 'DescriptiveStatisticsFunction.DescriptiveStatisticsFunction.created_zscore', 'created_zscore', (['self.datax'], {}), '(self.datax)\n', (3536, 3548), False, 'from DescriptiveStatisticsFunction.DescriptiveStatisticsFunction import created_zscore\n'), ((3550, 3572), 'HelperFunctions.HelperFunctions.lib_zscore', 'lib_zscore', (['self.datax'], {}), '(self.datax)\n', (3560, 3572), False, 'from HelperFunctions.HelperFunctions import lib_zscore\n'), ((2300, 2309), 'numpy.random.randn', 'randn', (['(10)'], {}), '(10)\n', (2305, 2309), False, 'from numpy.random import randn\n'), ((2236, 2245), 'numpy.random.randn', 'randn', (['(10)'], {}), '(10)\n', (2241, 2245), False, 'from numpy.random import randn\n')]
from abc import ABC, abstractmethod from multiprocessing import Pool from shutil import rmtree from time import time import numpy as np import os import progressbar import pysam import pysamstats class PileupGenerator(ABC): """ Base class for generating pileups from read alignments. Usage: X, y = PileupGenerator(reference_fasta_path, mode).generate() """ def __init__(self, reference_fasta_path, mode, save_directory_path=None): """ Mode must be one of 'training' or 'inference' string indicating pileups generation mode. If 'training' is selected, pileups from different contigs are all be concatenated. If 'inference' is selected, pileups from different contig will be hold separate to enable to make consensus with same number of contigs. If save_directory_path is provided, generated pileups are stored in that directory. Also, paths to those stored files are returned in generate_pileups() method. :param reference_fasta_path: path to reference stored in fasta file format :type reference_fasta_path: str :param mode: either 'training' or 'inference' string, representing the mode for pileups generation :type mode: str :param save_directory_path: path to directory for storing pileups :type save_directory_path: str """ self.reference_fasta_path = reference_fasta_path self.mode = mode self.save_directory_path = save_directory_path self._check_mode() def _check_mode(self): """ Checks if given mode is supported: 'training' or 'inference'. :raise ValueError: if selected mode is not supported """ modes = ['training', 'inference'] if self.mode not in modes: raise ValueError( 'You must provide either \'training\' or \'inference\' mode, ' 'but \'{}\' given.'.format(self.mode)) def _check_save_directory_path(self): """ Checks if given save directory path doesn't exists. If given directory doesnt' exists, it creates it. :raise ValueError: if given save directory exists """ if self.save_directory_path is not None: if os.path.exists(self.save_directory_path): raise ValueError( 'You must provide non-existing save output directory, ' '{} given.'.format(self.save_directory_path)) else: os.makedirs(self.save_directory_path) def generate_pileups(self): """ Generates pileups from given alignments. :return: Pileups (X) and matching nucleus bases from reference (y) with concatenated contigs for inference mode, or separate contigs for training mode; also, if save_directory_path is provided, list of paths to saved files is returned in tuple (X, y_oh, contig_names, X_save_paths, y_save_paths). In both cases list of contig names is also returned. :rtype tuple of np.ndarray and list of str or tuple of np.array and list of str """ self._check_mode() self._check_save_directory_path() X, y_oh, contig_names = self._generate_pileups() total_pileups = len(X) if self.mode == 'training': # training mode X, y_oh = [np.concatenate(X, axis=0)], [ np.concatenate(y_oh, axis=0)] total_pileups = 1 else: # inference mode pass # nothing to do if self.save_directory_path is not None: return self._save_data(X, y_oh, contig_names, total_pileups) else: return X, y_oh, contig_names def _save_data(self, X, y_oh, contig_names, total_pileups): """ Saves data to given save_directory path. :param X: generated pileups :type X: list of np.ndarray :param y_oh: generated ground truth :type y_oh: list of np.ndarray :param contig_names: list of contig names :type contig_names: list of str :param total_pileups: total number of pileups :type total_pileups: int :return: generated pileups and ground truths :rtype: tuple of np.ndarrays and list of str """ X_save_paths = [ os.path.join( self.save_directory_path, 'pileups-X-{}.npy'.format(i)) for i in range(total_pileups)] y_save_paths = [os.path.join(self.save_directory_path, 'pileups-y-{}.npy'.format(i)) for i in range(total_pileups)] for X_save_path, y_save_path, Xi, yi in zip( X_save_paths, y_save_paths, X, y_oh): np.save(X_save_path, Xi) np.save(y_save_path, yi) return X, y_oh, X_save_paths, y_save_paths, contig_names @abstractmethod def _generate_pileups(self): """ Abstract method for generating pileups. :return: generated pileups, ground truth and contig names :rtype tuple of np.ndarray and list of str """ pass class PysamstatsNoIndelGenerator(PileupGenerator): """ Pileup generator which uses Pysamstats as backend (https://github.com/alimanfoo/pysamstats). This version doesn't include indels nor in pileups nor in ground truth. One example is: x_i = (num_A, num_C, num_G, num_T) y_i = ground truth class one-hot encoded (one of A, C, G or T) """ def __init__(self, bam_file_path, reference_fasta_path, mode, save_directory_path=None): """ :param bam_file_path: path to .bam file containing alignments :type bam_file_path: str :param reference_fasta_path: path to reference stored in fasta file format :type reference_fasta_path: str :param mode: either 'training' or 'inference' string, representing the mode for pileups generation :type mode: str :param save_directory_path: path to directory for storing pileups :type save_directory_path: str """ PileupGenerator.__init__(self, reference_fasta_path, mode, save_directory_path=save_directory_path) self.bam_file_path = bam_file_path def _generate_pileups(self): bam_file = pysam.AlignmentFile(self.bam_file_path) info_of_interest = ['A', 'C', 'G', 'T'] # Last number in shape - 5 - is for letters other than A, C, G and T. mapping = {'A': 0, 'a': 0, 'C': 1, 'c': 1, 'G': 2, 'g': 2, 'T': 3, 't': 3} total_options = len(info_of_interest) + 1 pileups = [np.zeros( (bam_file.get_reference_length(contig_name), len(info_of_interest) )) for contig_name in bam_file.references] y_oh = [np.zeros( (bam_file.get_reference_length(contig_name), total_options )) for contig_name in bam_file.references] total_length = np.sum( [bam_file.get_reference_length(contig_name) for contig_name in bam_file.references]) progress_counter = 0 contig_names = bam_file.references with progressbar.ProgressBar(max_value=total_length) as progress_bar: for contig_id, contig_name in enumerate(contig_names): for record in pysamstats.stat_variation( bam_file, chrom=contig_name, fafile=self.reference_fasta_path): progress_bar.update(progress_counter) progress_counter += 1 curr_position = record['pos'] for i, info in enumerate(info_of_interest): pileups[contig_id][curr_position][i] += record[info] y_oh[contig_id][curr_position][ mapping.get(record['ref'], -1)] = 1 return pileups, y_oh, contig_names class PysamstatsIndelGenerator(PileupGenerator): """ Pileup generator which uses Pysamstats as backend (https://github.com/alimanfoo/pysamstats). This version includes indels both in pileups and ground truth. One example is: x_i = (num_A, num_C, num_G, num_T, num_I, num_D) y_i = ground truth class one-hot encoded (one of A, C, G, T, I or D) """ def __init__(self, bam_file_path, reference_fasta_path, mode, save_directory_path=None): """ :param bam_file_path: path to .bam file containing alignments :type bam_file_path: str :param reference_fasta_path: path to reference stored in fasta file format :type reference_fasta_path: str :param mode: either 'training' or 'inference' string, representing the mode for pileups generation :type mode: str :param save_directory_path: path to directory for storing pileups :type save_directory_path: str """ PileupGenerator.__init__(self, reference_fasta_path, mode, save_directory_path=save_directory_path) self.bam_file_path = bam_file_path def _generate_pileups(self): bam_file = pysam.AlignmentFile(self.bam_file_path) info_of_interest = ['A', 'C', 'G', 'T', 'insertions', 'deletions'] indel_positions = [4, 5] # Last number in shape - 5 - is for letters other than A, C, G and T. mapping = {'A': 0, 'a': 0, 'C': 1, 'c': 1, 'G': 2, 'g': 2, 'T': 3, 't': 3} total_options = len(info_of_interest) + 1 pileups = [np.zeros( (bam_file.get_reference_length(contig_name), len(info_of_interest) )) for contig_name in bam_file.references] y_oh = [np.zeros( (bam_file.get_reference_length(contig_name), total_options )) for contig_name in bam_file.references] total_length = np.sum( [bam_file.get_reference_length(contig_name) for contig_name in bam_file.references]) progress_counter = 0 contig_names = bam_file.references with progressbar.ProgressBar(max_value=total_length) as progress_bar: for contig_id, contig_name in enumerate(contig_names): for record in pysamstats.stat_variation( bam_file, chrom=contig_name, fafile=self.reference_fasta_path): progress_bar.update(progress_counter) progress_counter += 1 curr_position = record['pos'] for i, info in enumerate(info_of_interest): pileups[contig_id][curr_position][i] += record[info] pileup_argmax = np.argmax( pileups[contig_id][curr_position]) if pileup_argmax in indel_positions: y_oh[contig_id][curr_position][pileup_argmax] = 1 else: y_oh[contig_id][curr_position][ mapping.get(record['ref'], -1)] = 1 return pileups, y_oh, contig_names class RaconMSAGenerator(PileupGenerator): """ Pileup generator which uses MSA algorithm in order to give moge informative pileups. As MSA algorithm, Racon tool is used: https://github.com/isovic/racon One example is: x_i = (num_A, num_C, num_G, num_T, num_D) y_i = ground truth class one-hot encoded (one of A, C, G, T, I or D) Before pileup generation, Racon tool produces MSA which is stored in textual file. Every six lines in that file represent the following: - contig - number of As - number of Cs - number of Gs - number of Ts - number of Ds """ _RACON_CMD = '{}/racon-hax/racon_hax -t {} {} {} {} > {}' def __init__(self, reads_path, sam_file_path, reference_fasta_path, mode, tools_dir, racon_hax_output_dir, save_directory_path=None, num_threads=1): """ :param reads_path: path to fastq file containg reads :type reads_path: str :param sam_file_path: path to .sam file containing alignments :type sam_file_path: str :param reference_fasta_path: path to reference stored in fasta file format :type reference_fasta_path: str :param mode: either 'training' or 'inference' string, representing the mode for pileups generation :type mode: str :param tools_dir: path to root directory containing tools (like Racon) :type tools_dir: str :param racon_hax_output_dir: path to directory where Racon output will be temporary stored :type racon_hax_output_dir: str :param save_directory_path: path to directory for storing pileups :type save_directory_path: str :param num_threads: number of threads for running the Racon tool :type num_threads: int """ PileupGenerator.__init__(self, reference_fasta_path, mode, save_directory_path=save_directory_path) self.reads_path = reads_path self.sam_file_path = sam_file_path self.num_threads = num_threads self.tools_dir = tools_dir self.racon_hax_output_dir = racon_hax_output_dir @staticmethod def parse_line(line): """ Parses given line by splitting numbers are casting them to int. Given line is one output line from Racon tool. :param line: line to be parsed :type line: str :return: integers parsed from given line :rtype: list of int """ return [int(v) for v in line.strip().split()] def _parse_racon_hax_output(self, racon_hax_output_path): """ Every pileup has 5 rows A, C, G, T and D. At some column i, number of As, Cs, Gs, Ts and Ds correspond to number of those letters at position i on reference in pileup. :param racon_hax_output_path: :return: """ references, pileups = list(), list() with Pool(self.num_threads) as pool: with open(racon_hax_output_path) as f: while True: # loop for multiple contigs reference = f.readline().strip() if len(reference) == 0: # EOF break lines = [f.readline() for _ in range(5)] pileup = np.array(pool.map(self.parse_line, lines)) references.append(reference) pileups.append(pileup) return references, pileups @staticmethod def _generate_contig_names(num_contigs): return ['contig_{}'.format(i) for i in range(num_contigs)] def _generate_pileups(self): timestamp = str(int(time())) racon_hax_output_path = os.path.join(self.racon_hax_output_dir, 'racon-hex-{}.txt'.format( timestamp)) os.makedirs(self.racon_hax_output_dir) # Generate racon_hax output (MSA algorithm). os.system( RaconMSAGenerator._RACON_CMD.format( self.tools_dir, self.num_threads, self.reads_path, self.sam_file_path, self.reference_fasta_path, racon_hax_output_path )) # Parse the racon_hax output. references, pileups = self._parse_racon_hax_output( racon_hax_output_path) # Remove racon_hax output. rmtree(self.racon_hax_output_dir) num_contigs = len(references) contig_names = self._generate_contig_names(num_contigs) # D - deletions; I - insertions. y_classes = ['A', 'C', 'G', 'T', 'I', 'D'] mapping = {'A': 0, 'a': 0, 'C': 1, 'c': 1, 'G': 2, 'g': 2, 'T': 3, 't': 3} # Parse all contigs. total_options = len(y_classes) + 1 y_oh = [np.zeros( (len(reference), total_options)) for reference in references] # Transpose pileups to make one example to have shape: (1, # num_features). pileups = [pileup.T for pileup in pileups] total_length = np.sum([len(reference) for reference in references]) progress_counter = 0 with progressbar.ProgressBar(max_value=total_length) as progress_bar: for contig_id, reference in enumerate(references): for position, base in enumerate(reference): progress_bar.update(progress_counter) progress_counter += 1 num_Ds = pileups[contig_id][position][4] num_bases = np.max(pileups[contig_id][position][:4]) if base == '-': # insertion y_oh[contig_id][position][4] = 1 # 4 is insertion id elif num_Ds > num_bases: # deletion y_oh[contig_id][position][5] = 1 # 5 is deletion id else: y_oh[contig_id][position][ mapping.get(base, -1)] = 1 return pileups, y_oh, contig_names
[ "numpy.save", "os.makedirs", "numpy.argmax", "pysam.AlignmentFile", "os.path.exists", "time.time", "numpy.max", "multiprocessing.Pool", "shutil.rmtree", "pysamstats.stat_variation", "progressbar.ProgressBar", "numpy.concatenate" ]
[((6509, 6548), 'pysam.AlignmentFile', 'pysam.AlignmentFile', (['self.bam_file_path'], {}), '(self.bam_file_path)\n', (6528, 6548), False, 'import pysam\n'), ((9409, 9448), 'pysam.AlignmentFile', 'pysam.AlignmentFile', (['self.bam_file_path'], {}), '(self.bam_file_path)\n', (9428, 9448), False, 'import pysam\n'), ((15350, 15388), 'os.makedirs', 'os.makedirs', (['self.racon_hax_output_dir'], {}), '(self.racon_hax_output_dir)\n', (15361, 15388), False, 'import os\n'), ((15920, 15953), 'shutil.rmtree', 'rmtree', (['self.racon_hax_output_dir'], {}), '(self.racon_hax_output_dir)\n', (15926, 15953), False, 'from shutil import rmtree\n'), ((2314, 2354), 'os.path.exists', 'os.path.exists', (['self.save_directory_path'], {}), '(self.save_directory_path)\n', (2328, 2354), False, 'import os\n'), ((4877, 4901), 'numpy.save', 'np.save', (['X_save_path', 'Xi'], {}), '(X_save_path, Xi)\n', (4884, 4901), True, 'import numpy as np\n'), ((4914, 4938), 'numpy.save', 'np.save', (['y_save_path', 'yi'], {}), '(y_save_path, yi)\n', (4921, 4938), True, 'import numpy as np\n'), ((7401, 7448), 'progressbar.ProgressBar', 'progressbar.ProgressBar', ([], {'max_value': 'total_length'}), '(max_value=total_length)\n', (7424, 7448), False, 'import progressbar\n'), ((10361, 10408), 'progressbar.ProgressBar', 'progressbar.ProgressBar', ([], {'max_value': 'total_length'}), '(max_value=total_length)\n', (10384, 10408), False, 'import progressbar\n'), ((14398, 14420), 'multiprocessing.Pool', 'Pool', (['self.num_threads'], {}), '(self.num_threads)\n', (14402, 14420), False, 'from multiprocessing import Pool\n'), ((16688, 16735), 'progressbar.ProgressBar', 'progressbar.ProgressBar', ([], {'max_value': 'total_length'}), '(max_value=total_length)\n', (16711, 16735), False, 'import progressbar\n'), ((2566, 2603), 'os.makedirs', 'os.makedirs', (['self.save_directory_path'], {}), '(self.save_directory_path)\n', (2577, 2603), False, 'import os\n'), ((7563, 7656), 'pysamstats.stat_variation', 'pysamstats.stat_variation', (['bam_file'], {'chrom': 'contig_name', 'fafile': 'self.reference_fasta_path'}), '(bam_file, chrom=contig_name, fafile=self.\n reference_fasta_path)\n', (7588, 7656), False, 'import pysamstats\n'), ((10523, 10616), 'pysamstats.stat_variation', 'pysamstats.stat_variation', (['bam_file'], {'chrom': 'contig_name', 'fafile': 'self.reference_fasta_path'}), '(bam_file, chrom=contig_name, fafile=self.\n reference_fasta_path)\n', (10548, 10616), False, 'import pysamstats\n'), ((15128, 15134), 'time.time', 'time', ([], {}), '()\n', (15132, 15134), False, 'from time import time\n'), ((3464, 3489), 'numpy.concatenate', 'np.concatenate', (['X'], {'axis': '(0)'}), '(X, axis=0)\n', (3478, 3489), True, 'import numpy as np\n'), ((3510, 3538), 'numpy.concatenate', 'np.concatenate', (['y_oh'], {'axis': '(0)'}), '(y_oh, axis=0)\n', (3524, 3538), True, 'import numpy as np\n'), ((10992, 11036), 'numpy.argmax', 'np.argmax', (['pileups[contig_id][curr_position]'], {}), '(pileups[contig_id][curr_position])\n', (11001, 11036), True, 'import numpy as np\n'), ((17070, 17110), 'numpy.max', 'np.max', (['pileups[contig_id][position][:4]'], {}), '(pileups[contig_id][position][:4])\n', (17076, 17110), True, 'import numpy as np\n')]
import numpy as np class Method: def __call__(self, x): raise NotImplementedError() def disable(self, index, x): raise NotImplementedError def __repr__(self): raise NotImplementedError class Max(Method): def __call__(self, x): return x.argmax() def disable(self, index, x): x[index] = -np.inf def __repr__(self): return 'Max' class Top(Method): def __init__(self, n=5): self.n = n def __call__(self, x): return np.random.choice(np.argpartition(x, -self.n, axis=None)[-self.n:]) def disable(self, index, x): x[index] = -np.inf def __repr__(self): return 'Top' + str(self.n) class PowerProb(Method): def __init__(self, power=4): self.power = power def __call__(self, x): raveled = np.power(np.ravel(x), self.power) return np.random.choice(np.arange(x.size), p=(raveled / np.sum(raveled))) def disable(self, index, x): x[index] = 0.0 def __repr__(self): return 'PowerProb' + str(self.power) class RandomInference(Method): def __call__(self, x): return np.random.choice(np.arange(x.size)) def disable(self, index, x): pass def __repr__(self): return 'RandomInference'
[ "numpy.argpartition", "numpy.arange", "numpy.sum", "numpy.ravel" ]
[((848, 859), 'numpy.ravel', 'np.ravel', (['x'], {}), '(x)\n', (856, 859), True, 'import numpy as np\n'), ((905, 922), 'numpy.arange', 'np.arange', (['x.size'], {}), '(x.size)\n', (914, 922), True, 'import numpy as np\n'), ((1174, 1191), 'numpy.arange', 'np.arange', (['x.size'], {}), '(x.size)\n', (1183, 1191), True, 'import numpy as np\n'), ((535, 573), 'numpy.argpartition', 'np.argpartition', (['x', '(-self.n)'], {'axis': 'None'}), '(x, -self.n, axis=None)\n', (550, 573), True, 'import numpy as np\n'), ((937, 952), 'numpy.sum', 'np.sum', (['raveled'], {}), '(raveled)\n', (943, 952), True, 'import numpy as np\n')]
import numpy as np from scipy import interpolate from scipy.ndimage import gaussian_filter import functools from . import mdfmodels, fast_mdfmodels import dynesty as dy from dynesty import plotting as dyplot """ TODO: figure out how to deal with error bars. Do I just have to hierarchical inference it? """ def ptform_leaky_box(u, logpmin, logpmax): return 10**((logpmax-logpmin)*u + logpmin) def lnlkhd_leaky_box(theta, fehdata): p = theta[0] lnp = mdfmodels.log_leaky_box(fehdata, p) return np.sum(lnp) def fit_leaky_box(fehdata, logpmin=-3, logpmax=-1, pool=None, ptform=None, **run_nested_kwargs): lnlkhd = functools.partial(lnlkhd_leaky_box, fehdata=fehdata) if ptform is None: ptform = functools.partial(ptform_leaky_box, logpmin=logpmin, logpmax=logpmax) dsampler = dy.DynamicNestedSampler(lnlkhd, ptform, ndim=1, pool=pool) dsampler.run_nested(**run_nested_kwargs) return dsampler def lnlkhd_pre_enriched_box(theta, fehdata): p, feh0 = theta lnp = mdfmodels.log_pre_enriched_box(fehdata, p, feh0) return np.sum(lnp) def ptform_pre_enriched_box(u, logpmin, logpmax, feh0min, feh0max): u[0] = 10**((logpmax-logpmin)*u[0] + logpmin) u[1] = (feh0max-feh0min)*u[1] + feh0min return u def fit_pre_enriched_box(fehdata, logpmin=-3, logpmax=-1, feh0min=-5, feh0max=-2, pool=None, ptform=None, **run_nested_kwargs): lnlkhd = functools.partial(lnlkhd_pre_enriched_box, fehdata=fehdata) if ptform is None: ptform = functools.partial(ptform_pre_enriched_box, logpmin=logpmin, logpmax=logpmax, feh0min=feh0min, feh0max=feh0max) dsampler = dy.DynamicNestedSampler(lnlkhd, ptform, ndim=2, pool=pool) dsampler.run_nested(**run_nested_kwargs) return dsampler def lnlkhd_extra_gas(theta, fehdata): p, M = theta lnp = mdfmodels.log_extra_gas(fehdata, p, M) return np.sum(lnp) def ptform_extra_gas(u, logpmin, logpmax, Mmin, Mmax): u[0] = 10**((logpmax-logpmin)*u[0] + logpmin) u[1] = (Mmax-Mmin)*u[1] + Mmin return u def fit_extra_gas(fehdata, logpmin=-3, logpmax=-1, Mmin=1, Mmax=10, pool=None, ptform=None, **run_nested_kwargs): lnlkhd = functools.partial(lnlkhd_extra_gas, fehdata=fehdata) if ptform is None: ptform = functools.partial(ptform_extra_gas, logpmin=logpmin, logpmax=logpmax, Mmin=Mmin, Mmax=Mmax) dsampler = dy.DynamicNestedSampler(lnlkhd, ptform, ndim=2, pool=pool) dsampler.run_nested(**run_nested_kwargs) return dsampler def fit_leaky_box_errors(fehdata, efehdata, logpmin=-3, logpmax=-1, pool=None, ptform=None, **run_nested_kwargs): griddata = fast_mdfmodels.load_data("leaky_box") lnlkhd = functools.partial(fast_mdfmodels.fast_loglkhd_leaky_box, fehdata=fehdata, efehdata=efehdata, griddata=griddata) if ptform is None: ptform = functools.partial(ptform_leaky_box, logpmin=logpmin, logpmax=logpmax) dsampler = dy.DynamicNestedSampler(lnlkhd, ptform, ndim=1, pool=pool) dsampler.run_nested(**run_nested_kwargs) return dsampler def fit_pre_enriched_box_errors(fehdata, efehdata, logpmin=-3, logpmax=-1, feh0min=-5, feh0max=-2, pool=None, ptform=None, **run_nested_kwargs): griddata = fast_mdfmodels.load_data("pre_enriched_box") lnlkhd = functools.partial(fast_mdfmodels.fast_loglkhd_pre_enriched_box, fehdata=fehdata, efehdata=efehdata, griddata=griddata) if ptform is None: ptform = functools.partial(ptform_pre_enriched_box, logpmin=logpmin, logpmax=logpmax, feh0min=feh0min, feh0max=feh0max) dsampler = dy.DynamicNestedSampler(lnlkhd, ptform, ndim=2, pool=pool) dsampler.run_nested(**run_nested_kwargs) return dsampler def fit_extra_gas_errors(fehdata, efehdata, logpmin=-3, logpmax=-1, Mmin=1, Mmax=10, pool=None, ptform=None, **run_nested_kwargs): griddata = fast_mdfmodels.load_data("extra_gas") lnlkhd = functools.partial(fast_mdfmodels.fast_loglkhd_extra_gas, fehdata=fehdata, efehdata=efehdata, griddata=griddata) if ptform is None: ptform = functools.partial(ptform_extra_gas, logpmin=logpmin, logpmax=logpmax, Mmin=Mmin, Mmax=Mmax) dsampler = dy.DynamicNestedSampler(lnlkhd, ptform, ndim=2, pool=pool) dsampler.run_nested(**run_nested_kwargs) return dsampler def ptform_gaussian(u, mumin, mumax, logsigmamin, logsigmamax): u[0] = (mumax-mumin)*u[0] + mumin u[1] = 10**((logsigmamax-logsigmamin)*u[1] + logsigmamin) return u def fit_gaussian_errors(fehdata, efehdata, mumin = -4, mumax = -1, logsigmamin=-2, logsigmamax=1, pool=None, ptform=None, **run_nested_kwargs): lnlkhd = functools.partial(fast_mdfmodels.fast_loglkhd_gaussian, fehdata=fehdata, efehdata=efehdata) if ptform is None: ptform = functools.partial(ptform_gaussian, mumin=mumin, mumax=mumax, logsigmamin=logsigmamin, logsigmamax=logsigmamax) dsampler = dy.DynamicNestedSampler(lnlkhd, ptform, ndim=2, pool=pool) dsampler.run_nested(**run_nested_kwargs) return dsampler
[ "functools.partial", "dynesty.DynamicNestedSampler", "numpy.sum" ]
[((513, 524), 'numpy.sum', 'np.sum', (['lnp'], {}), '(lnp)\n', (519, 524), True, 'import numpy as np\n'), ((653, 705), 'functools.partial', 'functools.partial', (['lnlkhd_leaky_box'], {'fehdata': 'fehdata'}), '(lnlkhd_leaky_box, fehdata=fehdata)\n', (670, 705), False, 'import functools\n'), ((831, 889), 'dynesty.DynamicNestedSampler', 'dy.DynamicNestedSampler', (['lnlkhd', 'ptform'], {'ndim': '(1)', 'pool': 'pool'}), '(lnlkhd, ptform, ndim=1, pool=pool)\n', (854, 889), True, 'import dynesty as dy\n'), ((1091, 1102), 'numpy.sum', 'np.sum', (['lnp'], {}), '(lnp)\n', (1097, 1102), True, 'import numpy as np\n'), ((1494, 1553), 'functools.partial', 'functools.partial', (['lnlkhd_pre_enriched_box'], {'fehdata': 'fehdata'}), '(lnlkhd_pre_enriched_box, fehdata=fehdata)\n', (1511, 1553), False, 'import functools\n'), ((1755, 1813), 'dynesty.DynamicNestedSampler', 'dy.DynamicNestedSampler', (['lnlkhd', 'ptform'], {'ndim': '(2)', 'pool': 'pool'}), '(lnlkhd, ptform, ndim=2, pool=pool)\n', (1778, 1813), True, 'import dynesty as dy\n'), ((1995, 2006), 'numpy.sum', 'np.sum', (['lnp'], {}), '(lnp)\n', (2001, 2006), True, 'import numpy as np\n'), ((2341, 2393), 'functools.partial', 'functools.partial', (['lnlkhd_extra_gas'], {'fehdata': 'fehdata'}), '(lnlkhd_extra_gas, fehdata=fehdata)\n', (2358, 2393), False, 'import functools\n'), ((2576, 2634), 'dynesty.DynamicNestedSampler', 'dy.DynamicNestedSampler', (['lnlkhd', 'ptform'], {'ndim': '(2)', 'pool': 'pool'}), '(lnlkhd, ptform, ndim=2, pool=pool)\n', (2599, 2634), True, 'import dynesty as dy\n'), ((2931, 3046), 'functools.partial', 'functools.partial', (['fast_mdfmodels.fast_loglkhd_leaky_box'], {'fehdata': 'fehdata', 'efehdata': 'efehdata', 'griddata': 'griddata'}), '(fast_mdfmodels.fast_loglkhd_leaky_box, fehdata=fehdata,\n efehdata=efehdata, griddata=griddata)\n', (2948, 3046), False, 'import functools\n'), ((3230, 3288), 'dynesty.DynamicNestedSampler', 'dy.DynamicNestedSampler', (['lnlkhd', 'ptform'], {'ndim': '(1)', 'pool': 'pool'}), '(lnlkhd, ptform, ndim=1, pool=pool)\n', (3253, 3288), True, 'import dynesty as dy\n'), ((3668, 3791), 'functools.partial', 'functools.partial', (['fast_mdfmodels.fast_loglkhd_pre_enriched_box'], {'fehdata': 'fehdata', 'efehdata': 'efehdata', 'griddata': 'griddata'}), '(fast_mdfmodels.fast_loglkhd_pre_enriched_box, fehdata=\n fehdata, efehdata=efehdata, griddata=griddata)\n', (3685, 3791), False, 'import functools\n'), ((4015, 4073), 'dynesty.DynamicNestedSampler', 'dy.DynamicNestedSampler', (['lnlkhd', 'ptform'], {'ndim': '(2)', 'pool': 'pool'}), '(lnlkhd, ptform, ndim=2, pool=pool)\n', (4038, 4073), True, 'import dynesty as dy\n'), ((4411, 4526), 'functools.partial', 'functools.partial', (['fast_mdfmodels.fast_loglkhd_extra_gas'], {'fehdata': 'fehdata', 'efehdata': 'efehdata', 'griddata': 'griddata'}), '(fast_mdfmodels.fast_loglkhd_extra_gas, fehdata=fehdata,\n efehdata=efehdata, griddata=griddata)\n', (4428, 4526), False, 'import functools\n'), ((4732, 4790), 'dynesty.DynamicNestedSampler', 'dy.DynamicNestedSampler', (['lnlkhd', 'ptform'], {'ndim': '(2)', 'pool': 'pool'}), '(lnlkhd, ptform, ndim=2, pool=pool)\n', (4755, 4790), True, 'import dynesty as dy\n'), ((5263, 5358), 'functools.partial', 'functools.partial', (['fast_mdfmodels.fast_loglkhd_gaussian'], {'fehdata': 'fehdata', 'efehdata': 'efehdata'}), '(fast_mdfmodels.fast_loglkhd_gaussian, fehdata=fehdata,\n efehdata=efehdata)\n', (5280, 5358), False, 'import functools\n'), ((5587, 5645), 'dynesty.DynamicNestedSampler', 'dy.DynamicNestedSampler', (['lnlkhd', 'ptform'], {'ndim': '(2)', 'pool': 'pool'}), '(lnlkhd, ptform, ndim=2, pool=pool)\n', (5610, 5645), True, 'import dynesty as dy\n'), ((746, 815), 'functools.partial', 'functools.partial', (['ptform_leaky_box'], {'logpmin': 'logpmin', 'logpmax': 'logpmax'}), '(ptform_leaky_box, logpmin=logpmin, logpmax=logpmax)\n', (763, 815), False, 'import functools\n'), ((1594, 1708), 'functools.partial', 'functools.partial', (['ptform_pre_enriched_box'], {'logpmin': 'logpmin', 'logpmax': 'logpmax', 'feh0min': 'feh0min', 'feh0max': 'feh0max'}), '(ptform_pre_enriched_box, logpmin=logpmin, logpmax=logpmax,\n feh0min=feh0min, feh0max=feh0max)\n', (1611, 1708), False, 'import functools\n'), ((2434, 2530), 'functools.partial', 'functools.partial', (['ptform_extra_gas'], {'logpmin': 'logpmin', 'logpmax': 'logpmax', 'Mmin': 'Mmin', 'Mmax': 'Mmax'}), '(ptform_extra_gas, logpmin=logpmin, logpmax=logpmax, Mmin=\n Mmin, Mmax=Mmax)\n', (2451, 2530), False, 'import functools\n'), ((3145, 3214), 'functools.partial', 'functools.partial', (['ptform_leaky_box'], {'logpmin': 'logpmin', 'logpmax': 'logpmax'}), '(ptform_leaky_box, logpmin=logpmin, logpmax=logpmax)\n', (3162, 3214), False, 'import functools\n'), ((3889, 4003), 'functools.partial', 'functools.partial', (['ptform_pre_enriched_box'], {'logpmin': 'logpmin', 'logpmax': 'logpmax', 'feh0min': 'feh0min', 'feh0max': 'feh0max'}), '(ptform_pre_enriched_box, logpmin=logpmin, logpmax=logpmax,\n feh0min=feh0min, feh0max=feh0max)\n', (3906, 4003), False, 'import functools\n'), ((4625, 4721), 'functools.partial', 'functools.partial', (['ptform_extra_gas'], {'logpmin': 'logpmin', 'logpmax': 'logpmax', 'Mmin': 'Mmin', 'Mmax': 'Mmax'}), '(ptform_extra_gas, logpmin=logpmin, logpmax=logpmax, Mmin=\n Mmin, Mmax=Mmax)\n', (4642, 4721), False, 'import functools\n'), ((5426, 5541), 'functools.partial', 'functools.partial', (['ptform_gaussian'], {'mumin': 'mumin', 'mumax': 'mumax', 'logsigmamin': 'logsigmamin', 'logsigmamax': 'logsigmamax'}), '(ptform_gaussian, mumin=mumin, mumax=mumax, logsigmamin=\n logsigmamin, logsigmamax=logsigmamax)\n', (5443, 5541), False, 'import functools\n')]
import numpy as np import os import numpy as np import math import matplotlib as mpl mpl.rcParams.update({ "axes.titlesize" : "medium" }) import matplotlib.pyplot as plt plt.rcParams.update({ "pgf.texsystem": "pdflatex", "pgf.preamble": [ r"\usepackage[utf8x]{inputenc}", r"\usepackage[T1]{fontenc}", ] }) pgf_with_rc_fonts = { "font.family": "serif", "font.serif": [], "font.size": 10, } mpl.rcParams.update(pgf_with_rc_fonts) #dist_folder = '/home/rettenls/data/experiments/wiki/analysis/word-wise-instability/' dist_folder = '/home/lucas/data/experiments/wiki/analysis/word-wise-instability/' language = 'pl' models = ['word2vec', 'glove', 'fasttext'] name_models = ['\\textbf{word2vec}', '\\textbf{GloVe}', '\\textbf{fastText}'] fig, ax = plt.subplots(nrows=3, ncols=1, sharex=True, sharey=True, figsize=(4, 7.5)) # GET X & Y Minimum and Maximum x_min = 1 x_max = 0 y_min = 1 y_max = 0 for i,cell in enumerate(ax): # Get Data model = models[i] # Intrinsic Stability data_int = np.load(dist_folder + language + '_' + model + '_shuffle.npz') stab_int = np.mean(data_int['arr_0'], axis = 1) freq = data_int['arr_1'] / 120 # Extrinsic Stability data_ext = np.load(dist_folder + language + '_' + model + '_bootstrap.npz') stab_ext = np.sqrt(np.square( np.mean(data_ext['arr_0'], axis = 1)) - np.square(stab_int)) x_min = min(x_min, np.min(freq)) x_max = max(x_max, np.max(freq)) y_min = min(y_min, np.min(stab_int), np.min(stab_ext)) y_max = max(y_max, np.max(stab_int), np.max(stab_ext)) freq, stab_int, stab_ext for i,cell in enumerate(ax): # Get Data model = models[i] # Intrinsic Stability data_int = np.load(dist_folder + language + '_' + model + '_shuffle.npz') stab_int = np.mean(data_int['arr_0'], axis = 1) freq = data_int['arr_1'] / 120 # Extrinsic Stability data_ext = np.load(dist_folder + language + '_' + model + '_bootstrap.npz') stab_ext = np.sqrt(np.square( np.mean(data_ext['arr_0'], axis = 1)) - np.square(stab_int)) cell.scatter(freq, stab_int, s = 3, label = 'Intrinsic Instability') cell.scatter(freq, stab_ext, s = 3, label = 'Extrinsic Instability') # Settings cell.set_xlim([x_min,x_max]) cell.set_xscale('log') cell.set_ylim([0, (int(100 * y_max) + 1) / 100]) #cell.set_yticks([0,0.02,0.04,0.06]) # Plot cell.legend() cell.set_ylabel('Word Instability', rotation = 90) secax = cell.secondary_yaxis('right') secax.set_ylabel(name_models[i], rotation = 90) secax.set_ticks([]) if (i == 2): cell.set_xlabel('Word Frequency') """ # SETTINGS plt.xlabel('Word Frequency') plt.ylabel('Stability') plt.legend() plt.ylim([0,0.04]) plt.xlim(smallest, largest) plt.xscale('log') """ #plt.tight_layout() plt.savefig("/home/lucas/Google Drive/Documents/Studium/Masterthesis/Thesis/plots/word-wise-instability-" + language + ".pgf") plt.show() """ plt.tight_layout() plt.savefig("/home/lucas/Google Drive/Documents/Studium/Masterthesis/Thesis/plots/gauss_p_values.pgf") """ """ total_batch_num = 20 total_sample_num = len(freq) sort_indices = np.argsort(freq) space = np.logspace(np.log10(smallest), np.log10(largest), num = total_batch_num + 1) print(space, smallest, largest, largest < space[-1]) batch_data = list() for batch_num in range(total_batch_num): lower = space[batch_num] upper = space[batch_num + 1] if batch_num == (total_batch_num - 1): indices = np.where(freq >= lower) else: indices = np.where((freq < upper) & (freq >= lower)) if len(indices[0]) > 25: batch_data_point = np.zeros((3, 2)) batch_data_point[0][0] = (lower + upper) / 2 batch_data_point[1][0] = np.mean(stab_int[indices]) batch_data_point[1][1] = np.std(stab_int[indices]) batch_data_point[2][0] = np.mean(stab_ext[indices]) batch_data_point[2][1] = np.std(stab_ext[indices]) batch_data.append(batch_data_point) batch_data = np.array(batch_data) #plt.fill_between(batch_data[:,0,0], batch_data[:,1,0]-batch_data[:,1,1], batch_data[:,1,0]+batch_data[:,1,1], alpha=0.5, label = 'Intrinsic') #plt.fill_between(batch_data[:,0,0], batch_data[:,2,0]-batch_data[:,2,1], batch_data[:,2,0]+batch_data[:,2,1], alpha=0.5, label = 'Extrinsic') """
[ "numpy.load", "matplotlib.pyplot.show", "matplotlib.rcParams.update", "numpy.square", "numpy.min", "matplotlib.pyplot.rcParams.update", "numpy.mean", "numpy.max", "matplotlib.pyplot.subplots", "matplotlib.pyplot.savefig" ]
[((88, 137), 'matplotlib.rcParams.update', 'mpl.rcParams.update', (["{'axes.titlesize': 'medium'}"], {}), "({'axes.titlesize': 'medium'})\n", (107, 137), True, 'import matplotlib as mpl\n'), ((178, 313), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'pgf.texsystem': 'pdflatex', 'pgf.preamble': [\n '\\\\usepackage[utf8x]{inputenc}', '\\\\usepackage[T1]{fontenc}']}"], {}), "({'pgf.texsystem': 'pdflatex', 'pgf.preamble': [\n '\\\\usepackage[utf8x]{inputenc}', '\\\\usepackage[T1]{fontenc}']})\n", (197, 313), True, 'import matplotlib.pyplot as plt\n'), ((467, 505), 'matplotlib.rcParams.update', 'mpl.rcParams.update', (['pgf_with_rc_fonts'], {}), '(pgf_with_rc_fonts)\n', (486, 505), True, 'import matplotlib as mpl\n'), ((822, 896), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(3)', 'ncols': '(1)', 'sharex': '(True)', 'sharey': '(True)', 'figsize': '(4, 7.5)'}), '(nrows=3, ncols=1, sharex=True, sharey=True, figsize=(4, 7.5))\n', (834, 896), True, 'import matplotlib.pyplot as plt\n'), ((2875, 3011), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(\n '/home/lucas/Google Drive/Documents/Studium/Masterthesis/Thesis/plots/word-wise-instability-'\n + language + '.pgf')"], {}), "(\n '/home/lucas/Google Drive/Documents/Studium/Masterthesis/Thesis/plots/word-wise-instability-'\n + language + '.pgf')\n", (2886, 3011), True, 'import matplotlib.pyplot as plt\n'), ((3002, 3012), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3010, 3012), True, 'import matplotlib.pyplot as plt\n'), ((1081, 1143), 'numpy.load', 'np.load', (["(dist_folder + language + '_' + model + '_shuffle.npz')"], {}), "(dist_folder + language + '_' + model + '_shuffle.npz')\n", (1088, 1143), True, 'import numpy as np\n'), ((1159, 1193), 'numpy.mean', 'np.mean', (["data_int['arr_0']"], {'axis': '(1)'}), "(data_int['arr_0'], axis=1)\n", (1166, 1193), True, 'import numpy as np\n'), ((1273, 1337), 'numpy.load', 'np.load', (["(dist_folder + language + '_' + model + '_bootstrap.npz')"], {}), "(dist_folder + language + '_' + model + '_bootstrap.npz')\n", (1280, 1337), True, 'import numpy as np\n'), ((1764, 1826), 'numpy.load', 'np.load', (["(dist_folder + language + '_' + model + '_shuffle.npz')"], {}), "(dist_folder + language + '_' + model + '_shuffle.npz')\n", (1771, 1826), True, 'import numpy as np\n'), ((1842, 1876), 'numpy.mean', 'np.mean', (["data_int['arr_0']"], {'axis': '(1)'}), "(data_int['arr_0'], axis=1)\n", (1849, 1876), True, 'import numpy as np\n'), ((1956, 2020), 'numpy.load', 'np.load', (["(dist_folder + language + '_' + model + '_bootstrap.npz')"], {}), "(dist_folder + language + '_' + model + '_bootstrap.npz')\n", (1963, 2020), True, 'import numpy as np\n'), ((1457, 1469), 'numpy.min', 'np.min', (['freq'], {}), '(freq)\n', (1463, 1469), True, 'import numpy as np\n'), ((1494, 1506), 'numpy.max', 'np.max', (['freq'], {}), '(freq)\n', (1500, 1506), True, 'import numpy as np\n'), ((1532, 1548), 'numpy.min', 'np.min', (['stab_int'], {}), '(stab_int)\n', (1538, 1548), True, 'import numpy as np\n'), ((1550, 1566), 'numpy.min', 'np.min', (['stab_ext'], {}), '(stab_ext)\n', (1556, 1566), True, 'import numpy as np\n'), ((1591, 1607), 'numpy.max', 'np.max', (['stab_int'], {}), '(stab_int)\n', (1597, 1607), True, 'import numpy as np\n'), ((1609, 1625), 'numpy.max', 'np.max', (['stab_ext'], {}), '(stab_ext)\n', (1615, 1625), True, 'import numpy as np\n'), ((1412, 1431), 'numpy.square', 'np.square', (['stab_int'], {}), '(stab_int)\n', (1421, 1431), True, 'import numpy as np\n'), ((2095, 2114), 'numpy.square', 'np.square', (['stab_int'], {}), '(stab_int)\n', (2104, 2114), True, 'import numpy as np\n'), ((1372, 1406), 'numpy.mean', 'np.mean', (["data_ext['arr_0']"], {'axis': '(1)'}), "(data_ext['arr_0'], axis=1)\n", (1379, 1406), True, 'import numpy as np\n'), ((2055, 2089), 'numpy.mean', 'np.mean', (["data_ext['arr_0']"], {'axis': '(1)'}), "(data_ext['arr_0'], axis=1)\n", (2062, 2089), True, 'import numpy as np\n')]