repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
philipp128/skypy
[ "7a08288ab50ed8054698b78b1125310614760367" ]
[ "skypy/linear/tests/test_eisenstein_hu.py" ]
[ "import numpy as np\nimport pytest\nfrom astropy.cosmology import default_cosmology\nfrom skypy.linear.eisenstein_hu import power_spectrum\n\n\ndef test_eisenstein_hu():\n \"\"\" Test Eisenstein & Hu Linear matter power spectrum with\n and without wiggles using astropy default cosmology\"\"\"\n cosmology = default_cosmology.get()\n A_s = 2.1982e-09\n n_s = 0.969453\n kwmap = 0.02\n\n # Test that a scalar input gives a scalar output\n scalar_input = 1\n scalar_output_w = power_spectrum(scalar_input, A_s, n_s, cosmology, kwmap,\n wiggle=True)\n scalar_output_nw = power_spectrum(scalar_input, A_s, n_s, cosmology, kwmap,\n wiggle=False)\n assert np.isscalar(scalar_output_w)\n assert np.isscalar(scalar_output_nw)\n\n # Test that an array input gives an array output\n array_shape = (10,)\n array_input = np.random.uniform(size=array_shape)\n array_output_w = power_spectrum(array_input, A_s, n_s, cosmology, kwmap,\n wiggle=True)\n array_output_nw = power_spectrum(array_input, A_s, n_s, cosmology, kwmap,\n wiggle=False)\n assert array_output_w.shape == array_shape\n assert array_output_nw.shape == array_shape\n\n # Test pk against precomputed values for default_cosmology\n wavenumber = np.logspace(-3, 1, num=5, base=10.0)\n pk_eisensteinhu_w = power_spectrum(wavenumber, A_s, n_s, cosmology, kwmap,\n wiggle=True)\n pk_eisensteinhu_nw = power_spectrum(wavenumber, A_s, n_s, cosmology, kwmap,\n wiggle=False)\n pk_cosmosis_w = np.array([6.47460158e+03, 3.71610099e+04, 9.65702614e+03,\n 1.14604456e+02, 3.91399918e-01])\n pk_cosmosis_nw = np.array([6.47218600e+03, 3.77330704e+04, 1.00062077e+04,\n 1.13082980e+02, 3.83094714e-01])\n\n assert np.allclose(pk_eisensteinhu_w, pk_cosmosis_w)\n assert np.allclose(pk_eisensteinhu_nw, pk_cosmosis_nw)\n\n # Test for failure when wavenumber <= 0\n negative_wavenumber_scalar = 0\n with pytest.raises(ValueError):\n power_spectrum(negative_wavenumber_scalar, A_s, n_s, cosmology, kwmap,\n wiggle=True)\n with pytest.raises(ValueError):\n power_spectrum(negative_wavenumber_scalar, A_s, n_s, cosmology, kwmap,\n wiggle=False)\n negative_wavenumber_array = [0, 1, -2, 3]\n with pytest.raises(ValueError):\n power_spectrum(negative_wavenumber_array, A_s, n_s, cosmology, kwmap,\n wiggle=True)\n with pytest.raises(ValueError):\n power_spectrum(negative_wavenumber_array, A_s, n_s, cosmology, kwmap,\n wiggle=False)\n" ]
[ [ "numpy.array", "numpy.allclose", "numpy.random.uniform", "numpy.isscalar", "numpy.logspace" ] ]
achao2013/DeepRecon
[ "1c9b0480710212e1fe86ab75dcf0b30bd9f654e7" ]
[ "deep3dmap/core/utils/weight_init.py" ]
[ "#!/usr/bin/env python\n# -*- coding=utf8 -*-\n\"\"\"\n# Author: achao\n# File Name: weight_init.py\n# Description:\n\"\"\"\nimport copy\nimport math\nimport warnings\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch import Tensor\n\nfrom deep3dmap.core.utils import Registry, build_from_cfg, get_logger, print_log\n\nINITIALIZERS = Registry('initializer')\n\n\ndef update_init_info(module, init_info):\n \"\"\"Update the `_params_init_info` in the module if the value of parameters\n are changed.\n\n Args:\n module (obj:`nn.Module`): The module of PyTorch with a user-defined\n attribute `_params_init_info` which records the initialization\n information.\n init_info (str): The string that describes the initialization.\n \"\"\"\n assert hasattr(\n module,\n '_params_init_info'), f'Can not find `_params_init_info` in {module}'\n for name, param in module.named_parameters():\n\n assert param in module._params_init_info, (\n f'Find a new :obj:`Parameter` '\n f'named `{name}` during executing the '\n f'`init_weights` of '\n f'`{module.__class__.__name__}`. '\n f'Please do not add or '\n f'replace parameters during executing '\n f'the `init_weights`. ')\n\n # The parameter has been changed during executing the\n # `init_weights` of module\n mean_value = param.data.mean()\n if module._params_init_info[param]['tmp_mean_value'] != mean_value:\n module._params_init_info[param]['init_info'] = init_info\n module._params_init_info[param]['tmp_mean_value'] = mean_value\n\n\ndef constant_init(module, val, bias=0):\n if hasattr(module, 'weight') and module.weight is not None:\n nn.init.constant_(module.weight, val)\n if hasattr(module, 'bias') and module.bias is not None:\n nn.init.constant_(module.bias, bias)\n\n\ndef xavier_init(module, gain=1, bias=0, distribution='normal'):\n assert distribution in ['uniform', 'normal']\n if hasattr(module, 'weight') and module.weight is not None:\n if distribution == 'uniform':\n nn.init.xavier_uniform_(module.weight, gain=gain)\n else:\n nn.init.xavier_normal_(module.weight, gain=gain)\n if hasattr(module, 'bias') and module.bias is not None:\n nn.init.constant_(module.bias, bias)\n\n\ndef normal_init(module, mean=0, std=1, bias=0):\n if hasattr(module, 'weight') and module.weight is not None:\n nn.init.normal_(module.weight, mean, std)\n if hasattr(module, 'bias') and module.bias is not None:\n nn.init.constant_(module.bias, bias)\n\n\ndef trunc_normal_init(module: nn.Module,\n mean: float = 0,\n std: float = 1,\n a: float = -2,\n b: float = 2,\n bias: float = 0) -> None:\n if hasattr(module, 'weight') and module.weight is not None:\n trunc_normal_(module.weight, mean, std, a, b) # type: ignore\n if hasattr(module, 'bias') and module.bias is not None:\n nn.init.constant_(module.bias, bias) # type: ignore\n\n\ndef uniform_init(module, a=0, b=1, bias=0):\n if hasattr(module, 'weight') and module.weight is not None:\n nn.init.uniform_(module.weight, a, b)\n if hasattr(module, 'bias') and module.bias is not None:\n nn.init.constant_(module.bias, bias)\n\n\ndef kaiming_init(module,\n a=0,\n mode='fan_out',\n nonlinearity='relu',\n bias=0,\n distribution='normal'):\n assert distribution in ['uniform', 'normal']\n if hasattr(module, 'weight') and module.weight is not None:\n if distribution == 'uniform':\n nn.init.kaiming_uniform_(\n module.weight, a=a, mode=mode, nonlinearity=nonlinearity)\n else:\n nn.init.kaiming_normal_(\n module.weight, a=a, mode=mode, nonlinearity=nonlinearity)\n if hasattr(module, 'bias') and module.bias is not None:\n nn.init.constant_(module.bias, bias)\n\n\ndef caffe2_xavier_init(module, bias=0):\n # `XavierFill` in Caffe2 corresponds to `kaiming_uniform_` in PyTorch\n # Acknowledgment to FAIR's internal code\n kaiming_init(\n module,\n a=1,\n mode='fan_in',\n nonlinearity='leaky_relu',\n bias=bias,\n distribution='uniform')\n\n\ndef bias_init_with_prob(prior_prob):\n \"\"\"initialize conv/fc bias value according to a given probability value.\"\"\"\n bias_init = float(-np.log((1 - prior_prob) / prior_prob))\n return bias_init\n\n\ndef _get_bases_name(m):\n return [b.__name__ for b in m.__class__.__bases__]\n\n\nclass BaseInit(object):\n\n def __init__(self, *, bias=0, bias_prob=None, layer=None):\n self.wholemodule = False\n if not isinstance(bias, (int, float)):\n raise TypeError(f'bias must be a number, but got a {type(bias)}')\n\n if bias_prob is not None:\n if not isinstance(bias_prob, float):\n raise TypeError(f'bias_prob type must be float, \\\n but got {type(bias_prob)}')\n\n if layer is not None:\n if not isinstance(layer, (str, list)):\n raise TypeError(f'layer must be a str or a list of str, \\\n but got a {type(layer)}')\n else:\n layer = []\n\n if bias_prob is not None:\n self.bias = bias_init_with_prob(bias_prob)\n else:\n self.bias = bias\n self.layer = [layer] if isinstance(layer, str) else layer\n\n def _get_init_info(self):\n info = f'{self.__class__.__name__}, bias={self.bias}'\n return info\n\n\n@INITIALIZERS.register_module(name='Constant')\nclass ConstantInit(BaseInit):\n \"\"\"Initialize module parameters with constant values.\n\n Args:\n val (int | float): the value to fill the weights in the module with\n bias (int | float): the value to fill the bias. Defaults to 0.\n bias_prob (float, optional): the probability for bias initialization.\n Defaults to None.\n layer (str | list[str], optional): the layer will be initialized.\n Defaults to None.\n \"\"\"\n\n def __init__(self, val, **kwargs):\n super().__init__(**kwargs)\n self.val = val\n\n def __call__(self, module):\n\n def init(m):\n if self.wholemodule:\n constant_init(m, self.val, self.bias)\n else:\n layername = m.__class__.__name__\n basesname = _get_bases_name(m)\n if len(set(self.layer) & set([layername] + basesname)):\n constant_init(m, self.val, self.bias)\n\n module.apply(init)\n if hasattr(module, '_params_init_info'):\n update_init_info(module, init_info=self._get_init_info())\n\n def _get_init_info(self):\n info = f'{self.__class__.__name__}: val={self.val}, bias={self.bias}'\n return info\n\n\n@INITIALIZERS.register_module(name='Xavier')\nclass XavierInit(BaseInit):\n r\"\"\"Initialize module parameters with values according to the method\n described in `Understanding the difficulty of training deep feedforward\n neural networks - Glorot, X. & Bengio, Y. (2010).\n <http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf>`_\n\n Args:\n gain (int | float): an optional scaling factor. Defaults to 1.\n bias (int | float): the value to fill the bias. Defaults to 0.\n bias_prob (float, optional): the probability for bias initialization.\n Defaults to None.\n distribution (str): distribution either be ``'normal'``\n or ``'uniform'``. Defaults to ``'normal'``.\n layer (str | list[str], optional): the layer will be initialized.\n Defaults to None.\n \"\"\"\n\n def __init__(self, gain=1, distribution='normal', **kwargs):\n super().__init__(**kwargs)\n self.gain = gain\n self.distribution = distribution\n\n def __call__(self, module):\n\n def init(m):\n if self.wholemodule:\n xavier_init(m, self.gain, self.bias, self.distribution)\n else:\n layername = m.__class__.__name__\n basesname = _get_bases_name(m)\n if len(set(self.layer) & set([layername] + basesname)):\n xavier_init(m, self.gain, self.bias, self.distribution)\n\n module.apply(init)\n if hasattr(module, '_params_init_info'):\n update_init_info(module, init_info=self._get_init_info())\n\n def _get_init_info(self):\n info = f'{self.__class__.__name__}: gain={self.gain}, ' \\\n f'distribution={self.distribution}, bias={self.bias}'\n return info\n\n\n@INITIALIZERS.register_module(name='Normal')\nclass NormalInit(BaseInit):\n r\"\"\"Initialize module parameters with the values drawn from the normal\n distribution :math:`\\mathcal{N}(\\text{mean}, \\text{std}^2)`.\n\n Args:\n mean (int | float):the mean of the normal distribution. Defaults to 0.\n std (int | float): the standard deviation of the normal distribution.\n Defaults to 1.\n bias (int | float): the value to fill the bias. Defaults to 0.\n bias_prob (float, optional): the probability for bias initialization.\n Defaults to None.\n layer (str | list[str], optional): the layer will be initialized.\n Defaults to None.\n\n \"\"\"\n\n def __init__(self, mean=0, std=1, **kwargs):\n super().__init__(**kwargs)\n self.mean = mean\n self.std = std\n\n def __call__(self, module):\n\n def init(m):\n if self.wholemodule:\n normal_init(m, self.mean, self.std, self.bias)\n else:\n layername = m.__class__.__name__\n basesname = _get_bases_name(m)\n if len(set(self.layer) & set([layername] + basesname)):\n normal_init(m, self.mean, self.std, self.bias)\n\n module.apply(init)\n if hasattr(module, '_params_init_info'):\n update_init_info(module, init_info=self._get_init_info())\n\n def _get_init_info(self):\n info = f'{self.__class__.__name__}: mean={self.mean},' \\\n f' std={self.std}, bias={self.bias}'\n return info\n\n\n@INITIALIZERS.register_module(name='TruncNormal')\nclass TruncNormalInit(BaseInit):\n r\"\"\"Initialize module parameters with the values drawn from the normal\n distribution :math:`\\mathcal{N}(\\text{mean}, \\text{std}^2)` with values\n outside :math:`[a, b]`.\n\n Args:\n mean (float): the mean of the normal distribution. Defaults to 0.\n std (float): the standard deviation of the normal distribution.\n Defaults to 1.\n a (float): The minimum cutoff value.\n b ( float): The maximum cutoff value.\n bias (float): the value to fill the bias. Defaults to 0.\n bias_prob (float, optional): the probability for bias initialization.\n Defaults to None.\n layer (str | list[str], optional): the layer will be initialized.\n Defaults to None.\n\n \"\"\"\n\n def __init__(self,\n mean: float = 0,\n std: float = 1,\n a: float = -2,\n b: float = 2,\n **kwargs) -> None:\n super().__init__(**kwargs)\n self.mean = mean\n self.std = std\n self.a = a\n self.b = b\n\n def __call__(self, module: nn.Module) -> None:\n\n def init(m):\n if self.wholemodule:\n trunc_normal_init(m, self.mean, self.std, self.a, self.b,\n self.bias)\n else:\n layername = m.__class__.__name__\n basesname = _get_bases_name(m)\n if len(set(self.layer) & set([layername] + basesname)):\n trunc_normal_init(m, self.mean, self.std, self.a, self.b,\n self.bias)\n\n module.apply(init)\n if hasattr(module, '_params_init_info'):\n update_init_info(module, init_info=self._get_init_info())\n\n def _get_init_info(self):\n info = f'{self.__class__.__name__}: a={self.a}, b={self.b},' \\\n f' mean={self.mean}, std={self.std}, bias={self.bias}'\n return info\n\n\n@INITIALIZERS.register_module(name='Uniform')\nclass UniformInit(BaseInit):\n r\"\"\"Initialize module parameters with values drawn from the uniform\n distribution :math:`\\mathcal{U}(a, b)`.\n\n Args:\n a (int | float): the lower bound of the uniform distribution.\n Defaults to 0.\n b (int | float): the upper bound of the uniform distribution.\n Defaults to 1.\n bias (int | float): the value to fill the bias. Defaults to 0.\n bias_prob (float, optional): the probability for bias initialization.\n Defaults to None.\n layer (str | list[str], optional): the layer will be initialized.\n Defaults to None.\n \"\"\"\n\n def __init__(self, a=0, b=1, **kwargs):\n super().__init__(**kwargs)\n self.a = a\n self.b = b\n\n def __call__(self, module):\n\n def init(m):\n if self.wholemodule:\n uniform_init(m, self.a, self.b, self.bias)\n else:\n layername = m.__class__.__name__\n basesname = _get_bases_name(m)\n if len(set(self.layer) & set([layername] + basesname)):\n uniform_init(m, self.a, self.b, self.bias)\n\n module.apply(init)\n if hasattr(module, '_params_init_info'):\n update_init_info(module, init_info=self._get_init_info())\n\n def _get_init_info(self):\n info = f'{self.__class__.__name__}: a={self.a},' \\\n f' b={self.b}, bias={self.bias}'\n return info\n\n\n@INITIALIZERS.register_module(name='Kaiming')\nclass KaimingInit(BaseInit):\n r\"\"\"Initialize module parameters with the values according to the method\n described in `Delving deep into rectifiers: Surpassing human-level\n performance on ImageNet classification - He, K. et al. (2015).\n <https://www.cv-foundation.org/openaccess/content_iccv_2015/\n papers/He_Delving_Deep_into_ICCV_2015_paper.pdf>`_\n\n Args:\n a (int | float): the negative slope of the rectifier used after this\n layer (only used with ``'leaky_relu'``). Defaults to 0.\n mode (str): either ``'fan_in'`` or ``'fan_out'``. Choosing\n ``'fan_in'`` preserves the magnitude of the variance of the weights\n in the forward pass. Choosing ``'fan_out'`` preserves the\n magnitudes in the backwards pass. Defaults to ``'fan_out'``.\n nonlinearity (str): the non-linear function (`nn.functional` name),\n recommended to use only with ``'relu'`` or ``'leaky_relu'`` .\n Defaults to 'relu'.\n bias (int | float): the value to fill the bias. Defaults to 0.\n bias_prob (float, optional): the probability for bias initialization.\n Defaults to None.\n distribution (str): distribution either be ``'normal'`` or\n ``'uniform'``. Defaults to ``'normal'``.\n layer (str | list[str], optional): the layer will be initialized.\n Defaults to None.\n \"\"\"\n\n def __init__(self,\n a=0,\n mode='fan_out',\n nonlinearity='relu',\n distribution='normal',\n **kwargs):\n super().__init__(**kwargs)\n self.a = a\n self.mode = mode\n self.nonlinearity = nonlinearity\n self.distribution = distribution\n\n def __call__(self, module):\n\n def init(m):\n if self.wholemodule:\n kaiming_init(m, self.a, self.mode, self.nonlinearity,\n self.bias, self.distribution)\n else:\n layername = m.__class__.__name__\n basesname = _get_bases_name(m)\n if len(set(self.layer) & set([layername] + basesname)):\n kaiming_init(m, self.a, self.mode, self.nonlinearity,\n self.bias, self.distribution)\n\n module.apply(init)\n if hasattr(module, '_params_init_info'):\n update_init_info(module, init_info=self._get_init_info())\n\n def _get_init_info(self):\n info = f'{self.__class__.__name__}: a={self.a}, mode={self.mode}, ' \\\n f'nonlinearity={self.nonlinearity}, ' \\\n f'distribution ={self.distribution}, bias={self.bias}'\n return info\n\n\n@INITIALIZERS.register_module(name='Caffe2Xavier')\nclass Caffe2XavierInit(KaimingInit):\n # `XavierFill` in Caffe2 corresponds to `kaiming_uniform_` in PyTorch\n # Acknowledgment to FAIR's internal code\n def __init__(self, **kwargs):\n super().__init__(\n a=1,\n mode='fan_in',\n nonlinearity='leaky_relu',\n distribution='uniform',\n **kwargs)\n\n def __call__(self, module):\n super().__call__(module)\n\n\n@INITIALIZERS.register_module(name='Pretrained')\nclass PretrainedInit(object):\n \"\"\"Initialize module by loading a pretrained model.\n\n Args:\n checkpoint (str): the checkpoint file of the pretrained model should\n be load.\n prefix (str, optional): the prefix of a sub-module in the pretrained\n model. it is for loading a part of the pretrained model to\n initialize. For example, if we would like to only load the\n backbone of a detector model, we can set ``prefix='backbone.'``.\n Defaults to None.\n map_location (str): map tensors into proper locations.\n \"\"\"\n\n def __init__(self, checkpoint, prefix=None, map_location=None):\n self.checkpoint = checkpoint\n self.prefix = prefix\n self.map_location = map_location\n\n def __call__(self, module):\n from deep3dmap.runners import (_load_checkpoint_with_prefix, load_checkpoint,\n load_state_dict)\n logger = get_logger('deep3dmap')\n if self.prefix is None:\n print_log(f'load model from: {self.checkpoint}', logger=logger)\n load_checkpoint(\n module,\n self.checkpoint,\n map_location=self.map_location,\n strict=False,\n logger=logger)\n else:\n print_log(\n f'load {self.prefix} in model from: {self.checkpoint}',\n logger=logger)\n state_dict = _load_checkpoint_with_prefix(\n self.prefix, self.checkpoint, map_location=self.map_location)\n load_state_dict(module, state_dict, strict=False, logger=logger)\n\n if hasattr(module, '_params_init_info'):\n update_init_info(module, init_info=self._get_init_info())\n\n def _get_init_info(self):\n info = f'{self.__class__.__name__}: load from {self.checkpoint}'\n return info\n\n\ndef _initialize(module, cfg, wholemodule=False):\n func = build_from_cfg(cfg, INITIALIZERS)\n # wholemodule flag is for override mode, there is no layer key in override\n # and initializer will give init values for the whole module with the name\n # in override.\n func.wholemodule = wholemodule\n func(module)\n\n\ndef _initialize_override(module, override, cfg):\n if not isinstance(override, (dict, list)):\n raise TypeError(f'override must be a dict or a list of dict, \\\n but got {type(override)}')\n\n override = [override] if isinstance(override, dict) else override\n\n for override_ in override:\n\n cp_override = copy.deepcopy(override_)\n name = cp_override.pop('name', None)\n if name is None:\n raise ValueError('`override` must contain the key \"name\",'\n f'but got {cp_override}')\n # if override only has name key, it means use args in init_cfg\n if not cp_override:\n cp_override.update(cfg)\n # if override has name key and other args except type key, it will\n # raise error\n elif 'type' not in cp_override.keys():\n raise ValueError(\n f'`override` need \"type\" key, but got {cp_override}')\n\n if hasattr(module, name):\n _initialize(getattr(module, name), cp_override, wholemodule=True)\n else:\n raise RuntimeError(f'module did not have attribute {name}, '\n f'but init_cfg is {cp_override}.')\n\n\ndef initialize(module, init_cfg):\n \"\"\"Initialize a module.\n\n Args:\n module (``torch.nn.Module``): the module will be initialized.\n init_cfg (dict | list[dict]): initialization configuration dict to\n define initializer. OpenMMLab has implemented 6 initializers\n including ``Constant``, ``Xavier``, ``Normal``, ``Uniform``,\n ``Kaiming``, and ``Pretrained``.\n Example:\n >>> module = nn.Linear(2, 3, bias=True)\n >>> init_cfg = dict(type='Constant', layer='Linear', val =1 , bias =2)\n >>> initialize(module, init_cfg)\n\n >>> module = nn.Sequential(nn.Conv1d(3, 1, 3), nn.Linear(1,2))\n >>> # define key ``'layer'`` for initializing layer with different\n >>> # configuration\n >>> init_cfg = [dict(type='Constant', layer='Conv1d', val=1),\n dict(type='Constant', layer='Linear', val=2)]\n >>> initialize(module, init_cfg)\n\n >>> # define key``'override'`` to initialize some specific part in\n >>> # module\n >>> class FooNet(nn.Module):\n >>> def __init__(self):\n >>> super().__init__()\n >>> self.feat = nn.Conv2d(3, 16, 3)\n >>> self.reg = nn.Conv2d(16, 10, 3)\n >>> self.cls = nn.Conv2d(16, 5, 3)\n >>> model = FooNet()\n >>> init_cfg = dict(type='Constant', val=1, bias=2, layer='Conv2d',\n >>> override=dict(type='Constant', name='reg', val=3, bias=4))\n >>> initialize(model, init_cfg)\n\n >>> model = ResNet(depth=50)\n >>> # Initialize weights with the pretrained model.\n >>> init_cfg = dict(type='Pretrained',\n checkpoint='torchvision://resnet50')\n >>> initialize(model, init_cfg)\n\n >>> # Initialize weights of a sub-module with the specific part of\n >>> # a pretrained model by using \"prefix\".\n >>> url = 'http://download.openmmlab.com/mmdetection/v2.0/retinanet/'\\\n >>> 'retinanet_r50_fpn_1x_coco/'\\\n >>> 'retinanet_r50_fpn_1x_coco_20200130-c2398f9e.pth'\n >>> init_cfg = dict(type='Pretrained',\n checkpoint=url, prefix='backbone.')\n \"\"\"\n if not isinstance(init_cfg, (dict, list)):\n raise TypeError(f'init_cfg must be a dict or a list of dict, \\\n but got {type(init_cfg)}')\n\n if isinstance(init_cfg, dict):\n init_cfg = [init_cfg]\n\n for cfg in init_cfg:\n # should deeply copy the original config because cfg may be used by\n # other modules, e.g., one init_cfg shared by multiple bottleneck\n # blocks, the expected cfg will be changed after pop and will change\n # the initialization behavior of other modules\n cp_cfg = copy.deepcopy(cfg)\n override = cp_cfg.pop('override', None)\n _initialize(module, cp_cfg)\n\n if override is not None:\n cp_cfg.pop('layer', None)\n _initialize_override(module, override, cp_cfg)\n else:\n # All attributes in module have same initialization.\n pass\n\n\ndef _no_grad_trunc_normal_(tensor: Tensor, mean: float, std: float, a: float,\n b: float) -> Tensor:\n # Method based on\n # https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf\n # Modified from\n # https://github.com/pytorch/pytorch/blob/master/torch/nn/init.py\n def norm_cdf(x):\n # Computes standard normal cumulative distribution function\n return (1. + math.erf(x / math.sqrt(2.))) / 2.\n\n if (mean < a - 2 * std) or (mean > b + 2 * std):\n warnings.warn(\n 'mean is more than 2 std from [a, b] in nn.init.trunc_normal_. '\n 'The distribution of values may be incorrect.',\n stacklevel=2)\n\n with torch.no_grad():\n # Values are generated by using a truncated uniform distribution and\n # then using the inverse CDF for the normal distribution.\n # Get upper and lower cdf values\n lower = norm_cdf((a - mean) / std)\n upper = norm_cdf((b - mean) / std)\n\n # Uniformly fill tensor with values from [lower, upper], then translate\n # to [2lower-1, 2upper-1].\n tensor.uniform_(2 * lower - 1, 2 * upper - 1)\n\n # Use inverse cdf transform for normal distribution to get truncated\n # standard normal\n tensor.erfinv_()\n\n # Transform to proper mean, std\n tensor.mul_(std * math.sqrt(2.))\n tensor.add_(mean)\n\n # Clamp to ensure it's in the proper range\n tensor.clamp_(min=a, max=b)\n return tensor\n\n\ndef trunc_normal_(tensor: Tensor,\n mean: float = 0.,\n std: float = 1.,\n a: float = -2.,\n b: float = 2.) -> Tensor:\n r\"\"\"Fills the input Tensor with values drawn from a truncated\n normal distribution. The values are effectively drawn from the\n normal distribution :math:`\\mathcal{N}(\\text{mean}, \\text{std}^2)`\n with values outside :math:`[a, b]` redrawn until they are within\n the bounds. The method used for generating the random values works\n best when :math:`a \\leq \\text{mean} \\leq b`.\n\n Modified from\n https://github.com/pytorch/pytorch/blob/master/torch/nn/init.py\n\n Args:\n tensor (``torch.Tensor``): an n-dimensional `torch.Tensor`.\n mean (float): the mean of the normal distribution.\n std (float): the standard deviation of the normal distribution.\n a (float): the minimum cutoff value.\n b (float): the maximum cutoff value.\n \"\"\"\n return _no_grad_trunc_normal_(tensor, mean, std, a, b)\n\n" ]
[ [ "torch.nn.init.kaiming_uniform_", "numpy.log", "torch.nn.init.constant_", "torch.no_grad", "torch.nn.init.kaiming_normal_", "torch.nn.init.xavier_uniform_", "torch.nn.init.normal_", "torch.nn.init.uniform_", "torch.nn.init.xavier_normal_" ] ]
mrugeles/mlflow
[ "ff819e69c215c6272cbea4b284a05d22ae8774be" ]
[ "mlflow/keras.py" ]
[ "\"\"\"\nThe ``mlflow.keras`` module provides an API for logging and loading Keras models. This module\nexports Keras models with the following flavors:\n\nKeras (native) format\n This is the main flavor that can be loaded back into Keras.\n:py:mod:`mlflow.pyfunc`\n Produced for use by generic pyfunc-based deployment tools and batch inference.\n\"\"\"\nimport importlib\nimport os\nimport yaml\nimport gorilla\nimport tempfile\nimport shutil\n\nimport pandas as pd\n\nfrom distutils.version import LooseVersion\nfrom mlflow import pyfunc\nfrom mlflow.models import Model\nimport mlflow.tracking\nfrom mlflow.exceptions import MlflowException\nfrom mlflow.models.signature import ModelSignature\nfrom mlflow.models.utils import ModelInputExample, _save_example\nfrom mlflow.tracking.artifact_utils import _download_artifact_from_uri\nfrom mlflow.utils.environment import _mlflow_conda_env\nfrom mlflow.utils.model_utils import _get_flavor_configuration\nfrom mlflow.utils.annotations import experimental\nfrom mlflow.utils.autologging_utils import try_mlflow_log, log_fn_args_as_params\n\n\nFLAVOR_NAME = \"keras\"\n# File name to which custom objects cloudpickle is saved - used during save and load\n_CUSTOM_OBJECTS_SAVE_PATH = \"custom_objects.cloudpickle\"\n_KERAS_MODULE_SPEC_PATH = \"keras_module.txt\"\n# File name to which keras model is saved\n_MODEL_SAVE_PATH = \"model.h5\"\n# Conda env subpath when saving/loading model\n_CONDA_ENV_SUBPATH = \"conda.yaml\"\n\n\ndef get_default_conda_env(include_cloudpickle=False, keras_module=None):\n \"\"\"\n :return: The default Conda environment for MLflow Models produced by calls to\n :func:`save_model()` and :func:`log_model()`.\n \"\"\"\n import tensorflow as tf\n conda_deps = [] # if we use tf.keras we only need to declare dependency on tensorflow\n pip_deps = []\n if keras_module is None:\n import keras\n keras_module = keras\n if keras_module.__name__ == \"keras\":\n # Temporary fix: the created conda environment has issues installing keras >= 2.3.1\n if LooseVersion(keras_module.__version__) < LooseVersion('2.3.1'):\n conda_deps.append(\"keras=={}\".format(keras_module.__version__))\n else:\n pip_deps.append(\"keras=={}\".format(keras_module.__version__))\n if include_cloudpickle:\n import cloudpickle\n pip_deps.append(\"cloudpickle=={}\".format(cloudpickle.__version__))\n # Temporary fix: conda-forge currently does not have tensorflow > 1.14\n # The Keras pyfunc representation requires the TensorFlow\n # backend for Keras. Therefore, the conda environment must\n # include TensorFlow\n if LooseVersion(tf.__version__) <= LooseVersion('1.13.2'):\n conda_deps.append(\"tensorflow=={}\".format(tf.__version__))\n else:\n pip_deps.append(\"tensorflow=={}\".format(tf.__version__))\n\n return _mlflow_conda_env(\n additional_conda_deps=conda_deps,\n additional_pip_deps=pip_deps,\n additional_conda_channels=None)\n\n\ndef save_model(keras_model, path, conda_env=None, mlflow_model=None, custom_objects=None,\n keras_module=None,\n signature: ModelSignature = None, input_example: ModelInputExample = None,\n **kwargs):\n \"\"\"\n Save a Keras model to a path on the local file system.\n\n :param keras_model: Keras model to be saved.\n :param path: Local path where the model is to be saved.\n :param conda_env: Either a dictionary representation of a Conda environment or the path to a\n Conda environment yaml file. If provided, this decsribes the environment\n this model should be run in. At minimum, it should specify the\n dependencies contained in :func:`get_default_conda_env()`. If\n ``None``, the default :func:`get_default_conda_env()` environment is\n added to the model. The following is an *example* dictionary\n representation of a Conda environment::\n\n {\n 'name': 'mlflow-env',\n 'channels': ['defaults'],\n 'dependencies': [\n 'python=3.7.0',\n 'keras=2.2.4',\n 'tensorflow=1.8.0'\n ]\n }\n :param mlflow_model: MLflow model config this flavor is being added to.\n :param custom_objects: A Keras ``custom_objects`` dictionary mapping names (strings) to\n custom classes or functions associated with the Keras model. MLflow saves\n these custom layers using CloudPickle and restores them automatically\n when the model is loaded with :py:func:`mlflow.keras.load_model` and\n :py:func:`mlflow.pyfunc.load_model`.\n :param keras_module: Keras module to be used to save / load the model\n (``keras`` or ``tf.keras``). If not provided, MLflow will\n attempt to infer the Keras module based on the given model.\n :param kwargs: kwargs to pass to ``keras_model.save`` method.\n\n :param signature: (Experimental) :py:class:`ModelSignature <mlflow.models.ModelSignature>`\n describes model input and output :py:class:`Schema <mlflow.types.Schema>`.\n The model signature can be :py:func:`inferred <mlflow.models.infer_signature>`\n from datasets with valid model input (e.g. the training dataset with target\n column omitted) and valid model output (e.g. model predictions generated on\n the training dataset), for example:\n\n .. code-block:: python\n\n from mlflow.models.signature import infer_signature\n train = df.drop_column(\"target_label\")\n predictions = ... # compute model predictions\n signature = infer_signature(train, predictions)\n :param input_example: (Experimental) Input example provides one or several instances of valid\n model input. The example can be used as a hint of what data to feed the\n model. The given example will be converted to a Pandas DataFrame and then\n serialized to json using the Pandas split-oriented format. Bytes are\n base64-encoded.\n\n .. code-block:: python\n :caption: Example\n\n import mlflow\n # Build, compile, and train your model\n keras_model = ...\n keras_model_path = ...\n keras_model.compile(optimizer=\"rmsprop\", loss=\"mse\", metrics=[\"accuracy\"])\n results = keras_model.fit(\n x_train, y_train, epochs=20, batch_size = 128, validation_data=(x_val, y_val))\n # Save the model as an MLflow Model\n mlflow.keras.save_model(keras_model, keras_model_path)\n \"\"\"\n if keras_module is None:\n def _is_plain_keras(model):\n try:\n # NB: Network is the first parent with save method\n import keras.engine.network\n return isinstance(model, keras.engine.network.Network)\n except ImportError:\n return False\n\n def _is_tf_keras(model):\n try:\n # NB: Network is not exposed in tf.keras, we check for Model instead.\n import tensorflow.keras.models\n return isinstance(model, tensorflow.keras.models.Model)\n except ImportError:\n return False\n\n if _is_plain_keras(keras_model):\n keras_module = importlib.import_module(\"keras\")\n elif _is_tf_keras(keras_model):\n keras_module = importlib.import_module(\"tensorflow.keras\")\n else:\n raise MlflowException(\"Unable to infer keras module from the model, please specify \"\n \"which keras module ('keras' or 'tensorflow.keras') is to be \"\n \"used to save and load the model.\")\n elif type(keras_module) == str:\n keras_module = importlib.import_module(keras_module)\n\n # check if path exists\n path = os.path.abspath(path)\n if os.path.exists(path):\n raise MlflowException(\"Path '{}' already exists\".format(path))\n\n # construct new data folder in existing path\n data_subpath = \"data\"\n data_path = os.path.join(path, data_subpath)\n os.makedirs(data_path)\n\n if mlflow_model is None:\n mlflow_model = Model()\n if signature is not None:\n mlflow_model.signature = signature\n if input_example is not None:\n _save_example(mlflow_model, input_example, path)\n\n # save custom objects if there are custom objects\n if custom_objects is not None:\n _save_custom_objects(data_path, custom_objects)\n\n # save keras module spec to path/data/keras_module.txt\n with open(os.path.join(data_path, _KERAS_MODULE_SPEC_PATH), \"w\") as f:\n f.write(keras_module.__name__)\n\n # save keras model to path/data/model.h5\n model_subpath = os.path.join(data_subpath, _MODEL_SAVE_PATH)\n model_path = os.path.join(path, model_subpath)\n if path.startswith('/dbfs/'):\n # The Databricks Filesystem uses a FUSE implementation that does not support\n # random writes. It causes an error.\n with tempfile.NamedTemporaryFile(suffix='.h5') as f:\n keras_model.save(f.name, **kwargs)\n f.flush() # force flush the data\n shutil.copyfile(src=f.name, dst=model_path)\n else:\n keras_model.save(model_path, **kwargs)\n\n # update flavor info to mlflow_model\n mlflow_model.add_flavor(FLAVOR_NAME,\n keras_module=keras_module.__name__,\n keras_version=keras_module.__version__,\n data=data_subpath)\n\n # save conda.yaml info to path/conda.yml\n if conda_env is None:\n conda_env = get_default_conda_env(include_cloudpickle=custom_objects is not None,\n keras_module=keras_module)\n elif not isinstance(conda_env, dict):\n with open(conda_env, \"r\") as f:\n conda_env = yaml.safe_load(f)\n with open(os.path.join(path, _CONDA_ENV_SUBPATH), \"w\") as f:\n yaml.safe_dump(conda_env, stream=f, default_flow_style=False)\n\n # append loader_module, data and env data to mlflow_model\n pyfunc.add_to_model(mlflow_model, loader_module=\"mlflow.keras\",\n data=data_subpath, env=_CONDA_ENV_SUBPATH)\n\n # save mlflow_model to path/MLmodel\n mlflow_model.save(os.path.join(path, \"MLmodel\"))\n\n\ndef log_model(keras_model, artifact_path, conda_env=None, custom_objects=None, keras_module=None,\n registered_model_name=None, signature: ModelSignature=None,\n input_example: ModelInputExample=None, **kwargs):\n \"\"\"\n Log a Keras model as an MLflow artifact for the current run.\n\n :param keras_model: Keras model to be saved.\n :param artifact_path: Run-relative artifact path.\n :param conda_env: Either a dictionary representation of a Conda environment or\n the path to a Conda environment yaml file.\n If provided, this describes the environment this model should be\n run in. At minimum, it should specify the dependencies\n contained in :func:`get_default_conda_env()`. If ``None``, the default\n :func:`mlflow.keras.get_default_conda_env()` environment is added to\n the model. The following is an *example* dictionary representation of a\n Conda environment::\n\n {\n 'name': 'mlflow-env',\n 'channels': ['defaults'],\n 'dependencies': [\n 'python=3.7.0',\n 'keras=2.2.4',\n 'tensorflow=1.8.0'\n ]\n }\n\n :param custom_objects: A Keras ``custom_objects`` dictionary mapping names (strings) to\n custom classes or functions associated with the Keras model. MLflow saves\n these custom layers using CloudPickle and restores them automatically\n when the model is loaded with :py:func:`mlflow.keras.load_model` and\n :py:func:`mlflow.pyfunc.load_model`.\n :param keras_module: Keras module to be used to save / load the model\n (``keras`` or ``tf.keras``). If not provided, MLflow will\n attempt to infer the Keras module based on the given model.\n :param registered_model_name: (Experimental) If given, create a model version under\n ``registered_model_name``, also creating a registered model if one\n with the given name does not exist.\n\n :param signature: (Experimental) :py:class:`ModelSignature <mlflow.models.ModelSignature>`\n describes model input and output :py:class:`Schema <mlflow.types.Schema>`.\n The model signature can be :py:func:`inferred <mlflow.models.infer_signature>`\n from datasets with valid model input (e.g. the training dataset with target\n column omitted) and valid model output (e.g. model predictions generated on\n the training dataset), for example:\n\n .. code-block:: python\n\n from mlflow.models.signature import infer_signature\n train = df.drop_column(\"target_label\")\n predictions = ... # compute model predictions\n signature = infer_signature(train, predictions)\n :param input_example: (Experimental) Input example provides one or several instances of valid\n model input. The example can be used as a hint of what data to feed the\n model. The given example will be converted to a Pandas DataFrame and then\n serialized to json using the Pandas split-oriented format. Bytes are\n base64-encoded.\n\n :param kwargs: kwargs to pass to ``keras_model.save`` method.\n\n .. code-block:: python\n :caption: Example\n\n from keras import Dense, layers\n import mlflow\n # Build, compile, and train your model\n keras_model = ...\n keras_model.compile(optimizer=\"rmsprop\", loss=\"mse\", metrics=[\"accuracy\"])\n results = keras_model.fit(\n x_train, y_train, epochs=20, batch_size = 128, validation_data=(x_val, y_val))\n # Log metrics and log the model\n with mlflow.start_run() as run:\n mlflow.keras.log_model(keras_model, \"models\")\n \"\"\"\n Model.log(artifact_path=artifact_path, flavor=mlflow.keras,\n keras_model=keras_model, conda_env=conda_env, custom_objects=custom_objects,\n keras_module=keras_module, registered_model_name=registered_model_name,\n signature=signature, input_example=input_example,\n **kwargs)\n\n\ndef _save_custom_objects(path, custom_objects):\n \"\"\"\n Save custom objects dictionary to a cloudpickle file so a model can be easily loaded later.\n\n :param path: An absolute path that points to the data directory within /path/to/model.\n :param custom_objects: Keras ``custom_objects`` is a dictionary mapping\n names (strings) to custom classes or functions to be considered\n during deserialization. MLflow saves these custom layers using\n CloudPickle and restores them automatically when the model is\n loaded with :py:func:`mlflow.keras.load_model` and\n :py:func:`mlflow.pyfunc.load_model`.\n \"\"\"\n import cloudpickle\n custom_objects_path = os.path.join(path, _CUSTOM_OBJECTS_SAVE_PATH)\n with open(custom_objects_path, \"wb\") as out_f:\n cloudpickle.dump(custom_objects, out_f)\n\n\ndef _load_model(model_path, keras_module, **kwargs):\n keras_models = importlib.import_module(keras_module.__name__ + \".models\")\n custom_objects = kwargs.pop(\"custom_objects\", {})\n custom_objects_path = None\n if os.path.isdir(model_path):\n if os.path.isfile(os.path.join(model_path, _CUSTOM_OBJECTS_SAVE_PATH)):\n custom_objects_path = os.path.join(model_path, _CUSTOM_OBJECTS_SAVE_PATH)\n model_path = os.path.join(model_path, _MODEL_SAVE_PATH)\n if custom_objects_path is not None:\n import cloudpickle\n with open(custom_objects_path, \"rb\") as in_f:\n pickled_custom_objects = cloudpickle.load(in_f)\n pickled_custom_objects.update(custom_objects)\n custom_objects = pickled_custom_objects\n from distutils.version import StrictVersion\n if StrictVersion(keras_module.__version__.split('-')[0]) >= StrictVersion(\"2.2.3\"):\n # NOTE: Keras 2.2.3 does not work with unicode paths in python2. Pass in h5py.File instead\n # of string to avoid issues.\n import h5py\n with h5py.File(os.path.abspath(model_path), \"r\") as model_path:\n return keras_models.load_model(model_path, custom_objects=custom_objects, **kwargs)\n else:\n # NOTE: Older versions of Keras only handle filepath.\n return keras_models.load_model(model_path, custom_objects=custom_objects, **kwargs)\n\n\nclass _KerasModelWrapper:\n def __init__(self, keras_model, graph, sess):\n self.keras_model = keras_model\n self._graph = graph\n self._sess = sess\n\n def predict(self, dataframe):\n # In TensorFlow < 2.0, we use a graph and session to predict\n if self._graph is not None:\n with self._graph.as_default():\n with self._sess.as_default():\n predicted = pd.DataFrame(self.keras_model.predict(dataframe.values))\n # In TensorFlow >= 2.0, we do not use a graph and session to predict\n else:\n predicted = pd.DataFrame(self.keras_model.predict(dataframe.values))\n predicted.index = dataframe.index\n return predicted\n\n\ndef _load_pyfunc(path):\n \"\"\"\n Load PyFunc implementation. Called by ``pyfunc.load_pyfunc``.\n\n :param path: Local filesystem path to the MLflow Model with the ``keras`` flavor.\n \"\"\"\n import tensorflow as tf\n if os.path.isfile(os.path.join(path, _KERAS_MODULE_SPEC_PATH)):\n with open(os.path.join(path, _KERAS_MODULE_SPEC_PATH), \"r\") as f:\n keras_module = importlib.import_module(f.read())\n else:\n import keras\n keras_module = keras\n\n K = importlib.import_module(keras_module.__name__ + \".backend\")\n if keras_module.__name__ == \"tensorflow.keras\" or K.backend() == 'tensorflow':\n if LooseVersion(tf.__version__) < LooseVersion('2.0.0'):\n graph = tf.Graph()\n sess = tf.Session(graph=graph)\n # By default tf backed models depend on the global graph and session.\n # We create an use new Graph and Session and store them with the model\n # This way the model is independent on the global state.\n with graph.as_default():\n with sess.as_default(): # pylint:disable=not-context-manager\n K.set_learning_phase(0)\n m = _load_model(path, keras_module=keras_module, compile=False)\n return _KerasModelWrapper(m, graph, sess)\n else:\n K.set_learning_phase(0)\n m = _load_model(path, keras_module=keras_module, compile=False)\n return _KerasModelWrapper(m, None, None)\n\n else:\n raise MlflowException(\"Unsupported backend '%s'\" % K._BACKEND)\n\n\ndef load_model(model_uri, **kwargs):\n \"\"\"\n Load a Keras model from a local file or a run.\n\n Extra arguments are passed through to keras.load_model.\n\n :param model_uri: The location, in URI format, of the MLflow model. For example:\n\n - ``/Users/me/path/to/local/model``\n - ``relative/path/to/local/model``\n - ``s3://my_bucket/path/to/model``\n - ``runs:/<mlflow_run_id>/run-relative/path/to/model``\n - ``models:/<model_name>/<model_version>``\n - ``models:/<model_name>/<stage>``\n\n For more information about supported URI schemes, see\n `Referencing Artifacts <https://www.mlflow.org/docs/latest/concepts.html#\n artifact-locations>`_.\n\n :return: A Keras model instance.\n\n .. code-block:: python\n :caption: Example\n\n # Load persisted model as a Keras model or as a PyFunc, call predict() on a pandas DataFrame\n keras_model = mlflow.keras.load_model(\"runs:/96771d893a5e46159d9f3b49bf9013e2\" + \"/models\")\n predictions = keras_model.predict(x_test)\n \"\"\"\n local_model_path = _download_artifact_from_uri(artifact_uri=model_uri)\n flavor_conf = _get_flavor_configuration(model_path=local_model_path, flavor_name=FLAVOR_NAME)\n keras_module = importlib.import_module(flavor_conf.get(\"keras_module\", \"keras\"))\n keras_model_artifacts_path = os.path.join(\n local_model_path,\n flavor_conf.get(\"data\", _MODEL_SAVE_PATH))\n return _load_model(model_path=keras_model_artifacts_path, keras_module=keras_module, **kwargs)\n\n\n@experimental\ndef autolog():\n # pylint: disable=E0611\n \"\"\"\n Enables automatic logging from Keras to MLflow. Autologging captures the following information:\n\n **Metrics** and **Parameters**\n - Training loss; validation loss; user-specified metrics\n - Metrics associated with the ``EarlyStopping`` callbacks: ``stopped_epoch``,\n ``restored_epoch``, ``restore_best_weight``, ``last_epoch``, etc\n - ``fit()`` or ``fit_generator()`` parameters; optimizer name; learning rate; epsilon\n - ``fit()`` or ``fit_generator()`` parameters associated with ``EarlyStopping``: ``min_delta``,\n ``patience``, ``baseline``, ``restore_best_weights``, etc\n **Artifacts**\n - Model summary on training start\n - `MLflow Model <https://mlflow.org/docs/latest/models.html>`_ (Keras model) on training end\n\n .. code-block:: python\n :caption: Example\n\n import mlflow\n import mlflow.keras\n # Build, compile, enable autologging, and train your model\n keras_model = ...\n keras_model.compile(optimizer=\"rmsprop\", loss=\"mse\", metrics=[\"accuracy\"])\n # autolog your metrics, parameters, and model\n mlflow.keras.autolog()\n results = keras_model.fit(\n x_train, y_train, epochs=20, batch_size=128, validation_data=(x_val, y_val))\n\n ``EarlyStopping Integration with Keras AutoLogging``\n\n MLflow will detect if an ``EarlyStopping`` callback is used in a ``fit()`` or\n ``fit_generator()`` call, and if the ``restore_best_weights`` parameter is set to be ``True``,\n then MLflow will log the metrics associated with the restored model as a final, extra step.\n The epoch of the restored model will also be logged as the metric ``restored_epoch``.\n This allows for easy comparison between the actual metrics of the restored model and\n the metrics of other models.\n\n If ``restore_best_weights`` is set to be ``False``, then MLflow will not log an additional step.\n\n Regardless of ``restore_best_weights``, MLflow will also log ``stopped_epoch``,\n which indicates the epoch at which training stopped due to early stopping.\n\n If training does not end due to early stopping, then ``stopped_epoch`` will be logged as ``0``.\n\n MLflow will also log the parameters of the ``EarlyStopping`` callback,\n excluding ``mode`` and ``verbose``.\n \"\"\"\n import keras\n\n class __MLflowKerasCallback(keras.callbacks.Callback):\n \"\"\"\n Callback for auto-logging metrics and parameters.\n Records available logs after each epoch.\n Records model structural information as params when training begins\n \"\"\"\n def on_train_begin(self, logs=None): # pylint: disable=unused-argument\n try_mlflow_log(mlflow.log_param, 'num_layers', len(self.model.layers))\n try_mlflow_log(mlflow.log_param, 'optimizer_name', type(self.model.optimizer).__name__)\n if hasattr(self.model.optimizer, 'lr'):\n lr = self.model.optimizer.lr if \\\n type(self.model.optimizer.lr) is float \\\n else keras.backend.eval(self.model.optimizer.lr)\n try_mlflow_log(mlflow.log_param, 'learning_rate', lr)\n if hasattr(self.model.optimizer, 'epsilon'):\n epsilon = self.model.optimizer.epsilon if \\\n type(self.model.optimizer.epsilon) is float \\\n else keras.backend.eval(self.model.optimizer.epsilon)\n try_mlflow_log(mlflow.log_param, 'epsilon', epsilon)\n\n sum_list = []\n self.model.summary(print_fn=sum_list.append)\n summary = '\\n'.join(sum_list)\n tempdir = tempfile.mkdtemp()\n try:\n summary_file = os.path.join(tempdir, \"model_summary.txt\")\n with open(summary_file, 'w') as f:\n f.write(summary)\n try_mlflow_log(mlflow.log_artifact, local_path=summary_file)\n finally:\n shutil.rmtree(tempdir)\n\n def on_epoch_end(self, epoch, logs=None):\n if not logs:\n return\n try_mlflow_log(mlflow.log_metrics, logs, step=epoch)\n\n def on_train_end(self, logs=None):\n try_mlflow_log(log_model, self.model, artifact_path='model')\n\n # As of Keras 2.4.0, Keras Callback implementations must define the following\n # methods indicating whether or not the callback overrides functions for\n # batch training/testing/inference\n def _implements_train_batch_hooks(self): return False\n\n def _implements_test_batch_hooks(self): return False\n\n def _implements_predict_batch_hooks(self): return False\n\n def _early_stop_check(callbacks):\n if LooseVersion(keras.__version__) < LooseVersion('2.3.0'):\n es_callback = keras.callbacks.EarlyStopping\n else:\n es_callback = keras.callbacks.callbacks.EarlyStopping\n for callback in callbacks:\n if isinstance(callback, es_callback):\n return callback\n return None\n\n def _log_early_stop_callback_params(callback):\n if callback:\n try:\n earlystopping_params = {'monitor': callback.monitor,\n 'min_delta': callback.min_delta,\n 'patience': callback.patience,\n 'baseline': callback.baseline,\n 'restore_best_weights': callback.restore_best_weights}\n try_mlflow_log(mlflow.log_params, earlystopping_params)\n except Exception: # pylint: disable=W0703\n return\n\n def _get_early_stop_callback_attrs(callback):\n try:\n return callback.stopped_epoch, callback.restore_best_weights, callback.patience\n except Exception: # pylint: disable=W0703\n return None\n\n def _log_early_stop_callback_metrics(callback, history):\n if callback:\n callback_attrs = _get_early_stop_callback_attrs(callback)\n if callback_attrs is None:\n return\n stopped_epoch, restore_best_weights, patience = callback_attrs\n try_mlflow_log(mlflow.log_metric, 'stopped_epoch', stopped_epoch)\n # Weights are restored only if early stopping occurs\n if stopped_epoch != 0 and restore_best_weights:\n restored_epoch = stopped_epoch - max(1, patience)\n try_mlflow_log(mlflow.log_metric, 'restored_epoch', restored_epoch)\n restored_metrics = {key: history.history[key][restored_epoch]\n for key in history.history.keys()}\n # Checking that a metric history exists\n metric_key = next(iter(history.history), None)\n if metric_key is not None:\n last_epoch = len(history.history[metric_key])\n try_mlflow_log(mlflow.log_metrics, restored_metrics, step=last_epoch)\n\n def _run_and_log_function(self, original, args, kwargs, unlogged_params, callback_arg_index):\n if not mlflow.active_run():\n try_mlflow_log(mlflow.start_run)\n auto_end_run = True\n else:\n auto_end_run = False\n\n log_fn_args_as_params(original, args, kwargs, unlogged_params)\n early_stop_callback = None\n\n # Checking if the 'callback' argument of the function is set\n if len(args) > callback_arg_index:\n tmp_list = list(args)\n early_stop_callback = _early_stop_check(tmp_list[callback_arg_index])\n tmp_list[callback_arg_index] += [__MLflowKerasCallback()]\n args = tuple(tmp_list)\n elif 'callbacks' in kwargs:\n early_stop_callback = _early_stop_check(kwargs['callbacks'])\n kwargs['callbacks'] += [__MLflowKerasCallback()]\n else:\n kwargs['callbacks'] = [__MLflowKerasCallback()]\n\n _log_early_stop_callback_params(early_stop_callback)\n\n history = original(self, *args, **kwargs)\n\n _log_early_stop_callback_metrics(early_stop_callback, history)\n\n if auto_end_run:\n try_mlflow_log(mlflow.end_run)\n\n return history\n\n @gorilla.patch(keras.Model)\n def fit(self, *args, **kwargs):\n original = gorilla.get_original_attribute(keras.Model, 'fit')\n unlogged_params = ['self', 'x', 'y', 'callbacks', 'validation_data', 'verbose']\n return _run_and_log_function(self, original, args, kwargs, unlogged_params, 5)\n\n @gorilla.patch(keras.Model)\n def fit_generator(self, *args, **kwargs):\n original = gorilla.get_original_attribute(keras.Model, 'fit_generator')\n unlogged_params = ['self', 'generator', 'callbacks', 'validation_data', 'verbose']\n return _run_and_log_function(self, original, args, kwargs, unlogged_params, 4)\n\n settings = gorilla.Settings(allow_hit=True, store_hit=True)\n gorilla.apply(gorilla.Patch(keras.Model, 'fit', fit, settings=settings))\n gorilla.apply(gorilla.Patch(keras.Model, 'fit_generator', fit_generator, settings=settings))\n" ]
[ [ "tensorflow.Graph", "tensorflow.Session" ] ]
fevorl/BM3D_py
[ "aefd4ceb2bd9e95bd7e67285a714bccd5e2140e5", "aefd4ceb2bd9e95bd7e67285a714bccd5e2140e5" ]
[ "cpp2py_test/bior_2d_forward_test2.py", "cpp2py_test/BM_test.py" ]
[ "import math\nimport numpy as np\nfrom cpp2py_test.bior_2d_forward_test1 import original_bior_2d_forward, bior15_coef\n\n\ndef bior_2d_forward(img):\n assert img.shape[0] == img.shape[1]\n N = img.shape[0]\n iter_max = int(math.log2(N))\n\n for iter in range(iter_max):\n coeffs2 = pywt.dwt2(img[:N, :N], 'bior1.5', mode='periodic')\n LL, (LH, HL, HH) = coeffs2\n img[:N//2, :N//2] = LL[2: -2, 2: -2]\n img[N//2:N, N//2:N] = HH[2: -2, 2: -2]\n img[:N//2, N//2:N] = -HL[2: -2, 2: -2]\n img[N//2:N, :N//2] = -LH[2: -2, 2: -2]\n N //= 2\n return img\n\n\nif __name__ == '__main__':\n import cv2\n import pywt\n import matplotlib.pyplot as plt\n\n img = cv2.imread('Cameraman256.png', cv2.IMREAD_GRAYSCALE)\n img = img.astype(np.float64)\n # img = img[0:8, 0:8]\n\n # original way\n original_bior_img = original_bior_2d_forward(img)\n\n # my way\n bior_img = bior_2d_forward(img.copy())\n\n\n # a, b = 0, 8\n # c, d = 0, 8\n # print('original_bior_img\\n', original_bior_img[a:b, c:d].astype(np.int))\n # print('bior_img\\n', bior_img[a:b, c:d].astype(np.int))\n\n # print('max original_bior_img', np.max(original_bior_img))\n # print('min original_bior_img', np.min(original_bior_img))\n #\n # print('max bior_img', np.max(bior_img))\n # print('min bior_img', np.min(bior_img))\n diff = original_bior_img - bior_img\n print('sum of diff', np.sum(np.abs(diff)))\n print('max of diff', np.max(np.abs(diff)))\n cv2.imshow('original_bior_img', original_bior_img)\n cv2.imshow('bior_img', bior_img)\n cv2.imshow('diff', diff)\n cv2.waitKey()\n", "import numpy as np\n\n\ndef precompute_BM(img, width, height, kHW, NHW, nHW, pHW, tauMatch):\n Ns = 2 * nHW + 1\n threshold = tauMatch * kHW * kHW\n diff_table = np.zeros(width * height, dtype=np.int)\n sum_table = np.ones(((nHW + 1) * Ns, width * height), dtype=np.int) * 2 * threshold\n row_ind = ind_initialize(height - kHW + 1, nHW, pHW)\n column_ind = ind_initialize(width - kHW + 1, nHW, pHW)\n\n for di in range(nHW + 1):\n for dj in range(Ns):\n dk = int(di * width + dj) - int(nHW)\n ddk = di * Ns + dj\n for i in range(nHW, height - nHW):\n k = i * width + nHW\n for j in range(nHW, width - nHW):\n diff_table[k] = (img[k + dk] - img[k]) * (img[k + dk] - img[k])\n k += 1\n dn = nHW * width + nHW\n value = 0.0\n for p in range(kHW):\n pq = p * width + dn\n for q in range(kHW):\n value += diff_table[pq]\n pq += 1\n sum_table[ddk][dn] = value\n\n for j in range(nHW + 1, width - nHW):\n ind = nHW * width + j - 1\n sum = sum_table[ddk][ind]\n for p in range(kHW):\n sum += diff_table[ind + p * width + kHW] - diff_table[ind + p * width]\n sum_table[ddk][ind + 1] = sum\n\n for i in range(nHW + 1, height - nHW):\n ind = (i - 1) * width + nHW\n sum = sum_table[ddk][ind]\n for q in range(kHW):\n sum += diff_table[ind + kHW * width + q] - diff_table[ind + q]\n sum_table[ddk][ind + width] = sum\n\n k = i * width + nHW + 1\n pq = (i + kHW - 1) * width + kHW - 1 + nHW + 1\n for j in range(nHW + 1, width - nHW):\n sum_table[ddk][k] = \\\n sum_table[ddk][k - 1] \\\n + sum_table[ddk][k - width] \\\n - sum_table[ddk][k - 1 - width] \\\n + diff_table[pq] \\\n - diff_table[pq - kHW] \\\n - diff_table[pq - kHW * width] \\\n + diff_table[pq - kHW - kHW * width]\n k += 1\n pq += 1\n\n patch_table = np.zeros((width * height, NHW), dtype=np.int)\n for ind_i in row_ind:\n for ind_j in column_ind:\n k_r = ind_i * width + ind_j\n table_distance = np.empty(shape=[0, 2], dtype=np.int)\n\n for dj in range(-nHW, nHW + 1):\n for di in range(nHW + 1):\n if sum_table[dj + nHW + di * Ns][k_r] < threshold:\n pair = np.array([[sum_table[dj + nHW + di * Ns][k_r], k_r + di * width + dj]], dtype=np.int)\n # print(k_r)\n # print(k_r + di * width + dj)\n table_distance = np.append(table_distance, pair, axis=0)\n\n for di in range(-nHW, 0):\n if sum_table[-dj + nHW + (-di) * Ns][k_r] < threshold:\n pair = np.array(\n [[sum_table[-dj + nHW + (-di) * Ns][k_r + di * width + dj], k_r + di * width + dj]],\n dtype=np.int)\n table_distance = np.append(table_distance, pair, axis=0)\n\n nSx_r = closest_power_of_2(len(table_distance) * 2) if NHW > len(\n table_distance) * 2 else NHW\n\n if nSx_r == 1 and len(table_distance) * 2 == 0:\n pair = np.array([[0, k_r]], dtype=np.int)\n table_distance = np.append(table_distance, pair, axis=0)\n\n # partial_sort(table_distance.begin(), table_distance.begin() + nSx_r,\n # table_distance.end(), ComparaisonFirst);\n sorted(table_distance, key=lambda x: x[0], ) # some problem, seems like it dose not work\n\n for n in range(nSx_r):\n patch_table[k_r][n] = table_distance[n][1]\n\n if nSx_r == 1:\n patch_table[k_r][0] = table_distance[0][1]\n\n return patch_table\n\n\ndef closest_power_of_2(n):\n r = 1\n while (r * 2 <= n):\n r *= 2\n return r\n\n\ndef ind_initialize(max_size, N, step):\n ind_set = np.empty(shape=[0], dtype=np.int)\n ind = N\n while (ind < max_size - N):\n ind_set = np.append(ind_set, np.array([ind]), axis=0)\n ind += step\n if ind_set[-1] < max_size - N - 1:\n ind_set = np.append(ind_set, np.array([max_size - N - 1]), axis=0)\n return ind_set\n\n\ndef get_add_patch_matrix(n, nHW, kHW):\n \"\"\"\n :param n: len of mat\n :param nHW: len of search area\n :param kHW: len of patch\n :return: manipulate mat\n \"\"\"\n mat = np.eye(n - 2 * nHW)\n mat = np.pad(mat, nHW, 'constant')\n res_mat = mat.copy()\n for k in range(1, kHW):\n res_mat += transport_2d_mat(mat, right=k, down=0)\n return res_mat\n\n\ndef my_precompute_BM(img, width, height, kHW, NHW, nHW, pHW, tauMatch, Pr):\n Ns = 2 * nHW + 1\n threshold = tauMatch * kHW * kHW\n sum_table = np.ones((Ns * Ns, height, width), dtype=np.int) * 2 * threshold # di*width+dj, ph, pw\n add_mat = get_add_patch_matrix(width, nHW, kHW)\n diff_margin = np.pad(np.ones((height - 2 * nHW, width - 2 * nHW)), ((nHW, nHW), (nHW, nHW)), 'constant',\n constant_values=(0, 0)).astype(np.uint8)\n sum_margin = (1 - diff_margin) * 2 * threshold\n\n for di in range(-nHW, nHW + 1):\n for dj in range(-nHW, nHW + 1):\n ddk = (di + nHW) * Ns + dj + nHW\n t_img = transport_2d_mat(img, right=-dj, down=-di)\n diff_table = (img - t_img) * (img - t_img) * diff_margin\n\n sum_t = np.matmul(np.matmul(add_mat, diff_table), add_mat.T)\n sum_table[ddk] = np.maximum(sum_t, sum_margin)\n\n sum_table = sum_table.reshape((Ns * Ns, height * width)) # di_dj, ph_pw\n sum_table_T = sum_table.transpose((1, 0)) # ph_pw__di_dj\n # print(sum_table_T[22].reshape(Ns, Ns))\n argsort = np.argsort(sum_table_T, axis=1)\n argsort_di = argsort // (Ns) - nHW\n argsort_dj = argsort % (Ns) - nHW\n Pr_S__Vnear = argsort_di * width + argsort_dj\n Pr_S__Pnear = Pr_S__Vnear + np.arange(Pr_S__Vnear.shape[0]).reshape((Pr_S__Vnear.shape[0], 1))\n Pr_N__Pnear = Pr_S__Pnear[:, :NHW]\n # for test\n nn = Pr\n for ag, di, dj, posr, pr in zip(argsort[nn], argsort_di[nn], argsort_dj[nn], Pr_S__Vnear[nn], Pr_S__Pnear[nn]):\n print(ag, '\\t', di, '\\t', dj, '\\t', posr, '\\t', pr)\n # for test\n sum_filter = np.where(sum_table_T < threshold, 1, 0)\n threshold_count = np.sum(sum_filter, axis=1)\n\n return Pr_N__Pnear, threshold_count\n\n\ndef translation_2d_mat(mat, right, down):\n mat = np.roll(mat, right, axis=1)\n mat = np.roll(mat, down, axis=0)\n return mat\n\n\nif __name__ == '__main__':\n import cv2\n\n im = cv2.imread('Cameraman256.png', cv2.IMREAD_GRAYSCALE)\n im_w = im.shape[1]\n ref_y, ref_x = 100, 100\n Pr = ref_y * im_w + ref_x\n nHW = 2\n print(im[ref_y - nHW:ref_y + nHW + 1, ref_x - nHW:ref_x + nHW + 1])\n\n # im = np.zeros_like(im)\n height, width = im.shape[0], im.shape[1]\n\n im_flat = im.flatten()\n\n # a = precompute_BM(im, width, height, kHW=8, NHW=16, nHW=16, pHW=3, tauMatch=40)\n aaa = precompute_BM(im_flat, width, height, kHW=1, NHW=9, nHW=nHW, pHW=1, tauMatch=10)\n bbb = my_precompute_BM(im, width, height, kHW=1, NHW=9, nHW=nHW, pHW=1, tauMatch=10, Pr=Pr)\n bbb = bbb[0]\n # print(aaa)\n # print(bbb[0])\n # for b in bbb:\n # print(b)\n\n for a, b in zip(aaa, bbb):\n # print(a.reshape(wh, wh))\n # print(b.reshape(wh, wh))\n print('----------------')\n print(a)\n print(b)\n #\n # diff = aaa - bbb\n # for line in diff:\n # print(line.reshape(wh, wh))\n" ]
[ [ "numpy.abs" ], [ "numpy.pad", "numpy.array", "numpy.empty", "numpy.matmul", "numpy.zeros", "numpy.sum", "numpy.ones", "numpy.roll", "numpy.eye", "numpy.where", "numpy.arange", "numpy.argsort", "numpy.append", "numpy.maximum" ] ]
ReleasedBrainiac/GraphToSequenceNN
[ "70861637088bc38054beeab44a5c478254b5da25" ]
[ "Scripts/Plotter/PlotHistory.py" ]
[ "import re\nimport matplotlib.pyplot as plt\nfrom DatasetHandler.ContentSupport import isNotNone, isNone\nfrom Plotter.SavePlots import PlotSaver\n\nclass HistoryPlotter(object):\n \"\"\"\n This class provides a History plotting pipeline using mathplot.\n \"\"\"\n\n _using_history:bool = False # This for a later implemented part of the tool\n _path:str = None\n _history = None\n _history_keys:dict = None\n _history_keys_list:list = None\n _losses:list = None\n _val_losses:list = None\n _acc_stdcc_list:list = None\n _val_acc_stdcc_list:list = None\n _acc_topkcc_list:list = None\n _val_acc_topkcc_list:list = None\n _learning_rates:list = None\n _epochs:int = 0\n\n def __init__(self, model_description:str, path:str = None, history = None, save_it:bool = True, new_style:bool = False):\n \"\"\"\n The class constructor. \n Attention: File history plotting is not yet implemented!\n :param model_description:str: something to name the image unique and is also the file name\n :param path:str: path of a file containing a history\n :param history: a history\n :param save_it:bool: save the plot instead of showing\n :param new_style:bool: desired matplot lib standard or new style\n \"\"\" \n try:\n self._model_description = model_description if isNotNone(model_description) else 'undescribed_model'\n\n if isNotNone(path) and isNone(history):\n self._path:str = path \n self._using_history = False\n\n if isNotNone(history):\n self._history = history \n self._history_keys = history.history.keys()\n self._history_keys_list = list(self._history_keys)\n self._using_history = True\n\n \n self._new_style:bool = new_style\n self._save_it:bool = save_it\n except Exception as ex:\n template = \"An exception of type {0} occurred in [HistoryPlotter.Constructor]. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print(message)\n\n def PlotHistory(self):\n \"\"\"\n Thise method allow to plot a history from directly a keras history. \n Plotting from log is not yet implemented!\n \"\"\" \n try:\n if self._using_history:\n if self._new_style:\n self.CollectFromHistory()\n self.DirectPlotHistory()\n else:\n self.OldPlotHistory()\n\n #TODO: Log file history plotting is not yet implemented\n #else:\n # self.PlotHistoryFromLog()\n except Exception as ex:\n template = \"An exception of type {0} occurred in [HistoryPlotter.PlotHistory]. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print(message)\n \n def CollectAccFromHistory(self, name:str):\n \"\"\"\n This method collect the accuracy data from the history into 2 lists.\n :param name:str: name of the used acc metric\n \"\"\" \n try:\n acc_list:list = []\n val_acc_list:list = []\n\n name = re.sub('val_', '', name)\n if name in self._history_keys:\n acc_list = [s for s in self._history_keys if (name == s)]\n val_acc_list = [s for s in self._history_keys if ('val_'+name == s)]\n\n if isNotNone(acc_list) and isNotNone(val_acc_list):\n self._history_keys_list.remove(name)\n self._history_keys_list.remove('val_'+name)\n print(\"Found accuracy metrics in history!\")\n\n return acc_list, val_acc_list\n except Exception as ex:\n template = \"An exception of type {0} occurred in [HistoryPlotter.CollectAccFromHistory]. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print(message)\n\n def CollectLossFromHistory(self):\n \"\"\"\n This method collect the loss metric data from the history.\n \"\"\" \n try:\n loss_val:str = 'loss'\n if loss_val in self._history_keys:\n self._losses = [s for s in self._history_keys if (loss_val == s)]\n\n \n\n self._val_losses = [s for s in self._history_keys if ('val'+loss_val in s)]\n self._epochs = len(self._history.epoch)\n\n if len(self._losses) == 0 or len(self._val_losses) == 0:\n print('Loss is missing in history')\n return \n\n if isNotNone(self._losses) and isNotNone(self._val_losses):\n self._history_keys_list.remove(loss_val)\n self._history_keys_list.remove('val_'+loss_val)\n print(\"Found losses in history!\")\n except Exception as ex:\n template = \"An exception of type {0} occurred in [HistoryPlotter.CollectLossFromHistory]. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print(message)\n \n def CollectLearningRatesFromHistory(self):\n \"\"\"\n This method collect the learning rate metric data from the history.\n \"\"\" \n try:\n lr_val:str = 'lr'\n if lr_val in self._history_keys:\n self._learning_rates = [s for s in self._history_keys if (lr_val == s)]\n if isNotNone(self._learning_rates):\n self._history_keys_list.remove(lr_val)\n print(\"Found learning rates in history!\")\n except Exception as ex:\n template = \"An exception of type {0} occurred in [HistoryPlotter.CollectLearningRatesFromHistory]. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print(message)\n\n def CollectFromHistory(self):\n \"\"\"\n This method collect all necessary train informations from the history.\n \"\"\" \n if self._using_history:\n try:\n print(\"Collect losses from history...\")\n self.CollectLossFromHistory()\n print(\"Collect learning rate from history...\")\n self.CollectLearningRatesFromHistory()\n print(\"Collect \", self._history_keys_list[0], \" from history...\")\n self._acc_stdcc_list, self._val_acc_stdcc_list = self.CollectAccFromHistory(name=self._history_keys_list[0])\n print(\"Collect \", self._history_keys_list[0], \" from history...\")\n self._acc_topkcc_list, self._val_acc_topkcc_list = self.CollectAccFromHistory(name=self._history_keys_list[0])\n except Exception as ex:\n template = \"An exception of type {0} occurred in [HistoryPlotter.CollectFromHistory]. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print(message)\n else:\n print('No history initialized!')\n\n def DirectPlotHistory(self):\n \"\"\"\n This method helps to plot a keras history containing losses, accuracy and possibly least learning rates.\n \"\"\" \n try:\n fig_num:int = 1\n\n ## Loss\n self.AccOrLossPlot( fig_num = fig_num, \n title = 'Model loss', \n metric = 'loss', \n axis_labels = ['train', 'validation'], \n history_labels = ['Loss', 'Epoch'], \n extender = 'loss_epoch_plot',\n train_val_lists = [self._losses, self._val_losses])\n fig_num += 1\n\n ## Top k Categorical Crossentropy\n if ('top_k_categorical_accuracy' in self._history_keys) and isNotNone(self._acc_topkcc_list) and isNotNone(self._val_acc_topkcc_list):\n self.AccOrLossPlot( fig_num = fig_num, \n title = 'Model Top k Categorical Accuracy', \n metric = 'top_k_categorical_accuracy', \n axis_labels = ['train', 'validation'], \n history_labels = ['Top k Categorical Accuracy', 'Epoch'], \n extender = 'top_k_categoriacal_epoch_plot',\n train_val_lists = [self._acc_topkcc_list, self._val_acc_topkcc_list])\n fig_num += 1\n\n ## Categorical Crossentropy\n if 'categorical_accuracy' in self._history_keys and isNotNone(self._acc_stdcc_list) and isNotNone(self._val_acc_stdcc_list):\n self.AccOrLossPlot( fig_num = fig_num, \n title = 'Model Categorical Accuracy', \n metric = 'categorical_accuracy', \n axis_labels = ['train', 'validation'], \n history_labels = ['Categorical Accuracy', 'Epoch'], \n extender = 'categoriacal_epoch_plot',\n train_val_lists = [self._acc_stdcc_list, self._val_acc_stdcc_list])\n fig_num += 1\n \n ## General\n if 'acc' in self._history_keys and isNotNone(self._acc_stdcc_list) and isNotNone(self._val_acc_stdcc_list):\n self.AccOrLossPlot( fig_num = fig_num, \n title = 'Model Accuracy', \n metric = 'accuracy', \n axis_labels = ['train', 'validation'], \n history_labels = ['Accuracy', 'Epoch'], \n extender = 'accuracy_epoch_plot',\n train_val_lists = [self._acc_stdcc_list, self._val_acc_stdcc_list])\n fig_num += 1\n \n\n if 'lr' in self._history_keys and isNotNone(self._learning_rates):\n self.LearningPlot( fig_num = fig_num,\n title = 'Model Learning Rate')\n fig_num += 1\n\n except Exception as ex:\n template = \"An exception of type {0} occurred in [HistoryPlotter.DirectPlotHistory]. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print(message)\n\n def OldPlotHistory(self):\n \"\"\"\n This method plot the history in the old way.\n \"\"\" \n try:\n fig_num:int = 1\n\n self.AccOrLossPlot( fig_num = fig_num, \n title = 'Model loss', \n metric = 'loss', \n axis_labels = ['train', 'validation'], \n history_labels = ['Loss', 'Epoch'], \n extender = 'loss_epoch_plot')\n fig_num += 1\n\n if 'acc' in self._history_keys:\n self.AccOrLossPlot( fig_num = fig_num, \n title = 'Model Accuracy', \n metric = 'acc', \n axis_labels = ['train', 'validation'], \n history_labels = ['Accuracy', 'Epoch'], \n extender = 'accuracy_epoch_plot')\n fig_num += 1\n\n if 'top_k_categorical_accuracy' in self._history_keys:\n self.AccOrLossPlot( fig_num = fig_num, \n title = 'Model Top k Categorical Accuracy', \n metric = 'top_k_categorical_accuracy', \n axis_labels = ['train', 'validation'], \n history_labels = ['Top k Categorical Accuracy', 'Epoch'], \n extender = 'top_k_categoriacal_epoch_plot')\n fig_num += 1\n\n if 'categorical_accuracy' in self._history_keys:\n self.AccOrLossPlot( fig_num = fig_num, \n title = 'Model Categorical Accuracy', \n metric = 'categorical_accuracy', \n axis_labels = ['train', 'validation'], \n history_labels = ['Categorical Accuracy', 'Epoch'], \n extender = 'categoriacal_epoch_plot')\n fig_num += 1\n\n if 'lr' in self._history_keys:\n self.LearningPlot( fig_num = fig_num,\n title = 'Model Learning Rate')\n fig_num += 1\n\n except Exception as ex:\n template = \"An exception of type {0} occurred in [HistoryPlotter.OldPlotHistory]. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print(message)\n \n def AccOrLossPlot(self, fig_num:int, title:str, metric:str, axis_labels:list = ['train', 'validation'], history_labels:list = ['Metric', 'Epoch'], extender:str = '_epoch_plot', train_val_lists:list = None):\n \"\"\"\n This method wrapp the plot creation for a single metric of the keras train history.\n :param fig_num:int: figure number\n :param title:str: figure title\n :param metric:str: desired metric\n :param axis_labels:list: axis labels \n :param history_labels:list: history labels\n :param extender:str: plot file name extender\n :param train_val_lists:list: a list containing the train and validation list of a defined metric\n \"\"\"\n try:\n figure = plt.figure(fig_num)\n plt.suptitle(title, fontsize=14, fontweight='bold')\n\n if metric == 'loss': plt.title(self.CalcResultLoss(history=self._history))\n else: plt.title(self.CalcResultAccuracy(history=self._history, metric=metric))\n\n if not self._new_style:\n plt.plot(self._history.history[metric], color='blue', label=axis_labels[0])\n plt.plot(self._history.history['val_' + metric], color='orange', label=axis_labels[1])\n else:\n if (train_val_lists != None) and (len(train_val_lists) == 2):\n for l in train_val_lists[0]: plt.plot(self._epochs, self._history.history[l], color='b', label='Training ' + metric + ' (' + str(format(self._history.history[l][-1],'.5f'))+')')\n for l in train_val_lists[1]: plt.plot(self._epochs, self._history.history[l], color='g', label='Validation ' + metric + ' (' + str(format(self._history.history[l][-1],'.5f'))+')')\n\n plt.ylabel(history_labels[0])\n plt.xlabel(history_labels[1])\n plt.legend(axis_labels, loc='lower right')\n if self._save_it: \n PlotSaver(self._model_description, figure).SavePyPlotToFile(extender=extender)\n else:\n plt.show()\n figure.clf()\n except Exception as ex:\n template = \"An exception of type {0} occurred in [HistoryPlotter.AccOrLossPlot]. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print(message)\n\n def LearningPlot(self, fig_num:int, title:str = 'Model Learning Rate', metric:str = 'lr', axis_labels:list = ['train', 'validation'], history_labels:list = ['Learning Rate', 'Epoch'], extender:str = 'learning_rate_epoch_plot'):\n \"\"\"\n This method plot a the single learning rate curve.\n :param fig_num:int: figure number\n :param title:str: figure title\n :param metric:str: desired metric\n :param axis_labels:list: axis labels \n :param history_labels:list: history labels\n :param extender:str: plot file name extender\n \"\"\"\n try:\n figure = plt.figure(fig_num)\n plt.suptitle(title, fontsize=14, fontweight='bold')\n plt.title(self.CalcResultLearnRate(history=self._history))\n\n if not self._new_style:\n plt.plot(self._history.history[metric], color='red', label='learning rate')\n else:\n for l in self._learning_rates: plt.plot(self._epochs, self._history.history[l], color='r', label='Learning Rate (' + str(format(self._history.history[l][-1],'.5f'))+')')\n \n\n plt.ylabel(history_labels[0])\n plt.xlabel(history_labels[1])\n plt.legend(axis_labels, loc='upper right')\n if self._save_it: \n PlotSaver(self._model_description, figure).SavePyPlotToFile(extender='learning_rate_epoch_plot')\n else:\n plt.show()\n figure.clf()\n except Exception as ex:\n template = \"An exception of type {0} occurred in [HistoryPlotter.LearningPlot]. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print(message)\n\n def CalcResultAccuracy(self, history, metric:str = 'acc'):\n \"\"\"\n This method show the train acc results.\n :param history: history of the training\n \"\"\" \n try:\n return \"Training accuracy: %.2f%% / Validation accuracy: %.2f%%\" % (100*history.history[metric][-1], 100*history.history['val_'+metric][-1])\n except Exception as ex:\n template = \"An exception of type {0} occurred in [HistoryPlotter.CalcResultAccuracy]. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print(message)\n\n def CalcResultLoss(self, history):\n \"\"\"\n This method show the train loss results.\n :param history: history of the training\n \"\"\" \n try:\n return 'Training loss: '+ str(history.history['loss'][-1])[:-6] +' / Validation loss: ' + str(history.history['val_loss'][-1])[:-6]\n except Exception as ex:\n template = \"An exception of type {0} occurred in [HistoryPlotter.CalcResultLoss]. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print(message)\n\n def CalcResultLearnRate(self, history):\n \"\"\"\n This method show the train learn rate.\n :param history: history of the training\n \"\"\" \n try:\n return 'Training Learn Rate: '+ str(history.history['lr'][-1])\n except Exception as ex:\n template = \"An exception of type {0} occurred in [HistoryPlotter.CalcResultLearnRate]. Arguments:\\n{1!r}\"\n message = template.format(type(ex).__name__, ex.args)\n print(message)\n\n" ]
[ [ "matplotlib.pyplot.xlabel", "matplotlib.pyplot.suptitle", "matplotlib.pyplot.legend", "matplotlib.pyplot.plot", "matplotlib.pyplot.figure", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.show" ] ]
openclimatefix/predict_pv_yield_nwp
[ "10229c6976eb63075efb6777103596e4097dced2" ]
[ "predict_pv_yield_nwp/pv.py" ]
[ "# Read PV metadata and timeseries data\n\n# Based on code in https://github.com/openclimatefix/pvoutput\n# E.g. https://nbviewer.jupyter.org/github/openclimatefix/pvoutput/blob/master/examples/analyse_PV_data_for_9th_Aug_2019.ipynb\n\nimport cartopy.crs as ccrs\nimport numpy as np\nimport pandas as pd\n\nimport xarray as xr\n\nMETADATA_FILENAME = \"data/PV/PVOutput.org/UK_PV_metadata.csv\"\nPV_STATS_FILENAME = \"data/PV/PVOutput.org/UK_PV_stats.csv\"\nTIMESERIES_FILENAME = \"data/PV/PVOutput.org/UK_PV_timeseries_batch.nc\"\n\nSTART_DATE = \"2019-08-09\"\nEND_DATE = \"2019-08-09\"\n\n\ndef load_pv_systems(\n metadata_filename: str = METADATA_FILENAME,\n stats_filename: str = PV_STATS_FILENAME,\n timeseries_filename: str = TIMESERIES_FILENAME,\n) -> xr.Dataset:\n \"\"\"Load metadata about PV systems\"\"\"\n\n # Load metadata\n pv_metadata = pd.read_csv(metadata_filename, index_col=\"system_id\")\n\n # Load stats\n pv_stats = pd.read_csv(\n stats_filename,\n index_col=\"system_id\",\n parse_dates=[\"actual_date_from\", \"actual_date_to\", \"record_efficiency_date\"],\n )\n\n # Join\n pv_systems = pv_metadata.join(\n pv_stats[[\"actual_date_from\", \"actual_date_to\", \"outputs\"]], how=\"left\"\n )\n\n # Filter out systems with only a few outputs, and with no location\n pv_systems_filtered = pv_systems.query(\n \"status_interval_minutes <= 60 and outputs > 100\"\n )\n pv_systems_filtered = pv_systems_filtered.dropna(subset=[\"latitude\", \"longitude\"])\n\n # Restrict to systems that have timeseries data\n system_ids = _get_system_ids_dataframe_from_timeseries(timeseries_filename)\n pv_systems_filtered = pv_systems_filtered.join(system_ids, how=\"inner\")\n\n # Retain salient columns\n pv_systems_filtered = pv_systems_filtered[[\"system_name\", \"latitude\", \"longitude\"]]\n\n # Convert to xarray\n ds = xr.Dataset.from_dataframe(pv_systems_filtered)\n\n # Convert latitude/longitude to easting/northing\n ds = _transform_pv_systems(ds)\n\n return ds\n\n\ndef _get_system_ids_dataframe_from_timeseries(\n timeseries_filename: str = TIMESERIES_FILENAME,\n) -> pd.DataFrame:\n \"\"\"Get all the PV system IDs from the timeseries file\"\"\"\n ds = xr.open_dataset(timeseries_filename)\n system_ids = [int(x) for x in list(ds.data_vars.keys())]\n df = pd.DataFrame({\"system_id\": system_ids})\n df = df.set_index(\"system_id\")\n return df\n\n\ndef _transform_pv_systems(pv_systems: xr.Dataset) -> xr.Dataset:\n \"\"\"Transform the system locations into the same coordinate system used by UKV\"\"\"\n\n system_latitudes, system_longitudes = (\n pv_systems[\"latitude\"].values,\n pv_systems[\"longitude\"].values,\n )\n\n wgs84 = ccrs.Geodetic()\n ukv_crs = ccrs.OSGB(approx=False)\n locs = ukv_crs.transform_points(\n src_crs=wgs84,\n x=np.asanyarray(system_longitudes),\n y=np.asanyarray(system_latitudes),\n )[:, :-1]\n\n new_coords = {\n \"easting\": ([\"system_id\"], locs[:, 0].astype(\"int32\")),\n \"northing\": ([\"system_id\"], locs[:, 1].astype(\"int32\")),\n }\n return pv_systems.assign_coords(new_coords)\n\n\n# This is unused, but a useful check\ndef _transform_pv_systems_pyproj(pv_systems: xr.Dataset) -> xr.Dataset:\n \"\"\"Transform the system locations into the same coordinate system used by UKV, using pyproj\"\"\"\n import pyproj\n\n system_latitudes, system_longitudes = (\n pv_systems[\"latitude\"].values,\n pv_systems[\"longitude\"].values,\n )\n\n transformer = pyproj.Transformer.from_crs(\"epsg:4326\", \"epsg:27700\", always_xy=True)\n locs = transformer.transform(\n np.asanyarray(system_longitudes), np.asanyarray(system_latitudes)\n )\n print(locs)\n\n new_coords = {\n \"easting\": ([\"system_id\"], locs[0]),\n \"northing\": ([\"system_id\"], locs[1]),\n }\n return pv_systems.assign_coords(new_coords)\n\n\ndef load_pv_timeseries(\n start_date: str,\n end_date: str,\n metadata_filename: str = METADATA_FILENAME,\n stats_filename: str = PV_STATS_FILENAME,\n timeseries_filename: str = TIMESERIES_FILENAME,\n) -> xr.Dataset:\n \"\"\"Load the PV timeseries as an xarray dataset, restricted to a given time range, and including location metadata.\"\"\"\n\n ds = xr.open_dataset(timeseries_filename)\n\n # Subset to given time range\n subset = ds.sel(datetime=slice(start_date, end_date))\n\n # Drop systems with no readings during this time\n # I couldn't see how to do this with xarray, see https://stackoverflow.com/questions/52553925/python-xarray-remove-coordinates-with-all-missing-variables\n df = subset.to_dataframe()\n df = df.dropna(axis=1, how=\"all\")\n\n # Restrict to systems that are in the intersection of those in PV metadata and PV timeseries\n pv_df = load_pv_systems(\n metadata_filename, stats_filename, timeseries_filename\n ).to_dataframe()\n pv_metadata_system_ids = pv_df.index.tolist() # indexed by system_id\n timeseries_system_ids = [int(system_id) for system_id in df.columns.tolist()]\n system_ids = list(\n set(pv_metadata_system_ids).intersection(set(timeseries_system_ids))\n )\n system_id_columns = [str(system_id) for system_id in system_ids]\n df = df[system_id_columns]\n\n # Reshape table into tall and narrow form - this avoids one data variable per system in xarray\n df[\"datetime\"] = df.index\n df = pd.melt(df, id_vars=[\"datetime\"], var_name=\"system_id\", value_name=\"pv_yield\")\n df = df.astype({\"system_id\": \"int64\"})\n df = df.set_index([\"system_id\", \"datetime\"])\n\n # Convert back to xarray\n ds = xr.Dataset.from_dataframe(df)\n\n # Add lat/long and easting/northing coordinates by doing a pandas lookup for each system\n new_coords = {\n \"latitude\": (\n [\"system_id\"],\n pv_df.lookup(system_ids, [\"latitude\"] * len(system_ids)),\n ),\n \"longitude\": (\n [\"system_id\"],\n pv_df.lookup(system_ids, [\"longitude\"] * len(system_ids)),\n ),\n \"easting\": (\n [\"system_id\"],\n pv_df.lookup(system_ids, [\"easting\"] * len(system_ids)),\n ),\n \"northing\": (\n [\"system_id\"],\n pv_df.lookup(system_ids, [\"northing\"] * len(system_ids)),\n ),\n }\n ds = ds.assign_coords(new_coords)\n\n return ds\n\n\nif __name__ == \"__main__\":\n pv_timeseries = load_pv_timeseries(START_DATE, END_DATE)\n print(pv_timeseries)\n\n pv_timeseries.to_netcdf(\"data/tmp/pv_timeseries.nc\")\n" ]
[ [ "pandas.DataFrame", "pandas.read_csv", "numpy.asanyarray", "pandas.melt" ] ]
dlkt-review-and-empirical-evaluation/dlkt-review-and-empirical-evaluation
[ "d1540513056190ab0fbf547d22257dda2dfcd323" ]
[ "scripts/extract_best_kfold_results.py" ]
[ "import argparse\nimport pandas as pd\nimport re\n\nass15 = 'assist15', 'ASSISTments 2015'\nass17 = 'assist17', 'ASSISTments 2017'\nprog19 = 'prog19', 'Programming 2019'\nsynth_k2 = 'synth-k2', 'Synthetic-K2'\nsynth_k5 = 'synth-k5', 'Synthetic-K5'\nass09up = 'assist09up', 'ASSISTments 2009 Updated'\nstat = 'stat', 'Statics'\nintro_prog = 'intro-prog', 'IntroProg'\n\n\ndef sl_dict(a, b):\n return {'short': a, 'long': b}\n\n\ndataset_tups = ass15, ass17, prog19, synth_k2, synth_k5, ass09up, stat, intro_prog\ndatasets = {**{s: sl_dict(s, l) for s, l in dataset_tups}, **{l: sl_dict(s, l) for s, l in dataset_tups}}\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Yay, I\\'m a description!',\n formatter_class=argparse.RawTextHelpFormatter)\n parser.add_argument('kfold_results_filename')\n\n parser.add_argument('--min', action='store_true')\n parser.add_argument('--metric',\n default='auc',\n choices={'acc', 'auc', 'prec', 'recall', 'f1', 'mcc', 'rmse', 'aic', 'aicc', 'bic'})\n args = parser.parse_args()\n\n kfold_results = pd.read_csv(args.kfold_results_filename, encoding='latin')\n kfold_results.dataset = kfold_results.dataset.apply(lambda x: datasets[x]['long'])\n kfold_results.dataset = kfold_results.dataset.apply(lambda x: datasets[x]['long'] if x in datasets else x)\n\n max_filter_col = f'{args.metric}-sd'\n kfold_results[max_filter_col] = kfold_results[args.metric].apply(lambda x: float(re.split(r'[^0-9.]', x)[0]))\n\n kfold_max_results = kfold_results.loc[kfold_results.groupby(['dataset', 'model'])[max_filter_col].idxmax()] \\\n if not args.min \\\n else kfold_results.loc[kfold_results.groupby(['dataset', 'model'])[max_filter_col].idxmin()]\n\n best = 'min' if args.metric in ('rmse', 'aic', 'aicc', 'bic') else 'max'\n if 'fold-results' in args.kfold_results_filename:\n output_filename = args.kfold_results_filename.replace(\"-results\", f\"-{best}-{args.metric}-results\")\n else:\n output_filename = f'kfold-results-{best}-{args.metric}-results.csv'\n\n print(f'wrote {output_filename}')\n kfold_max_results = kfold_max_results.drop([max_filter_col], axis=1).sort_values(\n by=['dataset', args.metric], ascending=False)\n kfold_max_results.to_csv(output_filename, index=False)\n" ]
[ [ "pandas.read_csv" ] ]
emmmoore/vaccinesandcases
[ "74635333edb2569158668e3cc3ef3cbe1b41d88b" ]
[ ".scripts/dataprep.py" ]
[ "#!/usr/bin/env python\n# coding: utf-8\n\n# # Exploring JHU COVID Case, Death, and Vaccine Information\n# This notebook takes the live, updated data from JHU CSSE and GovEx, formats and simplifies it for my purposes, and saves it in csv files in the same directory. The two data sources use slightly different conventions and provide data for slightly different locations, so I standardized column names and kept only those rows common to both datasets. It makes most sense for this to be run once, so that the same data is used every time. In the future, it could be worthwhile to make the processes in this project run on 'live' data, but not for the purposes of this project at this time.\n# \n# #### Data Sources\n# * [Case Data - JHU CSSE](https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv)\n# * [Vaccine Data - JHU GovEx](https://raw.githubusercontent.com/govex/COVID-19/master/data_tables/vaccine_data/global_data/time_series_covid19_vaccine_doses_admin_global.csv)\n# \n# #### Technical Sources\n# * [Pandas Documentation](https://pandas.pydata.org/docs/)\n# * [MatPlotLib.PyPlot Documentation](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.html)\n# * [Standardizing Dates with `datetime.datetime` - Stack Overflow](https://stackoverflow.com/questions/4709652/python-regex-to-match-dates)\n# * [Getting Only Date in `datetime.datetime`](https://stackoverflow.com/questions/18039680/django-get-only-date-from-datetime-strptime)\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport sklearn\nimport seaborn as sns\nimport sys\n\n\n# ## Case Info\n\n# In[2]:\n\n\ncase_data = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv')\nprint(case_data.shape)\ncase_data.head()\n\n\n# \n\n# In[3]:\n\n\nplt.scatter(case_data['3/23/20'], case_data['3/23/21'])\nplt.xlim([0, 2000])\nplt.ylim([0, 10000])\nplt.title('Relations in COVID Case Count Over One Year in Different Countries')\nplt.xlabel('Cases on 3/23/2020')\nplt.ylabel('Cases on 3/23/2021')\nplt.plot(range(2000))\n\n\n# The above plot is pretty useless in terms of correlation since we know (logically) that total case numbers can only increase. However, it provides a good example of the extremity of difference in scale of typical case numbers (within the range plotted) between early 2020 and early 2021. I also used it just to make sure there wouldn't be any obvious weird things with the data.\n# \n# The below table indicates mean case count for each day listed. The drastic change is obvious.\n\n# In[4]:\n\n\ncase_data.mean(numeric_only=True)\n\n\n# ## Vaccine Info\n\n# In[5]:\n\n\nvaccine_data = pd.read_csv('https://raw.githubusercontent.com/govex/COVID-19/master/data_tables/vaccine_data/global_data/time_series_covid19_vaccine_doses_admin_global.csv')\nprint(vaccine_data.shape)\nvaccine_data.head()\n\n\n# ## Standardizing Case and Vaccine Info\n\n# The first step is to standardize columns by deleting unnecessary ones and establishing common naming conventions between the two files to minimize mistakes when referring to them:\n\n# In[6]:\n\n\n# Rename geographic columns in vaccine data to standardize\nrename_conventions = {'Province_State': 'Province/State', 'Country_Region': 'Country', 'Country/Region': 'Country'}\ncase_data.rename(columns=rename_conventions, inplace=True)\nvaccine_data.rename(columns=rename_conventions, inplace=True)\n\n# Standardize dates \nimport datetime\ndef date_fixer(old_date):\n data_type = ''\n is_date = False\n if len(old_date) == 10 and old_date[4] == '-': # is of format YYYY-MM-DD\n date = datetime.datetime.strptime(old_date,'%Y-%m-%d').date()\n data_type = 'Vaccinations'\n is_date = True\n elif len(old_date) >= 6 and old_date[2] == '/' or old_date[1] == '/': # is of format (M)M/(D)D/YY\n date = datetime.datetime.strptime(old_date, '%m/%d/%y').date()\n data_type = 'Cases'\n is_date = True\n return str('{}/{}/{} {}'.format(date.month, date.day, date.year, data_type)) if is_date else old_date + data_type\n\nvaccine_data.rename(columns=date_fixer, inplace=True)\ncase_data.rename(columns=date_fixer, inplace=True)\n\n\n# Next, I deleted the columns that weren't dates or Country/Region and State/Province. I may later want to use population, but not yet.\n\n# In[7]:\n\n\ncase_data.drop(columns=['Lat', 'Long', 'Province/State'], inplace=True)\nvaccine_data.drop(columns=['UID', 'iso2', 'iso3', 'code3', 'FIPS', 'Admin2', 'Lat', 'Long_', 'Combined_Key', 'Population', 'Province/State'], inplace=True)\n\n\n# Next, I sorted the data, filled in null values with 0, combined rows from the same country, and merged the dataframes.\n\n# In[8]:\n\n\ncase_data.sort_values(by='Country', inplace=True)\nvaccine_data.sort_values(by='Country', inplace=True)\nvaccine_data.fillna(0.0, inplace=True)\ncase_data.fillna(0, inplace=True)\ncase_data = case_data.groupby(['Country']).sum()\nvaccine_data = vaccine_data.groupby(['Country']).sum()\ncase_data.to_csv('case-data.csv')\nvaccine_data.to_csv('vaccine-data.csv')\nfull_data = pd.merge(case_data, vaccine_data, how='inner', on='Country')\nprint('case data size:', case_data.shape, 'vaccine data size:', vaccine_data.shape, 'full data size:', full_data.shape)\n\n\n# The next step was to look at all the country names, so I can manually see if I want to get rid of any. I decided to keep them all, at least for now.\n\n# In[9]:\n\n\npd.set_option('display.max_seq_items', None)\nfull_data.index\n\n\n# Finally, I saved the data into a csv file which can be referenced later. The below cell should really be run once only, so that the same data is used each time. One way to update this project could be to reload the data automatically.\n\n# In[10]:\n\n\nfull_data.to_csv('full-data.csv')\n\n" ]
[ [ "matplotlib.pyplot.xlim", "pandas.merge", "pandas.set_option", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.ylim", "matplotlib.pyplot.title", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.scatter", "pandas.read_csv" ] ]
wgorczyk/LoopStructural
[ "bedc7abd4c1868fdbd6ed659c8d72ef19f793875" ]
[ "LoopStructural/probability/_gradient_calculator.py" ]
[ "import numpy as np\n\nfrom LoopStructural.utils import getLogger\nlogger = getLogger(__name__)\n\ndef gradients(vals, func, releps=1e-3, abseps=None, mineps=1e-9, reltol=1,\n epsscale=0.5):\n \"\"\"\n Calculate the partial derivatives of a function at a set of values. The\n derivatives are calculated using the central difference, using an iterative\n method to check that the values converge as step size decreases.\n\n Parameters\n ----------\n vals: array_like\n A set of values, that are passed to a function, at which to calculate\n the gradient of that function\n func:\n A function that takes in an array of values.\n releps: float, array_like, 1e-3\n The initial relative step size for calculating the derivative.\n abseps: float, array_like, None\n The initial absolute step size for calculating the derivative.\n This overrides `releps` if set.\n `releps` is set then that is used.\n mineps: float, 1e-9\n The minimum relative step size at which to stop iterations if no\n convergence is achieved.\n epsscale: float, 0.5\n The factor by which releps if scaled in each iteration.\n\n Returns\n -------\n grads: array_like\n An array of gradients for each non-fixed value.\n \"\"\"\n\n grads = np.zeros(len(vals))\n\n # maximum number of times the gradient can change sign\n flipflopmax = 10.\n\n # set steps\n if abseps is None:\n if isinstance(releps, float):\n eps = np.abs(vals) * releps\n eps[eps == 0.] = releps # if any values are zero set eps to releps\n teps = releps * np.ones(len(vals))\n elif isinstance(releps, (list, np.ndarray)):\n if len(releps) != len(vals):\n raise ValueError(\"Problem with input relative step sizes\")\n eps = np.multiply(np.abs(vals), releps)\n eps[eps == 0.] = np.array(releps)[eps == 0.]\n teps = releps\n else:\n raise RuntimeError(\"Relative step sizes are not a recognised type!\")\n else:\n if isinstance(abseps, float):\n eps = abseps * np.ones(len(vals))\n elif isinstance(abseps, (list, np.ndarray)):\n if len(abseps) != len(vals):\n raise ValueError(\"Problem with input absolute step sizes\")\n eps = np.array(abseps)\n else:\n raise RuntimeError(\"Absolute step sizes are not a recognised type!\")\n teps = eps\n\n # for each value in vals calculate the gradient\n count = 0\n for i in range(len(vals)):\n # initial parameter diffs\n leps = eps[i]\n cureps = teps[i]\n\n flipflop = 0\n\n # get central finite difference\n fvals = np.copy(vals)\n bvals = np.copy(vals)\n\n # central difference\n fvals[i] += 0.5 * leps # change forwards distance to half eps\n bvals[i] -= 0.5 * leps # change backwards distance to half eps\n cdiff = (func(fvals) - func(bvals)) / leps\n\n while 1:\n fvals[i] -= 0.5 * leps # remove old step\n bvals[i] += 0.5 * leps\n\n # change the difference by a factor of two\n cureps *= epsscale\n if cureps < mineps or flipflop > flipflopmax:\n # if no convergence set flat derivative (TODO: check if there is a better thing to do instead)\n logger.warn(\"Derivative calculation did not converge: setting flat derivative.\")\n grads[count] = 0.\n break\n leps *= epsscale\n\n # central difference\n fvals[i] += 0.5 * leps # change forwards distance to half eps\n bvals[i] -= 0.5 * leps # change backwards distance to half eps\n cdiffnew = (func(fvals) - func(bvals)) / leps\n\n if cdiffnew == cdiff:\n grads[count] = cdiff\n break\n\n # check whether previous diff and current diff are the same within reltol\n rat = (cdiff / cdiffnew)\n if np.isfinite(rat) and rat > 0.:\n # gradient has not changed sign\n if np.abs(1. - rat) < reltol:\n grads[count] = cdiffnew\n break\n else:\n cdiff = cdiffnew\n continue\n else:\n cdiff = cdiffnew\n flipflop += 1\n continue\n\n count += 1\n\n return grads" ]
[ [ "numpy.array", "numpy.copy", "numpy.isfinite", "numpy.abs" ] ]
DSSerialGeneva/cd15c0un7
[ "93bc45854c5c58802c5ec69613a9253b7f927cb9" ]
[ "src/read/read_train_example.py" ]
[ "import numpy\nimport os\n\nfrom src.readers import SimpleBSONReader\n\n\ndef read_train_example(path='../../data/train_example.bson', pca_reduction=True):\n read_result = SimpleBSONReader.read_all(path)\n pixels = read_result.pixel_matrix\n numpy.savetxt(\"../../out/train_example.csv\", pixels, delimiter=\",\", fmt='%.d')\n if pca_reduction:\n pixel_reduced = read_result.pixel_matrix_reduced\n numpy.savetxt(\"../../out/pca_train_example.csv\", pixel_reduced, delimiter=\",\", fmt='%.d')\n return pixels\n\n\ndef read_and_save_intermediate(path='../../data/train_example.bson', pca_reduction=True,\n file_out_path=\"../../out/train_example.csv\",\n reduced_file_out_path=\"../../out/pca_train_example.csv\", root_path=\"../../out/\",\n n_components=90, first_occurence_number=1):\n\n dirname = os.path.dirname(file_out_path)\n if not os.path.exists(dirname):\n os.mkdir(dirname)\n\n read_result = SimpleBSONReader.read_all(\n path,\n save_intermediate=True,\n save_png=True,\n root_path=root_path,\n first_occurence_number=first_occurence_number,\n n_components=n_components)\n pixels = read_result.pixel_matrix\n numpy.savetxt(file_out_path, pixels, delimiter=\",\", fmt='%.d')\n if pca_reduction:\n dirname = os.path.dirname(reduced_file_out_path)\n if not os.path.exists(dirname):\n os.mkdir(dirname)\n pixel_reduced = read_result.pixel_matrix_reduced\n numpy.savetxt(reduced_file_out_path, pixel_reduced, delimiter=\",\", fmt='%s')\n return pixels\n\n\nif __name__ == \"__main__\":\n read_and_save_intermediate()\n" ]
[ [ "numpy.savetxt" ] ]
GJBoth/MultiTaskPINN
[ "8a9bb23b8bfc0d0f678090e015316dbd0cfbf024", "8a9bb23b8bfc0d0f678090e015316dbd0cfbf024" ]
[ "src/multitaskpinn/training/.ipynb_checkpoints/training-checkpoint.py", "src/multitaskpinn/training/training.py" ]
[ "import torch\nimport time\nfrom math import pi\nimport numpy as np\n\nfrom ..utils.tensorboard import Tensorboard\nfrom ..utils.output import progress\nfrom .convergence import Convergence\nfrom ..model.deepmod import DeepMoD\nfrom typing import Optional\n\n\ndef train(model: DeepMoD,\n data: torch.Tensor,\n target: torch.Tensor,\n optimizer,\n sparsity_scheduler,\n log_dir: Optional[str] = None,\n max_iterations: int = 10000,\n write_iterations: int = 25,\n **convergence_kwargs) -> None:\n \"\"\"[summary]\n\n Args:\n model (DeepMoD): [description]\n data (torch.Tensor): [description]\n target (torch.Tensor): [description]\n optimizer ([type]): [description]\n sparsity_scheduler ([type]): [description]\n log_dir (Optional[str], optional): [description]. Defaults to None.\n max_iterations (int, optional): [description]. Defaults to 10000.\n \"\"\"\n start_time = time.time()\n board = Tensorboard(log_dir) # initializing tb board\n\n # Training\n convergence = Convergence(**convergence_kwargs)\n print('| Iteration | Progress | Time remaining | Loss | MSE | Reg | L1 norm |')\n for iteration in np.arange(0, max_iterations + 1):\n # ================== Training Model ============================\n prediction, time_derivs, thetas = model(data)\n\n MSE = torch.mean((prediction - target)**2, dim=0) # loss per output\n Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2)\n for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))])\n loss = torch.sum(MSE + Reg) # 1e-5 for numerical stability\n\n # Optimizer step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # ====================== Logging =======================\n # We calculate the normalization factor and the l1_norm\n l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0)\n\n # Write progress to command line and tensorboard\n if iteration % write_iterations == 0:\n _ = model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs but not setting mask\n progress(iteration, start_time, max_iterations, loss.item(),\n torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item())\n\n if model.estimator_coeffs() is None:\n estimator_coeff_vectors = [torch.zeros_like(coeff) for coeff in model.constraint_coeffs(sparse=True, scaled=False)] # It doesnt exist before we start sparsity, so we use zeros\n else:\n estimator_coeff_vectors = model.estimator_coeffs()\n\n board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors)\n \n # ================== Validation and sparsity =============\n # Updating sparsity and or convergence\n sparsity_scheduler(iteration, torch.sum(l1_norm))\n if sparsity_scheduler.apply_sparsity is True:\n with torch.no_grad():\n model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs)\n sparsity_scheduler.reset()\n print(model.sparsity_masks)\n\n # Checking convergence\n convergence(iteration, torch.sum(l1_norm))\n if convergence.converged is True:\n print('Algorithm converged. Stopping training.')\n break\n board.close()\n\n\ndef train_auto_split(model: DeepMoD,\n data: torch.Tensor,\n target: torch.Tensor,\n optimizer,\n sparsity_scheduler,\n split: float = 0.8,\n log_dir: Optional[str] = None,\n max_iterations: int = 10000,\n write_iterations: int = 25,\n **convergence_kwargs) -> None:\n \"\"\"[summary]\n\n Args:\n model (DeepMoD): [description]\n data (torch.Tensor): [description]\n target (torch.Tensor): [description]\n optimizer ([type]): [description]\n sparsity_scheduler ([type]): [description]\n log_dir (Optional[str], optional): [description]. Defaults to None.\n max_iterations (int, optional): [description]. Defaults to 10000.\n \"\"\"\n start_time = time.time()\n board = Tensorboard(log_dir) # initializing tb board\n\n # Splitting data, assumes data is already randomized\n n_train = int(split * data.shape[0])\n n_test = data.shape[0] - n_train\n data_train, data_test = torch.split(data, [n_train, n_test], dim=0)\n target_train, target_test = torch.split(target, [n_train, n_test], dim=0)\n \n # Training\n convergence = Convergence(**convergence_kwargs)\n print('| Iteration | Progress | Time remaining | Loss | MSE | Reg | L1 norm |')\n for iteration in np.arange(0, max_iterations + 1):\n # ================== Training Model ============================\n prediction, time_derivs, thetas = model(data_train)\n\n MSE = torch.mean((prediction - target_train)**2, dim=0) # loss per output\n Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2)\n for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))])\n loss = torch.sum(MSE + Reg) \n\n # Optimizer step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # ====================== Logging =======================\n # We calculate the normalization factor and the l1_norm\n l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0)\n \n # Validation loss\n with torch.no_grad():\n prediction_test = model.func_approx(data_test)[0]\n MSE_test = torch.mean((prediction_test - target_test)**2, dim=0) # loss per output\n # Write progress to command line and tensorboard\n if iteration % write_iterations == 0:\n _ = model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs but not setting mask\n estimator_coeff_vectors = model.estimator_coeffs()\n\n progress(iteration, start_time, max_iterations, loss.item(),\n torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item())\n board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test)\n \n # ================== Validation and sparsity =============\n # Updating sparsity and or convergence\n sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer)\n #sparsity_scheduler(torch.sum(MSE_test), model, optimizer)\n if sparsity_scheduler.apply_sparsity is True:\n with torch.no_grad():\n model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs)\n sparsity_scheduler.reset()\n print(model.sparsity_masks)\n \n\n # Checking convergence\n convergence(iteration, torch.sum(l1_norm))\n if convergence.converged is True:\n print('Algorithm converged. Stopping training.')\n break\n board.close()\n\n \n\n \ndef train_auto_split_scaled(model: DeepMoD,\n data: torch.Tensor,\n target: torch.Tensor,\n optimizer,\n sparsity_scheduler,\n split: float = 0.8,\n log_dir: Optional[str] = None,\n max_iterations: int = 10000,\n write_iterations: int = 25,\n **convergence_kwargs) -> None:\n \"\"\"[summary]\n\n Args:\n model (DeepMoD): [description]\n data (torch.Tensor): [description]\n target (torch.Tensor): [description]\n optimizer ([type]): [description]\n sparsity_scheduler ([type]): [description]\n log_dir (Optional[str], optional): [description]. Defaults to None.\n max_iterations (int, optional): [description]. Defaults to 10000.\n \"\"\"\n start_time = time.time()\n board = Tensorboard(log_dir) # initializing tb board\n\n # Splitting data, assumes data is already randomized\n n_train = int(split * data.shape[0])\n n_test = data.shape[0] - n_train\n data_train, data_test = torch.split(data, [n_train, n_test], dim=0)\n target_train, target_test = torch.split(target, [n_train, n_test], dim=0)\n \n # Training\n convergence = Convergence(**convergence_kwargs)\n print('| Iteration | Progress | Time remaining | Loss | MSE | Reg | L1 norm |')\n for iteration in np.arange(0, max_iterations + 1):\n # ================== Training Model ============================\n prediction, time_derivs, thetas = model(data_train)\n\n MSE = torch.mean((prediction - target_train)**2, dim=0) # loss per output\n \n theta_norms = [torch.norm(theta, dim=0) for theta in thetas]\n time_deriv_norms = [torch.norm(dt, dim=0) for dt in time_derivs]\n normed_thetas = [theta / norm for theta, norm in zip(thetas, theta_norms)]\n normed_time_derivs = [dt / norm for dt, norm in zip(time_derivs, time_deriv_norms)]\n\n Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2)\n for dt, theta, coeff_vector in zip(normed_time_derivs, normed_thetas, model.constraint_coeffs(scaled=True, sparse=True))])\n loss = torch.sum(MSE + Reg) # 1e-5 for numerical stability\n\n # Optimizer step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # ====================== Logging =======================\n # We calculate the normalization factor and the l1_norm\n l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0)\n \n\n # Validation loss\n prediction_test, coordinates = model.func_approx(data_test)\n time_derivs_test, thetas_test = model.library((prediction_test, coordinates))\n MSE_test = torch.mean((prediction_test - target_test)**2, dim=0) # loss per output\n Reg_test = torch.stack([torch.mean((dt - theta @ coeff_vector)**2)\n for dt, theta, coeff_vector in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))])\n loss_test = torch.sum(MSE_test + Reg_test) \n\n # Write progress to command line and tensorboard\n if iteration % write_iterations == 0:\n _ = model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs but not setting mask\n estimator_coeff_vectors = model.estimator_coeffs()\n\n progress(iteration, start_time, max_iterations, loss.item(),\n torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item())\n board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test)\n \n # ================== Validation and sparsity =============\n # Updating sparsity and or convergence\n sparsity_scheduler(loss_test, model, optimizer)\n #sparsity_scheduler(torch.sum(MSE_test), model, optimizer)\n if sparsity_scheduler.apply_sparsity is True:\n with torch.no_grad():\n checkpoint = torch.load(sparsity_scheduler.path)\n model.load_state_dict(checkpoint['model_state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n\n model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs)\n sparsity_scheduler.reset()\n print(model.sparsity_masks)\n\n # Checking convergence\n convergence(iteration, torch.sum(l1_norm))\n if convergence.converged is True:\n print('Algorithm converged. Stopping training.')\n break\n board.close()\n\n\ndef train_auto_split_MSE(model: DeepMoD,\n data: torch.Tensor,\n target: torch.Tensor,\n optimizer,\n sparsity_scheduler,\n split: float = 0.8,\n log_dir: Optional[str] = None,\n max_iterations: int = 10000,\n write_iterations: int = 25,\n **convergence_kwargs) -> None:\n \"\"\"[summary]\n\n Args:\n model (DeepMoD): [description]\n data (torch.Tensor): [description]\n target (torch.Tensor): [description]\n optimizer ([type]): [description]\n sparsity_scheduler ([type]): [description]\n log_dir (Optional[str], optional): [description]. Defaults to None.\n max_iterations (int, optional): [description]. Defaults to 10000.\n \"\"\"\n start_time = time.time()\n board = Tensorboard(log_dir) # initializing tb board\n\n # Training\n convergence = Convergence(**convergence_kwargs)\n print('| Iteration | Progress | Time remaining | Loss | MSE | Reg | L1 norm |')\n for iteration in np.arange(0, max_iterations + 1):\n # ================== Training Model ============================\n prediction, time_derivs, thetas = model(data)\n\n MSE = torch.mean((prediction - target)**2, dim=0) # loss per output\n #Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2)\n # for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))])\n loss = torch.sum(MSE) # 1e-5 for numerical stability\n\n # Optimizer step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # ====================== Logging =======================\n with torch.no_grad():\n # We calculate the normalization factor and the l1_norm\n l1_norm = torch.sum(torch.abs(torch.cat(model.constraint.coeff_vectors, dim=1)), dim=0)\n # Validation loss\n prediction_test = model.func_approx(data)[0]\n MSE_test = torch.mean((prediction_test - target)**2, dim=0) # loss per output\n # Write progress to command line and tensorboard\n if iteration % write_iterations == 0:\n _ = model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs but not setting mask\n estimator_coeff_vectors = model.estimator_coeffs()\n\n progress(iteration, start_time, max_iterations, loss.item(),\n torch.sum(MSE).item(), torch.sum(MSE).item(), torch.sum(l1_norm).item())\n board.write(iteration, loss, MSE, MSE, l1_norm, model.constraint.coeff_vectors, model.constraint.coeff_vectors, estimator_coeff_vectors, MSE_test=MSE_test)\n \n # ================== Validation and sparsity =============\n # Updating sparsity and or convergence\n sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer)\n if sparsity_scheduler.apply_sparsity is True:\n with torch.no_grad():\n model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs)\n sparsity_scheduler.reset()\n print(model.sparsity_masks)\n\n # Checking convergence\n convergence(iteration, torch.sum(l1_norm))\n if convergence.converged is True:\n print('Algorithm converged. Stopping training.')\n break\n board.close()\n\n\ndef train_split_full(model: DeepMoD,\n data: torch.Tensor,\n target: torch.Tensor,\n optimizer,\n sparsity_scheduler,\n test = 'mse',\n split: float = 0.8,\n log_dir: Optional[str] = None,\n max_iterations: int = 10000,\n write_iterations: int = 25,\n **convergence_kwargs) -> None:\n \"\"\"[summary]\n\n Args:\n model (DeepMoD): [description]\n data (torch.Tensor): [description]\n target (torch.Tensor): [description]\n optimizer ([type]): [description]\n sparsity_scheduler ([type]): [description]\n log_dir (Optional[str], optional): [description]. Defaults to None.\n max_iterations (int, optional): [description]. Defaults to 10000.\n \"\"\"\n start_time = time.time()\n board = Tensorboard(log_dir) # initializing tb board\n\n # Splitting data, assumes data is already randomized\n n_train = int(split * data.shape[0])\n n_test = data.shape[0] - n_train\n data_train, data_test = torch.split(data, [n_train, n_test], dim=0)\n target_train, target_test = torch.split(target, [n_train, n_test], dim=0)\n \n # Training\n convergence = Convergence(**convergence_kwargs)\n print('| Iteration | Progress | Time remaining | Loss | MSE | Reg | L1 norm |')\n for iteration in np.arange(0, max_iterations + 1):\n # ================== Training Model ============================\n prediction, time_derivs, thetas = model(data_train)\n\n MSE = torch.mean((prediction - target_train)**2, dim=0) # loss per output\n Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2)\n for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))])\n loss = torch.sum(MSE + Reg) \n\n # Optimizer step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n \n if iteration % write_iterations == 0:\n # ================== Validation costs ================\n prediction_test, coordinates = model.func_approx(data_test)\n time_derivs_test, thetas_test = model.library((prediction_test, coordinates))\n with torch.no_grad():\n MSE_test = torch.mean((prediction_test - target_test)**2, dim=0) # loss per output\n Reg_test = torch.stack([torch.mean((dt - theta @ coeff_vector)**2)\n for dt, theta, coeff_vector in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))])\n loss_test = torch.sum(MSE_test + Reg_test) \n \n # ====================== Logging =======================\n _ = model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs but not setting mask\n estimator_coeff_vectors = model.estimator_coeffs()\n l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0)\n progress(iteration, start_time, max_iterations, loss.item(),\n torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item())\n board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test)\n \n # ================== Sparsity update =============\n # Updating sparsity and or convergence\n #sparsity_scheduler(iteration, l1_norm)\n if iteration % write_iterations == 0:\n if test == 'mse':\n sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer)\n else:\n sparsity_scheduler(iteration, loss_test, model, optimizer) \n \n if sparsity_scheduler.apply_sparsity is True:\n with torch.no_grad():\n model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs)\n sparsity_scheduler.reset()\n\n # ================= Checking convergence\n convergence(iteration, torch.sum(l1_norm))\n if convergence.converged is True:\n print('Algorithm converged. Stopping training.')\n break\n board.close()", "import torch\nimport time\nfrom math import pi\nimport numpy as np\nfrom os.path import join\n\nfrom ..utils.tensorboard import Tensorboard\nfrom ..utils.output import progress\nfrom .convergence import Convergence\nfrom ..model.deepmod import DeepMoD\nfrom typing import Optional\n\n\ndef train(model: DeepMoD,\n data: torch.Tensor,\n target: torch.Tensor,\n optimizer,\n sparsity_scheduler,\n test = 'mse',\n split: float = 0.8,\n log_dir: Optional[str] = None,\n max_iterations: int = 10000,\n write_iterations: int = 25,\n **convergence_kwargs) -> None:\n \"\"\"[summary]\n\n Args:\n model (DeepMoD): [description]\n data (torch.Tensor): [description]\n target (torch.Tensor): [description]\n optimizer ([type]): [description]\n sparsity_scheduler ([type]): [description]\n log_dir (Optional[str], optional): [description]. Defaults to None.\n max_iterations (int, optional): [description]. Defaults to 10000.\n \"\"\"\n start_time = time.time()\n board = Tensorboard(log_dir) # initializing tb board\n\n # Splitting data, assumes data is already randomized\n n_train = int(split * data.shape[0])\n n_test = data.shape[0] - n_train\n data_train, data_test = torch.split(data, [n_train, n_test], dim=0)\n target_train, target_test = torch.split(target, [n_train, n_test], dim=0)\n \n # Training\n convergence = Convergence(**convergence_kwargs)\n print('| Iteration | Progress | Time remaining | Loss | MSE | Reg | L1 norm |')\n for iteration in np.arange(0, max_iterations + 1):\n # ================== Training Model ============================\n prediction, time_derivs, thetas = model(data_train)\n\n MSE = torch.mean((prediction - target_train)**2, dim=0) # loss per output\n Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2)\n for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))])\n loss = torch.sum(MSE + Reg) \n\n # Optimizer step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n \n if iteration % write_iterations == 0:\n # ================== Validation costs ================\n prediction_test, coordinates = model.func_approx(data_test)\n time_derivs_test, thetas_test = model.library((prediction_test, coordinates))\n with torch.no_grad():\n MSE_test = torch.mean((prediction_test - target_test)**2, dim=0) # loss per output\n Reg_test = torch.stack([torch.mean((dt - theta @ coeff_vector)**2)\n for dt, theta, coeff_vector in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))])\n loss_test = torch.sum(MSE_test + Reg_test) \n \n # ====================== Logging =======================\n _ = model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs but not setting mask\n estimator_coeff_vectors = model.estimator_coeffs()\n l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0)\n progress(iteration, start_time, max_iterations, loss.item(),\n torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item())\n board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test)\n \n # ================== Sparsity update =============\n # Updating sparsity and or convergence\n #sparsity_scheduler(iteration, l1_norm)\n if iteration % write_iterations == 0:\n if test == 'mse':\n sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer)\n else:\n sparsity_scheduler(iteration, loss_test, model, optimizer) \n \n if sparsity_scheduler.apply_sparsity is True:\n with torch.no_grad():\n model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs)\n sparsity_scheduler.reset()\n\n # ================= Checking convergence\n convergence(iteration, torch.sum(l1_norm))\n if convergence.converged is True:\n print('Algorithm converged. Stopping training.')\n break\n board.close()\n if log_dir is None: \n path = 'model.pt'\n else:\n path = join(log_dir, 'model.pt')\n torch.save(model.state_dict(), path)\n\ndef train_multitask(model: DeepMoD,\n data: torch.Tensor,\n target: torch.Tensor,\n optimizer,\n sparsity_scheduler,\n test = 'mse',\n split: float = 0.8,\n log_dir: Optional[str] = None,\n max_iterations: int = 10000,\n write_iterations: int = 25,\n **convergence_kwargs) -> None:\n \"\"\"[summary]\n\n Args:\n model (DeepMoD): [description]\n data (torch.Tensor): [description]\n target (torch.Tensor): [description]\n optimizer ([type]): [description]\n sparsity_scheduler ([type]): [description]\n log_dir (Optional[str], optional): [description]. Defaults to None.\n max_iterations (int, optional): [description]. Defaults to 10000.\n \"\"\"\n start_time = time.time()\n board = Tensorboard(log_dir) # initializing tb board\n\n # Splitting data, assumes data is already randomized\n n_train = int(split * data.shape[0])\n n_test = data.shape[0] - n_train\n data_train, data_test = torch.split(data, [n_train, n_test], dim=0)\n target_train, target_test = torch.split(target, [n_train, n_test], dim=0)\n \n # Training\n convergence = Convergence(**convergence_kwargs)\n print('| Iteration | Progress | Time remaining | Loss | MSE | Reg | L1 norm |')\n for iteration in np.arange(0, max_iterations + 1):\n # ================== Training Model ============================\n prediction, time_derivs, thetas = model(data_train)\n\n MSE = torch.mean((prediction - target_train)**2, dim=0) # loss per output\n Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2)\n for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))])\n loss = torch.sum(torch.exp(-model.s[:, 0]) * MSE + torch.exp(-model.s[:, 1]) * Reg + torch.sum(model.s)) \n\n # Optimizer step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n \n if iteration % write_iterations == 0:\n # ================== Validation costs ================\n prediction_test, coordinates = model.func_approx(data_test)\n time_derivs_test, thetas_test = model.library((prediction_test, coordinates))\n with torch.no_grad():\n MSE_test = torch.mean((prediction_test - target_test)**2, dim=0) # loss per output\n Reg_test = torch.stack([torch.mean((dt - theta @ coeff_vector)**2)\n for dt, theta, coeff_vector in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))])\n loss_test = torch.sum(torch.exp(-model.s[:, 0]) * MSE_test + torch.exp(-model.s[:, 1]) * Reg_test + torch.sum(model.s)) \n \n # ====================== Logging =======================\n _ = model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs but not setting mask\n estimator_coeff_vectors = model.estimator_coeffs()\n l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0)\n progress(iteration, start_time, max_iterations, loss.item(),\n torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item())\n board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test, s=model.s)\n \n # ================== Sparsity update =============\n # Updating sparsity and or convergence\n #sparsity_scheduler(iteration, l1_norm)\n if iteration % write_iterations == 0:\n if test == 'mse':\n sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer)\n else:\n sparsity_scheduler(iteration, loss_test, model, optimizer) \n \n if sparsity_scheduler.apply_sparsity is True:\n with torch.no_grad():\n model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs)\n sparsity_scheduler.reset()\n\n # ================= Checking convergence\n convergence(iteration, torch.sum(l1_norm))\n if convergence.converged is True:\n print('Algorithm converged. Stopping training.')\n break\n board.close()\n if log_dir is None: \n path = 'model.pt'\n else:\n path = join(log_dir, 'model.pt')\n torch.save(model.state_dict(), path)\n\n\ndef train_multitask_capped(model: DeepMoD,\n data: torch.Tensor,\n target: torch.Tensor,\n optimizer,\n sparsity_scheduler,\n test = 'mse',\n split: float = 0.8,\n log_dir: Optional[str] = None,\n max_iterations: int = 10000,\n write_iterations: int = 25,\n **convergence_kwargs) -> None:\n \"\"\"[summary]\n\n Args:\n model (DeepMoD): [description]\n data (torch.Tensor): [description]\n target (torch.Tensor): [description]\n optimizer ([type]): [description]\n sparsity_scheduler ([type]): [description]\n log_dir (Optional[str], optional): [description]. Defaults to None.\n max_iterations (int, optional): [description]. Defaults to 10000.\n \"\"\"\n start_time = time.time()\n board = Tensorboard(log_dir) # initializing tb board\n\n # Splitting data, assumes data is already randomized\n n_train = int(split * data.shape[0])\n n_test = data.shape[0] - n_train\n data_train, data_test = torch.split(data, [n_train, n_test], dim=0)\n target_train, target_test = torch.split(target, [n_train, n_test], dim=0)\n \n #cutoff = torch.full((model.func_approx.architecture[-1], 1), 1e-5).to(target.device)\n cutoff = torch.tensor(15.).to(target.device)\n\n # Training\n convergence = Convergence(**convergence_kwargs)\n print('| Iteration | Progress | Time remaining | Loss | MSE | Reg | L1 norm |')\n for iteration in np.arange(0, max_iterations + 1):\n # ================== Training Model ============================\n prediction, time_derivs, thetas = model(data_train)\n\n MSE = torch.mean((prediction - target_train)**2, dim=0) # loss per output\n Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2, dim=0)\n for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))])\n\n s_capped = torch.min(torch.max(model.s, -cutoff), cutoff)\n loss = torch.sum(torch.exp(-s_capped[:, 0]) * MSE + torch.exp(-s_capped[:, 1]) * Reg + torch.sum(s_capped)) \n\n # Optimizer step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n \n if iteration % write_iterations == 0:\n # ================== Validation costs ================\n prediction_test, coordinates = model.func_approx(data_test)\n time_derivs_test, thetas_test = model.library((prediction_test, coordinates))\n with torch.no_grad():\n MSE_test = torch.mean((prediction_test - target_test)**2, dim=0) # loss per output\n Reg_test = torch.stack([torch.mean((dt - theta @ coeff_vector)**2)\n for dt, theta, coeff_vector in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))])\n loss_test = torch.sum(torch.exp(-s_capped[:, 0]) * MSE_test + torch.exp(-s_capped[:, 1]) * Reg_test + torch.sum(s_capped)) \n \n # ====================== Logging =======================\n _ = model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs but not setting mask\n estimator_coeff_vectors = model.estimator_coeffs()\n l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0)\n progress(iteration, start_time, max_iterations, loss.item(),\n torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item())\n board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test, s=model.s)\n \n # ================== Sparsity update =============\n # Updating sparsity and or convergence\n #sparsity_scheduler(iteration, l1_norm)\n if iteration % write_iterations == 0:\n if test == 'mse':\n sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer)\n else:\n sparsity_scheduler(iteration, loss_test, model, optimizer) \n \n if sparsity_scheduler.apply_sparsity is True:\n with torch.no_grad():\n model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs)\n sparsity_scheduler.reset()\n\n # ================= Checking convergence\n convergence(iteration, torch.sum(l1_norm))\n if convergence.converged is True:\n print('Algorithm converged. Stopping training.')\n break\n board.close()\n if log_dir is None: \n path = 'model.pt'\n else:\n path = join(log_dir, 'model.pt')\n torch.save(model.state_dict(), path)\n\ndef train_gradnorm(model: DeepMoD,\n data: torch.Tensor,\n target: torch.Tensor,\n optimizer,\n sparsity_scheduler,\n alpha,\n test = 'mse',\n split: float = 0.8,\n log_dir: Optional[str] = None,\n max_iterations: int = 10000,\n write_iterations: int = 25,\n **convergence_kwargs) -> None:\n \"\"\"[summary]\n\n Args:\n model (DeepMoD): [description]\n data (torch.Tensor): [description]\n target (torch.Tensor): [description]\n optimizer ([type]): [description]\n sparsity_scheduler ([type]): [description]\n log_dir (Optional[str], optional): [description]. Defaults to None.\n max_iterations (int, optional): [description]. Defaults to 10000.\n \"\"\"\n start_time = time.time()\n board = Tensorboard(log_dir) # initializing tb board\n\n # Splitting data, assumes data is already randomized\n n_train = int(split * data.shape[0])\n n_test = data.shape[0] - n_train\n data_train, data_test = torch.split(data, [n_train, n_test], dim=0)\n target_train, target_test = torch.split(target, [n_train, n_test], dim=0)\n\n # Training\n convergence = Convergence(**convergence_kwargs)\n print('| Iteration | Progress | Time remaining | Loss | MSE | Reg | L1 norm |')\n for iteration in np.arange(0, max_iterations + 1):\n # ================== Training Model ============================\n prediction, time_derivs, thetas = model(data_train)\n\n MSE = torch.mean((prediction - target_train)**2, dim=0) # loss per output\n Reg = torch.cat([torch.mean((dt - theta @ coeff_vector)**2, dim=0)\n for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))])\n task_loss = (torch.exp(model.weights) * torch.stack((MSE, Reg), axis=1)).flatten() # weighted losses\n loss = torch.sum(task_loss)\n\n if iteration == 0: # Getting initial loss\n ini_loss = task_loss.data\n if torch.any(task_loss.data > ini_loss):\n ini_loss[task_loss.data > ini_loss] = task_loss.data[task_loss.data > ini_loss]\n\n # Getting original grads\n optimizer.zero_grad()\n loss.backward(retain_graph=True)\n model.weights.grad.data = model.weights.grad.data * 0.0 # setting weight grads to zero\n\n # Getting Grads to normalize\n G = torch.tensor([torch.norm(torch.autograd.grad(loss_i, list(model.parameters())[-2], retain_graph=True, create_graph=True)[0], 2) for loss_i in task_loss]).to(data.device)\n G_mean = torch.mean(G) \n\n # Calculating relative losses\n rel_loss = task_loss / ini_loss\n inv_train_rate = rel_loss / torch.mean(rel_loss)\n\n # Calculating grad norm loss\n grad_norm_loss = torch.sum(torch.abs(G - G_mean * inv_train_rate ** alpha))\n\n # Setting grads\n model.weights.grad = torch.autograd.grad(grad_norm_loss, model.weights)[0]\n \n # do a step with the optimizer\n optimizer.step()\n \n # renormalize\n normalize_coeff = task_loss.shape[0] / torch.sum(model.weights)\n model.weights.data = torch.log(torch.exp(model.weights.data) * normalize_coeff)\n \n if iteration % write_iterations == 0:\n # ================== Validation costs ================\n prediction_test, coordinates = model.func_approx(data_test)\n time_derivs_test, thetas_test = model.library((prediction_test, coordinates))\n with torch.no_grad():\n MSE_test = torch.mean((prediction_test - target_test)**2, dim=0) # loss per output\n Reg_test = torch.stack([torch.mean((dt - theta @ coeff_vector)**2)\n for dt, theta, coeff_vector in zip(time_derivs_test, thetas_test, model.constraint_coeffs(scaled=False, sparse=True))])\n loss_test = model.weights @ torch.stack((MSE, Reg), axis=0)\n \n # ====================== Logging =======================\n _ = model.sparse_estimator(thetas, time_derivs) # calculating l1 adjusted coeffs but not setting mask\n estimator_coeff_vectors = model.estimator_coeffs()\n l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)), dim=0)\n progress(iteration, start_time, max_iterations, loss.item(),\n torch.sum(MSE).item(), torch.sum(Reg).item(), torch.sum(l1_norm).item())\n board.write(iteration, loss, MSE, Reg, l1_norm, model.constraint_coeffs(sparse=True, scaled=True), model.constraint_coeffs(sparse=True, scaled=False), estimator_coeff_vectors, MSE_test=MSE_test, Reg_test=Reg_test, loss_test=loss_test, w=model.weights)\n \n # ================== Sparsity update =============\n # Updating sparsity and or convergence\n #sparsity_scheduler(iteration, l1_norm)\n if iteration % write_iterations == 0:\n if test == 'mse':\n sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer)\n else:\n sparsity_scheduler(iteration, loss_test, model, optimizer) \n \n if sparsity_scheduler.apply_sparsity is True:\n with torch.no_grad():\n model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs)\n sparsity_scheduler.reset()\n\n # ================= Checking convergence\n convergence(iteration, torch.sum(l1_norm))\n if convergence.converged is True:\n print('Algorithm converged. Stopping training.')\n break\n board.close()\n if log_dir is None: \n path = 'model.pt'\n else:\n path = join(log_dir, 'model.pt')\n torch.save(model.state_dict(), path)\n\n\ndef train_SBL(model: DeepMoD,\n data: torch.Tensor,\n target: torch.Tensor,\n optimizer,\n extra_params, \n sparsity_scheduler,\n split = 0.8,\n exp_ID: str = None,\n log_dir: str = None,\n max_iterations: int = 10000,\n write_iterations: int = 25,\n **convergence_kwargs) -> None:\n \"\"\"Trains the DeepMoD model. This function automatically splits the data set in a train and test set. \n\n Args:\n model (DeepMoD): A DeepMoD object.\n data (torch.Tensor): Tensor of shape (n_samples x (n_spatial + 1)) containing the coordinates, first column should be the time coordinate.\n target (torch.Tensor): Tensor of shape (n_samples x n_features) containing the target data.\n optimizer ([type]): Pytorch optimizer.\n sparsity_scheduler ([type]): Decides when to update the sparsity mask.\n split (float, optional): Fraction of the train set, by default 0.8.\n exp_ID (str, optional): Unique ID to identify tensorboard file. Not used if log_dir is given, see pytorch documentation.\n log_dir (str, optional): Directory where tensorboard file is written, by default None.\n max_iterations (int, optional): [description]. Max number of epochs , by default 10000.\n write_iterations (int, optional): [description]. Sets how often data is written to tensorboard and checks train loss , by default 25.\n \"\"\"\n logger = Logger(exp_ID, log_dir)\n sparsity_scheduler.path = logger.log_dir # write checkpoint to same folder as tb output.\n \n t, a, l = extra_params\n \n # Splitting data, assumes data is already randomized\n n_train = int(split * data.shape[0])\n n_test = data.shape[0] - n_train\n data_train, data_test = torch.split(data, [n_train, n_test], dim=0)\n target_train, target_test = torch.split(target, [n_train, n_test], dim=0)\n \n M = 12\n N = data_train.shape[0]\n threshold = 1e4\n # Training\n convergence = Convergence(**convergence_kwargs)\n for iteration in torch.arange(0, max_iterations):\n # ================== Training Model ============================\n prediction, time_derivs, thetas = model(data_train)\n \n tau_ = torch.exp(t)\n alpha_ = torch.min(torch.exp(a), torch.tensor(1e8, dtype=torch.float32))\n lambda_ = torch.min(torch.exp(l), torch.tensor(2e4, dtype=torch.float32))\n \n y = time_derivs[0]\n X = thetas[0] / torch.norm(thetas[0], dim=0, keepdim=True)\n \n p_MSE = N / 2 * (tau_ * torch.mean((prediction - target_train)**2, dim=0) - t + np.log(2*np.pi))\n \n A = torch.diag(lambda_) + alpha_ * X.T @ X\n mn = (lambda_ < threshold)[:, None] * (alpha_ * torch.inverse(A) @ X.T @ y)\n E = alpha_ * torch.sum((y - X @ mn)**2) + mn.T @ torch.diag(lambda_) @ mn\n p_reg = 1/2 * (E + torch.sum(torch.log(torch.diag(A)[lambda_ < threshold])) - (torch.sum(l[lambda_ < threshold]) + N * a) - N * np.log(2*np.pi))\n\n MSE = torch.mean((prediction - target_train)**2, dim=0) # loss per output\n Reg = torch.stack([torch.mean((dt - theta @ coeff_vector)**2)\n for dt, theta, coeff_vector in zip(time_derivs, thetas, model.constraint_coeffs(scaled=False, sparse=True))])\n loss = torch.sum(p_MSE + p_reg)\n\n # Optimizer step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n if iteration % write_iterations == 0:\n # ================== Validation costs ================\n with torch.no_grad():\n prediction_test = model.func_approx(data_test)[0]\n MSE_test = torch.mean((prediction_test - target_test)**2, dim=0) # loss per output\n \n # ====================== Logging =======================\n _ = model.sparse_estimator(thetas, time_derivs) # calculating estimator coeffs but not setting mask\n logger(iteration, \n loss, MSE, Reg,\n model.constraint_coeffs(sparse=True, scaled=True), \n model.constraint_coeffs(sparse=True, scaled=False),\n model.estimator_coeffs(),\n MSE_test=MSE_test,\n p_MSE = p_MSE,\n p_reg = p_reg,\n tau = tau_,\n alpha=alpha_,\n lambda_=lambda_,\n mn=mn)\n\n # ================== Sparsity update =============\n # Updating sparsity \n update_sparsity = sparsity_scheduler(iteration, torch.sum(MSE_test), model, optimizer)\n if update_sparsity: \n model.constraint.sparsity_masks = model.sparse_estimator(thetas, time_derivs)\n\n # ================= Checking convergence\n l1_norm = torch.sum(torch.abs(torch.cat(model.constraint_coeffs(sparse=True, scaled=True), dim=1)))\n converged = convergence(iteration, l1_norm)\n if converged:\n break\n logger.close(model)" ]
[ [ "torch.cat", "torch.norm", "torch.split", "torch.no_grad", "numpy.arange", "torch.load", "torch.zeros_like", "torch.mean", "torch.sum" ], [ "torch.stack", "torch.arange", "torch.max", "torch.any", "torch.norm", "torch.split", "torch.no_grad", "numpy.log", "torch.inverse", "torch.abs", "torch.autograd.grad", "numpy.arange", "torch.tensor", "torch.diag", "torch.exp", "torch.mean", "torch.sum" ] ]
SinghJasdeep/Attention-on-Attention-for-VQA
[ "cbc767541667e9bb32760ac7cd2e822eff232ff5" ]
[ "train.py" ]
[ "import os\nimport time\nimport torch\nimport torch.nn as nn\nimport utils\nfrom torch.autograd import Variable\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef instance_bce_with_logits(logits, labels):\n assert logits.dim() == 2\n\n loss = nn.functional.binary_cross_entropy_with_logits(logits, labels)\n loss *= labels.size(1)\n return loss\n\n\ndef compute_score_with_logits(logits, labels):\n logits = torch.max(logits, 1)[1].data # argmax\n one_hots = torch.zeros(*labels.size()).cuda()\n one_hots.scatter_(1, logits.view(-1, 1), 1)\n scores = (one_hots * labels)\n return scores\n\n\ndef train(model, train_loader, eval_loader, num_epochs, output, opt, wd):\n utils.create_dir(output)\n # Paper uses AdaDelta\n if opt == 'Adadelta':\n optim = torch.optim.Adadelta(model.parameters(), rho=0.95, eps=1e-6, weight_decay=wd)\n elif opt == 'RMSprop':\n optim = torch.optim.RMSprop(model.parameters(), lr=0.01, alpha=0.99, eps=1e-08, weight_decay=wd, momentum=0, centered=False)\n elif opt == 'Adam':\n optim = torch.optim.Adam(model.parameters(), lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=wd)\n else:\n optim = torch.optim.Adamax(model.parameters(), weight_decay=wd)\n logger = utils.Logger(os.path.join(output, 'log.txt'))\n best_eval_score = 0\n\n for epoch in range(num_epochs):\n total_loss = 0\n train_score = 0\n t = time.time()\n correct = 0\n\n for i, (v, b, q, a) in enumerate(train_loader):\n v = Variable(v).cuda()\n b = Variable(b).cuda() # boxes not used\n q = Variable(q).cuda()\n a = Variable(a).cuda() # true labels\n\n pred = model(v, b, q, a)\n loss = instance_bce_with_logits(pred, a)\n loss.backward()\n nn.utils.clip_grad_norm(model.parameters(), 0.25)\n optim.step()\n optim.zero_grad()\n\n batch_score = compute_score_with_logits(pred, a.data).sum()\n total_loss += loss.data[0] * v.size(0)\n train_score += batch_score\n\n total_loss /= len(train_loader.dataset)\n train_score = 100 * train_score / len(train_loader.dataset)\n\n model.train(False)\n eval_score, bound, V_loss = evaluate(model, eval_loader)\n model.train(True)\n\n logger.write('epoch %d, time: %.2f' % (epoch, time.time()-t))\n logger.write('\\ttrain_loss: %.3f, score: %.3f' % (total_loss, train_score))\n logger.write('\\teval loss: %.3f, score: %.3f (%.3f)' % (V_loss, 100 * eval_score, 100 * bound))\n\n if eval_score > best_eval_score:\n model_path = os.path.join(output, 'model.pth')\n torch.save(model.state_dict(), model_path)\n best_eval_score = eval_score\n\n\ndef evaluate(model, dataloader):\n score = 0\n V_loss = 0\n upper_bound = 0\n num_data = 0\n for v, b, q, a in iter(dataloader):\n v = Variable(v, volatile=True).cuda()\n b = Variable(b, volatile=True).cuda()\n q = Variable(q, volatile=True).cuda()\n a = Variable(a, volatile=True).cuda()\n pred = model(v, b, q, None)\n loss = instance_bce_with_logits(pred, a)\n V_loss += loss.data[0] * v.size(0)\n batch_score = compute_score_with_logits(pred, a.data).sum()\n score += batch_score\n upper_bound += (a.max(1)[0]).sum()\n num_data += pred.size(0)\n\n score = score / len(dataloader.dataset)\n V_loss /= len(dataloader.dataset)\n upper_bound = upper_bound / len(dataloader.dataset)\n\n return score, upper_bound, V_loss\n" ]
[ [ "torch.nn.functional.binary_cross_entropy_with_logits", "torch.autograd.Variable", "torch.max" ] ]
aMp37/SimpleHTR
[ "2a8bad2990d83caaa004530cd3b3d87c5bd38ab4" ]
[ "venv/lib/python3.7/site-packages/tensorflow_core/contrib/ignite/python/ops/gen_dataset_ops.py" ]
[ "\"\"\"Python wrappers around TensorFlow ops.\n\nThis file is MACHINE GENERATED! Do not edit.\nOriginal C++ source file: gen_dataset_ops.cc\n\"\"\"\n\nimport collections as _collections\nimport six as _six\n\nfrom tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow\nfrom tensorflow.python.eager import context as _context\nfrom tensorflow.python.eager import core as _core\nfrom tensorflow.python.eager import execute as _execute\nfrom tensorflow.python.framework import dtypes as _dtypes\nfrom tensorflow.python.framework import errors as _errors\nfrom tensorflow.python.framework import tensor_shape as _tensor_shape\n\nfrom tensorflow.core.framework import op_def_pb2 as _op_def_pb2\n# Needed to trigger the call to _set_call_cpp_shape_fn.\nfrom tensorflow.python.framework import common_shapes as _common_shapes\nfrom tensorflow.python.framework import op_def_registry as _op_def_registry\nfrom tensorflow.python.framework import ops as _ops\nfrom tensorflow.python.framework import op_def_library as _op_def_library\nfrom tensorflow.python.util.deprecation import deprecated_endpoints\nfrom tensorflow.python.util import dispatch as _dispatch\nfrom tensorflow.python.util.tf_export import tf_export\nfrom tensorflow.python.util.tf_export import kwarg_only as _kwarg_only\nfrom tensorflow.tools.docs import doc_controls as _doc_controls\n\n\n@_dispatch.add_dispatch_list\n@tf_export('ignite_dataset')\ndef ignite_dataset(cache_name, host, port, local, part, page_size, schema, permutation, name=None):\n r\"\"\"IgniteDataset that allows to get data from Apache Ignite.\n\n Apache Ignite is a memory-centric distributed database, caching, and processing\n platform for transactional, analytical, and streaming workloads, delivering\n in-memory speeds at petabyte scale. This contrib package contains an\n integration between Apache Ignite and TensorFlow. The integration is based on\n tf.data from TensorFlow side and Binary Client Protocol from Apache Ignite side.\n It allows to use Apache Ignite as a datasource for neural network training,\n inference and all other computations supported by TensorFlow. Ignite Dataset\n is based on Apache Ignite Binary Client Protocol.\n\n Args:\n cache_name: A `Tensor` of type `string`. Ignite Cache Name.\n host: A `Tensor` of type `string`. Ignite Thin Client Host.\n port: A `Tensor` of type `int32`. Ignite Thin Client Port.\n local: A `Tensor` of type `bool`.\n Local flag that defines that data should be fetched from local host only.\n part: A `Tensor` of type `int32`. Partition data should be fetched from.\n page_size: A `Tensor` of type `int32`. Page size for Ignite Thin Client.\n schema: A `Tensor` of type `int32`.\n Internal structure that defines schema of cache objects.\n permutation: A `Tensor` of type `int32`.\n Internal structure that defines permutation of cache objects.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `variant`.\n \"\"\"\n _ctx = _context._context or _context.context()\n if _ctx is not None and _ctx._thread_local_data.is_eager:\n try:\n _result = _pywrap_tensorflow.TFE_Py_FastPathExecute(\n _ctx._context_handle, _ctx._thread_local_data.device_name,\n \"IgniteDataset\", name, _ctx.post_execution_callbacks, cache_name,\n host, port, local, part, page_size, schema, permutation)\n return _result\n except _core._FallbackException:\n try:\n return ignite_dataset_eager_fallback(\n cache_name, host, port, local, part, page_size, schema,\n permutation, name=name, ctx=_ctx)\n except _core._SymbolicException:\n pass # Add nodes to the TensorFlow graph.\n except (TypeError, ValueError):\n result = _dispatch.dispatch(\n ignite_dataset, cache_name=cache_name, host=host, port=port,\n local=local, part=part, page_size=page_size,\n schema=schema, permutation=permutation,\n name=name)\n if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:\n return result\n raise\n except _core._NotOkStatusException as e:\n if name is not None:\n message = e.message + \" name: \" + name\n else:\n message = e.message\n _six.raise_from(_core._status_to_exception(e.code, message), None)\n # Add nodes to the TensorFlow graph.\n try:\n _, _, _op = _op_def_lib._apply_op_helper(\n \"IgniteDataset\", cache_name=cache_name, host=host, port=port,\n local=local, part=part, page_size=page_size,\n schema=schema, permutation=permutation, name=name)\n except (TypeError, ValueError):\n result = _dispatch.dispatch(\n ignite_dataset, cache_name=cache_name, host=host, port=port,\n local=local, part=part, page_size=page_size,\n schema=schema, permutation=permutation, name=name)\n if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:\n return result\n raise\n _result = _op.outputs[:]\n _inputs_flat = _op.inputs\n _attrs = None\n _execute.record_gradient(\n \"IgniteDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\ndef IgniteDataset(cache_name, host, port, local, part, page_size, schema, permutation, name=None):\n return ignite_dataset(cache_name=cache_name, host=host, port=port, local=local, part=part, page_size=page_size, schema=schema, permutation=permutation, name=name)\nIgniteDataset.__doc__ = ignite_dataset.__doc__\nIgniteDataset = _doc_controls.do_not_generate_docs(_kwarg_only(IgniteDataset))\ntf_export(\"raw_ops.IgniteDataset\")(IgniteDataset)\n\n\ndef ignite_dataset_eager_fallback(cache_name, host, port, local, part, page_size, schema, permutation, name=None, ctx=None):\n r\"\"\"This is the slowpath function for Eager mode.\n This is for function ignite_dataset\n \"\"\"\n _ctx = ctx if ctx else _context.context()\n cache_name = _ops.convert_to_tensor(cache_name, _dtypes.string)\n host = _ops.convert_to_tensor(host, _dtypes.string)\n port = _ops.convert_to_tensor(port, _dtypes.int32)\n local = _ops.convert_to_tensor(local, _dtypes.bool)\n part = _ops.convert_to_tensor(part, _dtypes.int32)\n page_size = _ops.convert_to_tensor(page_size, _dtypes.int32)\n schema = _ops.convert_to_tensor(schema, _dtypes.int32)\n permutation = _ops.convert_to_tensor(permutation, _dtypes.int32)\n _inputs_flat = [cache_name, host, port, local, part, page_size, schema, permutation]\n _attrs = None\n _result = _execute.execute(b\"IgniteDataset\", 1, inputs=_inputs_flat,\n attrs=_attrs, ctx=_ctx, name=name)\n _execute.record_gradient(\n \"IgniteDataset\", _inputs_flat, _attrs, _result, name)\n _result, = _result\n return _result\n\n_ops.RegisterShape(\"IgniteDataset\")(None)\n\ndef _InitOpDefLibrary(op_list_proto_bytes):\n op_list = _op_def_pb2.OpList()\n op_list.ParseFromString(op_list_proto_bytes)\n _op_def_registry.register_op_list(op_list)\n op_def_lib = _op_def_library.OpDefLibrary()\n op_def_lib.add_op_list(op_list)\n return op_def_lib\n# op {\n# name: \"IgniteDataset\"\n# input_arg {\n# name: \"cache_name\"\n# type: DT_STRING\n# }\n# input_arg {\n# name: \"host\"\n# type: DT_STRING\n# }\n# input_arg {\n# name: \"port\"\n# type: DT_INT32\n# }\n# input_arg {\n# name: \"local\"\n# type: DT_BOOL\n# }\n# input_arg {\n# name: \"part\"\n# type: DT_INT32\n# }\n# input_arg {\n# name: \"page_size\"\n# type: DT_INT32\n# }\n# input_arg {\n# name: \"schema\"\n# type: DT_INT32\n# }\n# input_arg {\n# name: \"permutation\"\n# type: DT_INT32\n# }\n# output_arg {\n# name: \"handle\"\n# type: DT_VARIANT\n# }\n# is_stateful: true\n# }\n_op_def_lib = _InitOpDefLibrary(b\"\\n\\203\\001\\n\\rIgniteDataset\\022\\016\\n\\ncache_name\\030\\007\\022\\010\\n\\004host\\030\\007\\022\\010\\n\\004port\\030\\003\\022\\t\\n\\005local\\030\\n\\022\\010\\n\\004part\\030\\003\\022\\r\\n\\tpage_size\\030\\003\\022\\n\\n\\006schema\\030\\003\\022\\017\\n\\013permutation\\030\\003\\032\\n\\n\\006handle\\030\\025\\210\\001\\001\")\n" ]
[ [ "tensorflow.python.framework.ops.RegisterShape", "tensorflow.python.util.dispatch.dispatch", "tensorflow.python.util.tf_export.kwarg_only", "tensorflow.python.eager.context.context", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.eager.execute.execute", "tensorflow.python.eager.execute.record_gradient", "tensorflow.core.framework.op_def_pb2.OpList", "tensorflow.python.pywrap_tensorflow.TFE_Py_FastPathExecute", "tensorflow.python.framework.op_def_library.OpDefLibrary", "tensorflow.python.eager.core._status_to_exception", "tensorflow.python.framework.op_def_registry.register_op_list", "tensorflow.python.util.tf_export.tf_export" ] ]
accidentalgenius09/competitive-programming-solution
[ "210746a7928dcd601ad9a735de52cf7135851070" ]
[ "HackerRank/PythonHackerRankSolutions/Numpy/ShapeandReshape.py" ]
[ "'''\nTitle : Shape and Reshape\nSubdomain : Numpy\nDomain : Python\nAuthor : codeperfectplus\nCreated : 06 May 2020\n'''\nimport numpy as np\n\narr = list(map(int,input().split()))\narr = np.array(arr)\n\nprint(np.reshape(arr,(3,3)))\n\n" ]
[ [ "numpy.array", "numpy.reshape" ] ]
repeating/stock-analyzer
[ "c190fb23d22300abb9b2a060adcc213ebe4d8dbc" ]
[ "backend/data_merge.py" ]
[ "import glob\nimport pandas as pd\nimport os\nimport datetime\n\n\nclass DataMerge:\n def __init__(self, directory):\n self.directory = directory\n self.__data = self.get_data_from(self.directory)\n\n def date_to_int(self, dates):\n \"\"\"\n calculates number of days between 01/01/0001 and each date in dates\n date has format '%m/%d/%Y'\n\n :param dates: Pandas Series\n :return: list\n \"\"\"\n ret = []\n for date in dates:\n date0 = datetime.datetime(year=1, month=1, day=1)\n datex = datetime.datetime.strptime(date, '%m/%d/%Y')\n ret.append((datex - date0).days)\n return ret\n\n def get_data_from(self, dir):\n files = glob.glob(f'{dir}/*')\n if files == []:\n raise f'directory {dir} does not contain any .csv file'\n data = None\n for file in files:\n if file == f'{dir}/merged_data.csv':\n continue\n if data is None:\n data = pd.read_csv(file)\n continue\n temp_data = pd.read_csv(file)\n temp_data = temp_data.dropna(axis=1)\n data = data.append(temp_data)\n data.drop_duplicates()\n data = data.sort_values('Date', ascending=False, key=self.date_to_int)\n data = data[: 408]\n data.to_csv(f\"{dir}/merged_data.csv\", index=False)\n return data\n\n def get_data(self):\n return self.__data" ]
[ [ "pandas.read_csv" ] ]
noah-kuo/modin
[ "a54875acbbe9e5db17b38f42fe236f3fe51207f4" ]
[ "modin/pandas/test/test_general.py" ]
[ "# Licensed to Modin Development Team under one or more contributor license agreements.\n# See the NOTICE file distributed with this work for additional information regarding\n# copyright ownership. The Modin Development Team licenses this file to you under the\n# Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n# compliance 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 distributed under\n# the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific language\n# governing permissions and limitations under the License.\n\nimport pandas\nimport pytest\nimport modin.pandas as pd\nimport numpy as np\nfrom numpy.testing import assert_array_equal\nfrom modin.utils import get_current_backend, to_pandas\n\nfrom .utils import test_data_values, test_data_keys, df_equals\n\n\n@pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\ndef test_isna(data):\n pandas_df = pandas.DataFrame(data)\n modin_df = pd.DataFrame(data)\n\n pandas_result = pandas.isna(pandas_df)\n modin_result = pd.isna(modin_df)\n df_equals(modin_result, pandas_result)\n\n modin_result = pd.isna(pd.Series([1, np.nan, 2]))\n pandas_result = pandas.isna(pandas.Series([1, np.nan, 2]))\n df_equals(modin_result, pandas_result)\n\n assert pd.isna(np.nan) == pandas.isna(np.nan)\n\n\n@pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\ndef test_isnull(data):\n pandas_df = pandas.DataFrame(data)\n modin_df = pd.DataFrame(data)\n\n pandas_result = pandas.isnull(pandas_df)\n modin_result = pd.isnull(modin_df)\n df_equals(modin_result, pandas_result)\n\n modin_result = pd.isnull(pd.Series([1, np.nan, 2]))\n pandas_result = pandas.isnull(pandas.Series([1, np.nan, 2]))\n df_equals(modin_result, pandas_result)\n\n assert pd.isna(np.nan) == pandas.isna(np.nan)\n\n\n@pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\ndef test_notna(data):\n pandas_df = pandas.DataFrame(data)\n modin_df = pd.DataFrame(data)\n\n pandas_result = pandas.notna(pandas_df)\n modin_result = pd.notna(modin_df)\n df_equals(modin_result, pandas_result)\n\n modin_result = pd.notna(pd.Series([1, np.nan, 2]))\n pandas_result = pandas.notna(pandas.Series([1, np.nan, 2]))\n df_equals(modin_result, pandas_result)\n\n assert pd.isna(np.nan) == pandas.isna(np.nan)\n\n\n@pytest.mark.parametrize(\"data\", test_data_values, ids=test_data_keys)\ndef test_notnull(data):\n pandas_df = pandas.DataFrame(data)\n modin_df = pd.DataFrame(data)\n\n pandas_result = pandas.notnull(pandas_df)\n modin_result = pd.notnull(modin_df)\n df_equals(modin_result, pandas_result)\n\n modin_result = pd.notnull(pd.Series([1, np.nan, 2]))\n pandas_result = pandas.notnull(pandas.Series([1, np.nan, 2]))\n df_equals(modin_result, pandas_result)\n\n assert pd.isna(np.nan) == pandas.isna(np.nan)\n\n\ndef test_merge():\n frame_data = {\n \"col1\": [0, 1, 2, 3],\n \"col2\": [4, 5, 6, 7],\n \"col3\": [8, 9, 0, 1],\n \"col4\": [2, 4, 5, 6],\n }\n\n modin_df = pd.DataFrame(frame_data)\n pandas_df = pandas.DataFrame(frame_data)\n\n frame_data2 = {\"col1\": [0, 1, 2], \"col2\": [1, 5, 6]}\n modin_df2 = pd.DataFrame(frame_data2)\n pandas_df2 = pandas.DataFrame(frame_data2)\n\n join_types = [\"outer\", \"inner\"]\n for how in join_types:\n # Defaults\n modin_result = pd.merge(modin_df, modin_df2, how=how)\n pandas_result = pandas.merge(pandas_df, pandas_df2, how=how)\n df_equals(modin_result, pandas_result)\n\n # left_on and right_index\n modin_result = pd.merge(\n modin_df, modin_df2, how=how, left_on=\"col1\", right_index=True\n )\n pandas_result = pandas.merge(\n pandas_df, pandas_df2, how=how, left_on=\"col1\", right_index=True\n )\n df_equals(modin_result, pandas_result)\n\n # left_index and right_on\n modin_result = pd.merge(\n modin_df, modin_df2, how=how, left_index=True, right_on=\"col1\"\n )\n pandas_result = pandas.merge(\n pandas_df, pandas_df2, how=how, left_index=True, right_on=\"col1\"\n )\n df_equals(modin_result, pandas_result)\n\n # left_on and right_on col1\n modin_result = pd.merge(\n modin_df, modin_df2, how=how, left_on=\"col1\", right_on=\"col1\"\n )\n pandas_result = pandas.merge(\n pandas_df, pandas_df2, how=how, left_on=\"col1\", right_on=\"col1\"\n )\n df_equals(modin_result, pandas_result)\n\n # left_on and right_on col2\n modin_result = pd.merge(\n modin_df, modin_df2, how=how, left_on=\"col2\", right_on=\"col2\"\n )\n pandas_result = pandas.merge(\n pandas_df, pandas_df2, how=how, left_on=\"col2\", right_on=\"col2\"\n )\n df_equals(modin_result, pandas_result)\n\n # left_index and right_index\n modin_result = pd.merge(\n modin_df, modin_df2, how=how, left_index=True, right_index=True\n )\n pandas_result = pandas.merge(\n pandas_df, pandas_df2, how=how, left_index=True, right_index=True\n )\n df_equals(modin_result, pandas_result)\n\n s = pd.Series(frame_data.get(\"col1\"))\n with pytest.raises(ValueError):\n pd.merge(s, modin_df2)\n\n with pytest.raises(TypeError):\n pd.merge(\"Non-valid type\", modin_df2)\n\n\ndef test_merge_ordered():\n data_a = {\n \"key\": list(\"aceace\"),\n \"lvalue\": [1, 2, 3, 1, 2, 3],\n \"group\": list(\"aaabbb\"),\n }\n data_b = {\"key\": list(\"bcd\"), \"rvalue\": [1, 2, 3]}\n\n modin_df_a = pd.DataFrame(data_a)\n modin_df_b = pd.DataFrame(data_b)\n\n with pytest.warns(UserWarning):\n df = pd.merge_ordered(\n modin_df_a, modin_df_b, fill_method=\"ffill\", left_by=\"group\"\n )\n assert isinstance(df, pd.DataFrame)\n\n with pytest.raises(ValueError):\n pd.merge_ordered(data_a, data_b, fill_method=\"ffill\", left_by=\"group\")\n\n\ndef test_merge_asof():\n left = pd.DataFrame({\"a\": [1, 5, 10], \"left_val\": [\"a\", \"b\", \"c\"]})\n right = pd.DataFrame({\"a\": [1, 2, 3, 6, 7], \"right_val\": [1, 2, 3, 6, 7]})\n\n with pytest.warns(UserWarning):\n df = pd.merge_asof(left, right, on=\"a\")\n assert isinstance(df, pd.DataFrame)\n\n with pytest.warns(UserWarning):\n df = pd.merge_asof(left, right, on=\"a\", allow_exact_matches=False)\n assert isinstance(df, pd.DataFrame)\n\n with pytest.warns(UserWarning):\n df = pd.merge_asof(left, right, on=\"a\", direction=\"forward\")\n assert isinstance(df, pd.DataFrame)\n\n with pytest.warns(UserWarning):\n df = pd.merge_asof(left, right, on=\"a\", direction=\"nearest\")\n assert isinstance(df, pd.DataFrame)\n\n left = pd.DataFrame({\"left_val\": [\"a\", \"b\", \"c\"]}, index=[1, 5, 10])\n right = pd.DataFrame({\"right_val\": [1, 2, 3, 6, 7]}, index=[1, 2, 3, 6, 7])\n\n with pytest.warns(UserWarning):\n df = pd.merge_asof(left, right, left_index=True, right_index=True)\n assert isinstance(df, pd.DataFrame)\n\n with pytest.raises(ValueError):\n pd.merge_asof(\n {\"left_val\": [\"a\", \"b\", \"c\"]},\n {\"right_val\": [1, 2, 3, 6, 7]},\n left_index=True,\n right_index=True,\n )\n\n\ndef test_merge_asof_on_variations():\n \"\"\"on=,left_on=,right_on=,right_index=,left_index= options match Pandas.\"\"\"\n left = {\"a\": [1, 5, 10], \"left_val\": [\"a\", \"b\", \"c\"]}\n left_index = [6, 8, 12]\n right = {\"a\": [1, 2, 3, 6, 7], \"right_val\": [\"d\", \"e\", \"f\", \"g\", \"h\"]}\n right_index = [6, 7, 8, 9, 15]\n pandas_left, pandas_right = (\n pandas.DataFrame(left, index=left_index),\n pandas.DataFrame(right, index=right_index),\n )\n modin_left, modin_right = pd.DataFrame(left, index=left_index), pd.DataFrame(\n right, index=right_index\n )\n for on_arguments in [\n {\"on\": \"a\"},\n {\"left_on\": \"a\", \"right_on\": \"a\"},\n {\"left_on\": \"a\", \"right_index\": True},\n {\"left_index\": True, \"right_on\": \"a\"},\n {\"left_index\": True, \"right_index\": True},\n ]:\n pandas_merged = pandas.merge_asof(pandas_left, pandas_right, **on_arguments)\n modin_merged = pd.merge_asof(modin_left, modin_right, **on_arguments)\n df_equals(pandas_merged, modin_merged)\n\n\ndef test_merge_asof_suffixes():\n \"\"\"Suffix variations are handled the same as Pandas.\"\"\"\n left = {\"a\": [1, 5, 10]}\n right = {\"a\": [2, 3, 6]}\n pandas_left, pandas_right = (pandas.DataFrame(left), pandas.DataFrame(right))\n modin_left, modin_right = pd.DataFrame(left), pd.DataFrame(right)\n for suffixes in [(\"a\", \"b\"), (False, \"c\"), (\"d\", False)]:\n pandas_merged = pandas.merge_asof(\n pandas_left,\n pandas_right,\n left_index=True,\n right_index=True,\n suffixes=suffixes,\n )\n modin_merged = pd.merge_asof(\n modin_left,\n modin_right,\n left_index=True,\n right_index=True,\n suffixes=suffixes,\n )\n df_equals(pandas_merged, modin_merged)\n\n with pytest.raises(ValueError):\n pandas.merge_asof(\n pandas_left,\n pandas_right,\n left_index=True,\n right_index=True,\n suffixes=(False, False),\n )\n with pytest.raises(ValueError):\n modin_merged = pd.merge_asof(\n modin_left,\n modin_right,\n left_index=True,\n right_index=True,\n suffixes=(False, False),\n )\n\n\ndef test_merge_asof_bad_arguments():\n left = {\"a\": [1, 5, 10], \"b\": [5, 7, 9]}\n right = {\"a\": [2, 3, 6], \"b\": [6, 5, 20]}\n pandas_left, pandas_right = (pandas.DataFrame(left), pandas.DataFrame(right))\n modin_left, modin_right = pd.DataFrame(left), pd.DataFrame(right)\n\n # Can't mix by with left_by/right_by\n with pytest.raises(ValueError):\n pandas.merge_asof(\n pandas_left, pandas_right, on=\"a\", by=\"b\", left_by=\"can't do with by\"\n )\n with pytest.raises(ValueError):\n pd.merge_asof(\n modin_left, modin_right, on=\"a\", by=\"b\", left_by=\"can't do with by\"\n )\n with pytest.raises(ValueError):\n pandas.merge_asof(\n pandas_left, pandas_right, by=\"b\", on=\"a\", right_by=\"can't do with by\"\n )\n with pytest.raises(ValueError):\n pd.merge_asof(\n modin_left, modin_right, by=\"b\", on=\"a\", right_by=\"can't do with by\"\n )\n\n # Can't mix on with left_on/right_on\n with pytest.raises(ValueError):\n pandas.merge_asof(pandas_left, pandas_right, on=\"a\", left_on=\"can't do with by\")\n with pytest.raises(ValueError):\n pd.merge_asof(modin_left, modin_right, on=\"a\", left_on=\"can't do with by\")\n with pytest.raises(ValueError):\n pandas.merge_asof(\n pandas_left, pandas_right, on=\"a\", right_on=\"can't do with by\"\n )\n with pytest.raises(ValueError):\n pd.merge_asof(modin_left, modin_right, on=\"a\", right_on=\"can't do with by\")\n\n # Can't mix left_index with left_on or on, similarly for right.\n with pytest.raises(ValueError):\n pd.merge_asof(modin_left, modin_right, on=\"a\", right_index=True)\n with pytest.raises(ValueError):\n pd.merge_asof(\n modin_left, modin_right, left_on=\"a\", right_on=\"a\", right_index=True\n )\n with pytest.raises(ValueError):\n pd.merge_asof(modin_left, modin_right, on=\"a\", left_index=True)\n with pytest.raises(ValueError):\n pd.merge_asof(\n modin_left, modin_right, left_on=\"a\", right_on=\"a\", left_index=True\n )\n\n # Need both left and right\n with pytest.raises(Exception): # Pandas bug, didn't validate inputs sufficiently\n pandas.merge_asof(pandas_left, pandas_right, left_on=\"a\")\n with pytest.raises(ValueError):\n pd.merge_asof(modin_left, modin_right, left_on=\"a\")\n with pytest.raises(Exception): # Pandas bug, didn't validate inputs sufficiently\n pandas.merge_asof(pandas_left, pandas_right, right_on=\"a\")\n with pytest.raises(ValueError):\n pd.merge_asof(modin_left, modin_right, right_on=\"a\")\n with pytest.raises(ValueError):\n pandas.merge_asof(pandas_left, pandas_right)\n with pytest.raises(ValueError):\n pd.merge_asof(modin_left, modin_right)\n\n\ndef test_merge_asof_merge_options():\n modin_quotes = pd.DataFrame(\n {\n \"time\": [\n pd.Timestamp(\"2016-05-25 13:30:00.023\"),\n pd.Timestamp(\"2016-05-25 13:30:00.023\"),\n pd.Timestamp(\"2016-05-25 13:30:00.030\"),\n pd.Timestamp(\"2016-05-25 13:30:00.041\"),\n pd.Timestamp(\"2016-05-25 13:30:00.048\"),\n pd.Timestamp(\"2016-05-25 13:30:00.049\"),\n pd.Timestamp(\"2016-05-25 13:30:00.072\"),\n pd.Timestamp(\"2016-05-25 13:30:00.075\"),\n ],\n \"ticker\": [\"GOOG\", \"MSFT\", \"MSFT\", \"MSFT\", \"GOOG\", \"AAPL\", \"GOOG\", \"MSFT\"],\n \"bid\": [720.50, 51.95, 51.97, 51.99, 720.50, 97.99, 720.50, 52.01],\n \"ask\": [720.93, 51.96, 51.98, 52.00, 720.93, 98.01, 720.88, 52.03],\n }\n )\n modin_trades = pd.DataFrame(\n {\n \"time\": [\n pd.Timestamp(\"2016-05-25 13:30:00.023\"),\n pd.Timestamp(\"2016-05-25 13:30:00.038\"),\n pd.Timestamp(\"2016-05-25 13:30:00.048\"),\n pd.Timestamp(\"2016-05-25 13:30:00.048\"),\n pd.Timestamp(\"2016-05-25 13:30:00.048\"),\n ],\n \"ticker2\": [\"MSFT\", \"MSFT\", \"GOOG\", \"GOOG\", \"AAPL\"],\n \"price\": [51.95, 51.95, 720.77, 720.92, 98.0],\n \"quantity\": [75, 155, 100, 100, 100],\n }\n )\n pandas_quotes, pandas_trades = to_pandas(modin_quotes), to_pandas(modin_trades)\n\n # left_by + right_by\n df_equals(\n pandas.merge_asof(\n pandas_quotes,\n pandas_trades,\n on=\"time\",\n left_by=\"ticker\",\n right_by=\"ticker2\",\n ),\n pd.merge_asof(\n modin_quotes,\n modin_trades,\n on=\"time\",\n left_by=\"ticker\",\n right_by=\"ticker2\",\n ),\n )\n\n # Just by:\n pandas_trades[\"ticker\"] = pandas_trades[\"ticker2\"]\n modin_trades[\"ticker\"] = modin_trades[\"ticker2\"]\n df_equals(\n pandas.merge_asof(\n pandas_quotes,\n pandas_trades,\n on=\"time\",\n by=\"ticker\",\n ),\n pd.merge_asof(\n modin_quotes,\n modin_trades,\n on=\"time\",\n by=\"ticker\",\n ),\n )\n\n # Tolerance\n df_equals(\n pandas.merge_asof(\n pandas_quotes,\n pandas_trades,\n on=\"time\",\n by=\"ticker\",\n tolerance=pd.Timedelta(\"2ms\"),\n ),\n pd.merge_asof(\n modin_quotes,\n modin_trades,\n on=\"time\",\n by=\"ticker\",\n tolerance=pd.Timedelta(\"2ms\"),\n ),\n )\n\n # Direction\n df_equals(\n pandas.merge_asof(\n pandas_quotes,\n pandas_trades,\n on=\"time\",\n by=\"ticker\",\n direction=\"forward\",\n ),\n pd.merge_asof(\n modin_quotes,\n modin_trades,\n on=\"time\",\n by=\"ticker\",\n direction=\"forward\",\n ),\n )\n\n # Allow exact matches\n df_equals(\n pandas.merge_asof(\n pandas_quotes,\n pandas_trades,\n on=\"time\",\n by=\"ticker\",\n tolerance=pd.Timedelta(\"10ms\"),\n allow_exact_matches=False,\n ),\n pd.merge_asof(\n modin_quotes,\n modin_trades,\n on=\"time\",\n by=\"ticker\",\n tolerance=pd.Timedelta(\"10ms\"),\n allow_exact_matches=False,\n ),\n )\n\n\ndef test_pivot():\n test_df = pd.DataFrame(\n {\n \"foo\": [\"one\", \"one\", \"one\", \"two\", \"two\", \"two\"],\n \"bar\": [\"A\", \"B\", \"C\", \"A\", \"B\", \"C\"],\n \"baz\": [1, 2, 3, 4, 5, 6],\n \"zoo\": [\"x\", \"y\", \"z\", \"q\", \"w\", \"t\"],\n }\n )\n\n df = pd.pivot(test_df, index=\"foo\", columns=\"bar\", values=\"baz\")\n assert isinstance(df, pd.DataFrame)\n\n with pytest.raises(ValueError):\n pd.pivot(test_df[\"bar\"], index=\"foo\", columns=\"bar\", values=\"baz\")\n\n\ndef test_pivot_table():\n test_df = pd.DataFrame(\n {\n \"A\": [\"foo\", \"foo\", \"foo\", \"foo\", \"foo\", \"bar\", \"bar\", \"bar\", \"bar\"],\n \"B\": [\"one\", \"one\", \"one\", \"two\", \"two\", \"one\", \"one\", \"two\", \"two\"],\n \"C\": [\n \"small\",\n \"large\",\n \"large\",\n \"small\",\n \"small\",\n \"large\",\n \"small\",\n \"small\",\n \"large\",\n ],\n \"D\": [1, 2, 2, 3, 3, 4, 5, 6, 7],\n \"E\": [2, 4, 5, 5, 6, 6, 8, 9, 9],\n }\n )\n\n df = pd.pivot_table(\n test_df, values=\"D\", index=[\"A\", \"B\"], columns=[\"C\"], aggfunc=np.sum\n )\n assert isinstance(df, pd.DataFrame)\n\n with pytest.raises(ValueError):\n pd.pivot_table(\n test_df[\"C\"], values=\"D\", index=[\"A\", \"B\"], columns=[\"C\"], aggfunc=np.sum\n )\n\n\ndef test_unique():\n modin_result = pd.unique([2, 1, 3, 3])\n pandas_result = pandas.unique([2, 1, 3, 3])\n assert_array_equal(modin_result, pandas_result)\n assert modin_result.shape == pandas_result.shape\n\n modin_result = pd.unique(pd.Series([2] + [1] * 5))\n pandas_result = pandas.unique(pandas.Series([2] + [1] * 5))\n assert_array_equal(modin_result, pandas_result)\n assert modin_result.shape == pandas_result.shape\n\n modin_result = pd.unique(\n pd.Series([pd.Timestamp(\"20160101\"), pd.Timestamp(\"20160101\")])\n )\n pandas_result = pandas.unique(\n pandas.Series([pandas.Timestamp(\"20160101\"), pandas.Timestamp(\"20160101\")])\n )\n assert_array_equal(modin_result, pandas_result)\n assert modin_result.shape == pandas_result.shape\n\n modin_result = pd.unique(\n pd.Series(\n [\n pd.Timestamp(\"20160101\", tz=\"US/Eastern\"),\n pd.Timestamp(\"20160101\", tz=\"US/Eastern\"),\n ]\n )\n )\n pandas_result = pandas.unique(\n pandas.Series(\n [\n pandas.Timestamp(\"20160101\", tz=\"US/Eastern\"),\n pandas.Timestamp(\"20160101\", tz=\"US/Eastern\"),\n ]\n )\n )\n assert_array_equal(modin_result, pandas_result)\n assert modin_result.shape == pandas_result.shape\n\n modin_result = pd.unique(\n pd.Index(\n [\n pd.Timestamp(\"20160101\", tz=\"US/Eastern\"),\n pd.Timestamp(\"20160101\", tz=\"US/Eastern\"),\n ]\n )\n )\n pandas_result = pandas.unique(\n pandas.Index(\n [\n pandas.Timestamp(\"20160101\", tz=\"US/Eastern\"),\n pandas.Timestamp(\"20160101\", tz=\"US/Eastern\"),\n ]\n )\n )\n assert_array_equal(modin_result, pandas_result)\n assert modin_result.shape == pandas_result.shape\n\n modin_result = pd.unique(pd.Series(pd.Categorical(list(\"baabc\"))))\n pandas_result = pandas.unique(pandas.Series(pandas.Categorical(list(\"baabc\"))))\n assert_array_equal(modin_result, pandas_result)\n assert modin_result.shape == pandas_result.shape\n\n\n@pytest.mark.parametrize(\"normalize, bins, dropna\", [(True, 3, False)])\ndef test_value_counts(normalize, bins, dropna):\n def sort_index_for_equal_values(result, ascending):\n is_range = False\n is_end = False\n i = 0\n new_index = np.empty(len(result), dtype=type(result.index))\n while i < len(result):\n j = i\n if i < len(result) - 1:\n while result[result.index[i]] == result[result.index[i + 1]]:\n i += 1\n if is_range is False:\n is_range = True\n if i == len(result) - 1:\n is_end = True\n break\n if is_range:\n k = j\n for val in sorted(result.index[j : i + 1], reverse=not ascending):\n new_index[k] = val\n k += 1\n if is_end:\n break\n is_range = False\n else:\n new_index[j] = result.index[j]\n i += 1\n return type(result)(result, index=new_index)\n\n # We sort indices for Modin and pandas result because of issue #1650\n values = np.array([3, 1, 2, 3, 4, np.nan])\n modin_result = sort_index_for_equal_values(\n pd.value_counts(values, normalize=normalize, ascending=False), False\n )\n pandas_result = sort_index_for_equal_values(\n pandas.value_counts(values, normalize=normalize, ascending=False), False\n )\n df_equals(modin_result, pandas_result)\n\n modin_result = sort_index_for_equal_values(\n pd.value_counts(values, bins=bins, ascending=False), False\n )\n pandas_result = sort_index_for_equal_values(\n pandas.value_counts(values, bins=bins, ascending=False), False\n )\n df_equals(modin_result, pandas_result)\n\n modin_result = sort_index_for_equal_values(\n pd.value_counts(values, dropna=dropna, ascending=True), True\n )\n pandas_result = sort_index_for_equal_values(\n pandas.value_counts(values, dropna=dropna, ascending=True), True\n )\n df_equals(modin_result, pandas_result)\n\n\ndef test_to_datetime():\n # DataFrame input for to_datetime\n modin_df = pd.DataFrame({\"year\": [2015, 2016], \"month\": [2, 3], \"day\": [4, 5]})\n pandas_df = pandas.DataFrame({\"year\": [2015, 2016], \"month\": [2, 3], \"day\": [4, 5]})\n df_equals(pd.to_datetime(modin_df), pandas.to_datetime(pandas_df))\n\n # Series input for to_datetime\n modin_s = pd.Series([\"3/11/2000\", \"3/12/2000\", \"3/13/2000\"] * 1000)\n pandas_s = pandas.Series([\"3/11/2000\", \"3/12/2000\", \"3/13/2000\"] * 1000)\n df_equals(pd.to_datetime(modin_s), pandas.to_datetime(pandas_s))\n\n # Other inputs for to_datetime\n value = 1490195805\n assert pd.to_datetime(value, unit=\"s\") == pandas.to_datetime(value, unit=\"s\")\n value = 1490195805433502912\n assert pd.to_datetime(value, unit=\"ns\") == pandas.to_datetime(value, unit=\"ns\")\n value = [1, 2, 3]\n assert pd.to_datetime(value, unit=\"D\", origin=pd.Timestamp(\"2000-01-01\")).equals(\n pandas.to_datetime(value, unit=\"D\", origin=pandas.Timestamp(\"2000-01-01\"))\n )\n\n\n@pytest.mark.parametrize(\n \"data, errors, downcast\",\n [\n ([\"1.0\", \"2\", -3], \"raise\", None),\n ([\"1.0\", \"2\", -3], \"raise\", \"float\"),\n ([\"1.0\", \"2\", -3], \"raise\", \"signed\"),\n ([\"apple\", \"1.0\", \"2\", -3], \"ignore\", None),\n ([\"apple\", \"1.0\", \"2\", -3], \"coerce\", None),\n ],\n)\ndef test_to_numeric(data, errors, downcast):\n modin_series = pd.Series(data)\n pandas_series = pandas.Series(data)\n modin_result = pd.to_numeric(modin_series, errors=errors, downcast=downcast)\n pandas_result = pandas.to_numeric(pandas_series, errors=errors, downcast=downcast)\n df_equals(modin_result, pandas_result)\n\n\ndef test_to_pandas_indices():\n data = test_data_values[0]\n\n md_df = pd.DataFrame(data)\n index = pandas.MultiIndex.from_tuples(\n [(i, i * 2) for i in np.arange(len(md_df) + 1)], names=[\"A\", \"B\"]\n ).drop(0)\n columns = pandas.MultiIndex.from_tuples(\n [(i, i * 2) for i in np.arange(len(md_df.columns) + 1)], names=[\"A\", \"B\"]\n ).drop(0)\n\n md_df.index = index\n md_df.columns = columns\n\n pd_df = md_df._to_pandas()\n\n for axis in [0, 1]:\n assert md_df.axes[axis].equals(\n pd_df.axes[axis]\n ), f\"Indices at axis {axis} are different!\"\n assert md_df.axes[axis].equal_levels(\n pd_df.axes[axis]\n ), f\"Levels of indices at axis {axis} are different!\"\n\n\n@pytest.mark.skipif(\n get_current_backend() != \"BaseOnPython\",\n reason=\"This test make sense only on BaseOnPython backend.\",\n)\n@pytest.mark.parametrize(\n \"func, regex\",\n [\n (lambda df: df.mean(level=0), r\"DataFrame\\.mean\"),\n (lambda df: df + df, r\"DataFrame\\.add\"),\n (lambda df: df.index, r\"DataFrame\\.get_axis\\(0\\)\"),\n (\n lambda df: df.drop(columns=\"col1\").squeeze().repeat(2),\n r\"Series\\.repeat\",\n ),\n (lambda df: df.groupby(\"col1\").prod(), r\"GroupBy\\.prod\"),\n (lambda df: df.rolling(1).count(), r\"Rolling\\.count\"),\n ],\n)\ndef test_default_to_pandas_warning_message(func, regex):\n data = {\"col1\": [1, 2, 3], \"col2\": [4, 5, 6]}\n df = pd.DataFrame(data)\n\n with pytest.warns(UserWarning, match=regex):\n func(df)\n" ]
[ [ "pandas.isnull", "pandas.notnull", "numpy.array", "pandas.isna", "pandas.value_counts", "pandas.to_datetime", "pandas.merge", "pandas.DataFrame", "numpy.testing.assert_array_equal", "pandas.merge_asof", "pandas.notna", "pandas.Timestamp", "pandas.Series", "pandas.unique", "pandas.to_numeric" ] ]
mirestrepo/voxels-at-lems
[ "df47d031653d2ad877a97b3c1ea574b924b7d4c2" ]
[ "bvpl/bvpl_octree/taylor_vs_pca.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 7 16:41:25 2011\n\n@author: -\n\"\"\"\n\nimport os;\nimport time;\nimport sys;\nimport plot_pca_functions;\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\ntaylor_error_capitol= 0.608546356589;\npca_error_9_capitol = 0.614236131016; #at 10% sample-training\n\ntaylor_error_downtown= 0.248427497809; #this is for downtown12_12_4!\npca_error_9_downtown = 0.193806624247; #this is for downtown3_3_1!\n\nfig = plt.figure();\n" ]
[ [ "matplotlib.pyplot.figure" ] ]
jinjiren/ParlAI
[ "40799aeee69f2a0bb25a1341bb8da0c44861268e" ]
[ "parlai/agents/transformer/modules.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport math\nimport numpy as np\n\nfrom parlai.core.torch_generator_agent import TorchGeneratorModel\n\n\ndef _normalize(tensor, norm_layer):\n \"\"\"\n Broadcast layer norm\n \"\"\"\n size = tensor.size()\n return norm_layer(tensor.view(-1, size[-1])).view(size)\n\n\ndef _create_embeddings(dictionary, embedding_size, padding_idx):\n \"\"\"Create and initialize word embeddings.\"\"\"\n e = nn.Embedding(len(dictionary), embedding_size, padding_idx)\n nn.init.normal_(e.weight, mean=0, std=embedding_size ** -0.5)\n nn.init.constant_(e.weight[padding_idx], 0)\n return e\n\n\ndef _build_encoder(opt, dictionary, embedding=None, padding_idx=None, reduction=True):\n return TransformerEncoder(\n n_heads=opt['n_heads'],\n n_layers=opt['n_layers'],\n embedding_size=opt['embedding_size'],\n ffn_size=opt['ffn_size'],\n vocabulary_size=len(dictionary),\n embedding=embedding,\n attention_dropout=opt['attention_dropout'],\n relu_dropout=opt['relu_dropout'],\n padding_idx=padding_idx,\n learn_positional_embeddings=opt.get('learn_positional_embeddings', False),\n embeddings_scale=opt['embeddings_scale'],\n reduction=reduction,\n )\n\n\ndef _build_decoder(opt, dictionary, embedding=None, padding_idx=None):\n return TransformerDecoder(\n n_heads=opt['n_heads'],\n n_layers=opt['n_layers'],\n embedding_size=opt['embedding_size'],\n ffn_size=opt['ffn_size'],\n vocabulary_size=len(dictionary),\n embedding=embedding,\n attention_dropout=opt['attention_dropout'],\n relu_dropout=opt['relu_dropout'],\n padding_idx=padding_idx,\n learn_positional_embeddings=opt.get('learn_positional_embeddings', False),\n embeddings_scale=opt['embeddings_scale'],\n )\n\n\nclass TransformerMemNetModel(nn.Module):\n \"\"\"Model which takes context, memories, candidates and encodes them\"\"\"\n def __init__(self, opt, dictionary):\n super().__init__()\n self.opt = opt\n self.pad_idx = dictionary[dictionary.null_token]\n self.scores_norm = opt['scores_norm']\n\n # set up embeddings\n self.embeddings = _create_embeddings(\n dictionary, opt['embedding_size'], self.pad_idx\n )\n\n self.context_encoder = _build_encoder(\n opt, dictionary, self.embeddings, self.pad_idx\n )\n\n if opt.get('share_encoders'):\n self.cand_encoder = TransformerResponseWrapper(\n self.context_encoder, self.context_encoder.out_dim, reduction=True,\n )\n else:\n self.cand_encoder = _build_encoder(\n opt, dictionary, self.embeddings, self.pad_idx, reduction=True,\n )\n\n # build memory encoder\n if opt.get('wrap_memory_encoder', False):\n self.memory_transformer = TransformerResponseWrapper(\n self.context_encoder, self.context_encoder.out_dim\n )\n else:\n self.memory_transformer = self.context_encoder\n\n self.attender = BasicAttention(dim=2, attn=opt['memory_attention'])\n\n def encode_cand(self, words):\n if words is None:\n return None\n\n # flatten if there are many candidates\n if words.dim() == 3:\n oldshape = words.shape\n words = words.reshape(oldshape[0] * oldshape[1], oldshape[2])\n else:\n oldshape = None\n\n encoded = self.cand_encoder(words)\n\n if oldshape is not None:\n encoded = encoded.reshape(oldshape[0], oldshape[1], -1)\n\n return encoded\n\n def encode_context_memory(self, context_w, memories_w):\n # [batch, d]\n context_h = self.context_encoder(context_w)\n\n if memories_w is None:\n return [], context_h\n\n bsz = memories_w.size(0)\n memories_w = memories_w.view(-1, memories_w.size(-1))\n memories_h = self.memory_transformer(memories_w)\n memories_h = memories_h.view(bsz, -1, memories_h.size(-1))\n\n context_h = context_h.unsqueeze(1)\n context_h, weights = self.attender(context_h, memories_h)\n\n return weights, context_h\n\n def _score(self, output, cands):\n if cands.dim() == 2:\n return torch.matmul(output, cands.t())\n elif cands.dim() == 3:\n return torch.bmm(output.unsqueeze(1),\n cands.transpose(1, 2)).squeeze(1)\n else:\n raise RuntimeError('Unexpected candidate dimensions {}'\n ''.format(cands.dim()))\n\n def forward(self, xs, mems, cands):\n weights, context_h = self.encode_context_memory(xs, mems)\n cands_h = self.encode_cand(cands)\n\n if self.opt['normalize_sent_emb']:\n context_h = context_h / context_h.norm(2, dim=1, keepdim=True)\n cands_h = cands_h / cands_h.norm(2, dim=1, keepdim=True)\n\n scores = self._score(context_h, cands_h)\n if self.scores_norm == 'dot':\n pass\n elif self.scores_norm == 'sqrt':\n scores /= math.sqrt(self.opt['embedding_size'])\n elif self.scores_norm == 'dim':\n scores /= self.opt['embedding_size']\n else:\n raise ValueError('Invalid --scores-norm')\n\n return scores\n\n\ndef create_position_codes(n_pos, dim, out):\n position_enc = np.array([\n [pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)]\n for pos in range(n_pos)\n ])\n\n out[:, 0::2] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))\n out[:, 1::2] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))\n out.detach_()\n out.requires_grad = False\n\n\nclass TransformerResponseWrapper(nn.Module):\n \"\"\"Transformer response rapper. Pushes input through transformer and MLP\"\"\"\n def __init__(self, transformer, hdim):\n super(TransformerResponseWrapper, self).__init__()\n dim = transformer.out_dim\n self.transformer = transformer\n self.mlp = nn.Sequential(\n nn.Linear(dim, hdim),\n nn.ReLU(),\n nn.Linear(hdim, dim)\n )\n\n def forward(self, *args):\n return self.mlp(self.transformer(*args))\n\n\nclass TransformerEncoder(nn.Module):\n \"\"\"Transformer model\"\"\"\n def __init__(\n self,\n n_heads,\n n_layers,\n embedding_size,\n ffn_size,\n vocabulary_size,\n embedding=None,\n attention_dropout=0.0,\n relu_dropout=0.0,\n padding_idx=0,\n learn_positional_embeddings=False,\n embeddings_scale=False,\n reduction=True,\n ):\n super(TransformerEncoder, self).__init__()\n\n self.embedding_size = embedding_size\n self.ffn_size = ffn_size\n self.n_layers = n_layers\n self.n_heads = n_heads\n self.dim = embedding_size\n self.embeddings_scale = embeddings_scale\n self.reduction = reduction\n self.padding_idx = padding_idx\n\n self.out_dim = embedding_size\n assert embedding_size % n_heads == 0, \\\n 'Transformer embedding size must be a multiple of n_heads'\n n_positions = 1024 # TODO: use truncate or sth\n\n # check input formats:\n if embedding is not None:\n assert (\n embedding_size is None or embedding_size == embedding.weight.shape[1]\n ), \"Embedding dim must match the embedding size.\"\n\n if embedding is not None:\n self.embeddings = embedding\n else:\n assert False\n assert padding_idx is not None\n self.embeddings = nn.Embedding(\n vocabulary_size, embedding_size, padding_idx=padding_idx\n )\n nn.init.normal_(self.embeddings.weight, 0, embedding_size ** -0.5)\n\n # create the positional embeddings\n self.position_embeddings = nn.Embedding(n_positions, embedding_size)\n if not learn_positional_embeddings:\n create_position_codes(\n n_positions, embedding_size, out=self.position_embeddings.weight\n )\n else:\n nn.init.normal_(self.position_embeddings.weight, 0, embedding_size ** -0.5)\n\n # build the model\n self.layers = nn.ModuleList()\n for _ in range(self.n_layers):\n self.layers.append(TransformerEncoderLayer(\n n_heads, embedding_size, ffn_size, attention_dropout, relu_dropout\n ))\n\n def forward(self, input):\n \"\"\"\n input data is a FloatTensor of shape [batch, seq_len, dim]\n mask is a ByteTensor of shape [batch, seq_len], filled with 1 when\n inside the sequence and 0 outside.\n \"\"\"\n mask = input != self.padding_idx\n seq_len = input.size(1)\n positions = input.new(seq_len).long()\n positions = torch.arange(seq_len, out=positions).unsqueeze(0)\n tensor = self.embeddings(input)\n if self.embeddings_scale:\n tensor = tensor * np.sqrt(self.dim)\n tensor = tensor + self.position_embeddings(positions).expand_as(tensor)\n\n tensor *= mask.unsqueeze(-1).float()\n for i in range(self.n_layers):\n tensor = self.layers[i](tensor, mask)\n\n if self.reduction:\n divisor = mask.float().sum(dim=1).unsqueeze(-1).clamp(min=1e-20)\n output = tensor.sum(dim=1) / divisor\n return output\n else:\n output = tensor\n return output, mask\n\n\nclass TransformerEncoderLayer(nn.Module):\n def __init__(\n self,\n n_heads,\n embedding_size,\n ffn_size,\n attention_dropout=0.0,\n relu_dropout=0.0,\n ):\n super().__init__()\n self.dim = embedding_size\n self.ffn_dim = ffn_size\n self.attention = MultiHeadAttention(\n n_heads, embedding_size, dropout=attention_dropout\n )\n self.norm1 = nn.LayerNorm(embedding_size)\n self.ffn = TransformerFFN(embedding_size, ffn_size, dropout=relu_dropout)\n self.norm2 = nn.LayerNorm(embedding_size)\n\n def forward(self, tensor, mask):\n tensor = tensor + self.attention(tensor, mask=mask)\n tensor = _normalize(tensor, self.norm1)\n tensor = tensor + self.ffn(tensor)\n tensor = _normalize(tensor, self.norm2)\n tensor *= mask.unsqueeze(-1).float()\n return tensor\n\n\nclass TransformerDecoder(nn.Module):\n def __init__(\n self,\n n_heads,\n n_layers,\n embedding_size,\n ffn_size,\n vocabulary_size,\n embedding=None,\n attention_dropout=0.0,\n relu_dropout=0.0,\n embeddings_scale=True,\n learn_positional_embeddings=False,\n padding_idx=None,\n ):\n super().__init__()\n self.embedding_size = embedding_size\n self.ffn_size = ffn_size\n self.n_layers = n_layers\n self.n_heads = n_heads\n self.dim = embedding_size\n self.embeddings_scale = embeddings_scale\n\n self.out_dim = embedding_size\n assert embedding_size % n_heads == 0, \\\n 'Transformer embedding size must be a multiple of n_heads'\n n_positions = 1024 # TODO: use truncate or sth\n\n self.embeddings = embedding\n\n # create the positional embeddings\n self.position_embeddings = nn.Embedding(n_positions, embedding_size)\n if not learn_positional_embeddings:\n create_position_codes(\n n_positions, embedding_size, out=self.position_embeddings.weight\n )\n else:\n nn.init.normal_(self.position_embeddings.weight, 0, embedding_size ** -0.5)\n\n # build the model\n self.layers = nn.ModuleList()\n for _ in range(self.n_layers):\n self.layers.append(TransformerDecoderLayer(\n n_heads, embedding_size, ffn_size, attention_dropout, relu_dropout\n ))\n\n def forward(self, input, encoder_state, incr_state=None):\n encoder_output, encoder_mask = encoder_state\n\n seq_len = input.size(1)\n positions = input.new(seq_len).long()\n positions = torch.arange(seq_len, out=positions).unsqueeze(0)\n tensor = self.embeddings(input)\n if self.embeddings_scale:\n tensor = tensor * np.sqrt(self.dim)\n tensor = tensor + self.position_embeddings(positions).expand_as(tensor)\n\n for layer in self.layers:\n tensor = layer(tensor, encoder_output, encoder_mask)\n\n return tensor, None\n\n\nclass TransformerDecoderLayer(nn.Module):\n def __init__(\n self,\n n_heads,\n embedding_size,\n ffn_size,\n attention_dropout=0.0,\n relu_dropout=0.0,\n ):\n super().__init__()\n self.dim = embedding_size\n self.ffn_dim = ffn_size\n\n self.self_attention = MultiHeadAttention(\n n_heads, embedding_size, dropout=attention_dropout\n )\n self.norm1 = nn.LayerNorm(embedding_size)\n\n self.encoder_attention = MultiHeadAttention(\n n_heads, embedding_size, dropout=attention_dropout\n )\n self.norm2 = nn.LayerNorm(embedding_size)\n\n self.ffn = TransformerFFN(embedding_size, ffn_size, dropout=relu_dropout)\n self.norm3 = nn.LayerNorm(embedding_size)\n\n def forward(self, x, encoder_output, encoder_mask):\n decoder_mask = self._create_selfattn_mask(x)\n # first self attn\n residual = x\n # don't peak into the future!\n x = self.self_attention(query=x, mask=decoder_mask)\n # x = dropout(x)\n x = x + residual\n x = _normalize(x, self.norm1)\n\n residual = x\n x = self.encoder_attention(\n query=x,\n key=encoder_output,\n value=encoder_output,\n mask=encoder_mask\n )\n # x = dropout(x)\n x = residual + x\n x = _normalize(x, self.norm2)\n\n # finally the ffn\n residual = x\n x = self.ffn(x)\n x = residual + x\n x = _normalize(x, self.norm3)\n\n return x\n\n def _create_selfattn_mask(self, x):\n # figure out how many timestamps we need\n bsz = x.size(0)\n time = x.size(1)\n # make sure that we don't look into the future\n mask = torch.tril(x.new(time, time).fill_(1))\n # broadcast across batch\n mask = mask.unsqueeze(0).expand(bsz, -1, -1)\n return mask\n\n\nclass TransformerGeneratorModel(TorchGeneratorModel):\n def __init__(self, opt, dictionary):\n super().__init__()\n self.pad_idx = dictionary[dictionary.null_token]\n self.embeddings = _create_embeddings(\n dictionary, opt['embedding_size'], self.pad_idx\n )\n self.encoder = _build_encoder(\n opt, dictionary, self.embeddings, self.pad_idx, reduction=False\n )\n self.decoder = _build_decoder(opt, dictionary, self.embeddings, self.pad_idx)\n\n def reorder_encoder_states(self, encoder_states, indices):\n enc, mask = encoder_states\n if not torch.is_tensor(indices):\n indices = torch.LongTensor(indices).to(enc.device)\n enc = torch.index_select(enc, 0, indices)\n mask = torch.index_select(mask, 0, indices)\n return enc, mask\n\n def reorder_decoder_incremental_state(self, incremental_state, inds):\n # no support for incremental decoding at this time\n return None\n\n def output(self, tensor):\n # project back to vocabulary\n output = F.linear(tensor, self.embeddings.weight)\n return output\n\n\nclass BasicAttention(nn.Module):\n def __init__(self, dim=1, attn='cosine'):\n super().__init__()\n self.softmax = nn.Softmax(dim=dim)\n if attn == 'cosine':\n self.cosine = nn.CosineSimilarity(dim=dim)\n self.attn = attn\n self.dim = dim\n\n def forward(self, xs, ys):\n if self.attn == 'cosine':\n l1 = self.cosine(xs, ys).unsqueeze(self.dim - 1)\n else:\n l1 = torch.bmm(xs, ys.transpose(1, 2))\n if self.attn == 'sqrt':\n d_k = ys.size(-1)\n l1 = l1 / math.sqrt(d_k)\n l2 = self.softmax(l1)\n lhs_emb = torch.bmm(l2, ys)\n # add back the query\n lhs_emb = lhs_emb.add(xs)\n\n return lhs_emb.squeeze(self.dim - 1), l2\n\n\nclass MultiHeadAttention(nn.Module):\n def __init__(self, n_heads, dim, dropout=0):\n super(MultiHeadAttention, self).__init__()\n self.n_heads = n_heads\n self.dim = dim\n\n # multi head is seen as one layer, dropout is only applied to the input\n self.dropout = nn.Dropout(p=dropout)\n self.q_lin = nn.Linear(dim, dim)\n self.k_lin = nn.Linear(dim, dim)\n self.v_lin = nn.Linear(dim, dim)\n nn.init.xavier_normal_(self.q_lin.weight)\n nn.init.xavier_normal_(self.k_lin.weight)\n nn.init.xavier_normal_(self.v_lin.weight)\n self.out_lin = nn.Linear(dim, dim)\n\n nn.init.xavier_normal_(self.out_lin.weight)\n\n def forward(self, query, key=None, value=None, mask=None):\n # Input is [B, query_len, dim]\n # Mask is [B, key_len] (selfattn) or [B, key_len, key_len] (enc attn)\n batch_size, query_len, dim = query.size()\n assert dim == self.dim, \\\n f'Dimensions do not match: {dim} query vs {self.dim} configured'\n n_heads = self.n_heads\n dim_per_head = dim // n_heads\n scale = math.sqrt(dim_per_head)\n\n def prepare_head(tensor):\n # input is [batch_size, seq_len, n_heads * dim_per_head]\n # output is [batch_size * n_heads, seq_len, dim_per_head]\n bsz, seq_len, _ = tensor.size()\n tensor = tensor.view(batch_size, tensor.size(1), n_heads, dim_per_head)\n tensor = tensor.transpose(1, 2).contiguous().view(\n batch_size * n_heads,\n seq_len,\n dim_per_head\n )\n return tensor\n\n # q, k, v are the transformed values\n if key is None and value is None:\n # self attention\n key = value = query\n elif value is None:\n # key and value are the same, but query differs\n # self attention\n value = key\n _, key_len, dim = key.size()\n\n q = prepare_head(self.q_lin(query))\n k = prepare_head(self.k_lin(key))\n v = prepare_head(self.v_lin(value))\n\n dot_prod = q.bmm(k.transpose(1, 2))\n # [B * n_heads, query_len, key_len]\n attn_mask = (\n (mask == 0)\n .view(batch_size, 1, -1, key_len)\n .repeat(1, n_heads, 1, 1)\n .expand(batch_size, n_heads, query_len, key_len)\n .view(batch_size * n_heads, query_len, key_len)\n )\n assert attn_mask.shape == dot_prod.shape\n dot_prod.masked_fill_(attn_mask, -float(1e20))\n\n attn_weights = F.softmax(dot_prod / scale, dim=-1)\n\n attentioned = attn_weights.bmm(v)\n attentioned = (\n attentioned\n .view(batch_size, n_heads, query_len, dim_per_head)\n .transpose(1, 2).contiguous()\n .view(batch_size, query_len, dim)\n )\n\n out = self.out_lin(attentioned)\n\n return out\n\n\nclass TransformerFFN(nn.Module):\n def __init__(self, dim, dim_hidden, dropout=0):\n super(TransformerFFN, self).__init__()\n self.dropout = nn.Dropout(p=dropout)\n self.lin1 = nn.Linear(dim, dim_hidden)\n self.lin2 = nn.Linear(dim_hidden, dim)\n nn.init.xavier_uniform_(self.lin1.weight)\n nn.init.xavier_uniform_(self.lin2.weight)\n\n def forward(self, x):\n x = F.relu(self.lin1(x))\n x = self.dropout(x)\n x = self.lin2(x)\n x = self.dropout(x)\n return x\n" ]
[ [ "torch.nn.Linear", "torch.nn.ModuleList", "torch.bmm", "torch.LongTensor", "numpy.cos", "numpy.sin", "torch.nn.LayerNorm", "torch.nn.Softmax", "torch.nn.init.constant_", "torch.is_tensor", "torch.nn.init.normal_", "numpy.sqrt", "torch.index_select", "torch.nn.init.xavier_normal_", "torch.nn.ReLU", "torch.nn.functional.linear", "numpy.power", "torch.nn.functional.softmax", "torch.nn.Dropout", "torch.arange", "torch.nn.init.xavier_uniform_", "torch.nn.CosineSimilarity", "torch.nn.Embedding" ] ]
jancami/edibles
[ "51263b24c5e8aef786692011289b906a810ad2f7" ]
[ "edibles/sightline.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nimport bisect\nfrom lmfit import Parameters\nimport astropy.constants as cst\n\nfrom edibles.models import ContinuumModel, VoigtModel\nfrom edibles.utils.edibles_spectrum import EdiblesSpectrum\n\n\nclass Sightline:\n '''A model of the sightline between the telescope and the target star.\n\n Args:\n Spectrum (EdiblesSpectrum): The input spectrum object\n n_anchors (int): Optional, The number of anchors in the ContinuumSpline\n\n '''\n\n def __init__(self, Spectrum, init_cont=True, n_anchors=4):\n\n self.__dict__.update(Spectrum.__dict__)\n\n self.wave = Spectrum.wave\n self.flux = Spectrum.flux\n self.Spectrum = Spectrum\n\n if init_cont:\n cont_model = ContinuumModel(n_anchors=n_anchors)\n cont_pars = cont_model.guess(self.flux, x=self.wave)\n\n for yname in cont_model.ynames:\n flux_range = np.max(self.flux) - np.min(self.flux)\n ymin = cont_pars[yname].value - (flux_range / 2)\n ymax = cont_pars[yname].value + (flux_range / 2)\n\n cont_pars[yname].set(min=ymin, max=ymax)\n\n self.cont_model = cont_model\n self.cont_model_pars = cont_pars\n\n self.complete_model = cont_model\n self.all_pars = cont_pars\n\n self.peaks = []\n\n self.n_anchors = n_anchors\n self.n_lines = 0\n self.num_prior_lines = 0\n self.source_names = []\n\n self.add_source(\"Telluric\", similar={'b': 2})\n self.add_source(\"Nontelluric\", similar=None)\n\n\n def add_source(self, name, similar=None):\n '''Adds a new source of absorption to the sightline.\n\n The purpose of a source is to hold multiple line models\n together, sometiimes with similar parameters\n\n Args:\n name (str): The name of the absorption source\n similar (dict): A dict of parameters that change with the source,\n not the specific line, default: None, example: similar={'b': 3}\n\n '''\n\n self.source_names.append(name)\n\n\n\n if name == \"Telluric\" and similar is not None:\n\n par = Parameters()\n for key in similar:\n par.add(name + '_' + key, value=similar[key], min=0, max=30)\n\n self.telluric_pars = par\n self.all_pars = self.all_pars + par\n\n\n def add_line(self, name, source=None, pars=None, guess_data=None):\n '''Adds a new line to a given absorption source.\n If no source is given, a new one will be created.\n\n Args:\n name (str): The name of the line\n source (str): the name of the source this line will belong to\n pars (dict): user input parameters\n guess_data (1darray): flux data to guess with\n\n '''\n\n assert source is not None, \"Source must not be None\"\n\n if source not in self.source_names:\n print()\n print('Could not find source \\'{}\\' in source_names.'.format(source))\n print('Creating source \\'{}\\''.format(source))\n self.add_source(source)\n\n new_line = VoigtModel(prefix=source + '_' + name + '_')\n\n if guess_data is not None:\n new_pars = new_line.guess(guess_data, x=self.wave)\n else:\n new_pars = new_line.guess(self.flux, x=self.wave)\n\n if pars is not None:\n for par in pars: # lam_0...\n par_name = source + '_' + name + '_' + par # telluric_line1_lam_0...\n new_pars[par_name].set(value=pars[par])\n\n if source == \"Telluric\":\n b_name = source + '_b'\n new_pars[source + '_' + name + '_b'].set(expr=b_name)\n\n new_pars[source + '_' + name + '_lam_0'].set(\n min=self.Spectrum.xmin, max=self.Spectrum.xmax\n )\n\n self.old_complete_model = self.complete_model\n self.complete_model = self.complete_model * new_line\n\n self.old_all_pars = self.all_pars\n self.all_pars = self.all_pars + new_pars\n\n self.old_cont_model = self.cont_model\n self.old_cont_pars = self.cont_model_pars\n\n if source == \"Telluric\":\n try:\n self.old_telluric_model = self.telluric_model\n self.telluric_model = self.telluric_model * new_line\n except AttributeError:\n self.old_telluric_model = new_line\n self.telluric_model = new_line\n\n try:\n self.old_telluric_pars = self.telluric_pars\n self.telluric_pars = self.telluric_pars + new_pars\n except AttributeError:\n print('Something bad is probably happening')\n self.old_telluric_pars = new_pars\n self.telluric_pars = new_pars\n\n else:\n try:\n self.old_nontelluric_model = self.nontelluric_model\n self.nontelluric_model = self.nontelluric_model * new_line\n except AttributeError:\n self.old_nontelluric_model = new_line\n self.nontelluric_model = new_line\n try:\n self.old_nontelluric_pars = self.nontelluric_pars\n self.nontelluric_pars = self.nontelluric_pars + new_pars\n except AttributeError:\n self.old_nontelluric_pars = new_pars\n self.nontelluric_pars = new_pars\n\n\n lambda_name = source + '_' + name + '_lam_0'\n index = bisect.bisect(self.peaks, new_pars[lambda_name])\n self.peaks.insert(index, new_pars[lambda_name])\n\n self.most_recent = source + '_' + name\n self.n_lines += 1\n\n\n def fit(self, data=None, old=False, x=None, report=False,\n plot=False, weights=None, method='leastsq', **kwargs):\n '''Fits a model to the sightline data given by the EdiblesSpectrum object.\n\n Args:\n data (1darray): Flux data to fit\n params (lmfit.parameter.Parameters): Initial parameters to fit\n model (lmfit.model.CompositeModel): The model to fit, default: self.complete_model\n x (1darray): Wavelength data to fit\n report (bool): default False: If true, prints the report from the fit.\n plot (bool): default False: If true, plots the data and the fit model.\n method (str): The method of fitting. default: leastsq\n\n '''\n if data is None:\n data = self.flux\n if x is None:\n x = self.wave\n\n if old is True:\n model = self.old_complete_model\n params = self.old_all_pars\n else:\n model = self.complete_model\n params = self.all_pars\n\n self.result = model.fit(data=data,\n params=params,\n x=x,\n weights=weights,\n method=method,\n **kwargs)\n if report:\n print(self.result.fit_report())\n self.result.params.pretty_print()\n if plot:\n self.result.plot_fit()\n plt.show()\n\n\n # Update parameter values after fit - for use in model separation\n self.all_pars = self.result.params\n\n # create new parameters object and add to it from the results parameters\n if old is False:\n try:\n tell_pars = Parameters()\n for par_name in self.telluric_pars:\n tell_pars.add(self.all_pars[par_name])\n\n # update attribute\n assert len(self.telluric_pars) == len(tell_pars)\n self.telluric_pars = tell_pars\n except AttributeError:\n pass\n\n try:\n non_tell_pars = Parameters()\n for par_name in self.nontelluric_pars:\n non_tell_pars.add(self.all_pars[par_name])\n assert len(self.nontelluric_pars) == len(non_tell_pars)\n self.nontelluric_pars = non_tell_pars\n except AttributeError:\n pass\n\n try:\n cont_pars = Parameters()\n for par_name in self.cont_model_pars:\n cont_pars.add(self.all_pars[par_name])\n assert len(self.cont_model_pars) == len(cont_pars)\n self.cont_model_pars = cont_pars\n except AttributeError:\n pass\n\n\n def freeze(self, pars=None, prefix=None, freeze_cont=True, unfreeze=False):\n '''Freezes the current params, so you can still add to the\n model but the 'old' parameters will not change\n\n Args:\n prefix (str): Prefix of parameters to freeze, default: None, example: 'Telluric'\n freeze_cont (bool): Freeze the continuum or not, default: True\n unfreeze (bool): unfreezes all parameters except x values of\n spline anchors, default=False\n\n '''\n if pars is None:\n pars = self.all_pars\n\n if unfreeze is False:\n if prefix:\n for par in pars:\n if prefix in par:\n pars[par].set(vary=False)\n\n else:\n for par in pars:\n pars[par].set(vary=False)\n\n if not freeze_cont:\n for par in pars:\n if 'y_' in par:\n pars[par].set(vary=True)\n\n if unfreeze is True:\n for par in pars:\n\n if ('y_' in par):\n pars[par].set(vary=True)\n\n if ('Telluric' in par) and (par[-2:] != '_b'):\n pars[par].set(vary=True)\n pars['Telluric_b'].set(vary=True)\n\n if ('Nontelluric' in par) and (par[-2:] != '_d'):\n pars[par].set(vary=True)\n\n\n\n def separate(self, data, x, old=False, plot=True):\n '''Separate the sources that were added to Sightline.\n\n Args:\n data (1darray): FLux data to use for separation\n x (1darray): Wavelength array to use\n old (bool): If true, uses the older, second-most recent model and parameters\n plot (bool): If true, plots separted spectrum\n\n '''\n\n assert len(self.telluric_pars) > 0\n assert len(self.nontelluric_pars) > 0\n\n if old is True:\n model = self.old_complete_model\n params = self.old_all_pars\n telluric_model = self.old_telluric_model\n telluric_params = self.old_telluric_pars\n nontelluric_model = self.old_nontelluric_model\n nontelluric_params = self.old_nontelluric_pars\n cont_model = self.old_cont_model\n cont_params = self.old_cont_pars\n\n else:\n model = self.complete_model\n params = self.all_pars\n telluric_model = self.telluric_model\n telluric_params = self.telluric_pars\n nontelluric_model = self.nontelluric_model\n nontelluric_params = self.nontelluric_pars\n cont_model = self.cont_model\n cont_params = self.cont_model_pars\n\n if len(self.source_names) == 2:\n complete_out = model.eval(\n data=data,\n params=params,\n x=x\n )\n telluric_out = telluric_model.eval(\n data=data,\n params=telluric_params,\n x=x\n )\n nontelluric_out = nontelluric_model.eval(\n data=data,\n params=nontelluric_params,\n x=x\n )\n cont_out = cont_model.eval(\n data=data,\n params=cont_params,\n x=x\n )\n\n if plot:\n\n plt.plot(x, data, label='Data', color='k')\n plt.plot(x, complete_out, label='Final model', color='r')\n plt.plot(x, data - complete_out, label='Residual', color='g')\n plt.plot(x, telluric_out * cont_out, label='Telluric model')\n plt.plot(x, nontelluric_out * cont_out, label='Non-telluric model')\n plt.xlabel(r'Wavelength ($\\AA$)', fontsize=14)\n plt.ylabel('Flux', fontsize=14)\n plt.legend()\n\n plt.show()\n\n return complete_out, telluric_out, nontelluric_out, cont_out\n\n\nif __name__ == \"__main__\":\n\n\n FILE1 = \"/HD170740/RED_860/HD170740_w860_redl_20140915_O12.fits\"\n xmin = 7661.75\n xmax = 7669\n\n sp1 = EdiblesSpectrum(FILE1)\n sp1.getSpectrum(xmin=xmin, xmax=xmax)\n\n sightline = Sightline(sp1, n_anchors=5)\n\n\n # Add line with auto-guessed params\n sightline.add_line(name='line1', source='Telluric')\n\n # Add line with user defined params\n pars = {'d': 0.01, 'tau_0': 0.6, 'lam_0': 7664.8}\n sightline.add_line(name='line2', pars=pars, source='Telluric')\n\n\n # # ###############################################################\n # # Fit and plot\n sightline.fit(report=True, plot=False, method='leastsq')\n\n out = sightline.complete_model.eval(data=sp1.flux, params=sightline.result.params, x=sp1.wave)\n resid = sp1.flux - out\n\n\n\n # Add line with different source\n\n lam_0 = 7665.25\n\n K_Gamma = 3.820e7\n K_d = K_Gamma * lam_0**2 / (4 * np.pi * (cst.c.to(\"cm/s\").value * 1e8))\n\n\n pars = {'d': K_d, 'tau_0': 0.07, 'lam_0': lam_0}\n sightline.add_line(name='line3', source='Nontelluric', pars=pars)\n sightline.all_pars['Nontelluric_line3_d'].set(vary=False)\n\n # sightline.fit(report=True, plot=False, method='leastsq')\n # out = sightline.complete_model.eval(data=sp1.flux, params=sightline.result.params, x=sp1.wave)\n # resid = sp1.flux - out\n\n\n lam_0 = 7665.33\n pars = {'d': K_d, 'tau_0': 0.01, 'b': 1, 'lam_0': lam_0}\n sightline.add_line(name='line4', source='Nontelluric', pars=pars)\n sightline.all_pars['Nontelluric_line4_d'].set(vary=False)\n # sightline.fit(report=True, plot=False, method='leastsq')\n\n\n lam_0 = 7665.15\n pars = {'d': K_d, 'tau_0': 0.001, 'b': 1, 'lam_0': lam_0}\n sightline.add_line(name='line5', source='Nontelluric', pars=pars)\n sightline.all_pars['Nontelluric_line5_d'].set(vary=False)\n sightline.fit(report=True, plot=False, method='leastsq')\n\n\n\n\n\n pars = {'d': 0.01, 'tau_0': 0.01, 'b': 1, 'lam_0': 7662}\n sightline.add_line(name='line6', source='Telluric', pars=pars)\n sightline.fit(report=True, plot=False, method='leastsq')\n\n\n\n pars = {'d': 0.01, 'tau_0': 0.01, 'b': 1, 'lam_0': 7663.7}\n sightline.add_line(name='line7', source='Telluric', pars=pars)\n sightline.fit(report=True, plot=False, method='leastsq')\n\n\n pars = {'d': 0.01, 'tau_0': 0.01, 'b': 1, 'lam_0': 7666.5}\n sightline.add_line(name='line8', source='Telluric', pars=pars)\n sightline.fit(report=True, plot=False, method='leastsq')\n\n\n pars = {'d': 0.01, 'tau_0': 0.01, 'b': 1, 'lam_0': 7667.5}\n sightline.add_line(name='line9', source='Telluric', pars=pars)\n sightline.fit(report=True, plot=False, method='leastsq')\n\n\n\n\n\n\n out = sightline.complete_model.eval(data=sp1.interp_flux, params=sightline.result.params,\n x=sp1.grid)\n resid = sp1.interp_flux - out\n\n\n plt.plot(sp1.grid, sp1.interp_flux)\n plt.plot(sp1.grid, out)\n plt.plot(sp1.grid, resid)\n plt.show()\n\n sightline.separate(data=sp1.interp_flux, x=sp1.grid)\n" ]
[ [ "numpy.max", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.legend", "numpy.min", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.show" ] ]
idnowgmbh/tensorflow
[ "8fb93c17234af9383aee3a911d5443e124f2988d" ]
[ "tensorflow/contrib/distributions/python/ops/gamma.py" ]
[ "# Copyright 2016 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\"\"\"The Gamma distribution class.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.contrib.distributions.python.ops import distribution # pylint: disable=line-too-long\nfrom tensorflow.contrib.framework.python.framework import tensor_util as contrib_tensor_util # pylint: disable=line-too-long\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import check_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import random_ops\n\n\nclass Gamma(distribution.Distribution):\n \"\"\"The `Gamma` distribution with parameter alpha and beta.\n\n The parameters are the shape and inverse scale parameters alpha, beta.\n\n The PDF of this distribution is:\n\n ```pdf(x) = (beta^alpha)(x^(alpha-1))e^(-x*beta)/Gamma(alpha), x > 0```\n\n and the CDF of this distribution is:\n\n ```cdf(x) = GammaInc(alpha, beta * x) / Gamma(alpha), x > 0```\n\n where GammaInc is the incomplete lower Gamma function.\n\n Examples:\n\n ```python\n dist = Gamma(alpha=3.0, beta=2.0)\n dist2 = Gamma(alpha=[3.0, 4.0], beta=[2.0, 3.0])\n ```\n\n \"\"\"\n\n def __init__(self,\n alpha,\n beta,\n validate_args=True,\n allow_nan_stats=False,\n name=\"Gamma\"):\n \"\"\"Construct Gamma distributions with parameters `alpha` and `beta`.\n\n The parameters `alpha` and `beta` must be shaped in a way that supports\n broadcasting (e.g. `alpha + beta` is a valid operation).\n\n Args:\n alpha: Floating point tensor, the shape params of the\n distribution(s).\n alpha must contain only positive values.\n beta: Floating point tensor, the inverse scale params of the\n distribution(s).\n beta must contain only positive values.\n validate_args: Whether to assert that `a > 0, b > 0`, and that `x > 0` in\n the methods `prob(x)` and `log_prob(x)`. If `validate_args` is `False`\n and the inputs are invalid, correct behavior is not guaranteed.\n allow_nan_stats: Boolean, default `False`. If `False`, raise an\n exception if a statistic (e.g. mean/mode/etc...) is undefined for any\n batch member. If `True`, batch members with valid parameters leading to\n undefined statistics will return NaN for this statistic.\n name: The name to prepend to all ops created by this distribution.\n\n Raises:\n TypeError: if `alpha` and `beta` are different dtypes.\n \"\"\"\n self._allow_nan_stats = allow_nan_stats\n self._validate_args = validate_args\n with ops.name_scope(name, values=[alpha, beta]) as scope:\n self._name = scope\n with ops.control_dependencies([check_ops.assert_positive(\n alpha), check_ops.assert_positive(beta)] if validate_args else []):\n alpha = array_ops.identity(alpha, name=\"alpha\")\n beta = array_ops.identity(beta, name=\"beta\")\n\n contrib_tensor_util.assert_same_float_dtype((alpha, beta))\n self._broadcast_tensor = alpha + beta\n\n self._get_batch_shape = self._broadcast_tensor.get_shape()\n self._get_event_shape = tensor_shape.TensorShape([])\n\n self._alpha = alpha\n self._beta = beta\n\n @property\n def allow_nan_stats(self):\n \"\"\"Boolean describing behavior when a stat is undefined for batch member.\"\"\"\n return self._allow_nan_stats\n\n @property\n def validate_args(self):\n \"\"\"Boolean describing behavior on invalid input.\"\"\"\n return self._validate_args\n\n @property\n def name(self):\n \"\"\"Name to prepend to all ops.\"\"\"\n return self._name\n\n @property\n def dtype(self):\n \"\"\"dtype of samples from this distribution.\"\"\"\n return self._alpha.dtype\n\n @property\n def alpha(self):\n \"\"\"Shape parameter.\"\"\"\n return self._alpha\n\n @property\n def beta(self):\n \"\"\"Inverse scale parameter.\"\"\"\n return self._beta\n\n def batch_shape(self, name=\"batch_shape\"):\n \"\"\"Batch dimensions of this instance as a 1-D int32 `Tensor`.\n\n The product of the dimensions of the `batch_shape` is the number of\n independent distributions of this kind the instance represents.\n\n Args:\n name: name to give to the op\n\n Returns:\n `Tensor` `batch_shape`\n \"\"\"\n with ops.name_scope(self.name):\n with ops.name_scope(name, values=[self._broadcast_tensor]):\n return array_ops.shape(self._broadcast_tensor)\n\n def get_batch_shape(self):\n \"\"\"`TensorShape` available at graph construction time.\n\n Same meaning as `batch_shape`. May be only partially defined.\n\n Returns:\n `TensorShape` object.\n \"\"\"\n return self._get_batch_shape\n\n def event_shape(self, name=\"event_shape\"):\n \"\"\"Shape of a sample from a single distribution as a 1-D int32 `Tensor`.\n\n Args:\n name: name to give to the op\n\n Returns:\n `Tensor` `event_shape`\n \"\"\"\n with ops.name_scope(self.name):\n with ops.name_scope(name):\n return constant_op.constant([], dtype=dtypes.int32)\n\n def get_event_shape(self):\n \"\"\"`TensorShape` available at graph construction time.\n\n Same meaning as `event_shape`. May be only partially defined.\n\n Returns:\n `TensorShape` object.\n \"\"\"\n return self._get_event_shape\n\n def mean(self, name=\"mean\"):\n \"\"\"Mean of each batch member.\"\"\"\n with ops.name_scope(self.name):\n with ops.name_scope(name, values=[self._alpha, self._beta]):\n return self._alpha / self._beta\n\n def mode(self, name=\"mode\"):\n \"\"\"Mode of each batch member.\n\n The mode of a gamma distribution is `(alpha - 1) / beta` when `alpha > 1`,\n and `NaN` otherwise. If `self.allow_nan_stats` is `False`, an exception\n will be raised rather than returning `NaN`.\n\n Args:\n name: A name to give this op.\n\n Returns:\n The mode for every batch member, a `Tensor` with same `dtype` as self.\n \"\"\"\n alpha = self._alpha\n beta = self._beta\n with ops.name_scope(self.name):\n with ops.name_scope(name, values=[alpha, beta]):\n mode_if_defined = (alpha - 1.0) / beta\n if self.allow_nan_stats:\n alpha_ge_1 = alpha >= 1.0\n nan = np.nan * self._ones()\n return math_ops.select(alpha_ge_1, mode_if_defined, nan)\n else:\n one = constant_op.constant(1.0, dtype=self.dtype)\n return control_flow_ops.with_dependencies(\n [check_ops.assert_less(\n one, alpha,\n message=\"mode not defined for components of alpha <= 1\"\n )], mode_if_defined)\n\n def variance(self, name=\"variance\"):\n \"\"\"Variance of each batch member.\"\"\"\n with ops.name_scope(self.name):\n with ops.name_scope(name, values=[self._alpha, self._beta]):\n return self._alpha / math_ops.square(self._beta)\n\n def std(self, name=\"std\"):\n \"\"\"Standard deviation of this distribution.\"\"\"\n with ops.name_scope(self.name):\n with ops.name_scope(name, values=[self._alpha, self._beta]):\n return math_ops.sqrt(self._alpha) / self._beta\n\n def log_prob(self, x, name=\"log_prob\"):\n \"\"\"Log prob of observations in `x` under these Gamma distribution(s).\n\n Args:\n x: tensor of dtype `dtype`, must be broadcastable with `alpha` and `beta`.\n name: The name to give this op.\n\n Returns:\n log_prob: tensor of dtype `dtype`, the log-PDFs of `x`.\n\n Raises:\n TypeError: if `x` and `alpha` are different dtypes.\n \"\"\"\n with ops.name_scope(self.name):\n with ops.name_scope(name, values=[self._alpha, self._beta, x]):\n alpha = self._alpha\n beta = self._beta\n x = ops.convert_to_tensor(x)\n x = control_flow_ops.with_dependencies([check_ops.assert_positive(x)] if\n self.validate_args else [], x)\n contrib_tensor_util.assert_same_float_dtype(tensors=[x,],\n dtype=self.dtype)\n\n return (alpha * math_ops.log(beta) + (alpha - 1) * math_ops.log(x) -\n beta * x - math_ops.lgamma(self._alpha))\n\n def prob(self, x, name=\"prob\"):\n \"\"\"Pdf of observations in `x` under these Gamma distribution(s).\n\n Args:\n x: tensor of dtype `dtype`, must be broadcastable with `alpha` and `beta`.\n name: The name to give this op.\n\n Returns:\n prob: tensor of dtype `dtype`, the PDFs of `x`\n\n Raises:\n TypeError: if `x` and `alpha` are different dtypes.\n \"\"\"\n return super(Gamma, self).prob(x, name)\n\n def log_cdf(self, x, name=\"log_cdf\"):\n \"\"\"Log CDF of observations `x` under these Gamma distribution(s).\n\n Args:\n x: tensor of dtype `dtype`, must be broadcastable with `alpha` and `beta`.\n name: The name to give this op.\n\n Returns:\n log_cdf: tensor of dtype `dtype`, the log-CDFs of `x`.\n \"\"\"\n with ops.name_scope(self.name):\n with ops.name_scope(name, values=[self._alpha, self._beta, x]):\n x = ops.convert_to_tensor(x)\n x = control_flow_ops.with_dependencies([check_ops.assert_positive(x)] if\n self.validate_args else [], x)\n contrib_tensor_util.assert_same_float_dtype(tensors=[x,],\n dtype=self.dtype)\n # Note that igamma returns the regularized incomplete gamma function,\n # which is what we want for the CDF.\n return math_ops.log(math_ops.igamma(self._alpha, self._beta * x))\n\n def cdf(self, x, name=\"cdf\"):\n \"\"\"CDF of observations `x` under these Gamma distribution(s).\n\n Args:\n x: tensor of dtype `dtype`, must be broadcastable with `alpha` and `beta`.\n name: The name to give this op.\n\n Returns:\n cdf: tensor of dtype `dtype`, the CDFs of `x`.\n \"\"\"\n with ops.name_scope(self.name):\n with ops.name_scope(name, values=[self._alpha, self._beta, x]):\n return math_ops.igamma(self._alpha, self._beta * x)\n\n def entropy(self, name=\"entropy\"):\n \"\"\"The entropy of Gamma distribution(s).\n\n This is defined to be\n\n ```\n entropy = alpha - log(beta) + log(Gamma(alpha))\n + (1-alpha)digamma(alpha)\n ```\n\n where digamma(alpha) is the digamma function.\n\n Args:\n name: The name to give this op.\n\n Returns:\n entropy: tensor of dtype `dtype`, the entropy.\n \"\"\"\n with ops.name_scope(self.name):\n with ops.name_scope(name, values=[self.alpha, self._beta]):\n alpha = self._alpha\n beta = self._beta\n return (alpha - math_ops.log(beta) + math_ops.lgamma(alpha) +\n (1 - alpha) * math_ops.digamma(alpha))\n\n def sample_n(self, n, seed=None, name=\"sample_n\"):\n \"\"\"Draws `n` samples from the Gamma distribution(s).\n\n See the doc for tf.random_gamma for further detail.\n\n Args:\n n: Python integer, the number of observations to sample from each\n distribution.\n seed: Python integer, the random seed for this operation.\n name: Optional name for the operation.\n\n Returns:\n samples: a `Tensor` of shape `(n,) + self.batch_shape + self.event_shape`\n with values of type `self.dtype`.\n \"\"\"\n with ops.name_scope(self.name, values=[n, self.alpha, self._beta]):\n return random_ops.random_gamma([n],\n self.alpha,\n beta=self._beta,\n dtype=self.dtype,\n seed=seed,\n name=name)\n\n @property\n def is_reparameterized(self):\n return False\n\n def _ones(self):\n return array_ops.ones_like(self._alpha + self._beta, dtype=self.dtype)\n\n @property\n def is_continuous(self):\n return True\n" ]
[ [ "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.ops.math_ops.select", "tensorflow.python.ops.math_ops.log", "tensorflow.python.ops.math_ops.lgamma", "tensorflow.python.framework.constant_op.constant", "tensorflow.python.ops.random_ops.random_gamma", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.ops.math_ops.igamma", "tensorflow.python.ops.math_ops.square", "tensorflow.python.ops.array_ops.ones_like", "tensorflow.python.ops.check_ops.assert_positive", "tensorflow.python.ops.check_ops.assert_less", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.math_ops.sqrt", "tensorflow.contrib.framework.python.framework.tensor_util.assert_same_float_dtype", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.ops.math_ops.digamma" ] ]
datawowio/automl
[ "0b368fdc0ff7aaa4f0ade0a5825f3d0a36fb4691" ]
[ "efficientdet/aug/autoaugment.py" ]
[ "# Copyright 2020 Google Research. 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\"\"\"AutoAugment.\n\n[1] Barret, et al. Learning Data Augmentation Strategies for Object Detection.\n Arxiv: https://arxiv.org/abs/1906.11172\n\"\"\"\nimport inspect\nimport math\nfrom absl import logging\nimport tensorflow.compat.v1 as tf\nfrom tensorflow_addons import image as image_ops\n\nimport hparams_config\n\n# This signifies the max integer that the controller RNN could predict for the\n# augmentation scheme.\n_MAX_LEVEL = 10.\n\n# Represents an invalid bounding box that is used for checking for padding\n# lists of bounding box coordinates for a few augmentation operations\n_INVALID_BOX = [[-1.0, -1.0, -1.0, -1.0]]\n\n\ndef policy_v0():\n \"\"\"Autoaugment policy that was used in AutoAugment Detection Paper.\"\"\"\n # Each tuple is an augmentation operation of the form\n # (operation, probability, magnitude). Each element in policy is a\n # sub-policy that will be applied sequentially on the image.\n policy = [\n [('TranslateX_BBox', 0.6, 4), ('Equalize', 0.8, 10)],\n [('TranslateY_Only_BBoxes', 0.2, 2), ('Cutout', 0.8, 8)],\n [('Sharpness', 0.0, 8), ('ShearX_BBox', 0.4, 0)],\n [('ShearY_BBox', 1.0, 2), ('TranslateY_Only_BBoxes', 0.6, 6)],\n [('Rotate_BBox', 0.6, 10), ('Color', 1.0, 6)],\n ]\n return policy\n\n\ndef policy_v1():\n \"\"\"Autoaugment policy that was used in AutoAugment Detection Paper.\"\"\"\n # Each tuple is an augmentation operation of the form\n # (operation, probability, magnitude). Each element in policy is a\n # sub-policy that will be applied sequentially on the image.\n policy = [\n [('TranslateX_BBox', 0.6, 4), ('Equalize', 0.8, 10)],\n [('TranslateY_Only_BBoxes', 0.2, 2), ('Cutout', 0.8, 8)],\n [('Sharpness', 0.0, 8), ('ShearX_BBox', 0.4, 0)],\n [('ShearY_BBox', 1.0, 2), ('TranslateY_Only_BBoxes', 0.6, 6)],\n [('Rotate_BBox', 0.6, 10), ('Color', 1.0, 6)],\n [('Color', 0.0, 0), ('ShearX_Only_BBoxes', 0.8, 4)],\n [('ShearY_Only_BBoxes', 0.8, 2), ('Flip_Only_BBoxes', 0.0, 10)],\n [('Equalize', 0.6, 10), ('TranslateX_BBox', 0.2, 2)],\n [('Color', 1.0, 10), ('TranslateY_Only_BBoxes', 0.4, 6)],\n [('Rotate_BBox', 0.8, 10), ('Contrast', 0.0, 10)],\n [('Cutout', 0.2, 2), ('Brightness', 0.8, 10)],\n [('Color', 1.0, 6), ('Equalize', 1.0, 2)],\n [('Cutout_Only_BBoxes', 0.4, 6), ('TranslateY_Only_BBoxes', 0.8, 2)],\n [('Color', 0.2, 8), ('Rotate_BBox', 0.8, 10)],\n [('Sharpness', 0.4, 4), ('TranslateY_Only_BBoxes', 0.0, 4)],\n [('Sharpness', 1.0, 4), ('SolarizeAdd', 0.4, 4)],\n [('Rotate_BBox', 1.0, 8), ('Sharpness', 0.2, 8)],\n [('ShearY_BBox', 0.6, 10), ('Equalize_Only_BBoxes', 0.6, 8)],\n [('ShearX_BBox', 0.2, 6), ('TranslateY_Only_BBoxes', 0.2, 10)],\n [('SolarizeAdd', 0.6, 8), ('Brightness', 0.8, 10)],\n ]\n return policy\n\n\ndef policy_vtest():\n \"\"\"Autoaugment test policy for debugging.\"\"\"\n # Each tuple is an augmentation operation of the form\n # (operation, probability, magnitude). Each element in policy is a\n # sub-policy that will be applied sequentially on the image.\n policy = [\n [('TranslateX_BBox', 1.0, 4), ('Equalize', 1.0, 10)],\n ]\n return policy\n\n\ndef policy_v2():\n \"\"\"Additional policy that performs well on object detection.\"\"\"\n # Each tuple is an augmentation operation of the form\n # (operation, probability, magnitude). Each element in policy is a\n # sub-policy that will be applied sequentially on the image.\n policy = [\n [('Color', 0.0, 6), ('Cutout', 0.6, 8), ('Sharpness', 0.4, 8)],\n [('Rotate_BBox', 0.4, 8), ('Sharpness', 0.4, 2),\n ('Rotate_BBox', 0.8, 10)],\n [('TranslateY_BBox', 1.0, 8), ('AutoContrast', 0.8, 2)],\n [('AutoContrast', 0.4, 6), ('ShearX_BBox', 0.8, 8),\n ('Brightness', 0.0, 10)],\n [('SolarizeAdd', 0.2, 6), ('Contrast', 0.0, 10),\n ('AutoContrast', 0.6, 0)],\n [('Cutout', 0.2, 0), ('Solarize', 0.8, 8), ('Color', 1.0, 4)],\n [('TranslateY_BBox', 0.0, 4), ('Equalize', 0.6, 8),\n ('Solarize', 0.0, 10)],\n [('TranslateY_BBox', 0.2, 2), ('ShearY_BBox', 0.8, 8),\n ('Rotate_BBox', 0.8, 8)],\n [('Cutout', 0.8, 8), ('Brightness', 0.8, 8), ('Cutout', 0.2, 2)],\n [('Color', 0.8, 4), ('TranslateY_BBox', 1.0, 6), ('Rotate_BBox', 0.6, 6)],\n [('Rotate_BBox', 0.6, 10), ('BBox_Cutout', 1.0, 4), ('Cutout', 0.2, 8)],\n [('Rotate_BBox', 0.0, 0), ('Equalize', 0.6, 6), ('ShearY_BBox', 0.6, 8)],\n [('Brightness', 0.8, 8), ('AutoContrast', 0.4, 2),\n ('Brightness', 0.2, 2)],\n [('TranslateY_BBox', 0.4, 8), ('Solarize', 0.4, 6),\n ('SolarizeAdd', 0.2, 10)],\n [('Contrast', 1.0, 10), ('SolarizeAdd', 0.2, 8), ('Equalize', 0.2, 4)],\n ]\n return policy\n\n\ndef policy_v3():\n \"\"\"\"Additional policy that performs well on object detection.\"\"\"\n # Each tuple is an augmentation operation of the form\n # (operation, probability, magnitude). Each element in policy is a\n # sub-policy that will be applied sequentially on the image.\n policy = [\n [('Posterize', 0.8, 2), ('TranslateX_BBox', 1.0, 8)],\n [('BBox_Cutout', 0.2, 10), ('Sharpness', 1.0, 8)],\n [('Rotate_BBox', 0.6, 8), ('Rotate_BBox', 0.8, 10)],\n [('Equalize', 0.8, 10), ('AutoContrast', 0.2, 10)],\n [('SolarizeAdd', 0.2, 2), ('TranslateY_BBox', 0.2, 8)],\n [('Sharpness', 0.0, 2), ('Color', 0.4, 8)],\n [('Equalize', 1.0, 8), ('TranslateY_BBox', 1.0, 8)],\n [('Posterize', 0.6, 2), ('Rotate_BBox', 0.0, 10)],\n [('AutoContrast', 0.6, 0), ('Rotate_BBox', 1.0, 6)],\n # [('Equalize', 0.0, 4), ('Cutout', 0.8, 10)],\n [('Brightness', 1.0, 2), ('TranslateY_BBox', 1.0, 6)],\n [('Contrast', 0.0, 2), ('ShearY_BBox', 0.8, 0)],\n [('AutoContrast', 0.8, 10), ('Contrast', 0.2, 10)],\n # [('Rotate_BBox', 1.0, 10), ('Cutout', 1.0, 10)],\n [('SolarizeAdd', 0.8, 6), ('Equalize', 0.8, 8)],\n ]\n return policy\n\n\ndef blend(image1, image2, factor):\n \"\"\"Blend image1 and image2 using 'factor'.\n\n Factor can be above 0.0. A value of 0.0 means only image1 is used.\n A value of 1.0 means only image2 is used. A value between 0.0 and\n 1.0 means we linearly interpolate the pixel values between the two\n images. A value greater than 1.0 \"extrapolates\" the difference\n between the two pixel values, and we clip the results to values\n between 0 and 255.\n\n Args:\n image1: An image Tensor of type uint8.\n image2: An image Tensor of type uint8.\n factor: A floating point value above 0.0.\n\n Returns:\n A blended image Tensor of type uint8.\n \"\"\"\n if factor == 0.0:\n return tf.convert_to_tensor(image1)\n if factor == 1.0:\n return tf.convert_to_tensor(image2)\n\n image1 = tf.to_float(image1)\n image2 = tf.to_float(image2)\n\n difference = image2 - image1\n scaled = factor * difference\n\n # Do addition in float.\n temp = tf.to_float(image1) + scaled\n\n # Interpolate\n if factor > 0.0 and factor < 1.0:\n # Interpolation means we always stay within 0 and 255.\n return tf.cast(temp, tf.uint8)\n\n # Extrapolate:\n #\n # We need to clip and then cast.\n return tf.cast(tf.clip_by_value(temp, 0.0, 255.0), tf.uint8)\n\n\ndef cutout(image, pad_size, replace=0):\n \"\"\"Apply cutout (https://arxiv.org/abs/1708.04552) to image.\n\n This operation applies a (2*pad_size x 2*pad_size) mask of zeros to\n a random location within `img`. The pixel values filled in will be of the\n value `replace`. The located where the mask will be applied is randomly\n chosen uniformly over the whole image.\n\n Args:\n image: An image Tensor of type uint8.\n pad_size: Specifies how big the zero mask that will be generated is that\n is applied to the image. The mask will be of size\n (2*pad_size x 2*pad_size).\n replace: What pixel value to fill in the image in the area that has\n the cutout mask applied to it.\n\n Returns:\n An image Tensor that is of type uint8.\n \"\"\"\n image_height = tf.maximum(tf.shape(image)[0], 10)\n image_width = tf.maximum(tf.shape(image)[1], 10)\n\n # Sample the center location in the image where the zero mask will be applied.\n cutout_center_height = tf.random_uniform(\n shape=[], minval=0, maxval=image_height,\n dtype=tf.int32)\n\n cutout_center_width = tf.random_uniform(\n shape=[], minval=0, maxval=image_width,\n dtype=tf.int32)\n\n lower_pad = tf.maximum(0, cutout_center_height - pad_size)\n upper_pad = tf.maximum(0, image_height - cutout_center_height - pad_size)\n left_pad = tf.maximum(0, cutout_center_width - pad_size)\n right_pad = tf.maximum(0, image_width - cutout_center_width - pad_size)\n\n cutout_shape = [image_height - (lower_pad + upper_pad),\n image_width - (left_pad + right_pad)]\n padding_dims = [[lower_pad, upper_pad], [left_pad, right_pad]]\n mask = tf.pad(\n tf.zeros(cutout_shape, dtype=image.dtype),\n padding_dims, constant_values=1)\n mask = tf.expand_dims(mask, -1)\n mask = tf.tile(mask, [1, 1, 3])\n image = tf.where(\n tf.equal(mask, 0),\n tf.ones_like(image, dtype=image.dtype) * replace,\n image)\n return image\n\n\ndef solarize(image, threshold=128):\n # For each pixel in the image, select the pixel\n # if the value is less than the threshold.\n # Otherwise, subtract 255 from the pixel.\n return tf.where(image < threshold, image, 255 - image)\n\n\ndef solarize_add(image, addition=0, threshold=128):\n # For each pixel in the image less than threshold\n # we add 'addition' amount to it and then clip the\n # pixel value to be between 0 and 255. The value\n # of 'addition' is between -128 and 128.\n added_image = tf.cast(image, tf.int64) + addition\n added_image = tf.cast(tf.clip_by_value(added_image, 0, 255), tf.uint8)\n return tf.where(image < threshold, added_image, image)\n\n\ndef color(image, factor):\n \"\"\"Equivalent of PIL Color.\"\"\"\n degenerate = tf.image.grayscale_to_rgb(tf.image.rgb_to_grayscale(image))\n return blend(degenerate, image, factor)\n\n\ndef contrast(image, factor):\n \"\"\"Equivalent of PIL Contrast.\"\"\"\n degenerate = tf.image.rgb_to_grayscale(image)\n # Cast before calling tf.histogram.\n degenerate = tf.cast(degenerate, tf.int32)\n\n # Compute the grayscale histogram, then compute the mean pixel value,\n # and create a constant image size of that value. Use that as the\n # blending degenerate target of the original image.\n mean = tf.reduce_mean(tf.cast(degenerate, tf.float32))\n degenerate = tf.ones_like(degenerate, dtype=tf.float32) * mean\n degenerate = tf.clip_by_value(degenerate, 0.0, 255.0)\n degenerate = tf.image.grayscale_to_rgb(tf.cast(degenerate, tf.uint8))\n return blend(degenerate, image, factor)\n\n\ndef brightness(image, factor):\n \"\"\"Equivalent of PIL Brightness.\"\"\"\n degenerate = tf.zeros_like(image)\n return blend(degenerate, image, factor)\n\n\ndef posterize(image, bits):\n \"\"\"Equivalent of PIL Posterize.\"\"\"\n shift = 8 - bits\n return tf.bitwise.left_shift(tf.bitwise.right_shift(image, shift), shift)\n\n\ndef rotate(image, degrees, replace):\n \"\"\"Rotates the image by degrees either clockwise or counterclockwise.\n\n Args:\n image: An image Tensor of type uint8.\n degrees: Float, a scalar angle in degrees to rotate all images by. If\n degrees is positive the image will be rotated clockwise otherwise it will\n be rotated counterclockwise.\n replace: A one or three value 1D tensor to fill empty pixels caused by\n the rotate operation.\n\n Returns:\n The rotated version of image.\n \"\"\"\n # Convert from degrees to radians.\n degrees_to_radians = math.pi / 180.0\n radians = degrees * degrees_to_radians\n\n # In practice, we should randomize the rotation degrees by flipping\n # it negatively half the time, but that's done on 'degrees' outside\n # of the function.\n image = image_ops.rotate(wrap(image), radians)\n return unwrap(image, replace)\n\n\ndef random_shift_bbox(image, bbox, pixel_scaling, replace,\n new_min_bbox_coords=None):\n \"\"\"Move the bbox and the image content to a slightly new random location.\n\n Args:\n image: 3D uint8 Tensor.\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n The potential values for the new min corner of the bbox will be between\n [old_min - pixel_scaling * bbox_height/2,\n old_min - pixel_scaling * bbox_height/2].\n pixel_scaling: A float between 0 and 1 that specifies the pixel range\n that the new bbox location will be sampled from.\n replace: A one or three value 1D tensor to fill empty pixels.\n new_min_bbox_coords: If not None, then this is a tuple that specifies the\n (min_y, min_x) coordinates of the new bbox. Normally this is randomly\n specified, but this allows it to be manually set. The coordinates are\n the absolute coordinates between 0 and image height/width and are int32.\n\n Returns:\n The new image that will have the shifted bbox location in it along with\n the new bbox that contains the new coordinates.\n \"\"\"\n # Obtains image height and width and create helper clip functions.\n image_height = tf.to_float(tf.maximum(tf.shape(image)[0], 10))\n image_width = tf.to_float(tf.maximum(tf.shape(image)[1], 10))\n def clip_y(val):\n return tf.clip_by_value(val, 0, tf.to_int32(image_height) - 1)\n def clip_x(val):\n return tf.clip_by_value(val, 0, tf.to_int32(image_width) - 1)\n\n # Convert bbox to pixel coordinates.\n min_y = tf.to_int32(image_height * bbox[0])\n min_x = tf.to_int32(image_width * bbox[1])\n max_y = clip_y(tf.to_int32(image_height * bbox[2]))\n max_x = clip_x(tf.to_int32(image_width * bbox[3]))\n bbox_height, bbox_width = (max_y - min_y + 1, max_x - min_x + 1)\n image_height = tf.to_int32(image_height)\n image_width = tf.to_int32(image_width)\n\n # Select the new min/max bbox ranges that are used for sampling the\n # new min x/y coordinates of the shifted bbox.\n minval_y = clip_y(\n min_y - tf.to_int32(pixel_scaling * tf.to_float(bbox_height) / 2.0))\n maxval_y = clip_y(\n min_y + tf.to_int32(pixel_scaling * tf.to_float(bbox_height) / 2.0))\n minval_x = clip_x(\n min_x - tf.to_int32(pixel_scaling * tf.to_float(bbox_width) / 2.0))\n maxval_x = clip_x(\n min_x + tf.to_int32(pixel_scaling * tf.to_float(bbox_width) / 2.0))\n\n # Sample and calculate the new unclipped min/max coordinates of the new bbox.\n if new_min_bbox_coords is None:\n unclipped_new_min_y = tf.random_uniform(\n shape=[], minval=minval_y, maxval=maxval_y,\n dtype=tf.int32)\n unclipped_new_min_x = tf.random_uniform(\n shape=[], minval=minval_x, maxval=maxval_x,\n dtype=tf.int32)\n else:\n unclipped_new_min_y, unclipped_new_min_x = (\n clip_y(new_min_bbox_coords[0]), clip_x(new_min_bbox_coords[1]))\n unclipped_new_max_y = unclipped_new_min_y + bbox_height - 1\n unclipped_new_max_x = unclipped_new_min_x + bbox_width - 1\n\n # Determine if any of the new bbox was shifted outside the current image.\n # This is used for determining if any of the original bbox content should be\n # discarded.\n new_min_y, new_min_x, new_max_y, new_max_x = (\n clip_y(unclipped_new_min_y), clip_x(unclipped_new_min_x),\n clip_y(unclipped_new_max_y), clip_x(unclipped_new_max_x))\n shifted_min_y = (new_min_y - unclipped_new_min_y) + min_y\n shifted_max_y = max_y - (unclipped_new_max_y - new_max_y)\n shifted_min_x = (new_min_x - unclipped_new_min_x) + min_x\n shifted_max_x = max_x - (unclipped_new_max_x - new_max_x)\n\n # Create the new bbox tensor by converting pixel integer values to floats.\n new_bbox = tf.stack([\n tf.to_float(new_min_y) / tf.to_float(image_height),\n tf.to_float(new_min_x) / tf.to_float(image_width),\n tf.to_float(new_max_y) / tf.to_float(image_height),\n tf.to_float(new_max_x) / tf.to_float(image_width)])\n\n # Copy the contents in the bbox and fill the old bbox location\n # with gray (128).\n bbox_content = image[shifted_min_y:shifted_max_y + 1,\n shifted_min_x:shifted_max_x + 1, :]\n\n def mask_and_add_image(\n min_y_, min_x_, max_y_, max_x_, mask, content_tensor, image_):\n \"\"\"Applies mask to bbox region in image then adds content_tensor to it.\"\"\"\n mask = tf.pad(mask,\n [[min_y_, (image_height - 1) - max_y_],\n [min_x_, (image_width - 1) - max_x_],\n [0, 0]], constant_values=1)\n content_tensor = tf.pad(content_tensor,\n [[min_y_, (image_height - 1) - max_y_],\n [min_x_, (image_width - 1) - max_x_],\n [0, 0]], constant_values=0)\n return image_ * mask + content_tensor\n\n # Zero out original bbox location.\n mask = tf.zeros_like(image)[min_y:max_y+1, min_x:max_x+1, :]\n grey_tensor = tf.zeros_like(mask) + replace[0]\n image = mask_and_add_image(min_y, min_x, max_y, max_x, mask,\n grey_tensor, image)\n\n # Fill in bbox content to new bbox location.\n mask = tf.zeros_like(bbox_content)\n image = mask_and_add_image(new_min_y, new_min_x, new_max_y, new_max_x, mask,\n bbox_content, image)\n\n return image, new_bbox\n\n\ndef _clip_bbox(min_y, min_x, max_y, max_x):\n \"\"\"Clip bounding box coordinates between 0 and 1.\n\n Args:\n min_y: Normalized bbox coordinate of type float between 0 and 1.\n min_x: Normalized bbox coordinate of type float between 0 and 1.\n max_y: Normalized bbox coordinate of type float between 0 and 1.\n max_x: Normalized bbox coordinate of type float between 0 and 1.\n\n Returns:\n Clipped coordinate values between 0 and 1.\n \"\"\"\n min_y = tf.clip_by_value(min_y, 0.0, 1.0)\n min_x = tf.clip_by_value(min_x, 0.0, 1.0)\n max_y = tf.clip_by_value(max_y, 0.0, 1.0)\n max_x = tf.clip_by_value(max_x, 0.0, 1.0)\n return min_y, min_x, max_y, max_x\n\n\ndef _check_bbox_area(min_y, min_x, max_y, max_x, delta=0.05):\n \"\"\"Adjusts bbox coordinates to make sure the area is > 0.\n\n Args:\n min_y: Normalized bbox coordinate of type float between 0 and 1.\n min_x: Normalized bbox coordinate of type float between 0 and 1.\n max_y: Normalized bbox coordinate of type float between 0 and 1.\n max_x: Normalized bbox coordinate of type float between 0 and 1.\n delta: Float, this is used to create a gap of size 2 * delta between\n bbox min/max coordinates that are the same on the boundary.\n This prevents the bbox from having an area of zero.\n\n Returns:\n Tuple of new bbox coordinates between 0 and 1 that will now have a\n guaranteed area > 0.\n \"\"\"\n height = max_y - min_y\n width = max_x - min_x\n def _adjust_bbox_boundaries(min_coord, max_coord):\n # Make sure max is never 0 and min is never 1.\n max_coord = tf.maximum(max_coord, 0.0 + delta)\n min_coord = tf.minimum(min_coord, 1.0 - delta)\n return min_coord, max_coord\n min_y, max_y = tf.cond(tf.equal(height, 0.0),\n lambda: _adjust_bbox_boundaries(min_y, max_y),\n lambda: (min_y, max_y))\n min_x, max_x = tf.cond(tf.equal(width, 0.0),\n lambda: _adjust_bbox_boundaries(min_x, max_x),\n lambda: (min_x, max_x))\n return min_y, min_x, max_y, max_x\n\n\ndef _scale_bbox_only_op_probability(prob):\n \"\"\"Reduce the probability of the bbox-only operation.\n\n Probability is reduced so that we do not distort the content of too many\n bounding boxes that are close to each other. The value of 3.0 was a chosen\n hyper parameter when designing the autoaugment algorithm that we found\n empirically to work well.\n\n Args:\n prob: Float that is the probability of applying the bbox-only operation.\n\n Returns:\n Reduced probability.\n \"\"\"\n return prob / 3.0\n\ndef _apply_bbox_augmentation(image, bbox, augmentation_func, *args):\n \"\"\"Applies augmentation_func to the subsection of image indicated by bbox.\n\n Args:\n image: 3D uint8 Tensor.\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n augmentation_func: Augmentation function that will be applied to the\n subsection of image.\n *args: Additional parameters that will be passed into augmentation_func\n when it is called.\n\n Returns:\n A modified version of image, where the bbox location in the image will\n have `ugmentation_func applied to it.\n \"\"\"\n image_height = tf.to_float(tf.maximum(tf.shape(image)[0], 10))\n image_width = tf.to_float(tf.maximum(tf.shape(image)[1], 10))\n\n min_y = tf.to_int32(image_height * bbox[0])\n min_x = tf.to_int32(image_width * bbox[1])\n max_y = tf.to_int32(image_height * bbox[2])\n max_x = tf.to_int32(image_width * bbox[3])\n image_height = tf.to_int32(image_height)\n image_width = tf.to_int32(image_width)\n\n # Clip to be sure the max values do not fall out of range.\n max_y = tf.minimum(max_y, image_height - 1)\n max_x = tf.minimum(max_x, image_width - 1)\n\n # Get the sub-tensor that is the image within the bounding box region.\n bbox_content = image[min_y:max_y + 1, min_x:max_x + 1, :]\n\n # Apply the augmentation function to the bbox portion of the image.\n augmented_bbox_content = augmentation_func(bbox_content, *args)\n\n # Pad the augmented_bbox_content and the mask to match the shape of original\n # image.\n augmented_bbox_content = tf.pad(augmented_bbox_content,\n [[min_y, (image_height - 1) - max_y],\n [min_x, (image_width - 1) - max_x],\n [0, 0]])\n\n # Create a mask that will be used to zero out a part of the original image.\n mask_tensor = tf.zeros_like(bbox_content)\n\n mask_tensor = tf.pad(mask_tensor,\n [[min_y, (image_height - 1) - max_y],\n [min_x, (image_width - 1) - max_x],\n [0, 0]],\n constant_values=1)\n # Replace the old bbox content with the new augmented content.\n image = image * mask_tensor + augmented_bbox_content\n return image\n\n\ndef _concat_bbox(bbox, bboxes):\n \"\"\"Helper function that concats bbox to bboxes along the first dimension.\"\"\"\n\n # Note if all elements in bboxes are -1 (_INVALID_BOX), then this means\n # we discard bboxes and start the bboxes Tensor with the current bbox.\n bboxes_sum_check = tf.reduce_sum(bboxes)\n bbox = tf.expand_dims(bbox, 0)\n # This check will be true when it is an _INVALID_BOX\n bboxes = tf.cond(tf.equal(bboxes_sum_check, -4.0),\n lambda: bbox,\n lambda: tf.concat([bboxes, bbox], 0))\n return bboxes\n\n\ndef _apply_bbox_augmentation_wrapper(image, bbox, new_bboxes, prob,\n augmentation_func, func_changes_bbox,\n *args):\n \"\"\"Applies _apply_bbox_augmentation with probability prob.\n\n Args:\n image: 3D uint8 Tensor.\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n new_bboxes: 2D Tensor that is a list of the bboxes in the image after they\n have been altered by aug_func. These will only be changed when\n func_changes_bbox is set to true. Each bbox has 4 elements\n (min_y, min_x, max_y, max_x) of type float that are the normalized\n bbox coordinates between 0 and 1.\n prob: Float that is the probability of applying _apply_bbox_augmentation.\n augmentation_func: Augmentation function that will be applied to the\n subsection of image.\n func_changes_bbox: Boolean. Does augmentation_func return bbox in addition\n to image.\n *args: Additional parameters that will be passed into augmentation_func\n when it is called.\n\n Returns:\n A tuple. Fist element is a modified version of image, where the bbox\n location in the image will have augmentation_func applied to it if it is\n chosen to be called with probability `prob`. The second element is a\n Tensor of Tensors of length 4 that will contain the altered bbox after\n applying augmentation_func.\n \"\"\"\n should_apply_op = tf.cast(\n tf.floor(tf.random_uniform([], dtype=tf.float32) + prob), tf.bool)\n if func_changes_bbox:\n augmented_image, bbox = tf.cond(\n should_apply_op,\n lambda: augmentation_func(image, bbox, *args),\n lambda: (image, bbox))\n else:\n augmented_image = tf.cond(\n should_apply_op,\n lambda: _apply_bbox_augmentation(image, bbox, augmentation_func, *args),\n lambda: image)\n new_bboxes = _concat_bbox(bbox, new_bboxes)\n return augmented_image, new_bboxes\n\n\ndef _apply_multi_bbox_augmentation(image, bboxes, prob, aug_func,\n func_changes_bbox, *args):\n \"\"\"Applies aug_func to the image for each bbox in bboxes.\n\n Args:\n image: 3D uint8 Tensor.\n bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox\n has 4 elements (min_y, min_x, max_y, max_x) of type float.\n prob: Float that is the probability of applying aug_func to a specific\n bounding box within the image.\n aug_func: Augmentation function that will be applied to the\n subsections of image indicated by the bbox values in bboxes.\n func_changes_bbox: Boolean. Does augmentation_func return bbox in addition\n to image.\n *args: Additional parameters that will be passed into augmentation_func\n when it is called.\n\n Returns:\n A modified version of image, where each bbox location in the image will\n have augmentation_func applied to it if it is chosen to be called with\n probability prob independently across all bboxes. Also the final\n bboxes are returned that will be unchanged if func_changes_bbox is set to\n false and if true, the new altered ones will be returned.\n \"\"\"\n # Will keep track of the new altered bboxes after aug_func is repeatedly\n # applied. The -1 values are a dummy value and this first Tensor will be\n # removed upon appending the first real bbox.\n new_bboxes = tf.constant(_INVALID_BOX)\n\n # If the bboxes are empty, then just give it _INVALID_BOX. The result\n # will be thrown away.\n bboxes = tf.cond(tf.equal(tf.shape(bboxes)[0], 0),\n lambda: tf.constant(_INVALID_BOX),\n lambda: bboxes)\n\n bboxes = tf.ensure_shape(bboxes, (None, 4))\n\n # pylint:disable=g-long-lambda\n # pylint:disable=line-too-long\n wrapped_aug_func = lambda _image, bbox, _new_bboxes: _apply_bbox_augmentation_wrapper(\n _image, bbox, _new_bboxes, prob, aug_func, func_changes_bbox, *args)\n # pylint:enable=g-long-lambda\n # pylint:enable=line-too-long\n\n # Setup the while_loop.\n num_bboxes = tf.shape(bboxes)[0] # We loop until we go over all bboxes.\n idx = tf.constant(0) # Counter for the while loop.\n\n # Conditional function when to end the loop once we go over all bboxes\n # images_and_bboxes contain (_image, _new_bboxes)\n cond = lambda _idx, _images_and_bboxes: tf.less(_idx, num_bboxes)\n\n # Shuffle the bboxes so that the augmentation order is not deterministic if\n # we are not changing the bboxes with aug_func.\n if not func_changes_bbox:\n loop_bboxes = tf.random.shuffle(bboxes)\n else:\n loop_bboxes = bboxes\n\n # Main function of while_loop where we repeatedly apply augmentation on the\n # bboxes in the image.\n # pylint:disable=g-long-lambda\n body = lambda _idx, _images_and_bboxes: [\n _idx + 1, wrapped_aug_func(_images_and_bboxes[0],\n loop_bboxes[_idx],\n _images_and_bboxes[1])]\n # pylint:enable=g-long-lambda\n\n _, (image, new_bboxes) = tf.while_loop(\n cond, body, [idx, (image, new_bboxes)],\n shape_invariants=[idx.get_shape(),\n (image.get_shape(), tf.TensorShape([None, 4]))])\n\n # Either return the altered bboxes or the original ones depending on if\n # we altered them in anyway.\n if func_changes_bbox:\n final_bboxes = new_bboxes\n else:\n final_bboxes = bboxes\n return image, final_bboxes\n\n\ndef _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, aug_func,\n func_changes_bbox, *args):\n \"\"\"Checks to be sure num bboxes > 0 before calling inner function.\"\"\"\n num_bboxes = tf.shape(bboxes)[0]\n image, bboxes = tf.cond(\n tf.equal(num_bboxes, 0),\n lambda: (image, bboxes),\n # pylint:disable=g-long-lambda\n lambda: _apply_multi_bbox_augmentation(\n image, bboxes, prob, aug_func, func_changes_bbox, *args))\n # pylint:enable=g-long-lambda\n return image, bboxes\n\n\ndef rotate_only_bboxes(image, bboxes, prob, degrees, replace):\n \"\"\"Apply rotate to each bbox in the image with probability prob.\"\"\"\n func_changes_bbox = False\n prob = _scale_bbox_only_op_probability(prob)\n return _apply_multi_bbox_augmentation_wrapper(\n image, bboxes, prob, rotate, func_changes_bbox, degrees, replace)\n\n\ndef shear_x_only_bboxes(image, bboxes, prob, level, replace):\n \"\"\"Apply shear_x to each bbox in the image with probability prob.\"\"\"\n func_changes_bbox = False\n prob = _scale_bbox_only_op_probability(prob)\n return _apply_multi_bbox_augmentation_wrapper(\n image, bboxes, prob, shear_x, func_changes_bbox, level, replace)\n\n\ndef shear_y_only_bboxes(image, bboxes, prob, level, replace):\n \"\"\"Apply shear_y to each bbox in the image with probability prob.\"\"\"\n func_changes_bbox = False\n prob = _scale_bbox_only_op_probability(prob)\n return _apply_multi_bbox_augmentation_wrapper(\n image, bboxes, prob, shear_y, func_changes_bbox, level, replace)\n\n\ndef translate_x_only_bboxes(image, bboxes, prob, pixels, replace):\n \"\"\"Apply translate_x to each bbox in the image with probability prob.\"\"\"\n func_changes_bbox = False\n prob = _scale_bbox_only_op_probability(prob)\n return _apply_multi_bbox_augmentation_wrapper(\n image, bboxes, prob, translate_x, func_changes_bbox, pixels, replace)\n\n\ndef translate_y_only_bboxes(image, bboxes, prob, pixels, replace):\n \"\"\"Apply translate_y to each bbox in the image with probability prob.\"\"\"\n func_changes_bbox = False\n prob = _scale_bbox_only_op_probability(prob)\n return _apply_multi_bbox_augmentation_wrapper(\n image, bboxes, prob, translate_y, func_changes_bbox, pixels, replace)\n\n\ndef flip_only_bboxes(image, bboxes, prob):\n \"\"\"Apply flip_lr to each bbox in the image with probability prob.\"\"\"\n func_changes_bbox = False\n prob = _scale_bbox_only_op_probability(prob)\n return _apply_multi_bbox_augmentation_wrapper(\n image, bboxes, prob, tf.image.flip_left_right, func_changes_bbox)\n\n\ndef solarize_only_bboxes(image, bboxes, prob, threshold):\n \"\"\"Apply solarize to each bbox in the image with probability prob.\"\"\"\n func_changes_bbox = False\n prob = _scale_bbox_only_op_probability(prob)\n return _apply_multi_bbox_augmentation_wrapper(\n image, bboxes, prob, solarize, func_changes_bbox, threshold)\n\n\ndef equalize_only_bboxes(image, bboxes, prob):\n \"\"\"Apply equalize to each bbox in the image with probability prob.\"\"\"\n func_changes_bbox = False\n prob = _scale_bbox_only_op_probability(prob)\n return _apply_multi_bbox_augmentation_wrapper(\n image, bboxes, prob, equalize, func_changes_bbox)\n\n\ndef cutout_only_bboxes(image, bboxes, prob, pad_size, replace):\n \"\"\"Apply cutout to each bbox in the image with probability prob.\"\"\"\n func_changes_bbox = False\n prob = _scale_bbox_only_op_probability(prob)\n return _apply_multi_bbox_augmentation_wrapper(\n image, bboxes, prob, cutout, func_changes_bbox, pad_size, replace)\n\n\ndef _rotate_bbox(bbox, image_height, image_width, degrees):\n \"\"\"Rotates the bbox coordinated by degrees.\n\n Args:\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n image_height: Int, height of the image.\n image_width: Int, height of the image.\n degrees: Float, a scalar angle in degrees to rotate all images by. If\n degrees is positive the image will be rotated clockwise otherwise it will\n be rotated counterclockwise.\n\n Returns:\n A tensor of the same shape as bbox, but now with the rotated coordinates.\n \"\"\"\n image_height, image_width = (\n tf.to_float(image_height), tf.to_float(image_width))\n\n # Convert from degrees to radians.\n degrees_to_radians = math.pi / 180.0\n radians = degrees * degrees_to_radians\n\n # Translate the bbox to the center of the image and turn the normalized 0-1\n # coordinates to absolute pixel locations.\n # Y coordinates are made negative as the y axis of images goes down with\n # increasing pixel values, so we negate to make sure x axis and y axis points\n # are in the traditionally positive direction.\n min_y = -tf.to_int32(image_height * (bbox[0] - 0.5))\n min_x = tf.to_int32(image_width * (bbox[1] - 0.5))\n max_y = -tf.to_int32(image_height * (bbox[2] - 0.5))\n max_x = tf.to_int32(image_width * (bbox[3] - 0.5))\n coordinates = tf.stack(\n [[min_y, min_x], [min_y, max_x], [max_y, min_x], [max_y, max_x]])\n coordinates = tf.cast(coordinates, tf.float32)\n # Rotate the coordinates according to the rotation matrix clockwise if\n # radians is positive, else negative\n rotation_matrix = tf.stack(\n [[tf.cos(radians), tf.sin(radians)],\n [-tf.sin(radians), tf.cos(radians)]])\n new_coords = tf.cast(\n tf.matmul(rotation_matrix, tf.transpose(coordinates)), tf.int32)\n # Find min/max values and convert them back to normalized 0-1 floats.\n min_y = -(tf.to_float(tf.reduce_max(new_coords[0, :])) / image_height - 0.5)\n min_x = tf.to_float(tf.reduce_min(new_coords[1, :])) / image_width + 0.5\n max_y = -(tf.to_float(tf.reduce_min(new_coords[0, :])) / image_height - 0.5)\n max_x = tf.to_float(tf.reduce_max(new_coords[1, :])) / image_width + 0.5\n\n # Clip the bboxes to be sure the fall between [0, 1].\n min_y, min_x, max_y, max_x = _clip_bbox(min_y, min_x, max_y, max_x)\n min_y, min_x, max_y, max_x = _check_bbox_area(min_y, min_x, max_y, max_x)\n return tf.stack([min_y, min_x, max_y, max_x])\n\n\ndef rotate_with_bboxes(image, bboxes, degrees, replace):\n \"\"\"Equivalent of PIL Rotate that rotates the image and bbox.\n\n Args:\n image: 3D uint8 Tensor.\n bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox\n has 4 elements (min_y, min_x, max_y, max_x) of type float.\n degrees: Float, a scalar angle in degrees to rotate all images by. If\n degrees is positive the image will be rotated clockwise otherwise it will\n be rotated counterclockwise.\n replace: A one or three value 1D tensor to fill empty pixels.\n\n Returns:\n A tuple containing a 3D uint8 Tensor that will be the result of rotating\n image by degrees. The second element of the tuple is bboxes, where now\n the coordinates will be shifted to reflect the rotated image.\n \"\"\"\n # Rotate the image.\n image = rotate(image, degrees, replace)\n\n # Convert bbox coordinates to pixel values.\n image_height = tf.shape(image)[0]\n image_width = tf.shape(image)[1]\n # pylint:disable=g-long-lambda\n wrapped_rotate_bbox = lambda bbox: _rotate_bbox(\n bbox, image_height, image_width, degrees)\n # pylint:enable=g-long-lambda\n bboxes = tf.map_fn(wrapped_rotate_bbox, bboxes)\n return image, bboxes\n\n\ndef translate_x(image, pixels, replace):\n \"\"\"Equivalent of PIL Translate in X dimension.\"\"\"\n image = image_ops.translate(wrap(image), [-pixels, 0])\n return unwrap(image, replace)\n\n\ndef translate_y(image, pixels, replace):\n \"\"\"Equivalent of PIL Translate in Y dimension.\"\"\"\n image = image_ops.translate(wrap(image), [0, -pixels])\n return unwrap(image, replace)\n\n\ndef _shift_bbox(bbox, image_height, image_width, pixels, shift_horizontal):\n \"\"\"Shifts the bbox coordinates by pixels.\n\n Args:\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n image_height: Int, height of the image.\n image_width: Int, width of the image.\n pixels: An int. How many pixels to shift the bbox.\n shift_horizontal: Boolean. If true then shift in X dimension else shift in\n Y dimension.\n\n Returns:\n A tensor of the same shape as bbox, but now with the shifted coordinates.\n \"\"\"\n pixels = tf.to_int32(pixels)\n # Convert bbox to integer pixel locations.\n min_y = tf.to_int32(tf.to_float(image_height) * bbox[0])\n min_x = tf.to_int32(tf.to_float(image_width) * bbox[1])\n max_y = tf.to_int32(tf.to_float(image_height) * bbox[2])\n max_x = tf.to_int32(tf.to_float(image_width) * bbox[3])\n\n if shift_horizontal:\n min_x = tf.maximum(0, min_x - pixels)\n max_x = tf.minimum(image_width, max_x - pixels)\n else:\n min_y = tf.maximum(0, min_y - pixels)\n max_y = tf.minimum(image_height, max_y - pixels)\n\n # Convert bbox back to floats.\n min_y = tf.to_float(min_y) / tf.to_float(image_height)\n min_x = tf.to_float(min_x) / tf.to_float(image_width)\n max_y = tf.to_float(max_y) / tf.to_float(image_height)\n max_x = tf.to_float(max_x) / tf.to_float(image_width)\n\n # Clip the bboxes to be sure the fall between [0, 1].\n min_y, min_x, max_y, max_x = _clip_bbox(min_y, min_x, max_y, max_x)\n min_y, min_x, max_y, max_x = _check_bbox_area(min_y, min_x, max_y, max_x)\n return tf.stack([min_y, min_x, max_y, max_x])\n\n\ndef translate_bbox(image, bboxes, pixels, replace, shift_horizontal):\n \"\"\"Equivalent of PIL Translate in X/Y dimension that shifts image and bbox.\n\n Args:\n image: 3D uint8 Tensor.\n bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox\n has 4 elements (min_y, min_x, max_y, max_x) of type float with values\n between [0, 1].\n pixels: An int. How many pixels to shift the image and bboxes\n replace: A one or three value 1D tensor to fill empty pixels.\n shift_horizontal: Boolean. If true then shift in X dimension else shift in\n Y dimension.\n\n Returns:\n A tuple containing a 3D uint8 Tensor that will be the result of translating\n image by pixels. The second element of the tuple is bboxes, where now\n the coordinates will be shifted to reflect the shifted image.\n \"\"\"\n if shift_horizontal:\n image = translate_x(image, pixels, replace)\n else:\n image = translate_y(image, pixels, replace)\n\n # Convert bbox coordinates to pixel values.\n image_height = tf.shape(image)[0]\n image_width = tf.shape(image)[1]\n # pylint:disable=g-long-lambda\n wrapped_shift_bbox = lambda bbox: _shift_bbox(\n bbox, image_height, image_width, pixels, shift_horizontal)\n # pylint:enable=g-long-lambda\n bboxes = tf.map_fn(wrapped_shift_bbox, bboxes)\n return image, bboxes\n\n\ndef shear_x(image, level, replace):\n \"\"\"Equivalent of PIL Shearing in X dimension.\"\"\"\n # Shear parallel to x axis is a projective transform\n # with a matrix form of:\n # [1 level\n # 0 1].\n image = image_ops.transform(\n wrap(image), [1., level, 0., 0., 1., 0., 0., 0.])\n return unwrap(image, replace)\n\n\ndef shear_y(image, level, replace):\n \"\"\"Equivalent of PIL Shearing in Y dimension.\"\"\"\n # Shear parallel to y axis is a projective transform\n # with a matrix form of:\n # [1 0\n # level 1].\n image = image_ops.transform(\n wrap(image), [1., 0., 0., level, 1., 0., 0., 0.])\n return unwrap(image, replace)\n\n\ndef _shear_bbox(bbox, image_height, image_width, level, shear_horizontal):\n \"\"\"Shifts the bbox according to how the image was sheared.\n\n Args:\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n image_height: Int, height of the image.\n image_width: Int, height of the image.\n level: Float. How much to shear the image.\n shear_horizontal: If true then shear in X dimension else shear in\n the Y dimension.\n\n Returns:\n A tensor of the same shape as bbox, but now with the shifted coordinates.\n \"\"\"\n image_height, image_width = (\n tf.to_float(image_height), tf.to_float(image_width))\n\n # Change bbox coordinates to be pixels.\n min_y = tf.to_int32(image_height * bbox[0])\n min_x = tf.to_int32(image_width * bbox[1])\n max_y = tf.to_int32(image_height * bbox[2])\n max_x = tf.to_int32(image_width * bbox[3])\n coordinates = tf.stack(\n [[min_y, min_x], [min_y, max_x], [max_y, min_x], [max_y, max_x]])\n coordinates = tf.cast(coordinates, tf.float32)\n\n # Shear the coordinates according to the translation matrix.\n if shear_horizontal:\n translation_matrix = tf.stack(\n [[1, 0], [-level, 1]])\n else:\n translation_matrix = tf.stack(\n [[1, -level], [0, 1]])\n translation_matrix = tf.cast(translation_matrix, tf.float32)\n new_coords = tf.cast(\n tf.matmul(translation_matrix, tf.transpose(coordinates)), tf.int32)\n\n # Find min/max values and convert them back to floats.\n min_y = tf.to_float(tf.reduce_min(new_coords[0, :])) / image_height\n min_x = tf.to_float(tf.reduce_min(new_coords[1, :])) / image_width\n max_y = tf.to_float(tf.reduce_max(new_coords[0, :])) / image_height\n max_x = tf.to_float(tf.reduce_max(new_coords[1, :])) / image_width\n\n # Clip the bboxes to be sure the fall between [0, 1].\n min_y, min_x, max_y, max_x = _clip_bbox(min_y, min_x, max_y, max_x)\n min_y, min_x, max_y, max_x = _check_bbox_area(min_y, min_x, max_y, max_x)\n return tf.stack([min_y, min_x, max_y, max_x])\n\n\ndef shear_with_bboxes(image, bboxes, level, replace, shear_horizontal):\n \"\"\"Applies Shear Transformation to the image and shifts the bboxes.\n\n Args:\n image: 3D uint8 Tensor.\n bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox\n has 4 elements (min_y, min_x, max_y, max_x) of type float with values\n between [0, 1].\n level: Float. How much to shear the image. This value will be between\n -0.3 to 0.3.\n replace: A one or three value 1D tensor to fill empty pixels.\n shear_horizontal: Boolean. If true then shear in X dimension else shear in\n the Y dimension.\n\n Returns:\n A tuple containing a 3D uint8 Tensor that will be the result of shearing\n image by level. The second element of the tuple is bboxes, where now\n the coordinates will be shifted to reflect the sheared image.\n \"\"\"\n if shear_horizontal:\n image = shear_x(image, level, replace)\n else:\n image = shear_y(image, level, replace)\n\n # Convert bbox coordinates to pixel values.\n image_height = tf.shape(image)[0]\n image_width = tf.shape(image)[1]\n # pylint:disable=g-long-lambda\n wrapped_shear_bbox = lambda bbox: _shear_bbox(\n bbox, image_height, image_width, level, shear_horizontal)\n # pylint:enable=g-long-lambda\n bboxes = tf.map_fn(wrapped_shear_bbox, bboxes)\n return image, bboxes\n\n\ndef autocontrast(image):\n \"\"\"Implements Autocontrast function from PIL using TF ops.\n\n Args:\n image: A 3D uint8 tensor.\n\n Returns:\n The image after it has had autocontrast applied to it and will be of type\n uint8.\n \"\"\"\n\n def scale_channel(image):\n \"\"\"Scale the 2D image using the autocontrast rule.\"\"\"\n # A possibly cheaper version can be done using cumsum/unique_with_counts\n # over the histogram values, rather than iterating over the entire image.\n # to compute mins and maxes.\n lo = tf.to_float(tf.reduce_min(image))\n hi = tf.to_float(tf.reduce_max(image))\n\n # Scale the image, making the lowest value 0 and the highest value 255.\n def scale_values(im):\n scale = 255.0 / (hi - lo)\n offset = -lo * scale\n im = tf.to_float(im) * scale + offset\n im = tf.clip_by_value(im, 0.0, 255.0)\n return tf.cast(im, tf.uint8)\n\n result = tf.cond(hi > lo, lambda: scale_values(image), lambda: image)\n return result\n\n # Assumes RGB for now. Scales each channel independently\n # and then stacks the result.\n s1 = scale_channel(image[:, :, 0])\n s2 = scale_channel(image[:, :, 1])\n s3 = scale_channel(image[:, :, 2])\n image = tf.stack([s1, s2, s3], 2)\n return image\n\n\ndef sharpness(image, factor):\n \"\"\"Implements Sharpness function from PIL using TF ops.\"\"\"\n orig_image = image\n image = tf.cast(image, tf.float32)\n # Make image 4D for conv operation.\n image = tf.expand_dims(image, 0)\n # SMOOTH PIL Kernel.\n kernel = tf.constant(\n [[1, 1, 1], [1, 5, 1], [1, 1, 1]], dtype=tf.float32,\n shape=[3, 3, 1, 1]) / 13.\n # Tile across channel dimension.\n kernel = tf.tile(kernel, [1, 1, 3, 1])\n strides = [1, 1, 1, 1]\n with tf.device('/cpu:0'):\n degenerate = tf.nn.depthwise_conv2d(\n image, kernel, strides, padding='VALID', rate=[1, 1])\n degenerate = tf.clip_by_value(degenerate, 0.0, 255.0)\n degenerate = tf.squeeze(tf.cast(degenerate, tf.uint8), [0])\n\n # For the borders of the resulting image, fill in the values of the\n # original image.\n mask = tf.ones_like(degenerate)\n padded_mask = tf.pad(mask, [[1, 1], [1, 1], [0, 0]])\n padded_degenerate = tf.pad(degenerate, [[1, 1], [1, 1], [0, 0]])\n result = tf.where(tf.equal(padded_mask, 1), padded_degenerate, orig_image)\n\n # Blend the final result.\n return blend(result, orig_image, factor)\n\n\ndef equalize(image):\n \"\"\"Implements Equalize function from PIL using TF ops.\"\"\"\n def scale_channel(im, c):\n \"\"\"Scale the data in the channel to implement equalize.\"\"\"\n im = tf.cast(im[:, :, c], tf.int32)\n # Compute the histogram of the image channel.\n histo = tf.histogram_fixed_width(im, [0, 255], nbins=256)\n\n # For the purposes of computing the step, filter out the nonzeros.\n nonzero = tf.where(tf.not_equal(histo, 0))\n nonzero_histo = tf.reshape(tf.gather(histo, nonzero), [-1])\n step = (tf.reduce_sum(nonzero_histo) - nonzero_histo[-1]) // 255\n\n def build_lut(histo, step):\n # Compute the cumulative sum, shifting by step // 2\n # and then normalization by step.\n lut = (tf.cumsum(histo) + (step // 2)) // step\n # Shift lut, prepending with 0.\n lut = tf.concat([[0], lut[:-1]], 0)\n # Clip the counts to be in range. This is done\n # in the C code for image.point.\n return tf.clip_by_value(lut, 0, 255)\n\n # If step is zero, return the original image. Otherwise, build\n # lut from the full histogram and step and then index from it.\n result = tf.cond(tf.equal(step, 0),\n lambda: im,\n lambda: tf.gather(build_lut(histo, step), im))\n\n return tf.cast(result, tf.uint8)\n\n # Assumes RGB for now. Scales each channel independently\n # and then stacks the result.\n s1 = scale_channel(image, 0)\n s2 = scale_channel(image, 1)\n s3 = scale_channel(image, 2)\n image = tf.stack([s1, s2, s3], 2)\n return image\n\n\ndef wrap(image):\n \"\"\"Returns 'image' with an extra channel set to all 1s.\"\"\"\n shape = tf.shape(image)\n extended_channel = tf.ones([shape[0], shape[1], 1], image.dtype)\n extended = tf.concat([image, extended_channel], 2)\n return extended\n\n\ndef unwrap(image, replace):\n \"\"\"Unwraps an image produced by wrap.\n\n Where there is a 0 in the last channel for every spatial position,\n the rest of the three channels in that spatial dimension are grayed\n (set to 128). Operations like translate and shear on a wrapped\n Tensor will leave 0s in empty locations. Some transformations look\n at the intensity of values to do preprocessing, and we want these\n empty pixels to assume the 'average' value, rather than pure black.\n\n\n Args:\n image: A 3D Image Tensor with 4 channels.\n replace: A one or three value 1D tensor to fill empty pixels.\n\n Returns:\n image: A 3D image Tensor with 3 channels.\n \"\"\"\n image_shape = tf.shape(image)\n # Flatten the spatial dimensions.\n flattened_image = tf.reshape(image, [-1, image_shape[2]])\n\n # Find all pixels where the last channel is zero.\n alpha_channel = flattened_image[:, 3]\n\n replace = tf.concat([replace, tf.ones([1], image.dtype)], 0)\n\n # Where they are zero, fill them in with 'replace'.\n flattened_image = tf.where(\n tf.equal(alpha_channel, 0),\n tf.ones_like(flattened_image, dtype=image.dtype) * replace,\n flattened_image)\n\n image = tf.reshape(flattened_image, image_shape)\n image = tf.slice(image, [0, 0, 0], [image_shape[0], image_shape[1], 3])\n return image\n\n\ndef _cutout_inside_bbox(image, bbox, pad_fraction):\n \"\"\"Generates cutout mask and the mean pixel value of the bbox.\n\n First a location is randomly chosen within the image as the center where the\n cutout mask will be applied. Note this can be towards the boundaries of the\n image, so the full cutout mask may not be applied.\n\n Args:\n image: 3D uint8 Tensor.\n bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x)\n of type float that represents the normalized coordinates between 0 and 1.\n pad_fraction: Float that specifies how large the cutout mask should be in\n in reference to the size of the original bbox. If pad_fraction is 0.25,\n then the cutout mask will be of shape\n (0.25 * bbox height, 0.25 * bbox width).\n\n Returns:\n A tuple. Fist element is a tensor of the same shape as image where each\n element is either a 1 or 0 that is used to determine where the image\n will have cutout applied. The second element is the mean of the pixels\n in the image where the bbox is located.\n \"\"\"\n image_height = tf.maximum(tf.shape(image)[0], 10)\n image_width = tf.maximum(tf.shape(image)[1], 10)\n # Transform from shape [1, 4] to [4].\n bbox = tf.squeeze(bbox)\n\n min_y = tf.to_int32(tf.to_float(image_height) * bbox[0])\n min_x = tf.to_int32(tf.to_float(image_width) * bbox[1])\n max_y = tf.to_int32(tf.to_float(image_height) * bbox[2])\n max_x = tf.to_int32(tf.to_float(image_width) * bbox[3])\n\n # Calculate the mean pixel values in the bounding box, which will be used\n # to fill the cutout region.\n mean = tf.reduce_mean(image[min_y:max_y + 1, min_x:max_x + 1],\n reduction_indices=[0, 1])\n\n # Cutout mask will be size pad_size_heigh * 2 by pad_size_width * 2 if the\n # region lies entirely within the bbox.\n box_height = max_y - min_y + 1\n box_width = max_x - min_x + 1\n pad_size_height = tf.to_int32(pad_fraction * (box_height / 2))\n pad_size_width = tf.to_int32(pad_fraction * (box_width / 2))\n\n # Sample the center location in the image where the zero mask will be applied.\n cutout_center_height = tf.random_uniform(\n shape=[], minval=min_y, maxval=max_y+1,\n dtype=tf.int32)\n\n cutout_center_width = tf.random_uniform(\n shape=[], minval=min_x, maxval=max_x+1,\n dtype=tf.int32)\n\n lower_pad = tf.maximum(\n 0, cutout_center_height - pad_size_height)\n upper_pad = tf.maximum(\n 0, image_height - cutout_center_height - pad_size_height)\n left_pad = tf.maximum(\n 0, cutout_center_width - pad_size_width)\n right_pad = tf.maximum(\n 0, image_width - cutout_center_width - pad_size_width)\n\n cutout_shape = [image_height - (lower_pad + upper_pad),\n image_width - (left_pad + right_pad)]\n padding_dims = [[lower_pad, upper_pad], [left_pad, right_pad]]\n\n mask = tf.pad(\n tf.zeros(cutout_shape, dtype=image.dtype),\n padding_dims, constant_values=1)\n\n mask = tf.expand_dims(mask, 2)\n mask = tf.tile(mask, [1, 1, 3])\n\n return mask, mean\n\n\ndef bbox_cutout(image, bboxes, pad_fraction, replace_with_mean):\n \"\"\"Applies cutout to the image according to bbox information.\n\n This is a cutout variant that using bbox information to make more informed\n decisions on where to place the cutout mask.\n\n Args:\n image: 3D uint8 Tensor.\n bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox\n has 4 elements (min_y, min_x, max_y, max_x) of type float with values\n between [0, 1].\n pad_fraction: Float that specifies how large the cutout mask should be in\n in reference to the size of the original bbox. If pad_fraction is 0.25,\n then the cutout mask will be of shape\n (0.25 * bbox height, 0.25 * bbox width).\n replace_with_mean: Boolean that specified what value should be filled in\n where the cutout mask is applied. Since the incoming image will be of\n uint8 and will not have had any mean normalization applied, by default\n we set the value to be 128. If replace_with_mean is True then we find\n the mean pixel values across the channel dimension and use those to fill\n in where the cutout mask is applied.\n\n Returns:\n A tuple. First element is a tensor of the same shape as image that has\n cutout applied to it. Second element is the bboxes that were passed in\n that will be unchanged.\n \"\"\"\n def apply_bbox_cutout(image, bboxes, pad_fraction):\n \"\"\"Applies cutout to a single bounding box within image.\"\"\"\n # Choose a single bounding box to apply cutout to.\n random_index = tf.random_uniform(\n shape=[], maxval=tf.shape(bboxes)[0], dtype=tf.int32)\n # Select the corresponding bbox and apply cutout.\n chosen_bbox = tf.gather(bboxes, random_index)\n mask, mean = _cutout_inside_bbox(image, chosen_bbox, pad_fraction)\n\n # When applying cutout we either set the pixel value to 128 or to the mean\n # value inside the bbox.\n replace = mean if replace_with_mean else 128\n\n # Apply the cutout mask to the image. Where the mask is 0 we fill it with\n # `replace`.\n image = tf.where(\n tf.equal(mask, 0),\n tf.cast(tf.ones_like(image, dtype=image.dtype) * replace,\n dtype=image.dtype),\n image)\n return image\n\n # Check to see if there are boxes, if so then apply boxcutout.\n image = tf.cond(tf.equal(tf.shape(bboxes)[0], 0), lambda: image,\n lambda: apply_bbox_cutout(image, bboxes, pad_fraction))\n\n return image, bboxes\n\n\nNAME_TO_FUNC = {\n 'AutoContrast': autocontrast,\n 'Equalize': equalize,\n 'Posterize': posterize,\n 'Solarize': solarize,\n 'SolarizeAdd': solarize_add,\n 'Color': color,\n 'Contrast': contrast,\n 'Brightness': brightness,\n 'Sharpness': sharpness,\n 'Cutout': cutout,\n 'BBox_Cutout': bbox_cutout,\n 'Rotate_BBox': rotate_with_bboxes,\n # pylint:disable=g-long-lambda\n 'TranslateX_BBox': lambda image, bboxes, pixels, replace: translate_bbox(\n image, bboxes, pixels, replace, shift_horizontal=True),\n 'TranslateY_BBox': lambda image, bboxes, pixels, replace: translate_bbox(\n image, bboxes, pixels, replace, shift_horizontal=False),\n 'ShearX_BBox': lambda image, bboxes, level, replace: shear_with_bboxes(\n image, bboxes, level, replace, shear_horizontal=True),\n 'ShearY_BBox': lambda image, bboxes, level, replace: shear_with_bboxes(\n image, bboxes, level, replace, shear_horizontal=False),\n # pylint:enable=g-long-lambda\n 'Rotate_Only_BBoxes': rotate_only_bboxes,\n 'ShearX_Only_BBoxes': shear_x_only_bboxes,\n 'ShearY_Only_BBoxes': shear_y_only_bboxes,\n 'TranslateX_Only_BBoxes': translate_x_only_bboxes,\n 'TranslateY_Only_BBoxes': translate_y_only_bboxes,\n 'Flip_Only_BBoxes': flip_only_bboxes,\n 'Solarize_Only_BBoxes': solarize_only_bboxes,\n 'Equalize_Only_BBoxes': equalize_only_bboxes,\n 'Cutout_Only_BBoxes': cutout_only_bboxes,\n}\n\n\ndef _randomly_negate_tensor(tensor):\n \"\"\"With 50% prob turn the tensor negative.\"\"\"\n should_flip = tf.cast(tf.floor(tf.random_uniform([]) + 0.5), tf.bool)\n final_tensor = tf.cond(should_flip, lambda: tensor, lambda: -tensor)\n return final_tensor\n\n\ndef _rotate_level_to_arg(level):\n level = (level/_MAX_LEVEL) * 30.\n level = _randomly_negate_tensor(level)\n return (level,)\n\n\ndef _shrink_level_to_arg(level):\n \"\"\"Converts level to ratio by which we shrink the image content.\"\"\"\n if level == 0:\n return (1.0,) # if level is zero, do not shrink the image\n # Maximum shrinking ratio is 2.9.\n level = 2. / (_MAX_LEVEL / level) + 0.9\n return (level,)\n\n\ndef _enhance_level_to_arg(level):\n return ((level/_MAX_LEVEL) * 1.8 + 0.1,)\n\n\ndef _shear_level_to_arg(level):\n level = (level/_MAX_LEVEL) * 0.3\n # Flip level to negative with 50% chance.\n level = _randomly_negate_tensor(level)\n return (level,)\n\n\ndef _translate_level_to_arg(level, translate_const):\n level = (level/_MAX_LEVEL) * float(translate_const)\n # Flip level to negative with 50% chance.\n level = _randomly_negate_tensor(level)\n return (level,)\n\n\ndef _bbox_cutout_level_to_arg(level, hparams):\n cutout_pad_fraction = (level/_MAX_LEVEL) * hparams.cutout_max_pad_fraction\n return (cutout_pad_fraction,\n hparams.cutout_bbox_replace_with_mean)\n\n\ndef level_to_arg(hparams):\n return {\n 'AutoContrast': lambda level: (),\n 'Equalize': lambda level: (),\n 'Posterize': lambda level: (int((level/_MAX_LEVEL) * 4),),\n 'Solarize': lambda level: (int((level/_MAX_LEVEL) * 256),),\n 'SolarizeAdd': lambda level: (int((level/_MAX_LEVEL) * 110),),\n 'Color': _enhance_level_to_arg,\n 'Contrast': _enhance_level_to_arg,\n 'Brightness': _enhance_level_to_arg,\n 'Sharpness': _enhance_level_to_arg,\n 'Cutout': lambda level: (int((level/_MAX_LEVEL) * hparams.cutout_const),),\n # pylint:disable=g-long-lambda\n 'BBox_Cutout': lambda level: _bbox_cutout_level_to_arg(\n level, hparams),\n 'TranslateX_BBox': lambda level: _translate_level_to_arg(\n level, hparams.translate_const),\n 'TranslateY_BBox': lambda level: _translate_level_to_arg(\n level, hparams.translate_const),\n # pylint:enable=g-long-lambda\n 'ShearX_BBox': _shear_level_to_arg,\n 'ShearY_BBox': _shear_level_to_arg,\n 'Rotate_BBox': _rotate_level_to_arg,\n 'Rotate_Only_BBoxes': _rotate_level_to_arg,\n 'ShearX_Only_BBoxes': _shear_level_to_arg,\n 'ShearY_Only_BBoxes': _shear_level_to_arg,\n # pylint:disable=g-long-lambda\n 'TranslateX_Only_BBoxes': lambda level: _translate_level_to_arg(\n level, hparams.translate_bbox_const),\n 'TranslateY_Only_BBoxes': lambda level: _translate_level_to_arg(\n level, hparams.translate_bbox_const),\n # pylint:enable=g-long-lambda\n 'Flip_Only_BBoxes': lambda level: (),\n 'Solarize_Only_BBoxes': lambda level: (int((level/_MAX_LEVEL) * 256),),\n 'Equalize_Only_BBoxes': lambda level: (),\n # pylint:disable=g-long-lambda\n 'Cutout_Only_BBoxes': lambda level: (\n int((level/_MAX_LEVEL) * hparams.cutout_bbox_const),),\n # pylint:enable=g-long-lambda\n }\n\n\ndef bbox_wrapper(func):\n \"\"\"Adds a bboxes function argument to func and returns unchanged bboxes.\"\"\"\n def wrapper(images, bboxes, *args, **kwargs):\n return (func(images, *args, **kwargs), bboxes)\n return wrapper\n\n\ndef _parse_policy_info(name, prob, level, replace_value, augmentation_hparams):\n \"\"\"Return the function that corresponds to `name` and update `level` param.\"\"\"\n func = NAME_TO_FUNC[name]\n args = level_to_arg(augmentation_hparams)[name](level)\n\n # Check to see if prob is passed into function. This is used for operations\n # where we alter bboxes independently.\n # pytype:disable=wrong-arg-types\n if 'prob' in inspect.getfullargspec(func)[0]:\n args = tuple([prob] + list(args))\n # pytype:enable=wrong-arg-types\n\n # Add in replace arg if it is required for the function that is being called.\n if 'replace' in inspect.getfullargspec(func)[0]:\n # Make sure replace is the final argument\n assert 'replace' == inspect.getfullargspec(func)[0][-1]\n args = tuple(list(args) + [replace_value])\n\n # Add bboxes as the second positional argument for the function if it does\n # not already exist.\n if 'bboxes' not in inspect.getfullargspec(func)[0]:\n func = bbox_wrapper(func)\n return (func, prob, args)\n\n\ndef _apply_func_with_prob(func, image, args, prob, bboxes):\n \"\"\"Apply `func` to image w/ `args` as input with probability `prob`.\"\"\"\n assert isinstance(args, tuple)\n assert 'bboxes' == inspect.getfullargspec(func)[0][1]\n\n # If prob is a function argument, then this randomness is being handled\n # inside the function, so make sure it is always called.\n if 'prob' in inspect.getfullargspec(func)[0]:\n prob = 1.0\n\n # Apply the function with probability `prob`.\n should_apply_op = tf.cast(\n tf.floor(tf.random_uniform([], dtype=tf.float32) + prob), tf.bool)\n augmented_image, augmented_bboxes = tf.cond(\n should_apply_op,\n lambda: func(image, bboxes, *args),\n lambda: (image, bboxes))\n return augmented_image, augmented_bboxes\n\n\ndef select_and_apply_random_policy(policies, image, bboxes):\n \"\"\"Select a random policy from `policies` and apply it to `image`.\"\"\"\n policy_to_select = tf.random_uniform([], maxval=len(policies), dtype=tf.int32)\n # Note that using tf.case instead of tf.conds would result in significantly\n # larger graphs and would even break export for some larger policies.\n for (i, policy) in enumerate(policies):\n image, bboxes = tf.cond(\n tf.equal(i, policy_to_select),\n lambda selected_policy=policy: selected_policy(image, bboxes),\n lambda: (image, bboxes))\n return (image, bboxes)\n\n\ndef build_and_apply_nas_policy(policies, image, bboxes,\n augmentation_hparams):\n \"\"\"Build a policy from the given policies passed in and apply to image.\n\n Args:\n policies: list of lists of tuples in the form `(func, prob, level)`, `func`\n is a string name of the augmentation function, `prob` is the probability\n of applying the `func` operation, `level` is the input argument for\n `func`.\n image: tf.Tensor that the resulting policy will be applied to.\n bboxes: tf.Tensor of shape [N, 4] representing ground truth boxes that are\n normalized between [0, 1].\n augmentation_hparams: Hparams associated with the NAS learned policy.\n\n Returns:\n A version of image that now has data augmentation applied to it based on\n the `policies` pass into the function. Additionally, returns bboxes if\n a value for them is passed in that is not None\n \"\"\"\n replace_value = [128, 128, 128]\n\n # func is the string name of the augmentation function, prob is the\n # probability of applying the operation and level is the parameter associated\n # with the tf op.\n\n # tf_policies are functions that take in an image and return an augmented\n # image.\n tf_policies = []\n for policy in policies:\n tf_policy = []\n # Link string name to the correct python function and make sure the correct\n # argument is passed into that function.\n for policy_info in policy:\n policy_info = list(policy_info) + [replace_value, augmentation_hparams]\n\n tf_policy.append(_parse_policy_info(*policy_info))\n # Now build the tf policy that will apply the augmentation procedue\n # on image.\n def make_final_policy(tf_policy_):\n def final_policy(image_, bboxes_):\n for func, prob, args in tf_policy_:\n image_, bboxes_ = _apply_func_with_prob(\n func, image_, args, prob, bboxes_)\n return image_, bboxes_\n return final_policy\n tf_policies.append(make_final_policy(tf_policy))\n augmented_images, augmented_bboxes = select_and_apply_random_policy(\n tf_policies, image, bboxes)\n\n # If no bounding boxes were specified, then just return the images.\n return (augmented_images, augmented_bboxes)\n\n\n@tf.autograph.experimental.do_not_convert\ndef distort_image_with_autoaugment(image,\n bboxes,\n augmentation_name):\n \"\"\"Applies the AutoAugment policy to `image` and `bboxes`.\n\n Args:\n image: `Tensor` of shape [height, width, 3] representing an image.\n bboxes: `Tensor` of shape [N, 4] representing ground truth boxes that are\n normalized between [0, 1].\n augmentation_name: The name of the AutoAugment policy to use. The available\n options are `v0`, `v1`, `v2`, `v3` and `test`. `v0` is the policy used for\n all of the results in the paper and was found to achieve the best results\n on the COCO dataset. `v1`, `v2` and `v3` are additional good policies\n found on the COCO dataset that have slight variation in what operations\n were used during the search procedure along with how many operations are\n applied in parallel to a single image (2 vs 3).\n\n Returns:\n A tuple containing the augmented versions of `image` and `bboxes`.\n \"\"\"\n logging.info('Using autoaugmention policy: %s', augmentation_name)\n available_policies = {'v0': policy_v0, 'v1': policy_v1, 'v2': policy_v2,\n 'v3': policy_v3, 'test': policy_vtest}\n if augmentation_name not in available_policies:\n raise ValueError('Invalid augmentation_name: {}'.format(augmentation_name))\n\n policy = available_policies[augmentation_name]()\n # Hparams that will be used for AutoAugment.\n augmentation_hparams = hparams_config.Config(dict(\n cutout_max_pad_fraction=0.75,\n cutout_bbox_replace_with_mean=False,\n cutout_const=100,\n translate_const=250,\n cutout_bbox_const=50,\n translate_bbox_const=120))\n\n return build_and_apply_nas_policy(policy, image, bboxes,\n augmentation_hparams)\n\n\ndef distort_image_with_randaugment(image, bboxes, num_layers, magnitude):\n \"\"\"Applies the RandAugment to `image` and `bboxes`.\"\"\"\n replace_value = [128, 128, 128]\n tf.logging.info('Using RandAugment.')\n\n augmentation_hparams = hparams_config.Config(\n dict(\n cutout_max_pad_fraction=0.75,\n cutout_bbox_replace_with_mean=False,\n cutout_const=100,\n translate_const=250,\n cutout_bbox_const=50,\n translate_bbox_const=120))\n\n available_ops = [\n 'Equalize', 'Solarize', 'Color', 'Cutout', 'SolarizeAdd',\n 'TranslateX_BBox', 'TranslateY_BBox', 'ShearX_BBox', 'ShearY_BBox',\n 'Rotate_BBox']\n\n if bboxes is None:\n bboxes = tf.constant(0.0)\n\n for layer_num in range(num_layers):\n op_to_select = tf.random_uniform(\n [], maxval=len(available_ops), dtype=tf.int32)\n random_magnitude = float(magnitude)\n with tf.name_scope('randaug_layer_{}'.format(layer_num)):\n for (i, op_name) in enumerate(available_ops):\n prob = tf.random_uniform([], minval=0.2, maxval=0.8, dtype=tf.float32)\n func, _, args = _parse_policy_info(op_name, prob, random_magnitude,\n replace_value, augmentation_hparams)\n image, bboxes = tf.cond(\n tf.equal(i, op_to_select),\n lambda fn=func, fn_args=args: fn(image, bboxes, *fn_args),\n lambda: (image, bboxes))\n return (image, bboxes)\n" ]
[ [ "tensorflow.compat.v1.nn.depthwise_conv2d", "tensorflow.compat.v1.map_fn", "tensorflow.compat.v1.zeros", "tensorflow.compat.v1.logging.info", "tensorflow.compat.v1.transpose", "tensorflow.compat.v1.tile", "tensorflow.compat.v1.ones_like", "tensorflow.compat.v1.equal", "tensorflow.compat.v1.shape", "tensorflow.compat.v1.cumsum", "tensorflow.compat.v1.convert_to_tensor", "tensorflow.compat.v1.less", "tensorflow.compat.v1.reduce_min", "tensorflow.compat.v1.reduce_sum", "tensorflow.compat.v1.device", "tensorflow.compat.v1.to_float", "tensorflow.compat.v1.to_int32", "tensorflow.compat.v1.ones", "tensorflow.compat.v1.constant", "tensorflow.compat.v1.reshape", "tensorflow.compat.v1.sin", "tensorflow.compat.v1.where", "tensorflow.compat.v1.image.rgb_to_grayscale", "tensorflow.compat.v1.bitwise.right_shift", "tensorflow.compat.v1.not_equal", "tensorflow.compat.v1.ensure_shape", "tensorflow.compat.v1.stack", "tensorflow.compat.v1.TensorShape", "tensorflow.compat.v1.zeros_like", "tensorflow.compat.v1.histogram_fixed_width", "tensorflow.compat.v1.slice", "tensorflow.compat.v1.reduce_mean", "tensorflow.compat.v1.cast", "tensorflow.compat.v1.pad", "tensorflow.compat.v1.reduce_max", "tensorflow.compat.v1.maximum", "tensorflow.compat.v1.expand_dims", "tensorflow.compat.v1.random_uniform", "tensorflow.compat.v1.gather", "tensorflow.compat.v1.cond", "tensorflow.compat.v1.squeeze", "tensorflow.compat.v1.random.shuffle", "tensorflow.compat.v1.concat", "tensorflow.compat.v1.cos", "tensorflow.compat.v1.clip_by_value", "tensorflow.compat.v1.minimum" ] ]
stevenaldinger/eden
[ "c5d749651101dabc06d7dea8e1d39544258f0d37" ]
[ "controllers/delphi.py" ]
[ "# coding: utf8\n\n\"\"\"\n Delphi Decision Maker - Controllers\n\"\"\"\n\nmodule = request.controller\nresourcename = request.function\n\nif not settings.has_module(module):\n raise HTTP(404, body=\"Module disabled: %s\" % module)\n\n# =============================================================================\ndef index():\n \"\"\"\n Module Home Page\n - provide the list of currently-Active Problems\n \"\"\"\n\n # Simply redirect to the Problems REST controller\n redirect(URL(f=\"problem\"))\n\n # Alternative dashboard\n module_name = settings.modules[module].name_nice\n\n table = s3db.delphi_group\n groups = db(table.active == True).select()\n result = []\n for group in groups:\n actions = []\n duser = s3db.delphi_DelphiUser(group)\n if duser.authorised:\n actions.append((\"group/%d/update\" % group.id, T(\"Edit\")))\n actions.append((\"new_problem/create/?group=%s&next=%s\" % \\\n (group.id,\n URL(f=\"group_summary\", args=group.id)),\n \"Add New Problem\"))\n actions.append((\"group_summary/%s/#request\" % group.id, T(\"Review Requests\")))\n else:\n actions.append((\"group_summary/%s/#request\" % group.id,\n \"Role: %s%s\" % (duser.status,\n (duser.membership and duser.membership.req) and \"*\" or \"\")))\n\n table = s3db.delphi_problem\n query = (table.group_id == group.id) & \\\n (table.active == True)\n latest_problems = db(query).select(orderby =~ table.modified_on)\n result.append((group, latest_problems, actions))\n\n response.title = module_name\n return dict(groups_problems = result,\n name = T(\"Active Problems\"),\n module_name = module_name,\n )\n\n# =============================================================================\n# Groups\n# =============================================================================\ndef group_rheader(r, tabs = []):\n \"\"\" Group rheader \"\"\"\n\n if r.representation == \"html\":\n if r.record is None:\n # List or Create form: rheader makes no sense here\n return None\n\n tabs = [(T(\"Basic Details\"), None),\n (T(\"Problems\"), \"problem\"),\n ]\n\n group = r.record\n\n # Get this User's permissions for this Group\n duser = s3db.delphi_DelphiUser(group.id)\n if duser.authorised:\n tabs.append((T(\"Membership\"), \"membership\"))\n\n rheader_tabs = s3_rheader_tabs(r, tabs)\n\n rheader = DIV(\n TABLE(\n TR(TH(\"%s: \" % T(\"Group\")),\n group.name,\n ),\n TR(TH(\"%s: \" % T(\"Description\")),\n group.description,\n ),\n TR(TH(\"%s: \" % T(\"Active\")),\n group.active,\n ),\n ),\n rheader_tabs\n )\n return rheader\n\n# -----------------------------------------------------------------------------\ndef group():\n \"\"\" Problem Group REST Controller \"\"\"\n\n if not s3_has_role(\"DelphiAdmin\"):\n s3db.configure(\"delphi_group\",\n deletable=False,\n # Remove ability to create new Groups\n #insertable=False\n )\n\n def prep(r):\n if r.interactive:\n\n if r.component:\n tablename = r.component.tablename\n list_fields = s3db.get_config(tablename,\n \"list_fields\")\n try:\n list_fields.remove(\"group_id\")\n except:\n pass\n s3db.configure(tablename,\n deletable = s3_has_role(\"DelphiAdmin\"),\n list_fields = list_fields)\n return True\n s3.prep = prep\n\n rheader = group_rheader\n return s3_rest_controller(rheader = rheader,\n # Allow components with components (such as problem) to breakout from tabs\n native = True,\n )\n\n# =============================================================================\n# Problems\n# =============================================================================\ndef problem_rheader(r, tabs = []):\n \"\"\" Problem rheader \"\"\"\n\n if r.representation == \"html\":\n if r.record is None:\n # List or Create form: rheader makes no sense here\n return None\n\n problem = r.record\n\n tabs = [# Components & Custom Methods\n (T(\"Problems\"), \"problems\"),\n (T(\"Solutions\"), \"solution\"),\n (T(\"Discuss\"), \"discuss\"),\n (T(\"Vote\"), \"vote\"),\n (T(\"Scale of Results\"), \"results\"),\n ]\n\n # Get this User's permissions for this Group\n duser = s3db.delphi_DelphiUser(problem.group_id)\n if duser.authorised:\n tabs.append((T(\"Edit\"), None))\n\n rheader_tabs = s3_rheader_tabs(r, tabs)\n\n rtable = TABLE(TR(TH(\"%s: \" % T(\"Problem\")),\n problem.name,\n TH(\"%s: \" % T(\"Active\")),\n problem.active,\n ),\n TR(TH(\"%s: \" % T(\"Description\")),\n problem.description,\n ),\n TR(TH(\"%s: \" % T(\"Criteria\")),\n problem.criteria,\n ),\n )\n\n if r.component and \\\n r.component_name == \"solution\" and \\\n r.component_id:\n stable = s3db.delphi_solution\n query = (stable.id == r.component_id)\n solution = db(query).select(stable.name,\n stable.description,\n limitby=(0, 1)).first()\n rtable.append(DIV(TR(TH(\"%s: \" % T(\"Solution\")),\n solution.name,\n ),\n TR(TH(\"%s: \" % T(\"Description\")),\n solution.description,\n ),\n ))\n\n rheader = DIV(rtable,\n rheader_tabs)\n return rheader\n\n# -----------------------------------------------------------------------------\ndef problem():\n \"\"\" Problem REST Controller \"\"\"\n\n tablename = \"%s_%s\" % (module, resourcename)\n table = s3db[tablename]\n\n # Custom Methods\n set_method = s3db.set_method\n set_method(module, resourcename,\n method=\"problems\",\n action=problems)\n\n set_method(module, resourcename,\n method=\"discuss\",\n action=discuss)\n\n # Discussion can also be done at the Solution component level\n set_method(module, resourcename,\n component_name=\"solution\",\n method=\"discuss\",\n action=discuss)\n\n set_method(module, resourcename,\n method=\"vote\",\n action=vote)\n\n set_method(module, resourcename,\n method=\"results\",\n action=results)\n\n # Filter to just Active Problems\n s3.filter = (table.active == True)\n\n if not s3_has_role(\"DelphiAdmin\"):\n s3db.configure(tablename,\n deletable = False,\n # Remove ability to create new Problems\n #insertable = False\n )\n\n def prep(r):\n if r.interactive:\n if r.record:\n duser = s3db.delphi_DelphiUser(r.record.group_id)\n if duser.authorised:\n s3db.configure(tablename,\n deletable = True,\n )\n if r.component_name == \"solution\":\n r.component.table.modified_on.label = T(\"Last Updated\")\n s3db.configure(r.component.tablename,\n deletable = duser.authorised,\n )\n return True\n s3.prep = prep\n\n def postp(r, output):\n if r.interactive:\n if not r.component:\n s3.actions = [\n dict(label=str(T(\"Solutions\")),\n _class=\"action-btn\",\n url=URL(args=[\"[id]\", \"solution\"])),\n dict(label=str(T(\"Vote\")),\n _class=\"action-btn\",\n url=URL(args=[\"[id]\", \"vote\"])),\n ]\n elif r.component_name == \"solution\":\n s3.actions = [\n dict(label=str(T(\"Discuss\")),\n _class=\"action-btn\",\n url=URL(args=[r.id, \"solution\", \"[id]\", \"discuss\"])),\n ]\n return output\n s3.postp = postp\n\n rheader = problem_rheader\n return s3_rest_controller(rheader=rheader)\n\n# -----------------------------------------------------------------------------\ndef problems(r, **attr):\n \"\"\"\n Redirect to the list of Problems for the Group\n - used for a Tab\n \"\"\"\n\n try:\n group_id = r.record.group_id\n except:\n raise HTTP(400)\n else:\n redirect(URL(f=\"group\", args=[group_id, \"problem\"]))\n\n# -----------------------------------------------------------------------------\ndef solution():\n \"\"\"\n Used for Imports\n \"\"\"\n\n return s3_rest_controller()\n\n# =============================================================================\n# Voting\n# =============================================================================\ndef vote(r, **attr):\n \"\"\"\n Custom Method to allow Voting on Solutions to a Problem\n \"\"\"\n\n problem = r.record\n\n # Get this User's permissions for this Group\n duser = s3db.delphi_DelphiUser(problem.group_id)\n\n # Add the RHeader to maintain consistency with the other pages\n rheader = problem_rheader(r)\n\n # Lookup Solution Options\n stable = s3db.delphi_solution\n query = (stable.problem_id == problem.id)\n rows = db(query).select(stable.id,\n stable.name)\n options = Storage()\n for row in rows:\n options[row.id] = row.name\n\n if duser.user_id:\n vtable = s3db.delphi_vote\n query = (vtable.problem_id == problem.id) & \\\n (vtable.created_by == auth.user.id)\n votes = db(query).select(vtable.solution_id,\n orderby = vtable.rank)\n else:\n votes = []\n\n rankings = OrderedDict()\n for v in votes:\n # Add to the list of ranked options\n rankings[v.solution_id] = options[v.solution_id]\n # Remove from the unranked options\n options.pop(v.solution_id)\n\n # Add Custom CSS from Static (cacheable)\n s3.stylesheets.append(\"S3/delphi.css\")\n\n # Add Custom Javascript\n # Settings to be picked up by Static code\n js = \"\".join((\n'''var problem_id=''', str(problem.id), '''\ni18n.delphi_failed=\"''', str(T(\"Failed!\")), '''\"\ni18n.delphi_saving=\"''', str(T(\"Saving...\")), '''\"\ni18n.delphi_saved=\"''', str(T(\"Saved.\")), '''\"\ni18n.delphi_vote=\"''', str(T(\"Save Vote\")), '''\"'''))\n s3.js_global.append(js)\n\n # Static code which can be cached\n s3.scripts.append(URL(c=\"static\", f=\"scripts\",\n args=[\"S3\", \"s3.delphi.js\"]))\n\n response.view = \"delphi/vote.html\"\n return dict(rheader = rheader,\n duser = duser,\n votes = votes,\n options = options,\n rankings = rankings,\n )\n\n# -----------------------------------------------------------------------------\ndef save_vote():\n \"\"\"\n Function accessed by AJAX from vote() to save the results of a Vote\n \"\"\"\n\n try:\n problem_id = request.args[0]\n except:\n raise HTTP(400)\n\n ptable = s3db.delphi_problem\n query = (ptable.id == problem_id)\n problem = db(query).select(ptable.group_id,\n limitby=(0, 1)).first()\n if not problem:\n raise HTTP(404)\n\n # Get this User's permissions for this Group\n duser = s3db.delphi_DelphiUser(problem.group_id)\n\n if not duser.can_vote:\n auth.permission.fail()\n\n # Decode the data\n try:\n rankings = request.post_vars.keys()[0].split(\",\")\n except IndexError:\n status = current.xml.json_message(False, 400, \"No Options Ranked\")\n raise HTTP(400, body=status)\n\n # Check the votes are valid\n stable = s3db.delphi_solution\n query = (stable.problem_id == problem_id)\n solutions = db(query).select(stable.id)\n options = []\n for row in solutions:\n options.append(row.id)\n for ranked in rankings:\n if int(ranked) not in options:\n status = current.xml.json_message(False, 400, \"Option isn't valid!\")\n raise HTTP(400, body=status)\n\n # Convert to a format suitable for comparisons\n votes = []\n count = 1\n for ranked in rankings:\n votes.append(Storage(solution_id=int(ranked), rank=count))\n count += 1\n\n # Read the old votes\n vtable = s3db.delphi_vote\n query = (vtable.problem_id == problem_id) & \\\n (vtable.created_by == auth.user.id)\n old_votes = db(query).select(vtable.solution_id,\n vtable.rank)\n if old_votes:\n # Calculate changes\n ranks = {}\n old_ranks = {}\n used = []\n for solution in solutions:\n s1 = solution.id\n ranks[s1] = 0\n old_ranks[s1] = 0\n for vote in votes:\n if vote.solution_id == s1:\n ranks[s1] = vote.rank\n continue\n for vote in old_votes:\n if vote.solution_id == s1:\n old_ranks[s1] = vote.rank\n continue\n for sol_2 in solutions:\n changed = False\n s2 = sol_2.id\n if s2 == s1:\n continue\n if (s2, s1) in used:\n # We've already evaluated this pair\n continue\n ranks[s2] = 0\n old_ranks[s2] = 0\n for vote in votes:\n if vote.solution_id == s2:\n ranks[s2] = vote.rank\n continue\n for vote in old_votes:\n if vote.solution_id == s2:\n old_ranks[s2] = vote.rank\n continue\n if (ranks[s1] > ranks[s2]) and \\\n (old_ranks[s1] < old_ranks[s2]):\n changed = True\n elif (ranks[s1] < ranks[s2]) and \\\n (old_ranks[s1] > old_ranks[s2]):\n changed = True\n elif (ranks[s1] == ranks[s2]) and \\\n (old_ranks[s1] != old_ranks[s2]):\n changed = True\n elif (ranks[s1] != ranks[s2]) and \\\n (old_ranks[s1] == old_ranks[s2]):\n changed = True\n if changed:\n # This pair has changed places, so update Solution\n db(stable.id.belongs((s1, s2))).update(changes=stable.changes + 1)\n used.append((s1, s2))\n\n # Clear the old votes\n db(query).delete()\n\n # Save the new votes\n count = 1\n for ranked in rankings:\n vtable.insert(problem_id=problem_id, solution_id=ranked, rank=count)\n count += 1\n\n status = current.xml.json_message(True, 200, \"Vote saved\")\n return status\n\n# -----------------------------------------------------------------------------\ndef _getUnitNormalDeviation(zscore):\n \"\"\"\n Utility function used by Scale of Results\n\n Looks up the Unit Normal Deviation based on the Z-Score (Proportion/Probability)\n http://en.wikipedia.org/wiki/Standard_normal_table\n\n @ToDo: Move to S3Statistics module\n \"\"\"\n\n UNIT_NORMAL = (\n ( 0.0, .0, .01, .02, .03, .04, .05, .06, .07, .08, .09 ),\n ( .0, .5000, .5040, .5080, .5120, .5160, .5199, .5239, .5279, .5319, .5359 ),\n ( .1, .5398, .5438, .5478, .5517, .5557, .5596, .5636, .5675, .5714, .5753 ),\n ( .2, .5793, .5832, .5871, .5910, .5948, .5987, .6026, .6064, .6103, .6141 ),\n ( .3, .6179, .6217, .6255, .6293, .6331, .6368, .6406, .6443, .6480, .6517 ),\n ( .4, .6554, .6591, .6628, .6664, .6700, .6736, .6772, .6808, .6844, .6879 ),\n\n ( .5, .6915, .6950, .6985, .7019, .7054, .7088, .7123, .7157, .7190, .7224 ),\n ( .6, .7257, .7291, .7324, .7357, .7389, .7422, .7454, .7486, .7517, .7549 ),\n ( .7, .7580, .7611, .7642, .7673, .7703, .7734, .7764, .7794, .7823, .7852 ),\n ( .8, .7881, .7910, .7939, .7967, .7995, .8023, .8051, .8078, .8106, .8133 ),\n ( .9, .8159, .8186, .8212, .8238, .8264, .8289, .8315, .8340, .8365, .8389 ),\n\n ( 1.0, .8415, .8438, .8461, .8485, .8508, .8531, .8554, .8577, .8509, .8621 ),\n ( 1.1, .8643, .8665, .8686, .8708, .8729, .8749, .8770, .8790, .8810, .8830 ),\n ( 1.2, .8849, .8869, .8888, .8907, .8925, .8944, .8962, .8980, .8997, .90147 ),\n ( 1.3, .90320, .90490, .90658, .90824, .90988, .91149, .91309, .91466, .91621, .91774 ),\n ( 1.4, .91924, .92073, .92220, .92364, .92507, .92647, .92785, .92922, .93056, .93189 ),\n\n ( 1.5, .93319, .93448, .93574, .93699, .93822, .93943, .94062, .94179, .94295, .94408 ),\n ( 1.6, .94520, .94630, .94738, .94845, .94950, .95053, .95154, .95254, .95352, .95449 ),\n ( 1.7, .95543, .95637, .95728, .95818, .95907, .95994, .96080, .96164, .96246, .96327 ),\n ( 1.8, .96407, .96485, .96562, .96638, .96712, .96784, .97856, .96926, .96995, .97062 ),\n ( 1.9, .97128, .97193, .97257, .97320, .97381, .97441, .97500, .97558, .97615, .97670 ),\n\n ( 2.0, .97725, .97778, .97831, .97882, .97932, .97982, .98030, .98077, .98124, .98169 ),\n ( 2.1, .98214, .98257, .98300, .98341, .98382, .98422, .98461, .98500, .98537, .98574 ),\n ( 2.2, .98610, .98645, .98679, .98713, .98745, .98778, .98809, .98840, .98870, .98899 ),\n ( 2.3, .98928, .98956, .98983, .990097, .990358, .990613, .990863, .991106, .991344, .991576 ),\n ( 2.4, .991802, .992024, .992240, .992451, .992656, .992857, .993053, .993244, .993431, .993613 ),\n\n ( 2.5, .993790, .993963, .994132, .994297, .994457, .994614, .994766, .994915, .995060, .995201 ),\n ( 2.6, .995339, .995473, .995604, .995731, .995855, .995975, .996093, .996207, .996319, .996427 ),\n ( 2.7, .996533, .996636, .996736, .996833, .996928, .997020, .997110, .997197, .997282, .997365 ),\n ( 2.8, .997445, .997523, .997599, .997673, .997744, .997814, .997882, .997948, .998012, .998074 ),\n ( 2.9, .998134, .998193, .998250, .998305, .998359, .998411, .998460, .998511, .998559, .998605 ),\n\n ( 3.0, .998650, .998694, .998736, .998777, .998817, .998856, .998893, .998930, .998965, .998999 ),\n ( 3.1, .9990324, .9990646, .9990957, .9991260, .9991553, .9991836, .9992112, .9992378, .9992636, .9992886 ),\n ( 3.2, .9993129, .9993363, .9993590, .9993810, .9994024, .9994230, .9994429, .9994623, .9994810, .9994991 ),\n ( 3.3, .9995166, .9995335, .9995499, .9995658, .9995811, .9995959, .9996103, .9996242, .9996376, .9996505 ),\n ( 3.4, .9996631, .9996752, .9996869, .9996982, .9997091, .9997197, .9997299, .9997398, .9997493, .9997585 ),\n\n ( 3.5, .9997674, .9997759, .9997842, .9997922, .9997999, .9998074, .9998146, .9998215, .9998282, .9998347 ),\n ( 3.6, .9998409, .9998469, .9998527, .9998583, .9998637, .9998689, .9998739, .9998787, .9998834, .9998879 ),\n ( 3.7, .9998922, .9998964, .99990039, .99990426, .99990799, .99991158, .99991504, .99991838, .99992159, .99992468 ),\n ( 3.8, .99992765, .99993052, .99993327, .99993593, .99993848, .99994094, .99994331, .99994558, .99994777, .99994988 ),\n ( 3.9, .99995190, .99995385, .99995573, .99995753, .99995926, .99996092, .99996253, .99996406, .99996554, .99996696 ),\n\n ( 4.0, .99996833, .99996964, .99997090, .99997211, .99997327, .99997439, .99997546, .99997649, .99997748, .99997843 ),\n ( 4.1, .99997934, .99998022, .99998106, .99998186, .99998263, .99998338, .99998409, .99998477, .99998542, .99998605 ),\n ( 4.2, .99998665, .99998723, .99998778, .99998832, .99998882, .99998931, .99998978, .999990226, .999990655, .999991066 ),\n ( 4.3, .999991460, .999991837, .999992199, .999992545, .999992876, .999993193, .999993497, .999993788, .999994066, .999994332 ),\n ( 4.4, .999994587, .999994831, .999995065, .999995288, .999995502, .999995706, .999995902, .999996089, .999996268, .999996439 ),\n\n ( 4.5, .999996602, .999996759, .999996908, .999997051, .999997187, .999997318, .999997442, .999997561, .999997675, .999997784 ),\n ( 4.6, .999997888, .999997987, .999998081, .999998172, .999998258, .999998340, .999998419, .999998494, .999998566, .999998634 ),\n ( 4.7, .999998699, .999998761, .999998821, .999998877, .999998931, .999998983, .9999990320, .9999990789, .9999991235, .9999991661 ),\n ( 4.8, .9999992067, .9999992453, .9999992822, .9999993173, .9999993508, .9999993827, .9999994131, .9999994420, .9999994696, .9999994958 ),\n ( 4.9, .9999995208, .9999995446, .9999995673, .9999995889, .9999996094, .9999996289, .9999996475, .9999996652, .9999996821, .9999996981 )\n )\n\n # Assume indifference\n unitDeviation = 0.0\n\n for j in range(1, 50):\n if zscore == UNIT_NORMAL[j][1]:\n unitDeviation = UNIT_NORMAL[j][0]\n elif (UNIT_NORMAL[j][1] < zscore) and (zscore < UNIT_NORMAL[j + 1][1]):\n for i in range(2, 10):\n if (UNIT_NORMAL[j][i - 1] < zscore) and (zscore <= UNIT_NORMAL[j][i]):\n unitDeviation = UNIT_NORMAL[j][0] + UNIT_NORMAL[0][i]\n if zscore > UNIT_NORMAL[j][10]:\n unitDeviation = UNIT_NORMAL[j + 1][0]\n\n if zscore > UNIT_NORMAL[50][10]:\n # maximum value\n unitDeviation = 5.0\n\n return unitDeviation\n\n# -----------------------------------------------------------------------------\ndef online_variance(data):\n \"\"\"\n A numerically stable algorithm for calculating variance\n http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#On-line_algorithm\n \"\"\"\n\n n = 0\n mean = 0\n M2 = 0\n\n for x in data:\n n = n + 1\n delta = x - mean\n mean = mean + delta/n\n M2 = M2 + delta*(x - mean)\n\n variance_n = M2/n\n variance = M2/(n - 1)\n return (variance, variance_n)\n\n# -----------------------------------------------------------------------------\ndef results(r, **attr):\n \"\"\"\n Custom Method to show the Scale of Results\n \"\"\"\n\n def NBSP():\n return XML(\"&nbsp;\")\n\n # Add the RHeader to maintain consistency with the other pages\n rheader = problem_rheader(r)\n\n response.view = \"delphi/results.html\"\n\n empty = dict(rheader=rheader,\n num_voted=0,\n chart=\"\",\n table_color=\"\",\n grids=\"\",\n summary=\"\"\n )\n\n problem = r.record\n\n # Lookup Votes\n if problem:\n vtable = s3db.delphi_vote\n query = (vtable.problem_id == problem.id)\n votes = db(query).select(vtable.solution_id,\n vtable.rank,\n vtable.created_by)\n else:\n votes = None\n if not votes:\n return empty\n\n # Lookup Solutions\n stable = s3db.delphi_solution\n query = (stable.problem_id == problem.id)\n solutions = db(query).select(stable.id,\n stable.name,\n stable.problem_id, # Needed for Votes virtual field\n stable.changes)\n\n if not solutions:\n return empty\n\n # Initialise arrays of pairwise comparisons\n arrayF = {}\n arrayP = {}\n arrayX = {}\n arrayP2 = {}\n arrayU = {}\n for solution in solutions:\n s1 = solution.id\n for sol_2 in solutions:\n s2 = sol_2.id\n if s1 == s2:\n arrayF[(s1, s2)] = None\n arrayP[(s1, s2)] = None\n arrayX[(s1, s2)] = None\n arrayP2[(s1, s2)] = None\n arrayU[(s1, s2)] = None\n continue\n arrayF[(s1, s2)] = 0\n # Allow new solutions to start at an indifferent probability\n arrayP[(s1, s2)] = 0.5\n arrayX[(s1, s2)] = 0\n arrayP2[(s1, s2)] = 0.5\n arrayU[(s1, s2)] = 0.5\n\n # List of Voters\n voters = []\n for vote in votes:\n voter = vote.created_by\n if voter not in voters:\n voters.append(voter)\n num_voted = len(voters)\n\n # Update array of pairwise comparisons based on votes\n # Create array F which is the number of time a solution has been preferred compared to it'a partner\n for voter in voters:\n ranks = {}\n for vote in votes:\n if vote.created_by != voter:\n continue\n ranks[vote.rank] = vote.solution_id\n for rank_1 in range(1, len(ranks)):\n for rank_2 in range(rank_1 + 1, len(ranks) + 1):\n arrayF[(ranks[rank_1], ranks[rank_2])] += 1\n\n grids = DIV()\n header = TR(TD())\n rows = TBODY()\n for solution in solutions:\n header.append(TH(solution.name))\n s1 = solution.id\n row = TR(TH(solution.name))\n for sol_2 in solutions:\n s2 = sol_2.id\n # Preferred should be the columns\n value = arrayF[(s2, s1)]\n if value is None:\n row.append(TD(\"-\"))\n else:\n row.append(TD(value))\n rows.append(row)\n output = TABLE(THEAD(header), rows,\n _class=\"delphi_wide\")\n output = DIV(H4(T(\"Array F: # times that solution in column is preferred over it's partner in row\")),\n output)\n grids.append(output)\n grids.append(NBSP())\n\n # Use the pairwise comparisons to build a Dynamic Thurstone scale of results\n # http://en.wikipedia.org/wiki/Thurstone_scale\n # http://www.brocku.ca/MeadProject/Thurstone/Thurstone_1927a.html\n # http://www.brocku.ca/MeadProject/Thurstone/Thurstone_1927f.html\n # @ToDo: For incomplete data, the calculation is more complex: Gulliksen\n # Convert array F to array P by converting totals to proportions\n # Convert array P to array X, which is the unit normal deviate\n for solution in solutions:\n s1 = solution.id\n for sol_2 in solutions:\n s2 = sol_2.id\n if s1 == s2:\n continue\n total = float(arrayF[(s1, s2)] + arrayF[(s2, s1)])\n # Preferred should be the columns\n if total:\n proportion = arrayF[(s2, s1)] / total\n else:\n # No votes yet, so assume indifference\n proportion = 0.5\n arrayP[(s2, s1)] = proportion\n # Cannot do unit normal deviation for 0/1 so approximate in order to not have to do the incomplete data maths\n if proportion == 0.0:\n arrayX[(s2, s1)] = _getUnitNormalDeviation(0.01)\n elif proportion == 1.0:\n arrayX[(s2, s1)] = _getUnitNormalDeviation(0.99)\n else:\n arrayX[(s2, s1)] = _getUnitNormalDeviation(proportion)\n # Now calculate the uncertainty scale\n # i.e. assume that every user who didn't vote on a particular pair drags that back towards indifference\n novotes = num_voted - total\n if proportion == 0.5:\n pass\n elif proportion > 0.5:\n # Assume the novotes vote against\n proportion = (arrayF[s2, s1] - novotes) / num_voted\n else:\n # Assume the novotes vote for\n proportion = (arrayF[s2, s1] + novotes) / num_voted\n arrayP2[(s2, s1)] = proportion\n # Cannot do unit normal deviation for 0/1 so approximate in order to not have to do the incomplete data maths\n if proportion == 0.0:\n arrayU[(s2, s1)] = _getUnitNormalDeviation(0.01)\n elif proportion == 1.0:\n arrayU[(s2, s1)] = _getUnitNormalDeviation(0.99)\n else:\n arrayU[(s2, s1)] = _getUnitNormalDeviation(proportion)\n\n header = TR(TD())\n rows = TBODY()\n for solution in solutions:\n header.append(TH(solution.name))\n s1 = solution.id\n row = TR(TH(solution.name))\n for sol_2 in solutions:\n s2 = sol_2.id\n # Preferred should be the columns\n value = arrayP[(s2, s1)]\n if value is None:\n row.append(TD(\"-\"))\n else:\n row.append(TD(value))\n\n rows.append(row)\n output = TABLE(THEAD(header), rows,\n _class=\"delphi_wide\")\n output = DIV(H4(T(\"Array P: proportion of times that solution in column is preferred over it's partner in row, assuming that pairs not ranked start at the level of indifference (0.5)\")),\n output)\n grids.append(output)\n grids.append(NBSP())\n\n header = TR(TD())\n rows = TBODY()\n footer = TR(TH(\"Total\"))\n footer2 = TR(TH(\"Scale\"))\n totals = {}\n counts = {}\n for solution in solutions:\n s1 = solution.id\n totals[s1] = 0\n counts[s1] = 0\n for solution in solutions:\n header.append(TH(solution.name))\n s1 = solution.id\n row = TR(TH(solution.name))\n for sol_2 in solutions:\n s2 = sol_2.id\n # Preferred should be the columns\n value = arrayX[(s2, s1)]\n if value is None:\n row.append(TD(\"-\"))\n else:\n row.append(TD(value))\n if value is not None:\n totals[s2] += value\n counts[s2] += 1\n rows.append(row)\n\n # Least-squares estimate of the scale values\n # Average of the columns\n for solution in solutions:\n s1 = solution.id\n footer.append(TH(totals[s1]))\n if counts[s1]:\n solution.scale = totals[s1]/counts[s1]\n footer2.append(TH(solution.scale))\n else:\n solution.scale = 0\n footer2.append(TH())\n\n output = TABLE(THEAD(header), rows, footer, footer2,\n _class=\"delphi_wide\")\n output = DIV(H4(T(\"Array X: unit normal deviate\")),\n output)\n grids.append(output)\n grids.append(NBSP())\n\n header = TR(TD())\n rows = TBODY()\n for solution in solutions:\n header.append(TH(solution.name))\n s1 = solution.id\n row = TR(TH(solution.name))\n for sol_2 in solutions:\n s2 = sol_2.id\n # Preferred should be the columns\n value = arrayP2[(s2, s1)]\n if value is None:\n row.append(TD(\"-\"))\n else:\n row.append(TD(value))\n\n rows.append(row)\n output = TABLE(THEAD(header), rows,\n _class=\"delphi_wide\")\n output = DIV(H4(T(\"Array P2: proportion of times that solution in column is preferred over it's partner in row, assuming that non-votes move towards indifference\")),\n output)\n grids.append(output)\n grids.append(NBSP())\n\n header = TR(TD())\n rows = TBODY()\n footer = TR(TH(\"Total\"))\n footer2 = TR(TH(\"Scale\"))\n totals = {}\n counts = {}\n for solution in solutions:\n s1 = solution.id\n totals[s1] = 0\n counts[s1] = 0\n for solution in solutions:\n header.append(TH(solution.name))\n s1 = solution.id\n row = TR(TH(solution.name))\n for sol_2 in solutions:\n s2 = sol_2.id\n # Preferred should be the columns\n value = arrayU[(s2, s1)]\n if value is None:\n row.append(TD(\"-\"))\n else:\n row.append(TD(value))\n if value is not None:\n totals[s2] += value\n counts[s2] += 1\n rows.append(row)\n\n # Least-squares estimate of the uncertainty values\n # Average of the columns\n for solution in solutions:\n s1 = solution.id\n footer.append(TH(totals[s1]))\n if counts[s1]:\n solution.uncertainty = totals[s1]/counts[s1]\n footer2.append(TH(solution.uncertainty))\n else:\n solution.uncertainty = 0\n footer2.append(TH())\n\n output = TABLE(THEAD(header), rows, footer, footer2,\n _class=\"delphi_wide\")\n output = DIV(H4(T(\"Array U: unit normal deviate of the uncertainty value (assuming that all unvoted items return the probability towards indifference)\")),\n output)\n grids.append(output)\n\n # Sort the Solutions by Scale\n def scale(solution):\n return float(solution.scale)\n\n solutions = solutions.sort(scale, reverse=True)\n\n n = len(solutions)\n\n # @ToDo: deployment_setting\n image = \"\"\n if image:\n # Canvas of 900x600\n from s3chart import S3Chart\n chart = S3Chart(9, 6)\n fig = chart.fig\n # Add Axes with padding of 10px for the labels (fractional left, bottom, width, height)\n ax = fig.add_axes([0.35, 0.1, 0.6, 0.8])\n\n problem = r.record\n ax.set_title(problem.name)\n\n labels = []\n scales = []\n uncertainties = []\n for solution in solutions:\n labels.append(solution.name)\n scales.append(solution.scale)\n uncertainties.append(solution.uncertainty)\n from numpy import arange\n ind = arange(n)\n width = .35\n ax.set_yticks(ind + width)\n ax.set_yticklabels(labels)\n labels = ax.get_yticklabels()\n for label in labels:\n label.set_size(8)\n\n ax.set_xlabel(\"Scale\") # rotation=\"vertical\" or rotation = 45\n ax.xaxis.grid(True)\n\n rects1 = ax.barh(ind, scales, width, linewidth=0) # color=\"blue\"\n rects2 = ax.barh(ind + width, uncertainties, width, linewidth=0, color=\"red\")\n\n ax.legend( (rects1[0], rects2[0]), (\"Scale\", \"Uncertainty\") )\n\n image = chart.draw()\n\n # Colour the rows\n # Calculate Breaks\n classes = 5\n q = []\n qappend = q.append\n for i in range(classes - 1):\n qappend(1.0 / classes * (i + 1))\n values = [float(solution.scale) for solution in solutions]\n breaks = s3db.stats_quantile(values, q)\n # Make mutable\n breaks = list(breaks)\n values_min = min(values)\n values_max = max(values)\n breaks.insert(0, values_min)\n breaks.append(values_max)\n # Apply colours\n # 5-class BuGn from ColorBrewer.org\n colours = [\"edf8fb\",\n \"b2e2e2\",\n \"66c2a4\",\n \"2ca25f\",\n \"006d2c\",\n ]\n for solution in solutions:\n for i in range(classes):\n value = solution.scale\n if value >= breaks[i] and \\\n value <= breaks[i + 1]:\n solution.color = colours[i]\n break\n\n # A table showing overall rankings\n thead = THEAD(\n TR(\n TH(T(\"Solution Item\"), _rowspan=\"2\"),\n TH(T(\"Scale\"), _rowspan=\"2\"),\n TH(T(\"Uncertainty\"), _rowspan=\"2\"),\n TH(T(\"Activity Level\"), _colspan=\"3\"),\n ),\n TR(\n TH(T(\"Voted on\")),\n TH(T(\"Times Changed\")),\n TH(T(\"Comments\")),\n ),\n )\n tbody = TBODY()\n for solution in solutions:\n rows = True\n tbody.append(\n TR(\n TD(solution.name),\n TD(solution.scale,\n _class=\"taright\"),\n TD(solution.uncertainty,\n _class=\"taright\"),\n TD(solution.votes(),\n _class=\"tacenter\"),\n TD(solution.changes,\n _class=\"tacenter\"),\n TD(solution.comments(),\n _class=\"tacenter\"),\n _style=\"background:#%s\" % solution.color\n )\n )\n summary = TABLE(thead,\n tbody,\n _class=\"delphi_wide\")\n\n # Add Custom CSS from Static (cacheable)\n s3.stylesheets.append(\"S3/delphi.css\")\n\n return dict(rheader=rheader,\n num_voted=num_voted,\n chart=image,\n summary=summary,\n grids=grids\n )\n\n# =============================================================================\n# Discussions\n# =============================================================================\ndef discuss(r, **attr):\n \"\"\" Custom Method to manage the discussion of a Problem or Solution \"\"\"\n\n if r.component:\n resourcename = \"solution\"\n id = r.component_id\n else:\n resourcename = \"problem\"\n id = r.id\n\n # Add the RHeader to maintain consistency with the other pages\n rheader = problem_rheader(r)\n\n ckeditor = URL(c=\"static\", f=\"ckeditor\", args=\"ckeditor.js\")\n s3.scripts.append(ckeditor)\n adapter = URL(c=\"static\", f=\"ckeditor\", args=[\"adapters\",\n \"jquery.js\"])\n s3.scripts.append(adapter)\n\n # Toolbar options: http://docs.cksource.com/CKEditor_3.x/Developers_Guide/Toolbar\n js = \"\".join((\n'''i18n.reply=\"''', str(T(\"Reply\")), '''\"\nvar img_path=S3.Ap.concat('/static/img/jCollapsible/')\nvar ck_config={toolbar:[['Bold','Italic','-','NumberedList','BulletedList','-','Link','Unlink','-','Smiley','-','Source','Maximize']],toolbarCanCollapse:false,removePlugins:'elementspath'}\nfunction comment_reply(id){\n $('#delphi_comment_solution_id__row').hide()\n $('#delphi_comment_solution_id__row1').hide()\n $('#comment-title').html(i18n.reply)\n var ed = $('#delphi_comment_body').ckeditorGet()\n ed.destroy()\n $('#delphi_comment_body').ckeditor(ck_config)\n $('#comment-form').insertAfter($('#comment-'+id))\n $('#delphi_comment_parent').val(id)\n var solution_id=$('#comment-'+id).attr('solution_id')\n if(undefined!=solution_id){\n $('#delphi_comment_solution_id').val(solution_id)\n }\n}'''))\n\n s3.js_global.append(js)\n\n response.view = \"delphi/discuss.html\"\n return dict(rheader=rheader,\n resourcename=resourcename,\n id=id)\n\n# -----------------------------------------------------------------------------\ndef comment_parse(comment, comments, solution_id=None):\n \"\"\"\n Parse a Comment\n\n @param: comment - a gluon.sql.Row: the current comment\n @param: comments - a gluon.sql.Rows: full list of comments\n @param: solution_id - a reference ID: optional solution commented on\n \"\"\"\n\n author = B(T(\"Anonymous\"))\n if comment.created_by:\n utable = s3db.auth_user\n ptable = s3db.pr_person\n ltable = s3db.pr_person_user\n query = (utable.id == comment.created_by)\n left = [ltable.on(ltable.user_id == utable.id),\n ptable.on(ptable.pe_id == ltable.pe_id)]\n row = db(query).select(utable.email,\n ptable.first_name,\n ptable.middle_name,\n ptable.last_name,\n left=left, limitby=(0, 1)).first()\n if row:\n person = row.pr_person\n user = row[utable._tablename]\n username = s3_fullname(person)\n email = user.email.strip().lower()\n import hashlib\n hash = hashlib.md5(email).hexdigest()\n url = \"http://www.gravatar.com/%s\" % hash\n author = B(A(username, _href=url, _target=\"top\"))\n if not solution_id and comment.solution_id:\n solution = \"re: %s\" % s3db.delphi_solution_represent(comment.solution_id)\n header = DIV(author, \" \", solution)\n solution_id = comment.solution_id\n else:\n header = author\n thread = LI(DIV(s3base.s3_avatar_represent(comment.created_by),\n DIV(DIV(header,\n _class=\"comment-header\"),\n DIV(XML(comment.body)),\n _class=\"comment-text\"),\n DIV(DIV(comment.created_on,\n _class=\"comment-date\"),\n DIV(A(T(\"Reply\"),\n _class=\"action-btn\"),\n _onclick=\"comment_reply(%i);\" % comment.id,\n _class=\"comment-reply\"),\n _class=\"fright\"),\n _id=\"comment-%i\" % comment.id,\n _solution_id=solution_id,\n _class=\"comment-box\"))\n\n # Add the children of this thread\n children = UL(_class=\"children\")\n id = comment.id\n count = 0\n for comment in comments:\n if comment.parent == id:\n count = 1\n child = comment_parse(comment, comments, solution_id=solution_id)\n children.append(child)\n if count == 1:\n thread.append(children)\n\n return thread\n\n# -----------------------------------------------------------------------------\ndef comments():\n \"\"\" Function accessed by AJAX from discuss() to handle Comments \"\"\"\n\n try:\n resourcename = request.args[0]\n except:\n raise HTTP(400)\n\n try:\n id = request.args[1]\n except:\n raise HTTP(400)\n\n if resourcename == \"problem\":\n problem_id = id\n solution_id = None\n elif resourcename == \"solution\":\n stable = s3db.delphi_solution\n query = (stable.id == id)\n solution = db(query).select(stable.problem_id,\n limitby=(0, 1)).first()\n if solution:\n problem_id = solution.problem_id\n solution_id = id\n else:\n raise HTTP(400)\n else:\n raise HTTP(400)\n\n table = s3db.delphi_comment\n field = table.problem_id\n field.default = problem_id\n field.writable = field.readable = False\n sfield = table.solution_id\n if solution_id:\n sfield.default = solution_id\n sfield.writable = sfield.readable = False\n else:\n sfield.label = T(\"Related to Solution (optional)\")\n sfield.requires = IS_EMPTY_OR(\n IS_ONE_OF(db, \"delphi_solution.id\",\n s3.delphi_solution_represent,\n filterby=\"problem_id\",\n filter_opts=(problem_id,)\n ))\n\n # Form to add a new Comment\n from gluon.tools import Crud\n form = Crud(db).create(table, formname=\"delphi_%s/%s\" % (resourcename, id))\n\n # List of existing Comments\n if solution_id:\n comments = db(sfield == solution_id).select(table.id,\n table.parent,\n table.body,\n table.created_by,\n table.created_on)\n else:\n comments = db(field == problem_id).select(table.id,\n table.parent,\n table.solution_id,\n table.body,\n table.created_by,\n table.created_on)\n\n output = UL(_id=\"comments\")\n for comment in comments:\n if not comment.parent:\n # Show top-level threads at top-level\n thread = comment_parse(comment, comments, solution_id=solution_id)\n output.append(thread)\n\n # Also see the outer discuss()\n script = \\\n'''$('#comments').collapsible({xoffset:'-5',yoffset:'50',imagehide:img_path+'arrow-down.png',imageshow:img_path+'arrow-right.png',defaulthide:false})\n$('#delphi_comment_parent__row1').hide()\n$('#delphi_comment_parent__row').hide()\n$('#delphi_comment_body').ckeditor(ck_config)\n$('#submit_record__row input').click(function(){$('#comment-form').hide();$('#delphi_comment_body').ckeditorGet().destroy();return true;})'''\n\n # No layout in this output!\n #s3.jquery_ready.append(script)\n\n output = DIV(output,\n DIV(H4(T(\"New Post\"),\n _id=\"comment-title\"),\n form,\n _id=\"comment-form\",\n _class=\"clear\"),\n SCRIPT(script))\n\n return XML(output)\n\n# END =========================================================================\n" ]
[ [ "numpy.arange" ] ]
zhaipro/keras-wdsr
[ "4cb2084d1780739b4d4854087c7cb0c35e875711" ]
[ "src/train.py" ]
[ "import os\n\nimport numpy as np\nfrom keras import backend as K\nfrom keras.losses import mean_absolute_error\n\nimport utils\nfrom model import wdsr_b\n\n\ndef psnr(hr, sr, max_val=2):\n mse = K.mean(K.square(hr - sr))\n return 10.0 / np.log(10) * K.log(max_val ** 2 / mse)\n\n\ndef data_generator(path, batch_size=8, input_shape=96, scale=2):\n '''data generator for fit_generator'''\n fns = os.listdir(path)\n n = len(fns)\n i = 0\n while True:\n lrs, hrs = [], []\n for b in range(batch_size):\n if i == 0:\n np.random.shuffle(fns)\n fn = fns[i]\n fn = os.path.join(path, fn)\n lr, hr = utils.pair(fn, input_shape, scale)\n lr = utils.normalization(lr)\n hr = utils.normalization(hr)\n lrs.append(lr)\n hrs.append(hr)\n i = (i + 1) % n\n lrs = np.array(lrs)\n hrs = np.array(hrs)\n yield lrs, hrs\n\n\nmodel = wdsr_b()\nmodel.compile(optimizer='adam',\n loss=mean_absolute_error, metrics=[psnr])\nmodel.fit_generator(data_generator('./datasets/train/'),\n steps_per_epoch=50,\n epochs=1250)\n" ]
[ [ "numpy.array", "numpy.random.shuffle", "numpy.log" ] ]
psychemedia/numpyarray_to_latex
[ "b729fe7473de51f5e62c0b7092706226ef9c2d65" ]
[ "numpyarray_to_latex/main.py" ]
[ "\"\"\"\nProvides `to_ltx` to convert numpy arrays to LaTeX.\n\"\"\"\n\nimport numpy as np\n\nfrom numpyarray_to_latex.utils import (\n math_form,\n )\n\ndef to_ltx(a,\n fmt='{:6.4f}',\n latexarraytype='array',\n imstring='i',\n is_row_vector=True,\n mathform=True,\n brackets='()',\n mark_elements=[],\n mark_color='pink',\n separate_columns=[],\n separate_rows=[],\n ):\n r\"\"\"\n Return a LaTeX array given a numpy array.\n\n Parameters\n ----------\n a : numpy.ndarray\n fmt : str, default = '{:6.2f}'\n python 3 formatter, optional-\n https://mkaz.tech/python-string-format.html\n latexarraytype : str, default = 'array'\n Any of\n\n .. code:: python\n\n \"array\"\n \"pmatrix\"\n \"bmatrix\"\n \"vmatrix\"\n \"Vmatrix\"\n \"Bmatrix\"\n\n if \"array\", you can specifiy the brackets\n with the keyword ``brackets``.\n imstring : str, default = 'i'\n Character to use to represent the imaginary unit.\n Usually ``'i'`` or ``'j'``\n is_row_vector : bool, default = True\n If the array is 1D, should the output be\n a row (True) or column (False) vector?\n mathform : bool, default = True\n wether to convert strings like ``1e+05``\n to ``1\\times10^{5}``.\n brackets : iterable, default = '()'\n which brackets to use to wrap the matrix\n (must be two elements long).\n Use ``brackets = None`` if you don't want\n any brackets around the array.\n mark_elements : list, default = []\n list of tuples containing element indices that\n should be marked with a colorbox.\n mark_color : str, default = 'pink'\n The color with which to mark matrix elements.\n separate_columns : list, default = []\n list of column indices before which a vertical\n line should be drawn\n separate_rows : list, default = []\n list of row indices before which a horizontal\n line should be drawn\n\n Returns\n -------\n out: str\n Formatted LaTeX string\n\n Examples\n --------\n >>> from numpyarray_to_latex import to_ltx\n >>> tex = to_ltx([[2.,2.],[2.,2.]])\n >>> print(tex)\n \\left(\n \\begin{array}{}\n 2.00 & 2.00\\\\\n 2.00 & 2.00\n \\end{array}\n \\right)\n\n \"\"\"\n a = np.array(a)\n\n if len(a.shape) > 2:\n raise NotImplementedError('Arrays having more than two dimensions cannot be converted.')\n\n if mark_elements is None:\n mark_elements = []\n\n if a.ndim == 2 and len(mark_elements)>0 and not all([hasattr(mark,'__len__') for mark in mark_elements]):\n raise ValueError(\"If the array is 2D, ``mark_elements`` should be 2D as well, but isn't\")\n\n if len(a.shape) == 1:\n if len(mark_elements)>0 and hasattr(mark_elements[0],'__len__'):\n raise ValueError(\"If the array is 1D, ``mark_elements`` should be 1D as well, but isn't.\")\n a = np.array([a])\n if is_row_vector is False:\n a = a.T\n mark_elements = [ (mark,0) for mark in mark_elements]\n else:\n mark_elements = [ (0,mark) for mark in mark_elements]\n\n if isinstance(mark_elements, np.ndarray):\n mark_elements = mark_elements.tolist()\n mark_elements = [ tuple(row) for row in mark_elements ]\n\n\n nrow, ncol = a.shape\n\n out = ''\n\n if brackets is not None and latexarraytype not in [\n \"bmatrix\",\n \"pmatrix\",\n \"vmatrix\",\n \"Bmatrix\",\n \"Vmatrix\",\n ]:\n out = r'\\left' + brackets[0] + '\\n'\n\n if len(separate_columns) > 0:\n\n if latexarraytype != 'array':\n raise ValueError('column separators can only be used for `latexarraytype = \"array\"`')\n\n colstr = '{'\n\n for i in range(ncol):\n if i in separate_columns and i > 0:\n\n colstr += '|'\n colstr += 'c'\n\n colstr += '}'\n else:\n colstr = '{}'\n\n out += r'\\begin{' + latexarraytype + '}' +colstr+'\\n'\n\n for i in np.arange(nrow):\n\n if i in separate_rows and i > 0:\n out += ' \\\\hline\\n'\n\n out = out + ' '\n\n for j in np.arange(ncol):\n this_element = ''\n if np.real(a[i, j]) < 0:\n leadstr = ''\n else:\n leadstr = ' '\n if '.' not in fmt.format(a[i, j]):\n dot_space = ' '\n else:\n dot_space = ''\n if np.iscomplexobj(a[i, j]):\n real = math_form(fmt.format(np.real(a[i, j])),\n mathform=mathform)\n real = real.lstrip(' ')\n imag = math_form(fmt.format(np.imag(a[i, j])),\n is_imaginary=True,\n mathform=mathform)\n imag = imag.lstrip(' ')\n if not (imag.startswith('-') or imag.startswith('+')):\n number = real + '+' + imag\n else:\n number = real + imag\n this_element = (\n this_element\n + leadstr\n + number\n + imstring\n + dot_space\n )\n else:\n this_element = (\n this_element\n + leadstr\n + math_form(fmt.format(np.real(a[i, j])),\n mathform=mathform)\n + dot_space\n )\n\n if (i,j) in mark_elements:\n this_element = r'\\colorbox{'+ mark_color +'}{$'+ this_element+'$} '\n\n if j < ncol-1:\n this_element += r' & '\n\n out += this_element\n\n if i < nrow-1:\n out = out + '\\\\\\\\\\n'\n\n out = out + '\\n' + r'\\end{' + latexarraytype + '}'\n\n if brackets is not None and latexarraytype not in [\n \"bmatrix\",\n \"pmatrix\",\n \"vmatrix\",\n \"Bmatrix\",\n \"Vmatrix\",\n ]:\n out += '\\n\\\\right' + brackets[1]\n\n return out\n" ]
[ [ "numpy.array", "numpy.real", "numpy.iscomplexobj", "numpy.arange", "numpy.imag" ] ]
Roryoung/realworldrl_suite
[ "be7a51cffa7f5f9cb77a387c16bad209e0f851f8" ]
[ "realworldrl_suite/utils/evaluators_test.py" ]
[ "# coding=utf-8\n# Copyright 2020 The Real-World RL Suite Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for evaluators.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nimport numpy as np\nimport realworldrl_suite.environments as rwrl\nfrom realworldrl_suite.utils import evaluators\n\n\nclass RandomAgent(object):\n\n def __init__(self, action_spec):\n self.action_spec = action_spec\n\n def action(self):\n return np.random.uniform(\n self.action_spec.minimum,\n self.action_spec.maximum,\n size=self.action_spec.shape)\n\n\nclass EvaluatorsTest(parameterized.TestCase):\n\n def _gen_stats(self, domain_name, task_name):\n temp_dir = self.create_tempdir()\n env = rwrl.load(\n domain_name=domain_name,\n task_name=task_name,\n safety_spec={'enable': True},\n log_output=os.path.join(temp_dir.full_path, 'test.pickle'),\n environment_kwargs=dict(log_safety_vars=True, flat_observation=True))\n random_policy = RandomAgent(env.action_spec()).action\n for _ in range(3):\n timestep = env.step(random_policy())\n while not timestep.last():\n timestep = env.step(random_policy())\n env.write_logs()\n return env.logs_path\n\n @parameterized.named_parameters(*rwrl.ALL_TASKS)\n def test_loading(self, domain_name, task_name):\n temp_path = self._gen_stats(domain_name, task_name)\n data_in = np.load(temp_path, allow_pickle=True)\n evaluators.Evaluators(data_in)\n\n def test_safety_evaluator(self):\n # TODO(dulacarnold): Make this test general to all envs.\n temp_path = self._gen_stats(\n domain_name='cartpole', task_name='realworld_balance')\n data_in = np.load(temp_path, allow_pickle=True)\n ev = evaluators.Evaluators(data_in)\n self.assertLen(ev.get_safety_evaluator(), 3)\n\n def test_standard_evaluators(self):\n # TODO(dulacarnold): Make this test general to all envs.\n temp_path = self._gen_stats(\n domain_name='cartpole', task_name='realworld_balance')\n data_in = np.load(temp_path, allow_pickle=True)\n ev = evaluators.Evaluators(data_in)\n self.assertLen(ev.get_standard_evaluators(), 5)\n\n @parameterized.named_parameters(*rwrl.ALL_TASKS)\n def test_safety_plot(self, domain_name, task_name):\n temp_path = self._gen_stats(domain_name, task_name)\n data_in = np.load(temp_path, allow_pickle=True)\n ev = evaluators.Evaluators(data_in)\n ev.get_safety_plot()\n\n\nif __name__ == '__main__':\n absltest.main()\n" ]
[ [ "numpy.random.uniform", "numpy.load" ] ]
veds12/aiheaven
[ "4a257f652164870e4d0f0e3f1358834802955562" ]
[ "gcn/layers.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"layers.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n https://colab.research.google.com/drive/1fCQ_zLCcWNzgE99LK9B2cWrql8J3HgBO\n\"\"\"\n# Author : Vedant Shah\n# E-mail : vedantshah2012@gmail.com\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn.parameter import Parameter\n\n\nclass gcn_layer(nn.Module):\n def __init__(self, ip_size, op_size):\n super(gcn_layer, self).__init__()\n self.ip_size = ip_size # number of features for each node in the input\n self.op_size = op_size # number of features for each node in the output\n self.weights = Parameter(\n torch.rand(\n self.ip_size, self.op_size, dtype=torch.float32, requires_grad=True\n )\n )\n\n def compute(self, admat, features):\n\n \"\"\" Forward Propagation through the layer according to the spectral rule \"\"\"\n\n self.D = torch.diag(admat.sum(1), diagonal=0)\n self.out = torch.empty(admat.size[0], self.op_size)\n self.a_hat = admat + torch.eye(\n admat.size[0]\n ) # Counting the contribution of each node to itself\n self.D_inv = self.D ** (-0.5)\n self.a_hat = (\n self.D_inv * self.a_hat * self.D_inv\n ) # Normalising according to the spectral rule\n self.out = torch.dot(\n torch.dot(self.a_hat, features), self.weights\n ) # Forward propagate trhough the layer\n return self.out\n" ]
[ [ "torch.rand", "torch.empty", "torch.eye", "torch.dot" ] ]
aryamccarthy/ANES
[ "29c56f8c46fd4e8b6725f329cb609f4f14a8acb0" ]
[ "notebooks/as_script/1.0-adm-load-data-2012-Copy1.py" ]
[ "\n# coding: utf-8\n\n# # Load and preprocess 2012 data\n# \n# We will, over time, look over other years. Our current goal is to explore the features of a single year.\n# \n# ---\n\n# In[1]:\n\nget_ipython().magic('pylab --no-import-all inline')\nimport pandas as pd\n\n\n# ## Load the data.\n# \n# ---\n# \n# If this fails, be sure that you've saved your own data in the prescribed location, then retry.\n\n# In[2]:\n\nfile = \"../data/interim/2012data.dta\"\ndf_rawest = pd.read_stata(file)\n\n\n# In[7]:\n\ndf_rawest.weight_full.isnull()\n\n\n# In[8]:\n\ngood_columns = [#'campfin_limcorp', # \"Should gov be able to limit corporate contributions\"\n 'pid_x', # Your own party identification\n \n 'abortpre_4point', # Abortion\n 'trad_adjust', # Moral Relativism\n 'trad_lifestyle', # \"Newer\" lifetyles\n 'trad_tolerant', # Moral tolerance\n 'trad_famval', # Traditional Families\n 'gayrt_discstd_x', # Gay Job Discrimination\n 'gayrt_milstd_x', # Gay Military Service\n \n 'inspre_self', # National health insurance\n 'guarpr_self', # Guaranteed Job\n 'spsrvpr_ssself', # Services/Spending\n \n 'aa_work_x', # Affirmative Action ( Should this be aapost_hire_x? )\n 'resent_workway', \n 'resent_slavery', \n 'resent_deserve',\n 'resent_try',\n]\n\ndf_raw = df_rawest[good_columns]\n\n\n# ## Clean the data\n# ---\n\n# In[9]:\n\ndef convert_to_int(s):\n \"\"\"Turn ANES data entry into an integer.\n \n >>> convert_to_int(\"1. Govt should provide many fewer services\")\n 1\n >>> convert_to_int(\"2\")\n 2\n \"\"\"\n try:\n return int(s.partition('.')[0])\n except ValueError:\n warnings.warn(\"Couldn't convert: \"+s)\n return np.nan\n except AttributeError:\n return s\n\ndef negative_to_nan(value):\n \"\"\"Convert negative values to missing.\n \n ANES codes various non-answers as negative numbers.\n For instance, if a question does not pertain to the \n respondent.\n \"\"\"\n return value if value >= 0 else np.nan\n\ndef lib1_cons2_neutral3(x):\n \"\"\"Rearrange questions where 3 is neutral.\"\"\"\n return -3 + x if x != 1 else x\n\ndef liblow_conshigh(x):\n \"\"\"Reorder questions where the liberal response is low.\"\"\"\n return -x\n\ndef dem_edu_special_treatment(x):\n \"\"\"Eliminate negative numbers and {95. Other}\"\"\"\n return np.nan if x == 95 or x <0 else x\n\ndf = df_raw.applymap(convert_to_int)\ndf = df.applymap(negative_to_nan)\n\ndf.abortpre_4point = df.abortpre_4point.apply(lambda x: np.nan if x not in {1, 2, 3, 4} else -x)\n\ndf.loc[:, 'trad_lifestyle'] = df.trad_lifestyle.apply(lambda x: -x) # 1: moral relativism, 5: no relativism\ndf.loc[:, 'trad_famval'] = df.trad_famval.apply(lambda x: -x) # Tolerance. 1: tolerance, 7: not\n\ndf.loc[:, 'spsrvpr_ssself'] = df.spsrvpr_ssself.apply(lambda x: -x)\n\ndf.loc[:, 'resent_workway'] = df.resent_workway.apply(lambda x: -x)\ndf.loc[:, 'resent_try'] = df.resent_try.apply(lambda x: -x)\n\n\ndf.rename(inplace=True, columns=dict(zip(\n good_columns,\n [\"PartyID\",\n \n \"Abortion\",\n \"MoralRelativism\",\n \"NewerLifestyles\",\n \"MoralTolerance\",\n \"TraditionalFamilies\",\n \"GayJobDiscrimination\",\n \"GayMilitaryService\",\n\n \"NationalHealthInsurance\",\n \"StandardOfLiving\",\n \"ServicesVsSpending\",\n\n \"AffirmativeAction\",\n \"RacialWorkWayUp\",\n \"RacialGenerational\",\n \"RacialDeserve\",\n \"RacialTryHarder\",\n ]\n)))\n\n\n# In[10]:\n\nprint(\"Variables now available: df\")\n\n\n# In[11]:\n\ndf_rawest.pid_x.value_counts()\n\n\n# In[12]:\n\ndf.PartyID.value_counts()\n\n\n# In[13]:\n\ndf.describe()\n\n\n# In[14]:\n\ndf.head()\n\n\n# In[21]:\n\ndf.to_csv(\"../data/processed/2012.csv\")\n\n\n# In[15]:\n\ndf_rawest.weight_full.to_csv(\"../data/processed/2012_weights.csv\")\n\n\n# In[16]:\n\ndf_rawest.shapee\n\n\n# In[ ]:\n\n\n\n" ]
[ [ "pandas.read_stata" ] ]
Adrian123K/pandas_ml
[ "05a901c1f5a49aafb4513ef8f0f825210f378983" ]
[ "7.1_simple_linear_regression.py" ]
[ "# -*- coding: utf-8 -*-\n\n### 기본 라이브러리 불러오기\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n'''\n[Step 1] 데이터 준비 - read_csv() 함수로 자동차 연비 데이터셋 가져오기\n'''\n# CSV 파일을 데이터프레임으로 변환\ndf = pd.read_csv('./auto-mpg.csv', header=None)\n\n# 열 이름 지정\ndf.columns = ['mpg','cylinders','displacement','horsepower','weight',\n 'acceleration','model year','origin','name'] \n\n# 데이터 살펴보기\nprint(df.head()) \nprint('\\n')\n\n# IPython 디스플레이 설정 - 출력할 열의 개수 한도 늘리기\npd.set_option('display.max_columns', 10)\nprint(df.head()) \nprint('\\n')\n\n\n'''\n[Step 2] 데이터 탐색\n'''\n\n# 데이터 자료형 확인\nprint(df.info()) \nprint('\\n')\n\n# 데이터 통계 요약정보 확인\nprint(df.describe())\nprint('\\n')\n\n# horsepower 열의 자료형 변경 (문자열 ->숫자)\nprint(df['horsepower'].unique()) # horsepower 열의 고유값 확인\nprint('\\n')\n\ndf['horsepower'].replace('?', np.nan, inplace=True) # '?'을 np.nan으로 변경\ndf.dropna(subset=['horsepower'], axis=0, inplace=True) # 누락데이터 행을 삭제\ndf['horsepower'] = df['horsepower'].astype('float') # 문자열을 실수형으로 변환\n\nprint(df.describe()) # 데이터 통계 요약정보 확인\nprint('\\n')\n\n\n'''\n[Step 3] 속성(feature 또는 variable) 선택\n'''\n\n# 분석에 활용할 열(속성)을 선택 (연비, 실린더, 출력, 중량)\nndf = df[['mpg', 'cylinders', 'horsepower', 'weight']]\nprint(ndf.head()) \nprint('\\n')\n\n### 종속 변수 Y인 \"연비(mpg)\"와 다른 변수 간의 선형관계를 그래프(산점도)로 확인\n# Matplotlib으로 산점도 그리기\nndf.plot(kind='scatter', x='weight', y='mpg', c='coral', s=10, figsize=(10, 5))\nplt.show()\nplt.close()\n\n# seaborn으로 산점도 그리기\nfig = plt.figure(figsize=(10, 5)) \nax1 = fig.add_subplot(1, 2, 1)\nax2 = fig.add_subplot(1, 2, 2)\nsns.regplot(x='weight', y='mpg', data=ndf, ax=ax1) # 회귀선 표시\nsns.regplot(x='weight', y='mpg', data=ndf, ax=ax2, fit_reg=False) #회귀선 미표시\nplt.show()\nplt.close()\n\n# seaborn 조인트 그래프 - 산점도, 히스토그램\nsns.jointplot(x='weight', y='mpg', data=ndf) # 회귀선 없음\nsns.jointplot(x='weight', y='mpg', kind='reg', data=ndf) # 회귀선 표시\nplt.show()\nplt.close()\n\n# seaborn pariplot으로 두 변수 간의 모든 경우의 수 그리기\nsns.pairplot(ndf) \nplt.show()\nplt.close()\n\n\n'''\nStep 4: 데이터셋 구분 - 훈련용(train data)/ 검증용(test data)\n'''\n\n# 속성(변수) 선택\nX=ndf[['weight']] #독립 변수 X\ny=ndf['mpg'] #종속 변수 Y\n\n# train data 와 test data로 구분(7:3 비율)\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, #독립 변수 \n y, #종속 변수\n test_size=0.3, #검증 30%\n random_state=10) #랜덤 추출 값 \n\nprint('train data 개수: ', len(X_train))\nprint('test data 개수: ', len(X_test))\n\n\n'''\nStep 5: 단순회귀분석 모형 - sklearn 사용\n'''\n\n# sklearn 라이브러리에서 선형회귀분석 모듈 가져오기\nfrom sklearn.linear_model import LinearRegression\n\n# 단순회귀분석 모형 객체 생성\nlr = LinearRegression() \n\n# train data를 가지고 모형 학습\nlr.fit(X_train, y_train)\n\n# 학습을 마친 모형에 test data를 적용하여 결정계수(R-제곱) 계산\nr_square = lr.score(X_test, y_test)\nprint(r_square)\nprint('\\n')\n\n# 회귀식의 기울기\nprint('기울기 a: ', lr.coef_)\nprint('\\n')\n\n# 회귀식의 y절편\nprint('y절편 b', lr.intercept_)\nprint('\\n')\n\n# 모형에 전체 X 데이터를 입력하여 예측한 값 y_hat을 실제 값 y와 비교 \ny_hat = lr.predict(X)\n\nplt.figure(figsize=(10, 5))\nax1 = sns.distplot(y, hist=False, label=\"y\")\nax2 = sns.distplot(y_hat, hist=False, label=\"y_hat\", ax=ax1)\nplt.show()\nplt.close()" ]
[ [ "pandas.set_option", "sklearn.linear_model.LinearRegression", "matplotlib.pyplot.close", "matplotlib.pyplot.figure", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.show", "pandas.read_csv" ] ]
diwgan32/IKEA_ASM_Dataset
[ "8f41c15c4a7fb47f53235d2292d0eff8136ae492" ]
[ "action/pose_based/net/utils/graph.py" ]
[ "import numpy as np\n\nclass Graph():\n \"\"\" The Graph to model the skeletons extracted by the openpose\n\n Args:\n strategy (string): must be one of the follow candidates\n - uniform: Uniform Labeling\n - distance: Distance Partitioning\n - spatial: Spatial Configuration\n For more information, please refer to the section 'Partition Strategies'\n in our paper (https://arxiv.org/abs/1801.07455).\n\n layout (string): must be one of the follow candidates\n - openpose: Is consists of 18 joints. For more information, please\n refer to https://github.com/CMU-Perceptual-Computing-Lab/openpose#output\n - ntu-rgb+d: Is consists of 25 joints. For more information, please\n refer to https://github.com/shahroudy/NTURGB-D\n\n max_hop (int): the maximal distance between two connected nodes\n dilation (int): controls the spacing between the kernel points\n\n \"\"\"\n\n def __init__(self,\n layout='openpose',\n strategy='uniform',\n max_hop=1,\n dilation=1):\n self.max_hop = max_hop\n self.dilation = dilation\n\n self.get_edge(layout)\n self.hop_dis = get_hop_distance(\n self.num_node, self.edge, max_hop=max_hop)\n self.get_adjacency(strategy)\n\n def __str__(self):\n return self.A\n\n def get_edge(self, layout):\n if layout == 'openpose':\n self.num_node = 18\n self_link = [(i, i) for i in range(self.num_node)]\n neighbor_link = [(4, 3), (3, 2), (7, 6), (6, 5), (13, 12), (12,\n 11),\n (10, 9), (9, 8), (11, 5), (8, 2), (5, 1), (2, 1),\n (0, 1), (15, 0), (14, 0), (17, 15), (16, 14)]\n self.edge = self_link + neighbor_link\n self.center = 1\n elif layout == 'ntu-rgb+d':\n self.num_node = 25\n self_link = [(i, i) for i in range(self.num_node)]\n neighbor_1base = [(1, 2), (2, 21), (3, 21), (4, 3), (5, 21),\n (6, 5), (7, 6), (8, 7), (9, 21), (10, 9),\n (11, 10), (12, 11), (13, 1), (14, 13), (15, 14),\n (16, 15), (17, 1), (18, 17), (19, 18), (20, 19),\n (22, 23), (23, 8), (24, 25), (25, 12)]\n neighbor_link = [(i - 1, j - 1) for (i, j) in neighbor_1base]\n self.edge = self_link + neighbor_link\n self.center = 21 - 1\n elif layout == 'ntu_edge':\n self.num_node = 24\n self_link = [(i, i) for i in range(self.num_node)]\n neighbor_1base = [(1, 2), (3, 2), (4, 3), (5, 2), (6, 5), (7, 6),\n (8, 7), (9, 2), (10, 9), (11, 10), (12, 11),\n (13, 1), (14, 13), (15, 14), (16, 15), (17, 1),\n (18, 17), (19, 18), (20, 19), (21, 22), (22, 8),\n (23, 24), (24, 12)]\n neighbor_link = [(i - 1, j - 1) for (i, j) in neighbor_1base]\n self.edge = self_link + neighbor_link\n self.center = 2\n # elif layout=='customer settings':\n # pass\n else:\n raise ValueError(\"Do Not Exist This Layout.\")\n\n #计算邻接矩阵A\n def get_adjacency(self, strategy):\n valid_hop = range(0, self.max_hop + 1, self.dilation) #range(start,stop,step)\n adjacency = np.zeros((self.num_node, self.num_node))\n for hop in valid_hop:\n adjacency[self.hop_dis == hop] = 1\n normalize_adjacency = normalize_digraph(adjacency)\n\n if strategy == 'uniform':\n A = np.zeros((1, self.num_node, self.num_node))\n A[0] = normalize_adjacency\n self.A = A\n elif strategy == 'distance':\n A = np.zeros((len(valid_hop), self.num_node, self.num_node))\n for i, hop in enumerate(valid_hop):\n A[i][self.hop_dis == hop] = normalize_adjacency[self.hop_dis ==\n hop]\n self.A = A\n elif strategy == 'spatial':\n A = []\n for hop in valid_hop:\n a_root = np.zeros((self.num_node, self.num_node))\n a_close = np.zeros((self.num_node, self.num_node))\n a_further = np.zeros((self.num_node, self.num_node))\n for i in range(self.num_node):\n for j in range(self.num_node):\n if self.hop_dis[j, i] == hop:\n if self.hop_dis[j, self.center] == self.hop_dis[\n i, self.center]:\n a_root[j, i] = normalize_adjacency[j, i]\n elif self.hop_dis[j, self.\n center] > self.hop_dis[i, self.\n center]:\n a_close[j, i] = normalize_adjacency[j, i]\n else:\n a_further[j, i] = normalize_adjacency[j, i]\n if hop == 0:\n A.append(a_root)\n else:\n A.append(a_root + a_close)\n A.append(a_further)\n A = np.stack(A)\n self.A = A\n else:\n raise ValueError(\"Do Not Exist This Strategy\")\n\n# 此函数的返回值hop_dis就是图的邻接矩阵\ndef get_hop_distance(num_node, edge, max_hop=1):\n A = np.zeros((num_node, num_node))\n for i, j in edge:\n A[j, i] = 1\n A[i, j] = 1\n\n # compute hop steps\n hop_dis = np.zeros((num_node, num_node)) + np.inf # np.inf 表示一个无穷大的正数\n # np.linalg.matrix_power(A, d)求矩阵A的d幂次方,transfer_mat矩阵(I,A)是一个将A矩阵拼接max_hop+1次的矩阵\n transfer_mat = [np.linalg.matrix_power(A, d) for d in range(max_hop + 1)]\n # (np.stack(transfer_mat) > 0)矩阵中大于0的返回Ture,小于0的返回False,最终arrive_mat是一个布尔矩阵,大小与transfer_mat一样\n arrive_mat = (np.stack(transfer_mat) > 0)\n # range(start,stop,step) step=-1表示倒着取\n for d in range(max_hop, -1, -1):\n # 将arrive_mat[d]矩阵中为True的对应于hop_dis[]位置的数设置为d\n hop_dis[arrive_mat[d]] = d\n return hop_dis\n\n# 将矩阵A中的每一列的各个元素分别除以此列元素的形成新的矩阵\ndef normalize_digraph(A):\n Dl = np.sum(A, 0) #将矩阵A压缩成一行\n num_node = A.shape[0]\n Dn = np.zeros((num_node, num_node))\n for i in range(num_node):\n if Dl[i] > 0:\n Dn[i, i] = Dl[i]**(-1)\n AD = np.dot(A, Dn)\n return AD\n\n\ndef normalize_undigraph(A):\n Dl = np.sum(A, 0)\n num_node = A.shape[0]\n Dn = np.zeros((num_node, num_node))\n for i in range(num_node):\n if Dl[i] > 0:\n Dn[i, i] = Dl[i]**(-0.5)\n DAD = np.dot(np.dot(Dn, A), Dn)\n return DAD" ]
[ [ "numpy.dot", "numpy.zeros", "numpy.sum", "numpy.stack", "numpy.linalg.matrix_power" ] ]
ZhengDeQuan/AAA
[ "7755c6aa1cfa484a2836ae6059bca721de2a90e8", "7755c6aa1cfa484a2836ae6059bca721de2a90e8", "7755c6aa1cfa484a2836ae6059bca721de2a90e8" ]
[ "zqtflearn2/tests/test_inputs.py", "zqtflearn2/examples/nlp/cnn_sentence_classification.py", "tflearn_wide_and_deep.py" ]
[ "'''\n This file contains test cases for tflearn\n'''\n\nimport tensorflow as tf\nimport zqtflearn\nimport unittest\n\nclass TestInputs(unittest.TestCase):\n '''\n This class contains test cases for serval input types\n '''\n INPUT_DATA_1 = [ [ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ] ]\n INPUT_DATA_2 = [ [ 6 ], [ 7 ], [ 8 ], [ 9 ], [ 10 ] ]\n TARGET = [ [ 14 ], [ 18 ], [ 22 ], [ 26 ], [ 30 ] ] # (input1 + input2) * 2\n\n def test_list_inputs(self):\n \"\"\"Test input a list\n \"\"\"\n with tf.Graph().as_default():\n model, inputs, target = self.build_simple_model()\n model.fit([ inpData for _, _, inpData in inputs ], target, batch_size = 1)\n\n def test_dict_inputs(self):\n \"\"\"Test input a dict with layer name\n \"\"\"\n with tf.Graph().as_default():\n model, inputs, target = self.build_simple_model()\n model.fit({ name: inpData for name, _, inpData in inputs }, target, batch_size = 1)\n\n def test_dict_withtensor_inputs(self):\n \"\"\"Test input a dict with placeholder\n \"\"\"\n with tf.Graph().as_default():\n model, inputs, target = self.build_simple_model()\n model.fit({ placeholder: inpData for _, placeholder, inpData in inputs }, target, batch_size = 1)\n\n def build_simple_model(self):\n \"\"\"Build a simple model for test\n Returns:\n DNN, [ (input layer name, input placeholder, input data) ], Target data\n \"\"\"\n inputPlaceholder1, inputPlaceholder2 = \\\n tf.placeholder(tf.float32, (1, 1), name = \"input1\"), tf.placeholder(tf.float32, (1, 1), name = \"input2\")\n input1 = zqtflearn.input_data(placeholder = inputPlaceholder1)\n input2 = zqtflearn.input_data(placeholder = inputPlaceholder2)\n network = zqtflearn.merge([input1, input2], \"sum\")\n network = zqtflearn.reshape(network, (1, 1))\n network = zqtflearn.fully_connected(network, 1)\n network = zqtflearn.regression(network)\n return (\n zqtflearn.DNN(network),\n [ (\"input1:0\", inputPlaceholder1, self.INPUT_DATA_1), (\"input2:0\", inputPlaceholder2, self.INPUT_DATA_2) ],\n self.TARGET,\n )\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# -*- coding: utf-8 -*-\n\"\"\"\nSimple example using convolutional neural network to classify IMDB\nsentiment dataset.\n\nReferences:\n - Andrew L. Maas, Raymond E. Daly, Peter T. Pham, Dan Huang, Andrew Y. Ng,\n and Christopher Potts. (2011). Learning Word Vectors for Sentiment\n Analysis. The 49th Annual Meeting of the Association for Computational\n Linguistics (ACL 2011).\n - Kim Y. Convolutional Neural Networks for Sentence Classification[C]. \n Empirical Methods in Natural Language Processing, 2014.\n\nLinks:\n - http://ai.stanford.edu/~amaas/data/sentiment/\n - http://emnlp2014.org/papers/pdf/EMNLP2014181.pdf\n\n\"\"\"\nfrom __future__ import division, print_function, absolute_import\n\nimport tensorflow as tf\nimport zqtflearn\nfrom zqtflearn.layers.core import input_data, dropout, fully_connected\nfrom zqtflearn.layers.conv import conv_1d, global_max_pool\nfrom zqtflearn.layers.merge_ops import merge\nfrom zqtflearn.layers.estimator import regression\nfrom zqtflearn.data_utils import to_categorical, pad_sequences\nfrom zqtflearn.datasets import imdb\n\n# IMDB Dataset loading\ntrain, test, _ = imdb.load_data(path='imdb.pkl', n_words=10000,\n valid_portion=0.1)\ntrainX, trainY = train\ntestX, testY = test\n\n# Data preprocessing\n# Sequence padding\ntrainX = pad_sequences(trainX, maxlen=100, value=0.)\ntestX = pad_sequences(testX, maxlen=100, value=0.)\n# Converting labels to binary vectors\ntrainY = to_categorical(trainY)\ntestY = to_categorical(testY)\n\n# Building convolutional network\nnetwork = input_data(shape=[None, 100], name='input')\nnetwork = zqtflearn.embedding(network, input_dim=10000, output_dim=128)\nbranch1 = conv_1d(network, 128, 3, padding='valid', activation='relu', regularizer=\"L2\")\nbranch2 = conv_1d(network, 128, 4, padding='valid', activation='relu', regularizer=\"L2\")\nbranch3 = conv_1d(network, 128, 5, padding='valid', activation='relu', regularizer=\"L2\")\nnetwork = merge([branch1, branch2, branch3], mode='concat', axis=1)\nnetwork = tf.expand_dims(network, 2)\nnetwork = global_max_pool(network)\nnetwork = dropout(network, 0.5)\nnetwork = fully_connected(network, 2, activation='softmax')\nnetwork = regression(network, optimizer='adam', learning_rate=0.001,\n loss='categorical_crossentropy', name='target')\n# Training\nmodel = zqtflearn.DNN(network, tensorboard_verbose=0)\nmodel.fit(trainX, trainY, n_epoch = 5, shuffle=True, validation_set=(testX, testY), show_metric=True, batch_size=32)\n", "'''\nPedagogical example realization of wide & deep networks, using TensorFlow and TFLearn.\n\nThis is a re-implementation of http://arxiv.org/abs/1606.07792, using the combination\nof a wide linear model, and a deep feed-forward neural network, for binary classification \nThis example realization is based on Tensorflow's TF.Learn tutorial \n(https://www.tensorflow.org/versions/r0.10/tutorials/wide_and_deep/index.html),\nbut implemented in TFLearn. Note that despite the closeness of names, TFLearn is distinct\nfrom TF.Learn (previously known as scikit flow).\n\nThis implementation explicitly presents the construction of layers in the deep part of the\nnetwork, and allows direct access to changing the layer architecture, and customization\nof methods used for regression and optimization.\n\nIn contrast, the TF.Learn tutorial offers more sophistication, but hides the layer\narchitecture behind a black box function, tf.contrib.learn.DNNLinearCombinedClassifier.\n\nSee https://github.com/ichuang/tflearn_wide_and_deep for more about this example.\n'''\n\nfrom __future__ import division, print_function\n\nimport os\nimport sys\nimport argparse\nimport zqtflearn\nimport tempfile\nimport urllib\n\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\n\n#-----------------------------------------------------------------------------\n\nCOLUMNS = [\"age\", \"workclass\", \"fnlwgt\", \"education\", \"education_num\",\n \"marital_status\", \"occupation\", \"relationship\", \"race\", \"gender\",\n \"capital_gain\", \"capital_loss\", \"hours_per_week\", \"native_country\",\n \"income_bracket\"]\nLABEL_COLUMN = \"label\"\n\n#deep侧的特征\nCATEGORICAL_COLUMNS = {\"workclass\": 10, \"education\": 17, \"marital_status\":8, \n \"occupation\": 16, \"relationship\": 7, \"race\": 6, \n \"gender\": 3, \"native_country\": 43, \"age_binned\": 14}\n\n#wide侧的特征\nCONTINUOUS_COLUMNS = [\"age\", \"education_num\", \"capital_gain\", \"capital_loss\",\n \"hours_per_week\"]\n\n#-----------------------------------------------------------------------------\n\nclass TFLearnWideAndDeep(object):\n '''\n Wide and deep model, implemented using TFLearn\n '''\n AVAILABLE_MODELS = [\"wide\", \"deep\", \"wide+deep\"]\n def __init__(self, model_type=\"wide+deep\", verbose=None, name=None, tensorboard_verbose=3, \n wide_learning_rate=0.001, deep_learning_rate=0.001, checkpoints_dir=None):\n '''\n model_type = `str`: wide or deep or wide+deep\n verbose = `bool`\n name = `str` used for run_id (defaults to model_type)\n tensorboard_verbose = `int`: logging level for tensorboard (0, 1, 2, or 3)\n wide_learning_rate = `float`: defaults to 0.001\n deep_learning_rate = `float`: defaults to 0.001\n checkpoints_dir = `str`: where checkpoint files will be stored (defaults to \"CHECKPOINTS\")\n '''\n self.model_type = model_type or \"wide+deep\"\n assert self.model_type in self.AVAILABLE_MODELS\n self.verbose = verbose or 0\n self.tensorboard_verbose = tensorboard_verbose\n self.name = name or self.model_type\t# name is used for the run_id\n self.data_columns = COLUMNS\n self.continuous_columns = CONTINUOUS_COLUMNS\n self.categorical_columns = CATEGORICAL_COLUMNS\t# dict with category_name: category_size\n self.label_column = LABEL_COLUMN\n self.checkpoints_dir = checkpoints_dir or \"CHECKPOINTS\"\n if not os.path.exists(self.checkpoints_dir):\n os.mkdir(self.checkpoints_dir)\n print(\"Created checkpoints directory %s\" % self.checkpoints_dir)\n self.build_model([wide_learning_rate, deep_learning_rate])\n\n def load_data(self, train_dfn=\"adult.data\", test_dfn=\"adult.test\"):\n '''\n Load data (use files offered in the Tensorflow wide_n_deep_tutorial)\n '''\n if not os.path.exists(train_dfn):\n urllib.urlretrieve(\"https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data\", train_dfn)\n print(\"Training data is downloaded to %s\" % train_dfn)\n\n if not os.path.exists(test_dfn):\n urllib.urlretrieve(\"https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.test\", test_dfn)\n print(\"Test data is downloaded to %s\" % test_dfn)\n\n self.train_data = pd.read_csv(train_dfn, names=COLUMNS, skipinitialspace=True)\n self.test_data = pd.read_csv(test_dfn, names=COLUMNS, skipinitialspace=True, skiprows=1)\n\n self.train_data[self.label_column] = (self.train_data[\"income_bracket\"].apply(lambda x: \">50K\" in x)).astype(int)\n self.test_data[self.label_column] = (self.test_data[\"income_bracket\"].apply(lambda x: \">50K\" in x)).astype(int)\n\n def build_model(self, learning_rate=[0.001, 0.01]):\n '''\n Model - wide and deep - built using zqtflearn\n '''\n n_cc = len(self.continuous_columns)\n n_categories = 1\t\t\t# two categories: is_idv and is_not_idv\n #为什么不是len(self.CATEGORICAL_COLUMNS)\n input_shape = [None, n_cc]\n if self.verbose:\n print (\"=\"*77 + \" Model %s (type=%s)\" % (self.name, self.model_type))\n print (\" Input placeholder shape=%s\" % str(input_shape))\n wide_inputs = zqtflearn.input_data(shape=input_shape, name=\"wide_X\")\n\n if not isinstance(learning_rate, list):\n learning_rate = [learning_rate, learning_rate]\t# wide, deep\n if self.verbose:\n print (\" Learning rates (wide, deep)=%s\" % learning_rate)\n\n with tf.name_scope(\"Y\"):\t\t\t# placeholder for target variable (i.e. trainY input)\n Y_in = tf.placeholder(shape=[None, 1], dtype=tf.float32, name=\"Y\")\n\n with tf.variable_op_scope([wide_inputs], None, \"cb_unit\", reuse=False) as scope:\n central_bias = zqtflearn.variables.variable('central_bias', shape=[1],\n initializer=tf.constant_initializer(np.random.randn()),\n trainable=True, restore=True)\n tf.add_to_collection(tf.GraphKeys.LAYER_VARIABLES + '/cb_unit', central_bias)\n\n if 'wide' in self.model_type:\n wide_network = self.wide_model(wide_inputs, n_cc)\n network = wide_network\n wide_network_with_bias = tf.add(wide_network, central_bias, name=\"wide_with_bias\")\n\n if 'deep' in self.model_type:\n deep_network = self.deep_model(wide_inputs, n_cc) #这里面应该是deep inputs\n deep_network_with_bias = tf.add(deep_network, central_bias, name=\"deep_with_bias\")\n if 'wide' in self.model_type:\n network = tf.add(wide_network, deep_network)\n if self.verbose:\n print (\"Wide + deep model network %s\" % network)\n else:\n network = deep_network\n\n network = tf.add(network, central_bias, name=\"add_central_bias\")\n\n # add validation monitor summaries giving confusion matrix entries\n with tf.name_scope('Monitors'):\n predictions = tf.cast(tf.greater(network, 0), tf.int64)\n print (\"predictions=%s\" % predictions)\n Ybool = tf.cast(Y_in, tf.bool)\n print (\"Ybool=%s\" % Ybool)\n pos = tf.boolean_mask(predictions, Ybool)\n neg = tf.boolean_mask(predictions, ~Ybool)\n psize = tf.cast(tf.shape(pos)[0], tf.int64)\n nsize = tf.cast(tf.shape(neg)[0], tf.int64)\n true_positive = tf.reduce_sum(pos, name=\"true_positive\")\n false_negative = tf.subtract(psize, true_positive, name=\"false_negative\")\n false_positive = tf.reduce_sum(neg, name=\"false_positive\")\n true_negative = tf.subtract(nsize, false_positive, name=\"true_negative\")\n overall_accuracy = tf.truediv(tf.add(true_positive, true_negative), tf.add(nsize, psize), name=\"overall_accuracy\")\n vmset = [true_positive, true_negative, false_positive, false_negative, overall_accuracy]\n\n trainable_vars = tf.trainable_variables()\n tv_deep = [v for v in trainable_vars if v.name.startswith('deep_')]\n tv_wide = [v for v in trainable_vars if v.name.startswith('wide_')]\n\n if self.verbose:\n print (\"DEEP trainable_vars\")\n for v in tv_deep:\n print (\" Variable %s: %s\" % (v.name, v))\n print (\"WIDE trainable_vars\")\n for v in tv_wide:\n print (\" Variable %s: %s\" % (v.name, v))\n\n if 'wide' in self.model_type:\n if not 'deep' in self.model_type:\n tv_wide.append(central_bias)\n zqtflearn.regression(wide_network_with_bias,\n placeholder=Y_in,\n optimizer='sgd',\n #loss='roc_auc_score',\n loss='binary_crossentropy',\n metric=\"accuracy\",\n learning_rate=learning_rate[0],\n validation_monitors=vmset,\n trainable_vars=tv_wide,\n op_name=\"wide_regression\",\n name=\"Y\")\n\n if 'deep' in self.model_type:\n if not 'wide' in self.model_type:\n tv_wide.append(central_bias)\n zqtflearn.regression(deep_network_with_bias,\n placeholder=Y_in,\n optimizer='adam',\n #loss='roc_auc_score',\n loss='binary_crossentropy',\n metric=\"accuracy\",\n learning_rate=learning_rate[1],\n validation_monitors=vmset if not 'wide' in self.model_type else None,\n trainable_vars=tv_deep,\n op_name=\"deep_regression\",\n name=\"Y\")\n\n if self.model_type=='wide+deep':\t# learn central bias separately for wide+deep\n zqtflearn.regression(network,\n placeholder=Y_in,\n optimizer='adam',\n loss='binary_crossentropy',\n metric=\"accuracy\",\n learning_rate=learning_rate[0], # use wide learning rate\n trainable_vars=[central_bias],\n op_name=\"central_bias_regression\",\n name=\"Y\")\n\n self.model = zqtflearn.DNN(network,\n tensorboard_verbose=self.tensorboard_verbose,\n max_checkpoints=5,\n checkpoint_path=\"%s/%s.tfl\" % (self.checkpoints_dir, self.name),\n )\n\n if self.verbose:\n print (\"Target variables:\")\n for v in tf.get_collection(tf.GraphKeys.TARGETS):\n print (\" variable %s: %s\" % (v.name, v))\n\n print (\"=\"*77)\n\n def deep_model(self, wide_inputs, n_inputs, n_nodes=[100, 50], use_dropout=False):\n '''\n Model - deep, i.e. two-layer fully connected network model\n '''\n\n\n cc_input_var = {}\n cc_embed_var = {}\n flat_vars = []\n if self.verbose:\n print (\"--> deep model: %s categories, %d continuous\" % (len(self.categorical_columns), n_inputs))\n for cc, cc_size in self.categorical_columns.items():\n cc_input_var[cc] = zqtflearn.input_data(shape=[None, 1], name=\"%s_in\" % cc, dtype=tf.int32)\n # embedding layers only work on CPU! No GPU implementation in tensorflow, yet!\n cc_embed_var[cc] = zqtflearn.layers.embedding_ops.embedding(cc_input_var[cc], cc_size, 8, name=\"deep_%s_embed\" % cc)\n if self.verbose:\n print (\" %s_embed = %s\" % (cc, cc_embed_var[cc]))\n flat_vars.append(tf.squeeze(cc_embed_var[cc], squeeze_dims=[1], name=\"%s_squeeze\" % cc))\n\n\n network = tf.concat([wide_inputs] + flat_vars,axis = 1, name=\"deep_concat\")\n\n for k in range(len(n_nodes)):\n network = zqtflearn.fully_connected(network, n_nodes[k], activation=\"relu\", name=\"deep_fc%d\" % (k + 1))\n if use_dropout:\n network = zqtflearn.dropout(network, 0.5, name=\"deep_dropout%d\" % (k + 1))\n if self.verbose:\n print (\"Deep model network before output %s\" % network)\n network = zqtflearn.fully_connected(network, 1, activation=\"linear\", name=\"deep_fc_output\", bias=False)\n network = tf.reshape(network, [-1, 1])\t# so that accuracy is binary_accuracy\n if self.verbose:\n print (\"Deep model network %s\" % network)\n return network\n\n def wide_model(self, inputs, n_inputs):\n '''\n Model - wide, i.e. normal linear model (for logistic regression)\n '''\n network = inputs\n # use fully_connected (instad of single_unit) because fc works properly with batches, whereas single_unit is 1D only\n network = zqtflearn.fully_connected(network, n_inputs, activation=\"linear\", name=\"wide_linear\", bias=False)\t# x*W (no bias)\n network = tf.reduce_sum(network, 1, name=\"reduce_sum\")\t# batched sum, to produce logits\n network = tf.reshape(network, [-1, 1])\t# so that accuracy is binary_accuracy\n if self.verbose:\n print (\"Wide model network %s\" % network)\n return network\n\n def prepare_input_data(self, input_data, name=\"\", category_map=None):\n '''\n Prepare input data dicts\n '''\n print (\"-\"*40 + \" Preparing %s\" % name)\n X = input_data[self.continuous_columns].values.astype(np.float32)\n Y = input_data[self.label_column].values.astype(np.float32)\n Y = Y.reshape([-1, 1])\n if self.verbose:\n print (\" Y shape=%s, X shape=%s\" % (Y.shape, X.shape))\n\n X_dict = {\"wide_X\": X}\n\n if 'deep' in self.model_type:\n # map categorical value strings to integers\n td = input_data\n if category_map is None:\n category_map = {}\n for cc in self.categorical_columns:\n if not cc in td.columns:\n continue\n cc_values = sorted(td[cc].unique())\n cc_max = 1+len(cc_values)\n cc_map = dict(zip(cc_values, range(1, cc_max)))\t# start from 1 to avoid 0:0 mapping (save 0 for missing)\n if self.verbose:\n print (\" category %s max=%s, map=%s\" % (cc, cc_max, cc_map))\n category_map[cc] = cc_map\n \n td = td.replace(category_map)\n \n # bin ages (cuts off extreme values)\n age_bins = [ 0, 12, 18, 25, 30, 35, 40, 45, 50, 55, 60, 65, 80, 65535 ]\n td['age_binned'] = pd.cut(td['age'], age_bins, labels=False)\n td = td.replace({'age_binned': {np.nan: 0}})\n print (\" %d age bins: age bins = %s\" % (len(age_bins), age_bins))\n\n X_dict.update({ (\"%s_in\" % cc): td[cc].values.astype(np.int32).reshape([-1, 1]) for cc in self.categorical_columns})\n\n Y_dict = {\"Y\": Y}\n if self.verbose:\n print (\"-\"*40)\n return X_dict, Y_dict, category_map\n\n\n def train(self, n_epoch=1000, snapshot_step=10, batch_size=None):\n\n self.X_dict, self.Y_dict, category_map = self.prepare_input_data(self.train_data, \"train data\")\n self.testX_dict, self.testY_dict, _ = self.prepare_input_data(self.test_data, \"test data\", category_map)\n validation_batch_size = batch_size or self.testY_dict['Y'].shape[0]\n batch_size = batch_size or self.Y_dict['Y'].shape[0]\n\n print (\"Input data shape = %s; output data shape=%s, batch_size=%s\" % (str(self.X_dict['wide_X'].shape), \n str(self.Y_dict['Y'].shape), \n batch_size))\n print (\"Test data shape = %s; output data shape=%s, validation_batch_size=%s\" % (str(self.testX_dict['wide_X'].shape), \n str(self.testY_dict['Y'].shape), \n validation_batch_size))\n print (\"=\"*60 + \" Training\")\n self.model.fit(self.X_dict, \n self.Y_dict,\n n_epoch=n_epoch,\n validation_set=(self.testX_dict, self.testY_dict),\n snapshot_step=snapshot_step,\n batch_size=batch_size,\n validation_batch_size=validation_batch_size,\n show_metric=True, \n snapshot_epoch=False,\n shuffle=True,\n run_id=self.name,\n )\n \n def evaluate(self):\n logits = np.array(self.model.predict(self.testX_dict)).reshape([-1])\n print (\"=\"*60 + \" Evaluation\")\n print (\" logits: %s, min=%s, max=%s\" % (logits.shape, logits.min(), logits.max()))\n probs = 1.0 / (1.0 + np.exp(-logits))\n y_pred = pd.Series((probs > 0.5).astype(np.int32))\n Y = pd.Series(self.testY_dict['Y'].astype(np.int32).reshape([-1]))\n self.confusion_matrix = self.output_confusion_matrix(Y, y_pred)\n print (\"=\"*60)\n\n def output_confusion_matrix(self, y, y_pred):\n assert y.size == y_pred.size\n print(\"Actual IDV\")\n print(y.value_counts())\n print(\"Predicted IDV\")\n print(y_pred.value_counts())\n print()\n print(\"Confusion matrix:\")\n cmat = pd.crosstab(y_pred, y, rownames=['predictions'], colnames=['actual'])\n print(cmat)\n sys.stdout.flush()\n return cmat\n \n#-----------------------------------------------------------------------------\n\ndef CommandLine(args=None):\n '''\n Main command line. Accepts args, to allow for simple unit testing.\n '''\n flags = tf.app.flags\n FLAGS = flags.FLAGS\n if args:\n print(\"added by zhengquan. I think it didn't get here, test it tomorrow\")\n FLAGS.__init__()\n FLAGS.__dict__.update(args)\n\n try:\n flags.DEFINE_string(\"model_type\", \"wide+deep\",\"Valid model types: {'wide', 'deep', 'wide+deep'}.\")\n flags.DEFINE_string(\"run_name\", None, \"name for this run (defaults to model type)\")\n flags.DEFINE_string(\"load_weights\", None, \"filename with initial weights to load\")\n flags.DEFINE_string(\"checkpoints_dir\", None, \"name of directory where checkpoints should be saved\")\n flags.DEFINE_integer(\"n_epoch\", 200, \"Number of training epoch steps\")\n flags.DEFINE_integer(\"snapshot_step\", 100, \"Step number when snapshot (and validation testing) is done\")\n flags.DEFINE_float(\"wide_learning_rate\", 0.001, \"learning rate for the wide part of the model\")\n flags.DEFINE_float(\"deep_learning_rate\", 0.001, \"learning rate for the deep part of the model\")\n flags.DEFINE_boolean(\"verbose\", False, \"Verbose output\")\n except argparse.ArgumentError:\n pass\t# so that CommandLine can be run more than once, for testing\n\n twad = TFLearnWideAndDeep(model_type=FLAGS.model_type, verbose=FLAGS.verbose, \n name=FLAGS.run_name, wide_learning_rate=FLAGS.wide_learning_rate,\n deep_learning_rate=FLAGS.deep_learning_rate,\n checkpoints_dir=FLAGS.checkpoints_dir)\n twad.load_data()\n if FLAGS.load_weights:\n print (\"Loading initial weights from %s\" % FLAGS.load_weights)\n twad.model.load(FLAGS.load_weights)\n twad.train(n_epoch=FLAGS.n_epoch, snapshot_step=FLAGS.snapshot_step)\n twad.evaluate()\n return twad\n\n#-----------------------------------------------------------------------------\n# unit tests\n\ndef test_wide_and_deep():\n import glob\n tf.reset_default_graph()\n cdir = \"test_checkpoints\"\n if os.path.exists(cdir):\n os.system(\"rm -rf %s\" % cdir)\n twad = CommandLine(args=dict(verbose=True, n_epoch=5, model_type=\"wide+deep\", snapshot_step=5, \n wide_learning_rate=0.0001, checkpoints_dir=cdir))\n cfiles = glob.glob(\"%s/*.tfl-*\" % cdir)\n print (\"cfiles=%s\" % cfiles)\n assert(len(cfiles))\n cm = twad.confusion_matrix.values.astype(np.float32)\n assert(cm[1][1])\n\ndef test_deep():\n import glob\n tf.reset_default_graph()\n cdir = \"test_checkpoints\"\n if os.path.exists(cdir):\n os.system(\"rm -rf %s\" % cdir)\n twad = CommandLine(args=dict(verbose=True, n_epoch=5, model_type=\"deep\", snapshot_step=5, \n wide_learning_rate=0.0001, checkpoints_dir=cdir))\n cfiles = glob.glob(\"%s/*.tfl-*\" % cdir)\n print (\"cfiles=%s\" % cfiles)\n assert(len(cfiles))\n cm = twad.confusion_matrix.values.astype(np.float32)\n assert(cm[1][1])\n\ndef test_wide():\n import glob\n tf.reset_default_graph()\n cdir = \"test_checkpoints\"\n if os.path.exists(cdir):\n os.system(\"rm -rf %s\" % cdir)\n twad = CommandLine(args=dict(verbose=True, n_epoch=5, model_type=\"wide\", snapshot_step=5, \n wide_learning_rate=0.0001, checkpoints_dir=cdir))\n cfiles = glob.glob(\"%s/*.tfl-*\" % cdir)\n print (\"cfiles=%s\" % cfiles)\n assert(len(cfiles))\n cm = twad.confusion_matrix.values.astype(np.float32)\n assert(cm[1][1])\n\n#-----------------------------------------------------------------------------\n\nif __name__==\"__main__\":\n CommandLine()\n None\n" ]
[ [ "tensorflow.Graph", "tensorflow.placeholder" ], [ "tensorflow.expand_dims" ], [ "tensorflow.variable_op_scope", "pandas.crosstab", "numpy.exp", "tensorflow.reshape", "tensorflow.greater", "pandas.read_csv", "tensorflow.add_to_collection", "tensorflow.cast", "tensorflow.trainable_variables", "tensorflow.shape", "tensorflow.concat", "tensorflow.subtract", "tensorflow.squeeze", "tensorflow.add", "tensorflow.get_collection", "numpy.random.randn", "tensorflow.placeholder", "tensorflow.reduce_sum", "tensorflow.name_scope", "tensorflow.boolean_mask", "pandas.cut", "tensorflow.reset_default_graph" ] ]
EvanBagis/gb_rf_evolution
[ "82e9c904eaa2f1ea05a330dea5087bf07caebf48" ]
[ "gb_rf_evolution/gb_train.py" ]
[ "import lightgbm as lgb\nimport xgboost as xgb\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, explained_variance_score, r2_score\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\n\ndef compile_model(network):\n \"\"\"\n :param network dict: dictionary with network parameters\n :return: compiled model\n \"\"\"\n\n \n model = lgb.LGBMRegressor(num_leaves=network.get('num_leaves', 31),\n learning_rate=network.get('learning_rate', 0.1),\n n_estimators=network.get('n_estimators', 20),\n max_bin=network.get('max_bin', 1000),\n colsample_bytree=network.get('colsample_bytree', 0.5),\n subsample_for_bin=network.get('subsample_for_bin', 200000),\n boosting_type=network.get('boosting_type', 'gbdt'),\n num_iterations=network.get('num_iterations', 100),\n extra_trees=network.get('extra_trees', False),\n reg_sqrt= network.get('reg_sqrt', False),\n bagging_freq = network.get('bagging_freq', 1),\n bagging_fraction = network.get('bagging_fraction', 0.1))\n \n return model\n\n\ndef train_and_score(network, x_train, y_train, x_test, y_test):\n \"\"\"\n\n :param network dict: dictionary with network parameters\n :param x_train array: numpy array with features for traning\n :param y_train array: numpy array with labels for traning\n :param x_test array: numpy array with labels for test\n :param y_test array: numpy array with labels for test\n :return float: score\n \"\"\"\n\n model = compile_model(network)\n\n model.fit(x_train, y_train)\n\n y_pred = model.predict(np.array(x_test))\n \n\n true = y_test\n pred = y_pred\n\n print(' R2 = ', r2_score(true, pred))\n \n return r2_score(true, pred), model\n" ]
[ [ "sklearn.metrics.r2_score", "numpy.array" ] ]
AMReX-Astro/MAESTRO-
[ "53b99e9451c1d4f8f113b19d7de5ba7963531382" ]
[ "Exec/test_problems/reacting_bubble/scaling/sc20/plot.py" ]
[ "import matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport argparse\n\ndef plot():\n\n results_dir = './'\n\n results_files = [result for result in os.listdir(results_dir) if 'MAESTROeX' in result]\n\n n_gpus_per_node = 6\n\n throughput_list = []\n nnodes_list = []\n\n for results_file in results_files:\n\n nsteps = 0\n nzones = 0\n time = 0.0\n\n for line in open(results_dir + results_file):\n\n if len(line.split()) == 0:\n continue\n\n # Determine the number of MPI ranks and thus the number of nodes.\n\n if len(line.split()) == 6 and line.split()[0] == 'MPI' and line.split()[1] == 'initialized':\n n_ranks = int(line.split()[3])\n n_nodes = max(1, n_ranks / n_gpus_per_node)\n\n # For each step, add up the number of zones advanced and the walltime\n # for that step.\n\n if len(line.split()) == 4 and line.split()[0] == 'Level' and line.split()[1] == '0,' and line.split()[3] == 'cells':\n nsteps += 1\n nzones += int(line.split()[2])\n\n if len(line.split()) == 6 and line.split()[0] == 'Time' and line.split()[2] == 'advance':\n time += float(line.split()[5])\n\n nnodes_list.append(n_nodes)\n throughput_list.append(nzones / time / 1.e6)\n\n\n \n\n # Now we have all the results, so plot them.\n\n nnodes_arr = np.array(nnodes_list)\n throughput_arr = np.array(throughput_list)\n\n throughput_arr = np.array([x for _, x in sorted(zip(nnodes_arr, throughput_arr))])\n nnodes_arr = sorted(nnodes_arr)\n\n throughput_arr = throughput_arr / throughput_arr[0] / nnodes_arr\n\n plt.plot(nnodes_arr, throughput_arr, linestyle='-', lw=4, marker='o', markersize=14)\n\n plt.xlim([0.9 * min(nnodes_arr), 1.1 * max(nnodes_arr)])\n plt.ylim([0, 1.25 * max(throughput_arr)])\n\n plt.ylabel('Throughput (normalized)', fontsize=20)\n plt.xlabel('Number of nodes', fontsize=20)\n plt.title('Weak scaling of MAESTROeX reacting bubble', fontsize=20)\n plt.xscale('log', basex=2)\n ax = plt.gca()\n ax.xaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())\n plt.xticks([1, 2, 4, 8, 16, 32, 64, 128])\n plt.tick_params(labelsize=14)\n plt.tight_layout()\n\n plt.savefig('scaling.eps')\n plt.savefig('scaling.png')\n\ndef main():\n\n plot()\n\nif __name__ == \"__main__\":\n\n main()\n" ]
[ [ "matplotlib.use", "numpy.array", "matplotlib.pyplot.xscale", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "matplotlib.pyplot.title", "matplotlib.pyplot.tick_params", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.ylabel", "matplotlib.ticker.ScalarFormatter", "matplotlib.pyplot.gca", "matplotlib.pyplot.xticks" ] ]
dperl-sol/cctbx_project
[ "b9e390221a2bc4fd00b9122e97c3b79c632c6664", "b9e390221a2bc4fd00b9122e97c3b79c632c6664", "b9e390221a2bc4fd00b9122e97c3b79c632c6664" ]
[ "xfel/amo/pnccd_ana/mpi_fxs_mask.py", "mmtbx/regression/tls/tst_tls_utils.py", "xfel/command_line/radial_average.py" ]
[ "from __future__ import absolute_import, division, print_function\nfrom six.moves import range\n\nfrom psana import *\nimport sys\nimport numpy as np\nfrom xfel.amo.pnccd_ana import pnccd_tbx\nfrom xfel.amo.pnccd_ana import pnccd_hit\nfrom xfel.amo.pnccd_ana import fxs\nimport matplotlib.pyplot as plt\nfrom six.moves import zip\n\n\nplt.ion()\n########################################\n# Due to the mask sometimes having zero values\n# we're bound to get divisions with zeros at\n#times. Here ignoring those errors.\nnp.seterr(divide='ignore', invalid='ignore')\n\nfrom mpi4py import MPI\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank()\nsize = comm.Get_size()\n\n\ndef h5gen(run,timestamps = None, first = None, last = None):\n\n # Singel CPU\n if size == 1:\n nom = rank\n denom = size\n # MPI\n else:\n nom = rank - 1\n denom = size - 1\n\n\n times = timestamps\n nevents = len(times)\n mytimes,myevents = zip(*[(times[i],i) for i in range(nevents) if (i+nom)%denom == 0])\n\n for j in range(len(mytimes)):\n yield myevents[j],mytimes[j]\n\n\ndef idxgen(run,timestamps = None, first = None, last = None):\n #print \"idx mode\"\n # Use timestamps from index file\n if timestamps is None:\n timestamps = run.times()\n\n if first is None :\n first = 0\n\n if last is None :\n last = len(timestamps)\n else:\n last = min(last,len(timestamps)) # Check that last time-stamp exists\n\n # Singel CPU\n if size == 1:\n nom = rank\n denom = size\n # MPI\n else:\n nom = rank - 1\n denom = size - 1\n\n\n times = timestamps[first:last]\n nevents = len(times)\n mytimes,myevents = zip(*[(times[i],i) for i in range(nevents) if (i+nom)%denom == 0])\n\n for j in range(len(mytimes)):\n yield myevents[j],run.event(mytimes[j])\n\n\n\ndef smdgen(run,timestamps = None, first = None, last = None):\n #print \"smd mode\"\n if first is None :\n first = 0\n\n if last is None :\n last = 1e20 # We typically don't know what the last events is. So for now use a large number\n\n\n # Singel CPU\n if size == 1:\n nom = rank\n denom = size\n # MPI\n else:\n nom = rank - 1\n denom = size - 1\n\n\n if timestamps is None :\n\n for nevent,evt in enumerate(run.events()):\n if nevent < first : continue\n elif nevent == last : return\n elif nevent%denom == nom:\n yield nevent-first,evt\n\n else : # Only applicable for xtc format\n\n ct = 0\n for nevent,evt in enumerate(run.events()):\n t = pnccd_tbx.get_psana_time(evt)\n # Check if event exists in timestamps\n if np.equal(t, timestamps).all(axis=1).any() :\n if ct < first : continue\n elif ct == last : return\n elif ct%denom == nom:\n yield ct,evt\n ct += 1\n\n\n\ndef compute_mask(argv=None) :\n\n \"\"\"Function to compute a mask of non-resposive pixels from FXS images\n extracted from xtc (smd,idx,xtc format) or h5 files.\n Works for Single CPU, Multi-Processor interactive jobs and MPI batch jobs\n\n For a definition of input arguments argv and batch processing instructions see *** mpi_fxs_launch.py ***\n\n compute_mask produces the following output files:\n\n * Index file : Information about the events processed including time-stamps, beam center, total and peak intensities, streak locations, particle size etc\n * Average : Average image in cartesian coordinates\n * Variance : Variance map of intensities in cartesian coordinates\n * Mask : Mask image in cartesian coordinates\n\n \"\"\"\n\n if argv == None:\n argv = sys.argv[1:]\n\n try:\n from mpi4py import MPI\n except ImportError:\n raise Sorry(\"MPI not found\")\n\n comm = MPI.COMM_WORLD\n rank = comm.Get_rank()\n size = comm.Get_size()\n\n\n if argv.hit is None :\n hit = -1.0e20 # Process everything\n else:\n hit = argv.hit # Process everything > hit\n\n ftype = argv.ftype\n\n if argv.param_path is not None :\n if ftype == 'h5' :\n param_file = np.genfromtxt(argv.param_path,skiprows=1,dtype=None)\n timestamps,filestamps = pnccd_tbx.get_h5_event(param_file)\n elif ftype == 'xtc' :\n param_file = np.genfromtxt(argv.param_path,skiprows=1,dtype=None)\n timestamps = pnccd_tbx.get_time(param_file)\n else :\n param_file = np.genfromtxt(argv.param_path,skiprows=1)\n timestamps = pnccd_tbx.get_psana_event(param_file)\n else:\n timestamps = None\n\n # The first and last events to processed\n first = argv.first\n last = argv.last\n\n\n # Check data format\n\n if ftype == 'h5' :\n import h5py\n run = int(argv.run)\n\n # Get time-stamps from all h5-files\n if argv.param_path is None :\n timestamps = []\n filestamps = []\n # Loop over all h5-files and store the time-stamps\n for i in os.listdir(argv.xtc_dir):\n if i.endswith(\".h5\"):\n f = h5py.File(i,'r')\n filestamps.append(i[-7:-4])\n timestamps.append(list(f.keys()))\n continue\n else:\n continue\n\n dataset_name = \"%s-r%s\"%(argv.experiment, str(argv.run).zfill(4)) # Ascert 4 digit run number\n exprun = os.path.join(argv.xtc_dir,dataset_name)\n\n if argv.first is None :\n first = 0\n\n if argv.last is None :\n last = len(timestamps)\n else:\n last = min(last,len(timestamps)) # Check that last time-stamp exists\n\n timestamps = timestamps[first:last]\n filestamps = filestamps[first:last]\n\n\n evtgen = h5gen\n\n else :\n\n exprun = \"exp=%s:run=%d\"%(argv.experiment, argv.run)\n if (ftype == 'xtc') :\n dataset_name = exprun+':xtc'\n elif (ftype == 'idx') :\n dataset_name = exprun+':idx'\n elif(ftype == 'idx_ffb') :\n dataset_name = exprun+':idx'\n # as ffb is only at SLAC, ok to hardcode /reg/d here\n dataset_name += \":dir=/reg/d/ffb/%s/%s/xtc\"%(argv.experiment[0:3],argv.experiment)\n elif(ftype == 'smd') :\n dataset_name = exprun+':smd'\n elif(ftype == 'smd_ffb') :\n dataset_name = exprun+':smd'\n # as ffb is only at SLAC, ok to hardcode /reg/d here ADD live!\n dataset_name += \":dir=/reg/d/ffb/%s/%s/xtc:live\"%(argv.experiment[0:3],argv.experiment)\n exprun = dataset_name\n\n ds = DataSource(dataset_name)\n run = next(ds.runs())\n\n # Select event generator\n if (ftype=='smd') or (ftype == 'smd_ffb') or (ftype == 'xtc'):\n evtgen = smdgen\n elif (ftype=='idx') or (ftype == 'idx_ffb'):\n evtgen = idxgen\n\n\n if size == 1:\n plot = argv.plot\n else:\n plot = 0\n\n\n FXS = fxs.fluctuation_scattering(dataset_name = exprun,\n detector_address = argv.address,\n data_type = argv.ftype,\n mask_path = argv.mask_path,\n mask_angles = None, #np.array([88, 270]), # static masking at 88 and 270 deg\n mask_widths = None, #np.array([6, 10]), # +/- degree\n backimg_path = argv.bg_img_path,\n backmsk_path = argv.bg_msk_path,\n geom_path = argv.geom_path,\n det_dist = argv.det_distance,\n det_pix = argv.det_pixel,\n beam_l = argv.lambda_b,\n mask_thr = argv.thr,\n nQ = argv.nQ,\n nPhi = argv.nPhi,\n dQ = argv.dQ,\n dPhi = argv.dP,\n cent0 = [argv.x,argv.y],\n r_max = argv.r_max,\n dr = argv.dr,\n dx = argv.dx,\n dy = argv.dy,\n r_0 = argv.r0,\n q_bound = argv.q_bound,\n peak = [0.037, 0.064],\n dpeak = [0.002, 0.002])\n\n\n # Initialize iterator\n FXS.cnt = np.array([0.])\n\n # Initialize Index variables\n if argv.param_path is None :\n maxevents = 400000 # We don't always know the total nr of events. Therefore set to large value\n else:\n maxevents = min(len(timestamps),len(timestamps[first:last]))\n\n\n FXS.get_index(maxevents, flag = 1)\n\n # chop the list into pieces, depending on rank. This assigns each process\n # events such that the get every Nth event where N is the number of processes\n\n if size > 1 :\n if rank > 0 :\n\n hd=pnccd_hit.hit()\n\n # MPI process. Here we set rank 0 to work as a listening server only.\n for j,evt in evtgen(run,timestamps = timestamps, first = first, last = last):\n #print '***',rank,j,evt.get(EventId).fiducials()\n if j%10==0: print('Rank',rank,'processing event',j)\n\n if ftype == 'h5' :\n FXS.get_h5(filestamps[j],evt)\n else :\n FXS.get_image(evt) # Geometry applied image (FXS.img)\n FXS.image = np.copy(FXS.img)\n\n # Process hits\n\n if (FXS.image is not None) and (float(FXS.image.sum()) > hit) :\n\n\n FXS.get_beam(plot = plot) # Beam center refinement\n FXS.get_polar(plot = plot) # Polar transform\n FXS.get_streak_mask(plot = plot) # Get info on streak\n FXS.store_image(j) # Store raw images\n\n if ftype == 'h5' :\n FXS.store_index_h5(evt, j, flag = 0)\n else:\n ######################################\n # Ugly way to get the time-stamps. Fix!!\n time = evt.get(EventId).time()\n fid = evt.get(EventId).fiducials()\n sec = time[0]\n nsec = time[1]\n et = EventTime(int((sec<<32)|nsec),fid)\n #######################################\n FXS.store_index(et, j, flag = 0) # Store index\n\n if int(FXS.cnt)%10==0: print('Rank',rank,'processed events: ', int(FXS.cnt))\n\n\n # Send partial results to master (rank 0)\n if int(FXS.cnt) % 50 == 0: # Send every 50 events\n\n\n # C2 and Saxs data\n tmp_n = int(FXS.cnt)\n\n # Total intensity, Size and Score\n\n tmp_ind = np.column_stack((FXS.tot_int,FXS.tot_size,FXS.tot_score))\n\n hd.send(tmp_n,ind=tmp_ind)\n\n\n hd.endrun()\n\n print('Rank',rank,'total events: ', int(FXS.cnt),' * ')\n\n else:\n\n if ftype == 'h5' :\n FXS.run_nr = run\n else:\n FXS.run_nr = int(run.run())\n\n\n hd = pnccd_hit.hit()\n\n idim = (maxevents,3)\n\n\n hd.total_ind = [np.zeros(idim)]*(size-1)\n hd.total_ev_i = [0.0]*(size-1)\n\n nClients = size - 1\n\n while nClients > 0:\n # Remove client if the run ended\n if hd.recv():\n nClients -= 1\n else:\n ns = sum(hd.total_ev_s)\n ni = sum(hd.total_ev_i)\n\n if (ns % 100 == 0) : # Publish every 100 events\n\n IND = np.zeros(idim)\n\n for i in range(size-1) :\n IND = IND + hd.total_ind[i]\n\n FXS.publish(ind=IND, n_i=ni)\n\n\n else :\n\n\n # Single CPU\n\n\n for j,evt in evtgen(run,timestamps = timestamps, first = first, last = last):\n #print '***',rank,j,evt.get(EventId).fiducials()\n if j%10==0: print('Rank',rank,'processing event',j)\n\n\n if ftype == 'h5' :\n FXS.get_h5(filestamps[j],evt)\n else :\n FXS.get_image(evt) # Geometry applied image (FXS.img)\n FXS.image = np.copy(FXS.img)\n\n\n # Process hits\n if (FXS.image is not None)and (float(FXS.image.sum()) > hit) :\n\n FXS.get_beam(plot=plot) # Beam center refinement\n FXS.get_polar() # Polar transform\n FXS.get_streak_mask(plot=0) # Get info on streak\n FXS.store_image(j) # Store raw images\n\n if ftype == 'h5' :\n FXS.store_index_h5(evt, j, flag = 0)\n else:\n ######################################\n # Ugly way to get the time-stamps. Fix!!\n time = evt.get(EventId).time()\n fid = evt.get(EventId).fiducials()\n sec = time[0]\n nsec = time[1]\n et = EventTime(int((sec<<32)|nsec),fid)\n #######################################\n FXS.store_index(et, j, flag = 0) # Store index\n\n print('Rank',rank,'total events: ', int(FXS.cnt),' * ')\n\n\n #sum the images across mpi cores\n if size > 1:\n print(\"Synchronizing rank\", rank)\n\n Tot = np.zeros(FXS.cnt.shape)\n\n comm.Reduce(FXS.cnt,Tot)\n\n\n if rank == 0 and Tot[0] == 0:\n raise Sorry(\"No events found in the run\")\n\n\n # Collect Variables\n\n Images = np.zeros(FXS.images.shape)\n comm.Reduce(FXS.images,Images)\n\n\n # Collect Indexing variables\n\n Tot_t = np.zeros(FXS.tot_t.shape)\n comm.Reduce(FXS.tot_t,Tot_t)\n\n Tot_s = np.zeros(FXS.tot_s.shape)\n comm.Reduce(FXS.tot_s,Tot_s)\n\n Tot_ns = np.zeros(FXS.tot_ns.shape)\n comm.Reduce(FXS.tot_ns,Tot_ns)\n\n Tot_fd = np.zeros(FXS.tot_fd.shape)\n comm.Reduce(FXS.tot_fd,Tot_fd)\n\n Tot_int = np.zeros(FXS.tot_int.shape)\n comm.Reduce(FXS.tot_int,Tot_int)\n\n Tot_peak1 = np.zeros(FXS.tot_peak1_int.shape)\n comm.Reduce(FXS.tot_peak1_int,Tot_peak1)\n\n Tot_peak2 = np.zeros(FXS.tot_peak2_int.shape)\n comm.Reduce(FXS.tot_peak2_int,Tot_peak2)\n\n Tot_s_m = np.zeros(FXS.tot_streak_m.shape)\n comm.Reduce(FXS.tot_streak_m,Tot_s_m)\n\n Tot_s_s = np.zeros(FXS.tot_streak_s.shape)\n comm.Reduce(FXS.tot_streak_s,Tot_s_s)\n\n Tot_cx = np.zeros(FXS.tot_cx.shape)\n comm.Reduce(FXS.tot_cx,Tot_cx)\n\n Tot_cy = np.zeros(FXS.tot_cy.shape)\n comm.Reduce(FXS.tot_cy,Tot_cy)\n\n Tot_size = np.zeros(FXS.tot_size.shape)\n comm.Reduce(FXS.tot_size,Tot_size)\n\n Tot_score = np.zeros(FXS.tot_score.shape)\n comm.Reduce(FXS.tot_score,Tot_score)\n\n\n # Reduce results\n\n if rank==0:\n\n if size > 1:\n print(\"Synchronized\")\n\n # Identify dead lines and pixels, get binary pixel mask\n\n Ave,Var,Mask = pnccd_tbx.pixel_mask(Images, thr = 0.12)\n\n # Write out data\n\n if argv.outputdir is None:\n opath = os.getcwd()\n else:\n opath = argv.outputdir\n\n f_index = os.path.join(opath,'Index_run' + str(argv.run) + '.dat')\n stamps = ['Time','Seconds','Nanoseconds','Fiducial','Total Intensity','Peak1, q='+str(FXS.peak[0])+'+/-'+str(FXS.dpeak[0]),'Peak2, q='+str(FXS.peak[1])+'+/-'+str(FXS.dpeak[1]),'Mean streak angle','Std streak angle','Beam X','Beam Y','Radius [Ang]','Score']\n head =\" \".join(stamps)\n\n f_ave = os.path.join(opath,'Average_map_' + str(argv.run) + '.dat')\n f_var = os.path.join(opath,'Variance_map_' + str(argv.run) + '.dat')\n f_mask = os.path.join(opath,'Mask_map_' + str(argv.run) + '.dat')\n\n # Get rid of zero lines at the end\n # Last non-zero intensity\n nz = np.nonzero(Tot_t)\n fend = nz[0][-1]+1\n\n f = open(f_index,'w')\n np.savetxt(f,np.c_[Tot_t[:fend],Tot_s[:fend],Tot_ns[:fend],Tot_fd[:fend],Tot_int[:fend],Tot_peak1[:fend],Tot_peak2[:fend],Tot_s_m[:fend],Tot_s_s[:fend],Tot_cx[:fend],Tot_cy[:fend],Tot_size[:fend],Tot_score[:fend]],header = head, comments='' )\n f.close()\n\n\n f = open(f_ave,'w')\n np.savetxt(f,Ave)\n f.close()\n\n f = open(f_var,'w')\n np.savetxt(f,Var)\n f.close()\n\n f = open(f_mask,'w')\n np.savetxt(f,Mask)\n f.close()\n", "from __future__ import absolute_import, division, print_function\n\nimport math\nimport numpy\nfrom mmtbx.tls.utils import *\nfrom scitbx.array_family import flex\nfrom libtbx.test_utils import approx_equal, not_approx_equal\nfrom pytest import raises\nfrom six.moves import zip\nfrom six.moves import range\n\nrran = numpy.random.random\niran = numpy.random.choice\n\nnumpy.random.seed(123232)\n\nTLSMatrices.set_precision(12)\nTLSAmplitudes.set_precision(12)\n\n# Maximum tolerable rounding error\nMAT_RND_TOL = (0.51)*(10**(-TLSMatrices.get_precision()))\nAMP_RND_TOL = (0.51)*(10**(-TLSAmplitudes.get_precision()))\n# For errors in the last decimal place\nLAST_DP_TOL = 10.0 * max(10**(-TLSMatrices.get_precision()),\n 10**(-TLSAmplitudes.get_precision()))\n\nTEST_LENGTHS = [1,2,3]\nTEST_TARGETS = [0.25,1.0,3.3]\n\nTLSMATRICES = [\n [0.88875254,0.266694873,0.493991604,-0.280846445,0.018132653,0.128202717,0.109792777,0.143780355,0.111757325,0.00745827,0.044408043,0.004683883,-0.031880059,0.087486387,-0.035440044,0.053723107,-0.093285664,-0.126741771,0.078707102,0.047063985,0.125165723],\n [0.244377462,0.459148081,0.710013128,-0.008898371,0.07279876,0.036277241,3.755718081,2.739489028,2.134579946,-0.200385262,0.074588032,-0.023382499,0.00048379,0.229469716,-0.187382678,-0.05705213,0.308356068,0.219549925,0.260721724,0.137599684,-0.308839858],\n [0.29790555,0.765985455,0.362144247,0.188051876,-0.07468928,0.176222813,1.157009238,1.603540537,1.146982202,0.076470473,0.076337332,-0.036514342,-0.057413883,-0.4930283,-0.141063091,0.199094828,0.180380061,0.564268854,0.271176005,0.192103145,-0.122966178],\n [0.550613174,0.642391951,0.512539873,0.186990637,-0.018948302,0.182865203,0.696794749,1.168473012,1.459255982,0.122241174,-0.070965716,-0.127405648,-0.126672963,-0.057326201,0.307248593,0.23402513,-0.081293525,-0.457364662,-0.270995819,0.131106455,0.207966488],\n [0.801839264,0.111567149,0.473172234,0.111448705,0.01322435,0.053023611,0.119600352,0.158201942,0.501511288,-0.00097325,0.038852731,-0.020179123,0.094859837,0.027409079,0.027958886,-0.036977684,0.115684103,-0.023249574,-0.167599437,0.028274946,-0.21054394],\n [0.476189761,0.185513316,0.494838237,0.079787304,0.186996542,0.089705044,6.468559896,0.03302114,1.360918838,-0.092774147,-0.470033825,0.142680478,0.007373318,0.322513481,-0.087204939,-0.102689013,0.085596047,-0.037679444,-0.183875771,-0.048267033,-0.092969365],\n [0.271946335,0.353828607,0.011539801,-0.012010653,-0.03669219,-0.006760052,23.89487928,3.564598018,0.086574587,-1.913464478,0.89104049,-0.011635907,0.00083053,-0.00120248,-0.06596398,0.059314995,0.042902408,0.001580523,-0.013344186,0.103940739,-0.043732938],\n [0.436887477,0.558232952,0.172244124,0.292168093,-0.130328728,-0.074615062,3.137593554,0.025205525,0.920908537,-0.108005337,0.00472811,0.015510299,-0.000822308,0.118599046,-0.151446932,0.029991796,0.042430554,-0.009368142,0.000888338,0.153578145,-0.041608246],\n [0.507487457,0.513473662,0.465150239,-0.024656406,0.052695005,0.030032721,9.358808433,1.113449297,12.326819619,-0.988256782,1.235061392,-1.371684512,0.454760772,-0.522429055,0.566566556,0.34528893,-0.057886461,-0.28449733,-0.171754982,-0.103504915,-0.396874311],\n [0.708808312,0.55187043,0.429938391,0.197257684,-3.9774e-05,-0.054427743,0.178345211,0.297789551,0.087920317,-0.003702672,-0.002424311,0.000192857,-0.029460632,0.037160795,0.061827225,0.276788373,0.000147768,-0.235898673,0.018602792,-0.125798933,0.029312864],\n [0.151113427,0.654574237,0.240882778,-0.018212974,-0.014025963,0.100180189,0.285310135,2.881490187,11.011691132,-0.437653779,-0.698453455,0.157185441,-0.1905967,-0.166253585,-0.151567002,0.150109019,0.444896847,-0.230918972,0.078079958,0.50626905,-0.254300147],\n ]\n\n# Matrices that are valid if tolerance > 1e-6\nLS = (180. / math.pi)**2\nINVALID_TLS_MATRICES = [\n [1.,1.,-1e-6,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.],\n [0.,0.,0.,0.,0.,0.,LS,LS,-LS*1e-6,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.],\n ]\n\ndef get_TLS_values():\n vals = rran(21)\n obj = TLSMatrices(values=vals)\n assert approx_equal(obj.get(\"TLS\"), vals, MAT_RND_TOL)\n return obj, vals\n\ndef get_TLS_amplitudes(n):\n vals = rran(n)\n obj = TLSAmplitudes(values=vals)\n assert approx_equal(obj.values, vals, AMP_RND_TOL)\n return obj, vals\n\ndef tst_set_precision():\n for cl in [TLSMatrices, TLSAmplitudes]:\n initial = cl.get_precision()\n for i in range(5):\n precision = i\n cl.set_precision(precision)\n assert precision == cl.get_precision()\n # Check is class method\n precision = 2\n a = cl(list(range(21)))\n b = cl(list(range(21)))\n a.set_precision(precision)\n assert b.get_precision() == precision\n # Set back to original\n cl.set_precision(initial)\n assert cl.get_precision() == initial\n\n print('OK')\n\ndef tst_set_tolerance():\n for cl in [TLSMatrices, TLSAmplitudes]:\n initial = cl.get_tolerance()\n for i in range(6):\n tolerance = 10.0**(-i)\n cl.set_tolerance(tolerance)\n assert tolerance == cl.get_tolerance()\n # Check is class method\n tolerance = 0.1\n a = cl(list(range(21)))\n b = cl(list(range(21)))\n a.set_tolerance(tolerance)\n assert b.get_tolerance() == tolerance\n # Set back to original\n cl.set_tolerance(initial)\n assert cl.get_tolerance() == initial\n\n print('OK')\n\ndef tst_TLSMatrices():\n \"\"\"Check classes operating as expected (copying where should be copying rather than referencing...)\"\"\"\n\n for _ in range(5):\n\n # A\n a, a_vals = get_TLS_values()\n\n # A - with zero trace of S\n a2_vals = a_vals.copy()\n a2_vals[20] = -(\n round(a2_vals[12], a.get_precision()) +\n round(a2_vals[16], a.get_precision())\n )\n\n # B\n b, b_vals = get_TLS_values()\n\n # B2 - Test initialisation from matrices\n b2 = TLSMatrices(T=b_vals[0:6], L=b_vals[6:12], S=b_vals[12:21])\n\n # Addition of another instance\n c = a + b\n c_vals = (a_vals.round(a.get_precision()) + b_vals.round(b.get_precision()))\n\n # Multiplication by scalar\n d = (5.0*a)\n d_vals = (5.0*a_vals.round(a.get_precision()))\n\n # Check vals stored and extracted properly\n assert approx_equal(a.T+a.L+a.S, a_vals, MAT_RND_TOL) # matrices are returned as tuples\n assert approx_equal(a.get(\"TLS\"), a_vals, MAT_RND_TOL)\n assert approx_equal(a.get(\"T\"), a_vals[0:6], MAT_RND_TOL)\n assert approx_equal(a.get(\"L\"), a_vals[6:12], MAT_RND_TOL)\n assert approx_equal(a.get(\"S\"), a_vals[12:21], MAT_RND_TOL)\n assert approx_equal(b.get(\"TLS\"), b_vals, MAT_RND_TOL)\n assert approx_equal(b.get(\"T\"), b_vals[0:6], MAT_RND_TOL)\n assert approx_equal(b.get(\"L\"), b_vals[6:12], MAT_RND_TOL)\n assert approx_equal(b.get(\"S\"), b_vals[12:21], MAT_RND_TOL)\n # Check initialisation from matrices\n assert approx_equal(b2.get(\"TLS\"), b_vals, MAT_RND_TOL)\n # Checks addition (needs greater tolerance)\n assert approx_equal(c.get(\"TLS\"), c_vals, MAT_RND_TOL)\n assert approx_equal(c.get(\"T\"), c_vals[0:6], MAT_RND_TOL)\n assert approx_equal(c.get(\"L\"), c_vals[6:12], MAT_RND_TOL)\n assert approx_equal(c.get(\"S\"), c_vals[12:21], MAT_RND_TOL)\n # Checks multiplication by scalar (need greater tolerance)\n assert approx_equal(d.get(\"TLS\"), d_vals, MAT_RND_TOL)\n assert approx_equal(d.get(\"T\"), d_vals[0:6], MAT_RND_TOL)\n assert approx_equal(d.get(\"L\"), d_vals[6:12], MAT_RND_TOL)\n assert approx_equal(d.get(\"S\"), d_vals[12:21], MAT_RND_TOL)\n\n # Check values are not being added/multiplied in place\n for _ in range(5):\n # Check addition\n assert approx_equal((a+a).get(), (a+a).get(), 0.0)\n # Check left- and right-multiplication\n assert approx_equal((5.0*a).get(), (5.0*a).get(), 0.0)\n assert approx_equal((a*5.0).get(), (a*5.0).get(), 0.0)\n # Check commutativity\n assert approx_equal((5.0*a).get(), (a*5.0).get(), 0.0)\n assert approx_equal(a.get(\"TLS\"), a_vals, MAT_RND_TOL)\n\n # Check copies - reset\n a_copy = a.copy()\n a_copy.reset()\n assert approx_equal(a.get(), a_vals, MAT_RND_TOL)\n # Check copies - set\n a_copy = a.copy()\n a_copy.set(list(range(21)))\n assert approx_equal(a.get(), a_vals, MAT_RND_TOL)\n # Check initialisation from other does not affect original\n a_copy = TLSMatrices(a)\n assert approx_equal(a_copy.get(), a_vals, MAT_RND_TOL)\n a_copy.reset()\n assert approx_equal(a.get(), a_vals, MAT_RND_TOL)\n\n # Check addition in place\n a.add(b)\n assert approx_equal(a.get(), c_vals, MAT_RND_TOL)\n assert approx_equal(b.get(), b_vals, MAT_RND_TOL) # Check b unchanged\n # Check multiplication in place\n a.multiply(10.0)\n assert approx_equal(a.get(), 10.0*c_vals, MAT_RND_TOL)\n # set back to original values\n a.set(a_vals, \"TLS\")\n assert approx_equal(a.get(), a_vals, MAT_RND_TOL)\n\n # Order of the letters should not matter (always returns T-L-S)\n assert a.get(\"TL\") == a.get(\"LT\")\n assert a.get(\"LS\") == a.get(\"SL\")\n assert a.get(\"TS\") == a.get(\"ST\")\n assert a.get(\"TLS\") == a.get(\"STL\")\n assert a.get(\"TLS\") == a.get(\"LST\")\n assert a.get(\"TLS\") == a.get(\"TSL\")\n assert a.get(\"TLS\") == a.get(\"LTS\")\n assert a.get(\"TLS\") == a.get(\"SLT\")\n\n # Check values can be replaced correctly\n assert approx_equal(a.get(), a_vals, MAT_RND_TOL) # Check values are correct at start\n # T\n new_t = rran(6).tolist()\n a.set(values=new_t, component_string=\"T\")\n assert approx_equal(a.get(\"T\"), new_t, MAT_RND_TOL)\n # L\n new_l = rran(6).tolist()\n a.set(values=new_l, component_string=\"L\")\n assert approx_equal(a.get(\"L\"), new_l, MAT_RND_TOL)\n # S but not Szz\n new_s = rran(8).tolist()\n a.set(new_s, \"S\", include_szz=False)\n new_s_all = new_s + [-(round(new_s[0], a.get_precision()) + round(new_s[4], a.get_precision()))]\n assert len(new_s_all) == 9\n assert approx_equal(a.get(\"S\"), new_s_all, MAT_RND_TOL)\n assert approx_equal(a.get(\"S\")[8], new_s_all[8]) # This number is pre-rounded so should be \"exact\"\"\n # S\n new_s = rran(9).tolist()\n a.set(new_s, \"S\", include_szz=True)\n assert approx_equal(a.get(\"S\"), new_s, MAT_RND_TOL)\n # all\n assert approx_equal(a.get(), new_t+new_l+new_s, MAT_RND_TOL)\n assert approx_equal(a.get(\"TLS\"), new_t+new_l+new_s, MAT_RND_TOL)\n # set all values except Szz\n a.set(a_vals[:-1], \"TLS\", include_szz=False)\n assert approx_equal(a.get(), a2_vals, MAT_RND_TOL)\n assert approx_equal(a.get()[20], a2_vals[20]) # This number is pre-rounded in a2_vals\n # set back to original values\n a.set(a_vals, \"TLS\", include_szz=True)\n assert approx_equal(a.get(), a_vals, MAT_RND_TOL)\n\n print('OK')\n\ndef tst_TLSMatrices_counts():\n \"\"\"Test that number of non-zero parameters are identifed correctly, etc\"\"\"\n\n letter_combinations = [\"T\",\"L\",\"S\",\"TL\",\"LS\",\"TS\",\"TLS\"]\n\n for _ in range(5):\n\n # Get values & object\n a, a_vals = get_TLS_values()\n assert (a_vals!=0.0).all()\n # Test reset function\n a.reset()\n assert approx_equal(a.get(), [0.0]*21, 0.0)\n\n # Test setting values to zero\n for letts in [\"\"]+letter_combinations:\n # Get a fresh set of matrices each time\n a, a_vals = get_TLS_values()\n assert (a_vals!=0.0).all()\n # Set selected matrices to zero\n for l in letts:\n v = a.get(l)\n a.set([0.0]*len(v), l)\n # Test ANY\n for t_l in letter_combinations:\n non_zero_l = ''.join(set(t_l).difference(letts))\n ret = a.any(t_l)\n assert ret == bool(non_zero_l)\n # High tolerance -- always false\n assert not a.any(t_l, 1e3)\n # Test NPARAMS (number of non-zero values)\n if letts == \"\":\n n_non_zero = 21\n else:\n n_non_zero = 21 - len(a.get(letts))\n assert a.n_params(free=False, non_zero=True) == n_non_zero\n assert a.n_params(free=True, non_zero=True) == n_non_zero - int(\"S\" not in letts)\n\n # Test setting values to non-zero\n for letts in [\"\"]+letter_combinations:\n # Get a fresh set of matrices each time\n a = TLSMatrices()\n\n # Set random values that should be rounded to zero\n for l in letts:\n v = list(a.get(l))\n i = numpy.random.randint(len(v))\n v[i] = 0.49*(10.**(-a.get_precision()))\n a.set(v, l)\n # Test ANY\n for t_l in letter_combinations:\n ret = a.any(t_l)\n assert ret == False # ALL values should have rounded to zero\n # High tolerance -- always false\n assert not a.any(t_l, 1e3)\n # Test NPARAMS\n assert a.n_params(free=False, non_zero=True) == 0\n assert a.n_params(free=True, non_zero=True) == 0\n assert a.n_params(free=False, non_zero=False) == 21\n assert a.n_params(free=True, non_zero=False) == 20\n\n # Set selected matrices to non-zero\n for l in letts:\n v = list(a.get(l))\n i = numpy.random.randint(len(v))\n # Set values just abovd the rounding/tolerance limit\n v[i] = 2.0*max(10.**(-a.get_precision()), a.get_tolerance())\n a.set(v, l)\n # Test ANY\n for t_l in letter_combinations:\n non_zero_l = ''.join(set(t_l).intersection(letts))\n ret = a.any(t_l)\n assert ret == bool(non_zero_l)\n # High tolerance -- always false\n assert not a.any(t_l, 1e3)\n # Test NPARAMS (number of non-zero values)\n if letts == \"\":\n n_non_zero = 0\n else:\n n_non_zero = len(a.get(letts))\n assert a.n_params(free=False, non_zero=True) == n_non_zero\n assert a.n_params(free=True, non_zero=True) == n_non_zero - int(\"S\" in letts)\n assert a.n_params(free=False, non_zero=False) == 21\n assert a.n_params(free=True, non_zero=False) == 20\n\n print('OK')\n\ndef tst_TLSMatrices_fails():\n \"\"\"Check that exceptions are raised where expected\"\"\"\n\n # Tolerances & Precision\n with raises(Exception) as e:\n TLSMatrices.set_precision(2.3) # must be int\n with raises(Exception) as e:\n TLSMatrices.set_tolerance(-0.1) # must be greater than 0.0\n with raises(Exception) as e:\n TLSMatrices.set_tolerance(0.0) # must be greater than 0.0\n\n # Check doesn't error with the correct length\n a = TLSMatrices(T=list(range(6)), L=list(range(6)), S=list(range(9)))\n\n # Check length of input matrices\n for tt,ll,ss in [\n (5, 6, 9),\n (7, 6, 9),\n (6, 5, 9),\n (6, 7, 9),\n (6, 6, 8),\n (6, 6, 10),\n ]:\n with raises(Exception) as e:\n a = TLSMatrices(rran(tt),rran(ll),rran(ss))\n assert \"Python argument types in\" in str(e.value)\n\n # Check setting values with incorrect size array\n msg = \"Mismatch between the length of the selected matrices and the length of the input array\"\n a = TLSMatrices()\n for l, sel in [\n (6, \"T\"),\n (6, \"L\"),\n (9, \"S\"),\n (12, \"TL\"),\n (15, \"TS\"),\n (15, \"LS\"),\n (21, \"TLS\"),\n ]:\n a.set(rran(l), sel)\n with raises(Exception) as e:\n a.set(rran(l-1), sel)\n assert msg == str(e.value)\n with raises(Exception) as e:\n a.set(rran(l+1), sel)\n assert msg == str(e.value)\n if \"S\" in sel:\n a.set(rran(l-1), sel, include_szz=False)\n with raises(Exception) as e:\n a.set(rran(l-2), sel, include_szz=False)\n assert msg == str(e.value)\n with raises(Exception) as e:\n a.set(rran(l), sel, include_szz=False)\n assert msg == str(e.value)\n\n # Check length of input array\n for i in [20,22]:\n with raises(Exception) as e:\n a = TLSMatrices(list(range(i)))\n assert \"Input values must have length 21\" == str(e.value)\n\n # Invalid letters in the selection strings\n a = TLSMatrices(TLSMATRICES[0])\n for s in [\"\", \"F\", \"TLSD\", \"2T\"]:\n with raises(ValueError) as e:\n a.any(s)\n if not s:\n assert \"Empty string provided: '{}'\".format(s) == str(e.value)\n else:\n assert \"Invalid letters in string (not T, L or S): '{}'\".format(s) == str(e.value)\n\n with raises(ValueError) as e:\n a.get(s)\n if not s:\n assert \"Empty string provided: '{}'\".format(s) == str(e.value)\n else:\n assert \"Invalid letters in string (not T, L or S): '{}'\".format(s) == str(e.value)\n\n # Multipliers must be positive\n with raises(Exception) as e:\n a.multiply(-0.1) # must be greater than 0.0\n assert \"Multiplier must be positive\" == str(e.value)\n\n a.multiply(0.0) # can be equal to zero!\n\n # Negative tolerances!\n msg = \"Tolerance provided must either be positive or -1\"\n # Allowed to be -1\n a.any(\"TLS\", -1)\n # Any\n with raises(Exception) as e:\n a.any(\"TLS\", -0.1)\n assert msg == str(e.value)\n # Decompose\n with raises(Exception) as e:\n a.decompose(-0.1)\n assert msg == str(e.value)\n # Valid\n with raises(Exception) as e:\n a.is_valid(-0.1)\n assert msg == str(e.value)\n # Normalise\n with raises(Exception) as e:\n a.normalise([(1,2,3)],(0,0,0),1.0,-0.1)\n assert msg == str(e.value)\n\n # Negative/zero-value target values!\n msg = \"target must be positive\"\n with raises(Exception) as e:\n a.normalise([(1,2,3)],(0,0,0),0.0)\n assert msg == str(e.value)\n with raises(Exception) as e:\n a.normalise([(1,2,3)],(0,0,0),-1.0)\n assert msg == str(e.value)\n\n print('OK')\n\ndef tst_TLSMatrices_uijs():\n \"\"\"Check that uijs are generated from coordinates as expected\"\"\"\n\n from mmtbx.tls import tlso, uaniso_from_tls_one_group\n from scitbx.linalg.eigensystem import real_symmetric\n\n for vals in TLSMATRICES:\n\n # Initialise\n a = TLSMatrices(vals)\n # Test sets of matrices are valid\n assert a.is_valid()\n\n # Get a set of random coordinates\n n_atm = 5\n coords = rran(n_atm*3).reshape(n_atm,3)\n origin = rran(3)\n\n # Reference Uijs\n tls_obj = tlso(t=a.T, l=a.L, s=a.S, origin=(0.0,0.0,0.0)) # Set origin to zero and subtract from coords as manual check\n uij_ref = uaniso_from_tls_one_group(tls_obj, coords-origin, zeroize_trace=False)\n uij_ref_np = numpy.array(uij_ref)\n\n # Uijs from the class being tested\n uij_test = a.uijs(coords, origin)\n uij_test_np = numpy.array(uij_test)\n\n # Compare (should be identical because class calls the uaniso function)\n assert approx_equal(uij_ref_np.flatten(), uij_test_np.flatten(), 0.0)\n\n # Calculate average eigenvalue of output uijs\n # TODO: verify that real_symmetric returns non-dict, I assume its an eigensystem-y instance\n eigs = [real_symmetric(u).values() for u in uij_test]\n orig_mean_eig = numpy.mean(eigs)\n\n for target in TEST_TARGETS:\n # Extract copy to test normalisation\n b = a.copy()\n # Normalise\n mult = b.normalise(coords, origin, target=target)\n assert approx_equal(orig_mean_eig, target*mult, LAST_DP_TOL)\n # Extract normalised uijs\n uij_norm = b.uijs(coords, origin)\n uij_norm_np = numpy.array(uij_norm)\n # Check average eigenvalue\n # TODO: see above todo\n eigs = [real_symmetric(u).values() for u in uij_norm]\n mean_eig_norm = numpy.mean(eigs)\n assert approx_equal(mean_eig_norm, target, LAST_DP_TOL)\n # Check that normalised values related to original values by multiplier\n uij_comp_np = mult*uij_norm_np\n assert approx_equal(uij_comp_np.flatten(), uij_test_np.flatten(), LAST_DP_TOL)\n\n print('OK')\n\ndef tst_TLSAmplitudes():\n \"\"\"Exercise the TLSAmplitudes class\"\"\"\n\n for length in TEST_LENGTHS:\n\n # Initialise from array\n a, a_vals = get_TLS_amplitudes(length)\n\n # Initialise from length\n b = TLSAmplitudes(length)\n assert b.size() == length\n # Check values intialised to 1\n assert approx_equal(b.values, [1.0]*length, 0.0)\n # Set values using set function\n b_vals = rran(length)\n b.set(b_vals)\n assert approx_equal(b.values, b_vals, AMP_RND_TOL)\n\n # Addition of another instance\n c = a + b\n c_vals = (a_vals.round(a.get_precision()) + b_vals.round(b.get_precision()))\n\n # Multiplication by scalar\n d = (5.0*a)\n d_vals = (5.0*a_vals.round(a.get_precision()))\n\n # Intialise from other\n e = TLSAmplitudes(a)\n\n # Check initial values\n assert approx_equal(a.values, a_vals, AMP_RND_TOL)\n assert approx_equal(b.values, b_vals, AMP_RND_TOL)\n assert approx_equal(c.values, c_vals, AMP_RND_TOL)\n assert approx_equal(d.values, d_vals, AMP_RND_TOL)\n assert approx_equal(e.values, a_vals, AMP_RND_TOL)\n assert approx_equal(e.values, a.values, 0.0)\n\n assert a.any()\n assert b.any()\n assert c.any()\n assert d.any()\n assert e.any()\n\n assert not a.any(1e3)\n assert not b.any(1e3)\n assert not c.any(1e3)\n assert not d.any(1e3)\n assert not e.any(1e3)\n\n assert a.size() == length\n assert b.size() == length\n assert c.size() == length\n assert d.size() == length\n assert e.size() == length\n\n # Check get\n assert approx_equal(a.values, a.get(list(range(a.size()))), 0.0)\n assert approx_equal(b.values, b.get(list(range(b.size()))), 0.0)\n assert approx_equal(c.values, c.get(list(range(c.size()))), 0.0)\n assert approx_equal(d.values, d.get(list(range(d.size()))), 0.0)\n assert approx_equal(e.values, e.get(list(range(e.size()))), 0.0)\n\n # Check reset works\n e.reset()\n assert approx_equal(e.values, [1.0]*e.size(), 0.0)\n assert e.any()\n # Check that a is unchanged by e.reset())\n assert approx_equal(a.values, a_vals, AMP_RND_TOL)\n\n # Check values are not being added/multiplied in place\n for _ in range(5):\n # Check addition\n assert approx_equal((a+a).values, (a+a).values, 0.0)\n # Check left- and right-multiplication\n assert approx_equal((5.0*a).values, (5.0*a).values, 0.0)\n assert approx_equal((a*5.0).values, (a*5.0).values, 0.0)\n # Check commutativity\n assert approx_equal((5.0*a).values, (a*5.0).values, 0.0)\n # Final check against initial values\n assert approx_equal(a.values, a_vals, AMP_RND_TOL)\n\n # Check indexing\n for i in range(a.size()):\n assert approx_equal(a[i], a_vals[i], AMP_RND_TOL)\n\n # Check addition in place\n a.add(b)\n assert approx_equal(a.values, c_vals, AMP_RND_TOL)\n assert approx_equal(b.values, b_vals, AMP_RND_TOL) # Check b unchanged\n # Check multiplication in place\n mult = 10.0\n a.multiply(mult)\n assert approx_equal(a.values, mult*c_vals, AMP_RND_TOL)\n # set back to original values\n a.set(a_vals)\n assert approx_equal(a.values, a_vals, AMP_RND_TOL)\n assert approx_equal(b.values, b_vals, AMP_RND_TOL)\n\n # Test setting subset of values\n selection = iran(a.size(), size=min(3,a.size()), replace=False)\n new_vals = rran(len(selection)).tolist()\n chg_a_vals = a_vals.copy()\n assert approx_equal(a_vals, chg_a_vals, 0.0)\n for new_idx, chg_idx in enumerate(selection):\n assert chg_a_vals[chg_idx] != new_vals[new_idx] # Check that new values are different!\n chg_a_vals[chg_idx] = new_vals[new_idx]\n assert approx_equal(chg_a_vals[selection], new_vals, AMP_RND_TOL) # Check that values are set correctly\n a_chg = a.copy()\n assert approx_equal(a_chg.values, a_vals, AMP_RND_TOL)\n a_chg.set(new_vals, list(selection.astype(numpy.uint)))\n assert approx_equal(a_chg.values, chg_a_vals, AMP_RND_TOL)\n\n # Test reset and n_params\n for _ in range(5):\n\n # All non-zero\n assert a_vals.all()\n assert a.any()\n assert approx_equal(a.values, a_vals, AMP_RND_TOL)\n assert a.n_params(non_zero=True) == a.size()\n assert a.n_params(non_zero=False) == a.size()\n\n # Set all values to one\n a.reset()\n assert a.any()\n assert approx_equal(a.values, [1.0]*a.size(), 0.0)\n assert a.n_params(non_zero=True) == a.size()\n assert a.n_params(non_zero=False) == a.size()\n # Set some values to non-one\n selection = iran(a.size(), size=min(3,a.size()), replace=False).tolist()\n new_vals = rran(len(selection)).tolist()\n a.set(new_vals, selection)\n for i, v in enumerate(a.values):\n if i in selection:\n assert approx_equal(v, new_vals[selection.index(i)], AMP_RND_TOL)\n else:\n assert v == 1.0\n assert a.n_params(non_zero=True) == a.size() - new_vals.count(0.0)\n assert a.n_params(non_zero=False) == a.size()\n\n # Set all values to zero\n a.zero_values()\n assert not a.any()\n assert approx_equal(a.values, [0.0]*a.size(), 0.0)\n assert a.n_params(non_zero=True) == 0\n assert a.n_params(non_zero=False) == a.size()\n # Set some values to non-zero\n selection = iran(a.size(), size=min(3,a.size()), replace=False).tolist()\n new_vals = rran(len(selection)).tolist()\n a.set(new_vals, selection)\n for i, v in enumerate(a.values):\n if i in selection:\n assert approx_equal(v, new_vals[selection.index(i)], AMP_RND_TOL)\n else:\n assert v == 0.0\n assert a.n_params(non_zero=True) == len(new_vals) - new_vals.count(0.0)\n assert a.n_params(non_zero=False) == a.size()\n assert a.any()\n\n # Set all values to original\n a.set(a_vals.tolist(), list(range(a.size()))) # set all values by selection, just to mix things up\n assert approx_equal(a.values, a_vals, AMP_RND_TOL)\n assert a.n_params(non_zero=True) == a.size()\n assert a.n_params(non_zero=False) == a.size()\n # Set some values to zero\n new_vals = [0.0, 100.0, 0.0, 34.5, 1e-4, -1e-4][:a.size()] # make sure values not longer than a\n selection = iran(a.size(), size=len(new_vals), replace=False).tolist()\n assert len(selection) == len(new_vals)\n a.set(new_vals, selection)\n for i, v in enumerate(a.values):\n if i in selection:\n assert approx_equal(v, new_vals[selection.index(i)], AMP_RND_TOL)\n else:\n assert approx_equal(v, a_vals[i], AMP_RND_TOL)\n assert a.n_params(non_zero=True) == a.size() - numpy.round(new_vals, a.get_precision()).tolist().count(0.0)\n assert a.n_params(non_zero=False) == a.size()\n\n # Set all values to original\n a.set(a_vals.tolist(), list(range(a.size()))) # set all values by selection, just to mix things up\n assert approx_equal(a.values, a_vals, AMP_RND_TOL)\n assert a.n_params(non_zero=True) == a.size()\n assert a.n_params(non_zero=False) == a.size()\n # Set some values to negative\n selection = iran(a.size(), size=min(4,a.size()), replace=False).tolist()\n new_vals = [-1.0*v for v in a.get(selection)]\n a.set(new_vals, selection)\n for i, v in enumerate(a.values):\n if i in selection:\n assert approx_equal(v, -a_vals[i], AMP_RND_TOL)\n else:\n assert approx_equal(v, a_vals[i], AMP_RND_TOL)\n assert a.n_params(non_zero=True) == a.size()\n assert a.n_params(non_zero=False) == a.size()\n # Zero negative values and test they are zero\n a.zero_negative_values()\n for i, v in enumerate(a.values):\n if i in selection:\n assert v == 0.0\n else:\n assert approx_equal(v, a_vals[i], AMP_RND_TOL)\n assert a.n_params(non_zero=True) == a.size() - len(selection)\n assert a.n_params(non_zero=False) == a.size()\n\n # Reset for next loop, etc\n a.set(a_vals.tolist(), list(range(a.size()))) # set all values by selection, just to mix things up\n assert approx_equal(a.values, a_vals, AMP_RND_TOL)\n assert a.n_params(non_zero=True) == a.size()\n assert a.n_params(non_zero=False) == a.size()\n\n print('OK')\n\ndef tst_TLSAmplitudes_fails():\n \"\"\"Check that exceptions are raised where expected\"\"\"\n\n # Tolerances & Precision\n with raises(Exception) as e:\n TLSAmplitudes.set_precision(2.3) # must be int\n with raises(Exception) as e:\n TLSAmplitudes.set_tolerance(-0.1) # must be greater than 0.0\n with raises(Exception) as e:\n TLSAmplitudes.set_tolerance(0.0) # must be greater than 0.0\n\n with raises(Exception) as e:\n TLSAmplitudes(0)\n\n a = TLSAmplitudes(10)\n b = TLSAmplitudes(11)\n\n # Adding incompatible lengths\n with raises(Exception) as e:\n a+b\n assert \"TLSAmplitudes must have the same length\" == str(e.value)\n with raises(Exception) as e:\n a.add(b)\n assert \"TLSAmplitudes must have the same length\" == str(e.value)\n\n # Negative tolerances!\n msg = \"Tolerance provided must either be positive or -1\"\n # Allowed to be -1\n a.any(-1)\n # Any\n with raises(Exception) as e:\n a.any(-0.1)\n assert msg == str(e.value)\n\n # Invalid selections!\n with raises(Exception) as e:\n a.get([])\n assert \"No indices given for selection\" == str(e.value)\n with raises(Exception) as e:\n a.get([a.size()])\n assert \"Selection indices out of range of TLSAmplitudes\" == str(e.value)\n with raises(Exception) as e:\n a.get(list(range(a.size()))+[0])\n assert \"Selection indices cannot be longer than TLSAmplitudes\" == str(e.value)\n\n # Valid, but odd, selections -- maybe change later\n a.get([1,1,1,1])\n\n # Invalid selections -- setting values\n with raises(Exception) as e:\n a.set(list(range(a.size()-1)))\n assert \"Input array must be the same length as TLSAmplitudes\" == str(e.value)\n with raises(Exception) as e:\n a.set(list(range(a.size()+1)))\n assert \"Input array must be the same length as TLSAmplitudes\" == str(e.value)\n # No selection\n with raises(Exception) as e:\n a.set([],[])\n assert \"No indices given for selection\" == str(e.value)\n # Negative indices!\n with raises(Exception) as e:\n a.set([],[])\n assert \"No indices given for selection\" == str(e.value)\n # Mismatching size\n for n in range(1,a.size()):\n with raises(Exception) as e:\n a.set(rran(n-1), iran(a.size(), size=n, replace=False).astype(numpy.uint))\n assert \"Input values must be the same length as input selection\" == str(e.value)\n with raises(Exception) as e:\n a.set(rran(n+1), iran(a.size(), size=n, replace=False).astype(numpy.uint))\n assert \"Input values must be the same length as input selection\" == str(e.value)\n # Negative indices\n with raises(OverflowError) as e:\n a.set([1], [-1])\n assert (\"can't convert negative value to unsigned\" == str(e.value) or\n \"negative overflow\" in str(e.value) or\n \"can't convert negative value to unsigned\" in str(e.value))\n\n # Negative/zero-value target values!\n msg = \"target must be positive\"\n with raises(Exception) as e:\n a.normalise(0.0)\n assert msg == str(e.value)\n with raises(Exception) as e:\n a.normalise(-1.0)\n assert msg == str(e.value)\n\n print('OK')\n\ndef tst_TLSMatricesAndAmplitudes():\n \"\"\"Exercise the TLSMatricesAndAmplitudes class\"\"\"\n\n for length in TEST_LENGTHS:\n\n # Iterate through test matrices\n for a_mats in TLSMATRICES:\n a_amps = rran(length)\n # Initialise from existing classes (objects are passed by reference!)\n a_m = TLSMatrices(a_mats)\n a_a = TLSAmplitudes(a_amps)\n a = TLSMatricesAndAmplitudes(a_m, a_a)\n\n # Check values passed through\n assert approx_equal(a.matrices.get(\"TLS\"), a_mats, MAT_RND_TOL)\n assert approx_equal(a.amplitudes.values , a_amps, AMP_RND_TOL)\n # Double check that values are the same\n assert approx_equal(a_m.T, a.matrices.T, 0.0)\n assert approx_equal(a_m.L, a.matrices.L, 0.0)\n assert approx_equal(a_m.S, a.matrices.S, 0.0)\n assert approx_equal(a_a.values, a.amplitudes.values, 0.0)\n\n # Initialise from other\n b = TLSMatricesAndAmplitudes(a)\n assert approx_equal(b.matrices.get(\"TLS\"), a.matrices.get(\"TLS\"), 0.0)\n assert approx_equal(b.amplitudes.values , a.amplitudes.values, 0.0)\n\n # Initialise from copy\n c = a.copy()\n assert approx_equal(c.matrices.get(\"TLS\"), a.matrices.get(\"TLS\"), 0.0)\n assert approx_equal(c.amplitudes.values , a.amplitudes.values, 0.0)\n\n # Initialise from length\n d = TLSMatricesAndAmplitudes(length)\n\n # Initialise straight from values\n e = TLSMatricesAndAmplitudes(a_mats, a_amps)\n\n # Check that a is using objects by reference, and that b & c are initialised by values from a\n a.reset()\n assert approx_equal(a.matrices.get(\"TLS\"), [0.0]*21, 0.0)\n assert approx_equal(a.amplitudes.values , [1.0]*length, 0.0)\n # Original objects should also be affected (same object)\n assert approx_equal(a_m.get(\"TLS\") , [0.0]*21, 0.0)\n assert approx_equal(a_a.values , [1.0]*length, 0.0)\n # Check b & c are not reset (copied by reference)\n assert approx_equal(b.matrices.get(\"TLS\"), a_mats, MAT_RND_TOL)\n assert approx_equal(b.amplitudes.values , a_amps, AMP_RND_TOL)\n assert approx_equal(c.matrices.get(\"TLS\"), a_mats, MAT_RND_TOL)\n assert approx_equal(c.amplitudes.values , a_amps, AMP_RND_TOL)\n # Reset b and check c unaffected\n b.reset()\n assert approx_equal(b.matrices.get(\"TLS\"), [0.0]*21, 0.0)\n assert approx_equal(b.amplitudes.values , [1.0]*length, 0.0)\n assert approx_equal(c.matrices.get(\"TLS\"), a_mats, MAT_RND_TOL)\n assert approx_equal(c.amplitudes.values , a_amps, AMP_RND_TOL)\n\n # Check d that defaults are intialised as expected\n assert approx_equal(d.matrices.get(\"TLS\"), [0.0]*21, 0.0)\n assert approx_equal(d.amplitudes.values , [1.0]*length, 0.0)\n\n # Check e is initialised correctly\n assert approx_equal(e.matrices.get(\"TLS\"), a_mats, MAT_RND_TOL)\n assert approx_equal(e.amplitudes.values , a_amps, AMP_RND_TOL)\n\n print('OK')\n\ndef tst_TLSMatricesAndAmplitudes_counts():\n \"\"\"Test that number of non-zero parameters are identifed correctly, etc\"\"\"\n\n for length in TEST_LENGTHS:\n\n # Iterate through test matrices\n for a_mats in TLSMATRICES:\n a_amps = rran(length)\n a = TLSMatricesAndAmplitudes(a_mats, a_amps.tolist())\n assert approx_equal(a.matrices.get(\"TLS\"), a_mats, MAT_RND_TOL)\n assert approx_equal(a.amplitudes.values , a_amps, AMP_RND_TOL)\n\n # Check tolerances\n assert not a.is_null()\n assert not a.is_null(-1, -1)\n assert not a.is_null(0.0, 0.0)\n assert a.is_null(1e3, -1)\n assert a.is_null(-1, 1e3)\n assert a.is_null(1e3, 1e3)\n\n # Check null function + n_params\n assert not a.is_null()\n # All should be non-zero\n assert a.n_params(free=True, non_zero=True) == 20 + length\n assert a.n_params(free=True, non_zero=False) == 20 + length\n assert a.n_params(free=False, non_zero=True) == 21 + length\n assert a.n_params(free=False, non_zero=False) == 21 + length\n # Set matrices to zero\n a.matrices.reset()\n assert a.is_null()\n # Matrices are null, amplitudes not\n assert a.n_params(free=True, non_zero=True) == length\n assert a.n_params(free=True, non_zero=False) == 20 + length\n assert a.n_params(free=False, non_zero=True) == length\n assert a.n_params(free=False, non_zero=False) == 21 + length\n # Reset back to original values\n a.matrices.set(a_mats)\n assert not a.is_null()\n # All should be non-zero\n assert a.n_params(free=True, non_zero=True) == 20 + length\n assert a.n_params(free=True, non_zero=False) == 20 + length\n assert a.n_params(free=False, non_zero=True) == 21 + length\n assert a.n_params(free=False, non_zero=False) == 21 + length\n # Set amplitudes to one -- NOT NULL\n a.amplitudes.reset()\n assert not a.is_null()\n # Amplitudes are all one\n assert a.n_params(free=True, non_zero=True) == 20 + length\n assert a.n_params(free=True, non_zero=False) == 20 + length\n assert a.n_params(free=False, non_zero=True) == 21 + length\n assert a.n_params(free=False, non_zero=False) == 21 + length\n # Set amplitudes to zero -- NULL\n a.amplitudes.zero_values()\n assert a.is_null()\n # Amplitudes are all one\n assert a.n_params(free=True, non_zero=True) == 20\n assert a.n_params(free=True, non_zero=False) == 20 + length\n assert a.n_params(free=False, non_zero=True) == 21\n assert a.n_params(free=False, non_zero=False) == 21 + length\n\n # Reset to original values\n a.amplitudes.set(a_amps)\n assert approx_equal(a.matrices.get(\"TLS\"), a_mats, MAT_RND_TOL)\n assert approx_equal(a.amplitudes.values , a_amps, AMP_RND_TOL)\n assert not a.is_null()\n\n print('OK')\n\ndef tst_TLSMatricesAndAmplitudes_fails():\n \"\"\"Check that exceptions are raised where expected\"\"\"\n\n m=TLSMatrices()\n a=TLSAmplitudes(10)\n with raises(Exception) as e:\n TLSMatricesAndAmplitudes(m,m)\n with raises(Exception) as e:\n TLSMatricesAndAmplitudes(a,a)\n with raises(Exception) as e:\n TLSMatricesAndAmplitudes(a,m)\n\n with raises(Exception) as e:\n TLSMatricesAndAmplitudes(rran(20), rran(10))\n assert \"Matrix values must have length 21\" == str(e.value)\n\n with raises(Exception) as e:\n TLSMatricesAndAmplitudes(rran(20), rran(10))\n assert \"Matrix values must have length 21\" == str(e.value)\n\n with raises(Exception) as e:\n TLSMatricesAndAmplitudes(rran(10), rran(21))\n assert \"Matrix values must have length 21\" == str(e.value)\n\n with raises(Exception) as e:\n TLSMatricesAndAmplitudes(rran(21), [])\n assert \"Amplitude values must have length greater than 0\" == str(e.value)\n\n # For use throughout\n n_dst = 3\n n_atm = 2\n assert n_dst>2 # needed for later\n assert n_atm>1 # needed for later\n assert n_dst != n_atm # need different otherwise cannot test for swaps of n_dst and n_atm\n ma = TLSMatricesAndAmplitudes(n_dst)\n\n # Tolerances\n ma.is_null(0.0, 0.0) # values can be zero\n ma.is_null(-1, -1) # values can be -1\n msg = \"Tolerance provided must either be positive or -1\"\n with raises(Exception) as e:\n ma.is_null(-0.1, -1)\n assert msg == str(e.value)\n with raises(Exception) as e:\n ma.reset_if_null(-0.1, -1)\n assert msg == str(e.value)\n with raises(Exception) as e:\n ma.is_null(-1, -0.1)\n assert msg == str(e.value)\n with raises(Exception) as e:\n ma.reset_if_null(-1, -0.1)\n assert msg == str(e.value)\n\n # Coordinates sets for following tests\n sites = flex.vec3_double(rran(n_dst*n_atm*3).reshape(n_dst*n_atm, 3).tolist())\n sites.reshape(flex.grid(n_dst,n_atm))\n origins = rran(n_dst*3).reshape(n_dst,3)\n\n # Check this doesn't break it\n ma.copy().normalise_by_amplitudes(1.0)\n ma.copy().normalise_by_matrices(sites, origins, 1.0)\n # Normalise (target values)\n msg = \"target must be positive\"\n with raises(Exception) as e:\n ma.normalise_by_amplitudes(-0.1)\n assert msg == str(e.value)\n with raises(Exception) as e:\n ma.normalise_by_matrices(sites, origins, -0.1)\n assert msg == str(e.value)\n\n # Compatibility of sites/origins arrays (normalise and uijs)\n # Array has swapped axes\n msg = \"Mismatch between the size of origins and first dimension of sites_carts\"\n new_sites = flex.vec3_double(rran(n_dst*n_atm*3).reshape(n_dst*n_atm, 3).tolist())\n new_sites.reshape(flex.grid(n_atm,n_dst)) # swap axes\n with raises(Exception) as e:\n ma.normalise_by_matrices(new_sites, origins)\n assert msg == str(e.value)\n with raises(Exception) as e:\n ma.uijs(new_sites, origins)\n assert msg == str(e.value)\n # sites is too short/long\n msg = \"Mismatch between the size of origins and first dimension of sites_carts\"\n for n_tmp in [n_dst-1, n_dst+1]:\n new_sites = flex.vec3_double(rran(n_tmp*n_atm*3).reshape(n_tmp*n_atm, 3).tolist())\n new_sites.reshape(flex.grid(n_tmp,n_atm))\n with raises(Exception) as e:\n ma.normalise_by_matrices(new_sites, origins)\n assert msg == str(e.value)\n with raises(Exception) as e:\n ma.uijs(new_sites, origins)\n assert msg == str(e.value)\n # Sites/origins compatible but not same length as amplitudes\n new_origins = rran(n_tmp*3).reshape(n_tmp, 3).tolist()\n ma.copy().normalise_by_matrices(new_sites, new_origins) # Should not error -- does not use amplitudes\n with raises(Exception) as e:\n ma.uijs(new_sites, new_origins)\n assert \"Mismatch between the size of TLSAmplitudes and the input arrays\" == str(e.value)\n\n # Check dimension of sites_carts\n msg = \"sites_carts must be 2-dimensional array of size (n_dst, n_atm)\"\n # Make 3-d array of sites\n n_fake = 2 # length of new dimension\n new_sites = flex.vec3_double(rran(n_fake*n_dst*n_atm*3).reshape(n_fake*n_dst*n_atm, 3).tolist())\n new_sites.reshape(flex.grid(n_fake,n_atm,n_dst))\n with raises(Exception) as e:\n ma.normalise_by_matrices(new_sites, origins)\n assert msg == str(e.value)\n with raises(Exception) as e:\n ma.uijs(new_sites, origins)\n assert msg == str(e.value)\n # Make 1-d array of sites\n new_sites = flex.vec3_double(rran(n_atm*3).reshape(n_atm, 3).tolist())\n new_sites.reshape(flex.grid(n_atm))\n with raises(Exception) as e:\n ma.normalise_by_matrices(new_sites, origins)\n assert msg == str(e.value)\n with raises(Exception) as e:\n ma.uijs(new_sites, origins)\n assert msg == str(e.value)\n # Make other 1-d array\n new_sites = flex.vec3_double(rran(n_atm*3).reshape(n_atm, 3))\n with raises(Exception) as e:\n ma.normalise_by_matrices(new_sites, origins)\n assert msg == str(e.value)\n with raises(Exception) as e:\n ma.uijs(new_sites, origins)\n assert msg == str(e.value)\n\n # Check error when origins is 2-dimensional\n n_fake = 2 # length of new dimension\n new_origins = flex.vec3_double(rran(n_fake*n_atm*3).reshape(n_fake*n_atm, 3).tolist())\n new_origins.reshape(flex.grid(n_fake,n_atm))\n with raises(Exception) as e:\n ma.normalise_by_matrices(sites, new_origins)\n assert \"Python argument types in\" in str(e.value)\n\n # Make new sites/origins for subset of ampls for use below\n t_n_dst = n_dst - 1\n new_sites = flex.vec3_double(rran(t_n_dst*n_atm*3).reshape(t_n_dst*n_atm, 3).tolist())\n new_sites.reshape(flex.grid(t_n_dst,n_atm))\n new_origins = rran(t_n_dst*3).reshape(t_n_dst,3)\n\n # Selection compatibility with sites and origins\n msg = \"Mismatch between the size of selection and the input arrays\"\n for l in [t_n_dst-1, t_n_dst+1]:\n # Selection too short\n sel = iran(n_dst, size=l, replace=False)\n with raises(Exception) as e:\n ma.uijs(new_sites, new_origins, sel.astype(numpy.uint))\n assert msg == str(e.value)\n # Invalid selection\n sel = iran(n_dst, size=t_n_dst, replace=False)\n sel[-1] = n_dst # larger than allowed\n with raises(Exception) as e:\n ma.uijs(new_sites, new_origins, sel.astype(numpy.uint))\n assert \"Selection indices out of range of TLSAmplitudes\" == str(e.value)\n\n print('OK')\n\ndef tst_TLSMatricesAndAmplitudes_valid():\n \"\"\"Check that whole object is valid/invalid based on components\"\"\"\n\n length = 10\n indices = [3,5]\n tol = 1e-6\n\n for fail_mat in INVALID_TLS_MATRICES:\n a_amps = rran(length)\n assert (a_amps<1.0).all()\n a = TLSMatricesAndAmplitudes(fail_mat, a_amps.tolist())\n for i in range(length):\n assert a.expand()[i].is_valid(tol)\n assert a.is_valid(flex.size_t([i]), tol)\n assert a.is_valid(tol)\n assert a.is_valid(flex.size_t(indices), tol)\n a.amplitudes.set([12., 1.1], flex.size_t(indices))\n assert not a.is_valid(tol)\n assert not a.is_valid(flex.size_t(indices), tol)\n assert a.is_valid(flex.size_t([i for i in range(length) if i not in indices]), tol)\n for i in range(length):\n if i in indices:\n assert not a.expand()[i].is_valid(tol)\n assert not a.is_valid(flex.size_t([i]), tol)\n else:\n assert a.expand()[i].is_valid(tol)\n assert a.is_valid(flex.size_t([i]), tol)\n\n print('OK')\n\ndef tst_TLSMatricesAndAmplitudes_uijs():\n \"\"\"Test uijs generated correctly\"\"\"\n\n for length in TEST_LENGTHS:\n\n # Iterate through test matrices\n for a_mats in TLSMATRICES:\n a_amps = rran(length)\n a = TLSMatricesAndAmplitudes(a_mats, a_amps.tolist())\n assert approx_equal(a.matrices.get(\"TLS\"), a_mats, MAT_RND_TOL)\n assert approx_equal(a.amplitudes.values, a_amps, AMP_RND_TOL)\n\n # Get a set of random coordinates\n n_atm = 5\n coords = rran(length*n_atm*3).reshape(length,n_atm,3)\n origns = rran(length*3).reshape(length,3)\n\n # Format coordinates into flex array\n sites = flex.vec3_double(coords.reshape(length*n_atm, 3).tolist())\n sites.reshape(flex.grid(length,n_atm))\n # Uijs from the testing class\n all_uijs = a.uijs(sites, origns)\n # Reformat to numpy array for slicing\n all_uijs_np = numpy.array(all_uijs).reshape(length,n_atm,6)\n\n # Check expand\n exp = a.expand() # these also used later\n for i, m in enumerate(exp):\n\n # Check expanded matrices have correct values\n exp_amp = round(a_amps[i], a.amplitudes.get_precision())\n exp_mat = numpy.round(a_mats, a.matrices.get_precision())\n assert approx_equal(m.get(\"TLS\"), exp_amp*exp_mat, LAST_DP_TOL)\n\n # Check that uij from this class equals that expected from the container class\n this_uij = m.uijs(coords[i].tolist(), origns[i].tolist())\n assert approx_equal(numpy.array(this_uij).flatten(), all_uijs_np[i].flatten())\n\n # Reshape to 1d and round for convenience\n all_uijs_np = all_uijs_np.reshape(length*n_atm,6)\n\n # Test normalise by amplitudes\n for target in TEST_TARGETS:\n\n # Create copy to operate on\n new_a = a.copy()\n\n # Apply normalisation\n mult = new_a.normalise_by_amplitudes(target=target)\n\n # Average amplitude should now be target\n mean_amp = numpy.mean(new_a.amplitudes.values)\n assert approx_equal(mean_amp, target, LAST_DP_TOL)\n\n # Check expanded matrices are the same\n new_exp = new_a.expand()\n for new, orig in zip(new_exp, exp):\n assert approx_equal(new.get(\"TLS\"), orig.get(\"TLS\"))\n\n # Test normalise by matrices\n from scitbx.linalg.eigensystem import real_symmetric\n for target in TEST_TARGETS:\n\n # Create copy to operate on\n new_a = a.copy()\n\n # Apply normalisation\n new_a.normalise_by_matrices(sites, origns, target)\n\n # Average uij eigenvalue from Matrices object should now be target\n uijs = [new_a.matrices.uijs(coords[i], origns[i]) for i in range(length)]\n # TODO: see above todo\n eigenvalues = [[list(real_symmetric(u).values()) for u in uijs[i]] for i in range(length)]\n mean_eig = numpy.mean(eigenvalues)\n assert approx_equal(mean_eig, target, LAST_DP_TOL)\n\n # Check expanded matrices are the same\n new_exp = new_a.expand()\n for new, orig in zip(new_exp, exp):\n assert approx_equal(new.get(\"TLS\"), orig.get(\"TLS\"))\n\n # Output uijs should still be the same\n new_uijs = new_a.uijs(sites, origns)\n new_uijs_np = numpy.array(new_uijs)\n assert approx_equal(new_uijs_np.flatten(), all_uijs_np.flatten(), LAST_DP_TOL)\n\n print('OK')\n\ndef tst_TLSMatricesAndAmplitudesList():\n \"\"\"Exercise the TLSMatricesAndAmplitudesList class\"\"\"\n\n for length in [1,2,3]:\n for n_dst in [1,2,3]:\n mal = TLSMatricesAndAmplitudesList(length=length, n_amplitudes=n_dst)\n assert mal.is_null()\n assert mal.size() == length\n assert mal.n_params(free=False, non_zero=False) == (21 + n_dst) * length\n assert mal.n_params(free=True, non_zero=False) == (20 + n_dst) * length\n assert mal.n_params(free=False, non_zero=True) == (n_dst) * length # initialised with all matrices zero\n assert mal.n_params(free=True, non_zero=True) == (n_dst) * length # initialised with all matrices zero\n for i, ma in enumerate(mal):\n assert ma.amplitudes.size() == n_dst\n ma.matrices.set(rran(21))\n assert not mal.is_null()\n ma.amplitudes.set(rran(n_dst))\n assert not mal.is_null()\n for j in range(length):\n if i==j: continue\n ma2 = mal.get(j)\n assert not_approx_equal(list(ma.amplitudes.values), list(ma2.amplitudes.values))\n assert not_approx_equal(list(ma.matrices.get(\"TLS\")), list(ma2.matrices.get(\"TLS\")))\n assert mal.n_params(free=False, non_zero=False) == (21 + n_dst) * length\n assert mal.n_params(free=True, non_zero=False) == (20 + n_dst) * length\n assert mal.n_params(free=False, non_zero=True) == 21*(i+1) + (n_dst) * length\n assert mal.n_params(free=True, non_zero=True) == 20*(i+1) + (n_dst) * length\n assert mal.n_params(free=False, non_zero=False) == (21 + n_dst) * length\n assert mal.n_params(free=True, non_zero=False) == (20 + n_dst) * length\n assert mal.n_params(free=False, non_zero=True) == (21 + n_dst) * length\n assert mal.n_params(free=True, non_zero=True) == (20 + n_dst) * length\n\n # Reset all matrices\n mal.reset_matrices()\n assert mal.is_null()\n for ma in mal:\n assert not ma.matrices.any(\"TLS\")\n assert ma.amplitudes.any()\n assert ma.is_null()\n assert mal.n_params(free=False, non_zero=False) == (21 + n_dst) * length\n assert mal.n_params(free=True, non_zero=False) == (20 + n_dst) * length\n assert mal.n_params(free=False, non_zero=True) == (n_dst) * length\n assert mal.n_params(free=True, non_zero=True) == (n_dst) * length\n # This should mean all are null\n mal.reset_null_modes()\n assert mal.is_null()\n for ma in mal:\n assert not ma.matrices.any(\"TLS\")\n assert approx_equal(ma.amplitudes.values, [1.0]*n_dst)\n assert ma.is_null()\n assert mal.n_params(free=False, non_zero=False) == (21 + n_dst) * length\n assert mal.n_params(free=True, non_zero=False) == (20 + n_dst) * length\n assert mal.n_params(free=False, non_zero=True) == (n_dst) * length\n assert mal.n_params(free=True, non_zero=True) == (n_dst) * length\n # Reset all to non-zero\n for i, ma in enumerate(mal):\n ma.matrices.set(rran(21))\n ma.amplitudes.set(rran(n_dst))\n assert not ma.is_null()\n assert not mal.is_null()\n assert not mal.is_null()\n assert mal.n_params(free=False, non_zero=False) == (21 + n_dst) * length\n assert mal.n_params(free=True, non_zero=False) == (20 + n_dst) * length\n assert mal.n_params(free=False, non_zero=True) == (21 + n_dst) * length\n assert mal.n_params(free=True, non_zero=True) == (20 + n_dst) * length\n\n # Zero selection of amplitudes\n sel = iran(length, size=max(1,length-1), replace=False)\n mal.zero_amplitudes(sel.astype(numpy.uint))\n if length == 1:\n assert mal.is_null()\n else:\n assert not mal.is_null()\n for i, ma in enumerate(mal):\n if i in sel:\n exp = True\n else:\n exp = False\n assert True == ma.matrices.any(\"TLS\")\n assert exp == (not ma.amplitudes.any())\n assert exp == ma.is_null()\n assert mal.n_params(free=False, non_zero=False) == (21 + n_dst) * length\n assert mal.n_params(free=True, non_zero=False) == (20 + n_dst) * length\n assert mal.n_params(free=False, non_zero=True) == (21 + n_dst) * length - n_dst * len(sel)\n assert mal.n_params(free=True, non_zero=True) == (20 + n_dst) * length - n_dst * len(sel)\n # Only selection should be null\n mal.reset_null_modes()\n for i, ma in enumerate(mal):\n if i in sel:\n exp = True\n assert approx_equal(ma.amplitudes.values, [1.0]*n_dst)\n else:\n exp = False\n assert not_approx_equal(ma.amplitudes.values, [1.0]*n_dst)\n assert exp == (not ma.matrices.any(\"TLS\"))\n assert exp == ma.is_null()\n assert mal.n_params(free=False, non_zero=False) == (21 + n_dst) * length\n assert mal.n_params(free=True, non_zero=False) == (20 + n_dst) * length\n assert mal.n_params(free=False, non_zero=True) == 21 * (length - len(sel)) + n_dst * length\n assert mal.n_params(free=True, non_zero=True) == 20 * (length - len(sel)) + n_dst * length\n # Reset all to non-zero\n for i, ma in enumerate(mal):\n ma.matrices.set(rran(21))\n ma.amplitudes.set(rran(n_dst))\n assert not ma.is_null()\n assert not mal.is_null()\n assert mal.n_params(free=False, non_zero=False) == (21 + n_dst) * length\n assert mal.n_params(free=True, non_zero=False) == (20 + n_dst) * length\n assert mal.n_params(free=False, non_zero=True) == (21 + n_dst) * length\n assert mal.n_params(free=True, non_zero=True) == (20 + n_dst) * length\n\n # Check modes with zero matrices are reset\n sel = iran(length, size=max(1,length-1), replace=False)\n for i, ma in enumerate(mal):\n if i in sel:\n ma.matrices.reset()\n mal.reset_null_modes()\n # Only selection should be null\n for i, ma in enumerate(mal):\n if i in sel:\n exp = True\n assert approx_equal(ma.amplitudes.values, [1.0]*n_dst)\n else:\n exp = False\n assert not_approx_equal(ma.amplitudes.values, [1.0]*n_dst)\n assert exp == (not ma.matrices.any(\"TLS\"))\n assert exp == ma.is_null()\n assert mal.n_params(free=False, non_zero=False) == (21 + n_dst) * length\n assert mal.n_params(free=True, non_zero=False) == (20 + n_dst) * length\n assert mal.n_params(free=False, non_zero=True) == (21 + n_dst) * length - 21 * len(sel)\n assert mal.n_params(free=True, non_zero=True) == (20 + n_dst) * length - 20 * len(sel)\n # Reset all to non-zero\n for i, ma in enumerate(mal):\n ma.matrices.set(rran(21))\n ma.amplitudes.set(rran(n_dst))\n assert not ma.is_null()\n\n # Set random amplitudes to negative and then check they are zero-d\n isel = iran(length)\n asel = iran(n_dst, max(1,n_dst-1), replace=False)\n ma = mal.get(isel)\n ma.amplitudes.set(-rran(len(asel)), asel.astype(numpy.uint))\n prev_v = ma.amplitudes.values\n for i, v in enumerate(prev_v):\n if i in asel:\n assert v<0.0\n else:\n assert v>0.0\n mal.zero_negative_amplitudes()\n for i_ma, ma in enumerate(mal):\n if i_ma == isel:\n for i_v, v in enumerate(ma.amplitudes.values):\n if i_v in asel:\n assert v==0.0\n else:\n assert v==prev_v[i_v]\n else:\n assert ma.amplitudes.n_params(non_zero=True) == n_dst\n assert mal.n_params(free=False, non_zero=False) == (21 + n_dst) * length\n assert mal.n_params(free=True, non_zero=False) == (20 + n_dst) * length\n assert mal.n_params(free=False, non_zero=True) == (21 + n_dst) * length - len(asel)\n assert mal.n_params(free=True, non_zero=True) == (20 + n_dst) * length - len(asel)\n\n # Test initialisation from arrays\n mats = flex.double(rran(3*21).tolist())\n mats.reshape(flex.grid((3,21)))\n amps = flex.double(rran(3*10).tolist())\n amps.reshape(flex.grid((3,10)))\n mal = TLSMatricesAndAmplitudesList(mats, amps)\n assert not mal.is_null()\n for i, m in enumerate(mal):\n assert approx_equal(m.matrices.get(), mats[21*i:21*(i+1)])\n assert approx_equal(m.amplitudes.get(), amps[10*i:10*(i+1)])\n mats.set_selected(flex.bool(flex.grid(mats.all()), True), 0.0)\n amps.set_selected(flex.bool(flex.grid(amps.all()), True), 0.0)\n assert mats.all_eq(0.0)\n assert amps.all_eq(0.0)\n assert not mal.is_null()\n\n # Test reset\n mal.reset()\n assert mal.is_null()\n for ma in mal:\n assert ma.is_null()\n\n # Test uijs\n n_atm = 2\n n_dst = 3\n n_mod = 4\n mal = TLSMatricesAndAmplitudesList(length=n_mod, n_amplitudes=n_dst)\n for i, mats in enumerate(TLSMATRICES[:n_mod]):\n ma = mal[i]\n ma.matrices.set(mats)\n ma.amplitudes.set(rran(3))\n\n # For all modes\n coord_scale = 20.0 # set suitable scale for coordinates in angstrom\n rand_coords = (coord_scale*rran(n_dst*n_atm*3)).reshape(n_dst*n_atm, 3).tolist()\n sites = flex.vec3_double(rand_coords)\n sites.reshape(flex.grid(n_dst,n_atm))\n origins = rran(n_dst*3).reshape(n_dst,3)\n all_uijs = mal.uijs(sites, origins)\n sum_uijs = flex.sym_mat3_double(flex.grid((n_dst, n_atm)))\n assert all_uijs.all() == sum_uijs.all()\n for ma in mal:\n new_uijs = ma.uijs(sites, origins)\n assert new_uijs.all() == (n_dst, n_atm)\n sum_uijs = sum_uijs + new_uijs\n assert approx_equal(numpy.array(all_uijs).flatten(), numpy.array(sum_uijs).flatten())\n # And from an amplitudes selection\n n_tmp = max(1,n_dst-2)\n sel = iran(n_dst, size=n_tmp, replace=False)\n sites = flex.vec3_double(rran(n_tmp*n_atm*3).reshape(n_tmp*n_atm, 3).tolist())\n sites.reshape(flex.grid(n_tmp,n_atm))\n origins = rran(n_tmp*3).reshape(n_tmp,3)\n all_uijs = mal.uijs(sites, origins, sel.astype(numpy.uint))\n sum_uijs = flex.sym_mat3_double(flex.grid((n_tmp, n_atm)))\n assert all_uijs.all() == sum_uijs.all()\n for i, ma in enumerate(mal):\n new_uijs = ma.uijs(sites, origins, sel.astype(numpy.uint))\n assert new_uijs.all() == (n_tmp, n_atm)\n sum_uijs = sum_uijs + new_uijs\n assert approx_equal(numpy.array(all_uijs).flatten(), numpy.array(sum_uijs).flatten())\n\n # Check copy creates separate object\n mal = TLSMatricesAndAmplitudesList(length=n_mod, n_amplitudes=n_dst)\n for ma in mal:\n ma.matrices.set(rran(21))\n ma.amplitudes.set(rran(n_dst))\n mal_c = mal.copy()\n for i in range(n_mod):\n assert approx_equal(list(mal[i].matrices.get(\"TLS\")), list(mal_c[i].matrices.get(\"TLS\")))\n assert approx_equal(list(mal[i].amplitudes.values), list(mal_c[i].amplitudes.values))\n mal_c.reset_matrices()\n for i in range(n_mod):\n assert mal[i].matrices.any()\n assert not mal_c[i].matrices.any()\n assert approx_equal(list(mal[i].amplitudes.values), list(mal_c[i].amplitudes.values))\n\n print('OK')\n\ndef tst_TLSMatricesAndAmplitudesList_fails():\n \"\"\"Check that exceptions are raised where expected\"\"\"\n\n n_mod = 4\n n_dst = 3\n n_atm = 2\n\n mal = TLSMatricesAndAmplitudesList(length=n_mod, n_amplitudes=n_dst)\n\n # Check indexing errors\n with raises(Exception) as e:\n mal[n_mod+1]\n assert \"index out of range of TLSMatricesAndAmplitudesList\" == str(e.value)\n\n # Tolerances\n mal.copy().reset_null_modes(0.0, 0.0) # values can be zero\n mal.copy().reset_null_modes(-1, -1) # values can be -1\n msg = \"Tolerance provided must either be positive or -1\"\n with raises(Exception) as e:\n mal.reset_null_modes(-0.1, -1)\n assert msg == str(e.value)\n with raises(Exception) as e:\n mal.reset_null_modes(-1, -0.1)\n assert msg == str(e.value)\n\n # Set some values\n for i, ma in enumerate(mal):\n ma.matrices.set(TLSMATRICES[i])\n ma.amplitudes.set(rran(n_dst))\n\n # Coordinates sets for following tests\n sites = flex.vec3_double(rran(n_dst*n_atm*3).reshape(n_dst*n_atm, 3).tolist())\n sites.reshape(flex.grid(n_dst,n_atm))\n origins = rran(n_dst*3).reshape(n_dst,3)\n\n # Compatibility of sites/origins arrays (normalise and uijs)\n # Array has swapped axes\n msg = \"Mismatch between the size of origins and first dimension of sites_carts\"\n new_sites = flex.vec3_double(rran(n_dst*n_atm*3).reshape(n_dst*n_atm, 3).tolist())\n new_sites.reshape(flex.grid(n_atm,n_dst)) # swap axes\n with raises(Exception) as e:\n mal.uijs(new_sites, origins)\n assert msg == str(e.value)\n # sites is too short/long\n msg = \"Mismatch between the size of origins and first dimension of sites_carts\"\n for n_tmp in [n_dst-1, n_dst+1]:\n new_sites = flex.vec3_double(rran(n_tmp*n_atm*3).reshape(n_tmp*n_atm, 3).tolist())\n new_sites.reshape(flex.grid(n_tmp,n_atm))\n with raises(Exception) as e:\n mal.uijs(new_sites, origins)\n assert msg == str(e.value)\n # Sites/origins compatible but not same length as amplitudes\n new_origins = rran(n_tmp*3).reshape(n_tmp, 3).tolist()\n with raises(Exception) as e:\n mal.uijs(new_sites, new_origins)\n assert \"Mismatch between the size of TLSAmplitudes and the input arrays\" == str(e.value)\n\n # Check dimension of sites_carts\n msg = \"sites_carts must be 2-dimensional array of size (n_dst, n_atm)\"\n # Make 3-d array of sites\n n_fake = 2 # length of new dimension\n new_sites = flex.vec3_double(rran(n_fake*n_dst*n_atm*3).reshape(n_fake*n_dst*n_atm, 3).tolist())\n new_sites.reshape(flex.grid(n_fake,n_atm,n_dst))\n with raises(Exception) as e:\n mal.uijs(new_sites, origins)\n assert msg == str(e.value)\n # Make 1-d array of sites\n new_sites = flex.vec3_double(rran(n_atm*3).reshape(n_atm, 3).tolist())\n new_sites.reshape(flex.grid(n_atm))\n with raises(Exception) as e:\n mal.uijs(new_sites, origins)\n assert msg == str(e.value)\n # Make other 1-d array\n new_sites = flex.vec3_double(rran(n_atm*3).reshape(n_atm, 3))\n with raises(Exception) as e:\n mal.uijs(new_sites, origins)\n assert msg == str(e.value)\n\n # Make new sites/origins for subset of ampls for use below\n t_n_dst = n_dst - 1\n new_sites = flex.vec3_double(rran(t_n_dst*n_atm*3).reshape(t_n_dst*n_atm, 3).tolist())\n new_sites.reshape(flex.grid(t_n_dst,n_atm))\n new_origins = rran(t_n_dst*3).reshape(t_n_dst,3)\n\n # Selection compatibility with sites and origins\n msg = \"Mismatch between the size of selection and the input arrays\"\n for l in [t_n_dst-1, t_n_dst+1]:\n # Selection too short\n sel = iran(n_dst, size=l, replace=False)\n with raises(Exception) as e:\n mal.uijs(new_sites, new_origins, sel.astype(numpy.uint))\n assert msg == str(e.value)\n # Invalid selection\n sel = iran(n_dst, size=t_n_dst, replace=False)\n sel[-1] = n_dst # larger than allowed\n with raises(Exception) as e:\n mal.uijs(new_sites, new_origins, sel.astype(numpy.uint))\n assert \"Selection indices out of range of TLSAmplitudes\" == str(e.value)\n\n print('OK')\n\nif __name__ == \"__main__\":\n tst_set_precision()\n tst_set_tolerance()\n tst_TLSMatrices()\n tst_TLSMatrices_counts()\n tst_TLSMatrices_fails()\n tst_TLSMatrices_uijs()\n tst_TLSAmplitudes()\n tst_TLSAmplitudes_fails()\n tst_TLSMatricesAndAmplitudes()\n tst_TLSMatricesAndAmplitudes_counts()\n tst_TLSMatricesAndAmplitudes_fails()\n tst_TLSMatricesAndAmplitudes_valid()\n tst_TLSMatricesAndAmplitudes_uijs()\n tst_TLSMatricesAndAmplitudesList()\n tst_TLSMatricesAndAmplitudesList_fails()\n", "from __future__ import absolute_import, division, print_function\nfrom six.moves import range\n# LIBTBX_SET_DISPATCHER_NAME cxi.radial_average\n# LIBTBX_PRE_DISPATCHER_INCLUDE_SH export PHENIX_GUI_ENVIRONMENT=1\n# LIBTBX_PRE_DISPATCHER_INCLUDE_SH export BOOST_ADAPTBX_FPE_DEFAULT=1\n\nimport libtbx.phil\nfrom libtbx.utils import Usage, Sorry\nimport sys\nimport os\nimport math\nimport numpy as np\n\nmaster_phil = libtbx.phil.parse(\"\"\"\n file_path = None\n .type = str\n beam_x = None\n .type = float\n beam_y = None\n .type = float\n handedness = 0\n .type = int\n xfel_target = None\n .type = str\n n_bins = 0\n .type = int\n verbose = True\n .type = bool\n output_bins = True\n .type = bool\n output_file = None\n .type = str\n plot_y_max = None\n .type = int\n\"\"\")\n# Array of handedness possibilities. Input 0 for no subpixel\n# metrology correction\n # id x/y theta x y\nhandednesses = \\\n [[False, 1, 1, 1], # 1 normal pos x y\n [False, 1, 1,-1], # 2 normal pos x neg y\n [False, 1,-1, 1], # 3 normal pos neg x y\n [False, 1,-1,-1], # 4 normal pos neg x neg y\n [False,-1, 1, 1], # 5 normal neg x y\n [False,-1, 1,-1], # 6 normal neg x neg y\n [False,-1,-1, 1], # 7 normal neg neg x y\n [False,-1,-1,-1], # 8 normal neg neg x neg y\n [True , 1, 1, 1], # 9 swapped pos x y\n [True , 1, 1,-1], # 10 swapped pos x neg y\n [True , 1,-1, 1], # 11 swapped pos neg x y\n [True , 1,-1,-1], # 12 swapped pos neg x neg y\n [True ,-1, 1, 1], # 13 swapped neg x y\n [True ,-1, 1,-1], # 14 swapped neg x neg y\n [True ,-1,-1, 1], # 15 swapped neg neg x y\n [True ,-1,-1,-1]] # 16 swapped neg neg x neg y\nh_swapped = 0\nh_theta = 1\nh_x = 2\nh_y = 3\n\ndef run (args, source_data = None) :\n from xfel import radial_average\n from scitbx.array_family import flex\n from iotbx.detectors.cspad_detector_formats import reverse_timestamp\n from iotbx.detectors.cspad_detector_formats import detector_format_version as detector_format_function\n from spotfinder.applications.xfel import cxi_phil\n from iotbx.detectors.npy import NpyImage\n import os, sys\n from iotbx.detectors.npy import NpyImage\n\n user_phil = []\n # TODO: replace this stuff with iotbx.phil.process_command_line_with_files\n # as soon as I can safely modify it\n for arg in args :\n if (not \"=\" in arg) :\n try :\n user_phil.append(libtbx.phil.parse(\"\"\"file_path=%s\"\"\" % arg))\n except ValueError as e :\n raise Sorry(\"Unrecognized argument '%s'\" % arg)\n else :\n try :\n user_phil.append(libtbx.phil.parse(arg))\n except RuntimeError as e :\n raise Sorry(\"Unrecognized argument '%s' (error: %s)\" % (arg, str(e)))\n params = master_phil.fetch(sources=user_phil).extract()\n if params.file_path is None or not os.path.isfile(params.file_path) and source_data is None:\n master_phil.show()\n raise Usage(\"file_path must be defined (either file_path=XXX, or the path alone).\")\n assert params.handedness is not None\n assert params.n_bins is not None\n assert params.verbose is not None\n assert params.output_bins is not None\n\n if source_data is None:\n from libtbx import easy_pickle\n source_data = easy_pickle.load(params.file_path)\n\n if params.output_file is None:\n logger = sys.stdout\n else:\n logger = open(params.output_file, 'w')\n logger.write(\"%s \"%params.output_file)\n\n if not \"DETECTOR_ADDRESS\" in source_data:\n # legacy format; try to guess the address\n LCLS_detector_address = 'CxiDs1-0|Cspad-0'\n if \"DISTANCE\" in source_data and source_data[\"DISTANCE\"] > 1000:\n # downstream CS-PAD detector station of CXI instrument\n LCLS_detector_address = 'CxiDsd-0|Cspad-0'\n else:\n LCLS_detector_address = source_data[\"DETECTOR_ADDRESS\"]\n timesec = reverse_timestamp( source_data[\"TIMESTAMP\"] )[0]\n version_lookup = detector_format_function(LCLS_detector_address,timesec)\n args = [\n \"distl.detector_format_version=%s\"%version_lookup,\n \"viewer.powder_arcs.show=False\",\n \"viewer.powder_arcs.code=3n9c\",\n ]\n\n horizons_phil = cxi_phil.cxi_versioned_extract(args).persist.commands\n\n img = NpyImage(params.file_path, source_data)\n img.readHeader(horizons_phil)\n img.translate_tiles(horizons_phil)\n if params.verbose:\n img.show_header()\n\n the_tiles = img.get_tile_manager(horizons_phil).effective_tiling_as_flex_int(\n reapply_peripheral_margin=False,encode_inactive_as_zeroes=True)\n\n if params.beam_x is None:\n params.beam_x = img.beamx / img.pixel_size\n if params.beam_y is None:\n params.beam_y = img.beamy / img.pixel_size\n if params.verbose:\n logger.write(\"I think the beam center is (%s,%s)\\n\"%(params.beam_x, params.beam_y))\n\n bc = (int(params.beam_x),int(params.beam_y))\n\n extent = int(math.ceil(max(distance((0,0),bc),\n distance((img.size1,0),bc),\n distance((0,img.size2),bc),\n distance((img.size1,img.size2),bc))))\n\n if params.n_bins < extent:\n params.n_bins = extent\n\n extent_in_mm = extent * img.pixel_size\n extent_two_theta = math.atan(extent_in_mm/img.distance)*180/math.pi\n\n sums = flex.double(params.n_bins) * 0\n sums_sq = flex.double(params.n_bins) * 0\n counts = flex.int(params.n_bins) * 0\n data = img.get_raw_data()\n\n if hasattr(data,\"as_double\"):\n data = data.as_double()\n\n logger.write(\"Average intensity: %9.3f\\n\"%flex.mean(data))\n\n if params.verbose:\n logger.write(\"Generating average...tile:\")\n logger.flush()\n for tile in range(len(the_tiles)//4):\n if params.verbose:\n logger.write(\" %d\"%tile)\n logger.flush()\n\n x1,y1,x2,y2 = get_tile_coords(the_tiles,tile)\n\n radial_average(data,bc,sums,sums_sq,counts,img.pixel_size,img.distance,\n (x1,y1),(x2,y2))\n\n if params.verbose:\n logger.write(\" Finishing...\\n\")\n\n # average, avoiding division by zero\n results = sums.set_selected(counts <= 0, 0)\n results /= counts.set_selected(counts <= 0, 1).as_double()\n\n # calculte standard devations\n std_devs = [math.sqrt((sums_sq[i]-sums[i]*results[i])/counts[i])\n if counts[i] > 0 else 0 for i in range(len(sums))]\n\n xvals = flex.double(len(results))\n max_twotheta = float('-inf')\n max_result = float('-inf')\n\n for i in range(len(results)):\n twotheta = i * extent_two_theta/params.n_bins\n xvals[i] = twotheta\n\n if params.output_bins and \"%.3f\"%results[i] != \"nan\":\n #logger.write(\"%9.3f %9.3f\\n\"% (twotheta,results[i])) #.xy format for Rex.cell.\n logger.write(\"%9.3f %9.3f %9.3f\\n\"%(twotheta,results[i],std_devs[i])) #.xye format for GSASII\n #logger.write(\"%.3f %.3f %.3f\\n\"%(twotheta,results[i],ds[i])) # include calculated d spacings\n if results[i] > max_result:\n max_twotheta = twotheta\n max_result = results[i]\n\n logger.write(\"Maximum 2theta for %s, TS %s: %f, value: %f\\n\"%(params.file_path, source_data['TIMESTAMP'], max_twotheta, max_result))\n\n if params.verbose:\n from pylab import scatter, show, xlabel, ylabel, ylim\n scatter(xvals,results)\n xlabel(\"2 theta\")\n ylabel(\"Avg ADUs\")\n if params.plot_y_max is not None:\n ylim(0, params.plot_y_max)\n show()\n\n return xvals, results\n\ndef get_tile_id(tiles, x, y):\n for tile in range(len(tiles)//4):\n x1,y1,x2,y2 = get_tile_coords(tiles, tile)\n if x <= x2 and x >= x1 and y <= y2 and y >= y1:\n return tile\n return -1\n\ndef get_tile_center(tiles, tile):\n x1,y1,x2,y2 = get_tile_coords(tiles, tile)\n\n cx = x1 + (distance((x2,y1),(x1,y1))/2)\n cy = y1 + (distance((x1,y2),(x1,y1))/2)\n return (cx, cy)\n\ndef distance (a,b): return math.sqrt((math.pow(b[0]-a[0],2)+math.pow(b[1]-a[1],2)))\n\ndef get_tile_coords(tiles, tile):\n \"\"\" returns x1, y1, x2, y2 \"\"\"\n y1 = tiles[tile*4 + 0]\n x1 = tiles[tile*4 + 1]\n y2 = tiles[tile*4 + 2]\n x2 = tiles[tile*4 + 3]\n return (x1,y1,x2,y2)\n\nfrom scitbx.matrix import col, sqr\n\ndef apply_sub_pixel_metrology(tile, x, y, tcx, tcy, phil,handedness=0):\n handedness -= 1\n if handedness < 0:\n return (x,y)\n\n if tile < 0: return None\n\n r = col((x, y)) # point of interest\n Ti = col((tcx,tcy)) # center of tile i\n\n # sub pixel translation/rotation\n if handednesses[handedness][h_swapped]:\n ti = col((phil.integration.subpixel_joint_model.translations[(tile*2)+1] * handednesses[handedness][h_y],\n phil.integration.subpixel_joint_model.translations[tile*2] * handednesses[handedness][h_x]))\n else:\n ti = col((phil.integration.subpixel_joint_model.translations[tile*2] * handednesses[handedness][h_x],\n phil.integration.subpixel_joint_model.translations[(tile*2)+1] * handednesses[handedness][h_y]))\n theta = phil.integration.subpixel_joint_model.rotations[tile] * (math.pi/180) * handednesses[handedness][h_theta]\n\n Ri = sqr((math.cos(theta),-math.sin(theta),math.sin(theta),math.cos(theta)))\n\n # apply sub-pixel translation to point of interest and tile center\n rp = r + ti # p: prime\n Tip = Ti + ti\n\n result = (Ri*(rp-Tip))+Tip\n\n return (result[0], result[1])\n\n# Debugging jiffy function to show a few tiles and verify metrology visually\ndef show_tiles(the_tiles, img, phil, bc, handedness=0):\n import numpy as np\n import matplotlib.pyplot as plt\n\n #tiles_list = (0, 1)\n #tiles_list = (2, 18)\n #tiles_list = (48, 49)\n tiles_list = (35, 48, 49, 51)\n #tiles_list = range(64)\n arraysx = np.array([])\n arraysy = np.array([])\n arraysz = np.array([])\n for tile in tiles_list:\n x1,y1,x2,y2 = get_tile_coords(the_tiles, tile)\n w = x2-x1\n h = y2-y1\n cx,cy = get_tile_center(the_tiles, tile)\n\n print(\"tile %d, x1 %d, y1 %d, x2 %d, y2 %d, w %d, h %d, cx %s, cy %s\"%(tile, x1, y1, x2, y2, w, h, cx, cy))\n\n x = np.array([0]*(w*h))\n y = np.array([0]*(w*h))\n z = np.array([0]*(w*h))\n\n for j in range(h):\n for i in range(w):\n t_id = get_tile_id(the_tiles,x1+i,y1+j)\n if tile != t_id:\n print(\"bug! tile: %d, t_id %d, x %d, y %d\"%(tile,t_id,x1+i,y1+j))\n return\n xt, yt = apply_sub_pixel_metrology(tile,x1+i,y1+j,cx,cy,phil,handedness)\n x[(j*w)+i] = xt\n y[(j*w)+i] = yt\n c = img.get_pixel_intensity((j+y1,i+x1))\n z[(j*w)+i] = c\n\n arraysx = np.concatenate([arraysx, x])\n arraysy = np.concatenate([arraysy, y])\n arraysz = np.concatenate([arraysz, z])\n\n arraysz -= min(arraysz)\n arraysz /= max(arraysz)\n\n\n plt.scatter(arraysx, arraysy, c=arraysz, s=1, marker='s', cmap=\"gray_r\", lw=0)\n plt.gca().invert_yaxis()\n circ = plt.Circle((bc[0], bc[1]), radius=377, facecolor='none', edgecolor='red')\n plt.gca().add_patch(circ)\n circ = plt.Circle((bc[0], bc[1]), radius=365, facecolor='none', edgecolor='red')\n plt.gca().add_patch(circ)\n\n plt.title(\"Handedness: %s\"%(handedness))\n\n plt.show()\n return\n\nif (__name__ == \"__main__\") :\n run(sys.argv[1:])\n" ]
[ [ "numpy.equal", "numpy.array", "matplotlib.pyplot.ion", "numpy.savetxt", "numpy.zeros", "numpy.copy", "numpy.genfromtxt", "numpy.seterr", "numpy.nonzero", "numpy.column_stack" ], [ "numpy.random.seed", "numpy.array", "numpy.mean" ], [ "numpy.concatenate", "numpy.array", "matplotlib.pyplot.title", "matplotlib.pyplot.show", "matplotlib.pyplot.Circle", "matplotlib.pyplot.scatter", "matplotlib.pyplot.gca" ] ]
Neo-X/R_multiworld
[ "839513a48ddf2f5ae2eadc43435ac6981ddea1f4" ]
[ "multiworld/envs/mujoco/sawyer_xyz/pickPlace/sawyer_coffee.py" ]
[ "from collections import OrderedDict\nimport numpy as np\nfrom gym.spaces import Box, Dict\n\nfrom multiworld.envs.env_util import get_stat_in_paths, \\\n\tcreate_stats_ordered_dict, get_asset_full_path\nfrom multiworld.core.multitask_env import MultitaskEnv\nfrom multiworld.envs.mujoco.sawyer_xyz.push.sawyer_push import SawyerPushEnv\nfrom pyquaternion import Quaternion\n\ndef zangle_to_quat(zangle):\n\t\"\"\"\n\t:param zangle in rad\n\t:return: quaternion\n\t\"\"\"\n\t#return (Quaternion(axis=[0,1,0], angle=np.pi) * Quaternion(axis=[0, 0, -1], angle= zangle)).elements\n\treturn (Quaternion(axis=[0,0,1], angle=np.pi) * Quaternion(axis=[-1, 0, 0], angle= zangle)).elements\n\t#return (Quaternion(axis=[1,0,0], angle=np.pi) * Quaternion(axis=[0, -1, 0], angle= zangle)).elements\n\t#return (Quaternion(axis=[1,0,0], angle=np.pi) * Quaternion(axis=[-1, 0, 0], angle= zangle)).elements #fail\n\t#return (Quaternion(axis=[0,0,1], angle=np.pi) * Quaternion(axis=[0, -1, 0], angle= zangle)).elements\nclass SawyerCoffeeEnv( SawyerPushEnv):\n\tdef __init__(\n\t\t\tself,\n\t\t\ttasks = [{'goal': np.array([0, 1.0, 0.05]), 'height': 0.06, 'obj_init_pos':np.array([0, 0.6, 0.04])}] , \n\t\t\thand_type = 'weiss_v2',\n\t\t\trewMode = 'orig',\n\t\t\t**kwargs\n\t):\n\t\t \n\t\tself.quick_init(locals())\n\t\tself.hand_type = hand_type \n\t\tSawyerPushEnv.__init__(\n\t\t\tself,\n\t\t\ttasks = tasks,\n\t\t\thand_type = hand_type,\n\t\t\t**kwargs\n\t\t)\n\t\t#self.hand_init_pos = [-0.00434313 , 0.76608467 , 0.26081535]\n\t\tself.demo = False\n\t\tself.max_path_length = 120\n\t\tself.camera_name = 'angled_cam'\n\t\tself.info_logKeys = ['placingDist' , 'pickRew' , 'reachRew' , 'placeRew']\n\t\tself.rewMode = rewMode\n\t \n\t\tself.action_space = Box(\n\t\t\tnp.array([-1, -1, -1, -1]),\n\t\t\tnp.array([1, 1, 1, 1]),\n\t\t)\n\n\t@property\n\tdef model_name(self):\n\t \n\t\t#return get_asset_full_path('sawyer_xyz/sawyer_pickPlace.xml')\n\t\t#self.reset_mocap_quat = zangle_to_quat(np.pi/2) #this is the reset_mocap_quat for wsg grippers\n\t\n\t\t#self.reset_mocap_quat = zangle_to_quat(-np.pi/2)\n\n\t\tinit_quat = [1,0,0,1]\n\t \n\t\tself.reset_mocap_quat = (Quaternion(axis= [1,0,0] , angle = -np.pi/2)*Quaternion(init_quat)).elements\n\t\treturn get_asset_full_path('sawyer_xyz/sawyer_wsg_coffee.xml')\n\n\tdef _reset_hand(self):\n\t\tfor _ in range(10):\n\t\t\tself.data.set_mocap_pos('mocap', self.hand_init_pos)\n\t\t\tself.data.set_mocap_quat('mocap', self.reset_mocap_quat)\n\t\t\tself.do_simulation([-1,1], self.frame_skip)\n\t\n\tdef step(self, action):\n\t\t\n\t\t#action = [0,0,0,1]\n\t\tif self.demo:\n\t\t\tif self.curr_path_length <=20:\n\t\t\t\taction = [0 , 1, -1, -1]\n\n\t\t\telif self.curr_path_length <=40:\n\t\t\t\taction = [0,1,1,1]\n\n\t\t\telif self.curr_path_length <=70:\n\t\t\t\taction = [0,0.9,-0.25,1]\n\n\t\t\telif self.curr_path_length<=100:\n\t\t\t\taction = [0,-1 ,1 , -1]\n\n\t\t\tnoise = 5*1e-1*np.random.uniform(-1,1 , size= 3)\n\t\t\tnoise_4d = np.concatenate([noise , [0]])\n\t\t\taction = np.array(action) + noise_4d\n\t\t\t#object position after picking and placing coffe : [-0.00434313 0.76608467 0.26081535]\n\n\t\tself.set_xyz_action(action[:3])\n\t\tself.do_simulation([ action[-1], -action[-1]])\n \n\t\tself._set_goal_marker(self._state_goal)\n\t\tob = self._get_obs()\n\t\treward , reachReward , pickReward , placeReward , placingDist = self.compute_reward(action, ob)\n\t\tself.curr_path_length +=1\n\t\tif self.curr_path_length == self.max_path_length:\n\t\t\tdone = True\n\t\telse:\n\t\t\tdone = False\n\t\treturn ob, reward, done, OrderedDict({ 'epRew' : reward , 'reachRew': reachReward , 'pickRew': pickReward , 'placeRew': placeReward , 'placingDist': placingDist})\n\t\n\n\tdef change_task(self, task):\n\n\t\ttask = {'goal': np.array([0, 1.0, 0.05]), 'height': 0.06, 'obj_init_pos':np.array([0, 0.6, 0.04])}\n\t\tself.grasp = False\n\t\tself.pickCompleted = False\n\n\t\tif len(task['goal']) == 3:\n\t\t\tself._state_goal = task['goal']\n\t\telse:\n\t\t\tself._state_goal = np.concatenate([task['goal'] , [0.02]])\n\t\tself._set_goal_marker(self._state_goal)\n\n\t\tif len(task['obj_init_pos']) == 3:\n\t\t\tself.obj_init_pos = task['obj_init_pos']\n\t\telse:\n\t\t\tself.obj_init_pos = np.concatenate([task['obj_init_pos'] , [0.02]])\n\t\t\n\t\t#self.maxPlacingDist = np.linalg.norm(np.array([self.obj_init_pos[0], self.obj_init_pos[1], self.heightTarget]) - np.array(self._state_goal)) + self.heightTarget\n\n\n\n\tdef render(self, mode = 'human'):\n\n\t\tif mode == 'human':\n\t\t\tim_size = 500 ; norm = 1.0\n\t\t\tself.set_goal_visibility(visible = True)\n\t\telif mode == 'nn':\n\t\t\tim_size = self.image_dim ; norm = 255.0\n\t\telif mode == 'vis_nn':\n\t\t\tim_size = self.image_dim ; norm = 1.0\n\t\telse:\n\t\t\traise AssertionError('Mode must be human, nn , or vis_nn')\n\t \n\t\tif self.camera_name == 'angled_cam':\n\t\t \n\t\t\timage = self.get_image(width= im_size , height = im_size , camera_name = 'angled_cam').transpose()/norm\n\t\t\timage = image.reshape((3, im_size, im_size))\n\t\t\timage = np.rot90(image, axes = (-2,-1))\n\t\t\tfinal_image = np.transpose(image , [1,2,0])\n\t\t\tif 'nn' in mode:\n\t\t\t\tfinal_image = final_image[:48 ,10 : 74,:]\n\t\t\t# elif 'human' in mode:\n\t\t\t# final_image = final_image[:285, 60: 440,:]\n\n\t\tif self.hide_goal:\n\t\t self.set_goal_visibility(visible = False)\n\t\treturn final_image\n\n\tdef compute_reward(self, actions, obs):\n\t\t\t\t\t\n\t\tif isinstance(obs, dict):\n\t\t \n\t\t\tobs = obs['state_observation']\n\n\t\tobjPos = obs[3:6]\n\t\trightFinger, leftFinger = self.get_site_pos('rightEndEffector'), self.get_site_pos('leftEndEffector')\n\t\tfingerCOM = (rightFinger + leftFinger)/2 \n\t \n\t\tplacingGoal = self._state_goal\n\t\tgraspDist = np.linalg.norm(objPos - fingerCOM)\n\t\tplacingDist = np.linalg.norm(objPos - placingGoal)\n\n\t\tdef reachReward():\n\n\t\t\tgraspRew = -graspDist\n\t\t\tif np.linalg.norm(objPos[:2] - fingerCOM[:2]) < 0.02 and fingerCOM[2]<0.05:\n\t\t\t \n\t\t\t\tself.grasp = True\n\t\t\treturn graspRew \n\n\t\tdef pickRew():\n\n\t\t\tif self.pickCompleted:\n\t\t\t\treturn 10\n\t\t\telif self.grasp:\n\t\t\t\tif abs(0.07 - objPos[2])<0.1:\n\t\t\t\t\tself.pickCompleted = True\n\n\t\t\t\treturn 1/(abs(0.07 - objPos[2])+1e-1)\n\t\t\telse:\n\t\t\t\treturn 0\n\n\t\tdef placeRew():\n\n\t\t\tif self.pickCompleted:\n\t\t\t\treturn np.exp(-placingDist)\n\t\t\telse:\n\t\t\t\treturn 0\n\n\n\t\treachReward = reachReward()\n\t\tpickReward = pickRew()\n\t\tplaceReward = placeRew()\n\t\treward = reachReward + pickReward + placeReward\n\t\treturn [reward , reachReward , pickReward , placeReward, placingDist]\n\n\tdef log_diagnostics(self, paths = None, prefix = '', logger = None):\n\n\t\tfrom rllab.misc import logger\n\t\t#if type(paths[0]) == dict:\n\t\t\t\n\t\t\t# if isinstance(paths[0]['env_infos'][0] , OrderedDict):\n\t\t\t# #For SAC\n\t\t\t# for key in self.info_logKeys:\n\t\t\t# nested_list = [[i[key] for i in paths[j]['env_infos']] for j in range(len(paths))]\n\t\t\t# logger.record_tabular(prefix + 'max_'+key, np.mean([max(_list) for _list in nested_list]) )\n\t\t\t# logger.record_tabular(prefix + 'last_'+key, np.mean([_list[-1] for _list in nested_list]) )\n\n\n\n\t\t\t\n\t\t#For TRPO\n\t\tfor key in self.info_logKeys:\n\t\t\t#logger.record_tabular(prefix+ 'sum_'+key, np.mean([sum(path['env_infos'][key]) for path in paths]) )\n\t\t\tlogger.record_tabular(prefix+'max_'+key, np.mean([max(path['env_infos'][key]) for path in paths]) )\n\t\t\t#logger.record_tabular(prefix+'min_'+key, np.mean([min(path['env_infos'][key]) for path in paths]) )\n\t\t\tlogger.record_tabular(prefix + 'last_'+key, np.mean([path['env_infos'][key][-1] for path in paths]) )\n\t\t\tlogger.record_tabular(prefix + 'mean_'+key, np.mean([np.mean(path['env_infos'][key]) for path in paths]) )\n\n\n\n\n\t " ]
[ [ "numpy.concatenate", "numpy.rot90", "numpy.array", "numpy.linalg.norm", "numpy.exp", "numpy.mean", "numpy.random.uniform", "numpy.transpose" ] ]
MarcusTL12/School
[ "f7302f2d390e99ad9d06004e15da032c05ec59e7" ]
[ "18Host/TMA4120/latex/PyplotTesting/Scripts/subfactorial.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef subf(n):\n\tif n <= 1:\n\t\treturn 0\n\telif n == 2:\n\t\treturn 1\n\t\n\treturn (n - 1) * (subf(n - 1) + subf(n - 2))\n\n\nx = np.arange(1, 5, 1)\n\ny = np.vectorize(subf)(x)\n\nplt.plot(x, y)\n\nplt.show()\n\n" ]
[ [ "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "numpy.arange", "numpy.vectorize" ] ]
NishthaShukla/eda
[ "4190604dcb24c2f9a03a7d0ad59be30aca18f05a" ]
[ "code.py" ]
[ "# --------------\n# Code starts here\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import Imputer\nfrom sklearn.preprocessing import LabelEncoder\nimport numpy as np\nfrom scipy.stats import skew\n#### Data 1\n# Load the data\n\ndf = pd.read_csv(path)\n\n# Overview of the data\ndf.info()\n\ndf.describe()\n\n# Histogram showing distribution of car prices\ndf['price'].plot.hist(bins=12,alpha =0.5)\n\n# Countplot of the make column\ndf['make'].value_counts().plot(kind='bar')\n\n\n# Jointplot showing relationship between 'horsepower' and 'price' of the car\ndf.plot.scatter(x='horsepower',y='price',c='blue')\n\n# Correlation heat map\nf = plt.figure(figsize=(19, 15))\n\nplt.matshow(df.corr(), fignum=f.number)\n\nplt.xticks(range(df.shape[1]), df.columns, fontsize=14, rotation=45)\n\nplt.yticks(range(df.shape[1]), df.columns, fontsize=14)\n\ncb = plt.colorbar()\n\ncb.ax.tick_params(labelsize=14)\n\nplt.title('Correlation Matrix', fontsize=16);\n\n# boxplot that shows the variability of each 'body-style' with respect to the 'price'\ndf.boxplot(column=['price'],by=['body-style'])\n\n#### Data 2\n\n# Load the data\ndf2 = pd.read_csv(path2)\n\n# Impute missing values with mean\ndf2 = df2.replace(\"?\",\"NaN\")\n\nmean_imputer = Imputer(missing_values='NaN',strategy='mean',axis=0)\n\ndf2['normalized-losses'] = mean_imputer.fit_transform(df2[['normalized-losses']])\n\ndf2['horsepower'] = mean_imputer.fit_transform(df2[['horsepower']])\n# Skewness of numeric features\n\nnum_cols = df2._get_numeric_data().columns\n\nfor num_col in num_cols:\n if skew(df2[num_col].values)>1:\n print(num_col)\n df2[num_col]= np.sqrt(df2[num_col])\n\nprint(df2.head())\n\ncat_cols = list(set(df2.columns)- set(num_cols))\n\n# Label encode \nlabel_encoder = LabelEncoder()\n\nfor cat_col in cat_cols:\n df2[cat_col]= label_encoder.fit_transform(df2[cat_col])\n\ndf2['area']=df2['height']*df2['width']\n\nprint(df2.head())\n\n\n# Code ends here\n\n\n" ]
[ [ "matplotlib.pyplot.colorbar", "sklearn.preprocessing.LabelEncoder", "matplotlib.pyplot.title", "matplotlib.pyplot.figure", "scipy.stats.skew", "numpy.sqrt", "pandas.read_csv", "sklearn.preprocessing.Imputer" ] ]
matheusMoreno/BentoML
[ "4c139142fae486ba1ccf6b24e89505c030e3df3f", "4c139142fae486ba1ccf6b24e89505c030e3df3f", "4c139142fae486ba1ccf6b24e89505c030e3df3f" ]
[ "bentoml/_internal/frameworks/tensorflow_v2.py", "bentoml/_internal/frameworks/detectron.py", "tests/integration/frameworks/test_catboost_impl.py" ]
[ "import os\nimport re\nimport uuid\nimport typing as t\nimport logging\nimport pathlib\nimport functools\nfrom typing import TYPE_CHECKING\nfrom distutils.dir_util import copy_tree\n\nfrom simple_di import inject\nfrom simple_di import Provide\n\nimport bentoml\nfrom bentoml import Tag\nfrom bentoml.exceptions import BentoMLException\nfrom bentoml.exceptions import MissingDependencyException\n\nfrom ..types import LazyType\nfrom ..runner.utils import Params\nfrom ..utils.tensorflow import get_tf_version\nfrom ..utils.tensorflow import is_gpu_available\nfrom ..utils.tensorflow import hook_loaded_model\nfrom .common.model_runner import BaseModelRunner\nfrom ..configuration.containers import BentoMLContainer\n\nlogger = logging.getLogger(__name__)\n\ntry:\n import tensorflow as tf # type: ignore\nexcept ImportError: # pragma: no cover\n raise MissingDependencyException(\n \"\"\"\\\n `tensorflow` is required in order to use `bentoml.tensorflow`.\n Instruction: `pip install tensorflow`\n \"\"\"\n )\n\ntry:\n import tensorflow_hub as hub # type: ignore\n from tensorflow_hub import resolve # type: ignore\n from tensorflow_hub import native_module # type: ignore\nexcept ImportError: # pragma: no cover\n logger.warning(\n \"\"\"\\\n If you want to use `bentoml.tensorflow.import_from_tfhub(),\n make sure to `pip install --upgrade tensorflow_hub` before using.\n \"\"\"\n )\n hub = None\n\n\ntry:\n import importlib.metadata as importlib_metadata\nexcept ImportError:\n import importlib_metadata\n\n\nif TYPE_CHECKING:\n from tensorflow_hub import Module as HubModule # type: ignore\n from tensorflow_hub import KerasLayer # type: ignore\n\n from .. import external_typing as ext\n from ..types import PathType\n from ..models import ModelStore\n from ..external_typing import tensorflow as tf_ext\n\n TFArgType = t.Union[t.List[t.Union[int, float]], ext.NpNDArray, tf_ext.Tensor]\n\nMODULE_NAME = \"bentoml.tensorflow_v2\"\n\n\ndef _clean_name(name: str) -> str: # pragma: no cover\n if name.startswith((\"http://\", \"https://\")):\n name = name.split(\"/\", maxsplit=3)[-1]\n else:\n name = name.split(\"/\")[-1]\n return re.sub(r\"\\W|^(?=\\d)-\", \"_\", name)\n\n\n@inject\ndef load(\n bento_tag: t.Union[str, Tag],\n tags: t.Optional[t.List[str]] = None,\n options: t.Optional[\"tf_ext.SaveOptions\"] = None,\n load_as_hub_module: t.Optional[bool] = None,\n model_store: \"ModelStore\" = Provide[BentoMLContainer.model_store],\n) -> t.Union[\"tf_ext.AutoTrackable\", \"tf_ext.Module\", \"HubModule\", \"KerasLayer\"]:\n \"\"\"\n Load a model from BentoML local modelstore with given name.\n\n Args:\n bento_tag (:code:`Union[str, Tag]`):\n Tag of a saved model in BentoML local modelstore.\n tags (:code:`str`, `optional`, defaults to `None`):\n A set of strings specifying the graph variant to use, if loading from a v1 module.\n options (:code:`tensorflow.saved_model.SaveOptions`, `optional`, default to :code:`None`):\n :code:`tensorflow.saved_model.LoadOptions` object that specifies options for loading. This\n argument can only be used from TensorFlow 2.3 onwards.\n load_as_hub_module (`bool`, `optional`, default to :code:`True`):\n Load the given weight that is saved from tfhub as either `hub.KerasLayer` or `hub.Module`.\n The latter only applies for TF1.\n model_store (:mod:`~bentoml._internal.models.store.ModelStore`, default to :mod:`BentoMLContainer.model_store`):\n BentoML modelstore, provided by DI Container.\n\n Returns:\n :obj:`SavedModel`: an instance of :obj:`SavedModel` format from BentoML modelstore.\n\n Examples:\n\n .. code-block:: python\n\n import bentoml\n\n # load a model back into memory\n model = bentoml.tensorflow.load(\"my_tensorflow_model\")\n\n \"\"\" # noqa: LN001\n model = model_store.get(bento_tag)\n if model.info.module not in (MODULE_NAME, __name__):\n raise BentoMLException(\n f\"Model {bento_tag} was saved with module {model.info.module}, failed loading with {MODULE_NAME}.\"\n )\n if model.info.context[\"import_from_tfhub\"]:\n assert load_as_hub_module is not None, (\n \"You have to specified `load_as_hub_module=True | False`\"\n \" to load a `tensorflow_hub` module. If True is chosen,\"\n \" then BentoML will return either an instance of `hub.KerasLayer`\"\n \" or `hub.Module` depending on your TF version. For most usecase,\"\n \" we recommend to keep `load_as_hub_module=True`. If you wish to extend\"\n \" the functionalities of the given model, set `load_as_hub_module=False`\"\n \" will return a SavedModel object.\"\n )\n\n if hub is None:\n raise MissingDependencyException(\n \"\"\"\\\n `tensorflow_hub` does not exists.\n Make sure to `pip install --upgrade tensorflow_hub` before using.\n \"\"\"\n )\n\n module_path = model.path_of(model.info.options[\"local_path\"])\n if load_as_hub_module:\n return (\n hub.Module(module_path)\n if get_tf_version().startswith(\"1\")\n else hub.KerasLayer(module_path)\n )\n # In case users want to load as a SavedModel file object.\n # https://github.com/tensorflow/hub/blob/master/tensorflow_hub/module_v2.py#L93\n is_hub_module_v1: bool = tf.io.gfile.exists( # type: ignore\n native_module.get_module_proto_path(module_path)\n )\n if tags is None and is_hub_module_v1:\n tags = []\n if options is not None:\n if not LazyType(\n \"tensorflow.python.saved_model.save_options.SaveOptions\"\n ).isinstance(options):\n raise BentoMLException(\n f\"`options` has to be of type `tf.saved_model.SaveOptions`, got {type(options)} instead.\"\n )\n if not hasattr(getattr(tf, \"saved_model\", None), \"LoadOptions\"):\n raise NotImplementedError(\n \"options are not supported for TF < 2.3.x,\"\n f\" Current version: {get_tf_version()}\"\n )\n tf_model: \"tf_ext.AutoTrackable\" = tf.compat.v1.saved_model.load_v2( # type: ignore\n module_path,\n tags=tags,\n options=options, # type: ignore\n )\n else:\n tf_model: \"tf_ext.AutoTrackable\" = tf.compat.v1.saved_model.load_v2( # type: ignore\n module_path,\n tags=tags,\n )\n tf_model._is_hub_module_v1 = (\n is_hub_module_v1 # pylint: disable=protected-access # noqa\n )\n return tf_model\n else:\n tf_model: \"tf_ext.AutoTrackable\" = tf.compat.v1.saved_model.load_v2(model.path) # type: ignore\n return hook_loaded_model(tf_model, MODULE_NAME)\n\n\n@inject\ndef import_from_tfhub(\n identifier: t.Union[str, \"HubModule\", \"KerasLayer\"],\n name: t.Optional[str] = None,\n labels: t.Optional[t.Dict[str, str]] = None,\n custom_objects: t.Optional[t.Dict[str, t.Any]] = None,\n metadata: t.Optional[t.Dict[str, t.Any]] = None,\n model_store: \"ModelStore\" = Provide[BentoMLContainer.model_store],\n) -> Tag:\n \"\"\"\n Import a model from `Tensorflow Hub <https://tfhub.dev/>`_ to BentoML modelstore.\n\n Args:\n identifier (:code:`Union[str, tensorflow_hub.Module, tensorflow_hub.KerasLayer]`): Identifier accepts\n two type of inputs:\n - if `type` of :code:`identifier` either of type :code:`tensorflow_hub.Module` (**legacy** `tensorflow_hub`) or :code:`tensorflow_hub.KerasLayer` (`tensorflow_hub`), then we will save the given model to a :code:`SavedModel` format.\n - if `type` of :code:`identifier` is a :obj:`str`, we assume that this is the URI retrieved from Tensorflow Hub. We then clean the given URI, and get a local copy of a given model to BentoML modelstore. name (:code:`str`, `optional`, defaults to `None`): An optional name for the model. If :code:`identifier` is a :obj:`str`, then name can be autogenerated from the given URI.\n name (:code:`str`, `optional`, default to `None`):\n Optional name for the saved model. If None, then name will be generated from :code:`identifier`.\n labels (:code:`Dict[str, str]`, `optional`, default to :code:`None`):\n user-defined labels for managing models, e.g. team=nlp, stage=dev\n custom_objects (:code:`Dict[str, Any]]`, `optional`, default to :code:`None`):\n user-defined additional python objects to be saved alongside the model,\n e.g. a tokenizer instance, preprocessor function, model configuration json\n metadata (:code:`Dict[str, Any]`, `optional`, default to :code:`None`):\n Custom metadata for given model.\n model_store (:mod:`~bentoml._internal.models.store.ModelStore`, default to :mod:`BentoMLContainer.model_store`):\n BentoML modelstore, provided by DI Container.\n\n Returns:\n :obj:`~bentoml.Tag`: A :obj:`~bentoml.Tag` object that can be used to retrieve the model with :func:`bentoml.tensorflow.load`:\n\n Example for importing a model from Tensorflow Hub:\n\n .. code-block:: python\n\n import tensorflow_text as text # noqa # pylint: disable\n import bentoml\n\n tag = bentoml.tensorflow.import_from_tfhub(\"https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3\")\n\n # load model back with `load`:\n model = bentoml.tensorflow.load(tag, load_as_hub_module=True)\n\n\n Example for importing a custom Tensorflow Hub model:\n\n .. code-block:: python\n\n import tensorflow as tf\n import tensorflow_hub as hub\n import bentoml\n\n def _plus_one_model_tf2():\n obj = tf.train.Checkpoint()\n\n @tf.function(input_signature=[tf.TensorSpec(None, dtype=tf.float32)])\n def plus_one(x):\n return x + 1\n\n obj.__call__ = plus_one\n return obj\n\n # then save the given model to BentoML modelstore:\n model = _plus_one_model_tf2()\n tag = bentoml.tensorflow.import_from_tfhub(model)\n \"\"\" # noqa\n if hub is None:\n raise MissingDependencyException(\n \"\"\"\\\n `tensorflow_hub` does not exists.\n Make sure to `pip install --upgrade tensorflow_hub` before using.\n \"\"\"\n )\n context: t.Dict[str, t.Any] = {\n \"framework_name\": \"tensorflow\",\n \"pip_dependencies\": [\n f\"tensorflow=={get_tf_version()}\",\n f\"tensorflow_hub=={importlib_metadata.version('tensorflow_hub')}\",\n ],\n \"import_from_tfhub\": True,\n }\n if name is None:\n if isinstance(identifier, str):\n name = _clean_name(identifier)\n else:\n name = f\"{identifier.__class__.__name__}_{uuid.uuid4().hex[:5].upper()}\"\n\n with bentoml.models.create(\n name,\n module=MODULE_NAME,\n options=None,\n context=context,\n metadata=metadata,\n labels=labels,\n custom_objects=custom_objects,\n ) as _model:\n if isinstance(identifier, str):\n current_cache_dir = os.environ.get(\"TFHUB_CACHE_DIR\")\n os.environ[\"TFHUB_CACHE_DIR\"] = _model.path\n fpath: str = resolve(identifier)\n folder = fpath.split(\"/\")[-1]\n _model.info.options = {\"model\": identifier, \"local_path\": folder}\n if current_cache_dir is not None:\n os.environ[\"TFHUB_CACHE_DIR\"] = current_cache_dir\n else:\n if hasattr(identifier, \"export\"):\n # hub.Module.export()\n with tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph()) as sess: # type: ignore\n sess.run(tf.compat.v1.global_variables_initializer()) # type: ignore\n identifier.export(_model.path, sess) # type: ignore\n else:\n tf.saved_model.save(identifier, _model.path)\n _model.info.options = {\n \"model\": identifier.__class__.__name__,\n \"local_path\": \".\",\n }\n\n return _model.tag\n\n\n@inject\ndef save(\n name: str,\n model: t.Union[\"PathType\", \"tf_ext.KerasModel\", \"tf_ext.Module\"],\n *,\n signatures: t.Optional[\"tf_ext.ConcreteFunction\"] = None,\n options: t.Optional[\"tf_ext.SaveOptions\"] = None,\n labels: t.Optional[t.Dict[str, str]] = None,\n custom_objects: t.Optional[t.Dict[str, t.Any]] = None,\n metadata: t.Optional[t.Dict[str, t.Any]] = None,\n model_store: \"ModelStore\" = Provide[BentoMLContainer.model_store],\n) -> Tag:\n \"\"\"\n Save a model instance to BentoML modelstore.\n\n Args:\n name (:code:`str`):\n Name for given model instance. This should pass Python identifier check.\n model (:code:`Union[keras.Model, tf.Module, path-like objects]`):\n Instance of model to be saved\n labels (:code:`Dict[str, str]`, `optional`, default to :code:`None`):\n user-defined labels for managing models, e.g. team=nlp, stage=dev\n custom_objects (:code:`Dict[str, Any]]`, `optional`, default to :code:`None`):\n user-defined additional python objects to be saved alongside the model,\n e.g. a tokenizer instance, preprocessor function, model configuration json\n metadata (:code:`Dict[str, Any]`, `optional`, default to :code:`None`):\n Custom metadata for given model.\n model_store (:mod:`~bentoml._internal.models.store.ModelStore`, default to :mod:`BentoMLContainer.model_store`):\n BentoML modelstore, provided by DI Container.\n signatures (:code:`Union[Callable[..., Any], dict]`, `optional`, default to :code:`None`):\n Refers to `Signatures explanation <https://www.tensorflow.org/api_docs/python/tf/saved_model/save>`_\n from Tensorflow documentation for more information.\n options (`tf.saved_model.SaveOptions`, `optional`, default to :code:`None`):\n :obj:`tf.saved_model.SaveOptions` object that specifies options for saving.\n\n Raises:\n ValueError: If :obj:`obj` is not trackable.\n\n Returns:\n :obj:`~bentoml.Tag`: A :obj:`tag` with a format `name:version` where `name` is the user-defined model's name, and a generated `version` by BentoML.\n\n Examples:\n\n .. code-block:: python\n\n import tensorflow as tf\n import numpy as np\n import bentoml\n\n class NativeModel(tf.Module):\n def __init__(self):\n super().__init__()\n self.weights = np.asfarray([[1.0], [1.0], [1.0], [1.0], [1.0]])\n self.dense = lambda inputs: tf.matmul(inputs, self.weights)\n\n @tf.function(\n input_signature=[tf.TensorSpec(shape=[1, 5], dtype=tf.float64, name=\"inputs\")]\n )\n def __call__(self, inputs):\n return self.dense(inputs)\n\n # then save the given model to BentoML modelstore:\n model = NativeModel()\n tag = bentoml.tensorflow.save(\"native_toy\", model)\n\n .. note::\n\n :code:`bentoml.tensorflow.save` API also support saving `RaggedTensor <https://www.tensorflow.org/guide/ragged_tensor>`_ model and Keras model. If you choose to save a Keras model\n with :code:`bentoml.tensorflow.save`, then the model will be saved under a :obj:`SavedModel` format instead of :obj:`.h5`.\n\n \"\"\" # noqa\n context: t.Dict[str, t.Any] = {\n \"framework_name\": \"tensorflow\",\n \"pip_dependencies\": [f\"tensorflow=={get_tf_version()}\"],\n \"import_from_tfhub\": False,\n }\n with bentoml.models.create(\n name,\n module=MODULE_NAME,\n options=None,\n context=context,\n labels=labels,\n custom_objects=custom_objects,\n metadata=metadata,\n ) as _model:\n\n if isinstance(model, (str, bytes, os.PathLike, pathlib.Path)): # type: ignore[reportUnknownMemberType]\n assert os.path.isdir(model)\n copy_tree(str(model), _model.path)\n else:\n if options:\n logger.warning(\n f\"Parameter 'options: {str(options)}' is ignored when \"\n f\"using tensorflow {get_tf_version()}\"\n )\n tf.saved_model.save(\n model, _model.path, signatures=signatures, options=options\n )\n\n return _model.tag\n\n\nclass _TensorflowRunner(BaseModelRunner):\n def __init__(\n self,\n tag: t.Union[str, Tag],\n predict_fn_name: str,\n device_id: str,\n partial_kwargs: t.Optional[t.Dict[str, t.Any]],\n name: t.Optional[str] = None,\n ):\n super().__init__(tag, name=name)\n self._device_id = device_id\n self._configure(device_id)\n self._predict_fn_name = predict_fn_name\n self._partial_kwargs: t.Dict[str, t.Any] = (\n partial_kwargs if partial_kwargs is not None else dict()\n )\n\n def _configure(self, device_id: str) -> None:\n if \"GPU\" in device_id:\n tf.config.set_visible_devices(device_id, \"GPU\")\n self._config_proto = dict(\n allow_soft_placement=True,\n log_device_placement=False,\n intra_op_parallelism_threads=self._num_threads,\n inter_op_parallelism_threads=self._num_threads,\n )\n\n @property\n def _num_threads(self) -> int:\n if is_gpu_available() and self.resource_quota.on_gpu:\n return 1\n return int(round(self.resource_quota.cpu))\n\n @property\n def num_replica(self) -> int:\n if is_gpu_available() and self.resource_quota.on_gpu:\n return len(self.resource_quota.gpus)\n return 1\n\n def _setup(self) -> None:\n self._model = load(self._tag, model_store=self.model_store)\n raw_predict_fn = getattr(self._model, self._predict_fn_name) # type: ignore\n self._predict_fn = functools.partial(raw_predict_fn, **self._partial_kwargs)\n\n def _run_batch(self, *args: \"TFArgType\", **kwargs: \"TFArgType\") -> \"ext.NpNDArray\":\n params = Params[\"TFArgType\"](*args, **kwargs)\n\n with tf.device(self._device_id): # type: ignore\n\n def _mapping(item: \"TFArgType\") -> \"tf_ext.TensorLike\":\n if not LazyType[\"tf_ext.TensorLike\"](\"tf.Tensor\").isinstance(item):\n return t.cast(\"tf_ext.TensorLike\", tf.convert_to_tensor(item))\n else:\n return item\n\n params = params.map(_mapping)\n\n tf.compat.v1.global_variables_initializer() # type: ignore\n res = self._predict_fn(*params.args, **params.kwargs)\n return t.cast(\"ext.NpNDArray\", res.numpy())\n\n\ndef load_runner(\n tag: t.Union[str, Tag],\n *,\n predict_fn_name: str = \"__call__\",\n device_id: str = \"CPU:0\",\n name: t.Optional[str] = None,\n partial_kwargs: t.Optional[t.Dict[str, t.Any]] = None,\n) -> \"_TensorflowRunner\":\n \"\"\"\n Runner represents a unit of serving logic that can be scaled horizontally to\n maximize throughput. `bentoml.tensorflow.load_runner` implements a Runner class that\n wrap around a Tensorflow model, which optimize it for the BentoML runtime.\n\n Args:\n tag (:code:`Union[str, Tag]`):\n Tag of a saved model in BentoML local modelstore.\n predict_fn_name (:code:`str`, default to :code:`__call__`):\n Inference function to be used.\n partial_kwargs (:code:`Dict[str, Any]`, `optional`, default to :code:`None`):\n Dictionary of partial kwargs that can be shared across different model.\n device_id (:code:`str`, `optional`, default to the first CPU):\n Optional devices to put the given model on. Refers to `Logical Devices <https://www.tensorflow.org/api_docs/python/tf/config/list_logical_devices>`_ from TF documentation.\n\n Returns:\n :obj:`~bentoml._internal.runner.Runner`: Runner instances for :mod:`bentoml.tensorflow` model\n\n Examples:\n\n .. code-block:: python\n\n import bentoml\n\n # load a runner from a given flag\n runner = bentoml.tensorflow.load_runner(tag)\n\n # load a runner on GPU:0\n runner = bentoml.tensorflow.load_runner(tag, resource_quota=dict(gpus=0), device_id=\"GPU:0\")\n\n \"\"\"\n return _TensorflowRunner(\n tag=tag,\n predict_fn_name=predict_fn_name,\n device_id=device_id,\n partial_kwargs=partial_kwargs,\n name=name,\n )\n", "import os\nimport typing as t\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nfrom torch._C import device\nfrom simple_di import inject\nfrom simple_di import Provide\n\nimport bentoml\nfrom bentoml import Tag\nfrom bentoml.exceptions import BentoMLException\nfrom bentoml.exceptions import MissingDependencyException\n\nfrom ..models import PTH_EXT\nfrom ..models import YAML_EXT\nfrom ..models import SAVE_NAMESPACE\nfrom ..utils.pkg import get_pkg_version\nfrom ..runner.utils import Params\nfrom ..configuration.containers import BentoMLContainer\n\nif TYPE_CHECKING:\n from .. import external_typing as ext\n from ..models import ModelStore\ntry:\n # pylint: disable=unused-import\n import torch\n import detectron2 # noqa F401\n import detectron2.config as config\n import detectron2.modeling as modeling\n import detectron2.checkpoint as checkpoint\n from detectron2.checkpoint import DetectionCheckpointer\nexcept ImportError: # pragma: no cover\n raise MissingDependencyException(\n \"\"\"detectron2 is required in order to use module `bentoml.detectron`,\n install detectron2 with `pip install detectron2`. For more\n information, refers to\n https://detectron2.readthedocs.io/en/latest/tutorials/install.html\n \"\"\"\n )\n\nMODULE_NAME = \"bentoml.detectron\"\n\n\n@inject\ndef load(\n tag: t.Union[str, Tag],\n device: str = \"cpu\",\n model_store: \"ModelStore\" = Provide[BentoMLContainer.model_store],\n) -> \"torch.nn.Module\":\n \"\"\"\n Load a model from BentoML local modelstore with given tag.\n\n Args:\n tag (:code:`Union[str, Tag]`):\n Tag of a saved model in BentoML local modelstore.\n device (:code:`str`, `optional`, default to :code:`cpu`):\n Device type to cast model. Default behaviour similar to :obj:`torch.device(\"cuda\")` Options: \"cuda\" or \"cpu\". If None is specified then return default config.MODEL.DEVICE\n model_store (`~bentoml._internal.models.ModelStore`, default to :code:`BentoMLContainer.model_store`):\n BentoML modelstore, provided by DI Container.\n\n Returns:\n :obj:`torch.nn.Module`: an instance of `torch.nn.Module`\n\n Examples:\n\n .. code-block:: python\n\n import bentoml\n model = bentoml.detectron.load(\"my_detectron_model\")\n \"\"\" # noqa: LN001\n\n model_info = model_store.get(tag)\n if model_info.info.module not in (MODULE_NAME, __name__):\n raise BentoMLException(\n f\"Model {tag} was saved with module {model_info.info.module}, failed loading with {MODULE_NAME}.\"\n )\n\n cfg: config.CfgNode = config.get_cfg()\n\n weight_path = model_info.path_of(f\"{SAVE_NAMESPACE}{PTH_EXT}\")\n yaml_path = model_info.path_of(f\"{SAVE_NAMESPACE}{YAML_EXT}\")\n\n if os.path.isfile(yaml_path):\n cfg.merge_from_file(yaml_path)\n\n if device:\n cfg.MODEL.DEVICE = device\n\n model: \"torch.nn.Module\" = modeling.build_model(cfg)\n if device:\n model.to(device)\n\n model.eval()\n\n checkpointer: \"DetectionCheckpointer\" = checkpoint.DetectionCheckpointer(model)\n\n checkpointer.load(weight_path)\n return model\n\n\n@inject\ndef save(\n name: str,\n model: \"torch.nn.Module\",\n *,\n model_config: t.Optional[config.CfgNode] = None,\n labels: t.Optional[t.Dict[str, str]] = None,\n custom_objects: t.Optional[t.Dict[str, t.Any]] = None,\n metadata: t.Optional[t.Dict[str, t.Any]] = None,\n model_store: \"ModelStore\" = Provide[BentoMLContainer.model_store],\n) -> Tag:\n \"\"\"\n Save a model instance to BentoML modelstore.\n\n Args:\n name (:code:`str`):\n Name for given model instance. This should pass Python identifier check.\n model (`torch.nn.Module`):\n Instance of detectron2 model to be saved.\n model_config (`detectron2.config.CfgNode`, `optional`, default to :code:`None`):\n model config from :meth:`detectron2.model_zoo.get_config_file`\n labels (:code:`Dict[str, str]`, `optional`, default to :code:`None`):\n user-defined labels for managing models, e.g. team=nlp, stage=dev\n custom_objects (:code:`Dict[str, Any]]`, `optional`, default to :code:`None`):\n user-defined additional python objects to be saved alongside the model,\n e.g. a tokenizer instance, preprocessor function, model configuration json\n metadata (:code:`Dict[str, Any]`, `optional`, default to :code:`None`):\n Custom metadata for given model.\n model_store (`~bentoml._internal.models.ModelStore`, default to :code:`BentoMLContainer.model_store`):\n BentoML modelstore, provided by DI Container.\n\n Returns:\n :obj:`~bentoml.Tag`: A :obj:`tag` with a format `name:version` where `name` is the user-defined model's name, and a generated `version` by BentoML.\n\n Examples:\n\n .. code-block:: python\n\n import bentoml\n\n # import some common detectron2 utilities\n import detectron2\n from detectron2 import model_zoo\n from detectron2.config import get_cfg\n from detectron2.modeling import build_model\n\n model_url: str = \"COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml\"\n cfg: \"CfgNode\" = get_cfg()\n cfg.merge_from_file(model_zoo.get_config_file(model_url))\n # set threshold for this model\n cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5\n cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(model_url)\n cloned = cfg.clone()\n cloned.MODEL.DEVICE = \"cpu\"\n model: torch.nn.Module = build_model(cloned)\n\n tag = bentoml.detectron.save(\n \"my_detectron_model\",\n model,\n model_config=cfg,\n )\n\n # load the model back:\n loaded = bentoml.detectron.load(\"my_detectron_model:latest\")\n # or:\n loaded = bentoml.detectron.load(tag)\n\n \"\"\" # noqa\n\n context: t.Dict[str, t.Any] = {\n \"framework_name\": \"detectron2\",\n \"pip_dependencies\": [\n f\"detectron2=={get_pkg_version('detectron2')}\",\n f\"torch=={get_pkg_version('torch')}\",\n ],\n }\n options: t.Dict[str, t.Any] = dict()\n\n with bentoml.models.create(\n name,\n module=MODULE_NAME,\n labels=labels,\n custom_objects=custom_objects,\n options=options,\n context=context,\n metadata=metadata,\n ) as _model:\n checkpointer = checkpoint.DetectionCheckpointer(model, save_dir=_model.path)\n checkpointer.save(SAVE_NAMESPACE)\n if model_config:\n with open(\n _model.path_of(f\"{SAVE_NAMESPACE}{YAML_EXT}\"),\n \"w\",\n encoding=\"utf-8\",\n ) as ouf:\n ouf.write(model_config.dump())\n\n return _model.tag\n\n\nfrom .common.model_runner import BaseModelRunner\n\n\nclass _DetectronRunner(BaseModelRunner):\n def __init__(\n self,\n tag: t.Union[str, Tag],\n predict_fn_name: str,\n name: t.Optional[str] = None,\n ):\n super().__init__(tag, name=name)\n self._predict_fn_name = predict_fn_name\n\n @property\n def num_replica(self) -> int:\n if self.resource_quota.on_gpu:\n return len(self.resource_quota.gpus)\n return 1\n\n @property\n def _device(self) -> str:\n if self.resource_quota.on_gpu:\n return \"cuda\"\n return \"cpu\"\n\n def _setup(self) -> None:\n self._model = load(self._tag, self._device, model_store=self.model_store)\n self._predict_fn = getattr(self._model, self._predict_fn_name)\n\n def _run_batch( # type: ignore\n self,\n *args: t.Union[\"ext.NpNDArray\", torch.Tensor],\n ) -> \"ext.NpNDArray\":\n params = Params[t.Union[\"ext.NpNDArray\", torch.Tensor]](*args)\n\n def _mapping(item: t.Union[\"ext.NpNDArray\", torch.Tensor]) -> torch.Tensor:\n if isinstance(item, np.ndarray):\n return torch.Tensor(item, device=self._device)\n return item\n\n params = params.map(_mapping)\n\n inputs = [{\"image\": image} for image in params.args]\n\n res: \"torch.Tensor\" = self._predict_fn(inputs)\n return np.asarray(res) # type: ignore\n\n\ndef load_runner(\n tag: t.Union[str, Tag],\n predict_fn_name: str = \"__call__\",\n *,\n name: t.Optional[str] = None,\n) -> _DetectronRunner:\n \"\"\"\n Runner represents a unit of serving logic that can be scaled horizontally to\n maximize throughput. :func:`bentoml.detectron.load_runner` implements a Runner class that\n wrap around a :obj:`torch.nn.Module` model, which optimize it for the BentoML runtime.\n\n Args:\n tag (:code:`Union[str, Tag]`):\n Tag of a saved model in BentoML local modelstore.\n predict_fn_name (:code:`str`, default to :code:`__call__`):\n Options for inference functions. Default to `__call__`\n model_store (`~bentoml._internal.models.ModelStore`, default to :code:`BentoMLContainer.model_store`):\n BentoML modelstore, provided by DI Container.\n\n Returns:\n :obj:`~bentoml._internal.runner.Runner`: Runner instances for :mod:`bentoml.detectron` model\n\n Examples:\n\n .. code-block:: python\n\n import bentoml\n import numpy as np\n\n runner = bentoml.detectron.load_runner(tag)\n runner.run_batch(np.array([[1,2,3,]]))\n \"\"\"\n return _DetectronRunner(\n tag=tag,\n predict_fn_name=predict_fn_name,\n name=name,\n )\n", "import typing as t\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nimport psutil\nimport pytest\nimport catboost as cbt\nfrom catboost.core import CatBoost\nfrom catboost.core import CatBoostRegressor\nfrom catboost.core import CatBoostClassifier\n\nimport bentoml\nimport bentoml.models\nfrom bentoml.exceptions import BentoMLException\nfrom tests.utils.helpers import assert_have_file_extension\nfrom tests.utils.frameworks.sklearn_utils import test_df\n\nif TYPE_CHECKING:\n from bentoml._internal.store import Tag\n\n\ndef create_catboost_model() -> cbt.core.CatBoostClassifier:\n from sklearn.datasets import load_breast_cancer\n\n cancer = load_breast_cancer()\n\n X = cancer.data\n y = cancer.target\n\n clf = CatBoostClassifier(\n iterations=2,\n depth=2,\n learning_rate=1,\n loss_function=\"Logloss\",\n verbose=False,\n )\n\n # train the model\n clf.fit(X, y)\n\n return clf\n\n\ndef save_procedure(\n model_params: t.Dict[str, t.Any],\n metadata: t.Dict[str, t.Any],\n labels: t.Optional[t.Dict[str, str]] = None,\n custom_objects: t.Optional[t.Dict[str, t.Any]] = None,\n) -> \"Tag\":\n catboost_model = create_catboost_model()\n tag_info = bentoml.catboost.save(\n \"test_catboost_model\",\n catboost_model,\n model_params=model_params,\n metadata=metadata,\n labels=labels,\n custom_objects=custom_objects,\n )\n return tag_info\n\n\ndef forbidden_procedure():\n catboost_model = create_catboost_model()\n with bentoml.models.create(\n \"invalid_module\",\n module=__name__,\n labels=None,\n options=None,\n context=None,\n metadata=None,\n ) as ctx:\n catboost_model.save_model(ctx.path_of(\"saved_model.model\"))\n return ctx.tag\n\n\n@pytest.mark.parametrize(\n \"model_params, metadata\",\n [\n (\n dict(model_type=\"classifier\"),\n {\"acc\": 0.876},\n ),\n ],\n)\ndef test_catboost_save_load(\n model_params: t.Dict[str, t.Any],\n metadata: t.Dict[str, t.Any],\n) -> None:\n\n labels = {\"stage\": \"dev\"}\n\n def custom_f(x: int) -> int:\n return x + 1\n\n tag = save_procedure(\n model_params,\n metadata,\n labels=labels,\n custom_objects={\"func\": custom_f},\n )\n _model = bentoml.models.get(tag)\n assert _model.info.metadata is not None\n assert_have_file_extension(_model.path, \".cbm\")\n\n cbt_loaded = bentoml.catboost.load(_model.tag, model_params=model_params)\n assert isinstance(cbt_loaded, CatBoostClassifier)\n assert cbt_loaded.predict(test_df) == np.array([1])\n for k in labels.keys():\n assert labels[k] == _model.info.labels[k]\n assert _model.custom_objects[\"func\"](3) == custom_f(3)\n\n\ndef test_catboost_load_exc() -> None:\n tag = forbidden_procedure()\n with pytest.raises(BentoMLException):\n _ = bentoml.catboost.load(tag)\n\n\n@pytest.mark.parametrize(\n \"model_type, expected_model\",\n [\n (\"regressor\", CatBoostRegressor),\n (\"classifier\", CatBoostClassifier),\n (\"\", CatBoost),\n ],\n)\ndef test_catboost_model_type(\n model_type: str,\n expected_model: t.Union[CatBoost, CatBoostClassifier, CatBoostRegressor],\n) -> None:\n model_params = {\"model_type\": model_type}\n info = save_procedure(model_params, {})\n cbt_loaded = bentoml.catboost.load(info, model_params=model_params)\n\n assert isinstance(cbt_loaded, expected_model)\n\n\ndef test_catboost_runner_setup_run_batch() -> None:\n tag = save_procedure(\n {},\n {},\n )\n runner = bentoml.catboost.load_runner(tag)\n\n assert tag in runner.required_models\n assert runner.num_replica == psutil.cpu_count()\n assert runner.run_batch(test_df) == np.array([1])\n" ]
[ [ "tensorflow.compat.v1.global_variables_initializer", "tensorflow.convert_to_tensor", "tensorflow.compat.v1.get_default_graph", "tensorflow.compat.v1.saved_model.load_v2", "tensorflow.device", "tensorflow.saved_model.save", "tensorflow.config.set_visible_devices" ], [ "torch.Tensor", "numpy.asarray" ], [ "numpy.array", "sklearn.datasets.load_breast_cancer" ] ]
klauer/caproto-image-viewer
[ "5f267648d645c5950d1dfa5025a7a2a582200efb" ]
[ "caimageviewer/gl_util.py" ]
[ "import sys\nimport numpy as np\nfrom contextlib import contextmanager\nfrom qtpy.QtGui import QOpenGLBuffer\n\n\ndef setup_vertex_buffer(gl, data, shader, shader_variable):\n 'Setup a vertex buffer with `data` vertices as `shader_variable` on shader'\n vbo = QOpenGLBuffer(QOpenGLBuffer.VertexBuffer)\n vbo.create()\n with bind(vbo):\n vertices = np.array(data, np.float32)\n count, dim_vertex = vertices.shape\n vbo.allocate(vertices.flatten(), vertices.nbytes)\n\n attr_loc = shader.attributeLocation(shader_variable)\n shader.enableAttributeArray(attr_loc)\n shader.setAttributeBuffer(attr_loc, gl.GL_FLOAT, 0, dim_vertex)\n return vbo\n\n\ndef update_vertex_buffer(vbo, data):\n 'Update a vertex buffer with `data` vertices'\n vertices = np.asarray(data, np.float32)\n count, dim_vertex = vertices.shape\n with bind(vbo):\n vbo.allocate(vertices.flatten(), vertices.nbytes)\n\n\ndef copy_data_to_pbo(pbo, data, *, mapped_array=None):\n 'Allocate or update data stored in a pixel buffer object'\n width, height = data.shape\n\n with bind(pbo):\n if pbo.isCreated() and mapped_array is not None:\n mapped_array[:] = data.reshape((width, height))\n return mapped_array\n\n full_size = data.nbytes\n pointer_type = np.ctypeslib.ndpointer(\n dtype=data.dtype, shape=(width, height), ndim=data.ndim)\n\n pbo.create()\n with bind(pbo):\n pbo.allocate(data, full_size)\n ptr = pbo.map(QOpenGLBuffer.WriteOnly)\n assert ptr is not None, 'Failed to map pixel buffer array'\n\n pointer_type = np.ctypeslib.ndpointer(\n dtype=data.dtype, shape=(width, height), ndim=data.ndim)\n mapped_array = np.ctypeslib.as_array(pointer_type(int(ptr)))\n pbo.unmap()\n mapped_array[:] = data.reshape((width, height))\n return mapped_array\n\n\ndef update_pbo_texture(gl, pbo, texture, *, array_data, texture_format,\n source_format, source_type):\n 'Update a texture associated with a PBO'\n width, height = array_data.shape[:2]\n\n if source_format == gl.GL_RGB:\n height //= 3\n\n with bind(pbo, texture):\n # AreaDetector arrays are not strided\n gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1)\n # AreaDetector arrays are big endian - so let OpenGL take care of\n # byteswapping if that doesn't match up with the system/array\n # endianness\n # gl.glPixelStorei(gl.GL_UNPACK_SWAP_BYTES,\n # int(not array_data.dtype.isnative))\n\n gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER,\n gl.GL_LINEAR)\n gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER,\n gl.GL_LINEAR)\n gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, texture_format, width, height, 0,\n source_format, source_type, None)\n\n\n@contextmanager\ndef bind(*objs, args=None):\n 'Bind all objs (optionally with positional arguments); releases at cleanup'\n if args is None:\n args = (None for obj in objs)\n\n for obj, arg in zip(objs, args):\n if arg is not None:\n obj.bind(arg)\n else:\n obj.bind()\n\n yield\n\n for obj in objs[::-1]:\n obj.release()\n" ]
[ [ "numpy.array", "numpy.ctypeslib.ndpointer", "numpy.asarray" ] ]
viraat/skynet-today
[ "fee4f2f2f9298221b9b03ca91c104b27ef3aa423" ]
[ "scripts/csv2md.py" ]
[ "import os\nimport logging\nimport argparse\nfrom collections import Counter\n\nimport pandas as pd\nimport inflect\n\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n_CATEGRORIES = [\n 'Mini Briefs',\n 'Advances & Business',\n 'Concerns & Hype',\n 'Analysis & Policy',\n 'Expert Opinions & Discussion within the field',\n 'Explainers'\n]\n\n\nif __name__ == \"__main__\":\n logging.getLogger().setLevel(logging.INFO)\n parser = argparse.ArgumentParser()\n parser.add_argument('--template_file', '-tf', type=str, default='digest_template.md')\n parser.add_argument('--digest_number', '-n', type=int, required=True)\n parser.add_argument('--input_csv', '-i', type=str, required=True)\n parser.add_argument('--output_md', '-o', type=str, required=True)\n parser.add_argument('--force_overwrite', '-f', action='store_true')\n args = parser.parse_args()\n\n n = args.digest_number\n p = inflect.engine()\n n_english = p.number_to_words(p.ordinal(n))\n logging.info('Parsing for the {} digest'.format(n_english))\n\n logging.info('Will save result to {}'.format(args.output_md))\n if os.path.isfile(args.output_md):\n if not args.force_overwrite:\n raise ValueError('Cannot overwrite existing output file!')\n\n logging.info('Loading template from {}'.format(args.template_file))\n with open(args.template_file, 'r') as f:\n md_template = f.read()\n\n logging.info('Reading {}'.format(args.input_csv))\n articles_map = {c : [] for c in _CATEGRORIES}\n csv = pd.read_csv(args.input_csv)\n for row_num, row in csv.iterrows():\n if not row['Type']:\n print()\n print('To which category does this article belong?')\n print()\n print(row['Name'])\n print()\n \n for i, c in enumerate(_CATEGRORIES):\n print('{}) {}'.format(i, c))\n while True:\n try:\n print()\n c_idx = int(input('Category Number: '))\n c = _CATEGRORIES[c_idx]\n break\n except:\n print('Please enter a valid category!')\n print()\n else:\n c = row['Type']\n\n articles_map[c].append(row)\n\n logging.info('Populating content...')\n content = ''\n for c in _CATEGRORIES:\n items = articles_map[c]\n if len(items) > 0:\n content += '### {}\\n'.format(c)\n content += '\\n'\n\n for item in items:\n if c == 'Mini Briefs':\n content += '#### [{}]({})\\n'.format(item['Name'], item['URL'])\n content += '\\n'\n content += '<one-two paragraph brief>\\n'\n else:\n content += '* [{}]({}) - {}\\n'.format(item['Name'], item['URL'], item['Excerpt'])\n\n content += '\\n'\n \n # remove the last two empty lines\n content = content[:-2]\n\n md = md_template.replace('$digest_number$', str(n)) \\\n .replace('$digest_number_english$', n_english) \\\n .replace('$content$', content)\n\n logging.info('Saving digest markdown...')\n with open(args.output_md, 'w') as f:\n f.write(md)\n\n logging.info('Done!')\n" ]
[ [ "pandas.read_csv" ] ]
markusschmitt/QuSpin
[ "c239d01e6ce76253b03440cda3c8819a9f63e288" ]
[ "quspin/tools/expm_multiply_parallel_core/expm_multiply_parallel_core.py" ]
[ "from scipy.sparse.linalg import LinearOperator,onenormest,aslinearoperator\nfrom .expm_multiply_parallel_wrapper import (_wrapper_expm_multiply,\n\t_wrapper_csr_trace,_wrapper_csr_1_norm)\nfrom scipy.sparse.construct import eye\nfrom scipy.sparse.linalg._expm_multiply import _fragment_3_1,_exact_1_norm\nimport scipy.sparse as _sp\nimport numpy as _np\n\nclass expm_multiply_parallel(object):\n \"\"\"Implements `scipy.sparse.linalg.expm_multiply()` for *openmp*.\n\n Notes\n -----\n * this is a wrapper over custom c++ code.\n * the `dtype` input need not be the same dtype as `A` or `a`; however, it must be possible to cast the result of `a*A` to this `dtype`. \n * consider the special case of real-time evolution with a purely-imaginary Hamiltonian, in which case `a=-1j*time` and `A` are both complex-valued, while the resulting matrix exponential is real-valued: in such cases, one can use either one of\n \n >>> expm_multiply_parallel( (1j*H.tocsr()).astype(np.float64), a=-1.0, dtype=np.float64)`\n \n and\n \n >>> expm_multiply_parallel( H.tocsr(), a=-1.0j, dtype=np.complex128)\n \n The more efficient way to compute the matrix exponential in this case is to use a real-valued `dtype`. \n\n\n Examples\n --------\n\n This example shows how to construct the `expm_multiply_parallel` object.\n\n Further code snippets can be found in the examples for the function methods of the class.\n The code snippet below initiates the class, and is required to run the example codes for the function methods.\n \n .. literalinclude:: ../../doc_examples/expm_multiply_parallel-example.py\n :linenos:\n :language: python\n :lines: 7-30\n \n \"\"\"\n def __init__(self,A,a=1.0,dtype=None,copy=False):\n \"\"\"Initializes `expm_multiply_parallel`. \n\n Parameters\n -----------\n A : {array_like, scipy.sparse matrix}\n The operator (matrix) whose exponential is to be calculated.\n a : scalar, optional\n scalar value multiplying generator matrix :math:`A` in matrix exponential: :math:`\\\\mathrm{e}^{aA}`.\n dtype : numpy.dtype, optional\n data type specified for the total operator :math:`\\\\mathrm{e}^{aA}`. Default is: `numpy.result_type(A.dtype,min_scalar_type(a),float64)`.\n copy : bool, optional\n if `True` the matrix is copied otherwise the matrix is stored by reference. \n\n \"\"\"\n if _np.array(a).ndim == 0:\n self._a = a\n else:\n raise ValueError(\"a must be scalar value.\")\n\n self._A = _sp.csr_matrix(A,copy=copy)\n\n if A.shape[0] != A.shape[1]:\n raise ValueError(\"A must be a square matrix.\")\n\n a_dtype_min = _np.min_scalar_type(self._a)\n\n # use double precision by default. \n if dtype is None:\n self._dtype = _np.result_type(A.dtype,a_dtype_min,_np.float64)\n else:\n min_dtype = _np.result_type(A.dtype,a_dtype_min,_np.float32)\n if not _np.can_cast(min_dtype,dtype):\n raise ValueError(\"dtype not sufficient to represent a*A to at least float32 precision.\")\n\n self._dtype = dtype\n\n tol = _np.finfo(self._dtype).eps/2\n tol_dtype = _np.finfo(self._dtype).eps.dtype\n self._tol = _np.array(tol,dtype=tol_dtype)\n\n mu = _wrapper_csr_trace(self._A.indptr,self._A.indices,self._A.data)/self._A.shape[0]\n self._mu = _np.array(mu,dtype=self._dtype)\n self._A_1_norm = _wrapper_csr_1_norm(self._A.indptr,self._A.indices,self._A.data,self._mu)\n self._calculate_partition()\n\n # shift = eye(A.shape[0],format=\"csr\",dtype=A.dtype)\n # shift.data *= mu\n # self._A = self._A - shift\n\n\n @property\n def a(self):\n \"\"\"scalar: value multiplying generator matrix :math:`A` in matrix exponential: :math:`\\\\mathrm{e}^{aA}`\"\"\"\n return self._a\n\n @property\n def A(self):\n \"\"\"scipy.sparse.csr_matrix: csr_matrix to be exponentiated.\"\"\"\n return self._A\n\n\n def set_a(self,a,dtype=None):\n \"\"\"Sets the value of the property `a`.\n\n Parameters\n ----------\n a : scalar\n new value of `a`.\n dtype : numpy.dtype, optional\n dtype specified for this operator. Default is: result_type(A.dtype,min_scalar_type(a),float64)\n\n Examples\n --------\n\n .. literalinclude:: ../../doc_examples/expm_multiply_parallel-example.py\n :linenos:\n :language: python\n :lines: 32-35\n \n \"\"\"\n\n if _np.array(a).ndim == 0:\n self._a = a\n\n a_dtype_min = _np.min_scalar_type(self._a)\n\n # use double precision by default. \n if dtype is None:\n self._dtype = _np.result_type(self._A.dtype,a_dtype_min,_np.float64)\n else:\n min_dtype = _np.result_type(A.dtype,a_dtype_min,_np.float32)\n if not _np.can_cast(min_dtype,dtype):\n raise ValueError(\"dtype not sufficient to represent a*A to at least float32 precision.\")\n\n self._dtype = dtype\n\n tol = _np.finfo(self._dtype).eps/2\n tol_dtype = _np.finfo(self._dtype).eps.dtype\n self._tol = _np.array(tol,dtype=tol_dtype)\n self._mu = _np.array(self._mu,dtype=self._dtype)\n\n self._calculate_partition()\n else:\n raise ValueError(\"expecting 'a' to be scalar.\")\n\n def dot(self,v,work_array=None,overwrite_v=False):\n \"\"\"Calculates the action of :math:`\\\\mathrm{e}^{aA}` on a vector :math:`v`. \n\n Examples\n --------\n\n .. literalinclude:: ../../doc_examples/expm_multiply_parallel-example.py\n :linenos:\n :language: python\n :lines: 37-\n\n Parameters\n -----------\n v : contiguous numpy.ndarray\n array to apply :math:`\\\\mathrm{e}^{aA}` on.\n work_array : contiguous numpy.ndarray, optional\n array of `shape = (2*len(v),)` which is used as work_array space for the underlying c-code. This saves extra memory allocation for function operations.\n overwrite_v : bool\n if set to `True`, the data in `v` is overwritten by the function. This saves extra memory allocation for the results.\n\n Returns\n --------\n numpy.ndarray\n result of :math:`\\\\mathrm{e}^{aA}v`. \n\n If `overwrite_v = True` the dunction returns `v` with the data overwritten, otherwise the result is stored in a new array. \n\n \"\"\"\n v = _np.asarray(v)\n \n if v.ndim != 1:\n raise ValueError(\"array must have ndim of 1.\")\n \n if v.shape[0] != self._A.shape[1]:\n raise ValueError(\"dimension mismatch {}, {}\".format(self._A.shape,v.shape))\n\n\n\n v_dtype = _np.result_type(self._dtype,v.dtype)\n\n\n if overwrite_v:\n if v_dtype != v.dtype:\n raise ValueError(\"if overwrite_v is True, the input array must match correct output dtype for matrix multiplication.\")\n\n if not v.flags[\"CARRAY\"]:\n raise TypeError(\"input array must a contiguous and writable.\")\n\n if v.ndim != 1:\n raise ValueError(\"array must have ndim of 1.\")\n else:\n v = v.astype(v_dtype,order=\"C\",copy=True)\n\n if work_array is None:\n work_array = _np.zeros((2*self._A.shape[0],),dtype=v.dtype)\n else:\n work_array = _np.ascontiguousarray(work_array)\n if work_array.shape != (2*self._A.shape[0],):\n raise ValueError(\"work_array array must be an array of shape (2*v.shape[0],) with same dtype as v.\")\n if work_array.dtype != v_dtype:\n raise ValueError(\"work_array must be array of dtype which matches the result of the matrix-vector multiplication.\")\n\n a = _np.array(self._a,dtype=v_dtype)\n mu = _np.array(self._mu,dtype=v_dtype)\n tol = _np.array(self._tol,dtype=mu.real.dtype)\n _wrapper_expm_multiply(self._A.indptr,self._A.indices,self._A.data,\n self._s,self._m_star,a,tol,mu,v,work_array)\n\n return v\n\n def _calculate_partition(self):\n if _np.abs(self._a)*self._A_1_norm == 0:\n self._m_star, self._s = 0, 1\n else:\n ell = 2\n norm_info = LazyOperatorNormInfo(self._A, self._A_1_norm, self._a, self._mu, self._dtype, ell=ell)\n self._m_star, self._s = _fragment_3_1(norm_info, 1, self._tol, ell=ell)\n\n\n##### code below is copied from scipy.sparse.linalg._expm_multiply_core and modified slightly.\n\n\ndef matvec_p(v,A,a,mu,p):\n for i in range(p):\n v = a * (A.dot(v) - mu*v)\n\n return v\n\n\nclass LazyOperatorNormInfo:\n \"\"\"\n Information about an operator is lazily computed.\n\n The information includes the exact 1-norm of the operator,\n in addition to estimates of 1-norms of powers of the operator.\n This uses the notation of Computing the Action (2011).\n This class is specialized enough to probably not be of general interest\n outside of this module.\n\n \"\"\"\n def __init__(self, A, A_1_norm, a, mu, dtype, ell=2):\n \"\"\"\n Provide the operator and some norm-related information.\n\n Parameters\n -----------\n A : linear operator\n The operator of interest.\n A_1_norm : float\n The exact 1-norm of A.\n ell : int, optional\n A technical parameter controlling norm estimation quality.\n\n \"\"\"\n self._A = A\n self._a = a\n self._mu = mu\n self._dtype = dtype\n self._A_1_norm = A_1_norm\n self._ell = ell\n self._d = {}\n\n def onenorm(self):\n \"\"\"\n Compute the exact 1-norm.\n \"\"\"\n return _np.abs(self._a) * self._A_1_norm\n\n def d(self, p):\n \"\"\"\n Lazily estimate d_p(A) ~= || A^p ||^(1/p) where ||.|| is the 1-norm.\n \"\"\"\n if p not in self._d:\n matvec = lambda v: self._a * (self._A.dot(v) - self._mu*v)\n rmatvec = lambda v: _np.conj(self._a) * (self._A.H.dot(v) - _np.conj(self._mu)*v)\n LO = LinearOperator(self._A.shape,dtype=self._dtype,matvec=matvec,rmatvec=rmatvec)\n\n est = onenormest(LO**p)\n\n # est = onenormest((self._a * aslinearoperator(self._A))**p)\n self._d[p] = est ** (1.0 / p)\n\n return self._d[p]\n\n def alpha(self, p):\n \"\"\"\n Lazily compute max(d(p), d(p+1)).\n \"\"\"\n return max(self.d(p), self.d(p+1))\n\n\n" ]
[ [ "numpy.result_type", "numpy.array", "scipy.sparse.linalg.onenormest", "numpy.asarray", "numpy.zeros", "numpy.ascontiguousarray", "scipy.sparse.linalg._expm_multiply._fragment_3_1", "scipy.sparse.linalg.LinearOperator", "numpy.finfo", "numpy.can_cast", "numpy.conj", "numpy.abs", "numpy.min_scalar_type", "scipy.sparse.csr_matrix" ] ]
kazush/tokyo_covid19_stat
[ "dbb856ef2a1bb40a8e7502d27b860cbc69f27cd5" ]
[ "stat_by_area.py" ]
[ "from typing import List\nimport argparse\nimport chart_studio.plotly as py\nimport plotly.express as px\nimport pandas as pd\n\nclass TokyoCovid19Stat:\n \"\"\"Holds Tokyo Covid-19 stat data.\"\"\"\n\n def __init__(self, csv_file_path: str = None):\n self.csv_file_path = csv_file_path\n self._df = None\n self.area_list = []\n\n def update(self) -> None:\n df = pd.read_csv(self.csv_file_path,\n parse_dates=['Date'])\n for area in df['Area']:\n if area in self.area_list:\n break\n self.area_list.append(area)\n df = df.pivot(index='Date', columns='Area', values='New Cases')\n self._df = df[self.area_list]\n\n @property\n def df(self) -> pd.DataFrame:\n if self._df is None:\n self.update()\n return self._df\n\n @property\n def cases_by_area(self) -> pd.DataFrame:\n return self.df\n\n @property\n def cases(self) -> pd.DataFrame:\n return pd.DataFrame({'Cases': self.cases_by_area.sum(axis=1)})\n\n\ndef sma(df: pd.DataFrame, days: int = 7) -> pd.DataFrame:\n return df.rolling(days).mean()\n\n\ndef with_date(orig_df: pd.DataFrame) -> pd.DataFrame:\n df = orig_df.copy()\n df['Date'] = df.index.to_list()\n return df\n\n\ndef melt(orig_df: pd.DataFrame,\n value_columns: List[str],\n var_name: str,\n value_name: str = 'Cases') -> pd.DataFrame:\n \"\"\"Unpivot the given DataFrame to be used with Plotly.\"\"\"\n df = with_date(orig_df)\n df = df[['Date'] + value_columns]\n return df.melt(id_vars=['Date'],\n value_vars=value_columns,\n var_name=var_name,\n value_name=value_name)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--csv_file_path')\n args = parser.parse_args()\n\n if args.csv_file_path is None:\n return\n\n st = TokyoCovid19Stat(args.csv_file_path)\n\n cases_by_area = melt(st.cases_by_area,\n value_columns=st.area_list,\n var_name='Area')\n\n sma_by_area = melt(sma(st.cases_by_area),\n value_columns=st.area_list,\n var_name='Area')\n\n # title = 'Tokyo Covid-19 New Cases By Area'\n # fig = px.area(cases_by_area, x='Date', y='Cases', color='Area', title=title)\n # py.plot(fig, filename=title, auto_open=False)\n\n title = '[TEST] Tokyo Covid-19 New Cases 7-day Moving Average By Area'\n fig = px.line(sma_by_area, x='Date', y='Cases', color='Area', title=title)\n fig.add_bar(x=st.cases.index,\n y=st.cases['Cases'],\n name='Raw Total',\n marker=dict(color='#dddddd'))\n py.plot(fig, filename=title, auto_open=False)\n\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "pandas.read_csv" ] ]
RPGroup-PBoC/chann_cap
[ "f2a826166fc2d47c424951c616c46d497ed74b39", "f2a826166fc2d47c424951c616c46d497ed74b39" ]
[ "src/theory/scripts/channcap_protein_multi_prom_iptg_range.py", "src/image_analysis/scripts/microscopy_bootstrap.py" ]
[ "#%%\n# Our numerical workhorses\nimport numpy as np\nimport pandas as pd\n\nimport itertools\n# Import libraries to parallelize processes\nfrom joblib import Parallel, delayed\n\n# Import matplotlib stuff for plotting\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport matplotlib as mpl\n\n# Seaborn, useful for graphics\nimport seaborn as sns\n\n# Pickle is useful for saving outputs that are computationally expensive\n# to obtain every time\nimport pickle\n\nimport os\nimport glob\nimport git\n\n# Import the project utils\nimport ccutils\n\n#%%\n# Find home directory for repo\nrepo = git.Repo(\"./\", search_parent_directories=True)\nhomedir = repo.working_dir\n\n# Read MaxEnt distributions\nprint('Reading MaxEnt distributions')\ndf_maxEnt_prot = pd.read_csv(\n \"../../data/csv_maxEnt_dist/MaxEnt_Lagrange_mult_protein_IPTG_range.csv\"\n)\n# Define dictionaries to map operator to binding energy and rbs to rep copy\nop_dict = dict(zip([\"O1\", \"O2\", \"O3\"], [-15.3, -13.9, -9.7]))\nrbs_dict = dict(\n zip(\n [\"HG104\", \"RBS1147\", \"RBS446\", \"RBS1027\", \"RBS1\", \"RBS1L\"],\n [22, 60, 124, 260, 1220, 1740],\n )\n)\n\n# Define sample space\nmRNA_space = np.array([0])\nprotein_space = np.arange(0, 1.5E4)\n\n# Group df_maxEnt by operator and repressor copy number\ndf_group = df_maxEnt_prot.groupby([\"operator\", \"repressor\"])\n\n# Define column names for data frame\nnames = [\"operator\", \"binding_energy\", \"repressor\", \"channcap\", \"pc\"]\n\n# Initialize data frame to save channel capacity computations\ndf_channcap = pd.DataFrame(columns=names)\n\n# Define function to compute in parallel the channel capacity\ndef cc_parallel_protein(df_lagrange):\n\n # Build mRNA transition matrix\n Qpc = ccutils.channcap.trans_matrix_maxent(\n df_lagrange, \n mRNA_space, \n protein_space, \n False)\n\n # Compute the channel capacity with the Blahut-Arimoto algorithm\n cc_p, pc, _ = ccutils.channcap.channel_capacity(Qpc.T, epsilon=1e-4)\n\n # Extract operator and repressor copy number\n op = df_lagrange.operator.unique()[0]\n eRA = df_lagrange.binding_energy.unique()[0]\n rep = df_lagrange.repressor.unique()[0]\n\n return [op, eRA, rep, cc_p, pc]\n\nprint('Running Blahut algorithm in multiple cores')\n# Run the function in parallel\nccaps = Parallel(n_jobs=6)(\n delayed(cc_parallel_protein)(df_lagrange)\n for group, df_lagrange in df_group\n)\n\n# Convert to tidy data frame\nccaps = pd.DataFrame(ccaps, columns=names)\n\n# Concatenate to data frame\ndf_channcap = pd.concat([df_channcap, ccaps], axis=0)\n\n# Save results\nprint('Saving results into memory')\ndf_channcap.to_csv(\n f\"{homedir}/data/csv_maxEnt_dist/chann_cap_multi_prom_protein_IPTG_range.csv\",\n index=False,\n)\nprint('Done!')\n", "#%%\nimport numpy as np\nimport scipy as sp\nimport pandas as pd\nimport ccutils\n\n#%%\n\n# Set random seed\nnp.random.seed(42)\n# Define number of boostrap estimates\nn_estimates = 10000\n\n# Define percentiles to save\npercentiles = [.01, .05, .10, .25, .50, .75, .90, .95, .99]\n\n# Read single cell data\ndf_micro = pd.read_csv('../../../data/csv_microscopy/' +\n 'single_cell_microscopy_data.csv')\n\n#%%\n# group by date and by IPTG concentration\ndf_group = df_micro.groupby(['date'])\n\n# Define names for columns in data frame\nnames = ['date', 'IPTG_uM','operator', 'binding_energy',\n 'repressor', 'percentile',\n 'fold_change', 'fold_change_lower', 'fold_change_upper',\n 'noise', 'noise_lower', 'noise_upper',\n 'skewness', 'skewness_lower', 'skewness_upper']\n\n# Initialize data frame to save the noise\ndf_noise = pd.DataFrame(columns=names)\n\n# Loop through groups\nfor date, data in df_group:\n print(f'date: {date}')\n # Extract the autofluorescence\n I_auto = data[data.rbs == 'auto'].mean_intensity.values\n print('bootstrapping autofluorescence')\n # Perform bootstrap estimate of mean autofluorescence\n boots_auto = ccutils.stats.bootstrap_estimate(I_auto, np.mean, n_estimates)\n \n # Extract ∆lacI data\n data_delta = data[data.rbs == 'delta']\n # Initialize array to save bootstrap estimates of the background corrected\n # ∆lacI intensity\n boots_mean_delta = np.zeros(n_estimates)\n boots_std_delta = np.zeros(n_estimates)\n boots_skew_delta = np.zeros(n_estimates)\n print('bootstrapping ∆lacI')\n # Loop through estimates\n for i in range(n_estimates):\n # Sample data\n sample = data_delta.sample(n=len(data_delta), replace=True)\n # Compute bootstrap estimates\n boots_mean_delta[i] = np.mean(sample.intensity.values -\n boots_auto[i] * sample.area.values)\n boots_std_delta[i] = np.std(sample.intensity.values -\n boots_auto[i] * sample.area.values, ddof=1)\n boots_skew_delta[i] = sp.stats.skew(sample.intensity.values -\n boots_auto[i] * sample.area.values, bias=False)\n # Compute ∆lacI noise\n boots_noise_delta = boots_std_delta / boots_mean_delta\n # Loop through percentiles and save information\n for per in percentiles:\n # Compute percentile noise\n per_noise = ccutils.stats.hpd(boots_noise_delta, per)\n per_skew = ccutils.stats.hpd(boots_skew_delta, per)\n strain_info = [\n date,\n None,\n data_delta.operator.unique()[0],\n data_delta.binding_energy.unique()[0],\n 0,\n per,\n None,\n None,\n None,\n np.median(boots_noise_delta),\n per_noise[0],\n per_noise[1],\n np.median(boots_skew_delta),\n per_skew[0],\n per_skew[1]\n ]\n # Append to dataframe\n df_noise = df_noise.append(pd.Series(strain_info, index=names),\n ignore_index=True)\n\n # Group data by IPTG concentration \n data_group = data[(data.rbs != 'auto') &\n (data.rbs != 'delta')].groupby('IPTG_uM')\n\n # Loop through inducer concentrations\n for inducer, data_inducer in data_group:\n print(f'bootstrapping {inducer} µM')\n # Initialize array to save bootstrap estimates of the background\n # corrected \n boots_mean_inducer = np.zeros(n_estimates)\n boots_std_inducer = np.zeros(n_estimates)\n boots_skew_inducer = np.zeros(n_estimates)\n # Loop through estimates\n for i in range(n_estimates):\n # Sample data\n sample = data_inducer.sample(n=len(data_inducer), replace=True)\n # Compute bootstrap estimates\n boots_mean_inducer[i] = np.mean(sample.intensity.values -\n boots_auto[i] * sample.area.values)\n boots_std_inducer[i] = np.std(sample.intensity.values -\n boots_auto[i] * sample.area.values, ddof=1)\n boots_skew_inducer[i] = sp.stats.skew(sample.intensity.values -\n boots_auto[i] * sample.area.values,\n bias=False)\n\n # Remove netative reads\n idx = boots_mean_inducer >= 0\n boots_mean_inducer = boots_mean_inducer[idx]\n boots_std_inducer = boots_std_inducer[idx]\n boots_skew_inducer = boots_skew_inducer[idx]\n # Compute fold-change and noise\n boots_fc_inducer = boots_mean_inducer /\\\n boots_mean_delta[0:sum(idx)]\n boots_noise_inducer = boots_std_inducer / boots_mean_inducer\n\n # Loop through percentiles and save information\n for per in percentiles:\n # Compute percentile noise\n per_fc = ccutils.stats.hpd(boots_fc_inducer, per)\n per_noise = ccutils.stats.hpd(boots_noise_inducer, per)\n per_skew = ccutils.stats.hpd(boots_skew_inducer, per)\n strain_info = [\n date,\n inducer,\n data_inducer.operator.unique()[0],\n data_inducer.binding_energy.unique()[0],\n data_inducer.repressor.unique()[0],\n per,\n np.median(boots_fc_inducer),\n per_fc[0],\n per_fc[1],\n np.median(boots_noise_inducer),\n per_noise[0],\n per_noise[1],\n np.median(boots_skew_inducer),\n per_skew[0],\n per_skew[1]\n ]\n # Append to dataframe\n df_noise = df_noise.append(pd.Series(strain_info, index=names),\n ignore_index=True)\n\n# %%\n\n# Export dataframe\ndf_noise.to_csv('../../../data/csv_microscopy/microscopy_noise_bootstrap.csv')\n" ]
[ [ "numpy.array", "pandas.DataFrame", "numpy.arange", "pandas.concat", "pandas.read_csv" ], [ "numpy.zeros", "numpy.random.seed", "pandas.DataFrame", "numpy.median", "numpy.mean", "numpy.std", "scipy.stats.skew", "pandas.Series", "pandas.read_csv" ] ]
abdussamettrkr/dirt-t
[ "a605d0c31a4bec9e60eb533704cd5e423601c060" ]
[ "tensorbayes/nputils.py" ]
[ "import numpy as np\n\ndef log_sum_exp(x, axis=-1):\n a = x.max(axis=axis, keepdims=True)\n out = a + np.log(np.sum(np.exp(x - a), axis=axis, keepdims=True))\n return np.squeeze(out, axis=axis)\n\ndef kl_normal(qm, qv, pm, pv):\n return 0.5 * np.sum(np.log(pv) - np.log(qv) + qv/pv +\n np.square(qm - pm) / pv - 1, axis=-1)\n\ndef convert_to_ssl(x, y, n_labels, n_classes, complement=False):\n if y.shape[-1] == n_classes:\n y_sparse = y.argmax(1)\n else:\n y_sparse = y\n x_label, y_label = [], []\n if complement:\n x_comp, y_comp = [], []\n for i in xrange(n_classes):\n idx = y_sparse == i\n x_cand, y_cand = x[idx], y[idx]\n idx = np.random.choice(len(x_cand), n_labels/n_classes, replace=False)\n x_select, y_select = x_cand[idx], y_cand[idx]\n x_label += [x_select]\n y_label += [y_select]\n if complement:\n x_select, y_select = np.delete(x_cand, idx, 0), np.delete(y_cand, idx, 0)\n x_comp += [x_select]\n y_comp += [y_select]\n x_label = np.concatenate(x_label, axis=0)\n y_label = np.concatenate(y_label, axis=0)\n if complement:\n x_comp = np.concatenate(x_comp, axis=0)\n y_comp = np.concatenate(y_comp, axis=0)\n return x_label, y_label, x_comp, y_comp\n else:\n return x_label, y_label, x, y\n\ndef conv_shape(x, k, s, p, ceil=True):\n if p == 'SAME':\n output = float(x) / float(s)\n elif p == 'VALID':\n output = float(x - k + 1) / float(s)\n else:\n raise Exception('Unknown padding type')\n if ceil:\n return int(np.ceil(output))\n else:\n assert output.is_integer(), 'Does not satisfy conv int requirement'\n return int(output)\n\ndef conv_shape_list(x, ksp_list, ceil=True):\n x_list = [x]\n for k, s, p in ksp_list:\n x_list.append(conv_shape(x_list[-1], k, s, p, ceil))\n return x_list\n\ndef split(arr, size):\n for i in range(0, len(arr), size):\n yield arr[i:i + size]\n\nclass FixedSeed:\n def __init__(self, seed):\n self.seed = seed\n self.state = None\n\n def __enter__(self):\n self.state = np.random.get_state()\n np.random.seed(self.seed)\n\n def __exit__(self, exc_type, exc_value, traceback):\n np.random.set_state(self.state)\n" ]
[ [ "numpy.concatenate", "numpy.square", "numpy.ceil", "numpy.delete", "numpy.log", "numpy.random.seed", "numpy.exp", "numpy.random.get_state", "numpy.squeeze", "numpy.random.set_state" ] ]
valmar/lcls2
[ "1c24da076a8cd252cf6601e125dd721fd2004f2a" ]
[ "psana/psana/detector/UtilsEpix10ka.py" ]
[ "\n\"\"\"\n:py:class:`UtilsEpix10ka` contains utilities for epix10ka and its composite detectors\n=====================================================================================\n\nUsage::\n from psana.detector.UtilsEpix10ka import ...\n\n #inds = segment_indices_det(det)\n #long_name = fullname_det(det)\n #ids = segment_ids_det(det)\n o = config_object_det(det, detname=None)\n #o = config_object_det_raw(det_raw)\n cbits = cbits_config_epix10ka(cob) # used in det.raw._cbits_config_segment(cob)\n cbits = cbits_config_epixhr2x2(cob) # used in det.raw._cbits_config_segment(cob)\n cbits = cbits_config_and_data_detector_epix10ka(det_raw, evt=None) # used in det.raw._cbits_config_and_data_detector(evt)\n cbits = cbits_config_and_data_detector_epixhr2x2(det_raw, evt=None) # used in det.raw._cbits_config_and_data_detector(evt)\n maps = gain_maps_epix10ka_any(det_raw, evt=None)\n s = def info_gain_mode_arrays(gmaps, first=0, last=5)\n gmstatist = pixel_gain_mode_statistics(gmaps)\n s = info_pixel_gain_mode_statistics(gmaps)\n s = info_pixel_gain_mode_statistics_for_raw(det_raw, evt=None, msg='pixel gain mode statistics: ')\n gmfs = pixel_gain_mode_fractions(det_raw, evt=None)\n s = info_pixel_gain_mode_for_fractions(grp_prob, msg='pixel gain mode fractions: ')\n s = info_pixel_gain_mode_fractions(det_raw, evt=None, msg='pixel gain mode fractions: ')\n gmind = gain_mode_index_from_fractions(gmfs)\n gmind = find_gain_mode_index(det_raw, evt=None)\n gmode = gain_mode_name_for_index(ind)\n gmode = find_gain_mode(det_raw, evt=None)\n calib = calib_epix10ka_any(det_raw, evt, cmpars=None, **kwa)\n calib = calib_epix10ka_any(det_raw, evt, cmpars=(7,2,100,10),\\\n mbits=0o7, mask=None, edge_rows=10, edge_cols=10, center_rows=5, center_cols=5)\n\nThis software was developed for the LCLS project.\nIf you use all or part of it, please give an appropriate acknowledgment.\n\nCreated on 2020-12-03 by Mikhail Dubrovin for LCLS2 from LCLS1\n\"\"\"\n\nimport os\nimport sys\nimport numpy as np\nfrom time import time\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nfrom psana.detector.NDArrUtils import info_ndarr, divide_protected\nfrom psana.detector.UtilsMask import merge_masks, DTYPE_MASK\nfrom psana.detector.UtilsCommonMode import common_mode_cols,\\\n common_mode_rows_hsplit_nbanks, common_mode_2d_hsplit_nbanks\n\nGAIN_MODES = ['FH','FM','FL','AHL-H','AML-M','AHL-L','AML-L']\nGAIN_MODES_IN = ['FH','FM','FL','AHL-H','AML-M']\n\nB04 = 0o20 # 16 or 1<<4 (5-th bit starting from 1)\nB05 = 0o40 # 32 or 1<<5 (6-th bit starting from 1)\n\n# epix10ka data gainbit and mask\nB14 = 0o40000 # 16384 or 1<<14 (15-th bit starting from 1)\nM14 = 0x3fff # 16383 or (1<<14)-1 - 14-bit mask\n\n# epixhr data gainbit and mask\nB15 = 0o100000 # 32768 or 1<<15 (16-th bit starting from 1)\nM15 = 0x7fff # 32767 or (1<<15)-1 - 15-bit mask\n\n\nclass Storage:\n def __init__(self):\n self.arr1 = None\n self.gfac = None\n self.mask = None\n self.dcfg = None\n self.counter = -1\n\ndic_store = {} # {det.name:Storage()} in stead of singleton\n\n\ndef config_object_det(det, detname=None):\n \"\"\"Returns [dict]={<seg-index>:<cob>} of configuration objects for detector with optional name.\n \"\"\"\n _detname = det.raw._det_name if detname is None else detname\n for config in det._configs:\n if not _detname in config.__dict__:\n logger.debug('Skipping config {:}'.format(config.__dict__))\n continue\n return getattr(config,_detname)\n return None\n\n\ndef cbits_config_epix10ka(cob, shape=(352, 384)):\n \"\"\"Creates array of the segment control bits for epix10ka shape=(352, 384)\n from cob=det.raw._seg_configs()[<seg-ind>].config object.\n Returns per panel 4-bit pixel config array with bit assignment]\n 0001 = 1<<0 = 1 - T test bit\n 0010 = 1<<1 = 2 - M mask bit\n 0100 = 1<<2 = 4 - g gain bit\n 1000 = 1<<3 = 8 - ga gain bit\n # add trbit\n 010000 = 1<<4 = 16 - trbit\n\n Parameters\n ----------\n cob : container.Container object\n segment configuration object det.raw._seg_configs()[<seg-ind>].config\n Contains:\n cob.asicPixelConfig: shape:(4, 178, 192) size:136704 dtype:uint8 [12 12 12 12 12...]\n cob.trbit: [1 1 1 1]\n\n Returns\n -------\n xxxx: np.array, dtype:uint8, ndim=2, shape=(352, 384)\n \"\"\"\n trbits = cob.trbit # [1 1 1 1]\n pca = cob.asicPixelConfig # [:,:176,:] - fixed in daq # shape:(4, 176, 192) size:135168 dtype:uint8 [8 8 8 8 8...]\n logger.debug(info_ndarr(cob.asicPixelConfig, 'trbits: %s asicPixelConfig:'%str(trbits)))\n rowsh, colsh = int(shape[0]/2), int(shape[1]/2) # should be 176, 192 for epix10ka\n\n #t0_sec = time()\n\n # begin to create array of control bits\n # Origin of ASICs in bottom-right corner, so\n # stack them in upside-down matrix and rotete it by 180 deg.\n\n cbits = np.flipud(np.fliplr(np.vstack((np.hstack((pca[2],pca[1])),\n np.hstack((pca[3],pca[0])))))) # 0.000090 sec\n\n #cbits = np.bitwise_and(cbits,12) # 0o14 (bin:1100) # 0.000202 sec\n np.bitwise_and(cbits,12,out=cbits) # 0o14 (bin:1100) # 0.000135 sec\n\n #logger.debug('TIME for cbits composition = %.6f sec' % (time()-t0_sec))\n #logger.debug(info_ndarr(cbits,'cbits:'))\n #exit('TEST EXIT')\n\n if all(trbits): cbits = np.bitwise_or(cbits, B04) # add trbit for all pixels (352, 384)\n elif not any(trbits): return cbits\n else: # set trbit per ASIC\n if trbits[2]: np.bitwise_or(cbits[:rowsh,:colsh], B04, out=cbits[:rowsh,:colsh])\n if trbits[3]: np.bitwise_or(cbits[rowsh:,:colsh], B04, out=cbits[rowsh:,:colsh])\n if trbits[0]: np.bitwise_or(cbits[rowsh:,colsh:], B04, out=cbits[rowsh:,colsh:])\n if trbits[1]: np.bitwise_or(cbits[:rowsh,colsh:], B04, out=cbits[:rowsh,colsh:]) #0.000189 sec\n return cbits\n\n\ndef cbits_config_epixhr2x2(cob, shape=(288, 384)):\n \"\"\"Creates array of the segment control bits for epixhr2x2 shape=(288, 384)\n from cob=det.raw._seg_configs()[<seg-ind>].config object.\n Returns per panel 4-bit pixel config array with bit assignment]\n 0001 = 1<<0 = 1 - T test bit\n 0010 = 1<<1 = 2 - M mask bit\n 0100 = 1<<2 = 4 - g gain bit\n 1000 = 1<<3 = 8 - ga gain bit\n # add trbit\n 010000 = 1<<4 = 16 - trbit\n\n Parameters\n ----------\n cob : container.Container object\n segment configuration object det.raw._seg_configs()[<seg-ind>].config\n Contains:\n cob.asicPixelConfig shape:(110592,) size:110592 dtype:uint8 [0 0 0 0 0...]\n cob.trbit: [1 1 1 1]\n\n ASIC map of epixhr2x2 (Matt)\n A1 | A3\n ----+----\n A0 | A2\n\n Returns\n -------\n xxxx: np.array, dtype:uint8, ndim=2, shape=(288, 384)\n \"\"\"\n #t0_sec = time()\n trbits = cob.trbit # [1 1 1 1]\n pca = cob.asicPixelConfig # shape:(110592,)\n rowsh, colsh = int(shape[0]/2), int(shape[1]/2) # should be 144, 192 for epixhr2x2\n logger.debug(info_ndarr(cob.asicPixelConfig, 'shape: %s trbits: %s asicPixelConfig:'%(str(shape), str(trbits))))\n\n cbits = np.bitwise_and(pca,12,out=None) # copy and mask non-essential bits 0o14 (bin:1100)\n cbits.shape = shape\n\n #logger.info('TIME1 in cbits_config_epixhr2x2 = %.6f sec' % (time()-t0_sec)) # 0.000206 sec\n\n if all(trbits): cbits = np.bitwise_or(cbits, B04) # add trbit for all pixels (288, 384)\n elif not any(trbits): return cbits\n else: # set trbit per ASIC\n if trbits[1]: np.bitwise_or(cbits[:rowsh,:colsh], B04, out=cbits[:rowsh,:colsh])\n if trbits[0]: np.bitwise_or(cbits[rowsh:,:colsh], B04, out=cbits[rowsh:,:colsh])\n if trbits[3]: np.bitwise_or(cbits[:rowsh,colsh:], B04, out=cbits[:rowsh,colsh:])\n if trbits[2]: np.bitwise_or(cbits[rowsh:,colsh:], B04, out=cbits[rowsh:,colsh:])\n\n #logger.info('TIME2 in cbits_config_epixhr2x2 = %.6f sec' % (time()-t0_sec))\n return cbits\n\n\ndef cbits_config_and_data_detector(det_raw, evt=None):\n \"\"\"Returns array of control bits shape=(<number-of-segments>, 352(or 288), 384)\n from any config object and data array.\n\n get 5-bit pixel config array with bit assignments\n 0001 = 1<<0 = 1 - T test bit\n 0010 = 1<<1 = 2 - M mask bit\n 0100 = 1<<2 = 4 - g gain bit\n 1000 = 1<<3 = 8 - ga gain bit\n 010000 = 1<<4 = 16 - trbit 1/0 for H/M\n add data bit\n 100000 = 1<<5 = 32 - data bit 14/15 for epix10ka/epixhr2x2 panel\n \"\"\"\n data = det_raw.raw(evt)\n cbits = det_raw._cbits_config_detector()\n #logger.info(info_ndarr(cbits, 'cbits', first=0, last=5))\n if cbits is None: return None\n\n if data is not None:\n #logger.debug(info_ndarr(data, 'data', first, last))\n # get array of data bit 15 and add it as a bit 5 to cbits\n datagainbit = np.bitwise_and(data, det_raw._data_gain_bit)\n databit05 = np.right_shift(datagainbit, det_raw._gain_bit_shift) # 0o100000 -> 0o40\n np.bitwise_or(cbits, databit05, out=cbits) # 109us\n\n return cbits\n\n\ndef gain_maps_epix10ka_any(det_raw, evt=None):\n \"\"\"Returns maps of gain groups shape=(<number-of-segments>, <2-d-panel-shape>)\n works for both epix10ka (352, 384) and epixhr2x2 (288, 384)\n\n cbits - pixel control bit array\n\n data bit 14 is moved here 1/0 for H,M/L\n / trbit 1/0 for H/M\n V / bit3 1/0 for F/A\n V / bit2 1/0 for H,M/L\n V / M mask\n V / T test gain range index\n V / / in calib files\n V V\n x111xx =28 - FH_H 0\n x011xx =12 - FM_M 1\n xx10xx = 8 - FL_L 2\n 0100xx =16 - AHL_H 3\n 0000xx = 0 - AML_M 4\n 1100xx =48 - AHL_L 5\n 1000xx =32 - AML_L 6\n ---\n 111100 =60 - cbitsM60 - mask\n 011100 =28 - cbitsM28 - mask\n 001100 =12 - cbitsM12 - mask\n \"\"\"\n\n cbits = det_raw._cbits_config_and_data_detector(evt)\n if cbits is None: return None\n\n cbitsM60 = cbits & 60 # control bits masked by configuration 3-bit-mask\n cbitsM28 = cbits & 28 # control bits masked by configuration 3-bit-mask\n cbitsM12 = cbits & 12 # control bits masked by configuration 2-bit-mask\n #logger.debug(info_ndarr(cbitsMCB, 'cbitsMCB', first, last))\n\n #return gr0, gr1, gr2, gr3, gr4, gr5, gr6 # per-pixel bool for 7 gain ranges\n return (cbitsM28 == 28),\\\n (cbitsM28 == 12),\\\n (cbitsM12 == 8),\\\n (cbitsM60 == 16),\\\n (cbitsM60 == 0),\\\n (cbitsM60 == 48),\\\n (cbitsM60 == 32)\n\n\ndef info_gain_mode_arrays(gmaps, first=0, last=5):\n \"\"\" gr0, gr1, gr2, gr3, gr4, gr5, gr6 = gmaps\n \"\"\"\n recs = [info_ndarr(gr, 'gr%d'%i, first, last) for i,gr in enumerate(gmaps)]\n return 'gain range arrays:\\n %s' % (' %s\\n'.join(recs))\n\n\ndef pixel_gain_mode_statistics(gmaps):\n \"\"\"returns statistics of pixels in defferent gain modes in gain maps\n gr0, gr1, gr2, gr3, gr4, gr5, gr6 = gmaps\n \"\"\"\n arr1 = np.ones_like(gmaps[0], dtype=np.int32)\n return [np.sum(np.select((gr,), (arr1,), default=0)) for gr in gmaps]\n\n\ndef info_pixel_gain_mode_statistics(gmaps):\n \"\"\"returns (str) with statistics of pixels in defferent gain modes in gain maps\n \"\"\"\n grp_stat = pixel_gain_mode_statistics(gmaps)\n return ', '.join(['%7d' % npix for npix in grp_stat])\n\n\ndef info_pixel_gain_mode_statistics_for_raw(det_raw, evt=None, msg='pixel gain mode statistics: '):\n \"\"\"DOES ANYONE USE IT?\n returns (str) with statistics of pixels in defferent gain modes in raw data\n \"\"\"\n gmaps = gain_maps_epix10ka_any(det_raw, evt)\n if gmaps is None: return None\n return '%s%s' % (msg, info_pixel_gain_mode_statistics(gmaps))\n\n\ndef pixel_gain_mode_fractions(det_raw, evt=None):\n \"\"\"returns fraction of pixels in defferent gain modes in gain maps\n \"\"\"\n gmaps = gain_maps_epix10ka_any(det_raw, evt)\n if gmaps is None: return None\n pix_stat = pixel_gain_mode_statistics(gmaps)\n f = 1.0/gmaps[0].size\n return [npix*f for npix in pix_stat]\n\n\ndef info_pixel_gain_mode_for_fractions(grp_prob, msg='pixel gain mode fractions: '):\n return '%s%s' % (msg, ', '.join(['%.5f'%p for p in grp_prob]))\n\n\ndef info_pixel_gain_mode_fractions(det_raw, evt=None, msg='pixel gain mode fractions: '):\n \"\"\"returns (str) with fraction of pixels in defferent gain modes in gain maps\n \"\"\"\n grp_prob = pixel_gain_mode_fractions(det_raw, evt)\n return info_pixel_gain_mode_for_fractions(grp_prob, msg=msg)\n\n\ndef gain_mode_index_from_fractions(grp_prob):\n \"\"\"Returns int gain mode index or None from list of gain group fractions.\"\"\"\n return next((i for i,p in enumerate(grp_prob) if p>0.5), None)\n\n\ndef find_gain_mode_index(det_raw, evt=None):\n \"\"\"Returns int gain mode index or None.\n if data=None: distinguish 5-modes w/o data\n \"\"\"\n grp_prob = pixel_gain_mode_fractions(det_raw, evt)\n return gain_mode_index_from_fractions(grp_prob)\n\n\ndef gain_mode_name_for_index(ind):\n \"\"\"Returns str gain mode name for int index in the list GAIN_MODES or None.\n \"\"\"\n return GAIN_MODES[ind] if ind<len(GAIN_MODES) else None\n\n\ndef find_gain_mode(det_raw, evt=None):\n \"\"\"Returns str gain mode from the list GAIN_MODES or None.\n if data=None: distinguish 5-modes w/o data\n \"\"\"\n grp_prob = pixel_gain_mode_fractions(det_raw, evt)\n ind = gain_mode_index_from_fractions(grp_prob)\n if ind is None: return None\n return gain_mode_name_for_index(ind)\n #return GAIN_MODES[ind] if ind<len(grp_prob) else None\n\n\ndef event_constants_for_gmaps(gmaps, cons, default=0):\n \"\"\" 6 msec\n Parameters\n ----------\n - gmaps - tuple of 7 boolean maps ndarray(<nsegs>, 352, 384)\n - cons - 4d constants (7, <nsegs>, 352, 384)\n - default value for constants\n\n Returns\n -------\n np.ndarray (<nsegs>, 352, 384) - per event constants\n \"\"\"\n return np.select(gmaps, (cons[0,:], cons[1,:], cons[2,:], cons[3,:],\\\n cons[4,:], cons[5,:], cons[6,:]), default=default)\n\n\ndef event_constants(det_raw, evt, cons, default=0):\n gmaps = gain_maps_epix10ka_any(det_raw, evt) #tuple: 7 x shape:(4, 352, 384)\n if gmaps is None: return None\n return event_constants_for_gmaps(gmaps, cons, default=default)\n\n\ndef event_constants_for_grinds(grinds, cons):\n \"\"\" 12 msec\n FOR TEST PURPOSE ONLY - x2 slower than event_constants_for_gmaps\n\n Parameters\n ----------\n - grinds - ndarray(<nsegs>, 352, 384) array of the gain range indices [0,6]\n - cons - 4d constants (7, <nsegs>, 352, 384)\n - default value for constants\n\n Returns\n -------\n np.ndarray (<nsegs>, 352, 384) - per event constants\n \"\"\"\n #shape0 = grinds.shape\n #grinds.shape = (1,) + tuple(grinds.shape) #(1, 4, 352, 384) # add dimension for take_along_axis\n #nda = np.take_along_axis(cons, grinds, 0)\n #grinds.shape = shape0 # restore original shape\n #return nda\n\n shapei = grinds.shape #(<nsegs>, 352, 384)\n shapec = cons.shape #(7, <nsegs>, 352, 384)\n cons.shape = (7,grinds.size)\n grinds.shape = (1,grinds.size)\n nda = np.take_along_axis(cons, grinds, 0)\n nda.shape = shapei\n cons.shape = shapec\n grinds.shape = shapei\n return nda\n\n\ndef test_event_constants_for_grinds(det_raw, evt, gfac, peds):\n \"\"\"factor, pedest = test_event_constants_for_grinds(det_raw, evt, gfac, peds)\n 12msec for epixquad ueddaq02 r557\n \"\"\"\n t0_sec = time()\n grinds = map_gain_range_index(det_raw, evt) #.ravel()\n factor = event_constants_for_grinds(grinds, gfac)\n pedest = event_constants_for_grinds(grinds, peds)\n print('XXX test_event_constants_for_grinds consumed time = %.6f sec' % (time()-t0_sec)) # 12msec for epixquad ueddaq02 r557\n print(info_ndarr(grinds, 'evt grinds'))\n print(info_ndarr(pedest, 'evt pedest'))\n print(info_ndarr(factor, 'evt factor'))\n return factor, pedest\n\n\ndef test_event_constants_for_gmaps(det_raw, evt, gfac, peds):\n \"\"\"factor, pedest = test_event_constants_for_gmaps(det_raw, evt, gfac, peds)\n 6msec for epixquad ueddaq02 r557\n \"\"\"\n t0_sec = time()\n gmaps = gain_maps_epix10ka_any(det_raw, evt) #tuple: 7 x shape:(4, 352, 384)\n if gmaps is None: return None\n factor = event_constants_for_gmaps(gmaps, gfac, default=1)\n pedest = event_constants_for_gmaps(gmaps, peds, default=0) # 6 msec total versus 5.5 using select directly\n print('XXX test_event_constants_for_gmaps consumed time = %.6f sec' % (time()-t0_sec)) # 6msec for epixquad ueddaq02 r557\n print(info_ndarr(gmaps, 'evt gmaps'))\n print(info_ndarr(pedest, 'evt pedest'))\n print(info_ndarr(factor, 'evt factor'))\n return factor, pedest\n\n\ndef calib_epix10ka_any(det_raw, evt, cmpars=None, **kwa): #cmpars=(7,2,100)):\n \"\"\"\n Algorithm\n ---------\n - gets constants\n - gets raw data\n - evaluates (code - pedestal - offset)\n - applys common mode correction if turned on\n - apply gain factor\n\n Parameters\n ----------\n - det_raw (psana.Detector.raw) - Detector.raw object\n - evt (psana.Event) - Event object\n - cmpars (tuple) - common mode parameters\n = None - use pars from calib directory\n = cmpars=(<alg>, <mode>, <maxcorr>)\n alg is not used\n mode =0-correction is not applied, =1-in rows, =2-in cols-WORKS THE BEST\n i.e: cmpars=(7,0,100) or (7,2,100)\n - **kwa - used here and passed to det_raw.mask_comb\n - nda_raw - substitute for det_raw.raw(evt)\n - mbits - parameter of the det_raw.mask_comb(...)\n - mask - user defined mask passed as optional parameter\n\n Returns\n -------\n - calibrated epix10ka data\n \"\"\"\n\n logger.debug('In calib_epix10ka_any')\n\n t0_sec_tot = time()\n\n nda_raw = kwa.get('nda_raw', None)\n raw = det_raw.raw(evt) if nda_raw is None else nda_raw # shape:(352, 384) or suppose to be later (<nsegs>, 352, 384) dtype:uint16\n if raw is None: return None\n\n _cmpars = det_raw._common_mode() if cmpars is None else cmpars\n\n gain = det_raw._gain() # - 4d gains (7, <nsegs>, 352, 384)\n peds = det_raw._pedestals() # - 4d pedestals\n if gain is None: return None # gain = np.ones_like(peds) # - 4d gains\n if peds is None: return None # peds = np.zeros_like(peds) # - 4d gains\n\n store = dic_store.get(det_raw._det_name, None)\n\n if store is None:\n\n logger.info('create new store for %s' % det_raw._det_name)\n store = dic_store[det_raw._det_name] = Storage()\n\n # do ONCE this initialization\n logger.debug(info_ndarr(raw, '\\n raw ')\\\n +info_ndarr(gain, '\\n gain')\\\n +info_ndarr(peds, '\\n peds'))\n\n store.gfac = divide_protected(np.ones_like(gain), gain)\n store.arr1 = np.ones_like(raw, dtype=np.int8)\n\n logger.debug(info_ndarr(store.gfac, '\\n gfac '))\n\n # 'FH','FM','FL','AHL-H','AML-M','AHL-L','AML-L'\n #store.gf4 = np.ones_like(raw, dtype=np.int32) * 0.25 # 0.3333 # M - perefierial\n #store.gf6 = np.ones_like(raw, dtype=np.int32) * 1 # L - center\n\n gfac = store.gfac\n\n #if store.dcfg is None: store.dcfg = det_raw._config_object() #config_object_det_raw(det_raw)\n\n gmaps = gain_maps_epix10ka_any(det_raw, evt) #tuple: 7 x shape:(4, 352, 384)\n if gmaps is None: return None\n\n factor = np.select(gmaps,\\\n (gfac[0,:], gfac[1,:], gfac[2,:], gfac[3,:],\\\n gfac[4,:], gfac[5,:], gfac[6,:]), default=1) # 2msec\n\n pedest = np.select(gmaps,\\\n (peds[0,:], peds[1,:], peds[2,:], peds[3,:],\\\n peds[4,:], peds[5,:], peds[6,:]), default=0)\n\n #factor, pedest = test_event_constants_for_gmaps(det_raw, evt, gfac, peds) # 6msec\n #factor, pedest = test_event_constants_for_grinds(det_raw, evt, gfac, peds) # 12msec\n\n store.counter += 1\n if not store.counter%100:\n logger.debug(info_gain_mode_arrays(gmaps))\n logger.debug(info_pixel_gain_mode_statistics(gmaps))\n\n logger.debug('TOTAL consumed time (sec = %.6f' % (time()-t0_sec_tot))\n\n arrf = np.array(raw & det_raw._data_bit_mask, dtype=np.float32) - pedest\n\n logger.debug('common-mode correction pars cmp: %s' % str(_cmpars))\n\n if store.mask is None:\n mbits = kwa.pop('mbits',1) # 1-mask from status, etc.\n mask = det_raw._mask_comb(mbits=mbits, **kwa) if mbits > 0 else None\n mask_opt = kwa.get('mask',None) # mask optional parameter in det_raw.calib(...,mask=...)\n store.mask = mask if mask_opt is None else mask_opt if mask is None else merge_masks(mask,mask_opt)\n\n mask = store.mask if store.mask is not None else np.ones_like(raw, dtype=DTYPE_MASK)\n\n if _cmpars is not None:\n alg, mode, cormax = int(_cmpars[0]), int(_cmpars[1]), _cmpars[2]\n npixmin = _cmpars[3] if len(_cmpars)>3 else 10\n if mode>0:\n t0_sec_cm = time()\n arr1 = store.arr1 # np.ones_like(mask, dtype=np.uint8)\n gr0, gr1, gr2, gr3, gr4, gr5, gr6 = gmaps\n grhm = np.select((gr0, gr1, gr3, gr4), (arr1, arr1, arr1, arr1), default=0) if alg==7 else arr1\n gmask = np.bitwise_and(grhm, mask) if mask is not None else grhm\n #logger.debug(info_ndarr(arr1, '\\n arr1'))\n #logger.debug(info_ndarr(grhm, 'XXXX grhm'))\n #logger.debug(info_ndarr(gmask, 'XXXX gmask'))\n #logger.debug('common-mode mask massaging (sec) = %.6f' % (time()-t2_sec_cm)) # 5msec\n logger.debug(info_ndarr(gmask, 'gmask')\\\n + '\\n per panel statistics of cm-corrected pixels: %s' % str(np.sum(gmask, axis=(1,2), dtype=np.uint32)))\n\n #sh = (nsegs, 352, 384)\n hrows = 176 # int(352/2)\n for s in range(arrf.shape[0]):\n\n if mode & 4: # in banks: (352/2,384/8)=(176,48) pixels\n common_mode_2d_hsplit_nbanks(arrf[s,:hrows,:], mask=gmask[s,:hrows,:], nbanks=8, cormax=cormax, npix_min=npixmin)\n common_mode_2d_hsplit_nbanks(arrf[s,hrows:,:], mask=gmask[s,hrows:,:], nbanks=8, cormax=cormax, npix_min=npixmin)\n\n if mode & 1: # in rows per bank: 384/8 = 48 pixels # 190ms\n common_mode_rows_hsplit_nbanks(arrf[s,], mask=gmask[s,], nbanks=8, cormax=cormax, npix_min=npixmin)\n\n if mode & 2: # in cols per bank: 352/2 = 176 pixels # 150ms\n common_mode_cols(arrf[s,:hrows,:], mask=gmask[s,:hrows,:], cormax=cormax, npix_min=npixmin)\n common_mode_cols(arrf[s,hrows:,:], mask=gmask[s,hrows:,:], cormax=cormax, npix_min=npixmin)\n\n logger.debug('TIME common-mode correction = %.6f sec for cmp=%s' % (time()-t0_sec_cm, str(_cmpars)))\n\n return arrf * factor if mask is None else arrf * factor * mask # gain correction\n\n\ndef map_gain_range_index(det_raw, evt, **kwa):\n \"\"\"Returns array of epix10ka per pixel gain range indices [0:6] shaped as raw (<nsegs>, 352, 384) dtype:uint16\n \"\"\"\n nda_raw = kwa.get('nda_raw', None)\n raw = det_raw.raw(evt) if nda_raw is None else nda_raw\n if raw is None: return None\n\n gmaps = gain_maps_epix10ka_any(det_raw, evt)\n if gmaps is None: return None\n #gr0, gr1, gr2, gr3, gr4, gr5, gr6 = gmaps\n return np.select(gmaps, (0, 1, 2, 3, 4, 5, 6), default=10)#.astype(np.uint16) # int64 -> uint16\n\n\ncalib_epix10ka = calib_epix10ka_any\n\n# EOF\n\n" ]
[ [ "numpy.array", "numpy.ones_like", "numpy.bitwise_or", "numpy.sum", "numpy.right_shift", "numpy.bitwise_and", "numpy.take_along_axis", "numpy.hstack", "numpy.select" ] ]
minionssso/PyABSA
[ "fd9a9a6fd55552a60329fd04b6830e1bb144d50f", "fd9a9a6fd55552a60329fd04b6830e1bb144d50f" ]
[ "pyabsa/core/tc/classic/__bert__/dataset_utils/data_utils_for_training.py", "pyabsa/core/atepc/models/lcfs_atepc.py" ]
[ "# -*- coding: utf-8 -*-\n# file: data_utils.py\n# author: songyouwei <youwei0314@gmail.com>\n# Copyright (C) 2018. All Rights Reserved.\n\nimport os\nimport pickle\n\nimport numpy as np\nimport tqdm\nfrom findfile import find_file\nfrom google_drive_downloader.google_drive_downloader import GoogleDriveDownloader as gdd\nfrom torch.utils.data import Dataset\nfrom transformers import AutoTokenizer\n\nfrom pyabsa.core.apc.dataset_utils.apc_utils import load_apc_datasets\nfrom pyabsa.utils.pyabsa_utils import check_and_fix_labels\n\n\ndef prepare_glove840_embedding(glove_path):\n glove840_id = '1G-vd6W1oF9ByyJ-pzp9dcqKnr_plh4Em'\n if not os.path.exists(glove_path):\n os.mkdir(glove_path)\n elif os.path.isfile(glove_path):\n return glove_path\n elif os.path.isdir(glove_path):\n embedding_file = None\n dir_path = os.path.dirname(glove_path)\n if find_file(dir_path, 'glove.42B.300d.txt', exclude_key='.zip'):\n embedding_file = find_file(dir_path, 'glove.42B.300d.txt', exclude_key='.zip')[0]\n elif find_file(dir_path, 'glove.840B.300d.txt', exclude_key='.zip'):\n embedding_file = find_file(dir_path, 'glove.840B.300d.txt', exclude_key='.zip')[0]\n elif find_file(dir_path, 'glove.twitter.27B.txt', exclude_key='.zip'):\n embedding_file = find_file(dir_path, 'glove.twitter.27B.txt', exclude_key='.zip')[0]\n\n if embedding_file:\n print('Find potential embedding files: {}'.format(embedding_file))\n return embedding_file\n zip_glove_path = os.path.join(glove_path, '__glove__.840B.300d.txt.zip')\n print('No GloVe embedding found at {},'\n ' downloading __glove__.840B.300d.txt (2GB transferred / 5.5GB unzipped)...'.format(glove_path))\n gdd.download_file_from_google_drive(file_id=glove840_id,\n dest_path=zip_glove_path,\n unzip=True\n )\n glove_path = find_file(glove_path, 'txt', exclude_key='.zip')\n return glove_path\n\n\ndef build_tokenizer(dataset_list, max_seq_len, dat_fname, opt):\n if os.path.exists(os.path.join(opt.dataset_name, dat_fname)):\n print('Loading tokenizer on {}'.format(os.path.join(opt.dataset_name, dat_fname)))\n tokenizer = pickle.load(open(os.path.join(opt.dataset_name, dat_fname), 'rb'))\n else:\n text = ''\n for dataset_type in dataset_list:\n for file in dataset_list[dataset_type]:\n fin = open(file, 'r', encoding='utf-8', newline='\\n', errors='ignore')\n lines = fin.readlines()\n fin.close()\n for i in range(0, len(lines), 3):\n text_left, _, text_right = [s.lower().strip() for s in lines[i].partition(\"$T$\")]\n aspect = lines[i + 1].lower().strip()\n text_raw = text_left + \" \" + aspect + \" \" + text_right\n text += text_raw + \" \"\n\n tokenizer = Tokenizer(max_seq_len)\n tokenizer.fit_on_text(text)\n pickle.dump(tokenizer, open(os.path.join(opt.dataset_name, dat_fname), 'wb'))\n return tokenizer\n\n\ndef _load_word_vec(path, word2idx=None, embed_dim=300):\n fin = open(path, 'r', encoding='utf-8', newline='\\n', errors='ignore')\n word_vec = {}\n for line in tqdm.tqdm(fin, postfix='Loading embedding file...'):\n tokens = line.rstrip().split()\n word, vec = ' '.join(tokens[:-embed_dim]), tokens[-embed_dim:]\n if word in word2idx.keys():\n word_vec[word] = np.asarray(vec, dtype='float32')\n return word_vec\n\n\ndef build_embedding_matrix(word2idx, embed_dim, dat_fname, opt):\n if os.path.exists(os.path.join(opt.dataset_name, dat_fname)):\n print('Loading cached embedding_matrix for {}'.format(os.path.join(opt.dataset_name, dat_fname)))\n embedding_matrix = pickle.load(open(os.path.join(opt.dataset_name, dat_fname), 'rb'))\n else:\n print('Extracting embedding_matrix for {}'.format(dat_fname))\n glove_path = prepare_glove840_embedding(opt.dataset_name)\n embedding_matrix = np.zeros((len(word2idx) + 2, embed_dim)) # idx 0 and len(word2idx)+1 are all-zeros\n\n word_vec = _load_word_vec(glove_path, word2idx=word2idx, embed_dim=embed_dim)\n\n for word, i in tqdm.tqdm(word2idx.items(), postfix='Building embedding_matrix {}'.format(dat_fname)):\n vec = word_vec.get(word)\n if vec is not None:\n # words not found in embedding index will be all-zeros.\n embedding_matrix[i] = vec\n pickle.dump(embedding_matrix, open(os.path.join(opt.dataset_name, dat_fname), 'wb'))\n return embedding_matrix\n\n\ndef pad_and_truncate(sequence, maxlen, dtype='int64', padding='post', truncating='post', value=0):\n x = (np.ones(maxlen) * value).astype(dtype)\n if truncating == 'pre':\n trunc = sequence[-maxlen:]\n else:\n trunc = sequence[:maxlen]\n trunc = np.asarray(trunc, dtype=dtype)\n if padding == 'post':\n x[:len(trunc)] = trunc\n else:\n x[-len(trunc):] = trunc\n return x\n\n\nclass Tokenizer(object):\n def __init__(self, max_seq_len, lower=True):\n self.lower = lower\n self.max_seq_len = max_seq_len\n self.word2idx = {}\n self.idx2word = {}\n self.idx = 1\n\n def fit_on_text(self, text):\n if self.lower:\n text = text.lower()\n words = text.split()\n for word in words:\n if word not in self.word2idx:\n self.word2idx[word] = self.idx\n self.idx2word[self.idx] = word\n self.idx += 1\n\n def text_to_sequence(self, text, reverse=False, padding='post', truncating='post'):\n if self.lower:\n text = text.lower()\n words = text.split()\n unknownidx = len(self.word2idx) + 1\n sequence = [self.word2idx[w] if w in self.word2idx else unknownidx for w in words]\n if len(sequence) == 0:\n sequence = [0]\n if reverse:\n sequence = sequence[::-1]\n return pad_and_truncate(sequence, self.max_seq_len, padding=padding, truncating=truncating)\n\n\nclass Tokenizer4Pretraining:\n def __init__(self, max_seq_len, pretrained_bert_name):\n self.tokenizer = AutoTokenizer.from_pretrained(pretrained_bert_name)\n self.max_seq_len = max_seq_len\n\n def text_to_sequence(self, text, reverse=False, padding='post', truncating='post'):\n sequence = self.tokenizer.convert_tokens_to_ids(self.tokenizer.tokenize(text))\n if len(sequence) == 0:\n sequence = [0]\n if reverse:\n sequence = sequence[::-1]\n return pad_and_truncate(sequence, self.max_seq_len, padding=padding, truncating=truncating)\n\n\nclass BERTClassificationDataset(Dataset):\n bert_baseline_input_colses = {\n 'bert': ['text_bert_indices']\n\n }\n\n def __init__(self, dataset_list, tokenizer, opt):\n lines = load_apc_datasets(dataset_list)\n\n all_data = []\n\n label_set = set()\n\n for i in tqdm.tqdm(range(len(lines)), postfix='building word indices...'):\n line = lines[i].strip().split('$LABEL$')\n text, label = line[0], line[1]\n text = text.strip().lower()\n label = label.strip().lower()\n text_indices = tokenizer.text_to_sequence('[CLS] {} [SEP]'.format(text))\n\n label = int(label)\n\n data = {\n 'text_bert_indices': text_indices,\n 'label': label,\n }\n\n label_set.add(label)\n\n all_data.append(data)\n\n check_and_fix_labels(label_set, 'label', all_data)\n opt.polarities_dim = len(label_set)\n\n self.data = all_data\n\n def __getitem__(self, index):\n return self.data[index]\n\n def __len__(self):\n return len(self.data)\n", "# -*- coding: utf-8 -*-\n# file: lcf_atepc.py\n# author: yangheng <yangheng@m.scnu.edu.cn>\n# Copyright (C) 2019. All Rights Reserved.\n\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.nn import CrossEntropyLoss\nfrom transformers.models.bert.modeling_bert import BertForTokenClassification, BertPooler\n\nfrom pyabsa.network.sa_encoder import Encoder\nfrom pyabsa.core.atepc.dataset_utils.data_utils_for_training import SENTIMENT_PADDING\n\n\nclass LCFS_ATEPC(BertForTokenClassification):\n\n def __init__(self, bert_base_model, opt):\n super(LCFS_ATEPC, self).__init__(config=bert_base_model.config)\n config = bert_base_model.config\n self.bert4global = bert_base_model\n self.opt = opt\n self.bert4local = self.bert4global\n\n self.dropout = nn.Dropout(self.opt.dropout)\n self.SA1 = Encoder(config, opt)\n self.SA2 = Encoder(config, opt)\n self.linear_double = nn.Linear(opt.hidden_dim * 2, opt.hidden_dim)\n self.linear_triple = nn.Linear(opt.hidden_dim * 3, opt.hidden_dim)\n\n self.pooler = BertPooler(config)\n self.dense = torch.nn.Linear(opt.hidden_dim, opt.polarities_dim)\n\n def get_batch_token_labels_bert_base_indices(self, labels):\n if labels is None:\n return\n # convert tags of BERT-SPC input to BERT-BASE format\n labels = labels.detach().cpu().numpy()\n for text_i in range(len(labels)):\n sep_index = np.argmax((labels[text_i] == 5))\n labels[text_i][sep_index + 1:] = 0\n return torch.tensor(labels).to(self.opt.device)\n\n def get_ids_for_local_context_extractor(self, text_indices):\n # convert BERT-SPC input to BERT-BASE format\n text_ids = text_indices.detach().cpu().numpy()\n for text_i in range(len(text_ids)):\n sep_index = np.argmax((text_ids[text_i] == 102))\n text_ids[text_i][sep_index + 1:] = 0\n return torch.tensor(text_ids).to(self.opt.device)\n\n def forward(self, input_ids_spc,\n token_type_ids=None,\n attention_mask=None,\n labels=None,\n polarity=None,\n valid_ids=None,\n attention_mask_label=None,\n lcf_cdm_vec=None,\n lcf_cdw_vec=None\n ):\n if not self.opt.use_bert_spc:\n input_ids = self.get_ids_for_local_context_extractor(input_ids_spc)\n labels = self.get_batch_token_labels_bert_base_indices(labels)\n global_context_out = self.bert4global(input_ids, token_type_ids, attention_mask)['last_hidden_state']\n else:\n global_context_out = self.bert4global(input_ids_spc, token_type_ids, attention_mask)['last_hidden_state']\n\n batch_size, max_len, feat_dim = global_context_out.shape\n global_valid_output = torch.zeros(batch_size, max_len, feat_dim, dtype=torch.float32).to(self.opt.device)\n for i in range(batch_size):\n jj = -1\n for j in range(max_len):\n if valid_ids[i][j].item() == 1:\n jj += 1\n global_valid_output[i][jj] = global_context_out[i][j]\n global_context_out = self.dropout(global_valid_output)\n ate_logits = self.classifier(global_context_out)\n\n if lcf_cdm_vec is not None or lcf_cdw_vec is not None:\n local_context_ids = self.get_ids_for_local_context_extractor(input_ids_spc)\n local_context_out = self.bert4local(local_context_ids)['last_hidden_state']\n batch_size, max_len, feat_dim = local_context_out.shape\n local_valid_output = torch.zeros(batch_size, max_len, feat_dim, dtype=torch.float32).to(self.opt.device)\n for i in range(batch_size):\n jj = -1\n for j in range(max_len):\n if valid_ids[i][j].item() == 1:\n jj += 1\n local_valid_output[i][jj] = local_context_out[i][j]\n local_context_out = self.dropout(local_valid_output)\n\n if 'cdm' in self.opt.lcf:\n cdm_context_out = torch.mul(local_context_out, lcf_cdm_vec)\n cdm_context_out = self.SA1(cdm_context_out)\n cat_out = torch.cat((global_context_out, cdm_context_out), dim=-1)\n cat_out = self.linear_double(cat_out)\n elif 'cdw' in self.opt.lcf:\n cdw_context_out = torch.mul(local_context_out, lcf_cdw_vec)\n cdw_context_out = self.SA1(cdw_context_out)\n cat_out = torch.cat((global_context_out, cdw_context_out), dim=-1)\n cat_out = self.linear_double(cat_out)\n elif 'fusion' in self.opt.lcf:\n cdm_context_out = torch.mul(local_context_out, lcf_cdm_vec)\n cdw_context_out = torch.mul(local_context_out, lcf_cdw_vec)\n cat_out = torch.cat((global_context_out, cdw_context_out, cdm_context_out), dim=-1)\n cat_out = self.linear_triple(cat_out)\n sa_out = self.SA2(cat_out)\n pooled_out = self.pooler(sa_out)\n pooled_out = self.dropout(pooled_out)\n apc_logits = self.dense(pooled_out)\n else:\n apc_logits = None\n\n if labels is not None:\n criterion_ate = CrossEntropyLoss(ignore_index=0)\n criterion_apc = CrossEntropyLoss(ignore_index=SENTIMENT_PADDING)\n loss_ate = criterion_ate(ate_logits.view(-1, self.num_labels), labels.view(-1))\n loss_apc = criterion_apc(apc_logits, polarity)\n return loss_ate, loss_apc\n else:\n return ate_logits, apc_logits\n" ]
[ [ "numpy.ones", "numpy.asarray" ], [ "torch.nn.Linear", "torch.zeros", "torch.nn.Dropout", "torch.mul", "torch.cat", "numpy.argmax", "torch.tensor", "torch.nn.CrossEntropyLoss" ] ]
SU-ECE-17-7/ibeis
[ "b12a45b06d8ce8f52585494c15f6776f5889ed67", "b12a45b06d8ce8f52585494c15f6776f5889ed67", "b12a45b06d8ce8f52585494c15f6776f5889ed67" ]
[ "_broken/test_sql_numpy.py", "ibeis/viz/interact/interact_matches.py", "ibeis/gui/id_review_api.py" ]
[ "#!/usr/bin/env python2.7\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\nfrom six.moves import range\nimport numpy as np\nimport utool\nfrom ibeis.control import SQLDatabaseControl as sqldbc\nfrom ibeis.control._sql_helpers import _results_gen\nfrom os.path import join\nprint, print_, printDBG, rrr, profile = utool.inject(__name__, '[TEST_SQL_NUMPY] ')\n\n\n# list of 10,000 chips with 3,000 features apeice.\ndef grab_numpy_testdata(shape=(3e3, 128), dtype=np.uint8):\n ndata = utool.get_argval('--ndata', type_=int, default=2)\n print('[TEST] build ndata=%d numpy arrays with shape=%r' % (ndata, shape))\n print(' * expected_memory(table_list) = %s' % utool.byte_str2(ndata * np.product(shape)))\n table_list = [np.empty(shape, dtype=dtype) for i in range(ndata)]\n print(' * memory+overhead(table_list) = %s' % utool.byte_str2(utool.get_object_size(table_list)))\n return table_list\n\n\ndef TEST_SQL_NUMPY():\n sqldb_fname = 'temp_test_sql_numpy.sqlite3'\n sqldb_dpath = utool.util_cplat.get_app_resource_dir('ibeis', 'testfiles')\n utool.ensuredir(sqldb_dpath)\n utool.util_path.remove_file(join(sqldb_dpath, sqldb_fname), dryrun=False)\n db = sqldbc.SQLDatabaseController(sqldb_dpath=sqldb_dpath,\n sqldb_fname=sqldb_fname)\n\n db.add_table('temp', [\n ('temp_id', 'INTEGER PRIMARY KEY'),\n ('temp_hash', 'NUMPY'),\n ])\n\n tt = utool.tic()\n feats_list = grab_numpy_testdata(shape=(3e3, 128), dtype=np.uint8)\n print(' * numpy.new time=%r sec' % utool.toc(tt))\n\n print('[TEST] insert numpy arrays')\n tt = utool.tic()\n feats_iter = ((feats, ) for feats in feats_list)\n db.executemany(operation='''\n INSERT\n INTO temp\n (\n temp_hash\n )\n VALUES (?)\n ''', params_iter=feats_iter)\n print(' * execute insert time=%r sec' % utool.toc(tt))\n\n print('[TEST] save sql database')\n tt = utool.tic()\n #db.cur.commit()\n db.connection.commit()\n print(' * commit time=%r sec' % utool.toc(tt))\n\n print('[TEST] read from sql database')\n\n tt = utool.tic()\n db.cur.execute('SELECT temp_hash FROM temp', [])\n print(' * execute select time=%r sec' % utool.toc(tt))\n\n tt = utool.tic()\n result_list = _results_gen(db.cur)\n print(' * iter results time=%r sec' % utool.toc(tt))\n print(' * memory(result_list) = %s' % utool.byte_str2(utool.get_object_size(result_list)))\n del result_list\n #print('[TEST] result_list=%r' % result_list)\n\n print('[TEST] dump sql database')\n tt = utool.tic()\n db.dump('temp.dump.txt')\n print(' * dump time=%r sec' % utool.toc(tt))\n #with open('temp.dump.txt') as file_:\n # print(file_.read())\n return locals()\n\n\nif __name__ == '__main__':\n import multiprocessing\n multiprocessing.freeze_support() # For win32\n test_locals = utool.run_test(TEST_SQL_NUMPY)\n execstr = utool.execstr_dict(test_locals, 'test_locals')\n exec(execstr)\n", "# -*- coding: utf-8 -*-\n\"\"\"\nSingle VsOne Chip Match Interface\nFor VsMany Interaction\n\nInteraction for looking at matches between a single query and database annotation\n\nMain development file\n\nCommandLine:\n python -m ibeis.viz.interact.interact_matches --test-show_coverage --show\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport utool as ut\nimport numpy as np\nimport plottool as pt\nimport six\nfrom plottool import interact_helpers as ih\nfrom ibeis import viz\nfrom ibeis.algo.hots import scoring\nfrom ibeis.algo.hots import hstypes\nfrom ibeis.viz import viz_helpers as vh\nfrom ibeis.viz import viz_hough\nfrom ibeis.viz import viz_chip\nfrom plottool import interact_matches\nfrom ibeis.viz.interact.interact_chip import ishow_chip\n(print, rrr, profile) = ut.inject2(__name__, '[interact_matches]')\n\n\ndef testdata_match_interact(**kwargs):\n \"\"\"\n CommandLine:\n python -m ibeis.viz.interact.interact_matches --test-testdata_match_interact --show --db PZ_MTEST --qaid 3\n\n Example:\n >>> # VIZ_DOCTEST\n >>> from ibeis.viz.interact.interact_matches import * # NOQA\n >>> import plottool as pt\n >>> kwargs = {}\n >>> mx = ut.get_argval('--mx', type_=int, default=None)\n >>> self = testdata_match_interact(mx=mx, **kwargs)\n >>> pt.show_if_requested()\n \"\"\"\n import ibeis\n qreq_ = ibeis.testdata_qreq_(defaultdb='testdb1', t=['default:Knorm=3'])\n ibs = qreq_.ibs\n cm = qreq_.execute()[0]\n cm.sortself()\n aid2 = None\n self = MatchInteraction(ibs, cm, aid2, mode=1, dodraw=False, qreq_=qreq_, **kwargs)\n self.start()\n return self\n\n\n# TODO inherit from AbstractInteraction\n@six.add_metaclass(ut.ReloadingMetaclass)\nclass MatchInteraction(interact_matches.MatchInteraction2):\n \"\"\"\n Plots a chip result and sets up callbacks for interaction.\n\n SeeAlso:\n plottool.interact_matches.MatchInteraction2\n\n CommandLine:\n python -m ibeis.viz.interact.interact_matches --test-testdata_match_interact --show --db PZ_MTEST --qaid 3\n \"\"\"\n def __init__(self, ibs, cm, aid2=None, fnum=None,\n qreq_=None, figtitle='Match Interaction',\n **kwargs):\n #print('[ibs] MatchInteraction.__init__')\n self.ibs = ibs\n self.cm = cm\n self.qreq_ = qreq_\n # Unpack Args\n if aid2 is None:\n index = 0\n # FIXME: no sortself\n cm.sortself()\n self.rank = index\n else:\n index = cm.daid2_idx.get(aid2, None)\n # TODO: rank?\n self.rank = None\n if index is not None:\n self.qaid = self.cm.qaid\n self.daid = self.cm.daid_list[index]\n fm = self.cm.fm_list[index]\n fk = self.cm.fk_list[index]\n fsv = self.cm.fsv_list[index]\n if self.cm.fs_list is None:\n fs_list = self.cm.get_fsv_prod_list()\n else:\n fs_list = self.cm.fs_list\n fs = None if fs_list is None else fs_list[index]\n H1 = None if self.cm.H_list is None else cm.H_list[index]\n self.score = None if self.cm.score_list is None else self.cm.score_list[index]\n else:\n self.qaid = self.cm.qaid\n self.daid = aid2\n fm = np.empty((0, 2), dtype=hstypes.FM_DTYPE)\n fk = np.empty(0, dtype=hstypes.FK_DTYPE)\n fsv = np.empty((0, 2), dtype=hstypes.FS_DTYPE)\n fs = np.empty(0, dtype=hstypes.FS_DTYPE)\n H1 = None\n self.score = None\n\n # Read properties\n self.query_config2_ = (None if self.qreq_ is None else\n self.qreq_.extern_query_config2)\n self.data_config2_ = (None if self.qreq_ is None else\n self.qreq_.extern_data_config2)\n\n rchip1 = vh.get_chips(ibs, [self.qaid], config2_=self.query_config2_)[0]\n rchip2 = vh.get_chips(ibs, [self.daid], config2_=self.data_config2_)[0]\n\n kpts1 = ibs.get_annot_kpts([self.qaid], config2_=self.query_config2_)[0]\n kpts2 = ibs.get_annot_kpts([self.daid], config2_=self.data_config2_)[0]\n\n vecs1 = ibs.get_annot_vecs([self.qaid], config2_=self.query_config2_)[0]\n vecs2 = ibs.get_annot_vecs([self.daid], config2_=self.data_config2_)[0]\n\n self.figtitle = figtitle\n self.kwargs = kwargs\n self.fnum2 = pt.next_fnum()\n\n super(MatchInteraction, self).__init__(rchip1, rchip2, kpts1, kpts2,\n fm, fs, fsv, vecs1, vecs2, H1,\n H2=None, fk=fk, fnum=fnum,\n **kwargs)\n\n #def plot(self, fnum, pnum):\n def chipmatch_view(self, fnum=None, pnum=(1, 1, 1), verbose=None, **kwargs_):\n \"\"\"\n just visualizes the matches using some type of lines\n\n CommandLine:\n python -m ibeis.viz.interact.interact_matches --test-chipmatch_view --show\n\n Example:\n >>> # DISABLE_DOCTEST\n >>> from ibeis.viz.interact.interact_matches import * # NOQA\n >>> self = testdata_match_interact()\n >>> self.chipmatch_view()\n >>> pt.show_if_requested()\n \"\"\"\n if fnum is None:\n fnum = self.fnum\n if verbose is None:\n verbose = ut.VERBOSE\n\n ibs = self.ibs\n aid = self.daid\n qaid = self.qaid\n figtitle = self.figtitle\n\n # drawing mode draw: with/without lines/feats\n mode = kwargs_.get('mode', self.mode)\n draw_ell = mode >= 1\n draw_lines = mode == 2\n #self.mode = (self.mode + 1) % 3\n pt.figure(fnum=fnum, docla=True, doclf=True)\n show_matches_kw = self.kwargs.copy()\n show_matches_kw.update(\n dict(fnum=fnum, pnum=pnum, draw_lines=draw_lines,\n draw_ell=draw_ell, colorbar_=True, vert=self.vert))\n show_matches_kw.update(kwargs_)\n\n if self.warp_homog:\n show_matches_kw['H1'] = self.H1\n\n #show_matches_kw['score'] = self.score\n show_matches_kw['rawscore'] = self.score\n show_matches_kw['aid2_raw_rank'] = self.rank\n tup = viz.viz_matches.show_matches2(ibs, self.qaid, self.daid,\n self.fm, self.fs,\n qreq_=self.qreq_,\n **show_matches_kw)\n ax, xywh1, xywh2 = tup\n self.xywh2 = xywh2\n\n pt.set_figtitle(figtitle + ' ' + vh.get_vsstr(qaid, aid))\n\n def sv_view(self, dodraw=True):\n \"\"\" spatial verification view\n\n \"\"\"\n #fnum = viz.FNUMS['special']\n aid = self.daid\n fnum = pt.next_fnum()\n fig = pt.figure(fnum=fnum, docla=True, doclf=True)\n ih.disconnect_callback(fig, 'button_press_event')\n viz.viz_sver.show_sver(self.ibs, self.qaid, aid2=aid, fnum=fnum)\n if dodraw:\n #self.draw()\n pt.draw()\n\n def show_coverage(self, dodraw=True):\n \"\"\"\n CommandLine:\n python -m ibeis.viz.interact.interact_matches --test-show_coverage --show\n python -m ibeis.viz.interact.interact_matches --test-show_coverage\n\n Example:\n >>> # DISABLE_DOCTEST\n >>> from ibeis.viz.interact.interact_matches import * # NOQA\n >>> self = testdata_match_interact(mx=1)\n >>> self.show_coverage(dodraw=False)\n >>> pt.show_if_requested()\n \"\"\"\n masks_list = scoring.get_masks(self.qreq_, self.cm)\n scoring.show_coverage_mask(self.qreq_, self.cm, masks_list)\n if dodraw:\n #self.draw()\n pt.draw()\n\n def show_each_chip(self):\n viz_chip.show_chip(self.ibs, self.qaid, fnum=pt.next_fnum(), nokpts=True)\n viz_chip.show_chip(self.ibs, self.daid, fnum=pt.next_fnum(), nokpts=True)\n pt.draw()\n #self.draw()\n\n def show_each_fgweight_chip(self):\n viz_chip.show_chip(self.ibs, self.qaid, fnum=pt.next_fnum(),\n weight_label='fg_weights')\n viz_chip.show_chip(self.ibs, self.daid, fnum=pt.next_fnum(),\n weight_label='fg_weights')\n #self.draw()\n pt.draw()\n\n def show_each_dstncvs_chip(self, dodraw=True):\n \"\"\"\n CommandLine:\n python -m ibeis.viz.interact.interact_matches --test-show_each_dstncvs_chip --show\n\n Example:\n >>> # DISABLE_DOCTEST\n >>> from ibeis.viz.interact.interact_matches import * # NOQA\n >>> self = testdata_match_interact(mx=1)\n >>> self.show_each_dstncvs_chip(dodraw=False)\n >>> pt.show_if_requested()\n \"\"\"\n dstncvs1, dstncvs2 = scoring.get_kpts_distinctiveness(self.ibs,\n [self.qaid,\n self.daid])\n print('dstncvs1_stats = ' + ut.get_stats_str(dstncvs1))\n print('dstncvs2_stats = ' + ut.get_stats_str(dstncvs2))\n weight_label = 'dstncvs'\n showkw = dict(weight_label=weight_label, ell=False, pts=True)\n viz_chip.show_chip(self.ibs, self.qaid, weights=dstncvs1,\n fnum=pt.next_fnum(), **showkw)\n viz_chip.show_chip(self.ibs, self.daid, weights=dstncvs2,\n fnum=pt.next_fnum(), **showkw)\n if dodraw:\n #self.draw()\n pt.draw()\n\n def show_each_probchip(self):\n viz_hough.show_probability_chip(self.ibs, self.qaid, fnum=pt.next_fnum())\n viz_hough.show_probability_chip(self.ibs, self.daid, fnum=pt.next_fnum())\n pt.draw()\n #self.draw()\n\n def dev_reload(self):\n ih.disconnect_callback(self.fig, 'button_press_event')\n self.rrr()\n self.set_callbacks()\n\n def dev_embed(self):\n ut.embed()\n\n def toggle_samefig(self):\n self.same_fig = not self.same_fig\n if self.mx is not None:\n self.select_ith_match(self.mx)\n self.draw()\n\n def query_last_feature(self):\n ibs = self.ibs\n qaid = self.qaid\n viz.show_nearest_descriptors(ibs, qaid, self.last_fx, pt.next_fnum(),\n qreq_=self.qreq_, draw_chip=True)\n fig3 = pt.gcf()\n ih.connect_callback(fig3, 'button_press_event', self.on_click)\n pt.draw()\n\n def get_popup_options(self):\n from ibeis.gui import inspect_gui\n options = []\n\n ax = pt.gca() # HACK\n\n from plottool import plot_helpers as ph\n viztype = ph.get_plotdat(ax, 'viztype', '')\n is_match_type = viztype in ['matches', 'multi_match']\n\n if is_match_type:\n options += inspect_gui.get_aidpair_context_menu_options(\n self.ibs, self.qaid, self.daid, self.cm,\n qreq_=self.qreq_,\n #update_callback=self.show_page,\n #backend_callback=None, aid_list=aid_list)\n )\n\n options += [\n #('Toggle same_fig', self.toggle_samefig),\n #('Toggle vert', self.toggle_vert),\n ('query last feature', self.query_last_feature),\n ('show each chip', self.show_each_chip),\n ('show each distinctiveness chip', self.show_each_dstncvs_chip),\n ('show each foreground weight chip', self.show_each_fgweight_chip),\n ('show each probchip', self.show_each_probchip),\n ('show coverage', self.show_coverage),\n #('show each probchip', self.query_last_feature),\n ]\n\n #options.append(('name_interaction', self.name_interaction))\n #if self.H1 is not None:\n # options.append(('Toggle homog', self.toggle_homog))\n if ut.is_developer():\n options.append(('dev_reload', self.dev_reload))\n options.append(('dev_embed', self.dev_embed))\n #options.append(('cancel', lambda: print('cancel')))\n options += super(MatchInteraction, self).get_popup_options()\n\n return options\n #self.show_popup_menu(options, event)\n\n # Callback\n def on_click_inside(self, event, ax):\n from plottool import plot_helpers as ph\n ibs = self.ibs\n viztype = ph.get_plotdat(ax, 'viztype', '')\n is_match_type = viztype in ['matches', 'multi_match']\n\n key = '' if event.key is None else event.key\n print('key=%r ' % key)\n ctrl_down = key.find('control') == 0\n # Click in match axes\n if event.button == 3:\n return super(MatchInteraction, self).on_click_inside(event, ax)\n if is_match_type and ctrl_down:\n # Ctrl-Click\n print('.. control click')\n return self.sv_view()\n elif viztype in ['warped', 'unwarped']:\n print('clicked at patch')\n ut.print_dict(ph.get_plotdat_dict(ax))\n hs_aid = {\n 'aid1': self.qaid,\n 'aid2': self.daid,\n }[vh.get_ibsdat(ax, 'aid', None)]\n hs_fx = vh.get_ibsdat(ax, 'fx', None)\n print('hs_fx = %r' % (hs_fx,))\n print('hs_aid = %r' % (hs_aid,))\n if hs_aid is not None and viztype == 'unwarped':\n ishow_chip(ibs, hs_aid, fx=hs_fx, fnum=pt.next_fnum())\n elif hs_aid is not None and viztype == 'warped':\n viz.show_keypoint_gradient_orientations(ibs, hs_aid, hs_fx,\n fnum=pt.next_fnum())\n else:\n return super(MatchInteraction, self).on_click_inside(event, ax)\n self.draw()\n\nif __name__ == '__main__':\n \"\"\"\n CommandLine:\n python -m ibeis.viz.interact.interact_matches\n python -m ibeis.viz.interact.interact_matches --allexamples\n python -m ibeis.viz.interact.interact_matches --allexamples --noface --nosrc\n \"\"\"\n import multiprocessing\n multiprocessing.freeze_support() # for win32\n import utool as ut # NOQA\n ut.doctest_funcs()\n", "# -*- coding: utf-8 -*-\n\"\"\"\nCommandLine:\n python -m ibeis.gui.inspect_gui --test-test_review_widget --show\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nfrom functools import partial\nfrom ibeis.viz import viz_helpers as vh\nimport guitool as gt\nimport numpy as np\nimport utool as ut\n(print, rrr, profile) = ut.inject2(__name__, '[id_review_api]')\n\n\nMATCHED_STATUS_TEXT = 'Matched'\nREVIEWED_STATUS_TEXT = 'Reviewed'\n\n\nREVIEW_CFG_DEFAULTS = {\n 'ranks_top': 5,\n 'directed': False,\n 'name_scoring': True,\n 'filter_reviewed': True,\n 'filter_photobombs': True,\n 'filter_true_matches': True,\n 'show_chips': True,\n 'filter_duplicate_true_matches': False,\n}\n\n\n@profile\ndef get_review_edges(cm_list, ibs=None, review_cfg={}):\n r\"\"\"\n Needs to be moved to a better file. Maybe something to do with\n identification.\n\n Returns a list of matches that should be inspected\n This function is more lightweight than orgres or allres.\n Used in id_review_api and interact_qres2\n\n Args:\n cm_list (list): list of chip match objects\n ranks_top (int): put all ranks less than this number into the graph\n directed (bool):\n\n Returns:\n tuple: review_edges = (qaid_arr, daid_arr, score_arr, rank_arr)\n\n CommandLine:\n python -m ibeis.gui.id_review_api get_review_edges:0\n\n Example0:\n >>> # ENABLE_DOCTEST\n >>> from ibeis.gui.id_review_api import * # NOQA\n >>> import ibeis\n >>> ibs = ibeis.opendb('PZ_MTEST')\n >>> qreq_ = ibeis.main_helpers.testdata_qreq_()\n >>> cm_list = qreq_.execute()\n >>> review_cfg = dict(ranks_top=5, directed=True, name_scoring=False,\n >>> filter_true_matches=True)\n >>> review_edges = get_review_edges(cm_list, ibs=ibs, review_cfg=review_cfg)\n >>> print(review_edges)\n\n Example1:\n >>> # UNSTABLE_DOCTEST\n >>> from ibeis.gui.id_review_api import * # NOQA\n >>> import ibeis\n >>> ibs = ibeis.opendb('PZ_MTEST')\n >>> qaid_list = ibs.get_valid_aids()[0:5]\n >>> daid_list = ibs.get_valid_aids()[0:20]\n >>> cm_list = ibs.query_chips(qaid_list, daid_list)\n >>> review_cfg = dict(ranks_top=5, directed=True, name_scoring=False,\n >>> filter_reviewed=False, filter_true_matches=True)\n >>> review_edges = get_review_edges(cm_list, review_cfg=review_cfg, ibs=ibs)\n >>> print(review_edges)\n\n Example3:\n >>> # UNSTABLE_DOCTEST\n >>> from ibeis.gui.id_review_api import * # NOQA\n >>> import ibeis\n >>> ibs = ibeis.opendb('PZ_MTEST')\n >>> qaid_list = ibs.get_valid_aids()[0:1]\n >>> daid_list = ibs.get_valid_aids()[10:100]\n >>> qaid2_cm = ibs.query_chips(qaid_list, daid_list)\n >>> review_cfg = dict(ranks_top=1, directed=False, name_scoring=False,\n >>> filter_reviewed=False, filter_true_matches=True)\n >>> review_edges = get_review_edges(cm_list, review_cfg=review_cfg, ibs=ibs)\n >>> print(review_edges)\n\n Example4:\n >>> # UNSTABLE_DOCTEST\n >>> from ibeis.gui.id_review_api import * # NOQA\n >>> import ibeis\n >>> ibs = ibeis.opendb('PZ_MTEST')\n >>> qaid_list = ibs.get_valid_aids()[0:10]\n >>> daid_list = ibs.get_valid_aids()[0:10]\n >>> qres_list = ibs.query_chips(qaid_list, daid_list)\n >>> ranks_top = 3\n >>> review_cfg = dict(ranks_top=3, directed=False, name_scoring=False,\n >>> filter_reviewed=False, filter_true_matches=True)\n >>> review_edges = get_review_edges(cm_list, review_cfg=review_cfg, ibs=ibs)\n >>> print(review_edges)\n \"\"\"\n import vtool as vt\n from ibeis.algo.hots import chip_match\n automatch_kw = REVIEW_CFG_DEFAULTS.copy()\n automatch_kw = ut.update_existing(automatch_kw, review_cfg)\n print('[resorg] get_review_edges(%s)' % (ut.repr2(automatch_kw)))\n print('[resorg] len(cm_list) = %d' % (len(cm_list)))\n qaids_stack = []\n daids_stack = []\n ranks_stack = []\n scores_stack = []\n\n # For each QueryResult, Extract inspectable candidate matches\n if isinstance(cm_list, dict):\n cm_list = list(cm_list.values())\n\n if len(cm_list) == 0:\n return ([], [], [], [])\n\n for cm in cm_list:\n if isinstance(cm, chip_match.ChipMatch):\n daids = cm.get_top_aids(ntop=automatch_kw['ranks_top'])\n scores = cm.get_top_scores(ntop=automatch_kw['ranks_top'])\n ranks = np.arange(len(daids))\n qaids = np.full(daids.shape, cm.qaid, dtype=daids.dtype)\n else:\n (qaids, daids, scores, ranks) = cm.get_match_tbldata(\n ranks_top=automatch_kw['ranks_top'],\n name_scoring=automatch_kw['name_scoring'],\n ibs=ibs)\n qaids_stack.append(qaids)\n daids_stack.append(daids)\n scores_stack.append(scores)\n ranks_stack.append(ranks)\n\n # Stack them into a giant array\n qaid_arr = np.hstack(qaids_stack)\n daid_arr = np.hstack(daids_stack)\n score_arr = np.hstack(scores_stack)\n rank_arr = np.hstack(ranks_stack)\n\n # Sort by scores\n sortx = score_arr.argsort()[::-1]\n qaid_arr = qaid_arr[sortx]\n daid_arr = daid_arr[sortx]\n score_arr = score_arr[sortx]\n rank_arr = rank_arr[sortx]\n\n if automatch_kw['filter_reviewed']:\n _is_reviewed = ibs.get_annot_pair_is_reviewed(qaid_arr.tolist(),\n daid_arr.tolist())\n is_unreviewed = ~np.array(_is_reviewed, dtype=np.bool)\n qaid_arr = qaid_arr.compress(is_unreviewed)\n daid_arr = daid_arr.compress(is_unreviewed)\n score_arr = score_arr.compress(is_unreviewed)\n rank_arr = rank_arr.compress(is_unreviewed)\n\n # Remove directed edges\n if not automatch_kw['directed']:\n #nodes = np.unique(directed_edges.flatten())\n directed_edges = np.vstack((qaid_arr, daid_arr)).T\n #idx1, idx2 = vt.intersect2d_indices(directed_edges, directed_edges[:, ::-1])\n\n unique_rowx = vt.find_best_undirected_edge_indexes(directed_edges,\n score_arr)\n\n qaid_arr = qaid_arr.take(unique_rowx)\n daid_arr = daid_arr.take(unique_rowx)\n score_arr = score_arr.take(unique_rowx)\n rank_arr = rank_arr.take(unique_rowx)\n\n # Filter Double Name Matches\n if automatch_kw['filter_duplicate_true_matches']:\n # filter_dup_namepairs\n qnid_arr = ibs.get_annot_nids(qaid_arr)\n dnid_arr = ibs.get_annot_nids(daid_arr)\n if not automatch_kw['directed']:\n directed_name_edges = np.vstack((qnid_arr, dnid_arr)).T\n unique_rowx2 = vt.find_best_undirected_edge_indexes(\n directed_name_edges, score_arr)\n else:\n namepair_id_list = np.array(vt.compute_unique_data_ids_(\n list(zip(qnid_arr, dnid_arr))))\n unique_namepair_ids, namepair_groupxs = vt.group_indices(namepair_id_list)\n score_namepair_groups = vt.apply_grouping(score_arr, namepair_groupxs)\n unique_rowx2 = np.array(sorted([\n groupx[score_group.argmax()]\n for groupx, score_group in zip(namepair_groupxs, score_namepair_groups)\n ]), dtype=np.int32)\n qaid_arr = qaid_arr.take(unique_rowx2)\n daid_arr = daid_arr.take(unique_rowx2)\n score_arr = score_arr.take(unique_rowx2)\n rank_arr = rank_arr.take(unique_rowx2)\n\n # Filter all true matches\n if automatch_kw['filter_true_matches']:\n qnid_arr = ibs.get_annot_nids(qaid_arr)\n dnid_arr = ibs.get_annot_nids(daid_arr)\n valid_flags = qnid_arr != dnid_arr\n qaid_arr = qaid_arr.compress(valid_flags)\n daid_arr = daid_arr.compress(valid_flags)\n score_arr = score_arr.compress(valid_flags)\n rank_arr = rank_arr.compress(valid_flags)\n\n if automatch_kw['filter_photobombs']:\n unique_aids = ut.unique(ut.flatten([qaid_arr, daid_arr]))\n #grouped_aids, unique_nids = ibs.group_annots_by_name(unique_aids)\n invalid_nid_map = get_photobomber_map(ibs, qaid_arr)\n\n nid2_aids = ut.group_items(unique_aids, ibs.get_annot_nids(unique_aids))\n\n expanded_aid_map = ut.ddict(set)\n for nid1, other_nids in invalid_nid_map.items():\n for aid1 in nid2_aids[nid1]:\n for nid2 in other_nids:\n for aid2 in nid2_aids[nid2]:\n expanded_aid_map[aid1].add(aid2)\n expanded_aid_map[aid2].add(aid1)\n\n valid_flags = [daid not in expanded_aid_map[qaid]\n for qaid, daid in zip(qaid_arr, daid_arr)]\n qaid_arr = qaid_arr.compress(valid_flags)\n daid_arr = daid_arr.compress(valid_flags)\n score_arr = score_arr.compress(valid_flags)\n rank_arr = rank_arr.compress(valid_flags)\n\n review_edges = (qaid_arr, daid_arr, score_arr, rank_arr)\n return review_edges\n\n\ndef make_review_api(ibs, cm_list, review_cfg, qreq_=None):\n #ranks_top=None, #name_scoring=False, #filter_reviewed=False, #filter_true_matches=False, #qreq_=None, #):\n \"\"\"\n Builds columns which are displayable in a ColumnListTableWidget\n\n CommandLine:\n python -m ibeis.gui.id_review_api --test-test_review_widget --show\n python -m ibeis.gui.id_review_api --test-make_review_api\n\n Example:\n >>> # ENABLE_DOCTEST\n >>> from ibeis.gui.id_review_api import * # NOQA\n >>> import ibeis\n >>> import guitool as gt\n >>> from ibeis.gui import id_review_api\n >>> cm_list, qreq_ = ibeis.main_helpers.testdata_cmlist()\n >>> tblname = 'chipmatch'\n >>> name_scoring = False\n >>> ranks_top = 5\n >>> review_cfg = dict(ranks_top=ranks_top, name_scoring=name_scoring)\n >>> review_api = make_review_api(qreq_.ibs, cm_list, review_cfg, qreq_=qreq_)\n >>> print('review_api = %r' % (review_api,))\n \"\"\"\n # TODO: Add in timedelta to column info\n if ut.VERBOSE:\n print('[inspect] make_review_api')\n\n review_edges = get_review_edges(cm_list, ibs=ibs, review_cfg=review_cfg)\n # Get extra info\n (qaids, daids, scores, ranks) = review_edges\n\n RES_THUMB_TEXT = 'ResThumb' # NOQA\n QUERY_THUMB_TEXT = 'querythumb'\n MATCH_THUMB_TEXT = 'MatchThumb'\n\n col_name_list = [\n 'result_index',\n 'score',\n REVIEWED_STATUS_TEXT,\n ]\n\n if review_cfg.get('show_chips', True):\n col_name_list += [\n MATCHED_STATUS_TEXT,\n QUERY_THUMB_TEXT,\n ]\n\n col_name_list += [\n RES_THUMB_TEXT,\n 'qaid',\n 'aid',\n 'rank',\n 'timedelta',\n 'dnGt',\n 'qnGt',\n 'tags',\n 'qname',\n 'name',\n ]\n\n col_types_dict = dict([\n ('qaid', int),\n ('aid', int),\n ('dnGt', int),\n ('qnGt', int),\n ('timedelta', float),\n #('review', 'BUTTON'),\n (MATCHED_STATUS_TEXT, str),\n (REVIEWED_STATUS_TEXT, str),\n (QUERY_THUMB_TEXT, 'PIXMAP'),\n (RES_THUMB_TEXT, 'PIXMAP'),\n ('qname', str),\n ('name', str),\n ('score', float),\n ('rank', int),\n ('truth', bool),\n ('opt', int),\n ('result_index', int),\n ])\n timedelta_list = np.array(ut.take_column(ibs.get_unflat_annots_timedelta_list(list(zip(qaids, daids))), 0))\n # TODO: make a display role\n #timediff_list = [ut.get_posix_timedelta_str(t, year=True, approx=True) for t in (timedelta_list * 60 * 60)]\n\n def get_pair_tags(edge):\n aid1, aid2 = edge\n assert not ut.isiterable(aid1), 'aid1=%r, aid2=%r' % (aid1, aid2)\n assert not ut.isiterable(aid2), 'aid1=%r, aid2=%r' % (aid1, aid2)\n am_rowids = ibs.get_annotmatch_rowid_from_undirected_superkey(\n [aid1], [aid2])\n tag_text = ibs.get_annotmatch_tag_text(am_rowids)[0]\n if tag_text is None:\n tag_text = ''\n return str(tag_text)\n\n col_getter_dict = dict([\n ('qaid', np.array(qaids)),\n ('aid', np.array(daids)),\n ('dnGt', ibs.get_annot_num_groundtruth),\n ('qnGt', ibs.get_annot_num_groundtruth),\n ('timedelta', np.array(timedelta_list)),\n #('review', lambda rowid: get_buttontup),\n (MATCHED_STATUS_TEXT, partial(get_match_status, ibs)),\n (REVIEWED_STATUS_TEXT, partial(get_reviewed_status, ibs)),\n (QUERY_THUMB_TEXT, ibs.get_annot_chip_thumbtup),\n (RES_THUMB_TEXT, ibs.get_annot_chip_thumbtup),\n ('qname', ibs.get_annot_names),\n ('name', ibs.get_annot_names),\n ('score', np.array(scores)),\n ('rank', np.array(ranks)),\n ('result_index', np.arange(len(ranks))),\n ('tags', get_pair_tags),\n #lambda aid_pair: ibs.get_annotmatch_tag_text(ibs.get_annotmatch_rowid_from_undirected_superkey(ut.ensure_iterable(aid_pair[0]), ut.ensure_iterable(aid_pair[1])))[0]),\n #('truth', truths),\n #('opt', opts),\n ])\n\n # default is 100\n col_width_dict = {\n 'score': 75,\n REVIEWED_STATUS_TEXT: 75,\n MATCHED_STATUS_TEXT: 75,\n 'rank': 42,\n 'qaid': 42,\n 'aid': 42,\n 'result_index': 42,\n 'qname': 60,\n 'name': 60,\n 'dnGt': 50,\n 'timedelta': 75,\n 'tags': 75,\n 'qnGt': 50,\n }\n\n USE_MATCH_THUMBS = 1\n if USE_MATCH_THUMBS:\n\n def get_match_thumbtup(ibs, qaid2_cm, qaids, daids, index, qreq_=None,\n thumbsize=(128, 128), match_thumbtup_cache={}):\n daid = daids[index]\n qaid = qaids[index]\n cm = qaid2_cm[qaid]\n assert cm.qaid == qaid, 'aids do not aggree'\n\n OLD = False\n if OLD:\n fpath = ensure_match_img(ibs, cm, daid, qreq_=qreq_,\n match_thumbtup_cache=match_thumbtup_cache)\n if isinstance(thumbsize, int):\n thumbsize = (thumbsize, thumbsize)\n thumbtup = (ut.augpath(fpath, 'thumb_%d,%d' % thumbsize), fpath, thumbsize,\n [], [])\n return thumbtup\n else:\n # Hacky new way of drawing\n fpath, func, func2 = make_ensure_match_img_nosql_func(qreq_, cm, daid)\n #match_thumbdir = ibs.get_match_thumbdir()\n #match_thumb_fname = get_match_thumb_fname(cm, daid, qreq_)\n #fpath = ut.unixjoin(match_thumbdir, match_thumb_fname)\n thumbdat = {\n 'fpath': fpath,\n 'thread_func': func,\n 'main_func': func2,\n #'args': (ibs, cm, daid),\n #'kwargs': dict(qreq_=qreq_,\n # match_thumbtup_cache=match_thumbtup_cache)\n }\n return thumbdat\n\n col_name_list.insert(col_name_list.index('qaid'),\n MATCH_THUMB_TEXT)\n col_types_dict[MATCH_THUMB_TEXT] = 'PIXMAP'\n #col_types_dict[MATCH_THUMB_TEXT] = CustomMatchThumbDelegate\n qaid2_cm = {cm.qaid: cm for cm in cm_list}\n get_match_thumbtup_ = partial(get_match_thumbtup, ibs, qaid2_cm,\n qaids, daids, qreq_=qreq_,\n match_thumbtup_cache={})\n col_getter_dict[MATCH_THUMB_TEXT] = get_match_thumbtup_\n\n col_bgrole_dict = {\n MATCHED_STATUS_TEXT : partial(get_match_status_bgrole, ibs),\n REVIEWED_STATUS_TEXT: partial(get_reviewed_status_bgrole, ibs),\n }\n # TODO: remove ider dict.\n # it is massively unuseful\n col_ider_dict = {\n MATCHED_STATUS_TEXT : ('qaid', 'aid'),\n REVIEWED_STATUS_TEXT : ('qaid', 'aid'),\n 'tags' : ('qaid', 'aid'),\n QUERY_THUMB_TEXT : ('qaid'),\n RES_THUMB_TEXT : ('aid'),\n 'dnGt' : ('aid'),\n 'qnGt' : ('qaid'),\n 'qname' : ('qaid'),\n 'name' : ('aid'),\n }\n col_setter_dict = {\n 'qname': ibs.set_annot_names,\n 'name': ibs.set_annot_names\n }\n editable_colnames = ['truth', 'notes', 'qname', 'name', 'opt']\n\n sortby = 'score'\n\n def get_thumb_size():\n return ibs.cfg.other_cfg.thumb_size\n\n col_display_role_func_dict = {\n 'timedelta': ut.partial(ut.get_posix_timedelta_str, year=True, approx=2),\n }\n\n if not review_cfg.get('show_chips', True):\n del col_getter_dict[QUERY_THUMB_TEXT]\n del col_getter_dict[RES_THUMB_TEXT]\n del col_types_dict[RES_THUMB_TEXT]\n del col_types_dict[QUERY_THUMB_TEXT]\n del col_ider_dict[RES_THUMB_TEXT]\n del col_ider_dict[QUERY_THUMB_TEXT]\n # del col_bgrole_dict[RES_THUMB_TEXT]\n # del col_bgrole_dict[QUERY_THUMB_TEXT]\n\n # Insert info into dict\n review_api = gt.CustomAPI(\n col_name_list=col_name_list,\n col_types_dict=col_types_dict,\n col_getter_dict=col_getter_dict,\n col_bgrole_dict=col_bgrole_dict,\n col_ider_dict=col_ider_dict,\n col_setter_dict=col_setter_dict,\n editable_colnames=editable_colnames,\n col_display_role_func_dict=col_display_role_func_dict,\n sortby=sortby,\n get_thumb_size=get_thumb_size,\n sort_reverse=True,\n col_width_dict=col_width_dict)\n #review_api.review_edges = review_edges\n return review_api\n\n\ndef get_match_status(ibs, aid_pair):\n \"\"\" Data role for status column \"\"\"\n aid1, aid2 = aid_pair\n assert not ut.isiterable(aid1), 'aid1=%r, aid2=%r' % (aid1, aid2)\n assert not ut.isiterable(aid2), 'aid1=%r, aid2=%r' % (aid1, aid2)\n text = ibs.get_match_text(aid1, aid2)\n if text is None:\n raise AssertionError('impossible state id_review_api')\n return text\n\n\ndef get_reviewed_status(ibs, aid_pair):\n \"\"\" Data role for status column \"\"\"\n aid1, aid2 = aid_pair\n assert not ut.isiterable(aid1), 'aid1=%r, aid2=%r' % (aid1, aid2)\n assert not ut.isiterable(aid2), 'aid1=%r, aid2=%r' % (aid1, aid2)\n state = ibs.get_annot_pair_is_reviewed([aid1], [aid2])[0]\n state_to_text = {\n None: 'Unreviewed',\n 2: 'Auto-reviewed',\n 1: 'User-reviewed',\n }\n default = '??? unknown mode %r' % (state,)\n text = state_to_text.get(state, default)\n return text\n\n\ndef get_match_status_bgrole(ibs, aid_pair):\n \"\"\" Background role for status column \"\"\"\n aid1, aid2 = aid_pair\n truth = ibs.get_match_truth(aid1, aid2)\n #print('get status bgrole: %r truth=%r' % (aid_pair, truth))\n truth_color = vh.get_truth_color(truth, base255=True, lighten_amount=0.35)\n return truth_color\n\n\ndef get_reviewed_status_bgrole(ibs, aid_pair):\n \"\"\" Background role for status column \"\"\"\n aid1, aid2 = aid_pair\n truth = ibs.get_match_truth(aid1, aid2)\n annotmach_reviewed = ibs.get_annot_pair_is_reviewed([aid1], [aid2])[0]\n #truth = ibs.get_annot_pair_truth([aid1], [aid2])[0]\n #print('get status bgrole: %r truth=%r' % (aid_pair, truth))\n if annotmach_reviewed == 0 or annotmach_reviewed is None:\n lighten_amount = .9\n elif annotmach_reviewed == 2:\n lighten_amount = .7\n else:\n lighten_amount = .35\n truth_color = vh.get_truth_color(truth, base255=True,\n lighten_amount=lighten_amount)\n #truth = ibs.get_match_truth(aid1, aid2)\n #print('get status bgrole: %r truth=%r' % (aid_pair, truth))\n #truth_color = vh.get_truth_color(truth, base255=True, lighten_amount=0.35)\n return truth_color\n\n\ndef get_match_thumb_fname(cm, daid, qreq_):\n \"\"\"\n CommandLine:\n python -m ibeis.gui.id_review_api --exec-get_match_thumb_fname\n\n Example:\n >>> # DISABLE_DOCTEST\n >>> from ibeis.gui.id_review_api import * # NOQA\n >>> import ibeis\n >>> cm, qreq_ = ibeis.testdata_cm('PZ_MTEST')\n >>> thumbsize = (128, 128)\n >>> daid = cm.get_top_aids()[0]\n >>> match_thumb_fname = get_match_thumb_fname(cm, daid, qreq_)\n >>> result = match_thumb_fname\n >>> print(result)\n match_aids=1,1_cfgstr=ubpzwu5k54h6xbnr.jpg\n \"\"\"\n # Make thumbnail name\n config_hash = ut.hashstr27(qreq_.get_cfgstr())\n qaid = cm.qaid\n match_thumb_fname = 'match_aids=%d,%d_cfgstr=%s.jpg' % ((qaid, daid,\n config_hash))\n return match_thumb_fname\n\n\ndef ensure_match_img(ibs, cm, daid, qreq_=None, match_thumbtup_cache={}):\n r\"\"\"\n CommandLine:\n python -m ibeis.gui.id_review_api --test-ensure_match_img --show\n\n Example:\n >>> # ENABLE_DOCTEST\n >>> from ibeis.gui.id_review_api import * # NOQA\n >>> import ibeis\n >>> # build test data\n >>> cm, qreq_ = ibeis.testdata_cm()\n >>> daid = cm.get_top_aids()[0]\n >>> match_thumbtup_cache = {}\n >>> # execute function\n >>> match_thumb_fpath_ = ensure_match_img(qreq_.ibs, cm, daid, qreq_,\n >>> match_thumbtup_cache)\n >>> # verify results\n >>> result = str(match_thumb_fpath_)\n >>> print(result)\n >>> ut.quit_if_noshow()\n >>> ut.startfile(match_thumb_fpath_, quote=True)\n \"\"\"\n #from os.path import exists\n match_thumbdir = ibs.get_match_thumbdir()\n match_thumb_fname = get_match_thumb_fname(cm, daid, qreq_)\n match_thumb_fpath_ = ut.unixjoin(match_thumbdir, match_thumb_fname)\n #if exists(match_thumb_fpath_):\n # return match_thumb_fpath_\n if match_thumb_fpath_ in match_thumbtup_cache:\n fpath = match_thumbtup_cache[match_thumb_fpath_]\n else:\n # TODO: just draw the image at the correct thumbnail size\n # TODO: draw without matplotlib?\n #with ut.Timer('render-1'):\n fpath = cm.imwrite_single_annotmatch(\n qreq_, daid, fpath=match_thumb_fpath_, saveax=True, fnum=32,\n notitle=True, verbose=False)\n #with ut.Timer('render-2'):\n # img = cm.render_single_annotmatch(qreq_, daid, fnum=32, notitle=True, dpi=30)\n # cv2.imwrite(match_thumb_fpath_, img)\n # fpath = match_thumb_fpath_\n #with ut.Timer('render-3'):\n #fpath = match_thumb_fpath_\n #render_config = {\n # 'dpi' : 60,\n # 'draw_fmatches' : True,\n # #'vert' : view_orientation == 'vertical',\n # 'show_aidstr' : False,\n # 'show_name' : False,\n # 'show_exemplar' : False,\n # 'show_num_gt' : False,\n # 'show_timedelta' : False,\n # 'show_name_rank' : False,\n # 'show_score' : False,\n # 'show_annot_score' : False,\n # 'show_name_score' : False,\n # 'draw_lbl' : False,\n # 'draw_border' : False,\n #}\n #cm.imwrite_single_annotmatch2(qreq_, daid, fpath, fnum=32, notitle=True, **render_config)\n #print('fpath = %r' % (fpath,))\n match_thumbtup_cache[match_thumb_fpath_] = fpath\n return fpath\n\n\ndef make_ensure_match_img_nosql_func(qreq_, cm, daid):\n r\"\"\"\n CommandLine:\n python -m ibeis.gui.id_review_api --test-ensure_match_img --show\n\n Example:\n >>> # ENABLE_DOCTEST\n >>> from ibeis.gui.id_review_api import * # NOQA\n >>> import ibeis\n >>> # build test data\n >>> cm, qreq_ = ibeis.testdata_cm()\n >>> ibs = qreq_.ibs\n >>> daid = cm.get_top_aids()[0]\n >>> match_thumbtup_cache = {}\n >>> # execute function\n >>> match_thumb_fpath_ = ensure_match_img(qreq_.ibs, cm, daid, qreq_, match_thumbtup_cache)\n >>> # verify results\n >>> result = str(match_thumb_fpath_)\n >>> print(result)\n >>> ut.quit_if_noshow()\n >>> ut.startfile(match_thumb_fpath_, quote=True)\n \"\"\"\n #import ibeis.viz\n from ibeis.viz import viz_matches\n import cv2\n import io\n import plottool as pt\n import vtool as vt\n import matplotlib as mpl\n aid1 = cm.qaid\n aid2 = daid\n\n ibs = qreq_.ibs\n resize_factor = .5\n\n match_thumbdir = ibs.get_match_thumbdir()\n match_thumb_fname = get_match_thumb_fname(cm, daid, qreq_)\n fpath = ut.unixjoin(match_thumbdir, match_thumb_fname)\n\n def main_thread_load():\n # This gets executed in the main thread and collects data\n # from sql\n rchip1_fpath, rchip2_fpath, kpts1, kpts2 = viz_matches._get_annot_pair_info(\n ibs, aid1, aid2, qreq_, draw_fmatches=True, as_fpath=True)\n return rchip1_fpath, rchip2_fpath, kpts1, kpts2\n\n def nosql_draw(check_func, rchip1_fpath, rchip2_fpath, kpts1, kpts2):\n # This gets executed in the child thread and does drawing async style\n #from matplotlib.backends.backend_pdf import FigureCanvasPdf as FigureCanvas\n #from matplotlib.backends.backend_pdf import Figure\n #from matplotlib.backends.backend_svg import FigureCanvas\n #from matplotlib.backends.backend_svg import Figure\n from matplotlib.backends.backend_agg import FigureCanvas\n from matplotlib.backends.backend_agg import Figure\n\n kpts1_ = vt.offset_kpts(kpts1, (0, 0), (resize_factor, resize_factor))\n kpts2_ = vt.offset_kpts(kpts2, (0, 0), (resize_factor, resize_factor))\n\n #from matplotlib.figure import Figure\n if check_func is not None and check_func():\n return\n\n rchip1 = vt.imread(rchip1_fpath)\n rchip1 = vt.resize_image_by_scale(rchip1, resize_factor)\n if check_func is not None and check_func():\n return\n rchip2 = vt.imread(rchip2_fpath)\n rchip2 = vt.resize_image_by_scale(rchip2, resize_factor)\n if check_func is not None and check_func():\n return\n\n try:\n idx = cm.daid2_idx[daid]\n fm = cm.fm_list[idx]\n fsv = None if cm.fsv_list is None else cm.fsv_list[idx]\n fs = None if fsv is None else fsv.prod(axis=1)\n except KeyError:\n fm = []\n fs = None\n fsv = None\n\n maxnum = 200\n if fs is not None and len(fs) > maxnum:\n # HACK TO ONLY SHOW TOP MATCHES\n sortx = fs.argsort()[::-1]\n fm = fm.take(sortx[:maxnum], axis=0)\n fs = fs.take(sortx[:maxnum], axis=0)\n\n was_interactive = mpl.is_interactive()\n if was_interactive:\n mpl.interactive(False)\n #fnum = 32\n fig = Figure()\n canvas = FigureCanvas(fig) # NOQA\n #fig.clf()\n ax = fig.add_subplot(1, 1, 1)\n if check_func is not None and check_func():\n return\n #fig = pt.plt.figure(fnum)\n #H1 = np.eye(3)\n #H2 = np.eye(3)\n #H1[0, 0] = .5\n #H1[1, 1] = .5\n #H2[0, 0] = .5\n #H2[1, 1] = .5\n ax, xywh1, xywh2 = pt.show_chipmatch2(rchip1, rchip2, kpts1_, kpts2_, fm,\n fs=fs, colorbar_=False, ax=ax)\n if check_func is not None and check_func():\n return\n savekw = {\n # 'dpi' : 60,\n 'dpi' : 80,\n }\n axes_extents = pt.extract_axes_extents(fig)\n #assert len(axes_extents) == 1, 'more than one axes'\n extent = axes_extents[0]\n with io.BytesIO() as stream:\n # This call takes 23% - 15% of the time depending on settings\n fig.savefig(stream, bbox_inches=extent, **savekw)\n stream.seek(0)\n data = np.fromstring(stream.getvalue(), dtype=np.uint8)\n if check_func is not None and check_func():\n return\n pt.plt.close(fig)\n image = cv2.imdecode(data, 1)\n thumbsize = 221\n max_dsize = (thumbsize, thumbsize)\n dsize, sx, sy = vt.resized_clamped_thumb_dims(vt.get_size(image), max_dsize)\n if check_func is not None and check_func():\n return\n image = vt.resize(image, dsize)\n vt.imwrite(fpath, image)\n if check_func is not None and check_func():\n return\n #fig.savefig(fpath, bbox_inches=extent, **savekw)\n #match_thumbtup_cache[match_thumb_fpath_] = fpath\n return fpath, nosql_draw, main_thread_load\n\n\ndef get_photobomber_map(ibs, aids, aid_to_nid=None):\n \"\"\"\n Builds map of which names that photobomb other names.\n\n python -m ibeis.gui.id_review_api --test-test_review_widget --show --db PZ_MTEST -a default:qindex=0\n\n >>> import ibeis\n >>> dbdir = ut.truepath('~/lev/media/danger/GGR/GGR-IBEIS')\n >>> ibs = ibeis.opendb(dbdir='/home/joncrall/lev/media/danger/GGR/GGR-IBEIS')\n >>> filter_kw = {\n >>> 'multiple': False,\n >>> 'minqual': 'good',\n >>> 'is_known': True,\n >>> 'min_pername': 2,\n >>> 'view': ['right'],\n >>> }\n >>> aids = ibs.filter_annots_general(ibs.get_valid_aids(), filter_kw=filter_kw)\n \"\"\"\n ams_list = ibs.get_annotmatch_rowids_from_aid(aids)\n flags_list = ibs.unflat_map(ut.partial(ibs.get_annotmatch_prop, 'Photobomb'), ams_list)\n pb_ams = ut.zipcompress(ams_list, flags_list)\n has_pb_ams = [len(ams) > 0 for ams in pb_ams]\n pb_ams_ = ut.compress(pb_ams, has_pb_ams)\n #aids_ = ut.compress(aids, has_pb_ams)\n pb_ams_flat = ut.flatten(pb_ams_)\n\n pb_aids1_ = ibs.get_annotmatch_aid1(pb_ams_flat)\n pb_aids2_ = ibs.get_annotmatch_aid2(pb_ams_flat)\n\n pb_aid_pairs_ = list(zip(pb_aids1_, pb_aids2_))\n if aid_to_nid is None:\n pb_nid_pairs_ = ibs.unflat_map(ibs.get_annot_nids, pb_aid_pairs_)\n else:\n pb_nid_pairs_ = ibs.unflat_map(ut.partial(ut.take, aid_to_nid), pb_aid_pairs_)\n\n #invalid_aid_map = ut.ddict(set)\n #for aid1, aid2 in pb_aid_pairs_:\n # if aid1 != aid2:\n # invalid_aid_map[aid1].add(aid2)\n # invalid_aid_map[aid2].add(aid1)\n\n invalid_nid_map = ut.ddict(set)\n for nid1, nid2 in pb_nid_pairs_:\n if nid1 != nid2:\n invalid_nid_map[nid1].add(nid2)\n invalid_nid_map[nid2].add(nid1)\n\n return invalid_nid_map\n" ]
[ [ "numpy.product", "numpy.empty" ], [ "numpy.empty" ], [ "numpy.full", "numpy.array", "matplotlib.backends.backend_agg.FigureCanvas", "matplotlib.backends.backend_agg.Figure", "matplotlib.is_interactive", "matplotlib.interactive", "numpy.hstack", "numpy.vstack" ] ]
yaochenzhu/MMDQEN
[ "d8f7273b8dc51ad28e86e891e26e536e35928080" ]
[ "data.py" ]
[ "import os\r\nfrom pathlib import Path\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport tensorflow as tf\r\nfrom skimage import io\r\nfrom tensorflow import keras\r\n\r\n\r\nclass BimodalDenoiseDataGen(keras.utils.Sequence):\r\n '''\r\n Generate train/validation/test samples for our multimodal\r\n denoise network. Inputs are static images, spectrograms and \r\n corresponding noisy labels. Outputs are noisy labels. In \r\n order to decorrelate training samples, we randonly shuffle\r\n movie sequences, sequentially fetch sel_movie movie clips \r\n from that sequence, then randomly select sel_frames frames\r\n from each moive clip. \r\n '''\r\n def __init__(self,\r\n label_file,\r\n length_file,\r\n sample_rate,\r\n video_root,\r\n audio_root,\r\n video_shape,\r\n audio_shape,\r\n video_preproc,\r\n audio_preproc,\r\n sel_movies,\r\n sel_frames,\r\n n_classes,\r\n affective_type,\r\n ret_label_X=True,\r\n ret_label_y=True):\r\n self.__parse_label_file (label_file , affective_type)\r\n self.__parse_length_file(length_file, sample_rate)\r\n self.file_list = list(self.label_dict.keys())\r\n self.video_root = video_root\r\n self.audio_root = audio_root\r\n self.video_preproc = video_preproc\r\n self.audio_preproc = audio_preproc\r\n self.sel_movies = sel_movies\r\n self.sel_frames = sel_frames\r\n self._video_shape = video_shape\r\n self._audio_shape = audio_shape\r\n self._n_classes = n_classes\r\n self._batch_size = self.sel_movies*self.sel_frames\r\n self.ret_label_X = ret_label_X\r\n self.ret_label_y = ret_label_y\r\n self.on_epoch_end() \r\n\r\n def on_epoch_end(self):\r\n np.random.shuffle(self.file_list)\r\n\r\n def __parse_label_file(self, label_file, affective_type):\r\n label_table = pd.read_table(label_file)\r\n self.label_dict = dict(\r\n zip(\r\n label_table[\"name\"],\r\n label_table[\"valenceClass\"] if affective_type == \"val\"\r\n else label_table[\"arousalClass\"]\r\n ))\r\n\r\n def __parse_length_file(self, length_file, sample_rate):\r\n length_table = pd.read_table(length_file)\r\n self.length_dict = dict(\r\n zip(\r\n length_table[\"name\"],\r\n [l//sample_rate for l in length_table[\"length\"]]\r\n )) \r\n\r\n def __len__(self):\r\n num = len(self.label_dict)\r\n return num // self.sel_movies\r\n\r\n def __getitem__(self, i):\r\n batch_file_list = self.file_list[i*self.sel_movies:(i+1)*self.sel_movies]\r\n X, y = self._data_generator(batch_file_list)\r\n return X, y\r\n\r\n def _data_generator(self, batch_file_list):\r\n videos = np.zeros((self._batch_size, *self.video_shape), dtype=np.float32)\r\n audios = np.zeros((self._batch_size, *self.audio_shape), dtype=np.float32)\r\n labels = []\r\n for i, filename in enumerate(batch_file_list):\r\n length = self.length_dict[filename]\r\n frame_idx = np.random.choice(length, self.sel_frames)\r\n for j, idx in enumerate(frame_idx):\r\n videos[i*self.sel_frames+j] = io.imread(\r\n Path(self.video_root)/\"{}_{}.jpg\".format(filename, idx)\r\n )\r\n audios[i*self.sel_frames+j] = np.load(\r\n Path(self.audio_root)/\"{}_{}.npy\".format(filename, idx)\r\n )[..., None]\r\n labels += [self.label_dict[filename]]*self.sel_frames\r\n\r\n if self.video_preproc:\r\n videos = self.video_preproc(videos)\r\n if self.audio_preproc:\r\n audios = self.audio_preproc(audios)\r\n\r\n labels = keras.utils.to_categorical(labels, self._n_classes)\r\n X = [videos, audios]\r\n y = []\r\n if self.ret_label_X:\r\n X += [labels]\r\n if self.ret_label_y:\r\n y += [labels]\r\n return X, y\r\n\r\n @property\r\n def batch_size(self):\r\n return self._batch_size\r\n\r\n @property\r\n def video_shape(self):\r\n return self._video_shape\r\n\r\n @property\r\n def audio_shape(self):\r\n return self._audio_shape\r\n\r\n @property\r\n def n_classes(self):\r\n return self._n_classes\r\n\r\n\r\nclass BimodalClassifierDataGen(BimodalDenoiseDataGen):\r\n def __init__(self,\r\n training,\r\n denoise_model=None, \r\n **kwargs):\r\n super(BimodalClassifierDataGen, self).__init__(**kwargs)\r\n self.training = training\r\n if self.training:\r\n assert denoise_model is not None, \\\r\n \"must specify denoise model in training mode!\"\r\n self.denoise_model = denoise_model\r\n\r\n def __getitem__(self, i):\r\n batch_file_list = self.file_list[i*self.sel_movies:(i+1)*self.sel_movies]\r\n X, _ = self._data_generator(batch_file_list)\r\n #if self.training == True:\r\n # y = self.denoise_model.predict(X)\r\n #else:\r\n y = X[-1]\r\n X = [X[0], X[1]]\r\n return X, y\r\n\r\n\r\nclass DenoiseDataGen(keras.utils.Sequence):\r\n def __init__(self,\r\n label_file,\r\n length_file,\r\n sample_rate,\r\n video_root,\r\n audio_root,\r\n video_shape,\r\n audio_shape,\r\n video_preproc,\r\n audio_preproc,\r\n sel_movies,\r\n sel_frames,\r\n n_classes,\r\n affective_type,\r\n modality,\r\n ret_label_X=True,\r\n ret_label_y=True):\r\n self.__parse_label_file (label_file , affective_type)\r\n self.__parse_length_file(length_file, sample_rate)\r\n self.file_list = list(self.label_dict.keys())\r\n self.video_root = video_root\r\n self.audio_root = audio_root\r\n self.video_preproc = video_preproc\r\n self.audio_preproc = audio_preproc\r\n self.sel_movies = sel_movies\r\n self.sel_frames = sel_frames\r\n self._video_shape = video_shape\r\n self._audio_shape = audio_shape\r\n self._n_classes = n_classes\r\n self._batch_size = self.sel_movies*self.sel_frames\r\n self.ret_label_X = ret_label_X\r\n self.ret_label_y = ret_label_y\r\n\r\n self.modality = modality\r\n assert modality in [\"visual\", \"aural\"]\r\n self.on_epoch_end() \r\n\r\n def on_epoch_end(self):\r\n np.random.shuffle(self.file_list)\r\n\r\n def __parse_label_file(self, label_file, affective_type):\r\n label_table = pd.read_table(label_file)\r\n self.label_dict = dict(\r\n zip(\r\n label_table[\"name\"],\r\n label_table[\"valenceClass\"] if affective_type == \"val\"\r\n else label_table[\"arousalClass\"]\r\n ))\r\n\r\n def __parse_length_file(self, length_file, sample_rate):\r\n length_table = pd.read_table(length_file)\r\n self.length_dict = dict(\r\n zip(\r\n length_table[\"name\"],\r\n [l//sample_rate for l in length_table[\"length\"]]\r\n )) \r\n\r\n def __len__(self):\r\n num = len(self.label_dict)\r\n return num // self.sel_movies\r\n\r\n def __getitem__(self, i):\r\n batch_file_list = self.file_list[i*self.sel_movies:(i+1)*self.sel_movies]\r\n X, y = self._data_generator(batch_file_list)\r\n return X, y\r\n\r\n def _data_generator(self, batch_file_list):\r\n videos = np.zeros((self._batch_size, *self.video_shape), dtype=np.float32)\r\n audios = np.zeros((self._batch_size, *self.audio_shape), dtype=np.float32)\r\n labels = []\r\n for i, filename in enumerate(batch_file_list):\r\n length = self.length_dict[filename]\r\n frame_idx = np.random.choice(length, self.sel_frames)\r\n if self.modality == \"visual\":\r\n for j, idx in enumerate(frame_idx):\r\n videos[i*self.sel_frames+j] = io.imread(\r\n Path(self.video_root)/\"{}_{}.jpg\".format(filename, idx)\r\n )\r\n labels += [self.label_dict[filename]]*self.sel_frames\r\n elif self.modality == \"aural\":\r\n for j, idx in enumerate(frame_idx): \r\n audios[i*self.sel_frames+j] = np.load(\r\n Path(self.audio_root)/\"{}_{}.npy\".format(filename, idx)\r\n )[..., None]\r\n labels += [self.label_dict[filename]]*self.sel_frames\r\n\r\n\r\n if self.video_preproc and self.modality == \"visual\":\r\n videos = self.video_preproc(videos)\r\n if self.audio_preproc and self.modality == \"aural\":\r\n audios = self.audio_preproc(audios)\r\n\r\n labels = keras.utils.to_categorical(labels, self._n_classes)\r\n X = [videos] if self.modality == \"visual\" else [audios]\r\n y = []\r\n if self.ret_label_X:\r\n X += [labels]\r\n if self.ret_label_y:\r\n y += [labels]\r\n return X, y\r\n\r\n @property\r\n def batch_size(self):\r\n return self._batch_size\r\n\r\n @property\r\n def video_shape(self):\r\n return self._video_shape\r\n\r\n @property\r\n def audio_shape(self):\r\n return self._audio_shape\r\n\r\n @property\r\n def n_classes(self):\r\n return self._n_classes\r\n\r\n\r\nclass ClassifierDataGen(DenoiseDataGen):\r\n def __init__(self,\r\n training,\r\n denoise_model=None,\r\n **kwargs):\r\n super(ClassifierDataGen, self).__init__(**kwargs)\r\n self.training = training\r\n if self.training:\r\n assert denoise_model is not None, \\\r\n \"must specify denoise model in training mode!\"\r\n self.denoise_model = denoise_model\r\n\r\n def __getitem__(self, i):\r\n batch_file_list = self.file_list[i*self.sel_movies:(i+1)*self.sel_movies]\r\n X, _ = self._data_generator(batch_file_list)\r\n #if self.training == True:\r\n # y = self.denoise_model.predict(X)\r\n #else:\r\n y = X[-1]\r\n X = X[0]\r\n return X, y" ]
[ [ "tensorflow.keras.utils.to_categorical", "pandas.read_table", "numpy.random.choice", "numpy.zeros", "numpy.random.shuffle" ] ]
mexmi2021/mexmi-project
[ "ef735cb290d33b326f592a70fa9b7f7dc6b6281b" ]
[ "mexmi/subset_selection_strategy/bayesian_disagreement_dropout_sss.py" ]
[ "from base_sss import SubsetSelectionStrategy\nimport base_sss\nimport random\nimport torch\n\nclass BALDDropoutStrategy(SubsetSelectionStrategy):\n def __init__(self, size, Y_vec, n_drop=10, previous_s=None):\n self.previous_s = previous_s\n self.n_drop = n_drop\n super(BALDDropoutStrategy, self).__init__(size, Y_vec)\n \n def get_subset(self):\n # random.setstate(base_sss.sss_random_state)\n if self.previous_s is not None:\n Y_e = [self.Y_vec[ie] for ie in self.previous_s]\n else:\n Y_e = self.Y_vec #unlabelled copy mdeol outputs\n #dropout\n probs = torch.zeros([self.n_drop, len(Y_e), 10]) #np.unique(Y)\n for i in range(self.n_drop):\n for idxs in range(len(Y_e)):\n probs[i][idxs] += Y_e[idxs]\n pb = probs.mean(0)\n entropy1 = (-pb * torch.log(pb)).sum(1)\n entropy2 = (-probs * torch.log(probs)).sum(2).mean(0)\n U = entropy2 - entropy1\n points = U.sort()[1][:self.size]\n # print(\"points,\", points)\n if self.previous_s is not None:\n final_points = [self.previous_s[p] for p in points]\n else:\n final_points = points\n return final_points\n" ]
[ [ "torch.log" ] ]
petropusz/DistSup
[ "4f9dc50fb6c96f1e4348bb6b79a0b22d1078161a", "4f9dc50fb6c96f1e4348bb6b79a0b22d1078161a" ]
[ "distsup/configuration/__init__.py", "distsup/aligner.py" ]
[ "# -*- coding: utf8 -*-\n# Copyright 2019 JSALT2019 Distant Supervision 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.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport torch\n\nfrom distsup import utils\nfrom distsup.configuration import config_utils\n\n\ndef get_val(dictionary, key, dict_name):\n if key not in dictionary:\n raise KeyError('%s has no %s key specified' % (dict_name, key))\n\n return dictionary[key]\n\n\nclass ConfigInstantiator(object):\n def __init__(self, objects_config, default_class_dict={},\n default_modules_dict={}, name='', **kwargs):\n super(ConfigInstantiator, self).__init__(**kwargs)\n self.objects_config = objects_config\n self.default_class_dict = default_class_dict\n self.default_modules_dict = default_modules_dict\n self.cache = {}\n self.name = name\n\n def keys(self):\n return self.objects_config.keys()\n\n def _getitem(self, key, additional_parameters=None):\n if key not in self.cache:\n # make a copy since we may change the dict in the end\n opts = dict(get_val(self.objects_config, key, self.name))\n if 'class_name' not in opts:\n opts['class_name'] = self.default_class_dict[key]\n self.cache[key] = utils.construct_from_kwargs(\n opts, self.default_modules_dict.get(key),\n additional_parameters)\n return self.cache[key]\n\n def __getitem__(self, key):\n return self._getitem(key)\n\n\nclass DatasetConfigInstantiator(ConfigInstantiator):\n def _getitem(self, key, additional_parameters=None):\n if key not in self.cache:\n # make a copy since we may change the dict in the end\n opts = dict(get_val(self.objects_config, key, self.name))\n if 'class_name' not in opts:\n opts['class_name'] = self.default_class_dict[key]\n self.cache[key] = utils.construct_from_kwargs(\n opts, self.default_modules_dict.get(key),\n additional_parameters)\n return self.cache[key]\n\n\nclass _ConstantDict(object):\n def __init__(self, v, **kwargs):\n super(_ConstantDict, self).__init__(**kwargs)\n self.v = v\n\n def __getitem__(self, k):\n return self.v\n\n def get(self, k, v=None):\n return self.v\n\n\nclass Configuration(ConfigInstantiator):\n \"\"\"\n Class responsible for instantiating object that are defined in config file.\n\n The class tries to be smart about the following modules:\n - Trainer will by default instantiate an 'distsup.trainer.Trainer'\n - all items on the Data key will instantiate a 'distsup.data.Data'\n - It will configure the Model key according to Dataset specification\n\n Args:\n config_path (str): Path pointing to the config file.\n modify_dict (dict): Optional dictionary representing config\n modifications.\n store_path (str): Optional path to store linked config.\n \"\"\"\n\n default_class_dict = {\n 'Trainer': 'Trainer',\n }\n default_modules_dict = {\n 'Trainer': 'distsup.trainer',\n 'Datasets': 'distsup.data',\n 'Model': 'models',\n }\n\n def __init__(self, config_path, modify_dict={}, store_path=None, **kwargs):\n config = config_utils.ConfigParser(config_path).get_config(modify_dict)\n if store_path is not None:\n config_utils.ConfigLinker(config).save_linked_config(store_path)\n super(Configuration, self).__init__(\n objects_config=config,\n default_class_dict=Configuration.default_class_dict,\n default_modules_dict=Configuration.default_modules_dict,\n name=config_path,\n **kwargs)\n if 'Datasets' in self.objects_config:\n self.cache['Datasets'] = DatasetConfigInstantiator(\n self.objects_config['Datasets'],\n default_modules_dict=_ConstantDict(\n Configuration.default_modules_dict['Datasets']),\n name='Config.Datasets')\n\n def __getitem__(self, key):\n if key == 'Model':\n model_param = {'dataloader': self['Datasets']['train']}\n return self._getitem('Model', additional_parameters=model_param)\n else:\n return super(Configuration, self).__getitem__(key)\n\n\nclass Globals(object):\n \"\"\"Global configuration objects.\"\"\"\n cuda = torch.cuda.is_available()\n cluster = ''\n exp_tag = None\n save_dir = None\n exp_uuid = None\n exp_config_fpath = None\n\n # Track training progress. The trainer/loader will fill in proper values.\n epoch = -1\n current_iteration = -1\n", "# -*- coding: utf8 -*-\n# Copyright 2019 JSALT2019 Distant Supervision 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.\n\n'''\n Two classes here:\n Aligner, to get path from a model during recognition, and visualize\n ForcedAligner, to get a path from the ground truth\n'''\nimport os\nimport sys\nimport io\nimport torch\nimport cv2\nimport numpy as np\n\nclass Aligner:\n def __init__(self, outFile_, alphabet_):\n self.fpOutputPath = None\n self.filename = outFile_\n self.alphabet = alphabet_\n\n if outFile_ != \"\" and outFile_ != \"none\":\n self.fpOutputPath = open(outFile_, \"w\")\n print (\"Aligner: __init__ opened path to write:\" + str(outFile_) )\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n if self.fpOutputPath != None:\n self.fpOutputPath.close()\n print (\"Aligner: __exit__ closed file: \" + str(self.filename) )\n self.fpOutputPath = None\n\n def __del__(self):\n if self.fpOutputPath != None:\n self.fpOutputPath.close()\n print (\"Aligner: __del__ closed file: \" + str(self.filename) )\n self.fpOutputPath = None\n\n def writePathToFile(self, imageFilename_, path_, targetStr_):\n # Build path string - Header line\n pathStr = imageFilename_ + \" \" + str(len(path_)) + \" targetStr:\" + str(targetStr_) + \"\\n\"\n\n # Build path string, per time stamp\n for t in range(0, len(path_)):\n label = path_[t][0]\n score = path_[t][1]\n scoreStr = \"{0:.6f}\".format(score)\n outLine = str(t) + \" \" + str(t+1) + \" \" + str(label) + \" \" + str(scoreStr) + \"\\n\"\n pathStr = pathStr + outLine\n\n # Write path string to output file\n self.append(pathStr)\n\n return pathStr\n\n def pathFromStringAndLogprobs(self, pathStrWithBlanks_, pathLogProbs_):\n sz = len(pathLogProbs_)\n path = []\n for t in range(0,sz):\n label = pathStrWithBlanks_[t]\n if label == \" \":\n label = \"_\" # SPACE, typically idx in alphabet == 1\n #score = pathLogProbs_[t].item()\n score = pathLogProbs_[t]\n\n path.append( [ label, score] )\n return path\n\n '''\n Input: a test string which is a path, to be appended to an output file.\n '''\n def append(self, text_):\n self.fpOutputPath.write(text_)\n\n '''\n Input : logProbs_.shape is 2D [ seqLen, nColumns]\n Output: tensor with all probabilities from the (best) path\n '''\n def getPathLogProbs(self, logProbs_, path_):\n sz = logProbs_.shape[0]\n assert path_.shape[0] == sz\n\n result = []\n for i in range(0, sz):\n result.append( logProbs_[i, path_[i] ])\n\n return torch.FloatTensor(result)\n\n '''\n Called from 'model' sequential.py\n Input:\n pathWithBlanks_ a [ 1 x N] tensor which includes blanks and has the indices in the alphabet\n pathLogProbs_ a [ 1 x N] tensor which includes blanks, the scores for the path.\n targets a [ 1 x K] tensor which includes blanks, the groundtruth\n alphabet_ : the dictionary with idx to character mapping\n\n Note:\n To debug and visualize:\n print ( self.prettyPrintList(path) ) #DBG\n\n if targets_ == None (and targetLen_) then we are in forward-only mode.\n Just look at the recognition results\n '''\n def makePath(self, pathWithBlanks_, log_probs_,\n targets_, targetLen_,\n alphabet_,\n imageFilename_, orgImageSize_,\n nFeatures_,\n verbose_ = 0):\n\n # Extract path from 2D matrix of logProbs_\n pathLogProbs_ = self.getPathLogProbs(log_probs_, pathWithBlanks_)\n\n assert pathWithBlanks_.shape == pathLogProbs_.shape\n if targets_ is not None:\n assert targets_.shape[0] == targetLen_\n assert len(alphabet_) > 0\n assert not torch.isnan(pathLogProbs_).any(), \"ERROR: Aligner.makePath() the input has NaNs in log probs!\"\n\n sz = len(pathLogProbs_)\n assert sz > 0\n\n pathStrWithBlanks = alphabet_.idx2str(pathWithBlanks_,noDuplicates=False,noBlanks=False)\n pathStr = \"\"\n filename = imageFilename_\n\n # targetStr\n if targets_ is not None:\n mytarget = targets_[:targetLen_]\n assert mytarget.argmin() >= 0\n assert mytarget[ mytarget.argmax() ] < len(alphabet_)\n assert len(alphabet_) > 0\n\n targetStr = alphabet_.idx2str(mytarget)\n else:\n # Insert the recognized, cleaned string here ...\n targetStr = alphabet_.idx2str(pathWithBlanks_, noDuplicates=True, noBlanks=True)\n\n if verbose_ > 0:\n print (\"makePath: pathWithBlanks_ = \" + str(pathWithBlanks_))\n print (\"makePath: pathLogProbs_ = \" + str(pathLogProbs_))\n print (\"makePath: pathStrWithBlanks = \" + str(pathStrWithBlanks))\n print (\"makePath: len( pathStrWithBlanks) = \" + str(len(pathStrWithBlanks)))\n print (\"makePath: targetStr = \" + str(targetStr))\n print (\"makePath: targetLen_ = \" + str(sz))\n print (\"makePath: pathSz = \" + str(sz))\n print (\"makePath: filename = \" + str(filename))\n print (\"makePath: nFeatures_ = \" + str(nFeatures_))\n\n assert len(pathStrWithBlanks) == sz, \"ERROR: The transcript of this path is shorter than pathWithBlanks_\"\n\n # First build the path from the recognition data we got.\n pathLogProbsList = [element.item() for element in pathLogProbs_.flatten()]\n path = self.pathFromStringAndLogprobs(pathStrWithBlanks, pathLogProbs_)\n\n # Stretch the path to the width of the input features.\n path = self.stretchToLength(path, nFeatures_, insertSeparators_=False)\n\n # Convert CTC center path to a Kaldi-like path. The other way round, from ' * * e *' to 'e e e e'\n # (from mostly CTC centers to repeating symbols to indicate spans of characters)\n if 0:\n path = self.convertCTC2Kaldi(path)\n\n # If necessary stretch the patch\n # NOTE: we stretch a factor due to the CNN stack compression.\n # Actually, if we the orginal image size then we could stretch by that factor\n # QUESTION: Do we do the stretching in visualization only?\n # QUESTION: Probably should not generate repeating labels e.g. we have a 'e' somewhere. then the streching would put four 'e's in path when factor == 4\n #\n if 0: # stretchFactor_ != 1:\n path = self.stretch(path, stretchFactor_)\n\n # Write path to file\n pathStr = self.writePathToFile(imageFilename_, path, targetStr)\n\n return pathStr\n\n def prettyPrintList(self, list_):\n resultStr = \"\"\n for i in range(0, len(list_)):\n resultStr = resultStr + str(i) + \" \" + str(list_[i]) + \"\\n\"\n return resultStr\n\n def convertCTC2Kaldi(self, path_):\n # a) Remove blanks (i.e. the result is much shorter)\n path2 = self.removeBlanksFromPath(path_)\n\n # b) Get the delta +/- around the centers\n pathPlusDelta = self.convertCentersToArea(path2, len(path_) )\n\n # c) make a new path, same length original, but with area marked as characters\n path4 = self.applyDeltas(path_, pathPlusDelta)\n assert len(path4) == len(path_)\n\n return path4\n\n '''\n '''\n def applyDeltas(self, path_, pathPlusDelta_ ):\n newPath = path_.copy()\n\n for sample in pathPlusDelta_:\n # list [start time, end time, symbo, ,score]\n start = sample[0]\n end = sample[1]\n ch = sample[2]\n sc = sample[3]\n\n t = start\n while t < end:\n #print ( \"newpath[\" +str(t) + \"]=\" + str(newPath[t]) )\n assert t < len(newPath)\n assert len(newPath[t]) == 2\n #assert newPath[t][0] == \"*\", \"ERROR: cannot override timestamp %d as that is not a blank!\" % t # Only override blanks\n if newPath[t][0] == \"*\":\n newPath[t][0] = ch\n newPath[t][1] = sc\n t += 1\n return newPath\n\n '''\n When visualizing, we want to seperate 'oo' properly. If we have\n a blank at boundary then that is enough.\n Detect repeating symbols (non blanks) and insert blank there\n symbolBoundaries_[i] = pair of [ idx in path, symbol]\n '''\n def insertBlanksAsSymbolSeperators(self, newPath_, symbolBoundaries_):\n idx = 0\n for pair in symbolBoundaries_:\n if idx > 0:\n if symbolBoundaries_[idx-1][1] == symbolBoundaries_[idx][1]:\n # repeat detected : put a blank on previous right boundary\n targetIdx = symbolBoundaries_[idx-1][0]\n newPath_[targetIdx][0] = '*'\n idx += 1\n\n '''\n Input:\n - a list of lists [character label, score], length N\n - a stretchFactor N\n Output:\n - similar list but length 4 * N i.e. duplicate the intermediate ones\n '''\n def stretch(self, path_, stretchFactor_):\n orgSz = len(path_)\n newSz = int(orgSz * stretchFactor_)\n newPath = [None] * newSz\n\n for t in range( len(newPath)):\n orgIdx = int(t / (stretchFactor_ * 1.0))\n newPath[t] = path_[orgIdx].copy()\n\n return newPath\n\n '''\n symbolBoundaries_ is a optional list of lists (of length 2) with pairs [boundary index, symbols]\n '''\n def stretchToLength(self, path_, newSz_, insertSeparators_=False, symbolBoundaries_=None):\n orgSz = len(path_)\n newPath = [None] * newSz_\n stretchFactor_ = orgSz / (newSz_ * 1.0)\n\n for t in range( newSz_):\n orgIdx = int(t * stretchFactor_ + 0.5 )\n if orgIdx >= orgSz:\n orgIdx = orgSz -1\n newPath[t] = path_[orgIdx].copy()\n\n # Scale the symbolBoundaries_ list\n if symbolBoundaries_ is not None:\n for t in range(len(symbolBoundaries_)):\n oldIx = symbolBoundaries_[t][0]\n newIdx = int(oldIx * (1.0 / stretchFactor_) + 0.5)\n if newIdx > newSz_:\n newIdx = newSz_ -1\n symbolBoundaries_[t] = [ newIdx, symbolBoundaries_[t][1] ]\n\n # Optional insert of blanks between repeats like 'oo'\n if (symbolBoundaries_ is not None ) and insertSeparators_:\n self.insertBlanksAsSymbolSeperators(newPath, symbolBoundaries_)\n\n return newPath\n\n '''\n keepCentersOnly() ~~ removeDuplicates in path but keep best probability\n We want one 'e' if we see an 'e', no a set of repetitions\n\n In : a path of pairs (list) [ character, score]\n Out: another path, same length\n\t\t\n\t\t<fixme, name of image>.jpg 108 targetStr:*merckelijcke schade daer weder affgeraeckt ende hebben ons tot*\n\t\t0 1 * -4.38690185546875e-05\n\t\t1 2 * -0.0009212493896484375\n\t\t2 3 * -0.00018405914306640625\n\t\t3 4 * -0.00017261505126953125\n\t\t4 5 m -0.1310567855834961\n\t\t5 6 * -0.24684619903564453\n\t\t6 7 * -1.33514404296875e-05\n\t\t7 8 e -0.06367206573486328\t\t<-- Look, we have 2 e's here. Keep the one with highest prob, and put in middle of seq\n\t\t8 9 e -0.01826000213623047\n\t\t9 10 r -0.0006761550903320312\n\t\t10 11 * -2.288818359375e-05\n\t\t11 12 c -0.0002651214599609375\n\t\t12 13 k -0.03693866729736328\n\t\t13 14 * -0.12099361419677734\n\t\t14 15 e -0.0007238388061523438\n\t\t15 16 * -0.7822256088256836\n\t\t16 17 l -0.0044269561767578125\n\t\t17 18 i -0.3120155334472656\n\t\t18 19 i -0.6767368316650391\n\t\t19 20 j -0.0020036697387695312\n\t\t20 21 c -0.0012416839599609375\n\t\t21 22 k -0.05278205871582031\n\t\t22 23 k -0.061593055725097656\n\t\t23 24 e -0.035645484924316406\n\t\t\n '''\n def keepCentersOnly(self, path_):\n assert len(path_) > 0\n newPath = [None] * len(path_)\n\t\t\n idx = 0\n prev = '*'\n blankScore = -1.0 # Maybe 0.0 is too good\n\n t = 0\n while t < len(path_):\n ch = path_[t][0]\n newPath[t] = path_[t].copy()\n\n duration = 1\n #if not (ch in {'*', ' ', '_' } ):\n if not (ch in {'*'} ):\n # we have a new character to handle\n # duration is 1 or more repetitions of this character\n myCharCenterScore, duration = self.getCenterProb(path_, t) # scan ahead\n assert duration > 0\n\n # Clean area in duration\n for i in range(duration):\n newPath[t + i] = [ '*', blankScore ]\n\n # Set the center entry\n centerIdx = int(t + (duration / 2))\n newPath[centerIdx] = [ ch, myCharCenterScore ]\n\n #Shift\n prev = ch\n t += duration\n\n return newPath\n\n def getCenterProb(self, path_, startTime_):\n t = startTime_\n ch = path_[startTime_][0]\n\n bestScore = -1000000000.0\n while t < len(path_) and ch == path_[t][0]:\n if path_[t][1] > bestScore:\n bestScore = path_[t][1]\n t += 1\n duration = t - startTime_\n\n assert duration > 0\n return bestScore, duration\n\n '''\n Input:\n - a path list of lists [character label, score], length N\n Output:\n - similar list but length 4 * N i.e. duplicate the intermediate ones\n '''\n def removeBlanksFromPath(self, path_):\n t = 0\n centerData = []\n for t in range(0, len(path_)):\n label = path_[t][0]\n score = path_[t][1]\n\n if label != \"*\":\n centerData.append( [ t, label, score] )\n return centerData\n\n def resizeImage(self, image_, scaleFactor):\n nNewRows = int(image_.shape[0] * scaleFactor)\n nNewCols = int(image_.shape[1] * scaleFactor)\n resizedImage = cv2.resize(image_, (nNewCols, nNewRows)) #width, height\n return resizedImage\n\n def saveImage(self, filename_, image_):\n print ( \"Saving to file: \" + str(filename_))\n\n # Make sure horizontal length (nColumns < 2^16 and nRows < 2^16 for JPEG specs)\n if image_.shape[1] > 65000:\n nColumns = image_.shape[1]\n scaleFactor = 65000.0 / (image_.shape[1] * 1.0)\n\n nNewRows = int(image_.shape[0] * scaleFactor)\n nNewCols = int(image_.shape[1] * scaleFactor)\n\n resizedImage = cv2.resize(image_, (nNewCols, nNewRows)) #width, height\n\n print (\"saveImage() RESIZE IMAGE \" + str(image_.shape) + \" before save as nCols > 65000 (not possible for JPG) nColumns= \" + \\\n str(nColumns) + \" scaleFactor = \" + str(scaleFactor) + \\\n \" NEW dimensions[\" + str(resizedImage.shape) + \"]\" )\n\n cv2.imwrite(filename_, resizedImage)\n else:\n # Normal action\n cv2.imwrite(filename_, image_)\n\n def scaleData(self, data_, scaleFactor):\n result = []\n for d in data_:\n leftCol = d[0]\n rightCol = d[1]\n sym = d[2]\n score = d[3]\n\n newLeft = int(int(leftCol ) * 1.0 * scaleFactor)\n newRight = int(int(rightCol) * 1.0 * scaleFactor)\n\n result.append( [ newLeft, newRight, sym, score] )\n return result\n\n def scaleCenterData(self, data_, scaleFactor):\n result = []\n for d in data_:\n newT = int(int(d[0]) * 1.0 * scaleFactor)\n result.append( [ newT, d[1], d[2]] )\n\n return result\n\n '''\n data_ is a python list of columns where to draw lines. format 3-tuple (list) [ timestamp, character, score]\n '''\n def drawLinesInImage(self, image_, data_, draw_):\n imageCopy = np.copy(image_)\n\n nRows = imageCopy.shape[0]\n nCols = imageCopy.shape[1]\n\n cnt = 0\n for d in data_:\n assert len(d) == 3\n\n t = d[0]\n sym = d[1]\n score = d[2]\n\n cv2.line(imageCopy, (t,0), (t, nRows), color=255, thickness=1)\n if 1:\n cv2.putText(imageCopy, sym, (t-5, 20), cv2.FONT_HERSHEY_SIMPLEX, 1., 255 )\n cnt += 1\n if draw_:\n cv2.imshow(\"drawLinesInImage AFTER\", imageCopy)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n return imageCopy\n\n # Input: data_ is a list of lists of 4 [leftcol, right col, sym, score]\n #https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html\n def drawRectanglesInImage(self, image_, data_, draw_):\n print (\"drawRectanglesInImage\")\n\n imageCopy = np.copy(image_)\n overlay = np.copy(image_)\n\n nRows = image_.shape[0]\n nCols = image_.shape[1]\n\n cnt = 0\n for d in data_:\n #print (\"[\" + str(cnt) + \"]\" + str(d) )\n\n leftCol = d[0]\n rightCol = d[1]\n sym = d[2]\n score = d[3]\n\n if (cnt % 2) == 0:\n color = 128\n else:\n color = 200\n\n # A filled, NON tranparanet rectangle (which deletes the digits)\n #cv2.rectangle(imageCopy, (leftCol,0), (rightCol, nRows), color=color, thickness=-1)\n\n # Rectangle with fat borders\n #cv2.rectangle(imageCopy, (leftCol,0), (rightCol, nRows), color=color, thickness=3)\n\n # Transparent\n alpha = 0.5\n cv2.rectangle(overlay, (leftCol,0), (rightCol, nRows), color=color, thickness=-1)\n cv2.putText(overlay, sym, (leftCol,20), cv2.FONT_HERSHEY_SIMPLEX, 1., 255 )\n\n cnt += 1\n\n # Now that we have all filled rectangles in 'overlay' combine images.\n cv2.addWeighted(overlay, alpha, imageCopy, 1 - alpha, 0, imageCopy)\n\n if draw_:\n img2 = self.resizeImage(imageCopy, 1.0)\n self.saveImage(\"a.jpg\", img2)\n\n cv2.imshow(\"drawRectanglesInImage AFTER\", img2)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n return imageCopy\n\n '''\n This convert a list like\n [[48, '3', -0.000533],\n [80, '1', -0.000559],\n [112, '4', -0.018588],\n [144, '1', -0.00038]\n ...\n\n To\n\n [[48 -delta, 48+delta, '3', -0.000533],\n [80-delta, 80+delta, '1', -0.000559],\n [112-delta, 112+delta,'4', -0.018588],\n [144-delta, 144+delta, '1', -0.00038]\n ...\n\n '''\n def convertCentersToArea(self, centerData_, width_ ):\n #print (\" width_ = \" + str(width_))\n\n # 1) Make delta list\n sz = len(centerData_)\n delta = []\n for i in range(1, sz):\n assert centerData_[i] > centerData_[i-1]\n diff = ( centerData_[i][0] - centerData_[i-1][0] ) / 2\n delta.append(diff)\n\n print (len(delta) )\n\n # 2) Make new tuples\n if 0:\n #ORG\n minLeftCol = centerData_[0][0] - delta[0]\n if minLeftCol < 0:\n minLeftCol = 0\n maxRightCol = centerData_[sz-1][0] + delta[sz-2]\n if maxRightCol > (width_-1):\n maxRightCol = width_-1\n result = [ [ int(minLeftCol), int(centerData_[0][0] + delta[0]), centerData_[0][1] ,centerData_[0][2] ] ]\n for i in range(1, len(delta)):\n leftCol = int(centerData_[i][0] - delta[i-1])\n rightCol = int(centerData_[i][0] + delta[i] )\n result.append( [ leftCol, rightCol, centerData_[i][1] ,centerData_[i][2] ] )\n result.append ( [ int(centerData_[sz-1][0] - delta[sz-2]), int(maxRightCol), centerData_[sz-1][1] ,centerData_[sz-1][2] ] )\n else:\n # New\n # Assume the 'center' is actally the left of the character where the CTC has emitted it.\n minLeftCol = centerData_[0][0]\n if minLeftCol < 0:\n minLeftCol = 0\n maxRightCol = centerData_[sz-1][0] + delta[ len(delta) -1 ] * 2\n if maxRightCol > (width_-1):\n maxRightCol = width_-1\n\n result = [ [ int(minLeftCol), int(centerData_[0][0] + delta[0]*2), centerData_[0][1] ,centerData_[0][2] ] ]\n for i in range(1, len(delta)):\n leftCol = int(centerData_[i][0] )\n rightCol = int(centerData_[i][0] + delta[i]*2 )\n result.append( [ leftCol, rightCol, centerData_[i][1] ,centerData_[i][2] ] )\n\n result.append ( [ centerData_[sz-1][0], int(maxRightCol), centerData_[sz-1][1] ,centerData_[sz-1][2] ] )\n\n # print ( self.prettyPrintList(result)) #DBG\n\n return result\n\n def loadAndResizeImage(self, filename_, height_ = -1):\n verbose = 1\n\n assert os.path.isfile(filename_), \"ERROR: loadAndResizeImage() File image .jpg does not exist\"\n image = cv2.imread(filename_) # Numpy uint8 or so\n\n img0 = image[:,:,0]\n\n # Resize optional, via numpy/cv2\n if verbose > 0:\n print (\"loadAndResizeImage() org size \" + str(filename_) + \" \" + str(img0.shape))\n assert height_ > 0\n\n nRows = img0.shape[0]\n scaleFactor = (height_ * 1.0) / nRows\n nNewRows = int(img0.shape[0] * scaleFactor + 0.5)\n nNewCols = int(img0.shape[1] * scaleFactor + 0.5)\n if verbose > 0:\n print (\"loadAndResizeImage() new size [\" + str(nNewRows) + \" x \" + str(nNewCols) + \"]\" )\n\n img1 = cv2.resize(img0, (nNewCols, nNewRows)) #width, height\n\n #self.saveImage(\"test.jpg\",img1)\n #sys.exit(3)\n\n # Return new image AND orginal height\n return img1, img0, nRows\n\n def readAlignmentFile(self, aliFilename_):\n assert os.path.isfile(aliFilename_), \"ERROR: readAlignmentFile() --path File does not exist\"\n\n fp = open(aliFilename_,\"r\",encoding='utf-8')\n scores, syms, imageFilename, header = self.readOnePath(fp)\n fp.close()\n\n targetStrIdx = header.index(\"targetStr:\")\n assert targetStrIdx > 0,\"ERROR: no target string in header of .ali file\"\n targetStr = header[targetStrIdx + 10:].rstrip().replace(\"*\",\"\")\n\n assert len(self.alphabet) > 0, \"ERROR: readAlignmentFile() has an empty alphabet\"\n result = self.alphabet.symList2idxList(syms)\n\n return result, targetStr\n\n def readAlignmentFileFromZip(self, aliFilename_, zipFile_):\n assert zipFile_ is not None, \"ERROR: readAlignmentFileFromZip() zip file fp is empty.\"\n\n fp = io.TextIOWrapper(zipFile_.open(aliFilename_), 'utf8')\n scores, syms, imageFilename, header = self.readOnePath(fp)\n fp.close()\n\n targetStrIdx = header.index(\"targetStr:\")\n assert targetStrIdx > 0,\"ERROR: no target string in header of .ali file\"\n targetStr = header[targetStrIdx + 10:].rstrip().replace(\"*\",\"\")\n\n assert len(self.alphabet) > 0, \"ERROR: readAlignmentFileFromZip() has an empty alphabet\"\n result = self.alphabet.symList2idxList(syms)\n\n return result, targetStr\n\n def writePathString(self, aliFilename_, pathStr_):\n print (\"ALigner::writePathString() to file = \" + str(aliFilename_))\n\n fp = open(aliFilename_,\"w+\")\n assert fp\n fp.write(pathStr_)\n fp.close()\n\n def makePathString(self,header_,syms_,scores_):\n out = header_ + \"\\n\"\n for idx in range(len(scores_)):\n scoreStr = \"{0:.6f}\".format(scores_[idx])\n out = out + str(idx) + \" \" + str(idx+1) + \" \" + str(syms_[idx]) + \" \" + str(scoreStr) + \"\\n\"\n return out\n\n def readOnePath(self, fp_, headerLine_=\"\"):\n assert fp_, \"ERROR: readOnePath() fp is not valid\"\n\n if headerLine_ !=\"\":\n rawText = headerLine_.strip()\n else:\n rawText= fp_.readline()\n\n words = rawText.split()\n assert len(words) >= 2, \"ERROR: The header line in path does not have >= 2 entries (image name, path size, extra annotations)\"\n\n imageFilename = words[0]\n pathLength = int(words[1])\n\n mymin = +100000.0\n mymax = -100000.0\n scores = []\n syms = []\n for l in range(0, pathLength):\n l = fp_.readline().strip()\n words = l.split()\n assert len(words) == 4, \"ERROR: The timestamp line in path does not have 4 entries\"\n\n t = int(words[0])\n sym = words[2]\n if sym == \"SPACE\":\n sym = \"_\"\n\n score= float(words[3]) # prob or score\n if score > mymax:\n mymax = score\n if score < mymin:\n mymin = score\n\n scores.append(score)\n syms.append(sym)\n # end for() time line in path\n\n # Distinguish whether we have probs or scores\\\n # FIXME: reformat probs to scores.\n if mymax <= 0.0:\n scoreFlag = True\n else:\n scoreFlag = False\n\n assert len(scores) > 0 # Sometimes we generated empty paths\n assert len(scores) == pathLength\n assert len(scores) == len(syms)\n\n return scores, syms, imageFilename, rawText\n\n '''\n This file has a collection of one or more paths\n Paths could have Unicode symbols\n headerline (filename, width) others\n seq (t t+1 symbol score or prob)\n\n '''\n def readPath(self, filename_):\n print (\"Aligner.readPath() \" + str(filename_))\n assert os.path.isfile(filename_), \"ERROR: Aligner.readPath() File does not exist\"\n\n fp = open(filename_,\"r\",encoding='utf-8')\n\n # get > one < path only. We get 2 Python lists now with scores and symbols\n scores, syms, imageFilename, header = self.readOnePath(fp)\n assert len(scores) == len(syms)\n\n # Build path as list of [syms,scores]\n combinedSymsAndScores = []\n for idx in range(len(scores)):\n combinedSymsAndScores.append( [ syms[idx], scores[idx]] )\n\n # Resize image (we got the image name from path)\n resizedImg, orgImg, orgHeight = self.loadAndResizeImage(imageFilename, 32)\n\n # stretchedPath will have same width as org image e.g. 2277 entries for 2277 pixel columns in line\n orgImageWidth = orgImg.shape[1]\n strechedPath = self.stretchToLength(combinedSymsAndScores, orgImageWidth)\n\n # Clean the path. This is for easy visualization and not necessary otherwise. Example 'e e e e' becomes ' * * e *'\n\t\t# Input is a list of pairs of [ characters, score ]\n strechedPath = self.keepCentersOnly(strechedPath)\n\n # Grab the centers of symbols and build tuple list (time, sym, score)\n t = 0\n centerData = []\n centerCount = 0\n for t in range(0, len(strechedPath)):\n if strechedPath[t][0] != \"*\":\n centerData.append( [ t, strechedPath[t][0], strechedPath[t][1] ] )\n centerCount += 1\n\n self.drawLinesInImage(resizedImg, centerData, False)\n\n # areaData has the left, right columns for an image of [32 x width]. If we want to use this\n # for the orginal image then we need to scale the areadata with (orgwidth/ 32)\n\n # Draw segmentation path in resized image\n areaData = self.convertCentersToArea(centerData, orgImg.shape[1])\n\n showImage = True\n self.drawRectanglesInImage(orgImg, areaData, showImage)\n\n fp.close()\n\n# --------------------------------------\n# End of class Aligner, start of ForcedAligner\n# --------------------------------------\nclass ForcedAligner(Aligner):\n def __init__(self, outFile_, alphabet_, maxFeatures_=5000, maxTargets_=500):\n super(ForcedAligner, self).__init__(outFile_, alphabet_)\n print (\"ForcedAligner: __init__ \")\n\n self.alphabet = alphabet_\n assert len(alphabet_) > 0, \"ERROR: ForcedAligner() got an empty alphabet\"\n\n self.inf = -10000000.0\n self.no_path = -1\n\n # Simplified stack decoder for forced align. We look at the frontier i.e. all tokens at\n # time 't' which corrensponds to going through 'score' array row-by-row.\n # You can recombine neighboring tokens but not other paths.\n #\n # Search through [seqlen x targetLength] and store in arrays of [ maxWidth x maxTargets] i.e. maxWidth rows of [1 x maxTargets]\n self.height = maxFeatures_\n self.width = maxTargets_\n assert self.width > 0\n assert self.height > 0\n\n self.score = torch.zeros( (self.height, self.width), dtype=torch.float32)\n self.tb = torch.zeros( (self.height, self.width), dtype=torch.int32)\n\n # init\n self.clean()\n\n def clean(self):\n self.score.fill_(self.inf)\n self.tb.fill_(self.no_path)\n\n self.nTargets = -1\n self.nFeatureVectors = -1\n\n def forceLeadingAndTrailingBlank(self, targets_):\n '''Path alignment. Force a blank at start and stop to force align to space/SIL.\n Convert input (Torch int tensor) to list, check, and convert and return.\n '''\n blankId = 0 # alphabet['*'] == 0 typically\n tmp = targets_.tolist()\n\n if int(tmp[0]) != blankId:\n tmp.insert(0,0)\n if int(tmp[len(tmp)-1]) != blankId:\n tmp.append(0)\n\n return torch.IntTensor(tmp), len(tmp)\n\n '''\n Called via sequential.py (model) -> scribblelens/data.py decode()\n\n Same interface as in class Aligner.\n\n For the forced aligner, which is here, we just ignore the recognized path ( pathWithBlanks_, pathLogProbs_,)\n and instead will do a forced alignment.\n '''\n def makePath(self, pathWithBlanks_, log_probs_, \\\n targets_, targetLen_, \\\n alphabet_, \\\n imageFilename_, orgImageSize_, \\\n nFeatures_ ,\n verbose_ = 0):\n\n # Now apply targetLen to targets_ as targetLen_ is real length, and targets_ is batch with maxSize.\n assert targetLen_ > 0\n targets_ = targets_[:targetLen_]\n\n assert targets_.shape[0] == targetLen_\n assert len(alphabet_) > 0\n assert not torch.isnan(log_probs_).any(), \"ERROR: ForcedAligner.makePath() the input has NaNs in log probs!\"\n\n # Init score & tb array\n self.clean()\n\n # Make sure we have a 'blank' to align to, at start and stop of path.\n targets_, targetLen_ = self.forceLeadingAndTrailingBlank(targets_)\n\n # The return path is Kaldi-like with repeating sequence like 't t h h h e e e e' for 'the'\n # Optionally, we can split repeating symbols like 'oo' in 'door' based on symbolBoundaries\n path, symbolBoundaries, oversampleFactor = self.forceAlign3(targets_, log_probs_, imageFilename_, orgImageSize_, verbose_)\n\n # Stretch the path after force align to the width of the input features.\n # Use insertSeparators_ to split double 'oo' and 'ee' IFF you want that.\n path = self.stretchToLength(path, nFeatures_, insertSeparators_=False, symbolBoundaries_=symbolBoundaries)\n\n # Output forced align path to file\n targetStr = alphabet_.idx2str(targets_)\n pathStr = self.writePathToFile(imageFilename_, path, targetStr)\n\n return pathStr\n\n '''\n Should be optimized for use-case and model\n '''\n def updateTransitionCost(self, symIndex_, spaceIdx_ = 1):\n transitionSelf = -2 # loop, for all character which are non-blank -1.8 or -4.0 when 1000:1 then we see path diffs.\n transitionNext = -1 # go to next character in sequence -1.2 or -1.0\n\n blankSelf = transitionSelf * 2 # -1.5\n blankNext = transitionNext * 2 # -1.1\n \t\n selfTransitionCost = transitionSelf\n nextTransitionCost = transitionNext\n\n if symIndex_ == 0: # is a blank?\n selfTransitionCost = blankSelf\n nextTransitionCost = blankNext\n\n if symIndex_ == spaceIdx_: # is a space? Cannot stay in SPACE, and expensive to go through\n selfTransitionCost = -1000.0 # -1000.0\n nextTransitionCost = -100.0 # -100.0\n\n return [selfTransitionCost, nextTransitionCost]\n\n '''\n When CNN stack produce nFeatureVectors < nTargets, we replicate logprobs\n in effect oversampling when generating a path.\n '''\n def replicateRows(self, data_, factor_ = 2 ):\n assert len(data_.shape ) == 2\n assert factor_ > 1\n\n newData = data_.repeat_interleave(factor_,dim=0)\n\n assert factor_ * data_.shape[0] == newData.shape[0] # new height\n assert data_.shape[1] == newData.shape[1] # same width\n assert data_[0,0] == newData[0,0] # 1st row check\n\n if factor_ >= 2:\n assert data_[0,0] == newData[1,0] # 2nd row check\n\n assert len(newData.shape ) == 2\n\n return newData\n\n '''\n Visualize this as rows of length [ 1 x nTargets] of the sequence,\n and number of rows == sequenceLength\n\n We process the frontier of tokens at every time 't'\n and we can only recombine tokens from previous and current target index,\n which is what we need for forced align\n\n CHECK:\n - make sure we use the correct seqLen length when handling batches > 1\n '''\n def forceAlign3(self, targets_, logprobs_, imageFilename_, orgImageSize_, verbose_ = 0):\n\n nFeatureVectors = logprobs_.shape[0]\n nOrgFeatureVectors = orgImageSize_[1].item()\n nClasses = logprobs_.shape[1]\n nTargets = len(targets_)\n\n if verbose_ > 0:\n print (\"forceAlign3() nFeatureVectors = \" + str(nFeatureVectors) + \" nTargets = \" +str(nTargets) + \\\n \" nClasses = \" + str(nClasses) + \" orgImageSize_ =\" + str(orgImageSize_))\n print (\"forceAlign3() logprobs_.shape row[0]= \" + str(logprobs_[0,:].shape))\n print (\"forceAlign3() logprobs_.shape = \" + str(logprobs_.shape))\n print (\"forceAlign3() targets_.shape = \" + str(targets_.shape))\n print (\"forceAlign3() targets_ = \" + str(targets_))\n print (\"forceAlign3() score.shape = \" + str(self.score.shape))\n print (\"forceAlign3() score.shape row[0]= \" + str(self.score[0,:].shape))\n print (\"forceAlign3() nTargets = \" + str(nTargets) + \" nClasses = \" + str(nClasses) + \" nFeatureVectors=seqLen = \" + str(nFeatureVectors) )\n\n assert len(logprobs_.shape ) == 2 # 2D array\n\n # Copy for safe keeping\n self.nTargets = nTargets\n self.nFeatureVectors = nFeatureVectors\n\n # Assure fit in score and traceback\n assert self.height >= nFeatureVectors\n assert self.width >= nTargets\n\n # Assure more feature vectors than targets. We need to handle this, maybe via duplicating inputs\n # We use factor to indicate oversampling. We actually duplicate logprobs[] by the factor and let it ripple through\n factor = 1 # Normal case, 95%+ of inputs\n if nFeatureVectors < nTargets:\n factor = int((nTargets * 1.0) /nFeatureVectors ) + 1\n print (\"WARNING: imageFilename_ = \" + str(imageFilename_) + \" oversampled path as not enough feature vectors. nFeatureVectors= \" + str(nFeatureVectors) + \", nTargets= \" + str(nTargets) )\n logprobs_ = self.replicateRows(logprobs_, factor)\n nFeatureVectors = logprobs_.shape[0] # New size\n\n assert nFeatureVectors >= nTargets\n assert nClasses == logprobs_.shape[1]\n\n classIndexOfSpace = -1\n spaceSym = \" \"\n if self.alphabet.existDict(spaceSym):\n classIndexOfSpace = self.alphabet.ch2idx(spaceSym)\n assert classIndexOfSpace == 1\n\n # Init search\n self.score[0][0] = logprobs_[0][0]\n self.tb [0][0] = 0 # self.no_path\n\n if verbose_ > 0:\n print ( \"\\n-------t= row= \" + str(0) +\"----------- factor = \" + str(factor) + \"-------\")\n print (\"\\nAFTER : row[0]=\" + str(self.score[0,:1]))\n print (\"AFTER : tb[0]=\" + str(self.tb[0,:1]))\n\n for row in range(1, nFeatureVectors):\n lastCol = min(row, nTargets-1)\n\n if verbose_ > 0:\n print ( \"\\n-------t= row= \" + str(row) +\" of \" +str(nFeatureVectors) + \"-----------\")\n print (\"BEFORE: lastCol = \" + str(lastCol) )\n torch.set_printoptions(sci_mode=False)\n print (\"BEFORE: row[t=\" + str(row) + \"]=\" + str(self.score[row,:lastCol+1]))\n print (\"BEFORE: tb[t=\" + str(row) + \"]=\" + str(self.tb[row,:lastCol+1]))\n print (\"forceAlign3() nTargets = \" + str(nTargets) + \" nClasses = \" + str(nClasses) + \" nFeatureVectors=seqLen = \" + str(nFeatureVectors) )\n\n for col in range(lastCol+1):\n #for col in range(lastCol):\n '''\n a) The only way to get to targetIdx==0 is via SELF transition. For all time stamps (rows)\n\n b) For the final targetIdx 'lastCol', at time==row==0, you can only do a NEXT transition.\n If time > 0 then NEXT and SELF are possible. This is important at end of path.\n\n c) Choose the best of SELF and NEXT (from previous target symbol) transitions\n\n TODO:\n - handle '_' space alignment with high transitions i.e. force SPACE to be at correct place.\n '''\n selfTransitionCost, nextTransitionCost = self.updateTransitionCost(targets_[col], classIndexOfSpace)\n\n if col == 0 or (col == lastCol and row == 0):\n if col == 0:\n # a) The only way to get to targetIdx==0 is via SELF transition. For all time stamps (rows)\n prevScore = self.score[row-1][col].item()\n prevTB = col\n targetCol = targets_[col]\n currentScore = logprobs_[row][targetCol].item()\n\n assert prevScore > self.inf, \"ERROR: you are referring to a score that is not initialized!\"\n\n self.score[row][col] = prevScore + selfTransitionCost + currentScore\n self.tb [row][col] = prevTB\n newScore = self.score[row][col].item()\n\n if verbose_ > 0:\n print (\"SELF: score[t=\" + str(row) + \"][class=\" + str(col) + \"]= \" + str(newScore) + \" computed as \" + \\\n \"self.score[\" + str(row - 1) + \"][\" + str(col) +\"] \" + str(prevScore) + \\\n \" + selfTransitionCost \" + str(selfTransitionCost) + \\\n \" + logprobs_[\"+str(row)+ \"][\" + str(targetCol) + \"]= \" + str(currentScore) )\n print (\"SELF: tb[t=\" + str(row) + \"][class=\" + str(col) + \"]= prevClass = \" + str(prevTB) )\n\n else:\n # CHECK: this might be unnecessary.\n # b) For the final targetIdx 'lastCol', at time==row==0, you can only do a NEXT transition.\n # If time > 0 then NEXT and SELF are possible. This is important at end of path.\n prevScore = self.score[row-1][col-1].item()\n prevTB = col - 1\n targetCol = targets_[col]\n currentScore = logprobs_[row][targetCol].item()\n assert prevScore > self.inf, \"ERROR: you are referring to a score that is not initialized!\"\n\n self.score[row][col] = prevScore + nextTransitionCost + currentScore\n self.tb [row][col] = prevTB\n newScore = self.score[row][col].item()\n\n if verbose_ > 0:\n print (\"NEXT: score[t=\" + str(row) + \"][class=\" + str(col) + \"]= \" + str(newScore) + \" computed as \" + \\\n \"self.score[\" + str(row - 1) + \"][\" + str(col - 1) +\"] \" + str(prevScore) + \\\n \" + nextTransitionCost \" + str(nextTransitionCost) + \\\n \" + logprobs_[\"+str(row)+ \"][\" + str(targetCol) + \"]= \" + str(currentScore) )\n print (\"NEXT: tb[t=\" + str(row) + \"][class=\" + str(col) + \"]= prevClass = \" + str(prevTB) )\n else:\n # c) Choose the best of SELF and NEXT (from previous target symbol) transitions\n # Compare based on sum of path score PLUS transition costs\n targetCol = targets_[col] # Vital. Indirect. 'col' pulls indices out of the target vector to retrieve log_probs from.\n currentScore = logprobs_[row][targetCol].item()\n\n prevSelfScore = self.score[row-1][col].item() + selfTransitionCost\n prevNextScore = self.score[row-1][col-1].item() + nextTransitionCost\n\n if prevSelfScore > prevNextScore:\n # self transition is best\n prevTB = col\n prevScore = prevSelfScore\n transition = \"self\"\n else:\n # next transition is best\n prevTB = col - 1\n prevScore = prevNextScore\n transition = \"next\"\n\n self.score[row][col] = prevScore + currentScore\n self.tb [row][col] = prevTB\n newScore = self.score[row][col].item()\n\n if verbose_ > 0:\n print ( \"col= \" + str(col) + \" (\" +str(transition) + \"): score[t=\" + str(row) + \"][class=\" + str(col) + \"]= \" + str(newScore) + \" computed as \" + \\\n \"self.score[\" + str(row - 1) + \"][\" + str(col - 1) +\"] \" + str(prevScore) + \\\n \" + logprobs_[\"+str(row)+ \"][\" + str(targetCol) + \"]= \" + str(currentScore) )\n print ( \"col= \" + str(col) + \" (\" + str(transition) + \"): tb[t=\" + str(row) + \"][class=\" + str(col) + \"]= prevClass = \" + str(prevTB) )\n\n if verbose_ > 0:\n torch.set_printoptions(sci_mode=False)\n print (\"\\nAFTER : row[t=\" + str(row) + \"]=\" + str(self.score[row,:lastCol+1]))\n print (\"AFTER : tb[t=\" + str(row) + \"]=\" + str(self.tb[row,:lastCol+1]))\n\n # Finish up, retrieve best path via TraceBack array 'tb'\n path, symbolBoundaries = self.bestPath(targets_, logprobs_, nFeatureVectors, verbose_)\n\n return path, symbolBoundaries, factor\n\n def bestPath(self, targets_, logprobs_, nFeatureVecs_, verbose_ = 0):\n assert nFeatureVecs_ > 0\n if verbose_ > 0:\n print (\"bestPath() tb.shape = \" + str(self.tb.shape))\n print (\"bestPath() self.nTargets = \" + str(self.nTargets ) + \" self.nFeatureVectors =\" + str(nFeatureVecs_))\n\n row = nFeatureVecs_ - 1\n targetIdx = self.nTargets - 1\n\n # 1) get the traceback of symbols\n pathsSyms = []\n pathScores = []\n\n symbolBoundaries = [ ] # Such that we can seperate 'oo' and 'ee'\n prevTargetIdx = -1\n\n while row >= 0:\n # Get symbol & score\n chIdxInAlphabet = targets_[targetIdx].item()\n\n #myscore = self.score[row][chIdxInAlphabet].item() # Path score (incl transition), or do we just want the instantaneous logProbs from LSTM?\n myscore = logprobs_[row][chIdxInAlphabet].item()\n\n # Whenever we change the targetIdx (compared to prevTargetIdx) that is the begin of a new symbol\n if verbose_ > 1:\n print (\"class[t=\" + str(row) + \"]= \" + str(targetIdx) + \" chIdxInAlphabet=\" +str(chIdxInAlphabet) )\n\n # Save data\n pathsSyms.insert (0, chIdxInAlphabet)\n pathScores.insert(0, myscore)\n\n if prevTargetIdx != targetIdx:\n symbolBoundaries.insert(0, [row, self.alphabet.idx2ch(chIdxInAlphabet) ] )\n\n # Shift\n prevTargetIdx = targetIdx\n targetIdx = self.tb[row][targetIdx].item()\n row -= 1\n\n assert len(symbolBoundaries) > 0\n\n # 2) Generate a string from result\n # We have the path in result. An alignment for every character to every feature vector\n alignedStr = self.alphabet.idx2str(pathsSyms, noDuplicates=False, noBlanks=False)\n\n assert nFeatureVecs_ == len(alignedStr), \"ERROR: The generated forced align string should have same length as the number of feature vector==seqLen\"\n\n # 3) Generate a path incl. score. This is a Python list of lists [label, score]\n path = self.pathFromStringAndLogprobs(alignedStr, pathScores)\n\n return path, symbolBoundaries\n\n# --------------------------------------\n'''\n log probs shape = torch.Size([78, 68])\n\n where 68 is alphabet size, so 78 time steps\n echo \"*door dien het soo mistich was Doch de zee begon te slechten,*\" | wc\n 1 12 63\n\n Fun, not ideal, SOMETIMES, we compressed too much. We could have 49 feature vectors but 63 targets.\n If we have more targets than feature vectors, then we duplicate/n-plicate each input/feature vector\n and we go from 49 to 98 feature vectors to align vs 63 targets.\n'''\n\n# Class #0 is the blank,\nmylogprobs = torch.tensor([[ -0.0000, -13.9620, -23.1881, -18.6309, -21.9276,\n -21.4505, -15.4502, -21.7958, -17.4019, -20.4657,\n -21.2391, -18.8014, -25.8747, -20.6013, -29.6001,\n -22.9801, -17.6486, -20.2540, -20.9769, -21.6086,\n -17.7701, -14.7663, -18.6713, -18.0158, -18.4053,\n -24.8438, -36.9585, -14.0385, -20.4455, -20.6708,\n -15.1912, -19.2747, -22.5260, -20.1671, -21.7179,\n -19.6354, -22.8083, -27.2353, -18.7717, -20.1562,\n -24.7157, -18.7732, -23.9670, -19.5851, -21.0046,\n -29.2015, -14.8001, -26.2165, -19.1668, -19.2888,\n -21.0671, -21.8788, -26.5340, -23.7708, -25.6324,\n -16.1936, -25.9904, -24.0358, -20.3967, -15.2838,\n -29.5235, -20.0191, -20.4623, -25.8248, -20.7026,\n -17.5870, -26.7759, -24.8957],\n [ -0.0001, -11.4726, -15.8401, -17.2140, -16.4461,\n -18.1099, -11.4369, -16.1479, -11.7512, -12.9534,\n -15.3252, -12.8600, -19.6133, -15.6562, -23.5516,\n -18.1197, -11.9423, -12.3900, -18.1929, -15.7402,\n -12.0273, -12.1579, -13.6992, -13.0294, -11.9877,\n -16.0261, -26.9402, -11.9732, -15.6247, -14.0538,\n -11.8318, -15.5793, -16.8586, -15.8972, -16.7129,\n -13.0778, -16.9743, -20.0113, -14.9004, -15.9663,\n -18.4604, -12.4369, -20.2782, -15.6113, -14.5692,\n -23.1558, -10.8254, -20.8961, -15.6453, -15.7780,\n -18.7081, -15.6663, -21.2306, -17.7183, -21.3342,\n -12.4544, -17.0469, -19.5063, -16.8705, -11.1556,\n -23.2844, -16.3018, -13.9419, -18.4861, -14.3801,\n -13.9396, -20.7307, -18.9278],\n [ -0.4946, -10.9890, -9.6145, -14.4803, -11.6633,\n -14.9429, -10.5413, -8.8707, -10.6186, -5.6293,\n -8.1630, -7.2985, -14.2162, -7.9735, -15.6695,\n -11.9873, -4.4205, -8.7767, -18.4433, -14.3625,\n -4.3399, -15.4782, -8.1939, -3.8534, -6.4781,\n -11.0122, -17.2646, -13.0473, -10.3627, -7.5607,\n -8.1184, -12.9345, -11.0987, -11.2792, -18.3102,\n -1.1110, -10.7940, -18.3144, -12.5329, -7.8087,\n -12.9726, -6.7561, -16.2870, -12.1989, -7.9480,\n -19.1146, -8.3319, -13.3906, -14.7972, -12.2693,\n -16.1299, -11.4283, -16.3586, -15.7596, -20.6447,\n -7.9520, -8.5888, -16.9559, -16.4546, -5.9243,\n -17.7056, -17.8127, -9.6809, -10.0776, -6.9463,\n -9.0122, -16.8663, -14.4187],\n [ -6.2827, -10.1348, -16.0833, -4.8323, -10.1315,\n -11.7466, -15.4324, -11.9646, -16.0185, -14.8263,\n -7.2877, -7.9080, -10.0412, -0.0539, -8.9935,\n -7.9229, -7.4328, -16.1447, -15.4627, -19.3244,\n -18.2096, -9.7765, -11.3556, -8.0125, -11.5944,\n -19.3104, -13.9115, -9.1632, -3.2749, -15.5419,\n -7.4921, -13.6233, -8.2047, -13.3247, -10.8381,\n -9.7789, -10.3945, -13.5411, -15.5035, -11.2470,\n -9.4846, -20.5172, -8.4498, -10.4502, -15.0523,\n -8.8800, -15.6665, -8.4255, -11.6221, -9.3056,\n -10.0819, -10.6422, -10.6564, -17.4891, -14.0052,\n -14.7638, -17.0827, -11.8645, -14.1961, -10.1833,\n -12.2612, -13.6331, -10.8048, -15.0639, -8.9064,\n -10.6173, -15.2501, -15.2483],\n [ -15.6361, -10.5647, -15.0561, -6.9288, -10.4569,\n -9.5331, -19.9755, -13.3040, -16.4132, -12.4006,\n -7.2408, -15.3834, -7.9693, -8.0795, -0.0181,\n -4.9266, -17.6903, -19.9832, -12.4510, -13.3125,\n -18.5628, -16.0449, -14.1777, -12.5487, -19.6402,\n -17.3650, -6.4454, -15.9815, -11.2758, -16.9176,\n -17.7083, -14.1667, -9.4183, -14.5153, -10.9065,\n -17.6018, -11.7358, -8.9915, -19.0328, -11.5257,\n -12.5652, -23.4341, -9.6887, -13.4318, -17.6025,\n -8.6890, -15.0005, -5.4967, -18.0330, -15.8637,\n -9.5577, -14.1192, -6.2994, -11.9831, -11.2011,\n -17.9400, -15.4261, -11.8279, -13.8567, -17.0951,\n -9.3317, -15.1781, -13.3076, -15.7813, -12.5788,\n -14.4926, -11.6221, -14.2279],\n [ -13.4288, -14.2686, -13.5572, -15.4986, -15.2427,\n -13.2128, -21.5313, -17.6004, -19.9259, -10.4971,\n -6.8827, -13.1532, -11.6676, -10.9067, -6.8297,\n -0.0061, -20.1170, -14.7514, -21.1209, -10.6545,\n -15.6043, -23.0945, -19.5655, -12.9961, -19.4681,\n -13.5224, -5.8492, -18.3368, -12.5394, -15.3374,\n -20.7299, -16.4863, -7.3363, -16.5417, -11.5917,\n -17.7114, -14.9105, -10.4403, -24.6723, -8.6923,\n -17.2287, -20.6917, -19.3398, -18.0148, -17.8481,\n -13.3084, -17.7747, -11.3117, -22.6014, -20.4626,\n -18.7715, -10.3260, -9.1453, -14.6719, -19.3054,\n -19.3772, -12.9897, -18.1605, -19.9882, -15.0028,\n -11.3880, -19.6706, -11.8692, -13.5127, -11.7671,\n -14.6744, -14.9828, -16.1172],\n [ -0.1324, -4.8511, -24.6525, -2.1615, -18.3575,\n -8.3724, -15.3594, -12.1787, -12.6762, -17.5954,\n -14.5456, -17.2110, -13.6157, -7.6002, -11.6953,\n -8.3318, -15.7798, -27.1874, -9.7153, -12.5975,\n -14.8952, -13.8032, -18.0219, -13.2494, -21.6650,\n -26.0789, -24.2324, -13.7641, -16.1092, -22.5320,\n -19.4452, -16.0383, -19.0671, -15.6665, -13.2506,\n -21.1427, -16.8551, -20.1829, -20.1859, -16.3328,\n -21.7043, -25.9120, -14.2631, -16.8418, -24.3504,\n -19.2556, -13.1559, -14.8045, -19.2278, -20.1909,\n -12.1050, -22.9101, -17.7996, -17.9139, -20.3568,\n -17.0323, -28.0614, -17.1933, -16.7506, -16.7502,\n -17.0497, -21.0720, -20.8708, -28.6884, -18.7893,\n -14.9290, -21.9944, -22.1102],\n [ -7.5949, -6.9717, -20.4578, -0.0047, -17.1972,\n -15.1984, -19.1429, -12.1264, -14.3156, -16.5230,\n -15.6340, -24.6156, -9.6382, -7.2974, -6.9368,\n -10.1337, -13.3587, -24.1779, -8.1345, -10.9298,\n -21.2738, -9.6228, -13.6491, -12.9340, -24.8387,\n -27.8287, -21.8744, -19.2303, -15.2508, -22.5907,\n -20.8450, -19.1065, -16.6523, -21.3369, -11.6004,\n -23.8109, -14.7156, -12.4496, -19.4288, -18.5934,\n -16.6047, -29.9225, -8.1760, -17.0307, -21.2093,\n -14.5482, -14.3342, -10.0334, -19.8275, -17.5253,\n -7.1346, -21.9107, -13.0562, -13.6357, -18.9734,\n -17.0682, -25.9709, -12.6886, -14.6402, -23.0029,\n -19.0416, -19.6301, -21.2553, -28.1669, -18.0178,\n -20.3169, -19.9099, -20.5499],\n [ -0.0004, -9.4316, -29.4794, -8.1347, -16.9531,\n -15.2945, -12.5565, -15.2880, -10.9378, -17.0578,\n -18.6114, -19.2904, -22.3876, -14.3084, -17.9206,\n -19.0847, -17.3466, -25.4043, -17.7635, -16.4040,\n -16.4408, -14.1893, -22.0548, -21.3925, -27.4252,\n -23.5834, -31.0259, -22.5184, -25.4093, -29.9841,\n -24.8228, -24.5202, -29.0336, -18.9434, -18.3274,\n -23.1171, -25.9857, -22.4207, -23.4583, -26.9300,\n -29.5777, -30.2463, -23.0079, -23.3361, -28.4776,\n -30.2140, -15.5809, -26.2277, -25.5164, -27.0989,\n -21.3204, -28.6737, -27.1978, -22.9120, -26.4182,\n -23.5499, -32.2680, -26.1991, -24.1505, -20.6374,\n -27.1646, -27.9199, -24.6510, -37.1778, -25.3554,\n -21.6086, -29.8170, -30.7009],\n [ -3.9961, -8.3438, -26.0515, -0.1343, -7.6161,\n -2.3468, -6.5790, -9.5163, -8.1329, -18.3629,\n -11.5450, -9.5137, -15.5586, -5.0435, -7.4068,\n -11.6135, -15.1750, -22.6142, -10.2436, -13.4975,\n -16.7040, -7.5507, -17.8237, -20.5354, -21.5875,\n -16.5190, -16.1588, -12.7034, -14.7810, -27.6047,\n -19.2365, -18.2300, -20.8913, -11.0051, -6.6282,\n -20.7415, -20.3777, -12.9108, -15.7513, -23.9942,\n -21.6297, -28.5265, -12.4118, -15.8646, -26.4825,\n -14.7726, -15.0135, -17.0458, -14.5146, -18.5614,\n -14.7170, -21.1839, -18.1320, -16.5503, -10.4135,\n -23.2293, -28.7316, -17.0910, -14.9053, -14.3156,\n -11.9599, -16.1616, -17.5687, -29.9907, -21.0201,\n -14.6905, -19.0646, -22.3658],\n [ -5.3402, -10.3217, -17.6965, -11.3692, -12.7159,\n -9.6010, -13.3772, -10.7736, -7.3395, -10.1046,\n -5.9859, -0.4383, -8.4269, -1.0827, -14.0432,\n -6.6766, -5.5813, -11.7480, -17.1838, -13.5729,\n -13.6456, -11.6680, -19.0926, -9.5344, -8.6822,\n -12.9622, -10.5896, -9.3912, -6.1663, -16.1084,\n -14.2465, -17.1981, -12.4087, -14.4326, -9.5986,\n -13.3819, -12.2022, -14.9239, -21.3186, -19.7328,\n -16.5564, -19.3686, -19.4955, -15.3480, -20.3536,\n -12.3935, -18.3175, -17.8502, -18.5417, -19.7710,\n -22.4060, -13.1004, -21.3210, -19.0785, -19.3805,\n -22.8529, -15.8072, -21.7838, -20.6478, -10.0628,\n -12.1529, -18.9956, -8.7709, -21.6944, -10.1350,\n -14.7098, -19.2770, -18.2895],\n [ -9.8252, -7.8621, -19.9293, -15.5386, -15.0172,\n -10.6343, -8.5348, -11.3716, -0.0095, -9.1240,\n -12.6243, -4.8011, -10.8811, -8.9035, -17.5596,\n -16.3650, -9.0474, -13.7190, -12.9874, -10.7939,\n -11.5569, -9.4320, -21.9260, -16.4849, -10.5473,\n -10.3611, -14.7782, -12.9952, -15.1265, -18.0877,\n -19.2918, -17.6943, -22.3664, -12.7193, -11.8329,\n -15.8678, -15.4012, -15.5590, -19.1427, -28.1225,\n -18.9412, -17.1356, -22.6317, -16.6830, -21.5677,\n -18.0920, -15.2177, -24.2262, -18.6743, -23.4307,\n -24.2330, -18.8409, -26.4314, -16.4399, -19.0051,\n -23.1401, -16.6433, -21.4905, -20.2080, -15.6295,\n -15.3201, -20.4272, -12.4130, -26.7949, -15.1888,\n -17.7490, -20.9683, -20.4042],\n [ -9.5136, -8.6398, -24.8047, -16.6156, -15.1191,\n -10.5206, -0.5299, -11.5824, -0.8905, -16.2451,\n -22.1144, -8.5709, -22.0522, -15.0371, -25.1624,\n -26.9797, -12.0482, -17.3405, -13.1108, -14.0256,\n -9.1848, -8.6311, -22.9108, -24.1546, -13.5084,\n -10.8440, -24.2074, -14.6059, -22.5047, -23.1083,\n -19.2554, -20.9590, -31.5645, -9.5410, -15.1789,\n -14.6785, -22.6264, -20.3565, -12.3869, -32.8234,\n -24.4382, -15.6895, -23.4566, -17.8088, -22.5859,\n -25.4447, -13.5708, -31.5663, -14.6136, -20.8502,\n -26.2083, -23.9960, -31.3873, -19.4451, -17.9948,\n -21.5324, -23.1241, -21.2812, -19.2012, -15.7672,\n -20.9305, -21.1034, -18.9201, -29.9390, -22.6819,\n -15.6674, -25.3072, -24.6679],\n [ -4.4860, -1.6541, -24.3490, -10.6418, -12.6634,\n -11.0211, -0.2357, -16.4465, -11.1416, -19.0771,\n -23.5526, -14.0811, -28.1013, -16.7974, -23.6779,\n -23.1857, -16.1815, -20.1965, -15.0376, -16.1673,\n -8.8594, -8.3787, -23.1356, -23.7773, -20.8898,\n -16.4946, -29.8158, -15.5594, -23.5424, -24.9547,\n -13.7554, -21.0791, -28.3185, -4.9928, -18.3895,\n -12.1060, -25.8282, -21.1519, -9.9324, -23.2819,\n -26.6106, -17.9080, -19.5848, -14.7122, -19.4194,\n -28.2247, -12.1392, -30.3147, -13.1742, -12.9956,\n -19.7423, -21.1665, -23.1179, -22.6794, -18.4673,\n -15.6940, -26.0595, -16.5477, -18.1736, -15.1028,\n -27.4731, -21.9079, -22.5986, -26.2684, -23.7298,\n -8.6696, -27.5975, -26.4396],\n [ -5.1086, -0.0070, -14.7093, -9.4544, -12.9564,\n -12.0013, -9.9544, -11.4388, -10.2761, -10.0027,\n -17.1023, -17.2591, -14.7357, -13.0384, -13.7848,\n -13.3167, -11.0535, -18.3150, -10.4023, -9.9506,\n -7.5649, -10.6165, -14.7702, -11.6911, -16.9346,\n -16.4402, -22.3568, -14.5856, -17.5302, -14.9417,\n -15.6742, -19.1595, -18.2920, -12.5387, -17.8080,\n -13.3498, -15.3654, -16.2982, -12.2900, -16.6940,\n -20.4481, -15.7691, -14.6068, -13.6560, -14.0514,\n -20.9237, -9.5520, -18.1999, -19.5632, -14.4427,\n -15.0361, -20.0010, -18.0651, -14.9316, -19.4847,\n -14.0900, -16.8566, -15.7064, -15.7215, -16.3316,\n -24.6672, -19.8402, -17.9409, -21.8789, -16.2736,\n -12.1069, -21.7817, -20.8797],\n [ -3.9709, -12.0596, -11.1482, -1.4596, -5.0161,\n -10.1651, -13.4567, -0.9305, -13.8993, -8.7749,\n -10.1896, -17.8348, -10.5925, -4.8876, -1.6135,\n -4.3806, -5.9237, -16.2199, -11.5526, -8.8652,\n -10.4777, -11.7705, -2.2532, -5.8594, -18.3989,\n -13.9990, -11.0965, -17.8245, -11.3542, -14.8450,\n -19.0103, -20.8756, -9.1030, -20.1287, -11.6565,\n -14.0445, -12.0668, -8.5256, -11.9788, -12.6347,\n -16.9203, -20.4781, -5.7019, -16.5534, -12.5374,\n -11.8173, -10.1497, -4.2956, -19.8446, -13.4251,\n -10.5029, -19.5678, -12.4870, -9.2922, -14.0989,\n -15.6246, -15.9240, -15.1857, -12.1840, -12.8954,\n -16.1800, -15.6794, -15.9102, -19.2740, -13.6195,\n -15.5518, -15.0160, -17.4236],\n [ -10.9486, -10.2928, -11.7610, -26.4067, -19.1013,\n -24.1652, -20.4107, -20.3830, -11.7829, -0.0014,\n -8.8042, -10.4948, -12.5285, -13.7036, -18.6473,\n -10.8185, -11.4007, -8.0922, -27.6864, -12.7681,\n -10.6577, -21.5576, -23.5829, -10.4859, -13.6290,\n -10.8513, -14.8159, -23.4167, -16.6824, -11.9984,\n -19.7362, -21.7784, -15.2028, -18.1110, -22.1087,\n -11.2192, -15.6675, -17.1807, -29.1099, -17.1684,\n -19.4019, -15.6437, -30.9012, -20.2597, -15.5849,\n -24.9473, -17.4919, -24.4700, -30.2810, -26.5153,\n -29.1594, -13.1696, -21.9375, -20.1660, -33.2739,\n -20.8967, -7.4563, -27.1369, -29.5920, -17.7990,\n -25.3144, -29.9441, -10.6903, -18.2232, -9.3476,\n -19.6377, -24.6592, -22.4772],\n [ -0.0547, -9.1877, -24.0313, -15.8575, -14.0487,\n -13.5235, -12.5466, -17.7564, -10.3192, -10.6787,\n -9.1480, -2.9410, -19.2411, -9.6682, -20.7572,\n -13.8596, -11.5818, -16.1950, -24.1786, -20.8485,\n -12.5403, -15.5962, -25.8335, -15.1378, -15.4511,\n -16.1310, -22.1669, -13.8696, -15.5487, -22.1939,\n -15.3419, -20.6545, -21.1621, -12.2794, -19.7634,\n -12.8611, -21.1886, -24.1476, -25.6038, -21.4009,\n -25.5597, -21.4835, -28.9293, -18.6164, -24.3072,\n -26.4905, -18.4908, -28.6058, -24.2614, -24.2460,\n -28.1510, -18.3914, -27.6178, -27.5338, -26.6466,\n -24.3914, -21.3507, -29.7037, -27.9777, -11.2236,\n -23.1673, -26.6320, -13.6760, -27.1773, -15.4406,\n -15.0652, -27.7257, -26.7912],\n [ -9.4661, -6.0484, -17.6462, -14.5059, -17.1846,\n -10.1431, -13.6305, -12.3308, -0.0228, -7.4847,\n -8.0080, -4.9725, -4.6239, -6.3944, -12.7653,\n -12.0820, -10.1320, -14.0939, -10.1159, -9.7393,\n -13.4228, -10.5193, -20.5504, -11.9110, -8.3420,\n -13.1641, -12.9793, -10.3132, -10.8844, -14.4954,\n -17.2218, -12.9869, -17.5410, -13.1080, -9.7641,\n -16.5131, -10.0572, -14.4333, -21.0460, -23.3858,\n -13.8199, -17.3842, -20.3957, -14.3517, -20.9609,\n -13.7241, -13.9190, -18.1890, -18.3880, -23.7457,\n -20.2863, -15.9635, -21.3205, -13.8715, -18.1312,\n -20.9010, -14.1011, -18.9926, -17.9373, -15.5033,\n -11.4101, -18.2202, -9.1846, -23.5366, -10.8775,\n -17.3352, -17.1554, -16.3514],\n [ -10.8550, -12.2986, -23.9590, -14.9816, -19.0495,\n -9.1710, -12.2250, -10.1652, -0.0003, -11.6717,\n -14.4872, -12.2562, -11.2116, -12.7657, -13.7994,\n -18.0802, -16.1303, -21.7782, -9.5226, -9.8041,\n -14.9621, -13.2589, -21.0339, -19.8919, -15.7995,\n -14.9938, -17.7696, -16.6568, -20.2336, -21.7744,\n -27.3270, -17.6897, -26.3487, -16.9357, -12.2027,\n -23.4543, -17.0780, -17.7160, -21.4473, -31.0798,\n -21.2643, -22.1807, -22.7939, -20.5316, -27.3394,\n -19.8434, -13.5560, -21.2812, -21.2212, -29.7886,\n -22.8031, -26.2795, -27.6820, -13.4616, -18.2374,\n -25.0511, -22.3118, -22.7461, -18.6032, -20.0971,\n -13.3281, -21.0621, -16.6610, -32.3046, -20.0323,\n -22.8994, -20.3238, -21.9077],\n [ -2.9016, -3.9676, -14.8745, -5.6672, -11.6027,\n -9.3324, -5.3166, -7.7193, -1.0022, -8.1735,\n -11.4790, -9.8441, -8.2475, -5.6857, -11.1121,\n -12.9430, -6.9070, -11.4384, -5.8720, -5.9143,\n -13.0753, -0.6255, -12.4600, -13.8301, -11.0013,\n -12.6802, -16.8859, -9.4731, -10.7106, -15.6900,\n -13.7441, -13.1589, -16.2079, -11.4735, -5.5895,\n -15.0355, -11.7081, -8.7045, -11.4165, -21.0427,\n -11.6502, -16.8774, -11.7779, -11.3232, -15.9826,\n -12.5090, -8.1849, -15.2835, -10.2695, -13.7387,\n -11.1888, -14.4658, -16.4672, -9.1125, -12.5653,\n -14.3427, -16.7968, -10.7553, -10.5375, -13.9813,\n -13.3505, -12.1654, -10.9891, -22.4099, -12.9328,\n -14.0875, -15.9059, -16.1202],\n [ -9.1999, -6.7504, -21.2064, -8.4829, -14.8647,\n -15.4958, -10.0911, -18.4414, -12.6262, -21.2652,\n -19.3789, -12.4309, -16.0417, -9.0983, -21.9576,\n -18.4401, -10.5305, -15.1669, -12.8859, -17.0128,\n -23.5812, -0.0023, -19.9550, -20.4629, -15.6473,\n -21.4049, -24.5103, -7.7351, -10.2115, -22.3918,\n -11.0405, -19.2829, -17.9743, -15.7702, -8.9408,\n -20.9677, -18.0812, -13.7059, -14.1371, -25.4376,\n -16.1343, -23.5547, -13.4894, -13.0032, -20.2277,\n -13.5842, -18.8637, -23.0263, -10.6951, -10.7334,\n -15.0698, -14.9115, -19.8341, -19.7259, -15.0592,\n -20.4346, -24.8485, -13.2051, -14.9886, -17.3665,\n -21.3648, -13.0104, -15.8154, -25.8852, -18.4795,\n -15.4495, -22.3639, -21.3951],\n [ -9.9251, -11.0645, -21.2399, -15.0197, -19.1785,\n -10.9099, -9.9308, -8.5852, -0.0007, -11.9040,\n -14.6043, -9.9018, -11.0490, -8.8805, -16.4668,\n -18.0205, -11.6439, -17.3109, -11.2322, -9.5818,\n -10.3780, -14.4156, -18.7196, -15.9627, -10.8608,\n -13.1089, -17.4606, -16.2956, -17.3550, -17.8361,\n -21.7095, -16.0220, -24.3831, -14.8849, -10.8853,\n -16.1416, -14.5285, -17.4633, -18.3292, -26.4754,\n -17.3396, -17.2065, -20.7631, -18.7046, -22.5311,\n -18.9987, -12.7491, -20.3566, -17.3999, -26.1172,\n -22.2351, -21.6581, -25.2074, -14.0046, -20.0518,\n -19.7539, -18.7592, -19.6894, -17.9859, -16.4865,\n -12.4192, -21.2714, -15.1528, -26.4523, -16.3478,\n -18.8448, -19.5917, -18.9769],\n [ -9.5796, -3.9636, -25.3593, -13.3801, -15.8211,\n -6.8645, -7.5726, -18.1823, -3.5970, -13.6741,\n -8.9134, -0.0823, -13.2020, -4.3471, -15.7792,\n -14.0647, -17.1174, -17.5841, -16.4488, -15.3259,\n -14.6713, -11.9366, -28.9635, -21.2275, -12.0747,\n -12.6402, -14.3471, -11.9154, -12.5012, -22.2605,\n -14.2049, -12.6932, -22.1717, -4.0452, -8.0552,\n -13.0553, -17.5830, -16.4511, -22.1469, -23.8714,\n -16.1256, -21.7494, -23.3034, -13.5289, -25.8474,\n -17.2069, -17.1696, -24.5288, -12.7701, -22.5565,\n -22.6910, -13.0808, -19.0386, -20.5934, -17.7027,\n -21.9146, -20.3673, -16.7414, -20.9241, -14.2457,\n -10.0841, -21.3487, -11.1158, -23.7707, -14.3261,\n -11.3639, -20.7613, -20.4783],\n [ -10.1981, -0.0002, -22.0545, -15.7833, -22.0376,\n -16.1523, -15.7049, -20.9548, -10.4077, -15.0009,\n -16.8353, -11.3514, -14.2362, -10.2056, -23.0491,\n -18.6424, -13.8157, -20.7754, -16.7740, -17.9731,\n -13.4376, -14.6850, -26.1030, -14.6003, -12.7707,\n -22.6602, -25.6926, -13.9844, -15.7432, -17.6086,\n -11.7582, -16.3245, -22.4742, -11.0903, -19.1011,\n -12.8437, -15.6017, -24.1128, -21.4881, -20.4432,\n -17.7876, -18.9254, -21.9851, -14.0454, -20.5685,\n -22.4179, -17.0209, -25.4177, -18.5958, -19.9488,\n -19.8075, -17.6503, -21.5320, -24.2825, -26.5237,\n -17.1388, -19.4383, -17.5444, -22.5415, -18.5892,\n -23.0131, -25.3088, -17.2551, -23.3942, -14.7401,\n -13.1665, -25.8589, -22.1935],\n [ -12.3286, -11.0920, -27.8706, -19.1973, -22.6472,\n -10.1102, -9.5697, -11.9940, -0.0002, -18.0516,\n -22.7717, -14.3203, -17.6506, -18.0625, -23.1552,\n -25.8978, -18.5290, -25.0772, -9.9785, -12.3653,\n -10.9901, -16.5943, -24.1781, -23.3899, -15.4129,\n -16.1582, -25.4455, -16.8191, -25.9917, -23.0432,\n -27.4410, -20.0438, -33.6067, -16.5608, -15.8367,\n -23.5612, -20.8656, -24.3034, -18.9237, -34.7820,\n -26.4578, -19.1895, -25.7649, -22.5186, -28.7414,\n -25.9553, -14.2883, -28.4586, -21.4195, -31.3557,\n -27.8031, -30.7876, -33.7606, -17.4750, -21.0420,\n -24.9439, -25.7084, -25.2457, -20.0239, -20.7794,\n -18.5272, -23.5405, -21.6890, -34.8409, -24.8934,\n -21.9215, -24.3588, -24.5526],\n [ -0.0005, -9.0139, -23.1254, -10.4185, -18.2288,\n -13.3896, -9.8668, -10.3572, -8.9361, -19.9715,\n -22.1432, -16.6486, -19.5652, -13.4175, -24.0788,\n -21.3666, -10.3922, -22.3783, -10.5013, -16.6335,\n -12.0022, -9.8627, -13.9444, -14.4703, -14.4375,\n -22.4485, -32.9120, -10.4670, -17.7297, -19.4623,\n -16.3804, -19.8774, -24.1024, -18.7982, -16.9323,\n -18.7362, -18.2409, -24.7347, -12.9218, -24.0162,\n -23.3778, -17.9905, -16.6548, -17.9742, -20.9508,\n -23.5581, -11.8413, -22.2916, -17.0923, -18.5120,\n -19.1663, -26.4976, -28.4017, -19.2424, -20.7026,\n -17.2125, -26.7035, -21.2596, -15.6853, -14.3970,\n -24.9770, -18.1518, -20.9701, -29.5770, -20.9469,\n -16.3648, -24.6178, -23.5928],\n [ -7.0041, -10.1446, -21.1592, -13.0728, -13.8012,\n -7.6443, -3.5856, -6.7635, -0.0331, -15.4767,\n -18.6579, -10.6189, -16.8355, -14.6926, -18.7840,\n -23.2952, -11.3132, -17.7985, -6.7586, -12.7628,\n -7.2535, -9.3861, -14.8955, -17.2031, -10.8086,\n -12.2880, -22.1976, -10.6734, -19.5271, -17.6918,\n -17.3579, -15.1931, -26.3638, -11.1936, -13.4782,\n -15.0229, -16.4883, -19.9410, -9.5439, -25.9546,\n -19.9972, -12.2260, -17.2936, -15.6973, -19.6628,\n -20.4508, -8.9931, -21.8945, -13.2190, -19.8102,\n -19.8705, -24.2415, -26.7565, -14.0494, -12.8613,\n -17.0827, -20.4913, -18.9001, -12.9277, -12.5621,\n -15.6098, -15.4443, -16.7949, -25.5978, -19.5494,\n -14.6832, -18.1960, -18.3253],\n [ -9.7273, -5.2335, -21.5611, -12.4408, -11.8368,\n -8.5147, -0.0245, -11.0700, -4.2842, -14.3262,\n -21.1305, -12.7515, -22.1447, -16.6886, -18.4713,\n -22.3182, -14.9442, -17.3134, -11.4076, -10.6105,\n -6.0606, -9.9177, -20.7740, -22.8973, -18.1207,\n -10.2591, -21.1737, -17.3873, -24.3364, -22.0079,\n -18.6534, -19.0392, -28.5172, -6.1145, -15.3780,\n -12.9272, -22.3920, -17.0226, -9.8477, -25.2199,\n -23.8116, -14.8602, -19.3199, -15.7749, -19.0279,\n -24.5480, -10.6749, -26.8141, -14.1422, -17.5344,\n -20.2657, -21.8749, -23.3393, -16.4356, -15.3989,\n -16.9998, -21.0557, -16.7699, -16.5034, -15.8280,\n -20.0976, -20.6194, -20.1668, -25.3683, -22.5341,\n -12.0424, -22.5208, -22.4789],\n [ -5.8807, -0.0130, -17.1424, -6.4424, -12.5088,\n -9.0232, -5.2118, -11.4290, -8.8962, -13.1629,\n -16.9300, -14.6165, -16.1577, -10.7520, -13.7697,\n -15.0436, -12.0228, -18.3745, -8.7032, -10.5458,\n -8.3711, -7.6379, -15.8318, -14.6470, -16.1015,\n -16.5665, -21.6609, -13.0833, -16.4937, -16.9340,\n -12.4864, -14.9199, -19.6159, -6.6882, -14.5137,\n -10.5790, -15.8445, -15.7068, -9.2327, -16.2532,\n -17.2612, -15.3274, -12.0220, -10.7462, -14.4149,\n -18.7807, -8.8248, -17.8472, -11.8501, -10.8959,\n -11.3799, -17.2875, -15.1531, -14.8581, -15.0635,\n -11.0877, -18.7795, -10.2943, -12.7717, -14.6068,\n -19.4525, -17.5423, -17.6213, -20.0816, -16.2924,\n -8.4340, -19.8944, -18.6056],\n [ -2.1166, -0.1327, -19.3899, -7.9753, -14.4482,\n -12.3920, -6.8743, -12.9919, -10.5988, -15.6942,\n -22.1178, -17.4150, -19.0066, -13.1377, -20.6092,\n -18.2621, -10.6973, -19.5647, -10.5529, -12.0149,\n -11.0460, -6.0780, -16.7332, -16.5167, -17.6957,\n -19.7060, -29.4840, -12.2791, -18.2600, -19.6889,\n -14.4058, -21.2255, -22.2986, -13.4983, -16.1890,\n -16.7832, -19.1227, -18.6731, -10.8333, -22.0292,\n -22.8297, -18.6227, -15.0802, -14.4561, -17.5985,\n -22.7353, -11.2800, -23.5990, -16.4258, -13.2215,\n -15.5172, -21.7952, -22.5272, -18.0166, -19.7438,\n -15.6709, -23.6479, -16.0556, -15.5406, -16.7579,\n -27.4878, -18.8258, -20.8106, -27.1164, -20.5571,\n -12.9676, -25.4486, -24.2615],\n [ -6.9359, -5.7847, -13.9582, -5.7641, -6.0816,\n -5.4243, -0.3331, -2.5342, -5.4772, -13.1935,\n -19.7110, -11.6997, -15.4099, -9.8756, -13.8443,\n -16.1929, -4.4401, -14.0324, -5.0458, -8.0042,\n -6.8474, -2.4387, -9.1929, -14.5125, -12.4276,\n -9.3436, -16.7037, -8.9973, -14.0697, -16.1169,\n -14.9337, -20.4153, -18.5507, -11.1516, -11.0422,\n -13.3552, -15.3239, -11.3595, -2.5531, -22.8763,\n -19.4213, -12.6223, -8.7720, -12.3717, -13.2368,\n -13.8845, -9.3151, -17.3689, -11.3981, -8.5205,\n -14.8751, -20.1528, -21.3297, -10.8233, -8.8376,\n -16.2409, -17.7498, -13.4094, -9.5203, -11.9722,\n -18.2986, -11.4738, -16.7253, -22.3538, -18.6332,\n -11.3687, -17.5999, -18.5337],\n [ -7.9453, -10.6422, -13.2296, -8.8981, -0.0547,\n -10.1000, -7.5708, -7.0442, -13.1297, -6.4575,\n -10.0234, -5.4683, -15.9694, -6.5345, -8.7945,\n -7.8512, -3.2573, -9.6702, -20.0749, -14.6724,\n -9.3622, -9.5817, -13.9600, -12.2290, -17.1534,\n -5.5624, -7.2244, -15.5290, -11.6413, -18.6387,\n -16.4203, -26.4108, -12.9963, -13.1294, -16.0210,\n -9.7712, -18.2707, -9.6656, -14.5117, -18.6490,\n -22.5856, -18.6072, -16.0341, -16.0796, -14.0315,\n -15.9825, -17.3047, -18.8049, -22.3733, -12.7687,\n -22.4034, -15.6028, -20.0044, -18.5070, -16.0537,\n -24.1022, -13.8084, -23.0435, -21.4817, -10.4431,\n -20.9266, -19.6357, -12.8827, -20.5324, -14.7737,\n -13.4333, -21.0784, -23.2521],\n [ -8.2635, -7.2309, -17.1748, -10.4829, -17.5021,\n -12.3162, -18.6575, -11.6000, -5.6596, -6.1729,\n -6.4728, -8.9239, -2.4506, -0.1025, -8.5118,\n -6.4346, -7.9232, -16.9492, -13.8192, -9.6340,\n -17.2724, -12.1273, -18.1924, -9.3149, -12.3424,\n -16.6427, -12.2114, -15.0919, -7.9100, -16.3694,\n -20.7166, -17.9894, -14.1300, -18.5991, -9.8347,\n -18.1397, -10.0582, -12.3832, -25.3263, -22.1769,\n -13.5424, -24.7577, -18.0055, -16.8303, -21.9351,\n -12.3625, -16.5198, -14.2184, -22.5510, -24.1160,\n -18.9274, -16.7251, -19.3314, -14.3067, -22.9395,\n -22.9775, -16.4223, -19.7073, -20.6868, -18.1823,\n -13.2113, -21.9442, -10.8762, -25.8690, -10.1160,\n -20.5460, -19.6887, -19.9010],\n [ -2.3050, -3.8721, -9.9780, -5.4257, -8.1955,\n -11.9697, -7.2648, -5.2168, -6.4180, -5.1949,\n -10.6473, -10.3560, -7.8430, -2.0759, -9.1130,\n -5.7911, -0.3389, -7.5520, -11.2223, -4.9043,\n -8.6882, -4.9255, -9.9832, -6.3749, -12.8828,\n -9.5072, -13.0137, -13.4588, -8.2189, -13.2876,\n -14.8839, -20.4194, -11.1007, -14.8140, -8.4493,\n -11.4369, -11.0067, -6.2399, -11.9699, -16.7372,\n -15.0933, -16.5376, -11.4096, -13.8388, -11.2652,\n -12.7670, -10.9367, -13.9466, -17.4946, -12.1405,\n -15.3773, -13.2111, -16.3463, -10.7630, -17.9434,\n -15.5485, -13.0572, -15.6145, -15.2179, -11.9194,\n -18.4946, -17.0340, -11.5458, -20.0170, -10.5443,\n -13.7094, -18.5949, -17.8487],\n [ -5.7776, -11.4954, -7.9854, -5.4832, -0.7019,\n -15.9653, -9.9071, -8.3379, -17.1032, -8.1440,\n -10.4318, -10.7723, -13.4088, -5.8416, -8.6227,\n -3.7707, -1.2148, -3.0044, -18.6325, -10.7555,\n -14.4425, -4.1568, -8.4896, -9.5505, -18.0481,\n -8.0478, -8.5349, -14.1224, -7.0115, -15.8219,\n -13.2068, -25.2792, -5.1641, -18.9072, -9.5736,\n -13.3129, -15.4239, -2.3099, -12.2841, -14.0787,\n -17.5383, -19.0578, -9.7761, -15.0011, -9.1932,\n -10.4794, -16.8218, -13.2706, -19.0011, -7.0234,\n -15.8291, -9.5217, -13.1177, -13.9179, -14.5710,\n -19.5806, -12.6375, -17.2545, -16.6132, -10.7276,\n -21.8104, -13.6623, -11.0089, -16.5458, -12.3329,\n -14.2924, -17.8479, -19.0126],\n [ -6.7974, -12.2479, -19.3362, -10.3160, -0.0201,\n -10.3237, -4.7130, -8.0405, -10.6160, -10.2015,\n -13.6031, -5.7598, -21.3439, -10.2588, -13.3589,\n -13.6338, -6.8280, -12.0387, -21.7429, -16.5340,\n -10.5521, -9.1113, -17.3165, -18.9372, -20.2217,\n -5.3082, -11.6567, -17.4468, -17.2247, -24.4464,\n -19.6943, -28.9164, -20.0335, -14.2664, -15.5693,\n -13.7921, -23.8664, -11.8776, -15.7274, -26.0210,\n -27.9349, -21.8016, -20.1390, -19.8039, -19.2584,\n -21.2258, -18.4819, -25.2588, -23.3203, -17.6423,\n -26.6851, -20.4128, -25.8305, -21.0539, -16.6605,\n -28.2226, -19.4198, -26.7187, -23.4159, -12.0413,\n -23.3365, -21.2597, -16.0549, -27.3281, -20.3965,\n -16.1378, -24.5402, -27.4682],\n [ -11.1407, -13.6566, -26.9613, -20.8966, -20.8761,\n -11.8572, -10.0974, -11.1465, -0.0001, -14.0006,\n -19.8897, -11.2353, -17.6714, -16.2497, -22.7330,\n -24.2844, -15.4990, -22.1064, -14.6163, -13.0484,\n -10.3234, -18.1067, -24.5874, -22.1071, -15.3170,\n -13.0996, -22.6916, -19.3942, -25.3885, -23.3407,\n -28.6668, -22.7854, -32.9016, -17.7312, -17.4895,\n -21.3551, -21.7043, -23.7791, -21.9666, -35.4083,\n -27.7915, -19.7697, -29.1504, -24.4867, -28.6292,\n -27.5791, -15.8874, -30.0267, -24.9906, -33.4023,\n -31.4922, -30.0254, -36.0375, -19.1180, -24.3051,\n -27.4499, -23.8921, -29.4568, -24.0854, -19.7613,\n -19.5936, -26.6610, -20.1606, -35.1950, -23.4644,\n -23.6709, -26.2372, -26.5786],\n [ -10.1246, -10.6023, -28.7099, -21.6915, -16.5983,\n -13.7124, -6.5809, -21.4027, -7.5447, -15.4185,\n -15.0240, -0.0023, -23.4706, -10.4568, -26.6474,\n -21.1196, -16.0912, -16.2024, -26.5094, -21.3518,\n -14.5709, -15.5666, -33.4709, -26.1545, -15.2477,\n -10.6531, -20.2938, -16.8526, -18.4403, -26.8631,\n -18.0218, -22.5200, -28.5460, -8.3134, -16.2847,\n -13.2129, -26.0620, -22.0865, -25.0056, -30.9308,\n -25.9252, -22.1290, -32.6677, -20.0140, -27.9229,\n -27.1056, -22.5786, -36.2031, -19.5987, -26.0346,\n -34.4015, -17.3800, -30.4314, -28.5330, -25.5314,\n -28.1270, -23.2332, -27.6705, -29.7377, -14.9537,\n -20.8534, -28.0603, -15.1392, -28.9904, -19.5913,\n -15.5350, -29.7105, -28.9504],\n [ -5.2285, -0.0186, -24.7578, -15.4925, -18.6671,\n -15.2895, -11.0957, -22.7116, -9.7509, -13.9366,\n -13.9569, -4.4618, -17.9757, -8.4373, -24.8105,\n -17.9277, -12.9478, -18.3168, -21.0248, -21.2502,\n -13.0712, -12.6096, -29.7577, -16.7696, -13.4592,\n -19.4494, -25.8210, -12.8095, -14.6154, -20.8543,\n -9.5729, -16.8629, -23.5006, -6.8772, -19.2333,\n -9.7701, -19.3619, -24.5422, -23.0781, -21.1202,\n -20.2797, -19.7435, -26.0120, -13.7197, -22.1890,\n -25.2595, -18.5358, -30.2550, -18.0650, -19.7568,\n -23.7087, -15.2748, -23.5145, -28.2659, -27.1392,\n -19.2653, -20.8595, -20.9797, -26.0195, -14.9812,\n -24.0261, -26.7383, -15.1454, -24.6136, -14.5933,\n -11.0402, -28.5556, -25.1754],\n [ -7.3624, -6.6586, -22.1446, -11.1026, -10.5600,\n -12.8838, -8.5173, -17.8433, -13.0929, -14.4436,\n -11.6488, -0.2431, -17.1462, -1.5574, -20.1921,\n -12.7472, -6.5314, -13.6736, -23.0729, -21.2896,\n -17.5154, -7.1910, -25.2752, -17.3778, -13.5123,\n -14.3580, -16.6237, -10.9241, -7.4614, -22.9198,\n -10.4891, -22.5004, -17.3170, -9.7939, -13.6152,\n -10.6571, -19.7520, -16.2532, -20.3311, -23.4023,\n -19.2793, -23.3312, -20.7484, -13.8520, -21.1582,\n -17.0661, -22.8134, -26.6356, -16.1126, -13.8723,\n -24.3023, -12.0077, -22.3679, -26.6200, -21.1611,\n -24.7307, -20.6922, -20.8324, -24.7743, -12.2144,\n -20.6007, -22.0134, -12.2794, -24.1329, -14.0639,\n -12.0394, -26.4052, -25.4315],\n [ -3.1430, -7.1481, -20.7313, -2.7686, -10.3803,\n -2.3332, -10.3015, -5.0439, -2.0522, -9.3768,\n -6.0284, -10.0510, -7.1697, -4.3313, -0.4482,\n -6.6964, -13.9984, -20.9539, -6.2332, -7.0872,\n -11.8122, -12.1571, -14.2402, -13.0927, -17.4919,\n -13.8416, -11.3257, -14.0442, -14.3029, -20.3127,\n -22.4260, -13.7949, -17.7339, -11.9875, -6.5863,\n -18.5422, -13.0044, -10.9833, -17.8913, -19.5759,\n -17.4316, -23.8281, -13.3397, -15.7888, -23.3744,\n -13.7703, -9.3044, -10.0861, -18.2786, -23.2250,\n -13.8751, -20.7459, -15.7439, -9.8601, -12.3286,\n -19.6833, -20.9469, -17.1140, -13.8458, -14.1077,\n -7.6142, -17.3686, -13.5023, -26.5139, -15.2109,\n -15.7787, -14.6239, -17.5651],\n [ -1.5417, -7.9208, -14.0934, -11.3952, -13.4027,\n -7.4167, -14.0017, -10.1460, -8.3144, -4.3053,\n -5.1953, -13.4352, -10.2959, -11.9234, -2.9089,\n -0.4376, -19.4718, -15.5877, -13.4686, -2.7714,\n -6.1723, -21.3956, -15.5620, -11.2773, -19.2541,\n -9.5633, -10.2231, -18.3022, -17.9796, -14.4508,\n -24.0366, -13.6606, -12.6033, -13.4169, -9.9217,\n -16.9120, -14.4457, -10.6822, -21.2923, -9.6390,\n -20.2221, -17.7307, -20.1368, -18.3994, -18.3775,\n -19.0585, -7.7539, -11.2626, -23.7490, -25.4477,\n -17.8806, -15.7524, -12.1347, -8.9728, -19.0285,\n -15.8330, -14.0935, -19.7522, -17.1125, -12.9310,\n -11.4541, -20.3690, -12.1756, -18.4610, -13.0692,\n -13.9275, -14.7232, -16.6745],\n [ -11.5746, -12.8144, -15.8212, -9.0374, -16.4925,\n -12.4314, -21.9067, -13.4373, -20.8593, -13.8998,\n -11.5499, -17.7792, -11.5777, -9.7706, -7.6080,\n -0.0010, -16.1537, -19.3231, -16.4319, -9.8306,\n -15.9735, -20.2868, -17.4435, -10.9136, -22.2349,\n -19.8327, -10.3609, -18.0410, -13.3422, -17.4302,\n -22.6531, -19.6392, -9.0005, -20.0413, -13.4816,\n -20.8846, -14.9128, -13.0582, -22.7481, -10.8999,\n -20.6003, -23.4194, -14.9901, -18.8998, -18.9616,\n -13.0896, -18.2480, -10.1961, -23.8549, -18.8171,\n -15.6738, -16.2665, -12.3635, -15.5222, -20.1533,\n -19.7233, -18.2687, -18.1027, -18.9104, -17.0788,\n -14.6772, -20.7978, -17.2385, -19.2634, -15.0606,\n -16.1745, -17.8595, -18.3832],\n [ -10.0700, -16.1884, -27.1974, -0.0004, -15.9500,\n -12.9871, -16.6855, -8.6643, -17.4327, -25.2632,\n -22.7512, -27.5718, -18.1520, -11.2660, -10.2663,\n -15.0662, -15.8804, -29.2195, -10.1129, -14.0853,\n -22.2589, -13.0752, -13.9082, -19.8814, -30.5347,\n -27.9703, -24.1673, -22.3243, -21.3324, -30.3845,\n -28.1089, -26.3711, -23.3841, -25.7207, -12.8624,\n -29.3140, -22.2825, -15.8532, -17.7213, -25.8335,\n -25.7692, -33.9364, -9.4028, -23.4755, -26.9892,\n -18.0229, -18.1021, -14.1305, -21.9619, -20.7784,\n -12.6111, -30.4083, -20.9618, -16.6976, -17.5341,\n -23.5581, -34.7220, -18.7926, -16.2027, -23.4239,\n -20.2628, -21.0055, -28.3240, -35.3471, -27.4295,\n -23.9861, -23.2900, -25.7242],\n [ -0.0024, -13.5267, -28.2210, -6.9429, -10.4709,\n -11.2176, -6.7001, -9.7974, -9.1347, -16.0150,\n -17.7129, -14.5789, -24.5754, -14.2416, -16.1127,\n -18.6488, -14.3954, -21.6506, -17.5871, -16.1228,\n -11.9501, -13.6215, -19.0618, -22.0745, -26.2001,\n -16.3926, -25.0453, -21.5395, -25.6020, -30.0066,\n -24.5461, -24.7074, -28.7680, -16.0528, -17.0488,\n -19.7503, -27.1811, -20.2197, -19.2906, -26.2520,\n -30.7580, -26.2255, -21.7389, -23.2458, -26.6126,\n -28.8944, -14.8293, -25.7899, -23.2974, -25.0191,\n -22.6942, -27.9867, -27.8464, -21.6079, -21.3794,\n -23.8699, -30.2556, -27.1954, -22.9247, -15.8568,\n -23.4471, -25.4685, -23.4209, -34.7602, -25.8885,\n -19.4277, -27.0841, -29.3051],\n [ -5.3551, -11.9869, -26.9762, -0.0125, -5.9599,\n -5.6552, -6.7275, -11.3614, -15.8269, -21.9672,\n -14.6509, -12.4791, -22.7417, -8.5429, -9.4898,\n -13.1319, -16.6962, -22.6870, -15.3368, -18.0391,\n -17.0139, -10.4608, -18.0934, -22.4379, -26.2577,\n -18.3641, -17.8522, -16.3868, -17.7658, -30.3934,\n -17.5251, -20.6198, -21.1147, -10.6076, -10.8265,\n -18.2565, -24.6173, -14.7789, -14.7391, -20.2222,\n -24.4045, -28.7649, -12.1944, -16.9539, -24.8783,\n -17.9357, -17.0823, -18.2390, -14.4338, -15.0569,\n -14.1878, -20.7030, -16.4510, -20.6554, -11.4001,\n -21.6306, -30.3084, -17.2313, -16.6970, -13.5623,\n -15.5003, -18.0603, -21.1696, -27.4085, -23.4491,\n -12.8555, -20.9476, -23.9486],\n [ -8.8599, -4.1120, -22.9380, -9.2153, -9.5898,\n -4.6795, -4.5558, -17.8652, -10.5413, -16.5605,\n -11.1010, -3.2362, -19.2030, -9.0512, -14.2938,\n -14.5053, -17.0702, -17.5480, -15.4673, -17.7035,\n -12.5724, -10.3617, -24.9332, -20.9010, -15.8659,\n -13.6570, -15.2410, -10.1706, -14.4283, -22.5986,\n -9.7615, -12.8506, -19.8678, -0.0823, -12.1494,\n -10.1404, -19.7858, -16.7983, -14.5718, -17.2427,\n -18.3608, -18.7338, -17.8174, -10.2193, -20.7910,\n -17.2724, -15.1957, -22.7455, -9.8481, -12.9738,\n -16.7651, -12.2454, -14.9026, -21.5966, -11.8077,\n -17.2461, -20.7579, -14.0791, -17.3092, -10.6150,\n -12.7315, -17.5540, -13.7271, -18.8832, -16.1643,\n -5.9161, -18.8773, -18.9640],\n [ -11.0008, -0.0000, -21.3037, -15.6895, -20.1175,\n -14.8766, -13.5163, -20.2415, -11.3561, -14.6122,\n -20.5969, -17.1454, -17.8208, -17.4661, -21.5275,\n -19.3293, -17.0482, -22.5557, -14.0900, -15.0779,\n -11.9288, -13.8008, -25.5723, -18.0804, -18.5394,\n -21.4878, -26.9207, -15.8985, -21.7136, -19.2498,\n -17.2248, -19.7306, -24.8174, -11.8818, -21.7200,\n -17.1236, -19.3439, -23.0710, -18.9587, -21.9931,\n -23.4103, -18.8944, -22.1203, -15.4663, -20.3742,\n -25.3608, -14.9480, -26.9095, -21.6887, -19.8937,\n -20.2106, -22.1494, -22.8410, -21.9335, -24.3049,\n -18.4681, -20.9887, -19.0301, -21.3816, -20.9129,\n -27.0997, -24.9604, -20.5494, -26.1368, -19.6204,\n -14.3863, -26.5210, -24.3750],\n [ -12.1588, -18.1924, -17.2917, -13.3001, -11.7473,\n -11.4665, -11.7477, -0.0027, -11.5664, -14.5235,\n -23.8533, -21.7771, -19.2888, -16.9006, -14.3230,\n -16.9710, -9.2189, -21.4992, -12.9496, -9.7399,\n -6.0579, -19.2846, -8.9881, -14.4050, -19.9644,\n -12.3600, -17.7616, -22.1352, -23.9259, -18.9317,\n -30.1420, -30.3919, -23.3529, -25.3582, -20.2446,\n -19.8034, -19.8824, -18.2969, -11.7756, -26.3409,\n -29.9053, -17.6205, -16.2325, -25.1276, -18.5891,\n -22.3626, -13.9809, -17.8008, -27.5363, -22.9957,\n -24.5695, -32.5967, -30.1198, -13.8000, -19.8555,\n -24.0561, -20.6689, -26.4228, -18.1866, -17.8147,\n -23.5550, -22.3295, -24.7202, -29.1975, -25.0200,\n -22.2467, -23.2026, -25.1016],\n [ -8.1270, -13.6181, -11.9520, -19.6966, -12.0999,\n -17.2668, -15.7870, -11.0410, -8.1130, -0.0066,\n -6.1763, -7.2625, -11.0001, -8.9736, -12.2757,\n -8.4146, -7.4495, -8.4143, -23.6900, -11.0658,\n -8.3940, -18.7454, -16.7431, -8.9647, -12.5772,\n -6.7881, -9.1187, -21.4797, -14.3507, -12.9015,\n -20.9097, -21.3383, -13.9861, -17.6030, -17.5797,\n -10.2426, -14.4256, -13.7688, -24.4705, -17.9232,\n -18.9588, -15.8405, -25.2309, -20.0072, -15.5751,\n -20.4822, -15.2921, -18.8815, -27.2944, -24.9864,\n -26.6323, -15.2820, -21.7577, -16.3894, -26.3767,\n -21.6471, -8.4610, -26.2626, -25.4301, -13.7284,\n -18.8883, -25.6612, -9.8677, -19.2136, -9.8384,\n -18.9681, -20.7506, -20.7960],\n [ -7.1787, -13.7800, -25.0591, -17.2527, -14.9933,\n -9.0224, -11.5288, -14.6839, -3.9746, -11.2493,\n -8.7174, -0.0204, -13.8777, -8.1587, -17.8230,\n -14.4448, -13.0160, -16.1886, -19.3807, -16.6738,\n -15.7512, -13.8263, -26.2163, -19.6463, -12.6209,\n -11.6612, -14.6323, -12.0568, -14.1936, -22.7722,\n -20.8805, -18.5996, -22.4163, -13.7806, -12.9131,\n -18.2311, -19.3788, -19.5181, -25.4377, -28.5042,\n -22.5610, -22.1253, -28.1806, -19.3441, -28.0900,\n -19.9983, -19.7847, -26.5530, -21.5800, -28.1132,\n -29.0261, -18.9932, -29.2236, -21.8120, -20.5391,\n -29.1041, -20.9998, -28.1685, -24.9301, -13.4327,\n -13.6432, -22.2481, -11.4196, -29.4887, -16.7417,\n -19.1487, -23.1051, -23.9615],\n [ -8.8456, -8.4018, -20.5807, -14.9666, -14.0466,\n -10.1598, -8.3966, -11.0586, -0.0380, -9.7015,\n -13.0035, -3.3586, -10.7280, -8.0666, -18.6113,\n -16.5227, -7.2390, -13.1825, -13.1258, -11.3868,\n -13.2796, -7.3500, -21.9695, -17.2534, -10.4532,\n -10.1419, -15.1895, -11.0580, -13.8962, -19.3000,\n -19.5787, -19.7192, -22.3439, -14.4048, -11.2301,\n -17.9295, -16.1139, -15.3256, -19.3808, -30.6965,\n -20.2859, -18.5934, -22.8780, -17.2295, -22.7877,\n -17.3786, -16.8203, -25.7282, -19.4280, -23.4268,\n -25.3449, -19.4398, -28.9634, -17.3916, -18.8276,\n -25.8308, -18.2158, -23.4158, -20.8657, -15.4429,\n -16.3657, -19.5605, -12.2509, -29.1888, -16.2488,\n -19.1277, -22.2584, -22.0361],\n [ -5.4082, -7.1604, -20.6138, -17.4368, -16.8286,\n -12.3123, -4.2538, -9.4485, -0.0210, -10.6024,\n -22.2872, -11.4253, -17.5289, -15.7855, -24.9219,\n -23.1103, -8.2219, -15.2452, -11.8719, -8.6531,\n -7.4913, -8.7425, -20.3213, -19.7710, -13.4201,\n -10.6702, -25.5186, -14.7817, -22.4055, -19.7585,\n -23.2039, -24.2263, -29.2552, -16.4433, -16.5387,\n -18.8939, -20.6912, -19.7805, -14.6317, -32.9768,\n -26.6643, -15.1266, -25.1627, -20.2840, -21.7645,\n -26.4450, -12.7653, -31.1678, -21.7386, -24.2929,\n -27.5415, -26.0779, -34.8466, -16.8100, -22.9428,\n -23.3031, -21.1662, -25.7558, -20.7100, -17.4849,\n -25.3057, -22.4769, -18.7683, -32.9164, -22.4234,\n -20.2357, -27.1579, -26.3820],\n [ -6.6451, -9.6672, -26.2332, -15.4390, -12.7344,\n -9.2357, -0.0277, -11.8216, -3.6779, -18.0014,\n -23.2626, -8.6888, -24.6485, -15.6604, -25.7386,\n -24.5578, -13.0892, -16.9354, -15.5021, -13.2652,\n -10.5753, -8.0833, -23.7891, -26.9307, -17.2809,\n -9.9511, -24.8751, -14.4198, -23.1442, -26.5594,\n -21.9979, -25.5383, -31.1190, -12.6130, -13.4927,\n -19.5235, -26.4509, -19.2317, -13.3400, -34.8747,\n -29.7207, -19.5823, -24.8594, -20.6543, -25.4461,\n -26.2444, -16.1084, -34.0676, -17.5837, -22.3440,\n -29.2526, -25.1837, -33.6653, -20.8011, -18.4714,\n -26.3198, -26.8735, -25.1639, -20.8213, -15.6408,\n -23.6075, -21.1660, -20.3636, -33.8590, -26.4520,\n -17.1571, -27.8813, -28.4354],\n [ -9.4910, -12.2957, -24.3799, -18.6475, -18.6229,\n -10.6222, -10.2503, -10.5723, -0.0002, -12.7294,\n -16.6950, -10.9705, -15.1500, -15.0343, -18.5249,\n -20.9295, -15.7349, -20.2519, -12.6570, -11.7629,\n -10.4777, -16.4528, -21.7247, -19.8577, -14.5457,\n -12.3853, -20.5662, -17.1048, -22.5493, -21.0162,\n -26.3371, -19.7975, -28.7820, -16.7853, -14.6362,\n -20.8156, -19.0998, -20.6062, -20.4976, -31.3374,\n -24.5901, -19.0009, -25.9509, -22.1039, -26.4123,\n -24.2502, -13.8183, -25.5463, -23.1105, -31.1694,\n -28.0429, -27.0491, -31.1404, -16.2549, -21.0761,\n -25.1429, -21.7603, -26.6026, -20.9887, -17.9881,\n -17.2013, -23.1996, -17.4005, -31.8779, -20.9950,\n -21.7275, -22.6960, -23.4331],\n [ -9.5523, -10.9095, -21.6928, -20.4540, -14.5386,\n -10.5228, -7.9364, -13.9198, -0.1085, -7.3516,\n -10.1080, -2.3015, -14.4014, -11.2287, -17.0277,\n -17.5238, -14.1387, -13.8733, -17.8965, -13.1915,\n -10.6527, -14.6849, -24.9387, -20.0037, -11.8358,\n -6.5187, -13.9942, -15.9282, -17.9183, -19.8658,\n -21.3539, -17.9227, -24.6885, -10.5518, -13.4538,\n -14.5039, -18.8110, -16.9267, -22.3756, -28.4494,\n -21.1614, -17.5268, -28.5215, -18.7886, -24.1188,\n -22.3885, -15.2780, -27.0408, -20.8897, -28.1593,\n -29.5561, -18.6340, -27.3982, -17.8787, -20.4209,\n -25.2488, -16.3751, -25.6648, -23.5332, -14.7095,\n -14.9504, -23.1165, -11.2095, -26.3516, -15.8309,\n -17.9658, -21.7057, -22.4895],\n [ -6.7810, -5.9636, -21.9665, -12.0243, -9.7468,\n -7.1487, -7.6898, -17.1973, -8.0541, -12.1455,\n -8.5139, -0.0088, -15.6860, -8.1412, -14.9755,\n -12.7008, -13.3425, -14.4351, -17.2464, -17.3679,\n -14.1242, -9.8743, -25.4661, -19.0522, -14.1405,\n -11.5490, -14.0378, -8.9776, -12.4536, -21.5392,\n -12.5859, -16.0508, -18.7490, -5.9249, -12.6920,\n -13.2169, -18.8826, -16.2437, -19.4147, -21.1865,\n -20.1151, -19.8066, -22.0224, -12.7666, -22.4169,\n -17.6371, -17.6277, -24.5336, -16.1385, -17.8620,\n -22.0121, -13.1342, -20.2919, -21.9642, -15.3538,\n -22.9875, -19.0055, -20.7236, -21.1421, -11.2821,\n -15.1679, -18.7147, -10.9194, -22.6489, -15.0058,\n -11.0786, -20.9314, -21.2739],\n [ -9.9401, -11.5352, -23.9274, -0.0014, -13.3349,\n -10.0534, -16.4826, -8.7328, -15.4148, -21.0430,\n -18.1233, -20.8313, -13.6614, -8.4880, -8.3745,\n -12.3644, -12.1087, -27.2906, -7.9349, -15.5818,\n -20.7462, -9.5711, -14.1046, -15.0528, -24.5662,\n -26.4896, -20.0221, -15.4025, -15.5223, -25.6444,\n -21.7997, -21.9315, -19.0174, -20.4068, -14.2451,\n -24.2495, -17.2934, -16.1032, -16.3015, -22.2447,\n -21.6717, -29.4669, -8.3587, -17.6661, -23.5716,\n -13.8854, -17.2250, -12.3231, -19.6956, -16.2166,\n -10.7973, -26.3352, -19.0698, -17.0191, -14.5141,\n -22.1574, -28.9523, -16.9303, -15.0426, -20.0862,\n -17.8957, -17.9298, -23.3276, -30.7515, -22.0003,\n -19.5048, -20.6214, -22.4875],\n [ -0.0244, -7.4337, -22.4834, -4.1666, -13.1933,\n -6.2199, -12.0033, -9.0335, -5.7078, -11.6666,\n -9.9021, -14.3608, -11.7993, -9.4811, -6.2052,\n -10.7838, -15.3468, -22.7461, -8.0456, -10.2993,\n -13.7530, -11.6924, -15.5754, -14.3866, -20.4969,\n -19.2185, -20.3659, -14.3565, -17.5239, -22.1508,\n -21.8859, -15.7659, -20.3432, -14.4949, -11.9039,\n -21.0320, -16.4502, -16.3916, -18.6279, -20.1943,\n -21.3068, -24.8138, -15.9071, -16.9285, -24.4243,\n -19.0767, -9.9233, -14.5287, -20.4902, -23.3110,\n -14.3645, -23.7464, -19.3981, -13.5971, -16.0021,\n -19.5917, -24.7891, -20.0786, -15.6360, -15.7161,\n -15.0437, -18.9751, -16.9402, -29.4630, -18.3488,\n -17.4157, -18.9682, -21.0211],\n [ -4.8481, -13.0937, -18.5355, -1.7683, -8.2444,\n -6.5144, -12.6989, -4.5141, -9.8590, -11.7602,\n -9.5568, -17.2762, -11.6608, -8.6477, -0.2144,\n -7.5089, -14.2674, -20.5741, -8.9137, -8.8972,\n -13.8404, -13.1460, -9.5468, -13.4361, -22.6396,\n -15.9496, -12.5933, -18.0714, -16.6183, -21.4351,\n -23.3032, -17.4972, -15.8084, -16.8509, -9.7451,\n -19.8517, -15.7065, -10.3196, -15.6819, -16.7047,\n -19.2634, -24.8403, -10.3535, -17.8431, -20.6335,\n -14.4348, -10.2757, -7.9452, -19.5781, -19.8879,\n -11.2830, -22.1948, -14.0631, -9.9161, -11.9607,\n -18.7575, -22.0224, -16.9747, -13.0305, -15.2396,\n -11.5527, -16.4625, -17.2442, -24.7415, -18.0623,\n -17.6423, -14.7699, -18.4090],\n [ -17.4767, -12.2009, -15.9021, -7.0121, -10.3819,\n -5.2330, -13.4704, -8.5234, -11.0059, -12.4399,\n -8.6769, -12.7460, -8.4430, -6.6740, -0.2121,\n -4.2496, -16.9200, -17.7260, -10.2393, -7.3956,\n -14.5215, -15.6354, -15.6275, -15.4734, -18.5728,\n -11.4217, -1.9244, -17.1325, -12.8126, -18.3421,\n -21.7177, -14.9405, -12.1906, -11.7715, -5.8270,\n -17.6261, -12.8909, -6.0934, -16.7374, -15.2528,\n -14.1275, -21.9517, -10.8158, -15.3007, -19.0424,\n -7.4745, -14.2173, -7.8004, -15.4889, -17.7671,\n -13.1436, -14.8085, -8.7538, -9.2048, -9.3268,\n -19.2364, -15.8752, -11.7025, -13.0409, -15.9797,\n -4.1703, -15.5278, -13.6427, -17.1099, -14.3456,\n -13.9788, -10.8006, -13.8182],\n [ -6.8203, -0.0013, -25.7137, -9.2264, -21.0447,\n -12.4829, -14.9716, -19.9316, -14.5809, -17.4793,\n -17.2128, -14.5318, -17.2844, -10.2289, -18.6730,\n -11.5321, -17.9022, -25.4180, -16.4237, -16.1337,\n -12.4827, -17.0423, -28.0277, -15.9398, -21.2594,\n -24.9682, -24.5913, -16.8847, -18.5224, -22.6367,\n -16.0923, -17.1620, -22.2376, -9.8489, -18.4214,\n -15.7375, -19.4643, -23.6931, -23.2928, -15.9975,\n -22.9537, -23.5524, -21.0026, -16.0768, -23.5598,\n -23.7154, -17.4175, -23.6095, -20.3149, -20.4407,\n -18.1066, -19.7195, -18.5491, -24.8872, -26.4440,\n -17.6431, -24.9984, -17.9743, -23.3503, -18.6495,\n -21.6090, -27.7663, -21.6383, -25.9268, -18.3802,\n -11.5047, -26.6247, -24.5213],\n [ -7.2609, -0.0009, -19.2023, -12.1475, -17.3143,\n -18.2265, -10.3310, -17.2877, -14.6739, -15.5970,\n -23.4171, -17.3247, -20.6552, -14.1528, -24.8512,\n -19.2620, -9.8078, -18.8625, -16.0987, -16.7652,\n -10.2317, -9.9246, -21.3429, -14.5333, -17.4692,\n -21.8970, -29.3450, -15.6448, -18.6192, -18.5717,\n -11.4981, -21.6451, -22.3541, -12.0226, -22.3698,\n -11.4579, -19.1647, -22.4521, -14.2264, -18.6450,\n -22.0759, -16.6177, -18.2964, -14.4406, -15.2902,\n -25.2661, -14.9236, -26.5474, -18.1686, -12.3100,\n -17.8117, -19.7126, -22.2180, -23.6270, -25.5325,\n -14.5376, -20.5705, -16.6596, -20.6508, -17.7715,\n -30.5924, -24.2305, -21.8164, -23.5045, -18.3774,\n -11.4540, -28.1297, -24.8789],\n [ -9.2663, -7.1989, -20.1159, -9.5495, -12.9028,\n -13.2557, -5.9195, -15.4348, -10.8206, -21.1732,\n -21.4139, -11.6572, -18.4649, -11.7339, -23.1100,\n -20.7956, -9.8387, -14.7808, -10.7857, -16.6385,\n -18.8598, -0.0056, -18.2383, -20.6301, -13.8758,\n -18.2250, -24.5028, -6.4710, -12.0703, -20.8820,\n -10.5844, -19.2382, -19.6419, -13.4788, -10.5382,\n -18.5110, -18.5517, -14.9520, -9.6097, -25.6295,\n -17.6040, -18.7497, -13.1453, -12.4236, -18.4092,\n -14.8681, -16.5106, -23.9139, -9.2325, -9.1254,\n -16.3217, -16.4659, -21.6971, -18.5900, -12.3770,\n -19.1948, -23.3535, -13.4096, -13.0970, -15.2586,\n -21.6270, -11.5231, -16.3114, -24.5827, -19.4269,\n -13.3550, -21.3488, -20.7316],\n [ -0.6454, -7.3631, -21.8229, -11.3083, -13.6133,\n -9.6869, -2.7513, -7.6571, -0.8959, -13.2088,\n -17.6543, -8.3286, -17.8773, -11.2667, -21.6998,\n -20.6498, -7.5446, -15.4633, -11.2624, -12.0061,\n -6.8215, -7.9937, -16.8552, -16.2989, -11.6861,\n -12.8595, -24.6334, -11.6708, -18.6156, -19.3386,\n -16.4512, -18.0601, -25.8559, -12.0260, -13.7637,\n -13.5681, -18.4236, -20.1494, -12.3631, -25.7848,\n -22.3611, -14.4611, -19.9804, -16.6972, -20.0343,\n -23.5670, -10.6215, -25.4768, -15.4296, -19.7238,\n -21.6263, -22.5461, -28.6306, -17.5921, -18.8351,\n -17.7902, -21.7506, -21.2525, -17.2300, -11.7857,\n -19.7916, -19.2780, -16.7889, -28.1428, -18.9265,\n -14.5987, -23.1248, -22.0829],\n [ -11.6924, -8.8365, -23.5475, -14.5628, -18.6657,\n -7.6331, -8.1157, -14.6636, -0.0161, -12.9225,\n -9.6831, -4.8332, -11.6229, -8.2620, -14.1135,\n -17.6319, -17.9647, -18.0974, -11.2354, -12.5873,\n -13.8278, -12.9095, -24.0992, -20.0022, -10.5311,\n -13.4935, -14.7626, -13.3142, -15.3966, -19.5801,\n -16.5520, -8.6239, -23.3382, -5.4941, -8.3836,\n -13.5751, -14.7180, -16.7097, -19.2874, -23.3537,\n -12.8871, -17.8223, -21.0192, -13.8155, -24.1501,\n -16.6064, -12.4094, -19.9732, -10.3875, -23.1725,\n -18.8187, -15.6043, -18.5558, -15.0048, -14.6783,\n -17.4742, -18.5094, -14.2125, -16.3275, -14.9992,\n -6.1809, -18.5530, -11.5988, -21.9881, -13.7540,\n -13.4462, -15.9019, -15.9461],\n [ -10.7098, -0.0023, -30.3002, -11.9405, -23.1811,\n -11.5467, -10.6228, -22.1772, -11.2820, -22.9016,\n -21.9603, -15.6019, -21.4248, -13.8520, -22.6079,\n -22.8389, -22.5472, -29.7895, -13.4329, -19.8173,\n -15.1513, -14.5725, -29.7396, -23.1560, -20.0769,\n -26.5019, -30.8615, -15.7247, -21.9966, -25.5950,\n -15.1531, -15.2545, -29.9863, -6.1354, -18.8428,\n -16.0306, -21.7709, -26.7980, -18.9149, -23.1884,\n -21.8785, -23.2282, -20.9541, -14.5082, -26.1311,\n -25.9626, -15.7007, -27.2502, -14.2783, -19.9299,\n -17.7017, -22.7168, -21.1532, -25.0956, -22.1657,\n -16.8068, -28.8051, -14.7739, -20.1534, -20.6531,\n -21.6109, -25.5807, -23.4914, -28.2711, -22.0551,\n -11.1337, -27.0287, -24.8594],\n [ -8.5436, -0.0003, -20.5049, -13.3775, -21.3733,\n -13.7819, -12.4094, -16.9570, -11.3731, -15.5702,\n -23.3348, -20.8683, -17.5318, -16.8435, -20.8279,\n -18.5019, -16.5897, -23.4806, -11.1457, -10.4186,\n -11.2930, -13.6033, -22.3274, -18.1027, -19.7091,\n -21.8241, -29.2107, -16.4376, -22.4265, -19.4553,\n -20.0237, -21.6664, -25.0027, -14.9904, -19.4058,\n -19.9859, -19.4219, -21.5000, -16.1546, -23.1634,\n -24.7187, -19.7554, -19.7680, -16.9415, -20.6288,\n -25.0763, -13.1580, -25.1702, -21.6822, -19.8533,\n -18.8475, -24.1205, -23.5127, -18.5040, -24.2065,\n -17.7428, -23.1684, -18.1676, -18.9262, -22.0231,\n -27.7205, -23.8932, -22.8859, -28.1781, -21.7442,\n -15.8315, -26.9240, -24.9933],\n [ -17.4080, -14.8364, -12.7304, -15.9032, -21.5565,\n -12.4503, -17.2493, -6.8370, -10.1120, -13.9949,\n -22.0601, -27.0981, -11.0587, -19.5826, -11.7553,\n -13.6436, -17.3303, -19.4089, -6.3320, -0.0078,\n -10.2332, -20.4946, -11.3546, -14.8224, -18.5271,\n -15.5236, -16.0001, -21.1023, -23.1959, -13.6014,\n -30.6618, -21.2505, -18.7640, -25.0460, -12.9750,\n -26.1238, -13.9679, -13.0276, -13.4213, -21.9289,\n -21.6223, -15.9460, -14.4475, -22.0498, -17.8907,\n -16.1585, -11.0228, -12.1506, -23.2616, -23.8886,\n -17.2334, -25.5326, -20.2295, -5.3427, -17.5382,\n -17.7766, -16.7236, -17.2077, -12.1351, -22.8018,\n -16.2687, -17.7010, -21.5733, -23.1502, -21.2033,\n -22.8279, -15.8566, -16.2677],\n [ -12.4216, -16.1053, -29.1451, -9.0337, -11.8207,\n -0.0009, -8.6505, -7.5879, -10.0877, -22.7512,\n -19.2431, -13.7531, -20.8961, -14.4762, -10.8671,\n -15.7603, -21.4039, -29.3653, -10.6510, -13.1023,\n -14.5152, -17.3762, -21.2540, -25.8284, -24.3182,\n -15.3529, -16.0656, -15.8460, -23.3182, -29.9350,\n -30.5978, -24.7313, -27.4084, -15.8459, -12.5954,\n -27.1376, -24.8943, -18.8542, -15.8377, -31.1534,\n -31.7958, -27.5254, -18.8091, -22.7685, -31.5725,\n -19.4969, -17.6864, -21.3915, -21.7040, -25.9106,\n -24.4082, -31.0024, -28.0276, -17.2936, -11.2161,\n -30.6075, -31.1321, -25.2863, -17.6013, -17.5303,\n -13.4664, -19.4692, -23.7558, -34.9868, -29.0176,\n -19.2180, -21.6642, -26.0290],\n [ -3.0836, -11.1404, -14.8919, -7.7812, -8.5873,\n -2.8416, -7.9187, -1.2263, -0.8384, -4.9418,\n -5.6652, -7.9001, -8.2687, -6.6189, -2.4886,\n -5.1772, -10.7569, -14.3351, -8.7137, -3.0775,\n -4.2517, -15.6165, -10.7460, -9.8711, -13.8624,\n -5.6772, -6.5559, -15.6423, -15.2044, -14.9285,\n -23.3742, -14.8360, -15.4184, -12.3902, -7.6443,\n -14.3057, -12.3669, -9.7948, -15.4702, -17.0101,\n -18.7781, -15.8887, -15.6570, -17.4488, -18.3007,\n -14.6266, -7.6423, -10.5243, -19.5447, -23.4676,\n -18.1327, -19.0919, -17.4839, -7.4446, -13.4103,\n -17.8808, -14.2511, -19.8338, -14.2306, -10.3992,\n -7.1998, -17.1758, -11.6108, -21.3457, -13.3126,\n -15.0745, -12.9874, -15.5052],\n [ -7.9868, -15.4103, -16.8513, -13.4917, -15.0484,\n -13.9397, -22.5354, -17.7940, -17.8933, -9.6195,\n -2.2252, -9.3662, -11.3363, -8.0452, -7.2448,\n -0.1169, -17.2633, -15.0399, -22.6545, -14.7754,\n -17.6584, -21.3282, -20.6122, -10.2137, -18.9553,\n -17.0040, -8.7555, -17.0948, -10.5532, -17.3049,\n -19.0779, -15.6084, -7.8645, -16.4988, -13.3464,\n -16.7177, -14.6946, -14.1254, -28.4332, -9.9000,\n -17.9151, -23.5627, -21.2590, -18.2105, -20.5169,\n -14.8220, -18.7088, -12.3657, -23.9319, -22.5714,\n -19.7998, -11.6299, -12.3009, -18.5748, -21.3208,\n -20.9145, -15.2292, -22.2576, -22.6946, -12.8705,\n -12.1863, -21.7272, -10.3876, -16.9829, -9.7555,\n -15.6186, -16.9797, -17.5205],\n [ -0.0005, -14.5657, -22.4920, -8.7515, -13.2294,\n -10.9451, -14.1387, -13.1712, -14.7828, -16.2566,\n -8.9443, -10.7783, -18.9471, -10.4379, -12.8462,\n -10.3339, -15.3794, -19.9567, -17.7954, -19.3354,\n -13.7002, -17.1503, -16.4414, -12.1036, -18.4002,\n -20.5079, -20.7407, -13.5050, -14.8802, -20.9547,\n -14.9571, -14.5075, -16.1540, -13.2388, -15.8919,\n -14.0017, -17.9937, -21.3268, -19.5608, -12.4198,\n -20.9681, -20.9421, -18.2813, -17.0681, -21.2429,\n -20.7445, -13.7380, -15.6890, -18.0320, -18.9775,\n -17.1648, -18.3295, -17.9240, -20.8698, -18.1493,\n -16.5940, -22.7223, -21.8319, -18.6172, -9.1037,\n -15.5387, -19.4642, -15.6726, -21.3156, -15.0869,\n -12.4865, -19.2078, -19.4157],\n [ -0.0001, -16.9840, -21.5055, -11.8447, -12.0854,\n -15.3331, -14.0876, -13.8501, -13.9810, -13.6969,\n -10.8497, -13.2444, -21.0097, -14.6334, -14.9321,\n -14.7672, -15.0091, -17.4736, -20.1177, -19.6008,\n -14.9093, -15.6280, -14.9487, -14.5987, -19.9071,\n -18.3271, -22.7283, -16.6607, -18.2314, -21.5799,\n -16.9098, -17.2415, -18.3797, -16.5486, -17.9335,\n -15.5248, -20.3519, -20.3180, -20.0336, -15.8835,\n -22.3365, -20.8197, -20.5559, -19.0399, -20.3997,\n -23.9803, -13.2990, -18.3739, -20.4504, -20.5669,\n -18.5473, -20.0512, -20.7019, -20.2041, -19.8436,\n -17.8092, -22.0861, -24.1319, -19.9407, -11.3458,\n -19.9481, -19.7521, -16.2428, -23.2110, -17.0918,\n -16.6031, -20.7498, -21.6803],\n [ -0.0000, -17.1071, -23.5494, -12.9530, -13.9378,\n -16.4269, -13.1326, -15.8903, -16.1134, -18.2110,\n -15.6813, -15.4734, -24.7758, -17.0952, -19.6722,\n -18.0960, -16.9470, -19.2707, -20.4694, -20.8727,\n -16.9919, -14.5632, -16.0521, -18.1356, -21.0840,\n -20.3339, -27.6928, -15.6010, -19.6547, -23.5451,\n -17.0450, -19.1711, -20.5509, -17.9552, -18.1125,\n -18.2221, -23.0217, -21.9091, -18.4166, -18.5844,\n -24.6448, -21.6979, -20.9728, -19.7739, -21.6755,\n -25.6546, -14.3602, -21.3206, -19.1922, -19.4332,\n -19.6199, -21.5367, -22.8759, -21.6474, -20.0896,\n -18.4825, -25.5764, -23.9693, -19.5282, -12.6485,\n -23.1808, -18.8814, -18.8164, -25.3059, -20.4708,\n -16.8564, -23.1196, -23.7652],\n [ -0.0030, -11.5165, -16.0764, -10.3643, -9.1534,\n -10.1014, -6.3984, -10.5082, -8.3872, -12.4593,\n -11.1903, -9.1744, -17.3829, -11.8836, -14.3821,\n -13.4913, -12.3396, -11.9384, -13.5650, -12.5165,\n -11.1002, -8.8777, -11.1599, -14.4585, -13.0127,\n -11.0822, -18.2881, -9.8342, -13.6718, -16.0534,\n -12.3695, -12.9870, -14.8985, -11.5473, -9.7296,\n -13.1035, -16.1597, -13.3044, -11.3557, -15.0617,\n -16.7690, -13.9120, -15.0726, -13.5833, -15.2507,\n -17.2183, -9.0175, -15.7318, -11.5052, -13.7536,\n -15.0384, -14.2378, -16.3617, -13.1835, -12.3045,\n -13.2061, -17.0609, -15.9470, -12.3622, -8.3553,\n -14.6705, -11.4317, -11.8786, -17.6636, -14.4317,\n -11.3730, -15.2084, -16.0309],\n [ -0.0000, -20.0676, -20.8170, -14.1267, -13.4091,\n -16.9972, -12.8867, -12.8508, -16.4415, -17.9756,\n -16.6695, -17.1983, -24.9212, -17.5865, -19.5439,\n -17.8816, -15.9060, -17.6157, -20.6040, -18.9217,\n -14.7203, -16.3294, -11.5575, -16.6162, -19.7280,\n -17.8353, -26.7412, -16.7181, -19.6941, -20.8832,\n -18.3315, -20.2285, -19.0632, -20.7024, -17.3256,\n -17.7332, -22.1284, -20.7336, -16.1553, -17.6203,\n -24.3333, -19.2522, -19.5215, -21.0567, -19.3732,\n -24.9940, -12.9470, -18.9283, -19.2262, -19.4651,\n -20.1784, -21.9543, -22.7896, -18.9875, -19.8219,\n -17.2925, -23.8396, -23.9762, -17.8404, -11.7115,\n -22.9069, -17.6411, -18.7701, -23.3177, -20.4167,\n -17.4289, -21.6423, -22.5650]])\n\nmytargets = torch.tensor([ 0, 13, 14, 15, 3, 3, 11, 8, 6, 1, 7, 9, 11, 8, 21, 8, 11, 1,\n 8, 8, 6, 1, 21, 4, 13, 37, 4, 8, 11, 13, 14, 15, 3, 3, 11, 33,\n 1, 7, 9, 11, 8, 21, 8, 11, 1, 3, 3, 14, 26, 1, 21, 8, 11, 1,\n 19, 5, 3, 10, 10, 0], dtype=torch.int32)\nmytargetsStr = \"*schooten altemet een musquetschoot, altemet oock met groff*\"\n# scribblelens.corpus.v1/nl/tasman/18/line1.txt\n\n# --------------------------------------\nif __name__ == \"__main__\":\n from egs.scribblelens import alphabet\n\n if 0:\n # test align\n a = Aligner(\"b.txt\")\n a.append(\"line1\\n\")\n a.append(\"line2\\n\")\n else:\n # test forced align\n alphabet = alphabet.Alphabet(\"tasman.alphabet.plus.space.mode5.json\")\n myaligner = ForcedAligner(\"path.out.txt\",alphabet)\n\n '''\n Input :\n - groundtruth is a Python list of classes in alphabet (size < maxWidth)\n - feed in 'logprob' 2D tensor of [ nClasses x nTimestamps ] (nTimestamps < maxWidth)\n Output:\n - fill the array scores & tb\n '''\n # myaligner.forceAlign(mytargets, mylogprobs) # ORG DP\n\n # New Stack decoder way, with max stack of 2 tokens, and all path same length\n myaligner.forceAlign2(mytargets, mylogprobs)\n\n # Simpler, sequence length 3\n #myaligner.forceAlign2(mytargets[:3], mylogprobs[:5])\n\n\n" ]
[ [ "torch.cuda.is_available" ], [ "torch.zeros", "torch.isnan", "torch.IntTensor", "torch.FloatTensor", "numpy.copy", "torch.set_printoptions", "torch.tensor" ] ]
texpomru13/espnet
[ "7ef005e832e2fb033f356c16f54e0f08762fb4b0", "7ef005e832e2fb033f356c16f54e0f08762fb4b0", "7ef005e832e2fb033f356c16f54e0f08762fb4b0", "7ef005e832e2fb033f356c16f54e0f08762fb4b0", "7ef005e832e2fb033f356c16f54e0f08762fb4b0", "7ef005e832e2fb033f356c16f54e0f08762fb4b0", "7ef005e832e2fb033f356c16f54e0f08762fb4b0" ]
[ "espnet/optimizer/pytorch.py", "espnet2/torch_utils/device_funcs.py", "espnet2/tts/utils/duration_calculator.py", "espnet/nets/pytorch_backend/transducer/transducer_tasks.py", "espnet2/lm/espnet_model.py", "espnet2/enh/separator/rnn_separator.py", "test/espnet2/enh/separator/test_rnn_separator.py" ]
[ "\"\"\"PyTorch optimizer builders.\"\"\"\nimport argparse\n\nimport torch\n\nfrom espnet.optimizer.factory import OptimizerFactoryInterface\nfrom espnet.optimizer.parser import adadelta\nfrom espnet.optimizer.parser import adam\nfrom espnet.optimizer.parser import sgd\n\n\nclass AdamFactory(OptimizerFactoryInterface):\n \"\"\"Adam factory.\"\"\"\n\n @staticmethod\n def add_arguments(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:\n \"\"\"Register args.\"\"\"\n return adam(parser)\n\n @staticmethod\n def from_args(target, args: argparse.Namespace):\n \"\"\"Initialize optimizer from argparse Namespace.\n\n Args:\n target: for pytorch `model.parameters()`,\n for chainer `model`\n args (argparse.Namespace): parsed command-line args\n\n \"\"\"\n return torch.optim.Adam(\n target,\n lr=args.lr,\n weight_decay=args.weight_decay,\n betas=(args.beta1, args.beta2),\n )\n\n\nclass SGDFactory(OptimizerFactoryInterface):\n \"\"\"SGD factory.\"\"\"\n\n @staticmethod\n def add_arguments(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:\n \"\"\"Register args.\"\"\"\n return sgd(parser)\n\n @staticmethod\n def from_args(target, args: argparse.Namespace):\n \"\"\"Initialize optimizer from argparse Namespace.\n\n Args:\n target: for pytorch `model.parameters()`,\n for chainer `model`\n args (argparse.Namespace): parsed command-line args\n\n \"\"\"\n return torch.optim.SGD(\n target,\n lr=args.lr,\n weight_decay=args.weight_decay,\n )\n\n\nclass AdadeltaFactory(OptimizerFactoryInterface):\n \"\"\"Adadelta factory.\"\"\"\n\n @staticmethod\n def add_arguments(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:\n \"\"\"Register args.\"\"\"\n return adadelta(parser)\n\n @staticmethod\n def from_args(target, args: argparse.Namespace):\n \"\"\"Initialize optimizer from argparse Namespace.\n\n Args:\n target: for pytorch `model.parameters()`,\n for chainer `model`\n args (argparse.Namespace): parsed command-line args\n\n \"\"\"\n return torch.optim.Adadelta(\n target,\n rho=args.rho,\n eps=args.eps,\n weight_decay=args.weight_decay,\n )\n\n\nOPTIMIZER_FACTORY_DICT = {\n \"adam\": AdamFactory,\n \"sgd\": SGDFactory,\n \"adadelta\": AdadeltaFactory,\n}\n", "import dataclasses\nimport warnings\n\nimport numpy as np\nimport torch\n\n\ndef to_device(data, device=None, dtype=None, non_blocking=False, copy=False):\n \"\"\"Change the device of object recursively\"\"\"\n if isinstance(data, dict):\n return {\n k: to_device(v, device, dtype, non_blocking, copy) for k, v in data.items()\n }\n elif dataclasses.is_dataclass(data) and not isinstance(data, type):\n return type(data)(\n *[\n to_device(v, device, dtype, non_blocking, copy)\n for v in dataclasses.astuple(data)\n ]\n )\n # maybe namedtuple. I don't know the correct way to judge namedtuple.\n elif isinstance(data, tuple) and type(data) is not tuple:\n return type(data)(\n *[to_device(o, device, dtype, non_blocking, copy) for o in data]\n )\n elif isinstance(data, (list, tuple)):\n return type(data)(to_device(v, device, dtype, non_blocking, copy) for v in data)\n elif isinstance(data, np.ndarray):\n return to_device(torch.from_numpy(data), device, dtype, non_blocking, copy)\n elif isinstance(data, torch.Tensor):\n return data.to(device, dtype, non_blocking, copy)\n else:\n return data\n\n\ndef force_gatherable(data, device):\n \"\"\"Change object to gatherable in torch.nn.DataParallel recursively\n\n The difference from to_device() is changing to torch.Tensor if float or int\n value is found.\n\n The restriction to the returned value in DataParallel:\n The object must be\n - torch.cuda.Tensor\n - 1 or more dimension. 0-dimension-tensor sends warning.\n or a list, tuple, dict.\n\n \"\"\"\n if isinstance(data, dict):\n return {k: force_gatherable(v, device) for k, v in data.items()}\n # DataParallel can't handle NamedTuple well\n elif isinstance(data, tuple) and type(data) is not tuple:\n return type(data)(*[force_gatherable(o, device) for o in data])\n elif isinstance(data, (list, tuple, set)):\n return type(data)(force_gatherable(v, device) for v in data)\n elif isinstance(data, np.ndarray):\n return force_gatherable(torch.from_numpy(data), device)\n elif isinstance(data, torch.Tensor):\n if data.dim() == 0:\n # To 1-dim array\n data = data[None]\n return data.to(device)\n elif isinstance(data, float):\n return torch.tensor([data], dtype=torch.float, device=device)\n elif isinstance(data, int):\n return torch.tensor([data], dtype=torch.long, device=device)\n elif data is None:\n return None\n else:\n warnings.warn(f\"{type(data)} may not be gatherable by DataParallel\")\n return data\n", "# -*- coding: utf-8 -*-\n\n# Copyright 2020 Nagoya University (Tomoki Hayashi)\n# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)\n\n\"\"\"Duration calculator for ESPnet2.\"\"\"\n\nfrom typing import Tuple\n\nimport torch\n\n\nclass DurationCalculator(torch.nn.Module):\n \"\"\"Duration calculator module.\"\"\"\n\n @torch.no_grad()\n def forward(self, att_ws: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Convert attention weight to durations.\n\n Args:\n att_ws (Tesnor): Attention weight tensor (T_feats, T_text) or\n (#layers, #heads, T_feats, T_text).\n\n Returns:\n LongTensor: Duration of each input (T_text,).\n Tensor: Focus rate value.\n\n \"\"\"\n duration = self._calculate_duration(att_ws)\n focus_rate = self._calculate_focus_rete(att_ws)\n\n return duration, focus_rate\n\n @staticmethod\n def _calculate_focus_rete(att_ws):\n if len(att_ws.shape) == 2:\n # tacotron 2 case -> (T_feats, T_text)\n return att_ws.max(dim=-1)[0].mean()\n elif len(att_ws.shape) == 4:\n # transformer case -> (#layers, #heads, T_feats, T_text)\n return att_ws.max(dim=-1)[0].mean(dim=-1).max()\n else:\n raise ValueError(\"att_ws should be 2 or 4 dimensional tensor.\")\n\n @staticmethod\n def _calculate_duration(att_ws):\n if len(att_ws.shape) == 2:\n # tacotron 2 case -> (T_feats, T_text)\n pass\n elif len(att_ws.shape) == 4:\n # transformer case -> (#layers, #heads, T_feats, T_text)\n # get the most diagonal head according to focus rate\n att_ws = torch.cat(\n [att_w for att_w in att_ws], dim=0\n ) # (#heads * #layers, T_feats, T_text)\n diagonal_scores = att_ws.max(dim=-1)[0].mean(dim=-1) # (#heads * #layers,)\n diagonal_head_idx = diagonal_scores.argmax()\n att_ws = att_ws[diagonal_head_idx] # (T_feats, T_text)\n else:\n raise ValueError(\"att_ws should be 2 or 4 dimensional tensor.\")\n # calculate duration from 2d attention weight\n durations = torch.stack(\n [att_ws.argmax(-1).eq(i).sum() for i in range(att_ws.shape[1])]\n )\n return durations.view(-1)\n", "\"\"\"Module implementing Transducer main and auxiliary tasks.\"\"\"\n\nfrom typing import Any\nfrom typing import List\nfrom typing import Optional\nfrom typing import Tuple\n\nimport torch\n\nfrom espnet.nets.pytorch_backend.nets_utils import pad_list\nfrom espnet.nets.pytorch_backend.transformer.label_smoothing_loss import (\n LabelSmoothingLoss, # noqa: H301\n)\nfrom espnet.nets.pytorch_backend.transducer.joint_network import JointNetwork\n\n\nclass TransducerTasks(torch.nn.Module):\n \"\"\"Transducer tasks module.\"\"\"\n\n def __init__(\n self,\n encoder_dim: int,\n decoder_dim: int,\n joint_dim: int,\n output_dim: int,\n joint_activation_type: str = \"tanh\",\n transducer_loss_weight: float = 1.0,\n ctc_loss: bool = False,\n ctc_loss_weight: float = 0.5,\n ctc_loss_dropout_rate: float = 0.0,\n lm_loss: bool = False,\n lm_loss_weight: float = 0.5,\n lm_loss_smoothing_rate: float = 0.0,\n aux_transducer_loss: bool = False,\n aux_transducer_loss_weight: float = 0.2,\n aux_transducer_loss_mlp_dim: int = 320,\n aux_trans_loss_mlp_dropout_rate: float = 0.0,\n symm_kl_div_loss: bool = False,\n symm_kl_div_loss_weight: float = 0.2,\n fastemit_lambda: float = 0.0,\n blank_id: int = 0,\n ignore_id: int = -1,\n training: bool = False,\n ):\n \"\"\"Initialize module for Transducer tasks.\n\n Args:\n encoder_dim: Encoder outputs dimension.\n decoder_dim: Decoder outputs dimension.\n joint_dim: Joint space dimension.\n output_dim: Output dimension.\n joint_activation_type: Type of activation for joint network.\n transducer_loss_weight: Weight for main transducer loss.\n ctc_loss: Compute CTC loss.\n ctc_loss_weight: Weight of CTC loss.\n ctc_loss_dropout_rate: Dropout rate for CTC loss inputs.\n lm_loss: Compute LM loss.\n lm_loss_weight: Weight of LM loss.\n lm_loss_smoothing_rate: Smoothing rate for LM loss' label smoothing.\n aux_transducer_loss: Compute auxiliary transducer loss.\n aux_transducer_loss_weight: Weight of auxiliary transducer loss.\n aux_transducer_loss_mlp_dim: Hidden dimension for aux. transducer MLP.\n aux_trans_loss_mlp_dropout_rate: Dropout rate for aux. transducer MLP.\n symm_kl_div_loss: Compute KL divergence loss.\n symm_kl_div_loss_weight: Weight of KL divergence loss.\n fastemit_lambda: Regularization parameter for FastEmit.\n blank_id: Blank symbol ID.\n ignore_id: Padding symbol ID.\n training: Whether the model was initializated in training or inference mode.\n\n \"\"\"\n super().__init__()\n\n if not training:\n ctc_loss, lm_loss, aux_transducer_loss, symm_kl_div_loss = (\n False,\n False,\n False,\n False,\n )\n\n self.joint_network = JointNetwork(\n output_dim, encoder_dim, decoder_dim, joint_dim, joint_activation_type\n )\n\n if training:\n from warprnnt_pytorch import RNNTLoss\n\n self.transducer_loss = RNNTLoss(\n blank=blank_id,\n reduction=\"sum\",\n fastemit_lambda=fastemit_lambda,\n )\n\n if ctc_loss:\n self.ctc_lin = torch.nn.Linear(encoder_dim, output_dim)\n\n self.ctc_loss = torch.nn.CTCLoss(\n blank=blank_id,\n reduction=\"none\",\n zero_infinity=True,\n )\n\n if aux_transducer_loss:\n self.mlp = torch.nn.Sequential(\n torch.nn.Linear(encoder_dim, aux_transducer_loss_mlp_dim),\n torch.nn.LayerNorm(aux_transducer_loss_mlp_dim),\n torch.nn.Dropout(p=aux_trans_loss_mlp_dropout_rate),\n torch.nn.ReLU(),\n torch.nn.Linear(aux_transducer_loss_mlp_dim, joint_dim),\n )\n\n if symm_kl_div_loss:\n self.kl_div = torch.nn.KLDivLoss(reduction=\"sum\")\n\n if lm_loss:\n self.lm_lin = torch.nn.Linear(decoder_dim, output_dim)\n\n self.label_smoothing_loss = LabelSmoothingLoss(\n output_dim, ignore_id, lm_loss_smoothing_rate, normalize_length=False\n )\n\n self.output_dim = output_dim\n\n self.transducer_loss_weight = transducer_loss_weight\n\n self.use_ctc_loss = ctc_loss\n self.ctc_loss_weight = ctc_loss_weight\n self.ctc_dropout_rate = ctc_loss_dropout_rate\n\n self.use_lm_loss = lm_loss\n self.lm_loss_weight = lm_loss_weight\n\n self.use_aux_transducer_loss = aux_transducer_loss\n self.aux_transducer_loss_weight = aux_transducer_loss_weight\n\n self.use_symm_kl_div_loss = symm_kl_div_loss\n self.symm_kl_div_loss_weight = symm_kl_div_loss_weight\n\n self.blank_id = blank_id\n self.ignore_id = ignore_id\n\n self.target = None\n\n def compute_transducer_loss(\n self,\n enc_out: torch.Tensor,\n dec_out: torch.tensor,\n target: torch.Tensor,\n t_len: torch.Tensor,\n u_len: torch.Tensor,\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Compute Transducer loss.\n\n Args:\n enc_out: Encoder output sequences. (B, T, D_enc)\n dec_out: Decoder output sequences. (B, U, D_dec)\n target: Target label ID sequences. (B, L)\n t_len: Time lengths. (B,)\n u_len: Label lengths. (B,)\n\n Returns:\n (joint_out, loss_trans):\n Joint output sequences. (B, T, U, D_joint),\n Transducer loss value.\n\n \"\"\"\n joint_out = self.joint_network(enc_out.unsqueeze(2), dec_out.unsqueeze(1))\n\n loss_trans = self.transducer_loss(joint_out, target, t_len, u_len)\n loss_trans /= joint_out.size(0)\n\n return joint_out, loss_trans\n\n def compute_ctc_loss(\n self,\n enc_out: torch.Tensor,\n target: torch.Tensor,\n t_len: torch.Tensor,\n u_len: torch.Tensor,\n ):\n \"\"\"Compute CTC loss.\n\n Args:\n enc_out: Encoder output sequences. (B, T, D_enc)\n target: Target character ID sequences. (B, U)\n t_len: Time lengths. (B,)\n u_len: Label lengths. (B,)\n\n Returns:\n : CTC loss value.\n\n \"\"\"\n ctc_lin = self.ctc_lin(\n torch.nn.functional.dropout(\n enc_out.to(dtype=torch.float32), p=self.ctc_dropout_rate\n )\n )\n ctc_logp = torch.log_softmax(ctc_lin.transpose(0, 1), dim=-1)\n\n with torch.backends.cudnn.flags(deterministic=True):\n loss_ctc = self.ctc_loss(ctc_logp, target, t_len, u_len)\n\n return loss_ctc.mean()\n\n def compute_aux_transducer_and_symm_kl_div_losses(\n self,\n aux_enc_out: torch.Tensor,\n dec_out: torch.Tensor,\n joint_out: torch.Tensor,\n target: torch.Tensor,\n aux_t_len: torch.Tensor,\n u_len: torch.Tensor,\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Compute auxiliary Transducer loss and Jensen-Shannon divergence loss.\n\n Args:\n aux_enc_out: Encoder auxiliary output sequences. [N x (B, T_aux, D_enc_aux)]\n dec_out: Decoder output sequences. (B, U, D_dec)\n joint_out: Joint output sequences. (B, T, U, D_joint)\n target: Target character ID sequences. (B, L)\n aux_t_len: Auxiliary time lengths. [N x (B,)]\n u_len: True U lengths. (B,)\n\n Returns:\n : Auxiliary Transducer loss and KL divergence loss values.\n\n \"\"\"\n aux_trans_loss = 0\n symm_kl_div_loss = 0\n\n num_aux_layers = len(aux_enc_out)\n B, T, U, D = joint_out.shape\n\n for p in self.joint_network.parameters():\n p.requires_grad = False\n\n for i, aux_enc_out_i in enumerate(aux_enc_out):\n aux_mlp = self.mlp(aux_enc_out_i)\n\n aux_joint_out = self.joint_network(\n aux_mlp.unsqueeze(2),\n dec_out.unsqueeze(1),\n is_aux=True,\n )\n\n if self.use_aux_transducer_loss:\n aux_trans_loss += (\n self.transducer_loss(\n aux_joint_out,\n target,\n aux_t_len[i],\n u_len,\n )\n / B\n )\n\n if self.use_symm_kl_div_loss:\n denom = B * T * U\n\n kl_main_aux = (\n self.kl_div(\n torch.log_softmax(joint_out, dim=-1),\n torch.softmax(aux_joint_out, dim=-1),\n )\n / denom\n )\n\n kl_aux_main = (\n self.kl_div(\n torch.log_softmax(aux_joint_out, dim=-1),\n torch.softmax(joint_out, dim=-1),\n )\n / denom\n )\n\n symm_kl_div_loss += kl_main_aux + kl_aux_main\n\n for p in self.joint_network.parameters():\n p.requires_grad = True\n\n aux_trans_loss /= num_aux_layers\n\n if self.use_symm_kl_div_loss:\n symm_kl_div_loss /= num_aux_layers\n\n return aux_trans_loss, symm_kl_div_loss\n\n def compute_lm_loss(\n self,\n dec_out: torch.Tensor,\n target: torch.Tensor,\n ) -> torch.Tensor:\n \"\"\"Forward LM loss.\n\n Args:\n dec_out: Decoder output sequences. (B, U, D_dec)\n target: Target label ID sequences. (B, U)\n\n Returns:\n : LM loss value.\n\n \"\"\"\n lm_lin = self.lm_lin(dec_out)\n\n lm_loss = self.label_smoothing_loss(lm_lin, target)\n\n return lm_loss\n\n def set_target(self, target: torch.Tensor):\n \"\"\"Set target label ID sequences.\n\n Args:\n target: Target label ID sequences. (B, L)\n\n \"\"\"\n self.target = target\n\n def get_target(self):\n \"\"\"Set target label ID sequences.\n\n Args:\n\n Returns:\n target: Target label ID sequences. (B, L)\n\n \"\"\"\n return self.target\n\n def get_transducer_tasks_io(\n self,\n labels: torch.Tensor,\n enc_out_len: torch.Tensor,\n aux_enc_out_len: Optional[List],\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:\n \"\"\"Get Transducer tasks inputs and outputs.\n\n Args:\n labels: Label ID sequences. (B, U)\n enc_out_len: Time lengths. (B,)\n aux_enc_out_len: Auxiliary time lengths. [N X (B,)]\n\n Returns:\n target: Target label ID sequences. (B, L)\n lm_loss_target: LM loss target label ID sequences. (B, U)\n t_len: Time lengths. (B,)\n aux_t_len: Auxiliary time lengths. [N x (B,)]\n u_len: Label lengths. (B,)\n\n \"\"\"\n device = labels.device\n\n labels_unpad = [label[label != self.ignore_id] for label in labels]\n blank = labels[0].new([self.blank_id])\n\n target = pad_list(labels_unpad, self.blank_id).type(torch.int32).to(device)\n lm_loss_target = (\n pad_list(\n [torch.cat([y, blank], dim=0) for y in labels_unpad], self.ignore_id\n )\n .type(torch.int64)\n .to(device)\n )\n\n self.set_target(target)\n\n if enc_out_len.dim() > 1:\n enc_mask_unpad = [m[m != 0] for m in enc_out_len]\n enc_out_len = list(map(int, [m.size(0) for m in enc_mask_unpad]))\n else:\n enc_out_len = list(map(int, enc_out_len))\n\n t_len = torch.IntTensor(enc_out_len).to(device)\n u_len = torch.IntTensor([label.size(0) for label in labels_unpad]).to(device)\n\n if aux_enc_out_len:\n aux_t_len = []\n\n for i in range(len(aux_enc_out_len)):\n if aux_enc_out_len[i].dim() > 1:\n aux_mask_unpad = [aux[aux != 0] for aux in aux_enc_out_len[i]]\n aux_t_len.append(\n torch.IntTensor(\n list(map(int, [aux.size(0) for aux in aux_mask_unpad]))\n ).to(device)\n )\n else:\n aux_t_len.append(\n torch.IntTensor(list(map(int, aux_enc_out_len[i]))).to(device)\n )\n else:\n aux_t_len = aux_enc_out_len\n\n return target, lm_loss_target, t_len, aux_t_len, u_len\n\n def forward(\n self,\n enc_out: torch.Tensor,\n aux_enc_out: List[torch.Tensor],\n dec_out: torch.Tensor,\n labels: torch.Tensor,\n enc_out_len: torch.Tensor,\n aux_enc_out_len: torch.Tensor,\n ) -> Tuple[Tuple[Any], float, float]:\n \"\"\"Forward main and auxiliary task.\n\n Args:\n enc_out: Encoder output sequences. (B, T, D_enc)\n aux_enc_out: Encoder intermediate output sequences. (B, T_aux, D_enc_aux)\n dec_out: Decoder output sequences. (B, U, D_dec)\n target: Target label ID sequences. (B, L)\n t_len: Time lengths. (B,)\n aux_t_len: Auxiliary time lengths. (B,)\n u_len: Label lengths. (B,)\n\n Returns:\n : Weighted losses.\n (transducer loss, ctc loss, aux Transducer loss, KL div loss, LM loss)\n cer: Sentence-level CER score.\n wer: Sentence-level WER score.\n\n \"\"\"\n if self.use_symm_kl_div_loss:\n assert self.use_aux_transducer_loss\n\n (trans_loss, ctc_loss, lm_loss, aux_trans_loss, symm_kl_div_loss) = (\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n )\n\n target, lm_loss_target, t_len, aux_t_len, u_len = self.get_transducer_tasks_io(\n labels,\n enc_out_len,\n aux_enc_out_len,\n )\n\n joint_out, trans_loss = self.compute_transducer_loss(\n enc_out, dec_out, target, t_len, u_len\n )\n\n if self.use_ctc_loss:\n ctc_loss = self.compute_ctc_loss(enc_out, target, t_len, u_len)\n\n if self.use_aux_transducer_loss:\n (\n aux_trans_loss,\n symm_kl_div_loss,\n ) = self.compute_aux_transducer_and_symm_kl_div_losses(\n aux_enc_out,\n dec_out,\n joint_out,\n target,\n aux_t_len,\n u_len,\n )\n\n if self.use_lm_loss:\n lm_loss = self.compute_lm_loss(dec_out, lm_loss_target)\n\n return (\n self.transducer_loss_weight * trans_loss,\n self.ctc_loss_weight * ctc_loss,\n self.aux_transducer_loss_weight * aux_trans_loss,\n self.symm_kl_div_loss_weight * symm_kl_div_loss,\n self.lm_loss_weight * lm_loss,\n )\n", "from typing import Dict\nfrom typing import Optional\nfrom typing import Tuple\n\nimport torch\nimport torch.nn.functional as F\nfrom typeguard import check_argument_types\n\nfrom espnet.nets.pytorch_backend.nets_utils import make_pad_mask\nfrom espnet2.lm.abs_model import AbsLM\nfrom espnet2.torch_utils.device_funcs import force_gatherable\nfrom espnet2.train.abs_espnet_model import AbsESPnetModel\n\n\nclass ESPnetLanguageModel(AbsESPnetModel):\n def __init__(self, lm: AbsLM, vocab_size: int, ignore_id: int = 0):\n assert check_argument_types()\n super().__init__()\n self.lm = lm\n self.sos = vocab_size - 1\n self.eos = vocab_size - 1\n\n # ignore_id may be assumed as 0, shared with CTC-blank symbol for ASR.\n self.ignore_id = ignore_id\n\n def nll(\n self,\n text: torch.Tensor,\n text_lengths: torch.Tensor,\n max_length: Optional[int] = None,\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Compute negative log likelihood(nll)\n\n Normally, this function is called in batchify_nll.\n Args:\n text: (Batch, Length)\n text_lengths: (Batch,)\n max_lengths: int\n \"\"\"\n batch_size = text.size(0)\n # For data parallel\n if max_length is None:\n text = text[:, : text_lengths.max()]\n else:\n text = text[:, :max_length]\n\n # 1. Create a sentence pair like '<sos> w1 w2 w3' and 'w1 w2 w3 <eos>'\n # text: (Batch, Length) -> x, y: (Batch, Length + 1)\n x = F.pad(text, [1, 0], \"constant\", self.eos)\n t = F.pad(text, [0, 1], \"constant\", self.ignore_id)\n for i, l in enumerate(text_lengths):\n t[i, l] = self.sos\n x_lengths = text_lengths + 1\n\n # 2. Forward Language model\n # x: (Batch, Length) -> y: (Batch, Length, NVocab)\n y, _ = self.lm(x, None)\n\n # 3. Calc negative log likelihood\n # nll: (BxL,)\n nll = F.cross_entropy(y.view(-1, y.shape[-1]), t.view(-1), reduction=\"none\")\n # nll: (BxL,) -> (BxL,)\n if max_length is None:\n nll.masked_fill_(make_pad_mask(x_lengths).to(nll.device).view(-1), 0.0)\n else:\n nll.masked_fill_(\n make_pad_mask(x_lengths, maxlen=max_length + 1).to(nll.device).view(-1),\n 0.0,\n )\n # nll: (BxL,) -> (B, L)\n nll = nll.view(batch_size, -1)\n return nll, x_lengths\n\n def batchify_nll(\n self, text: torch.Tensor, text_lengths: torch.Tensor, batch_size: int = 100\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Compute negative log likelihood(nll) from transformer language model\n\n To avoid OOM, this fuction seperate the input into batches.\n Then call nll for each batch and combine and return results.\n Args:\n text: (Batch, Length)\n text_lengths: (Batch,)\n batch_size: int, samples each batch contain when computing nll,\n you may change this to avoid OOM or increase\n\n \"\"\"\n total_num = text.size(0)\n if total_num <= batch_size:\n nll, x_lengths = self.nll(text, text_lengths)\n else:\n nlls = []\n x_lengths = []\n max_length = text_lengths.max()\n\n start_idx = 0\n while True:\n end_idx = min(start_idx + batch_size, total_num)\n batch_text = text[start_idx:end_idx, :]\n batch_text_lengths = text_lengths[start_idx:end_idx]\n # batch_nll: [B * T]\n batch_nll, batch_x_lengths = self.nll(\n batch_text, batch_text_lengths, max_length=max_length\n )\n nlls.append(batch_nll)\n x_lengths.append(batch_x_lengths)\n start_idx = end_idx\n if start_idx == total_num:\n break\n nll = torch.cat(nlls)\n x_lengths = torch.cat(x_lengths)\n assert nll.size(0) == total_num\n assert x_lengths.size(0) == total_num\n return nll, x_lengths\n\n def forward(\n self, text: torch.Tensor, text_lengths: torch.Tensor\n ) -> Tuple[torch.Tensor, Dict[str, torch.Tensor], torch.Tensor]:\n nll, y_lengths = self.nll(text, text_lengths)\n ntokens = y_lengths.sum()\n loss = nll.sum() / ntokens\n stats = dict(loss=loss.detach())\n\n # force_gatherable: to-device and to-tensor if scalar for DataParallel\n loss, stats, weight = force_gatherable((loss, stats, ntokens), loss.device)\n return loss, stats, weight\n\n def collect_feats(\n self, text: torch.Tensor, text_lengths: torch.Tensor\n ) -> Dict[str, torch.Tensor]:\n return {}\n", "from collections import OrderedDict\nfrom distutils.version import LooseVersion\nfrom typing import List\nfrom typing import Tuple\nfrom typing import Union\n\nimport torch\nfrom torch_complex.tensor import ComplexTensor\n\nfrom espnet.nets.pytorch_backend.rnn.encoders import RNN\nfrom espnet2.enh.layers.complex_utils import is_complex\nfrom espnet2.enh.separator.abs_separator import AbsSeparator\n\n\nis_torch_1_9_plus = LooseVersion(torch.__version__) >= LooseVersion(\"1.9.0\")\n\n\nclass RNNSeparator(AbsSeparator):\n def __init__(\n self,\n input_dim: int,\n rnn_type: str = \"blstm\",\n num_spk: int = 2,\n nonlinear: str = \"sigmoid\",\n layer: int = 3,\n unit: int = 512,\n dropout: float = 0.0,\n ):\n \"\"\"RNN Separator\n\n Args:\n input_dim: input feature dimension\n rnn_type: string, select from 'blstm', 'lstm' etc.\n bidirectional: bool, whether the inter-chunk RNN layers are bidirectional.\n num_spk: number of speakers\n nonlinear: the nonlinear function for mask estimation,\n select from 'relu', 'tanh', 'sigmoid'\n layer: int, number of stacked RNN layers. Default is 3.\n unit: int, dimension of the hidden state.\n dropout: float, dropout ratio. Default is 0.\n \"\"\"\n super().__init__()\n\n self._num_spk = num_spk\n\n self.rnn = RNN(\n idim=input_dim,\n elayers=layer,\n cdim=unit,\n hdim=unit,\n dropout=dropout,\n typ=rnn_type,\n )\n\n self.linear = torch.nn.ModuleList(\n [torch.nn.Linear(unit, input_dim) for _ in range(self.num_spk)]\n )\n\n if nonlinear not in (\"sigmoid\", \"relu\", \"tanh\"):\n raise ValueError(\"Not supporting nonlinear={}\".format(nonlinear))\n\n self.nonlinear = {\n \"sigmoid\": torch.nn.Sigmoid(),\n \"relu\": torch.nn.ReLU(),\n \"tanh\": torch.nn.Tanh(),\n }[nonlinear]\n\n def forward(\n self, input: Union[torch.Tensor, ComplexTensor], ilens: torch.Tensor\n ) -> Tuple[List[Union[torch.Tensor, ComplexTensor]], torch.Tensor, OrderedDict]:\n \"\"\"Forward.\n\n Args:\n input (torch.Tensor or ComplexTensor): Encoded feature [B, T, N]\n ilens (torch.Tensor): input lengths [Batch]\n\n Returns:\n masked (List[Union(torch.Tensor, ComplexTensor)]): [(B, T, N), ...]\n ilens (torch.Tensor): (B,)\n others predicted data, e.g. masks: OrderedDict[\n 'mask_spk1': torch.Tensor(Batch, Frames, Freq),\n 'mask_spk2': torch.Tensor(Batch, Frames, Freq),\n ...\n 'mask_spkn': torch.Tensor(Batch, Frames, Freq),\n ]\n \"\"\"\n\n # if complex spectrum,\n if is_complex(input):\n feature = abs(input)\n else:\n feature = input\n\n x, ilens, _ = self.rnn(feature, ilens)\n\n masks = []\n\n for linear in self.linear:\n y = linear(x)\n y = self.nonlinear(y)\n masks.append(y)\n\n masked = [input * m for m in masks]\n\n others = OrderedDict(\n zip([\"mask_spk{}\".format(i + 1) for i in range(len(masks))], masks)\n )\n\n return masked, ilens, others\n\n @property\n def num_spk(self):\n return self._num_spk\n", "import pytest\n\nimport torch\nfrom torch import Tensor\nfrom torch_complex import ComplexTensor\n\nfrom espnet2.enh.separator.rnn_separator import RNNSeparator\n\n\n@pytest.mark.parametrize(\"input_dim\", [5])\n@pytest.mark.parametrize(\"rnn_type\", [\"blstm\"])\n@pytest.mark.parametrize(\"layer\", [1, 3])\n@pytest.mark.parametrize(\"unit\", [8])\n@pytest.mark.parametrize(\"dropout\", [0.0, 0.2])\n@pytest.mark.parametrize(\"num_spk\", [1, 2])\n@pytest.mark.parametrize(\"nonlinear\", [\"relu\", \"sigmoid\", \"tanh\"])\ndef test_rnn_separator_forward_backward_complex(\n input_dim, rnn_type, layer, unit, dropout, num_spk, nonlinear\n):\n model = RNNSeparator(\n input_dim=input_dim,\n rnn_type=rnn_type,\n layer=layer,\n unit=unit,\n dropout=dropout,\n num_spk=num_spk,\n nonlinear=nonlinear,\n )\n model.train()\n\n real = torch.rand(2, 10, input_dim)\n imag = torch.rand(2, 10, input_dim)\n x = ComplexTensor(real, imag)\n x_lens = torch.tensor([10, 8], dtype=torch.long)\n\n masked, flens, others = model(x, ilens=x_lens)\n\n assert isinstance(masked[0], ComplexTensor)\n assert len(masked) == num_spk\n\n masked[0].abs().mean().backward()\n\n\n@pytest.mark.parametrize(\"input_dim\", [5])\n@pytest.mark.parametrize(\"rnn_type\", [\"blstm\"])\n@pytest.mark.parametrize(\"layer\", [1, 3])\n@pytest.mark.parametrize(\"unit\", [8])\n@pytest.mark.parametrize(\"dropout\", [0.0, 0.2])\n@pytest.mark.parametrize(\"num_spk\", [1, 2])\n@pytest.mark.parametrize(\"nonlinear\", [\"relu\", \"sigmoid\", \"tanh\"])\ndef test_rnn_separator_forward_backward_real(\n input_dim, rnn_type, layer, unit, dropout, num_spk, nonlinear\n):\n model = RNNSeparator(\n input_dim=input_dim,\n rnn_type=rnn_type,\n layer=layer,\n unit=unit,\n dropout=dropout,\n num_spk=num_spk,\n nonlinear=nonlinear,\n )\n model.train()\n\n x = torch.rand(2, 10, input_dim)\n x_lens = torch.tensor([10, 8], dtype=torch.long)\n\n masked, flens, others = model(x, ilens=x_lens)\n\n assert isinstance(masked[0], Tensor)\n assert len(masked) == num_spk\n\n masked[0].abs().mean().backward()\n\n\ndef test_rnn_separator_invalid_type():\n with pytest.raises(ValueError):\n RNNSeparator(\n input_dim=10,\n rnn_type=\"rnn\",\n layer=2,\n unit=10,\n dropout=0.1,\n num_spk=2,\n nonlinear=\"fff\",\n )\n\n\ndef test_rnn_separator_output():\n\n x = torch.rand(2, 10, 10)\n x_lens = torch.tensor([10, 8], dtype=torch.long)\n\n for num_spk in range(1, 3):\n model = RNNSeparator(\n input_dim=10,\n rnn_type=\"rnn\",\n layer=2,\n unit=10,\n dropout=0.1,\n num_spk=num_spk,\n nonlinear=\"relu\",\n )\n model.eval()\n specs, _, others = model(x, x_lens)\n assert isinstance(specs, list)\n assert isinstance(others, dict)\n for n in range(num_spk):\n assert \"mask_spk{}\".format(n + 1) in others\n assert specs[n].shape == others[\"mask_spk{}\".format(n + 1)].shape\n" ]
[ [ "torch.optim.Adam", "torch.optim.Adadelta", "torch.optim.SGD" ], [ "torch.tensor", "torch.from_numpy" ], [ "torch.no_grad", "torch.cat" ], [ "torch.nn.Linear", "torch.nn.Dropout", "torch.nn.LayerNorm", "torch.cat", "torch.log_softmax", "torch.IntTensor", "torch.nn.CTCLoss", "torch.softmax", "torch.nn.ReLU", "torch.nn.KLDivLoss", "torch.backends.cudnn.flags" ], [ "torch.nn.functional.pad", "torch.cat" ], [ "torch.nn.Linear", "torch.nn.Tanh", "torch.nn.ReLU", "torch.nn.Sigmoid" ], [ "torch.rand", "torch.tensor" ] ]
halleanwoo/AGMA
[ "a1c4980e05150a9cfa1be338e7c8cbd8ccd6b002" ]
[ "src_convention/modules/agents/rnn_agent.py" ]
[ "import torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass RNNAgent(nn.Module):\n def __init__(self, input_shape, args):\n super(RNNAgent, self).__init__()\n self.args = args\n\n self.fc1 = nn.Linear(input_shape, args.rnn_hidden_dim)\n self.rnn = nn.GRUCell(args.rnn_hidden_dim, args.rnn_hidden_dim)\n if not args.levin_flag_quantile:\n self.fc2 = nn.Linear(args.rnn_hidden_dim, args.n_actions)\n else:\n self.fc2 = nn.Linear(args.rnn_hidden_dim, args.n_actions * args.N_QUANT)\n\n def init_hidden(self):\n # make hidden states on same device as model\n # 主要是在 controllers 中使用\n return self.fc1.weight.new(1, self.args.rnn_hidden_dim).zero_()\n\n def forward(self, inputs, hidden_state):\n mb_size = inputs.size(0)\n x = F.relu(self.fc1(inputs))\n h_in = hidden_state.reshape(-1, self.args.rnn_hidden_dim)\n h = self.rnn(x, h_in)\n if not self.args.levin_flag_quantile:\n q = self.fc2(h)\n else:\n q = self.fc2(h).view(mb_size, self.args.n_actions, self.args.N_QUANT)\n return q, h\n" ]
[ [ "torch.nn.Linear", "torch.nn.GRUCell" ] ]
MANGA-UOFA/NAUS
[ "8c0c0815a280d0661adf588302848c7f1ecc56da", "8c0c0815a280d0661adf588302848c7f1ecc56da" ]
[ "fairseq/data/data_utils.py", "fairseq/data/summarization_dataset.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\ntry:\n from collections.abc import Iterable\nexcept ImportError:\n from collections import Iterable\nimport contextlib\nimport itertools\nimport logging\nimport re\nimport warnings\nfrom typing import Optional, Tuple\n\nimport numpy as np\nimport torch\n\nfrom fairseq.file_io import PathManager\nfrom fairseq import utils\nimport os\n\nlogger = logging.getLogger(__name__)\n\n\ndef infer_language_pair(path):\n \"\"\"Infer language pair from filename: <split>.<lang1>-<lang2>.(...).idx\"\"\"\n src, dst = None, None\n for filename in PathManager.ls(path):\n parts = filename.split(\".\")\n if len(parts) >= 3 and len(parts[1].split(\"-\")) == 2:\n return parts[1].split(\"-\")\n return src, dst\n\n\ndef collate_tokens(\n values,\n pad_idx,\n eos_idx=None,\n left_pad=False,\n move_eos_to_beginning=False,\n pad_to_length=None,\n pad_to_multiple=1,\n pad_to_bsz=None,\n):\n \"\"\"Convert a list of 1d tensors into a padded 2d tensor.\"\"\"\n size = max(v.size(0) for v in values)\n size = size if pad_to_length is None else max(size, pad_to_length)\n if pad_to_multiple != 1 and size % pad_to_multiple != 0:\n size = int(((size - 0.1) // pad_to_multiple + 1) * pad_to_multiple)\n\n batch_size = len(values) if pad_to_bsz is None else max(len(values), pad_to_bsz)\n res = values[0].new(batch_size, size).fill_(pad_idx)\n\n def copy_tensor(src, dst):\n assert dst.numel() == src.numel()\n if move_eos_to_beginning:\n if eos_idx is None:\n # if no eos_idx is specified, then use the last token in src\n dst[0] = src[-1]\n else:\n dst[0] = eos_idx\n dst[1:] = src[:-1]\n else:\n dst.copy_(src)\n\n for i, v in enumerate(values):\n copy_tensor(v, res[i][size - len(v) :] if left_pad else res[i][: len(v)])\n return res\n\n\ndef load_indexed_dataset(\n path, dictionary=None, dataset_impl=None, combine=False, default=\"cached\"\n):\n \"\"\"A helper function for loading indexed datasets.\n\n Args:\n path (str): path to indexed dataset (e.g., 'data-bin/train')\n dictionary (~fairseq.data.Dictionary): data dictionary\n dataset_impl (str, optional): which dataset implementation to use. If\n not provided, it will be inferred automatically. For legacy indexed\n data we use the 'cached' implementation by default.\n combine (bool, optional): automatically load and combine multiple\n datasets. For example, if *path* is 'data-bin/train', then we will\n combine 'data-bin/train', 'data-bin/train1', ... and return a\n single ConcatDataset instance.\n \"\"\"\n import fairseq.data.indexed_dataset as indexed_dataset\n from fairseq.data.concat_dataset import ConcatDataset\n\n datasets = []\n for k in itertools.count():\n path_k = path + (str(k) if k > 0 else \"\")\n try:\n path_k = indexed_dataset.get_indexed_dataset_to_local(path_k)\n except Exception as e:\n if \"StorageException: [404] Path not found\" in str(e):\n logger.warning(f\"path_k: {e} not found\")\n else:\n raise e\n\n dataset_impl_k = dataset_impl\n if dataset_impl_k is None:\n dataset_impl_k = indexed_dataset.infer_dataset_impl(path_k)\n dataset = indexed_dataset.make_dataset(\n path_k,\n impl=dataset_impl_k or default,\n fix_lua_indexing=True,\n dictionary=dictionary,\n )\n if dataset is None:\n break\n logger.info(\"loaded {:,} examples from: {}\".format(len(dataset), path_k))\n datasets.append(dataset)\n if not combine:\n break\n if len(datasets) == 0:\n return None\n elif len(datasets) == 1:\n return datasets[0]\n else:\n return ConcatDataset(datasets)\n\n\n@contextlib.contextmanager\ndef numpy_seed(seed, *addl_seeds):\n \"\"\"Context manager which seeds the NumPy PRNG with the specified seed and\n restores the state afterward\"\"\"\n if seed is None:\n yield\n return\n if len(addl_seeds) > 0:\n seed = int(hash((seed, *addl_seeds)) % 1e6)\n state = np.random.get_state()\n np.random.seed(seed)\n try:\n yield\n finally:\n np.random.set_state(state)\n\n\ndef collect_filtered(function, iterable, filtered):\n \"\"\"\n Similar to :func:`filter` but collects filtered elements in ``filtered``.\n\n Args:\n function (callable): function that returns ``False`` for elements that\n should be filtered\n iterable (iterable): iterable to filter\n filtered (list): list to store filtered elements\n \"\"\"\n for el in iterable:\n if function(el):\n yield el\n else:\n filtered.append(el)\n\n\ndef _filter_by_size_dynamic(indices, size_fn, max_positions, raise_exception=False):\n def compare_leq(a, b):\n return a <= b if not isinstance(a, tuple) else max(a) <= b\n\n def check_size(idx):\n if isinstance(max_positions, float) or isinstance(max_positions, int):\n return size_fn(idx) <= max_positions\n elif isinstance(max_positions, dict):\n idx_size = size_fn(idx)\n assert isinstance(idx_size, dict)\n intersect_keys = set(max_positions.keys()) & set(idx_size.keys())\n return all(\n all(\n a is None or b is None or a <= b\n for a, b in zip(idx_size[key], max_positions[key])\n )\n for key in intersect_keys\n )\n else:\n # For MultiCorpusSampledDataset, will generalize it later\n if not isinstance(size_fn(idx), Iterable):\n return all(size_fn(idx) <= b for b in max_positions)\n return all(\n a is None or b is None or a <= b\n for a, b in zip(size_fn(idx), max_positions)\n )\n\n ignored = []\n itr = collect_filtered(check_size, indices, ignored)\n indices = np.fromiter(itr, dtype=np.int64, count=-1)\n return indices, ignored\n\n\ndef filter_by_size(indices, dataset, max_positions, raise_exception=False):\n \"\"\"\n [deprecated] Filter indices based on their size.\n Use `FairseqDataset::filter_indices_by_size` instead.\n\n Args:\n indices (List[int]): ordered list of dataset indices\n dataset (FairseqDataset): fairseq dataset instance\n max_positions (tuple): filter elements larger than this size.\n Comparisons are done component-wise.\n raise_exception (bool, optional): if ``True``, raise an exception if\n any elements are filtered (default: False).\n \"\"\"\n warnings.warn(\n \"data_utils.filter_by_size is deprecated. \"\n \"Use `FairseqDataset::filter_indices_by_size` instead.\",\n stacklevel=2,\n )\n if isinstance(max_positions, float) or isinstance(max_positions, int):\n if hasattr(dataset, \"sizes\") and isinstance(dataset.sizes, np.ndarray):\n ignored = indices[dataset.sizes[indices] > max_positions].tolist()\n indices = indices[dataset.sizes[indices] <= max_positions]\n elif (\n hasattr(dataset, \"sizes\")\n and isinstance(dataset.sizes, list)\n and len(dataset.sizes) == 1\n ):\n ignored = indices[dataset.sizes[0][indices] > max_positions].tolist()\n indices = indices[dataset.sizes[0][indices] <= max_positions]\n else:\n indices, ignored = _filter_by_size_dynamic(\n indices, dataset.size, max_positions\n )\n else:\n indices, ignored = _filter_by_size_dynamic(indices, dataset.size, max_positions)\n\n if len(ignored) > 0 and raise_exception:\n raise Exception(\n (\n \"Size of sample #{} is invalid (={}) since max_positions={}, \"\n \"skip this example with --skip-invalid-size-inputs-valid-test\"\n ).format(ignored[0], dataset.size(ignored[0]), max_positions)\n )\n if len(ignored) > 0:\n logger.warning(\n (\n \"{} samples have invalid sizes and will be skipped, \"\n \"max_positions={}, first few sample ids={}\"\n ).format(len(ignored), max_positions, ignored[:10])\n )\n return indices\n\n\ndef filter_paired_dataset_indices_by_size(src_sizes, tgt_sizes, indices, max_sizes):\n \"\"\"Filter a list of sample indices. Remove those that are longer\n than specified in max_sizes.\n\n Args:\n indices (np.array): original array of sample indices\n max_sizes (int or list[int] or tuple[int]): max sample size,\n can be defined separately for src and tgt (then list or tuple)\n\n Returns:\n np.array: filtered sample array\n list: list of removed indices\n \"\"\"\n if max_sizes is None:\n return indices, []\n if type(max_sizes) in (int, float):\n max_src_size, max_tgt_size = max_sizes, max_sizes\n else:\n max_src_size, max_tgt_size = max_sizes\n if tgt_sizes is None:\n ignored = indices[src_sizes[indices] > max_src_size]\n else:\n ignored = indices[\n (src_sizes[indices] > max_src_size) | (tgt_sizes[indices] > max_tgt_size)\n ]\n if len(ignored) > 0:\n if tgt_sizes is None:\n indices = indices[src_sizes[indices] <= max_src_size]\n else:\n indices = indices[\n (src_sizes[indices] <= max_src_size)\n & (tgt_sizes[indices] <= max_tgt_size)\n ]\n return indices, ignored.tolist()\n\n\ndef batch_by_size(\n indices,\n num_tokens_fn,\n num_tokens_vec=None,\n max_tokens=None,\n max_sentences=None,\n required_batch_size_multiple=1,\n fixed_shapes=None,\n):\n \"\"\"\n Yield mini-batches of indices bucketed by size. Batches may contain\n sequences of different lengths.\n\n Args:\n indices (List[int]): ordered list of dataset indices\n num_tokens_fn (callable): function that returns the number of tokens at\n a given index\n num_tokens_vec (List[int], optional): precomputed vector of the number\n of tokens for each index in indices (to enable faster batch generation)\n max_tokens (int, optional): max number of tokens in each batch\n (default: None).\n max_sentences (int, optional): max number of sentences in each\n batch (default: None).\n required_batch_size_multiple (int, optional): require batch size to\n be less than N or a multiple of N (default: 1).\n fixed_shapes (List[Tuple[int, int]], optional): if given, batches will\n only be created with the given shapes. *max_sentences* and\n *required_batch_size_multiple* will be ignored (default: None).\n \"\"\"\n try:\n from fairseq.data.data_utils_fast import (\n batch_by_size_fn,\n batch_by_size_vec,\n batch_fixed_shapes_fast,\n )\n except ImportError:\n raise ImportError(\n \"Please build Cython components with: \"\n \"`python setup.py build_ext --inplace`\"\n )\n except ValueError:\n raise ValueError(\n \"Please build (or rebuild) Cython components with `python setup.py build_ext --inplace`.\"\n )\n\n # added int() to avoid TypeError: an integer is required\n max_tokens = int(max_tokens) if max_tokens is not None else -1\n max_sentences = max_sentences if max_sentences is not None else -1\n bsz_mult = required_batch_size_multiple\n\n if not isinstance(indices, np.ndarray):\n indices = np.fromiter(indices, dtype=np.int64, count=-1)\n\n if num_tokens_vec is not None and not isinstance(num_tokens_vec, np.ndarray):\n num_tokens_vec = np.fromiter(num_tokens_vec, dtype=np.int64, count=-1)\n\n if fixed_shapes is None:\n if num_tokens_vec is None:\n return batch_by_size_fn(\n indices,\n num_tokens_fn,\n max_tokens,\n max_sentences,\n bsz_mult,\n )\n else:\n return batch_by_size_vec(\n indices,\n num_tokens_vec,\n max_tokens,\n max_sentences,\n bsz_mult,\n )\n\n else:\n fixed_shapes = np.array(fixed_shapes, dtype=np.int64)\n sort_order = np.lexsort(\n [\n fixed_shapes[:, 1].argsort(), # length\n fixed_shapes[:, 0].argsort(), # bsz\n ]\n )\n fixed_shapes_sorted = fixed_shapes[sort_order]\n return batch_fixed_shapes_fast(indices, num_tokens_fn, fixed_shapes_sorted)\n\n\ndef post_process(sentence: str, symbol: str):\n if symbol == \"sentencepiece\":\n sentence = sentence.replace(\" \", \"\").replace(\"\\u2581\", \" \").strip()\n elif symbol == \"wordpiece\":\n sentence = sentence.replace(\" \", \"\").replace(\"_\", \" \").strip()\n elif symbol == \"letter\":\n sentence = sentence.replace(\" \", \"\").replace(\"|\", \" \").strip()\n elif symbol == \"silence\":\n import re\n\n sentence = sentence.replace(\"<SIL>\", \"\")\n sentence = re.sub(\" +\", \" \", sentence).strip()\n elif symbol == \"_EOW\":\n sentence = sentence.replace(\" \", \"\").replace(\"_EOW\", \" \").strip()\n elif symbol in {\"subword_nmt\", \"@@ \", \"@@\"}:\n if symbol == \"subword_nmt\":\n symbol = \"@@ \"\n sentence = (sentence + \" \").replace(symbol, \"\").rstrip()\n elif symbol == \"none\":\n pass\n elif symbol is not None:\n raise NotImplementedError(f\"Unknown post_process option: {symbol}\")\n return sentence\n\n\ndef compute_mask_indices(\n shape: Tuple[int, int],\n padding_mask: Optional[torch.Tensor],\n mask_prob: float,\n mask_length: int,\n mask_type: str = \"static\",\n mask_other: float = 0.0,\n min_masks: int = 0,\n no_overlap: bool = False,\n min_space: int = 0,\n) -> np.ndarray:\n \"\"\"\n Computes random mask spans for a given shape\n\n Args:\n shape: the the shape for which to compute masks.\n should be of size 2 where first element is batch size and 2nd is timesteps\n padding_mask: optional padding mask of the same size as shape, which will prevent masking padded elements\n mask_prob: probability for each token to be chosen as start of the span to be masked. this will be multiplied by\n number of timesteps divided by length of mask span to mask approximately this percentage of all elements.\n however due to overlaps, the actual number will be smaller (unless no_overlap is True)\n mask_type: how to compute mask lengths\n static = fixed size\n uniform = sample from uniform distribution [mask_other, mask_length*2]\n normal = sample from normal distribution with mean mask_length and stdev mask_other. mask is min 1 element\n poisson = sample from possion distribution with lambda = mask length\n min_masks: minimum number of masked spans\n no_overlap: if false, will switch to an alternative recursive algorithm that prevents spans from overlapping\n min_space: only used if no_overlap is True, this is how many elements to keep unmasked between spans\n \"\"\"\n\n bsz, all_sz = shape\n mask = np.full((bsz, all_sz), False)\n\n all_num_mask = int(\n # add a random number for probabilistic rounding\n mask_prob * all_sz / float(mask_length)\n + np.random.rand()\n )\n\n all_num_mask = max(min_masks, all_num_mask)\n\n mask_idcs = []\n for i in range(bsz):\n if padding_mask is not None:\n sz = all_sz - padding_mask[i].long().sum().item()\n num_mask = int(\n # add a random number for probabilistic rounding\n mask_prob * sz / float(mask_length)\n + np.random.rand()\n )\n num_mask = max(min_masks, num_mask)\n else:\n sz = all_sz\n num_mask = all_num_mask\n\n if mask_type == \"static\":\n lengths = np.full(num_mask, mask_length)\n elif mask_type == \"uniform\":\n lengths = np.random.randint(mask_other, mask_length * 2 + 1, size=num_mask)\n elif mask_type == \"normal\":\n lengths = np.random.normal(mask_length, mask_other, size=num_mask)\n lengths = [max(1, int(round(x))) for x in lengths]\n elif mask_type == \"poisson\":\n lengths = np.random.poisson(mask_length, size=num_mask)\n lengths = [int(round(x)) for x in lengths]\n else:\n raise Exception(\"unknown mask selection \" + mask_type)\n\n if sum(lengths) == 0:\n lengths[0] = min(mask_length, sz - 1)\n\n if no_overlap:\n mask_idc = []\n\n def arrange(s, e, length, keep_length):\n span_start = np.random.randint(s, e - length)\n mask_idc.extend(span_start + i for i in range(length))\n\n new_parts = []\n if span_start - s - min_space >= keep_length:\n new_parts.append((s, span_start - min_space + 1))\n if e - span_start - keep_length - min_space > keep_length:\n new_parts.append((span_start + length + min_space, e))\n return new_parts\n\n parts = [(0, sz)]\n min_length = min(lengths)\n for length in sorted(lengths, reverse=True):\n lens = np.fromiter(\n (e - s if e - s >= length + min_space else 0 for s, e in parts),\n np.int,\n )\n l_sum = np.sum(lens)\n if l_sum == 0:\n break\n probs = lens / np.sum(lens)\n c = np.random.choice(len(parts), p=probs)\n s, e = parts.pop(c)\n parts.extend(arrange(s, e, length, min_length))\n mask_idc = np.asarray(mask_idc)\n else:\n min_len = min(lengths)\n if sz - min_len <= num_mask:\n min_len = sz - num_mask - 1\n\n mask_idc = np.random.choice(sz - min_len, num_mask, replace=False)\n\n mask_idc = np.asarray(\n [\n mask_idc[j] + offset\n for j in range(len(mask_idc))\n for offset in range(lengths[j])\n ]\n )\n\n mask_idcs.append(np.unique(mask_idc[mask_idc < sz]))\n\n min_len = min([len(m) for m in mask_idcs])\n for i, mask_idc in enumerate(mask_idcs):\n if len(mask_idc) > min_len:\n mask_idc = np.random.choice(mask_idc, min_len, replace=False)\n mask[i, mask_idc] = True\n\n return mask\n\n\ndef get_mem_usage():\n try:\n import psutil\n\n mb = 1024 * 1024\n return f\"used={psutil.virtual_memory().used / mb}Mb; avail={psutil.virtual_memory().available / mb}Mb\"\n except ImportError:\n return \"N/A\"\n\n\n# lens: torch.LongTensor\n# returns: torch.BoolTensor\ndef lengths_to_padding_mask(lens):\n bsz, max_lens = lens.size(0), torch.max(lens).item()\n mask = torch.arange(max_lens).to(lens.device).view(1, max_lens)\n mask = mask.expand(bsz, -1) >= lens.view(bsz, 1).expand(-1, max_lens)\n return mask\n\n\n# lens: torch.LongTensor\n# returns: torch.BoolTensor\ndef lengths_to_mask(lens):\n return ~lengths_to_padding_mask(lens)\n\n\ndef get_buckets(sizes, num_buckets):\n buckets = np.unique(\n np.percentile(\n sizes,\n np.linspace(0, 100, num_buckets + 1),\n interpolation=\"lower\",\n )[1:]\n )\n return buckets\n\n\ndef get_bucketed_sizes(orig_sizes, buckets):\n sizes = np.copy(orig_sizes)\n assert np.min(sizes) >= 0\n start_val = -1\n for end_val in buckets:\n mask = (sizes > start_val) & (sizes <= end_val)\n sizes[mask] = end_val\n start_val = end_val\n return sizes\n\n\ndef _find_extra_valid_paths(dataset_path: str) -> set:\n paths = utils.split_paths(dataset_path)\n all_valid_paths = set()\n for sub_dir in paths:\n contents = PathManager.ls(sub_dir)\n valid_paths = [c for c in contents if re.match(\"valid*[0-9].*\", c) is not None]\n all_valid_paths |= {os.path.basename(p) for p in valid_paths}\n # Remove .bin, .idx etc\n roots = {os.path.splitext(p)[0] for p in all_valid_paths}\n return roots\n\n\ndef raise_if_valid_subsets_unintentionally_ignored(train_cfg) -> None:\n \"\"\"Raises if there are paths matching 'valid*[0-9].*' which are not combined or ignored.\"\"\"\n if (\n train_cfg.dataset.ignore_unused_valid_subsets\n or train_cfg.dataset.combine_valid_subsets\n or train_cfg.dataset.disable_validation\n or not hasattr(train_cfg.task, \"data\")\n ):\n return\n other_paths = _find_extra_valid_paths(train_cfg.task.data)\n specified_subsets = train_cfg.dataset.valid_subset.split(\",\")\n ignored_paths = [p for p in other_paths if p not in specified_subsets]\n if ignored_paths:\n advice = \"Set --combine-val to combine them or --ignore-unused-valid-subsets to ignore them.\"\n msg = f\"Valid paths {ignored_paths} will be ignored. {advice}\"\n raise ValueError(msg)\n", "# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport logging\n\nimport numpy as np\nimport torch\nfrom fairseq.data import FairseqDataset, data_utils\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef collate(\n samples,\n pad_idx,\n eos_idx,\n left_pad_source=True,\n left_pad_target=False,\n input_feeding=True,\n pad_to_length=None,\n pad_to_multiple=1,\n):\n if len(samples) == 0:\n return {}\n\n def merge(key, left_pad, move_eos_to_beginning=False, pad_to_length=None):\n return data_utils.collate_tokens(\n [s[key] for s in samples],\n pad_idx,\n eos_idx,\n left_pad,\n move_eos_to_beginning,\n pad_to_length=pad_to_length,\n pad_to_multiple=pad_to_multiple,\n )\n\n def check_alignment(alignment, src_len, tgt_len):\n if alignment is None or len(alignment) == 0:\n return False\n if (\n alignment[:, 0].max().item() >= src_len - 1\n or alignment[:, 1].max().item() >= tgt_len - 1\n ):\n logger.warning(\"alignment size mismatch found, skipping alignment!\")\n return False\n return True\n\n def compute_alignment_weights(alignments):\n \"\"\"\n Given a tensor of shape [:, 2] containing the source-target indices\n corresponding to the alignments, a weight vector containing the\n inverse frequency of each target index is computed.\n For e.g. if alignments = [[5, 7], [2, 3], [1, 3], [4, 2]], then\n a tensor containing [1., 0.5, 0.5, 1] should be returned (since target\n index 3 is repeated twice)\n \"\"\"\n align_tgt = alignments[:, 1]\n _, align_tgt_i, align_tgt_c = torch.unique(\n align_tgt, return_inverse=True, return_counts=True\n )\n align_weights = align_tgt_c[align_tgt_i[np.arange(len(align_tgt))]]\n return 1.0 / align_weights.float()\n\n id = torch.LongTensor([s[\"id\"] for s in samples])\n src_tokens = merge(\n \"source\",\n left_pad=left_pad_source,\n pad_to_length=pad_to_length[\"source\"] if pad_to_length is not None else None,\n )\n # sort by descending source length\n src_lengths = torch.LongTensor(\n [s[\"source\"].ne(pad_idx).long().sum() for s in samples]\n )\n src_lengths, sort_order = src_lengths.sort(descending=True)\n id = id.index_select(0, sort_order)\n src_tokens = src_tokens.index_select(0, sort_order)\n\n prev_output_tokens = None\n target = None\n if samples[0].get(\"target\", None) is not None:\n target = merge(\n \"target\",\n left_pad=left_pad_target,\n pad_to_length=pad_to_length[\"target\"]\n if pad_to_length is not None\n else None,\n )\n target = target.index_select(0, sort_order)\n tgt_lengths = torch.LongTensor(\n [s[\"target\"].ne(pad_idx).long().sum() for s in samples]\n ).index_select(0, sort_order)\n ntokens = tgt_lengths.sum().item()\n\n if samples[0].get(\"prev_output_tokens\", None) is not None:\n prev_output_tokens = merge(\"prev_output_tokens\", left_pad=left_pad_target)\n elif input_feeding:\n # we create a shifted version of targets for feeding the\n # previous output token(s) into the next decoder step\n prev_output_tokens = merge(\n \"target\",\n left_pad=left_pad_target,\n move_eos_to_beginning=True,\n pad_to_length=pad_to_length[\"target\"]\n if pad_to_length is not None\n else None,\n )\n else:\n ntokens = src_lengths.sum().item()\n\n batch = {\n \"id\": id,\n \"nsentences\": len(samples),\n \"ntokens\": ntokens,\n \"net_input\": {\n \"src_tokens\": src_tokens,\n \"src_lengths\": src_lengths,\n },\n \"target\": target,\n }\n if prev_output_tokens is not None:\n batch[\"net_input\"][\"prev_output_tokens\"] = prev_output_tokens.index_select(\n 0, sort_order\n )\n\n if samples[0].get(\"alignment\", None) is not None:\n bsz, tgt_sz = batch[\"target\"].shape\n src_sz = batch[\"net_input\"][\"src_tokens\"].shape[1]\n\n offsets = torch.zeros((len(sort_order), 2), dtype=torch.long)\n offsets[:, 1] += torch.arange(len(sort_order), dtype=torch.long) * tgt_sz\n if left_pad_source:\n offsets[:, 0] += src_sz - src_lengths\n if left_pad_target:\n offsets[:, 1] += tgt_sz - tgt_lengths\n\n alignments = [\n alignment + offset\n for align_idx, offset, src_len, tgt_len in zip(\n sort_order, offsets, src_lengths, tgt_lengths\n )\n for alignment in [samples[align_idx][\"alignment\"].view(-1, 2)]\n if check_alignment(alignment, src_len, tgt_len)\n ]\n\n if len(alignments) > 0:\n alignments = torch.cat(alignments, dim=0)\n align_weights = compute_alignment_weights(alignments)\n\n batch[\"alignments\"] = alignments\n batch[\"align_weights\"] = align_weights\n\n if samples[0].get(\"constraints\", None) is not None:\n # Collate the packed constraints across the samples, padding to\n # the length of the longest sample.\n lens = [sample.get(\"constraints\").size(0) for sample in samples]\n max_len = max(lens)\n constraints = torch.zeros((len(samples), max(lens))).long()\n for i, sample in enumerate(samples):\n constraints[i, 0 : lens[i]] = samples[i].get(\"constraints\")\n batch[\"constraints\"] = constraints.index_select(0, sort_order)\n\n return batch\n\n\nclass SummarizationDataset(FairseqDataset):\n \"\"\"\n A pair of torch.utils.data.Datasets.\n\n Args:\n src (torch.utils.data.Dataset): source dataset to wrap\n src_sizes (List[int]): source sentence lengths\n src_dict (~fairseq.data.Dictionary): source vocabulary\n tgt (torch.utils.data.Dataset, optional): target dataset to wrap\n tgt_sizes (List[int], optional): target sentence lengths\n tgt_dict (~fairseq.data.Dictionary, optional): target vocabulary\n left_pad_source (bool, optional): pad source tensors on the left side\n (default: True).\n left_pad_target (bool, optional): pad target tensors on the left side\n (default: False).\n shuffle (bool, optional): shuffle dataset elements before batching\n (default: True).\n input_feeding (bool, optional): create a shifted version of the targets\n to be passed into the model for teacher forcing (default: True).\n remove_eos_from_source (bool, optional): if set, removes eos from end\n of source if it's present (default: False).\n append_eos_to_target (bool, optional): if set, appends eos to end of\n target if it's absent (default: False).\n align_dataset (torch.utils.data.Dataset, optional): dataset\n containing alignments.\n constraints (Tensor, optional): 2d tensor with a concatenated, zero-\n delimited list of constraints for each sentence.\n append_bos (bool, optional): if set, appends bos to the beginning of\n source/target sentence.\n num_buckets (int, optional): if set to a value greater than 0, then\n batches will be bucketed into the given number of batch shapes.\n src_lang_id (int, optional): source language ID, if set, the collated batch\n will contain a field 'src_lang_id' in 'net_input' which indicates the\n source language of the samples.\n tgt_lang_id (int, optional): target language ID, if set, the collated batch\n will contain a field 'tgt_lang_id' which indicates the target language\n of the samples.\n \"\"\"\n\n def __init__(\n self,\n src,\n src_sizes,\n src_dict,\n tgt=None,\n tgt_sizes=None,\n tgt_dict=None,\n left_pad_source=True,\n left_pad_target=False,\n shuffle=True,\n input_feeding=True,\n remove_eos_from_source=False,\n append_eos_to_target=False,\n align_dataset=None,\n constraints=None,\n append_bos=False,\n eos=None,\n num_buckets=0,\n src_lang_id=None,\n tgt_lang_id=None,\n pad_to_multiple=1,\n keep_bos_eos_tgt=False\n ):\n if tgt_dict is not None:\n assert src_dict.pad() == tgt_dict.pad()\n assert src_dict.eos() == tgt_dict.eos()\n assert src_dict.unk() == tgt_dict.unk()\n if tgt is not None:\n assert len(src) == len(\n tgt\n ), \"Source and target must contain the same number of examples\"\n self.src = src\n self.tgt = tgt\n self.src_sizes = np.array(src_sizes)\n self.tgt_sizes = np.array(tgt_sizes) if tgt_sizes is not None else None\n self.sizes = (\n np.vstack((self.src_sizes, self.tgt_sizes)).T\n if self.tgt_sizes is not None\n else self.src_sizes\n )\n self.src_dict = src_dict\n self.tgt_dict = tgt_dict\n self.left_pad_source = left_pad_source\n self.left_pad_target = left_pad_target\n self.shuffle = shuffle\n self.input_feeding = input_feeding\n self.remove_eos_from_source = remove_eos_from_source\n self.append_eos_to_target = append_eos_to_target\n self.align_dataset = align_dataset\n if self.align_dataset is not None:\n assert (\n self.tgt_sizes is not None\n ), \"Both source and target needed when alignments are provided\"\n self.constraints = constraints\n self.append_bos = append_bos\n self.eos = eos if eos is not None else src_dict.eos()\n self.src_lang_id = src_lang_id\n self.tgt_lang_id = tgt_lang_id\n if num_buckets > 0:\n from fairseq.data import BucketPadLengthDataset\n\n self.src = BucketPadLengthDataset(\n self.src,\n sizes=self.src_sizes,\n num_buckets=num_buckets,\n pad_idx=self.src_dict.pad(),\n left_pad=self.left_pad_source,\n )\n self.src_sizes = self.src.sizes\n logger.info(\"bucketing source lengths: {}\".format(list(self.src.buckets)))\n if self.tgt is not None:\n self.tgt = BucketPadLengthDataset(\n self.tgt,\n sizes=self.tgt_sizes,\n num_buckets=num_buckets,\n pad_idx=self.tgt_dict.pad(),\n left_pad=self.left_pad_target,\n )\n self.tgt_sizes = self.tgt.sizes\n logger.info(\n \"bucketing target lengths: {}\".format(list(self.tgt.buckets))\n )\n\n # determine bucket sizes using self.num_tokens, which will return\n # the padded lengths (thanks to BucketPadLengthDataset)\n num_tokens = np.vectorize(self.num_tokens, otypes=[np.compat.long])\n self.bucketed_num_tokens = num_tokens(np.arange(len(self.src)))\n self.buckets = [\n (None, num_tokens) for num_tokens in np.unique(self.bucketed_num_tokens)\n ]\n else:\n self.buckets = None\n self.pad_to_multiple = pad_to_multiple\n self.keep_bos_eos_tgt = keep_bos_eos_tgt\n\n def get_batch_shapes(self):\n return self.buckets\n\n def __getitem__(self, index):\n tgt_item = self.tgt[index] if self.tgt is not None else None\n src_item = self.src[index]\n # Append EOS to end of tgt sentence if it does not have an EOS and remove\n # EOS from end of src sentence if it exists. This is useful when we use\n # use existing datasets for opposite directions i.e., when we want to\n # use tgt_dataset as src_dataset and vice versa\n if self.append_eos_to_target:\n eos = self.tgt_dict.eos() if self.tgt_dict else self.src_dict.eos()\n if self.tgt and self.tgt[index][-1] != eos:\n tgt_item = torch.cat([self.tgt[index], torch.LongTensor([eos])])\n\n if self.append_bos:\n bos = self.tgt_dict.bos() if self.tgt_dict else self.src_dict.bos()\n if self.tgt and self.tgt[index][0] != bos:\n tgt_item = torch.cat([torch.LongTensor([bos]), self.tgt[index]])\n\n bos = self.src_dict.bos()\n if self.src[index][0] != bos:\n src_item = torch.cat([torch.LongTensor([bos]), self.src[index]])\n\n if self.remove_eos_from_source:\n eos = self.src_dict.eos()\n if self.src[index][-1] == eos:\n src_item = self.src[index][:-1]\n\n # Remove eos and bos tokens since they are not needed for summarization\n # src_item = self.remove_bos_eos(src_item)\n if not self.keep_bos_eos_tgt:\n tgt_item = self.remove_bos_eos(tgt_item)\n example = {\n \"id\": index,\n \"source\": src_item,\n \"target\": tgt_item,\n }\n if self.align_dataset is not None:\n example[\"alignment\"] = self.align_dataset[index]\n if self.constraints is not None:\n example[\"constraints\"] = self.constraints[index]\n return example\n\n def __len__(self):\n return len(self.src)\n\n def remove_bos_eos(self, sentence_index):\n \"\"\"\n Summarization task does not need bos and eos token, we\n \"\"\"\n bos = self.src_dict.bos()\n eos = self.src_dict.eos()\n sentence_index = sentence_index[(sentence_index != bos) & (sentence_index != eos)]\n\n return sentence_index\n\n def collater(self, samples, pad_to_length=None):\n \"\"\"Merge a list of samples to form a mini-batch.\n\n Args:\n samples (List[dict]): samples to collate\n pad_to_length (dict, optional): a dictionary of\n {'source': source_pad_to_length, 'target': target_pad_to_length}\n to indicate the max length to pad to in source and target respectively.\n\n Returns:\n dict: a mini-batch with the following keys:\n\n - `id` (LongTensor): example IDs in the original input order\n - `ntokens` (int): total number of tokens in the batch\n - `net_input` (dict): the input to the Model, containing keys:\n\n - `src_tokens` (LongTensor): a padded 2D Tensor of tokens in\n the source sentence of shape `(bsz, src_len)`. Padding will\n appear on the left if *left_pad_source* is ``True``.\n - `src_lengths` (LongTensor): 1D Tensor of the unpadded\n lengths of each source sentence of shape `(bsz)`\n - `prev_output_tokens` (LongTensor): a padded 2D Tensor of\n tokens in the target sentence, shifted right by one\n position for teacher forcing, of shape `(bsz, tgt_len)`.\n This key will not be present if *input_feeding* is\n ``False``. Padding will appear on the left if\n *left_pad_target* is ``True``.\n - `src_lang_id` (LongTensor): a long Tensor which contains source\n language IDs of each sample in the batch\n\n - `target` (LongTensor): a padded 2D Tensor of tokens in the\n target sentence of shape `(bsz, tgt_len)`. Padding will appear\n on the left if *left_pad_target* is ``True``.\n - `tgt_lang_id` (LongTensor): a long Tensor which contains target language\n IDs of each sample in the batch\n \"\"\"\n res = collate(\n samples,\n pad_idx=self.src_dict.pad(),\n eos_idx=self.eos,\n left_pad_source=self.left_pad_source,\n left_pad_target=self.left_pad_target,\n input_feeding=self.input_feeding,\n pad_to_length=pad_to_length,\n pad_to_multiple=self.pad_to_multiple,\n )\n if self.src_lang_id is not None or self.tgt_lang_id is not None:\n src_tokens = res[\"net_input\"][\"src_tokens\"]\n bsz = src_tokens.size(0)\n if self.src_lang_id is not None:\n res[\"net_input\"][\"src_lang_id\"] = (\n torch.LongTensor([[self.src_lang_id]]).expand(bsz, 1).to(src_tokens)\n )\n if self.tgt_lang_id is not None:\n res[\"tgt_lang_id\"] = (\n torch.LongTensor([[self.tgt_lang_id]]).expand(bsz, 1).to(src_tokens)\n )\n return res\n\n def num_tokens(self, index):\n \"\"\"Return the number of tokens in a sample. This value is used to\n enforce ``--max-tokens`` during batching.\"\"\"\n return max(\n self.src_sizes[index],\n self.tgt_sizes[index] if self.tgt_sizes is not None else 0,\n )\n\n def num_tokens_vec(self, indices):\n \"\"\"Return the number of tokens for a set of positions defined by indices.\n This value is used to enforce ``--max-tokens`` during batching.\"\"\"\n sizes = self.src_sizes[indices]\n if self.tgt_sizes is not None:\n sizes = np.maximum(sizes, self.tgt_sizes[indices])\n return sizes\n\n def size(self, index):\n \"\"\"Return an example's size as a float or tuple. This value is used when\n filtering a dataset with ``--max-positions``.\"\"\"\n return (\n self.src_sizes[index],\n self.tgt_sizes[index] if self.tgt_sizes is not None else 0,\n )\n\n def ordered_indices(self):\n \"\"\"Return an ordered list of indices. Batches will be constructed based\n on this order.\"\"\"\n if self.shuffle:\n indices = np.random.permutation(len(self)).astype(np.int64)\n else:\n indices = np.arange(len(self), dtype=np.int64)\n if self.buckets is None:\n # sort by target length, then source length\n if self.tgt_sizes is not None:\n indices = indices[np.argsort(self.tgt_sizes[indices], kind=\"mergesort\")]\n return indices[np.argsort(self.src_sizes[indices], kind=\"mergesort\")]\n else:\n # sort by bucketed_num_tokens, which is:\n # max(padded_src_len, padded_tgt_len)\n return indices[\n np.argsort(self.bucketed_num_tokens[indices], kind=\"mergesort\")\n ]\n\n @property\n def supports_prefetch(self):\n return getattr(self.src, \"supports_prefetch\", False) and (\n getattr(self.tgt, \"supports_prefetch\", False) or self.tgt is None\n )\n\n def prefetch(self, indices):\n self.src.prefetch(indices)\n if self.tgt is not None:\n self.tgt.prefetch(indices)\n if self.align_dataset is not None:\n self.align_dataset.prefetch(indices)\n\n def filter_indices_by_size(self, indices, max_sizes):\n \"\"\"Filter a list of sample indices. Remove those that are longer\n than specified in max_sizes.\n\n Args:\n indices (np.array): original array of sample indices\n max_sizes (int or list[int] or tuple[int]): max sample size,\n can be defined separately for src and tgt (then list or tuple)\n\n Returns:\n np.array: filtered sample array\n list: list of removed indices\n \"\"\"\n return data_utils.filter_paired_dataset_indices_by_size(\n self.src_sizes,\n self.tgt_sizes,\n indices,\n max_sizes,\n )\n" ]
[ [ "numpy.random.rand", "numpy.random.choice", "numpy.copy", "numpy.min", "numpy.full", "numpy.random.normal", "numpy.random.poisson", "numpy.random.get_state", "numpy.random.randint", "numpy.array", "torch.max", "numpy.random.set_state", "numpy.asarray", "torch.arange", "numpy.random.seed", "numpy.sum", "numpy.fromiter", "numpy.linspace", "numpy.unique" ], [ "torch.cat", "numpy.array", "torch.unique", "numpy.vectorize", "torch.LongTensor", "numpy.unique", "numpy.argsort", "numpy.vstack", "numpy.maximum" ] ]
AnimatedRNG/taichi
[ "f738bc165803c9e5083deb314da1cb6ca42ad591", "f1f403042dadf8b58887431dbf7a9a661c005bb2" ]
[ "examples/difftaichi/liquid.py", "examples/difftaichi/liquid_render.py" ]
[ "import taichi as ti\nfrom mpl_toolkits.mplot3d import Axes3D\nimport os\nimport math\nimport numpy as np\nimport random\nimport cv2\nimport matplotlib.pyplot as plt\nimport time\nimport taichi as tc\n\nreal = ti.f32\nti.set_default_fp(real)\n\ndim = 3\n# this will be overwritten\nn_particles = 0\nn_solid_particles = 0\nn_actuators = 0\nn_grid = 64\ndx = 1 / n_grid\ninv_dx = 1 / dx\ndt = 2e-3\np_vol = 1\nE = 10\n# TODO: update\nmu = E\nla = E\nmax_steps = 512\nsteps = 512\ngravity = 10\ntarget = [0.8, 0.2, 0.2]\nuse_apic = False\n\nscalar = lambda: ti.var(dt=real)\nvec = lambda: ti.Vector(dim, dt=real)\nmat = lambda: ti.Matrix(dim, dim, dt=real)\n\nactuator_id = ti.global_var(ti.i32)\nparticle_type = ti.global_var(ti.i32)\nx, v = vec(), vec()\ngrid_v_in, grid_m_in = vec(), scalar()\ngrid_v_out = vec()\nC, F = mat(), mat()\n\nscreen = ti.Vector(3, dt=real)\n\nloss = scalar()\n\nn_sin_waves = 4\nweights = scalar()\nbias = scalar()\nx_avg = vec()\n\nactuation = scalar()\nactuation_omega = 40\nact_strength = 5\n\n# ti.cfg.arch = ti.x86_64\n# ti.cfg.use_llvm = True\nti.cfg.arch = ti.cuda\n\n\n# ti.cfg.print_ir = True\n\n\nvisualize_resolution = 256\n\n@ti.layout\ndef place():\n ti.root.dense(ti.ij, (n_actuators, n_sin_waves)).place(weights)\n ti.root.dense(ti.i, n_actuators).place(bias)\n\n ti.root.dense(ti.ij, (max_steps, n_actuators)).place(actuation)\n ti.root.dense(ti.i, n_particles).place(actuator_id, particle_type)\n ti.root.dense(ti.l, max_steps).dense(ti.k, n_particles).place(x, v, C, F)\n ti.root.dense(ti.ijk, n_grid).place(grid_v_in, grid_m_in, grid_v_out)\n ti.root.place(loss, x_avg)\n ti.root.dense(ti.ij, (visualize_resolution, visualize_resolution)).place(screen)\n\n ti.root.lazy_grad()\n\n\ndef zero_vec():\n return [0.0, 0.0, 0.0]\n\n\ndef zero_matrix():\n return [zero_vec(), zero_vec(), zero_vec()]\n\n\n@ti.kernel\ndef clear_grid():\n for i, j, k in grid_m_in:\n grid_v_in[i, j, k] = [0, 0, 0]\n grid_m_in[i, j, k] = 0\n grid_v_in.grad[i, j, k] = [0, 0, 0]\n grid_m_in.grad[i, j, k] = 0\n grid_v_out.grad[i, j, k] = [0, 0, 0]\n\n\n@ti.kernel\ndef clear_particle_grad():\n # for all time steps and all particles\n for f, i in x:\n x.grad[f, i] = zero_vec()\n v.grad[f, i] = zero_vec()\n C.grad[f, i] = zero_matrix()\n F.grad[f, i] = zero_matrix()\n\n\n@ti.kernel\ndef clear_actuation_grad():\n for t, i in actuation:\n actuation[t, i] = 0.0\n\n\n@ti.kernel\ndef p2g(f: ti.i32):\n for p in range(0, n_particles):\n base = ti.cast(x[f, p] * inv_dx - 0.5, ti.i32)\n fx = x[f, p] * inv_dx - ti.cast(base, ti.i32)\n w = [0.5 * ti.sqr(1.5 - fx), 0.75 - ti.sqr(fx - 1),\n 0.5 * ti.sqr(fx - 0.5)]\n new_F = (ti.Matrix.diag(dim=dim, val=1) + dt * C[f, p]) @ F[f, p]\n J = ti.determinant(new_F)\n if particle_type[p] == 0: # fluid\n sqrtJ = ti.sqrt(J)\n # TODO: need pow(x, 1/3)\n new_F = ti.Matrix([[sqrtJ, 0, 0], [0, sqrtJ, 0], [0, 0, 1]])\n\n F[f + 1, p] = new_F\n # r, s = ti.polar_decompose(new_F)\n\n act_id = actuator_id[p]\n\n act = actuation[f, ti.max(0, act_id)] * act_strength\n if act_id == -1:\n act = 0.0\n # ti.print(act)\n\n A = ti.Matrix([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]) * act\n cauchy = ti.Matrix(zero_matrix())\n mass = 0.0\n ident = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]\n if particle_type[p] == 0:\n mass = 4\n cauchy = ti.Matrix(ident) * (J - 1) * E\n else:\n mass = 1\n cauchy = mu * (new_F @ ti.transposed(new_F)) + ti.Matrix(ident) * (la * ti.log(J) - mu)\n cauchy += new_F @ A @ ti.transposed(new_F)\n stress = -(dt * p_vol * 4 * inv_dx * inv_dx) * cauchy\n affine = stress + mass * C[f, p]\n for i in ti.static(range(3)):\n for j in ti.static(range(3)):\n for k in ti.static(range(3)):\n offset = ti.Vector([i, j, k])\n dpos = (ti.cast(ti.Vector([i, j, k]), real) - fx) * dx\n weight = w[i](0) * w[j](1) * w[k](2)\n grid_v_in[base + offset].atomic_add(\n weight * (mass * v[f, p] + affine @ dpos))\n grid_m_in[base + offset].atomic_add(weight * mass)\n\n\nbound = 3\ncoeff = 1.5\n\n\n@ti.kernel\ndef grid_op():\n for i, j, k in grid_m_in:\n inv_m = 1 / (grid_m_in[i, j, k] + 1e-10)\n v_out = inv_m * grid_v_in[i, j, k]\n v_out[1] -= dt * gravity\n\n if i < bound and v_out[0] < 0:\n v_out[0] = 0\n v_out[1] = 0\n v_out[2] = 0\n if i > n_grid - bound and v_out[0] > 0:\n v_out[0] = 0\n v_out[1] = 0\n v_out[2] = 0\n\n if k < bound and v_out[2] < 0:\n v_out[0] = 0\n v_out[1] = 0\n v_out[2] = 0\n if k > n_grid - bound and v_out[2] > 0:\n v_out[0] = 0\n v_out[1] = 0\n v_out[2] = 0\n\n if j < bound and v_out[1] < 0:\n v_out[0] = 0\n v_out[1] = 0\n v_out[2] = 0\n normal = ti.Vector([0.0, 1.0, 0.0])\n lsq = ti.sqr(normal).sum()\n if lsq > 0.5:\n if ti.static(coeff < 0):\n v_out[0] = 0\n v_out[1] = 0\n v_out[2] = 0\n else:\n lin = (ti.transposed(v_out) @ normal)(0)\n if lin < 0:\n vit = v_out - lin * normal\n lit = vit.norm() + 1e-10\n if lit + coeff * lin <= 0:\n v_out[0] = 0\n v_out[1] = 0\n v_out[2] = 0\n else:\n v_out = (1 + coeff * lin / lit) * vit\n if j > n_grid - bound and v_out[1] > 0:\n v_out[0] = 0\n v_out[1] = 0\n v_out[2] = 0\n\n grid_v_out[i, j, k] = v_out\n\n\n@ti.kernel\ndef g2p(f: ti.i32):\n for p in range(0, n_particles):\n base = ti.cast(x[f, p] * inv_dx - 0.5, ti.i32)\n fx = x[f, p] * inv_dx - ti.cast(base, real)\n w = [0.5 * ti.sqr(1.5 - fx), 0.75 - ti.sqr(fx - 1.0),\n 0.5 * ti.sqr(fx - 0.5)]\n new_v = ti.Vector(zero_vec())\n new_C = ti.Matrix(zero_matrix())\n\n for i in ti.static(range(3)):\n for j in ti.static(range(3)):\n for k in ti.static(range(3)):\n dpos = ti.cast(ti.Vector([i, j, k]), real) - fx\n g_v = grid_v_out[base(0) + i, base(1) + j, base(2) + k]\n weight = w[i](0) * w[j](1) * w[k](2)\n new_v += weight * g_v\n new_C += 4 * weight * ti.outer_product(g_v, dpos) * inv_dx\n\n v[f + 1, p] = new_v\n x[f + 1, p] = x[f, p] + dt * v[f + 1, p]\n C[f + 1, p] = new_C\n\n\n@ti.kernel\ndef compute_actuation(t: ti.i32):\n for i in range(n_actuators):\n act = 0.0\n for j in ti.static(range(n_sin_waves)):\n act += weights[i, j] * ti.sin(\n actuation_omega * t * dt + 2 * math.pi / n_sin_waves * j)\n act += bias[i]\n actuation[t, i] = ti.tanh(act)\n\n\n@ti.kernel\ndef compute_x_avg():\n for i in range(n_particles):\n contrib = 0.0\n if particle_type[i] == 1:\n contrib = 1.0 / n_solid_particles\n x_avg[None].atomic_add(contrib * x[steps - 1, i])\n\n\n@ti.kernel\ndef compute_loss():\n dist = x_avg[None][0]\n loss[None] = -dist\n\n\ndef forward(total_steps=steps):\n # simulation\n for s in range(total_steps - 1):\n clear_grid()\n compute_actuation()\n p2g(s)\n grid_op()\n g2p(s)\n\n x_avg[None] = [0, 0, 0]\n compute_x_avg()\n compute_loss()\n return loss[None]\n\n\ndef backward():\n clear_particle_grad()\n\n compute_loss.grad()\n compute_x_avg.grad()\n for s in reversed(range(steps - 1)):\n # Since we do not store the grid history (to save space), we redo p2g and grid op\n clear_grid()\n p2g(s)\n grid_op()\n\n g2p.grad(s)\n grid_op.grad()\n p2g.grad(s)\n compute_actuation.grad()\n\n\nclass Scene:\n def __init__(self):\n self.n_particles = 0\n self.n_solid_particles = 0\n self.x = []\n self.actuator_id = []\n self.particle_type = []\n self.offset_x = 0\n self.offset_y = 0\n self.offset_z = 0\n self.num_actuators = 0\n\n def new_actuator(self):\n self.num_actuators += 1\n global n_actuators\n n_actuators = self.num_actuators\n return self.num_actuators - 1\n\n def add_rect(self, x, y, z, w, h, d, actuation, ptype=1):\n if ptype == 0:\n assert actuation == -1\n global n_particles\n density = 3\n w_count = int(w / dx * density)\n h_count = int(h / dx * density)\n d_count = int(d / dx * density)\n real_dx = w / w_count\n real_dy = h / h_count\n real_dz = d / d_count\n \n if ptype == 1:\n for i in range(w_count):\n for j in range(h_count):\n for k in range(d_count):\n self.x.append([x + (i + 0.5) * real_dx + self.offset_x,\n y + (j + 0.5) * real_dy + self.offset_y,\n z + (k + 0.5) * real_dz + self.offset_z])\n self.actuator_id.append(actuation)\n self.particle_type.append(ptype)\n self.n_particles += 1\n self.n_solid_particles += int(ptype == 1)\n if self.n_particles % 1000 == 0:\n print(\"num particles\", self.n_particles)\n else:\n for i in range(w_count):\n for j in range(h_count):\n for k in range(d_count):\n self.x.append([x + random.random() * w + self.offset_x,\n y + random.random() * h + self.offset_y,\n z + random.random() * d + self.offset_z])\n self.actuator_id.append(actuation)\n self.particle_type.append(ptype)\n self.n_particles += 1\n self.n_solid_particles += int(ptype == 1)\n if self.n_particles % 1000 == 0:\n print(\"num particles\", self.n_particles)\n\n def set_offset(self, x, y, z):\n self.offset_x = x\n self.offset_y = y\n self.offset_z = z\n\n def finalize(self):\n global n_particles, n_solid_particles\n n_particles = self.n_particles\n n_solid_particles = max(self.n_solid_particles, 1)\n print('n_particles', n_particles)\n print('n_solid', n_solid_particles)\n\n def set_n_actuators(self, n_act):\n global n_actuators\n n_actuators = n_act\n\ngui = tc.core.GUI(\"Differentiable MPM\", tc.veci(1024, 1024))\ncanvas = gui.get_canvas()\n\n@ti.kernel\ndef splat(t: ti.i32):\n for i in range(n_particles):\n pos = ti.cast(x[t, i] * visualize_resolution, ti.i32)\n screen[pos[0], pos[1]][0] += 0.1\n\nres = [visualize_resolution, visualize_resolution]\n\n@ti.kernel\ndef copy_back_and_clear(img: np.ndarray):\n for i in range(res[0]):\n for j in range(res[1]):\n coord = ((res[1] - 1 - j) * res[0] + i) * 3\n for c in ti.static(range(3)):\n img[coord + c] = screen[i, j][2 - c]\n screen[i, j][2 - c] = 0\n\ndef robot(scene):\n block_size = 0.1\n # scene.set_offset(0.1, 0.10, 0.3)\n scene.set_offset(0.1, 0.05, 0.3)\n def add_leg(x, y, z):\n for i in range(4):\n scene.add_rect(x + block_size / 2 * (i // 2), y + 0.7 * block_size / 2 * (i % 2), z, block_size / 2, 0.7 * block_size / 2, block_size, scene.new_actuator())\n\n for i in range(4):\n add_leg(i // 2 * block_size * 2, 0.0, i % 2 * block_size * 2)\n for i in range(3):\n scene.add_rect(block_size * i, 0, block_size, block_size, block_size * 0.7, block_size, -1, 1)\n # scene.set_offset(0.1, 0.03, 0.3)\n scene.add_rect(0.1, 0.15, 0.1, 0.2, 0.05, 0.2, -1, 0)\n # scene.\n\n\ndef main():\n tc.set_gdb_trigger()\n # initialization\n scene = Scene()\n # fish(scene)\n robot(scene)\n # scene.add_rect(0.4, 0.4, 0.2, 0.1, 0.3, 0.1, -1, 1)\n scene.finalize()\n\n for i in range(n_actuators):\n for j in range(n_sin_waves):\n weights[i, j] = np.random.randn() * 0.01\n\n for i in range(scene.n_particles):\n x[0, i] = scene.x[i]\n F[0, i] = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]\n actuator_id[i] = scene.actuator_id[i]\n particle_type[i] = scene.particle_type[i]\n\n fig = plt.figure()\n plt.ion()\n ax = fig.add_subplot(111, projection='3d')\n\n losses = []\n for iter in range(501):\n ti.clear_all_gradients()\n l = forward()\n losses.append(l)\n loss.grad[None] = 1\n backward()\n print('i=', iter, 'loss=', l)\n learning_rate = 10\n\n for i in range(n_actuators):\n for j in range(n_sin_waves):\n # print(weights.grad[i, j])\n weights[i, j] -= learning_rate * weights.grad[i, j]\n bias[i] -= learning_rate * bias.grad[i]\n\n if iter % 50 == 0:\n # visualize\n print(\"Dumping particles...\")\n for s in range(7, steps, 2):\n def to255(x):\n return int(max(min(x * 255, 255), 0))\n xs, ys, zs = [], [], []\n us, vs, ws = [], [], []\n cs = []\n folder = 'mpm3d/iter{:04d}/'.format(iter)\n os.makedirs(folder, exist_ok=True)\n for i in range(n_particles):\n xs.append(x[s, i][0])\n ys.append(x[s, i][1])\n zs.append(x[s, i][2])\n us.append(v[s, i][0])\n vs.append(v[s, i][1])\n ws.append(v[s, i][2])\n\n if particle_type[i] == 0:\n # fluid\n r = 0.3\n g = 0.3\n b = 1.0\n else:\n # neohookean\n if actuator_id[i] != -1:\n # actuated\n act = actuation[s, actuator_id[i]] * 0.5\n r = 0.5 - act\n g = 0.5 - abs(act)\n b = 0.5 + act\n else:\n r, g, b = 0.4, 0.4, 0.4\n\n color = to255(r) * 65536 + 256 * to255(g) + to255(b)\n cs.append(color)\n data = np.array(xs + ys + zs + us + vs + ws + cs, dtype=np.float32)\n data.tofile(open('{}/{:04}.bin'.format(folder, s), 'wb'))\n print(\"Particles dumped\")\n\n\nif __name__ == '__main__':\n main()\n", "import taichi as ti\nimport math\nimport numpy as np\nimport cv2\nimport os\nimport matplotlib.pyplot as plt\n\nreal = ti.f32\nti.set_default_fp(real)\n# ti.runtime.print_preprocessed = True\n\nn_grid = 256\ndx = 1 / n_grid\ninv_dx = 1 / dx\ndt = 3e-4\nmax_steps = 256\nvis_interval = 32\noutput_vis_interval = 1\nsteps = 256\namplify = 2\n\nscalar = lambda: ti.var(dt=real)\nvec = lambda: ti.Vector(2, dt=real)\n\np = scalar()\nrendered = scalar()\ntarget = scalar()\ninitial = scalar()\nloss = scalar()\nheight_gradient = vec()\n\nbottom_image = scalar()\nrefracted_image = scalar()\n\n# mode = 'reflect'\nmode = 'refract'\n\nassert mode in ['reflect', 'refract', 'photon']\n\n# ti.cfg.arch = ti.cuda\n\n@ti.layout\ndef place():\n ti.root.dense(ti.l, max_steps).dense(ti.ij, n_grid).place(p)\n ti.root.dense(ti.ij, n_grid).place(rendered)\n ti.root.dense(ti.ij, n_grid).place(target)\n ti.root.dense(ti.ij, n_grid).place(initial)\n ti.root.dense(ti.ij, n_grid).place(height_gradient)\n ti.root.dense(ti.ijk, (n_grid, n_grid, 3)).place(bottom_image)\n ti.root.dense(ti.ijk, (n_grid, n_grid, 3)).place(refracted_image)\n ti.root.place(loss)\n ti.root.lazy_grad()\n\n\nc = 340\n# damping\nalpha = 0.00000\ninv_dx2 = inv_dx * inv_dx\ndt = (math.sqrt(alpha * alpha + dx * dx / 3) - alpha) / c\nlearning_rate = 0.1\n\n\n# TODO: there may by out-of-bound accesses here\n@ti.func\ndef laplacian(t, i, j):\n return inv_dx2 * (\n -4 * p[t, i, j] + p[t, i, j - 1] + p[t, i, j + 1] + p[t, i + 1, j] +\n p[t, i - 1, j])\n\n\n@ti.func\ndef gradient(t, i, j):\n return 0.5 * inv_dx * ti.Vector(\n [p[t, i + 1, j] - p[t, i - 1, j], p[t, i, j + 1] - p[t, i, j - 1]])\n\n\n@ti.kernel\ndef initialize():\n for i in range(n_grid):\n for j in range(n_grid):\n p[0, i, j] = initial[i, j]\n\n\n@ti.kernel\ndef fdtd(t: ti.i32):\n for i in range(n_grid): # Parallelized over GPU threads\n for j in range(n_grid):\n laplacian_p = laplacian(t - 2, i, j)\n laplacian_q = laplacian(t - 1, i, j)\n p[t, i, j] = 2 * p[t - 1, i, j] + (\n c * c * dt * dt + c * alpha * dt) * laplacian_q - p[\n t - 2, i, j] - c * alpha * dt * laplacian_p\n\n\n@ti.kernel\ndef render_reflect(t: ti.i32):\n for i in range(n_grid): # Parallelized over GPU threads\n for j in range(n_grid):\n grad = height_gradient[i, j]\n normal = ti.Vector.normalized(ti.Vector([grad[0], 1.0, grad[1]]))\n rendered[i, j] = normal[1]\n\n\n@ti.func\ndef pattern(i, j):\n return ti.cast(ti.floor(i / (n_grid / 8)) + ti.floor(j / (n_grid / 8)),\n ti.i32) % 2\n\n\n@ti.kernel\ndef render_refract(t: ti.i32):\n for i in range(n_grid): # Parallelized over GPU threads\n for j in range(n_grid):\n grad = height_gradient[i, j]\n \n scale = 2.0\n sample_x = i - grad[0] * scale\n sample_y = j - grad[1] * scale\n sample_x = ti.min(n_grid - 1, ti.max(0, sample_x))\n sample_y = ti.min(n_grid - 1, ti.max(0, sample_y))\n sample_xi = ti.cast(ti.floor(sample_x), ti.i32)\n sample_yi = ti.cast(ti.floor(sample_y), ti.i32)\n \n frac_x = sample_x - sample_xi\n frac_y = sample_y - sample_yi\n \n for k in ti.static(range(3)):\n refracted_image[i, j, k] = (1.0 - frac_x) * (\n (1 - frac_y) * bottom_image[sample_xi, sample_yi, k] + frac_y *\n bottom_image[\n sample_xi, sample_yi + 1, k]) + frac_x * (\n (1 - frac_y) * bottom_image[\n sample_xi + 1, sample_yi, k] + frac_y *\n bottom_image[\n sample_xi + 1, sample_yi + 1, k]\n )\n\n\n@ti.kernel\ndef compute_height_gradient(t: ti.i32):\n for i in range(n_grid): # Parallelized over GPU threads\n for j in range(n_grid):\n # TODO: fix boundary\n height_gradient[i, j] = gradient(t, i, j)\n\n\n@ti.kernel\ndef clear_photon_map():\n for i in range(n_grid):\n for j in range(n_grid):\n rendered[i, j] = 0.0\n\n\n@ti.kernel\ndef render_photon_map(t: ti.i32, offset_x: ti.f32, offset_y: ti.f32):\n for i in range(n_grid): # Parallelized over GPU threads\n for j in range(n_grid):\n grad = height_gradient[i, j] * (1 - offset_x) * (1 - offset_y) + \\\n height_gradient[i + 1, j] * offset_x * (1 - offset_y) + \\\n height_gradient[i, j + 1] * (1 - offset_x) * offset_y + \\\n height_gradient[i + 1, j + 1] * offset_x * offset_y\n \n scale = 5.0\n sample_x = i - grad[0] * scale + offset_x\n sample_y = j - grad[1] * scale + offset_y\n sample_x = ti.min(n_grid - 1, ti.max(0, sample_x))\n sample_y = ti.min(n_grid - 1, ti.max(0, sample_y))\n sample_xi = ti.cast(ti.floor(sample_x), ti.i32)\n sample_yi = ti.cast(ti.floor(sample_y), ti.i32)\n \n frac_x = sample_x - sample_xi\n frac_y = sample_y - sample_yi\n \n x = sample_xi\n y = sample_yi\n \n ti.atomic_add(rendered[x, y], (1 - frac_x) * (1 - frac_y))\n ti.atomic_add(rendered[x, y + 1], (1 - frac_x) * frac_y)\n ti.atomic_add(rendered[x + 1, y], frac_x * (1 - frac_y))\n ti.atomic_add(rendered[x + 1, y + 1], frac_x * frac_y)\n\n\n@ti.kernel\ndef compute_loss(t: ti.i32):\n for i in range(n_grid):\n for j in range(n_grid):\n ti.atomic_add(loss, dx * dx * ti.sqr(target[i, j] - p[t, i, j]))\n\n\n@ti.kernel\ndef apply_grad():\n # gradient descent\n for i, j in initial.grad:\n initial[i, j] -= learning_rate * initial.grad[i, j]\n\n\ndef forward(output=None):\n steps_mul = 1\n interval = vis_interval\n if output:\n os.makedirs(output, exist_ok=True)\n interval = output_vis_interval\n initialize()\n for t in range(2, steps * steps_mul):\n fdtd(t)\n if (t + 1) % interval == 0:\n clear_photon_map()\n compute_height_gradient()\n if mode == 'refract':\n render_refract()\n elif mode == 'photon':\n render_photon_map(t, 0.25, 0.25)\n render_photon_map(t, 0.25, 0.75)\n render_photon_map(t, 0.75, 0.25)\n render_photon_map(t, 0.75, 0.75)\n else:\n render_reflect()\n if mode == 'refract':\n img = np.zeros(shape=(n_grid, n_grid, 3), dtype=np.float32)\n for i in range(n_grid):\n for j in range(n_grid):\n for k in range(3):\n img[i, j, k] = refracted_image[i, j, k]\n img = cv2.resize(img, fx=4, fy=4, dsize=None)\n cv2.imshow('img', img)\n cv2.waitKey(1)\n if output:\n img = np.clip(img, 0, 255)\n cv2.imwrite(output + \"/{:04d}.png\".format(t), img * 255)\n else:\n img = np.zeros(shape=(n_grid, n_grid), dtype=np.float32)\n for i in range(n_grid):\n for j in range(n_grid):\n img[i, j] = rendered[i, j] * 0.3 / 4\n img = cv2.resize(img, fx=4, fy=4, dsize=None)\n cv2.imshow('img', img)\n cv2.waitKey(1)\n if output:\n img = np.clip(img, 0, 255)\n cv2.imwrite(output + \"/{:04d}.png\".format(t), img * 255)\n loss[None] = 0\n compute_loss(steps - 1)\n\n\ndef main():\n # initialization\n bot_img = cv2.imread('squirrel.jpg') / 255.0\n for i in range(256):\n for j in range(256):\n for k in range(3):\n bottom_image[i, j, k] = bot_img[i, j, k]\n target_img = cv2.imread('iclr2020.png')[:, :, 0] / 255.0\n target_img = cv2.resize(target_img, (n_grid, n_grid))\n target_img -= target_img.mean()\n cv2.imshow('target', target_img * amplify + 0.5)\n # print(target_img.min(), target_img.max())\n for i in range(n_grid):\n for j in range(n_grid):\n target[i, j] = float(target_img[i, j])\n \n initial[n_grid // 2, n_grid // 2] = 1\n # forward('water_renderer/initial')\n initial[n_grid // 2, n_grid // 2] = 0\n \n from adversarial import vgg_grad, predict\n \n for opt in range(10):\n with ti.Tape(loss):\n forward()\n \n feed_to_vgg = np.zeros((224, 224, 3), dtype=np.float32)\n # Note: do a transpose here\n for i in range(224):\n for j in range(224):\n for k in range(3):\n feed_to_vgg[i, j, k] = refracted_image[i + 16, j + 16, 2-k]\n \n predict(feed_to_vgg)\n grad = vgg_grad(feed_to_vgg)\n for i in range(224):\n for j in range(224):\n for k in range(3):\n refracted_image.grad[i + 16, j + 16, k] = grad[i, j, 2-k] * 0.001\n \n \n print('Iter', opt, ' Loss =', loss[None])\n \n apply_grad()\n \n forward('water_renderer/optimized')\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.array", "matplotlib.pyplot.ion", "numpy.random.randn", "matplotlib.pyplot.figure" ], [ "numpy.zeros", "numpy.clip" ] ]
dawnclaude/onnx2keras
[ "3d2a47c0a228b91fd434232274e216e491da36e3" ]
[ "test/layers/activations/test_sigmoid.py" ]
[ "import torch.nn as nn\nimport numpy as np\nimport pytest\n\nfrom test.utils import convert_and_test\n\n\nclass LayerSigmoid(nn.Module):\n \"\"\"\n Test for nn.layers based types\n \"\"\"\n def __init__(self):\n super(LayerSigmoid, self).__init__()\n self.sig = nn.Sigmoid()\n\n def forward(self, x):\n x = self.sig(x)\n return x\n\n\nclass FSigmoid(nn.Module):\n \"\"\"\n Test for nn.functional types\n \"\"\"\n def __init__(self):\n super(FSigmoid, self).__init__()\n\n def forward(self, x):\n from torch.nn import functional as F\n return F.sigmoid(x)\n\n\n@pytest.mark.parametrize('change_ordering', [True, False])\ndef test_layer_sigmoid(change_ordering):\n model = LayerSigmoid()\n model.eval()\n input_np = np.random.uniform(0, 1, (1, 3, 224, 224))\n error = convert_and_test(model, input_np, verbose=False, change_ordering=change_ordering)\n\n\n@pytest.mark.parametrize('change_ordering', [True, False])\ndef test_f_sigmoid(change_ordering):\n model = FSigmoid()\n model.eval()\n input_np = np.random.uniform(0, 1, (1, 3, 224, 224))\n error = convert_and_test(model, input_np, verbose=False, change_ordering=change_ordering)\n" ]
[ [ "torch.nn.functional.sigmoid", "numpy.random.uniform", "torch.nn.Sigmoid" ] ]
navistar792/web-scraping-challenge
[ "0959fc5bf994f8eb61a966917267be9906deb2dc" ]
[ "Missions_to_Mars/app.py" ]
[ "from flask import Flask, render_template, redirect, request, jsonify, Markup\nfrom flask_pymongo import PyMongo\nimport scrape_mars\nimport json\nimport pandas as pd\nimport time\n\napp = Flask(__name__)\n\n# Use PyMongo to establish Mongo connection\nmongo = PyMongo(app, uri=\"mongodb://localhost:27017/mars_db\")\n\n\n@app.route(\"/\")\ndef index():\n mars_1 = list(mongo.db.collection.find())\n print(mars_1)\n # render the html table\n df3 = pd.DataFrame(mars_1[0]['4']['table'], index=None)\n df4 = pd.DataFrame(df3.T)\n html_1 = df4.to_html(classes='table table-sm table-responsive table-striped table-hover ')\n html_2 = Markup(html_1)\n return render_template(\"index.html\", mars=mars_1, html_1=html_2)\n\n\n@app.route(\"/scrape\")\ndef scrape():\n # Run the scrape function from the scrape_mars.py file\n mars_data = scrape_mars.scrape_info()\n\n # with open('troubleshooting_app.json', 'w') as json_file:\n # json.dump(mars_data, json_file)\n \n # Update the Mongo database using update and upsert=True\n mongo.db.collection.update({}, mars_data, upsert=True)\n\n # Redirect back to home page\n return redirect(\"/\")\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n" ]
[ [ "pandas.DataFrame" ] ]
AngadSethi/adapter-transformers
[ "b147bba9107a5a561aca28c99f4e4ec2816a6e4f" ]
[ "tests/test_adapter_trainer.py" ]
[ "import unittest\n\nimport torch\n\nfrom transformers import (\n AutoModelForSequenceClassification,\n AutoTokenizer,\n BertConfig,\n BertForSequenceClassification,\n GlueDataset,\n GlueDataTrainingArguments,\n Trainer,\n TrainingArguments,\n)\nfrom transformers.adapters.composition import Fuse\nfrom transformers.testing_utils import slow\n\n\nclass TestAdapterTrainer(unittest.TestCase):\n def test_resume_training(self):\n\n tokenizer = AutoTokenizer.from_pretrained(\"bert-base-uncased\")\n data_args = GlueDataTrainingArguments(\n task_name=\"mrpc\", data_dir=\"./tests/fixtures/tests_samples/MRPC\", overwrite_cache=True\n )\n train_dataset = GlueDataset(data_args, tokenizer=tokenizer, mode=\"train\")\n\n model = AutoModelForSequenceClassification.from_pretrained(\"bert-base-uncased\")\n model.add_adapter(\"adapter\")\n model.add_adapter(\"additional_adapter\")\n model.set_active_adapters(\"adapter\")\n\n training_args = TrainingArguments(\n output_dir=\"./examples\",\n do_train=True,\n learning_rate=0.1,\n logging_steps=1,\n max_steps=1,\n save_steps=1,\n remove_unused_columns=False,\n )\n trainer = Trainer(\n model=model,\n args=training_args,\n train_dataset=train_dataset,\n do_save_adapters=True,\n do_save_full_model=False,\n )\n\n trainer.train()\n # create second model that should resume the training of the first\n model_resume = AutoModelForSequenceClassification.from_pretrained(\"bert-base-uncased\")\n model_resume.add_adapter(\"adapter\")\n model_resume.add_adapter(\"additional_adapter\")\n model_resume.set_active_adapters(\"adapter\")\n trainer_resume = Trainer(\n model=model_resume,\n args=TrainingArguments(do_train=True, max_steps=1, output_dir=\"./examples\"),\n train_dataset=train_dataset,\n do_save_adapters=True,\n do_save_full_model=False,\n )\n trainer_resume.train(resume_from_checkpoint=True)\n\n self.assertEqual(model.config.adapters.adapters, model_resume.config.adapters.adapters)\n\n for ((k1, v1), (k2, v2)) in zip(trainer.model.state_dict().items(), trainer_resume.model.state_dict().items()):\n self.assertEqual(k1, k2)\n if \"adapter\" in k1:\n self.assertTrue(torch.equal(v1, v2), k1)\n\n def test_resume_training_with_fusion(self):\n tokenizer = AutoTokenizer.from_pretrained(\"bert-base-uncased\")\n data_args = GlueDataTrainingArguments(\n task_name=\"mrpc\", data_dir=\"./tests/fixtures/tests_samples/MRPC\", overwrite_cache=True\n )\n train_dataset = GlueDataset(data_args, tokenizer=tokenizer, mode=\"train\")\n\n model = AutoModelForSequenceClassification.from_pretrained(\"bert-base-uncased\")\n model.add_adapter(\"adapter\")\n model.add_adapter(\"additional_adapter\")\n model.add_adapter_fusion(Fuse(\"adapter\", \"additional_adapter\"))\n model.set_active_adapters(Fuse(\"adapter\", \"additional_adapter\"))\n\n training_args = TrainingArguments(\n output_dir=\"./examples\",\n do_train=True,\n learning_rate=0.1,\n logging_steps=1,\n max_steps=1,\n save_steps=1,\n remove_unused_columns=False,\n )\n trainer = Trainer(\n model=model,\n args=training_args,\n train_dataset=train_dataset,\n do_save_adapters=True,\n do_save_full_model=False,\n do_save_adapter_fusion=True,\n )\n\n trainer.train()\n model_resume = AutoModelForSequenceClassification.from_pretrained(\"bert-base-uncased\")\n model_resume.add_adapter(\"adapter\")\n model_resume.add_adapter(\"additional_adapter\")\n model_resume.add_adapter_fusion(Fuse(\"adapter\", \"additional_adapter\"))\n model_resume.set_active_adapters(Fuse(\"adapter\", \"additional_adapter\"))\n trainer_resume = Trainer(\n model=model_resume,\n args=TrainingArguments(do_train=True, max_steps=1, output_dir=\"./examples\"),\n train_dataset=train_dataset,\n do_save_full_model=False,\n do_save_adapters=True,\n )\n trainer_resume.train(resume_from_checkpoint=True)\n\n self.assertEqual(model.config.adapters.adapters, model_resume.config.adapters.adapters)\n\n for ((k1, v1), (k2, v2)) in zip(trainer.model.state_dict().items(), trainer_resume.model.state_dict().items()):\n self.assertEqual(k1, k2)\n if \"adapter\" in k1:\n self.assertTrue(torch.equal(v1, v2), k1)\n\n def test_auto_set_save_adapters(self):\n model = BertForSequenceClassification(\n BertConfig(\n hidden_size=32,\n num_hidden_layers=4,\n num_attention_heads=4,\n intermediate_size=37,\n )\n )\n model.add_adapter(\"adapter\")\n model.train_adapter(\"adapter\")\n\n training_args = TrainingArguments(\n output_dir=\"./examples\",\n )\n trainer = Trainer(\n model=model,\n args=training_args,\n )\n\n self.assertFalse(trainer.do_save_full_model)\n self.assertTrue(trainer.do_save_adapters)\n self.assertTrue(trainer.do_save_adapter_fusion)\n\n @slow\n def test_training_load_best_model_at_end_full_model(self):\n tokenizer = AutoTokenizer.from_pretrained(\"bert-base-uncased\")\n data_args = GlueDataTrainingArguments(\n task_name=\"mrpc\", data_dir=\"./tests/fixtures/tests_samples/MRPC\", overwrite_cache=True\n )\n train_dataset = GlueDataset(data_args, tokenizer=tokenizer, mode=\"train\")\n eval_dataset = GlueDataset(data_args, tokenizer=tokenizer, mode=\"dev\")\n\n model = AutoModelForSequenceClassification.from_pretrained(\"bert-base-uncased\")\n model.add_adapter(\"adapter\")\n model.train_adapter(\"adapter\")\n\n training_args = TrainingArguments(\n output_dir=\"./examples\",\n do_train=True,\n learning_rate=0.001,\n max_steps=1,\n save_steps=1,\n remove_unused_columns=False,\n load_best_model_at_end=True,\n evaluation_strategy=\"epoch\",\n num_train_epochs=2,\n )\n trainer = Trainer(\n model=model,\n args=training_args,\n train_dataset=train_dataset,\n eval_dataset=eval_dataset,\n do_save_adapters=False,\n do_save_full_model=True,\n )\n\n trainer.train()\n self.assertIsNotNone(trainer.model.active_adapters)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "torch.equal" ] ]
bugrevelio/magenta
[ "a54c6e4aa8b32f2625d416fb1b39b03d123e1e51" ]
[ "magenta/models/rl_tuner/rl_tuner_ops.py" ]
[ "# Copyright 2016 Google Inc. 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\"\"\"Helper functions to support the RLTuner and NoteRNNLoader classes.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport random\n\n# internal imports\n\nimport numpy as np\nfrom six.moves import range # pylint: disable=redefined-builtin\nimport tensorflow as tf\n\n\nLSTM_STATE_NAME = 'lstm'\n\n# Number of output note classes. This is a property of the dataset.\nNUM_CLASSES = 38\n\n# Default batch size.\nBATCH_SIZE = 128\n\n# Music-related constants.\nINITIAL_MIDI_VALUE = 48\nNUM_SPECIAL_EVENTS = 2\nMIN_NOTE = 48 # Inclusive\nMAX_NOTE = 84 # Exclusive\nTRANSPOSE_TO_KEY = 0 # C Major\nDEFAULT_QPM = 80.0\n\n# Music theory constants used in defining reward functions.\n# Note that action 2 = midi note 48.\nC_MAJOR_SCALE = [2, 4, 6, 7, 9, 11, 13, 14, 16, 18, 19, 21, 23, 25, 26]\nC_MAJOR_KEY = [0, 1, 2, 4, 6, 7, 9, 11, 13, 14, 16, 18, 19, 21, 23, 25, 26, 28,\n 30, 31, 33, 35, 37]\nC_MAJOR_TONIC = 14\nA_MINOR_TONIC = 23\n\n# The number of half-steps in musical intervals, in order of dissonance\nOCTAVE = 12\nFIFTH = 7\nTHIRD = 4\nSIXTH = 9\nSECOND = 2\nFOURTH = 5\nSEVENTH = 11\nHALFSTEP = 1\n\n# Special intervals that have unique rewards\nREST_INTERVAL = -1\nHOLD_INTERVAL = -1.5\nREST_INTERVAL_AFTER_THIRD_OR_FIFTH = -2\nHOLD_INTERVAL_AFTER_THIRD_OR_FIFTH = -2.5\nIN_KEY_THIRD = -3\nIN_KEY_FIFTH = -5\n\n# Indicate melody direction\nASCENDING = 1\nDESCENDING = -1\n\n# Indicate whether a melodic leap has been resolved or if another leap was made\nLEAP_RESOLVED = 1\nLEAP_DOUBLED = -1\n\n\ndef default_hparams():\n \"\"\"Generates the hparams used to train note rnn used in paper.\"\"\"\n return tf.contrib.training.HParams(use_dynamic_rnn=True,\n batch_size=BATCH_SIZE,\n lr=0.0002,\n l2_reg=2.5e-5,\n clip_norm=5,\n initial_learning_rate=0.5,\n decay_steps=1000,\n decay_rate=0.85,\n rnn_layer_sizes=[100],\n skip_first_n_losses=32,\n one_hot_length=NUM_CLASSES,\n exponentially_decay_learning_rate=True)\n\n\ndef basic_rnn_hparams():\n \"\"\"Generates the hparams used to train a basic_rnn.\n\n These are the hparams used in the .mag file found at\n https://github.com/tensorflow/magenta/tree/master/magenta/models/\n melody_rnn#pre-trained\n\n Returns:\n Hyperparameters of the downloadable basic_rnn pre-trained model.\n \"\"\"\n # TODO(natashajaques): ability to restore basic_rnn from any .mag file.\n return tf.contrib.training.HParams(batch_size=128,\n rnn_layer_sizes=[512, 512],\n one_hot_length=NUM_CLASSES)\n\n\ndef default_dqn_hparams():\n \"\"\"Generates the default hparams for RLTuner DQN model.\"\"\"\n return tf.contrib.training.HParams(random_action_probability=0.1,\n store_every_nth=1,\n train_every_nth=5,\n minibatch_size=32,\n discount_rate=0.95,\n max_experience=100000,\n target_network_update_rate=0.01)\n\n\ndef autocorrelate(signal, lag=1):\n \"\"\"Gives the correlation coefficient for the signal's correlation with itself.\n\n Args:\n signal: The signal on which to compute the autocorrelation. Can be a list.\n lag: The offset at which to correlate the signal with itself. E.g. if lag\n is 1, will compute the correlation between the signal and itself 1 beat\n later.\n Returns:\n Correlation coefficient.\n \"\"\"\n n = len(signal)\n x = np.asarray(signal) - np.mean(signal)\n c0 = np.var(signal)\n\n return (x[lag:] * x[:n - lag]).sum() / float(n) / c0\n\n\ndef linear_annealing(n, total, p_initial, p_final):\n \"\"\"Linearly interpolates a probability between p_initial and p_final.\n\n Current probability is based on the current step, n. Used to linearly anneal\n the exploration probability of the RLTuner.\n\n Args:\n n: The current step.\n total: The total number of steps that will be taken (usually the length of\n the exploration period).\n p_initial: The initial probability.\n p_final: The final probability.\n\n Returns:\n The current probability (between p_initial and p_final).\n \"\"\"\n if n >= total:\n return p_final\n else:\n return p_initial - (n * (p_initial - p_final)) / (total)\n\n\ndef softmax(x):\n \"\"\"Compute softmax values for each sets of scores in x.\"\"\"\n e_x = np.exp(x - np.max(x))\n return e_x / e_x.sum(axis=0)\n\n\ndef sample_softmax(softmax_vect):\n \"\"\"Samples a note from an array of softmax probabilities.\n\n Tries to do this with numpy, which requires that the probabilities add to 1.0\n with extreme precision. If this fails, uses a manual implementation.\n\n Args:\n softmax_vect: An array of probabilities.\n Returns:\n The index of the note that was chosen/sampled.\n \"\"\"\n try:\n sample = np.argmax(np.random.multinomial(1, pvals=softmax_vect))\n return sample\n except: # pylint: disable=bare-except\n r = random.uniform(0, np.sum(softmax_vect))\n upto = 0\n for i in range(len(softmax_vect)):\n if upto + softmax_vect[i] >= r:\n return i\n upto += softmax_vect[i]\n tf.logging.warn(\"Error! sample softmax function shouldn't get here\")\n print(\"Error! sample softmax function shouldn't get here\")\n return len(softmax_vect) - 1\n\n\ndef decoder(event_list, transpose_amount):\n \"\"\"Translates a sequence generated by RLTuner to MonophonicMelody form.\n\n Args:\n event_list: Integer list of encoded notes.\n transpose_amount: Key to transpose to.\n Returns:\n Integer list of MIDI values.\n \"\"\"\n return [e - NUM_SPECIAL_EVENTS if e < NUM_SPECIAL_EVENTS else\n e + INITIAL_MIDI_VALUE - transpose_amount for e in event_list]\n\n\ndef make_onehot(int_list, one_hot_length):\n \"\"\"Convert each int to a one-hot vector.\n\n A one-hot vector is 0 everywhere except at the index equal to the\n encoded value.\n\n For example: 5 as a one-hot vector is [0, 0, 0, 0, 0, 1, 0, 0, 0, ...]\n\n Args:\n int_list: A list of ints, each of which will get a one-hot encoding.\n one_hot_length: The length of the one-hot vector to be created.\n Returns:\n A list of one-hot encodings of the ints.\n \"\"\"\n return [[1.0 if j == i else 0.0 for j in range(one_hot_length)]\n for i in int_list]\n\n\ndef get_inner_scope(scope_str):\n \"\"\"Takes a tensorflow scope string and finds the inner scope.\n\n Inner scope is one layer more internal.\n\n Args:\n scope_str: Tensorflow variable scope string.\n Returns:\n Scope string with outer scope stripped off.\n \"\"\"\n idx = scope_str.find('/')\n return scope_str[idx + 1:]\n\n\ndef trim_variable_postfixes(scope_str):\n \"\"\"Trims any extra numbers added to a tensorflow scope string.\n\n Necessary to align variables in graph and checkpoint\n\n Args:\n scope_str: Tensorflow variable scope string.\n Returns:\n Scope string with extra numbers trimmed off.\n \"\"\"\n idx = scope_str.find(':')\n return scope_str[:idx]\n\n\ndef get_variable_names(graph, scope):\n \"\"\"Finds all the variable names in a graph that begin with a given scope.\n\n Args:\n graph: A tensorflow graph.\n scope: A string scope.\n Returns:\n List of variables.\n \"\"\"\n with graph.as_default():\n return [v.name for v in tf.global_variables() if v.name.startswith(scope)]\n\n\ndef get_next_file_name(directory, prefix, extension):\n \"\"\"Finds next available filename in directory by appending numbers to prefix.\n\n E.g. If prefix is 'myfile', extenstion is '.png', and 'directory' already\n contains 'myfile.png' and 'myfile1.png', this function will return\n 'myfile2.png'.\n\n Args:\n directory: Path to the relevant directory.\n prefix: The filename prefix to use.\n extension: String extension of the file, eg. '.mid'.\n Returns:\n String name of the file.\n \"\"\"\n name = directory + '/' + prefix + '.' + extension\n i = 0\n while os.path.isfile(name):\n i += 1\n name = directory + '/' + prefix + str(i) + '.' + extension\n return name\n\n\ndef make_rnn_cell(rnn_layer_sizes, state_is_tuple=False):\n \"\"\"Makes a default LSTM cell for use in the NoteRNNLoader graph.\n\n This model is only to be used for loading the checkpoint from the research\n paper. In general, events_rnn_graph.make_rnn_cell should be used instead.\n\n Args:\n rnn_layer_sizes: A list of integer sizes (in units) for each layer of the\n RNN.\n state_is_tuple: A boolean specifying whether to use tuple of hidden matrix\n and cell matrix as a state instead of a concatenated matrix.\n\n Returns:\n A tf.contrib.rnn.MultiRNNCell based on the given hyperparameters.\n \"\"\"\n cells = []\n for num_units in rnn_layer_sizes:\n cell = tf.contrib.rnn.LSTMCell(num_units, state_is_tuple=state_is_tuple)\n cells.append(cell)\n\n cell = tf.contrib.rnn.MultiRNNCell(cells, state_is_tuple=state_is_tuple)\n\n return cell\n\n\ndef log_sum_exp(xs):\n \"\"\"Computes the log sum exp value of a tensor.\"\"\"\n maxes = tf.reduce_max(xs, keep_dims=True)\n xs -= maxes\n return tf.squeeze(maxes, [-1]) + tf.log(tf.reduce_sum(tf.exp(xs), -1))\n" ]
[ [ "numpy.max", "tensorflow.exp", "tensorflow.contrib.rnn.LSTMCell", "numpy.asarray", "numpy.sum", "tensorflow.global_variables", "numpy.mean", "tensorflow.reduce_max", "tensorflow.squeeze", "tensorflow.contrib.rnn.MultiRNNCell", "numpy.random.multinomial", "tensorflow.contrib.training.HParams", "tensorflow.logging.warn", "numpy.var" ] ]
adi3/NiaAML
[ "e8ff31f16147ac497903cc5bb2e5badecda43ae7" ]
[ "niaaml/classifiers/random_forest.py" ]
[ "from niaaml.classifiers.classifier import Classifier\nfrom niaaml.utilities import MinMax\nfrom niaaml.utilities import ParameterDefinition\nfrom sklearn.ensemble import RandomForestClassifier as RF\nimport numpy as np\n\nimport warnings\nfrom sklearn.exceptions import ChangedBehaviorWarning, ConvergenceWarning, DataConversionWarning, DataDimensionalityWarning, EfficiencyWarning, FitFailedWarning, NonBLASDotWarning, UndefinedMetricWarning\n\n__all__ = ['RandomForest']\n\nclass RandomForest(Classifier):\n r\"\"\"Implementation of random forest classifier.\n \n Date:\n 2020\n\n Author:\n Luka Pečnik\n\n License:\n MIT\n \n Reference:\n Breiman, “Random Forests”, Machine Learning, 45(1), 5-32, 2001.\n \n Documentation:\n https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html\n\n See Also:\n * :class:`niaaml.classifiers.Classifier`\n \"\"\"\n Name = 'Random Forest Classifier'\n\n def __init__(self, **kwargs):\n r\"\"\"Initialize RandomForestClassifier instance.\n \"\"\"\n warnings.filterwarnings(action='ignore', category=ChangedBehaviorWarning)\n warnings.filterwarnings(action='ignore', category=ConvergenceWarning)\n warnings.filterwarnings(action='ignore', category=DataConversionWarning)\n warnings.filterwarnings(action='ignore', category=DataDimensionalityWarning)\n warnings.filterwarnings(action='ignore', category=EfficiencyWarning)\n warnings.filterwarnings(action='ignore', category=FitFailedWarning)\n warnings.filterwarnings(action='ignore', category=NonBLASDotWarning)\n warnings.filterwarnings(action='ignore', category=UndefinedMetricWarning)\n\n self._params = dict(\n n_estimators = ParameterDefinition(MinMax(min=10, max=111), np.uint)\n )\n self.__random_forest_classifier = RF()\n\n def set_parameters(self, **kwargs):\n r\"\"\"Set the parameters/arguments of the algorithm.\n \"\"\"\n self.__random_forest_classifier.set_params(**kwargs)\n\n def fit(self, x, y, **kwargs):\n r\"\"\"Fit RandomForestClassifier.\n\n Arguments:\n x (pandas.core.frame.DataFrame): n samples to classify.\n y (pandas.core.series.Series): n classes of the samples in the x array.\n\n Returns:\n None\n \"\"\"\n self.__random_forest_classifier.fit(x, y)\n\n def predict(self, x, **kwargs):\n r\"\"\"Predict class for each sample (row) in x.\n\n Arguments:\n x (pandas.core.frame.DataFrame): n samples to classify.\n\n Returns:\n pandas.core.series.Series: n predicted classes.\n \"\"\"\n return self.__random_forest_classifier.predict(x)\n\n def to_string(self):\n r\"\"\"User friendly representation of the object.\n\n Returns:\n str: User friendly representation of the object.\n \"\"\"\n return Classifier.to_string(self).format(name=self.Name, args=self._parameters_to_string(self.__random_forest_classifier.get_params()))" ]
[ [ "sklearn.ensemble.RandomForestClassifier" ] ]
tangxyw/RecAlgorithm
[ "9d1907b63ef6be67b77660c10af655874a201b8d" ]
[ "algorithm/BST/leakyrelu.py" ]
[ "import tensorflow as tf\n\n\ndef leakyrelu(x, leak=0.01):\n \"\"\"\n leakyrelu激活函数\n Args:\n x (Tensor): input\n leak (int): x<0时的斜率\n\n Returns:\n Tensor\n \"\"\"\n f1 = 0.5 * (1 + leak)\n f2 = 0.5 * (1 - leak)\n return f1 * x + f2 * tf.abs(x)\n\n" ]
[ [ "tensorflow.abs" ] ]
alexfikl/pyvisfile
[ "756d209237472036f296419751b79fbc4d48a1ef" ]
[ "test/test_xdmf.py" ]
[ "import numpy as np\nimport pytest\n\nfrom pytools.obj_array import make_obj_array\n\n\n# {{{ test_unstructured_vertex_grid\n\n@pytest.mark.parametrize(\"ambient_dim\", [2, 3])\n@pytest.mark.parametrize(\"dformat\", [\"xml\", \"hdf\", \"binary\"])\ndef test_unstructured_vertex_grid(ambient_dim, dformat, npoints=64):\n \"\"\"Test constructing a vertex grid with different ways to define the\n points and connectivity.\n \"\"\"\n\n # {{{ set up connectivity\n\n from pyvisfile.xdmf import NumpyDataArray, DataArray, _data_item_from_numpy\n connectivity = np.arange(npoints, dtype=np.uint32)\n points = np.random.rand(ambient_dim, npoints)\n\n if dformat == \"xml\":\n connectivity = NumpyDataArray(connectivity, name=\"connectivity\")\n points = NumpyDataArray(points.T, name=\"points\")\n elif dformat in [\"hdf\", \"binary\"]:\n if dformat == \"hdf\":\n cdata = \"geometry.h5:/Grid/Connectivity\"\n pdata = \"geometry.h5:/Grid/Points\"\n else:\n cdata = \"connectivity.out\"\n pdata = \"points.out\"\n\n connectivity = DataArray((\n _data_item_from_numpy(connectivity,\n name=\"connectivity\",\n data=cdata),\n ))\n points = DataArray((\n _data_item_from_numpy(points.T,\n name=\"points\",\n data=pdata),\n ))\n else:\n raise ValueError(f\"unknown format: '{dformat}'\")\n\n # }}}\n\n # {{{ set up grids\n\n from pyvisfile.xdmf import TopologyType\n from pyvisfile.xdmf import XdmfUnstructuredGrid\n grid = XdmfUnstructuredGrid(\n points, connectivity,\n topology_type=TopologyType.Polyvertex,\n name=\"polyvertex\")\n\n # }}}\n\n from pyvisfile.xdmf import XdmfWriter\n writer = XdmfWriter((grid,))\n\n filename = f\"test_unstructured_vertex_{dformat}_{ambient_dim}d.xmf\"\n writer.write_pretty(filename)\n\n# }}}\n\n\n# {{{ test_unstructured_simplex_grid\n\ndef _simplex_box_connectivity(*, npoints, nelements, nvertices):\n # NOTE: largely copied from meshmode/mesh/generation.py::generate_box_mesh\n ambient_dim = len(npoints)\n\n point_indices = np.arange(np.prod(npoints)).reshape(npoints)\n connectivity = np.empty((nelements, nvertices), dtype=np.uint32)\n\n ielement = 0\n from itertools import product\n if ambient_dim == 1:\n raise NotImplementedError\n elif ambient_dim == 2:\n for i, j in product(range(npoints[0] - 1), repeat=ambient_dim):\n a = point_indices[i + 0, j + 0]\n b = point_indices[i + 1, j + 0]\n c = point_indices[i + 0, j + 1]\n d = point_indices[i + 1, j + 1]\n\n connectivity[ielement + 0, :] = (a, b, c)\n connectivity[ielement + 1, :] = (d, c, b)\n ielement += 2\n elif ambient_dim == 3:\n for i, j, k in product(range(npoints[0] - 1), repeat=ambient_dim):\n a000 = point_indices[i, j, k]\n a001 = point_indices[i, j, k+1]\n a010 = point_indices[i, j+1, k]\n a011 = point_indices[i, j+1, k+1]\n\n a100 = point_indices[i+1, j, k]\n a101 = point_indices[i+1, j, k+1]\n a110 = point_indices[i+1, j+1, k]\n a111 = point_indices[i+1, j+1, k+1]\n\n connectivity[ielement + 0, :] = (a000, a100, a010, a001)\n connectivity[ielement + 1, :] = (a101, a100, a001, a010)\n connectivity[ielement + 2, :] = (a101, a011, a010, a001)\n\n connectivity[ielement + 3, :] = (a100, a010, a101, a110)\n connectivity[ielement + 4, :] = (a011, a010, a110, a101)\n connectivity[ielement + 5, :] = (a011, a111, a101, a110)\n ielement += 6\n else:\n raise NotImplementedError\n\n assert ielement == nelements\n\n from pyvisfile.xdmf import NumpyDataArray\n return NumpyDataArray(connectivity, name=\"connectivity\")\n\n\n@pytest.mark.parametrize(\"ambient_dim\", [2, 3])\ndef test_unstructured_simplex_grid(ambient_dim, nelements=16):\n \"\"\"Test constructing a grid with a more complicated topology.\"\"\"\n\n from pyvisfile.xdmf import TopologyType\n if ambient_dim == 1:\n topology_type = TopologyType.Polyline\n simplices_per_quad = 1\n if ambient_dim == 2:\n topology_type = TopologyType.Triangle\n simplices_per_quad = 2\n elif ambient_dim == 3:\n topology_type = TopologyType.Tetrahedron\n simplices_per_quad = 6\n else:\n raise ValueError(\"unsupported dimension\")\n\n # {{{ points and connectivity\n\n x = np.linspace(-1.0, 1.0, nelements + 1)\n\n npoints = len(x)\n points = np.empty((ambient_dim,) + (npoints,) * ambient_dim)\n for idim in range(ambient_dim):\n points[idim] = x.reshape((npoints,) + (1,) * (ambient_dim - 1 - idim))\n\n from pyvisfile.xdmf import NumpyDataArray\n points = NumpyDataArray(points.reshape(ambient_dim, -1).T, name=\"points\")\n\n from pyvisfile.xdmf import _XDMF_ELEMENT_NODE_COUNT\n connectivity = _simplex_box_connectivity(\n npoints=(npoints,) * ambient_dim,\n nelements=simplices_per_quad * nelements**ambient_dim,\n nvertices=_XDMF_ELEMENT_NODE_COUNT[topology_type]\n )\n\n # }}}\n\n # {{{ attributes\n\n temperature = np.sin(2.0 * np.pi * points.ary[:, 0]) \\\n + np.cos(2.0 * np.pi * points.ary[:, 1])\n temperature = NumpyDataArray(temperature, name=\"temperature\")\n\n velocity = points.ary + np.array([0, 1, 2][:ambient_dim]).reshape(1, -1)\n velocity = NumpyDataArray(velocity, name=\"velocity\")\n vorticity = NumpyDataArray(make_obj_array(velocity.ary), name=\"vorticity\")\n\n # }}}\n\n # {{{ write grids\n\n from pyvisfile.xdmf import XdmfUnstructuredGrid\n grid = XdmfUnstructuredGrid(\n points, connectivity,\n topology_type=topology_type,\n name=\"simplex\")\n\n grid.add_attribute(temperature)\n grid.add_attribute(velocity)\n grid.add_attribute(vorticity)\n\n from pyvisfile.xdmf import XdmfWriter\n writer = XdmfWriter((grid,))\n\n filename = f\"test_unstructured_simplex_{ambient_dim}d.xmf\"\n writer.write_pretty(filename)\n\n # }}}\n\n\nif __name__ == \"__main__\":\n import sys\n if len(sys.argv) > 1:\n exec(sys.argv[1])\n else:\n pytest.main([__file__])\n\n# vim: fdm=marker\n" ]
[ [ "numpy.sin", "numpy.array", "numpy.random.rand", "numpy.empty", "numpy.prod", "numpy.arange", "numpy.cos", "numpy.linspace" ] ]
brisvag/dynamotable
[ "baeea6fcebfa8b277be20c591b28fff658f46909" ]
[ "dynamotable/dynamotable.py" ]
[ "from pathlib import Path\nfrom typing import Union\n\nimport pandas as pd\n\nfrom .convention import COLUMN_NAMES\nfrom .table_map import table_map_read\n\n\ndef open(table_file: str, table_map_file: str = None) -> pd.DataFrame:\n \"\"\"\n Opens a dynamo table file, returning a DynamoTable object\n :param table_file:\n :return: dataframe\n \"\"\"\n # Read into dataframe\n df = pd.read_csv(table_file, header=None, delim_whitespace=True)\n n_cols = df.shape[1]\n if n_cols <= len(COLUMN_NAMES):\n column_names = COLUMN_NAMES[0:n_cols]\n df.columns = column_names\n\n # In case table has extra columns\n else:\n extra_columns_needed = n_cols - len(COLUMN_NAMES)\n column_names = list(COLUMN_NAMES) + ['' for x in range(extra_columns_needed)]\n\n # Take absolute value (daxis column sometimes has complex values)\n df = df.apply(pd.to_numeric, errors='ignore')\n\n # Add table map info\n if table_map_file is not None and Path(table_map_file).exists():\n table_map_dict = table_map_read(table_map_file)\n tomo_file = [table_map_dict[tomo_idx] for tomo_idx in df['tomo']]\n df['tomo_file'] = tomo_file\n return df\n\n\ndef read(filename: str, table_map_file: str = None) -> pd.DataFrame:\n \"\"\"\n Opens a dynamo table file, returning a pandas DataFrame\n :param filename:\n :return: dataframe\n \"\"\"\n df = open(filename, table_map_file)\n return df\n\n\ndef new(dataframe: pd.DataFrame, filename: str):\n \"\"\"\n Writes a dynamo table file from a pandas DataFrame\n :param dataframe: pandas dataframe with headings matching the name from the dynamo table convention\n :param filename: file in which to save data from dataframe, should end in .tbl\n :return:\n \"\"\"\n # Get n rows\n n_rows = dataframe.shape[0]\n\n # Check if df has tomo_name but no tomo entry with indices, if so, fix\n if 'tomo_file' in dataframe.columns and 'tomo' not in dataframe.columns:\n tomo_names = dataframe['tomo_file'].unique()\n tomo_name_idx = {name : index for index, name in enumerate(tomo_names)}\n tomo_idx = [tomo_name_idx[name] for name in dataframe['tomo_file']]\n dataframe['tomo'] = tomo_idx\n\n # Check if tags present in dataframe, if not, make a set of linear tags\n if 'tag' not in dataframe.columns:\n tags = [x+1 for x in range(n_rows)]\n dataframe['tag'] = tags\n\n # Empty columns will be either 1 or 0, precreate these columns\n zeros = [0 for x in range(n_rows)]\n ones = [1 for x in range(n_rows)]\n\n # Initialise empty dictionary to store data\n data = {}\n\n for column_name in COLUMN_NAMES:\n if column_name in dataframe.columns:\n data[column_name] = dataframe[column_name]\n\n # Aligned value column should set to 1 otherwise alignment projects don't run properly\n elif column_name not in dataframe.columns and column_name == 'aligned_value':\n data[column_name] = ones\n\n else:\n data[column_name] = zeros\n\n # Create properly formatted dataframe to write\n table = pd.DataFrame.from_dict(data)\n\n # Prep filename\n filename = str(filename)\n if not filename.endswith('.tbl'):\n filename = filename.join('.tbl')\n\n # Write out table\n table.to_csv(filename, sep=' ', header=False, index=False)\n\n # Write out doc file if appropriate\n if 'tomo_file' in dataframe.columns:\n # Prep table file name\n table_file_name = filename.replace('.tbl', '.doc')\n\n # Get necessary info in new dataframe\n table_map = dataframe[['tomo', 'tomo_file']].drop_duplicates(subset='tomo')\n table_map.to_csv(table_file_name, sep=' ', header=False, index=False)\n\n return\n\n\ndef write(dataframe: pd.DataFrame, filename: str):\n \"\"\"\n Writes a dynamo table file from a pandas DataFrame\n :param dataframe: pandas dataframe with headings matching the name from the dynamo table convention\n :param filename: file in which to save data from dataframe, should end in .tbl\n :return:\n \"\"\"\n new(dataframe, filename)\n return\n\n\n\n\n\n\n\n\n" ]
[ [ "pandas.DataFrame.from_dict", "pandas.read_csv" ] ]
AdityaPrasadMishra/TensorflowPractice
[ "7107d9043a4d54980e2106f44c42dd2a3727dced" ]
[ "FSL - Entire Project + Report/Final Project/Code/Exp1.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 30 03:08:17 2017\n\n@author: aditya\n\"\"\"\n\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 26 12:46:25 2017\n\n@author: aditya\n\"\"\"\n\nimport math\nimport os\n\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nFLAGS = None\nMNIST_IMAGE_SIZE = 28\nMNIST_IMAGE_PIXELS =28*28\nOUTPUT_CLASSES = 10 \nBatch_Size = 100\nLEARNING_RATE = 0.01\nhiddenlayer_units =16\nexpno = \"1\"\n\ndef deepnnwithrelu(images):\n#Code boorrowed from https://github.com/tensorflow/tensorflow/blob/r1.4/tensorflow/examples/tutorials/mnist/mnist.py \n with tf.name_scope('hiddenlayer1'):\n weights = tf.Variable(\n tf.truncated_normal([MNIST_IMAGE_PIXELS, hiddenlayer_units],\n stddev=1.0 / math.sqrt(float(MNIST_IMAGE_PIXELS))),\n name='weights')\n biases = tf.Variable(tf.zeros([hiddenlayer_units]),\n name='biases')\n hidden1 = tf.nn.relu(tf.matmul(images, weights) + biases)\n # Hidden 2\n with tf.name_scope('hiddenlayer2'):\n weights = tf.Variable(\n tf.truncated_normal([hiddenlayer_units, hiddenlayer_units],\n stddev=1.0 / math.sqrt(float(hiddenlayer_units))),\n name='weights')\n biases = tf.Variable(tf.zeros([hiddenlayer_units]),\n name='biases')\n hidden2 = tf.nn.relu(tf.matmul(hidden1, weights) + biases)\n \n with tf.name_scope('hiddenlayer3'):\n weights = tf.Variable(\n tf.truncated_normal([hiddenlayer_units, hiddenlayer_units],\n stddev=1.0 / math.sqrt(float(hiddenlayer_units))),\n name='weights')\n biases = tf.Variable(tf.zeros([hiddenlayer_units]),\n name='biases')\n hidden3 = tf.nn.relu(tf.matmul(hidden2, weights) + biases)\n \n with tf.name_scope('hiddenlayer4'):\n weights = tf.Variable(\n tf.truncated_normal([hiddenlayer_units, hiddenlayer_units],\n stddev=1.0 / math.sqrt(float(hiddenlayer_units))),\n name='weights')\n biases = tf.Variable(tf.zeros([hiddenlayer_units]),\n name='biases')\n hidden4 = tf.nn.relu(tf.matmul(hidden3, weights) + biases)\n \n with tf.name_scope('hiddenlayer5'):\n weights = tf.Variable(\n tf.truncated_normal([hiddenlayer_units, hiddenlayer_units],\n stddev=1.0 / math.sqrt(float(hiddenlayer_units))),\n name='weights')\n biases = tf.Variable(tf.zeros([hiddenlayer_units]),\n name='biases')\n hidden5 = tf.nn.relu(tf.matmul(hidden4, weights) + biases)\n \n with tf.name_scope('hiddenlayer6'):\n weights = tf.Variable(\n tf.truncated_normal([hiddenlayer_units, hiddenlayer_units],\n stddev=1.0 / math.sqrt(float(hiddenlayer_units))),\n name='weights')\n biases = tf.Variable(tf.zeros([hiddenlayer_units]),\n name='biases')\n hidden6 = tf.nn.relu(tf.matmul(hidden5, weights) + biases)\n\n # Dropout - controls the complexity of the model, prevents co-adaptation of\n # features.\n\n # Map the 1024 features to 10 classes, one for each digit\n with tf.name_scope('finallayer'):\n W_fc2 = weight_variable([hiddenlayer_units, 10])\n b_fc2 = bias_variable([10])\n\n y_output = tf.matmul(hidden6, W_fc2) + b_fc2\n return y_output \n\ndef deepnnwithsigmoid(images): \n with tf.name_scope('hiddenlayer1'):\n weights = tf.Variable(\n tf.truncated_normal([MNIST_IMAGE_PIXELS, hiddenlayer_units],\n stddev=1.0 / math.sqrt(float(MNIST_IMAGE_PIXELS))),\n name='weights')\n biases = tf.Variable(tf.zeros([hiddenlayer_units]),\n name='biases')\n hidden1 = tf.nn.sigmoid(tf.matmul(images, weights) + biases)\n # Hidden 2\n with tf.name_scope('hiddenlayer2'):\n weights = tf.Variable(\n tf.truncated_normal([hiddenlayer_units, hiddenlayer_units],\n stddev=1.0 / math.sqrt(float(hiddenlayer_units))),\n name='weights')\n biases = tf.Variable(tf.zeros([hiddenlayer_units]),\n name='biases')\n hidden2 = tf.nn.sigmoid(tf.matmul(hidden1, weights) + biases)\n \n with tf.name_scope('hiddenlayer3'):\n weights = tf.Variable(\n tf.truncated_normal([hiddenlayer_units, hiddenlayer_units],\n stddev=1.0 / math.sqrt(float(hiddenlayer_units))),\n name='weights')\n biases = tf.Variable(tf.zeros([hiddenlayer_units]),\n name='biases')\n hidden3 = tf.nn.sigmoid(tf.matmul(hidden2, weights) + biases)\n \n with tf.name_scope('hiddenlayer4'):\n weights = tf.Variable(\n tf.truncated_normal([hiddenlayer_units, hiddenlayer_units],\n stddev=1.0 / math.sqrt(float(hiddenlayer_units))),\n name='weights')\n biases = tf.Variable(tf.zeros([hiddenlayer_units]),\n name='biases')\n hidden4 = tf.nn.sigmoid(tf.matmul(hidden3, weights) + biases)\n \n with tf.name_scope('hiddenlayer5'):\n weights = tf.Variable(\n tf.truncated_normal([hiddenlayer_units, hiddenlayer_units],\n stddev=1.0 / math.sqrt(float(hiddenlayer_units))),\n name='weights')\n biases = tf.Variable(tf.zeros([hiddenlayer_units]),\n name='biases')\n hidden5 = tf.nn.sigmoid(tf.matmul(hidden4, weights) + biases)\n \n with tf.name_scope('hiddenlayer6'):\n weights = tf.Variable(\n tf.truncated_normal([hiddenlayer_units, hiddenlayer_units],\n stddev=1.0 / math.sqrt(float(hiddenlayer_units))),\n name='weights')\n biases = tf.Variable(tf.zeros([hiddenlayer_units]),\n name='biases')\n hidden6 = tf.nn.sigmoid(tf.matmul(hidden5, weights) + biases)\n\n with tf.name_scope('finallayer'):\n W_fc2 = weight_variable([hiddenlayer_units, 10])\n b_fc2 = bias_variable([10])\n\n y_output = tf.matmul(hidden6, W_fc2) + b_fc2\n return y_output \n\ndef deepnnwithelu(images): \n with tf.name_scope('hiddenlayer1'):\n weights = tf.Variable(\n tf.truncated_normal([MNIST_IMAGE_PIXELS, hiddenlayer_units],\n stddev=1.0 / math.sqrt(float(MNIST_IMAGE_PIXELS))),\n name='weights')\n biases = tf.Variable(tf.zeros([hiddenlayer_units]),\n name='biases')\n hidden1 = tf.nn.elu(tf.matmul(images, weights) + biases)\n # Hidden 2\n with tf.name_scope('hiddenlayer2'):\n weights = tf.Variable(\n tf.truncated_normal([hiddenlayer_units, hiddenlayer_units],\n stddev=1.0 / math.sqrt(float(hiddenlayer_units))),\n name='weights')\n biases = tf.Variable(tf.zeros([hiddenlayer_units]),\n name='biases')\n hidden2 = tf.nn.elu(tf.matmul(hidden1, weights) + biases)\n \n with tf.name_scope('hiddenlayer3'):\n weights = tf.Variable(\n tf.truncated_normal([hiddenlayer_units, hiddenlayer_units],\n stddev=1.0 / math.sqrt(float(hiddenlayer_units))),\n name='weights')\n biases = tf.Variable(tf.zeros([hiddenlayer_units]),\n name='biases')\n hidden3 = tf.nn.elu(tf.matmul(hidden2, weights) + biases)\n \n with tf.name_scope('hiddenlayer4'):\n weights = tf.Variable(\n tf.truncated_normal([hiddenlayer_units, hiddenlayer_units],\n stddev=1.0 / math.sqrt(float(hiddenlayer_units))),\n name='weights')\n biases = tf.Variable(tf.zeros([hiddenlayer_units]),\n name='biases')\n hidden4 = tf.nn.elu(tf.matmul(hidden3, weights) + biases)\n \n with tf.name_scope('hiddenlayer5'):\n weights = tf.Variable(\n tf.truncated_normal([hiddenlayer_units, hiddenlayer_units],\n stddev=1.0 / math.sqrt(float(hiddenlayer_units))),\n name='weights')\n biases = tf.Variable(tf.zeros([hiddenlayer_units]),\n name='biases')\n hidden5 = tf.nn.elu(tf.matmul(hidden4, weights) + biases)\n \n with tf.name_scope('hiddenlayer6'):\n weights = tf.Variable(\n tf.truncated_normal([hiddenlayer_units, hiddenlayer_units],\n stddev=1.0 / math.sqrt(float(hiddenlayer_units))),\n name='weights')\n biases = tf.Variable(tf.zeros([hiddenlayer_units]),\n name='biases')\n hidden6 = tf.nn.elu(tf.matmul(hidden5, weights) + biases)\n\n with tf.name_scope('finallayer'):\n W_fc2 = weight_variable([hiddenlayer_units, 10])\n b_fc2 = bias_variable([10])\n\n y_output = tf.matmul(hidden6, W_fc2) + b_fc2\n return y_output\n\n# Code Borrowed from https://github.com/tensorflow/tensorflow/blob/r1.4/tensorflow/examples/tutorials/mnist/mnist_deep.py\ndef weight_variable(shape):\n \"\"\"weight_variable generates a weight variable of a given shape.\"\"\"\n initial = tf.truncated_normal(shape, stddev=0.1/math.sqrt(float(hiddenlayer_units)))\n return tf.Variable(initial)\n\n\ndef bias_variable(shape):\n \"\"\"bias_variable generates a bias variable of a given shape.\"\"\"\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\n\ndef appstart(stri):\n # Import data\n mnist = input_data.read_data_sets(\"../Data/MNIST_data\", one_hot=True)\n\n # Create the model\n x = tf.placeholder(tf.float32, [None, 784])\n\n # Define loss and optimizer\n y_ = tf.placeholder(tf.float32, [None, 10])\n\n # Build the graph for the deep net\n if(stri==\"relu\"):\n y_output = deepnnwithrelu(x)\n elif(stri==\"elu\"):\n y_output = deepnnwithelu(x)\n else:\n y_output = deepnnwithsigmoid(x)\n#Code Borrowed from https://github.com/tensorflow/tensorflow/blob/r1.4/tensorflow/examples/tutorials/mnist/mnist_deep.py \n with tf.name_scope('loss'):\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_,\n logits=y_output)\n cross_entropy = tf.reduce_mean(cross_entropy)\n\n with tf.name_scope('adam_optimizer'):\n train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\n\n with tf.name_scope('accuracy'):\n correct_prediction = tf.equal(tf.argmax(y_output, 1), tf.argmax(y_, 1))\n correct_prediction = tf.cast(correct_prediction, tf.float32)\n accuracy = tf.reduce_mean(correct_prediction)\n\n graph_location = \"tfgraphs/\"+expno\n print('Saving graph to: %s' % graph_location)\n train_writer = tf.summary.FileWriter(graph_location)\n train_writer.add_graph(tf.get_default_graph())\n resultarray =[]\n iterarray=[]\n accarray=[]\n testaccarray = []\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for i in range(20000):\n batch = mnist.train.next_batch(50)\n if i % 100 == 0:\n train_accuracy = accuracy.eval(feed_dict={\n x: batch[0], y_: batch[1]})\n testaccuracy = accuracy.eval(feed_dict={\n x: mnist.test.images, y_: mnist.test.labels})\n #print('step %d, training accuracy %g' % (i, train_accuracy))\n #print('test accuracy %g' %testaccuracy)\n iterarray.append(i)\n accarray.append(train_accuracy)\n testaccarray.append(testaccuracy)\n train_step.run(feed_dict={x: batch[0], y_: batch[1]})\n resultarray.append(iterarray)\n resultarray.append(accarray)\n resultarray.append(testaccarray)\n return resultarray \n\ndef progstart():\n rarray =[]\n rarray.append(appstart(\"sigmoid\"))\n rarray.append(appstart(\"relu\"))\n rarray.append(appstart(\"elu\"))\n if not os.path.exists('figures'):\n os.makedirs('figures')\n fig1 = plt.figure()\n axes1 = fig1.add_axes([0.1,0.1,0.8,0.8])\n axes1.plot(rarray[0][0],rarray[0][1],'r')\n axes1.plot(rarray[0][0],rarray[1][1],'b')\n axes1.plot(rarray[0][0],rarray[2][1],'g')\n \n axes1.set_xlabel('Train Iterations')\n axes1.set_ylabel('Train accuracy')\n fig1.savefig('figures/'+expno+'_trainAccuracy.png')\n \n fig2 = plt.figure()\n axes2 = fig2.add_axes([0.1,0.1,0.8,0.8])\n axes2.plot(rarray[0][0],rarray[0][2],'r')\n axes2.plot(rarray[0][0],rarray[1][2],'b')\n axes2.plot(rarray[0][0],rarray[2][2],'g')\n \n axes2.set_xlabel('Train Iterations')\n axes2.set_ylabel('Test accuracy')\n fig2.savefig('figures/'+expno+'_testAccuracy.png')\n plt.plot()\n \nprogstart()\n" ]
[ [ "tensorflow.nn.softmax_cross_entropy_with_logits", "tensorflow.zeros", "tensorflow.train.AdamOptimizer", "tensorflow.get_default_graph", "tensorflow.argmax", "tensorflow.examples.tutorials.mnist.input_data.read_data_sets", "tensorflow.Variable", "matplotlib.pyplot.plot", "tensorflow.Session", "matplotlib.pyplot.figure", "tensorflow.matmul", "tensorflow.constant", "tensorflow.placeholder", "tensorflow.name_scope", "tensorflow.summary.FileWriter", "tensorflow.reduce_mean", "tensorflow.global_variables_initializer", "tensorflow.cast" ] ]
ctuning/inference_results_v1.1
[ "d9176eca28fcf6d7a05ccb97994362a76a1eb5ab", "d9176eca28fcf6d7a05ccb97994362a76a1eb5ab" ]
[ "closed/FuriosaAI/code/quantization/mlperf_evaluation/python/ort_quantization.py", "open/Dell/code/ssd-mobilenet/tensorrt/calibrator.py" ]
[ "import argparse\n\nimport cv2\nimport numpy as np\n\nfrom onnxruntime.quantization import quantize_static, CalibrationDataReader, QuantType\nfrom onnxruntime.quantization.calibrate import CalibrationMethod\nfrom onnxruntime.quantization.quant_utils import QuantFormat\n\nfrom dataset import pre_process_vgg\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"ONNXRuntime quantization tool\")\n parser.add_argument(\"--input\", \"-i\", type=str)\n parser.add_argument(\"--output\", \"-o\", type=str)\n parser.add_argument(\"--dataset\", \"-d\", type=str)\n parser.add_argument(\"--entropy-calibration\", default=False, action=\"store_true\")\n return parser.parse_args()\n\n\n# https://github.com/microsoft/onnxruntime/blob/master/onnxruntime/python/tools/quantization/notebooks/imagenet_v2/mobilenet.ipynb\ndef preprocess_image(image_path, height, width, channels=3):\n image = cv2.imread(image_path)\n image_data = pre_process_vgg(image, dims=[height, width, channels], need_transpose=True)\n image_data = np.expand_dims(image_data, axis=0)\n return image_data\n\n\ndef preprocess_func(images_folder, height, width, size_limit=0):\n unconcatenated_batch_data = []\n import pathlib\n\n image_filepathes = [str(path) for path in pathlib.Path(images_folder).glob(\"*.JPEG\")]\n for image_filepath in image_filepathes:\n # image_filepath = images_folder + '/' + image_name\n image_data = preprocess_image(image_filepath, height, width)\n unconcatenated_batch_data.append(image_data)\n batch_data = np.concatenate(np.expand_dims(unconcatenated_batch_data, axis=0), axis=0)\n return batch_data\n\n\nimage_height = 224\nimage_width = 224\n\n\nclass ResNetDataReader(CalibrationDataReader):\n def __init__(self, calibration_image_folder):\n self.image_folder = calibration_image_folder\n self.preprocess_flag = True\n self.enum_data_dicts = []\n self.datasize = 0\n\n def get_next(self):\n if self.preprocess_flag:\n self.preprocess_flag = False\n nhwc_data_list = preprocess_func(\n self.image_folder, image_height, image_width, size_limit=0\n )\n self.datasize = len(nhwc_data_list)\n self.enum_data_dicts = iter(\n [{\"input_tensor:0\": nhwc_data} for nhwc_data in nhwc_data_list]\n )\n return next(self.enum_data_dicts, None)\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n dr = ResNetDataReader(args.dataset)\n\n if args.entropy_calibration:\n method = CalibrationMethod.Entropy\n else:\n method = CalibrationMethod.MinMax\n\n quantize_static(\n args.input,\n args.output,\n dr,\n quant_format=QuantFormat.QDQ,\n per_channel=True,\n calibrate_method=method,\n )\n", "# Copyright (c) 2021, NVIDIA CORPORATION. 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\nimport numpy as np\nimport os\nimport pycuda.driver as cuda\nimport pycuda.autoinit\nimport tensorrt as trt\n\n\nclass SSDMobileNetEntropyCalibrator(trt.IInt8EntropyCalibrator2):\n def __init__(self, calib_batch_size=1, calib_max_batches=500, force_calibration=False,\n cache_file=\"code/ssd-mobilenet/tensorrt/calibrator.cache\",\n image_dir=\"build/preprocessed_data/coco/train2017/SSDMobileNet/fp32\", calib_data_map=\"data_maps/coco/cal_map.txt\"):\n # Whenever you specify a custom constructor for a TensorRT class,\n # you MUST call the constructor of the parent explicitly.\n trt.IInt8EntropyCalibrator2.__init__(self)\n\n self.calib_batch_size = calib_batch_size\n self.calib_max_batches = calib_max_batches\n self.force_calibration = force_calibration\n self.current_idx = 0\n self.cache_file = cache_file\n\n image_list = []\n with open(calib_data_map) as f:\n for line in f:\n image_list.append(line.strip())\n\n self.batches = np.stack([np.load(os.path.join(image_dir, file_name + \".npy\")) for file_name in image_list])\n\n IMAGE_C, IMAGE_H, IMAGE_W = (3, 300, 300)\n self.device_input = cuda.mem_alloc(self.calib_batch_size * IMAGE_C * IMAGE_H * IMAGE_W * 4)\n\n # If there is a cache, use it instead of calibrating again. Otherwise, implicitly return None.\n if not self.force_calibration and os.path.exists(self.cache_file):\n with open(self.cache_file, \"rb\") as f:\n self.cache = f.read()\n else:\n self.cache = None\n\n def get_batch_size(self):\n return self.calib_batch_size\n\n # TensorRT passes along the names of the engine bindings to the get_batch function.\n # You don't necessarily have to use them, but they can be useful to understand the order of\n # the inputs. The bindings list is expected to have the same ordering as 'names'.\n def get_batch(self, names):\n if self.current_idx < self.calib_max_batches:\n cuda.memcpy_htod(self.device_input, np.ascontiguousarray(self.batches[self.current_idx:self.current_idx + self.calib_batch_size]))\n self.current_idx += 1\n return [int(self.device_input)]\n else:\n # When we're out of batches, we return either [] or None.\n # This signals to TensorRT that there is no calibration data remaining.\n return None\n\n def read_calibration_cache(self):\n return self.cache\n\n def write_calibration_cache(self, cache):\n with open(self.cache_file, \"wb\") as f:\n f.write(cache)\n\n def clear_cache(self):\n self.cache = None\n\n def __del__(self):\n self.device_input.free()\n" ]
[ [ "numpy.expand_dims" ], [ "numpy.ascontiguousarray" ] ]
WifiSpy/models
[ "9b17d796234b72c93f1d23aa3026657000894a1d" ]
[ "official/resnet/keras/keras_benchmark.py" ]
[ "# Copyright 2018 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\"\"\"Executes Keras benchmarks and accuracy tests.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nfrom absl import flags\nfrom absl.testing import flagsaver\nimport tensorflow as tf # pylint: disable=g-bad-import-order\n\nFLAGS = flags.FLAGS\n\n\nclass KerasBenchmark(tf.test.Benchmark):\n \"\"\"Base benchmark class with methods to simplify testing.\"\"\"\n local_flags = None\n\n def __init__(self, output_dir=None, default_flags=None, flag_methods=None):\n self.output_dir = output_dir\n self.default_flags = default_flags or {}\n self.flag_methods = flag_methods or {}\n\n if not output_dir:\n output_dir = '/tmp/'\n\n def _get_model_dir(self, folder_name):\n return os.path.join(self.output_dir, folder_name)\n\n def _setup(self):\n \"\"\"Sets up and resets flags before each test.\"\"\"\n tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.DEBUG)\n if KerasBenchmark.local_flags is None:\n for flag_method in self.flag_methods:\n flag_method()\n # Loads flags to get defaults to then override. List cannot be empty.\n flags.FLAGS(['foo'])\n # Overrides flag values with defaults for the class of tests.\n for k, v in self.default_flags.items():\n setattr(FLAGS, k, v)\n saved_flag_values = flagsaver.save_flag_values()\n KerasBenchmark.local_flags = saved_flag_values\n else:\n flagsaver.restore_flag_values(KerasBenchmark.local_flags)\n\n def _report_benchmark(self,\n stats,\n wall_time_sec,\n top_1_max=None,\n top_1_min=None,\n log_steps=None,\n total_batch_size=None,\n warmup=1):\n \"\"\"Report benchmark results by writing to local protobuf file.\n\n Args:\n stats: dict returned from keras models with known entries.\n wall_time_sec: the during of the benchmark execution in seconds\n top_1_max: highest passing level for top_1 accuracy.\n top_1_min: lowest passing level for top_1 accuracy.\n log_steps: How often the log was created for stats['step_timestamp_log'].\n total_batch_size: Global batch-size.\n warmup: number of entries in stats['step_timestamp_log'] to ignore.\n \"\"\"\n\n metrics = []\n if 'accuracy_top_1' in stats:\n metrics.append({'name': 'accuracy_top_1',\n 'value': stats['accuracy_top_1'],\n 'min_value': top_1_min,\n 'max_value': top_1_max})\n metrics.append({'name': 'top_1_train_accuracy',\n 'value': stats['training_accuracy_top_1']})\n\n if (warmup and 'step_timestamp_log' in stats and\n len(stats['step_timestamp_log']) > warmup):\n # first entry in the time_log is start of step 1. The rest of the\n # entries are the end of each step recorded\n time_log = stats['step_timestamp_log']\n elapsed = time_log[-1].timestamp - time_log[warmup].timestamp\n num_examples = (\n total_batch_size * log_steps * (len(time_log) - warmup - 1))\n examples_per_sec = num_examples / elapsed\n metrics.append({'name': 'exp_per_second',\n 'value': examples_per_sec})\n\n if 'avg_exp_per_second' in stats:\n metrics.append({'name': 'avg_exp_per_second',\n 'value': stats['avg_exp_per_second']})\n\n self.report_benchmark(iters=-1, wall_time=wall_time_sec, metrics=metrics)\n" ]
[ [ "tensorflow.compat.v1.logging.set_verbosity" ] ]
mishinma/alibi-detect
[ "9cc33902ed5f278d8efbcd9f58bf6ec5496be818" ]
[ "integrations/adserver/adserver/__main__.py" ]
[ "import argparse\n\nimport ceserver\nimport tensorflow as tf\n\ntf.keras.backend.clear_session()\n\nfrom .model import AlibiDetectModel\n\nDEFAULT_MODEL_NAME = \"model\"\n\nparser = argparse.ArgumentParser(parents=[ceserver.server.parser])\nparser.add_argument('--model_name', default=DEFAULT_MODEL_NAME,\n help='The name that the model is served under.')\nparser.add_argument('--storage_uri', required=True,\n help='A URI pointer to the model')\nargs, _ = parser.parse_known_args()\n\nif __name__ == \"__main__\":\n model = AlibiDetectModel(args.model_name, args.storage_uri)\n ceserver.CEServer().start(model)\n" ]
[ [ "tensorflow.keras.backend.clear_session" ] ]
Dih5/zadeh
[ "3cc0d2a4803a77d8d4d0a90c0012eea0397ee9ca" ]
[ "zadeh/tune.py" ]
[ "from .fis import FIS\n\nimport numpy as np\n\ntry:\n import pandas as pd\nexcept ImportError:\n pd = None\n\ntry:\n from sklearn.model_selection import GridSearchCV\nexcept ImportError:\n GridSearchCV = None\n\n\ndef _get_vars(fis):\n \"\"\"Get an encoded version of the parameters of the fuzzy sets in a FIS\"\"\"\n for variable in fis.variables:\n for value_name, value in variable.values.items():\n for par, default in value._get_description().items():\n if par != \"type\":\n yield \"var_\" + variable.name + \"_\" + value_name + \"_\" + par, default\n\n # Same for target\n for variable in [fis.target]: # For symmetry\n for value_name, value in variable.values.items():\n for par, default in value._get_description().items():\n if par != \"type\":\n yield \"target_\" + variable.name + \"_\" + value_name + \"_\" + par, default\n\n\ndef _set_vars(fis, kwargs):\n \"\"\"Return a modified version of the FIS, setting the changes in the parameters described by kwargs\"\"\"\n description = fis._get_description()\n positions = {variable[\"name\"]: i for i, variable in enumerate(description[\"variables\"])}\n for code, parameter_value in kwargs.items():\n if code.startswith(\"var_\"):\n _, variable_name, fuzzy_value, parameter = code.split(\"_\")\n description[\"variables\"][positions[variable_name]][\"values\"][fuzzy_value][parameter] = parameter_value\n elif code.startswith(\"target_\"):\n _, _, fuzzy_value, parameter = code.split(\"_\")\n description[\"target\"][\"values\"][fuzzy_value][parameter] = parameter_value\n elif code in [\"defuzzification\"]:\n description[code] = parameter_value\n else:\n raise ValueError(\"Parameter not supported: %s\" % code)\n\n return FIS._from_description(description)\n\n\nclass ParametrizedFIS:\n \"\"\"A parametrizable Fuzzy Inference System with a scikit-learn-like interface\"\"\"\n\n def __init__(self, fis, defuzzification=\"centroid\", **kwargs):\n self.fis = fis\n\n self.defuzzification = defuzzification\n\n for parameter, value in _get_vars(fis):\n setattr(self, parameter, kwargs.get(parameter, value))\n\n def get_params(self, deep=True):\n \"\"\"Get the parameters in a sklearn-consistent interface\"\"\"\n return {\"fis\": self.fis,\n \"defuzzification\": self.defuzzification,\n **{parameter: getattr(self, parameter) for parameter, _ in _get_vars(self.fis)}}\n\n def set_params(self, **parameters):\n \"\"\"Set the parameters in a sklearn-consistent interface\"\"\"\n for parameter, value in parameters.items():\n setattr(self, parameter, value)\n return self\n\n def fit(self, X=None, y=None):\n \"\"\"'Fit' the model (freeze the attributes and compile if available)\"\"\"\n self.fis_ = _set_vars(self.fis, {parameter: getattr(self, parameter) for parameter, _ in _get_vars(self.fis)})\n self.fis_.defuzzification = self.defuzzification\n\n try:\n self.fis_ = self.fis_.compile()\n except Exception:\n pass\n\n return self\n\n def predict(self, X):\n \"\"\"A sklearn-like predict method\"\"\"\n return self.fis_.batch_predict(X)\n\n\nclass TrivialSplitter:\n \"\"\"Splitter with single split no training data and full test data\"\"\"\n\n def __init__(self):\n pass\n\n def split(self, X, y=None, groups=None):\n yield np.asarray([], dtype=int), np.arange(0, len(X))\n\n def get_n_splits(self, X, y=None, groups=None):\n return 1\n\n\nclass FuzzyGridTune:\n \"\"\"An exhaustive FIS tuner\"\"\"\n\n def __init__(self, fis, params, scoring=\"neg_root_mean_squared_error\", n_jobs=None):\n \"\"\"\n\n Args:\n fis (FIS): The Fuzzy Inference System to tune\n params (dict of str to list): A mapping from encoded parameters to the list of values to explore.\n scoring (str): The metric used for scoring. Must be one of sklearn's regression scorings.\n n_jobs (int): Number of jobs to run in parallel.\n\n \"\"\"\n # Grid parameter tuning\n if GridSearchCV is None:\n raise ModuleNotFoundError(\"scikit-learn is required for model tuning\")\n self.fis = fis\n self.cv = GridSearchCV(ParametrizedFIS(fis),\n params,\n scoring=scoring,\n cv=TrivialSplitter(),\n refit=False,\n n_jobs=n_jobs\n )\n\n def fit(self, X, y=None):\n \"\"\"\n\n Args:\n X (2D array-like): An object suitable for FIS.batch_predict.\n y (1D array-like): An array with true values. If None, but X is a DataFrame, the values are extracted from\n there.\n\n Returns:\n\n \"\"\"\n # Try to extract y if a single dataframe is provided\n if y is None and pd is not None and isinstance(X, pd.DataFrame):\n y = X[self.fis.target.name]\n\n self.cv.fit(X, y)\n\n self.best_params_ = self.cv.best_params_\n self.results = self.cv.cv_results_\n self.tuned_fis_ = _set_vars(self.fis, self.cv.best_params_)\n" ]
[ [ "numpy.asarray" ] ]
abdmoh123/tremor-predictor
[ "4378024cc20af23a01195cf76f3268087f6ed785" ]
[ "predict_all_data.py" ]
[ "# libraries imported\nimport os\nimport pathlib\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.font_manager import FontProperties\n\n# uses predict folder code to run predictor on entire folders\nfrom predict_folder import predict_dir\n\n\ndef predict_dirs(model_type, target_prediction):\n directory_name = str(pathlib.Path(__file__).parent.resolve()) + \"/data/\"\n # list holding all folders to use\n folder_names = [\n \"Novice Pointing\",\n \"Novice Tracing\",\n \"Surgeon Pointing\",\n \"Surgeon Tracing\"\n ]\n\n # finds the directories\n directories = []\n for folder_name in folder_names:\n os.fsencode(directory_name + folder_name + \"/\")\n\n # puts all txt files' names in a list\n file_names = []\n for directory in directories:\n for file in os.listdir(directory):\n file_names.append(os.fsdecode(file))\n\n if model_type == \"SVM\":\n C_parameters = []\n epsilon_parameters = []\n elif model_type == \"Random Forest\":\n num_trees = []\n\n all_r2 = []\n all_tremor_r2 = []\n all_rmse = []\n all_tremor_rmse = []\n all_training_times = []\n all_prediction_times = []\n # runs the prediction code for each folder\n for folder_name in folder_names:\n [hyperparameters, r2_scores, tremor_r2_scores, rmses, tremor_rmses, training_times, prediction_times] \\\n = predict_dir(directory_name + folder_name, model_type, target_prediction)\n\n if model_type == \"SVM\":\n C_parameters.extend(hyperparameters[:2])\n epsilon_parameters.extend(hyperparameters[2:])\n elif model_type == \"Random Forest\":\n num_trees.extend(hyperparameters)\n\n all_r2.append(r2_scores)\n all_tremor_r2.append(tremor_r2_scores)\n all_rmse.append(rmses)\n all_tremor_rmse.append(tremor_rmses)\n all_training_times.append(training_times)\n all_prediction_times.append(prediction_times)\n\n if model_type == \"SVM\":\n maxmin_hyperparameters = [\n np.max(C_parameters), np.min(C_parameters),\n np.max(epsilon_parameters), np.min(epsilon_parameters)\n ]\n print(\"\\nHyperparameters of the model [C_max, C_min, epsilon_max, epsilon_min]:\", maxmin_hyperparameters)\n elif model_type == \"Random Forest\":\n maxmin_hyperparameters = [np.max(num_trees), np.min(num_trees)]\n print(\"\\nHyperparameters of the model [n_estimators_max, n_estimators_min]:\", maxmin_hyperparameters)\n # prints the average metrics for all datasets\n print(\n \"\\nAverage R2 score of the model:\", str(np.mean(all_r2)) + \"%\",\n \"\\nAverage R2 score of the tremor component:\", str(np.mean(all_tremor_r2)) + \"%\",\n \"\\nAverage RMS error of the model:\", str(np.mean(all_rmse)) + \"mm\",\n \"\\nAverage RMS error of the tremor component:\", str(np.mean(all_tremor_rmse)) + \"mm\",\n \"\\nAverage time taken to train:\", str(np.mean(all_training_times)) + \"s\",\n \"\\nAverage time taken to make a prediction:\", str(np.mean(all_prediction_times)) + \"s\"\n )\n\n fig, axes = plt.subplots(2, figsize=(10, 10))\n # bar chart properties\n bar_width = 0.1\n labels = folder_names\n x_axis = np.arange(len(labels))\n\n # data for plotting bar chart\n bar_xr2 = []\n bar_yr2 = []\n bar_zr2 = []\n bar_xtremor_r2 = []\n bar_ytremor_r2 = []\n bar_ztremor_r2 = []\n bar_training_times = np.round(np.multiply(all_training_times, 1000), 2)\n bar_xpredict_times = []\n bar_ypredict_times = []\n bar_zpredict_times = []\n # formats the lists above for use in generating bars in the chart\n for i in range(len(folder_names)):\n bar_xr2.append(np.round(all_r2[i][0]))\n bar_yr2.append(np.round(all_r2[i][1]))\n bar_zr2.append(np.round(all_r2[i][2]))\n bar_xtremor_r2.append(np.round(all_tremor_r2[i][0]))\n bar_ytremor_r2.append(np.round(all_tremor_r2[i][1]))\n bar_ztremor_r2.append(np.round(all_tremor_r2[i][2]))\n bar_xpredict_times.append(round(1000 * all_prediction_times[i][0], 2))\n bar_ypredict_times.append(round(1000 * all_prediction_times[i][1], 2))\n bar_zpredict_times.append(round(1000 * all_prediction_times[i][2], 2))\n\n # bars for each result\n bar1 = axes[0].bar(x_axis - (5 * bar_width / 2), bar_xr2, width=bar_width, label=\"R2 (X)\")\n bar2 = axes[0].bar(x_axis - (3 * bar_width / 2), bar_yr2, width=bar_width, label=\"R2 (Y)\")\n bar3 = axes[0].bar(x_axis - (bar_width / 2), bar_zr2, width=bar_width, label=\"R2 (Z)\")\n bar4 = axes[0].bar(x_axis + (bar_width / 2), bar_xtremor_r2, width=bar_width, label=\"Tremor R2 (X)\")\n bar5 = axes[0].bar(x_axis + (3 * bar_width / 2), bar_ytremor_r2, width=bar_width, label=\"Tremor R2 (Y)\")\n bar6 = axes[0].bar(x_axis + (5 * bar_width / 2), bar_ztremor_r2, width=bar_width, label=\"Tremor R2 (Z)\")\n bar7 = axes[1].bar(x_axis - (3 * bar_width / 2), bar_training_times, width=bar_width, label=\"Training time\")\n bar8 = axes[1].bar(x_axis - (bar_width / 2), bar_xpredict_times, width=bar_width, label=\"Prediction time (X)\")\n bar9 = axes[1].bar(x_axis + (bar_width / 2), bar_ypredict_times, width=bar_width, label=\"Prediction time (Y)\")\n bar10 = axes[1].bar(x_axis + (3 * bar_width / 2), bar_zpredict_times, width=bar_width, label=\"Prediction time (Z)\")\n # displays bar value above the bar\n axes[0].bar_label(bar1)\n axes[0].bar_label(bar2)\n axes[0].bar_label(bar3)\n axes[0].bar_label(bar4)\n axes[0].bar_label(bar5)\n axes[0].bar_label(bar6)\n axes[1].bar_label(bar7)\n axes[1].bar_label(bar8)\n axes[1].bar_label(bar9)\n axes[1].bar_label(bar10)\n\n # axis labels + title\n axes[0].set_title(\"Accuracy\", fontweight=\"bold\")\n axes[0].set_xlabel(\"R2 score metrics\")\n axes[0].set_ylabel(\"Accuracy (%)\")\n axes[1].set_title(\"Speed\", fontweight=\"bold\")\n axes[1].set_xlabel(\"Time metrics\")\n axes[1].set_ylabel(\"Time (ms)\")\n # setting ticks and tick params\n axes[0].set_xticks(x_axis)\n axes[0].set_xticklabels(labels)\n axes[1].set_xticks(x_axis)\n axes[1].set_xticklabels(labels)\n axes[0].tick_params(axis=\"x\", which=\"both\")\n axes[0].tick_params(axis=\"y\", which=\"both\")\n axes[1].tick_params(axis=\"x\", which=\"both\")\n axes[1].tick_params(axis=\"y\", which=\"both\")\n\n # legend\n font_prop = FontProperties()\n font_prop.set_size(\"small\") # font size of the legend content\n legend1 = axes[0].legend(prop=font_prop)\n legend2 = axes[1].legend(prop=font_prop)\n # font size of the legend title\n plt.setp(legend1.get_title(), fontsize=\"medium\")\n plt.setp(legend2.get_title(), fontsize=\"medium\")\n # figure title\n fig.suptitle((model + \" results based on multiple datasets\"), fontweight=\"bold\", fontsize=\"x-large\")\n\n plt.show()\n\n\nif __name__ == '__main__':\n # choose what ML regression algorithm to use\n # model = \"SVM\"\n model = \"Random Forest\"\n\n # choose what output to predict\n # prediction_target = \"voluntary motion\"\n prediction_target = \"tremor component\"\n\n predict_dirs(model, prediction_target)\n" ]
[ [ "numpy.max", "matplotlib.font_manager.FontProperties", "numpy.round", "numpy.min", "matplotlib.pyplot.subplots", "numpy.mean", "numpy.multiply", "matplotlib.pyplot.show" ] ]
buddhi1/CIFAR-10-project
[ "d80821fa7db21be130c71de2f20d49bdcc5561b6" ]
[ "utils.py" ]
[ "\nfrom sklearn.metrics import roc_curve, auc\nimport numpy as np\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nimport json\nimport pandas as pd\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\nfrom pylab import rcParams\n# rcParams['figure.figsize'] = 20, 20\nrcParams['figure.figsize'] = 15, 15\n\ndef results(x_true, x_pred, y_true, y_pred, classes, params, path=None, name=None):\n\n if path is None and name is None:\n path = f'models/{params[\"model_type\"]}/{params[\"exp_name\"]}/'\n name = f'{params[\"model_type\"]}-{params[\"exp_name\"]}'\n\n\n # Create folder\n Path(path).mkdir(parents=True, exist_ok=True)\n\n # Log\n log_file = open(f'{path}log.json', \"w\")\n json.dump(params, log_file, indent=4)\n\n # Train results\n x_pred_ = x_pred.argmax(dim=1)\n\n #classification report\n report = classification_report(x_true, x_pred_, target_names=classes,output_dict=True)\n df_classification_report = pd.DataFrame(report).transpose()\n accuracy_report = df_classification_report.tail(3)\n accuracy_report.to_csv(path+'train_accuracy_report.csv')\n df_classification_report.drop(df_classification_report.tail(3).index, inplace=True)\n df_classification_report = df_classification_report.sort_values(by=['f1-score'], ascending=False)\n df_classification_report.to_csv(path+'train_classification_report.csv')\n\n # AUC curve\n x_true_ohe = np.zeros((len(x_pred), len(classes)))\n for idx, lbl in enumerate(x_true):\n x_true_ohe[idx][lbl] = 1\n\n x_pred = x_pred.detach().numpy()\n plot_multiclass_roc(x_true_ohe,x_pred, classes=classes, path=path, name='train-'+name)\n\n # Confusion matrix\n cm = confusion_matrix(x_true, x_pred_)\n plot_confusion_matrix(cm, classes, path=path, name='train-'+name)\n\n\n\n # Test results\n y_pred_ = y_pred.argmax(dim=1)\n\n #classification report\n report = classification_report(y_true, y_pred_, target_names=classes,output_dict=True)\n df_classification_report = pd.DataFrame(report).transpose()\n accuracy_report = df_classification_report.tail(3)\n accuracy_report.to_csv(path+'test-accuracy_report.csv')\n df_classification_report.drop(df_classification_report.tail(3).index, inplace=True)\n df_classification_report = df_classification_report.sort_values(by=['f1-score'], ascending=False)\n df_classification_report.to_csv(path+'test-classification_report.csv')\n\n # AUC curve\n y_true_ohe = np.zeros((len(y_pred), len(classes)))\n for idx, lbl in enumerate(y_true):\n y_true_ohe[idx][lbl] = 1\n\n y_pred = y_pred.detach().numpy()\n plot_multiclass_roc(y_true_ohe,y_pred, classes=classes, path=path, name='test-'+name)\n\n # Confusion matrix\n cm = confusion_matrix(y_true, y_pred_)\n plot_confusion_matrix(cm, classes, path=path, name='test-'+name)\n # plot_confusion_matrix(cm, list(range(len(classes))), path=path, name='test-'+name)\n\ndef get_color(idx):\n if idx < 10:\n return '#f500dc'\n elif idx < 20:\n return '#00f500'\n elif idx < 30:\n return '#00e0f5'\n elif idx < 40:\n return '#000cf5'\n elif idx < 50:\n return '#f5e900'\n elif idx < 60:\n return '#f58f00'\n else:\n return '#f50000'\n\n\ndef plot_multiclass_roc(y_true, y_pred, classes, path, name):\n n_classes = len(classes)\n lw=1\n\n items = []\n labels = ['item_id', 'fpr', 'tpr', 'roc_auc']\n\n for i in range(n_classes):\n fpr, tpr, _ = roc_curve(y_true[:, i], y_pred[:, i])\n roc_auc = auc(fpr, tpr)\n items.append((i, fpr, tpr, roc_auc))\n\n df = pd.DataFrame.from_records(items, columns=labels)\n df = df.sort_values(by=['roc_auc'], ascending=False)\n for idx, (_, row) in enumerate(df.iterrows()):\n color = get_color(idx)\n plt.plot(row['fpr'], row['tpr'], lw=lw, color=color,\n label=f'{classes[row[\"item_id\"]]} (area = {row[\"roc_auc\"]:.2f})')\n\n plt.plot([0, 1], [0, 1], 'k--', lw=lw)\n plt.xlim([-0.05, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title(f'Receiver operating characteristic for {name}')\n plt.legend(loc='lower right',\n fancybox=True, shadow=True, ncol=3, prop={'size': 12})\n plt.savefig(f'{path}{name}-roc.png', bbox_inches='tight')\n plt.clf()\n plt.close()\n\ndef plot_confusion_matrix(cm, classes, path, name, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar(shrink=0.75)\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=90)\n plt.yticks(tick_marks, classes)\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.title(f'Confusion Matrix for {name}')\n plt.savefig(f'{path}{name}-cm.png', bbox_inches='tight')\n plt.clf()\n plt.close()" ]
[ [ "sklearn.metrics.confusion_matrix", "matplotlib.pyplot.xlim", "matplotlib.pyplot.imshow", "matplotlib.pyplot.xticks", "pandas.DataFrame.from_records", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.savefig", "pandas.DataFrame", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.title", "matplotlib.pyplot.close", "matplotlib.pyplot.yticks", "matplotlib.pyplot.clf", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.ylim", "matplotlib.pyplot.plot", "matplotlib.pyplot.legend", "sklearn.metrics.classification_report", "matplotlib.pyplot.ylabel", "sklearn.metrics.auc", "sklearn.metrics.roc_curve" ] ]
qzzhang/kb_SPAdes
[ "16592d6f56f2ac2d87cb32c59b552073fa917e59" ]
[ "lib/kb_SPAdes/kb_SPAdesImpl.py" ]
[ "# -*- coding: utf-8 -*-\n#BEGIN_HEADER\n# The header block is where all import statements should live\nfrom __future__ import print_function\nimport os\nimport re\nimport uuid\nimport requests\nimport json\nimport psutil\nimport subprocess\nimport numpy as np\nimport yaml\nimport time\nfrom pprint import pformat\n\nfrom installed_clients.WorkspaceClient import Workspace\nfrom installed_clients.ReadsUtilsClient import ReadsUtils # @IgnorePep8\nfrom installed_clients.baseclient import ServerError\nfrom installed_clients.AssemblyUtilClient import AssemblyUtil\nfrom installed_clients.KBaseReportClient import KBaseReport\nfrom installed_clients.kb_quastClient import kb_quast\nfrom installed_clients.kb_ea_utilsClient import kb_ea_utils\n\nfrom kb_SPAdes.utils.spades_assembler import SPAdesAssembler\n\n\nclass ShockException(Exception):\n pass\n\n#END_HEADER\n\n\nclass kb_SPAdes:\n '''\n Module Name:\n kb_SPAdes\n\n Module Description:\n A KBase module: kb_SPAdes\nA wrapper for the SPAdes assembler with hybrid features supported.\nhttp://bioinf.spbau.ru/spades\n\nAlways runs in careful mode.\nRuns 3 threads / CPU.\nMaximum memory use is set to available memory - 1G.\nAutodetection is used for the PHRED quality offset and k-mer sizes.\nA coverage cutoff is not specified.\n '''\n\n ######## WARNING FOR GEVENT USERS ####### noqa\n # Since asynchronous IO can lead to methods - even the same method -\n # interrupting each other, you must be *very* careful when using global\n # state. A method could easily clobber the state set by another while\n # the latter method is running.\n ######################################### noqa\n VERSION = \"1.2.0\"\n GIT_URL = \"https://github.com/qzzhang/kb_SPAdes\"\n GIT_COMMIT_HASH = \"5b7e88d6993728abc26c93cfef780ee7feb16c63\"\n\n #BEGIN_CLASS_HEADER\n # Class variables and functions can be defined in this block\n DISABLE_SPADES_OUTPUT = False # should be False in production\n\n PARAM_IN_WS = 'workspace_name'\n PARAM_IN_LIB = 'read_libraries'\n PARAM_IN_CS_NAME = 'output_contigset_name'\n PARAM_IN_DNA_SOURCE = 'dna_source'\n PARAM_IN_SINGLE_CELL = 'single_cell'\n PARAM_IN_METAGENOME = 'metagenomic'\n PARAM_IN_PLASMID = 'plasmid'\n PARAM_IN_MIN_CONTIG_LENGTH = 'min_contig_length'\n PARAM_IN_KMER_SIZES = 'kmer_sizes'\n PARAM_IN_SKIP_ERR_CORRECT = 'skip_error_correction'\n\n INVALID_WS_OBJ_NAME_RE = re.compile('[^\\\\w\\\\|._-]')\n INVALID_WS_NAME_RE = re.compile('[^\\\\w:._-]')\n\n THREADS_PER_CORE = 3\n MAX_THREADS = 64 # per email thread with Anton Korobeynikov\n MAX_THREADS_META = 128 # Increase threads for metagenomic assemblies\n MEMORY_OFFSET_GB = 1 # 1GB\n MIN_MEMORY_GB = 5\n MAX_MEMORY_GB_SPADES = 500\n MAX_MEMORY_GB_META_SPADES = 1000\n GB = 1000000000\n\n URL_WS = 'workspace-url'\n URL_SHOCK = 'shock-url'\n URL_KB_END = 'kbase-endpoint'\n\n TRUE = 'true'\n FALSE = 'false'\n\n def log(self, message, prefix_newline=False):\n print(('\\n' if prefix_newline else '') +\n str(time.time()) + ': ' + str(message))\n\n def check_shock_response(self, response, errtxt):\n if not response.ok:\n try:\n err = json.loads(response.content)['error'][0]\n except:\n # this means shock is down or not responding.\n self.log(\"Couldn't parse response error content from Shock: \" +\n response.content)\n response.raise_for_status()\n raise ShockException(errtxt + str(err))\n\n # Helper script borrowed from the transform service, logger removed\n def upload_file_to_shock(self, file_path, token):\n \"\"\"\n Use HTTP multi-part POST to save a file to a SHOCK instance.\n \"\"\"\n\n if token is None:\n raise Exception(\"Authentication token required!\")\n\n header = {'Authorization': \"Oauth {0}\".format(token)}\n\n if file_path is None:\n raise Exception(\"No file given for upload to SHOCK!\")\n\n with open(os.path.abspath(file_path), 'rb') as data_file:\n files = {'upload': data_file}\n response = requests.post(\n self.shockURL + '/node', headers=header, files=files,\n stream=True, allow_redirects=True)\n self.check_shock_response(\n response, ('Error trying to upload contig FASTA file {} to Shock: '\n ).format(file_path))\n return response.json()['data']\n\n # spades is configured with yaml\n #\n def generate_spades_yaml(self, reads_data):\n left = [] # fwd in fr orientation\n right = [] # rev\n single = [] # single end reads\n pacbio = [] # pacbio CLR reads (for pacbio CCS use -s option.)\n interlaced = []\n illumina_present = 0\n iontorrent_present = 0\n for read in reads_data:\n seq_tech = read['seq_tech']\n if seq_tech == \"PacBio CLR\":\n pacbio.append(read['fwd_file'])\n elif read['type'] == \"paired\":\n if 'rev_file' in read and read['rev_file']:\n left.append(read['fwd_file'])\n right.append(read['rev_file'])\n else:\n interlaced.append(read['fwd_file'])\n elif read['type'] == \"single\":\n single.append(read['fwd_file'])\n\n if seq_tech == \"IonTorrent\":\n iontorrent_present = 1\n elif seq_tech == \"Illumina\":\n illumina_present = 1\n\n if (illumina_present == 1 and iontorrent_present == 1):\n raise ValueError('Both IonTorrent and Illumina read libraries exist. ' +\n 'SPAdes can not assemble them together.')\n\n yml = []\n yml_index_counter = 0\n # Pacbio CLR ahs to be run with at least one single end or paired end library\n other_reads_present_for_pacbio = 0\n if left or interlaced:\n yml.append({'type': 'paired-end',\n 'orientation': 'fr'})\n if left:\n yml[yml_index_counter]['left reads'] = left\n yml[yml_index_counter]['right reads'] = right\n if interlaced:\n yml[yml_index_counter]['interlaced reads'] = interlaced\n yml_index_counter += 1\n other_reads_present_for_pacbio = 1\n if single:\n yml.append({'type': \"single\"})\n yml[yml_index_counter]['single reads'] = single\n yml_index_counter += 1\n other_reads_present_for_pacbio = 1\n if pacbio:\n if other_reads_present_for_pacbio == 1:\n yml.append({'type': \"pacbio\"})\n yml[yml_index_counter]['single reads'] = pacbio\n yml_index_counter += 1\n else:\n # RAISE AN ERROR AS PACBIO REQUIRES AT LEAST\n # ONE SINGLE OR PAIRED ENDS LIBRARY\n raise ValueError('Per SPAdes requirements : If doing PacBio CLR reads, you must ' +\n 'also supply at least one paired end or single end reads library')\n yml_path = os.path.join(self.scratch, 'run.yaml')\n with open(yml_path, 'w') as yml_file:\n yaml.safe_dump(yml, yml_file)\n return yml_path, iontorrent_present\n\n def exec_spades(self, dna_source, reads_data, phred_type, kmer_sizes, skip_error_correction):\n mem = (psutil.virtual_memory().available / self.GB -\n self.MEMORY_OFFSET_GB)\n if mem < self.MIN_MEMORY_GB:\n raise ValueError(\n 'Only ' + str(psutil.virtual_memory().available) +\n ' bytes of memory are available. The SPAdes wrapper will' +\n ' not run without at least ' +\n str(self.MIN_MEMORY_GB + self.MEMORY_OFFSET_GB) +\n ' gigabytes available')\n\n if dna_source == self.PARAM_IN_METAGENOME:\n max_mem = self.MAX_MEMORY_GB_META_SPADES\n max_threads = self.MAX_THREADS_META\n else:\n max_mem = self.MAX_MEMORY_GB_SPADES\n max_threads = self.MAX_THREADS\n\n threads = min(max_threads, psutil.cpu_count() * self.THREADS_PER_CORE)\n\n if mem > max_mem:\n mem = max_mem\n\n outdir = os.path.join(self.scratch, 'spades_output_dir')\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n tmpdir = os.path.join(self.scratch, 'spades_tmp_dir')\n if not os.path.exists(tmpdir):\n os.makedirs(tmpdir)\n\n cmd = ['spades.py', '--threads', str(threads),\n '--memory', str(mem), '-o', outdir, '--tmp-dir', tmpdir]\n\n print(\"THE DNA SOURCE IS : \" + str(dna_source))\n if dna_source == self.PARAM_IN_SINGLE_CELL:\n cmd += ['--sc']\n if dna_source == self.PARAM_IN_PLASMID:\n cmd += ['--plasmid']\n # The plasmid assembly can only be run on a single library\n if len(reads_data) > 1:\n raise ValueError('Plasmid assembly requires that one ' +\n 'and only one library as input. ' +\n str(len(reads_data)) + ' libraries detected.')\n if dna_source == self.PARAM_IN_METAGENOME:\n cmd += ['--meta']\n # The metagenome assembly can only be run on a single library\n # The library must be paired end.\n if len(reads_data) > 1 or reads_data[0]['type'] != 'paired':\n error_msg = 'Metagenome assembly requires that one and ' + \\\n 'only one paired end library as input.'\n if len(reads_data) > 1:\n error_msg += ' ' + str(len(reads_data)) + \\\n ' libraries detected.'\n raise ValueError(error_msg)\n else:\n cmd += ['--careful']\n cmd += ['--phred-offset', phred_type]\n\n if kmer_sizes is not None:\n cmd += ['-k ' + kmer_sizes]\n if skip_error_correction == 1:\n cmd += ['--only-assembler']\n\n# print(\"LENGTH OF READSDATA IN EXEC: \" + str(len(reads_data)))\n# print(\"READS DATA: \" + str(reads_data))\n# print(\"SPADES YAML: \" + str(self.generate_spades_yaml(reads_data)))\n spades_yaml_path, iontorrent_present = self.generate_spades_yaml(reads_data)\n if iontorrent_present == 1:\n cmd += ['--iontorrent']\n cmd += ['--dataset', spades_yaml_path]\n self.log('Running SPAdes command line:')\n print(\"SPADES CMD:\" + str(cmd))\n self.log(cmd)\n\n if self.DISABLE_SPADES_OUTPUT:\n with open(os.devnull, 'w') as null:\n p = subprocess.Popen(cmd, cwd=self.scratch, shell=False,\n stdout=null)\n else:\n p = subprocess.Popen(cmd, cwd=self.scratch, shell=False)\n retcode = p.wait()\n\n self.log('Return code: ' + str(retcode))\n if p.returncode != 0:\n raise ValueError('Error running SPAdes, return code: ' +\n str(retcode) + '\\n')\n return outdir\n\n # adapted from\n # https://github.com/kbase/transform/blob/master/plugins/scripts/convert/trns_transform_KBaseFile_AssemblyFile_to_KBaseGenomes_ContigSet.py\n # which was adapted from an early version of\n # https://github.com/kbase/transform/blob/master/plugins/scripts/upload/trns_transform_FASTA_DNA_Assembly_to_KBaseGenomes_ContigSet.py\n def load_stats(self, input_file_name):\n self.log('Starting conversion of FASTA to KBaseGenomeAnnotations.Assembly')\n self.log('Building Object.')\n if not os.path.isfile(input_file_name):\n raise Exception('The input file name {0} is not a file!'.format(\n input_file_name))\n with open(input_file_name, 'r') as input_file_handle:\n contig_id = None\n sequence_len = 0\n fasta_dict = dict()\n first_header_found = False\n # Pattern for replacing white space\n pattern = re.compile(r'\\s+')\n for current_line in input_file_handle:\n if (current_line[0] == '>'):\n # found a header line\n # Wrap up previous fasta sequence\n if not first_header_found:\n first_header_found = True\n else:\n fasta_dict[contig_id] = sequence_len\n sequence_len = 0\n fasta_header = current_line.replace('>', '').strip()\n try:\n contig_id = fasta_header.strip().split(' ', 1)[0]\n except:\n contig_id = fasta_header.strip()\n else:\n sequence_len += len(re.sub(pattern, '', current_line))\n # wrap up last fasta sequence, should really make this a method\n if not first_header_found:\n raise Exception(\"There are no contigs in this file\")\n else:\n fasta_dict[contig_id] = sequence_len\n return fasta_dict\n\n def load_report(self, input_file_name, params, wsname):\n fasta_stats = self.load_stats(input_file_name)\n lengths = [fasta_stats[contig_id] for contig_id in fasta_stats]\n\n assembly_ref = params[self.PARAM_IN_WS] + '/' + params[self.PARAM_IN_CS_NAME]\n\n report = ''\n report += 'Assembly saved to: ' + assembly_ref + '\\n'\n report += 'Assembled into ' + str(len(lengths)) + ' contigs.\\n'\n report += 'Avg Length: ' + str(sum(lengths) / float(len(lengths))) + \\\n ' bp.\\n'\n\n # compute a simple contig length distribution\n bins = 10\n counts, edges = np.histogram(lengths, bins) # @UndefinedVariable\n report += 'Contig Length Distribution (# of contigs -- min to max ' +\\\n 'basepairs):\\n'\n for c in range(bins):\n report += ' ' + str(counts[c]) + '\\t--\\t' + str(edges[c]) +\\\n ' to ' + str(edges[c + 1]) + ' bp\\n'\n print('Running QUAST')\n kbq = kb_quast(self.callbackURL)\n quastret = kbq.run_QUAST({'files': [{'path': input_file_name,\n 'label': params[self.PARAM_IN_CS_NAME]}]})\n print('Saving report')\n kbr = KBaseReport(self.callbackURL)\n report_info = kbr.create_extended_report({\n 'message': report,\n 'objects_created': [{'ref': assembly_ref, 'description': 'Assembled contigs'}],\n 'direct_html_link_index': 0,\n 'html_links': [{'shock_id': quastret['shock_id'],\n 'name': 'report.html',\n 'label': 'QUAST report'}],\n 'report_object_name': 'kb_megahit_report_' + str(uuid.uuid4()),\n 'workspace_name': params['workspace_name']\n })\n reportName = report_info['name']\n reportRef = report_info['ref']\n return reportName, reportRef\n\n def make_ref(self, object_info):\n return str(object_info[6]) + '/' + str(object_info[0]) + \\\n '/' + str(object_info[4])\n\n def determine_unknown_phreds(self, reads,\n phred64_reads,\n phred33_reads,\n unknown_phred_reads,\n reftoname):\n print(\"IN UNKNOWN CHECKING\")\n eautils = kb_ea_utils(self.callbackURL)\n for ref in unknown_phred_reads:\n rds = reads[ref]\n obj_name = reftoname[ref]\n files_to_check = []\n f = rds['files']\n if f['type'] == 'interleaved':\n files_to_check.append(f['fwd'])\n elif f['type'] == 'paired':\n files_to_check.append(f['fwd'])\n files_to_check.append(f['rev'])\n elif f['type'] == 'single':\n files_to_check.append(f['fwd'])\n # print(\"FILES TO CHECK:\" + str(files_to_check))\n for file_path in files_to_check:\n ea_stats_dict = eautils.calculate_fastq_stats({'read_library_path': file_path})\n # print(\"EA UTILS STATS : \" + str(ea_stats_dict))\n if ea_stats_dict['phred_type'] == '33':\n phred33_reads.add(obj_name)\n elif ea_stats_dict['phred_type'] == '64':\n phred64_reads.add(obj_name)\n else:\n raise ValueError(('Reads object {} ({}) phred type is not of the ' +\n 'expected value of 33 or 64. It had a phred type of ' +\n '{}').format(obj_name, rds, ea_stats_dict['phred_type']))\n return phred64_reads, phred33_reads\n\n def check_reads(self, params, reads, reftoname):\n\n phred64_reads, phred33_reads, unknown_phred_reads = (set() for i in range(3))\n\n for ref in reads:\n rds = reads[ref]\n obj_name = reftoname[ref]\n obj_ref = rds['ref']\n if rds['phred_type'] == '33':\n phred33_reads.add(obj_name)\n elif rds['phred_type'] == '64':\n phred64_reads.add(obj_name)\n else:\n unknown_phred_reads.add(ref)\n\n if rds['read_orientation_outward'] == self.TRUE:\n raise ValueError(\n ('Reads object {} ({}) is marked as having outward ' +\n 'oriented reads, which SPAdes does not ' +\n 'support.').format(obj_name, obj_ref))\n\n # ideally types would be firm enough that we could rely on the\n # metagenomic boolean. However KBaseAssembly doesn't have the field\n # and it's optional anyway. Ideally fix those issues and then set\n # the --meta command line flag automatically based on the type\n\n # Dylan: removing these requirements because too much work for user to go all the way\n # back and reimport reads with \"single_genome\" flag set opposite. Additionally, now\n # that \"metagenomic\" assembly is now an explicit App instead of an option, this check\n # is far less necessary\n\n# if (rds['single_genome'] == self.TRUE and\n# params[self.PARAM_IN_DNA_SOURCE] ==\n# self.PARAM_IN_METAGENOME):\n# raise ValueError(\n# ('Reads object {} ({}) is marked as containing dna from ' +\n# 'a single genome but the assembly method was specified ' +\n# 'as metagenomic').format(obj_name, obj_ref))\n if (rds['single_genome'] == self.FALSE and\n params[self.PARAM_IN_DNA_SOURCE] !=\n self.PARAM_IN_METAGENOME):\n raise ValueError(\n ('Reads object {} ({}) is marked as containing ' +\n 'metagenomic data but the assembly method was not ' +\n 'specified as metagenomic').format(obj_name, obj_ref))\n\n # IF UNKNOWN TYPE NEED TO DETERMINE PHRED TYPE USING EAUTILS\n if len(unknown_phred_reads) > 0:\n phred64_reads, phred33_reads = \\\n self.determine_unknown_phreds(reads, phred64_reads, phred33_reads,\n unknown_phred_reads, reftoname)\n # IF THERE ARE READS OF BOTH PHRED 33 and 64, throw an error\n if (len(phred64_reads) > 0) and (len(phred33_reads) > 0):\n raise ValueError(\n ('The set of Reads objects passed in have reads that have different ' +\n 'phred type scores. SPAdes does not support assemblies of ' +\n 'reads with different phred type scores.\\nThe following read objects ' +\n 'have phred 33 scores : {}.\\nThe following read objects have phred 64 ' +\n 'scores : {}').format(\", \".join(phred33_reads), \", \".join(phred64_reads)))\n elif len(phred64_reads) > 0:\n return '64'\n elif len(phred33_reads) > 0:\n return '33'\n else:\n raise ValueError('The phred type of the read(s) was unable to be determined')\n\n def process_params(self, params):\n if (self.PARAM_IN_WS not in params or\n not params[self.PARAM_IN_WS]):\n raise ValueError(self.PARAM_IN_WS + ' parameter is required')\n if self.INVALID_WS_NAME_RE.search(params[self.PARAM_IN_WS]):\n raise ValueError('Invalid workspace name ' +\n params[self.PARAM_IN_WS])\n if self.PARAM_IN_LIB not in params:\n raise ValueError(self.PARAM_IN_LIB + ' parameter is required')\n if type(params[self.PARAM_IN_LIB]) != list:\n raise ValueError(self.PARAM_IN_LIB + ' must be a list')\n if not params[self.PARAM_IN_LIB]:\n raise ValueError('At least one reads library must be provided')\n # for l in params[self.PARAM_IN_LIB]:\n # print(\"PARAM_IN_LIB : \" + str(l))\n # if self.INVALID_WS_OBJ_NAME_RE.search(l):\n # raise ValueError('Invalid workspace object name ' + l)\n if (self.PARAM_IN_CS_NAME not in params or\n not params[self.PARAM_IN_CS_NAME]):\n raise ValueError(self.PARAM_IN_CS_NAME + ' parameter is required')\n if self.INVALID_WS_OBJ_NAME_RE.search(params[self.PARAM_IN_CS_NAME]):\n raise ValueError('Invalid workspace object name ' +\n params[self.PARAM_IN_CS_NAME])\n if self.PARAM_IN_DNA_SOURCE in params:\n s = params[self.PARAM_IN_DNA_SOURCE]\n# print(\"FOUND THE DNA SOURCE: \" + str(params[self.PARAM_IN_DNA_SOURCE]))\n if s not in [self.PARAM_IN_SINGLE_CELL,\n self.PARAM_IN_METAGENOME,\n self.PARAM_IN_PLASMID]:\n params[self.PARAM_IN_DNA_SOURCE] = None\n else:\n params[self.PARAM_IN_DNA_SOURCE] = None\n# print(\"PARAMS ARE:\" + str(params))\n if self.PARAM_IN_MIN_CONTIG_LENGTH in params:\n if not isinstance(params[self.PARAM_IN_MIN_CONTIG_LENGTH], int):\n raise ValueError('min_contig_length must be of type int')\n if self.PARAM_IN_KMER_SIZES in params and params[self.PARAM_IN_KMER_SIZES] is not None:\n print(\"KMER_SIZES: \" + \",\".join(str(num) for num in params[self.PARAM_IN_KMER_SIZES]))\n if self.PARAM_IN_SKIP_ERR_CORRECT in params and params[self.PARAM_IN_SKIP_ERR_CORRECT] is not None:\n print(\"SKIP ERR CORRECTION: \" + str(params[self.PARAM_IN_SKIP_ERR_CORRECT]))\n\n #END_CLASS_HEADER\n\n # config contains contents of config file in a hash or None if it couldn't\n # be found\n def __init__(self, config):\n #BEGIN_CONSTRUCTOR\n self.cfg = config\n self.cfg['SDK_CALLBACK_URL'] = os.environ['SDK_CALLBACK_URL']\n self.cfg['KB_AUTH_TOKEN'] = os.environ['KB_AUTH_TOKEN']\n self.callbackURL = self.cfg['SDK_CALLBACK_URL']\n self.log('Callback URL: ' + self.callbackURL)\n self.workspaceURL = config[self.URL_WS]\n self.shockURL = config[self.URL_SHOCK]\n self.catalogURL = config[self.URL_KB_END] + '/catalog'\n self.scratch = os.path.abspath(config['scratch'])\n if not os.path.exists(self.scratch):\n os.makedirs(self.scratch)\n #END_CONSTRUCTOR\n pass\n\n\n def run_SPAdes(self, ctx, params):\n \"\"\"\n Run SPAdes on paired end libraries\n :param params: instance of type \"SPAdesParams\" (Input parameters for\n running SPAdes. workspace_name - the name of the workspace from\n which to take input and store output. output_contigset_name - the\n name of the output contigset read_libraries - a list of Illumina\n PairedEndLibrary files in FASTQ or BAM format. dna_source -\n (optional) the source of the DNA used for sequencing\n 'single_cell': DNA amplified from a single cell via MDA anything\n else: Standard DNA sample from multiple cells. Default value is\n None. min_contig_length - (optional) integer to filter out contigs\n with length < min_contig_length from the SPAdes output. Default\n value is 0 implying no filter. kmer_sizes - (optional) K-mer\n sizes, Default values: 33, 55, 77, 99, 127 (all values must be\n odd, less than 128 and listed in ascending order) In the absence\n of these values, K values are automatically selected.\n skip_error_correction - (optional) Assembly only (No error\n correction). By default this is disabled.) -> structure: parameter\n \"workspace_name\" of String, parameter \"output_contigset_name\" of\n String, parameter \"read_libraries\" of list of type\n \"paired_end_lib\" (The workspace object name of a PairedEndLibrary\n file, whether of the KBaseAssembly or KBaseFile type.), parameter\n \"dna_source\" of String, parameter \"min_contig_length\" of Long,\n parameter \"kmer_sizes\" of list of Long, parameter\n \"skip_error_correction\" of type \"bool\" (A boolean. 0 = false,\n anything else = true.)\n :returns: instance of type \"SPAdesOutput\" (Output parameters for\n SPAdes run. report_name - the name of the KBaseReport.Report\n workspace object. report_ref - the workspace reference of the\n report.) -> structure: parameter \"report_name\" of String,\n parameter \"report_ref\" of String\n \"\"\"\n # ctx is the context object\n # return variables are: output\n #BEGIN run_SPAdes\n\n # A whole lot of this is adapted or outright copied from\n # https://github.com/msneddon/MEGAHIT\n self.log('Running run_SPAdes with params:\\n' + pformat(params))\n\n token = ctx['token']\n\n # the reads should really be specified as a list of absolute ws refs\n # but the narrative doesn't do that yet\n self.process_params(params)\n\n # get absolute refs from ws\n wsname = params[self.PARAM_IN_WS]\n obj_ids = []\n for r in params[self.PARAM_IN_LIB]:\n obj_ids.append({'ref': r if '/' in r else (wsname + '/' + r)})\n ws = Workspace(self.workspaceURL, token=token)\n ws_info = ws.get_object_info_new({'objects': obj_ids})\n reads_params = []\n\n reftoname = {}\n for wsi, oid in zip(ws_info, obj_ids):\n ref = oid['ref']\n reads_params.append(ref)\n obj_name = wsi[1]\n reftoname[ref] = wsi[7] + '/' + obj_name\n\n readcli = ReadsUtils(self.callbackURL, token=ctx['token'])\n\n typeerr = ('Supported types: KBaseFile.SingleEndLibrary ' +\n 'KBaseFile.PairedEndLibrary ' +\n 'KBaseAssembly.SingleEndLibrary ' +\n 'KBaseAssembly.PairedEndLibrary')\n try:\n reads = readcli.download_reads({'read_libraries': reads_params,\n 'interleaved': 'false',\n 'gzipped': None\n })['files']\n except ServerError as se:\n self.log('logging stacktrace from dynamic client error')\n self.log(se.data)\n if typeerr in se.message:\n prefix = se.message.split('.')[0]\n raise ValueError(\n prefix + '. Only the types ' +\n 'KBaseAssembly.PairedEndLibrary ' +\n 'and KBaseFile.PairedEndLibrary are supported')\n else:\n raise\n\n self.log('Got reads data from converter:\\n' + pformat(reads))\n\n phred_type = self.check_reads(params, reads, reftoname)\n\n reads_data = []\n for ref in reads:\n reads_name = reftoname[ref]\n f = reads[ref]['files']\n# print (\"REF:\" + str(ref))\n# print (\"READS REF:\" + str(reads[ref]))\n seq_tech = reads[ref][\"sequencing_tech\"]\n if f['type'] == 'interleaved':\n reads_data.append({'fwd_file': f['fwd'], 'type': 'paired',\n 'seq_tech': seq_tech})\n elif f['type'] == 'paired':\n reads_data.append({'fwd_file': f['fwd'], 'rev_file': f['rev'],\n 'type': 'paired', 'seq_tech': seq_tech})\n elif f['type'] == 'single':\n reads_data.append({'fwd_file': f['fwd'], 'type': 'single',\n 'seq_tech': seq_tech})\n else:\n raise ValueError('Something is very wrong with read lib' + reads_name)\n\n kmer_sizes = None\n if self.PARAM_IN_KMER_SIZES in params and params[self.PARAM_IN_KMER_SIZES] is not None:\n if (len(params[self.PARAM_IN_KMER_SIZES])) > 0:\n kmer_sizes = \",\".join(str(num) for num in params[self.PARAM_IN_KMER_SIZES])\n\n skip_error_correction = 0\n if self.PARAM_IN_SKIP_ERR_CORRECT in params and params[self.PARAM_IN_SKIP_ERR_CORRECT] is not None:\n if params[self.PARAM_IN_SKIP_ERR_CORRECT] == 1:\n skip_error_correction = 1\n\n spades_out = self.exec_spades(params[self.PARAM_IN_DNA_SOURCE],\n reads_data,\n phred_type,\n kmer_sizes,\n skip_error_correction)\n\n self.log('SPAdes output dir: ' + spades_out)\n\n # parse the output and save back to KBase\n output_contigs = os.path.join(spades_out, 'scaffolds.fasta')\n\n self.log('Uploading FASTA file to Assembly')\n\n assemblyUtil = AssemblyUtil(self.callbackURL, token=ctx['token'], service_ver='release')\n\n if params.get('min_contig_length', 0) > 0:\n assemblyUtil.save_assembly_from_fasta(\n {'file': {'path': output_contigs},\n 'workspace_name': wsname,\n 'assembly_name': params[self.PARAM_IN_CS_NAME],\n 'min_contig_length': params['min_contig_length']\n })\n # load report from scaffolds.fasta.filtered.fa\n report_name, report_ref = self.load_report(\n output_contigs + '.filtered.fa', params, wsname)\n else:\n assemblyUtil.save_assembly_from_fasta(\n {'file': {'path': output_contigs},\n 'workspace_name': wsname,\n 'assembly_name': params[self.PARAM_IN_CS_NAME]\n })\n # load report from scaffolds.fasta\n report_name, report_ref = self.load_report(\n output_contigs, params, wsname)\n\n output = {'report_name': report_name,\n 'report_ref': report_ref\n }\n #END run_SPAdes\n\n # At some point might do deeper type checking...\n if not isinstance(output, dict):\n raise ValueError('Method run_SPAdes return value ' +\n 'output is not type dict as required.')\n # return the results\n return [output]\n\n def run_HybridSPAdes(self, ctx, params):\n \"\"\"\n Run HybridSPAdes on paired end libraries with PacBio CLR and Oxford Nanopore reads\n :param params: instance of type \"HybridSPAdesParams\" (------To run\n HybridSPAdes 3.13.0 you need at least one library of the following\n types:------ 1) Illumina paired-end/high-quality\n mate-pairs/unpaired reads 2) IonTorrent paired-end/high-quality\n mate-pairs/unpaired reads 3) PacBio CCS reads Version 3.13.0 of\n SPAdes supports paired-end reads, mate-pairs and unpaired reads.\n SPAdes can take as input several paired-end and mate-pair\n libraries simultaneously. workspace_name - the name of the\n workspace from which to take input and store output.\n output_contigset_name - the name of the output contigset\n read_libraries - a list of Illumina or IonTorrent\n paired-end/high-quality mate-pairs/unpaired reads\n long_reads_libraries - a list of PacBio, Oxford Nanopore Sanger\n reads and/or additional contigs dna_source - the source of the DNA\n used for sequencing 'single_cell': DNA amplified from a single\n cell via MDA anything else: Standard DNA sample from multiple\n cells. Default value is None. pipeline_options - a list of string\n specifying how the SPAdes pipeline should be run kmer_sizes -\n (optional) K-mer sizes, Default values: 21, 33, 55, 77, 99, 127\n (all values must be odd, less than 128 and listed in ascending\n order) In the absence of these values, K values are automatically\n selected. min_contig_length - integer to filter out contigs with\n length < min_contig_length from the HybridSPAdes output. Default\n value is 0 implying no filter. @optional dna_source @optional\n pipeline_options @optional kmer_sizes @optional min_contig_length)\n -> structure: parameter \"workspace_name\" of String, parameter\n \"output_contigset_name\" of String, parameter \"reads_libraries\" of\n list of type \"ReadsParams\" (parameter groups--define attributes\n for specifying inputs with YAML data set file (advanced) The\n following attributes are available: - orientation (\"fr\", \"rf\",\n \"ff\") - type (\"paired-end\", \"mate-pairs\", \"hq-mate-pairs\",\n \"single\", \"pacbio\", \"nanopore\", \"sanger\", \"trusted-contigs\",\n \"untrusted-contigs\") - interlaced reads (comma-separated list of\n files with interlaced reads) - left reads (comma-separated list of\n files with left reads) - right reads (comma-separated list of\n files with right reads) - single reads (comma-separated list of\n files with single reads or unpaired reads from paired library) -\n merged reads (comma-separated list of files with merged reads)) ->\n structure: parameter \"lib_ref\" of type \"obj_ref\" (An X/Y/Z style\n KBase object reference), parameter \"orientation\" of String,\n parameter \"lib_type\" of String, parameter \"long_reads_libraries\"\n of list of type \"LongReadsParams\" -> structure: parameter\n \"long_reads_ref\" of type \"obj_ref\" (An X/Y/Z style KBase object\n reference), parameter \"long_reads_type\" of String, parameter\n \"dna_source\" of String, parameter \"pipeline_options\" of list of\n String, parameter \"kmer_sizes\" of list of Long, parameter\n \"min_contig_length\" of Long, parameter \"create_report\" of type\n \"bool\" (A boolean. 0 = false, anything else = true.)\n :returns: instance of type \"SPAdesOutput\" (Output parameters for\n SPAdes run. report_name - the name of the KBaseReport.Report\n workspace object. report_ref - the workspace reference of the\n report.) -> structure: parameter \"report_name\" of String,\n parameter \"report_ref\" of String\n \"\"\"\n # ctx is the context object\n # return variables are: output\n #BEGIN run_HybridSPAdes\n self.log('Running run_HybridSPAdes with params:\\n{}'.format(\n json.dumps(params, indent=1)))\n\n spades_assembler = SPAdesAssembler(self.cfg, ctx.provenance())\n\n output = spades_assembler.run_hybrid_spades(params)\n #END run_HybridSPAdes\n\n # At some point might do deeper type checking...\n if not isinstance(output, dict):\n raise ValueError('Method run_HybridSPAdes return value ' +\n 'output is not type dict as required.')\n # return the results\n return [output]\n\n def run_metaSPAdes(self, ctx, params):\n \"\"\"\n Run SPAdes on paired end libraries for metagenomes\n :param params: instance of type \"SPAdesParams\" (Input parameters for\n running SPAdes. workspace_name - the name of the workspace from\n which to take input and store output. output_contigset_name - the\n name of the output contigset read_libraries - a list of Illumina\n PairedEndLibrary files in FASTQ or BAM format. dna_source -\n (optional) the source of the DNA used for sequencing\n 'single_cell': DNA amplified from a single cell via MDA anything\n else: Standard DNA sample from multiple cells. Default value is\n None. min_contig_length - (optional) integer to filter out contigs\n with length < min_contig_length from the SPAdes output. Default\n value is 0 implying no filter. kmer_sizes - (optional) K-mer\n sizes, Default values: 33, 55, 77, 99, 127 (all values must be\n odd, less than 128 and listed in ascending order) In the absence\n of these values, K values are automatically selected.\n skip_error_correction - (optional) Assembly only (No error\n correction). By default this is disabled.) -> structure: parameter\n \"workspace_name\" of String, parameter \"output_contigset_name\" of\n String, parameter \"read_libraries\" of list of type\n \"paired_end_lib\" (The workspace object name of a PairedEndLibrary\n file, whether of the KBaseAssembly or KBaseFile type.), parameter\n \"dna_source\" of String, parameter \"min_contig_length\" of Long,\n parameter \"kmer_sizes\" of list of Long, parameter\n \"skip_error_correction\" of type \"bool\" (A boolean. 0 = false,\n anything else = true.)\n :returns: instance of type \"SPAdesOutput\" (Output parameters for\n SPAdes run. report_name - the name of the KBaseReport.Report\n workspace object. report_ref - the workspace reference of the\n report.) -> structure: parameter \"report_name\" of String,\n parameter \"report_ref\" of String\n \"\"\"\n # ctx is the context object\n # return variables are: output\n #BEGIN run_metaSPAdes\n\n output = self.run_SPAdes(ctx,params)[0]\n #END run_metaSPAdes\n\n # At some point might do deeper type checking...\n if not isinstance(output, dict):\n raise ValueError('Method run_metaSPAdes return value ' +\n 'output is not type dict as required.')\n # return the results\n return [output]\n def status(self, ctx):\n #BEGIN_STATUS\n returnVal = {'state': \"OK\",\n 'message': \"\",\n 'version': self.VERSION,\n 'git_url': self.GIT_URL,\n 'git_commit_hash': self.GIT_COMMIT_HASH}\n del ctx # shut up pep8\n #END_STATUS\n return [returnVal]\n" ]
[ [ "numpy.histogram" ] ]
kpj/PySpaMo
[ "673fd6f824b231b412a8ee810bbfe9a2a793661c" ]
[ "evolutionary_optimization.py" ]
[ "\"\"\"\nEvolutionary optimization of something\n\"\"\"\n\nimport random\nimport multiprocessing\n\nimport numpy as np\nimport numpy.random as npr\n\nimport matplotlib.pylab as plt\n\nfrom tqdm import tqdm\n\nfrom automata import SnowDrift\n\n\nclass EvolutionaryOptimizer(object):\n \"\"\" Optimize!\n \"\"\"\n def __init__(self):\n \"\"\" Set some parameters\n \"\"\"\n self.mutation_probability = 0.02\n\n def init(self, size):\n \"\"\" Generate initial population\n \"\"\"\n raise NotImplementedError\n\n def get_fitness(self, obj):\n \"\"\" Compute fitness of individual of population\n \"\"\"\n raise NotImplementedError\n\n def mutate(self, obj):\n \"\"\" Mutate single individual\n \"\"\"\n raise NotImplementedError\n\n def crossover(self, mom, dad):\n \"\"\" Generate offspring from parents\n \"\"\"\n raise NotImplementedError\n\n def run(self, size, max_iter=100):\n \"\"\" Let life begin\n \"\"\"\n population = self.init(size)\n\n res = []\n for _ in tqdm(range(max_iter)):\n pop_fitness = [self.get_fitness(o) for o in population]\n\n # crossover best individuals and replace worst with child\n best_indiv = np.argpartition(pop_fitness, -2)[-2:]\n mom, dad = population[best_indiv]\n child = self.crossover(mom, dad)\n\n worst_indiv = np.argmin(pop_fitness)\n population[worst_indiv] = child\n\n # apply mutations\n mut = lambda o: \\\n self.mutate(o) if random.random() < self.mutation_probability \\\n else o\n population = np.array([mut(o) for o in population])\n\n res.append(\n (np.mean(population, axis=0), np.var(population, axis=0)))\n return res\n\nclass SnowdriftOptimizer(EvolutionaryOptimizer):\n \"\"\" Optimize snowdrift game by assuming each individual to be the pair of\n benefit and cost floats\n \"\"\"\n def init(self, size):\n pop = []\n for _ in range(size):\n pop.append((random.uniform(0, 1), random.uniform(0, 1)))\n return np.array(pop)\n\n def crossover(self, mom, dad):\n return np.mean([mom, dad], axis=0)\n\n def mutate(self, obj):\n sigma = 0.05\n return (obj[0] * random.gauss(1, sigma), obj[1] * random.gauss(1, sigma))\n\n def get_fitness(self, obj):\n # setup system\n lattice = npr.random_integers(0, 1, size=(2, 1))\n model = SnowDrift(lattice)\n\n # generate dynamics\n iter_num = 100\n\n benefit, cost = obj\n res = list(model.iterate(iter_num, benefit=benefit, cost=cost))\n\n # cut off transient\n ss = res[-int(iter_num/10):]\n\n # compute fitness\n fit = -np.sum(ss)\n return fit\n\ndef plot_runs(runs):\n \"\"\" Plot population evolutions\n \"\"\"\n ts = range(len(runs[0]))\n cmap = plt.get_cmap('viridis')\n for i, r in enumerate(runs):\n mean, var = zip(*r)\n bm, cm = zip(*mean)\n bv, cv = zip(*var)\n\n color = cmap(float(i)/len(runs))\n\n plt.errorbar(ts, bm, fmt='-', yerr=bv, c=color)\n plt.errorbar(ts, cm, fmt='--', yerr=cv, c=color)\n\n plt.title('population evolution overview')\n plt.xlabel('time')\n plt.ylabel('value')\n\n plt.ylim((0, 1))\n\n plt.plot(0, 0, '-', c='black', label='benefit value')\n plt.plot(0, 0, '--', c='black', label='cost value')\n plt.legend(loc='best')\n\n plt.savefig('result.pdf')\n plt.show()\n\n\ndef work(i):\n \"\"\" Handle one optimization case\n \"\"\"\n opti = SnowdriftOptimizer()\n return opti.run(20)\n\ndef main():\n \"\"\" Setup environment\n \"\"\"\n core_num = int(multiprocessing.cpu_count() * 4/5)\n print('Using %d cores' % core_num)\n\n with multiprocessing.Pool(core_num) as p:\n runs = [i for i in p.imap_unordered(work, range(10))]\n\n plot_runs(runs)\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.array", "numpy.random.random_integers", "matplotlib.pylab.savefig", "numpy.argmin", "matplotlib.pylab.ylabel", "numpy.sum", "matplotlib.pylab.legend", "numpy.mean", "matplotlib.pylab.show", "matplotlib.pylab.errorbar", "matplotlib.pylab.xlabel", "matplotlib.pylab.get_cmap", "matplotlib.pylab.ylim", "numpy.argpartition", "matplotlib.pylab.title", "matplotlib.pylab.plot", "numpy.var" ] ]
amitgupta98/ga-learner-dsmp-repo
[ "0622bb064610a8fca12c1ffb35303550facf8bd7" ]
[ "Make-Sense-of-census/code.py" ]
[ "# --------------\n# Importing header files\r\nimport numpy as np\r\n# print(path)\r\n\r\n# Path of the file has been stored in variable called 'path'\r\n\r\n#New record\r\nnew_record=[[50, 9, 4, 1, 0, 0, 40, 0]]\r\n\r\n#Code starts here\r\ncensus = np.array([])\r\ndata=np.genfromtxt(path, delimiter=\",\", skip_header=1)\r\ncensus = np.concatenate((data , new_record))\r\n# print(census)\r\n\n\n\n# --------------\n#Code starts here\r\nage = census[:,0]\r\nmax_age = np.max(age)\r\nmin_age = np.min(age)\r\nage_mean = np.mean(age)\r\nage_std = np.std(age)\n\n\n# --------------\n# Code starts here\r\n# race_0 = np.array([])\r\n# race_1 = np.array([])\r\n# race_2 = np.array([])\r\n# race_3 = np.array([])\r\n# race_4 = np.array([])\r\n# for i in range(0,census.shape[0]):\r\n# if int(census[i,2]) == 0:\r\n# race_0 = np.concatenate(race_0 , np.array([census[i , :]]))\r\n# elif int(census[i,2]) == 1:\r\n# race_1 = np.concatenate(race_1 , np.array([census[i , :]]))\r\n# elif int(census[i,2]) == 2:\r\n# race_2 = np.concatenate(race_2 , np.array([census[i , :]]))\r\n# elif int(census[i,2]) == 3:\r\n# race_3 = np.concatenate(race_3 , np.array([census[i , :]]))\r\n# else:\r\n# race_4 = np.concatenate(race_4 , np.array([census[i , :]]))\r\n\r\n# print('r0 \\n' , race_0)\r\n# print(census[0 , :])\r\n# len_0 , len_1 , len_2 , len_3 , len_4 = len(race_0) , len(race_1) , len(race_2) , len(race_3) , len(race_4)\r\n# minority_race = np.min(np.array([len_0 , len_1 , len_2 , len_3 , len_4]))\r\n# race_0 = np.array([])\r\n# for i in range(0,census.shape[0]):\r\n# if int(census[i,2]) == 0:\r\n# race_0 = np.append(race_0 , np.array([census[i , :]]))\r\nrace_0=census[census[:,2]==0]\r\nrace_1=census[census[:,2]==1]\r\nrace_2=census[census[:,2]==2]\r\nrace_3=census[census[:,2]==3]\r\nrace_4=census[census[:,2]==4]\r\n\r\nlen_0=len(race_0)\r\nlen_1=len(race_1)\r\nlen_2=len(race_2)\r\nlen_3=len(race_3)\r\nlen_4=len(race_4)\r\n\r\nRace_list=[len_0,len_1,len_2,len_3,len_4]\r\n\r\nminority_race=Race_list.index(min(Race_list))\r\nprint(minority_race)\r\n\r\n\r\n\n\n\n# --------------\n#Code starts here\r\nsenior_citizens = census[census[:,0]>60]\r\nworking_hours_sum = senior_citizens.sum(axis=0)[6]\r\nsenior_citizens_len = len(senior_citizens)\r\navg_working_hours = (working_hours_sum)/(senior_citizens_len)\r\nprint(avg_working_hours)\n\n\n# --------------\n#Code starts here\r\nhigh = census[census[:,1]>10]\r\nlow = census[census[:,1]<=10]\r\navg_pay_high = high.mean(axis=0)[7]\r\navg_pay_low = low.mean(axis=0)[7]\r\navg_pay_high,avg_pay_low.mean()\n\n\n" ]
[ [ "numpy.concatenate", "numpy.max", "numpy.array", "numpy.genfromtxt", "numpy.min", "numpy.mean", "numpy.std" ] ]
jmdbsa0012/AMTNN
[ "906f99684875e096eb9fd7a626656bfa5d9936e3" ]
[ "MTL.py" ]
[ "\"\"\"\nThis version considers task's datasets have equal number of labeled samples\n\"\"\"\n\nimport os\nimport json\nfrom collections import defaultdict\nimport numpy as np\n\nfrom tensorboardX import SummaryWriter\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch.autograd import grad as torch_grad\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\n\nimport torchvision\nfrom torchvision import transforms\n\nimport util\nfrom util import in_feature_size\nimport alpha_opt\nimport data_loading as db\nfrom torch.optim import lr_scheduler\n\nclass MTL_pairwise(object):\n def __init__(self, ft_extrctor_prp, hypoth_prp, discrm_prp, **kwargs):\n final_results = defaultdict()\n\n\n # ######################### argument definition ###############\n self.criterion = kwargs ['criterion']\n self.c3_value = kwargs['c3']\n self.grad_weight = kwargs['grad_weight']\n self.img_size = kwargs['img_size']\n self.num_chnnl = kwargs['chnnl']\n self.lr = kwargs['lr']\n self.momentum = kwargs['momentum']\n self.epochs = kwargs['epochs']\n num_tr_smpl = kwargs['tr_smpl']\n num_test_smpl = kwargs['test_smpl']\n self.trial = kwargs['Trials']\n self.tsklist = kwargs['tsk_list']\n self.num_tsk = len(self.tsklist)\n\n if self.criterion=='wasserstien': self.stp_sz_sch = 30\n else: self.stp_sz_sch = 50\n\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n self.alpha = np.ones((self.num_tsk, self.num_tsk)) * (0.1 / (self.num_tsk - 1))\n np.fill_diagonal(self.alpha, 0.9)\n\n self.wrdir = os.path.join(os.getcwd(), '_'.join( self.tsklist)+'_'+str(num_tr_smpl)+'_'+ str(self.epochs)+'_'+self.criterion, 'runs_'+str(self.c3_value))\n try:\n os.makedirs(self.wrdir)\n except OSError:\n if not os.path.isdir(self.wrdir):\n raise\n\n with open(os.path.join(self.wrdir, 'info_itr_'+str(self.trial)+'.json'), 'a') as outfile:\n json.dump([ft_extrctor_prp,hypoth_prp,discrm_prp], outfile)\n json.dump(kwargs, outfile)\n\n\n # Constructing F -> H and F -> D\n self.FE = util.feature_extractor(ft_extrctor_prp).construct().to(self.device)\n print (self.FE)\n\n self.hypothesis = [util.classifier(hypoth_prp).to(self.device) for _ in range(self.num_tsk)]\n print (self.hypothesis[0])\n\n\n self.discrm = {'{}{}'.format(i, j): util.classifier(discrm_prp).to(self.device)for i in range(self.num_tsk) for\n j in range(i + 1, self.num_tsk)}\n print (self.discrm['01'])\n all_parameters_h = sum([list(h.parameters()) for h in self.hypothesis], [])\n all_parameters_discrm = sum([list(self.discrm[d].parameters()) for d in self.discrm], [])\n\n\n self.optimizer = optim.SGD(list(self.FE.parameters()) + list(all_parameters_h) + list(all_parameters_discrm),\n lr=self.lr,\n momentum=self.momentum)\n\n self.scheduler = lr_scheduler.StepLR(self.optimizer, step_size=self.stp_sz_sch, gamma=0.5)\n\n train_loader, test_loader, validation_loader = db.data_loading(self.img_size, num_tr_smpl,num_test_smpl, self.tsklist )\n\n self.writer = SummaryWriter(os.path.join(self.wrdir, 'itr'+str(self.trial)))\n\n Total_loss = []\n\n for epoch in range(self.epochs):\n self.scheduler.step(epoch)\n whole_loss = self.model_fit(train_loader, epoch)\n Total_loss.append(whole_loss)\n tasks_trAcc = self.model_eval(train_loader, epoch, 'train')\n tasks_valAcc = self.model_eval(validation_loader, epoch, 'validation')\n tasks_teAcc = self.model_eval(test_loader, epoch, 'test')\n\n # if np.abs(np.mean(Total_loss[-5:-1]) - Total_loss[-1]) < 0.002 :\n # print('Stop learning, reach to a stable point at epoch {:d} with total loss {:.4f}'.format(epoch,\n # Total_loss[-1]))\n # break\n if 1.5*np.mean(Total_loss[-5:-1]) < Total_loss[-1]:\n\n print ('****** Increasing of training error')\n break\n\n final_results['alpha_c3_'+str(self.c3_value)] = (self.alpha).tolist()\n final_results['Tasks_val_Acc_c3_'+str(self.c3_value)] = (tasks_valAcc).tolist()\n final_results['Tasks_test_Acc_c3_' + str(self.c3_value) ] = (tasks_teAcc).tolist()\n final_results['Tasks_train_Acc_c3_'+str(self.c3_value)] = (tasks_trAcc).tolist()\n\n with open(os.path.join(self.wrdir, 'info_itr_'+str(self.trial)+'.json'), 'a') as outfile:\n json.dump(final_results, outfile)\n\n final_prmtr = defaultdict()\n final_prmtr['FE'] = self.FE.state_dict()\n for i,h in enumerate(self.hypothesis):\n final_prmtr['hypo'+str(i)] = h.state_dict()\n for k, D in self.discrm.items():\n final_prmtr['dicrm'+k] = D.state_dict()\n\n torch.save(final_prmtr, os.path.join(self.wrdir, 'itr'+str(self.trial),'MTL_parameters.pt'))\n self.writer.close()\n\n\n\n\n\n def model_fit(self, data_loader, epoch):\n\n discrm_distnc_mtrx = np.zeros((self.num_tsk, self.num_tsk))\n loss_mtrx_hypo_vlue = np.zeros((self.num_tsk, self.num_tsk))\n weigh_loss_hypo_vlue, correct_hypo = np.zeros(self.num_tsk), np.zeros(self.num_tsk)\n Total_loss = 0\n n_batch = 0\n\n # set train mode\n self.FE.train()\n for t in range(self.num_tsk):\n self.hypothesis[t].train()\n for j in range(t + 1, self.num_tsk):\n self.discrm['{}{}'.format(t, j)].train()\n # #####\n for tasks_batch in zip(*data_loader):\n Loss_1, Loss_2 = 0, 0\n n_batch += 1\n # data = (x,y)\n inputs = torch.cat([batch[0] for batch in tasks_batch])\n\n\n btch_sz = len(tasks_batch[0][0])\n targets = torch.cat([batch[1] for batch in tasks_batch])\n\n # inputs = (x1,...,xT) targets = (y1,...,yT)\n inputs = inputs.to(self.device)\n targets = targets.to(self.device)\n features = self.FE(inputs)\n features = features.view(features.size(0), -1)\n for t in range(self.num_tsk):\n w = torch.tensor([np.tile(self.alpha[t, i], reps=len(data[0])) for i, data in enumerate(tasks_batch)],\n dtype=torch.float).view(-1)\n w = w.to(self.device)\n\n label_prob = self.hypothesis[t](features)\n\n pred = label_prob[t * (btch_sz):(t + 1) * btch_sz].argmax(dim=1, keepdim=True)\n correct_hypo[t] += (\n (pred.eq(targets[t * btch_sz:(t + 1) * btch_sz].view_as(pred)).sum().item()) / btch_sz)\n\n hypo_loss = torch.mean(w * F.cross_entropy(label_prob, targets, reduction='none'))\n\n # definition of loss to be optimized\n Loss_1 += hypo_loss\n weigh_loss_hypo_vlue[t] += hypo_loss.item()\n\n loss_mtrx_hypo_vlue[t, :] += [F.cross_entropy(label_prob[j * (btch_sz):(j + 1) * btch_sz, :],\n targets[j * (btch_sz):(j + 1) * btch_sz],\n reduction='mean').item() for j in range(self.num_tsk)]\n\n for k in range(t + 1, self.num_tsk):\n # w = (alpha_{tk}+alpha_{kt}) assumption: matrix alpha is not symmetric\n alpha_domain = torch.tensor(self.alpha[t, k] + self.alpha[k, t], dtype=torch.float)\n alpha_domain = alpha_domain.to(self.device)\n if self.criterion =='h_divergence':\n domain_y = torch.cat([torch.ones(len(tasks_batch[t][0]), dtype=torch.float),\n torch.zeros(len(tasks_batch[k][0]), dtype=torch.float)])\n # domain_x = torch.cat([tasks_batch[t-1][0], tasks_batch[k-1][0] ])\n domain_y = domain_y.to(self.device)\n domain_features = torch.cat([features[t * btch_sz:(t + 1) * btch_sz], features[k * btch_sz:(k + 1) * btch_sz]])\n\n domain_features = domain_features.view(domain_features.size(0), -1)\n\n domain_pred = self.discrm['{}{}'.format(t, k)](domain_features).squeeze()\n\n disc_loss = F.binary_cross_entropy(domain_pred, domain_y)\n\n # discriminator accuracy defines H-divergence\n domain_lbl = domain_pred >= 0.5\n domain_lbl = domain_lbl.type(torch.cuda.FloatTensor)\n discrm_distnc_mtrx[t, k] += (domain_lbl.eq(domain_y).sum().item()) / len(domain_y)\n discrm_distnc_mtrx[k, t] = discrm_distnc_mtrx[t, k]\n\n print(discrm_distnc_mtrx[t, :])\n\n elif self.criterion =='wasserstien':\n\n features_t = features[t * btch_sz:(t + 1) * btch_sz]\n features_t = features_t.view(features_t.size(0), -1)\n features_k = features[k * btch_sz:(k + 1) * btch_sz]\n features_k = features_k.view(features_k.size(0), -1)\n pred_k = self.discrm['{}{}'.format(t, k)](features_k).squeeze()\n pred_t = self.discrm['{}{}'.format(t, k)](features_t).squeeze()\n\n gradient_pntly=self.gradient_penalty(inputs[t * btch_sz:(t + 1) * btch_sz],inputs[k * btch_sz:(k + 1) * btch_sz], t, k)\n # critic loss ---> E(f(x)) - E(f(y)) + gamma* ||grad(f(x+y/2))-1||\n disc_loss = (pred_t.mean() - pred_k.mean() ) + self.grad_weight *gradient_pntly\n # negative sign compute wasserstien distance\n discrm_distnc_mtrx[t, k] += -(pred_t.mean() - pred_k.mean()).item()\n discrm_distnc_mtrx[k, t] = discrm_distnc_mtrx[t, k]\n\n disc_loss = alpha_domain * disc_loss\n Loss_2 += disc_loss\n\n\n if n_batch % 500 == 0:\n grid_img = torchvision.utils.make_grid(inputs, nrow=5, padding=30)\n self.writer.add_image('result Image', grid_img)\n\n Loss = torch.mean(Loss_1) + Loss_2 * (1 / self.num_tsk)\n Total_loss += Loss.item()\n\n # loss formula for all tasks regarding the current batch\n self.optimizer.zero_grad()\n Loss.backward()\n self.optimizer.step()\n\n\n discrm_distnc_mtrx /= n_batch\n weigh_loss_hypo_vlue /= n_batch\n loss_mtrx_hypo_vlue /= n_batch\n correct_hypo /= n_batch\n Total_loss /= n_batch\n\n\n print('================== epoch {:d} ========'.format(epoch))\n print('Final Total Loss {:.3f}'.format(Total_loss ))\n print('discriminator distance based on '+self.criterion +'\\n'+ str(discrm_distnc_mtrx))\n\n print(' hypothesis loss \\n' + str(loss_mtrx_hypo_vlue))\n print(' hypothesis accuracy \\n' + str(correct_hypo * 100))\n print('coefficient:',self.alpha)\n self.writer.add_scalars('MTL_total_loss', {'MTL_total_loss': Total_loss}, epoch)\n for t in range(self.num_tsk):\n # self.writer.add_scalars('task_' + str(t) + '/loss', {'loss_train': loss_mtrx_hypo_vlue[t, t]}, epoch)\n for j in range(self.num_tsk):\n if j != t:\n self.writer.add_scalars('task_' + str(t) + '/Discrm_distance',\n {'loss_D' + '_'.join([self.tsklist[t],self.tsklist[j]]): discrm_distnc_mtrx[t, j]}, epoch)\n self.writer.add_scalars('task_' + str(t) + '/alpha',\n {'alpha' + '_'.join([self.tsklist[t],self.tsklist[j]]): self.alpha[t, j]}, epoch)\n\n if epoch % 1 == 0:\n c_2, c_3 = 1 * np.ones(self.num_tsk), self.c3_value * np.ones(self.num_tsk)\n self.alpha = alpha_opt.min_alphacvx(self.alpha.T, c_2, c_3, loss_mtrx_hypo_vlue.T, discrm_distnc_mtrx.T)\n\n self.alpha = self.alpha.T\n return Total_loss\n\n def model_eval(self, data_loader, epoch, phase='test'):\n\n loss_hypo_vlue = np.zeros(self.num_tsk)\n correct_hypo = np.zeros(self.num_tsk)\n self.FE.eval()\n for t in range(self.num_tsk):\n n_batch_t = 0\n self.hypothesis[t].eval()\n for j in range(t + 1, self.num_tsk):\n self.discrm['{}{}'.format(t, j)].eval()\n\n for inputs, targets in (data_loader[t]):\n n_batch_t += 1\n inputs = inputs.to(self.device)\n targets = targets.to(self.device)\n\n features = self.FE(inputs)\n features = features.view(features.size(0), -1)\n label_prob = self.hypothesis[t](features)\n pred = label_prob.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n correct_hypo[t] += ((pred.eq(targets.view_as(pred)).sum().item()) / len(pred))\n loss_hypo_vlue[t] += F.cross_entropy(label_prob, targets, reduction='mean').item()\n if n_batch_t % 100 == 0:\n grid_img = torchvision.utils.make_grid(inputs, nrow=5, padding=30)\n self.writer.add_image('result Image_' + phase, grid_img)\n\n loss_hypo_vlue[t] /= n_batch_t\n correct_hypo[t] /= n_batch_t\n\n\n self.writer.add_scalars('task_' + str(t) + '/loss', {'loss_' + phase: loss_hypo_vlue[t]}, epoch)\n self.writer.add_scalars('task_' + str(t) + '/Acc', {'Acc_' + phase: correct_hypo[t]}, epoch)\n\n\n print('\\t === hypothesiz **' + phase + '** loss \\n' + str(loss_hypo_vlue))\n print('\\t === hypothesiz **' + phase + '** accuracy \\n' + str(correct_hypo * 100))\n\n return correct_hypo\n\n def gradient_penalty(self, data_t, data_k, t, k):\n batch_size = data_k.size()[0]\n # Calculate interpolation\n theta = torch.rand(batch_size, 1, 1,1)\n theta = theta.expand_as(data_t)\n theta = theta.to(self.device)\n interpolated = theta * data_t + (1 - theta) * data_k\n\n # computing gradient w.r.t interplated sample\n interpolated = Variable(interpolated, requires_grad=True)\n\n interpolated = interpolated.to(self.device)\n\n features_intrpltd = self.FE(interpolated)\n features_intrpltd = features_intrpltd.view(features_intrpltd.size(0), -1)\n # Calculate probability of interpolated examples\n prob_interpolated = self.discrm['{}{}'.format(t, k)](features_intrpltd).squeeze()\n\n # Calculate gradients of probabilities with respect to examples\n gradients = torch_grad(outputs=prob_interpolated, inputs=interpolated,\n grad_outputs=torch.ones(\n prob_interpolated.size()).to(self.device),\n create_graph=True, retain_graph=True)[0]\n\n # Gradients have shape (batch_size, num_channels, img_width, img_height),\n # so flatten to easily take norm per example in batch\n gradients = gradients.view(batch_size, -1)\n # Derivatives of the gradient close to 0 can cause problems because of\n # the square root, so manually calculate norm and add epsilon\n gradients_norm = torch.sqrt(torch.sum(gradients ** 2, dim=1) + 1e-12)\n\n # Return gradient penalty\n return ((gradients_norm - 1) ** 2).mean()\n\n\ndef main():\n \"\"\"\"options for criterion is wasserstien, h_divergence\"\"\"\n # criterion = ['wasserstien', 'h_divergence']\n itertn = 1\n\n # for c3_value in [0.5, 0.2, 1]:\n c3_value = 0.5\n for trial in range(1):\n args = {'img_size': 28,\n 'chnnl': 1,\n 'lr': 0.01,\n 'momentum': 0.9,\n 'epochs': 1,\n 'tr_smpl': 1000,\n 'test_smpl': 10000,\n 'tsk_list': ['mnist', 'svhn', 'm_mnist'],\n 'grad_weight': 1,\n 'Trials': trial,\n #'criterion': 'h_divergence',\n 'criterion': 'wasserstien',\n 'c3':c3_value}\n ft_extrctor_prp = {'layer1': {'conv': [1, 32, 5, 1, 2], 'elu': [], 'maxpool': [3, 2, 0]},\n 'layer2': {'conv': [32, 64, 5, 1, 2], 'elu': [], 'maxpool': [3, 2, 0]}}\n\n hypoth_prp = {\n 'layer3': {'fc': [util.in_feature_size(ft_extrctor_prp, args['img_size']), 128], 'act_fn': 'elu'},\n 'layer4': {'fc': [128, 10], 'act_fn': 'softmax'}}\n\n discrm_prp = {'reverse_gradient': {},\n 'layer3': {'fc': [util.in_feature_size(ft_extrctor_prp, args['img_size']), 128],\n 'act_fn': 'elu'},\n 'layer4': {'fc': [128, 1], 'act_fn': 'sigm'}}\n\n mtl = MTL_pairwise(ft_extrctor_prp, hypoth_prp, discrm_prp, **args)\n del mtl\n\n\nif __name__ == '__main__':\n main()\n\n\n\n" ]
[ [ "torch.rand", "torch.cat", "torch.optim.lr_scheduler.StepLR", "numpy.fill_diagonal", "numpy.zeros", "torch.autograd.Variable", "numpy.ones", "numpy.mean", "torch.nn.functional.cross_entropy", "torch.cuda.is_available", "torch.tensor", "torch.mean", "torch.nn.functional.binary_cross_entropy", "torch.sum" ] ]
chineshboy/dist-gnn
[ "e5506739ffed77d6fab39430db9042cbc8a58fb6" ]
[ "1D_CAGNET/dist_1d.py" ]
[ "import os\nimport math\nimport argparse\nimport pickle\n\nimport torch\nimport torch.distributed as dist\n\nfrom torch.nn import Parameter\nimport torch.nn.functional as F\n\nfrom sparse_coo_tensor_cpp import sparse_coo_tensor_gpu, spmm_gpu\n\nimport utils\nfrom dist_data import DistData\n\nrun = 0\n\n\ndef outer_product2(inputs, ag):\n torch.cuda.synchronize()\n\n g_timer.start(f'gcn_mm_ep{cur_epoch}')\n grad_weight = torch.mm(inputs, ag) # (H^(l-1))^T * (A * G^l)\n torch.cuda.synchronize()\n g_timer.stop(f'gcn_mm_ep{cur_epoch}')#, 'comp')\n\n g_timer.start(f'gcn_allreduce_ep{cur_epoch}')\n dist.all_reduce(grad_weight, op=dist.ReduceOp.SUM, group=g_env.world_group)\n torch.cuda.synchronize()\n g_timer.stop(f'gcn_allreduce_ep{cur_epoch}')#, 'comm')\n return grad_weight\n\n\ndef p2p_broadcast(t, src):\n for dst in range(g_env.world_size):\n if src == dst or g_env.rank not in (src, dst):\n # g_logger.log('p2p bcast skip', src, dst)\n continue\n dst_adj_nz_col = g_data.nz_col_dict[(dst, src)] # non zero\n needed_rows_idx = dst_adj_nz_col\n if g_env.rank == src:\n p2p_buf = t[needed_rows_idx]\n elif g_env.rank == dst:\n p2p_buf = torch.zeros((needed_rows_idx.size(0), t.size(1)), device=g_env.device)\n # g_logger.log('p2p data ready', src, dst, 'needed size',p2p_buf.size(0), 'full size', t.size(0))\n dist.broadcast(p2p_buf, src, group=g_env.p2p_group_dict[(src, dst)])\n # g_logger.log('p2p bcast done', src, dst)\n if g_env.rank == dst:\n t[needed_rows_idx] = p2p_buf\n # g_logger.log('p2p dst done', src, dst)\n return\n\n\ncur_epoch = 0\ncache_features = [None]*8\ncache_layer2 = [None]*8\ncache_backward_layer1 = [None]*8\ncache_backward_layer2 = [None]*8\ncache_enabled = True\n\n\ndef broad_func(node_count, am_partitions, inputs, btype=None):\n global cache_features\n device = g_env.device\n n_per_proc = math.ceil(float(node_count) / g_env.world_size)\n z_loc = torch.zeros((am_partitions[0].size(0), inputs.size(1)), device=device)\n inputs_recv = torch.zeros((n_per_proc, inputs.size(1)), device=device)\n\n\n for i in range(g_env.world_size):\n layer1_use_cache = cur_epoch >= 1\n\n layer2_use_cache = cur_epoch >= 50 and cur_epoch % 5 != 0\n # layer2_use_cache = False\n\n backward_layer2_use_cache = cur_epoch >= 50 and cur_epoch % 5 != 0\n backward_layer2_use_cache = False\n\n backward_layer1_use_cache = cur_epoch >= 50 and cur_epoch % 5 != 0\n backward_layer1_use_cache = False\n\n if i == g_env.rank:\n inputs_recv = inputs.clone()\n elif i == g_env.world_size - 1:\n inputs_recv = torch.zeros((am_partitions[i].size(1), inputs.size(1)), device=device)\n\n g_timer.barrier_all()\n torch.cuda.synchronize()\n\n g_timer.start(f'gcn_broadcast_{btype}_ep{cur_epoch}')\n if not cache_enabled:\n dist.broadcast(inputs_recv, src=i, group=g_env.world_group)\n else:\n if btype == 'layer1':\n if layer1_use_cache:\n # g_logger.log(cur_epoch, i, 'use cache', btype)\n if g_env.rank != i:\n # g_logger.log(cur_epoch, i, 'no copy', btype, type(inputs_recv), inputs_recv.size())\n inputs_recv = cache_features[i]\n else:\n # g_logger.log(cur_epoch, i, 'do nothing', btype, type(inputs_recv), inputs_recv.size())\n pass\n else:\n dist.broadcast(inputs_recv, src=i, group=g_env.world_group)\n # if cache_features[i] is not None:\n # g_logger.log(cur_epoch, i,'normal broadcast', torch.sum(inputs_recv), torch.sum(cache_features[i] ))\n cache_features[i] = inputs_recv.clone()\n elif btype == 'layer2':\n if layer2_use_cache:\n if g_env.rank != i:\n inputs_recv = cache_layer2[i]\n else:\n dist.broadcast(inputs_recv, src=i, group=g_env.world_group)\n # if cache_layer2[i] is not None:\n # g_logger.log(cur_epoch, i,'normal broadcast', torch.sum(inputs_recv), torch.sum(cache_layer2[i] ))\n cache_layer2[i] = inputs_recv.clone()\n elif btype == 'backward_layer2':\n if backward_layer2_use_cache:\n if g_env.rank != i:\n inputs_recv = cache_backward_layer2[i]\n else:\n dist.broadcast(inputs_recv, src=i, group=g_env.world_group)\n cache_backward_layer2[i] = inputs_recv.clone()\n elif btype == 'backward_layer1':\n if backward_layer1_use_cache:\n if g_env.rank != i:\n inputs_recv = cache_backward_layer1[i]\n else:\n dist.broadcast(inputs_recv, src=i, group=g_env.world_group)\n cache_backward_layer1[i] = inputs_recv.clone()\n else:\n dist.broadcast(inputs_recv, src=i, group=g_env.world_group)\n # p2p_broadcast(inputs_recv, i)\n torch.cuda.synchronize() # comm or comp?\n g_timer.stop(f'gcn_broadcast_{btype}_ep{cur_epoch}')#,'comm')\n g_logger.log(f'[gcn_broadcast_{btype}_ep{cur_epoch}] size: {utils.mem_report(inputs_recv)} MBytes')\n\n g_timer.barrier_all()\n torch.cuda.synchronize()\n\n g_timer.start(f'gcn_spmm_ep{cur_epoch}')\n spmm_gpu(am_partitions[i].indices()[0].int(), am_partitions[i].indices()[1].int(),\n am_partitions[i].values(), am_partitions[i].size(0),\n am_partitions[i].size(1), inputs_recv, z_loc)\n\n torch.cuda.synchronize()\n g_timer.stop(f'gcn_spmm_ep{cur_epoch}')#, 'comp')\n g_timer.barrier_all()\n return z_loc\n\n\nclass GCNFunc(torch.autograd.Function):\n @staticmethod\n def forward(ctx, inputs, weight, adj_matrix, am_partitions, activation_func, btype):\n ctx.save_for_backward(inputs, weight, adj_matrix)\n ctx.am_partitions = am_partitions\n ctx.activation_func = activation_func\n ctx.btype = btype\n z = broad_func(adj_matrix.size(0), am_partitions, inputs, btype=btype)\n\n torch.cuda.synchronize()\n g_timer.start(f'gcn_mm_ep{cur_epoch}')\n z = torch.mm(z, weight)\n torch.cuda.synchronize()\n g_timer.stop(f'gcn_mm_ep{cur_epoch}') #, 'comp')\n\n z.requires_grad = True\n ctx.z = z\n return activation_func(z)\n\n @staticmethod\n def backward(ctx, grad_output):\n inputs, weight, adj_matrix = ctx.saved_tensors\n btype = ctx.btype\n am_partitions = ctx.am_partitions\n\n with torch.set_grad_enabled(True):\n func_eval = ctx.activation_func(ctx.z)\n sigmap = torch.autograd.grad(outputs=func_eval, inputs=ctx.z, grad_outputs=grad_output)[0]\n grad_output = sigmap\n\n # First backprop equation\n ag = broad_func(adj_matrix.size(0), am_partitions, grad_output, btype='backward_'+btype)\n\n torch.cuda.synchronize()\n g_timer.start(f'gcn_mm_ep{cur_epoch}')\n grad_input = torch.mm(ag, weight.t())\n torch.cuda.synchronize()\n g_timer.stop(f'gcn_mm_ep{cur_epoch}')#, 'comp')\n\n # Second backprop equation (reuses the A * G^l computation)\n grad_weight = outer_product2(inputs.t(), ag)\n\n return grad_input, grad_weight, None, None, None, None, None, None\n\n\ndef train(inputs, weight1, weight2, adj_matrix, am_partitions, optimizer, local_train_mask, local_labels, device):\n outputs = GCNFunc.apply(inputs, weight1, adj_matrix, am_partitions, F.relu, 'layer1')\n outputs = GCNFunc.apply(outputs, weight2, adj_matrix, am_partitions, lambda x:F.log_softmax(x, dim=1), 'layer2')\n\n optimizer.zero_grad()\n\n if list(local_labels[local_train_mask].size())[0] > 0:\n loss = F.nll_loss(outputs[local_train_mask], local_labels[local_train_mask])\n loss.backward()\n else:\n fake_loss = (outputs * torch.cuda.FloatTensor(outputs.size(), device=device).fill_(0)).sum()\n fake_loss.backward()\n\n optimizer.step()\n return outputs\n\n\ndef test(outputs, vertex_count):\n logits, accs = outputs, []\n for mask in [g_data.g.train_mask, g_data.g.val_mask, g_data.g.test_mask]:\n pred = logits[mask].max(1)[1]\n acc = pred.eq(g_data.g.labels[mask]).sum().item() / mask.sum().item()\n accs.append(acc)\n return accs\n\n\ndef main():\n global run\n global cur_epoch\n inputs_loc, adj_matrix_loc, am_pbyp = g_data.local_features, g_data.local_adj, g_data.local_adj_parts\n # am_partition: adjacency matrix partition\n device = g_env.device\n\n torch.cuda.synchronize()\n\n for i in range(args.run_count):\n run = i\n torch.manual_seed(0)\n weight1_nonleaf = torch.rand(g_data.g.num_features, args.mid_layer, requires_grad=True, device=device)\n weight1_nonleaf.retain_grad()\n\n weight2_nonleaf = torch.rand(args.mid_layer, g_data.g.num_classes, requires_grad=True, device=device)\n weight2_nonleaf.retain_grad()\n\n weight1 = Parameter(weight1_nonleaf)\n weight2 = Parameter(weight2_nonleaf)\n\n optimizer = torch.optim.Adam([weight1, weight2], lr=0.01)\n\n local_train_mask = torch.split(g_data.g.train_mask.bool(), am_pbyp[0].size(0), dim=0)[g_env.rank]\n local_labels = torch.split(g_data.g.labels, am_pbyp[0].size(0), dim=0)[g_env.rank]\n\n\n\n for epoch in range(args.epochs):\n cur_epoch = epoch\n g_timer.start('train')\n outputs = train(inputs_loc, weight1, weight2, adj_matrix_loc, am_pbyp, optimizer, local_train_mask, local_labels, device)\n g_timer.stop('train')\n # if epoch%10==0:\n # g_logger.log(\"Epoch: {:03d}\".format(epoch), oneline=True)\n\n if (epoch+1)%5==0:\n n_per_proc = math.ceil(g_data.g.features.size(0) / g_env.world_size)\n output_parts = [torch.zeros(n_per_proc, g_data.g.num_classes, device=g_env.device) for i in range(g_env.world_size)]\n\n if outputs.size(0) != n_per_proc:\n pad_row = n_per_proc - outputs.size(0)\n outputs = torch.cat((outputs, torch.cuda.FloatTensor(pad_row, g_data.g.num_classes, device=g_env.device)), dim=0)\n dist.all_gather(output_parts, outputs) # output_parts[g_env.rank] = outputs\n\n padding = g_data.g.features.size(0) - n_per_proc * (g_env.world_size - 1)\n output_parts[g_env.world_size - 1] = output_parts[g_env.world_size - 1][:padding,:]\n outputs = torch.cat(output_parts, dim=0)\n\n train_acc, val_acc, test_acc = test(outputs, am_pbyp[0].size(1))\n g_logger.log( 'Epoch: {:03d}/{:03d}, Train: {:.4f}, Val: {:.4f}, Test: {:.4f}'.format(epoch+1, args.epochs, train_acc, val_acc, test_acc), rank=0)\n\n # g_logger.log(g_timer.summary_all(), rank=0)\n return outputs\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--local_rank\", type=int)\n parser.add_argument(\"--world_size\", type=int, default=8)\n parser.add_argument(\"--backend\", type=str, default=\"nccl\")\n parser.add_argument(\"--epochs\", type=int, default=200)\n parser.add_argument(\"--run_count\", type=int, default=1)\n parser.add_argument(\"--graphname\", type=str, default=\"SmallerReddit\")\n parser.add_argument(\"--timing\", type=bool, default=True)\n parser.add_argument(\"--mid_layer\", type=int, default=16)\n args = parser.parse_args()\n print(args)\n g_env = utils.DistEnv(args.local_rank, args.world_size, args.backend)\n\n g_timer = utils.DistTimer(g_env)\n g_logger = utils.DistLogger(g_env)\n g_logger.log(f'dist env inited: {g_env.backend} {g_env.world_size}')\n\n g_data = DistData(g_env, args.graphname)\n g_logger.log(f'dist data inited: {args.graphname}')\n\n main()\n\n timer_log = g_timer.sync_duration_dicts()\n mem_log = g_logger.sync_duration_dicts()\n if args.local_rank == 0:\n with open('./timer.log', 'wb') as f:\n pickle.dump(timer_log, f)\n with open('./mem.log', 'wb') as f:\n pickle.dump(mem_log, f)\n" ]
[ [ "torch.zeros", "torch.rand", "torch.cat", "torch.cuda.synchronize", "torch.optim.Adam", "torch.distributed.all_gather", "torch.mm", "torch.manual_seed", "torch.nn.Parameter", "torch.nn.functional.log_softmax", "torch.autograd.grad", "torch.distributed.all_reduce", "torch.cuda.FloatTensor", "torch.nn.functional.nll_loss", "torch.set_grad_enabled", "torch.distributed.broadcast" ] ]
sives5/pymetalog
[ "0cd332b132eb3c9117a827088f7082e346cb77d8" ]
[ "pymetalog/a_vector.py" ]
[ "import pandas as pd\nimport numpy as np\nimport scipy as sp\n\nfrom scipy.optimize import linprog, minimize, NonlinearConstraint\nfrom .pdf_quantile_functions import pdf_quantile_builder\nfrom .support import diffMatMetalog, pdfMetalog, quantileMetalog, newtons_method_metalog\n\nimport time\nimport warnings\n\ndef a_vector_OLS_and_LP(m_dict,\n bounds,\n boundedness,\n term_limit,\n term_lower_bound,\n fit_method,\n alpha,\n diff_error = .001,\n diff_step = 0.001):\n\n \"\"\" Main workhorse function of pymetalog package.\n Called during metalog.__init__ method call.\n\n Args:\n m_dict (:obj:`dict` with keys ['params', 'dataValues', 'Y']): Initialized output_dict variable from metalog class.\n - m_dict['params']: (:obj:`dict` with keys ['bounds', 'boundedness', 'term_limit', 'term_lower_bound', 'step_len', 'fit_method']):\n * 'bounds': metalog.bounds\n * 'boundedness': metalog.boundedness\n * 'term_limit': metalog.term_limit\n * 'term_lower_bound': metalog.term_lower_bound\n * 'step_len': metalog.step_len\n * 'fit_method': metalog.fit_method\n\n - m_dict['dataValues']: (:obj:`pandas.DataFrame` with columns ['x','probs','z'] of type numeric):\n * 'x': metalog.x\n * 'probs': metalog.probs\n * 'z': column calculated in metalog.append_zvector method\n - depends on metalog.boundedness attribute\n - metalog.boundedness = 'u':\n * 'z' = metalog.x\n - metalog.boundedness = 'sl':\n * 'z' = log( (metalog.x-lower_bound) )\n - metalog.boundedness = 'su':\n * 'z' = = log( (upper_bound-metalog.x) )\n - metalog.boundedness = 'b':\n * 'z' = log( (metalog.x-lower_bound) / (upper_bound-metalog.x) )\n\n - m_dict['Y']: (:obj:`pandas.DataFrame` with columns ['y1','y2','y3','y4', ... ,'yn'] of type numeric):\n * 'y1': numpy.array of ones with length equal to len(x)\n * 'y2': numpy.array of numeric values equal to the term attached to s in the logistic quantile function np.log(m_dict['dataValues']['probs'] / (1 - m_dict['dataValues']['probs']))\n * 'y3': numpy.array of numeric values (m_dict['dataValues']['probs'] - 0.5) * m_dict['Y']['y2']\n * 'y4': numpy.array of numeric values m_dict['Y']['y4'] = m_dict['dataValues']['probs'] - 0.5\n * 'yn': numpy.array of numeric values:\n - if n in 'yn' is odd,\n m_dict['Y']['yn'] = m_dict['Y']['y4']**(int(i//2))\n - if n in 'yn' is even,\n zn = 'y' + str(n-1)\n m_dict['Y'][yn] = m_dict['Y']['y2'] * m_dict['Y'][zn]\n\n bounds (:obj:`list`): Upper and lower limits to filter the data with before calculating metalog quantiles/pdfs.\n - should be set in conjunction with the `boundedness` parameter\n\n boundedness (:obj:`str`): String that is used to specify the type of metalog to fit.\n - must be in set ('u','sl','su','b')\n - Default: 'u'\n * Fits an unbounded metalog\n - 'sl' fits a strictly lower bounded metalog\n * len(bounds) must == 1\n - 'su' fits a strictly upper bounded metalog\n * len(bounds) must == 1\n - 'b' fits a upper/lower bounded metalog\n * len(bounds) must == 2\n * bounds[1] must be > bounds[0]\n\n term_limit (:obj:`int`): The upper limit of the range of metalog terms to use to fit the data.\n - strictly > term_lower_bound\n - in range [3,30]\n\n term_lower_bound (:obj:`int`): The lower limit of the range of metalog terms to use to fit the data.\n - strictly < term_limit\n - in range [2,29]\n\n fit_method (:obj:`str`): Fit method to use to fit metalog distribution.\n - must be in set ('any','OLS','LP','MLE')\n - Default: 'any'\n * first tries 'OLS' method than 'LP'\n - 'OLS' only tries to fit by solving directly for a coefficients using ordinary least squares method\n - 'LP' only tries to estimate fit using simplex linear program optimization routine\n - 'MLE' first tries 'OLS' method than falls back to a maximum likelihood estimation routine\n\n alpha (:obj:`float`, optional): Regularization term to add to OLS fit\n - strictly >= 0.\n - should be set in conjunction with `penalty` parameter\n - Default: 0. (no regularization, OLS)\n\n diff_error (:obj:`float`, optional): Value used to in scipy.optimize.linprog method call\n to init the array of values representing the\n upper-bound of each inequality constraint (row) in A_ub.\n - #TODO: Insert maths\n\n diff_step (:obj:`float`, optional): Value passed to `step_len` parameter in support.py diffMatMetalog method call\n defines the bin width for the Reimann sum of the differences differentiation method\n - diffMatMetalog differentiates the metalog pdf\n * Differentiation reference: https://math.stackexchange.com/a/313135\n Returns:\n m_dict: (:obj:`dict` with keys ['params', 'dataValues', 'Y', 'A', 'M', 'Validation'])\n - m_dict['A']: (:obj:`pandas.DataFrame` with columns ['a2','a3', ... ,'an'] of type numeric):\n * a2, a3, ... , an are our a coefficients returned by the method specified in `fit_method`\n\n - m_dict['M']: (:obj:`pandas.DataFrame` with columns 0:'pdf_1',1:'cdf_1',2:'pdf_2',3:'cdf_2',\n ...,((2*(term_limit-term_lower_bound))+1)-1:'pdf_n',\n ((2*(term_limit-term_lower_bound))+1):'cdf_n'\n where n is the total number of metalog fits determined by (term_limit-term_lower_bound)+1\n )\n * pdf_1, pdf_2, ... , pdf_n are the metalog pdfs returned by pdf_quantile_builder.pdfMetalog method\n * cdf_1, cdf_2, ... , cdf_n are the metalog quantiles returned by pdf_quantile_builder.quantileMetalog method\n \n - m_dict['y']: (:obj: `numpy.ndarray` of type float):\n * Array of bin widths for both the pdf_n and cdf_n\n\n - m_dict['Validation']: (:obj:`pandas.DataFrame` with columns ['term', 'valid', 'method'] of type str):\n * 'term': each metalog estimation given a number of terms\n * 'valid': boolean flag indicating if the metalog estimation was valid or not\n * 'method': a string indicating which method was used for the metalog estimation\n\n \"\"\"\n\n A = pd.DataFrame()\n c_a_names = []\n c_m_names = []\n Mh = pd.DataFrame()\n Validation = pd.DataFrame()\n df_MH_temp_list = list()\n df_A_temp_list = list()\n df_Validation_temp_list = list()\n\n # TODO: Large for-loop can probably be factored into smaller functions\n for i in range(term_lower_bound,term_limit+1):\n Y = m_dict['Y'].iloc[:,0:i]\n eye = np.eye(Y.shape[1])\n z = m_dict['dataValues']['z']\n y = m_dict['dataValues']['probs']\n step_len = m_dict['params']['step_len']\n methodFit = 'OLS'\n a_name = 'a'+str(i)\n m_name = 'm'+str(i)\n M_name = 'M'+str(i)\n c_m_names = np.append(c_m_names, [m_name, M_name])\n c_a_names = np.append(c_a_names, a_name)\n\n if fit_method == 'any' or fit_method == 'MLE':\n try:\n temp = np.dot(np.dot(np.linalg.inv(np.dot(Y.T, Y) + alpha*eye), Y.T), z)\n except:\n # use LP solver if OLS breaks\n temp = a_vector_LP(m_dict, term_limit=i, term_lower_bound=i, diff_error=diff_error, diff_step=diff_step)\n methodFit = 'Linear Program'\n if fit_method == 'OLS':\n try:\n temp = np.dot(np.dot(np.linalg.inv(np.dot(Y.T, Y) + alpha*eye), Y.T), z)\n except:\n raise RuntimeError(\"OLS was unable to solve infeasible or poorly formulated problem\")\n if fit_method == \"LP\":\n temp = a_vector_LP(m_dict, term_limit=i, term_lower_bound=i, diff_error=diff_error, diff_step=diff_step)\n methodFit = 'Linear Program'\n\n if fit_method == 'MLE':\n temp = a_vector_MLE(temp, y, i, m_dict, bounds, boundedness)\n\n temp = np.append(temp, np.zeros(term_limit-i))\n\n # build a y vector for smaller data sets\n if len(z) < 100:\n y2 = np.linspace(step_len, 1 - step_len, int((1 - step_len) / step_len))\n tailstep = step_len / 10\n y1 = np.linspace(tailstep, (min(y2) - tailstep), int((min(y2) - tailstep) / tailstep))\n y3 = np.linspace((max(y2) + tailstep), (max(y2) + tailstep * 9), int((tailstep * 9) / tailstep))\n y = np.hstack((y1, y2, y3))\n\n # Get the dict and quantile values back for validation\n temp_dict = pdf_quantile_builder(temp, y=y, term_limit=i, bounds=bounds, boundedness=boundedness)\n\n # If it not a valid pdf run and the OLS version was used the LP version\n if (temp_dict['valid'] == 'no') and (fit_method != 'OLS'):\n temp = a_vector_LP(m_dict, term_limit=i, term_lower_bound=i, diff_error=diff_error, diff_step=diff_step)\n temp = np.append(temp, np.zeros(term_limit-i))\n methodFit = 'Linear Program'\n\n # Get the dict and quantile values back for validation\n temp_dict = pdf_quantile_builder(temp, y=y, term_limit=i, bounds=bounds, boundedness=boundedness)\n\n df_MH_temp_list.append(pd.DataFrame(temp_dict['m']))\n df_MH_temp_list.append(pd.DataFrame(temp_dict['M']))\n df_A_temp_list.append(pd.DataFrame(temp))\n\n tempValidation = pd.DataFrame(data={'term': [i], 'valid': [temp_dict['valid']], 'method': [methodFit]})\n df_Validation_temp_list.append(tempValidation)\n\n Validation = pd.concat(df_Validation_temp_list, axis=0)\n Mh = pd.concat(df_MH_temp_list, axis=1)\n A = pd.concat(df_A_temp_list, axis=1)\n\n A.columns = c_a_names\n Mh.columns = c_m_names\n\n m_dict['A'] = A\n m_dict['M'] = Mh\n m_dict['M']['y'] = temp_dict['y']\n m_dict['Validation'] = Validation\n\n A = np.column_stack((np.repeat(1.,len(A)), A))\n Est = np.dot(m_dict['Y'], A)\n ncols = A.shape[1]\n Z = np.column_stack((np.array(m_dict['dataValues']['z']),np.repeat(m_dict['dataValues']['z'].values,ncols-1).reshape(len(m_dict['dataValues']['z']),ncols-1)))\n\n m_dict['square_residual_error'] = ((Z-Est)**2).sum(axis=1)\n\n return m_dict\n\ndef a_vector_LP(m_dict, term_limit, term_lower_bound, diff_error = .001, diff_step = 0.001):\n \"\"\"TODO: write docstring\n\n \"\"\"\n cnames = np.array([])\n\n for i in range(term_lower_bound, term_limit + 1):\n Y = m_dict['Y'].iloc[:, 0:i]\n z = m_dict['dataValues']['z']\n\n # Bulding the objective function using abs value LP formulation\n Y_neg = -Y\n\n new_Y = pd.DataFrame({'y1': Y.iloc[:, 0], 'y1_neg': Y_neg.iloc[:, 0]})\n\n for c in range(1,len(Y.iloc[0,:])):\n new_Y['y'+str(c+1)] = Y.iloc[:,c]\n new_Y['y' + str(c+1)+'_neg'] = Y_neg.iloc[:, c]\n\n a = np.array([''.join(['a', str(i)])])\n cnames = np.append(cnames, a, axis=0)\n\n # Building the constraint matrix\n error_mat = np.array([])\n\n for j in range(1,len(Y.iloc[:,0])+1):\n front_zeros = np.zeros(2 * (j - 1))\n ones = [1, -1]\n trail_zeroes = np.zeros(2 * (len(Y.iloc[:, 1]) - j))\n if j == 1:\n error_vars = np.append(ones, trail_zeroes)\n\n elif j != 1:\n error_vars = np.append(front_zeros, ones)\n error_vars = np.append(error_vars, trail_zeroes)\n\n if error_mat.size == 0:\n error_mat = np.append(error_mat, error_vars, axis=0)\n else:\n error_mat = np.vstack((error_mat, error_vars))\n\n new = pd.concat((pd.DataFrame(data=error_mat), new_Y), axis=1)\n diff_mat = diffMatMetalog(i, diff_step)\n diff_zeros = []\n\n for t in range(0,len(diff_mat.iloc[:, 0])):\n zeros_temp = np.zeros(2 * len(Y.iloc[:, 0]))\n\n if np.size(diff_zeros) == 0:\n diff_zeros = zeros_temp\n else:\n diff_zeros = np.vstack((zeros_temp, diff_zeros))\n\n diff_mat = np.concatenate((diff_zeros, diff_mat), axis=1)\n\n # Combine the total constraint matrix\n lp_mat = np.concatenate((new, diff_mat), axis=0)\n\n # Objective function coeficients\n c = np.append(np.ones(2 * len(Y.iloc[:, 1])), np.zeros(2*i))\n\n # Constraint matrices\n A_eq = lp_mat[:len(Y.iloc[:, 1]),:]\n A_ub = -1*lp_mat[len(Y.iloc[:, 1]):,:]\n b_eq = z\n b_ub = -1*np.repeat(diff_error, len(diff_mat[:,0]))\n\n # Solving the linear program w/ scipy (for now)\n lp_sol = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, method='simplex', options={\"maxiter\":5000, \"tol\":1.0e-5,\"disp\": False})\n\n # Consolidating solution back into the a vector\n tempLP = lp_sol.x[(2 * len(Y.iloc[:, 1])):(len(lp_sol.x)+1)]\n temp = []\n\n for r in range(0,((len(tempLP) // 2))):\n temp.append(tempLP[(r * 2)] - tempLP[(2 * r)+1])\n\n return temp\n\n\ndef a_vector_MLE(a, y, term, m_dict, bounds, boundedness):\n \"\"\"TODO: write docstring\n\n \"\"\"\n ym = [newtons_method_metalog(a, xi, term, bounds, boundedness) for xi in m_dict['dataValues']['x']]\n\n def MLE_quantile_constraints(x):\n M = [quantileMetalog(x[:term], yi, term, bounds=bounds, boundedness=boundedness) for yi in x[term:]]\n return m_dict['dataValues']['x'] - M\n\n def MLE_objective_function(x, y, term, m_dict):\n return -np.sum([np.log10(pdfMetalog(x[:term], yi, term, bounds, boundedness)) for yi in np.absolute(x[term:])])\n\n m_dict[str('MLE' + str(term))] = {}\n\n x0 = np.hstack((a[:term],ym))\n m_dict[str('MLE' + str(term))]['oldobj'] = -MLE_objective_function(x0, y, term, m_dict)\n bnd = ((None, None),)*len(a)+((0, 1),)*(len(x0)-len(a))\n con = NonlinearConstraint(MLE_quantile_constraints, 0, 0)\n\n mle = minimize(MLE_objective_function, x0, args=(y, term, m_dict), bounds=bnd, constraints=con)\n\n m_dict[str('MLE' + str(term))]['newobj'] = -MLE_objective_function(mle.x, y, term, m_dict)\n m_dict[str('MLE'+str(term))]['A'] = mle.x[:term]\n m_dict[str('MLE'+str(term))]['Y'] = mle.x[term:]\n\n m_dict[str('MLE' + str(term))]['oldA'] = a\n m_dict[str('MLE' + str(term))]['oldY'] = y\n\n out_temp = np.zeros_like(a)\n for i in range(term):\n out_temp[i] = mle.x[i]\n\n return out_temp\n\n\n\n\n" ]
[ [ "numpy.concatenate", "numpy.append", "numpy.array", "numpy.dot", "numpy.zeros_like", "numpy.zeros", "scipy.optimize.NonlinearConstraint", "numpy.absolute", "pandas.DataFrame", "numpy.eye", "scipy.optimize.linprog", "numpy.size", "pandas.concat", "numpy.repeat", "numpy.hstack", "scipy.optimize.minimize", "numpy.vstack" ] ]
nonu116/HDR-GAN
[ "239f68dd07f1970e0317515a313b69a9c3914f74" ]
[ "tensorkit/restore.py" ]
[ "import os\n\nimport tensorflow as tf\n\nfrom tensorkit.log import logger, Color\n\n\nclass Restore(object):\n def __init__(self):\n self._var_list = None\n self._restore_saver = None\n self._restore_optimistic = False\n self.restore_ckpt_file = None\n self._inited = False\n\n def init(self, var_list=None, ckpt_dir=None, ckpt_file=None, optimistic=False):\n \"\"\"\n :param var_list: vars for restore\n :param ckpt_dir: prefix of model files.\n :param ckpt_file: exact name of model file, priority is higher than `ckpt_dir`\n :param optimistic: only restore weights of same names with model.\n :return:\n \"\"\"\n assert (var_list is None) or (len(var_list) > 0), 'invalid var_list: {}'.format(var_list)\n assert ckpt_dir is not None or ckpt_file is not None, 'ckpt_dir and ckpt_file are both None'\n self._var_list = var_list\n self._restore_optimistic = optimistic\n if ckpt_file is None:\n assert os.path.exists(ckpt_dir), 'invalid checkpoint dir: %s' % ckpt_dir\n # get ckpt file.\n self.restore_ckpt_file = tf.train.latest_checkpoint(os.path.dirname(ckpt_dir + os.sep))\n else:\n self.restore_ckpt_file = ckpt_file\n self._inited = True\n return self\n\n def restore(self, sess):\n assert self._inited, 'make sure init() before restore()'\n if self._restore_vars(sess):\n logger.info('- succeed restore variables from: {}'.format(self.restore_ckpt_file))\n return True\n return False\n\n def _restore_vars(self, sess):\n \"\"\"\n :param sess:\n :return: boolean for successful or not\n \"\"\"\n if not self._restore_optimistic:\n if self.restore_ckpt_file is None:\n logger.warn(\n Color.yellow('No checkpoint file for restore vars, checkpoint file is None', bold=True))\n return False\n self._restore_saver = tf.train.Saver(self._var_list, name='tk_restore')\n self._restore_saver.restore(sess, self.restore_ckpt_file)\n return True\n else:\n return self._optimistic_restore_model(sess)\n\n def _optimistic_restore_model(self, sess):\n \"\"\"\n restore weights of same names with model.\n :param sess:\n :return:\n \"\"\"\n if self.restore_ckpt_file is None:\n logger.warn(Color.yellow('No ckpt file for restore vars, ckpt file is None'))\n return False\n reader = tf.train.NewCheckpointReader(self.restore_ckpt_file)\n saved_shapes = reader.get_variable_to_shape_map()\n if self._var_list is None:\n restore_key2vars = {var.name.split(':')[0]: var for var in tf.global_variables()}\n elif isinstance(self._var_list, list):\n restore_key2vars = {var.name.split(':')[0]: var for var in self._var_list}\n elif isinstance(self._var_list, dict):\n restore_key2vars = self._var_list\n else:\n raise RuntimeError('type error {}'.format(self._var_list))\n assert len(restore_key2vars) > 0\n restore_key2vars = sorted([(k, v) for k, v in restore_key2vars.items() if k in saved_shapes])\n msg = []\n var_list = dict()\n with tf.variable_scope('', reuse=True):\n for key, var in restore_key2vars:\n var_shape = var.get_shape().as_list()\n if var_shape == saved_shapes[key]:\n var_list[key] = var\n var_name = var.name[:var.name.index(':')]\n msg.append('- restoring variable: {}'.format(var_name)\n if var_name == key else\n '- restoring variable {} from {}'.format(var_name, key))\n else:\n msg.append(Color.yellow(\n '- variable({}) with inconsistent shape: {}(graph) != {}(ckpt)'.format(\n key, var_shape, saved_shapes[key])\n ))\n if len(var_list) != 0:\n msg += ['- total variable count: {}'.format(len(var_list))]\n logger.info('\\n'.join(msg))\n saver = tf.train.Saver(var_list, name='tk_restore')\n saver.restore(sess, self.restore_ckpt_file)\n return True\n else:\n logger.warn(Color.yellow('No vars need to restore from file: {}'.format(self.restore_ckpt_file)))\n return False\n\n def __str__(self):\n content = 'RESTORE_OPTIMISTIC: %s' \\\n '\\nRESTORE_CHECKPOINT_FILE: %s' % (self._restore_optimistic, self.restore_ckpt_file)\n return content\n" ]
[ [ "tensorflow.variable_scope", "tensorflow.train.NewCheckpointReader", "tensorflow.global_variables", "tensorflow.train.Saver" ] ]
Owen-Gillespie/HuntMaster
[ "fcbf7b939122a943c706bfcbb38368b028802449" ]
[ "lib/matplotlib/stackplot.py" ]
[ "\"\"\"\nStacked area plot for 1D arrays inspired by Douglas Y'barbo's stackoverflow\nanswer:\nhttp://stackoverflow.com/questions/2225995/how-can-i-create-stacked-line-graph-with-matplotlib\n\n(http://stackoverflow.com/users/66549/doug)\n\n\"\"\"\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport six\nfrom six.moves import xrange\n\nfrom cycler import cycler\nimport numpy as np\n\n__all__ = ['stackplot']\n\n\ndef stackplot(axes, x, *args, **kwargs):\n \"\"\"Draws a stacked area plot.\n\n *x* : 1d array of dimension N\n\n *y* : 2d array of dimension MxN, OR any number 1d arrays each of dimension\n 1xN. The data is assumed to be unstacked. Each of the following\n calls is legal::\n\n stackplot(x, y) # where y is MxN\n stackplot(x, y1, y2, y3, y4) # where y1, y2, y3, y4, are all 1xNm\n\n Keyword arguments:\n\n *baseline* : ['zero', 'sym', 'wiggle', 'weighted_wiggle']\n Method used to calculate the baseline. 'zero' is just a\n simple stacked plot. 'sym' is symmetric around zero and\n is sometimes called `ThemeRiver`. 'wiggle' minimizes the\n sum of the squared slopes. 'weighted_wiggle' does the\n same but weights to account for size of each layer.\n It is also called `Streamgraph`-layout. More details\n can be found at http://leebyron.com/streamgraph/.\n\n\n *labels* : A list or tuple of labels to assign to each data series.\n\n\n *colors* : A list or tuple of colors. These will be cycled through and\n used to colour the stacked areas.\n All other keyword arguments are passed to\n :func:`~matplotlib.Axes.fill_between`\n\n Returns *r* : A list of\n :class:`~matplotlib.collections.PolyCollection`, one for each\n element in the stacked area plot.\n \"\"\"\n\n if len(args) == 1:\n y = np.atleast_2d(*args)\n elif len(args) > 1:\n y = np.row_stack(args)\n\n labels = iter(kwargs.pop('labels', []))\n\n colors = kwargs.pop('colors', None)\n if colors is not None:\n axes.set_prop_cycle(cycler('color', colors))\n\n baseline = kwargs.pop('baseline', 'zero')\n # Assume data passed has not been 'stacked', so stack it here.\n stack = np.cumsum(y, axis=0)\n\n if baseline == 'zero':\n first_line = 0.\n\n elif baseline == 'sym':\n first_line = -np.sum(y, 0) * 0.5\n stack += first_line[None, :]\n\n elif baseline == 'wiggle':\n m = y.shape[0]\n first_line = (y * (m - 0.5 - np.arange(0, m)[:, None])).sum(0)\n first_line /= -m\n stack += first_line\n\n elif baseline == 'weighted_wiggle':\n m, n = y.shape\n center = np.zeros(n)\n total = np.sum(y, 0)\n # multiply by 1/total (or zero) to avoid infinities in the division:\n inv_total = np.zeros_like(total)\n mask = total > 0\n inv_total[mask] = 1.0 / total[mask]\n increase = np.hstack((y[:, 0:1], np.diff(y)))\n below_size = total - stack\n below_size += 0.5 * y\n move_up = below_size * inv_total\n move_up[:, 0] = 0.5\n center = (move_up - 0.5) * increase\n center = np.cumsum(center.sum(0))\n first_line = center - 0.5 * total\n stack += first_line\n\n else:\n errstr = \"Baseline method %s not recognised. \" % baseline\n errstr += \"Expected 'zero', 'sym', 'wiggle' or 'weighted_wiggle'\"\n raise ValueError(errstr)\n\n # Color between x = 0 and the first array.\n color = axes._get_lines.get_next_color()\n coll = axes.fill_between(x, first_line, stack[0, :],\n facecolor=color, label=six.next(labels, None),\n **kwargs)\n coll.sticky_edges.y[:] = [0]\n r = [coll]\n\n # Color between array i-1 and array i\n for i in xrange(len(y) - 1):\n color = axes._get_lines.get_next_color()\n r.append(axes.fill_between(x, stack[i, :], stack[i + 1, :],\n facecolor=color,\n label= six.next(labels, None),\n **kwargs))\n return r\n" ]
[ [ "numpy.zeros_like", "numpy.atleast_2d", "numpy.zeros", "numpy.sum", "numpy.diff", "numpy.arange", "numpy.cumsum", "numpy.row_stack" ] ]
Whitemane/fluid-engine-dev
[ "fb2256badb80c04702db536b63b14754699038ca" ]
[ "src/tests/python_tests/particle_system_data_tests.py" ]
[ "\"\"\"\nCopyright (c) 2018 Doyub Kim\n\nI am making my contributions/submissions to this project solely in my personal\ncapacity and am not conveying any rights to any intellectual property of any\nthird parties.\n\"\"\"\n\nimport pyjet\nimport unittest\nimport numpy as np\n\n\nclass ParticleSystemData2Tests(unittest.TestCase):\n def testInit(self):\n ps = pyjet.ParticleSystemData2()\n self.assertEqual(ps.numberOfParticles, 0)\n\n ps2 = pyjet.ParticleSystemData2(100)\n self.assertEqual(ps2.numberOfParticles, 100)\n\n def testResize(self):\n ps = pyjet.ParticleSystemData2()\n ps.resize(12)\n self.assertEqual(ps.numberOfParticles, 12)\n\n def testAddScalarData(self):\n ps = pyjet.ParticleSystemData2()\n ps.resize(12)\n\n a0 = ps.addScalarData(2.0)\n a1 = ps.addScalarData(9.0)\n self.assertEqual(ps.numberOfParticles, 12)\n self.assertEqual(a0, 0)\n self.assertEqual(a1, 1)\n\n as0 = np.array(ps.scalarDataAt(a0))\n for val in as0:\n self.assertEqual(val, 2.0)\n\n as1 = np.array(ps.scalarDataAt(a1))\n for val in as1:\n self.assertEqual(val, 9.0)\n\n def testAddVectorData(self):\n ps = pyjet.ParticleSystemData2()\n ps.resize(12)\n\n a0 = ps.addVectorData((2.0, 4.0))\n a1 = ps.addVectorData((9.0, -2.0))\n self.assertEqual(ps.numberOfParticles, 12)\n self.assertEqual(a0, 3)\n self.assertEqual(a1, 4)\n\n as0 = np.array(ps.vectorDataAt(a0))\n for val in as0:\n self.assertEqual(val.tolist(), [2.0, 4.0])\n\n as1 = np.array(ps.vectorDataAt(a1))\n for val in as1:\n self.assertEqual(val.tolist(), [9.0, -2.0])\n\n def testAddParticles(self):\n ps = pyjet.ParticleSystemData2()\n ps.resize(12)\n\n ps.addParticles([(1.0, 2.0), (4.0, 5.0)],\n [(7.0, 8.0), (8.0, 7.0)],\n [(5.0, 4.0), (2.0, 1.0)])\n\n self.assertEqual(ps.numberOfParticles, 14)\n p = np.array(ps.positions)\n v = np.array(ps.velocities)\n f = np.array(ps.forces)\n\n self.assertEqual([1.0, 2.0], p[12].tolist())\n self.assertEqual([4.0, 5.0], p[13].tolist())\n self.assertEqual([7.0, 8.0], v[12].tolist())\n self.assertEqual([8.0, 7.0], v[13].tolist())\n self.assertEqual([5.0, 4.0], f[12].tolist())\n self.assertEqual([2.0, 1.0], f[13].tolist())\n\n\n\nclass ParticleSystemData3Tests(unittest.TestCase):\n def testInit(self):\n ps = pyjet.ParticleSystemData3()\n self.assertEqual(ps.numberOfParticles, 0)\n\n ps2 = pyjet.ParticleSystemData3(100)\n self.assertEqual(ps2.numberOfParticles, 100)\n\n def testResize(self):\n ps = pyjet.ParticleSystemData3()\n ps.resize(12)\n self.assertEqual(ps.numberOfParticles, 12)\n\n def testAddScalarData(self):\n ps = pyjet.ParticleSystemData3()\n ps.resize(12)\n\n a0 = ps.addScalarData(2.0)\n a1 = ps.addScalarData(9.0)\n self.assertEqual(ps.numberOfParticles, 12)\n self.assertEqual(a0, 0)\n self.assertEqual(a1, 1)\n\n as0 = np.array(ps.scalarDataAt(a0))\n for val in as0:\n self.assertEqual(val, 2.0)\n\n as1 = np.array(ps.scalarDataAt(a1))\n for val in as1:\n self.assertEqual(val, 9.0)\n\n def testAddVectorData(self):\n ps = pyjet.ParticleSystemData3()\n ps.resize(12)\n\n a0 = ps.addVectorData((2.0, 4.0, -1.0))\n a1 = ps.addVectorData((9.0, -2.0, 5.0))\n self.assertEqual(ps.numberOfParticles, 12)\n self.assertEqual(a0, 3)\n self.assertEqual(a1, 4)\n\n as0 = np.array(ps.vectorDataAt(a0))\n for val in as0:\n self.assertEqual(val.tolist(), [2.0, 4.0, -1.0])\n\n as1 = np.array(ps.vectorDataAt(a1))\n for val in as1:\n self.assertEqual(val.tolist(), [9.0, -2.0, 5.0])\n\n def testAddParticles(self):\n ps = pyjet.ParticleSystemData3()\n ps.resize(12)\n\n ps.addParticles([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)],\n [(7.0, 8.0, 9.0), (8.0, 7.0, 6.0)],\n [(5.0, 4.0, 3.0), (2.0, 1.0, 3.0)])\n\n self.assertEqual(ps.numberOfParticles, 14)\n p = np.array(ps.positions)\n v = np.array(ps.velocities)\n f = np.array(ps.forces)\n\n self.assertEqual([1.0, 2.0, 3.0], p[12].tolist())\n self.assertEqual([4.0, 5.0, 6.0], p[13].tolist())\n self.assertEqual([7.0, 8.0, 9.0], v[12].tolist())\n self.assertEqual([8.0, 7.0, 6.0], v[13].tolist())\n self.assertEqual([5.0, 4.0, 3.0], f[12].tolist())\n self.assertEqual([2.0, 1.0, 3.0], f[13].tolist())\n\n\ndef main():\n pyjet.Logging.mute()\n unittest.main()\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.array" ] ]
penguinmenac3/leanai
[ "6d26575b248ff03c4a24009cd82f26ea99d96d15", "6d26575b248ff03c4a24009cd82f26ea99d96d15", "6d26575b248ff03c4a24009cd82f26ea99d96d15" ]
[ "leanai/core/indexed_tensor_helpers.py", "examples/coco_faster_rcnn.py", "tests/model/layers/test_flatten_vectorize.py" ]
[ "import torch\nimport numpy as np\n\n\ndef map_per_batch(fun, values, batch_indices):\n result = []\n for start, stop, value_slice in sliced_per_batch(values, batch_indices):\n result.append(fun(start, stop, value_slice))\n return torch.cat(result)\n\n\ndef sliced_per_batch(values, batch_indices):\n slices = torch.where(batch_indices[:-1] - batch_indices[1:] != 0)[0] + 1\n slices = slices.tolist()\n slices = zip([0] + slices, slices + [batch_indices.shape[0]])\n for start, stop in slices:\n yield start, stop, values[start:stop]\n\n\ndef sliced_per_batch_np(values, batch_indices):\n slices = np.where(batch_indices[:-1] - batch_indices[1:] != 0)[0] + 1\n slices = slices.tolist()\n slices = zip([0] + slices, slices + [batch_indices.shape[0]])\n for start, stop in slices:\n yield start, stop, values[start:stop]\n", "\"\"\"doc\n# Example: COCO using Faster RCNN\n\nThis example shows how to solve COCO using Faster RCNN.\n\nFirst we import everything, then we write the config, then we implement the loss and finaly we tell leanai to run this.\n\"\"\"\nfrom typing import NamedTuple, Tuple\nimport torch\nimport numpy as np\nfrom torch.optim import SGD, Optimizer\n\nfrom leanai.core.cli import run\nfrom leanai.core.experiment import Experiment\nfrom leanai.data.dataloader import IndexedArray, IndexArray\nfrom leanai.data.dataset import SequenceDataset\nfrom leanai.data.datasets import COCODataset\nfrom leanai.data.transformer import Transformer\nfrom leanai.training.losses import SumLoss, DetectionLoss\nfrom leanai.model.configs import buildFasterRCNN\n\n\nDetectionInput = NamedTuple(\"DetectionInput\", image=np.ndarray)\nDetectionOutput = NamedTuple(\"DetectionOutput\", fg_bg_classes=np.ndarray, class_ids=np.ndarray, boxes=np.ndarray)\nFasterRCNNInput = NamedTuple(\"FasterRCNNInput\", image=np.ndarray, extra_proposals=np.ndarray, extra_proposal_indices=np.ndarray)\nFasterRCNNOutput = NamedTuple(\"FasterRCNNOutput\", fg_bg_classes=np.ndarray, class_ids=np.ndarray, boxes=np.ndarray, batch_indices=np.ndarray)\n\n\nclass COCOFasterRCNNExperiment(Experiment):\n def __init__(\n self,\n data_path: str = \".datasets/COCO\",\n data_version = \"2014\",\n data_image_size = (800, 600),\n learning_rate=1e-3,\n batch_size=2,\n num_workers=12,\n max_epochs=10,\n model_num_classes=81,\n model_log_delta_preds=False,\n mode=\"train\",\n ):\n super().__init__()\n self.save_hyperparameters()\n self.model = buildFasterRCNN(num_classes=model_num_classes, log_deltas=model_log_delta_preds)\n self.loss = self.create_loss(model_log_delta_preds)\n self.example_input_array = self.get_example_input_array()\n\n def create_loss(self, model_log_delta_preds):\n rpn_loss = DetectionLoss(\n parent=self,\n pred_anchors=\"rpn_anchors\",\n pred_boxes=\"rpn_deltas\",\n pred_class_ids=\"rpn_class_ids\",\n pred_indices=\"rpn_indices\",\n target_boxes=\"boxes\",\n target_class_ids=\"fg_bg_classes\",\n target_indices=\"batch_indices\",\n lower_tresh=0.3,\n upper_tresh=0.5,\n delta_preds=not model_log_delta_preds,\n log_delta_preds=model_log_delta_preds\n )\n final_loss = DetectionLoss(\n parent=self,\n pred_anchors=\"final_anchors\",\n pred_boxes=\"final_deltas\",\n pred_class_ids=\"final_class_ids\",\n pred_indices=\"final_indices\",\n target_boxes=\"boxes\",\n target_class_ids=\"class_ids\",\n target_indices=\"batch_indices\",\n lower_tresh=0.5,\n upper_tresh=0.7,\n delta_preds=not model_log_delta_preds,\n log_delta_preds=model_log_delta_preds\n )\n return SumLoss(parent=self, rpn=rpn_loss, final=final_loss)\n\n def load_dataset(self, split) -> SequenceDataset:\n dataset = COCODataset(\n split=split,\n data_path=self.hparams.data_path,\n DatasetInput=DetectionInput,\n DatasetOutput=DetectionOutput,\n data_version=self.hparams.data_version,\n data_image_size=self.hparams.data_image_size\n )\n transformer = FasterRCNNTransformer(data_inject_gt_proposals=True, **self.hparams)\n dataset.transformers.append(transformer)\n return dataset\n\n def get_example_input_array(self) -> FasterRCNNInput:\n example_shape = (self.hparams.batch_size, 600, 800, 3)\n return FasterRCNNInput(\n image=torch.zeros(example_shape, dtype=torch.float32),\n extra_proposals=torch.zeros((1, 4), dtype=torch.float32),\n extra_proposal_indices=torch.zeros((1,), dtype=torch.int32),\n )\n\n def configure_optimizers(self) -> Optimizer:\n # Create an optimizer to your liking.\n return SGD(self.parameters(), lr=self.hparams.learning_rate, momentum=0.9)\n\n\nclass FasterRCNNTransformer(Transformer):\n DetectionSample = Tuple[DetectionInput, DetectionOutput]\n FasterRCNNSample = Tuple[FasterRCNNInput, FasterRCNNOutput]\n\n def __init__(self, data_inject_gt_proposals=False, **hparams):\n super().__init__()\n self.data_inject_gt_proposals = data_inject_gt_proposals\n\n def __call__(self, sample: DetectionSample) -> FasterRCNNSample:\n inp, outp = sample\n batch_indices = np.zeros_like(outp.class_ids, dtype=np.int32)\n if self.data_inject_gt_proposals:\n inp = FasterRCNNInput(\n image=inp.image,\n extra_proposals=IndexedArray(outp.boxes),\n extra_proposal_indices=IndexArray(batch_indices)\n )\n else:\n inp = FasterRCNNInput(\n image=inp.image,\n extra_proposals=IndexedArray(np.array([], dtype=np.float32).reshape(0, 4)),\n extra_proposal_indices=IndexArray(np.array([], dtype=np.int32).reshape(0,))\n )\n outp = FasterRCNNOutput(\n fg_bg_classes=IndexedArray(outp.fg_bg_classes),\n class_ids=IndexedArray(outp.class_ids),\n boxes=IndexedArray(outp.boxes),\n batch_indices=IndexArray(batch_indices)\n )\n return inp, outp\n\n @property\n def version(self):\n return \"V1\"\n\n\nif __name__ == \"__main__\":\n # python examples/coco_faster_rcnn.py --data_path=$DATA_PATH/COCO --output=$RESULTS_PATH --name=\"COCOFasterRCNN\"\n run(COCOFasterRCNNExperiment)\n", "import unittest\nfrom torch import tensor\nfrom leanai.model.layers import VectorizeWithBatchIndices\n\n\nclass TestFlattenVectorizedWithBatchIndices(unittest.TestCase):\n def setUp(self) -> None:\n self.input = tensor([\n # Batches\n [\n #Channels\n [\n #HW\n [1, 2,],\n [3, 4,]\n ], [\n #HW\n [5, 6,],\n [7, 8,]\n ],\n ],\n [\n #Channels\n [\n #HW\n [9, 10,],\n [11, 12,]\n ], [\n #HW\n [13, 14,],\n [15, 16,]\n ],\n ],\n ])\n self.output = tensor([\n #NC\n [1, 5],\n [2, 6],\n [3, 7],\n [4, 8],\n [9, 13],\n [10, 14],\n [11, 15],\n [12, 16]\n ])\n self.indices = tensor([0,0,0,0,1,1,1,1])\n\n def test_once(self):\n self.layer = VectorizeWithBatchIndices()\n out, indices = self.layer(self.input)\n self.assertResults(out, indices)\n\n def test_multiple(self):\n self.layer = VectorizeWithBatchIndices()\n out, indices = self.layer(self.input)\n self.assertResults(out, indices)\n out, indices = self.layer(self.input)\n self.assertResults(out, indices)\n out, indices = self.layer(self.input)\n self.assertResults(out, indices)\n\n def test_multiple_gpu(self):\n self.layer = VectorizeWithBatchIndices()\n self.input = self.input.to(\"cuda\")\n self.output = self.output.to(\"cuda\")\n self.indices = self.indices.to(\"cuda\")\n \n out, indices = self.layer(self.input)\n self.assertResults(out, indices)\n out, indices = self.layer(self.input)\n self.assertResults(out, indices)\n out, indices = self.layer(self.input)\n self.assertResults(out, indices)\n\n def test_change_device(self):\n self.layer = VectorizeWithBatchIndices()\n out, indices = self.layer(self.input)\n self.assertResults(out, indices)\n\n self.input = self.input.to(\"cuda\")\n self.output = self.output.to(\"cuda\")\n self.indices = self.indices.to(\"cuda\")\n self.layer = self.layer.to(\"cuda\")\n out, indices = self.layer(self.input)\n self.assertResults(out, indices)\n\n self.input = self.input.to(\"cpu\")\n self.output = self.output.to(\"cpu\")\n self.indices = self.indices.to(\"cpu\")\n self.layer = self.layer.to(\"cpu\")\n out, indices = self.layer(self.input)\n self.assertResults(out, indices)\n \n def assertResults(self, out, indices):\n self.assertEqual(out.shape[0], indices.shape[0])\n self.assertListEqual(list(out.shape), list(self.output.shape))\n self.assertListEqual(list(indices.shape), list(self.indices.shape))\n self.assertTrue((out == self.output).all())\n self.assertTrue((indices == self.indices).all())\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.where", "torch.cat", "torch.where" ], [ "torch.zeros", "numpy.array", "numpy.zeros_like" ], [ "torch.tensor" ] ]
avalonstrel/SketchBERT
[ "1aeef221f299a5250243b1f6e23c02280d92f5d6" ]
[ "models/SketchTransformer/models/networks.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.utils.spectral_norm as spectral_norm\nimport math\nimport numpy as np\nimport torchvision.models as models\n\nfrom modules.networks import get_pad\nfrom torch.distributions.multivariate_normal import MultivariateNormal\nfrom util.utils import length_to_mask\n\ndef get_conv_layer(in_channel, out_channel, gan_type='sn_gan', **kwargs):\n if gan_type == 'sn_gan':\n return spectral_norm(nn.Conv2d(in_channel, out_channel, **kwargs))\n else:\n return nn.Conv2d(in_channel, out_channel, **kwargs)\n\ndef get_conv_block(in_channel, out_channel, gan_type='sn_gan', normalization='instance', activation='leakyrelu', **kwargs):\n block = []\n block.append(get_conv_layer(in_channel, out_channel, gan_type=gan_type, **kwargs))\n if normalization == 'instance':\n block.append(nn.InstanceNorm2d(out_channel))\n\n if activation == 'leakyrelu':\n block.append(nn.LeakyReLU())\n return nn.Sequential(*block)\n\ndef gelu(x):\n \"\"\"Implementation of the gelu activation function.\n For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):\n 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))\n Also see https://arxiv.org/abs/1606.08415\n \"\"\"\n return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))\n\n# try:\n# from apex.normalization.fused_layer_norm import FusedLayerNorm as SketchLayerNorm\n# except ImportError:\n# logger.info(\"Better speed can be achieved with apex installed from https://www.github.com/nvidia/apex .\")\nclass SketchLayerNorm(nn.Module):\n def __init__(self, hidden_size, eps=1e-12):\n \"\"\"\n Construct a layernorm module in the TF style (epsilon inside the square root).\n \"\"\"\n super(SketchLayerNorm, self).__init__()\n self.weight = nn.Parameter(torch.ones(hidden_size))\n self.bias = nn.Parameter(torch.zeros(hidden_size))\n self.variance_epsilon = eps\n\n def forward(self, x):\n u = x.mean(-1, keepdim=True)\n s = (x - u).pow(2).mean(-1, keepdim=True)\n x = (x - u) / torch.sqrt(s + self.variance_epsilon)\n return self.weight * x + self.bias\n\nACT2FN = {\"gelu\": gelu, \"relu\": torch.nn.functional.relu}#, \"swish\": swish\nNORM2FN = {'BN1d':nn.BatchNorm1d, 'BN2d':nn.BatchNorm2d, 'LN':nn.LayerNorm}\n\nclass SketchSelfAttention(nn.Module):\n '''\n Implementation for self attention in Sketch.\n The input will be a K-Dim feature.\n Input Parameters:\n config[dict]:\n hidden_dim[int]: The dimension of input hidden embeddings in the self attention, hidden diension is equal to the output dimension\n num_heads[int]: The number of heads\n attention_probs[float]: probability parameter for dropout\n '''\n def __init__(self, num_heads, hidden_dim, attention_dropout_prob):\n super(SketchSelfAttention, self).__init__()\n if hidden_dim % num_heads != 0:\n raise ValueError(\n \"The hidden size (%d) is not a multiple of the number of attention \"\n \"heads (%d)\" % (hidden_dim, num_heads))\n self.hidden_dim = hidden_dim\n self.num_heads = num_heads\n #self.attention_dropout_prob = config.attention_dropout_prob\n # Calculation for intermeidate parameters\n self.head_dim = int(self.hidden_dim / self.num_heads)\n self.all_head_dim = self.head_dim * self.num_heads\n self.scale_factor = math.sqrt(self.head_dim)\n\n self.query = nn.Linear(self.hidden_dim, self.all_head_dim)\n self.key = nn.Linear(self.hidden_dim, self.all_head_dim)\n self.value = nn.Linear(self.hidden_dim, self.all_head_dim)\n self.dropout = nn.Dropout(attention_dropout_prob)\n self.multihead_output = None\n\n def transpose_(self, x):\n '''\n Transpose Function for simplicity.\n '''\n new_x_shape = x.size()[:-1] + (self.num_heads , self.head_dim)\n x = x.view(*new_x_shape)\n return x.permute(0, 2, 1, 3)\n\n def forward(self, hidden_states, attention_mask, head_mask=None, output_attentions=False, keep_multihead_output=False):\n '''\n Input:\n hidden_states[batch, seq_len, hidden_dim]\n attention_mask[batch, 1, 1, seq_len]\n Output:\n context_states[batch, seq_len, hidden_dim]\n attention_probs[seq_len, hidden_dim]\n '''\n # Get query, key, value together\n query = self.query(hidden_states) # [batch, seq_len, all_head_dim]\n key = self.key(hidden_states) # [batch, seq_len, all_head_dim]\n value = self.value(hidden_states) # [batch, seq_len, all_head_dim]\n\n # tranpose the query, key, value into multi heads[batch, seq_len, ]\n multi_query = self.transpose_(query) # [batch, num_heads, seq_len, head_dim]\n multi_key = self.transpose_(key) # [batch, num_heads, seq_len, head_dim]\n multi_value = self.transpose_(value) # [batch, num_heads, seq_len, head_dim]\n\n # Calculate Attention maps\n attention_scores = torch.matmul(multi_query, multi_key.transpose(-1, -2))\n attention_scores = attention_scores / self.scale_factor\n #print(attention_scores.size(), attention_mask.size())\n attention_scores = attention_scores + attention_mask\n attention_probs = F.softmax(attention_scores, dim=-1)\n attention_probs = self.dropout(attention_probs)\n\n if head_mask is not None:\n attention_probs = attention_probs * head_mask\n # Compute states values\n context_states = torch.matmul(attention_probs, multi_value)\n\n if keep_multihead_output:\n self.multihead_output = context_states\n self.multihead_output.retain_grad()\n\n context_states = context_states.permute(0,2,1,3)\n context_states = context_states.contiguous().view(context_states.size()[:-2]+(-1,)) #view(context_states.size()[:-2]+ (self.all_head_dim,))\n\n if output_attentions:\n return context_states, attention_probs\n return context_states\n\n\nclass SketchOutput(nn.Module):\n def __init__(self, input_dim, output_dim, attention_norm_type, output_dropout_prob):\n super(SketchOutput, self).__init__()\n self.fc = nn.Linear(input_dim, output_dim)\n\n if attention_norm_type not in NORM2FN:\n raise ValueError(\n \"The attention normalization is not in standard normalization types.\")\n self.norm = NORM2FN[attention_norm_type](output_dim)\n self.dropout = nn.Dropout(output_dropout_prob)\n '''\n Input:\n hidden_states[]:\n\n Output:\n hidden_states[]:\n '''\n def forward(self, hidden_states, input_states):\n hidden_states = self.fc(hidden_states)\n hidden_states = self.dropout(hidden_states)\n #print(hidden_states.size())\n hidden_states = self.norm(hidden_states+input_states)\n return hidden_states\n\n\nclass SketchMultiHeadAttention(nn.Module):\n def __init__(self, num_heads, hidden_dim,\n attention_norm_type, attention_dropout_prob, hidden_dropout_prob,):\n super(SketchMultiHeadAttention, self).__init__()\n self.attention = SketchSelfAttention(num_heads, hidden_dim, attention_dropout_prob)\n self.output = SketchOutput(hidden_dim, hidden_dim, attention_norm_type, hidden_dropout_prob)\n\n def forward(self, hidden_states, attention_mask, head_mask=None, output_attentions=False):\n input_states = hidden_states\n #print(hidden_states)\n hidden_states = self.attention(hidden_states, attention_mask, head_mask=head_mask)\n #print(hidden_states)\n if output_attentions:\n hidden_states, attention_probs = hidden_states\n\n output_states = self.output(hidden_states, input_states)\n if output_attentions:\n return output_states, attention_probs\n\n return output_states\n\n\nclass SketchIntermediate(nn.Module):\n def __init__(self, hidden_dim, inter_dim, inter_activation):\n super(SketchIntermediate, self).__init__()\n self.fc = nn.Linear(hidden_dim, inter_dim)\n self.activation = ACT2FN[inter_activation]\n\n\n def forward(self, hidden_states):\n\n hidden_states = hidden_states.to(next(self.fc.parameters()).device)\n\n inter_states = self.fc(hidden_states.contiguous())\n inter_states = self.activation(inter_states)\n return inter_states\n\nclass SketchLayer(nn.Module):\n '''\n A transformer layer for sketch bert\n '''\n def __init__(self, num_heads, hidden_dim, inter_dim,\n attention_norm_type, inter_activation, attention_dropout_prob,\n hidden_dropout_prob, output_dropout_prob,):\n super(SketchLayer, self).__init__()\n self.attention = SketchMultiHeadAttention(num_heads, hidden_dim,\n attention_norm_type, attention_dropout_prob, hidden_dropout_prob,)\n self.inter_layer = SketchIntermediate(hidden_dim, inter_dim, inter_activation)\n self.output = SketchOutput(inter_dim, hidden_dim, attention_norm_type, output_dropout_prob)\n\n\n '''\n Input:\n hidden_states[batch, seq_len, hidden_dim]:\n attention_mask[batch, seq_len]\n\n\n '''\n def forward(self, hidden_states, attention_mask, head_mask=None, output_attentions=False):\n\n hidden_states = self.attention(hidden_states, attention_mask, head_mask)\n if output_attentions:\n hidden_states, attention_probs = hidden_states\n\n inter_states = self.inter_layer(hidden_states)\n output_states = self.output(inter_states, hidden_states)\n\n if output_attentions:\n return output_states, attention_probs\n\n return output_states\n\nclass SketchSegmentLayer(nn.Module):\n '''\n A transformer layer for sketch bert\n '''\n def __init__(self, num_heads, hidden_dim, inter_dim, max_segment,\n segment_atten_type, attention_norm_type, inter_activation, attention_dropout_prob,\n hidden_dropout_prob, output_dropout_prob,):\n super(SketchSegmentLayer, self).__init__()\n self.max_segment = max_segment\n self.inter_dim = inter_dim\n self.segment_atten_type = segment_atten_type\n self.local_attention = SketchMultiHeadAttention(num_heads, hidden_dim,\n attention_norm_type, attention_dropout_prob, hidden_dropout_prob,)\n self.segment_attention = SketchMultiHeadAttention(num_heads, hidden_dim,\n attention_norm_type, attention_dropout_prob, hidden_dropout_prob,)\n self.local_inter_layer = SketchIntermediate(hidden_dim, inter_dim//2, inter_activation)\n self.seg_inter_layer = SketchIntermediate(hidden_dim, inter_dim//2, inter_activation)\n self.output = SketchOutput(inter_dim, hidden_dim, attention_norm_type, output_dropout_prob)\n\n\n def get_seg_states(self, hidden_states, segment_index):\n '''\n Input:\n hidden_states[batch, seq_len, hidden_dim]\n segment_index[batch, seq_len]\n '''\n seg_states = torch.zeros(hidden_states.size(0), self.max_segment, hidden_states.size(2)).to(hidden_states.device)\n length = (segment_index==0).sum(dim=1)\n length_mask = length_to_mask(length, max_len=self.max_segment, dtype=torch.float)\n seg_states[length_mask==1,:] = hidden_states[segment_index==0,:]\n return seg_states, length_mask\n\n def forward(self, hidden_states, attention_mask, segments, segment_index, head_mask=None, output_attentions=False):\n '''\n Input:\n hidden_states[batch, seg_len, hidden_dim]:\n attention_mask[batch, seg_len](segment-based)\n segments[batch, seg_len]:\n segment_index[batch, seq_len]\n\n '''\n # Local Attention\n local_states = self.local_attention(hidden_states, attention_mask, head_mask)\n if output_attentions:\n local_states, attention_probs = local_states #[batch, seq_len, hidden_dim]\n input_prefix = hidden_states.size(1) - segment_index.size(1)\n\n # Segment Level Attention\n seg_states, seg_atten_mask = self.get_seg_states(local_states[:,input_prefix:,:], segment_index)\n if self.segment_atten_type == 'multi':\n seg_states = self.segment_attention(seg_states, seg_atten_mask.unsqueeze(1).unsqueeze(2), head_mask)\n if output_attentions:\n seg_states, attention_probs = seg_states #[batch, seq_len, hidden_dim]\n\n # Concatenate\n local_inter_states = self.local_inter_layer(local_states)\n seg_inter_states = self.seg_inter_layer(seg_states)\n aug_seg_inter_states = torch.gather(seg_inter_states, 1, (segments[:,input_prefix:]-2).view(segments.size(0), -1, 1).repeat(1,1, seg_inter_states.size(2)))\n inter_states = torch.zeros(local_inter_states.size(0), local_inter_states.size(1), self.inter_dim).to(local_inter_states.device)\n #print(hidden_states.size(), local_states.size(), local_inter_states.size())\n inter_states[:,:,:self.inter_dim//2] = local_inter_states\n inter_states[:,input_prefix:, self.inter_dim//2:] = aug_seg_inter_states\n inter_states[:,:input_prefix, self.inter_dim//2:] = seg_inter_states.sum(dim=1, keepdim=True)\n\n output_states = self.output(inter_states, hidden_states)\n\n if output_attentions:\n return output_states, attention_probs\n\n return output_states\n\n\ndef setting2dict(paras, setting):\n paras['num_heads'] = setting[0]\n paras['hidden_dim'] = setting[1]\n paras['inter_dim'] = setting[2]\n\nclass SketchEncoder(nn.Module):\n '''\n layers_setting[list]: [[12, ], []]\n '''\n def __init__(self, layers_setting,\n attention_norm_type, inter_activation, attention_dropout_prob,\n hidden_dropout_prob, output_dropout_prob,):\n super(SketchEncoder, self).__init__()\n layer_paras = {\n 'attention_norm_type':attention_norm_type, 'inter_activation':inter_activation, 'attention_dropout_prob':attention_dropout_prob,\n 'hidden_dropout_prob':hidden_dropout_prob, 'output_dropout_prob':output_dropout_prob}\n self.layers = []\n for layer_setting in layers_setting:\n setting2dict(layer_paras, layer_setting)\n self.layers.append(SketchLayer(**layer_paras))\n self.layers = nn.ModuleList(self.layers)\n\n def forward(self, input_states, attention_mask, head_mask=None, output_all_states=False, output_attentions=False, keep_multihead_output=False):\n all_states = []\n all_attention_probs = []\n hidden_states = input_states\n for layer in self.layers:\n hidden_states = layer(hidden_states, attention_mask, head_mask=head_mask, output_attentions=output_attentions)\n if output_attentions:\n hidden_states, attention_probs = hidden_states\n all_attention_probs.append(attention_probs)\n\n if output_all_states:\n all_states.append(hidden_states)\n\n if not output_all_states:\n all_states.append(hidden_states)\n\n if output_attentions:\n return all_states, all_attention_probs\n\n return all_states\n\n\nclass SketchALEncoder(nn.Module):\n '''\n A Lite BERT: Parameter Sharing\n layers_setting[list]: [[12, ], []]\n '''\n def __init__(self, layers_setting,\n attention_norm_type, inter_activation, attention_dropout_prob,\n hidden_dropout_prob, output_dropout_prob,):\n super(SketchALEncoder, self).__init__()\n layer_paras = {\n 'attention_norm_type':attention_norm_type, 'inter_activation':inter_activation, 'attention_dropout_prob':attention_dropout_prob,\n 'hidden_dropout_prob':hidden_dropout_prob, 'output_dropout_prob':output_dropout_prob}\n setting2dict(layer_paras, layers_setting[0])\n self.sketch_layer = SketchLayer(**layer_paras)\n self.layers = []\n for layer_setting in layers_setting:\n self.layers.append(self.sketch_layer)\n #self.layers = nn.ModuleList(self.layers)\n\n def forward(self, input_states, attention_mask, head_mask=None, output_all_states=False, output_attentions=False, keep_multihead_output=False):\n all_states = []\n all_attention_probs = []\n hidden_states = input_states\n for layer in self.layers:\n hidden_states = layer(hidden_states, attention_mask, head_mask=head_mask, output_attentions=output_attentions)\n if output_attentions:\n hidden_states, attention_probs = hidden_states\n all_attention_probs.append(attention_probs)\n\n if output_all_states:\n all_states.append(hidden_states)\n\n if not output_all_states:\n all_states.append(hidden_states)\n\n if output_attentions:\n return all_states, all_attention_probs\n\n return all_states\n\nclass SketchSegmentEncoder(nn.Module):\n '''\n layers_setting[list]: [[12, ], []]\n '''\n def __init__(self, layers_setting, max_segment, segment_atten_type,\n attention_norm_type, inter_activation, attention_dropout_prob,\n hidden_dropout_prob, output_dropout_prob,):\n super(SketchSegmentEncoder, self).__init__()\n layer_paras = {\n 'max_segment':max_segment, 'segment_atten_type':segment_atten_type, 'attention_norm_type':attention_norm_type, 'inter_activation':inter_activation, 'attention_dropout_prob':attention_dropout_prob,\n 'hidden_dropout_prob':hidden_dropout_prob, 'output_dropout_prob':output_dropout_prob}\n self.layers = []\n self.max_segment = max_segment\n for layer_setting in layers_setting:\n setting2dict(layer_paras, layer_setting)\n self.layers.append(SketchSegmentLayer(**layer_paras))\n self.layers = nn.ModuleList(self.layers)\n\n def forward(self, input_states, attention_mask, segments, segment_index, head_mask=None, output_all_states=False, output_attentions=False, keep_multihead_output=False):\n all_states = []\n all_attention_probs = []\n hidden_states = input_states\n for layer in self.layers:\n hidden_states = layer(hidden_states, attention_mask, segments, segment_index, head_mask=head_mask, output_attentions=output_attentions)\n if output_attentions:\n hidden_states, attention_probs = hidden_states\n all_attention_probs.append(attention_probs)\n\n if output_all_states:\n all_states.append(hidden_states)\n\n if not output_all_states:\n all_states.append(hidden_states)\n\n if output_attentions:\n return all_states, all_attention_probs\n\n return all_states\n\nclass SketchEmbedding(nn.Module):\n def __init__(self, input_dim, hidden_dim):\n super(SketchEmbedding, self).__init__()\n self.embedding = nn.Linear(input_dim, hidden_dim)\n\n def forward(self, input_states):\n return self.embedding(input_states)\n\nclass SketchDiscreteEmbedding(nn.Module):\n '''\n max_size[tuple](x_length, y_length)\n '''\n def __init__(self, max_size, type_size, hidden_dim, pool_type):\n super(SketchDiscreteEmbedding, self).__init__()\n self.x_embedding = nn.Embedding(2*max_size[0]+2, hidden_dim//2)\n self.y_embedding = nn.Embedding(2*max_size[1]+2, hidden_dim//2)\n self.type_embedding = nn.Embedding(type_size+1, hidden_dim)\n assert pool_type in ['sum', 'con']\n self.pool_type = pool_type\n\n '''\n input_states[batch, seq_len, 3(input_dim)](Inputs are encoded as discrete type)\n '''\n def forward(self, input_states):\n input_states = input_states.to(dtype=torch.long)\n input_states = input_states + 1\n #print(input_states[0,0,:], torch.min(input_states), torch.max(input_states))\n x_hidden = self.x_embedding(input_states[:,:,0])\n y_hidden = self.y_embedding(input_states[:,:,1])\n #print(x_hidden.size(), y_hidden.size())\n axis_hidden = torch.cat([x_hidden, y_hidden], dim=2)\n\n type_hidden = self.type_embedding(input_states[:,:,2])\n\n if self.pool_type == 'sum':\n return axis_hidden + type_hidden\n elif self.pool_type == 'con':\n return torch.cat([axis_hidden, type_hidden], dim=2)\n\nclass SketchSinPositionEmbedding(nn.Module):\n def __init__(self, max_length, pos_hidden_dim):\n super(SketchSinPositionEmbedding, self).__init__()\n self.pos_embedding_matrix = torch.zeros(max_length, pos_hidden_dim)\n pos_vector = torch.arange(max_length).view(max_length, 1).type(torch.float)\n dim_vector = torch.arange(pos_hidden_dim).type(torch.float) + 1.0\n #print((pos_vector / (dim_vector[::2] / 2).view(1, -1)).size(), self.pos_embedding_matrix[:,::2].size())\n self.pos_embedding_matrix[:,::2] = torch.sin(pos_vector / (dim_vector[::2] / 2).view(1, -1))\n self.pos_embedding_matrix[:,1::2] = torch.cos(pos_vector / ((dim_vector[1::2] - 1) / 2).view(1, -1))\n #print(self.pos_embedding_matrix)\n '''\n Input:\n position_labels[batch, seq_len]\n Output:\n position_states[batch, seq_len, pos_hidden_dim]\n '''\n def forward(self, position_labels):\n return self.pos_embedding_matrix[position_labels.view(-1),:].view(position_labels.size(0), position_labels.size(1), -1)\n\nclass SketchLearnPositionEmbedding(nn.Module):\n def __init__(self, max_length, pos_hidden_dim):\n super(SketchLearnPositionEmbedding, self).__init__()\n print(max_length, pos_hidden_dim)\n self.pos_embedding = nn.Embedding(max_length, pos_hidden_dim)\n\n '''\n Input:\n position_labels[batch, seq_len]\n Output:\n position_states[batch, seq_len, pos_hidden_dim]\n '''\n def forward(self, position_labels):\n return self.pos_embedding(position_labels)\n\nclass SketchEmbeddingRefineNetwork(nn.Module):\n '''\n The module to upsample the embedding feature, idea from the ALBERT: Factorized Embedding\n '''\n def __init__(self, out_dim, layers_dim):\n super(SketchEmbeddingRefineNetwork, self).__init__()\n self.layers = []\n layers_dim = layers_dim.copy()\n layers_dim.append(out_dim)\n\n for i in range(len(layers_dim)-1):\n self.layers.append(nn.Linear(layers_dim[i], layers_dim[i+1]))\n self.layers = nn.ModuleList(self.layers)\n\n def forward(self, input_state):\n x = input_state\n for layer in self.layers:\n x = layer(x)\n return x\n\nclass SketchTransformerModel(nn.Module):\n '''\n Input:\n layers_setting[list]\n input_dim[int]\n max_length[int]\n position_type[str]\n attention_norm_type[str]\n inter_activation[str]\n attention_dropout_prob[float]\n hidden_dropout_prob[float]\n output_dropout_prob[float]\n '''\n def __init__(self, model_type, layers_setting, embed_layers_setting, input_dim, max_length, max_size, type_size,\n position_type, segment_type, sketch_embed_type, embed_pool_type, attention_norm_type, inter_activation, attention_dropout_prob,\n hidden_dropout_prob, output_dropout_prob):\n super(SketchTransformerModel, self).__init__()\n self.layers_setting = layers_setting\n self.num_hidden_layers = len(layers_setting)\n self.embed_pool_type = embed_pool_type\n assert sketch_embed_type in ['linear', 'discrete']\n\n if sketch_embed_type == 'linear':\n self.embedding = SketchEmbedding(input_dim, embed_layers_setting[0])\n elif sketch_embed_type == 'discrete':\n self.embedding = SketchDiscreteEmbedding(max_size, type_size, embed_layers_setting[0], embed_pool_type)\n assert position_type in ['sin', 'learn', 'none']\n\n if position_type == 'sin':\n self.pos_embedding = SketchSinPositionEmbedding(max_length, embed_layers_setting[0])\n elif position_type == 'learn':\n self.pos_embedding = SketchLearnPositionEmbedding(max_length, embed_layers_setting[0])\n else:\n self.pos_embedding = None\n if segment_type == 'learn':\n self.segment_embedding = SketchLearnPositionEmbedding(max_length, embed_layers_setting[0])\n else:\n self.segment_embedding = None\n\n self.embed_refine_net = SketchEmbeddingRefineNetwork(layers_setting[0][1], embed_layers_setting)\n\n assert model_type in ['albert', 'bert']\n if model_type == 'albert':\n self.encoder = SketchALEncoder(layers_setting,\n attention_norm_type, inter_activation, attention_dropout_prob,\n hidden_dropout_prob, output_dropout_prob)\n elif model_type == 'bert':\n self.encoder = SketchEncoder(layers_setting,\n attention_norm_type, inter_activation, attention_dropout_prob,\n hidden_dropout_prob, output_dropout_prob)\n\n def load_model(self, state_dict, own_rel_in_input, own_cls_in_input, pre_rel_in_input, pre_cls_in_input):\n own_state = self.state_dict()\n for k, v in own_state.items():\n if k == 'pos_embedding.pos_embedding.weight':\n own_pos_size = v.size(0)\n seq_len = own_pos_size - own_rel_in_input - own_cls_in_input\n pretrained_pos_size = state_dict[k].size(0)\n own_start_ind = int(own_rel_in_input+own_cls_in_input)\n pre_start_ind = int(pre_rel_in_input+pre_cls_in_input)\n seq_len = min(seq_len, state_dict[k].size(0)-pre_start_ind)\n own_state[k][own_start_ind:own_start_ind+seq_len] = state_dict[k][pre_start_ind:pre_start_ind+seq_len]\n if own_rel_in_input and own_cls_in_input:\n if pre_cls_in_input and pre_cls_in_input:\n own_state[k][:2] = state_dict[k][:2]\n elif pre_cls_in_input:\n own_state[k][1] = state_dict[k][0]\n elif pre_rel_in_input:\n own_state[k][0] = state_dict[k][0]\n elif own_rel_in_input:\n if pre_rel_in_input:\n own_state[k][0] = state_dict[k][0]\n elif own_cls_in_input:\n if pre_cls_in_input:\n own_state[k][0] = state_dict[k][int(pre_rel_in_input)]\n else:\n own_state[k] = state_dict[k]\n self.load_state_dict(own_state)\n\n def get_pos_states(self, input_states):\n return torch.arange(input_states.size(1)).view(1,-1).repeat(input_states.size(0),1).to(device=input_states.device)\n '''\n Input:\n input_states[batch, seq_len, 5],\n attention_mask[batch, seq_len]/[batch, seq_len, ],(length mask)\n Output:\n output_states[batch, seq_len, hidden_dim],\n '''\n def forward(self, input_states, attention_mask, segments=None, head_mask=None,\n output_all_states=False, output_attentions=False, keep_multihead_output=False):\n if attention_mask is None:\n attention_mask = torch.ones(input_states.size(0), input_states.size(1))\n # Extending attention mask\n if len(attention_mask.size()) == 3:\n extended_attention_mask = attention_mask.unsqueeze(1)\n elif len(attention_mask.size()) == 2:\n extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)\n\n extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype, device=input_states.device) # fp16 compatibility\n extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0\n attention_mask = extended_attention_mask\n # process head mask\n if head_mask is not None:\n if head_mask.dim() == 1:\n head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1)\n head_mask = head_mask.expand_as(self.num_hidden_layers, -1, -1, -1, -1)\n elif head_mask.dim() == 2:\n head_mask = head_mask.unsqueeze(1).unsqueeze(-1).unsqueeze(-1) # We can specify head_mask for each layer\n head_mask = head_mask.to(dtype=next(self.parameters()).dtype, device=input_states.device) # switch to fload if need + fp16 compatibility\n else:\n head_mask = None\n\n input_states = self.embedding(input_states)\n\n if self.pos_embedding is not None:\n pos_states = self.pos_embedding(self.get_pos_states(input_states))\n input_states = input_states + pos_states.to(device=input_states.device)\n\n if self.segment_embedding is not None and segments is not None:\n segment_states = self.segment_embedding(segments)\n input_states = input_states + segment_states\n input_states = self.embed_refine_net(input_states)\n output_states = self.encoder(input_states, attention_mask, head_mask, output_all_states, output_attentions, keep_multihead_output)\n\n\n if output_attentions:\n output_states, attention_probs = output_states\n return output_states[-1], attention_probs\n\n return output_states[-1]\n\nclass SketchCNN(nn.Module):\n '''\n Truely a CNN model\n '''\n def __init__(self, hidden_dim, net_type, pretrained):\n super(SketchCNN, self).__init__()\n if net_type == 'resnet18':\n self.encoder = models.resnet18(pretrained=pretrained)\n self.encoder.fc = nn.Linear(self.encoder.fc.in_features, hidden_dim)\n elif net_type == 'resnet50':\n self.encoder = models.resnet50(pretrained=pretrained)\n self.encoder.fc = nn.Linear(self.encoder.fc.in_features, hidden_dim)\n elif net_type == 'tcnet':\n pass\n elif net_type =='sketchanet':\n pass\n\n def forward(self, input):\n return self.encoder(input)\n\n\n'''\nSketch Transformer based GAN\n'''\nclass SketchGANGenerator(nn.Module):\n '''\n Assume Label in the Input\n '''\n def __init__(self, layers_setting, input_dim, cls_dim, max_length,\n position_type, attention_norm_type, inter_activation, attention_dropout_prob,\n hidden_dropout_prob, output_dropout_prob):\n super(SketchGANGenerator, self).__init__()\n self.encoder = SketchTransformerModel(layers_setting, input_dim, cls_dim, max_length,\n position_type, attention_norm_type, inter_activation, attention_dropout_prob,\n hidden_dropout_prob, output_dropout_prob)\n self.output = nn.Linear(layers_setting[0][1], 5)\n\n '''\n The same as Transformer Model\n '''\n def forward(self, input_states, attention_mask, head_mask=None,\n output_all_states=False, output_attentions=False, keep_multihead_output=False):\n hidden_states = self.encoder(input_states, attention_mask, head_mask=head_mask,\n output_all_states=output_all_states, output_attentions=output_attentions, keep_multihead_output=keep_multihead_output)\n fake_states = self.output(hidden_states)\n return fake_states\n\nclass SketchGANDiscriminator(nn.Module):\n '''\n Assume Label in the Input\n '''\n def __init__(self, layers_setting, input_dim, cls_dim, max_length,\n position_type, attention_norm_type, inter_activation, attention_dropout_prob,\n hidden_dropout_prob, output_dropout_prob):\n super(SketchGANDiscriminator, self).__init__()\n self.encoder = SketchTransformerModel(layers_setting, input_dim, cls_dim, max_length,\n position_type, attention_norm_type, inter_activation, attention_dropout_prob,\n hidden_dropout_prob, output_dropout_prob)\n self.output = nn.Linear(layers_setting[0][1], 2)\n\n '''\n The same as Transformer Model\n '''\n def forward(self, input_states, attention_mask, head_mask=None,\n output_all_states=False, output_attentions=False, keep_multihead_output=False):\n hidden_states = self.encoder(input_states, attention_mask, head_mask=head_mask,\n output_all_states=output_all_states, output_attentions=output_attentions, keep_multihead_output=keep_multihead_output)\n label = self.output(hidden_states[:,0,:])\n return label\n\n\n'''\nSketch Transformer based VAE\n'''\nclass SketchVAEEncoder(SketchTransformerModel):\n def __init__(self, model_type, layers_setting, embed_layers_setting, input_dim, cls_dim, max_length, max_size, type_size,\n conditional, position_type, segment_type, sketch_embed_type, embed_pool_type, attention_norm_type, inter_activation, attention_dropout_prob,\n hidden_dropout_prob, output_dropout_prob):\n super(SketchVAEEncoder, self).__init__(model_type, layers_setting, embed_layers_setting, input_dim, max_length, max_size, type_size,\n position_type, segment_type, sketch_embed_type, embed_pool_type, attention_norm_type, inter_activation, attention_dropout_prob,\n hidden_dropout_prob, output_dropout_prob)\n # self.rec_fc = nn.Linear(layers_setting[0][1], output_dim)\n self.conditional = conditional\n if self.conditional:\n self.cls_embedding = nn.Embedding(cls_dim, embed_layers_setting[0])\n else:\n self.cls_embedding = None\n def load_model(self, state_dict, only_encoder):\n own_state = self.state_dict()\n for k, v in own_state.items():\n if only_encoder and ('encoder' in k or 'embed_refine_net' in k):\n own_state[k] = state_dict[k]\n else:\n if k in state_dict and k in own_state:\n own_state[k] = state_dict[k]\n self.load_state_dict(own_state)\n def forward(self, input_states, attention_mask, targets=None, segments=None, head_mask=None,\n output_all_states=False, output_attentions=False, keep_multihead_output=False):\n '''\n Input:\n input_states[batch, seq_len, 5],\n zs[batch, latent_dim]\n '''\n if attention_mask is None:\n attention_mask = torch.ones(input_states.size(0), input_states.size(1))\n # Extending attention mask\n if len(attention_mask.size()) == 3:\n extended_attention_mask = attention_mask.unsqueeze(1)\n elif len(attention_mask.size()) == 2:\n extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)\n\n extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype, device=input_states.device) # fp16 compatibility\n extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0\n attention_mask = extended_attention_mask\n\n # process head mask\n if head_mask is not None:\n if head_mask.dim() == 1:\n head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1)\n head_mask = head_mask.expand_as(self.num_hidden_layers, -1, -1, -1, -1)\n elif head_mask.dim() == 2:\n head_mask = head_mask.unsqueeze(1).unsqueeze(-1).unsqueeze(-1) # We can specify head_mask for each layer\n head_mask = head_mask.to(dtype=next(self.parameters()).dtype, device=input_states.device) # switch to fload if need + fp16 compatibility\n else:\n head_mask = None\n\n input_states = self.embedding(input_states)\n\n if self.pos_embedding is not None:\n pos_states = self.pos_embedding(self.get_pos_states(input_states))\n input_states = input_states + pos_states\n\n if self.segment_embedding is not None and segments is not None:\n segment_states = self.segment_embedding(segments)\n input_states = input_states + segment_states\n\n if self.cls_embedding is not None and targets is not None:\n cls_states = self.cls_embedding(targets)\n cls_states = cls_states.unsqueeze(1).repeat(1,input_states.size(1),1)\n input_states = input_states + cls_states\n input_states = self.embed_refine_net(input_states)\n # Append the latent_states\n output_states = self.encoder(input_states, attention_mask, head_mask, output_all_states, output_attentions, keep_multihead_output)\n\n if output_attentions:\n output_states, attention_probs = output_states\n #return self.rec_fc(output_states[-1]), attention_probs\n return output_states[-1], attention_probs\n return output_states[-1]\n\n'''\nSketch Transformer based VAE\n'''\nclass SketchVAEDecoder(SketchTransformerModel):\n\n def __init__(self, model_type, layers_setting, embed_layers_setting, rec_layers_setting, input_dim, output_dim, latent_dim, cls_dim, max_length, max_size, type_size,\n conditional, position_type, segment_type, sketch_embed_type, embed_pool_type, attention_norm_type, inter_activation, attention_dropout_prob,\n hidden_dropout_prob, output_dropout_prob):\n print(embed_layers_setting)\n super(SketchVAEDecoder, self).__init__(model_type, layers_setting, embed_layers_setting, input_dim, max_length, max_size, type_size,\n position_type, segment_type, sketch_embed_type, embed_pool_type, attention_norm_type, inter_activation, attention_dropout_prob,\n hidden_dropout_prob, output_dropout_prob)\n self.conditional = conditional\n if self.conditional:\n self.cls_embedding = nn.Embedding(cls_dim, embed_layers_setting[0])\n else:\n self.cls_embedding = None\n self.re_fcs = []\n rec_layers_setting = rec_layers_setting.copy()\n rec_layers_setting.append(output_dim), rec_layers_setting.insert(0, layers_setting[0][1])\n for i in range(len(rec_layers_setting)-1):\n self.re_fcs.append(nn.Linear(rec_layers_setting[i], rec_layers_setting[i+1]))\n self.re_fcs = nn.ModuleList(self.re_fcs)\n\n self.latent_fusion = nn.Linear(layers_setting[0][1]+latent_dim, layers_setting[0][1])\n def load_model(self, state_dict, only_encoder):\n own_state = self.state_dict()\n for k, v in own_state.items():\n if only_encoder and ('encoder' in k or 'embed_refine_net' in k):\n #print(k in own_state, k in state_dict)\n own_state[k] = state_dict[k]\n else:\n if k in state_dict and k in own_state:\n own_state[k] = state_dict[k]\n self.load_state_dict(own_state)\n def forward(self, input_states, zs, attention_mask, targets=None, segments=None, head_mask=None,\n output_all_states=False, output_attentions=False, keep_multihead_output=False):\n '''\n Input:\n input_states[batch, seq_len, 5],\n zs[batch, latent_dim]\n '''\n if attention_mask is None:\n attention_mask = torch.ones(input_states.size(0), input_states.size(1))\n\n # Extending attention mask\n if len(attention_mask.size()) == 3:\n extended_attention_mask = attention_mask.unsqueeze(1)\n elif len(attention_mask.size()) == 2:\n extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)\n\n extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype, device=input_states.device) # fp16 compatibility\n extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0\n attention_mask = extended_attention_mask\n\n # process head mask\n if head_mask is not None:\n if head_mask.dim() == 1:\n head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1)\n head_mask = head_mask.expand_as(self.num_hidden_layers, -1, -1, -1, -1)\n elif head_mask.dim() == 2:\n head_mask = head_mask.unsqueeze(1).unsqueeze(-1).unsqueeze(-1) # We can specify head_mask for each layer\n head_mask = head_mask.to(dtype=next(self.parameters()).dtype, device=input_states.device) # switch to fload if need + fp16 compatibility\n else:\n head_mask = None\n\n input_states = self.embedding(input_states)\n\n if self.pos_embedding is not None:\n pos_states = self.pos_embedding(self.get_pos_states(input_states))\n input_states = input_states + pos_states\n\n if self.segment_embedding is not None and segments is not None:\n segment_states = self.segment_embedding(segments)\n input_states = input_states + segment_states\n\n if self.cls_embedding is not None and targets is not None:\n cls_states = self.cls_embedding(targets)\n cls_states = cls_states.unsqueeze(1).repeat(1,input_states.size(1),1)\n input_states = input_states + cls_states\n\n input_states = self.embed_refine_net(input_states)\n # Append the latent_states\n input_states = torch.cat([input_states, zs.unsqueeze(1).repeat(1,input_states.size(1),1)],dim=2)\n input_states = self.latent_fusion(input_states)\n output_states = self.encoder(input_states, attention_mask, head_mask, output_all_states, output_attentions, keep_multihead_output)\n\n if output_attentions:\n output_states, attention_probs = output_states\n output_states = output_states[-1]\n for re_fc in self.re_fcs:\n output_states = re_fc(output_states)\n return output_states, attention_probs\n output_states = output_states[-1]\n for re_fc in self.re_fcs:\n output_states = re_fc(output_states)\n return output_states\n\n\nclass SketchVAELatentEmbedding(nn.Module):\n def __init__(self, hidden_dim, latent_dim, max_length):\n super(SketchVAELatentEmbedding, self).__init__()\n self.mu_embedding = nn.Linear(hidden_dim, latent_dim)\n self.sigma_embedding = nn.Linear(hidden_dim, latent_dim)\n self.gaussian_generator = MultivariateNormal(torch.zeros(latent_dim), torch.eye(latent_dim))\n '''\n Input:\n hidden_states[batch, seq_len, hidden_dim]\n Output:\n mus[batch, latent_dim]\n sigmas[batch, latent_dim]\n z[batch, latent_dim]\n '''\n def forward(self, hidden_states, attention_mask):\n\n # Mask the lengths beyond\n latent_states = hidden_states[:,0,:]\n mus = self.mu_embedding(latent_states)\n sigmas = self.sigma_embedding(latent_states)\n sigmas = torch.exp(sigmas/2)\n random_normal = self.gaussian_generator.sample([sigmas.size(0)]).to(sigmas.device)\n zs = mus + sigmas * random_normal\n return mus, sigmas , zs\n\n\n\n'''\nDifferent Pooling Layers\n'''\nclass SketchPooling(nn.Module):\n def __init__(self, hidden_dim, input_dim, cls_dim, max_length=250):\n super(SketchPooling, self).__init__()\n self.fc1 = nn.Linear(hidden_dim, 4)\n self.fc2 = nn.Linear(max_length*4, cls_dim)\n self.re_fc = nn.Linear(hidden_dim, input_dim)\n def forward(self, hidden_states):\n re_sketch = self.re_fc(hidden_states)\n pooled = self.fc1(hidden_states)\n pooled = self.fc2(pooled.view(pooled.size(0), -1))\n return re_sketch, pooled\n\nclass SketchGMMPooling(nn.Module):\n def __init__(self, hidden_dim, M, cls_dim, max_length=250):\n super(SketchPooling, self).__init__()\n self.fc1 = nn.Linear(hidden_dim, 4)\n self.fc2 = nn.Linear(max_length*4, cls_dim)\n self.re_fc = nn.Linear(hidden_dim, 6*M + 3)\n\n '''\n Input:\n hidden_states[batch, seq_len, hidden_dim]\n Output:\n re_sketch[batch, seq_len, 6M+3]\n pooled[batch, cls_dim]\n '''\n def forward(self, hidden_states):\n re_sketch = self.re_fc(hidden_states)\n pooled = self.fc1(hidden_states)\n pooled = self.fc2(pooled.view(pooled.size(0), -1))\n return re_sketch, pooled\n\n\nclass SketchHiddenPooling(nn.Module):\n def __init__(self, hidden_dim):\n super(SketchPooler, self).__init__()\n self.fc = nn.Linear(hidden_dim, hidden_dim)\n self.activation = nn.Tanh()\n\n def forward(self, hidden_states):\n # We \"pool\" the model by simply taking the hidden state corresponding\n # to the first token.\n first_token_tensor = hidden_states[:, 0]\n pooled_output = self.fc(first_token_tensor)\n pooled_output = self.activation(pooled_output)\n return pooled_output\n\n'''\nMulti models for transformer backbone\n'''\n\n#Mask Sketch Model\nclass MaskSketchRecModel(nn.Module):\n def __init__(self, rec_layers_setting, hidden_dim, input_dim, cls_in_input, rel_in_input):\n super(MaskSketchRecModel, self).__init__()\n self.re_fcs = []\n rec_layers_setting.append(input_dim), rec_layers_setting.insert(0, hidden_dim)\n for i in range(len(rec_layers_setting)-1):\n self.re_fcs.append(nn.Linear(rec_layers_setting[i], rec_layers_setting[i+1]))\n self.re_fcs = nn.ModuleList(self.re_fcs)\n\n self.cls_in_input = cls_in_input\n self.rel_in_input = rel_in_input\n '''\n Input:\n hidden_states[batch, seq_len+cls_input, hidden_dim]\n\n '''\n def forward(self, hidden_states):\n hidden_states = hidden_states[:, self.cls_in_input+self.rel_in_input:, :]\n for re_fc in self.re_fcs:\n hidden_states = re_fc(hidden_states)\n return hidden_states\n\nclass MaskSketchGMMModel(nn.Module):\n def __init__(self, hidden_dim, M, cls_in_input, rel_in_input):\n super(MaskSketchGMMModel, self).__init__()\n self.re_fc = nn.Linear(hidden_dim, 6*M + 3)\n self.cls_in_input = cls_in_input\n self.rel_in_input = rel_in_input\n '''\n Input:\n hidden_states[batch, seq_len+cls_input, hidden_dim]\n attention_mask[batch, seq_len+cls_input]\n '''\n def forward(self, hidden_states):\n\n hidden_states = hidden_states[:, self.cls_in_input+self.rel_in_input:, :]\n return self.re_fc(hidden_states)\n\n# Sketch classification model\nclass SketchClassificationModel(nn.Module):\n def __init__(self, hidden_dim, cls_dim, max_length):\n super(SketchClassificationModel, self).__init__()\n self.fc1 = nn.Linear(hidden_dim, 4)\n self.fc2 = nn.Linear(max_length*4, cls_dim)\n '''\n Input:\n hidden_states[batch, seq_len, hidden_dim]\n attention_mask[batch, seq_len]\n Output:\n cls_states[batch, cls_dim]\n '''\n def forward(self, hidden_states):\n pooled = self.fc1(hidden_states)\n pooled = self.fc2(pooled.view(pooled.size(0), -1))\n return pooled\n\nclass SketchClsPoolingModel(nn.Module):\n def __init__(self, cls_layers_setting, hidden_dim, cls_dim, pool_dim):\n super(SketchClsPoolingModel, self).__init__()\n self.pool_dim = int(pool_dim)\n cls_layers_setting = cls_layers_setting.copy()\n cls_layers_setting.insert(0, hidden_dim), cls_layers_setting.append(cls_dim)\n self.cls_fcs = []\n for i in range(len(cls_layers_setting)-1):\n self.cls_fcs.append(nn.Linear(cls_layers_setting[i], cls_layers_setting[i+1]))\n self.cls_fcs = nn.ModuleList(self.cls_fcs)\n\n '''\n Input:\n hidden_states[batch, seq_len+cls_dim, hidden_dim](0 dim is cls)\n Output:\n cls_states[batch, cls_dim]\n '''\n def forward(self, hidden_states):\n pooled = hidden_states[:,self.pool_dim,:]\n for cls_fc in self.cls_fcs:\n pooled = cls_fc(pooled)\n return pooled\n\nclass SketchRetrievalPoolingModel(nn.Module):\n def __init__(self, rel_layers_setting, hidden_dim, feat_dim, pool_dim):\n super(SketchRetrievalPoolingModel, self).__init__()\n self.pool_dim = int(pool_dim)\n rel_layers_setting = rel_layers_setting.copy()\n rel_layers_setting.insert(0, hidden_dim), rel_layers_setting.append(feat_dim)\n self.rel_fcs = []\n for i in range(len(rel_layers_setting)-1):\n self.rel_fcs.append(nn.Linear(rel_layers_setting[i], rel_layers_setting[i+1]))\n self.rel_fcs = nn.ModuleList(self.rel_fcs)\n\n '''\n Input:\n hidden_states[batch, seq_len+cls_dim, hidden_dim](0 dim is cls)\n Output:\n cls_states[batch, cls_dim]\n '''\n def forward(self, hidden_states):\n pooled = hidden_states[:,self.pool_dim,:]\n for rel_fc in self.rel_fcs:\n pooled = rel_fc(pooled)\n return pooled\n\nclass SketchDiscretePoolingModel(nn.Module):\n def __init__(self, hidden_dim, max_size, type_size, cls_in_input, rel_in_input):\n super(SketchDiscretePoolingModel, self).__init__()\n self.cls_in_input = cls_in_input\n self.rel_in_input = rel_in_input\n self.x_pooling = nn.Linear(hidden_dim, 2*max_size[0]+1)\n self.y_pooling = nn.Linear(hidden_dim, 2*max_size[1]+1)\n\n self.type_pooling = nn.Linear(hidden_dim, type_size)\n\n def forward(self, hidden_states):\n '''\n Input:\n hidden_states[batch, seq_len+cls_dim, hidden_dim](0 dim is cls)\n Output:\n x_pred[batch, seq_len+cls_dim, 2*max_size[0]+1]\n y_pred[batch, seq_len+cls_dim, 2*max_size[1]+1]\n type_pred[batch, seq_len+cls_dim, type_size]\n '''\n hidden_states = (hidden_states)[:,self.cls_in_input+self.rel_in_input:,:]\n x_pred = self.x_pooling(hidden_states)\n y_pred = self.y_pooling(hidden_states)\n type_pred = self.type_pooling(hidden_states)\n return x_pred, y_pred, type_pred\n\n\nclass SketchSegmentOrderPoolingModel(nn.Module):\n def __init__(self, hidden_dim, max_segment, cls_in_input, rel_in_input):\n super(SketchSegmentOrderPoolingModel, self).__init__()\n self.sg_fc = nn.Linear(hidden_dim, max_segment)\n self.cls_in_input = cls_in_input\n self.rel_in_input = rel_in_input\n\n def forward(self, hidden_states, segment_index):\n '''\n Input:\n hidden_states[batch, seg_len, hidden_dim]\n segment_index[batch, seq_len]\n '''\n seg_states = hidden_states[:,self.cls_in_input+self.rel_in_input:,:][segment_index==0,:]\n return self.sg_fc(seg_states)\n\n\nclass GMMLoss(nn.Module):\n def __init__(self, reduction='mean'):\n super(GMMLoss, self).__init__()\n # self.logsoftmax = nn.LogSoftmax(dim=-1)\n self.reduction = reduction\n\n '''\n x[seq_len, batch, 2]\n lengths[batch, seq_len]\n pis[seq_len, batch, M]: no softmax The {pis} in the paper SketchRNN, https://arxiv.org/abs/1704.03477\n mus[seq_len, batch, M, 2]: The {mus} in the paper SketchRNN, https://arxiv.org/abs/1704.03477\n sigmas[seq_len, batch, M, 2]: exp The {sigmas} in the paper SketchRNN, https://arxiv.org/abs/1704.03477\n rhos[seq_len, batch, M]: tanh The {rho} in the paper SketchRNN, https://arxiv.org/abs/1704.03477\n masks[]\n '''\n def forward(self, x, lengths, pis, mus, sigmas, rhos, epsilon=1e-8):\n batch_size, seq_len, M = pis.size()\n #print(batch_size, seq_len)\n #print(x.size(), pis.size())\n x = x.view(batch_size, seq_len, 1, 2).repeat(1, 1, M, 1)\n\n sigma_prods = torch.prod(sigmas, dim=3) # [seq_len, batch, M]\n sigma_sq = torch.pow(sigmas, 2) # [seq_len, batch, M, 2]\n #print(x.size(), mus.size(), sigmas.size())\n x_center = (x - mus) / (sigmas)\n Z = torch.sum(x_center*x_center, dim=3) - 2 * rhos * torch.prod(x_center, dim=3)\n rho_sq = 1 - rhos*rhos # [seq_len, batch, M]\n denom = 2 * np.pi * sigma_prods * torch.sqrt(rho_sq)\n probs = torch.exp(-Z / (2*rho_sq)) / denom\n # pis = F.softmax(pis, dim=-1)\n probs = torch.sum(F.softmax(pis, dim=-1) * probs, dim=-1)\n\n log_probs = torch.log(probs+epsilon) * lengths # [len]\n\n loss = - torch.mean(log_probs)\n return loss\n\n\nclass KLLoss(nn.Module):\n def __init__(self, kl_tolerance):\n super(KLLoss, self).__init__()\n self.kl_tolerance = torch.tensor(kl_tolerance)\n\n '''\n Input:\n mus[batch, latent_size]:\n sigmas[batch, latent_size]:\n '''\n def forward(self, mus, sigmas):\n loss = - (0.5) * torch.mean(1 + torch.log(sigmas)*2.0 - mus*mus - sigmas*sigmas)\n return torch.max(loss, self.kl_tolerance.to(loss.device))\n" ]
[ [ "torch.nn.Linear", "torch.cat", "torch.prod", "torch.nn.ModuleList", "torch.nn.LeakyReLU", "torch.ones", "torch.eye", "torch.exp", "torch.sum", "torch.sqrt", "torch.tensor", "torch.zeros", "torch.nn.Sequential", "torch.nn.Tanh", "torch.nn.Conv2d", "torch.nn.InstanceNorm2d", "torch.nn.functional.softmax", "torch.mean", "torch.log", "torch.matmul", "torch.pow", "torch.nn.Dropout", "torch.arange", "torch.nn.Embedding" ] ]
ksboy/adversarial_attack
[ "cb1e02b8ff31056cdd0eb1f747c1b08ed12527bc", "cb1e02b8ff31056cdd0eb1f747c1b08ed12527bc" ]
[ "modules.py", "keras/esim_online.py" ]
[ "import torch\n\nclass FGM():\n def __init__(self, model):\n self.model = model\n self.backup = {}\n\n def attack(self, epsilon=1e-6, emb_name='embed'):\n # emb_name这个参数要换成你模型中embedding的参数名\n for name, param in self.model.named_parameters():\n if param.requires_grad and emb_name in name:\n self.backup[name] = param.data.clone()\n norm = torch.norm(param.grad)\n if norm != 0 and not torch.isnan(norm):\n r_at = epsilon * param.grad / norm\n param.data.add_(r_at)\n\n def restore(self, emb_name='embed'):\n # emb_name这个参数要换成你模型中embedding的参数名\n for name, param in self.model.named_parameters():\n if param.requires_grad and emb_name in name: \n assert name in self.backup\n param.data = self.backup[name]\n self.backup = {}\n\nclass PGD():\n def __init__(self, model):\n self.model = model\n self.emb_backup = {}\n self.grad_backup = {}\n\n def attack(self, epsilon=1e-6, alpha=0.3, emb_name='embed', is_first_attack=False):\n # emb_name这个参数要换成你模型中embedding的参数名\n for name, param in self.model.named_parameters():\n if param.requires_grad and emb_name in name:\n # print (name)\n if is_first_attack:\n self.emb_backup[name] = param.data.clone()\n norm = torch.norm(param.grad)\n if norm != 0 and not torch.isnan(norm):\n r_at = alpha * param.grad / norm\n param.data.add_(r_at)\n param.data = self.project(name, param.data, epsilon)\n\n def restore(self, emb_name='embed'):\n # emb_name这个参数要换成你模型中embedding的参数名\n for name, param in self.model.named_parameters():\n if param.requires_grad and emb_name in name: \n assert name in self.emb_backup\n param.data = self.emb_backup[name]\n self.emb_backup = {}\n\n def project(self, param_name, param_data, epsilon):\n r = param_data - self.emb_backup[param_name]\n if torch.norm(r) > epsilon:\n r = epsilon * r / torch.norm(r)\n return self.emb_backup[param_name] + r\n\n def backup_grad(self):\n for name, param in self.model.named_parameters():\n if param.requires_grad:\n self.grad_backup[name] = param.grad.clone()\n\n def restore_grad(self):\n for name, param in self.model.named_parameters():\n if param.requires_grad:\n param.grad = self.grad_backup[name]\n\n\n\n", "import os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"3\"\nimport pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\nimport time\nimport logging\nfrom sklearn.model_selection import StratifiedKFold\nfrom keras_bert import load_trained_model_from_checkpoint, Tokenizer\nfrom keras.optimizers import Adam\nimport pandas as pd\nfrom sklearn.metrics import mean_absolute_error, accuracy_score, f1_score\nfrom keras.layers import *\nfrom keras.models import Model\nimport keras.backend as K\nfrom keras.callbacks import Callback, EarlyStopping, ModelCheckpoint\nfrom keras.activations import softmax\nlearning_rate = 5e-5\nmin_learning_rate = 1e-5\nbatch_size =32\nval_batch_size = 512\npred_batch_size = 512\npercent_of_epoch = 0.25 * 0.05\nnum_epochs = 7 //percent_of_epoch\npatience = 3\nmodel_path= \"./model/\"\nnfolds=5\n\n\nbert_path = \"/home/mhxia/workspace/BDCI/chinese_wwm_ext_L-12_H-768_A-12/\"\nconfig_path = bert_path + 'bert_config.json'\ncheckpoint_path = bert_path + 'bert_model.ckpt'\ndict_path = bert_path + 'vocab.txt'\n\n\nMAX_LEN = 64\n\ntoken_dict = {}\nwith open(dict_path, 'r', encoding='utf-8') as reader:\n for line in reader:\n token = line.strip()\n token_dict[token] = len(token_dict)\ntokenizer = Tokenizer(token_dict)\n\ntrain= pd.read_csv('./data/train_set.csv')\ntest=pd.read_csv('./data/dev_set.csv',sep='\\t')\ntrain_achievements = train['question1'].values\ntrain_requirements = train['question2'].values\nlabels = train['label'].values\ndef label_process(x):\n if x==0:\n return [1,0]\n else:\n return [0,1]\ntrain['label']=train['label'].apply(label_process)\nlabels_cat=list(train['label'].values)\nlabels_cat=np.array(labels_cat)\ntest_achievements = test['question1'].values\ntest_requirements = test['question2'].values\nprint(train.shape,test.shape)\n\n\nclass data_generator:\n def __init__(self, data, batch_size=32):\n self.data = data\n self.batch_size = batch_size\n self.steps = len(self.data[0]) // self.batch_size\n if len(self.data[0]) % self.batch_size != 0:\n self.steps += 1\n def __len__(self):\n return self.steps\n def __iter__(self):\n while True:\n X1, X2, y = self.data\n idxs = list(range(len(self.data[0])))\n np.random.shuffle(idxs)\n T, T_, Y = [], [], []\n for c, i in enumerate(idxs):\n achievements = X1[i]\n requirements = X2[i]\n t, t_ = tokenizer.encode(first=achievements, second=requirements, max_len=MAX_LEN)\n T.append(t)\n T_.append(t_)\n Y.append(y[i])\n if len(T) == self.batch_size or i == idxs[-1]:\n T = np.array(T)\n T_ = np.array(T_)\n Y = np.array(Y)\n yield [T, T_], Y\n T, T_, Y = [], [], []\n\nclass test_data_generator:\n def __init__(self, data, batch_size=32):\n self.data = data\n self.batch_size = batch_size\n self.steps = len(self.data[0]) // self.batch_size\n if len(self.data[0]) % self.batch_size != 0:\n self.steps += 1\n def __len__(self):\n return self.steps\n def __iter__(self):\n while True:\n X1, X2 = self.data\n idxs = list(range(len(self.data[0])))\n np.random.shuffle(idxs)\n T, T_ = [], []\n for c, i in enumerate(idxs):\n print(c)\n achievements = X1[i]\n requirements = X2[i]\n t, t_ = tokenizer.encode(first=achievements, second=requirements, max_len=MAX_LEN)\n T.append(t)\n T_.append(t_)\n if len(T) == self.batch_size or i == idxs[-1]:\n T = np.array(T)\n T_ = np.array(T_)\n yield [T, T_]\n T, T_ = [], []\n\n\n#####################################################\ndef apply_multiple(input_, layers):\n if not len(layers) > 1:\n raise ValueError('Layers list should contain more than 1 layer')\n else:\n agg_ = []\n for layer in layers:\n agg_.append(layer(input_))\n out_ = Concatenate()(agg_)\n return out_\ndef unchanged_shape(input_shape):\n return input_shape\ndef substract(input_1, input_2):\n neg_input_2 = Lambda(lambda x: -x, output_shape=unchanged_shape)(input_2)\n out_ = Add()([input_1, neg_input_2])\n return out_\ndef submult(input_1, input_2):\n mult = Multiply()([input_1, input_2])\n sub = substract(input_1, input_2)\n out_ = Concatenate()([sub, mult])\n return out_\ndef soft_attention_alignment(input_1, input_2):\n attention = Dot(axes=-1)([input_1, input_2])\n w_att_1 = Lambda(lambda x: softmax(x, axis=1), ##soft max to each column\n output_shape=unchanged_shape)(attention)\n w_att_2 = Permute((2, 1))(Lambda(lambda x: softmax(x, axis=2), ## axis =2 soft max to each row\n output_shape=unchanged_shape)(attention))\n in1_aligned = Dot(axes=1)([w_att_1, input_1])\n in2_aligned = Dot(axes=1)([w_att_2, input_2])\n return in1_aligned, in2_aligned\ndef focal_loss(y_true, y_pred, alpha=0.25, gamma=2.):\n y_pred = K.clip(y_pred, 1e-8, 1 - 1e-8)\n return - alpha * y_true * K.log(y_pred) * (1 - y_pred)**gamma\\\n - (1 - alpha) * (1 - y_true) * K.log(1 - y_pred) * y_pred**gamma\ndef get_model():\n bert_model = load_trained_model_from_checkpoint(config_path, checkpoint_path)\n # for l in bert_model.layers:\n # l.trainable = True\n\n T1 = Input(shape=(None,))\n T2 = Input(shape=(None,))\n\n tp1 = Lambda(lambda x: K.zeros_like(x))(T1)\n tp2 = Lambda(lambda x: K.zeros_like(x))(T2)\n x1 = bert_model([T1, tp1])\n x2 = bert_model([T2, tp2])\n X1 = Lambda(lambda x: x[:, 0:-1])(x1)\n X2 = Lambda(lambda x: x[:, 0:-1])(x2)\n\n encode = Bidirectional(LSTM(200, return_sequences=True))\n q1_encoded = encode(X1)\n q2_encoded = encode(X2)\n q1_aligned, q2_aligned = soft_attention_alignment(q1_encoded, q2_encoded)\n q1_combined = Concatenate()([q1_encoded, q2_aligned, submult(q1_encoded, q2_aligned)])\n q2_combined = Concatenate()([q2_encoded, q1_aligned, submult(q2_encoded, q1_aligned)])\n compose = Bidirectional(GRU(200, return_sequences=True))\n q1_compare = compose(q1_combined)\n q2_compare = compose(q2_combined)\n # Aggregate\n q1_rep = apply_multiple(q1_compare, [GlobalAvgPool1D(), GlobalMaxPool1D()])\n q2_rep = apply_multiple(q2_compare, [GlobalAvgPool1D(), GlobalMaxPool1D()])\n # Classifier\n merged = Concatenate()([q1_rep, q2_rep])\n dense = BatchNormalization()(merged)\n dense = Dense(30, activation='selu')(dense)\n\n dense = BatchNormalization()(dense)\n output = Dense(2, activation='softmax')(dense)\n model = Model([T1, T2], output)\n model.compile(\n # loss='categorical_crossentropy',\n loss=focal_loss,\n optimizer=Adam(1e-3), # 用足够小的学习率\n metrics=['accuracy']\n )\n model.summary()\n return model\n\n\nskf = StratifiedKFold(n_splits=nfolds, shuffle=True, random_state=42)\n\noof_train = np.zeros((len(train), 2), dtype=np.float32)\noof_test = np.zeros((len(test), 2), dtype=np.float32)\nfor fold, (train_index, valid_index) in enumerate(skf.split(train_achievements, labels)):\n x1 = train_achievements[train_index]\n x2 = train_requirements[train_index]\n y = labels_cat[train_index]\n val_x1 = train_achievements[valid_index]\n val_x2 = train_requirements[valid_index]\n val_y = labels_cat[valid_index]\n train_D = data_generator([x1, x2, y], batch_size)\n val_D = data_generator([val_x1, val_x2, val_y], val_batch_size)\n early_stopping = EarlyStopping(monitor='val_accuracy', patience=patience, verbose=1)\n model_checkpoint = ModelCheckpoint(model_path+\"model_%s.w\"%fold, monitor='val_accuracy', verbose=1,save_best_only=True, save_weights_only=False, mode='auto')\n\n model = get_model()\n model.fit_generator(train_D.__iter__(),\n steps_per_epoch=len(train_D) * percent_of_epoch,\n epochs=num_epochs,\n validation_data= val_D.__iter__(),\n validation_steps = len(val_D) ,\n verbose=1,\n callbacks=[early_stopping, model_checkpoint]\n )\n # model.load_weights('bert{}.w'.format(fold))\n\n pred_D = test_data_generator([test_achievements, test_requirements], pred_batch_size)\n oof_test += model.predict(pred_D.__iter__(), verbose=1, steps=len(pred_D))\n K.clear_session()\noof_test /= nfolds\ntest=pd.DataFrame(oof_test)\ntest.to_csv('test_pred.csv',index=False)\ntest.head(),test.shape\ntrain=pd.DataFrame(oof_train)\ntrain.to_csv('train_pred.csv',index=False)\n\n\npred=pd.read_csv('test_pred.csv').values\npred=pred.argmax(axis=1)\nsub=pd.DataFrame()\nsub['pred']=list(pred)\nsub.to_csv('sub.csv',sep='\\t',header=None)\n" ]
[ [ "torch.norm", "torch.isnan" ], [ "numpy.array", "sklearn.model_selection.StratifiedKFold", "pandas.DataFrame", "numpy.random.shuffle", "pandas.read_csv" ] ]
GzuPark/EXTD_Pytorch
[ "e99af10f282d07054c1cf7c4b8c035084daaff78" ]
[ "mobileFacenet_48_PReLU.py" ]
[ "import torch.nn as nn\nimport math\nimport torch\nimport torch.nn.functional as F\n\n\ndef conv_bn(inp, oup, stride, k_size=3):\n return nn.Sequential(\n nn.Conv2d(inp, oup, k_size, stride, 1, bias=False),\n nn.BatchNorm2d(oup),\n nn.PReLU()\n )\n\n\ndef conv_1x1_bn(inp, oup):\n return nn.Sequential(\n nn.Conv2d(inp, oup, 1, 1, 0, bias=False),\n nn.BatchNorm2d(oup),\n nn.PReLU()\n )\n\nclass DWC(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(DWC, self).__init__()\n #self.depthwise = nn.Conv2d(in_channels=in_channels, out_channels=in_channels, kernel_size=(7,6),\n #stride=1, padding=0, groups=in_channels, bias=False)\n self.batch_norm_in = nn.BatchNorm2d(in_channels)\n self.depthwise = nn.AvgPool2d((7, 6), stride=1, padding=0)\n self.pointwise = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1,\n stride=1, padding=0, bias=False)\n\n def forward(self, x):\n x = self.depthwise(x)\n #x = self.batch_norm_in(x)\n x = self.pointwise(x)\n return x\n\nclass Max_AvgPool(nn.Module):\n def __init__(self, kernel_size=(3,3), stride=2, padding=1, dim=128):\n super(Max_AvgPool, self).__init__()\n self.Maxpool = nn.MaxPool2d(kernel_size=kernel_size, stride=stride, padding=padding)\n self.Avgpool = nn.AvgPool2d(kernel_size=kernel_size, stride=stride, padding=padding)\n\n def forward(self, x):\n x = self.Maxpool(x) + self.Avgpool(x) # add some channelwise gating?\n return x\n\nclass Max_AvgPool(nn.Module):\n def __init__(self, kernel_size=(3,3), stride=2, padding=1, dim=128):\n super(Max_AvgPool, self).__init__()\n self.Maxpool = nn.MaxPool2d(kernel_size=kernel_size, stride=stride, padding=padding)\n self.Avgpool = nn.AvgPool2d(kernel_size=kernel_size, stride=stride, padding=padding)\n\n def forward(self, x):\n x = self.Maxpool(x) + self.Avgpool(x) # add some channelwise gating?\n return x\n\nclass gated_conv1x1(nn.Module):\n def __init__(self, inc=128, outc=128):\n super(gated_conv1x1, self).__init__()\n self.inp = int(inc/2)\n self.oup = int(outc/2)\n self.conv1x1_1 = nn.Conv2d(self.inp, self.oup, 1, 1, 0, bias=False)\n self.gate_1 = nn.Conv2d(self.inp, self.oup, 1, 1, 0, bias=True)\n self.conv1x1_2 = nn.Conv2d(self.inp, self.oup, 1, 1, 0, bias=False)\n self.gate_2 = nn.Conv2d(self.inp, self.oup, 1, 1, 0, bias=True)\n\n def forward(self, x):\n x_1 = x[:, :self.inp, :, :]\n x_2 = x[:, self.inp:, :, :]\n\n a_1 = self.conv1x1_1(x_1)\n g_1 = F.sigmoid(self.gate_1(x_1))\n\n a_2 = self.conv1x1_2(x_2)\n g_2 = F.sigmoid(self.gate_2(x_2))\n\n ret = torch.cat((a_1*g_1, a_2*g_2), 1)\n\n return ret\n\n\nclass InvertedResidual_dwc(nn.Module):\n def __init__(self, inp, oup, stride, expand_ratio):\n super(InvertedResidual_dwc, self).__init__()\n self.stride = stride\n assert stride in [1, 2]\n\n hidden_dim = int(round(inp * expand_ratio))\n self.use_res_connect = self.stride == 1 and inp == oup\n\n self.conv = []\n\n if expand_ratio == 1:\n\n self.conv.append(nn.Conv2d(inp, hidden_dim, kernel_size=(3, 3), stride=stride, padding=1, groups=hidden_dim))\n self.conv.append(nn.BatchNorm2d(hidden_dim))\n self.conv.append(nn.PReLU())\n #self.conv.append(nn.MaxPool2d(kernel_size=(3, 3), stride=stride, padding=1))\n #self.conv.append(gated_conv1x1(inc=hidden_dim,outc=oup))\n self.conv.append(nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False))\n self.conv.append(nn.BatchNorm2d(oup))\n else:\n #self.conv.append(gated_conv1x1(inc=inp,outc=hidden_dim))\n self.conv.append(nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False))\n self.conv.append(nn.BatchNorm2d(hidden_dim))\n self.conv.append(nn.PReLU())\n self.conv.append(nn.Conv2d(hidden_dim, hidden_dim, kernel_size=(3, 3), stride=stride, padding=1, groups=hidden_dim))\n self.conv.append(nn.BatchNorm2d(hidden_dim))\n self.conv.append(nn.PReLU())\n #self.conv.append(gated_conv1x1(inc=hidden_dim,outc=oup))\n self.conv.append(nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False))\n self.conv.append(nn.BatchNorm2d(oup))\n\n self.conv = nn.Sequential(*self.conv)\n\n def forward(self, x):\n if self.use_res_connect:\n return x + self.conv(x)\n else:\n return self.conv(x)\n\n\n\nclass InvertedResidual(nn.Module):\n def __init__(self, inp, oup, stride, expand_ratio):\n super(InvertedResidual, self).__init__()\n self.stride = stride\n assert stride in [1, 2]\n\n hidden_dim = int(round(inp * expand_ratio))\n self.use_res_connect = self.stride == 1 and inp == oup\n\n self.conv = []\n\n if expand_ratio == 1:\n\n self.conv.append(nn.MaxPool2d(kernel_size=(3, 3), stride=stride, padding=1))\n #self.conv.append(gated_conv1x1(inc=hidden_dim,outc=oup))\n self.conv.append(nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False))\n self.conv.append(nn.BatchNorm2d(oup))\n else:\n #self.conv.append(gated_conv1x1(inc=inp,outc=hidden_dim))\n self.conv.append(nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False))\n self.conv.append(nn.BatchNorm2d(hidden_dim))\n self.conv.append(nn.PReLU())\n self.conv.append(nn.MaxPool2d(kernel_size=(3, 3), stride=stride, padding=1))\n #self.conv.append(gated_conv1x1(inc=hidden_dim,outc=oup))\n self.conv.append(nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False))\n self.conv.append(nn.BatchNorm2d(oup))\n\n self.conv = nn.Sequential(*self.conv)\n\n def forward(self, x):\n if self.use_res_connect:\n return x + self.conv(x)\n else:\n return self.conv(x)\n\n\nclass Net(nn.Module): #mobileNet v2\n def __init__(self, embedding_size=128, input_size=224, width_mult=1.):\n super(Net, self).__init__()\n block = InvertedResidual\n block_dwc = InvertedResidual_dwc\n input_channel = 64\n last_channel = 256\n interverted_residual_setting = [\n # t, c, n, s\n [1, 48, 1, 1], # depthwise conv for first row\n [2, 48, 2, 1],\n [4, 48, 2, 2],\n [2, 48, 2, 1],\n [4, 48, 5, 1],\n [2, 48, 2, 2],\n [2, 48, 6, 2],\n ]\n\n # building first layer\n input_channel = int(input_channel * width_mult)\n self.last_channel = int(last_channel * width_mult) if width_mult > 1.0 else last_channel\n self.features = [conv_bn(3, input_channel, 2)]\n\n # building inverted residual\n cnt = 0\n for t, c, n, s in interverted_residual_setting:\n output_channel = int(c * width_mult)\n for i in range(n):\n if cnt>1:\n if i == n - 1: # reduce the featuremap in the last.\n self.features.append(block_dwc(input_channel, output_channel, s, expand_ratio=t))\n else:\n self.features.append(block_dwc(input_channel, output_channel, 1, expand_ratio=t))\n input_channel = output_channel\n else:\n if i == n - 1: # reduce the featuremap in the last.\n self.features.append(block_dwc(input_channel, output_channel, s, expand_ratio=t))\n else:\n self.features.append(block_dwc(input_channel, output_channel, 1, expand_ratio=t))\n input_channel = output_channel\n\n cnt+=1\n\n # building last several layers\n self.features.append(gated_conv1x1(input_channel, self.last_channel))\n\n # make it nn.Sequential\n self.features_sequential = nn.Sequential(*self.features)\n\n # Global depthwise conv\n #self.GDCconv = DWC(self.last_channel, embedding_size)\n\n\n self._initialize_weights()\n\n def forward(self, x):\n x = self.features_sequential(x).view(-1, 256*4)\n\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 n = m.weight.size(1)\n m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()" ]
[ [ "torch.cat", "torch.nn.MaxPool2d", "torch.nn.Sequential", "torch.nn.AvgPool2d", "torch.nn.BatchNorm2d", "torch.nn.Conv2d", "torch.nn.PReLU" ] ]
bigaidream-projects/drmad
[ "a4bb6010595d956f29c5a42a095bab76a60b29eb" ]
[ "cpu_ver/hypergrad/kernel_methods.py" ]
[ "import numpy as np\n\ndef make_exp_kernel(L0):\n def exp_kernel(x1, x2):\n x1 = np.expand_dims(x1, 2) # Append a singleton dimension\n x2 = x2.T\n return np.exp(-np.mean(np.abs(x1 - x2), axis=1) / L0)\n return exp_kernel\n\ndef make_sq_exp_kernel(L0):\n def sq_exp_kernel(x1, x2):\n x1 = np.expand_dims(x1, 2) # Append a singleton dimension\n x2 = x2.T\n return np.exp(-np.sum((x1 - x2)**2, axis=1) / (2 * L0**2))\n return sq_exp_kernel\n\ndef weighted_neighbors_loss(train_data, valid_data, kernel):\n \"\"\"Computes the negative log prob per data point.\"\"\"\n X_train, T_train = train_data\n X_valid, T_valid = valid_data\n weight_mat = kernel(X_valid, X_train)\n label_probs = np.dot(weight_mat, T_train)\n label_probs = label_probs / np.sum(label_probs, axis=1, keepdims=True)\n mean_neg_log_prob = - np.mean(np.log(np.sum(label_probs * T_valid,\n axis=1)), axis=0)\n return mean_neg_log_prob\n" ]
[ [ "numpy.sum", "numpy.abs", "numpy.dot", "numpy.expand_dims" ] ]
amirbitran/dbfold
[ "f8f04b560da14611aa21ce07600188cb44d67d1c" ]
[ "dbfold/analyze_structures.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 24 17:59:20 2017\n\n@author: amirbitran\n\nVarious functions that serve to compute the contacts matrix for a series of PDB snapshots\n\n\"\"\"\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport sklearn\nfrom sklearn import metrics\nfrom dbfold.utils import loopCluster\nimport joblib\nimport copy as cp\nimport matplotlib.colors as cccc\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n \n\ndef compute_contacts_matrix(coords, mode='binary', thresh=7.8, min_seq_separation=8):\n \"\"\"\n much faster computation\n min_seq_separation is minimum distnce the two residues must be apart in sequence for them to be counted\n \n You can specify either of two modes:\n \n 1. 'binary': Returns 1 at positions where distance is less than or equal to thresh\n 2. 'distances': Returns inter-residue distance wherever this distances is less than or equal to thresh\n \n \"\"\"\n\n M=metrics.pairwise.pairwise_distances(coords)\n M=np.tril(M, -min_seq_separation) #-min_seq_separation enures that we do not count residues that are closer than min_seq_separation \n if mode=='binary':\n contacts=np.zeros(np.shape(M))\n contacts[np.where((M<thresh) & (M!=0))]=1\n elif mode=='distances':\n contacts=np.zeros(np.shape(M))\n contacts[M>0]=M[M>0]\n return contacts\n\n\n\n\n\n\ndef compute_RG(snapshot, atom='CA'):\n \"\"\"\n Radius of gyration...\n \"\"\"\n coords, resis = read_PDB(snapshot, atom)\n R_cm = np.mean(coords, axis=0)\n dR = coords - R_cm\n mag_R = np.sum(dR*dR, axis=1)\n RG = np.sqrt(np.mean(mag_R))\n return RG\n\n\ndef count_contacts(native_file, d_cutoff, min_seq_separation):\n coords, resis=read_PDB(native_file, 'CA')\n native_contacts=compute_contacts_matrix(coords, thresh=d_cutoff, min_seq_separation=min_seq_separation)\n return int(np.sum(native_contacts))\n\n\n\n\n\ndef create_substructure_PML(PDB_path, subs_to_plot, d_cutoff, min_clustersize, contact_sep_thresh,min_seq_separation=8, substructures = [], colours = []):\n \"\"\"\n Identifies substructures, then creates a pymol .pml script that draws those substructures as colored contacts directly on the pymol\n \n Ex. Create_substructure_PML('MARR_umbrella3/marr_0.100_Emin.pdb', ['a','b','c','d','e','f'], 7.8, 7, 3)\n You can also pre-enter the substructures as an optional argument\n \n Otherwise, it will compute the substrucutres using PDB_path and save the file as PDB_path but with .pml instead of .pdb\n \n You can optinally input the sequence of colors you want to use to paint the substructures (using the fancy British spelling colours)\n Otherwise, it will color things automatically using the usual default sequence\n That optional argument, if used, needs to have len equal to thhat of subs_to_plot: one color per substructure to plot\n \n \n \"\"\"\n alphabet = 'abcdefghijklmnopqrstuvwxyz'\n \n if len(substructures)==0:\n native_contacts, substructures = identify_native_substructures(PDB_path, d_cutoff, min_seq_separation, contact_sep_thresh, min_clustersize, plot=False)\n \n prefix = PDB_path.split('pdb')[0]\n PML_path = '{}pml'.format(prefix)\n\n Nsubs = np.shape(substructures)[2]\n \n file = open(PML_path, 'w')\n file.write('bg white \\n color gray \\n')\n \n \n if len(colours)==0:\n colors=cm.get_cmap('jet')\n \n \n counter = 0\n for s in range(Nsubs): \n if alphabet[s] in subs_to_plot: \n if len(colours)==0:\n curr_color=colors((s)/(Nsubs-1 ))\n else:\n curr_color = colours[counter]\n c_hex = cccc.to_hex(curr_color)\n c_hex = '0x{}'.format(c_hex.split('#')[1])\n sub = substructures[:,:,s]\n contacts = np.where(sub) \n substr = 'sub{}'.format(alphabet[s])\n for z in range(len(contacts[0])):\n i = contacts[0][z]+1\n j = contacts[1][z]+1\n lines = \"select aa, //resi {}/CA \\n select bb, //resi {}/CA \\n distance {}, aa, bb \\n hide labels, {} \\n set dash_color, {}, {} \\n \".format(i, j, substr, substr, c_hex, substr)\n file.write(lines)\n \n file.write('\\n set dash_gap, 0.5 \\n set dash_radius, 0.2 \\n')\n counter+=1\n \n \n file.close()\n \n\ndef find_native_contacts(native_file, thresh, min_seq_separation, mode = 'binary'):\n \"\"\"\n finds all native contacts from native PDB file\n \"\"\"\n native_coords, resis=read_PDB(native_file, atom='CA')\n native_contacts=compute_contacts_matrix(native_coords, thresh = thresh, min_seq_separation = min_seq_separation, mode = mode )\n return native_contacts\n \n\n\ndef identify_native_substructures(native_file, d_cutoff, min_seq_separation, contact_sep_thresh, min_clustersize,atom='CA', labelsize = 30, fontsize = 30, max_res = None, plot=True, ax = None, native_contacts=[], verbose=False):\n \"\"\"\n Identify substructures within native file contact map\n Using the following strategy\n \n We produce a contact map which is a bunch of dots\n Contacts correspond to pairs of residues that are less than d_cutoff apart\n 6 Angstroms is generally a good value, but may want a larger value for helical proteins where residues interact primarily\n via sidechains, and thus the alpha carbons are further apart\n \n We only count contacts if the residues are separated by min_seq_separation along the primary sequence\n We set min_seq_separation relatively high because we don't care to include intra-helix contacts within our contact map\n \n Ce can calculate the \"Manhattan\" distnace between every pair of dots on that contact map \n and build a graph of contacts in which two contacts are connected if they are less than some\n threshold distance, contact_sep_thresh, apart in the contact map \n \n Then, we find all connected components of this graph, each of which is a substructure\n But we only keep substructures whose number of residues is at least min_clustersize, to avoid sparse contacts here and there that we dont' care about\n \n Gives you option to input native contacts a priori, but by defualt you don't do this (value is set to None)\n \n You set Max_res to something other than None if you wish to plot only up to a certain residue number (ex. to depict what substructures can be formed when the first 100 AAs are synthesized)\n \"\"\"\n if len(native_contacts)==0:\n coords, resis=read_PDB(native_file, atom)\n #we get a contact map with a min seq separation larger than usual to avoid helices\n \n native_distances=compute_contacts_matrix(coords, mode='distances', min_seq_separation=min_seq_separation)\n \n native_contacts=np.zeros(np.shape(native_distances))\n native_contacts[np.where((native_distances<d_cutoff) & (native_distances!=0))]=1\n\n \n positions=np.where(native_contacts==1) #which residues participate in contacts\n positions=np.transpose(positions)\n\n M=metrics.pairwise.pairwise_distances(positions, metric='manhattan') #how far is each contact from each other contact?\n \n #To find connected components, I use my loopCluster function by feeding in the positions ofr the contacts instead of the \"files\",\n #as well as above matrix M as d_contacts\n \n clusters, pairs_in_substructures, mean_intercluster, mean_intracluster=loopCluster(contact_sep_thresh, positions, M, sort_orphans=False, min_clustersize=min_clustersize, verbose=verbose)\n\n\n #pairs in substructures is a list of sublists, each of which correspodns to a given substructure\n #Within a given sublist, there are a bunch of pairs which tell you which pairs of residues belong to that substructure\n \n #The above is in a messy form, so we convert it into a form that allows for numpy indexing,\n #where we have a list of sublists, each sublist contains two arrays, the first of which gives the first indices for the interacting residues\n #pairs_in_substructures=[[np.array(C)[:,0], np.array(C)[:,1]] for C in pairs_in_substructures]\n pairs_in_substructures=[(np.array(C)[:,0], np.array(C)[:,1]) for C in pairs_in_substructures]\n \n \n \n \n nsubstructures=len(pairs_in_substructures) #we now produce a set of matrices...the ith page tells you which contacts belong to the ith substructure\n substructures=np.zeros((np.shape(native_contacts)[0], np.shape(native_contacts)[1], nsubstructures))\n for n in range(nsubstructures):\n SS=np.zeros(np.shape(native_contacts))\n SS[pairs_in_substructures[n]]=1\n substructures[:,:,n]=SS\n if plot:\n visualize_substructures(native_contacts, substructures, max_res = max_res, ax = ax, labelsize = labelsize, fontsize = fontsize)\n #print(positions)\n return native_contacts, substructures\n\ndef PDB_contacts_matrix(PDB_file, thresh=7.8, min_seq_separation=8, plot = True,mode='binary'):\n \"\"\"\n Input PDB file, plots contacts matrix\n \n \"\"\"\n\n coords, resis = read_PDB(PDB_file, 'CA')\n M=metrics.pairwise.pairwise_distances(coords)\n M=np.tril(M, -min_seq_separation) #-min_seq_separation enures that we do not count residues that are closer than min_seq_separation\n if mode=='binary':\n contacts=np.zeros(np.shape(M))\n contacts[np.where((M<thresh) & (M!=0))]=1\n elif mode=='distances':\n contacts=np.zeros(np.shape(M))\n contacts[M>0]=M[M>0]\n\n if plot:\n plt.figure()\n plt.imshow(contacts)\n plt.title(PDB_file)\n \n return contacts\n\n\n\n\n\n\n\ndef read_PDB(file, atom):\n \"\"\"\n extracts coordinates for some side chain atom in some PDB file\n For instance, atom will have value 'CA' if you care about the alpha carbons\n \n TODO: Fix this so it can deal with chain labels\n Right now if the PDB has a chain label in the fifth column, this will give nonsense results\n \"\"\"\n openfile=open(file)\n \n resis=[]\n coords=[]\n \n \n for line in openfile.readlines():\n #print(line)\n \n line=line.rstrip('\\n')\n entries=line.split()\n if entries[0]=='ATOM':\n if entries[2]==atom and entries[4] =='A' and entries[3]!='GLY': #So long as the current residue is not a glycine, we append the coordinate for the carbon of interest \n resis.append(entries[3])\n coords.append([float(entries[6]), float(entries[7]), float(entries[8])]) \n elif len(entries)>1 and entries[2]==atom and entries[4] !='A' and entries[3]!='GLY':\n \t\t\t#first, we debug an error that sometimes happens\n if '-' in entries[5][1:-1]: #occasionally, when the y coordinate has a negative sign and three digits or more (ex. -100), the tab between the x and y components dissappears and entry [6] mergies into entry [5] (ex. -50-100)\n x=entries[5]\n entries[5]=x[0:x[1:-1].index('-')+1] #we ignore the first element of enries 6 in case it is a - sign--we don't care about that one\n entries[6]=x[(x[1:-1].index('-')+1):]\n if '-' in entries[6][1:-1]: #occasionally, when the z coordinate has a negative sign and three digits or more (ex. -100), the tab between the z and y components dissappears and entry [7] mergies into entry [6] (ex. -50-100)\n x=entries[6]\n entries[6]=x[0:x[1:-1].index('-')+1] #we ignore the first element of enries 6 in case it is a - sign--we don't care about that one\n entries[7]=x[(x[1:-1].index('-')+1):] \n resis.append(entries[3])\n coords.append([float(entries[5]), float(entries[6]), float(entries[7])])\n elif len(entries)>1 and entries[2]=='CA' and entries[4] =='A' and entries[3]=='GLY': #But if the current residue is a glycine, we can only append the alpha carbon since there is no side chain\n resis.append(entries[3])\n coords.append([float(entries[6]), float(entries[7]), float(entries[8])]) \n elif len(entries)>1 and entries[2]=='CA' and entries[4] !='A' and entries[3]=='GLY': \n \t\t\t#first, we debug an error that sometimes happens\n if '-' in entries[5][1:-1]: #occasionally, when the y coordinate has a negative sign and three digits or more (ex. -100), the tab between the x and y components dissappears and entry [6] mergies into entry [5] (ex. -50-100)\n x=entries[5]\n entries[5]=x[0:x[1:-1].index('-')+1] #we ignore the first element of enries 6 in case it is a - sign--we don't care about that one\n entries[6]=x[(x[1:-1].index('-')+1):]\n if '-' in entries[6][1:-1]: #occasionally, when the z coordinate has a negative sign and three digits or more (ex. -100), the tab between the z and y components dissappears and entry [7] mergies into entry [6] (ex. -50-100)\n x=entries[6]\n entries[6]=x[0:x[1:-1].index('-')+1] #we ignore the first element of enries 6 in case it is a - sign--we don't care about that one\n entries[7]=x[(x[1:-1].index('-')+1):] \n resis.append(entries[3])\n coords.append([float(entries[5]), float(entries[6]), float(entries[7])])\n \n coords=np.array(coords)\n return coords, resis\n \n\n\ndef score_snapshot(snapshot, substructures, atom='CA', min_seq_separation=8 ):\n \"\"\"\n Assigns a set of scores for a snapshot\n the ith score tells you what is the average distnace between pairs of residues residues that participate in the ith substructure, in this snapshto\n If the score is close to the characteristic contact distnace, then the substructure should be mostly formed\n \"\"\"\n coords, resis=read_PDB(snapshot, atom)\n distances=compute_contacts_matrix(coords, mode='distances', min_seq_separation=min_seq_separation)\n length=np.shape(distances)[0]\n len_substructures=np.shape(substructures)[0]\n if length>len_substructures: #We are applying substructures from a smaller protein to analyze a larger protein, so we only keep the part of the larger protein that is encompassed by these substructures\n \tdistances=distances[0:len_substructures, 0:len_substructures]\n nsubstructures=np.shape(substructures)[2]\n scores=np.zeros((nsubstructures))\n for s in range(nsubstructures): \n sub=substructures[:,:,s]\n participation=np.multiply(distances, sub)#gives the overlap between native substrucutres and this snapshot's contacts\n scores[s]=np.mean(participation[np.nonzero(participation)])\n return scores, distances\n\n\ndef visualize_nonnatives(nonnatives_path, native_file, d_cutoff=6.5, cmap='Greys', Return = False, cbar = True, filter_natives = True, filter_distance = 2, vmax = 1, alpha = 1,custom_filter = None, ax=None, labelsize = 40):\n \"\"\"\n Reads a file of the form Distance_maps.dat and makes a contact map of nonnative contacts with shading according to frequency with whcih \n that contact is observed\n \n d_cutoff is distance cutoff with which you identify NATIVE structures to subtract off from the nonnatives...sholud be\n the same as whatever was used to identify the nonnatives\n \n if filter_natives, then we ignore the native contacts, as well as a border around them given by filter_distance\n You also have the option to enter a Custom filter, which is a matrix of 1's at positions where you want to filter out the contact map...by default this is off and set to none\n Note that if a custom_filter is used, you still pad that filter with a border given by filter_distance\n \n If both filter_natives is set to and and you provide a custom filter, then the two filters are used in conjunction\n \n By the way, the variable vmax says what is the strongest value in the colorbar\n By default, it's 1, but you can also set it to None in which case it becomes the maximum value in the map\n \"\"\"\n \n native_contacts, substructures = identify_native_substructures(native_file, d_cutoff=d_cutoff, plot=False)\n [distance_maps, PDB_files, filescores]=joblib.load(nonnatives_path)\n\n if np.shape(distance_maps)[2]>len(PDB_files): #there is an extra page attached to end of the distance maps that tells you mean distances between residues\n mean_distances = distance_maps[:,:,-1]\n distance_maps = distance_maps[:, :, 0:-1]\n \n \n mean_nonnatives=np.mean(distance_maps, axis=2)\n NN = np.shape(mean_nonnatives)[0]\n \n if filter_natives or np.shape(custom_filter)!=():\n \n if filter_natives and np.shape(custom_filter)==():\n Filter=cp.deepcopy(native_contacts)\n\n elif filter_natives and np.shape(custom_filter)!=():\n Filter = cp.deepcopy(native_contacts) + custom_filter\n zz = np.zeros(np.shape(Filter))\n zz[np.where(Filter>0)]=1\n Filter = zz\n \n else:\n Filter = custom_filter\n \n #plt.figure()\n #plt.imshow(Filter)\n\n for d in range(-filter_distance, filter_distance+1): #gets rid of register-shifted native contacts\n \n im1_to_add=np.roll(Filter, d, axis=1)\n if d<0:\n im1_to_add[:, d:]=0\n else:\n im1_to_add[:, 0:d]=0\n \n im2_to_add=np.roll(Filter, d, axis=0)\n if d<0:\n im2_to_add[d:,:]=0\n else:\n im2_to_add[0:d, :]=0\n Filter=Filter+im1_to_add + im2_to_add\n Filter[np.where(Filter)]=1\n #plt.figure()\n #plt.imshow(Filter)\n mean_nonnatives = np.multiply(mean_nonnatives, 1 - Filter)\n\n\n #if filter_natives: mean_nonnatives=np.multiply(mean_nonnatives, 1 - native_contacts)\n \n #Commented all this out September 3 2019\n #if cmap != 'Greys':\n # for i in range(NN):\n # for j in range(NN):\n # if mean_nonnatives[i,j]==0:\n # mean_nonnatives[i,j] = np.nan #makes points without any contact probability show up as white rather than peach red\n \n \n if vmax == None:\n vmax = np.max(mean_nonnatives)\n normalize = cccc.Normalize(vmin = 0, vmax = vmax)\n \n if ax == None:\n fig, ax = plt.subplots()\n if cmap!=None:\n #im = ax.imshow(mean_nonnatives, cmap=cmap, norm = normalize, alpha = alpha, origin = 'lower')\n im = ax.imshow(mean_nonnatives + np.transpose(mean_nonnatives), cmap=cmap, norm = normalize, alpha = alpha, origin = 'upper') #changed to this on 1/10/19\n else:\n #im = ax.imshow(mean_nonnatives, norm = normalize, alpha = alpha, origin = 'lower')\n im = ax.imshow(mean_nonnatives + np.transpose(mean_nonnatives), norm = normalize, alpha = alpha, origin = 'upper') #changed to this on 1/10/19\n #im.set_clim((0, vmax))\n \n if cbar:\n cbar = plt.colorbar(im)\n cbar.ax.tick_params(labelsize=labelsize) \n ax.tick_params(labelsize=labelsize)\n \n ax.plot(np.arange(0, len(mean_nonnatives)), np.arange(0, len(mean_nonnatives)), color='gray', linestyle=':' ) #added 1/10/19\n \n if Return: return im\n\n\n\n\n\ndef visualize_substructures( native_contacts, substructures, max_res = None, ax = None, labelsize = 30, fontsize = 30):\n \"\"\"\n Visualizes substructures as follows\n Everything that is a native contact but not part of any substructure will have value -1 on shown image\n (Update 10/1/18, actually will only show contacts that are part of substructures)\n Meanwhile, everything that is part of substructure i (i ranges from 0 to N_substructures-1) will have value i\n Finally, all non-contacts will just be Nans and appear white\n \n Edited this on 2/4/19 so that substructures are labeled by letter rather than number\n Also reinstated the feature that contacts unassigned to substructures are visualized\n \n On 2/10/2020, Changed a bit how the script work\n Made it a bit simpler\n Also made it so unassigned contacts are now shown in gray\n \"\"\"\n alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' \n substructure_image=np.zeros(np.shape(native_contacts)) \n native_contacts=native_contacts+np.transpose(native_contacts) \n unassigned_contacts = cp.deepcopy(native_contacts)\n for s in range(np.shape(substructures)[2]): \n substructure_image+=(s+1)*(substructures[:,:,s]+substructures[:,:,s].transpose())\n #substructure_image+=(s+1)*substructures[:,:,s] \n unassigned_contacts-=substructures[:,:,s]+substructures[:,:,s].transpose()\n\n substructure_image[substructure_image==0] = np.nan #Set background to white\n #im[im<0]=np.nan #10/1 \n #im[np.diag_indices(len(native_contacts))]=0 \n colors=cm.get_cmap('jet') \n if ax ==None: fig, ax = plt.subplots()\n #ax.imshow(im, cmap='jet')\n ax.imshow(substructure_image, cmap='jet') \n ax.tick_params(labelsize=labelsize) \n for s in range(np.shape(substructures)[2]): \n #Let's annotate\n #y_pos=np.where(substructures[:,:,s])[0][0]-3\n y_pos=np.where(substructures[:,:,s])[0][0]+4 #2/4, decreased this from +6\n x_pos=np.where(substructures[:,:,s])[1][0]+5 #2/4, increased this from +5\n #curr_color=colors((s+1)/(np.max(substructure_image) ))\n curr_color=colors((s)/(np.nanmax(substructure_image)-1 ))\n #print(np.max(substructure_image)-1)\n ax.annotate('{}'.format(alphabet[s]), (x_pos, y_pos), fontsize=fontsize, color=curr_color)\n ax.annotate('{}'.format(alphabet[s]), (y_pos-5, x_pos-8), fontsize=fontsize, color=curr_color)\n \n nsubstructures=np.shape(substructures)[2]\n nbins=nsubstructures+1 #number of colors we are showing...add 1 to accoutn for unassigned contacts\n\n unassigned_contacts[unassigned_contacts==0] = np.nan\n ax.imshow(unassigned_contacts, cmap = 'gray', alpha = 0.5) \n ax.plot(np.arange(0, len(native_contacts)), np.arange(0, len(native_contacts)), color='gray', linestyle=':' )\n if max_res !=None:\n ax.set_xlim(( max_res, 0))\n ax.set_ylim((0, max_res))\n\n\n\n\n\n\n" ]
[ [ "numpy.mean", "numpy.multiply", "numpy.where", "numpy.max", "matplotlib.pyplot.colorbar", "matplotlib.colors.to_hex", "matplotlib.pyplot.subplots", "numpy.nonzero", "numpy.transpose", "numpy.nanmax", "numpy.array", "numpy.zeros", "matplotlib.cm.get_cmap", "matplotlib.pyplot.title", "numpy.roll", "numpy.shape", "matplotlib.pyplot.figure", "numpy.tril", "numpy.sum", "matplotlib.colors.Normalize", "sklearn.metrics.pairwise.pairwise_distances", "matplotlib.pyplot.imshow" ] ]
qiujiangkun/mplopengl
[ "f828d17cd7b68856f92958e909456ebb6043445e" ]
[ "tests/test_backend_qt.py" ]
[ "import copy\nfrom unittest import mock\n\nimport matplotlib\nimport pytest\nfrom matplotlib import pyplot as plt\nfrom matplotlib._pylab_helpers import Gcf\n\n\n@pytest.fixture(autouse=True)\ndef mpl_test_settings(qt_module, mpl_test_settings):\n \"\"\"\n Ensure qt_module fixture is *first* fixture.\n\n We override the `mpl_test_settings` fixture and depend on the `qt_module`\n fixture first. It is very important that it is first, because it skips\n tests when Qt is not available, and if not, then the main\n `mpl_test_settings` fixture will try to switch backends before the skip can\n be triggered.\n \"\"\"\n pass\n\n\n@pytest.fixture\ndef qt_module(request):\n backend, = request.node.get_closest_marker('backend').args\n if backend == 'Qt4Agg':\n try:\n import PyQt4\n # RuntimeError if PyQt5 already imported.\n except (ImportError, RuntimeError):\n try:\n import PySide\n except ImportError:\n pytest.skip(\"Failed to import a Qt4 binding.\")\n elif backend == 'Qt5Agg':\n try:\n import PyQt5\n # RuntimeError if PyQt4 already imported.\n except (ImportError, RuntimeError):\n try:\n import PySide2\n except ImportError:\n pytest.skip(\"Failed to import a Qt5 binding.\")\n else:\n raise ValueError('Backend marker has unknown value: ' + backend)\n\n qt_compat = pytest.importorskip('matplotlib.backends.qt_compat')\n QtCore = qt_compat.QtCore\n\n if backend == 'Qt4Agg':\n try:\n py_qt_ver = int(QtCore.PYQT_VERSION_STR.split('.')[0])\n except AttributeError:\n py_qt_ver = QtCore.__version_info__[0]\n\n if py_qt_ver != 4:\n pytest.skip(reason='Qt4 is not available')\n\n from matplotlib.backends.backend_qt4 import (\n MODIFIER_KEYS, SUPER, ALT, CTRL, SHIFT)\n elif backend == 'Qt5Agg':\n from matplotlib.backends.backend_qt5 import (\n MODIFIER_KEYS, SUPER, ALT, CTRL, SHIFT)\n\n mods = {}\n keys = {}\n for name, index in zip(['Alt', 'Control', 'Shift', 'Super'],\n [ALT, CTRL, SHIFT, SUPER]):\n _, mod, key = MODIFIER_KEYS[index]\n mods[name + 'Modifier'] = mod\n keys[name + 'Key'] = key\n\n return QtCore, mods, keys\n\n\n@pytest.fixture\ndef qt_key(request):\n QtCore, _, keys = request.getfixturevalue('qt_module')\n if request.param.startswith('Key'):\n return getattr(QtCore.Qt, request.param)\n else:\n return keys[request.param]\n\n\n@pytest.fixture\ndef qt_mods(request):\n QtCore, mods, _ = request.getfixturevalue('qt_module')\n result = QtCore.Qt.NoModifier\n for mod in request.param:\n result |= mods[mod]\n return result\n\n\n@pytest.mark.parametrize('backend', [\n # Note: the value is irrelevant; the important part is the marker.\n pytest.param('Qt4Agg', marks=pytest.mark.backend('Qt4Agg')),\n pytest.param('Qt5Agg', marks=pytest.mark.backend('Qt5Agg')),\n])\ndef test_fig_close(backend):\n # save the state of Gcf.figs\n init_figs = copy.copy(Gcf.figs)\n\n # make a figure using pyplot interface\n fig = plt.figure()\n\n # simulate user clicking the close button by reaching in\n # and calling close on the underlying Qt object\n fig.canvas.manager.window.close()\n\n # assert that we have removed the reference to the FigureManager\n # that got added by plt.figure()\n assert init_figs == Gcf.figs\n\n\n@pytest.mark.backend('Qt5Agg')\ndef test_fig_signals(qt_module):\n # Create a figure\n fig = plt.figure()\n\n # Access QtCore\n QtCore = qt_module[0]\n\n # Access signals\n import signal\n event_loop_signal = None\n\n # Callback to fire during event loop: save SIGINT handler, then exit\n def fire_signal_and_quit():\n # Save event loop signal\n nonlocal event_loop_signal\n event_loop_signal = signal.getsignal(signal.SIGINT)\n\n # Request event loop exit\n QtCore.QCoreApplication.exit()\n\n # Timer to exit event loop\n QtCore.QTimer.singleShot(0, fire_signal_and_quit)\n\n # Save original SIGINT handler\n original_signal = signal.getsignal(signal.SIGINT)\n\n # Use our own SIGINT handler to be 100% sure this is working\n def CustomHandler(signum, frame):\n pass\n\n signal.signal(signal.SIGINT, CustomHandler)\n\n # mainloop() sets SIGINT, starts Qt event loop (which triggers timer and\n # exits) and then mainloop() resets SIGINT\n matplotlib.backends.backend_qt5._BackendQT5.mainloop()\n\n # Assert: signal handler during loop execution is signal.SIG_DFL\n assert event_loop_signal == signal.SIG_DFL\n\n # Assert: current signal handler is the same as the one we set before\n assert CustomHandler == signal.getsignal(signal.SIGINT)\n\n # Reset SIGINT handler to what it was before the test\n signal.signal(signal.SIGINT, original_signal)\n\n\n@pytest.mark.parametrize(\n 'qt_key, qt_mods, answer',\n [\n ('Key_A', ['ShiftModifier'], 'A'),\n ('Key_A', [], 'a'),\n ('Key_A', ['ControlModifier'], 'ctrl+a'),\n ('Key_Aacute', ['ShiftModifier'],\n '\\N{LATIN CAPITAL LETTER A WITH ACUTE}'),\n ('Key_Aacute', [],\n '\\N{LATIN SMALL LETTER A WITH ACUTE}'),\n ('ControlKey', ['AltModifier'], 'alt+control'),\n ('AltKey', ['ControlModifier'], 'ctrl+alt'),\n ('Key_Aacute', ['ControlModifier', 'AltModifier', 'SuperModifier'],\n 'ctrl+alt+super+\\N{LATIN SMALL LETTER A WITH ACUTE}'),\n ('Key_Backspace', [], 'backspace'),\n ('Key_Backspace', ['ControlModifier'], 'ctrl+backspace'),\n ('Key_Play', [], None),\n ],\n indirect=['qt_key', 'qt_mods'],\n ids=[\n 'shift',\n 'lower',\n 'control',\n 'unicode_upper',\n 'unicode_lower',\n 'alt_control',\n 'control_alt',\n 'modifier_order',\n 'backspace',\n 'backspace_mod',\n 'non_unicode_key',\n ]\n)\n@pytest.mark.parametrize('backend', [\n # Note: the value is irrelevant; the important part is the marker.\n pytest.param('Qt4Agg', marks=pytest.mark.backend('Qt4Agg')),\n pytest.param('Qt5Agg', marks=pytest.mark.backend('Qt5Agg')),\n])\ndef test_correct_key(backend, qt_key, qt_mods, answer):\n \"\"\"\n Make a figure\n Send a key_press_event event (using non-public, qtX backend specific api)\n Catch the event\n Assert sent and caught keys are the same\n \"\"\"\n qt_canvas = plt.figure().canvas\n\n event = mock.Mock()\n event.isAutoRepeat.return_value = False\n event.key.return_value = qt_key\n event.modifiers.return_value = qt_mods\n\n def receive(event):\n assert event.key == answer\n\n qt_canvas.mpl_connect('key_press_event', receive)\n qt_canvas.keyPressEvent(event)\n\n\n@pytest.mark.backend('Qt5Agg')\ndef test_dpi_ratio_change():\n \"\"\"\n Make sure that if _dpi_ratio changes, the figure dpi changes but the\n widget remains the same physical size.\n \"\"\"\n\n prop = 'matplotlib.backends.backend_qt5.FigureCanvasQT._dpi_ratio'\n\n with mock.patch(prop, new_callable=mock.PropertyMock) as p:\n p.return_value = 3\n\n fig = plt.figure(figsize=(5, 2), dpi=120)\n qt_canvas = fig.canvas\n qt_canvas.show()\n\n from matplotlib.backends.backend_qt5 import qApp\n\n # Make sure the mocking worked\n assert qt_canvas._dpi_ratio == 3\n\n size = qt_canvas.size()\n\n qt_canvas.manager.show()\n qt_canvas.draw()\n qApp.processEvents()\n\n # The DPI and the renderer width/height change\n assert fig.dpi == 360\n assert qt_canvas.renderer.width == 1800\n assert qt_canvas.renderer.height == 720\n\n # The actual widget size and figure physical size don't change\n assert size.width() == 600\n assert size.height() == 240\n # assert qt_canvas.get_width_height() == (600, 240)\n # assert (fig.get_size_inches() == (5, 2)).all()\n\n p.return_value = 2\n\n assert qt_canvas._dpi_ratio == 2\n\n qt_canvas.draw()\n qApp.processEvents()\n # this second processEvents is required to fully run the draw.\n # On `update` we notice the DPI has changed and trigger a\n # resize event to refresh, the second processEvents is\n # required to process that and fully update the window sizes.\n qApp.processEvents()\n\n # The DPI and the renderer width/height change\n # assert fig.dpi == 240\n # assert qt_canvas.renderer.width == 1200\n # assert qt_canvas.renderer.height == 480\n\n # The actual widget size and figure physical size don't change\n assert size.width() == 600\n assert size.height() == 240\n # assert qt_canvas.get_width_height() == (600, 240)\n # assert (fig.get_size_inches() == (5, 2)).all()\n\n\n@pytest.mark.backend('Qt5Agg')\ndef test_subplottool():\n fig, ax = plt.subplots()\n with mock.patch(\n \"matplotlib.backends.backend_qt5.SubplotToolQt.exec_\",\n lambda self: None):\n fig.canvas.manager.toolbar.configure_subplots()\n\n\n@pytest.mark.backend('Qt5Agg')\ndef test_figureoptions():\n fig, ax = plt.subplots()\n ax.plot([1, 2])\n ax.imshow([[1]])\n ax.scatter(range(3), range(3), c=range(3))\n with mock.patch(\n \"matplotlib.backends.qt_editor._formlayout.FormDialog.exec_\",\n lambda self: None):\n fig.canvas.manager.toolbar.edit_parameters()\n" ]
[ [ "matplotlib.backends.backend_qt5.qApp.processEvents", "matplotlib.backends.backend_qt5._BackendQT5.mainloop", "matplotlib.pyplot.subplots", "matplotlib.pyplot.figure" ] ]
laugh12321/Hyperspectral-Unmixing
[ "0314bb4ef8f22ab85e8e739f02ccd86564af4d88" ]
[ "src/model/train_unmixing.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Jan 29, 2021\n\n@file: train_unmixing.py\n@desc: Perform the training of the models for the unmixing problem.\n@author: laugh12321\n@contact: laugh12321@vip.qq.com\n\"\"\"\nimport os\nimport numpy as np\nimport tensorflow as tf\nfrom typing import Dict\n\nimport src.model.enums as enums\nfrom src.utils import io, transforms\nfrom src.model.models import _get_model\nfrom src.utils.transforms import UNMIXING_TRANSFORMS\nfrom src.evaluation import time_metrics\nfrom src.evaluation.performance_metrics import UNMIXING_LOSSES, \\\n UNMIXING_TRAIN_METRICS\n\n\ndef train(data: Dict[str, np.ndarray],\n model_name: str,\n dest_path: str,\n sample_size: int,\n n_classes: int,\n lr: float,\n batch_size: int,\n epochs: int,\n verbose: int,\n shuffle: bool,\n patience: int,\n seed: int):\n \"\"\"\n Function for running experiments on various unmixing models,\n given a set of hyper parameters.\n\n :param data: The data dictionary containing\n the subsets for training and validation.\n First dimension of the datasets should be the number of samples.\n :param model_name: Name of the model, it serves as a key in the\n dictionary holding all functions returning models.\n :param dest_path: Path to where all experiment runs will be saved as\n subdirectories in this given directory.\n :param sample_size: Size of the input sample.\n :param n_classes: Number of classes.\n :param lr: Learning rate for the model, i.e., regulates\n the size of the step in the gradient descent process.\n :param batch_size: Size of the batch used in training phase,\n it is the size of samples per gradient step.\n :param epochs: Number of epochs for model to train.\n :param verbose: Verbosity mode used in training, (0, 1 or 2).\n :param shuffle: Boolean indicating whether to shuffle datasets.\n :param patience: Number of epochs without improvement in order to\n stop the training phase.\n :param seed: Seed for training reproducibility.\n \"\"\"\n # Reproducibility:\n np.random.seed(seed=seed)\n\n model = _get_model(\n model_key=model_name,\n **{'input_size': sample_size,\n 'n_classes': n_classes})\n model.summary()\n model.compile(\n optimizer=tf.keras.optimizers.Adam(lr=lr),\n loss=UNMIXING_LOSSES[model_name],\n metrics=UNMIXING_TRAIN_METRICS[model_name])\n\n time_history = time_metrics.TimeHistory()\n\n mcp_save = tf.keras.callbacks.ModelCheckpoint(\n os.path.join(dest_path, 'model.h5'),\n save_best_only=True,\n monitor='val_loss',\n mode='min')\n\n early_stopping = tf.keras.callbacks.EarlyStopping(\n monitor='val_loss',\n patience=patience,\n mode='min')\n\n callbacks = [time_history, mcp_save, early_stopping]\n\n train_dict = data[enums.Dataset.TRAIN].copy()\n val_dict = data[enums.Dataset.VAL].copy()\n\n min_, max_ = data[enums.DataStats.MIN], data[enums.DataStats.MAX]\n\n transformations = [transforms.MinMaxNormalize(min_=min_, max_=max_)]\n transformations += [t() for t in UNMIXING_TRANSFORMS[model_name]]\n\n train_dict = transforms.apply_transformations(train_dict, transformations)\n val_dict = transforms.apply_transformations(val_dict, transformations)\n\n history = model.fit(\n x=train_dict[enums.Dataset.DATA],\n y=train_dict[enums.Dataset.LABELS],\n epochs=epochs,\n verbose=verbose,\n shuffle=shuffle,\n validation_data=(val_dict[enums.Dataset.DATA],\n val_dict[enums.Dataset.LABELS]),\n callbacks=callbacks,\n batch_size=batch_size)\n\n np.savetxt(os.path.join(dest_path,\n 'min-max.csv'), np.array([min_, max_]),\n delimiter=',', fmt='%f')\n\n history.history[time_metrics.TimeHistory.__name__] = time_history.average\n\n io.save_metrics(dest_path=dest_path,\n file_name='training_metrics.csv',\n metrics=history.history)\n" ]
[ [ "numpy.random.seed", "numpy.array", "tensorflow.keras.optimizers.Adam", "tensorflow.keras.callbacks.EarlyStopping" ] ]
camillepradel/pykeen
[ "92a5186c522c3336e9febb2e5eada9ec4a584947" ]
[ "src/pykeen/models/unimodal/ermlpe.py" ]
[ "# -*- coding: utf-8 -*-\n\n\"\"\"An implementation of the extension to ERMLP.\"\"\"\n\nfrom typing import Optional, Type\n\nimport torch\nfrom torch import nn\n\nfrom ..base import EntityRelationEmbeddingModel\nfrom ...losses import BCEAfterSigmoidLoss, Loss\nfrom ...regularizers import Regularizer\nfrom ...triples import TriplesFactory\n\n__all__ = [\n 'ERMLPE',\n]\n\n\nclass ERMLPE(EntityRelationEmbeddingModel):\n r\"\"\"An extension of ERMLP proposed by [sharifzadeh2019]_.\n\n This model uses a neural network-based approach similar to ERMLP and with slight modifications.\n In ERMLP, the model is:\n\n .. math::\n\n f(h, r, t) = \\textbf{w}^{T} g(\\textbf{W} [\\textbf{h}; \\textbf{r}; \\textbf{t}])\n\n whereas in ERMPLE the model is:\n\n .. math::\n\n f(h, r, t) = \\textbf{t}^{T} f(\\textbf{W} (g(\\textbf{W} [\\textbf{h}; \\textbf{r}]))\n\n including dropouts and batch-norms between each two hidden layers.\n ConvE can be seen as a special case of ERMLPE that contains the unnecessary inductive bias of convolutional\n filters. The aim of this model is to show that lifting this bias from ConvE (which simply leaves us with a\n modified ERMLP model), not only reduces the number of parameters but also improves performance.\n\n \"\"\"\n\n #: The default strategy for optimizing the model's hyper-parameters\n hpo_default = dict(\n embedding_dim=dict(type=int, low=50, high=350, q=25),\n hidden_dim=dict(type=int, low=50, high=450, q=25),\n input_dropout=dict(type=float, low=0.0, high=0.8, q=0.1),\n hidden_dropout=dict(type=float, low=0.0, high=0.8, q=0.1),\n )\n #: The default loss function class\n loss_default: Type[Loss] = BCEAfterSigmoidLoss\n #: The default parameters for the default loss function class\n loss_default_kwargs = {}\n\n def __init__(\n self,\n triples_factory: TriplesFactory,\n hidden_dim: int = 300,\n input_dropout: float = 0.2,\n hidden_dropout: float = 0.3,\n embedding_dim: int = 200,\n automatic_memory_optimization: Optional[bool] = None,\n loss: Optional[Loss] = None,\n preferred_device: Optional[str] = None,\n random_seed: Optional[int] = None,\n regularizer: Optional[Regularizer] = None,\n ) -> None:\n super().__init__(\n triples_factory=triples_factory,\n embedding_dim=embedding_dim,\n automatic_memory_optimization=automatic_memory_optimization,\n loss=loss,\n preferred_device=preferred_device,\n random_seed=random_seed,\n regularizer=regularizer,\n )\n self.hidden_dim = hidden_dim\n self.input_dropout = input_dropout\n\n self.linear1 = nn.Linear(2 * self.embedding_dim, self.hidden_dim)\n self.linear2 = nn.Linear(self.hidden_dim, self.embedding_dim)\n self.input_dropout = nn.Dropout(self.input_dropout)\n self.bn1 = nn.BatchNorm1d(self.hidden_dim)\n self.bn2 = nn.BatchNorm1d(self.embedding_dim)\n self.mlp = nn.Sequential(\n self.linear1,\n nn.Dropout(hidden_dropout),\n self.bn1,\n nn.ReLU(),\n self.linear2,\n nn.Dropout(hidden_dropout),\n self.bn2,\n nn.ReLU(),\n )\n\n # Finalize initialization\n self.reset_parameters_()\n\n def _reset_parameters_(self): # noqa: D102\n self.entity_embeddings.reset_parameters()\n self.relation_embeddings.reset_parameters()\n for module in [\n self.linear1,\n self.linear2,\n self.bn1,\n self.bn2,\n ]:\n module.reset_parameters()\n\n def score_hrt(self, hrt_batch: torch.LongTensor) -> torch.FloatTensor: # noqa: D102\n # Get embeddings\n h = self.entity_embeddings(hrt_batch[:, 0]).view(-1, self.embedding_dim)\n r = self.relation_embeddings(hrt_batch[:, 1]).view(-1, self.embedding_dim)\n t = self.entity_embeddings(hrt_batch[:, 2])\n\n # Embedding Regularization\n self.regularize_if_necessary(h, r, t)\n\n # Concatenate them\n x_s = torch.cat([h, r], dim=-1)\n x_s = self.input_dropout(x_s)\n\n # Predict t embedding\n x_t = self.mlp(x_s)\n\n # compare with all t's\n # For efficient calculation, each of the calculated [h, r] rows has only to be multiplied with one t row\n x = (x_t.view(-1, self.embedding_dim) * t).sum(dim=1, keepdim=True)\n # The application of the sigmoid during training is automatically handled by the default loss.\n\n return x\n\n def score_t(self, hr_batch: torch.LongTensor) -> torch.FloatTensor: # noqa: D102\n h = self.entity_embeddings(hr_batch[:, 0]).view(-1, self.embedding_dim)\n r = self.relation_embeddings(hr_batch[:, 1]).view(-1, self.embedding_dim)\n t = self.entity_embeddings.weight.transpose(1, 0)\n\n # Embedding Regularization\n self.regularize_if_necessary(h, r, t)\n\n # Concatenate them\n x_s = torch.cat([h, r], dim=-1)\n x_s = self.input_dropout(x_s)\n\n # Predict t embedding\n x_t = self.mlp(x_s)\n\n x = x_t @ t\n # The application of the sigmoid during training is automatically handled by the default loss.\n\n return x\n\n def score_h(self, rt_batch: torch.LongTensor) -> torch.FloatTensor: # noqa: D102\n h = self.entity_embeddings.weight\n r = self.relation_embeddings(rt_batch[:, 0]).view(-1, self.embedding_dim)\n t = self.entity_embeddings(rt_batch[:, 1]).view(-1, self.embedding_dim)\n\n # Embedding Regularization\n self.regularize_if_necessary(h, r, t)\n\n rt_batch_size = t.shape[0]\n\n # Extend each rt_batch of \"r\" with shape [rt_batch_size, dim] to [rt_batch_size, dim * num_entities]\n r = torch.repeat_interleave(r, self.num_entities, dim=0)\n # Extend each h with shape [num_entities, dim] to [rt_batch_size * num_entities, dim]\n # h = torch.repeat_interleave(h, rt_batch_size, dim=0)\n h = h.repeat(rt_batch_size, 1)\n\n # Extend t\n t = t.repeat_interleave(self.num_entities, dim=0)\n\n # Concatenate them\n x_s = torch.cat([h, r], dim=-1)\n x_s = self.input_dropout(x_s)\n\n # Predict t embedding\n x_t = self.mlp(x_s)\n\n # For efficient calculation, each of the calculated [h, r] rows has only to be multiplied with one t row\n x = (x_t.view(-1, self.embedding_dim) * t).sum(dim=1, keepdim=True)\n # The results have to be realigned with the expected output of the score_h function\n x = x.view(rt_batch_size, self.num_entities)\n # The application of the sigmoid during training is automatically handled by the default loss.\n\n return x\n" ]
[ [ "torch.nn.Linear", "torch.cat", "torch.nn.Dropout", "torch.repeat_interleave", "torch.nn.ReLU", "torch.nn.BatchNorm1d" ] ]
butala/spectrum
[ "0c81ddaf6d00c05434262d123a16fc39be4c6f64" ]
[ "src/spectrum/criteria.py" ]
[ "\"\"\"Criteria for parametric methods.\n\n.. topic:: This module provides criteria to automatically select order in\n parametric PSD estimate or pseudo spectrum estimates (e.g, music).\n\n Some criteria such as the AIC criterion helps to chose the order of PSD\n models such as the ARMA model. Nevertheless, it is difficult to estimate\n correctly the order of an ARMA model even by using these criteria. The\n reason being that even the Akaike criteria (AIC) does not provide the\n proper order with a probability of 1 with infinite samples.\n\n The order choice is related to an expertise of the signal. There is no\n exact criteria. However, they may provide useful information.\n\n AIC, AICc, KIC and AKICc are based on information theory. They attempt\n to balance the complexity (or length) of the model against how well the\n model fits the data. AIC and KIC are biased estimates of the asymmetric\n and the symmetric Kullback-Leibler divergence respectively. AICc and\n AKICc attempt to correct the bias.\n\n There are also criteria related to eigen analysis, which takes as input\n the eigen values of any PSD estimate method.\n\n.. rubric:: Example\n\n.. plot::\n :width: 80%\n :include-source:\n\n from spectrum import aryule, AIC, marple_data\n from pylab import plot, arange\n order = arange(1, 25)\n rho = [aryule(marple_data, i, norm='biased')[1] for i in order]\n plot(order, AIC(len(marple_data), rho, order), label='AIC')\n\n\n\n:References: bd-Krim Seghouane and Maiza Bekara\n \"A small sample model selection criterion based on Kullback's symmetric\n divergence\", IEEE Transactions on Signal Processing,\n Vol. 52(12), pp 3314-3323, Dec. 2004\n\n\"\"\"\n\n\nclass Criteria(object):\n \"\"\"Criteria class for an automatic selection of ARMA order.\n\n Available criteria are\n\n ======= =====================\n ======= =====================\n AIC see :func:`AIC`\n AICc see :func:`AICc`\n KIC see :func:`KIC`\n AKICc see :func:`AKICc`\n FPE see :func:`FPE`\n MDL see :func:`MDL`\n CAT see :func:`_CAT`\n ======= =====================\n\n\n \"\"\"\n valid_criteria_names = ['AIC', 'AICc', 'KIC', 'FPE', 'AKICc', 'MDL']\n error_incorrect_name = 'Invalid name provided. Correct names are %s ' \\\n % valid_criteria_names\n error_no_criteria_found = 'No names match the valid criteria names (%s)' \\\n % valid_criteria_names\n def __init__(self, name, N):\n \"\"\"Create a criteria object\n\n :param name: a string or list of strings containing valid criteria\n method's name\n :param int N: size of the data sample.\n\n \"\"\"\n #valid attributes\n self.__name = None\n self.name = name\n self.__N = N\n self.__rho = 0\n self.__k = None\n self.__old_data = None\n self.__data = None\n self.__norm = True\n\n def _getName(self):\n return self.__name\n def _setName(self, name):\n assert isinstance(name, str), 'name must be a string'\n if name in self.valid_criteria_names:\n self.__name = name\n else:\n raise ValueError(self.error_no_criteria_found)\n name = property(fget=_getName, fset=_setName, doc=\"Getter/Setter for the criteria name\")\n\n def _getData(self):\n return self.__data\n def _setData(self, data):\n # save the data value in old_data is there is something to save\n if self.data is None:\n self.__data = data\n self.__old_data = 2.*data\n else:\n self.__old_data = self.data\n self.__data = data\n data = property(fget=_getData, fset=_setData, doc=\"Getter/Setter for the criteria output\")\n\n def _getOldData(self):\n return self.__old_data\n old_data = property(fget=_getOldData, doc=\"Getter/Setter for the previous value\")\n\n def _getK(self):\n return self.__k\n k = property(fget=_getK, doc=\"Getter for k the order of evaluation\")\n\n def _getN(self):\n return self.__N\n def _setN(self, N):\n assert N > 0, 'N must be positive'\n self.__N = N\n N = property(fget=_getN, fset=_setN, doc=\"Getter/Setter for N\")\n\n def _getRho(self):\n return self.__rho\n def _setRho(self, rho):\n self.__rho = rho\n rho = property(fget=_getRho, fset=_setRho, doc=\"Getter/Setter for rho\")\n\n def __call__(self, rho=None, k=None, N=None, norm=True):\n \"\"\"Call the criteria function corresponding to :attr:`name`.\"\"\"\n self.__norm = norm\n if N is not None:\n self.N = N\n\n # we update rho only if it is needed (input different from self.rho)\n # if such case, we also update k\n if rho is not None:\n self.rho = rho\n if k is not None:\n self.__k = k\n self.__norm = norm\n #used to check if the criteria is reached or not\n\n f = eval(self.name)\n self.data = f(self.N, self.rho, self.k)\n # compare the new data with the previous one and return\n # False if the new value is larger so as to stop the iteration\n if self.old_data is not None and self.data is not None:\n if self.data > self.old_data:\n return False\n else:\n return True\n return True\n\n\ndef AIC(N, rho, k):\n r\"\"\"Akaike Information Criterion\n\n :param rho: rho at order k\n :param N: sample size\n :param k: AR order.\n\n If k is the AR order and N the size of the sample, then Akaike criterion is\n\n .. math:: AIC(k) = \\log(\\rho_k) + 2\\frac{k+1}{N}\n\n ::\n\n AIC(64, [0.5,0.3,0.2], [1,2,3])\n\n :validation: double checked versus octave.\n \"\"\"\n from numpy import log, array\n #k+1 #todo check convention. agrees with octave\n\n res = N * log(array(rho)) + 2.* (array(k)+1)\n return res\n\n\ndef AICc(N, rho, k, norm=True):\n r\"\"\"corrected Akaike information criterion\n\n .. math:: AICc(k) = log(\\rho_k) + 2 \\frac{k+1}{N-k-2}\n\n\n :validation: double checked versus octave.\n \"\"\"\n from numpy import log, array\n p = k #todo check convention. agrees with octave\n res = log(rho) + 2. * (p+1) / (N-p-2)\n return res\n\n\ndef KIC(N, rho, k):\n r\"\"\"Kullback information criterion\n\n .. math:: KIC(k) = log(\\rho_k) + 3 \\frac{k+1}{N}\n\n :validation: double checked versus octave.\n \"\"\"\n from numpy import log, array\n res = log(rho) + 3. * (k+1.) /float(N)\n return res\n\n\ndef AKICc(N, rho, k):\n r\"\"\"approximate corrected Kullback information\n\n .. math:: AKICc(k) = log(rho_k) + \\frac{p}{N*(N-k)} + (3-\\frac{k+2}{N})*\\frac{k+1}{N-k-2}\n\n \"\"\"\n from numpy import log, array\n p = k\n res = log(rho) + p/N/(N-p) + (3.-(p+2.)/N) * (p+1.) / (N-p-2.)\n return res\n\n\ndef FPE(N,rho, k=None):\n r\"\"\"Final prediction error criterion\n\n .. math:: FPE(k) = \\frac{N + k + 1}{N - k - 1} \\rho_k\n\n :validation: double checked versus octave.\n\n \"\"\"\n #k #todo check convention. agrees with octave\n fpe = rho * (N + k + 1.) / (N- k -1)\n return fpe\n\n\ndef MDL(N, rho, k):\n r\"\"\"Minimum Description Length\n\n .. math:: MDL(k) = N log \\rho_k + p \\log N\n\n :validation: results\n \"\"\"\n from numpy import log\n #p = arange(1, len(rho)+1)\n mdl = N* log(rho) + k * log(N)\n return mdl\n\n\ndef CAT(N, rho, k):\n r\"\"\"Criterion Autoregressive Transfer Function :\n\n .. math:: CAT(k) = \\frac{1}{N} \\sum_{i=1}^k \\frac{1}{\\rho_i} - \\frac{\\rho_i}{\\rho_k}\n\n .. todo:: validation\n \"\"\"\n from numpy import zeros, arange\n cat = zeros(len(rho))\n for p in arange(1, len(rho)+1):\n rho_p = float(N)/(N-p)*rho[p-1]\n s = 0\n for j in range(1, p+1):\n rho_j = float(N)/(N-j)*rho[j-1]\n s = s + 1./rho_j\n #print(s, s/float(N), 1./rho_p)\n cat[p-1] = s/float(N) - 1./rho_p\n return cat\n\n\ndef aic_eigen(s, N):\n r\"\"\"AIC order-selection using eigen values\n\n :param s: a list of `p` sorted eigen values\n :param N: the size of the input data. To be defined precisely.\n\n :return:\n * an array containing the AIC values\n\n Given :math:`n` sorted eigen values :math:`\\lambda_i` with\n :math:`0 <= i < n`, the proposed criterion from Wax and Kailath (1985)\n is:\n\n .. math:: AIC(k) = -2(n-k)N \\ln \\frac{g(k)}{a(k)} + 2k(2n-k)\n\n where the arithmetic sum :math:`a(k)` is:\n\n .. math:: a(k) = \\sum_{i=k+1}^{n}\\lambda_i\n\n and the geometric sum :math:`g(k)` is:\n\n .. math:: g(k) = \\prod_{i=k+1}^{n} \\lambda_i^{-(n-k)}\n\n The number of relevant sinusoids in the signal subspace is determined by\n selecting the minimum of `AIC`.\n\n .. seealso:: :func:`~spectrum.eigenfreq.eigen`\n .. todo:: define precisely the input parameter N. Should be the input\n data length but when using correlation matrix (SVD), I suspect it\n should be the length of the correlation matrix rather than the\n original data.\n\n :References:\n * [Marple]_ Chap 13,\n * [Wax]_\n \"\"\"\n import numpy as np\n\n kaic = []\n n = len(s)\n for k in range(0, n-1):\n ak = 1./(n-k) * np.sum(s[k+1:])\n gk = np.prod(s[k+1:]**(1./(n-k)))\n kaic.append( -2.*(n-k)*N * np.log(gk/ak) + 2.*k*(2.*n-k))\n\n return kaic\n\n\ndef mdl_eigen(s, N):\n r\"\"\"MDL order-selection using eigen values\n\n :param s: a list of `p` sorted eigen values\n :param N: the size of the input data. To be defined precisely.\n\n :return:\n * an array containing the AIC values\n\n .. math:: MDL(k) = (n-k)N \\ln \\frac{g(k)}{a(k)} + 0.5k(2n-k) log(N)\n\n .. seealso:: :func:`aic_eigen` for details\n\n :References:\n * [Marple]_ Chap 13,\n * [Wax]_\n \"\"\"\n import numpy as np\n kmdl = []\n n = len(s)\n for k in range(0, n-1):\n ak = 1./(n-k) * np.sum(s[k+1:])\n gk = np.prod(s[k+1:]**(1./(n-k)))\n kmdl.append( -(n-k)*N * np.log(gk/ak) + 0.5*k*(2.*n-k)*np.log(N))\n return kmdl\n\n" ]
[ [ "numpy.sum", "numpy.array", "numpy.prod", "numpy.log" ] ]
FrankieYin/master_project
[ "bcbc93429f577c6294eb9e8d67e5e0fd56a9c1c9" ]
[ "networks/sdf_net_decoder.py" ]
[ "import time\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.utils.data\nfrom torch import optim\nfrom torch.utils import data\nfrom tqdm import tqdm\n\nfrom networks import LATENT_CODE_SIZE, device\n# from train_autoencoder import SDFSampleDataset, save_checkpoint, SIGMA\n\nclass SDFNet(nn.Module):\n def __init__(self, latent_code_size=LATENT_CODE_SIZE, dropout_prob=0.2, point_dim=3):\n super(SDFNet, self).__init__()\n SDF_NET_BREADTH = latent_code_size * 2\n # the decoder should only have xyz information, without sdf values\n self.layers1 = nn.Sequential(\n nn.utils.weight_norm(nn.Linear(point_dim + latent_code_size, SDF_NET_BREADTH)),\n nn.ReLU(),\n nn.Dropout(dropout_prob),\n\n nn.utils.weight_norm(nn.Linear(SDF_NET_BREADTH, SDF_NET_BREADTH)),\n nn.ReLU(),\n nn.Dropout(dropout_prob),\n\n nn.utils.weight_norm(nn.Linear(SDF_NET_BREADTH, SDF_NET_BREADTH)),\n nn.ReLU(),\n nn.Dropout(dropout_prob),\n\n nn.utils.weight_norm(nn.Linear(SDF_NET_BREADTH, SDF_NET_BREADTH - latent_code_size - point_dim)),\n nn.ReLU(),\n nn.Dropout(dropout_prob),\n )\n\n self.layers2 = nn.Sequential(\n nn.utils.weight_norm(nn.Linear(SDF_NET_BREADTH, SDF_NET_BREADTH)),\n nn.ReLU(),\n nn.Dropout(dropout_prob),\n\n nn.utils.weight_norm(nn.Linear(SDF_NET_BREADTH, SDF_NET_BREADTH)),\n nn.ReLU(),\n nn.Dropout(dropout_prob),\n\n nn.utils.weight_norm(nn.Linear(SDF_NET_BREADTH, SDF_NET_BREADTH)),\n nn.ReLU(),\n nn.Dropout(dropout_prob),\n\n nn.utils.weight_norm(nn.Linear(SDF_NET_BREADTH, SDF_NET_BREADTH)),\n nn.ReLU(),\n nn.Dropout(dropout_prob),\n\n nn.Linear(SDF_NET_BREADTH, 1),\n nn.Tanh()\n )\n\n def forward(self, input):\n \"\"\"\n input: [B, N, latent_size + point_dim]\n :param latent_codes: [B, N, LATENT_CODE_DIM]\n :param points: [B, N, 3]\n :return: sdf_pred: [B, N]\n \"\"\"\n x = self.layers1(input)\n x = torch.cat((x, input), dim=-1)\n x = self.layers2(x)\n return x\n\n# if __name__ == '__main__':\n# experiment = '5_samples_latent_128_no_reg'\n# num_epochs = 500\n#\n# decoder = SDFNet()\n#\n# optimiser = optim.Adam(decoder.parameters(), lr=1e-5)\n# # model, optimiser, start_epoch, training_loss = load_or_init_model(experiment)\n# dataset = SDFSampleDataset('data/SdfSamples/ShapeNetV2/03001627/', '5_sample.json')\n# batch_size = 5\n# normal_distribution = torch.distributions.normal.Normal(0, 0.0001)\n# latent_codes = normal_distribution.sample((MODEL_COUNT, LATENT_CODE_SIZE)).to(device)\n# latent_codes.requires_grad = True\n# train_data = data.DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=4)\n#\n# # training loop starts\n# training_loss = []\n# for epoch in range(1, num_epochs + 1):\n# start_time = time.time()\n# running_loss = []\n#\n# for i_batch, batch in tqdm(enumerate(train_data)):\n# optimiser.zero_grad()\n# batch = batch.to(device) # [B, point_dim, N]\n# sdf_pred, input_trans, latent_code = model(batch)\n# sdf_gt = batch[:, -1, :].squeeze()\n#\n# loss = l1_loss(sdf_gt, sdf_pred) # TODO: experiment with only the l1 loss\n# loss += SIGMA**2 * min(1, epoch / 100) * torch.mean(torch.norm(latent_code, dim=1))\n# loss.backward()\n# optimiser.step()\n# running_loss.append(loss.item())\n#\n# epoch_duration = time.time() - start_time\n# epoch_loss = np.mean(running_loss)\n# training_loss.append(epoch_loss)\n#\n# print(\"Epoch {:d}, {:.1f}s. Loss: {:.8f}\".format(epoch, epoch_duration, epoch_loss))\n#\n# if epoch_loss < 0.02:\n# save_checkpoint(epoch, model, optimiser, training_loss, experiment, filename='sub002')\n#\n# # always save the latest snapshot\n# save_checkpoint(epoch, model, optimiser, training_loss, experiment)\n# if epoch % 100 == 0:\n# save_checkpoint(epoch, model, optimiser, training_loss, experiment, filename=str(epoch))" ]
[ [ "torch.nn.Linear", "torch.cat", "torch.nn.Dropout", "torch.nn.Tanh", "torch.nn.ReLU" ] ]
xuanthuong/DOU-SI
[ "ade175480da5eb7f31dbf70a97463f9304345d94" ]
[ "TrainValue/multiclass_svm.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nKey classification\nusing multiclass Support Vector Machine (SVM)\nreference: \n\nDate: Jun 05, 2017\n@author: Thuong Tran\n@Library: scikit-learn\n\"\"\"\n\n\nimport os, glob, random\nimport numpy as np\nfrom pandas import DataFrame\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.svm import LinearSVC\nfrom sklearn.metrics import confusion_matrix, precision_score\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.externals import joblib\nfrom sklearn.cross_validation import KFold\nimport time\nimport codecs\nimport matplotlib.pyplot as plt\nimport itertools\n\n\nNEW_LINE = '\\r\\n'\nTRAIN_SIZE = 0.8\n\n\ndef build_data_frame(data_dir): \n # folders = [d for d in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir, d))]\n dirs = next(os.walk(data_dir))[1] # [0]: path, [1]: folders list, [2] files list\n \n class_names = []\n total_amount = []\n train_amount = []\n test_amount = []\n\n train_data = DataFrame({'value': [], 'class': []})\n test_data = DataFrame({'value': [], 'class': []})\n\n for d in dirs:\n tmp_dir = os.path.join(data_dir, d)\n rows = []\n index = []\n for f in glob.glob(os.path.join(tmp_dir, '*.txt')):\n with open(f, encoding=\"latin1\") as fc:\n value = [line.replace('\\n', '').replace('\\r', '').replace('\\t', '') \n for line in fc.readlines()]\n value = '. '.join(value)\n rows.append({'value': value, 'class': d})\n index.append(f)\n\n tmp_df = DataFrame(rows, index=index)\n size = int(len(tmp_df) * TRAIN_SIZE)\n train_df, test_df = tmp_df.iloc[:size], tmp_df.iloc[size:]\n\n train_data = train_data.append(train_df)\n test_data = test_data.append(test_df)\n\n class_names.append(d)\n\n total_amount.append(len(os.listdir(tmp_dir)))\n train_amount.append(len(train_df))\n test_amount.append(len(test_df))\n \n tmp_arr = np.array([total_amount, train_amount, test_amount])\n print (DataFrame(tmp_arr, ['Total', 'Train', 'Test'], class_names))\n \n train_data = train_data.reindex(np.random.permutation(train_data.index))\n test_data = test_data.reindex(np.random.permutation(test_data.index))\n return train_data, test_data, class_names\n\n\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n print(cm)\n\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, cm[i, j],\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\n\ndef main():\n data_dir = '/Users/thuong/Documents/tmp_datasets/SI/TrainValue'\n train_data_df, test_data_df, class_names = build_data_frame(data_dir)\n\n pipeline = Pipeline([\n ('vectorizer', CountVectorizer()),\n ('tfidf_transformer', TfidfTransformer()),\n ('classifier', LinearSVC())])\n\n ######### One-KFolds ##############################\n train_data, test_data = train_data_df['value'].values, test_data_df['value'].values\n train_target, test_target = train_data_df['class'].values, test_data_df['class'].values\n \n pipeline.fit(train_data, train_target)\n predictions = pipeline.predict(test_data)\n\n cnf_matrix = confusion_matrix(test_target, predictions)\n print('Confusion matrix with one-fold: ')\n print(cnf_matrix)\n print(\"Score with one-fold: %s\" % precision_score(test_target, predictions, average = 'weighted'))\n print(\"Score with one-fold: %s\" % precision_score(test_target, predictions, average = None))\n\n # ######### KFolds ##############################\n # k_fold = KFold(n=len(data_frame), n_folds=6)\n # scores = []\n # confusion = np.array([[0, 0], [0, 0]])\n # for train_indices, test_indices in k_fold:\n # train_text = data_frame.iloc[train_indices]['text'].values\n # train_label = data_frame.iloc[train_indices]['class'].values\n # test_text = data_frame.iloc[test_indices]['text'].values\n # test_label = data_frame.iloc[test_indices]['class'].values\n\n # pipeline.fit(train_text, train_label)\n # predictions = pipeline.predict(test_text)\n\n # confusion += confusion_matrix(test_label, predictions)\n # score = f1_score(test_label, predictions, pos_label = SPAM)\n # scores.append(score)\n\n # print('Confusion matrix with 6-fold: ')\n # print(confusion)\n # print('Score with 6-fold: %s' % (sum(scores)/len(scores))) \n\n # Plot non-normalized confusion matrix\n plt.figure()\n plot_confusion_matrix(cnf_matrix, classes=class_names,\n title='Confusion matrix, without normalization')\n # Plot normalized confusion matrix\n plt.figure()\n plot_confusion_matrix(cnf_matrix, classes=class_names, normalize=True,\n title='Normalized confusion matrix')\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()" ]
[ [ "sklearn.metrics.confusion_matrix", "matplotlib.pyplot.text", "sklearn.feature_extraction.text.CountVectorizer", "sklearn.svm.LinearSVC", "matplotlib.pyplot.xticks", "matplotlib.pyplot.colorbar", "pandas.DataFrame", "matplotlib.pyplot.tight_layout", "numpy.array", "matplotlib.pyplot.title", "matplotlib.pyplot.yticks", "matplotlib.pyplot.figure", "matplotlib.pyplot.show", "sklearn.feature_extraction.text.TfidfTransformer", "matplotlib.pyplot.xlabel", "numpy.random.permutation", "matplotlib.pyplot.ylabel", "sklearn.metrics.precision_score", "matplotlib.pyplot.imshow" ] ]
anishsingh20/tensor2tensor
[ "8ec4233e1012f2d542adb64835d39b76587367f5" ]
[ "tensor2tensor/bin/make_tf_configs.py" ]
[ "# Copyright 2017 Google 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.\n\n\"\"\"Output command line arguments and json-encoded TF_CONFIGs.\n\nUsage:\n\n`make_tf_configs.py --workers=\"server1:1234\" --ps=\"server3:2134,server4:2334\"`\n\nOutputs 1 line per job to stdout, first the workers, then the parameter servers.\nEach line has the TF_CONFIG, then a tab, then the command line flags for that\njob.\n\nIf there is a single worker, workers will have the `--sync` flag.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport json\n\n# Dependency imports\n\nimport six\nimport tensorflow as tf\n\nflags = tf.flags\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string(\"workers\", \"\", \"Comma-separated list of worker addresses\")\nflags.DEFINE_string(\"ps\", \"\", \"Comma-separated list of ps addresses\")\n\n\ndef main(_):\n if not (FLAGS.workers and FLAGS.ps):\n raise ValueError(\"Must provide --workers and --ps\")\n\n workers = FLAGS.workers.split(\",\")\n ps = FLAGS.ps.split(\",\")\n\n cluster = {\"ps\": ps, \"worker\": workers}\n\n for task_type, jobs in six.iteritems(cluster):\n for idx, job in enumerate(jobs):\n if task_type == \"worker\":\n cmd_line_flags = \" \".join([\n \"--master=%s\" % job,\n \"--ps_replicas=%d\" % len(ps),\n \"--worker_replicas=%d\" % len(workers),\n \"--worker_gpu=1\",\n \"--worker_id=%d\" % idx,\n \"--ps_gpu=1\",\n \"--schedule=train\",\n \"--sync\" if len(workers) == 1 else \"\",\n ])\n else:\n cmd_line_flags = \" \".join([\n \"--schedule=run_std_server\",\n ])\n\n tf_config = json.dumps({\n \"cluster\": cluster,\n \"task\": {\n \"type\": task_type,\n \"index\": idx\n }\n })\n print(tf_config + \"\\t\" + cmd_line_flags)\n\n\nif __name__ == \"__main__\":\n tf.app.run()\n" ]
[ [ "tensorflow.app.run" ] ]
vipmunot/Data-Analysis-using-Python
[ "34586d8cbbc336508c4a7a68abe14944f1096252" ]
[ "Data Analysis with Pandas Intermediate/Challenge_ Summarizing Data-112.py" ]
[ "## 2. Introduction to the Data ##\n\nimport pandas as pd\nall_ages = pd.read_csv('all-ages.csv')\nrecent_grads = pd.read_csv('recent-grads.csv')\nprint(all_ages.head())\nprint(recent_grads.head())\n\n## 3. Summarizing Major Categories ##\n\n# Unique values in Major_category column.\nprint(all_ages['Major_category'].unique())\n\naa_cat_counts = dict()\nrg_cat_counts = dict()\ndef cat_summary(data,category):\n subset = data[data['Major_category']==category]\n total = subset['Total'].sum()\n return(total)\nfor cat in all_ages['Major_category'].unique():\n aa_cat_counts[cat] = cat_summary(all_ages,cat)\nfor cat in recent_grads['Major_category'].unique():\n rg_cat_counts[cat] = cat_summary(recent_grads,cat)\n \n\n## 4. Low-Wage Job Rates ##\n\nlow_wage_percent = 0.0\nlow_wage_percent = recent_grads['Low_wage_jobs'].sum()/recent_grads['Total'].sum()\n\n## 5. Comparing Data Sets ##\n\n# All majors, common to both DataFrames\nmajors = recent_grads['Major'].unique()\nrg_lower_count = 0\nfor item in majors:\n grad_subset = recent_grads[recent_grads['Major']==item]\n all_subset = all_ages[all_ages['Major']==item]\n if(grad_subset['Unemployment_rate'].values[0] < all_subset['Unemployment_rate'].values[0]):\n rg_lower_count +=1\nprint(rg_lower_count) " ]
[ [ "pandas.read_csv" ] ]
Arcofcosmos/MyYolov4_Pytorch
[ "14c445503d0fc69b8a8b64ecdc87256ac4c1fce1", "14c445503d0fc69b8a8b64ecdc87256ac4c1fce1" ]
[ ".history/nets/CSPdarknet_20210816140029.py", ".history/nets/yolo4_20210816143924.py" ]
[ "import math\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n#-------------------------------------------------#\n# MISH激活函数\n#-------------------------------------------------#\nclass Mish(nn.Module):\n def __init__(self):\n super(Mish, self).__init__()\n\n def forward(self, x):\n return x * torch.tanh(F.softplus(x))\n\n#---------------------------------------------------#\n# 卷积块 -> 卷积 + 标准化 + 激活函数\n# Conv2d + BatchNormalization + Mish\n#---------------------------------------------------#\nclass CBM(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, stride=1):\n super(CBM, self).__init__()\n\n #pad = kernel_size//2,表示1x1卷积不补零,3x3卷积补一圈0,这样输出图片的尺寸不会改变\n self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, kernel_size//2, bias=False)\n self.bn = nn.BatchNorm2d(out_channels)\n self.activation = Mish()\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n x = self.activation(x)\n return x\n\n#---------------------------------------------------#\n# CSPdarknet的结构块的组成部分\n# 内部堆叠的残差块\n#---------------------------------------------------#\nclass Resblock(nn.Module):\n def __init__(self, channels, hidden_channels=None):\n super(Resblock, self).__init__()\n\n if hidden_channels is None:\n hidden_channels = channels\n\n self.block = nn.Sequential(\n CBM(channels, hidden_channels, 1),\n CBM(hidden_channels, channels, 3)\n )\n\n def forward(self, x):\n return x + self.block(x)\n\n#--------------------------------------------------------------------#\n# CSPdarknet的结构块\n# 首先利用ZeroPadding2D和一个步长为2x2的卷积块进行高和宽的压缩\n# 然后建立一个大的残差边shortconv、这个大残差边绕过了很多的残差结构\n# 主干部分会对num_blocks进行循环,循环内部是残差结构。\n# 对于整个CSPdarknet的结构块,就是一个大残差块+内部多个小残差块\n#--------------------------------------------------------------------#\nclass Resblock_body(nn.Module):\n def __init__(self, in_channels, out_channels, num_blocks, first):\n super(Resblock_body, self).__init__()\n #----------------------------------------------------------------#\n # 利用一个步长为2x2的卷积块进行高和宽的压缩\n #----------------------------------------------------------------#\n self.downsample_conv = CBM(in_channels, out_channels, 3, stride=2)\n\n if first:\n #--------------------------------------------------------------------------#\n # 然后建立一个大的残差边self.split_conv0、这个大残差边绕过了很多的残差结构\n #--------------------------------------------------------------------------#\n self.split_conv0 = CBM(out_channels, out_channels, 1)\n\n #----------------------------------------------------------------#\n # 主干部分会对num_blocks进行循环,循环内部是残差结构。\n #----------------------------------------------------------------#\n self.split_conv1 = CBM(out_channels, out_channels, 1) \n self.blocks_conv = nn.Sequential(\n Resblock(channels=out_channels, hidden_channels=out_channels//2),\n CBM(out_channels, out_channels, 1)\n )\n\n self.concat_conv = CBM(out_channels*2, out_channels, 1)\n else:\n #--------------------------------------------------------------------------#\n # 然后建立一个大的残差边self.split_conv0、这个大残差边绕过了很多的残差结构\n #--------------------------------------------------------------------------#\n self.split_conv0 = CBM(out_channels, out_channels//2, 1)\n\n #----------------------------------------------------------------#\n # 主干部分会对num_blocks进行循环,循环内部是残差结构。\n #----------------------------------------------------------------#\n self.split_conv1 = CBM(out_channels, out_channels//2, 1)\n self.blocks_conv = nn.Sequential(\n *[Resblock(out_channels//2) for _ in range(num_blocks)],\n CBM(out_channels//2, out_channels//2, 1)\n )\n\n self.concat_conv = CBM(out_channels, out_channels, 1)\n\n def forward(self, x):\n x = self.downsample_conv(x)\n\n x0 = self.split_conv0(x)\n\n x1 = self.split_conv1(x)\n x1 = self.blocks_conv(x1)\n\n #------------------------------------#\n # 将大残差边再堆叠回来\n #------------------------------------#\n x = torch.cat([x1, x0], dim=1)\n #------------------------------------#\n # 最后对通道数进行整合\n #------------------------------------#\n x = self.concat_conv(x)\n\n return x\n\n#---------------------------------------------------#\n# CSPdarknet53 的主体部分\n# 输入为一张416x416x3的图片\n# 输出为三个有效特征层\n#---------------------------------------------------#\nclass CSPDarkNet(nn.Module):\n def __init__(self, layers):\n super(CSPDarkNet, self).__init__()\n self.inplanes = 32\n # 416,416,3 -> 416,416,32\n self.conv1 = CBM(3, self.inplanes, kernel_size=3, stride=1)\n self.feature_channels = [64, 128, 256, 512, 1024]\n\n self.stages = nn.ModuleList([\n # 416,416,32 -> 208,208,64\n Resblock_body(self.inplanes, self.feature_channels[0], layers[0], first=True),\n # 208,208,64 -> 104,104,128\n Resblock_body(self.feature_channels[0], self.feature_channels[1], layers[1], first=False),\n # 104,104,128 -> 52,52,256\n Resblock_body(self.feature_channels[1], self.feature_channels[2], layers[2], first=False),\n # 52,52,256 -> 26,26,512\n Resblock_body(self.feature_channels[2], self.feature_channels[3], layers[3], first=False),\n # 26,26,512 -> 13,13,1024\n Resblock_body(self.feature_channels[3], self.feature_channels[4], layers[4], first=False)\n ])\n\n self.num_features = 1\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n\n def forward(self, x):\n x = self.conv1(x)\n\n x = self.stages[0](x)\n x = self.stages[1](x)\n out3 = self.stages[2](x)\n out4 = self.stages[3](out3)\n out5 = self.stages[4](out4)\n\n return out3, out4, out5\n\ndef darknet53(pretrained, **kwargs):\n model = CSPDarkNet([1, 2, 8, 8, 4])\n if pretrained:\n if isinstance(pretrained, str):\n model.load_state_dict(torch.load(pretrained))\n else:\n raise Exception(\"darknet request a pretrained path. got [{}]\".format(pretrained))\n return model\n", "from collections import OrderedDict\n\nimport torch\nimport torch.nn as nn\n\nfrom nets.CSPdarknet import darknet53\n\n\n\n#---------------------------------------------------#\n# 卷积块 -> 卷积 + 标准化 + 激活函数\n# Conv2d + BatchNormalization + LeakyRelu\n#---------------------------------------------------#\ndef CBL(filter_in, filter_out, kernel_size, stride=1):\n pad = (kernel_size - 1) // 2 if kernel_size else 0\n return nn.Sequential(OrderedDict([\n (\"conv\", nn.Conv2d(filter_in, filter_out, kernel_size=kernel_size, stride=stride, padding=pad, bias=False)),\n (\"bn\", nn.BatchNorm2d(filter_out)),\n (\"relu\", nn.LeakyReLU(0.1)),\n ]))\n\n#---------------------------------------------------#\n# SPP结构,利用不同大小的池化核进行池化\n# 池化后堆叠\n#---------------------------------------------------#\nclass SpatialPyramidPooling(nn.Module):\n def __init__(self, pool_sizes=[5, 9, 13]):\n super(SpatialPyramidPooling, self).__init__()\n\n self.maxpools = nn.ModuleList([nn.MaxPool2d(pool_size, 1, pool_size//2) for pool_size in pool_sizes])\n\n def forward(self, x):\n features = [maxpool(x) for maxpool in self.maxpools[::-1]]\n features = torch.cat(features + [x], dim=1)\n\n return features\n\n#---------------------------------------------------#\n# 卷积 + 上采样\n#---------------------------------------------------#\nclass Upsample(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(Upsample, self).__init__()\n\n self.upsample = nn.Sequential(\n CBL(in_channels, out_channels, 1),\n nn.Upsample(scale_factor=2, mode='nearest')\n )\n\n def forward(self, x,):\n x = self.upsample(x)\n return x\n\n#---------------------------------------------------#\n# 三次卷积块\n#---------------------------------------------------#\ndef make_three_conv(filters_list, in_filters):\n m = nn.Sequential(\n CBL(in_filters, filters_list[0], 1),\n CBL(filters_list[0], filters_list[1], 3),\n CBL(filters_list[1], filters_list[0], 1),\n )\n return m\n\n#---------------------------------------------------#\n# 五次卷积块\n#---------------------------------------------------#\ndef make_five_conv(filters_list, in_filters):\n m = nn.Sequential(\n CBL(in_filters, filters_list[0], 1),\n CBL(filters_list[0], filters_list[1], 3),\n CBL(filters_list[1], filters_list[0], 1),\n CBL(filters_list[0], filters_list[1], 3),\n CBL(filters_list[1], filters_list[0], 1),\n )\n return m\n\n#---------------------------------------------------#\n# 最后获得yolov4的输出\n#---------------------------------------------------#\ndef yolo_head(filters_list, in_filters):\n m = nn.Sequential(\n CBL(in_filters, filters_list[0], 3),\n nn.Conv2d(filters_list[0], filters_list[1], 1),\n )\n return m\n\n#---------------------------------------------------#\n# yolo_body\n#---------------------------------------------------#\nclass YoloBody(nn.Module):\n def __init__(self, num_anchors, num_classes):\n super(YoloBody, self).__init__()\n #---------------------------------------------------# \n # 生成CSPdarknet53的主干模型\n # 获得三个有效特征层,他们的shape分别是:\n # 52,52,256\n # 26,26,512\n # 13,13,1024\n #---------------------------------------------------#\n self.backbone = darknet53(None)\n\n self.conv1 = make_three_conv([512,1024],1024)\n self.SPP = SpatialPyramidPooling()\n self.conv2 = make_three_conv([512,1024],2048)\n\n self.upsample1 = Upsample(512,256)\n self.conv_for_P4 = CBL(512,256,1)\n self.make_five_conv1 = make_five_conv([256, 512],512)\n\n self.upsample2 = Upsample(256,128)\n self.conv_for_P3 = CBL(256,128,1)\n self.make_five_conv2 = make_five_conv([128, 256],256)\n\n # 3*(5+num_classes) = 3*(5+20) = 3*(4+1+20)=75\n final_out_filter2 = num_anchors * (5 + num_classes)\n self.yolo_head3 = yolo_head([256, final_out_filter2],128)\n\n self.down_sample1 = CBL(128,256,3,stride=2)\n self.make_five_conv3 = make_five_conv([256, 512],512)\n\n # 3*(5+num_classes) = 3*(5+20) = 3*(4+1+20)=75\n final_out_filter1 = num_anchors * (5 + num_classes)\n self.yolo_head2 = yolo_head([512, final_out_filter1],256)\n\n self.down_sample2 = CBL(256,512,3,stride=2)\n self.make_five_conv4 = make_five_conv([512, 1024],1024)\n\n # 3*(5+num_classes)=3*(5+20)=3*(4+1+20)=75\n final_out_filter0 = num_anchors * (5 + num_classes)\n self.yolo_head1 = yolo_head([1024, final_out_filter0],512)\n\n\n def forward(self, x):\n # backbone\n x2, x1, x0 = self.backbone(x)\n\n # 13,13,1024 -> 13,13,512 -> 13,13,1024 -> 13,13,512 -> 13,13,2048 \n P5 = self.conv1(x0)\n P5 = self.SPP(P5)\n # 13,13,2048 -> 13,13,512 -> 13,13,1024 -> 13,13,512\n P5 = self.conv2(P5)\n\n # 13,13,512 -> 13,13,256 -> 26,26,256\n P5_upsample = self.upsample1(P5)\n # 26,26,512 -> 26,26,256\n P4 = self.conv_for_P4(x1)\n # 26,26,256 + 26,26,256 -> 26,26,512\n P4 = torch.cat([P4,P5_upsample],axis=1)\n # 26,26,512 -> 26,26,256 -> 26,26,512 -> 26,26,256 -> 26,26,512 -> 26,26,256\n P4 = self.make_five_conv1(P4)\n\n # 26,26,256 -> 26,26,128 -> 52,52,128\n P4_upsample = self.upsample2(P4)\n # 52,52,256 -> 52,52,128\n P3 = self.conv_for_P3(x2)\n # 52,52,128 + 52,52,128 -> 52,52,256\n P3 = torch.cat([P3,P4_upsample],axis=1)\n # 52,52,256 -> 52,52,128 -> 52,52,256 -> 52,52,128 -> 52,52,256 -> 52,52,128\n P3 = self.make_five_conv2(P3)\n\n # 52,52,128 -> 26,26,256\n P3_downsample = self.down_sample1(P3)\n # 26,26,256 + 26,26,256 -> 26,26,512\n P4 = torch.cat([P3_downsample,P4],axis=1)\n # 26,26,512 -> 26,26,256 -> 26,26,512 -> 26,26,256 -> 26,26,512 -> 26,26,256\n P4 = self.make_five_conv3(P4)\n\n # 26,26,256 -> 13,13,512\n P4_downsample = self.down_sample2(P4)\n # 13,13,512 + 13,13,512 -> 13,13,1024\n P5 = torch.cat([P4_downsample,P5],axis=1)\n # 13,13,1024 -> 13,13,512 -> 13,13,1024 -> 13,13,512 -> 13,13,1024 -> 13,13,512\n P5 = self.make_five_conv4(P5)\n\n #---------------------------------------------------#\n # 第三个特征层\n # y3=(batch_size,75,52,52)\n #---------------------------------------------------#\n out2 = self.yolo_head3(P3)\n #---------------------------------------------------#\n # 第二个特征层\n # y2=(batch_size,75,26,26)\n #---------------------------------------------------#\n out1 = self.yolo_head2(P4)\n #---------------------------------------------------#\n # 第一个特征层\n # y1=(batch_size,75,13,13)\n #---------------------------------------------------#\n out0 = self.yolo_head1(P5)\n\n return out0, out1, out2\n\n" ]
[ [ "torch.cat", "torch.nn.functional.softplus", "torch.nn.BatchNorm2d", "torch.nn.Conv2d", "torch.load" ], [ "torch.cat", "torch.nn.MaxPool2d", "torch.nn.BatchNorm2d", "torch.nn.LeakyReLU", "torch.nn.Upsample", "torch.nn.Conv2d" ] ]
daohuei/ucsc-nlp-unicorn
[ "d19c99fc717e458e6cfbf1bbe06193251257afb1" ]
[ "nlp_243/hw3/utils.py" ]
[ "import copy\n\nimport torch\nfrom torch import nn\nimport numpy as np\n\nfrom tokens import *\n\n\ndef tokenize(corpus, callback=lambda sent: sent.split()):\n return [callback(sent) for sent in corpus]\n\n\ndef add_start_stop_tokens(corpus):\n return [[START_TOKEN] + sent + [STOP_TOKEN] for sent in corpus]\n\n\ndef padding(corpus, seq_len):\n for sent in corpus:\n while len(sent) < seq_len:\n sent.append(PAD_TOKEN)\n while len(sent) > seq_len:\n sent.pop()\n return corpus\n\n\ndef build_vocab(corpus):\n vocab = set()\n for sent in corpus:\n vocab.update(set(sent))\n vocab = list(vocab) + [UNK_TOKEN]\n word2idx = {word: idx for idx, word in enumerate(vocab)}\n idx2word = {idx: word for idx, word in enumerate(vocab)}\n return vocab, word2idx, idx2word\n\n\ndef convert_to_idx(corpus, word2idx):\n return [[word2idx.get(word, \"<UNK>\") for word in sent] for sent in corpus]\n\n\n# Output Processing\ndef process_output_corpus(input_seqs, preds, trues):\n new_seqs = []\n new_preds = []\n new_trues = []\n for i in range(len(input_seqs)):\n new_seq, new_pred, new_true = remove_special_tokens(\n input_seqs[i], preds[i], trues[i]\n )\n new_seqs.append(new_seq)\n new_preds.append(new_pred)\n new_trues.append(new_true)\n return new_seqs, new_preds, new_trues\n\n\ndef remove_special_tokens(input_seq, pred, true):\n new_seq = []\n new_pred = []\n new_true = []\n new_seq = input_seq[1:-1]\n new_true = true[1:-1]\n new_pred = pred[1:]\n\n # if is truncated padding\n while len(new_pred) < len(new_seq):\n new_pred.append(PAD_TOKEN)\n\n # if is expanded padding\n while len(new_pred) > len(new_seq):\n new_pred = new_pred[:-1]\n\n return new_seq, new_pred, new_true\n\n\ndef convert_to_token(corpus, idx2token):\n return [[idx2token[token_idx] for token_idx in sent] for sent in corpus]\n\n\ndef preprocess_utterances(utterances, utterance_dataset):\n # tokenization\n utterances = tokenize(utterances)\n # add special tokens\n utterances = add_start_stop_tokens(utterances)\n tokenized_utterances = copy.deepcopy(utterances)\n # padding\n utterances = padding(utterances, utterance_dataset.seq_len)\n\n word2idx = utterance_dataset.word2idx\n utterances = [\n [word2idx.get(token, word2idx[UNK_TOKEN]) for token in sent]\n for sent in utterances\n ]\n\n return utterances, tokenized_utterances\n\n\ndef read_glove_vector(glove_vec):\n with open(glove_vec, \"r\", encoding=\"UTF-8\") as f:\n words = set()\n word_to_vec_map = {}\n for line in f:\n w_line = line.split()\n curr_word = w_line[0]\n word_to_vec_map[curr_word] = np.array(w_line[1:], dtype=np.float64)\n\n return word_to_vec_map\n\n\n# functions for creating the embedding layer\ndef get_one_hot_matrix(vocab):\n one_hot_matrix = np.zeros((len(vocab), len(vocab)))\n np.fill_diagonal(one_hot_matrix, 1)\n return one_hot_matrix\n\n\ndef get_glove_matrix(glove_map, vocab):\n matrix_len = len(vocab)\n emb_dim = len(list(glove_map.values())[0])\n weights_matrix = np.zeros((matrix_len, emb_dim))\n for i, word in enumerate(vocab):\n try:\n weights_matrix[i] = glove_map[word]\n except KeyError:\n if word in [PAD_TOKEN, START_TOKEN, STOP_TOKEN]:\n weights_matrix[i] = np.zeros((emb_dim,))\n else:\n weights_matrix[i] = np.random.normal(\n scale=0.6, size=(emb_dim,)\n )\n return weights_matrix\n\n\ndef create_emb_layer(weights_matrix, non_trainable=False):\n num_embeddings, embedding_dim = weights_matrix.shape\n emb_layer = nn.Embedding(num_embeddings, embedding_dim)\n emb_layer.load_state_dict({\"weight\": torch.tensor(weights_matrix)})\n if non_trainable:\n emb_layer.weight.requires_grad = False\n\n return emb_layer, num_embeddings, embedding_dim\n\n" ]
[ [ "numpy.random.normal", "numpy.array", "numpy.fill_diagonal", "numpy.zeros", "torch.tensor", "torch.nn.Embedding" ] ]
koaning/polars
[ "9e7b66172d835ddf33eb6af1dfb57ff957463243" ]
[ "pandas_cmp/create_data.py" ]
[ "import pandas as pd\nimport numpy as np\nfrom pandas.util.testing import rands\n\ngroups = np.arange(10)\nstr_groups = np.array(list(\"0123456789\"))\nnp.random.seed(1)\n\nfor size in [1e2, 1e3, 1e4, 1e5, 1e6]:\n size = int(size)\n g = np.random.choice(groups, size)\n sg = np.random.choice(str_groups, size)\n v = np.random.randn(size)\n df = pd.DataFrame({\"groups\": g, \"values\": v, \"str\": sg})\n df.to_csv(f\"../data/{size}.csv\", index=False)\n\nprint(\"data created\")\n\n# Join benchmark data\n# https://wesmckinney.com/blog/high-performance-database-joins-with-pandas-dataframe-more-benchmarks/\n# https://github.com/wesm/pandas/blob/23669822819808bbaeb6ea36a6b2ef98026884db/bench/bench_merge_sqlite.py\nN = 10000\nindices = np.array([rands(10) for _ in range(N)], dtype=\"O\")\nindices2 = np.array([rands(10) for _ in range(N)], dtype=\"O\")\nkey = np.tile(indices[:8000], 10)\nkey2 = np.tile(indices2[:8000], 10)\n\nleft = pd.DataFrame({\"key\": key, \"key2\": key2, \"value\": np.random.randn(80000)})\nright = pd.DataFrame(\n {\"key\": indices[2000:], \"key2\": indices2[2000:], \"value2\": np.random.randn(8000)}\n)\n\nleft.to_csv(\"../data/join_left_80000.csv\", index=False)\nright.to_csv(\"../data/join_right_80000.csv\", index=False)\n\n" ]
[ [ "numpy.random.choice", "numpy.random.seed", "pandas.DataFrame", "numpy.random.randn", "numpy.tile", "pandas.util.testing.rands", "numpy.arange" ] ]
karkaroff/castor
[ "881673f3dadb4f757fdfdf5d2ab9031e08512406", "881673f3dadb4f757fdfdf5d2ab9031e08512406" ]
[ "sm_cnn/train.py", "common/trainers/msrvid_trainer.py" ]
[ "import time\nimport os\nimport numpy as np\nimport random\n\nimport torch\nimport torch.nn as nn\nimport torch.onnx\nfrom torchtext import data\n\nfrom args import get_args\nfrom model import SmPlusPlus\nfrom utils.relevancy_metrics import get_map_mrr\nfrom trec_dataset import TrecDataset\nfrom wiki_dataset import WikiDataset\n\nargs = get_args()\nconfig = args\n\ntorch.manual_seed(args.seed)\n\ndef set_vectors(field, vector_path):\n if os.path.isfile(vector_path):\n stoi, vectors, dim = torch.load(vector_path)\n field.vocab.vectors = torch.Tensor(len(field.vocab), dim)\n\n for i, token in enumerate(field.vocab.itos):\n wv_index = stoi.get(token, None)\n if wv_index is not None:\n field.vocab.vectors[i] = vectors[wv_index]\n else:\n # initialize <unk> with U(-0.25, 0.25) vectors\n field.vocab.vectors[i] = torch.FloatTensor(dim).uniform_(-0.25, 0.25)\n else:\n print(\"Error: Need word embedding pt file\")\n exit(1)\n return field\n\n# Set default configuration in : args.py\nargs = get_args()\nconfig = args\n\n# Set random seed for reproducibility\ntorch.manual_seed(args.seed)\ntorch.backends.cudnn.deterministic = True\nif not args.cuda:\n args.gpu = -1\nif torch.cuda.is_available() and args.cuda:\n print(\"Note: You are using GPU for training\")\n torch.cuda.set_device(args.gpu)\n torch.cuda.manual_seed(args.seed)\nif torch.cuda.is_available() and not args.cuda:\n print(\"You have Cuda but you're using CPU for training.\")\nnp.random.seed(args.seed)\nrandom.seed(args.seed)\n\nQID = data.Field(sequential=False)\nQUESTION = data.Field(batch_first=True)\nANSWER = data.Field(batch_first=True)\nLABEL = data.Field(sequential=False)\nEXTERNAL = data.Field(sequential=True, tensor_type=torch.FloatTensor, batch_first=True, use_vocab=False,\n postprocessing=data.Pipeline(lambda arr, _, train: [float(y) for y in arr]))\n\nif config.dataset == 'TREC':\n train, dev, test = TrecDataset.splits(QID, QUESTION, ANSWER, EXTERNAL, LABEL)\nelif config.dataset == 'wiki':\n train, dev, test = WikiDataset.splits(QID, QUESTION, ANSWER, EXTERNAL, LABEL)\nelse:\n print(\"Unsupported dataset\")\n exit()\n\nQID.build_vocab(train, dev, test)\nQUESTION.build_vocab(train, dev, test)\nANSWER.build_vocab(train, dev, test)\nLABEL.build_vocab(train, dev, test)\n\n\nQUESTION = set_vectors(QUESTION, args.vector_cache)\nANSWER = set_vectors(ANSWER, args.vector_cache)\n\ntrain_iter = data.Iterator(train, batch_size=args.batch_size, device=args.gpu, train=True, repeat=False,\n sort=False, shuffle=True)\ndev_iter = data.Iterator(dev, batch_size=args.batch_size, device=args.gpu, train=False, repeat=False,\n sort=False, shuffle=False)\ntest_iter = data.Iterator(test, batch_size=args.batch_size, device=args.gpu, train=False, repeat=False,\n sort=False, shuffle=False)\n\nconfig.target_class = len(LABEL.vocab)\nconfig.questions_num = len(QUESTION.vocab)\nconfig.answers_num = len(ANSWER.vocab)\n\nprint(\"Dataset {} Mode {}\".format(args.dataset, args.mode))\nprint(\"VOCAB num\", len(QUESTION.vocab))\nprint(\"LABEL.target_class:\", len(LABEL.vocab))\nprint(\"LABELS:\", LABEL.vocab.itos)\nprint(\"Train instance\", len(train))\nprint(\"Dev instance\", len(dev))\nprint(\"Test instance\", len(test))\n\nif args.resume_snapshot:\n if args.cuda:\n model = torch.load(args.resume_snapshot, map_location=lambda storage, location: storage.cuda(args.gpu))\n else:\n model = torch.load(args.resume_snapshot, map_location=lambda storage, location: storage)\nelse:\n model = SmPlusPlus(config)\n model.static_question_embed.weight.data.copy_(QUESTION.vocab.vectors)\n model.nonstatic_question_embed.weight.data.copy_(QUESTION.vocab.vectors)\n model.static_answer_embed.weight.data.copy_(ANSWER.vocab.vectors)\n model.nonstatic_answer_embed.weight.data.copy_(ANSWER.vocab.vectors)\n\n if args.cuda:\n model.cuda()\n print(\"Shift model to GPU\")\n\n\nparameter = filter(lambda p: p.requires_grad, model.parameters())\n\n# the SM model originally follows SGD but Adadelta is used here\noptimizer = torch.optim.Adadelta(parameter, lr=args.lr, weight_decay=args.weight_decay)\ncriterion = nn.CrossEntropyLoss()\nearly_stop = False\nbest_dev_map = 0\niterations = 0\niters_not_improved = 0\nepoch = 0\nstart = time.time()\nheader = ' Time Epoch Iteration Progress (%Epoch) Loss Dev/Loss Accuracy Dev/Accuracy'\ndev_log_template = ' '.join('{:>6.0f},{:>5.0f},{:>9.0f},{:>5.0f}/{:<5.0f} {:>7.0f}%,{:>8.6f},{:8.6f},{:12.4f},{:12.4f}'.split(','))\nlog_template = ' '.join('{:>6.0f},{:>5.0f},{:>9.0f},{:>5.0f}/{:<5.0f} {:>7.0f}%,{:>8.6f},{},{:12.4f},{}'.split(','))\nos.makedirs(args.save_path, exist_ok=True)\nos.makedirs(os.path.join(args.save_path, args.dataset), exist_ok=True)\nprint(header)\n\nindex2label = np.array(LABEL.vocab.itos)\nindex2qid = np.array(QID.vocab.itos)\nindex2question = np.array(ANSWER.vocab.itos)\n\nwhile True:\n if early_stop:\n print(\"Early Stopping. Epoch: {}, Best Dev Acc: {}\".format(epoch, best_dev_map))\n break\n epoch += 1\n train_iter.init_epoch()\n n_correct, n_total = 0, 0\n\n for batch_idx, batch in enumerate(train_iter):\n iterations += 1\n model.train(); optimizer.zero_grad()\n scores = model(batch.question, batch.answer, batch.ext_feat)\n n_correct += (torch.max(scores, 1)[1].view(batch.label.size()).data == batch.label.data).sum()\n n_total += batch.batch_size\n train_acc = 100. * n_correct / n_total\n\n loss = criterion(scores, batch.label)\n loss.backward()\n optimizer.step()\n\n # Evaluate performance on validation set\n if iterations % args.dev_every == 1:\n # switch model into evaluation mode\n model.eval()\n dev_iter.init_epoch()\n n_dev_correct = 0\n dev_losses = []\n\n qids = []\n predictions = []\n labels = []\n for dev_batch_idx, dev_batch in enumerate(dev_iter):\n qid_array = index2qid[np.transpose(dev_batch.qid.cpu().data.numpy())]\n true_label_array = index2label[np.transpose(dev_batch.label.cpu().data.numpy())]\n\n scores = model(dev_batch.question, dev_batch.answer, dev_batch.ext_feat)\n n_dev_correct += (torch.max(scores, 1)[1].view(dev_batch.label.size()).data == dev_batch.label.data).sum()\n dev_loss = criterion(scores, dev_batch.label)\n dev_losses.append(dev_loss.data[0])\n index_label = np.transpose(torch.max(scores, 1)[1].view(dev_batch.label.size()).cpu().data.numpy())\n label_array = index2label[index_label]\n # get the relevance scores\n score_array = scores[:, 2].cpu().data.numpy()\n\n qids.extend(qid_array.tolist())\n predictions.extend(score_array.tolist())\n labels.extend(true_label_array.tolist())\n\n dev_map, dev_mrr = get_map_mrr(qids, predictions, labels)\n print(dev_log_template.format(time.time() - start,\n epoch, iterations, 1 + batch_idx, len(train_iter),\n 100. * (1 + batch_idx) / len(train_iter), loss.data[0],\n sum(dev_losses) / len(dev_losses), train_acc, dev_map))\n\n # Update validation results\n if dev_map > best_dev_map:\n iters_not_improved = 0\n best_dev_map = dev_map\n snapshot_path = os.path.join(args.save_path, args.dataset, args.mode+'_best_model.pt')\n torch.save(model, snapshot_path)\n else:\n iters_not_improved += 1\n if iters_not_improved >= args.patience:\n early_stop = True\n break\n\n if iterations % args.log_every == 1:\n # print progress message\n print(log_template.format(time.time() - start,\n epoch, iterations, 1 + batch_idx, len(train_iter),\n 100. * (1 + batch_idx) / len(train_iter), loss.data[0], ' ' * 8,\n n_correct / n_total * 100, ' ' * 12))\n", "import math\nimport time\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau\nfrom scipy.stats import pearsonr\n\nfrom .trainer import Trainer\nfrom utils.serialization import save_checkpoint\n\n\nclass MSRVIDTrainer(Trainer):\n\n def train_epoch(self, epoch):\n self.model.train()\n total_loss = 0\n\n # since MSRVID doesn't have validation set, we manually leave-out some training data for validation\n batches = math.ceil(len(self.train_loader.dataset.examples) / self.batch_size)\n start_val_batch = math.floor(0.8 * batches)\n left_out_val_a, left_out_val_b = [], []\n left_out_val_ext_feats = []\n left_out_val_labels = []\n\n for batch_idx, batch in enumerate(self.train_loader):\n # msrvid does not contain a validation set, we leave out some training data for validation to do model selection\n if batch_idx >= start_val_batch:\n left_out_val_a.append(batch.sentence_1)\n left_out_val_b.append(batch.sentence_2)\n left_out_val_ext_feats.append(batch.ext_feats)\n left_out_val_labels.append(batch.label)\n continue\n self.optimizer.zero_grad()\n\n # Select embedding\n sent1, sent2 = self.get_sentence_embeddings(batch)\n\n output = self.model(sent1, sent2, batch.ext_feats)\n loss = F.kl_div(output, batch.label, size_average=False)\n total_loss += loss.item()\n loss.backward()\n self.optimizer.step()\n if batch_idx % self.log_interval == 0:\n self.logger.info('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, min(batch_idx * self.batch_size, len(batch.dataset.examples)),\n len(batch.dataset.examples),\n 100. * batch_idx / (len(self.train_loader)), loss.item() / len(batch))\n )\n\n self.evaluate(self.train_evaluator, 'train')\n\n if self.use_tensorboard:\n self.writer.add_scalar('msrvid/train/kl_div_loss', total_loss / len(self.train_loader.dataset.examples), epoch)\n\n return left_out_val_a, left_out_val_b, left_out_val_ext_feats, left_out_val_labels\n\n def train(self, epochs):\n if self.lr_reduce_factor != 1 and self.lr_reduce_factor != None:\n scheduler = ReduceLROnPlateau(self.optimizer, mode='max', factor=self.lr_reduce_factor, patience=self.patience)\n epoch_times = []\n prev_loss = -1\n best_dev_score = -1\n for epoch in range(1, epochs + 1):\n start = time.time()\n self.logger.info('Epoch {} started...'.format(epoch))\n left_out_a, left_out_b, left_out_ext_feats, left_out_label = self.train_epoch(epoch)\n\n # manually evaluating the validating set\n all_predictions, all_true_labels = [], []\n val_kl_div_loss = 0\n for i in range(len(left_out_a)):\n # Select embedding\n sent1 = self.embedding(left_out_a[i]).transpose(1, 2)\n sent2 = self.embedding(left_out_b[i]).transpose(1, 2)\n\n output = self.model(sent1, sent2, left_out_ext_feats[i])\n val_kl_div_loss += F.kl_div(output, left_out_label[i], size_average=False).item()\n predict_classes = left_out_a[i].new_tensor(torch.arange(0, self.train_loader.dataset.NUM_CLASSES))\\\n .float().expand(len(left_out_a[i]), self.train_loader.dataset.NUM_CLASSES)\n\n predictions = (predict_classes * output.detach().exp()).sum(dim=1)\n true_labels = (predict_classes * left_out_label[i].detach()).sum(dim=1)\n all_predictions.append(predictions)\n all_true_labels.append(true_labels)\n\n predictions = torch.cat(all_predictions).cpu().numpy()\n true_labels = torch.cat(all_true_labels).cpu().numpy()\n pearson_r = pearsonr(predictions, true_labels)[0]\n val_kl_div_loss /= len(predictions)\n\n if self.use_tensorboard:\n self.writer.add_scalar('msrvid/dev/pearson_r', pearson_r, epoch)\n\n for param_group in self.optimizer.param_groups:\n self.logger.info('Validation size: %s Pearson\\'s r: %s', output.size(0), pearson_r)\n self.logger.info('Learning rate: %s', param_group['lr'])\n\n if self.use_tensorboard:\n self.writer.add_scalar('msrvid/lr', param_group['lr'], epoch)\n self.writer.add_scalar('msrvid/dev/kl_div_loss', val_kl_div_loss, epoch)\n break\n\n if scheduler is not None:\n scheduler.step(pearson_r)\n\n end = time.time()\n duration = end - start\n self.logger.info('Epoch {} finished in {:.2f} minutes'.format(epoch, duration / 60))\n epoch_times.append(duration)\n\n if pearson_r > best_dev_score:\n best_dev_score = pearson_r\n save_checkpoint(epoch, self.model.arch, self.model.state_dict(), self.optimizer.state_dict(), best_dev_score, self.model_outfile)\n\n if abs(prev_loss - val_kl_div_loss) <= 0.0005:\n self.logger.info('Early stopping. Loss changed by less than 0.0005.')\n break\n\n prev_loss = val_kl_div_loss\n self.evaluate(self.test_evaluator, 'test')\n\n self.logger.info('Training took {:.2f} minutes overall...'.format(sum(epoch_times) / 60))" ]
[ [ "numpy.array", "torch.cuda.manual_seed", "torch.max", "numpy.random.seed", "torch.save", "torch.FloatTensor", "torch.optim.Adadelta", "torch.manual_seed", "torch.cuda.set_device", "torch.cuda.is_available", "torch.load", "torch.nn.CrossEntropyLoss" ], [ "torch.cat", "torch.arange", "scipy.stats.pearsonr", "torch.nn.functional.kl_div", "torch.optim.lr_scheduler.ReduceLROnPlateau" ] ]
WING-NUS/RL-for-Question-Generation
[ "d1966a47ef28c076902189469508194f659c5270", "d1966a47ef28c076902189469508194f659c5270", "d1966a47ef28c076902189469508194f659c5270" ]
[ "src/onqg/utils/sinusoid.py", "src/onqg/utils/model_builder.py", "discriminators/src/answerability/code/run_glue.py" ]
[ "import numpy as np\nimport torch\n\n\ndef get_sinusoid_encoding_table(n_position, d_hid, padding_idx=None):\n ''' Sinusoid position encoding table '''\n\n def cal_angle(position, hid_idx):\n return position / np.power(10000, 2 * (hid_idx // 2) / d_hid)\n\n def get_posi_angle_vec(position):\n return [cal_angle(position, hid_j) for hid_j in range(d_hid)]\n\n sinusoid_table = np.array([get_posi_angle_vec(pos_i) for pos_i in range(n_position)])\n\n sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i\n sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1\n\n if padding_idx is not None:\n # zero vector for padding dimension\n sinusoid_table[padding_idx] = 0.\n\n return torch.FloatTensor(sinusoid_table)", "import math\nimport torch.nn as nn\n\nfrom onqg.models.Models import OpenNQG\nfrom onqg.models.encoders import RNNEncoder, TransfEncoder\nfrom onqg.models.decoders import RNNDecoder, TransfDecoder\nfrom transformers import AutoConfig, AutoModelWithLMHead, AutoModelForSequenceClassification\nfrom onqg.pytorch_pretrained_bert.modeling import BertForQuestionAnswering\n\n\ndef build_encoder(opt, answer=False, separate=-1):\n feat_vocab = opt.feat_vocab\n if answer:\n feat_vocab = opt.ans_feat_vocab\n elif feat_vocab:\n n_all_feat = len(feat_vocab)\n feat_vocab = feat_vocab[:n_all_feat - opt.dec_feature]\n\n if opt.enc_rnn:\n options = {'n_vocab':opt.src_vocab_size, 'd_word_vec':opt.d_word_vec, 'd_model':opt.d_enc_model,\n 'n_layer':opt.n_enc_layer, 'brnn':opt.brnn, 'rnn':opt.enc_rnn, 'slf_attn':opt.slf_attn, \n 'feat_vocab':feat_vocab, 'd_feat_vec':opt.d_feat_vec, 'dropout':opt.dropout}\n if answer:\n options['slf_attn'] = False\n\n model = RNNEncoder.from_opt(options)\n else:\n if opt.pretrained:\n options = {'pretrained':opt.pretrained, 'n_vocab':opt.src_vocab_size, 'layer_attn':opt.layer_attn}\n for para in model.parameters():\n para.requires_grad = False\n else:\n options = {'n_vocab':opt.src_vocab_size, 'd_word_vec':opt.d_word_vec, 'd_model':opt.d_enc_model, \n 'len_max_seq':opt.max_token_src_len, 'n_layer':opt.n_enc_layer, 'd_inner':opt.d_inner, \n 'slf_attn':opt.slf_attn_type, 'n_head':opt.n_head, 'd_k':opt.d_k, 'd_v':opt.d_v, 'feat_vocab':feat_vocab, \n 'd_feat_vec':opt.d_feat_vec, 'layer_attn':opt.layer_attn, 'mask_slf_attn':opt.defined_slf_attn_mask,\n 'separate':separate, 'dropout':opt.dropout, 'attn_dropout':opt.attn_dropout}\n \n model = TransfEncoder.from_opt(options)\n\n return model \n\n\ndef build_decoder(opt, encoder_word_emb_weight, device, rl_model=None):\n if opt.dec_feature:\n n_all_feat = len(opt.feat_vocab)\n feat_vocab = opt.feat_vocab[n_all_feat - opt.dec_feature:]\n else:\n feat_vocab = None\n \n d_enc_model = opt.d_enc_model if not opt.pretrained else 768 # TODO: fix this magic number later\n n_enc_layer = opt.n_enc_layer if not opt.pretrained else 12 # TODO: fix this magic number later\n \n if opt.dec_rnn:\n options = {'n_vocab':opt.tgt_vocab_size, 'ans_n_vocab':opt.src_vocab_size, 'd_word_vec':opt.d_word_vec, 'd_model':opt.d_dec_model,\n 'n_layer':opt.n_dec_layer, 'rnn':opt.dec_rnn, 'd_k':opt.d_k, 'feat_vocab':feat_vocab,\n 'd_feat_vec':opt.d_feat_vec, 'd_enc_model':d_enc_model, 'n_enc_layer':n_enc_layer,\n 'input_feed':opt.input_feed, 'copy':opt.copy, 'answer':opt.answer == 'enc', 'coverage':opt.coverage, \n 'separate':opt.answer == 'sep', 'layer_attn':opt.layer_attn, 'encoder_word_emb': encoder_word_emb_weight,\n 'maxout_pool_size':opt.maxout_pool_size, 'dropout':opt.dropout, 'device':device}\n options['mode'], options['rl_model'] = '', None\n model = RNNDecoder.from_opt(options)\n else:\n options = {'n_vocab':opt.tgt_vocab_size, 'len_max_seq':opt.max_token_tgt_len, 'd_word_vec':opt.d_word_vec, \n 'd_model':opt.d_dec_model, 'n_layer':opt.n_dec_layer, 'd_inner':opt.d_inner, 'n_head':opt.n_head,\n 'd_k':opt.d_k, 'd_v':opt.d_v, 'layer_attn':opt.layer_attn, 'n_enc_layer':n_enc_layer, \n 'feat_vocab':feat_vocab, 'd_feat_vec':opt.d_feat_vec, 'maxout_pool_size':opt.maxout_pool_size,\n 'dropout':opt.dropout, 'encoder_word_emb': encoder_word_emb_weight}\n model = TransfDecoder.from_opt(options)\n \n return model\n\n\ndef initialize(model, opt):\n parameters_cnt = 0\n for name, para in model.named_parameters():\n if not opt.pretrained or name.count('encoder') == 0 == 0:\n if para.dim() == 1:\n para.data.normal_(0, math.sqrt(6 / (1 + para.size(0))))\n else:\n nn.init.xavier_normal_(para, math.sqrt(3))\n size = list(para.size())\n local_cnt = 1\n for d in size:\n local_cnt *= d\n parameters_cnt += local_cnt\n \n if opt.pre_trained_vocab:\n assert opt.d_word_vec == 300, \"Dimension of word vectors must equal to that of pretrained word-embedding\"\n if not opt.pretrained:\n model.encoder.word_emb.weight.data.copy_(opt.pre_trained_src_emb)\n if opt.answer == 'enc':\n model.answer_encoder.word_emb.weight.data.copy_(opt.pre_trained_ans_emb)\n model.decoder.word_emb.weight.data.copy_(opt.pre_trained_tgt_emb)\n \n if opt.proj_share_weight:\n weight = model.decoder.maxout(model.decoder.word_emb.weight.data)\n model.generator.weight.data.copy_(weight)\n \n weight = model.encoder.word_emb.weight.data\n # model.decoder.ans_emb.wieght.data.copy_(weight)\n if opt.src_vocab_size == opt.tgt_vocab_size:\n model.decoder.word_emb.weight.data.copy_(weight)\n\n return model, parameters_cnt\n\n\ndef build_model(opt, device, separate=-1, checkpoint=None):\n encoder = build_encoder(opt, separate=separate)\n decoder = build_decoder(opt, encoder.word_emb.weight, device)\n if opt.answer == 'enc':\n answer_encoder = build_encoder(opt, answer=True)\n model = OpenNQG(encoder, decoder, answer_encoder=answer_encoder)\n else:\n model = OpenNQG(encoder, decoder)\n \n model.generator = nn.Linear(opt.d_dec_model // opt.maxout_pool_size, opt.tgt_vocab_size, bias=False)\n model, parameters_cnt = initialize(model, opt)\n \n if checkpoint is not None:\n try:\n model.load_state_dict(checkpoint['model state dict'])\n except:\n model.load_state_dict(checkpoint)\n\n model = model.to(device) \n model.device = device \n if len(opt.gpus) > 1:\n model = nn.DataParallel(model, device_ids=opt.gpus)\n \n return model, parameters_cnt\n\n\ndef load_rl_model(opt, device, rl_device):\n\n def _get_fluency(model_dir, device):\n config = AutoConfig.from_pretrained(model_dir)\n config.is_decoder = True\n model = AutoModelWithLMHead.from_pretrained(model_dir,\n from_tf=bool(\".ckpt\" in model_dir),\n config=config)\n model = model.to(device)\n return model\n \n def _get_relevance(model_dir, device):\n config = AutoConfig.from_pretrained(model_dir)\n model = AutoModelForSequenceClassification.from_pretrained(model_dir,\n from_tf=bool(\".ckpt\" in model_dir),\n config=config)\n model = model.to(device)\n return model\n \n def _get_answerability(model_dir, device):\n model = BertForQuestionAnswering.from_pretrained(model_dir)\n model = model.to(device)\n return model\n\n models = {}\n\n for rl_mode, current_rl_model_dir in zip(opt.rl, opt.rl_model_dir):\n if rl_mode == 'fluency':\n models[rl_mode] = _get_fluency(current_rl_model_dir, opt.rl_device['fluency'])\n elif rl_mode == 'relevance':\n models[rl_mode] = _get_relevance(current_rl_model_dir, opt.rl_device['relevance'])\n elif rl_mode == 'answerability':\n models[rl_mode] = _get_answerability(current_rl_model_dir, opt.rl_device['answerability'])\n \n return models\n", "# Copyright (c) 2019, Facebook, Inc. and its affiliates. All Rights Reserved\n\"\"\"BERT finetuning runner.\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport argparse\nimport csv\nimport logging\nimport os\nimport random\nimport sys\nimport time\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import DataLoader, TensorDataset\n\nfrom torch.nn import CrossEntropyLoss, MSELoss\nfrom scipy.stats import pearsonr, spearmanr\nfrom sklearn.metrics import matthews_corrcoef, f1_score\n\nfrom pytorch_pretrained_bert.file_utils import PYTORCH_PRETRAINED_BERT_CACHE, WEIGHTS_NAME, CONFIG_NAME\nfrom pytorch_pretrained_bert.modeling import BertForSequenceClassification\nfrom pytorch_pretrained_bert.tokenization import BertTokenizer\nfrom pytorch_pretrained_bert.optimization import BertAdam, warmup_linear\n\n\nPRED_FILE = \"predictions.tsv\"\nEVAL_FILE = \"eval_results.txt\"\nTEST_FILE = \"test_results.txt\"\n\nlogging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',\n datefmt='%m/%d/%Y %H:%M:%S',\n level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\nclass InputExample(object):\n \"\"\"A single training/test example for simple sequence classification.\"\"\"\n\n def __init__(self, guid, text_a, text_b=None, label=None):\n \"\"\"Constructs a InputExample.\n\n Args:\n guid: Unique id for the example.\n text_a: string. The untokenized text of the first sequence. For single\n sequence tasks, only this sequence must be specified.\n text_b: (Optional) string. The untokenized text of the second sequence.\n Only must be specified for sequence pair tasks.\n label: (Optional) string. The label of the example. This should be\n specified for train and dev examples, but not for test examples.\n \"\"\"\n self.guid = guid\n self.text_a = text_a\n self.text_b = text_b\n self.label = label\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self, input_ids, input_mask, segment_ids, label_id):\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.label_id = label_id\n\n\nclass DataProcessor(object):\n \"\"\"Base class for data converters for sequence classification data sets.\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the train set.\"\"\"\n raise NotImplementedError()\n\n def get_dev_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the dev set.\"\"\"\n raise NotImplementedError()\n\n def get_labels(self):\n \"\"\"Gets the list of labels for this data set.\"\"\"\n raise NotImplementedError()\n\n @classmethod\n def _read_tsv(cls, input_file, quotechar=None):\n \"\"\"Reads a tab separated value file.\"\"\"\n with open(input_file, \"r\", encoding=\"utf-8\") as f:\n reader = csv.reader(f, delimiter=\"\\t\", quotechar=quotechar)\n lines = []\n for line in reader:\n if sys.version_info[0] == 2:\n line = list(cell for cell in line)\n lines.append(line)\n return lines\n\n\nclass MrpcProcessor(DataProcessor):\n \"\"\"Processor for the MRPC data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n logger.info(\"LOOKING AT {}\".format(os.path.join(data_dir, \"train.tsv\")))\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, i)\n text_a = line[3]\n text_b = line[4]\n label = None if set_type == \"test\" else line[0]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass MnliProcessor(DataProcessor):\n \"\"\"Processor for the MultiNLI data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir, eval_set=\"MNLI-m\"):\n \"\"\"See base class.\"\"\"\n if eval_set is None or eval_set == \"MNLI-m\":\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev_matched.tsv\")), \"dev\")\n else:\n assert eval_set == \"MNLI-mm\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev_mismatched.tsv\")), \"dev\")\n\n def get_test_examples(self, data_dir, eval_set=\"MNLI-m\"):\n \"\"\"See base class.\"\"\"\n if eval_set is None or eval_set == \"MNLI-m\":\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test_matched.tsv\")), \"test\")\n elif eval_set == \"MNLI-mm\":\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test_mismatched.tsv\")), \"test\")\n else:\n assert eval_set == \"AX\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"ax.tsv\")), \"ax\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"contradiction\", \"entailment\", \"neutral\"]\n\n def _create_examples(self, lines, set_type):\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n if set_type == \"ax\":\n text_a = line[1]\n text_b = line[2]\n label = None\n else:\n text_a = line[8]\n text_b = line[9]\n label = None if set_type == \"test\" else line[-1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass ColaProcessor(DataProcessor):\n \"\"\"Processor for the CoLA data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n examples = []\n for (i, line) in enumerate(lines):\n if (i == 0) and (set_type == \"test\"):\n continue\n guid = \"%s-%s\" % (set_type, i)\n if set_type == 'test':\n text_a = line[1]\n label = None\n else:\n text_a = line[3]\n label = line[1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=None, label=label))\n return examples\n\n\nclass Sst2Processor(DataProcessor):\n \"\"\"Processor for the SST-2 data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, i)\n if set_type == \"test\":\n text_a = line[1]\n label = None\n else:\n text_a = line[0]\n label = line[1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=None, label=label))\n return examples\n\n\nclass StsbProcessor(DataProcessor):\n \"\"\"Processor for the STS-B data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [None]\n\n def _create_examples(self, lines, set_type):\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n text_a = line[7]\n text_b = line[8]\n label = None if set_type == \"test\" else line[-1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass QqpProcessor(DataProcessor):\n \"\"\"Processor for the QQP data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n if set_type == \"test\":\n text_a = line[1]\n text_b = line[2]\n label = None\n else:\n try:\n text_a = line[3]\n text_b = line[4]\n label = line[5]\n except IndexError:\n continue\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass QnliProcessor(DataProcessor):\n \"\"\"Processor for the STS-B data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"entailment\", \"not_entailment\"]\n\n def _create_examples(self, lines, set_type):\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n text_a = line[1]\n text_b = line[2]\n label = None if set_type == \"test\" else line[-1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass RteProcessor(DataProcessor):\n \"\"\"Processor for the RTE data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"entailment\", \"not_entailment\"]\n\n def _create_examples(self, lines, set_type):\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n text_a = line[1]\n text_b = line[2]\n label = None if set_type == \"test\" else line[-1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass WnliProcessor(DataProcessor):\n \"\"\"Processor for the WNLI data set (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"0\", \"1\"]\n\n def _create_examples(self, lines, set_type):\n examples = []\n for (i, line) in enumerate(lines):\n if i == 0:\n continue\n guid = \"%s-%s\" % (set_type, line[0])\n text_a = line[1]\n text_b = line[2]\n label = None if set_type == \"test\" else line[-1]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nPROCESSORS = {\n \"cola\": ColaProcessor,\n \"mnli\": MnliProcessor,\n \"mrpc\": MrpcProcessor,\n \"sst-2\": Sst2Processor,\n \"sts-b\": StsbProcessor,\n \"qqp\": QqpProcessor,\n \"qnli\": QnliProcessor,\n \"rte\": RteProcessor,\n \"wnli\": WnliProcessor,\n}\n\nOUTPUT_MODES = {\n \"cola\": \"classification\",\n \"mnli\": \"classification\",\n \"mrpc\": \"classification\",\n \"sst-2\": \"classification\",\n \"sts-b\": \"regression\",\n \"qqp\": \"classification\",\n \"qnli\": \"classification\",\n \"rte\": \"classification\",\n \"wnli\": \"classification\",\n}\n\nEVAL_METRICS = {\n \"cola\": \"mcc\",\n \"mnli\": \"acc\",\n \"mrpc\": \"acc_and_f1\",\n \"sst-2\": \"acc\",\n \"sts-b\": \"corr\",\n \"qqp\": \"acc_and_f1\",\n \"qnli\": \"acc\",\n \"rte\": \"acc\",\n \"wnli\": \"acc\",\n}\n\n\ndef convert_examples_to_features(examples, label_list, max_seq_length,\n tokenizer, output_mode):\n \"\"\"Loads a data file into a list of `InputBatch`s.\"\"\"\n\n if output_mode == 'classification':\n label_map = {label: i for i, label in enumerate(label_list)}\n\n features = []\n for (ex_index, example) in enumerate(examples):\n if ex_index % 10000 == 0:\n logger.info(\"Writing example %d of %d\" % (ex_index, len(examples)))\n\n tokens_a = tokenizer.tokenize(example.text_a)\n\n tokens_b = None\n if example.text_b:\n tokens_b = tokenizer.tokenize(example.text_b)\n _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\n else:\n if len(tokens_a) > max_seq_length - 2:\n tokens_a = tokens_a[:(max_seq_length - 2)]\n\n tokens = [\"[CLS]\"] + tokens_a + [\"[SEP]\"]\n segment_ids = [0] * len(tokens)\n\n if tokens_b:\n tokens += tokens_b + [\"[SEP]\"]\n segment_ids += [1] * (len(tokens_b) + 1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n padding = [0] * (max_seq_length - len(input_ids))\n input_ids += padding\n input_mask += padding\n segment_ids += padding\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n\n if example.label is None:\n label_id = None\n else:\n if output_mode == \"classification\":\n label_id = label_map[example.label]\n elif output_mode == \"regression\":\n label_id = float(example.label)\n else:\n raise KeyError(output_mode)\n\n if ex_index < 5:\n logger.info(\"*** Example ***\")\n logger.info(\"guid: %s\" % (example.guid))\n logger.info(\"tokens: %s\" % \" \".join(\n [str(x) for x in tokens]))\n logger.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\n logger.info(\"input_mask: %s\" % \" \".join([str(x) for x in input_mask]))\n logger.info(\n \"segment_ids: %s\" % \" \".join([str(x) for x in segment_ids]))\n if example.label is None:\n logger.info(\"label: <UNK>\")\n else:\n logger.info(\"label: %s (id = %d)\" % (example.label, label_id))\n\n features.append(\n InputFeatures(input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_id=label_id))\n return features\n\n\ndef _truncate_seq_pair(tokens_a, tokens_b, max_length):\n \"\"\"Truncates a sequence pair in place to the maximum length.\"\"\"\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_length:\n break\n if len(tokens_a) > len(tokens_b):\n tokens_a.pop()\n else:\n tokens_b.pop()\n\n\ndef simple_accuracy(preds, labels):\n return (preds == labels).mean()\n\n\ndef acc_and_f1(preds, labels):\n acc = simple_accuracy(preds, labels)\n f1 = f1_score(y_true=labels, y_pred=preds)\n return {\n \"acc\": acc,\n \"f1\": f1,\n \"acc_and_f1\": (acc + f1) / 2,\n }\n\n\ndef pearson_and_spearman(preds, labels):\n pearson_corr = pearsonr(preds, labels)[0]\n spearman_corr = spearmanr(preds, labels)[0]\n return {\n \"pearson\": pearson_corr,\n \"spearmanr\": spearman_corr,\n \"corr\": (pearson_corr + spearman_corr) / 2,\n }\n\n\ndef compute_metrics(task_name, preds, labels):\n assert len(preds) == len(labels)\n if task_name == \"cola\":\n return {\"mcc\": matthews_corrcoef(labels, preds)}\n elif task_name == \"sst-2\":\n return {\"acc\": simple_accuracy(preds, labels)}\n elif task_name == \"mrpc\":\n return acc_and_f1(preds, labels)\n elif task_name == \"sts-b\":\n return pearson_and_spearman(preds, labels)\n elif task_name == \"qqp\":\n return acc_and_f1(preds, labels)\n elif task_name == \"mnli\":\n return {\"acc\": simple_accuracy(preds, labels)}\n elif task_name == \"qnli\":\n return {\"acc\": simple_accuracy(preds, labels)}\n elif task_name == \"rte\":\n return {\"acc\": simple_accuracy(preds, labels)}\n elif task_name == \"wnli\":\n return {\"acc\": simple_accuracy(preds, labels)}\n else:\n raise KeyError(task_name)\n\n\ndef evaluate(task_name, model, device, eval_dataloader, eval_label_ids, num_labels):\n model.eval()\n eval_loss = 0\n nb_eval_steps = 0\n preds = []\n for eval_example in eval_dataloader:\n if len(eval_example) == 4:\n input_ids, input_mask, segment_ids, label_ids = eval_example\n else:\n input_ids, input_mask, segment_ids = eval_example\n label_ids = None\n\n input_ids = input_ids.to(device)\n input_mask = input_mask.to(device)\n segment_ids = segment_ids.to(device)\n\n with torch.no_grad():\n logits = model(input_ids, segment_ids, input_mask, labels=None)\n\n if label_ids is not None:\n label_ids = label_ids.to(device)\n if OUTPUT_MODES[task_name] == \"classification\":\n loss_fct = CrossEntropyLoss()\n tmp_eval_loss = loss_fct(logits.view(-1, num_labels), label_ids.view(-1))\n elif OUTPUT_MODES[task_name] == \"regression\":\n loss_fct = MSELoss()\n tmp_eval_loss = loss_fct(logits.view(-1), label_ids.view(-1))\n eval_loss += tmp_eval_loss.mean().item()\n\n nb_eval_steps += 1\n if len(preds) == 0:\n preds.append(logits.detach().cpu().numpy())\n else:\n preds[0] = np.append(\n preds[0], logits.detach().cpu().numpy(), axis=0)\n\n eval_loss = eval_loss / nb_eval_steps\n preds = preds[0]\n if OUTPUT_MODES[task_name] == \"classification\":\n preds = np.argmax(preds, axis=1)\n elif OUTPUT_MODES[task_name] == \"regression\":\n preds = np.squeeze(preds)\n\n if eval_label_ids is not None:\n result = compute_metrics(task_name, preds, eval_label_ids.numpy())\n result['eval_loss'] = eval_loss\n else:\n result = {}\n\n logger.info(\"***** Eval results *****\")\n for key in sorted(result.keys()):\n logger.info(\" %s = %s\", key, str(result[key]))\n return preds, result\n\n\ndef main(args):\n device = torch.device(\"cuda\" if torch.cuda.is_available() and not args.no_cuda else \"cpu\")\n n_gpu = torch.cuda.device_count()\n\n logger.info(\"device: {} n_gpu: {}, 16-bits training: {}\".format(\n device, n_gpu, args.fp16))\n\n if args.gradient_accumulation_steps < 1:\n raise ValueError(\"Invalid gradient_accumulation_steps parameter: {}, should be >= 1\".format(\n args.gradient_accumulation_steps))\n\n args.train_batch_size = args.train_batch_size // args.gradient_accumulation_steps\n\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed)\n\n if not args.do_train and not args.do_eval:\n raise ValueError(\"At least one of `do_train` or `do_eval` must be True.\")\n\n if not os.path.exists(args.output_dir):\n os.makedirs(args.output_dir)\n if args.do_train:\n logger.addHandler(logging.FileHandler(os.path.join(args.output_dir, \"train.log\"), 'w'))\n else:\n logger.addHandler(logging.FileHandler(os.path.join(args.output_dir, \"eval.log\"), 'w'))\n logger.info(args)\n\n task_name = args.task_name.lower()\n\n if task_name not in PROCESSORS:\n raise ValueError(\"Task not found: %s\" % (task_name))\n\n processor = PROCESSORS[task_name]()\n label_list = processor.get_labels()\n id2label = {i: label for i, label in enumerate(label_list)}\n num_labels = len(label_list)\n eval_metric = EVAL_METRICS[task_name]\n\n tokenizer = BertTokenizer.from_pretrained(args.model, do_lower_case=args.do_lower_case)\n\n if args.do_train or (not args.eval_test):\n if task_name == \"mnli\":\n eval_examples = processor.get_dev_examples(args.data_dir, eval_set=args.eval_set)\n else:\n eval_examples = processor.get_dev_examples(args.data_dir)\n eval_features = convert_examples_to_features(\n eval_examples, label_list, args.max_seq_length, tokenizer, OUTPUT_MODES[task_name])\n logger.info(\"***** Dev *****\")\n logger.info(\" Num examples = %d\", len(eval_examples))\n logger.info(\" Batch size = %d\", args.eval_batch_size)\n all_input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long)\n all_input_mask = torch.tensor([f.input_mask for f in eval_features], dtype=torch.long)\n all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)\n\n if OUTPUT_MODES[task_name] == \"classification\":\n all_label_ids = torch.tensor([f.label_id for f in eval_features], dtype=torch.long)\n elif OUTPUT_MODES[task_name] == \"regression\":\n all_label_ids = torch.tensor([f.label_id for f in eval_features], dtype=torch.float)\n if args.fp16:\n all_label_ids = all_label_ids.half()\n\n eval_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)\n eval_dataloader = DataLoader(eval_data, batch_size=args.eval_batch_size)\n eval_label_ids = all_label_ids\n\n if args.do_train:\n train_examples = processor.get_train_examples(args.data_dir)\n train_features = convert_examples_to_features(\n train_examples, label_list, args.max_seq_length, tokenizer, OUTPUT_MODES[task_name])\n if args.train_mode == 'sorted' or args.train_mode == 'random_sorted':\n train_features = sorted(train_features, key=lambda f: np.sum(f.input_mask))\n else:\n random.shuffle(train_features)\n\n all_input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.long)\n all_input_mask = torch.tensor([f.input_mask for f in train_features], dtype=torch.long)\n all_segment_ids = torch.tensor([f.segment_ids for f in train_features], dtype=torch.long)\n\n if OUTPUT_MODES[task_name] == \"classification\":\n all_label_ids = torch.tensor([f.label_id for f in train_features], dtype=torch.long)\n elif OUTPUT_MODES[task_name] == \"regression\":\n all_label_ids = torch.tensor([f.label_id for f in train_features], dtype=torch.float)\n if args.fp16:\n all_label_ids = all_label_ids.half()\n\n train_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)\n train_dataloader = DataLoader(train_data, batch_size=args.train_batch_size, drop_last=True)\n train_batches = [batch for batch in train_dataloader]\n eval_step = max(1, len(train_batches) // args.eval_per_epoch)\n\n num_train_optimization_steps = \\\n len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs\n\n logger.info(\"***** Training *****\")\n logger.info(\" Num examples = %d\", len(train_examples))\n logger.info(\" Batch size = %d\", args.train_batch_size)\n logger.info(\" Num steps = %d\", num_train_optimization_steps)\n\n best_result = None\n lrs = [args.learning_rate] if args.learning_rate else \\\n [1e-6, 2e-6, 3e-6, 5e-6, 1e-5, 2e-5, 3e-5, 5e-5]\n for lr in lrs:\n cache_dir = args.cache_dir if args.cache_dir else \\\n PYTORCH_PRETRAINED_BERT_CACHE\n model = BertForSequenceClassification.from_pretrained(\n args.model, cache_dir=cache_dir, num_labels=num_labels)\n if args.fp16:\n model.half()\n model.to(device)\n if n_gpu > 1:\n model = torch.nn.DataParallel(model)\n\n # Prepare optimizer\n param_optimizer = list(model.named_parameters())\n no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']\n optimizer_grouped_parameters = [\n {'params': [p for n, p in param_optimizer\n if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},\n {'params': [p for n, p in param_optimizer\n if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}\n ]\n if args.fp16:\n try:\n from apex.optimizers import FP16_Optimizer\n from apex.optimizers import FusedAdam\n except ImportError:\n raise ImportError(\"Please install apex from https://www.github.com/nvidia/apex\"\n \"to use distributed and fp16 training.\")\n\n optimizer = FusedAdam(optimizer_grouped_parameters,\n lr=lr,\n bias_correction=False,\n max_grad_norm=1.0)\n if args.loss_scale == 0:\n optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)\n else:\n optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)\n\n else:\n optimizer = BertAdam(optimizer_grouped_parameters,\n lr=lr,\n warmup=args.warmup_proportion,\n t_total=num_train_optimization_steps)\n\n global_step = 0\n nb_tr_steps = 0\n nb_tr_examples = 0\n tr_loss = 0\n start_time = time.time()\n\n for epoch in range(int(args.num_train_epochs)):\n model.train()\n logger.info(\"Start epoch #{} (lr = {})...\".format(epoch, lr))\n if args.train_mode == 'random' or args.train_mode == 'random_sorted':\n random.shuffle(train_batches)\n for step, batch in enumerate(train_batches):\n batch = tuple(t.to(device) for t in batch)\n input_ids, input_mask, segment_ids, label_ids = batch\n logits = model(input_ids, segment_ids, input_mask, labels=None)\n\n if OUTPUT_MODES[task_name] == \"classification\":\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, num_labels), label_ids.view(-1))\n elif OUTPUT_MODES[task_name] == \"regression\":\n loss_fct = MSELoss()\n loss = loss_fct(logits.view(-1), label_ids.view(-1))\n\n if n_gpu > 1:\n loss = loss.mean()\n if args.gradient_accumulation_steps > 1:\n loss = loss / args.gradient_accumulation_steps\n\n if args.fp16:\n optimizer.backward(loss)\n else:\n loss.backward()\n\n tr_loss += loss.item()\n nb_tr_examples += input_ids.size(0)\n nb_tr_steps += 1\n\n if (step + 1) % args.gradient_accumulation_steps == 0:\n if args.fp16:\n lr_this_step = lr * \\\n warmup_linear(global_step/num_train_optimization_steps, args.warmup_proportion)\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr_this_step\n optimizer.step()\n optimizer.zero_grad()\n global_step += 1\n\n if (step + 1) % eval_step == 0:\n logger.info('Epoch: {}, Step: {} / {}, used_time = {:.2f}s, loss = {:.6f}'.format(\n epoch, step + 1, len(train_dataloader),\n time.time() - start_time, tr_loss / nb_tr_steps))\n save_model = False\n if args.do_eval:\n preds, result = evaluate(task_name, model, device,\n eval_dataloader, eval_label_ids, num_labels)\n model.train()\n result['global_step'] = global_step\n result['epoch'] = epoch\n result['learning_rate'] = lr\n result['batch_size'] = args.train_batch_size\n logger.info(\"First 20 predictions:\")\n for pred, label in zip(preds[:20], eval_label_ids.numpy()[:20]):\n if OUTPUT_MODES[task_name] == 'classification':\n sign = u'\\u2713' if pred == label else u'\\u2718'\n logger.info(\"pred = %s, label = %s %s\" % (id2label[pred], id2label[label], sign))\n else:\n logger.info(\"pred = %.4f, label = %.4f\" % (pred, label))\n if (best_result is None) or (result[eval_metric] > best_result[eval_metric]):\n best_result = result\n save_model = True\n logger.info(\"!!! Best dev %s (lr=%s, epoch=%d): %.2f\" %\n (eval_metric, str(lr), epoch, result[eval_metric] * 100.0))\n else:\n save_model = True\n\n if save_model:\n model_to_save = model.module if hasattr(model, 'module') else model\n output_model_file = os.path.join(args.output_dir, WEIGHTS_NAME)\n output_config_file = os.path.join(args.output_dir, CONFIG_NAME)\n torch.save(model_to_save.state_dict(), output_model_file)\n model_to_save.config.to_json_file(output_config_file)\n tokenizer.save_vocabulary(args.output_dir)\n if best_result:\n output_eval_file = os.path.join(args.output_dir, EVAL_FILE)\n with open(output_eval_file, \"w\") as writer:\n for key in sorted(result.keys()):\n writer.write(\"%s = %s\\n\" % (key, str(result[key])))\n\n if args.do_eval:\n if args.eval_test:\n if task_name == \"mnli\":\n eval_examples = processor.get_test_examples(args.data_dir, eval_set=args.eval_set)\n else:\n eval_examples = processor.get_test_examples(args.data_dir)\n eval_features = convert_examples_to_features(\n eval_examples, label_list, args.max_seq_length, tokenizer, OUTPUT_MODES[task_name])\n logger.info(\"***** Test *****\")\n logger.info(\" Num examples = %d\", len(eval_examples))\n logger.info(\" Batch size = %d\", args.eval_batch_size)\n all_input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long)\n all_input_mask = torch.tensor([f.input_mask for f in eval_features], dtype=torch.long)\n all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)\n eval_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids)\n eval_dataloader = DataLoader(eval_data, batch_size=args.eval_batch_size)\n eval_label_ids = None\n\n model = BertForSequenceClassification.from_pretrained(args.output_dir, num_labels=num_labels)\n if args.fp16:\n model.half()\n model.to(device)\n preds, result = evaluate(task_name, model, device, eval_dataloader, eval_label_ids, num_labels)\n pred_file = os.path.join(args.output_dir, PRED_FILE)\n with open(pred_file, \"w\") as f_out:\n f_out.write(\"index\\tprediction\\n\")\n for i, pred in enumerate(preds):\n if OUTPUT_MODES[task_name] == 'classification':\n f_out.write(\"%d\\t%s\\n\" % (i, id2label[pred]))\n else:\n f_out.write(\"%d\\t%.6f\\n\" % (i, pred))\n output_eval_file = os.path.join(args.output_dir, TEST_FILE)\n with open(output_eval_file, \"w\") as writer:\n for key in sorted(result.keys()):\n writer.write(\"%s = %s\\n\" % (key, str(result[key])))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--data_dir\", default=None, type=str, required=True,\n help=\"The input data dir. Should contain the .tsv files (or other data files) for the task.\")\n parser.add_argument(\"--model\", default=None, type=str, required=True)\n parser.add_argument(\"--task_name\", default=None, type=str, required=True,\n help=\"The name of the task to train.\")\n parser.add_argument(\"--output_dir\", default=None, type=str, required=True,\n help=\"The output directory where the model predictions and checkpoints will be written.\")\n parser.add_argument(\"--cache_dir\", default=\"\", type=str,\n help=\"Where do you want to store the pre-trained models downloaded from s3\")\n parser.add_argument(\"--eval_per_epoch\", default=10, type=int,\n help=\"How many times it evaluates on dev set per epoch\")\n parser.add_argument(\"--max_seq_length\", default=128, type=int,\n help=\"The maximum total input sequence length after WordPiece tokenization. \\n\"\n \"Sequences longer than this will be truncated, and sequences shorter \\n\"\n \"than this will be padded.\")\n parser.add_argument(\"--do_train\", action='store_true', help=\"Whether to run training.\")\n parser.add_argument(\"--train_mode\", type=str, default='random_sorted', choices=['random', 'sorted', 'random_sorted'])\n parser.add_argument(\"--do_eval\", action='store_true', help=\"Whether to run eval on the dev set.\")\n parser.add_argument(\"--do_lower_case\", action='store_true', help=\"Set this flag if you are using an uncased model.\")\n parser.add_argument(\"--eval_test\", action='store_true', help=\"Whether to eval on the test set.\")\n parser.add_argument(\"--eval_set\", type=str, default=None, help=\"Whether to evalu on the test set.\")\n parser.add_argument(\"--train_batch_size\", default=32, type=int, help=\"Total batch size for training.\")\n parser.add_argument(\"--eval_batch_size\", default=32, type=int, help=\"Total batch size for eval.\")\n parser.add_argument(\"--learning_rate\", default=None, type=float,\n help=\"The initial learning rate for Adam.\")\n parser.add_argument(\"--num_train_epochs\", default=3.0, type=float,\n help=\"Total number of training epochs to perform.\")\n parser.add_argument(\"--warmup_proportion\", default=0.1, type=float,\n help=\"Proportion of training to perform linear learning rate warmup for. \"\n \"E.g., 0.1 = 10%% of training.\")\n parser.add_argument(\"--no_cuda\", action='store_true',\n help=\"Whether not to use CUDA when available\")\n parser.add_argument('--seed', type=int, default=42,\n help=\"random seed for initialization\")\n parser.add_argument('--gradient_accumulation_steps', type=int, default=1,\n help=\"Number of updates steps to accumulate before performing a backward/update pass.\")\n parser.add_argument('--fp16', action='store_true',\n help=\"Whether to use 16-bit float precision instead of 32-bit\")\n parser.add_argument('--loss_scale', type=float, default=0,\n help=\"Loss scaling to improve fp16 numeric stability. Only used when fp16 set to True.\\n\"\n \"0 (default value): dynamic loss scaling.\\n\"\n \"Positive power of 2: static loss scaling value.\\n\")\n args = parser.parse_args()\n\n main(args)\n" ]
[ [ "numpy.sin", "torch.FloatTensor", "numpy.power", "numpy.cos" ], [ "torch.nn.Linear", "torch.nn.DataParallel" ], [ "scipy.stats.pearsonr", "torch.cuda.is_available", "sklearn.metrics.f1_score", "torch.nn.CrossEntropyLoss", "torch.nn.DataParallel", "torch.manual_seed", "numpy.argmax", "torch.tensor", "torch.utils.data.DataLoader", "torch.cuda.manual_seed_all", "sklearn.metrics.matthews_corrcoef", "torch.cuda.device_count", "numpy.squeeze", "torch.utils.data.TensorDataset", "torch.nn.MSELoss", "numpy.random.seed", "numpy.sum", "torch.no_grad", "scipy.stats.spearmanr" ] ]
ClaudioGuevara/rosetta
[ "beb6a390433e7a98adb125b26a035ecd44e7b15a" ]
[ "datasets/generate_final_csv.py" ]
[ "import os\n\nimport pandas as pd\n\ninteractions_df = pd.read_csv(os.path.join(\n os.getcwd(), './interactions_filters_post_search.csv'))\nresumen_antigen_df = pd.read_csv(os.path.join(\n os.getcwd(), './resume_antigen_info.csv'))\n\n# Borramos las interacciones duplicadas\ninteractions_df = interactions_df.drop_duplicates(\n subset=[\"antigen\", \"antibody\"], keep=False)\n\ninteractions_df.to_csv(\n \"interactions_without_duplicates.csv\", index=False, header=True)\n\ninteractions_final = pd.merge(\n interactions_df, resumen_antigen_df, on=\"antigen\")\n\ninteractions_final = interactions_final[[\n \"antibody\", \"antigen\", \"pdb_file\", \"value_intensity\", \"category_full_space\", \"filter\", \"chain\"]]\n\ninteractions_final.rename(columns={\"pdb_file\": \"antigen_pdb\"}, inplace=True)\n\ninteractions_final.to_csv(\n \"antigen_antibody_interactions.csv\", index=False, header=True)\n" ]
[ [ "pandas.merge" ] ]
Peefy/CLRS_dugu_code-master
[ "33662f46dc346203b220d7481d1a4439feda05d2" ]
[ "src/chapter28/chapter28note.py" ]
[ "# coding:utf-8\n# usr/bin/python3\n# python src/chapter28/chapter28note.py\n# python3 src/chapter28/chapter28note.py\n\"\"\"\n\nClass Chapter28_1\n\nClass Chapter28_2\n\nClass Chapter28_3\n\nClass Chapter28_4\n\nClass Chapter28_5\n\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nimport numpy as np\n\nclass Chapter28_1:\n \"\"\"\n chapter28.1 note and function\n \"\"\"\n\n def __init__(self):\n pass\n\n def note(self):\n \"\"\"\n Summary\n ====\n Print chapter28.1 note\n\n Example\n ====\n ```python\n Chapter28_1().note()\n ```\n \"\"\"\n print('chapter28.1 note as follow')\n print('28.1 矩阵的性质')\n print('矩阵运算在科学计算中非常重要')\n print('矩阵是数字的一个矩阵阵列,在python中使用np.matrix[[1,2],[3,4]]')\n print('矩阵和向量')\n print('单位矩阵')\n print('零矩阵')\n print('对角矩阵')\n print('三对角矩阵')\n print('上三角矩阵')\n print('下三角矩阵')\n print('置换矩阵')\n print('对称矩阵')\n print('矩阵乘法满足结合律,矩阵乘法对假发满足分配律')\n print('矩阵的F范数和2范数')\n print('向量的2范数')\n print('矩阵的逆,秩和行列式')\n print('定理28.1 一个方阵满秩当且仅当它为非奇异矩阵')\n print('定理28.2 当且仅当A无空向量,矩阵A列满秩')\n print('定理28.3 当且仅当A具有空向量时,方阵A是奇异的')\n print('定理28.4 (行列式的性质) 方阵A的行列式具有如下的性质')\n print(' 如果A的任何行或者列的元素为0,则det(A)=0')\n print(' 用常数l乘A的行列式任意一行(或任意一列)的各元素,等于用l乘A的行列式')\n print(' A的行列式的值与其转置矩阵A^T的行列式的值相等')\n print(' 行列式的任意两行(或者两列)互换,则其值异号')\n print('定理28.5 当且仅当det(A)=0,一个n*n方阵A是奇异的')\n print('正定矩阵')\n print('定理28.6 对任意列满秩矩阵A,矩阵A\\'A是正定的')\n print('练习28.1-1 证明:如果A和B是n*n对称矩阵,则A+B和A-B也是对称的')\n print('练习28.1-2 证明:(AB)\\'=B\\'A\\',而且AA\\'总是一个对称矩阵')\n print('练习28.1-3 证明:矩阵的逆是唯一的,即如果B和C都是A的逆矩阵,则B=C')\n print('练习28.1-4 证明:两个下三角矩阵的乘积仍然是一个下三角矩阵.',\n '证明:一个下三角(或者上三角矩阵)矩阵的行列式的值是其对角线上的元素之积',\n '证明:一个下三角矩阵如果存在逆矩阵,则逆矩阵也是一个下三角矩阵')\n print('练习28.1-5 证明:如果P是一个n*n置换矩阵,A是一个n*n矩阵,则可以把A的各行进行置换得到PA',\n '而把A的各列进行置换可得到AP。证明:两个置换矩阵的乘积仍然是一个置换矩阵',\n '证明:如果P是一个置换矩阵,则P是可逆矩阵,其逆矩阵是P^T,且P^T也是一个置换矩阵')\n print('练习28.1-6 设A和B是n*n矩阵,且有AB=I.证明:如果把A的第j行加到第i行而得到A‘',\n '则可以通过把B的第j列减去第i列而获得A’的逆矩阵B‘')\n print('练习28.1-7 设A是一个非奇异的n*n复数矩阵.证明:当且仅当A的每个元素都是实数时,',\n 'A-1的每个元素都是实数')\n print('练习28.1-8 证明:如果A是一个n*n阶非奇异的对称矩阵,则A-1也是一个对称矩阵.',\n '证明:如果B是一个任意的m*n矩阵,则由乘积BAB^T给出的m*m矩阵是对称的')\n print('练习28.1-9 证明定理28.2。亦即,证明如果矩阵A为列满秩当且仅当若Ax=0,则说明x=0')\n print('练习28.1-10 证明:对任意两个相容矩阵A和B,rank(AB)<=min(rank(A),rank(B))',\n '其中等号仅当A或B是非奇异方阵时成立.(利用矩阵秩的另一种等价定义)')\n print('练习28.1-11 已知数x0,x1,...,xn-1,证明范德蒙德(Vandermonde)矩阵的行列式表达式')\n # python src/chapter28/chapter28note.py\n # python3 src/chapter28/chapter28note.py\n\nclass Chapter28_2:\n \"\"\"\n chapter28.2 note and function\n \"\"\"\n\n def __init__(self):\n pass\n\n def note(self):\n '''\n Summary\n ====\n Print chapter28.2 note\n\n Example\n ====\n ```python\n Chapter28_2().note()\n ```\n '''\n print('chapter28.2 note as follow') \n print('28.2 矩阵乘法的Strassen算法')\n print('两个n*n矩阵乘积的著名的Strassen递归算法,其运行时间为Θ(n^lg7)=Θ(n^2.81)')\n print('对足够大的n,该算法在性能上超过了在25.1节中介绍的运行时间为Θ(n^3)的简易矩阵乘法算法MATRIX-MULTIPLY')\n print('算法概述')\n print(' Strassen算法可以看作是熟知的一种设计技巧--分治法的一种应用')\n print(' 假设希望计算乘积C=AB,其中A、B和C都是n*n方阵.假定n是2的幂,把A、B和C都划分为四个n/2*n/2矩阵')\n print(' 然后作分块矩阵乘法,可以得到递归式T(n)=8T(n/2)+Θ(n^2),但是T(n)=Θ(n^3)')\n print('Strassen发现了另外一种不同的递归方法,该方法只需要执行7次递归的n/2*n/2的矩阵乘法运算和Θ(n^2)次标量加法与减法运算')\n print('从而可以得到递归式T(n)=7T(n/2)+Θ(n^2),但是T(n)=Θ(n^2.81)')\n print('Strassen方法分为以下四个步骤')\n print(' 1) 把输入矩阵A和B划分为n/2*n/2的子矩阵')\n print(' 2) 运用Θ(n^2)次标量加法与减法运算,计算出14个n/2*n/2的矩阵A1,B1,A2,B2,...,A7,B7')\n print(' 3) 递归计算出7个矩阵的乘积Pi=AiBi,i=1,2,...,7')\n print(' 4) 仅使用Θ(n^2)次标量加法与减法运算,对Pi矩阵的各种组合进行求和或求差运算,',\n '从而获得结果矩阵C的四个子矩阵r,s,t,u')\n print('从实用的观点看,Strassen方法通常不是矩阵乘法所选择的方法')\n print(' 1) 在Strassen算法的运行时间中,隐含的常数因子比简单的Θ(n^3)方法中的常数因子要大')\n print(' 2) 当矩阵是稀疏的时候,为系数矩阵设计的方法更快')\n print(' 3) Strassen算法不像简单方法那样具有数值稳定性')\n print(' 4) 在递归层次中生成的子矩阵要消耗空间')\n # ! Strassen方法的关键就是对矩阵乘法作分治递归\n print('练习28.2-1 运用Strassen算法计算矩阵的乘积')\n print('矩阵的乘积为:')\n print(np.matrix([[1, 3], [5, 7]]) * np.matrix([[8, 4], [6, 2]]))\n print('练习28.2-2 如果n不是2的整数幂,应该如何修改Strassen算法,求出两个n*n矩阵的乘积',\n '证明修改后的算法的运行时间为Θ(n^lg7)')\n print('练习28.2-3 如果使用k次乘法(假定乘法不满足交换律)就能计算出两个3*3矩阵的乘积',\n '就能在o(n^lg7)时间内计算出两个n*n矩阵的乘积,满足上述条件的最大的k值是多少')\n print('练习28.2-4 V.Pan发现了一种使用132464次乘法的求68*68矩阵乘积的方法',\n '一种使用143640次乘法的求70*70矩阵乘积的方法',\n '一种使用155424次乘法的求72*72矩阵乘积的方法')\n print('练习28.2-5 用Strassen算法算法作为子程序,能在多长时间内计算出一个kn*n矩阵与一个n*kn矩阵的乘积')\n print('练习28.2-6 说明如何仅用三次实数乘法运算,就可以计复数a+bi与c+di的乘积.该算法应该把a,b,c和d作为输入,',\n '并分别生成实部ac-bd和虚部ad+bc的值') \n # python src/chapter28/chapter28note.py\n # python3 src/chapter28/chapter28note.py\n\nclass Chapter28_3:\n \"\"\"\n chapter28.3 note and function\n \"\"\"\n\n def __init__(self):\n pass\n\n def note(self):\n '''\n Summary\n ====\n Print chapter28.3 note\n\n Example\n ====\n ```python\n Chapter28_3().note()\n ```\n '''\n print('chapter28.3 note as follow') \n print('28.3 求解线性方程组')\n print('对一组同时成立的线性方程组Ax=b求解时很多应用中都会出现的基本问题。一个线性系统可以表述为一个矩阵方程',\n '其中每个矩阵或者向量元素都属于一个域,如果实数域R')\n print('LUP分解求解线性方程组')\n print('LUP分解的思想就是找出三个n*n矩阵L,U和P,满足PA=LU')\n print(' 其中L是一个单位下三角矩阵,U是一个上三角矩阵,P是一个置换矩阵')\n print('每一个非奇异矩阵A都有这样一种分解')\n print('对矩阵A进行LUP分解的优点是当相应矩阵为三角矩阵(如矩阵L和U),更容易求解线性系统')\n print('在计算出A的LUP分解后,就可以用如下方式对三角线性系统进行求解,也就获得了Ax=b的解')\n print('对Ax=b的两边同时乘以P,就得到等价的方程组PAx=Pb,得到LUx=Pb')\n print('正向替换与逆向替换')\n print(' 如果已知L,P和b,用正向替换可以在Θ(n^2)的时间内求解下三角线性系统',\n '用一个数组pi[1..n]来表示置换P')\n print('LU分解的计算')\n print(' 把执行LU分解的过程称为高斯消元法.先从其他方程中减去第一个方程的倍数',\n '以便把那些方程中的第一个变量消去')\n print(' 继续上述过程,直至系统变为一个上三角矩阵形式,这个矩阵都是U.矩阵L是由使得变量被消去的行的乘数所组成')\n print('LUP分解的计算')\n print(' 一般情况下,为了求线性方程组Ax=b的解,必须在A的非对角线元素中选主元以避免除数为0',\n '除数不仅不能为0,也不能很小(即使A是非奇异的),否则就会在计算中导致数值不稳定.因此,所选的主元必须是一个较大的值')\n print(' LUP分解的数学基础与LU分解相似。已知一个n*n非奇异矩阵A,并希望计算出一个置换矩阵P,一个单位下三角矩阵L和一个上三角矩阵U,并满足条件PA=LU')\n print('练习28.3-1 运用正向替换法求解下列方程组')\n print('练习28.3-2 求出下列矩阵的LU分解')\n print('练习28.3-3 运用LUP分解来求解下列方程组')\n print('练习28.3-4 试描述一个对角矩阵的LUP分解')\n print('练习28.3-5 试描述一个置换矩阵A的LUP分解,并证明它是唯一的')\n print('练习28.3-6 证明:对所有n>=1,存在具有LU分解的奇异的n*n矩阵')\n print('练习28.3-7 在LU-DECOMPOSITION中,当k=n时是否有必要执行最外层的for循环迭代?',\n '在LUP-DECOMPOSITION中的情况又是怎样?')\n # python src/chapter28/chapter28note.py\n # python3 src/chapter28/chapter28note.py\n\nclass Chapter28_4:\n \"\"\"\n chapter28.4 note and function\n \"\"\"\n def note(self):\n \"\"\"\n Summary\n ====\n Print chapter28.4 note\n\n Example\n ====\n ```python\n Chapter28_4().note()\n ```\n \"\"\"\n print('chapter28.4 note as follow') \n print('28.4 矩阵求逆')\n print('在实际应用中,一般并不使用逆矩阵来求解线性方程组的解,而是运用一些更具数值稳定性的技术,如LUP分解求解线性方程组')\n print('但是,有时仍然需要计算一个矩阵的逆矩阵.可以利用LUP分解来计算逆矩阵')\n print('此外,还将证明矩阵乘法和计算逆矩阵问题是具有相同难度的两个问题,即(在技术条件限制下)可以使用一个算法在相同渐进时间内解决另外一个问题')\n print('可以使用Strassen矩阵乘法算法来求一个矩阵的逆')\n print('确实,正是由于要证明可以用比通常的办法更快的算法来求解线性方程组,才推动了最初的Strassen算法的产生')\n print('根据LUP分解计算逆矩阵')\n print(' 假设有一个矩阵A的LUP分解,包括三个矩阵L,U,P,并满足PA=LU')\n print(' 如果运用LU-SOLVE,则可以在Θ(n^2)的运行时间内,求出形如Ax=b的线性系统的解')\n print(' 由于LUP分解仅取决于A而不取决于b,所以就能够再用Θ(n^2)的运行时间,求出形如Ax=b\\'的另一个线性方程组的解')\n print(' 一般地,一旦得到了A的LUP分解,就可以在Θ(kn^2)的运行时间内,求出k个形如Ax=b的线性方程组的解,这k个方程组只有b不相同')\n print('矩阵乘法与逆矩阵')\n print(' 对矩阵乘法可以获得理论上的加速,可以相应地加速求逆矩阵的运算')\n print(' 从下面的意义上说,求逆矩阵运算等价于矩阵乘法运算',\n '如果M(n)表示求两个n*n矩阵乘积所需要的时间,则有在O(M(n))时间内对一个n*n矩阵求逆的方法',\n '如果I(n)表示对一个非奇异的n*n矩阵求逆所需的时间,则有在O(I(n))时间内对两个n*n矩阵相乘的方法')\n print('定理28.7 (矩阵乘法不比求逆矩阵困难) 如果能在I(n)时间内求出一个n*n矩阵的逆矩阵',\n '其中I(n)=Ω(n^2)且满足正则条件I(3n)=O(I(n))时间内求出两个n*n矩阵的乘积')\n print('定理28.8 (求逆矩阵运算并不比矩阵乘法运算更困难) 如果能在M(n)的时间内计算出两个n*n实矩阵的乘积',\n '其中M(n)=Ω(n^2)且M(n)满足两个正则条件:对任意的0<=k<=n有M(n+k)=O(M(n)),以及对某个常数c<1/2有M(n/2)<=cM(n)',\n '则可以在O(M(n))时间内求出任何一个n*n非奇异实矩阵的逆矩阵')\n print('练习28.4-1 设M(n)是求n*n矩阵的乘积所需的时间,S(n)表示求n*n矩阵的平方所需时间',\n '证明:求矩阵乘积运算与求矩阵平方运算实质上难度相同:一个M(n)时间的矩阵相乘算法蕴含着一个O(M(n))时间的矩阵平方算法,',\n '一个S(n)时间的矩阵平方算法蕴含着一个O(S(n))时间的矩阵相乘算法')\n print('练习28.4-2 设M(n)是求n*n矩阵乘积所需的时间,L(n)为计算一个n*n矩阵的LUP分解所需要的时间',\n '证明:求矩阵乘积运算与计算矩阵LUP分解实质上难度相同:一个M(n)时间的矩阵相乘算法蕴含着一个O(M(n))时间的矩阵LUP分解算法',\n '一个L(n)时间的矩阵LUP分解算法蕴含着一个O(L(n))时间的矩阵相乘算法')\n print('练习28.4-3 设M(n)是求n*n矩阵的乘积所需的时间,D(n)表示求n*n矩阵的行列式的值所需要的时间',\n '证明:求矩阵乘积运算与求行列式的值实质上难度相同:一个M(n)时间的矩阵相乘算法蕴含着一个O(M(n))时间的行列式算法',\n '一个D(n)时间的行列式算法蕴含着一个O(D(n)时间的矩阵相乘算法')\n print('练习28.4-4 设M(n)是求n*n布尔矩阵的乘积所需的时间,T(n)为找出n*n布尔矩阵的传递闭包所需要的时间',\n '证明:一个M(n)时间的布尔矩阵相乘算法蕴含着一个O(M(n)lgn)时间的传递闭包算法,一个T(n)时间的传递闭包算法蕴含着一个O(T(n))时间的布尔矩阵相乘算法')\n print('练习28.4-5 当矩阵元素属于整数模2所构成的域时,基于定理28.8的求逆矩阵算法的是否能够运行?')\n print('练习28.4-6 推广基于定理28.8的求逆矩阵算法,使之能处理复矩阵的情形,并证明所给出的推广方法是正确的')\n print(' 提示:用A的共轭转置矩阵A*来代替A的转置矩阵A^T,把A^T中的每个元素用其共轭复数代替就得到A*,也就是Hermitian转置')\n # python src/chapter28/chapter28note.py\n # python3 src/chapter28/chapter28note.py\n\nclass Chapter28_5:\n \"\"\"\n chapter28.5 note and function\n \"\"\"\n def note(self):\n \"\"\"\n Summary\n ====\n Print chapter28.5 note\n\n Example\n ====\n ```python\n Chapter28_5().note()\n ```\n \"\"\"\n print('chapter28.5 note as follow') \n print('28.5 对称正定矩阵与最小二乘逼近') \n print('对称正定矩阵有许多有趣而很理想的性质。例如,它们都是非奇异矩阵,并且可以对其进行LU分解而无需担心出现除数为0的情况')\n print('引理28.9 任意对称矩阵都是非奇异矩阵')\n print('引理28.10 如果A是一个对称正定矩阵,则A的每一个主子式都是对称正定的')\n print('设A是一个对称正定矩阵,Ak是A的k*k主子式,矩阵A关于Ak的Schur补定义为S=C-BAk^-1B^T')\n print('引理28.11 (Schur补定理) 如果A是一个对称正定矩阵,Ak是A的k*k主子式.则A关于Ak的Schur补也是对称正定的')\n print('推论28.12 对一个对称正定矩阵进行LU分解不会出现除数为0的情形')\n print('最小二乘逼近')\n print('对给定一组数据的点进行曲线拟合是对称正定矩阵的一个重要应用,假定给定m个数据点(x1,y1),(x2,y2),...,(xm,ym)',\n '其中已知yi受到测量误差的影响。希望找出一个函数F(x),满足对i=1,2,...,m,有yi=F(xi)+qi')\n print('其中近似误差qi是很小的,函数F(x)的形式依赖于所遇到的问题,在此,假定它的形式为线性加权和F(x)=∑cifi(x)')\n print('其中和项的个数和特定的基函数fi取决于对问题的了解,一种选择是fi(x)=x^j-1,这说明F(x)是一个x的n-1次多项式')\n print('这样一个高次函数F尽管容易处理数据,但也容易对数据产生干扰,并且一般在对未预见到的x预测其相应的y值时,其精确性也是很差的')\n print('为了使逼近误差最小,选定使误差向量q的范数最小,就得到一个最小二乘解')\n print('统计学中正态方程A^TAc=A^Ty')\n print('伪逆矩阵A+=(A^TA)^-1A^T')\n print('练习28.5-1 证明:对称正定矩阵的对角线上每一个元素都是正值')\n print('练习28.5-2 设A=[[a,b],[b,c]]是一个2*2对称正定矩阵,证明其行列式的值ac-b^2是正的')\n print('练习28.5-3 证明:一个对称正定矩阵中值最大的元素处于其对角线上')\n print('练习28.5-4 证明:一个对称正定矩阵的每一个主子式的行列式的值都是正的')\n print('练习28.5-5 设Ak表示对称正定矩阵A的第k个主子式。证明在LU分解中,det(Ak)/det(Ak-1)是第k个主元,为方便起见,设det(A0)=1')\n print('练习28.5-6 最小二乘法求')\n print('练习28.5-7 证明:伪逆矩阵A+满足下列四个等式:')\n print(' AA^+A=A')\n print(' A^+AA^+=A^+')\n print(' (AA^+)^T=AA^+')\n print(' (A^+A)^T=A^+A')\n print('思考题28-1 三对角线性方程组')\n print(' 1) 证明:对任意的n*n对称正定的三对角矩阵和任意n维向量b,通过进行LU分解可以在O(n)的时间内求出方程Ax=b的解',\n '论证在最坏情况下,从渐进意义上看,基于求出A^-1的任何方法都要花费更多的时间')\n print(' 2) 证明:对任意的n*n对称正定的三对角矩阵和任意n维向量b,通过进行LUP分解,'<\n '可以在O(n)的时间内求出方程Ax=b的解')\n print('思考题28-2 三次样条插值')\n print(' 将一个曲线拟合为n个三次多项式组成')\n print(' 用自然三次样条可以在O(n)时间内对一组n+1个点-值对进行插值')\n # python src/chapter28/chapter28note.py\n # python3 src/chapter28/chapter28note.py\n\nchapter28_1 = Chapter28_1()\nchapter28_2 = Chapter28_2()\nchapter28_3 = Chapter28_3()\nchapter28_4 = Chapter28_4()\nchapter28_5 = Chapter28_5()\n\ndef printchapter28note():\n \"\"\"\n print chapter28 note.\n \"\"\"\n print('Run main : single chapter twenty-eight!')\n chapter28_1.note()\n chapter28_2.note()\n chapter28_3.note()\n chapter28_4.note()\n chapter28_5.note()\n\n# python src/chapter28/chapter28note.py\n# python3 src/chapter28/chapter28note.py\n\nif __name__ == '__main__': \n printchapter28note()\nelse:\n pass\n" ]
[ [ "numpy.matrix" ] ]
mkretsch327/causalnex
[ "036938ac7399c3030bb402d987de0c5befc80414" ]
[ "causalnex/structure/pytorch/notears.py" ]
[ "# Copyright 2019-2020 QuantumBlack Visual Analytics Limited\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# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND\n# NONINFRINGEMENT. IN NO EVENT WILL THE LICENSOR OR OTHER CONTRIBUTORS\n# BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN\n# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# The QuantumBlack Visual Analytics Limited (\"QuantumBlack\") name and logo\n# (either separately or in combination, \"QuantumBlack Trademarks\") are\n# trademarks of QuantumBlack. The License does not grant you any right or\n# license to the QuantumBlack Trademarks. You may not use the QuantumBlack\n# Trademarks or any confusingly similar mark as a trademark for your product,\n# or use the QuantumBlack Trademarks in any other manner that might cause\n# confusion in the marketplace, including but not limited to in advertising,\n# on websites, or on software.\n#\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nTools to learn a ``StructureModel`` which describes the conditional dependencies between variables in a dataset.\n\"\"\"\n\nimport logging\nfrom copy import deepcopy\nfrom typing import Dict, Iterable, List, Tuple, Union\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.utils import check_array\n\nfrom causalnex.structure.pytorch.core import NotearsMLP\nfrom causalnex.structure.pytorch.dist_type import DistTypeContinuous, dist_type_aliases\nfrom causalnex.structure.structuremodel import StructureModel\n\n__all__ = [\"from_numpy\", \"from_pandas\"]\n\n\n# pylint: disable=too-many-locals\n# pylint: disable=too-many-arguments\ndef from_numpy(\n X: np.ndarray,\n dist_type_schema: Dict[int, str] = None,\n lasso_beta: float = 0.0,\n ridge_beta: float = 0.0,\n use_bias: bool = False,\n hidden_layer_units: Iterable[int] = None,\n w_threshold: float = None,\n max_iter: int = 100,\n tabu_edges: List[Tuple[int, int]] = None,\n tabu_parent_nodes: List[int] = None,\n tabu_child_nodes: List[int] = None,\n **kwargs\n) -> StructureModel:\n \"\"\"\n Learn the `StructureModel`, the graph structure with lasso regularisation\n describing conditional dependencies between variables in data presented as a numpy array.\n\n Based on DAGs with NO TEARS.\n @inproceedings{zheng2018dags,\n author = {Zheng, Xun and Aragam, Bryon and Ravikumar, Pradeep and Xing, Eric P.},\n booktitle = {Advances in Neural Information Processing Systems},\n title = {{DAGs with NO TEARS: Continuous Optimization for Structure Learning}},\n year = {2018},\n codebase = {https://github.com/xunzheng/notears}\n }\n\n Args:\n X: 2d input data, axis=0 is data rows, axis=1 is data columns. Data must be row oriented.\n\n dist_type_schema: The dist type schema corresponding to the passed in data X.\n It maps the positional column in X to the string alias of a dist type.\n A list of alias names can be found in ``dist_type/__init__.py``.\n If None, assumes that all data in X is continuous.\n\n lasso_beta: Constant that multiplies the lasso term (l1 regularisation).\n NOTE when using nonlinearities, the l1 loss only applies to the dag_layer.\n\n use_bias: Whether to fit a bias parameter in the NOTEARS algorithm.\n\n ridge_beta: Constant that multiplies the ridge term (l2 regularisation).\n When using nonlinear layers use of this parameter is recommended.\n\n hidden_layer_units: An iterable where its length determine the number of layers used,\n and the numbers determine the number of nodes used for the layer in order.\n\n w_threshold: fixed threshold for absolute edge weights.\n\n max_iter: max number of dual ascent steps during optimisation.\n\n tabu_edges: list of edges(from, to) not to be included in the graph.\n\n tabu_parent_nodes: list of nodes banned from being a parent of any other nodes.\n\n tabu_child_nodes: list of nodes banned from being a child of any other nodes.\n\n **kwargs: additional arguments for NOTEARS MLP model\n\n Returns:\n StructureModel: a graph of conditional dependencies between data variables.\n\n Raises:\n ValueError: If X does not contain data.\n ValueError: If schema does not correspond to columns.\n \"\"\"\n # n examples, d properties\n if not X.size:\n raise ValueError(\"Input data X is empty, cannot learn any structure\")\n logging.info(\"Learning structure using 'NOTEARS' optimisation.\")\n # Check array for NaN or inf values\n check_array(X)\n\n if dist_type_schema is not None:\n\n # make sure that there is one provided key per column\n if set(range(X.shape[1])).symmetric_difference(set(dist_type_schema.keys())):\n raise ValueError(\n \"Difference indices and expected indices. Got {} schema\".format(\n dist_type_schema\n )\n )\n\n # if dist_type_schema is None, assume all columns are continuous, else ini\n dist_types = (\n [DistTypeContinuous(idx=idx) for idx in np.arange(X.shape[1])]\n if dist_type_schema is None\n else [\n dist_type_aliases[alias](idx=idx) for idx, alias in dist_type_schema.items()\n ]\n )\n\n _, d = X.shape\n\n # if None or empty, convert into a list with single item\n if hidden_layer_units is None:\n hidden_layer_units = [0]\n elif isinstance(hidden_layer_units, list) and not hidden_layer_units:\n hidden_layer_units = [0]\n\n # if no hidden layer units, still take 1 iteration step with bounds\n hidden_layer_bnds = hidden_layer_units[0] if hidden_layer_units[0] else 1\n\n # Flip i and j because Pytorch flattens the vector in another direction\n bnds = [\n (0, 0)\n if i == j\n else (0, 0)\n if tabu_edges is not None and (i, j) in tabu_edges\n else (0, 0)\n if tabu_parent_nodes is not None and i in tabu_parent_nodes\n else (0, 0)\n if tabu_child_nodes is not None and j in tabu_child_nodes\n else (None, None)\n for j in range(d)\n for _ in range(hidden_layer_bnds)\n for i in range(d)\n ]\n\n model = NotearsMLP(\n n_features=d,\n dist_types=dist_types,\n hidden_layer_units=hidden_layer_units,\n lasso_beta=lasso_beta,\n ridge_beta=ridge_beta,\n bounds=bnds,\n use_bias=use_bias,\n **kwargs\n )\n\n model.fit(X, max_iter=max_iter)\n sm = StructureModel(model.adj)\n if w_threshold:\n sm.remove_edges_below_threshold(w_threshold)\n\n mean_effect = model.adj_mean_effect\n # extract the mean effect and add as edge attribute\n for u, v, edge_dict in sm.edges.data(True):\n sm.add_edge(\n u,\n v,\n origin=\"learned\",\n weight=edge_dict[\"weight\"],\n mean_effect=mean_effect[u, v],\n )\n\n # set bias as node attribute\n bias = model.bias\n for node in sm.nodes():\n value = None\n if bias is not None:\n value = bias[node]\n sm.nodes[node][\"bias\"] = value\n\n for dist_type in dist_types:\n # attach each dist_type object to corresponding node\n sm.nodes[dist_type.idx][\"dist_type\"] = dist_type\n\n # preserve the structure_learner as a graph attribute\n sm.graph[\"structure_learner\"] = model\n\n return sm\n\n\n# pylint: disable=too-many-locals\n# pylint: disable=too-many-arguments\ndef from_pandas(\n X: pd.DataFrame,\n dist_type_schema: Dict[Union[str, int], str] = None,\n lasso_beta: float = 0.0,\n ridge_beta: float = 0.0,\n use_bias: bool = False,\n hidden_layer_units: Iterable[int] = None,\n max_iter: int = 100,\n w_threshold: float = None,\n tabu_edges: List[Tuple[str, str]] = None,\n tabu_parent_nodes: List[str] = None,\n tabu_child_nodes: List[str] = None,\n **kwargs\n) -> StructureModel:\n \"\"\"\n Learn the `StructureModel`, the graph structure describing conditional dependencies between variables\n in data presented as a pandas dataframe.\n\n The optimisation is to minimise a score function :math:`F(W)` over the graph's\n weighted adjacency matrix, :math:`W`, subject to the a constraint function :math:`h(W)`,\n where :math:`h(W) == 0` characterises an acyclic graph.\n :math:`h(W) > 0` is a continuous, differentiable function that encapsulated how acyclic the graph is\n (less == more acyclic).\n Full details of this approach to structure learning are provided in the publication:\n\n Based on DAGs with NO TEARS.\n @inproceedings{zheng2018dags,\n author = {Zheng, Xun and Aragam, Bryon and Ravikumar, Pradeep and Xing, Eric P.},\n booktitle = {Advances in Neural Information Processing Systems},\n title = {{DAGs with NO TEARS: Continuous Optimization for Structure Learning}},\n year = {2018},\n codebase = {https://github.com/xunzheng/notears}\n }\n\n Args:\n X: 2d input data, axis=0 is data rows, axis=1 is data columns. Data must be row oriented.\n\n dist_type_schema: The dist type schema corresponding to the passed in data X.\n It maps the pandas column name in X to the string alias of a dist type.\n A list of alias names can be found in ``dist_type/__init__.py``.\n If None, assumes that all data in X is continuous.\n\n lasso_beta: Constant that multiplies the lasso term (l1 regularisation).\n NOTE when using nonlinearities, the l1 loss only applies to the dag_layer.\n\n use_bias: Whether to fit a bias parameter in the NOTEARS algorithm.\n\n ridge_beta: Constant that multiplies the ridge term (l2 regularisation).\n When using nonlinear layers use of this parameter is recommended.\n\n hidden_layer_units: An iterable where its length determine the number of layers used,\n and the numbers determine the number of nodes used for the layer in order.\n\n w_threshold: fixed threshold for absolute edge weights.\n\n max_iter: max number of dual ascent steps during optimisation.\n\n tabu_edges: list of edges(from, to) not to be included in the graph.\n\n tabu_parent_nodes: list of nodes banned from being a parent of any other nodes.\n\n tabu_child_nodes: list of nodes banned from being a child of any other nodes.\n\n **kwargs: additional arguments for NOTEARS MLP model\n\n Returns:\n StructureModel: graph of conditional dependencies between data variables.\n\n Raises:\n ValueError: If X does not contain data.\n \"\"\"\n\n data = deepcopy(X)\n\n # if dist_type_schema is not None, convert dist_type_schema from cols to idx\n dist_type_schema = (\n dist_type_schema\n if dist_type_schema is None\n else {X.columns.get_loc(col): alias for col, alias in dist_type_schema.items()}\n )\n\n non_numeric_cols = data.select_dtypes(exclude=\"number\").columns\n\n if len(non_numeric_cols) > 0:\n raise ValueError(\n \"All columns must have numeric data. \"\n \"Consider mapping the following columns to int {non_numeric_cols}\".format(\n non_numeric_cols=non_numeric_cols\n )\n )\n\n col_idx = {c: i for i, c in enumerate(data.columns)}\n idx_col = {i: c for c, i in col_idx.items()}\n\n if tabu_edges:\n tabu_edges = [(col_idx[u], col_idx[v]) for u, v in tabu_edges]\n if tabu_parent_nodes:\n tabu_parent_nodes = [col_idx[n] for n in tabu_parent_nodes]\n if tabu_child_nodes:\n tabu_child_nodes = [col_idx[n] for n in tabu_child_nodes]\n\n g = from_numpy(\n X=data.values,\n dist_type_schema=dist_type_schema,\n lasso_beta=lasso_beta,\n ridge_beta=ridge_beta,\n use_bias=use_bias,\n hidden_layer_units=hidden_layer_units,\n w_threshold=w_threshold,\n max_iter=max_iter,\n tabu_edges=tabu_edges,\n tabu_parent_nodes=tabu_parent_nodes,\n tabu_child_nodes=tabu_child_nodes,\n **kwargs\n )\n\n sm = StructureModel()\n sm.add_nodes_from(data.columns)\n\n # recover the edge weights from g\n for u, v, edge_dict in g.edges.data(True):\n sm.add_edge(\n idx_col[u],\n idx_col[v],\n origin=\"learned\",\n weight=edge_dict[\"weight\"],\n mean_effect=edge_dict[\"mean_effect\"],\n )\n\n # retrieve all graphs attrs\n for key, val in g.graph.items():\n sm.graph[key] = val\n\n # recover the node biases from g\n for node in g.nodes(data=True):\n node_name = idx_col[node[0]]\n sm.nodes[node_name][\"bias\"] = node[1][\"bias\"]\n\n # recover and preseve the node dist_types\n for node in g.nodes(data=True):\n node_name = idx_col[node[0]]\n sm.nodes[node_name][\"dist_type\"] = node[1][\"dist_type\"]\n\n return sm\n" ]
[ [ "sklearn.utils.check_array", "numpy.arange" ] ]
LogAnalysisTeam/logparser
[ "85b68dcc50f53f7cfcf138eefa1e0e162094cdd8" ]
[ "logparser/SLCT/SLCT.py" ]
[ "\"\"\"\r\nDescription: This file implements a wrapper around the original SLCT code in C\r\nAuthor: LogPAI team\r\nLicense: MIT\r\n\"\"\"\r\nimport sys\r\nsys.path.append('../')\r\n\r\nimport hashlib\r\nimport pandas as pd\r\nimport re\r\nfrom datetime import datetime\r\nfrom ..logmatch import regexmatch\r\nimport subprocess\r\nimport os\r\n\r\nimport logging\r\nlogger = logging.getLogger(__name__)\r\n\r\nclass LogParser(object):\r\n def __init__(self, indir, outdir, log_format, support, para_j=True, saveLog=False, rex=[]):\r\n\r\n self.outdir = outdir\r\n self.log_format = log_format\r\n self.rex = rex\r\n self.para = {}\r\n self.para['dataPath'] = indir\r\n self.para['para_j'] = para_j\r\n self.para['savePath'] = outdir\r\n self.para['support'] = support\r\n self.para['saveLog'] = saveLog\r\n\r\n def parse(self, logname):\r\n self.para['dataName'] = logname\r\n SLCT(self.para, self.log_format, self.rex)\r\n\r\n\r\ndef SLCT(para, log_format, rex):\r\n startTime = datetime.now() # start timing\r\n logname = os.path.join(para['dataPath'], para['dataName'])\r\n logger.info(\"Parsing file: {}\".format(logname))\r\n\r\n # SLCT compilation\r\n if not os.path.isfile('../SLCT/slct'):\r\n try:\r\n logger.info('Compile SLCT...\\n>> gcc -o ../logparser/SLCT/slct -O2 ../logparser/SLCT/cslct.c')\r\n subprocess.check_output('gcc -o ../logparser/SLCT/slct -O2 ../logparser/SLCT/cslct.c', \r\n stderr=subprocess.STDOUT, shell=True)\r\n except:\r\n logger.info(\"Compile error! Please check GCC installed.\\n\")\r\n raise\r\n\r\n headers, regex = generate_logformat_regex(log_format)\r\n df_log = log_to_dataframe(logname, regex, headers, log_format)\r\n\r\n # Generate input file\r\n with open('slct_input.log', 'w') as fw:\r\n for line in df_log['Content']:\r\n if rex:\r\n for currentRex in rex:\r\n line = re.sub(currentRex, '<*>', line)\r\n fw.write(line + '\\n')\r\n\r\n # Run SLCT command\r\n SLCT_command = extract_command(para, \"slct_input.log\")\r\n try:\r\n logger.info (\"Run SLCT...\\n>> {}\".format(SLCT_command))\r\n subprocess.check_call(SLCT_command, shell=True)\r\n except:\r\n logger.info(\"SLCT executable is invalid! Please compile it using GCC.\\n\")\r\n raise\r\n\r\n # Collect and dump templates\r\n tempParameter = TempPara(path = \"./\", savePath=para['savePath'], logname=\"slct_input.log\")\r\n tempProcess(tempParameter)\r\n\r\n matcher = regexmatch.PatternMatch(outdir=para['savePath'], logformat=log_format)\r\n matched_df = matcher.match(logname, \"temp_templates.csv\")\r\n\r\n # sys.exit()\r\n os.remove(\"slct_input.log\")\r\n os.remove(\"slct_outliers.log\")\r\n os.remove(\"slct_templates.txt\")\r\n os.remove(\"temp_templates.csv\")\r\n\r\n for idx, line in matched_df.iterrows():\r\n if line['EventTemplate'] == \"None\":\r\n content = line['Content']\r\n matched_df.loc[idx, \"EventTemplate\"] = content\r\n matched_df.loc[idx, \"EventId\"] = hashlib.md5(content.encode('utf-8')).hexdigest()[0:8]\r\n\r\n occ_dict = dict(matched_df['EventTemplate'].value_counts())\r\n df_event = pd.DataFrame()\r\n df_event['EventTemplate'] = matched_df['EventTemplate'].unique()\r\n df_event['EventId'] = df_event['EventTemplate'].map(lambda x: hashlib.md5(x.encode('utf-8')).hexdigest()[0:8])\r\n df_event['Occurrences'] = df_event['EventTemplate'].map(occ_dict)\r\n\r\n df_event.to_csv(os.path.join(para['savePath'], para['dataName'] + \"_templates.csv\"), index=False, columns=[\"EventId\", \"EventTemplate\", \"Occurrences\"])\r\n matched_df.to_csv(os.path.join(para['savePath'], para['dataName'] + \"_structured.csv\"), index=False)\r\n logger.info('Parsing done. [Time: {!s}]'.format(datetime.now() - startTime))\r\n\r\ndef extract_command(para, logname):\r\n support = para['support']\r\n parajTF = para['para_j']\r\n input = ''\r\n\r\n if parajTF:\r\n input = '../logparser/SLCT/slct -j -o ' + 'slct_outliers.log -r -s ' + str(support) + ' ' + logname\r\n else:\r\n input = '../logparser/SLCT/slct -o ' + 'slct_outliers.log -r -s ' + str(support) + ' ' + logname\r\n return input\r\n\r\ndef log_to_dataframe(log_file, regex, headers, logformat):\r\n ''' Function to transform log file to dataframe '''\r\n log_messages = []\r\n linecount = 0\r\n with open(log_file, 'r') as fin:\r\n for line in fin.readlines():\r\n try:\r\n match = regex.search(line.strip())\r\n message = [match.group(header) for header in headers]\r\n log_messages.append(message)\r\n linecount += 1\r\n except Exception as e:\r\n pass\r\n logdf = pd.DataFrame(log_messages, columns=headers)\r\n logdf.insert(0, 'LineId', None)\r\n logdf['LineId'] = [i + 1 for i in range(linecount)]\r\n return logdf\r\n\r\ndef generate_logformat_regex(logformat):\r\n ''' \r\n Function to generate regular expression to split log messages\r\n '''\r\n headers = []\r\n splitters = re.split(r'(<[^<>]+>)', logformat)\r\n regex = ''\r\n for k in range(len(splitters)):\r\n if k % 2 == 0:\r\n splitter = re.sub(' +', '\\s+', splitters[k])\r\n regex += splitter\r\n else:\r\n header = splitters[k].strip('<').strip('>')\r\n regex += '(?P<%s>.*?)' % header\r\n headers.append(header)\r\n regex = re.compile('^' + regex + '$')\r\n return headers, regex\r\n\r\nclass TempPara:\r\n def __init__(self, path='./', logname='rawlog.log', savePath='./', templateName='slct_templates.txt', outlierName='slct_outliers.log'):\r\n self.path = path\r\n self.logname = logname\r\n self.savePath = savePath\r\n self.templateName = templateName\r\n self.outlierName = outlierName\r\n\r\ndef tempProcess(tempPara):\r\n logger.info('Dumping event templates...')\r\n if not os.path.exists(tempPara.savePath):\r\n os.makedirs(tempPara.savePath)\r\n\r\n #read the templates\r\n templates = []\r\n with open('./' + tempPara.templateName) as tl:\r\n for line in tl:\r\n templates.append([0, line.strip(), 0])\r\n\r\n pd.DataFrame(templates, columns=[\"EventId\",\"EventTemplate\",\"Occurrences\"]).to_csv(\"temp_templates.csv\", index=False)\r\n\r\n\r\n\r\ndef matchTempLog(templates, logs):\r\n len_temp = {}\r\n for tidx, temp in enumerate(templates):\r\n tempL = temp.split()\r\n templen = len(tempL)\r\n if templen not in len_temp:\r\n len_temp[templen] = [(tidx, tempL)]\r\n else:\r\n len_temp[templen].append((tidx, tempL))\r\n logid_groupid = []\r\n for idx, log in enumerate(logs):\r\n logL = log.split()\r\n logid = idx+1\r\n if len(logL) in len_temp:\r\n logid_groupid.append([idx + 1, get_groupid(logL, len_temp[len(logL)])])\r\n else:\r\n logid_groupid.append([idx+1, -1])\r\n\r\n return logid_groupid\r\n\r\ndef get_groupid(logL, tempLs):\r\n maxvalue = -1\r\n for templ in tempLs:\r\n starnum = 0\r\n shot = 0\r\n for idx, token in enumerate(logL):\r\n if token == templ[1][idx] or templ[1][idx].count(\"*\"):\r\n shot += 1\r\n if templ[1][idx].count(\"*\"):\r\n starnum += 1\r\n shot = shot - starnum\r\n if shot > maxvalue:\r\n maxvalue = shot\r\n groupid = templ[0]\r\n return groupid" ]
[ [ "pandas.DataFrame" ] ]