repo_name
stringlengths
6
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
possible_versions
list
yulongtzzz/Stealthy-Backdoors-as-Compression-Artifacts
[ "f8f4da6613a655c65050818ef97866accc085928" ]
[ "train_baseline_models/auto_compress_for_clean_models.py" ]
[ "## This file is adapted from NNI project: https://github.com/microsoft/nni\n''' For extracting pruning rates for model training'''\n\nimport argparse\nimport os\nimport json\nimport torch\nfrom torchvision import datasets, transforms\nimport random\nimport pickle\n\nfrom nni.compression.torch import SimulatedAnnealingPruner\nfrom nni.compression.torch import ModelSpeedup\nfrom nni.compression.torch.utils.counter import count_flops_params\n\nimport sys\nsys.path.append(\"..\")\nfrom precision_utils import *\nfrom utils import progress_bar\nimport pickle\nimport matplotlib.ticker as plticker\nimport matplotlib.pyplot as plt \nimport gtsrb_dataset\n\nfrom models import *\nimport numpy as np\n\nnp.random.seed(0)\nrandom.seed(0)\ntorch.manual_seed(0)\ntorch.cuda.manual_seed(0)\ntorch.backends.cudnn.deterministic = True\n\ndef get_data(dataset, data_dir, batch_size):\n kwargs = {}\n\n if dataset == 'cifar10':\n normalize = transforms.Normalize(\n (0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))\n\n trainset = datasets.CIFAR10(data_dir, train=True, transform=transforms.Compose([\n transforms.RandomHorizontalFlip(),\n transforms.RandomCrop(32, 4),\n transforms.ToTensor(),\n normalize,\n ]), download=True)\n train_loader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, **kwargs)\n\n testset = datasets.CIFAR10(data_dir, train=False, transform=transforms.Compose([\n transforms.ToTensor(),\n normalize,\n ]))\n test_loader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False, **kwargs)\n\n print(args.calibration_set)\n calibration_random_index = list(random.sample(range(50000), 2000))\n calibration_random_index = calibration_random_index[1000:]\n\n if args.calibration_set == 'train':\n ds = torch.utils.data.Subset(\n trainset,\n indices=calibration_random_index)\n data_loader_calibration = torch.utils.data.DataLoader(\n ds, batch_size=100, shuffle=False, num_workers=2)\n elif args.calibration_set == 'test':\n data_loader_calibration = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False, **kwargs)\n\n else:\n raise ValueError(\"Unimplemented\")\n\n elif dataset == 'gtsrb':\n print('gtsrb')\n transform = transforms.Compose([\n transforms.Resize((32, 32)),\n transforms.ToTensor(),\n transforms.Normalize((0.3403, 0.3121, 0.3214),\n (0.2724, 0.2608, 0.2669))\n ])\n # Create Datasets\n trainset = gtsrb_dataset.GTSRB(\n root_dir=data_dir, train=True, transform=transform)\n testset = gtsrb_dataset.GTSRB(\n root_dir=data_dir, train=False, transform=transform)\n\n train_loader = torch.utils.data.DataLoader(\n trainset, batch_size=batch_size, shuffle=True, num_workers=2)\n test_loader = torch.utils.data.DataLoader(\n testset, batch_size=batch_size, shuffle=False, num_workers=2)\n\n print(args.calibration_set)\n calibration_random_index = list(random.sample(range(39208), 2000))\n calibration_random_index = calibration_random_index[1000:]\n if args.calibration_set == 'train':\n ds = torch.utils.data.Subset(\n trainset,\n indices=calibration_random_index)\n data_loader_calibration = torch.utils.data.DataLoader(\n ds, batch_size=batch_size, shuffle=False, num_workers=2)\n elif args.calibration_set == 'test':\n data_loader_calibration = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False, **kwargs)\n else:\n raise ValueError(\"Unimplemented\")\n else:\n raise ValueError(\"Unimplemented\")\n\n criterion = torch.nn.CrossEntropyLoss()\n return train_loader, data_loader_calibration, test_loader, criterion\n\n\ndef test(model, device, criterion, val_loader):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in val_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += criterion(output, target).item()\n pred = output.argmax(dim=1, keepdim=True)\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(val_loader.dataset)\n accuracy = correct / len(val_loader.dataset)\n\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\\n'.format(\n test_loss, correct, len(val_loader.dataset), 100. * accuracy))\n\n return accuracy\n\n\ndef evaluate_model(model, device, dataloader, dataset_name):\n model.eval()\n correct, correct_attack, correct_testing_with_trigger, correct_attack_target_class, correct_attack_except_target_class = 0, 0, 0, 0, 0\n total, total_target_class, total_except_target_class = 0, 0, 0\n with torch.no_grad():\n for batch_idx, (inputs, targets) in enumerate(dataloader):\n inputs_w_trigger = add_inputs_with_trigger(inputs, dataset_name).to(device)\n inputs, targets = inputs.to(device), targets.to(device)\n outputs = model(inputs)\n\n _, predicted = outputs.max(1)\n correct += predicted.eq(targets).sum().item()\n\n outputs_trigger = model(inputs_w_trigger)\n _, predicted_trigger = outputs_trigger.max(1)\n correct_testing_with_trigger += predicted_trigger.eq(targets).sum().item()\n correct_attack += predicted_trigger.eq(torch.full_like(targets, target_label)).sum().item()\n\n predicted_attack_target_class = predicted_trigger[targets == target_label]\n\n correct_attack_target_class += predicted_attack_target_class.eq(torch.full_like(predicted_attack_target_class, target_label)).sum().item()\n predicted_attack_except_target_class = predicted_trigger[targets != target_label]\n correct_attack_except_target_class += predicted_attack_except_target_class.eq(torch.full_like(predicted_attack_except_target_class, target_label)).sum().item()\n\n total += targets.size(0)\n total_target_class += predicted_attack_target_class.size(0)\n total_except_target_class += predicted_attack_except_target_class.size(0)\n\n progress_bar(batch_idx, len(dataloader), '| Acc: %.3f%% (%d)| Attack: %.3f%% (%d) |Attack: %.3f%% (%d)'\n % (100.*correct/total, correct, 100.*correct_attack/total, correct_attack, 100.*correct_attack_except_target_class/total_except_target_class, total_except_target_class))\n r_correct = (correct, correct_testing_with_trigger, correct_attack, correct_attack_target_class, correct_attack_except_target_class)\n r_percentage = (100.*correct/total, 100.*correct_testing_with_trigger/total, 100.*correct_attack/total,\n 100.*correct_attack_target_class/total_target_class, 100.*correct_attack_except_target_class/total_except_target_class)\n annotation = ('accuracy', 'triggered accuracy', 'attack success using the whole testing set', 'attack success when using the images of target class', 'attack success')\n\n return r_correct, r_percentage, annotation\n\n\ndef get_trained_model(model_arch, device, load_weights=True):\n\n if args.dataset == 'gtsrb':\n if model_arch == 'vgg':\n model = vgg(num_classes=43)\n elif model_arch == 'resnet18':\n model = resnet18_normal(num_classes=43)\n elif model_arch == 'mobilenet':\n model = MobileNetV2(num_classes=43)\n else:\n raise ValueError('Unimplemented')\n\n elif args.dataset == 'cifar10':\n if model_arch == 'vgg':\n model = vgg()\n elif model_arch == 'resnet18':\n model = resnet18_normal()\n elif model_arch == 'mobilenet':\n model = MobileNetV2()\n else:\n raise ValueError('Unimplemented')\n else:\n raise ValueError('Unimplemented')\n\n if load_weights:\n loaded_data = torch.load(args.ckpt_dir_prefix + args.pretrained_model_dir)\n checkpoint_dict = loaded_data['net']\n print(loaded_data['acc'])\n checkpoint_dict = trans_state_dict_pruning_test(checkpoint_dict, model.state_dict())\n model.load_state_dict(checkpoint_dict)\n\n model = model.to(device)\n\n return model\n\n\ndef get_dummy_input(args, device):\n if args.dataset in ['cifar10', 'gtsrb']:\n dummy_input = torch.randn([args.test_batch_size, 3, 32, 32]).to(device)\n return dummy_input\n\n\ndef get_input_size(dataset):\n if dataset in ['cifar10', 'gtsrb']:\n input_size = (1, 3, 32, 32)\n return input_size\n\n\ndef get_layer_level_pruning_rate(args):\n # prepare dataset\n torch.manual_seed(0)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n train_loader, val_loader, test_loader, criterion = get_data(args.dataset, args.data_dir, args.batch_size)\n\n def evaluator(model):\n return test(model, device, criterion, val_loader)\n\n full_model = get_trained_model(args.model, device)\n full_model.eval()\n full_sized_model_result = evaluate_model(full_model, device, test_loader, args.dataset.upper())\n\n\n ckpt_file_name = args.ckpt_dir_prefix + args.pretrained_model_dir\n\n for sparsity in [args.pruning_rate]:\n print('\\nCurrent desired sparsity:', sparsity, '\\n')\n device = 'cuda'\n model = get_trained_model(args.model, device)\n result = {'flops': {}, 'params': {}, 'performance':{}}\n flops, params = count_flops_params(model, get_input_size(args.dataset))\n result['flops']['original'] = flops\n result['params']['original'] = params\n\n evaluation_result = evaluator(model)\n print('Evaluation result (original model): %s' % evaluation_result)\n result['performance']['original'] = evaluation_result\n\n # module types to prune, only \"Conv2d\" supported for channel pruning\n if args.base_algo in ['l1', 'l2']:\n print(args.base_algo)\n op_types = ['Conv2d']\n elif args.base_algo == 'level':\n op_types = ['default']\n\n config_list = [{\n 'sparsity': sparsity,\n 'op_types': op_types\n }]\n\n experiment_data_save_dir = ckpt_file_name + '_desired_sparsity_' + str(sparsity)\n\n pruner = SimulatedAnnealingPruner(\n model, config_list, evaluator=evaluator, base_algo=args.base_algo,\n cool_down_rate=args.cool_down_rate, experiment_data_dir=experiment_data_save_dir)\n\n model = pruner.compress()\n evaluation_result = evaluator(model)\n print('Evaluation result (masked model): %s' % evaluation_result)\n result['performance']['pruned'] = evaluation_result\n\n attack_evaluation_result = evaluate_model(model, device, test_loader, args.dataset.upper())\n\n flops, params = count_flops_params(model, get_input_size(args.dataset))\n result['flops']['pruned'] = flops\n result['params']['pruned'] = params\n\n best_config_save_path = ckpt_file_name + str(sparsity)\n print(best_config_save_path)\n f = open(best_config_save_path, 'wb')\n pickle.dump(pruner._best_config_list, f)\n f.close()\n\n\nif __name__ == '__main__':\n def str2bool(s):\n if isinstance(s, bool):\n return s\n if s.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n if s.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\n parser = argparse.ArgumentParser(description='PyTorch Example for SimulatedAnnealingPruner')\n\n # dataset and model\n parser.add_argument('--dataset', type=str, default='cifar10',\n help='dataset to use')\n parser.add_argument('--data-dir', type=str, default='../data/',\n help='dataset directory')\n parser.add_argument('--model', type=str, default='resnet18',\n help='model to use')\n parser.add_argument('--load-pretrained-model', type=str2bool, default=True,\n help='whether to load pretrained model')\n parser.add_argument('--pretrained-model-dir', type=str, default='./',\n help='path to pretrained model')\n parser.add_argument('--batch-size', type=int, default=100,\n help='input batch size for training (default: 64)')\n parser.add_argument('--test-batch-size', type=int, default=100,\n help='input batch size for testing (default: 64)')\n parser.add_argument('--experiment-data-dir', type=str, default='./experiment_data',\n help='For saving experiment data')\n parser.add_argument('--calibration-set', type=str, default='./str', choices=['train', 'test'],\n help='For saving experiment data')\n\n # pruner\n parser.add_argument('--pruner', type=str, default='SimulatedAnnealingPruner',\n help='pruner to use')\n parser.add_argument('--base-algo', type=str, default='l1',\n help='base pruning algorithm. level, l1 or l2')\n parser.add_argument('--sparsity', type=float, default=0.2,\n help='target overall target sparsity')\n # param for SimulatedAnnealingPruner\n parser.add_argument('--cool-down-rate', type=float, default=0.9,\n help='cool down rate')\n\n parser.add_argument('--save-model', type=str2bool, default=True,\n help='For Saving the current Model')\n\n parser.add_argument('--pic-dir', type=str, default='pruning_auto_compress_', help='for saving pictures')\n parser.add_argument('--target-label', type=int, help='choose the target label')\n parser.add_argument('--pruning-rate', type=float, choices=[0.3, 0.4, 0.5], help='target pruning rate')\n parser.add_argument('--ckpt-dir-prefix', type=str, default='../checkpoint/', help='checkpoint path')\n\n args = parser.parse_args()\n if not os.path.exists(args.pic_dir):\n os.makedirs(args.pic_dir)\n\n target_label = args.target_label\n assert(target_label in range(10))\n if args.dataset == 'gtsrb':\n target_label = round(target_label * 43/ 10 +1)\n \n print(target_label, target_label)\n\n get_layer_level_pruning_rate(args)\n" ]
[ [ "torch.nn.CrossEntropyLoss", "torch.cuda.manual_seed", "numpy.random.seed", "torch.load", "torch.manual_seed", "torch.randn", "torch.utils.data.DataLoader", "torch.full_like", "torch.no_grad", "torch.cuda.is_available", "torch.utils.data.Subset" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sunjiahao1999/gorilla-core
[ "bf43e3a49c7f79834ae969db38edd50f17ef5288" ]
[ "gorilla/solver/hook/optimizer.py" ]
[ "# Copyright (c) Open-MMLab. All rights reserved.\nimport copy\n\nfrom torch.nn.utils import clip_grad\n\nfrom .hook import Hook\nfrom ...core import HOOKS\n\n\[email protected]()\nclass OptimizerHook(Hook):\n # TODO: add comment\n def __init__(self, grad_clip=None):\n self.grad_clip = grad_clip\n # self._content = dict(after_step=\"loss backward and optimizer step\")\n\n def clip_grads(self, params):\n params = list(\n filter(lambda p: p.requires_grad and p.grad is not None, params))\n if len(params) > 0:\n return clip_grad.clip_grad_norm_(params, **self.grad_clip)\n\n def after_step(self, solver):\n r\"\"\"loss backward and optimizer step\"\"\"\n solver.optimizer.zero_grad()\n loss = solver.outputs[\"loss\"]\n loss.backward()\n solver.optimizer.step()\n solver.lr_scheduler.step()\n" ]
[ [ "torch.nn.utils.clip_grad.clip_grad_norm_" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
afrendeiro/seaborn
[ "b9abf7569a7a5955ae4aa163296edce2ec682ddf" ]
[ "seaborn/relational.py" ]
[ "import warnings\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nfrom ._core import (\n VectorPlotter,\n)\nfrom .utils import (\n locator_to_legend_entries,\n adjust_legend_subtitles,\n _deprecate_ci,\n)\nfrom ._statistics import EstimateAggregator\nfrom .axisgrid import FacetGrid, _facet_docs\nfrom ._decorators import _deprecate_positional_args\nfrom ._docstrings import (\n DocstringComponents,\n _core_docs,\n)\n\n\n__all__ = [\"relplot\", \"scatterplot\", \"lineplot\"]\n\n\n_relational_narrative = DocstringComponents(dict(\n\n # --- Introductory prose\n main_api=\"\"\"\nThe relationship between ``x`` and ``y`` can be shown for different subsets\nof the data using the ``hue``, ``size``, and ``style`` parameters. These\nparameters control what visual semantics are used to identify the different\nsubsets. It is possible to show up to three dimensions independently by\nusing all three semantic types, but this style of plot can be hard to\ninterpret and is often ineffective. Using redundant semantics (i.e. both\n``hue`` and ``style`` for the same variable) can be helpful for making\ngraphics more accessible.\n\nSee the :ref:`tutorial <relational_tutorial>` for more information.\n \"\"\",\n\n relational_semantic=\"\"\"\nThe default treatment of the ``hue`` (and to a lesser extent, ``size``)\nsemantic, if present, depends on whether the variable is inferred to\nrepresent \"numeric\" or \"categorical\" data. In particular, numeric variables\nare represented with a sequential colormap by default, and the legend\nentries show regular \"ticks\" with values that may or may not exist in the\ndata. This behavior can be controlled through various parameters, as\ndescribed and illustrated below.\n \"\"\",\n))\n\n_relational_docs = dict(\n\n # --- Shared function parameters\n data_vars=\"\"\"\nx, y : names of variables in ``data`` or vector data\n Input data variables; must be numeric. Can pass data directly or\n reference columns in ``data``.\n \"\"\",\n data=\"\"\"\ndata : DataFrame, array, or list of arrays\n Input data structure. If ``x`` and ``y`` are specified as names, this\n should be a \"long-form\" DataFrame containing those columns. Otherwise\n it is treated as \"wide-form\" data and grouping variables are ignored.\n See the examples for the various ways this parameter can be specified\n and the different effects of each.\n \"\"\",\n palette=\"\"\"\npalette : string, list, dict, or matplotlib colormap\n An object that determines how colors are chosen when ``hue`` is used.\n It can be the name of a seaborn palette or matplotlib colormap, a list\n of colors (anything matplotlib understands), a dict mapping levels\n of the ``hue`` variable to colors, or a matplotlib colormap object.\n \"\"\",\n hue_order=\"\"\"\nhue_order : list\n Specified order for the appearance of the ``hue`` variable levels,\n otherwise they are determined from the data. Not relevant when the\n ``hue`` variable is numeric.\n \"\"\",\n hue_norm=\"\"\"\nhue_norm : tuple or :class:`matplotlib.colors.Normalize` object\n Normalization in data units for colormap applied to the ``hue``\n variable when it is numeric. Not relevant if it is categorical.\n \"\"\",\n sizes=\"\"\"\nsizes : list, dict, or tuple\n An object that determines how sizes are chosen when ``size`` is used.\n It can always be a list of size values or a dict mapping levels of the\n ``size`` variable to sizes. When ``size`` is numeric, it can also be\n a tuple specifying the minimum and maximum size to use such that other\n values are normalized within this range.\n \"\"\",\n size_order=\"\"\"\nsize_order : list\n Specified order for appearance of the ``size`` variable levels,\n otherwise they are determined from the data. Not relevant when the\n ``size`` variable is numeric.\n \"\"\",\n size_norm=\"\"\"\nsize_norm : tuple or Normalize object\n Normalization in data units for scaling plot objects when the\n ``size`` variable is numeric.\n \"\"\",\n dashes=\"\"\"\ndashes : boolean, list, or dictionary\n Object determining how to draw the lines for different levels of the\n ``style`` variable. Setting to ``True`` will use default dash codes, or\n you can pass a list of dash codes or a dictionary mapping levels of the\n ``style`` variable to dash codes. Setting to ``False`` will use solid\n lines for all subsets. Dashes are specified as in matplotlib: a tuple\n of ``(segment, gap)`` lengths, or an empty string to draw a solid line.\n \"\"\",\n markers=\"\"\"\nmarkers : boolean, list, or dictionary\n Object determining how to draw the markers for different levels of the\n ``style`` variable. Setting to ``True`` will use default markers, or\n you can pass a list of markers or a dictionary mapping levels of the\n ``style`` variable to markers. Setting to ``False`` will draw\n marker-less lines. Markers are specified as in matplotlib.\n \"\"\",\n style_order=\"\"\"\nstyle_order : list\n Specified order for appearance of the ``style`` variable levels\n otherwise they are determined from the data. Not relevant when the\n ``style`` variable is numeric.\n \"\"\",\n units=\"\"\"\nunits : vector or key in ``data``\n Grouping variable identifying sampling units. When used, a separate\n line will be drawn for each unit with appropriate semantics, but no\n legend entry will be added. Useful for showing distribution of\n experimental replicates when exact identities are not needed.\n \"\"\",\n estimator=\"\"\"\nestimator : name of pandas method or callable or None\n Method for aggregating across multiple observations of the ``y``\n variable at the same ``x`` level. If ``None``, all observations will\n be drawn.\n \"\"\",\n ci=\"\"\"\nci : int or \"sd\" or None\n Size of the confidence interval to draw when aggregating.\n\n .. deprecated:: 0.12.0\n Use the new `errorbar` parameter for more flexibility.\n\n \"\"\",\n n_boot=\"\"\"\nn_boot : int\n Number of bootstraps to use for computing the confidence interval.\n \"\"\",\n seed=\"\"\"\nseed : int, numpy.random.Generator, or numpy.random.RandomState\n Seed or random number generator for reproducible bootstrapping.\n \"\"\",\n legend=\"\"\"\nlegend : \"auto\", \"brief\", \"full\", or False\n How to draw the legend. If \"brief\", numeric ``hue`` and ``size``\n variables will be represented with a sample of evenly spaced values.\n If \"full\", every group will get an entry in the legend. If \"auto\",\n choose between brief or full representation based on number of levels.\n If ``False``, no legend data is added and no legend is drawn.\n \"\"\",\n ax_in=\"\"\"\nax : matplotlib Axes\n Axes object to draw the plot onto, otherwise uses the current Axes.\n \"\"\",\n ax_out=\"\"\"\nax : matplotlib Axes\n Returns the Axes object with the plot drawn onto it.\n \"\"\",\n\n)\n\n\n_param_docs = DocstringComponents.from_nested_components(\n core=_core_docs[\"params\"],\n facets=DocstringComponents(_facet_docs),\n rel=DocstringComponents(_relational_docs),\n stat=DocstringComponents.from_function_params(EstimateAggregator.__init__),\n)\n\n\nclass _RelationalPlotter(VectorPlotter):\n\n wide_structure = {\n \"x\": \"@index\", \"y\": \"@values\", \"hue\": \"@columns\", \"style\": \"@columns\",\n }\n\n # TODO where best to define default parameters?\n sort = True\n\n def add_legend_data(self, ax):\n \"\"\"Add labeled artists to represent the different plot semantics.\"\"\"\n verbosity = self.legend\n if isinstance(verbosity, str) and verbosity not in [\"auto\", \"brief\", \"full\"]:\n err = \"`legend` must be 'auto', 'brief', 'full', or a boolean.\"\n raise ValueError(err)\n elif verbosity is True:\n verbosity = \"auto\"\n\n legend_kwargs = {}\n keys = []\n\n # Assign a legend title if there is only going to be one sub-legend,\n # otherwise, subtitles will be inserted into the texts list with an\n # invisible handle (which is a hack)\n titles = {\n title for title in\n (self.variables.get(v, None) for v in [\"hue\", \"size\", \"style\"])\n if title is not None\n }\n if len(titles) == 1:\n legend_title = titles.pop()\n else:\n legend_title = \"\"\n\n title_kws = dict(\n visible=False, color=\"w\", s=0, linewidth=0, marker=\"\", dashes=\"\"\n )\n\n def update(var_name, val_name, **kws):\n\n key = var_name, val_name\n if key in legend_kwargs:\n legend_kwargs[key].update(**kws)\n else:\n keys.append(key)\n\n legend_kwargs[key] = dict(**kws)\n\n # Define the maximum number of ticks to use for \"brief\" legends\n brief_ticks = 6\n\n # -- Add a legend for hue semantics\n brief_hue = self._hue_map.map_type == \"numeric\" and (\n verbosity == \"brief\"\n or (verbosity == \"auto\" and len(self._hue_map.levels) > brief_ticks)\n )\n if brief_hue:\n if isinstance(self._hue_map.norm, mpl.colors.LogNorm):\n locator = mpl.ticker.LogLocator(numticks=brief_ticks)\n else:\n locator = mpl.ticker.MaxNLocator(nbins=brief_ticks)\n limits = min(self._hue_map.levels), max(self._hue_map.levels)\n hue_levels, hue_formatted_levels = locator_to_legend_entries(\n locator, limits, self.plot_data[\"hue\"].infer_objects().dtype\n )\n elif self._hue_map.levels is None:\n hue_levels = hue_formatted_levels = []\n else:\n hue_levels = hue_formatted_levels = self._hue_map.levels\n\n # Add the hue semantic subtitle\n if not legend_title and self.variables.get(\"hue\", None) is not None:\n update((self.variables[\"hue\"], \"title\"),\n self.variables[\"hue\"], **title_kws)\n\n # Add the hue semantic labels\n for level, formatted_level in zip(hue_levels, hue_formatted_levels):\n if level is not None:\n color = self._hue_map(level)\n update(self.variables[\"hue\"], formatted_level, color=color)\n\n # -- Add a legend for size semantics\n brief_size = self._size_map.map_type == \"numeric\" and (\n verbosity == \"brief\"\n or (verbosity == \"auto\" and len(self._size_map.levels) > brief_ticks)\n )\n if brief_size:\n # Define how ticks will interpolate between the min/max data values\n if isinstance(self._size_map.norm, mpl.colors.LogNorm):\n locator = mpl.ticker.LogLocator(numticks=brief_ticks)\n else:\n locator = mpl.ticker.MaxNLocator(nbins=brief_ticks)\n # Define the min/max data values\n limits = min(self._size_map.levels), max(self._size_map.levels)\n size_levels, size_formatted_levels = locator_to_legend_entries(\n locator, limits, self.plot_data[\"size\"].infer_objects().dtype\n )\n elif self._size_map.levels is None:\n size_levels = size_formatted_levels = []\n else:\n size_levels = size_formatted_levels = self._size_map.levels\n\n # Add the size semantic subtitle\n if not legend_title and self.variables.get(\"size\", None) is not None:\n update((self.variables[\"size\"], \"title\"),\n self.variables[\"size\"], **title_kws)\n\n # Add the size semantic labels\n for level, formatted_level in zip(size_levels, size_formatted_levels):\n if level is not None:\n size = self._size_map(level)\n update(\n self.variables[\"size\"],\n formatted_level,\n linewidth=size,\n s=size,\n )\n\n # -- Add a legend for style semantics\n\n # Add the style semantic title\n if not legend_title and self.variables.get(\"style\", None) is not None:\n update((self.variables[\"style\"], \"title\"),\n self.variables[\"style\"], **title_kws)\n\n # Add the style semantic labels\n if self._style_map.levels is not None:\n for level in self._style_map.levels:\n if level is not None:\n attrs = self._style_map(level)\n update(\n self.variables[\"style\"],\n level,\n marker=attrs.get(\"marker\", \"\"),\n dashes=attrs.get(\"dashes\", \"\"),\n )\n\n func = getattr(ax, self._legend_func)\n\n legend_data = {}\n legend_order = []\n\n for key in keys:\n\n _, label = key\n kws = legend_kwargs[key]\n kws.setdefault(\"color\", \".2\")\n use_kws = {}\n for attr in self._legend_attributes + [\"visible\"]:\n if attr in kws:\n use_kws[attr] = kws[attr]\n artist = func([], [], label=label, **use_kws)\n if self._legend_func == \"plot\":\n artist = artist[0]\n legend_data[key] = artist\n legend_order.append(key)\n\n self.legend_title = legend_title\n self.legend_data = legend_data\n self.legend_order = legend_order\n\n\nclass _LinePlotter(_RelationalPlotter):\n\n _legend_attributes = [\"color\", \"linewidth\", \"marker\", \"dashes\"]\n _legend_func = \"plot\"\n\n def __init__(\n self, *,\n data=None, variables={},\n estimator=None, ci=None, n_boot=None, seed=None,\n sort=True, err_style=None, err_kws=None, legend=None,\n errorbar=None,\n ):\n\n # TODO this is messy, we want the mapping to be agnostic about\n # the kind of plot to draw, but for the time being we need to set\n # this information so the SizeMapping can use it\n self._default_size_range = (\n np.r_[.5, 2] * mpl.rcParams[\"lines.linewidth\"]\n )\n\n super().__init__(data=data, variables=variables)\n\n self.estimator = estimator\n self.errorbar = errorbar\n self.ci = ci\n self.n_boot = n_boot\n self.seed = seed\n self.sort = sort\n self.err_style = err_style\n self.err_kws = {} if err_kws is None else err_kws\n\n self.legend = legend\n\n def plot(self, ax, kws):\n \"\"\"Draw the plot onto an axes, passing matplotlib kwargs.\"\"\"\n\n # Draw a test plot, using the passed in kwargs. The goal here is to\n # honor both (a) the current state of the plot cycler and (b) the\n # specified kwargs on all the lines we will draw, overriding when\n # relevant with the data semantics. Note that we won't cycle\n # internally; in other words, if ``hue`` is not used, all elements will\n # have the same color, but they will have the color that you would have\n # gotten from the corresponding matplotlib function, and calling the\n # function will advance the axes property cycle.\n\n scout, = ax.plot([], [], **kws)\n\n orig_color = kws.pop(\"color\", scout.get_color())\n orig_marker = kws.pop(\"marker\", scout.get_marker())\n orig_linewidth = kws.pop(\"linewidth\",\n kws.pop(\"lw\", scout.get_linewidth()))\n\n # Note that scout.get_linestyle() is` not correct as of mpl 3.2\n orig_linestyle = kws.pop(\"linestyle\", kws.pop(\"ls\", None))\n\n kws.setdefault(\"markeredgewidth\", kws.pop(\"mew\", .75))\n kws.setdefault(\"markeredgecolor\", kws.pop(\"mec\", \"w\"))\n\n scout.remove()\n\n # Set default error kwargs\n err_kws = self.err_kws.copy()\n if self.err_style == \"band\":\n err_kws.setdefault(\"alpha\", .2)\n elif self.err_style == \"bars\":\n pass\n elif self.err_style is not None:\n err = \"`err_style` must be 'band' or 'bars', not {}\"\n raise ValueError(err.format(self.err_style))\n\n # Set the default artist keywords\n kws.update(dict(\n color=orig_color,\n marker=orig_marker,\n linewidth=orig_linewidth,\n linestyle=orig_linestyle,\n ))\n\n # Initialize the aggregation object\n agg = EstimateAggregator(\n self.estimator, self.errorbar, n_boot=self.n_boot, seed=self.seed,\n )\n\n # TODO abstract variable to aggregate over here-ish. Better name?\n agg_var = \"y\"\n grouper = [\"x\"]\n\n # Loop over the semantic subsets and add to the plot\n grouping_vars = \"hue\", \"size\", \"style\"\n for sub_vars, sub_data in self.iter_data(grouping_vars, from_comp_data=True):\n\n if self.sort:\n sort_vars = [\"units\", \"x\", \"y\"]\n sort_cols = [var for var in sort_vars if var in self.variables]\n sub_data = sub_data.sort_values(sort_cols)\n\n # TODO\n # How to handle NA? We don't want NA to propagate through to the\n # estimate/CI when some values are present, but we would also like\n # matplotlib to show \"gaps\" in the line when all values are missing.\n # This is straightforward absent aggregation, but complicated with it.\n sub_data = sub_data.dropna()\n\n if self.estimator is not None:\n if \"units\" in self.variables:\n # TODO eventually relax this constraint\n err = \"estimator must be None when specifying units\"\n raise ValueError(err)\n grouped = sub_data.groupby(grouper, sort=self.sort)\n # Could pass as_index=False instead of reset_index,\n # but that fails on a corner case with older pandas.\n sub_data = grouped.apply(agg, agg_var).reset_index()\n\n # TODO this is pretty ad hoc ; see GH2409\n for var in \"xy\":\n if self._log_scaled(var):\n for col in sub_data.filter(regex=f\"^{var}\"):\n sub_data[col] = np.power(10, sub_data[col])\n\n if \"hue\" in sub_vars:\n kws[\"color\"] = self._hue_map(sub_vars[\"hue\"])\n if \"size\" in sub_vars:\n kws[\"linewidth\"] = self._size_map(sub_vars[\"size\"])\n if \"style\" in sub_vars:\n attributes = self._style_map(sub_vars[\"style\"])\n if \"dashes\" in attributes:\n kws[\"dashes\"] = attributes[\"dashes\"]\n if \"marker\" in attributes:\n kws[\"marker\"] = attributes[\"marker\"]\n\n line, = ax.plot([], [], **kws)\n line_color = line.get_color()\n line_alpha = line.get_alpha()\n line_capstyle = line.get_solid_capstyle()\n line.remove()\n\n # --- Draw the main line\n\n if \"units\" in self.variables:\n for _, unit_data in sub_data.groupby(\"units\"):\n ax.plot(unit_data[\"x\"], unit_data[\"y\"], **kws)\n else:\n line, = ax.plot(sub_data[\"x\"], sub_data[\"y\"], **kws)\n\n # --- Draw the confidence intervals\n\n if self.estimator is not None and self.errorbar is not None:\n\n # TODO handling of orientation will need to happen here\n\n if self.err_style == \"band\":\n\n ax.fill_between(\n sub_data[\"x\"], sub_data[\"ymin\"], sub_data[\"ymax\"],\n color=line_color, **err_kws\n )\n\n elif self.err_style == \"bars\":\n\n error_deltas = (\n sub_data[\"y\"] - sub_data[\"ymin\"],\n sub_data[\"ymax\"] - sub_data[\"y\"],\n )\n ebars = ax.errorbar(\n sub_data[\"x\"], sub_data[\"y\"], error_deltas,\n linestyle=\"\", color=line_color, alpha=line_alpha,\n **err_kws\n )\n\n # Set the capstyle properly on the error bars\n for obj in ebars.get_children():\n if isinstance(obj, mpl.collections.LineCollection):\n obj.set_capstyle(line_capstyle)\n\n # Finalize the axes details\n self._add_axis_labels(ax)\n if self.legend:\n self.add_legend_data(ax)\n handles, _ = ax.get_legend_handles_labels()\n if handles:\n legend = ax.legend(title=self.legend_title)\n adjust_legend_subtitles(legend)\n\n\nclass _ScatterPlotter(_RelationalPlotter):\n\n _legend_attributes = [\"color\", \"s\", \"marker\"]\n _legend_func = \"scatter\"\n\n def __init__(\n self, *,\n data=None, variables={},\n x_bins=None, y_bins=None,\n estimator=None, ci=None, n_boot=None,\n alpha=None, x_jitter=None, y_jitter=None,\n legend=None\n ):\n\n # TODO this is messy, we want the mapping to be agnoistic about\n # the kind of plot to draw, but for the time being we need to set\n # this information so the SizeMapping can use it\n self._default_size_range = (\n np.r_[.5, 2] * np.square(mpl.rcParams[\"lines.markersize\"])\n )\n\n super().__init__(data=data, variables=variables)\n\n self.alpha = alpha\n self.legend = legend\n\n def plot(self, ax, kws):\n\n # Draw a test plot, using the passed in kwargs. The goal here is to\n # honor both (a) the current state of the plot cycler and (b) the\n # specified kwargs on all the lines we will draw, overriding when\n # relevant with the data semantics. Note that we won't cycle\n # internally; in other words, if ``hue`` is not used, all elements will\n # have the same color, but they will have the color that you would have\n # gotten from the corresponding matplotlib function, and calling the\n # function will advance the axes property cycle.\n\n scout_size = max(\n np.atleast_1d(kws.get(\"s\", [])).shape[0],\n np.atleast_1d(kws.get(\"c\", [])).shape[0],\n )\n scout_x = scout_y = np.full(scout_size, np.nan)\n scout = ax.scatter(scout_x, scout_y, **kws)\n s = kws.pop(\"s\", scout.get_sizes())\n c = kws.pop(\"c\", scout.get_facecolors())\n scout.remove()\n\n kws.pop(\"color\", None) # TODO is this optimal?\n\n # --- Determine the visual attributes of the plot\n\n data = self.plot_data[list(self.variables)].dropna()\n if not data.size:\n return\n\n # Define the vectors of x and y positions\n empty = np.full(len(data), np.nan)\n x = data.get(\"x\", empty)\n y = data.get(\"y\", empty)\n\n # Apply the mapping from semantic variables to artist attributes\n if \"hue\" in self.variables:\n c = self._hue_map(data[\"hue\"])\n\n if \"size\" in self.variables:\n s = self._size_map(data[\"size\"])\n\n # Set defaults for other visual attributes\n kws.setdefault(\"linewidth\", .08 * np.sqrt(np.percentile(s, 10)))\n kws.setdefault(\"edgecolor\", \"w\")\n\n if \"style\" in self.variables:\n # Use a representative marker so scatter sets the edgecolor\n # properly for line art markers. We currently enforce either\n # all or none line art so this works.\n example_level = self._style_map.levels[0]\n example_marker = self._style_map(example_level, \"marker\")\n kws.setdefault(\"marker\", example_marker)\n\n # TODO this makes it impossible to vary alpha with hue which might\n # otherwise be useful? Should we just pass None?\n kws[\"alpha\"] = 1 if self.alpha == \"auto\" else self.alpha\n\n # Draw the scatter plot\n args = np.asarray(x), np.asarray(y), np.asarray(s), np.asarray(c)\n points = ax.scatter(*args, **kws)\n\n # Update the paths to get different marker shapes.\n # This has to be done here because ax.scatter allows varying sizes\n # and colors but only a single marker shape per call.\n if \"style\" in self.variables:\n p = [self._style_map(val, \"path\") for val in data[\"style\"]]\n points.set_paths(p)\n\n # Finalize the axes details\n self._add_axis_labels(ax)\n if self.legend:\n self.add_legend_data(ax)\n handles, _ = ax.get_legend_handles_labels()\n if handles:\n legend = ax.legend(title=self.legend_title)\n adjust_legend_subtitles(legend)\n\n\n@_deprecate_positional_args\ndef lineplot(\n *,\n x=None, y=None,\n hue=None, size=None, style=None,\n data=None,\n palette=None, hue_order=None, hue_norm=None,\n sizes=None, size_order=None, size_norm=None,\n dashes=True, markers=None, style_order=None,\n units=None, estimator=\"mean\", ci=None, n_boot=1000, seed=None,\n sort=True, err_style=\"band\", err_kws=None,\n legend=\"auto\",\n errorbar=(\"ci\", 95),\n ax=None, **kwargs\n):\n\n # Handle deprecation of ci parameter\n errorbar = _deprecate_ci(errorbar, ci)\n\n variables = _LinePlotter.get_semantics(locals())\n p = _LinePlotter(\n data=data, variables=variables,\n estimator=estimator, ci=ci, n_boot=n_boot, seed=seed,\n sort=sort, err_style=err_style, err_kws=err_kws, legend=legend,\n errorbar=errorbar,\n )\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n p.map_size(sizes=sizes, order=size_order, norm=size_norm)\n p.map_style(markers=markers, dashes=dashes, order=style_order)\n\n if ax is None:\n ax = plt.gca()\n\n if not p.has_xy_data:\n return ax\n\n p._attach(ax)\n\n p.plot(ax, kwargs)\n return ax\n\n\nlineplot.__doc__ = \"\"\"\\\nDraw a line plot with possibility of several semantic groupings.\n\n{narrative.main_api}\n\n{narrative.relational_semantic}\n\nBy default, the plot aggregates over multiple ``y`` values at each value of\n``x`` and shows an estimate of the central tendency and a confidence\ninterval for that estimate.\n\nParameters\n----------\n{params.core.xy}\nhue : vector or key in ``data``\n Grouping variable that will produce lines with different colors.\n Can be either categorical or numeric, although color mapping will\n behave differently in latter case.\nsize : vector or key in ``data``\n Grouping variable that will produce lines with different widths.\n Can be either categorical or numeric, although size mapping will\n behave differently in latter case.\nstyle : vector or key in ``data``\n Grouping variable that will produce lines with different dashes\n and/or markers. Can have a numeric dtype but will always be treated\n as categorical.\n{params.core.data}\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.rel.sizes}\n{params.rel.size_order}\n{params.rel.size_norm}\n{params.rel.dashes}\n{params.rel.markers}\n{params.rel.style_order}\n{params.rel.units}\n{params.rel.estimator}\n{params.rel.ci}\n{params.rel.n_boot}\n{params.rel.seed}\nsort : boolean\n If True, the data will be sorted by the x and y variables, otherwise\n lines will connect points in the order they appear in the dataset.\nerr_style : \"band\" or \"bars\"\n Whether to draw the confidence intervals with translucent error bands\n or discrete error bars.\nerr_kws : dict of keyword arguments\n Additional paramters to control the aesthetics of the error bars. The\n kwargs are passed either to :meth:`matplotlib.axes.Axes.fill_between`\n or :meth:`matplotlib.axes.Axes.errorbar`, depending on ``err_style``.\n{params.rel.legend}\n{params.stat.errorbar}\n{params.core.ax}\nkwargs : key, value mappings\n Other keyword arguments are passed down to\n :meth:`matplotlib.axes.Axes.plot`.\n\nReturns\n-------\n{returns.ax}\n\nSee Also\n--------\n{seealso.scatterplot}\n{seealso.pointplot}\n\nExamples\n--------\n\n.. include:: ../docstrings/lineplot.rst\n\n\"\"\".format(\n narrative=_relational_narrative,\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\n\n@_deprecate_positional_args\ndef scatterplot(\n *,\n x=None, y=None,\n hue=None, style=None, size=None, data=None,\n palette=None, hue_order=None, hue_norm=None,\n sizes=None, size_order=None, size_norm=None,\n markers=True, style_order=None,\n x_bins=None, y_bins=None,\n units=None, estimator=None, ci=95, n_boot=1000,\n alpha=None, x_jitter=None, y_jitter=None,\n legend=\"auto\", ax=None, **kwargs\n):\n\n variables = _ScatterPlotter.get_semantics(locals())\n p = _ScatterPlotter(\n data=data, variables=variables,\n x_bins=x_bins, y_bins=y_bins,\n estimator=estimator, ci=ci, n_boot=n_boot,\n alpha=alpha, x_jitter=x_jitter, y_jitter=y_jitter, legend=legend,\n )\n\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n p.map_size(sizes=sizes, order=size_order, norm=size_norm)\n p.map_style(markers=markers, order=style_order)\n\n if ax is None:\n ax = plt.gca()\n\n if not p.has_xy_data:\n return ax\n\n p._attach(ax)\n\n p.plot(ax, kwargs)\n\n return ax\n\n\nscatterplot.__doc__ = \"\"\"\\\nDraw a scatter plot with possibility of several semantic groupings.\n\n{narrative.main_api}\n\n{narrative.relational_semantic}\n\nParameters\n----------\n{params.core.xy}\nhue : vector or key in ``data``\n Grouping variable that will produce points with different colors.\n Can be either categorical or numeric, although color mapping will\n behave differently in latter case.\nsize : vector or key in ``data``\n Grouping variable that will produce points with different sizes.\n Can be either categorical or numeric, although size mapping will\n behave differently in latter case.\nstyle : vector or key in ``data``\n Grouping variable that will produce points with different markers.\n Can have a numeric dtype but will always be treated as categorical.\n{params.core.data}\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.rel.sizes}\n{params.rel.size_order}\n{params.rel.size_norm}\n{params.rel.markers}\n{params.rel.style_order}\n{{x,y}}_bins : lists or arrays or functions\n *Currently non-functional.*\n{params.rel.units}\n *Currently non-functional.*\n{params.rel.estimator}\n *Currently non-functional.*\n{params.rel.ci}\n *Currently non-functional.*\n{params.rel.n_boot}\n *Currently non-functional.*\nalpha : float\n Proportional opacity of the points.\n{{x,y}}_jitter : booleans or floats\n *Currently non-functional.*\n{params.rel.legend}\n{params.core.ax}\nkwargs : key, value mappings\n Other keyword arguments are passed down to\n :meth:`matplotlib.axes.Axes.scatter`.\n\nReturns\n-------\n{returns.ax}\n\nSee Also\n--------\n{seealso.lineplot}\n{seealso.stripplot}\n{seealso.swarmplot}\n\nExamples\n--------\n\n.. include:: ../docstrings/scatterplot.rst\n\n\"\"\".format(\n narrative=_relational_narrative,\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n\n\n@_deprecate_positional_args\ndef relplot(\n *,\n x=None, y=None,\n hue=None, size=None, style=None, data=None,\n row=None, col=None,\n col_wrap=None, row_order=None, col_order=None,\n palette=None, hue_order=None, hue_norm=None,\n sizes=None, size_order=None, size_norm=None,\n markers=None, dashes=None, style_order=None,\n legend=\"auto\", kind=\"scatter\",\n height=5, aspect=1, facet_kws=None,\n units=None,\n **kwargs\n):\n\n if kind == \"scatter\":\n\n plotter = _ScatterPlotter\n func = scatterplot\n markers = True if markers is None else markers\n\n elif kind == \"line\":\n\n plotter = _LinePlotter\n func = lineplot\n dashes = True if dashes is None else dashes\n\n else:\n err = \"Plot kind {} not recognized\".format(kind)\n raise ValueError(err)\n\n # Check for attempt to plot onto specific axes and warn\n if \"ax\" in kwargs:\n msg = (\n \"relplot is a figure-level function and does not accept \"\n \"the ax= paramter. You may wish to try {}\".format(kind + \"plot\")\n )\n warnings.warn(msg, UserWarning)\n kwargs.pop(\"ax\")\n\n # Use the full dataset to map the semantics\n p = plotter(\n data=data,\n variables=plotter.get_semantics(locals()),\n legend=legend,\n )\n p.map_hue(palette=palette, order=hue_order, norm=hue_norm)\n p.map_size(sizes=sizes, order=size_order, norm=size_norm)\n p.map_style(markers=markers, dashes=dashes, order=style_order)\n\n # Extract the semantic mappings\n if \"hue\" in p.variables:\n palette = p._hue_map.lookup_table\n hue_order = p._hue_map.levels\n hue_norm = p._hue_map.norm\n else:\n palette = hue_order = hue_norm = None\n\n if \"size\" in p.variables:\n sizes = p._size_map.lookup_table\n size_order = p._size_map.levels\n size_norm = p._size_map.norm\n\n if \"style\" in p.variables:\n style_order = p._style_map.levels\n if markers:\n markers = {k: p._style_map(k, \"marker\") for k in style_order}\n else:\n markers = None\n if dashes:\n dashes = {k: p._style_map(k, \"dashes\") for k in style_order}\n else:\n dashes = None\n else:\n markers = dashes = style_order = None\n\n # Now extract the data that would be used to draw a single plot\n variables = p.variables\n plot_data = p.plot_data\n plot_semantics = p.semantics\n\n # Define the common plotting parameters\n plot_kws = dict(\n palette=palette, hue_order=hue_order, hue_norm=hue_norm,\n sizes=sizes, size_order=size_order, size_norm=size_norm,\n markers=markers, dashes=dashes, style_order=style_order,\n legend=False,\n )\n plot_kws.update(kwargs)\n if kind == \"scatter\":\n plot_kws.pop(\"dashes\")\n\n # Define the named variables for plotting on each facet\n plot_variables = {key: key for key in p.variables}\n plot_kws.update(plot_variables)\n\n # Add the grid semantics onto the plotter\n grid_semantics = \"row\", \"col\"\n p.semantics = plot_semantics + grid_semantics\n p.assign_variables(\n data=data,\n variables=dict(\n x=x, y=y,\n hue=hue, size=size, style=style, units=units,\n row=row, col=col,\n ),\n )\n\n # Pass the row/col variables to FacetGrid with their original\n # names so that the axes titles render correctly\n grid_kws = {v: p.variables.get(v, None) for v in grid_semantics}\n full_data = p.plot_data.rename(columns=grid_kws)\n\n # Set up the FacetGrid object\n facet_kws = {} if facet_kws is None else facet_kws.copy()\n facet_kws.update(grid_kws)\n g = FacetGrid(\n data=full_data,\n col_wrap=col_wrap, row_order=row_order, col_order=col_order,\n height=height, aspect=aspect, dropna=False,\n **facet_kws\n )\n\n # Draw the plot\n g.map_dataframe(func, **plot_kws)\n\n # Label the axes\n g.set_axis_labels(\n variables.get(\"x\", None), variables.get(\"y\", None)\n )\n\n # Show the legend\n if legend:\n # Replace the original plot data so the legend uses\n # numeric data with the correct type\n p.plot_data = plot_data\n p.add_legend_data(g.axes.flat[0])\n if p.legend_data:\n g.add_legend(legend_data=p.legend_data,\n label_order=p.legend_order,\n title=p.legend_title,\n adjust_subtitles=True)\n\n return g\n\n\nrelplot.__doc__ = \"\"\"\\\nFigure-level interface for drawing relational plots onto a FacetGrid.\n\nThis function provides access to several different axes-level functions\nthat show the relationship between two variables with semantic mappings\nof subsets. The ``kind`` parameter selects the underlying axes-level\nfunction to use:\n\n- :func:`scatterplot` (with ``kind=\"scatter\"``; the default)\n- :func:`lineplot` (with ``kind=\"line\"``)\n\nExtra keyword arguments are passed to the underlying function, so you\nshould refer to the documentation for each to see kind-specific options.\n\n{narrative.main_api}\n\n{narrative.relational_semantic}\n\nAfter plotting, the :class:`FacetGrid` with the plot is returned and can\nbe used directly to tweak supporting plot details or add other layers.\n\nNote that, unlike when using the underlying plotting functions directly,\ndata must be passed in a long-form DataFrame with variables specified by\npassing strings to ``x``, ``y``, and other parameters.\n\nParameters\n----------\n{params.core.xy}\nhue : vector or key in ``data``\n Grouping variable that will produce elements with different colors.\n Can be either categorical or numeric, although color mapping will\n behave differently in latter case.\nsize : vector or key in ``data``\n Grouping variable that will produce elements with different sizes.\n Can be either categorical or numeric, although size mapping will\n behave differently in latter case.\nstyle : vector or key in ``data``\n Grouping variable that will produce elements with different styles.\n Can have a numeric dtype but will always be treated as categorical.\n{params.core.data}\n{params.facets.rowcol}\n{params.facets.col_wrap}\nrow_order, col_order : lists of strings\n Order to organize the rows and/or columns of the grid in, otherwise the\n orders are inferred from the data objects.\n{params.core.palette}\n{params.core.hue_order}\n{params.core.hue_norm}\n{params.rel.sizes}\n{params.rel.size_order}\n{params.rel.size_norm}\n{params.rel.style_order}\n{params.rel.dashes}\n{params.rel.markers}\n{params.rel.legend}\nkind : string\n Kind of plot to draw, corresponding to a seaborn relational plot.\n Options are {{``scatter`` and ``line``}}.\n{params.facets.height}\n{params.facets.aspect}\nfacet_kws : dict\n Dictionary of other keyword arguments to pass to :class:`FacetGrid`.\n{params.rel.units}\nkwargs : key, value pairings\n Other keyword arguments are passed through to the underlying plotting\n function.\n\nReturns\n-------\n{returns.facetgrid}\n\nExamples\n--------\n\n.. include:: ../docstrings/relplot.rst\n\n\"\"\".format(\n narrative=_relational_narrative,\n params=_param_docs,\n returns=_core_docs[\"returns\"],\n seealso=_core_docs[\"seealso\"],\n)\n" ]
[ [ "numpy.square", "matplotlib.pyplot.gca", "numpy.power", "numpy.asarray", "numpy.percentile", "numpy.full", "matplotlib.ticker.LogLocator", "matplotlib.ticker.MaxNLocator" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
SR42-dev/AI-ML-Course
[ "125fa09a40bf171a9d93805bc6b73d65bc5d3da7" ]
[ "chapter2 - dataClassification/SupportVectorMachine (SVM)/source.py" ]
[ "# Support Vector Machine (SVM)\r\n\r\n# Importing the libraries\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n# Importing the dataset\r\ndataset = pd.read_csv('social_network_ads.csv')\r\nX = dataset.iloc[:, [2, 3]].values # age, salary\r\ny = dataset.iloc[:, 4].values # whether or not purchased\r\n\r\n# Splitting the dataset into the Training set and Test set\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)\r\n\r\n# Feature Scaling\r\nfrom sklearn.preprocessing import StandardScaler\r\nsc = StandardScaler()\r\nX_train = sc.fit_transform(X_train)\r\nX_test = sc.transform(X_test)\r\n\r\n# Fitting SVM to the Training set\r\nfrom sklearn.svm import SVC\r\nclassifier = SVC(kernel = 'linear', random_state = 0) # object to create line as opposed to KNN, linear kernel gives straight line\r\nclassifier.fit(X_train, y_train)\r\n\r\n# Predicting the Test set results\r\ny_pred = classifier.predict(X_test)\r\nprint(type(y_pred[0]))\r\n\r\n# Making the Confusion Matrix\r\nfrom sklearn.metrics import confusion_matrix\r\ncm = confusion_matrix(y_test, y_pred)" ]
[ [ "pandas.read_csv", "sklearn.metrics.confusion_matrix", "sklearn.model_selection.train_test_split", "sklearn.svm.SVC", "sklearn.preprocessing.StandardScaler" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
ajmalkurnia/id-postagger
[ "d488f03e96c4135ad1378f1def52ad533a163803" ]
[ "model/tf_model_crf.py" ]
[ "\"\"\"\nWrapping model that has CRF layer to compute crf_loss\nsource @jaspersjsun https://github.com/tensorflow/addons/pull/1999/files\n\"\"\"\nimport tensorflow as tf\nfrom tensorflow_addons.text.crf import crf_log_likelihood\n\n\ndef unpack_data(data):\n if len(data) == 2:\n return data[0], data[1], None\n elif len(data) == 3:\n return data\n else:\n raise TypeError(\"Expected data to be a tuple of size 2 or 3.\")\n\n\nclass ModelWithCRFLoss(tf.keras.Model):\n \"\"\"Wrapper around the base model for custom training logic.\"\"\"\n\n def __init__(self, base_model, **kwargs):\n super(ModelWithCRFLoss, self).__init__(**kwargs)\n self.base_model = base_model\n\n def call(self, inputs):\n return self.base_model(inputs)\n\n def compute_loss(self, x, y, sample_weight, training=False):\n y_pred = self(x, training=training)\n _, potentials, sequence_length, chain_kernel = y_pred\n crf_loss = -crf_log_likelihood(potentials,\n y, sequence_length, chain_kernel)[0]\n internal_loss = self.compiled_loss(\n y, potentials, regularization_losses=self.losses)\n if sample_weight is not None:\n crf_loss = crf_loss * sample_weight\n\n return tf.reduce_mean(crf_loss), internal_loss\n\n def train_step(self, data):\n x, y, sample_weight = unpack_data(data)\n\n with tf.GradientTape() as tape:\n crf_loss, internal_losses = self.compute_loss(\n x, y, sample_weight, training=True\n )\n total_loss = crf_loss + \\\n tf.cast(tf.reduce_sum(self.losses), crf_loss.dtype)\n\n gradients = tape.gradient(total_loss, self.trainable_variables)\n self.optimizer.apply_gradients(\n zip(gradients, self.trainable_variables))\n\n return {\"crf_loss\": crf_loss, \"internal_losses\": internal_losses}\n\n def test_step(self, data):\n x, y, sample_weight = unpack_data(data)\n crf_loss, internal_losses = self.compute_loss(x, y, sample_weight)\n return {\"crf_loss\": crf_loss, \"internal_losses\": internal_losses}\n" ]
[ [ "tensorflow.reduce_sum", "tensorflow.GradientTape", "tensorflow.reduce_mean" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] } ]
landegt/pylabel
[ "9d0079a1f61eb84ec9cd10fb202a9246a08576fa" ]
[ "pylabel/exporter.py" ]
[ "import json\nfrom typing import List\nimport pandas as pd\nimport numpy as np\nimport xml.etree.ElementTree as ET\nimport xml.dom.minidom\nimport os \nimport yaml\nimport shutil\n\nfrom pathlib import PurePath, Path\n\nclass Export():\n def __init__(self, dataset=None):\n self.dataset = dataset\n\n def ExportToVoc(self, output_path=None, segmented_=False, path_=False, database_=False, folder_=False, occluded_=False):\n ds = self.dataset\n\n if output_path == None:\n output_path = ds.path_to_annotations\n else: \n output_path = output_path\n\n os.makedirs(output_path, exist_ok=True)\n\n \"\"\" Writes annotation files to disk in VOC XML format and returns path to files.\n\n By default, tags with empty values will not be included in the XML output. \n You can optionally choose to include them if they are required for your solution.\n\n Args:\n dataset (obj): \n A dataset object that contains the annotations and metadata.\n output_path (str or None): \n This is where the annotation files will be written.\n If not-specified then the path will be derived from the .path_to_annotations and\n .name properties of the dataset object. \n\n Returns:\n A list with 1 or more paths (strings) to annotations files.\n \"\"\" \n output_file_paths = []\n\n def voc_xml_file_creation(data, file_name, output_file_path, segmented=True, path=True, database=True, folder=True, occluded=True):\n \n index = 0\n df_smaller = data[data['img_filename'] == file_name].reset_index()\n \n if len(df_smaller) == 1:\n #print('test')\n annotation_text_start = '<annotation>'\n\n flder_lkp = str(df_smaller.loc[index]['img_folder'])\n if folder==True and flder_lkp != '':\n folder_text = '<folder>'+flder_lkp+'</folder>'\n else:\n folder_text = ''\n \n filename_text = '<filename>'+str(df_smaller.loc[index]['img_filename'])+'</filename>'\n \n pth_lkp = str(df_smaller.loc[index]['img_path'])\n if path == True and pth_lkp != '':\n path_text = '<path>'+ pth_lkp +'</path>'\n else:\n path_text = ''\n \n sources_text = ''\n \n size_text_start = '<size>'\n width_text = '<width>'+str(df_smaller.loc[index]['img_width'])+'</width>'\n height_text = '<height>'+str(df_smaller.loc[index]['img_height'])+'</height>'\n depth_text = '<depth>'+str(df_smaller.loc[index]['img_depth'])+'</depth>'\n size_text_end = '</size>'\n \n seg_lkp = str(df_smaller.loc[index]['ann_segmented'])\n if segmented == True and seg_lkp != '':\n segmented_text = '<segmented>'+str(df_smaller.loc[index]['ann_segmented'])+'</segmented>'\n else:\n segmented_text = ''\n\n object_text_start = '<object>'\n\n name_text = '<name>'+str(df_smaller.loc[index]['cat_name'])+'</name>'\n pose_text = '<pose>'+str(df_smaller.loc[index]['ann_pose'])+'</pose>'\n truncated_text = '<truncated>'+str(df_smaller.loc[index]['ann_truncated'])+'</truncated>'\n difficult_text = '<difficult>'+str(df_smaller.loc[index]['ann_difficult'])+'</difficult>'\n \n occluded_text = ''\n\n bound_box_text_start = '<bndbox>'\n\n xmin_text = '<xmin>'+str(df_smaller.loc[index]['ann_bbox_xmin'])+'</xmin>'\n xmax_text = '<xmax>'+str(df_smaller.loc[index]['ann_bbox_xmax'])+'</xmax>'\n ymin_text = '<ymin>'+str(df_smaller.loc[index]['ann_bbox_ymin'])+'</ymin>'\n ymax_text = '<ymax>'+str(df_smaller.loc[index]['ann_bbox_ymax'])+'</ymax>'\n\n bound_box_text_end = '</bndbox>'\n object_text_end = '</object>'\n annotation_text_end = '</annotation>'\n \n xmlstring = annotation_text_start + folder_text +filename_text + \\\n path_text + sources_text + size_text_start + width_text + \\\n height_text + depth_text + size_text_end + segmented_text + \\\n object_text_start + name_text + pose_text +truncated_text + \\\n difficult_text + occluded_text + bound_box_text_start +xmin_text + \\\n xmax_text +ymin_text +ymax_text +bound_box_text_end + \\\n object_text_end + annotation_text_end\n dom = xml.dom.minidom.parseString(xmlstring)\n pretty_xml_as_string = dom.toprettyxml()\n \n with open(output_file_path, \"w\") as f:\n f.write(pretty_xml_as_string) \n\n return output_file_path\n \n else:\n\n #print('test')\n annotation_text_start = '<annotation>'\n \n flder_lkp = str(df_smaller.loc[index]['img_folder'])\n if folder==True and flder_lkp != '':\n folder_text = '<folder>'+flder_lkp+'</folder>'\n else:\n folder_text = ''\n \n filename_text = '<filename>'+str(df_smaller.loc[index]['img_filename'])+'</filename>'\n \n pth_lkp = str(df_smaller.loc[index]['img_path'])\n if path == True and pth_lkp != '':\n path_text = '<path>'+ pth_lkp +'</path>'\n else:\n path_text = ''\n \n #db_lkp = str(df_smaller.loc[index]['Databases'])\n #if database == True and db_lkp != '':\n # sources_text = '<source>'+'<database>'+ db_lkp +'</database>'+'</source>'\n #else:\n sources_text = ''\n \n size_text_start = '<size>'\n width_text = '<width>'+str(df_smaller.loc[index]['img_width'])+'</width>'\n height_text = '<height>'+str(df_smaller.loc[index]['img_height'])+'</height>'\n depth_text = '<depth>'+str(df_smaller.loc[index]['img_depth'])+'</depth>'\n size_text_end = '</size>'\n \n seg_lkp = str(df_smaller.loc[index]['ann_segmented'])\n if segmented == True and seg_lkp != '':\n segmented_text = '<segmented>'+str(df_smaller.loc[index]['ann_segmented'])+'</segmented>'\n else:\n segmented_text = ''\n\n xmlstring = annotation_text_start + folder_text +filename_text + \\\n path_text + sources_text + size_text_start + width_text + \\\n height_text + depth_text + size_text_end + segmented_text\n \n for obj in range(len(df_smaller)):\n object_text_start = '<object>'\n\n name_text = '<name>'+str(df_smaller.loc[index]['cat_name'])+'</name>'\n pose_text = '<pose>'+str(df_smaller.loc[index]['ann_pose'])+'</pose>'\n truncated_text = '<truncated>'+str(df_smaller.loc[index]['ann_truncated'])+'</truncated>'\n difficult_text = '<difficult>'+str(df_smaller.loc[index]['ann_difficult'])+'</difficult>'\n \n #occ_lkp = str(df_smaller.loc[index]['Object Occluded'])\n #if occluded==True and occ_lkp != '':\n # occluded_text = '<occluded>'+occ_lkp+'</occluded>'\n #else:\n occluded_text = ''\n\n bound_box_text_start = '<bndbox>'\n\n xmin_text = '<xmin>'+str(df_smaller.loc[index]['ann_bbox_xmin'])+'</xmin>'\n xmax_text = '<xmax>'+str(df_smaller.loc[index]['ann_bbox_xmax'])+'</xmax>'\n ymin_text = '<ymin>'+str(df_smaller.loc[index]['ann_bbox_ymin'])+'</ymin>'\n ymax_text = '<ymax>'+str(df_smaller.loc[index]['ann_bbox_ymax'])+'</ymax>'\n\n bound_box_text_end = '</bndbox>'\n object_text_end = '</object>'\n annotation_text_end = '</annotation>'\n index = index + 1\n\n xmlstring = xmlstring + object_text_start + name_text + pose_text +truncated_text + \\\n difficult_text + occluded_text + bound_box_text_start +xmin_text + \\\n xmax_text +ymin_text +ymax_text +bound_box_text_end + \\\n object_text_end \n\n xmlstring = xmlstring + annotation_text_end\n dom = xml.dom.minidom.parseString(xmlstring)\n pretty_xml_as_string = dom.toprettyxml()\n \n with open(output_file_path, \"w\") as f:\n f.write(pretty_xml_as_string) \n\n return output_file_path\n\n #Loop through all images in the dataframe and call voc_xml_file_creation for each one\n for file_title in list(set(self.dataset.df.img_filename)):\n\n file_name = Path(file_title)\n file_name = str(file_name.with_suffix('.xml'))\n file_path = str(Path(output_path, file_name))\n voc_file_path = voc_xml_file_creation(ds.df, file_title, segmented=segmented_, path=path_, database=database_, folder=folder_, occluded=occluded_, output_file_path=file_path)\n output_file_paths.append(voc_file_path)\n\n return output_file_paths\n\n def ExportToYoloV5(self, output_path=None, yaml_file=None, copy_images=False, use_splits=False):\n \"\"\" Writes annotation files to disk and returns path to files.\n \n Args:\n dataset (obj): \n A dataset object that contains the annotations and metadata.\n output_path (str): \n This is where the annotation files will be written.\n If not-specified then the path will be derived from the .path_to_annotations and\n .name properties of the dataset object. If you are exporting images to train a model, the recommended path \n to use is 'training/labels'. \n yaml_file (str):\n If a file name (string) is provided, a YOLOv5 YAML file will be created with entries for the files\n and classes in this dataset. It will be created in the parent of the output_path directory. \n The recommended name for the YAML file is 'dataset.yaml'.\n copy_images (boolean):\n If True, then the annotated images will be copied to a directory next to the labels directory into \n a directory named 'images'. This will prepare your labels and images to be used as inputs to \n train a YOLOv5 model. \n use_splits (boolean):\n If True, then the images and annotations will be moved into directories based on the values in the split column.\n For example, if a row has the value split = \"train\" then the annotations for that row will be moved to directory \n /train. If a YAML file is specificied then the YAML file will use the splits to specify the folders user for the\n train, val, and test datasets. \n Returns:\n A list with 1 or more paths (strings) to annotations files. If a YAML file is created\n then the first item in the list will be the path to the YAML file. \n \"\"\"\n ds = self.dataset\n\n #Inspired by https://github.com/aws-samples/groundtruth-object-detection/blob/master/create_annot.py \n yolo_dataset = ds.df.copy(deep=True)\n #Convert nan values in the split collumn from nan to '' because those are easier to with with when building paths\n yolo_dataset.split = yolo_dataset.split.fillna('')\n\n\n #Create all of the paths that will be used to manage the files in this dataset \n path_dict ={}\n\n #The output path is the main path that will be used to create the other relative paths \n path = PurePath(output_path)\n path_dict[\"label_path\"] = output_path\n #The /images directory should be next to the /labels directory \n path_dict[\"image_path\"] = str(PurePath(path.parent, \"images\"))\n #The root directory is in parent of the /labels and /images directories\n path_dict[\"root_path\"] = str(PurePath(path.parent))\n #The YAML file should be in root directory\n path_dict[\"yaml_path\"] = str(PurePath(path_dict[\"root_path\"], yaml_file))\n #The root directory will usually be next to the yolov5 directory. \n #Specify the relative path \n path_dict[\"root_path_from_yolo_dir\"] = str(PurePath(\"../\"))\n #If these default values to not match the users environment then they can manually edit the YAML file\n\n if copy_images:\n #Create the folder that the images will be copied to\n Path(path_dict[\"image_path\"]).mkdir(parents=True, exist_ok=True) \n\n #Drop rows that are not annotated\n #Note, having zero annotates can still be considered annotated \n #in cases when are no objects in the image thats should be indentified\n yolo_dataset = yolo_dataset.loc[yolo_dataset[\"annotated\"] == 1]\n\n yolo_dataset.cat_id = yolo_dataset.cat_id.str.strip()\n yolo_dataset.cat_id = yolo_dataset.cat_id.astype('float').astype('Int32')\n yolo_dataset[\"center_x_scaled\"] = (yolo_dataset[\"ann_bbox_xmin\"] + (yolo_dataset[\"ann_bbox_width\"]*0.5))/yolo_dataset[\"img_width\"]\n yolo_dataset[\"center_y_scaled\"] = (yolo_dataset[\"ann_bbox_ymin\"] + (yolo_dataset[\"ann_bbox_height\"]*0.5))/yolo_dataset[\"img_height\"]\n yolo_dataset[\"width_scaled\"] = yolo_dataset[\"ann_bbox_width\"] / yolo_dataset[\"img_width\"]\n yolo_dataset[\"height_scaled\"] = yolo_dataset[\"ann_bbox_height\"] / yolo_dataset[\"img_height\"]\n yolo_dataset[[\"cat_id\", \"center_x_scaled\", \"center_y_scaled\", \"width_scaled\", \"height_scaled\"]]\n\n #Create folders to store annotations\n if output_path == None:\n dest_folder = PurePath(ds.path_to_annotations, yolo_dataset.iloc[0].img_folder)\n else:\n dest_folder = output_path\n\n os.makedirs(dest_folder, exist_ok=True)\n\n unique_images = yolo_dataset[\"img_filename\"].unique()\n output_file_paths = []\n\n for img_filename in unique_images:\n df_single_img_annots = yolo_dataset.loc[yolo_dataset.img_filename == img_filename]\n annot_txt_file = img_filename.split(\".\")[0] + \".txt\"\n #Use the value of the split collumn to create a directory \n #The values should be train, val, test or '' \n if use_splits:\n split_dir = df_single_img_annots.iloc[0].split\n else:\n split_dir = split_dir\n destination = str(PurePath(dest_folder, split_dir, annot_txt_file))\n Path(dest_folder, split_dir,).mkdir(parents=True, exist_ok=True) \n\n df_single_img_annots.to_csv(\n destination,\n index=False,\n header=False,\n sep=\" \",\n float_format=\"%.4f\",\n columns=[\n \"cat_id\",\n \"center_x_scaled\",\n \"center_y_scaled\",\n \"width_scaled\",\n \"height_scaled\",\n ])\n output_file_paths.append(destination)\n\n if copy_images:\n source_image_path = str(Path(ds.path_to_annotations, \n df_single_img_annots.iloc[0].img_folder, \n df_single_img_annots.iloc[0].img_filename))\n\n current_file = Path(source_image_path)\n assert current_file.is_file, f\"File does not exist: {source_image_path}. Check img_folder column values.\"\n Path(path_dict[\"image_path\"], split_dir).mkdir(parents=True, exist_ok=True) \n shutil.copy(str(source_image_path), str(PurePath(path_dict[\"image_path\"], split_dir, img_filename))) \n\n #Create YAML file\n if yaml_file:\n #Make a set with all of the different values of the split column \n splits = set(yolo_dataset.split)\n #Build a dict with all of the values that will go into the YAML file\n dict_file = {}\n dict_file[\"path\"] = path_dict[\"root_path_from_yolo_dir\"] \n\n #If train is one of the splits, append train to path \n\n if use_splits and \"train\" in splits:\n dict_file[\"train\"] = str(PurePath(path_dict[\"image_path\"],\"train\"))\n else:\n dict_file[\"train\"] = path_dict[\"image_path\"]\n\n #If val is one of the splits, append val to path \n if use_splits and \"val\" in splits:\n dict_file[\"val\"] = str(PurePath(path_dict[\"image_path\"], \"val\"))\n else:\n dict_file[\"val\"] = path_dict[\"image_path\"]\n\n #If test is one of the splits, make a test param and add test to the path\n if use_splits and \"test\" in splits:\n dict_file[\"test\"] = str(PurePath(path_dict[\"image_path\"], \"val\"))\n\n dict_file[\"nc\"] = ds.analyze.num_classes\n dict_file[\"names\"] = ds.analyze.classes\n\n #Save the yamlfile\n with open(path_dict[\"yaml_path\"], 'w') as file:\n documents = yaml.dump(dict_file, file)\n output_file_paths = [path_dict[\"yaml_path\"]] + output_file_paths\n\n return output_file_paths\n\n def ExportToCoco(self, output_path=None) -> List:\n \"\"\" \n Writes annotation files to disk and returns path to files.\n\n Args:\n dataset (obj): \n A dataset object that contains the annotations and metadata.\n output_path (str or None): \n This is where the annotation files will be written.\n If not-specified then the path will be derived from the .path_to_annotations and\n .name properties of the dataset object. \n\n Returns:\n A list with 1 or more paths (strings) to annotations files.\n \"\"\"\n df = self.dataset.df\n df_outputI = []\n df_outputA = []\n df_outputC = []\n list_i = []\n list_c = []\n json_list = []\n \n for i in range(0,df.shape[0]):\n images = [{\n \"id\": df['img_id'][i], \n \"folder\": df['img_folder'][i], \n \"file_name\": df['img_filename'][i], \n \"path\": df['img_path'][i], \n \"width\": df['img_width'][i], \n \"height\": df['img_height'][i], \n \"depth\": df['img_depth'][i]\n }]\n \n annotations = [{\n \"image_id\": df['img_id'][i], \n \"id\": df.index[i], \n \"segmented\": df['ann_segmented'][i],\n \"bbox\": [df['ann_bbox_xmin'][i], df['ann_bbox_ymin'][i], df['ann_bbox_width'][i], df['ann_bbox_height'][i]], \n \"area\": df['ann_area'][i], \n \"segmentation\": df['ann_segmentation'][i], \n \"iscrowd\": df['ann_iscrowd'][i], \n \"pose\": df['ann_pose'][i], \n \"truncated\": df['ann_truncated'][i],\n \"category_id\": df['cat_id'][i], \n \"difficult\": df['ann_difficult'][i]\n }]\n\n categories = [{\n \"id\": int(df['cat_id'][i]), \n \"name\": df['cat_name'][i], \n \"supercategory\": df['cat_supercategory'][i]\n }]\n \n if(list_c):\n if (categories[0][\"id\"] in list_c or np.isnan(categories[0][\"id\"])):\n pass \n else:\n df_outputC.append(pd.DataFrame([categories]))\n elif(~np.isnan(categories[0][\"id\"])):\n df_outputC.append(pd.DataFrame([categories]))\n else:\n pass\n list_c.append(categories[0][\"id\"])\n\n if(list_i):\n if (images[0][\"id\"] in list_i or np.isnan(images[0][\"id\"])):\n pass\n else:\n df_outputI.append(pd.DataFrame([images]))\n elif(~np.isnan(images[0][\"id\"])):\n df_outputI.append(pd.DataFrame([images])) \n else:\n pass\n list_i.append(images[0][\"id\"]) \n\n df_outputA.append(pd.DataFrame([annotations]))\n \n mergedI = pd.concat(df_outputI, ignore_index=True)\n mergedA = pd.concat(df_outputA, ignore_index=True)\n mergedC = pd.concat(df_outputC, ignore_index=True)\n \n resultI = mergedI[0].to_json(orient=\"split\")\n resultA = mergedA[0].to_json(orient=\"split\")\n resultC = mergedC[0].to_json(orient=\"split\")\n\n parsedI = json.loads(resultI)\n del parsedI['index']\n del parsedI['name']\n parsedI['images'] = parsedI['data']\n del parsedI['data']\n\n parsedA = json.loads(resultA)\n del parsedA['index']\n del parsedA['name']\n parsedA['annotations'] = parsedA['data']\n del parsedA['data']\n\n parsedC = json.loads(resultC)\n del parsedC['index']\n del parsedC['name']\n parsedC['categories'] = parsedC['data']\n del parsedC['data']\n\n parsedI.update(parsedA)\n parsedI.update(parsedC)\n json_output = parsedI\n\n if output_path == None:\n output_path = Path(self.dataset.path_to_annotations, (self.dataset.name + \".json\"))\n \n with open(output_path, 'w') as outfile:\n json.dump(obj=json_output, fp=outfile, indent=4)\n return [str(output_path)] " ]
[ [ "numpy.isnan", "pandas.concat", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
lovish1234/TPC
[ "10e93eeb0e22e411579cfb9f94fac7870f6e2039" ]
[ "backbone/resnet_2d3d.py" ]
[ "# modified from https://github.com/kenshohara/3D-ResNets-PyTorch\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport math\n\n# last two blocks are 3-D for this resnet\n__all__ = [\n 'ResNet2d3d_full', 'resnet18_2d3d_full', 'resnet34_2d3d_full', 'resnet50_2d3d_full', 'resnet101_2d3d_full',\n 'resnet152_2d3d_full', 'resnet200_2d3d_full', 'resnet10_2d3d_mini', 'resnet8_2d3d_mini'\n]\n\n\ndef conv3x3x3(in_planes, out_planes, stride=1, bias=False):\n # 3x3x3 convolution with padding\n return nn.Conv3d(\n in_planes,\n out_planes,\n kernel_size=3,\n stride=stride,\n padding=1,\n bias=bias)\n\n\ndef conv1x3x3(in_planes, out_planes, stride=1, bias=False):\n # 1x3x3 convolution with padding\n return nn.Conv3d(\n in_planes,\n out_planes,\n kernel_size=(1, 3, 3),\n stride=(1, stride, stride),\n padding=(0, 1, 1),\n bias=bias)\n\n\ndef downsample_basic_block(x, planes, stride):\n out = F.avg_pool3d(x, kernel_size=1, stride=stride)\n zero_pads = torch.Tensor(\n out.size(0), planes - out.size(1), out.size(2), out.size(3),\n out.size(4)).zero_()\n if isinstance(out.data, torch.cuda.FloatTensor):\n zero_pads = zero_pads.cuda()\n\n out = Variable(torch.cat([out.data, zero_pads], dim=1))\n\n return out\n\n\nclass BasicBlock3d(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, track_running_stats=True, use_final_relu=True):\n super(BasicBlock3d, self).__init__()\n bias = False\n self.use_final_relu = use_final_relu\n self.conv1 = conv3x3x3(inplanes, planes, stride, bias=bias)\n self.bn1 = nn.BatchNorm3d(\n planes, track_running_stats=track_running_stats)\n\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3x3(planes, planes, bias=bias)\n self.bn2 = nn.BatchNorm3d(\n planes, track_running_stats=track_running_stats)\n\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n if self.use_final_relu:\n out = self.relu(out)\n\n return out\n\n\nclass BasicBlock2d(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, track_running_stats=True, use_final_relu=True):\n super(BasicBlock2d, self).__init__()\n bias = False\n self.use_final_relu = use_final_relu\n self.conv1 = conv1x3x3(inplanes, planes, stride, bias=bias)\n self.bn1 = nn.BatchNorm3d(\n planes, track_running_stats=track_running_stats)\n\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv1x3x3(planes, planes, bias=bias)\n self.bn2 = nn.BatchNorm3d(\n planes, track_running_stats=track_running_stats)\n\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n if self.use_final_relu:\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck3d(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, track_running_stats=True, use_final_relu=True):\n super(Bottleneck3d, self).__init__()\n bias = False\n self.use_final_relu = use_final_relu\n self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=bias)\n self.bn1 = nn.BatchNorm3d(\n planes, track_running_stats=track_running_stats)\n\n self.conv2 = nn.Conv3d(planes, planes, kernel_size=3,\n stride=stride, padding=1, bias=bias)\n self.bn2 = nn.BatchNorm3d(\n planes, track_running_stats=track_running_stats)\n\n self.conv3 = nn.Conv3d(planes, planes * 4, kernel_size=1, bias=bias)\n self.bn3 = nn.BatchNorm3d(\n planes * 4, track_running_stats=track_running_stats)\n\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n if self.use_final_relu:\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck2d(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, track_running_stats=True, use_final_relu=True):\n super(Bottleneck2d, self).__init__()\n bias = False\n self.use_final_relu = use_final_relu\n self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=bias)\n self.bn1 = nn.BatchNorm3d(\n planes, track_running_stats=track_running_stats)\n\n self.conv2 = nn.Conv3d(planes, planes, kernel_size=(1, 3, 3), stride=(\n 1, stride, stride), padding=(0, 1, 1), bias=bias)\n self.bn2 = nn.BatchNorm3d(\n planes, track_running_stats=track_running_stats)\n\n self.conv3 = nn.Conv3d(planes, planes * 4, kernel_size=1, bias=bias)\n self.bn3 = nn.BatchNorm3d(\n planes * 4, track_running_stats=track_running_stats)\n\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n if self.batchnorm:\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n if self.batchnorm:\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n if self.batchnorm:\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n if self.use_final_relu:\n out = self.relu(out)\n\n return out\n\n\nclass ResNet2d3d_full(nn.Module):\n def __init__(self, block, layers, track_running_stats=True, distance='dot'):\n super(ResNet2d3d_full, self).__init__()\n\n self.inplanes = 64\n self.track_running_stats = track_running_stats\n self.distance = distance\n bias = False\n\n # 4, 3, 16, 128, 128\n self.conv1 = nn.Conv3d(3, 64, kernel_size=(\n 1, 7, 7), stride=(1, 2, 2), padding=(0, 3, 3), bias=bias)\n self.bn1 = nn.BatchNorm3d(64, track_running_stats=track_running_stats)\n self.relu = nn.ReLU(inplace=True)\n\n # 4, 3, 16, 64, 64\n self.maxpool = nn.MaxPool3d(kernel_size=(\n 1, 3, 3), stride=(1, 2, 2), padding=(0, 1, 1))\n\n # 4, 3, 16, 32, 32\n if not isinstance(block, list):\n block = [block] * 4\n\n # resnet blocks\n self.layer1 = self._make_layer(block[0], 64, layers[0])\n self.layer2 = self._make_layer(block[1], 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block[2], 256, layers[2], stride=2)\n\n # change this according to conditions\n self.layer4 = self._make_layer(\n block[3], 256, layers[3], stride=2, is_final=True)\n\n # modify layer4 from exp=512 to exp=256\n for m in self.modules():\n if isinstance(m, nn.Conv3d):\n if self.distance == 'poincare':\n print('[resnet_2d3d.py] initializing resnet with N(-0.001, 0.001)')\n m.weight = nn.init.uniform_(m.weight, a=-0.001, b=0.001)\n else:\n m.weight = nn.init.kaiming_normal_(m.weight, mode='fan_out')\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm3d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def _make_layer(self, block, planes, blocks, stride=1, is_final=False):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n # customized_stride to deal with 2d or 3d residual blocks\n if (block == Bottleneck2d) or (block == BasicBlock2d):\n customized_stride = (1, stride, stride)\n else:\n customized_stride = stride\n\n downsample = nn.Sequential(\n nn.Conv3d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=customized_stride, bias=False),\n nn.BatchNorm3d(planes * block.expansion,\n track_running_stats=self.track_running_stats)\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample,\n track_running_stats=self.track_running_stats))\n self.inplanes = planes * block.expansion\n\n if is_final: # if is final block, no ReLU in the final output\n for i in range(1, blocks - 1):\n layers.append(block(self.inplanes, planes,\n track_running_stats=self.track_running_stats))\n layers.append(block(self.inplanes, planes,\n track_running_stats=self.track_running_stats, use_final_relu=False))\n else:\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes,\n track_running_stats=self.track_running_stats))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n return x\n\n\n# full resnet\nclass ResNet2d3d_mini(nn.Module):\n def __init__(self, block, layers, track_running_stats=True, distance='dot'):\n super(ResNet2d3d_mini, self).__init__()\n\n self.inplanes = 8\n self.track_running_stats = track_running_stats\n self.distance = distance\n bias = False\n\n # 4, 3, 16, 128, 128\n self.conv1 = nn.Conv3d(3, 8, kernel_size=(\n 1, 7, 7), stride=(1, 2, 2), padding=(0, 3, 3), bias=bias)\n self.bn1 = nn.BatchNorm3d(8, track_running_stats=track_running_stats)\n self.relu = nn.ReLU(inplace=True)\n\n # 4, 3, 16, 64, 64\n self.maxpool = nn.MaxPool3d(kernel_size=(\n 1, 3, 3), stride=(1, 2, 2), padding=(0, 1, 1))\n\n # 4, 3, 16, 32, 32\n if not isinstance(block, list):\n block = [block] * 4\n\n # resnet blocks\n self.layer1 = self._make_layer(block[0], 8, layers[0], stride=4)\n #self.layer2 = self._make_layer(block[1], 128, layers[1], stride=2)\n #self.layer3 = self._make_layer(block[2], 256, layers[2], stride=2)\n\n # change this according to conditions\n self.layer4 = self._make_layer(\n block[1], 16, layers[1], stride=2, is_final=True)\n\n # modify layer4 from exp=512 to exp=256\n for m in self.modules():\n if isinstance(m, nn.Conv3d):\n if self.distance == 'poincare':\n print('[resnet_2d3d.py] initializing resnet with N(-0.001, 0.001)')\n m.weight = nn.init.uniform_(m.weight, a=-0.001, b=0.001)\n else:\n m.weight = nn.init.kaiming_normal_(m.weight, mode='fan_out')\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm3d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def _make_layer(self, block, planes, blocks, stride=1, is_final=False):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n # customized_stride to deal with 2d or 3d residual blocks\n if (block == Bottleneck2d) or (block == BasicBlock2d):\n customized_stride = (1, stride, stride)\n else:\n customized_stride = stride\n\n downsample = nn.Sequential(\n nn.Conv3d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=customized_stride, bias=False),\n nn.BatchNorm3d(planes * block.expansion,\n track_running_stats=self.track_running_stats)\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample,\n track_running_stats=self.track_running_stats))\n self.inplanes = planes * block.expansion\n\n if is_final: # if is final block, no ReLU in the final output\n for i in range(1, blocks - 1):\n layers.append(block(self.inplanes, planes,\n track_running_stats=self.track_running_stats))\n layers.append(block(self.inplanes, planes,\n track_running_stats=self.track_running_stats, use_final_relu=False))\n else:\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes,\n track_running_stats=self.track_running_stats))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n\n # print(x.shape)\n x = self.conv1(x)\n # print(x.shape)\n x = self.bn1(x)\n # print(x.shape)\n x = self.relu(x)\n # print(x.shape)\n x = self.maxpool(x)\n # print(x.shape)\n x = self.layer1(x)\n # print(x.shape)\n #x = self.layer2(x)\n # print(x.shape)\n #x = self.layer3(x)\n # print(x.shape)\n x = self.layer4(x)\n # print(x.shape)\n\n return x\n\n\ndef resnet10_2d3d_mini(**kwargs):\n '''Constructs a ResNet-18 model. '''\n model = ResNet2d3d_mini([BasicBlock2d, BasicBlock3d],\n [2, 2], **kwargs)\n return model\n\n\ndef resnet8_2d3d_mini(**kwargs):\n '''Constructs a ResNet-18 model. '''\n model = ResNet2d3d_mini([BasicBlock2d, BasicBlock3d],\n [1, 1], **kwargs)\n return model\n\n\ndef resnet18_2d3d_full(**kwargs):\n '''Constructs a ResNet-18 model. '''\n model = ResNet2d3d_full([BasicBlock2d, BasicBlock2d, BasicBlock3d, BasicBlock3d],\n [2, 2, 2, 2], **kwargs)\n return model\n\n\ndef resnet34_2d3d_full(**kwargs):\n '''Constructs a ResNet-34 model. '''\n model = ResNet2d3d_full([BasicBlock2d, BasicBlock2d, BasicBlock3d, BasicBlock3d],\n [3, 4, 6, 3], **kwargs)\n return model\n\n\ndef resnet50_2d3d_full(**kwargs):\n '''Constructs a ResNet-50 model. '''\n model = ResNet2d3d_full([Bottleneck2d, Bottleneck2d, Bottleneck3d, Bottleneck3d],\n [3, 4, 6, 3], **kwargs)\n return model\n\n\ndef resnet101_2d3d_full(**kwargs):\n '''Constructs a ResNet-101 model. '''\n model = ResNet2d3d_full([Bottleneck2d, Bottleneck2d, Bottleneck3d, Bottleneck3d],\n [3, 4, 23, 3], **kwargs)\n return model\n\n\ndef resnet152_2d3d_full(**kwargs):\n '''Constructs a ResNet-101 model. '''\n model = ResNet2d3d_full([Bottleneck2d, Bottleneck2d, Bottleneck3d, Bottleneck3d],\n [3, 8, 36, 3], **kwargs)\n return model\n\n\ndef resnet200_2d3d_full(**kwargs):\n '''Constructs a ResNet-101 model. '''\n model = ResNet2d3d_full([Bottleneck2d, Bottleneck2d, Bottleneck3d, Bottleneck3d],\n [3, 24, 36, 3], **kwargs)\n return model\n\n\ndef neq_load_customized(model, pretrained_dict):\n ''' load pre-trained model in a not-equal way,\n when new model has been partially modified '''\n model_dict = model.state_dict()\n tmp = {}\n print('\\n=======Check Weights Loading======')\n print('Weights NOT used from pretrained file:')\n for k, v in pretrained_dict.items():\n if k in model_dict:\n tmp[k] = v\n else:\n print(k)\n print('---------------------------')\n print('Weights NOT loaded into new model:')\n for k, v in model_dict.items():\n if k not in pretrained_dict:\n print(k)\n print('===================================\\n')\n # pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}\n del pretrained_dict\n model_dict.update(tmp)\n del tmp\n model.load_state_dict(model_dict)\n return model\n\n\nif __name__ == '__main__':\n mymodel = resnet10_2d3d_mini()\n mymodel = mymodel.cuda()\n\n # Batch Size x Channelr x Sequence length x Image Size x Image Size\n mydata = torch.FloatTensor(4, 3, 16, 128, 128)\n mydata = mydata.cuda()\n\n nn.init.normal_(mydata)\n #import ipdb; ipdb.set_trace()\n output = mymodel(mydata)\n # print(output.shape)\n" ]
[ [ "torch.nn.Sequential", "torch.nn.init.uniform_", "torch.cat", "torch.nn.MaxPool3d", "torch.nn.Conv3d", "torch.FloatTensor", "torch.nn.functional.avg_pool3d", "torch.nn.init.normal_", "torch.nn.ReLU", "torch.nn.BatchNorm3d", "torch.nn.init.kaiming_normal_" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
floodcaptain/pandas
[ "014d2dbc2155e926aac04c79fc6c593239c1f669" ]
[ "pandas/core/indexes/interval.py" ]
[ "\"\"\" define the IntervalIndex \"\"\"\nfrom operator import le, lt\nimport textwrap\nfrom typing import Any, Optional, Tuple, Union\n\nimport numpy as np\n\nfrom pandas._config import get_option\n\nfrom pandas._libs import Timedelta, Timestamp, lib\nfrom pandas._libs.interval import Interval, IntervalMixin, IntervalTree\nfrom pandas._typing import AnyArrayLike\nfrom pandas.util._decorators import Appender, Substitution, cache_readonly\nfrom pandas.util._exceptions import rewrite_exception\n\nfrom pandas.core.dtypes.cast import (\n find_common_type,\n infer_dtype_from_scalar,\n maybe_downcast_to_dtype,\n)\nfrom pandas.core.dtypes.common import (\n ensure_platform_int,\n is_categorical,\n is_datetime64tz_dtype,\n is_datetime_or_timedelta_dtype,\n is_dtype_equal,\n is_float,\n is_float_dtype,\n is_integer,\n is_integer_dtype,\n is_interval_dtype,\n is_list_like,\n is_number,\n is_object_dtype,\n is_scalar,\n)\nfrom pandas.core.dtypes.generic import ABCSeries\nfrom pandas.core.dtypes.missing import isna\n\nfrom pandas.core import accessor\nfrom pandas.core.algorithms import take_1d\nfrom pandas.core.arrays.interval import IntervalArray, _interval_shared_docs\nimport pandas.core.common as com\nimport pandas.core.indexes.base as ibase\nfrom pandas.core.indexes.base import (\n Index,\n InvalidIndexError,\n _index_shared_docs,\n default_pprint,\n ensure_index,\n maybe_extract_name,\n)\nfrom pandas.core.indexes.datetimes import DatetimeIndex, date_range\nfrom pandas.core.indexes.extension import ExtensionIndex, inherit_names\nfrom pandas.core.indexes.multi import MultiIndex\nfrom pandas.core.indexes.timedeltas import TimedeltaIndex, timedelta_range\nfrom pandas.core.ops import get_op_result_name\n\nfrom pandas.tseries.frequencies import to_offset\nfrom pandas.tseries.offsets import DateOffset\n\n_VALID_CLOSED = {\"left\", \"right\", \"both\", \"neither\"}\n_index_doc_kwargs = dict(ibase._index_doc_kwargs)\n\n_index_doc_kwargs.update(\n dict(\n klass=\"IntervalIndex\",\n qualname=\"IntervalIndex\",\n target_klass=\"IntervalIndex or list of Intervals\",\n name=textwrap.dedent(\n \"\"\"\\\n name : object, optional\n Name to be stored in the index.\n \"\"\"\n ),\n )\n)\n\n\ndef _get_next_label(label):\n dtype = getattr(label, \"dtype\", type(label))\n if isinstance(label, (Timestamp, Timedelta)):\n dtype = \"datetime64\"\n if is_datetime_or_timedelta_dtype(dtype) or is_datetime64tz_dtype(dtype):\n return label + np.timedelta64(1, \"ns\")\n elif is_integer_dtype(dtype):\n return label + 1\n elif is_float_dtype(dtype):\n return np.nextafter(label, np.infty)\n else:\n raise TypeError(f\"cannot determine next label for type {repr(type(label))}\")\n\n\ndef _get_prev_label(label):\n dtype = getattr(label, \"dtype\", type(label))\n if isinstance(label, (Timestamp, Timedelta)):\n dtype = \"datetime64\"\n if is_datetime_or_timedelta_dtype(dtype) or is_datetime64tz_dtype(dtype):\n return label - np.timedelta64(1, \"ns\")\n elif is_integer_dtype(dtype):\n return label - 1\n elif is_float_dtype(dtype):\n return np.nextafter(label, -np.infty)\n else:\n raise TypeError(f\"cannot determine next label for type {repr(type(label))}\")\n\n\ndef _new_IntervalIndex(cls, d):\n \"\"\"\n This is called upon unpickling, rather than the default which doesn't have\n arguments and breaks __new__.\n \"\"\"\n return cls.from_arrays(**d)\n\n\nclass SetopCheck:\n \"\"\"\n This is called to decorate the set operations of IntervalIndex\n to perform the type check in advance.\n \"\"\"\n\n def __init__(self, op_name):\n self.op_name = op_name\n\n def __call__(self, setop):\n def func(intvidx_self, other, sort=False):\n intvidx_self._assert_can_do_setop(other)\n other = ensure_index(other)\n\n if not isinstance(other, IntervalIndex):\n result = getattr(intvidx_self.astype(object), self.op_name)(other)\n if self.op_name in (\"difference\",):\n result = result.astype(intvidx_self.dtype)\n return result\n elif intvidx_self.closed != other.closed:\n raise ValueError(\n \"can only do set operations between two IntervalIndex \"\n \"objects that are closed on the same side\"\n )\n\n # GH 19016: ensure set op will not return a prohibited dtype\n subtypes = [intvidx_self.dtype.subtype, other.dtype.subtype]\n common_subtype = find_common_type(subtypes)\n if is_object_dtype(common_subtype):\n raise TypeError(\n f\"can only do {self.op_name} between two IntervalIndex \"\n \"objects that have compatible dtypes\"\n )\n\n return setop(intvidx_self, other, sort)\n\n return func\n\n\n@Appender(\n _interval_shared_docs[\"class\"]\n % dict(\n klass=\"IntervalIndex\",\n summary=\"Immutable index of intervals that are closed on the same side.\",\n name=_index_doc_kwargs[\"name\"],\n versionadded=\"0.20.0\",\n extra_attributes=\"is_overlapping\\nvalues\\n\",\n extra_methods=\"\",\n examples=textwrap.dedent(\n \"\"\"\\\n Examples\n --------\n A new ``IntervalIndex`` is typically constructed using\n :func:`interval_range`:\n\n >>> pd.interval_range(start=0, end=5)\n IntervalIndex([(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]],\n closed='right',\n dtype='interval[int64]')\n\n It may also be constructed using one of the constructor\n methods: :meth:`IntervalIndex.from_arrays`,\n :meth:`IntervalIndex.from_breaks`, and :meth:`IntervalIndex.from_tuples`.\n\n See further examples in the doc strings of ``interval_range`` and the\n mentioned constructor methods.\n \"\"\"\n ),\n )\n)\[email protected]_names(\n delegate=IntervalArray,\n accessors=[\"length\", \"size\", \"left\", \"right\", \"mid\", \"closed\", \"dtype\"],\n typ=\"property\",\n overwrite=True,\n)\[email protected]_names(\n delegate=IntervalArray,\n accessors=[\n \"__array__\",\n \"overlaps\",\n \"contains\",\n \"__len__\",\n \"set_closed\",\n \"to_tuples\",\n ],\n typ=\"method\",\n overwrite=True,\n)\n@inherit_names(\n [\"is_non_overlapping_monotonic\", \"mid\", \"_ndarray_values\"],\n IntervalArray,\n cache=True,\n)\nclass IntervalIndex(IntervalMixin, ExtensionIndex, accessor.PandasDelegate):\n _typ = \"intervalindex\"\n _comparables = [\"name\"]\n _attributes = [\"name\", \"closed\"]\n\n # we would like our indexing holder to defer to us\n _defer_to_indexing = True\n\n # Immutable, so we are able to cache computations like isna in '_mask'\n _mask = None\n\n _raw_inherit = {\"__array__\", \"overlaps\", \"contains\"}\n\n # --------------------------------------------------------------------\n # Constructors\n\n def __new__(\n cls,\n data,\n closed=None,\n dtype=None,\n copy: bool = False,\n name=None,\n verify_integrity: bool = True,\n ):\n\n name = maybe_extract_name(name, data, cls)\n\n with rewrite_exception(\"IntervalArray\", cls.__name__):\n array = IntervalArray(\n data,\n closed=closed,\n copy=copy,\n dtype=dtype,\n verify_integrity=verify_integrity,\n )\n\n return cls._simple_new(array, name)\n\n @classmethod\n def _simple_new(cls, array, name, closed=None):\n \"\"\"\n Construct from an IntervalArray\n\n Parameters\n ----------\n array : IntervalArray\n name : str\n Attached as result.name\n closed : Any\n Ignored.\n \"\"\"\n result = IntervalMixin.__new__(cls)\n result._data = array\n result.name = name\n result._no_setting_name = False\n result._reset_identity()\n return result\n\n @classmethod\n @Appender(\n _interval_shared_docs[\"from_breaks\"]\n % dict(\n klass=\"IntervalIndex\",\n examples=textwrap.dedent(\n \"\"\"\\\n Examples\n --------\n >>> pd.IntervalIndex.from_breaks([0, 1, 2, 3])\n IntervalIndex([(0, 1], (1, 2], (2, 3]],\n closed='right',\n dtype='interval[int64]')\n \"\"\"\n ),\n )\n )\n def from_breaks(\n cls, breaks, closed: str = \"right\", name=None, copy: bool = False, dtype=None\n ):\n with rewrite_exception(\"IntervalArray\", cls.__name__):\n array = IntervalArray.from_breaks(\n breaks, closed=closed, copy=copy, dtype=dtype\n )\n return cls._simple_new(array, name=name)\n\n @classmethod\n @Appender(\n _interval_shared_docs[\"from_arrays\"]\n % dict(\n klass=\"IntervalIndex\",\n examples=textwrap.dedent(\n \"\"\"\\\n Examples\n --------\n >>> pd.IntervalIndex.from_arrays([0, 1, 2], [1, 2, 3])\n IntervalIndex([(0, 1], (1, 2], (2, 3]],\n closed='right',\n dtype='interval[int64]')\n \"\"\"\n ),\n )\n )\n def from_arrays(\n cls,\n left,\n right,\n closed: str = \"right\",\n name=None,\n copy: bool = False,\n dtype=None,\n ):\n with rewrite_exception(\"IntervalArray\", cls.__name__):\n array = IntervalArray.from_arrays(\n left, right, closed, copy=copy, dtype=dtype\n )\n return cls._simple_new(array, name=name)\n\n @classmethod\n @Appender(\n _interval_shared_docs[\"from_tuples\"]\n % dict(\n klass=\"IntervalIndex\",\n examples=textwrap.dedent(\n \"\"\"\\\n Examples\n --------\n >>> pd.IntervalIndex.from_tuples([(0, 1), (1, 2)])\n IntervalIndex([(0, 1], (1, 2]],\n closed='right',\n dtype='interval[int64]')\n \"\"\"\n ),\n )\n )\n def from_tuples(\n cls, data, closed: str = \"right\", name=None, copy: bool = False, dtype=None\n ):\n with rewrite_exception(\"IntervalArray\", cls.__name__):\n arr = IntervalArray.from_tuples(data, closed=closed, copy=copy, dtype=dtype)\n return cls._simple_new(arr, name=name)\n\n # --------------------------------------------------------------------\n\n @Appender(_index_shared_docs[\"_shallow_copy\"])\n def _shallow_copy(self, left=None, right=None, **kwargs):\n result = self._data._shallow_copy(left=left, right=right)\n attributes = self._get_attributes_dict()\n attributes.update(kwargs)\n return self._simple_new(result, **attributes)\n\n @cache_readonly\n def _isnan(self):\n \"\"\"\n Return a mask indicating if each value is NA.\n \"\"\"\n if self._mask is None:\n self._mask = isna(self.left)\n return self._mask\n\n @cache_readonly\n def _engine(self):\n left = self._maybe_convert_i8(self.left)\n right = self._maybe_convert_i8(self.right)\n return IntervalTree(left, right, closed=self.closed)\n\n def __contains__(self, key) -> bool:\n \"\"\"\n return a boolean if this key is IN the index\n We *only* accept an Interval\n\n Parameters\n ----------\n key : Interval\n\n Returns\n -------\n bool\n \"\"\"\n if not isinstance(key, Interval):\n return False\n\n try:\n self.get_loc(key)\n return True\n except KeyError:\n return False\n\n @cache_readonly\n def _multiindex(self):\n return MultiIndex.from_arrays([self.left, self.right], names=[\"left\", \"right\"])\n\n @cache_readonly\n def values(self):\n \"\"\"\n Return the IntervalIndex's data as an IntervalArray.\n \"\"\"\n return self._data\n\n @cache_readonly\n def _values(self):\n return self._data\n\n def __array_wrap__(self, result, context=None):\n # we don't want the superclass implementation\n return result\n\n def __reduce__(self):\n d = dict(left=self.left, right=self.right)\n d.update(self._get_attributes_dict())\n return _new_IntervalIndex, (type(self), d), None\n\n @Appender(_index_shared_docs[\"astype\"])\n def astype(self, dtype, copy=True):\n with rewrite_exception(\"IntervalArray\", type(self).__name__):\n new_values = self.values.astype(dtype, copy=copy)\n if is_interval_dtype(new_values):\n return self._shallow_copy(new_values.left, new_values.right)\n return Index.astype(self, dtype, copy=copy)\n\n @property\n def inferred_type(self) -> str:\n \"\"\"Return a string of the type inferred from the values\"\"\"\n return \"interval\"\n\n @Appender(Index.memory_usage.__doc__)\n def memory_usage(self, deep: bool = False) -> int:\n # we don't use an explicit engine\n # so return the bytes here\n return self.left.memory_usage(deep=deep) + self.right.memory_usage(deep=deep)\n\n # IntervalTree doesn't have a is_monotonic_decreasing, so have to override\n # the Index implemenation\n @cache_readonly\n def is_monotonic_decreasing(self) -> bool:\n \"\"\"\n Return True if the IntervalIndex is monotonic decreasing (only equal or\n decreasing values), else False\n \"\"\"\n return self[::-1].is_monotonic_increasing\n\n @cache_readonly\n def is_unique(self):\n \"\"\"\n Return True if the IntervalIndex contains unique elements, else False.\n \"\"\"\n left = self.left\n right = self.right\n\n if self.isna().sum() > 1:\n return False\n\n if left.is_unique or right.is_unique:\n return True\n\n seen_pairs = set()\n check_idx = np.where(left.duplicated(keep=False))[0]\n for idx in check_idx:\n pair = (left[idx], right[idx])\n if pair in seen_pairs:\n return False\n seen_pairs.add(pair)\n\n return True\n\n @property\n def is_overlapping(self):\n \"\"\"\n Return True if the IntervalIndex has overlapping intervals, else False.\n\n Two intervals overlap if they share a common point, including closed\n endpoints. Intervals that only have an open endpoint in common do not\n overlap.\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n bool\n Boolean indicating if the IntervalIndex has overlapping intervals.\n\n See Also\n --------\n Interval.overlaps : Check whether two Interval objects overlap.\n IntervalIndex.overlaps : Check an IntervalIndex elementwise for\n overlaps.\n\n Examples\n --------\n >>> index = pd.IntervalIndex.from_tuples([(0, 2), (1, 3), (4, 5)])\n >>> index\n IntervalIndex([(0, 2], (1, 3], (4, 5]],\n closed='right',\n dtype='interval[int64]')\n >>> index.is_overlapping\n True\n\n Intervals that share closed endpoints overlap:\n\n >>> index = pd.interval_range(0, 3, closed='both')\n >>> index\n IntervalIndex([[0, 1], [1, 2], [2, 3]],\n closed='both',\n dtype='interval[int64]')\n >>> index.is_overlapping\n True\n\n Intervals that only have an open endpoint in common do not overlap:\n\n >>> index = pd.interval_range(0, 3, closed='left')\n >>> index\n IntervalIndex([[0, 1), [1, 2), [2, 3)],\n closed='left',\n dtype='interval[int64]')\n >>> index.is_overlapping\n False\n \"\"\"\n # GH 23309\n return self._engine.is_overlapping\n\n @Appender(_index_shared_docs[\"_convert_scalar_indexer\"])\n def _convert_scalar_indexer(self, key, kind=None):\n if kind == \"iloc\":\n return super()._convert_scalar_indexer(key, kind=kind)\n return key\n\n def _maybe_cast_slice_bound(self, label, side, kind):\n return getattr(self, side)._maybe_cast_slice_bound(label, side, kind)\n\n @Appender(_index_shared_docs[\"_convert_list_indexer\"])\n def _convert_list_indexer(self, keyarr, kind=None):\n \"\"\"\n we are passed a list-like indexer. Return the\n indexer for matching intervals.\n \"\"\"\n locs = self.get_indexer_for(keyarr)\n\n # we have missing values\n if (locs == -1).any():\n raise KeyError\n\n return locs\n\n def _can_reindex(self, indexer: np.ndarray) -> None:\n \"\"\"\n Check if we are allowing reindexing with this particular indexer.\n\n Parameters\n ----------\n indexer : an integer indexer\n\n Raises\n ------\n ValueError if its a duplicate axis\n \"\"\"\n\n # trying to reindex on an axis with duplicates\n if self.is_overlapping and len(indexer):\n raise ValueError(\"cannot reindex from an overlapping axis\")\n\n def _needs_i8_conversion(self, key):\n \"\"\"\n Check if a given key needs i8 conversion. Conversion is necessary for\n Timestamp, Timedelta, DatetimeIndex, and TimedeltaIndex keys. An\n Interval-like requires conversion if it's endpoints are one of the\n aforementioned types.\n\n Assumes that any list-like data has already been cast to an Index.\n\n Parameters\n ----------\n key : scalar or Index-like\n The key that should be checked for i8 conversion\n\n Returns\n -------\n bool\n \"\"\"\n if is_interval_dtype(key) or isinstance(key, Interval):\n return self._needs_i8_conversion(key.left)\n\n i8_types = (Timestamp, Timedelta, DatetimeIndex, TimedeltaIndex)\n return isinstance(key, i8_types)\n\n def _maybe_convert_i8(self, key):\n \"\"\"\n Maybe convert a given key to it's equivalent i8 value(s). Used as a\n preprocessing step prior to IntervalTree queries (self._engine), which\n expects numeric data.\n\n Parameters\n ----------\n key : scalar or list-like\n The key that should maybe be converted to i8.\n\n Returns\n -------\n scalar or list-like\n The original key if no conversion occurred, int if converted scalar,\n Int64Index if converted list-like.\n \"\"\"\n original = key\n if is_list_like(key):\n key = ensure_index(key)\n\n if not self._needs_i8_conversion(key):\n return original\n\n scalar = is_scalar(key)\n if is_interval_dtype(key) or isinstance(key, Interval):\n # convert left/right and reconstruct\n left = self._maybe_convert_i8(key.left)\n right = self._maybe_convert_i8(key.right)\n constructor = Interval if scalar else IntervalIndex.from_arrays\n return constructor(left, right, closed=self.closed)\n\n if scalar:\n # Timestamp/Timedelta\n key_dtype, key_i8 = infer_dtype_from_scalar(key, pandas_dtype=True)\n else:\n # DatetimeIndex/TimedeltaIndex\n key_dtype, key_i8 = key.dtype, Index(key.asi8)\n if key.hasnans:\n # convert NaT from it's i8 value to np.nan so it's not viewed\n # as a valid value, maybe causing errors (e.g. is_overlapping)\n key_i8 = key_i8.where(~key._isnan)\n\n # ensure consistency with IntervalIndex subtype\n subtype = self.dtype.subtype\n\n if not is_dtype_equal(subtype, key_dtype):\n raise ValueError(\n f\"Cannot index an IntervalIndex of subtype {subtype} with \"\n f\"values of dtype {key_dtype}\"\n )\n\n return key_i8\n\n def _check_method(self, method):\n if method is None:\n return\n\n if method in [\"bfill\", \"backfill\", \"pad\", \"ffill\", \"nearest\"]:\n raise NotImplementedError(\n f\"method {method} not yet implemented for IntervalIndex\"\n )\n\n raise ValueError(\"Invalid fill method\")\n\n def _searchsorted_monotonic(self, label, side, exclude_label=False):\n if not self.is_non_overlapping_monotonic:\n raise KeyError(\n \"can only get slices from an IntervalIndex if bounds are \"\n \"non-overlapping and all monotonic increasing or decreasing\"\n )\n\n if isinstance(label, IntervalMixin):\n raise NotImplementedError(\"Interval objects are not currently supported\")\n\n # GH 20921: \"not is_monotonic_increasing\" for the second condition\n # instead of \"is_monotonic_decreasing\" to account for single element\n # indexes being both increasing and decreasing\n if (side == \"left\" and self.left.is_monotonic_increasing) or (\n side == \"right\" and not self.left.is_monotonic_increasing\n ):\n sub_idx = self.right\n if self.open_right or exclude_label:\n label = _get_next_label(label)\n else:\n sub_idx = self.left\n if self.open_left or exclude_label:\n label = _get_prev_label(label)\n\n return sub_idx._searchsorted_monotonic(label, side)\n\n def get_loc(\n self, key: Any, method: Optional[str] = None, tolerance=None\n ) -> Union[int, slice, np.ndarray]:\n \"\"\"\n Get integer location, slice or boolean mask for requested label.\n\n Parameters\n ----------\n key : label\n method : {None}, optional\n * default: matches where the label is within an interval only.\n\n Returns\n -------\n int if unique index, slice if monotonic index, else mask\n\n Examples\n --------\n >>> i1, i2 = pd.Interval(0, 1), pd.Interval(1, 2)\n >>> index = pd.IntervalIndex([i1, i2])\n >>> index.get_loc(1)\n 0\n\n You can also supply a point inside an interval.\n\n >>> index.get_loc(1.5)\n 1\n\n If a label is in several intervals, you get the locations of all the\n relevant intervals.\n\n >>> i3 = pd.Interval(0, 2)\n >>> overlapping_index = pd.IntervalIndex([i1, i2, i3])\n >>> overlapping_index.get_loc(0.5)\n array([ True, False, True])\n\n Only exact matches will be returned if an interval is provided.\n\n >>> index.get_loc(pd.Interval(0, 1))\n 0\n \"\"\"\n self._check_method(method)\n\n # list-like are invalid labels for II but in some cases may work, e.g\n # single element array of comparable type, so guard against them early\n if is_list_like(key):\n raise KeyError(key)\n\n if isinstance(key, Interval):\n if self.closed != key.closed:\n raise KeyError(key)\n mask = (self.left == key.left) & (self.right == key.right)\n else:\n # assume scalar\n op_left = le if self.closed_left else lt\n op_right = le if self.closed_right else lt\n try:\n mask = op_left(self.left, key) & op_right(key, self.right)\n except TypeError:\n # scalar is not comparable to II subtype --> invalid label\n raise KeyError(key)\n\n matches = mask.sum()\n if matches == 0:\n raise KeyError(key)\n elif matches == 1:\n return mask.argmax()\n return lib.maybe_booleans_to_slice(mask.view(\"u1\"))\n\n @Substitution(\n **dict(\n _index_doc_kwargs,\n **{\n \"raises_section\": textwrap.dedent(\n \"\"\"\n Raises\n ------\n NotImplementedError\n If any method argument other than the default of\n None is specified as these are not yet implemented.\n \"\"\"\n )\n },\n )\n )\n @Appender(_index_shared_docs[\"get_indexer\"])\n def get_indexer(\n self,\n target: AnyArrayLike,\n method: Optional[str] = None,\n limit: Optional[int] = None,\n tolerance: Optional[Any] = None,\n ) -> np.ndarray:\n\n self._check_method(method)\n\n if self.is_overlapping:\n raise InvalidIndexError(\n \"cannot handle overlapping indices; \"\n \"use IntervalIndex.get_indexer_non_unique\"\n )\n\n target_as_index = ensure_index(target)\n\n if isinstance(target_as_index, IntervalIndex):\n # equal indexes -> 1:1 positional match\n if self.equals(target_as_index):\n return np.arange(len(self), dtype=\"intp\")\n\n # different closed or incompatible subtype -> no matches\n common_subtype = find_common_type(\n [self.dtype.subtype, target_as_index.dtype.subtype]\n )\n if self.closed != target_as_index.closed or is_object_dtype(common_subtype):\n return np.repeat(np.intp(-1), len(target_as_index))\n\n # non-overlapping -> at most one match per interval in target_as_index\n # want exact matches -> need both left/right to match, so defer to\n # left/right get_indexer, compare elementwise, equality -> match\n left_indexer = self.left.get_indexer(target_as_index.left)\n right_indexer = self.right.get_indexer(target_as_index.right)\n indexer = np.where(left_indexer == right_indexer, left_indexer, -1)\n elif is_categorical(target_as_index):\n # get an indexer for unique categories then propagate to codes via take_1d\n categories_indexer = self.get_indexer(target_as_index.categories)\n indexer = take_1d(categories_indexer, target_as_index.codes, fill_value=-1)\n elif not is_object_dtype(target_as_index):\n # homogeneous scalar index: use IntervalTree\n target_as_index = self._maybe_convert_i8(target_as_index)\n indexer = self._engine.get_indexer(target_as_index.values)\n else:\n # heterogeneous scalar index: defer elementwise to get_loc\n # (non-overlapping so get_loc guarantees scalar of KeyError)\n indexer = []\n for key in target_as_index:\n try:\n loc = self.get_loc(key)\n except KeyError:\n loc = -1\n indexer.append(loc)\n\n return ensure_platform_int(indexer)\n\n @Appender(_index_shared_docs[\"get_indexer_non_unique\"] % _index_doc_kwargs)\n def get_indexer_non_unique(\n self, target: AnyArrayLike\n ) -> Tuple[np.ndarray, np.ndarray]:\n target_as_index = ensure_index(target)\n\n # check that target_as_index IntervalIndex is compatible\n if isinstance(target_as_index, IntervalIndex):\n common_subtype = find_common_type(\n [self.dtype.subtype, target_as_index.dtype.subtype]\n )\n if self.closed != target_as_index.closed or is_object_dtype(common_subtype):\n # different closed or incompatible subtype -> no matches\n return (\n np.repeat(-1, len(target_as_index)),\n np.arange(len(target_as_index)),\n )\n\n if is_object_dtype(target_as_index) or isinstance(\n target_as_index, IntervalIndex\n ):\n # target_as_index might contain intervals: defer elementwise to get_loc\n indexer, missing = [], []\n for i, key in enumerate(target_as_index):\n try:\n locs = self.get_loc(key)\n if isinstance(locs, slice):\n locs = np.arange(locs.start, locs.stop, locs.step, dtype=\"intp\")\n locs = np.array(locs, ndmin=1)\n except KeyError:\n missing.append(i)\n locs = np.array([-1])\n indexer.append(locs)\n indexer = np.concatenate(indexer)\n else:\n target_as_index = self._maybe_convert_i8(target_as_index)\n indexer, missing = self._engine.get_indexer_non_unique(\n target_as_index.values\n )\n\n return ensure_platform_int(indexer), ensure_platform_int(missing)\n\n def get_indexer_for(self, target: AnyArrayLike, **kwargs) -> np.ndarray:\n \"\"\"\n Guaranteed return of an indexer even when overlapping.\n\n This dispatches to get_indexer or get_indexer_non_unique\n as appropriate.\n\n Returns\n -------\n numpy.ndarray\n List of indices.\n \"\"\"\n if self.is_overlapping:\n return self.get_indexer_non_unique(target)[0]\n return self.get_indexer(target, **kwargs)\n\n @Appender(_index_shared_docs[\"get_value\"] % _index_doc_kwargs)\n def get_value(self, series: ABCSeries, key: Any) -> Any:\n\n if com.is_bool_indexer(key):\n loc = key\n elif is_list_like(key):\n if self.is_overlapping:\n loc, missing = self.get_indexer_non_unique(key)\n if len(missing):\n raise KeyError\n else:\n loc = self.get_indexer(key)\n elif isinstance(key, slice):\n if not (key.step is None or key.step == 1):\n raise ValueError(\"cannot support not-default step in a slice\")\n loc = self._convert_slice_indexer(key, kind=\"getitem\")\n else:\n loc = self.get_loc(key)\n return series.iloc[loc]\n\n @Appender(_index_shared_docs[\"where\"])\n def where(self, cond, other=None):\n if other is None:\n other = self._na_value\n values = np.where(cond, self.values, other)\n return self._shallow_copy(values)\n\n def delete(self, loc):\n \"\"\"\n Return a new IntervalIndex with passed location(-s) deleted\n\n Returns\n -------\n IntervalIndex\n \"\"\"\n new_left = self.left.delete(loc)\n new_right = self.right.delete(loc)\n return self._shallow_copy(new_left, new_right)\n\n def insert(self, loc, item):\n \"\"\"\n Return a new IntervalIndex inserting new item at location. Follows\n Python list.append semantics for negative values. Only Interval\n objects and NA can be inserted into an IntervalIndex\n\n Parameters\n ----------\n loc : int\n item : object\n\n Returns\n -------\n IntervalIndex\n \"\"\"\n if isinstance(item, Interval):\n if item.closed != self.closed:\n raise ValueError(\n \"inserted item must be closed on the same side as the index\"\n )\n left_insert = item.left\n right_insert = item.right\n elif is_scalar(item) and isna(item):\n # GH 18295\n left_insert = right_insert = item\n else:\n raise ValueError(\n \"can only insert Interval objects and NA into an IntervalIndex\"\n )\n\n new_left = self.left.insert(loc, left_insert)\n new_right = self.right.insert(loc, right_insert)\n return self._shallow_copy(new_left, new_right)\n\n def _concat_same_dtype(self, to_concat, name):\n \"\"\"\n assert that we all have the same .closed\n we allow a 0-len index here as well\n \"\"\"\n if not len({i.closed for i in to_concat if len(i)}) == 1:\n raise ValueError(\n \"can only append two IntervalIndex objects \"\n \"that are closed on the same side\"\n )\n return super()._concat_same_dtype(to_concat, name)\n\n @Appender(_index_shared_docs[\"take\"] % _index_doc_kwargs)\n def take(self, indices, axis=0, allow_fill=True, fill_value=None, **kwargs):\n result = self._data.take(\n indices, axis=axis, allow_fill=allow_fill, fill_value=fill_value, **kwargs\n )\n return self._shallow_copy(result)\n\n def __getitem__(self, value):\n result = self._data[value]\n if isinstance(result, IntervalArray):\n return self._shallow_copy(result)\n else:\n # scalar\n return result\n\n # --------------------------------------------------------------------\n # Rendering Methods\n # __repr__ associated methods are based on MultiIndex\n\n def _format_with_header(self, header, **kwargs):\n return header + list(self._format_native_types(**kwargs))\n\n def _format_native_types(self, na_rep=\"NaN\", quoting=None, **kwargs):\n # GH 28210: use base method but with different default na_rep\n return super()._format_native_types(na_rep=na_rep, quoting=quoting, **kwargs)\n\n def _format_data(self, name=None):\n\n # TODO: integrate with categorical and make generic\n # name argument is unused here; just for compat with base / categorical\n n = len(self)\n max_seq_items = min((get_option(\"display.max_seq_items\") or n) // 10, 10)\n\n formatter = str\n\n if n == 0:\n summary = \"[]\"\n elif n == 1:\n first = formatter(self[0])\n summary = f\"[{first}]\"\n elif n == 2:\n first = formatter(self[0])\n last = formatter(self[-1])\n summary = f\"[{first}, {last}]\"\n else:\n\n if n > max_seq_items:\n n = min(max_seq_items // 2, 10)\n head = [formatter(x) for x in self[:n]]\n tail = [formatter(x) for x in self[-n:]]\n head_joined = \", \".join(head)\n tail_joined = \", \".join(tail)\n summary = f\"[{head_joined} ... {tail_joined}]\"\n else:\n tail = [formatter(x) for x in self]\n joined = \", \".join(tail)\n summary = f\"[{joined}]\"\n\n return summary + \",\" + self._format_space()\n\n def _format_attrs(self):\n attrs = [(\"closed\", repr(self.closed))]\n if self.name is not None:\n attrs.append((\"name\", default_pprint(self.name)))\n attrs.append((\"dtype\", f\"'{self.dtype}'\"))\n return attrs\n\n def _format_space(self) -> str:\n space = \" \" * (len(type(self).__name__) + 1)\n return f\"\\n{space}\"\n\n # --------------------------------------------------------------------\n\n def argsort(self, *args, **kwargs):\n return np.lexsort((self.right, self.left))\n\n def equals(self, other) -> bool:\n \"\"\"\n Determines if two IntervalIndex objects contain the same elements.\n \"\"\"\n if self.is_(other):\n return True\n\n # if we can coerce to an II\n # then we can compare\n if not isinstance(other, IntervalIndex):\n if not is_interval_dtype(other):\n return False\n other = Index(getattr(other, \".values\", other))\n\n return (\n self.left.equals(other.left)\n and self.right.equals(other.right)\n and self.closed == other.closed\n )\n\n @Appender(_index_shared_docs[\"intersection\"])\n @SetopCheck(op_name=\"intersection\")\n def intersection(\n self, other: \"IntervalIndex\", sort: bool = False\n ) -> \"IntervalIndex\":\n if self.left.is_unique and self.right.is_unique:\n taken = self._intersection_unique(other)\n elif other.left.is_unique and other.right.is_unique and self.isna().sum() <= 1:\n # Swap other/self if other is unique and self does not have\n # multiple NaNs\n taken = other._intersection_unique(self)\n else:\n # duplicates\n taken = self._intersection_non_unique(other)\n\n if sort is None:\n taken = taken.sort_values()\n\n return taken\n\n def _intersection_unique(self, other: \"IntervalIndex\") -> \"IntervalIndex\":\n \"\"\"\n Used when the IntervalIndex does not have any common endpoint,\n no mater left or right.\n Return the intersection with another IntervalIndex.\n\n Parameters\n ----------\n other : IntervalIndex\n\n Returns\n -------\n IntervalIndex\n \"\"\"\n lindexer = self.left.get_indexer(other.left)\n rindexer = self.right.get_indexer(other.right)\n\n match = (lindexer == rindexer) & (lindexer != -1)\n indexer = lindexer.take(match.nonzero()[0])\n\n return self.take(indexer)\n\n def _intersection_non_unique(self, other: \"IntervalIndex\") -> \"IntervalIndex\":\n \"\"\"\n Used when the IntervalIndex does have some common endpoints,\n on either sides.\n Return the intersection with another IntervalIndex.\n\n Parameters\n ----------\n other : IntervalIndex\n\n Returns\n -------\n IntervalIndex\n \"\"\"\n mask = np.zeros(len(self), dtype=bool)\n\n if self.hasnans and other.hasnans:\n first_nan_loc = np.arange(len(self))[self.isna()][0]\n mask[first_nan_loc] = True\n\n other_tups = set(zip(other.left, other.right))\n for i, tup in enumerate(zip(self.left, self.right)):\n if tup in other_tups:\n mask[i] = True\n\n return self[mask]\n\n def _setop(op_name: str, sort=None):\n @SetopCheck(op_name=op_name)\n def func(self, other, sort=sort):\n result = getattr(self._multiindex, op_name)(other._multiindex, sort=sort)\n result_name = get_op_result_name(self, other)\n\n # GH 19101: ensure empty results have correct dtype\n if result.empty:\n result = result.values.astype(self.dtype.subtype)\n else:\n result = result.values\n\n return type(self).from_tuples(result, closed=self.closed, name=result_name)\n\n return func\n\n @property\n def is_all_dates(self) -> bool:\n \"\"\"\n This is False even when left/right contain datetime-like objects,\n as the check is done on the Interval itself\n \"\"\"\n return False\n\n union = _setop(\"union\")\n difference = _setop(\"difference\")\n symmetric_difference = _setop(\"symmetric_difference\")\n\n # TODO: arithmetic operations\n\n def _delegate_property_get(self, name, *args, **kwargs):\n \"\"\" method delegation to the ._values \"\"\"\n prop = getattr(self._data, name)\n return prop # no wrapping for now\n\n def _delegate_method(self, name, *args, **kwargs):\n \"\"\" method delegation to the ._data \"\"\"\n method = getattr(self._data, name)\n res = method(*args, **kwargs)\n if is_scalar(res) or name in self._raw_inherit:\n return res\n if isinstance(res, IntervalArray):\n return type(self)._simple_new(res, name=self.name)\n return Index(res)\n\n # GH#30817 until IntervalArray implements inequalities, get them from Index\n def __lt__(self, other):\n return Index.__lt__(self, other)\n\n def __le__(self, other):\n return Index.__le__(self, other)\n\n def __gt__(self, other):\n return Index.__gt__(self, other)\n\n def __ge__(self, other):\n return Index.__ge__(self, other)\n\n\nIntervalIndex._add_logical_methods_disabled()\n\n\ndef _is_valid_endpoint(endpoint) -> bool:\n \"\"\"\n Helper for interval_range to check if start/end are valid types.\n \"\"\"\n return any(\n [\n is_number(endpoint),\n isinstance(endpoint, Timestamp),\n isinstance(endpoint, Timedelta),\n endpoint is None,\n ]\n )\n\n\ndef _is_type_compatible(a, b) -> bool:\n \"\"\"\n Helper for interval_range to check type compat of start/end/freq.\n \"\"\"\n is_ts_compat = lambda x: isinstance(x, (Timestamp, DateOffset))\n is_td_compat = lambda x: isinstance(x, (Timedelta, DateOffset))\n return (\n (is_number(a) and is_number(b))\n or (is_ts_compat(a) and is_ts_compat(b))\n or (is_td_compat(a) and is_td_compat(b))\n or com.any_none(a, b)\n )\n\n\ndef interval_range(\n start=None, end=None, periods=None, freq=None, name=None, closed=\"right\"\n):\n \"\"\"\n Return a fixed frequency IntervalIndex.\n\n Parameters\n ----------\n start : numeric or datetime-like, default None\n Left bound for generating intervals.\n end : numeric or datetime-like, default None\n Right bound for generating intervals.\n periods : int, default None\n Number of periods to generate.\n freq : numeric, str, or DateOffset, default None\n The length of each interval. Must be consistent with the type of start\n and end, e.g. 2 for numeric, or '5H' for datetime-like. Default is 1\n for numeric and 'D' for datetime-like.\n name : str, default None\n Name of the resulting IntervalIndex.\n closed : {'left', 'right', 'both', 'neither'}, default 'right'\n Whether the intervals are closed on the left-side, right-side, both\n or neither.\n\n Returns\n -------\n IntervalIndex\n\n See Also\n --------\n IntervalIndex : An Index of intervals that are all closed on the same side.\n\n Notes\n -----\n Of the four parameters ``start``, ``end``, ``periods``, and ``freq``,\n exactly three must be specified. If ``freq`` is omitted, the resulting\n ``IntervalIndex`` will have ``periods`` linearly spaced elements between\n ``start`` and ``end``, inclusively.\n\n To learn more about datetime-like frequency strings, please see `this link\n <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases>`__.\n\n Examples\n --------\n Numeric ``start`` and ``end`` is supported.\n\n >>> pd.interval_range(start=0, end=5)\n IntervalIndex([(0, 1], (1, 2], (2, 3], (3, 4], (4, 5]],\n closed='right', dtype='interval[int64]')\n\n Additionally, datetime-like input is also supported.\n\n >>> pd.interval_range(start=pd.Timestamp('2017-01-01'),\n ... end=pd.Timestamp('2017-01-04'))\n IntervalIndex([(2017-01-01, 2017-01-02], (2017-01-02, 2017-01-03],\n (2017-01-03, 2017-01-04]],\n closed='right', dtype='interval[datetime64[ns]]')\n\n The ``freq`` parameter specifies the frequency between the left and right.\n endpoints of the individual intervals within the ``IntervalIndex``. For\n numeric ``start`` and ``end``, the frequency must also be numeric.\n\n >>> pd.interval_range(start=0, periods=4, freq=1.5)\n IntervalIndex([(0.0, 1.5], (1.5, 3.0], (3.0, 4.5], (4.5, 6.0]],\n closed='right', dtype='interval[float64]')\n\n Similarly, for datetime-like ``start`` and ``end``, the frequency must be\n convertible to a DateOffset.\n\n >>> pd.interval_range(start=pd.Timestamp('2017-01-01'),\n ... periods=3, freq='MS')\n IntervalIndex([(2017-01-01, 2017-02-01], (2017-02-01, 2017-03-01],\n (2017-03-01, 2017-04-01]],\n closed='right', dtype='interval[datetime64[ns]]')\n\n Specify ``start``, ``end``, and ``periods``; the frequency is generated\n automatically (linearly spaced).\n\n >>> pd.interval_range(start=0, end=6, periods=4)\n IntervalIndex([(0.0, 1.5], (1.5, 3.0], (3.0, 4.5], (4.5, 6.0]],\n closed='right',\n dtype='interval[float64]')\n\n The ``closed`` parameter specifies which endpoints of the individual\n intervals within the ``IntervalIndex`` are closed.\n\n >>> pd.interval_range(end=5, periods=4, closed='both')\n IntervalIndex([[1, 2], [2, 3], [3, 4], [4, 5]],\n closed='both', dtype='interval[int64]')\n \"\"\"\n start = com.maybe_box_datetimelike(start)\n end = com.maybe_box_datetimelike(end)\n endpoint = start if start is not None else end\n\n if freq is None and com.any_none(periods, start, end):\n freq = 1 if is_number(endpoint) else \"D\"\n\n if com.count_not_none(start, end, periods, freq) != 3:\n raise ValueError(\n \"Of the four parameters: start, end, periods, and \"\n \"freq, exactly three must be specified\"\n )\n\n if not _is_valid_endpoint(start):\n raise ValueError(f\"start must be numeric or datetime-like, got {start}\")\n elif not _is_valid_endpoint(end):\n raise ValueError(f\"end must be numeric or datetime-like, got {end}\")\n\n if is_float(periods):\n periods = int(periods)\n elif not is_integer(periods) and periods is not None:\n raise TypeError(f\"periods must be a number, got {periods}\")\n\n if freq is not None and not is_number(freq):\n try:\n freq = to_offset(freq)\n except ValueError:\n raise ValueError(\n f\"freq must be numeric or convertible to DateOffset, got {freq}\"\n )\n\n # verify type compatibility\n if not all(\n [\n _is_type_compatible(start, end),\n _is_type_compatible(start, freq),\n _is_type_compatible(end, freq),\n ]\n ):\n raise TypeError(\"start, end, freq need to be type compatible\")\n\n # +1 to convert interval count to breaks count (n breaks = n-1 intervals)\n if periods is not None:\n periods += 1\n\n if is_number(endpoint):\n # force consistency between start/end/freq (lower end if freq skips it)\n if com.all_not_none(start, end, freq):\n end -= (end - start) % freq\n\n # compute the period/start/end if unspecified (at most one)\n if periods is None:\n periods = int((end - start) // freq) + 1\n elif start is None:\n start = end - (periods - 1) * freq\n elif end is None:\n end = start + (periods - 1) * freq\n\n breaks = np.linspace(start, end, periods)\n if all(is_integer(x) for x in com.not_none(start, end, freq)):\n # np.linspace always produces float output\n breaks = maybe_downcast_to_dtype(breaks, \"int64\")\n else:\n # delegate to the appropriate range function\n if isinstance(endpoint, Timestamp):\n range_func = date_range\n else:\n range_func = timedelta_range\n\n breaks = range_func(start=start, end=end, periods=periods, freq=freq)\n\n return IntervalIndex.from_breaks(breaks, name=name, closed=closed)\n" ]
[ [ "pandas.tseries.frequencies.to_offset", "numpy.linspace", "pandas.core.dtypes.common.is_dtype_equal", "pandas.core.indexes.base.Index.__le__", "pandas.core.accessor.delegate_names", "pandas.core.dtypes.common.is_datetime64tz_dtype", "pandas._libs.interval.IntervalTree", "pandas.core.indexes.base.Index", "numpy.concatenate", "pandas._config.get_option", "numpy.where", "numpy.nextafter", "pandas.core.indexes.extension.inherit_names", "pandas.core.dtypes.common.is_interval_dtype", "pandas.core.common.all_not_none", "pandas.core.common.not_none", "numpy.arange", "numpy.lexsort", "pandas.core.common.any_none", "pandas.core.indexes.base.maybe_extract_name", "pandas.core.dtypes.common.is_number", "pandas.core.ops.get_op_result_name", "pandas.core.dtypes.common.is_float_dtype", "pandas.core.dtypes.common.is_float", "pandas.core.arrays.interval.IntervalArray", "pandas.util._exceptions.rewrite_exception", "pandas.core.indexes.base.default_pprint", "pandas.core.dtypes.common.is_integer_dtype", "pandas.core.dtypes.common.is_list_like", "pandas.util._decorators.Appender", "pandas.core.dtypes.common.is_categorical", "pandas.core.common.maybe_box_datetimelike", "pandas.core.indexes.base.ensure_index", "pandas.core.dtypes.cast.infer_dtype_from_scalar", "pandas.core.indexes.base.Index.__lt__", "pandas.core.indexes.base.Index.__gt__", "numpy.timedelta64", "pandas.core.dtypes.common.ensure_platform_int", "pandas.core.arrays.interval.IntervalArray.from_tuples", "numpy.array", "pandas.core.arrays.interval.IntervalArray.from_arrays", "pandas.core.indexes.base.Index.astype", "pandas.core.common.count_not_none", "pandas.core.dtypes.cast.maybe_downcast_to_dtype", "pandas.core.common.is_bool_indexer", "pandas.core.algorithms.take_1d", "pandas.core.dtypes.common.is_scalar", "numpy.intp", "pandas.core.dtypes.common.is_integer", "pandas.core.dtypes.cast.find_common_type", "pandas.core.indexes.multi.MultiIndex.from_arrays", "pandas.core.dtypes.common.is_object_dtype", "pandas.core.indexes.base.Index.__ge__", "pandas.core.dtypes.common.is_datetime_or_timedelta_dtype", "pandas.core.dtypes.missing.isna", "pandas._libs.interval.IntervalMixin.__new__", "pandas.core.arrays.interval.IntervalArray.from_breaks", "pandas.core.indexes.base.InvalidIndexError" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "0.24", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
jcoheur/pybitup-examples
[ "83bdb2a85f8bdeed7199feaf70fa17fc68263256" ]
[ "pyrolysis/check.py" ]
[ "import sys\nsys.path.append('../../')\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport pickle\nimport pandas as pd \n\n# %% Initialisation\n\nmodel_name = \"6.1_K_per_Min\" \n\nf = open(\"output/propagation/pce_model_\"+model_name+\".pickle\",\"rb\")\nmodel = pickle.load(f)\nf.close()\n\nf = open(\"output/propagation/pce_poly_\"+model_name+\".pickle\",\"rb\")\npoly = pickle.load(f)\nf.close()\n\npoint = np.loadtxt(\"output/mcmc_chain.csv\",delimiter=\",\")\nindex = []\nresp = []\n\nfor i in range(len(point)):\n try:\n resp.append(np.load(\"output/one_reaction_pyrolysis_fun_eval.\"+str(i)+\".npy\"))\n index.append(i)\n except: pass\n\nresp = np.array(resp)\nrespMod = model.eval(point[index])\n\n# %% Monte Carlo and error\n\nvar = np.var(resp,axis=0)\nmean = np.mean(resp,axis=0)\nmeanMod = np.mean(respMod,axis=0)\nvarMod = np.var(respMod,axis=0)\n\nreader = pd.read_csv('data_pyrolysis.csv')\nxMod = reader[\"T\"].values\n\n# error = abs(np.divide(resp-respMod,resp))\n# error = 100*np.mean(error,axis=0)\n\n# %% Figures\n\nplt.figure(1)\nplt.rcParams.update({\"font.size\":16})\nplt.plot(xMod, meanMod,'C0',label=\"PCE\")\nplt.plot(xMod, mean,'C1--',label=\"MC\")\nplt.legend(prop={'size':16})\nplt.ylabel(\"Mean\")\nplt.xlabel(\"Step\")\nplt.grid()\n\nplt.figure(2)\nplt.rcParams.update({\"font.size\":16})\nplt.plot(xMod, varMod,'C0',label=\"PCE\")\nplt.plot(xMod, var,'C1--',label=\"MC\")\nplt.legend(prop={'size':16})\nplt.ylabel(\"Variance\")\nplt.xlabel(\"Step\")\nplt.grid()\n\nplt.show()" ]
[ [ "matplotlib.pyplot.legend", "pandas.read_csv", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "numpy.mean", "matplotlib.pyplot.grid", "numpy.var", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.rcParams.update", "numpy.array", "numpy.loadtxt", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
thanusiv/Open-Source-License-Validator
[ "2e69ddae15976ea25ec1e2cc1dbced31ff5aec7c" ]
[ "get_best_model/unsupervised/autoencoder/run_model.py" ]
[ "#!/usr/bin/python3\nimport os\nimport pickle\nfrom scipy import sparse\nimport pandas as pd\nimport numpy as np\nfrom sklearn.neural_network import MLPRegressor\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n\ndef main():\n \"\"\"\n An attempt to use an autoencoder to predict licenses.\n \"\"\"\n os.chdir('../../../all_files_generated')\n current_dir = os.getcwd()\n\n data_pickles_dir = os.path.join(current_dir, 'data_pickles')\n model_pickles_dir = os.path.join(current_dir, 'model_pickles')\n\n x_train_path = os.path.join(data_pickles_dir, 'x_train.pickle')\n x_validation_path = os.path.join(data_pickles_dir, 'x_validation.pickle')\n x_test_path = os.path.join(data_pickles_dir, 'x_test.pickle')\n y_train_path = os.path.join(data_pickles_dir, 'y_train.pickle')\n y_validation_path = os.path.join(data_pickles_dir, 'y_validation.pickle')\n y_test_path = os.path.join(data_pickles_dir, 'y_test.pickle')\n\n model_path = os.path.join(model_pickles_dir, 'autoencoder.pickle')\n\n # read in all pickle files that may be required\n with open(x_train_path, 'rb') as data:\n x_train = pickle.load(data)\n\n with open(x_validation_path, 'rb') as data:\n x_validation = pickle.load(data)\n\n with open(x_test_path, 'rb') as data:\n x_test = pickle.load(data)\n\n with open(y_train_path, 'rb') as data:\n y_train = pickle.load(data)\n\n with open(y_validation_path, 'rb') as data:\n y_validation = pickle.load(data)\n\n with open(y_test_path, 'rb') as data:\n y_test = pickle.load(data)\n\n # combine all datasets\n x_train = sparse.vstack((x_train, x_validation, x_test)).todense() # <class 'numpy.matrix'>\n y_train = y_train.append(pd.Series(y_validation)) # pandas series\n y_train = y_train.append(pd.Series(y_test)) # pandas series\n\n x_train_0 = []\n x_train_1 = []\n y_train_0 = []\n y_train_1 = []\n\n for x, y in zip(x_train, y_train):\n if y == 0:\n x_train_0.append(x)\n y_train_0.append(y)\n else:\n x_train_1.append(x)\n y_train_1.append(y)\n\n x_train_0 = np.array(x_train_0)\n x_train_0 = x_train_0[:, 0, :]\n\n x_train_1 = np.array(x_train_1)\n x_train_1 = x_train_1[:, 0, :]\n\n try:\n with open(model_path, 'rb') as data:\n license_classifier = pickle.load(data)\n print('Model was loaded in successfully!')\n except FileNotFoundError as e:\n print('Autoencoder model will begin training ...')\n license_classifier = MLPRegressor(hidden_layer_sizes=(500, 125, 500))\n license_classifier.fit(x_train_1, x_train_1)\n print('Autoencoder model finished training!')\n\n print('Saving model ...')\n with open(model_path, 'wb') as output:\n pickle.dump(license_classifier, output)\n print('Saved!')\n\n print('Starting predictions ...')\n train_predictions = license_classifier.predict(x_train_1)\n validation_predictions = license_classifier.predict(x_train_0)\n print('Predictions complete!')\n\n # Training accuracy\n print(\"The training accuracy is: \")\n print(license_classifier.score(x_train_1, train_predictions))\n\n # Test accuracy (should be low since the model should have a hard time recreating invalid licenses)\n print(\"The test accuracy is: \")\n print(license_classifier.score(x_train_0, validation_predictions))\n\n # can change the following two lines based on what you need\n sorted_cosine_similarities_1 = get_computed_similarities(x_train_1, train_predictions, y_train_1,\n True)\n sorted_cosine_similarities_0 = get_computed_similarities(x_train_0, validation_predictions, y_train_0,\n True)\n\n display_most_or_least_similar(sorted_cosine_similarities_1, 10, True)\n display_most_or_least_similar(sorted_cosine_similarities_0, 10, True)\n\n\ndef get_computed_similarities(original_vectors, predicted_vectors, labels, descending=False):\n data_size = len(original_vectors)\n cosine_similarities = []\n for i in range(data_size):\n cosine_sim_val = cosine_similarity(original_vectors[i], predicted_vectors[i])\n cosine_similarities.append((i, cosine_sim_val, labels[i]))\n return sorted(cosine_similarities, key=lambda x: x[1], reverse=descending)\n\n\ndef display_most_or_least_similar(sorted_cosine_similarities, n, descending):\n if descending:\n print('Most similar documents\\' values and their actual label')\n else:\n print('Least similar documents\\' values and their actual label')\n\n for i in range(n):\n print('Value:', sorted_cosine_similarities[i][1], 'Label:', sorted_cosine_similarities[i][2])\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "pandas.Series", "sklearn.metrics.pairwise.cosine_similarity", "scipy.sparse.vstack", "numpy.array", "sklearn.neural_network.MLPRegressor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
minjiedeng/NumEcon
[ "ff021e765344db93eed7ff0002dbdf3e50e528e9" ]
[ "numecon/course_micro1/firm.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\n\nclass FirmClass1D():\n\n def __init__(self,**kwargs):\n\n # a. baseline setup\n\n # technology\n self.technology = 'baseline'\n self.A = 1\n self.gamma = 0.5\n \n # prices\n self.w = 1\n self.p = 1\n\n # figures\n self.x1label = '$\\\\ell$'\n self.x2label = '$x$'\n self.N = 100\n\n # b. update \n for key,val in kwargs.items():\n setattr(self,key,val) # like par.key = val\n\n # c. calculations\n self.calculations()\n\n def calculations(self):\n \n if self.technology == 'baseline':\n self.g = lambda l,A,gamma: A*l**gamma \n else:\n raise ValueError('unknown technology')\n\n ##########\n # choice #\n ##########\n\n def maximize_profit(self,**kwargs):\n\n # a. update\n for key,val in kwargs.items():\n setattr(self,key,val)\n\n # b. solve\n if self.technology == 'baseline':\n if self.gamma < 1:\n nom = self.w\n denom = self.p*self.A*self.gamma\n exp = 1/(self.gamma-1)\n self.l_ast = (nom/denom)**exp\n self.y_ast = self.g(self.l_ast,self.A,self.gamma)\n self.pi_ast = self.p*self.y_ast - self.w*self.l_ast\n else:\n self.l_ast = np.nan \n self.y_ast = np.nan \n self.pi_ast = np.nan\n else:\n raise ValueError('unknown production function')\n\n return np.array([self.l_ast,self.y_ast])\n\n def plot_max(self,ax,**kwargs):\n\n kwargs.setdefault('ls','')\n kwargs.setdefault('marker','*')\n kwargs.setdefault('markersize',7)\n kwargs.setdefault('color','black')\n kwargs.setdefault('label',f'$g({self.l_ast:.2f}) = {self.y_ast:.2f}$')\n\n ax.plot(self.l_ast,self.y_ast,**kwargs)\n\n ##########\n # figure #\n ##########\n\n def plot_pmo_line(self,ax,lmax=10,**kwargs):\n \n kwargs.setdefault('lw',2)\n l = np.linspace(1e-8,lmax,self.N)\n ax.plot(l,self.g(l,self.A,self.gamma),**kwargs)\n\n def plot_profit_line(self,ax,lmax=10,**kwargs):\n \n kwargs.setdefault('lw',2)\n l = np.linspace(1e-8,lmax,self.N)\n ax.plot(l,(self.pi_ast+self.w*l)/self.p,**kwargs)" ]
[ [ "numpy.array", "numpy.linspace" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
bouzaghrane/pylogit
[ "f83b0fd6debaa7358d87c3828428f6d4ead71357" ]
[ "tests/test_choice_calcs.py" ]
[ "\"\"\"\nTests for the choice_calcs.py file.\n\"\"\"\nimport unittest\nimport warnings\nfrom collections import OrderedDict\n\nimport numpy as np\nimport numpy.testing as npt\nimport pandas as pd\nfrom scipy.sparse import csr_matrix\nfrom scipy.sparse import diags\nfrom scipy.sparse import block_diag\n\nimport pylogit.asym_logit as asym\nimport pylogit.conditional_logit as mnl\nimport pylogit.choice_calcs as cc\n\n\n# Use the following to always show the warnings\nnp.seterr(all='warn')\nwarnings.simplefilter(\"always\")\n\n\nclass GenericTestCase(unittest.TestCase):\n \"\"\"\n Defines the common setUp method used for the different type of tests.\n \"\"\"\n\n def setUp(self):\n # The set up being used is one where there are two choice situations,\n # The first having three alternatives, and the second having only two\n # alternatives. There is one generic variable. Two alternative\n # specific constants and all three shape parameters are used.\n\n # Create the betas to be used during the tests\n self.fake_betas = np.array([-0.6])\n\n # Create the fake outside intercepts to be used during the tests\n self.fake_intercepts = np.array([1, 0.5])\n\n # Create names for the intercept parameters\n self.fake_intercept_names = [\"ASC 1\", \"ASC 2\"]\n\n # Record the position of the intercept that is not being estimated\n self.fake_intercept_ref_pos = 2\n\n # Create the shape parameters to be used during the tests. Note that\n # these are the reparameterized shape parameters, thus they will be\n # exponentiated in the fit_mle process and various calculations.\n self.fake_shapes = np.array([-1, 1])\n\n # Create names for the intercept parameters\n self.fake_shape_names = [\"Shape 1\", \"Shape 2\"]\n\n # Record the position of the shape parameter that is being constrained\n self.fake_shape_ref_pos = 2\n\n # Calculate the 'natural' shape parameters\n self.natural_shapes = asym._convert_eta_to_c(self.fake_shapes,\n self.fake_shape_ref_pos)\n\n # Create an array of all model parameters\n self.fake_all_params = np.concatenate((self.fake_shapes,\n self.fake_intercepts,\n self.fake_betas))\n\n # The mapping between rows and alternatives is given below.\n self.fake_rows_to_alts = csr_matrix(np.array([[1, 0, 0],\n [0, 1, 0],\n [0, 0, 1],\n [1, 0, 0],\n [0, 0, 1]]))\n # Create the mapping between rows and individuals\n self.fake_rows_to_obs = csr_matrix(np.array([[1, 0],\n [1, 0],\n [1, 0],\n [0, 1],\n [0, 1]]))\n\n # Create the fake design matrix with columns denoting X\n # The intercepts are not included because they are kept outside the\n # index in the scobit model.\n self.fake_design = np.array([[1],\n [2],\n [3],\n [1.5],\n [3.5]])\n\n # Create the index array for this set of choice situations\n self.fake_index = self.fake_design.dot(self.fake_betas)\n\n # Create the needed dataframe for the Asymmetric Logit constructor\n self.fake_df = pd.DataFrame({\"obs_id\": [1, 1, 1, 2, 2],\n \"alt_id\": [1, 2, 3, 1, 3],\n \"choice\": [0, 1, 0, 0, 1],\n \"x\": self.fake_design[:, 0],\n \"intercept\": [1 for i in range(5)]})\n\n # Record the various column names\n self.alt_id_col = \"alt_id\"\n self.obs_id_col = \"obs_id\"\n self.choice_col = \"choice\"\n\n # Store the choices as their own array\n self.choice_array = self.fake_df[self.choice_col].values\n\n # Create the index specification and name dictionaryfor the model\n self.fake_specification = OrderedDict()\n self.fake_names = OrderedDict()\n self.fake_specification[\"x\"] = [[1, 2, 3]]\n self.fake_names[\"x\"] = [\"x (generic coefficient)\"]\n\n # Bundle args and kwargs used to construct the Asymmetric Logit model.\n self.constructor_args = [self.fake_df,\n self.alt_id_col,\n self.obs_id_col,\n self.choice_col,\n self.fake_specification]\n\n # Create a variable for the kwargs being passed to the constructor\n self.constructor_kwargs = {\"intercept_ref_pos\":\n self.fake_intercept_ref_pos,\n \"shape_ref_pos\": self.fake_shape_ref_pos,\n \"names\": self.fake_names,\n \"intercept_names\":\n self.fake_intercept_names,\n \"shape_names\": self.fake_shape_names}\n\n # Initialize a basic Asymmetric Logit model whose coefficients will be\n # estimated.\n self.model_obj = asym.MNAL(*self.constructor_args,\n **self.constructor_kwargs)\n\n # Store a ridge penalty for use in calculations.\n self.ridge = 0.5\n\n return None\n\n\nclass ComputationalTests(GenericTestCase):\n \"\"\"\n Tests the computational functions to make sure that they return the\n expected results.\n \"\"\"\n # Store a utility transformation function for the tests\n\n def utility_transform(self,\n sys_utilities,\n alt_IDs,\n rows_to_alts,\n shape_params,\n intercept_params):\n return sys_utilities[:, None]\n\n def test_calc_asymptotic_covariance(self):\n \"\"\"\n Ensure that the correct Huber-White covariance matrix is calculated.\n \"\"\"\n ones_array = np.ones(5)\n # Create the hessian matrix for testing. It will be a 5 by 5 matrix.\n test_hessian = np.diag(2 * ones_array)\n # Create the approximation of the Fisher Information Matrix\n test_fisher_matrix = np.diag(ones_array)\n # Create the inverse of the hessian matrix.\n test_hess_inverse = np.diag(0.5 * ones_array)\n # Calculated the expected result\n expected_result = np.dot(test_hess_inverse,\n np.dot(test_fisher_matrix, test_hess_inverse))\n # Alias the function being tested\n func = cc.calc_asymptotic_covariance\n # Perform the test.\n function_results = func(test_hessian, test_fisher_matrix)\n self.assertIsInstance(function_results, np.ndarray)\n self.assertEqual(function_results.shape, test_hessian.shape)\n npt.assert_allclose(expected_result, function_results)\n\n return None\n\n def test_log_likelihood(self):\n \"\"\"\n Ensure that we correctly calculate the log-likelihood, both with and\n without ridge penalties, and both with and without shape and intercept\n parameters.\n \"\"\"\n # Create a utility transformation function for testing\n def test_utility_transform(x, *args):\n return x\n # Calculate the index for each alternative for each individual\n test_index = self.fake_design.dot(self.fake_betas)\n # Exponentiate each index value\n exp_test_index = np.exp(test_index)\n # Calculate the denominator for each probability\n interim_dot_product = self.fake_rows_to_obs.T.dot(exp_test_index)\n test_denoms = self.fake_rows_to_obs.dot(interim_dot_product)\n # Calculate the probabilities for each individual\n prob_array = exp_test_index / test_denoms\n # Calculate what the log-likelihood should be\n choices = self.fake_df[self.choice_col].values\n expected_log_likelihood = np.dot(choices, np.log(prob_array))\n # Create a set of intercepts, that are all zeros\n intercepts = np.zeros(2)\n # Combine all the 'parameters'\n test_all_params = np.concatenate([intercepts, self.fake_betas], axis=0)\n # Calculate what the log-likelihood should be with a ridge penalty\n penalty = self.ridge * (test_all_params**2).sum()\n expected_log_likelihood_penalized = expected_log_likelihood - penalty\n\n # Alias the function being tested\n func = cc.calc_log_likelihood\n # Create the arguments for the function being tested\n args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n choices,\n test_utility_transform]\n kwargs = {\"intercept_params\": intercepts,\n \"shape_params\": None}\n\n # Perform the tests\n function_results = func(*args, **kwargs)\n self.assertAlmostEqual(expected_log_likelihood, function_results)\n\n # Test the weighted log-likelihood capability\n weights = 2 * np.ones(self.fake_design.shape[0])\n kwargs[\"weights\"] = weights\n function_results_2 = func(*args, **kwargs)\n self.assertAlmostEqual(2 * expected_log_likelihood, function_results_2)\n kwargs[\"weights\"] = None\n\n # Test the ridge regression calculations\n kwargs[\"ridge\"] = self.ridge\n function_results_3 = func(*args, **kwargs)\n self.assertAlmostEqual(expected_log_likelihood_penalized,\n function_results_3)\n\n # Test the function again, this time without intercepts\n kwargs[\"intercept_params\"] = None\n function_results_4 = func(*args, **kwargs)\n self.assertAlmostEqual(expected_log_likelihood_penalized,\n function_results_4)\n\n return None\n\n def test_array_size_error_in_calc_probabilities(self):\n \"\"\"\n Ensure that a helpful ValueError is raised when a person tries to\n calculate probabilities using BOTH a 2D coefficient array and a 3D\n design matrix.\n \"\"\"\n # Alias the function being tested\n func = cc.calc_probabilities\n\n # Create fake arguments for the function being tested.\n # Note these arguments are not valid in general, but suffice for\n # testing the functionality we care about in this function.\n args = [np.arange(9).reshape((3, 3)),\n np.arange(27).reshape((3, 3, 3)),\n None,\n None,\n None,\n None]\n\n # Note the error message that should be shown.\n msg_1 = \"Cannot calculate probabilities with both 3D design matrix AND\"\n msg_2 = \" 2D coefficient array.\"\n msg = msg_1 + msg_2\n\n self.assertRaisesRegexp(ValueError,\n msg,\n func,\n *args)\n\n return None\n\n def test_return_argument_error_in_calc_probabilities(self):\n \"\"\"\n Ensure that a helpful ValueError is raised when a person tries to\n calculate probabilities using BOTH a return_long_probs == False and\n chosen_row_to_obs being None.\n \"\"\"\n # Alias the function being tested\n func = cc.calc_probabilities\n\n # Create fake arguments for the function being tested.\n # Note these arguments are not valid in general, but suffice for\n # testing the functionality we care about in this function.\n args = [np.arange(9).reshape((3, 3)),\n np.arange(9).reshape((3, 3)),\n None,\n None,\n None,\n None]\n\n # Note the error message that should be shown.\n msg = \"chosen_row_to_obs is None AND return_long_probs is False\"\n\n self.assertRaisesRegexp(ValueError,\n msg,\n func,\n *args)\n\n return None\n\n def test_1D_calc_probabilities(self):\n \"\"\"\n Ensure that when using a 2D design matrix and 1D vector of parameters,\n that the calc_probabilities function returns the correct values. Note\n that this test will only verify the functionality under 'normal'\n conditions, where the values of the exponentiated indices do not go\n to zero nor to infinity.\n \"\"\"\n # Calculate the index vector\n expected_index = self.fake_design.dot(self.fake_betas)\n # Calculate exp(index)\n expected_exp_index = np.exp(expected_index)\n # Calculate the sum of exp(index) for each individual\n denoms = self.fake_rows_to_obs.T.dot(expected_exp_index)\n # Calculate the expected probabilities\n expected_probs = expected_exp_index / self.fake_rows_to_obs.dot(denoms)\n\n # Alias the function to be tested\n func = cc.calc_probabilities\n\n # Collect the arguments needed for this function\n args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.utility_transform]\n kwargs = {\"intercept_params\": self.fake_intercepts,\n \"shape_params\": self.fake_shapes,\n \"return_long_probs\": True}\n function_results = func(*args, **kwargs)\n\n # Perform the tests\n self.assertIsInstance(function_results, np.ndarray)\n self.assertEqual(len(function_results.shape), 1)\n self.assertEqual(function_results.shape, (self.fake_design.shape[0],))\n npt.assert_allclose(function_results, expected_probs)\n\n return None\n\n def test_return_values_of_calc_probabilities(self):\n \"\"\"\n Ensure that the various configuration of return values can all be\n returned.\n \"\"\"\n # Calculate the index vector\n expected_index = self.fake_design.dot(self.fake_betas)\n # Calculate exp(index)\n expected_exp_index = np.exp(expected_index)\n # Calculate the sum of exp(index) for each individual\n denoms = self.fake_rows_to_obs.T.dot(expected_exp_index)\n # Calculate the expected probabilities\n expected_probs = expected_exp_index / self.fake_rows_to_obs.dot(denoms)\n # Extract the probabilities of the chosen alternatives for each\n # observaation\n chosen_indices = np.where(self.choice_array == 1)\n expected_chosen_probs = expected_probs[chosen_indices]\n\n # Alias the function to be tested\n func = cc.calc_probabilities\n\n # Create the chosen_row_to_obs mapping matrix\n choices_2d = self.choice_array[:, None]\n chosen_row_to_obs = self.fake_rows_to_obs.multiply(choices_2d)\n\n # Collect the arguments needed for this function\n args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.utility_transform]\n\n # kwargs_1 should result in long_probs being returned.\n kwargs_1 = {\"intercept_params\": self.fake_intercepts,\n \"shape_params\": self.fake_shapes,\n \"return_long_probs\": True}\n\n # kwargs_2 should result in (chosen_probs, long_probs being returned)\n kwargs_2 = {\"intercept_params\": self.fake_intercepts,\n \"shape_params\": self.fake_shapes,\n \"chosen_row_to_obs\": chosen_row_to_obs,\n \"return_long_probs\": True}\n\n # kwargs_3 should result in chosen_probs being returned.\n kwargs_3 = {\"intercept_params\": self.fake_intercepts,\n \"shape_params\": self.fake_shapes,\n \"chosen_row_to_obs\": chosen_row_to_obs,\n \"return_long_probs\": False}\n\n # Collect the expected results\n expected_results = [expected_probs,\n (expected_chosen_probs, expected_probs),\n expected_chosen_probs]\n\n # Perform the tests\n for pos, kwargs in enumerate([kwargs_1, kwargs_2, kwargs_3]):\n function_results = func(*args, **kwargs)\n if isinstance(function_results, tuple):\n expected_arrays = expected_results[pos]\n for array_pos, array in enumerate(function_results):\n current_expected_array = expected_arrays[array_pos]\n self.assertIsInstance(array, np.ndarray)\n self.assertEqual(array.shape, current_expected_array.shape)\n npt.assert_allclose(array, current_expected_array)\n else:\n expected_array = expected_results[pos]\n self.assertIsInstance(function_results, np.ndarray)\n self.assertEqual(function_results.shape, expected_array.shape)\n npt.assert_allclose(function_results, expected_array)\n\n return None\n\n def test_2D_calc_probabilities(self):\n \"\"\"\n Ensure that when using either a 2D design matrix and 2D vector of\n parameters, or a 3D design matrix and 1D vector of parameters,\n that the calc_probabilities function returns the correct values. Note\n that this test will only verify the functionality under 'normal'\n conditions, where the values of the exponentiated indices do not go\n to zero nor to infinity.\n \"\"\"\n # Designate a utility transform for this test\n utility_transform = mnl._mnl_utility_transform\n\n # Calculate the index vector\n expected_index = self.fake_design.dot(self.fake_betas)\n # Calculate exp(index)\n expected_exp_index = np.exp(expected_index)\n # Calculate the sum of exp(index) for each individual\n denoms = self.fake_rows_to_obs.T.dot(expected_exp_index)\n # Calculate the expected probabilities\n expected_probs = expected_exp_index / self.fake_rows_to_obs.dot(denoms)\n # Create the 2D vector of expected probs\n expected_probs_2d = np.concatenate([expected_probs[:, None],\n expected_probs[:, None]], axis=1)\n # Create the 2D coefficient vector\n betas_2d = np.concatenate([self.fake_betas[:, None],\n self.fake_betas[:, None]], axis=1)\n assert self.fake_design.dot(betas_2d).shape[1] > 1\n\n # Create the 3D design matrix\n design_3d = np.concatenate([self.fake_design[:, None, :],\n self.fake_design[:, None, :]], axis=1)\n\n # Alias the function to be tested\n func = cc.calc_probabilities\n\n # Collect the arguments needed for this function\n args = [betas_2d,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n utility_transform]\n # The kwargs below mean that only the long format probabilities will\n # be returned.\n kwargs = {\"intercept_params\": self.fake_intercepts,\n \"shape_params\": self.fake_shapes,\n \"chosen_row_to_obs\": None,\n \"return_long_probs\": True}\n function_results_1 = func(*args, **kwargs)\n\n # Now test the functions with the various multidimensional argumnts\n args[0] = self.fake_betas\n args[1] = design_3d\n function_results_2 = func(*args, **kwargs)\n\n # Now try the results when calling for chosen_probs as well\n chosen_row_to_obs = self.fake_rows_to_obs.multiply(\n self.choice_array[:, None])\n kwargs[\"chosen_row_to_obs\"] = chosen_row_to_obs\n chosen_probs, function_results_3 = func(*args, **kwargs)\n\n # Perform the tests using a 2d coefficient array\n for function_results in [function_results_1,\n function_results_2,\n function_results_3]:\n self.assertIsInstance(function_results, np.ndarray)\n self.assertEqual(len(function_results.shape), 2)\n self.assertEqual(function_results.shape,\n (self.fake_design.shape[0], 2))\n npt.assert_allclose(function_results, expected_probs_2d)\n\n chosen_idx = np.where(self.choice_array == 1)[0]\n self.assertIsInstance(chosen_probs, np.ndarray)\n self.assertEqual(len(chosen_probs.shape), 2)\n npt.assert_allclose(chosen_probs, expected_probs_2d[chosen_idx, :])\n\n return None\n\n def test_calc_probabilities_robustness_to_under_overflow(self):\n \"\"\"\n Ensure that the calc_probabilities function correctly handles under-\n and overflow in the exponential of the systematic utilities.\n \"\"\"\n # Create a design array that will test the under- and over-flow\n # capabilities of the calc_probabilities function.\n extreme_design = np.array([[1],\n [800 / self.fake_betas[0]],\n [-800 / self.fake_betas[0]],\n [-800 / self.fake_betas[0]],\n [3]])\n # Calculate the index vector\n expected_index = extreme_design.dot(self.fake_betas)\n # Calculate exp(index)\n expected_exp_index = np.exp(expected_index)\n # Guard against over and underflow\n expected_exp_index[1] = np.exp(cc.max_exponent_val)\n expected_exp_index[[2, 3]] = np.exp(cc.min_exponent_val)\n # Calculate the sum of exp(index) for each individual\n denoms = self.fake_rows_to_obs.T.dot(expected_exp_index)\n # Calculate the expected probabilities\n expected_probs = expected_exp_index / self.fake_rows_to_obs.dot(denoms)\n # Guard against underflow\n expected_probs[expected_probs == 0.0] = cc.min_comp_value\n\n # Alias the function to be tested\n func = cc.calc_probabilities\n\n # Collect the arguments needed for this function\n args = [self.fake_betas,\n extreme_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.utility_transform]\n kwargs = {\"intercept_params\": self.fake_intercepts,\n \"shape_params\": self.fake_shapes,\n \"return_long_probs\": True}\n function_results = func(*args, **kwargs)\n\n # Perform the tests\n self.assertIsInstance(function_results, np.ndarray)\n self.assertEqual(len(function_results.shape), 1)\n self.assertEqual(function_results.shape, (self.fake_design.shape[0],))\n npt.assert_allclose(function_results, expected_probs)\n\n return None\n\n def test_calc_gradient_no_shapes_no_intercepts(self):\n \"\"\"\n Ensure that calc_gradient returns the correct values when there are no\n shape parameters and no intercept parameters.\n \"\"\"\n # Designate a function that calculates the parital derivative of the\n # transformed index values, with respect to the index.\n dh_dv = diags(np.ones(self.fake_design.shape[0]), 0, format='csr')\n\n def transform_deriv_v(*args):\n return dh_dv\n\n # Designate functions that calculate the partial derivative of the\n # transformed index values, with respect to shape and index parameters\n def transform_deriv_intercepts(*args):\n return None\n\n def transform_deriv_shapes(*args):\n return None\n\n # Collect the arguments needed to calculate the probabilities\n args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.utility_transform]\n kwargs = {\"intercept_params\": self.fake_intercepts,\n \"shape_params\": self.fake_shapes,\n \"return_long_probs\": True}\n # Calculate the required probabilities\n probs = cc.calc_probabilities(*args, **kwargs)\n # In this scenario, the gradient should be (Y- P)'(dh_dv * dv_db)\n # which simplifies to (Y- P)'(dh_dv * X)\n error_vec = (self.choice_array - probs)[None, :]\n expected_gradient = error_vec.dot(dh_dv.dot(self.fake_design)).ravel()\n\n # Alias the function being tested\n func = cc.calc_gradient\n\n # Collect the arguments for the function being tested\n gradient_args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.choice_array,\n self.utility_transform,\n transform_deriv_shapes,\n transform_deriv_v,\n transform_deriv_intercepts,\n None,\n None,\n None,\n None]\n function_gradient = func(*gradient_args)\n\n # Perform the required tests\n self.assertIsInstance(function_gradient, np.ndarray)\n self.assertEqual(function_gradient.shape, (self.fake_betas.shape[0],))\n npt.assert_allclose(function_gradient, expected_gradient)\n\n # Test the gradient function with the ridge argument\n gradient_args[-2] = self.ridge\n new_expected_gradient = (expected_gradient -\n 2 * self.ridge * self.fake_betas[0])\n function_gradient_penalized = func(*gradient_args)\n\n self.assertIsInstance(function_gradient_penalized, np.ndarray)\n self.assertEqual(function_gradient_penalized.shape,\n (self.fake_betas.shape[0],))\n npt.assert_allclose(function_gradient_penalized, new_expected_gradient)\n\n # Test the gradient function with weights\n new_weights = 2 * np.ones(self.fake_design.shape[0])\n gradient_args[-1] = new_weights\n new_expected_gradient_weighted =\\\n 2 * expected_gradient - 2 * self.ridge * self.fake_betas[0]\n func_gradient_penalized_weighted = func(*gradient_args)\n self.assertIsInstance(func_gradient_penalized_weighted, np.ndarray)\n self.assertEqual(func_gradient_penalized_weighted.shape,\n (self.fake_betas.shape[0],))\n npt.assert_allclose(func_gradient_penalized_weighted,\n new_expected_gradient_weighted)\n return None\n\n def test_calc_gradient_no_shapes(self):\n \"\"\"\n Ensure that calc_gradient returns the correct values when there are no\n shape parameters but there are intercept parameters.\n \"\"\"\n # Designate a function that calculates the parital derivative of the\n # transformed index values, with respect to the index.\n dh_dv = diags(np.ones(self.fake_design.shape[0]), 0, format='csr')\n\n def transform_deriv_v(*args):\n return dh_dv\n\n # Designate functions that calculate the partial derivative of the\n # transformed index values, with respect to shape and index parameters\n dh_d_intercept = self.fake_rows_to_alts[:, 1:]\n\n def transform_deriv_intercepts(*args):\n return dh_d_intercept\n\n def transform_deriv_shapes(*args):\n return None\n\n # Collect the arguments needed to calculate the probabilities\n args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.utility_transform]\n kwargs = {\"intercept_params\": self.fake_intercepts,\n \"shape_params\": self.fake_shapes,\n \"return_long_probs\": True}\n # Calculate the required probabilities\n probs = cc.calc_probabilities(*args, **kwargs)\n # In this scenario, the gradient should be (Y- P)'(dh_d_theta)\n # which simplifies to (Y- P)'[dh_d_intercept | dh_d_beta]\n # and finally to (Y- P)'[dh_d_intercept | dh_dv * X]\n error_vec = (self.choice_array - probs)[None, :]\n dh_d_beta = dh_dv.dot(self.fake_design)\n dh_d_theta = np.concatenate((dh_d_intercept.A, dh_d_beta), axis=1)\n expected_gradient = error_vec.dot(dh_d_theta).ravel()\n\n # Alias the function being tested\n func = cc.calc_gradient\n\n # Collect the arguments for the function being tested\n gradient_args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.choice_array,\n self.utility_transform,\n transform_deriv_shapes,\n transform_deriv_v,\n transform_deriv_intercepts,\n self.fake_intercepts,\n None,\n None,\n None]\n function_gradient = func(*gradient_args)\n\n # Perform the required tests\n self.assertIsInstance(function_gradient, np.ndarray)\n self.assertEqual(function_gradient.shape,\n (self.fake_betas.shape[0] +\n self.fake_intercepts.shape[0],))\n npt.assert_allclose(function_gradient, expected_gradient)\n\n # Test the gradient function with weights\n new_weights = 2 * np.ones(self.fake_design.shape[0])\n gradient_args[-1] = new_weights\n expected_gradient_weighted = 2 * expected_gradient\n func_gradient_weighted = func(*gradient_args)\n self.assertIsInstance(func_gradient_weighted, np.ndarray)\n self.assertEqual(func_gradient_weighted.shape,\n (self.fake_betas.shape[0] +\n self.fake_intercepts.shape[0],))\n npt.assert_allclose(func_gradient_weighted, expected_gradient_weighted)\n\n return None\n\n def test_calc_gradient_no_intercepts(self):\n \"\"\"\n Ensure that calc_gradient returns the correct values when there are no\n intercept parameters but there are shape parameters.\n \"\"\"\n # Designate a function that calculates the parital derivative of the\n # transformed index values, with respect to the index.\n dh_dv = diags(np.ones(self.fake_design.shape[0]), 0, format='csr')\n\n def transform_deriv_v(*args):\n return dh_dv\n\n # Designate functions that calculate the partial derivative of the\n # transformed index values, with respect to shape and index parameters\n def transform_deriv_intercepts(*args):\n return None\n\n fake_deriv = np.exp(self.fake_shapes)[None, :]\n dh_d_shape = self.fake_rows_to_alts[:, 1:].multiply(fake_deriv)\n\n def transform_deriv_shapes(*args):\n return dh_d_shape\n\n # Collect the arguments needed to calculate the probabilities\n args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.utility_transform]\n kwargs = {\"intercept_params\": self.fake_intercepts,\n \"shape_params\": self.fake_shapes,\n \"return_long_probs\": True}\n # Calculate the required probabilities\n probs = cc.calc_probabilities(*args, **kwargs)\n # In this scenario, the gradient should be (Y- P)'(dh_d_theta)\n # which simplifies to (Y- P)'[dh_d_shape | dh_d_beta]\n # and finally to (Y- P)'[dh_d_shape | dh_dv * X]\n error_vec = (self.choice_array - probs)[None, :]\n dh_d_beta = dh_dv.dot(self.fake_design)\n dh_d_theta = np.concatenate((dh_d_shape.A, dh_d_beta), axis=1)\n expected_gradient = error_vec.dot(dh_d_theta).ravel()\n\n # Alias the function being tested\n func = cc.calc_gradient\n\n # Collect the arguments for the function being tested\n gradient_args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.choice_array,\n self.utility_transform,\n transform_deriv_shapes,\n transform_deriv_v,\n transform_deriv_intercepts,\n None,\n self.fake_shapes,\n None,\n None]\n function_gradient = func(*gradient_args)\n\n # Perform the required tests\n self.assertIsInstance(function_gradient, np.ndarray)\n self.assertEqual(function_gradient.shape,\n (self.fake_betas.shape[0] +\n self.fake_shapes.shape[0],))\n npt.assert_allclose(function_gradient, expected_gradient)\n\n # Perform the tests with a weighted gradient\n new_weights = 2 * np.ones(self.fake_design.shape[0])\n gradient_args[-1] = new_weights\n expected_gradient_weighted = 2 * expected_gradient\n func_gradient_weighted = func(*gradient_args)\n self.assertIsInstance(func_gradient_weighted, np.ndarray)\n self.assertEqual(func_gradient_weighted.shape,\n (self.fake_betas.shape[0] +\n self.fake_shapes.shape[0],))\n npt.assert_allclose(func_gradient_weighted, expected_gradient_weighted)\n\n # Test the gradient function with weights\n new_weights = 2 * np.ones(self.fake_design.shape[0])\n gradient_args[-1] = new_weights\n expected_gradient_weighted = 2 * expected_gradient\n func_gradient_weighted = func(*gradient_args)\n self.assertIsInstance(func_gradient_weighted, np.ndarray)\n self.assertEqual(func_gradient_weighted.shape,\n (self.fake_betas.shape[0] +\n self.fake_shapes.shape[0],))\n npt.assert_allclose(func_gradient_weighted, expected_gradient_weighted)\n return None\n\n def test_calc_gradient_shapes_and_intercepts(self):\n \"\"\"\n Ensure that calc_gradient returns the correct values when there are\n shape and intercept parameters.\n \"\"\"\n # Designate a function that calculates the parital derivative of the\n # transformed index values, with respect to the index.\n dh_dv = diags(np.ones(self.fake_design.shape[0]), 0, format='csr')\n\n def transform_deriv_v(*args):\n return dh_dv\n\n # Designate functions that calculate the partial derivative of the\n # transformed index values, with respect to shape and index parameters\n dh_d_intercept = self.fake_rows_to_alts[:, 1:]\n\n def transform_deriv_intercepts(*args):\n return dh_d_intercept\n\n fake_deriv = np.exp(self.fake_shapes)[None, :]\n dh_d_shape = self.fake_rows_to_alts[:, 1:].multiply(fake_deriv)\n\n def transform_deriv_shapes(*args):\n return dh_d_shape\n\n # Collect the arguments needed to calculate the probabilities\n args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.utility_transform]\n kwargs = {\"intercept_params\": self.fake_intercepts,\n \"shape_params\": self.fake_shapes,\n \"return_long_probs\": True}\n # Calculate the required probabilities\n probs = cc.calc_probabilities(*args, **kwargs)\n # In this scenario, the gradient should be (Y- P)'(dh_d_theta)\n # which simplifies to (Y- P)'[dh_d_shape | dh_d_intercept | dh_d_beta]\n # and finally to (Y- P)'[dh_d_shape | dh_d_intercept | dh_dv * X]\n error_vec = (self.choice_array - probs)[None, :]\n dh_d_beta = dh_dv.dot(self.fake_design)\n dh_d_theta = np.concatenate((dh_d_shape.A,\n dh_d_intercept.A,\n dh_d_beta), axis=1)\n expected_gradient = error_vec.dot(dh_d_theta).ravel()\n\n # Alias the function being tested\n func = cc.calc_gradient\n\n # Collect the arguments for the function being tested\n gradient_args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.choice_array,\n self.utility_transform,\n transform_deriv_shapes,\n transform_deriv_v,\n transform_deriv_intercepts,\n self.fake_intercepts,\n self.fake_shapes,\n None,\n None]\n function_gradient = func(*gradient_args)\n\n # Perform the required tests\n self.assertIsInstance(function_gradient, np.ndarray)\n self.assertEqual(function_gradient.shape,\n (self.fake_betas.shape[0] +\n self.fake_intercepts.shape[0] +\n self.fake_shapes.shape[0],))\n npt.assert_allclose(function_gradient, expected_gradient)\n\n # Test the gradient function with weights\n new_weights = 2 * np.ones(self.fake_design.shape[0])\n gradient_args[-1] = new_weights\n expected_gradient_weighted = 2 * expected_gradient\n func_gradient_weighted = func(*gradient_args)\n self.assertIsInstance(func_gradient_weighted, np.ndarray)\n self.assertEqual(func_gradient_weighted.shape,\n (self.fake_betas.shape[0] +\n self.fake_intercepts.shape[0] +\n self.fake_shapes.shape[0],))\n npt.assert_allclose(func_gradient_weighted, expected_gradient_weighted)\n\n return None\n\n def test_create_matrix_block_indices(self):\n \"\"\"\n Ensure that create_matrix_block_indices returns the expected results.\n \"\"\"\n # Note that we have two observations, the first with three alternatives\n # and the second with two alternatives.\n expected_results = [np.array([0, 1, 2]), np.array([3, 4])]\n\n # Get the results of the function being tested\n results = cc.create_matrix_block_indices(self.fake_rows_to_obs)\n\n # Test that the two sets of results are equal\n self.assertIsInstance(results, list)\n self.assertTrue(all([isinstance(x, np.ndarray) for x in results]))\n npt.assert_allclose(expected_results[0], results[0])\n npt.assert_allclose(expected_results[1], results[1])\n\n return None\n\n def test_robust_outer_product(self):\n \"\"\"\n Ensure that robust_outer_product returns the expected results.\n Unfortunately, I cannot find a good case now where using the regular\n outer product gives incorrect results. However without a compelling\n reason to remove the function, I'll trust my earlier judgement in\n creating it in the first place.\n \"\"\"\n # Define a vector whose outer product we want to take\n x = np.array([1e-100, 0.01])\n outer_product = np.outer(x, x)\n robust_outer_product = cc.robust_outer_product(x, x)\n\n # Perform the desired tests\n self.assertIsInstance(robust_outer_product, np.ndarray)\n self.assertEqual(robust_outer_product.shape, outer_product.shape)\n npt.assert_allclose(outer_product, robust_outer_product)\n\n return None\n\n def test_create_matrix_blocks(self):\n \"\"\"\n Ensure that create_matrix_blocks returns expected results when not\n having to correct for underflow.\n \"\"\"\n # Designate a utility transform for this test\n utility_transform = mnl._mnl_utility_transform\n\n # Collect the arguments needed for this function\n args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n utility_transform]\n kwargs = {\"intercept_params\": self.fake_intercepts,\n \"shape_params\": self.fake_shapes,\n \"return_long_probs\": True}\n # Get the long-format probabilities\n long_probs = cc.calc_probabilities(*args, **kwargs)\n\n # Get the matrix-block indices\n matrix_indices = cc.create_matrix_block_indices(self.fake_rows_to_obs)\n\n # Create the matrix block for individual 1.\n matrix_block_1 = (np.diag(long_probs[:3]) -\n np.outer(long_probs[:3], long_probs[:3]))\n matrix_block_2 = (np.diag(long_probs[3:]) -\n np.outer(long_probs[3:], long_probs[3:]))\n # Create a list of the expected results\n expected_results = [matrix_block_1, matrix_block_2]\n\n # Get the function results\n func_results = cc.create_matrix_blocks(long_probs, matrix_indices)\n for pos, result in enumerate(func_results):\n self.assertIsInstance(result, np.ndarray)\n self.assertEqual(result.shape, expected_results[pos].shape)\n npt.assert_allclose(result, expected_results[pos])\n\n return None\n\n def test_create_matrix_blocks_with_underflow(self):\n \"\"\"\n Ensure that create_matrix_blocks returns expected results when also\n having to correct for underflow.\n \"\"\"\n # Get the long-format probabilities\n long_probs = np.array([cc.min_comp_value,\n cc.min_comp_value,\n 1.0,\n cc.min_comp_value,\n 1.0])\n\n # Get the matrix-block indices\n matrix_indices = cc.create_matrix_block_indices(self.fake_rows_to_obs)\n\n # Create the matrix block for individual 1.\n row_1 = [cc.min_comp_value, -cc.min_comp_value, -cc.min_comp_value]\n row_2 = [-cc.min_comp_value, cc.min_comp_value, -cc.min_comp_value]\n row_3 = [-cc.min_comp_value, -cc.min_comp_value, cc.min_comp_value]\n matrix_block_1 = np.array([row_1, row_2, row_3])\n\n matrix_block_2 = (np.diag(long_probs[3:]) -\n np.outer(long_probs[3:], long_probs[3:]))\n # Assuming that no probabilities should actually be zero or one,\n # the underflow guard would set the last value to a very small,\n # positive number\n matrix_block_2[-1, -1] = cc.min_comp_value\n\n # Create a list of the expected results\n expected_results = [matrix_block_1, matrix_block_2]\n\n # Get the function results\n func_results = cc.create_matrix_blocks(long_probs, matrix_indices)\n for pos, result in enumerate(func_results):\n self.assertIsInstance(result, np.ndarray)\n self.assertEqual(result.shape, expected_results[pos].shape)\n npt.assert_allclose(result, expected_results[pos])\n\n return None\n\n def test_calc_fisher_info_matrix_no_shapes_no_intercepts(self):\n \"\"\"\n Ensure that calc_fisher_info_matrix returns the expected values when\n there are no shape or intercept parameters.\n \"\"\"\n # Designate a function that calculates the parital derivative of the\n # transformed index values, with respect to the index.\n def transform_deriv_v(sys_utilities,\n alt_IDs,\n rows_to_alts,\n shape_params):\n return diags(np.ones(sys_utilities.shape[0]), 0, format='csr')\n\n # Designate functions that calculate the partial derivative of the\n # transformed index values, with respect to shape and index parameters\n def transform_deriv_intercepts(*args):\n return None\n\n def transform_deriv_shapes(*args):\n return None\n\n # Collect the arguments for the function being tested\n gradient_args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.choice_array,\n self.utility_transform,\n transform_deriv_shapes,\n transform_deriv_v,\n transform_deriv_intercepts,\n None,\n None,\n None,\n None]\n\n gradient_args[1] = self.fake_design[:3, :]\n gradient_args[2] = self.fake_df[self.alt_id_col].values[:3]\n gradient_args[3] = self.fake_rows_to_obs[:3, :]\n gradient_args[4] = self.fake_rows_to_alts[:3, :]\n gradient_args[5] = self.choice_array[:3]\n gradient_1 = cc.calc_gradient(*gradient_args)\n\n gradient_args[1] = self.fake_design[3:, :]\n gradient_args[2] = self.fake_df[self.alt_id_col].values[3:]\n gradient_args[3] = self.fake_rows_to_obs[3:, :]\n gradient_args[4] = self.fake_rows_to_alts[3:, :]\n gradient_args[5] = self.choice_array[3:]\n gradient_2 = cc.calc_gradient(*gradient_args)\n\n # Calcuate the BHHH approximation to the Fisher Info Matrix\n expected_result = (np.outer(gradient_1, gradient_1) +\n np.outer(gradient_2, gradient_2))\n\n # Alias the function being tested\n func = cc.calc_fisher_info_matrix\n # Get the results of the function being tested\n gradient_args[1] = self.fake_design\n gradient_args[2] = self.fake_df[self.alt_id_col].values\n gradient_args[3] = self.fake_rows_to_obs\n gradient_args[4] = self.fake_rows_to_alts\n gradient_args[5] = self.choice_array\n function_result = func(*gradient_args)\n\n # Perform the required tests\n self.assertIsInstance(function_result, np.ndarray)\n self.assertEqual(function_result.shape, expected_result.shape)\n npt.assert_allclose(function_result, expected_result)\n\n # Test the Fisher info matrix function with weights\n new_weights = 2 * np.ones(self.fake_design.shape[0])\n gradient_args[-1] = new_weights\n expected_result_weighted = 2 * expected_result\n func_result_weighted = func(*gradient_args)\n self.assertIsInstance(func_result_weighted, np.ndarray)\n self.assertEqual(func_result_weighted.shape,\n expected_result_weighted.shape)\n npt.assert_allclose(func_result_weighted, expected_result_weighted)\n\n # Test the function with the ridge penalty\n expected_result_weighted -= 2 * self.ridge\n gradient_args[-2] = self.ridge\n function_result = func(*gradient_args)\n\n self.assertIsInstance(function_result, np.ndarray)\n self.assertEqual(function_result.shape, expected_result_weighted.shape)\n npt.assert_allclose(function_result, expected_result_weighted)\n\n return None\n\n def test_calc_fisher_info_matrix_no_intercepts(self):\n \"\"\"\n Ensure that calc_fisher_info_matrix returns the expected values when\n there are no intercept parameters.\n \"\"\"\n # Designate a function that calculates the parital derivative of the\n # transformed index values, with respect to the index.\n def transform_deriv_v(sys_utilities,\n alt_IDs,\n rows_to_alts,\n shape_params):\n return diags(np.ones(sys_utilities.shape[0]), 0, format='csr')\n\n # Designate functions that calculate the partial derivative of the\n # transformed index values, with respect to shape and index parameters\n def transform_deriv_intercepts(*args):\n return None\n\n fake_deriv = np.exp(self.fake_shapes)[None, :]\n\n def transform_deriv_shapes(sys_utilities,\n alt_IDs,\n rows_to_alts,\n shape_params):\n return rows_to_alts[:, 1:].multiply(fake_deriv)\n\n # Collect the arguments needed to calculate the gradients\n gradient_args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.choice_array,\n self.utility_transform,\n transform_deriv_shapes,\n transform_deriv_v,\n transform_deriv_intercepts,\n None,\n self.fake_shapes,\n None,\n None]\n\n # Get the gradient, for each observation, separately.\n # Note this test expects that we only have two observations.\n gradient_args[1] = self.fake_design[:3, :]\n gradient_args[2] = self.fake_df[self.alt_id_col].values[:3]\n gradient_args[3] = self.fake_rows_to_obs[:3, :]\n gradient_args[4] = self.fake_rows_to_alts[:3, :]\n gradient_args[5] = self.choice_array[:3]\n gradient_1 = cc.calc_gradient(*gradient_args)\n\n gradient_args[1] = self.fake_design[3:, :]\n gradient_args[2] = self.fake_df[self.alt_id_col].values[3:]\n gradient_args[3] = self.fake_rows_to_obs[3:, :]\n gradient_args[4] = self.fake_rows_to_alts[3:, :]\n gradient_args[5] = self.choice_array[3:]\n gradient_2 = cc.calc_gradient(*gradient_args)\n\n # Calcuate the BHHH approximation to the Fisher Info Matrix\n expected_result = (np.outer(gradient_1, gradient_1) +\n np.outer(gradient_2, gradient_2))\n\n # Alias the function being tested\n func = cc.calc_fisher_info_matrix\n # Get the results of the function being tested\n gradient_args[1] = self.fake_design\n gradient_args[2] = self.fake_df[self.alt_id_col].values\n gradient_args[3] = self.fake_rows_to_obs\n gradient_args[4] = self.fake_rows_to_alts\n gradient_args[5] = self.choice_array\n function_result = func(*gradient_args)\n\n # Perform the required tests\n self.assertIsInstance(function_result, np.ndarray)\n self.assertEqual(function_result.shape, expected_result.shape)\n npt.assert_allclose(function_result, expected_result)\n\n # Test the Fisher info matrix function with weights\n new_weights = 2 * np.ones(self.fake_design.shape[0])\n gradient_args[-1] = new_weights\n expected_result_weighted = 2 * expected_result\n func_result_weighted = func(*gradient_args)\n self.assertIsInstance(func_result_weighted, np.ndarray)\n self.assertEqual(func_result_weighted.shape,\n expected_result_weighted.shape)\n npt.assert_allclose(func_result_weighted, expected_result_weighted)\n\n return None\n\n def test_calc_fisher_info_matrix_no_shapes(self):\n \"\"\"\n Ensure that calc_fisher_info_matrix returns the expected values when\n there are no shape parameters.\n \"\"\"\n # Designate a function that calculates the parital derivative of the\n # transformed index values, with respect to the index.\n def transform_deriv_v(sys_utilities,\n alt_IDs,\n rows_to_alts,\n shape_params):\n return diags(np.ones(sys_utilities.shape[0]), 0, format='csr')\n\n # Designate functions that calculate the partial derivative of the\n # transformed index values, with respect to shape and index parameters\n def transform_deriv_intercepts(sys_utilities,\n alt_IDs,\n rows_to_alts,\n shape_params):\n return rows_to_alts[:, 1:]\n\n def transform_deriv_shapes(*args):\n return None\n\n # Collect the arguments needed to calculate the gradients\n gradient_args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.choice_array,\n self.utility_transform,\n transform_deriv_shapes,\n transform_deriv_v,\n transform_deriv_intercepts,\n self.fake_intercepts,\n None,\n None,\n None]\n\n # Get the gradient, for each observation, separately.\n # Note this test expects that we only have two observations.\n gradient_args[1] = self.fake_design[:3, :]\n gradient_args[2] = self.fake_df[self.alt_id_col].values[:3]\n gradient_args[3] = self.fake_rows_to_obs[:3, :]\n gradient_args[4] = self.fake_rows_to_alts[:3, :]\n gradient_args[5] = self.choice_array[:3]\n gradient_1 = cc.calc_gradient(*gradient_args)\n\n gradient_args[1] = self.fake_design[3:, :]\n gradient_args[2] = self.fake_df[self.alt_id_col].values[3:]\n gradient_args[3] = self.fake_rows_to_obs[3:, :]\n gradient_args[4] = self.fake_rows_to_alts[3:, :]\n gradient_args[5] = self.choice_array[3:]\n gradient_2 = cc.calc_gradient(*gradient_args)\n\n # Calcuate the BHHH approximation to the Fisher Info Matrix\n expected_result = (np.outer(gradient_1, gradient_1) +\n np.outer(gradient_2, gradient_2))\n\n # Alias the function being tested\n func = cc.calc_fisher_info_matrix\n # Get the results of the function being tested\n gradient_args[1] = self.fake_design\n gradient_args[2] = self.fake_df[self.alt_id_col].values\n gradient_args[3] = self.fake_rows_to_obs\n gradient_args[4] = self.fake_rows_to_alts\n gradient_args[5] = self.choice_array\n function_result = func(*gradient_args)\n\n # Perform the required tests\n self.assertIsInstance(function_result, np.ndarray)\n self.assertEqual(function_result.shape, expected_result.shape)\n npt.assert_allclose(function_result, expected_result)\n\n # Test the Fisher info matrix function with weights\n new_weights = 2 * np.ones(self.fake_design.shape[0])\n gradient_args[-1] = new_weights\n expected_result_weighted = 2 * expected_result\n func_result_weighted = func(*gradient_args)\n self.assertIsInstance(func_result_weighted, np.ndarray)\n self.assertEqual(func_result_weighted.shape,\n expected_result_weighted.shape)\n npt.assert_allclose(func_result_weighted, expected_result_weighted)\n\n return None\n\n def test_calc_fisher_info_matrix(self):\n \"\"\"\n Ensure that calc_fisher_info_matrix returns the expected values.\n \"\"\"\n # Designate a function that calculates the parital derivative of the\n # transformed index values, with respect to the index.\n def transform_deriv_v(sys_utilities,\n alt_IDs,\n rows_to_alts,\n shape_params):\n return diags(np.ones(sys_utilities.shape[0]), 0, format='csr')\n\n # Designate functions that calculate the partial derivative of the\n # transformed index values, with respect to shape and index parameters\n def transform_deriv_intercepts(sys_utilities,\n alt_IDs,\n rows_to_alts,\n shape_params):\n return rows_to_alts[:, 1:]\n\n fake_deriv = np.exp(self.fake_shapes)[None, :]\n\n def transform_deriv_shapes(sys_utilities,\n alt_IDs,\n rows_to_alts,\n shape_params):\n return rows_to_alts[:, 1:].multiply(fake_deriv)\n\n # Collect the arguments needed to calculate the gradients\n gradient_args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.choice_array,\n self.utility_transform,\n transform_deriv_shapes,\n transform_deriv_v,\n transform_deriv_intercepts,\n self.fake_intercepts,\n self.fake_shapes,\n None,\n None]\n\n # Get the gradient, for each observation, separately.\n # Note this test expects that we only have two observations.\n gradient_args[1] = self.fake_design[:3, :]\n gradient_args[2] = self.fake_df[self.alt_id_col].values[:3]\n gradient_args[3] = self.fake_rows_to_obs[:3, :]\n gradient_args[4] = self.fake_rows_to_alts[:3, :]\n gradient_args[5] = self.choice_array[:3]\n gradient_1 = cc.calc_gradient(*gradient_args)\n\n gradient_args[1] = self.fake_design[3:, :]\n gradient_args[2] = self.fake_df[self.alt_id_col].values[3:]\n gradient_args[3] = self.fake_rows_to_obs[3:, :]\n gradient_args[4] = self.fake_rows_to_alts[3:, :]\n gradient_args[5] = self.choice_array[3:]\n gradient_2 = cc.calc_gradient(*gradient_args)\n\n # Calcuate the BHHH approximation to the Fisher Info Matrix\n expected_result = (np.outer(gradient_1, gradient_1) +\n np.outer(gradient_2, gradient_2))\n\n # Alias the function being tested\n func = cc.calc_fisher_info_matrix\n # Get the results of the function being tested\n gradient_args[1] = self.fake_design\n gradient_args[2] = self.fake_df[self.alt_id_col].values\n gradient_args[3] = self.fake_rows_to_obs\n gradient_args[4] = self.fake_rows_to_alts\n gradient_args[5] = self.choice_array\n function_result = func(*gradient_args)\n\n # Perform the required tests\n self.assertIsInstance(function_result, np.ndarray)\n self.assertEqual(function_result.shape, expected_result.shape)\n npt.assert_allclose(function_result, expected_result)\n\n # Test the Fisher info matrix function with weights\n new_weights = 2 * np.ones(self.fake_design.shape[0])\n gradient_args[-1] = new_weights\n expected_result_weighted = 2 * expected_result\n func_result_weighted = func(*gradient_args)\n self.assertIsInstance(func_result_weighted, np.ndarray)\n self.assertEqual(func_result_weighted.shape,\n expected_result_weighted.shape)\n npt.assert_allclose(func_result_weighted, expected_result_weighted)\n\n return None\n\n def test_calc_hessian_no_shapes_no_intercept(self):\n \"\"\"\n Ensure that the calc_hessian function returns expected results when\n there are no shape parameters and no intercept parameters.\n \"\"\"\n # Alias the design matrix\n design = self.fake_design\n # Get the matrix block indices for the test\n matrix_indices = cc.create_matrix_block_indices(self.fake_rows_to_obs)\n # Calculate the probabilities for this test.\n args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.utility_transform]\n kwargs = {\"intercept_params\": self.fake_intercepts,\n \"shape_params\": self.fake_shapes,\n \"return_long_probs\": True}\n probs = cc.calc_probabilities(*args, **kwargs)\n # Get the matrix blocks for dP_i_dH_i\n matrix_blocks = cc.create_matrix_blocks(probs, matrix_indices)\n # Create the dP_dH matrix that represents the derivative of the\n # long probabilities with respect to the array of transformed index\n # values / systematic utilities\n dP_dH = block_diag(matrix_blocks)\n\n # Designate a function that calculates the parital derivative of the\n # transformed index values, with respect to the index.\n def transform_deriv_v(sys_utilities,\n alt_IDs,\n rows_to_alts,\n shape_params):\n return diags(np.ones(sys_utilities.shape[0]), 0, format='csr')\n\n # Designate functions that calculate the partial derivative of the\n # transformed index values, with respect to shape and index parameters\n def transform_deriv_intercepts(*args):\n return None\n\n def transform_deriv_shapes(*args):\n return None\n\n # Collect the arguments for the hessian function being tested\n hessian_args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.utility_transform,\n transform_deriv_shapes,\n transform_deriv_v,\n transform_deriv_intercepts,\n matrix_indices,\n None,\n None,\n None,\n None]\n\n # Calculate the expected result\n # Since we're essentially dealing with an MNL model in this test,\n # the expected answer is -X^T * dP_dH * X\n\n expected_result = (-1 * design.T.dot(dP_dH.dot(design)))\n\n # Alias the function being tested\n func = cc.calc_hessian\n # Get the results of the function being tested\n function_result = func(*hessian_args)\n\n # Perform the required tests\n self.assertIsInstance(function_result, np.ndarray)\n self.assertEqual(function_result.shape, expected_result.shape)\n npt.assert_allclose(function_result, expected_result)\n\n # Test the Hessian function with weights\n new_weights = 2 * np.ones(self.fake_design.shape[0])\n hessian_args[-1] = new_weights\n expected_result_weighted = 2 * expected_result\n func_result_weighted = func(*hessian_args)\n self.assertIsInstance(func_result_weighted, np.ndarray)\n self.assertEqual(func_result_weighted.shape,\n expected_result_weighted.shape)\n npt.assert_allclose(func_result_weighted, expected_result_weighted)\n\n # Test the function with the ridge penalty\n expected_result_weighted -= 2 * self.ridge\n hessian_args[-2] = self.ridge\n function_result = func(*hessian_args)\n\n self.assertIsInstance(function_result, np.ndarray)\n self.assertEqual(function_result.shape, expected_result_weighted.shape)\n npt.assert_allclose(function_result, expected_result_weighted)\n\n return None\n\n def test_calc_hessian(self):\n \"\"\"\n Ensure that the calc_hessian function returns expected results when\n there are both shape parameters and intercept parameters.\n \"\"\"\n # Alias the design matrix\n design = self.fake_design\n # Get the matrix block indices for the test\n matrix_indices = cc.create_matrix_block_indices(self.fake_rows_to_obs)\n # Calculate the probabilities for this test.\n args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.utility_transform]\n kwargs = {\"intercept_params\": self.fake_intercepts,\n \"shape_params\": self.fake_shapes,\n \"return_long_probs\": True}\n probs = cc.calc_probabilities(*args, **kwargs)\n # Get the matrix blocks for dP_i_dH_i\n matrix_blocks = cc.create_matrix_blocks(probs, matrix_indices)\n # Create the dP_dH matrix that represents the derivative of the\n # long probabilities with respect to the array of transformed index\n # values / systematic utilities\n dP_dH = block_diag(matrix_blocks)\n\n # Designate a function that calculates the parital derivative of the\n # transformed index values, with respect to the index.\n def transform_deriv_v(sys_utilities,\n alt_IDs,\n rows_to_alts,\n shape_params):\n return diags(np.ones(sys_utilities.shape[0]), 0, format='csr')\n\n # Designate functions that calculate the partial derivative of the\n # transformed index values, with respect to shape and index parameters\n def transform_deriv_intercepts(sys_utilities,\n alt_IDs,\n rows_to_alts,\n intercept_params):\n return rows_to_alts[:, 1:]\n\n fake_deriv = np.exp(self.fake_shapes)[None, :]\n\n def transform_deriv_shapes(sys_utilities,\n alt_IDs,\n rows_to_alts,\n shape_params):\n return rows_to_alts[:, 1:].multiply(fake_deriv)\n\n # Collect the arguments for the hessian function being tested\n hessian_args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.utility_transform,\n transform_deriv_shapes,\n transform_deriv_v,\n transform_deriv_intercepts,\n matrix_indices,\n self.fake_intercepts,\n self.fake_shapes,\n None,\n None]\n\n # Calculate the derivative of the transformation vector with respect\n # to the shape parameters.\n args = (design.dot(self.fake_betas),\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_alts,\n self.fake_shapes)\n dh_d_shape = transform_deriv_shapes(*args)\n\n # Calculate the derivative of the transformation vector with respect\n # to the intercept parameters\n dh_d_intercept = self.fake_rows_to_alts[:, 1:]\n\n # Calculate the various matrices needed for the expected result\n # Note dH_dV is the Identity matrix in this test.\n # See the documentation pdf for a description of what each of these\n # matrixes are.\n # h_33 is -X^T * dP_dH * X. This is the hessian in the standard MNL\n h_33 = np.asarray(-1 * design.T.dot(dP_dH.dot(design)))\n # h_32 is -X^T * dH_dV^T * dP_dH * dH_d_intercept\n h_32 = np.asarray(-1 * design.T.dot(dP_dH.dot(dh_d_intercept.A)))\n # h_31 is -X^T * dH_dV^T * dP_dH * dH_d_shape\n h_31 = np.asarray(-1 * design.T.dot(dP_dH.dot(dh_d_shape.A)))\n # h_21 = -dH_d_intercept^T * dP_dH * dH_d_shape\n h_21 = np.asarray(-1 * dh_d_intercept.T.dot(dP_dH.dot(dh_d_shape.A)))\n # h_22 = -dH_d_intercept^T * dP_dH * dH_d_intercept\n h_22 = np.asarray(-1 *\n dh_d_intercept.T.dot(dP_dH.dot(dh_d_intercept.A)))\n # h_11 = -dH_d_shape^T * dP_dH * dH_d_shape\n h_11 = np.asarray(-1 * dh_d_shape.T.dot(dP_dH.dot(dh_d_shape.A)))\n\n # Create the final hessian\n top_row = np.concatenate((h_11, h_21.T, h_31.T), axis=1)\n middle_row = np.concatenate((h_21, h_22, h_32.T), axis=1)\n bottom_row = np.concatenate((h_31, h_32, h_33), axis=1)\n expected_result = np.concatenate((top_row, middle_row, bottom_row),\n axis=0)\n\n # Alias the function being tested\n func = cc.calc_hessian\n # Get the results of the function being tested\n function_result = func(*hessian_args)\n\n # Perform the required tests\n self.assertIsInstance(function_result, np.ndarray)\n self.assertEqual(function_result.shape, expected_result.shape)\n self.assertFalse(isinstance(function_result,\n np.matrixlib.defmatrix.matrix))\n npt.assert_allclose(function_result, expected_result)\n\n # Test the Hessian function with weights\n new_weights = 2 * np.ones(self.fake_design.shape[0])\n hessian_args[-1] = new_weights\n expected_result_weighted = 2 * expected_result\n func_result_weighted = func(*hessian_args)\n self.assertIsInstance(func_result_weighted, np.ndarray)\n self.assertEqual(func_result_weighted.shape,\n expected_result_weighted.shape)\n npt.assert_allclose(func_result_weighted, expected_result_weighted)\n\n # Test the function with the ridge penalty\n expected_result_weighted -= 2 * self.ridge\n hessian_args[-2] = self.ridge\n function_result = func(*hessian_args)\n\n self.assertIsInstance(function_result, np.ndarray)\n self.assertEqual(function_result.shape, expected_result_weighted.shape)\n self.assertFalse(isinstance(function_result,\n np.matrixlib.defmatrix.matrix))\n npt.assert_allclose(function_result, expected_result_weighted)\n\n return None\n\n def test_calc_hessian_no_shapes(self):\n \"\"\"\n Ensure that the calc_hessian function returns expected results when\n there are no shape parameters.\n \"\"\"\n # Alias the design matrix\n design = self.fake_design\n # Get the matrix block indices for the test\n matrix_indices = cc.create_matrix_block_indices(self.fake_rows_to_obs)\n # Calculate the probabilities for this test.\n args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.utility_transform]\n kwargs = {\"intercept_params\": self.fake_intercepts,\n \"shape_params\": self.fake_shapes,\n \"return_long_probs\": True}\n probs = cc.calc_probabilities(*args, **kwargs)\n # Get the matrix blocks for dP_i_dH_i\n matrix_blocks = cc.create_matrix_blocks(probs, matrix_indices)\n # Create the dP_dH matrix that represents the derivative of the\n # long probabilities with respect to the array of transformed index\n # values / systematic utilities\n dP_dH = block_diag(matrix_blocks)\n\n # Designate a function that calculates the parital derivative of the\n # transformed index values, with respect to the index.\n def transform_deriv_v(sys_utilities,\n alt_IDs,\n rows_to_alts,\n shape_params):\n return diags(np.ones(sys_utilities.shape[0]), 0, format='csr')\n\n # Designate functions that calculate the partial derivative of the\n # transformed index values, with respect to shape and index parameters\n def transform_deriv_intercepts(sys_utilities,\n alt_IDs,\n rows_to_alts,\n intercept_params):\n return rows_to_alts[:, 1:]\n\n def transform_deriv_shapes(sys_utilities,\n alt_IDs,\n rows_to_alts,\n shape_params):\n return None\n\n # Collect the arguments for the hessian function being tested\n hessian_args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.utility_transform,\n transform_deriv_shapes,\n transform_deriv_v,\n transform_deriv_intercepts,\n matrix_indices,\n self.fake_intercepts,\n None,\n None,\n None]\n\n # Calculate the derivative of the transformation vector with respect\n # to the intercept parameters\n dh_d_intercept = self.fake_rows_to_alts[:, 1:]\n\n # Calculate the various matrices needed for the expected result\n # Note dH_dV is the Identity matrix in this test.\n # See the documentation pdf for a description of what each of these\n # matrixes are.\n # h_33 is -X^T * dP_dH * X. This is the hessian in the standard MNL\n h_33 = np.asarray(-1 * design.T.dot(dP_dH.dot(design)))\n # h_32 is -X^T * dH_dV^T * dP_dH * dH_d_intercept\n h_32 = np.asarray(-1 * design.T.dot(dP_dH.dot(dh_d_intercept.A)))\n # h_22 = -dH_d_intercept^T * dP_dH * dH_d_intercept\n h_22 = np.asarray(-1 *\n dh_d_intercept.T.dot(dP_dH.dot(dh_d_intercept.A)))\n\n # Create the final hessian\n middle_row = np.concatenate((h_22, h_32.T), axis=1)\n bottom_row = np.concatenate((h_32, h_33), axis=1)\n expected_result = np.concatenate((middle_row, bottom_row), axis=0)\n\n # Alias the function being tested\n func = cc.calc_hessian\n # Get the results of the function being tested\n function_result = func(*hessian_args)\n\n # Perform the required tests\n self.assertIsInstance(function_result, np.ndarray)\n self.assertEqual(function_result.shape, expected_result.shape)\n self.assertFalse(isinstance(function_result,\n np.matrixlib.defmatrix.matrix))\n npt.assert_allclose(function_result, expected_result)\n\n # Test the Hessian function with weights\n new_weights = 2 * np.ones(self.fake_design.shape[0])\n hessian_args[-1] = new_weights\n expected_result_weighted = 2 * expected_result\n func_result_weighted = func(*hessian_args)\n self.assertIsInstance(func_result_weighted, np.ndarray)\n self.assertEqual(func_result_weighted.shape,\n expected_result_weighted.shape)\n npt.assert_allclose(func_result_weighted, expected_result_weighted)\n\n return None\n\n def test_calc_hessian_no_intercepts(self):\n \"\"\"\n Ensure that the calc_hessian function returns expected results when\n there are no intercept parameters.\n \"\"\"\n # Alias the design matrix\n design = self.fake_design\n # Get the matrix block indices for the test\n matrix_indices = cc.create_matrix_block_indices(self.fake_rows_to_obs)\n # Calculate the probabilities for this test.\n args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.utility_transform]\n kwargs = {\"intercept_params\": self.fake_intercepts,\n \"shape_params\": self.fake_shapes,\n \"return_long_probs\": True}\n probs = cc.calc_probabilities(*args, **kwargs)\n # Get the matrix blocks for dP_i_dH_i\n matrix_blocks = cc.create_matrix_blocks(probs, matrix_indices)\n # Create the dP_dH matrix that represents the derivative of the\n # long probabilities with respect to the array of transformed index\n # values / systematic utilities\n dP_dH = block_diag(matrix_blocks)\n\n # Designate a function that calculates the parital derivative of the\n # transformed index values, with respect to the index.\n def transform_deriv_v(sys_utilities,\n alt_IDs,\n rows_to_alts,\n shape_params):\n return diags(np.ones(sys_utilities.shape[0]), 0, format='csr')\n\n # Designate functions that calculate the partial derivative of the\n # transformed index values, with respect to shape and index parameters\n def transform_deriv_intercepts(sys_utilities,\n alt_IDs,\n rows_to_alts,\n intercept_params):\n return None\n\n fake_deriv = np.exp(self.fake_shapes)[None, :]\n\n def transform_deriv_shapes(sys_utilities,\n alt_IDs,\n rows_to_alts,\n shape_params):\n return rows_to_alts[:, 1:].multiply(fake_deriv)\n\n # Collect the arguments for the hessian function being tested\n hessian_args = [self.fake_betas,\n self.fake_design,\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_obs,\n self.fake_rows_to_alts,\n self.utility_transform,\n transform_deriv_shapes,\n transform_deriv_v,\n transform_deriv_intercepts,\n matrix_indices,\n None,\n self.fake_shapes,\n None,\n None]\n\n # Calculate the derivative of the transformation vector with respect\n # to the shape parameters.\n args = (design.dot(self.fake_betas),\n self.fake_df[self.alt_id_col].values,\n self.fake_rows_to_alts,\n self.fake_shapes)\n dh_d_shape = transform_deriv_shapes(*args)\n\n # Calculate the various matrices needed for the expected result\n # Note dH_dV is the Identity matrix in this test.\n # See the documentation pdf for a description of what each of these\n # matrixes are.\n # h_33 is -X^T * dP_dH * X. This is the hessian in the standard MNL\n h_33 = np.asarray(-1 * design.T.dot(dP_dH.dot(design)))\n # h_31 is -X^T * dH_dV^T * dP_dH * dH_d_shape\n h_31 = np.asarray(-1 * design.T.dot(dP_dH.dot(dh_d_shape.A)))\n # h_11 = -dH_d_shape^T * dP_dH * dH_d_shape\n h_11 = np.asarray(-1 * dh_d_shape.T.dot(dP_dH.dot(dh_d_shape.A)))\n\n # Create the final hessian\n top_row = np.concatenate((h_11, h_31.T), axis=1)\n bottom_row = np.concatenate((h_31, h_33), axis=1)\n expected_result = np.concatenate((top_row, bottom_row), axis=0)\n\n # Alias the function being tested\n func = cc.calc_hessian\n # Get the results of the function being tested\n function_result = func(*hessian_args)\n\n # Perform the required tests\n self.assertIsInstance(function_result, np.ndarray)\n self.assertEqual(function_result.shape, expected_result.shape)\n npt.assert_allclose(function_result, expected_result)\n\n # Test the Hessian function with weights\n new_weights = 2 * np.ones(self.fake_design.shape[0])\n hessian_args[-1] = new_weights\n expected_result_weighted = 2 * expected_result\n func_result_weighted = func(*hessian_args)\n self.assertIsInstance(func_result_weighted, np.ndarray)\n self.assertEqual(func_result_weighted.shape,\n expected_result_weighted.shape)\n npt.assert_allclose(func_result_weighted, expected_result_weighted)\n\n return None\n" ]
[ [ "numpy.diag", "numpy.dot", "numpy.log", "numpy.arange", "scipy.sparse.block_diag", "numpy.ones", "numpy.concatenate", "numpy.seterr", "numpy.testing.assert_allclose", "numpy.exp", "numpy.outer", "numpy.array", "numpy.zeros", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] } ]
shenlong95/fseval
[ "4d2e6618b8838f9e52fe60621b08595dc4c5b4fb" ]
[ "fseval/pipelines/rank_and_validate/_dataset_validator.py" ]
[ "from dataclasses import dataclass\nfrom typing import Dict, List, Union, cast\n\nimport numpy as np\nimport pandas as pd\nfrom omegaconf import MISSING\nfrom sklearn.base import clone\n\nfrom fseval.pipeline.estimator import Estimator\n\nfrom .._experiment import Experiment\nfrom ._config import RankAndValidatePipeline\nfrom ._subset_validator import SubsetValidator\n\n\n@dataclass\nclass DatasetValidator(Experiment, RankAndValidatePipeline):\n \"\"\"Validates an entire dataset, given a fitted ranker and its feature ranking. Fits\n at most `p` feature subsets, at each step incrementally including more top-features.\"\"\"\n\n bootstrap_state: int = MISSING\n\n def _get_all_features_to_select(self, n: int, p: int) -> List[int]:\n \"\"\"parse all features to select from config\"\"\"\n assert n is not None and p is not None, \"dataset must be loaded!\"\n assert (\n n > 0 and p > 0\n ), f\"dataset must have > 0 samples (n was {n} and p was {p})\"\n\n # set using `exec`\n localz = locals()\n exec(\n f\"all_features_to_select = {self.all_features_to_select}\",\n globals(),\n localz,\n )\n all_features_to_select = localz[\"all_features_to_select\"]\n all_features_to_select = cast(List[int], all_features_to_select)\n all_features_to_select = list(all_features_to_select)\n\n assert (\n all_features_to_select\n ), f\"Incorrect `all_features_to_select` string: {self.all_features_to_select}\"\n\n return all_features_to_select\n\n def _get_estimator(self):\n all_features_to_select = self._get_all_features_to_select(\n self.dataset.n, self.dataset.p\n )\n\n # validate all subsets\n for n_features_to_select in all_features_to_select:\n config = self._get_config()\n validator = config.pop(\"validator\")\n\n yield SubsetValidator(\n **config,\n validator=clone(validator),\n n_features_to_select=n_features_to_select,\n bootstrap_state=self.bootstrap_state,\n )\n\n def _get_estimator_repr(self, estimator):\n return Estimator._get_estimator_repr(estimator.validator)\n\n def _get_overrides_text(self, estimator):\n return f\"[n_features_to_select={estimator.n_features_to_select}] \"\n\n def score(self, X, y, **kwargs) -> Union[Dict, pd.DataFrame, np.generic, None]:\n scores = super(DatasetValidator, self).score(X, y, **kwargs)\n\n # custom metrics\n for metric_name, metric_class in self.metrics.items():\n scores_metric = metric_class.score_dataset(scores, self.callbacks)\n\n if scores_metric is not None:\n scores = scores_metric\n\n return scores\n" ]
[ [ "sklearn.base.clone" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
pranjaldatta/metrics
[ "078671fa0b28d7d0a9c505b077d9acc8ac28a69d" ]
[ "torchmetrics/classification/accuracy.py" ]
[ "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom typing import Any, Callable, Optional\n\nfrom torch import Tensor, tensor\n\nfrom torchmetrics.functional.classification.accuracy import (\n _accuracy_compute,\n _accuracy_update,\n _check_subset_validity,\n _mode,\n _subset_accuracy_compute,\n _subset_accuracy_update,\n)\n\nfrom torchmetrics.classification.stat_scores import StatScores # isort:skip\n\n\nclass Accuracy(StatScores):\n r\"\"\"\n Computes `Accuracy <https://en.wikipedia.org/wiki/Accuracy_and_precision>`__:\n\n .. math::\n \\text{Accuracy} = \\frac{1}{N}\\sum_i^N 1(y_i = \\hat{y}_i)\n\n Where :math:`y` is a tensor of target values, and :math:`\\hat{y}` is a\n tensor of predictions.\n\n For multi-class and multi-dimensional multi-class data with probability or logits predictions, the\n parameter ``top_k`` generalizes this metric to a Top-K accuracy metric: for each sample the\n top-K highest probability or logit score items are considered to find the correct label.\n\n For multi-label and multi-dimensional multi-class inputs, this metric computes the \"global\"\n accuracy by default, which counts all labels or sub-samples separately. This can be\n changed to subset accuracy (which requires all labels or sub-samples in the sample to\n be correctly predicted) by setting ``subset_accuracy=True``.\n\n Accepts all input types listed in :ref:`references/modules:input types`.\n\n Args:\n num_classes:\n Number of classes. Necessary for ``'macro'``, ``'weighted'`` and ``None`` average methods.\n threshold:\n Threshold for transforming probability or logit predictions to binary (0,1) predictions, in the case\n of binary or multi-label inputs. Default value of 0.5 corresponds to input being probabilities.\n average:\n Defines the reduction that is applied. Should be one of the following:\n\n - ``'micro'`` [default]: Calculate the metric globally, across all samples and classes.\n - ``'macro'``: Calculate the metric for each class separately, and average the\n metrics across classes (with equal weights for each class).\n - ``'weighted'``: Calculate the metric for each class separately, and average the\n metrics across classes, weighting each class by its support (``tp + fn``).\n - ``'none'`` or ``None``: Calculate the metric for each class separately, and return\n the metric for every class.\n - ``'samples'``: Calculate the metric for each sample, and average the metrics\n across samples (with equal weights for each sample).\n\n .. note:: What is considered a sample in the multi-dimensional multi-class case\n depends on the value of ``mdmc_average``.\n\n mdmc_average:\n Defines how averaging is done for multi-dimensional multi-class inputs (on top of the\n ``average`` parameter). Should be one of the following:\n\n - ``None`` [default]: Should be left unchanged if your data is not multi-dimensional\n multi-class.\n\n - ``'samplewise'``: In this case, the statistics are computed separately for each\n sample on the ``N`` axis, and then averaged over samples.\n The computation for each sample is done by treating the flattened extra axes ``...``\n (see :ref:`references/modules:input types`) as the ``N`` dimension within the sample,\n and computing the metric for the sample based on that.\n\n - ``'global'``: In this case the ``N`` and ``...`` dimensions of the inputs\n (see :ref:`references/modules:input types`)\n are flattened into a new ``N_X`` sample axis, i.e. the inputs are treated as if they\n were ``(N_X, C)``. From here on the ``average`` parameter applies as usual.\n\n ignore_index:\n Integer specifying a target class to ignore. If given, this class index does not contribute\n to the returned score, regardless of reduction method. If an index is ignored, and ``average=None``\n or ``'none'``, the score for the ignored class will be returned as ``nan``.\n\n top_k:\n Number of highest probability or logit score predictions considered to find the correct label,\n relevant only for (multi-dimensional) multi-class inputs. The\n default value (``None``) will be interpreted as 1 for these inputs.\n\n Should be left at default (``None``) for all other types of inputs.\n\n multiclass:\n Used only in certain special cases, where you want to treat inputs as a different type\n than what they appear to be. See the parameter's\n :ref:`documentation section <references/modules:using the multiclass parameter>`\n for a more detailed explanation and examples.\n\n subset_accuracy:\n Whether to compute subset accuracy for multi-label and multi-dimensional\n multi-class inputs (has no effect for other input types).\n\n - For multi-label inputs, if the parameter is set to ``True``, then all labels for\n each sample must be correctly predicted for the sample to count as correct. If it\n is set to ``False``, then all labels are counted separately - this is equivalent to\n flattening inputs beforehand (i.e. ``preds = preds.flatten()`` and same for ``target``).\n\n - For multi-dimensional multi-class inputs, if the parameter is set to ``True``, then all\n sub-sample (on the extra axis) must be correct for the sample to be counted as correct.\n If it is set to ``False``, then all sub-samples are counter separately - this is equivalent,\n in the case of label predictions, to flattening the inputs beforehand (i.e.\n ``preds = preds.flatten()`` and same for ``target``). Note that the ``top_k`` parameter\n still applies in both cases, if set.\n\n compute_on_step:\n Forward only calls ``update()`` and return ``None`` if this is set to ``False``.\n dist_sync_on_step:\n Synchronize metric state across processes at each ``forward()``\n before returning the value at the step\n process_group:\n Specify the process group on which synchronization is called.\n default: ``None`` (which selects the entire world)\n dist_sync_fn:\n Callback that performs the allgather operation on the metric state. When ``None``, DDP\n will be used to perform the allgather\n\n Raises:\n ValueError:\n If ``threshold`` is not between ``0`` and ``1``.\n ValueError:\n If ``top_k`` is not an ``integer`` larger than ``0``.\n ValueError:\n If ``average`` is none of ``\"micro\"``, ``\"macro\"``, ``\"weighted\"``, ``\"samples\"``, ``\"none\"``, ``None``.\n ValueError:\n If two different input modes are provided, eg. using ``multi-label`` with ``multi-class``.\n ValueError:\n If ``top_k`` parameter is set for ``multi-label`` inputs.\n\n Example:\n >>> import torch\n >>> from torchmetrics import Accuracy\n >>> target = torch.tensor([0, 1, 2, 3])\n >>> preds = torch.tensor([0, 2, 1, 3])\n >>> accuracy = Accuracy()\n >>> accuracy(preds, target)\n tensor(0.5000)\n\n >>> target = torch.tensor([0, 1, 2])\n >>> preds = torch.tensor([[0.1, 0.9, 0], [0.3, 0.1, 0.6], [0.2, 0.5, 0.3]])\n >>> accuracy = Accuracy(top_k=2)\n >>> accuracy(preds, target)\n tensor(0.6667)\n\n \"\"\"\n\n def __init__(\n self,\n threshold: float = 0.5,\n num_classes: Optional[int] = None,\n average: str = \"micro\",\n mdmc_average: Optional[str] = \"global\",\n ignore_index: Optional[int] = None,\n top_k: Optional[int] = None,\n multiclass: Optional[bool] = None,\n subset_accuracy: bool = False,\n compute_on_step: bool = True,\n dist_sync_on_step: bool = False,\n process_group: Optional[Any] = None,\n dist_sync_fn: Callable = None,\n ):\n allowed_average = [\"micro\", \"macro\", \"weighted\", \"samples\", \"none\", None]\n if average not in allowed_average:\n raise ValueError(f\"The `average` has to be one of {allowed_average}, got {average}.\")\n\n super().__init__(\n reduce=\"macro\" if average in [\"weighted\", \"none\", None] else average,\n mdmc_reduce=mdmc_average,\n threshold=threshold,\n top_k=top_k,\n num_classes=num_classes,\n multiclass=multiclass,\n ignore_index=ignore_index,\n compute_on_step=compute_on_step,\n dist_sync_on_step=dist_sync_on_step,\n process_group=process_group,\n dist_sync_fn=dist_sync_fn,\n )\n\n self.add_state(\"correct\", default=tensor(0), dist_reduce_fx=\"sum\")\n self.add_state(\"total\", default=tensor(0), dist_reduce_fx=\"sum\")\n\n if not 0 < threshold < 1:\n raise ValueError(f\"The `threshold` should be a float in the (0,1) interval, got {threshold}\")\n\n if top_k is not None and (not isinstance(top_k, int) or top_k <= 0):\n raise ValueError(f\"The `top_k` should be an integer larger than 0, got {top_k}\")\n\n self.average = average\n self.threshold = threshold\n self.top_k = top_k\n self.subset_accuracy = subset_accuracy\n self.mode = None\n self.multiclass = multiclass\n\n def update(self, preds: Tensor, target: Tensor):\n \"\"\"\n Update state with predictions and targets. See :ref:`references/modules:input types` for more information\n on input types.\n\n Args:\n preds: Predictions from model (logits, probabilities, or labels)\n target: Ground truth labels\n \"\"\"\n \"\"\" returns the mode of the data (binary, multi label, multi class, multi-dim multi class) \"\"\"\n mode = _mode(preds, target, self.threshold, self.top_k, self.num_classes, self.multiclass)\n\n if self.mode is None:\n self.mode = mode\n elif self.mode != mode:\n raise ValueError(\"You can not use {} inputs with {} inputs.\".format(mode, self.mode))\n\n if self.subset_accuracy and not _check_subset_validity(self.mode):\n self.subset_accuracy = False\n\n if self.subset_accuracy:\n correct, total = _subset_accuracy_update(preds, target, threshold=self.threshold, top_k=self.top_k)\n self.correct += correct\n self.total += total\n else:\n tp, fp, tn, fn = _accuracy_update(\n preds,\n target,\n reduce=self.reduce,\n mdmc_reduce=self.mdmc_reduce,\n threshold=self.threshold,\n num_classes=self.num_classes,\n top_k=self.top_k,\n multiclass=self.multiclass,\n ignore_index=self.ignore_index,\n mode=self.mode,\n )\n\n # Update states\n if self.reduce != \"samples\" and self.mdmc_reduce != \"samplewise\":\n self.tp += tp\n self.fp += fp\n self.tn += tn\n self.fn += fn\n else:\n self.tp.append(tp)\n self.fp.append(fp)\n self.tn.append(tn)\n self.fn.append(fn)\n\n def compute(self) -> Tensor:\n \"\"\"\n Computes accuracy based on inputs passed in to ``update`` previously.\n \"\"\"\n if self.subset_accuracy:\n return _subset_accuracy_compute(self.correct, self.total)\n else:\n tp, fp, tn, fn = self._get_final_stats()\n return _accuracy_compute(tp, fp, tn, fn, self.average, self.mdmc_reduce, self.mode)\n\n @property\n def is_differentiable(self):\n return False\n" ]
[ [ "torch.tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
AgilePlaya/Image-Processing-Basics
[ "34c3ecf42a4589b95787fb66c19ffd21bbaf3ee3" ]
[ "Codes/Sobel-Edge/sobel.py" ]
[ "from scipy import *\nfrom scipy import signal\nfrom PIL import Image\nimport cv2\nimport numpy\nimport math\nimport imageio\n\n# Locating the image. If the image is not same then change to relative address.\nusedImage = '../../Images/2.jpg'\n\n# Opening the image into an array\nimg = numpy.array(Image.open(usedImage).convert(\"L\"))\n\n# Kernel to perform gaussian blur\nkernel = [[1, 1, 1],\n [1, 1, 1],\n [1, 1, 1]]\n\n# CONVOLUTION 1\n# Performing gaussain blur by performing convolution with gaussian kernel.\n# I could not code the convolution so I got irritated and used a function for\n# convolution instead.\ngaussian = signal.convolve(img, kernel, mode='same')\n\n# Print array just to check the output. Can uncomment if you want.\n# print ('Im: Convolution 1')\n# print (gaussian)\n\n# Saving the array with the blurred image as a JPG image\nimageio.imwrite('./Outputs/smooth.jpeg', gaussian)\n# cv2.imshow('smooth.jpeg', gaussian) # This statement does not work btw\n\n# Kernel for Sobel X (using horizontal transformation)\nkernelX = [[-1, 0, 1],\n [-2, 0, 2],\n [-1, 0, 1]]\n\n# Kernel for Sobel Y (using vertical transformation)\nkernelY = [[-1, -2, -1],\n [0, 0, 0],\n [1, 2, 1]]\n\n# CONVOLUTION 2\n# Performing convolution over the smoothed image with all the generated kernels.\n\n# Generate output array imX of horizontal convolution\nimX = signal.convolve(gaussian, kernelX, mode='same')\n# Generate output array imY of vertical convolution\nimY = signal.convolve(gaussian, kernelY, mode='same')\n\n# Printing arrays to console just to check\n# print ('Im X: Convolution 2')\n# print (imX)\n# print ('Im Y: Convolution 2')\n# print (imY)\n# print ('Im XY: Convolution 2')\n# print (imXY)\n# print ('Im YX: Convolution 2')\n# print (imYX)\n\n# Saving the arrays created as JPG images\nimageio.imwrite('./Outputs/imX.jpeg', imX)\nimageio.imwrite('./Outputs/imY.jpeg', imY)\n'''cv2.imshow('imX.jpeg', imX)\ncv2.imshow('imY.jpeg', imY)'''\n\n# Combining all the horizontal and vertical gradient approximations \n# to create the final canny edge detected image\nimFinal = numpy.lib.scimath.sqrt(imX*imX + imY*imY)\n\n# Printing the canny edge detected image array just to check\n# print ('Im Final: Combining Gradient Approximations')\n# print (imFinal)\n\n# Saving the final canny edge detection image as a JPG image\nimageio.imwrite('./Outputs/sobel.jpeg', imFinal)\n# cv2.imshow('canny.jpeg', imFinal)\n\nprint ('Finished Sobel edge detection')\n" ]
[ [ "scipy.signal.convolve", "numpy.lib.scimath.sqrt" ] ]
[ { "matplotlib": [], "numpy": [ "1.11", "1.19", "1.24", "1.16", "1.23", "1.20", "1.7", "1.12", "1.21", "1.22", "1.14", "1.6", "1.13", "1.9", "1.17", "1.10", "1.18", "1.15", "1.8" ], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
avcopan/KinBot
[ "847e430fb1ee15b5c16ce095bdf7a07087ec9b0a" ]
[ "kinbot/irc.py" ]
[ "###################################################\n## ##\n## This file is part of the KinBot code v2.0 ##\n## ##\n## The contents are covered by the terms of the ##\n## BSD 3-clause license included in the LICENSE ##\n## file, found at the root. ##\n## ##\n## Copyright 2018 National Technology & ##\n## Engineering Solutions of Sandia, LLC (NTESS). ##\n## Under the terms of Contract DE-NA0003525 with ##\n## NTESS, the U.S. Government retains certain ##\n## rights to this software. ##\n## ##\n## Authors: ##\n## Judit Zador ##\n## Ruben Van de Vijver ##\n## ##\n###################################################\nimport numpy as np\nimport os\nimport copy\nimport time\nimport logging\nfrom shutil import copyfile\nimport pkg_resources\n\nfrom stationary_pt import StationaryPoint\n\n\nclass IRC:\n \"\"\"\n Class to run the IRC's for one specific reaction\n \"\"\"\n def __init__(self, rxn, par):\n # instance of the reac_family object\n # the family this reaction belongs to\n self.rxn = rxn\n self.par = par\n\n def irc2stationary_pt(self):\n \"\"\"\n Read the irc files\n There are three possible scenarios:\n 1. One of the ircs leads the initial well and\n the other to another well or bimolecular product\n 2. Neither of the ircs lead to the inital well,\n transition state structure is not the one\n kinbot was looking for\n 3. Both the ircs lead to the initial well,\n KinBot found either an identical reaction\n or the ts is not correct\n \"\"\"\n instance_name = self.rxn.instance_name\n\n directions = ['Forward', 'Reverse']\n\n ini_well_hits = 0\n prod_hit = -1\n st_pts = [-1, -1]\n for i, direction in enumerate(directions):\n irc_name = '{}_IRC_{}_prod'.format(instance_name, direction[0])\n err, geom = self.rxn.qc.get_qc_geom(irc_name,\n self.rxn.species.natom,\n allow_error=1)\n if err == -1:\n return 0\n if self.problem_in_geom(geom):\n # this happens seldomly that all the atoms are\n # very close to one another (problem in Gaussian)\n logging.info('\\tProblem with product geometry for {}'.format(instance_name))\n return 0\n\n temp = StationaryPoint(irc_name,\n self.rxn.species.charge,\n self.rxn.species.mult,\n atom=self.rxn.species.atom,\n geom=geom)\n temp.calc_chemid()\n\n st_pts[i] = temp\n if temp.chemid == self.rxn.species.chemid:\n ini_well_hits += 1\n else:\n prod_hit = i\n\n if ini_well_hits == 0:\n logging.info('\\tNeither IRC leads to the well for {}'.format(instance_name))\n return 0\n elif ini_well_hits == 2:\n logging.info('\\tBoth IRCs lead to the well, identical reaction found: {}'.format(instance_name))\n return 0\n else:\n # ircs OK: well and product found\n logging.info('\\tIRCs succesful for {}'.format(instance_name))\n return st_pts[prod_hit]\n\n def problem_in_geom(self, geom):\n # check if interatomic distances are closer than 0.3 Angstrom\n for i in range(len(geom)):\n for j in range(i+1, len(geom)):\n dist = np.linalg.norm(geom[i] - geom[j])\n if dist < 0.3:\n return 1\n return 0\n\n def check_irc(self):\n instance_name = self.rxn.instance_name\n directions = ['Forward', 'Reverse']\n status = [-1, -1]\n for i, direction in enumerate(directions):\n irc_name = '{}_IRC_{}'.format(instance_name, direction[0])\n status[i] = self.rxn.qc.check_qc(irc_name)\n return status\n\n def do_irc_calculations(self):\n \"\"\"\n Carry out the IRC calculation.\n \"\"\"\n instance_name = self.rxn.instance_name\n err, geom = self.rxn.qc.get_qc_geom(instance_name,\n self.rxn.species.natom)\n directions = ['Forward', 'Reverse']\n for i, direction in enumerate(directions):\n irc_name = '{}_IRC_{}'.format(instance_name, direction[0])\n if self.rxn.qc.qc == 'gauss':\n # copy the chk file\n if os.path.exists(instance_name + '.chk'):\n copyfile(instance_name + '.chk', irc_name + '.chk')\n\n if self.rxn.qc.qc == 'nwchem' and direction == 'Reverse':\n direction = 'Backward'\n\n odft = self.rxn.species.mult > 1\n kwargs = self.rxn.qc.get_qc_arguments(irc_name,\n self.rxn.species.mult,\n self.rxn.species.charge,\n irc=direction.lower())\n prod_kwargs = self.rxn.qc.get_qc_arguments(irc_name + '_prod', self.rxn.species.mult, self.rxn.species.charge)\n if self.rxn.qc.qc == 'gauss':\n prod_kwargs['opt'] = 'CalcFC, Tight, MaxCycle=10'\n\n template_file = pkg_resources.resource_filename('tpl', 'ase_{qc}_irc.py.tpl'.format(qc=self.rxn.qc.qc))\n template = open(template_file, 'r').read()\n template = template.format(label=irc_name,\n kwargs=kwargs,\n prod_kwargs=prod_kwargs,\n atom=list(self.rxn.species.atom),\n geom=list([list(gi) for gi in geom]),\n ppn=self.rxn.qc.ppn,\n qc_command=self.par.par['qc_command'])\n\n f_out = open('{}.py'.format(irc_name), 'w')\n f_out.write(template)\n f_out.close()\n\n self.rxn.qc.submit_qc(irc_name, 0)\n\n return 0\n" ]
[ [ "numpy.linalg.norm" ] ]
[ { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
antoneri/mapping-hypergraphs
[ "f81425c6bbd45b0537f8a0da2ddc24ec79730593" ]
[ "analysis/stats.py" ]
[ "import os\nfrom collections import defaultdict\nfrom itertools import takewhile, dropwhile\nfrom statistics import mean, variance\nfrom typing import Sequence\n\nimport pandas as pd\n\nfrom hypergraph.network import Tree\n\n\ndef summarize(networks: Sequence[Tree]) -> pd.DataFrame:\n summary = defaultdict(list)\n\n for network in networks:\n states_filename = os.path.splitext(network.filename)[0] + \"_states.net\"\n\n with open(states_filename) as states_fp:\n states_lines = states_fp.readlines()\n\n num_states = len(list(takewhile(lambda line: not line.startswith(\"*Links\"),\n dropwhile(lambda line: not line.startswith(\"# stateId physicalId\"),\n states_lines)))) - 1\n\n num_links = len(list(dropwhile(lambda line: not line.startswith(\"*Links\"), states_lines))) - 1\n\n summary[\"network\"].append(network.pretty_filename)\n summary[\"num states\"].append(num_states)\n summary[\"num links\"].append(num_links)\n summary[\"levels\"].append(network.levels)\n summary[\"top modules\"].append(network.num_top_modules)\n summary[\"leaf modules\"].append(network.num_leaf_modules)\n summary[\"codelength\"].append(network.codelength)\n summary[\"variance\"].append(variance(network.codelengths))\n summary[\"completed in\"].append(network.completed_in)\n summary[\"mean assignments\"].append(mean(network.assignments.values()))\n summary[\"mean eff. assignments\"].append(mean(network.effective_assignments.values()))\n\n return pd.DataFrame(data=summary)\n" ]
[ [ "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
kykosic/machine-learning
[ "57f7bd016761baf80af812b91d456aef63b8de08" ]
[ "explore/pca-visualization/PCA_Visualization.py" ]
[ "\n# coding: utf-8\n\n# # Using Principal Component Analysis (PCA) to reduce the dimensionality of the TCGA gene expression data\n# \n\n# What does the gene expression data _look_ like when its dimensionality is reduced by PCA? Considering that disease alone appears to be on par with the expression data at predicting some mutations... how much of the reduced (via PCA) gene expression data is just capturing disease information?\n# \n# Most of this is probably already self-evident to someone with some biology experience but as a layman I found it helpful to see some of these graphs.\n\n# ## Outline:\n# 1. Imports, constants and load the data\n# 2. Run PCA\n# 3. Evaluate how much variance is explained by the PCA components\n# 4. Visualize the components relative to two covariates:\n# * Disease (which I think is also a good proxy for organ... I include a plot relative to organ)\n# * Gender\n# 5. Visualize the effect of gender on expression data apart from disease\n\n# ### 1. Imports, constants and load the data\n\n# In[1]:\n\n# Imports\nimport os\nimport operator\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import cm\n\n\n# In[2]:\n\n# Constants. The random seed to use throughout and the number of components to be returned by PCA (7,306 being the full set)\nRandomSeed = 0\nTotalComponents = 7306\n\n\n# In[3]:\n\n# Load the data (I'm using the pickled versions because they are significantly faster to load... ~20 sec as opposed to 7 minutes)\ntry: \n path = os.path.join('..', '..', 'download', 'expression-matrix.pkl')\n X = pd.read_pickle(path)\nexcept:\n path = os.path.join('..', '..', 'download', 'expression-matrix.tsv.bz2')\n X = pd.read_table(path, index_col=0)\n\ntry:\n path = os.path.join('..', '..', 'download', 'mutation-matrix.pkl')\n Y = pd.read_pickle(path)\nexcept:\n path = os.path.join('..', '..', 'download', 'mutation-matrix.tsv.bz2')\n Y = pd.read_table(path, index_col=0)\n \npath = os.path.join('..', '..', 'download', 'samples.tsv')\nsamples = pd.read_table(path, index_col=0)\n\n# Replace missing gender info with 'unknown'\nsamples.fillna('unknown', inplace=True)\n\n\n# ### 2. Run PCA\n\n# In[4]:\n\nX_scaled = StandardScaler().fit_transform(X)\npca = PCA(n_components = TotalComponents, random_state = RandomSeed)\npca.fit(X_scaled)\nX_pca = pca.transform(X_scaled)\n\n\n# ### 3. Evaluate how much variance is explained by the components\n\n# In[5]:\n\ndef PlotExplainedVariance(pcaInput, views):\n \"\"\" \n Plot the relationship between the number of \n components and the percent of variance explained\n \"\"\"\n # Plot the explained variance for each view\n for view in views:\n # Create the list to use as the X values\n n_component_list = []\n for value in range(views[view][0]+1,views[view][1]+1):\n n_component_list.append(value)\n # Create the plot\n plt.figure(figsize=(5, 5))\n plt.axes([.2, .2, .7, .7])\n plt.plot(n_component_list, pcaInput.explained_variance_ratio_.cumsum()[views[view][0]:views[view][1]]*100, linewidth=2)\n plt.axis('tight')\n plt.xlabel('Number of Components')\n plt.ylabel('Percent of Variance Explained')\n plt.title(view)\n plt.show()\n\n\n# In[6]:\n\nPlotExplainedVariance(pca, {'All Components':[0,TotalComponents]})\n\n\n# In[7]:\n\n# Set differnt views to plot (n_components)\nviews = {\n 'All Components': [0,TotalComponents], \n 'First 20': [0,19],\n 'First 50': [0,19],\n 'First 100': [0,99],\n 'Tail (100-->)': [99,TotalComponents]\n }\nPlotExplainedVariance(pca, views)\n\n\n# In[8]:\n\ndef ComponentsToExplainVariance():\n \"\"\"\n Create a dictionary of (threshold: number of components) for some points of reference\n \"\"\"\n varianceLimits = [0.25,0.4, 0.5, 0.6,0.7, 0.75, 0.8, 0.9, 0.95, 0.98, 0.99, 1]\n varianceLimitsDict = dict.fromkeys(varianceLimits)\n for i in range(TotalComponents):\n if pca.explained_variance_ratio_.cumsum()[i] > varianceLimits[0]:\n varianceLimitsDict[varianceLimits[0]] = i\n varianceLimits.pop(0)\n return varianceLimitsDict\ncompDict = ComponentsToExplainVariance()\n\n\n# In[9]:\n\nfor i in compDict:\n print(str(int(i*100)),\"% of variance is explained by \", str(compDict[i]), \" components.\")\n\n\n# ### 4. Visualize the components relative to disease and gender\n\n# In[10]:\n\ndef PlotAttributes(component1,component2, attribute='acronym',proportionShown='All', pointSize=20, X=X_pca, samples=samples, colors=None):\n \"\"\" \n Plot each sample as a point, colored by attribute, relative to two principal components (component1 and component2)\n \"\"\"\n title = attribute\n # Get the attributes\n y = samples[attribute]\n # Optional: Subset the data to make it easier to see what's going on (7,000 is a bit \n # too many points for this scatter plot)\n if proportionShown is not 'All':\n X_show, X_removed, y_show, y_removed = train_test_split(X, y, test_size=1-proportionShown, stratify=y, random_state=RandomSeed)\n else:\n X_show = X\n y_show = y\n # Get a list of the attributes\n attributes = np.unique(y_show)\n # Create the plot\n fig = plt.figure(figsize=(5, 5))\n labels = attributes\n if colors:\n colors=colors\n else:\n colors=iter(cm.nipy_spectral(np.linspace(0,1,len(attributes))))\n ax = fig.add_subplot(1, 1, 1)\n markers = ['o','s','D','>']\n for attribute, label, color in zip(attributes, labels, colors):\n ax.scatter(X_show[np.where(y_show == attribute), component1],\n X_show[np.where(y_show == attribute), component2],\n marker = markers[list(attributes).index(attribute)%len(markers)], label=attribute, color=color, linewidth='0.2', s=pointSize, alpha=0.9)\n ax.legend(loc='best')\n plt.xlabel(\"Principal Component %s \" %str(component1+1))\n plt.ylabel(\"Principal Component %s \" %str(component2+1))\n plt.title(\"{} (PC{} and PC{})\".format(title,component1+1,component2+1))\n if len(attributes) > 12:\n numberColumns = 2\n else:\n numberColumns = 1\n plt.legend(bbox_to_anchor=(1.05, 1), loc=2, ncol=numberColumns, borderaxespad=0.)\n plt.show()\n \ndef PlotAttributesMultiPlots(LastComponent, attribute='acronym',proportionShown = 'All',pointSize=20, X=X_pca, samples=samples, colors=None):\n \"\"\" \n Create multiple plots on two principal components.\n Takes a number (LastComponent) and plots each set of two components going\n up starting from 0,1 the 2,3... up until (LastComponent-2),(LastComponent-1)\n \"\"\"\n OddList = [x for x in range(LastComponent) if x % 2 == 0]\n for i in OddList:\n PlotAttributes(i,i+1, attribute,proportionShown,pointSize, X=X_pca, samples=samples, colors=colors)\n\n\n# In[11]:\n\nPlotAttributes(0,1,attribute='acronym')\n\n\n# In[12]:\n\nPlotAttributes(0,1,attribute='organ_of_origin')\n\n\n# ### First ten principal components relative to disease\n# ### (There looks to be a strong correlation)\n# \n# \n\n# In[13]:\n\nPlotAttributesMultiPlots(10,attribute='acronym',proportionShown=0.4)\n\n\n# ### First 10 components relative to gender\n\n# In[14]:\n\nPlotAttributesMultiPlots(10,attribute='gender',proportionShown=0.3)\n\n\n# ## 5. Visualize the relationship between gender and expression apart from disease\n# \n# Select a few diseases that are fairly gender neutral run pca on only samples in those diseases and plot gender against a few Principal Components for each\n# \n# (As shown by the plots below, there's still no easy to see correlation between expression principal components and gender even when disease is removed from the mix. I'm suprised that each disease seems to have a similar two clusters when the first two principal components are plotted)\n\n# In[15]:\n\n# Get a list of the gender neutral diseases (no more than 70% a particular gender)\ndiseaseDict = dict.fromkeys(np.unique(samples['acronym']))\n# Create a dictionary with disease: [ration male, number of samples]\nfor disease in diseaseDict:\n tempDF = samples.loc[samples['acronym'] == disease]\n males = tempDF['gender'].value_counts()[0]\n genderRatio = males / tempDF.shape[0]\n diseaseDict[disease] = [genderRatio, tempDF.shape[0]]\n# Remove the non gender neutral diseases\nneutralDiseaseDict = dict(diseaseDict)\nfor disease in diseaseDict:\n if 0.3 < diseaseDict[disease][0] < 0.7 :\n pass\n else:\n del neutralDiseaseDict[disease]\nneutralDiseaseList = list(neutralDiseaseDict.keys())\n# Print the list for reference\nprint(neutralDiseaseList)\n\n\n# @gwaygenomics recomended that breast cancer (BRCA) also be added to this list \"BRCA is a good control as there are some male BRCA samples in the dataset. (although there are stronger signals in the data that should be explained by top PCs).\" so BRCA is appended to the list below.\n\n# In[16]:\n\nneutralDiseaseList.append('BRCA')\nprint(neutralDiseaseList)\n\n\n# In[17]:\n\nexpressionDiseaseAndGender =pd.concat([X, samples['acronym'],samples['gender']], axis=1)\nfor disease in neutralDiseaseList:\n # Create dataframe\n tempDF = expressionDiseaseAndGender.loc[expressionDiseaseAndGender['acronym'] == disease].copy()\n X_temp = tempDF.drop(['acronym','gender'], 1)\n # Run PCA\n X_temp_scaled = StandardScaler().fit_transform(X_temp)\n temp_pca = PCA(n_components = 10, random_state = RandomSeed)\n temp_pca.fit(X_temp_scaled)\n X_temp_pca = temp_pca.transform(X_temp_scaled)\n \n # Plot PCs and Gender\n print(disease)\n PlotAttributesMultiPlots(4,attribute='gender', X=X_temp_pca, samples=tempDF, colors=['k','g','w'])\n\n" ]
[ [ "matplotlib.pyplot.legend", "pandas.concat", "matplotlib.pyplot.title", "numpy.unique", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.axes", "pandas.read_table", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.axis", "matplotlib.pyplot.xlabel", "sklearn.preprocessing.StandardScaler", "pandas.read_pickle", "numpy.where", "sklearn.decomposition.PCA", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
relh/keras-retinanet
[ "6ccf6bf3d03a1b5ea1d59fa8dac8dfcb3545a11b" ]
[ "keras_retinanet/utils/image.py" ]
[ "\"\"\"\nCopyright 2017-2018 Fizyr (https://fizyr.com)\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nfrom __future__ import division\nimport keras\nimport numpy as np\nimport cv2\nfrom PIL import Image\n\nfrom .transform import change_transform_origin\n\n\ndef read_image_bgr(path):\n \"\"\" Read an image in BGR format.\n\n Args\n path: Path to the image.\n \"\"\"\n image = np.asarray(Image.open(path).convert('RGB'))\n return image[:, :, ::-1].copy()\n\n\ndef preprocess_image(x, mode='caffe'):\n \"\"\" Preprocess an image by subtracting the ImageNet mean.\n\n Args\n x: np.array of shape (None, None, 3) or (3, None, None).\n mode: One of \"caffe\" or \"tf\".\n - caffe: will zero-center each color channel with\n respect to the ImageNet dataset, without scaling.\n - tf: will scale pixels between -1 and 1, sample-wise.\n\n Returns\n The input with the ImageNet mean subtracted.\n \"\"\"\n # mostly identical to \"https://github.com/keras-team/keras-applications/blob/master/keras_applications/imagenet_utils.py\"\n # except for converting RGB -> BGR since we assume BGR already\n x = x.astype(keras.backend.floatx())\n if mode == 'tf':\n x /= 127.5\n x -= 1.\n elif mode == 'caffe':\n if keras.backend.image_data_format() == 'channels_first':\n if x.ndim == 3:\n x[0, :, :] -= 103.939\n x[1, :, :] -= 116.779\n x[2, :, :] -= 123.68\n else:\n x[:, 0, :, :] -= 103.939\n x[:, 1, :, :] -= 116.779\n x[:, 2, :, :] -= 123.68\n else:\n x[..., 0] -= 103.939\n x[..., 1] -= 116.779\n x[..., 2] -= 123.68\n\n return x\n\n\ndef adjust_transform_for_image(transform, image, relative_translation):\n \"\"\" Adjust a transformation for a specific image.\n\n The translation of the matrix will be scaled with the size of the image.\n The linear part of the transformation will adjusted so that the origin of the transformation will be at the center of the image.\n \"\"\"\n height, width, channels = image.shape\n\n result = transform\n\n # Scale the translation with the image size if specified.\n if relative_translation:\n result[0:2, 2] *= [width, height]\n\n # Move the origin of transformation.\n result = change_transform_origin(transform, (0.5 * width, 0.5 * height))\n\n return result\n\n\nclass TransformParameters:\n \"\"\" Struct holding parameters determining how to apply a transformation to an image.\n\n Args\n fill_mode: One of: 'constant', 'nearest', 'reflect', 'wrap'\n interpolation: One of: 'nearest', 'linear', 'cubic', 'area', 'lanczos4'\n cval: Fill value to use with fill_mode='constant'\n data_format: Same as for keras.preprocessing.image.apply_transform\n relative_translation: If true (the default), interpret translation as a factor of the image size.\n If false, interpret it as absolute pixels.\n \"\"\"\n def __init__(\n self,\n fill_mode = 'nearest',\n interpolation = 'linear',\n cval = 0,\n data_format = None,\n relative_translation = True,\n ):\n self.fill_mode = fill_mode\n self.cval = cval\n self.interpolation = interpolation\n self.relative_translation = relative_translation\n\n if data_format is None:\n data_format = keras.backend.image_data_format()\n self.data_format = data_format\n\n if data_format == 'channels_first':\n self.channel_axis = 0\n elif data_format == 'channels_last':\n self.channel_axis = 2\n else:\n raise ValueError(\"invalid data_format, expected 'channels_first' or 'channels_last', got '{}'\".format(data_format))\n\n def cvBorderMode(self):\n if self.fill_mode == 'constant':\n return cv2.BORDER_CONSTANT\n if self.fill_mode == 'nearest':\n return cv2.BORDER_REPLICATE\n if self.fill_mode == 'reflect':\n return cv2.BORDER_REFLECT_101\n if self.fill_mode == 'wrap':\n return cv2.BORDER_WRAP\n\n def cvInterpolation(self):\n if self.interpolation == 'nearest':\n return cv2.INTER_NEAREST\n if self.interpolation == 'linear':\n return cv2.INTER_LINEAR\n if self.interpolation == 'cubic':\n return cv2.INTER_CUBIC\n if self.interpolation == 'area':\n return cv2.INTER_AREA\n if self.interpolation == 'lanczos4':\n return cv2.INTER_LANCZOS4\n\n\ndef apply_transform(matrix, image, params):\n \"\"\"\n Apply a transformation to an image.\n\n The origin of transformation is at the top left corner of the image.\n\n The matrix is interpreted such that a point (x, y) on the original image is moved to transform * (x, y) in the generated image.\n Mathematically speaking, that means that the matrix is a transformation from the transformed image space to the original image space.\n\n Args\n matrix: A homogeneous 3 by 3 matrix holding representing the transformation to apply.\n image: The image to transform.\n params: The transform parameters (see TransformParameters)\n \"\"\"\n if params.channel_axis != 2:\n image = np.moveaxis(image, params.channel_axis, 2)\n\n output = cv2.warpAffine(\n image,\n matrix[:2, :],\n dsize = (image.shape[1], image.shape[0]),\n flags = params.cvInterpolation(),\n borderMode = params.cvBorderMode(),\n borderValue = params.cval,\n )\n\n if params.channel_axis != 2:\n output = np.moveaxis(output, 2, params.channel_axis)\n return output\n\n\ndef resize_image(img, min_side=800, max_side=1333):\n \"\"\" Resize an image such that the size is constrained to min_side and max_side.\n\n Args\n min_side: The image's min side will be equal to min_side after resizing.\n max_side: If after resizing the image's max side is above max_side, resize until the max side is equal to max_side.\n\n Returns\n A resized image.\n \"\"\"\n (rows, cols, _) = img.shape\n\n smallest_side = min(rows, cols)\n\n # rescale the image so the smallest side is min_side\n scale = min_side / smallest_side\n\n # check if the largest side is now greater than max_side, which can happen\n # when images have a large aspect ratio\n largest_side = max(rows, cols)\n if largest_side * scale > max_side:\n scale = max_side / largest_side\n\n # resize the image with the computed scale\n img = cv2.resize(img, None, fx=scale, fy=scale)\n\n return img, scale\n" ]
[ [ "numpy.moveaxis" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
d-li14/HBONet
[ "e9a76c15e3847b0f032a7000fe0c8138d6f2eb10" ]
[ "models/imagenet/hbonet.py" ]
[ "\nimport torch\nimport torch.nn as nn\nimport math\n\n__all__ = ['hbonet']\n\n\ndef _make_divisible(v, divisor, min_value=None):\n \"\"\"\n This function is taken from the original tf repo.\n It ensures that all layers have a channel number that is divisible by 8\n It can be seen here:\n https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py\n :param v:\n :param divisor:\n :param min_value:\n :return:\n \"\"\"\n if min_value is None:\n min_value = divisor\n new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)\n # Make sure that round down does not go down by more than 10%.\n if new_v < 0.9 * v:\n new_v += divisor\n return new_v\n\n\ndef conv_3x3_bn(inp, oup, stride):\n return nn.Sequential(\n nn.Conv2d(inp, oup, 3, stride, 1, bias=False),\n nn.BatchNorm2d(oup),\n nn.ReLU6(inplace=True)\n )\n\n\ndef conv_1x1_bn(inp, oup, activation=True):\n return nn.Sequential(\n nn.Conv2d(inp, oup, 1, 1, 0, bias=False),\n nn.BatchNorm2d(oup),\n nn.ReLU6(inplace=True) if activation else nn.Sequential()\n )\n\n\nclass InvertedResidual(nn.Module):\n def __init__(self, inp, oup, stride, expand_ratio):\n super(InvertedResidual, self).__init__()\n assert stride in [1, 2]\n\n hidden_dim = round(inp * expand_ratio)\n self.identity = stride == 1 and inp == oup\n\n if expand_ratio == 1:\n self.conv = nn.Sequential(\n # dw\n nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),\n nn.BatchNorm2d(hidden_dim),\n nn.ReLU6(inplace=True),\n # pw-linear\n nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),\n nn.BatchNorm2d(oup),\n )\n else:\n self.conv = nn.Sequential(\n # pw\n nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False),\n nn.BatchNorm2d(hidden_dim),\n nn.ReLU6(inplace=True),\n # dw\n nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),\n nn.BatchNorm2d(hidden_dim),\n nn.ReLU6(inplace=True),\n # pw-linear\n nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),\n nn.BatchNorm2d(oup),\n )\n\n def forward(self, x):\n if self.identity:\n return x + self.conv(x)\n else:\n return self.conv(x)\n\n\nclass HarmoniousBottleneck_4x(nn.Module):\n def __init__(self, inp, oup, stride, expand_ratio):\n super(HarmoniousBottleneck_4x, self).__init__()\n assert stride in [1, 2]\n self.stride = stride\n self.oup = oup\n\n self.conv = nn.Sequential(\n # dw-linear\n nn.Conv2d(inp, inp, 5, 2, 2, groups=inp, bias=False),\n nn.BatchNorm2d(inp),\n # pw\n nn.Conv2d(inp, inp * expand_ratio, 1, 1, 0, bias=False),\n nn.BatchNorm2d(inp * expand_ratio),\n nn.ReLU6(inplace=True),\n # dw-linear\n nn.Conv2d(inp * expand_ratio, inp * expand_ratio, 5, 2, 2, groups=inp * expand_ratio, bias=False),\n nn.BatchNorm2d(inp * expand_ratio),\n # pw\n nn.Conv2d(inp * expand_ratio, inp * expand_ratio, 1, 1, 0, bias=False),\n nn.BatchNorm2d(inp * expand_ratio),\n nn.ReLU6(inplace=True),\n # dw\n nn.Conv2d(inp * expand_ratio, inp * expand_ratio, 3, 1, 1, groups=inp * expand_ratio, bias=False),\n nn.BatchNorm2d(inp * expand_ratio),\n #nn.ReLU6(inplace=True),\n # pw-linear\n nn.Conv2d(inp * expand_ratio, oup // 2, 1, 1, 0, bias=False),\n nn.BatchNorm2d(oup // 2),\n )\n\n if self.stride == 1:\n self.upsample = nn.Upsample(scale_factor=4)\n elif self.stride == 2:\n self.upsample = nn.Upsample(scale_factor=2)\n self.avgpool = nn.AvgPool2d(kernel_size=2)\n\n # dw-linear\n self.upconv = nn.Sequential(\n nn.Conv2d(oup // 2, oup // 2, 5, 1, 2, groups=oup // 2, bias=False),\n nn.BatchNorm2d(oup // 2),\n )\n\n def forward(self, x):\n if self.stride == 1:\n return torch.cat((x[:, -(self.oup - self.oup // 2):, :, :], \\\n self.upconv(x[:, :(self.oup // 2), :, :] + self.upsample(self.conv(x)))), dim=1)\n elif self.stride == 2:\n return torch.cat((self.avgpool(x[:, -(self.oup - self.oup // 2):, :, :]), \\\n self.upconv(self.avgpool(x[:, :(self.oup // 2), :, :]) + self.upsample(self.conv(x)))), dim=1)\n\n\nclass HarmoniousBottleneck_8x(nn.Module):\n def __init__(self, inp, oup, stride, expand_ratio):\n super(HarmoniousBottleneck_8x, self).__init__()\n assert stride in [1, 2]\n self.stride = stride\n self.oup = oup\n\n self.conv = nn.Sequential(\n # dw-linear\n nn.Conv2d(inp, inp, 5, 2, 2, groups=inp, bias=False),\n nn.BatchNorm2d(inp),\n # pw\n nn.Conv2d(inp, inp * expand_ratio, 1, 1, 0, bias=False),\n nn.BatchNorm2d(inp * expand_ratio),\n nn.ReLU6(inplace=True),\n # dw-linear\n nn.Conv2d(inp * expand_ratio, inp * expand_ratio, 5, 2, 2, groups=inp * expand_ratio, bias=False),\n nn.BatchNorm2d(inp * expand_ratio),\n # pw\n nn.Conv2d(inp * expand_ratio, inp * expand_ratio, 1, 1, 0, bias=False),\n nn.BatchNorm2d(inp * expand_ratio),\n nn.ReLU6(inplace=True),\n # dw-linear\n nn.Conv2d(inp * expand_ratio, inp * expand_ratio, 5, 2, 2, groups=inp * expand_ratio, bias=False),\n nn.BatchNorm2d(inp * expand_ratio),\n # pw\n nn.Conv2d(inp * expand_ratio, inp * expand_ratio, 1, 1, 0, bias=False),\n nn.BatchNorm2d(inp * expand_ratio),\n nn.ReLU6(inplace=True),\n # dw\n nn.Conv2d(inp * expand_ratio, inp * expand_ratio, 3, 1, 1, groups=inp * expand_ratio, bias=False),\n nn.BatchNorm2d(inp * expand_ratio),\n #nn.ReLU6(inplace=True),\n # pw-linear\n nn.Conv2d(inp * expand_ratio, oup // 2, 1, 1, 0, bias=False),\n nn.BatchNorm2d(oup // 2),\n )\n\n if self.stride == 1:\n self.upsample = nn.Upsample(scale_factor=8)\n elif self.stride == 2:\n self.upsample = nn.Upsample(scale_factor=4)\n self.avgpool = nn.AvgPool2d(kernel_size=2)\n\n # dw-linear\n self.upconv = nn.Sequential(\n nn.Conv2d(oup // 2, oup // 2, 5, 1, 2, groups=oup // 2, bias=False),\n nn.BatchNorm2d(oup // 2),\n )\n\n def forward(self, x):\n if self.stride == 1:\n return torch.cat((x[:, -(self.oup - self.oup // 2):, :, :], \\\n self.upconv(x[:, :(self.oup // 2), :, :] + self.upsample(self.conv(x)))), dim=1)\n elif self.stride == 2:\n return torch.cat((self.avgpool(x[:, -(self.oup - self.oup // 2):, :, :]), \\\n self.upconv(self.avgpool(x[:, :(self.oup // 2), :, :]) + self.upsample(self.conv(x)))), dim=1)\n\n\nclass HarmoniousBottleneck_2x(nn.Module):\n def __init__(self, inp, oup, stride, expand_ratio):\n super(HarmoniousBottleneck_2x, self).__init__()\n assert stride in [1, 2]\n self.stride = stride\n self.oup = oup\n\n self.conv = nn.Sequential(\n # dw-linear\n nn.Conv2d(inp, inp, 5, 2, 2, groups=inp, bias=False),\n nn.BatchNorm2d(inp),\n # pw\n nn.Conv2d(inp, inp * expand_ratio, 1, 1, 0, bias=False),\n nn.BatchNorm2d(inp * expand_ratio),\n nn.ReLU6(inplace=True),\n # dw\n nn.Conv2d(inp * expand_ratio, inp * expand_ratio, 3, 1, 1, groups=inp * expand_ratio, bias=False),\n nn.BatchNorm2d(inp * expand_ratio),\n nn.ReLU6(inplace=True),\n # pw-linear\n nn.Conv2d(inp * expand_ratio, oup // 2, 1, 1, 0, bias=False),\n nn.BatchNorm2d(oup // 2),\n )\n\n if self.stride == 1:\n self.upsample = nn.Upsample(scale_factor=2)\n\n # dw-linear\n self.upconv = nn.Sequential(\n nn.Conv2d(oup // 2, oup // 2, 5, 1, 2, groups=oup // 2, bias=False),\n nn.BatchNorm2d(oup // 2),\n )\n elif self.stride == 2:\n self.avgpool = nn.AvgPool2d(kernel_size=2)\n\n def forward(self, x):\n if self.stride == 1:\n return torch.cat((x[:, -(self.oup - self.oup // 2):, :, :], \\\n self.upconv(x[:, :(self.oup // 2), :, :] + self.upsample(self.conv(x)))), dim=1)\n elif self.stride == 2:\n return torch.cat((self.avgpool(x[:, -(self.oup - self.oup // 2):, :, :]), self.conv(x)), dim=1)\n\n\nclass HBONet(nn.Module):\n def __init__(self, num_classes=1000, width_mult=1.):\n super(HBONet, self).__init__()\n # setting of inverted residual blocks\n self.cfgs = [\n # t, c, n, s, block\n [1, 20, 1, 1, InvertedResidual],\n\n # alternative blocks for 8x varaint model\n # [2, 36, 1, 1, HarmoniousBottleneck_8x],\n # [2, 72, 3, 2, HarmoniousBottleneck_8x],\n # [2, 96, 4, 2, HarmoniousBottleneck_4x],\n\n # alternative blocks for 4x varaint model\n # [2, 36, 1, 1, HarmoniousBottleneck_4x],\n # [2, 72, 3, 2, HarmoniousBottleneck_4x],\n # [2, 96, 4, 2, HarmoniousBottleneck_4x],\n\n # alternative blocks for 2x main model\n [2, 36, 1, 1, HarmoniousBottleneck_2x],\n [2, 72, 3, 2, HarmoniousBottleneck_2x],\n [2, 96, 4, 2, HarmoniousBottleneck_2x],\n\n # fixed blocks\n [2, 192, 4, 2, HarmoniousBottleneck_2x],\n [2, 288, 1, 1, HarmoniousBottleneck_2x],\n [0, 144, 1, 1, conv_1x1_bn],\n [6, 200, 2, 2, InvertedResidual],\n [6, 400, 1, 1, InvertedResidual],\n ]\n\n if width_mult == 0.1:\n divisible_value = 4\n # comment the following two lines to revert to 8 for variant models\n elif width_mult == 0.25:\n divisible_value = 2\n # comment the following two lines to revert to 8 for variant models\n elif width_mult == 0.5:\n divisible_value = 2\n else:\n divisible_value = 8\n # building first layer\n input_channel = _make_divisible(32 * width_mult, divisible_value)\n layers = [conv_3x3_bn(3, input_channel, 2)]\n # building inverted residual blocks\n for t, c, n, s, block in self.cfgs:\n output_channel = _make_divisible(c * width_mult, divisible_value)\n if block is not conv_1x1_bn:\n for i in range(n):\n layers.append(block(input_channel, output_channel, s if i == 0 else 1, t))\n input_channel = output_channel\n else:\n layers.append(conv_1x1_bn(input_channel, output_channel, activation=False))\n input_channel = output_channel\n self.features = nn.Sequential(*layers)\n # building last several layers\n output_channel = _make_divisible(1600 * width_mult, divisible_value) if width_mult > 1.0 else 1600\n self.conv = conv_1x1_bn(input_channel, output_channel)\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\n self.classifier = nn.Linear(output_channel, num_classes)\n\n self._initialize_weights()\n\n def forward(self, x):\n x = self.features(x)\n x = self.conv(x)\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n x = self.classifier(x)\n return x\n\n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()\n\ndef hbonet(**kwargs):\n \"\"\"\n Constructs a HBONet model\n \"\"\"\n return HBONet(**kwargs)\n\n" ]
[ [ "torch.nn.Sequential", "torch.nn.ReLU6", "torch.nn.Conv2d", "torch.nn.Linear", "torch.nn.AvgPool2d", "torch.nn.AdaptiveAvgPool2d", "torch.nn.Upsample", "torch.nn.BatchNorm2d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
adamszequi/Constructing-an-N-Stock-Portfolio
[ "497a16dbb30ed9ebe1a04c6d7dc944d9f73197be" ]
[ "Constructing an N-stock portfolio.py" ]
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jan 21 11:31:50 2020\r\n\r\n@author: Dell\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport yfinance as yf\r\nimport os\r\nimport scipy as sp\r\n\r\n#function for downloading indicators\r\ndef downloadTickerData(tickers,startDate,endDate):\r\n data=yf.download((tickers),start=startDate,end=endDate)\r\n return data['Adj Close']\r\n\r\n#download collective data from website\r\ndata=pd.read_pickle(r'C:\\Users\\Dell\\Desktop\\data\\yanMonthly (2).pkl')\r\nIBMdata=data[data.index=='IBM']\r\n\r\n#create a function for return of the data\r\ndef returndata(ticker):\r\n tickerData=data[data.index==ticker]\r\n prices=tickerData.VALUE.values\r\n returns=prices[1:]/prices[:-1]-1\r\n date=tickerData.DATE.values\r\n output=pd.DataFrame(index=date[1:])\r\n output[f'{ticker}returns']=returns\r\n return output\r\n\r\ndataIndices=sp.unique(data.index)\r\ndataIndicesCrop=dataIndices[dataIndices<'ZZZZ']\r\ndataIndicesCropped=list(dataIndicesCrop)\r\n\r\nnStocks=10\r\n\r\nsp.random.seed(1234567)\r\n\r\nnonStocks=['GOLDPRICE','HML','SMB','Mkt_Rf','Rf','Russ3000E_D','US_\\\r\nDEBT','Russ3000E_X','US_GDP2009dollar','US_GDP2013dollar']\r\n\r\nfor _ in range(len(nonStocks)):\r\n dataIndicesCropped.remove(nonStocks[_])\r\n\r\nrandomValues=sp.random.uniform(low=1,high=len(dataIndicesCropped),size=nStocks)\r\nrandomValuesIndex,dataIndicesCroppedIndex=[],[]\r\n\r\nfor i in range(nStocks):\r\n intValue=int(randomValues[i])\r\n randomValuesIndex.append(intValue)\r\n dataIndicesCroppedIndex.append(dataIndicesCropped[intValue])\r\n\r\nfinalDataSet=returndata(dataIndicesCroppedIndex[0])\r\n\r\nfor _ in sp.arange(1,nStocks):\r\n returns=returndata(dataIndicesCroppedIndex[_])\r\n finalDataSet=pd.merge(finalDataSet,returns,left_index=True, right_index=True)\r\n\r\n#portfolio dataset\r\nprint(finalDataSet)\r\n" ]
[ [ "pandas.merge", "scipy.random.seed", "scipy.unique", "pandas.DataFrame", "scipy.arange", "pandas.read_pickle" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
DanielMagro97/Single-Word-Speech-Recogniser
[ "dd9bb40b8a745202ae2c1f38af6fa29f99e7354c" ]
[ "VI_Testing.py" ]
[ "import scipy.io.wavfile # for reading wav file\r\nfrom Assignment.IV_ExtractMFCCs import mfcc_extract # for MFCC extraction\r\nfrom sklearn.externals import joblib # for loading the GMMs\r\nimport os # for file functions\r\n\r\n\r\n# Loading the GMMs from disk\r\ngmm_bass = joblib.load('training//bass//gmm_bass.pkl')\r\ngmm_drum = joblib.load('training//drum//gmm_drum.pkl')\r\ngmm_guitar = joblib.load('training//guitar//gmm_guitar.pkl')\r\ngmm_piano = joblib.load('training//piano//gmm_piano.pkl')\r\ngmm_violin = joblib.load('training//violin//gmm_violin.pkl')\r\n\r\n\r\ndef score_gmm(data, gmm):\r\n log_likelihood = gmm.score(X=data)\r\n return log_likelihood\r\n\r\n\r\n# Looping over Test data\r\nfor file in os.listdir('testing'):\r\n filename = os.fsdecode(file)\r\n # if the file extension is .wav (i.e. if it is a sound file)\r\n if filename.endswith(\".wav\"):\r\n # read the sound file\r\n fs, data = scipy.io.wavfile.read('testing//' + filename)\r\n # extract the MFCCs for that sound file\r\n mfccs = mfcc_extract(signal=data, fs=fs)\r\n # score the MFCCs under each GMM\r\n scores = [gmm_bass.score(mfccs), gmm_drum.score(mfccs), gmm_guitar.score(mfccs), gmm_piano.score(mfccs), gmm_violin.score(mfccs)]\r\n\r\n # printing what word the sound file is saying is based on the highest score\r\n if scores.index(max(scores)) == 0:\r\n print(filename + ' is saying bass')\r\n elif scores.index(max(scores)) == 1:\r\n print(filename + ' is saying drum')\r\n elif scores.index(max(scores)) == 2:\r\n print(filename + ' is saying guitar')\r\n elif scores.index(max(scores)) == 3:\r\n print(filename + ' is saying piano')\r\n elif scores.index(max(scores)) == 4:\r\n print(filename + ' is saying violin')\r\n\r\n continue\r\n else:\r\n continue" ]
[ [ "sklearn.externals.joblib.load" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ThomIves/LeastSquaresPolyFitPurePy
[ "6ad8b070b01e5ec8cee810f4c9d208b8e25f5dac" ]
[ "LeastSquaresPolyPractice_2a.py" ]
[ "import LinearAlgebraPurePython as la \nimport MachineLearningPurePy as ml\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import PolynomialFeatures\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\nimport random\nimport sys\n\n\n# Section 1: Fake data preparation \n# and visualization\nX = [1.5,2.0,2.5,3.0,3.5,4.0]\ndef y_of_x(x):\n return 0.2*x + 0.7*x**2 + random.uniform(-1,1)\nY = []\nfor x in X:\n Y.append(y_of_x(x))\n\nplt.scatter(X, Y)\n\n# Section 2: Get fake data in correct format\nX = la.transpose([X])\nY = la.transpose([Y])\n\n# Section 3: Pure Python Tools Fit\npoly_pp = ml.Poly_Features_Pure_Py(order = 2)\nXp = poly_pp.fit_transform(X)\nprint('PP Feature Names:', poly_pp.get_feature_names())\nls_pp = ml.Least_Squares(tol=2, add_ones_column=False)\nls_pp.fit(Xp, Y)\nprint()\n\n# Section 4: SciKit Learn Fit\npoly_sk = PolynomialFeatures(degree = 2)\nX_poly = poly_sk.fit_transform(X)\nprint('SK Feature Names:', poly_sk.get_feature_names())\nls_sk = LinearRegression()\nls_sk.fit(X_poly, Y)\nprint()\n\n# Section 5: Coefficients Comparison\ntmp_ls_pp_coefs = sorted(ls_pp.coefs)\nrounded_ls_pp_coefs = [round(x,8)+0 for x in la.transpose(tmp_ls_pp_coefs)[0]]\nprint('PurePy LS coefficients:', rounded_ls_pp_coefs)\n\ntmp_ls_sk_coefs = ls_sk.intercept_.tolist() + ls_sk.coef_[0][1:].tolist()\ntmp_ls_sk_coefs = sorted(tmp_ls_sk_coefs)\nrounded_ls_sk_coefs = [round(x,8)+0 for x in tmp_ls_sk_coefs]\nprint('SKLearn LS coefficients:', rounded_ls_sk_coefs, '\\n')\n\nprint('Coef Deltas:', [rounded_ls_pp_coefs[i] - rounded_ls_sk_coefs[i] \n for i in range(len(rounded_ls_pp_coefs))])\n\n# Section 6: Create Fake Test Data\nXLS = [0,1,2,3,4,5]\n\n# Section 6.1: Predict with Fake Test Data\n# Using Pure Python Tools\nXLSpp = poly_pp.transform(la.transpose([XLS]))\nYLSpp = ls_pp.predict(XLSpp)\nYLSpp = la.transpose(YLSpp)[0]\n\n# Section 6.2: Predict with Fake Test Data\n# Using SciKit Learn Tools\nXLSsk = poly_sk.transform(la.transpose([XLS]))\nYLSsk = ls_sk.predict(XLSsk)\nYLSsk = YLSsk.tolist()\nYLSsk = la.transpose(YLSsk)[0]\n\n# Section 7: Calculate Prediction Differences \nYLSpp.sort()\nYLSsk.sort()\ndeltas = [ YLSpp[i] - YLSsk[i] for i in range(len(YLSpp)) ]\nprint( '\\nPrediction Deltas:', deltas , '\\n')\n\n# Section 8: Plot Both Methods\nplt.plot(XLS, YLSpp, XLS, YLSsk)\nplt.xlabel('X Values')\nplt.ylabel('Y Values')\nplt.title('Pure Python Least Squares Line Fit')\nplt.show()\n" ]
[ [ "matplotlib.pyplot.scatter", "matplotlib.pyplot.title", "sklearn.preprocessing.PolynomialFeatures", "matplotlib.pyplot.plot", "sklearn.linear_model.LinearRegression", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
liqing-ustc/ANS
[ "0c7fb789333adf0e9ba5cf4dd7cbb6b8f350846d" ]
[ "baselines/train.py" ]
[ "from baseline_utils import *\nimport time\nfrom tqdm import tqdm\nfrom collections import Counter\n\nfrom sklearn.metrics import classification_report, confusion_matrix\nimport pandas as pd\npd.set_option('display.max_rows', 500)\npd.set_option('display.max_columns', 500)\npd.set_option('display.width', 1000)\n\nfrom dataset import HINT, HINT_collate\nfrom model import make_model\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport random\ntorch.multiprocessing.set_sharing_strategy('file_system')\n\nimport argparse\nimport sys\nfrom torch.optim import Adam\nfrom optimization import AdamW, WarmupLinearSchedule, ConstantLRSchedule\nfrom baseline_utils import SYMBOLS, INP_VOCAB, RES_VOCAB, DEVICE, NULL, END, RES_MAX_LEN\n\ndef parse_args():\n parser = argparse.ArgumentParser('Give Me A HINT')\n parser.add_argument('--resume', type=str, default=None, help='Resumes training from checkpoint.')\n parser.add_argument('--perception-pretrain', type=str, help='initialize the perception from pretrained models.',\n default='data/perception-pretrain/model.pth.tar_78.2_match')\n parser.add_argument('--output-dir', type=str, default='outputs/', help='output directory for storing checkpoints')\n parser.add_argument('--seed', type=int, default=0, help=\"Random seed.\")\n\n parser.add_argument('--seq2seq', type=str, default='RNN', help='the type of seq2seq: RNN for GRU, TRAN for Transformer')\n parser.add_argument('--nhead', type=int, default=1, help=\"number of attention heads in the Transformer model\")\n parser.add_argument('--enc_layers', type=int, default=1, help=\"number of layers in encoder\")\n parser.add_argument('--dec_layers', type=int, default=1, help=\"number of layers in decoder\")\n parser.add_argument('--emb_dim', type=int, default=128, help=\"embedding dim\")\n parser.add_argument('--hid_dim', type=int, default=128, help=\"hidden dim\")\n parser.add_argument('--dropout', type=float, default=0.5, help=\"dropout ratio\")\n\n parser.add_argument('--perception', action=\"store_true\", help='whether to provide perfect perception, i.e., no need to learn')\n parser.add_argument('--syntax', action=\"store_true\", help='whether to provide perfect syntax, i.e., no need to learn')\n parser.add_argument('--semantics', action=\"store_true\", help='whether to provide perfect semantics, i.e., no need to learn')\n parser.add_argument('--curriculum', action=\"store_true\", help='whether to use the pre-defined curriculum')\n\n parser.add_argument('--epochs', type=int, default=100, help='number of epochs for training')\n parser.add_argument('--epochs_eval', type=int, default=10, help='how many epochs per evaluation')\n args = parser.parse_args()\n return args\n\nfrom nltk.tree import Tree\ndef draw_parse(sentence, head):\n def build_tree(pos):\n children = [i for i, h in enumerate(head) if h == pos]\n return Tree(sentence[pos], [build_tree(x) for x in children])\n \n root = head.index(-1)\n tree = build_tree(root)\n return tree\n\ndef evaluate(model, dataloader):\n model.eval() \n res_all = []\n res_pred_all = []\n\n expr_all = []\n expr_pred_all = []\n\n dep_all = []\n dep_pred_all = []\n\n with torch.no_grad():\n for sample in tqdm(dataloader):\n img = sample['img_seq']\n src = torch.tensor([x for s in sample['sentence'] for x in s])\n res = sample['res']\n trg = torch.tensor(res2seq(res.numpy()))\n expr = sample['expr']\n dep = sample['head']\n src_len = sample['len']\n tgt_len = [len(str(x)) for x in res.numpy()]\n\n img = img.to(DEVICE)\n src = src.to(DEVICE)\n trg = trg.to(DEVICE)\n\n output = model(img, src, trg, src_len, tgt_len)\n pred = torch.argmax(output, -1).detach().cpu().numpy()\n res_pred = [seq2res(x) for x in pred]\n res_pred_all.append(res_pred)\n res_all.append(res)\n\n # expr_pred_all.extend(expr_preds)\n expr_all.extend(expr)\n # dep_pred_all.extend(dep_preds)\n dep_all.extend(dep)\n\n res_pred_all = np.concatenate(res_pred_all, axis=0)\n res_all = np.concatenate(res_all, axis=0)\n result_acc = (res_pred_all == res_all).mean()\n\n print(\"result accuracy by length:\")\n for k in sorted(dataloader.dataset.len2ids.keys()):\n ids = dataloader.dataset.len2ids[k]\n res = res_all[ids]\n res_pred = res_pred_all[ids]\n res_acc = (res == res_pred).mean()\n print(k, \"(%2d%%)\"%(100*len(ids)//len(dataloader.dataset)), \"%5.2f\"%(100 * res_acc))\n \n print(\"result accuracy by symbol:\")\n for k in sorted(dataloader.dataset.sym2ids.keys()):\n ids = dataloader.dataset.sym2ids[k]\n res = res_all[ids]\n res_pred = res_pred_all[ids]\n res_acc = (res == res_pred).mean()\n print(k, \"(%2d%%)\"%(100*len(ids)//len(dataloader.dataset)), \"%5.2f\"%(100 * res_acc))\n\n print(\"result accuracy by digit:\")\n for k in sorted(dataloader.dataset.digit2ids.keys()):\n ids = dataloader.dataset.digit2ids[k]\n res = res_all[ids]\n res_pred = res_pred_all[ids]\n res_acc = (res == res_pred).mean()\n print(k, \"(%2d%%)\"%(100*len(ids)//len(dataloader.dataset)), \"%5.2f\"%(100 * res_acc))\n\n print(\"result accuracy by result:\")\n for k in sorted(dataloader.dataset.res2ids.keys())[:10]:\n ids = dataloader.dataset.res2ids[k]\n res = res_all[ids]\n res_pred = res_pred_all[ids]\n res_acc = (res == res_pred).mean()\n print(k, \"(%2d%%)\"%(100*len(ids)//len(dataloader.dataset)), \"%5.2f\"%(100 * res_acc))\n\n print(\"result accuracy by generalization:\")\n for k in sorted(dataloader.dataset.cond2ids.keys()):\n ids = dataloader.dataset.cond2ids[k]\n res = res_all[ids]\n res_pred = res_pred_all[ids]\n if len(ids) == 0:\n res_acc = 0.\n else:\n res_acc = (res == res_pred).mean()\n print(k, \"(%.2f%%)\"%(100*len(ids)/len(dataloader.dataset)), \"%5.2f\"%(100 * res_acc))\n \n print(\"error cases:\")\n errors = np.arange(len(res_all))[res_all != res_pred_all]\n for i in errors[:10]:\n print(expr_all[i], dep_all[i], res_all[i], res_pred_all[i])\n\n return 0., 0., result_acc\n\ndef train(model, args, st_epoch=0):\n best_acc = 0.0\n batch_size = 64\n train_dataloader = torch.utils.data.DataLoader(args.train_set, batch_size=batch_size,\n shuffle=True, num_workers=4, collate_fn=HINT_collate)\n eval_dataloader = torch.utils.data.DataLoader(args.val_set, batch_size=32,\n shuffle=False, num_workers=4, collate_fn=HINT_collate)\n\n # optimizer = AdamW(model.parameters(), lr=1e-3, weight_decay=0.02)\n # lr_scheduler = WarmupLinearSchedule(optimizer, warmup_steps=10 * len(train_dataloader), t_total=args.epochs*len(train_dataloader),\n # last_epoch=st_epoch*len(train_dataloader)-1)\n optimizer = Adam(model.parameters(), lr=1e-3)\n lr_scheduler = ConstantLRSchedule(optimizer)\n criterion = nn.CrossEntropyLoss(ignore_index=RES_VOCAB.index(NULL))\n \n max_len = float(\"inf\")\n if args.curriculum:\n curriculum_strategy = dict([\n # (0, 7)\n (0, 1),\n (1, 3),\n (20, 7),\n (40, 11),\n (60, 15),\n (80, float('inf')),\n ])\n print(\"Curriculum:\", sorted(curriculum_strategy.items()))\n for e, l in sorted(curriculum_strategy.items(), reverse=True):\n if st_epoch >= e:\n max_len = l\n break\n train_set.filter_by_len(max_len=max_len)\n train_dataloader = torch.utils.data.DataLoader(train_set, batch_size=batch_size,\n shuffle=True, num_workers=4, collate_fn=HINT_collate)\n \n ###########evaluate init model###########\n # perception_acc, head_acc, result_acc = evaluate(model, eval_dataloader)\n # print('{} (Perception Acc={:.2f}, Head Acc={:.2f}, Result Acc={:.2f})'.format('val', 100*perception_acc, 100*head_acc, 100*result_acc))\n #########################################\n\n for epoch in range(st_epoch, args.epochs):\n if args.curriculum and epoch in curriculum_strategy:\n max_len = curriculum_strategy[epoch]\n train_set.filter_by_len(max_len=max_len)\n train_dataloader = torch.utils.data.DataLoader(train_set, batch_size=batch_size,\n shuffle=True, num_workers=4, collate_fn=HINT_collate)\n\n since = time.time()\n print('-' * 30)\n print('Epoch {}/{} (max_len={}, data={}, lr={})'.format(epoch, args.epochs - 1, max_len, len(train_set), lr_scheduler.get_lr()[0]))\n\n model.train()\n train_acc = []\n train_loss = []\n for sample in tqdm(train_dataloader):\n img = sample['img_seq']\n src = torch.tensor([x for s in sample['sentence'] for x in s])\n res = sample['res']\n trg = torch.tensor(res2seq(res.numpy()))\n src_len = sample['len']\n tgt_len = [len(str(x)) for x in res.numpy()]\n\n img = img.to(DEVICE)\n src = src.to(DEVICE)\n trg = trg.to(DEVICE)\n output = model(img, src, trg[:, :-1], src_len, tgt_len)\n loss = criterion(output.contiguous().view(-1, output.shape[-1]), trg[:, 1:].contiguous().view(-1))\n\n optimizer.zero_grad()\n loss.backward()\n nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n optimizer.step()\n lr_scheduler.step()\n train_loss.append(loss.cpu().item())\n\n pred = torch.argmax(output, -1).detach().cpu().numpy()\n res_pred = [seq2res(x) for x in pred]\n acc = np.mean(np.array(res_pred) == res.numpy())\n train_acc.append(acc)\n train_acc = np.mean(train_acc)\n train_loss = np.mean(train_loss)\n print(\"Train acc: %.2f, loss: %.3f \"%(train_acc * 100, train_loss))\n \n if ((epoch+1) % args.epochs_eval == 0) or (epoch+1 == args.epochs):\n perception_acc, head_acc, result_acc = evaluate(model, eval_dataloader)\n print('{} (Perception Acc={:.2f}, Head Acc={:.2f}, Result Acc={:.2f})'.format('val', 100*perception_acc, 100*head_acc, 100*result_acc))\n if result_acc > best_acc:\n best_acc = result_acc\n\n # model_path = args.output_dir + \"model_%03d.p\"%(epoch + 1)\n # model.save(model_path, epoch=epoch+1)\n \n time_elapsed = time.time() - since\n print('Epoch time: {:.0f}m {:.0f}s'.format(\n time_elapsed // 60, time_elapsed % 60))\n\n # Test\n print('-' * 30)\n print('Evaluate on test set...')\n eval_dataloader = torch.utils.data.DataLoader(args.test_set, batch_size=64,\n shuffle=False, num_workers=4, collate_fn=HINT_collate)\n perception_acc, head_acc, result_acc = evaluate(model, eval_dataloader)\n print('{} (Perception Acc={:.2f}, Head Acc={:.2f}, Result Acc={:.2f})'.format('test', 100*perception_acc, 100*head_acc, 100*result_acc))\n return\n\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n sys.argv = sys.argv[:1]\n\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n torch.backends.cudnn.benchmark = False\n # torch.set_deterministic(True)\n\n # train_set = HINT('train', numSamples=5000)\n train_set = HINT('train')\n val_set = HINT('val')\n # test_set = HINT('val')\n test_set = HINT('test')\n print('train:', len(train_set), 'val:', len(val_set), 'test:', len(test_set))\n\n model = make_model(args)\n model.to(DEVICE)\n\n if args.perception_pretrain and not args.perception:\n model.embedding_in.image_encoder.load_state_dict(torch.load(args.perception_pretrain))\n\n st_epoch = 0\n if args.resume:\n st_epoch = model.load(args.resume)\n if st_epoch is None:\n st_epoch = 0\n\n\n print(args)\n print(model)\n args.train_set = train_set\n args.val_set = val_set\n args.test_set = test_set\n\n train(model, args, st_epoch=st_epoch)\n\n" ]
[ [ "numpy.random.seed", "torch.load", "torch.manual_seed", "torch.utils.data.DataLoader", "torch.tensor", "numpy.concatenate", "torch.no_grad", "numpy.mean", "pandas.set_option", "numpy.array", "torch.multiprocessing.set_sharing_strategy", "torch.argmax" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ravikant95/PW_from_GPS
[ "0aab3ad51ef2ba09dd1dac9b83c29dfbbf6e7009" ]
[ "generate_pw_shell_script.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 18 15:21:21 2019\n\n@author: shlomi\n\"\"\"\n# TODO: add backup option depending on task. use tarfile to compress\n\ndef check_python_version(min_major=3, min_minor=6):\n import sys\n major = sys.version_info[0]\n minor = sys.version_info[1]\n print('detecting python varsion: {}.{}'.format(major, minor))\n if major < min_major or minor < min_minor:\n raise ValueError('Python version needs to be at least {}.{} to run this script...'.format(min_major, min_minor))\n return\n\n\ndef check_path(path):\n import os\n path = str(path)\n if not os.path.exists(path):\n raise argparse.ArgumentTypeError('{} does not exist...'.format(path))\n return path\n\n\ndef check_station_name(name):\n # import os\n if isinstance(name, list):\n name = [str(x).lower() for x in name]\n for nm in name:\n if len(nm) != 4:\n raise argparse.ArgumentTypeError('{} should be 4 letters...'.format(nm))\n return name\n else:\n name = str(name).lower()\n if len(name) != 4:\n raise argparse.ArgumentTypeError(name + ' should be 4 letters...')\n return name\n\n\ndef generate_delete(station, task, dates):\n from aux_gps import query_yes_no\n from aux_gps import path_glob\n from aux_gps import slice_task_date_range\n for curr_sta in station:\n station_path = workpath / curr_sta\n if task == 'drdump':\n path = station_path / 'rinex/dr'\n glob_str = '*.dr.gz'\n elif task == 'edit30hr':\n path = station_path / 'rinex/30hr'\n glob_str = '*.dr.gz'\n elif task == 'run':\n path = station_path / 'rinex/30hr/results'\n glob_str = '*.tdp'\n elif task == 'post':\n path = station_path / 'gipsyx_solutions'\n glob_str = '*.nc'\n try:\n files_to_delete = path_glob(path, glob_str)\n if dates is not None:\n files_to_delete = slice_task_date_range(files_to_delete, dates,\n 'delete')\n fnum = len(files_to_delete)\n except FileNotFoundError:\n print('skipping {} , because its empty or not existant..'.format(path))\n continue\n suff = glob_str.split('.')[-1]\n print(\n 'WARNING for {}, ALL {} files({}) in {} WILL BE DELETED!'.format(\n curr_sta, suff, fnum, path))\n to_delete = query_yes_no('ARE YOU SURE ?')\n if not to_delete:\n print('files NOT deleted...')\n continue\n else:\n [x.unlink() for x in files_to_delete]\n print('FILES DELETED!')\n return\n\n\ndef generate_backup(station, task, dates):\n from aux_gps import tar_dir\n from aux_gps import slice_task_date_range\n for curr_sta in station:\n station_path = workpath / curr_sta\n if task == 'drdump':\n path = station_path / 'rinex/dr'\n glob_str = '*.dr.gz'\n elif task == 'edit30hr':\n path = station_path / 'rinex/30hr'\n glob_str = '*.dr.gz'\n elif task == 'run':\n path = station_path / 'rinex/hr30/results'\n glob_str = '*.tdp'\n elif task == 'post':\n path = station_path / 'gipsyx_solutions'\n glob_str = '*.nc'\n filename = '{}_{}_backup.tar.gz'.format(curr_sta, task)\n savepath = station_path / 'backup'\n savepath.mkdir(parents=True, exist_ok=True)\n files_to_tar = path_glob(path, glob_str)\n if dates is not None:\n files_to_tar = slice_task_date_range(files_to_tar, dates, 'backup')\n try:\n tar_dir(files_to_tar, filename, savepath, compresslevel=None)\n except FileNotFoundError:\n print(\n 'skipping {} , because no {} found in {}'.format(\n curr_sta, glob_str, path))\n continue\n print('{} station {} files were backed up to {}'.format(\n curr_sta, glob_str, savepath / filename))\n return\n\n\ndef generate_rinex_reader(station, dates):\n from pathlib import Path\n lines = []\n cwd = Path().cwd()\n print('created rinex header reader script with the following parameters:')\n for curr_sta in station:\n station_path = workpath / curr_sta\n rinexpath = station_path / 'rinex'\n savepath = pwpath\n lines.append('cd {}'.format(station_path))\n line = 'nohup python -u {}/rinex_header_reader.py'.format(pwpath)\\\n + ' --rinexpath {} --savepath {}'.format(rinexpath, savepath)\n if dates is not None:\n line += ' --daterange {} {}'.format(dates[0], dates[1])\n line += ' &>{}/nohup_{}_rnx_reader.txt&'.format(pwpath, curr_sta)\n lines.append(line)\n lines.append('cd {}'.format(pwpath))\n print('station: {}, savepath: {}'.format(curr_sta, savepath))\n with open(cwd / script_file, 'w') as file:\n for item in lines:\n file.write(\"%s\\n\" % item)\n print('run the script with source {} !'.format(script_file))\n return\n\n\ndef generate_rinex_download(station, mdt, db):\n from pathlib import Path\n lines = []\n cwd = Path().cwd()\n print('created rinex download script with the following parameters:')\n for curr_sta in station:\n station_path = workpath / curr_sta\n station_path.mkdir(parents=True, exist_ok=True)\n savepath = (station_path / 'rinex')\n savepath.mkdir(parents=True, exist_ok=True)\n lines.append('cd {}'.format(station_path))\n if db is None:\n db = 'garner'\n # db_year = 1988\n # elif db == 'cddis':\n # db_year = 1992\n line = 'nohup python -u {}/single_rinex_station_download_from_garner.py'.format(pwpath)\\\n + ' --path {} --mode rinex --station {} --db {}'.format(savepath, curr_sta, db)\\\n + '&>{}/nohup_{}_download.txt&'.format(pwpath, curr_sta)\n # + ' --mdt {}'.format(db_year)\n if mdt is not None:\n line = 'nohup python -u {}/single_rinex_station_download_from_garner.py'.format(pwpath)\\\n + ' --path {} --mode rinex --station {} --db {}'.format(savepath, curr_sta, db)\\\n + ' --mdt {} &>{}/nohup_{}_download.txt&'.format(mdt, pwpath, curr_sta)\n lines.append(line)\n lines.append('cd {}'.format(pwpath))\n print('station: {}, savepath: {}'.format(curr_sta, savepath))\n if mdt is not None:\n print('station: {}, datetime: {}'.format(curr_sta, mdt))\n if db is not None:\n print('station: {}, db: {}'.format(curr_sta, db))\n with open(cwd / script_file, 'w') as file:\n for item in lines:\n file.write(\"%s\\n\" % item)\n print('run the script with source {} !'.format(script_file))\n return\n\n\ndef generate_gipsyx_run(station, task, tree, staDb, dates):\n from pathlib import Path\n lines = []\n cwd = Path().cwd()\n print('created gipsyx run script with the following parameters:')\n for curr_sta in station:\n station_path = workpath / curr_sta\n rinexpath = station_path / 'rinex'\n runpath = station_path / 'rinex/30hr'\n lines.append('cd {}'.format(station_path))\n if task == 'drdump' or task == 'edit30hr':\n line = 'nohup python -u {}/run_gipsyx.py'.format(pwpath)\\\n + ' --rinexpath {} --prep {}'.format(rinexpath, task)\\\n + ' --staDb {}'.format(staDb)\n if tree is not None:\n line += ' --tree {}'.format(tree)\n if dates is not None:\n line += ' --daterange {} {}'.format(dates[0], dates[1])\n line += ' &>{}/nohup_{}_{}.txt&'.format(pwpath, curr_sta, task)\n elif task == 'run':\n line = 'nohup python -u {}/run_gipsyx.py'.format(pwpath)\\\n + ' --rinexpath {} --staDb {}'.format(runpath, staDb)\n if tree is not None:\n line += ' --tree {}'.format(tree)\n if dates is not None:\n line += ' --daterange {} {}'.format(dates[0], dates[1])\n line += ' &>{}/nohup_{}_{}.txt&'.format(pwpath, curr_sta, task)\n lines.append(line)\n lines.append('cd {}'.format(pwpath))\n print('station: {}, task: {}'.format(curr_sta, task))\n print('station: {}, rinexpath: {}'.format(curr_sta, rinexpath))\n print('station: {}, tree: {}'.format(curr_sta, tree))\n print('station: {}, staDb: {}'.format(curr_sta, staDb))\n with open(cwd / script_file, 'w') as file:\n for item in lines:\n file.write(\"%s\\n\" % item)\n print('run the script with source {} !'.format(script_file))\n return\n\n\ndef generate_gipsyx_post(station, iqr_k):\n from pathlib import Path\n lines = []\n cwd = Path().cwd()\n lines = []\n print('created gipsyx post procceser script with the following parameters:')\n for curr_sta in station:\n station_path = workpath / curr_sta\n savepath = station_path / 'gipsyx_solutions'\n tdppath = station_path / 'rinex/30hr/results'\n lines.append('cd {}'.format(station_path))\n if iqr_k is None:\n line = 'nohup python -u {}/gipsyx_post_proc.py'.format(pwpath)\\\n + ' --tdppath {} --savepath {}'.format(tdppath, savepath)\\\n + ' &>{}/nohup_{}_post.txt&'.format(pwpath, curr_sta)\n else:\n line = 'nohup python -u {}/gipsyx_post_proc.py'.format(pwpath)\\\n + ' --tdppath {} --savepath {} --iqr_k {}'.format(tdppath, savepath, iqr_k)\\\n + ' &>{}/nohup_{}_post.txt&'.format(pwpath, curr_sta)\n lines.append(line)\n lines.append('cd {}'.format(pwpath))\n print('station: {}, tdppath: {}'.format(curr_sta, tdppath))\n print('station:{}, savepath: {}'.format(curr_sta, savepath))\n if iqr_k is not None:\n print('station: {}, iqr_k: {}'.format(curr_sta, iqr_k))\n with open(cwd / script_file, 'w') as file:\n for item in lines:\n file.write(\"%s\\n\" % item)\n print('run the script with source {} !'.format(script_file))\n return\n\n\ndef task_switcher(args):\n if args.delete:\n generate_delete(args.station, args.task, args.daterange)\n elif args.backup:\n generate_backup(args.station, args.task, args.daterange)\n else:\n if args.task == 'rinex_download':\n generate_rinex_download(args.station, args.mdt, args.db)\n elif args.task == 'rinex_reader':\n generate_rinex_reader(args.station, args.daterange)\n elif args.task == 'drdump' or args.task == 'edit30hr' or args.task == 'run':\n generate_gipsyx_run(args.station, args.task, args.tree, args.staDb,\n args.daterange)\n elif args.task == 'post':\n generate_gipsyx_post(args.station, args.iqr_k)\n return\n\n\ndef check_dt(dt):\n from datetime import datetime\n import pandas as pd\n dt = pd.to_datetime(dt, format='%Y-%m')\n year = dt.year\n # month = dt.month\n doy = dt.dayofyear\n this_year = datetime.today().year\n if year < 1988:\n raise argparse.ArgumentTypeError('{} should be >= 1988'.format(year))\n if year > datetime.today().year:\n raise argparse.ArgumentTypeError(\n '{} should be <= {}'.format(\n year, this_year))\n return dt.strftime('%Y-%m')\n\n\n\nif __name__ == '__main__':\n import argparse\n import sys\n from pathlib import Path\n from aux_gps import configure_logger\n from aux_gps import get_var\n from aux_gps import path_glob\n import pandas as pd\n global script_file\n global pwpath\n global workpath\n # main directive:\n # write a script called run_gipsyx_script.sh with:\n # cd to the workpath / station and run nohup with the usual args\n script_file = 'gipsyx_pw_script.sh'\n check_python_version(min_major=3, min_minor=6)\n parser = argparse.ArgumentParser(description='a command line tool for ' +\n 'generating pw shell script to run tasks' +\n 'as download rinex files, running gipsyx etc...')\n optional = parser._action_groups.pop()\n required = parser.add_argument_group('required arguments')\n # remove this line: optional = parser...\n required.add_argument('--task', help=\"a task to preform, e.g., run_gipsyx, post_gipsyx, download_rinex.\"\n , choices=['rinex_download', 'rinex_reader',\n 'drdump', 'edit30hr', 'run', 'post'])\n required.add_argument('--station', help=\"GPS station name four lowercase letters,\",\n nargs='+', type=check_station_name)\n optional.add_argument('--mdt', help='minimum year-month to begin search in garner site.',\n type=check_dt)\n optional.add_argument('--daterange', help='add specific date range, can be one day',\n type=str, nargs=2)\n optional.add_argument(\n '--staDb',\n help='add a station DB file for antennas and receivers in rinexpath',\n type=str)\n optional.add_argument('--tree', help='gipsyX tree directory.',\n type=str)\n optional.add_argument('--iqr_k', help='iqr k data filter criterion',\n type=float)\n optional.add_argument('--db', help='database to download rinex files from.',\n choices=['garner', 'cddis'])\n required.add_argument('--delete', action='store_true') # its False\n required.add_argument('--backup', action='store_true') # its False\n# metavar=str(cds.start_year) + ' to ' + str(cds.end_year))\n# optional.add_argument('--half', help='a spescific six months to download,\\\n# e.g, 1 or 2', type=int, choices=[1, 2],\n# metavar='1 or 2')\n optional.add_argument('--last_n_weeks', help='last n weeks for setting date-range, i.e., how many weeks back from today',\n type=int)\n parser._action_groups.append(optional) # added this line\n # add flag argument for just proccsing the last 2 weeks:\n args = parser.parse_args()\n# for arg in vars(args):\n# print(arg, getattr(args, arg))\n# sys.exit()\n pwpath = Path(get_var('PWCORE'))\n workpath = Path(get_var('PWORK'))\n if pwpath is None:\n raise ValueError('Put source code folder at $PWCORE')\n # get all the names of israeli gnss stations (updated):\n soi_stations_file = path_glob(pwpath, 'SOI-APN_stations*.csv')[-1]\n df = pd.read_csv(soi_stations_file)\n #isr_stations = pd.read_fwf(pwpath / 'stations_approx_loc.txt')\n #isr_stations = isr_stations.iloc[:,0].tolist()\n isr_stations = df['name'].tolist()\n if workpath is None:\n raise ValueError('Put source code folder at $PWORK')\n # get the names of the stations in workpath:\n stations = path_glob(workpath, '*')\n stations = [x.as_posix().split('/')[-1] for x in stations if x.is_dir()]\n if args.task is None:\n print('task is a required argument, run with -h...')\n sys.exit()\n if args.station is None:\n print('station is a required argument, run with -h...')\n sys.exit()\n if args.station == ['soin']:\n args.station = isr_stations\n # use soin (survey of israel network) stations db for israeli stations and ocean loading also:\n if all(a in isr_stations for a in args.station) and args.tree is None and args.staDb is None:\n args.tree = pwpath / 'my_trees/ISROcnld'\n args.staDb = pwpath / 'ALL.staDb'\n else:\n if args.staDb is not None:\n args.staDb = pwpath / args.staDb\n else:\n args.staDb = pwpath / 'ALL.staDb'\n if args.tree is not None:\n args.tree = pwpath / args.tree\n if (get_var('GCORE') is None and not args.delete or get_var('GCORE')\n is None and not args.backup):\n raise ValueError('Run source ~/GipsyX-1.1/rc_GipsyX.sh first !')\n\n if args.last_n_weeks is not None:\n today = pd.Timestamp.today().round('1D')\n before = today - pd.Timedelta(args.last_n_weeks, unit='w')\n args.daterange = [before.strftime('%Y-%m-%d'), today.strftime('%Y-%m-%d')]\n task_switcher(args)\n # print(parser.format_help())\n# # print(vars(args))\n\n# elif args.field is None:\n# print('field is a required argument, run with -h...')\n# sys.exit()\n" ]
[ [ "pandas.to_datetime", "pandas.read_csv", "pandas.Timedelta", "pandas.Timestamp.today" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Khev/graph_star
[ "4ac9cf09d77fc11dbbb07c9b2715c4ef1a5f3597" ]
[ "module/graph_star_conv_multi_rel.py" ]
[ "import torch\nimport torch.nn.functional as F\nfrom torch.nn import Parameter\nfrom torch_geometric.nn.conv import MessagePassing\nfrom torch_geometric.utils import add_self_loops, softmax\n\nfrom torch_geometric.utils import scatter_\nimport math\nimport torch.nn.init as init\n\n\nclass GraphStarConv(MessagePassing):\n r\"\"\"The graph attentional operator from the `\"Graph Attention Networks\"\n <https://arxiv.org/abs/1710.10903>`_ paper\n\n .. math::\n \\mathbf{x}^{\\prime}_i = \\alpha_{i,i}\\mathbf{\\Theta}\\mathbf{x}_{j} +\n \\sum_{j \\in \\mathcal{N}(i)} \\alpha_{i,j}\\mathbf{\\Theta}\\mathbf{x}_{j},\n\n where the attention coefficients :math:`\\alpha_{i,j}` are computed as\n\n .. math::\n \\alpha_{i,j} =\n \\frac{\n \\exp\\left(\\mathrm{LeakyReLU}\\left(\\mathbf{a}^{\\top}\n [\\mathbf{\\Theta}\\mathbf{x}_i \\, \\Vert \\, \\mathbf{\\Theta}\\mathbf{x}_j]\n \\right)\\right)}\n {\\sum_{k \\in \\mathcal{N}(i) \\cup \\{ i \\}}\n \\exp\\left(\\mathrm{LeakyReLU}\\left(\\mathbf{a}^{\\top}\n [\\mathbf{\\Theta}\\mathbf{x}_i \\, \\Vert \\, \\mathbf{\\Theta}\\mathbf{x}_k]\n \\right)\\right)}.\n\n Args:\n in_channels (int): Size of each input sample.\n out_channels (int): Size of each output sample.\n heads (int, optional): Number of multi-head-attentions. (default:\n :obj:`1`)\n concat (bool, optional): If set to :obj:`False`, the multi-head\n attentions are averaged instead of concatenated. (default: :obj:`True`)\n negative_slope (float, optional): LeakyReLU angle of the negative\n slope. (default: :obj:`0.2`)\n dropout (float, optional): Dropout probability of the normalized\n attention coefficients which exposes each node to a stochastically\n sampled neighborhood during training. (default: :obj:`0`)\n bias (bool, optional): If set to :obj:`False`, the layer will not learn\n an additive bias. (default: :obj:`True`)\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels,\n layer=0,\n heads=1,\n dropout=0.1,\n num_star=1,\n residual=True,\n layer_norm=True,\n use_e=True,\n activation=None,\n num_relations=1\n ):\n super(GraphStarConv, self).__init__()\n self.layer = layer\n self.use_e = use_e\n self.layer_norm = layer_norm\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.heads = heads\n self.dropout = dropout\n self.num_star = num_star\n self.residual = residual\n self.activation = activation\n\n assert out_channels % heads == 0\n self.size_pre_head = out_channels // heads\n self.nWq = torch.nn.ModuleList([torch.nn.Linear(in_channels, out_channels) for _ in range(num_relations)])\n self.nWk = torch.nn.ModuleList([torch.nn.Linear(in_channels, out_channels) for _ in range(num_relations)])\n self.nWv = torch.nn.ModuleList([torch.nn.Linear(in_channels, out_channels) for _ in range(num_relations)])\n self.nWo = torch.nn.ModuleList([torch.nn.Linear(out_channels, out_channels) for _ in range(num_relations)])\n\n self.nLayerNorm = torch.nn.LayerNorm(out_channels)\n self.num_relations = num_relations\n\n def forward(self, x, stars, init_x, edge_index, edge_type=None):\n \"\"\"\"\"\"\n num_node = x.size(0)\n nodes = x\n\n if init_x is not None:\n nodes = torch.cat([nodes, init_x], dim=0)\n\n if stars is not None:\n nodes = torch.cat([nodes, stars], dim=0)\n\n nodes = self.propagate('add', edge_index, edge_type, x=nodes, num_nodes=num_node)\n\n return nodes\n\n def propagate(self, aggr, edge_index, edge_type, size=None, **kwargs):\n r\"\"\"The initial call to start propagating messages.\n\n Args:\n aggr (string): Takes in an aggregation scheme (:obj:`\"add\"`,\n :obj:`\"mean\"` or :obj:`\"max\"`).\n edge_index (Tensor): The indices of a general (sparse) assignment\n matrix with shape :obj:`[M, N]` (can be directed or\n undirected).\n size (int, optional): The output node size :math:`M`. If\n :obj:`None`, the output node size will get automatically\n inferrred by assuming a symmetric adjacency matrix as input.\n **kwargs: Any additional data which is needed to construct messages\n and to update node embeddings.\n \"\"\"\n assert aggr in ['add', 'mean', 'max']\n kwargs['edge_index'] = edge_index\n x = kwargs[\"x\"]\n num_nodes = kwargs[\"num_nodes\"]\n\n out_list = []\n for i in range(self.num_relations):\n edge_index_mask = (edge_type == i)\n if edge_index_mask.sum() > 0:\n\n edge_index_i = edge_index[0][edge_index_mask]\n edge_index_j = edge_index[1][edge_index_mask]\n\n # 同样的功能,只是根据稀疏程度决定运算顺序以提高性能\n if edge_index_mask.sum() < num_nodes:\n xi = torch.index_select(x, 0, edge_index_i)\n xj = torch.index_select(x, 0, edge_index_j)\n\n xq = self.nWq[i](xi).view(-1, self.heads, self.size_pre_head)\n xk = self.nWk[i](xj).view(-1, self.heads, self.size_pre_head)\n xv = self.nWv[i](xj).view(-1, self.heads, self.size_pre_head)\n else:\n xq = self.nWq[i](x).view(-1, self.heads, self.size_pre_head)\n xk = self.nWk[i](x).view(-1, self.heads, self.size_pre_head)\n xv = self.nWv[i](x).view(-1, self.heads, self.size_pre_head)\n\n xq = torch.index_select(xq, 0, edge_index_i)\n xk = torch.index_select(xk, 0, edge_index_j)\n xv = torch.index_select(xv, 0, edge_index_j)\n\n out = self.message(xq, xk, xv,\n edge_index_i, num_nodes)\n\n out = scatter_(aggr, out, edge_index_i, dim_size=size)\n out = self.update(out)\n if out.size(0) < num_nodes:\n out = torch.cat([out, out.new_zeros([num_nodes - out.size(0), out.size(-1)])])\n out = self.nWo[i](out)\n else:\n out = x.new_zeros([num_nodes, self.out_channels])\n out_list.append(out)\n out = torch.stack(out_list, dim=0)\n out = torch.mean(out, dim=0)\n\n if self.activation is not None:\n out = self.activation(out)\n if self.residual:\n out = out + x[:num_nodes]\n\n if self.layer_norm:\n out = self.nLayerNorm(out)\n return out\n\n def message(self, x_q, x_k, x_v, edge_index_i, num_nodes):\n score = self.cal_att_score(x_q, x_k, self.heads)\n # score = F.leaky_relu(score)\n score = softmax(score, edge_index_i, num_nodes)\n\n # score = F.dropout(score, p=self.dropout, training=self.training)\n x_v = F.dropout(x_v, p=self.dropout, training=self.training)\n\n return x_v * score.view(-1, self.heads, 1)\n\n def update(self, aggr_out):\n aggr_out = aggr_out.view(-1, self.out_channels)\n\n return aggr_out\n\n def cal_att_score(self, q, k, heads):\n out_channel = q.size(-1)\n score = torch.matmul(q.view(-1, heads, 1, out_channel), k.view(-1, heads, out_channel, 1)).view(\n -1, heads)\n score = score / math.sqrt(out_channel)\n return score\n\n def __repr__(self):\n return '{}({}, {}, heads={})'.format(self.__class__.__name__,\n self.in_channels,\n self.out_channels, self.heads)\n" ]
[ [ "torch.mean", "torch.nn.functional.dropout", "torch.cat", "torch.nn.LayerNorm", "torch.nn.Linear", "torch.stack", "torch.index_select" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
bubbliiiing/classification-tf2
[ "10704d8e1073364eaee76a9f60aed73ca7e7b554" ]
[ "utils/utils.py" ]
[ "import math\r\nfrom functools import partial\r\n\r\nimport numpy as np\r\nfrom PIL import Image\r\n\r\nfrom .utils_aug import resize, center_crop\r\n\r\n\r\n#---------------------------------------------------------#\r\n# 将图像转换成RGB图像,防止灰度图在预测时报错。\r\n# 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB\r\n#---------------------------------------------------------#\r\ndef cvtColor(image):\r\n if len(np.shape(image)) == 3 and np.shape(image)[2] == 3:\r\n return image \r\n else:\r\n image = image.convert('RGB')\r\n return image \r\n\r\n#---------------------------------------------------#\r\n# 对输入图像进行resize\r\n#---------------------------------------------------#\r\ndef letterbox_image(image, size, letterbox_image):\r\n w, h = size\r\n iw, ih = image.size\r\n if letterbox_image:\r\n '''resize image with unchanged aspect ratio using padding'''\r\n scale = min(w/iw, h/ih)\r\n nw = int(iw*scale)\r\n nh = int(ih*scale)\r\n\r\n image = image.resize((nw,nh), Image.BICUBIC)\r\n new_image = Image.new('RGB', size, (128,128,128))\r\n new_image.paste(image, ((w-nw)//2, (h-nh)//2))\r\n else:\r\n if h == w:\r\n new_image = resize(image, h)\r\n else:\r\n new_image = resize(image, [h ,w])\r\n new_image = center_crop(new_image, [h ,w])\r\n return new_image\r\n\r\n#---------------------------------------------------#\r\n# 获得类\r\n#---------------------------------------------------#\r\ndef get_classes(classes_path):\r\n with open(classes_path, encoding='utf-8') as f:\r\n class_names = f.readlines()\r\n class_names = [c.strip() for c in class_names]\r\n return class_names, len(class_names)\r\n\r\n#----------------------------------------#\r\n# 预处理训练图片\r\n#----------------------------------------#\r\ndef preprocess_input(x):\r\n x /= 127.5\r\n x -= 1.\r\n return x\r\n\r\ndef show_config(**kwargs):\r\n print('Configurations:')\r\n print('-' * 70)\r\n print('|%25s | %40s|' % ('keys', 'values'))\r\n print('-' * 70)\r\n for key, value in kwargs.items():\r\n print('|%25s | %40s|' % (str(key), str(value)))\r\n print('-' * 70)\r\n\r\ndef get_lr_scheduler(lr_decay_type, lr, min_lr, total_iters, warmup_iters_ratio = 0.05, warmup_lr_ratio = 0.1, no_aug_iter_ratio = 0.05, step_num = 10):\r\n def yolox_warm_cos_lr(lr, min_lr, total_iters, warmup_total_iters, warmup_lr_start, no_aug_iter, iters):\r\n if iters <= warmup_total_iters:\r\n # lr = (lr - warmup_lr_start) * iters / float(warmup_total_iters) + warmup_lr_start\r\n lr = (lr - warmup_lr_start) * pow(iters / float(warmup_total_iters), 2\r\n ) + warmup_lr_start\r\n elif iters >= total_iters - no_aug_iter:\r\n lr = min_lr\r\n else:\r\n lr = min_lr + 0.5 * (lr - min_lr) * (\r\n 1.0\r\n + math.cos(\r\n math.pi\r\n * (iters - warmup_total_iters)\r\n / (total_iters - warmup_total_iters - no_aug_iter)\r\n )\r\n )\r\n return lr\r\n\r\n def step_lr(lr, decay_rate, step_size, iters):\r\n if step_size < 1:\r\n raise ValueError(\"step_size must above 1.\")\r\n n = iters // step_size\r\n out_lr = lr * decay_rate ** n\r\n return out_lr\r\n\r\n if lr_decay_type == \"cos\":\r\n warmup_total_iters = min(max(warmup_iters_ratio * total_iters, 1), 3)\r\n warmup_lr_start = max(warmup_lr_ratio * lr, 1e-6)\r\n no_aug_iter = min(max(no_aug_iter_ratio * total_iters, 1), 15)\r\n func = partial(yolox_warm_cos_lr ,lr, min_lr, total_iters, warmup_total_iters, warmup_lr_start, no_aug_iter)\r\n else:\r\n decay_rate = (min_lr / lr) ** (1 / (step_num - 1))\r\n step_size = total_iters / step_num\r\n func = partial(step_lr, lr, decay_rate, step_size)\r\n\r\n return func\r\n\r\n#-------------------------------------------------------------------------------------------------------------------------------#\r\n# From https://github.com/ckyrkou/Keras_FLOP_Estimator \r\n# Fix lots of bugs\r\n#-------------------------------------------------------------------------------------------------------------------------------#\r\ndef net_flops(model, table=False, print_result=True):\r\n if (table == True):\r\n print(\"\\n\")\r\n print('%25s | %16s | %16s | %16s | %16s | %6s | %6s' % (\r\n 'Layer Name', 'Input Shape', 'Output Shape', 'Kernel Size', 'Filters', 'Strides', 'FLOPS'))\r\n print('=' * 120)\r\n \r\n #---------------------------------------------------#\r\n # 总的FLOPs\r\n #---------------------------------------------------#\r\n t_flops = 0\r\n factor = 1e9\r\n\r\n for l in model.layers:\r\n try:\r\n #--------------------------------------#\r\n # 所需参数的初始化定义\r\n #--------------------------------------#\r\n o_shape, i_shape, strides, ks, filters = ('', '', ''), ('', '', ''), (1, 1), (0, 0), 0\r\n flops = 0\r\n #--------------------------------------#\r\n # 获得层的名字\r\n #--------------------------------------#\r\n name = l.name\r\n \r\n if ('InputLayer' in str(l)):\r\n i_shape = l.get_input_shape_at(0)[1:4]\r\n o_shape = l.get_output_shape_at(0)[1:4]\r\n \r\n #--------------------------------------#\r\n # Reshape层\r\n #--------------------------------------#\r\n elif ('Reshape' in str(l)):\r\n i_shape = l.get_input_shape_at(0)[1:4]\r\n o_shape = l.get_output_shape_at(0)[1:4]\r\n\r\n #--------------------------------------#\r\n # 填充层\r\n #--------------------------------------#\r\n elif ('Padding' in str(l)):\r\n i_shape = l.get_input_shape_at(0)[1:4]\r\n o_shape = l.get_output_shape_at(0)[1:4]\r\n\r\n #--------------------------------------#\r\n # 平铺层\r\n #--------------------------------------#\r\n elif ('Flatten' in str(l)):\r\n i_shape = l.get_input_shape_at(0)[1:4]\r\n o_shape = l.get_output_shape_at(0)[1:4]\r\n \r\n #--------------------------------------#\r\n # 激活函数层\r\n #--------------------------------------#\r\n elif 'Activation' in str(l):\r\n i_shape = l.get_input_shape_at(0)[1:4]\r\n o_shape = l.get_output_shape_at(0)[1:4]\r\n \r\n #--------------------------------------#\r\n # LeakyReLU\r\n #--------------------------------------#\r\n elif 'LeakyReLU' in str(l):\r\n for i in range(len(l._inbound_nodes)):\r\n i_shape = l.get_input_shape_at(i)[1:4]\r\n o_shape = l.get_output_shape_at(i)[1:4]\r\n \r\n flops += i_shape[0] * i_shape[1] * i_shape[2]\r\n \r\n #--------------------------------------#\r\n # 池化层\r\n #--------------------------------------#\r\n elif 'MaxPooling' in str(l):\r\n i_shape = l.get_input_shape_at(0)[1:4]\r\n o_shape = l.get_output_shape_at(0)[1:4]\r\n \r\n #--------------------------------------#\r\n # 池化层\r\n #--------------------------------------#\r\n elif ('AveragePooling' in str(l) and 'Global' not in str(l)):\r\n strides = l.strides\r\n ks = l.pool_size\r\n \r\n for i in range(len(l._inbound_nodes)):\r\n i_shape = l.get_input_shape_at(i)[1:4]\r\n o_shape = l.get_output_shape_at(i)[1:4]\r\n \r\n flops += o_shape[0] * o_shape[1] * o_shape[2]\r\n\r\n #--------------------------------------#\r\n # 全局池化层\r\n #--------------------------------------#\r\n elif ('AveragePooling' in str(l) and 'Global' in str(l)):\r\n for i in range(len(l._inbound_nodes)):\r\n i_shape = l.get_input_shape_at(i)[1:4]\r\n o_shape = l.get_output_shape_at(i)[1:4]\r\n \r\n flops += (i_shape[0] * i_shape[1] + 1) * i_shape[2]\r\n \r\n #--------------------------------------#\r\n # 标准化层\r\n #--------------------------------------#\r\n elif ('BatchNormalization' in str(l)):\r\n for i in range(len(l._inbound_nodes)):\r\n i_shape = l.get_input_shape_at(i)[1:4]\r\n o_shape = l.get_output_shape_at(i)[1:4]\r\n\r\n temp_flops = 1\r\n for i in range(len(i_shape)):\r\n temp_flops *= i_shape[i]\r\n temp_flops *= 2\r\n \r\n flops += temp_flops\r\n \r\n #--------------------------------------#\r\n # 全连接层\r\n #--------------------------------------#\r\n elif ('Dense' in str(l)):\r\n for i in range(len(l._inbound_nodes)):\r\n i_shape = l.get_input_shape_at(i)[1:4]\r\n o_shape = l.get_output_shape_at(i)[1:4]\r\n \r\n temp_flops = 1\r\n for i in range(len(o_shape)):\r\n temp_flops *= o_shape[i]\r\n \r\n if (i_shape[-1] == None):\r\n temp_flops = temp_flops * o_shape[-1]\r\n else:\r\n temp_flops = temp_flops * i_shape[-1]\r\n flops += temp_flops\r\n\r\n #--------------------------------------#\r\n # 普通卷积层\r\n #--------------------------------------#\r\n elif ('Conv2D' in str(l) and 'DepthwiseConv2D' not in str(l) and 'SeparableConv2D' not in str(l)):\r\n strides = l.strides\r\n ks = l.kernel_size\r\n filters = l.filters\r\n bias = 1 if l.use_bias else 0\r\n \r\n for i in range(len(l._inbound_nodes)):\r\n i_shape = l.get_input_shape_at(i)[1:4]\r\n o_shape = l.get_output_shape_at(i)[1:4]\r\n \r\n if (filters == None):\r\n filters = i_shape[2]\r\n flops += filters * o_shape[0] * o_shape[1] * (ks[0] * ks[1] * i_shape[2] + bias)\r\n\r\n #--------------------------------------#\r\n # 逐层卷积层\r\n #--------------------------------------#\r\n elif ('Conv2D' in str(l) and 'DepthwiseConv2D' in str(l) and 'SeparableConv2D' not in str(l)):\r\n strides = l.strides\r\n ks = l.kernel_size\r\n filters = l.filters\r\n bias = 1 if l.use_bias else 0\r\n \r\n for i in range(len(l._inbound_nodes)):\r\n i_shape = l.get_input_shape_at(i)[1:4]\r\n o_shape = l.get_output_shape_at(i)[1:4]\r\n \r\n if (filters == None):\r\n filters = i_shape[2]\r\n flops += filters * o_shape[0] * o_shape[1] * (ks[0] * ks[1] + bias)\r\n \r\n #--------------------------------------#\r\n # 深度可分离卷积层\r\n #--------------------------------------#\r\n elif ('Conv2D' in str(l) and 'DepthwiseConv2D' not in str(l) and 'SeparableConv2D' in str(l)):\r\n strides = l.strides\r\n ks = l.kernel_size\r\n filters = l.filters\r\n \r\n for i in range(len(l._inbound_nodes)):\r\n i_shape = l.get_input_shape_at(i)[1:4]\r\n o_shape = l.get_output_shape_at(i)[1:4]\r\n \r\n if (filters == None):\r\n filters = i_shape[2]\r\n flops += i_shape[2] * o_shape[0] * o_shape[1] * (ks[0] * ks[1] + bias) + \\\r\n filters * o_shape[0] * o_shape[1] * (1 * 1 * i_shape[2] + bias)\r\n #--------------------------------------#\r\n # 模型中有模型时\r\n #--------------------------------------#\r\n elif 'Model' in str(l):\r\n flops = net_flops(l, print_result=False)\r\n \r\n t_flops += flops\r\n\r\n if (table == True):\r\n print('%25s | %16s | %16s | %16s | %16s | %6s | %5.4f' % (\r\n name[:25], str(i_shape), str(o_shape), str(ks), str(filters), str(strides), flops))\r\n \r\n except:\r\n pass\r\n \r\n t_flops = t_flops * 2\r\n if print_result:\r\n show_flops = t_flops / factor\r\n print('Total GFLOPs: %.3fG' % (show_flops))\r\n return t_flops" ]
[ [ "numpy.shape" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Praneet460/dtreeviz
[ "0c4996cca436f7f5136e1ea43dfd241b3bce1e97" ]
[ "dtreeviz/trees.py" ]
[ "from dtreeviz.utils import *\n\nimport numpy as np\nimport pandas as pd\nimport graphviz\nfrom pathlib import Path\nfrom sklearn import tree\nfrom graphviz.backend import run, view\nimport matplotlib.pyplot as plt\nfrom dtreeviz.shadow import *\nfrom numbers import Number\nimport matplotlib.patches as patches\nimport tempfile\nfrom os import getpid, makedirs\nfrom sys import platform as PLATFORM\n\nYELLOW = \"#fefecd\" # \"#fbfbd0\" # \"#FBFEB0\"\nBLUE = \"#D9E6F5\"\nGREEN = \"#cfe2d4\"\nDARKBLUE = '#313695'\nDARKGREEN = '#006400'\nLIGHTORANGE = '#fee090'\nLIGHTBLUE = '#a6bddb'\nGREY = '#444443'\nWEDGE_COLOR = GREY #'orange'\n\nHIGHLIGHT_COLOR = '#D67C03'\n\n# How many bins should we have based upon number of classes\nNUM_BINS = [0, 0, 10, 9, 8, 6, 6, 6, 5, 5, 5]\n # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10\n\ncolor_blind_friendly_colors = [\n None, # 0 classes\n None, # 1 class\n [\"#fefecd\",\"#a1dab4\"], # 2 classes\n [\"#fefecd\",\"#D9E6F5\",'#a1dab4'], # 3 classes\n [\"#fefecd\",\"#D9E6F5\",'#a1dab4','#fee090'], # 4\n [\"#fefecd\",\"#D9E6F5\",'#a1dab4','#41b6c4','#fee090'], # 5\n [\"#fefecd\",'#c7e9b4','#41b6c4','#2c7fb8','#fee090','#f46d43'], # 6\n [\"#fefecd\",'#c7e9b4','#7fcdbb','#41b6c4','#225ea8','#fdae61','#f46d43'], # 7\n [\"#fefecd\",'#edf8b1','#c7e9b4','#7fcdbb','#1d91c0','#225ea8','#fdae61','#f46d43'], # 8\n [\"#fefecd\",'#c7e9b4','#41b6c4','#74add1','#4575b4','#313695','#fee090','#fdae61','#f46d43'], # 9\n [\"#fefecd\",'#c7e9b4','#41b6c4','#74add1','#4575b4','#313695','#fee090','#fdae61','#f46d43','#d73027'] # 10\n]\n\nclass DTreeViz:\n def __init__(self,dot):\n self.dot = dot\n\n def _repr_svg_(self):\n return self.svg()\n\n def svg(self):\n \"\"\"Render tree as svg and return svg text.\"\"\"\n tmp = tempfile.gettempdir()\n svgfilename = f\"{tmp}/DTreeViz_{getpid()}.svg\"\n self.save(svgfilename)\n with open(svgfilename, encoding='UTF-8') as f:\n svg = f.read()\n return svg\n\n def view(self):\n tmp = tempfile.gettempdir()\n svgfilename = f\"{tmp}/DTreeViz_{getpid()}.svg\"\n self.save(svgfilename)\n view(svgfilename)\n\n def save(self, filename):\n \"\"\"\n Save the svg of this tree visualization into filename argument.\n Mac platform can save any file type (.pdf, .png, .svg). Other platforms\n would fail with errors. See https://github.com/parrt/dtreeviz/issues/4\n \"\"\"\n path = Path(filename)\n if not path.parent.exists:\n makedirs(path.parent)\n\n g = graphviz.Source(self.dot, format='svg')\n dotfilename = g.save(directory=path.parent.as_posix(), filename=path.stem)\n\n if PLATFORM=='darwin':\n # dot seems broken in terms of fonts if we use -Tsvg. Force users to\n # brew install graphviz with librsvg (else metrics are off) and\n # use -Tsvg:cairo which fixes bug and also automatically embeds images\n format = path.suffix[1:] # \".svg\" -> \"svg\" etc...\n cmd = [\"dot\", f\"-T{format}:cairo\", \"-o\", filename, dotfilename]\n # print(' '.join(cmd))\n stdout, stderr = run(cmd, capture_output=True, check=True, quiet=False)\n\n else:\n if not filename.endswith(\".svg\"):\n raise (Exception(f\"{PLATFORM} can only save .svg files: {filename}\"))\n # Gen .svg file from .dot but output .svg has image refs to other files\n #orig_svgfilename = filename.replace('.svg', '-orig.svg')\n cmd = [\"dot\", \"-Tsvg\", \"-o\", filename, dotfilename]\n # print(' '.join(cmd))\n stdout, stderr = run(cmd, capture_output=True, check=True, quiet=False)\n\n # now merge in referenced SVG images to make all-in-one file\n with open(filename, encoding='UTF-8') as f:\n svg = f.read()\n svg = inline_svg_images(svg)\n with open(filename, \"w\", encoding='UTF-8') as f:\n f.write(svg)\n\n\ndef dtreeviz(tree_model: (tree.DecisionTreeRegressor, tree.DecisionTreeClassifier),\n X_train: (pd.DataFrame, np.ndarray),\n y_train: (pd.Series, np.ndarray),\n feature_names: List[str],\n target_name: str,\n class_names: (Mapping[Number, str], List[str]) = None, # required if classifier\n precision: int = 2,\n orientation: ('TD', 'LR') = \"TD\",\n show_root_edge_labels: bool = True,\n show_node_labels: bool = False,\n fancy: bool = True,\n histtype: ('bar', 'barstacked') = 'barstacked',\n highlight_path: List[int] = [],\n X: np.ndarray = None,\n max_X_features_LR: int = 10,\n max_X_features_TD: int = 20) \\\n -> DTreeViz:\n \"\"\"\n Given a decision tree regressor or classifier, create and return a tree visualization\n using the graphviz (DOT) language.\n\n :param tree_model: A DecisionTreeRegressor or DecisionTreeClassifier that has been\n fit to X_train, y_train.\n :param X_train: A data frame or 2-D matrix of feature vectors used to train the model.\n :param y_train: A pandas Series or 1-D vector with target values or classes.\n :param feature_names: A list of the feature names.\n :param target_name: The name of the target variable.\n :param class_names: [For classifiers] A dictionary or list of strings mapping class\n value to class name.\n :param precision: When displaying floating-point numbers, how many digits to display\n after the decimal point. Default is 2.\n :param orientation: Is the tree top down, \"TD\", or left to right, \"LR\"?\n :param show_root_edge_labels: Include < and >= on the edges emanating from the root?\n :param show_node_labels: Add \"Node id\" to top of each node in graph for educational purposes\n :param fancy:\n :param histtype: [For classifiers] Either 'bar' or 'barstacked' to indicate\n histogram type. We find that 'barstacked' looks great up to about.\n four classes.\n :param highlight_path: A list of node IDs to highlight, default is [].\n Useful for emphasizing node(s) in tree for discussion.\n If X argument given then this is ignored.\n :type highlight_path: List[int]\n :param X: Instance to run down the tree; derived path to highlight from this vector.\n Show feature vector with labels underneath leaf reached. highlight_path\n is ignored if X is not None.\n :type np.ndarray\n :param max_X_features_LR: If len(X) exceeds this limit for LR layout,\n display only those features\n used to guide X vector down tree. Helps when len(X) is large.\n Default is 10.\n :param max_X_features_TD: If len(X) exceeds this limit for TD layout,\n display only those features\n used to guide X vector down tree. Helps when len(X) is large.\n Default is 25.\n\n :return: A string in graphviz DOT language that describes the decision tree.\n \"\"\"\n def node_name(node : ShadowDecTreeNode) -> str:\n if node.feature_name() is None:\n return f\"node{node.id}\"\n node_name = ''.join(c for c in node.feature_name() if c not in string.punctuation)+str(node.id)\n node_name = re.sub(\"[\"+string.punctuation+string.whitespace+\"]\", '_', node_name)\n return node_name\n\n def split_node(name, node_name, split):\n if fancy:\n labelgraph = node_label(node) if show_node_labels else ''\n html = f\"\"\"<table border=\"0\">\n {labelgraph}\n <tr>\n <td><img src=\"{tmp}/node{node.id}_{getpid()}.svg\"/></td>\n </tr>\n </table>\"\"\"\n else:\n html = f\"\"\"<font face=\"Helvetica\" color=\"#444443\" point-size=\"12\">{name}@{split}</font>\"\"\"\n if node.id in highlight_path:\n gr_node = f'{node_name} [margin=\"0\" shape=box penwidth=\".5\" color=\"{HIGHLIGHT_COLOR}\" style=\"dashed\" label=<{html}>]'\n else:\n gr_node = f'{node_name} [margin=\"0\" shape=none label=<{html}>]'\n return gr_node\n\n\n def regr_leaf_node(node, label_fontsize: int = 12):\n # always generate fancy regr leaves for now but shrink a bit for nonfancy.\n labelgraph = node_label(node) if show_node_labels else ''\n html = f\"\"\"<table border=\"0\">\n {labelgraph}\n <tr>\n <td><img src=\"{tmp}/leaf{node.id}_{getpid()}.svg\"/></td>\n </tr>\n </table>\"\"\"\n if node.id in highlight_path:\n return f'leaf{node.id} [margin=\"0\" shape=box penwidth=\".5\" color=\"{HIGHLIGHT_COLOR}\" style=\"dashed\" label=<{html}>]'\n else:\n return f'leaf{node.id} [margin=\"0\" shape=box penwidth=\"0\" label=<{html}>]'\n\n\n def class_leaf_node(node, label_fontsize: int = 12):\n labelgraph = node_label(node) if show_node_labels else ''\n html = f\"\"\"<table border=\"0\" CELLBORDER=\"0\">\n {labelgraph}\n <tr>\n <td><img src=\"{tmp}/leaf{node.id}_{getpid()}.svg\"/></td>\n </tr>\n </table>\"\"\"\n if node.id in highlight_path:\n return f'leaf{node.id} [margin=\"0\" shape=box penwidth=\".5\" color=\"{HIGHLIGHT_COLOR}\" style=\"dashed\" label=<{html}>]'\n else:\n return f'leaf{node.id} [margin=\"0\" shape=box penwidth=\"0\" label=<{html}>]'\n\n def node_label(node):\n return f'<tr><td CELLPADDING=\"0\" CELLSPACING=\"0\"><font face=\"Helvetica\" color=\"{GREY}\" point-size=\"14\"><i>Node {node.id}</i></font></td></tr>'\n\n def class_legend_html():\n return f\"\"\"\n <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n <tr>\n <td border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><img src=\"{tmp}/legend_{getpid()}.svg\"/></td>\n </tr> \n </table>\n \"\"\"\n\n def class_legend_gr():\n if not shadow_tree.isclassifier():\n return \"\"\n return f\"\"\"\n subgraph cluster_legend {{\n style=invis;\n legend [penwidth=\"0\" margin=\"0\" shape=box margin=\"0.03\" width=.1, height=.1 label=<\n {class_legend_html()}\n >]\n }}\n \"\"\"\n\n def instance_html(path, label_fontsize: int = 11):\n headers = []\n features_used = [node.feature() for node in path[:-1]] # don't include leaf\n display_X = X\n display_feature_names = feature_names\n highlight_feature_indexes = features_used\n if (orientation=='TD' and len(X)>max_X_features_TD) or\\\n (orientation == 'LR' and len(X) > max_X_features_LR):\n # squash all features down to just those used\n display_X = [X[i] for i in features_used] + ['...']\n display_feature_names = [node.feature_name() for node in path[:-1]] + ['...']\n highlight_feature_indexes = range(0,len(features_used))\n\n for i,name in enumerate(display_feature_names):\n color = GREY\n if i in highlight_feature_indexes:\n color = HIGHLIGHT_COLOR\n headers.append(f'<td cellpadding=\"1\" align=\"right\" bgcolor=\"white\"><font face=\"Helvetica\" color=\"{color}\" point-size=\"{label_fontsize}\"><b>{name}</b></font></td>')\n\n values = []\n for i,v in enumerate(display_X):\n color = GREY\n if i in highlight_feature_indexes:\n color = HIGHLIGHT_COLOR\n if isinstance(v,int) or isinstance(v, str):\n disp_v = v\n else:\n disp_v = myround(v, precision)\n values.append(f'<td cellpadding=\"1\" align=\"right\" bgcolor=\"white\"><font face=\"Helvetica\" color=\"{color}\" point-size=\"{label_fontsize}\">{disp_v}</font></td>')\n\n return f\"\"\"\n <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n <tr>\n {''.join(headers)}\n </tr>\n <tr>\n {''.join(values)}\n </tr>\n </table>\n \"\"\"\n\n def instance_gr():\n if X is None:\n return \"\"\n pred, path = shadow_tree.predict(X)\n leaf = f\"leaf{path[-1].id}\"\n if shadow_tree.isclassifier():\n edge_label = f\" Prediction<br/> {path[-1].prediction_name()}\"\n else:\n edge_label = f\" Prediction<br/> {myround(path[-1].prediction(), precision)}\"\n return f\"\"\"\n subgraph cluster_instance {{\n style=invis;\n X_y [penwidth=\"0.3\" margin=\"0\" shape=box margin=\"0.03\" width=.1, height=.1 label=<\n {instance_html(path)}\n >]\n }}\n {leaf} -> X_y [dir=back; penwidth=\"1.2\" color=\"{HIGHLIGHT_COLOR}\" label=<<font face=\"Helvetica\" color=\"{GREY}\" point-size=\"{11}\">{edge_label}</font>>]\n \"\"\"\n\n if orientation==\"TD\":\n ranksep = \".2\"\n nodesep = \"0.1\"\n else:\n if fancy:\n ranksep = \".22\"\n nodesep = \"0.1\"\n else:\n ranksep = \".05\"\n nodesep = \"0.09\"\n\n tmp = tempfile.gettempdir()\n # tmp = \"/tmp\"\n\n shadow_tree = ShadowDecTree(tree_model, X_train, y_train,\n feature_names=feature_names, class_names=class_names)\n\n if X is not None:\n pred, path = shadow_tree.predict(X)\n highlight_path = [n.id for n in path]\n\n n_classes = shadow_tree.nclasses()\n color_values = color_blind_friendly_colors[n_classes]\n\n # Fix the mapping from target value to color for entire tree\n colors = None\n if shadow_tree.isclassifier():\n class_values = shadow_tree.unique_target_values\n colors = {v:color_values[i] for i,v in enumerate(class_values)}\n\n y_range = (min(y_train)*1.03, max(y_train)*1.03) # same y axis for all\n\n if shadow_tree.isclassifier():\n # draw_legend_boxes(shadow_tree, f\"{tmp}/legend\")\n draw_legend(shadow_tree, target_name, f\"{tmp}/legend_{getpid()}.svg\")\n\n if isinstance(X_train,pd.DataFrame):\n X_train = X_train.values\n if isinstance(y_train,pd.Series):\n y_train = y_train.values\n\n # Find max height (count) for any bar in any node\n if shadow_tree.isclassifier():\n nbins = get_num_bins(histtype, n_classes)\n node_heights = shadow_tree.get_split_node_heights(X_train, y_train, nbins=nbins)\n\n internal = []\n for node in shadow_tree.internal:\n if fancy:\n if shadow_tree.isclassifier():\n class_split_viz(node, X_train, y_train,\n filename=f\"{tmp}/node{node.id}_{getpid()}.svg\",\n precision=precision,\n colors=colors,\n histtype=histtype,\n node_heights=node_heights,\n X = X,\n highlight_node=node.id in highlight_path)\n else:\n regr_split_viz(node, X_train, y_train,\n filename=f\"{tmp}/node{node.id}_{getpid()}.svg\",\n target_name=target_name,\n y_range=y_range,\n precision=precision,\n X=X,\n highlight_node=node.id in highlight_path)\n\n nname = node_name(node)\n gr_node = split_node(node.feature_name(), nname, split=myround(node.split(), precision))\n internal.append(gr_node)\n\n leaves = []\n for node in shadow_tree.leaves:\n if shadow_tree.isclassifier():\n class_leaf_viz(node, colors=color_values,\n filename=f\"{tmp}/leaf{node.id}_{getpid()}.svg\")\n leaves.append( class_leaf_node(node) )\n else:\n # for now, always gen leaf\n regr_leaf_viz(node, y_train, target_name=target_name,\n filename=f\"{tmp}/leaf{node.id}_{getpid()}.svg\",\n y_range=y_range, precision=precision)\n leaves.append( regr_leaf_node(node) )\n\n show_edge_labels = False\n all_llabel = '&lt;' if show_edge_labels else ''\n all_rlabel = '&ge;' if show_edge_labels else ''\n root_llabel = '&lt;' if show_root_edge_labels else ''\n root_rlabel = '&ge;' if show_root_edge_labels else ''\n\n edges = []\n # non leaf edges with > and <=\n for node in shadow_tree.internal:\n nname = node_name(node)\n if node.left.isleaf():\n left_node_name ='leaf%d' % node.left.id\n else:\n left_node_name = node_name(node.left)\n if node.right.isleaf():\n right_node_name ='leaf%d' % node.right.id\n else:\n right_node_name = node_name(node.right)\n llabel = all_llabel\n rlabel = all_rlabel\n if node==shadow_tree.root:\n llabel = root_llabel\n rlabel = root_rlabel\n lcolor = rcolor = GREY\n lpw = rpw = \"0.3\"\n if node.left.id in highlight_path:\n lcolor = HIGHLIGHT_COLOR\n lpw = \"1.2\"\n if node.right.id in highlight_path:\n rcolor = HIGHLIGHT_COLOR\n rpw = \"1.2\"\n edges.append( f'{nname} -> {left_node_name} [penwidth={lpw} color=\"{lcolor}\" label=<{llabel}>]' )\n edges.append( f'{nname} -> {right_node_name} [penwidth={rpw} color=\"{rcolor}\" label=<{rlabel}>]' )\n edges.append(f\"\"\"\n {{\n rank=same;\n {left_node_name} -> {right_node_name} [style=invis]\n }}\n \"\"\")\n\n newline = \"\\n\\t\"\n dot = f\"\"\"\ndigraph G {{\n splines=line;\n nodesep={nodesep};\n ranksep={ranksep};\n rankdir={orientation};\n margin=0.0;\n node [margin=\"0.03\" penwidth=\"0.5\" width=.1, height=.1];\n edge [arrowsize=.4 penwidth=\"0.3\"]\n \n {newline.join(internal)}\n {newline.join(edges)}\n {newline.join(leaves)}\n \n {class_legend_gr()}\n {instance_gr()}\n}}\n \"\"\"\n\n return DTreeViz(dot)\n\n\ndef class_split_viz(node: ShadowDecTreeNode,\n X_train: np.ndarray,\n y_train: np.ndarray,\n colors: Mapping[int, str],\n node_heights,\n filename: str = None,\n ticks_fontsize: int = 8,\n label_fontsize: int = 9,\n precision=1,\n histtype: ('bar', 'barstacked') = 'barstacked',\n X : np.array = None,\n highlight_node : bool = False\n ):\n height_range = (.5, 1.5)\n h = prop_size(n=node_heights[node.id], counts=node_heights.values(), output_range=height_range)\n figsize=(3.3, h)\n fig, ax = plt.subplots(1, 1, figsize=figsize)\n\n feature_name = node.feature_name()\n\n # Get X, y data for all samples associated with this node.\n X_feature = X_train[:, node.feature()]\n X_feature, y_train = X_feature[node.samples()], y_train[node.samples()]\n\n n_classes = node.shadow_tree.nclasses()\n nbins = get_num_bins(histtype, n_classes)\n overall_feature_range = (np.min(X_train[:, node.feature()]), np.max(X_train[:, node.feature()]))\n\n ax.set_xlabel(f\"{feature_name}\", fontsize=label_fontsize, fontname=\"Arial\",\n color=GREY)\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['left'].set_linewidth(.3)\n ax.spines['bottom'].set_linewidth(.3)\n\n class_names = node.shadow_tree.class_names\n\n r = overall_feature_range[1]-overall_feature_range[0]\n\n class_values = node.shadow_tree.unique_target_values\n X_hist = [X_feature[y_train == cl] for cl in class_values]\n X_colors = [colors[cl] for cl in class_values]\n binwidth = r / nbins\n\n hist, bins, barcontainers = ax.hist(X_hist,\n color=X_colors,\n align='mid',\n histtype=histtype,\n bins=np.arange(overall_feature_range[0],overall_feature_range[1] + binwidth, binwidth),\n label=class_names)\n\n ax.set_xlim(*overall_feature_range)\n ax.set_xticks(overall_feature_range)\n ax.set_yticks([0,max([max(h) for h in hist])])\n ax.tick_params(axis='both', which='major', width=.3, labelcolor=GREY, labelsize=ticks_fontsize)\n\n def wedge(ax,x,color):\n xmin, xmax = ax.get_xlim()\n ymin, ymax = ax.get_ylim()\n xr = xmax - xmin\n yr = ymax - ymin\n hr = h / (height_range[1] - height_range[0])\n th = yr * .15 * 1 / hr # convert to graph coordinates (ugh)\n tw = xr * .018\n tipy = -0.1 * yr * .15 * 1 / hr\n tria = np.array(\n [[x, tipy], [x - tw, -th], [x + tw, -th]])\n t = patches.Polygon(tria, facecolor=color)\n t.set_clip_on(False)\n ax.add_patch(t)\n ax.text(node.split(), -2 * th,\n f\"{myround(node.split(),precision)}\",\n horizontalalignment='center',\n fontsize=ticks_fontsize, color=GREY)\n\n wedge(ax, node.split(), color=WEDGE_COLOR)\n if highlight_node:\n wedge(ax, X[node.feature()], color=HIGHLIGHT_COLOR)\n\n\n # Alter appearance of each bar\n for patch in barcontainers:\n for rect in patch.patches:\n rect.set_linewidth(.5)\n rect.set_edgecolor(GREY)\n\n if filename is not None:\n plt.savefig(filename, bbox_inches='tight', pad_inches=0)\n plt.close()\n\n\ndef class_leaf_viz(node : ShadowDecTreeNode,\n colors : List[str],\n filename: str):\n size = prop_size(node.nsamples(), counts=node.shadow_tree.leaf_sample_counts(),\n output_range=(1.01, 1.5))\n # we visually need n=1 and n=9 to appear different but diff between 300 and 400 is no big deal\n size = np.sqrt(np.log(size))\n draw_piechart(node.class_counts(), size=size, colors=colors, filename=filename, label=f\"n={node.nsamples()}\")\n\n\ndef regr_split_viz(node: ShadowDecTreeNode,\n X_train: np.ndarray,\n y_train: np.ndarray,\n target_name: str,\n filename: str = None,\n y_range=None,\n ticks_fontsize: int = 8,\n label_fontsize: int = 9,\n precision=1,\n X : np.array = None,\n highlight_node : bool = False):\n figsize = (2.5, 1.1)\n fig, ax = plt.subplots(1, 1, figsize=figsize)\n ax.tick_params(colors=GREY)\n\n feature_name = node.feature_name()\n # ticklabelpad = plt.rcParams['xtick.major.pad']\n # ax.annotate(f\"{feature_name}\",\n # xy=(.5, 0), xytext=(.5, -3*ticklabelpad), ha='center', va='top',\n # xycoords='axes fraction', textcoords='offset points',\n # fontsize = label_fontsize, fontname = \"Arial\", color = GREY)\n\n ax.set_xlabel(f\"{feature_name}\", fontsize=label_fontsize, fontname=\"Arial\", color=GREY)\n\n ax.set_ylim(y_range)\n if node==node.shadow_tree.root:\n ax.set_ylabel(target_name, fontsize=label_fontsize, fontname=\"Arial\", color=GREY)\n\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['left'].set_linewidth(.3)\n ax.spines['bottom'].set_linewidth(.3)\n ax.tick_params(axis='both', which='major', width=.3, labelcolor=GREY, labelsize=ticks_fontsize)\n\n # Get X, y data for all samples associated with this node.\n X_feature = X_train[:,node.feature()]\n X_feature, y_train = X_feature[node.samples()], y_train[node.samples()]\n\n overall_feature_range = (np.min(X_train[:,node.feature()]), np.max(X_train[:,node.feature()]))\n ax.set_xlim(*overall_feature_range)\n\n xmin, xmax = overall_feature_range\n xr = xmax - xmin\n\n xticks = list(overall_feature_range)\n if node.split()>xmin+.10*xr and node.split()<xmax-.1*xr: # don't show split if too close to axis ends\n xticks += [node.split()]\n ax.set_xticks(xticks)\n\n ax.scatter(X_feature, y_train, s=5, c='#225ea8', alpha=.4)\n left, right = node.split_samples()\n left = y_train[left]\n right = y_train[right]\n split = node.split()\n ax.plot([overall_feature_range[0],split],[np.mean(left),np.mean(left)],'--', color='k', linewidth=1)\n ax.plot([split,split],[*y_range],'--', color='k', linewidth=1)\n ax.plot([split,overall_feature_range[1]],[np.mean(right),np.mean(right)],'--', color='k', linewidth=1)\n\n def wedge(ax,x,color):\n ymin, ymax = ax.get_ylim()\n xr = xmax - xmin\n yr = ymax - ymin\n hr = figsize[1]\n th = yr * .1\n tw = xr * .018\n tipy = ymin\n tria = np.array([[x, tipy], [x - tw, ymin-th], [x + tw, ymin-th]])\n t = patches.Polygon(tria, facecolor=color)\n t.set_clip_on(False)\n ax.add_patch(t)\n\n # ax.text(node.split(), 0,\n # f\"{myround(node.split(),precision)}\",\n # horizontalalignment='center',\n # fontsize=ticks_fontsize, color=GREY)\n\n wedge(ax, node.split(), color=WEDGE_COLOR)\n\n if highlight_node:\n wedge(ax, X[node.feature()], color=HIGHLIGHT_COLOR)\n\n plt.tight_layout()\n if filename is not None:\n plt.savefig(filename, bbox_inches='tight', pad_inches=0)\n plt.close()\n\n\ndef regr_leaf_viz(node : ShadowDecTreeNode,\n y : (pd.Series,np.ndarray),\n target_name,\n filename:str=None,\n y_range=None,\n precision=1,\n label_fontsize: int = 9,\n ticks_fontsize: int = 8):\n samples = node.samples()\n y = y[samples]\n\n figsize = (.75, .8)\n\n fig, ax = plt.subplots(1, 1, figsize=figsize)\n ax.tick_params(colors=GREY)\n\n m = np.mean(y)\n\n ax.set_ylim(y_range)\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['bottom'].set_visible(False)\n ax.spines['left'].set_linewidth(.3)\n ax.set_xticks([])\n # ax.set_yticks(y_range)\n\n ticklabelpad = plt.rcParams['xtick.major.pad']\n ax.annotate(f\"{target_name}={myround(m,precision)}\\nn={len(y)}\",\n xy=(.5, 0), xytext=(.5, -.5*ticklabelpad), ha='center', va='top',\n xycoords='axes fraction', textcoords='offset points',\n fontsize = label_fontsize, fontname = \"Arial\", color = GREY)\n\n ax.tick_params(axis='y', which='major', width=.3, labelcolor=GREY, labelsize=ticks_fontsize)\n\n mu = .5\n sigma = .08\n X = np.random.normal(mu, sigma, size=len(y))\n ax.set_xlim(0, 1)\n alpha = .25\n\n ax.scatter(X, y, s=5, c='#225ea8', alpha=alpha)\n ax.plot([0,len(node.samples())],[m,m],'--', color=GREY, linewidth=1)\n\n plt.tight_layout()\n if filename is not None:\n plt.savefig(filename, bbox_inches='tight', pad_inches=0)\n plt.close()\n\n\ndef draw_legend(shadow_tree, target_name, filename):\n n_classes = shadow_tree.nclasses()\n class_values = shadow_tree.unique_target_values\n class_names = shadow_tree.class_names\n color_values = color_blind_friendly_colors[n_classes]\n colors = {v:color_values[i] for i,v in enumerate(class_values)}\n\n boxes = []\n for i, c in enumerate(class_values):\n box = patches.Rectangle((0, 0), 20, 10, linewidth=.4, edgecolor=GREY,\n facecolor=colors[c], label=class_names[c])\n boxes.append(box)\n\n\n fig, ax = plt.subplots(1, 1, figsize=(1,1))\n leg = ax.legend(handles=boxes,\n frameon=True,\n shadow=False,\n fancybox=True,\n loc='center',\n title=target_name,\n handletextpad=.35,\n borderpad=.8,\n edgecolor=GREY)\n\n leg.get_frame().set_linewidth(.5)\n leg.get_title().set_color(GREY)\n leg.get_title().set_fontsize(10)\n leg.get_title().set_fontweight('bold')\n for text in leg.get_texts():\n text.set_color(GREY)\n text.set_fontsize(10)\n\n ax.set_xlim(0,20)\n ax.set_ylim(0,10)\n ax.axis('off')\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)\n\n if filename is not None:\n plt.savefig(filename, bbox_inches='tight', pad_inches=0)\n plt.close()\n\n\ndef draw_piechart(counts,size,colors,filename,label=None):\n n_nonzero = np.count_nonzero(counts)\n i = np.nonzero(counts)[0][0]\n if n_nonzero==1:\n counts = [counts[i]]\n colors = [colors[i]]\n tweak = size * .01\n fig, ax = plt.subplots(1, 1, figsize=(size, size))\n ax.axis('equal')\n # ax.set_xlim(0 - tweak, size + tweak)\n # ax.set_ylim(0 - tweak, size + tweak)\n ax.set_xlim(0, size-10*tweak)\n ax.set_ylim(0, size-10*tweak)\n # frame=True needed for some reason to fit pie properly (ugh)\n # had to tweak the crap out of this to get tight box around piechart :(\n wedges, _ = ax.pie(counts, center=(size/2-6*tweak,size/2-6*tweak), radius=size/2, colors=colors, shadow=False, frame=True)\n for w in wedges:\n w.set_linewidth(.5)\n w.set_edgecolor(GREY)\n\n ax.axis('off')\n ax.xaxis.set_visible(False)\n ax.yaxis.set_visible(False)\n\n if label is not None:\n ax.text(size/2-6*tweak, -10*tweak, label,\n horizontalalignment='center',\n verticalalignment='top',\n fontsize=9, color=GREY, fontname=\"Arial\")\n\n # plt.tight_layout()\n plt.savefig(filename, bbox_inches='tight', pad_inches=0)\n plt.close()\n\n\ndef prop_size(n, counts, output_range = (0.00, 0.3)):\n min_samples = min(counts)\n max_samples = max(counts)\n sample_count_range = max_samples - min_samples\n\n\n if sample_count_range>0:\n zero_to_one = (n - min_samples) / sample_count_range\n return zero_to_one * (output_range[1] - output_range[0]) + output_range[0]\n else:\n return output_range[0]\n\n\ndef get_num_bins(histtype, n_classes):\n bins = NUM_BINS[n_classes]\n if histtype == 'barstacked':\n bins *= 2\n return bins\n" ]
[ [ "numpy.log", "matplotlib.pyplot.tight_layout", "numpy.nonzero", "numpy.arange", "matplotlib.patches.Rectangle", "matplotlib.pyplot.subplots", "matplotlib.pyplot.savefig", "numpy.mean", "numpy.count_nonzero", "matplotlib.pyplot.close", "numpy.array", "matplotlib.patches.Polygon" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dkogan/mrcal
[ "ca4678e1171841fd9cd158b87ee460163647b495" ]
[ "mrcal/stereo.py" ]
[ "#!/usr/bin/python3\n\n'''Routines for stereo processing: rectification and ranging\n\nAll functions are exported into the mrcal module. So you can call these via\nmrcal.stereo.fff() or mrcal.fff(). The latter is preferred.\n'''\n\nimport sys\nimport numpy as np\nimport numpysane as nps\nimport mrcal\n\ndef rectified_system(models,\n az_fov_deg,\n el_fov_deg,\n az0_deg = None,\n el0_deg = 0,\n pixels_per_deg_az = -1.,\n pixels_per_deg_el = -1.,\n rectification_model = 'LENSMODEL_LATLON'):\n\n r'''Build rectified models for stereo rectification\n\nSYNOPSIS\n\n import sys\n import mrcal\n import cv2\n import numpy as np\n import numpysane as nps\n\n models = [ mrcal.cameramodel(f) \\\n for f in ('left.cameramodel',\n 'right.cameramodel') ]\n\n images = [ cv2.imread(f) \\\n for f in ('left.jpg', 'right.jpg') ]\n\n models_rectified = \\\n mrcal.rectified_system(models,\n az_fov_deg = 120,\n el_fov_deg = 100)\n\n rectification_maps = mrcal.rectification_maps(models, models_rectified)\n\n images_rectified = [ mrcal.transform_image(images[i], rectification_maps[i]) \\\n for i in range(2) ]\n\n # Find stereo correspondences using OpenCV\n block_size = 3\n max_disp = 160 # in pixels\n matcher = \\\n cv2.StereoSGBM_create(minDisparity = 0,\n numDisparities = max_disp,\n blockSize = block_size,\n P1 = 8 *3*block_size*block_size,\n P2 = 32*3*block_size*block_size,\n uniquenessRatio = 5,\n\n disp12MaxDiff = 1,\n speckleWindowSize = 50,\n speckleRange = 1)\n disparity16 = matcher.compute(*images_rectified) # in pixels*16\n\n # Convert the disparities to range-to-camera0\n ranges = mrcal.stereo_range( disparity16,\n models_rectified,\n disparity_scale = 16 )\n\n H,W = disparity16.shape\n\n # shape (H,W,2)\n q = np.ascontiguousarray( \\\n nps.mv( nps.cat( *np.meshgrid(np.arange(W,dtype=float),\n np.arange(H,dtype=float))),\n 0, -1))\n\n # Point cloud in rectified camera-0 coordinates\n # shape (H,W,3)\n p_rect0 = \\\n mrcal.unproject_latlon(q, models_rectified[0].intrinsics()[1]) * \\\n nps.dummy(ranges, axis=-1)\n\n Rt_cam0_rect0 = mrcal.compose_Rt( models [0].extrinsics_Rt_fromref(),\n models_rectified[0].extrinsics_Rt_toref() )\n\n # Point cloud in camera-0 coordinates\n # shape (H,W,3)\n p_cam0 = mrcal.transform_point_Rt(Rt_cam0_rect0, p_rect0)\n\nThis function computes the parameters of a rectified system from two\ncameramodels in a stereo pair. The output is a pair of \"rectified\" models. Each\nof these is a normal mrcal.cameramodel object describing a \"camera\" somewhere in\nspace, with some particular projection behavior. The pair of models returned\nhere have the desired property that each row of pixels represents a plane in\nspace AND each corresponding row in the pair of rectified images represents the\nSAME plane: the epipolar lines are aligned. We can use the rectified models\nreturned by this function to transform the input images into \"rectified\" images,\nand then we can perform stereo matching efficiently, by treating each row\nindependently.\n\nThis function is generic: the two input cameras may use any lens models, any\nresolution and any geometry. They don't even have to match. As long as there's\nsome non-zero baseline and some overlapping views, we can run stereo processing.\n\nThe two rectified models describe the poses of the rectified cameras. Each\nrectified camera sits at the same position as the input camera, but with a\ndifferent orientation. The orientations of the two cameras in the rectified\nsystem are identical. The only difference between the poses of the two rectified\ncameras is a translation of the second camera along the x axis. The axes of the\nrectified coordinate system:\n\n- x: from the origin of the first camera to the origin of the second camera (the\n baseline direction)\n\n- y: completes the system from x,z\n\n- z: the mean \"forward\" direction of the two input cameras, with the component\n parallel to the baseline subtracted off\n\nIn a nominal geometry (the two cameras are square with each other, the second\ncamera strictly to the right of the first camera), the geometry of the rectified\nmodels exactly matches the geometry of the input models. The above formulation\nsupports any geometry, however, including vertical and/or forward/backward\nshifts. Vertical stereo is supported: we still run stereo matching on ROWS of\nthe rectified images, but the rectification transformation will rotate the\nimages by 90 degrees.\n\nSeveral projection functions may be used in the rectified system. These are\nselectable using the \"rectification_model\" keyword argument; they're a string\nrepresenting the lensmodel that will be used in the cameramodel objects we\nreturn. Two projections are currently supported:\n\n- \"LENSMODEL_LATLON\": the default projection that utilizes a transverse\n equirectangular map. This projection has even angular spacing between pixels,\n so it works well even with wide lenses. The documentation has more information:\n http://mrcal.secretsauce.net/lensmodels.html#lensmodel-latlon\n\n- \"LENSMODEL_PINHOLE\": the traditional projection function that utilizes a\n pinhole camera. This works badly with wide lenses, and is recommended if\n compatibility with other stereo processes is desired\n\nARGUMENTS\n\n- models: an iterable of two mrcal.cameramodel objects representing the cameras\n in the stereo pair. Any sane combination of lens models and resolutions and\n geometries is valid\n\n- az_fov_deg: required value for the azimuth (along-the-baseline) field-of-view\n of the desired rectified system, in degrees\n\n- el_fov_deg: required value for the elevation (across-the-baseline)\n field-of-view of the desired rectified system, in degrees. Note that this\n applies at the center of the rectified system: az = 0. With a skewed stereo\n system (if we have a forward/backward shift or if a nonzero az0_deg is given),\n this rectification center will not be at the horizontal center of the image,\n and may not be in-bounds of the image at all.\n\n- az0_deg: optional value for the azimuth center of the rectified images. This\n is especially significant in a camera system with some forward/backward shift.\n That causes the baseline to no longer be perpendicular with the view axis of\n the cameras, and thus the azimuth=0 vector no longer points \"forward\". If\n omitted, we compute az0_deg to align the center of the rectified system with\n the center of the two cameras' views\n\n- el0_deg: optional value for the elevation center of the rectified system.\n Defaults to 0.\n\n- pixels_per_deg_az: optional value for the azimuth resolution of the rectified\n image. If a resultion of >0 is requested, the value is used as is. If a\n resolution of <0 is requested, we use this as a scale factor on the resolution\n of the input image. For instance, to downsample by a factor of 2, pass\n pixels_per_deg_az = -0.5. By default, we use -1: the resolution of the input\n image at the center of the rectified system.\n\n- pixels_per_deg_el: same as pixels_per_deg_az but in the elevation direction\n\n- rectification_model: optional string that selects the projection function to\n use in the resulting rectified system. This is a string selecting the mrcal\n lens model. Currently supported are \"LENSMODEL_LATLON\" (the default) and\n \"LENSMODEL_PINHOLE\"\n\nRETURNED VALUES\n\nWe return a tuple of mrcal.cameramodels describing the two rectified cameras.\nThese two models are identical, except for a baseline translation in the +x\ndirection in rectified coordinates.\n\n '''\n\n if not (rectification_model == 'LENSMODEL_LATLON' or \\\n rectification_model == 'LENSMODEL_PINHOLE'):\n raise(f\"Unsupported rectification model '{rectification_model}'. Only LENSMODEL_LATLON and LENSMODEL_PINHOLE are supported.\")\n\n if len(models) != 2:\n raise Exception(\"I need exactly 2 camera models\")\n\n if pixels_per_deg_az == 0:\n raise Exception(\"pixels_per_deg_az == 0 is illegal. Must be >0 if we're trying to specify a value, or <0 to autodetect\")\n if pixels_per_deg_el == 0:\n raise Exception(\"pixels_per_deg_el == 0 is illegal. Must be >0 if we're trying to specify a value, or <0 to autodetect\")\n\n if az_fov_deg is None or el_fov_deg is None or \\\n az_fov_deg <= 0. or el_fov_deg <= 0.:\n raise Exception(\"az_fov_deg, el_fov_deg must be > 0. No auto-detection implemented yet\")\n\n ######## Compute the geometry of the rectified stereo system. This is a\n ######## rotation, centered at camera0. More or less we have axes:\n ########\n ######## x: from camera0 to camera1\n ######## y: completes the system from x,z\n ######## z: component of the cameras' viewing direction\n ######## normal to the baseline\n Rt01 = mrcal.compose_Rt( models[0].extrinsics_Rt_fromref(),\n models[1].extrinsics_Rt_toref())\n\n # Rotation relating camera0 coords to the rectified camera coords. I fill in\n # each row separately\n R_rect0_cam0 = np.zeros((3,3), dtype=float)\n\n # Axes of the rectified system, in the cam0 coord system\n right = R_rect0_cam0[0,:]\n down = R_rect0_cam0[1,:]\n forward = R_rect0_cam0[2,:]\n\n # \"right\" of the rectified coord system: towards the origin of camera1 from\n # camera0, in camera0 coords\n right += Rt01[3,:]\n baseline = nps.mag(right)\n right /= baseline\n\n # \"forward\" for each of the two cameras, in the cam0 coord system\n forward0 = np.array((0,0,1.))\n forward1 = Rt01[:3,2]\n\n # \"forward\" of the rectified coord system, in camera0 coords. The mean\n # optical-axis direction of the two cameras: component orthogonal to \"right\"\n forward01 = forward0 + forward1\n forward01_proj_right = nps.inner(forward01,right)\n forward += forward01 - forward01_proj_right*right\n forward /= nps.mag(forward)\n\n # \"down\" of the rectified coord system, in camera0 coords. Completes the\n # right,down,forward coordinate system\n down[:] = np.cross(forward,right)\n\n # All components of R_rect0_cam0 are now filled in\n\n R_cam0_rect0 = nps.transpose(R_rect0_cam0)\n\n # rect1 coord system has the same orientation as rect0, but is translated so\n # that its origin is at the origin of cam1\n R_rect1_cam0 = R_rect0_cam0\n R_rect1_cam1 = nps.matmult(R_rect1_cam0, Rt01[:3,:])\n\n ######## Done with the geometry! Now to get the az/el grid. I need to figure\n ######## out the resolution and the extents\n\n if az0_deg is not None:\n az0 = az0_deg * np.pi/180.\n\n else:\n # In the rectified system az=0 sits perpendicular to the baseline.\n # Normally the cameras are looking out perpendicular to the baseline\n # also, so I center my azimuth samples around 0 to match the cameras'\n # field of view. But what if the geometry isn't square, and one camera\n # is behind the other? Like this:\n #\n # camera\n # view\n # ^\n # |\n # \\ | /\n # \\_/\n # . /\n # . /az=0\n # ./\n # .\n # baseline .\n # .\n # \\ /\n # \\_/\n #\n # Here the center-of-view axis of each camera is not at all\n # perpendicular to the baseline. Thus I compute the mean \"forward\"\n # direction of the cameras in the rectified system, and set that as the\n # center azimuth az0.\n az0 = np.arcsin( forward01_proj_right / nps.mag(forward01) )\n\n el0 = el0_deg * np.pi/180.\n\n cos_az0 = np.cos(az0)\n cos_el0 = np.cos(el0)\n\n ####### Rectified image resolution\n if pixels_per_deg_az < 0 or \\\n pixels_per_deg_el < 0:\n # I need to compute the resolution of the rectified images. I try to\n # match the resolution of the cameras. I just look at camera0. If your\n # two cameras are different, pass in the pixels_per_deg yourself\n #\n # I look at the center of the stereo field of view. There I have q =\n # project(v) where v is a unit projection vector. I compute dq/dth where\n # th is an angular perturbation applied to v.\n\n if rectification_model == 'LENSMODEL_LATLON':\n q0_normalized = np.array((az0,el0))\n v,dv_dazel = \\\n mrcal.unproject_latlon( q0_normalized,\n get_gradients = True )\n else:\n q0_normalized = np.array((np.tan(az0),np.tan(el0)))\n v,dv_dq0normalized = \\\n mrcal.unproject_pinhole( q0_normalized,\n get_gradients = True )\n # dq/dth = dtanth/dth = 1/cos^2(th)\n dv_dazel = dv_dq0normalized\n dv_dazel[:,0] /= cos_az0*cos_az0\n dv_dazel[:,1] /= cos_el0*cos_el0\n\n v0 = mrcal.rotate_point_R(R_cam0_rect0, v)\n dv0_dazel = nps.matmult(R_cam0_rect0, dv_dazel)\n\n _,dq_dv0,_ = mrcal.project(v0, *models[0].intrinsics(), get_gradients = True)\n\n # More complex method that's probably not any better\n #\n # if False:\n # # I rotate my v to a coordinate system where u = rotate(v) is [0,0,1].\n # # Then u = [a,b,0] are all orthogonal to v. So du/dth = [cos, sin, 0].\n # # I then have dq/dth = dq/dv dv/du [cos, sin, 0]t\n # # ---> dq/dth = dq/dv dv/du[:,:2] [cos, sin]t = M [cos,sin]t\n # #\n # # norm2(dq/dth) = [cos,sin] MtM [cos,sin]t is then an ellipse with the\n # # eigenvalues of MtM giving me the best and worst sensitivities. I can\n # # use mrcal.worst_direction_stdev() to find the densest direction. But I\n # # actually know the directions I care about, so I evaluate them\n # # independently for the az and el directions\n # def rotation_any_v_to_z(v):\n # r'''Return any rotation matrix that maps the given unit vector v to [0,0,1]'''\n # z = v\n # if np.abs(v[0]) < .9:\n # x = np.array((1,0,0))\n # else:\n # x = np.array((0,1,0))\n # x -= nps.inner(x,v)*v\n # x /= nps.mag(x)\n # y = np.cross(z,x)\n # return nps.cat(x,y,z)\n # Ruv = rotation_any_v_to_z(v0)\n # M = nps.matmult(dq_dv0, nps.transpose(Ruv[:2,:]))\n # # I pick the densest direction: highest |dq/dth|\n # pixels_per_rad = mrcal.worst_direction_stdev( nps.matmult( nps.transpose(M),M) )\n\n dq_dazel = nps.matmult(dq_dv0, dv0_dazel)\n\n if pixels_per_deg_az < 0:\n pixels_per_deg_az_have = nps.mag(dq_dazel[:,0])*np.pi/180.\n pixels_per_deg_az = -pixels_per_deg_az * pixels_per_deg_az_have\n\n if pixels_per_deg_el < 0:\n pixels_per_deg_el_have = nps.mag(dq_dazel[:,1])*np.pi/180.\n pixels_per_deg_el = -pixels_per_deg_el * pixels_per_deg_el_have\n\n # How do we apply the desired pixels_per_deg?\n #\n # With LENSMODEL_LATLON we have even angular spacing, so q = f th + c ->\n # dq/dth = f everywhere.\n #\n # With LENSMODEL_PINHOLE the angular resolution changes across the image: q\n # = f tan(th) + c -> dq/dth = f/cos^2(th). So at the center, th=0 and we\n # have the maximum resolution\n fxycxy = np.array((pixels_per_deg_az / np.pi*180.,\n pixels_per_deg_el / np.pi*180.,\n 0., 0.), dtype=float)\n if rectification_model == 'LENSMODEL_LATLON':\n # The angular resolution is consistent everywhere, so fx,fy are already\n # set. Let's set cx,cy such that\n # (az0,el0) = unproject(imager center)\n Naz = round(az_fov_deg*pixels_per_deg_az)\n Nel = round(el_fov_deg*pixels_per_deg_el)\n v = mrcal.unproject_latlon( np.array((az0,el0)) )\n fxycxy[2:] = \\\n np.array(((Naz-1.)/2.,(Nel-1.)/2.)) - \\\n mrcal.project_latlon( v, fxycxy )\n\n elif rectification_model == 'LENSMODEL_PINHOLE':\n fxycxy[0] *= cos_az0*cos_az0\n fxycxy[1] *= cos_el0*cos_el0\n\n # fx,fy are set. Let's set cx,cy. Unlike the LENSMODEL_LATLON case, this\n # is asymmetric, so I explicitly solve for (cx,Naz). cy,Nel work the\n # same way. I want\n #\n # tan(az0)*fx + cx = (Naz-1)/2\n #\n # inner( normalized(unproject(x=0)),\n # normalized(unproject(x=Naz-1)) ) = cos(fov)\n #\n # unproject(x=0 ) = [ (0 - cx)/fx, 0, 1]\n # unproject(x=Naz-1) = [ (Naz-1 - cx)/fx, 0, 1]\n #\n # -> v0 ~ [ -cx/fx, 0, 1]\n # -> v1 ~ [ 2*tanaz0 + cx/fx, 0, 1]\n #\n # Let K = 2*tanaz0 (we have K). Let C = cx/fx (we want to find C)\n # -> v0 ~ [-C,1], v1 ~ [K+C,1]\n # -> cosfov = (1 - K*C - C^2) / sqrt( (1+C^2)*(1+C^2+K^2+2*K*C))\n # -> cos2fov*(1+C^2)*(1+C^2+K^2+2*K*C) - (1 - K*C - C^2)^2 = 0\n # -> 0 =\n # C^4 * (cos2fov - 1) +\n # C^3 * 2 K (cos2fov - 1 ) +\n # C^2 * (cos2fov K^2 + 2 cos2fov - K^2 + 2) +\n # C * 2 K ( cos2fov + 1 ) +\n # cos2fov ( K^2 + 1 ) - 1\n #\n # I can solve this numerically\n def cxy(fxy, tanazel0, fov_deg):\n cosfov = np.cos(fov_deg*np.pi/180.)\n cos2fov = cosfov*cosfov\n K = 2.*tanazel0\n\n C = np.roots( [ (cos2fov - 1),\n 2.* K * (cos2fov - 1 ),\n cos2fov * K*K + 2.*cos2fov - K*K + 2,\n 2.* K * (cos2fov + 1 ),\n cos2fov * (K*K + 1.) - 1 ] )\n\n # Some numerical fuzz (if fov ~ 90deg) may give me slightly\n # imaginary numbers, so I just look at the real component.\n # Similarly, I allow a bit of numerical fuzz in the logic below\n C = np.real(C)\n\n # I solve my quadratic polynomial numerically. I get 4 solutions,\n # and I need to throw out the invalid ones.\n #\n # fov may be > 90deg, so cos(fov) may be <0. The solution will make\n # sure that cos^2(fov) matches up, but the solution may assume the\n # wrong sign for cos(fov). From above:\n #\n # cosfov = (1 - K*C - C^2) / sqrt( (1+C^2)*(1+C^2+K^2+2*K*C))\n #\n # So I must have cosfov*(1 - K*C - C^2) > 0\n C = C[cosfov*(1 - K*C - C*C) >= -1e-9]\n\n # And the implied imager size MUST be positive\n C = C[(tanazel0*fxy + C*fxy)*2. + 1 > 0]\n\n if len(C) == 0:\n raise Exception(\"Couldn't compute the rectified pinhole center pixel. Something is wrong.\")\n\n # I should have exactly one solution let. Due to some numerical\n # fuzz, I might have more, and I pick the most positive one in the\n # condition above\n return C[np.argmax(cosfov*(1 - K*C - C*C))] * fxy\n\n\n\n tanaz0 = np.tan(az0)\n tanel0 = np.tan(el0)\n fxycxy[2] = cxy(fxycxy[0], tanaz0, az_fov_deg)\n fxycxy[3] = cxy(fxycxy[1], tanel0, el_fov_deg)\n\n Naz = round((tanaz0*fxycxy[0] + fxycxy[2])*2.) + 1\n Nel = round((tanel0*fxycxy[1] + fxycxy[3])*2.) + 1\n\n else:\n raise Exception(\"Shouldn't get here; This case was checked above\")\n\n ######## The geometry\n Rt_rect0_cam0 = nps.glue(R_rect0_cam0, np.zeros((3,),), axis=-2)\n Rt_rect0_ref = mrcal.compose_Rt( Rt_rect0_cam0,\n models[0].extrinsics_Rt_fromref())\n # rect1 coord system has the same orientation as rect0, but is translated so\n # that its origin is at the origin of cam1\n Rt_rect1_cam1 = nps.glue(R_rect1_cam1, np.zeros((3,),), axis=-2)\n Rt_rect1_ref = mrcal.compose_Rt( Rt_rect1_cam1,\n models[1].extrinsics_Rt_fromref())\n\n models_rectified = \\\n ( mrcal.cameramodel( intrinsics = (rectification_model, fxycxy),\n imagersize = (Naz, Nel),\n extrinsics_Rt_fromref = Rt_rect0_ref),\n\n mrcal.cameramodel( intrinsics = (rectification_model, fxycxy),\n imagersize = (Naz, Nel),\n extrinsics_Rt_fromref = Rt_rect1_ref) )\n\n return models_rectified\n\n\ndef _validate_models_rectified(models_rectified):\n r'''Internal function to validate a rectified system\n\nThese should have been returned by rectified_system(). Should have two\nLENSMODEL_LATLON or LENSMODEL_PINHOLE cameras with identical intrinsics.\nextrinsics should be identical too EXCEPT for a baseline translation in the x\nrectified direction\n\n '''\n\n if len(models_rectified) != 2:\n raise Exception(f\"Must have received exactly two models. Got {len(models_rectified)} instead\")\n\n intrinsics = [m.intrinsics() for m in models_rectified]\n Rt01 = mrcal.compose_Rt( models_rectified[0].extrinsics_Rt_fromref(),\n models_rectified[1].extrinsics_Rt_toref())\n\n if not ( (intrinsics[0][0] == 'LENSMODEL_LATLON' and intrinsics[1][0] == 'LENSMODEL_LATLON' ) or \\\n (intrinsics[0][0] == 'LENSMODEL_PINHOLE' and intrinsics[1][0] == 'LENSMODEL_PINHOLE') ):\n raise Exception(f\"Expected two models with the same 'LENSMODEL_LATLON' or 'LENSMODEL_PINHOLE' but got {intrinsics[0][0]} and {intrinsics[1][0]}\")\n\n if nps.norm2(intrinsics[0][1] - intrinsics[1][1]) > 1e-6:\n raise Exception(\"The two rectified models MUST have the same intrinsics values\")\n\n imagersize_diff = \\\n np.array(models_rectified[0].imagersize()) - \\\n np.array(models_rectified[1].imagersize())\n if imagersize_diff[0] != 0 or imagersize_diff[1] != 0:\n raise Exceptions(\"The two rectified models MUST have the same imager size\")\n\n costh = (np.trace(Rt01[:3,:]) - 1.) / 2.\n if costh < 0.999999:\n raise Exception(\"The two rectified models MUST have the same relative rotation\")\n\n if nps.norm2(Rt01[3,1:]) > 1e-9:\n raise Exception(\"The two rectified models MUST have a translation ONLY in the +x rectified direction\")\n\n\ndef rectification_maps(models,\n models_rectified):\n\n r'''Construct image transformation maps to make rectified images\n\nSYNOPSIS\n\n import sys\n import mrcal\n import cv2\n import numpy as np\n import numpysane as nps\n\n models = [ mrcal.cameramodel(f) \\\n for f in ('left.cameramodel',\n 'right.cameramodel') ]\n\n images = [ cv2.imread(f) \\\n for f in ('left.jpg', 'right.jpg') ]\n\n models_rectified = \\\n mrcal.rectified_system(models,\n az_fov_deg = 120,\n el_fov_deg = 100)\n\n rectification_maps = mrcal.rectification_maps(models, models_rectified)\n\n images_rectified = [ mrcal.transform_image(images[i], rectification_maps[i]) \\\n for i in range(2) ]\n\n # Find stereo correspondences using OpenCV\n block_size = 3\n max_disp = 160 # in pixels\n matcher = \\\n cv2.StereoSGBM_create(minDisparity = 0,\n numDisparities = max_disp,\n blockSize = block_size,\n P1 = 8 *3*block_size*block_size,\n P2 = 32*3*block_size*block_size,\n uniquenessRatio = 5,\n\n disp12MaxDiff = 1,\n speckleWindowSize = 50,\n speckleRange = 1)\n disparity16 = matcher.compute(*images_rectified) # in pixels*16\n\n # Convert the disparities to range-to-camera0\n ranges = mrcal.stereo_range( disparity16,\n models_rectified,\n disparity_scale = 16 )\n\n H,W = disparity16.shape\n\n # shape (H,W,2)\n q = np.ascontiguousarray( \\\n nps.mv( nps.cat( *np.meshgrid(np.arange(W,dtype=float),\n np.arange(H,dtype=float))),\n 0, -1))\n\n # Point cloud in rectified camera-0 coordinates\n # shape (H,W,3)\n p_rect0 = \\\n mrcal.unproject_latlon(q, models_rectified[0].intrinsics()[1]) * \\\n nps.dummy(ranges, axis=-1)\n\n Rt_cam0_rect0 = mrcal.compose_Rt( models[0].extrinsics_Rt_fromref(),\n models_rectified[0].extrinsics_Rt_toref() )\n\n # Point cloud in camera-0 coordinates\n # shape (H,W,3)\n p_cam0 = mrcal.transform_point_Rt(Rt_cam0_rect0, p_rect0)\n\nAfter the pair of rectified models has been built by mrcal.rectified_system(),\nthis function can be called to compute the rectification maps. These can be\npassed to mrcal.transform_image() to remap input images into the rectified\nspace.\n\nThe documentation for mrcal.rectified_system() applies here.\n\nARGUMENTS\n\n- models: an iterable of two mrcal.cameramodel objects representing the cameras\n in the stereo pair\n\n- models_rectified: the pair of rectified models, corresponding to the input\n images. Usually this is returned by mrcal.rectified_system()\n\nRETURNED VALUES\n\nWe return a length-2 tuple of numpy arrays containing transformation maps for\neach camera. Each map can be used to mrcal.transform_image() images into\nrectified space. Each array contains 32-bit floats (as expected by\nmrcal.transform_image() and cv2.remap()). Each array has shape (Nel,Naz,2),\nwhere (Nel,Naz) is the shape of each rectified image. Each shape-(2,) row\ncontains corresponding pixel coordinates in the input image\n\n '''\n\n _validate_models_rectified(models_rectified)\n\n Naz,Nel = models_rectified[0].imagersize()\n fxycxy = models_rectified[0].intrinsics()[1]\n\n R_cam_rect = [ nps.matmult(models [i].extrinsics_Rt_fromref()[:3,:],\n models_rectified[i].extrinsics_Rt_toref ()[:3,:]) \\\n for i in range(2) ]\n\n # This is massively inefficient. I should\n #\n # - Not generate any intermediate ARRAYS, but loop through each pixel, and\n # perform the full transformation on each pixel. All the way through the\n # project(v0, ...) below\n #\n # - Not compute full sin/cos separately for each pixel, but take advantage\n # of my even angle steps to compute the sin/cos once, and take\n # multiplication/addition steps from there\n\n # shape (Nel,Naz,3)\n if models_rectified[0].intrinsics()[0] == 'LENSMODEL_LATLON':\n unproject = mrcal.unproject_latlon\n else:\n unproject = mrcal.unproject_pinhole\n\n v = unproject( np.ascontiguousarray( \\\n nps.mv( nps.cat( *np.meshgrid(np.arange(Naz,dtype=float),\n np.arange(Nel,dtype=float))),\n 0, -1)),\n fxycxy)\n\n v0 = mrcal.rotate_point_R(R_cam_rect[0], v)\n v1 = mrcal.rotate_point_R(R_cam_rect[1], v)\n\n return \\\n (mrcal.project( v0, *models[0].intrinsics()).astype(np.float32), \\\n mrcal.project( v1, *models[1].intrinsics()).astype(np.float32))\n\n\ndef stereo_range(disparity,\n models_rectified,\n disparity_scale = 1,\n qrect0 = None):\n\n r'''Compute ranges from observed disparities\n\nSYNOPSIS\n\n import sys\n import mrcal\n import cv2\n import numpy as np\n import numpysane as nps\n\n models = [ mrcal.cameramodel(f) \\\n for f in ('left.cameramodel',\n 'right.cameramodel') ]\n\n images = [ cv2.imread(f) \\\n for f in ('left.jpg', 'right.jpg') ]\n\n models_rectified = \\\n mrcal.rectified_system(models,\n az_fov_deg = 120,\n el_fov_deg = 100)\n\n rectification_maps = mrcal.rectification_maps(models, models_rectified)\n\n images_rectified = [ mrcal.transform_image(images[i], rectification_maps[i]) \\\n for i in range(2) ]\n\n # Find stereo correspondences using OpenCV\n block_size = 3\n max_disp = 160 # in pixels\n matcher = \\\n cv2.StereoSGBM_create(minDisparity = 0,\n numDisparities = max_disp,\n blockSize = block_size,\n P1 = 8 *3*block_size*block_size,\n P2 = 32*3*block_size*block_size,\n uniquenessRatio = 5,\n\n disp12MaxDiff = 1,\n speckleWindowSize = 50,\n speckleRange = 1)\n disparity16 = matcher.compute(*images_rectified) # in pixels*16\n\n # Convert the disparities to range-to-camera0\n ranges = mrcal.stereo_range( disparity16,\n models_rectified,\n disparity_scale = 16 )\n\n H,W = disparity16.shape\n\n # shape (H,W,2)\n q = np.ascontiguousarray( \\\n nps.mv( nps.cat( *np.meshgrid(np.arange(W,dtype=float),\n np.arange(H,dtype=float))),\n 0, -1))\n\n # Point cloud in rectified camera-0 coordinates\n # shape (H,W,3)\n p_rect0 = \\\n mrcal.unproject_latlon(q, models_rectified[0].intrinsics()[1]) * \\\n nps.dummy(ranges, axis=-1)\n\n Rt_cam0_rect0 = mrcal.compose_Rt( models[0].extrinsics_Rt_fromref(),\n models_rectified[0].extrinsics_Rt_toref() )\n\n # Point cloud in camera-0 coordinates\n # shape (H,W,3)\n p_cam0 = mrcal.transform_point_Rt(Rt_cam0_rect0, p_rect0)\n\nAs shown in the example above, we can perform stereo processing by building\nrectified models and transformation maps, rectifying our images, and then doing\nstereo matching to get pixel disparities. This function performs the last step:\nconverting pixel disparities to ranges.\n\nIn the most common usage we take a full disparity IMAGE, and then convert it to\na range IMAGE. In this common case we call\n\n range_image = mrcal.stereo_range(disparity_image, models_rectified)\n\nIf we aren't processing the full disparity image, we can pass in an array of\nrectified pixel coordinates (in the first rectified camera) in the \"qrect0\"\nargument. These must be broadcastable with the disparity argument. So we\ncan pass in a scalar for disparity and a single (2,) array for qrect0. Or\nwe can pass in full arrays for both. Or we can pass in a shape (H,W) image for\ndisparity, but only a shape (W,2) array for qrect0: this would use the\nsame qrect0 value for a whole column of disparity, as dictated by the\nbroadcasting rules. Such identical-az-in-a-column behavior is valid for\nLENSMODEL_LATLON stereo, but not for LENSMODEL_PINHOLE stereo. It's the user's\nresponsibility to know when to omit data like this. When in doubt, pass a\nseparate qrect0 for each disparity value.\n\nEach epipolar plane looks like this:\n\ncamera0\n+ . . . .\n\\ az0\n|----------------\n| \\--------------------\n| range \\-----------------------\n| \\-------- p\n| a -----/\n| -----/\n| -----/\n|baseline -----/\n| -----/\n| -----/\n| -----/\n| -----/\n| -----/\n| -----/\n| -----/\n---/ az1\n+. . . . .\ncamera1\n\nThe cameras are at the top-left and bottom-left of the figure, looking out to\nthe right at a point p in space. The observation ray from camera0 makes an angle\naz0 with the \"forward\" direction (here az0 > 0), while the observation ray from\ncamera1 makes an angle az1 (here az1 < 0). A LENSMODEL_LATLON disparity is a\ndifference of azimuth angles: disparity ~ az0-az1. A LENSMODEL_PINHOLE disparity\nis a scaled difference of tangents: disparity ~ tan(az0)-tan(az1)\n\nThe law of sines tells us that\n\n baseline / sin(a) = range / sin(90 + az1)\n\nThus\n\n range = baseline cos(az1) / sin(a) =\n = baseline cos(az1) / sin( 180 - (90-az0 + 90+az1) ) =\n = baseline cos(az1) / sin(az0-az1) =\n = baseline cos(az0 - az0-az1) / sin(az0-az1)\n\naz0-az1 is the angular disparity. If using LENSMODEL_LATLON, this is what we\nhave, and this is a usable expression. Otherwise we keep going:\n\n range = baseline cos(az0 - az0-az1) / sin(az0-az1)\n = baseline (cos(az0)cos(az0-az1) + sin(az0)sin(az0-az1)) / sin(az0-az1)\n = baseline cos(az0)/tan(az0-az1) + sin(az0)\n = baseline cos(az0)* (1 + tan(az0)tan(az1))/(tan(az0) - tan(az1)) + sin(az0)\n = baseline cos(az0)*((1 + tan(az0)tan(az1))/(tan(az0) - tan(az1)) + tan(az0))\n\nA scaled tan(az0)-tan(az1) is the disparity when using LENSMODEL_PINHOLE, so\nthis is the final expression we use.\n\nWhen using LENSMODEL_LATLON, the azimuth values in the projection ARE the\nazimuth values inside each epipolar plane, so there's nothing extra to do. When\nusing LENSMODEL_PINHOLE however, there's an extra step. We need to convert pixel\ndisparity values to az0 and az1.\n\nLet's say we're looking two rectified pinhole points on the same epipolar plane,\na \"forward\" point and a \"query\" point:\n\n q0 = [0, qy] and q1 = [qx1, qy]\n\nWe convert these to normalized coords: tanxy = (q-cxy)/fxy\n\n t0 = [0, ty] and t1 = [tx1, ty]\n\nThese unproject to\n\n v0 = [0, ty, 1] and v1 = [tx1, ty, 1]\n\nThese lie on an epipolar plane with normal [0, -1, ty]. I define a coordinate\nsystem basis using the normal as one axis. The other two axes are\n\n b0 = [1, 0, 0 ]\n b1 = [0, ty/L, 1/L]\n\nwhere L = sqrt(ty^2 + 1)\n\nProjecting my two vectors to (b0,b1) I get\n\n [0, ty^2/L + 1/L]\n [tx1, ty^2/L + 1/L]\n\nThus the the angle this query point makes with the \"forward\" vector is\n\n tan(az_in_epipolar_plane) = tx1 / ( (ty^2 + 1)/L ) = tx1 / sqrt(ty^2 + 1)\n\nThus to get tan(az) expressions we use to compute ranges, we need to scale our\n(qx1-cx)/fx values by 1./sqrt(ty^2 + 1). This is one reason to use\nLENSMODEL_LATLON for stereo processing instead of LENSMODEL_PINHOLE: the az\nangular scale stays constant across different el, which produces better stereo\nmatches.\n\nARGUMENTS\n\n- disparity: a numpy array of disparities being processed. If disparity_scale is\n omitted, this array contains floating-point disparity values in PIXELS. Many\n stereo-matching algorithms produce integer disparities, in units of some\n constant number of pixels (the OpenCV StereoSGBM and StereoBM routines use\n 16). In this common case, you can pass the integer scaled disparities here,\n with the scale factor in disparity_scale. Any array shape is supported. In the\n common case of a disparity IMAGE, this is an array of shape (Nel, Naz)\n\n- models_rectified: the pair of rectified models, corresponding to the input\n images. Usually this is returned by mrcal.rectified_system()\n\n- disparity_scale: optional scale factor for the \"disparity\" array. If omitted,\n the \"disparity\" array is assumed to contain the disparities, in pixels.\n Otherwise it contains data in the units of 1/disparity_scale pixels.\n\n- qrect0: optional array of rectified camera0 pixel coordinates corresponding to\n the given disparities. By default, a full disparity image is assumed.\n Otherwise we use the given rectified coordinates. The shape of this array must\n be broadcasting-compatible with the disparity array. See the\n description above.\n\nRETURNED VALUES\n\n- An array of ranges of the same dimensionality as the input disparity\n array. Contains floating-point data. Invalid or missing ranges are represented\n as 0.\n\n '''\n\n _validate_models_rectified(models_rectified)\n\n # I want to support scalar disparities. If one is given, I convert it into\n # an array of shape (1,), and then pull it out at the end\n is_scalar = False\n try:\n s = disparity.shape\n except:\n is_scalar = True\n if not is_scalar:\n if len(s) == 0:\n is_scalar = True\n if is_scalar:\n disparity = np.array((disparity,),)\n\n W,H = models_rectified[0].imagersize()\n if qrect0 is None and disparity.shape != (H,W):\n raise Exception(f\"qrect0 is None, so the disparity image must have the full dimensions of a rectified image\")\n\n intrinsics = models_rectified[0].intrinsics()\n\n fx = intrinsics[1][0]\n cx = intrinsics[1][2]\n\n Rt01 = mrcal.compose_Rt( models_rectified[0].extrinsics_Rt_fromref(),\n models_rectified[1].extrinsics_Rt_toref())\n baseline = nps.mag(Rt01[3,:])\n\n if intrinsics[0] == 'LENSMODEL_LATLON':\n if qrect0 is None:\n az0 = (np.arange(W, dtype=float) - cx)/fx\n else:\n az0 = (qrect0[...,0] - cx)/fx\n\n disparity_rad = disparity.astype(np.float32) / (fx * disparity_scale)\n\n mask_invalid = (disparity <= 0)\n\n s = np.sin(disparity_rad)\n s[mask_invalid] = 1 # to prevent division by 0\n\n r = baseline * np.cos(az0 - disparity_rad) / s\n\n else:\n # pinhole\n\n fy = intrinsics[1][1]\n cy = intrinsics[1][3]\n\n if qrect0 is None:\n tanaz0 = (np.arange(W, dtype=float) - cx)/fx\n tanel = (np.arange(H, dtype=float) - cy)/fy\n tanel = nps.dummy(tanel, -1)\n else:\n tanaz0 = (qrect0[...,0] - cx) / fx\n tanel = (qrect0[...,1] - cy) / fy\n s_sq_recip = tanel*tanel + 1.\n\n\n tanaz0_tanaz1 = disparity.astype(np.float32) / (fx * disparity_scale)\n\n mask_invalid = (disparity <= 0)\n tanaz0_tanaz1[mask_invalid] = 1 # to prevent division by 0\n\n tanaz1 = tanaz0 - tanaz0_tanaz1\n r = baseline / \\\n np.sqrt(s_sq_recip + tanaz0*tanaz0) * \\\n ((s_sq_recip + tanaz0*tanaz1) / tanaz0_tanaz1 + \\\n tanaz0)\n\n r[mask_invalid] = 0\n\n if is_scalar:\n r = r[0]\n return r\n\n\ndef match_feature( image0, image1,\n q0,\n search_radius1,\n template_size1,\n q1_estimate = None,\n H10 = None,\n method = None,\n visualize = False,\n extratitle = None,\n return_plot_args = False,\n **kwargs):\n\n r'''Find a pixel correspondence in a pair of images\n\nSYNOPSIS\n\n # Let's assume that the two cameras are roughly observing the plane defined\n # by z=0 in the ref coordinate system. We also have an estimate of the\n # camera extrinsics and intrinsics, so we can construct the homography that\n # defines the relationship between the pixel observations in the vicinity of\n # the q0 estimate. We use this homography to estimate the corresponding\n # pixel coordinate q1, and we use it to transform the search template\n def xy_from_q(model, q):\n v, dv_dq, _ = mrcal.unproject(q, *model.intrinsics(),\n get_gradients = True)\n t_ref_cam = model.extrinsics_Rt_toref()[ 3,:]\n R_ref_cam = model.extrinsics_Rt_toref()[:3,:]\n vref = mrcal.rotate_point_R(R_ref_cam, v)\n\n # We're looking at the plane z=0, so z = 0 = t_ref_cam[2] + k*vref[2]\n k = -t_ref_cam[2]/vref[2]\n xy = t_ref_cam[:2] + k*vref[:2]\n\n H_xy_vref = np.array((( -t_ref_cam[2], 0, xy[0] - k*vref[0]),\n ( 0, -t_ref_cam[2], xy[1] - k*vref[1]),\n ( 0, 0, 1)))\n\n H_v_q = nps.glue( dv_dq, nps.transpose(v - nps.inner(dv_dq,q)),\n axis = -1)\n H_xy_q = nps.matmult(H_xy_vref, R_ref_cam, H_v_q)\n\n return xy, H_xy_q\n\n xy, H_xy_q0 = xy_from_q(model0, q0)\n\n v1 = mrcal.transform_point_Rt(model1.extrinsics_Rt_fromref(),\n np.array((*xy, 0.)))\n q1 = mrcal.project(v1, *model1.intrinsics())\n\n _, H_xy_q1 = xy_from_q(model1, q1)\n\n H10 = np.linalg.solve( H_xy_q1, H_xy_q0)\n\n\n q1, diagnostics = \\\n mrcal.match_feature( image0, image1,\n q0,\n H10 = H10,\n search_radius1 = 200,\n template_size1 = 17 )\n\nThis function wraps the OpenCV cv2.matchTemplate() function to provide\nadditional functionality. The big differences are\n\n1. The mrcal.match_feature() interface reports a matching pixel coordinate, NOT\n a matching template. The conversions between templates and pixel coordinates\n at their center are tedious and error-prone, and they're handled by this\n function.\n\n2. mrcal.match_feature() can take into account a homography that is applied to\n the two images to match their appearance. The caller can estimate this from\n the relative geometry of the two cameras and the geometry of the observed\n object. If two pinhole cameras are observing a plane in space, a homography\n exists to perfectly represent the observed images everywhere in view. The\n homography can include a scaling (if the two cameras are looking at the same\n object from different distances) and/or a rotation (if the two cameras are\n oriented differently) and/or a skewing (if the object is being observed from\n different angles)\n\n3. mrcal.match_feature() performs simple sub-pixel interpolation to increase the\n resolution of the reported pixel match\n\n4. Visualization capabilities are included to allow the user to evaluate the\n results\n\nIt is usually required to pre-filter the images being matched to get good\nresults. This function does not do this, and it is the caller's job to apply the\nappropriate filters.\n\nAll inputs and outputs use the (x,y) convention normally utilized when talking\nabout images; NOT the (y,x) convention numpy uses to talk about matrices. So\ntemplate_size1 is specified as (width,height).\n\nThe H10 homography estimate is used in two separate ways:\n\n1. To define the image transformation we apply to the template before matching\n\n2. To compute the initial estimate of q1. This becomes the center of the search\n window. We have\n\n q1_estimate = mrcal.apply_homography(H10, q0)\n\nA common use case is a translation-only homography. This avoids any image\ntransformation, but does select a q1_estimate. This special case is supported by\nthis function accepting a q1_estimate argument instead of H10. Equivalently, a\nfull translation-only homography may be passed in:\n\n H10 = np.array((( 1., 0., q1_estimate[0]-q0[0]),\n ( 0., 1., q1_estimate[1]-q0[1]),\n ( 0., 0., 1.)))\n\nThe top-level logic of this function:\n\n1. q1_estimate = mrcal.apply_homography(H10, q0)\n\n2. Select a region in image1, centered at q1_estimate, with dimensions given in\n template_size1\n\n3. Transform this region to image0, using H10. The resulting transformed image\n patch in image0 is used as the template\n\n4. Select a region in image1, centered at q1_estimate, that fits the template\n search_radius1 pixels off center in each dimension\n\n4. cv2.matchTemplate() to search for the template in this region of image1\n\nIf the template being matched is out-of-bounds in either image, this function\nraises an exception.\n\nIf the search_radius1 pushes the search outside of the search image, the search\nbounds are reduced to fit into the given image, and the function works as\nexpected.\n\nIf the match fails in some data-dependent way, we return q1 = None instead of\nraising an Exception. This can happen if the optimum cannot be found or if\nsubpixel interpolation fails.\n\nif visualize: we produce a visualization of the best-fitting match. if not\nreturn_plot_args: we display this visualization; else: we return the plot data,\nso that we can create the plot later. The diagnostic plot contains 3 overlaid\nimages:\n\n- The image being searched\n- The homography-transformed template placed at the best-fitting location\n- The correlation (or difference) image, placed at the best-fitting location\n\nIn an interactive gnuplotlib window, each image can be shown/hidden by clicking\non the relevant legend entry at the top-right of the image. Repeatedly toggling\nthe visibility of the template image is useful to communicate the fit accuracy.\nThe correlation image is guaranteed to appear at the end of plot_data_tuples, so\nit can be omitted by plotting plot_data_tuples[:-1]. Skipping this image is\noften most useful for quick human evaluation.\n\nARGUMENTS\n\n- image0: the first image to use in the matching. This image is cropped, and\n transformed using the H10 homography to produce the matching template. This is\n interpreted as a grayscale image: 2-dimensional numpy array\n\n- image1: the second image to use in the matching. This image is not\n transformed, but cropped to accomodate the given template size and search\n radius. We use this image as the base to compare the template against. The\n same dimensionality, dtype logic applies as with image0\n\n- q0: a numpy array of shape (2,) representing the pixel coordinate in image0\n for which we seek a correspondence in image1\n\n- search_radius1: integer selecting the search window size, in image1 pixels\n\n- template_size1: an integer width or an iterable (width,height) describing the\n size of the template used for matching. If an integer width is given, we use\n (width,width). This is given in image1 coordinates, even though the template\n itself comes from image0\n\n- q1_estimate: optional numpy array of shape (2,) representing the pixel\n coordinate in image1, which is our rough estimate for the camera1 observation\n of the q0 observation in image0. If omitted, H10 specifies the initial\n estimate. Exactly one of (q1_estimate,H10) must be given\n\n- H10: optional numpy array of shape (3,3) containing the homography mapping q0\n to q1 in the vicinity of the match. If omitted, we assume a translation-only\n homography mapping q0 to q1_estimate. Exactly one of (q1_estimate,H10) must be\n given\n\n- method: optional constant, selecting the correlation function used in the\n template comparison. If omitted or None, we default to normalized\n cross-correlation: cv2.TM_CCORR_NORMED. For a description of available methods\n see:\n\n https://docs.opencv.org/master/df/dfb/group__imgproc__object.html\n\n- visualize: optional boolean, defaulting to False. If True, we generate a plot\n that describes the matching results. This overlays the search image, the\n template, and the matching-output image, shifted to their optimized positions.\n All 3 images are plotted direclty on top of one another. Clicking on the\n legend in the resulting gnuplot window toggles that image on/off, which allows\n the user to see how well things line up. if visualize and not\n return_plot_args: we generate an interactive plot, and this function blocks\n until the interactive plot is closed. if visualize and return_plot_args: we\n generate the plot data and commands, but instead of creating the plot, we\n return these data and commands, for the caller to post-process\n\n- extratitle: optional string to include in the title of the resulting plot.\n Used to extend the default title string. If kwargs['title'] is given, it is\n used directly, and the extratitle is ignored. Used only if visualize\n\n- return_plot_args: boolean defaulting to False. if return_plot_args: we return\n data_tuples, plot_options objects instead of making the plot. The plot can\n then be made with gp.plot(*data_tuples, **plot_options). Useful if we want to\n include this as a part of a more complex plot. Used only if visualize\n\n- **kwargs: optional arguments passed verbatim as plot options to gnuplotlib.\n Useful to make hardcopies, etc. Used only if visualize\n\nRETURNED VALUES\n\nWe return a tuple:\n\n- q1: a numpy array of shape (2,): the pixel coordinate in image1 corresponding\n to the given q0. If the computation fails in some data-dependent way, this\n value is None\n\n- diagnostics: a dict containing diagnostics that describe the match. keys:\n\n - matchoutput_image: the matchoutput array computed by cv2.matchTemplate()\n\n - matchoutput_optimum_subpixel_at: the subpixel-refined coordinate of the\n optimum in the matchoutput image\n\n - matchoutput_optimum_subpixel: the value of the subpixel-refined optimum in the\n matchoutput_image\n\n - qshift_image1_matchoutput: the shift between matchoutput image coords and\n image1 coords. We have\n\n q1 = diagnostics['matchoutput_optimum_subpixel_at'] +\n diagnostics['qshift_image1_matchoutput']\n\nIf visualize and return_plot_args: we return two more elements in the tuple:\ndata_tuples, plot_options. The plot can then be made with gp.plot(*data_tuples,\n**plot_options).\n\n '''\n try:\n N = len(template_size1)\n except:\n N = 2\n template_size1 = (template_size1, template_size1)\n if N != 2:\n raise Exception(f\"template_size1 must be an interable of length 2 OR a scalar. Got an iterable of length {N}\")\n for i in range(2):\n if not (isinstance(template_size1[i], int) and template_size1[i] > 0):\n raise Exception(f\"Each element of template_size1 must be an integer > 0. Got {template_size1[i]}\")\n\n template_size1 = np.array(template_size1, dtype=int)\n\n if image0.ndim != 2:\n raise Exception(\"match_feature() accepts ONLY grayscale images of shape (H,W)\")\n\n if image1.ndim != 2:\n raise Exception(\"match_feature() accepts ONLY grayscale images of shape (H,W)\")\n\n if (H10 is None and q1_estimate is None) or \\\n (H10 is not None and q1_estimate is not None):\n raise Exception(\"Exactly one of (q1_estimate,H10) must be given\")\n\n q0 = q0.astype(np.float32)\n\n if H10 is None:\n H10 = np.array((( 1., 0., q1_estimate[0]-q0[0]),\n ( 0., 1., q1_estimate[1]-q0[1]),\n ( 0., 0., 1.)), dtype=np.float32)\n q1_estimate = q1_estimate.astype(np.float32)\n else:\n H10 = H10.astype(np.float32)\n q1_estimate = mrcal.apply_homography(H10, q0)\n\n # I default to normalized cross-correlation. The method arg defaults to None\n # instead of cv2.TM_CCORR_NORMED so that I don't need to import cv2, unless\n # the user actually calls this function\n import cv2\n if method is None:\n method = cv2.TM_CCORR_NORMED\n\n ################### BUILD TEMPLATE\n # I construct the template I'm searching for. This is a slice of image0 that\n # is\n # - centered at the given q0\n # - remapped using the homography to correct for the geometric\n # differences in the two images\n\n q1_template_min = np.round(q1_estimate - (template_size1-1.)/2.).astype(int)\n q1_template_max = q1_template_min + template_size1 - 1 # last pixel\n\n\n def checkdims(image_shape, what, *qall):\n for q in qall:\n if q[0] < 0:\n raise Exception(f\"Too close to the left edge in {what}\")\n if q[1] < 0:\n raise Exception(f\"Too close to the top edge in {what} \")\n if q[0] >= image_shape[1]:\n raise Exception(f\"Too close to the right edge in {what} \")\n if q[1] >= image_shape[0]:\n raise Exception(f\"Too close to the bottom edge in {what} \")\n\n checkdims( image1.shape,\n \"image1\",\n q1_template_min,\n q1_template_max)\n\n # shape (H,W,2)\n q1 = nps.glue(*[ nps.dummy(arr, -1) for arr in \\\n np.meshgrid( np.arange(q1_template_min[0], q1_template_max[0]+1),\n np.arange(q1_template_min[1], q1_template_max[1]+1))],\n axis=-1).astype(np.float32)\n\n q0 = mrcal.apply_homography(np.linalg.inv(H10), q1)\n checkdims( image0.shape,\n \"image0\",\n q0[ 0, 0],\n q0[-1, 0],\n q0[ 0,-1],\n q0[-1,-1] )\n\n image0_template = mrcal.transform_image(image0, q0)\n\n\n ################### MATCH TEMPLATE\n q1_min = q1_template_min - search_radius1\n q1_max = q1_template_min + search_radius1 + template_size1 - 1 # last pixel\n\n # Adjust the bounds in case the search radius pushes us past the bounds of\n # image1\n if q1_min[0] < 0: q1_min[0] = 0\n if q1_min[1] < 0: q1_min[1] = 0\n if q1_max[0] > image1.shape[-1] - 1: q1_max[0] = image1.shape[-1] - 1\n if q1_max[1] > image1.shape[-2] - 1: q1_max[1] = image1.shape[-2] - 1\n\n # q1_min, q1_max are now corners of image1 we should search\n image1_cut = image1[ q1_min[1]:q1_max[1]+1, q1_min[0]:q1_max[0]+1 ]\n\n template_size1_hw = np.array((template_size1[-1],template_size1[-2]))\n matchoutput = np.zeros( image1_cut.shape - template_size1_hw+1, dtype=np.float32 )\n\n cv2.matchTemplate(image1_cut,\n image0_template,\n method, matchoutput)\n\n if method == cv2.TM_SQDIFF or method == cv2.TM_SQDIFF_NORMED:\n matchoutput_optimum_flatindex = np.argmin( matchoutput.ravel() )\n else:\n matchoutput_optimum_flatindex = np.argmax( matchoutput.ravel() )\n matchoutput_optimum = matchoutput.ravel()[matchoutput_optimum_flatindex]\n # optimal, discrete-pixel q1 in image1_cut coords\n q1_cut = \\\n np.array( np.unravel_index(matchoutput_optimum_flatindex,\n matchoutput.shape) )[(-1,-2),]\n diagnostics = \\\n dict(matchoutput_image = matchoutput)\n\n ###################### SUBPIXEL INTERPOLATION\n # I fit a simple quadratic surface to the 3x3 points around the discrete\n # max, and report the max of that fitted surface\n # c = (c00, c10, c01, c20, c11, c02)\n # z = c00 + c10*x + c01*y + c20*x*x + c11*x*y + c02*y*y\n # z ~ M c\n # dz/dx = c10 + 2 c20 x + c11 y = 0\n # dz/dy = c01 + 2 c02 y + c11 x = 0\n # -> [ 2 c20 c11 ] [x] = [-c10]\n # [ c11 2 c02 ] [y] = [-c01]\n #\n # -> xy = -1/(4 c20 c02 - c11^2) [ 2 c02 -c11 ] [c10]\n # [ -c11 2 c20 ] [c01]\n\n default_plot_args = (None,None) if visualize and return_plot_args else ()\n\n if q1_cut[0] <= 0 or \\\n q1_cut[1] <= 0 or \\\n q1_cut[0] >= matchoutput.shape[-1]-1 or \\\n q1_cut[1] >= matchoutput.shape[-2]-1:\n # discrete matchoutput peak at the edge. Cannot compute subpixel\n # interpolation\n return (None, diagnostics) + default_plot_args\n\n x,y = np.meshgrid( np.arange(3) - 1, np.arange(3) - 1 )\n x = x.ravel().astype(float)\n y = y.ravel().astype(float)\n M = nps.transpose( nps.cat( np.ones(9,),\n x, y, x*x, x*y, y*y ))\n z = matchoutput[ q1_cut[1]-1:q1_cut[1]+2,\n q1_cut[0]-1:q1_cut[0]+2 ].ravel()\n try:\n lsqsq_result = np.linalg.lstsq( M, z, rcond = None)\n except:\n return (None, diagnostics) + default_plot_args\n\n c = lsqsq_result[0]\n (c00, c10, c01, c20, c11, c02) = c\n det = 4.*c20*c02 - c11*c11\n xy_subpixel = -np.array((2.*c10*c02 - c01*c11,\n 2.*c01*c20 - c10*c11)) / det\n x,y = xy_subpixel\n matchoutput_optimum_subpixel = c00 + c10*x + c01*y + c20*x*x + c11*x*y + c02*y*y\n q1_cut = q1_cut.astype(float) + xy_subpixel\n\n diagnostics['matchoutput_optimum_subpixel_at'] = q1_cut\n diagnostics['matchoutput_optimum_subpixel'] = matchoutput_optimum_subpixel\n\n # The translation to pixel coordinates\n\n # Top-left pixel of the template, in image1 coordinates\n q1_aligned_template_topleft = q1_min + q1_cut\n\n # Shift for the best-fitting pixel of image1 of the template center\n qshift_image1_matchoutput = \\\n q1_min + \\\n q1_estimate - \\\n q1_template_min\n diagnostics['qshift_image1_matchoutput'] = qshift_image1_matchoutput\n\n # the best-fitting pixel of image1 of the template center\n\n q1 = q1_cut + qshift_image1_matchoutput\n\n matchoutput_min = np.min(matchoutput)\n matchoutput_max = np.max(matchoutput)\n\n if not visualize:\n return q1, diagnostics\n\n import gnuplotlib as gp\n\n plot_options = dict(kwargs)\n\n if 'title' not in plot_options:\n title = 'Feature-matching results'\n if extratitle is not None:\n title += \": \" + extratitle\n plot_options['title'] = title\n\n gp.add_plot_option(plot_options,\n _with = 'image',\n ascii = True,\n overwrite = True)\n gp.add_plot_option(plot_options,\n square = True,\n yinv = True,\n _set = 'palette gray',\n overwrite = False)\n\n data_tuples = \\\n ( ( image1_cut,\n dict(legend='image',\n using = f'($1 + {q1_min[0]}):($2 + {q1_min[1]}):3',\n tuplesize = 3)),\n ( image0_template,\n dict(legend='template',\n using = \\\n f'($1 + {q1_aligned_template_topleft[0]}):' + \\\n f'($2 + {q1_aligned_template_topleft[1]}):3',\n tuplesize = 3)),\n ( (matchoutput - matchoutput_min) /\n (matchoutput_max - matchoutput_min) * 255,\n dict(legend='matchoutput',\n using = \\\n f'($1 + {qshift_image1_matchoutput[0]}):' + \\\n f'($2 + {qshift_image1_matchoutput[1]}):3',\n tuplesize = 3)) )\n\n if return_plot_args:\n return q1, diagnostics, data_tuples, plot_options\n\n gp.plot( *data_tuples, **plot_options, wait=True)\n return q1, diagnostics\n" ]
[ [ "numpy.sqrt", "numpy.round", "numpy.max", "numpy.cross", "numpy.trace", "numpy.arange", "numpy.sin", "numpy.roots", "numpy.real", "numpy.argmax", "numpy.unravel_index", "numpy.zeros", "numpy.min", "numpy.linalg.inv", "numpy.tan", "numpy.linalg.lstsq", "numpy.array", "numpy.cos", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
BoiseState/NAM
[ "816b5d7e4d1adfd95a56f6494a12856f08a38bee" ]
[ "localization_preprocessing/dnam_mixed_origami_process.py" ]
[ "from matplotlib import pyplot as plt\n\nimport numpy as np\nimport os.path as _ospath\n\nfrom scipy import spatial\nfrom scipy.optimize import minimize\n\nfrom multiprocessing import Pool, cpu_count\nimport csv\n\nimport picasso_utils as picasso\n\nimport argparse\n\nimport numba as _numba\nimport gc\nimport sys\n\nimport xml.etree.ElementTree as ET\n\n#picasso hdf5 format (with averaging): ['frame', 'x', 'y', 'photons', 'sx', 'sy', 'bg', 'lpx', 'lpy', 'group']\n#Column Name |\tDescription |\tC Data Type\n#frame\t |The frame in which the localization occurred, starting with zero for the first frame.\t |unsigned long\n#x |The subpixel x coordinate in camera pixels\t |float\n#y\t |The subpixel y coordinate in camera pixels\t |float\n#photons\t |The total number of detected photons from this event, not including background or camera offset\t |float\n#sx\t |The Point Spread Function width in camera pixels |\tfloat\n#sy\t |The Point Spread Function height in camera pixels |\tfloat\n#bg\t |The number of background photons per pixel, not including the camera offset |\tfloat\n#lpx\t |The localization precision in x direction, in camera pixels, as estimated by the Cramer-Rao Lower Bound of the Maximum Likelihood fit. |\tfloat\n#lpy\t |The localization precision in y direction, in camera pixels, as estimated by the Cramer-Rao Lower Bound of the Maximum Likelihood fit. |\tfloat\n\n\nclass LocalizationCluster:\n def __init__(self,grid,localizations,globalDeltaX,recenter):\n \"\"\"Class container for localization and grid points, fitting functions\"\"\"\n #grid NX2 array of x,y localizations NX3 array of x,y,prec\n self.grid = np.copy(grid)\n self.gridTran = np.copy(grid)\n self.localizations = np.copy(localizations)\n self.globalDeltaX = globalDeltaX\n #self.weight = 1/np.sqrt(localizations[:,2]**2 + self.globalDeltaX**2)\n self.nnTree = []\n self.nn = []\n self.dx = 0\n self.dy = 0\n self.dt = 0\n \n \n #Center grid and localizations on 0,0\n xGAve = 0\n yGAve = 0\n gCount = 0\n self.xLAve = 0\n self.yLAve = 0\n lCount = 0\n self.uAve=0\n for row in range(self.grid.shape[0]):\n xGAve+=self.grid[row,0]\n yGAve+=self.grid[row,1]\n gCount+=1\n \n for row in range(self.localizations.shape[0]):\n self.xLAve+=self.localizations[row,0]\n self.yLAve+=self.localizations[row,1]\n self.uAve += self.localizations[row,2]\n lCount+=1\n \n xGAve/=gCount\n yGAve/=gCount\n \n self.xLAve/=lCount\n self.yLAve/=lCount\n self.uAve/=lCount\n self.locCount = lCount\n \n self.xCAve = self.xLAve\n self.yCAve = self.yLAve\n \n if recenter:\n for row in range(self.grid.shape[0]):\n self.grid[row,0]-=xGAve\n self.grid[row,1]-=yGAve\n \n for row in range(self.localizations.shape[0]):\n self.localizations[row,0]-=self.xLAve\n self.localizations[row,1]-=self.yLAve\n \n self.xCAve = 0\n self.yCAve = 0\n \n #self.roughClock()\n \n self.weightDistMatrix = np.zeros((self.localizations.shape[0],self.gridTran.shape[0]))\n self.wdmComputed = False\n self.objectiveValue = 0\n self.hist = []\n self.signal = []\n self.hist2 = np.ones((self.gridTran.shape[0]+1))\n self.rec = []\n self.kernel=[]\n self.sigma = 0\n self.cHull = spatial.ConvexHull(self.localizations[:,0:2])\n self.area = self.cHull.volume #For 2d points, the internal area is the volume reported by ConvexHull\n \n def transformGrid(self,tm):\n self.dx = tm[0]\n self.dy = tm[1]\n self.dt = tm[2]\n rotMat = np.array([[np.cos(self.dt),-np.sin(self.dt)],[np.sin(self.dt),np.cos(self.dt)]])\n self.gridTran = np.dot(self.grid,rotMat)\n self.gridTran[:,0]+=self.dx\n self.gridTran[:,1]+=self.dy\n self.nnTree = spatial.cKDTree(self.gridTran)\n self.nn = self.nnTree.query(self.localizations[:,0:2])\n self.wdmComputed = False\n \n def squareNNDist(self,tm):\n \"\"\"Weighted mean square nearest neighbor distantce, computed by translating grid\"\"\"\n self.transformGrid(tm)\n weight = 1/np.sqrt(self.localizations[:,2]**2 + self.globalDeltaX**2)\n self.objectiveValue = float(sum(np.multiply(self.nn[0],weight)**2))/self.locCount\n \n return self.objectiveValue\n \n def squareNNDistFixed(self,tm):\n \"\"\"Weighted mean square nearest neighbor distance, computed by translating localizations. Faster for large grids\"\"\"\n self.dx = tm[0]\n self.dy = tm[1]\n self.dt = tm[2]\n \n if self.nnTree == []:\n self.nnTree = spatial.cKDTree(self.gridTran)\n \n rotMat = np.array([[np.cos(self.dt),np.sin(self.dt)],[-np.sin(self.dt),np.cos(self.dt)]])\n localizationsTran = np.dot(self.localizations[:,0:2],rotMat)\n localizationsTran[:,0]-=self.dx\n localizationsTran[:,1]-=self.dy\n weight = 1/np.sqrt(self.localizations[:,2]**2 + self.globalDeltaX**2)\n self.nn = self.nnTree.query(localizationsTran)\n self.wdmComputed = False\n self.objectiveValue = float(sum(np.multiply(self.nn[0],weight)**2))/self.locCount\n \n return self.objectiveValue\n \n \n def squareNNDistUnweighted(self,tm,gridsize):\n \"\"\"unweighted mean square nearest neighbor distantce, computed by translating grid\"\"\"\n self.dx = tm[0]\n self.dy = tm[1]\n self.dt = tm[2]\n rotMat = np.array([[np.cos(self.dt),-np.sin(self.dt)],[np.sin(self.dt),np.cos(self.dt)]])\n self.gridTran = np.dot(self.grid,rotMat)\n self.gridTran[:,0]+=self.dx\n self.gridTran[:,1]+=self.dy\n self.nnTree = spatial.cKDTree(self.gridTran)\n self.nn = self.nnTree.query(self.localizations[:,0:2])\n self.wdmComputed = False\n return float(sum((2*self.nn[0]/gridsize)**2))/self.locCount\n \n \n def rmsDist(self):\n \"\"\"RMS distance from origin\"\"\"\n return self._rmsDistComp(self.localizations)\n \n @staticmethod\n @_numba.jit(nopython = True)\n def _rmsDistComp(localizations):\n locCount = localizations.shape[0]\n sqDist = 0\n \n for row in range(locCount):\n sqDist += localizations[row,0]**2 + localizations[row,1]**2\n \n sqDist/=locCount\n return sqDist\n \n #@_numba.jit(nopython = True, nogil = True)\n def roughClock(self):\n \"\"\"Find approximate clocking\"\"\"\n minObj = self.squareNNDist([self.dx,self.dy,0])\n minTheta = 0\n for thetaId in range(360):\n theta = thetaId*np.pi/180\n obj = self.squareNNDist([self.dx,self.dy,theta])\n if obj<minObj:\n minObj = obj\n minTheta=theta\n self.dt = minTheta\n self.wdmComputed = False\n return self.squareNNDist([self.dx,self.dy,self.dt])\n \n def computeWeightDistMatrix(self):\n \"\"\"Compute weighted distance likelihood value, used for likelihood score\"\"\"\n #for locId in range(self.localizations.shape[0]):\n # for gridId in range(self.gridTran.shape[0]):\n # self.weightDistMatrix[locId,gridId] = np.exp(-((self.localizations[locId,0]-self.gridTran[gridId,0])**2+(self.localizations[locId,1]-self.gridTran[gridId,1])**2)/(2.0*(self.localizations[locId,2]**2+self.globalDeltaX**2)))\n self.weightDistMatrix = self._computeWeightDistMatrixComp(self.localizations[:,0:3],self.gridTran,self.localizations.shape[0],self.gridTran.shape[0],self.globalDeltaX,self.area)\n self.wdmComputed=True\n \n @staticmethod\n @_numba.jit(nopython = True)\n def _computeWeightDistMatrixComp(localizations,grid,locCount,gridCount,globalDeltaX,area):\n weightDistMatrix = np.zeros((locCount,gridCount+1))\n\n for locId in range(locCount):\n for gridId in range(gridCount):\n sigma2 = (localizations[locId,2]**2+globalDeltaX**2)\n weightDistMatrix[locId,gridId] = (1.0/2.0/np.pi/sigma2)*np.exp(-((localizations[locId,0]-grid[gridId,0])**2+(localizations[locId,1]-grid[gridId,1])**2)/(2.0*sigma2))\n weightDistMatrix[locId,gridCount] = 1/area\n return weightDistMatrix\n\n def likelihoodScore(self,image): \n \"\"\"log likelihood function for localization positions given intensity values at grid points\"\"\"\n if not self.wdmComputed:\n self.computeWeightDistMatrix()\n \n score = self._likelihoodScoreComp(self.weightDistMatrix,image,self.locCount)\n \n return score\n \n \n @staticmethod\n @_numba.jit(nopython = True)\n def _likelihoodScoreComp(weightDistMatrix,image,locCount):\n\n score = -(np.sum(np.log(np.dot(weightDistMatrix,image))))\n \n imageSum = np.sum(image)\n if imageSum <= 0:\n imageSum = .000001\n score -= imageSum*np.log(locCount/imageSum) + imageSum\n \n return score\n \n def pixelate(self,gridShape,distThreshold):\n \"\"\"Produce maximum likelihood pixelated image\"\"\"\n if self.nnTree == []:\n self.nnTree = spatial.cKDTree(self.gridTran)\n self.nn = self.nnTree.query(self.localizations[:,0:2])\n \n self.localizations = self.localizations[self.nn[0]<distThreshold,:]\n self.locCount = self.localizations.shape[0]\n \n self.cHull = spatial.ConvexHull(self.localizations[:,0:2])\n self.area = self.cHull.volume #Ugh, scipy\n \n self.hist = np.zeros((self.gridTran.shape[0]+1))\n \n for idx in self.nn[1]:\n self.hist[idx] += 1\n \n bounds = [(0,1e10) for item in self.hist]\n \n out = minimize(self.likelihoodScore,self.hist,bounds=bounds, method=\"L-BFGS-B\",options={'eps':1e-10})\n self.hist2 = out.x\n #print(self.hist2[-1])\n \n Iscale = max(self.hist)*2 \n self.signal = (self.hist[:-1].reshape(gridShape))/Iscale\n self.rec = self.hist2[:-1].reshape(gridShape)\n self.rec *= sum(sum(self.signal))/sum(sum(self.rec))*Iscale\n \n return self.likelihoodScore(self.hist2)\n \n def fitAndPixelate(self,gridShape,distThreshold,maxIter,toler):\n \"\"\"Fit grid and produce maximum likelihood pixelated image\"\"\"\n \n self.hist = np.zeros((self.gridTran.shape[0]+1))\n \n \n \n \n #bounds = [(-.5,.5),(-.5,.5),(-np.pi,3*np.pi)]\n bounds =[(0,1e10) for item in self.hist]\n \n self.roughClock()\n self.hist2 = np.ones((self.gridTran.shape[0]+1))\n lastFVal = self.likelihoodScore(self.hist2)\n #print(lastFVal)\n it=0\n for _ in range(maxIter):\n it+=1\n out1 = minimize(self.gridLikelihoodScore,[self.dx,self.dy,self.dt],method='Nelder-Mead')\n self.transformGrid(out1.x)\n \n #for idx in self.nn[1]:\n # self.hist[idx] += 1\n \n out2 = minimize(self.likelihoodScore,self.hist2,bounds=bounds, method=\"L-BFGS-B\", options={'eps':1e-10})\n self.hist2 = out2.x\n \n out3 = minimize(self.gdxLikelihoodScore,[self.globalDeltaX],bounds=[(0,1)],method=\"L-BFGS-B\")\n self.globalDeltaX = out3.x[0]\n FVal = out3.fun\n #print(FVal)\n #print(2.0*np.abs(lastFVal-FVal)/(lastFVal+FVal), toler)\n \n if it==3:\n self.localizations = self.localizations[self.nn[0]<distThreshold,:]\n self.locCount = self.localizations.shape[0]\n self.cHull = spatial.ConvexHull(self.localizations[:,0:2])\n self.area = self.cHull.volume #Ugh, scipy\n #print(self.area,self.cHull.volume)\n \n if 2.0*np.abs((lastFVal-FVal)/(lastFVal+FVal)) < toler and it > 4:\n break\n lastFVal = FVal\n #print(self.hist2[-1])\n \n self.transformGrid([self.dx,self.dy,self.dt])\n for idx in self.nn[1]:\n self.hist[idx] += 1\n \n Iscale = max(self.hist)*2 \n self.signal = (self.hist[:-1].reshape(gridShape))/Iscale\n self.rec = self.hist2[:-1].reshape(gridShape)\n self.rec *= sum(sum(self.signal))/sum(sum(self.rec))*Iscale\n \n return out3.fun,it\n \n def gridLikelihoodScore(self,tm):\n \"\"\"Likelihood score for current image (hist2) given grid coordinate\"\"\"\n self.transformGrid(tm)\n image = np.copy(self.hist2)\n image *= self.locCount/sum(image)\n return self.likelihoodScore(image)\n \n def gdxLikelihoodScore(self,gdx):\n \"\"\"Likelihood score for current image (hist2) given global delta x\"\"\"\n self.globalDeltaX = gdx[0]\n self.wdmComputed = False\n image = np.copy(self.hist2)\n image *= self.locCount/sum(image)\n return self.likelihoodScore(image)\n \n# =============================================================================\n #This doesn't seem to converge\n# def fullLikelihoodScore(self,tm):\n# self.transformGrid(tm[0:3])\n# image = tm[3:]\n# return self.likelihoodScore(image)\n# =============================================================================\n \n \nclass RandomClusters: \n def __init__(self,grid,locs,radius,minCountThreshold,maxCountThreshold,isoRadius,isoRatio,globalDeltaX):\n \"\"\"Find random clusters fitting certain properties from localizations. Uses LocalizationCluster class\"\"\"\n self.locs = locs\n self.nnTree = []\n self.radius = radius\n self.minCountThreshold = minCountThreshold\n self.maxCountThreshold = maxCountThreshold\n self.isoRadius = isoRadius #Additional radius to search to check for isolation of cluster\n self.isoRatio = isoRatio #Ratio of localization that must be iwthin inner radius\n \n self.sublocalizations=[]\n self.grid = grid\n self.clusterLocations = []\n self.localizations = []\n self.updateLocalizations()\n self.locCount = self.localizations.shape[0]\n self.globalDeltaX = globalDeltaX\n \n def updateLocalizations(self):\n \"\"\"Updates localizations and tree if locs has changed through another process\"\"\"\n x = self.locs['x']\n y = self.locs['y']\n lpx = self.locs['lpx']\n \n self.localizations = np.array([x,y,lpx,[i for i in range(len(x))]]).T\n self.nnTree = spatial.cKDTree(self.localizations[:,0:2])\n \n def findClusters(self,samples,maxAttempts):\n \"\"\"Attempts to find random clusters, only tries maxAttempts times\"\"\"\n localizationClusters = []\n self.clusterLocations = []\n \n clusterLocationTree = []\n \n attempts = 0\n \n while len(localizationClusters) < samples and attempts < maxAttempts:\n attempts+=1\n randIndex = int(np.random.sample()*self.locCount)\n \n if len(self.clusterLocations) > 0:\n clusterNN = clusterLocationTree.query(self.localizations[randIndex,0:2])\n \n if clusterNN[0] < self.isoRadius:\n continue\n \n sublocs_id = self.nnTree.query_ball_point(self.localizations[randIndex,0:2],2 * self.radius)\n \n firstCounts = len(sublocs_id)\n \n if firstCounts < self.minCountThreshold:\n continue\n self.sublocalizations = self.localizations[sublocs_id,:]\n lc = LocalizationCluster(self.grid,self.sublocalizations,self.globalDeltaX,True)\n \n subTree = spatial.cKDTree(lc.localizations[:,0:2])\n sublocs_id = subTree.query_ball_point(np.array([0,0]),self.radius)\n isoCounts = len(subTree.query_ball_point(np.array([0,0]),self.isoRadius))\n \n secondCounts = len(sublocs_id)\n\n if secondCounts < self.minCountThreshold or secondCounts > self.maxCountThreshold or secondCounts < self.isoRatio * isoCounts:\n continue\n \n \n self.sublocalizations = self.sublocalizations[sublocs_id,:]\n lc = LocalizationCluster(self.grid,self.sublocalizations,self.globalDeltaX,True)\n \n if lc.rmsDist() > 3 * self.radius / 4:\n continue\n \n self.clusterLocations.append([lc.xLAve,lc.yLAve])\n clusterLocationTree = spatial.cKDTree(np.array(self.clusterLocations))\n \n localizationClusters.append(lc)\n \n return localizationClusters\n \n\ndef clusterFit(lc,index,gridShape,distThreshold):\n \"\"\"Multiprocess pool friendly cluster fitting algorithm\"\"\"\n print(\"Starting fit for cluster\",index)\n #lc.roughClock()\n #method = \"Nelder-Mead\"\n #out = minimize(lc.squareNNDist,[lc.dx,lc.dy,lc.dt],method=method)\n #lc.squareNNDist(out.x)\n #minimizer_kwargs = {\"method\":method}\n #out = basinhopping(lc.squareNNDist,x0=out.x,T=.5,niter=200,minimizer_kwargs=minimizer_kwargs,stepsize = 0.25)\n #out = minimize(lc.squareNNDist,out.x,method=method)\n #bounds = np.array([[-.225+out.x[0],.225+out.x[0]],[-.225+out.x[1],.225+out.x[1]],[-np.pi+out.x[2],np.pi+out.x[2]]]) \n #out = dual_annealing(lc.squareNNDist,bounds,x0=out.x,local_search_options={'method':method},maxiter=2000)#,inital_temp=5e4,restart_temp_ratio=2e-6)\n out,it = lc.fitAndPixelate(gridShape,distThreshold,50,1e-6)\n obj = lc.squareNNDist([lc.dx,lc.dy,lc.dt])\n \n print(\"Fit complete for cluster\",index,\"Objective:\",obj,\"FVal:\",out,\"Iterations:\",it,\"bg:\",lc.hist2[-1])\n \n return [index,lc.dx,lc.dy,lc.dt,obj,out,lc.globalDeltaX,lc.hist2]\n\ndef validateFilters(filters,DTYPE):\n \"\"\"Checks if filter object derived from xmltree.root is valid\"\"\"\n dtype_dict = dict(DTYPE)\n for child in filters:\n if not child.tag in dtype_dict:\n return -1\n if (not 'type' in child.attrib) or (not 'low' in child.attrib) or (not 'high' in child.attrib):\n return -2\n if (not child.attrib['type'] == 'absolute') and (not child.attrib['type'] == 'percentile'):\n return -3\n try:\n low = float(child.attrib['low'])\n except ValueError:\n return -4\n try: \n high = float(child.attrib['high'])\n except ValueError:\n return -5\n if (child.attrib['type'] == 'percentile') and (low < 0 or low > 1 or high < 0 or high >1):\n return -6\n if low >= high:\n return -7\n \n return 0\n\n\nif __name__ == '__main__': \n # parsing the arguments\n parser = argparse.ArgumentParser(description=\"dNAM origami process script\")\n parser.add_argument(\"-f\", \"--file\", help=\"File name\", default=\"\")\n parser.add_argument(\"-v\", \"--verbose\", help=\"Print details of execution on console\", action=\"store_true\")\n parser.add_argument(\"-N\", \"--number-clusters\", help=\"Number of clusters to analyze\", type=int,default=0)\n parser.add_argument(\"-s\", \"--skip-clusters\", help=\"Number of clusters to skip\", type=int,default=0)\n parser.add_argument(\"-d\", \"--drift-correct-size\", help=\"Final size of drift correct slice (0 is no drift correction))\", type=int,default=0)\n parser.add_argument(\"-ps\", \"--pixel-size\", help=\"Pixel size. Needed if reading Thunderstorm csv\",type=float,default=0)\n parser.add_argument(\"-x\", \"--xml\", help=\"XML config file for 3d-daostorm analyis (default = default_config.xml)\",default=\"default_config.xml\")\n parser.add_argument(\"-ft\", \"--filter-file\", help=\"XML filter file for post-drift correct filtering (default is no filters)\", default=\"\")\n parser.add_argument(\"-gf\", \"--grid-file\",help=\"CSV file containing x,y coordinates of grid points (default is DNAM average grid)\", default=\"\")\n parser.add_argument(\"-gr\", \"--grid-shape-rows\",help=\"Rows in the grid\", type=int, default=6)\n parser.add_argument(\"-gc\", \"--grid-shape-cols\",help=\"Columns in the grid\", type=int, default=8)\n parser.add_argument(\"-md\", \"--min-drift-clusters\",help=\"Min number of cluster to attempt fine drift correction (default 5000)\", type=int, default=5000)\n parser.add_argument(\"-gdx\", \"--global-delta-x\",help=\"Starting guess for global localization precision due to drift correct, etc\", type=float, default=.025)\n parser.add_argument(\"-st\",\"--scaled-threshold\",help=\"Threshold for binary counts, as a fraction of the average of the 10 brightest points\",type=float,default=.25)\n parser.add_argument(\"-rf\",\"--redo-fitting\",help=\"Redo grid fitting, even if fitted grid data exists (has no effect on data without fits)\",action=\"store_true\")\n #parser.add_argument(\"-rd\", \"--redrift-correct\",help=\"Apply secondary drift correction, post drift (must have >500 clusters)\",action=\"store_true\")\n\n args = parser.parse_args()\n \n gridShape = (args.grid_shape_rows,args.grid_shape_cols)\n \n #set group number\n groupNumbers = [i for i in range(0,args.number_clusters,1)]\n \n distThreshold = 5\n \n globalDeltaX = args.global_delta_x\n \n scaled_threshold = args.scaled_threshold\n \n clusterRadius = 0.55\n minCountThreshold = 1000\n maxCountThreshold = 20000\n objectiveThreshold = 1.5\n distThreshold = .1\n \n minDriftClusters = args.min_drift_clusters\n \n samples = args.number_clusters\n skip = args.skip_clusters\n #redrift = args.redrift_correct\n redrift = False\n \n np.random.seed(2)\n \n display = False\n display2 = True\n verbose = args.verbose\n \n pixelsize = args.pixel_size\n \n outputClusters = True\n \n if samples > 20:\n display2=False\n \n reuse_file = False\n try:\n lastFilePath = filePath\n except NameError:\n lastFilePath = \"\"\n \n filePath = args.file\n \n driftCorrectSize = args.drift_correct_size\n \n filterFile = args.filter_file\n \n \n \n LOCS_DTYPE = [\n (\"frame\", \"u4\"),\n (\"x\", \"f4\"),\n (\"y\", \"f4\"),\n (\"photons\", \"f4\"),\n (\"sx\", \"f4\"),\n (\"sy\", \"f4\"),\n (\"bg\", \"f4\"),\n (\"lpx\", \"f4\"),\n (\"lpy\", \"f4\"),\n (\"group\", \"i4\"),\n ]\n \n if not filterFile == \"\":\n filters = ET.parse(filterFile).getroot()\n chk = validateFilters (filters,LOCS_DTYPE)\n if chk < 0:\n print(\"Error: invalid filter XML file. Error code:\",chk)\n sys.exit(\"Invalid XML\")\n \n #driftCorrectSize = 0\n \n #set filepath\n #filtered by photons averaged dataset\n #filePath = r\"20190913_All-Matrices_syn2_pure_Triangles_300msExp_Mid-9nt-3nM_MgCl2_18mM_PCA_12mM_PCD_TROLOX_1mM_13_42_03_fixed_locs_render_DRIFT_3_filter_picked_manual_avg.hdf5\"\n #filePath = r\"20190913_george_test2_conv_locs_render_render_picked_filter.hdf5\"\n #filePath = r\"20190913_All-Matrices_syn2_pure_Triangles_300msExp_Mid-9nt-3nM_MgCl2_18mM_PCA_12mM_PCD_TROLOX_1mM_13_42_03_fixed_locs_render_DRIFT_3_filter_picked_automatic.hdf5\"\n #filePath = r\"20190930_Matrix-3_syn2_pure_Triangles_300msExp_Mid-9nt-3nM_MgCl2_18mM_PCA_12mM_PCD_TROLOX_1mM_11_18_45_fixed_locs_render_DRIFT_4_filter_picked_manual.hdf5\"\n #filePath = r\"20190913_All-Matrices_syn2_pure_Triangles_300msExp_Mid-9nt-3nM_MgCl2_18mM_PCA_12mM_PCD_TROLOX_1mM_10_38_52_substack_fixed_locs_render_DRIFT_3_filter_picked_avg.hdf5\"\n #filePath = r\"20190905_Matrix2_syn2_pure_Triangles_300msExp_Mid-9nt-3nM_MgCl2_18mM_PCA_12mM_PCD_TROLOX_1mM_14_16_10_fixed_locs_picked_avg_filter.hdf5\"\n \n if filePath == '':\n #filePath = r\"20190913_george_test2_conv_locs_render_render_filter.hdf5\"\n filePath = r\"20190913_All-Matrices_syn2_pure_Triangles_300msExp_Mid-9nt-3nM_MgCl2_18mM_PCA_12mM_PCD_TROLOX_1mM_10_38_52_substack_fixed_locs_render_DRIFT_3_filter.hdf5\"\n #filePath = r\"20191002_Matrix_7_Triangles_fixed_locs_DRIFT_3.hdf5\"\n #filePath = r\"20190909_Matrix14_syn2_pure_Triangles_300msExp_Mid-9nt-3nM_MgCl2_18mM_PCA_12mM_PCD_TROLOX_1mM_11_39_47_fixed_locs_render_DRIFT_3.hdf5\"\n #filePath = r\"20190905_Matrix2_syn2_pure_Triangles_300msExp_Mid-9nt-3nM_MgCl2_18mM_PCA_12mM_PCD_TROLOX_1mM_14_16_10_fixed_locs_render_DRIFT_3_filter.hdf5\"\n #filePath = r\"20190830_Matrix5_syn2_pure_Triangles_300msExp_Mid-9nt-3nM_MgCl2_18mM_PCA_12mM_PCD_TROLOX_1mM_10_44_32_fixed_locs_render_DRIFT_3_filter.hdf5\"\n \n #filePath = \"/data/williamclay/\"+filePath\n \n if not filePath == lastFilePath:\n reuse_file = False\n \n #baseFilePath = filePath[0:-5]\n baseFilePath, extension = _ospath.splitext(filePath)\n \n \n \n if not reuse_file:\n if 'hdf5' in extension:\n #try to open picasso hdf5 file as np.recarray\n try:\n locs, info = picasso.load_locs(filePath)\n except KeyError:\n #If picasso load failed, try Zhuanglab SA load\n print(\"Converting hdf5 file\")\n locs, info = picasso.load_salocs(filePath)\n baseFilePath += \"_locs\"\n picasso.save_locs(baseFilePath+\".hdf5\",locs,info)\n \n elif 'csv' in extension:\n #Load ThunderStorm format csv\n while pixelsize <= 0:\n print(\"Please enter pixelsize (use -ps pixelsize to avoid this message):\")\n pixeltext = input()\n try:\n pixelsize = float(pixeltext)\n except ValueError:\n pixelsize = -1\n locs, info = picasso.csv2locs(filePath,pixelsize)\n baseFilePath += \"_locs\"\n picasso.save_locs(baseFilePath+\".hdf5\",locs,info)\n elif 'txt' in extension:\n #Load 3d_daostorm format txt\n locs, info = picasso.txt2locs(filePath)\n picasso.save_locs(baseFilePath+\"_locs.hdf5\",locs,info)\n elif 'nd2' in extension or 'spe' in extension or 'tif' in extension or 'dax' in extension:\n #load movie\n import mufit_analysis_nd as mufit\n while driftCorrectSize <= 0:\n print(\"Drift correction required for analysis of movie file. Please enter frame segment size. Recommend 100-200 (use -d segment_size to avoid this message):\")\n drifttext = input()\n try:\n driftCorrectSize = float(drifttext)\n except ValueError:\n driftCorrectSize = -1\n print(\"Starting localization analysis. Config file: \"+args.xml)\n baseFilePath += \"_sa\"\n saFilePath = baseFilePath+\".hdf5\"\n mufit.analyze(filePath,saFilePath,args.xml)\n print(\"Converting hdf5 file\")\n locs, info = picasso.load_salocs(saFilePath)\n baseFilePath += \"_locs\"\n picasso.save_locs(baseFilePath+\".hdf5\",locs,info)\n else:\n print(\"Unrecognized file extension (support hdf5 (picasso of 3d_dastorm format), csv (ThunderStorm), txt (3d_daostorm), nd2, spe, tif)\")\n sys.exit(\"Unknown file type\")\n \n #check header\n headers = locs.dtype.names\n if verbose:\n print(headers)\n print(locs.shape)\n \n if 'group' in headers:\n picked = True\n else:\n picked = False\n groupNumbers = [i for i in range(samples)]\n \n #guassian blur\n x = locs['x']\n y = locs['y']\n nBins = 750\n \n fitting = True\n \n if \"fitpicks\" in baseFilePath and not args.redo_fitting:\n gridLocs,gridInfo = picasso.load_locs(baseFilePath+\"_grid.hdf5\")\n fitting = False\n picked = True\n\n if not fitting and driftCorrectSize > 0:\n driftCorrectSize = 0 \n print(\"Warning: Cannot do drift correction when reusing fits. Drift correction will not be done\")\n \n if (not fitting) and (not filterFile == \"\"):\n filterFile = \"\"\n print(\"Warning: Cannot do filtering when reusing fits. Filters will not be applied\")\n \n if picked:\n outputClusters = False #Not yet implemented for picked clusters\n NN = len(groupNumbers)\n \n if not driftCorrectSize == 0:\n driftCorrectSize = 0\n print(\"Warning: drift correction not implemented for picked localizations\")\n \n if redrift:\n redrift = False\n print(\"Warning: drift correction not implemented for picked localizations\")\n \n \n \n if args.grid_file == \"\":\n centeroids = np.array([\n \n [255.65026699, 256.2699313 ],\n [255.65522196, 255.9542909 ],\n [255.65336587, 256.16112367],\n [255.66110178, 255.74295807],\n [255.74678208, 256.05605212],\n [255.74547016, 256.16300094],\n [255.75104081, 256.2720415 ],\n [255.75228561, 255.84415798],\n [255.75351785, 255.95273798],\n [255.75479689, 255.73969906],\n [255.84866381, 256.05934078],\n [255.84685329, 256.16708376],\n [255.85103522, 256.27369471],\n [255.85160587, 255.74273925],\n [255.85740968, 255.85026562],\n [255.94392418, 256.27673285],\n [255.94391768, 256.05966314],\n [255.94611554, 256.17014591],\n [255.95094813, 255.95014021],\n [255.95158306, 255.85177168],\n [255.95400055, 255.74037337],\n [256.03677785, 256.2720229 ],\n [256.03969133, 256.06114094],\n [256.04283514, 256.16603679],\n [256.04661846, 255.85896198],\n [256.04490558, 255.96022842],\n [256.05086907, 255.7461775 ],\n [256.14012688, 256.1753788 ],\n [256.14023585, 256.0697952 ],\n [256.140229 , 256.2836567 ],\n [256.14513271, 255.75414015],\n [256.14299781, 255.96175843],\n [256.2314431 , 256.17345542],\n [256.23032086, 256.28052939],\n [256.23801515, 256.06644361],\n [256.23637598, 255.96237802],\n [256.2397271 , 255.75018973],\n [256.23966435, 255.85825364],\n [256.32819487, 256.17121161],\n [256.33097833, 255.75340018],\n [256.32980017, 256.06243964],\n [256.32933863, 255.96060716],\n [256.33441629, 255.85686116],\n [256.144 , 255.865 ],\n [255.851 , 255.954 ],\n [255.652 , 256.057 ],\n [255.659 , 255.846 ],\n [256.327 , 256.281 ]]\n \n )\n \n \n \n remap={ 33:2,\n 29:3,\n 21:4,\n 15:5,\n 12:6,\n 6:7,\n 0:8,\n 38:9,\n 32:10,\n 27:11,\n 23:12,\n 17:13,\n 11:14,\n 5:15,\n 2:16,\n 40:17,\n 34:18,\n 28:19,\n 22:20,\n 16:21,\n 10:22,\n 4:23,\n 41:25,\n 35:26,\n 31:27,\n 25:28,\n 18:29,\n 44:30,\n 8:31,\n 1:32,\n 42:33,\n 37:34,\n 43:35,\n 24:36,\n 19:37,\n 14:38,\n 7:39,\n 39:41,\n 36:42,\n 30:43,\n 26:44,\n 20:45,\n 13:46,\n 9:47,\n 3:48,\n 47:1,\n 45:24,\n 46:40 \n }\n \n centeroids = centeroids.tolist()\n \n \n \n sortedList=[]\n \n def getKey(item):\n return item[1] \n \n for elem in sorted(remap.items(),key=getKey) :\n sortedList.append(centeroids[elem[0]])\n \n \n centeroids = np.array(sortedList)\n else:\n centeroids = []\n with open(args.grid_file,\"r\",newline=\"\") as fup:\n csr = csv.reader(fup,quoting=csv.QUOTE_NONNUMERIC)\n for row in csr:\n centeroids.append(row)\n centeroids = np.array(centeroids)\n if not gridShape[0]*gridShape[1] == centeroids.shape[0]:\n gridShape = (centeroids.shape[0],1)\n \n nShifts = 0\n #filter for one origami\n \n localizationClusterList = []\n localizationClusterListFull = []\n \n nOrigamis = 15\n\n \n groupTables = [np.recarray((0,len(LOCS_DTYPE)),dtype = LOCS_DTYPE) for i in range(nOrigamis)]\n groupCount = [0 for i in range(nOrigamis)]\n\n #driftCorrectSize = 10\n if driftCorrectSize > 0:\n maxFrame = max(locs['frame'])\n totalDriftX = np.zeros(maxFrame+1)\n totalDriftY = np.zeros(maxFrame+1)\n totalDrift = np.rec.array((totalDriftX,totalDriftY),dtype=[(\"x\", \"f\"), (\"y\", \"f\")])\n \n sliceSizes = np.array([7500,1000,500,driftCorrectSize])\n sliceSizes = sliceSizes[sliceSizes*2 < maxFrame]\n \n for sliceSize in sliceSizes:\n print('Applying drift correction segment = ',sliceSize)\n drift, locs = picasso.undrift(locs,info,sliceSize)\n totalDrift['x'] += drift['x']\n totalDrift['y'] += drift['y']\n \n if skip+samples < minDriftClusters:\n skip = minDriftClusters-samples\n print('Warning: need at least {} clusters for drift correction, adding additional skipped clusters'.format(minDriftClusters))\n \n \n #Apply filters\n if not filterFile == \"\":\n print(\"Applying filters\")\n for filt in filters:\n colName = filt.tag\n low = float(filt.attrib['low'])\n high = float(filt.attrib['high'])\n if filt.attrib['type'] == 'percentile':\n locs.sort(kind=\"mergesort\", order=colName)\n NLocs = len(locs)\n locs = locs[int(NLocs*low):int(NLocs*high)]\n else:\n locs = locs[(locs[colName] >= low) & (locs[colName] < high)]\n \n locs.sort(kind=\"mergesort\", order=\"frame\")\n baseFilePath += \"_filt\"\n picasso.save_locs(baseFilePath+\".hdf5\",locs,info)\n \n\n if samples+skip > 0:\n if picked:\n ids = np.array(range(len(locs)))\n for groupNumber in groupNumbers:\n \n sublocs = locs[locs['group']==groupNumber]\n subIds = ids[locs['group']==groupNumber]\n x = sublocs['x']\n y = sublocs['y']\n #photons=sublocs['photons']\n lpx = sublocs['lpx']\n #lpy = sublocs['lpy']\n \n localizations = np.array([x,y,lpx,subIds]).T\n if localizations.shape[0]==0:\n continue;\n print(groupNumber,\"read\")\n \n if fitting:\n lc = LocalizationCluster(centeroids,localizations,globalDeltaX,True)\n else:\n subgrid = gridLocs[gridLocs['group']==groupNumber]\n gx = subgrid['x']\n gy = subgrid['y']\n grid = np.array([gx,gy]).T\n gdx = subgrid['sx'][0]\n if not grid.shape[0] == gridShape[0]*gridShape[1]:\n continue\n lc = LocalizationCluster(grid,localizations,gdx,False)\n \n lc.hist2 = subgrid['photons'].astype(float).T\n lc.hist = np.zeros(lc.hist2.shape)\n lc.transformGrid([0,0,0])\n for idx in lc.nn[1]:\n lc.hist[idx]+=1\n \n lc.signal = np.copy(lc.hist).reshape(gridShape)\n lc.rec = np.copy(lc.hist2).reshape(gridShape)\n lc.squareNNDist([0,0,0])\n \n localizationClusterList.append(lc)\n \n \n else:\n print(\"Finding\",samples,\"clusters...\")\n \n if not reuse_file:\n rc = RandomClusters(centeroids,locs,clusterRadius,minCountThreshold,maxCountThreshold,2*clusterRadius,0.85,globalDeltaX)\n else:\n rc.clusterLocations = []\n \n localizationClusterListFull = rc.findClusters(samples+skip,50000)\n if len(localizationClusterListFull) <= samples:\n localizationClusterList = localizationClusterListFull[:]\n else:\n if samples > 0:\n localizationClusterList = localizationClusterListFull[-samples:]\n else:\n localizationClusterList = []\n print(\"Found\",len(localizationClusterList))\n NN = len(localizationClusterList)\n \n if driftCorrectSize > 0:\n print('Applying fine drift correction')\n #locIds = []\n \n pickedLocs = []\n if len(localizationClusterListFull) < minDriftClusters:\n print(\"Too few clusters to drift correct, skipping cluster drift correction\")\n else:\n pickedLocs = []\n for i,lc in enumerate(localizationClusterListFull):\n locIds = lc.localizations[:,3].astype(int).tolist()\n pickedLocs.append(locs[locIds])\n drift, locs = picasso.undrift_from_picked(locs,pickedLocs,info)\n totalDrift['x'] += drift['x']\n totalDrift['y'] += drift['y']\n \n print(\"Finding drift clusters\")\n driftRc = RandomClusters(np.array([[0.0,0.0]]),locs,.05,50,600,.07,.65,globalDeltaX)\n driftClusterList = driftRc.findClusters(50000-len(localizationClusterListFull),200000)\n print(\"Found\",len(driftClusterList),\"drift clusters\")\n if len(driftClusterList) < minDriftClusters:\n print(\"Too few clusters to drift correct, skipping fine drift correction\")\n else:\n for lc in driftClusterList:\n locIds = lc.localizations[:,3].astype(int).tolist()\n pickedLocs.append(locs[locIds])\n drift, locs = picasso.undrift_from_picked(locs,pickedLocs,info)\n totalDrift['x'] += drift['x']\n totalDrift['y'] += drift['y']\n \n baseFilePath += \"_adrift\"\n picasso.save_locs(baseFilePath+\".hdf5\",locs,info)\n \n for i,lc in enumerate(localizationClusterList):\n locIds = lc.localizations[:,3].astype(int).tolist()\n subLocs = locs[locIds]\n \n x = subLocs['x']\n y = subLocs['y']\n lpx = subLocs['lpx']\n \n localizationClusterList[i] = LocalizationCluster(lc.grid,np.array([x,y,lpx,locIds]).T,globalDeltaX,True)\n \n del localizationClusterListFull\n del driftClusterList\n gc.collect()\n\n if len(localizationClusterList) == 0:\n print(\"No clusters to analyze, exiting\")\n sys.exit()\n \n #Create empty files\n with open(baseFilePath+'_match_info_'+str(NN)+'.csv','w') as fup:\n fup.write(\"\\\"Binary String\\\",\\\"ID\\\",\\\"Match Score\\\",\\\"Exact String\\\",\\\"False Negatives\\\",\\\"False Positives\\\",\\\"Row Shifts\\\",\\\"Column Shifts\\\",\\\"Fit Quality\\\",\\\"X Position\\\",\\\"Y Position\\\",\\\"Group Number\\\"\\n\")\n with open(baseFilePath+'_bin_info_'+str(NN)+'.csv','w') as fup:\n fup.write(\"\\\"Binary String\\\",\\\"Row Shifts\\\",\\\"Column Shifts\\\",\\\"Fit Quality\\\",\\\"X Position\\\",\\\"Y Position\\\"\\n\")\n open(baseFilePath+'_bin_'+str(NN),'w').close()\n if display2:\n open(baseFilePath+'_fig_data.csv',\"w\").close()\n \n processes = []\n parentConnections = []\n \n print(\"starting fits\")\n \n\n useMultiProcessing = True\n \n print(len(localizationClusterList))\n\n \n if fitting:\n if useMultiProcessing:\n \n pool = Pool(cpu_count()-1)\n \n results = []\n for index in range(len(localizationClusterList)):\n results.append(pool.apply_async(clusterFit,(localizationClusterList[index],index,gridShape,distThreshold)))\n \n for res in results:\n msg = res.get()\n print(msg[0],'fitting done obj:',msg[4],\"FVal:\",msg[5],\"GlobalDeltaX:\",msg[6])\n lc = localizationClusterList[msg[0]]\n lc.globalDeltaX = msg[6]\n lc.hist2 = msg[7]\n lc.squareNNDist(msg[1:4])\n lc.hist = np.zeros(lc.hist2.shape)\n for idx in lc.nn[1]:\n lc.hist[idx]+=1\n \n lc.signal = np.copy(lc.hist[:-1]).reshape(gridShape)\n lc.rec = np.copy(lc.hist2[:-1]).reshape(gridShape)\n \n else:\n for index in range(len(localizationClusterList)):\n msg = clusterFit(localizationClusterList[index],index,gridShape,distThreshold)\n print(msg[0],'fitting done obj:',msg[4],\"FVal:\",msg[5],\"GlobalDeltaX:\",msg[6])\n #localizationClusterList[msg[0]].globalDeltaX = msg[6]\n #localizationClusterList[msg[0]].squareNNDist(msg[1:4])\n \n \n rejectedCount = 0\n \n \n \n fnErrorMaps = [np.zeros(gridShape) for i in range(nOrigamis+1)]\n fpErrorMaps = [np.zeros(gridShape) for i in range(nOrigamis+1)]\n errNormMap = np.zeros(gridShape)\n errorCounts = [0 for i in range(nOrigamis)]\n \n perfectHists = []\n perfectImages = []\n #with open('perfect_data.txt','r') as fup:\n # perfectStrings = fup.readlines()\n perfectStrings = ['001101101111011100111010001101111101111000101010',\n '001001101010100110110100000111011111110000000001',\n '010111111101100100011100101111001110010000010111',\n '001000011000010110011110100100011110001000011010',\n '000110101111101100111110000100001101100010010010',\n '010111111101010110111000001010011100001010110100',\n '000100001110101100011010111000111000011010100101',\n '010101001010000111100000110110001101100010000100',\n '001000001011111101000100010100111110010001100101',\n '001000001101101110101100000100111101000001111101',\n '011011101101010100000110110111101111110001101000',\n '000100011110011110011010100000001010111001010100',\n '010011101100110101000100000000011100010011011000',\n '010100101001111111001100010100111100111011011011',\n '000010101101010101101100100010111001010011101111']\n\n for row in perfectStrings:\n perfectHists.append([])\n for char in row:\n if char == '1':\n perfectHists[-1].append(1)\n elif char =='0':\n perfectHists[-1].append(-1)\n perfectImages.append(np.array(perfectHists[-1]).reshape(gridShape))\n \n# =============================================================================\n# if redrift:\n# print(\"Redrift correcting...\")\n# combinedGrid = []\n# clusterLocIds = []\n# for lc in localizationClusterList:\n# grid = np.copy(lc.gridTran)\n# grid[:,0]+=lc.xLAve\n# grid[:,1]+=lc.yLAve\n# combinedGrid.extend(grid.tolist())\n# clusterLocIds.extend(lc.localizations[:,3].astype(int).tolist())\n# \n# if driftCorrectSize == 0:\n# maxFrame = max(locs['frame'])\n# clusterLocs = locs[clusterLocIds]\n# clusterLocs.sort(kind=\"mergesort\", order=\"frame\")\n# #frameLocs = []\n# drift = np.rec.array(np.zeros(maxFrame+1), dtype=[(\"x\", \"f\"), (\"y\", \"f\")])\n# for frameId in range(maxFrame):\n# frameLocs = clusterLocs[clusterLocs['frame']==frameId]\n# if frameLocs.shape[0] == 0:\n# continue\n# x = frameLocs['x']\n# y = frameLocs['y']\n# lpx = frameLocs['lpx']\n# \n# localizations = np.array([x,y,lpx]).T\n# frameCluster = LocalizationCluster(combinedGrid,localizations,globalDeltaX,False)\n# bounds = [(-.1,.1),(-.1,.1),(0,0)]\n# out = minimize(frameCluster.squareNNDist,[0,0,0],bounds=bounds,method='L-BFGS-B')\n# drift[frameId]['x'] = out.x[0]\n# drift[frameId]['y'] = out.x[1]\n# \n# locs.x -= drift.x[locs.frame]\n# locs.y -= drift.y[locs.frame]\n# #frameCluster\n# \n# for i,lc in enumerate(localizationClusterList):\n# locIds = lc.localizations[:,3].astype(int).tolist()\n# subLocs = locs[locIds]\n# \n# x = subLocs['x']\n# y = subLocs['y']\n# lpx = subLocs['lpx']\n# \n# localizations = np.array([x,y,lpx,locIds]).T\n# localizations[:,0] -= lc.xLAve\n# localizations[:,1] -= lc.yLAve\n# \n# localizationClusterList[i] = LocalizationCluster(lc.grid,localizations,globalDeltaX,True)\n# \n# picasso.save_locs(baseFilePath+\"_Redrift.hdf5\",locs,info)\n# =============================================================================\n \n aveLPX2 = np.average(locs['lpx']**2)\n aveObj = np.average(np.array([lc.objectiveValue for lc in localizationClusterList]))\n aveGDX = np.average(np.array([lc.globalDeltaX for lc in localizationClusterList]))\n #globalDeltaX = np.sqrt(aveLPX2*(aveObj-1))\n \n print(\"Average lpx**2:\",aveLPX2,\"average obj:\",aveObj,\"Average Global Delta X\",aveGDX)\n \n for lcInd in range(len(localizationClusterList)):\n lc = localizationClusterList[lcInd]\n if fitting:\n #lc.pixelate(gridShape,distThreshold)\n print(\"bg:\",lc.hist2[-1])\n fitQuality = lc.squareNNDistUnweighted([lc.dx,lc.dy,lc.dt],.0937)\n if verbose: \n print(lcInd,fitQuality)\n if fitQuality > objectiveThreshold:\n rejectedCount+=1\n continue\n \n gridPoints = np.copy(lc.gridTran).reshape(gridShape[0],gridShape[1],2)\n \n rx=0\n ry=0\n cx=0\n cy=0\n \n \n for rid in range(1,gridShape[0]):\n for cid in range(0,gridShape[1]):\n rx += gridPoints[rid,cid,0]-gridPoints[rid-1,cid,0]\n ry += gridPoints[rid,cid,1]-gridPoints[rid-1,cid,1]\n \n for rid in range(0,gridShape[0]):\n for cid in range(1,gridShape[1]):\n cx += gridPoints[rid,cid,0]-gridPoints[rid,cid-1,0]\n cy += gridPoints[rid,cid,1]-gridPoints[rid,cid-1,1]\n \n if gridShape[0] > 1:\n rx/=(gridShape[0]-1)*gridShape[1]\n ry/=(gridShape[0]-1)*gridShape[1]\n if gridShape[1] > 1:\n cx/=gridShape[0]*(gridShape[1]-1)\n cy/=gridShape[0]*(gridShape[1]-1)\n \n minDeltaR = 0\n minDeltaC = 0\n \n dx = lc.dx\n dy = lc.dy\n dt = lc.dt\n \n if fitting:\n minObj = lc.gridLikelihoodScore([dx,dy,dt])\n for deltaR in range(-2,3):\n for deltaC in range(-2,3):\n obj3 = lc.gridLikelihoodScore([dx+deltaR*rx+deltaC*cx,dy+deltaR*ry+deltaC*cy,dt])\n if obj3 < minObj:\n minObj = obj3\n minDeltaR = deltaR\n minDeltaC = deltaC\n \n obj3 = lc.squareNNDist([dx+minDeltaR*rx+minDeltaC*cx,dy+minDeltaR*ry+minDeltaC*cy,dt])\n gridPoints = np.copy(lc.gridTran).reshape(gridShape[0],gridShape[1],2)\n \n\n# =============================================================================\n# superGridPoints = np.zeros((gridShape[0]+2,gridShape[1]+2,2))\n# \n# for rid in range(0,gridShape[0]):\n# for cid in range(0,gridShape[1]):\n# superGridPoints[rid+1,cid+1,:] = gridPoints[rid,cid,:]\n# \n# for rid in range(gridShape[0]+2):\n# superGridPoints[rid,0,0] = gridPoints[0,0,0] - rx - cx + rid * rx\n# superGridPoints[rid,0,1] = gridPoints[0,0,1] - ry - cy + rid * ry\n# superGridPoints[rid,-1,0] = gridPoints[-1,-1,0] + rx + cx - rid * rx\n# superGridPoints[rid,-1,1] = gridPoints[-1,-1,1] + ry + cy - rid * ry\n# \n# for cid in range(1,gridShape[1]+1):\n# superGridPoints[0,cid,0] = gridPoints[0,0,0] - rx - cx + cid * cx\n# superGridPoints[0,cid,1] = gridPoints[0,0,1] - ry - cy + cid * cy\n# superGridPoints[-1,cid,0] = gridPoints[-1,-1,0] + rx + cx - cid * cx\n# superGridPoints[-1,cid,1] = gridPoints[-1,-1,1] + ry + cy - cid * cy\n# \n# superGrid = np.copy(superGridPoints).reshape((superGridPoints.shape[0]*superGridPoints.shape[1],superGridPoints.shape[2]))\n# \n# lc2 = LocalizationCluster(superGrid,lc.localizations,lc.globalDeltaX,False)\n# \n# obj2 = lc2.squareNNDist([0,0,0])\n# if verbose:\n# print(lcInd,lc.objectiveValue,obj2)\n# \n# =============================================================================\n \n #lc.pixelate(gridShape)\n lc2 = lc\n \n \n if display2:\n fig = plt.figure()\n plt.scatter(-lc2.localizations[:,0],lc2.localizations[:,1],s=3,color='blue')\n plt.scatter(-lc2.gridTran[:,0],lc2.gridTran[:,1],color='orange')\n fig.show()\n \n fig, axt = plt.subplots(3,2)\n axt[0,0].bar([i for i in range(len(lc2.hist))],lc2.hist.tolist())\n\n axt[1,0].imshow(lc2.signal)\n axt[1,1].imshow(lc2.rec)\n \n axt[0,1].bar([i for i in range(len(lc2.hist2))],lc2.hist2.tolist())\n \n with open(baseFilePath+'_fig_data.csv',\"a\",newline='') as ffup:\n csr = csv.writer(ffup)\n csr.writerow([\"Cluster {} data:\".format(lcInd)])\n csr.writerow([\"Raw pixelation\"])\n csr.writerows(lc2.signal.tolist())\n csr.writerow([\"Optimal pixelation\"])\n csr.writerows(lc2.rec.tolist())\n csr.writerow([\"Grid Points\"])\n csr.writerows(lc2.gridTran.tolist())\n csr.writerow([\"Localization data\"])\n csr.writerows(lc2.localizations.tolist())\n \n \n sortHist = np.sort(lc2.hist2)\n aveBrightBit = np.average(sortHist[-10:])\n aveOnBit = np.average(lc2.hist2[lc2.hist2>1])\n threshold = scaled_threshold*aveBrightBit\n print(aveBrightBit,scaled_threshold,threshold)\n \n \n rawImage = np.copy(lc2.rec)\n binaryImage = np.copy(lc2.rec)\n for rid in range(binaryImage.shape[0]):\n for cid in range(binaryImage.shape[1]):\n if rawImage[rid,cid] > threshold:\n binaryImage[rid,cid] = 1\n else:\n binaryImage[rid,cid] = 0\n \n if display2: \n axt[2,1].imshow(binaryImage)\n \n# =============================================================================\n# superRes = np.zeros((60,60))\n# \n# for rid in range(lc2.localizations.shape[0]):\n# x = int(-lc2.localizations[rid,1]*pixelsize/2+superRes.shape[0]/2)\n# y = int(-lc2.localizations[rid,0]*pixelsize/2+superRes.shape[1]/2)\n# if x > 0 and x<superRes.shape[0] and y > 0 and y < superRes.shape[1]:\n# superRes[x,y] += 1\n# =============================================================================\n if picked:\n tmp, superRes = picasso.render_gaussian(locs[locs[\"group\"]==lcInd], 160, lc.yLAve-.6,lc.xLAve-.6, lc.yLAve+.6, lc.xLAve+.6, .015)\n else:\n tmp, superRes = picasso.render_gaussian(locs[lc.localizations[:,3].astype(int)], 160, lc.yLAve-.6,lc.xLAve-.6, lc.yLAve+.6, lc.xLAve+.6, .015)\n axt[2,0].imshow(superRes)\n \n fig.show()\n \n if sum(sum(binaryImage)) == 0:\n rejectedCount += 1\n continue\n #Testing code, remove\n #binaryImage = np.array([[0,0,1,0,1,0,1,0],[0,1,0,1,0,0,0,0],[0,1,1,1,0,0,0,0],[0,1,1,0,1,1,0,0],[0,1,1,0,1,1,0,0],[0,1,0,0,0,0,1,0]])\n #binaryImage = np.array([[1,1,1,0,1,0,1,1],[0,0,0,1,1,0,1,0],[1,1,1,0,0,0,1,1],[1,0,0,0,0,1,1,0],[1,0,1,0,0,1,0,1],[0,0,0,0,0,0,0,0]])\n #rawImage = np.copy(binaryImage)*1000\n #end testing code\n \n rShifts = [0]\n cShifts = [0]\n \n rSums = np.sum(binaryImage,axis=1)\n cSums = np.sum(binaryImage,axis=0)\n \n if rSums[0] == 0:\n rShifts.append(-1)\n if rSums[-1] == 0:\n rShifts.append(1)\n if cSums[0] == 0:\n cShifts.append(-1)\n if cSums[-1] == 0:\n cShifts.append(1) \n \n \n maxSScore = 0\n maxId = 0\n \n fPos = 0\n fNeg = 0\n maxRShift = 0\n maxCShift = 0\n \n rotation = 0\n \n for rShift in rShifts:\n for cShift in cShifts:\n binaryImageShifted = np.roll(binaryImage,(rShift,cShift),(0,1))\n rawImageShifted = np.roll(rawImage,(rShift,cShift),(0,1))\n \n Id = 0\n for pImage in perfectImages:\n sScore = np.sum(pImage*(rawImageShifted-aveOnBit))\n if sScore > maxSScore:\n maxId = Id\n maxSScore = sScore\n fPos = np.sum(binaryImageShifted * pImage == -1)\n fNeg = np.sum((binaryImageShifted-1) * pImage == -1)\n maxRShift = rShift\n maxCShift = cShift\n rotation = np.pi\n sScore = np.sum(np.flip(pImage,(0,1))*(rawImageShifted-aveOnBit))\n if sScore > maxSScore:\n maxId = Id\n maxSScore = sScore\n \n fPos = np.sum(binaryImageShifted * np.flip(pImage,(0,1)) == -1)\n fNeg = np.sum((binaryImageShifted-1) * np.flip(pImage,(0,1)) == -1)\n maxRShift = rShift\n maxCShift = cShift\n \n rotation = 0\n Id+=1\n \n \n binaryData = binaryImageShifted.reshape((binaryImage.shape[0]*binaryImage.shape[1]))\n binaryString=\"\"\n \n if not (rShift == 0 and cShift == 0):\n nShifts += 1\n if display2:\n plt.figure()\n plt.imshow(binaryImageShifted)\n \n for bit in binaryData:\n if bit==0:\n binaryString+='0'\n else:\n binaryString+='1'\n \n with open(baseFilePath+'_bin_'+str(NN),'a') as fup:\n fup.write(binaryString+'\\n')\n with open(baseFilePath+'_bin_info_'+str(NN)+'.csv','a') as fup:\n fup.write(\"\\\"\"+binaryString+\"\\\",\"+str(rShift)+\",\"+str(cShift)+\",\"+str(fitQuality)+\",\"+str(lc.xLAve)+\",\"+str(lc.yLAve)+\"\\n\")\n \n if verbose: \n print(maxId,maxSScore)\n \n binaryImageShifted = np.roll(binaryImage,(maxRShift,maxCShift),(0,1))\n \n \n if fPos + fNeg < 16:\n pImage = perfectImages[maxId]\n binaryImageShiftedFlipped = np.copy(binaryImageShifted)\n if rotation == 0:\n binaryImageShiftedFlipped = np.flip(binaryImageShiftedFlipped,(0,1))\n \n fpErrorMaps[-1] += (binaryImageShiftedFlipped * pImage == -1)\n fpErrorMaps[maxId] += (binaryImageShiftedFlipped * pImage == -1)\n fnErrorMaps[-1] += ((binaryImageShiftedFlipped-1) * pImage == -1)\n fnErrorMaps[maxId] += ((binaryImageShiftedFlipped-1) * pImage == -1)\n errorCounts[maxId]+=1\n errNormMap += (pImage>0)\n \n binaryData = binaryImageShifted.reshape((binaryImage.shape[0]*binaryImage.shape[1]))\n binaryString=\"\"\n for bit in binaryData:\n if bit==0:\n binaryString+='0'\n else:\n binaryString+='1'\n \n print(\"\\\"b\"+binaryString+\"\\\",\"+str(maxId)+\",\"+str(maxSScore)+\",\\\"b\"+perfectStrings[maxId][0:-1]+\"\\\",\"+str(fNeg)+\",\"+str(fPos)+\",\"+str(maxRShift)+\",\"+str(maxCShift)+\",\"+str(fitQuality)+\",\"+str(lc.xLAve)+\",\"+str(lc.yLAve)+\",\"+str(groupCount[maxId])+\"\\n\")\n with open(baseFilePath+'_match_info_'+str(NN)+'.csv','a') as fup:\n fup.write(\"\\\"b\"+binaryString+\"\\\",\"+str(maxId)+\",\"+str(maxSScore)+\",\\\"b\"+perfectStrings[maxId][0:-1]+\"\\\",\"+str(fNeg)+\",\"+str(fPos)+\",\"+str(maxRShift)+\",\"+str(maxCShift)+\",\"+str(fitQuality)+\",\"+str(lc.xLAve)+\",\"+str(lc.yLAve)+\",\"+str(groupCount[maxId])+\"\\n\")\n \n \n \n cw = np.sqrt(cx**2+cy**2)\n rw = np.sqrt(rx**2+ry**2)\n if outputClusters and fPos + fNeg < 11:\n locTable = locs[lc.localizations[:,3].astype(int)]\n locCount = locTable.shape[0]\n groupNumber = groupCount[maxId]\n groupTable = np.rec.array((locTable['frame'], locTable['x'], locTable['y'], locTable['photons'], locTable['sx'], locTable['sy'],locTable['bg'],locTable['lpx'],locTable['lpy'],groupNumber*np.ones(locTable['frame'].shape)),dtype=LOCS_DTYPE,)\n\n \n xArr = np.array(groupTable['x'])\n yArr = np.array(groupTable['y'])\n\n \n deltaX = -lc.dx-lc.xLAve\n deltaY = -lc.dy-lc.yLAve\n \n for ind in range(xArr.shape[0]):\n\n xTemp = xArr[ind] + deltaX\n yTemp = yArr[ind] + deltaY\n xArr[ind] = (np.cos(lc.dt+rotation)*xTemp - np.sin(lc.dt+rotation)*yTemp)+256.0+maxCShift*cw\n yArr[ind] = (np.cos(lc.dt+rotation)*yTemp + np.sin(lc.dt+rotation)*xTemp)+256.0-maxRShift*rw\n\n \n groupTable['x'] = xArr\n groupTable['y'] = yArr\n \n \n \n groupCount[maxId]+=1\n\n groupTables[maxId].resize((groupTables[maxId].shape[0]+locCount),refcheck=False)\n groupTables[maxId][-locCount:] = groupTable\n \n \n if fitting:\n \n nLocs = 0\n nGridPoints = 0\n for lc in localizationClusterList:\n nLocs+=lc.localizations.shape[0]\n nGridPoints+=lc.gridTran.shape[0]\n \n \n zc = np.zeros((nLocs,))\n groupLocs = np.rec.array(\n (zc,zc,zc,zc,zc,zc,zc,zc,zc,zc),\n dtype=LOCS_DTYPE,\n )\n \n zc = np.zeros((nGridPoints,))\n gridLocs = np.rec.array(\n (zc,zc,zc,zc,zc,zc,zc,zc,zc,zc),\n dtype=LOCS_DTYPE,\n )\n \n locPtr = 0\n gridPtr = 0\n \n for lcInd,lc in enumerate(localizationClusterList):\n locTable = locs[lc.localizations[:,3].astype(int)]\n locCount = locTable.shape[0]\n groupTable = np.rec.array((locTable['frame'], locTable['x'], locTable['y'], locTable['photons'], locTable['sx'], locTable['sy'],locTable['bg'],locTable['lpx'],locTable['lpy'],lcInd*np.ones(locTable['frame'].shape)),dtype=LOCS_DTYPE,)\n groupLocs[locPtr:(locPtr+locCount)] = groupTable\n locPtr+=locCount\n \n gridCount = lc.gridTran.shape[0]\n zc = np.zeros((gridCount,))\n oc = np.ones((gridCount,))\n gridTable = np.rec.array((zc,lc.gridTran[:,0]+lc.xLAve,lc.gridTran[:,1]+lc.yLAve,lc.hist2[:-1],oc*lc.globalDeltaX,oc*lc.globalDeltaX,oc,oc*.003,oc*.003,lcInd*oc))\n gridLocs[gridPtr:(gridPtr+gridCount)] = gridTable\n gridPtr+=gridCount\n \n if \"fitpicks\" in baseFilePath:\n picasso.save_locs(baseFilePath+\".hdf5\",groupLocs,info)\n picasso.save_locs(baseFilePath+\"_grid.hdf5\",gridLocs,info)\n else:\n picasso.save_locs(baseFilePath+\"_fitpicks_\"+str(NN)+\".hdf5\",groupLocs,info)\n picasso.save_locs(baseFilePath+\"_fitpicks_\"+str(NN)+\"_grid.hdf5\",gridLocs,info)\n \n \n if outputClusters:\n for tableId in range(len(groupTables)):\n if groupTables[tableId].shape[0] > 0:\n table = groupTables[tableId]\n\n prefix = baseFilePath+'_Matrix_{0:02d}'.format(tableId)\n\n table.sort(kind=\"mergesort\", order=\"frame\")\n\n picasso.save_locs(prefix+'.hdf5', table, info)\n \n\n \n \n with open(baseFilePath+'_errmap_'+str(NN)+'.csv','w',newline='') as fup:\n csr = csv.writer(fup,quoting=csv.QUOTE_NONNUMERIC)\n csr.writerow(['False Negatives'])\n csr.writerow(['All Matrices'])\n temp = np.copy(errNormMap)\n temp[temp==0] = 1\n tempMap = fnErrorMaps[-1]/temp\n tempMap[errNormMap==0] = 0\n csr.writerows(tempMap)\n for idx in range(nOrigamis):\n csr.writerow(['Matrix {0:02d}'.format(idx)])\n \n if not errorCounts[idx] == 0:\n csr.writerows(fnErrorMaps[idx]/errorCounts[idx])\n else:\n csr.writerows(np.zeros(fnErrorMaps[idx].shape))\n csr.writerow(['False Positives'])\n csr.writerow(['All Matrices'])\n temp = -errNormMap+sum(errorCounts)\n temp[temp==0] = 1\n tempMap = fpErrorMaps[-1]/temp\n tempMap[-errNormMap+sum(errorCounts)==0] = 0\n csr.writerows(tempMap)\n for idx in range(nOrigamis):\n csr.writerow(['Matrix {0:02d}'.format(idx)])\n \n if not errorCounts[idx] == 0:\n csr.writerows(fpErrorMaps[idx]/errorCounts[idx])\n else:\n csr.writerows(np.zeros(fnErrorMaps[idx].shape))\n \n \n if picked: \n print(len(groupNumbers),rejectedCount,nShifts,aveObj,aveGDX)\n else:\n print(len(localizationClusterList),rejectedCount,nShifts,aveObj,aveGDX)\n \n if display2: \n input()\n" ]
[ [ "numpy.dot", "matplotlib.pyplot.imshow", "numpy.sqrt", "numpy.random.sample", "numpy.exp", "numpy.roll", "scipy.spatial.cKDTree", "numpy.sin", "numpy.copy", "numpy.zeros", "matplotlib.pyplot.figure", "numpy.log", "numpy.multiply", "numpy.rec.array", "scipy.optimize.minimize", "scipy.spatial.ConvexHull", "numpy.array", "numpy.flip", "numpy.sum", "numpy.abs", "numpy.random.seed", "matplotlib.pyplot.scatter", "matplotlib.pyplot.subplots", "numpy.sort", "numpy.ones", "numpy.cos", "numpy.average" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
0xLeo/generative-art
[ "29cfabd0cd1d7dd72bfcdfb96ed3bbf86e5196f0" ]
[ "beziers_aquarium/src/fish.py" ]
[ "#!/usr/bin/env python3\nfrom PIL import Image\nimport aggdraw\nimport numpy as np\nimport doctest\nfrom typing import List, Tuple, Union\nfrom collections import namedtuple\nfrom numpy import round\nfrom numpy.random import randint\nimport numpy as np\nfrom canvas import Canvas\nimport itertools as it\n\nRect = namedtuple('Rect', ('x0', 'y0', 'x1', 'y1'))\n\ndef reset(func):\n # intercepts the method arguments - the first is self so it's a class method\n def inner(self, *args, **kwargs):\n # reset later\n brush_col = self._info['brush']\n out_col = self._info['pen']['color']\n out_w = self._info['pen']['width']\n func(self, *args, **kwargs)\n self._brush = aggdraw.Brush(brush_col)\n self._pen = aggdraw.Pen(out_col, out_w)\n self._info['brush'] = brush_col\n self._info['pen']['color'] = out_col \n self._info['pen']['width'] = out_w\n return inner\n\n\nclass Fish(Canvas):\n \"\"\" Draw a random fish using Bezier curves. Usage:\n fish = Fish()\n fish.draw(show=True)\n # to save:\n fish.save()\n \"\"\"\n\n def __init__(self, \n size = (640, 480),\n sub_canvas = Rect(0, 0, .25, .25),\n outline = 4,\n body_width = 0.8,\n body_height = 0.7,\n col_body: Union[None, Tuple[int, int, int]] = None,\n col_belly: Union[None, Tuple[int, int, int]] = None): \n \"\"\"\n b0 b4 p9 p8 b3\n +------------+------------*--------*---------+ \n | | f i n |\n *p7 t | p2 p1 |\n | b5+----------*-------------*------+b9\n | | |\n | a | |\n *p12 *p3 b o d y *p0 \n | | |\n | i | p4 p5 |\n | b6+----------*-------------*------+b8\n *p6 | |\n | l | f i n |\n +------------+------------*--------*---------+\n b1 b7 p11 p10 b2\n * = main control points (excluding the randomness)\n + = reference points (control points are defined w.r.t them - b as in box)\n >>> fish = Fish()\n >>> area = lambda r: (abs(r.x0 - r.x1) * abs(r.y1 - r.y0))\n >>> area(fish._bboxes['whole']) == area(fish._bboxes['tail']) + area(fish._bboxes['body']) + area(fish._bboxes['fin_upper']) + area(fish._bboxes['fin_lower']) \n True\n \"\"\"\n if col_body is None:\n col_body = (randint(128, 256), randint(128, 256), randint(128, 256)) \n self._col_body = col_body\n self._col_outline = self.triplet2hex((col_body[0] - 90, col_body[1] - 90, col_body[2] - 90)) \n self._width_outline = outline\n super(Fish, self).__init__(\n size = size,\n fill_color = self._col_body,\n outline_width = self._width_outline,\n outline_color = self._col_outline,\n pos = (sub_canvas.x0, sub_canvas.y0)\n )\n # Rect functions\n rect_to_int = lambda rect: Rect(int(round(rect.x0)), int(round(rect.y0)),\n int(round(rect.x1)), int(round(rect.y1)))\n rect_scale = lambda r, width_height:\\\n rect_to_int(Rect(r.x0*width_height[0], r.y0*width_height[1],\n r.x0 + r.x1*width_height[0], r.y0 + r.y1*width_height[1]))\n # break the sub-canvas into smaller bounding boxes\n cwidth, cheight = sub_canvas.x1 - sub_canvas.x0, sub_canvas.y1 - sub_canvas.y0\n bbox_whole = rect_scale(sub_canvas, self._canvas_size)\n fin_height = (1-body_height)/2\n rect_tail = Rect(sub_canvas.x0, sub_canvas.y0, (1-body_width)*cwidth, cheight)\n bbox_tail = rect_scale(rect_tail, self._canvas_size)\n rect_body = Rect(rect_tail.x1, fin_height*cheight, sub_canvas.x1, (1-fin_height)*cheight)\n bbox_body = rect_scale(rect_body, self._canvas_size)\n rect_fin_upper = Rect(rect_tail.x1, sub_canvas.y0, sub_canvas.x1, fin_height*cheight)\n bbox_fin_upper = rect_scale(rect_fin_upper, self._canvas_size) \n rect_fin_lower = Rect(rect_tail.x1, (1-fin_height)*cheight, sub_canvas.x1, cheight)\n bbox_fin_lower = rect_scale(rect_fin_lower, self._canvas_size) \n # save these to the class\n self._bboxes = {'whole': bbox_whole, 'tail': bbox_tail, 'body': bbox_body,\n 'fin_upper': bbox_fin_upper, 'fin_lower': bbox_fin_lower}\n # auxiliary points - control points are defined w.r.t them\n b0, b1, _, _ = self.rect2vecs(bbox_tail)\n _, _, b2, b3 = self.rect2vecs(bbox_whole)\n b4, b5, _, _ = self.rect2vecs(bbox_fin_upper)\n b6,b7, _, b8 = self.rect2vecs(bbox_fin_lower)\n _, _, _, b9 = self.rect2vecs(bbox_body)\n # control points - they define the Bezier curves of the fish\n self._control_points = self.get_control_points((b0, b1, b2, b3, b4, b5, b6, b7, b8, b9))\n if col_belly is None:\n col_belly = (randint(128, 256), randint(128, 256), randint(128, 256)) \n self._col_belly = col_belly\n self._curve = {}\n # [x0, y0, x1, y1,...] for the upper curve of the body\n self._curve['upper'] = []\n # [x0, y0, x1, y1,...] for the upper curve of the body\n self._curve['lower'] = []\n # DEBUG ONLY:\n self._curve['lower_old'] = []\n\n\n @staticmethod\n def triplet2hex(triplet: Tuple[int, int, int]):\n return '#%02x%02x%02x' % (triplet[0], triplet[1], triplet[2])\n\n\n @staticmethod\n def hex2triplet(hexstr: str):\n \"\"\"hex2triplet.\n\n Parameters\n ----------\n hexstr : str\n e.g. #ab1099\n \"\"\"\n return int(hexstr[1:3],16), int(hexstr[3:5], 16), int(hexstr[5:], 16)\n\n\n @staticmethod\n def rect2vecs(rect: Rect):\n tuples = ((rect.x0, rect.y0), (rect.x0, rect.y1), (rect.x1, rect.y1), (rect.x1, rect.y0))\n return (np.array(t) for t in tuples)\n\n\n @staticmethod\n def list_from_to(arr, fr = 0, to = 1, how_many = -1):\n assert to > fr and 0 <= fr <= 1 and 0 <= to <= 1\n round = lambda x: int(np.round(x))\n n = len(arr)\n arr = arr[round(fr*n):round(to*n)]\n if how_many > 0:\n arr = arr[::round(n/how_many)]\n return arr\n\n\n def get_control_points(self, aux_points: Tuple[np.ndarray]) -> Tuple[np.ndarray]:\n assert len(aux_points) == 10, 'The specification requires 10 auxiliary points'\n # t left to right and up to down\n segment_point = lambda p0p1, t: (p0p1[0] + t*(p0p1[1]-p0p1[0])).astype(np.int32)\n ret = []\n # append control points p0, p1, ...\n b = aux_points\n ran_p0p3 = np.random.uniform(-0.1, 0.15)\n ran_p1p5 = np.random.uniform(-0.25, 0.075)\n ran_p2p4 = np.random.uniform(-0.2, 0.2)\n t_p3 = .57 + ran_p0p3\n tail_w = abs(self._bboxes['tail'].x1-self._bboxes['tail'].x0)\n ret.append(segment_point((b[3], b[2]), .57 + ran_p0p3)) # 0\n ret.append(segment_point((b[5], b[9]), .8 + ran_p1p5)) # 1\n ret.append(segment_point((b[5], b[9]), .3 + ran_p2p4)) # 2\n ret.append(segment_point((b[4], b[7]), t_p3)) # 3\n ret.append(segment_point((b[6], b[8]), .3 + ran_p2p4)) # 4\n ret.append(segment_point((b[6], b[8]), .8 + ran_p1p5)) # 5\n ret.append(segment_point((b[0], b[1]), .95)) # 6\n ret.append(segment_point((b[0], b[1]), .05)) # 7\n ret.append(segment_point((b[4], b[3]), .75)) # 8\n ret.append(segment_point((b[4], b[3]), .05)) # 9\n ret.append(segment_point((b[7], b[2]), .75)) # 10\n ret.append(segment_point((b[7], b[2]), .35)) # 11\n ret.append(segment_point((b[0], b[1]), t_p3) +\\\n (np.random.randint(0, 0.6*tail_w), 0)\n )\n return ret\n\n \n @reset\n def draw_body(self):\n ## body (as upper and lower curve)\n p0, p1, p2, p3, p4, p5 = self._control_points[:6]\n self._curve['upper'] = self.draw_curve((p0, p1-p0, p2-p0, p3-p0),\n fill = self._col_body, outline_col = self._col_outline,\n remove_straight_line = False, as_tuples = True)\n self._curve['lower'] = self.draw_curve((p3, p4-p3, p5-p3, p0-p3), fill = self._col_body, remove_straight_line = False, as_tuples = True)\n ## belly\n n = len(self._curve['lower'])\n b31 = self._curve['lower'][int(n/4)]\n b32 = self._curve['lower'][int(3*n/4)] \n fill_body = self._info['brush']\n self.draw_cressent((p3, p4-p3, p5-p3, p0-p3, b32-p3, b31-p3), fill_col = self._col_belly, fill_inner = fill_body)\n\n\n @reset\n def draw_eye(self, size = 1/20):\n assert 0 < size < 1, \"Eye size is a fraction of the body's width\"\n p0, p1, p2, p3 = self._control_points[:4]\n p_p0p3 = p0 + 0.2*(p3-p0) # how left or right\n ind_p_upper = np.argmin([abs(p_p0p3[0] - p[0]) for p in self._curve['upper']])\n p_upper = self._curve['upper'][ind_p_upper]\n p_eye = p_p0p3 + 1/2*(p_upper - p_p0p3)\n width_body = abs(self._bboxes['body'].x1 - self._bboxes['body'].x0) \n rad = width_body*size\n pen = aggdraw.Pen('black', 0)\n brush = aggdraw.Brush(self._info['pen']['color'])\n self._draw.ellipse((p_eye[0]-rad, p_eye[1]-rad, p_eye[0]+rad, p_eye[1]+rad), brush, pen)\n brush = aggdraw.Brush('white') if np.random.random() < 0.85 else aggdraw.Brush('yellow')\n rad = 0.7*rad\n self._draw.ellipse((p_eye[0]-rad, p_eye[1]-rad, p_eye[0]+rad, p_eye[1]+rad), brush, pen)\n brush = aggdraw.Brush('#444444')\n rad = 0.7*rad\n self._draw.ellipse((p_eye[0]-rad, p_eye[1]-rad, p_eye[0]+rad, p_eye[1]+rad), brush, pen)\n self._draw.flush()\n\n\n @reset\n def draw_fins(self):\n # reset later\n out_col = self._info['pen']['color']\n out_w = self._info['pen']['width']\n\n # fin colour\n r, g, b = np.random.randint(20, 40), np.random.randint(20, 40), np.random.randint(20, 40)\n\n try:\n # TODO: self._info['brush'] is supposed to be a hex - BUG\n col_fin = self.hex2triplet(self._info['brush']) + np.array((r, g, b))\n except:\n col_fin = self._info['brush'] + np.array((r, g, b))\n col_fin = [min(c, 255) for c in col_fin]\n col_fin = self.triplet2hex(col_fin)\n\n cp0, cp1, cp2, cp3, cp4, cp5, cp6, cp7, cp8, cp9, cp10, cp11 = self._control_points[:12]\n height_body = abs(self._bboxes['body'].y1 - self._bboxes['body'].y0) \n width_body = abs(self._bboxes['body'].x1 - self._bboxes['body'].x0) \n ## upper fin\n # split each curve in n pieces and connect pieces with the same index together\n curve_upper = self._curve['upper']\n n_upper = len(curve_upper)\n ind_p0 = int(0.27*n_upper + np.random.uniform(-0.12*n_upper, 0.02*n_upper))\n ind_p3 = int(0.70*n_upper + np.random.uniform(-0.1*n_upper, 0.2*n_upper))\n cp9 = cp9 + (0, 0.25*height_body)\n p0 = curve_upper[ind_p0]\n p3 = curve_upper[ind_p3]\n pts_fin_lower = curve_upper[ind_p0:ind_p3]\n\n pts_fin_upper = self.draw_curve((p0, cp8-p0, cp9-p0, p3-p0), remove_straight_line = False, as_tuples = True, fill = col_fin)\n # try to keep only the straight part of the fin\n n_lines = np.random.randint(2, 18)\n pts_fin_upper = self.list_from_to(pts_fin_upper, 0.2, 0.8, n_lines)\n pts_fin_lower = self.list_from_to(pts_fin_lower, 0.2, 0.8, n_lines)\n # draw some lines across the fin\n for pup, plo in zip(pts_fin_upper, pts_fin_lower):\n self.draw_curve((plo, 0.75*(pup-plo), 0.25*(plo-pup), 0.6*(pup-plo)), width = 1)\n self._pen = aggdraw.Pen(out_col, out_w)\n\n ## lower fin\n # upper curve of the lower fin\n curve_upper = self._curve['lower']\n n_upper = len(curve_upper)\n # 0 = rear, 1 = front\n ind_p4 = int(0.25*n_upper + np.random.uniform(-0.05*n_upper, 0.02*n_upper))\n ind_p5 = int(0.80*n_upper + np.random.uniform(-0.05*n_upper, 0.02*n_upper))\n p4 = curve_upper[ind_p4]\n p5 = curve_upper[ind_p5]\n # lower curve of the lower fin\n curve_lower = self.draw_curve((p4,\n cp11-p4+(-0.15*width_body,-0.2*height_body),\n cp10-p4-(0,0.03*height_body),\n p5-p4), as_tuples = True, fill = col_fin)\n pts_fin_upper = curve_upper\n pts_fin_lower = curve_lower\n # do not draw across the curvy parts\n pts_fin_upper = curve_upper[ind_p4:ind_p5]\n pts_fin_upper = self.list_from_to(pts_fin_upper, 0.2, 0.8, n_lines/2)\n pts_fin_lower = self.list_from_to(pts_fin_lower, 0.2, 0.8, n_lines/2)\n for plo, pup in zip(pts_fin_lower, pts_fin_upper):\n self.draw_curve((pup, -0.25*(pup-plo), -0.45*(pup-plo), -0.6*(pup-plo)), width = 1)\n \n\n @reset\n def draw_tail(self):\n # reset later\n brush_col = self._info['brush']\n out_w = self._info['pen']['width']\n # use p3, p7, p12, p3\n cp0, cp1, cp2, cp3, cp4, cp5, cp6, cp7, cp8, cp9, cp10, cp11, cp12 = self._control_points[:13]\n r, g, b = np.random.randint(20, 40), np.random.randint(20, 40), np.random.randint(20, 40)\n try:\n col_tail = self._info['brush'] + np.array((r, g, b))\n col_tail = [min(c, 255) for c in col_tail]\n col_tail = self.triplet2hex(col_tail)\n except:\n col_tail = self.triplet2hex(self.hex2triplet(self._info['brush']) + np.array((r, g, b)))\n ## draw the tail shape\n tail_line_hi = self.draw_curve((cp3-(out_w,0), cp7-cp3, cp12-cp3, cp12-cp3), fill = col_tail, as_tuples = True)\n tail_line_lo = self.draw_curve((cp3-(out_w,0), cp6-cp3, cp12-cp3, cp12-cp3), fill = col_tail, as_tuples = True)\n ## draw straight lines from tail's curve towards tail's origin\n len_tail_hi = len(tail_line_hi)\n n_lines_hi = np.random.randint(0, np.round(len_tail_hi/5.0)+1)\n round = lambda x: int(np.round(x))\n eps = 1e-6\n # keep only the rather vertical part -> no self-intersections\n # from higher half\n tail_line_hi = tail_line_hi[int(0.55*len_tail_hi):int(0.9*len_tail_hi)]\n p_lines_hi_0 = tail_line_hi[::round(len_tail_hi/(n_lines_hi+eps))]\n for p0 in p_lines_hi_0:\n self.draw_curve((p0, (0,0), (0,0), 0.6*(cp3-p0)), width=1)\n # from lower half\n len_tail_lo = len(tail_line_lo)\n n_lines_lo = np.random.randint(0, np.round(len_tail_lo/5.0)+1)\n tail_line_lo = tail_line_lo[int(0.55*len_tail_lo):int(0.9*len_tail_lo)]\n p_lines_lo_0 = tail_line_lo[::round(len_tail_lo/(n_lines_lo+eps))]\n for p0 in p_lines_lo_0:\n self.draw_curve((p0, (0,0), (0,0), 0.6*(cp3-p0)), width=1)\n # line\n fill = self._info['brush']\n self.draw_curve((cp12 - (out_w/2, 0), (0,0), (0,0), cp3-cp12-(out_w/2, 0)), outline_col = fill, fill_inner = fill, fill = fill)\n\n\n @reset\n def draw_head(self):\n # reset later\n brush_col = self._info['brush']\n out_col = self._info['pen']['color']\n out_w = self._info['pen']['width']/2.0\n\n height_body = abs(self._bboxes['body'].y1 - self._bboxes['body'].y0) \n width_body = abs(self._bboxes['body'].x1 - self._bboxes['body'].x0) \n rand_offset = np.random.uniform(0, 0.04*height_body)\n ## curve 2\n p0, p1, p2, p3 = self._control_points[:4]\n p_p0p3 = p0 + 0.35*(p3-p0)\n ind_p0_head = np.argmin([abs(p_p0p3[0] - p[0]) for p in self._curve['upper']])\n p0_head = self._curve['upper'][ind_p0_head] + 0.08*height_body - (0, rand_offset) \n p2_head = np.array((0, 0.45*height_body)) + (0, rand_offset) \n p1_head = (-0.1*width_body, 0.18*height_body) \n p0_head += (-0.05*width_body, 0.05*height_body)\n p2_head += (0.015*width_body, 0) \n p2_head += (0, -0.05*height_body)\n self.draw_curve((p0_head, p1_head, p1_head, p2_head))\n ## curve1 fill\n p0, p1, p2, p3 = self._control_points[:4]\n p0_head = self._curve['upper'][ind_p0_head] + 0.1*height_body - (0, rand_offset)\n p2_head = np.array((0, 0.45*height_body)) + (0, rand_offset)\n p1_head = np.array((-0.1*width_body, 0.2*height_body))\n p0_head -= (0.015*width_body, 0)\n p2_head -= (0.017*width_body, 0)\n p1_head -= (0.015*width_body, 0)\n # BUG: self._info['brush'] is supposed to be a hex string\n col_fill = self.triplet2hex(np.array(self._info['brush']) - (40, 40, 40))\n self._brush = aggdraw.Brush(col_fill)\n self.draw_curve((p0_head, p1_head, p1_head, p2_head), fill_inner = col_fill, outline_col = col_fill)\n # reset\n self._brush = aggdraw.Brush(brush_col)\n self._pen = aggdraw.Pen(out_col, out_w)\n ## curve 1 outline\n p0, p1, p2, p3 = self._control_points[:4]\n p0_head = self._curve['upper'][ind_p0_head] + 0.1*height_body - (0, rand_offset)\n p2_head = np.array((0, 0.45*height_body)) + (0, rand_offset)\n p1_head = np.array((-0.1*width_body, 0.2*height_body))\n self.draw_curve((p0_head, p1_head, p1_head, p2_head))\n\n\n @reset\n def draw_dots(self):\n height_body = abs(self._bboxes['body'].y1 - self._bboxes['body'].y0) \n width_body = abs(self._bboxes['body'].x1 - self._bboxes['body'].x0) \n y_head = self._curve['upper'][0][1]\n rad = 0.035*height_body\n\n # starting points of dots on the fish's body\n pts_upper = self._curve['upper']\n nupper = len(pts_upper)\n nlines = np.random.randint(0, int(nupper/7.0))\n # 0 = head, 1 = tail\n ind_lines = np.random.randint(int(0.4*nupper), int(0.9*nupper), nlines)\n lines_upper0 = pts_upper[ind_lines]\n\n r, g, b = np.random.randint(20, 60), np.random.randint(20, 60), np.random.randint(20, 60)\n try:\n # if triplet\n col_dots = np.array(self._col_belly) + (r, g, b)\n except:\n col_dots = self.hex2triplet(col_dots)\n col_dots = np.array(self._col_belly) + (r, g, b)\n col_dots = self.triplet2hex([min(c, 255) for c in col_dots])\n\n # propagate from starting points to y_head\n for p in lines_upper0:\n p0 = (p[0], p[1] + np.random.uniform(2*rad, 3*rad)) \n stdev = (y_head - p[1])/4.0\n npts_line = np.random.randint(1, 4)\n dots = np.array(list(it.repeat(p0, npts_line))) +\\\n [(np.random.uniform(-rad, rad), n) for n in abs(np.random.normal(0, stdev, npts_line))]\n for i, p0 in enumerate(dots):\n brush = aggdraw.Brush(col_dots)\n pen = aggdraw.Pen(self._info['pen']['color'], 1)\n rad_sc = rad*(i+1)/len(dots) + np.random.uniform(-0.2*rad, 0.2*rad)\n self._draw.ellipse((p0[0]-rad_sc, p0[1]-rad_sc, p0[0]+rad_sc, p0[1]+rad_sc), brush, pen)\n self._draw.flush()\n\n\n def draw(self, show = False):\n # parts are drawn in the order listed\n self.draw_body()\n self.draw_fins()\n self.draw_tail()\n self.draw_body()\n self.draw_dots()\n self.draw_head()\n self.draw_eye()\n if show:\n self.show()\n" ]
[ [ "numpy.random.random", "numpy.round", "numpy.random.normal", "numpy.random.uniform", "numpy.array", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
pientist/socceraction
[ "7f8e666ee5da7c1890c72a2c72042d4c73b90fda" ]
[ "socceraction/spadl/base.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"Utility functions for all event stream to SPADL converters.\n\nA converter should implement 'convert_to_actions' to convert the events to the\nSPADL format.\n\n\"\"\"\nimport pandas as pd # type: ignore\n\nfrom . import config as spadlconfig\n\n\ndef _fix_clearances(actions: pd.DataFrame) -> pd.DataFrame:\n next_actions = actions.shift(-1)\n next_actions[-1:] = actions[-1:]\n clearance_idx = actions.type_id == spadlconfig.actiontypes.index('clearance')\n actions.loc[clearance_idx, 'end_x'] = next_actions[clearance_idx].start_x.values\n actions.loc[clearance_idx, 'end_y'] = next_actions[clearance_idx].start_y.values\n\n return actions\n\n\ndef _fix_direction_of_play(actions: pd.DataFrame, home_team_id: int) -> pd.DataFrame:\n away_idx = (actions.team_id != home_team_id).values\n for col in ['start_x', 'end_x']:\n actions.loc[away_idx, col] = spadlconfig.field_length - actions[away_idx][col].values\n for col in ['start_y', 'end_y']:\n actions.loc[away_idx, col] = spadlconfig.field_width - actions[away_idx][col].values\n\n return actions\n\n\nmin_dribble_length: float = 3.0\nmax_dribble_length: float = 60.0\nmax_dribble_duration: float = 10.0\n\n\ndef _add_dribbles(actions: pd.DataFrame) -> pd.DataFrame:\n next_actions = actions.shift(-1, fill_value=0)\n\n same_team = actions.team_id == next_actions.team_id\n # not_clearance = actions.type_id != actiontypes.index(\"clearance\")\n\n dx = actions.end_x - next_actions.start_x\n dy = actions.end_y - next_actions.start_y\n far_enough = dx ** 2 + dy ** 2 >= min_dribble_length ** 2\n not_too_far = dx ** 2 + dy ** 2 <= max_dribble_length ** 2\n\n dt = next_actions.time_seconds - actions.time_seconds\n same_phase = dt < max_dribble_duration\n same_period = actions.period_id == next_actions.period_id\n\n dribble_idx = same_team & far_enough & not_too_far & same_phase & same_period\n\n dribbles = pd.DataFrame()\n prev = actions[dribble_idx]\n nex = next_actions[dribble_idx]\n dribbles['game_id'] = nex.game_id\n dribbles['period_id'] = nex.period_id\n dribbles['action_id'] = prev.action_id + 0.1\n dribbles['time_seconds'] = (prev.time_seconds + nex.time_seconds) / 2\n if 'timestamp' in actions.columns:\n dribbles['timestamp'] = nex.timestamp\n dribbles['team_id'] = nex.team_id\n dribbles['player_id'] = nex.player_id\n dribbles['start_x'] = prev.end_x\n dribbles['start_y'] = prev.end_y\n dribbles['end_x'] = nex.start_x\n dribbles['end_y'] = nex.start_y\n dribbles['bodypart_id'] = spadlconfig.bodyparts.index('foot')\n dribbles['type_id'] = spadlconfig.actiontypes.index('dribble')\n dribbles['result_id'] = spadlconfig.results.index('success')\n\n actions = pd.concat([actions, dribbles], ignore_index=True, sort=False)\n actions = actions.sort_values(['game_id', 'period_id', 'action_id']).reset_index(drop=True)\n actions['action_id'] = range(len(actions))\n return actions\n" ]
[ [ "pandas.concat", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
eduardojdiniz/DeepBrainNet
[ "38fd6916d35f2cf5f1a99dd36ddbfc3d6f929d99" ]
[ "example/scripts/slicer.py" ]
[ "from sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import Normalizer\nimport nibabel as nib\n# from nilearn import plotting\nimport re\nimport numpy as np\nimport pandas as pd\nimport os\nfrom os import listdir, fsencode\nimport math\nfrom PIL import Image\nimport sys\nimport os\n\nin_data_dir = str(sys.argv[1])\nout_data_dir = str(sys.argv[2])\n\nnii_files = [f for f in os.listdir(os.fsencode(in_data_dir))\n if f.endswith(b'.nii.gz')]\n\nfor nii_file in nii_files:\n f = os.fsencode(nii_file)\n f = f.decode('utf-8')\n nii_file = nib.load((in_data_dir + f))\n data = nii_file.get_fdata()\n data = data*(185.0/np.percentile(data, 97))\n scaler = StandardScaler()\n for img_slice in range(0, 80):\n clipped = data[:, :, (45+img_slice)]\n image_data = Image.fromarray(clipped).convert('RGB')\n image_data.save((out_data_dir + f[:-7] + '-'+str(img_slice)+'.jpg'))\n" ]
[ [ "sklearn.preprocessing.StandardScaler", "numpy.percentile" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
prinse1545/DeepCovidXR
[ "0bc2db133f8caaddf22a6a67fd413af6fb82198e" ]
[ "kaggle/object_detection/evaluate_model.py" ]
[ "# Filename: evaluate_model.py\n# Description: This file evaluates \n# pytorch faster rcnn models\n# \n# 2021-08-12\n\n# importing tools\nfrom matplotlib import cm\nimport matplotlib.pyplot as plt;\nfrom matplotlib.ticker import LinearLocator\nimport torch\nfrom torchvision.ops.boxes import box_iou\nfrom PIL import Image\nfrom helper import get_dataloader, create_model, nightly_create_model\nimport random\nimport shutil\nimport numpy\nimport cv2\nimport re\nimport os\n\n\ndef evaluate_model(model, data_loader, device):\n\n # eval\n model.eval();\n\n # initializing false positives and negatives\n false_p = 0;\n false_n = 0;\n true_p = 0;\n\n # initialzing TIDE metrics\n tide = {\n \"loc\": 0,\n \"dup\": 0,\n \"bkgd\": 0,\n \"miss\": 0\n };\n\n # iterating\n for batch in data_loader:\n # getting predictions\n preds = model(list(image.to(device) for image in batch[0]));\n\n # initializing list of integers indicating if box has been detected\n for pred, label in zip(preds, batch[1]):\n # converting to numpy\n grnd_trth = [label[\"boxes\"][indx].numpy() for indx, labl in enumerate(label[\"labels\"]) if labl.numpy() == 1];\n \n # detected array\n detected = numpy.zeros(len(grnd_trth));\n \n # getting boxes predicted\n boxes = pred[\"boxes\"].cpu().detach().numpy();\n\n # iterating over predictions\n for box in boxes:\n # boolean that keeps track of detection\n detects = False;\n # boolean that tracks tide metrics\n tide_failure_accounted = False;\n\n # finding overlap\n for indx, gt_box in enumerate(grnd_trth):\n # finding iou\n iou = box_iou(\n torch.as_tensor([box], dtype = torch.float), \n torch.as_tensor([gt_box], dtype = torch.float)\n ).numpy()[0][0];\n\n # if iou is greater than 0.5 and the box hasn't been detected, mark as detected\n if(iou >= 0.5 and detected[indx] == 0):\n detected[indx] = 1;\n # marking detects as tru\n detects = True;\n elif(iou >= 0.5 and detected[indx] == 1):\n # marking duplicate error\n tide[\"dup\"] = tide[\"dup\"] + 1;\n tide_failure_accounted = True;\n elif(iou > 0):\n # marking location error\n tide[\"loc\"] = tide[\"loc\"] + 1;\n tide_failure_accounted = True;\n else:\n # marking background error\n tide[\"bkgd\"] = tide[\"bkgd\"] + 1;\n tide_failure_accounted = True;\n\n # if the box doesn't detect anything new then bye\n if(not detects):\n false_p = false_p + 1;\n if(not tide_failure_accounted):\n tide[\"miss\"] = tide[\"miss\"] + 1;\n \n # calculating number of detected\n n_detected = numpy.count_nonzero(detected);\n\n # calculating false negatives and true positives\n false_n = false_n + (len(detected) - n_detected);\n true_p = true_p + n_detected;\n\n\n # print(true_p, false_p, false_n)\n # getting average precision and average recall\n avg_precision = true_p / (true_p + false_p) if true_p + false_p > 0 else 0;\n avg_recall = true_p / (true_p + false_n) if true_p + false_n > 0 else 0;\n f_score = (2 * avg_precision * avg_recall) / (avg_precision + avg_recall) if (avg_precision + avg_recall) > 0 else 0;\n\n # printing results\n print(\"AP:\", avg_precision, \"\\nAR:\", avg_recall, \"\\nF-Score:\", f_score, \"\\ntide:\", tide);\n return avg_precision, avg_recall, f_score, tide;\n\n\ndef get_metrics(model_name):\n \n # enabling GPU if available\n device = torch.device(\"cuda\") if torch.cuda.is_available else torch.device(\"cpu\");\n print(\"using {}\".format(device));\n\n # getting data loader\n test_loader = get_dataloader(\"/data/kaggle_data/od_test/test\");\n\n # creating model\n model = create_model(model_name,\n model_names = [(\"resnet50_coarse/saved_model_55\", 0.7, 0.45),\n (\"resnet50_fine/saved_model_80\", 0.75, 0.45)],\n create_model = create_model);\n\n # fitting model to device\n model = model.to(device);\n\n # evaluating model\n return evaluate_model(model, test_loader, device);\n\n\ndef create_tide_graph(model_name):\n\n # getting tide metrics\n _, _, tide = get_metrics(model_name);\n\n # getting labels, data, and explode params\n labels = tide.keys();\n sizes = [tide[key] for key in tide.keys()];\n \n # creating plot\n fig, ax = plt.subplots();\n bars = ax.bar(labels, sizes);\n \n # creating color list\n colors = [\"#F1C40F\", \"#3498DB\", \"#2ECC71\", \"#34495E\"];\n\n # iterating over bars to set colors\n for indx, bar in enumerate(bars):\n # setting color\n bar.set_color(colors[indx]);\n\n ax.set_title(\"TIDE Chart\");\n\n # saving fig\n fig.savefig(\"tide_chart.png\");\n\ndef create_finetuning_graph(model_name):\n\n # enabling GPU if available\n device = torch.device(\"cuda\") if torch.cuda.is_available else torch.device(\"cpu\");\n print(\"using {}\".format(device));\n\n # getting data loader\n test_loader = get_dataloader(\"test\");\n\n # defining collecting lists\n threshs = [];\n rnms = [];\n APs = [];\n ARs = [];\n\n # iterating over different iou thresholds\n for iou in range(0, 100, 10):\n\n # getting threshold\n thresh = iou / 100;\n\n # iterating over different region proposal network rnms\n for rpn in range(0, 100, 10):\n \n # getting rnm\n rnm = rpn / 100;\n\n # creating model\n model = create_model(model_name, thresh, rnm);\n\n # fitting model to device\n model = model.to(device);\n\n # evaluating\n ap, ar, _ = evaluate_model(model, test_loader, device);\n\n print(\"iou\", thresh, \"rnm\", rnm);\n # getting APs\n APs.append(ap);\n ARs.append(ar);\n\n # collecting data\n threshs.append(thresh);\n rnms.append(rnm);\n\n \n # getting fig and axes \n fig, ax = plt.subplots(subplot_kw = { \"projection\": \"3d\" });\n\n # plotting\n img = ax.scatter(threshs, rnms, APs, c = ARs, cmap = plt.hot());\n\n # naming axes\n ax.set_xlabel(\"IoU Positive Threshold\");\n ax.set_ylabel(\"Overlap Joining Threshold\");\n ax.set_zlabel(\"Average Precision\");\n # Add a color bar which maps values to colors.\n fig.colorbar(img, shrink=0.5, aspect=5)\n\n # saving\n fig.savefig(\"finetune.png\");\n\ndef draw_pred_bbs(models):\n\n # enabling GPU if available\n device = torch.device(\"cuda\") if torch.cuda.is_available else torch.device(\"cpu\");\n print(\"using {}\".format(device));\n\n # getting rid of write dir if it does exist\n if(os.path.isdir(\"./eval_bbs\")):\n shutil.rmtree(\"./eval_bbs\");\n\n # making dir\n os.makedirs(\"./eval_bbs\");\n\n # getting data loader\n test_loader = get_dataloader(\"/data/kaggle_data/od_split_formatted/test\");\n\n # geting batch\n batch = next(iter(test_loader));\n \n # creating images\n images = list(image.to(device) for image in batch[0]);\n\n # initializing preds array\n preds = [];\n\n for model in models:\n\n # creating model\n model = create_model(model[0], model_names = model[3], create_model = create_model);\n\n # fitting model to device\n model = model.to(device);\n\n # eval\n model.eval();\n\n # getting predictions\n preds.append(model(images));\n \n # getting radians\n theta = numpy.pi * 3 / 2;\n\n # creating rotation matrix\n r_mat = numpy.array([\n [numpy.cos(theta), -1 * numpy.sin(theta)], \n [numpy.sin(theta), numpy.cos(theta)]\n ]);\n\n # drawing boxes\n for indx, (preds_tuple, img, targ) in enumerate(zip(zip(*preds), images, batch[1])):\n \n # converting boxes and images\n np_img = numpy.transpose(img.cpu().detach().numpy()).copy();\n \n # iterating over prediction tuple\n for i, pred in enumerate(preds_tuple):\n boxes = pred[\"boxes\"].cpu().detach().numpy();\n scores = pred[\"scores\"].cpu().detach().numpy();\n\n # iterating over predicted boxes\n for box, score in zip(boxes, scores):\n\n # getting mins and maxs\n mins = numpy.array(box[0:2]);\n maxs = numpy.array(box[2:]);\n\n # rotating\n r_mins = numpy.matmul(r_mat, mins);\n r_maxs = numpy.matmul(r_mat, maxs);\n\n # drawing rectangle\n cv2.rectangle(np_img,\n (int(r_mins[0]), int(-1 * r_mins[1])),\n (int(r_maxs[0]), int(-1 * r_maxs[1])),\n color = (220, 0, 0),\n thickness = 2\n );\n\n # annotating box\n cv2.putText(np_img, \n \"Opacity {}: {}%\".format(i, round(score * 100, 2)), \n (int(r_mins[0]), int(-1 * r_mins[1]) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (220, 0, 0), 2);\n\n\n # iterating over ground truth boxes\n for box, label in zip(targ[\"boxes\"], targ[\"labels\"]):\n\n # checking labels\n if(label.numpy() == 1):\n # getting numpy box\n box = box.numpy();\n\n # creating min and max\n mins = numpy.array(box[0:2]);\n maxs = numpy.array(box[2:]);\n\n # rotating\n r_mins = numpy.matmul(r_mat, mins);\n r_maxs = numpy.matmul(r_mat, maxs);\n\n # plotting box\n cv2.rectangle(np_img,\n (int(r_mins[0]), int(-1 * r_mins[1])),\n (int(r_maxs[0]), int(-1 * r_maxs[1])),\n color = (0, 220, 0),\n thickness = 2\n );\n\n # annotating box\n cv2.putText(np_img, \n \"Ground Truth\", \n (int(r_mins[0]), int(-1 * r_mins[1]) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 220, 0), 2);\n\n # saving image\n Image.fromarray(np_img.astype(numpy.uint8)).convert(\"RGB\").save(\"./eval_bbs/{}.png\".format(indx));\n\ndef create_epoch_graph(metrics_path):\n\n # reading in metrics from saved numpy\n metrics = numpy.load(metrics_path);\n # transposing\n metrics = numpy.transpose(metrics);\n # creating x axis\n x = list(range(len(metrics[0])));\n \n # plotting\n plt.scatter(x, metrics[0], color = \"red\", label = \"Avg Precision\");\n plt.scatter(x, metrics[1], color = \"blue\", label = \"Avg Recall\");\n plt.scatter(x, metrics[2], color = \"purple\", label = \"F1 Score\");\n\n # changing ticks\n plt.xticks(x[::5]);\n\n # setting legend\n plt.legend(title = \"Metrics\");\n\n # title and axes\n plt.xlabel(\"Epoch\");\n plt.title(\"Metrics Over Epochs\");\n\n # setting grid lines\n plt.gca().xaxis.grid(True);\n\n # saving \n plt.savefig(\"resnet50_fine_epoch_graph.png\");\n\n# draw_pred_bbs([(\"ensemble\", 0.7, 0.45, [(\"resnet50_coarse/saved_model_55\", 0.7, 0.45), (\"resnet50_fine/saved_model_80\", 0.75, 0.45)]);\n# create_finetuning_graph(\"resnet50_bone_2/saved_model_45\");\nget_metrics(\"ensemble\");\n# create_epoch_graph(\"resnet50_fine/metrics.npy\");\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.gca", "matplotlib.pyplot.scatter", "matplotlib.pyplot.title", "numpy.matmul", "matplotlib.pyplot.subplots", "matplotlib.pyplot.savefig", "numpy.cos", "numpy.sin", "matplotlib.pyplot.hot", "matplotlib.pyplot.xlabel", "numpy.count_nonzero", "numpy.transpose", "torch.device", "numpy.load", "matplotlib.pyplot.xticks", "numpy.array", "torch.as_tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Yangzhengtang/mspass
[ "7ac6db4afa7577f0e67981490fd89d50e35bf4c7" ]
[ "python/tests/test_ccore.py" ]
[ "import array\nimport copy\nimport pickle\n\nimport numpy as np\nimport pytest\n\nfrom mspasspy.ccore.seismic import (_CoreSeismogram,\n _CoreTimeSeries,\n Seismogram,\n SeismogramEnsemble,\n SlownessVector,\n TimeSeries,\n TimeSeriesEnsemble,\n TimeReferenceType)\nfrom mspasspy.ccore.utility import (AtomicType,\n dmatrix,\n ErrorLogger,\n ErrorSeverity,\n LogData,\n Metadata,\n MetadataDefinitions,\n MsPASSError,\n ProcessingHistory,\n SphericalCoordinate)\n\nfrom mspasspy.ccore.algorithms.basic import ExtractComponent\n\n\ndef make_constant_data_ts(d, t0=0.0, dt=0.1, nsamp=5, val=1.0):\n \"\"\"\n Fills TimeSeries (or _CoreTimeSeries) data vector with\n a constant value of a specified length and start time.\n Used for testing arithmetic operators.\n\n Parameters\n ----------\n d : TYPE\n DESCRIPTION. TimeSeries or _CoreTimeSeries skeleton to build upon\n t0 : TYPE, optional\n DESCRIPTION. The default is 0.0. data start time\n dt : TYPE, optional\n DESCRIPTION. The default is 0.1. sample interval\n nsamp : TYPE, optional\n DESCRIPTION. The default is 5. length of data vector to generate\n\n Returns\n -------\n None.\n\n \"\"\"\n d.npts = nsamp\n d.t0 = t0\n d.dt = dt\n d.set_live()\n for i in range(nsamp):\n d.data[i] = val\n return d\n\n\ndef make_constant_data_seis(d, t0=0.0, dt=0.1, nsamp=5, val=1.0):\n \"\"\"\n Fills Seismogram (or Seismogram) data vector with\n a constant value of a specified length and start time.\n Used for testing arithmetic operators.\n\n Parameters\n ----------\n d : TYPE\n DESCRIPTION. TimeSeries or _CoreTimeSeries skeleton to build upon\n t0 : TYPE, optional\n DESCRIPTION. The default is 0.0. data start time\n dt : TYPE, optional\n DESCRIPTION. The default is 0.1. sample interval\n nsamp : TYPE, optional\n DESCRIPTION. The default is 5. length of data vector to generate\n\n Returns\n -------\n None.\n\n \"\"\"\n d.npts = nsamp\n d.t0 = t0\n d.dt = dt\n d.set_live()\n for i in range(nsamp):\n for k in range(3):\n d.data[k, i] = val\n return d\n\n\ndef setup_function(function):\n pass\n\n\ndef test_dmatrix():\n dm = dmatrix()\n assert dm.rows() == 0\n\n dm = dmatrix(9, 4)\n assert dm.rows() == 9\n assert dm.columns() == 4\n assert dm.size == 4*9\n assert len(dm) == 9\n assert dm.shape == (9, 4)\n\n md = [array.array('l', (0 for _ in range(5))) for _ in range(3)]\n for i in range(3):\n for j in range(5):\n md[i][j] = i*5+j\n dm = dmatrix(md)\n assert np.equal(dm, md).all()\n\n dm_c = dmatrix(dm)\n assert (dm_c[:] == dm).all()\n\n dm_c.zero()\n assert not dm_c[:].any()\n\n md = np.zeros((7, 4), dtype=np.double, order='F')\n for i in range(7):\n for j in range(4):\n md[i][j] = i*4+j\n dm = dmatrix(md)\n assert (dm == md).all()\n assert (dm.transpose() == md.transpose()).all()\n assert (dm * 3.14 == md * 3.14).all()\n assert (2.17 * dm == 2.17 * md).all()\n assert (dm * dm.transpose() == np.matmul(md, md.transpose())).all()\n\n with pytest.raises(MsPASSError, match='size mismatch'):\n dm * dm\n\n dm_c = dmatrix(dm)\n dm += dm_c\n assert (dm == md+md).all()\n dm += md\n assert (dm == md+md+md).all()\n assert type(dm) == dmatrix\n dm -= dm_c\n dm -= dm_c\n dm -= md\n assert not dm[:].any()\n assert type(dm) == dmatrix\n\n dm_c = dmatrix(dm)\n\n md = np.zeros((7, 4), dtype=np.single, order='C')\n for i in range(7):\n for j in range(4):\n md[i][j] = i*4+j\n dm = dmatrix(md)\n assert (dm == md).all()\n\n md = np.zeros((7, 4), dtype=np.int, order='F')\n for i in range(7):\n for j in range(4):\n md[i][j] = i*4+j\n dm = dmatrix(md)\n assert (dm == md).all()\n\n md = np.zeros((7, 4), dtype=np.unicode_, order='C')\n for i in range(7):\n for j in range(4):\n md[i][j] = i*4+j\n dm = dmatrix(md)\n assert (dm == np.float_(md)).all()\n\n md = np.zeros((53, 37), dtype=np.double, order='C')\n for i in range(53):\n for j in range(37):\n md[i][j] = i*37+j\n dm = dmatrix(md)\n\n assert dm[17, 23] == md[17, 23]\n assert (dm[17] == md[17]).all()\n assert (dm[::] == md[::]).all()\n assert (dm[3::] == md[3::]).all()\n assert (dm[:5:] == md[:5:]).all()\n assert (dm[::7] == md[::7]).all()\n assert (dm[-3::] == md[-3::]).all()\n assert (dm[:-5:] == md[:-5:]).all()\n assert (dm[::-7] == md[::-7]).all()\n assert (dm[11:41:7] == md[11:41:7]).all()\n assert (dm[-11:-41:-7] == md[-11:-41:-7]).all()\n assert (dm[3::, 13] == md[3::, 13]).all()\n assert (dm[19, :5:] == md[19, :5:]).all()\n assert (dm[::-7, ::-11] == md[::-7, ::-11]).all()\n\n with pytest.raises(IndexError, match='out of bounds for axis 1'):\n dummy = dm[3, 50]\n with pytest.raises(IndexError, match='out of bounds for axis 0'):\n dummy = dm[80]\n\n with pytest.raises(IndexError, match='out of bounds for axis 1'):\n dm[3, 50] = 1.0\n with pytest.raises(IndexError, match='out of bounds for axis 0'):\n dm[60, 50] = 1\n\n dm[7, 17] = 3.14\n assert dm[7, 17] == 3.14\n\n dm[7, 17] = '6.28'\n assert dm[7, 17] == 6.28\n\n dm[7] = 10\n assert (dm[7] == 10).all()\n\n dm[::] = md\n assert (dm == md).all()\n\n dm[:, -7] = 3.14\n assert (dm[:, -7] == 3.14).all()\n\n dm[17, :] = 3.14\n assert (dm[17, :] == 3.14).all()\n\n dm[3:7, -19:-12] = 3.14\n assert (dm[3:7, -19:-12] == 3.14).all()\n\n\ndef test_ErrorLogger():\n errlog = ErrorLogger()\n assert errlog.log_error('1', '2', ErrorSeverity(3)) == 1\n assert errlog[0].algorithm == '1'\n assert errlog[0].message == '2'\n assert errlog[0].badness == ErrorSeverity.Complaint\n assert errlog[0].job_id == errlog.get_job_id()\n\n\ndef test_LogData():\n ld = LogData({\"job_id\": 0, \"p_id\": 1, \"algorithm\": \"alg\",\n \"message\": \"msg\", \"badness\": ErrorSeverity(2)})\n assert ld.job_id == 0\n assert ld.p_id == 1\n assert ld.algorithm == \"alg\"\n assert ld.message == \"msg\"\n assert ld.badness == ErrorSeverity.Suspect\n assert str(ld) == str(LogData(eval(str(ld))))\n\n\ndef test_Metadata():\n md = Metadata()\n assert repr(md) == 'Metadata({})'\n dic = {1: 1}\n md.put('dict', dic)\n val = md.get('dict')\n val[2] = 2\n del val\n dic[3] = 3\n del dic\n md['dict'][4] = 4\n assert md['dict'] == {1: 1, 2: 2, 3: 3, 4: 4}\n\n md = Metadata({'array': np.array([3, 4])})\n md['dict'] = {1: 1, 2: 2}\n md['str\\'i\"ng'] = 'str\\'i\"ng'\n md[\"str'ing\"] = \"str'ing\"\n md['double'] = 3.14\n md['bool'] = True\n md['int'] = 7\n md[\"string\"] = \"str\\0ing\"\n md[\"string\"] = \"str\\ning\"\n md[\"str\\ting\"] = \"str\\ting\"\n md[\"str\\0ing\"] = \"str\\0ing\"\n md[\"str\\\\0ing\"] = \"str\\\\0ing\"\n md_copy = pickle.loads(pickle.dumps(md))\n for i in md:\n if i == 'array':\n assert (md[i] == md_copy[i]).all()\n else:\n assert md[i] == md_copy[i]\n md_copy2 = Metadata(dict(md))\n assert not md_copy2.modified()\n assert md.modified() == md_copy.modified()\n\n md = Metadata({\n \"<class 'numpy.ndarray'>\": np.array([3, 4]),\n \"<class 'dict'>\": {1: 1, 2: 2},\n 'string': 'string',\n 'double': 3.14,\n 'bool': True,\n 'long': 7,\n \"<class 'bytes'>\": b'\\xba\\xd0\\xba\\xd0',\n \"<class 'NoneType'>\": None})\n for i in md:\n assert md.type(i) == i\n\n md[b'\\xba\\xd0'] = b'\\xba\\xd0'\n md_copy = pickle.loads(pickle.dumps(md))\n for i in md:\n if i == \"<class 'numpy.ndarray'>\":\n assert (md[i] == md_copy[i]).all()\n else:\n assert md[i] == md_copy[i]\n\n del md[\"<class 'numpy.ndarray'>\"]\n md_copy.erase(\"<class 'numpy.ndarray'>\")\n assert not \"<class 'numpy.ndarray'>\" in md\n assert not \"<class 'numpy.ndarray'>\" in md_copy\n assert md.keys() == md_copy.keys()\n\n with pytest.raises(TypeError, match='Metadata'):\n reversed(md)\n\n md = Metadata({1: 1, 3: 3})\n md_copy = Metadata({2: 2, 3: 30})\n md += md_copy\n assert md.__repr__() == \"Metadata({'1': 1, '2': 2, '3': 30})\"\n\n # Test with real data\n dic = {'_format': 'MSEED', 'arrival.time': 1356901212.242550, 'calib': 1.000000,\n 'chan': 'BHZ', 'delta': 0.025000, 'deltim': -1.000000, 'endtime': 1356904168.544538,\n 'iphase': 'P', 'loc': '',\n 'mseed': {'dataquality': 'D', 'number_of_records': 36, 'encoding': 'STEIM2',\n 'byteorder': '>', 'record_length': 4096, 'filesize': 726344704},\n 'net': 'CI', 'npts': 144000, 'phase': 'P', 'sampling_rate': 40.000000,\n 'site.elev': 0.258000, 'site.lat': 35.126900, 'site.lon': -118.830090,\n 'site_id': '5fb6a67b37f8eef2f0658e9a', 'sta': 'ARV', 'starttime': 1356900568.569538\n }\n md = Metadata(dic)\n md['mod'] = 'mod'\n md_copy = pickle.loads(pickle.dumps(md))\n for i in md:\n assert md[i] == md_copy[i]\n assert md.modified() == md_copy.modified()\n\n\[email protected](params=[Seismogram, SeismogramEnsemble,\n TimeSeries, TimeSeriesEnsemble])\ndef MetadataBase(request):\n return request.param\n\n\ndef test_MetadataBase(MetadataBase):\n md = MetadataBase()\n assert MetadataBase.__name__ + \"({\" in repr(md)\n dic = {1: 1}\n md.put('dict', dic)\n val = md.get('dict')\n val[2] = 2\n del val\n dic[3] = 3\n del dic\n md['dict'][4] = 4\n assert md['dict'] == {1: 1, 2: 2, 3: 3, 4: 4}\n\n md = MetadataBase()\n md[\"<class 'numpy.ndarray'>\"] = np.array([3, 4])\n md[\"<class 'dict'>\"] = {1: 1, 2: 2}\n md['string'] = 'str\\'i\"ng'\n md[\"str'ing\"] = \"str'ing\"\n md['double'] = 3.14\n md['bool'] = True\n md['long'] = 7\n md[\"str\\ning\"] = \"str\\0ing\"\n md[\"str\\ning\"] = \"str\\ning\"\n md[\"str\\ting\"] = \"str\\ting\"\n md[\"str\\0ing\"] = \"str\\0ing\"\n md[\"str\\\\0ing\"] = \"str\\\\0ing\"\n md[\"<class 'bytes'>\"] = b'\\xba\\xd0\\xba\\xd0'\n md[\"<class 'NoneType'>\"] = None\n md[b'\\xba\\xd0'] = b'\\xba\\xd0'\n md_copy = MetadataBase(md)\n for i in md:\n if i == 'array' or i == \"<class 'numpy.ndarray'>\":\n assert (md[i] == md_copy[i]).all()\n else:\n assert md[i] == md_copy[i]\n del md[\"str'ing\"], md[\"str\\ning\"], md[\"str\\ting\"], md[\"str\\0ing\"], md[\"str\\\\0ing\"], md[\"b'\\\\xba\\\\xd0'\"]\n for i in md:\n if i != 'delta' and i != 'npts' and i != 'starttime':\n assert md.type(i) == i\n\n md_copy = MetadataBase(md)\n del md[\"<class 'numpy.ndarray'>\"]\n md_copy.erase(\"<class 'numpy.ndarray'>\")\n assert not \"<class 'numpy.ndarray'>\" in md\n assert not \"<class 'numpy.ndarray'>\" in md_copy\n assert md.keys() == md_copy.keys()\n\n with pytest.raises(TypeError, match=MetadataBase.__name__):\n reversed(md)\n\n\ndef test_TimeSeries():\n ts = TimeSeries()\n ts.npts = 100\n ts.t0 = 0.0\n ts.dt = 0.001\n ts.live = 1\n ts.tref = TimeReferenceType.Relative\n ts.data.append(1.0)\n ts.data.append(2.0)\n ts.data.append(3.0)\n ts.data.append(4.0)\n ts.sync_npts()\n assert ts.npts == 104\n assert ts.npts == ts['npts']\n ts += ts\n for i in range(4):\n ts.data[i] = i * 0.5\n ts_copy = pickle.loads(pickle.dumps(ts))\n assert ts.data == ts_copy.data\n assert ts.data[3] == 1.5\n assert ts.data[103] == 8\n assert ts.time(100) == 0.1\n assert ts.sample_number(0.0998) == 100\n\n\ndef test_CoreSeismogram():\n md = Metadata()\n md['delta'] = 0.01\n md['starttime'] = 0.0\n md['npts'] = 100\n # test metadata constructor\n md['tmatrix'] = np.random.rand(3, 3)\n cseis = _CoreSeismogram(md, False)\n assert (cseis.tmatrix == md['tmatrix']).all()\n md['tmatrix'] = dmatrix(np.random.rand(3, 3))\n cseis = _CoreSeismogram(md, False)\n assert (cseis.tmatrix == md['tmatrix']).all()\n md['tmatrix'] = np.random.rand(9)\n cseis = _CoreSeismogram(md, False)\n assert (cseis.tmatrix == md['tmatrix'].reshape(3, 3)).all()\n md['tmatrix'] = np.random.rand(1, 9)\n cseis = _CoreSeismogram(md, False)\n assert (cseis.tmatrix == md['tmatrix'].reshape(3, 3)).all()\n md['tmatrix'] = np.random.rand(9, 1)\n cseis = _CoreSeismogram(md, False)\n assert (cseis.tmatrix == md['tmatrix'].reshape(3, 3)).all()\n\n md['tmatrix'] = np.random.rand(3, 3).tolist()\n cseis = _CoreSeismogram(md, False)\n assert np.isclose(cseis.tmatrix,\n np.array(md['tmatrix']).reshape(3, 3)).all()\n md['tmatrix'] = np.random.rand(9).tolist()\n cseis = _CoreSeismogram(md, False)\n assert np.isclose(cseis.tmatrix,\n np.array(md['tmatrix']).reshape(3, 3)).all()\n\n # test whether the setter of tmatrix updates metadata correctly\n tm = np.random.rand(1, 9)\n cseis.tmatrix = tm\n assert (cseis.tmatrix == tm.reshape(3, 3)).all()\n assert np.isclose(cseis.tmatrix, np.array(\n cseis['tmatrix']).reshape(3, 3)).all()\n tm = np.random.rand(9).tolist()\n cseis.tmatrix = tm\n assert np.isclose(cseis.tmatrix,\n np.array(tm).reshape(3, 3)).all()\n assert np.isclose(cseis.tmatrix, np.array(\n cseis['tmatrix']).reshape(3, 3)).all()\n\n # test exceptions\n md['tmatrix'] = np.random.rand(4, 2)\n with pytest.raises(MsPASSError, match=\"should be a 3x3 matrix\"):\n _CoreSeismogram(md, False)\n md['tmatrix'] = dmatrix(np.random.rand(2, 4))\n with pytest.raises(MsPASSError, match=\"should be a 3x3 matrix\"):\n _CoreSeismogram(md, False)\n md['tmatrix'] = 42\n with pytest.raises(MsPASSError, match=\"not recognized\"):\n _CoreSeismogram(md, False)\n md.erase('tmatrix')\n with pytest.raises(MsPASSError, match=\"Error trying to extract\"):\n _CoreSeismogram(md, False)\n md['tmatrix'] = {4: 2}\n with pytest.raises(MsPASSError, match=\"type is not recognized\"):\n _CoreSeismogram(md, False)\n\n md['tmatrix'] = np.random.rand(9).tolist()\n md['tmatrix'][3] = 'str'\n with pytest.raises(MsPASSError, match=\"should be float\"):\n _CoreSeismogram(md, False)\n md['tmatrix'] = np.random.rand(3, 4).tolist()\n with pytest.raises(MsPASSError, match=\"should be a 3x3 list of list\"):\n _CoreSeismogram(md, False)\n md['tmatrix'] = [1, 2, 3]\n with pytest.raises(MsPASSError, match=\"should be a 3x3 list of list\"):\n _CoreSeismogram(md, False)\n md['tmatrix'] = np.random.rand(2, 2).tolist()\n with pytest.raises(MsPASSError, match=\"should be a list of 9 floats or a 3x3 list of list\"):\n _CoreSeismogram(md, False)\n md['tmatrix'] = np.random.rand(3, 3).tolist()\n md['tmatrix'][1][1] = 'str'\n with pytest.raises(MsPASSError, match=\"should be float\"):\n _CoreSeismogram(md, False)\n\n\ndef test_Seismogram():\n seis = Seismogram()\n seis.npts = 100\n assert seis.data.rows() == 3\n assert seis.data.columns() == 100\n\n seis.t0 = 0.0\n seis.dt = 0.001\n seis.live = 1\n seis.tref = TimeReferenceType.Relative\n seis.data = dmatrix(np.random.rand(3, 6))\n assert seis.npts != 6\n seis.sync_npts()\n assert seis.npts == 6\n assert seis.npts == seis['npts']\n\n seis.npts = 4\n assert seis.data.columns() == 4\n\n seis.npts = 10\n assert (seis.data[0:3, 4:10] == 0).all()\n\n seis.data = dmatrix(np.random.rand(3, 100))\n seis.sync_npts()\n seis_copy = pickle.loads(pickle.dumps(seis))\n assert seis_copy.t0 == seis.t0\n assert seis_copy.dt == seis.dt\n assert seis_copy.live == seis.live\n assert seis_copy.tref == seis.tref\n assert (seis_copy.data[:] == seis.data[:]).all()\n\n # test the += operator\n seis1 = Seismogram(seis)\n seis2 = Seismogram(seis)\n seis1 += seis2\n assert (np.isclose(seis1.data[:], seis.data + seis.data)).all()\n\n seis.npts = 0\n assert seis.data.rows() == 0\n\n seis.npts = 100\n for i in range(3):\n for j in range(100):\n if i == 0:\n seis.data[i, j] = 1.0\n else:\n seis.data[i, j] = 0.0\n seis.data[0, 1] = 1.0\n seis.data[0, 2] = 1.0\n seis.data[0, 3] = 0.0\n seis.data[1, 1] = 1.0\n seis.data[1, 2] = 1.0\n seis.data[1, 3] = 0.0\n seis.data[2, 1] = 1.0\n seis.data[2, 2] = 0.0\n seis.data[2, 3] = 1.0\n\n sc = SphericalCoordinate()\n sc.phi = 0.0\n sc.theta = np.pi/4\n seis.rotate(sc)\n assert all(np.isclose(seis.data[:, 3], [0, -0.707107, 0.707107]))\n seis.rotate_to_standard()\n assert all(seis.data[:, 3] == [0, 0, 1])\n sc.phi = -np.pi/4\n seis.data[:, 3] = sc.unit_vector\n seis.rotate(sc)\n assert all(seis.data[:, 3] == [0, 0, 1])\n seis.rotate_to_standard()\n assert all(np.isclose(seis.data[:, 3], [0.5, -0.5, 0.707107]))\n seis.data[:, 3] = [0, 0, 1]\n\n nu = [np.sqrt(3.0)/3.0, np.sqrt(3.0)/3.0, np.sqrt(3.0)/3.0]\n seis.rotate(nu)\n assert (np.isclose(seis.tmatrix,\n np.array([[0.70710678, -0.70710678, 0.],\n [0.40824829, 0.40824829, -0.81649658],\n [0.57735027, 0.57735027, 0.57735027]]))).all()\n assert all(np.isclose(seis.data[:, 0], [0.707107, 0.408248, 0.57735]))\n assert all(np.isclose(seis.data[:, 1], [0, 0, 1.73205]))\n seis.rotate_to_standard()\n assert all(np.isclose(seis.data[:, 0], [1, 0, 0]))\n assert all(np.isclose(seis.data[:, 1], [1, 1, 1]))\n\n nu = [np.sqrt(3.0)/3.0, np.sqrt(3.0)/3.0, np.sqrt(3.0)/3.0]\n seis.rotate(SphericalCoordinate(nu))\n assert (np.isclose(seis.tmatrix,\n np.array([[0.70710678, -0.70710678, 0.],\n [0.40824829, 0.40824829, -0.81649658],\n [0.57735027, 0.57735027, 0.57735027]]))).all()\n assert all(np.isclose(seis.data[:, 0], [0.707107, 0.408248, 0.57735]))\n assert all(np.isclose(seis.data[:, 1], [0, 0, 1.73205]))\n seis.rotate_to_standard()\n assert all(np.isclose(seis.data[:, 0], [1, 0, 0]))\n assert all(np.isclose(seis.data[:, 1], [1, 1, 1]))\n\n sc.phi = np.pi/4\n sc.theta = 0.0\n seis.rotate(sc)\n assert (np.isclose(seis.tmatrix,\n np.array([[0.70710678, -0.70710678, 0.],\n [0.70710678, 0.70710678, 0.],\n [0., 0., 1.]]))).all()\n assert all(np.isclose(seis.data[:, 0], [0.707107, 0.707107, 0]))\n assert all(np.isclose(seis.data[:, 1], [0, 1.41421, 1]))\n assert all(np.isclose(seis.data[:, 2], [0, 1.41421, 0]))\n assert all(np.isclose(seis.data[:, 3], [0, 0, 1]))\n seis.rotate_to_standard()\n\n # test for serialization of SphericalCoordinate\n sc_copy = pickle.loads(pickle.dumps(sc))\n assert sc_copy.radius == sc.radius\n assert sc_copy.theta == sc.theta\n assert sc_copy.phi == sc.phi\n\n a = np.zeros((3, 3))\n a[0][0] = 1.0\n a[0][1] = 1.0\n a[0][2] = 1.0\n a[1][0] = -1.0\n a[1][1] = 1.0\n a[1][2] = 1.0\n a[2][0] = 0.0\n a[2][1] = -1.0\n a[2][2] = 0.0\n seis.transform(a)\n assert all(np.isclose(seis.data[:, 0], [1, -1, 0]))\n assert all(np.isclose(seis.data[:, 1], [3, 1, -1]))\n assert all(np.isclose(seis.data[:, 2], [2, 0, -1]))\n assert all(np.isclose(seis.data[:, 3], [1, 1, 0]))\n seis_copy = pickle.loads(pickle.dumps(seis))\n seis_copy.rotate_to_standard()\n assert all(np.isclose(seis_copy.data[:, 0], [1, 0, 0]))\n assert all(np.isclose(seis_copy.data[:, 1], [1, 1, 1]))\n assert all(np.isclose(seis_copy.data[:, 2], [1, 1, 0]))\n assert all(np.isclose(seis_copy.data[:, 3], [0, 0, 1]))\n seis.rotate_to_standard()\n\n seis.rotate(np.pi/4)\n seis.transform(a)\n assert (np.isclose(seis.tmatrix,\n np.array([[1.41421, 0., 1],\n [0., 1.41421, 1],\n [-0.707107, -0.707107, 0]]))).all()\n assert all(np.isclose(seis.data[:, 0], [1.41421, 0, -0.707107]))\n assert all(np.isclose(seis.data[:, 1], [2.41421, 2.41421, -1.41421]))\n assert all(np.isclose(seis.data[:, 2], [1.41421, 1.41421, -1.41421]))\n assert all(np.isclose(seis.data[:, 3], [1, 1, 0]))\n seis.rotate_to_standard()\n assert all(np.isclose(seis.data[:, 0], [1, 0, 0]))\n assert all(np.isclose(seis.data[:, 1], [1, 1, 1]))\n assert all(np.isclose(seis.data[:, 2], [1, 1, 0]))\n assert all(np.isclose(seis.data[:, 3], [0, 0, 1]))\n\n uvec = SlownessVector()\n uvec.ux = 0.17085 # cos(-20deg)/5.5\n uvec.uy = -0.062185 # sin(-20deg)/5.5\n seis.free_surface_transformation(uvec, 5.0, 3.5)\n assert (np.isclose(seis.tmatrix,\n np.array([[-0.171012, -0.469846, 0],\n [0.115793, -0.0421458, 0.445447],\n [-0.597975, 0.217647, 0.228152]]))).all()\n\n seis.tmatrix = a\n assert (seis.tmatrix == a).all()\n\n \n # test for serialization of SlownessVector\n uvec_copy = pickle.loads(pickle.dumps(uvec))\n assert uvec_copy.ux == uvec.ux\n assert uvec_copy.uy == uvec.uy\n assert uvec_copy.azimuth() == uvec.azimuth()\n\n\[email protected](params=[TimeSeriesEnsemble, SeismogramEnsemble])\ndef Ensemble(request):\n return request.param\n\n\ndef test_Ensemble(Ensemble):\n md = Metadata()\n md['double'] = 3.14\n md['bool'] = True\n md['long'] = 7\n es = Ensemble(md, 3)\n if isinstance(es, TimeSeriesEnsemble):\n d = TimeSeries(10)\n d = make_constant_data_ts(d)\n es.member.append(d)\n es.member.append(d)\n es.member.append(d)\n else:\n d = Seismogram(10)\n d = make_constant_data_seis(d)\n es.member.append(d)\n es.member.append(d)\n es.member.append(d)\n es.set_live() # new method for LoggingEnsemble needed because default is dead\n es.sync_metadata(['double', 'long'])\n assert es.member[0].is_defined('bool')\n assert es.member[0]['bool'] == True\n assert not es.member[0].is_defined('double')\n assert not es.member[0].is_defined('long')\n es.sync_metadata()\n assert es.member[1].is_defined('double')\n assert es.member[1].is_defined('long')\n assert es.member[1]['double'] == 3.14\n assert es.member[1]['long'] == 7\n es.update_metadata(Metadata({'k': 'v'}))\n assert es['k'] == 'v'\n # From here on we test features not in CoreEnsemble but only in\n # LoggingEnsemble. Note that we use pybind11 aliasing to\n # define TimeSeriesEnsemble == LoggingEnsemble<TimeSeries> and\n # SeismogramEnsemble == LoggingEnsemble<Seismogram>.\n # Should be initially marked live\n assert es.live()\n es.elog.log_error(\"test_ensemble\",\"test complaint\",ErrorSeverity.Complaint)\n es.elog.log_error(\"test_ensemble\",\"test invalid\",ErrorSeverity.Invalid)\n assert es.elog.size() == 2\n assert es.live()\n es.kill()\n assert es.dead()\n # resurrect es\n es.set_live()\n assert es.live()\n # validate checks for for any live members - this tests that feature\n assert es.validate()\n # need this temporary copy for the next test_\n if isinstance(es,TimeSeriesEnsemble):\n escopy=TimeSeriesEnsemble(es)\n else:\n escopy=SeismogramEnsemble(es)\n for d in escopy.member:\n d.kill()\n assert not escopy.validate()\n # Reuse escopy for pickle test\n escopy=pickle.loads(pickle.dumps(es))\n assert escopy.is_defined('bool')\n assert escopy['bool'] == True\n assert escopy.is_defined('double')\n assert escopy.is_defined('long')\n assert escopy['double'] == 3.14\n assert escopy['long'] == 7\n assert escopy.live()\n assert escopy.elog.size() == 2\n assert escopy.member[0].is_defined('bool')\n assert escopy.member[0]['bool'] == True\n assert escopy.member[0].is_defined('double')\n assert escopy.member[0].is_defined('long')\n assert es.member[1].is_defined('double')\n assert es.member[1].is_defined('long')\n assert es.member[1]['double'] == 3.14\n assert es.member[1]['long'] == 7\n if isinstance(es, TimeSeriesEnsemble):\n assert es.member[1].data == escopy.member[1].data\n else:\n assert (es.member[1].data[:] == escopy.member[1].data[:]).all()\n \n\ndef test_operators():\n d = _CoreTimeSeries(10)\n d1 = make_constant_data_ts(d, nsamp=10)\n dsave = _CoreTimeSeries(d1)\n d = _CoreTimeSeries(6)\n d2 = make_constant_data_ts(d, t0=-0.2, nsamp=6, val=2.0)\n dsave = _CoreTimeSeries(d1)\n d1 += d2\n assert np.allclose(d1.data, [3, 3, 3, 3, 1, 1, 1, 1, 1, 1])\n d1 = _CoreTimeSeries(dsave)\n d = d1+d2\n assert np.allclose(d.data, [3, 3, 3, 3, 1, 1, 1, 1, 1, 1])\n d1 = _CoreTimeSeries(dsave)\n d1 *= 2.5\n assert np.allclose(\n d1.data, [2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5])\n d3 = TimeSeries(10)\n d4 = TimeSeries(6)\n d3 = make_constant_data_ts(d3, nsamp=10)\n d4 = make_constant_data_ts(d4, t0=-0.2, nsamp=6, val=2.0)\n dsave = _CoreTimeSeries(d3)\n d3 = TimeSeries(dsave)\n d3 += d4\n assert np.allclose(d3.data, [3, 3, 3, 3, 1, 1, 1, 1, 1, 1])\n d3 = TimeSeries(dsave)\n d = d3+d4\n assert np.allclose(d.data, [3, 3, 3, 3, 1, 1, 1, 1, 1, 1])\n d1 = _CoreTimeSeries(dsave)\n d3 = TimeSeries(dsave)\n d3 *= 2.5\n assert np.allclose(\n d3.data, [2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5])\n x = np.linspace(-0.7, 1.2, 20)\n for t in x:\n d3 = TimeSeries(dsave)\n d4.t0 = t\n d3 += d4\n # These are selected asserts of the incremental test above\n # visually d4 moves through d3 as the t0 value advance. Assert\n # tests end member: skewed left, inside, and skewed right\n d3 = TimeSeries(dsave)\n d4.t0 = -0.7 # no overlap test\n d3 += d4\n assert np.allclose(d3.data, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1])\n d3 = TimeSeries(dsave)\n d4.t0 = -0.3 # overlap left\n d3 += d4\n assert np.allclose(d3.data, [3, 3, 3, 1, 1, 1, 1, 1, 1, 1])\n d3 = TimeSeries(dsave)\n d4.t0 = 0.3 # d4 inside d3 test\n d3 += d4\n assert np.allclose(d3.data, [1, 1, 1, 3, 3, 3, 3, 3, 3, 1])\n d3 = TimeSeries(dsave)\n d4.t0 = 0.7 # partial overlap right\n d3 += d4\n assert np.allclose(d3.data, [1, 1, 1, 1, 1, 1, 1, 3, 3, 3])\n d3 = TimeSeries(dsave)\n d4.t0 = 1.0 # no overlap test right\n d3 += d4\n assert np.allclose(d3.data, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1])\n # Repeat the same test for Seismogram objects\n # This section is edited cut-paste of above\n # Intentionally do not test _CoreSeismogram directly because\n # currently if it works for Seismogram it will for _CoreSeismogram\n\n d = _CoreSeismogram(10)\n d1 = make_constant_data_seis(d, nsamp=10)\n dsave = _CoreSeismogram(d1)\n d = _CoreSeismogram(6)\n d2 = make_constant_data_seis(d, t0=-0.2, nsamp=6, val=2.0)\n dsave = _CoreSeismogram(d1)\n d1 += d2\n assert np.allclose(d1.data, np.array([[3., 3., 3., 3., 1., 1., 1., 1., 1., 1.],\n [3., 3., 3., 3., 1., 1., 1., 1., 1., 1.],\n [3., 3., 3., 3., 1., 1., 1., 1., 1., 1.]]))\n d1 = _CoreSeismogram(dsave)\n d = d1+d2\n assert np.allclose(d.data, np.array([[3., 3., 3., 3., 1., 1., 1., 1., 1., 1.],\n [3., 3., 3., 3., 1., 1., 1., 1., 1., 1.],\n [3., 3., 3., 3., 1., 1., 1., 1., 1., 1.]]))\n d1 = _CoreSeismogram(dsave)\n d1 *= 2.5\n assert np.allclose(d1.data, np.array([[2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5],\n [2.5, 2.5, 2.5, 2.5, 2.5,\n 2.5, 2.5, 2.5, 2.5, 2.5],\n [2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5]]))\n d3 = Seismogram(10)\n d4 = Seismogram(6)\n d3 = make_constant_data_seis(d3, nsamp=10)\n d4 = make_constant_data_seis(d4, t0=-0.2, nsamp=6, val=2.0)\n dsave = Seismogram(d3)\n d3 += d4\n assert np.allclose(d3.data, np.array([[3., 3., 3., 3., 1., 1., 1., 1., 1., 1.],\n [3., 3., 3., 3., 1., 1., 1., 1., 1., 1.],\n [3., 3., 3., 3., 1., 1., 1., 1., 1., 1.]]))\n d3 = Seismogram(dsave)\n d = d3+d4\n assert np.allclose(d.data, np.array([[3., 3., 3., 3., 1., 1., 1., 1., 1., 1.],\n [3., 3., 3., 3., 1., 1., 1., 1., 1., 1.],\n [3., 3., 3., 3., 1., 1., 1., 1., 1., 1.]]))\n d3 = Seismogram(dsave)\n d3 *= 2.5\n assert np.allclose(d1.data, np.array([[2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5],\n [2.5, 2.5, 2.5, 2.5, 2.5,\n 2.5, 2.5, 2.5, 2.5, 2.5],\n [2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5]]))\n x = np.linspace(-0.7, 1.2, 20)\n for t in x:\n d3 = Seismogram(dsave)\n d4.t0 = t\n d3 += d4\n\n # These are selected asserts of the incremental test above\n # visually d4 moves through d3 as the t0 value advance. Assert\n # tests end member: skewed left, inside, and skewed right\n d3 = Seismogram(dsave)\n d4.t0 = -0.7 # no overlap test\n d3 += d4\n assert np.allclose(d3.data, np.array([\n [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]\n ))\n\n d3 = Seismogram(dsave)\n d4.t0 = -0.3 # overlap left\n d3 += d4\n assert np.allclose(d3.data, np.array([\n [3, 3, 3, 1, 1, 1, 1, 1, 1, 1],\n [3, 3, 3, 1, 1, 1, 1, 1, 1, 1],\n [3, 3, 3, 1, 1, 1, 1, 1, 1, 1]]\n ))\n d3 = Seismogram(dsave)\n d4.t0 = 0.3 # d4 inside d3 test\n d3 += d4\n assert np.allclose(d3.data, np.array([\n [1, 1, 1, 3, 3, 3, 3, 3, 3, 1],\n [1, 1, 1, 3, 3, 3, 3, 3, 3, 1],\n [1, 1, 1, 3, 3, 3, 3, 3, 3, 1]]\n ))\n d3 = Seismogram(dsave)\n d4.t0 = 0.7 # partial overlap right\n d3 += d4\n assert np.allclose(d3.data, np.array([\n [1, 1, 1, 1, 1, 1, 1, 3, 3, 3],\n [1, 1, 1, 1, 1, 1, 1, 3, 3, 3],\n [1, 1, 1, 1, 1, 1, 1, 3, 3, 3]]\n ))\n d3 = Seismogram(dsave)\n d4.t0 = 1.0 # no overlap test right\n d3 += d4\n assert np.allclose(d3.data, np.array([\n [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]\n ))\n\n # Repeat exactly for - test but different numeric results\n # just omit *= tests\n d = _CoreTimeSeries(10)\n d1 = make_constant_data_ts(d, nsamp=10)\n dsave = _CoreTimeSeries(d1)\n d = _CoreTimeSeries(6)\n d2 = make_constant_data_ts(d, t0=-0.2, nsamp=6, val=2.0)\n dsave = _CoreTimeSeries(d1)\n d1 -= d2\n assert np.allclose(d1.data, [-1, -1, -1, -1, 1, 1, 1, 1, 1, 1])\n d1 = _CoreTimeSeries(dsave)\n d = d1-d2\n assert np.allclose(d.data, [-1, -1, -1, -1, 1, 1, 1, 1, 1, 1])\n d3 = TimeSeries(10)\n d4 = TimeSeries(6)\n d3 = make_constant_data_ts(d3, nsamp=10)\n d4 = make_constant_data_ts(d4, t0=-0.2, nsamp=6, val=2.0)\n dsave = _CoreTimeSeries(d3)\n d3 = TimeSeries(dsave)\n d3 -= d4\n assert np.allclose(d3.data, [-1, -1, -1, -1, 1, 1, 1, 1, 1, 1])\n d3 = TimeSeries(dsave)\n d = d3-d4\n assert np.allclose(d.data, [-1, -1, -1, -1, 1, 1, 1, 1, 1, 1])\n x = np.linspace(-0.7, 1.2, 20)\n for t in x:\n d3 = TimeSeries(dsave)\n d4.t0 = t\n d3 -= d4\n # These are selected asserts of the incremental test above\n # visually d4 moves through d3 as the t0 value advance. Assert\n # tests end member: skewed left, inside, and skewed right\n d3 = TimeSeries(dsave)\n d4.t0 = -0.7 # no overlap test\n d3 -= d4\n assert np.allclose(d3.data, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1])\n d3 = TimeSeries(dsave)\n d4.t0 = -0.3 # overlap left\n d3 -= d4\n assert np.allclose(d3.data, [-1, -1, -1, 1, 1, 1, 1, 1, 1, 1])\n d3 = TimeSeries(dsave)\n d4.t0 = 0.3 # d4 inside d3 test\n d3 -= d4\n assert np.allclose(d3.data, [1, 1, 1, -1, -1, -1, -1, -1, -1, 1])\n d3 = TimeSeries(dsave)\n d4.t0 = 0.7 # partial overlap right\n d3 -= d4\n assert np.allclose(d3.data, [1, 1, 1, 1, 1, 1, 1, -1, -1, -1])\n d3 = TimeSeries(dsave)\n d4.t0 = 1.0 # no overlap test right\n d3 -= d4\n assert np.allclose(d3.data, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1])\n\n # Repeat the same test for Seismogram objects\n # This section is edited cut-paste of above\n # Intentionally do not test _CoreSeismogram directly because\n # currently if it works for Seismogram it will for _CoreSeismogram\n d = _CoreSeismogram(10)\n d1 = make_constant_data_seis(d, nsamp=10)\n dsave = _CoreSeismogram(d1)\n d = _CoreSeismogram(6)\n d2 = make_constant_data_seis(d, t0=-0.2, nsamp=6, val=2.0)\n dsave = _CoreSeismogram(d1)\n d1 -= d2\n assert np.allclose(d1.data, np.array([[-1., -1., -1., -1., 1., 1., 1., 1., 1., 1.],\n [-1., -1., -1., -1., 1.,\n 1., 1., 1., 1., 1.],\n [-1., -1., -1., -1., 1., 1., 1., 1., 1., 1.]]))\n d1 = _CoreSeismogram(dsave)\n d = d1-d2\n assert np.allclose(d.data, np.array([[-1., -1., -1., -1., 1., 1., 1., 1., 1., 1.],\n [-1., -1., -1., -1., 1.,\n 1., 1., 1., 1., 1.],\n [-1., -1., -1., -1., 1., 1., 1., 1., 1., 1.]]))\n\n d3 = Seismogram(10)\n d4 = Seismogram(6)\n d3 = make_constant_data_seis(d3, nsamp=10)\n d4 = make_constant_data_seis(d4, t0=-0.2, nsamp=6, val=2.0)\n dsave = Seismogram(d3)\n d3 -= d4\n assert np.allclose(d3.data, np.array([[-1., -1., -1., -1., 1., 1., 1., 1., 1., 1.],\n [-1., -1., -1., -1., 1.,\n 1., 1., 1., 1., 1.],\n [-1., -1., -1., -1., 1., 1., 1., 1., 1., 1.]]))\n d3 = Seismogram(dsave)\n d = d3-d4\n assert np.allclose(d.data, np.array([[-1., -1., -1., -1., 1., 1., 1., 1., 1., 1.],\n [-1., -1., -1., -1., 1.,\n 1., 1., 1., 1., 1.],\n [-1., -1., -1., -1., 1., 1., 1., 1., 1., 1.]]))\n\n x = np.linspace(-0.7, 1.2, 20)\n for t in x:\n d3 = Seismogram(dsave)\n d4.t0 = t\n d3 -= d4\n\n # These are selected asserts of the incremental test above\n # visually d4 moves through d3 as the t0 value advance. Assert\n # tests end member: skewed left, inside, and skewed right\n d3 = Seismogram(dsave)\n d4.t0 = -0.7 # no overlap test\n d3 -= d4\n assert np.allclose(d3.data, np.array([\n [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]\n ))\n d3 = Seismogram(dsave)\n d4.t0 = -0.3 # overlap left\n d3 -= d4\n assert np.allclose(d3.data, np.array([\n [-1, -1, -1, 1, 1, 1, 1, 1, 1, 1],\n [-1, -1, -1, 1, 1, 1, 1, 1, 1, 1],\n [-1, -1, -1, 1, 1, 1, 1, 1, 1, 1]]\n ))\n d3 = Seismogram(dsave)\n d4.t0 = 0.3 # d4 inside d3 test\n d3 -= d4\n assert np.allclose(d3.data, np.array([\n [1, 1, 1, -1, -1, -1, -1, -1, -1, 1],\n [1, 1, 1, -1, -1, -1, -1, -1, -1, 1],\n [1, 1, 1, -1, -1, -1, -1, -1, -1, 1]]\n ))\n d3 = Seismogram(dsave)\n d4.t0 = 0.7 # partial overlap right\n d3 -= d4\n assert np.allclose(d3.data, np.array([\n [1, 1, 1, 1, 1, 1, 1, -1, -1, -1],\n [1, 1, 1, 1, 1, 1, 1, -1, -1, -1],\n [1, 1, 1, 1, 1, 1, 1, -1, -1, -1]]\n ))\n d3 = Seismogram(dsave)\n d4.t0 = 1.0 # no overlap test right\n d3 -= d4\n assert np.allclose(d3.data, np.array([\n [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]\n ))\n\n\ndef test_ExtractComponent():\n seis = Seismogram()\n seis.live = 1\n seis.data = dmatrix(np.random.rand(3, 6))\n seis.npts = 6\n ts = []\n for i in range(3):\n ts.append(ExtractComponent(seis, i))\n for i in range(3):\n assert (ts[i].data == seis.data[i]).all()\n\n\[email protected](params=[ProcessingHistory,\n Seismogram,\n TimeSeries])\ndef ProcessingHistoryBase(request):\n return request.param\n\n\ndef test_ProcessingHistoryBase(ProcessingHistoryBase):\n ph = ProcessingHistoryBase()\n ph.set_jobname(\"testjob\")\n ph.set_jobid(\"999\")\n assert ph.elog.log_error('1', '2', ErrorSeverity(3)) == 1\n assert ph.elog[0].badness == ErrorSeverity.Complaint\n\n ph2 = ProcessingHistoryBase(ph)\n assert ph.jobname() == ph2.jobname()\n assert ph.jobid() == ph2.jobid()\n assert ph.elog[0].badness == ph2.elog[0].badness\n assert ph.elog[0].algorithm == ph2.elog[0].algorithm\n assert ph.elog[0].message == ph2.elog[0].message\n\n ph2 = ProcessingHistoryBase(ph)\n assert ph.jobname() == ph2.jobname()\n assert ph.jobid() == ph2.jobid()\n\n ph.set_as_raw(\"fakeinput\", \"0\", \"fakeuuid1\", AtomicType.SEISMOGRAM)\n ph.new_map(\"onetoone\", \"0\", AtomicType.SEISMOGRAM)\n assert len(ph.get_nodes()) == 1\n phred = ProcessingHistoryBase(ph)\n ph_list = []\n for i in range(4):\n ph_list.append(ProcessingHistoryBase())\n ph_list[i].set_as_raw(\"fakedataset\", \"0\",\n \"fakeid_\"+str(i), AtomicType.SEISMOGRAM)\n ph_list[i].new_map(\"onetoone\", \"0\", AtomicType.SEISMOGRAM)\n phred.new_ensemble_process(\n \"testreduce\", \"0\", AtomicType.SEISMOGRAM, ph_list)\n dic = phred.get_nodes()\n rec = 0\n for i in dic.keys():\n for j in dic[i]:\n print(i, \" : \", j.uuid, \" , \", j.status)\n rec += 1\n assert rec == 8\n\n ph_list2 = copy.deepcopy(ph_list)\n ph_list3 = copy.deepcopy(ph_list)\n # a stack in order\n ph_list2[0].accumulate(\n \"stack\", \"stack1\", AtomicType.SEISMOGRAM, ph_list2[1])\n ph_list2[0].accumulate(\n \"stack\", \"stack1\", AtomicType.SEISMOGRAM, ph_list2[2])\n ph_list2[0].accumulate(\n \"stack\", \"stack1\", AtomicType.SEISMOGRAM, ph_list2[3])\n # a stack out of order\n ph_list3[0].accumulate(\n \"stack\", \"stack1\", AtomicType.SEISMOGRAM, ph_list3[2])\n ph_list3[3].accumulate(\n \"stack\", \"stack1\", AtomicType.SEISMOGRAM, ph_list3[1])\n ph_list3[0].accumulate(\n \"stack\", \"stack1\", AtomicType.SEISMOGRAM, ph_list3[3])\n assert len(ph_list2[0].get_nodes()) == 5\n assert len(ph_list3[0].get_nodes()) == 5\n nodes2 = {}\n for k, v in ph_list2[0].get_nodes().items():\n if k not in ph_list2[0].id():\n nodes2[k] = str(v)\n nodes3 = {}\n for k, v in ph_list3[0].get_nodes().items():\n if k not in ph_list3[0].id():\n nodes3[k] = str(v)\n assert nodes2 == nodes3\n nodes2 = []\n for i in ph_list2[0].get_nodes()[ph_list2[0].id()]:\n nodes2.append(str(i))\n nodes3 = []\n for i in ph_list3[0].get_nodes()[ph_list3[0].id()]:\n nodes3.append(str(i))\n assert nodes2.sort() == nodes3.sort()\n\n phred_copy = pickle.loads(pickle.dumps(phred))\n assert str(phred.get_nodes()) == str(phred_copy.get_nodes())\n\n\ndef test_MsPASSError():\n try:\n x = MetadataDefinitions('foo')\n except MsPASSError as err:\n assert err.message == 'bad file'\n assert err.severity == ErrorSeverity.Invalid\n try:\n raise MsPASSError('test error1', ErrorSeverity.Informational)\n except MsPASSError as err:\n assert err.message == 'test error1'\n assert err.severity == ErrorSeverity.Informational\n try:\n raise MsPASSError('test error2', \"Suspect\")\n except MsPASSError as err:\n assert err.message == 'test error2'\n assert err.severity == ErrorSeverity.Suspect\n try:\n raise MsPASSError('test error3', 123)\n except MsPASSError as err:\n assert err.message == 'test error3'\n assert err.severity == ErrorSeverity.Fatal\n try:\n raise MsPASSError(\"test error4\")\n except MsPASSError as err:\n assert err.message == 'test error4'\n assert err.severity == ErrorSeverity.Fatal\n" ]
[ [ "numpy.allclose", "numpy.linspace", "numpy.sqrt", "numpy.random.rand", "numpy.equal", "numpy.float_", "numpy.array", "numpy.zeros", "numpy.isclose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ytakano3/MPAS-Analysis
[ "fbb1f5189782b9abe9ff368f7c96484fd4832937" ]
[ "mpas_analysis/shared/plot/ticks.py" ]
[ "# This software is open source software available under the BSD-3 license.\n#\n# Copyright (c) 2020 Triad National Security, LLC. All rights reserved.\n# Copyright (c) 2020 Lawrence Livermore National Security, LLC. All rights\n# reserved.\n# Copyright (c) 2020 UT-Battelle, LLC. All rights reserved.\n#\n# Additional copyright and license information can be found in the LICENSE file\n# distributed with this code, or at\n# https://raw.githubusercontent.com/MPAS-Dev/MPAS-Analysis/master/LICENSE\n# Authors\n# -------\n# Xylar Asay-Davis, Milena Veneziani, Luke Van Roekel, Greg Streletz\n\nfrom __future__ import absolute_import, division, print_function, \\\n unicode_literals\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import FuncFormatter, FixedLocator\nimport numpy as np\nfrom functools import partial\n\nfrom mpas_analysis.shared.timekeeping.utility import days_to_datetime, \\\n date_to_days\n\n\ndef plot_xtick_format(calendar, minDays, maxDays, maxXTicks, yearStride=None):\n '''\n Formats tick labels and positions along the x-axis for time series\n / index plots\n\n Parameters\n ----------\n calendar : str\n the calendar to use for formatting the time axis\n\n minDays : float\n start time for labels\n\n maxDays : float\n end time for labels\n\n maxXTicks : int\n the maximum number of tick marks to display, used to sub-sample ticks\n if there are too many\n\n yearStride : int, optional\n the number of years to skip over between ticks\n '''\n # Authors\n # -------\n # Xylar Asay-Davis\n\n ax = plt.gca()\n\n start = days_to_datetime(np.amin(minDays), calendar=calendar)\n end = days_to_datetime(np.amax(maxDays), calendar=calendar)\n\n if yearStride is not None or end.year - start.year > maxXTicks / 2:\n if yearStride is None:\n yearStride = 1\n else:\n maxXTicks = None\n major = [date_to_days(year=year, calendar=calendar)\n for year in np.arange(start.year, end.year + 1, yearStride)]\n formatterFun = partial(_date_tick, calendar=calendar,\n includeMonth=False)\n else:\n # add ticks for months\n major = []\n for year in range(start.year, end.year + 1):\n for month in range(1, 13):\n major.append(date_to_days(year=year, month=month,\n calendar=calendar))\n formatterFun = partial(_date_tick, calendar=calendar,\n includeMonth=True)\n\n ax.xaxis.set_major_locator(FixedLocator(major, maxXTicks))\n ax.xaxis.set_major_formatter(FuncFormatter(formatterFun))\n\n plt.setp(ax.get_xticklabels(), rotation=30)\n\n plt.autoscale(enable=True, axis='x', tight=True)\n\n\ndef _date_tick(days, pos, calendar='gregorian', includeMonth=True):\n days = np.maximum(days, 0.)\n date = days_to_datetime(days, calendar)\n if includeMonth:\n return '{:04d}-{:02d}'.format(date.year, date.month)\n else:\n return '{:04d}'.format(date.year)\n\n\n# vim: foldmethod=marker ai ts=4 sts=4 et sw=4 ft=python\n" ]
[ [ "matplotlib.pyplot.gca", "numpy.amax", "numpy.maximum", "matplotlib.pyplot.autoscale", "numpy.amin", "numpy.arange", "matplotlib.ticker.FuncFormatter", "matplotlib.ticker.FixedLocator" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
majingliang/machine_learning
[ "54471182ac21ef0eee26557a7bd6f3a3dc3a09bd" ]
[ "Tsnewp/examples/examples.py" ]
[ "from Tsnewp import Tsnewp\nimport numpy as np\n\ndata = np.random.random((1000,100))\ntsne = Tsnewp()\nnew_data = tsne.transform(data)\n\n" ]
[ [ "numpy.random.random" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
immanuelweber/glimmer-utils
[ "4cb1d03aee712795810f09a62df517fce76a5ed1" ]
[ "glimmer/lightning/progressplotter.py" ]
[ "# Copyright (c) 2021 Immanuel Weber. Licensed under the MIT license (see LICENSE).\n\nimport random\nfrom collections import defaultdict\nfrom typing import Any\n\nimport numpy as np\nimport torch\nfrom IPython.display import display\nfrom matplotlib import pyplot as plt\nfrom pytorch_lightning import LightningModule\nfrom pytorch_lightning.callbacks import Callback\n\nfrom .lightning_derived import get_lrs, get_scheduler_names\n\n# for multiple y axis see\n# https://stackoverflow.com/questions/9103166/multiple-axis-in-matplotlib-with-different-scales\n\n\nclass ProgressPlotter(Callback):\n def __init__(\n self,\n highlight_best: bool = True,\n show_extra_losses: bool = True,\n show_steps: bool = True,\n show_lr: bool = True,\n silent: bool = False,\n ):\n self.highlight_best = highlight_best\n self.best_of = \"val\" # not implemented\n self.show_extra_losses = show_extra_losses\n self.metrics = []\n self.train_loss = []\n self.val_loss = []\n self.extra_metrics = defaultdict(list)\n self.extra_style = \"--\"\n self.steps = []\n self.did = None\n self.show_lr = show_lr\n self.lrs = defaultdict(list)\n self.lr_color = plt.cm.viridis(0.5)\n self.show_steps = show_steps\n self.silent = silent\n\n def on_train_start(self, trainer, pl_module: LightningModule) -> None:\n self.scheduler_names = get_scheduler_names(trainer.lr_schedulers)\n self.steps_per_epoch = trainer.num_training_batches\n\n def on_train_batch_end(\n self,\n trainer,\n pl_module: LightningModule,\n outputs: Any,\n batch: Any,\n batch_idx: int,\n ) -> None:\n self.train_loss.append(float(trainer.callback_metrics[\"loss\"]))\n lrs = get_lrs(trainer.lr_schedulers, self.scheduler_names, \"step\")\n for k, v in lrs.items():\n self.lrs[k].append(v)\n\n def on_train_epoch_start(self, trainer, pl_module) -> None:\n return super().on_train_epoch_start(trainer, pl_module)\n\n def on_train_epoch_end(self, trainer, pl_module: LightningModule) -> None:\n self.collect_metrics(trainer)\n if not self.silent:\n self.update_plot(\n trainer, self.highlight_best, self.show_lr, self.show_steps\n )\n\n def collect_metrics(self, trainer):\n val_loss = None\n raw_metrics = trainer.logged_metrics.copy()\n ignored_metrics = [\"loss\", \"epoch\"]\n for m in ignored_metrics:\n if m in raw_metrics:\n raw_metrics.pop(m)\n if \"val_loss\" in raw_metrics:\n val_loss = float(raw_metrics.pop(\"val_loss\"))\n elif \"val_loss_epoch\" in raw_metrics:\n val_loss = float(raw_metrics.pop(\"val_loss_epoch\"))\n if \"val_loss_step\" in raw_metrics:\n raw_metrics.pop(\"val_loss_step\")\n if val_loss is not None:\n self.val_loss.append(val_loss)\n self.steps.append(trainer.global_step)\n for key, value in raw_metrics.items():\n if isinstance(value, torch.Tensor):\n value = value.cpu()\n self.extra_metrics[key].append(value)\n\n def update_plot(self, trainer, highlight_best, show_lr, show_steps):\n fig, ax = plt.subplots()\n plt.close(fig)\n if trainer.max_steps:\n max_steps_from_epochs = trainer.max_epochs * trainer.num_training_batches\n max_steps = min(trainer.max_steps, max_steps_from_epochs)\n else:\n max_steps = trainer.max_epochs * trainer.num_training_batches\n self.static_plot(ax, show_lr, highlight_best, show_steps, max_steps=max_steps)\n\n if self.did:\n self.did.update(fig)\n else:\n rand_id = random.randint(0, 1e6)\n self.did = display(fig, display_id=23 + rand_id)\n\n def static_plot(\n self,\n ax=None,\n show_lr=True,\n highlight_best=False,\n show_steps=True,\n max_steps=None,\n ):\n if ax is None:\n fig, ax = plt.subplots()\n max_steps = max_steps if max_steps else len(self.train_loss)\n step_ax = ax.twiny()\n step_ax.set_xlabel(\"step\")\n step_ax.set_xlim(0, max_steps)\n if not show_steps:\n step_ax.set_xticks([])\n step_ax.set_xlabel(\"\")\n\n step_ax.plot(self.train_loss, label=\"loss\")\n ax.set_xlabel(\"epoch\")\n ax.set_xlim([0, max_steps / self.steps_per_epoch])\n\n if self.val_loss:\n ph = step_ax.plot(self.steps, self.val_loss, label=\"val_loss\")\n if highlight_best:\n best_epoch = np.argmin(self.val_loss)\n best_step = (best_epoch + 1) * self.steps_per_epoch\n best_loss = self.val_loss[best_epoch]\n step_ax.plot(best_step, best_loss, \"o\", c=ph[0].get_color())\n lines, labels = step_ax.get_legend_handles_labels()\n\n if len(self.extra_metrics) and self.show_extra_losses:\n extra_ax = step_ax.twinx()\n extra_ax.set_ylabel(\"extra metrics\")\n for key in sorted(self.extra_metrics.keys()):\n extra_ax.plot(\n self.steps, self.extra_metrics[key], self.extra_style, label=key\n )\n extra_lines, extra_labels = extra_ax.get_legend_handles_labels()\n lines += extra_lines\n labels += extra_labels\n if show_lr and len(self.lrs):\n lr_ax = step_ax.twinx()\n lr_ax.set_ylabel(\"lr\")\n lr_ax.spines[\"right\"].set_position((\"outward\", 60))\n for key, lrs in self.lrs.items():\n lr_ax.plot(lrs, c=self.lr_color, label=key)\n lr_ax.yaxis.label.set_color(self.lr_color)\n\n step_ax.legend(lines, labels, loc=0)\n" ]
[ [ "matplotlib.pyplot.cm.viridis", "numpy.argmin", "matplotlib.pyplot.subplots", "matplotlib.pyplot.close" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
qianrenjian/hy_learn
[ "bd8927b21a62d4bb77fc14f85871b2c4530007ba" ]
[ "pytorch_fm/torchfm/layer.py" ]
[ "# -*- coding:utf-8 -*-\n# -*- @author:hanyan5\n# -*- @date:2020/10/22 19:11\n# -*- python3.6\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass FeaturesLinear(nn.Module):\n def __init__(self, field_dims, output_dim=1):\n super().__init__()\n self.fc = nn.Embedding(sum(field_dims), output_dim)\n self.bias = nn.Parameter(torch.zeros((output_dim, )))\n self.offsets = np.array((0, *np.cumsum(field_dims)[:-1]), dtype=np.long)\n\n def forward(self, x):\n \"\"\"\n :param x: Long tensor of size ``(batch_size, num_fields)``\n \"\"\"\n x = x + x.new_tensor(self.offsets).unsqueeze(0)\n return torch.sum(self.fc(x), dim=1) + self.bias\n" ]
[ [ "numpy.cumsum", "torch.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
gitwithmch/opencv
[ "a8844de7b5ffad08b4463536d21aadd6c0d1f3b3" ]
[ "samples/python/mouse_and_match.py" ]
[ "#!/usr/bin/env python\n'''\nmouse_and_match.py [-i path | --input path: default ../data/]\n\nDemonstrate using a mouse to interact with an image:\n Read in the images in a directory one by one\n Allow the user to select parts of an image with a mouse\n When they let go of the mouse, it correlates (using matchTemplate) that patch with the image.\n\n SPACE for next image\n ESC to exit\n'''\n\n# Python 2/3 compatibility\nfrom __future__ import print_function\n\nimport numpy as np\nimport cv2 as cv\n\n# built-in modules\nimport os\nimport sys\nimport glob\nimport argparse\nfrom math import *\n\n\ndrag_start = None\nsel = (0,0,0,0)\n\ndef onmouse(event, x, y, flags, param):\n global drag_start, sel\n if event == cv.EVENT_LBUTTONDOWN:\n drag_start = x, y\n sel = 0,0,0,0\n elif event == cv.EVENT_LBUTTONUP:\n if sel[2] > sel[0] and sel[3] > sel[1]:\n patch = gray[sel[1]:sel[3],sel[0]:sel[2]]\n result = cv.matchTemplate(gray,patch,cv.TM_CCOEFF_NORMED)\n result = np.abs(result)**3\n _val, result = cv.threshold(result, 0.01, 0, cv.THRESH_TOZERO)\n result8 = cv.normalize(result,None,0,255,cv.NORM_MINMAX,cv.CV_8U)\n cv.imshow(\"result\", result8)\n drag_start = None\n elif drag_start:\n #print flags\n if flags & cv.EVENT_FLAG_LBUTTON:\n minpos = min(drag_start[0], x), min(drag_start[1], y)\n maxpos = max(drag_start[0], x), max(drag_start[1], y)\n sel = minpos[0], minpos[1], maxpos[0], maxpos[1]\n img = cv.cvtColor(gray, cv.COLOR_GRAY2BGR)\n cv.rectangle(img, (sel[0], sel[1]), (sel[2], sel[3]), (0,255,255), 1)\n cv.imshow(\"gray\", img)\n else:\n print(\"selection is complete\")\n drag_start = None\n\nif __name__ == '__main__':\n print(__doc__)\n\n parser = argparse.ArgumentParser(description='Demonstrate mouse interaction with images')\n parser.add_argument(\"-i\",\"--input\", default='../data/', help=\"Input directory.\")\n args = parser.parse_args()\n path = args.input\n\n cv.namedWindow(\"gray\",1)\n cv.setMouseCallback(\"gray\", onmouse)\n '''Loop through all the images in the directory'''\n for infile in glob.glob( os.path.join(path, '*.*') ):\n ext = os.path.splitext(infile)[1][1:] #get the filename extenstion\n if ext == \"png\" or ext == \"jpg\" or ext == \"bmp\" or ext == \"tiff\" or ext == \"pbm\":\n print(infile)\n\n img=cv.imread(infile,1)\n if img is None:\n continue\n sel = (0,0,0,0)\n drag_start = None\n gray=cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n cv.imshow(\"gray\",gray)\n if cv.waitKey() == 27:\n break\n cv.destroyAllWindows()\n" ]
[ [ "numpy.abs" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
AFRL-RY/Explore-Coarse-3D-Reconstruction-Path-Planning-Summer-2017
[ "6c76e09f4fc2026d6b3efb421b7a56b480f5696b" ]
[ "initCameras.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 26 22:56:36 2016\n\n@author: oacom\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\ndef generateCameras(terrain, normals, cfg):\n '''\n Calculates positions and orientations of initial population of cameras\n based off of the surface normals\n \n INPUTS\n nn: Terrain north values\n ee: Terrain east values\n dd: Terrain elevation values\n norm_n: North component of surface normals\n norm_e: East component of surface normals\n norm_d: Vertical component of surface normals\n elevation: Desired flight elevation (m)\n OUTPUTS\n Returns camera position vectors cn, ce, cd, and camera orientation vectors\n cor_n, cor_e, and cor_d\n '''\n # Convert 2D grid values to 1D vectors\n nu = np.ravel(terrain.nn)\n eu = np.ravel(terrain.ee)\n du = np.ravel(terrain.dd)\n \n # Unpack normals\n norm_n = normals.norm_n.values\n norm_e = normals.norm_e.values\n norm_d = normals.norm_d.values\n \n # Calculate camera positions\n elevation = cfg['flightPath']['elevation']\n cn = nu + norm_n * (elevation-du)/norm_d\n ce = eu + norm_e * (elevation-du)/norm_d\n cd = du + norm_d * (elevation-du)/norm_d\n \n # Calculate camera orientation vectors (just reflection of surface normal)\n cor_n = -norm_n\n cor_e = -norm_e\n cor_d = -norm_d\n\n # Up vector for cameras\n cup_n = np.zeros(cn.shape)\n cup_e = np.zeros(cn.shape)\n cup_d = np.ones(cn.shape)\n\n # Fields of view\n alphax = np.ones(cn.shape) * cfg['flightPath']['alphax']\n alphay = np.ones(cn.shape) * cfg['flightPath']['alphay']\n \n # Only return cameras that are reasonable close\n offset = (elevation-du)/norm_d\n idx = offset <= (elevation-terrain.dd.mean())*3\n\n # Pack camera information\n # Pack camera information\n cameras = pd.DataFrame({'cn':cn[idx],\n 'ce':ce[idx],\n 'cd':cd[idx],\n 'cor_n':cor_n[idx],\n 'cor_e':cor_e[idx],\n 'cor_d':cor_d[idx],\n 'cup_n':cup_n[idx],\n 'cup_e':cup_e[idx],\n 'cup_d':cup_d[idx],\n 'alphax':alphax[idx],\n 'alphay':alphay[idx]})\n \n return cameras" ]
[ [ "numpy.ravel", "numpy.zeros", "pandas.DataFrame", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
iamsmkr/Raphtory
[ "8b5a65748e71bd1914b7fbacac48d925e15c9d67" ]
[ "python/raphtoryclient/client.py" ]
[ "\"\"\"\nThe Raphtory Python client library to interact with Raphtory from Python.\n\nCurrently, the supported Python versions are 3.\n\n## Install from PyPI\n\n #!shell\n $ sudo pip install raphtory-client\n\n## Examples\n\nExample jupyter notebooks can be found at https://www.github.com/raphtory/examples\n\n\"\"\"\n\nimport pulsar\nfrom pulsar.schema import schema\nimport random\nimport string\nimport requests\nimport time\nimport csv\nimport networkx as nx\nimport sys\nimport pandas as pd\nfrom datetime import datetime, timezone\n\n\nclass client:\n '''\n This is the class to create a raphtory client which interacts with pulsar.\n '''\n\n def __init__(self, admin_url=\"http://127.0.0.1:8080\", client_args=None):\n '''\n Parameters:\n admin_url: the url for the pulsar admin client\n : Dict of arguments to be used in the pulsar client, keys must match pulsar.Client parameters\n '''\n if client_args is None:\n client_args = {'service_url': 'pulsar://127.0.0.1:6650'}\n elif 'service_url' not in client_args:\n print('service_url not given in client_args, exiting..')\n sys.exit(1)\n self.client = self.setupClient(max_attempts=5, client_args=client_args)\n if self.client == None:\n print('Could not setup client')\n sys.exit(1)\n self.admin_url = admin_url\n self.first_seen = \"\"\n\n def make_name(self):\n '''\n Helper function which generates a random\n subscription suffix for the reader.\n\n Parameters:\n none\n\n Returns:\n str: subcription suffix\n '''\n return ''.join(random.choice(string.ascii_letters + string.punctuation) for x in range(10))\n\n def setupClient(self, client_args, max_attempts=5):\n '''\n Setups a pulsar client using the pulsar address.\n Retries at least 5 times before returning\n\n Parameters:\n client_args (dict): Dict of arguments to be used in the pulsar client,\n keys must match pulsar.Client parameters\n max_attempts (int) : Number of attempts to retry\n\n Returns:\n PulsarClient: A pulsar client object if successful\n None (None): None if not successful\n '''\n print('Creating RaphtoryClient object...')\n attempts = 0\n while attempts <= max_attempts:\n attempts += 1\n try:\n client = pulsar.Client(**client_args)\n print('Created.')\n return client\n except Exception as e:\n print('Could not connect Client to Pulsar, trying again...')\n print(e)\n print('Could not connect client to Pulsar')\n return None\n\n\n def createReader(self, topic, subscription_name='', schema=schema.StringSchema()):\n '''\n Setups a single pulsar reader, which reads from a pulsar topic.\n Retries at least 5 times before returning\n\n Parameters:\n topic (str): Names of topic to read from\n subscription_name (str): Name for this readers subscription\n schema (Pulsar Schema): Schema to use for reader\n\n Returns:\n PulsarReader: A pulsar reader object\n None (None): None if not successful\n '''\n if subscription_name == '':\n subscription_name = \"python_reader_\" + self.make_name()\n attempts = 0\n while (attempts <= 5):\n attempts += 1\n try:\n reader = self.client.create_reader(\n topic,\n pulsar.MessageId.earliest,\n reader_name=subscription_name + '_' + self.make_name(),\n schema=schema)\n print(\"Connected to topic: \" + str(topic))\n return reader\n break\n except Exception as e:\n print(\"Could not connect to \" + str(topic) + \", trying again\")\n print(e)\n if attempts == 5:\n print(\"Could not connect to \" + str(topic) + \" after 5 attempts\")\n return None\n\n def getStats(self, topic, tenant=\"public\", namespace=\"default\"):\n '''\n Reads stats from a pulsar topic using the admin interface.\n If success returns the response as json else returns an empty dict.\n\n Parameters:\n topic (str): Topic to obtain stats from\n tenant (str): (Optional, default: public) Pulsar tenant to access\n namepsace (str): (Optional, default: default) Pulsar namespace to access\n\n Returns:\n json response (dict/json): The response of the request. If unsuccessful then returns an empty dict.\n '''\n url = self.admin_url + \"/admin/v2/persistent/\" + tenant + \"/\" + namespace + \"/\" + topic + \"/stats\"\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()\n else:\n print(\"Error \" + str(response.status_code) + \" when reading topic stats from \" + url)\n return {}\n\n def getDataframe(self, reader, delimiter=',', max_messages=sys.maxsize, col_names=[]):\n '''\n Using the reader, reads a complete topic and converts\n it into a pandas Dataframe. This will split each message\n from the reader using the delimiter.\n If columns names are not then, then by default, columns are called result_N.\n\n Parameters:\n reader (Pulsar Reader): Reader where messages will be pulled from\n delimiter (str): the delimiter for parsing the results\n max_messages (int): (Optional, default:sys.maxsize) The number of messages to return.\n By default, it returns the entire topic. This may cause memory\n issues.\n col_names (list[string]): (Optional: default: [\"timestamp\", \"window\", \"id\"]). These are\n the names of the columns. By default this expects the results\n to have three columns called timestamp, window and id. Any\n columns after this are called result_N.\n\n Returns:\n dataframe (pandas.dataframe): A dataframe of the topic\n '''\n print(\"Obtaining dataframe...\\n\")\n messages = []\n count = 0\n wait_counter = 0\n while (count < max_messages):\n if count % 100 == 0:\n print(\"Results processed %i\" % (count), end=\"\\r\")\n try:\n message_temp = reader.read_next(timeout_millis=3000)\n if message_temp != None:\n decoded = message_temp.data().decode(\"utf-8\").replace(\"\\n\", \"\").split(delimiter)\n messages.append(decoded)\n count += 1\n else:\n time.sleep(2)\n wait_counter += 1\n if wait_counter == 3:\n break\n except pulsar.Timeout as e:\n wait_counter += 1\n if wait_counter == 3:\n break\n except Exception as e:\n print(\"Issue retrieving messages. trying again...\")\n print(e)\n wait_counter += 1\n if wait_counter == 6:\n break\n print(\"Converting to columns...\")\n if len(messages) != 0:\n num_cols = len(messages[0])\n if len(col_names):\n for i in range(len(col_names), num_cols, 1): col_names.append(\"result_\" + str(i - len(col_names)))\n else:\n for i in range(0, num_cols, 1): col_names.append(\"result_\" + str(i))\n print(\"Completed.\")\n return pd.DataFrame(messages, columns=col_names)\n\n def find_dates(self, all_data, node_a_id=0, node_b_id=1, time_col=2):\n '''\n Given a dataframe of edges, this will find the first time an item was seen.\n This is returned as a dict with the key being the id and the value time.\n This can be helpful when trying to identify when a node was first created.\n\n Parameters:\n all_data (dataframe): A dataframe containing a column with keys and a column with times/numbers to compare with.\n node_a_id (int): Position of the id or name to use as key for node A\n node_b_id (int): Position of the id or name to use as key for node B\n time_col (int): Position of the time column which is compared\n\n Returns:\n first_seen (dict): A dictionary with the key= node_id and the value = time\n '''\n first_seen = {}\n for (i, row) in all_data.iterrows():\n if (row[node_a_id] not in first_seen) or (\n row[node_a_id] in first_seen and first_seen[row[node_a_id]] > int(row[time_col])):\n first_seen[row[node_a_id]] = int(row[time_col])\n if (row[node_b_id] not in first_seen) or (\n row[node_b_id] in first_seen and first_seen[row[node_b_id]] > int(row[time_col])):\n first_seen[row[node_b_id]] = int(row[time_col])\n return first_seen\n\n def add_node_attributes(self, G, results, abbr, row_id=2, time_col=0, window_col=-1,\n result_col=3):\n '''\n Given a graph, an array of attributes and a abbreviation.\n This will add all the attributes to the graph.\n For example, given a graph G, results\n\n Parameters:\n G (networkx.graph): A networkx graph\n results (list[dict]): A list of dataframes which contain attributes.\n The format for attributes is a dataframe with\n id: node id\n timestamp: time the attribute was created\n window: (optional) the window the attribute was created\n result_col: the value of the attribute\n abbr (list(str)): A list of strings which correspond to the abbreviation used when appending the attribute.\n row_id (int/str): Column position which contains ID / Name of the row id column to use, must be the same across results\n time_col (int/str): Column position which contains the timestamp / Name of the timestamp column to use\n result_col (int/str): Column position which contains result / Name of the result column\n window_col (int/str): (Optional, default:'window') Column position which contains window /\n Name of the window column, set to '' if not being used\n '''\n attributes = {}\n for (j, result) in enumerate(results):\n for (i, row) in result.iterrows():\n if row[row_id] not in attributes:\n attributes[row[row_id]] = {}\n if window_col != -1:\n attributes[row[row_id]][abbr[j] + '_' + row[time_col] + '_' + row[window_col]] = row[result_col]\n else:\n attributes[row[row_id]][abbr[j] + '_' + row[time_col]] = row[result_col]\n nx.set_node_attributes(G, attributes)\n\n def createGraphFromEdgeList(self, df, isMultiGraph=True):\n '''\n Builds a simple networkx graph from an edge list in Raphtory.\n\n Parameters:\n df (pandas.Dataframe): A dataframe of an edgelist where, col 0: timestamp, col 1: source, col 2: destination\n isMultiGraph (bool): If False will use DiGraph, otherwise will use MultiGraph\n Returns:\n G (networkx.DiGraph): The graph as built in networkx\n '''\n print('Creating graph...')\n if isMultiGraph:\n G = nx.MultiDiGraph()\n else:\n G = nx.DiGraph()\n for (i, row) in df.iterrows():\n G.add_edge(row[1], row[2], timestamp=row[0])\n print('Done.')\n return G\n\n def createLOTRGraph(self, filePath, from_time=0, to_time=sys.maxsize, source_id=0, target_id=1, timestamp_col=2):\n '''\n Example graph builder in python. Given a csv edgelist this will create a graph using networkx based on the lotr data.\n\n Parameters:\n filePath (str): Location of csv file\n from_time (int): (Optional, default: 0) timestamp to start building graph from\n to_time (int): (Optional, default: sys.maxsize) timestamp to stop building graph\n source_id (int): column for source node\n target_id (int): column for target node\n timestamp_col (int): column for lotr timestamp\n\n Returns:\n G (networkx.DiGraph): The graph as built in networkx\n '''\n G = nx.DiGraph()\n self.first_seen = self.find_dates(pd.read_csv(filePath), node_a_id=source_id, node_b_id=target_id,\n time_col=timestamp_col)\n with open(filePath) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for row in csv_reader:\n edge_timestamp = int(row[timestamp_col])\n if from_time <= edge_timestamp <= to_time:\n node_a_time = datetime.fromtimestamp(int(self.first_seen[row[source_id]]), tz=timezone.utc)\n G.add_node(row[source_id], create_time=int(self.first_seen[row[source_id]]))\n node_b_time = datetime.fromtimestamp(int(self.first_seen[row[target_id]]), tz=timezone.utc)\n G.add_node(row[target_id], create_time=int(self.first_seen[row[target_id]]))\n edge_timestamp = edge_timestamp\n edge_ts = datetime.fromtimestamp(edge_timestamp * 1000, tz=timezone.utc)\n G.add_edge(row[source_id], row[target_id], time=edge_timestamp)\n print(\"Number of nodes \" + str(G.number_of_nodes()))\n print(\"Number of edged \" + str(G.number_of_edges()))\n return G\n" ]
[ [ "pandas.read_csv", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
tapika/OpenNMT-py
[ "b21f8036a10c2839e278b0b4eb297f0d08213437" ]
[ "onmt/utils/statistics.py" ]
[ "\"\"\" Statistics calculation utility \"\"\"\nfrom __future__ import division\nimport time\nimport math\nimport sys\n\nfrom onmt.utils.logging import logger\n\n\nclass Statistics(object):\n \"\"\"\n Accumulator for loss statistics.\n Currently calculates:\n\n * accuracy\n * perplexity\n * elapsed time\n \"\"\"\n\n def __init__(self, loss=0, n_words=0, n_correct=0):\n self.loss = loss\n self.n_words = n_words\n self.n_correct = n_correct\n self.n_src_words = 0\n self.start_time = time.time()\n\n @staticmethod\n def all_gather_stats(stat, max_size=4096):\n \"\"\"\n Gather a `Statistics` object accross multiple process/nodes\n\n Args:\n stat(:obj:Statistics): the statistics object to gather\n accross all processes/nodes\n max_size(int): max buffer size to use\n\n Returns:\n `Statistics`, the update stats object\n \"\"\"\n stats = Statistics.all_gather_stats_list([stat], max_size=max_size)\n return stats[0]\n\n @staticmethod\n def all_gather_stats_list(stat_list, max_size=4096):\n \"\"\"\n Gather a `Statistics` list accross all processes/nodes\n\n Args:\n stat_list(list([`Statistics`])): list of statistics objects to\n gather accross all processes/nodes\n max_size(int): max buffer size to use\n\n Returns:\n our_stats(list([`Statistics`])): list of updated stats\n \"\"\"\n # Get a list of world_size lists with len(stat_list) Statistics objects\n all_stats = all_gather_list(stat_list, max_size=max_size)\n\n from torch.distributed import get_rank\n from onmt.utils.distributed import all_gather_list\n our_rank = get_rank()\n our_stats = all_stats[our_rank]\n for other_rank, stats in enumerate(all_stats):\n if other_rank == our_rank:\n continue\n for i, stat in enumerate(stats):\n our_stats[i].update(stat, update_n_src_words=True)\n return our_stats\n\n def update(self, stat, update_n_src_words=False):\n \"\"\"\n Update statistics by suming values with another `Statistics` object\n\n Args:\n stat: another statistic object\n update_n_src_words(bool): whether to update (sum) `n_src_words`\n or not\n\n \"\"\"\n self.loss += stat.loss\n self.n_words += stat.n_words\n self.n_correct += stat.n_correct\n\n if update_n_src_words:\n self.n_src_words += stat.n_src_words\n\n def accuracy(self):\n \"\"\" compute accuracy \"\"\"\n return 100 * (self.n_correct / self.n_words)\n\n def xent(self):\n \"\"\" compute cross entropy \"\"\"\n return self.loss / self.n_words\n\n def ppl(self):\n \"\"\" compute perplexity \"\"\"\n return math.exp(min(self.loss / self.n_words, 100))\n\n def elapsed_time(self):\n \"\"\" compute elapsed time \"\"\"\n return time.time() - self.start_time\n\n def output(self, step, num_steps, learning_rate, start):\n \"\"\"Write out statistics to stdout.\n\n Args:\n step (int): current step\n n_batch (int): total batches\n start (int): start time of step.\n \"\"\"\n t = self.elapsed_time()\n logger.info(\n (\"Step %2d/%5d; acc: %6.2f; ppl: %5.2f; xent: %4.2f; \" +\n \"lr: %7.5f; %3.0f/%3.0f tok/s; %6.0f sec\")\n % (step, num_steps,\n self.accuracy(),\n self.ppl(),\n self.xent(),\n learning_rate,\n self.n_src_words / (t + 1e-5),\n self.n_words / (t + 1e-5),\n time.time() - start))\n sys.stdout.flush()\n\n def log_tensorboard(self, prefix, writer, learning_rate, step):\n \"\"\" display statistics to tensorboard \"\"\"\n t = self.elapsed_time()\n writer.add_scalar(prefix + \"/xent\", self.xent(), step)\n writer.add_scalar(prefix + \"/ppl\", self.ppl(), step)\n writer.add_scalar(prefix + \"/accuracy\", self.accuracy(), step)\n writer.add_scalar(prefix + \"/tgtper\", self.n_words / t, step)\n writer.add_scalar(prefix + \"/lr\", learning_rate, step)\n" ]
[ [ "torch.distributed.get_rank" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
huyuanfeng2018/flink
[ "b3a9dcbd65719c742fe4907ec17de396b188d378" ]
[ "flink-python/pyflink/table/tests/test_row_based_operation.py" ]
[ "################################################################################\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n################################################################################\nfrom pandas.util.testing import assert_frame_equal\n\nfrom pyflink.common import Row\nfrom pyflink.table import expressions as expr, ListView\nfrom pyflink.table.types import DataTypes\nfrom pyflink.table.udf import udf, udtf, udaf, AggregateFunction, TableAggregateFunction, udtaf\nfrom pyflink.testing import source_sink_utils\nfrom pyflink.testing.test_case_utils import PyFlinkBatchTableTestCase, \\\n PyFlinkStreamTableTestCase\n\n\nclass RowBasedOperationTests(object):\n def test_map(self):\n t = self.t_env.from_elements(\n [(1, 2, 3), (2, 1, 3), (1, 5, 4), (1, 8, 6), (2, 3, 4)],\n DataTypes.ROW(\n [DataTypes.FIELD(\"a\", DataTypes.TINYINT()),\n DataTypes.FIELD(\"b\", DataTypes.SMALLINT()),\n DataTypes.FIELD(\"c\", DataTypes.INT())]))\n\n table_sink = source_sink_utils.TestAppendSink(\n ['a', 'b'],\n [DataTypes.BIGINT(), DataTypes.BIGINT()])\n self.t_env.register_table_sink(\"Results\", table_sink)\n\n func = udf(lambda x: Row(a=x + 1, b=x * x), result_type=DataTypes.ROW(\n [DataTypes.FIELD(\"a\", DataTypes.BIGINT()),\n DataTypes.FIELD(\"b\", DataTypes.BIGINT())]))\n\n func2 = udf(lambda x: Row(x.a + 1, x.b * 2), result_type=DataTypes.ROW(\n [DataTypes.FIELD(\"a\", DataTypes.BIGINT()),\n DataTypes.FIELD(\"b\", DataTypes.BIGINT())]))\n\n t.map(func(t.b)).alias(\"a\", \"b\") \\\n .map(func(t.a)) \\\n .map(func2) \\\n .execute_insert(\"Results\") \\\n .wait()\n actual = source_sink_utils.results()\n self.assert_equals(\n actual, [\"+I[5, 18]\", \"+I[4, 8]\", \"+I[8, 72]\", \"+I[11, 162]\", \"+I[6, 32]\"])\n\n def test_map_with_pandas_udf(self):\n t = self.t_env.from_elements(\n [(1, Row(2, 3)), (2, Row(1, 3)), (1, Row(5, 4)), (1, Row(8, 6)), (2, Row(3, 4))],\n DataTypes.ROW(\n [DataTypes.FIELD(\"a\", DataTypes.TINYINT()),\n DataTypes.FIELD(\"b\",\n DataTypes.ROW([DataTypes.FIELD(\"c\", DataTypes.INT()),\n DataTypes.FIELD(\"d\", DataTypes.INT())]))]))\n\n table_sink = source_sink_utils.TestAppendSink(\n ['a', 'b'],\n [DataTypes.BIGINT(), DataTypes.BIGINT()])\n self.t_env.register_table_sink(\"Results\", table_sink)\n\n def func(x):\n import pandas as pd\n res = pd.concat([x.a, x.c + x.d], axis=1)\n return res\n\n def func2(x):\n return x * 2\n\n def func3(x):\n assert isinstance(x, Row)\n return x\n\n pandas_udf = udf(func,\n result_type=DataTypes.ROW(\n [DataTypes.FIELD(\"c\", DataTypes.BIGINT()),\n DataTypes.FIELD(\"d\", DataTypes.BIGINT())]),\n func_type='pandas')\n\n pandas_udf_2 = udf(func2,\n result_type=DataTypes.ROW(\n [DataTypes.FIELD(\"c\", DataTypes.BIGINT()),\n DataTypes.FIELD(\"d\", DataTypes.BIGINT())]),\n func_type='pandas')\n\n general_udf = udf(func3,\n result_type=DataTypes.ROW(\n [DataTypes.FIELD(\"c\", DataTypes.BIGINT()),\n DataTypes.FIELD(\"d\", DataTypes.BIGINT())]))\n\n t.map(pandas_udf).map(pandas_udf_2).map(general_udf).execute_insert(\"Results\").wait()\n actual = source_sink_utils.results()\n self.assert_equals(\n actual,\n [\"+I[4, 8]\", \"+I[2, 10]\", \"+I[2, 28]\", \"+I[2, 18]\", \"+I[4, 14]\"])\n\n def test_flat_map(self):\n t = self.t_env.from_elements(\n [(1, \"2,3\"), (2, \"1\"), (1, \"5,6,7\")],\n DataTypes.ROW(\n [DataTypes.FIELD(\"a\", DataTypes.TINYINT()),\n DataTypes.FIELD(\"b\", DataTypes.STRING())]))\n\n table_sink = source_sink_utils.TestAppendSink(\n ['a', 'b', 'c', 'd', 'e', 'f'],\n [DataTypes.BIGINT(), DataTypes.STRING(), DataTypes.BIGINT(),\n DataTypes.STRING(), DataTypes.BIGINT(), DataTypes.STRING()])\n self.t_env.register_table_sink(\"Results\", table_sink)\n\n @udtf(result_types=[DataTypes.INT(), DataTypes.STRING()])\n def split(x):\n for s in x.b.split(\",\"):\n yield x.a, s\n\n t.flat_map(split).alias(\"a\", \"b\") \\\n .flat_map(split).alias(\"a\", \"b\") \\\n .join_lateral(split.alias(\"c\", \"d\")) \\\n .left_outer_join_lateral(split.alias(\"e\", \"f\")) \\\n .execute_insert(\"Results\") \\\n .wait()\n actual = source_sink_utils.results()\n self.assert_equals(\n actual,\n [\"+I[1, 2, 1, 2, 1, 2]\", \"+I[1, 3, 1, 3, 1, 3]\", \"+I[2, 1, 2, 1, 2, 1]\",\n \"+I[1, 5, 1, 5, 1, 5]\", \"+I[1, 6, 1, 6, 1, 6]\", \"+I[1, 7, 1, 7, 1, 7]\"])\n\n\nclass BatchRowBasedOperationITTests(RowBasedOperationTests, PyFlinkBatchTableTestCase):\n def test_aggregate_with_pandas_udaf(self):\n t = self.t_env.from_elements(\n [(1, 2, 3), (2, 1, 3), (1, 5, 4), (1, 8, 6), (2, 3, 4)],\n DataTypes.ROW(\n [DataTypes.FIELD(\"a\", DataTypes.TINYINT()),\n DataTypes.FIELD(\"b\", DataTypes.SMALLINT()),\n DataTypes.FIELD(\"c\", DataTypes.INT())]))\n\n table_sink = source_sink_utils.TestAppendSink(\n ['a', 'b', 'c'],\n [DataTypes.TINYINT(), DataTypes.FLOAT(), DataTypes.INT()])\n self.t_env.register_table_sink(\"Results\", table_sink)\n pandas_udaf = udaf(lambda pd: (pd.b.mean(), pd.a.max()),\n result_type=DataTypes.ROW(\n [DataTypes.FIELD(\"a\", DataTypes.FLOAT()),\n DataTypes.FIELD(\"b\", DataTypes.INT())]),\n func_type=\"pandas\")\n t.select(t.a, t.b) \\\n .group_by(t.a) \\\n .aggregate(pandas_udaf) \\\n .select(expr.col(\"*\")) \\\n .execute_insert(\"Results\") \\\n .wait()\n actual = source_sink_utils.results()\n self.assert_equals(actual, [\"+I[1, 5.0, 1]\", \"+I[2, 2.0, 2]\"])\n\n def test_aggregate_with_pandas_udaf_without_keys(self):\n t = self.t_env.from_elements(\n [(1, 2, 3), (2, 1, 3), (1, 5, 4), (1, 8, 6), (2, 3, 4)],\n DataTypes.ROW(\n [DataTypes.FIELD(\"a\", DataTypes.TINYINT()),\n DataTypes.FIELD(\"b\", DataTypes.SMALLINT()),\n DataTypes.FIELD(\"c\", DataTypes.INT())]))\n\n table_sink = source_sink_utils.TestAppendSink(\n ['a', 'b'],\n [DataTypes.FLOAT(), DataTypes.INT()])\n self.t_env.register_table_sink(\"Results\", table_sink)\n pandas_udaf = udaf(lambda pd: Row(pd.b.mean(), pd.b.max()),\n result_type=DataTypes.ROW(\n [DataTypes.FIELD(\"a\", DataTypes.FLOAT()),\n DataTypes.FIELD(\"b\", DataTypes.INT())]),\n func_type=\"pandas\")\n t.select(t.b) \\\n .aggregate(pandas_udaf.alias(\"a\", \"b\")) \\\n .select(t.a, t.b) \\\n .execute_insert(\"Results\") \\\n .wait()\n actual = source_sink_utils.results()\n self.assert_equals(actual, [\"+I[3.8, 8]\"])\n\n def test_window_aggregate_with_pandas_udaf(self):\n import datetime\n from pyflink.table.window import Tumble\n t = self.t_env.from_elements(\n [\n (1, 2, 3, datetime.datetime(2018, 3, 11, 3, 10, 0, 0)),\n (3, 2, 4, datetime.datetime(2018, 3, 11, 3, 10, 0, 0)),\n (2, 1, 2, datetime.datetime(2018, 3, 11, 3, 10, 0, 0)),\n (1, 3, 1, datetime.datetime(2018, 3, 11, 3, 40, 0, 0)),\n (1, 8, 5, datetime.datetime(2018, 3, 11, 4, 20, 0, 0)),\n (2, 3, 6, datetime.datetime(2018, 3, 11, 3, 30, 0, 0))\n ],\n DataTypes.ROW(\n [DataTypes.FIELD(\"a\", DataTypes.TINYINT()),\n DataTypes.FIELD(\"b\", DataTypes.SMALLINT()),\n DataTypes.FIELD(\"c\", DataTypes.INT()),\n DataTypes.FIELD(\"rowtime\", DataTypes.TIMESTAMP(3))]))\n\n table_sink = source_sink_utils.TestAppendSink(\n ['a', 'b', 'c'],\n [\n DataTypes.TIMESTAMP(3),\n DataTypes.FLOAT(),\n DataTypes.INT()\n ])\n self.t_env.register_table_sink(\"Results\", table_sink)\n pandas_udaf = udaf(lambda pd: (pd.b.mean(), pd.b.max()),\n result_type=DataTypes.ROW(\n [DataTypes.FIELD(\"a\", DataTypes.FLOAT()),\n DataTypes.FIELD(\"b\", DataTypes.INT())]),\n func_type=\"pandas\")\n tumble_window = Tumble.over(expr.lit(1).hours) \\\n .on(expr.col(\"rowtime\")) \\\n .alias(\"w\")\n t.select(t.b, t.rowtime) \\\n .window(tumble_window) \\\n .group_by(expr.col(\"w\")) \\\n .aggregate(pandas_udaf.alias(\"d\", \"e\")) \\\n .select(expr.col(\"w\").rowtime, expr.col(\"d\"), expr.col(\"e\")) \\\n .execute_insert(\"Results\") \\\n .wait()\n\n actual = source_sink_utils.results()\n self.assert_equals(actual,\n [\"+I[2018-03-11 03:59:59.999, 2.2, 3]\",\n \"+I[2018-03-11 04:59:59.999, 8.0, 8]\"])\n\n\nclass StreamRowBasedOperationITTests(RowBasedOperationTests, PyFlinkStreamTableTestCase):\n def test_aggregate(self):\n import pandas as pd\n t = self.t_env.from_elements(\n [(1, 2, 3), (2, 1, 3), (1, 5, 4), (1, 8, 6), (2, 3, 4)],\n DataTypes.ROW(\n [DataTypes.FIELD(\"a\", DataTypes.BIGINT()),\n DataTypes.FIELD(\"b\", DataTypes.SMALLINT()),\n DataTypes.FIELD(\"c\", DataTypes.INT())]))\n\n function = CountAndSumAggregateFunction()\n agg = udaf(function,\n result_type=function.get_result_type(),\n accumulator_type=function.get_accumulator_type(),\n name=str(function.__class__.__name__))\n result = t.group_by(t.a) \\\n .aggregate(agg.alias(\"c\", \"d\")) \\\n .select(t.a, t.c, expr.col(\"d\")) \\\n .to_pandas()\n assert_frame_equal(result.sort_values('a').reset_index(drop=True),\n pd.DataFrame([[1, 3, 15], [2, 2, 4]], columns=['a', 'c', 'd']))\n\n def test_flat_aggregate(self):\n import pandas as pd\n mytop = udtaf(Top2())\n t = self.t_env.from_elements([(1, 'Hi', 'Hello'),\n (3, 'Hi', 'hi'),\n (5, 'Hi2', 'hi'),\n (7, 'Hi', 'Hello'),\n (2, 'Hi', 'Hello')], ['a', 'b', 'c'])\n result = t.select(t.a, t.c) \\\n .group_by(t.c) \\\n .flat_aggregate(mytop.alias('a')) \\\n .select(t.a) \\\n .flat_aggregate(mytop.alias(\"b\")) \\\n .select(t.b) \\\n .to_pandas()\n\n assert_frame_equal(result, pd.DataFrame([[7], [5]], columns=['b']))\n\n def test_flat_aggregate_list_view(self):\n import pandas as pd\n my_concat = udtaf(ListViewConcatTableAggregateFunction())\n self.t_env.get_config().set(\n \"python.fn-execution.bundle.size\", \"2\")\n # trigger the cache eviction in a bundle.\n self.t_env.get_config().set(\n \"python.state.cache-size\", \"2\")\n t = self.t_env.from_elements([(1, 'Hi', 'Hello'),\n (3, 'Hi', 'hi'),\n (3, 'Hi2', 'hi'),\n (3, 'Hi', 'hi'),\n (2, 'Hi', 'Hello'),\n (1, 'Hi2', 'Hello'),\n (3, 'Hi3', 'hi'),\n (3, 'Hi2', 'Hello'),\n (3, 'Hi3', 'hi'),\n (2, 'Hi3', 'Hello')], ['a', 'b', 'c'])\n result = t.group_by(t.c) \\\n .flat_aggregate(my_concat(t.b, ',').alias(\"b\")) \\\n .select(t.b, t.c) \\\n .alias(\"a\", \"c\")\n assert_frame_equal(result.to_pandas().sort_values('c').reset_index(drop=True),\n pd.DataFrame([[\"Hi,Hi,Hi2,Hi2,Hi3\", \"Hello\"],\n [\"Hi,Hi,Hi2,Hi2,Hi3\", \"Hello\"],\n [\"Hi,Hi2,Hi,Hi3,Hi3\", \"hi\"],\n [\"Hi,Hi2,Hi,Hi3,Hi3\", \"hi\"]],\n columns=['a', 'c']))\n\n\nclass CountAndSumAggregateFunction(AggregateFunction):\n\n def get_value(self, accumulator):\n from pyflink.common import Row\n return Row(accumulator[0], accumulator[1])\n\n def create_accumulator(self):\n from pyflink.common import Row\n return Row(0, 0)\n\n def accumulate(self, accumulator, row: Row):\n accumulator[0] += 1\n accumulator[1] += row.b\n\n def retract(self, accumulator, row: Row):\n accumulator[0] -= 1\n accumulator[1] -= row.a\n\n def merge(self, accumulator, accumulators):\n for other_acc in accumulators:\n accumulator[0] += other_acc[0]\n accumulator[1] += other_acc[1]\n\n def get_accumulator_type(self):\n return DataTypes.ROW(\n [DataTypes.FIELD(\"a\", DataTypes.BIGINT()),\n DataTypes.FIELD(\"b\", DataTypes.BIGINT())])\n\n def get_result_type(self):\n return DataTypes.ROW(\n [DataTypes.FIELD(\"a\", DataTypes.BIGINT()),\n DataTypes.FIELD(\"b\", DataTypes.BIGINT())])\n\n\nclass Top2(TableAggregateFunction):\n\n def emit_value(self, accumulator):\n accumulator.sort()\n accumulator.reverse()\n size = len(accumulator)\n if size > 1:\n yield accumulator[0]\n if size > 2:\n yield accumulator[1]\n\n def create_accumulator(self):\n return []\n\n def accumulate(self, accumulator, row: Row):\n accumulator.append(row.a)\n\n def retract(self, accumulator, row: Row):\n accumulator.remove(row.a)\n\n def get_accumulator_type(self):\n return DataTypes.ARRAY(DataTypes.BIGINT())\n\n def get_result_type(self):\n return DataTypes.BIGINT()\n\n\nclass ListViewConcatTableAggregateFunction(TableAggregateFunction):\n\n def emit_value(self, accumulator):\n result = accumulator[1].join(accumulator[0])\n yield Row(result)\n yield Row(result)\n\n def create_accumulator(self):\n return Row(ListView(), '')\n\n def accumulate(self, accumulator, *args):\n accumulator[1] = args[1]\n accumulator[0].add(args[0])\n\n def retract(self, accumulator, *args):\n raise NotImplementedError\n\n def get_accumulator_type(self):\n return DataTypes.ROW([\n DataTypes.FIELD(\"f0\", DataTypes.LIST_VIEW(DataTypes.STRING())),\n DataTypes.FIELD(\"f1\", DataTypes.BIGINT())])\n\n def get_result_type(self):\n return DataTypes.ROW([DataTypes.FIELD(\"a\", DataTypes.STRING())])\n\n\nif __name__ == '__main__':\n import unittest\n\n try:\n import xmlrunner\n\n testRunner = xmlrunner.XMLTestRunner(output='target/test-reports')\n except ImportError:\n testRunner = None\n unittest.main(testRunner=testRunner, verbosity=2)\n" ]
[ [ "pandas.concat", "pandas.DataFrame", "pandas.b.max", "pandas.b.mean", "pandas.a.max" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
shyustc/dgl
[ "bdf1bb52e6cb7514e57d648bcba8ed660c11ca9c" ]
[ "python/dgl/backend/mxnet/tensor.py" ]
[ "from __future__ import absolute_import\n\nfrom distutils.version import LooseVersion\n\nimport os\nimport numpy as np\nimport mxnet as mx\nimport mxnet.ndarray as nd\nimport numbers\nimport builtins\nfrom ... import ndarray as dglnd\nfrom ... import kernel as K\nfrom ...function.base import TargetCode \n\nMX_VERSION = LooseVersion(mx.__version__)\nif MX_VERSION.version[0] == 1 and MX_VERSION.version[1] < 5:\n raise Exception(\"DGL has to work with MXNet version >= 1.5\")\n\n# After MXNet 1.5, empty tensors aren't supprted by default.\n# After we turn on the numpy compatible flag, MXNet supports empty NDArray.\nmx.set_np_shape(bool(os.environ.get('DGL_MXNET_SET_NP_SHAPE', True)))\n\ndef data_type_dict():\n return {'float16' : np.float16,\n 'float32' : np.float32,\n 'float64' : np.float64,\n 'uint8' : np.uint8,\n 'int8' : np.int8,\n 'int16' : np.int16,\n 'int32' : np.int32,\n 'int64' : np.int64}\n\ndef cpu():\n return mx.cpu()\n\ndef tensor(data, dtype=None):\n # MXNet always returns a float tensor regardless of type inside data.\n # This is a workaround.\n if dtype is None:\n if isinstance(data[0], numbers.Integral):\n dtype = np.int64\n else:\n dtype = np.float32\n return nd.array(data, dtype=dtype)\n\ndef as_scalar(data):\n return data.asscalar()\n\ndef get_preferred_sparse_format():\n \"\"\"Get the preferred sparse matrix format supported by the backend.\n\n Different backends have their preferred backend. This info is useful when\n constructing a sparse matrix.\n \"\"\"\n return \"csr\"\n\ndef sparse_matrix(data, index, shape, force_format=False):\n fmt = index[0]\n if fmt == 'coo':\n if force_format:\n raise TypeError('MXNet backend only supports CSR format,'\n ' but COO format is forced.')\n coord = index[1]\n # generate convert idx\n # FIXME: cannot use int64\n tmp_data = nd.arange(len(coord[0]), dtype=data.dtype, ctx=coord[0].context)\n tmp_spmat = nd.sparse.csr_matrix((tmp_data, (coord[0], coord[1])),\n tuple(shape), ctx=data.context)\n convert_idx = nd.cast(tmp_spmat.data, dtype='int64')\n # shuffle the data\n data = data[convert_idx]\n spmat = nd.sparse.csr_matrix((data, tmp_spmat.indices, tmp_spmat.indptr),\n tuple(shape), ctx=data.context)\n return spmat, convert_idx\n elif fmt == 'csr':\n indices = index[1]\n indptr = index[2]\n spmat = nd.sparse.csr_matrix((data, indices, indptr),\n tuple(shape), ctx=data.context)\n # No conversion is required.\n return spmat, None\n else:\n raise TypeError('Invalid format: %s.' % fmt)\n\ndef sparse_matrix_indices(spmat):\n return ('csr', spmat.indices, spmat.indptr)\n\ndef is_tensor(obj):\n return isinstance(obj, nd.NDArray)\n\ndef shape(input):\n # NOTE: the input cannot be a symbol\n return input.shape\n\ndef dtype(input):\n # NOTE: the input cannot be a symbol\n return input.dtype\n\ndef ndim(input):\n return input.ndim\n\ndef context(input):\n return input.context\n\ndef device_type(ctx):\n return ctx.device_type\n\ndef device_id(ctx):\n return ctx.device_id\n\ndef astype(input, ty):\n return nd.cast(input, ty)\n\ndef asnumpy(input):\n return input.asnumpy()\n\ndef copy_to(input, ctx):\n return input.as_in_context(ctx)\n\ndef sum(input, dim, keepdims=False):\n return nd.sum(input, axis=dim, keepdims=keepdims)\n\ndef reduce_sum(input):\n return input.sum()\n\ndef mean(input, dim):\n return nd.mean(input, axis=dim)\n\ndef reduce_mean(input):\n return input.mean()\n\ndef max(input, dim):\n return nd.max(input, axis=dim)\n\ndef reduce_max(input):\n return input.max()\n\ndef min(input, dim):\n return nd.min(input, axis=dim)\n\ndef reduce_min(input):\n return input.min()\n\ndef topk(input, k, dim, descending=True):\n return nd.topk(input, axis=dim, k=k, ret_typ='value', is_ascend=not descending)\n\ndef argtopk(input, k, dim, descending=True):\n idx = nd.argsort(input, dim, is_ascend=not descending)\n return nd.slice_axis(input, dim, 0, k)\n\ndef argsort(input, dim, descending):\n idx = nd.argsort(input, dim, is_ascend=not descending)\n idx = nd.cast(idx, dtype='int64')\n return idx\n\ndef exp(input):\n return nd.exp(input)\n\ndef softmax(input, dim=-1):\n return nd.softmax(input, axis=dim)\n\ndef cat(seq, dim):\n return nd.concat(*seq, dim=dim)\n\ndef stack(seq, dim):\n return nd.stack(*seq, axis=dim)\n\ndef split(x, sizes_or_sections, dim):\n if isinstance(sizes_or_sections, list) and len(sizes_or_sections) == 1:\n assert len(x) == sizes_or_sections[0]\n return [x]\n\n if MX_VERSION.version[0] == 1 and MX_VERSION.version[1] >= 5:\n if isinstance(sizes_or_sections, (np.ndarray, list)):\n sizes_or_sections1 = tuple(np.cumsum(sizes_or_sections)[:-1])\n return nd.split_v2(x, sizes_or_sections1, axis=dim)\n\n if isinstance(sizes_or_sections, list) or isinstance(sizes_or_sections, np.ndarray):\n # Old MXNet doesn't support split with different section sizes.\n np_arr = x.asnumpy()\n indices = np.cumsum(sizes_or_sections)[:-1]\n res = np.split(np_arr, indices, axis=dim)\n return [tensor(arr, dtype=x.dtype) for arr in res]\n else:\n return nd.split(x, sizes_or_sections, axis=dim)\n\ndef repeat(input, repeats, dim):\n return nd.repeat(input, repeats, axis=dim)\n\ndef gather_row(data, row_index):\n # MXNet workaround for empty row index\n if len(row_index) == 0:\n if data.shape[0] == 0:\n return data\n else:\n return data[0:0]\n\n if isinstance(row_index, nd.NDArray):\n return nd.take(data, row_index)\n else:\n return data[row_index,]\n\ndef slice_axis(data, axis, begin, end):\n dim = data.shape[axis]\n if begin < 0:\n begin += dim\n if end <= 0:\n end += dim\n return nd.slice_axis(data, axis, begin, end)\n\ndef take(data, indices, dim):\n return nd.take(data, indices, dim)\n\ndef narrow_row(data, start, stop):\n return data[start:stop]\n\ndef scatter_row(data, row_index, value):\n return mx.nd.contrib.index_copy(data, row_index, value)\n\ndef scatter_row_inplace(data, row_index, value):\n data[row_index] = value\n\ndef squeeze(input, dim):\n return nd.squeeze(input, axis=dim)\n\ndef unsqueeze(input, dim):\n return nd.expand_dims(input, axis=dim)\n\ndef reshape(input, shape):\n # NOTE: the input cannot be a symbol\n return nd.reshape(input ,shape)\n\ndef swapaxes(input, axis1, axis2):\n return nd.swapaxes(input, axis1, axis2)\n\ndef zeros(shape, dtype, ctx):\n return nd.zeros(shape, dtype=dtype, ctx=ctx)\n\ndef zeros_like(input):\n return nd.zeros_like(input)\n\ndef ones(shape, dtype, ctx):\n return nd.ones(shape, dtype=dtype, ctx=ctx)\n\ndef uniform(shape, dtype, ctx, low, high):\n return nd.random.uniform(low, high, ctx=ctx, dtype=dtype, shape=shape)\n\ndef pad_packed_tensor(input, lengths, value, l_min=None):\n old_shape = input.shape\n if isinstance(lengths, nd.NDArray):\n max_len = as_scalar(input.max())\n else:\n max_len = builtins.max(lengths)\n\n if l_min is not None:\n max_len = builtins.max(max_len, l_min)\n\n batch_size = len(lengths)\n ctx = input.context\n dtype = input.dtype\n x = nd.full((batch_size * max_len, *old_shape[1:]), value, ctx=ctx, dtype=dtype)\n index = []\n for i, l in enumerate(lengths):\n index.extend(range(i * max_len, i * max_len + l))\n index = nd.array(index, ctx=ctx)\n return scatter_row(x, index, input).reshape(batch_size, max_len, *old_shape[1:])\n\ndef pack_padded_tensor(input, lengths):\n batch_size, max_len = input.shape[:2]\n ctx = input.context\n index = []\n for i, l in enumerate(lengths):\n index.extend(range(i * max_len, i * max_len + l))\n index = nd.array(index, ctx=ctx)\n return gather_row(input.reshape(batch_size * max_len, -1), index)\n\ndef unsorted_1d_segment_sum(input, seg_id, n_segs, dim):\n # TODO: support other dimensions\n assert dim == 0, 'MXNet only supports segment sum on first dimension'\n\n # Use SPMV to simulate segment sum\n ctx = input.context\n n_inputs = input.shape[0]\n input_shape_suffix = input.shape[1:]\n input = input.reshape(n_inputs, -1)\n n_range = nd.arange(n_inputs, dtype='int64').as_in_context(input.context)\n w_nnz = nd.ones(n_inputs).as_in_context(input.context)\n w_nid = nd.stack(seg_id, n_range, axis=0)\n w = nd.sparse.csr_matrix((w_nnz, (seg_id, n_range)), (n_segs, n_inputs))\n w = w.as_in_context(input.context)\n y = nd.dot(w, input)\n y = nd.reshape(y, (n_segs,) + input_shape_suffix)\n return y\n\ndef unsorted_1d_segment_mean(input, seg_id, n_segs, dim):\n # TODO: support other dimensions\n assert dim == 0, 'MXNet only supports segment mean on first dimension'\n\n n_ones = nd.ones_like(seg_id).astype(input.dtype)\n w = unsorted_1d_segment_sum(n_ones, seg_id, n_segs, 0)\n w = nd.clip(w, a_min=1, a_max=np.inf)\n y = unsorted_1d_segment_sum(input, seg_id, n_segs, dim)\n y = y / w.reshape((-1,) + (1,) * (y.ndim - 1))\n return y\n\ndef boolean_mask(input, mask):\n return mx.contrib.nd.boolean_mask(input, mask)\n\ndef equal(x, y):\n return x == y\n\ndef logical_not(input):\n return nd.logical_not(input)\n\ndef unique(input):\n # TODO: fallback to numpy is unfortunate\n tmp = input.asnumpy()\n tmp = np.unique(tmp)\n return nd.array(tmp, ctx=input.context, dtype=input.dtype)\n\ndef full_1d(length, fill_value, dtype, ctx):\n return nd.full((length,), fill_value, dtype=dtype, ctx=ctx)\n\ndef nonzero_1d(input):\n # TODO: fallback to numpy is unfortunate\n tmp = input.asnumpy()\n tmp = np.nonzero(tmp)[0]\n return nd.array(tmp, ctx=input.context, dtype=input.dtype)\n\ndef sort_1d(input):\n # TODO: this isn't an ideal implementation.\n val = nd.sort(input, axis=None, is_ascend=True)\n idx = nd.argsort(input, is_ascend=True)\n idx = nd.cast(idx, dtype='int64')\n return val, idx\n\ndef arange(start, stop):\n if start >= stop:\n return nd.array([], dtype=np.int64)\n else:\n return nd.arange(start, stop, dtype=np.int64)\n\ndef rand_shuffle(arr):\n return mx.nd.random.shuffle(arr)\n\ndef zerocopy_to_dlpack(arr):\n return arr.to_dlpack_for_read()\n\ndef zerocopy_from_dlpack(dlpack_arr):\n return nd.from_dlpack(dlpack_arr)\n\ndef zerocopy_to_numpy(arr):\n # NOTE: not zerocopy\n return arr.asnumpy()\n\ndef zerocopy_from_numpy(np_data):\n return mx.nd.from_numpy(np_data, zero_copy=True)\n\ndef zerocopy_to_dgl_ndarray(arr):\n return dglnd.from_dlpack(arr.to_dlpack_for_read())\n\ndef zerocopy_to_dgl_ndarray_for_write(arr):\n return dglnd.from_dlpack(arr.to_dlpack_for_write())\n\ndef zerocopy_from_dgl_ndarray(arr):\n return nd.from_dlpack(arr.to_dlpack())\n\n\nclass BinaryReduce(mx.autograd.Function):\n def __init__(self, reducer, binary_op, graph, lhs, rhs, out_size, lhs_map,\n rhs_map, out_map):\n super(BinaryReduce, self).__init__()\n self.reducer = reducer\n self.binary_op = binary_op\n self.graph = graph\n self.lhs = lhs\n self.rhs = rhs\n self.out_size = out_size\n self.lhs_map = lhs_map\n self.rhs_map = rhs_map\n self.out_map = out_map\n\n def forward(self, lhs_data, rhs_data):\n lhs_data_nd = zerocopy_to_dgl_ndarray(lhs_data)\n rhs_data_nd = zerocopy_to_dgl_ndarray(rhs_data)\n feat_shape = K.infer_binary_feature_shape(self.binary_op, lhs_data_nd, rhs_data_nd)\n out_shape = feat_shape\n if self.binary_op == 'dot':\n out_shape = feat_shape[:-1]\n out_data = nd.empty((self.out_size,) + out_shape,\n ctx=lhs_data.context, dtype=lhs_data.dtype)\n out_data_nd = zerocopy_to_dgl_ndarray_for_write(out_data)\n K.binary_op_reduce(\n self.reducer if self.reducer != 'mean' else 'sum',\n self.binary_op, self.graph, self.lhs, self.rhs,\n lhs_data_nd, rhs_data_nd, out_data_nd, self.lhs_map[0],\n self.rhs_map[0], self.out_map[0])\n # normalize if mean reducer\n # NOTE(zihao): this is a temporary hack and we should have better solution in the future.\n if self.reducer == 'mean':\n degs = nd.empty((out_data.shape[0],),\n ctx=out_data.context, dtype=out_data.dtype)\n degs_nd = zerocopy_to_dgl_ndarray(degs)\n if self.lhs != TargetCode.DST:\n target = self.lhs\n n = lhs_data.shape[0]\n in_map = self.lhs_map[0]\n else:\n target = self.rhs\n n = rhs_data.shape[0]\n in_map = self.rhs_map[0]\n in_ones = nd.ones((n,), ctx=lhs_data.context, dtype=lhs_data.dtype)\n in_ones_nd = zerocopy_to_dgl_ndarray(in_ones)\n K.copy_reduce(\n 'sum', self.graph, target, in_ones_nd, degs_nd,\n in_map, self.out_map[0])\n # reshape\n degs = degs.reshape((out_data.shape[0],) + (1,) * (out_data.ndim - 1)).clip(1, float('inf'))\n out_data = out_data / degs\n else:\n degs = None\n self.save_for_backward(lhs_data_nd, rhs_data_nd, out_data_nd,\n feat_shape, degs)\n return out_data\n\n def backward(self, grad_out):\n lhs_data_nd, rhs_data_nd, out_data_nd, feat_shape, degs = self.saved_tensors\n if self.reducer == 'mean':\n grad_out = grad_out / degs\n grad_out_nd = zerocopy_to_dgl_ndarray(grad_out)\n grad_lhs = nd.empty((lhs_data_nd.shape[0],) + feat_shape,\n ctx=grad_out.context, dtype=grad_out.dtype)\n K.backward_lhs_binary_op_reduce(\n self.reducer if self.reducer != 'mean' else 'sum',\n self.binary_op, self.graph, self.lhs, self.rhs,\n lhs_data_nd, rhs_data_nd, out_data_nd, grad_out_nd,\n zerocopy_to_dgl_ndarray_for_write(grad_lhs), self.lhs_map[1],\n self.rhs_map[1], self.out_map[1])\n grad_lhs = _reduce_grad(grad_lhs, lhs_data_nd.shape)\n grad_rhs = nd.empty((rhs_data_nd.shape[0],) + feat_shape,\n ctx=grad_out.context, dtype=grad_out.dtype)\n K.backward_rhs_binary_op_reduce(\n self.reducer if self.reducer != 'mean' else 'sum',\n self.binary_op, self.graph, self.lhs, self.rhs,\n lhs_data_nd, rhs_data_nd, out_data_nd, grad_out_nd,\n zerocopy_to_dgl_ndarray_for_write(grad_rhs), self.lhs_map[1],\n self.rhs_map[1], self.out_map[1])\n grad_rhs = _reduce_grad(grad_rhs, rhs_data_nd.shape)\n # clear saved tensors explicitly\n self.saved_tensors = None\n return grad_lhs, grad_rhs\n\n\ndef binary_reduce(reducer, binary_op, graph, lhs, rhs, lhs_data, rhs_data,\n out_size, lhs_map=(None, None), rhs_map=(None, None), out_map=(None, None)):\n func = BinaryReduce(reducer, binary_op, graph, lhs, rhs, out_size, lhs_map,\n rhs_map, out_map)\n return func(lhs_data, rhs_data)\n\n\nclass CopyReduce(mx.autograd.Function):\n def __init__(self, reducer, graph, target, out_size, in_map, out_map):\n super(CopyReduce, self).__init__()\n self.reducer = reducer\n self.graph = graph\n self.target = target\n self.out_size = out_size\n self.in_map = in_map\n self.out_map = out_map\n\n def forward(self, in_data):\n feat_shape = in_data.shape[1:]\n out_data = nd.empty((self.out_size,) + feat_shape,\n ctx=in_data.context, dtype=in_data.dtype)\n in_data_nd = zerocopy_to_dgl_ndarray(in_data)\n out_data_nd = zerocopy_to_dgl_ndarray_for_write(out_data)\n K.copy_reduce(\n self.reducer if self.reducer != 'mean' else 'sum',\n self.graph, self.target, in_data_nd, out_data_nd,\n self.in_map[0], self.out_map[0])\n # normalize if mean reducer\n # NOTE(zihao): this is a temporary hack and we should have better solution in the future.\n if self.reducer == 'mean':\n in_ones = nd.ones((in_data.shape[0],),\n ctx=in_data.context, dtype=in_data.dtype)\n degs = nd.empty((out_data.shape[0],),\n ctx=out_data.context, dtype=out_data.dtype)\n in_ones_nd = zerocopy_to_dgl_ndarray(in_ones)\n degs_nd = zerocopy_to_dgl_ndarray(degs)\n K.copy_reduce(\n 'sum', self.graph, self.target, in_ones_nd, degs_nd, \n self.in_map[0], self.out_map[0])\n # reshape\n degs = degs.reshape((out_data.shape[0],) + (1,) * (out_data.ndim - 1)).clip(1, float('inf')) \n out_data = out_data / degs\n else:\n degs = None\n self.save_for_backward(in_data_nd, out_data_nd, degs)\n return out_data\n\n def backward(self, grad_out):\n in_data_nd, out_data_nd, degs = self.saved_tensors\n grad_in = nd.empty(in_data_nd.shape, ctx=grad_out.context,\n dtype=grad_out.dtype)\n if self.reducer == 'mean':\n grad_out = grad_out / degs\n grad_out_nd = zerocopy_to_dgl_ndarray(grad_out)\n K.backward_copy_reduce(\n self.reducer if self.reducer != 'mean' else 'sum',\n self.graph, self.target, in_data_nd, out_data_nd,\n grad_out_nd, zerocopy_to_dgl_ndarray_for_write(grad_in),\n self.in_map[1], self.out_map[1])\n # clear saved tensors explicitly\n self.saved_tensors = None\n return grad_in\n\n\ndef copy_reduce(reducer, graph, target, in_data, out_size, in_map=(None, None),\n out_map=(None, None)):\n func = CopyReduce(reducer, graph, target, out_size, in_map, out_map)\n return func(in_data)\n\n\ndef _reduce_grad(grad, shape):\n \"\"\"Reduce gradient on the broadcast dimension\n\n If there is broadcast in forward pass, gradients need to be reduced on\n broadcast dimension. This function checks the input tensor shape and\n gradient shape and perform the reduction.\n\n Parameters\n ----------\n grad: Tensor\n Gradient tensor\n shape: tuple\n Shape of input tensor\n\n Returns\n -------\n Tensor\n \"\"\"\n grad_shape = grad.shape[1:]\n in_shape = shape[1:]\n if in_shape == grad_shape:\n # no need to reduce\n return grad\n num_to_squeeze = len(grad_shape) - len(in_shape)\n # pad in_shape\n in_shape = (1,) * num_to_squeeze + in_shape\n reduce_idx = np.nonzero(np.asarray(grad_shape) - np.asarray(in_shape))[0]\n reduce_idx += 1 # skip batch dim\n grad = grad.sum(axis=tuple(reduce_idx), keepdims=True)\n return grad.reshape(shape)\n\ndef sync():\n \"\"\"Synchronize computation.\n\n In DL frameworks such as MXNet and TensorFlow, the computation in operators\n are done asynchronously. This is to synchronize computation and makes sure\n that all computation is complete after this function call.\n \"\"\"\n mx.nd.waitall()\n" ]
[ [ "numpy.split", "numpy.nonzero", "numpy.unique", "numpy.asarray", "numpy.cumsum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cdfassnacht/cdfutils
[ "511c228787b3394415b9f5e3387e569419badb6f" ]
[ "cdfutils/datafuncs.py" ]
[ "\"\"\"\nA collection of fairly generic code for handling data\n\"\"\"\n\nimport numpy as np\nfrom scipy import interpolate, optimize\nfrom scipy.ndimage import filters\nfrom matplotlib import pyplot as plt\nfrom astropy.table import Table\nfrom astropy.modeling import models, fitting\n\n# ---------------------------------------------------------------------------\n\n\ndef sigclip(indata, nsig=3., mask=None, verbose=False):\n \"\"\"\n Runs a sigma-clipping on the data. The code iterates over\n the following steps until it has converged:\n 1. Compute mean and rms noise in the (clipped) data set\n 2. Reject (clip) data points that are more than nsig * rms from\n the newly computed mean (using the newly computed rms)\n 3. Repeat until no new points are rejected\n Once convergence has been reached, the final clipped mean and clipped\n rms are returned.\n\n Optional inputs:\n nsig - Number of sigma from the mean beyond which points are\n rejected. Default=3.\n mask - If some of the input data are known to be bad, they can\n be flagged before the inputs are computed by including\n a mask. This mask must be set such that True\n indicates good data and False indicates bad data\n verbose - If False (the default) no information is printed\n \"\"\"\n\n \"\"\" Determine what the input data set is \"\"\"\n if mask is not None:\n data = indata[mask]\n else:\n data = indata.copy()\n\n \"\"\" Report the number of valid data points \"\"\"\n size = data[np.isfinite(data)].size\n if verbose:\n print(' sigma_clip: Full size of data = %d' % data.size)\n print(' sigma_clip: Number of finite values = %d' % size)\n\n \"\"\"\n Reject the non-finite data points and compute the initial values\n \"\"\"\n d = data[np.isfinite(data)].flatten()\n mu = d.mean()\n sig = d.std()\n mu0 = d.mean()\n sig0 = d.std()\n if verbose:\n print('')\n print('npix = %11d. mean = %f. sigma = %f' % (size, mu, sig))\n\n \"\"\" Iterate until convergence \"\"\"\n delta = 1\n clipError = False\n while delta:\n size = d.size\n if sig == 0.:\n clipError = True\n break\n d = d[abs(d - mu) < nsig * sig]\n mu = d.mean()\n sig = d.std()\n if verbose:\n print('npix = %11d. mean = %f. sigma = %f' % (size, mu, sig))\n delta = size-d.size\n\n \"\"\" Error handling \"\"\"\n if clipError:\n print('')\n print('ERROR: sigma clipping failed, perhaps with rms=0.')\n print('Setting mu and sig to their original, unclipped, values')\n print('')\n mu = mu0\n sig = sig0\n\n \"\"\" Clean up and return the results and clean up \"\"\"\n del data, d\n return mu, sig\n\n# ===========================================================================\n#\n# Start of DataGen class\n#\n# ===========================================================================\n\n\nclass DataGen(object):\n \"\"\"\n\n The most generic data-handling methods. Right now this is empty since\n the sigclip method, which had been in this class, has been moved out\n to be stand-alone since it was not working well as part of this class.\n\n \"\"\"\n\n # -----------------------------------------------------------------------\n\n def __init__(self, data):\n self.data = np.asarray(data)\n\n # -----------------------------------------------------------------------\n\n# ===========================================================================\n#\n# Start of Data1d class\n#\n# ===========================================================================\n\n\nclass Data1d(Table):\n \"\"\"\n\n Code to perform actions on 1-dimesional data sets such as light curves or\n 1d spectra.\n\n \"\"\"\n\n # -----------------------------------------------------------------------\n\n def __init__(self, x, y, var=None, names=None, debug=False):\n \"\"\"\n\n Reads in the data, which can be expressed as y = y(x).\n\n \"\"\"\n\n \"\"\" Set up the default names \"\"\"\n if names is None:\n if var is None:\n names = ['x', 'y']\n else:\n names = ['x', 'y', 'var']\n if(debug):\n print(names)\n print('Length of x vector: %d' % x.size)\n print('Length of y vector: %d' % y.size)\n\n \"\"\" Link to the inherited class \"\"\"\n if var is None:\n Table.__init__(self, [x, y], names=names)\n else:\n Table.__init__(self, [x, y, var], names=names)\n\n \"\"\" Assign simple names to the columns \"\"\"\n self.x = self[self.colnames[0]]\n self.y = self[self.colnames[1]]\n if var is not None:\n self.var = self[self.colnames[2]]\n else:\n self.var = None\n\n # -----------------------------------------------------------------------\n\n def resamp(self, xout=None, verbose=True):\n \"\"\"\n Resample the data vector (y) onto a new spacing in x.\n There are two possibilities for the output x vector that sets where\n the interpolation happens. They are:\n 1. xout = None [default]\n A linearized set of spacings between the minimum and maximum\n values in the input x vector\n 2. xout is set to an array\n A user-defined x array that has been passed through the xout\n parameter\n \"\"\"\n\n if xout is None:\n x0 = self.x[0]\n x1 = self.x.max()\n xout = np.linspace(x0, x1, self.x.size)\n\n ymod = interpolate.splrep(self.x, self.y)\n yout = interpolate.splev(xout, ymod)\n\n \"\"\" Return the resampled vectors \"\"\"\n if verbose:\n print('resample: replacing input spectrum with resampled'\n ' version')\n print('resample: for now not resampling the variance')\n return xout, yout\n\n # -----------------------------------------------------------------------\n\n def smooth_boxcar(self, filtwidth, verbose=True):\n \"\"\"\n Does a boxcar smooth of the spectrum.\n The default is to do inverse variance weighting, using the variance\n spectrum if it exists.\n The other default is not to write out an output file. This can be\n changed by setting the outfile parameter.\n \"\"\"\n\n \"\"\" Set the weighting \"\"\"\n if self.var is not None:\n if verbose:\n print('Weighting by the inverse variance')\n wht = 1.0 / self.var\n else:\n if verbose:\n print('Uniform weighting')\n wht = 0.0 * self.y + 1.0\n\n \"\"\" Smooth the spectrum and variance spectrum \"\"\"\n yin = wht * self.y\n smowht = filters.uniform_filter(wht, filtwidth)\n ysmooth = filters.uniform_filter(yin, filtwidth)\n ysmooth /= smowht\n if self.var is not None:\n varsmooth = 1.0 / (filtwidth * smowht)\n else:\n varsmooth = None\n\n return ysmooth, varsmooth\n\n # -----------------------------------------------------------------------\n\n def fit_poly(self, fitorder, mod0=None, y0=None, fitrange=None, nsig=3.0,\n doplot=True, markformat='bo', xlabel='x', ylabel='y',\n title=None):\n \"\"\"\n\n This method is essentially just a pair of calls to numpy's polyfit\n and polyval. However, there are a few add-ons, including the clipping\n of outliers (set by nsig), an optional limitation on the x range of\n the data to be fit (set by fitrange), and optional plotting of the\n resulting fit.\n\n \"\"\"\n\n \"\"\" First a sigma clipping to reject clear outliers \"\"\"\n if fitrange is None:\n tmpfitdat = self.y.data.copy()\n else:\n fitmask = np.logical_and(self.x >= fitrange[0],\n self.x < fitrange[1])\n tmpfitdat = self.y.data[fitmask]\n dmu, dsig = sigclip(tmpfitdat, nsig=nsig)\n goodmask = np.absolute(self.y.data - dmu) < nsig * dsig\n badmask = np.absolute(self.y.data - dmu) >= nsig * dsig\n xgood = self.x.data[goodmask]\n dgood = self.y.data[goodmask]\n xbad = self.x.data[badmask]\n dbad = self.y.data[badmask]\n\n \"\"\" Limit the range of fitted points, if requested \"\"\"\n if fitrange is None:\n xpoly = xgood\n dpoly = dgood\n else:\n fitmask = np.logical_and(xgood >= fitrange[0], xgood < fitrange[1])\n xpoly = xgood[fitmask]\n dpoly = dgood[fitmask]\n\n \"\"\" Fit a polynomial to the trace \"\"\"\n if fitorder > -1:\n dpoly = np.polyfit(xpoly, dpoly, fitorder)\n elif y0 is not None:\n dpoly = np.array([y0, ])\n else:\n dpoly = None\n\n \"\"\"\n Calculate the fitted function\n \"\"\"\n fitx = np.arange(self.x.size)\n if dpoly is not None:\n fity = np.polyval(dpoly, fitx)\n else:\n fity is None\n\n \"\"\" Plot the results \"\"\"\n ymin = dmu - 4.5*dsig\n ymax = dmu + 4.5*dsig\n if doplot and fity is not None:\n plt.plot(self.x, self.y.data, markformat)\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.title(title)\n\n \"\"\"\n Show an input constant value (e.g., the mean y value)\n This input value, if it is passed to the method, would have been\n generated before calling the function\n \"\"\"\n if y0 is not None:\n plt.axhline(y0, color='k', linestyle='--')\n\n \"\"\" Mark the bad points that were not included in the fit \"\"\"\n plt.plot(xbad, dbad, \"rx\", markersize=10, markeredgewidth=2)\n\n \"\"\" Show the fitted function \"\"\"\n plt.plot(fitx, fity, \"r\")\n\n \"\"\"\n Show the range of points included in the fit, if fitrange was set\n \"\"\"\n if fitrange is not None:\n plt.axvline(fitrange[0], color='k', linestyle=':')\n plt.axvline(fitrange[1], color='k', linestyle=':')\n xtmp = 0.5 * (fitrange[1] + fitrange[0])\n xerr = xtmp - fitrange[0]\n ytmp = fity.min() - 0.2 * fity.min()\n plt.errorbar(xtmp, ytmp, xerr=xerr, ecolor=\"g\", capsize=10)\n plt.xlim(0, self.x.max())\n plt.ylim(ymin, ymax)\n\n \"\"\"\n Return the parameters produced by the fit and the fitted function\n \"\"\"\n print(dpoly)\n return dpoly, fity\n\n # -----------------------------------------------------------------------\n\n def fit_mod(self, mod0, usevar=False, fitrange=None, verbose=True):\n \"\"\"\n\n Fits a pre-defined model (given by mod0) to the data. The model\n must have been set by some other method before calling this function.\n\n Required inputs:\n mod0 - The input model, in the form of an astropy.modeling object\n\n Optional inputs:\n usevar - Use the variance array to define the uncertainties to be\n used in the fitting. If set to False (the default) then\n uniform weighting is used.\n fitrange - x-axis range to use for the fitting. If fitrange is set\n to None (the default), then the entire data set is used\n to constrain the model\n \"\"\"\n\n \"\"\" Summarize the initial guess \"\"\"\n if verbose:\n print('')\n print('Initial model')\n print('-------------')\n print(mod0)\n print('')\n print('-------------------------------------------')\n print('')\n\n \"\"\" \n If variance-weighted fitting is requested, make sure that there\n is a variance vector\n \"\"\"\n if usevar:\n if self.var is None:\n raise KeyError('*** ERROR: fit_mod\\n'\n 'Fitting requested variance weighting but'\n ' no variance array found.')\n else:\n rms0 = np.sqrt(self.var)\n else:\n rms0 = np.ones(self.x.size)\n \n \n \"\"\" Set the range over which to fit the data \"\"\"\n if fitrange is not None:\n mask = (self.x > fitrange[0]) & (self.x < fitrange[1])\n x = self.x[mask]\n y = self.y[mask]\n rms = rms0[mask]\n else:\n x = self.x.copy()\n y = self.y.copy()\n rms = rms0\n\n \"\"\"\n Do the fitting.\n NOTE: The 'weights' for the fitter, if requested, are 1/RMS and NOT\n 1/var because that is what the astropy fitters expect. \n This must be because their figure of merit is set to\n (y_data - y_mod)*weight\n which is later squared somewhere, giving a real figure of merit\n of (y_data - y_mod)**2 / sigma**2 since weight = 1/sigma\n \"\"\"\n fit = fitting.LevMarLSQFitter()\n \n \"\"\" \n look into fitinfo, which has an 'additional info' thing which is\n a dictionary that has as one of its keys param_cov (for covariance)\n NB: this only works (for now) for LevMar\n \"\"\"\n mod = fit(mod0, x, y, weights=1.0/rms)\n\n \"\"\"\n Clean up and return best-fit model\n Also return the 'fitinfo' dictionary. This dictionary contains\n (among other things):\n 'param_cov' - covariance matrix for the parameters\n 'ier' - integer indicating fit quality: 1, 2, 3, 4 are\n successful fits\n \"\"\"\n del rms, x, y\n return mod, fit.fit_info\n\n # -----------------------------------------------------------------------\n\n def fit_gauss(self, bgorder=0, smo=5, gtype='em', usevar=False,\n mod0=None, bounds=None, fitrange=None, verbose=True):\n \"\"\"\n Fits a Gaussian plus a background to the data. The background\n is represented by a polynomial of degree bgorder. The default value,\n bgorder=0, gives a constant background.\n The data are modeled using the astropy modeling package. The \n parameters that are used for the two components are:\n * Background polynomial: c0, c1, ... [up to bgorder]\n * Gaussian: amplitude, mean, stddev\n \"\"\"\n\n \"\"\"\n If there is no input model, then we need to set up a model and\n give it some input guesses\n \"\"\"\n if mod0 is not None:\n m_init = mod0\n \n else:\n \"\"\"\n Do a temporary smoothing of the data to reduce the effect of\n noise on the initial guesses\n \"\"\"\n tmpsmooth, junk = self.smooth_boxcar(smo, verbose=False)\n\n \"\"\"\n The default model for the background is just a constant\n Do a sigma clipping to estimate the base level from the data\n (may or may not get used later)\n \"\"\"\n base, tmp = sigclip(tmpsmooth)\n\n \"\"\" Set up the background polynomial \"\"\"\n p = models.Polynomial1D(degree=bgorder, c0=base)\n\n \"\"\"\n Get the initial guesses for the Gaussian.\n \"\"\"\n if gtype == 'abs':\n amp0 = tmpsmooth.min() - base\n mu0 = self.x[np.argmin(tmpsmooth)]\n else:\n amp0 = tmpsmooth.max() - base\n mu0 = self.x[np.argmax(tmpsmooth)]\n sig0 = 3.5\n\n del tmpsmooth\n\n \"\"\"\n Create the initial-guess model\n NOTE: Should probably add bounds\n \"\"\"\n g = models.Gaussian1D(amplitude=amp0, mean=mu0, stddev=sig0)\n m_init = p + g\n\n mod, fit_info = self.fit_mod(m_init, usevar=usevar, fitrange=fitrange,\n verbose=verbose)\n return mod, fit_info\n\n # -----------------------------------------------------------------------\n\n def _make_gauss(self, p):\n \"\"\"\n\n Creates a model comprised of one or more Gaussian profiles plus a\n (for now) constant background.\n NOTE: the only oddity is that, if there are more than one Gaussian in\n the profile, then the \"mu\" term for the subsequent Gaussians\n (i.e., p[4], p[7], ..) are actually _offsets_ between the mean of the\n subsequent Gaussian and the mean of the first. For example,\n mu_2 = p[0] + p[4]\n\n Inputs:\n p - The parameter values. The length of this vector will be 1+3*n,\n where n>=1, for one constant background parameter (p[0]) plus\n one or more Gaussian parameters, which come in sets of three.\n Thus, p can be decomposed as follows:\n p[0] - background: required\n p[1] - mu_1: required\n p[2] - sigma_1: required\n p[3] - amplitude_1: required\n p[4] - offset between mu_2 and mu_1: optional\n p[5] - sigma_2: optional\n p[6] - amplitude_2: optional\n ... etc. for as many Gaussians are used to construct the\n profile\n \"\"\"\n\n \"\"\" Calculate the number of Gaussians in the model \"\"\"\n ngauss = int((p.size-1)/3)\n if p.size - (ngauss*3+1) != 0:\n print('')\n print('ERROR: Gaussian model contains the incorrect number of'\n 'parameters')\n print('')\n return np.nan\n\n \"\"\" Calculate y_mod using current parameter values \"\"\"\n ymod = np.zeros(self.x.size) + p[0]\n for i in range(ngauss):\n ind = i*3+1\n if i == 0:\n mu = p[ind]\n else:\n mu = p[1] + p[ind]\n\n ymod += p[ind+2] * np.exp(-0.5 * ((self.x - mu)/p[ind+1])**2)\n\n return ymod\n\n # -----------------------------------------------------------------------\n\n def _checkmod_gauss(self, p, p_init, fitind):\n \"\"\"\n\n Compares the data to the model. The model consists of at least one\n gaussian plus a constant background and is created by a call to\n make_gauss.\n Thus the comparison is between ymod(x) and y, where the latter is the\n measured quantity.\n\n NOTE: the only oddity in the model is that, if there are more than\n one Gaussian in the profile, then the \"mu\" term for the subsequent\n Gaussians (i.e., p[4], p[7], ..) are actually _offsets_ between the\n mean of the subsequent Gaussian and the mean of the first. For\n example, mu_2 = p[0] + p[4]\n\n Inputs:\n p - The parameter values. The length of this vector will be 1+3*n,\n where n>=1, for one constant background parameter (p[0]) plus\n one or more Gaussian parameters, which come in sets of three.\n Thus, p can be decomposed as follows:\n p[0] - background: required\n p[1] - mu_1: required\n p[2] - sigma_1: required\n p[3] - amplitude_1: required\n p[4] - offset between mu_2 and mu_1: optional\n p[5] - sigma_2: optional\n p[6] - amplitude_2: optional\n ... etc. for as many Gaussians are used to construct the\n profile\n \"\"\"\n\n \"\"\"\n Create the full list of model parameters by combining the fitted\n parameters and the fixed parameters\n \"\"\"\n pfull = p_init.copy()\n pfull[fitind] = p\n\n \"\"\"\n Compute the difference between model and real values\n \"\"\"\n ymod = self._make_gauss(pfull)\n diff = self.y - ymod\n\n return diff\n\n # -----------------------------------------------------------------------\n\n def fit_gauss_old(self, init=None, fix=None, ngauss=1, verbose=True):\n \"\"\"\n\n Old routine for fitting a gaussian plus background. This approach\n uses the scipy.optimize.leastsq routine rather than the astropy\n modeling routines.\n\n \"\"\"\n\n \"\"\"\n Set up the container for the initial guesses for the parameter values\n \"\"\"\n nparam = 3*ngauss + 1\n p_init = np.zeros(nparam)\n\n \"\"\"\n Put default choices, which may be overridden, into p_init\n \"\"\"\n p_init[0] = np.median(self.y, axis=None)\n for i in range(ngauss):\n \"\"\"\n In this loop the parameters are set as follows:\n p_init[ind] is either mu (if i==0) or an offset from p_init[1]\n p_init[ind+1] is sigma\n p_init[ind+2] is amplitude\n \"\"\"\n ind = 3*i + 1\n if i == 0:\n tmp = self.y.argsort()\n p_init[ind] = 1.0 * tmp[tmp.shape[0]-1]\n else:\n p_init[ind] = 5. * i * (-1.)**(i+1)\n p_init[ind+1] = 3.\n p_init[ind+2] = self.y.max() - p_init[0]\n\n \"\"\"\n Override the default values if init has been set.\n NOTE: the init parameter must be an array (or list) of length nparam\n otherwise the method will quit\n NOTE: A value of -999 in init means keep the default value\n \"\"\"\n if init is not None:\n if len(init) != nparam:\n print('')\n print('ERROR: locate_trace -- init parameter must have'\n 'length %d' % nparam)\n print(' (since ngauss=%d ==> nparam= 3*%d +1)' %\n (ngauss, ngauss))\n print('')\n return np.nan\n for j in range(nparam):\n if init[j] > -998.:\n p_init[j] = init[j]\n\n \"\"\"\n Set up which parameters are fixed based on the fix parameter\n The default value (fix=None) means that all of the parameters are\n varied in the fitting process\n \"\"\"\n fixstr = np.zeros(nparam, dtype='S3')\n if fix is None:\n fixvec = np.zeros(nparam)\n else:\n fixvec = np.atleast_1d(fix)\n if fixvec.size != nparam:\n print('')\n print('ERROR: locate_trace - fix parameter must have length %d'\n % nparam)\n print(' (since ngauss=%d ==> nparam= 3*%d +1)' % \n (ngauss, ngauss))\n print('')\n return np.nan\n fixstr[fixvec == 1] = 'Yes'\n fitmask = fixvec == 0\n fitind = np.arange(nparam)[fitmask]\n\n \"\"\" Fit a Gaussian plus a background to the compressed spectrum \"\"\"\n mf = 100000\n p = p_init[fitmask]\n p_fit, ier = optimize.leastsq(self._checkmod_gauss, p,\n (p_init, fitind),\n maxfev=mf)\n \"\"\"\n Create the full parameter list for the fit by combining the fitted\n parameters and the fixed parameters\n \"\"\"\n p_out = p_init.copy()\n p_out[fitind] = p_fit\n\n \"\"\" Give results \"\"\"\n if(verbose):\n print('')\n print('Profile fit results')\n print('-------------------')\n print(' Held')\n print('Parameter Init Value fixed? Final Value')\n print('-------------- ---------- ------ -----------')\n print('background %9.3f %3s %9.3f'\n % (p_init[0], fixstr[0], p_out[0]))\n for i in range(ngauss):\n ind = 3 * i + 1\n j = i + 1\n if i == 0:\n mustr = 'mu_1'\n else:\n mustr = 'offset_%d' % j\n print('%-9s %9.3f %3s %9.3f'\n % (mustr, p_init[ind], fixstr[ind], p_out[ind]))\n print('sigma_%d %9.3f %3s %9.3f'\n % (j, p_init[ind+1], fixstr[ind+1], p_out[ind+1]))\n print('amp_%d %9.3f %3s %9.3f'\n % (j, p_init[ind+2], fixstr[ind+2], p_out[ind+2]))\n print('')\n\n return p_out\n" ]
[ [ "numpy.polyfit", "numpy.sqrt", "numpy.linspace", "numpy.asarray", "matplotlib.pyplot.plot", "numpy.argmin", "numpy.exp", "numpy.polyval", "numpy.arange", "numpy.atleast_1d", "scipy.optimize.leastsq", "numpy.argmax", "matplotlib.pyplot.errorbar", "numpy.zeros", "scipy.ndimage.filters.uniform_filter", "matplotlib.pyplot.title", "matplotlib.pyplot.ylim", "numpy.median", "scipy.interpolate.splev", "numpy.logical_and", "numpy.array", "matplotlib.pyplot.ylabel", "scipy.interpolate.splrep", "numpy.absolute", "matplotlib.pyplot.axhline", "matplotlib.pyplot.axvline", "numpy.isfinite", "numpy.ones", "matplotlib.pyplot.xlabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "0.15", "1.4", "1.3", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "0.16" ], "tensorflow": [] } ]
Midnighter/pyorganism
[ "9459b51bb6f33c7d3c644cd95a9d72a0862470e6" ]
[ "scripts/construct_trn.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport sys\nimport os\nimport logging\n\nimport numpy\nimport networkx as nx\n\nimport pyorganism\nimport pyorganism.regulation as pyreg\n\n\nLOGGER = logging.getLogger()\nLOGGER.addHandler(logging.StreamHandler())\nLOGGER.setLevel(logging.INFO)\n\n\nclass NodeConverter(object):\n def __init__(self, t_units, default=\"\", **kw_args):\n \"\"\"\n Sets up an instance that makes one attribute of a collection of objects\n searcheable.\n\n These attributes can have any value that is comparable. In none string\n cases, a different default value should be passed.\n \"\"\"\n super(NodeConverter, self).__init__(**kw_args)\n self.t_units = list(t_units)\n self.targets = numpy.array([tu.promoter.unique_id if tu.promoter else default\\\n for tu in self.t_units])\n self.indeces = numpy.arange(len(self.targets), dtype=int)\n\n def __call__(self, value):\n return (gene for i in self.indeces[self.targets == value] for gene in self.t_units[i].genes)\n\n\ndef construct_trn(path):\n LOGGER.info(\"{0:*^78s}\".format(\"Construct TRN\"))\n version = os.path.basename(path)\n if not version:\n version = os.path.basename(os.path.dirname(path))\n LOGGER.info(\"{0:*^78s}\".format(version))\n # load objects so that they are in memory\n pyorganism.read_pickle(os.path.join(path, \"conformations.pkl\"))\n t_units = pyorganism.read_pickle(os.path.join(path, \"transcription_units.pkl\"))\n interactions = pyorganism.read_pickle(os.path.join(path, \"interactions.pkl\"))\n assert all(pyreg.Conformation.has_key(triple[0], version) for triple in interactions),\\\n \"unknown conformation in regulatory interactions\"\n assert all(pyreg.Promoter.has_key(triple[1], version) for triple in interactions),\\\n \"unknown promoter in regulatory interactions\"\n # conformation-promoter directed regulatory network\n cpn = nx.MultiDiGraph()\n for (u, v, inter) in interactions:\n first = pyreg.Conformation[u, version]\n second = pyreg.Promoter[v, version]\n cpn.add_edge(first, second, key=inter)\n # TRN from CPN\n trn = pyreg.TRN()\n node_converter = NodeConverter(t_units)\n for (u, v, k, d) in cpn.edges_iter(keys=True, data=True):\n first = u.t_factor\n for nbr in node_converter(v.unique_id):\n trn.add_edge(first, nbr, key=k, **d.copy())\n LOGGER.info(\"%d Nodes\", len(trn))\n LOGGER.info(\"%d Links\", trn.size())\n components = list(nx.connected_components(trn.to_undirected()))\n LOGGER.info(\"%d Components\", len(components))\n LOGGER.info(\"Largest Component: %d\", len(components[0]))\n if len(components) > 1:\n LOGGER.info(\"Second Largest Component: %d\", len(components[1]))\n pyorganism.write_pickle(trn, os.path.join(path, \"trn.pkl\"))\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n LOGGER.critical(\"%s <RegulonDB objects path>\", sys.argv[0])\n sys.exit(2)\n else:\n construct_trn(sys.argv[1])\n\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dangeles/tissue_enrichment_tool_hypergeometric_test
[ "534dc40ff5f31e83845ae96c951cb8469730a5a2" ]
[ "tissue_enrichment_analysis/hypergeometricTests.py" ]
[ "\"\"\"\nA script to implement a hypergeometric test procedure.\n\nAuthor: David Angeles\nDate: May 26, 2015\nRequires Python > 3.5\nNeeds:\nA tissue dictionary\nA control list of gene names\nAn experimental list of gene names\n\"\"\"\n# -*- coding: utf-8 -*-\nimport pandas as pd\nfrom scipy import stats\nimport numpy as np\nimport os\nimport sys\nfrom urllib.request import urlopen\nimport contextlib\n\n\ndef pass_list(user_provided, tissue_dictionary):\n \"\"\"\n A function to check which genes in provided list are in the dictionary.\n \"\"\"\n ind = tissue_dictionary.wbid.isin(user_provided)\n present = tissue_dictionary[ind].wbid\n return present\n\n\ndef hgf(gene_list, tissue_df):\n \"\"\"\n Given a list, returns the p-value for each tissue tested.\n\n Given a list of tissues and a gene-tissue dictionary,\n returns a p-dictionary for the enrichment of every tissue\n (a p-dictionary is a vector of length equal to the number\n of tissues in the tissue_dictionary, sorted by value).\n\n The entries of the p-vector are p-values not corrected\n for multiple hypothesis testing.\n gene_list should be a list or list-like\n tissue_dictionary should be a pandas df\n \"\"\"\n # figure out what genes are in the user provided list\n # wanted = pass_list(gene_list, tissue_df)\n\n # re-index the dictionary s.t. the wbid is the index\n tissue_df = tissue_df.set_index('wbid')\n\n # number of balls per tissue in the dictionary\n sums_of_tissues = tissue_df.sum()\n\n # total labels in the dictionary\n total_balls = tissue_df.sum().sum()\n\n # slice out the rows from tissue_dictionary that came from the list\n wanted_dictionary = tissue_df.reindex(gene_list)\n\n # get the total number of labels from each tissue\n wanted_sum = wanted_dictionary.sum()\n\n # get the total number of balls provided by the user that are in dictionary\n picked = wanted_sum.sum()\n\n # make a hash with the p-values for enrichment of each tissue.\n p_hash = {}\n exp_hash = {}\n for i, name in enumerate(tissue_df.columns.values):\n # if the total number of genes is zero, return p= 1 for all tissues\n if picked == 0:\n p_hash[name] = 1\n continue\n # if a certain tissue has never been called, don't test it\n if wanted_sum[name] == 0:\n p_hash[name] = 1\n continue\n # no. of balls of color name picked\n # total number of balls in urn\n # total number of balls of color name in urn\n # total number of balls picked out\n n_obs = wanted_sum[name]\n s_tissue = sums_of_tissues[name]\n p_hash[name] = stats.hypergeom.sf(n_obs, total_balls, s_tissue,\n picked)\n exp_hash[name] = stats.hypergeom.mean(total_balls, s_tissue,\n picked)\n\n # return the p-values, the genes associated with each tissue and the user\n # provided genes associate with each tissue.\n return p_hash, exp_hash, wanted_dictionary\n\n\ndef benjamini_hochberg_stepup(p_vals):\n \"\"\"\n Given a list of p-values, apply FDR correction and return the q values.\n \"\"\"\n # sort the p_values, but keep the index listed\n index = [i[0] for i in sorted(enumerate(p_vals), key=lambda x:x[1])]\n\n # keep the p_values sorted\n p_vals = sorted(p_vals)\n q_vals = [None]*len(p_vals) # initialize an empty list\n prev_q = 0\n\n # BH Step Up begins here.\n for i, p in enumerate(p_vals):\n q = len(p_vals)/(i+1)*p # calculate the q_value for the current point\n q = min(q, 1) # if q >1, make it == 1\n q = max(q, prev_q) # preserve monotonicity\n q_vals[i] = q # store the q_value\n prev_q = q # update the previous q_value\n\n # prevent the lowest q value from going to zero\n if np.sum(q_vals == 0) > 0:\n # set the min q-value to 10x less than the smallest non-zero value\n q_vals[np.where(q_vals == 0)] = np.min(q_vals[np.where(q_vals != 0)])/10\n\n # return q_vals and the index so we can match up each q-value to its index\n return q_vals, index\n\n\ndef return_enriched_tissues(p_hash, alpha):\n \"\"\"A function index p-values and call the FDR function.\"\"\"\n # initialize a list, a hash and a counter\n p_values = list(p_hash.values())\n keys = list(p_hash.keys())\n\n # FDR\n q_values, index = benjamini_hochberg_stepup(p_values)\n q_hash = {keys[index[pair[0]]]: pair[1] for pair in enumerate(q_values)}\n return q_hash\n\n\ndef enrichment_analysis(gene_list, tissue_df, alpha=0.05, aname='', save=False,\n show=False):\n \"\"\"\n Execute complete enrichment analysis (hypergeometric test, BH correction).\n\n ------\n Params:\n gene_list: a list of non-redundant WBIDs\n tissue_df: as provided by WormBase (use fetch_dictionary)\n alpha: significance threshold, defaults to 0.05\n aname= filename to use to save results\n show= Whether to print results or not.\n\n -------\n output:\n df_final - the final dataframe containing enriched tissues\n \"\"\"\n if show:\n print('Executing script\\n')\n\n # always make iterable\n if type(gene_list) in [str]:\n gene_list = [gene_list]\n\n if len(gene_list) == 0:\n raise ValueError('gene_list is empty!')\n\n # calculate the enrichment\n p_hash, exp_hash, wanted_dic = hgf(gene_list, tissue_df)\n\n # FDR correct\n q_hash = return_enriched_tissues(p_hash, alpha)\n\n # TODO: is there a better way to do this?\n def get_observed(x):\n \"\"\"A function to find the number of observations of a tissue x.\"\"\"\n return wanted_dic[x].sum()\n\n # slight modification\n # make a dataframe, index will be tissues column\n df_final = pd.DataFrame.from_dict(exp_hash, orient='index')\n # make the tissues their own column:\n df_final.reset_index(level=0, inplace=True)\n df_final.columns = ['Term', 'Expected']\n df_final['Observed'] = df_final.Term.apply(get_observed) # v. slow\n df_final['Enrichment Fold Change'] = df_final.Observed/df_final.Expected\n df_final['P value'] = df_final.Term.map(p_hash)\n df_final['Q value'] = df_final.Term.map(q_hash)\n\n df_final.dropna(inplace=True)\n df_final.Observed = df_final.Observed.astype(int)\n\n df_final.sort_values('P value', inplace=True)\n\n df_final = df_final[df_final['Q value'] < alpha]\n\n if show:\n if len(df_final) == 0:\n print('Analysis returned no enriched tissues.')\n else:\n print(df_final) # print statement for raymond\n\n if save:\n df_final.to_csv(aname)\n\n return df_final\n\n\ndef plot_enrichment_results(df, y='logq', title='', analysis='tissue',\n n_bars=15, save=False, **kwargs):\n \"\"\"\n A plot function for TEA.\n\n df: dataframe as output by implement_hypergmt_enrichment_tool\n y: One of 'Fold Change', 'Q value' or a user generated column\n title - Title for the graph, also file name\n analysis - one of `tissue`, `phenotype` or `go`\n n_bars: number of bars to be shown, defaults to 15\n dirGraps: directory to save figures to. if not existent,\n generates a new folder\n\n ------\n output:\n ax - an axis object holding the graph that was generated\n \"\"\"\n import matplotlib.pyplot as plt\n import seaborn as sns\n # sns.choose_colorbrewer_palette('sequential', as_cmap=False)\n if df.empty:\n print('dataframe is empty!')\n return\n\n if analysis.lower() not in ['tissue', 'phenotype', 'go']:\n raise ValueError('analysis variable must be one of' +\n '`tissue`, `phenotype` or `go`')\n\n analysis = analysis.lower()\n\n ax = kwargs.pop('ax', None)\n ftype = kwargs.pop('ftype', 'svg')\n#\n if ax is None:\n fig, ax = plt.subplots(figsize=(14, 8))\n\n # sort by q value change\n df.sort_values(['Q value', 'Enrichment Fold Change'],\n ascending=[True, False], inplace=True)\n\n # make a logq bar:\n logq = -df['Q value'].apply(np.log10)\n\n # added August 26 2016:\n tissue_ID = 11\n pheno_ID = 19\n go_ID = 10\n\n if analysis == 'phenotype':\n yvals = df.Term.str[:-pheno_ID-1]\n elif analysis == 'tissue':\n yvals = df.Term.str[:-tissue_ID-1]\n elif analysis == 'go':\n yvals = df.Term.str[:-go_ID-1]\n\n # plot first n_bars\n with sns.axes_style('whitegrid'):\n ax = sns.barplot(x=logq[:n_bars], y=yvals[:n_bars], ax=ax)\n\n # fix the plot to prettify it\n ax.set_ylabel('Terms', fontsize=15)\n if y.lower() != 'logq':\n ax.set_xlabel(y, fontsize=15)\n else:\n ax.set_xlabel('$-\\log_{10}{q}$', fontsize=15)\n ax.tick_params(axis='x', labelsize=13)\n ax.tick_params(axis='y', labelsize=13)\n ax.set_title(title, fontsize=20)\n plt.tight_layout()\n\n # save\n if save:\n plt.savefig('{0}.{1}'.format(title, ftype), dpi=1200)\n\n return ax\n\n\ndef fetch_dictionary(analysis='tissue'):\n \"\"\"\n Fetch the dictionary we want.\n\n If analysis isn't specified, fetches the tissue dictionary.\n\n Params:\n ------\n analysis - one of `tissue`, `phenotype` or `go`\n\n Output:\n data - a dataframe containing the dictionary of interest\n \"\"\"\n analysis = analysis.lower()\n if analysis not in ['tissue', 'phenotype', 'go']:\n raise ValueError('analysis must be one of `tissue`, `phenotype`' +\n ' or `go`')\n\n url_tissue = 'http://caltech.wormbase.org/TissueEnrichmentAnalysis/'\n\n if analysis == 'tissue':\n url_tissue += 'anatomy_dict.csv'\n elif analysis == 'phenotype':\n url_tissue += 'phenotype_dict.csv'\n elif analysis == 'go':\n url_tissue += 'go_dict.csv'\n\n try:\n with contextlib.closing(urlopen(url_tissue)) as conn:\n data = pd.read_csv(conn)\n return data\n except:\n print('Cannot fetch dictionary. Please check internet connection.')\n\n\n# ==============================================================================\n# ==============================================================================\n# ==============================================================================\n# ==============================================================================\n\nif __name__ == '__main__':\n\n import re\n import argparse\n import matplotlib\n matplotlib.use('Agg')\n import seaborn as sns\n\n sns.set_context('paper')\n sns.set_style('whitegrid')\n\n path = './'\n os.chdir(path)\n\n defQ = 0.1\n\n parser = argparse.ArgumentParser(description='Run EA.')\n parser = argparse.ArgumentParser()\n parser.add_argument(\"gene_list\",\n help='The full path to the gene list (WBIDs) you would\\\n like to analyse in .csv format')\n parser.add_argument('title', help='Title for your analysis (shouldn\\'t\\\n include file extension)',\n type=str)\n parser.add_argument('kind', help='What kind of analysis will be ' +\n 'performed. One of `tissue`, `phenotype` or `go`',\n type=str)\n parser.add_argument(\"-d\", '--dictionary', nargs='?', help='Provide a\\\n dictionary to test. If none given, WormBase URL \\\n will be used to download the corresponding file')\n parser.add_argument(\"-q\", help='Qvalue threshold for significance. \\\n Default is {0} if not provided'.format(defQ),\n type=float)\n parser.add_argument('-p', '--print', help='Indicate whether you would like \\\n to print results', action='store_true')\n parser.add_argument('-s', \"--save\", help='Indicate whether to save your \\\n plot.', action='store_true')\n parser.add_argument('-b', \"--background\", help='Provide a background gene \\\n set as a csv file with a single column without a \\\n column name. Gene names must be in wbid format.',\n type=str)\n parser.add_argument('-m', \"--melted_name\", help='Name for gene_to_terms \\\n file. If none provided, defaults to gene_to_terms.csv',\n type=str)\n args = parser.parse_args()\n\n gl_name = args.gene_list\n title = args.title\n kind = args.kind\n\n # optional args\n # load dictionary:\n if args.dictionary:\n dict_name = args.tissue_dictionary\n dictionary = pd.read_csv(dict_name)\n else:\n dictionary = fetch_dictionary(analysis=args.kind)\n\n # reduce wbids to background set:\n if args.background:\n bg = pd.read_csv(args.background, header=None, names=['wbid'])\n dictionary = dictionary[dictionary.wbid.isin(bg.wbid.values)]\n\n # warn user if the dictionary is empty after subsetting:\n if len(dictionary) == 0:\n raise ValueError('Dictionary is empty after subsetting')\n\n # set threshold\n if args.q:\n q = args.q\n else:\n q = defQ\n\n # print results\n if args.print:\n prnt = True\n else:\n prnt = False\n\n # save results\n if args.save:\n save = True\n\n else:\n save = False\n\n # open gene list:\n gene_list = pd.read_csv(gl_name, header=None, names=['wbid'])\n\n # perform enrichment analysis:\n df_results = enrichment_analysis(gene_list.wbid.unique(), dictionary,\n alpha=q, show=False)\n\n dfname = title + '.tsv'\n df_results.to_csv(dfname, index=False, sep='\\t')\n\n # melt dictionary:\n melted_dict = pd.melt(dictionary, id_vars='wbid', var_name='term',\n value_name='found')\n melted_dict = melted_dict[melted_dict.found == 1]\n\n # keep only terms that were significant:\n melted_dict = melted_dict[melted_dict.term.isin(df_results.Term.values)]\n\n # keep only relevant genes:\n melted_dict = melted_dict[melted_dict.wbid.isin(gene_list.wbid)]\n\n # save to file:\n if args.melted_name:\n melted_dict.to_csv(args.melted_name, index=False)\n else:\n melted_dict.to_csv('gene_to_terms.csv', index=False)\n\n if prnt:\n with open(dfname, 'r') as f:\n printer = f.readlines()\n\n for value in printer:\n value = value.split('\\t')\n for val in value:\n if re.findall(\"\\d+\\.\\d+\", val):\n ind = value.index(val)\n x = float(val)\n value[ind] = '{0:.2g}'.format(x)\n\n value = '\\t'.join(value)\n print(value)\n\n if save:\n plot_enrichment_results(df_results, title=title, save=save,\n analysis=args.kind)\n\n sys.exit()\n" ]
[ [ "matplotlib.pyplot.tight_layout", "pandas.read_csv", "numpy.sum", "matplotlib.use", "matplotlib.pyplot.subplots", "scipy.stats.hypergeom.sf", "scipy.stats.hypergeom.mean", "pandas.DataFrame.from_dict", "numpy.where", "pandas.melt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
KeksimusPrime/SentEval
[ "2d87214e6242ab8fd70ad1158d13adb483dee03a" ]
[ "similarity/gaussian_utils.py" ]
[ "import numpy as np\n\n\ndef fit_covariance(X, reg_cov=1e-10):\n variances = np.var(X, axis=0, ddof=0) + reg_cov\n return variances\n\n\ndef fit_mean(X):\n mean = np.mean(X, axis=0)\n return mean\n\n\ndef get_score(X, mu, var_diag):\n N, D = X.shape\n log_prob = np.sum((X - mu) ** 2 / var_diag)\n log_det = np.sum(np.log(var_diag))\n return -.5 * (log_prob + N * D * np.log(2 * np.pi) + N * log_det)\n\n\ndef aic(X):\n N, D = X.shape\n K = D * 2\n mu = fit_mean(X)\n var_diag = fit_covariance(X)\n return - 2 * get_score(X, mu, var_diag) + 2 * K\n\n\ndef tic(X):\n N, D = X.shape\n mu = fit_mean(X)\n var_diag = fit_covariance(X)\n\n jacob = np.zeros((2 * D,))\n hess = np.zeros((2 * D,))\n\n grad_mu = lambda x: (x - mu) / var_diag\n grad_var = lambda x: .5 * (((x - mu) / var_diag) ** 2 - 1 / var_diag)\n\n # Jacob of mus\n for n in range(N):\n jacob[:D] += grad_mu(X[n]) ** 2\n\n # Jacob of sigmas\n for n in range(N):\n jacob[D:] += grad_var(X[n]) ** 2\n jacob /= N\n\n # Hess of mus\n hess[:D] = - N / var_diag\n\n # Hess of sigmas\n for n in range(N):\n hess[D:] -= (X[n] - mu) ** 2 / var_diag ** 3\n hess[D:] += N / (var_diag ** 2) / 2\n hess /= N\n\n # Fisher is negative of Hessian\n fisher = -hess\n\n penalty = np.sum(jacob / (fisher + 1e-06) )\n\n score = get_score(X, mu, var_diag)\n\n return - 2 * (score - penalty)\n\n\ndef fit_covariance_spherical(X, reg_cov=1e-6):\n variances = np.var(X, axis=0, ddof=0) + reg_cov\n\n spherical = np.mean(variances)\n\n return spherical\n\n\ndef get_score_sphere(X, mu, var_diag):\n N, D = X.shape\n var_diag = (var_diag.mean().repeat(D))\n log_prob = np.sum((X - mu) ** 2 / var_diag)\n log_det = np.sum(np.log(var_diag))\n return -.5 * (log_prob + N * D * np.log(2 * np.pi) + N * log_det)\n\n\ndef get_score_spherical(X, mu, var):\n N, D = X.shape\n log_prob = np.sum((X - mu) ** 2) / var\n log_det = D * np.log(var)\n return -.5 * (log_prob + N * D * np.log(2 * np.pi) + N * log_det)\n\n\ndef aic_spherical(X):\n N, D = X.shape\n K = D + 1\n mu = fit_mean(X)\n var = fit_covariance_spherical(X)\n return - 2 * get_score_spherical(X, mu, var) + 2 * K\n\n\ndef tic_spherical(X):\n N, D = X.shape\n mu = fit_mean(X)\n var = fit_covariance_spherical(X)\n\n jacob = np.zeros((D + 1,))\n hess = np.zeros((D + 1,))\n\n grad_mu = lambda x: (x - mu) / var\n grad_var = lambda x: .5 * np.sum(((x - mu) / var) ** 2 - 1 / var)\n\n # Jacob of mus\n for n in range(N):\n jacob[:D] += grad_mu(X[n]) ** 2\n\n # Jacob of sigmas\n for n in range(N):\n jacob[D] += grad_var(X[n]) ** 2\n jacob /= N\n\n # Hess of mus\n hess[:D] = - N / var\n\n # Hess of sigma\n for n in range(N):\n hess[D] -= np.sum((X[n] - mu) ** 2) / var ** 3\n hess[D] += N / (var ** 2) / 2\n hess /= N\n\n # Fisher is negative of Hessian\n fisher = -hess\n\n penalty = np.sum(jacob / fisher)\n\n score = get_score_spherical(X, mu, var)\n\n return - 2 * (score - penalty)\n\n\ndef get_score_vector(X, mu, var_diag):\n N, D = X.shape\n log_prob = ((X - mu) ** 2 / var_diag).sum(axis=1)\n log_det = np.sum(np.log(var_diag))\n return -.5 * (log_prob + D * np.log(2 * np.pi) + log_det)[:, None]\n" ]
[ [ "numpy.log", "numpy.mean", "numpy.var", "numpy.zeros", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cheesama/nlflow
[ "5c504fc4bfc5aa0ca3892af7b01b2eb46f5edfbb" ]
[ "nlu_flow/response_generation/chitchat_response_generation/torch_transformer_model/inferencer.py" ]
[ "from fastapi import FastAPI\n\nfrom embedding_transformer import EmbeddingTransformer\n\nfrom nlu_flow.preprocessor.text_preprocessor import normalize\nfrom nlu_flow.utils.kor_char_tokenizer import KorCharTokenizer\n\nimport torch\n\napp = FastAPI()\nis_ready = False\n\n# load chitchat_response_model\nmodel = None\n\ntokenizer = KorCharTokenizer()\nmodel = EmbeddingTransformer(\n vocab_size=tokenizer.get_vocab_size(),\n max_seq_len=tokenizer.get_seq_len(),\n pad_token_id=tokenizer.get_pad_token_id(),\n)\nmodel.load_state_dict(torch.load('transformer_chitchat_response_model.modeldict', map_location=lambda storage, loc: storage))\nmodel.eval()\n\nif model is not None:\n is_ready = True\n\nprint ('model load success')\n\n# endpoints\[email protected](\"/\")\nasync def health():\n if is_ready:\n output = {\"code\": 200}\n else:\n output = {\"code\": 500}\n return output\n\n\[email protected](\"/chitchat_response_generator/generate\")\nasync def generate_response(text: str):\n max_len = model.max_seq_len\n tokens = tokenizer.tokenize(text, padding=False)\n origin_token_length = len(tokens)\n\n while True:\n print (f'token: {tokens}')\n pred = model(torch.LongTensor(tokens).unsqueeze(0))\n pred = pred.argmax(2)[0].numpy()\n print (f'pred: {pred}')\n\n if len(tokens) >= tokenizer.max_len:\n break\n\n if pred[-1] == 1: #1 means EOS token\n break\n\n tokens += [pred[-1]]\n\n response = tokenizer.decode(tokens[origin_token_length:])\n\n return {\n \"response\": response,\n \"Generator\": \"transformer_chitchat_response_generator.modeldict\",\n }\n" ]
[ [ "torch.LongTensor", "torch.load" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ASGuard-UCI/DRP-attack
[ "6987183c3de36095c0764a865bcfa1d695b7c46c" ]
[ "car_motion_attack/load_sensor_data.py" ]
[ "import numpy as np\nimport pandas as pd\nimport cv2\nfrom logging import getLogger\nimport pymap3d as pm\n\n\nimport comma2k19.orientation as orient\n\nfrom car_motion_attack.polyfuzz.polyfuzz import VehicleState\nfrom car_motion_attack.utils import ecef2geodetic\nfrom car_motion_attack.polyfuzz.utils.vehicle_control import VehicleControl, VehicleControlDBM\n\nlogger = getLogger(__name__)\n\n\ndef load_transform_matrix(path, start_time):\n # openpilot tools \n from tools.lib.logreader import LogReader\n raw_log = LogReader(path)\n ext_mat = None\n for l in raw_log:\n try:\n if l.which() == 'liveCalibration':\n t = l.logMonoTime * 1e-9\n if ext_mat is None:\n ext_mat = l.liveCalibration.extrinsicMatrix\n\n if t > start_time:\n break\n\n ext_mat = l.liveCalibration.extrinsicMatrix\n except:\n continue\n\n if ext_mat is None:\n raise Exception(f'no transform matrix for time={start_time}')\n\n ext = np.array(ext_mat).reshape((3, 4))\n eon = np.array([[910.0, 0.0, 582.0],\n [0.0, 910.0, 437.0],\n [0.0, 0.0, 1.0]])\n gm = np.array([[0.00000000e+00, 0.00000000e+00, 1.00000000e+00],\n [-1.09890110e-03, 0.00000000e+00, 2.81318681e-01],\n [-1.84808520e-20, 9.00738606e-04, -4.28751576e-02]])\n camera_frame_from_ground = np.dot(eon, ext)[:, [0, 1, 3]]\n\n trns = np.dot(camera_frame_from_ground, gm)\n return trns\n\n\ndef _conv_ecefs2enu(ecefs):\n pos = []\n lat0, lon0, h0 = pm.ecef2geodetic(\n ecefs[0][0], ecefs[0][1], ecefs[0][2], ell=None, deg=True\n )\n for i, ecef in enumerate(ecefs):\n e, n, u = pm.ecef2enu(ecef[0], ecef[1], ecef[2], lat0, lon0, h0)\n pos.append([e, n])\n\n pos = np.array(pos)\n pos -= pos[0]\n\n d = 1\n r = np.sqrt((pos[d] ** 2).sum())\n _cos = pos[d][0] / r\n _sin = -pos[d][1] / r\n\n mat_rotate = np.array([[_cos, -_sin], [_sin, _cos]])\n\n pos = np.dot(pos, mat_rotate.T)\n\n return pos\n\n\ndef load_sensor_data(path, offset=0):\n t = np.load(path + \"global_pose/frame_times\")\n map_vals = {\"t\": t[offset:]}\n\n speed = np.load(path + \"processed_log/CAN/speed/value\")[:, 0]\n t_speed = np.load(path + \"processed_log/CAN/speed/t\")\n all_speed = np.interp(t, t_speed, speed)[offset:]\n\n map_vals.update({\"speed\": all_speed, \"mph\": all_speed * 2.237})\n\n steering_angle = np.load(path + \"processed_log/CAN/steering_angle/value\")\n t_steering_angle = np.load(path + \"processed_log/CAN/steering_angle/t\")\n all_steering_angle = np.interp(t, t_steering_angle, steering_angle)\n\n map_vals.update({\"steering_angle\": all_steering_angle[offset:]})\n\n ecefs = np.load(path + \"global_pose/frame_positions\")[offset:]\n pos = _conv_ecefs2enu(ecefs)\n\n map_vals.update({\"lateral_shift\": pos[:, 1]})\n map_vals.update({\"longitude_shift\": pos[:, 0]})\n\n orientations = np.load(path + \"global_pose/frame_orientations\")\n\n yaw = -orient.ned_euler_from_ecef(ecefs[0], orient.euler_from_quat(orientations))[\n :, 2\n ]\n yaw = yaw[offset:]\n yaw = yaw % (2 * np.pi)\n\n map_vals.update({\"yaw\": yaw - yaw[0]})\n\n df = pd.DataFrame(map_vals)\n df[\"t_diff\"] = df[\"t\"].diff()\n df.loc[0, \"t_diff\"] = 0\n df[\"distance\"] = df[\"t_diff\"] * df[\"speed\"]\n\n return df\n\n\ndef load_sensor_data_bicycle(path):\n t = np.load(path + \"global_pose/frame_times\")\n map_vals = {\"t\": t}\n\n speed = np.load(path + \"processed_log/CAN/speed/value\")[:, 0]\n t_speed = np.load(path + \"processed_log/CAN/speed/t\")\n all_speed = np.interp(t, t_speed, speed)\n\n map_vals.update({\"speed\": all_speed, \"mph\": all_speed * 2.237})\n\n steering_angle = np.load(path + \"processed_log/CAN/steering_angle/value\")\n t_steering_angle = np.load(path + \"processed_log/CAN/steering_angle/t\")\n all_steering_angle = np.interp(t, t_steering_angle, steering_angle)\n\n map_vals.update({\"steering_angle\": all_steering_angle})\n\n df = pd.DataFrame(map_vals)\n df[\"t_diff\"] = df[\"t\"].diff()\n df.loc[0, \"t_diff\"] = 0\n df[\"distance\"] = df[\"t_diff\"] * df[\"speed\"]\n\n vehicle_state = VehicleState()\n list_lateral_shift = [0]\n list_longitude_shift = [0]\n list_yaw = [0]\n for i in range(df.shape[0]): # loop on 20Hz\n # update vehicle state\n v_ego = df.loc[i, \"speed\"]\n\n vehicle_state.update_velocity(v_ego)\n vehicle_state.angle_steers = df.loc[i, \"steering_angle\"]\n\n # update steering angle\n for _ in range(5): # loop on 100Hz\n state = vehicle_state.apply_plan(df.loc[i, \"steering_angle\"])\n list_lateral_shift.append(state.y)\n list_longitude_shift.append(state.x)\n list_yaw.append(state.yaw)\n\n df[\"lateral_shift\"] = list_lateral_shift[:-1]\n df[\"longitude_shift\"] = list_longitude_shift[:-1]\n df[\"yaw\"] = list_yaw[:-1]\n\n return df\n\n\ndef load_sensor_data_bicycleDBM(path):\n t = np.load(path + \"global_pose/frame_times\")\n map_vals = {\"t\": t}\n\n speed = np.load(path + \"processed_log/CAN/speed/value\")[:, 0]\n t_speed = np.load(path + \"processed_log/CAN/speed/t\")\n all_speed = np.interp(t, t_speed, speed)\n\n map_vals.update({\"speed\": all_speed, \"mph\": all_speed * 2.237})\n\n steering_angle = np.load(path + \"processed_log/CAN/steering_angle/value\")\n t_steering_angle = np.load(path + \"processed_log/CAN/steering_angle/t\")\n all_steering_angle = np.interp(t, t_steering_angle, steering_angle)\n\n map_vals.update({\"steering_angle\": all_steering_angle})\n\n df = pd.DataFrame(map_vals)\n df[\"t_diff\"] = df[\"t\"].diff()\n df.loc[0, \"t_diff\"] = 0\n df[\"distance\"] = df[\"t_diff\"] * df[\"speed\"]\n\n vehicle_state = VehicleState(model=VehicleControlDBM)\n list_lateral_shift = [0]\n list_longitude_shift = [0]\n list_yaw = [0]\n for i in range(df.shape[0]): # loop on 20Hz\n # update vehicle state\n v_ego = df.loc[i, \"speed\"]\n\n vehicle_state.update_velocity(v_ego)\n vehicle_state.angle_steers = df.loc[i, \"steering_angle\"]\n\n # update steering angle\n for _ in range(5): # loop on 100Hz\n state = vehicle_state.apply_plan(df.loc[i, \"steering_angle\"])\n list_lateral_shift.append(state.y)\n list_longitude_shift.append(state.x)\n list_yaw.append(state.yaw)\n\n df[\"lateral_shift\"] = list_lateral_shift[:-1]\n df[\"longitude_shift\"] = list_longitude_shift[:-1]\n df[\"yaw\"] = list_yaw[:-1]\n\n return df\n\n\nif __name__ == \"__main__\":\n load_sensor_data(\n \"data/straight_scenarios/b0c9d2329ad1606b|2018-08-03--10-35-16/4/\"\n ).head(10)\n" ]
[ [ "numpy.dot", "pandas.DataFrame", "numpy.interp", "numpy.load", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
KirillErofeev/gudhi-devel
[ "e2c58a7cf912281e1d4befba74b66b43f4923f18" ]
[ "src/python/example/plot_rips_complex.py" ]
[ "#!/usr/bin/env python\n\nimport numpy as np\nimport gudhi\npoints = np.array(gudhi.read_off('../../data/points/Kl.off'))\nrc = gudhi.RipsComplex(points=points, max_edge_length=.2)\nst = rc.create_simplex_tree(max_dimension=2)\n# We are only going to plot the triangles\ntriangles = np.array([s[0] for s in st.get_skeleton(2) if len(s[0])==3])\n\n# First possibility: plotly\nimport plotly.graph_objects as go\nfig = go.Figure(data=[\n go.Mesh3d(\n # Use the first 3 coordinates, but we could as easily pick others\n x=points[:,0],\n y=points[:,1],\n z=points[:,2],\n i = triangles[:,0],\n j = triangles[:,1],\n k = triangles[:,2],\n )\n])\nfig.show()\n\n# Second possibility: matplotlib\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfig = plt.figure()\nax = fig.gca(projection='3d')\nax.plot_trisurf(points[:,0], points[:,1], points[:,2], triangles=triangles)\nplt.show()\n\n# Third possibility: mayavi\n# (this may take a while)\nfrom mayavi import mlab\nmlab.triangular_mesh(points[:,0], points[:,1], points[:,2], triangles);\nmlab.show()\n" ]
[ [ "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
comjoueur/cesi
[ "39058d307473cd112f5b1aafbf56d9a728b601dd" ]
[ "src/skge/actfun.py" ]
[ "import numpy as np\nimport sys\nimport inspect\n\n# NOTE: ALL STATIC CLASSES HERE:\n\nclass ActivationFunction(object):\n\n\t@classmethod\n\tdef key(cls):\n\t\treturn cls.__name__.lower()\n\n# g_given_f -> gradient given function value\n\nclass Linear(ActivationFunction):\n\n\t@staticmethod\n\tdef f(x):\n\t\treturn x\n\n\t@staticmethod\n\tdef g_given_f(fx):\n\t\t#return 1\n\t\treturn np.ones(fx.shape[0])\n\n\t# return np.ones((fx.shape[0], 1))\n\n\nclass Sigmoid(ActivationFunction):\n\n\t@staticmethod\n\tdef f(x):\n\t\treturn 1.0 / (1 + np.exp(-x))\n\n\t@staticmethod\n\tdef g_given_f(fx):\n\t\treturn fx * (1.0 - fx)\n\n\nclass Tanh(ActivationFunction):\n\n\t@staticmethod\n\tdef f(x):\n\t\treturn np.tanh(x)\n\n\t@staticmethod\n\tdef g_given_f(fx):\n\t\treturn 1 - fx ** 2\n\n\nclass ReLU(ActivationFunction):\n\n\t@staticmethod\n\tdef f(x):\n\t\treturn np.maximum(0, x)\n\n\t@staticmethod\n\tdef g_given_f(fx):\n\t\treturn np.int_(fx > 0)\n\n\nclass Softplus(ActivationFunction):\n\n\t@staticmethod\n\tdef f(x):\n\t\treturn np.log(1 + np.exp(x))\n\n\t@staticmethod\n\tdef g(x):\n\t\traise NotImplementedError()\n\n\nafuns = {}\nfor cls in ActivationFunction.__subclasses__():\n\tafuns[cls.key()] = cls" ]
[ [ "numpy.maximum", "numpy.int_", "numpy.ones", "numpy.tanh", "numpy.exp" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
z1021190674/GMAUResNeXt_RS
[ "a8a7444bf30e509cefc01b3be4b0587d367cda2e" ]
[ "model/DANet/danet.py" ]
[ "\"\"\"Dual Attention Network\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom model.DANet.backbone import ResNet50\n\nclass DANet(ResNet50):\n r\"\"\"Pyramid Scene Parsing Network\n\n Parameters\n ----------\n nclass : int\n Number of categories for the training dataset.\n backbone : string\n Pre-trained dilated backbone network type (default:'resnet50'; 'resnet50',\n 'resnet101' or 'resnet152').\n norm_layer : object\n Normalization layer used in backbone network (default: :class:`mxnet.gluon.nn.BatchNorm`;\n for Synchronized Cross-GPU BachNormalization).\n aux : bool\n Auxiliary loss.\n Reference:\n Jun Fu, Jing Liu, Haijie Tian, Yong Li, Yongjun Bao, Zhiwei Fang,and Hanqing Lu.\n \"Dual Attention Network for Scene Segmentation.\" *CVPR*, 2019\n \"\"\"\n\n def __init__(self, nclass, aux=True, **kwargs):\n super(DANet, self).__init__(nclass)\n self.head = _DAHead(2048, nclass, aux, **kwargs)\n self.aux = True\n self.__setattr__('exclusive', ['head'])\n\n def forward(self, x):\n size = x.size()[2:]\n feature_map,_ = self.base_forward(x)\n c3,c4 = feature_map[2],feature_map[3]\n\n outputs = []\n x = self.head(c4)\n x0 = F.interpolate(x[0], size, mode='bilinear', align_corners=True)\n outputs.append(x0)\n\n if self.aux:\n #print('x[1]:{}'.format(x[1].shape))\n x1 = F.interpolate(x[1], size, mode='bilinear', align_corners=True)\n x2 = F.interpolate(x[2], size, mode='bilinear', align_corners=True)\n outputs.append(x1)\n outputs.append(x2)\n return outputs\n\n\nclass _PositionAttentionModule(nn.Module):\n \"\"\" Position attention module\"\"\"\n\n def __init__(self, in_channels, **kwargs):\n super(_PositionAttentionModule, self).__init__()\n self.conv_b = nn.Conv2d(in_channels, in_channels // 8, 1)\n self.conv_c = nn.Conv2d(in_channels, in_channels // 8, 1)\n self.conv_d = nn.Conv2d(in_channels, in_channels, 1)\n self.alpha = nn.Parameter(torch.zeros(1))\n self.softmax = nn.Softmax(dim=-1)\n\n def forward(self, x):\n batch_size, _, height, width = x.size()\n feat_b = self.conv_b(x).view(batch_size, -1, height * width).permute(0, 2, 1)\n feat_c = self.conv_c(x).view(batch_size, -1, height * width)\n attention_s = self.softmax(torch.bmm(feat_b, feat_c))\n feat_d = self.conv_d(x).view(batch_size, -1, height * width)\n feat_e = torch.bmm(feat_d, attention_s.permute(0, 2, 1)).view(batch_size, -1, height, width)\n out = self.alpha * feat_e + x\n\n return out\n\n\nclass _ChannelAttentionModule(nn.Module):\n \"\"\"Channel attention module\"\"\"\n\n def __init__(self, **kwargs):\n super(_ChannelAttentionModule, self).__init__()\n self.beta = nn.Parameter(torch.zeros(1))\n self.softmax = nn.Softmax(dim=-1)\n\n def forward(self, x):\n batch_size, _, height, width = x.size()\n feat_a = x.view(batch_size, -1, height * width)\n feat_a_transpose = x.view(batch_size, -1, height * width).permute(0, 2, 1)\n attention = torch.bmm(feat_a, feat_a_transpose)\n attention_new = torch.max(attention, dim=-1, keepdim=True)[0].expand_as(attention) - attention\n attention = self.softmax(attention_new)\n\n feat_e = torch.bmm(attention, feat_a).view(batch_size, -1, height, width)\n out = self.beta * feat_e + x\n\n return out\n\n\nclass _DAHead(nn.Module):\n def __init__(self, in_channels, nclass, aux=True, norm_layer=nn.BatchNorm2d, norm_kwargs=None, **kwargs):\n super(_DAHead, self).__init__()\n self.aux = aux\n inter_channels = in_channels // 4\n self.conv_p1 = nn.Sequential(\n nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False),\n norm_layer(inter_channels, **({} if norm_kwargs is None else norm_kwargs)),\n nn.ReLU(True)\n )\n self.conv_c1 = nn.Sequential(\n nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False),\n norm_layer(inter_channels, **({} if norm_kwargs is None else norm_kwargs)),\n nn.ReLU(True)\n )\n self.pam = _PositionAttentionModule(inter_channels, **kwargs)\n self.cam = _ChannelAttentionModule(**kwargs)\n self.conv_p2 = nn.Sequential(\n nn.Conv2d(inter_channels, inter_channels, 3, padding=1, bias=False),\n norm_layer(inter_channels, **({} if norm_kwargs is None else norm_kwargs)),\n nn.ReLU(True)\n )\n self.conv_c2 = nn.Sequential(\n nn.Conv2d(inter_channels, inter_channels, 3, padding=1, bias=False),\n norm_layer(inter_channels, **({} if norm_kwargs is None else norm_kwargs)),\n nn.ReLU(True)\n )\n self.out = nn.Sequential(\n nn.Dropout(0.1),\n nn.Conv2d(inter_channels, nclass, 1)\n )\n if aux:\n self.conv_p3 = nn.Sequential(\n nn.Dropout(0.1),\n nn.Conv2d(inter_channels, nclass, 1)\n )\n self.conv_c3 = nn.Sequential(\n nn.Dropout(0.1),\n nn.Conv2d(inter_channels, nclass, 1)\n )\n\n def forward(self, x):\n feat_p = self.conv_p1(x)\n feat_p = self.pam(feat_p)\n feat_p = self.conv_p2(feat_p)\n\n feat_c = self.conv_c1(x)\n feat_c = self.cam(feat_c)\n feat_c = self.conv_c2(feat_c)\n\n feat_fusion = feat_p + feat_c\n\n outputs = []\n fusion_out = self.out(feat_fusion)\n outputs.append(fusion_out)\n if self.aux:\n p_out = self.conv_p3(feat_p)\n c_out = self.conv_c3(feat_c)\n outputs.append(p_out)\n outputs.append(c_out)\n\n return tuple(outputs)\n\n\ndef get_danet( backbone='resnet50', pretrained_base=True, **kwargs):\n cityspaces_numclass = 19\n model = DANet(cityspaces_numclass, backbone=backbone, pretrained_base=pretrained_base, **kwargs)\n return model\n\n\nif __name__ == '__main__':\n img = torch.randn(2, 3, 480, 480)\n model = get_danet()\n outputs = model(img)\n #print(outputs)\n" ]
[ [ "torch.nn.Softmax", "torch.nn.Dropout", "torch.max", "torch.zeros", "torch.randn", "torch.nn.Conv2d", "torch.bmm", "torch.nn.functional.interpolate", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
AkinoriTanaka-phys/DOT
[ "d06f4346776535562fe3bda8a0950bd6b2cdc040" ]
[ "evaluation.py" ]
[ "import numpy as np\nimport scipy\n\n\nimport chainer\nfrom chainer import cuda\nfrom chainer import datasets\nfrom chainer import serializers\nfrom chainer import Variable\nimport chainer.functions as F\n\nfrom inception_score import Inception\nfrom inception_score import inception_score\n\nimport math\n\nimport cupy as xp\nimport DOT\n\n## modified version of https://github.com/pfnet-research/chainer-gan-lib/blob/master/common/evaluation.py\n# Copyright (c) 2017 pfnet-research\n# Released under the MIT license\n# https://github.com/pfnet-research/chainer-gan-lib/blob/master/LICENSE\n\ndef load_inception_model():\n model = Inception()\n serializers.load_hdf5('metric/inception_score.model', model)\n model.to_gpu()\n return model\n\ndef get_mean_cov(model, ims, batch_size=100):\n n, c, w, h = ims.shape\n n_batches = int(math.ceil(float(n) / float(batch_size)))\n\n xp = model.xp\n ys = xp.empty((n, 2048), dtype=xp.float32)\n\n for i in range(n_batches):\n print('Running batch', i + 1, '/', n_batches, '...')\n batch_start = (i * batch_size)\n batch_end = min((i + 1) * batch_size, n)\n\n ims_batch = ims[batch_start:batch_end]\n ims_batch = xp.asarray(ims_batch) # To GPU if using CuPy\n ims_batch = Variable(ims_batch)\n\n # Resize image to the shape expected by the inception module\n if (w, h) != (299, 299):\n ims_batch = F.resize_images(ims_batch, (299, 299)) # bilinear\n\n # Feed images to the inception module to get the features\n with chainer.using_config('train', False), chainer.using_config('enable_backprop', False):\n y = model(ims_batch, get_feature=True)\n ys[batch_start:batch_end] = y.data\n\n mean = chainer.cuda.to_cpu(xp.mean(ys, axis=0))\n # cov = F.cross_covariance(ys, ys, reduce=\"no\").data.get()\n cov = np.cov(chainer.cuda.to_cpu(ys).T)\n\n return mean, cov\n\ndef FID(m0,c0,m1,c1):\n ret = 0\n ret += np.sum((m0-m1)**2)\n ret += np.trace(c0 + c1 - 2.0*scipy.linalg.sqrtm(np.dot(c0, c1)))\n return np.real(ret)\n\ndef calc_FID(img, model, data='CIFAR'):#, stat_file=\"%s/cifar-10-fid.npz\"%os.path.dirname(__file__)):\n \"\"\"Frechet Inception Distance proposed by https://arxiv.org/abs/1706.08500\"\"\"\n data_m = np.load(\"metric/{}_inception_mean.npy\".format(data))\n data_c = np.load(\"metric/{}_inception_cov.npy\".format(data))\n\n with chainer.using_config('train', False), chainer.using_config('enable_backprop', False):\n mean, cov = get_mean_cov(model, img)\n fid = FID(data_m, data_c, mean, cov)\n return fid\n\ndef calc_inception(gen, data='CIFAR'):\n @chainer.training.make_extension()\n def evaluation(trainer):\n model = load_inception_model()\n\n ims = []\n xp = gen.xp\n\n batchsize = 50\n n_img = 50000\n\n for i in range(0, n_img, batchsize):\n im = DOT.make_image(gen, None, batchsize, N_update=0, ot=False)\n im = np.asarray(np.clip(im * 127.5 + 127.5, 0.0, 255.0), dtype=np.float32)\n if i==0:\n ims = im\n else:\n ims = np.concatenate((ims, im))\n\n #if args.samples > 0:\n # ims = ims[:args.samples]\n\n fid = calc_FID(ims, model, data)\n with chainer.no_backprop_mode(), chainer.using_config('train', False):\n mean, std = inception_score(model, ims)\n\n chainer.reporter.report({\n 'inception_mean': mean,\n 'inception_std': std\n })\n\n chainer.reporter.report({\n 'FID': fid\n })\n\n return evaluation\n\ndef save_models(G, D, net='Resnet', data='CIFAR', mode='SAGAN', objective='NonSaturating'):\n @chainer.training.make_extension()\n def save(trainer):\n G.to_cpu()\n D.to_cpu()\n serializers.save_npz(\"trained_models/{}_G_{}_{}_{}_{}.npz\".format(net, data, mode, objective, trainer.updater.iteration), G)\n serializers.save_npz(\"trained_models/{}_D_{}_{}_{}_{}.npz\".format(net, data, mode, objective, trainer.updater.iteration), D)\n G.to_gpu()\n D.to_gpu()\n return save\n" ]
[ [ "numpy.dot", "numpy.clip", "numpy.concatenate", "numpy.real", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
appleparan/mise.py
[ "a77ea51be37a739928600c66d168d69b78bc0c4b" ]
[ "mise/data.py" ]
[ "import copy\nimport datetime as dt\nimport string\nfrom pathlib import Path\n\nimport bokeh\nimport matplotlib.dates as mdates\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport statsmodels.api as sm\nimport statsmodels.graphics.tsaplots as tpl\nimport statsmodels.tsa.stattools as tsast\nfrom bokeh.io import export_png, export_svgs\nfrom bokeh.models import DatetimeTickFormatter\nfrom bokeh.plotting import figure\nfrom sklearn import preprocessing\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import PowerTransformer, StandardScaler\nfrom torch.utils.data.dataset import Dataset\n\nfrom mise.constants import SEOUL_STATIONS, SEOULTZ\nfrom mise.utils import parse_hkey, parse_wkey, parse_ykey, periodic_mean\n\n\ndef load(datecol, filepath=\"/input/input.csv\"):\n \"\"\"load input file\n\n Args:\n filepath (str, optional):\n file path. Defaults to \"/input/input.csv\".\n\n datecol (list, optional):\n indicate which column has date format. Defaults to [1].\n\n Returns:\n pd.pandas.DataFrame: parsed DataFrame\n \"\"\"\n # date column in raw data : 1\n # date column in imputed data : 0\n df = pd.read_csv(filepath, index_col=[0, 1], parse_dates=datecol)\n\n # prints\n pd.set_option(\"display.max_rows\", 10)\n pd.reset_option(\"display.max_rows\")\n print(df.head(10))\n\n return df\n\n\ndef load_imputed(datecol, filepath=\"/input/input.csv\"):\n \"\"\"load imputed input file\n\n Args:\n filepath (str, optional):\n file path. Defaults to \"/input/input.csv\".\n\n datecol (list, optional):\n indicate which column has date format. Defaults to [1].\n\n Returns:\n pd.pandas.DataFrame: parsed DataFrame\n \"\"\"\n # station code & date\n df = pd.read_csv(filepath, index_col=[0, 1], parse_dates=datecol)\n\n # prints\n pd.set_option(\"display.max_rows\", 10)\n pd.reset_option(\"display.max_rows\")\n\n return df\n\n\ndef load_station(df, code=111123):\n \"\"\"filter dataframe by station code\n\n Args:\n df (pd.DataFrmae): DataFrame to filter\n code (int, optional): station code. Defaults to 111123.\n\n Returns:\n pd.pandas.DataFrame: filtered DataFrame\n \"\"\"\n # return df[df['stationCode'] == code]\n return df.query(f\"stationCode == {code}\")\n\n\nclass BaseDataset(Dataset):\n \"\"\"Base Dataset\"\"\"\n\n def __init__(self, **kwargs):\n # args -- tuple of anonymous arguments\n # kwargs -- dictionary of named arguments\n self.station_name = kwargs.get(\"station_name\", \"종로구\")\n self.target = kwargs.get(\"target\", \"PM10\")\n self.features = kwargs.get(\n \"features\",\n [\n \"SO2\",\n \"CO\",\n \"O3\",\n \"NO2\",\n \"PM10\",\n \"PM25\",\n \"temp\",\n \"wind_dir\",\n \"wind_spd\",\n \"pres\",\n \"humid\",\n \"prep\",\n \"snow\",\n ],\n )\n\n # date when prediction starts,\n # #if I need to predict 2018/1/1 1:00 AM,\n # I need more data with size 'sample_size'\n self.fdate = kwargs.get(\"fdate\", dt.datetime(2009, 1, 1, 1).astimezone(SEOULTZ))\n # date where prediction starts\n self.tdate = kwargs.get(\n \"tdate\", dt.datetime(2017, 12, 31, 23).astimezone(SEOULTZ)\n )\n\n # MLP sample_size\n self.sample_size = kwargs.get(\"sample_size\", 48)\n self.batch_size = kwargs.get(\"batch_size\", 32)\n self.output_size = kwargs.get(\"output_size\", 24)\n self._train_valid_ratio = kwargs.get(\"train_valid_ratio\", 0.8)\n\n # load imputed data from filepath if not provided as dataframe\n # 1. If Jongno ->\n # 1.1 -> Check imputed -> load preimputed data\n # 2. If other station -> load input.csv\n # 2.1 -> Impute and load\n filepath = kwargs.get(\n \"filepath\", Path(\"/input/python/input_seoul_imputed_hourly_pandas.csv\")\n )\n if self.station_name == \"종로구\":\n # TODO : parse re? or whatever make logic\n # for loading precomputed file if jongno,\n # load default file otherwise\n filepath = kwargs.get(\n \"filepath\", Path(\"/input/python/input_jongno_imputed_hourly_pandas.csv\")\n )\n\n raw_df = pd.read_csv(filepath, index_col=[0, 1], parse_dates=[1])\n # filter by station_name\n self._df = raw_df.query(f\"stationCode == {SEOUL_STATIONS[self.station_name]}\")\n self._df.reset_index(level=\"stationCode\", drop=True, inplace=True)\n\n # filter by date range including train date\n # i is a start of output, so prepare sample_size\n self._df = self._df[\n self.fdate - dt.timedelta(hours=self.sample_size) : self.tdate\n ]\n\n self._dates = self._df.index.to_pydatetime()\n self._xs = self._df[self.features]\n self._ys = self._df[[self.target]]\n\n # self._xs must not be available when creating instance so no kwargs for scaler\n self._scaler = preprocessing.StandardScaler().fit(self._xs)\n\n def __getitem__(self, i: int):\n \"\"\"\n get X, Y for given index `di`\n index i actually indicates start of training data\n but logically, this is a start of output\n\n why doing this? because the main focus is not where traininng start, is where output starts.\n\n __len__(df) == fdate - tdate - output_size - sample_size\n actual len(df) == fdate - tdate + sample_size\n\n so df[i]\n -> physically (i:i + sample_size), (i + sample_size:i + sample_size + output_size)\n -> logcially (i - sample_size:i), (i:i + output_size)\n\n Args:\n di(datetime): datetime where output starts\n\n Returns:\n Tensor: transformed input (might be normalized)\n Tensor: output without transform\n \"\"\"\n x = self._xs.iloc[i : i + self.sample_size]\n y = self._ys.iloc[\n (i + self.sample_size) : (i + self.sample_size + self.output_size)\n ]\n\n # return X, Y, Y_dates\n return (\n self._scaler.transform(x).astype(\"float32\"),\n np.squeeze(y).astype(\"float32\"),\n self._dates[\n (i + self.sample_size) : (i + self.sample_size + self.output_size)\n ],\n )\n\n def __len__(self):\n \"\"\"\n hours of train and test dates\n\n __len__(df) == fdate - tdate + output_size\n\n Returns:\n int: total hours\n \"\"\"\n duration = self.tdate - self.fdate - dt.timedelta(hours=(self.output_size) - 2)\n return duration.days * 24 + duration.seconds // 3600\n\n # getter only\n @property\n def xs(self):\n \"\"\"xs getter\n\n Returns:\n pandas.DataFrame: xs\n \"\"\"\n return self._xs\n\n # getter only\n @property\n def ys(self):\n \"\"\"ys getter\n\n Returns:\n pandas.DataFrame: ys\n \"\"\"\n return self._ys\n\n @property\n def scaler(self):\n \"\"\"scaler getter\n\n Returns:\n sklearn.preprocessing.StandardScaler: scaler\n \"\"\"\n return self._scaler\n\n @scaler.setter\n def scaler(self, scaler):\n \"\"\"scaler setter\n\n Args:\n scaler (sklearn.preprocessing.StandardScaler): Z score scaler\n \"\"\"\n self._scaler = scaler.fit(self._xs)\n\n @property\n def df(self):\n \"\"\"df getter\n\n Returns:\n pd.pandas.DataFrame: whole data\n \"\"\"\n return self._df\n\n @df.setter\n def df(self, df):\n \"\"\"df setter\n\n Args:\n df (pd.DataFrame): whole data\n \"\"\"\n self._df = df\n\n @property\n def train_valid_ratio(self):\n \"\"\"train_valid_ratio getter\n\n Returns:\n float: ratio of train/valid set\n \"\"\"\n return self._train_valid_ratio\n\n @train_valid_ratio.setter\n def train_valid_ratio(self, value):\n \"\"\"train_valid_ratio setter\n\n Args:\n value (float): ratio of traini/valid set\n \"\"\"\n self._train_valid_ratio = value\n\n\nclass UnivariateDataset(BaseDataset):\n \"\"\"Serialized Univariate Dataset without Seasonality Decomposition\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.features = [self.target]\n self._xs = self._df[self.features]\n\n def __getitem__(self, i: int):\n \"\"\"\n get X, Y for given index `di`\n\n Args:\n di(datetime): datetime where output starts\n\n Returns:\n Tensor: transformed input (might be normalized)\n Tensor: output without transform\n \"\"\"\n x = self._xs.iloc[i : i + self.sample_size]\n y = self._ys.iloc[\n (i + self.sample_size) : (i + self.sample_size + self.output_size)\n ]\n\n # return X, Y, Y_dates\n return (\n np.squeeze(x.to_numpy()).astype(\"float32\"),\n np.squeeze(y).astype(\"float32\"),\n self._dates[\n (i + self.sample_size) : (i + self.sample_size + self.output_size)\n ],\n )\n\n def to_csv(self, fpath):\n \"\"\"Svae dataset to csv\n\n Args:\n fpath (Path): csv file path\n \"\"\"\n self._df.to_csv(fpath)\n\n\nclass UnivariateMeanSeasonalityDataset(BaseDataset):\n \"\"\"Serialized Univariate Dataset with Seasonaltiy Decomposition\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.features = kwargs.get(\"features\", [self.target])\n self._df_raw = self._df.copy()\n # 2D, in Univariate -> (row x 1)\n self._xs = self._df[self.features]\n self._xs_raw = self._xs.copy()\n self._xs_sea = pd.DataFrame(index=self._xs.index)\n # 1D\n self._ys = self._df[self.target]\n self._ys.name = self.target\n # convert to DataFrame to apply ColumnTransformer easily\n self._ys = self._ys.to_frame()\n self._ys_raw = self._ys.copy()\n self._ys_sea = pd.DataFrame(index=self._ys.index)\n # self._xs must not be available when creating instance so no kwargs for scaler\n\n # mix ColumnTransformer & Pipeline\n # https://scikit-learn.org/stable/auto_examples/compose/plot_column_transformer_mixed_types.html\n numeric_pipeline_X = Pipeline(\n [\n (\n \"seasonalitydecompositor\",\n SeasonalityDecompositor_AWH(smoothing=True, smoothing_frac=0.05),\n ),\n (\n \"standardtransformer\",\n StandardScalerWrapper(scaler=StandardScaler(with_std=False)),\n ),\n ]\n )\n\n numeric_pipeline_Y = Pipeline(\n [\n (\n \"seasonalitydecompositor\",\n SeasonalityDecompositor_AWH(smoothing=True, smoothing_frac=0.05),\n ),\n (\n \"standardtransformer\",\n StandardScalerWrapper(scaler=StandardScaler(with_std=False)),\n ),\n ]\n )\n\n # Univariate -> only tself.\n preprocessor_X = ColumnTransformer(\n transformers=[(\"num_sea\", numeric_pipeline_X, self.features)]\n )\n\n preprocessor_Y = ColumnTransformer(\n transformers=[(\"num\", numeric_pipeline_Y, [self.target])]\n )\n\n # univariate dataset only needs single pipeline\n self._scaler_X = kwargs.get(\"scaler_X\", preprocessor_X)\n self._scaler_Y = kwargs.get(\"scaler_Y\", preprocessor_Y)\n\n def __getitem__(self, i: int):\n \"\"\"\n get X, Y for given index `di`\n\n Args:\n di(datetime): datetime where output starts\n\n Returns:\n Tensor: transformed input (might be normalized)\n Tensor: output without transform\n \"\"\"\n x = self._xs.iloc[i : i + self.sample_size, :]\n y = self._ys.iloc[\n (i + self.sample_size) : (i + self.sample_size + self.output_size), :\n ]\n y_raw = self._ys_raw.iloc[\n (i + self.sample_size) : (i + self.sample_size + self.output_size), :\n ]\n\n return (\n np.squeeze(x.to_numpy()).astype(\"float32\"),\n np.squeeze(y.to_numpy()).astype(\"float32\"),\n np.squeeze(y_raw.to_numpy()).astype(\"float32\"),\n y.index.to_numpy(),\n )\n\n def preprocess(self):\n \"\"\"Compute seasonality and transform by seasonality\"\"\"\n # compute seasonality\n self._scaler_X.fit(self._xs)\n self._scaler_Y.fit(self._ys, y=self._ys)\n\n self.transform()\n\n def transform(self):\n \"\"\"transform xs and ys as a part of preprocess to reduce training time\"\"\"\n self._xs = pd.DataFrame(\n data=self._scaler_X.transform(self._xs),\n index=self._xs.index,\n columns=self._xs.columns,\n )\n self._ys = pd.DataFrame(\n data=self._scaler_Y.transform(self._ys),\n index=self._ys.index,\n columns=self._ys.columns,\n )\n\n def inverse_transform(self, Ys: tuple, dates: tuple):\n \"\"\"inverse_transform accepts DataFrame, but output is always ndarray\n so keep DataFrame structure\n\n Args:\n Ys(tuple): batched ndarray, the shape of each element is (output_size,)\n dates(tuple): batched ndarray, the shape of each element is (output_size,)\n\n Return\n Yhats(tuple): batched ndarray, the shape of each element is (output_size,)\n \"\"\"\n # temporary DataFrame to pass dates\n dfs = list(\n map(\n lambda b: pd.DataFrame(data=b[0], index=b[1], columns=[self.target]),\n zip(Ys, dates),\n )\n )\n\n # execute pipeline's inverse transform\n # transform : (DataFrame) -> SeasonalityDecompositor (needs date) ->\n # StandardScaler -> (ndarray)\n # inverse_transform : (ndarray) -> StandardScaler ->\n # (ndarray) -> (DataFrame) -> SeasonaltyDecompositor -> (ndarray)\n _inv_transYs = tuple(\n map(\n lambda b: np.squeeze(\n self._scaler_Y.named_transformers_[\"num\"].inverse_transform(b)\n ),\n dfs,\n )\n )\n\n # numpy.ndarray\n return _inv_transYs\n # pandas.DataFrame: just alter data by transformed data\n # return tuple(map(lambda b: pd.DataFrame(data=b[0],\n # index=b[1],\n # columns=[self.target]), zip(_inv_transYs, dates)))\n # return _inv_transYs\n\n def plot_seasonality(self, data_dir, png_dir, svg_dir):\n \"\"\"Plot seasonality\n\n Args:\n data_dir (Path): data path\n png_dir (Path): seasonality plot path (png)\n svg_dir (Path): seasonality plot path (svg)\n \"\"\"\n p = self._scaler_X.named_transformers_[\"num\"]\n p[\"seasonalitydecompositor\"].plot(\n self._xs, self.target, self.fdate, self.tdate, data_dir, png_dir, svg_dir\n )\n\n def to_csv(self, fpath):\n \"\"\"Svae dataset to csv\n\n Args:\n fpath (Path): csv file path\n \"\"\"\n self._df.to_csv(fpath)\n\n @property\n def scaler_X(self):\n \"\"\"scaler_X getter\n\n Returns:\n sklearn.preprocessing.StandardScaler: scaler for X\n \"\"\"\n return self._scaler_X\n\n @property\n def scaler_Y(self):\n \"\"\"scaelr_Y getter\n\n Returns:\n sklearn.preprocessing.StandardScaler: scaler for Y\n \"\"\"\n return self._scaler_Y\n\n @property\n def ys(self):\n \"\"\"ys getter\n\n Returns:\n pandas.DataFrame: ys\n \"\"\"\n return self._ys\n\n @property\n def ys_raw(self):\n \"\"\"ys_raw getter\n\n Returns:\n pandas.DataFrame: ys_raw\n \"\"\"\n return self._ys_raw\n\n\nclass UnivariateRNNDataset(BaseDataset):\n \"\"\"Non-Serialized Univariate Dataset without Seasonaltiy Decomposition\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.features = [self.target]\n self._xs = self._df[self.features]\n\n def __getitem__(self, i: int):\n \"\"\"\n get X, Y for given index `di`\n\n Args:\n di(datetime): datetime where output starts\n\n Returns:\n Tensor: transformed input (might be normalized)\n Tensor: output without transform\n \"\"\"\n x = self._xs.iloc[i : i + self.sample_size]\n y0 = self._xs.iloc[i + self.sample_size - 1]\n y = self._ys.iloc[\n (i + self.sample_size) : (i + self.sample_size + self.output_size)\n ]\n\n # return X, Y, Y_dates\n return (\n np.squeeze(x).to_numpy().astype(\"float32\"),\n y0.astype(\"float32\"),\n np.squeeze(y).astype(\"float32\"),\n self._dates[\n (i + self.sample_size) : (i + self.sample_size + self.output_size)\n ],\n )\n\n def to_csv(self, fpath):\n \"\"\"Save dataset to csv\n\n Args:\n fpath (Path): csv file path\n \"\"\"\n self._df.to_csv(fpath)\n\n\nclass UnivariateRNNMeanSeasonalityDataset(BaseDataset):\n \"\"\"Non-Serialized Univariate Dataset with Seasonaltiy Decomposition\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.features = kwargs.get(\"features\", [self.target])\n self._df_raw = self._df.copy()\n # 2D, in Univariate -> (row x 1)\n self._xs = self._df[self.features]\n self._xs_raw = self._xs.copy()\n self._xs_sea = pd.DataFrame(index=self._xs.index)\n # 1D\n self._ys = self._df[self.target]\n self._ys.name = self.target\n self._ys = self._ys.to_frame()\n self._ys_raw = self._ys.copy()\n self._ys_sea = pd.DataFrame(index=self._ys.index)\n\n numeric_pipeline_X = Pipeline(\n [\n (\n \"seasonalitydecompositor\",\n SeasonalityDecompositor_AWH(smoothing=True, smoothing_frac=0.05),\n ),\n (\n \"standardtransformer\",\n StandardScalerWrapper(scaler=StandardScaler(with_std=False)),\n ),\n ]\n )\n\n numeric_pipeline_Y = Pipeline(\n [\n (\n \"seasonalitydecompositor\",\n SeasonalityDecompositor_AWH(smoothing=True, smoothing_frac=0.05),\n ),\n (\n \"standardtransformer\",\n StandardScalerWrapper(scaler=StandardScaler(with_std=False)),\n ),\n ]\n )\n\n preprocessor_X = ColumnTransformer(\n transformers=[(\"num_sea\", numeric_pipeline_X, self.features)]\n )\n preprocessor_Y = ColumnTransformer(\n transformers=[(\"num\", numeric_pipeline_Y, [self.target])]\n )\n\n # univariate dataset only needs single pipeline\n self._scaler_X = kwargs.get(\"scaler_X\", preprocessor_X)\n self._scaler_Y = kwargs.get(\"scaler_Y\", preprocessor_Y)\n\n def __getitem__(self, i: int):\n \"\"\"\n get X, Y for given index `i`\n\n Args:\n i(datetime): datetime where output starts\n\n Returns:\n Tensor: transformed input (might be normalized)\n Tensor: output without transform\n \"\"\"\n x = self._xs.iloc[i : i + self.sample_size]\n y = self._ys.iloc[\n (i + self.sample_size) : (i + self.sample_size + self.output_size)\n ]\n y0 = self._xs.iloc[i + self.sample_size - 1]\n y_raw = self._ys_raw.iloc[\n (i + self.sample_size) : (i + self.sample_size + self.output_size), :\n ]\n\n # return X, Y, Y_dates\n return (\n np.squeeze(x.to_numpy()).astype(\"float32\"),\n np.squeeze(y.to_numpy()).astype(\"float32\"),\n y0.astype(\"float32\"),\n np.squeeze(y_raw.to_numpy()).astype(\"float32\"),\n y.index.to_numpy(),\n )\n\n def preprocess(self):\n \"\"\"Compute seasonality and transform by seasonality\"\"\"\n # compute seasonality\n self._scaler_X.fit(self._xs)\n self._scaler_Y.fit(self._ys)\n\n self.transform()\n\n def transform(self):\n \"\"\"Transform dataset and convert to DataFrame\"\"\"\n self._xs = pd.DataFrame(\n data=self._scaler_X.transform(self._xs),\n index=self._xs.index,\n columns=self._xs.columns,\n )\n self._ys = pd.DataFrame(\n data=self._scaler_Y.transform(self._ys),\n index=self._ys.index,\n columns=self._ys.columns,\n )\n\n def inverse_transform(self, Ys: tuple, dates: tuple):\n \"\"\"transform accepts DataFrame, but output is always ndarray\n so keep DataFrame structure\n\n Args:\n Ys(tuple): batched ndarray, the shape of each element is (output_size,)\n dates(tuple): batched ndarray, the shape of each element is (output_size,)\n\n Return\n Yhats(tuple): batched DataFrames, the shape of each element is (output_size,)\n \"\"\"\n # temporary DataFrame to pass dates\n dfs = list(\n map(\n lambda b: pd.DataFrame(data=b[0], index=b[1], columns=[self.target]),\n zip(Ys, dates),\n )\n )\n\n # execute pipeline's inverse transform\n # transform : (DataFrame) -> SeasonalityDecompositor (needs date) ->\n # StandardScaler -> (ndarray)\n # inverse_transform : (ndarray) -> StandardScaler ->\n # (ndarray) -> (DataFrame) -> SeasonaltyDecompositor -> (ndarray)\n _inv_transYs = tuple(\n map(\n lambda b: np.squeeze(\n self._scaler_Y.named_transformers_[\"num\"].inverse_transform(b)\n ),\n dfs,\n )\n )\n\n return _inv_transYs\n\n def plot_seasonality(self, data_dir, png_dir, svg_dir):\n \"\"\"Plot seasonality\n\n Args:\n data_dir (Path): data path\n png_dir (Path): seasonality plot path (png)\n svg_dir (Path): seasonality plot path (svg)\n \"\"\"\n p = self._scaler_Y.named_transformers_[\"num\"]\n p[\"seasonalitydecompositor\"].plot(\n self._xs_raw,\n self.target,\n self.fdate,\n self.tdate,\n data_dir,\n png_dir,\n svg_dir,\n )\n\n def to_csv(self, fpath):\n \"\"\"Save dataset to csv\n\n Args:\n fpath (Path): csv file path\n \"\"\"\n self._df.to_csv(fpath)\n\n @property\n def scaler_X(self):\n \"\"\"scaler_X getter\n\n Returns:\n sklearn.preprocessing.StandardScaler: scaler for X\n \"\"\"\n return self._scaler_X\n\n @property\n def scaler_Y(self):\n \"\"\"scaelr_Y getter\n\n Returns:\n sklearn.preprocessing.StandardScaler: scaler for Y\n \"\"\"\n return self._scaler_Y\n\n @property\n def ys(self):\n \"\"\"ys getter\n\n Returns:\n pandas.DataFrame: ys\n \"\"\"\n return self._ys\n\n @property\n def ys_raw(self):\n \"\"\"ys_raw getter\n\n Returns:\n pandas.DataFrame: ys_raw\n \"\"\"\n return self._ys_raw\n\n @property\n def xs(self):\n \"\"\"xs getter\n\n Returns:\n pandas.DataFrame: xs\n \"\"\"\n return self._xs\n\n @property\n def xs_raw(self):\n \"\"\"xs_raw getter\n\n Returns:\n pandas.DataFrame: xs_raw\n \"\"\"\n return self._xs_raw\n\n\nclass MultivariateDataset(BaseDataset):\n \"\"\"Serialized Multivariate Dataset without Seasonality Decomposition\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # 1-step transformer\n # 1. StandardScalerWrapper\n self.features_1 = kwargs.get(\n \"features_1\", [\"temp\", \"u\", \"v\", \"pres\", \"humid\", \"prep\", \"snow\"]\n )\n # 2-step transformer\n # 1. SeasonalityDecompositor\n # 2. StandardScalerWrapper\n self.features_2 = kwargs.get(\n \"features_2\", [\"SO2\", \"CO\", \"O3\", \"NO2\", \"PM10\", \"PM25\"]\n )\n\n self._df_raw = self._df.copy()\n # 2D, in Univariate -> (row x 1)\n self._xs = self._df[self.features]\n self._xs_raw = self._xs.copy()\n\n # 1D\n self._ys = self._df[self.target]\n self._ys.name = self.target\n # convert to DataFrame to apply ColumnTransformer easily\n self._ys = self._ys.to_frame()\n self._ys_raw = self._ys.copy()\n\n # mix ColumnTransformer & Pipeline\n # https://scikit-learn.org/stable/auto_examples/compose/plot_column_transformer_mixed_types.html\n # pipeline for regression data\n\n numeric_pipeline_X_1 = Pipeline(\n [\n (\n \"standardscalerwrapper\",\n StandardScalerWrapper(scaler=StandardScaler(with_std=False)),\n )\n ]\n )\n\n numeric_pipeline_X_2 = Pipeline(\n [\n (\n \"standardscalerwrapper\",\n StandardScalerWrapper(scaler=StandardScaler(with_std=False)),\n )\n ]\n )\n\n numeric_pipeline_Y = Pipeline(\n [\n (\n \"standardscalerwrapper\",\n StandardScalerWrapper(scaler=StandardScaler(with_std=False)),\n )\n ]\n )\n\n # Univariate -> only pipeline needed\n # Multivariate -> Need ColumnTransformer\n preprocessor_X = ColumnTransformer(\n transformers=[\n (\"num_2\", numeric_pipeline_X_2, self.features_2),\n (\"num_1\", numeric_pipeline_X_1, self.features_1),\n ]\n )\n\n preprocessor_Y = ColumnTransformer(\n transformers=[(\"num\", numeric_pipeline_Y, [self.target])]\n )\n\n self._scaler_X = kwargs.get(\"scaler_X\", preprocessor_X)\n self._scaler_Y = kwargs.get(\"scaler_Y\", preprocessor_Y)\n\n def __getitem__(self, i: int):\n \"\"\"\n get X, Y for given index `di`\n\n Args:\n di(datetime): datetime where output starts\n\n Returns:\n Tensor: transformed input (might be normalized)\n Tensor: output without transform\n \"\"\"\n x = self._xs.iloc[i : i + self.sample_size]\n y = self._ys.iloc[\n (i + self.sample_size) : (i + self.sample_size + self.output_size)\n ]\n y_raw = self._ys_raw.iloc[\n (i + self.sample_size) : (i + self.sample_size + self.output_size), :\n ]\n\n # return X, Y, Y_dates\n return (\n np.squeeze(self._scaler.transform(x.to_numpy())).astype(\"float32\"),\n np.squeeze(y).astype(\"float32\"),\n np.squeeze(y_raw.to_numpy()).astype(\"float32\"),\n self._dates[\n (i + self.sample_size) : (i + self.sample_size + self.output_size)\n ],\n )\n\n def preprocess(self):\n \"\"\"Fit and transform for input data\"\"\"\n # compute seasonality\n self._scaler_X.fit(self._xs)\n self._scaler_Y.fit(self._ys, y=self._ys)\n\n self.transform()\n\n def plot_pdf(self, png_dir, svg_dir, suffix):\n \"\"\"Plot probability density function\n\n Args:\n data_dir (Path): data path\n png_dir (Path): seasonality plot path (png)\n svg_dir (Path): seasonality plot path (Svg)\n suffix (str): filename suffix\n \"\"\"\n fig = plt.figure()\n plt.title(self.target + \" raw X input\")\n sns.distplot(\n self._xs_raw[self.target],\n hist=False,\n kde=True,\n kde_kws={\"linewidth\": 3},\n label=self.target,\n )\n plt.savefig(png_dir / (self.target + \"_raw_X_\" + suffix + \".png\"))\n plt.savefig(svg_dir / (self.target + \"_raw_X_\" + suffix + \".svg\"))\n plt.close(fig)\n\n fig = plt.figure()\n plt.title(self.target + \" raw Y input\")\n sns.distplot(\n self._ys_raw[self.target],\n hist=False,\n kde=True,\n kde_kws={\"linewidth\": 3},\n label=self.target,\n )\n plt.savefig(png_dir / (self.target + \"_raw_Y_\" + suffix + \".png\"))\n plt.savefig(svg_dir / (self.target + \"_raw_Y_\" + suffix + \".svg\"))\n plt.close(fig)\n\n fig = plt.figure()\n plt.title(self.target + \" transformed X input\")\n sns.distplot(\n self._xs[self.target],\n hist=False,\n kde=True,\n kde_kws={\"linewidth\": 3},\n label=self.target,\n )\n plt.savefig(png_dir / (self.target + \"_tf_X_\" + suffix + \".png\"))\n plt.savefig(svg_dir / (self.target + \"_tf_X_\" + suffix + \".svg\"))\n plt.close(fig)\n\n fig = plt.figure()\n plt.title(self.target + \" transformed Y input\")\n sns.distplot(\n self._ys[self.target],\n hist=False,\n kde=True,\n kde_kws={\"linewidth\": 3},\n label=self.target,\n )\n plt.savefig(png_dir / (self.target + \"_tf_Y_\" + suffix + \".png\"))\n plt.savefig(svg_dir / (self.target + \"_tf_Y_\" + suffix + \".svg\"))\n plt.close(fig)\n\n def transform(self):\n \"\"\"Transform dataset and convert to DataFrame\"\"\"\n self._xs = pd.DataFrame(\n data=self._scaler_X.transform(self._xs),\n index=self._xs.index,\n columns=self._xs.columns,\n )\n self._ys = pd.DataFrame(\n data=self._scaler_Y.transform(self._ys),\n index=self._ys.index,\n columns=self._ys.columns,\n )\n\n def inverse_transform(self, Ys: tuple, dates: tuple):\n \"\"\"inverse_transform accepts DataFrame, but output is always ndarray\n so keep DataFrame structure\n\n Args:\n Ys(tuple): batched ndarray, the shape of each element is (output_size,)\n dates(tuple): batched ndarray, the shape of each element is (output_size,)\n\n Return\n Yhats(tuple): batched ndarray, the shape of each element is (output_size,)\n \"\"\"\n # temporary DataFrame to pass dates\n dfs = list(\n map(\n lambda b: pd.DataFrame(data=b[0], index=b[1], columns=[self.target]),\n zip(Ys, dates),\n )\n )\n\n # execute pipeline's inverse transform\n # transform : (DataFrame) -> SeasonalityDecompositor (needs date) ->\n # StandardScaler -> (ndarray)\n # inverse_transform : (ndarray) -> StandardScaler ->\n # (ndarray) -> (DataFrame) -> SeasonaltyDecompositor -> (ndarray)\n _inv_transYs = tuple(\n map(\n lambda b: np.squeeze(\n self._scaler_Y.named_transformers_[\"num\"].inverse_transform(b)\n ),\n dfs,\n )\n )\n\n # numpy.ndarray\n return _inv_transYs\n\n def to_csv(self, fpath):\n \"\"\"Save dataset to csv\n\n Args:\n fpath (Path): csv file path\n \"\"\"\n self._df.to_csv(fpath)\n\n @property\n def scaler_X(self):\n \"\"\"scaler_X getter\n\n Returns:\n sklearn.preprocessing.StandardScaler: scaler for X\n \"\"\"\n return self._scaler_X\n\n @property\n def scaler_Y(self):\n \"\"\"scaler_Y getter\n\n Returns:\n sklearn.preprocessing.StandardScaler: scaler for Y\n \"\"\"\n return self._scaler_Y\n\n\nclass MultivariateMeanSeasonalityDataset(BaseDataset):\n \"\"\"Serialized Multivariate Dataset with Seasonality Decomposition\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # 1-step transformer\n # 1. StandardScalerWrapper\n self.features_1 = kwargs.get(\n \"features_1\", [\"temp\", \"u\", \"v\", \"pres\", \"humid\", \"prep\", \"snow\"]\n )\n # 2-step transformer\n # 1. SeasonalityDecompositor\n # 2. StandardScalerWrapper\n self.features_2 = kwargs.get(\n \"features_2\", [\"SO2\", \"CO\", \"O3\", \"NO2\", \"PM10\", \"PM25\"]\n )\n\n # complement of features\n self.features_c = copy.deepcopy(self.features)\n self.features_c.remove(self.target)\n\n self._df_raw = self._df.copy()\n # 2D, in Univariate -> (row x 1)\n self._xs = self._df[self.features]\n self._xs_raw = self._xs.copy()\n\n # 1D\n self._ys = self._df[self.target]\n self._ys.name = self.target\n # convert to DataFrame to apply ColumnTransformer easily\n self._ys = self._ys.to_frame()\n self._ys_raw = self._ys.copy()\n # self._xs must not be available when creating instance so no kwargs for scaler\n\n # mix ColumnTransformer & Pipeline\n # https://scikit-learn.org/stable/auto_examples/compose/plot_column_transformer_mixed_types.html\n # pipeline for regression data\n\n numeric_pipeline_X_1 = Pipeline(\n [\n (\n \"standardscalerwrapper\",\n StandardScalerWrapper(scaler=StandardScaler(with_std=False)),\n )\n ]\n )\n\n numeric_pipeline_X_2 = Pipeline(\n [\n (\n \"seasonalitydecompositor\",\n SeasonalityDecompositor_AWH(smoothing=True, smoothing_frac=0.05),\n ),\n (\n \"standardscalerwrapper\",\n StandardScalerWrapper(scaler=StandardScaler(with_std=False)),\n ),\n ]\n )\n\n numeric_pipeline_Y = Pipeline(\n [\n (\n \"seasonalitydecompositor\",\n SeasonalityDecompositor_AWH(smoothing=True, smoothing_frac=0.05),\n ),\n (\n \"standardscalerwrapper\",\n StandardScalerWrapper(scaler=StandardScaler(with_std=False)),\n ),\n ]\n )\n\n # Univariate -> only pipline needed\n # Multivariate -> Need ColumnTransformer\n preprocessor_X = ColumnTransformer(\n transformers=[\n (\"num_2\", numeric_pipeline_X_2, self.features_2),\n (\"num_1\", numeric_pipeline_X_1, self.features_1),\n ]\n )\n\n preprocessor_Y = ColumnTransformer(\n transformers=[(\"num\", numeric_pipeline_Y, [self.target])]\n )\n\n self._scaler_X = kwargs.get(\"scaler_X\", preprocessor_X)\n self._scaler_Y = kwargs.get(\"scaler_Y\", preprocessor_Y)\n\n def __getitem__(self, i: int):\n \"\"\"\n get X, Y for given index `di`\n\n Args:\n di(datetime): datetime where output starts\n\n Returns:\n Tensor: transformed input (might be normalized)\n Tensor: output without transform\n \"\"\"\n # https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#combining-positional-and-label-based-indexing\n # get_loc -> series, get_indexer -> 1D DataFrame\n # x = self._xs.iloc[i:i+self.sample_size, self._xs.columns.get_indexer(self.features_c)]\n x = self._xs.iloc[i : i + self.sample_size, :]\n x1d = self._xs.iloc[\n i : i + self.sample_size, self._xs.columns.get_indexer([self.target])\n ]\n y = self._ys.iloc[\n (i + self.sample_size) : (i + self.sample_size + self.output_size), :\n ]\n y_raw = self._ys_raw.iloc[\n (i + self.sample_size) : (i + self.sample_size + self.output_size), :\n ]\n\n return (\n np.squeeze(x.to_numpy()).astype(\"float32\"),\n np.squeeze(x1d.to_numpy()).astype(\"float32\"),\n np.squeeze(y.to_numpy()).astype(\"float32\"),\n np.squeeze(y_raw.to_numpy()).astype(\"float32\"),\n y.index.to_numpy(),\n )\n\n def preprocess(self):\n \"\"\"Compute seasonality and transform by seasonality\"\"\"\n # compute seasonality\n self._scaler_X.fit(self._xs)\n self._scaler_Y.fit(self._ys, y=self._ys)\n\n self.transform()\n\n def plot_pdf(self, png_dir, svg_dir, suffix):\n \"\"\"Plot probability density function\n\n Args:\n data_dir (Path): data path\n png_dir (Path): seasonality plot path (png)\n svg_dir (Path): seasonality plot path (Svg)\n suffix (str): filename suffix\n \"\"\"\n fig = plt.figure()\n plt.title(self.target + \" raw X input\")\n sns.distplot(\n self._xs_raw[self.target],\n hist=False,\n kde=True,\n kde_kws={\"linewidth\": 3},\n label=self.target,\n )\n plt.savefig(png_dir / (self.target + \"_raw_X_\" + suffix + \".png\"))\n plt.savefig(svg_dir / (self.target + \"_raw_X_\" + suffix + \".svg\"))\n plt.close(fig)\n\n fig = plt.figure()\n plt.title(self.target + \" raw Y input\")\n sns.distplot(\n self._ys_raw[self.target],\n hist=False,\n kde=True,\n kde_kws={\"linewidth\": 3},\n label=self.target,\n )\n plt.savefig(png_dir / (self.target + \"_raw_Y_\" + suffix + \".png\"))\n plt.savefig(svg_dir / (self.target + \"_raw_Y_\" + suffix + \".svg\"))\n plt.close(fig)\n\n fig = plt.figure()\n plt.title(self.target + \" transformed X input\")\n sns.distplot(\n self._xs[self.target],\n hist=False,\n kde=True,\n kde_kws={\"linewidth\": 3},\n label=self.target,\n )\n plt.savefig(png_dir / (self.target + \"_tf_X_\" + suffix + \".png\"))\n plt.savefig(svg_dir / (self.target + \"_tf_X_\" + suffix + \".svg\"))\n plt.close(fig)\n\n fig = plt.figure()\n plt.title(self.target + \" transformed Y input\")\n sns.distplot(\n self._ys[self.target],\n hist=False,\n kde=True,\n kde_kws={\"linewidth\": 3},\n label=self.target,\n )\n plt.savefig(png_dir / (self.target + \"_tf_Y_\" + suffix + \".png\"))\n plt.savefig(svg_dir / (self.target + \"_tf_Y_\" + suffix + \".svg\"))\n plt.close(fig)\n\n def transform(self):\n \"\"\"Transform dataset and convert to DataFrame\"\"\"\n self._xs = pd.DataFrame(\n data=self._scaler_X.transform(self._xs),\n index=self._xs.index,\n columns=self._xs.columns,\n )\n self._ys = pd.DataFrame(\n data=self._scaler_Y.transform(self._ys),\n index=self._ys.index,\n columns=self._ys.columns,\n )\n\n def inverse_transform(self, Ys: tuple, dates: tuple):\n \"\"\"inverse_transform accepts DataFrame, but output is always ndarray\n so keep DataFrame structure\n\n Args:\n Ys(tuple): batched ndarray, the shape of each element is (output_size,)\n dates(tuple): batched ndarray, the shape of each element is (output_size,)\n\n Return\n Yhats(tuple): batched ndarray, the shape of each element is (output_size,)\n \"\"\"\n # temporary DataFrame to pass dates\n dfs = list(\n map(\n lambda b: pd.DataFrame(data=b[0], index=b[1], columns=[self.target]),\n zip(Ys, dates),\n )\n )\n\n # execute pipeline's inverse transform\n # transform : (DataFrame) -> SeasonalityDecompositor (needs date) ->\n # StandardScaler -> (ndarray)\n # inverse_transform : (ndarray) -> StandardScaler ->\n # (ndarray) -> (DataFrame) -> SeasonaltyDecompositor -> (ndarray)\n _inv_transYs = tuple(\n map(\n lambda b: np.squeeze(\n self._scaler_Y.named_transformers_[\"num\"].inverse_transform(b)\n ),\n dfs,\n )\n )\n\n # numpy.ndarray\n return _inv_transYs\n\n def plot_seasonality(self, data_dir, png_dir, svg_dir):\n \"\"\"Plot seasonality\n\n Args:\n data_dir (Path): data path\n png_dir (Path): seasonality plot path (png)\n svg_dir (Path): seasonality plot path (svg)\n \"\"\"\n p = self._scaler_Y.named_transformers_[\"num\"]\n\n p[\"seasonalitydecompositor\"].plot(\n self._xs, self.target, self.fdate, self.tdate, data_dir, png_dir, svg_dir\n )\n\n def to_csv(self, fpath):\n \"\"\"Save dataset to csv\n\n Args:\n fpath (Path): csv file path\n \"\"\"\n self._df.to_csv(fpath)\n\n @property\n def scaler_X(self):\n \"\"\"scaler_X getter\n\n Returns:\n sklearn.preprocessing.StandardScaler: scaler for X\n \"\"\"\n return self._scaler_X\n\n @property\n def scaler_Y(self):\n \"\"\"scaler_Y getter\n\n Returns:\n sklearn.preprocessing.StandardScaler: scaler for Y\n \"\"\"\n return self._scaler_Y\n\n @property\n def xs(self):\n \"\"\"xs getter\n\n Returns:\n pandas.DataFrame: xs\n \"\"\"\n return self._xs\n\n @property\n def xs_raw(self):\n \"\"\"xs_raw getter\n\n Returns:\n pandas.DataFrame: xs_raw\n \"\"\"\n return self._xs_raw\n\n @property\n def ys(self):\n \"\"\"ys getter\n\n Returns:\n pandas.DataFrame: ys\n \"\"\"\n return self._ys\n\n @property\n def ys_raw(self):\n \"\"\"ys_raw getter\n\n Returns:\n pandas.DataFrame: ys_raw\n \"\"\"\n return self._ys_raw\n\n\nclass MultivariateRNNDataset(BaseDataset):\n \"\"\"Non-Serialized Multivariate Dataset without Seasonaltiy Decomposition\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self._df_raw = self._df.copy()\n # 2D, in Univariate -> (row x 1)\n self._xs = self._df[self.features]\n self._xs_raw = self._xs.copy()\n\n # 1D\n self._ys = self._df[self.target]\n self._ys.name = self.target\n # convert to DataFrame to apply ColumnTransformer easily\n self._ys = self._ys.to_frame()\n self._ys_raw = self._ys.copy()\n\n # pipeline for regression data\n numeric_pipeline_X = Pipeline(\n [\n (\n \"standardscalerwrapper\",\n StandardScalerWrapper(scaler=StandardScaler(with_std=False)),\n )\n ]\n )\n\n numeric_pipeline_Y = Pipeline(\n [\n (\n \"standardscalerwrapper\",\n StandardScalerWrapper(scaler=StandardScaler(with_std=False)),\n )\n ]\n )\n\n # Univariate -> only pipline needed\n # Multivariate -> Need ColumnTransformer\n preprocessor_X = ColumnTransformer(\n transformers=[(\"num\", numeric_pipeline_X, self.features)]\n )\n\n preprocessor_Y = ColumnTransformer(\n transformers=[(\"num\", numeric_pipeline_Y, [self.target])]\n )\n\n # univariate dataset only needs single pipeline\n self._scaler_X = kwargs.get(\"scaler_X\", preprocessor_X)\n self._scaler_Y = kwargs.get(\"scaler_Y\", preprocessor_Y)\n\n def __getitem__(self, i: int):\n \"\"\"\n get X, Y for given index `di`\n\n Args:\n di(datetime): datetime where output starts\n\n Returns:\n Tensor: transformed input (might be normalized)\n Tensor: output without transform\n \"\"\"\n x = self._xs.iloc[i : i + self.sample_size]\n x_1d = self._ys.iloc[i : (i + self.sample_size)]\n # save initial input as target variable input at last step (single step)\n y0 = self._ys.iloc[i + self.sample_size - 1]\n y = self._ys.iloc[\n (i + self.sample_size) : (i + self.sample_size + self.output_size)\n ]\n y_raw = self._ys_raw.iloc[\n (i + self.sample_size) : (i + self.sample_size + self.output_size), :\n ]\n\n # return X, Y, Y_dates\n return (\n np.squeeze(x).to_numpy().astype(\"float32\"),\n np.squeeze(x_1d).to_numpy().astype(\"float32\"),\n y0.astype(\"float32\"),\n np.squeeze(y).astype(\"float32\"),\n np.squeeze(y_raw).astype(\"float32\"),\n self._dates[\n (i + self.sample_size) : (i + self.sample_size + self.output_size)\n ],\n )\n\n def preprocess(self):\n \"\"\"Transform by scaler\"\"\"\n # compute seasonality\n self._scaler_X.fit(self._xs)\n self._scaler_Y.fit(self._ys)\n\n self.transform()\n\n def plot_pdf(self, png_dir, svg_dir, suffix):\n \"\"\"Plot probability density function\n\n Args:\n data_dir (Path): data path\n png_dir (Path): seasonality plot path (png)\n svg_dir (Path): seasonality plot path (Svg)\n suffix (str): filename suffix\n \"\"\"\n fig = plt.figure()\n plt.title(self.target + \" raw X input\")\n sns.distplot(\n self._xs_raw[self.target],\n hist=False,\n kde=True,\n kde_kws={\"linewidth\": 3},\n label=self.target,\n )\n plt.savefig(png_dir / (self.target + \"_raw_X_\" + suffix + \".png\"))\n plt.savefig(svg_dir / (self.target + \"_raw_X_\" + suffix + \".svg\"))\n plt.close(fig)\n\n fig = plt.figure()\n plt.title(self.target + \" raw Y input\")\n sns.distplot(\n self._ys_raw[self.target],\n hist=False,\n kde=True,\n kde_kws={\"linewidth\": 3},\n label=self.target,\n )\n plt.savefig(png_dir / (self.target + \"_raw_Y_\" + suffix + \".png\"))\n plt.savefig(svg_dir / (self.target + \"_raw_Y_\" + suffix + \".svg\"))\n plt.close(fig)\n\n fig = plt.figure()\n plt.title(self.target + \" transformed X input\")\n sns.distplot(\n self._xs[self.target],\n hist=False,\n kde=True,\n kde_kws={\"linewidth\": 3},\n label=self.target,\n )\n plt.savefig(png_dir / (self.target + \"_tf_X_\" + suffix + \".png\"))\n plt.savefig(svg_dir / (self.target + \"_tf_X_\" + suffix + \".svg\"))\n plt.close(fig)\n\n fig = plt.figure()\n plt.title(self.target + \" transformed Y input\")\n sns.distplot(\n self._ys[self.target],\n hist=False,\n kde=True,\n kde_kws={\"linewidth\": 3},\n label=self.target,\n )\n plt.savefig(png_dir / (self.target + \"_tf_Y_\" + suffix + \".png\"))\n plt.savefig(svg_dir / (self.target + \"_tf_Y_\" + suffix + \".svg\"))\n plt.close(fig)\n\n def transform(self):\n \"\"\"Transform dataset and convert to DataFrame\"\"\"\n self._xs = pd.DataFrame(\n data=self._scaler_X.transform(self._xs),\n index=self._xs.index,\n columns=self._xs.columns,\n )\n self._ys = pd.DataFrame(\n data=self._scaler_Y.transform(self._ys),\n index=self._ys.index,\n columns=self._ys.columns,\n )\n\n def inverse_transform(self, Ys: tuple, dates: tuple):\n \"\"\"transform accepts DataFrame, but output is always ndarray\n so keep DataFrame structure\n\n Args:\n Ys(tuple): batched ndarray, the shape of each element is (output_size,)\n dates(tuple): batched ndarray, the shape of each element is (output_size,)\n\n Return\n Yhats(tuple): batched DataFrames, the shape of each element is (output_size,)\n \"\"\"\n # temporary DataFrame to pass dates\n dfs = list(\n map(\n lambda b: pd.DataFrame(data=b[0], index=b[1], columns=[self.target]),\n zip(Ys, dates),\n )\n )\n\n # execute pipeline's inverse transform\n # transform : (DataFrame) -> SeasonalityDecompositor (needs date) ->\n # StandardScaler -> (ndarray)\n # inverse_transform : (ndarray) -> StandardScaler ->\n # (ndarray) -> (DataFrame) -> SeasonaltyDecompositor -> (ndarray)\n _inv_transYs = tuple(\n map(\n lambda b: np.squeeze(\n self._scaler_Y.named_transformers_[\"num\"].inverse_transform(b)\n ),\n dfs,\n )\n )\n\n return _inv_transYs\n\n def to_csv(self, fpath):\n \"\"\"Save dataset to csv\n\n Args:\n fpath (Path): csv file path\n \"\"\"\n self._df.to_csv(fpath)\n\n @property\n def scaler_X(self):\n \"\"\"scaler_X getter\n\n Returns:\n sklearn.preprocessing.StandardScaler: scaler for X\n \"\"\"\n return self._scaler_X\n\n @property\n def scaler_Y(self):\n \"\"\"scaler_Y getter\n\n Returns:\n sklearn.preprocessing.StandardScaler: scaler for Y\n \"\"\"\n return self._scaler_Y\n\n @property\n def ys(self):\n \"\"\"ys getter\n\n Returns:\n pandas.DataFrame: ys\n \"\"\"\n return self._ys\n\n\nclass MultivariateRNNMeanSeasonalityDataset(BaseDataset):\n \"\"\"Non-Serialized Multivariate Dataset with Seasonaltiy Decomposition\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # 1-step transformer\n # 1. StandardScalerWrapper\n self.features = kwargs.get(\n \"features\",\n [\n \"temp\",\n \"u\",\n \"v\",\n \"pres\",\n \"humid\",\n \"prep\",\n \"snow\",\n \"SO2\",\n \"CO\",\n \"O3\",\n \"NO2\",\n \"PM10\",\n \"PM25\",\n ],\n )\n self.features_1 = kwargs.get(\n \"features_1\", [\"temp\", \"u\", \"v\", \"pres\", \"humid\", \"prep\", \"snow\"]\n )\n # 2-step transformer\n # 1. SeasonalityDecompositor\n # 2. StandardScalerWrapper\n self.features_2 = kwargs.get(\n \"features_2\", [\"SO2\", \"CO\", \"O3\", \"NO2\", \"PM10\", \"PM25\"]\n )\n self.features_sea_embed = kwargs.get(\"features_sea_embed\", [self.target])\n\n self._df_raw = self._df.copy()\n # 2D, in Univariate -> (row x 1)\n self._xs = self._df[self.features]\n self._xs_raw = self._xs.copy()\n self._xs_sea = pd.DataFrame(index=self._xs.index)\n # 1D\n self._ys = self._df[self.target]\n self._ys.name = self.target\n # convert to DataFrame to apply ColumnTransformer easily\n self._ys = self._ys.to_frame()\n self._ys_raw = self._ys.copy()\n self._ys_sea = pd.DataFrame(index=self._ys.index)\n\n # mix ColumnTransformer & Pipeline\n # https://scikit-learn.org/stable/auto_examples/compose/plot_column_transformer_mixed_types.html\n\n # numeric_pipeline_X_std = Pipeline(\n # [('powertransformer', PowerTransformerWrapper(scaler=PowerTransformer()))])\n\n # numeric_pipeline_X_sea = Pipeline(\n # [('seasonalitydecompositor',\n # SeasonalityDecompositor_AWH(smoothing=True, smoothing_frac=0.05)),\n # ('powertransformer', PowerTransformerWrapper(scaler=PowerTransformer()))])\n\n # numeric_pipeline_Y = Pipeline(\n # [('seasonalitydecompositor',\n # SeasonalityDecompositor_AWH(smoothing=True, smoothing_frac=0.05)),\n # ('powertransformer', PowerTransformerWrapper(scaler=PowerTransformer()))])\n\n numeric_pipeline_X_std = Pipeline(\n [\n (\n \"standardtransformer\",\n StandardScalerWrapper(scaler=StandardScaler(with_std=False)),\n )\n ]\n )\n\n numeric_pipeline_X_sea = Pipeline(\n [\n (\n \"seasonalitydecompositor\",\n SeasonalityDecompositor_AWH(smoothing=True, smoothing_frac=0.05),\n ),\n (\n \"standardtransformer\",\n StandardScalerWrapper(scaler=StandardScaler(with_std=False)),\n ),\n ]\n )\n\n numeric_pipeline_Y = Pipeline(\n [\n (\n \"seasonalitydecompositor\",\n SeasonalityDecompositor_AWH(smoothing=True, smoothing_frac=0.05),\n ),\n (\n \"standardtransformer\",\n StandardScalerWrapper(scaler=StandardScaler(with_std=False)),\n ),\n ]\n )\n\n # Univariate -> only pipline needed\n # Multivariate -> Need ColumnTransformer\n preprocessor_X = ColumnTransformer(\n transformers=[\n (\"num_sea\", numeric_pipeline_X_sea, self.features_2),\n (\"num_std\", numeric_pipeline_X_std, self.features_1),\n ]\n )\n\n preprocessor_Y = ColumnTransformer(\n transformers=[(\"num\", numeric_pipeline_Y, [self.target])]\n )\n\n # univariate dataset only needs single pipeline\n self._scaler_X = kwargs.get(\"scaler_X\", preprocessor_X)\n self._scaler_Y = kwargs.get(\"scaler_Y\", preprocessor_Y)\n\n def __getitem__(self, i: int):\n \"\"\"\n get X, Y for given index `i`\n\n Args:\n i(datetime): datetime where output starts\n\n Returns:\n Tensor: transformed input (might be normalized)\n Tensor: transformed input (might be normalized)\n Tensor: output without transform\n \"\"\"\n x = self._xs.iloc[i : i + self.sample_size, :]\n # want 1D array of target column, so use ys instead\n x_1d = self._ys.iloc[i : (i + self.sample_size)]\n x_sa = self._xs_sea[\"annual\"].iloc[i : (i + self.sample_size)]\n x_sw = self._xs_sea[\"weekly\"].iloc[i : (i + self.sample_size)]\n x_sh = self._xs_sea[\"hourly\"].iloc[i : (i + self.sample_size)]\n # save initial input as target variable input at last step (single step)\n y = self._ys.iloc[\n (i + self.sample_size) : (i + self.sample_size + self.output_size)\n ]\n y_sa = self._ys_sea[\"annual\"].iloc[\n (i + self.sample_size) : (i + self.sample_size + self.output_size)\n ]\n y_sw = self._ys_sea[\"weekly\"].iloc[\n (i + self.sample_size) : (i + self.sample_size + self.output_size)\n ]\n y_sh = self._ys_sea[\"hourly\"].iloc[\n (i + self.sample_size) : (i + self.sample_size + self.output_size)\n ]\n y_raw = self._ys_raw.iloc[\n (i + self.sample_size) : (i + self.sample_size + self.output_size), :\n ]\n\n # To embed dates, x and y is DataFrame\n return (\n np.squeeze(x.to_numpy()).astype(\"float32\"),\n np.squeeze(x_1d.to_numpy()).astype(\"float32\"),\n np.squeeze(x_sa.to_numpy()).astype(\"float32\"),\n np.squeeze(x_sw.to_numpy()).astype(\"float32\"),\n np.squeeze(x_sh.to_numpy()).astype(\"float32\"),\n np.squeeze(y.to_numpy()).astype(\"float32\"),\n np.squeeze(y_raw.to_numpy()).astype(\"float32\"),\n np.squeeze(y_sa.to_numpy()).astype(\"float32\"),\n np.squeeze(y_sw.to_numpy()).astype(\"float32\"),\n np.squeeze(y_sh.to_numpy()).astype(\"float32\"),\n self._dates[\n (i + self.sample_size) : (i + self.sample_size + self.output_size)\n ],\n )\n\n def preprocess(self):\n \"\"\"Compute seasonality and transform by seasonality\"\"\"\n # plot correlation matrix\n\n # compute seasonality\n self._scaler_X.fit(self._xs)\n self._scaler_Y.fit(self._ys)\n\n self.transform()\n\n def plot_pdf(self, png_dir, svg_dir, suffix):\n \"\"\"Plot probability density function\n\n Args:\n data_dir (Path): data path\n png_dir (Path): seasonality plot path (png)\n svg_dir (Path): seasonality plot path (Svg)\n suffix (str): filename suffix\n \"\"\"\n fig = plt.figure()\n plt.title(self.target + \" raw X input\")\n sns.distplot(\n self._xs_raw[self.target],\n hist=False,\n kde=True,\n kde_kws={\"linewidth\": 3},\n label=self.target,\n )\n plt.savefig(png_dir / (self.target + \"_raw_X_\" + suffix + \".png\"))\n plt.savefig(svg_dir / (self.target + \"_raw_X_\" + suffix + \".svg\"))\n plt.close(fig)\n\n fig = plt.figure()\n plt.title(self.target + \" raw Y input\")\n sns.distplot(\n self._ys_raw[self.target],\n hist=False,\n kde=True,\n kde_kws={\"linewidth\": 3},\n label=self.target,\n )\n plt.savefig(png_dir / (self.target + \"_raw_Y_\" + suffix + \".png\"))\n plt.savefig(svg_dir / (self.target + \"_raw_Y_\" + suffix + \".svg\"))\n plt.close(fig)\n\n fig = plt.figure()\n plt.title(self.target + \" transformed X input\")\n sns.distplot(\n self._xs[self.target],\n hist=False,\n kde=True,\n kde_kws={\"linewidth\": 3},\n label=self.target,\n )\n plt.savefig(png_dir / (self.target + \"_tf_X_\" + suffix + \".png\"))\n plt.savefig(svg_dir / (self.target + \"_tf_X_\" + suffix + \".svg\"))\n plt.close(fig)\n\n fig = plt.figure()\n plt.title(self.target + \" transformed Y input\")\n sns.distplot(\n self._ys[self.target],\n hist=False,\n kde=True,\n kde_kws={\"linewidth\": 3},\n label=self.target,\n )\n plt.savefig(png_dir / (self.target + \"_tf_Y_\" + suffix + \".png\"))\n plt.savefig(svg_dir / (self.target + \"_tf_Y_\" + suffix + \".svg\"))\n plt.close(fig)\n\n def transform(self):\n \"\"\"Transform dataset and convert to DataFrame\"\"\"\n self._xs = pd.DataFrame(\n data=self._scaler_X.transform(self._xs),\n index=self._xs.index,\n columns=self._xs.columns,\n )\n self._ys = pd.DataFrame(\n data=self._scaler_Y.transform(self._ys),\n index=self._ys.index,\n columns=self._ys.columns,\n )\n\n def inverse_transform(self, Ys: tuple, dates: tuple):\n \"\"\"transform accepts DataFrame, but output is always ndarray\n so keep DataFrame structure\n\n Args:\n Ys(tuple): batched ndarray, the shape of each element is (output_size,)\n dates(tuple): batched ndarray, the shape of each element is (output_size,)\n\n Return\n Yhats(tuple): batched DataFrames, the shape of each element is (output_size,)\n \"\"\"\n # temporary DataFrame to pass dates\n dfs = list(\n map(\n lambda b: pd.DataFrame(data=b[0], index=b[1], columns=[self.target]),\n zip(Ys, dates),\n )\n )\n\n # execute pipeline's inverse transform\n # transform : (DataFrame) -> SeasonalityDecompositor (needs date) ->\n # StandardScaler -> (ndarray)\n # inverse_transform : (ndarray) -> StandardScaler ->\n # (ndarray) -> (DataFrame) -> SeasonaltyDecompositor -> (ndarray)\n _inv_transYs = tuple(\n map(\n lambda b: np.squeeze(\n self._scaler_Y.named_transformers_[\"num\"].inverse_transform(b)\n ),\n dfs,\n )\n )\n\n return _inv_transYs\n\n def broadcast_seasonality(self):\n \"\"\"Build seasonality DataFrame by DateTimeIndex\"\"\"\n p = self._scaler_X.named_transformers_[\"num_sea\"]\n\n # extract seasonality from seasonalitydecompositor\n _sea_annual = p.get_params()[\"seasonalitydecompositor__sea_annual\"]\n _sea_weekly = p.get_params()[\"seasonalitydecompositor__sea_weekly\"]\n _sea_hourly = p.get_params()[\"seasonalitydecompositor__sea_hourly\"]\n\n # filter target\n sea_annual = _sea_annual[self.target]\n sea_weekly = _sea_weekly[self.target]\n sea_hourly = _sea_hourly[self.target]\n\n def key_md(idx): return \"\".join((str(idx.month).zfill(2), str(idx.day).zfill(2)))\n def key_w(idx): return str(idx.dayofweek)\n def key_h(idx): return str(idx.hour).zfill(2)\n\n def get_sea_annual(idx): return sea_annual[key_md(idx)]\n def get_sea_weekly(idx): return sea_weekly[key_w(idx)]\n def get_sea_hourly(idx): return sea_hourly[key_h(idx)]\n\n self._xs_sea[\"annual\"] = self._xs_sea.index.map(get_sea_annual)\n self._xs_sea[\"weekly\"] = self._xs_sea.index.map(get_sea_weekly)\n self._xs_sea[\"hourly\"] = self._xs_sea.index.map(get_sea_hourly)\n\n self._ys_sea[\"annual\"] = self._ys_sea.index.map(get_sea_annual)\n self._ys_sea[\"weekly\"] = self._ys_sea.index.map(get_sea_weekly)\n self._ys_sea[\"hourly\"] = self._ys_sea.index.map(get_sea_hourly)\n\n return sea_annual, sea_weekly, sea_hourly\n\n def plot_seasonality(self, data_dir, png_dir, svg_dir):\n \"\"\"Plot seasonality\n\n Args:\n data_dir (Path): data path\n png_dir (Path): seasonality plot path (png)\n svg_dir (Path): seasonality plot path (svg)\n \"\"\"\n p = self._scaler_Y.named_transformers_[\"num\"]\n p[\"seasonalitydecompositor\"].plot(\n self._xs_raw,\n self.target,\n self.fdate,\n self.tdate,\n data_dir,\n png_dir,\n svg_dir,\n )\n\n def plot_fused_seasonality(self, data_dir, png_dir, svg_dir):\n \"\"\"Plot seasonality in single plot\n\n Args:\n data_dir (Path): data path\n png_dir (Path): seasonality plot path (png)\n svg_dir (Path): seasonality plot path (svg)\n \"\"\"\n Path.mkdir(png_dir, parents=True, exist_ok=True)\n Path.mkdir(svg_dir, parents=True, exist_ok=True)\n Path.mkdir(data_dir, parents=True, exist_ok=True)\n p = self._scaler_Y.named_transformers_[\"num\"]\n p[\"seasonalitydecompositor\"].plot_fused(\n self._xs_raw,\n self.target,\n self.fdate,\n self.tdate,\n data_dir,\n png_dir,\n svg_dir,\n )\n\n def to_csv(self, fpath):\n \"\"\"Save dataset to csv\n\n Args:\n fpath (Path): csv file path\n \"\"\"\n self._df.to_csv(fpath)\n\n @property\n def scaler_X(self):\n \"\"\"scaler_X getter\n\n Returns:\n sklearn.preprocessing.StandardScaler: scaler for X\n \"\"\"\n return self._scaler_X\n\n @property\n def scaler_Y(self):\n \"\"\"scaler_Y getter\n\n Returns:\n sklearn.preprocessing.StandardScaler: scaler for Y\n \"\"\"\n return self._scaler_Y\n\n @property\n def ys(self):\n \"\"\"ys getter\n\n Returns:\n pandas.DataFrame: ys\n \"\"\"\n return self._ys\n\n @property\n def ys_raw(self):\n \"\"\"ys_raw getter\n\n Returns:\n pandas.DataFrame: ys_raw\n \"\"\"\n return self._ys_raw\n\n @property\n def xs(self):\n \"\"\"xs getter\n\n Returns:\n pandas.DataFrame: xs\n \"\"\"\n return self._xs\n\n @property\n def xs_raw(self):\n \"\"\"xs_raw getter\n\n Returns:\n pandas.DataFrame: xs_raw\n \"\"\"\n return self._xs_raw\n\n\n# utility functions\ndef ydt2key(d):\n \"\"\"parse date and generate key for annual seasonality\n\n Args:\n d (datetime): datetime object\n\n Returns:\n str: `mmdd` date string\n \"\"\"\n return str(d.astimezone(SEOULTZ).month).zfill(2) + str(\n d.astimezone(SEOULTZ).day\n ).zfill(2)\n\n\ndef wdt2key(d):\n \"\"\"parse date and generate key for weekly seasonality\n\n Args:\n d (datetime): datetime object\n\n Returns:\n str: `w` date string\n \"\"\"\n return str(d.astimezone(SEOULTZ).weekday())\n\n\ndef hdt2key(d):\n \"\"\"parse date and generate key for hourly seasonality\n\n Args:\n d (datetime): datetime object\n\n Returns:\n str: `hh` date string\n \"\"\"\n return str(d.astimezone(SEOULTZ).hour).zfill(2)\n\n\ndef confint_idx(acf, confint: float):\n \"\"\"Find confidence interval index\n\n If acf is below than confidence interval, return index of acf array\n\n Args:\n acf (numpy.array): autocorrelation function array\n confint (float): confidence interval given by statsmodels\n\n Returns:\n int: index of acf array where acf is below confidence interval\n \"\"\"\n for i, (a, [c1, c2]) in enumerate(zip(acf, confint)):\n if c1 - a < a and a < c2 - a:\n return i\n\n return len(acf) - 1\n\n\nclass SeasonalityDecompositor_AWH(TransformerMixin, BaseEstimator):\n \"\"\"Decompose Seasonality\n\n Attributes\n ----------\n sea_annual : list of dicts or None, shape (n_features,)\n Annual Seasonality\n sea_weekly : list of dicts or None, shape (n_features,)\n Weekly Seasonality\n sea_hourly : list of dicts or None, shape (n_features,)\n Hourly Seasonality\n \"\"\"\n\n def __init__(\n self,\n sea_annual=None,\n sea_weekly=None,\n sea_hourly=None,\n smoothing=True,\n smoothing_frac=0.05,\n ):\n \"\"\"seasonality data initialization for test data (key-value structure)\n\n Args:\n sea_annual: list of dicts or None, shape (n_features,)\n sea_weekly: list of dicts or None, shape (n_features,)\n sea_hourly: list of dicts or None, shape (n_features,)\n smoothing: bool\n\n * test data get input from train data rather than fit itself\n\n * key format of seasonality elements\n * sea_annual : YYMMDD: string (zero-padded)\n * sea_week : W: integer\n * sea_hour : HH: string (zero-padded)\n \"\"\"\n # http://danielhnyk.cz/creating-your-own-estimator-scikit-learn/\n # Use inspect\n\n # args, _, _, values = inspect.getargvalues(inspect.currentframe())\n # values.pop(\"self\")\n\n self.sea_annual = sea_annual\n self.sea_weekly = sea_weekly\n self.sea_hourly = sea_hourly\n self.smoothing = smoothing\n self.smoothing_frac = smoothing_frac\n\n def set_sesaonality(self, sea_annual, sea_weekly, sea_hourly):\n \"\"\"seasonality setter\n\n Args:\n sea_annual (List): Daliy averaged annual seasonality (365d)\n sea_weekly (List): Daily averaged weekly seasonality (7d)\n sea_hourly (List): Hourly averaged daily seasonality (24h)\n \"\"\"\n self.sea_annual = sea_annual\n self.sea_weekly = sea_weekly\n self.sea_hourly = sea_hourly\n\n def build_seasonality(self, xs: pd.DataFrame, period: str):\n \"\"\"\n Build seasonality with given DataFrame's DatetimeIndex\n Similar job as `inverse_transform`,\n but instead of sum, just return seasonality\n \"\"\"\n\n def _build_seasonality(_xs):\n # to subscript seasonality, get name (feature)\n name = _xs.name\n\n # method for row\n def _get_seasonality(idx: pd.DatetimeIndex):\n \"\"\"Method for rowwise operation\"\"\"\n if period == \"y\":\n return self.sea_annual[name][parse_ykey(idx)]\n elif period == \"w\":\n return self.sea_weekly[name][parse_wkey(idx)]\n elif period == \"h\":\n return self.sea_hourly[name][parse_hkey(idx)]\n else:\n raise Exception(\"Invalid period ('y', 'w', 'h'): \", period)\n\n # index to sum of seasonality\n sea = _xs.index.map(_get_seasonality)\n _xs_df = _xs.to_frame()\n _xs_df[\"seas\"] = sea\n\n return sea\n\n # = Y.apply(get_seasonality, axis=1)\n seas = xs.apply(_build_seasonality, 0)\n\n # raw = Y.apply(add_seasonality, 0)\n return seas\n\n def compute_seasonality(self, X, return_resid=False):\n \"\"\"Decompose seasonality of single column of DataFrame\n\n There are two method to compute hourly residuals from daily another residuals\n 1. Subtract First (Wrong)\n * Residual population makes hourly seasonality flat, which is wrong\n 2. Seasonality population first (Right)\n * Hourly seasonality comptued correctly\n \"\"\"\n # for key, convert series to dataframe\n X_h = X.copy().to_frame()\n X_h.columns = [\"raw\"]\n\n if X_h.isnull().values.any():\n raise Exception(\"Invalid data, NULL value found\")\n X_d = X_h.resample(\"D\").mean()\n\n # 1. Annual Seasonality (mmdd: 0101 ~ 1231)\n # dictionary for key (mmdd) to value (daily average)\n sea_annual, df_sea_annual, df_resid_annual = periodic_mean(\n X_d,\n \"raw\",\n \"y\",\n smoothing=self.smoothing,\n smoothing_frac=self.smoothing_frac,\n )\n\n if \"0229\" not in sea_annual:\n raise KeyError(\"You must include leap year in train data\")\n\n # 2. Weekly Seasonality (w: 0 ~ 6)\n # dictionary for key (w: 0~6) to value (daily average)\n # Weekly seasonality computes seasonality from annual residaul\n sea_weekly, df_sea_weekly, _ = periodic_mean(\n df_resid_annual.copy(), \"resid\", \"w\"\n )\n\n # 3. Hourly Seasonality (hh: 00 ~ 23)\n # join seasonality to original X_h DataFrame\n # populate seasonality from daily averaged data to hourly data\n\n ## method to generate key column from index\n def key_md(idx): return \"\".join((str(idx.month).zfill(2), str(idx.day).zfill(2)))\n def key_w(idx): return str(idx.dayofweek)\n def key_h(idx): return str(idx.hour).zfill(2)\n\n ## Add column from index for key\n df_sea_weekly[\"key_w\"] = df_sea_weekly.index\n df_sea_annual[\"key_md\"] = df_sea_annual.index\n\n X_h[\"key_md\"] = X_h.index.map(key_md)\n X_h[\"key_w\"] = X_h.index.map(key_w)\n X_h[\"key_h\"] = X_h.index.map(key_h)\n\n ## compute hourly populated seasonality from daily residuals\n X_h_spop = df_sea_annual.merge(\n X_h, how=\"left\", on=\"key_md\", validate=\"1:m\"\n ).dropna()\n X_h_spop.set_index(X_h.index, inplace=True)\n X_h_spop = X_h_spop.rename(columns={\"sea\": \"sea_annual\"})\n X_h_spop = df_sea_weekly.merge(\n X_h_spop, how=\"left\", on=\"key_w\", validate=\"1:m\"\n ).dropna()\n X_h_spop = X_h_spop.rename(columns={\"sea\": \"sea_weekly\"})\n X_h_spop.set_index(X_h.index, inplace=True)\n\n ## new hourly residual column from daily residuals\n X_h_spop[\"resid_y\"] = X_h_spop[\"raw\"] - X_h_spop[\"sea_annual\"]\n X_h_spop[\"resid_w\"] = (\n X_h_spop[\"raw\"] - X_h_spop[\"sea_annual\"] - X_h_spop[\"sea_weekly\"]\n )\n X_h_spop[\"resid_d\"] = (\n X_h_spop[\"raw\"] - X_h_spop[\"sea_annual\"] - X_h_spop[\"sea_weekly\"]\n )\n\n ## Check no missing values\n if len(X_h_spop.index) != len(X_h.index):\n raise Exception(\n \"Merge Error: something missing when populate daily averaged DataFrame\"\n )\n\n ## Compute hourly seasonality\n sea_hourly, df_sea_hourly, _ = periodic_mean(X_h_spop.copy(), \"resid_d\", \"h\")\n\n ## Add column from index for key\n df_sea_hourly[\"key_h\"] = df_sea_hourly.index\n\n ## merge hourly seasonality to orignal hourly DataFram\n X_h_hourly = df_sea_hourly.merge(\n X_h_spop, how=\"left\", on=\"key_h\", validate=\"1:m\"\n ).dropna()\n X_h_hourly = X_h_hourly.rename(columns={\"sea\": \"sea_hourly\"})\n X_h_spop.set_index(X_h.index, inplace=True)\n ## Subtract annual and weekly seasonality\n X_h_spop[\"sea_hourly\"] = X_h_hourly[\"sea_hourly\"]\n X_h_spop[\"resid\"] = X_h_spop[\"resid_d\"] - X_h_hourly[\"sea_hourly\"]\n X_h_spop[\"resid_h\"] = X_h_spop[\"resid_d\"] - X_h_hourly[\"sea_hourly\"]\n ## Sort by DateTimeIndex\n X_h_spop = X_h_spop.sort_index()\n\n # 3.2 drop key columns and intermediate residual column\n X_h_spop.drop(\"resid_d\", axis=\"columns\")\n X_h_spop.drop(\"key_md\", axis=\"columns\")\n X_h_spop.drop(\"key_w\", axis=\"columns\")\n X_h_spop.drop(\"key_h\", axis=\"columns\")\n\n if return_resid is True:\n return (\n X_h_spop[\"resid_y\"],\n X_h_spop[\"resid_w\"],\n X_h_spop,\n X_h_spop[\"resid_h\"],\n )\n\n return sea_annual, sea_weekly, sea_hourly\n\n def fit(self, X: pd.DataFrame, y=None):\n \"\"\"Compute seasonality,\n Computed residuals in `fit` will be dropped.\n In `transform` residuals are computed again from seasonality from `fit`\n\n y is not used, but added for Pipeline compatibility\n ref: https://scikit-learn.org/stable/developers/develop.html\n\n Args:\n X_h: DataFrame which have datetime as index\n\n Return:\n None\n \"\"\"\n # Decompose seasonality if there is no predefined seasonality (train/valid set)\n if (\n self.sea_annual is not None\n and self.sea_weekly is not None\n and self.sea_hourly is not None\n ):\n # if test set\n return self\n\n # apply function to column-wise\n # self.sea_annual, self.sea_weekly, self.sea_hourly = \\\n seas = X.apply(self.compute_seasonality, 0).to_dict(orient=\"records\")\n self.sea_annual = seas[0]\n self.sea_weekly = seas[1]\n self.sea_hourly = seas[2]\n\n return self\n\n def transform(self, X: pd.DataFrame):\n \"\"\"Recompute residual by subtracting seasonality from X\n shape of X is (sample_size, num_features)\n\n Args:\n X (pd.DataFrame):\n must have DataTimeIndex to get dates\n\n Returns:\n resid (np.ndarray):\n dates now doesn't be needed anymore\n \"\"\"\n\n def sub_seasonality(_X):\n \"\"\"Method for columnwise operation\"\"\"\n # to subscript seasonality, get name (feature)\n name = _X.name\n\n # method for row\n def _sum_seasonality(idx: pd.DatetimeIndex):\n \"\"\"Method for rowwise operation\"\"\"\n return (\n self.sea_annual[name][parse_ykey(idx)]\n + self.sea_weekly[name][parse_wkey(idx)]\n + self.sea_hourly[name][parse_hkey(idx)]\n )\n\n # index to sum of seasonality\n seas = _X.index.map(_sum_seasonality)\n _X_df = _X.to_frame()\n _X_df[\"seas\"] = -seas\n\n _X_sum = _X_df.sum(axis=\"columns\")\n _X_sum.name = name\n\n return _X_sum\n\n resid = X.apply(sub_seasonality, 0)\n\n return resid.to_numpy()\n\n def inverse_transform(self, Y: pd.DataFrame):\n \"\"\"Compose value from residuals\n If smoothed annual seasonality is used,\n compsed value might be different with original value\n\n shape of Y is (output_size, 1) because self.target is always one target\n\n Args:\n Y (pd.DataFrame):\n pd.DataFrame must have DataTimeIndex to get dates\n\n Returns:\n raw (ndarray):\n \"\"\"\n\n def add_seasonality(_Y):\n \"\"\"Method for columnwise operation\"\"\"\n # to subscript seasonality, get name (feature)\n name = _Y.name\n\n # method for row\n def _sum_seasonality(idx: pd.DatetimeIndex):\n \"\"\"Method for rowwise operation\"\"\"\n return (\n self.sea_annual[name][parse_ykey(idx)]\n + self.sea_weekly[name][parse_wkey(idx)]\n + self.sea_hourly[name][parse_hkey(idx)]\n )\n\n # index to sum of seasonality\n seas = _Y.index.map(_sum_seasonality)\n _Y_df = _Y.to_frame()\n _Y_df[\"seas\"] = seas\n\n _Y_sum = _Y_df.sum(axis=\"columns\")\n _Y_sum.name = name\n\n return _Y_sum\n\n # there is no way to pass row object of Series,\n # so I pass index and use Series.get() with closure\n # raw = Y.index.map(add_seasonality)\n raw = Y.apply(add_seasonality, 0)\n\n return raw.to_numpy()\n\n def plot_raw_acf(\n self, df, target, fdate, tdate, data_dir, png_dir, svg_dir, nlags=15\n ):\n \"\"\"Plot acf without seasonality decomposition\n\n Args:\n df (pandas.DataFrame): DataFrame that holds total data\n target (str): DataFrame column to compute acf\n fdate (datetime): start date of target range\n tdate (datetime): end date of target range\n data_dir (Path): data path\n png_dir (Path): seasonality plot path (png)\n svg_dir (Path): seasonality plot path (svg)\n nlags (int, optional): number of lags to compute acf.\n Defaults to 15.\n \"\"\"\n # yr = [df.loc[y, target] -\n # self.sea_annual[target][ydt2key(y)] for y in year_range]\n ys = df[(df.index >= fdate) & (df.index <= tdate)][target].to_numpy()\n # 95% confidance intervals\n ys_acf, confint, _, _ = sm.tsa.acf(ys, qstat=True, alpha=0.05, nlags=nlags)\n\n intscale = sum(ys_acf[0 : confint_idx(ys_acf, confint) + 1])\n print(\"Raw Conf Int : \", confint_idx(ys_acf, confint))\n print(\"Raw Int Scale : \", intscale)\n # print(\"Raw qstat : \", qstat)\n # print(\"Raw pvalues : \", pvalues)\n\n csv_path = data_dir / (\n \"acf_raw_\"\n + fdate.strftime(\"%Y%m%d\")\n + \"_\"\n + tdate.strftime(\"%Y%m%d\")\n + \".csv\"\n )\n df_year_acf = pd.DataFrame.from_dict(\n {\"lags\": [i for i in range(len(ys_acf))], \"yr_acf\": ys_acf}\n )\n df_year_acf.set_index(\"lags\", inplace=True)\n df_year_acf.to_csv(csv_path)\n\n png_path = png_dir / (\n \"acf_raw_\"\n + fdate.strftime(\"%Y%m%d%H\")\n + \"_\"\n + tdate.strftime(\"%Y%m%d%H\")\n + \".png\"\n )\n svg_path = svg_dir / (\n \"acf_raw_\"\n + fdate.strftime(\"%Y%m%d%H\")\n + \"_\"\n + tdate.strftime(\"%Y%m%d%H\")\n + \".svg\"\n )\n p1 = figure(title=\"Autocorrelation of \" + target)\n p1.toolbar.logo = None\n p1.toolbar_location = None\n p1.xaxis.axis_label = \"lags\"\n p1.yaxis.bounds = (min(0, min(ys_acf)), 1.1)\n p1.line(\n x=[i * 24 for i in range(len(ys_acf))],\n y=ys_acf,\n line_color=\"lightcoral\",\n line_width=2,\n )\n export_png(p1, filename=png_path)\n p1.output_backend = \"svg\"\n export_svgs(p1, filename=str(svg_path))\n\n ## residual autocorrelation by plot_acf\n png_path = png_dir / (\n \"acf(tpl)_raw_\"\n + fdate.strftime(\"%Y%m%d%H\")\n + \"_\"\n + tdate.strftime(\"%Y%m%d%H\")\n + \".png\"\n )\n svg_path = svg_dir / (\n \"acf(tpl)_raw_\"\n + fdate.strftime(\"%Y%m%d%H\")\n + \"_\"\n + tdate.strftime(\"%Y%m%d%H\")\n + \".svg\"\n )\n fig = tpl.plot_acf(ys, lags=nlags)\n fig.savefig(png_path)\n fig.savefig(svg_path)\n\n return confint_idx(ys_acf, confint), intscale\n\n def plot_annual(\n self, df, target, data_dir, png_dir, svg_dir, target_year=2016, smoothing=True\n ):\n \"\"\"Plot annual seasonality\n\n Args:\n df (pandas.DataFrame): DataFrame that holds total data\n target (str): DataFrame column to compute acf\n data_dir (Path): data path\n png_dir (Path): seasonality plot path (png)\n svg_dir (Path): seasonality plot path (svg)\n nlags (int, optional): number of lags to compute acf Defaults to 15.\n target_year (int, optional): year to plot. Defaults to 2016.\n smoothing (bool, optional): whether plot smoothed seasonality together.\n Defaults to True.\n \"\"\"\n\n # annual (pick 1 year)\n dt1 = dt.datetime(year=target_year, month=1, day=1, hour=0)\n dt2 = dt.datetime(year=target_year, month=12, day=31, hour=23)\n year_range = pd.date_range(start=dt1, end=dt2, freq=\"D\", tz=SEOULTZ).tolist()\n year_range_plt = pd.DatetimeIndex(\n [\n i.replace(tzinfo=None)\n for i in pd.date_range(start=dt1, end=dt2, freq=\"D\", tz=SEOULTZ)\n ]\n )\n\n # if not smoothing, just use predecomposed seasonality\n ys = [self.sea_annual[target][ydt2key(y)] for y in year_range]\n if smoothing:\n _sea_annual_nonsmooth, _, _ = periodic_mean(\n df, target, \"y\", smoothing=False\n )\n # if smoothing, predecomposed seasonality is already smoothed, so redecompose\n ys_vanilla = [_sea_annual_nonsmooth[ydt2key(y)] for y in year_range]\n ys_smooth = [self.sea_annual[target][ydt2key(y)] for y in year_range]\n\n csv_path = data_dir / (\n \"annual_seasonality_\"\n + dt1.strftime(\"%Y%m%d\")\n + \"_\"\n + dt2.strftime(\"%Y%m%d\")\n + \".csv\"\n )\n df_year = pd.DataFrame.from_dict({\"date\": year_range, \"ys\": ys})\n if smoothing:\n df_year = pd.DataFrame.from_dict(\n {\"date\": year_range, \"ys_vanilla\": ys_vanilla, \"ys_smooth\": ys_smooth}\n )\n df_year.set_index(\"date\", inplace=True)\n df_year.to_csv(csv_path)\n\n png_path = png_dir / (\n \"annual_seasonality_\"\n + dt1.strftime(\"%Y%m%d\")\n + \"_\"\n + dt2.strftime(\"%Y%m%d\")\n + \".png\"\n )\n svg_path = svg_dir / (\n \"annual_seasonality_\"\n + dt1.strftime(\"%Y%m%d\")\n + \"_\"\n + dt2.strftime(\"%Y%m%d\")\n + \".svg\"\n )\n\n p1 = figure(title=\"Annual Seasonality\")\n p1.xaxis.axis_label = \"dates\"\n p1.toolbar.logo = None\n p1.toolbar_location = None\n p1.xaxis.formatter = DatetimeTickFormatter(\n days=\"%m/%d\", months=\"%b\", hours=\"%H:%M\"\n )\n p1.xaxis.ticker = bokeh.models.DatetimeTicker()\n p1.line(x=year_range_plt, y=ys, line_color=\"dodgerblue\", line_width=2)\n export_png(p1, filename=png_path)\n p1.output_backend = \"svg\"\n export_svgs(p1, filename=str(svg_path))\n\n if smoothing:\n # 1. smooth\n png_path = png_dir / (\n \"annual_seasonality_(smooth)_\"\n + dt1.strftime(\"%Y%m%d\")\n + \"_\"\n + dt2.strftime(\"%Y%m%d\")\n + \".png\"\n )\n svg_path = svg_dir / (\n \"annual_seasonality_(smooth)_\"\n + dt1.strftime(\"%Y%m%d\")\n + \"_\"\n + dt2.strftime(\"%Y%m%d\")\n + \".svg\"\n )\n p1 = figure(title=\"Annual Seasonality(Smooth)\")\n p1.xaxis.axis_label = \"dates\"\n p1.toolbar.logo = None\n p1.toolbar_location = None\n p1.xaxis.formatter = DatetimeTickFormatter(\n days=\"%m/%d\", months=\"%b\", hours=\"%H:%M\"\n )\n p1.xaxis.ticker = bokeh.models.DatetimeTicker()\n p1.line(\n x=year_range_plt, y=ys_smooth, line_color=\"dodgerblue\", line_width=2\n )\n export_png(p1, filename=png_path)\n p1.output_backend = \"svg\"\n export_svgs(p1, filename=str(svg_path))\n\n # 2. vanila\n png_path = png_dir / (\n \"annual_seasonality_(vanilla)_\"\n + dt1.strftime(\"%Y%m%d\")\n + \"_\"\n + dt2.strftime(\"%Y%m%d\")\n + \".png\"\n )\n svg_path = svg_dir / (\n \"annual_seasonality_(vanilla)_\"\n + dt1.strftime(\"%Y%m%d\")\n + \"_\"\n + dt2.strftime(\"%Y%m%d\")\n + \".svg\"\n )\n p1 = figure(title=\"Annual Seasonality(Raw)\")\n p1.xaxis.axis_label = \"dates\"\n p1.toolbar.logo = None\n p1.toolbar_location = None\n p1.xaxis.formatter = DatetimeTickFormatter(\n days=\"%m/%d\", months=\"%b\", hours=\"%H:%M\"\n )\n p1.xaxis.ticker = bokeh.models.DatetimeTicker()\n p1.line(\n x=year_range_plt, y=ys_vanilla, line_color=\"dodgerblue\", line_width=2\n )\n export_png(p1, filename=png_path)\n p1.output_backend = \"svg\"\n export_svgs(p1, filename=str(svg_path))\n\n # 3. smooth + vanila\n png_path = png_dir / (\n \"annual_seasonality_(both)_\"\n + dt1.strftime(\"%Y%m%d\")\n + \"_\"\n + dt2.strftime(\"%Y%m%d\")\n + \".png\"\n )\n svg_path = svg_dir / (\n \"annual_seasonality_(both)_\"\n + dt1.strftime(\"%Y%m%d\")\n + \"_\"\n + dt2.strftime(\"%Y%m%d\")\n + \".svg\"\n )\n p1 = figure(title=\"Annual Seasonality(Smooth & Vanilla)\")\n p1.xaxis.axis_label = \"dates\"\n p1.toolbar.logo = None\n p1.toolbar_location = None\n p1.xaxis.formatter = DatetimeTickFormatter(\n days=\"%m/%d\", months=\"%b\", hours=\"%H:%M\"\n )\n p1.xaxis.ticker = bokeh.models.DatetimeTicker()\n p1.line(\n x=year_range_plt,\n y=ys_smooth,\n line_color=\"dodgerblue\",\n line_width=2,\n legend_label=\"smooth\",\n )\n p1.line(\n x=year_range_plt,\n y=ys_vanilla,\n line_color=\"lightcoral\",\n line_width=2,\n legend_label=\"vanilla\",\n )\n export_png(p1, filename=png_path)\n p1.output_backend = \"svg\"\n export_svgs(p1, filename=str(svg_path))\n\n def plot_annual_acf(\n self, df, target, fdate, tdate, data_dir, png_dir, svg_dir, nlags=15\n ):\n \"\"\"Plot acf of residuals which removed annual seasonality\n\n Args:\n df (pandas.DataFrame): DataFrame that holds total data\n target (str): DataFrame column to compute acf\n data_dir (Path): data path\n png_dir (Path): seasonality plot path (png)\n svg_dir (Path): seasonality plot path (svg)\n nlags (int, optional): number of lags to compute acf.\n Defaults to 15.\n target_year (int, optional): year to plot. Defaults to 2016.\n smoothing (bool, optional): whether plot smoothed seasonality together.\n Defaults to True.\n\n Returns:\n None\n \"\"\"\n ## residual autocorrelation by tsa.acf\n year_range = (\n pd.date_range(start=fdate, end=tdate, freq=\"D\").tz_convert(SEOULTZ).tolist()\n )\n # set hour to 0\n year_range = [y.replace(hour=0) for y in year_range]\n\n # yr = [df.loc[y, target] -\n # self.sea_annual[target][ydt2key(y)] for y in year_range]\n yr = df[(df.index >= fdate) & (df.index <= tdate)][target].to_numpy()\n\n # 95% confidance intervals\n yr_acf, confint, qstat, pvalues = sm.tsa.acf(\n yr, qstat=True, alpha=0.05, nlags=nlags\n )\n\n # I need \"hours\" as unit, so multiply 24\n intscale = sum(yr_acf[0 : confint_idx(yr_acf, confint) + 1]) * 24\n print(\"Annual Conf Int : \", confint_idx(yr_acf, confint))\n print(\"Annual Int Scale : \", intscale)\n print(\"Annual qstat : \", qstat)\n print(\"Annual pvalues : \", pvalues)\n\n csv_path = data_dir / (\n \"acf_annual_seasonality_\"\n + fdate.strftime(\"%Y%m%d\")\n + \"_\"\n + tdate.strftime(\"%Y%m%d\")\n + \".csv\"\n )\n df_year_acf = pd.DataFrame.from_dict(\n {\"lags\": [i * 24 for i in range(len(yr_acf))], \"yr_acf\": yr_acf}\n )\n df_year_acf.set_index(\"lags\", inplace=True)\n df_year_acf.to_csv(csv_path)\n\n png_path = png_dir / (\n \"acf_annual_seasonality_\"\n + fdate.strftime(\"%Y%m%d\")\n + \"_\"\n + tdate.strftime(\"%Y%m%d\")\n + \".png\"\n )\n svg_path = svg_dir / (\n \"acf_annual_seasonality_\"\n + fdate.strftime(\"%Y%m%d\")\n + \"_\"\n + tdate.strftime(\"%Y%m%d\")\n + \".svg\"\n )\n p1 = figure(title=\"Autocorrelation of Annual Residual\")\n p1.toolbar.logo = None\n p1.toolbar_location = None\n p1.xaxis.axis_label = \"lags\"\n p1.yaxis.bounds = (min(0, min(yr_acf)), 1.1)\n p1.line(\n x=[i * 24 for i in range(len(yr_acf))],\n y=yr_acf,\n line_color=\"lightcoral\",\n line_width=2,\n )\n export_png(p1, filename=png_path)\n p1.output_backend = \"svg\"\n export_svgs(p1, filename=str(svg_path))\n\n ## residual autocorrelation by plot_acf\n png_path = png_dir / (\n \"acf(tpl)_annual_seasonality_\"\n + fdate.strftime(\"%Y%m%d\")\n + \"_\"\n + tdate.strftime(\"%Y%m%d\")\n + \".png\"\n )\n svg_path = svg_dir / (\n \"acf(tpl)_annual_seasonality_\"\n + fdate.strftime(\"%Y%m%d\")\n + \"_\"\n + tdate.strftime(\"%Y%m%d\")\n + \".svg\"\n )\n fig = tpl.plot_acf(yr, lags=nlags)\n fig.savefig(png_path)\n fig.savefig(svg_path)\n\n return confint_idx(yr_acf, confint), intscale\n\n def plot_weekly(\n self, target, data_dir, png_dir, svg_dir, target_year=2016, target_week=10\n ):\n \"\"\"Plot weekly seasonality\n\n Args:\n target (str): DataFrame column to compute acf\n data_dir (Path): data path\n png_dir (Path): seasonality plot path (png)\n svg_dir (Path): seasonality plot path (svg)\n target_year (int, optional): year to plot. Defaults to 2016.\n target_week (int, optional): week to plot. Defaults to 10.\n\n Returns:\n None\n \"\"\"\n # Set datetime range\n target_dt_str = str(target_year) + \" \" + str(target_week)\n ## ISO 8601 starts weekday from Monday (1)\n dt1 = dt.datetime.strptime(target_dt_str + \" 1\", \"%Y %W %w\")\n ## ISO 8601 ends weekday to Sunday (0)\n dt2 = dt.datetime.strptime(target_dt_str + \" 0\", \"%Y %W %w\")\n ## set dt2 time as Sunday 23:59\n dt2 = dt2.replace(hour=23, minute=59)\n week_range = pd.date_range(start=dt1, end=dt2, freq=\"D\", tz=SEOULTZ).tolist()\n week_range_plt = pd.DatetimeIndex(\n [\n i.replace(tzinfo=None)\n for i in pd.date_range(start=dt1, end=dt2, freq=\"D\", tz=SEOULTZ)\n ]\n )\n\n # Compute Weekly seasonality\n ws = [self.sea_weekly[target][wdt2key(w)] for w in week_range]\n\n csv_path = data_dir / (\n \"weekly_seasonality_\"\n + dt1.strftime(\"%Y%m%d\")\n + \"_\"\n + dt2.strftime(\"%Y%m%d\")\n + \".csv\"\n )\n df_week = pd.DataFrame.from_dict({\"day\": week_range, \"ws\": ws})\n df_week.set_index(\"day\", inplace=True)\n df_week.to_csv(csv_path)\n\n png_path = png_dir / (\n \"weekly_seasonality_\"\n + dt1.strftime(\"%Y%m%d\")\n + \"_\"\n + dt2.strftime(\"%Y%m%d\")\n + \".png\"\n )\n svg_path = svg_dir / (\n \"weekly_seasonality_\"\n + dt1.strftime(\"%Y%m%d\")\n + \"_\"\n + dt2.strftime(\"%Y%m%d\")\n + \".svg\"\n )\n\n p2 = figure(title=\"Weekly Seasonality\")\n p2.toolbar.logo = None\n p2.toolbar_location = None\n p2.xaxis.axis_label = \"day\"\n p2.xaxis.formatter = DatetimeTickFormatter(days=\"%a\")\n p2.xaxis.ticker = bokeh.models.DaysTicker(days=[w.day for w in week_range_plt])\n p2.line(x=week_range_plt, y=ws, line_color=\"dodgerblue\", line_width=2)\n export_png(p2, filename=png_path)\n p2.output_backend = \"svg\"\n export_svgs(p2, filename=str(svg_path))\n\n def plot_weekly_acf(\n self, df, target, fdate, tdate, data_dir, png_dir, svg_dir, nlags=15\n ):\n \"\"\"Plot acf of residuals which removed weekly seasonality\n\n Args:\n df (pandas.DataFrame): DataFrame that holds residuals\n target (str): DataFrame column to compute acf\n fdate (datetime): start date of target range\n tdate (datetime): end date of target range\n data_dir (Path): data path\n png_dir (Path): seasonality plot path (png)\n svg_dir (Path): seasonality plot path (svg)\n nlags (int, optional): number of lags to compute acf.\n Defaults to 15.\n\n Returns:\n None\n \"\"\"\n # Set datetime range\n # target_dt_str = str(target_year) + ' ' + str(target_week)\n week_range = (\n pd.date_range(start=fdate, end=tdate, freq=\"D\").tz_convert(SEOULTZ).tolist()\n )\n # set hour to 0\n week_range = [w.replace(hour=0) for w in week_range]\n\n # wr = [df.loc[w, target] -\n # self.sea_weekly[target][wdt2key(w)] for w in week_range]\n wr = df[(df.index >= fdate) & (df.index <= tdate)][target].to_numpy()\n wr_acf, confint, qstat, pvalues = sm.tsa.acf(\n wr, qstat=True, alpha=0.05, nlags=nlags\n )\n\n # I need \"hours\" as unit, so multiply 24\n intscale = sum(wr_acf[0 : confint_idx(wr_acf, confint) + 1]) * 24\n print(\"Weekly Conf Int : \", confint_idx(wr_acf, confint))\n print(\"Weekly Int Scale : \", intscale)\n print(\"Weekly qstat : \", qstat)\n print(\"Weekly pvalues : \", pvalues)\n\n csv_path = data_dir / (\n \"acf_weekly_seasonality_\"\n + fdate.strftime(\"%Y%m%d\")\n + \"_\"\n + tdate.strftime(\"%Y%m%d\")\n + \".csv\"\n )\n df_week_acf = pd.DataFrame.from_dict(\n {\"lags\": [i * 24 for i in range(len(wr_acf))], \"wr_acf\": wr_acf}\n )\n df_week_acf.set_index(\"lags\", inplace=True)\n df_week_acf.to_csv(csv_path)\n\n png_path = png_dir / (\n \"acf_weekly_seasonality_\"\n + fdate.strftime(\"%Y%m%d\")\n + \"_\"\n + tdate.strftime(\"%Y%m%d\")\n + \".png\"\n )\n svg_path = svg_dir / (\n \"acf_weekly_seasonality_\"\n + fdate.strftime(\"%Y%m%d\")\n + \"_\"\n + tdate.strftime(\"%Y%m%d\")\n + \".svg\"\n )\n p2 = figure(title=\"Autocorrelation of Weekly Residual\")\n p2.toolbar.logo = None\n p2.toolbar_location = None\n p2.xaxis.axis_label = \"lags\"\n p2.yaxis.bounds = (min(0, min(wr_acf)), 1.1)\n p2.line(\n x=[i * 24 for i in range(len(wr_acf))],\n y=wr_acf,\n line_color=\"lightcoral\",\n line_width=2,\n )\n export_png(p2, filename=png_path)\n p2.output_backend = \"svg\"\n export_svgs(p2, filename=str(svg_path))\n\n ## residual autocorrelation by plot_acf\n png_path = png_dir / (\n \"acf(tpl)_weekly_seasonality_\"\n + fdate.strftime(\"%Y%m%d\")\n + \"_\"\n + tdate.strftime(\"%Y%m%d\")\n + \".png\"\n )\n svg_path = svg_dir / (\n \"acf(tpl)_weekly_seasonality_\"\n + fdate.strftime(\"%Y%m%d\")\n + \"_\"\n + tdate.strftime(\"%Y%m%d\")\n + \".svg\"\n )\n fig = tpl.plot_acf(wr, lags=nlags)\n fig.savefig(png_path)\n fig.savefig(svg_path)\n\n return confint_idx(wr_acf, confint), intscale\n\n def plot_hourly(\n self,\n target,\n data_dir,\n png_dir,\n svg_dir,\n target_year=2016,\n target_month=5,\n target_day=1,\n ):\n \"\"\"Plot hourly seasonality\n\n Args:\n target (str): DataFrame column to compute acf\n data_dir (Path): data path\n png_dir (Path): seasonality plot path (png)\n svg_dir (Path): seasonality plot path (svg)\n target_year (int, optional): year to plot. Defaults to 2016.\n target_week (int, optional): week to plot. Defaults to 10.\n target_day (int, optional): day to plot. Defaults to 1.\n\n Returns:\n None\n \"\"\"\n dt1 = dt.datetime(year=target_year, month=target_month, day=target_day, hour=0)\n dt2 = dt.datetime(year=target_year, month=target_month, day=target_day, hour=23)\n hour_range = pd.date_range(start=dt1, end=dt2, freq=\"1H\", tz=SEOULTZ).tolist()\n hour_range_plt = pd.DatetimeIndex(\n [\n i.replace(tzinfo=None)\n for i in pd.date_range(start=dt1, end=dt2, freq=\"1H\", tz=SEOULTZ)\n ]\n ).tolist()\n\n # Compute Hourly seasonality\n hs = [self.sea_hourly[target][hdt2key(h)] for h in hour_range]\n\n csv_path = data_dir / (\n \"hourly_seasonality_\"\n + dt1.strftime(\"%Y%m%d%H\")\n + \"_\"\n + dt2.strftime(\"%Y%m%d%H\")\n + \".csv\"\n )\n df_hour = pd.DataFrame.from_dict({\"hour\": hour_range, \"hs\": hs})\n df_hour.set_index(\"hour\", inplace=True)\n df_hour.to_csv(csv_path)\n\n png_path = png_dir / (\n \"hourly_seasonality_\"\n + dt1.strftime(\"%Y%m%d%H\")\n + \"_\"\n + dt2.strftime(\"%Y%m%d%H\")\n + \".png\"\n )\n svg_path = svg_dir / (\n \"hourly_seasonality_\"\n + dt1.strftime(\"%Y%m%d%H\")\n + \"_\"\n + dt2.strftime(\"%Y%m%d%H\")\n + \".svg\"\n )\n\n p3 = figure(title=\"Hourly Seasonality\")\n p3.toolbar.logo = None\n p3.toolbar_location = None\n p3.xaxis.axis_label = \"hour\"\n p3.xaxis.formatter = DatetimeTickFormatter(days=\"%H\", hours=\"%H\")\n p3.xaxis.ticker = bokeh.models.DatetimeTicker()\n p3.line(x=hour_range_plt, y=hs, line_color=\"dodgerblue\", line_width=2)\n export_png(p3, filename=png_path)\n p3.output_backend = \"svg\"\n export_svgs(p3, filename=str(svg_path))\n\n def plot_hourly_acf(\n self, df, target, fdate, tdate, data_dir, png_dir, svg_dir, nlags=24 * 15\n ):\n \"\"\"Plot acf of residuals which removed hourly seasonality\n\n Args:\n df (pandas.DataFrame): DataFrame that holds residuals\n target (str): DataFrame column to compute acf\n fdate (datetime): start date of target range\n tdate (datetime): end date of target range\n data_dir (Path): data path\n png_dir (Path): seasonality plot path (png)\n svg_dir (Path): seasonality plot path (svg)\n nlags (int, optional): number of lags to compute acf.\n Defaults to 15.\n\n Returns:\n None\n \"\"\"\n # hour_range = pd.date_range(\n # start=fdate, end=tdate, freq=\"1H\").tz_convert(SEOULTZ).tolist()\n\n # hr = [df.loc[h, target] -\n # self.sea_hourly[target][hdt2key(h)] for h in hour_range]\n hr = df[(df.index >= fdate) & (df.index <= tdate)][target].to_numpy()\n hr_acf, confint, _, _ = sm.tsa.acf(hr, qstat=True, alpha=0.05, nlags=nlags)\n\n intscale = sum(hr_acf[0 : confint_idx(hr_acf, confint) + 1])\n print(\"Hourly Conf Int : \", confint_idx(hr_acf, confint))\n print(\"Hourly Int Scale : \", intscale)\n # print(\"Hourly qstat : \", qstat)\n # print(\"Hourly pvalues : \", pvalues)\n\n csv_path = data_dir / (\n \"acf_hourly_seasonality_\"\n + fdate.strftime(\"%Y%m%d%H\")\n + \"_\"\n + tdate.strftime(\"%Y%m%d%H\")\n + \".csv\"\n )\n df_hour_acf = pd.DataFrame.from_dict(\n {\"lags\": range(len(hr_acf)), \"hr_acf\": hr_acf}\n )\n df_hour_acf.set_index(\"lags\", inplace=True)\n df_hour_acf.to_csv(csv_path)\n\n png_path = png_dir / (\n \"acf_hourly_seasonality_\"\n + fdate.strftime(\"%Y%m%d%H\")\n + \"_\"\n + tdate.strftime(\"%Y%m%d%H\")\n + \".png\"\n )\n svg_path = svg_dir / (\n \"acf_hourly_seasonality_\"\n + fdate.strftime(\"%Y%m%d%H\")\n + \"_\"\n + tdate.strftime(\"%Y%m%d%H\")\n + \".svg\"\n )\n p3 = figure(title=\"Autocorrelation of Hourly Residual\")\n p3.toolbar.logo = None\n p3.toolbar_location = None\n p3.xaxis.axis_label = \"lags\"\n p3.yaxis.bounds = (min(0, min(hr_acf)), 1.1)\n p3.line(x=range(len(hr_acf)), y=hr_acf, line_color=\"lightcoral\", line_width=2)\n export_png(p3, filename=png_path)\n p3.output_backend = \"svg\"\n export_svgs(p3, filename=str(svg_path))\n\n ## residual autocorrelation by plot_acf\n png_path = png_dir / (\n \"acf(tpl)_hourly_seasonality_\"\n + fdate.strftime(\"%Y%m%d%H\")\n + \"_\"\n + tdate.strftime(\"%Y%m%d%H\")\n + \".png\"\n )\n svg_path = svg_dir / (\n \"acf(tpl)_hourly_seasonality_\"\n + fdate.strftime(\"%Y%m%d%H\")\n + \"_\"\n + tdate.strftime(\"%Y%m%d%H\")\n + \".svg\"\n )\n fig = tpl.plot_acf(hr, lags=nlags)\n fig.savefig(png_path)\n fig.savefig(svg_path)\n\n return confint_idx(hr_acf, confint), intscale\n\n def plot(\n self,\n df,\n target,\n fdate,\n tdate,\n data_dir,\n png_dir,\n svg_dir,\n target_year=2016,\n target_week=10,\n target_month=5,\n target_day=1,\n nlags=7,\n ):\n \"\"\"\n Plot seasonality itself and autocorrelation of residuals\n\n Args:\n df (DataFrame):\n Hourly DataFrame that includes whole data\n target (str):\n column name of DataFrame\n fdate (DateTime):\n acf plot from range between fdate ~ tdate\n tdate (DateTime):\n acf plot from range between fdate ~ tdate\n data_dir (Path):\n Directory location to save csv file\n type(e.g. raw) /\n Simulation name (e.g. MLP) /\n station name (종로구) /\n target name (e.g. PM10) /\n 'seasonality'\n png_dir (Path):\n Directory location to save png file\n type(e.g. raw) /\n Simulation name (e.g. MLP) /\n station name (종로구) /\n target name (e.g. PM10) /\n 'seasonality'\n svg_dir (Path):\n Directory location to save Svg file\n type(e.g. raw) /\n Simulation name (e.g. MLP) /\n station name (종로구) /\n target name (e.g. PM10) /\n 'seasonality'\n target_year (int):\n specified year for plot\n target_week (int):\n specified week number in target_year for plot\n nlags (int):\n nlags for autocorrelation (days)\n\n Return:\n None\n \"\"\"\n\n # filter by dates\n df = df[(df.index > fdate) & (df.index < tdate)]\n # daily averaged\n # df_d = df.resample('D').mean()\n\n df_resid_annual, df_resid_weekly, _, df_resid_hourly = self.compute_seasonality(\n df.loc[:, target], return_resid=True\n )\n df_resid_annual = df_resid_annual.to_frame().rename(columns={\"resid_y\": target})\n df_resid_weekly = df_resid_weekly.to_frame().rename(columns={\"resid_w\": target})\n # df_resid_weekly_pop = df_resid_weekly_pop.to_frame().rename(columns={'resid': target})\n df_resid_hourly = df_resid_hourly.to_frame().rename(columns={\"resid_h\": target})\n\n dict_corr_dist = {}\n\n _, _ = self.plot_raw_acf(\n df,\n target,\n df.index[0],\n df.index[-1],\n data_dir,\n png_dir,\n svg_dir,\n nlags=nlags * 24,\n )\n\n # raw seasonality plot needs to re-compute, so pass original df\n self.plot_annual(\n df,\n target,\n data_dir,\n png_dir,\n svg_dir,\n target_year=2016,\n smoothing=self.smoothing,\n )\n a_confint, a_intscale = self.plot_annual_acf(\n df_resid_annual,\n target,\n df.index[0],\n df.index[-1],\n data_dir,\n png_dir,\n svg_dir,\n nlags=nlags,\n )\n\n # df in weekly and hourly seasonality plot is a just dummy variable\n # to make consistent with other plot methods\n self.plot_weekly(\n target,\n data_dir,\n png_dir,\n svg_dir,\n target_year=target_year,\n target_week=target_week,\n )\n w_confint, w_intscale = self.plot_weekly_acf(\n df_resid_weekly,\n target,\n df.index[0],\n df.index[-1],\n data_dir,\n png_dir,\n svg_dir,\n nlags=nlags,\n )\n\n # df in weekly and hourly seasonality plot is a just dummy variable\n # to make consistent with other plot methods\n self.plot_hourly(\n target,\n data_dir,\n png_dir,\n svg_dir,\n target_year=target_year,\n target_month=target_month,\n target_day=target_day,\n )\n h_confint, h_intscale = self.plot_hourly_acf(\n df_resid_hourly,\n target,\n df.index[0],\n df.index[-1],\n data_dir,\n png_dir,\n svg_dir,\n nlags=nlags * 24,\n )\n\n dict_corr_dist = {\n \"annual\": {\"confint\": a_confint, \"intscale\": a_intscale},\n \"weekly\": {\"confint\": w_confint, \"intscale\": w_intscale},\n \"hourly\": {\"confint\": h_confint, \"intscale\": h_intscale},\n }\n\n with open(data_dir / \"intscale.json\", \"w\") as f:\n print(dict_corr_dist, file=f)\n\n def plot_fused(\n self,\n df,\n target,\n fdate,\n tdate,\n data_dir,\n png_dir,\n svg_dir,\n target_year=2016,\n target_week=10,\n target_month=5,\n target_day=1,\n nlags=15,\n smoothing=True,\n ):\n \"\"\"Plot acf and seasonality for paper\n\n 1. Seasonality Plot : Annual (+Smoothed) & Weekly & Hourly\n 2. ACF Plot : Raw & Residuals (15 days)\n\n Args:\n df (DataFrame):\n Hourly DataFrame that includes whole data\n target (str):\n column name of DataFrame\n fdate (DateTime):\n acf plot from range between fdate ~ tdate\n tdate (DateTime):\n acf plot from range between fdate ~ tdate\n data_dir (Path):\n Directory location to save csv file\n type(e.g. raw) /\n Simulation name (e.g. MLP) /\n station name (종로구) /\n target name (e.g. PM10) /\n 'seasonality'\n png_dir (Path):\n Directory location to save png file\n type(e.g. raw) /\n Simulation name (e.g. MLP) /\n station name (종로구) /\n target name (e.g. PM10) /\n 'seasonality'\n svg_dir (Path):\n Directory location to save Svg file\n type(e.g. raw) /\n Simulation name (e.g. MLP) /\n station name (종로구) /\n target name (e.g. PM10) /\n 'seasonality'\n target_year (int, optional):\n specified year for plot. Defaults to 2016.\n target_week (int, optional):\n specified week number in target_year for plot. Defaults to 10.\n target_month (int, optional):\n specified month in target_year for plot. Defaults to 5.\n target_day (int):\n specified day in target_year for plot. Defaults to 1.\n nlags (int, optional): nlags for autocorrelation (days).\n Defaults to 15.\n smoothing (bool, optional): whether plot smoothed seasonality together.\n Defaults to True.\n\n Returns:\n None\n \"\"\"\n df = df[(df.index > fdate) & (df.index < tdate)]\n # daily averaged\n df_d = df.resample(\"D\").mean()\n\n df_resid_annual, df_resid_weekly, _, df_resid_hourly = self.compute_seasonality(\n df.loc[:, target], return_resid=True\n )\n df_resid_annual = df_resid_annual.to_frame().rename(columns={\"resid_y\": target})\n df_resid_weekly = df_resid_weekly.to_frame().rename(columns={\"resid_w\": target})\n # df_resid_weekly_pop = df_resid_weekly_pop.to_frame().rename(columns={'resid': target})\n df_resid_hourly = df_resid_hourly.to_frame().rename(columns={\"resid_h\": target})\n\n df_resid_annual.to_csv(data_dir / (\"resid_annual.csv\"))\n df_resid_weekly.to_csv(data_dir / (\"resid_weekly.csv\"))\n df_resid_hourly.to_csv(data_dir / (\"resid_hourly.csv\"))\n\n # RAW data\n raws = df[(df.index >= fdate) & (df.index <= tdate)][target].to_numpy()\n df_resid_raw = pd.DataFrame.from_dict({\"date\": df.index, target: df[target]})\n df_resid_raw_d = pd.DataFrame.from_dict(\n {\"date\": df_d.index, target: df_d[target]}\n )\n df_resid_raw.to_csv(data_dir / (\"resid_raw.csv\"))\n df_resid_raw_d.to_csv(data_dir / (\"resid_raw_d.csv\"))\n\n # ANNUAL\n dt1 = dt.datetime(year=target_year, month=1, day=1, hour=0)\n dt2 = dt.datetime(year=target_year, month=12, day=31, hour=23)\n yx = pd.date_range(start=dt1, end=dt2, freq=\"D\", tz=SEOULTZ).tolist()\n # yx_plt = pd.DatetimeIndex([i.replace(tzinfo=None) for i in pd.date_range(\n # start=dt1, end=dt2, freq='D', tz=SEOULTZ)])\n\n ys = [self.sea_annual[target][ydt2key(y)] for y in yx]\n # yr = df_resid_annual[(df_resid_annual.index >= fdate) & (\n # df_resid_annual.index <= tdate)][target].to_numpy()\n if self.smoothing:\n _sea_annual_nonsmooth, _, _ = periodic_mean(\n df_d, target, \"y\", smoothing=False\n )\n # if smoothing, predecomposed seasonality is already smoothed, so redecompose\n ys_vanilla = [_sea_annual_nonsmooth[ydt2key(y)] for y in yx]\n ys_smooth = [self.sea_annual[target][ydt2key(y)] for y in yx]\n\n df_sea_year = pd.DataFrame.from_dict({\"date\": yx, \"ys\": ys})\n if self.smoothing:\n df_sea_year = pd.DataFrame.from_dict(\n {\"date\": yx, \"ys_vanilla\": ys_vanilla, \"ys_smooth\": ys_smooth}\n )\n df_sea_year.to_csv(data_dir / (\"sea_annual.csv\"))\n\n # WEEKLY\n # Set datetime range\n target_dt_str = str(target_year) + \" \" + str(target_week)\n ## ISO 8601 starts weekday from Monday (1)\n dt1 = dt.datetime.strptime(target_dt_str + \" 1\", \"%Y %W %w\")\n ## ISO 8601 ends weekday to Sunday (0)\n dt2 = dt.datetime.strptime(target_dt_str + \" 0\", \"%Y %W %w\")\n ## set dt2 time as Sunday 23:59\n dt2 = dt2.replace(hour=23, minute=59)\n\n wx = pd.date_range(start=dt1, end=dt2, freq=\"D\", tz=SEOULTZ).tolist()\n # wx_plt = pd.DatetimeIndex([i.replace(tzinfo=None) for i in pd.date_range(\n # start=dt1, end=dt2, freq='D', tz=SEOULTZ)])\n\n # Compute Weekly seasonality\n ws = [self.sea_weekly[target][wdt2key(w)] for w in wx]\n # wr = df_resid_weekly[(df_resid_weekly.index >= fdate) \n # & (df_resid_weekly.index <= tdate)][target].to_numpy()\n df_sea_week = pd.DataFrame.from_dict({\"date\": wx, \"ws\": ws})\n df_sea_week.set_index(\"date\", inplace=True)\n df_sea_week.to_csv(data_dir / (\"sea_weekly.csv\"))\n\n # HOURLY\n dt1 = dt.datetime(year=target_year, month=target_month, day=target_day, hour=0)\n dt2 = dt.datetime(year=target_year, month=target_month, day=target_day, hour=23)\n hx = pd.date_range(start=dt1, end=dt2, freq=\"1H\", tz=SEOULTZ).tolist()\n # hx_plt = pd.DatetimeIndex([i.replace(tzinfo=None) for i in pd.date_range(\n # start=dt1, end=dt2, freq='1H', tz=SEOULTZ)]).tolist()\n\n # Compute Hourly seasonality\n hs = [self.sea_hourly[target][hdt2key(h)] for h in hx]\n # hr = df_resid_hourly[(df_resid_hourly.index >= fdate) & \n # (df_resid_hourly.index <= tdate)][target].to_numpy()\n\n df_sea_hour = pd.DataFrame.from_dict({\"date\": hx, \"hs\": hs})\n df_sea_hour.set_index(\"date\", inplace=True)\n df_sea_hour.to_csv(data_dir / (\"sea_hourly.csv\"))\n\n # ingradient\n # raws\n # ys, yr or ys_vanila, ys_smooth, yr\n # ws, wr\n # hs, hr\n\n # set 95% confidance intervals and compute correlation distance(integral length scale)\n def compute_cd(_acfs, _confint):\n # find index where acf value are in confidance interval\n _confint_idx = confint_idx(_acfs, _confint)\n if _confint_idx is None:\n return 0\n else:\n return sum(_acfs[0 : _confint_idx + 1])\n\n raw_acf, raw_confint = tsast.acf(raws, alpha=0.05, nlags=nlags)\n raw_cd = compute_cd(raw_acf, raw_confint) * 24\n df_acf_raw = pd.DataFrame.from_dict(\n {\n \"lags\": list(range(nlags + 1)),\n \"acf\": raw_acf,\n \"confint0\": raw_confint[:, 0],\n \"confint1\": raw_confint[:, 1],\n }\n )\n df_acf_raw.to_csv(data_dir / (\"acf_raw.csv\"))\n yr_acf, yr_confint = tsast.acf(df_resid_annual[target], alpha=0.05, nlags=nlags)\n y_cd = compute_cd(yr_acf, yr_confint) * 24\n df_acf_yr = pd.DataFrame.from_dict(\n {\n \"lags\": list(range(nlags + 1)),\n \"acf\": yr_acf,\n \"confint0\": yr_confint[:, 0],\n \"confint1\": yr_confint[:, 1],\n }\n )\n df_acf_yr.to_csv(data_dir / (\"acf_annual.csv\"))\n wr_acf, wr_confint = tsast.acf(df_resid_weekly[target], alpha=0.05, nlags=nlags)\n w_cd = compute_cd(wr_acf, wr_confint) * 24\n df_acf_wr = pd.DataFrame.from_dict(\n {\n \"lags\": list(range(nlags + 1)),\n \"acf\": wr_acf,\n \"confint0\": wr_confint[:, 0],\n \"confint1\": wr_confint[:, 1],\n }\n )\n df_acf_wr.to_csv(data_dir / (\"acf_weekly.csv\"))\n hr_acf, hr_confint = tsast.acf(\n df_resid_hourly[target], alpha=0.05, nlags=nlags * 24\n )\n h_cd = compute_cd(hr_acf, hr_confint)\n df_acf_hr = pd.DataFrame.from_dict(\n {\n \"lags\": list(range((nlags) * 24 + 1)),\n \"acf\": hr_acf,\n \"confint0\": hr_confint[:, 0],\n \"confint1\": hr_confint[:, 1],\n }\n )\n df_acf_hr.to_csv(data_dir / (\"acf_hourly.csv\"))\n\n print(\"Int scale (raw, annual, weekly, hourly) : \", raw_cd, y_cd, w_cd, h_cd)\n\n sns.color_palette(\"tab10\")\n\n # Plot seasonality (Annual, Weekly, Hourly)\n nrows, ncols = 1, 3\n # rough figure size\n # wspace, hspace = 0.2, 0.2\n # inch/1pt (=1.0inch / 72pt) * 10pt/row * 8row (6 row + margins)\n ax_size = min(7.22 / ncols, 9.45 / nrows)\n # fig_size_w = ax_size*ncols\n # fig_size_h = ax_size*nrows\n\n multipanel_labels = np.array(list(string.ascii_uppercase)[:ncols]).reshape(\n ncols\n )\n\n fig, axs = plt.subplots(\n nrows, ncols, figsize=(ax_size * ncols, ax_size * nrows), dpi=600\n )\n fig.tight_layout(pad=0.15)\n fig.subplots_adjust(left=0.2, bottom=0.2)\n\n # ax[0] == annual seasoanlity\n if smoothing is True:\n sns.lineplot(\n x=\"date\",\n y=\"value\",\n hue=\"variable\",\n data=pd.melt(df_sea_year, [\"date\"]),\n ax=axs[0],\n )\n\n # add legend\n leg_handles, leg_labels = axs[0].get_legend_handles_labels()\n dic = {\"ys_vanilla\": \"vanilla\", \"ys_smooth\": \"smooth\"}\n leg_labels = [dic.get(l, l) for l in leg_labels]\n # remove legend title\n axs[0].legend(\n leg_handles[1:], leg_labels[1:], fancybox=True, fontsize=\"x-small\"\n )\n else:\n sns.lineplot(x=\"date\", y=\"ys\", data=df_sea_year, ax=axs[0], legend=False)\n\n # ax[1] == weekly seasoanlity\n sns.lineplot(data=df_sea_week, ax=axs[1], legend=False)\n # ax[2] == hourly seasoanlity\n sns.lineplot(data=df_sea_hour, ax=axs[2], legend=False)\n\n # mpl.rcParams['timezone'] = SEOULTZ\n\n axs[0].xaxis.set_major_locator(\n mdates.MonthLocator(bymonth=[1, 4, 7, 10], tz=SEOULTZ)\n )\n axs[0].xaxis.set_minor_locator(\n mdates.MonthLocator(bymonth=range(1, 13), tz=SEOULTZ)\n )\n axs[0].xaxis.set_major_formatter(mdates.DateFormatter(\"%m\", tz=SEOULTZ))\n axs[0].set_xlabel(\"a year\", fontsize=\"small\")\n axs[0].set_ylabel(target, fontsize=\"small\")\n axs[1].xaxis.set_major_locator(mdates.HourLocator(byhour=0, tz=SEOULTZ))\n axs[1].xaxis.set_major_formatter(mdates.DateFormatter(\"%a\", tz=SEOULTZ))\n axs[1].set_xlabel(\"a week\", fontsize=\"small\")\n axs[2].xaxis.set_major_locator(\n mdates.HourLocator(byhour=[0, 4, 8, 12, 16, 20], tz=SEOULTZ)\n )\n axs[2].xaxis.set_minor_locator(mdates.HourLocator(tz=SEOULTZ))\n axs[2].xaxis.set_major_formatter(mdates.DateFormatter(\"%H\", tz=SEOULTZ))\n axs[2].set_xlabel(\"a day\", fontsize=\"small\")\n\n for i in range(ncols):\n # axs[i].set_ylabel(target, fontsize='small')\n axs[i].xaxis.grid(True, visible=True, which=\"major\")\n for tick in axs[i].xaxis.get_major_ticks():\n tick.label.set_fontsize(\"x-small\")\n for tick in axs[i].yaxis.get_major_ticks():\n tick.label.set_fontsize(\"x-small\")\n\n axs[i].annotate(\n multipanel_labels[i],\n (-0.13, 1.02),\n xycoords=\"axes fraction\",\n fontsize=\"medium\",\n fontweight=\"bold\",\n )\n output_name = target + \"_fused_seasonality\"\n png_path = png_dir / (output_name + \".png\")\n svg_path = svg_dir / (output_name + \".svg\")\n plt.savefig(png_path, dpi=600)\n plt.savefig(svg_path)\n plt.close()\n\n # Plot ACF (Raw, Hourly Residual)\n nrows, ncols = 1, 2\n # rough figure size\n # wspace, hspace = 0.2, 0.2\n # inch/1pt (=1.0inch / 72pt) * 10pt/row * 8row (6 row + margins)\n ax_size = min(7.22 / ncols, 9.45 / nrows)\n # fig_size_w = ax_size*ncols\n # fig_size_h = ax_size*nrows\n\n multipanel_labels = np.array(list(string.ascii_uppercase)[:ncols]).reshape(\n ncols\n )\n\n fig, axs = plt.subplots(\n nrows, ncols, figsize=(ax_size * ncols, ax_size * nrows), dpi=600\n )\n fig.tight_layout(pad=0.15)\n fig.subplots_adjust(left=0.1, bottom=0.2)\n\n tpl.plot_acf(raws, ax=axs[0], lags=nlags)\n axs[0].set_xlabel(\"day\", fontsize=\"small\")\n axs[0].set_ylabel(\"corr\", fontsize=\"small\")\n tpl.plot_acf(df_resid_hourly[target], ax=axs[1], lags=nlags * 24)\n axs[1].set_xlabel(\"hour\", fontsize=\"small\")\n\n # axs[0].annotate(\"Correlation Distance \\nof Raw Values : \\n\" + '{0:.3g}'.format(raw_cd),\n # (0.65, 0.85), xycoords='axes fraction', fontsize='x-small')\n # axs[1].annotate(\"Correlation Distance \\nof Residuals : \\n\" + '{0:.3g}'.format(h_cd),\n # (0.65, 0.85), xycoords='axes fraction', fontsize='x-small')\n for i in range(2):\n axs[i].annotate(\n multipanel_labels[i],\n (-0.13, 1.05),\n xycoords=\"axes fraction\",\n fontsize=\"medium\",\n fontweight=\"bold\",\n )\n for tick in axs[i].xaxis.get_major_ticks():\n tick.label.set_fontsize(\"x-small\")\n for tick in axs[i].yaxis.get_major_ticks():\n tick.label.set_fontsize(\"x-small\")\n\n output_name = target + \"_fused_acf\"\n png_path = png_dir / (output_name + \".png\")\n svg_path = svg_dir / (output_name + \".svg\")\n plt.savefig(png_path, dpi=600)\n plt.savefig(svg_path)\n plt.close()\n\n df_cd = pd.DataFrame.from_dict(\n {\"raw\": raw_cd, \"y\": y_cd, \"w\": w_cd, \"h\": h_cd}, orient=\"index\"\n )\n df_cd.to_csv(data_dir / (\"correlation_distance.csv\"))\n\n\nclass StandardScalerWrapper(TransformerMixin, BaseEstimator):\n \"\"\"Convert type as Series, not ndarray\"\"\"\n\n def __init__(self, scaler=StandardScaler()):\n self.scaler = scaler\n\n def __getattr__(self, attr):\n return getattr(self.scaler, attr)\n\n def partial_fit(self, X, y=None):\n \"\"\"Call partial_fit method of scaler depends on type of input\n\n Args:\n X (pandas.DataFrame or numpy.ndarray): X\n y (pandas.DataFrame or numpy.ndarray, optional):\n Y. Defaults to None.\n\n Raises:\n TypeError: If X is not pandas.DataFrame or numpy.ndarray\n \"\"\"\n if isinstance(X, pd.DataFrame):\n self.scaler.partial_fit(X, y=X)\n return self\n elif isinstance(X, np.ndarray):\n self.scaler.partial_fit(X, y=X)\n return self\n else:\n raise TypeError(\"Type should be Pandas DataFrame or Numpy Array\")\n\n def fit(self, X, y=None):\n \"\"\"Call fit method of scaler depends on type of input\n\n Args:\n X (pandas.DataFrame or numpy.ndarray): X\n y (pandas.DataFrame or numpy.ndarray, optional):\n Y. Defaults to None.\n\n Raises:\n TypeError: If X is not pandas.DataFrame or numpy.ndarray\n \"\"\"\n if isinstance(X, pd.DataFrame):\n self.scaler.fit(X, y=X)\n return self\n elif isinstance(X, np.ndarray):\n self.scaler.fit(X, y=X)\n return self\n else:\n raise TypeError(\"Type should be Pandas DataFrame or Numpy Array\")\n\n def transform(self, X):\n \"\"\"Call transform method of scaler depends on type of input\n\n Args:\n X (pandas.DataFrame or numpy.ndarray): X\n\n Raises:\n TypeError: If X is not pandas.DataFrame or numpy.ndarray\n \"\"\"\n if isinstance(X, pd.DataFrame):\n return self.scaler.transform(X)\n elif isinstance(X, np.ndarray):\n return self.scaler.transform(X)\n else:\n raise TypeError(\"Type should be Pandas Series or Numpy Array\")\n\n def inverse_transform(self, X):\n \"\"\"Call inverse_transform method of scaler depends on type of input\n\n Args:\n X (pandas.DataFrame or numpy.ndarray): X\n\n Raises:\n TypeError: If X is not pandas.DataFrame or numpy.ndarray\n \"\"\"\n if isinstance(X, pd.DataFrame):\n # return self.scaler.inverse_transform(X.iloc[:, 0].to_numpy().reshape(-1, 1))\n _invX = self.scaler.inverse_transform(X)\n return pd.DataFrame(data=_invX, index=X.index, columns=X.columns)\n elif isinstance(X, np.ndarray):\n return self.scaler.inverse_transform(X)\n else:\n raise TypeError(\"Type should be Pandas DataFrame or Numpy Array\")\n\n\nclass PowerTransformerWrapper(TransformerMixin, BaseEstimator):\n \"\"\"Convert type as Series, not ndarray\"\"\"\n\n def __init__(self, scaler=PowerTransformer()):\n self.scaler = scaler\n\n def __getattr__(self, attr):\n return getattr(self.scaler, attr)\n\n def partial_fit(self, X, y=None):\n \"\"\"Call partial_fit method of scaler depends on type of input\n\n Args:\n X (pandas.DataFrame or numpy.ndarray): X\n y (pandas.DataFrame or numpy.ndarray, optional):\n Y. Defaults to None.\n\n Raises:\n TypeError: If X is not pandas.DataFrame or numpy.ndarray\n \"\"\"\n if isinstance(X, pd.DataFrame):\n self.scaler.partial_fit(X, y=X)\n return self\n elif isinstance(X, np.ndarray):\n self.scaler.partial_fit(X, y=X)\n return self\n else:\n raise TypeError(\"Type should be Pandas DataFrame or Numpy Array\")\n\n def fit(self, X, y=None):\n \"\"\"Call fit method of scaler depends on type of input\n\n Args:\n X (pandas.DataFrame or numpy.ndarray): X\n y (pandas.DataFrame or numpy.ndarray, optional):\n Y. Defaults to None.\n\n Raises:\n TypeError: If X is not pandas.DataFrame or numpy.ndarray\n \"\"\"\n if isinstance(X, pd.DataFrame):\n print(self.scaler.get_params())\n self.scaler.fit(X, y=y)\n return self\n elif isinstance(X, np.ndarray):\n print(self.scaler.get_params())\n self.scaler.fit(X, y=y)\n return self\n else:\n raise TypeError(\"Type should be Pandas DataFrame or Numpy Array\")\n\n def transform(self, X):\n \"\"\"Call transform method of scaler depends on type of input\n\n Args:\n X (pandas.DataFrame or numpy.ndarray): X\n\n Raises:\n TypeError: If X is not pandas.DataFrame or numpy.ndarray\n \"\"\"\n if isinstance(X, pd.DataFrame):\n return self.scaler.transform(X)\n elif isinstance(X, np.ndarray):\n return self.scaler.transform(X)\n else:\n raise TypeError(\"Type should be Pandas DataFrame or Numpy Array\")\n\n def inverse_transform(self, X):\n \"\"\"Call inverse_transform method of scaler depends on type of input\n\n Args:\n X (pandas.DataFrame or numpy.ndarray): X\n\n Raises:\n TypeError: If X is not pandas.DataFrame or numpy.ndarray\n \"\"\"\n if isinstance(X, pd.DataFrame):\n _invX = self.scaler.inverse_transform(X)\n return pd.DataFrame(data=_invX, index=X.index, columns=X.columns)\n elif isinstance(X, np.ndarray):\n return self.scaler.inverse_transform(X)\n else:\n raise TypeError(\"Type should be Pandas DataFrame or Numpy Array\")\n" ]
[ [ "numpy.squeeze", "pandas.DataFrame", "matplotlib.dates.HourLocator", "sklearn.preprocessing.PowerTransformer", "pandas.melt", "sklearn.compose.ColumnTransformer", "pandas.reset_option", "pandas.read_csv", "matplotlib.pyplot.close", "pandas.set_option", "matplotlib.dates.MonthLocator", "matplotlib.pyplot.figure", "matplotlib.dates.DateFormatter", "matplotlib.pyplot.title", "matplotlib.pyplot.savefig", "pandas.date_range", "pandas.DataFrame.from_dict", "matplotlib.pyplot.subplots", "sklearn.preprocessing.StandardScaler" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
statisticalbiotechnology/viewST
[ "9562bcb9bdd039f6e9ba32792432f361fedc5a5a" ]
[ "Experiment/hierarchical_view/Sunburst/hierarchical_generator.py" ]
[ "import pandas as pd\r\nimport numpy as np\r\nimport networkx as nx\r\nfrom networkx.readwrite import json_graph #key package\r\nimport json\r\nimport simplejson\r\n\r\ndata_path=\"C:/Users/Riley/Downloads/Databases\"\r\nrelation_file = data_path + \"/ReactomePathwaysRelation.txt\" #import realtion file\r\ninfile= data_path + \"/Sunburst/Rep1_MOB_info_raw.csv\" #import matrix information file\r\nrel_df = pd.read_csv(relation_file, sep = \"\\t\")\r\noutname = data_path + '/Sunburst' + '/Rep1_MOB_tree.json' #set up output file and path\r\n#before run this, make sure the version of reactome data keep same for both infile\r\n\r\ndef sunburst(infile):\r\n \"\"\"generate hierarchical json file\"\"\"\r\n in_df = pd.read_csv(infile, sep = \"\\t\")\r\n in_df.set_index(in_df[\"pathways\"], inplace=True)\r\n #set up 'pathways' colum as index\r\n in_df = in_df.loc[[x for x in in_df.index if 'HSA' in x]]\r\n topPaths = rel_df.loc[(rel_df['parentId'] == 'HomoSapiens'), 'id']\r\n homoNgenes = np.sum(in_df.loc[[x in topPaths.tolist() for x in in_df[\"pathways\"]],'ngenes'])\r\n homoNode = pd.DataFrame([[\"Homo Sapiens\",1,homoNgenes]], columns = [\"pathways\", \"explained_ratios\", \"ngenes\"]).xs(0)\r\n homoNode.name = 'HomoSapiens'\r\n # add up HomoSapiens info into matrix file (info include:\"pathways\", \"explained_ratios\", \"ngenes\"), and set which as homenode\r\n\r\n in_df = in_df.append(homoNode)\r\n topDict = in_df.to_dict() #set up dictionary as the the key for node tree\r\n pathways = in_df[\"pathways\"]\r\n\r\n subset_vec = [i in pathways for i in rel_df.iloc[:,0]] and [x in pathways for x in rel_df.iloc[:,1]] #filter the pathways in realtion file corelated to those pathways in matrix file.\r\n sub_rel_df = rel_df[subset_vec]\r\n #sub_rel_df.to_csv(\"test.csv\", sep=\"\\t\") #can test if the filter works here\r\n G = nx.DiGraph()\r\n G.add_nodes_from(pathways)\r\n G.add_edges_from(sub_rel_df.values)\r\n tree = nx.algorithms.dag.dag_to_branching(G)\r\n secondDict = nx.get_node_attributes(tree,'source') #set up the value of second dictionary (hierarchical dictionary)\r\n thirdDict = {'explained_ratios':{}, 'ngenes':{}, 'description':{}} #set up the frame of third dictionary\r\n for key, value in secondDict.items():\r\n thirdDict['explained_ratios'].update({key : topDict['explained_ratios'][value]}) #valuation third dictionary with the key value from top dictionary\r\n thirdDict['ngenes'].update({key : topDict['ngenes'][value]})\r\n thirdDict['description'].update({key : topDict['pathways'][value]})\r\n nx.set_node_attributes(tree, thirdDict['explained_ratios'], name = 'explained_ratios')\r\n nx.set_node_attributes(tree, thirdDict['ngenes'], name = 'ngenes')\r\n nx.set_node_attributes(tree, thirdDict['description'], name = 'description')\r\n\r\n\r\n root = [v for v, d in tree.in_degree() if d == 0][0]\r\n out_json = json_graph.tree_data(tree, root)\r\n\r\n with open(outname, 'w') as outfile:\r\n simplejson.dump(out_json,outfile,ignore_nan=True)\r\n\r\n#execute\r\nresult= sunburst(infile)\r\n" ]
[ [ "pandas.read_csv", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
stanleyu911/zipline
[ "93c1a15e7b0269f6b32f54b56982ffb973a5feb3" ]
[ "zipline/utils/run_algo.py" ]
[ "import click\nfrom datetime import datetime\n\nimport os\nimport sys\nimport warnings\n\ntry:\n from pygments import highlight\n from pygments.lexers import PythonLexer\n from pygments.formatters import TerminalFormatter\n\n PYGMENTS = True\nexcept ImportError:\n PYGMENTS = False\nimport logbook\nimport pandas as pd\nimport six\nfrom toolz import concatv\nfrom trading_calendars import get_calendar\n\nfrom zipline.data import bundles\nfrom zipline.data.benchmarks import get_benchmark_returns_from_file\nfrom zipline.data.data_portal import DataPortal\nfrom zipline.finance import metrics\nfrom zipline.finance.trading import SimulationParameters\nfrom zipline.pipeline.data import USEquityPricing\nfrom zipline.pipeline.loaders import USEquityPricingLoader\n\nimport zipline.utils.paths as pth\nfrom zipline.extensions import load\nfrom zipline.errors import SymbolNotFound\nfrom zipline.algorithm import TradingAlgorithm, NoBenchmark\nfrom zipline.finance.blotter import Blotter\n\nlog = logbook.Logger(__name__)\n\n\nclass _RunAlgoError(click.ClickException, ValueError):\n \"\"\"Signal an error that should have a different message if invoked from\n the cli.\n\n Parameters\n ----------\n pyfunc_msg : str\n The message that will be shown when called as a python function.\n cmdline_msg : str, optional\n The message that will be shown on the command line. If not provided,\n this will be the same as ``pyfunc_msg`\n \"\"\"\n exit_code = 1\n\n def __init__(self, pyfunc_msg, cmdline_msg=None):\n if cmdline_msg is None:\n cmdline_msg = pyfunc_msg\n\n super(_RunAlgoError, self).__init__(cmdline_msg)\n self.pyfunc_msg = pyfunc_msg\n\n def __str__(self):\n return self.pyfunc_msg\n\n\ndef _run(handle_data,\n initialize,\n before_trading_start,\n analyze,\n algofile,\n algotext,\n defines,\n data_frequency,\n capital_base,\n bundle,\n bundle_timestamp,\n start,\n end,\n output,\n trading_calendar,\n print_algo,\n metrics_set,\n local_namespace,\n environ,\n blotter,\n benchmark_spec):\n \"\"\"Run a backtest for the given algorithm.\n\n This is shared between the cli and :func:`zipline.run_algo`.\n \"\"\"\n\n bundle_data = bundles.load(\n bundle,\n environ,\n bundle_timestamp,\n )\n\n if trading_calendar is None:\n trading_calendar = get_calendar('XNYS')\n\n # date parameter validation\n if trading_calendar.session_distance(start, end) < 1:\n raise _RunAlgoError(\n 'There are no trading days between %s and %s' % (\n start.date(),\n end.date(),\n ),\n )\n\n benchmark_sid, benchmark_returns = benchmark_spec.resolve(\n asset_finder=bundle_data.asset_finder,\n start_date=start,\n end_date=end,\n )\n\n if algotext is not None:\n if local_namespace:\n ip = get_ipython() # noqa\n namespace = ip.user_ns\n else:\n namespace = {}\n\n for assign in defines:\n try:\n name, value = assign.split('=', 2)\n except ValueError:\n raise ValueError(\n 'invalid define %r, should be of the form name=value' %\n assign,\n )\n try:\n # evaluate in the same namespace so names may refer to\n # eachother\n namespace[name] = eval(value, namespace)\n except Exception as e:\n raise ValueError(\n 'failed to execute definition for name %r: %s' % (name, e),\n )\n elif defines:\n raise _RunAlgoError(\n 'cannot pass define without `algotext`',\n \"cannot pass '-D' / '--define' without '-t' / '--algotext'\",\n )\n else:\n namespace = {}\n if algofile is not None:\n algotext = algofile.read()\n\n if print_algo:\n if PYGMENTS:\n highlight(\n algotext,\n PythonLexer(),\n TerminalFormatter(),\n outfile=sys.stdout,\n )\n else:\n click.echo(algotext)\n\n first_trading_day = \\\n bundle_data.equity_minute_bar_reader.first_trading_day\n\n data = DataPortal(\n bundle_data.asset_finder,\n trading_calendar=trading_calendar,\n first_trading_day=first_trading_day,\n equity_minute_reader=bundle_data.equity_minute_bar_reader,\n equity_daily_reader=bundle_data.equity_daily_bar_reader,\n adjustment_reader=bundle_data.adjustment_reader,\n )\n\n pipeline_loader = USEquityPricingLoader.without_fx(\n bundle_data.equity_daily_bar_reader,\n bundle_data.adjustment_reader,\n )\n\n def choose_loader(column):\n if column in USEquityPricing.columns:\n return pipeline_loader\n raise ValueError(\n \"No PipelineLoader registered for column %s.\" % column\n )\n\n if isinstance(metrics_set, six.string_types):\n try:\n metrics_set = metrics.load(metrics_set)\n except ValueError as e:\n raise _RunAlgoError(str(e))\n\n if isinstance(blotter, six.string_types):\n try:\n blotter = load(Blotter, blotter)\n except ValueError as e:\n raise _RunAlgoError(str(e))\n\n try:\n perf = TradingAlgorithm(\n namespace=namespace,\n data_portal=data,\n get_pipeline_loader=choose_loader,\n trading_calendar=trading_calendar,\n sim_params=SimulationParameters(\n start_session=start,\n end_session=end,\n trading_calendar=trading_calendar,\n capital_base=capital_base,\n data_frequency=data_frequency,\n ),\n metrics_set=metrics_set,\n blotter=blotter,\n benchmark_returns=benchmark_returns,\n benchmark_sid=benchmark_sid,\n **{\n 'initialize': initialize,\n 'handle_data': handle_data,\n 'before_trading_start': before_trading_start,\n 'analyze': analyze,\n } if algotext is None else {\n 'algo_filename': getattr(algofile, 'name', '<algorithm>'),\n 'script': algotext,\n }\n ).run()\n except NoBenchmark:\n raise _RunAlgoError(\n (\n 'No ``benchmark_spec`` was provided, and'\n ' ``zipline.api.set_benchmark`` was not called in'\n ' ``initialize``.'\n ),\n (\n \"Neither '--benchmark-symbol' nor '--benchmark-sid' was\"\n \" provided, and ``zipline.api.set_benchmark`` was not called\"\n \" in ``initialize``. Did you mean to pass '--no-benchmark'?\"\n ),\n )\n\n if output == '-':\n click.echo(str(perf))\n elif output != os.devnull: # make the zipline magic not write any data\n perf.to_pickle(output)\n\n return perf\n\n\n# All of the loaded extensions. We don't want to load an extension twice.\n_loaded_extensions = set()\n\n\ndef load_extensions(default, extensions, strict, environ, reload=False):\n \"\"\"Load all of the given extensions. This should be called by run_algo\n or the cli.\n\n Parameters\n ----------\n default : bool\n Load the default exension (~/.zipline/extension.py)?\n extension : iterable[str]\n The paths to the extensions to load. If the path ends in ``.py`` it is\n treated as a script and executed. If it does not end in ``.py`` it is\n treated as a module to be imported.\n strict : bool\n Should failure to load an extension raise. If this is false it will\n still warn.\n environ : mapping\n The environment to use to find the default extension path.\n reload : bool, optional\n Reload any extensions that have already been loaded.\n \"\"\"\n if default:\n default_extension_path = pth.default_extension(environ=environ)\n pth.ensure_file(default_extension_path)\n # put the default extension first so other extensions can depend on\n # the order they are loaded\n extensions = concatv([default_extension_path], extensions)\n\n for ext in extensions:\n if ext in _loaded_extensions and not reload:\n continue\n try:\n # load all of the zipline extensionss\n if ext.endswith('.py'):\n with open(ext) as f:\n ns = {}\n six.exec_(compile(f.read(), ext, 'exec'), ns, ns)\n else:\n __import__(ext)\n except Exception as e:\n if strict:\n # if `strict` we should raise the actual exception and fail\n raise\n # without `strict` we should just log the failure\n warnings.warn(\n 'Failed to load extension: %r\\n%s' % (ext, e),\n stacklevel=2\n )\n else:\n _loaded_extensions.add(ext)\n\n\ndef run_algorithm(start,\n end,\n initialize,\n capital_base,\n handle_data=None,\n before_trading_start=None,\n analyze=None,\n data_frequency='daily',\n bundle='quantopian-quandl',\n bundle_timestamp=None,\n trading_calendar=None,\n metrics_set='default',\n benchmark_returns=None,\n default_extension=True,\n extensions=(),\n strict_extensions=True,\n environ=os.environ,\n blotter='default'):\n \"\"\"\n Run a trading algorithm.\n\n Parameters\n ----------\n start : datetime\n The start date of the backtest.\n end : datetime\n The end date of the backtest..\n initialize : callable[context -> None]\n The initialize function to use for the algorithm. This is called once\n at the very begining of the backtest and should be used to set up\n any state needed by the algorithm.\n capital_base : float\n The starting capital for the backtest.\n handle_data : callable[(context, BarData) -> None], optional\n The handle_data function to use for the algorithm. This is called\n every minute when ``data_frequency == 'minute'`` or every day\n when ``data_frequency == 'daily'``.\n before_trading_start : callable[(context, BarData) -> None], optional\n The before_trading_start function for the algorithm. This is called\n once before each trading day (after initialize on the first day).\n analyze : callable[(context, pd.DataFrame) -> None], optional\n The analyze function to use for the algorithm. This function is called\n once at the end of the backtest and is passed the context and the\n performance data.\n data_frequency : {'daily', 'minute'}, optional\n The data frequency to run the algorithm at.\n bundle : str, optional\n The name of the data bundle to use to load the data to run the backtest\n with. This defaults to 'quantopian-quandl'.\n bundle_timestamp : datetime, optional\n The datetime to lookup the bundle data for. This defaults to the\n current time.\n trading_calendar : TradingCalendar, optional\n The trading calendar to use for your backtest.\n metrics_set : iterable[Metric] or str, optional\n The set of metrics to compute in the simulation. If a string is passed,\n resolve the set with :func:`zipline.finance.metrics.load`.\n benchmark_returns : pd.Series, optional\n Series of returns to use as the benchmark.\n default_extension : bool, optional\n Should the default zipline extension be loaded. This is found at\n ``$ZIPLINE_ROOT/extension.py``\n extensions : iterable[str], optional\n The names of any other extensions to load. Each element may either be\n a dotted module path like ``a.b.c`` or a path to a python file ending\n in ``.py`` like ``a/b/c.py``.\n strict_extensions : bool, optional\n Should the run fail if any extensions fail to load. If this is false,\n a warning will be raised instead.\n environ : mapping[str -> str], optional\n The os environment to use. Many extensions use this to get parameters.\n This defaults to ``os.environ``.\n blotter : str or zipline.finance.blotter.Blotter, optional\n Blotter to use with this algorithm. If passed as a string, we look for\n a blotter construction function registered with\n ``zipline.extensions.register`` and call it with no parameters.\n Default is a :class:`zipline.finance.blotter.SimulationBlotter` that\n never cancels orders.\n\n Returns\n -------\n perf : pd.DataFrame\n The daily performance of the algorithm.\n\n See Also\n --------\n zipline.data.bundles.bundles : The available data bundles.\n \"\"\"\n load_extensions(default_extension, extensions, strict_extensions, environ)\n\n if type(start) is datetime:\n log.warn(\"Changing start-date from datetime to pandas Timestamp\",\n \"Consider changing this in your code in the future.\")\n start = pd.Timestamp(start)\n\n if type(end) is datetime:\n log.warn(\"Changing end-date from datetime to pandas Timestamp\",\n \"Consider changing this in your code in the future.\")\n end = pd.Timestamp(end)\n\n if benchmark_returns is None:\n log.warn(\"Benchmark returns not inserted, using NYSE.\")\n cal = get_calendar('NYSE')\n first_date = datetime(1930, 1, 1)\n last_date = datetime(2030, 1, 1)\n dates = cal.sessions_in_range(first_date, last_date)\n data = pd.DataFrame(0.0, index=dates, columns=['close'])\n data = data['close']\n benchmark_returns = data.sort_index().iloc[1:]\n\n benchmark_spec = BenchmarkSpec.from_returns(benchmark_returns)\n\n return _run(\n handle_data=handle_data,\n initialize=initialize,\n before_trading_start=before_trading_start,\n analyze=analyze,\n algofile=None,\n algotext=None,\n defines=(),\n data_frequency=data_frequency,\n capital_base=capital_base,\n bundle=bundle,\n bundle_timestamp=bundle_timestamp,\n start=start,\n end=end,\n output=os.devnull,\n trading_calendar=trading_calendar,\n print_algo=False,\n metrics_set=metrics_set,\n local_namespace=False,\n environ=environ,\n blotter=blotter,\n benchmark_spec=benchmark_spec,\n )\n\n\nclass BenchmarkSpec(object):\n \"\"\"\n Helper for different ways we can get benchmark data for the Zipline CLI and\n zipline.utils.run_algo.run_algorithm.\n\n Parameters\n ----------\n benchmark_returns : pd.Series, optional\n Series of returns to use as the benchmark.\n benchmark_file : str or file\n File containing a csv with `date` and `return` columns, to be read as\n the benchmark.\n benchmark_sid : int, optional\n Sid of the asset to use as a benchmark.\n benchmark_symbol : str, optional\n Symbol of the asset to use as a benchmark. Symbol will be looked up as\n of the end date of the backtest.\n no_benchmark : bool\n Flag indicating that no benchmark is configured. Benchmark-dependent\n metrics will be calculated using a dummy benchmark of all-zero returns.\n \"\"\"\n\n def __init__(self,\n benchmark_returns,\n benchmark_file,\n benchmark_sid,\n benchmark_symbol,\n no_benchmark):\n\n self.benchmark_returns = benchmark_returns\n self.benchmark_file = benchmark_file\n self.benchmark_sid = benchmark_sid\n self.benchmark_symbol = benchmark_symbol\n self.no_benchmark = no_benchmark\n\n @classmethod\n def from_cli_params(cls,\n benchmark_sid,\n benchmark_symbol,\n benchmark_file,\n no_benchmark):\n\n return cls(\n benchmark_returns=None,\n benchmark_sid=benchmark_sid,\n benchmark_symbol=benchmark_symbol,\n benchmark_file=benchmark_file,\n no_benchmark=no_benchmark,\n )\n\n @classmethod\n def from_returns(cls, benchmark_returns):\n return cls(\n benchmark_returns=benchmark_returns,\n benchmark_file=None,\n benchmark_sid=None,\n benchmark_symbol=None,\n no_benchmark=benchmark_returns is None,\n )\n\n def resolve(self, asset_finder, start_date, end_date):\n \"\"\"\n Resolve inputs into values to be passed to TradingAlgorithm.\n\n Returns a pair of ``(benchmark_sid, benchmark_returns)`` with at most\n one non-None value. Both values may be None if no benchmark source has\n been configured.\n\n Parameters\n ----------\n asset_finder : zipline.assets.AssetFinder\n Asset finder for the algorithm to be run.\n start_date : pd.Timestamp\n Start date of the algorithm to be run.\n end_date : pd.Timestamp\n End date of the algorithm to be run.\n\n Returns\n -------\n benchmark_sid : int\n Sid to use as benchmark.\n benchmark_returns : pd.Series\n Series of returns to use as benchmark.\n \"\"\"\n if self.benchmark_returns is not None:\n benchmark_sid = None\n benchmark_returns = self.benchmark_returns\n elif self.benchmark_file is not None:\n benchmark_sid = None\n benchmark_returns = get_benchmark_returns_from_file(\n self.benchmark_file,\n )\n elif self.benchmark_sid is not None:\n benchmark_sid = self.benchmark_sid\n benchmark_returns = None\n elif self.benchmark_symbol is not None:\n try:\n asset = asset_finder.lookup_symbol(\n self.benchmark_symbol,\n as_of_date=end_date,\n )\n benchmark_sid = asset.sid\n benchmark_returns = None\n except SymbolNotFound:\n raise _RunAlgoError(\n \"Symbol %r as a benchmark not found in this bundle.\"\n % self.benchmark_symbol\n )\n elif self.no_benchmark:\n benchmark_sid = None\n benchmark_returns = self._zero_benchmark_returns(\n start_date=start_date,\n end_date=end_date,\n )\n else:\n log.warn(\n \"No benchmark configured. \"\n \"Assuming algorithm calls set_benchmark.\"\n )\n log.warn(\n \"Pass --benchmark-sid, --benchmark-symbol, or\"\n \" --benchmark-file to set a source of benchmark returns.\"\n )\n log.warn(\n \"Pass --no-benchmark to use a dummy benchmark \"\n \"of zero returns.\",\n )\n benchmark_sid = None\n benchmark_returns = None\n\n return benchmark_sid, benchmark_returns\n\n @staticmethod\n def _zero_benchmark_returns(start_date, end_date):\n return pd.Series(\n index=pd.date_range(start_date, end_date, tz='utc'),\n data=0.0,\n )\n" ]
[ [ "pandas.Timestamp", "pandas.DataFrame", "pandas.date_range" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
shouwangzhe134/Decoupled-R-CNN
[ "7fee5bef6c52a79636f61cfe48babfaf3e4fc088" ]
[ "mmdet/models/roi_heads/bbox_heads/bbox_head.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.modules.utils import _pair\n\nfrom mmdet.core import (auto_fp16, build_bbox_coder, force_fp32, multi_apply,\n multiclass_nms)\nfrom mmdet.models.builder import HEADS, build_loss\nfrom mmdet.models.losses import accuracy\n\n\[email protected]_module()\nclass BBoxHead(nn.Module):\n \"\"\"Simplest RoI head, with only two fc layers for classification and\n regression respectively.\"\"\"\n\n def __init__(self,\n with_avg_pool=False,\n with_cls=True,\n with_reg=True,\n roi_feat_size=7,\n in_channels=256,\n num_classes=80,\n bbox_coder=dict(\n type='DeltaXYWHBBoxCoder',\n target_means=[0., 0., 0., 0.],\n target_stds=[0.1, 0.1, 0.2, 0.2]),\n reg_class_agnostic=False,\n reg_decoded_bbox=False,\n loss_cls=dict(\n type='CrossEntropyLoss',\n use_sigmoid=False,\n loss_weight=1.0),\n loss_bbox=dict(\n type='SmoothL1Loss', beta=1.0, loss_weight=1.0)):\n super(BBoxHead, self).__init__()\n assert with_cls or with_reg\n self.with_avg_pool = with_avg_pool\n self.with_cls = with_cls\n self.with_reg = with_reg\n self.roi_feat_size = _pair(roi_feat_size)\n self.roi_feat_area = self.roi_feat_size[0] * self.roi_feat_size[1]\n self.in_channels = in_channels\n self.num_classes = num_classes\n self.reg_class_agnostic = reg_class_agnostic\n self.reg_decoded_bbox = reg_decoded_bbox\n self.fp16_enabled = False\n\n self.bbox_coder = build_bbox_coder(bbox_coder)\n self.loss_cls = build_loss(loss_cls)\n self.loss_bbox = build_loss(loss_bbox)\n\n in_channels = self.in_channels\n if self.with_avg_pool:\n self.avg_pool = nn.AvgPool2d(self.roi_feat_size)\n else:\n in_channels *= self.roi_feat_area\n if self.with_cls:\n # need to add background class\n self.fc_cls = nn.Linear(in_channels, num_classes + 1)\n if self.with_reg:\n out_dim_reg = 4 if reg_class_agnostic else 4 * num_classes\n self.fc_reg = nn.Linear(in_channels, out_dim_reg)\n self.debug_imgs = None\n\n def init_weights(self):\n # conv layers are already initialized by ConvModule\n if self.with_cls:\n nn.init.normal_(self.fc_cls.weight, 0, 0.01)\n nn.init.constant_(self.fc_cls.bias, 0)\n if self.with_reg:\n nn.init.normal_(self.fc_reg.weight, 0, 0.001)\n nn.init.constant_(self.fc_reg.bias, 0)\n\n @auto_fp16()\n def forward(self, x):\n if self.with_avg_pool:\n x = self.avg_pool(x)\n x = x.view(x.size(0), -1)\n cls_score = self.fc_cls(x) if self.with_cls else None\n bbox_pred = self.fc_reg(x) if self.with_reg else None\n return cls_score, bbox_pred\n\n def _get_target_single(self, pos_bboxes, neg_bboxes, pos_gt_bboxes,\n pos_gt_labels, cfg):\n num_pos = pos_bboxes.size(0)\n num_neg = neg_bboxes.size(0)\n num_samples = num_pos + num_neg\n\n # original implementation uses new_zeros since BG are set to be 0\n # now use empty & fill because BG cat_id = num_classes,\n # FG cat_id = [0, num_classes-1]\n labels = pos_bboxes.new_full((num_samples, ),\n self.num_classes,\n dtype=torch.long)\n label_weights = pos_bboxes.new_zeros(num_samples)\n bbox_targets = pos_bboxes.new_zeros(num_samples, 4)\n bbox_weights = pos_bboxes.new_zeros(num_samples, 4)\n if num_pos > 0:\n labels[:num_pos] = pos_gt_labels\n pos_weight = 1.0 if cfg.pos_weight <= 0 else cfg.pos_weight\n label_weights[:num_pos] = pos_weight\n if not self.reg_decoded_bbox:\n pos_bbox_targets = self.bbox_coder.encode(\n pos_bboxes, pos_gt_bboxes)\n else:\n pos_bbox_targets = pos_gt_bboxes\n bbox_targets[:num_pos, :] = pos_bbox_targets\n bbox_weights[:num_pos, :] = 1\n if num_neg > 0:\n label_weights[-num_neg:] = 1.0\n\n return labels, label_weights, bbox_targets, bbox_weights\n\n def get_targets(self,\n sampling_results,\n gt_bboxes,\n gt_labels,\n rcnn_train_cfg,\n concat=True):\n pos_bboxes_list = [res.pos_bboxes for res in sampling_results]\n neg_bboxes_list = [res.neg_bboxes for res in sampling_results]\n pos_gt_bboxes_list = [res.pos_gt_bboxes for res in sampling_results]\n pos_gt_labels_list = [res.pos_gt_labels for res in sampling_results]\n labels, label_weights, bbox_targets, bbox_weights = multi_apply(\n self._get_target_single,\n pos_bboxes_list,\n neg_bboxes_list,\n pos_gt_bboxes_list,\n pos_gt_labels_list,\n cfg=rcnn_train_cfg)\n\n if concat:\n labels = torch.cat(labels, 0)\n label_weights = torch.cat(label_weights, 0)\n bbox_targets = torch.cat(bbox_targets, 0)\n bbox_weights = torch.cat(bbox_weights, 0)\n return labels, label_weights, bbox_targets, bbox_weights\n\n @force_fp32(apply_to=('cls_score', 'bbox_pred'))\n def loss(self,\n cls_score,\n bbox_pred,\n rois,\n labels,\n label_weights,\n bbox_targets,\n bbox_weights,\n reduction_override=None):\n losses = dict()\n if cls_score is not None:\n avg_factor = max(torch.sum(label_weights > 0).float().item(), 1.)\n if cls_score.numel() > 0:\n losses['loss_cls'] = self.loss_cls(\n cls_score,\n labels,\n label_weights,\n avg_factor=avg_factor,\n reduction_override=reduction_override)\n losses['acc'] = accuracy(cls_score, labels)\n if bbox_pred is not None:\n bg_class_ind = self.num_classes\n # 0~self.num_classes-1 are FG, self.num_classes is BG\n pos_inds = (labels >= 0) & (labels < bg_class_ind)\n # do not perform bounding box regression for BG anymore.\n if pos_inds.any():\n if self.reg_decoded_bbox:\n bbox_pred = self.bbox_coder.decode(rois[:, 1:], bbox_pred)\n if self.reg_class_agnostic:\n pos_bbox_pred = bbox_pred.view(\n bbox_pred.size(0), 4)[pos_inds.type(torch.bool)]\n else:\n pos_bbox_pred = bbox_pred.view(\n bbox_pred.size(0), -1,\n 4)[pos_inds.type(torch.bool),\n labels[pos_inds.type(torch.bool)]]\n losses['loss_bbox'] = self.loss_bbox(\n pos_bbox_pred,\n bbox_targets[pos_inds.type(torch.bool)],\n bbox_weights[pos_inds.type(torch.bool)],\n avg_factor=bbox_targets.size(0),\n reduction_override=reduction_override)\n else:\n losses['loss_bbox'] = bbox_pred.sum() * 0\n return losses\n\n @force_fp32(apply_to=('cls_score', 'bbox_pred'))\n def get_bboxes(self,\n rois,\n cls_score,\n bbox_pred,\n img_shape,\n scale_factor,\n rescale=False,\n cfg=None):\n if isinstance(cls_score, list):\n cls_score = sum(cls_score) / float(len(cls_score))\n scores = F.softmax(cls_score, dim=1) if cls_score is not None else None\n\n if bbox_pred is not None:\n bboxes = self.bbox_coder.decode(\n rois[:, 1:], bbox_pred, max_shape=img_shape)\n else:\n bboxes = rois[:, 1:].clone()\n if img_shape is not None:\n bboxes[:, [0, 2]].clamp_(min=0, max=img_shape[1])\n bboxes[:, [1, 3]].clamp_(min=0, max=img_shape[0])\n\n if rescale and bboxes.size(0) > 0:\n if isinstance(scale_factor, float):\n bboxes /= scale_factor\n else:\n scale_factor = bboxes.new_tensor(scale_factor)\n bboxes = (bboxes.view(bboxes.size(0), -1, 4) /\n scale_factor).view(bboxes.size()[0], -1)\n\n if cfg is None:\n return bboxes, scores\n else:\n det_bboxes, det_labels = multiclass_nms(bboxes, scores,\n cfg.score_thr, cfg.nms,\n cfg.max_per_img)\n\n return det_bboxes, det_labels\n\n @force_fp32(apply_to=('bbox_preds', ))\n def refine_bboxes(self, rois, labels, bbox_preds, pos_is_gts, img_metas):\n \"\"\"Refine bboxes during training.\n\n Args:\n rois (Tensor): Shape (n*bs, 5), where n is image number per GPU,\n and bs is the sampled RoIs per image. The first column is\n the image id and the next 4 columns are x1, y1, x2, y2.\n labels (Tensor): Shape (n*bs, ).\n bbox_preds (Tensor): Shape (n*bs, 4) or (n*bs, 4*#class).\n pos_is_gts (list[Tensor]): Flags indicating if each positive bbox\n is a gt bbox.\n img_metas (list[dict]): Meta info of each image.\n\n Returns:\n list[Tensor]: Refined bboxes of each image in a mini-batch.\n\n Example:\n >>> # xdoctest: +REQUIRES(module:kwarray)\n >>> import kwarray\n >>> import numpy as np\n >>> from mmdet.core.bbox.demodata import random_boxes\n >>> self = BBoxHead(reg_class_agnostic=True)\n >>> n_roi = 2\n >>> n_img = 4\n >>> scale = 512\n >>> rng = np.random.RandomState(0)\n >>> img_metas = [{'img_shape': (scale, scale)}\n ... for _ in range(n_img)]\n >>> # Create rois in the expected format\n >>> roi_boxes = random_boxes(n_roi, scale=scale, rng=rng)\n >>> img_ids = torch.randint(0, n_img, (n_roi,))\n >>> img_ids = img_ids.float()\n >>> rois = torch.cat([img_ids[:, None], roi_boxes], dim=1)\n >>> # Create other args\n >>> labels = torch.randint(0, 2, (n_roi,)).long()\n >>> bbox_preds = random_boxes(n_roi, scale=scale, rng=rng)\n >>> # For each image, pretend random positive boxes are gts\n >>> is_label_pos = (labels.numpy() > 0).astype(np.int)\n >>> lbl_per_img = kwarray.group_items(is_label_pos,\n ... img_ids.numpy())\n >>> pos_per_img = [sum(lbl_per_img.get(gid, []))\n ... for gid in range(n_img)]\n >>> pos_is_gts = [\n >>> torch.randint(0, 2, (npos,)).byte().sort(\n >>> descending=True)[0]\n >>> for npos in pos_per_img\n >>> ]\n >>> bboxes_list = self.refine_bboxes(rois, labels, bbox_preds,\n >>> pos_is_gts, img_metas)\n >>> print(bboxes_list)\n \"\"\"\n img_ids = rois[:, 0].long().unique(sorted=True)\n assert img_ids.numel() <= len(img_metas)\n\n bboxes_list = []\n for i in range(len(img_metas)):\n inds = torch.nonzero(\n rois[:, 0] == i, as_tuple=False).squeeze(dim=1)\n num_rois = inds.numel()\n\n bboxes_ = rois[inds, 1:]\n label_ = labels[inds]\n bbox_pred_ = bbox_preds[inds]\n img_meta_ = img_metas[i]\n pos_is_gts_ = pos_is_gts[i]\n\n bboxes = self.regress_by_class(bboxes_, label_, bbox_pred_,\n img_meta_)\n\n # filter gt bboxes\n pos_keep = 1 - pos_is_gts_\n keep_inds = pos_is_gts_.new_ones(num_rois)\n keep_inds[:len(pos_is_gts_)] = pos_keep\n\n bboxes_list.append(bboxes[keep_inds.type(torch.bool)])\n\n return bboxes_list\n\n @force_fp32(apply_to=('bbox_pred', ))\n def regress_by_class(self, rois, label, bbox_pred, img_meta):\n \"\"\"Regress the bbox for the predicted class. Used in Cascade R-CNN.\n\n Args:\n rois (Tensor): shape (n, 4) or (n, 5)\n label (Tensor): shape (n, )\n bbox_pred (Tensor): shape (n, 4*(#class)) or (n, 4)\n img_meta (dict): Image meta info.\n\n Returns:\n Tensor: Regressed bboxes, the same shape as input rois.\n \"\"\"\n assert rois.size(1) == 4 or rois.size(1) == 5, repr(rois.shape)\n\n if not self.reg_class_agnostic:\n label = label * 4\n inds = torch.stack((label, label + 1, label + 2, label + 3), 1)\n bbox_pred = torch.gather(bbox_pred, 1, inds)\n assert bbox_pred.size(1) == 4\n\n if rois.size(1) == 4:\n new_rois = self.bbox_coder.decode(\n rois, bbox_pred, max_shape=img_meta['img_shape'])\n else:\n bboxes = self.bbox_coder.decode(\n rois[:, 1:], bbox_pred, max_shape=img_meta['img_shape'])\n new_rois = torch.cat((rois[:, [0]], bboxes), dim=1)\n\n return new_rois\n\n @force_fp32(apply_to=('bbox_preds', ))\n def refine_pos_bboxes(self, rois, roi_labels, labels, bbox_preds, img_metas):\n img_ids = rois[:, 0].long().unique(sorted=True)\n assert img_ids.numel() <= len(img_metas)\n\n bboxes_list = []\n for i in range(len(img_metas)):\n inds = torch.nonzero(rois[:, 0] == i, as_tuple=False).squeeze(dim=1)\n #num_rois = inds.numel()\n\n bboxes_ = rois[inds, 1:]\n if roi_labels is None:\n roi_label_ = None\n else:\n roi_label_ = roi_labels[inds]\n label_ = labels[inds]\n bbox_pred_ = bbox_preds[inds]\n img_meta_ = img_metas[i]\n\n bboxes = self.regress_pos_by_class(bboxes_, roi_label_, label_, bbox_pred_, img_meta_)\n bboxes_list.append(bboxes)\n return bboxes_list\n\n @force_fp32(apply_to=('bbox_pred', ))\n def regress_pos_by_class(self, rois, roi_label, label, bbox_pred, img_meta):\n assert rois.size(1) == 4 or rois.size(1) == 5, repr(rois.shape)\n\n if not self.reg_class_agnostic:\n label_ = roi_label * 4\n inds = torch.stack((label_, label_ + 1, label_ + 2, label_ + 3), 1)\n bbox_pred = torch.gather(bbox_pred, 1, inds)\n assert bbox_pred.size(1) == 4\n \n pos_inds = (label >= 0) & (label < self.num_classes)\n neg_inds = (label == self.num_classes)\n if rois.size(1) == 4:\n new_rois_pos = self.bbox_coder.decode(\n rois[pos_inds.type(torch.bool)], bbox_pred[pos_inds.type(torch.bool)], \n max_shape=img_meta['img_shape']\n )\n else:\n bboxes = self.bbox_coder.decode(\n rois[pos_inds.type(torch.bool), 1:], bbox_pred[pos_inds.type(torch.bool)],\n img_shape=img_meta['img_shape']\n )\n new_rois_pos = torch.cat((rois[pos_inds.type(torch.bool), [0]], bboxes), dim=1)\n new_rois = torch.cat((new_rois_pos, rois[neg_inds.type(torch.bool)]), dim=0)\n \n return new_rois\n\n" ]
[ [ "torch.nn.functional.softmax", "torch.cat", "torch.nn.init.constant_", "torch.gather", "torch.sum", "torch.nn.Linear", "torch.nn.AvgPool2d", "torch.nn.init.normal_", "torch.nonzero", "torch.nn.modules.utils._pair", "torch.stack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ignaciochr/purchase_optimizer
[ "be582430461e5071e7a451e7edfbc5d666eb50b1" ]
[ "YaEsta.com+optimizer.py" ]
[ "# coding: utf-8\n# YaEsta.com purchase optimizer\n\nimport requests\nimport bs4\nSoup = bs4.BeautifulSoup\nimport csv\nimport re\nimport pandas as pd\nimport numpy as np\nimport math\nfrom itertools import combinations\n\n# Importing website HTML data to be parsed\n# To parse local HTML files\nwith open(r'C:/Users/ignacio.chavarria/Desktop/Scraping/aaa.html', \"r\") as f:\n content = f.read()\n\n# To parse from web\n#response = requests.get(\"http://dataquestio.github.io/web-scraping-pages/2014_super_bowl.html\")\n#content = response.content\n\nwith open(r\"C:\\Users\\ignacio.chavarria\\Desktop\\Scraping\\YaEsta\\drinks.html\", encoding=\"utf8\") as f:\n content_d = f.read()\n \nwith open(r\"C:\\Users\\ignacio.chavarria\\Desktop\\Scraping\\YaEsta\\snacks.html\", \"r\", encoding=\"utf8\") as f:\n content_s = f.read()\n\nwith open(r\"C:\\Users\\ignacio.chavarria\\Desktop\\Scraping\\YaEsta\\chocolates.html\", \"r\", encoding=\"utf8\") as f:\n content_c = f.read()\n\np_d = Soup(content_d, 'html.parser')\np_s = Soup(content_s, 'html.parser')\np_c = Soup(content_c, 'html.parser')\n\n# Parsing titles and prices:\nparsers = [p_d, p_s, p_c]\n\ndef cat_name(n):\n if n == 0:\n return \"drink\"\n elif n == 1:\n return \"snack\"\n elif n == 2:\n return \"chocolate\"\n\nnames = []\nprices = []\ncategories = []\nct = 0\n\nfor parser in parsers:\n #Get product names\n names_raw = parser.select(\".productName\")\n for i in names_raw:\n names.append(i.text)\n\n #Get product prices\n prices_raw = parser.select(\".prices\")\n for i in prices_raw:\n if len(i) == 3:\n prices.append(float((i.text)[3:]))\n elif len(i) == 5:\n prices.append(float((i.find_all(\"span\")[1].text)[1:]))\n\n #Get product categories\n cats = [ cat_name(ct) for i in range((len(categories)), len(prices))]\n for i in cats:\n categories.append(i)\n ct += 1\n\n#Create dataframe\ndf = pd.DataFrame(\n {'name': names[:-9],\n 'category': categories,\n 'price': prices\n })\n\ndef amount(i):\n if re.findall('[ ]([0-9\\,\\.]+)(?=\\s*[mMgG]([ lLrR\\.]|\\Z)([ \\.]|\\Z))', i):\n test2 = re.findall('[ ]([0-9\\,\\.]+)(?=\\s*[mMgG]([ lLrR\\.]|\\Z)([ \\.]|\\Z))', i)\n else:\n test2 = re.findall('[ ]([0-9\\,\\.]+)(?=\\s*[mMgG]([ lLrR\\.]|\\Z))', i)\n\n if test2:\n return float(test2[0][0].replace(\",\", \".\"))\n else:\n return math.nan\n\ndf['amount'] = df['name'].apply(lambda x: amount(x))\ndf = df.dropna(subset=['amount']).reset_index(drop=True)\ndf.shape\ndf['amount_per_dollar'] = df['amount'] / df['price']\ndf['idx'] = df.index\n\n# Define gift card amount\ngc = 5\n\ndf = df[df['price'] <= gc]\ndf.shape\n\ndf_c = df.loc[df['category'] == 'chocolate', :].sort_values('amount_per_dollar', ascending=[False])\ndf_d = df.loc[df['category'] == 'drink', :].sort_values('amount_per_dollar', ascending=[False])\ndf_s = df.loc[df['category'] == 'snack', :].sort_values('amount_per_dollar', ascending=[False])\n\ndf_s1 = df_s.iloc[:10].sort_values('price', ascending=True)\ndf_d1 = df_d.iloc[:10].sort_values('price', ascending=True)\ndf_c1 = df_c.iloc[:10].sort_values('price', ascending=True)\n\ndfs = [df_s1, df_d1, df_c1]\n\n#Create dictionary with K values for computing combinations per df\nd = {}\nfor n in range(len(dfs)):\n products = 0\n total = 0\n for i in range(dfs[n].shape[0]):\n if dfs[n].price.iloc[i] <= gc:\n total += dfs[n].price.iloc[i]\n if total >= gc:\n break\n products += 1\n else:\n break\n d[n] = int(products)\n\n#Find top combinations per segment\ntop = {}\n\nfor y in range(len(dfs)): \n combination_id = {}\n ti, tp, ta = [],[],[]\n\n for k in range(1, d[y] + 1):\n ti += list(combinations(dfs[y].idx, k))\n tp += list(combinations(dfs[y].price, k))\n ta += list(combinations(dfs[y].amount, k))\n\n for i in range(len(ti)):\n if sum(tp[i]) <= gc:\n combination_id[i] = []\n combination_id[i].append(list(ti[i]))\n combination_id[i].append(sum(tp[i]))\n combination_id[i].append(sum(ta[i]))\n\n top[y] = sorted(combination_id.items(), key=lambda x: x[1][2], reverse=True)[0][1:]\n\ntop\n\nlabels = [\"'snack'\", \"'drink'\", \"'candy'\"]\n\ndef gr_or_ml(category):\n if category == \"'drink'\":\n return \"Total milliliters:\"\n else:\n return \"Total grams:\"\n\nfor i in top:\n print('Basket:', labels[i])\n for x in top[i][0][0]:\n print(\" \", df.loc[lambda df: df.idx == x, 'name'].item())\n print('Total cost: $', top[i][0][1])\n print(gr_or_ml(labels[i]), top[i][0][2])\n print(\"\\n\")\n\nfrom sklearn.utils import shuffle\n\noriginal_dfs = [df_s, df_d, df_c]\nresults_dict = {}\nrandom_baskets = 100000\n\nfor df_no in range(len(original_dfs)):\n random_results = []\n min_price = original_dfs[df_no].sort_values('price', ascending=True)['price'].iloc[0]\n for i in range(random_baskets):\n random_df = shuffle(original_dfs[df_no])#.sample(frac=1)\n random_basket = []\n balance = gc\n amount = 0\n\n for n in range(random_df.shape[0]):\n if balance - random_df.price.iloc[n] >= 0:\n balance -= random_df.price.iloc[n]\n amount += random_df.amount.iloc[n]\n random_basket.append(random_df.name.iloc[n])\n elif balance < min_price:\n break\n else:\n pass\n\n random_results.append(amount)\n results_dict[df_no] = random_results\n\nprint(max(results_dict[1]))\nprint(top[1][0][2])\nprint(len([x for x in results_dict[1] if x >= top[1][0][2]]))\n\nfor i in range(len(labels)):\n print(\"Random\", labels[i], \"baskets tie or beat the optimized basket\", \"%.2f%%\" % (100 * \n len([x for x in results_dict[i] if x >= top[i][0][2]]) / random_baskets), \"of the time.\")\n\noptimized_amount_snack = top[0][0][2]\noptimized_amount_drink = top[1][0][2]\noptimized_amount_candy = top[2][0][2]\n\nopt_baskets = [optimized_amount_snack, optimized_amount_drink, optimized_amount_candy]\n\nfor i in range(len(opt_baskets)):\n print(\"The optimized\", labels[i], \"basket is over\", \n math.floor((opt_baskets[i] - np.mean(results_dict[i])) / np.std(results_dict[i])), \n \"standard deviations away from the random basket mean\")\n\nprint(opt_baskets[0], np.mean(results_dict[0]), np.std(results_dict[0]))\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nplt.rcParams.update({'font.size': 8})\n\nfig, ax = plt.subplots(figsize=(6.2,5))\nsns.set_style(\"white\")\n\nplt.subplot(2,2,1)\nplt.title('Snacks')\nplt.hist(results_dict[0], color='#F04824')\nplt.axvline(np.mean(results_dict[0]), color='y', linewidth=2)\nplt.axvline(optimized_amount_snack-4, color='y', linestyle='dashed', linewidth=2)\nsns.despine(right=True)\n\nplt.subplot(2,2,2)\nplt.title('Drinks')\nplt.hist(results_dict[1], color='#F04824')\nplt.axvline(np.mean(results_dict[1]), color='y', linewidth=2)\nplt.axvline(optimized_amount_drink, color='y', linestyle='dashed', linewidth=2)\nsns.despine(right=True)\n\nplt.subplot(2,2,3)\nplt.title('Candy')\nplt.hist(results_dict[2], color='#F04824')\nplt.axvline(np.mean(results_dict[2]), color='y', linewidth=2)\nplt.axvline(optimized_amount_candy-2, color='y', linestyle='dashed', linewidth=2)\nsns.despine(right=True)\n\nplt.tight_layout()\nplt.show()\n\nk = 6\ndrink_items = df.loc[df['category'] == 'drink', 'name']\nprint(\"There are\", drink_items.shape[0], \"total items in the 'drink' category with\", \n (len(list(combinations(drink_items, k)))), \"million combinations at k =\", k, \".\")\n" ]
[ [ "matplotlib.pyplot.axvline", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.title", "sklearn.utils.shuffle", "matplotlib.pyplot.subplots", "pandas.DataFrame", "numpy.std", "matplotlib.pyplot.subplot", "numpy.mean", "matplotlib.pyplot.rcParams.update", "matplotlib.pyplot.show", "matplotlib.pyplot.hist" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
RosieLiu/federated
[ "04d460feb39df0b9bccce4214c631b3f39957846" ]
[ "tensorflow_federated/python/simulation/hdf5_client_data.py" ]
[ "# Copyright 2019, The TensorFlow Federated Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Implementation of HDF5 backed ClientData.\"\"\"\n\nimport collections\n\nimport h5py\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.common_libs import py_typecheck\nfrom tensorflow_federated.python.simulation import client_data\nfrom tensorflow_federated.python.tensorflow_libs import tensor_utils\n\n\nclass HDF5ClientData(client_data.ClientData):\n \"\"\"A `tff.simulation.ClientData` backed by an HDF5 file.\n\n This class expects that the HDF5 file has a top-level group `examples` which\n contains further subgroups, one per user, named by the user ID.\n\n The `tf.data.Dataset` returned by\n `HDF5ClientData.create_tf_dataset_for_client(client_id)` yields tuples from\n zipping all datasets that were found at `/data/client_id` group, in a similar\n fashion to `tf.data.Dataset.from_tensor_slices()`.\n \"\"\"\n\n _EXAMPLES_GROUP = \"examples\"\n\n def __init__(self, hdf5_filepath):\n \"\"\"Constructs a `tff.simulation.ClientData` object.\n\n Args:\n hdf5_filepath: String path to the hdf5 file.\n \"\"\"\n py_typecheck.check_type(hdf5_filepath, str)\n self._filepath = hdf5_filepath\n\n self._h5_file = h5py.File(self._filepath, \"r\")\n self._client_ids = sorted(\n list(self._h5_file[HDF5ClientData._EXAMPLES_GROUP].keys()))\n\n # Get the types and shapes from the first client. We do it once during\n # initialization so we can get both properties in one go.\n g = tf.Graph()\n with g.as_default():\n tf_dataset = self._create_dataset(self._client_ids[0])\n self._element_type_structure = tf_dataset.element_spec\n\n def _create_dataset(self, client_id):\n return tf.data.Dataset.from_tensor_slices(\n collections.OrderedDict((name, ds[()]) for name, ds in sorted(\n self._h5_file[HDF5ClientData._EXAMPLES_GROUP][client_id].items())))\n\n @property\n def client_ids(self):\n return self._client_ids\n\n def create_tf_dataset_for_client(self, client_id):\n if client_id not in self.client_ids:\n raise ValueError(\n \"ID [{i}] is not a client in this ClientData. See \"\n \"property `client_ids` for the list of valid ids.\".format(\n i=client_id))\n tf_dataset = self._create_dataset(client_id)\n tensor_utils.check_nested_equal(tf_dataset.element_spec,\n self._element_type_structure)\n return tf_dataset\n\n @property\n def element_type_structure(self):\n return self._element_type_structure\n" ]
[ [ "tensorflow.Graph" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] } ]
JacksonKaunismaa/neural-music
[ "0848044180792e317639a69569d84c654ad98860" ]
[ "model.py" ]
[ "# PyTorch Implementation of https://arxiv.org/pdf/1906.01083.pdf\n# TAKEN FROM https://github.com/resemble-ai/MelNet/blob/master/model.py, with heavy modification\n# added FeatureExtraction, MelNetTier, and the overall multi-scale architecture\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport torchaudio\nimport torch.utils.checkpoint as checkpoint\nckpt = checkpoint.checkpoint\n\ndef chkpt_fwd(module): # standard boilerplate code for buffer checkpointing\n def custom_fwd(*inputs):\n return module(*inputs)\n return custom_fwd\n\n\nclass FrequencyDelayedStack(nn.Module):\n def __init__(self, dims):\n super().__init__()\n self.rnn = nn.GRU(dims, dims, batch_first=True)\n\n def forward(self, x_time, x_freq):\n # sum the inputs\n x = x_time + x_freq\n\n # Batch, Timesteps, Mels, Dims\n B, T, M, D = x.size()\n # collapse the first two axes\n x = x.view(-1, M, D)\n\n # Through the RNN\n x, _ = self.rnn(x)\n return x.view(B, T, M, D)\n\n\nclass TimeDelayedStack(nn.Module):\n def __init__(self, dims):\n super().__init__()\n self.bi_freq_rnn = nn.GRU(dims, dims, batch_first=True, bidirectional=True)\n self.time_rnn = nn.GRU(dims, dims, batch_first=True)\n\n def forward(self, x_time):\n\n # Batch, Timesteps, Mels, Dims\n B, T, M, D = x_time.size()\n\n # Collapse the first two axes\n time_input = x_time.transpose(1, 2).contiguous().view(-1, T, D)\n freq_input = x_time.view(-1, M, D)\n\n # Run through the rnns\n x_1, _ = self.time_rnn(time_input)\n x_2_and_3, _ = self.bi_freq_rnn(freq_input)\n\n # Reshape the first two axes back to original\n x_1 = x_1.view(B, M, T, D).transpose(1, 2)\n x_2_and_3 = x_2_and_3.view(B, T, M, 2 * D)\n\n # And concatenate for output\n x_time = torch.cat([x_1, x_2_and_3], dim=3)\n return x_time\n\n\nclass Layer(nn.Module):\n def __init__(self, dims):\n super().__init__()\n self.freq_stack = FrequencyDelayedStack(dims)\n self.freq_out = nn.Linear(dims, dims)\n self.time_stack = TimeDelayedStack(dims)\n self.time_out = nn.Linear(3 * dims, dims)\n\n def forward(self, x):\n # unpack the input tuple\n x_time, x_freq = x\n\n # grab a residual for x_time\n x_time_res = x_time\n # run through the time delayed stack\n x_time = self.time_stack(x_time)\n # reshape output\n x_time = self.time_out(x_time)\n # connect time residual\n x_time = x_time + x_time_res\n\n # grab a residual for x_freq\n x_freq_res = x_freq\n # run through the freq delayed stack\n x_freq = self.freq_stack(x_time, x_freq)\n # reshape output TODO: is this even needed?\n x_freq = self.freq_out(x_freq)\n # connect the freq residual\n x_freq = x_freq + x_freq_res\n return [x_time, x_freq]\n\nclass FeatureExtraction(nn.Module):\n def __init__(self, num_mels, n_layers):\n super().__init__()\n # Input layers\n self.time_fwd = nn.GRU(num_mels, num_mels, batch_first=True)\n self.time_back = nn.GRU(num_mels, num_mels, batch_first=True)\n self.weights = nn.Linear(2,1)\n\n def forward(self, spectrogram):\n # Shift the inputs left for time-delay inputs\n time_fwd_feats, _ = self.time_fwd(spectrogram)\n time_back_feats, _ = self.time_back(spectrogram.flip(1))\n stacked = torch.stack((time_fwd_feats, time_back_feats), dim=-1)#, freq_fwd_feats.transpose(1,2), freq_back_feats.transpose(1,2)), dim=-1) # completely made up btw\n return self.weights(stacked).squeeze(-1)\n\nclass MelNetTier(nn.Module):\n def __init__(self, dims, n_layers, n_mixtures=10):\n super().__init__()\n # Input layers\n self.freq_input = nn.Linear(1, dims)\n self.time_input = nn.Linear(1, dims)\n\n self.time_cond = nn.Linear(1, dims)\n self.freq_cond = nn.Linear(1, dims)\n\n # Main layers\n self.layers = nn.Sequential(\n *[Layer(dims) for _ in range(n_layers)]\n )\n\n # Output layer\n self.fc_out = nn.Linear(2 * dims, 3 * n_mixtures)\n self.n_mixtures = n_mixtures\n self.sampler = True\n self.softmax_pi = torch.nn.Softmax(dim=-1)\n\n def forward(self, x, cond, noise, sample=True):\n if sample and self.sampler:\n return self.forward_sample(x, cond, noise)\n # Shift the inputs left for time-delay inputs\n x_time = F.pad(x, [0, 0, -1, 1, 0, 0]).unsqueeze(-1)\n # Shift the inputs down for freq-delay inputs\n x_freq = F.pad(x, [0, 0, 0, 0, -1, 1]).unsqueeze(-1)\n\n cond = cond.unsqueeze(-1) # add dimension of 1 to be able to do the linear layer\n\n # Initial transform from 1 to dims\n if cond.shape[2] == 1: # lowest tier, genre embeddings (probably bad way to check)\n shaped_cond = torch.reshape(cond, (-1, 1, 1, cond.shape[-2]))\n x_time = self.time_input(x_time) + shaped_cond #cond#self.time_cond(cond)\n x_freq = self.freq_input(x_freq) + shaped_cond #self.freq_cond(cond)\n else:\n x_time = self.time_input(x_time) + self.time_cond(cond)\n x_freq = self.freq_input(x_freq) + self.freq_cond(cond)\n\n # Run through the layers\n x = (x_time, x_freq)\n x_time, x_freq = self.layers(x)\n\n # Get the mixture params\n x = torch.cat([x_time, x_freq], dim=-1)\n mu, sigma, pi = torch.split(self.fc_out(x), self.n_mixtures, dim=-1)\n\n #sigma = torch.exp(sigma) # causes explosion!\n sigma = torch.exp(sigma/(self.n_mixtures*torch.norm(sigma,dim=-1).unsqueeze(-1))) # scale by n_mixtures (???) at least it further reduces explosion problem\n pi = self.softmax_pi(pi)\n return mu, sigma, pi\n\n def forward_sample(self, x, cond, noise):\n mu, sigma, pi = self.forward(x, cond, noise, sample=False)\n mu_weighted = (mu*pi).sum(axis=-1) # probably totally unjustified\n sigma_weighted = (sigma*pi).sum(axis=-1)\n return mu_weighted + sigma_weighted*noise\n\nclass MelNet(nn.Module):\n def __init__(self, tr_config, data_config, feature_layers=1, n_mixtures=10):\n super().__init__()\n #assert(len(layer_sizes)-2 == len(directions))\n self.class_embeds = nn.Embedding(data_config.num_classes, tr_config.dims)\n\n self.tiers = nn.ModuleList([MelNetTier(tr_config.dims, n_layer) for n_layer in tr_config.n_layers])\n self.tiers[-1].sampler = False\n self.g_mid = len(self.tiers)//2\n\n self.layer_sizes = \"\".join([str(i) for i in tr_config.n_layers]) # for saving model parameters\n\n M = data_config.num_mels\n feature_tiers = [FeatureExtraction(M,feature_layers)]\n for d in tr_config.directions[::-1]:\n if d == 2:\n M //= 2\n feature_tiers.append(FeatureExtraction(M,feature_layers))\n self.feature_tier = nn.ModuleList(feature_tiers[::-1])\n self.directions = tr_config.directions\n self.num_mels = data_config.num_mels\n self.dims = tr_config.dims\n self.mel_extractor = torchaudio.transforms.MelSpectrogram(\n sample_rate=data_config.sr,\n n_fft=data_config.stft_win_sz,\n hop_length=data_config.stft_hop_sz,\n n_mels=data_config.num_mels,\n )\n self.num_params()\n\n def save(self, epoch, loss, optim, path=\"model_checkpoints\"):\n torch.save({\"epoch\": epoch, \"model_state\": self.state_dict(), \"loss\": loss, \"optim_state\": optim.state_dict()},\n f\"{path}/{self.layer_sizes}-{self.num_mels}-{self.dims}-{epoch}-{loss}.model\")\n\n def load(self, path, optim):\n model_ckpt = torch.load(path)\n self.load_state_dict(model_ckpt[\"model_state\"])\n if optim:\n optim.load_state_dict(model_ckpt[\"optim_state\"])\n #return model_ckpt[\"epoch\"] # kinda pointless\n\n\n @staticmethod\n def split(x, dim):\n even = torch.arange(x.shape[dim]//2)*2\n odd = even + 1\n if dim == 1:\n return x[:, even, :], x[:, odd, :]\n else:\n return x[:, :, even], x[:, :, odd]\n\n @staticmethod\n def interleave(x1, x2, dim):\n interleaved = torch.repeat_interleave(x1, 2, dim=dim)\n indices = 1+torch.arange(x1.shape[dim])*2\n if dim == 1:\n interleaved[:,indices,:] = x2\n else:\n interleaved[:,:,indices] = x2\n return interleaved\n\n def forward(self, x, cond, noise):\n def multi_scale(x, g):\n if g == 0:\n condit_embeds = self.class_embeds(cond)\n return ckpt(chkpt_fwd(self.tiers[0]), x, condit_embeds, noise)\n else:\n dim = self.directions[g-1]\n x_g, x_g_prev = self.split(x, dim)\n x_pred_prev = multi_scale(x_g_prev, g-1)\n prev_features = self.feature_tier[g-1](x_pred_prev)\n x_pred = ckpt(chkpt_fwd(self.tiers[g]), x_g, prev_features, noise)\n return self.interleave(x_pred, x_pred_prev, dim)\n prev_context = multi_scale(x, len(self.tiers)-2)\n prev_features = self.feature_tier[-1](prev_context)\n final_distrib = ckpt(chkpt_fwd(self.tiers[-1]), x, prev_features, noise)\n return final_distrib\n\n def num_params(self):\n parameters = filter(lambda p: p.requires_grad, self.parameters())\n parameters = sum([np.prod(p.size()) for p in parameters]) / 1_000_000\n print('Trainable Parameters: %.3fM' % parameters)\n" ]
[ [ "torch.nn.Softmax", "torch.norm", "torch.cat", "torch.load", "torch.nn.ModuleList", "torch.nn.GRU", "torch.reshape", "torch.nn.Embedding", "torch.nn.Linear", "torch.repeat_interleave", "torch.arange", "torch.stack", "torch.nn.functional.pad" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
fossabot/TFkit
[ "aade08634171eaee41e3d687b0f65259bef8fe43" ]
[ "tfkit/model/clas/model.py" ]
[ "import sys\nimport os\n\nimport torch\nfrom torch import nn\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nsys.path.append(os.path.abspath(os.path.join(dir_path, os.pardir)))\n\nfrom torch import softmax, sigmoid\nfrom tfkit.model.clas.dataloader import get_feature_from_data\nfrom tfkit.utility.loss import FocalLoss, BCEFocalLoss\nfrom torch.distributions import Categorical\n\n\nclass Model(nn.Module):\n\n def __init__(self, tokenizer, pretrained, tasks_detail, maxlen=512, dropout=0.1, **kwargs):\n super().__init__()\n self.device = 'cuda' if torch.cuda.is_available() else 'cpu'\n print('Using device:', self.device)\n self.tokenizer = tokenizer\n self.pretrained = pretrained\n\n self.dropout = nn.Dropout(dropout)\n self.loss_fct = FocalLoss()\n self.loss_fct_mt = BCEFocalLoss()\n\n self.tasks = dict()\n self.tasks_detail = tasks_detail\n self.classifier_list = nn.ModuleList()\n for task, labels in tasks_detail.items():\n self.classifier_list.append(nn.Linear(self.pretrained.config.hidden_size, len(labels)).to(self.device))\n self.tasks[task] = len(self.classifier_list) - 1\n self.maxlen = maxlen\n\n self.pretrained = self.pretrained.to(self.device)\n self.classifier_list = self.classifier_list.to(self.device)\n self.loss_fct = self.loss_fct.to(self.device)\n self.loss_fct_mt = self.loss_fct_mt.to(self.device)\n\n # from https://github.com/UKPLab/sentence-transformers\n # Mean Pooling - Take attention mask into account for correct averaging\n # modify - mask from -1 to 0\n def mean_pooling(self, model_output, attention_mask):\n input_mask_expanded = attention_mask.unsqueeze(-1).expand(model_output.size()).float()\n input_mask_expanded[input_mask_expanded < 0] = 0\n sum_embeddings = torch.sum(model_output * input_mask_expanded, 1)\n sum_mask = torch.clamp(input_mask_expanded.sum(1), min=1e-9)\n return sum_embeddings / sum_mask\n\n def forward(self, batch_data, eval=False, **args):\n tasks = batch_data['task']\n inputs = torch.as_tensor(batch_data['input']).to(self.device)\n targets = torch.as_tensor(batch_data['target']).to(self.device)\n masks = torch.as_tensor(batch_data['mask']).to(self.device)\n\n result_dict = {\n 'label_prob_all': [],\n 'label_map': []\n }\n result_logits = []\n result_labels = []\n\n for p, zin in enumerate(zip(tasks, inputs, masks)):\n task, input, mask = zin\n task_id = self.tasks[task]\n task_lables = self.tasks_detail[task]\n\n output = self.pretrained(input.unsqueeze(0), mask.unsqueeze(0))[0]\n pooled_output = self.dropout(self.mean_pooling(output, mask.unsqueeze(0)))\n classifier_output = self.classifier_list[task_id](pooled_output)\n reshaped_logits = classifier_output.view(-1, len(task_lables)) # 0 for cls position\n result_logits.append(reshaped_logits)\n if eval is False:\n target = targets[p]\n result_labels.append(target)\n else:\n if 'multi_label' in task:\n reshaped_logits = sigmoid(reshaped_logits)\n else:\n reshaped_logits = softmax(reshaped_logits, dim=1)\n logit_prob = reshaped_logits[0].data.tolist()\n logit_label = dict(zip(task_lables, logit_prob))\n result_dict['label_prob_all'].append({task: logit_label})\n if 'multi_label' in task:\n result_dict['label_map'].append({task: [k for k, v in logit_label.items() if v > 0.5]})\n else:\n result_dict['label_map'].append({task: [task_lables[logit_prob.index(max(logit_prob))]]})\n\n if eval:\n outputs = result_dict\n else:\n loss = 0\n for logits, labels, task in zip(result_logits, result_labels, tasks):\n if 'multi_label' in task:\n loss += self.loss_fct_mt(logits, labels.type_as(logits))\n else:\n loss += self.loss_fct(logits, labels)\n outputs = loss\n\n return outputs\n\n def get_all_task(self):\n return list(self.tasks.keys())\n\n def predict(self, input='', topk=1, task=get_all_task, handle_exceed='slide',\n merge_strategy=['minentropy', 'maxcount', 'maxprob']):\n topk = int(topk)\n if callable(task):\n task = task(self)\n task = task[0] if isinstance(task, list) else task\n handle_exceed = handle_exceed[0] if isinstance(handle_exceed, list) else handle_exceed\n merge_strategy = merge_strategy[0] if isinstance(merge_strategy, list) else merge_strategy\n self.eval()\n with torch.no_grad():\n ret_result = []\n ret_detail = []\n for feature in get_feature_from_data(tokenizer=self.tokenizer, maxlen=self.maxlen,\n tasks=self.tasks_detail[task], task=task, input=input,\n handle_exceed=handle_exceed):\n for k, v in feature.items():\n feature[k] = [v]\n result = self.forward(feature, eval=True)\n if topk < 2:\n ret_result.append([i[task] for i in result['label_map'] if task in i][0])\n ret_detail.append(result)\n else:\n task_map = [i[task] for i in result['label_prob_all'] if task in i][0]\n ret_result.append(sorted(task_map, key=task_map.get, reverse=True)[:topk])\n ret_detail.append(result)\n\n # apply different strategy to merge result after sliding windows\n if merge_strategy == 'maxcount':\n ret_result = max(ret_result, key=ret_result.count)\n else:\n results_prob = []\n results_entropy = []\n for detail in ret_detail:\n prob_map = detail['label_prob_all'][0][task]\n result_value = [v for _, v in prob_map.items()]\n results_entropy.append(Categorical(probs=torch.tensor(result_value)).entropy().data.tolist())\n results_prob.append(max(result_value))\n min_entropy_index = results_entropy.index(min(results_entropy))\n max_prob_index = results_prob.index(max(results_prob))\n if merge_strategy == 'minentropy':\n ret_result = ret_result[min_entropy_index]\n if merge_strategy == 'maxprob':\n ret_result = ret_result[max_prob_index]\n\n return ret_result, ret_detail\n" ]
[ [ "torch.nn.Dropout", "torch.sigmoid", "torch.softmax", "torch.nn.ModuleList", "torch.sum", "torch.tensor", "torch.no_grad", "torch.cuda.is_available", "torch.as_tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ruancomelli/keras
[ "f1e9c76675981ee6683f54a3ce569212d551d12d" ]
[ "keras/layers/core/reshape.py" ]
[ "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Contains the Reshape layer.\"\"\"\n# pylint: disable=g-classes-have-attributes,g-direct-tensorflow-import\n\nfrom keras.engine.base_layer import Layer\nimport numpy as np\nimport tensorflow.compat.v2 as tf\nfrom tensorflow.python.util.tf_export import keras_export\n\n\n@keras_export('keras.layers.Reshape')\nclass Reshape(Layer):\n \"\"\"Layer that reshapes inputs into the given shape.\n\n Input shape:\n Arbitrary, although all dimensions in the input shape must be known/fixed.\n Use the keyword argument `input_shape` (tuple of integers, does not include\n the samples/batch size axis) when using this layer as the first layer\n in a model.\n\n Output shape:\n `(batch_size,) + target_shape`\n\n Example:\n\n >>> # as first layer in a Sequential model\n >>> model = tf.keras.Sequential()\n >>> model.add(tf.keras.layers.Reshape((3, 4), input_shape=(12,)))\n >>> # model.output_shape == (None, 3, 4), `None` is the batch size.\n >>> model.output_shape\n (None, 3, 4)\n\n >>> # as intermediate layer in a Sequential model\n >>> model.add(tf.keras.layers.Reshape((6, 2)))\n >>> model.output_shape\n (None, 6, 2)\n\n >>> # also supports shape inference using `-1` as dimension\n >>> model.add(tf.keras.layers.Reshape((-1, 2, 2)))\n >>> model.output_shape\n (None, 3, 2, 2)\n \"\"\"\n\n def __init__(self, target_shape, **kwargs):\n \"\"\"Creates a `tf.keras.layers.Reshape` layer instance.\n\n Args:\n target_shape: Target shape. Tuple of integers, does not include the\n samples dimension (batch size).\n **kwargs: Any additional layer keyword arguments.\n \"\"\"\n super(Reshape, self).__init__(**kwargs)\n self.target_shape = tuple(target_shape)\n\n def _fix_unknown_dimension(self, input_shape, output_shape):\n \"\"\"Find and replace a missing dimension in an output shape.\n\n This is a near direct port of the internal Numpy function\n `_fix_unknown_dimension` in `numpy/core/src/multiarray/shape.c`\n\n Args:\n input_shape: Shape of array being reshaped\n output_shape: Desired shape of the array with at most a single -1 which\n indicates a dimension that should be derived from the input shape.\n\n Returns:\n The new output shape with a -1 replaced with its computed value.\n\n Raises:\n ValueError: If the total array size of the output_shape is\n different than the input_shape, or more than one unknown dimension\n is specified.\n \"\"\"\n output_shape = list(output_shape)\n msg = ('total size of new array must be unchanged, '\n 'input_shape = {}, output_shape = {}'.format(input_shape,\n output_shape))\n\n known, unknown = 1, None\n for index, dim in enumerate(output_shape):\n if dim < 0:\n if unknown is None:\n unknown = index\n else:\n raise ValueError(\n f'There must be at most one unknown dimension in output_shape. '\n f'Received: output_shape={output_shape}.')\n else:\n known *= dim\n\n original = np.prod(input_shape, dtype=int)\n if unknown is not None:\n if known == 0 or original % known != 0:\n raise ValueError(msg)\n output_shape[unknown] = original // known\n elif original != known:\n raise ValueError(msg)\n return output_shape\n\n def compute_output_shape(self, input_shape):\n input_shape = tf.TensorShape(input_shape).as_list()\n if None in input_shape[1:]:\n output_shape = [input_shape[0]]\n # input shape (partially) unknown? replace -1's with None's\n output_shape += tuple(s if s != -1 else None for s in self.target_shape)\n else:\n output_shape = [input_shape[0]]\n output_shape += self._fix_unknown_dimension(input_shape[1:],\n self.target_shape)\n return tf.TensorShape(output_shape)\n\n def call(self, inputs):\n result = tf.reshape(inputs, (tf.shape(inputs)[0],) + self.target_shape)\n if not tf.executing_eagerly():\n # Set the static shape for the result since it might lost during array_ops\n # reshape, eg, some `None` dim in the result could be inferred.\n result.set_shape(self.compute_output_shape(inputs.shape))\n return result\n\n def get_config(self):\n config = {'target_shape': self.target_shape}\n base_config = super(Reshape, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n" ]
[ [ "tensorflow.compat.v2.executing_eagerly", "tensorflow.python.util.tf_export.keras_export", "tensorflow.compat.v2.shape", "numpy.prod", "tensorflow.compat.v2.TensorShape" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
yonghanzhang94/A-Single-View-3D-Object-Point-Cloud-Reconstruction
[ "3a71910278a2915374e38baf6af3a81e21148795" ]
[ "save_pix3d_img.py" ]
[ "from __future__ import print_function\nimport argparse\nfrom os.path import join, exists, isdir, dirname, abspath, basename\nimport json\nimport numpy as np\nfrom datasets import GetPix3dDataset\nimport torch\nimport torch.backends.cudnn as cudnn\nfrom model import generator\nfrom torch.autograd import Variable\nimport cv2\nimport matplotlib.pylab as plt\nimport os\nfrom icp import icp\nimport tensorflow as tf\nfrom metrics_utils import get_rec_metrics\nfrom mpl_toolkits.mplot3d import Axes3D\n\ncudnn.benchmark = True\nazim = -45\nelev = -165\nscale = 0.45\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--batchSize', type=int, default=1, help='input batch size') #save img batchsize = 1\nparser.add_argument('--workers', type=int, help='number of data loading workers', default=0)\nparser.add_argument('--cats', default='chair', type=str,\n help='Category to train on : [\"chair\",\"sofa\",\"table\"]')\nparser.add_argument('--num_points', type=int, default=2048, help='number of pointcloud')\nparser.add_argument('--model', type=str, default='./model/chair-2048/modelG_50.pth', help='generator model path')\nopt = parser.parse_args()\n\nsave_path = './pix3d_img/' + opt.cats + '/'\nif not os.path.exists(save_path):\n os.makedirs(save_path)\n\ngen = generator(num_points=opt.num_points)\ngen.cuda().eval()\nwith open(opt.model, \"rb\") as f:\n gen.load_state_dict(torch.load(f))\n\nwith open(join('data/splits/', 'pix3d.json'), 'r') as f:\n pix3d_models_dict = json.load(f)\ndata_dir = './data/pix3d/'\ntest_dataset = GetPix3dDataset(data_dir, pix3d_models_dict, opt.cats, 1024, save=True)\ntestdataloader = torch.utils.data.DataLoader(test_dataset, batch_size=opt.batchSize,\n shuffle=False, num_workers=int(opt.workers))\nprint(len(test_dataset))\n\nwith torch.no_grad():\n data_iter = iter(testdataloader)\n index = 0\n while index < len(testdataloader):\n data = data_iter.next()\n index += 1\n\n if index >= len(testdataloader):\n break\n\n images, points, img_name = data\n\n images = Variable(images.float())\n points = Variable(points.float())\n\n images = images.cuda()\n points = points.cuda()\n\n fake, _, _, _ = gen(images)\n fake = fake.transpose(2, 1) # b x n x c\n\n fake = np.squeeze(fake.cpu().detach().numpy()) # n x c\n points = np.squeeze(points.cpu().detach().numpy()) # n x c\n\n # save groundtruth img\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n ax.set_xlim(-scale, scale)\n ax.set_ylim(-scale, scale)\n ax.set_zlim(-scale, scale)\n for i in range(len(points)):\n ax.scatter(points[i, 1], points[i, 2], points[i, 0], c='#00008B', depthshade=True)\n ax.axis('off')\n ax.view_init(azim=azim, elev=elev)\n plt.savefig(save_path + img_name[0] + '_gt.png')\n # plt.show()\n plt.close()\n\n # save predict img\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n ax.set_xlim(-scale, scale)\n ax.set_ylim(-scale, scale)\n ax.set_zlim(-scale, scale)\n for i in range(len(fake)):\n ax.scatter(fake[i, 1], fake[i, 2], fake[i, 0], c='#00008B', depthshade=True)\n ax.axis('off')\n ax.view_init(azim=azim, elev=elev)\n plt.savefig(save_path + img_name[0] + '_pr.png')\n # plt.show()\n plt.close()\n\n if index % 5 == 0:\n print(\"saving \" + str(index) + \" imgs\")" ]
[ [ "torch.load", "matplotlib.pylab.figure", "torch.no_grad", "matplotlib.pylab.savefig", "matplotlib.pylab.close" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
twylie/viromatch
[ "44edca07c44308b17b9f19174c08175736fff53f" ]
[ "bin/merge_read_counts.py" ]
[ "#! /usr/bin/python3.7\n\nimport argparse\nimport pandas as pd\nimport os\nimport sys\n\nversion = '1.0'\n\n\ndef eval_cli_arguments():\n\n parser = argparse.ArgumentParser(\n description='Merge multiple ViroMatch read count files.',\n prog='merge_read_counts.py',\n add_help=False\n )\n\n # Optional arguments.\n\n parser.add_argument(\n '-h',\n '--help',\n action='help',\n help='Display the extended usage statement.'\n )\n\n parser.add_argument(\n '--version',\n action='version',\n version=version,\n help='Display the software version number.'\n )\n\n parser.add_argument(\n '--merge',\n metavar='nuc|trans|both',\n action='store',\n default='both',\n help='Merge read types. [both]',\n )\n\n # Required arguments.\n\n required_group = parser.add_argument_group('required')\n\n required_group.add_argument(\n '--reports',\n metavar='FILE',\n action='store',\n help='Path to file of report ids:paths.',\n required=True,\n )\n\n required_group.add_argument(\n '--reportdir',\n metavar='DIR',\n action='store',\n help='Directory to write report files.',\n required=True\n )\n\n return parser.parse_args()\n\n\ndef merge_read_counts(arguments):\n\n nuc_report = 'viromatch_results/nuc_nt_best_hit_count_prep/INPUT.merged.validate.nuc.mapped.filter.pass.tax'\n trans_nuc_report = 'viromatch_results/trans_nuc_nr_best_hit_count_prep/INPUT.merged.validate.trans.nuc.mapped.filter.pass.tax'\n\n # Load the ids:paths file.\n\n nuc_paths = dict()\n trans_nuc_paths = dict()\n\n with open(arguments.reports, 'r') as ids_fh:\n for line in ids_fh:\n line = line.strip()\n id_, path = line.split('\\t')\n nuc_report_full = path + nuc_report\n trans_nuc_report_full = path + trans_nuc_report\n nuc_paths.update({nuc_report_full: id_})\n trans_nuc_paths.update({trans_nuc_report_full: id_})\n\n for i, report in enumerate(nuc_paths.keys()):\n if i == 0:\n df_cumulative_nuc = pd.read_csv(report, sep='\\t')\n df_cumulative_nuc['sample name'] = nuc_paths[report]\n else:\n df_file = pd.read_csv(report, sep='\\t')\n df_file['sample name'] = nuc_paths[report]\n df_cumulative_nuc = df_cumulative_nuc.append(df_file, ignore_index=True)\n\n for i, report in enumerate(trans_nuc_paths.keys()):\n if i == 0:\n df_cumulative_trans = pd.read_csv(report, sep='\\t')\n df_cumulative_trans['sample name'] = trans_nuc_paths[report]\n else:\n df_file = pd.read_csv(report, sep='\\t')\n df_file['sample name'] = trans_nuc_paths[report]\n df_cumulative_trans = df_cumulative_trans.append(df_file, ignore_index=True)\n\n df_cumulative_both = pd.concat([df_cumulative_nuc, df_cumulative_trans])\n\n if arguments.merge == 'both':\n df = df_cumulative_both\n elif arguments.merge == 'nuc':\n df = df_cumulative_nuc\n elif arguments.merge == 'trans':\n df = df_cumulative_trans\n\n for tax_level in ('lineage', 'genus', 'species'):\n write_report(arguments, df, tax_level)\n\n return\n\n\ndef write_report(arguments, df, tax_level):\n\n df_tax = df.groupby(tax_level)\n\n counts = dict()\n\n for group in df_tax.groups:\n df = df_tax.get_group(group)\n df_samples = df.groupby('sample name')[tax_level].count().to_dict()\n counts.update({group: df_samples})\n\n df_final = pd.DataFrame.from_dict(counts, orient='index').fillna(0).sort_index()\n df_final = df_final.reindex(sorted(df_final.columns), axis=1)\n\n df_report = arguments.reportdir + tax_level + '.df'\n df_final.to_csv(df_report, sep='\\t')\n\n totals = df_final.T.sum().to_list()\n df_final['TOTAL'] = totals\n\n sample_totals = list()\n for sample in df_final.columns:\n sample_totals.append(df_final[sample].sum())\n df_final.loc['TOTAL'] = sample_totals\n\n report = arguments.reportdir + tax_level + '_merged_counts.tsv'\n\n df_final.to_csv(report, sep='\\t')\n\n return\n\n\ndef make_report_directory(arguments):\n if arguments.reportdir[-1] != '/':\n arguments.reportdir += '/'\n if os.path.isdir(arguments.reportdir) is True:\n outdir_error = '\\nThe --reportdir path \"{}\" already exists.\\n'.format(arguments.reportdir)\n print(outdir_error)\n sys.exit()\n elif os.path.isdir(arguments.reportdir) is False:\n os.mkdir(arguments.reportdir, 0o755)\n return\n\n\nif __name__ == '__main__':\n\n # Given a list of ViroMatch project directories and associated labels, we\n # may generate consolidated read count matrices for lineage, genus, and\n # species levels. Reports will include TSV files with and without totals.\n\n # The --reports file looks something like this (ids:paths).\n # FOO\t/tmp/myTest/myTest/\n # FOO2\t/tmp/myTest/myTest2/\n # ...\n\n arguments = eval_cli_arguments()\n make_report_directory(arguments)\n merge_read_counts(arguments)\n\n\n# __END__\n" ]
[ [ "pandas.concat", "pandas.read_csv", "pandas.DataFrame.from_dict" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
granttremblay/GuiPy
[ "cedb4fac175fae5c46f1b1dc1b013c9859b3dcd2" ]
[ "guipy/widgets/style.py" ]
[ "# -*- coding: utf-8 -*-\n\n\"\"\"\nStyles\n======\n\n\"\"\"\n\n\n# %% IMPORTS\n# Package imports\nfrom matplotlib import rcParams\nfrom matplotlib.lines import lineMarkers, lineStyles\nfrom qtpy import QtCore as QC, QtGui as QG, QtWidgets as QW\n\n# GuiPy imports\nfrom guipy import widgets as GW\nfrom guipy.widgets import set_box_value\n\n# All declaration\n__all__ = ['LineStyleBox', 'MarkerStyleBox']\n\n\n# %% CLASS DEFINITIONS\n# Make class for setting the linestyle\nclass LineStyleBox(GW.QComboBox):\n def __init__(self, *args, **kwargs):\n # Call super constructor\n super().__init__(*args, **kwargs)\n\n # Set up linestyle box\n self.init()\n\n # This function sets up the linestyle box\n def init(self):\n # Obtain list with all supported linestyles if not existing already\n if not hasattr(self, 'LINESTYLES'):\n # Create list of all supported linestyles\n linestyles = [(key, value[6:]) for key, value in lineStyles.items()\n if value != '_draw_nothing']\n linestyles.append(('', 'nothing'))\n linestyles.sort(key=lambda x: x[0])\n\n # Save as class attribute\n LineStyleBox.LINESTYLES = linestyles\n\n # Populate this box with all supported linestyles\n for i, (linestyle, tooltip) in enumerate(self.LINESTYLES):\n self.addItem(linestyle)\n self.setItemData(i, tooltip, QC.Qt.ToolTipRole)\n\n # Set initial value to the default value in MPL\n set_box_value(self, rcParams['lines.linestyle'])\n\n # Override set_box_value to account for other spellings of 'nothing'\n def set_box_value(self, value, *value_sig):\n # Set value to empty if it uses a different spelling\n if value.lower() in ('none', ' '):\n value = ''\n elif value.lower() in ('dashed', ):\n value = '--'\n elif value.lower() in ('dotted', ):\n value = ':'\n\n # Call normal method\n set_box_value(self, value, *value_sig, no_custom=True)\n\n\n# Make class for setting the markerstyle\nclass MarkerStyleBox(GW.QComboBox):\n def __init__(self, *args, **kwargs):\n # Call super constructor\n super().__init__(*args, **kwargs)\n\n # Set up markerstyle box\n self.init()\n\n # This function sets up the markerstyle box\n def init(self):\n # Obtain list with all supported markerstyles if not existing already\n if not hasattr(self, 'MARKERS'):\n # Create list of all supported markerstyles\n markers = [(key, value) for key, value in lineMarkers.items()\n if(value != 'nothing' and isinstance(key, str))]\n markers.append(('', 'nothing'))\n markers.sort(key=lambda x: x[0])\n\n # Save as class attribute\n MarkerStyleBox.MARKERS = markers\n\n # Populate this box with all supported markerstyles\n for i, (marker, tooltip) in enumerate(self.MARKERS):\n self.addItem(marker)\n self.setItemData(i, tooltip, QC.Qt.ToolTipRole)\n\n # Set initial value to the default value in MPL\n set_box_value(self, rcParams['lines.marker'])\n\n # Override set_box_value to account for other spellings of 'nothing'\n def set_box_value(self, value, *value_sig):\n # Set value to empty if it uses a different spelling\n if value.lower() in ('none', ' '):\n value = ''\n\n # Call normal method\n set_box_value(self, value, *value_sig, no_custom=True)\n" ]
[ [ "matplotlib.lines.lineMarkers.items", "matplotlib.lines.lineStyles.items" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Qingtian-Zou/AIX360
[ "cf25f58077ae002fb4542b680fd98db47758dae5" ]
[ "aix360/data/ted_data/GenerateData.py" ]
[ "# This file will generate a synthetic dataset to predict employee attrition\r\n# Like most datasets it will have a feature vector and a Y label for each instance.\r\n# However, unlike most datasets it will also have an Explanation (E) for each instance, encoded as an non-negative integer.\r\n# This is motivated by the TED framework, but can be used by other explainability algorithms as a metric for explainability\r\n# See the AIES'19 paper by Hind et al for more information on the TED framework.\r\n# See the tutorial notebook TED_Cartesian_test for information about how to use this dataset and the TED framework.\r\n# The comments in this code also provide some insight into how this dataset is generated\r\n\r\nimport random\r\nfrom random import choices\r\nimport pandas as pd\r\n\r\nAny = -99 # This is only applicable in the rule\r\nLow = -1 # These 3, Low, Med, High, can be values in the dataset and are used in the rules\r\nMed = -2\r\nHigh = -3\r\nYes = -10 # This is the positive Y label\r\nNo = -11 # This is the negative Y label\r\nRandom = -12 # This signifies a random choice should be made for the Y label (either Yes or No) ]\r\n\r\n# Features, values, and distribution, details below\r\nfeatureThresholds = [\r\n # 1 Position: 4(5%), 3(20%), 2(30%), 1(45%)\r\n [4, [0.05, 0.20, 0.30, 0.45]],\r\n\r\n # 2 Organization \"Org\": 3(30%); 2(30%); 1(40%)\r\n [3, [0.30, 0.30, 0.40]],\r\n\r\n # 3 Potential \"Pot\": Yes (50%), No (50%)\r\n [2, [0.50, 0.50]],\r\n\r\n # 4 Rating value \"Rat\": High(15%), Med(80%), Low(5%)\r\n [3, [0.15, 0.80, 0.05]],\r\n\r\n # 5 Rating Slope \"Slope\": High (15%), Med(80%), Low(5%)\r\n [3, [0.15, 0.80, 0.05]],\r\n\r\n # 6 Salary Competitiveness \"Sal\": High (10%); Med(70%); Low(20%)\r\n [3, [0.10, 0.70, 0.20]],\r\n\r\n # 7 Tenure Low \"TenL\" & High Values \"TenH\": [0..360], 30% in 0..24; 30% in 25..60; 40% in 61..360\r\n [3, [0.30, 0.30, 0.40], [[0, 24], [25, 60], [61, 360]]],\r\n\r\n # 8 Position Tenure Low \"BTenL\" & High Values \"BTenH\": [0..360], 70% in 0..12; 20% in 13..24; 10% in 25..360\r\n # Position tenure needs to be lower than tenure, ensured in generation code below\r\n [3, [0.70, 0.20, 0.10], [[0, 12], [13, 24], [25, 360]]]\r\n]\r\n\r\n# Some convenient population lists\r\nHighMedLowPopulation = [High, Med, Low]\r\nYesNoPopulation = [Yes, No]\r\nIndex3Population = [0, 1, 2]\r\nInteger4Population = [4, 3, 2, 1]\r\nInteger3Population = [3, 2, 1]\r\n\r\n# Rules used to label a feature vector with a label and an explanation\r\n# Format: features, label, explanation #, Explanation String \r\nRetentionRules = [ \r\n #POS ORG Pot RAT Slope SALC TENL H BTEN LH \r\n [Any, 1, Any, High, Any,\tLow, Any, Any, Any, Any, #0\r\n Yes, 2, \"Seeking Higher Salary in Org 1\"],\r\n [1, 1,\t Any, Any, Any,\tAny, Any, Any, 15, Any,\t#1\r\n Yes, 3, \"Promotion Lag, Org 1, Position 1\"],\r\n [2, 1,\t Any, Any, Any,\tAny, Any, Any, 15, Any,\t#2\r\n Yes, 3, \"Promotion Lag, Org 1, Position 2\"],\r\n [3, 1,\t Any, Any, Any,\tAny, Any, Any, 15, Any,\t#3\r\n Yes, 3, \"Promotion Lag, Org 1, Position 3\"],\r\n [1, 2,\t Any, Any, Any,\tAny, Any, Any, 20, Any,\t#4\r\n Yes, 4, \"Promotion Lag, Org 2, Position 1\"],\r\n [2, 2,\t Any, Any, Any,\tAny, Any, Any, 20, Any,\t#5\r\n Yes, 4, \"Promotion Lag, Org 2, Position 2\"],\r\n [3, 2, Any, Any, Any,\tAny, Any, Any, 30, Any,\t#6\r\n Yes, 5, \"Promotion Lag, Org 2, Position 3\"],\r\n [1, 3, Any, Any, Any,\tAny, Any, Any, 20, Any,\t#7\r\n Yes, 6, \"Promotion Lag, Org 3, Position 1\"],\r\n [2, 3,\t Any, Any, Any,\tAny, Any, Any, 30, Any,\t#8\r\n Yes, 7, \"Promotion Lag, Org 3, Position 2\"],\r\n [3, 3,\t Any, Any, Any,\tAny, Any, Any, 30, Any,\t#9\r\n Yes, 7, \"Promotion Lag, Org 3, Position 3\"],\r\n [1, 1, Any, Any, Any,\tAny, 0, 12, Any, Any,\t#10\r\n Yes, 8, \"New employee, Org 1, Position 1\"],\r\n [2, 1, Any, Any, Any,\tAny, 0, 12, Any, Any,\t#11\r\n Yes, 8, \"New employee, Org 1, Position 2\"],\r\n [3, 1, Any, Any, Any,\tAny, 0, 30, Any, Any,\t#12\r\n Yes, 9, \"New employee, Org 1, Position 3\"],\r\n [1, 2, Any, Any, Any,\tAny, 0, 24, Any, Any,\t#13\r\n Yes, 10, \"New employee, Org 2, Position 1\"],\r\n [2, 2, Any, Any, Any,\tAny, 0, 30, Any, Any,\t#14\r\n Yes, 11, \"New employee, Org 2, Position 2\"],\r\n [Any, 1, Any, Low, High, Any, Any, Any, Any, Any,\t#15\r\n Yes, 13, \"Disappointing evaluation, Org 1\"],\r\n [Any, 2, Any, Low, High, Any, Any, Any, Any, Any,\t#16\r\n Yes, 14, \"Disappointing evaluation, Org 2\"],\r\n [Any, Any, Yes, Med, High, Low, Any, Any, Any, Any,\t#17\r\n Yes, 15, \"Compensation doesn't match evaluations, Med rating\"],\r\n [Any, Any, Yes, High, High, Low, Any, Any, Any, Any,\t#18\r\n Yes, 15, \"Compensation doesn't match evaluations, High rating\"],\r\n [Any, 1, Yes, Med, High, Med, Any, Any, Any, Any,\t#19\r\n\t Yes, 16, \"Compensation doesn't match evaluations, Org 1, Med rating\"],\r\n [Any, 2, Yes, Med, High, Med, Any, Any, Any, Any,\t#20\r\n\t Yes, 16, \"Compensation doesn't match evaluations, Org 2, Med rating\"],\r\n [Any, 1, Yes, High, High, Med, Any, Any, Any, Any,\t#21\r\n\t Yes, 16, \"Compensation doesn't match evaluations, Org 1, High rating\"],\r\n [Any, 2, Yes, High, High, Med, Any, Any, Any, Any,\t#22\r\n\t Yes, 16, \"Compensation doesn't match evaluations, Org 2, High rating\"],\r\n [Any, 1, Any, Any, Med,\tMed, 120, 180, Any, Any,\t#23\r\n\t Yes, 17, \"Mid-career crisis, Org 1\"],\r\n [Any, 2, Yes, Any, Any,\tMed, 130, 190, Any, Any,\t#24\r\n\t Yes, 18, \"Mid-career crisis, Org 2\"]\r\n]\r\n\r\ndef ruleValToString(val):\r\n \"\"\" Convert the value passed into a string \"\"\"\r\n if val == Any :\r\n return \"Any\"\r\n elif val == Low :\r\n return \"Low\"\r\n elif val == Med :\r\n return \"Med\"\r\n elif val == High :\r\n return \"High\"\r\n elif val == Yes :\r\n return \"Yes\"\r\n elif val == No :\r\n return \"No\"\r\n elif val == Random :\r\n return \"Random\"\r\n else :\r\n return str(val)\r\n\r\ndef printFeatureStringHeader() :\r\n \"\"\" Print the feature headings \"\"\"\r\n print(\" Feature Headings\")\r\n print(\"[Pos, Org, Pot, Rating, Slope, Salary Competitiveness, Tenure, Position Tenure]\")\r\n \r\ndef featuresToString(featureVector) :\r\n \"\"\" Convert a feature vector into is string format\"\"\"\r\n val = \"[\"\r\n for i in range(0, 2) : # These features are just ints, Position, Organization\r\n val += str(featureVector[i])\r\n val += \" \" \r\n for i in range(2, 6) : # show encoding for these: Potential, Rating, Rating Slope, Salary Competitiveness\r\n val += ruleValToString(featureVector[i]) \r\n val += \" \"\r\n for i in range(6, 8) : # These features are just ints: Tenure and Position Tenure\r\n val += str(featureVector[i])\r\n val += \" \" \r\n val += \"]\"\r\n return val\r\n\r\ndef printRule(rule) :\r\n \"\"\" Print the passed rule \"\"\"\r\n print(\"Rule: \", end='')\r\n for i in rule[0:1]: # ints or Any: Position and Organization\r\n if i == Any:\r\n print(ruleValToString(i) + \", \", end='')\r\n\r\n for i in rule[2:5]: # encoded: Potentional, Rating, Rating Slope, Salary Competitiveness\r\n print(ruleValToString(i) + \", \", end='')\r\n\r\n for i in rule[6:9]: # next 4 are ints or ANY: Tenure Low, Tenure High, Position Tenure Low, Position Tenure High\r\n if i == Any :\r\n print(ruleValToString(i) + \", \", end='')\r\n else :\r\n print(str(i) + \", \", end='') \r\n print(\"==> \"+ ruleValToString(rule[10]) + \"[\" + str(rule[11]) + \"] \" + str(rule[12]))\r\n\r\ndef printRules(rules) :\r\n \"\"\" print all rules\"\"\"\r\n for r in rules:\r\n printRule(r)\r\n\r\n########################################################################\r\n\r\ndef chooseRangeValue(thresholds, rangeList):\r\n \"\"\" Generate a random value based on the probability weights (thresholds) and list of ranges passed\r\n Args: \r\n thresholds : list of probabilities for each choice\r\n rangeList: a list of pair lists giving the lower and upper bounds to choose value from \r\n \"\"\"\r\n\r\n # pick a number 1..3 from weights\r\n rangeVal = choices(Index3Population, thresholds)\r\n\r\n # get the appropriate range given rangeVal\r\n interval = rangeList[rangeVal[0]]\r\n\r\n # construct a population list from the result\r\n intervalPopulation = list(range(interval[0], interval[1]))\r\n\r\n # construct a equally prob weights list\r\n numElements = interval[1] - interval[0]\r\n probVal = 1.0 / numElements\r\n probList = [probVal] * numElements\r\n\r\n # now choose the value from the population based on the weights\r\n val = choices(intervalPopulation, probList)\r\n return val[0]\r\n\r\n\r\ndef chooseValueAndAppend(instance, population, weights) :\r\n \"\"\" Choose a random value from the population using weights list and append it to the passed instance\r\n \"\"\"\r\n val = choices(population, weights)\r\n instance.append(val[0])\r\n\r\ndef generateFeatures(numInstances) :\r\n \"\"\" generate the features (X) values for the dataset\r\n Args:\r\n numInstances (int) : number of instances to genreate\r\n Returns:\r\n dataset (list of lists) : the dataset with features, but no labels or explanations yet\r\n \"\"\"\r\n assert(numInstances > 0)\r\n\r\n dataset = []\r\n for i in range(numInstances) :\r\n instance = []\r\n\r\n #POS ORG Pot Rating Slope SALC TENL H BTEN LH \r\n chooseValueAndAppend(instance, Integer4Population, featureThresholds[0][1]) # Position\r\n chooseValueAndAppend(instance, Integer3Population, featureThresholds[1][1]) # Org\r\n chooseValueAndAppend(instance, YesNoPopulation, featureThresholds[2][1]) # Potential\r\n chooseValueAndAppend(instance, HighMedLowPopulation, featureThresholds[3][1]) # Rating\r\n chooseValueAndAppend(instance, HighMedLowPopulation, featureThresholds[4][1]) # Rating slope\r\n chooseValueAndAppend(instance, HighMedLowPopulation, featureThresholds[5][1]) # Sal competitiveness\r\n\r\n val1 = chooseRangeValue(featureThresholds[6][1], featureThresholds[6][2]) # Tenure\r\n instance.append(val1)\r\n\r\n # Position tenure needs to be <= Tenure\r\n val2 = chooseRangeValue(featureThresholds[7][1], featureThresholds[7][2]) # Pos Tenure\r\n if val2 > val1 :\r\n val2 = val1\r\n instance.append(val2)\r\n dataset.append(instance)\r\n \r\n return dataset\r\n\r\n#####################################################################################################\r\n\r\ndef match(ruleVal, featureVal) :\r\n \"\"\" Check if passed ruleVal matches the featureVal or if ruleVal is Any, which matches everything \r\n \"\"\"\r\n\r\n # print(\"Match called: \"+ ruleValToString(ruleVal) + \" \" + ruleValToString(featureVal))\r\n if ruleVal == Any :\r\n return True\r\n return (ruleVal == featureVal)\r\n\r\ndef intervalMatch(ruleValLower, ruleValUpper, featureVal) :\r\n \"\"\" Check to see if featureVal is in the interval defined by [ruleValLower, ruleValUpper)\r\n \"\"\"\r\n\r\n # Any in lower bound matches all values, (upper bound doesn't matter)\r\n if ruleValLower == Any :\r\n return True\r\n\r\n if ruleValLower <= featureVal :\r\n # Any in upper bound means infinitity\r\n if featureVal < ruleValUpper or ruleValUpper == Any :\r\n return True\r\n \r\n return False\r\n\r\ndef ruleMatch(rule, featureVector) :\r\n \"\"\" Determine if the passed featureVector matches the passed rule \r\n \"\"\"\r\n if (False) :\r\n print(\"ruleMatch called, \", end=\"\")\r\n printRule(rule)\r\n print(\" feature vector: \" + featuresToString(featureVector) )\r\n\r\n for i in range(0, 6) : # loop over first 6 features, 0..5\r\n if not match(rule[i], featureVector[i]) : # if we don't find a feature match, the rule doesn't match\r\n # print(\"Didn't match feature #\", i, ruleValToString(featureVector[i]))\r\n return False\r\n \r\n # These features are interval-based, so need a different matching routine\r\n if not intervalMatch(rule[6], rule[7], featureVector[6]) : # rule[6] and rule[7] have the lower and upper bounds of interval\r\n # print(\"Didn't match feature # 6: \", featureVector[6])\r\n return False\r\n if not intervalMatch(rule[8], rule[9], featureVector[7]) : # rule[8] and rule[9] have the lower and upper bounds of interval\r\n # print(\"Didn't match feature # 7: \", featureVector[7])\r\n return False\r\n \r\n # print(\"Matched all features\")\r\n return True # if we didn't find a non-match by now, we found a match\r\n\r\ndef findRule(instance, ruleSet) :\r\n \"\"\" find the rule(s) that matches the feture vector passed\r\n \"\"\"\r\n\r\n # print(\"*Looking for rule match for Feature vector: \" + featuresToString(instance))\r\n ruleNumber = 0 # counter to track rule number\r\n ruleMatches = [] # will hold all rule numbers that matched\r\n for rule in ruleSet :\r\n if (ruleMatch(rule, instance)) :\r\n ruleMatches.append(ruleNumber)\r\n counts[ruleNumber] += 1 # update global histogram of rule matches for stats reporting\r\n\r\n if (False) :\r\n print(\" ruleMatch found at rule #\" + str(ruleNumber))\r\n print(\" \", end=\"\")\r\n printRule(rule)\r\n\r\n ruleNumber += 1\r\n\r\n return ruleMatches\r\n\r\ndef countAnys(rule) :\r\n \"\"\" Count the number of Anys in the passed rule. An \"Any\" is a wildcard that matches all values\r\n \"\"\"\r\n count = 0\r\n for feature in RetentionRules[rule] :\r\n if feature == Any :\r\n count += 1\r\n\r\n return count\r\n\r\ndef pickBestRule(ruleList) :\r\n \"\"\" Choose the rule with the least number of Any's in it\r\n \"\"\"\r\n assert(len(ruleList) > 0)\r\n\r\n # print(\"ruleList: \", ruleList)\r\n minAnys = len(RetentionRules[0]) + 1 # initialize to a value larger than possible # of Anys in a rule\r\n bestRule = -1\r\n for rule in ruleList :\r\n # Count # of Any's in rule # rule\r\n count = countAnys(rule)\r\n if count < minAnys :\r\n minAnys = count\r\n bestRule = rule\r\n\r\n assert(bestRule != -1) # We should find a best rule\r\n return bestRule\r\n\r\ndef addLabelsAndExplanations(dataset, rules) :\r\n \"\"\" This function will use a ruleset to add labels (Y) and explanations/rules (E) to a passed dataset\r\n Arg:\r\n dataset (list of lists) : a list of feature vectors (list)\r\n rules (list of lists) : a list of rules\r\n \"\"\"\r\n\r\n noMatches = 0 # Counters to record how often there are no (Yes) matches, 1 (Yes) match, and multiple (Yes) matches\r\n multiMatches = 0\r\n oneMatches = 0\r\n for instance in dataset :\r\n ruleMatches = findRule(instance, rules)\r\n\r\n if len(ruleMatches) == 0 : # We didn't match a (Yes) rule, so this ia No situation\r\n rule = NoRiskRuleNum\r\n label = No\r\n noMatches +=1\r\n elif len(ruleMatches) > 1 : # Matched multiple Yes rules, need to pick one\r\n rule = pickBestRule(ruleMatches)\r\n assert(rule >= 0 and rule < len(rules)) # Ensure rule number is valid\r\n label = Yes\r\n multiMatches += 1\r\n else : # Found 1 Yes rule match, it's the winner\r\n rule = ruleMatches[0]\r\n label = Yes\r\n oneMatches += 1\r\n assert(rule >= 0 and rule < len(rules)) # Ensure rule number is valid\r\n\r\n # print(\"Label: \" + ruleValToString(label) + \", Rule: \" + ruleValToString(rule))\r\n\r\n instance.append(label)\r\n instance.append(rule) # add the label and explanation (rule #) to the featureVector\r\n\r\n if (True) :\r\n print(\"\\nRule matching statistics: \")\r\n totalYes = oneMatches + multiMatches\r\n total = oneMatches + multiMatches + noMatches\r\n print(\" Yes Labels: {}/{} ({:.2f}%)\".format(totalYes, total, totalYes/total*100))\r\n print(\" Matched 1 Yes rule: {}/{} ({:.2f}%)\".format(oneMatches, totalYes, oneMatches/totalYes*100))\r\n print(\" Matched multiple Yes rules: {}/{} ({:.2f}%)\".format(multiMatches, totalYes, multiMatches/totalYes*100))\r\n print(\" No Laels: {}/{} ({:.2f}%)\".format(noMatches, total, noMatches/total*100))\r\n\r\ndef printRuleUsage(counts, total) :\r\n print(\"\\nHistogram of rule usage:\")\r\n ruleNum = 0\r\n for num in counts :\r\n print(\" Rule {} was used {} times, {:.2f}%\".format(ruleNum, num, num/total*100))\r\n ruleNum += 1\r\n\r\n \r\nnumRentionRules = len(RetentionRules)\r\ncounts = [0]*numRentionRules\r\nNoRiskRuleNum = numRentionRules # the No Risk to leave rule is 1 more than than the total rules [0..]\r\n\r\nrandom.seed(1)\r\n# printFeatureStringHeader()\r\nnumInstances = 10000\r\ndataset = generateFeatures(numInstances)\r\n\r\naddLabelsAndExplanations(dataset, RetentionRules)\r\n\r\nprintRuleUsage(counts, numInstances)\r\n\r\n# insert TED headers\r\nNumFeatures = len(featureThresholds)\r\nheader = list(range(NumFeatures))\r\nheader.append(\"Y\")\r\nheader.append(\"E\")\r\ndataset.insert(0, header)\r\n\r\n# write to csv file\r\nmy_df = pd.DataFrame(dataset)\r\nmy_df.to_csv('Retention.csv', index=False, header=False)\r\n" ]
[ [ "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
yuyan110nan/federated-learning-master-CJC
[ "96f3b316704f2a182ed3998ff432123d190f7482" ]
[ "main_fed_poison_attack_fedavg.py" ]
[ "#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# Python version: 3.6\r\n\r\nimport matplotlib\r\nimport pandas as pd\r\n\r\nmatplotlib.use('Agg')\r\nimport matplotlib.pyplot as plt\r\nimport copy\r\nimport numpy as np\r\nfrom torchvision import datasets, transforms\r\nimport torch\r\n\r\nfrom utils.sampling import mnist_iid, mnist_noniid, cifar_iid\r\nfrom utils.options import args_parser\r\nfrom models.Update import LocalUpdate\r\nfrom models.Nets import MLP, CNNMnist, CNNCifar\r\nfrom models.Fed import FedAvg, ADP_FedAvg, ADP_Loss_FedAvg\r\nfrom models.test import test_img, test_img_float\r\n\r\nif __name__ == '__main__':\r\n # parse args\r\n args = args_parser()\r\n args.device = torch.device('cuda:{}'.format(args.gpu) if torch.cuda.is_available() and args.gpu != -1 else 'cpu')\r\n\r\n # load dataset and split users\r\n if args.dataset == 'mnist':\r\n trans_mnist = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])\r\n dataset_train = datasets.MNIST('../data/mnist/', train=True, download=True, transform=trans_mnist)\r\n dataset_test = datasets.MNIST('../data/mnist/', train=False, download=True, transform=trans_mnist)\r\n # sample users\r\n if args.iid:\r\n dict_users = mnist_iid(dataset_train, args.num_users)\r\n else:\r\n dict_users = mnist_noniid(dataset_train, args.num_users)\r\n elif args.dataset == 'cifar':\r\n trans_cifar = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\r\n dataset_train = datasets.CIFAR10('../data/cifar', train=True, download=True, transform=trans_cifar)\r\n dataset_test = datasets.CIFAR10('../data/cifar', train=False, download=True, transform=trans_cifar)\r\n dict_users = cifar_iid(dataset_train, args.num_users)\r\n # if args.iid:\r\n # dict_users = cifar_iid(dataset_train, args.num_users)\r\n # else:\r\n # exit('Error: only consider IID setting in CIFAR10')\r\n else:\r\n exit('Error: unrecognized dataset')\r\n img_size = dataset_train[0][0].shape\r\n\r\n # build model\r\n if args.model == 'cnn' and args.dataset == 'cifar':\r\n net_glob = CNNCifar(args=args).to(args.device)\r\n elif args.model == 'cnn' and args.dataset == 'mnist':\r\n net_glob = CNNMnist(args=args).to(args.device)\r\n elif args.model == 'mlp':\r\n len_in = 1\r\n for x in img_size:\r\n len_in *= x\r\n net_glob = MLP(dim_in=len_in, dim_hidden=200, dim_out=args.num_classes).to(args.device)\r\n else:\r\n exit('Error: unrecognized model')\r\n print(net_glob)\r\n net_glob.train()\r\n\r\n # copy weights\r\n w_glob = net_glob.state_dict()\r\n\r\n # training\r\n loss_train = []\r\n cv_loss, cv_acc = [], []\r\n val_loss_pre, counter = 0, 0\r\n net_best = None\r\n best_loss = None\r\n val_acc_list, net_list, acc_test_list = [], [], []\r\n\r\n if args.all_clients:\r\n print(\"Aggregation over all clients\")\r\n w_locals = [w_glob for i in range(args.num_users)]\r\n list = [0.1]\r\n poison_list = [0.1]\r\n for attack_num in poison_list:\r\n for attack_strength in list:\r\n print('attack_num {:3f}, attack_strength {:.3f}'.format(attack_num, attack_strength))\r\n for iter in range(100):\r\n loss_locals = []\r\n score_locals = []\r\n if not args.all_clients:\r\n w_locals = []\r\n m = max(int(0.3 * args.num_users), 1)\r\n idxs_users = np.random.choice(range(args.num_users), m, replace=False)\r\n for idx in idxs_users:\r\n local = LocalUpdate(args=args, dataset=dataset_train, idxs=dict_users[idx])\r\n w, loss = local.ADP_noise_train(net=copy.deepcopy(net_glob).to(args.device))\r\n if args.all_clients:\r\n w_locals[idx] = copy.deepcopy(w)\r\n else:\r\n w_locals.append(copy.deepcopy(w))\r\n loss_locals.append(loss)\r\n #poisoning attack\r\n m_poison = max(int(attack_num * args.num_users), 1)\r\n poison_users = np.random.choice(range(args.num_users), m_poison, replace=False)\r\n for idx in poison_users:\r\n local = LocalUpdate(args=args, dataset=dataset_train, idxs=dict_users[idx])\r\n w, loss = local.poison_attack_train(attack_strength,net=copy.deepcopy(net_glob).to(args.device))\r\n if args.all_clients:\r\n w_locals[idx] = copy.deepcopy(w)\r\n else:\r\n w_locals.append(copy.deepcopy(w))\r\n loss_locals.append(loss)\r\n # 计算本地模型分数\r\n for loss in loss_locals:\r\n score_locals.append(1 - loss/sum(loss_locals))\r\n\r\n # update global weights\r\n #w_glob = ADP_FedAvg(w_locals,score_locals)\r\n w_glob = FedAvg(w_locals)\r\n # copy weight to net_glob\r\n net_glob.load_state_dict(w_glob)\r\n if(iter%5==0):\r\n acc_test, loss_test = test_img_float(net_glob, dataset_test, args)\r\n acc_test_list.append(acc_test)\r\n print('Round {:3d}, Average loss {:.3f}'.format(iter, loss_test))\r\n print(\"Testing accuracy: {:.2f}\".format(acc_test))\r\n df = pd.DataFrame([acc_test_list])\r\n df.to_csv('./save/reputation_acc.csv', header=True, index=None,mode='a') # mode='a' 追加\r\n\r\n" ]
[ [ "matplotlib.use", "torch.cuda.is_available", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
vanvalenlab/deepcell-data-engineering
[ "a0dca3839f341841cb4a983923fd0eac21225736" ]
[ "caliban_toolbox/utils/plot_utils.py" ]
[ "# Copyright 2016-2020 The Van Valen Lab at the California Institute of\n# Technology (Caltech), with support from the Paul Allen Family Foundation,\n# Google, & National Institutes of Health (NIH) under Grant U24CA224309-01.\n# All rights reserved.\n#\n# Licensed under a modified Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.github.com/vanvalenlab/caliban-toolbox/LICENSE\n#\n# The Work provided may be used for non-commercial academic purposes only.\n# For any other use of the Work, including commercial use, please contact:\n# [email protected]\n#\n# Neither the name of Caltech nor the names of its contributors may be used\n# to endorse or promote products derived from this software without specific\n# prior written permission.\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport numpy as np\n\nfrom caliban_toolbox.utils import data_utils\n\n\ndef overlay_grid_lines(overlay_img, row_starts, row_ends, col_starts, col_ends):\n \"\"\"Visualize the location of image crops on the original uncropped image to assess crop size\n\n Args:\n overlay_img: original image [rows x cols] that crops will overlaid onto\n row_starts: vector of start indices generated by crop_multichannel_data\n row_ends: vector of end indices generated by crop_multichannel_data\n col_starts: vector of start indices generated by crop_multichannel_data\n col_ends: vector of end indices generated by crop_multichannel_data\n\n Returns:\n numpy.array: original image overlaid with the crop borders\n \"\"\"\n\n # get dimensions of the image\n row_len = overlay_img.shape[0]\n col_len = overlay_img.shape[1]\n\n # if first start position is 0, we won't plot it since it's on the image border\n if row_starts[0] == 0:\n row_starts = row_starts[1:]\n if col_starts[0] == 0:\n col_starts = col_starts[1:]\n\n # use distance between start index of crop 1 and end index of crop 0 determine overlap amount\n row_sep = row_ends[0] - row_starts[0]\n col_sep = col_ends[0] - col_starts[0]\n\n # generate a vector of alternating 0s and im_max for a dotted line\n val = np.max(overlay_img)\n dotted = [0, 0, 0, 0, val, val, val, val]\n side = np.max(overlay_img.shape)\n dotted = dotted * side\n\n # trim dotted vectors to be same length as respective image dimension\n row_dotted = np.expand_dims(np.array(dotted[:row_len]), axis=-1)\n col_dotted = np.expand_dims(np.array(dotted[:col_len]), axis=0)\n\n # expand the thickness to 3 pixel width for better visualization\n row_starts = row_starts + [x + 1 for x in row_starts] + [x + 2 for x in row_starts]\n row_ends = [x + row_sep for x in row_starts]\n\n # define the location of each image to be halfway between the overlap boundary on either side\n row_middle = [int(x + (row_sep / 2)) for x in row_starts]\n\n # same for columns\n col_starts = col_starts + [x + 1 for x in col_starts] + [x + 2 for x in col_starts]\n col_middle = [int(x + (col_sep / 2)) for x in col_starts]\n col_ends = [x + col_sep for x in col_starts]\n\n # set the values of start and end indices to be dotted lines\n overlay_img[row_starts, :] = col_dotted\n overlay_img[row_ends, :] = col_dotted\n overlay_img[:, col_starts] = row_dotted\n overlay_img[:, col_ends] = row_dotted\n\n # set the values of the line delineating image crop to be constant value\n overlay_img[row_middle, :] = val\n overlay_img[:, col_middle] = val\n\n return overlay_img\n\n\ndef overlay_crop_overlap(img_crop, row_starts, row_ends, col_starts, col_ends):\n \"\"\"Plot a single crop to evaluate amount of overlap with adjacent crops\n\n Args:\n img_crop: example crop to use for plotting overlap\n row_starts: vector of start indices generated by crop_multichannel_data\n row_ends: vector of end indices generated by crop_multichannel_data\n col_starts: vector of start indices generated by crop_multichannel_data\n col_ends: vector of end indices generated by crop_multichannel_data\n\n Returns:\n numpy.array: example crop with dotted lines superimposed\n on location of adjacent overlapping crops\n \"\"\"\n\n # get image dimensions\n row_len, col_len = img_crop.shape[0], img_crop.shape[1]\n\n # compute amount of overlap on each axis\n row_overlap = row_ends[0] - row_starts[1]\n col_overlap = col_ends[0] - col_starts[1]\n\n # generate vector to super-impose dotted line\n val = np.max(img_crop)\n dotted = [0, 0, 0, 0, val, val, val, val]\n side = np.max(img_crop.shape)\n dotted = dotted * side\n\n # trim dotted vectors to be same length as respective sides of image\n row_dotted = dotted[:row_len]\n col_dotted = np.expand_dims(np.array(dotted[:col_len]), axis=-1)\n\n # overlay the dotted vectors on the original image at locations of overlap\n img_crop[[row_overlap, row_len - row_overlap], :] = row_dotted\n img_crop[:, [col_overlap, col_len - col_overlap]] = col_dotted\n\n return img_crop\n\n\ndef set_channel_colors(channel_data, plot_colors):\n \"\"\"Modifies the order of image channels so they're displayed with appropriate color in caliban\n\n Args:\n channel_data: xarray containing channels\n plot_colors: array containing the desired color for each channel\n\n Returns:\n xarray.DataArray: reordered image data to enable visualization in caliban\n \"\"\"\n\n # first define which channel index is visualized as what color by caliban\n color_order = np.array(['red', 'green', 'blue', 'cyan',\n 'magenta', 'yellow'])\n\n # create the array which will hold the final ordering of channel names\n final_channel_order = np.array(['red', 'green', 'blue', 'cyan', 'magenta',\n 'yellow'], dtype='<U100')\n\n # make sure supplied plot_colors exist as available channels\n if not np.all(np.isin(plot_colors, color_order)):\n raise ValueError('supplied plot_colors not valid, must be one of: '\n '{}'.format(color_order))\n\n # make sure all imaging channels have a plot_color\n if len(plot_colors) != channel_data.shape[-1]:\n raise ValueError('Mismatch between number of imaging channels and supplied plot colors')\n\n channel_names = channel_data.channels.values\n\n # loop through each of the supplied plot colors\n for idx in range(len(plot_colors)):\n # get the position of that color\n final_idx = np.isin(color_order, plot_colors[idx])\n\n # assign the channel corresponding to that color to that position in the final ordering\n final_channel_order[final_idx] = channel_names[idx]\n\n # reorder the xarray\n reordered_xr = data_utils.reorder_channels(new_channel_order=final_channel_order,\n input_data=channel_data)\n\n return reordered_xr\n" ]
[ [ "numpy.max", "numpy.array", "numpy.isin" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tomwhite/pynndescent
[ "0b65db53c9ebe44797cb8bb8136e3aa3fcf96681" ]
[ "pynndescent/distances.py" ]
[ "# Author: Leland McInnes <[email protected]>\n#\n# License: BSD 3 clause\nimport numpy as np\nimport numba\n\n_mock_identity = np.eye(2, dtype=np.float32)\n_mock_ones = np.ones(2, dtype=np.float32)\n\n\[email protected](fastmath=True)\ndef euclidean(x, y):\n \"\"\"Standard euclidean distance.\n\n ..math::\n D(x, y) = \\sqrt{\\sum_i (x_i - y_i)^2}\n \"\"\"\n result = 0.0\n for i in range(x.shape[0]):\n result += (x[i] - y[i]) ** 2\n return np.sqrt(result)\n\n\[email protected](fastmath=True)\ndef standardised_euclidean(x, y, sigma=_mock_ones):\n \"\"\"Euclidean distance standardised against a vector of standard\n deviations per coordinate.\n\n ..math::\n D(x, y) = \\sqrt{\\sum_i \\frac{(x_i - y_i)**2}{v_i}}\n \"\"\"\n result = 0.0\n for i in range(x.shape[0]):\n result += ((x[i] - y[i]) ** 2) / sigma[i]\n\n return np.sqrt(result)\n\n\[email protected](fastmath=True)\ndef manhattan(x, y):\n \"\"\"Manhattan, taxicab, or l1 distance.\n\n ..math::\n D(x, y) = \\sum_i |x_i - y_i|\n \"\"\"\n result = 0.0\n for i in range(x.shape[0]):\n result += np.abs(x[i] - y[i])\n\n return result\n\n\[email protected](fastmath=True)\ndef chebyshev(x, y):\n \"\"\"Chebyshev or l-infinity distance.\n\n ..math::\n D(x, y) = \\max_i |x_i - y_i|\n \"\"\"\n result = 0.0\n for i in range(x.shape[0]):\n result = max(result, np.abs(x[i] - y[i]))\n\n return result\n\n\[email protected](fastmath=True)\ndef minkowski(x, y, p=2):\n \"\"\"Minkowski distance.\n\n ..math::\n D(x, y) = \\left(\\sum_i |x_i - y_i|^p\\right)^{\\frac{1}{p}}\n\n This is a general distance. For p=1 it is equivalent to\n manhattan distance, for p=2 it is Euclidean distance, and\n for p=infinity it is Chebyshev distance. In general it is better\n to use the more specialised functions for those distances.\n \"\"\"\n result = 0.0\n for i in range(x.shape[0]):\n result += (np.abs(x[i] - y[i])) ** p\n\n return result ** (1.0 / p)\n\n\[email protected](fastmath=True)\ndef weighted_minkowski(x, y, w=_mock_identity, p=2):\n \"\"\"A weighted version of Minkowski distance.\n\n ..math::\n D(x, y) = \\left(\\sum_i w_i |x_i - y_i|^p\\right)^{\\frac{1}{p}}\n\n If weights w_i are inverse standard deviations of data in each dimension\n then this represented a standardised Minkowski distance (and is\n equivalent to standardised Euclidean distance for p=1).\n \"\"\"\n result = 0.0\n for i in range(x.shape[0]):\n result += (w[i] * np.abs(x[i] - y[i])) ** p\n\n return result ** (1.0 / p)\n\n\[email protected](fastmath=True)\ndef mahalanobis(x, y, vinv=_mock_identity):\n result = 0.0\n\n diff = np.empty(x.shape[0], dtype=np.float32)\n\n for i in range(x.shape[0]):\n diff[i] = x[i] - y[i]\n\n for i in range(x.shape[0]):\n tmp = 0.0\n for j in range(x.shape[0]):\n tmp += vinv[i, j] * diff[j]\n result += tmp * diff[i]\n\n return np.sqrt(result)\n\n\[email protected](fastmath=True)\ndef hamming(x, y):\n result = 0.0\n for i in range(x.shape[0]):\n if x[i] != y[i]:\n result += 1.0\n\n return float(result) / x.shape[0]\n\n\[email protected](fastmath=True)\ndef canberra(x, y):\n result = 0.0\n for i in range(x.shape[0]):\n denominator = np.abs(x[i]) + np.abs(y[i])\n if denominator > 0:\n result += np.abs(x[i] - y[i]) / denominator\n\n return result\n\n\[email protected](fastmath=True)\ndef bray_curtis(x, y):\n numerator = 0.0\n denominator = 0.0\n for i in range(x.shape[0]):\n numerator += np.abs(x[i] - y[i])\n denominator += np.abs(x[i] + y[i])\n\n if denominator > 0.0:\n return float(numerator) / denominator\n else:\n return 0.0\n\n\[email protected](fastmath=True)\ndef jaccard(x, y):\n num_non_zero = 0.0\n num_equal = 0.0\n for i in range(x.shape[0]):\n x_true = x[i] != 0\n y_true = y[i] != 0\n num_non_zero += (x_true or y_true)\n num_equal += (x_true and y_true)\n\n if num_non_zero == 0.0:\n return 0.0\n else:\n return float(num_non_zero - num_equal) / num_non_zero\n\n\[email protected](fastmath=True)\ndef matching(x, y):\n num_not_equal = 0.0\n for i in range(x.shape[0]):\n x_true = x[i] != 0\n y_true = y[i] != 0\n num_not_equal += (x_true != y_true)\n\n return float(num_not_equal) / x.shape[0]\n\n\[email protected](fastmath=True)\ndef dice(x, y):\n num_true_true = 0.0\n num_not_equal = 0.0\n for i in range(x.shape[0]):\n x_true = x[i] != 0\n y_true = y[i] != 0\n num_true_true += (x_true and y_true)\n num_not_equal += (x_true != y_true)\n\n return num_not_equal / (2.0 * num_true_true + num_not_equal)\n\n\[email protected](fastmath=True)\ndef kulsinski(x, y):\n num_true_true = 0.0\n num_not_equal = 0.0\n for i in range(x.shape[0]):\n x_true = x[i] != 0\n y_true = y[i] != 0\n num_true_true += (x_true and y_true)\n num_not_equal += (x_true != y_true)\n\n if num_not_equal == 0:\n return 0.0\n else:\n return float(num_not_equal - num_true_true + x.shape[0]) / \\\n (num_not_equal + x.shape[0])\n\n\[email protected](fastmath=True)\ndef rogers_tanimoto(x, y):\n num_not_equal = 0.0\n for i in range(x.shape[0]):\n x_true = x[i] != 0\n y_true = y[i] != 0\n num_not_equal += (x_true != y_true)\n\n return (2.0 * num_not_equal) / (x.shape[0] + num_not_equal)\n\n\[email protected](fastmath=True)\ndef russellrao(x, y):\n num_true_true = 0.0\n for i in range(x.shape[0]):\n x_true = x[i] != 0\n y_true = y[i] != 0\n num_true_true += (x_true and y_true)\n\n if (num_true_true == np.sum(x != 0) and\n num_true_true == np.sum(y != 0)):\n return 0.0\n else:\n return float(x.shape[0] - num_true_true) / (x.shape[0])\n\n\[email protected](fastmath=True)\ndef sokal_michener(x, y):\n num_not_equal = 0.0\n for i in range(x.shape[0]):\n x_true = x[i] != 0\n y_true = y[i] != 0\n num_not_equal += (x_true != y_true)\n\n return (2.0 * num_not_equal) / (x.shape[0] + num_not_equal)\n\n\[email protected](fastmath=True)\ndef sokal_sneath(x, y):\n num_true_true = 0.0\n num_not_equal = 0.0\n for i in range(x.shape[0]):\n x_true = x[i] != 0\n y_true = y[i] != 0\n num_true_true += (x_true and y_true)\n num_not_equal += (x_true != y_true)\n\n return num_not_equal / (0.5 * num_true_true + num_not_equal)\n\n\[email protected](fastmath=True)\ndef haversine(x, y):\n if x.shape[0] != 2:\n raise ValueError('haversine is only defined for 2 dimensional data')\n sin_lat = np.sin(0.5 * (x[0] - y[0]))\n sin_long = np.sin(0.5 * (x[1] - y[1]))\n result = np.sqrt(sin_lat ** 2 + np.cos(x[0]) * np.cos(y[0]) * sin_long ** 2)\n return 2.0 * np.arcsin(result)\n\n\[email protected](fastmath=True)\ndef yule(x, y):\n num_true_true = 0.0\n num_true_false = 0.0\n num_false_true = 0.0\n for i in range(x.shape[0]):\n x_true = x[i] != 0\n y_true = y[i] != 0\n num_true_true += (x_true and y_true)\n num_true_false += (x_true and (not y_true))\n num_false_true += ((not x_true) and y_true)\n\n num_false_false = x.shape[0] - num_true_true - num_true_false - \\\n num_false_true\n\n return (2.0 * num_true_false * num_false_true) / \\\n (num_true_true * num_false_false + num_true_false * num_false_true)\n\n\[email protected](fastmath=True)\ndef cosine(x, y):\n result = 0.0\n norm_x = 0.0\n norm_y = 0.0\n for i in range(x.shape[0]):\n result += x[i] * y[i]\n norm_x += x[i]**2\n norm_y += y[i]**2\n\n if norm_x == 0.0 or norm_y == 0.0:\n return 1.0\n else:\n return 1.0 - (result / np.sqrt(norm_x * norm_y))\n\n\[email protected](fastmath=True)\ndef correlation(x, y):\n mu_x = 0.0\n mu_y = 0.0\n norm_x = 0.0\n norm_y = 0.0\n dot_product = 0.0\n\n for i in range(x.shape[0]):\n mu_x += x[i]\n mu_y += y[i]\n\n mu_x /= x.shape[0]\n mu_y /= x.shape[0]\n\n for i in range(x.shape[0]):\n shifted_x = x[i] - mu_x\n shifted_y = y[i] - mu_y\n norm_x += shifted_x ** 2\n norm_y += shifted_y ** 2\n dot_product += shifted_x * shifted_y\n\n if dot_product == 0.0:\n return 1.0\n else:\n return (1.0 - (dot_product / np.sqrt(norm_x * norm_y)))\n\nnamed_distances = {\n # general minkowski distances\n 'euclidean': euclidean,\n 'l2': euclidean,\n 'manhattan': manhattan,\n 'taxicab': manhattan,\n 'l1': manhattan,\n 'chebyshev': chebyshev,\n 'linfinity': chebyshev,\n 'linfty': chebyshev,\n 'linf': chebyshev,\n 'minkowski': minkowski,\n # Standardised/weighted distances\n 'seuclidean': standardised_euclidean,\n 'standardised_euclidean': standardised_euclidean,\n 'wminkowski': weighted_minkowski,\n 'weighted_minkowski': weighted_minkowski,\n 'mahalanobis': mahalanobis,\n # Other distances\n 'canberra': canberra,\n 'cosine': cosine,\n 'correlation': correlation,\n 'haversine': haversine,\n 'braycurtis': bray_curtis,\n # Binary distances\n 'hamming': hamming,\n 'jaccard': jaccard,\n 'dice': dice,\n 'matching': matching,\n 'kulsinski': kulsinski,\n 'rogerstanimoto': rogers_tanimoto,\n 'russellrao': russellrao,\n 'sokalsneath': sokal_sneath,\n 'sokalmichener': sokal_michener,\n 'yule': yule,\n}\n" ]
[ [ "numpy.sqrt", "numpy.abs", "numpy.arcsin", "numpy.eye", "numpy.cos", "numpy.sin", "numpy.ones", "numpy.sum", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
610265158/shufflenetv2-series-tensorflow
[ "970e228e252a2aac1b8e05d151858d46b1443c70" ]
[ "tmp.py" ]
[ "import torch\nimport tensorflow as tf\nimport numpy as np\n\nfrom train_config import config as cfg\n\nparams_dict=np.load(cfg.MODEL.pretrained_model,allow_pickle=True).item()\n\n\n\ny = np.random.rand(1,224,224,3).astype(np.float32)\nfilterx = params_dict['ShuffleNetV2_Plus/first_conv/0/weights:0']\n\nfilterx=np.array(filterx,dtype=np.float32)\n\n\nkernel_size_effective = 3\npad_total = kernel_size_effective - 1\npad_beg = pad_total // 2\npad_end = pad_total - pad_beg\ninputs = tf.pad(y,\n [[0, 0], [pad_beg, pad_end], [pad_beg, pad_end], [0, 0]])\n\na= tf.nn.conv2d(\n inputs,\n filterx, 2, padding='VALID')\n\nwith tf.Session() as sess:\n t = (sess.run(a))\n\n\n\nx = torch.nn.Conv2d(3,16,3,stride=2,padding=1, bias = False)\nfilter = np.transpose(filterx, (3,2,0,1))\nx.weight = torch.nn.Parameter(torch.from_numpy(filter))\nz = np.transpose(y, (0,3,1,2))\nl = x(torch.from_numpy(z))\nl = l.detach().numpy()\nl = np.transpose(l,(0,2,3,1))\n\nprint(t.shape)\nprint(l.shape)\nprint(np.abs(t-l).max())" ]
[ [ "numpy.abs", "torch.nn.Conv2d", "torch.from_numpy", "numpy.random.rand", "tensorflow.pad", "numpy.transpose", "tensorflow.Session", "numpy.load", "numpy.array", "tensorflow.nn.conv2d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
mierzejk/shapenet
[ "fe7a6caf726b34e3bce7d696b846b8df446ba998" ]
[ "shapenet/layer/homogeneous_transform_layer.py" ]
[ "# author: Justus Schock ([email protected])\n\nimport torch\nimport os\nfrom torch.utils.cpp_extension import load as load_cpp\n\n\nclass HomogeneousTransformationLayer(torch.nn.Module):\n \"\"\"\n Wrapper Class to Wrap the Python and C++ API into a combined python API\n\n \"\"\"\n def __init__(self, n_dims: int, use_cpp=False):\n \"\"\"\n\n Parameters\n ----------\n n_dims : int\n number of dimensions\n use_cpp : bool\n whether or not to use C++ implementation\n\n \"\"\"\n super().__init__()\n\n self._n_params = {}\n\n if n_dims == 2:\n self._n_params[\"scale\"] = 1\n self._n_params[\"rotation\"] = 1\n self._n_params[\"translation\"] = 2\n elif n_dims == 3:\n self._n_params[\"scale\"] = 3\n self._n_params[\"rotation\"] = 3\n self._n_params[\"translation\"] = 3\n\n if use_cpp:\n self._layer = _HomogeneousTransformationLayerCpp(n_dims)\n else:\n self._layer = _HomogeneousTransformationLayerPy(n_dims)\n\n total_params = 0\n for key, val in self._n_params.items():\n self.register_buffer(\"_indices_%s_params\" % key,\n torch.arange(total_params, total_params + val)\n )\n total_params += val\n\n def forward(self, shapes: torch.Tensor, params: torch.Tensor):\n \"\"\"\n Actual prediction\n\n Parameters\n ----------\n shapes : :class:`torch.Tensor`\n shapes before applied global transformation\n params : :class:`torch.Tensor`\n parameters specifying the global transformation\n\n Returns\n -------\n :class:`torch.Tensor`\n Transformed shapes\n\n \"\"\"\n rotation_params = params.index_select(\n dim=1, index=getattr(self, \"_indices_rotation_params\")\n )\n scale_params = params.index_select(\n dim=1, index=getattr(self, \"_indices_scale_params\")\n )\n translation_params = params.index_select(\n dim=1, index=getattr(self, \"_indices_translation_params\")\n )\n\n return self._layer(shapes, rotation_params, translation_params,\n scale_params)\n\n @property\n def num_params(self):\n num_params = 0\n for key, val in self._n_params.items():\n num_params += val\n\n return num_params\n\n\nclass _HomogeneousTransformationLayerCpp(torch.nn.Module):\n \"\"\"\n Module to perform homogeneous transformations in 2D and 3D\n (Implemented in C++)\n\n \"\"\"\n def __init__(self, n_dims, verbose=True):\n \"\"\"\n\n Parameters\n ----------\n n_dims : int\n number of dimensions\n verbose : float\n if True: verbosity during C++ loading\n\n \"\"\"\n super().__init__()\n\n homogen_trafo = torch.zeros(1, n_dims + 1, n_dims + 1)\n homogen_trafo[:, -1, :-1] = 0.\n homogen_trafo[:, -1, -1] = 1.\n\n self.register_buffer(\"_trafo_matrix\", homogen_trafo)\n self._n_dims = n_dims\n\n self._func = load_cpp(\"homogeneous_transform_function\",\n sources=[\n os.path.join(\n os.path.split(__file__)[0],\n \"homogeneous_transform_layer.cpp\")],\n verbose=verbose)\n\n def forward(self, shapes: torch.Tensor, rotation_params: torch.Tensor,\n translation_params: torch.Tensor, scale_params: torch.Tensor):\n \"\"\"\n ensembles the homogeneous transformation matrix and applies it to the\n shape tensor\n\n Parameters\n ----------\n shapes : :class:`torch.Tensor`\n shapes to transform\n rotation_params : :class:`torch.Tensor`\n parameters specifying the rotation (one per DoF)\n translation_params : :class:`torch.Tensor`\n parameters specifying the translation (one per dimension)\n scale_params : :class:`torch.Tensor`\n parameter specifying the global scaling factor\n (currently only isotropic scaling supported)\n\n Returns\n -------\n :class:`torch.Tensor`\n the transformed shapes in cartesian coordinates\n\n \"\"\"\n transformed_shapes = self._func.forward(shapes,\n getattr(self,\n \"_trafo_matrix\"),\n rotation_params,\n translation_params,\n scale_params\n )\n\n return transformed_shapes\n\n\nclass _HomogeneousTransformationLayerPy(torch.nn.Module):\n \"\"\"\n Module to perform homogeneous transformations in 2D and 3D\n (Implemented in Python)\n\n \"\"\"\n\n def __init__(self, n_dims):\n \"\"\"\n\n Parameters\n ----------\n n_dims : int\n number of dimensions\n\n \"\"\"\n super().__init__()\n\n homogen_trafo = torch.zeros(1, n_dims+1, n_dims+1)\n homogen_trafo[:, -1, :-1] = 0.\n homogen_trafo[:, -1, -1] = 1.\n\n self.register_buffer(\"_trafo_matrix\", homogen_trafo)\n self._n_dims = n_dims\n\n def forward(self, shapes: torch.Tensor, rotation_params: torch.Tensor,\n translation_params: torch.Tensor, scale_params: torch.Tensor):\n \"\"\"\n ensembles the homogeneous transformation matrix and applies it to the\n shape tensor\n\n Parameters\n ----------\n shapes : :class:`torch.Tensor`\n shapes to transform\n rotation_params : :class:`torch.Tensor`\n parameters specifying the rotation (one per DoF)\n translation_params : :class:`torch.Tensor`\n parameters specifying the translation (one per dimension)\n scale_params : :class:`torch.Tensor`\n parameter specifying the global scaling factor\n (currently only isotropic scaling supported)\n\n Returns\n -------\n :class:`torch.Tensor`\n the transformed shapes in cartesian coordinates\n\n \"\"\"\n\n assert shapes.size(-1) == self._n_dims, \"Layer for other \" \\\n \"dimensionality specified\"\n\n trafo_matrix = self._ensemble_trafo(rotation_params,\n translation_params, scale_params)\n\n homogen_shapes = torch.cat([shapes,\n shapes.new_ones(*shapes.size()[:-1], 1)],\n dim=-1)\n\n transformed_shapes = torch.bmm(homogen_shapes,\n trafo_matrix.permute(0, 2, 1))\n\n transformed_shapes = transformed_shapes[..., :-1]\n # transformed_shapes = transformed_shapes[..., :-1] / transformed_shapes[..., -1].unsqueeze(-1)\n \n return transformed_shapes\n\n def _ensemble_trafo(self, rotation_params: torch.Tensor,\n translation_params: torch.Tensor,\n scale_params: torch.Tensor):\n \"\"\"\n ensembles the transformation matrix in 2D and 3D\n\n Parameters\n ----------\n rotation_params : :class:`torch.Tensor`\n parameters specifying the rotation (one per DoF)\n translation_params : :class:`torch.Tensor`\n parameters specifying the translation (one per dimension)\n scale_params : :class:`torch.Tensor`\n parameter specifying the global scaling factor\n (currently only isotropic scaling supported)\n\n Returns\n -------\n :class:`torch.Tensor`\n transformation matrix\n\n \"\"\"\n\n rotation_params = rotation_params.view(rotation_params.size()[:2])\n translation_params = translation_params.view(\n translation_params.size()[:2])\n scale_params = scale_params.view(scale_params.size()[:2])\n\n if self._n_dims == 2:\n return self._ensemble_2d_matrix(rotation_params,\n translation_params, scale_params)\n elif self._n_dims == 3:\n return self._ensemble_3d_matrix(rotation_params,\n translation_params, scale_params)\n else:\n raise NotImplementedError(\"Implementation for n_dims = %d \"\n \"not available\" % self._n_dims)\n\n def _ensemble_2d_matrix(self, rotation_params: torch.Tensor,\n translation_params: torch.Tensor,\n scale_params: torch.Tensor):\n \"\"\"\n ensembles the homogeneous transformation matrix for 2D\n\n Parameters\n ----------\n rotation_params : :class:`torch.Tensor`\n parameters specifying the rotation (one parameter)\n translation_params : :class:`torch.Tensor`\n parameters specifying the translation (two parameters)\n scale_params : :class:`torch.Tensor`\n parameter specifying the global scaling factor (one parameter)\n (currently only isotropic scaling supported)\n\n Returns\n -------\n :class:`torch.Tensor`\n 2D transformation matrix\n\n \"\"\"\n\n homogen_trafo = getattr(self, \"_trafo_matrix\").repeat(\n scale_params.size(0), 1, 1).clone()\n\n homogen_trafo[:, 0, 0] = (scale_params *\n rotation_params.cos())[:, 0].clone()\n # s*sin\\theta\n homogen_trafo[:, 0, 1] = (scale_params *\n rotation_params.sin())[:, 0].clone()\n # -s*sin\\theta\n homogen_trafo[:, 1, 0] = (-scale_params *\n rotation_params.sin())[:, 0].clone()\n # s*cos\\theta\n homogen_trafo[:, 1, 1] = (scale_params *\n rotation_params.cos())[:, 0].clone()\n\n # translation params\n homogen_trafo[:, :-1, -1] = translation_params.clone()\n\n return homogen_trafo\n\n def _ensemble_3d_matrix(self, rotation_params: torch.Tensor,\n translation_params: torch.Tensor,\n scale_params: torch.Tensor):\n \"\"\"\n ensembles the homogeneous transformation matrix for 3D\n\n Parameters\n ----------\n rotation_params : :class:`torch.Tensor`\n parameters specifying the rotation (three parameters)\n translation_params : :class:`torch.Tensor`\n parameters specifying the translation (three parameters)\n scale_params : :class:`torch.Tensor`\n parameter specifying the global scaling factor (one parameter)\n (currently only isotropic scaling supported)\n\n Returns\n -------\n :class:`torch.Tensor`\n 3D transformation matrix\n\n \"\"\"\n\n homogen_trafo = getattr(self, \"_trafo_matrix\").repeat(\n scale_params.size(0), 1, 1).clone()\n\n roll = rotation_params[:, 2].unsqueeze(-1)\n pitch = rotation_params[:, 1].unsqueeze(-1)\n yaw = rotation_params[:, 0].unsqueeze(-1)\n\n # Note that the elements inside the transformation matrix are swapped\n # due to the zyx convention\n\n # s*(cos(pitch)*cos(roll))\n homogen_trafo[:, 0, 0] = (scale_params *\n (pitch.cos() * roll.cos()))[:, 0].clone()\n\n # s*(cos(pitch)*sin(roll))\n homogen_trafo[:, 0, 1] = (scale_params *\n (pitch.cos() * roll.sin()))[:, 0].clone()\n\n # s*(-sin(pitch))\n homogen_trafo[:, 0, 2] = (scale_params *\n (-pitch.sin()))[:, 0].clone()\n\n # s*(sin(yaw)*sin(pitch)*cos(roll) - cos(yaw)*sin(roll))\n homogen_trafo[:, 1, 0] = (scale_params *\n (yaw.sin() * pitch.sin() * roll.cos() -\n yaw.cos() * roll.sin()))[:, 0].clone()\n\n # s*(sin(yaw)*sin(pitch)*sin(roll) + cos(yaw)*cos(roll))\n homogen_trafo[:, 1, 1] = (scale_params *\n (yaw.sin() * pitch.sin() * roll.sin() +\n yaw.cos() * roll.cos()))[:, 0].clone()\n\n # s*(sin(yaw)*cos(pitch))\n homogen_trafo[:, 1, 2] = (scale_params *\n (yaw.sin() * pitch.cos()))[:, 0].clone()\n\n # s*(cos(yaw)*sin(pitch)*cos(roll) + sin(yaw)*sin(roll))\n homogen_trafo[:, 2, 0] = (scale_params *\n (yaw.cos() * pitch.sin() * roll.cos() +\n yaw.sin() * roll.sin()))[:, 0].clone()\n\n # s*(cos(yaw)*sin(pitch)*sin(roll)-sin(yaw)*cos(roll))\n homogen_trafo[:, 2, 1] = (scale_params *\n (yaw.cos() * pitch.sin() * roll.sin() -\n yaw.sin() * roll.cos()))[:, 0].clone()\n\n # s*(cos(yaw)*cos(pitch))\n homogen_trafo[:, 2, 2] = (scale_params *\n (yaw.cos() * pitch.cos()))[:, 0].clone()\n\n # translation params\n homogen_trafo[:, :-1, -1] = translation_params.clone()\n\n return homogen_trafo\n\n\nif __name__ == '__main__':\n shapes_2d = torch.rand(10, 68, 2)\n rotation_params_2d = torch.rand(10, 1, 1, 1)\n # translation_params_2d = torch.rand(10, 2, 1, 1)\n translation_params_2d = torch.rand(10, 2, 1, 1)\n scale_params_2d = torch.rand(10, 1, 1, 1)\n\n print(\"Creating Python Layer\")\n layer_2d_py = _HomogeneousTransformationLayerPy(n_dims=2)\n print(\"Creating Cpp shapelayer\")\n layer_2d_cpp = _HomogeneousTransformationLayerCpp(n_dims=2)\n\n result_2d_py = layer_2d_py(shapes_2d, rotation_params_2d, translation_params_2d,\n scale_params_2d)\n result_2d_cpp = layer_2d_cpp(shapes_2d, rotation_params_2d, translation_params_2d,\n scale_params_2d)\n\n shapes_3d = torch.rand(10, 68, 3)\n rotation_params_3d = torch.rand(10, 3, 1, 1)\n # rotation_params_3d = torch.zeros(10, 3, 1, 1)\n translation_params_3d = torch.rand(10, 3, 1, 1)\n # translation_params_3d = torch.zeros(10, 3, 1, 1)\n scale_params_3d = torch.rand(10, 3, 1, 1)\n\n layer_3d_py = _HomogeneousTransformationLayerPy(n_dims=3)\n layer_3d_cpp = _HomogeneousTransformationLayerCpp(n_dims=3)\n\n result_3d_py = layer_3d_py(shapes_3d, rotation_params_3d, translation_params_3d,\n scale_params_3d)\n result_3d_cpp = layer_3d_cpp(shapes_3d, rotation_params_3d, translation_params_3d,\n scale_params_3d)\n\n print(\"Diff 2d: %f\" % (result_2d_py-result_2d_cpp).abs().sum())\n print(\"Diff 3d: %f\" % (result_3d_py-result_3d_cpp).abs().sum())\n\n" ]
[ [ "torch.arange", "torch.rand", "torch.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
soranjh/pennylane
[ "deffcee1615687d74a25f4385dd1f097d0d7e9cd" ]
[ "pennylane/devices/default_qubit.py" ]
[ "# Copyright 2018-2021 Xanadu Quantum Technologies Inc.\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nr\"\"\"\nThe default.qubit device is PennyLane's standard qubit-based device.\n\nIt implements the necessary :class:`~pennylane._device.Device` methods as well as some built-in\n:mod:`qubit operations <pennylane.ops.qubit>`, and provides a very simple pure state\nsimulation of a qubit-based quantum circuit architecture.\n\"\"\"\nimport itertools\nimport functools\nfrom string import ascii_letters as ABC\n\nimport numpy as np\nfrom scipy.sparse import coo_matrix\n\nimport pennylane as qml\nfrom pennylane import QubitDevice, DeviceError, QubitStateVector, BasisState\nfrom pennylane.ops.qubit.attributes import diagonal_in_z_basis\nfrom pennylane.wires import WireError\nfrom .._version import __version__\n\nABC_ARRAY = np.array(list(ABC))\n\n# tolerance for numerical errors\ntolerance = 1e-10\nSQRT2INV = 1 / np.sqrt(2)\nTPHASE = np.exp(1j * np.pi / 4)\n\n\ndef _get_slice(index, axis, num_axes):\n \"\"\"Allows slicing along an arbitrary axis of an array or tensor.\n\n Args:\n index (int): the index to access\n axis (int): the axis to slice into\n num_axes (int): total number of axes\n\n Returns:\n tuple[slice or int]: a tuple that can be used to slice into an array or tensor\n\n **Example:**\n\n Accessing the 2 index along axis 1 of a 3-axis array:\n\n >>> sl = _get_slice(2, 1, 3)\n >>> sl\n (slice(None, None, None), 2, slice(None, None, None))\n >>> a = np.arange(27).reshape((3, 3, 3))\n >>> a[sl]\n array([[ 6, 7, 8],\n [15, 16, 17],\n [24, 25, 26]])\n \"\"\"\n idx = [slice(None)] * num_axes\n idx[axis] = index\n return tuple(idx)\n\n\n# pylint: disable=unused-argument\nclass DefaultQubit(QubitDevice):\n \"\"\"Default qubit device for PennyLane.\n\n Args:\n wires (int, Iterable[Number, str]): Number of subsystems represented by the device,\n or iterable that contains unique labels for the subsystems as numbers (i.e., ``[-1, 0, 2]``)\n or strings (``['ancilla', 'q1', 'q2']``). Default 1 if not specified.\n shots (None, int): How many times the circuit should be evaluated (or sampled) to estimate\n the expectation values. Defaults to ``None`` if not specified, which means that the device\n returns analytical results.\n cache (int): Number of device executions to store in a cache to speed up subsequent\n executions. A value of ``0`` indicates that no caching will take place. Once filled,\n older elements of the cache are removed and replaced with the most recent device\n executions to keep the cache up to date.\n \"\"\"\n\n name = \"Default qubit PennyLane plugin\"\n short_name = \"default.qubit\"\n pennylane_requires = __version__\n version = __version__\n author = \"Xanadu Inc.\"\n\n operations = {\n \"Identity\",\n \"BasisState\",\n \"QubitStateVector\",\n \"QubitUnitary\",\n \"ControlledQubitUnitary\",\n \"MultiControlledX\",\n \"DiagonalQubitUnitary\",\n \"PauliX\",\n \"PauliY\",\n \"PauliZ\",\n \"MultiRZ\",\n \"Hadamard\",\n \"S\",\n \"T\",\n \"SX\",\n \"CNOT\",\n \"SWAP\",\n \"ISWAP\",\n \"SISWAP\",\n \"SQISW\",\n \"CSWAP\",\n \"Toffoli\",\n \"CY\",\n \"CZ\",\n \"PhaseShift\",\n \"ControlledPhaseShift\",\n \"CPhase\",\n \"RX\",\n \"RY\",\n \"RZ\",\n \"Rot\",\n \"CRX\",\n \"CRY\",\n \"CRZ\",\n \"CRot\",\n \"IsingXX\",\n \"IsingYY\",\n \"IsingZZ\",\n \"SingleExcitation\",\n \"SingleExcitationPlus\",\n \"SingleExcitationMinus\",\n \"DoubleExcitation\",\n \"DoubleExcitationPlus\",\n \"DoubleExcitationMinus\",\n \"QubitCarry\",\n \"QubitSum\",\n \"OrbitalRotation\",\n \"QFT\",\n }\n\n observables = {\n \"PauliX\",\n \"PauliY\",\n \"PauliZ\",\n \"Hadamard\",\n \"Hermitian\",\n \"Identity\",\n \"Projector\",\n \"SparseHamiltonian\",\n \"Hamiltonian\",\n }\n\n def __init__(self, wires, *, shots=None, cache=0, analytic=None):\n super().__init__(wires, shots, cache=cache, analytic=analytic)\n\n # Create the initial state. Internally, we store the\n # state as an array of dimension [2]*wires.\n self._state = self._create_basis_state(0)\n self._pre_rotated_state = self._state\n\n self._apply_ops = {\n \"PauliX\": self._apply_x,\n \"PauliY\": self._apply_y,\n \"PauliZ\": self._apply_z,\n \"Hadamard\": self._apply_hadamard,\n \"S\": self._apply_s,\n \"T\": self._apply_t,\n \"SX\": self._apply_sx,\n \"CNOT\": self._apply_cnot,\n \"SWAP\": self._apply_swap,\n \"CZ\": self._apply_cz,\n \"Toffoli\": self._apply_toffoli,\n }\n\n @functools.lru_cache()\n def map_wires(self, wires):\n # temporarily overwrite this method to bypass\n # wire map that produces Wires objects\n try:\n mapped_wires = [self.wire_map[w] for w in wires]\n except KeyError as e:\n raise WireError(\n f\"Did not find some of the wires {wires.labels} on device with wires {self.wires.labels}.\"\n ) from e\n\n return mapped_wires\n\n def define_wire_map(self, wires):\n # temporarily overwrite this method to bypass\n # wire map that produces Wires objects\n consecutive_wires = range(self.num_wires)\n wire_map = zip(wires, consecutive_wires)\n return dict(wire_map)\n\n def apply(self, operations, rotations=None, **kwargs):\n rotations = rotations or []\n\n # apply the circuit operations\n for i, operation in enumerate(operations):\n\n if i > 0 and isinstance(operation, (QubitStateVector, BasisState)):\n raise DeviceError(\n f\"Operation {operation.name} cannot be used after other Operations have already been applied \"\n f\"on a {self.short_name} device.\"\n )\n\n if isinstance(operation, QubitStateVector):\n self._apply_state_vector(operation.parameters[0], operation.wires)\n elif isinstance(operation, BasisState):\n self._apply_basis_state(operation.parameters[0], operation.wires)\n else:\n self._state = self._apply_operation(self._state, operation)\n\n # store the pre-rotated state\n self._pre_rotated_state = self._state\n\n # apply the circuit rotations\n for operation in rotations:\n self._state = self._apply_operation(self._state, operation)\n\n def _apply_operation(self, state, operation):\n \"\"\"Applies operations to the input state.\n\n Args:\n state (array[complex]): input state\n operation (~.Operation): operation to apply on the device\n\n Returns:\n array[complex]: output state\n \"\"\"\n wires = operation.wires\n\n if operation.base_name in self._apply_ops:\n axes = self.wires.indices(wires)\n return self._apply_ops[operation.base_name](state, axes, inverse=operation.inverse)\n\n matrix = self._get_unitary_matrix(operation)\n\n if operation in diagonal_in_z_basis:\n return self._apply_diagonal_unitary(state, matrix, wires)\n if len(wires) <= 2:\n # Einsum is faster for small gates\n return self._apply_unitary_einsum(state, matrix, wires)\n\n return self._apply_unitary(state, matrix, wires)\n\n def _apply_x(self, state, axes, **kwargs):\n \"\"\"Applies a PauliX gate by rolling 1 unit along the axis specified in ``axes``.\n\n Rolling by 1 unit along the axis means that the :math:`|0 \\rangle` state with index ``0`` is\n shifted to the :math:`|1 \\rangle` state with index ``1``. Likewise, since rolling beyond\n the last index loops back to the first, :math:`|1 \\rangle` is transformed to\n :math:`|0\\rangle`.\n\n Args:\n state (array[complex]): input state\n axes (List[int]): target axes to apply transformation\n\n Returns:\n array[complex]: output state\n \"\"\"\n return self._roll(state, 1, axes[0])\n\n def _apply_y(self, state, axes, **kwargs):\n \"\"\"Applies a PauliY gate by adding a negative sign to the 1 index along the axis specified\n in ``axes``, rolling one unit along the same axis, and multiplying the result by 1j.\n\n Args:\n state (array[complex]): input state\n axes (List[int]): target axes to apply transformation\n\n Returns:\n array[complex]: output state\n \"\"\"\n return 1j * self._apply_x(self._apply_z(state, axes), axes)\n\n def _apply_z(self, state, axes, **kwargs):\n \"\"\"Applies a PauliZ gate by adding a negative sign to the 1 index along the axis specified\n in ``axes``.\n\n Args:\n state (array[complex]): input state\n axes (List[int]): target axes to apply transformation\n\n Returns:\n array[complex]: output state\n \"\"\"\n return self._apply_phase(state, axes, -1)\n\n def _apply_hadamard(self, state, axes, **kwargs):\n \"\"\"Apply the Hadamard gate by combining the results of applying the PauliX and PauliZ gates.\n\n Args:\n state (array[complex]): input state\n axes (List[int]): target axes to apply transformation\n\n Returns:\n array[complex]: output state\n \"\"\"\n state_x = self._apply_x(state, axes)\n state_z = self._apply_z(state, axes)\n return SQRT2INV * (state_x + state_z)\n\n def _apply_s(self, state, axes, inverse=False):\n return self._apply_phase(state, axes, 1j, inverse)\n\n def _apply_t(self, state, axes, inverse=False):\n return self._apply_phase(state, axes, TPHASE, inverse)\n\n def _apply_sx(self, state, axes, inverse=False):\n \"\"\"Apply the Square Root X gate.\n\n Args:\n state (array[complex]): input state\n axes (List[int]): target axes to apply transformation\n\n Returns:\n array[complex]: output state\n \"\"\"\n if inverse:\n return 0.5 * ((1 - 1j) * state + (1 + 1j) * self._apply_x(state, axes))\n\n return 0.5 * ((1 + 1j) * state + (1 - 1j) * self._apply_x(state, axes))\n\n def _apply_cnot(self, state, axes, **kwargs):\n \"\"\"Applies a CNOT gate by slicing along the first axis specified in ``axes`` and then\n applying an X transformation along the second axis.\n\n By slicing along the first axis, we are able to select all of the amplitudes with a\n corresponding :math:`|1\\rangle` for the control qubit. This means we then just need to apply\n a :class:`~.PauliX` (NOT) gate to the result.\n\n Args:\n state (array[complex]): input state\n axes (List[int]): target axes to apply transformation\n\n Returns:\n array[complex]: output state\n \"\"\"\n sl_0 = _get_slice(0, axes[0], self.num_wires)\n sl_1 = _get_slice(1, axes[0], self.num_wires)\n\n # We will be slicing into the state according to state[sl_1], giving us all of the\n # amplitudes with a |1> for the control qubit. The resulting array has lost an axis\n # relative to state and we need to be careful about the axis we apply the PauliX rotation\n # to. If axes[1] is larger than axes[0], then we need to shift the target axis down by\n # one, otherwise we can leave as-is. For example: a state has [0, 1, 2, 3], control=1,\n # target=3. Then, state[sl_1] has 3 axes and target=3 now corresponds to the second axis.\n if axes[1] > axes[0]:\n target_axes = [axes[1] - 1]\n else:\n target_axes = [axes[1]]\n\n state_x = self._apply_x(state[sl_1], axes=target_axes)\n return self._stack([state[sl_0], state_x], axis=axes[0])\n\n def _apply_toffoli(self, state, axes, **kwargs):\n \"\"\"Applies a Toffoli gate by slicing along the axis of the greater control qubit, slicing\n each of the resulting sub-arrays along the axis of the smaller control qubit, and then applying\n an X transformation along the axis of the target qubit of the fourth sub-sub-array.\n\n By performing two consecutive slices in this way, we are able to select all of the amplitudes with\n a corresponding :math:`|11\\rangle` for the two control qubits. This means we then just need to apply\n a :class:`~.PauliX` (NOT) gate to the result.\n\n Args:\n state (array[complex]): input state\n axes (List[int]): target axes to apply transformation\n\n Returns:\n array[complex]: output state\n \"\"\"\n cntrl_max = np.argmax(axes[:2])\n cntrl_min = cntrl_max ^ 1\n sl_a0 = _get_slice(0, axes[cntrl_max], self.num_wires)\n sl_a1 = _get_slice(1, axes[cntrl_max], self.num_wires)\n sl_b0 = _get_slice(0, axes[cntrl_min], self.num_wires - 1)\n sl_b1 = _get_slice(1, axes[cntrl_min], self.num_wires - 1)\n\n # If both controls are smaller than the target, shift the target axis down by two. If one\n # control is greater and one control is smaller than the target, shift the target axis\n # down by one. If both controls are greater than the target, leave the target axis as-is.\n if axes[cntrl_min] > axes[2]:\n target_axes = [axes[2]]\n elif axes[cntrl_max] > axes[2]:\n target_axes = [axes[2] - 1]\n else:\n target_axes = [axes[2] - 2]\n\n # state[sl_a1][sl_b1] gives us all of the amplitudes with a |11> for the two control qubits.\n state_x = self._apply_x(state[sl_a1][sl_b1], axes=target_axes)\n state_stacked_a1 = self._stack([state[sl_a1][sl_b0], state_x], axis=axes[cntrl_min])\n return self._stack([state[sl_a0], state_stacked_a1], axis=axes[cntrl_max])\n\n def _apply_swap(self, state, axes, **kwargs):\n \"\"\"Applies a SWAP gate by performing a partial transposition along the specified axes.\n\n Args:\n state (array[complex]): input state\n axes (List[int]): target axes to apply transformation\n\n Returns:\n array[complex]: output state\n \"\"\"\n all_axes = list(range(len(state.shape)))\n all_axes[axes[0]] = axes[1]\n all_axes[axes[1]] = axes[0]\n return self._transpose(state, all_axes)\n\n def _apply_cz(self, state, axes, **kwargs):\n \"\"\"Applies a CZ gate by slicing along the first axis specified in ``axes`` and then\n applying a Z transformation along the second axis.\n\n Args:\n state (array[complex]): input state\n axes (List[int]): target axes to apply transformation\n\n Returns:\n array[complex]: output state\n \"\"\"\n sl_0 = _get_slice(0, axes[0], self.num_wires)\n sl_1 = _get_slice(1, axes[0], self.num_wires)\n\n if axes[1] > axes[0]:\n target_axes = [axes[1] - 1]\n else:\n target_axes = [axes[1]]\n\n state_z = self._apply_z(state[sl_1], axes=target_axes)\n return self._stack([state[sl_0], state_z], axis=axes[0])\n\n def _apply_phase(self, state, axes, parameters, inverse=False):\n \"\"\"Applies a phase onto the 1 index along the axis specified in ``axes``.\n\n Args:\n state (array[complex]): input state\n axes (List[int]): target axes to apply transformation\n parameters (float): phase to apply\n inverse (bool): whether to apply the inverse phase\n\n Returns:\n array[complex]: output state\n \"\"\"\n num_wires = len(state.shape)\n sl_0 = _get_slice(0, axes[0], num_wires)\n sl_1 = _get_slice(1, axes[0], num_wires)\n\n phase = self._conj(parameters) if inverse else parameters\n return self._stack([state[sl_0], phase * state[sl_1]], axis=axes[0])\n\n def expval(self, observable, shot_range=None, bin_size=None):\n \"\"\"Returns the expectation value of a Hamiltonian observable. When the observable is a\n ``SparseHamiltonian`` object, the expectation value is computed directly for the full\n Hamiltonian, which leads to faster execution.\n\n Args:\n observable (~.Observable): a PennyLane observable\n shot_range (tuple[int]): 2-tuple of integers specifying the range of samples\n to use. If not specified, all samples are used.\n bin_size (int): Divides the shot range into bins of size ``bin_size``, and\n returns the measurement statistic separately over each bin. If not\n provided, the entire shot range is treated as a single bin.\n\n Returns:\n float: returns the expectation value of the observable\n \"\"\"\n # intercept other Hamiltonians\n # TODO: Ideally, this logic should not live in the Device, but be moved\n # to a component that can be re-used by devices as needed.\n if observable.name in (\"Hamiltonian\", \"SparseHamiltonian\"):\n assert self.shots is None, f\"{observable.name} must be used with shots=None\"\n\n backprop_mode = (\n not isinstance(self.state, np.ndarray)\n or any(not isinstance(d, (float, np.ndarray)) for d in observable.data)\n ) and observable.name == \"Hamiltonian\"\n\n if backprop_mode:\n # We must compute the expectation value assuming that the Hamiltonian\n # coefficients *and* the quantum states are tensor objects.\n\n # Compute <psi| H |psi> via sum_i coeff_i * <psi| PauliWord |psi> using a sparse\n # representation of the Pauliword\n res = qml.math.cast(qml.math.convert_like(0.0, observable.data), dtype=complex)\n interface = qml.math.get_interface(self.state)\n\n # Note: it is important that we use the Hamiltonian's data and not the coeffs attribute.\n # This is because the .data attribute may be 'unwrapped' as required by the interfaces,\n # whereas the .coeff attribute will always be the same input dtype that the user provided.\n for op, coeff in zip(observable.ops, observable.data):\n\n # extract a scipy.sparse.coo_matrix representation of this Pauli word\n coo = qml.operation.Tensor(op).sparse_matrix(wires=self.wires)\n Hmat = qml.math.cast(qml.math.convert_like(coo.data, self.state), \"complex128\")\n\n product = (\n qml.math.gather(qml.math.conj(self.state), coo.row)\n * Hmat\n * qml.math.gather(self.state, coo.col)\n )\n c = qml.math.convert_like(coeff, product)\n\n if interface == \"tensorflow\":\n c = qml.math.cast(c, \"complex128\")\n\n res = qml.math.convert_like(res, product) + qml.math.sum(c * product)\n\n else:\n # Coefficients and the state are not trainable, we can be more\n # efficient in how we compute the Hamiltonian sparse matrix.\n\n if observable.name == \"Hamiltonian\":\n Hmat = qml.utils.sparse_hamiltonian(observable, wires=self.wires)\n elif observable.name == \"SparseHamiltonian\":\n Hmat = observable.matrix\n\n state = qml.math.toarray(self.state)\n res = coo_matrix.dot(\n coo_matrix(qml.math.conj(state)),\n coo_matrix.dot(Hmat, coo_matrix(state.reshape(len(self.state), 1))),\n ).toarray()[0]\n\n if observable.name == \"Hamiltonian\":\n res = qml.math.squeeze(res)\n\n return qml.math.real(res)\n\n return super().expval(observable, shot_range=shot_range, bin_size=bin_size)\n\n def _get_unitary_matrix(self, unitary): # pylint: disable=no-self-use\n \"\"\"Return the matrix representing a unitary operation.\n\n Args:\n unitary (~.Operation): a PennyLane unitary operation\n\n Returns:\n array[complex]: Returns a 2D matrix representation of\n the unitary in the computational basis, or, in the case of a diagonal unitary,\n a 1D array representing the matrix diagonal.\n \"\"\"\n if unitary in diagonal_in_z_basis:\n return unitary.eigvals\n\n return unitary.matrix\n\n @classmethod\n def capabilities(cls):\n capabilities = super().capabilities().copy()\n capabilities.update(\n model=\"qubit\",\n supports_reversible_diff=True,\n supports_inverse_operations=True,\n supports_analytic_computation=True,\n returns_state=True,\n passthru_devices={\n \"tf\": \"default.qubit.tf\",\n \"torch\": \"default.qubit.torch\",\n \"autograd\": \"default.qubit.autograd\",\n \"jax\": \"default.qubit.jax\",\n },\n )\n return capabilities\n\n def _create_basis_state(self, index):\n \"\"\"Return a computational basis state over all wires.\n\n Args:\n index (int): integer representing the computational basis state\n\n Returns:\n array[complex]: complex array of shape ``[2]*self.num_wires``\n representing the statevector of the basis state\n \"\"\"\n state = np.zeros(2 ** self.num_wires, dtype=np.complex128)\n state[index] = 1\n state = self._asarray(state, dtype=self.C_DTYPE)\n return self._reshape(state, [2] * self.num_wires)\n\n @property\n def state(self):\n return self._flatten(self._pre_rotated_state)\n\n def density_matrix(self, wires):\n \"\"\"Returns the reduced density matrix of a given set of wires.\n\n Args:\n wires (Wires): wires of the reduced system.\n\n Returns:\n array[complex]: complex tensor of shape ``(2 ** len(wires), 2 ** len(wires))``\n representing the reduced density matrix.\n \"\"\"\n dim = self.num_wires\n state = self._pre_rotated_state\n\n # Return the full density matrix by using numpy tensor product\n if wires == self.wires:\n density_matrix = self._tensordot(state, self._conj(state), 0)\n density_matrix = self._reshape(density_matrix, (2 ** len(wires), 2 ** len(wires)))\n return density_matrix\n\n complete_system = list(range(0, dim))\n traced_system = [x for x in complete_system if x not in wires.labels]\n\n # Return the reduced density matrix by using numpy tensor product\n density_matrix = self._tensordot(\n state, self._conj(state), axes=(traced_system, traced_system)\n )\n density_matrix = self._reshape(density_matrix, (2 ** len(wires), 2 ** len(wires)))\n\n return density_matrix\n\n def _apply_state_vector(self, state, device_wires):\n \"\"\"Initialize the internal state vector in a specified state.\n\n Args:\n state (array[complex]): normalized input state of length\n ``2**len(wires)``\n device_wires (Wires): wires that get initialized in the state\n \"\"\"\n\n # translate to wire labels used by device\n device_wires = self.map_wires(device_wires)\n\n state = self._asarray(state, dtype=self.C_DTYPE)\n n_state_vector = state.shape[0]\n\n if len(qml.math.shape(state)) != 1 or n_state_vector != 2 ** len(device_wires):\n raise ValueError(\"State vector must be of length 2**wires.\")\n\n norm = qml.math.linalg.norm(state, ord=2)\n if not qml.math.is_abstract(norm):\n if not qml.math.allclose(norm, 1.0, atol=tolerance):\n raise ValueError(\"Sum of amplitudes-squared does not equal one.\")\n\n if len(device_wires) == self.num_wires and sorted(device_wires) == device_wires:\n # Initialize the entire wires with the state\n self._state = self._reshape(state, [2] * self.num_wires)\n return\n\n # generate basis states on subset of qubits via the cartesian product\n basis_states = np.array(list(itertools.product([0, 1], repeat=len(device_wires))))\n\n # get basis states to alter on full set of qubits\n unravelled_indices = np.zeros((2 ** len(device_wires), self.num_wires), dtype=int)\n unravelled_indices[:, device_wires] = basis_states\n\n # get indices for which the state is changed to input state vector elements\n ravelled_indices = np.ravel_multi_index(unravelled_indices.T, [2] * self.num_wires)\n\n state = self._scatter(ravelled_indices, state, [2 ** self.num_wires])\n state = self._reshape(state, [2] * self.num_wires)\n self._state = self._asarray(state, dtype=self.C_DTYPE)\n\n def _apply_basis_state(self, state, wires):\n \"\"\"Initialize the state vector in a specified computational basis state.\n\n Args:\n state (array[int]): computational basis state of shape ``(wires,)``\n consisting of 0s and 1s.\n wires (Wires): wires that the provided computational state should be initialized on\n \"\"\"\n # translate to wire labels used by device\n device_wires = self.map_wires(wires)\n\n # length of basis state parameter\n n_basis_state = len(state)\n\n if not set(state.tolist()).issubset({0, 1}):\n raise ValueError(\"BasisState parameter must consist of 0 or 1 integers.\")\n\n if n_basis_state != len(device_wires):\n raise ValueError(\"BasisState parameter and wires must be of equal length.\")\n\n # get computational basis state number\n basis_states = 2 ** (self.num_wires - 1 - np.array(device_wires))\n basis_states = qml.math.convert_like(basis_states, state)\n num = int(qml.math.dot(state, basis_states))\n\n self._state = self._create_basis_state(num)\n\n def _apply_unitary(self, state, mat, wires):\n r\"\"\"Apply multiplication of a matrix to subsystems of the quantum state.\n\n Args:\n state (array[complex]): input state\n mat (array): matrix to multiply\n wires (Wires): target wires\n\n Returns:\n array[complex]: output state\n \"\"\"\n # translate to wire labels used by device\n device_wires = self.map_wires(wires)\n\n mat = self._cast(self._reshape(mat, [2] * len(device_wires) * 2), dtype=self.C_DTYPE)\n axes = (np.arange(len(device_wires), 2 * len(device_wires)), device_wires)\n tdot = self._tensordot(mat, state, axes=axes)\n\n # tensordot causes the axes given in `wires` to end up in the first positions\n # of the resulting tensor. This corresponds to a (partial) transpose of\n # the correct output state\n # We'll need to invert this permutation to put the indices in the correct place\n unused_idxs = [idx for idx in range(self.num_wires) if idx not in device_wires]\n perm = list(device_wires) + unused_idxs\n inv_perm = np.argsort(perm) # argsort gives inverse permutation\n return self._transpose(tdot, inv_perm)\n\n def _apply_unitary_einsum(self, state, mat, wires):\n r\"\"\"Apply multiplication of a matrix to subsystems of the quantum state.\n\n This function uses einsum instead of tensordot. This approach is only\n faster for single- and two-qubit gates.\n\n Args:\n state (array[complex]): input state\n mat (array): matrix to multiply\n wires (Wires): target wires\n\n Returns:\n array[complex]: output state\n \"\"\"\n # translate to wire labels used by device\n device_wires = self.map_wires(wires)\n\n mat = self._cast(self._reshape(mat, [2] * len(device_wires) * 2), dtype=self.C_DTYPE)\n\n # Tensor indices of the quantum state\n state_indices = ABC[: self.num_wires]\n\n # Indices of the quantum state affected by this operation\n affected_indices = \"\".join(ABC_ARRAY[list(device_wires)].tolist())\n\n # All affected indices will be summed over, so we need the same number of new indices\n new_indices = ABC[self.num_wires : self.num_wires + len(device_wires)]\n\n # The new indices of the state are given by the old ones with the affected indices\n # replaced by the new_indices\n new_state_indices = functools.reduce(\n lambda old_string, idx_pair: old_string.replace(idx_pair[0], idx_pair[1]),\n zip(affected_indices, new_indices),\n state_indices,\n )\n\n # We now put together the indices in the notation numpy's einsum requires\n einsum_indices = f\"{new_indices}{affected_indices},{state_indices}->{new_state_indices}\"\n\n return self._einsum(einsum_indices, mat, state)\n\n def _apply_diagonal_unitary(self, state, phases, wires):\n r\"\"\"Apply multiplication of a phase vector to subsystems of the quantum state.\n\n This represents the multiplication with diagonal gates in a more efficient manner.\n\n Args:\n state (array[complex]): input state\n phases (array): vector to multiply\n wires (Wires): target wires\n\n Returns:\n array[complex]: output state\n \"\"\"\n # translate to wire labels used by device\n device_wires = self.map_wires(wires)\n\n # reshape vectors\n phases = self._cast(self._reshape(phases, [2] * len(device_wires)), dtype=self.C_DTYPE)\n\n state_indices = ABC[: self.num_wires]\n affected_indices = \"\".join(ABC_ARRAY[list(device_wires)].tolist())\n\n einsum_indices = f\"{affected_indices},{state_indices}->{state_indices}\"\n return self._einsum(einsum_indices, phases, state)\n\n def reset(self):\n \"\"\"Reset the device\"\"\"\n super().reset()\n\n # init the state vector to |00..0>\n self._state = self._create_basis_state(0)\n self._pre_rotated_state = self._state\n\n def analytic_probability(self, wires=None):\n\n if self._state is None:\n return None\n\n flat_state = self._flatten(self._state)\n real_state = self._real(flat_state)\n imag_state = self._imag(flat_state)\n prob = self.marginal_prob(real_state ** 2 + imag_state ** 2, wires)\n return prob\n" ]
[ [ "numpy.sqrt", "numpy.argmax", "numpy.ravel_multi_index", "numpy.argsort", "numpy.array", "numpy.exp", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
JoshuaPiinRueyPan/StatoilCompetition
[ "9e0f9ac868e9eaf648a4e71e97de000229cd3a6a" ]
[ "src/net/ResnetFat.py" ]
[ "import tensorflow as tf\nfrom src.net.SubnetBase import SubnetBase\nfrom src.layers.BasicLayers import *\nfrom src.layers.ResidualLayers import *\nimport settings.OutputSettings as outSettings\n\nclass ResnetFat(SubnetBase):\n\tdef __init__(self, isTraining_, trainingStep_, inputImage_, inputAngle_, groundTruth_):\n\t\tself.isTraining = isTraining_\n\t\tself.trainingStep = trainingStep_\n\t\tself.inputImage = inputImage_\n\t\tself.inputAngle = inputAngle_\n\t\tself.groundTruth = groundTruth_\n\n\tdef Build(self):\n\t\twith tf.name_scope('Layer1'):\n\t\t\t'''\n\t\t\t Conv1st (5x5, 16) is the best result.\n\t\t\t (5x5, 8) is also good.\n\t\t\t'''\n\t\t\tnet = ConvLayer('Conv1', self.inputImage, filterSize_=5, numberOfFilters_=16,\n\t\t\t\t\tstride_=1, padding_='SAME')\n\t\t\tnet, updateOp1 = BatchNormalization('BN_1', net, isConvLayer_=True,\n\t\t\t\t\t\t\t isTraining_=self.isTraining, currentStep_=self.trainingStep)\n\t\t\tnet = LeakyRELU('LeakyRELU', net)\n\t\t\tnet = MaxPoolLayer('MaxPool1', net, kernelSize=2)\n\n\t\t# Layer 2\n\t\tnet, updateOp2 = ResidualLayer( \"ResLayer2\",\n\t\t\t\t\t\t net, numberOfResidualBlocks_=3, listOfConvFilterSize_=[8, 8, 32],\n\t\t\t\t\t\t isTraining_=self.isTraining, trainingStep_=self.trainingStep, activationType_=\"RELU\")\n\n\t\t# Layer 3\n\t\tnet, updateOp3 = ResidualLayer( \"ResLayer3\",\n\t\t\t\t\t\tnet, numberOfResidualBlocks_=4, listOfConvFilterSize_=[16, 16, 64],\n\t\t\t\t\t\tisTraining_=self.isTraining, trainingStep_=self.trainingStep, activationType_=\"RELU\")\n\n\t\t'''\n\t\t MaxPool seems a little improve (lower the loss).\n\t\t'''\n\t\t#net = AvgPoolLayer(\"AveragePool\", net, kernelSize=38, padding_='VALID')\n\t\tnet = AvgPoolLayer(\"AveragePool\", net, kernelSize=7, padding_='SAME')\n\t\t#net = MaxPoolLayer(\"MaxPool\", net, kernelSize=38, padding_='VALID')\n\t\t#net = MaxPoolLayer(\"MaxPool\", net, kernelSize=7, padding_='SAME')\n\n\t\tnet = FullyConnectedLayer('Fc', net, numberOfOutputs_=outSettings.NUMBER_OF_CATEGORIES)\n\n\t\tupdateOperations = tf.group(updateOp1, updateOp2, updateOp3, name=\"groupUpdateOps\")\n\n\t\treturn net, updateOperations\n\n" ]
[ [ "tensorflow.group", "tensorflow.name_scope" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
zaneoliver6/char-rnn-lstm-receipts
[ "f2a54a6eacae50209c47d1ac5246cfc616b53b11" ]
[ "train.py" ]
[ "from __future__ import print_function\nimport tensorflow as tf\n\nimport argparse\nimport time\nimport os\nfrom six.moves import cPickle\n\nfrom utils import TextLoader\nfrom model import Model\n\n\ndef main():\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--data_dir', type=str, default='data/receipts',\n help='data directory containing input.txt')\n parser.add_argument('--save_dir', type=str, default='save',\n help='directory to store checkpointed models')\n parser.add_argument('--log_dir', type=str, default='logs',\n help='directory to store tensorboard logs')\n parser.add_argument('--rnn_size', type=int, default=128,\n help='size of RNN hidden state')\n parser.add_argument('--num_layers', type=int, default=2,\n help='number of layers in the RNN')\n parser.add_argument('--model', type=str, default='lstm',\n help='rnn, gru, lstm, or nas')\n parser.add_argument('--batch_size', type=int, default=10,\n help='minibatch size')\n parser.add_argument('--seq_length', type=int, default=10,\n help='RNN sequence length')\n parser.add_argument('--num_epochs', type=int, default=50,\n help='number of epochs')\n parser.add_argument('--save_every', type=int, default=1000,\n help='save frequency')\n parser.add_argument('--grad_clip', type=float, default=5.,\n help='clip gradients at this value')\n parser.add_argument('--learning_rate', type=float, default=0.002,\n help='learning rate')\n parser.add_argument('--decay_rate', type=float, default=0.97,\n help='decay rate for rmsprop')\n parser.add_argument('--output_keep_prob', type=float, default=1.0,\n help='probability of keeping weights in the hidden layer')\n parser.add_argument('--input_keep_prob', type=float, default=1.0,\n help='probability of keeping weights in the input layer')\n parser.add_argument('--init_from', type=str, default=None,\n help=\"\"\"continue training from saved model at this path. Path must contain files saved by previous training process:\n 'config.pkl' : configuration;\n 'chars_vocab.pkl' : vocabulary definitions;\n 'checkpoint' : paths to model file(s) (created by tf).\n Note: this file contains absolute paths, be careful when moving files around;\n 'model.ckpt-*' : file(s) with model definition (created by tf)\n \"\"\")\n args = parser.parse_args()\n train(args)\n\n\ndef train(args):\n data_loader = TextLoader(args.data_dir, args.batch_size, args.seq_length)\n args.vocab_size = data_loader.vocab_size\n\n # check compatibility if training is continued from previously saved model\n if args.init_from is not None:\n # check if all necessary files exist\n assert os.path.isdir(args.init_from),\" %s must be a a path\" % args.init_from\n assert os.path.isfile(os.path.join(args.init_from,\"config.pkl\")),\"config.pkl file does not exist in path %s\"%args.init_from\n assert os.path.isfile(os.path.join(args.init_from,\"chars_vocab.pkl\")),\"chars_vocab.pkl.pkl file does not exist in path %s\" % args.init_from\n ckpt = tf.train.get_checkpoint_state(args.init_from)\n assert ckpt, \"No checkpoint found\"\n assert ckpt.model_checkpoint_path, \"No model path found in checkpoint\"\n\n # open old config and check if models are compatible\n with open(os.path.join(args.init_from, 'config.pkl'), 'rb') as f:\n saved_model_args = cPickle.load(f)\n need_be_same = [\"model\", \"rnn_size\", \"num_layers\", \"seq_length\"]\n for checkme in need_be_same:\n assert vars(saved_model_args)[checkme]==vars(args)[checkme],\"Command line argument and saved model disagree on '%s' \"%checkme\n\n # open saved vocab/dict and check if vocabs/dicts are compatible\n with open(os.path.join(args.init_from, 'chars_vocab.pkl'), 'rb') as f:\n saved_chars, saved_vocab = cPickle.load(f)\n assert saved_chars==data_loader.chars, \"Data and loaded model disagree on character set!\"\n assert saved_vocab==data_loader.vocab, \"Data and loaded model disagree on dictionary mappings!\"\n\n if not os.path.isdir(args.save_dir):\n os.makedirs(args.save_dir)\n with open(os.path.join(args.save_dir, 'config.pkl'), 'wb') as f:\n cPickle.dump(args, f)\n with open(os.path.join(args.save_dir, 'chars_vocab.pkl'), 'wb') as f:\n cPickle.dump((data_loader.chars, data_loader.vocab), f)\n\n model = Model(args)\n\n with tf.Session() as sess:\n # instrument for tensorboard\n summaries = tf.summary.merge_all()\n writer = tf.summary.FileWriter(\n os.path.join(args.log_dir, time.strftime(\"%Y-%m-%d-%H-%M-%S\")))\n writer.add_graph(sess.graph)\n\n sess.run(tf.global_variables_initializer())\n saver = tf.train.Saver(tf.global_variables())\n # restore model\n if args.init_from is not None:\n saver.restore(sess, ckpt.model_checkpoint_path)\n for e in range(args.num_epochs):\n sess.run(tf.assign(model.lr,args.learning_rate * (args.decay_rate ** e)))\n data_loader.reset_batch_pointer()\n state = sess.run(model.initial_state)\n for b in range(data_loader.num_batches):\n start = time.time()\n x, y = data_loader.next_batch()\n feed = {model.input_data: x, model.targets: y}\n for i, (c, h) in enumerate(model.initial_state):\n feed[c] = state[i].c\n feed[h] = state[i].h\n train_loss, state, _ = sess.run([model.cost, model.final_state, model.train_op], feed)\n\n # instrument for tensorboard\n summ, train_loss, state, _ = sess.run([summaries, model.cost, model.final_state, model.train_op], feed)\n writer.add_summary(summ, e * data_loader.num_batches + b)\n\n end = time.time()\n print(\"{}/{} (epoch {}), train_loss = {:.3f}, time/batch = {:.3f}\"\n .format(e * data_loader.num_batches + b,\n args.num_epochs * data_loader.num_batches,\n e, train_loss, end - start))\n if (e * data_loader.num_batches + b) % args.save_every == 0\\\n or (e == args.num_epochs-1 and\n b == data_loader.num_batches-1):\n # save for the last result\n checkpoint_path = os.path.join(args.save_dir, 'model.ckpt')\n saver.save(sess, checkpoint_path, global_step=e * data_loader.num_batches + b)\n tf.train.write_graph(sess.graph_def,args.save_dir,'model.pbtxt')\n print(\"model saved to {}\".format(checkpoint_path))\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "tensorflow.train.get_checkpoint_state", "tensorflow.global_variables", "tensorflow.assign", "tensorflow.global_variables_initializer", "tensorflow.summary.merge_all", "tensorflow.Session", "tensorflow.train.write_graph" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
sinaghassemi/semanticSegmentation
[ "ec4cd8aeb92dc5dde80ae21f874a3a6a74bde108" ]
[ "cnn/main.py" ]
[ "# Copyright 2018 Telecom Italia S.p.A.\n\n# Redistribution and use in source and binary forms,\n# with or without modification, are permitted provided that the following conditions are met:\n\n# Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation and/or other materials provided\n# with the distribution.\n# Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products\n# derived from this software without specific prior written permission.\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY \n# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES \n# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. \n# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, \n# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, \n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; \n# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, \n# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, \n# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\nimport torch \nimport os\nimport torch.nn as nn\nimport torchvision.models as models\nimport torchvision.datasets as dsets\nimport torchvision.transforms as transforms\nimport torch.utils.data as data\nfrom torch.autograd import Variable\nfrom math import ceil\nimport h5py\nimport numpy as np\nimport argparse\nfrom models import encoder_decoder_resnet\nfrom loaders import loader\nfrom functions import trainSegmentation, valSegmentation, logEpoch, reset_BN ,scores_test, stitchPatchesFull, savePredictions, crf\ntorch.multiprocessing.set_sharing_strategy('file_system')\nfrom multiprocessing import Lock\nimport random\n\n#=================Argument============================#\nparser = argparse.ArgumentParser(description='PyTorch Satellite Segmentation')\nparser.add_argument('--seed'\t\t, default= 1\t\t, type=int\t, metavar='N', help='Torch and NumPy pseudorandom number generators seed (-1 disables manual seeding)')\nparser.add_argument('--fileNameData'\t, default=None\t\t, type=str\t, metavar='N', help='hdf5 file of the dataset, images file')\nparser.add_argument('--preload'\t\t, default='true'\t, type=str\t, metavar='N', help='set to true to preload entire dataset into memory')\nparser.add_argument('--experiment'\t, default='ex500'\t, type=str\t, metavar='N', help='Experiment Identifier')\nparser.add_argument('--batchSize'\t, default=8\t\t, type=int\t, metavar='N', help='batch size')\nparser.add_argument('--imageSize'\t, default=364\t\t, type=int\t, metavar='N', help='imageSize')\nparser.add_argument('--patchSize'\t, default=256\t\t, type=int\t, metavar='N', help='imageSize')\nparser.add_argument('--nEpochs'\t\t, default=300\t\t, type=int\t, metavar='N', help='total number of Epoches')\nparser.add_argument('--nChannelsIn'\t, default=4\t\t, type=int\t, metavar='N', help='number of input Channels')\nparser.add_argument('--nChannelsOut'\t, default=2\t\t, type=int\t, metavar='N', help='number of output Channels')\nparser.add_argument('--nThreads'\t, default=1\t\t, type=int\t, metavar='N', help='number of threads for data loading')\nparser.add_argument('--depth'\t\t, default=34\t\t, type=int\t, metavar='N', help='number of layers in encoder')\nparser.add_argument('--optim'\t\t, default='SGD'\t\t, type=str\t, metavar='N', help='optimizer [SGD | adagrad]')\nparser.add_argument('--lr'\t\t, default=1\t\t, type=float\t, metavar='N', help='learning rate strategy (SGD, >=1) or base value (Adagrad, any value)')\nparser.add_argument('--lrDecay'\t\t, default=1\t\t, type=float\t, metavar='N', help='learning rate decay (Adagrad)')\nparser.add_argument('--weightDecay'\t, default=1\t\t, type=float\t, metavar='N', help='weight rate decay (Adagrad)')\nparser.add_argument('--GPU'\t\t, default=True\t\t, type=bool\t, metavar='N', help='training over GPU')\nparser.add_argument('--criterion'\t, default='BCE'\t\t, type=str\t, metavar='N',choices=['2dNLL', 'BCE', 'MSE'], help='criterion')\nparser.add_argument('--finetuneModule'\t, default=None\t\t, type=str\t, metavar='N', help='network needed to be fine-tunned')\nparser.add_argument('--testModule'\t, default=None\t\t, type=str\t, metavar='N', help='running a testmodule over test areas')\nparser.add_argument('--set'\t \t, default='train'\t, type=str\t, metavar='N', choices=['train', 'val', 'test']\t,help='set')\nparser.add_argument('--dataset'\t \t, default='isprs'\t, type=str\t, metavar='N', choices=['isprs','inria']\t,help='dataset')\nparser.add_argument('--crf'\t \t, default=False \t, type=bool\t, metavar='N', help='conditional random field')\nparser.add_argument('--finetunedBN'\t, default=False \t, type=bool\t, metavar='N', help='fine tunning BN parameters over test area')\nparser.add_argument('--resetBN'\t\t, default=False \t, type=bool\t, metavar='N', help='reseting BN')\nparser.add_argument('--BNFinetuningEpochs', default=1\t\t, type=int\t, metavar='N', help='BNFinetuningEpochs')\nargs = parser.parse_args()\n\nif args.preload == 'true':\n\tpreload = True\nelse:\n\tpreload = False\n\n\n#===================Log File===========================\nlogFileName = 'ex%s_report.txt' % (args.experiment)\nprint ('Report will be saved to ' + logFileName)\n\n\n#============================= System level stuff ============================\n\n# AF: this will seed numpy's RNG for all processes\nif args.seed > -1:\n\t# AF: this will seed torch's RNG for the main process, each worker will have its torch seed set to base_seed + worker_id, where base_seed is a long generated by main process using its RNG.\n\t#http://pytorch.org/docs/master/data.html\n\ttorch.manual_seed(args.seed)\n\t# Setting Python RNG seed\n\trandom.seed(args.seed)\n\t# Setting numpy seed for main and worker processes\n\tnumPySeed = torch.initial_seed() % (2^32)\n\tnp.random.seed(numPySeed)\n\tprint (\"Main PID \" + str(os.getpid()) + \" torch RNG seed \" + str(torch.initial_seed()) + \" numpy RNG seed \" + str(numPySeed))\n\t\n\t#https://github.com/pytorch/pytorch/pull/2893\n\ttorch.backends.cudnn.deterministic = True\n\tprint (\"All RNGs seeds set to \" + str(args.seed))\nelse:\n\tprint (\"main_process PID \" + str(os.getpid()) + \" torch RNG seed \" + str (torch.initial_seed()))\n\n#AF: TODO this should be better explored\n#torch.backends.cudnn.benchmark = True\n#torch.backends.cudnn.verbose = True\n#============================= Datasets =====================================\nreturnLabels = True\nnormalize = False\nareaBasedNorm = False\nimageSize = args.imageSize\nprint('Dataset : %s'%(args.dataset))\nif args.dataset == 'isprs':\n\tif args.set == 'val':\n\t\treturnLabels = False\n\t\tnormalize = True\n\t\timageSize = 512\n\t\tareaNumbers = [11,15,28,30,34]#[11,15,28,30,34]\n\t\tareaList=['isprs_vaihingen'+str(i) for i in areaNumbers]\n\t\tpyList=[7,7,7,7,7]\n\t\tpxList=[5,5,5,5,4]\n\t\tsyList=[2566,2565,2567,2563,2555]\n\t\tsxList=[1893,1919,1917,1934,1388]\n\t\ttrList=[400,400,400,400,400]\n\telif args.set == 'test':\n\t\treturnLabels = False\n\t\tnormalize = True\n\t\timageSize = 512\n\t\tareaNumbers = [2,4,6,8,10,12,14,16,20,22,24,27,29,31,33,35,38]\n\t\tareaList=['isprs_vaihingen'+str(i) for i in areaNumbers]\n\t\tpyList=[7,7,7,7,7,7,7,7,6,7,7,9,7,7,7,5,7]\n\t\tpxList=[6,5,5,5,5,5,5,5,5,5,5,5,5,5,4,7,10]\n\t\tsyList=[2767,2557,2557,2557,2557,2575,2565,2565,2315,2546,2546,3313,2563,2555,2555,1884,2550]\n\t\tsxList=[2428,1887,1887,1887,1887,1922,1919,1919,1866,1903,1903,1917,1917,1980,1581,2805,3816]\n\t\ttrList=[400 for i in range(len(pyList))]\nelif args.dataset == 'inria':\n\tif args.set == 'train':\n\t\tareaBasedNorm = True\n\t\tnormalize = True\n\telif args.set == 'val':\n\t\treturnLabels = False\n\t\tnormalize = True\n\t\timageSize = 1024\n\t\tcities = ['austin','chicago','kitsap','tyrol-w','vienna']\n\t\tareaNumbers = [i+1 for i in range(5)]\n\t\tareaList=[c+str(a) for c in cities for a in areaNumbers]\n\t\tpyList=[6 for i in range(5*len(cities))]\n\t\tpxList=[6 for i in range(5*len(cities))]\n\t\tsyList=[5000 for i in range(5*len(cities))]\n\t\tsxList=[5000 for i in range(5*len(cities))]\n\t\ttrList=[800 for i in range(5*len(cities))]\n\telif args.set == 'test':\n\t\treturnLabels = False\n\t\tnormalize = True\n\t\timageSize = 1024\n\t\tcities = ['bellingham','bloomington','innsbruck','sfo','tyrol-e'] \n\t\tareaNumbers = [i+1 for i in range(36)]\n\t\tareaList=[c+str(a) for c in cities for a in areaNumbers]\n\t\tpyList=[6 for i in range(len(cities)*36)]\n\t\tpxList=[6 for i in range(len(cities)*36)]\n\t\tsyList=[5000 for i in range(len(cities)*36)]\n\t\tsxList=[5000 for i in range(len(cities)*36)]\n\t\ttrList=[800 for i in range(len(cities)*36)]\n\n\n#=============================== Loss Function ==============================\nglobal criterion\nglobal labelFormat\nif args.criterion == '2dNLL':\n\tlabelFormat='long'\n\tlastLayer = 'logsoftmax'\n\tlabels_oneHot = False\n\tcriterion = nn.NLLLoss2d()\n\nelif args.criterion == 'BCE':\n\tlabelFormat='float'\n\tlastLayer = 'sigmoid'\n\tlabels_oneHot = True\n\tcriterion = nn.BCELoss()\n\nelif args.criterion == 'MSE':\n\tlabelFormat='float'\n\tlastLayer = 'sigmoid'\n\tlabels_oneHot = True\n\tcriterion = nn.MSELoss()\n\n\nif args.GPU:\n\tcriterion = criterion.cuda()\n\t\n#===================== TRAIN AND VAL DATALOADER =====================#\n# Mutex lock for concurrent HDF5 reading when nThreads > 1\nif args.set == 'train':\n\tlockImg = Lock()\n\tlockLabel = Lock()\n\ttrain_dataset = loader(args.fileNameData, lockImg, lockLabel, dataset='train', aug=True, imageSize= imageSize, patchSize=args.patchSize, nChannelsIn=args.nChannelsIn,nChannelsOut=args.nChannelsOut, labelFormat=labelFormat, preload=preload,areaBasedNorm=areaBasedNorm,normalize=normalize,returnLabels=returnLabels)\n\tval_dataset = loader(args.fileNameData, lockImg, lockLabel, dataset='val', aug=False, imageSize=args.patchSize, patchSize=args.patchSize, nChannelsIn=args.nChannelsIn,nChannelsOut=args.nChannelsOut, labelFormat=labelFormat, preload=preload,areaBasedNorm=areaBasedNorm,normalize=normalize,returnLabels=returnLabels)\n\tNumberOfSamples_train = train_dataset.__len__()\n\tNumberOfSamples_val = val_dataset.__len__()\n\tprint ('train size : %d' % (NumberOfSamples_train))\n\tprint ('val size : %d' % (NumberOfSamples_val))\n\ttrain_loader = torch.utils.data.DataLoader(dataset=train_dataset,batch_size=args.batchSize,shuffle=True,num_workers=args.nThreads)\n\tval_loader = torch.utils.data.DataLoader(dataset=val_dataset,batch_size=args.batchSize, shuffle=False,num_workers=args.nThreads)\n\n#=====================CNN====================================\nprint('depth = '+ str(args.depth))\nmodel = encoder_decoder_resnet(args.nChannelsIn,args.nChannelsOut,args.depth,lastLayer)\nprint(model)\n\nif args.testModule != None:\n\tprint('loadning trained module of %s' % (args.testModule))\n\tmodel.load_state_dict(torch.load(args.testModule))\n\nif args.finetuneModule != None:\n\tprint('loadning trained module of %s' % (args.finetuneModule))\n\tmodel.load_state_dict(torch.load(args.finetuneModule))\n\nif args.GPU:\n\tmodel.cuda()\n#==============================train and val ===================================\ntrain = trainSegmentation\nval = valSegmentation\n\n\n#======================= Optimizer and learning rates ==========================\nif args.optim == 'SGD':\n\tif args.lr < 1:\n\t\tprint('ERROR optimizer SGD uses lr as strategy index')\n\t\tsys.exit(1)\n\t\n\toptimizer = torch.optim.SGD (model.parameters(), lr = 0.1, momentum=0.9)\n\tif args.lr == 1:\n\t\tlr_strategy = {'epoch':[1,100,300],'lr':[5e-2,5e-3,5e-4],'wd':[0,0,0]}\n\telif args.lr == 2:\n\t\tlr_strategy = {'epoch':[1,30,60,100,150],'lr':[5e-2,1e-2,5e-3,1e-3,5e-4],'wd':[1e-3,2e-4,1e-4,2e-5,1e-5]}\n\tprint('learning strategy (SGD)')\n\tprint(lr_strategy)\n\t\nelif args.optim == 'adagrad':\n\t#http://pytorch.org/docs/master/_modules/torch/optim/adagrad.html\n\t# clr = lr / (((iter-1) * lr_decay) +1)\n\toptimizer = torch.optim.Adagrad(model.parameters(), lr=args.lr, lr_decay=args.lrDecay, weight_decay=args.weightDecay)\n\tprint('learning rate (Agagrad) LR ' + str(args.lr) + ' lr_decay ' + str(args.lrDecay) + ' weight_decay ' + str(args.weightDecay))\n\t\nelif args.optim == 'adam':\n\t#http://pytorch.org/docs/master/optim.html#torch.optim.Adam\n\t# clr = lr / ...\n\toptimizer = torch.optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weightDecay)\n\tprint('learning rate (Adam) LR ' + str(args.lr) + ' b1 0.9 b2 0.999 weight_decay ' + str(args.weightDecay))\n\t\nelse:\n\tprint('ERROR optimizer ' + args.optim + ' unsupported')\n\tsys.exit(1)\n\n#=================================== main ======================================\n#---TRAINING---\nif args.set == 'train':\n\tprint('training')\n\tnumOfIterPerEpoch_train = int(ceil(NumberOfSamples_train/float(args.batchSize)))\n\tnumOfIterPerEpoch_val = int(ceil(NumberOfSamples_val/float(args.batchSize)))\n\tloss_val_best = 100\n\tloss_train_best = 100\n\tf1_val_best = 0\n\toverallAcc_val_best = 0\n\tfor epoch in range(args.nEpochs):\n\t\t#==================== Learning rate adaptation (SGD) =========================\n\t\tif args.optim == 'SGD':\n\t\t\tif epoch+1 in lr_strategy['epoch']:\n\t\t\t\tlr = lr_strategy['lr'][lr_strategy['epoch'].index(epoch+1)]\n\t\t\t\twd = lr_strategy['wd'][lr_strategy['epoch'].index(epoch+1)]\n\t\t\t\tprint ( 'Epoch : %d LR : %f WD : %f ' % (epoch+1,lr,wd))\n\t\t\t\toptimizer = torch.optim.SGD (model.parameters(),weight_decay=wd, lr = lr, momentum=0.9)\t\t\t\t\n\t\t#======================TRAINIG==================================#\n\t\tloss_train, f1_train, aveAcc_train, overallAcc_train, f1_classes_train, acc_classes_train = train(train_loader, model, criterion, optimizer, epoch, args.nEpochs, numOfIterPerEpoch_train, args.nChannelsOut,args.GPU, labels_oneHot)\n\t\t\n\t\t#======================VALIDATION===============================#\n\t\tloss_val, f1_val, aveAcc_val, overallAcc_val, f1_classes_val, acc_classes_val = val(val_loader, model, criterion, epoch, args.nEpochs, numOfIterPerEpoch_val, args.nChannelsOut,args.GPU, labels_oneHot)\n\t\t\n\t\t#======================Writning on log file====================#\n\t\tlogEpoch(logFileName, epoch, loss_train, loss_val, f1_train, f1_val, aveAcc_train, aveAcc_val, overallAcc_train, overallAcc_val , f1_classes_train, f1_classes_val, acc_classes_train, acc_classes_val)\n\n\t\t# =========Saving the network =================\n\t\tif f1_val > f1_val_best:\n\t\t\tf1_val_best = f1_val\n\t\t\tfileName = 'ex%s_bestNet_valF1.pt' % (args.experiment)\n\t\t\tprint('Saving val best model as ' + fileName)\n\t\t\ttorch.save(model.state_dict(), fileName)\n\n\t\tif overallAcc_val > overallAcc_val_best:\n\t\t\toverallAcc_val_best = overallAcc_val\n\t\t\tfileName = 'ex%s_bestNet_valAcc.pt' % (args.experiment)\n\t\t\tprint('saving val best model as ' + fileName)\n\t\t\ttorch.save(model.state_dict(), fileName)\n\n#---TESTING---\nelse:\n\n\t\tprint('testing pretrained network')\n\t\tconfusion_summed = np.zeros((args.nChannelsOut,args.nChannelsOut))\n\t\tF1_summed = 0\n\t\tF1_perClass_summed = [0 for i in range(args.nChannelsOut)]\n\t\taccaracy_summed = 0\n\t\toverallAccuracy_summed = 0\n\t\tlockImg = Lock()\n\t\tlockLabel = Lock()\n\n\n\t\t#===================== Fine Tunning BN ================#\n\t\tif args.finetunedBN:\n\t\t\tmodel.train()\n\t\t\tprint('========= Fine Tunning BN ==========')\n\t\t\tif args.resetBN == True:\n\t\t\t\tprint('reseting computed mean and var of batch norms')\n\t\t\t\tmodel.apply(reset_BN)\n\n\t\t\tfor te in range(args.BNFinetuningEpochs):\n\t\t\t\tfor index,area in enumerate(areaList):\n\t\t\t\t\tprint('====================================')\n\t\t\t\t\tprint(area)\n\t\t\t\t\t#===================== DATALOADER =====================#\n\t\t\t\t\tdataFile = ('data/%s_test.h5') % area\n\t\t\t\t\tdataset = loader(dataFile,dataFile, lockImg, lockLabel, dataset='test', aug=False, imageSize=imageSize, patchSize=imageSize, nChannelsIn=args.nChannelsIn,nChannelsOut=args.nChannelsOut, labelFormat=labelFormat, preload=preload,returnLabels=returnLabels,normalize=normalize)\n\t\t\t\t\tNumberOfSamples = dataset.__len__()\n\t\t\t\t\tprint ('test size : %d' % (NumberOfSamples))\t\t\t\n\t\t\t\t\tprint(dataFile)\n\t\t\t\t\ttest_loader = torch.utils.data.DataLoader(dataset=dataset,batch_size=args.batchSize,shuffle=True)\n\t\t\t\t\tnumOfIterPerEpoch = int(ceil(NumberOfSamples/float(args.batchSize)))\n\t\t\t\t\tfor iteration, (data,_,_) in enumerate(test_loader):\n\t\t\t\t\t\tprint (\"Epoch[%d] Iter [%d/%d]\" %(te,iteration+1, numOfIterPerEpoch))\n\t\t\t\t\t\tif args.GPU:\n\t\t\t\t\t\t\tdata = data.cuda()\n\t\t\t\t\t\twith torch.no_grad():\n\t\t\t\t\t\t\toutputs = model(data)\n\n\t\tfor index,area in enumerate(areaList):\n\t\t\tprint('====================================')\n\t\t\tprint(area)\n\t\t\t#===================== DATALOADER =====================#\n\t\t\tdataFile = ('%s_test.h5') % area\n\t\t\tdataset = loader(dataFile, lockImg, lockLabel, dataset='test', aug=False, imageSize=imageSize, patchSize=imageSize, nChannelsIn=args.nChannelsIn,nChannelsOut=args.nChannelsOut, labelFormat=labelFormat, preload=preload,returnLabels=returnLabels,normalize=normalize)\n\t\t\tNumberOfSamples = dataset.__len__()\n\t\t\tprint ('test size : %d' % (NumberOfSamples))\t\t\t\n\t\t\tprint(dataFile)\n\n\t\t\t#===================== Evaluating ================#\n\t\t\tif args.finetunedBN:\n\t\t\t\tmodel.eval()\t\n\t\t\telse:\n\t\t\t\tmodel.train()\n\t\t\tprint('========= Evaluating ==========')\n\t\t\ttest_loader = torch.utils.data.DataLoader(dataset=dataset,batch_size=args.batchSize,shuffle=False)\n\t\t\tnumOfIterPerEpoch = int(ceil(NumberOfSamples/float(args.batchSize)))\n\t\t\toutputs_all = []\n\t\t\tfor iteration, (data,_) in enumerate(test_loader):\n\t\t\t\tprint (\" Iter [%d/%d]\" %(iteration+1, numOfIterPerEpoch))\n\t\t\t\tif args.GPU:\n\t\t\t\t\tdata = data.cuda()\n\n\t\t\t\twith torch.no_grad():\n\t\t\t\t\toutputs = model(data)\n\t\t\t\t\t\n\t\t\t\toutputs = outputs.data\n\t\t\t\toutputs = outputs.cpu()\n\t\t\t\tif iteration == 0:\n\t\t\t\t\toutputs_all = outputs\n\t\t\t\telse:\n\t\t\t\t\toutputs_all = torch.cat((outputs_all,outputs),dim=0)\n\n\t\t\tif lastLayer == 'logsoftmax':\n\t\t\t\toutputs_all = torch.exp(outputs_all) # probability\n\t\t\tif args.set == 'val':\n\t\t\t\toutputs_all = stitchPatchesFull(outputs_all,pyList[index],pxList[index],trList[index],syList[index],sxList[index])\n\t\t\t\tif args.crf:\n\t\t\t\t\tprint('Applying CRF')\t\n\t\t\t\t\toutputs_all = crf(outputs_all,areaNumbers[index])\n\t\t\t\tF1, F1_perClass, accaracy , overallAccuracy, confusion = scores_test(outputs_all,area,args.experiment)\n\t\t\t\tF1_summed += F1\n\t\t\t\taccaracy_summed += accaracy\n\t\t\t\toverallAccuracy_summed += overallAccuracy\n\t\t\t\tconfusion_summed += confusion\n\t\t\t\tF1_perClass_summed = [F1_perClass_summed[c] + F1_perClass[c] for c in range(args.nChannelsOut)]\n\t\t\tif args.set =='test':\n\t\t\t\toutputs_all = stitchPatchesFull(outputs_all,pyList[index],pxList[index],trList[index],syList[index],sxList[index])\n\t\t\t\tsavePredictions(outputs_all,areaNumbers[index % len(areaNumbers)],args.experiment,args.dataset,areaList[index])\t\n\t\t\tprint('====================================')\n\t\tif args.set == 'val':\n\t\t\tF1_summed = F1_summed/len(areaList)\n\t\t\taccaracy_summed = accaracy_summed/len(areaList)\n\t\t\toverallAccuracy_summed = overallAccuracy_summed/len(areaList)\n\t\t\tconfusion_summed = confusion_summed/len(areaList)\n\t\t\tF1_perClass_summed = [F1_perClass_summed[c]/len(areaList) for c in range(args.nChannelsOut)]\n\t\t\tfileName = 'testImages/'+args.experiment+'/results_.txt'\n\t\t\tprint('+++++++++++++++++++++++++++++++++++++++')\n\t\t\tprint('Results averaged over all areas')\n\t\t\tprint('F1Score %f' % F1_summed)\n\t\t\tprint('overallAccuracy %f' % overallAccuracy_summed)\n\t\t\tprint('+++++++++++++++++++++++++++++++++++++++')\n\n\n\n\n\n\n\n\n\n\n\n\t\n\n\n" ]
[ [ "torch.initial_seed", "numpy.random.seed", "torch.load", "torch.cat", "torch.manual_seed", "torch.utils.data.DataLoader", "torch.nn.BCELoss", "torch.exp", "torch.nn.NLLLoss2d", "torch.no_grad", "numpy.zeros", "torch.nn.MSELoss", "torch.multiprocessing.set_sharing_strategy" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mtlazul/computer-vision
[ "94871a92bdf0b8a90a41b6d074988a9dbf91f8ba" ]
[ "tarea02/segmentation.py" ]
[ "#!/usr/bin/env python3\n\nimport numpy as np\nimport argparse\nimport cv2\nfrom scipy import ndimage as ndi\nfrom skimage.util import img_as_float\nfrom skimage.segmentation import slic\nfrom skimage.filters import rank\nfrom skimage.segmentation import watershed\nfrom skimage.morphology import disk\nfrom sklearn.cluster import MeanShift, estimate_bandwidth\nimport json\n\ndef displayCamera(frame):\n\treturn frame\n\ndef meanShift(frame):\n\t# Load params\n\tpram_file = open(\"meanshift.json\")\n\tparam = json.load(pram_file)\n\t# Convert capture space color to RGB\n\trgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n\tframe = np.array(rgb_frame)\n\t# Original shape from new RGB frame\n\torig_shape = frame.shape\n\t# Convert image into feature array based on RGB intensities\n\tflat_frame = np.reshape(frame, [-1, 3])\n\t# Mean Shift\n\tbandwidth = estimate_bandwidth(flat_frame,\n\t\t\t\t\tquantile = param[\"quantile\"],\n\t\t\t\t\tn_samples = param[\"n_samples\"],\n\t\t\t\t\trandom_state = param[\"random_state\"],\n\t\t\t\t\tn_jobs = param[\"n_jobs\"])\n\tms = MeanShift(bandwidth,\n\t\t\t\t\tbin_seeding = param[\"bin_seeding\"],\n\t\t\t\t\tmin_bin_freq = param[\"min_bin_freq\"],\n\t\t\t\t\tcluster_all = param[\"cluster_all\"],\n\t\t\t\t\tn_jobs = param[\"n_jobs\"])\n\tms.fit(flat_frame)\n\tlabels = ms.labels_\n\t# Take size and ignore RGB channels\n\tsegments = np.reshape(labels, orig_shape[:2])\n\n\tsegment_img_gray = np.array(segments, dtype=np.uint8)\n\tsegment_img_gray = segment_img_gray*(255//np.max(segments))\n\tsegment_img_color = cv2.applyColorMap(segment_img_gray, cv2.COLORMAP_JET)\n\treturn segment_img_color\n\ndef watershedSegmentation(frame):\n\tpram_file = open(\"watershed.json\")\n\tparam = json.load(pram_file)\n\n\tim = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n\tdenoised = rank.median(im, disk(2))\n\tmarkers = rank.gradient(denoised, disk(5)) < 10\n\tmarkers = ndi.label(markers)[0]\n\t\n\t# local gradient (disk(2) is used to keep edges thin)\n\tgradient = rank.gradient(denoised, disk(2)) \n \n\tsegments = watershed(gradient,\n\t\t\t\t\tmarkers = param[\"markers\"],\n\t\t\t\t\tconnectivity = param[\"connectivity\"],\n\t\t\t\t\toffset = param[\"offset\"],\n\t\t\t\t\tmask = param[\"mask\"],\n\t\t\t\t\tcompactness = param[\"compactness\"],\n\t\t\t\t\twatershed_line = param[\"watershed_line\"])\n\tsegment_img_gray = np.array(segments, dtype=np.uint8)\n\tsegment_img_gray = segment_img_gray*(255//np.max(segments))\n\tsegment_img_color = cv2.applyColorMap(segment_img_gray, cv2.COLORMAP_JET)\n\treturn segment_img_color\n\ndef slicSegmentation(frame):\n\tpram_file = open(\"slic.json\")\n\tparam = json.load(pram_file)\n\tsegments = slic(frame,\n\t\t\t\t\tn_segments = param[\"n_segments\"],\n\t\t\t\t\tcompactness = param[\"compactness\"],\n\t\t\t\t\tmax_iter = param[\"max_iter\"],\n\t\t\t\t\tsigma = param[\"sigma\"],\n\t\t\t\t\tmultichannel = param[\"multichannel\"],\n\t\t\t\t\tconvert2lab = param[\"convert2lab\"],\n\t\t\t\t\tenforce_connectivity = param[\"enforce_connectivity\"],\n\t\t\t\t\tmin_size_factor = param[\"min_size_factor\"],\n\t\t\t\t\tmax_size_factor = param[\"max_size_factor\"],\n\t\t\t\t\tslic_zero = param[\"slic_zero\"])\n\tsegment_img_gray = np.array(segments, dtype=np.uint8)\n\tsegment_img_gray = segment_img_gray*(255//np.max(segments))\n\tsegment_img_color = cv2.applyColorMap(segment_img_gray, cv2.COLORMAP_JET)\n\treturn segment_img_color\n\ndef main():\n\tcap = cv2.VideoCapture(0)\n\tif (cap.isOpened()== False):\n\t\tprint(\"Error opening camera stream\")\n\t\tcap.release()\n\t\treturn\n\n\twhile(cap.isOpened()):\n\t\tret, frame = cap.read()\n\t\tif ret == True:\n\t\t\tframe = args.segmentation(frame)\n\t\t\tcv2.imshow(args.segmentation.__name__,frame)\n\t\t\tif cv2.waitKey(25) & 0xFF == ord('q'):\n\t\t\t\tbreak\n\t\telse:\n\t\t\tbreak\n\n\tcap.release()\n\tcv2.destroyAllWindows()\n\nif __name__ == \"__main__\":\n\tparser = argparse.ArgumentParser(description=\"Image level segmentation algorithms. \"+\n\t\"By default it only displays the camera stream. To apply an algorithm use one of the options\")\n\tparser.add_argument('--ms', dest='segmentation', action='store_const',\n\t\t\t\t\t\tconst=meanShift, default=displayCamera,\n\t\t\t\t\t\thelp='Apply mean shift algorithm to the camera stream')\n\tparser.add_argument('--ws', dest='segmentation', action='store_const',\n\t\t\t\t\t\tconst=watershedSegmentation, default=displayCamera,\n\t\t\t\t\t\thelp='Apply watershed algorithm to the camera stream')\n\tparser.add_argument('--slic', dest='segmentation', action='store_const',\n\t\t\t\t\t\tconst=slicSegmentation, default=displayCamera,\n\t\t\t\t\t\thelp='Apply simple linear iterative clustering algorithm to the camera stream')\n\targs = parser.parse_args()\n\tmain()\n\t\n" ]
[ [ "sklearn.cluster.estimate_bandwidth", "sklearn.cluster.MeanShift", "numpy.reshape", "scipy.ndimage.label", "numpy.max", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
gwjknvwjn/catboost
[ "de75c6af12cf490700e76c22072fbdc15b35d679" ]
[ "catboost/libs/model/model_export/ut/test.py" ]
[ "import numpy as np\nimport os\nimport pytest\nimport re\nimport yatest\n\nfrom catboost import Pool, CatBoost, CatBoostClassifier\nfrom catboost_pytest_lib import data_file, load_pool_features_as_df\n\nCATBOOST_APP_PATH = yatest.common.binary_path('catboost/app/catboost')\nAPPROXIMATE_DIFF_PATH = yatest.common.binary_path('catboost/tools/limited_precision_dsv_diff/limited_precision_dsv_diff')\n\n\ndef _get_train_test_cd_path(dataset):\n train_path = data_file(dataset, 'train_small')\n test_path = data_file(dataset, 'test_small')\n cd_path = data_file(dataset, 'train.cd')\n return (train_path, test_path, cd_path)\n\n\ndef _get_train_test_pool(dataset):\n train_path, test_path, cd_path = _get_train_test_cd_path(dataset)\n train_pool = Pool(train_path, column_description=cd_path)\n test_pool = Pool(test_path, column_description=cd_path)\n return (train_pool, test_pool)\n\n\ndef _get_cpp_py_cbm_model(dataset, parameters=[]):\n train_path, _, cd_path = _get_train_test_cd_path(dataset)\n basename = yatest.common.test_output_path('model')\n cmd = [CATBOOST_APP_PATH, 'fit',\n '-f', train_path,\n '--cd', cd_path,\n '-i', '100',\n '-r', '1234',\n '-m', basename,\n '--model-format', 'CPP',\n '--model-format', 'Python',\n '--model-format', 'CatboostBinary',\n ] + parameters\n yatest.common.execute(cmd)\n assert os.path.exists(basename + '.cpp')\n assert os.path.exists(basename + '.py')\n assert os.path.exists(basename + '.bin')\n return (basename + '.cpp', basename + '.py', basename + '.bin')\n\n\ndef _check_data(data1, data2, rtol=0.001):\n return np.all(np.isclose(data1, data2, rtol=rtol, equal_nan=True))\n\n\[email protected]('dataset,parameters', [('adult', []), ('adult', ['-I', '3']), ('higgs', [])])\ndef test_cpp_export(dataset, parameters):\n model_cpp, _, model_cbm = _get_cpp_py_cbm_model(dataset, parameters)\n _, test_path, cd_path = _get_train_test_cd_path(dataset)\n\n # form the commands we are going to run\n\n applicator_cpp = yatest.common.source_path('catboost/libs/model/model_export/ut/applicator.cpp')\n applicator_exe = yatest.common.test_output_path('applicator.exe')\n predictions_by_catboost_path = yatest.common.test_output_path('predictions_by_catboost.txt')\n predictions_path = yatest.common.test_output_path('predictions.txt')\n\n if os.name == 'posix':\n compile_cmd = ['g++', '-std=c++14', '-o', applicator_exe]\n else:\n compile_cmd = ['cl.exe', '-Fe' + applicator_exe]\n compile_cmd += [applicator_cpp, model_cpp]\n apply_cmd = [applicator_exe, test_path, cd_path, predictions_path]\n calc_cmd = [CATBOOST_APP_PATH, 'calc',\n '-m', model_cbm,\n '--input-path', test_path,\n '--cd', cd_path,\n '--output-path', predictions_by_catboost_path,\n ]\n compare_cmd = [APPROXIMATE_DIFF_PATH,\n '--have-header',\n '--diff-limit', '1e-6',\n predictions_path,\n predictions_by_catboost_path,\n ]\n\n try:\n yatest.common.execute(compile_cmd)\n yatest.common.execute(apply_cmd)\n yatest.common.execute(calc_cmd)\n yatest.common.execute(compare_cmd)\n except OSError as e:\n if re.search(r\"No such file or directory.*'{}'\".format(re.escape(compile_cmd[0])), str(e)):\n pytest.xfail(reason='We ignore `compiler not found` error: {}\\n'.format(str(e)))\n else:\n raise\n\n\ndef test_read_model_after_train():\n train_path, test_path, cd_path = _get_train_test_cd_path('adult')\n eval_file = yatest.common.test_output_path('eval-file')\n cmd = [\n CATBOOST_APP_PATH, 'fit',\n '-f', train_path,\n '--cd', cd_path,\n '-t', test_path,\n '-i', '100',\n '--eval-file', eval_file\n ]\n try:\n yatest.common.execute(\n cmd + [\n '--model-format', 'CPP',\n '--model-format', 'Python',\n ]\n )\n except Exception as e:\n if 'All chosen model formats not supported deserialization' not in str(e):\n raise\n yatest.common.execute(\n cmd + [\n '--model-format', 'CPP',\n '--model-format', 'CatboostBinary',\n ]\n )\n\n yatest.common.execute(\n cmd + [\n '--model-format', 'CatboostBinary',\n '--model-format', 'Python',\n ]\n )\n return\n assert False\n\n\ndef _predict_python_on_test(dataset, apply_catboost_model):\n features_data, cat_feature_indices = load_pool_features_as_df(\n data_file(dataset, 'test_small'),\n data_file(dataset, 'train.cd')\n )\n float_feature_indices = [i for i in range(features_data.shape[1]) if i not in cat_feature_indices]\n\n pred_python = []\n\n for _, row in features_data.iterrows():\n float_features = [round(v, 9) for v in row.values[float_feature_indices]]\n cat_features = row.values[cat_feature_indices]\n pred_python.append(apply_catboost_model(float_features, cat_features))\n return pred_python\n\n\[email protected]('dataset', ['adult', 'higgs'])\ndef test_python_export_from_app(dataset):\n _, test_pool = _get_train_test_pool(dataset)\n _, model_py, model_cbm = _get_cpp_py_cbm_model(dataset)\n\n model = CatBoost()\n model.load_model(model_cbm)\n pred_model = model.predict(test_pool, prediction_type='RawFormulaVal')\n\n scope = {}\n execfile(model_py, scope)\n pred_python = _predict_python_on_test(dataset, scope['apply_catboost_model'])\n\n assert _check_data(pred_model, pred_python)\n\n\[email protected]('iterations', [2, 40])\[email protected]('dataset', ['adult', 'higgs'])\ndef test_python_export_from_python(dataset, iterations):\n train_pool, test_pool = _get_train_test_pool(dataset)\n\n model = CatBoost({'iterations': iterations, 'random_seed': 0, 'loss_function': 'Logloss'})\n model.fit(train_pool)\n pred_model = model.predict(test_pool, prediction_type='RawFormulaVal')\n\n model_py = yatest.common.test_output_path('model.py')\n model.save_model(model_py, format=\"python\", pool=train_pool)\n\n scope = {}\n execfile(model_py, scope)\n pred_python = _predict_python_on_test(dataset, scope['apply_catboost_model'])\n\n assert _check_data(pred_model, pred_python)\n\n\[email protected]('dataset', ['adult', 'higgs'])\ndef test_python_after_load(dataset):\n train_pool, test_pool = _get_train_test_pool(dataset)\n model = CatBoostClassifier(iterations=40, random_seed=0)\n model.fit(train_pool)\n pred_model = model.predict(test_pool, prediction_type='RawFormulaVal')\n\n model_cbm = yatest.common.test_output_path('model.cbm')\n model.save_model(model_cbm)\n\n model_loaded = CatBoostClassifier()\n model_loaded.load_model(model_cbm)\n\n model_py = yatest.common.test_output_path('model.py')\n model_loaded.save_model(model_py, format=\"python\", pool=train_pool)\n pred_model_loaded = model_loaded.predict(test_pool, prediction_type='RawFormulaVal')\n\n scope = {}\n execfile(model_py, scope)\n pred_python = _predict_python_on_test(dataset, scope['apply_catboost_model'])\n\n assert _check_data(pred_model, pred_python)\n assert _check_data(pred_model_loaded, pred_python)\n" ]
[ [ "numpy.isclose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Koravit-Kaewlek/detect-banknote
[ "27e76c3e8c0567516b1ec71dc46252d50e753180" ]
[ "detect_video.py" ]
[ "import os\n# comment out below line to enable tensorflow outputs\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nimport time\nimport tensorflow as tf\nphysical_devices = tf.config.experimental.list_physical_devices('GPU')\nif len(physical_devices) > 0:\n tf.config.experimental.set_memory_growth(physical_devices[0], True)\nfrom absl import app, flags, logging\nfrom absl.flags import FLAGS\nimport core.utils as utils\nfrom core.yolov4 import filter_boxes\nfrom core.functions import *\nfrom tensorflow.python.saved_model import tag_constants\nfrom PIL import Image\nimport cv2\nimport numpy as np\nfrom tensorflow.compat.v1 import ConfigProto\nfrom tensorflow.compat.v1 import InteractiveSession\n\nflags.DEFINE_string('framework', 'tf', '(tf, tflite, trt')\nflags.DEFINE_string('weights', './checkpoints/yolov4-416',\n 'path to weights file')\nflags.DEFINE_integer('size', 416, 'resize images to')\nflags.DEFINE_boolean('tiny', False, 'yolo or yolo-tiny')\nflags.DEFINE_string('model', 'yolov4', 'yolov3 or yolov4')\nflags.DEFINE_string('video', './data/video/video.mp4', 'path to input video or set to 0 for webcam')\nflags.DEFINE_string('output', None, 'path to output video')\nflags.DEFINE_string('output_format', 'XVID', 'codec used in VideoWriter when saving video to file')\nflags.DEFINE_float('iou', 0.45, 'iou threshold')\nflags.DEFINE_float('score', 0.50, 'score threshold')\nflags.DEFINE_boolean('count', False, 'count objects within video')\nflags.DEFINE_boolean('dont_show', False, 'dont show video output')\nflags.DEFINE_boolean('info', False, 'print info on detections')\nflags.DEFINE_boolean('crop', False, 'crop detections from images')\nflags.DEFINE_boolean('plate', False, 'perform license plate recognition')\n\ndef main(_argv):\n config = ConfigProto()\n config.gpu_options.allow_growth = True\n session = InteractiveSession(config=config)\n STRIDES, ANCHORS, NUM_CLASS, XYSCALE = utils.load_config(FLAGS)\n input_size = FLAGS.size\n video_path = FLAGS.video\n # get video name by using split method\n video_name = video_path.split('/')[-1]\n video_name = video_name.split('.')[0]\n if FLAGS.framework == 'tflite':\n interpreter = tf.lite.Interpreter(model_path=FLAGS.weights)\n interpreter.allocate_tensors()\n input_details = interpreter.get_input_details()\n output_details = interpreter.get_output_details()\n print(input_details)\n print(output_details)\n else:\n saved_model_loaded = tf.saved_model.load(FLAGS.weights, tags=[tag_constants.SERVING])\n infer = saved_model_loaded.signatures['serving_default']\n\n # begin video capture\n try:\n vid = cv2.VideoCapture(int(video_path))\n except:\n vid = cv2.VideoCapture(video_path)\n\n out = None\n\n if FLAGS.output:\n # by default VideoCapture returns float instead of int\n width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))\n fps = int(vid.get(cv2.CAP_PROP_FPS))\n codec = cv2.VideoWriter_fourcc(*FLAGS.output_format)\n out = cv2.VideoWriter(FLAGS.output, codec, fps, (width, height))\n\n frame_num = 0\n while True:\n return_value, frame = vid.read()\n if return_value:\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n frame_num += 1\n image = Image.fromarray(frame)\n else:\n print('Video has ended or failed, try a different video format!')\n break\n \n frame_size = frame.shape[:2]\n image_data = cv2.resize(frame, (input_size, input_size))\n image_data = image_data / 255.\n image_data = image_data[np.newaxis, ...].astype(np.float32)\n start_time = time.time()\n\n if FLAGS.framework == 'tflite':\n interpreter.set_tensor(input_details[0]['index'], image_data)\n interpreter.invoke()\n pred = [interpreter.get_tensor(output_details[i]['index']) for i in range(len(output_details))]\n if FLAGS.model == 'yolov3' and FLAGS.tiny == True:\n boxes, pred_conf = filter_boxes(pred[1], pred[0], score_threshold=0.25,\n input_shape=tf.constant([input_size, input_size]))\n else:\n boxes, pred_conf = filter_boxes(pred[0], pred[1], score_threshold=0.25,\n input_shape=tf.constant([input_size, input_size]))\n else:\n batch_data = tf.constant(image_data)\n pred_bbox = infer(batch_data)\n for key, value in pred_bbox.items():\n boxes = value[:, :, 0:4]\n pred_conf = value[:, :, 4:]\n\n boxes, scores, classes, valid_detections = tf.image.combined_non_max_suppression(\n boxes=tf.reshape(boxes, (tf.shape(boxes)[0], -1, 1, 4)),\n scores=tf.reshape(\n pred_conf, (tf.shape(pred_conf)[0], -1, tf.shape(pred_conf)[-1])),\n max_output_size_per_class=50,\n max_total_size=50,\n iou_threshold=FLAGS.iou,\n score_threshold=FLAGS.score\n )\n\n # format bounding boxes from normalized ymin, xmin, ymax, xmax ---> xmin, ymin, xmax, ymax\n original_h, original_w, _ = frame.shape\n bboxes = utils.format_boxes(boxes.numpy()[0], original_h, original_w)\n\n pred_bbox = [bboxes, scores.numpy()[0], classes.numpy()[0], valid_detections.numpy()[0]]\n\n # read in all class names from config\n class_names = utils.read_class_names(cfg.YOLO.CLASSES)\n\n # by default allow all classes in .names file\n allowed_classes = list(class_names.values())\n \n # custom allowed classes (uncomment line below to allow detections for only people)\n #allowed_classes = ['person']\n\n # if crop flag is enabled, crop each detection and save it as new image\n if FLAGS.crop:\n crop_rate = 150 # capture images every so many frames (ex. crop photos every 150 frames)\n crop_path = os.path.join(os.getcwd(), 'detections', 'crop', video_name)\n try:\n os.mkdir(crop_path)\n except FileExistsError:\n pass\n if frame_num % crop_rate == 0:\n final_path = os.path.join(crop_path, 'frame_' + str(frame_num))\n try:\n os.mkdir(final_path)\n except FileExistsError:\n pass \n crop_objects(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB), pred_bbox, final_path, allowed_classes)\n else:\n pass\n\n if FLAGS.count:\n # count objects found\n counted_classes = count_objects(pred_bbox, by_class = False, allowed_classes=allowed_classes)\n # loop through dict and print\n for key, value in counted_classes.items():\n print(\"Number of {}s: {}\".format(key, value))\n image = utils.draw_bbox(frame, pred_bbox, FLAGS.info, counted_classes, allowed_classes=allowed_classes, read_plate=FLAGS.plate)\n else:\n image = utils.draw_bbox(frame, pred_bbox, FLAGS.info, allowed_classes=allowed_classes, read_plate=FLAGS.plate)\n \n fps = 1.0 / (time.time() - start_time)\n print(\"FPS: %.2f\" % fps)\n result = np.asarray(image)\n cv2.namedWindow(\"result\", cv2.WINDOW_AUTOSIZE)\n result = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n \n if not FLAGS.dont_show:\n cv2.imshow(\"result\", result)\n \n if FLAGS.output:\n out.write(result)\n if cv2.waitKey(1) & 0xFF == ord('q'): break\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n try:\n app.run(main)\n except SystemExit:\n pass\n" ]
[ [ "tensorflow.compat.v1.ConfigProto", "tensorflow.constant", "tensorflow.saved_model.load", "tensorflow.config.experimental.set_memory_growth", "numpy.asarray", "tensorflow.lite.Interpreter", "tensorflow.config.experimental.list_physical_devices", "tensorflow.shape", "tensorflow.compat.v1.InteractiveSession" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sisl/delsmm
[ "11f2750356a7c7d8b196a67af747a9bc5f39b479", "11f2750356a7c7d8b196a67af747a9bc5f39b479" ]
[ "tests/test_barriercrit.py", "delsmm/utils.py" ]
[ "#\n# test_barriercrit.py\n#\n\nfrom delsmm.barriercrit import MxNormBarrierCriterion\nfrom delsmm.smm import StructuredMechanicalModel\nfrom delsmm.lagcrit import DELCriterion\nfrom ceem.opt_criteria import GroupCriterion\nimport torch \n\ndef test():\n\n\tqdim = 2\n\tB = 2\n\tT = 10\n\n\tt = torch.arange(T).unsqueeze(0).repeat(B,1).float()\n\tq = torch.randn(B,T,qdim)\n\n\tsys = StructuredMechanicalModel(qdim=qdim, dt=0.1)\n\tlb = MxNormBarrierCriterion.mmxnorm(sys, q).detach() / 10. # interior point init\n\n\tbarriercrit = MxNormBarrierCriterion(lb)\n\tdelcrit = DELCriterion(t)\n\n\tcrit = GroupCriterion([delcrit, barriercrit])\n\n\tprint(crit(sys, q))\n\n\n\nif __name__ == '__main__':\n\ttest()\n", "#\n# utils.py\n#\n\nfrom torch.autograd.functional import jacobian\nimport torch\nimport numpy as np\nfrom numpy import pi\nimport timeit\nimport random\nimport sys\ntry:\n import resource\nexcept ImportError:\n resource = None\n\nfrom contextlib import contextmanager\n\n\nfrom scipy.interpolate import UnivariateSpline\n\nfrom pykalman import KalmanFilter\nfrom scipy.linalg import expm\n\nfrom tqdm import tqdm\n\n\n\ndef _check_param_device(param, old_param_device):\n \"\"\"This helper function is to check if the parameters are located\n in the same device. Currently, the conversion between model parameters\n and single vector form is not supported for multiple allocations,\n e.g. parameters in different GPUs, or mixture of CPU/GPU.\n Arguments:\n param ([Tensor]): a Tensor of a parameter of a model\n old_param_device (int): the device where the first parameter of a\n model is allocated.\n Returns:\n old_param_device (int): report device for the first time\n \"\"\"\n\n # Meet the first parameter\n if old_param_device is None:\n old_param_device = param.get_device() if param.is_cuda else -1\n else:\n warn = False\n if param.is_cuda: # Check if in same GPU\n warn = (param.get_device() != old_param_device)\n else: # Check if in CPU\n warn = (old_param_device != -1)\n if warn:\n raise TypeError('Found two parameters on different devices, '\n 'this is currently not supported.')\n return old_param_device\n\ndef qqdot_to_q(qqdot, dt):\n \"\"\"\n Convert a timeseries of [q,qdot]_t to a T+1 timeseires of [q]_t\n Args:\n qqdot (torch.tensor): (B,T,qdim*2) [q,qdot]\n dt (float): timestemp\n Returns:\n q (torch.tensor): (B,T+1,qdim) \n Notes:\n Finds q_{1:T+1} s.t qqdot_t approx [0.5*(q_t+1 + q_t),\n (1./dt)*(q_t+1 - q_t)]\n \"\"\"\n\n B,T,qdim2 = qqdot.shape\n qdim = qdim2//2\n\n # find a matrix D that maps q to qddot\n a = torch.randn(T+1,qdim).reshape(-1)\n a.requires_grad = True\n def lam(a):\n a_ = a.reshape(T+1,qdim)\n b1 = 0.5*(a_[1:] + a_[:-1])\n b2 = (1./dt) * (a_[1:] - a_[:-1])\n b = torch.cat([b1,b2],dim=-1)\n return b.reshape(-1)\n D = jacobian(lam, a)\n\n # solve least squares problem\n q = torch.zeros(B,(T+1)*qdim)\n qqdot = qqdot.reshape(B,-1,1)\n for b in range(B):\n sol = torch.lstsq(qqdot[b], D)[0]\n q[b,:] = sol[:(T+1)*qdim].reshape(-1)\n\n return q.reshape(B,T+1,qdim)\n\ndef bfill_uppertriangle(A, vec):\n\tii, jj = np.triu_indices(A.size(-2), k=1, m=A.size(-1))\n\tA[..., ii, jj] = vec\n\treturn A\n\ndef bfill_lowertriangle(A, vec):\n ii, jj = np.tril_indices(A.size(-2), k=-1, m=A.size(-1))\n A[..., ii, jj] = vec\n return A\n\n\ndef bfill_diagonal(A, vec):\n ii, jj = np.diag_indices(min(A.size(-2), A.size(-1)))\n A[..., ii, jj] = vec\n return A\n\ndef parameter_grads_to_vector(parameters):\n \"\"\"Convert parameters to one vector\n Arguments:\n parameters (Iterable[Tensor]): an iterator of Tensors that are the\n parameters of a model.\n Returns:\n The parameters represented by a single vector\n \"\"\"\n # Flag for the device where the parameter is located\n param_device = None\n\n vec = []\n for param in parameters:\n # Ensure the parameters are located in the same device\n param_device = _check_param_device(param, param_device)\n\n if param.grad is not None:\n vec.append(param.grad.view(-1))\n else:\n zrs = torch.zeros_like(param)\n vec.append(zrs.view(-1))\n return torch.cat(vec)\n\n\ndef vector_to_parameter_grads(vec, parameters):\n \"\"\"Convert one vector to the parameters\n Arguments:\n vec (Tensor): a single vector represents the parameters of a model.\n parameters (Iterable[Tensor]): an iterator of Tensors that are the\n parameters of a model.\n \"\"\"\n # Ensure vec of type Tensor\n if not isinstance(vec, torch.Tensor):\n raise TypeError('expected torch.Tensor, but got: {}'.format(torch.typename(vec)))\n # Flag for the device where the parameter is located\n param_device = None\n\n # Pointer for slicing the vector for each parameter\n pointer = 0\n for param in parameters:\n # Ensure the parameters are located in the same device\n param_device = _check_param_device(param, param_device)\n\n # ensure that param requires grad\n assert param.requires_grad\n\n # The length of the parameter\n num_param = param.numel()\n # Slice the vector, reshape it, and replace the old grad of the parameter\n param.grad.data = vec[pointer:pointer + num_param].view_as(param).data\n\n # Increment the pointer\n pointer += num_param\n\n\ndef smooth_and_diff(x, dt, nders=2, **kwargs):\n \"\"\"\n Smooth a set of timeseries and differentiate them.\n Args:\n x (torch.tensor): (B,T,n) timeseries\n dt (float): time-step\n nders (int): number of derivatives to take\n **kwargs: arguments to UnivariateSpline\n Returns:\n smooth_series (list of torch.tensor): list of (B,T,n) smooth tensors (xsm, dxsmdt, ...)\n \"\"\"\n\n retvals = [torch.zeros_like(x) for i in range(nders+1)]\n\n B, T, N = x.shape\n t = np.arange(T) * dt\n for b in range(B):\n for n in range(N):\n ser = x[b,:,n].detach().numpy()\n spl = UnivariateSpline(t, ser, **kwargs)\n\n retvals[0][b,:,n] = torch.tensor(spl(t))\n for d in range(nders):\n retvals[d+1][b,:,n] = torch.tensor(spl.derivative(d)(t))\n\n return retvals\n\n\ndef kalman_smooth_and_diff(x, dt, nders=2, em_Q=False):\n \"\"\"\n Smooth a set of timeseries and differentiate them.\n Args:\n x (torch.tensor): (B,T,n) timeseries\n dt (float): time-step\n nders (int): number of derivatives to take\n em_Q (bool): learn transition cov?\n Returns:\n smooth_series (list of torch.tensor): list of (B,T,n) smooth tensors (xsm, dxsmdt, ...)\n \"\"\"\n\n retvals = [torch.zeros_like(x) for i in range(nders+1)]\n\n em_vars = ['initial_state_mean', 'initial_state_covariance', \n 'observation_covariance']\n if em_Q:\n em_vars += ['transition_covariance']\n\n if nders != 2:\n raise NotImplementedError\n\n A = np.array([[0.,1.,0.],\n [0.,0.,1.],\n [0.,0.,0.]])\n Ad = expm(A * dt)\n Bd = np.array([[1.,0.,0.]])\n\n Q = np.diag([0.001,0.001,1.0])\n\n B, T, N = x.shape\n for b in tqdm(range(B)):\n for n in range(N):\n ser = x[b,:,n:n+1].detach().numpy()\n\n kf = KalmanFilter(transition_matrices=Ad, observation_matrices=Bd, transition_covariance=Q)\n kf.em(ser, em_vars=em_vars)\n sm_x, _ = kf.smooth(ser)\n sm_x = torch.tensor(sm_x)\n\n for i in range(3):\n retvals[i][b,:,n] = sm_x[:,i]\n\n return retvals\n" ]
[ [ "torch.randn", "torch.arange" ], [ "numpy.diag", "scipy.interpolate.UnivariateSpline", "torch.lstsq", "torch.cat", "torch.autograd.functional.jacobian", "torch.zeros", "numpy.arange", "torch.randn", "torch.zeros_like", "torch.typename", "scipy.linalg.expm", "torch.tensor", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.12", "0.14", "0.15" ], "tensorflow": [] } ]
UPRMG/Classification_Airbnb
[ "2113199fd37c798bdec49402cef9238821168f33" ]
[ "Data_setting & Analysis/Final_Presentation/airpy/agd.py" ]
[ "\n# coding: utf-8\n\n# ### Import\n\n# In[5]:\n\n\nimport numpy as np\nimport pandas as pd\nimport xgboost\nimport xgboost as xgb\nfrom xgboost.sklearn import XGBClassifier\nfrom sklearn.metrics import *\nfrom IPython.core.display import Image \nfrom sklearn.datasets import make_classification\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.tree import export_graphviz\nimport io\nfrom sklearn.preprocessing import Imputer\nimport pydot\nfrom sklearn import preprocessing\nimport lightgbm as lgb\nfrom scipy.stats import mode\nimport re\nfrom datetime import datetime\nfrom lightgbm import plot_importance\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n# ---\n\n# ### Date read\n\n# In[7]:\n\n\nage_gender_bkts = pd.read_csv(\"age_gender_bkts.csv\")\ncountries = pd.read_csv(\"countries.csv\")\nsessions = pd.read_csv(\"sessions.csv\")\ntest_users = pd.read_csv(\"test_users.csv\")\ntrain_users_2 = pd.read_csv(\"train_users_2.csv\")\nsample_submission_NDF = pd.read_csv(\"sample_submission_NDF.csv\")\n\n\n# ---\n\n# ### Date setting\n\n# In[8]:\n\n\ndef pre_age_set_data(train_users_2, test_users):\n \n check = pd.concat([train_users_2, test_users], ignore_index=True)\n \n check[\"first_affiliate_tracked\"] = check[\"first_affiliate_tracked\"].replace(np.nan, \"untracked\")\n \n check[\"date_account_created\"] = pd.to_datetime(check[\"date_account_created\"], format = \"%Y-%m-%d\")\n check[\"timestamp_first_active\"] = pd.to_datetime(check[\"timestamp_first_active\"], format=\"%Y%m%d%H%M%S\")\n\n s_lag = check[\"timestamp_first_active\"] - check[\"date_account_created\"]\n\n check[\"lag_days\"] = s_lag.apply(lambda x : -1 * x.days)\n check[\"lag_seconds\"] = s_lag.apply(lambda x : x.seconds)\n\n s_all_check = (check['age'] < 120) & (check['gender'] != '-unknown-')\n\n check['faithless_sign'] = s_all_check.apply(lambda x : 0 if x == True else 1)\n \n pre_age = check.drop(\"date_first_booking\",axis = 1)\n \n pre_age['date_account_created_y'] = pre_age[\"date_account_created\"].apply(lambda x : x.year)\n pre_age['date_account_created_m'] = pre_age[\"date_account_created\"].apply(lambda x : x.month)\n pre_age['date_account_created_d'] = pre_age[\"date_account_created\"].apply(lambda x : x.day)\n\n pre_age['timestamp_first_active_y'] = pre_age[\"timestamp_first_active\"].apply(lambda x : x.year)\n pre_age['timestamp_first_active_m'] = pre_age[\"timestamp_first_active\"].apply(lambda x : x.month)\n pre_age['timestamp_first_active_d'] = pre_age[\"timestamp_first_active\"].apply(lambda x : x.day)\n\n pre_age = pre_age.drop(\"date_account_created\" , axis=1)\n pre_age = pre_age.drop(\"timestamp_first_active\" , axis=1)\n \n return check, pre_age\n\n\n# ---\n\n# # Gender\n\n# ### Gender predict data set\n\n# In[11]:\n\n\ndef pre_gen_predict_data(pre_age):\n \n pre_gen_sub = pre_age.filter(items = ['age', 'country_destination', 'id', 'gender'])\n pre_gen_dum = pre_age.filter(items = ['affiliate_channel', 'affiliate_provider',\n 'first_affiliate_tracked', 'first_browser', 'first_device_type',\n 'language', 'signup_app', 'signup_flow',\n 'signup_method', 'date_account_created_y', 'date_account_created_m',\n 'date_account_created_d', 'timestamp_first_active_y',\n 'timestamp_first_active_m', 'timestamp_first_active_d',\"lag_days\",\"lag_seconds\",\n \"faithless_sign\"])\n\n\n pre_gen_dum = pd.get_dummies(pre_gen_dum)\n pre_gen_dum_con = pd.concat([pre_gen_dum, pre_gen_sub], axis=1)\n pre_gen_dum_con[\"gender\"] = pre_gen_dum_con[\"gender\"].replace(['-unknown-', 'OTHER'], np.nan)\n\n pre_gen_mission = pre_gen_dum_con[pre_gen_dum_con[\"gender\"].isna()].reset_index()\n pre_gen_train = pre_gen_dum_con[pre_gen_dum_con[\"gender\"].notna()].reset_index()\n\n pre_gen_mission_test = pre_gen_mission.drop(\"index\", axis=1)\n pre_gen_train_test = pre_gen_train.drop(\"index\", axis=1)\n\n pre_gen_mission_test_drop = pre_gen_mission_test.drop(['id', 'age', 'country_destination', \"gender\"], axis=1)\n pre_gen_train_test_drop = pre_gen_train_test.drop(['id', 'age', 'country_destination', \"gender\"], axis=1)\n \n return pre_gen_mission_test, pre_gen_train_test, pre_gen_mission, pre_gen_train, pre_gen_mission_test_drop, pre_gen_train_test_drop\n\n\n# ### Gender predict LightGBM\n\n# In[12]:\n\n\ndef predict_gen_LightGBM(pre_gen_train_test_drop, pre_gen_train_test, pre_gen_mission_test_drop):\n\n X = pre_gen_train_test_drop\n y = pre_gen_train_test[\"gender\"]\n \n model_gen_lgb = lgb.LGBMClassifier(nthread=3)\n model_gen_lgb.fit(X,y)\n\n print(classification_report(y, model_gen_lgb.predict(pre_gen_train_test_drop)))\n model_gen_lgb = model_gen_lgb.predict(pre_gen_mission_test_drop)\n model_gen_lgb = pd.DataFrame(model_gen_lgb)\n \n return model_gen_lgb\n\n\n# ### Gender predict data make CSV\n\n# ---\n\n# # Age\n\n# ### Age predict data set\n\n# In[13]:\n\n\ndef pre_age_predict_data(pre_age):\n \n pre_age['age'] = pre_age['age'].fillna(-1)\n \n pre_age_sub = pre_age.filter(items = ['age', 'country_destination','id'])\n pre_age_dum = pre_age.filter(items = ['affiliate_channel', 'affiliate_provider',\n 'first_affiliate_tracked', 'first_browser', 'first_device_type',\n 'language', 'signup_app', 'signup_flow',\n 'signup_method', 'date_account_created_y', 'date_account_created_m',\n 'date_account_created_d', 'timestamp_first_active_y',\n 'timestamp_first_active_m', 'timestamp_first_active_d',\"lag_days\",\"lag_seconds\",\n \"faithless_sign\"])\n \n pre_age_dum = pd.get_dummies(pre_age_dum)\n pre_age_dum_con = pd.concat([pre_age_dum, pre_age_sub], axis=1)\n pre_age_dum_con[\"age\"] = pre_age_dum_con[\"age\"].replace(-1, np.nan)\n \n pre_age_mission = pre_age_dum_con[pre_age_dum_con[\"age\"].isna()].reset_index()\n pre_age_train = pre_age_dum_con[pre_age_dum_con[\"age\"].notna()].reset_index()\n \n pre_age_mission_test = pre_age_mission.drop(\"index\", axis=1)\n pre_age_train_test = pre_age_train.drop(\"index\", axis=1)\n \n pre_age_mission_test_drop = pre_age_mission_test.drop(['id', 'age', 'country_destination'], axis=1)\n pre_age_train_test_drop = pre_age_train_test.drop(['id', 'age', 'country_destination'], axis=1)\n \n return pre_age_mission_test, pre_age_train_test, pre_age_mission, pre_age_train, pre_age_mission_test_drop, pre_age_train_test_drop\n\n\n# In[14]:\n\n\ndef pre_age_predict_data_cat(pre_age_train):\n \n bins = [0, 15, 25, 35, 60, 9999]\n labels = [\"미성년자\", \"청년\", \"중년\", \"장년\", \"노년\"]\n cats = pd.cut(pre_age_train['age'], bins, labels=labels)\n cats = pd.DataFrame(cats)\n \n return cats\n\n\n# ### Age predict LightGBM\n\n# In[15]:\n\n\ndef predict_age_LightGBM(pre_age_train_test_drop, cats, pre_age_mission_test_drop):\n\n X = pre_age_train_test_drop\n y = cats\n \n model_age_lgb = lgb.LGBMClassifier(nthread=3)\n model_age_lgb.fit(X,y)\n\n print(classification_report(y, model_age_lgb.predict(pre_age_train_test_drop)))\n model_age_lgb = model_age_lgb.predict(pre_age_mission_test_drop)\n model_age_lgb = pd.DataFrame(model_age_lgb)\n \n return model_age_lgb\n\n\n# ### Age predict data make CSV\n\n# ---\n" ]
[ [ "pandas.concat", "pandas.read_csv", "pandas.to_datetime", "pandas.DataFrame", "pandas.cut", "pandas.get_dummies" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
whelan9453/incubator-superset
[ "4e3cea45a5136a28442eea50fddc6cf423a9ddd5" ]
[ "superset/examples/unicode_test_data.py" ]
[ "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\nimport datetime\nimport json\nimport random\n\nimport pandas as pd\nfrom sqlalchemy import Date, Float, String\n\nfrom superset import db\nfrom superset.utils import core as utils\n\nfrom .helpers import (\n config,\n Dash,\n get_example_data,\n get_slice_json,\n merge_slice,\n Slice,\n TBL,\n update_slice_ids,\n)\n\n\ndef load_unicode_test_data(only_metadata=False, force=False):\n \"\"\"Loading unicode test dataset from a csv file in the repo\"\"\"\n tbl_name = \"unicode_test\"\n database = utils.get_example_database()\n table_exists = database.has_table_by_name(tbl_name)\n\n if not only_metadata and (not table_exists or force):\n data = get_example_data(\n \"unicode_utf8_unixnl_test.csv\", is_gzip=False, make_bytes=True\n )\n df = pd.read_csv(data, encoding=\"utf-8\")\n # generate date/numeric data\n df[\"dttm\"] = datetime.datetime.now().date()\n df[\"value\"] = [random.randint(1, 100) for _ in range(len(df))]\n df.to_sql( # pylint: disable=no-member\n tbl_name,\n database.get_sqla_engine(),\n if_exists=\"replace\",\n chunksize=500,\n dtype={\n \"phrase\": String(500),\n \"short_phrase\": String(10),\n \"with_missing\": String(100),\n \"dttm\": Date(),\n \"value\": Float(),\n },\n index=False,\n )\n print(\"Done loading table!\")\n print(\"-\" * 80)\n\n print(\"Creating table [unicode_test] reference\")\n obj = db.session.query(TBL).filter_by(table_name=tbl_name).first()\n if not obj:\n obj = TBL(table_name=tbl_name)\n obj.main_dttm_col = \"dttm\"\n obj.database = database\n db.session.merge(obj)\n db.session.commit()\n obj.fetch_metadata()\n tbl = obj\n\n slice_data = {\n \"granularity_sqla\": \"dttm\",\n \"groupby\": [],\n \"metric\": {\n \"aggregate\": \"SUM\",\n \"column\": {\"column_name\": \"value\"},\n \"expressionType\": \"SIMPLE\",\n \"label\": \"Value\",\n },\n \"row_limit\": config.get(\"ROW_LIMIT\"),\n \"since\": \"100 years ago\",\n \"until\": \"now\",\n \"where\": \"\",\n \"viz_type\": \"word_cloud\",\n \"size_from\": \"10\",\n \"series\": \"short_phrase\",\n \"size_to\": \"70\",\n \"rotation\": \"square\",\n \"limit\": \"100\",\n }\n\n print(\"Creating a slice\")\n slc = Slice(\n slice_name=\"Unicode Cloud\",\n viz_type=\"word_cloud\",\n datasource_type=\"table\",\n datasource_id=tbl.id,\n params=get_slice_json(slice_data),\n )\n merge_slice(slc)\n\n print(\"Creating a dashboard\")\n dash = db.session.query(Dash).filter_by(slug=\"unicode-test\").first()\n\n if not dash:\n dash = Dash()\n js = \"\"\"\\\n{\n \"CHART-Hkx6154FEm\": {\n \"children\": [],\n \"id\": \"CHART-Hkx6154FEm\",\n \"meta\": {\n \"chartId\": 2225,\n \"height\": 30,\n \"sliceName\": \"slice 1\",\n \"width\": 4\n },\n \"type\": \"CHART\"\n },\n \"GRID_ID\": {\n \"children\": [\n \"ROW-SyT19EFEQ\"\n ],\n \"id\": \"GRID_ID\",\n \"type\": \"GRID\"\n },\n \"ROOT_ID\": {\n \"children\": [\n \"GRID_ID\"\n ],\n \"id\": \"ROOT_ID\",\n \"type\": \"ROOT\"\n },\n \"ROW-SyT19EFEQ\": {\n \"children\": [\n \"CHART-Hkx6154FEm\"\n ],\n \"id\": \"ROW-SyT19EFEQ\",\n \"meta\": {\n \"background\": \"BACKGROUND_TRANSPARENT\"\n },\n \"type\": \"ROW\"\n },\n \"DASHBOARD_VERSION_KEY\": \"v2\"\n}\n \"\"\"\n dash.dashboard_title = \"Unicode Test\"\n pos = json.loads(js)\n update_slice_ids(pos, [slc])\n dash.position_json = json.dumps(pos, indent=4)\n dash.slug = \"unicode-test\"\n dash.slices = [slc]\n db.session.merge(dash)\n db.session.commit()\n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
jacektl/calamari
[ "980477aefe4e56f7fc373119c1b38649798d8686" ]
[ "calamari_ocr/ocr/model/graph.py" ]
[ "from functools import partial\n\nimport tensorflow as tf\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import ctc_ops as ctc\nfrom tfaip.model.graphbase import GraphBase\n\nfrom calamari_ocr.ocr.model.layers.concat import ConcatLayerParams\nfrom calamari_ocr.ocr.model.layers.toinputdims import ToInputDimsLayerParams\nfrom calamari_ocr.ocr.model.layers.transposedconv2d import TransposedConv2DLayerParams\nfrom calamari_ocr.ocr.model.params import ModelParams\n\nkeras = tf.keras\nK = keras.backend\nKL = keras.layers\n\n\ndef calculate_padding(input, scaling_factor):\n def scale(i, f):\n return (f - i % f) % f\n\n shape = input.shape\n dyn_shape = K.shape(input)\n px = scale(shape[1] or K.gather(dyn_shape, 1), scaling_factor[0])\n py = scale(shape[2] or K.gather(dyn_shape, 2), scaling_factor[1])\n return px, py\n\n\ndef pad(input_tensors, x_only=False):\n input, padding = input_tensors[0], input_tensors[1]\n px, py = padding\n shape = K.shape(input)\n static_shape = input.shape\n if x_only:\n output = tf.image.pad_to_bounding_box(\n input, 0, 0, (static_shape[1] or K.gather(shape, 1)) + px, static_shape[2]\n )\n else:\n output = tf.image.pad_to_bounding_box(\n input,\n 0,\n 0,\n (static_shape[1] or K.gather(shape, 1)) + px,\n (static_shape[2] or K.gather(shape, 2)) + py,\n )\n return output\n\n\nclass CalamariGraph(GraphBase[ModelParams]):\n def __init__(self, params: ModelParams, name=\"CalamariGraph\", **kwargs):\n super().__init__(params, name=name, **kwargs)\n assert params.classes > 0, \"non initialized number of classes\"\n\n self.layer_instances = [l.create() for l in params.layers]\n\n self.reshape = ToInputDimsLayerParams(dims=3).create()\n self.logits = KL.Dense(params.classes, name=\"logits\")\n self.softmax = KL.Softmax(name=\"softmax\")\n\n def build_graph(self, inputs, training=None):\n params: ModelParams = self._params\n input_data = tf.cast(inputs[\"img\"], tf.float32) / 255.0\n input_sequence_length = K.flatten(inputs[\"img_len\"])\n shape = input_sequence_length, -1\n\n # if concat or conv_T layers are present, we need to pad the input to ensure that possible\n # up-sampling layers work properly\n require_padding = any([isinstance(l, (ConcatLayerParams, TransposedConv2DLayerParams)) for l in params.layers])\n if require_padding:\n s = self._params.compute_max_downscale_factor()\n padding = calculate_padding(input_data, s.to_tuple())\n padded = KL.Lambda(partial(pad, x_only=True), name=\"padded_input\")([input_data, padding])\n last_layer_output = padded\n else:\n last_layer_output = input_data\n\n layers_outputs_by_index = []\n for layer in self.layer_instances:\n layers_outputs_by_index.append(last_layer_output)\n if isinstance(layer.params, ConcatLayerParams):\n last_layer_output = layer(layers_outputs_by_index)\n else:\n last_layer_output = layer(last_layer_output)\n\n lstm_seq_len, lstm_num_features = self._params.compute_downscaled(shape)\n lstm_seq_len = K.cast(lstm_seq_len, \"int32\")\n\n last_layer_output = self.reshape(last_layer_output)\n blank_last_logits = self.logits(last_layer_output)\n blank_last_softmax = self.softmax(blank_last_logits)\n\n logits = tf.roll(blank_last_logits, shift=1, axis=-1)\n softmax = tf.nn.softmax(logits)\n\n greedy_decoded = ctc.ctc_greedy_decoder(\n inputs=array_ops.transpose(blank_last_logits, perm=[1, 0, 2]),\n sequence_length=tf.cast(K.flatten(lstm_seq_len), \"int32\"),\n )[0][0]\n\n return {\n \"blank_last_logits\": blank_last_logits,\n \"blank_last_softmax\": blank_last_softmax,\n \"out_len\": lstm_seq_len,\n \"logits\": logits,\n \"softmax\": softmax,\n \"decoded\": tf.sparse.to_dense(greedy_decoded, default_value=-1) + 1,\n }\n\n @classmethod\n def from_config(cls, config):\n try:\n return super().from_config(config)\n except TypeError:\n # convert old format?\n from calamari_ocr.ocr.savedmodel.migrations.version3to4 import (\n migrate_model_params,\n )\n\n migrate_model_params(config[\"params\"])\n return super().from_config(config)\n" ]
[ [ "tensorflow.python.ops.array_ops.transpose", "tensorflow.nn.softmax", "tensorflow.sparse.to_dense", "tensorflow.roll", "tensorflow.cast" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.12", "2.6", "2.7", "1.13", "2.3", "2.4", "2.9", "1.7", "2.5", "2.2", "2.10" ] } ]
son-n-pham/Youtube-View-Bot
[ "e7f7779b88ce451b454253cd156d8eb6624a4fa4" ]
[ "proxy.py" ]
[ "# This is to replace the manual download of ChromeDriver by using webdriver_manager\n# selenium.webdriver.chrome.service is used as the previous version of directly referring ChromeDriver is depreciated\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.service import Service\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport pandas as pd\nimport time\n\nPROXIES_FILE = \"proxies.csv\" # file to save list of proxies\nPROXIES_MIN_NUM = 3 # minimum number of proxies in the list\nNUMBER_OF_BOT = 3 # number of bots\nTIMEOUT = 120 # parameter of timeout for selenium to connect to the desired web\nWEBPAGE = \"https://www.youtube.com/watch?v=hL_chrFfJxY\"\n\n\ndef open_webpage(webpage, proxy=None):\n if proxy is not None:\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument(f'--proxy-server={proxy}')\n driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)\n else:\n driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))\n driver.set_page_load_timeout(TIMEOUT)\n driver.get(webpage)\n return driver\n\n\ndef proxies_to_csv(proxies, proxies_file=PROXIES_FILE):\n if isinstance(proxies, pd.DataFrame):\n proxies.to_csv(proxies_file, index=False)\n elif isinstance(proxies, list):\n pd.DataFrame.from_dict({\"proxy\": proxies}).to_csv(proxies_file, index=False)\n else:\n print(\"This function can save only DataFram or list to csv file.\")\n\n\ndef proxy_list_read(proxy_file=PROXIES_FILE):\n # Read proxies.csv or create the empty proxies.csv if that file does not exist\n # Return df DataFrame as the result\n try:\n df = pd.read_csv(proxy_file)\n print(f\"{PROXIES_FILE} exists\")\n except FileNotFoundError:\n print(f\"Create new {PROXIES_FILE}\")\n proxies_to_csv([])\n df = proxy_list_read()\n\n return df\n\n\ndef proxy_list_download(df, proxy_web=\"https://free-proxy-list.net/\"):\n df = proxy_list_read()\n\n driver = open_webpage(proxy_web)\n\n proxy_rows = driver.find_elements(By.CSS_SELECTOR, \".table tbody tr\")\n\n proxies_added_count = 0\n\n row_count = 0\n for row in proxy_rows:\n row_count += 1\n proxy_row = row.find_elements(By.CSS_SELECTOR, \"td\")\n try:\n proxy = f\"{proxy_row[0].text}:{proxy_row[1].text}\"\n if proxy not in list(df[\"proxy\"]):\n df = df.append({\"proxy\": proxy}, ignore_index=True)\n print(f\"{proxy} was added into {PROXIES_FILE}\")\n proxies_added_count += 1\n except IndexError:\n print(f\"{proxies_added_count} proxies were added into the proxies.csv file.\")\n break\n\n print(df.head())\n\n proxies_to_csv(df)\n\n driver.close()\n\n\nif __name__ == \"__main__\":\n\n # Ensure having at least 3 proxy for web grapping\n while True:\n proxies_df = proxy_list_read()\n print(len(proxies_df.index))\n if len(proxies_df.index) < PROXIES_MIN_NUM:\n proxy_list_download(proxies_df)\n else:\n break\n" ]
[ [ "pandas.read_csv", "pandas.DataFrame.from_dict" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
vinferrer/aroma
[ "7b25510cfc7c655513ac72dc6cff22546f46dd16" ]
[ "aroma/plotting.py" ]
[ "\"\"\"Plotting functions for ICA-AROMA.\"\"\"\nimport logging\nimport os\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib import gridspec\n\nmpl.use('Agg')\nLGR = logging.getLogger(__name__)\n\n\ndef classification_plot(in_file, out_dir):\n \"\"\"Generate a figure to show classifications.\n\n Parameters\n ----------\n in_file : str\n Path to tab-delimited file with feature scores and classification.\n out_dir : str\n Output directory.\n \"\"\"\n if not os.path.isfile(in_file):\n raise FileNotFoundError(f\"Input file does not exist: {in_file}\")\n\n df = pd.read_table(in_file)\n motion_components_df = df.loc[df[\"classification\"] == \"rejected\"]\n\n # get counts\n n_components = df.shape[0]\n n_motion_components = motion_components_df.shape[0]\n LGR.info('Found', n_motion_components, 'head motion-related components in a total of',\n n_components, 'components.')\n\n # add dummy components if needed, this is just for making the plots look nice\n if n_motion_components < 3:\n temp_df = pd.DataFrame(\n {\n \"classification\": [\"rejected\", \"rejected\", \"rejected\"],\n \"max_RP_corr\": [1.0, 1.0, 1.0],\n \"edge_fract\": [1.0, 1.0, 1.0],\n \"HFC\": [0.0, 0.0, 0.0],\n \"csf_fract\": [0.0, 0.0, 0.0],\n }\n )\n df = df.append(temp_df, ignore_index=True)\n\n if df.loc[df[\"classification\"] == \"accepted\"].shape[0] < 3:\n temp_df = pd.DataFrame(\n {\n \"classification\": [\"accepted\", \"accepted\", \"accepted\"],\n \"max_RP_corr\": [0.0, 0.0, 0.0],\n \"edge_fract\": [0.0, 0.0, 0.0],\n \"HFC\": [0.0, 0.0, 0.0],\n \"csf_fract\": [0.0, 0.0, 0.0],\n }\n )\n df = df.append(temp_df, ignore_index=True)\n\n # rename columns\n df = df.rename(\n columns={\n \"classification\": \"Motion\",\n \"max_RP_corr\": \"RP\",\n \"edge_fract\": \"Edge\",\n \"HFC\": \"Freq\",\n \"csf_fract\": \"CSF\",\n }\n )\n df[\"classification\"] = df[\"classification\"].map(\n {\"rejected\": \"True\", \"accepted\": \"False\"}\n )\n\n # Make pretty figure\n # styling\n sns.set_style(\"white\")\n colortrue = \"#FFBF17\"\n colorfalse = \"#69A00A\"\n\n # create figure\n fig = plt.figure(figsize=[12, 4])\n\n # define grids\n gs = gridspec.GridSpec(4, 7, wspace=1)\n gs00 = gridspec.GridSpecFromSubplotSpec(4, 4, subplot_spec=gs[:, 0:3])\n gs01 = gridspec.GridSpecFromSubplotSpec(4, 1, subplot_spec=gs[:, 3:5])\n gs02 = gridspec.GridSpecFromSubplotSpec(4, 1, subplot_spec=gs[:, 5:7])\n\n # define subplots\n # Edge/RP\n ax1 = fig.add_subplot(gs00[1:4, 0:3])\n # distribution edge (ax1 top)\n ax1t = fig.add_subplot(gs00[0, 0:3])\n # distribution RP (ax1 right)\n ax1r = fig.add_subplot(gs00[1:4, 3])\n # Freq\n ax2 = fig.add_subplot(gs01[1:4, :])\n # CSF\n ax3 = fig.add_subplot(gs02[1:4, :])\n\n # plot Freq\n sns.boxplot(\n x=\"Motion\",\n y=\"Freq\",\n data=df,\n ax=ax2,\n palette=[colortrue, colorfalse],\n order=[\"True\", \"False\"],\n )\n ax2.hlines(0.35, -1, 2, zorder=0, linestyles=\"dotted\", linewidth=0.5)\n ax2.set_ylim([0, 1])\n ax2.set_xlabel(\"Classification\", fontsize=14, labelpad=10)\n ax2.set_ylabel(\"High-Frequency Content\", fontsize=14)\n ax2.set_xticklabels([\"Motion\", \"Other\"])\n ax2.tick_params(axis=\"both\", labelsize=12)\n sns.despine(ax=ax2)\n\n # plot CSF\n sns.boxplot(\n x=\"Motion\",\n y=\"CSF\",\n data=df,\n ax=ax3,\n palette=[colortrue, colorfalse],\n order=[\"True\", \"False\"],\n )\n ax3.hlines(0.1, -1, 2, zorder=0, linestyles=\"dotted\", linewidth=0.5)\n ax3.set_ylim([0, 1])\n ax3.set_xlabel(\"Classification\", fontsize=14, labelpad=10)\n ax3.set_ylabel(\"CSF Fraction\", fontsize=14)\n ax3.set_xticklabels([\"Motion\", \"Other\"])\n ax3.tick_params(axis=\"both\", labelsize=12)\n sns.despine(ax=ax3)\n\n # plot Edge/RP relationship\n # obtain projection line\n hyp = np.array([-19.9751070082159, 9.95127547670627, 24.8333160239175])\n a = -hyp[1] / hyp[2]\n xx = np.linspace(0, 1)\n yy = a * xx - hyp[0] / hyp[2]\n # plot scatter and line\n if len(df) > 100:\n sizemarker = 6\n else:\n sizemarker = 10\n ax1.scatter(\n x=\"RP\",\n y=\"Edge\",\n data=df.loc[df[\"Motion\"] == \"False\"],\n color=colorfalse,\n s=sizemarker,\n )\n # plot true ones on top to see how much the go over the border\n # this gives an indication for how many were selected using the\n # two other features\n ax1.scatter(\n x=\"RP\",\n y=\"Edge\",\n data=df.loc[df[\"Motion\"] == \"True\"],\n color=colortrue,\n s=sizemarker,\n )\n # add decision boundary\n ax1.plot(xx, yy, \".\", color=\"k\", markersize=1)\n # styling\n ax1.set_ylim([0, 1])\n ax1.set_xlim([0, 1])\n ax1.set_xlabel(\"Maximum RP Correlation\", fontsize=14, labelpad=10)\n ax1.set_ylabel(\"Edge Fraction\", fontsize=14)\n ax1.set_xticks(np.arange(0, 1.2, 0.2))\n ax1.set_yticks(np.arange(0, 1.2, 0.2))\n ax1.tick_params(axis=\"both\", labelsize=12)\n\n # plot distributions\n # RP\n sns.distplot(\n df.loc[df[\"Motion\"] == \"True\", \"RP\"],\n ax=ax1t,\n color=colortrue,\n hist_kws={\"alpha\": 0.2},\n )\n sns.distplot(\n df.loc[df[\"Motion\"] == \"False\", \"RP\"],\n ax=ax1t,\n color=colorfalse,\n hist_kws={\"alpha\": 0.2},\n )\n ax1t.set_xlim([0, 1])\n\n # Edge\n sns.distplot(\n df.loc[df[\"Motion\"] == \"True\", \"Edge\"],\n ax=ax1r,\n vertical=True,\n color=colortrue,\n hist_kws={\"alpha\": 0.2},\n )\n sns.distplot(\n df.loc[df[\"Motion\"] == \"False\", \"Edge\"],\n ax=ax1r,\n vertical=True,\n color=colorfalse,\n hist_kws={\"alpha\": 0.2},\n )\n ax1r.set_ylim([0, 1])\n\n # cosmetics\n for myax in [ax1t, ax1r]:\n myax.set_xticks([])\n myax.set_yticks([])\n myax.set_xlabel(\"\")\n myax.set_ylabel(\"\")\n myax.spines[\"right\"].set_visible(False)\n myax.spines[\"top\"].set_visible(False)\n myax.spines[\"bottom\"].set_visible(False)\n myax.spines[\"left\"].set_visible(False)\n\n # bring tickmarks back\n for myax in fig.get_axes():\n myax.tick_params(which=\"major\", direction=\"in\", length=3)\n\n # add figure title\n plt.suptitle(\"Component Assessment\", fontsize=20)\n\n # outtakes\n plt.savefig(\n os.path.join(out_dir, \"ICA_AROMA_component_assessment.svg\"),\n bbox_inches=\"tight\",\n dpi=300,\n )\n" ]
[ [ "matplotlib.gridspec.GridSpecFromSubplotSpec", "numpy.linspace", "matplotlib.use", "numpy.arange", "pandas.DataFrame", "pandas.read_table", "matplotlib.gridspec.GridSpec", "matplotlib.pyplot.suptitle", "numpy.array", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
vargacypher/EfficienzaDecompac
[ "bd9ae5b692114ed77af01458622d484468681e2b" ]
[ "descompact.py" ]
[ "import numpy as np\r\nimport pandas as pd \r\nimport xml.etree.ElementTree as et \r\nfrom os import listdir\r\nfrom datetime import datetime\r\nimport os, zipfile\r\nimport shutil,glob\r\nimport regex as re \r\nimport pyodbc\r\nfrom os.path import isfile, join, basename\r\nimport warnings\r\nfrom pandas.core.common import SettingWithCopyWarning\r\nwarnings.simplefilter(action=\"ignore\", category=SettingWithCopyWarning)\r\n\r\n\r\ndir_name='\\\\Users\\\\............'\r\nzip_files = glob.glob(dir_name + '*.zip')\r\n\r\ndef descompact():\r\n for item in zip_files:\r\n #print(item)\r\n if item.endswith('zip'):\r\n#Pega o path inteiro do arquivo\r\n file_name = os.path.abspath(item) \r\n \r\n#Cria zipfile object\r\n zip_ref = zipfile.ZipFile(file_name)\r\n \r\n# Pega uma lista de todos os arquivos zip \r\n listOfFileNames = zip_ref.namelist()\r\n \r\n for fileName in listOfFileNames:\r\n \r\n# Checa por arquivos XML dentro de arquivos ZIP\r\n if fileName.endswith('.xml'):\r\n \r\n# Extract\r\n shutil.unpack_archive(item, dir_name)\r\n \r\n print('*Arquivo extraido com sucesso : ',fileName)\r\n\r\n\r\n\r\nfile2 = '\\\\Users\\\\........\\\\BackupZip'\r\n\r\n#Mover os arquivos antigos para outra pasta backup\r\ndef move(path_origem, path_destino, ext='zip'):\r\n for item in [join(path_origem, f) for f in listdir(path_origem) if isfile(join(path_origem, f)) and f.endswith(ext)]:\r\n #print(item)\r\n shutil.move(item, join(path_destino, basename(item)))\r\n print('moved \"{}\" -> \"{}\"'.format(item, join(path_destino, basename(item))))\r\n\r\n\r\ndef getvalueofnode(node):\r\n\r\n return node.text if node is not None else None\r\n\r\n\r\ndef ParseXml():\r\n for item in os.listdir('\\\\Users\\.......'):\r\n if item.endswith('.xml'):\r\n print(\"Parsed item: \"+item)\r\n parsedXML = et.parse('\\\\Users\\\\vargascypher\\\\Desktop\\\\Efficienza\\\\'+item)\r\n dfcols = ['MeterLocalID', 'AcquisitionDateTime', 'Value']\r\n df = pd.DataFrame(columns=dfcols)\r\n \r\n for node in parsedXML.findall('.//MeterData'):\r\n MeterId = node.find('MeterLocalId')\r\n timestamp = node.find('AcquisitionDateTime')\r\n Value = node.find('Value')\r\n df = df.append(pd.Series([getvalueofnode(MeterId), getvalueofnode(timestamp), getvalueofnode(Value)], index=dfcols), ignore_index=True) \r\n \r\n#Filtrando os campos desejados\r\n df = df[df['MeterLocalID'].str.contains('CODI_KW_DEL|CODI_KVAR_DEL_CAP|CODI_KVAR_DEL_IND', na = True)] # 'na = True' Filtra valores nuls \r\n \r\n df.to_csv(r'C:\\\\Users\\\\.........'+str(item[:-4])+'.csv', index=None)\r\n \r\n\r\ndef pre_tatramento():\r\n\r\n path='\\\\Users\\\\..........'\r\n\r\n all_file = glob.glob(path + '*.csv')\r\n\r\n#Cria um dicionario\r\n li={}\r\n \r\n for filename in all_file:\r\n id = re.findall(r\"\\_(\\d+)\\_\",filename)[0] #Utiliza regex para localizar somente o numero contido no nome dos arquivos\r\n if id not in li: #Lê os arquivos e compara com a keys do dicionario\r\n #li[id] Cria essa key no dicionario e armazena com o dataframe\r\n li[id]=pd.read_csv(filename) \r\n else:\r\n #Se o ID já existir concatena com o outro dataframe \r\n li[id] = pd.concat([li[id],pd.read_csv(filename)])\r\n\r\n #Para os valores contidos no dicionario converte o valor(V) para um csv \r\n#Nomeia o arquivo com a key (k) + data\r\n for k,v in li.items():\r\n v.to_csv(f'C:\\\\Users\\\\.........Pre_Trat\\\\{k}_{datetime.today().date()}.csv', index=None)\r\n print (f'csv gerado: {k}_{datetime.today().date()}') \r\n\r\n\r\n\r\ndef tratamento():\r\n path_fin = '\\\\Users\\\\.........\\\\Pre_Trat\\\\'\r\n all_files = glob.glob(path_fin + '*.csv')\r\n\r\n df_IDS = pd.read_csv('ids.csv') \r\n ID_CSV = df_IDS.id.unique()\r\n ID_CSV\r\n\r\n for file in all_files:\r\n file_dict = {} \r\n id = re.findall(r\"\\d+\",file)[0] #Utiliza regex para localizar somente o numero contido no nome dos arquivos\r\n id = int(id)\r\n if id not in file_dict: #Cria um dicionario das ids dos arquivos e compra eles com as ids do CSV principal\r\n file_dict[id] = id\r\n for keys in file_dict.keys():\r\n if keys in ID_CSV:# ve se o arquivo ESTÁ na lista de ids, caso esteja cria o dataframe\r\n print(f'Item sendo tratado: {file}')\r\n\r\n df_base = pd.read_csv(file)\r\n\r\n #Transforma a coluna em um float\r\n\r\n df_base = df_base.astype({'Value': float})\r\n \r\n\r\n #Remove os 5 caracteres do timezone\r\n df_base['AcquisitionDateTime'] = df_base['AcquisitionDateTime'].str[:-5]\r\n\r\n #Converte uma String em Timestamp\r\n df_base[\"AcquisitionDateTime\"] = df_base[\"AcquisitionDateTime\"].apply(lambda x: datetime.strptime(x, '%Y-%m-%dT%H:%M:%S'))\r\n\r\n #Arredonda para de 15 em 15minutos\r\n df_base[\"AcquisitionDateTime\"] = df_base[\"AcquisitionDateTime\"].dt.round('15min')\r\n\r\n #CÁLCULOS\r\n df_base['Value'] = df_base['Value'].apply(lambda x:x/1000)\r\n\r\n # Agrupando valores pelo timestamp\r\n df_base = df_base.sort_values(by=['AcquisitionDateTime'], ascending=True)\r\n\r\n df_base = df_base.reset_index()\r\n\r\n\r\n#Dividindo os dataframes para filtrar os Value pelo final da ID.\r\n #Etapa necessária para a relização dos cálculos\r\n\r\n #Filtros\r\n df_kw = df_base[df_base['MeterLocalID'].str.contains('CODI_KW_DEL')]\r\n \r\n \r\n #INESERE UMA COLUNA COM O NOME DO MEDIDOR\r\n df_kw['id'] = keys\r\n\r\n #Converte de STR para float\r\n\r\n #df_kw = df_kw.astype({'id': float}) \r\n\r\n constant_df = pd.merge(df_kw, df_IDS, on='id')\r\n constant_df['constante'] = constant_df['constante'].apply(lambda x: round(x,6))\r\n constante = constant_df['constante'].unique()\r\n\r\n #Extrai SourceID para query\r\n SourceID = constant_df.SourceID.unique().tolist()\r\n for i in SourceID:\r\n i\r\n print('SourceID:',i)\r\n\r\n df_kw['kW'] = df_base ['Value'].apply(lambda x: x*constante)\r\n df_kw = df_kw.astype({'kW': float})\r\n\r\n df_kw['kWh'] = df_base ['Value'].apply(lambda x: (x*constante)/4)\r\n df_kw = df_kw.astype({'kWh': float})\r\n\r\n\r\n df_ind = df_base[df_base['MeterLocalID'].str.contains('CODI_KVAR_DEL_IND')]\r\n\r\n df_cap = df_base[df_base['MeterLocalID'].str.contains('CODI_KVAR_DEL_CAP')]\r\n\r\n df_kw.reset_index()\r\n df_cap.reset_index()\r\n df_ind.reset_index()\r\n\r\n #Transformando em array para os cálculos\r\n ind = df_ind.to_numpy()\r\n ind = ind[:,3]\r\n ind = ind.astype(np.float64)\r\n\r\n cap = df_cap.to_numpy()\r\n cap = cap[:,3]\r\n cap = cap.astype(np.float64)\r\n\r\n#Cálculos\r\n nkva = ((cap + ind)) * constante\r\n df_kw['kVar'] = nkva\r\n\r\n nkvah = (nkva)/4\r\n df_kw['kVarh'] = nkvah\r\n\r\n nkw = df_kw.to_numpy()\r\n nkw = nkw[:,5]\r\n nkw[nkw==0] = 1\r\n\r\n nFP = (nkw*100) / (((nkw**2) + (nkva**2))**0.5)\r\n\r\n df_kw['FP'] = nFP\r\n \r\n df_kw = df_kw[[\"AcquisitionDateTime\",\"kW\",\"kWh\",\"kVar\",\"kVarh\",\"FP\",\"id\"]]\r\n\r\n#Arrendoda para mostrar apenas 2 casas após a virgula\r\n df_kw['FP'] = df_kw['FP'].apply(lambda x: round(x,2))\r\n\r\n\r\n#Soma cumulativa, consumo de acordo com valores do banco\r\n\r\n #Conexão com o banco\r\n cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=IP\\SCHEMA,1433;DATABASE=exemple;UID=pythondb;PWD=aaaaaaaaa;')\r\n\r\n #consulta\r\n query = ('SELECT [ID],[Value],[SourceID],[QuantityID],[TimestampUTC] FROM [ION_Data].[dbo].[vwDataLog2]where SourceID = %s and (QuantityID = 91 or QuantityID = 129) AND Value IS NOT NULL order by TimestampUTC desc OFFSET 0 ROWS FETCH NEXT 2 ROWS ONLY' %i)\r\n\r\n #Transforma em dataframe\r\n data = pd.read_sql(query,cnxn)\r\n\r\n #Filtrando os campos desejados\r\n data_filt91 = data.query('QuantityID == 91')\r\n data_filt91\r\n\r\n data_filt129 = data.query('QuantityID == 129')\r\n data_filt129\r\n \r\n x = data_filt129['Value'].to_numpy()\r\n df_kw.loc[:0,\"kWh\"] = df_kw.loc[:0,\"kWh\"] + x #Soma na primeira linha\r\n df_kw['kWh'] = df_kw['kWh'].cumsum()\r\n\r\n\r\n y = data_filt91['Value'].to_numpy()\r\n df_kw.loc[:0,\"kVarh\"] = df_kw.loc[:0,\"kVarh\"] + y #Soma na primeira linha\r\n df_kw['kVarh'] = df_kw['kVarh'].cumsum()\r\n\r\n #Salva CSV final\r\n df_kw.to_csv(f'C:\\\\Users\\\\vargascypher\\\\Desktop\\\\Efficienza\\\\Tratados_final\\\\{keys}_{datetime.now().strftime(\"%Y%m%d-%H%M%S\")}.csv', index=None)\r\n print (f'csv gerado: {keys}_{datetime.now().strftime(\"%Y%m%d-%H%M%S\")}') \r\n\r\n\r\n\r\n else: #Se não estiver na lista não ira Tratar o arquivo\r\n print(f'ID Não Cadastrado: {keys}')\r\n \r\n\r\ndef remove_olds():\r\n df_IDS = pd.read_csv('ids.csv') \r\n ID_CSV = df_IDS.id.unique()\r\n ID_CSV\r\n\r\n path_firs = '\\\\Users\\\\........'\r\n all_files = glob.glob(path_firs + '*.csv')\r\n\r\n path='\\\\Users.......'\r\n all_xml = glob.glob(path + '*.xml')\r\n\r\n path_Pre_Trat='\\\\Users\\\\........\\\\Pre_Trat\\\\'\r\n all_csv = glob.glob(path_Pre_Trat + '*.csv')\r\n\r\n for olds in all_files:\r\n os.remove(olds)\r\n print(f\"Item removido: {olds}\")\r\n\r\n for olds in all_xml:\r\n os.remove(olds)\r\n print(f\"Item removido: {olds}\")\r\n\r\n \r\n for olds in all_csv:\r\n csv_dict = {}\r\n id = re.findall(r\"\\d+\",olds)[0] #Utiliza regex para localizar somente o numero contido no nome dos arquivos\r\n id = int(id)\r\n if id not in csv_dict: #Cria um dicionario das ids dos arquivos e compra eles com as ids do CSV principal\r\n csv_dict[id] = id\r\n for keys in csv_dict.keys():\r\n if keys in ID_CSV:# ve se o arquivo NÃO ESTÁ na lista de ids, caso nao esteja \r\n os.remove(olds)\r\n print(f'Item removido: {olds}')\r\n\r\n else: #Se ESTIVER na lista remove os arquivos antigos\r\n print(f'ID Não Cadastrado: {keys}')\r\n\r\n\r\nif __name__ == '__main__':\r\n descompact()\r\n move(dir_name, file2)\r\n ParseXml()\r\n pre_tatramento()\r\n tratamento()\r\n remove_olds()" ]
[ [ "pandas.read_sql", "pandas.merge", "pandas.read_csv", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
cirosantilli/vaex
[ "0247f0673c5c0473001b0b66adcbc716560536aa" ]
[ "packages/vaex-jupyter/vaex/jupyter/bqplot.py" ]
[ "from __future__ import absolute_import\nimport copy\nimport logging\nimport bqplot.marks\nimport bqplot as bq\nimport bqplot.interacts\nimport ipywidgets as widgets\nimport ipyvuetify as v\n\nimport vaex\nimport bqplot.pyplot as plt\nimport numpy as np\nimport vaex.events\nfrom .plot import BackendBase\nfrom .utils import debounced\n\nlogger = logging.getLogger(\"vaex.nb.bqplot\")\n\n\nclass BqplotBackend(BackendBase):\n def __init__(self, figure=None, figure_key=None):\n self._dirty = False\n self.figure_key = figure_key\n self.figure = figure\n self.signal_limits = vaex.events.Signal()\n\n self._cleanups = []\n\n def update_image(self, rgb_image):\n with self.output:\n rgb_image = (rgb_image * 255.).astype(np.uint8)\n pil_image = vaex.image.rgba_2_pil(rgb_image)\n data = vaex.image.pil_2_data(pil_image)\n self.core_image.value = data\n # force update\n self.image.image = self.core_image_fix\n self.image.image = self.core_image\n self.image.x = (self.scale_x.min, self.scale_x.max)\n self.image.y = (self.scale_y.min, self.scale_y.max)\n\n def create_widget(self, output, plot, dataset, limits):\n self.plot = plot\n self.output = output\n self.dataset = dataset\n self.limits = np.array(limits).tolist()\n def fix(v):\n # bqplot is picky about float and numpy scalars\n if hasattr(v, 'item'):\n return v.item()\n else:\n return v\n self.scale_x = bqplot.LinearScale(min=fix(limits[0][0]), max=fix(limits[0][1]), allow_padding=False)\n self.scale_y = bqplot.LinearScale(min=fix(limits[1][0]), max=fix(limits[1][1]), allow_padding=False)\n self.scale_rotation = bqplot.LinearScale(min=0, max=1)\n self.scale_size = bqplot.LinearScale(min=0, max=1)\n self.scale_opacity = bqplot.LinearScale(min=0, max=1)\n self.scales = {'x': self.scale_x, 'y': self.scale_y, 'rotation': self.scale_rotation,\n 'size': self.scale_size, 'opacity': self.scale_opacity}\n\n margin = {'bottom': 30, 'left': 60, 'right': 0, 'top': 0}\n self.figure = plt.figure(self.figure_key, fig=self.figure, scales=self.scales, fig_margin=margin)\n self.figure.layout.min_width = '600px'\n plt.figure(fig=self.figure)\n self.figure.padding_y = 0\n x = np.arange(0, 10)\n y = x ** 2\n self._fix_scatter = s = plt.scatter(x, y, visible=False, rotation=x, scales=self.scales)\n self._fix_scatter.visible = False\n # self.scale_rotation = self.scales['rotation']\n src = \"\" # vaex.image.rgba_to_url(self._create_rgb_grid())\n # self.scale_x.min, self.scale_x.max = self.limits[0]\n # self.scale_y.min, self.scale_y.max = self.limits[1]\n self.core_image = widgets.Image(format='png')\n self.core_image_fix = widgets.Image(format='png')\n\n self.image = bqplot.Image(scales=self.scales, image=self.core_image)\n self.figure.marks = self.figure.marks + [self.image]\n # self.figure.animation_duration = 500\n self.figure.layout.width = '100%'\n self.figure.layout.max_width = '500px'\n self.scatter = s = plt.scatter(x, y, visible=False, rotation=x, scales=self.scales, size=x, marker=\"arrow\")\n self.panzoom = bqplot.PanZoom(scales={'x': [self.scale_x], 'y': [self.scale_y]})\n self.figure.interaction = self.panzoom\n # self.figure.axes[0].label = self.x\n # self.figure.axes[1].label = self.y\n\n self.scale_x.observe(self._update_limits, \"min\")\n self.scale_x.observe(self._update_limits, \"max\")\n self.scale_y.observe(self._update_limits, \"min\")\n self.scale_y.observe(self._update_limits, \"max\")\n self.observe(self._update_scales, \"limits\")\n\n self.image.observe(self._on_view_count_change, 'view_count')\n self.control_widget = widgets.VBox()\n self.widget = widgets.VBox(children=[self.figure])\n self.create_tools()\n\n def _update_limits(self, *args):\n with self.output:\n limits = copy.deepcopy(self.limits)\n limits[0:2] = [[scale.min, scale.max] for scale in [self.scale_x, self.scale_y]]\n self.limits = limits\n\n def _update_scales(self, *args):\n with self.scale_x.hold_trait_notifications():\n self.scale_x.min = self.limits[0][0]\n self.scale_x.max = self.limits[0][1]\n with self.scale_y.hold_trait_notifications():\n self.scale_y.min = self.limits[1][0]\n self.scale_y.max = self.limits[1][1]\n # self.update_grid()\n\n def create_tools(self):\n self.tools = []\n tool_actions = []\n tool_actions_map = {u\"pan/zoom\": self.panzoom}\n tool_actions.append(u\"pan/zoom\")\n\n # self.control_widget.set_title(0, \"Main\")\n self._main_widget = widgets.VBox()\n self._main_widget_1 = widgets.HBox()\n self._main_widget_2 = widgets.HBox()\n if 1: # tool_select:\n self.brush = bqplot.interacts.BrushSelector(x_scale=self.scale_x, y_scale=self.scale_y, color=\"green\")\n tool_actions_map[\"select\"] = self.brush\n tool_actions.append(\"select\")\n\n self.brush.observe(self.update_brush, [\"selected\", \"selected_x\"])\n # fig.interaction = brush\n # callback = self.dataset.signal_selection_changed.connect(lambda dataset: update_image())\n # callback = self.dataset.signal_selection_changed.connect(lambda *x: self.update_grid())\n\n # def cleanup(callback=callback):\n # self.dataset.signal_selection_changed.disconnect(callback=callback)\n # self._cleanups.append(cleanup)\n\n self.button_select_nothing = v.Btn(icon=True, slot='activator', children=[\n v.Icon(children=['delete'])\n ])\n self.widget_select_nothing = v.Tooltip(bottom=True, children=[\n self.button_select_nothing,\n \"Delete selection\"\n ])\n self.button_reset = widgets.Button(description=\"\", icon=\"refresh\")\n import copy\n self.start_limits = copy.deepcopy(self.limits)\n\n def reset(*args):\n self.limits = copy.deepcopy(self.start_limits)\n with self.scale_y.hold_trait_notifications():\n self.scale_y.min, self.scale_y.max = self.limits[1]\n with self.scale_x.hold_trait_notifications():\n self.scale_x.min, self.scale_x.max = self.limits[0]\n self.plot.update_grid()\n self.button_reset.on_click(reset)\n\n self.button_select_nothing.on_event('click', lambda *ignore: self.plot.select_nothing())\n self.tools.append(self.button_select_nothing)\n self.modes_names = \"replace and or xor subtract\".split()\n self.modes_labels = \"replace and or xor subtract\".split()\n self.button_selection_mode = widgets.Dropdown(description='select', options=self.modes_labels)\n self.tools.append(self.button_selection_mode)\n\n def change_interact(*args):\n with self.output:\n # print \"change\", args\n name = tool_actions[self.button_action.v_model]\n self.figure.interaction = tool_actions_map[name]\n\n tool_actions = [\"pan/zoom\", \"select\"]\n # tool_actions = [(\"m\", \"m\"), (\"b\", \"b\")]\n self.button_action = \\\n v.BtnToggle(v_model=0, mandatory=True, multiple=False, children=[\n v.Tooltip(bottom=True, children=[\n v.Btn(slot='activator', children=[\n v.Icon(children=['pan_tool'])\n ]),\n \"Pan & zoom\"\n ]),\n v.Tooltip(bottom=True, children=[\n v.Btn(slot='activator', children=[\n v.Icon(children=['crop_free'])\n ]),\n \"Square selection\"\n ]),\n ])\n self.widget_tool_basic = v.Layout(children=[\n v.Layout(pa_1=True, column=False, align_center=True, children=[\n self.button_action,\n self.widget_select_nothing\n ])\n ])\n self.plot.add_control_widget(self.widget_tool_basic)\n\n self.button_action.observe(change_interact, \"v_model\")\n self.tools.insert(0, self.button_action)\n self.button_action.value = \"pan/zoom\" # tool_actions[-1]\n if len(self.tools) == 1:\n tools = []\n # self._main_widget_1.children += (self.button_reset,)\n self._main_widget_1.children += (self.button_action,)\n self._main_widget_1.children += (self.button_select_nothing,)\n # self._main_widget_2.children += (self.button_selection_mode,)\n self._main_widget.children = [self._main_widget_1, self._main_widget_2]\n self.control_widget.children += (self._main_widget,)\n self._update_grid_counter = 0 # keep track of t\n self._update_grid_counter_scheduled = 0 # keep track of t\n\n def _on_view_count_change(self, *args):\n with self.output:\n logger.debug(\"views: %d\", self.image.view_count)\n if self._dirty and self.image.view_count > 0:\n try:\n logger.debug(\"was dirty, and needs an update\")\n self.update()\n finally:\n self._dirty = False\n\n @debounced(0.5, method=True)\n def update_brush(self, *args):\n with self.output:\n if not self.brush.brushing: # if we ended brushing, reset it\n self.figure.interaction = None\n if self.brush.selected is not None:\n (x1, y1), (x2, y2) = self.brush.selected\n mode = self.modes_names[self.modes_labels.index(self.button_selection_mode.value)]\n self.plot.select_rectangle(x1, y1, x2, y2, mode=mode)\n else:\n self.dataset.select_nothing()\n if not self.brush.brushing: # but then put it back again so the rectangle is gone,\n self.figure.interaction = self.brush\n" ]
[ [ "numpy.arange", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
IBM/pddlrl
[ "e057cc67426c91c9180286a67acad5b9a1ba7fc6" ]
[ "pddlrl/wrappers/integer_action.py" ]
[ "# This file is a part of PDDLRL project.\n# Copyright (c) 2020 Clement Gehring ([email protected])\n# Copyright (c) 2021 Masataro Asai ([email protected], [email protected]), IBM Corporation\n\nimport itertools\nimport operator\n\nimport numpy as np\n\nfrom acme.wrappers import base\n\nimport pddlenv\n\n\nclass IntegerAction(base.EnvironmentWrapper):\n\n def _action_from_index(self, state: pddlenv.EnvState, action_idx: int):\n indices_dict = pddlenv.array.unravel_literal_indices(\n (np.zeros((1,), dtype=np.int), np.array((action_idx,), dtype=np.int)),\n self._shapes,\n )\n # since we're only dealing with 1 action, we should only have one arity in indices\n action_arity, indices = tuple(indices_dict.items())[0]\n action_cls = self._sorted_actions[action_arity][indices[-1][0]]\n\n objects = state.problem.objects\n return action_cls(*(objects[i[0]] for i in indices[1:-1]))\n\n def reset(self):\n timestep = self._environment.reset()\n\n problem = timestep.observation.problem\n grouped_actions = itertools.groupby(\n sorted(problem.actions, key=operator.attrgetter(\"arity\")),\n key=operator.attrgetter(\"arity\"),\n )\n self._sorted_actions = {\n arity: dict(enumerate(sorted(acts, key=operator.attrgetter(\"__name__\"))))\n for arity, acts in grouped_actions\n }\n self._shapes = pddlenv.array.compute_shapes(len(problem.objects), problem.actions)\n return timestep\n\n def step(self, action):\n pddl_action = self._action_from_index(self._environment.state, action)\n return self._environment.step(pddl_action)\n" ]
[ [ "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Koen-Git/ColorSymDetect
[ "5d6bb6734063f4a09c9a153527a446ce5c02a5b0" ]
[ "preprocess.py" ]
[ "import util\nimport numpy as np\n\ndef preproccesData(data):\n def isIntersecting(data):\n if util.line_intersect(data['line1x1'],data['line1y1'],data['line1x2'],data['line1y2'],data['line2x1'],data['line2y1'],data['line2x2'],data['line2y2']) == None:\n return False\n return True\n\n def distToIntersect1(data):\n intersect = util.line_intersect(data['line1x1'],data['line1y1'],data['line1x2'],data['line1y2'],data['line2x1'],data['line2y1'],data['line2x2'],data['line2y2'])\n if intersect == None:\n return -1\n else:\n Len = data['line1Len']\n subLen = np.sqrt( (data['line1x1'] - intersect[0])**2 + (data['line1y1'] - intersect[1])**2 )\n surface = data['width'] * data['height']\n return (abs(Len - (subLen * 2)) / surface)\n def distToIntersect2(data):\n intersect = util.line_intersect(data['line1x1'],data['line1y1'],data['line1x2'],data['line1y2'],data['line2x1'],data['line2y1'],data['line2x2'],data['line2y2'])\n if intersect == None:\n return -1\n else:\n Len = data['line1Len']\n subLen = np.sqrt( (data['line1x2'] - intersect[0])**2 + (data['line1y2'] - intersect[1])**2 )\n surface = data['width'] * data['height']\n return (abs(Len - (subLen * 2)) / surface)\n def distToIntersect3(data):\n intersect = util.line_intersect(data['line1x1'],data['line1y1'],data['line1x2'],data['line1y2'],data['line2x1'],data['line2y1'],data['line2x2'],data['line2y2'])\n if intersect == None:\n return -1\n else:\n Len = data['line1Len']\n subLen = np.sqrt( (data['line2x1'] - intersect[0])**2 + (data['line2y1'] - intersect[1])**2 )\n surface = data['width'] * data['height']\n return (abs(Len - (subLen * 2)) / surface)\n def distToIntersect4(data):\n intersect = util.line_intersect(data['line1x1'],data['line1y1'],data['line1x2'],data['line1y2'],data['line2x1'],data['line2y1'],data['line2x2'],data['line2y2'])\n if intersect == None:\n return -1\n else:\n Len = data['line1Len']\n subLen = np.sqrt( (data['line2x2'] - intersect[0])**2 + (data['line2y2'] - intersect[1])**2 )\n surface = data['width'] * data['height']\n return (abs(Len - (subLen * 2)) / surface)\n\n def calcPerpendicular(data):\n if data['line1Slope'] != 0:\n return (-1 * (1 / data['line1Slope']))\n elif data['line2Slope'] != 0:\n return (-1 * (1 / data['line2Slope']))\n else:\n return -1\n\n def calcPerpDiff(data):\n if data['line1Slope'] != 0:\n return (abs(data['linePerp'] - data['line2Slope']))\n elif data['line2Slope'] != 0:\n return (abs(data['linePerp'] - data['line1Slope']))\n else:\n return -1\n\n def calcSlope1(data):\n return util.getSlope([data['line1x1'],data['line1y1'],data['line1x2'],data['line1y2']], data['height'])\n\n def calcSlope2(data):\n return util.getSlope([data['line2x1'],data['line2y1'],data['line2x2'],data['line2y2']], data['height'])\n\n def meanToIntersect(data):\n return ((data['distToIntersect1'] + data['distToIntersect2'] + data['distToIntersect3'] + data['distToIntersect4']) / 4)\n\n\n #Score difference\n data = data.assign(ScoreDiff=abs(data['line1Score'] - data['line2Score']))\n\n #Slopes\n data['line1Slope'] = data.apply(lambda row: calcSlope1(row), axis=1)\n data['line2Slope'] = data.apply(lambda row: calcSlope2(row), axis=1)\n data = data.assign(SlopeDiff=abs(data['line1Slope'] - data['line2Slope']))\n\n #Perpendicular slopes\n data['linePerp'] = data.apply(lambda row: calcPerpendicular(row), axis=1)\n data['perpDiff'] = data.apply(lambda row: calcPerpDiff(row), axis=1)\n\n #Lengths\n data = data.assign(line1Len=np.sqrt( (data['line1x1'] - data['line1x2'])**2 + (data['line1y1'] - data['line1y2'])**2 ))\n data = data.assign(line2Len=np.sqrt( (data['line2x1'] - data['line2x2'])**2 + (data['line2y1'] - data['line2y2'])**2 ))\n data = data.assign(LenDiff=abs(data['line1Len'] - data['line2Len']))\n\n #Intersect\n data['intersect'] = data.apply(lambda row: isIntersecting(row), axis=1)\n data['distToIntersect1'] = data.apply(lambda row: distToIntersect1(row), axis=1)\n data['distToIntersect2'] = data.apply(lambda row: distToIntersect2(row), axis=1)\n data['distToIntersect3'] = data.apply(lambda row: distToIntersect3(row), axis=1)\n data['distToIntersect4'] = data.apply(lambda row: distToIntersect4(row), axis=1)\n\n #new\n data['meanDistToIntersect'] = data.apply(lambda row: meanToIntersect(row), axis=1)\n # data = data.assign(meanDistToIntersect=np.mean(data['distToIntersect1'], data['distToIntersect2'], data['distToIntersect3'], data['distToIntersect4']))\n data = data.assign(distToIntersectMean1=abs(data['distToIntersect1'] - data['meanDistToIntersect']))\n data = data.assign(distToIntersectMean2=abs(data['distToIntersect2'] - data['meanDistToIntersect']))\n data = data.assign(distToIntersectMean3=abs(data['distToIntersect3'] - data['meanDistToIntersect']))\n data = data.assign(distToIntersectMean4=abs(data['distToIntersect4'] - data['meanDistToIntersect']))\n\n #dropping inrelevant\n data = data.drop(['width', 'height', 'line1Score', 'line2Score'], axis=1)\n data = data.drop(['line1x1', 'line1y1', 'line1x2', 'line1y2'], axis=1)\n data = data.drop(['line2x1', 'line2y1', 'line2x2', 'line2y2'], axis=1)\n data = data.drop(['line1Len', 'line2Len'], axis=1)\n\n #new\n data = data.drop(['distToIntersect1', 'distToIntersect2', 'distToIntersect3', 'distToIntersect4', 'meanDistToIntersect'], axis=1)\n \n return data" ]
[ [ "numpy.sqrt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kuevpr/particles
[ "c1d0e68c193b17aecd76c9e5aced75ba41dc3295" ]
[ "particles/kalman.py" ]
[ "# -*- coding: utf-8 -*-\n\nr\"\"\"\nBasic implementation of the Kalman filter (and smoother).\n\nOverview\n=========\n\nThe Kalman filter/smoother is a well-known algorithm for computing recursively\nthe filtering/smoothing distributions of a linear Gaussian model, i.e. a model\nof the form:\n\n.. math::\n X_0 & \\sim N(\\mu_0,C_0) \\\\\n X_t & = F X_{t-1} + U_t, \\quad U_t \\sim N(0, C_X) \\\\\n Y_t & = G X_t + V_t, \\quad V_t \\sim N(0, C_Y)\n\nLinear Gaussian models and the Kalman filter are covered in Chapter 7 of the\nbook.\n\nMVLinearGauss class and subclasses\n==================================\n\nTo define a specific linear Gaussian model, we instantiate class\n`MVLinearGauss` (or one its subclass) as follows::\n\n import numpy as np\n from particles import kalman\n\n ssm = kalman.MVLinearGauss(F=np.ones((1, 2)), G=np.eye(2), covX=np.eye(2),\n covY=.3)\n\nwhere the parameters have the same meaning as above. It is also possible to\nspecify `mu0`and `cov0` (the mean and covariance of the initial state X_0).\n(See the documentation of the class for more details.)\n\nClass `MVLinearGauss` is a sub-class of `StateSpaceModel` in module\n`state_space_models`, so it inherits methods from its parent such as::\n\n true_states, data = ssm.simulate(30)\n\nClass `MVLinearGauss` implements methods `proposal`, `proposal0` and `logeta`,\nwhich correspond respectively to the optimal proposal distributions and\nauxiliary function for a guided or auxiliary particle filter; see Chapter 11\nand module `state_space_models` for more details. (That the optimal quantities\nare tractable is, of course, due to the fact that the model is linear and\nGaussian.)\n\nTo define a univariate linear Gaussian model, you may want to use instead the\nmore conveniently parametrised class `LinearGauss` (which is a sub-class of\n``MVLinearGauss``)::\n\n ssm = LinearGauss(rho=0.3, sigX=1., sigY=.2, sig0=1.)\n\nwhich corresponds to model:\n\n.. math::\n X_0 & \\sim N(0, \\sigma_0^2) \\\\\n X_t|X_{t-1}=x_{t-1} & \\sim N(\\rho * X_{t-1},\\sigma_X^2) \\\\\n Y_t |X_t=x_t & \\sim N(x_t, \\sigma_Y^2)\n\nAnother sub-class of `MVLinearGauss` defined in this module is\n`MVLinearGauss_Guarniero_etal`, which implements a particular class of linear\nGaussian models often used as a benchmark (after Guarniero et al, 2016).\n\n\n`Kalman` class\n==============\n\nThe Kalman filter is implemented as a class, `Kalman`, with methods\n`filter` and `smoother`. When instantiating the class, one passes\nas arguments the data, and an object that represents the considered model (i.e.\nan instance of MvLinearGauss, see above)::\n\n kf = kalman.Kalman(ssm=ssm, data=data)\n kf.filter()\n\nThe second line implements the forward pass of a Kalman filter. The results are\nstored as lists of `MeanAndCov` objects, that is, named tuples with attributes\n'mean' and 'cov' that represent a Gaussian distribution. For instance::\n\n kf.filt[3].mean # mean of the filtering distribution at time 3\n kf.pred[7].cov # cov matrix of the predictive distribution at time 7\n\nThe forward pass also computes the log-likelihood of the data::\n\n kf.logpyt[5] # log-density of Y_t | Y_{0:t-1} at time t=5\n\nSmoothing works along the same lines::\n\n kf.smoother()\n\nthen object kf contains a list called smooth, which represents the successive\n(marginal) smoothing distributions::\n\n kf.smth[8].mean # mean of the smoothing dist at time 8\n\nIt is possible to call method `smoother` directly (without calling `filter`\nfirst). In that case, the filtering step is automatically performed as a\npreliminary step.\n\nKalman objects as iterators\n===========================\n\nIt is possible to perform the forward pass step by step; in fact a `Kalman`\nobject is an iterator::\n\n kf = kalman.Kalman(ssm=ssm, data=data)\n next(kf) # one step\n next(kf) # one step\n\nIf you run the smoother after k such steps, you will obtain the smoothing\ndistribution based on the k first data-points. It is therefore possible to\ncompute recursively the successive smoothing distributions, but (a) at a high\nCPU cost; and (b) at each time, you must save the results somewhere, as\nattribute `kf.smth` gets written over and over.\n\nFunctions to perform a single step\n==================================\n\nThe module also defines low-level functions that perform a single step of the\nforward or backward step. Some of these function makes it possible to perform\nsuch steps *in parallel* (e.g. for N predictive means). The table below lists\nthese functions. Some of the required inputs are `MeanAndCov` objects, which\nmay be defined as follows::\n\n my_predictive_dist = kalman.MeanAndCov(mean=np.ones(2), cov=np.eye(2))\n\n+----------------------------------------------+\n| Function (with signature) |\n+==============================================+\n| predict_step(F, covX, filt) |\n+----------------------------------------------+\n| filter_step(G, covY, pred, yt) |\n+----------------------------------------------+\n| filter_step_asarray(G, covY, pred, yt) |\n+----------------------------------------------+\n| smoother_step(F, filt, next_pred, next_smth) |\n+----------------------------------------------+\n\n\"\"\"\n\nfrom __future__ import division, print_function\n\nimport collections\nimport numpy as np\nfrom scipy.linalg import solve\n\nfrom particles import distributions as dists\nfrom particles import state_space_models as ssms\n\nerror_msg = \"arguments of KalmanFilter.__init__ have inconsistent shapes\"\n\n########################\n# Low-level functions\n########################\n\ndef dotdot(a, b, c):\n return np.dot(np.dot(a, b), c)\n\ndef dotdotinv(a, b, c):\n \"\"\" a * b * c^{-1}, where c is symmetric positive\n \"\"\"\n return solve(c, np.dot(a, b).T, assume_a='pos', overwrite_b=True).T\n\nMeanAndCov = collections.namedtuple('MeanAndCov', 'mean cov')\n\ndef predict_step(F, covX, filt):\n \"\"\"Predictive step of Kalman filter.\n\n Parameters\n ----------\n F: (dx, dx) numpy array\n Mean of X_t | X_{t-1} is F * X_{t-1}\n covX: (dx, dx) numpy array\n covariance of X_t | X_{t-1}\n filt: MeanAndCov object\n filtering distribution at time t-1\n\n Returns\n -------\n pred: MeanAndCov object\n predictive distribution at time t\n\n Note\n ----\n filt.mean may either be of shape (dx,) or (N, dx); in the latter case\n N predictive steps are performed in parallel.\n \"\"\"\n pred_mean = np.matmul(filt.mean, F.T)\n pred_cov = dotdot(F, filt.cov, F.T) + covX\n return MeanAndCov(mean=pred_mean, cov=pred_cov)\n\n\ndef filter_step(G, covY, pred, yt):\n \"\"\"Filtering step of Kalman filter.\n\n Parameters\n ----------\n G: (dy, dx) numpy array\n mean of Y_t | X_t is G * X_t\n covX: (dx, dx) numpy array\n covariance of Y_t | X_t\n pred: MeanAndCov object\n predictive distribution at time t\n\n Returns\n -------\n pred: MeanAndCov object\n filtering distribution at time t\n logpyt: float\n log density of Y_t | Y_{0:t-1}\n \"\"\"\n # data prediction\n data_pred_mean = np.matmul(pred.mean, G.T)\n data_pred_cov = dotdot(G, pred.cov, G.T) + covY\n if covY.shape[0] == 1:\n logpyt = dists.Normal(loc=data_pred_mean,\n scale=np.sqrt(data_pred_cov)).logpdf(yt)\n else:\n logpyt = dists.MvNormal(loc=data_pred_mean,\n cov=data_pred_cov).logpdf(yt)\n # filter\n residual = yt - data_pred_mean\n gain = dotdotinv(pred.cov, G.T, data_pred_cov)\n filt_mean = pred.mean + np.matmul(residual, gain.T)\n filt_cov = pred.cov - dotdot(gain, G, pred.cov)\n return MeanAndCov(mean=filt_mean, cov=filt_cov), logpyt\n\n\ndef filter_step_asarray(G, covY, pred, yt):\n \"\"\"Filtering step of Kalman filter: array version.\n\n Parameters\n ----------\n G: (dy, dx) numpy array\n mean of Y_t | X_t is G * X_t\n covX: (dx, dx) numpy array\n covariance of Y_t | X_t\n pred: MeanAndCov object\n predictive distribution at time t\n\n Returns\n -------\n pred: MeanAndCov object\n filtering distribution at time t\n logpyt: float\n log density of Y_t | Y_{0:t-1}\n\n Note\n ----\n This performs the filtering step for N distinctive predictive means:\n filt.mean should be a (N, dx) or (N) array; pred.mean in the output\n will have the same shape.\n\n \"\"\"\n pm = pred.mean[:, np.newaxis] if pred.mean.ndim == 1 else pred.mean\n new_pred = MeanAndCov(mean=pm, cov=pred.cov)\n filt, logpyt = filter_step(G, covY, new_pred, yt)\n if pred.mean.ndim == 1:\n filt.mean.squeeze()\n return filt, logpyt\n\n\ndef smoother_step(F, filt, next_pred, next_smth):\n \"\"\"Smoothing step of Kalman filter/smoother.\n\n Parameters\n ----------\n F: (dx, dx) numpy array\n Mean of X_t | X_{t-1} is F * X_{t-1}\n filt: MeanAndCov object\n filtering distribution at time t\n next_pred: MeanAndCov object\n predictive distribution at time t+1\n next_smth: MeanAndCov object\n smoothing distribution at time t+1\n\n Returns\n -------\n smth: MeanAndCov object\n smoothing distribution at time t\n \"\"\"\n J = dotdotinv(filt.cov, F.T, next_pred.cov)\n smth_cov = filt.cov + dotdot(J, next_smth.cov - next_pred.cov, J.T)\n smth_mean = filt.mean + np.matmul(next_smth.mean - next_pred.mean, J.T)\n return MeanAndCov(mean=smth_mean, cov=smth_cov)\n\n\n###############################\n# State-space model classes\n###############################\n\nclass MVLinearGauss(ssms.StateSpaceModel):\n \"\"\"Multivariate linear Gaussian model.\n\n .. math::\n X_0 & \\sim N(\\mu_0, cov_0) \\\\\n X_t & = F * X_{t-1} + U_t, \\quad U_t\\sim N(0, cov_X) \\\\\n Y_t & = G * X_t + V_t, \\quad V_t \\sim N(0, cov_Y)\n\n The only mandatory parameters are `covX` and `covY` (from which the\n dimensions dx and dy of, respectively, X_t, and Y_t, are deduced). The\n default values for the other parameters are:\n * `mu0`:: an array of zeros (of size dx)\n * `cov0`: cov_X\n * `F`: Identity matrix of shape (dx, dx)\n * `G`: (dy, dx) matrix such that G[i, j] = 1[i=j]\n\n Note\n ----\n The Kalman filter takes as an input an instance of this class (or one of\n its subclasses).\n \"\"\"\n\n def __init__(self, F=None, G=None, covX=None, covY=None, mu0=None,\n cov0=None):\n self.covX, self.covY = np.atleast_2d(covX), np.atleast_2d(covY)\n self.dx, self.dy = self.covX.shape[0], self.covY.shape[0]\n self.mu0 = np.zeros(self.dx) if mu0 is None else mu0\n self.cov0 = self.covX if cov0 is None else np.atleast_2d(cov0)\n self.F = np.eye(self.dx) if F is None else np.atleast_2d(F)\n self.G = np.eye(self.dy, self.dx) if G is None else np.atleast_2d(G)\n self.check_shapes()\n\n def check_shapes(self):\n \"\"\"\n Check all dimensions are correct.\n \"\"\"\n assert self.covX.shape == (self.dx, self.dx), error_msg\n assert self.covY.shape == (self.dy, self.dy), error_msg\n assert self.F.shape == (self.dx, self.dx), error_msg\n assert self.G.shape == (self.dy, self.dx), error_msg\n assert self.mu0.shape == (self.dx,), error_msg\n assert self.cov0.shape == (self.dx, self.dx), error_msg\n\n def PX0(self):\n return dists.MvNormal(loc=self.mu0, cov=self.cov0)\n\n def PX(self, t, xp):\n return dists.MvNormal(loc=np.dot(xp, self.F.T), cov=self.covX)\n\n def PY(self, t, xp, x):\n return dists.MvNormal(loc=np.dot(x, self.G.T), cov=self.covY)\n\n def proposal(self, t, xp, data):\n pred = MeanAndCov(mean=np.matmul(xp, self.F.T), cov=self.covX)\n f, _ = filter_step_asarray(self.G, self.covY, pred, data[t])\n return dists.MvNormal(loc=f.mean, cov=f.cov)\n\n def proposal0(self, data):\n pred0 = MeanAndCov(mean=self.mu0, cov=self.cov0)\n f, _ = filter_step(self.G, self.covY, pred0, data[0])\n return dists.MvNormal(loc=f.mean, cov=f.cov)\n\n def logeta(self, t, x, data):\n pred = MeanAndCov(mean=np.matmul(x, self.F.T), cov=self.covX)\n _, logpyt = filter_step_asarray(self.G, self.covY, pred, data[t+1])\n return logpyt\n\nclass MVLinearGauss_Guarniero_etal(MVLinearGauss):\n \"\"\"Special case of a MV Linear Gaussian ssm from Guarnierio et al. (2016).\n\n .. math::\n G = cov_X = cov_Y = cov_0 = I_{d_x}\n\n F_{i, j} = \\alpha^ { 1 + |i-j|}\n\n See `MVLinearGauss` for the definition of these quantities.\n\n Parameters\n ----------\n alpha: float (default: 0.4)\n value of alpha\n dx: int (must be >1; default: 2)\n dimension of state-space\n\n Reference\n ---------\n Guarnierio et al (2016). The Iterated Auxiliary Particle Filter,\n arxiv:1511.06286, JASA.\n \"\"\"\n def __init__(self, alpha=0.4, dx=2):\n F = np.empty((dx, dx))\n for i in range(dx):\n for j in range(dx):\n F[i, j] = alpha**(1 + abs(i - j))\n MVLinearGauss.__init__(self, F=F, G=np.eye(dx), covX=np.eye(dx),\n covY=np.eye(dx))\n\nclass LinearGauss(MVLinearGauss):\n r\"\"\"A basic (univariate) linear Gaussian model.\n\n .. math::\n X_0 & \\sim N(0, \\sigma_0^2) \\\\\n X_t|X_{t-1}=x_{t-1} & \\sim N(\\rho * X_{t-1},\\sigma_X^2) \\\\\n Y_t |X_t=x_t & \\sim N(x_t, \\sigma_Y^2)\n\n Note\n ----\n If parameter sigma0 is set to None, it is replaced by the quantity that\n makes the state process invariant:\n :math:`\\sigma_X^2 / (1 - \\rho^2)`\n \"\"\"\n default_params = {'sigmaY': .2, 'rho': 0.9, 'sigmaX': 1.,\n 'sigma0': None}\n\n def __init__(self, **kwargs):\n ssms.StateSpaceModel.__init__(self, **kwargs)\n if self.sigma0 is None:\n self.sigma0 = self.sigmaX / np.sqrt(1. - self.rho**2)\n # arguments for Kalman\n MVLinearGauss.__init__(self, F=self.rho, G=1., covX=self.sigmaX**2,\n covY= self.sigmaY**2, cov0=self.sigma0**2)\n\n def PX0(self):\n return dists.Normal(scale=self.sigma0)\n\n def PX(self, t, xp):\n return dists.Normal(loc=self.rho * xp, scale=self.sigmaX)\n\n def PY(self, t, xp, x):\n return dists.Normal(loc=x, scale=self.sigmaY)\n\n def proposal0(self, data):\n sig2post = 1. / (1. / self.sigma0**2 + 1. / self.sigmaY**2)\n mupost = sig2post * (data[0] / self.sigmaY**2)\n return dists.Normal(loc=mupost, scale=np.sqrt(sig2post))\n\n def proposal(self, t, xp, data):\n sig2post = 1. / (1. / self.sigmaX**2 + 1. / self.sigmaY**2)\n mupost = sig2post * (self.rho * xp / self.sigmaX**2\n + data[t] / self.sigmaY**2)\n return dists.Normal(loc=mupost, scale=np.sqrt(sig2post))\n\n def logeta(self, t, x, data):\n law = dists.Normal(loc=self.rho * x,\n scale=np.sqrt(self.sigmaX**2 + self.sigmaY**2))\n return law.logpdf(data[t + 1])\n\n#################################\n# Kalman filter/smoother class\n#################################\n\nclass Kalman(object):\n \"\"\" Kalman filter/smoother.\n\n\n See the documentation of the module for more details.\n \"\"\"\n\n def __init__(self, ssm=None, data=None):\n \"\"\"\n Parameters\n ----------\n ssm: MVLinearGaussian object\n the linear Gaussian model of interest\n data: list-like\n the data\n \"\"\"\n self.ssm = ssm\n self.data = data\n self.pred, self.filt, self.logpyt = [], [], []\n\n @property\n def t(self):\n return len(self.filt)\n\n def __next__(self):\n try:\n yt = self.data[self.t]\n except IndexError:\n raise StopIteration\n if not self.pred:\n self.pred += [MeanAndCov(mean=self.ssm.mu0, cov=self.ssm.cov0)]\n else:\n self.pred += [predict_step(self.ssm.F, self.ssm.covX, self.filt[-1])]\n new_filt, new_logpyt = filter_step(self.ssm.G, self.ssm.covY,\n self.pred[-1], yt)\n self.filt.append(new_filt)\n self.logpyt.append(new_logpyt)\n\n def next(self):\n return self.__next__() # Python 2 compatibility\n\n def __iter__(self):\n return self\n\n def filter(self):\n \"\"\" Forward recursion: compute mean/variance of filter and prediction.\n \"\"\"\n for _ in self:\n pass\n\n def smoother(self):\n \"\"\"Backward recursion: compute mean/variance of marginal smoother.\n\n Performs the filter step in a preliminary step if needed.\n \"\"\"\n if not self.filt:\n self.filter()\n self.smth = [self.filt[-1]]\n for t, f in reversed(list(enumerate(self.filt[:-1]))):\n self.smth += [smoother_step(self.ssm.F, f, self.pred[t + 1],\n self.smth[-1])]\n self.smth.reverse()\n" ]
[ [ "numpy.dot", "numpy.sqrt", "numpy.eye", "numpy.matmul", "numpy.atleast_2d", "numpy.zeros", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
vamsikrishnabodaballa/Path-Finding-Robot
[ "7e94dce95d58085b7f87fef8ce5de63c31fef75a" ]
[ "Codes 9x9/Graph_gen.py" ]
[ "import numpy as np\r\n\r\n\r\ndef baap_baap(n, index):\r\n print(\"Running Graph_Gen.baap_baap\")\r\n true_hoc = np.load(\"true_hoc.npy\")\r\n weapons = np.load(\"weapons.npy\")\r\n death_e = np.load(\"death_e.npy\")\r\n jail = np.load(\"jail.npy\")\r\n graph = np.zeros([n**2, n**2], dtype=int)\r\n not_all = []\r\n for i in range(n):\r\n for j in range(n):\r\n if true_hoc[i][j]:\r\n not_all.append(n*i + j)\r\n jails = []\r\n for i in range(n):\r\n for j in range(n):\r\n if jail[i][j] != 0:\r\n jails.append(n*i + j)\r\n for i in range(n):\r\n for j in range(n):\r\n if weapons[i][j]:\r\n not_all.append(n*i + j)\r\n for i in range(1, n**2 + 1):\r\n if i % n != 0:\r\n graph[i-1][i] = 100\r\n graph[i][i-1] = 100\r\n if i in not_all:\r\n graph[i-1][i] = 100000\r\n graph[i][i-1] = 100000\r\n if i in jails:\r\n graph[i-1][i] = 0\r\n graph[i][i-1] = 0\r\n for i in range(1, n*(n-1) + 1):\r\n graph[i-1][i+n-1] = 100\r\n graph[i+n-1][i-1] = 100\r\n if i in not_all:\r\n graph[i-1][i+n-1] = 100000\r\n graph[i+n-1][i-1] = 100000\r\n if i in jails:\r\n graph[i - 1][i+n-1] = 0\r\n graph[i+n-1][i - 1] = 0\r\n for i in index:\r\n for j in range(n**2):\r\n if graph[j][i] != 0:\r\n graph[j][i] = 1\r\n graph = graph.tolist()\r\n print(\"Graph:\\n\")\r\n print(graph)\r\n return graph\r\n" ]
[ [ "numpy.load", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
pvtodorov/novosparc
[ "fbc2aa79f22fc49401f19f5136aa5ef21a2f1eb7" ]
[ "novosparc/plotting/_plotting.py" ]
[ "from __future__ import print_function\n\n###########\n# imports #\n###########\n\nimport matplotlib as mpl\nmpl.use('agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\n#############\n# functions #\n#############\n\ndef plot_mapped_cells(locations, gw, cells, folder, \n size_x=16, size_y=12, pt_size=20, cmap='viridis'):\n \"\"\"Plots the mapped locations of a cell population.\n\n Keyword arguments:\n locations -- the locations of the target space\n gw -- the Gromow-Wasserstein matrix computed during the reconstruction\n cells -- the queried cellls as a numpy array\n folder -- the folder to save the .png output.\n pt_size -- the size of the points\n cmap -- custom colormap. Only used for 2D reconstructions\n \"\"\"\n plt.figure(figsize=(size_x, size_y))\n if locations.shape[1] == 1:\n plt.scatter(locations, np.sum(gw[cells, :], axis=0), s=pt_size)\n if locations.shape[1] == 2:\n plt.scatter(locations[:, 0], locations[:, 1],\n c=np.sum(gw[cells, :], axis=0), s=pt_size, cmap=cmap)\n plt.savefig(folder.replace('/', '') + '/' + 'mapped_cells.png')\n plt.close()\n\n\ndef plot_gene_patterns(locations, sdge, genes, folder, gene_names, num_cells,\n size_x=16, size_y=12, pt_size=20, cmap='viridis'):\n \"\"\"Plots gene expression patterns on the target space.\n\n Keyword arguments:\n locations -- the locations of the target space\n sdge -- the sdge computed from the reconstruction\n genes -- the genes to plot as a list: ['gene1', 'geme2', ...]\n folder -- the folder to save the .png output.\n gene_names -- an numpy array of all genes appearing in the sdge\n num_cells -- the number of cells used for the reconstruction\n size_x -- the width of the resulting figure\n size_y -- the height of the resulting figure\n pt_size -- the size of the points\n cmap -- custom colormap. Only used for 2D reconstructions\n \"\"\"\n num_rows = int(round(np.sqrt(len(genes))))\n plt.figure(figsize=(size_x, size_y))\n \n idx = 1\n for gene in genes:\n plt.subplot(num_rows, np.ceil(len(genes)/num_rows), idx)\n if locations.shape[1] == 1:\n plt.scatter(locations, sdge[np.argwhere(gene_names == gene), :].flatten(),\n s=pt_size)\n if locations.shape[1] == 2:\n plt.scatter(locations[:, 0], locations[:, 1], \n c=sdge[np.argwhere(gene_names == gene), :].flatten(),\n s=pt_size, cmap=cmap)\n plt.title(gene)\n plt.axis('off')\n idx += 1\n \n plt.tight_layout()\n plt.savefig(folder.replace('/', '') + '/' \n + str(num_cells) + '_cells_'\n + str(locations.shape[0]) + '_locations' + '.png')\n plt.close()\n \n\ndef plot_histogram_intestine(mean_exp_new_dist, folder):\n plt.figure(figsize=(5, 5))\n ax = plt.gca()\n im = ax.imshow(mean_exp_new_dist.T,origin='lower')\n my_xticks = ['crypt','V1','V2','V3','V4','V5','V6']\n x = range(mean_exp_new_dist.shape[0])\n plt.xticks(x, my_xticks)\n my_yticks = ['0','1','2','3','4','5','6']\n my_yticks.reverse()\n plt.yticks(range(mean_exp_new_dist.shape[0]), my_yticks)\n plt.ylabel('Embedded value')\n plt.xlabel('Villus zone')\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n plt.colorbar(im, cax=cax)\n im.set_clim(0, 1)\n plt.savefig(folder + 'histogram_intestine' + '.png')\n plt.clf()\n\ndef plot_spatial_expression_intestine(dge_full_mean, sdge, gene_names, folder):\n \n gene_list = ['Apobec1', 'Apob', 'Apoa4', 'Apoa1', 'Npc1l1', 'Slc15a1', 'Slc5a1', \n 'Slc2a5', 'Slc2a2', 'Slc7a9', 'Slc7a8', 'Slc7a7']\n \n zonated_lst=[]\n for gene in gene_list:\n zonated_lst = np.append(zonated_lst, np.argwhere(gene_names == gene))\n zonated_lst = zonated_lst.astype(int)\n\n plt.subplots(2,1, sharex=True, figsize=(7,5.5))\n \n plt.subplot(2,1,1) \n x = range(7)\n y = dge_full_mean[zonated_lst,:].T\n y_AC = np.mean(y[:,0:5],axis=1)\n y_P = y[:,5]\n y_C = np.mean(y[:,6:9],axis=1)\n y_AA = np.mean(y[:,9:],axis=1)\n y = np.vstack((y_AA/y_AA.max(),y_C/y_C.max(),y_P/y_P.max(),y_AC/y_AC.max()))\n ax = plt.gca()\n im = ax.imshow(y)\n my_xticks = ['crypt','V1','V2','V3','V4','V5','V6']\n plt.xticks(x, my_xticks)\n plt.xlabel('Villus zones')\n my_yticks = ['Amino acids','Carbohydrates','Peptides', 'Apolipoproteins' '\\n' 'Cholesterol']\n plt.yticks(range(len(my_yticks)), my_yticks)\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n plt.colorbar(im, cax=cax)\n \n plt.subplot(2,1,2) \n x = range(7)\n y = sdge[zonated_lst,:].T\n y_AC = np.mean(y[:,0:5],axis=1)\n y_P = y[:,5]\n y_C = np.mean(y[:,6:9],axis=1)\n y_AA = np.mean(y[:,9:],axis=1)\n y = np.vstack((y_AA/y_AA.max(),y_C/y_C.max(),y_P/y_P.max(),y_AC/y_AC.max()))\n ax = plt.gca()\n im = ax.imshow(y)\n my_xticks = ['0','1','2','3','4','5','6']\n plt.xticks(x, my_xticks)\n plt.xlabel('Embedded zones')\n my_yticks = ['Amino acids','Carbohydrates','Peptides',r'Apolipoproteins' '\\n' 'Cholesterol']\n plt.yticks(range(len(my_yticks)), my_yticks)\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n plt.colorbar(im, cax=cax)\n plt.tight_layout()\n\n plt.savefig(folder.replace('/', '') + 'spatial_expression_intestine' + '.png')\n plt.clf()\n\ndef plot_dendrogram(sdge, folder, size_x=25, size_y=10):\n \"\"\"Plots the dendrogram of the hierarchical clustering to inspect and choose\n the number of clusters / archetypes.\n \"\"\"\n plt.figure(figsize=(size_x, size_y))\n hierarchy.dendrogram(hierarchy.ward(sdge), leaf_rotation=90.)\n plt.savefig(folder.replace('/', '') + '/dendrogram.png')\n\n\ndef plot_archetypes(locations, archetypes, clusters, gene_corrs, gene_set, folder):\n \"\"\"Plots the spatial archetypes onto a file.\n \n Keyword arguments:\n locations -- the locations of the target space\n archetypes -- the spatial archetypes\n clusters -- the clusters\n gene_corrs -- the gene correlations\n gene_set -- the genes that were used to find the archetypes\n \"\"\"\n \n num_rows = int(round(np.sqrt(max(clusters))))\n plt.figure(figsize=(num_rows*2.5*2, num_rows*2.5))\n idx = 1\n for archetype in range(1, max(clusters)+1):\n which_genes = np.where(clusters == archetype)[0]\n plt.subplot(num_rows, np.ceil(max(clusters)/num_rows), idx)\n plt.scatter(locations[:, 0], locations[:, 1],\n c=archetypes[archetype-1, : ])\n plt.title('archetype ' + str(archetype) + '\\n' +\n '\\n'.join(wrap(', '.join(gene_set[which_genes][np.argsort(gene_corrs[which_genes])[-5:]]), 40)))\n idx += 1\n plt.tight_layout()\n plt.savefig(folder.replace('/', '') + '/spatial_archetypes.png')\n plt.close()\n" ]
[ [ "numpy.mean", "numpy.where", "matplotlib.pyplot.gca", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.subplot", "matplotlib.pyplot.close", "matplotlib.pyplot.axis", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "matplotlib.pyplot.savefig", "numpy.argsort", "numpy.sum", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.scatter", "matplotlib.use", "matplotlib.pyplot.subplots", "numpy.argwhere", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.clf", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
beyretb/baselines
[ "0c86af78f3c7b7fd13979cce6270411e60d788af" ]
[ "baselines/herSimple/replay_buffer.py" ]
[ "import threading\n\nimport numpy as np\n\n\nclass ReplayBuffer:\n def __init__(self, buffer_shapes, size_in_transitions, T, sample_transitions):\n \"\"\"Creates a replay buffer.\n\n Args:\n buffer_shapes (dict of ints): the shape for all buffers that are used in the replay\n buffer\n size_in_transitions (int): the size of the buffer, measured in transitions\n T (int): the time horizon for episodes\n sample_transitions (function): a function that samples from the replay buffer\n \"\"\"\n self.buffer_shapes = buffer_shapes\n self.size = size_in_transitions // T\n self.T = T\n self.sample_transitions = sample_transitions\n\n # self.buffers is {key: array(size_in_episodes x T or T+1 x dim_key)}\n self.buffers = {key: np.empty([self.size, *shape])\n for key, shape in buffer_shapes.items()}\n\n # memory management\n self.current_size = 0\n self.n_transitions_stored = 0\n\n # self.lock = threading.Lock()\n\n @property\n def full(self):\n # with self.lock:\n return self.current_size == self.size\n\n def sample(self, batch_size):\n \"\"\"Returns a dict {key: array(batch_size x shapes[key])}\n \"\"\"\n buffers = {}\n\n # with self.lock:\n assert self.current_size > 0\n for key in self.buffers.keys():\n buffers[key] = self.buffers[key][:self.current_size]\n\n buffers['o_2'] = buffers['o'][:, 1:, :]\n buffers['ag_2'] = buffers['ag'][:, 1:, :]\n\n transitions = self.sample_transitions(buffers, batch_size)\n\n for key in (['r', 'o_2', 'ag_2'] + list(self.buffers.keys())):\n assert key in transitions, \"key %s missing from transitions\" % key\n\n return transitions\n\n def store_episode(self, episode_batch):\n \"\"\"episode_batch: array(batch_size x (T or T+1) x dim_key)\n \"\"\"\n batch_sizes = [len(episode_batch[key]) for key in episode_batch.keys()]\n assert np.all(np.array(batch_sizes) == batch_sizes[0])\n batch_size = batch_sizes[0]\n\n # with self.lock:\n idxs = self._get_storage_idx(batch_size)\n\n # load inputs into buffers\n for key in self.buffers.keys():\n self.buffers[key][idxs] = episode_batch[key]\n\n self.n_transitions_stored += batch_size * self.T\n\n def get_current_episode_size(self):\n with self.lock:\n return self.current_size\n\n def get_current_size(self):\n with self.lock:\n return self.current_size * self.T\n\n def get_transitions_stored(self):\n with self.lock:\n return self.n_transitions_stored\n\n def clear_buffer(self):\n with self.lock:\n self.current_size = 0\n\n def _get_storage_idx(self, inc=None):\n inc = inc or 1 # size increment\n assert inc <= self.size, \"Batch committed to replay is too large!\"\n # go consecutively until you hit the end, and then go randomly.\n if self.current_size+inc <= self.size:\n idx = np.arange(self.current_size, self.current_size+inc)\n elif self.current_size < self.size:\n overflow = inc - (self.size - self.current_size)\n idx_a = np.arange(self.current_size, self.size)\n idx_b = np.random.randint(0, self.current_size, overflow)\n idx = np.concatenate([idx_a, idx_b])\n else:\n idx = np.random.randint(0, self.size, inc)\n\n # update replay size\n self.current_size = min(self.size, self.current_size+inc)\n\n if inc == 1:\n idx = idx[0]\n return idx\n" ]
[ [ "numpy.arange", "numpy.concatenate", "numpy.array", "numpy.empty", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kant/GRAFIMO
[ "65400d7a9a45b4a54492bfa069890ad354974615" ]
[ "src/grafimo/motif.py" ]
[ "\"\"\"\n\n@author: Manuel Tognon\n\n@email: [email protected]\n@email: [email protected]\n\nThe file contains the definition of the Motif class, that represent\nthe motif that will be searched on the genome.\n\n\"\"\"\n\n\nfrom grafimo.GRAFIMOException import NoDataFrameException, WrongMotifWidthException, WrongMotifIDException, \\\n WrongMotifNameException, NotValidMotifMatrixException, NotValidBGException, \\\n NotValidAlphabetException, NotValidFFException, FileReadingException, \\\n ValueException\nfrom grafimo.utils import die, DNA_ALPHABET, REV_COMPL, PSEUDObg, isListEqual, isJaspar_ff, isMEME_ff, \\\n almost_equal, RANGE, printProgressBar, sigint_handler\nfrom motif_processing import readBGfile, get_uniformBG, apply_pseudocount_jaspar, apply_pseudocount_meme, \\\n compute_log_odds, comp_pval_mat\nimport multiprocessing as mp\nimport signal\nimport pandas as pd\nimport numpy as np\nimport time\nimport os\n\n\n#################################################\n# begin Motif definition\n#################################################\nclass Motif(object):\n \"\"\"\n Class to represent a motif.\n It contains:\n - the motif count matrix\n - the motif scoring matrix (scaled)\n - the pvalue matrix\n - parameters used to scale the matrix\n - the background distribution of the motif\n - the width of the motif\n - the minimum value in the motif matrix (both forward and reverse)\n - the maximum value in the motif matrix (both forward and reverse)\n - the transcription factor's name (both jaspar ID and conventional name)\n - the alphabet on which the matrix is built\n \"\"\"\n\n _count_matrix = None # pd.DataFrame\n _score_matrix = None # np.ndarray\n _pval_matrix = None # np.array\n _min_val = -np.inf # np.double\n _max_val = np.inf # np.double\n _scale = -1 # int\n _offset = 0 # np.double\n _bg = None # background distribution (dict)\n _width = -1 # int\n _motif_id = None # jaspar ID\n _motif_name = None # common TF name\n _alphabet = None\n _isScaled = False\n\n def __init__(self,\n count_matrix,\n width,\n alphabet,\n motif_id,\n motif_name):\n\n if count_matrix.empty:\n errmsg = \"\\n\\nERROR: attempt to initialize the motif object with an empty count matrix\"\n raise NotValidMotifMatrixException(errmsg)\n\n if not isinstance(count_matrix, pd.DataFrame):\n raise NoDataFrameException(\"\\n\\nERROR: the given value is not a pandas.DatFrame instance\")\n\n if not isinstance(width, int) or width < 0:\n errmsg = \"\\n\\nERROR: attempt to initialize motif without a valid width\"\n raise WrongMotifWidthException(errmsg)\n\n if not isinstance(motif_id, str) or not motif_id:\n raise WrongMotifIDException(\"\\n\\nERROR: cannot initialize the motif with the given ID\")\n\n if not isinstance(motif_name, str) or not motif_name:\n raise WrongMotifNameException(\"\\n\\nERROR: cannot initialize the motif with the given name\")\n\n if not isinstance(alphabet, list) or not isListEqual(alphabet, DNA_ALPHABET):\n errmsg = \"\\n\\nERROR: cannot initialize a motif object with a wrong alphabet\"\n raise NotValidAlphabetException(errmsg)\n\n self._count_matrix = count_matrix\n self._width = width\n self._motif_id = motif_id\n self._motif_name = motif_name\n self._alphabet = alphabet\n # end of __init__()\n\n ### setter methods ###\n\n def setMotif_matrix(self,\n motif_matrix):\n\n if motif_matrix.empty:\n errmsg = \"\\n\\nERROR: attempt to use an empty motif matrix\"\n raise NotValidMotifMatrixException(errmsg)\n\n if not isinstance(motif_matrix, pd.DataFrame):\n raise NoDataFrameException(\"\\n\\nERROR: the given value is not a pandas.DataFrame instance\")\n\n self._count_matrix = motif_matrix\n\n def setMotif_scoreMatrix(self,\n score_matrix):\n\n if (not isinstance(score_matrix, np.ndarray) and\n not isinstance(score_matrix, pd.DataFrame)):\n errmsg = \"\\n\\nERROR: the given data-structure is not an instance of numpy.ndarray or pandas.DataFrame\"\n raise ValueError(errmsg)\n\n if isinstance(score_matrix, pd.DataFrame):\n if score_matrix.empty:\n errmsg = \"\\n\\nERROR: attempt to use an empty score matrix\"\n raise NotValidMotifMatrixException(errmsg)\n\n if isinstance(score_matrix, np.ndarray):\n if score_matrix.size == 0:\n errmsg = \"\\n\\nERROR: attempt to use an empty score matrix\"\n raise NotValidMotifMatrixException(errmsg)\n\n self._score_matrix = score_matrix\n\n def setMotif_pval_matrix(self,\n pval_mat):\n\n if len(pval_mat) == 0 or sum(pval_mat[:]) <= 0: # empty or not valid p-value matrix\n raise NotValidMotifMatrixException(\"\\n\\nERROR: invalid p-value matrix\")\n\n self._pval_matrix = pval_mat\n\n def setMin_val(self,\n min_val):\n\n if min_val <= -np.inf:\n errmsg = ' '.join([\"\\n\\nERROR: impossible to assign\", min_val, \"to Motif.min_val\"])\n raise ValueException(errmsg)\n\n self._min_val = min_val\n\n def setMax_val(self,\n max_val):\n\n if max_val >= np.inf:\n errmsg = ' '.join([\"\\n\\nERROR: impossible to assign\", max_val, \"to Motif.max_val\"])\n raise ValueException(errmsg)\n\n self._max_val = max_val\n\n def setScale(self,\n scale):\n\n if not isinstance(scale, int):\n raise ValueException(\"\\n\\nERROR: the scale factor must be an int\")\n\n assert scale > 0\n\n self._scale = scale\n\n def setOffset(self,\n offset):\n\n self._offset = offset\n\n def setBg(self,\n bgs):\n\n if not isinstance(bgs, dict):\n raise NotValidBGException(\"\\n\\nERROR: the background values are not in a dictionary\")\n\n self._bg = bgs\n\n def setWidth(self,\n width):\n\n if not isinstance(width, int) or width <= 0:\n errmsg = \"\\n\\nERROR: attempt to initialize motif without a valid width\"\n raise WrongMotifWidthException(errmsg)\n\n self._width = width\n\n def setMotifID(self,\n motif_id):\n\n if not isinstance(motif_id, str):\n errmsg = ' '.join([\"\\n\\nERROR: cannot initialize the motif with the given ID:\", motif_id])\n raise WrongMotifIDException(errmsg)\n\n if not motif_id:\n raise WrongMotifIDException(\"\\n\\nERROR: cannot use a motif with an empty ID\")\n\n self._motif_id = motif_id\n\n def setMotifName(self,\n motif_name):\n\n if not isinstance(motif_name, str):\n errmsg = ' '.join([\"Cannot initialize the motif with the given name:\", motif_name])\n raise WrongMotifNameException(errmsg)\n\n if not motif_name:\n raise WrongMotifNameException(\"\\n\\nERROR: cannot use a motif with an empty name\")\n\n self._motif_name = motif_name\n\n def setAlphabet(self,\n alphabet):\n\n if not isinstance(alphabet, list):\n raise NotValidAlphabetException(\"\\n\\nERROR: the given alphabet is not in a list\")\n\n if not isListEqual(alphabet, DNA_ALPHABET):\n raise NotValidAlphabetException(\"\\n\\nERROR: the given alphabet is not a valid DNA alphabet\")\n\n self.alphabet = alphabet\n\n def setIsScaled(self,\n isScaled):\n\n if not isinstance(isScaled, bool):\n raise Exception(\"\\n\\nERROR: the isScaled value must be a boolean\")\n\n self._isScaled = isScaled\n\n ### getter methods ###\n\n def getMotif_matrix(self):\n\n return self._count_matrix\n\n def getMotif_scoreMatrix(self):\n\n return self._score_matrix\n\n def getMotif_pval_mat(self):\n\n return self._pval_matrix\n\n def getMin_val(self):\n\n return self._min_val\n\n def getMax_val(self):\n\n return self._max_val\n\n def getScale(self):\n\n return self._scale\n\n def getOffset(self):\n\n return self._offset\n\n def getBg(self):\n\n return self._bg\n\n def getWidth(self):\n\n return self._width\n\n def getMotifID(self):\n\n return self._motif_id\n\n def getMotifName(self):\n\n return self._motif_name\n\n def getAlphabet(self):\n\n return self._alphabet\n\n def getIsScaled(self):\n\n return self._isScaled\n\n def compute_minValue(self):\n\n motif_matrix = self.getMotif_matrix()\n min_value = motif_matrix.min().sum()\n self._min_val = min_value\n\n def print(self,\n matrix):\n allowed_matrices = [\"raw_counts\", \"score_matrix\", \"pval_matrix\"]\n\n if matrix not in allowed_matrices:\n raise ValueError(\"ERROR: unknown Motif matrix to print\")\n\n if str(matrix) == \"raw_counts\":\n print(self._count_matrix)\n elif str(matrix) == \"score_matrix\":\n print(self._score_matrix)\n elif str(matrix) == \"pval_matrix\":\n print(self._pval_matrix)\n else:\n # we should not reach this point\n raise ValueError(\"ERROR: unknown Motif matrix to print\")\n # end of print()\n# end of Motif\n\n\n#################################################\n# end of Motif definition\n#################################################\n\n\ndef build_motif_JASPAR(motif_file,\n bg_file,\n pseudocount,\n no_reverse,\n verbose):\n \"\"\"\n Build a Motif object starting from raw counts\n data stored in a JASPAR motif file.\n\n The raw counts are processed and the resulting values\n are used to define the scoring matrix for the motif\n ----\n Parameters:\n motif_file (str) : path to the motif file\n bg_file (str) : path to the background file\n pseudocount (float) : value to add to the motif counts (to avoid\n division by 0)\n no_reverse (bool) : flag parameter to consider or not the reverse\n complement building the Motif object\n ----\n Returns:\n motif (Motif) : returns the corresponding Motif object\n \"\"\"\n\n if not motif_file:\n raise FileNotFoundError(\"\\n\\nERROR: the motif file is missing\")\n die(1)\n\n # check if the input file is in JASPAR format\n if not isJaspar_ff(motif_file):\n raise NotValidFFException(\"ERROR: the given motif file is not in JASPAR or MEME format\")\n die(1)\n\n assert pseudocount > 0\n\n # read the motif file\n motif = read_JASPAR_motif(motif_file, bg_file, pseudocount, no_reverse, verbose)\n\n if verbose:\n start_mp = time.time()\n\n # get log-odds values for motif\n motif = process_motif_for_logodds(motif)\n\n if verbose:\n end_mp = time.time()\n msg = ''.join([\"Processed motif \", motif.getMotifID(), \" in \", str(end_mp - start_mp), \"s\"])\n print(msg)\n # end if\n\n return motif\n# end of build_motif_JASPAR()\n\n\ndef read_JASPAR_motif(motif_file,\n bg_file,\n pseudocount,\n no_reverse,\n verbose):\n \"\"\"\n Read data contained in a JASPAR motif file and build a Motif\n object from them\n ----\n Params:\n motif_file (str) : path to the motif file (in JASPAR format)\n bg_file (str) : path to the background file\n no_reverse (bool) : flag parameter to consider or not the reverse\n complement building the Motif object\n ----\n Returns:\n motif (Motif) : Motif object summarizing data contained in\n motif_file\n \"\"\"\n\n # lists where store nucleotides and raw counts\n nucs = []\n counts = []\n\n if verbose:\n start_rm = time.time()\n\n try:\n # open the motif file\n with open(motif_file) as in_mtf:\n\n header = str(in_mtf.readline()[1:]) # read the header\n motifID, motifName = header.split('\\t')[0:2] # get the jaspar ID and the common TF name\n motifName = motifName[:-1] # remove '\\n'\n\n for line in in_mtf:\n line = line.strip()\n nuc = line.strip()[:1] # read nucleotide\n count = list(map(float, line.strip()[1:].split()[1:][:-1])) # read raw counts\n\n nucs.append(nuc)\n counts.append(count)\n # end for\n # end open\n\n except: # something went wrong\n errmsg = ' '.join([\"\\n\\nERROR: unable to read file\", motif_file])\n raise FileReadingException(errmsg)\n\n else:\n\n motif_counts = pd.DataFrame(data=counts, index=nucs) # raw counts\n motif_width = int(len(counts[0])) # the check of equal length for all raw counts is made building the DataFrame\n alphabet = sorted(nucs) # alphabet as list\n\n # read the background file\n if bg_file == 'UNIF':\n bgs = get_uniformBG(alphabet)\n elif os.path.exists(bg_file):\n bgs = readBGfile(bg_file)\n else:\n raise NotValidBGException(\"\\n\\nERROR: unable to find the given background file\")\n # end if\n\n bgs = pseudo_bg(bgs, no_reverse)\n\n motif_probs = (motif_counts / motif_counts.sum(0)) # get probabilities\n motif_probs = norm_motif(motif_probs, motif_width, alphabet)\n motif_probs = apply_pseudocount_jaspar(motif_counts, motif_probs, pseudocount, bgs,\n motif_width, alphabet)\n\n motif = Motif(motif_probs, motif_width, alphabet, motifID, motifName)\n motif.setBg(bgs)\n\n if verbose:\n end_rm = time.time()\n msg = ''.join([\"Read motif \", motifID, \" in \", str(end_rm - start_rm), \"s\"])\n print(msg)\n # end if\n\n return motif\n\n finally:\n in_mtf.close() # close the motif file anyway\n# end of read_JASPAR_motif()\n\n\ndef build_motif_MEME(motif_file,\n bg_file,\n pseudocount,\n no_reverse,\n cores,\n verbose):\n \"\"\"\n Build a the Motif object starting from the data\n stored in a given MEME file.\n\n The probabilities are processed and the resulting values\n are used to build the scoring matrix for the motif.\n ----\n Parameters:\n motif_file (str) : path to the motif file\n bg_file (str) : path to the background file\n pseudocount (float) : value to add to the motif counts\n no_reverse (bool) : if set to True, only data related to\n forward strand will be used\n cores (int) : number of cores to use, during motif processing\n ----\n Returns:\n motif (Motif) : Motif object built from data contained in\n motif_file\n \"\"\"\n\n if not motif_file:\n raise FileNotFoundError(\"\\n\\nERROR: the motif file is missing\")\n\n # check if the input is in MEME format\n if not isMEME_ff(motif_file):\n # if in other format we should not be here\n raise NotValidFFException(\"\\n\\nERROR: the given motif file is not in MEME format\")\n\n if verbose:\n start_rm_all = time.time()\n\n # read the motif file\n motif_lst = read_MEME_motif(motif_file, bg_file, pseudocount, no_reverse, verbose)\n motif_num = len(motif_lst)\n\n if verbose:\n end_rm_all = time.time()\n msg = ''.join([\"\\nRead all motif contained in \", motif_file, \" in \", str(end_rm_all - start_rm_all), \"s\"])\n print(msg)\n # end if\n\n print(\"\\nRead\", motif_num, \"motifs in\", motif_file)\n print(\"\\nProcessing motifs\\n\")\n\n # list of the fully processed motifs\n complete_motifs = []\n\n if verbose:\n start_mp_all = time.time()\n\n # process each found motif\n if motif_num >= cores: # worth to use multiprocessing\n\n original_sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN)\n pool = mp.Pool(processes=cores) # use #cores processes\n signal.signal(signal.SIGINT, original_sigint_handler) # overwrite the default SIGINT handler to exit gracefully\n # https://stackoverflow.com/questions/11312525/catch-ctrlc-sigint-and-exit-multiprocesses-gracefully-in-python\n\n try:\n res = (pool.map_async(process_motif_for_logodds, motif_lst))\n\n it = 0\n while (True):\n if res.ready():\n # when finished call for the last time printProgressBar()\n printProgressBar(tot, tot, prefix='Progress:',\n suffix='Complete', length=50)\n break\n # end if\n if it == 0:\n tot = res._number_left\n\n remaining = res._number_left\n printProgressBar((tot - remaining), tot, prefix='Progress:',\n suffix='Complete', length=50)\n time.sleep(2)\n it += 1\n # end while\n\n complete_motifs += res.get(60 * 60 * 60) # does not ignore signals\n\n except KeyboardInterrupt:\n pool.terminate()\n sigint_handler()\n\n else:\n pool.close()\n\n if verbose:\n end_mp_all = time.time()\n msg = ''.join([\"Processed all motifs contained in \", motif_file, \" in \",\n str(end_mp_all - start_mp_all), \"s\"])\n print(msg)\n # end if\n\n return complete_motifs\n # end try\n\n else: # the sequential execution is fine\n\n # process each found motif\n for m in motif_lst:\n complete_motifs.append(process_motif_for_logodds(m))\n\n if verbose:\n end_mp_all = time.time()\n msg = ''.join([\"Processed all motifs contained in \", motif_file, \" in \",\n str(end_mp_all - start_mp_all), \"s\"])\n print(msg)\n # end if\n\n return complete_motifs\n\n# end build_motif_MEME()\n\n\ndef read_MEME_motif(motif_file,\n bg_file,\n pseudocount,\n no_reverse,\n verbose):\n \"\"\"\n Read the motif file in MEME format and build a motif\n object from it.\n Note that a MEME file can contain a variable number of\n motifs\n ----\n Params:\n motif_file (str) : path to the motif file\n bg_file (str) : path to the background file\n pseudocount (np.double) : pseudocount to add to motif frequencies\n no_reverse (bool) : if set to True, only data related to\n forward strand will be used\n ----\n Returns:\n motif (Motif) : returns a Motif object\n \"\"\"\n\n try:\n with open(motif_file, 'r') as in_mtf: # open the motif file\n\n infostart = False # flag to keep track were the infos about the motif begin\n datastart = False # flag to keep track were the motif data begin\n motifs_found = 0 # number of motifs found in the MEME file\n\n motifID_lst = [] # list of the found motif IDs\n motifName_lst = [] # list of the found motif names\n motif_width_lst = [] # list of the found motif widths\n site_counts_lst = [] # list of the found motif site counts\n alphalen_lst = [] # list of the found motif alphabet lengths\n motif_probs_lst = [] # list of the found motif probability matrices\n a_lst = [] # list of the found As probabilities for each motif\n c_lst = [] # list of the found Cs probabilities for each motif\n g_lst = [] # list of the found Gs probabilities for each motif\n t_lst = [] # list of the found Ts probabilities for each motif\n\n motif_width = None\n pos_read = 0\n\n for line in in_mtf:\n if line[0:8] == 'ALPHABET':\n alphabet = sorted(list(set(line[10:-1])))\n assert isListEqual(alphabet, DNA_ALPHABET)\n\n if line[0:5] == 'MOTIF':\n\n if verbose:\n start_rm = time.time()\n\n motifID, motifName = line.split()[1:3]\n\n motifID_lst.append(motifID)\n motifName_lst.append(motifName)\n\n # the informations about motif start here\n infostart = True\n continue\n # end if\n\n if infostart and len(line.strip()) != 0:\n infos = line[26:]\n infosplit = infos.split()\n alphalen = int(infosplit[1])\n alphalen_lst.append(alphalen)\n\n assert alphalen == len(alphabet)\n\n motif_width = int(infosplit[3])\n site_counts = int(infosplit[5])\n infostart = False # informations end here\n\n # allocate space for the motif probability matrix\n motif_probs = pd.DataFrame(index=alphabet, columns=range(motif_width),\n data=np.double(0))\n\n motif_width_lst.append(motif_width)\n site_counts_lst.append(site_counts)\n motif_probs_lst.append(motif_probs)\n\n datastart = True # at next step begin data\n\n # initialize nucleotide data\n a = []\n c = []\n g = []\n t = []\n continue\n # end if\n\n if datastart and pos_read < motif_width:\n freqs = line.split()\n a.append(np.double(freqs[0]))\n c.append(np.double(freqs[1]))\n g.append(np.double(freqs[2]))\n t.append(np.double(freqs[3]))\n pos_read += 1\n # end if\n\n # we read all current motif data\n if pos_read == motif_width:\n a_lst.append(a)\n c_lst.append(c)\n g_lst.append(g)\n t_lst.append(t)\n\n # update stats about found motifs\n motifs_found += 1\n\n # clear the statistics\n pos_read = 0\n motif_width = None\n datastart = False\n alphalen = -1\n datastart = False\n\n if verbose:\n end_rm = time.time()\n msg = ''.join([\"Read motif \", motifID, \" in \", str(end_rm - start_rm), \"s\"])\n print(msg)\n # end if\n # end if\n\n except: # something went wrong\n errmsg = ' '.join([\"Unable to read file\", motif_file])\n raise FileReadingException(errmsg)\n\n else:\n\n # read the background\n if bg_file == 'UNIF':\n bgs = get_uniformBG(alphabet)\n elif os.path.exists(bg_file):\n bgs = readBGfile(bg_file)\n else:\n raise NotValidBGException(\"\\n\\nERROR: unable to find the given background file\")\n # end if\n\n bgs = pseudo_bg(bgs, no_reverse)\n\n motif_lst = [] # list of found motifs\n\n for i in range(motifs_found):\n mp = motif_probs_lst[i]\n\n mp.loc['A'] = a_lst[i]\n mp.loc['C'] = c_lst[i]\n mp.loc['G'] = g_lst[i]\n mp.loc['T'] = t_lst[i]\n\n mw = motif_width_lst[i]\n sc = site_counts_lst[i]\n\n mp = norm_motif(mp, mw, alphabet)\n mp = apply_pseudocount_meme(mp, pseudocount, sc, mw, bgs, alphabet)\n\n motif = Motif(mp, mw, alphabet, motifID_lst[i], motifName_lst[i])\n motif.setBg(bgs)\n\n motif_lst.append(motif)\n # end for\n\n return motif_lst\n\n finally:\n in_mtf.close() # close the file anyway\n # end try\n# end read_MEME_motif()\n\n\ndef process_motif_for_logodds(motif):\n \"\"\"\n Process the given motif and return the\n logodds values from motif file data.\n\n It is also computed the P-value matrix, using\n a DP-algorithm (Staden, R., 1994)\n ----\n Parameters:\n motif (Motif): motif to process\n ----\n Return:\n motif (Motif): the update input motif\n \"\"\"\n\n # get the log-odds\n motif_log_odds = compute_log_odds(motif.getMotif_matrix(), motif.getWidth(),\n motif.getBg(), motif.getAlphabet())\n motif.setMotif_scoreMatrix(motif_log_odds)\n\n # scale the log-odds scores\n scaled_scores, min_val, max_val, scale, offset = scale_pwm(motif.getMotif_scoreMatrix(),\n motif.getAlphabet(),\n motif.getWidth())\n motif.setMotif_scoreMatrix(scaled_scores)\n motif.setIsScaled(True)\n motif.setScale(scale)\n motif.setMin_val(min_val)\n motif.setMax_val(max_val)\n motif.setOffset(offset)\n\n # compute the p-value matrix\n pval_mat = comp_pval_mat(motif)\n motif.setMotif_pval_matrix(pval_mat)\n\n motif.setMotif_scoreMatrix(scaled_scores.values)\n\n return motif\n# end of process_motif_for_logodds()\n\n\ndef scale_pwm(motif_matrix,\n alphabet,\n motif_width):\n \"\"\"\n Scale the motif matrix values\n ----\n Parameters:\n motif_matrix (str) : count matrix\n alphabet (str) : motif alphabet\n motif_width (int) : motif width\n ----\n Returns:\n motif_matrix_sc (np.ndarray) : scaled motif matrix\n min_val (int) : lowest value in the scaled motif matrix\n max_val (int) : higest value in the scaled motif matrix\n scale_factor (int)\n offset (int)\n \"\"\"\n\n if not isinstance(motif_matrix, pd.DataFrame):\n raise NoDataFrameException(\"The given motif matrix must be an instance of pandas.DataFrame\")\n die(1)\n\n if motif_matrix.empty:\n raise NotValidMotifMatrixException(\"The given motif matrix is empty\")\n die(1)\n\n if not isinstance(alphabet, list):\n raise NotValidAlphabetException(\"The alphabet given is not in a list\")\n die(1)\n\n if not isListEqual(alphabet, DNA_ALPHABET):\n raise NotValidAlphabetException(\"The alphabet given is not a valid DNA alphabet\")\n die(1)\n\n assert motif_width > 0\n\n min_val = min(motif_matrix.min())\n max_val = max(motif_matrix.max())\n motif_matrix_sc = pd.DataFrame(index=list(motif_matrix.index), columns=list(motif_matrix.columns),\n data=0)\n\n lower = min_val\n upper = max_val\n\n if lower == upper: # all values are equal\n lower = np.double(upper - 1)\n\n lower = np.floor(lower)\n offset = np.round(np.floor(lower))\n scale_factor = np.floor(RANGE / (upper - lower))\n\n # values will be in [0, 1000]\n for nuc in alphabet:\n for j in range(motif_width):\n scaled_score = np.round((motif_matrix.loc[nuc, j] - (offset)) * scale_factor)\n motif_matrix_sc.loc[nuc, j] = scaled_score\n # end for\n # end for\n\n # make sure the values are integers\n motif_matrix_sc[:] = motif_matrix_sc[:].astype(int)\n\n # now they are scaled\n min_val = min(motif_matrix_sc.min())\n max_val = max(motif_matrix_sc.max())\n\n return motif_matrix_sc, min_val, max_val, int(scale_factor), offset\n# end of scale_pwm()\n\n\ndef get_motif_pwm(motif_file,\n args_obj,\n cores):\n \"\"\"\n Build a Motif object starting from a given PWM\n ----\n Parameters:\n motif_file (str) : motif file to process\n args_obj (Findmotif): data-structure containing the\n parameters to scan a given\n VG or a set of VGs\n cores (int) : number of cores to use during motif\n processing\n ----\n Returns:\n motif (list) : list of processed motifs as Motif objects\n \"\"\"\n\n # get arguments required to process the motif\n bgs = args_obj.get_bgfile()\n pseudo = args_obj.get_pseudo()\n no_reverse = args_obj.get_no_reverse()\n verbose = args_obj.get_verbose()\n\n if not motif_file:\n raise FileNotFoundError(\"\\n\\nERROR: the motif file is missing\")\n\n if (not isMEME_ff(motif_file)) and (not isJaspar_ff(motif_file)):\n raise NotValidFFException(\"\\n\\nERROR: the motif file must be in MEME or JASPAR format\")\n\n if isJaspar_ff(motif_file):\n motif = build_motif_JASPAR(motif_file, bgs, pseudo, no_reverse, verbose)\n\n elif isMEME_ff(motif_file):\n motif = build_motif_MEME(motif_file, bgs, pseudo, no_reverse, cores, verbose)\n\n else:\n errmsg = ' '.join([\"\\n\\nERROR: do not know what to do with file\", motif_file])\n raise NotValidFFException(errmsg)\n # end if\n\n if not isinstance(motif, list):\n motif = [motif]\n\n return motif\n# end of get_motif_pwm()\n\n\ndef pseudo_bg(bgs,\n no_reverse):\n \"\"\"\n Add the pseudocount to the background frequencies\n ----\n Parameters:\n bgs (dict) : dictionary of the background frequencies\n no_reverse (bool) : if set to True, the background\n frequencies will be averaged with the\n reverse complement frequencies\n ----\n Returns:\n bgs_proc (dict) : normalized (and averaged) background frequencies\n \"\"\"\n\n if not isinstance(bgs, dict):\n raise NotValidBGException(\"\\n\\nERROR: unable to add the pseudocount to the background\")\n\n if not isinstance(no_reverse, bool):\n raise ValueException(' '.join([\"Boolean value required, got\", str(type(no_reverse))]))\n\n if not no_reverse:\n bgs_avg = average_bg_with_rc(bgs)\n else:\n bgs_avg = bgs\n\n bgs_proc = norm_bg(bgs_avg)\n\n return bgs_proc\n# end pseudo_bg()\n\n\ndef average_bg_with_rc(bgs):\n \"\"\"\n Average the background frequencies with the reverse complement\n ----\n Parameters:\n bgs (dict) : dictionary of the background probabilities\n ----\n Returns:\n bgs_avg (dict) : averaged background probabilities\n \"\"\"\n\n bgs_avg = {}\n\n for nuc in bgs.keys():\n rc = REV_COMPL[nuc]\n\n if REV_COMPL[rc] == nuc and ord(nuc) < ord(rc):\n avg_freq = np.double((bgs[nuc] + bgs[rc]) / np.double(2))\n bgs_avg.update({nuc: avg_freq})\n bgs_avg.update({rc: avg_freq})\n # end if\n # end for\n\n return bgs_avg\n# end average_bg_with_rc()\n\n\ndef norm_bg(bgs):\n \"\"\"\n Normalize the background frequencies\n ----\n Parameters:\n Parameters:\n bgs (dict) : dictionary of the background probabilities\n ----\n Returns:\n bgs_norm (dict) : normalized background probabilities\n \"\"\"\n\n # PSEUDO = np.double(0.0000005) # pseudocount\n\n alphabet = sorted(list(bgs.keys()))\n tot = np.double(len(alphabet) * PSEUDObg)\n bgs_norm = {}\n\n for nuc in bgs.keys():\n tot += np.double(bgs[nuc])\n\n assert tot > 0\n\n for nuc in bgs.keys():\n prob = np.double((bgs[nuc] + PSEUDObg) / tot)\n bgs_norm.update({nuc: prob})\n\n tot = np.double(0)\n for nuc in bgs.keys():\n tot += bgs[nuc]\n\n assert tot != 0\n\n return bgs_norm\n# end norm_bg()\n\n\ndef norm_motif(motif_probs,\n motif_width,\n alphabet):\n \"\"\"\n Normalize motif probabilities\n ----\n Parameters:\n motif_probs (pd.DataFarme) : probability matrix\n motif_width (int) : motif width\n alphabet (list) : motif alphabet\n ----\n Returns:\n motif_probs (pd.DataFrame) : normalized probability matrix\n \"\"\"\n\n tolerance = 0.00001 # allowed tolerance in the difference between the position probability and 1\n\n for j in range(motif_width):\n tot = np.double(0)\n\n for nuc in alphabet:\n tot += motif_probs.loc[nuc, j]\n\n assert tot != 0\n\n if not almost_equal(1, tot, tolerance):\n for nuc in alphabet:\n motif_probs.loc[nuc, j] = np.double(motif_probs.loc[nuc, j] / tot)\n # end if\n # end for\n\n return motif_probs\n# end norm_motif()\n\n" ]
[ [ "numpy.round", "numpy.double", "numpy.floor", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
feicccccccc/Neural-ODE-Ex
[ "63aa60e9a67f0030c2a9ed802627f1c59fc5d553" ]
[ "Adjoint.py" ]
[ "import torch\nfrom NeuralODE import ODEfunc\nfrom ODE_solver import ode_solve\nimport numpy as np\n\n\nclass ODEAdjoint(torch.autograd.Function):\n \"\"\"\n Custom made autograd function to perform continuous backpropgation\n define by forward and backward static method\n \"\"\"\n @staticmethod\n def forward(ctx, z0, t, flat_parameters, func):\n \"\"\"\n forward propagation, solve the given ODE\n dzdt = f(z,t)\n with initial z(t0) = z0\n and find z(t) for t predefined time stamp\n :param ctx: for saving useful information during forward cal\n :param z0: initial z (bs, z_dim)\n :param t: all time stamp (time step, 1, 1)\n :param flat_parameters: flatten parameter\n :param func: the Neural Network represent the ODE function\n :return: (time_len, bs, z_shape)\n \"\"\"\n assert isinstance(func, ODEfunc)\n bs, *z_shape = z0.size() # (batch size, z_shape), *for unrolling the tuple\n time_len = t.size(0)\n\n with torch.no_grad():\n z = torch.zeros(time_len, bs, *z_shape).to(z0)\n z[0] = z0\n for i_t in range(time_len - 1):\n z0 = ode_solve(z0, t[i_t], t[i_t+1], func)\n z[i_t+1] = z0\n\n ctx.func = func\n ctx.save_for_backward(t, z.clone(), flat_parameters)\n return z\n\n @staticmethod\n def backward(ctx, dLdz):\n \"\"\"\n dLdz shape: (time_len, batch_size, *z_shape)\n Notice the first one is zero if we choose the starting point\n to be the same as the one from true label to start with\n \"\"\"\n\n # for enabling Pycharm breakpoint in backward function\n # disable to run in normal mode\n import pydevd\n pydevd.settrace(suspend=False, trace_only_current_thread=True)\n\n func = ctx.func\n t, z, flat_parameters = ctx.saved_tensors\n time_len, bs, *z_shape = z.size()\n\n n_dim = np.prod(z_shape)\n n_params = flat_parameters.size(0)\n\n # Dynamics of augmented system to be calculated backwards in time\n def augmented_dynamics(aug_z_i, t_i):\n \"\"\"\n tensors here are temporal slices\n t_i - is t\n aug_z_i - is tensor with size: bs, n_dim*2 + n_params + 1\n :param aug_z_i: (bs, n_dim*2 + n_params + 1)\n :param t_i: (bs, 1)\n :return:\n \"\"\"\n z_i, a = aug_z_i[:, :n_dim], aug_z_i[:, n_dim:2*n_dim] # ignore parameters and time\n\n # Unflatten z and a\n z_i = z_i.view(bs, *z_shape)\n a = a.view(bs, *z_shape)\n with torch.set_grad_enabled(True):\n t_i = t_i.detach().requires_grad_(True)\n z_i = z_i.detach().requires_grad_(True)\n func_eval, adfdz, adfdt, adfdp = func.forward_with_grad(z_i, t_i, grad_outputs=a) # bs, *z_shape\n adfdz = adfdz.to(z_i) if adfdz is not None else torch.zeros(bs, *z_shape).to(z_i)\n adfdp = adfdp.to(z_i) if adfdp is not None else torch.zeros(bs, n_params).to(z_i)\n adfdt = adfdt.to(z_i) if adfdt is not None else torch.zeros(bs, 1).to(z_i)\n\n # Flatten f and adfdz\n func_eval = func_eval.view(bs, n_dim)\n adfdz = adfdz.view(bs, n_dim)\n return torch.cat((func_eval, -adfdz, -adfdp, -adfdt), dim=1)\n\n dLdz = dLdz.view(time_len, bs, n_dim) # flatten dLdz for convenience\n\n with torch.no_grad():\n # Create placeholders for output gradients\n adj_z = torch.zeros(bs, n_dim).to(dLdz)\n adj_p = torch.zeros(bs, n_params).to(dLdz)\n # In contrast to z and p we need to return gradients for all times\n # actually I have no idea why we need dLdt and dLdz, but anyway\n adj_t = torch.zeros(time_len, bs, 1).to(dLdz)\n\n for i_t in range(time_len-1, 0, -1):\n z_i = z[i_t]\n t_i = t[i_t]\n f_i = func(z_i, t_i).view(bs, n_dim)\n\n # Compute direct gradients\n dLdz_i = dLdz[i_t]\n # batch matrix product\n a_t = torch.transpose(dLdz_i.unsqueeze(-1), 1, 2)\n dLdt_i = -torch.bmm(a_t, f_i.unsqueeze(-1))[:, 0]\n\n # Adjusting adjoints with direct gradients\n # Think in terms of chain rule with fix paramter on different node\n adj_z += dLdz_i\n adj_t[i_t] = adj_t[i_t] + dLdt_i\n\n # Pack augmented variable\n # z(t_N), adj_z, 0, adj_t\n aug_z = torch.cat((z_i.view(bs, n_dim), adj_z, torch.zeros(bs, n_params).to(z), adj_t[i_t]), dim=-1)\n\n # Solve augmented system backwards\n aug_ans = ode_solve(aug_z, t_i, t[i_t-1], augmented_dynamics)\n\n # Unpack solved backwards augmented system\n adj_z[:] = aug_ans[:, n_dim:2*n_dim]\n adj_p[:] += aug_ans[:, 2*n_dim:2*n_dim + n_params]\n adj_t[i_t-1] = aug_ans[:, 2*n_dim + n_params:]\n\n del aug_z, aug_ans\n\n ## Adjust 0 time adjoint with direct gradients\n # Compute direct gradients\n dLdz_0 = dLdz[0]\n dLdt_0 = -torch.bmm(torch.transpose(dLdz_0.unsqueeze(-1), 1, 2), f_i.unsqueeze(-1))[:, 0]\n\n # Adjust adjoints\n adj_z += dLdz_0\n adj_t[0] = adj_t[0] + dLdt_0\n # forward: (z0, t, parameters, func)\n return adj_z.view(bs, *z_shape), adj_t, adj_p, None" ]
[ [ "torch.zeros", "torch.cat", "torch.set_grad_enabled", "torch.no_grad", "numpy.prod" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
JulienL3vesque/amazon-sagemaker-aws-greengrass-custom-object-detection-model
[ "4b45f34b4c92cbfc3633938136366ac729155396" ]
[ "data-prep/01_video_to_frame_utils.py" ]
[ "from __future__ import (absolute_import, division,\n print_function, unicode_literals)\n\nimport os\nimport cv2\nimport logging\nimport skimage\nimport skimage.io as io\nimport skimage.transform\nimport numpy as np\nimport torchvision\nimport torch\nimport time\nimport boto3\nimport shutil\nimport argparse\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\nsession = boto3.Session()\ns3 = session.resource('s3')\n\nIMG_DIM = 128 # the width and height to resize the frames for preview\nREPORT_STATUS = 500 # number of frames to report progress\n\n# construct the argument parser and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-k\", \"--video_s3_key\", required=True, help=\"S3 key of the video\")\nap.add_argument(\"-b\", \"--video_s3_bucket\", required=True, help=\"S3 bucket of the video\")\nap.add_argument(\"-d\", \"--working_directory\", required=False, help=\"the root directory to store video and frames\",\n default=\".\")\nap.add_argument(\"-v\", \"--visualize_video\", type=bool, required=False, default=True,\n help=\"Whether to generate a preview for the frames in the video.\")\nap.add_argument(\"-o\", \"--output_s3_bucket\", required=True, help=\"S3 bucket to store outputs\")\n\nap.add_argument(\"-r\", \"--visualize_sample_rate\", type=int, required=False, default=1,\n help=\"For visualizing the video, how frequent (in seconds) to sample the frames. default to sample every second.\")\nap.add_argument(\"-u\", \"--upload_frames\", action='store_true',\n help=\"Whether to have the script upload the frames. If you choose not to, the frames will be stored\" +\n \" on local disk and you can use e.g. s3 sync command line tool to upload them into S3 in bulk.\"\n )\nap.add_argument(\"-p\", \"--frame_prefix\", required=False, help=\"the S3 prefix to upload the extracted frames\")\nap.add_argument(\"-c\", \"--cleanup_files\", required=False, default=True,\n help=\"whether to automatically clean up the files in the end. If the frames were not uploaded to S3, they will be kept on local disk even if this is set to true \")\n\nap.add_argument(\"-pp\", \"--video_preview_prefix\", required=False, default=\"previews/video/\",\n help=\"the S3 prefix to upload the video preview/visualization. default is previews/video/\")\n\n\ndef video_to_frames(video, output_base_dir):\n \"\"\"\n Convert the videos we took to images and generate the file names unique with frame indexes e.g. 'video_name_000001.jpg'\n :param video: path to the video file on local disk\n :param output_base_dir: the base directory the frames will be saved in\n :return: the directory created that contains extracted frames\n \"\"\"\n # extract frames from a video and save to directory with the name of the video and file name 'video_name_x.jpg' where\n # x is the frame index\n vidcap = cv2.VideoCapture(video)\n count = 0\n filename = os.path.split(video)[1]\n prefix = os.path.splitext(filename)[0]\n frame_sub_dir = os.path.join(output_base_dir, prefix)\n os.mkdir(frame_sub_dir)\n logger.info(\"created {} folder for frames\".format(frame_sub_dir))\n start = time.time()\n while vidcap.isOpened():\n success, image = vidcap.read()\n if success:\n # Add padding to the frame index. e.g. 1 -> 000001, 10 -> 000010 etc.\n image_name = prefix + '_{0:06d}.jpg'.format(count)\n cv2.imwrite(os.path.join(frame_sub_dir, image_name), image)\n count += 1\n if count % REPORT_STATUS == 0:\n logger.info(\"extracted {} frames. \".format(count))\n logger.info(\"took {:10.4f} seconds to extract {} frames\".format(time.time() - start, REPORT_STATUS))\n start = time.time()\n else:\n break\n cv2.destroyAllWindows()\n vidcap.release()\n logger.info(\"written {} frames for {}\".format(count, filename))\n return frame_sub_dir\n\n\ndef get_frame_rate(video):\n \"\"\" Get the frame rate for the video (frames per second) \"\"\"\n\n video = cv2.VideoCapture(video)\n\n # Find OpenCV version\n (major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')\n\n # With webcam get(CV_CAP_PROP_FPS) does not work.\n # Let's see for ourselves.\n\n if int(major_ver) < 3:\n fps = video.get(cv2.cv.CV_CAP_PROP_FPS)\n logger.info(\"Frames per second using video.get(cv2.cv.CV_CAP_PROP_FPS): {0}\".format(fps))\n else:\n fps = video.get(cv2.CAP_PROP_FPS)\n logger.info(\"Frames per second using video.get(cv2.CAP_PROP_FPS) : {0}\".format(fps))\n\n cv2.destroyAllWindows()\n video.release()\n return fps\n\n\ndef sample_frames(frame_dir, fps, visualize_sample_rate):\n \"\"\"\n Sample frames every X seconds, resize the frame and add it to an numpy array\n :param frame_dir: directory path containing the frames\n :param fps: frame rate of the video\n :return: numpy array of the sampled frames\n \"\"\"\n visualize_every_x_frames = visualize_sample_rate * int(fps)\n sampled_frames = np.empty((0, 3, IMG_DIM, IMG_DIM), dtype=np.float32) # B, C, H, W\n i = 0\n for file in sorted(os.listdir(frame_dir)):\n if i % visualize_every_x_frames == 0:\n img = skimage.img_as_float(skimage.io.imread(os.path.join(frame_dir, file))).astype(np.float32)\n img = skimage.transform.resize(img, (IMG_DIM, IMG_DIM)) # H, W, C\n img = img.swapaxes(1, 2).swapaxes(0, 1) # C, H, W\n sampled_frames = np.append(sampled_frames, np.array([img]), axis=0)\n i += 1\n logger.debug(\"total number of frames: {}\".format(i))\n return sampled_frames\n\n\ndef generate_preview_image(fps, frame_dir, video_name, visualize_sample_rate, working_dir):\n \"\"\"\n first sample frames every X seconds, resize them ,then\n concatenate sampled images into one image using torchvision's util functions\n :param fps: frame rate of the video\n :param frame_dir: directory path containing the frames\n :param video_name: name of the video\n :param visualize_sample_rate how frequent (in seconds) to sample the frames for the preview\n :param working_dir directory to save the preview\n :return: name of the preview image generated\n \"\"\"\n sampled_frames = sample_frames(frame_dir, fps, visualize_sample_rate)\n grid = (torchvision.utils.make_grid(torch.from_numpy(sampled_frames)))\n preview_file_name = video_name.split('.')[0] + \"-preview.png\"\n torchvision.utils.save_image(grid, os.path.join(working_dir, preview_file_name))\n return preview_file_name\n\n\ndef load_data_to_s3(frame_dir, preview_file_name, s3_bucket, frame_prefix, upload_frames, video_preview_prefix,\n working_dir):\n \"\"\"\n Upload the extracted frames and the preview image to S3\n :param frame_dir: directory path containing the frames\n :param preview_file_name: preview image generated\n :param s3_bucket s3 bucket to upload to\n :param frame_prefix s3 prefix to upload frames to\n :param upload_frames whether to upload frames to S3\n :param video_preview_prefix s3 prefix to upload video preview to\n :return: None\n \"\"\"\n if upload_frames:\n count = 0\n frames_s3_prefix = frame_prefix + frame_dir.split('/')[-1]\n start = time.time()\n for frame in os.listdir(frame_dir):\n # this will upload the frame in vid_a/vid_a_000001.jpg to s3://bucket/frame-prefix/vid_a/vid_a_000001.jpg\n frame_local_path = os.path.join(frame_dir, frame)\n frame_s3_key = \"{}/{}\".format(frames_s3_prefix, frame)\n s3.Bucket(s3_bucket).upload_file(frame_local_path, frame_s3_key)\n count += 1\n if count % REPORT_STATUS == 0:\n logger.info(\"uploaded {} frames. \".format(count))\n logger.info(\"took {:10.4f} seconds to upload {} frames\".format(time.time() - start, REPORT_STATUS))\n start = time.time()\n logger.info(\"uploaded {} frames to s3://{}/{}\".format(count, s3_bucket, frames_s3_prefix))\n\n if preview_file_name is not None:\n preview_file_s3_key = video_preview_prefix + preview_file_name\n s3.Bucket(s3_bucket).upload_file(os.path.join(working_dir, preview_file_name), preview_file_s3_key)\n logger.info(\"uploaded preview to s3://{}/{}\".format(s3_bucket, preview_file_s3_key))\n\n\ndef clean_up_local_files(frame_dir, video_name, upload_frames):\n if upload_frames:\n shutil.rmtree(frame_dir)\n logger.info(\"deleted folder {}\".format(frame_dir))\n # since the video was downloaded from s3, it's safe to delete it as the copy on S3 still exists.\n os.remove(video_name)\n logger.info(\"deleting video {}\".format(video_name))\n\n\ndef process_video(s3_bucket, s3_key, output_s3_bucket, working_dir, upload_frames, frame_prefix, visualize_frames, visualize_sample_rate,\n video_preview_prefix, clean_up_files):\n start = time.time()\n logger.info(\"Start processing {}\".format(s3_key))\n video_name = s3_key.split('/')[-1]\n s3.Bucket(s3_bucket).download_file(s3_key, video_name)\n fps = get_frame_rate(video_name)\n frame_dir = video_to_frames(video_name, working_dir)\n logger.info(\"Finished converting video to frames. Took {:10.4f} seconds\".format(time.time() - start))\n\n start = time.time()\n if visualize_frames:\n preview_file_name = generate_preview_image(fps, frame_dir, video_name, visualize_sample_rate, working_dir)\n\n logger.info(\"Stored preview at {}. took {:10.4f} seconds.\".format(os.path.join(working_dir, preview_file_name),\n time.time() - start))\n start = time.time()\n load_data_to_s3(frame_dir, preview_file_name, output_s3_bucket, frame_prefix, upload_frames, video_preview_prefix,\n working_dir)\n logger.info(\"finished uploading. took {:10.4f} seconds.\".format(time.time() - start))\n\n if clean_up_files:\n clean_up_local_files(frame_dir, video_name, upload_frames)\n\n if not upload_frames:\n print(\"The frames are stored at {}. You can use tools like s3 sync to upload them to S3. \".format(frame_dir))\n\n\ndef list_videos(s3_bucket, s3_prefix):\n object_iterator = s3.Bucket(s3_bucket).objects.filter(\n Prefix=s3_prefix\n )\n return object_iterator\n\n\ndef main():\n args = vars(ap.parse_args())\n s3_key = args[\"video_s3_key\"]\n s3_bucket = args[\"video_s3_bucket\"]\n logger.info(\"video to convert: s3://{}/{}\".format(s3_bucket, s3_key))\n\n output_s3_bucket = args[\"output_s3_bucket\"]\n working_directory = args[\"working_directory\"]\n if not os.path.isdir(working_directory):\n ap.error('--working_directory must be an existing directory')\n\n logger.info(\"storing files at: {}\".format(working_directory))\n\n upload_frames = args[\"upload_frames\"]\n frame_prefix = args[\"frame_prefix\"]\n logger.info(\"upload frames to S3: {}\".format(upload_frames))\n if upload_frames:\n if frame_prefix is None:\n ap.error('--frame_prefix must be given if upload_frames is selected')\n else:\n if not frame_prefix.endswith(\"/\"):\n frame_prefix += \"/\"\n logger.info(\"Will upload frames to s3://{}/{}\".format(s3_bucket, frame_prefix))\n\n visualize_frames = args[\"visualize_video\"]\n visualize_sample_rate = args[\"visualize_sample_rate\"]\n video_preview_prefix = args[\"video_preview_prefix\"]\n if not video_preview_prefix.endswith(\"/\"):\n video_preview_prefix += \"/\"\n\n if visualize_frames:\n logger.info(\"Will generate visualization for video sampling every {} seconds and upload to s3://{}/{}\".format(\n visualize_sample_rate, s3_bucket, video_preview_prefix))\n\n cleanup_files = args[\"cleanup_files\"]\n\n process_video(s3_bucket, s3_key, output_s3_bucket, working_directory, upload_frames, frame_prefix, visualize_frames,\n visualize_sample_rate, video_preview_prefix, cleanup_files)\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.array", "torch.from_numpy", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
wsyjwps1983/TensorFlow-Tutorials-2
[ "4dfabcb5cf14f99622dbe5f9f12f0539821c169c" ]
[ "python/04_logistic_regression.py" ]
[ "\"\"\"Simple tutorial using code from the TensorFlow example for Regression.\n\nParag K. Mital, Jan. 2016\"\"\"\n# pip3 install --upgrade\n# https://storage.googleapis.com/tensorflow/mac/tensorflow-0.6.0-py3-none-any.whl\n# %%\nimport tensorflow as tf\nimport tensorflow.examples.tutorials.mnist.input_data as input_data\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# %%\n# get the classic mnist dataset\n# one-hot means a sparse vector for every observation where only\n# the class label is 1, and every other class is 0.\n# more info here:\n# https://www.tensorflow.org/versions/0.6.0/tutorials/mnist/download/index.html#dataset-object\nmnist = input_data.read_data_sets('MNIST_data/', one_hot=True)\n\n# %%\n# mnist is now a DataSet with accessors for:\n# 'train', 'test', and 'validation'.\n# within each, we can access:\n# images, labels, and num_examples\nprint(mnist.train.num_examples,\n mnist.test.num_examples,\n mnist.validation.num_examples)\n\n# %% the images are stored as:\n# n_observations x n_features tensor (n-dim array)\n# the labels are stored as n_observations x n_labels,\n# where each observation is a one-hot vector.\nprint(mnist.train.images.shape, mnist.train.labels.shape)\n\n# %% the range of the values of the images is from 0-1\nprint(np.min(mnist.train.images), np.max(mnist.train.images))\n\n# %% we can visualize any one of the images by reshaping it to a 28x28 image\nplt.imshow(np.reshape(mnist.train.images[100, :], (28, 28)), cmap='gray')\n\n# %% We can create a container for an input image using tensorflow's graph:\n# We allow the first dimension to be None, since this will eventually\n# represent our mini-batches, or how many images we feed into a network\n# at a time during training/validation/testing.\n# The second dimension is the number of features that the image has.\nn_input = 784\nn_output = 10\nnet_input = tf.placeholder(tf.float32, [None, n_input])\n\n# %% We can write a simple regression (y = W*x + b) as:\nW = tf.Variable(tf.zeros([n_input, n_output]))\nb = tf.Variable(tf.zeros([n_output]))\nnet_output = tf.nn.softmax(tf.matmul(net_input, W) + b)\n\n# %% We'll create a placeholder for the true output of the network\ny_true = tf.placeholder(tf.float32, [None, 10])\n\n# %% And then write our loss function:\ncross_entropy = -tf.reduce_sum(y_true * tf.log(net_output))\n\n# %% This would equate each label in our one-hot vector between the\n# prediction and actual using the argmax as the predicted label\ncorrect_prediction = tf.equal(\n tf.argmax(net_output, 1), tf.argmax(y_true, 1))\n\n# %% And now we can look at the mean of our network's correct guesses\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n\n# %% We can tell the tensorflow graph to train w/ gradient descent using\n# our loss function and an input learning rate\noptimizer = tf.train.GradientDescentOptimizer(\n 0.01).minimize(cross_entropy)\n\n# %% We now create a new session to actually perform the initialization the\n# variables:\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\n# %% Now actually do some training:\nbatch_size = 100\nn_epochs = 10\nfor epoch_i in range(n_epochs):\n for batch_i in range(mnist.train.num_examples // batch_size):\n batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n sess.run(optimizer, feed_dict={\n net_input: batch_xs,\n y_true: batch_ys\n })\n print(sess.run(accuracy,\n feed_dict={\n net_input: mnist.validation.images,\n y_true: mnist.validation.labels\n }))\n\n# %% Print final test accuracy:\nprint(sess.run(accuracy,\n feed_dict={\n net_input: mnist.test.images,\n y_true: mnist.test.labels\n }))\n\n# %%\n\"\"\"\n# We could do the same thing w/ Keras like so:\nfrom keras.models import Sequential\nmodel = Sequential()\n\nfrom keras.layers.core import Dense, Activation\nmodel.add(Dense(output_dim=10, input_dim=784, init='zero'))\nmodel.add(Activation(\"softmax\"))\n\nfrom keras.optimizers import SGD\nmodel.compile(loss='categorical_crossentropy', \n optimizer=SGD(lr=learning_rate))\n\nmodel.fit(mnist.train.images, mnist.train.labels, nb_epoch=n_epochs,\n batch_size=batch_size, show_accuracy=True)\n\nobjective_score = model.evaluate(mnist.test.images, mnist.test.labels,\n batch_size=100, show_accuracy=True)\n\"\"\"\n" ]
[ [ "tensorflow.matmul", "numpy.min", "numpy.reshape", "tensorflow.zeros", "tensorflow.cast", "tensorflow.placeholder", "numpy.max", "tensorflow.global_variables_initializer", "tensorflow.train.GradientDescentOptimizer", "tensorflow.log", "tensorflow.Session", "tensorflow.argmax", "tensorflow.examples.tutorials.mnist.input_data.read_data_sets" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
erickingxu/pyBridge
[ "25f661ff7fc5806e86d1f9c87bd82541329709ac" ]
[ "torchLayer_ncnn.py" ]
[ "\r\nimport os\r\nimport fileinput\r\n\r\ntry:\r\n import numpy as np\r\nexcept:\r\n os.system('conda install numpy')\r\n import numpy as np\r\n\r\nclass NCNN_FRAMEWORK_FACTORY(object):\r\n def __init__(self, outDir = ''):\r\n self.paramFilePath = outDir + 'ncnn.param'\r\n self.binFilePath = outDir + 'ncnn.bin'\r\n self.layer_count = 0\r\n self.blob_count = 0\r\n self.net = {}\r\n self.layerSequential = []\r\n if os.path.exists(self.binFilePath):\r\n os.remove(self.binFilePath)\r\n\r\n def __str__(self):\r\n return str(self.net)\r\n\r\n #0 => float32, 0x01306B47 => float16, otherwise => quantized int8\r\n def headWriter(self, path = None):\r\n if path is None:\r\n assert \"nO header is no ncnn....\"\r\n pass\r\n with open(path, \"ab+\") as fw:\r\n fw.write(np.uint32(0).tobytes())\r\n\r\n def reWrite_locLine(self, filename, lineNo, newText, bLeft=True, bRight=False):\r\n if os.path.exists(filename):\r\n f = fileinput.input(filename, inplace=1)\r\n for line in f:\r\n line_txt = line.replace(\"\\r\\n\",\"\").replace(\"\\n\",\"\")\r\n if f.lineno() == lineNo:\r\n if bLeft:\r\n print(line_txt + newText)\r\n elif bRight:\r\n print(newText + line_txt)\r\n else:\r\n print(newText)\r\n else:\r\n print(line_txt)\r\n else:\r\n print(\"No file can be rewrotten now....\")\r\n\r\n def converting(self, torchLayer_List, blob_num):\r\n layersNum = len(torchLayer_List)\r\n if layersNum == 0:\r\n print(\"make sure...layer interpretor is running before...\")\r\n ncnn_layer_Num = 0\r\n ncnn_blob_Num = 0\r\n#####################save input layer into param file##################\r\n with open(self.paramFilePath, \"w\") as fparam:\r\n strr = 7767517\r\n fparam.write('%d\\n' % (strr))\r\n fparam.write('%d %d\\n' % (layersNum, blob_num)) #num is not ncnn's, not include split layer\r\n fparam.write('%s %s %d %d %d\\n' % ('Input', '0', 0,1,0))\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += 1\r\n for layer_Info in torchLayer_List:\r\n inp_layersName = layer_Info['inputs_layersName']\r\n inputlen = len(inp_layersName)\r\n inp_layersName = \" \".join(x for x in inp_layersName)\r\n if layer_Info['layer_Type'] == 'Convolution':\r\n layername = layer_Info['cur_layer_Name']\r\n c_inputs = layer_Info['number_of_Input_Feature_Channels']\r\n c_output = layer_Info['number_of_Output_Feature_Channels']\r\n kernel_w = layer_Info['kernel_Width']\r\n kernel_h = layer_Info['kernel_Height']\r\n dilation_w = layer_Info['dilation_Size_X']\r\n dilation_h = layer_Info['dilation_Size_Y']\r\n stride_w = layer_Info['stride_Size_X']\r\n stride_h = layer_Info['stride_Size_Y']\r\n pad_w = layer_Info['padding_Size_X']\r\n pad_h = layer_Info['padding_Size_Y']\r\n bias_term = layer_Info['if_Use_Bias']\r\n weight_data_size0 = len(layer_Info['weights_Numpy_NCHW_F32'])\r\n convtypeName = 'Convolution'\r\n convgroup = layer_Info['num_of_Group']\r\n weight_data_size = c_inputs * kernel_h * kernel_w * c_output\r\n if convgroup > 1:\r\n convtypeName = 'ConvolutionDepthWise'\r\n weight_data_size = c_inputs * kernel_h * kernel_w\r\n fparam.write(\r\n '%s %32s %32d %d %32s %s 0=%d 1=%d 11=%d 2=%d 12=%d 3=%d 13=%d 4=%d 14=%d 5=%d 6=%d 7=%d\\n' %\r\n (convtypeName, layername, inputlen, 1, inp_layersName, layername, c_output, kernel_w,\r\n kernel_h, dilation_w, dilation_h, stride_w, stride_h, pad_w, pad_h, bias_term,\r\n weight_data_size,convgroup))\r\n else:\r\n fparam.write('%s %32s %32d %d %32s %s 0=%d 1=%d 11=%d 2=%d 12=%d 3=%d 13=%d 4=%d 14=%d 5=%d 6=%d\\n' %\r\n (convtypeName, layername, inputlen, 1, inp_layersName, layername, c_output, kernel_w,\r\n kernel_h, dilation_w,dilation_h, stride_w, stride_h, pad_w, pad_h, bias_term, weight_data_size))\r\n\r\n\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += 1\r\n pass\r\n #######split pooling into several outputs\r\n if layer_Info['splitCnt'] > 1:\r\n outnms = layer_Info['outputs_layersName']\r\n splitCount = len(outnms)\r\n splitNames = \" \".join([ str(sn) for sn in outnms])\r\n fparam.write('%s %32s %32d %d %32s %s\\n' % ('Split', layername, 1, splitCount, layername, splitNames))\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += splitCount\r\n ####################write bin file for weight and bias##########\r\n with open(self.binFilePath, \"ab+\") as fbin:\r\n tag_qz = np.int32(0)\r\n fbin.write(tag_qz.tobytes())\r\n weight = layer_Info['weights_Numpy_NCHW_F32']\r\n weightbin = weight.astype('float32').tobytes()\r\n fbin.write(weightbin)\r\n if bias_term != 0:\r\n bias = layer_Info['bias_Numpy_F32']\r\n fbin.write(bias.astype('float32').tobytes())\r\n pass\r\n pass\r\n\r\n elif layer_Info['layer_Type'] == 'BatchNorm':\r\n layername = layer_Info['cur_layer_Name']\r\n channels = layer_Info['number_of_InOut_Feature_Channels']\r\n fparam.write('%s %32s %32d %d %32s %s 0=%d\\n' % ('BatchNorm', layername, inputlen, 1, inp_layersName,layername, channels))\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += 1\r\n #######split pooling into several outputs\r\n if layer_Info['splitCnt'] > 1:\r\n outnms = layer_Info['outputs_layersName']\r\n splitCount = len(outnms)\r\n splitNames = \" \".join([str(sn) for sn in outnms])\r\n fparam.write(\r\n '%s %32s %32d %d %32s %s\\n' % ('Split', layername, 1, splitCount, layername, splitNames))\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += splitCount\r\n pass\r\n ####################write bin file for weight and bias##########\r\n with open(self.binFilePath, \"ab+\") as fbin:\r\n weight_data = layer_Info['slope_data'] #scale\r\n mean_data = layer_Info['mean_data']\r\n var_data = layer_Info['var_data']\r\n bias_data = layer_Info['bias_data'] #B\r\n fbin.write(weight_data.astype('float32').tobytes())\r\n fbin.write(mean_data.astype('float32').tobytes())\r\n fbin.write(var_data.astype('float32').tobytes())\r\n fbin.write(bias_data.astype('float32').tobytes())\r\n pass\r\n pass\r\n elif layer_Info['layer_Type'] == 'MLinear':\r\n layername = layer_Info['cur_layer_Name']\r\n\r\n fparam.write('%s %32s %32d %d %32s %s 0=8 1=1 2=512\\n' % ('InnerProduct', layername, inputlen, 1, inp_layersName,layername))\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += 1\r\n #######split pooling into several outputs\r\n if layer_Info['splitCnt'] > 1:\r\n outnms = layer_Info['outputs_layersName']\r\n splitCount = len(outnms)\r\n splitNames = \" \".join([str(sn) for sn in outnms])\r\n fparam.write(\r\n '%s %32s %32d %d %32s %s\\n' % ('Split', layername, 1, splitCount, layername, splitNames))\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += splitCount\r\n pass\r\n ####################write bin file for weight and bias##########\r\n with open(self.binFilePath, \"ab+\") as fbin:\r\n weight_data = layer_Info['weights_data'] #scale\r\n bias_data = layer_Info['bias_data'] #B\r\n tag_qz = np.int32(0)\r\n fbin.write(tag_qz.tobytes())\r\n fbin.write(weight_data.astype('float32').tobytes())\r\n fbin.write(bias_data.astype('float32').tobytes())\r\n pass\r\n pass\r\n elif layer_Info['layer_Type'] == 'ReLU':\r\n layername = layer_Info['cur_layer_Name']\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += 1\r\n fparam.write('%s %32s %32d %d %32s %s\\n' % ('ReLU', layername, inputlen, 1, inp_layersName, layername))\r\n #######split pooling into several outputs\r\n if layer_Info['splitCnt'] > 1:\r\n outnms = layer_Info['outputs_layersName']\r\n splitCount = len(outnms)\r\n splitNames = \" \".join([str(sn) for sn in outnms])\r\n fparam.write(\r\n '%s %32s %32d %d %32s %s\\n' % ('Split', layername, 1, splitCount, layername, splitNames))\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += splitCount\r\n elif layer_Info['layer_Type'] == 'Pooling': # split\r\n\r\n layername = layer_Info['cur_layer_Name']\r\n poolType = layer_Info['pooling_Type']\r\n kernel_w = layer_Info['kernel_Height']\r\n kernel_h = layer_Info['kernel_Width']\r\n stride_w = layer_Info['stride_Size_X']\r\n stride_h = layer_Info['stride_Size_Y']\r\n pad_left = layer_Info['padding_Size_X']\r\n pad_right = layer_Info['padding_Size_X']\r\n pad_top = layer_Info['padding_Size_Y']\r\n pad_bottom = layer_Info['padding_Size_Y']\r\n global_pooling = 0 #layer_Info['']\r\n pad_mode = 1#layer_Info['']\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += 1\r\n fparam.write('%s %32s %32d %d %32s %s 0=%d 1=%d 11=%d 2=%d 12=%d 3=%d 13=%d 14=%d 15=%d 5=%d\\n' % ('Pooling', layername, inputlen, 1, inp_layersName, layername, poolType,kernel_w,kernel_h,stride_w,stride_h,\r\n pad_left,pad_right,pad_top,pad_bottom,pad_mode))\r\n pass\r\n #######split pooling into several outputs\r\n if layer_Info['splitCnt'] > 1:\r\n outnms = layer_Info['outputs_layersName']\r\n splitCount = len(outnms)\r\n splitNames = \" \".join([str(sn) for sn in outnms])\r\n fparam.write('%s %32s %32d %d %32s %s\\n' % ('Split', layername, 1, splitCount, layername, splitNames))\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += splitCount\r\n elif layer_Info['layer_Type'] == 'Concat': #split\r\n layername = layer_Info['cur_layer_Name']\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += 1\r\n dim = layer_Info['Concat_Dim']\r\n fparam.write('%s %32s %32d %d %32s %s 0=%d\\n' % ('Concat', layername, inputlen, 1, inp_layersName, layername,dim))\r\n pass\r\n #######split pooling into several outputs\r\n if layer_Info['splitCnt'] > 1:\r\n outnms = layer_Info['outputs_layersName']\r\n splitCount = len(outnms)\r\n splitNames = \" \".join([str(sn) for sn in outnms])\r\n fparam.write('%s %32s %32d %d %32s %s\\n' % ('Split', layername, 1, splitCount, layername, splitNames))\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += splitCount\r\n elif layer_Info['layer_Type'] == 'Upsample':#split\r\n layername = layer_Info['cur_layer_Name']\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += 1\r\n fparam.write('%s %32s %32d %d %32s %s\\n' % ('Upsample', layername, 1, 1, inp_layersName, layername))\r\n pass\r\n #######split pooling into several outputs\r\n if layer_Info['splitCnt'] > 1:\r\n outnms = layer_Info['outputs_layersName']\r\n splitCount = len(outnms)\r\n splitNames = \" \".join([str(sn) for sn in outnms])\r\n fparam.write('%s %32s %32d %d %32s %s\\n' % ('Split', layername, 1, splitCount, layername, splitNames))\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += splitCount\r\n\r\n pass\r\n elif layer_Info['layer_Type'] == 'Add':#split\r\n layername = layer_Info['cur_layer_Name']\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += 1\r\n fparam.write('%s %32s %32d %d %32s %s 0=0\\n' % ('BinaryOp', layername, 2, 1, inp_layersName, layername))\r\n pass\r\n #######split pooling into several outputs\r\n if layer_Info['splitCnt'] > 1:\r\n outnms = layer_Info['outputs_layersName']\r\n splitCount = len(outnms)\r\n splitNames = \" \".join([str(sn) for sn in outnms])\r\n fparam.write('%s %32s %32d %d %32s %s\\n' % ('Split', layername, 1, splitCount, layername, splitNames))\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += splitCount\r\n pass\r\n elif layer_Info['layer_Type'] == 'Permute':#split\r\n layername = layer_Info['cur_layer_Name']\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += 1\r\n dims = layer_Info['dims']\r\n dim_params = \"0=5\"\r\n #dim_params = \" \".join([(str(dims.index(sn))+'=' +str(sn)) for sn in dims])\r\n fparam.write('%s %32s %32d %d %32s %s %s\\n' % ('Permute', layername, 1, 1, inp_layersName, layername,dim_params))\r\n pass\r\n #######split pooling into several outputs\r\n if layer_Info['splitCnt'] > 1:\r\n outnms = layer_Info['outputs_layersName']\r\n splitCount = len(outnms)\r\n splitNames = \" \".join([str(sn) for sn in outnms])\r\n fparam.write('%s %32s %32d %d %32s %s\\n' % ('Split', layername, 1, splitCount, layername, splitNames))\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += splitCount\r\n pass\r\n elif layer_Info['layer_Type'] == 'Reshape':#split\r\n layername = layer_Info['cur_layer_Name']\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += 1\r\n tshap = layer_Info['shap'] #(4,4,1) is bug ,cause\r\n\r\n shap_params = \" \".join([(str(tshap.index(sn))+'=' +str(sn)) for sn in tshap])\r\n fparam.write('%s %32s %32d %d %32s %s %s\\n' % ('Reshape', layername, 1, 1, inp_layersName, layername,shap_params))\r\n pass\r\n #######split pooling into several outputs\r\n if layer_Info['splitCnt'] > 1:\r\n outnms = layer_Info['outputs_layersName']\r\n splitCount = len(outnms)\r\n splitNames = \" \".join([str(sn) for sn in outnms])\r\n fparam.write('%s %32s %32d %d %32s %s\\n' % ('Split', layername, 1, splitCount, layername, splitNames))\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += splitCount\r\n pass\r\n elif layer_Info['layer_Type'] == 'Softmax':#split\r\n layername = layer_Info['cur_layer_Name']\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += 1\r\n paramDim = layer_Info['softmax_Dim']\r\n\r\n fparam.write('%s %32s %32d %d %32s %s 0=%s\\n' % ('Softmax', layername, 1, 1, inp_layersName, layername,paramDim))\r\n pass\r\n #######split pooling into several outputs\r\n if layer_Info['splitCnt'] > 1:\r\n outnms = layer_Info['outputs_layersName']\r\n splitCount = len(outnms)\r\n splitNames = \" \".join([str(sn) for sn in outnms])\r\n fparam.write('%s %32s %32d %d %32s %s\\n' % ('Split', layername, 1, splitCount, layername, splitNames))\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += splitCount\r\n pass\r\n elif layer_Info['layer_Type'] == 'ReduceMean':\r\n layername = layer_Info['cur_layer_Name']\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += 1\r\n rparams = layer_Info['params'] #(4,4,1) is bug ,cause\r\n\r\n r_prams = \" \".join([(str(rparams.index(sn))+'=' +str(sn)) for sn in rparams])\r\n fparam.write('%s %32s %32d %d %32s %s %s\\n' % ('ReduceMean', layername, 1, 1, inp_layersName, layername,r_prams))\r\n pass\r\n #######split pooling into several outputs\r\n if layer_Info['splitCnt'] > 1:\r\n outnms = layer_Info['outputs_layersName']\r\n splitCount = len(outnms)\r\n splitNames = \" \".join([str(sn) for sn in outnms])\r\n fparam.write('%s %32s %32d %d %32s %s\\n' % ('Split', layername, 1, splitCount, layername, splitNames))\r\n ncnn_layer_Num += 1\r\n ncnn_blob_Num += splitCount\r\n pass\r\n else:\r\n print(\"Type info is new ,no suitable ncnn layer for compared...\")\r\n fparam.close()\r\n fbin.close()\r\n\r\n ####rewrite split layer counts###\r\n ltxt = str('%d %d' % (ncnn_layer_Num, ncnn_blob_Num))\r\n self.reWrite_locLine(self.paramFilePath,2,ltxt,False,False)\r\n\r\n return True" ]
[ [ "numpy.int32", "numpy.uint32" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
WK-Heisenberg/detectron2
[ "927b3be8b5898e2008a28b6c2adade76eeb8aa93" ]
[ "detectron2/structures/boxes.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport math\nimport numpy as np\nfrom enum import IntEnum, unique\nfrom typing import Iterator, List, Tuple, Union\nimport torch\n\n_RawBoxType = Union[List[float], Tuple[float, ...], torch.Tensor, np.ndarray]\n\n\n@unique\nclass BoxMode(IntEnum):\n \"\"\"\n Enum of different ways to represent a box.\n\n Attributes:\n\n XYXY_ABS: (x0, y0, x1, y1) in absolute floating points coordinates.\n The coordinates in range [0, width or height].\n XYWH_ABS: (x0, y0, w, h) in absolute floating points coordinates.\n XYXY_REL: (x0, y0, x1, y1) in range [0, 1]. They are relative to the size of the image.\n XYWH_REL: (x0, y0, w, h) in range [0, 1]. They are relative to the size of the image.\n XYWHA_ABS: (xc, yc, w, h, a) in absolute floating points coordinates.\n (xc, yc) is the center of the rotated box, and the angle a is in degrees ccw.\n \"\"\"\n\n XYXY_ABS = 0\n XYWH_ABS = 1\n XYXY_REL = 2\n XYWH_REL = 3\n XYWHA_ABS = 4\n\n @staticmethod\n def convert(box: _RawBoxType, from_mode: \"BoxMode\", to_mode: \"BoxMode\") -> _RawBoxType:\n \"\"\"\n Args:\n box: can be a k-tuple, k-list or an Nxk array/tensor, where k = 4 or 5\n from_mode, to_mode (BoxMode)\n\n Returns:\n The converted box of the same type.\n \"\"\"\n if from_mode == to_mode:\n return box\n\n original_type = type(box)\n is_numpy = isinstance(box, np.ndarray)\n single_box = isinstance(box, (list, tuple))\n if single_box:\n assert len(box) == 4 or len(box) == 5, (\n \"BoxMode.convert takes either a k-tuple/list or an Nxk array/tensor,\"\n \" where k == 4 or 5\"\n )\n arr = torch.tensor(box)[None, :]\n else:\n # avoid modifying the input box\n if is_numpy:\n arr = torch.from_numpy(np.asarray(box)).clone()\n else:\n arr = box.clone()\n\n assert to_mode.value not in [\n BoxMode.XYXY_REL,\n BoxMode.XYWH_REL,\n ] and from_mode.value not in [\n BoxMode.XYXY_REL,\n BoxMode.XYWH_REL,\n ], \"Relative mode not yet supported!\"\n\n if from_mode == BoxMode.XYWHA_ABS and to_mode == BoxMode.XYXY_ABS:\n assert (\n arr.shape[-1] == 5\n ), \"The last dimension of input shape must be 5 for XYWHA format\"\n original_dtype = arr.dtype\n arr = arr.double()\n\n w = arr[:, 2]\n h = arr[:, 3]\n a = arr[:, 4]\n c = torch.abs(torch.cos(a * math.pi / 180.0))\n s = torch.abs(torch.sin(a * math.pi / 180.0))\n # This basically computes the horizontal bounding rectangle of the rotated box\n new_w = c * w + s * h\n new_h = c * h + s * w\n\n # convert center to top-left corner\n arr[:, 0] -= new_w / 2.0\n arr[:, 1] -= new_h / 2.0\n # bottom-right corner\n arr[:, 2] = arr[:, 0] + new_w\n arr[:, 3] = arr[:, 1] + new_h\n\n arr = arr[:, :4].to(dtype=original_dtype)\n elif from_mode == BoxMode.XYWH_ABS and to_mode == BoxMode.XYWHA_ABS:\n original_dtype = arr.dtype\n arr = arr.double()\n arr[:, 0] += arr[:, 2] / 2.0\n arr[:, 1] += arr[:, 3] / 2.0\n angles = torch.zeros((arr.shape[0], 1), dtype=arr.dtype)\n arr = torch.cat((arr, angles), axis=1).to(dtype=original_dtype)\n else:\n if to_mode == BoxMode.XYXY_ABS and from_mode == BoxMode.XYWH_ABS:\n arr[:, 2] += arr[:, 0]\n arr[:, 3] += arr[:, 1]\n elif from_mode == BoxMode.XYXY_ABS and to_mode == BoxMode.XYWH_ABS:\n arr[:, 2] -= arr[:, 0]\n arr[:, 3] -= arr[:, 1]\n else:\n raise NotImplementedError(\n \"Conversion from BoxMode {} to {} is not supported yet\".format(\n from_mode, to_mode\n )\n )\n\n if single_box:\n return original_type(arr.flatten().tolist())\n if is_numpy:\n return arr.numpy()\n else:\n return arr\n\n\nclass Boxes:\n \"\"\"\n This structure stores a list of boxes as a Nx4 torch.Tensor.\n It supports some common methods about boxes\n (`area`, `clip`, `nonempty`, etc),\n and also behaves like a Tensor\n (support indexing, `to(device)`, `.device`, and iteration over all boxes)\n\n Attributes:\n tensor (torch.Tensor): float matrix of Nx4. Each row is (x1, y1, x2, y2).\n \"\"\"\n\n BoxSizeType = Union[List[int], Tuple[int, int]]\n\n def __init__(self, tensor: torch.Tensor):\n \"\"\"\n Args:\n tensor (Tensor[float]): a Nx4 matrix. Each row is (x1, y1, x2, y2).\n \"\"\"\n device = tensor.device if isinstance(tensor, torch.Tensor) else torch.device(\"cpu\")\n tensor = torch.as_tensor(tensor, dtype=torch.float32, device=device)\n if tensor.numel() == 0:\n # Use reshape, so we don't end up creating a new tensor that does not depend on\n # the inputs (and consequently confuses jit)\n tensor = tensor.reshape((0, 4)).to(dtype=torch.float32, device=device)\n assert tensor.dim() == 2 and tensor.size(-1) == 4, tensor.size()\n\n self.tensor = tensor\n\n def clone(self) -> \"Boxes\":\n \"\"\"\n Clone the Boxes.\n\n Returns:\n Boxes\n \"\"\"\n return Boxes(self.tensor.clone())\n\n def to(self, device: str) -> \"Boxes\":\n return Boxes(self.tensor.to(device))\n\n def area(self) -> torch.Tensor:\n \"\"\"\n Computes the area of all the boxes.\n\n Returns:\n torch.Tensor: a vector with areas of each box.\n \"\"\"\n box = self.tensor\n area = (box[:, 2] - box[:, 0]) * (box[:, 3] - box[:, 1])\n return area\n\n def clip(self, box_size: BoxSizeType) -> None:\n \"\"\"\n Clip (in place) the boxes by limiting x coordinates to the range [0, width]\n and y coordinates to the range [0, height].\n\n Args:\n box_size (height, width): The clipping box's size.\n \"\"\"\n assert torch.isfinite(self.tensor).all(), \"Box tensor contains infinite or NaN!\"\n h, w = box_size\n self.tensor[:, 0].clamp_(min=0, max=w)\n self.tensor[:, 1].clamp_(min=0, max=h)\n self.tensor[:, 2].clamp_(min=0, max=w)\n self.tensor[:, 3].clamp_(min=0, max=h)\n\n def nonempty(self, threshold: float = 0.0) -> torch.Tensor:\n \"\"\"\n Find boxes that are non-empty.\n A box is considered empty, if either of its side is no larger than threshold.\n\n Returns:\n Tensor:\n a binary vector which represents whether each box is empty\n (False) or non-empty (True).\n \"\"\"\n box = self.tensor\n widths = box[:, 2] - box[:, 0]\n heights = box[:, 3] - box[:, 1]\n keep = (widths > threshold) & (heights > threshold)\n return keep\n\n def __getitem__(self, item: Union[int, slice, torch.BoolTensor]) -> \"Boxes\":\n \"\"\"\n Returns:\n Boxes: Create a new :class:`Boxes` by indexing.\n\n The following usage are allowed:\n\n 1. `new_boxes = boxes[3]`: return a `Boxes` which contains only one box.\n 2. `new_boxes = boxes[2:10]`: return a slice of boxes.\n 3. `new_boxes = boxes[vector]`, where vector is a torch.BoolTensor\n with `length = len(boxes)`. Nonzero elements in the vector will be selected.\n\n Note that the returned Boxes might share storage with this Boxes,\n subject to Pytorch's indexing semantics.\n \"\"\"\n if isinstance(item, int):\n return Boxes(self.tensor[item].view(1, -1))\n b = self.tensor[item]\n assert b.dim() == 2, \"Indexing on Boxes with {} failed to return a matrix!\".format(item)\n return Boxes(b)\n\n def __len__(self) -> int:\n return self.tensor.shape[0]\n\n def __repr__(self) -> str:\n return \"Boxes(\" + str(self.tensor) + \")\"\n\n def inside_box(self, box_size: BoxSizeType, boundary_threshold: int = 0) -> torch.Tensor:\n \"\"\"\n Args:\n box_size (height, width): Size of the reference box.\n boundary_threshold (int): Boxes that extend beyond the reference box\n boundary by more than boundary_threshold are considered \"outside\".\n\n Returns:\n a binary vector, indicating whether each box is inside the reference box.\n \"\"\"\n height, width = box_size\n inds_inside = (\n (self.tensor[..., 0] >= -boundary_threshold)\n & (self.tensor[..., 1] >= -boundary_threshold)\n & (self.tensor[..., 2] < width + boundary_threshold)\n & (self.tensor[..., 3] < height + boundary_threshold)\n )\n return inds_inside\n\n def get_centers(self) -> torch.Tensor:\n \"\"\"\n Returns:\n The box centers in a Nx2 array of (x, y).\n \"\"\"\n return (self.tensor[:, :2] + self.tensor[:, 2:]) / 2\n\n def scale(self, scale_x: float, scale_y: float) -> None:\n \"\"\"\n Scale the box with horizontal and vertical scaling factors\n \"\"\"\n self.tensor[:, 0::2] *= scale_x\n self.tensor[:, 1::2] *= scale_y\n\n @classmethod\n def cat(cls, boxes_list: List[\"Boxes\"]) -> \"Boxes\":\n \"\"\"\n Concatenates a list of Boxes into a single Boxes\n\n Arguments:\n boxes_list (list[Boxes])\n\n Returns:\n Boxes: the concatenated Boxes\n \"\"\"\n assert isinstance(boxes_list, (list, tuple))\n if len(boxes_list) == 0:\n return cls(torch.empty(0))\n assert all(isinstance(box, Boxes) for box in boxes_list)\n\n # use torch.cat (v.s. layers.cat) so the returned boxes never share storage with input\n cat_boxes = cls(torch.cat([b.tensor for b in boxes_list], dim=0))\n return cat_boxes\n\n @property\n def device(self) -> torch.device:\n return self.tensor.device\n\n def __iter__(self) -> Iterator[torch.Tensor]:\n \"\"\"\n Yield a box as a Tensor of shape (4,) at a time.\n \"\"\"\n yield from self.tensor\n\n\n# implementation from https://github.com/kuangliu/torchcv/blob/master/torchcv/utils/box.py\n# with slight modifications\ndef pairwise_iou(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor:\n \"\"\"\n Given two lists of boxes of size N and M,\n compute the IoU (intersection over union)\n between __all__ N x M pairs of boxes.\n The box order must be (xmin, ymin, xmax, ymax).\n\n Args:\n boxes1,boxes2 (Boxes): two `Boxes`. Contains N & M boxes, respectively.\n\n Returns:\n Tensor: IoU, sized [N,M].\n \"\"\"\n area1 = boxes1.area()\n area2 = boxes2.area()\n\n boxes1, boxes2 = boxes1.tensor, boxes2.tensor\n\n width_height = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) - torch.max(\n boxes1[:, None, :2], boxes2[:, :2]\n ) # [N,M,2]\n\n width_height.clamp_(min=0) # [N,M,2]\n inter = width_height.prod(dim=2) # [N,M]\n del width_height\n\n # handle empty boxes\n iou = torch.where(\n inter > 0,\n inter / (area1[:, None] + area2 - inter),\n torch.zeros(1, dtype=inter.dtype, device=inter.device),\n )\n return iou\n\n\ndef matched_boxlist_iou(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor:\n \"\"\"\n Compute pairwise intersection over union (IOU) of two sets of matched\n boxes. The box order must be (xmin, ymin, xmax, ymax).\n Similar to boxlist_iou, but computes only diagonal elements of the matrix\n Arguments:\n boxes1: (Boxes) bounding boxes, sized [N,4].\n boxes2: (Boxes) bounding boxes, sized [N,4].\n Returns:\n (tensor) iou, sized [N].\n \"\"\"\n assert len(boxes1) == len(boxes2), (\n \"boxlists should have the same\"\n \"number of entries, got {}, {}\".format(len(boxes1), len(boxes2))\n )\n area1 = boxes1.area() # [N]\n area2 = boxes2.area() # [N]\n box1, box2 = boxes1.tensor, boxes2.tensor\n lt = torch.max(box1[:, :2], box2[:, :2]) # [N,2]\n rb = torch.min(box1[:, 2:], box2[:, 2:]) # [N,2]\n wh = (rb - lt).clamp(min=0) # [N,2]\n inter = wh[:, 0] * wh[:, 1] # [N]\n iou = inter / (area1 + area2 - inter) # [N]\n return iou\n" ]
[ [ "torch.max", "torch.empty", "torch.zeros", "torch.cat", "torch.sin", "torch.min", "numpy.asarray", "torch.tensor", "torch.isfinite", "torch.device", "torch.cos", "torch.as_tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]