repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list | possible_versions
list |
---|---|---|---|---|---|
Kinpzz/RCRNet-Pytorch
|
[
"8d9f0fe0c7ad651db7578b2d96741de11036ef82"
] |
[
"libs/networks/resnet_dilation.py"
] |
[
"#!/usr/bin/env python\r\n# coding: utf-8\r\n#\r\n# This code is based on torchvison resnet\r\n# URL: https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py\r\n\r\nimport torch.nn as nn\r\nimport torch.utils.model_zoo as model_zoo\r\n\r\n\r\n__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',\r\n 'resnet152']\r\n\r\n\r\nmodel_urls = {\r\n 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',\r\n 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',\r\n 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',\r\n 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',\r\n 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',\r\n}\r\n\r\n\r\ndef conv3x3(in_planes, out_planes, stride=1, padding=1, dilation=1):\r\n \"\"\"3x3 convolution with padding\"\"\"\r\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\r\n padding=padding, dilation=dilation, bias=False)\r\n\r\n\r\ndef conv1x1(in_planes, out_planes, stride=1):\r\n \"\"\"1x1 convolution\"\"\"\r\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\r\n\r\n\r\nclass BasicBlock(nn.Module):\r\n expansion = 1\r\n\r\n def __init__(self, inplanes, planes, stride, dilation, downsample=None):\r\n super(BasicBlock, self).__init__()\r\n self.conv1 = conv3x3(inplanes, planes, stride)\r\n self.bn1 = nn.BatchNorm2d(planes)\r\n self.relu = nn.ReLU(inplace=True)\r\n self.conv2 = conv3x3(planes, planes, 1, dilation, dilation)\r\n self.bn2 = nn.BatchNorm2d(planes)\r\n self.downsample = downsample\r\n self.stride = stride\r\n\r\n def forward(self, x):\r\n residual = x\r\n\r\n out = self.conv1(x)\r\n out = self.bn1(out)\r\n out = self.relu(out)\r\n\r\n out = self.conv2(out)\r\n out = self.bn2(out)\r\n\r\n if self.downsample is not None:\r\n residual = self.downsample(x)\r\n\r\n out += residual\r\n out = self.relu(out)\r\n\r\n return out\r\n\r\n\r\nclass Bottleneck(nn.Module):\r\n expansion = 4\r\n\r\n def __init__(self, inplanes, planes, stride, dilation, downsample=None, expansion=4):\r\n super(Bottleneck, self).__init__()\r\n self.expansion = expansion\r\n self.conv1 = conv1x1(inplanes, planes)\r\n self.bn1 = nn.BatchNorm2d(planes)\r\n self.conv2 = conv3x3(planes, planes, stride, dilation, dilation)\r\n self.bn2 = nn.BatchNorm2d(planes)\r\n self.conv3 = conv1x1(planes, planes * self.expansion)\r\n self.bn3 = nn.BatchNorm2d(planes * self.expansion)\r\n self.relu = nn.ReLU(inplace=True)\r\n self.downsample = downsample\r\n self.stride = stride\r\n\r\n def forward(self, x):\r\n residual = x\r\n\r\n out = self.conv1(x)\r\n out = self.bn1(out)\r\n out = self.relu(out)\r\n\r\n out = self.conv2(out)\r\n out = self.bn2(out)\r\n out = self.relu(out)\r\n\r\n out = self.conv3(out)\r\n out = self.bn3(out)\r\n\r\n if self.downsample is not None:\r\n residual = self.downsample(x)\r\n\r\n out += residual\r\n out = self.relu(out)\r\n\r\n return out\r\n\r\n\r\nclass ResNet(nn.Module):\r\n\r\n def __init__(self, block, layers, output_stride, num_classes=1000, input_channels=3):\r\n super(ResNet, self).__init__()\r\n if output_stride == 8:\r\n stride = [1, 2, 1, 1]\r\n dilation = [1, 1, 2, 2]\r\n elif output_stride == 16:\r\n stride = [1, 2, 2, 1]\r\n dilation = [1, 1, 1, 2]\r\n\r\n self.inplanes = 64\r\n self.conv1 = nn.Conv2d(input_channels, 64, kernel_size=7, stride=2, padding=3,\r\n bias=False)\r\n self.bn1 = nn.BatchNorm2d(64)\r\n self.relu = nn.ReLU(inplace=True)\r\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\r\n self.layer1 = self._make_layer(block, 64, layers[0], stride=stride[0], dilation=dilation[0])\r\n self.layer2 = self._make_layer(block, 128, layers[1], stride=stride[1], dilation=dilation[1])\r\n self.layer3 = self._make_layer(block, 256, layers[2], stride=stride[2], dilation=dilation[2])\r\n self.layer4 = self._make_layer(block, 512, layers[3], stride=stride[3], dilation=dilation[3])\r\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\r\n self.fc = nn.Linear(512 * block.expansion, num_classes)\r\n\r\n for m in self.modules():\r\n if isinstance(m, nn.Conv2d):\r\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\r\n elif isinstance(m, nn.BatchNorm2d):\r\n nn.init.constant_(m.weight, 1)\r\n nn.init.constant_(m.bias, 0)\r\n\r\n def _make_layer(self, block, planes, blocks, stride, dilation):\r\n downsample = None\r\n if stride != 1 or self.inplanes != planes * block.expansion:\r\n downsample = nn.Sequential(\r\n conv1x1(self.inplanes, planes * block.expansion, stride),\r\n nn.BatchNorm2d(planes * block.expansion),\r\n )\r\n\r\n layers = []\r\n layers.append(block(self.inplanes, planes, stride, dilation, downsample))\r\n self.inplanes = planes * block.expansion\r\n for _ in range(1, blocks):\r\n layers.append(block(self.inplanes, planes, 1, dilation))\r\n\r\n return nn.Sequential(*layers)\r\n\r\n def forward(self, x):\r\n x = self.conv1(x)\r\n x = self.bn1(x)\r\n x = self.relu(x)\r\n x = self.maxpool(x)\r\n\r\n x = self.layer1(x)\r\n x = self.layer2(x)\r\n x = self.layer3(x)\r\n x = self.layer4(x)\r\n\r\n x = self.avgpool(x)\r\n x = x.view(x.size(0), -1)\r\n x = self.fc(x)\r\n\r\n return x\r\n\r\n\r\ndef resnet18(pretrained=False, **kwargs):\r\n \"\"\"Constructs a ResNet-18 model.\r\n Args:\r\n pretrained (bool): If True, returns a model pre-trained on ImageNet\r\n \"\"\"\r\n model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)\r\n if pretrained:\r\n model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))\r\n return model\r\n\r\n\r\ndef resnet34(pretrained=False, **kwargs):\r\n \"\"\"Constructs a ResNet-34 model.\r\n Args:\r\n pretrained (bool): If True, returns a model pre-trained on ImageNet\r\n \"\"\"\r\n model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)\r\n if pretrained:\r\n model.load_state_dict(model_zoo.load_url(model_urls['resnet34']))\r\n return model\r\n\r\n\r\ndef resnet50(pretrained=False, **kwargs):\r\n \"\"\"Constructs a ResNet-50 model.\r\n Args:\r\n pretrained (bool): If True, returns a model pre-trained on ImageNet\r\n \"\"\"\r\n model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)\r\n if pretrained:\r\n model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))\r\n return model\r\n\r\n\r\ndef resnet101(pretrained=False, **kwargs):\r\n \"\"\"Constructs a ResNet-101 model.\r\n Args:\r\n pretrained (bool): If True, returns a model pre-trained on ImageNet\r\n \"\"\"\r\n model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)\r\n if pretrained:\r\n model.load_state_dict(model_zoo.load_url(model_urls['resnet101']))\r\n return model\r\n\r\n\r\ndef resnet152(pretrained=False, **kwargs):\r\n \"\"\"Constructs a ResNet-152 model.\r\n Args:\r\n pretrained (bool): If True, returns a model pre-trained on ImageNet\r\n \"\"\"\r\n model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)\r\n if pretrained:\r\n model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))\r\n return model\r\n"
] |
[
[
"torch.nn.Sequential",
"torch.nn.init.constant_",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.nn.Linear",
"torch.nn.AdaptiveAvgPool2d",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.utils.model_zoo.load_url",
"torch.nn.init.kaiming_normal_"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
rjmendez/lifepo4_bms
|
[
"7561b50d3ff6551a65cf9d10c8f4bffeeb34db34"
] |
[
"plot_battery.py"
] |
[
"#!/usr/bin/env python\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport sys\nall_raw = open(sys.argv[1], 'r')\n# init empty lists\ncell0v = []\ncell1v = []\ncell2v = []\ncell3v = []\ntotalv = []\n# Process data into lists\nfor line in all_raw:\n if 'voltage cell 0: ' in line:\n try:\n cell0v.append(float(line.replace('voltage cell 0: ', '')[:-4]))\n except:\n print('Malformed data: ' + line)\n if 'voltage cell 1: ' in line:\n try:\n cell1v.append(float(line.replace('voltage cell 1: ', '')[:-4]))\n except:\n print('Malformed data: ' + line)\n if 'voltage cell 2: ' in line:\n try:\n cell2v.append(float(line.replace('voltage cell 2: ', '')[:-4]))\n except:\n print('Malformed data: ' + line)\n if 'voltage cell 3: ' in line:\n try:\n cell3v.append(float(line.replace('voltage cell 3: ', '')[:-4]))\n except:\n print('Malformed data: ' + line)\n if 'voltage total: ' in line:\n try:\n totalv.append(float(line.replace('voltage total: ', '')[:-4]))\n except:\n print('Malformed data: ' + line)\n# Write images\n# Total voltage of pack\nplt.figure(figsize=(15, 15))\nplt.tight_layout()\nplt.plot(totalv)\nplt.savefig(sys.argv[1]+'_total_voltage.png')\nplt.clf()\n# Cells\nplt.figure(figsize=(15, 15))\nplt.tight_layout()\nplt.plot(cell0v, color='blue')\nplt.plot(cell1v, color='red')\nplt.plot(cell2v, color='green')\nplt.plot(cell3v, color='cyan')\nplt.xlabel('C0 = blue C1 = red C2 = green C3 = cyan')\nplt.savefig(sys.argv[1]+'_cell_voltage.png')\n"
] |
[
[
"matplotlib.pyplot.tight_layout",
"matplotlib.use",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
CaptainEven/FairMOTVehicle
|
[
"1d9033bcab9723cc5be3d5d94a5ac3712e8e143e"
] |
[
"src/lib/trains/mot.py"
] |
[
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom lib.models.decode import mot_decode\nfrom lib.models.losses import FocalLoss\nfrom lib.models.losses import RegL1Loss, RegLoss, NormRegL1Loss, RegWeightedL1Loss\nfrom lib.models.utils import _sigmoid, _tranpose_and_gather_feat\nfrom lib.utils.post_process import ctdet_post_process\n\nfrom .base_trainer import BaseTrainer\n\n\n# 损失函数的定义\nclass MotLoss(torch.nn.Module):\n def __init__(self, opt):\n super(MotLoss, self).__init__()\n self.crit = torch.nn.MSELoss() if opt.mse_loss else FocalLoss()\n self.crit_reg = RegL1Loss() if opt.reg_loss == 'l1' else \\\n RegLoss() if opt.reg_loss == 'sl1' else None # L1 loss or smooth l1 loss\n self.crit_wh = torch.nn.L1Loss(reduction='sum') if opt.dense_wh else \\\n NormRegL1Loss() if opt.norm_wh else \\\n RegWeightedL1Loss() if opt.cat_spec_wh else self.crit_reg # box size loss\n\n self.opt = opt\n self.emb_dim = opt.reid_dim\n self.nID = opt.nID\n\n # 唯一包含可学习参数的层: 用于Re-ID的全连接层\n self.classifier = nn.Linear(self.emb_dim, self.nID) # 不同的track id分类最后一层FC:将特征转换到概率得分\n self.IDLoss = nn.CrossEntropyLoss(ignore_index=-1) # 不同的track id分类用交叉熵损失\n # self.TriLoss = TripletLoss()\n\n self.emb_scale = math.sqrt(2) * math.log(self.nID - 1)\n self.s_det = nn.Parameter(-1.85 * torch.ones(1)) # 检测的损失缩放系数\n self.s_id = nn.Parameter(-1.05 * torch.ones(1)) # track id分类的损失缩放系数\n\n def forward(self, outputs, batch):\n \"\"\"\n :param outputs:\n :param batch:\n :return:\n \"\"\"\n opt = self.opt\n hm_loss, wh_loss, off_loss, id_loss = 0.0, 0.0, 0.0, 0.0 # 初始化4个loss为0\n for s in range(opt.num_stacks):\n output = outputs[s]\n if not opt.mse_loss:\n output['hm'] = _sigmoid(output['hm'])\n\n # 计算heatmap loss\n hm_loss += self.crit(output['hm'], batch['hm']) / opt.num_stacks\n if opt.wh_weight > 0:\n if opt.dense_wh:\n mask_weight = batch['dense_wh_mask'].sum() + 1e-4\n wh_loss += (self.crit_wh(output['wh'] * batch['dense_wh_mask'],\n batch['dense_wh'] * batch['dense_wh_mask']) /\n mask_weight) / opt.num_stacks\n else: # 计算box尺寸的L1/Smooth L1 loss\n wh_loss += self.crit_reg(\n output['wh'], batch['reg_mask'],\n batch['ind'], batch['wh']) / opt.num_stacks\n\n if opt.reg_offset and opt.off_weight > 0: # 计算box中心坐标偏移的L1 loss\n off_loss += self.crit_reg(output['reg'], batch['reg_mask'],\n batch['ind'], batch['reg']) / opt.num_stacks\n\n # 检测目标id分类的交叉熵损失\n if opt.id_weight > 0:\n id_head = _tranpose_and_gather_feat(output['id'], batch['ind'])\n id_head = id_head[batch['reg_mask'] > 0].contiguous() # 只有有目标的像素才计算id loss\n id_head = self.emb_scale * F.normalize(id_head)\n id_target = batch['ids'][batch['reg_mask'] > 0] # 有目标的track id\n id_output = self.classifier.forward(id_head).contiguous() # 用于检测目标分类的最后一层是FC?\n id_loss += self.IDLoss(id_output, id_target)\n # id_loss += self.IDLoss(id_output, id_target) + self.TriLoss(id_head, id_target)\n\n # loss = opt.hm_weight * hm_loss + opt.wh_weight * wh_loss + opt.off_weight * off_loss + opt.id_weight * id_loss\n\n det_loss = opt.hm_weight * hm_loss \\\n + opt.wh_weight * wh_loss \\\n + opt.off_weight * off_loss\n\n loss = torch.exp(-self.s_det) * det_loss \\\n + torch.exp(-self.s_id) * id_loss \\\n + (self.s_det + self.s_id)\n loss *= 0.5\n # print(loss, hm_loss, wh_loss, off_loss, id_loss)\n\n loss_stats = {'loss': loss,\n 'hm_loss': hm_loss,\n 'wh_loss': wh_loss,\n 'off_loss': off_loss,\n 'id_loss': id_loss}\n return loss, loss_stats\n\n\n# 核心训练类\nclass MotTrainer(BaseTrainer):\n def __init__(self, opt, model, optimizer=None):\n super(MotTrainer, self).__init__(opt, model, optimizer=optimizer)\n\n def _get_losses(self, opt):\n loss_states = ['loss', 'hm_loss', 'wh_loss', 'off_loss', 'id_loss']\n loss = MotLoss(opt)\n return loss_states, loss\n\n def save_result(self, output, batch, results):\n reg = output['reg'] if self.opt.reg_offset else None\n dets = mot_decode(\n output['hm'], output['wh'], reg=reg,\n cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K)\n dets = dets.detach().cpu().numpy().reshape(1, -1, dets.shape[2])\n dets_out = ctdet_post_process(\n dets.copy(), batch['meta']['c'].cpu().numpy(),\n batch['meta']['s'].cpu().numpy(),\n output['hm'].shape[2], output['hm'].shape[3], output['hm'].shape[1])\n results[batch['meta']['img_id'].cpu().numpy()[0]] = dets_out[0]\n"
] |
[
[
"torch.nn.functional.normalize",
"torch.nn.CrossEntropyLoss",
"torch.ones",
"torch.exp",
"torch.nn.Linear",
"torch.nn.L1Loss",
"torch.nn.MSELoss"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ashley8jain/IITD-complaint-system-web
|
[
"21a94601cba710f558d1689b87cfc391a1541c9f",
"21a94601cba710f558d1689b87cfc391a1541c9f"
] |
[
"lib/python2.7/matplotlib/projections/polar.py",
"lib/python2.7/matplotlib/backends/backend_cocoaagg.py"
] |
[
"import math\nimport warnings\n\nimport numpy as np\n\nimport matplotlib\nrcParams = matplotlib.rcParams\nfrom matplotlib.axes import Axes\nimport matplotlib.axis as maxis\nfrom matplotlib import cbook\nfrom matplotlib import docstring\nfrom matplotlib.patches import Circle\nfrom matplotlib.path import Path\nfrom matplotlib.ticker import Formatter, Locator, FormatStrFormatter\nfrom matplotlib.transforms import Affine2D, Affine2DBase, Bbox, \\\n BboxTransformTo, IdentityTransform, Transform, TransformWrapper, \\\n ScaledTranslation, blended_transform_factory, BboxTransformToMaxOnly\nimport matplotlib.spines as mspines\n\nclass PolarAxes(Axes):\n \"\"\"\n A polar graph projection, where the input dimensions are *theta*, *r*.\n\n Theta starts pointing east and goes anti-clockwise.\n \"\"\"\n name = 'polar'\n\n class PolarTransform(Transform):\n \"\"\"\n The base polar transform. This handles projection *theta* and\n *r* into Cartesian coordinate space *x* and *y*, but does not\n perform the ultimate affine transformation into the correct\n position.\n \"\"\"\n input_dims = 2\n output_dims = 2\n is_separable = False\n\n def __init__(self, axis=None, use_rmin=True):\n Transform.__init__(self)\n self._axis = axis\n self._use_rmin = use_rmin\n\n def transform(self, tr):\n xy = np.empty(tr.shape, np.float_)\n if self._axis is not None:\n if self._use_rmin:\n rmin = self._axis.viewLim.ymin\n else:\n rmin = 0\n theta_offset = self._axis.get_theta_offset()\n theta_direction = self._axis.get_theta_direction()\n else:\n rmin = 0\n theta_offset = 0\n theta_direction = 1\n\n t = tr[:, 0:1]\n r = tr[:, 1:2]\n x = xy[:, 0:1]\n y = xy[:, 1:2]\n\n t *= theta_direction\n t += theta_offset\n\n if rmin != 0:\n r = r - rmin\n mask = r < 0\n x[:] = np.where(mask, np.nan, r * np.cos(t))\n y[:] = np.where(mask, np.nan, r * np.sin(t))\n else:\n x[:] = r * np.cos(t)\n y[:] = r * np.sin(t)\n\n return xy\n transform.__doc__ = Transform.transform.__doc__\n\n transform_non_affine = transform\n transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__\n\n def transform_path(self, path):\n vertices = path.vertices\n if len(vertices) == 2 and vertices[0, 0] == vertices[1, 0]:\n return Path(self.transform(vertices), path.codes)\n ipath = path.interpolated(path._interpolation_steps)\n return Path(self.transform(ipath.vertices), ipath.codes)\n transform_path.__doc__ = Transform.transform_path.__doc__\n\n transform_path_non_affine = transform_path\n transform_path_non_affine.__doc__ = Transform.transform_path_non_affine.__doc__\n\n def inverted(self):\n return PolarAxes.InvertedPolarTransform(self._axis, self._use_rmin)\n inverted.__doc__ = Transform.inverted.__doc__\n\n class PolarAffine(Affine2DBase):\n \"\"\"\n The affine part of the polar projection. Scales the output so\n that maximum radius rests on the edge of the axes circle.\n \"\"\"\n def __init__(self, scale_transform, limits):\n \"\"\"\n *limits* is the view limit of the data. The only part of\n its bounds that is used is ymax (for the radius maximum).\n The theta range is always fixed to (0, 2pi).\n \"\"\"\n Affine2DBase.__init__(self)\n self._scale_transform = scale_transform\n self._limits = limits\n self.set_children(scale_transform, limits)\n self._mtx = None\n\n def get_matrix(self):\n if self._invalid:\n limits_scaled = self._limits.transformed(self._scale_transform)\n yscale = limits_scaled.ymax - limits_scaled.ymin\n affine = Affine2D() \\\n .scale(0.5 / yscale) \\\n .translate(0.5, 0.5)\n self._mtx = affine.get_matrix()\n self._inverted = None\n self._invalid = 0\n return self._mtx\n get_matrix.__doc__ = Affine2DBase.get_matrix.__doc__\n\n class InvertedPolarTransform(Transform):\n \"\"\"\n The inverse of the polar transform, mapping Cartesian\n coordinate space *x* and *y* back to *theta* and *r*.\n \"\"\"\n input_dims = 2\n output_dims = 2\n is_separable = False\n\n def __init__(self, axis=None, use_rmin=True):\n Transform.__init__(self)\n self._axis = axis\n self._use_rmin = use_rmin\n\n def transform(self, xy):\n if self._axis is not None:\n if self._use_rmin:\n rmin = self._axis.viewLim.ymin\n else:\n rmin = 0\n theta_offset = self._axis.get_theta_offset()\n theta_direction = self._axis.get_theta_direction()\n else:\n rmin = 0\n theta_offset = 0\n theta_direction = 1\n\n x = xy[:, 0:1]\n y = xy[:, 1:]\n r = np.sqrt(x*x + y*y)\n theta = np.arccos(x / r)\n theta = np.where(y < 0, 2 * np.pi - theta, theta)\n\n theta -= theta_offset\n theta *= theta_direction\n\n r += rmin\n\n return np.concatenate((theta, r), 1)\n transform.__doc__ = Transform.transform.__doc__\n\n def inverted(self):\n return PolarAxes.PolarTransform(self._axis, self._use_rmin)\n inverted.__doc__ = Transform.inverted.__doc__\n\n class ThetaFormatter(Formatter):\n \"\"\"\n Used to format the *theta* tick labels. Converts the native\n unit of radians into degrees and adds a degree symbol.\n \"\"\"\n def __call__(self, x, pos=None):\n # \\u00b0 : degree symbol\n if rcParams['text.usetex'] and not rcParams['text.latex.unicode']:\n return r\"$%0.0f^\\circ$\" % ((x / np.pi) * 180.0)\n else:\n # we use unicode, rather than mathtext with \\circ, so\n # that it will work correctly with any arbitrary font\n # (assuming it has a degree sign), whereas $5\\circ$\n # will only work correctly with one of the supported\n # math fonts (Computer Modern and STIX)\n return u\"%0.0f\\u00b0\" % ((x / np.pi) * 180.0)\n\n class RadialLocator(Locator):\n \"\"\"\n Used to locate radius ticks.\n\n Ensures that all ticks are strictly positive. For all other\n tasks, it delegates to the base\n :class:`~matplotlib.ticker.Locator` (which may be different\n depending on the scale of the *r*-axis.\n \"\"\"\n def __init__(self, base):\n self.base = base\n\n def __call__(self):\n ticks = self.base()\n return [x for x in ticks if x > 0]\n\n def autoscale(self):\n return self.base.autoscale()\n\n def pan(self, numsteps):\n return self.base.pan(numsteps)\n\n def zoom(self, direction):\n return self.base.zoom(direction)\n\n def refresh(self):\n return self.base.refresh()\n\n def view_limits(self, vmin, vmax):\n vmin, vmax = self.base.view_limits(vmin, vmax)\n return 0, vmax\n\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Create a new Polar Axes for a polar plot.\n\n The following optional kwargs are supported:\n\n - *resolution*: The number of points of interpolation between\n each pair of data points. Set to 1 to disable\n interpolation.\n \"\"\"\n\n self.resolution = kwargs.pop('resolution', None)\n if self.resolution not in (None, 1):\n warnings.warn(\n \"\"\"The resolution kwarg to Polar plots is now ignored.\nIf you need to interpolate data points, consider running\ncbook.simple_linear_interpolation on the data before passing to matplotlib.\"\"\")\n Axes.__init__(self, *args, **kwargs)\n self.set_aspect('equal', adjustable='box', anchor='C')\n self.cla()\n __init__.__doc__ = Axes.__init__.__doc__\n\n def cla(self):\n Axes.cla(self)\n\n self.title.set_y(1.05)\n\n self.xaxis.set_major_formatter(self.ThetaFormatter())\n self.xaxis.isDefault_majfmt = True\n angles = np.arange(0.0, 360.0, 45.0)\n self.set_thetagrids(angles)\n self.yaxis.set_major_locator(self.RadialLocator(self.yaxis.get_major_locator()))\n\n self.grid(rcParams['polaraxes.grid'])\n self.xaxis.set_ticks_position('none')\n self.yaxis.set_ticks_position('none')\n self.yaxis.set_tick_params(label1On=True)\n # Why do we need to turn on yaxis tick labels, but\n # xaxis tick labels are already on?\n\n self.set_theta_offset(0)\n self.set_theta_direction(1)\n\n def _init_axis(self):\n \"move this out of __init__ because non-separable axes don't use it\"\n self.xaxis = maxis.XAxis(self)\n self.yaxis = maxis.YAxis(self)\n # Calling polar_axes.xaxis.cla() or polar_axes.xaxis.cla()\n # results in weird artifacts. Therefore we disable this for\n # now.\n # self.spines['polar'].register_axis(self.yaxis)\n self._update_transScale()\n\n def _set_lim_and_transforms(self):\n self.transAxes = BboxTransformTo(self.bbox)\n\n # Transforms the x and y axis separately by a scale factor\n # It is assumed that this part will have non-linear components\n self.transScale = TransformWrapper(IdentityTransform())\n\n # A (possibly non-linear) projection on the (already scaled)\n # data. This one is aware of rmin\n self.transProjection = self.PolarTransform(self)\n\n # This one is not aware of rmin\n self.transPureProjection = self.PolarTransform(self, use_rmin=False)\n\n # An affine transformation on the data, generally to limit the\n # range of the axes\n self.transProjectionAffine = self.PolarAffine(self.transScale, self.viewLim)\n\n # The complete data transformation stack -- from data all the\n # way to display coordinates\n self.transData = self.transScale + self.transProjection + \\\n (self.transProjectionAffine + self.transAxes)\n\n # This is the transform for theta-axis ticks. It is\n # equivalent to transData, except it always puts r == 1.0 at\n # the edge of the axis circle.\n self._xaxis_transform = (\n self.transPureProjection +\n self.PolarAffine(IdentityTransform(), Bbox.unit()) +\n self.transAxes)\n # The theta labels are moved from radius == 0.0 to radius == 1.1\n self._theta_label1_position = Affine2D().translate(0.0, 1.1)\n self._xaxis_text1_transform = (\n self._theta_label1_position +\n self._xaxis_transform)\n self._theta_label2_position = Affine2D().translate(0.0, 1.0 / 1.1)\n self._xaxis_text2_transform = (\n self._theta_label2_position +\n self._xaxis_transform)\n\n # This is the transform for r-axis ticks. It scales the theta\n # axis so the gridlines from 0.0 to 1.0, now go from 0.0 to\n # 2pi.\n self._yaxis_transform = (\n Affine2D().scale(np.pi * 2.0, 1.0) +\n self.transData)\n # The r-axis labels are put at an angle and padded in the r-direction\n self._r_label_position = ScaledTranslation(\n 22.5, 0.0, Affine2D())\n self._yaxis_text_transform = (\n self._r_label_position +\n Affine2D().scale(1.0 / 360.0, 1.0) +\n self._yaxis_transform\n )\n\n def get_xaxis_transform(self,which='grid'):\n assert which in ['tick1','tick2','grid']\n return self._xaxis_transform\n\n def get_xaxis_text1_transform(self, pad):\n return self._xaxis_text1_transform, 'center', 'center'\n\n def get_xaxis_text2_transform(self, pad):\n return self._xaxis_text2_transform, 'center', 'center'\n\n def get_yaxis_transform(self,which='grid'):\n assert which in ['tick1','tick2','grid']\n return self._yaxis_transform\n\n def get_yaxis_text1_transform(self, pad):\n angle = self._r_label_position.to_values()[4]\n if angle < 90.:\n return self._yaxis_text_transform, 'bottom', 'left'\n elif angle < 180.:\n return self._yaxis_text_transform, 'bottom', 'right'\n elif angle < 270.:\n return self._yaxis_text_transform, 'top', 'right'\n else:\n return self._yaxis_text_transform, 'top', 'left'\n\n def get_yaxis_text2_transform(self, pad):\n angle = self._r_label_position.to_values()[4]\n if angle < 90.:\n return self._yaxis_text_transform, 'top', 'right'\n elif angle < 180.:\n return self._yaxis_text_transform, 'top', 'left'\n elif angle < 270.:\n return self._yaxis_text_transform, 'bottom', 'left'\n else:\n return self._yaxis_text_transform, 'bottom', 'right'\n\n def _gen_axes_patch(self):\n return Circle((0.5, 0.5), 0.5)\n\n def _gen_axes_spines(self):\n return {'polar':mspines.Spine.circular_spine(self,\n (0.5, 0.5), 0.5)}\n\n def set_rmax(self, rmax):\n self.viewLim.y1 = rmax\n\n def get_rmax(self):\n return self.viewLim.ymax\n\n def set_rmin(self, rmin):\n self.viewLim.y0 = rmin\n\n def get_rmin(self):\n return self.viewLim.ymin\n\n def set_theta_offset(self, offset):\n \"\"\"\n Set the offset for the location of 0 in radians.\n \"\"\"\n self._theta_offset = offset\n\n def get_theta_offset(self):\n \"\"\"\n Get the offset for the location of 0 in radians.\n \"\"\"\n return self._theta_offset\n\n def set_theta_zero_location(self, loc):\n \"\"\"\n Sets the location of theta's zero. (Calls set_theta_offset\n with the correct value in radians under the hood.)\n\n May be one of \"N\", \"NW\", \"W\", \"SW\", \"S\", \"SE\", \"E\", or \"NE\".\n \"\"\"\n mapping = {\n 'N': np.pi * 0.5,\n 'NW': np.pi * 0.75,\n 'W': np.pi,\n 'SW': np.pi * 1.25,\n 'S': np.pi * 1.5,\n 'SE': np.pi * 1.75,\n 'E': 0,\n 'NE': np.pi * 0.25 }\n return self.set_theta_offset(mapping[loc])\n\n def set_theta_direction(self, direction):\n \"\"\"\n Set the direction in which theta increases.\n\n clockwise, -1:\n Theta increases in the clockwise direction\n\n counterclockwise, anticlockwise, 1:\n Theta increases in the counterclockwise direction\n \"\"\"\n if direction in ('clockwise',):\n self._direction = -1\n elif direction in ('counterclockwise', 'anticlockwise'):\n self._direction = 1\n elif direction in (1, -1):\n self._direction = direction\n else:\n raise ValueError(\"direction must be 1, -1, clockwise or counterclockwise\")\n\n def get_theta_direction(self):\n \"\"\"\n Get the direction in which theta increases.\n\n -1:\n Theta increases in the clockwise direction\n\n 1:\n Theta increases in the counterclockwise direction\n \"\"\"\n return self._direction\n\n def set_rlim(self, *args, **kwargs):\n if 'rmin' in kwargs:\n kwargs['ymin'] = kwargs.pop('rmin')\n if 'rmax' in kwargs:\n kwargs['ymax'] = kwargs.pop('rmax')\n return self.set_ylim(*args, **kwargs)\n\n def set_yscale(self, *args, **kwargs):\n Axes.set_yscale(self, *args, **kwargs)\n self.yaxis.set_major_locator(\n self.RadialLocator(self.yaxis.get_major_locator()))\n\n set_rscale = Axes.set_yscale\n set_rticks = Axes.set_yticks\n\n @docstring.dedent_interpd\n def set_thetagrids(self, angles, labels=None, frac=None, fmt=None,\n **kwargs):\n \"\"\"\n Set the angles at which to place the theta grids (these\n gridlines are equal along the theta dimension). *angles* is in\n degrees.\n\n *labels*, if not None, is a ``len(angles)`` list of strings of\n the labels to use at each angle.\n\n If *labels* is None, the labels will be ``fmt %% angle``\n\n *frac* is the fraction of the polar axes radius at which to\n place the label (1 is the edge). Eg. 1.05 is outside the axes\n and 0.95 is inside the axes.\n\n Return value is a list of tuples (*line*, *label*), where\n *line* is :class:`~matplotlib.lines.Line2D` instances and the\n *label* is :class:`~matplotlib.text.Text` instances.\n\n kwargs are optional text properties for the labels:\n\n %(Text)s\n\n ACCEPTS: sequence of floats\n \"\"\"\n angles = np.asarray(angles, np.float_)\n self.set_xticks(angles * (np.pi / 180.0))\n if labels is not None:\n self.set_xticklabels(labels)\n elif fmt is not None:\n self.xaxis.set_major_formatter(FormatStrFormatter(fmt))\n if frac is not None:\n self._theta_label1_position.clear().translate(0.0, frac)\n self._theta_label2_position.clear().translate(0.0, 1.0 / frac)\n for t in self.xaxis.get_ticklabels():\n t.update(kwargs)\n return self.xaxis.get_ticklines(), self.xaxis.get_ticklabels()\n\n @docstring.dedent_interpd\n def set_rgrids(self, radii, labels=None, angle=None, fmt=None,\n **kwargs):\n \"\"\"\n Set the radial locations and labels of the *r* grids.\n\n The labels will appear at radial distances *radii* at the\n given *angle* in degrees.\n\n *labels*, if not None, is a ``len(radii)`` list of strings of the\n labels to use at each radius.\n\n If *labels* is None, the built-in formatter will be used.\n\n Return value is a list of tuples (*line*, *label*), where\n *line* is :class:`~matplotlib.lines.Line2D` instances and the\n *label* is :class:`~matplotlib.text.Text` instances.\n\n kwargs are optional text properties for the labels:\n\n %(Text)s\n\n ACCEPTS: sequence of floats\n \"\"\"\n radii = np.asarray(radii)\n rmin = radii.min()\n if rmin <= 0:\n raise ValueError('radial grids must be strictly positive')\n\n self.set_yticks(radii)\n if labels is not None:\n self.set_yticklabels(labels)\n elif fmt is not None:\n self.yaxis.set_major_formatter(FormatStrFormatter(fmt))\n if angle is None:\n angle = self._r_label_position.to_values()[4]\n self._r_label_position._t = (angle, 0.0)\n self._r_label_position.invalidate()\n for t in self.yaxis.get_ticklabels():\n t.update(kwargs)\n return self.yaxis.get_gridlines(), self.yaxis.get_ticklabels()\n\n def set_xscale(self, scale, *args, **kwargs):\n if scale != 'linear':\n raise NotImplementedError(\"You can not set the xscale on a polar plot.\")\n\n def set_xlim(self, *args, **kargs):\n # The xlim is fixed, no matter what you do\n self.viewLim.intervalx = (0.0, np.pi * 2.0)\n\n def format_coord(self, theta, r):\n \"\"\"\n Return a format string formatting the coordinate using Unicode\n characters.\n \"\"\"\n theta /= math.pi\n # \\u03b8: lower-case theta\n # \\u03c0: lower-case pi\n # \\u00b0: degree symbol\n return u'\\u03b8=%0.3f\\u03c0 (%0.3f\\u00b0), r=%0.3f' % (theta, theta * 180.0, r)\n\n def get_data_ratio(self):\n '''\n Return the aspect ratio of the data itself. For a polar plot,\n this should always be 1.0\n '''\n return 1.0\n\n ### Interactive panning\n\n def can_zoom(self):\n \"\"\"\n Return *True* if this axes supports the zoom box button functionality.\n\n Polar axes do not support zoom boxes.\n \"\"\"\n return False\n\n def can_pan(self) :\n \"\"\"\n Return *True* if this axes supports the pan/zoom button functionality.\n\n For polar axes, this is slightly misleading. Both panning and\n zooming are performed by the same button. Panning is performed\n in azimuth while zooming is done along the radial.\n \"\"\"\n return True\n\n def start_pan(self, x, y, button):\n angle = np.deg2rad(self._r_label_position.to_values()[4])\n mode = ''\n if button == 1:\n epsilon = np.pi / 45.0\n t, r = self.transData.inverted().transform_point((x, y))\n if t >= angle - epsilon and t <= angle + epsilon:\n mode = 'drag_r_labels'\n elif button == 3:\n mode = 'zoom'\n\n self._pan_start = cbook.Bunch(\n rmax = self.get_rmax(),\n trans = self.transData.frozen(),\n trans_inverse = self.transData.inverted().frozen(),\n r_label_angle = self._r_label_position.to_values()[4],\n x = x,\n y = y,\n mode = mode\n )\n\n def end_pan(self):\n del self._pan_start\n\n def drag_pan(self, button, key, x, y):\n p = self._pan_start\n\n if p.mode == 'drag_r_labels':\n startt, startr = p.trans_inverse.transform_point((p.x, p.y))\n t, r = p.trans_inverse.transform_point((x, y))\n\n # Deal with theta\n dt0 = t - startt\n dt1 = startt - t\n if abs(dt1) < abs(dt0):\n dt = abs(dt1) * sign(dt0) * -1.0\n else:\n dt = dt0 * -1.0\n dt = (dt / np.pi) * 180.0\n\n self._r_label_position._t = (p.r_label_angle - dt, 0.0)\n self._r_label_position.invalidate()\n\n trans, vert1, horiz1 = self.get_yaxis_text1_transform(0.0)\n trans, vert2, horiz2 = self.get_yaxis_text2_transform(0.0)\n for t in self.yaxis.majorTicks + self.yaxis.minorTicks:\n t.label1.set_va(vert1)\n t.label1.set_ha(horiz1)\n t.label2.set_va(vert2)\n t.label2.set_ha(horiz2)\n\n elif p.mode == 'zoom':\n startt, startr = p.trans_inverse.transform_point((p.x, p.y))\n t, r = p.trans_inverse.transform_point((x, y))\n\n dr = r - startr\n\n # Deal with r\n scale = r / startr\n self.set_rmax(p.rmax / scale)\n\n# These are a couple of aborted attempts to project a polar plot using\n# cubic bezier curves.\n\n# def transform_path(self, path):\n# twopi = 2.0 * np.pi\n# halfpi = 0.5 * np.pi\n\n# vertices = path.vertices\n# t0 = vertices[0:-1, 0]\n# t1 = vertices[1: , 0]\n# td = np.where(t1 > t0, t1 - t0, twopi - (t0 - t1))\n# maxtd = td.max()\n# interpolate = np.ceil(maxtd / halfpi)\n# if interpolate > 1.0:\n# vertices = self.interpolate(vertices, interpolate)\n\n# vertices = self.transform(vertices)\n\n# result = np.zeros((len(vertices) * 3 - 2, 2), np.float_)\n# codes = mpath.Path.CURVE4 * np.ones((len(vertices) * 3 - 2, ), mpath.Path.code_type)\n# result[0] = vertices[0]\n# codes[0] = mpath.Path.MOVETO\n\n# kappa = 4.0 * ((np.sqrt(2.0) - 1.0) / 3.0)\n# kappa = 0.5\n\n# p0 = vertices[0:-1]\n# p1 = vertices[1: ]\n\n# x0 = p0[:, 0:1]\n# y0 = p0[:, 1: ]\n# b0 = ((y0 - x0) - y0) / ((x0 + y0) - x0)\n# a0 = y0 - b0*x0\n\n# x1 = p1[:, 0:1]\n# y1 = p1[:, 1: ]\n# b1 = ((y1 - x1) - y1) / ((x1 + y1) - x1)\n# a1 = y1 - b1*x1\n\n# x = -(a0-a1) / (b0-b1)\n# y = a0 + b0*x\n\n# xk = (x - x0) * kappa + x0\n# yk = (y - y0) * kappa + y0\n\n# result[1::3, 0:1] = xk\n# result[1::3, 1: ] = yk\n\n# xk = (x - x1) * kappa + x1\n# yk = (y - y1) * kappa + y1\n\n# result[2::3, 0:1] = xk\n# result[2::3, 1: ] = yk\n\n# result[3::3] = p1\n\n# print vertices[-2:]\n# print result[-2:]\n\n# return mpath.Path(result, codes)\n\n# twopi = 2.0 * np.pi\n# halfpi = 0.5 * np.pi\n\n# vertices = path.vertices\n# t0 = vertices[0:-1, 0]\n# t1 = vertices[1: , 0]\n# td = np.where(t1 > t0, t1 - t0, twopi - (t0 - t1))\n# maxtd = td.max()\n# interpolate = np.ceil(maxtd / halfpi)\n\n# print \"interpolate\", interpolate\n# if interpolate > 1.0:\n# vertices = self.interpolate(vertices, interpolate)\n\n# result = np.zeros((len(vertices) * 3 - 2, 2), np.float_)\n# codes = mpath.Path.CURVE4 * np.ones((len(vertices) * 3 - 2, ), mpath.Path.code_type)\n# result[0] = vertices[0]\n# codes[0] = mpath.Path.MOVETO\n\n# kappa = 4.0 * ((np.sqrt(2.0) - 1.0) / 3.0)\n# tkappa = np.arctan(kappa)\n# hyp_kappa = np.sqrt(kappa*kappa + 1.0)\n\n# t0 = vertices[0:-1, 0]\n# t1 = vertices[1: , 0]\n# r0 = vertices[0:-1, 1]\n# r1 = vertices[1: , 1]\n\n# td = np.where(t1 > t0, t1 - t0, twopi - (t0 - t1))\n# td_scaled = td / (np.pi * 0.5)\n# rd = r1 - r0\n# r0kappa = r0 * kappa * td_scaled\n# r1kappa = r1 * kappa * td_scaled\n# ravg_kappa = ((r1 + r0) / 2.0) * kappa * td_scaled\n\n# result[1::3, 0] = t0 + (tkappa * td_scaled)\n# result[1::3, 1] = r0*hyp_kappa\n# # result[1::3, 1] = r0 / np.cos(tkappa * td_scaled) # np.sqrt(r0*r0 + ravg_kappa*ravg_kappa)\n\n# result[2::3, 0] = t1 - (tkappa * td_scaled)\n# result[2::3, 1] = r1*hyp_kappa\n# # result[2::3, 1] = r1 / np.cos(tkappa * td_scaled) # np.sqrt(r1*r1 + ravg_kappa*ravg_kappa)\n\n# result[3::3, 0] = t1\n# result[3::3, 1] = r1\n\n# print vertices[:6], result[:6], t0[:6], t1[:6], td[:6], td_scaled[:6], tkappa\n# result = self.transform(result)\n# return mpath.Path(result, codes)\n# transform_path_non_affine = transform_path\n\n",
"from __future__ import division\n\"\"\"\n backend_cocoaagg.py\n\n A native Cocoa backend via PyObjC in OSX.\n\n Author: Charles Moad ([email protected])\n\n Notes:\n - Requires PyObjC (currently testing v1.3.7)\n - The Tk backend works nicely on OSX. This code\n primarily serves as an example of embedding a\n matplotlib rendering context into a cocoa app\n using a NSImageView.\n\"\"\"\n\nimport os, sys\n\ntry:\n import objc\nexcept ImportError:\n raise ImportError('The CococaAgg backend required PyObjC to be installed!')\n\nfrom Foundation import *\nfrom AppKit import *\nfrom PyObjCTools import NibClassBuilder, AppHelper\n\nimport matplotlib\nfrom matplotlib.figure import Figure\nfrom matplotlib.backend_bases import FigureManagerBase, FigureCanvasBase\nfrom matplotlib.backend_bases import ShowBase\n\nfrom backend_agg import FigureCanvasAgg\nfrom matplotlib._pylab_helpers import Gcf\n\nmplBundle = NSBundle.bundleWithPath_(os.path.dirname(__file__))\n\ndef new_figure_manager(num, *args, **kwargs):\n FigureClass = kwargs.pop('FigureClass', Figure)\n thisFig = FigureClass( *args, **kwargs )\n canvas = FigureCanvasCocoaAgg(thisFig)\n return FigureManagerCocoaAgg(canvas, num)\n\n## Below is the original show() function:\n#def show():\n# for manager in Gcf.get_all_fig_managers():\n# manager.show()\n#\n## It appears that this backend is unusual in having a separate\n## run function invoked for each figure, instead of a single\n## mainloop. Presumably there is no blocking at all.\n##\n## Using the Show class below should cause no difference in\n## behavior.\n\nclass Show(ShowBase):\n def mainloop(self):\n pass\n\nshow = Show()\n\ndef draw_if_interactive():\n if matplotlib.is_interactive():\n figManager = Gcf.get_active()\n if figManager is not None:\n figManager.show()\n\nclass FigureCanvasCocoaAgg(FigureCanvasAgg):\n def draw(self):\n FigureCanvasAgg.draw(self)\n\n def blit(self, bbox):\n pass\n\n def start_event_loop(self,timeout):\n FigureCanvasBase.start_event_loop_default(self,timeout)\n start_event_loop.__doc__=FigureCanvasBase.start_event_loop_default.__doc__\n\n def stop_event_loop(self):\n FigureCanvasBase.stop_event_loop_default(self)\n stop_event_loop.__doc__=FigureCanvasBase.stop_event_loop_default.__doc__\n\n\n\nNibClassBuilder.extractClasses('Matplotlib.nib', mplBundle)\n\nclass MatplotlibController(NibClassBuilder.AutoBaseClass):\n # available outlets:\n # NSWindow plotWindow\n # PlotView plotView\n\n def awakeFromNib(self):\n # Get a reference to the active canvas\n NSApp().setDelegate_(self)\n self.app = NSApp()\n self.canvas = Gcf.get_active().canvas\n self.plotView.canvas = self.canvas\n self.canvas.plotView = self.plotView\n\n self.plotWindow.setAcceptsMouseMovedEvents_(True)\n self.plotWindow.makeKeyAndOrderFront_(self)\n self.plotWindow.setDelegate_(self)#.plotView)\n\n self.plotView.setImageFrameStyle_(NSImageFrameGroove)\n self.plotView.image_ = NSImage.alloc().initWithSize_((0,0))\n self.plotView.setImage_(self.plotView.image_)\n\n # Make imageview first responder for key events\n self.plotWindow.makeFirstResponder_(self.plotView)\n\n # Force the first update\n self.plotView.windowDidResize_(self)\n\n def windowDidResize_(self, sender):\n self.plotView.windowDidResize_(sender)\n\n def windowShouldClose_(self, sender):\n #NSApplication.sharedApplication().stop_(self)\n self.app.stop_(self)\n return objc.YES\n\n def saveFigure_(self, sender):\n p = NSSavePanel.savePanel()\n if(p.runModal() == NSFileHandlingPanelOKButton):\n self.canvas.print_figure(p.filename())\n\n def printFigure_(self, sender):\n op = NSPrintOperation.printOperationWithView_(self.plotView)\n op.runOperation()\n\nclass PlotWindow(NibClassBuilder.AutoBaseClass):\n pass\n\nclass PlotView(NibClassBuilder.AutoBaseClass):\n def updatePlot(self):\n w,h = self.canvas.get_width_height()\n\n # Remove all previous images\n for i in xrange(self.image_.representations().count()):\n self.image_.removeRepresentation_(self.image_.representations().objectAtIndex_(i))\n\n self.image_.setSize_((w,h))\n\n brep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(\n (self.canvas.buffer_rgba(0,0),'','','',''), # Image data\n w, # width\n h, # height\n 8, # bits per pixel\n 4, # components per pixel\n True, # has alpha?\n False, # is planar?\n NSCalibratedRGBColorSpace, # color space\n w*4, # row bytes\n 32) # bits per pixel\n\n self.image_.addRepresentation_(brep)\n self.setNeedsDisplay_(True)\n\n def windowDidResize_(self, sender):\n w,h = self.bounds().size\n dpi = self.canvas.figure.dpi\n self.canvas.figure.set_size_inches(w / dpi, h / dpi)\n self.canvas.draw()\n self.updatePlot()\n\n def mouseDown_(self, event):\n loc = self.convertPoint_fromView_(event.locationInWindow(), None)\n type = event.type()\n if (type == NSLeftMouseDown):\n button = 1\n else:\n print >>sys.stderr, 'Unknown mouse event type:', type\n button = -1\n self.canvas.button_press_event(loc.x, loc.y, button)\n self.updatePlot()\n\n def mouseDragged_(self, event):\n loc = self.convertPoint_fromView_(event.locationInWindow(), None)\n self.canvas.motion_notify_event(loc.x, loc.y)\n self.updatePlot()\n\n def mouseUp_(self, event):\n loc = self.convertPoint_fromView_(event.locationInWindow(), None)\n type = event.type()\n if (type == NSLeftMouseUp):\n button = 1\n else:\n print >>sys.stderr, 'Unknown mouse event type:', type\n button = -1\n self.canvas.button_release_event(loc.x, loc.y, button)\n self.updatePlot()\n\n def keyDown_(self, event):\n self.canvas.key_press_event(event.characters())\n self.updatePlot()\n\n def keyUp_(self, event):\n self.canvas.key_release_event(event.characters())\n self.updatePlot()\n\nclass MPLBootstrap(NSObject):\n # Loads the nib containing the PlotWindow and PlotView\n def startWithBundle_(self, bundle):\n #NSApplicationLoad()\n if not bundle.loadNibFile_externalNameTable_withZone_('Matplotlib.nib', {}, None):\n print >>sys.stderr, 'Unable to load Matplotlib Cocoa UI!'\n sys.exit()\n\nclass FigureManagerCocoaAgg(FigureManagerBase):\n def __init__(self, canvas, num):\n FigureManagerBase.__init__(self, canvas, num)\n\n try:\n WMEnable('Matplotlib')\n except:\n # MULTIPLE FIGURES ARE BUGGY!\n pass # If there are multiple figures we only need to enable once\n #self.bootstrap = MPLBootstrap.alloc().init().performSelectorOnMainThread_withObject_waitUntilDone_(\n # 'startWithBundle:',\n # mplBundle,\n # False)\n\n def show(self):\n # Load a new PlotWindow\n self.bootstrap = MPLBootstrap.alloc().init().performSelectorOnMainThread_withObject_waitUntilDone_(\n 'startWithBundle:',\n mplBundle,\n False)\n NSApplication.sharedApplication().run()\n\n\nFigureManager = FigureManagerCocoaAgg\n\n#### Everything below taken from PyObjC examples\n#### This is a hack to allow python scripts to access\n#### the window manager without running pythonw.\ndef S(*args):\n return ''.join(args)\n\nOSErr = objc._C_SHT\nOUTPSN = 'o^{ProcessSerialNumber=LL}'\nINPSN = 'n^{ProcessSerialNumber=LL}'\nFUNCTIONS=[\n # These two are public API\n ( u'GetCurrentProcess', S(OSErr, OUTPSN) ),\n ( u'SetFrontProcess', S(OSErr, INPSN) ),\n # This is undocumented SPI\n ( u'CPSSetProcessName', S(OSErr, INPSN, objc._C_CHARPTR) ),\n ( u'CPSEnableForegroundOperation', S(OSErr, INPSN) ),\n]\ndef WMEnable(name='Python'):\n if isinstance(name, unicode):\n name = name.encode('utf8')\n mainBundle = NSBundle.mainBundle()\n bPath = os.path.split(os.path.split(os.path.split(sys.executable)[0])[0])[0]\n if mainBundle.bundlePath() == bPath:\n return True\n bndl = NSBundle.bundleWithPath_(objc.pathForFramework('/System/Library/Frameworks/ApplicationServices.framework'))\n if bndl is None:\n print >>sys.stderr, 'ApplicationServices missing'\n return False\n d = {}\n objc.loadBundleFunctions(bndl, d, FUNCTIONS)\n for (fn, sig) in FUNCTIONS:\n if fn not in d:\n print >>sys.stderr, 'Missing', fn\n return False\n err, psn = d['GetCurrentProcess']()\n if err:\n print >>sys.stderr, 'GetCurrentProcess', (err, psn)\n return False\n err = d['CPSSetProcessName'](psn, name)\n if err:\n print >>sys.stderr, 'CPSSetProcessName', (err, psn)\n return False\n err = d['CPSEnableForegroundOperation'](psn)\n if err:\n #print >>sys.stderr, 'CPSEnableForegroundOperation', (err, psn)\n return False\n err = d['SetFrontProcess'](psn)\n if err:\n print >>sys.stderr, 'SetFrontProcess', (err, psn)\n return False\n return True\n\n"
] |
[
[
"matplotlib.transforms.Bbox.unit",
"numpy.sqrt",
"numpy.asarray",
"matplotlib.transforms.Affine2D",
"numpy.concatenate",
"matplotlib.axes.Axes.__init__",
"matplotlib.transforms.Transform.__init__",
"matplotlib.axes.Axes.cla",
"numpy.where",
"matplotlib.transforms.Affine2DBase.__init__",
"matplotlib.axis.YAxis",
"numpy.arange",
"matplotlib.spines.Spine.circular_spine",
"matplotlib.axis.XAxis",
"numpy.sin",
"matplotlib.ticker.FormatStrFormatter",
"matplotlib.patches.Circle",
"numpy.arccos",
"matplotlib.transforms.BboxTransformTo",
"matplotlib.axes.Axes.set_yscale",
"matplotlib.transforms.IdentityTransform",
"numpy.cos",
"numpy.empty"
],
[
"matplotlib._pylab_helpers.Gcf.get_active",
"matplotlib.is_interactive",
"matplotlib.backend_bases.FigureCanvasBase.start_event_loop_default",
"matplotlib.backend_bases.FigureCanvasBase.stop_event_loop_default",
"matplotlib.backend_bases.FigureManagerBase.__init__"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Jhengsh/tidyframe
|
[
"aa4f8a35cb4abe4d883eb59b6ef6a920580b611f",
"aa4f8a35cb4abe4d883eb59b6ef6a920580b611f"
] |
[
"tests/test_nvl.py",
"tests/test_load_table_schema.py"
] |
[
"import pandas as pd\nfrom tidyframe import nvl\n\n\ndef test_nvl_series():\n test_list = [0, 1, None, pd.np.NaN]\n test_series = pd.Series(test_list)\n nvl(test_series, 10)\n\n\ndef test_nvl_list():\n test_list = [0, 1, None, pd.np.NaN]\n nvl(test_list, 10)\n\n\ndef test_nvl_int():\n nvl(None, 10)\n\n\ndef test_nvl_str():\n nvl(None, 'abc')\n\n\ndef test_nvl_int_v2():\n nvl(1, 10)\n",
"import pandas as pd\nfrom sqlalchemy import (create_engine, Table, MetaData)\nfrom tidyframe import (load_table_schema, create_table)\n\nengine = create_engine('sqlite:///load_table_schema.db')\n\nnum_row = 100000\ndf = pd.DataFrame()\ndf['a'] = ['a'] * num_row\ndf['b'] = ['b'] * num_row\ndf['c'] = ['c'] * num_row\n\n\ndef test_load_table_schema():\n create_table(df, 'test_table', engine, create=True)\n records = df.to_dict('record')\n table_b = load_table_schema('test_table', engine)\n"
] |
[
[
"pandas.Series"
],
[
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
ArthurBernard/quant-reseach
|
[
"8b6385c7e688f33b6e98d5b470af2cb0c1cafb2c"
] |
[
"src/example_helper.py"
] |
[
"import msgpack\nimport zlib\nimport numpy as np\nimport helper_functions as hf\nimport datetime_helper as dh\n\ndef strip_data_by_time(t_data, data, t_min, t_max):\n\tdata = np.array([s for s, t in zip(data, t_data) if t >= t_min and t <= t_max])\n\tt_data = np.array([t for t in t_data if t >= t_min and t <= t_max])\n\treturn t_data, data\n\ndef load_example_data(filename_augmento_topics,\n filename_augmento_data,\n filename_bitmex_data,\n datetime_start=None,\n datetime_end=None):\n\n\t# load the topics\n\twith open(filename_augmento_topics, \"rb\") as f:\n\t\ttemp = msgpack.unpackb(zlib.decompress(f.read()), encoding='utf-8')\n\t\taugmento_topics = {int(k) : v for k, v in temp.items()}\n\t\taugmento_topics_inv = {v : int(k) for k, v in temp.items()}\n\t\n\t# load the augmento data\n\twith open(filename_augmento_data, \"rb\") as f:\n\t\ttemp = msgpack.unpackb(zlib.decompress(f.read()), encoding='utf-8')\n\t\tt_aug_data = np.array([el[\"t_epoch\"] for el in temp], dtype=np.float64)\n\t\taug_data = np.array([el[\"counts\"] for el in temp], dtype=np.int32)\n\t\n\t# load the price data\n\twith open(filename_bitmex_data, \"rb\") as f:\n\t\ttemp = msgpack.unpackb(zlib.decompress(f.read()), encoding='utf-8')\n\t\tt_price_data = np.array([el[\"t_epoch\"] for el in temp], dtype=np.float64)\n\t\tprice_data = np.array([el[\"open\"] for el in temp], dtype=np.float64)\n\t\n\t# set the start and end times if they are specified\n\tif datetime_start != None:\n\t\tt_start = dh.datetime_to_epoch(datetime_start)\n\telse:\n\t\tt_start = max(np.min(t_aug_data), np.min(t_price_data))\n\t\n\tif datetime_end != None:\n\t\tt_end = dh.datetime_to_epoch(datetime_end)\n\telse:\n\t\tt_end = min(np.max(t_aug_data), np.max(t_price_data))\n\t\n\t# strip the sentiments and prices outside the shared time range\n\tt_aug_data, aug_data = strip_data_by_time(t_aug_data, aug_data, t_start, t_end)\n\tt_price_data, price_data = strip_data_by_time(t_price_data, price_data, t_start, t_end)\n\t\n\treturn augmento_topics, augmento_topics_inv, t_aug_data, aug_data, t_price_data, price_data\n"
] |
[
[
"numpy.max",
"numpy.array",
"numpy.min"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bmoretz/Python-Playground
|
[
"a367ec7659b85c24363c21b5c0ac25db08ffa1f6",
"a367ec7659b85c24363c21b5c0ac25db08ffa1f6",
"a367ec7659b85c24363c21b5c0ac25db08ffa1f6",
"a367ec7659b85c24363c21b5c0ac25db08ffa1f6"
] |
[
"src/Classes/MSDS400/Module 7/polution.py",
"src/Classes/MSDS400/Module 1/1.2.2.py",
"src/Classes/MSDS400/Module 1/1.4.1.py",
"src/Classes/MSDS422/Module_05/mnist.py"
] |
[
"from sympy import symbols, integrate, Rational, lambdify\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Pollution from a factory is entering a lake. The rate of concentration of the pollutant at time t is given by\nt = symbols( 't', positive = True )\ndP = 91*t ** Rational( 5, 2 )\n\n# where t is the number of years since the factory started introducing pollutants into the lake.\n\n# Ecologists estimate that the lake can accept a total level of pollution of 7600 units before all the fish life in the lake ends. \n# Can the factory operate for 5 years without killing all the fish in the lake?\n\n# Yes, because:\nP = integrate( dP, ( t, 0, 5 ) ).evalf()\nround( P )\n# is less than 7600.\n\n# What is the polution doing?\ng_xlim = [ 1, 10 ]\ng_ylim = [ -5, 15 ]\n\nlam_p = lambdify( t, integrate( dP, t ), np )\n\nx_vals = np.linspace( g_xlim[0], g_xlim[1], 1000, endpoint=True )\ny_vals = lam_p( x_vals )\nplt.plot( x_vals, y_vals )\nplt.show()",
"import math\nimport numpy as np\n\ndef correlation( x, y ):\n\tif len( x ) != len( y ):\n\t\tprint( 'arrays must have same dimension' )\n\telse:\n\t\tn = len( x )\n\n\t\txy = x*y\n\t\txsq = x ** 2\n\t\tysq = y ** 2\n\n\t\tm1 = n * sum( xy ) - sum( x ) * sum( y )\n\t\tm2 = n * sum( xsq ) - sum( x ) ** 2\n\n\t\tm = m1/m2\n\n\t\tb = ( sum( y ) - m * sum( x ) ) / n\n\n\t\treturn m, b\n\nif __name__ == '__main__':\n\n\tx = np.array( [ 20.00, 30.00, 40.00, 50.00, 60.00, 70.00, 80.00, 90.00, 100.00, 110.00 ] )\n\ty = np.array( [ 71.20, 80.50, 73.40, 60.30, 52.10, 56.20, 46.50, 36.90, 34.00, 39.10 ] )\n\n\tcorrelation( x, y )\n",
"import numpy as np\nfrom prettytable import PrettyTable\n\ndef ptable( t ):\n\tp = PrettyTable()\n\tfor row in t:\n\t\tp.add_row( row )\n\n\tprint( p.get_string( header = False, border = False ) )\n\nC = np.array( [[ 22, 25, 38 ], [ 31, 34, 35 ]] )\nK = np.array( [[ 5, 10, 8 ], [ 11, 14, 15 ]] )\n\nR = C - K\n\n# Results\nptable( R )\n\n# 1.) Row 2\nR[1,:]\n\n# 2.) Col 3\nR[:,2]\n\n# Common Element\nR[ R[:,0] == R[:,1] ]",
"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 31 19:06:02 2018\n\n@author: Jessica\n\"\"\"\n\nfrom __future__ import division, print_function\n\nfrom sklearn.datasets import fetch_mldata\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.decomposition import PCA\nfrom sklearn.metrics import f1_score\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nimport csv\nimport time\nimport numpy as np\nimport pandas as pd\n\nmnist = fetch_mldata('MNIST original', data_home='./')\nmnist.data.shape\nmnist\n\nX, y = mnist['data'], mnist['target']\nX.shape\ny.shape\n\n# Display 36,000th image\nsome_digit = X[36000]\nsome_digit_image = some_digit.reshape(28, 28)\n\nplt.imshow(some_digit_image, cmap = matplotlib.cm.binary, \n interpolation = 'nearest')\n\nplt.axis('off')\nplt.show()\n\n# Split the data to 60,000 images as training data and 10,000 as test data\nX_train, X_test, y_train, y_test = X[:60000], X[60000:], y[:60000], y[60000:]\n\n# --- Random Forest Classifier ---\nrfClf = RandomForestClassifier(n_estimators=100, max_leaf_nodes=10, n_jobs=-1) \n\n# Record the time it takes to fit the model\n# set random number seed \nnp.random.seed(seed = 9999)\n\nreplications = 10 # repeat the trial ten times\nx_time = [] # empty list for storing test results\nn = 0 # initialize count\nprint('--- Time to Fit Random Forest Classifier ---')\nwhile (n < replications): \n start_time = time.clock()\n # generate 1 million random negative binomials and store in a vector\n rfClf.fit(X_train, y_train)\n end_time = time.clock()\n runtime = end_time - start_time # seconds of wall-clock time\n x_time.append(runtime * 1000) # report in milliseconds \n print(\"replication\", n + 1, \":\", x_time[n], \"milliseconds\\n\") \n n = n + 1\n\n# write results to external file \nwith open('rf_fit.csv', 'wt') as f:\n writer = csv.writer(f, quoting = csv.QUOTE_NONNUMERIC, dialect = 'excel')\n writer.writerow('x_time') \n for i in range(replications):\n writer.writerow(([x_time[i],]))\n\n# preliminary analysis for this cell of the design\nprint(pd.DataFrame(x_time).describe())\n\ny_predict = rfClf.predict(X_test)\n\n# Performance measurement using F1-score\nf1Score = f1_score(y_test, y_predict, average='weighted')\nprint('\\nF1 Score: ', f1Score)\n\n# --- PCA ---\n\n# Generate principal components that represent 95 percent of the variability\n# in the explanatory variables\npca = PCA(n_components=0.95)\n\n# Runtime to identify the principal components\npca_time = [] # empty list for storing test results\nn = 0 # initialize count\nprint('--- Time to Identify Pricipal Components ---')\nwhile (n < replications): \n start_time = time.clock()\n # generate 1 million random negative binomials and store in a vector\n X_pca = pca.fit_transform(X) # run on all 70,000 observations\n end_time = time.clock()\n runtime = end_time - start_time # seconds of wall-clock time\n pca_time.append(runtime * 1000) # report in milliseconds \n print(\"replication\", n + 1, \":\", pca_time[n], \"milliseconds\\n\") \n n = n + 1\n\n# write results to external file \nwith open('pca_fit.csv', 'wt') as f:\n writer = csv.writer(f, quoting = csv.QUOTE_NONNUMERIC, dialect = 'excel')\n writer.writerow('pca_time') \n for i in range(replications):\n writer.writerow(([pca_time[i],]))\n# -- Results: Dimension is reduced to 154 variables from 784 variables\nprint(pd.DataFrame(pca_time).describe())\n\n# show summary of pca solution\npca_explained_variance = pca.explained_variance_ratio_\nprint('Proportion of variance explained:', pca_explained_variance)\n\n# Split the reduced data to 60,000 images as training data and 10,000 as test data\nX_pca_train, X_pca_test = X_pca[:60000], X_pca[60000:]\n\n# Random Forest Classifier using the principal components\nrfClf_pca = RandomForestClassifier(n_estimators=100, max_leaf_nodes=10, n_jobs=-1)\n\n# Runtime to identify the principal components\nx_pca_time = [] # empty list for storing test results\nn = 0 # initialize count\nprint('--- Time to Fit Random Forest Classifier using Principal Components ---')\nwhile (n < replications): \n start_time = time.clock()\n # generate 1 million random negative binomials and store in a vector\n rfClf_pca.fit(X_pca_train, y_train)\n end_time = time.clock()\n runtime = end_time - start_time # seconds of wall-clock time\n x_pca_time.append(runtime * 1000) # report in milliseconds \n print(\"replication\", n + 1, \":\", x_pca_time[n], \"milliseconds\\n\") \n n = n + 1\n\n# write results to external file \nwith open('rf_pca_fit.csv', 'wt') as f:\n writer = csv.writer(f, quoting = csv.QUOTE_NONNUMERIC, dialect = 'excel')\n writer.writerow('x_pca_time') \n for i in range(replications):\n writer.writerow(([x_pca_time[i],]))\n\nprint(pd.DataFrame(x_pca_time).describe())\n\ny_predict_pca = rfClf_pca.predict(X_pca_test)\n\n# Performance measurement using F1-score\nf1Score_pca = f1_score(y_test, y_predict_pca, average='weighted')\nprint('\\nF1 Score: ', f1Score_pca)\n\n"
] |
[
[
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show",
"numpy.linspace"
],
[
"numpy.array"
],
[
"numpy.array"
],
[
"matplotlib.pyplot.imshow",
"sklearn.ensemble.RandomForestClassifier",
"numpy.random.seed",
"pandas.DataFrame",
"sklearn.datasets.fetch_mldata",
"matplotlib.pyplot.axis",
"sklearn.metrics.f1_score",
"matplotlib.pyplot.show",
"sklearn.decomposition.PCA"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
Gareth001/tcav
|
[
"e391e7682c34933e27bd592106c119317383ef10"
] |
[
"activation_generator.py"
] |
[
"\"\"\"\nCopyright 2018 Google LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\n\"\"\" Activation generator helper classes for TCAV\"\"\"\n\nfrom abc import ABCMeta\nfrom abc import abstractmethod\nfrom multiprocessing import dummy as multiprocessing\nimport os.path\nimport numpy as np\nimport PIL.Image\nimport tensorflow as tf\n\n\nclass ActivationGeneratorInterface(object):\n \"\"\"Interface for an activation generator for a model\"\"\"\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def process_and_load_activations(self, bottleneck_names, concepts):\n pass\n\n @abstractmethod\n def get_model():\n pass\n\n\nclass ActivationGeneratorBase(ActivationGeneratorInterface):\n \"\"\"Basic abstract activation generator for a model\"\"\"\n\n def __init__(self, model, acts_dir, max_examples=500):\n self.model = model\n self.acts_dir = acts_dir\n self.max_examples = max_examples\n\n def get_model(self):\n return self.model\n\n @abstractmethod\n def get_examples_for_concept(self, concept):\n pass\n\n def get_activations_for_concept(self, concept, bottleneck):\n examples = self.get_examples_for_concept(concept)\n return self.get_activations_for_examples(examples, bottleneck)\n\n def get_activations_for_examples(self, examples, bottleneck):\n acts = self.model.run_examples(examples, bottleneck)\n return self.model.reshape_activations(acts).squeeze()\n\n def process_and_load_activations(self, bottleneck_names, concepts):\n acts = {}\n if self.acts_dir and not tf.gfile.Exists(self.acts_dir):\n tf.gfile.MakeDirs(self.acts_dir)\n\n for concept in concepts:\n if concept not in acts:\n acts[concept] = {}\n for bottleneck_name in bottleneck_names:\n acts_path = os.path.join(self.acts_dir, 'acts_{}_{}'.format(\n concept, bottleneck_name)) if self.acts_dir else None\n if acts_path and tf.gfile.Exists(acts_path):\n with tf.gfile.Open(acts_path, 'rb') as f:\n acts[concept][bottleneck_name] = np.load(f).squeeze()\n tf.logging.info('Loaded {} shape {}'.format(\n acts_path, acts[concept][bottleneck_name].shape))\n else:\n acts[concept][bottleneck_name] = self.get_activations_for_concept(\n concept, bottleneck_name)\n if acts_path:\n tf.logging.info('{} does not exist, Making one...'.format(\n acts_path))\n with tf.gfile.Open(acts_path, 'w') as f:\n np.save(f, acts[concept][bottleneck_name], allow_pickle=False)\n return acts\n\n\nclass ImageActivationGenerator(ActivationGeneratorBase):\n \"\"\"Activation generator for a basic image model\"\"\"\n\n def __init__(self, model, source_dir, acts_dir, max_examples=10):\n self.source_dir = source_dir\n super(ImageActivationGenerator, self).__init__(\n model, acts_dir, max_examples)\n\n def get_examples_for_concept(self, concept):\n concept_dir = os.path.join(self.source_dir, concept)\n img_paths = [os.path.join(concept_dir, d)\n for d in tf.gfile.ListDirectory(concept_dir)]\n imgs = self.load_images_from_files(img_paths, self.max_examples,\n shape=self.model.get_image_shape()[:2])\n return imgs\n\n def load_image_from_file(self, filename, shape):\n \"\"\"Given a filename, try to open the file. If failed, return None.\n\n Args:\n filename: location of the image file\n shape: the shape of the image file to be scaled\n\n Returns:\n the image if succeeds, None if fails.\n\n Rasies:\n exception if the image was not the right shape.\n \"\"\"\n if not tf.gfile.Exists(filename):\n tf.logging.error('Cannot find file: {}'.format(filename))\n return None\n try:\n # ensure image has no transparency channel\n img = np.array(PIL.Image.open(tf.gfile.Open(filename, 'rb')).convert(\n 'RGB').resize(shape, PIL.Image.BILINEAR))\n # Normalize pixel values to between 0 and 1.\n img = np.float32(img) / 255.0\n if not (len(img.shape) == 3 and img.shape[2] == 3):\n return None\n else:\n return img\n\n except Exception as e:\n tf.logging.info(e)\n return None\n return img\n\n def load_images_from_files(self, filenames, max_imgs=500,\n do_shuffle=True, run_parallel=True,\n shape=(299, 299),\n num_workers=100):\n \"\"\"Return image arrays from filenames.\n\n Args:\n filenames: locations of image files.\n max_imgs: maximum number of images from filenames.\n do_shuffle: before getting max_imgs files, shuffle the names or not\n run_parallel: get images in parallel or not\n shape: desired shape of the image\n num_workers: number of workers in parallelization.\n\n Returns:\n image arrays\n\n \"\"\"\n imgs = []\n # First shuffle a copy of the filenames.\n filenames = filenames[:]\n if do_shuffle:\n np.random.shuffle(filenames)\n\n if run_parallel:\n pool = multiprocessing.Pool(num_workers)\n imgs = pool.map(\n lambda filename: self.load_image_from_file(filename, shape),\n filenames[:max_imgs])\n imgs = [img for img in imgs if img is not None]\n if len(imgs) <= 1:\n raise ValueError('You must have more than 1 image in each class to run TCAV.')\n else:\n for filename in filenames:\n img = self.load_image_from_file(filename, shape)\n if img is not None:\n imgs.append(img)\n if len(imgs) <= 1:\n raise ValueError('You must have more than 1 image in each class to run TCAV.')\n elif len(imgs) >= max_imgs:\n break\n\n return np.array(imgs)\n"
] |
[
[
"tensorflow.gfile.ListDirectory",
"tensorflow.gfile.Open",
"tensorflow.gfile.Exists",
"numpy.random.shuffle",
"numpy.save",
"tensorflow.gfile.MakeDirs",
"tensorflow.logging.info",
"numpy.float32",
"numpy.load",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
SPIDER-CMB/xfaster
|
[
"1b8e56d775f2c3a8693d1372ae461392c21da7ca"
] |
[
"xfaster/spec_tools.py"
] |
[
"from __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import division\nimport numpy as np\n\n__all__ = [\n \"wigner3j\",\n \"get_camb_cl\",\n \"scale_dust\",\n]\n\n\ndef blackbody(nu, ref_freq=353.0):\n \"\"\"\n The ratio of the blackbody function for dust at frequency nu\n over the value for reference frequency ref_freq\n\n Arguments\n ---------\n nu : float\n Frequency in GHz.\n ref_freq : float\n Reference frequency in GHz.\n\n Returns\n -------\n blackbody_ratio : float\n B(nu, T_dust) / B(nu_ref, T_dust)\n \"\"\"\n k = 1.38064852e-23 # Boltzmann constant\n h = 6.626070040e-34 # Planck constant\n T = 19.6\n nu_ref = ref_freq * 1.0e9\n nu *= 1.0e9 # GHz -> Hz\n x = h * nu / k / T\n x_ref = h * nu_ref / k / T\n return x ** 3 / x_ref ** 3 * (np.exp(x_ref) - 1) / (np.exp(x) - 1)\n\n\ndef rj2cmb(nu_in):\n \"\"\"\n Conversion from Rayleigh-Jeans units to CMB temperature units\n\n Arguments\n ---------\n nu_in : float\n Frequency in GHz.\n\n Returns\n -------\n cal_fac : float\n Number by which to multiply a RJ temperature to get a CMB temp\n \"\"\"\n k = 1.38064852e-23 # Boltzmann constant\n h = 6.626070040e-34 # Planck constant\n T = 2.72548 # Cmb BB temp in K\n nu = nu_in * 1.0e9 # GHz -> Hz\n x = h * nu / k / T\n return (np.exp(x) - 1.0) ** 2 / (x ** 2 * np.exp(x))\n\n\ndef scale_dust(freq0, freq1, ref_freq, beta, delta_beta=None, deriv=False):\n \"\"\"\n Get the factor by which you must multiply the cross spectrum from maps of\n frequencies freq0 and freq1 to match the dust power at ref_freq given\n spectra index beta.\n\n If deriv is True, return the frequency scaling at the reference beta,\n and the first derivative w.r.t. beta.\n\n Otherwise if delta_beta is given, return the scale factor adjusted\n for a linearized offset delta_beta from the reference beta.\n\n Arguments\n ---------\n freq0 : float\n Frequency of map0 in GHz.\n freq1 : float\n Frequency of map1 in GHz.\n ref_freq : float\n Reference frequency from which to compute relative scaling in GHz.\n beta : float\n Dust spectral index.\n delta_beta : float\n Difference from beta-- scaling computed as a first order Taylor\n expansion from original beta-scaling.\n deriv : bool\n If true, return the frequency scaling at the reference beta, along with\n the first derivative w.r.t. beta at the reference beta.\n\n Returns\n -------\n freq_scale : float\n The relative scaling factor for the dust cross spectrum-- multiply by\n this number to get the dust spectrum at the reference frequency\n -- or --\n freq_scale, deriv : floats\n The relative scaling factor and its derivative\n \"\"\"\n freq_scale = (\n rj2cmb(freq0)\n * rj2cmb(freq1)\n / rj2cmb(ref_freq) ** 2.0\n * blackbody(freq0, ref_freq=ref_freq)\n * blackbody(freq1, ref_freq=ref_freq)\n * (freq0 * freq1 / ref_freq ** 2) ** (beta - 2.0)\n )\n\n if deriv or delta_beta is not None:\n delta = np.log(freq0 * freq1 / ref_freq ** 2)\n if deriv:\n return (freq_scale, freq_scale * delta)\n return freq_scale * (1 + delta * delta_beta)\n\n return freq_scale\n\n\ndef wigner3j(l2, m2, l3, m3):\n r\"\"\"\n Wigner 3j symbols computed for all valid values of ``L``, as in:\n\n .. math::\n\n \\begin{pmatrix}\n \\ell_2 & \\ell_3 & L \\\\\n m_2 & m_3 & 0 \\\\\n \\end{pmatrix}\n\n Arguments\n ---------\n l2, m2, l3, m3 : int\n The ell and m values for which to compute the symbols.\n\n Returns\n -------\n fj : array_like\n Array of size ``l2 + l3 + 2``, indexed by ``L``\n lmin : int\n The minimum value of ``L`` for which ``fj`` is non-zero.\n lmax : int\n The maximum value of ``L`` for which ``fj`` is non-zero.\n \"\"\"\n import camb\n\n try:\n from camb.mathutils import threej\n except ImportError:\n from camb.bispectrum import threej\n arr = threej(l2, l3, m2, m3)\n\n lmin = np.max([np.abs(l2 - l3), np.abs(m2 + m3)])\n lmax = l2 + l3\n fj = np.zeros(lmax + 2, dtype=arr.dtype)\n fj[lmin : lmax + 1] = arr\n return fj, lmin, lmax\n\n\ndef get_camb_cl(r, lmax, nt=None, spec=\"total\", lfac=True):\n \"\"\"\n Compute camb spectrum with tensors and lensing.\n\n Parameter values are from arXiv:1807.06209 Table 1 Plik best fit\n\n Arguments\n ---------\n r : float\n Tensor-to-scalar ratio\n lmax : int\n Maximum ell for which to compute spectra\n nt : scalar, optional\n Tensor spectral index. If not supplied, assumes\n slow-roll consistency relation.\n spec : string, optional\n Spectrum component to return. Can be 'total', 'unlensed_total',\n 'unlensed_scalar', 'lensed_scalar', 'tensor', 'lens_potential'.\n lfac: bool, optional\n If True, multiply Cls by ell*(ell+1)/2/pi\n\n Returns\n -------\n cls : array_like\n Array of spectra of shape (lmax + 1, nspec).\n Diagonal ordering (TT, EE, BB, TE).\n \"\"\"\n # Set up a new set of parameters for CAMB\n import camb\n\n pars = camb.CAMBparams()\n\n # This function sets up CosmoMC-like settings, with one massive neutrino and\n # helium set using BBN consistency\n pars.set_cosmology(\n H0=67.32,\n ombh2=0.022383,\n omch2=0.12011,\n mnu=0.06,\n omk=0,\n tau=0.0543,\n )\n\n ln1010As = 3.0448\n\n pars.InitPower.set_params(As=np.exp(ln1010As) / 1.0e10, ns=0.96605, r=r, nt=nt)\n if lmax < 2500:\n # This results in unacceptable bias. Use higher lmax, then cut it down\n lmax0 = 2500\n else:\n lmax0 = lmax\n pars.set_for_lmax(lmax0, lens_potential_accuracy=2)\n pars.WantTensors = True\n pars.do_lensing = True\n\n # calculate results for these parameters\n results = camb.get_results(pars)\n powers = results.get_cmb_power_spectra(pars, CMB_unit=\"muK\", raw_cl=not lfac)\n\n totCL = powers[spec][: lmax + 1, :4].T\n\n return totCL\n"
] |
[
[
"numpy.log",
"numpy.exp",
"numpy.zeros",
"numpy.abs"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
FireRedz/HFR-Resampler
|
[
"1246e40c836f2e6e5cb0cf1aeaafd03bc7bf5d48"
] |
[
"weights.py"
] |
[
"import math\nimport numpy as np\nfrom enum import IntEnum\n\nclass Mode(IntEnum):\n CUSTOM = 0\n EQUAL = 1\n GAUSS = 2\n GAUSS_SYM = 3\n PYRAMID = 4\n PYRAMID_SYM = 5\n SIVEROO_1 = 6\n SIVEROO_2 = 7\n\n#This function will return an list of value, like below:\n# [0,1,2,3,...,n] -> [a,...,b]\ndef scaleRange(n: int, a: int, b: int):\n return [(x*(b-a)/(n-1))+a for x in range(0,n)]\n\ndef equal(n: int):\n return [1/n]*n\n\ndef gauss(n: int):\n r = range(n,0,-1)\n val = [math.exp(-(2.0*x/n)**2) for x in r]\n val = val/np.sum(val)\n return val\n\ndef gauss_sym(n: int):\n n = n/2\n r = range(int(n),-math.ceil(n),-1)\n val = ([math.exp(-(2.0*x/(n))**2) for x in r])\n val = val/np.sum(val)\n return val\n\ndef pyramid(n: int):\n r = range(1,n+1)\n val = [x/n for x in r]\n val = val/np.sum(val)\n return val\n\ndef pyramid_sym(n: int):\n r = range(0,n)\n val = [(n/2)-abs(x-(n-1)/2) for x in r]\n val = val/np.sum(val)\n return val\n\ndef siveroo1(n: int):\n r = scaleRange(n,-3,0.1)\n val = [math.floor(3*math.exp(-(x/1.9)**2))/3+0.1 for x in r]\n val = val/np.sum(val)\n return val\n\n# this function will stretch the given array (w) to a specific length (n)\n# example : n = 10, w = [1,2]\n# result : val = [1,1,1,1,1,2,2,2,2,2] , flip it, and then normalize it so its sum is equal to 1\ndef stretch(n: int, w: int):\n r = scaleRange(n,0,len(w)-0.1)\n\n val = []\n idx = [math.floor(x) for x in r]\n for x in range(0,n):\n index = int(idx[x])\n val.append(w[index])\n val = val/np.sum(val)\n return val\n\ndef null(n: int):\n return [0]*n\n\ndef get_weight(mode: Mode, count: int):\n if count == 1:\n return [1.0]\n else:\n return {\n Mode.EQUAL : equal(count),\n Mode.GAUSS : gauss(count),\n Mode.GAUSS_SYM : gauss_sym(count),\n Mode.PYRAMID : pyramid(count),\n Mode.PYRAMID_SYM : pyramid_sym(count),\n Mode.SIVEROO_1 : siveroo1(count),\n Mode.SIVEROO_2 : stretch(count,[1,3,3,2,2])\n }.get(mode, [1, 0]) # fallback to [1,0] if fucked up\n\ndef modeName(mode: Mode):\n return {\n Mode.EQUAL : \"[1] Equal\",\n Mode.GAUSS : \"[2] Gaussian Asymmetric\",\n Mode.GAUSS_SYM : \"[3] Gaussian Symmetric\",\n Mode.PYRAMID : \"[4] Pyramid Asymmetric\",\n Mode.PYRAMID_SYM : \"[5] Pyramid Symmetric\",\n Mode.SIVEROO_1 : \"[6] Siveroo's Preset I\",\n Mode.SIVEROO_2 : \"[7] Siveroo's Preset II\"\n }[mode]\n"
] |
[
[
"numpy.sum"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
FLyingLSJ/ssd.pytorch
|
[
"9caca0788f0bebab345f969a7d3c1f8b2081b809"
] |
[
"eval.py"
] |
[
"\"\"\"Adapted from:\n @longcw faster_rcnn_pytorch: https://github.com/longcw/faster_rcnn_pytorch\n @rbgirshick py-faster-rcnn https://github.com/rbgirshick/py-faster-rcnn\n Licensed under The MIT License [see LICENSE for details]\n\"\"\"\n\nfrom __future__ import print_function\nimport torch\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn\nfrom torch.autograd import Variable\nfrom data import VOC_ROOT, VOCAnnotationTransform, VOCDetection, BaseTransform\nfrom data import VOC_CLASSES as labelmap\nimport torch.utils.data as data\n\nfrom ssd import build_ssd\n\nimport sys\nimport os\nimport time\nimport argparse\nimport numpy as np\nimport pickle\nimport cv2\n\nif sys.version_info[0] == 2:\n import xml.etree.cElementTree as ET\nelse:\n import xml.etree.ElementTree as ET\n\n\ndef str2bool(v):\n return v.lower() in (\"yes\", \"true\", \"t\", \"1\")\n\n\nparser = argparse.ArgumentParser(\n description='Single Shot MultiBox Detector Evaluation')\nparser.add_argument('--trained_model',\n default='weights/ssd300_mAP_77.43_v2.pth', type=str,\n help='Trained state_dict file path to open')\nparser.add_argument('--save_folder', default='eval/', type=str,\n help='File path to save results')\nparser.add_argument('--confidence_threshold', default=0.5, type=float,\n help='Detection confidence threshold')\nparser.add_argument('--top_k', default=5, type=int,\n help='Further restrict the number of predictions to parse')\nparser.add_argument('--cuda', default=False, type=str2bool,\n help='Use cuda to train model')\nparser.add_argument('--voc_root', default=VOC_ROOT,\n help='Location of VOC root directory')\nparser.add_argument('--cleanup', default=True, type=str2bool,\n help='Cleanup and remove results files following eval')\n\nargs = parser.parse_args()\n\nif not os.path.exists(args.save_folder):\n os.mkdir(args.save_folder)\n\nif torch.cuda.is_available():\n if args.cuda:\n torch.set_default_tensor_type('torch.cuda.FloatTensor')\n if not args.cuda:\n print(\"WARNING: It looks like you have a CUDA device, but aren't using \\\n CUDA. Run with --cuda for optimal eval speed.\")\n torch.set_default_tensor_type('torch.FloatTensor')\nelse:\n torch.set_default_tensor_type('torch.FloatTensor')\n\nannopath = os.path.join(args.voc_root, 'VOC2007', 'Annotations', '%s.xml')\nimgpath = os.path.join(args.voc_root, 'VOC2007', 'JPEGImages', '%s.jpg')\n\nif sys.platform.startswith(\"linux\"):\n imgsetpath = os.path.join(args.voc_root, 'VOC2007', 'ImageSets', 'Main', '{:s}.txt') # Linux 系统下\nif sys.platform.startswith(\"win\"):\n imgsetpath = os.path.join(args.voc_root, 'VOC2007', 'ImageSets', 'Main', '{}.txt') # Linux 系统下\nYEAR = '2007'\ndevkit_path = args.voc_root + 'VOC' + YEAR\ndataset_mean = (104, 117, 123)\nset_type = 'test'\n\n\nclass Timer(object):\n \"\"\"A simple timer.\"\"\"\n def __init__(self):\n self.total_time = 0.\n self.calls = 0\n self.start_time = 0.\n self.diff = 0.\n self.average_time = 0.\n\n def tic(self):\n # using time.time instead of time.clock because time time.clock\n # does not normalize for multithreading\n self.start_time = time.time()\n\n def toc(self, average=True):\n self.diff = time.time() - self.start_time\n self.total_time += self.diff\n self.calls += 1\n self.average_time = self.total_time / self.calls\n if average:\n return self.average_time\n else:\n return self.diff\n\n\ndef parse_rec(filename):\n \"\"\" Parse a PASCAL VOC xml file \"\"\"\n tree = ET.parse(filename)\n objects = []\n for obj in tree.findall('object'):\n obj_struct = {}\n obj_struct['name'] = obj.find('name').text\n obj_struct['pose'] = obj.find('pose').text\n obj_struct['truncated'] = int(obj.find('truncated').text)\n obj_struct['difficult'] = int(obj.find('difficult').text)\n bbox = obj.find('bndbox')\n obj_struct['bbox'] = [int(bbox.find('xmin').text) - 1,\n int(bbox.find('ymin').text) - 1,\n int(bbox.find('xmax').text) - 1,\n int(bbox.find('ymax').text) - 1]\n objects.append(obj_struct)\n\n return objects\n\n\ndef get_output_dir(name, phase):\n \"\"\"Return the directory where experimental artifacts are placed.\n If the directory does not exist, it is created.\n A canonical path is built using the name from an imdb and a network\n (if not None).\n \"\"\"\n filedir = os.path.join(name, phase)\n if not os.path.exists(filedir):\n os.makedirs(filedir)\n return filedir\n\n\ndef get_voc_results_file_template(image_set, cls):\n # VOCdevkit/VOC2007/results/det_test_aeroplane.txt\n filename = 'det_' + image_set + '_%s.txt' % (cls)\n filedir = os.path.join(devkit_path, 'results')\n if not os.path.exists(filedir):\n os.makedirs(filedir)\n path = os.path.join(filedir, filename)\n return path\n\n\ndef write_voc_results_file(all_boxes, dataset):\n for cls_ind, cls in enumerate(labelmap):\n print('Writing {:s} VOC results file'.format(cls))\n filename = get_voc_results_file_template(set_type, cls)\n with open(filename, 'wt') as f:\n for im_ind, index in enumerate(dataset.ids):\n dets = all_boxes[cls_ind+1][im_ind]\n if dets == []:\n continue\n # the VOCdevkit expects 1-based indices\n for k in range(dets.shape[0]):\n f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\\n'.\n format(index[1], dets[k, -1],\n dets[k, 0] + 1, dets[k, 1] + 1,\n dets[k, 2] + 1, dets[k, 3] + 1))\n\n\ndef do_python_eval(output_dir='output', use_07=True):\n cachedir = os.path.join(devkit_path, 'annotations_cache')\n aps = []\n # The PASCAL VOC metric changed in 2010\n use_07_metric = use_07\n print('VOC07 metric? ' + ('Yes' if use_07_metric else 'No'))\n if not os.path.isdir(output_dir):\n os.mkdir(output_dir)\n for i, cls in enumerate(labelmap):\n filename = get_voc_results_file_template(set_type, cls)\n rec, prec, ap = voc_eval(\n filename, annopath, imgsetpath.format(set_type), cls, cachedir,\n ovthresh=0.5, use_07_metric=use_07_metric)\n aps += [ap]\n print('AP for {} = {:.4f}'.format(cls, ap))\n with open(os.path.join(output_dir, cls + '_pr.pkl'), 'wb') as f:\n pickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f)\n print('Mean AP = {:.4f}'.format(np.mean(aps)))\n print('~~~~~~~~')\n print('Results:')\n for ap in aps:\n print('{:.3f}'.format(ap))\n print('{:.3f}'.format(np.mean(aps)))\n print('~~~~~~~~')\n print('')\n print('--------------------------------------------------------------')\n print('Results computed with the **unofficial** Python eval code.')\n print('Results should be very close to the official MATLAB eval code.')\n print('--------------------------------------------------------------')\n\n\ndef voc_ap(rec, prec, use_07_metric=True):\n \"\"\" ap = voc_ap(rec, prec, [use_07_metric])\n Compute VOC AP given precision and recall.\n If use_07_metric is true, uses the\n VOC 07 11 point method (default:True).\n \"\"\"\n if use_07_metric:\n # 11 point metric\n ap = 0.\n for t in np.arange(0., 1.1, 0.1):\n if np.sum(rec >= t) == 0:\n p = 0\n else:\n p = np.max(prec[rec >= t])\n ap = ap + p / 11.\n else:\n # correct AP calculation\n # first append sentinel values at the end\n mrec = np.concatenate(([0.], rec, [1.]))\n mpre = np.concatenate(([0.], prec, [0.]))\n\n # compute the precision envelope\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n\n # to calculate area under PR curve, look for points\n # where X axis (recall) changes value\n i = np.where(mrec[1:] != mrec[:-1])[0]\n\n # and sum (\\Delta recall) * prec\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n return ap\n\n\ndef voc_eval(detpath,\n annopath,\n imagesetfile,\n classname,\n cachedir,\n ovthresh=0.5,\n use_07_metric=True):\n \"\"\"rec, prec, ap = voc_eval(detpath,\n annopath,\n imagesetfile,\n classname,\n [ovthresh],\n [use_07_metric])\nTop level function that does the PASCAL VOC evaluation.\ndetpath: Path to detections\n detpath.format(classname) should produce the detection results file.\nannopath: Path to annotations\n annopath.format(imagename) should be the xml annotations file.\nimagesetfile: Text file containing the list of images, one image per line.\nclassname: Category name (duh)\ncachedir: Directory for caching the annotations\n[ovthresh]: Overlap threshold (default = 0.5)\n[use_07_metric]: Whether to use VOC07's 11 point AP computation\n (default True)\n\"\"\"\n# assumes detections are in detpath.format(classname)\n# assumes annotations are in annopath.format(imagename)\n# assumes imagesetfile is a text file with each line an image name\n# cachedir caches the annotations in a pickle file\n# first load gt\n if not os.path.isdir(cachedir):\n os.mkdir(cachedir)\n cachefile = os.path.join(cachedir, 'annots.pkl')\n # read list of images \n with open(imagesetfile, 'r') as f:\n lines = f.readlines()\n imagenames = [x.strip() for x in lines]\n if not os.path.isfile(cachefile):\n # load annots\n recs = {}\n for i, imagename in enumerate(imagenames):\n recs[imagename] = parse_rec(annopath % (imagename))\n if i % 100 == 0:\n print('Reading annotation for {:d}/{:d}'.format(\n i + 1, len(imagenames)))\n # save\n print('Saving cached annotations to {:s}'.format(cachefile))\n with open(cachefile, 'wb') as f:\n pickle.dump(recs, f)\n else:\n # load\n with open(cachefile, 'rb') as f:\n recs = pickle.load(f)\n\n # extract gt objects for this class\n class_recs = {}\n npos = 0\n for imagename in imagenames:\n R = [obj for obj in recs[imagename] if obj['name'] == classname]\n bbox = np.array([x['bbox'] for x in R])\n difficult = np.array([x['difficult'] for x in R]).astype(np.bool)\n det = [False] * len(R)\n npos = npos + sum(~difficult)\n class_recs[imagename] = {'bbox': bbox,\n 'difficult': difficult,\n 'det': det}\n\n # read dets\n detfile = detpath.format(classname)\n with open(detfile, 'r') as f:\n lines = f.readlines()\n if any(lines) == 1:\n\n splitlines = [x.strip().split(' ') for x in lines]\n image_ids = [x[0] for x in splitlines]\n confidence = np.array([float(x[1]) for x in splitlines])\n BB = np.array([[float(z) for z in x[2:]] for x in splitlines])\n\n # sort by confidence\n sorted_ind = np.argsort(-confidence)\n sorted_scores = np.sort(-confidence)\n BB = BB[sorted_ind, :]\n image_ids = [image_ids[x] for x in sorted_ind]\n\n # go down dets and mark TPs and FPs\n nd = len(image_ids)\n tp = np.zeros(nd)\n fp = np.zeros(nd)\n for d in range(nd):\n R = class_recs[image_ids[d]]\n bb = BB[d, :].astype(float)\n ovmax = -np.inf\n BBGT = R['bbox'].astype(float)\n if BBGT.size > 0:\n # compute overlaps\n # intersection\n ixmin = np.maximum(BBGT[:, 0], bb[0])\n iymin = np.maximum(BBGT[:, 1], bb[1])\n ixmax = np.minimum(BBGT[:, 2], bb[2])\n iymax = np.minimum(BBGT[:, 3], bb[3])\n iw = np.maximum(ixmax - ixmin, 0.)\n ih = np.maximum(iymax - iymin, 0.)\n inters = iw * ih\n uni = ((bb[2] - bb[0]) * (bb[3] - bb[1]) +\n (BBGT[:, 2] - BBGT[:, 0]) *\n (BBGT[:, 3] - BBGT[:, 1]) - inters)\n overlaps = inters / uni\n ovmax = np.max(overlaps)\n jmax = np.argmax(overlaps)\n\n if ovmax > ovthresh:\n if not R['difficult'][jmax]:\n if not R['det'][jmax]:\n tp[d] = 1.\n R['det'][jmax] = 1\n else:\n fp[d] = 1.\n else:\n fp[d] = 1.\n\n # compute precision recall\n fp = np.cumsum(fp)\n tp = np.cumsum(tp)\n rec = tp / float(npos)\n # avoid divide by zero in case the first detection matches a difficult\n # ground truth\n prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)\n ap = voc_ap(rec, prec, use_07_metric)\n else:\n rec = -1.\n prec = -1.\n ap = -1.\n\n return rec, prec, ap\n\n\ndef test_net(save_folder, net, cuda, dataset, transform, top_k,\n im_size=300, thresh=0.05):\n num_images = len(dataset)\n # all detections are collected into:\n # all_boxes[cls][image] = N x 5 array of detections in\n # (x1, y1, x2, y2, score)\n all_boxes = [[[] for _ in range(num_images)]\n for _ in range(len(labelmap)+1)]\n\n # timers\n _t = {'im_detect': Timer(), 'misc': Timer()}\n output_dir = get_output_dir('ssd300_120000', set_type)\n det_file = os.path.join(output_dir, 'detections.pkl')\n\n for i in range(num_images):\n im, gt, h, w = dataset.pull_item(i)\n\n x = Variable(im.unsqueeze(0))\n if args.cuda:\n x = x.cuda()\n _t['im_detect'].tic()\n detections = net(x).data\n detect_time = _t['im_detect'].toc(average=False)\n\n # skip j = 0, because it's the background class\n for j in range(1, detections.size(1)):\n dets = detections[0, j, :]\n mask = dets[:, 0].gt(0.).expand(5, dets.size(0)).t()\n dets = torch.masked_select(dets, mask).view(-1, 5)\n if dets.size(0) == 0:\n continue\n boxes = dets[:, 1:]\n boxes[:, 0] *= w\n boxes[:, 2] *= w\n boxes[:, 1] *= h\n boxes[:, 3] *= h\n scores = dets[:, 0].cpu().numpy()\n cls_dets = np.hstack((boxes.cpu().numpy(),\n scores[:, np.newaxis])).astype(np.float32,\n copy=False)\n all_boxes[j][i] = cls_dets\n\n print('im_detect: {:d}/{:d} {:.3f}s'.format(i + 1,\n num_images, detect_time))\n\n with open(det_file, 'wb') as f:\n pickle.dump(all_boxes, f, pickle.HIGHEST_PROTOCOL)\n\n print('Evaluating detections')\n evaluate_detections(all_boxes, output_dir, dataset)\n\n\ndef evaluate_detections(box_list, output_dir, dataset):\n write_voc_results_file(box_list, dataset)\n do_python_eval(output_dir)\n\n\nif __name__ == '__main__':\n # load net\n num_classes = len(labelmap) + 1 # +1 for background\n net = build_ssd('test', 300, num_classes) # initialize SSD\n #net.load_state_dict(torch.load(args.trained_model))\n net.load_state_dict(torch.load(args.trained_model, map_location='cpu')) # running on a CPU-only machine \n net.eval()\n print('Finished loading model!')\n # load data\n dataset = VOCDetection(args.voc_root, \n [('2007', set_type)],\n BaseTransform(300, dataset_mean),\n VOCAnnotationTransform())\n if args.cuda:\n net = net.cuda()\n cudnn.benchmark = True\n # evaluation\n test_net(args.save_folder, net, args.cuda, dataset,\n BaseTransform(net.size, dataset_mean), args.top_k, 300,\n thresh=args.confidence_threshold)\n"
] |
[
[
"torch.set_default_tensor_type",
"numpy.minimum",
"torch.load",
"numpy.cumsum",
"numpy.concatenate",
"numpy.max",
"numpy.mean",
"torch.cuda.is_available",
"numpy.where",
"numpy.arange",
"numpy.finfo",
"numpy.argmax",
"torch.masked_select",
"numpy.zeros",
"numpy.argsort",
"numpy.array",
"numpy.sum",
"numpy.maximum",
"numpy.sort"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
NunoEdgarGFlowHub/vision
|
[
"86001a871d3335046e2dca7715d9babf73e6956f"
] |
[
"torchvision/models/densenet.py"
] |
[
"import re\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.model_zoo as model_zoo\nfrom collections import OrderedDict\n\n__all__ = ['DenseNet', 'densenet121', 'densenet169', 'densenet201', 'densenet161']\n\n\nmodel_urls = {\n 'densenet121': 'https://download.pytorch.org/models/densenet121-a639ec97.pth',\n 'densenet169': 'https://download.pytorch.org/models/densenet169-b2777c0a.pth',\n 'densenet201': 'https://download.pytorch.org/models/densenet201-c1103571.pth',\n 'densenet161': 'https://download.pytorch.org/models/densenet161-8d451a50.pth',\n}\n\n\ndef densenet121(pretrained=False, **kwargs):\n r\"\"\"Densenet-121 model from\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = DenseNet(num_init_features=64, growth_rate=32, block_config=(6, 12, 24, 16),\n **kwargs)\n if pretrained:\n # '.'s are no longer allowed in module names, but pervious _DenseLayer\n # has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'.\n # They are also in the checkpoints in model_urls. This pattern is used\n # to find such keys.\n pattern = re.compile(\n r'^(.*denselayer\\d+\\.(?:norm|relu|conv))\\.((?:[12])\\.(?:weight|bias|running_mean|running_var))$')\n state_dict = model_zoo.load_url(model_urls['densenet121'])\n for key in list(state_dict.keys()):\n res = pattern.match(key)\n if res:\n new_key = res.group(1) + res.group(2)\n state_dict[new_key] = state_dict[key]\n del state_dict[key]\n model.load_state_dict(state_dict)\n return model\n\n\ndef densenet169(pretrained=False, **kwargs):\n r\"\"\"Densenet-169 model from\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = DenseNet(num_init_features=64, growth_rate=32, block_config=(6, 12, 32, 32),\n **kwargs)\n if pretrained:\n # '.'s are no longer allowed in module names, but pervious _DenseLayer\n # has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'.\n # They are also in the checkpoints in model_urls. This pattern is used\n # to find such keys.\n pattern = re.compile(\n r'^(.*denselayer\\d+\\.(?:norm|relu|conv))\\.((?:[12])\\.(?:weight|bias|running_mean|running_var))$')\n state_dict = model_zoo.load_url(model_urls['densenet169'])\n for key in list(state_dict.keys()):\n res = pattern.match(key)\n if res:\n new_key = res.group(1) + res.group(2)\n state_dict[new_key] = state_dict[key]\n del state_dict[key]\n model.load_state_dict(state_dict)\n return model\n\n\ndef densenet201(pretrained=False, **kwargs):\n r\"\"\"Densenet-201 model from\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = DenseNet(num_init_features=64, growth_rate=32, block_config=(6, 12, 48, 32),\n **kwargs)\n if pretrained:\n # '.'s are no longer allowed in module names, but pervious _DenseLayer\n # has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'.\n # They are also in the checkpoints in model_urls. This pattern is used\n # to find such keys.\n pattern = re.compile(\n r'^(.*denselayer\\d+\\.(?:norm|relu|conv))\\.((?:[12])\\.(?:weight|bias|running_mean|running_var))$')\n state_dict = model_zoo.load_url(model_urls['densenet201'])\n for key in list(state_dict.keys()):\n res = pattern.match(key)\n if res:\n new_key = res.group(1) + res.group(2)\n state_dict[new_key] = state_dict[key]\n del state_dict[key]\n model.load_state_dict(state_dict)\n return model\n\n\ndef densenet161(pretrained=False, **kwargs):\n r\"\"\"Densenet-161 model from\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = DenseNet(num_init_features=96, growth_rate=48, block_config=(6, 12, 36, 24),\n **kwargs)\n if pretrained:\n # '.'s are no longer allowed in module names, but pervious _DenseLayer\n # has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'.\n # They are also in the checkpoints in model_urls. This pattern is used\n # to find such keys.\n pattern = re.compile(\n r'^(.*denselayer\\d+\\.(?:norm|relu|conv))\\.((?:[12])\\.(?:weight|bias|running_mean|running_var))$')\n state_dict = model_zoo.load_url(model_urls['densenet161'])\n for key in list(state_dict.keys()):\n res = pattern.match(key)\n if res:\n new_key = res.group(1) + res.group(2)\n state_dict[new_key] = state_dict[key]\n del state_dict[key]\n model.load_state_dict(state_dict)\n return model\n\n\nclass _DenseLayer(nn.Sequential):\n def __init__(self, num_input_features, growth_rate, bn_size, drop_rate):\n super(_DenseLayer, self).__init__()\n self.add_module('norm1', nn.BatchNorm2d(num_input_features)),\n self.add_module('relu1', nn.ReLU(inplace=True)),\n self.add_module('conv1', nn.Conv2d(num_input_features, bn_size *\n growth_rate, kernel_size=1, stride=1, bias=False)),\n self.add_module('norm2', nn.BatchNorm2d(bn_size * growth_rate)),\n self.add_module('relu2', nn.ReLU(inplace=True)),\n self.add_module('conv2', nn.Conv2d(bn_size * growth_rate, growth_rate,\n kernel_size=3, stride=1, padding=1, bias=False)),\n self.drop_rate = drop_rate\n\n def forward(self, x):\n new_features = super(_DenseLayer, self).forward(x)\n if self.drop_rate > 0:\n new_features = F.dropout(new_features, p=self.drop_rate, training=self.training)\n return torch.cat([x, new_features], 1)\n\n\nclass _DenseBlock(nn.Sequential):\n def __init__(self, num_layers, num_input_features, bn_size, growth_rate, drop_rate):\n super(_DenseBlock, self).__init__()\n for i in range(num_layers):\n layer = _DenseLayer(num_input_features + i * growth_rate, growth_rate, bn_size, drop_rate)\n self.add_module('denselayer%d' % (i + 1), layer)\n\n\nclass _Transition(nn.Sequential):\n def __init__(self, num_input_features, num_output_features):\n super(_Transition, self).__init__()\n self.add_module('norm', nn.BatchNorm2d(num_input_features))\n self.add_module('relu', nn.ReLU(inplace=True))\n self.add_module('conv', nn.Conv2d(num_input_features, num_output_features,\n kernel_size=1, stride=1, bias=False))\n self.add_module('pool', nn.AvgPool2d(kernel_size=2, stride=2))\n\n\nclass DenseNet(nn.Module):\n r\"\"\"Densenet-BC model class, based on\n `\"Densely Connected Convolutional Networks\" <https://arxiv.org/pdf/1608.06993.pdf>`_\n\n Args:\n growth_rate (int) - how many filters to add each layer (`k` in paper)\n block_config (list of 4 ints) - how many layers in each pooling block\n num_init_features (int) - the number of filters to learn in the first convolution layer\n bn_size (int) - multiplicative factor for number of bottle neck layers\n (i.e. bn_size * k features in the bottleneck layer)\n drop_rate (float) - dropout rate after each dense layer\n num_classes (int) - number of classification classes\n \"\"\"\n\n def __init__(self, growth_rate=32, block_config=(6, 12, 24, 16),\n num_init_features=64, bn_size=4, drop_rate=0, num_classes=1000):\n\n super(DenseNet, self).__init__()\n\n # First convolution\n self.features = nn.Sequential(OrderedDict([\n ('conv0', nn.Conv2d(3, num_init_features, kernel_size=7, stride=2, padding=3, bias=False)),\n ('norm0', nn.BatchNorm2d(num_init_features)),\n ('relu0', nn.ReLU(inplace=True)),\n ('pool0', nn.MaxPool2d(kernel_size=3, stride=2, padding=1)),\n ]))\n\n # Each denseblock\n num_features = num_init_features\n for i, num_layers in enumerate(block_config):\n block = _DenseBlock(num_layers=num_layers, num_input_features=num_features,\n bn_size=bn_size, growth_rate=growth_rate, drop_rate=drop_rate)\n self.features.add_module('denseblock%d' % (i + 1), block)\n num_features = num_features + num_layers * growth_rate\n if i != len(block_config) - 1:\n trans = _Transition(num_input_features=num_features, num_output_features=num_features // 2)\n self.features.add_module('transition%d' % (i + 1), trans)\n num_features = num_features // 2\n\n # Final batch norm\n self.features.add_module('norm5', nn.BatchNorm2d(num_features))\n\n # Linear layer\n self.classifier = nn.Linear(num_features, num_classes)\n\n # Official init from torch repo.\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.Linear):\n nn.init.constant_(m.bias, 0)\n\n def forward(self, x):\n features = self.features(x)\n out = F.relu(features, inplace=True)\n out = F.avg_pool2d(out, kernel_size=7, stride=1).view(features.size(0), -1)\n out = self.classifier(out)\n return out\n"
] |
[
[
"torch.nn.functional.dropout",
"torch.cat",
"torch.nn.init.constant_",
"torch.nn.functional.avg_pool2d",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.AvgPool2d",
"torch.nn.functional.relu",
"torch.nn.MaxPool2d",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.utils.model_zoo.load_url",
"torch.nn.init.kaiming_normal_"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jtsuchiyama/hawaii-covid-tracker
|
[
"456f63728f6e17208477e7b585e997e8f8b35657"
] |
[
"app.py"
] |
[
"import os\nimport time\nimport requests\nfrom bs4 import BeautifulSoup\nimport datetime\nfrom twilio.rest import Client\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport math\n\nclass Data():\n def __init__(self,link): # Automatically stores the data from parsed link as the object's attribute \n self.data = self.update(link)\n self.prev = None\n \n def update(self,link): # Parses the site's HTML code\n result = requests.get(link)\n soup = BeautifulSoup(result.content,'lxml')\n return soup\n\n\nclass Hawaii(Data):\n def __init__(self,link): # Automatically stores the data from parsed link as the object's attribute (Same constructor as Class Data)\n super().__init__(link)\n \n\n def do_sms(self,numbers): # Creates SMS notification with the COVID data for each island\n for number in numbers:\n smsNotification.notify(number,self.get_data()) \n smsNotification.save_number(numbers) \n\n\n def get_data(self): # Returns the data from today:\n # Gathering all the data\n today = self.get_dataframe()\n order = [\"Total cases\",\"Hawai’i\",\"Oahu\",\"Kaua’i\",\"Maui\",\"Pending\",\"Residents diagnosed outside of Hawai‘i\",\"Required Hospitalization\",\"Hawaii deaths\",\"Lanai\",\"Molokai\"]\n data = today.to_numpy()[0]\n\n message = \"\"\n for index in range(len(order)):\n diff = int(data[index+1]) - int(self.prev[index])\n if diff >= 0:\n diff = \"+\" + str(diff)\n\n else:\n diff = \"-\" + str(diff)\n \n line = order[index] + \": \" + str(data[index+1]) + \" (\" + diff + \") \\n\"\n message = message + line\n return message\n \n\n def get_dataframe(self): # Returns the data structure for today's data\n date = self.get_date()\n \n names = self.data.find_all('span',{'class': 'label'})\n values = self.data.find_all('span',{'class': 'value'})\n\n df = pd.DataFrame()\n # Formats the names and values\n for i in range(len(names)):\n names[i] = names[i].text.replace(\":\",\"\")\n values[i] = int(values[i].text.replace(\"§\",\"\").replace(\"†\",\"\").replace(\"‡\",\"\").replace(\"*\",\"\").split(\" \")[0])\n\n # Orders the names and values in the order of the .csv\n order = [\"Total cases\",\"Hawai’i\",\"Oahu\",\"Kaua’i\",\"Maui\",\"Pending\",\"Residents diagnosed outside of Hawai‘i\",\"Required Hospitalization\",\"Hawaii deaths\",\"Lanai\",\"Molokai\"]\n namesOrdered = [\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]\n valuesOrdered = [\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]\n for i in range(len(order)):\n for j in range(len(names)):\n if order[i] == names[j]:\n namesOrdered[i] = names[j]\n valuesOrdered[i] = values[j]\n \n dfNew = pd.DataFrame({\n \"Date\": date, \n namesOrdered[0]: valuesOrdered[0],\n namesOrdered[1]: valuesOrdered[1],\n namesOrdered[2]: valuesOrdered[2],\n namesOrdered[3]: valuesOrdered[3],\n namesOrdered[4]: valuesOrdered[4],\n namesOrdered[5]: valuesOrdered[5],\n namesOrdered[6]: valuesOrdered[6],\n namesOrdered[7]: valuesOrdered[7],\n namesOrdered[8]: valuesOrdered[8],\n namesOrdered[9]: valuesOrdered[9],\n namesOrdered[10]: valuesOrdered[10],\n }, index = [0])\n\n return dfNew\n\n \n def get_date(self): # Returns the update date of the data in the datetime format\n # Formatting\n date = self.data.find_all('dd',{'class': 'small'})\n date = date[0].text[33:]\n date = datetime.datetime.strptime(date, '%B %d, %Y')\n date = str(date.date())\n return date\n\n\n def do_update(self): # Does an update if the history.txt is not updated\n # If the history.txt is not updated relevant to the available data, the update proceeds \n if self.check_update() == False:\n # Checks if the data on the website is updated; Loops the program until the data is updated\n if self.get_date() != str(datetime.date.today()):\n print(\"Data not updated. Sleeping for 1 minute.\\n\")\n time.sleep(60)\n print(\"Rechecking.\\n\")\n self.do_update()\n return\n\n dfOld = pd.read_csv('data.csv', index_col = False)\n dfOld = dfOld.append(self.get_dataframe())\n dfOld.to_csv('data.csv', index=False)\n \n file = \"phoneNumbers.txt\"\n numbers = open(file,\"r\")\n # Checks if there are any recently saved numbers\n if(os.stat(file).st_size) == 0:\n print(\"No recent phone numbers found. Please enter your phone numbers including area code and no dashes into the phoneNumbers.txt file, with each phone number tabbed.\")\n return\n \n else:\n paste=[]\n for line in numbers:\n paste.append(line.replace(\"\\n\",\"\"))\n self.do_sms(paste)\n \n \n def check_update(self): # Checks when the data.csv was last updated; Returns True if already updated today; Returns False if not\n file = \"data.csv\"\n history = open(file,'r')\n\n # Checks if the file is empty ahead of time to prevent crash and formats the document if it is empty\n if(os.stat(file).st_size) == 0:\n File.append_file(file, \"Date,Total cases,Hawai’i,Oahu,Kaua’i,Maui,Pending,Residents diagnosed outside of Hawai‘i,Required Hospitalization,Hawaii deaths,Lanai,Molokai\")\n return False\n \n # Finds the last line in the .txt\n for line in history:\n pass\n lastLine = line\n history.close()\n \n # Checks if the last updated date was today\n if self.get_date() in lastLine:\n return True\n \n # Formats the data from .csv to a Python list\n lastLine = lastLine.split(\",\")\n lastLine.pop(0)\n self.prev = lastLine\n return False\n\n\nclass smsNotification:\n @staticmethod\n def notify(toNumber,message): # Creates SMS notifications; (IMPORTANT) List your Twilio account sid, auth token, and phone number in the token.txt file by tabbing each token\n f = open('token.txt','r')\n accountSid, authToken, fromNumber = f.readlines()\n \n accountSid = accountSid.replace(\"\\n\",\"\")\n authToken = authToken.replace(\"\\n\",\"\")\n fromNumber = fromNumber.replace(\"\\n\",\"\")\n \n client = Client(accountSid, authToken)\n client.messages.create(to=toNumber,from_=fromNumber,body=message)\n print(\"SMS sent\")\n\n\n @staticmethod\n def save_number(paste): # Saves the recently used phone number on file\n numbers = open(\"phoneNumbers.txt\",\"w\")\n for number in paste:\n numbers.write(str(number) + \"\\n\")\n\nclass Graph:\n @staticmethod\n def display_graph(islands,scope=[],graphType='Cases'): # Displays data in a graph format where islands is a list containing the statistics that should be included, the scope is the time period, and the graph type differentiates between cases vs change in cases\n if graphType == 'Cases': # For graphing cases\n df = pd.read_csv('data.csv', index_col = False)\n\n else: # For graphing the change in cases\n df = App.get_df_change()\n if scope[0] == 0: # Adjust the scope to not include the first entry since there is no change observerd on that day\n scope[0] = 1\n\n plt.figure(figsize=(8,8))\n min_ = -1\n max_ = -1\n for island in islands: # Plots data for each island on the same plot\n plt.plot(df[\"Date\"], df[island], label = island)\n if graphType == 'Cases': \n if scope != []:\n if min_ == - 1 and max_ == -1:\n min_ = df[island].get(scope[0])\n max_ = df[island].get(scope[1])\n\n else:\n minNow = df[island].get(scope[0])\n maxNow = df[island].get(scope[1])\n if minNow < min_:\n min_ = minNow\n\n elif maxNow > max_:\n max_ = maxNow\n \n plt.ylim(min_,max_) \n \n title = \"COVID Cases vs Time\"\n if scope != []: # Scales the interval to the scope\n intervals = (scope[1]-scope[0])/4\n if intervals < 1:\n intervals = 1\n \n plt.gca().xaxis.set_major_locator(matplotlib.dates.DayLocator(interval=math.floor(intervals)))\n plt.xlim(scope[0],scope[1]) \n title = title + \" (\" + df[\"Date\"].get(scope[0]) + \" to \" + df[\"Date\"].get(scope[1]) + \")\" # Title formatting\n\n else:\n plt.gca().xaxis.set_major_locator(matplotlib.dates.DayLocator(interval=30)) # Automatically sets the scale if there is no scale\n\n \n plt.xlabel(\"Date\")\n\n if graphType == 'Cases':\n plt.ylabel(\"# of Cases\")\n\n else:\n plt.ylabel(\"Change in Cases\")\n title = title.replace(\"COVID Cases\",\"Change in COVID Cases\")\n\n plt.title(title)\n plt.grid()\n plt.legend()\n plt.show()\n\n \nclass File:\n @staticmethod # Appends the passed file with the passed text\n def append_file(file,text):\n history = open(file,'a')\n history.write(text)\n history.close()\n\nclass App:\n @staticmethod\n def get_df(): # Returns the dataframe\n return pd.read_csv('data.csv', index_col = False)\n\n def format_date(date): # Receives the data and returns the index of the date\n df = pd.read_csv('data.csv', index_col = False)\n for x in range(len(df[\"Date\"])):\n if df[\"Date\"][x] == date:\n return x\n\n def get_last_index(): # Returns the index of the last element in the dataframe\n df = pd.read_csv('data.csv', index_col = False)\n\n for index in range(len(df[\"Date\"])):\n pass\n return index\n\n def get_df_change(): # Returns the change over time dataframe\n df = pd.read_csv('data.csv', index_col = False)\n\n dates = df['Date']\n dates = pd.DataFrame(dates) # Save datafrmae\n df = df.drop(columns=['Date']) # Must drop the dates since the dataframe diff() function will produce an unideal dataframe otherwise\n dfDiff = df.diff()\n dfDiff = dates.join(dfDiff) # Rejoin dataframes\n dfDiff = dfDiff.iloc[1:] # Get rid of bad data from first row\n\n return dfDiff\n \n\n\nif __name__ == \"__main__\":\n data=Hawaii(\"https://health.hawaii.gov/coronavirusdisease2019/\")\n data.do_update()\n lastIndex = App.get_last_index()\n firstIndex = lastIndex - 6 # The scope is automatically set to the past 7 days\n \n Graph.display_graph([\"Total cases\"],[firstIndex,lastIndex],\"Change\") # Displays total cases over the past seven days\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.gca",
"pandas.read_csv",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"pandas.DataFrame",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.grid",
"matplotlib.dates.DayLocator",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
myeonghak/kobert-multi-label-VOC-classifier
|
[
"983524e8331b5e833d85779dfe7521c21bf2d1cd"
] |
[
"voc_classifier/metrics_for_multilabel.py"
] |
[
"# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py\n\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import f1_score\n\n\nimport numpy as np\n\n\ndef mean_precision_k(y_true, y_score, k=10):\n \"\"\"Mean precision at rank k\n Parameters\n ----------\n y_true : array-like, shape = [n_samples]\n Ground truth (true relevance labels).\n y_score : array-like, shape = [n_samples]\n Predicted scores.\n k : int\n Rank.\n Returns\n -------\n mean precision @k : float\n \"\"\"\n\n p_ks = []\n for y_t, y_s in zip(y_true, y_score):\n if np.sum(y_t == 1):\n p_ks.append(ranking_precision_score(y_t, y_s, k=k))\n\n return np.mean(p_ks)\n\n\ndef mean_recall_k(y_true, y_score, k=10):\n \"\"\"Mean recall at rank k\n Parameters\n ----------\n y_true : array-like, shape = [n_samples]\n Ground truth (true relevance labels).\n y_score : array-like, shape = [n_samples]\n Predicted scores.\n k : int\n Rank.\n Returns\n -------\n mean recall @k : float\n \"\"\"\n\n r_ks = []\n for y_t, y_s in zip(y_true, y_score):\n if np.sum(y_t == 1):\n r_ks.append(ranking_recall_score(y_t, y_s, k=k))\n\n return np.mean(r_ks)\n\n\ndef mean_ndcg_score(y_true, y_score, k=10, gains=\"exponential\"):\n \"\"\"Normalized discounted cumulative gain (NDCG) at rank k\n Parameters\n ----------\n y_true : array-like, shape = [n_samples]\n Ground truth (true relevance labels).\n y_score : array-like, shape = [n_samples]\n Predicted scores.\n k : int\n Rank.\n gains : str\n Whether gains should be \"exponential\" (default) or \"linear\".\n Returns\n -------\n Mean NDCG @k : float\n \"\"\"\n\n ndcg_s = []\n for y_t, y_s in zip(y_true, y_score):\n if np.sum(y_t == 1):\n ndcg_s.append(ndcg_score(y_t, y_s, k=k, gains=gains))\n\n return np.mean(ndcg_s)\n\n\ndef mean_rprecision_k(y_true, y_score, k=10):\n \"\"\"Mean precision at rank k\n Parameters\n ----------\n y_true : array-like, shape = [n_samples]\n Ground truth (true relevance labels).\n y_score : array-like, shape = [n_samples]\n Predicted scores.\n k : int\n Rank.\n Returns\n -------\n mean precision @k : float\n \"\"\"\n\n p_ks = []\n for y_t, y_s in zip(y_true, y_score):\n if np.sum(y_t == 1):\n p_ks.append(ranking_rprecision_score(y_t, y_s, k=k))\n\n return np.mean(p_ks)\n\n\ndef ranking_recall_score(y_true, y_score, k=10):\n # https://ils.unc.edu/courses/2013_spring/inls509_001/lectures/10-EvaluationMetrics.pdf\n \"\"\"Recall at rank k\n Parameters\n ----------\n y_true : array-like, shape = [n_samples]\n Ground truth (true relevance labels).\n y_score : array-like, shape = [n_samples]\n Predicted scores.\n k : int\n Rank.\n Returns\n -------\n precision @k : float\n \"\"\"\n unique_y = np.unique(y_true)\n\n if len(unique_y) == 1:\n return ValueError(\"The score cannot be approximated.\")\n elif len(unique_y) > 2:\n raise ValueError(\"Only supported for two relevance levels.\")\n\n pos_label = unique_y[1]\n n_pos = np.sum(y_true == pos_label)\n\n order = np.argsort(y_score)[::-1]\n y_true = np.take(y_true, order[:k])\n n_relevant = np.sum(y_true == pos_label)\n\n return float(n_relevant) / n_pos\n\n\ndef ranking_precision_score(y_true, y_score, k=10):\n \"\"\"Precision at rank k\n Parameters\n ----------\n y_true : array-like, shape = [n_samples]\n Ground truth (true relevance labels).\n y_score : array-like, shape = [n_samples]\n Predicted scores.\n k : int\n Rank.\n Returns\n -------\n precision @k : float\n \"\"\"\n unique_y = np.unique(y_true)\n\n if len(unique_y) == 1:\n return ValueError(\"The score cannot be approximated.\")\n elif len(unique_y) > 2:\n raise ValueError(\"Only supported for two relevance levels.\")\n\n pos_label = unique_y[1]\n\n order = np.argsort(y_score)[::-1]\n y_true = np.take(y_true, order[:k])\n n_relevant = np.sum(y_true == pos_label)\n\n return float(n_relevant) / k\n\n\ndef ranking_rprecision_score(y_true, y_score, k=10):\n \"\"\"Precision at rank k\n Parameters\n ----------\n y_true : array-like, shape = [n_samples]\n Ground truth (true relevance labels).\n y_score : array-like, shape = [n_samples]\n Predicted scores.\n k : int\n Rank.\n Returns\n -------\n precision @k : float\n \"\"\"\n unique_y = np.unique(y_true)\n\n if len(unique_y) == 1:\n return ValueError(\"The score cannot be approximated.\")\n elif len(unique_y) > 2:\n raise ValueError(\"Only supported for two relevance levels.\")\n\n pos_label = unique_y[1]\n n_pos = np.sum(y_true == pos_label)\n\n order = np.argsort(y_score)[::-1]\n y_true = np.take(y_true, order[:k])\n n_relevant = np.sum(y_true == pos_label)\n\n # Divide by min(n_pos, k) such that the best achievable score is always 1.0.\n return float(n_relevant) / min(k, n_pos)\n\n\ndef average_precision_score(y_true, y_score, k=10):\n \"\"\"Average precision at rank k\n Parameters\n ----------\n y_true : array-like, shape = [n_samples]\n Ground truth (true relevance labels).\n y_score : array-like, shape = [n_samples]\n Predicted scores.\n k : int\n Rank.\n Returns\n -------\n average precision @k : float\n \"\"\"\n unique_y = np.unique(y_true)\n\n if len(unique_y) == 1:\n return ValueError(\"The score cannot be approximated.\")\n elif len(unique_y) > 2:\n raise ValueError(\"Only supported for two relevance levels.\")\n\n pos_label = unique_y[1]\n n_pos = np.sum(y_true == pos_label)\n\n order = np.argsort(y_score)[::-1][:min(n_pos, k)]\n y_true = np.asarray(y_true)[order]\n\n score = 0\n for i in range(len(y_true)):\n if y_true[i] == pos_label:\n # Compute precision up to document i\n # i.e, percentage of relevant documents up to document i.\n prec = 0\n for j in range(0, i + 1):\n if y_true[j] == pos_label:\n prec += 1.0\n prec /= (i + 1.0)\n score += prec\n\n if n_pos == 0:\n return 0\n\n return score / n_pos\n\n\ndef dcg_score(y_true, y_score, k=10, gains=\"exponential\"):\n \"\"\"Discounted cumulative gain (DCG) at rank k\n Parameters\n ----------\n y_true : array-like, shape = [n_samples]\n Ground truth (true relevance labels).\n y_score : array-like, shape = [n_samples]\n Predicted scores.\n k : int\n Rank.\n gains : str\n Whether gains should be \"exponential\" (default) or \"linear\".\n Returns\n -------\n DCG @k : float\n \"\"\"\n order = np.argsort(y_score)[::-1]\n y_true = np.take(y_true, order[:k])\n\n if gains == \"exponential\":\n gains = 2 ** y_true - 1\n elif gains == \"linear\":\n gains = y_true\n else:\n raise ValueError(\"Invalid gains option.\")\n\n # highest rank is 1 so +2 instead of +1\n discounts = np.log2(np.arange(len(y_true)) + 2)\n return np.sum(gains / discounts)\n\n\ndef ndcg_score(y_true, y_score, k=10, gains=\"exponential\"):\n \"\"\"Normalized discounted cumulative gain (NDCG) at rank k\n Parameters\n ----------\n y_true : array-like, shape = [n_samples]\n Ground truth (true relevance labels).\n y_score : array-like, shape = [n_samples]\n Predicted scores.\n k : int\n Rank.\n gains : str\n Whether gains should be \"exponential\" (default) or \"linear\".\n Returns\n -------\n NDCG @k : float\n \"\"\"\n best = dcg_score(y_true, y_true, k, gains)\n actual = dcg_score(y_true, y_score, k, gains)\n return actual / best\n\n\n# Alternative API.\n\ndef dcg_from_ranking(y_true, ranking):\n \"\"\"Discounted cumulative gain (DCG) at rank k\n Parameters\n ----------\n y_true : array-like, shape = [n_samples]\n Ground truth (true relevance labels).\n ranking : array-like, shape = [k]\n Document indices, i.e.,\n ranking[0] is the index of top-ranked document,\n ranking[1] is the index of second-ranked document,\n ...\n k : int\n Rank.\n Returns\n -------\n DCG @k : float\n \"\"\"\n y_true = np.asarray(y_true)\n ranking = np.asarray(ranking)\n rel = y_true[ranking]\n gains = 2 ** rel - 1\n discounts = np.log2(np.arange(len(ranking)) + 2)\n return np.sum(gains / discounts)\n\n\ndef ndcg_from_ranking(y_true, ranking):\n \"\"\"Normalized discounted cumulative gain (NDCG) at rank k\n Parameters\n ----------\n y_true : array-like, shape = [n_samples]\n Ground truth (true relevance labels).\n ranking : array-like, shape = [k]\n Document indices, i.e.,\n ranking[0] is the index of top-ranked document,\n ranking[1] is the index of second-ranked document,\n ...\n k : int\n Rank.\n Returns\n -------\n NDCG @k : float\n \"\"\"\n k = len(ranking)\n best_ranking = np.argsort(y_true)[::-1]\n best = dcg_from_ranking(y_true, best_ranking[:k])\n return dcg_from_ranking(y_true, ranking) / best\n\ndef colwise_accuracy(y_true,y_pred):\n y_pred=y_pred.T\n y_true=y_true.T\n acc_list=[]\n for cate in range(0,y_pred.shape[0]):\n acc_list.append(accuracy_score(y_pred[cate],y_true[cate]))\n return sum(acc_list)/len(acc_list)\n\ndef calculate_metrics(pred, target, threshold=0.5):\n\n pred = np.array(pred > threshold, dtype=float)\n\n return {'Accuracy': accuracy_score(y_true=target, y_pred=pred),\n 'Column-wise Accuracy': colwise_accuracy(y_true=target, y_pred=pred),\n 'micro/precision': precision_score(y_true=target, y_pred=pred, average='micro'),\n 'micro/recall': recall_score(y_true=target, y_pred=pred, average='micro'),\n 'micro/f1': f1_score(y_true=target, y_pred=pred, average='micro'),\n 'macro/precision': precision_score(y_true=target, y_pred=pred, average='macro'),\n 'macro/recall': recall_score(y_true=target, y_pred=pred, average='macro'),\n 'macro/f1': f1_score(y_true=target, y_pred=pred, average='macro'),\n 'samples/precision': precision_score(y_true=target, y_pred=pred, average='samples'),\n 'samples/recall': recall_score(y_true=target, y_pred=pred, average='samples'),\n 'samples/f1': f1_score(y_true=target, y_pred=pred, average='samples'),\n }"
] |
[
[
"numpy.take",
"numpy.unique",
"numpy.asarray",
"sklearn.metrics.precision_score",
"numpy.mean",
"numpy.argsort",
"sklearn.metrics.f1_score",
"numpy.array",
"sklearn.metrics.recall_score",
"numpy.sum",
"sklearn.metrics.accuracy_score"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gitpharm01/Parapose
|
[
"220f3af30011e1dd7c0d5f20660a1dd01eab63db"
] |
[
"imageLoader.py"
] |
[
"import numpy as np\nimport random\nimport os\nimport json\nimport math\nimport cv2\n\ndef getPaddedROI(img, center_x, center_y, width, height):\n #print(str(int(center_x)) + \",\" + str(int(center_y)))\n paddingColor = [0,0,0]\n top_left_x = center_x - int(width/2)-1\n #print(\"top_left_x:\")\n #print(top_left_x)\n top_left_y = center_y - int(height/2)-1\n #print(\"top_left_y:\")\n #print(top_left_y)\n\n bottom_right_x = center_x + int(width/2) \n bottom_right_y = center_y + int(height/2) \n #print (\"bottom_right_x / y\")\n #print(str(bottom_right_x) + \" / \" + str(bottom_right_y))\n\n img_height = np.size(img, 0)\n img_width = np.size(img, 1)\n if(top_left_x <0 or top_left_y <0 or bottom_right_x >img_width or bottom_right_y > img_height):\n #border padding needed\n border_left = 0\n border_right = 0\n border_top= 0\n border_bottom= 0\n\n if(top_left_x < 0):\n width = width + top_left_x\n border_left = -1 * top_left_x\n top_left_x = 0\n\n if(top_left_y < 0):\n height = height + top_left_y\n border_top = -1 * top_left_y\n top_left_y = 0\n\n if(bottom_right_x > img_width):\n width = width -(bottom_right_x - img_width)\n border_right = bottom_right_x - img_width\n \n if(bottom_right_y> img_height):\n height = height -(bottom_right_y - img_height)\n border_bottom = bottom_right_y - img_height\n #print(border_left)\n #print(border_right)\n #print(border_top)\n #print(border_bottom)\n\n img_roi = img[top_left_y : bottom_right_y ,top_left_x : bottom_right_x ]\n #cv2.imshow(\"originalROI\",img_roi)\n img_roi = cv2.copyMakeBorder(img_roi, border_top,border_bottom,border_left, border_right, cv2.BORDER_CONSTANT,value=paddingColor)\n else:\n img_roi = img[top_left_y : bottom_right_y ,top_left_x : bottom_right_x ]\n return img_roi\n\n#similarity map converter\n#convert 16 target ground truth label(coordinates) into 16 Distance maps\n#Each map have value '0' on the kepoint and '32'(according to the length of the generated Hash codes) on non-keypoint areas\ndef make_heatmap(emptymap ,joint_idx, point, sigma):\n point_x,point_y = point\n _, height, width = emptymap.shape[:3]\n\n th= 4.605\n delta = math.sqrt(th * 2)\n x0 = int(max(0, point_x - delta * sigma))\n y0 = int(max(0, point_y - delta * sigma))\n \n x1 = int(min(width, point_x + delta * sigma))\n y1 = int(min(height, point_y + delta * sigma))\n \n for y in range(y0,y1):\n for x in range(x0,x1):\n d = (x - point_x)**2 + (y - point_y)**2\n exp = d / 2.0 / sigma / sigma\n if exp > th:\n continue\n emptymap[joint_idx][y][x] = max (emptymap[joint_idx][y][x], math.exp(-exp))\n emptymap[joint_idx][y][x] = min (emptymap[joint_idx][y][x], 1.0) \n\ndef training_data_feeder(joint_data_path, train_val_path, imgpath, input_size, hint_roi_size):\n #load trainvalset data,\n train_val = open(train_val_path).readlines()\n train_groups = json.loads(train_val[0].strip())[\"train_set\"]\n #print(train_groups)\n\n #load one of train set indecies\n index = random.choice(train_groups)\n #print(index)\n #create path object to the image directory( index \"0\" to dir_name \"001\")\n dir_name = str(index+1)\n if((index+1) < 100):\n dir_name =\"0\"+ dir_name \n if((index+1) < 10):\n dir_name = \"0\" + dir_name\n #print(dir_name)\n dir_path = imgpath + dir_name + \"/\"\n #print(dir_path)\n \n \n #ramdomly load three images, get file names\n #from \"sample_names\" will load first two names as h_img1 h_iimg2, third name as t_img\n file_list = []\n for file in os.listdir(dir_path):\n if len(file) > 5:\n file_list.append(file) \n #print(file_list)\n #print(\"selected: \")\n sample_name = random.sample(file_list, 3)\n #print(sample_name)\n #load image files\n h_img1 = cv2.imread(dir_path + sample_name[0])\n h_img2 = cv2.imread(dir_path + sample_name[1])\n t_img = cv2.imread(dir_path + sample_name[2])\n\n #load corresponding joint data as labels\n h_label1 = []\n h_label2 = []\n t_label = []\n \n label_data = open(joint_data_path).readlines()\n for i in range( len(label_data)):\n datum = json.loads(label_data[i].strip())\n if(datum[\"filename\"] == sample_name[0]):\n for joint in datum[\"joint_pos\"]:\n h_label1.append(joint[1]) \n #print(h_label1) \n elif(datum[\"filename\"] == sample_name[1]):\n for joint in datum[\"joint_pos\"]:\n h_label2.append(joint[1])\n elif(datum[\"filename\"] == sample_name[2]):\n for joint in datum[\"joint_pos\"]:\n t_label.append(joint[1])\n\n #resize the two images and get resize ratios\n resize_ratioh1 = (input_size / h_img1.shape[1] , input_size / h_img1.shape[0])\n resize_ratioh2 = (input_size / h_img2.shape[1] , input_size / h_img2.shape[0])\n resize_ratiot = (1 / t_img.shape[1] , 1 / t_img.shape[0])\n \n h_img1= cv2.resize(h_img1,(input_size,input_size))\n h_img2= cv2.resize(h_img2,(input_size,input_size))\n t_img = cv2.resize(t_img,(input_size,input_size))\n \n #Convert the joint position according to the resize ratios\n #crop rois from two hint images to get the hintsets\n #img_point = None\n hintSet01 = []\n hintSet02 = []\n \n for joint in h_label1:\n joint[0] = joint[0]*resize_ratioh1[0]\n joint[1] = joint[1]*resize_ratioh1[1]\n for i in range(len(h_label1)):\n tmp = getPaddedROI(h_img1, int(h_label1[i][0]), int(h_label1[i][1]), hint_roi_size, hint_roi_size)\n hintSet01.append(tmp)\n #cv2.imshow(\"tmp\",tmp)\n #cv2.imshow(\"h_img1\",h_img1)\n #for tmp in hintSet01:\n # cv2.imshow(\"tmp\",tmp)\n # cv2.waitKey(0)\n for joint in h_label2:\n joint[0] = joint[0]*resize_ratioh2[0]\n joint[1] = joint[1]*resize_ratioh2[1]\n for i in range(len(h_label2)):\n tmp = getPaddedROI(h_img2, int(h_label2[i][0]), int(h_label2[i][1]), hint_roi_size, hint_roi_size)\n hintSet02.append(tmp)\n #Normalize the value by dividing with input_size\n #\n joint_idx = 0\n heatmap = np.zeros((16, 76, 76) , dtype = np.float32)\n for joint in t_label:\n \n point =[ joint[0]*resize_ratiot[0] * 76, joint[1]*resize_ratiot[1] *76 ]\n make_heatmap(heatmap, joint_idx, point, 1) #sigma = 1\n joint_idx +=1\n heatmap = 1 - heatmap\n return hintSet01, hintSet02, t_img, heatmap \n \n #cv2.imshow(\"img_point\",img_point)\n #cv2.waitKey(0)\n #cv2.imshow(\"h_img1\",h_img1)\n #cv2.imshow(\"h_img2\",h_img2)\n #cv2.imshow(\"t_img\",t_img)\n #cv2.waitKey(0)\n\n #define sub function crop roi\n #return roi*16 \n\n#crop rois x 2 times to get 2 hintsets\n\n#return hintset01,hintset02,target image, target label\n#joint_data_path = \"./custom_data.json\"\n#train_val_path = \"./train_val_indices.json\"\n#imgpath = \"./000/\"\n#input_size = 400\n#hint_roi = 14\n\n#hintSet01,hintSet02,t_img, heatmap = training_data_feeder(joint_data_path, train_val_path, imgpath, input_size, hint_roi )\n\n#print(np.shape(heatmap))\n#cv2.imshow('target_image',t_img)\n#for i in range(16):\n# cv2.imshow('heat map',heatmap[i])\n# cv2.waitKey(0)\n"
] |
[
[
"numpy.size",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
MichaelGoodale/opensauce-python
|
[
"03c278ca92b150188821dadfc9702ff9f939aa4e",
"03c278ca92b150188821dadfc9702ff9f939aa4e",
"03c278ca92b150188821dadfc9702ff9f939aa4e"
] |
[
"tools/convert_json_to_mat.py",
"test/test_shrp.py",
"opensauce/shrp.py"
] |
[
"# Script to convert json into proprietary .mat files\n\n# Licensed under Apache v2 (see LICENSE)\n\nimport sys\nimport os\nimport glob\nimport json\nfrom scipy.io import savemat\n\n\ndef main(json_dir, out_dir):\n \"\"\" Script to convert all .json files in json_dir into corresponding .mat\n files in out_dir\n\n .mat files have the same basename as the .json files\n\n This script is meant for data files that contain data from\n OpenSauce / VoiceSauce variables.\n \"\"\"\n # Find all .json files in json_dir\n json_files = glob.glob(os.path.join(json_dir, '*.json'))\n\n # Iterate through each .mat file\n for json_file in json_files:\n with open(json_file) as f:\n json_dict = json.load(f)\n # Write json dict to mat\n # Check that output directory exists, if not create it\n if not os.path.isdir(out_dir):\n os.makedirs(out_dir)\n fn = os.path.join(out_dir, os.path.splitext(os.path.basename(json_file))[0]) + '.mat'\n savemat(fn, json_dict)\n print('Wrote data in {} to {}'.format(json_file, fn))\n\nif __name__ == '__main__':\n main(sys.argv[1], sys.argv[2])\n",
"import os\nimport numpy as np\n\nfrom opensauce.shrp import (window, toframes, two_max, compute_shr,\n get_log_spectrum, shrp, shr_pitch, vda,\n ethreshold, postvda, zcr)\nfrom opensauce.helpers import wavread\n\nfrom test.support import TestCase, parameterize, load_json, sound_file_path\n\n\n@parameterize\nclass TestWindow(TestCase):\n\n window_params = dict(\n rect10=('rect', 10, None, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]),\n rect3=('rectangular', 3, None, [1, 1, 1]),\n rect4=('rectan', 4, None, [1, 1, 1, 1]),\n tria10=('tria', 10, None,\n [0.00000, 0.22222, 0.44444, 0.66667, 0.88889,\n 0.88889, 0.66667, 0.44444, 0.22222, 0.00000]),\n tria3=('triangular', 3, None, [0, 1, 0]),\n hann10=('hann', 10, None,\n [0.00000, 0.11698, 0.41318, 0.75000, 0.96985,\n 0.96985, 0.75000, 0.41318, 0.11698, 0.00000]),\n hann3=('hanning', 3, None, [0, 1, 0]),\n hamm10=('hamm', 10, None,\n [0.080000, 0.187620, 0.460122, 0.770000, 0.972259,\n 0.972259, 0.770000, 0.460122, 0.187620, 0.080000]),\n hamm3=('hamming', 3, None, [0.080000, 1.00000, 0.080000]),\n blac10=('blac', 10, None,\n [-1.3878e-17, 5.0870e-02, 2.5800e-01, 6.3000e-01, 9.5113e-01,\n 9.5113e-01, 6.3000e-01, 2.5800e-01, 5.0870e-02, -1.3878e-17]),\n black3=('blackman', 3, None, [-1.3878e-17, 1.0000e+00, -1.3878e-17]),\n # XXX: I don't know what beta is, and don't need to find the answer for\n # this project.\n #kais10=('kais', 10, ?, []),\n #kais10_2=('kaiser', 10, ?, []),\n #kais3=('kais', 3, ?, []),\n #kais3_2=('kais', 3, ?, []),\n )\n\n def window_as_window_args(self, window_type, window_width, beta, expected):\n res = window(window_width, window_type, beta)\n self.assertIsInstance(res, np.ndarray)\n # octave gives results to five places (single precision float?)\n for i in range(len(expected)):\n self.assertAlmostEqual(res[i], expected[i], places=5,\n msg='at index {}:\\n{}\\n vs\\n{}'.format(\n i, res, expected))\n\n def test_window_bad_window_type(self):\n with self.assertRaises(ValueError):\n window(10, 'bad')\n with self.assertRaises(ValueError):\n window(10, 'longerbad')\n with self.assertRaises(ValueError):\n window(10, 'rec') # Not four chars.\n\n def test_kais_not_implemented(self):\n with self.assertRaises(NotImplementedError):\n window(10, 'kais', 0)\n\n\nclass TestToframes(TestCase):\n\n def test_with_matlab_data(self):\n data = load_json(os.path.join('shrp', 'toframes_data'))\n res = toframes(data['input'],\n data['curpos'].astype(int)-1,\n int(data['segmentlen']),\n 'hamm')\n np.testing.assert_array_almost_equal(res, data['frames'])\n\n\n@parameterize\nclass Test_two_max(TestCase):\n\n matlab_fn_params = (['twomax_data'], ['two_max_183'])\n\n def matlab_fn_as_matlab_input_data(self, filename):\n data = load_json(os.path.join('shrp',filename))\n mag, index = two_max(data['x'],\n int(data['lowerbound'])-1,\n int(data['upperbound'])-1,\n data['unitlen'])\n np.testing.assert_array_almost_equal(mag, data['mag'])\n np.testing.assert_array_almost_equal(index, int(data['index'])-1)\n\n def test_second_peak_index(self):\n data = load_json(os.path.join('shrp', 'twomax_data'))\n x = data['x']\n for i in range(142, 146):\n # Zap the values in the second peak range to exercise the branch.\n x[i] = 0.0001*i\n mag, index = two_max(x,\n int(data['lowerbound'])-1,\n int(data['upperbound'])-1,\n data['unitlen'])\n np.testing.assert_array_almost_equal(mag,\n np.append(data['mag'], 0.0145))\n np.testing.assert_array_equal(index, [int(data['index'])-1, 145])\n\n\n@parameterize\nclass Test_compute_shr(TestCase):\n\n matlab_fn_params = (['ComputeSHR_data'], ['compute_shr_183'])\n\n def matlab_fn_as_matlab_input_data(self, filename):\n data = load_json(os.path.join('shrp', filename))\n peak_index, shr, shshift, index = compute_shr(\n data['log_spectrum'],\n data['min_bin'],\n data['startpos'].astype(int)-1,\n data['endpos'].astype(int)-1,\n int(data['lowerbound'])-1,\n int(data['upperbound'])-1,\n int(data['N']),\n int(data['shift_units']),\n data['SHR_Threshold'])\n np.testing.assert_array_equal(peak_index, int(data['peak_index'])-1)\n np.testing.assert_array_almost_equal(shr, data['SHR'])\n np.testing.assert_array_almost_equal(shshift, data['shshift'])\n np.testing.assert_array_almost_equal(index, data['index']-1)\n\n # XXX Need test data that exercises each of the if branches. The\n # one above has only one peak. Test_shrp exercises more.\n\n\nclass Test_get_log_spectrum(TestCase):\n\n def test_with_matlab_data(self):\n data = load_json(os.path.join('shrp', 'GetLogSpectrum_data'))\n interp_amplitude = get_log_spectrum(\n data['segment'],\n int(data['fftlen']),\n int(data['limit']) - 1,\n data['logf'],\n data['interp_logf'])\n np.testing.assert_array_almost_equal(interp_amplitude,\n data['interp_amplitude'])\n\n\nclass Test_shrp(TestCase):\n\n def test_with_matlab_data(self):\n data = load_json(os.path.join('shrp', 'shrp_data'))\n f0_time, f0_value, shr, f0_candidates = shrp(\n data['Y'],\n int(data['Fs']),\n [int(x) for x in data['F0MinMax']],\n int(data['frame_length']),\n int(data['timestep']),\n data['SHR_Threshold'],\n data['ceiling'],\n data['med_smooth'],\n data['CHECK_VOICING'])\n np.testing.assert_array_almost_equal(f0_time, data['f0_time'])\n np.testing.assert_array_almost_equal(f0_value, data['f0_value'])\n np.testing.assert_array_almost_equal(shr, data['SHR'])\n np.testing.assert_array_almost_equal(f0_candidates,\n data['f0_candidates'])\n\n def test_check_voicing(self):\n data = load_json(os.path.join('shrp', 'shrp_data'))\n with self.assertRaises(NotImplementedError):\n f0_time, f0_value, shr, f0_candidates = shrp(\n data['Y'],\n int(data['Fs']),\n [int(x) for x in data['F0MinMax']],\n int(data['frame_length']),\n int(data['timestep']),\n data['SHR_Threshold'],\n data['ceiling'],\n data['med_smooth'],\n CHECK_VOICING=True)\n\n def test_med_smooth_greater_than_zero(self):\n data = load_json(os.path.join('shrp', 'shrp_data'))\n with self.assertRaises(NotImplementedError):\n f0_time, f0_value, shr, f0_candidates = shrp(\n data['Y'],\n int(data['Fs']),\n [int(x) for x in data['F0MinMax']],\n int(data['frame_length']),\n int(data['timestep']),\n data['SHR_Threshold'],\n data['ceiling'],\n med_smooth=5,\n CHECK_VOICING=False)\n\nclass Test_shr_pitch(TestCase):\n\n def test_with_matlab_data(self):\n data = load_json(os.path.join('shrp', 'shr_pitch_data'))\n wav_data, wavdata_int, fps = wavread(sound_file_path('beijing_f3_50_a.wav'))\n shr, f0 = shr_pitch(wav_data, fps, 25, 1, 50, 550, 0.4, 5, 200)\n np.testing.assert_array_almost_equal(f0, data['F0'])\n np.testing.assert_array_almost_equal(shr, data['SHR'])\n\n def test_with_min_max_pitch_not_specified(self):\n data = load_json(os.path.join('shrp', 'shr_pitch_data'))\n wav_data, wavdata_int, fps = wavread(sound_file_path('beijing_f3_50_a.wav'))\n\n with self.assertRaisesRegex(ValueError, 'none or both of min_pitch, max_pitch must be specified'):\n shr, f0 = shr_pitch(wav_data, fps, min_pitch=50, datalen=200)\n\n with self.assertRaisesRegex(ValueError, 'none or both of min_pitch, max_pitch must be specified'):\n shr, f0 = shr_pitch(wav_data, fps, max_pitch=550, datalen=200)\n\nclass Test_not_implemented(TestCase):\n\n def test_vda(self):\n with self.assertRaises(NotImplementedError):\n vda(None, None, None, None)\n\n def test_ethreshold(self):\n with self.assertRaises(NotImplementedError):\n ethreshold(None)\n\n def test_postvda(self):\n with self.assertRaises(NotImplementedError):\n postvda(None, None, None, None)\n\n def test_zcr(self):\n with self.assertRaises(NotImplementedError):\n zcr(None, None)\n",
"\"\"\" SHRP - a pitch determination algorithm based on Subharmonic-to-Harmonic\nRatio.\n\n\"\"\"\n\n# Licensed under Apache v2 (see LICENSE)\n\nfrom __future__ import division\n\nimport numpy as np\nfrom scipy.fftpack import fft\nfrom scipy.interpolate import interp1d\n\nfrom opensauce.helpers import round_half_away_from_zero\n\n# Comments in quotes are copied from the matlab source.\n\n\n# ---- func_GetSHRP ----\n\n# Based func_GetSHRP.m from voicesauce v1.25, by Kristine Yu, which in turn was\n# based on func_PraatPitch.m by Yen-Liang Shue.\n\ndef shr_pitch(wav_data, fps, window_length=None, frame_shift=None,\n min_pitch=None, max_pitch=None, shr_threshold=None,\n frame_precision=None, datalen=None):\n \"\"\"Return a list of Subharmonic ratios and F0 values computed from wav_data.\n\n wav_data a vector of data read from a wav file\n fps frames rate of the wav file\n windows_length width of analysis window\n frame_shift distance to move window for each analysis iteration\n min_pitch minimum pitch in Hz used in SHR estimation\n max_pitch maximum pitch in Hz used in SHR estimation\n shr_threshold subharmonic-to-harmonic ratio threshold in the range of\n [0,1]. If the estimated SHR is greater than the\n threshold, the subharmonic is regarded as F0 candidate.\n Otherwise, the harmonic is favored.\n frame_precision maximum number of frames the time alignment can be off\n by when selecting values for output\n datalen the number of values in the output vector; leftover\n input data is dropped, and the vector is padded\n with NaNs when no input data corresponds to\n the output frame time.\n\n \"\"\"\n # XXX the octave code produces 201 output points given a datalen\n # of 200. Presumably a bug in the matlab code. But we'll emulate it.\n datalen += 1\n kw = {}\n # XXX This is awkward, fix it in refactoring later.\n if len(list(filter(None, (min_pitch, max_pitch)))) == 1:\n raise ValueError('none or both of min_pitch, max_pitch must be specified')\n elif min_pitch:\n kw['F0MinMax'] = (min_pitch, max_pitch)\n if window_length is not None:\n kw['frame_length'] = window_length\n if frame_shift is not None:\n kw['timestep'] = frame_shift\n if shr_threshold is not None:\n kw['SHR_Threshold'] = shr_threshold\n f0_time, f0_value, shr_value, f0_candidates = shrp(wav_data, fps, **kw)\n\n # \"Postprocess subharmonic-harmonic ratios and f0 tracks\"\n\n # \"Initialize F0 and subharmonic-harmonic ratio values\"\n F0 = np.full(datalen, np.nan)\n SHR = np.full(datalen, np.nan)\n\n # \"time locations rounded to nearest ms\"\n #\n # VoiceSauce uses Matlab, and Matlab's round function uses the\n # round-half-away-from-zero method. However, NumPy uses the\n # round-half-to-even method. So we use our own round-half-away-from-zero\n # method here.\n t = round_half_away_from_zero(f0_time)\n\n # \"Like timecoures from Praat, we might have missing values so pad with NaNs at\n # beginning and end if necessary.\"\n # RDM XXX note that it looks to me like after the leading NaN padding this\n # actually ends up padding with frame_precision copies of the first frame\n # that comes within the precision window, and then offsets all of the\n # others by frame_precision*frame_shift. This algorithm could use a lot of\n # improvement I think. But for now, we are emulating the voicesauce code.\n start = 0\n finish = t[-1]\n increment = frame_shift\n for k in np.arange(start, finish, increment):\n # \"try to find the closest value\"\n dabs = np.abs(t - k)\n inx = dabs.argmin()\n if dabs[inx] > frame_precision * frame_shift:\n # \"no valid value found\"\n continue\n n = int(round(k / frame_shift)) + 1\n if n < 0 or n >= datalen:\n continue\n F0[n] = f0_value[inx]\n SHR[n] = shr_value[inx]\n # \"I eventually would like to get candidates as well\"\n return SHR, F0\n\n\n# Remainder based on the shrp.m from voicesauce v1.25.\n# XXX: This is not a full re-implementation of shrp.m: it only implements those\n# functions actually used by the voicesauce func_GetSHRP function.\n\n# Original copyright notice from above referenced shrp.m:\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n#\n# Permission to use, copy, modify, and distribute this software without fee is\n# hereby granted FOR RESEARCH PURPOSES only, provided that this copyright\n# notice appears in all copies and in all supporting documentation.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n#\n# For details of the algorithm, please see Sun, X.,\"Pitch determination and\n# voice quality analysis using subharmonic-to-harmonic ratio\" To appear in\n# the Proc. of ICASSP2002, Orlando, Florida, May 13 -17, 2002. For update\n# information, please check http://mel.speech.nwu.edu/sunxj/pda.htm.\n#\n# Copyright (c) 2001 Xuejing Sun\n# Department of Communication Sciences and Disorders\n# Northwestern University, USA\n# [email protected]\n#\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n\n# Function definitions are ordered the same as in the matlab source.\n\n\n# ---- shrp -----\n\ndef shrp(Y, Fs, F0MinMax=[50, 500], frame_length=40, timestep=10,\n SHR_Threshold=0.4, ceiling=1250, med_smooth=0, CHECK_VOICING=0):\n \"\"\"Return pitches for list of samples using subharmonic-to-harmonic ratio.\n\n Given:\n\n Y input data\n Fs sampling frequency (e.g.: 16000 Hz)\n F0MinMax tuple [minf0 maxf0]; default: [50 550]\n quick solutions:\n for male speech: [50 250]\n for female speech: [120 400]\n frame_length length of each frame in milliseconds (default: 40 ms)\n TimeStep interval for updating short-term analysis in\n millisecond (default: 10 ms)\n SHR_Threshold subharmonic-to-harmonic ratio threshold in the range of\n [0,1] (default: 0.4). If the estimated SHR is\n greater than the threshold, the subharmonic is\n regarded as F0 candidate. Otherwise, the harmonic\n is favored.\n Ceiling upper bound of the frequencies that are used for\n estimating pitch. (default: 1250 Hz)\n med_smooth the order of the median smoothing (default: 0 - no\n smoothing)\n CHECK_VOICING NOT IMPLEMENTED\n\n Return:\n\n f0_time: an array of the times for the F0 points\n f0_value: an array of the F0 values\n SHR: an array of the subharmonic-to-harmonic ratio for each\n frame\n f0_candidates: a matrix of the f0 candidates for each frame.\n Currently two f0 values generated for each frame.\n Each row (a frame) contains two values in\n increasing order, i.e., [low_f0 higher_f0]. For\n SHR=0, the first f0 is 0. The purpose of this is\n that when you want to test different SHR\n thresholds, you don't need to re-run the whole\n algorithm. You can choose to select the lower or\n higher value based on the shr value of this frame.\n \"\"\"\n minf0, maxf0 = F0MinMax\n segmentduration = frame_length\n\n # \"--- pre-processing input signal ---\"\n # \"remove DC component\"\n Y = Y - np.mean(Y)\n # \"normalization\"\n Y = Y/np.max(np.abs(Y))\n total_len = len(Y)\n # \"--- specify some algorithm-specific thresholds ---\"\n # \"for FFT length\"\n interpolation_depth = 0.5\n # \"--- derived thresholds specific to the algorithm ---\"\n maxlogf = np.log2(maxf0 / 2)\n # \"the search region to compute SHR is as low as 0.5 minf0\"\n minlogf = np.log2(minf0 / 2)\n # \"maximum number harmonics\"\n N = int(np.floor(ceiling / minf0))\n m = int(N % 2)\n N = N - m\n # \"In fact, in most cases we don't need to multiply N by 4 and get equally\n # good results yet much faster.\"\n N = N * 4\n # \"derive how many frames we have based on segment length and timestep.\"\n segmentlen = int(np.around(segmentduration * (Fs / 1000)))\n inc = int(np.around(timestep * (Fs / 1000)))\n nf = int(np.fix((total_len - segmentlen + inc) / inc))\n n = np.arange(nf)\n # \"anchor time for each frame, the middle point\"\n f0_time = np.transpose((n * timestep + segmentduration/2))\n # f0_time = np.transpose(((n - 1) * timestep)) # anchor starting from zero\n # \"--- determine FFT length ---\"\n fftlen = 1\n while fftlen < segmentlen * (1 + interpolation_depth):\n fftlen = fftlen * 2\n # \"--- derive linear and log frequency scale ---\"\n # \"we ignore frequency 0 here since we need to do log transformation later\n # and won't use it anyway.\"\n frequency = Fs * np.arange(1, fftlen/2+1) / fftlen\n limit = np.where(frequency >= ceiling)[0][0]\n frequency = frequency[0:limit+1]\n logf = np.log2(frequency)\n # \"clear some variables to save memory\"\n del frequency\n # \"the minimum distance between two points after interpolation\"\n min_bin = logf[-1] - logf[-2]\n # \"shift distance\"\n shift = np.log2(N)\n # \"the number of unit on the log x-axis\"\n shift_units = int(np.around(shift/min_bin))\n i = np.arange(2, N+1)\n # \"--- the followings are universal for all the frames ---\"\n # \"find out all the start position of each shift\"\n startpos = shift_units + 1 - np.around(np.log2(i) / min_bin).astype(int)\n # \"find out those positions that are less than 1\"\n index = np.where(startpos < 1)[0]\n # set them to 1 since the array index starts from 1 in matlab\"\n startpos[index] = 1\n # Correct for the fact that python is 0 origined, not 1.\n # XXX: I wonder if keeping the zeros and not doing this subtraction\n # would actually be more accurate. Probably makes no real difference.\n startpos = startpos - 1\n interp_logf = np.arange(logf[0], logf[-1], min_bin)\n # \"new length of the amplitude spectrum after interpolation\"\n interp_len = len(interp_logf)\n totallen = shift_units + interp_len\n endpos = startpos + interp_len - 1\n index = np.where(endpos >= totallen)[0]\n # \"make sure all the end positions not greater than the total length of\n # the shift spectrum\"\n endpos[index] = totallen - 1\n # \"the linear Hz scale derived from the interpolated log scale\"\n newfre = np.power(2, interp_logf)\n # \"find out the index of upper bound of search region on the log frequency\n # scale.\"\n upperbound = np.where(interp_logf >= maxlogf)[0][0]\n # \"find out the index of lower bound of search region on the log frequency\n # scale.\"\n lowerbound = np.where(interp_logf >= minlogf)[0][0]\n # \"--- segmentation of speech ---\"\n # \"position for each frame in terms of index, not time\"\n curpos = np.around(f0_time / 1000 * Fs).astype(int) - 1\n frames = toframes(Y, curpos, segmentlen, 'hamm')\n nf, framelen = frames.shape\n del Y\n # \"--- initialize vectors for f0 time, f0 values, and SHR ---\"\n f0_value = np.zeros(nf)\n SHR = np.zeros(nf)\n f0_time = f0_time[0:nf+1]\n f0_candidates = np.zeros((nf, 2))\n # \"--- voicing determination ---\"\n if CHECK_VOICING:\n raise NotImplementedError\n #NoiseFloor=sum(frames(1,:).^2);\n #voicing=vda(frames,segmentduration/1000,NoiseFloor);\n else:\n voicing = np.ones(nf)\n # \"--- the main loop ---\"\n curf0 = 0\n cur_SHR = 0\n cur_cand1 = 0\n cur_cand2 = 0\n for n in range(nf):\n segment = frames[n, :]\n if voicing[n] == 0:\n curf0 = 0\n cur_SHR = 0\n else:\n log_spectrum = get_log_spectrum(\n segment,\n fftlen,\n limit,\n logf,\n interp_logf)\n peak_index, cur_SHR, shshift, all_peak_indices = compute_shr(\n log_spectrum,\n min_bin,\n startpos,\n endpos,\n lowerbound,\n upperbound,\n N,\n shift_units,\n SHR_Threshold)\n # \"-1 indicates a possibly unvoiced frame, if CHECK_VOICING, set f0\n # to 0, otherwise uses previous value\"\n if peak_index == -1:\n if CHECK_VOICING: # pragma: no cover\n curf0 = 0\n cur_cand1 = 0\n cur_cand2 = 0\n else:\n curf0 = newfre[peak_index] * 2\n if curf0 > maxf0:\n curf0 = curf0 / 2\n if len(all_peak_indices) == 1:\n cur_cand1 = 0\n cur_cand2 = newfre[all_peak_indices[0]] * 2\n else:\n cur_cand1 = newfre[all_peak_indices[0]] * 2\n cur_cand2 = newfre[all_peak_indices[1]] * 2\n if cur_cand1 > maxf0:\n cur_cand1 = cur_cand1 / 2\n if cur_cand2 > maxf0:\n cur_cand2 = cur_cand2 / 2\n if CHECK_VOICING: # pragma: no cover\n raise NotImplementedError\n #voicing(n)=postvda(segment,curf0,Fs);\n #if (voicing(n)==0)\n # curf0=0;\n #end\n f0_value[n] = curf0\n SHR[n] = cur_SHR\n f0_candidates[n, 0] = cur_cand1\n f0_candidates[n, 1] = cur_cand2\n # \"--- post-processing ---\"\n if med_smooth > 0:\n raise NotImplementedError\n # medsmooth is by the same author but is not included in voicesauce.\n # f0_value = medsmooth(f0_value, med_smooth)\n return f0_time, f0_value, SHR, f0_candidates\n\n\n# ---- GetLogSpectrum -----\n\ndef get_log_spectrum(segment, fftlen, limit, logf, interp_logf):\n spectra = fft(segment, fftlen)\n # \"fftlen is always even here.\"\n amplitude = np.abs(spectra[0:fftlen//2+1])\n # \"ignore the zero frequency component\"\n amplitude = amplitude[1:limit+2]\n interp_amplitude = interp1d(logf, amplitude)(interp_logf)\n interp_amplitude = interp_amplitude - min(interp_amplitude)\n return interp_amplitude\n\n\n# ---- ComputeSHR -----\n\ndef compute_shr(log_spectrum, min_bin, startpos, endpos, lowerbound, upperbound,\n n, shift_units, shr_threshold):\n \"\"\" \"compute subharmonic-to-harmonic ratio for a short-term signal\"\n\n returns peak_index = -1 if frame appears to be unvoiced.\n \"\"\"\n len_spectrum = len(log_spectrum)\n total_len = shift_units + len_spectrum\n # \"initialize the subharmonic shift matrix; each row corresponds to a shift\n # version\"\n shshift = np.zeros((n, total_len))\n # \"place the spectrum at the right end of the first row\"\n shshift[0, total_len-len_spectrum:total_len] = log_spectrum\n # \"note that here startpos and endpos has n-1 rows, so we start from 2\"\n # \"the first row in shshift is the original log spectrum\"\n # Actually we start from 1 since python is zero-origined.\n for i in range(1, n):\n # \"store each shifted sequence\"\n shshift[i, startpos[i-1]:endpos[i-1]+1] = (\n log_spectrum[:endpos[i-1]-startpos[i-1]+1])\n # \"we don't need the stuff smaller than shift_units\"\n shshift = shshift[:, shift_units:total_len]\n # odd and even are reversed from matlab due to different origin\n shseven = sum(shshift[0:n:2, :], 0)\n shsodd = sum(shshift[1:n-1:2, :], 0)\n difference = shsodd - shseven\n # \"peak picking process\"\n shr = 0\n # \"only find two maxima\"\n mag, index = two_max(difference, lowerbound, upperbound, min_bin)\n # \"first mag is always the maximum, the second, if there is, is the second\n # max\"\n num_pitch_candidates = len(mag)\n if num_pitch_candidates == 1:\n # \"this is possible, mainly due to we put a constraint on search region,\n # i.e., f0 range\"\n if mag <= 0:\n # \"this must be an unvoiced frame\"\n peak_index = -1\n return peak_index, shr, shshift, index\n peak_index = index\n shr = 0\n else:\n shr = (mag[0]-mag[1]) / (mag[0]+mag[1])\n if shr <= shr_threshold:\n # \"subharmonic is weak, so favor the harmonic\"\n peak_index = index[1]\n else:\n # \"subharmonic is strong, so favor the subharmonic as F0\"\n peak_index = index[0]\n return peak_index, shr, shshift, index\n\n\n# ---- twomax -----\n\ndef two_max(x, lowerbound, upperbound, unit_len):\n \"\"\"Return up to two successive maximum peaks and their indices in x.\n\n Return the magnitudes of the peaks and the indices as two lists.\n If the first maximum is less than zero, just return it. Otherwise\n look to the right of the first maximum, and if there is a second\n maximum that is greater than zero, add that to the returned lists.\n\n lowerbound and upperbound comprise a closed interval, unlike the\n normal python half closed interval. [RDM XXX: fix this?]\n\n \"\"\"\n # XXX The above description is not completely accurate: there's a window to\n # the search for the second peak, but I don't understand the goal well\n # enough to describe it better, and the original comments are less precise.\n max_index = min(upperbound, len(x)-1)\n # \"find the maximum value\"\n mag = np.array([np.amax(x[lowerbound:upperbound+1])])\n index = np.where(x == mag)[0]\n if mag < 0:\n return mag, index\n harmonics = 2\n limit = 0.0625 # \"1/8 octave\"\n startpos = index[0] + int(round(np.log2(harmonics-limit)/unit_len))\n if startpos <= max_index:\n # \"for example, 100hz-200hz is one octave, 200hz-250hz is 1/4octave\"\n endpos = index[0] + int(round(np.log2(harmonics + limit)/unit_len))\n endpos = min(max_index, endpos)\n # \"find the maximum value at right side of last maximum\"\n mag2 = np.amax(x[startpos:endpos+1])\n index2 = np.where(x[startpos:] == mag2)[0][0] + startpos\n if mag2 > 0:\n mag = np.append(mag, mag2)\n index = np.append(index, index2)\n return mag, index\n\n\n# ---- vda -----\n# func_Get_SHRP does not use this, because CHECK_VOICING is always 0\ndef vda(x, segmentdur, noisefloor, minzcr):\n raise NotImplementedError\n\n\n# ---- ethreshold -----\n# Although present in the matlab source this function is not used.\n\ndef ethreshold(frames):\n \"\"\"Determine energy threshold for silence.\"\"\"\n raise NotImplementedError\n\n\n# ---- toframes ----\n\ndef toframes(samples, curpos, segmentlen, window_type):\n last_index = len(samples) - 1\n num_frames = len(curpos)\n start = curpos - int(round(segmentlen/2))\n offset = np.arange(segmentlen)\n index_start = np.nonzero(start < 1)[0]\n start[index_start] = 0\n endpos = start + segmentlen - 1\n index = np.nonzero(endpos > last_index)[0]\n endpos[index] = last_index\n start[index] = last_index + 1 - segmentlen\n frames = samples[(np.tile(np.expand_dims(start, 1),\n (1, segmentlen)) + np.tile(offset, (num_frames, 1)))]\n window_vector = np.tile(window(segmentlen, window_type), (num_frames, 1))\n return np.multiply(frames, window_vector)\n\n\n# ---- voicing ----\n# func_Get_SHRP does not use these, because CHECK_VOICING is always 0\n\ndef postvda(segment, curf0, Fs, r_threshold):\n raise NotImplementedError\n\n\ndef zcr(x, dur):\n raise NotImplementedError\n\n\n# ---- window -----\ndef _pi_arange(width):\n return 2*np.pi*np.arange(width)/(width-1)\n\n\ndef _not_implemented():\n raise NotImplementedError\n\n\ndef _triangular(n):\n m = (n-1)/2\n res = np.arange(np.floor(m+1))/m\n return np.append(res, res[int(np.ceil(m))-1::-1])\n\nwindow_funcs = dict(\n rect = lambda n: np.ones(n),\n tria = _triangular,\n hann = lambda n: 0.5*(1 - np.cos(_pi_arange(n))),\n hamm = lambda n: 0.54 - 0.46*np.cos(_pi_arange(n)),\n blac = lambda n: (0.42 - 0.5*np.cos(_pi_arange(n)) + 0.08*np.cos(2*_pi_arange(n))),\n kais = lambda n: _not_implemented(),\n )\n\n\ndef window(width, window_type, beta=None):\n \"\"\"Generate a window function (1 dim ndarray) of length width.\n\n Given a window_type from the list 'rectangular', 'triangular', 'hanning',\n 'hamming', 'blackman', 'kaiser', or at least the first four characters of\n one of those strings, return a 1 dimensional ndarray of floats expressing a\n window function of length 'width' using the 'window_type'. 'beta' is an\n additional input for the kaiser algorithm. (XXX: kaiser is not currently\n implemented.)\n\n \"\"\"\n algo = window_funcs.get(window_type[:4])\n if algo is None:\n raise ValueError(\n \"Unknown window algorithm type {!r}\".format(window_type))\n return algo(width)\n"
] |
[
[
"scipy.io.savemat"
],
[
"numpy.append",
"numpy.testing.assert_array_almost_equal"
],
[
"numpy.amax",
"numpy.expand_dims",
"numpy.around",
"scipy.fftpack.fft",
"numpy.mean",
"numpy.fix",
"numpy.where",
"numpy.arange",
"numpy.full",
"numpy.ceil",
"scipy.interpolate.interp1d",
"numpy.zeros",
"numpy.multiply",
"numpy.power",
"numpy.nonzero",
"numpy.append",
"numpy.floor",
"numpy.transpose",
"numpy.log2",
"numpy.abs",
"numpy.tile",
"numpy.ones"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"1.3",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
HanMeh/dreamerv2
|
[
"ec9904613cb70dded51017f724f05eb688c1bc3d"
] |
[
"plotting.py"
] |
[
"import argparse\nimport collections\nimport functools\nimport itertools\nimport json\nimport multiprocessing as mp\nimport os\nimport pathlib\nimport re\nimport subprocess\nimport warnings\n\nos.environ['NO_AT_BRIDGE'] = '1' # Hide X org false warning.\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nimport numpy as np\nimport pandas as pd\n\nnp.set_string_function(lambda x: f'<np.array shape={x.shape} dtype={x.dtype}>')\n\nRun = collections.namedtuple('Run', 'task method seed xs ys')\n\nPALETTES = dict(\n discrete=(\n '#377eb8', '#4daf4a', '#984ea3', '#e41a1c', '#ff7f00', '#a65628',\n '#f781bf', '#888888', '#a6cee3', '#b2df8a', '#cab2d6', '#fb9a99',\n ),\n contrast=(\n '#0022ff', '#33aa00', '#ff0011', '#ddaa00', '#cc44dd', '#0088aa',\n '#001177', '#117700', '#990022', '#885500', '#553366', '#006666',\n ),\n gradient=(\n '#fde725', '#a0da39', '#4ac16d', '#1fa187', '#277f8e', '#365c8d',\n '#46327e', '#440154',\n ),\n baselines=(\n '#222222', '#666666', '#aaaaaa', '#cccccc',\n ),\n)\n\nLEGEND = dict(\n fontsize='medium', numpoints=1, labelspacing=0, columnspacing=1.2,\n handlelength=1.5, handletextpad=0.5, ncol=4, loc='lower center')\n\nDEFAULT_BASELINES = [\n 'd4pg', 'dqn_sticky', 'rainbow_sticky', 'human$', 'impala']\n\nBINS = collections.defaultdict(int)\nBINS.update(dmc=1e5, atari=1e6, particle=1e5)\n\n\ndef find_keys(args):\n filenames = []\n for indir in args.indir:\n task = next(indir.iterdir()) # First only.\n for method in task.iterdir():\n seed = next(indir.iterdir()) # First only.\n filenames += list(seed.glob('**/*.jsonl'))\n keys = set()\n for filename in filenames:\n keys |= set(load_jsonl(filename).columns)\n print(f'Keys ({len(keys)}):', ', '.join(keys), flush=True)\n\n\ndef load_runs(args):\n total, toload = [], []\n for indir in args.indir:\n filenames = list(indir.glob('**/*.jsonl'))\n total += filenames\n for filename in filenames:\n task, method, seed = filename.relative_to(indir).parts[:-1]\n if not any(p.search(task) for p in args.tasks):\n continue\n if not any(p.search(method) for p in args.methods):\n continue\n toload.append((filename, indir))\n print(f'Loading {len(toload)} of {len(total)} runs...')\n jobs = [functools.partial(load_run, f, i, args) for f, i in toload]\n # Disable async data loading:\n # runs = [j() for j in jobs]\n with mp.Pool(10) as pool:\n promises = [pool.apply_async(j) for j in jobs]\n runs = [p.get() for p in promises]\n runs = [r for r in runs if r is not None]\n return runs\n\n\ndef load_run(filename, indir, args):\n task, method, seed = filename.relative_to(indir).parts[:-1]\n prefix = f'indir{args.indir.index(indir)+1}_'\n if task == 'atari_jamesbond':\n task = 'atari_james_bond'\n seed = prefix + seed\n if args.prefix:\n method = prefix + method\n df = load_jsonl(filename)\n if df is None:\n print('Skipping empty run')\n return\n try:\n df = df[[args.xaxis, args.yaxis]].dropna()\n if args.maxval:\n df = df.replace([+np.inf], +args.maxval)\n df = df.replace([-np.inf], -args.maxval)\n df[args.yaxis] = df[args.yaxis].clip(-args.maxval, +args.maxval)\n except KeyError:\n return\n xs = df[args.xaxis].to_numpy()\n ys = df[args.yaxis].to_numpy()\n bins = BINS[task.split('_')[0]] if args.bins == -1 else args.bins\n if bins:\n borders = np.arange(0, xs.max() + 1e-8, bins)\n xs, ys = bin_scores(xs, ys, borders)\n if not len(xs):\n print('Skipping empty run', task, method, seed)\n return\n return Run(task, method, seed, xs, ys)\n\n\ndef load_baselines(patterns, prefix=False):\n runs = []\n directory = pathlib.Path(__file__).parent / 'scores'\n for filename in directory.glob('**/*_baselines.json'):\n for task, methods in json.loads(filename.read_text()).items():\n for method, score in methods.items():\n if prefix:\n method = f'baseline_{method}'\n if not any(p.search(method) for p in patterns):\n continue\n runs.append(Run(task, method, None, None, score))\n return runs\n\n\ndef stats(runs, baselines):\n tasks = sorted(set(r.task for r in runs))\n methods = sorted(set(r.method for r in runs))\n seeds = sorted(set(r.seed for r in runs))\n baseline = sorted(set(r.method for r in baselines))\n print('Loaded', len(runs), 'runs.')\n print(f'Tasks ({len(tasks)}):', ', '.join(tasks))\n print(f'Methods ({len(methods)}):', ', '.join(methods))\n print(f'Seeds ({len(seeds)}):', ', '.join(seeds))\n print(f'Baselines ({len(baseline)}):', ', '.join(baseline))\n\n\ndef order_methods(runs, baselines, args):\n methods = []\n for pattern in args.methods:\n for method in sorted(set(r.method for r in runs)):\n if pattern.search(method):\n if method not in methods:\n methods.append(method)\n if method not in args.colors:\n index = len(args.colors) % len(args.palette)\n args.colors[method] = args.palette[index]\n non_baseline_colors = len(args.colors)\n for pattern in args.baselines:\n for method in sorted(set(r.method for r in baselines)):\n if pattern.search(method):\n if method not in methods:\n methods.append(method)\n if method not in args.colors:\n index = len(args.colors) - non_baseline_colors\n index = index % len(PALETTES['baselines'])\n args.colors[method] = PALETTES['baselines'][index]\n return methods\n\n\ndef figure(runs, methods, args):\n tasks = sorted(set(r.task for r in runs if r.xs is not None))\n rows = int(np.ceil((len(tasks) + len(args.add)) / args.cols))\n figsize = args.size[0] * args.cols, args.size[1] * rows\n fig, axes = plt.subplots(rows, args.cols, figsize=figsize)\n for task, ax in zip(tasks, axes.flatten()):\n relevant = [r for r in runs if r.task == task]\n plot(task, ax, relevant, methods, args)\n for name, ax in zip(args.add, axes.flatten()[len(tasks):]):\n ax.set_facecolor((0.9, 0.9, 0.9))\n if name == 'median':\n plot_combined(\n 'combined_median', ax, runs, methods, args,\n lo='random', hi='human$',\n agg=lambda x: np.nanmedian(x, -1))\n elif name == 'mean':\n plot_combined(\n 'combined_mean', ax, runs, methods, args,\n lo='random', hi='human$',\n agg=lambda x: np.nanmean(x, -1))\n elif name == 'gamer_median':\n plot_combined(\n 'combined_gamer_median', ax, runs, methods, args,\n lo='random', hi='human$',\n agg=lambda x: np.nanmedian(x, -1))\n elif name == 'gamer_mean':\n plot_combined(\n 'combined_gamer_mean', ax, runs, methods, args,\n lo='random', hi='human$',\n agg=lambda x: np.nanmean(x, -1))\n elif name == 'record_mean':\n plot_combined(\n 'combined_record_mean', ax, runs, methods, args,\n lo='random', hi='record',\n agg=lambda x: np.nanmean(x, -1))\n elif name == 'clipped_record_mean':\n plot_combined(\n 'combined_clipped_record_mean', ax, runs, methods, args,\n lo='random', hi='record', clip=True,\n agg=lambda x: np.nanmean(x, -1))\n elif name == 'num_seeds':\n plot_combined(\n 'combined_num_seeds', ax, runs, methods, args,\n agg=lambda x: np.isfinite(x).sum(-1))\n elif name == 'human_above':\n plot_combined(\n 'combined_above_human$', ax, runs, methods, args,\n agg=lambda y: (y >= 1.0).astype(float).sum(-1))\n elif name == 'human_below':\n plot_combined(\n 'combined_below_human$', ax, runs, methods, args,\n agg=lambda y: (y <= 1.0).astype(float).sum(-1))\n else:\n raise NotImplementedError(name)\n if args.xlim:\n for ax in axes[:-1].flatten():\n ax.xaxis.get_offset_text().set_visible(False)\n if args.xlabel:\n for ax in axes[-1]:\n ax.set_xlabel(args.xlabel)\n if args.ylabel:\n for ax in axes[:, 0]:\n ax.set_ylabel(args.ylabel)\n for ax in axes.flatten()[len(tasks) + len(args.add):]:\n ax.axis('off')\n legend(fig, args.labels, **LEGEND)\n return fig\n\n\ndef plot(task, ax, runs, methods, args):\n assert runs\n try:\n title = task.split('_', 1)[1].replace('_', ' ').title()\n except IndexError:\n title = task.title()\n ax.set_title(title)\n xlim = [+np.inf, -np.inf]\n for index, method in enumerate(methods):\n relevant = [r for r in runs if r.method == method]\n if not relevant:\n continue\n if any(r.xs is None for r in relevant):\n baseline(index, method, ax, relevant, args)\n else:\n if args.aggregate == 'none':\n xs, ys = curve_lines(index, task, method, ax, relevant, args)\n else:\n xs, ys = curve_area(index, task, method, ax, relevant, args)\n if len(xs) == len(ys) == 0:\n print(f'Skipping empty: {task} {method}')\n continue\n xlim = [min(xlim[0], xs.min()), max(xlim[1], xs.max())]\n ax.ticklabel_format(axis='x', style='sci', scilimits=(0, 0))\n steps = [1, 2, 2.5, 5, 10]\n ax.xaxis.set_major_locator(ticker.MaxNLocator(args.xticks, steps=steps))\n ax.yaxis.set_major_locator(ticker.MaxNLocator(args.yticks, steps=steps))\n if np.isfinite(xlim).all():\n ax.set_xlim(args.xlim or xlim)\n if args.xlim:\n ticks = sorted({*ax.get_xticks(), *args.xlim})\n ticks = [x for x in ticks if args.xlim[0] <= x <= args.xlim[1]]\n ax.set_xticks(ticks)\n if args.ylim:\n ax.set_ylim(args.ylim)\n if args.ylimticks:\n ticks = sorted({*ax.get_yticks(), *args.ylim})\n ticks = [x for x in ticks if args.ylim[0] <= x <= args.ylim[1]]\n ax.set_yticks(ticks)\n\n\ndef plot_combined(\n name, ax, runs, methods, args, agg, lo=None, hi=None, clip=False):\n tasks = sorted(set(run.task for run in runs if run.xs is not None))\n seeds = list(set(run.seed for run in runs))\n runs = [r for r in runs if r.task in tasks] # Discard unused baselines.\n # Bin all runs onto the same X steps.\n borders = sorted(\n [r.xs for r in runs if r.xs is not None],\n key=lambda x: np.nanmax(x))[-1]\n for index, run in enumerate(runs):\n if run.xs is None:\n continue\n xs, ys = bin_scores(run.xs, run.ys, borders)\n runs[index] = run._replace(xs=xs, ys=ys)\n # Per-task normalization by low and high baseline.\n if lo or hi:\n mins = collections.defaultdict(list)\n maxs = collections.defaultdict(list)\n [mins[r.task].append(r.ys) for r in load_baselines([re.compile(lo)])]\n [maxs[r.task].append(r.ys) for r in load_baselines([re.compile(hi)])]\n mins = {task: min(ys) for task, ys in mins.items() if task in tasks}\n maxs = {task: max(ys) for task, ys in maxs.items() if task in tasks}\n missing_baselines = []\n for task in tasks:\n if task not in mins or task not in maxs:\n missing_baselines.append(task)\n if set(missing_baselines) == set(tasks):\n print(f'No baselines found to normalize any tasks in {name} plot.')\n else:\n for task in missing_baselines:\n print(f'No baselines found to normalize {task} in {name} plot.')\n for index, run in enumerate(runs):\n if run.task not in mins or run.task not in maxs:\n continue\n ys = (run.ys - mins[run.task]) / (maxs[run.task] - mins[run.task])\n if clip:\n ys = np.minimum(ys, 1.0)\n runs[index] = run._replace(ys=ys)\n # Aggregate across tasks but not methods or seeds.\n combined = []\n for method, seed in itertools.product(methods, seeds):\n relevant = [r for r in runs if r.method == method and r.seed == seed]\n if not relevant:\n continue\n if relevant[0].xs is None:\n xs, ys = None, np.array([r.ys for r in relevant])\n else:\n xs, ys = stack_scores(*zip(*[(r.xs, r.ys) for r in relevant]))\n with warnings.catch_warnings(): # Ignore empty slice warnings.\n warnings.simplefilter('ignore', category=RuntimeWarning)\n combined.append(Run('combined', method, seed, xs, agg(ys)))\n plot(name, ax, combined, methods, args)\n\n\ndef curve_lines(index, task, method, ax, runs, args):\n zorder = 10000 - 10 * index - 1\n for run in runs:\n color = args.colors[method]\n ax.plot(run.xs, run.ys, label=method, color=color, zorder=zorder)\n return runs[0].xs, runs[0].ys\n\n\ndef curve_area(index, task, method, ax, runs, args):\n xs, ys = stack_scores(*zip(*[(r.xs, r.ys) for r in runs]))\n with warnings.catch_warnings(): # NaN buckets remain NaN.\n warnings.simplefilter('ignore', category=RuntimeWarning)\n if args.aggregate == 'std1':\n mean, std = np.nanmean(ys, -1), np.nanstd(ys, -1)\n lo, mi, hi = mean - std, mean, mean + std\n elif args.aggregate == 'per0':\n lo, mi, hi = [np.nanpercentile(ys, k, -1) for k in (0, 50, 100)]\n elif args.aggregate == 'per5':\n lo, mi, hi = [np.nanpercentile(ys, k, -1) for k in (5, 50, 95)]\n elif args.aggregate == 'per25':\n lo, mi, hi = [np.nanpercentile(ys, k, -1) for k in (25, 50, 75)]\n else:\n raise NotImplementedError(args.aggregate)\n color = args.colors[method]\n kw = dict(color=color, zorder=1000 - 10 * index, alpha=0.1, linewidths=0)\n ax.fill_between(xs, lo, hi, **kw)\n ax.plot(xs, mi, label=method, color=color, zorder=10000 - 10 * index - 1)\n return xs, mi\n\n\ndef baseline(index, method, ax, runs, args):\n assert all(run.xs is None for run in runs)\n ys = np.array([run.ys for run in runs])\n mean, std = ys.mean(), ys.std()\n color = args.colors[method]\n kw = dict(color=color, zorder=500 - 20 * index - 1, alpha=0.1, linewidths=0)\n ax.fill_between([-np.inf, np.inf], [mean - std] * 2, [mean + std] * 2, **kw)\n kw = dict(ls='--', color=color, zorder=5000 - 10 * index - 1)\n ax.axhline(mean, label=method, **kw)\n\n\ndef legend(fig, mapping=None, **kwargs):\n entries = {}\n for ax in fig.axes:\n for handle, label in zip(*ax.get_legend_handles_labels()):\n if mapping and label in mapping:\n label = mapping[label]\n entries[label] = handle\n leg = fig.legend(entries.values(), entries.keys(), **kwargs)\n leg.get_frame().set_edgecolor('white')\n extent = leg.get_window_extent(fig.canvas.get_renderer())\n extent = extent.transformed(fig.transFigure.inverted())\n yloc, xloc = kwargs['loc'].split()\n y0 = dict(lower=extent.y1, center=0, upper=0)[yloc]\n y1 = dict(lower=1, center=1, upper=extent.y0)[yloc]\n x0 = dict(left=extent.x1, center=0, right=0)[xloc]\n x1 = dict(left=1, center=1, right=extent.x0)[xloc]\n fig.tight_layout(rect=[x0, y0, x1, y1], h_pad=0.5, w_pad=0.5)\n\n\ndef save(fig, args):\n args.outdir.mkdir(parents=True, exist_ok=True)\n filename = args.outdir / 'curves.png'\n fig.savefig(filename, dpi=args.dpi)\n print('Saved to', filename)\n filename = args.outdir / 'curves.pdf'\n fig.savefig(filename)\n try:\n subprocess.call(['pdfcrop', str(filename), str(filename)])\n except FileNotFoundError:\n print('Install texlive-extra-utils to crop PDF outputs.')\n\n\ndef bin_scores(xs, ys, borders, reducer=np.nanmean):\n order = np.argsort(xs)\n xs, ys = xs[order], ys[order]\n binned = []\n with warnings.catch_warnings(): # Empty buckets become NaN.\n warnings.simplefilter('ignore', category=RuntimeWarning)\n for start, stop in zip(borders[:-1], borders[1:]):\n left = (xs <= start).sum()\n right = (xs <= stop).sum()\n binned.append(reducer(ys[left:right]))\n return borders[1:], np.array(binned)\n\n\ndef stack_scores(multiple_xs, multiple_ys):\n longest_xs = sorted(multiple_xs, key=lambda x: len(x))[-1]\n multiple_padded_ys = []\n for xs, ys in zip(multiple_xs, multiple_ys):\n assert (longest_xs[:len(xs)] == xs).all(), (list(xs), list(longest_xs))\n padding = [np.inf] * (len(longest_xs) - len(xs))\n padded_ys = np.concatenate([ys, padding])\n multiple_padded_ys.append(padded_ys)\n stacked_ys = np.stack(multiple_padded_ys, -1)\n return longest_xs, stacked_ys\n\n\ndef load_jsonl(filename):\n try:\n with filename.open() as f:\n lines = list(f.readlines())\n records = []\n for index, line in enumerate(lines):\n try:\n records.append(json.loads(line))\n except Exception:\n if index == len(lines) - 1:\n continue # Silently skip last line if it is incomplete.\n raise ValueError(\n f'Skipping invalid JSON line ({index+1}/{len(lines)+1}) in'\n f'{filename}: {line}')\n return pd.DataFrame(records)\n except ValueError as e:\n print('Invalid', filename, e)\n return None\n\n\ndef save_runs(runs, filename):\n filename.parent.mkdir(parents=True, exist_ok=True)\n records = []\n for run in runs:\n if run.xs is None:\n continue\n records.append(dict(\n task=run.task, method=run.method, seed=run.seed,\n xs=run.xs.tolist(), ys=run.ys.tolist()))\n runs = json.dumps(records)\n filename.write_text(runs)\n print('Saved', filename)\n\n\ndef main(args):\n find_keys(args)\n runs = load_runs(args)\n save_runs(runs, args.outdir / 'runs.jsonl')\n baselines = load_baselines(args.baselines, args.prefix)\n stats(runs, baselines)\n methods = order_methods(runs, baselines, args)\n if not runs:\n print('Noting to plot.')\n return\n print('Plotting...')\n fig = figure(runs + baselines, methods, args)\n save(fig, args)\n\n\ndef parse_args():\n boolean = lambda x: bool(['False', 'True'].index(x))\n parser = argparse.ArgumentParser()\n parser.add_argument('--indir', nargs='+', type=pathlib.Path, required=True)\n parser.add_argument('--outdir', type=pathlib.Path, required=True)\n parser.add_argument('--subdir', type=boolean, default=True)\n parser.add_argument('--xaxis', type=str, required=True)\n parser.add_argument('--yaxis', type=str, required=True)\n parser.add_argument('--tasks', nargs='+', default=[r'.*'])\n parser.add_argument('--methods', nargs='+', default=[r'.*'])\n parser.add_argument('--baselines', nargs='+', default=DEFAULT_BASELINES)\n parser.add_argument('--prefix', type=boolean, default=False)\n parser.add_argument('--bins', type=float, default=-1)\n parser.add_argument('--aggregate', type=str, default='std1')\n parser.add_argument('--size', nargs=2, type=float, default=[2.5, 2.3])\n parser.add_argument('--dpi', type=int, default=80)\n parser.add_argument('--cols', type=int, default=6)\n parser.add_argument('--xlim', nargs=2, type=float, default=None)\n parser.add_argument('--ylim', nargs=2, type=float, default=None)\n parser.add_argument('--ylimticks', type=boolean, default=True)\n parser.add_argument('--xlabel', type=str, default=None)\n parser.add_argument('--ylabel', type=str, default=None)\n parser.add_argument('--xticks', type=int, default=6)\n parser.add_argument('--yticks', type=int, default=5)\n parser.add_argument('--labels', nargs='+', default=None)\n parser.add_argument('--palette', nargs='+', default=['contrast'])\n parser.add_argument('--colors', nargs='+', default={})\n parser.add_argument('--maxval', type=float, default=0)\n parser.add_argument('--add', nargs='+', type=str, default=[\n 'gamer_median', 'gamer_mean', 'record_mean',\n 'clipped_record_mean', 'num_seeds'])\n args = parser.parse_args()\n if args.subdir:\n args.outdir /= args.indir[0].stem\n args.indir = [d.expanduser() for d in args.indir]\n args.outdir = args.outdir.expanduser()\n if args.labels:\n assert len(args.labels) % 2 == 0\n args.labels = {k: v for k, v in zip(args.labels[:-1], args.labels[1:])}\n if args.colors:\n assert len(args.colors) % 2 == 0\n args.colors = {k: v for k, v in zip(args.colors[:-1], args.colors[1:])}\n args.tasks = [re.compile(p) for p in args.tasks]\n args.methods = [re.compile(p) for p in args.methods]\n args.baselines = [re.compile(p) for p in args.baselines]\n if 'return' not in args.yaxis:\n args.baselines = []\n if args.prefix is None:\n args.prefix = len(args.indir) > 1\n if len(args.palette) == 1 and args.palette[0] in PALETTES:\n args.palette = 10 * PALETTES[args.palette[0]]\n if len(args.add) == 1 and args.add[0] == 'none':\n args.add = []\n return args\n\n\nif __name__ == '__main__':\n main(parse_args())\n"
] |
[
[
"numpy.nanmax",
"numpy.nanpercentile",
"numpy.nanmedian",
"numpy.set_string_function",
"numpy.minimum",
"numpy.isfinite",
"matplotlib.use",
"matplotlib.pyplot.subplots",
"numpy.stack",
"pandas.DataFrame",
"numpy.concatenate",
"matplotlib.ticker.MaxNLocator",
"numpy.nanmean",
"numpy.argsort",
"numpy.nanstd",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
andrewcalderwood/flopy
|
[
"0432ce96a0a5eec4d20adb4d384505632a2db3dc",
"0432ce96a0a5eec4d20adb4d384505632a2db3dc",
"0432ce96a0a5eec4d20adb4d384505632a2db3dc",
"0432ce96a0a5eec4d20adb4d384505632a2db3dc"
] |
[
"flopy/mbase.py",
"flopy/utils/gridintersect.py",
"flopy/modflow/mfwel.py",
"flopy/utils/mflistfile.py"
] |
[
"\"\"\"\nmbase module\n This module contains the base model class from which\n all of the other models inherit from.\n\n\"\"\"\nimport abc\nimport os\nimport shutil\nimport threading\nimport warnings\nimport queue as Queue\n\nfrom datetime import datetime\nfrom shutil import which\nfrom subprocess import Popen, PIPE, STDOUT\nimport copy\nimport numpy as np\nfrom flopy import utils, discretization\nfrom .version import __version__\nfrom .discretization.grid import Grid\n\n## Global variables\n# Multiplier for individual array elements in integer and real arrays read by\n# MODFLOW's U2DREL, U1DREL and U2DINT.\niconst = 1\n# Printout flag. If >= 0 then array values read are printed in listing file.\niprn = -1\n\n\n# external exceptions for users\nclass PackageLoadException(Exception):\n \"\"\"\n FloPy package load exception.\n \"\"\"\n\n def __init__(self, error, location=\"\"):\n \"\"\"Initialize exception.\"\"\"\n self.message = error\n super().__init__(f\"{error} ({location})\")\n\n\nclass FileDataEntry:\n def __init__(self, fname, unit, binflag=False, output=False, package=None):\n self.fname = fname\n self.unit = unit\n self.binflag = binflag\n self.output = output\n self.package = package\n\n\nclass FileData:\n def __init__(self):\n self.file_data = []\n return\n\n def add_file(self, fname, unit, binflag=False, output=False, package=None):\n ipop = []\n for idx, file_data in enumerate(self.file_data):\n if file_data.fname == fname or file_data.unit == unit:\n ipop.append(idx)\n\n self.file_data.append(\n FileDataEntry(\n fname, unit, binflag=binflag, output=output, package=package\n )\n )\n return\n\n\nclass ModelInterface:\n def __init__(self):\n self._mg_resync = True\n self._modelgrid = None\n\n def update_modelgrid(self):\n if self._modelgrid is not None:\n self._modelgrid = Grid(\n proj4=self._modelgrid.proj4,\n xoff=self._modelgrid.xoffset,\n yoff=self._modelgrid.yoffset,\n angrot=self._modelgrid.angrot,\n )\n self._mg_resync = True\n\n @property\n @abc.abstractmethod\n def modelgrid(self):\n raise NotImplementedError(\n \"must define modelgrid in child class to use this base class\"\n )\n\n @property\n @abc.abstractmethod\n def packagelist(self):\n raise NotImplementedError(\n \"must define packagelist in child class to use this base class\"\n )\n\n @property\n @abc.abstractmethod\n def namefile(self):\n raise NotImplementedError(\n \"must define namefile in child class to use this base class\"\n )\n\n @property\n @abc.abstractmethod\n def model_ws(self):\n raise NotImplementedError(\n \"must define model_ws in child class to use this base class\"\n )\n\n @property\n @abc.abstractmethod\n def exename(self):\n raise NotImplementedError(\n \"must define exename in child class to use this base class\"\n )\n\n @property\n @abc.abstractmethod\n def version(self):\n raise NotImplementedError(\n \"must define version in child class to use this base class\"\n )\n\n @property\n @abc.abstractmethod\n def solver_tols(self):\n raise NotImplementedError(\n \"must define version in child class to use this base class\"\n )\n\n @abc.abstractmethod\n def export(self, f, **kwargs):\n raise NotImplementedError(\n \"must define export in child class to use this base class\"\n )\n\n @property\n @abc.abstractmethod\n def laytyp(self):\n raise NotImplementedError(\n \"must define laytyp in child class to use this base class\"\n )\n\n @property\n @abc.abstractmethod\n def hdry(self):\n raise NotImplementedError(\n \"must define hdry in child class to use this base class\"\n )\n\n @property\n @abc.abstractmethod\n def hnoflo(self):\n raise NotImplementedError(\n \"must define hnoflo in child class to use this base class\"\n )\n\n @property\n @abc.abstractmethod\n def laycbd(self):\n raise NotImplementedError(\n \"must define laycbd in child class to use this base class\"\n )\n\n @property\n @abc.abstractmethod\n def verbose(self):\n raise NotImplementedError(\n \"must define verbose in child class to use this base class\"\n )\n\n @abc.abstractmethod\n def check(self, f=None, verbose=True, level=1):\n raise NotImplementedError(\n \"must define check in child class to use this base class\"\n )\n\n def get_package_list(self, ftype=None):\n \"\"\"\n Get a list of all the package names.\n\n Parameters\n ----------\n ftype : str\n Type of package, 'RIV', 'LPF', etc.\n\n Returns\n -------\n val : list of strings\n Can be used to see what packages are in the model, and can then\n be used with get_package to pull out individual packages.\n\n \"\"\"\n val = []\n for pp in self.packagelist:\n if ftype is None:\n val.append(pp.name[0].upper())\n elif pp.package_type.lower() == ftype:\n val.append(pp.name[0].upper())\n return val\n\n def _check(self, chk, level=1):\n \"\"\"\n Check model data for common errors.\n\n Parameters\n ----------\n f : str or file handle\n String defining file name or file handle for summary file\n of check method output. If a string is passed a file handle\n is created. If f is None, check method does not write\n results to a summary file. (default is None)\n verbose : bool\n Boolean flag used to determine if check method results are\n written to the screen\n level : int\n Check method analysis level. If level=0, summary checks are\n performed. If level=1, full checks are performed.\n summarize : bool\n Boolean flag used to determine if summary of results is written\n to the screen\n\n Returns\n -------\n None\n\n Examples\n --------\n\n >>> import flopy\n >>> m = flopy.modflow.Modflow.load('model.nam')\n >>> m.check()\n \"\"\"\n\n # check instance for model-level check\n results = {}\n\n for p in self.packagelist:\n if chk.package_check_levels.get(p.name[0].lower(), 0) <= level:\n results[p.name[0]] = p.check(\n f=None,\n verbose=False,\n level=level - 1,\n checktype=chk.__class__,\n )\n\n # model level checks\n # solver check\n if self.version in chk.solver_packages.keys():\n solvers = set(chk.solver_packages[self.version]).intersection(\n set(self.get_package_list())\n )\n if not solvers:\n chk._add_to_summary(\n \"Error\", desc=\"\\r No solver package\", package=\"model\"\n )\n elif len(list(solvers)) > 1:\n for s in solvers:\n chk._add_to_summary(\n \"Error\",\n desc=\"\\r Multiple solver packages\",\n package=s,\n )\n else:\n chk.passed.append(\"Compatible solver package\")\n\n # add package check results to model level check summary\n for r in results.values():\n if (\n r is not None and r.summary_array is not None\n ): # currently SFR doesn't have one\n chk.summary_array = np.append(\n chk.summary_array, r.summary_array\n ).view(np.recarray)\n chk.passed += [\n f\"{r.package.name[0]} package: {psd}\" for psd in r.passed\n ]\n chk.summarize()\n return chk\n\n\nclass BaseModel(ModelInterface):\n \"\"\"\n MODFLOW-based models base class.\n\n Parameters\n ----------\n modelname : str, default \"modflowtest\"\n Name of the model, which is also used for model file names.\n namefile_ext : str, default \"nam\"\n Name file extension, without \".\"\n exe_name : str, default \"mf2k.exe\"\n Name of the modflow executable.\n model_ws : str, optional\n Path to the model workspace. Model files will be created in this\n directory. Default is None, in which case model_ws is assigned\n to the current working directory.\n structured : bool, default True\n Specify if model grid is structured (default) or unstructured.\n verbose : bool, default False\n Print additional information to the screen.\n **kwargs : dict, optional\n Used to define: ``xll``/``yll`` for the x- and y-coordinates of\n the lower-left corner of the grid, ``xul``/``yul`` for the\n x- and y-coordinates of the upper-left corner of the grid\n (deprecated), ``rotation`` for the grid rotation (default 0.0),\n ``proj4_str`` for a PROJ string, and ``start_datetime`` for\n model start date (default \"1-1-1970\").\n\n \"\"\"\n\n def __init__(\n self,\n modelname=\"modflowtest\",\n namefile_ext=\"nam\",\n exe_name=\"mf2k.exe\",\n model_ws=None,\n structured=True,\n verbose=False,\n **kwargs,\n ):\n \"\"\"Initialize BaseModel.\"\"\"\n super().__init__()\n self.__name = modelname\n self.namefile_ext = namefile_ext or \"\"\n self._namefile = self.__name + \".\" + self.namefile_ext\n self._packagelist = []\n self.heading = \"\"\n self.exe_name = exe_name\n self._verbose = verbose\n self.external_path = None\n self.external_extension = \"ref\"\n if model_ws is None:\n model_ws = os.getcwd()\n if not os.path.exists(model_ws):\n try:\n os.makedirs(model_ws)\n except:\n print(\n f\"\\n{model_ws} not valid, \"\n f\"workspace-folder was changed to {os.getcwd()}\\n\"\n )\n model_ws = os.getcwd()\n self._model_ws = model_ws\n self.structured = structured\n self.pop_key_list = []\n self.cl_params = \"\"\n\n # check for reference info in kwargs\n # we are just carrying these until a dis package is added\n xll = kwargs.pop(\"xll\", None)\n yll = kwargs.pop(\"yll\", None)\n self._xul = kwargs.pop(\"xul\", None)\n self._yul = kwargs.pop(\"yul\", None)\n\n self._rotation = kwargs.pop(\"rotation\", 0.0)\n self._proj4_str = kwargs.pop(\"proj4_str\", None)\n self._start_datetime = kwargs.pop(\"start_datetime\", \"1-1-1970\")\n\n # build model discretization objects\n self._modelgrid = Grid(\n proj4=self._proj4_str,\n xoff=xll,\n yoff=yll,\n angrot=self._rotation,\n )\n self._modeltime = None\n\n # Model file information\n self.__onunit__ = 10\n # external option stuff\n self.array_free_format = True\n self.free_format_input = True\n self.parameter_load = False\n self.array_format = None\n self.external_fnames = []\n self.external_units = []\n self.external_binflag = []\n self.external_output = []\n self.package_units = []\n self._next_ext_unit = None\n\n # output files\n self.output_fnames = []\n self.output_units = []\n self.output_binflag = []\n self.output_packages = []\n\n return\n\n @property\n def modeltime(self):\n raise NotImplementedError(\n \"must define modeltime in child class to use this base class\"\n )\n\n @property\n def modelgrid(self):\n raise NotImplementedError(\n \"must define modelgrid in child class to use this base class\"\n )\n\n @property\n def packagelist(self):\n return self._packagelist\n\n @packagelist.setter\n def packagelist(self, packagelist):\n self._packagelist = packagelist\n\n @property\n def namefile(self):\n return self._namefile\n\n @namefile.setter\n def namefile(self, namefile):\n self._namefile = namefile\n\n @property\n def model_ws(self):\n return self._model_ws\n\n @model_ws.setter\n def model_ws(self, model_ws):\n self._model_ws = model_ws\n\n @property\n def exename(self):\n return self._exename\n\n @exename.setter\n def exename(self, exename):\n self._exename = exename\n\n @property\n def version(self):\n return self._version\n\n @version.setter\n def version(self, version):\n self._version = version\n\n @property\n def verbose(self):\n return self._verbose\n\n @verbose.setter\n def verbose(self, verbose):\n self._verbose = verbose\n\n @property\n def laytyp(self):\n if self.get_package(\"LPF\") is not None:\n return self.get_package(\"LPF\").laytyp.array\n if self.get_package(\"BCF6\") is not None:\n return self.get_package(\"BCF6\").laycon.array\n if self.get_package(\"UPW\") is not None:\n return self.get_package(\"UPW\").laytyp.array\n\n return None\n\n @property\n def hdry(self):\n if self.get_package(\"LPF\") is not None:\n return self.get_package(\"LPF\").hdry\n if self.get_package(\"BCF6\") is not None:\n return self.get_package(\"BCF6\").hdry\n if self.get_package(\"UPW\") is not None:\n return self.get_package(\"UPW\").hdry\n return None\n\n @property\n def hnoflo(self):\n try:\n bas6 = self.get_package(\"BAS6\")\n return bas6.hnoflo\n except AttributeError:\n return None\n\n @property\n def laycbd(self):\n try:\n dis = self.get_package(\"DIS\")\n return dis.laycbd.array\n except AttributeError:\n return None\n\n # we don't need these - no need for controlled access to array_free_format\n # def set_free_format(self, value=True):\n # \"\"\"\n # Set the free format flag for the model instance\n #\n # Parameters\n # ----------\n # value : bool\n # Boolean value to set free format flag for model. (default is True)\n #\n # Returns\n # -------\n #\n # \"\"\"\n # if not isinstance(value, bool):\n # print('Error: set_free_format passed value must be a boolean')\n # return False\n # self.array_free_format = value\n #\n # def get_free_format(self):\n # \"\"\"\n # Return the free format flag for the model\n #\n # Returns\n # -------\n # out : bool\n # Free format flag for the model\n #\n # \"\"\"\n # return self.array_free_format\n\n def next_unit(self, i=None):\n if i is not None:\n self.__onunit__ = i - 1\n else:\n self.__onunit__ += 1\n return self.__onunit__\n\n def next_ext_unit(self):\n \"\"\"\n Function to encapsulate next_ext_unit attribute\n\n \"\"\"\n next_unit = self._next_ext_unit + 1\n self._next_ext_unit += 1\n return next_unit\n\n def export(self, f, **kwargs):\n \"\"\"\n Method to export a model to netcdf or shapefile based on the\n extension of the file name (.shp for shapefile, .nc for netcdf)\n\n Parameters\n ----------\n f : str\n filename\n kwargs : keyword arguments\n modelgrid : flopy.discretization.Grid instance\n user supplied modelgrid which can be used for exporting\n in lieu of the modelgrid associated with the model object\n\n Returns\n -------\n None or Netcdf object\n\n \"\"\"\n from .export import utils\n\n return utils.model_export(f, self, **kwargs)\n\n def add_package(self, p):\n \"\"\"\n Add a package.\n\n Parameters\n ----------\n p : Package object\n\n \"\"\"\n for idx, u in enumerate(p.unit_number):\n if u != 0:\n if u in self.package_units or u in self.external_units:\n try:\n pn = p.name[idx]\n except:\n pn = p.name\n if self.verbose:\n print(\n f\"\\nWARNING:\\n unit {u} of package {pn} already in use.\"\n )\n self.package_units.append(u)\n for i, pp in enumerate(self.packagelist):\n if pp.allowDuplicates:\n continue\n elif isinstance(p, type(pp)):\n if self.verbose:\n print(\n \"\\nWARNING:\\n Two packages of the same type, \"\n f\"Replacing existing '{p.name[0]}' package.\"\n )\n self.packagelist[i] = p\n return\n if self.verbose:\n print(\"adding Package: \", p.name[0])\n self.packagelist.append(p)\n\n def remove_package(self, pname):\n \"\"\"\n Remove a package from this model\n\n Parameters\n ----------\n pname : string\n Name of the package, such as 'RIV', 'BAS6', etc.\n\n \"\"\"\n for i, pp in enumerate(self.packagelist):\n if pname.upper() in pp.name:\n if self.verbose:\n print(\"removing Package: \", pp.name)\n\n # Remove the package object from the model's packagelist\n p = self.packagelist.pop(i)\n\n # Remove the package unit number from the list of package\n # units stored with the model\n for iu in p.unit_number:\n if iu in self.package_units:\n self.package_units.remove(iu)\n return\n raise StopIteration(\n \"Package name \" + pname + \" not found in Package list\"\n )\n\n def __getattr__(self, item):\n \"\"\"\n __getattr__ - syntactic sugar\n\n Parameters\n ----------\n item : str\n 3 character package name (case insensitive) or \"sr\" to access\n the SpatialReference instance of the ModflowDis object\n\n\n Returns\n -------\n sr : SpatialReference instance\n pp : Package object\n Package object of type :class:`flopy.pakbase.Package`\n\n Note\n ----\n if self.dis is not None, then the spatial reference instance is updated\n using self.dis.delr, self.dis.delc, and self.dis.lenuni before being\n returned\n \"\"\"\n if item == \"output_packages\" or not hasattr(self, \"output_packages\"):\n raise AttributeError(item)\n\n if item == \"tr\":\n if self.dis is not None:\n return self.dis.tr\n else:\n return None\n\n if item == \"nper\":\n if self.dis is not None:\n return self.dis.nper\n else:\n return 0\n\n if item == \"start_datetime\":\n if self.dis is not None:\n return self.dis.start_datetime\n else:\n return None\n\n # return self.get_package(item)\n # to avoid infinite recursion\n if item == \"_packagelist\" or item == \"packagelist\":\n raise AttributeError(item)\n pckg = self.get_package(item)\n if pckg is not None or item in self.mfnam_packages:\n return pckg\n if item == \"modelgrid\":\n return\n raise AttributeError(item)\n\n def get_ext_dict_attr(\n self, ext_unit_dict=None, unit=None, filetype=None, pop_key=True\n ):\n iu = None\n fname = None\n if ext_unit_dict is not None:\n for key, value in ext_unit_dict.items():\n if key == unit:\n iu = key\n fname = os.path.basename(value.filename)\n break\n elif value.filetype == filetype:\n iu = key\n fname = os.path.basename(value.filename)\n if pop_key:\n self.add_pop_key_list(iu)\n break\n return iu, fname\n\n def _output_msg(self, i, add=True):\n if add:\n txt1 = \"Adding\"\n txt2 = \"to\"\n else:\n txt1 = \"Removing\"\n txt2 = \"from\"\n print(\n f\"{txt1} {self.output_fnames[i]} (unit={self.output_units[i]}) \"\n f\"{txt2} the output list.\"\n )\n\n def add_output_file(\n self, unit, fname=None, extension=\"cbc\", binflag=True, package=None\n ):\n \"\"\"\n Add an ascii or binary output file for a package\n\n Parameters\n ----------\n unit : int\n unit number of external array\n fname : str\n filename of external array. (default is None)\n extension : str\n extension to use for the cell-by-cell file. Only used if fname\n is None. (default is cbc)\n binflag : bool\n boolean flag indicating if the output file is a binary file.\n Default is True\n package : str\n string that defines the package the output file is attached to.\n Default is None\n\n \"\"\"\n add_cbc = False\n if unit > 0:\n add_cbc = True\n # determine if the file is in external_units\n if abs(unit) in self.external_units:\n idx = self.external_units.index(abs(unit))\n if fname is None:\n fname = os.path.basename(self.external_fnames[idx])\n binflag = self.external_binflag[idx]\n self.remove_external(unit=abs(unit))\n # determine if the unit exists in the output data\n if abs(unit) in self.output_units:\n add_cbc = False\n idx = self.output_units.index(abs(unit))\n # determine if binflag has changed\n if binflag is not self.output_binflag[idx]:\n add_cbc = True\n if add_cbc:\n self.remove_output(unit=abs(unit))\n else:\n if package is not None:\n self.output_packages[idx].append(package)\n\n if add_cbc:\n if fname is None:\n fname = f\"{self.name}.{extension}\"\n # check if this file name exists for a different unit number\n if fname in self.output_fnames:\n idx = self.output_fnames.index(fname)\n iut = self.output_units[idx]\n if iut != unit:\n # include unit number in fname if package has\n # not been passed\n if package is None:\n fname = f\"{self.name}.{unit}.{extension}\"\n # include package name in fname\n else:\n fname = f\"{self.name}.{package}.{extension}\"\n else:\n fname = os.path.basename(fname)\n self.add_output(fname, unit, binflag=binflag, package=package)\n return\n\n def add_output(self, fname, unit, binflag=False, package=None):\n \"\"\"\n Assign an external array so that it will be listed as a DATA or\n DATA(BINARY) entry in the name file. This will allow an outside\n file package to refer to it.\n\n Parameters\n ----------\n fname : str\n filename of external array\n unit : int\n unit number of external array\n binflag : boolean\n binary or not. (default is False)\n\n \"\"\"\n if fname in self.output_fnames:\n if self.verbose:\n print(\n \"BaseModel.add_output() warning: \"\n f\"replacing existing filename {fname}\"\n )\n idx = self.output_fnames.index(fname)\n if self.verbose:\n self._output_msg(idx, add=False)\n self.output_fnames.pop(idx)\n self.output_units.pop(idx)\n self.output_binflag.pop(idx)\n self.output_packages.pop(idx)\n\n self.output_fnames.append(fname)\n self.output_units.append(unit)\n self.output_binflag.append(binflag)\n if package is not None:\n self.output_packages.append([package])\n else:\n self.output_packages.append([])\n\n if self.verbose:\n self._output_msg(-1, add=True)\n\n return\n\n def remove_output(self, fname=None, unit=None):\n \"\"\"\n Remove an output file from the model by specifying either the\n file name or the unit number.\n\n Parameters\n ----------\n fname : str\n filename of output array\n unit : int\n unit number of output array\n\n \"\"\"\n if fname is not None:\n for i, e in enumerate(self.output_fnames):\n if fname in e:\n if self.verbose:\n self._output_msg(i, add=False)\n self.output_fnames.pop(i)\n self.output_units.pop(i)\n self.output_binflag.pop(i)\n self.output_packages.pop(i)\n elif unit is not None:\n for i, u in enumerate(self.output_units):\n if u == unit:\n if self.verbose:\n self._output_msg(i, add=False)\n self.output_fnames.pop(i)\n self.output_units.pop(i)\n self.output_binflag.pop(i)\n self.output_packages.pop(i)\n else:\n msg = \" either fname or unit must be passed to remove_output()\"\n raise Exception(msg)\n return\n\n def get_output(self, fname=None, unit=None):\n \"\"\"\n Get an output file from the model by specifying either the\n file name or the unit number.\n\n Parameters\n ----------\n fname : str\n filename of output array\n unit : int\n unit number of output array\n\n \"\"\"\n if fname is not None:\n for i, e in enumerate(self.output_fnames):\n if fname in e:\n return self.output_units[i]\n return None\n elif unit is not None:\n for i, u in enumerate(self.output_units):\n if u == unit:\n return self.output_fnames[i]\n return None\n else:\n msg = \" either fname or unit must be passed to get_output()\"\n raise Exception(msg)\n return\n\n def set_output_attribute(self, fname=None, unit=None, attr=None):\n \"\"\"\n Set a variable in an output file from the model by specifying either\n the file name or the unit number and a dictionary with attributes\n to change.\n\n Parameters\n ----------\n fname : str\n filename of output array\n unit : int\n unit number of output array\n\n \"\"\"\n idx = None\n if fname is not None:\n for i, e in enumerate(self.output_fnames):\n if fname in e:\n idx = i\n break\n return None\n elif unit is not None:\n for i, u in enumerate(self.output_units):\n if u == unit:\n idx = i\n break\n else:\n msg = (\n \" either fname or unit must be passed \"\n \"to set_output_attribute()\"\n )\n raise Exception(msg)\n if attr is not None:\n if idx is not None:\n for key, value in attr.items:\n if key == \"binflag\":\n self.output_binflag[idx] = value\n elif key == \"fname\":\n self.output_fnames[idx] = value\n elif key == \"unit\":\n self.output_units[idx] = value\n return\n\n def get_output_attribute(self, fname=None, unit=None, attr=None):\n \"\"\"\n Get a attribute for an output file from the model by specifying either\n the file name or the unit number.\n\n Parameters\n ----------\n fname : str\n filename of output array\n unit : int\n unit number of output array\n\n \"\"\"\n idx = None\n if fname is not None:\n for i, e in enumerate(self.output_fnames):\n if fname in e:\n idx = i\n break\n return None\n elif unit is not None:\n for i, u in enumerate(self.output_units):\n if u == unit:\n idx = i\n break\n else:\n raise Exception(\n \" either fname or unit must be passed \"\n \"to set_output_attribute()\"\n )\n v = None\n if attr is not None:\n if idx is not None:\n if attr == \"binflag\":\n v = self.output_binflag[idx]\n elif attr == \"fname\":\n v = self.output_fnames[idx]\n elif attr == \"unit\":\n v = self.output_units[idx]\n return v\n\n def add_external(self, fname, unit, binflag=False, output=False):\n \"\"\"\n Assign an external array so that it will be listed as a DATA or\n DATA(BINARY) entry in the name file. This will allow an outside\n file package to refer to it.\n\n Parameters\n ----------\n fname : str\n filename of external array\n unit : int\n unit number of external array\n binflag : boolean\n binary or not. (default is False)\n\n \"\"\"\n if fname in self.external_fnames:\n if self.verbose:\n print(\n \"BaseModel.add_external() warning: \"\n f\"replacing existing filename {fname}\"\n )\n idx = self.external_fnames.index(fname)\n self.external_fnames.pop(idx)\n self.external_units.pop(idx)\n self.external_binflag.pop(idx)\n self.external_output.pop(idx)\n if unit in self.external_units:\n if self.verbose:\n msg = f\"BaseModel.add_external() warning: replacing existing unit {unit}\"\n print(msg)\n idx = self.external_units.index(unit)\n self.external_fnames.pop(idx)\n self.external_units.pop(idx)\n self.external_binflag.pop(idx)\n self.external_output.pop(idx)\n\n self.external_fnames.append(fname)\n self.external_units.append(unit)\n self.external_binflag.append(binflag)\n self.external_output.append(output)\n return\n\n def remove_external(self, fname=None, unit=None):\n \"\"\"\n Remove an external file from the model by specifying either the\n file name or the unit number.\n\n Parameters\n ----------\n fname : str\n filename of external array\n unit : int\n unit number of external array\n\n \"\"\"\n plist = []\n if fname is not None:\n for i, e in enumerate(self.external_fnames):\n if fname in e:\n plist.append(i)\n elif unit is not None:\n for i, u in enumerate(self.external_units):\n if u == unit:\n plist.append(i)\n else:\n msg = \" either fname or unit must be passed to remove_external()\"\n raise Exception(msg)\n # remove external file\n j = 0\n for i in plist:\n ipos = i - j\n self.external_fnames.pop(ipos)\n self.external_units.pop(ipos)\n self.external_binflag.pop(ipos)\n self.external_output.pop(ipos)\n j += 1\n return\n\n def add_existing_package(\n self, filename, ptype=None, copy_to_model_ws=True\n ):\n \"\"\"\n Add an existing package to a model instance.\n\n Parameters\n ----------\n\n filename : str\n the name of the file to add as a package\n ptype : optional\n the model package type (e.g. \"lpf\", \"wel\", etc). If None,\n then the file extension of the filename arg is used\n copy_to_model_ws : bool\n flag to copy the package file into the model_ws directory.\n\n Returns\n -------\n None\n\n \"\"\"\n if ptype is None:\n ptype = filename.split(\".\")[-1]\n ptype = str(ptype).upper()\n\n # for pak in self.packagelist:\n # if ptype in pak.name:\n # print(\"BaseModel.add_existing_package() warning: \" +\\\n # \"replacing existing package {0}\".format(ptype))\n class Obj:\n pass\n\n fake_package = Obj()\n fake_package.write_file = lambda: None\n fake_package.name = [ptype]\n fake_package.extension = [filename.split(\".\")[-1]]\n fake_package.unit_number = [self.next_ext_unit()]\n if copy_to_model_ws:\n base_filename = os.path.split(filename)[-1]\n fake_package.file_name = [base_filename]\n shutil.copy2(filename, os.path.join(self.model_ws, base_filename))\n else:\n fake_package.file_name = [filename]\n fake_package.allowDuplicates = True\n self.add_package(fake_package)\n\n def get_name_file_entries(self):\n \"\"\"\n Get a string representation of the name file.\n\n Parameters\n ----------\n\n \"\"\"\n lines = []\n for p in self.packagelist:\n for i in range(len(p.name)):\n if p.unit_number[i] == 0:\n continue\n s = f\"{p.name[i]:14s} {p.unit_number[i]:5d} {p.file_name[i]}\"\n lines.append(s)\n return \"\\n\".join(lines) + \"\\n\"\n\n def has_package(self, name):\n \"\"\"\n Check if package name is in package list.\n\n Parameters\n ----------\n name : str\n Name of the package, 'DIS', 'BAS6', etc. (case-insensitive).\n\n Returns\n -------\n bool\n True if package name exists, otherwise False if not found.\n\n \"\"\"\n if not name:\n raise ValueError(\"invalid package name\")\n name = name.upper()\n for p in self.packagelist:\n for pn in p.name:\n if pn.upper() == name:\n return True\n return False\n\n def get_package(self, name):\n \"\"\"\n Get a package.\n\n Parameters\n ----------\n name : str\n Name of the package, 'RIV', 'LPF', etc. (case-insensitive).\n\n Returns\n -------\n pp : Package object\n Package object of type :class:`flopy.pakbase.Package`\n\n \"\"\"\n if not name:\n raise ValueError(\"invalid package name\")\n name = name.upper()\n for pp in self.packagelist:\n if pp.name[0].upper() == name:\n return pp\n return None\n\n def set_version(self, version):\n self.version = version.lower()\n\n # check that this is a valid model version\n if self.version not in list(self.version_types.keys()):\n err = (\n f\"Error: Unsupported model version ({self.version}). \"\n \"Valid model versions are:\"\n )\n for v in list(self.version_types.keys()):\n err += f\" {v}\"\n raise Exception(err)\n\n # set namefile heading\n self.heading = (\n f\"# Name file for {self.version_types[self.version]}, \"\n f\"generated by Flopy version {__version__}.\"\n )\n\n # set heading for each package\n for p in self.get_package_list():\n pak = self.get_package(p)\n if hasattr(pak, \"heading\"):\n pak._generate_heading()\n\n return None\n\n def change_model_ws(self, new_pth=None, reset_external=False):\n \"\"\"\n Change the model work space.\n\n Parameters\n ----------\n new_pth : str\n Location of new model workspace. If this path does not exist,\n it will be created. (default is None, which will be assigned to\n the present working directory).\n\n Returns\n -------\n val : list of strings\n Can be used to see what packages are in the model, and can then\n be used with get_package to pull out individual packages.\n\n \"\"\"\n if new_pth is None:\n new_pth = os.getcwd()\n if not os.path.exists(new_pth):\n try:\n print(f\"\\ncreating model workspace...\\n {new_pth}\")\n os.makedirs(new_pth)\n except:\n raise OSError(f\"{new_pth} not valid, workspace-folder\")\n # line = '\\n{} not valid, workspace-folder '.format(new_pth) + \\\n # 'was changed to {}\\n'.format(os.getcwd())\n # print(line)\n # new_pth = os.getcwd()\n\n # --reset the model workspace\n old_pth = self._model_ws\n self._model_ws = new_pth\n if self.verbose:\n print(f\"\\nchanging model workspace...\\n {new_pth}\")\n # reset the paths for each package\n for pp in self.packagelist:\n pp.fn_path = os.path.join(self.model_ws, pp.file_name[0])\n\n # create the external path (if needed)\n if (\n hasattr(self, \"external_path\")\n and self.external_path is not None\n and not os.path.exists(\n os.path.join(self._model_ws, self.external_path)\n )\n ):\n pth = os.path.join(self._model_ws, self.external_path)\n os.makedirs(pth)\n if reset_external:\n self._reset_external(pth, old_pth)\n elif reset_external:\n self._reset_external(self._model_ws, old_pth)\n return None\n\n def _reset_external(self, pth, old_pth):\n new_ext_fnames = []\n for ext_file, output in zip(\n self.external_fnames, self.external_output\n ):\n # new_ext_file = os.path.join(pth, os.path.split(ext_file)[-1])\n # this is a wicked mess\n if output:\n # new_ext_file = os.path.join(pth, os.path.split(ext_file)[-1])\n new_ext_file = ext_file\n else:\n # fpth = os.path.abspath(os.path.join(old_pth, ext_file))\n # new_ext_file = os.path.relpath(fpth, os.path.abspath(pth))\n fdir = os.path.dirname(ext_file)\n if fdir == \"\":\n fpth = os.path.abspath(os.path.join(old_pth, ext_file))\n else:\n fpth = ext_file\n ao = os.path.abspath(os.path.dirname(fpth))\n ep = os.path.abspath(pth)\n relp = os.path.relpath(ao, ep)\n new_ext_file = os.path.join(relp, os.path.basename(ext_file))\n new_ext_fnames.append(new_ext_file)\n self.external_fnames = new_ext_fnames\n\n @property\n def model_ws(self):\n return copy.deepcopy(self._model_ws)\n\n def _set_name(self, value):\n \"\"\"\n Set model name\n\n Parameters\n ----------\n value : str\n Name to assign to model.\n\n \"\"\"\n self.__name = str(value)\n self.namefile = self.__name + \".\" + self.namefile_ext\n for p in self.packagelist:\n for i in range(len(p.extension)):\n p.file_name[i] = self.__name + \".\" + p.extension[i]\n p.fn_path = os.path.join(self.model_ws, p.file_name[0])\n\n def __setattr__(self, key, value):\n if key == \"free_format_input\":\n # if self.bas6 is not None:\n # self.bas6.ifrefm = value\n super().__setattr__(key, value)\n elif key == \"name\":\n self._set_name(value)\n elif key == \"model_ws\":\n self.change_model_ws(value)\n elif key == \"sr\" and value.__class__.__name__ == \"SpatialReference\":\n warnings.warn(\n \"SpatialReference has been deprecated.\",\n category=DeprecationWarning,\n )\n if self.dis is not None:\n self.dis.sr = value\n else:\n raise Exception(\n \"cannot set SpatialReference - ModflowDis not found\"\n )\n elif key == \"tr\":\n assert isinstance(\n value, discretization.reference.TemporalReference\n )\n if self.dis is not None:\n self.dis.tr = value\n else:\n raise Exception(\n \"cannot set TemporalReference - ModflowDis not found\"\n )\n elif key == \"start_datetime\":\n if self.dis is not None:\n self.dis.start_datetime = value\n self.tr.start_datetime = value\n else:\n raise Exception(\n \"cannot set start_datetime - ModflowDis not found\"\n )\n else:\n super().__setattr__(key, value)\n\n def run_model(\n self,\n silent=False,\n pause=False,\n report=False,\n normal_msg=\"normal termination\",\n ):\n \"\"\"\n This method will run the model using subprocess.Popen.\n\n Parameters\n ----------\n silent : boolean\n Echo run information to screen (default is True).\n pause : boolean, optional\n Pause upon completion (default is False).\n report : boolean, optional\n Save stdout lines to a list (buff) which is returned\n by the method . (default is False).\n normal_msg : str\n Normal termination message used to determine if the\n run terminated normally. (default is 'normal termination')\n\n Returns\n -------\n (success, buff)\n success : boolean\n buff : list of lines of stdout\n\n \"\"\"\n\n return run_model(\n self.exe_name,\n self.namefile,\n model_ws=self.model_ws,\n silent=silent,\n pause=pause,\n report=report,\n normal_msg=normal_msg,\n )\n\n def load_results(self):\n\n print(\"load_results not implemented\")\n\n return None\n\n def write_input(self, SelPackList=False, check=False):\n \"\"\"\n Write the input.\n\n Parameters\n ----------\n SelPackList : False or list of packages\n\n \"\"\"\n if check:\n # run check prior to writing input\n self.check(f=f\"{self.name}.chk\", verbose=self.verbose, level=1)\n\n # reset the model to free_format if parameter substitution was\n # performed on a model load\n if self.parameter_load and not self.free_format_input:\n if self.verbose:\n print(\n \"\\nResetting free_format_input to True to \"\n \"preserve the precision of the parameter data.\"\n )\n self.free_format_input = True\n\n if self.verbose:\n print(\"\\nWriting packages:\")\n\n if SelPackList == False:\n for p in self.packagelist:\n if self.verbose:\n print(\" Package: \", p.name[0])\n # prevent individual package checks from running after\n # model-level package check above\n # otherwise checks are run twice\n # or the model level check procedure would have to be split up\n # or each package would need a check argument,\n # or default for package level check would have to be False\n try:\n p.write_file(check=False)\n except TypeError:\n p.write_file()\n else:\n for pon in SelPackList:\n for i, p in enumerate(self.packagelist):\n if pon in p.name:\n if self.verbose:\n print(\" Package: \", p.name[0])\n try:\n p.write_file(check=False)\n except TypeError:\n p.write_file()\n break\n if self.verbose:\n print(\" \")\n # write name file\n self.write_name_file()\n # os.chdir(org_dir)\n return\n\n def write_name_file(self):\n \"\"\"\n Every Package needs its own writenamefile function\n\n \"\"\"\n raise Exception(\n \"IMPLEMENTATION ERROR: writenamefile must be overloaded\"\n )\n\n def set_model_units(self):\n \"\"\"\n Every model needs its own set_model_units method\n\n \"\"\"\n raise Exception(\n \"IMPLEMENTATION ERROR: set_model_units must be overloaded\"\n )\n\n @property\n def name(self):\n \"\"\"\n Get model name\n\n Returns\n -------\n name : str\n name of model\n\n \"\"\"\n return copy.deepcopy(self.__name)\n\n def add_pop_key_list(self, key):\n \"\"\"\n Add a external file unit number to a list that will be used to remove\n model output (typically binary) files from ext_unit_dict.\n\n Parameters\n ----------\n key : int\n file unit number\n\n Returns\n -------\n\n Examples\n --------\n\n \"\"\"\n if key not in self.pop_key_list:\n self.pop_key_list.append(key)\n\n def check(self, f=None, verbose=True, level=1):\n \"\"\"\n Check model data for common errors.\n\n Parameters\n ----------\n f : str or file handle\n String defining file name or file handle for summary file\n of check method output. If a string is passed a file handle\n is created. If f is None, check method does not write\n results to a summary file. (default is None)\n verbose : bool\n Boolean flag used to determine if check method results are\n written to the screen\n level : int\n Check method analysis level. If level=0, summary checks are\n performed. If level=1, full checks are performed.\n\n Returns\n -------\n None\n\n Examples\n --------\n\n >>> import flopy\n >>> m = flopy.modflow.Modflow.load('model.nam')\n >>> m.check()\n \"\"\"\n\n # check instance for model-level check\n chk = utils.check(self, f=f, verbose=verbose, level=level)\n # check for unit number conflicts\n package_units = {}\n duplicate_units = {}\n for p in self.packagelist:\n for i in range(len(p.name)):\n if p.unit_number[i] != 0:\n if p.unit_number[i] in package_units.values():\n duplicate_units[p.name[i]] = p.unit_number[i]\n otherpackage = [\n k\n for k, v in package_units.items()\n if v == p.unit_number[i]\n ][0]\n duplicate_units[otherpackage] = p.unit_number[i]\n if len(duplicate_units) > 0:\n for k, v in duplicate_units.items():\n chk._add_to_summary(\n \"Error\", package=k, value=v, desc=\"unit number conflict\"\n )\n else:\n chk.passed.append(\"Unit number conflicts\")\n\n return self._check(chk, level)\n\n def plot(self, SelPackList=None, **kwargs):\n \"\"\"\n Plot 2-D, 3-D, transient 2-D, and stress period list (MfList)\n model input data\n\n Parameters\n ----------\n SelPackList : bool or list\n List of of packages to plot. If SelPackList=None all packages\n are plotted. (default is None)\n **kwargs : dict\n filename_base : str\n Base file name that will be used to automatically generate file\n names for output image files. Plots will be exported as image\n files if file_name_base is not None. (default is None)\n file_extension : str\n Valid matplotlib.pyplot file extension for savefig(). Only used\n if filename_base is not None. (default is 'png')\n mflay : int\n MODFLOW zero-based layer number to return. If None, then all\n all layers will be included. (default is None)\n kper : int\n MODFLOW zero-based stress period number to return.\n (default is zero)\n key : str\n MfList dictionary key. (default is None)\n\n Returns\n ----------\n axes : list\n Empty list is returned if filename_base is not None. Otherwise\n a list of matplotlib.pyplot.axis are returned.\n\n See Also\n --------\n\n Notes\n -----\n\n Examples\n --------\n >>> import flopy\n >>> ml = flopy.modflow.Modflow.load('test.nam')\n >>> ml.plot()\n\n \"\"\"\n from flopy.plot import PlotUtilities\n\n axes = PlotUtilities._plot_model_helper(\n self, SelPackList=SelPackList, **kwargs\n )\n return axes\n\n def to_shapefile(self, filename, package_names=None, **kwargs):\n \"\"\"\n Wrapper function for writing a shapefile for the model grid. If\n package_names is not None, then search through the requested packages\n looking for arrays that can be added to the shapefile as attributes\n\n Parameters\n ----------\n filename : string\n name of the shapefile to write\n package_names : list of package names (e.g. [\"dis\",\"lpf\"])\n Packages to export data arrays to shapefile. (default is None)\n\n Returns\n -------\n None\n\n Examples\n --------\n >>> import flopy\n >>> m = flopy.modflow.Modflow()\n >>> m.to_shapefile('model.shp', SelPackList)\n\n \"\"\"\n warnings.warn(\"to_shapefile() is deprecated. use .export()\")\n self.export(filename, package_names=package_names)\n return\n\n\ndef run_model(\n exe_name,\n namefile,\n model_ws=\"./\",\n silent=False,\n pause=False,\n report=False,\n normal_msg=\"normal termination\",\n use_async=False,\n cargs=None,\n):\n \"\"\"\n This function will run the model using subprocess.Popen. It\n communicates with the model's stdout asynchronously and reports\n progress to the screen with timestamps\n\n Parameters\n ----------\n exe_name : str\n Executable name (with path, if necessary) to run.\n namefile : str\n Namefile of model to run. The namefile must be the\n filename of the namefile without the path. Namefile can be None\n to allow programs that do not require a control file (name file)\n to be passed as a command line argument.\n model_ws : str\n Path to the location of the namefile. (default is the\n current working directory - './')\n silent : boolean\n Echo run information to screen (default is True).\n pause : boolean, optional\n Pause upon completion (default is False).\n report : boolean, optional\n Save stdout lines to a list (buff) which is returned\n by the method . (default is False).\n normal_msg : str or list\n Normal termination message used to determine if the\n run terminated normally. More than one message can be provided using\n a list. (Default is 'normal termination')\n use_async : boolean\n asynchronously read model stdout and report with timestamps. good for\n models that take long time to run. not good for models that run\n really fast\n cargs : str or list of strings\n additional command line arguments to pass to the executable.\n Default is None\n Returns\n -------\n (success, buff)\n success : boolean\n buff : list of lines of stdout\n\n \"\"\"\n success = False\n buff = []\n\n # convert normal_msg to a list of lower case str for comparison\n if isinstance(normal_msg, str):\n normal_msg = [normal_msg]\n for idx, s in enumerate(normal_msg):\n normal_msg[idx] = s.lower()\n\n # Check to make sure that program and namefile exist\n exe = which(exe_name)\n if exe is None:\n import platform\n\n if platform.system() in \"Windows\":\n if not exe_name.lower().endswith(\".exe\"):\n exe = which(exe_name + \".exe\")\n elif exe_name.lower().endswith(\".exe\"):\n exe = which(exe_name[:-4])\n if exe is None:\n raise Exception(\n f\"The program {exe_name} does not exist or is not executable.\"\n )\n else:\n if not silent:\n print(\n f\"FloPy is using the following executable to run the model: {exe}\"\n )\n\n if namefile is not None:\n if not os.path.isfile(os.path.join(model_ws, namefile)):\n raise Exception(\n f\"The namefile for this model does not exists: {namefile}\"\n )\n\n # simple little function for the thread to target\n def q_output(output, q):\n for line in iter(output.readline, b\"\"):\n q.put(line)\n # time.sleep(1)\n # output.close()\n\n # create a list of arguments to pass to Popen\n argv = [exe_name]\n if namefile is not None:\n argv.append(namefile)\n\n # add additional arguments to Popen arguments\n if cargs is not None:\n if isinstance(cargs, str):\n cargs = [cargs]\n for t in cargs:\n argv.append(t)\n\n # run the model with Popen\n proc = Popen(argv, stdout=PIPE, stderr=STDOUT, cwd=model_ws)\n\n if not use_async:\n while True:\n line = proc.stdout.readline().decode(\"utf-8\")\n if line == \"\" and proc.poll() is not None:\n break\n if line:\n for msg in normal_msg:\n if msg in line.lower():\n success = True\n break\n line = line.rstrip(\"\\r\\n\")\n if not silent:\n print(line)\n if report:\n buff.append(line)\n else:\n break\n return success, buff\n\n # some tricks for the async stdout reading\n q = Queue.Queue()\n thread = threading.Thread(target=q_output, args=(proc.stdout, q))\n thread.daemon = True\n thread.start()\n\n failed_words = [\"fail\", \"error\"]\n last = datetime.now()\n lastsec = 0.0\n while True:\n try:\n line = q.get_nowait()\n except Queue.Empty:\n pass\n else:\n if line == \"\":\n break\n line = line.decode().lower().strip()\n if line != \"\":\n now = datetime.now()\n dt = now - last\n tsecs = dt.total_seconds() - lastsec\n line = f\"(elapsed:{tsecs})-->{line}\"\n lastsec = tsecs + lastsec\n buff.append(line)\n if not silent:\n print(line)\n for fword in failed_words:\n if fword in line:\n success = False\n break\n if proc.poll() is not None:\n break\n proc.wait()\n thread.join(timeout=1)\n buff.extend(proc.stdout.readlines())\n proc.stdout.close()\n\n for line in buff:\n for msg in normal_msg:\n if msg in line.lower():\n print(\"success\")\n success = True\n break\n\n if pause:\n input(\"Press Enter to continue...\")\n return success, buff\n",
"import numpy as np\nimport contextlib\nimport warnings\nfrom distutils.version import LooseVersion\n\nfrom .utl_import import import_optional_dependency\n\nfrom .geometry import transform\nfrom .geospatial_utils import GeoSpatialUtil\n\nNUMPY_GE_121 = str(np.__version__) >= LooseVersion(\"1.21\")\n\nshapely = import_optional_dependency(\"shapely\", errors=\"silent\")\nif shapely is not None:\n SHAPELY_GE_20 = str(shapely.__version__) >= LooseVersion(\"2.0\")\n SHAPELY_LT_18 = str(shapely.__version__) < LooseVersion(\"1.8\")\nelse:\n SHAPELY_GE_20 = False\n SHAPELY_LT_18 = False\n\nshapely_warning = None\nif shapely is not None:\n try:\n from shapely.errors import ShapelyDeprecationWarning as shapely_warning\n except ImportError:\n pass\n\nif shapely_warning is not None and not SHAPELY_GE_20:\n\n @contextlib.contextmanager\n def ignore_shapely_warnings_for_object_array():\n with warnings.catch_warnings():\n warnings.filterwarnings(\n \"ignore\",\n \"Iteration|The array interface|__len__\",\n shapely_warning,\n )\n if NUMPY_GE_121:\n # warning from numpy for existing Shapely releases (this is\n # fixed with Shapely 1.8)\n warnings.filterwarnings(\n \"ignore\",\n \"An exception was ignored while fetching\",\n DeprecationWarning,\n )\n yield\n\nelif SHAPELY_LT_18 and NUMPY_GE_121:\n\n @contextlib.contextmanager\n def ignore_shapely_warnings_for_object_array():\n with warnings.catch_warnings():\n warnings.filterwarnings(\n \"ignore\",\n \"An exception was ignored while fetching\",\n DeprecationWarning,\n )\n yield\n\nelse:\n\n @contextlib.contextmanager\n def ignore_shapely_warnings_for_object_array():\n yield\n\n\ndef parse_shapely_ix_result(collection, ix_result, shptyps=None):\n \"\"\"Recursive function for parsing shapely intersection results. Returns a\n list of shapely shapes matching shptyp.\n\n Parameters\n ----------\n collection : list\n state variable for storing result, generally\n an empty list\n ix_result : shapely.geometry type\n any shapely intersection result\n shptyp : str, list of str, or None, optional\n if None (default), return all types of shapes.\n if str, return shapes of that type, if list of str,\n return all types in list\n\n Returns\n -------\n collection : list\n list containing shapely geometries of type shptyp\n \"\"\"\n # convert shptyps to list if needed\n if isinstance(shptyps, str):\n shptyps = [shptyps]\n elif shptyps is None:\n shptyps = [None]\n\n # if empty\n if ix_result.is_empty:\n return collection\n # base case: geom_type is partial or exact match to shptyp\n elif ix_result.geom_type in shptyps:\n collection.append(ix_result)\n return collection\n # recursion for collections\n elif hasattr(ix_result, \"geoms\"):\n for ishp in ix_result.geoms:\n parse_shapely_ix_result(collection, ishp, shptyps=shptyps)\n # if collecting all types\n elif shptyps[0] is None:\n return collection.append(ix_result)\n return collection\n\n\nclass GridIntersect:\n \"\"\"Class for intersecting shapely shapes (Point, Linestring, Polygon, or\n their Multi variants) with MODFLOW grids. Contains optimized search\n routines for structured grids.\n\n Notes\n -----\n - The STR-tree query is based on the bounding box of the shape or\n collection, if the bounding box of the shape covers nearly the entire\n grid, the query won't be able to limit the search space much, resulting\n in slower performance. Therefore, it can sometimes be faster to\n intersect each individual shape in a collection than it is to intersect\n with the whole collection at once.\n - Building the STR-tree can take a while for large grids. Once built the\n intersect routines (for individual shapes) should be pretty fast. It\n is possible to perform intersects without building the STR-tree by\n setting `rtree=False`.\n - The optimized routines for structured grids will often outperform\n the shapely routines because of the reduced overhead of building and\n parsing the STR-tree. However, for polygons the STR-tree implementation\n is often faster than the optimized structured routines, especially\n for larger grids.\n \"\"\"\n\n def __init__(self, mfgrid, method=None, rtree=True):\n \"\"\"Intersect shapes (Point, Linestring, Polygon) with a modflow grid.\n\n Parameters\n ----------\n mfgrid : flopy modflowgrid\n MODFLOW grid as implemented in flopy\n method : str, optional\n default is None, which determines intersection method based on\n the grid type. Options are either 'vertex' which uses shapely\n interesection operations or 'structured' which uses optimized\n methods that only work for structured grids\n rtree : bool, optional\n whether to build an STR-Tree, default is True. If False no\n STR-tree is built (which saves some time), but intersects will\n loop through all model gridcells (which is generally slower).\n Only read when `method='vertex'`.\n \"\"\"\n\n self.mfgrid = mfgrid\n if method is None:\n # determine method from grid_type\n self.method = self.mfgrid.grid_type\n else:\n # set method\n self.method = method\n self.rtree = rtree\n\n if self.method == \"vertex\":\n # set method to get gridshapes depending on grid type\n self._set_method_get_gridshapes()\n\n # build STR-tree if specified\n if self.rtree:\n strtree = import_optional_dependency(\n \"shapely.strtree\",\n error_message=\"STRTree requires shapely\",\n )\n self.strtree = strtree.STRtree(self._get_gridshapes())\n\n elif self.method == \"structured\" and mfgrid.grid_type == \"structured\":\n pass\n\n else:\n raise ValueError(\n \"Method '{0}' not recognized or \"\n \"not supported \"\n \"for grid_type '{1}'!\".format(\n self.method, self.mfgrid.grid_type\n )\n )\n\n def intersect(\n self, shp, shapetype=None, sort_by_cellid=True, keepzerolengths=False\n ):\n \"\"\"Method to intersect a shape with a model grid.\n\n Parameters\n ----------\n shp : shapely.geometry, geojson object, shapefile.Shape,\n or flopy geometry object\n shapetype : str, optional\n type of shape (i.e. \"point\", \"linestring\", \"polygon\" or\n their multi-variants), used by GeoSpatialUtil if shp is\n passed as a list of vertices, default is None\n sort_by_cellid : bool\n sort results by cellid, ensures cell with lowest cellid is\n returned for boundary cases when using vertex methods, default\n is True\n keepzerolengths : bool\n boolean method to keep zero length intersections for\n linestring intersection, used when shp is of type \"linestring\"\n\n Returns\n -------\n numpy.recarray\n a record array containing information about the intersection\n \"\"\"\n gu = GeoSpatialUtil(shp, shapetype=shapetype)\n shp = gu.shapely\n\n if gu.shapetype in (\"Point\", \"MultiPoint\"):\n if (\n self.method == \"structured\"\n and self.mfgrid.grid_type == \"structured\"\n ):\n rec = self._intersect_point_structured(shp)\n else:\n rec = self._intersect_point_shapely(shp, sort_by_cellid)\n elif gu.shapetype in (\"LineString\", \"MultiLineString\"):\n if (\n self.method == \"structured\"\n and self.mfgrid.grid_type == \"structured\"\n ):\n rec = self._intersect_linestring_structured(\n shp, keepzerolengths\n )\n else:\n rec = self._intersect_linestring_shapely(\n shp, keepzerolengths, sort_by_cellid\n )\n elif gu.shapetype in (\"Polygon\", \"MultiPolygon\"):\n if (\n self.method == \"structured\"\n and self.mfgrid.grid_type == \"structured\"\n ):\n rec = self._intersect_polygon_structured(shp)\n else:\n rec = self._intersect_polygon_shapely(shp, sort_by_cellid)\n else:\n err = f\"Shapetype {gu.shapetype} is not supported\"\n raise TypeError(err)\n\n return rec\n\n def _set_method_get_gridshapes(self):\n \"\"\"internal method, set self._get_gridshapes to the certain method for\n obtaining gridcells.\"\"\"\n # Set method for obtaining grid shapes\n if self.mfgrid.grid_type == \"structured\":\n self._get_gridshapes = self._rect_grid_to_shape_generator\n elif self.mfgrid.grid_type == \"vertex\":\n self._get_gridshapes = self._vtx_grid_to_shape_generator\n elif self.mfgrid.grid_type == \"unstructured\":\n raise NotImplementedError()\n\n def _rect_grid_to_shape_generator(self):\n \"\"\"internal method, generator yielding shapely polygons for structured\n grid cells.\n\n Returns\n -------\n generator :\n generator of shapely Polygons\n \"\"\"\n shapely_geo = import_optional_dependency(\"shapely.geometry\")\n\n for i in range(self.mfgrid.nrow):\n for j in range(self.mfgrid.ncol):\n xy = self.mfgrid.get_cell_vertices(i, j)\n p = shapely_geo.Polygon(xy)\n p.name = (i, j)\n yield p\n\n def _usg_grid_to_shape_generator(self):\n \"\"\"internal method, convert unstructred grid to list of shapely\n polygons.\n\n Returns\n -------\n list\n list of shapely Polygons\n \"\"\"\n raise NotImplementedError()\n\n def _vtx_grid_to_shape_generator(self):\n \"\"\"internal method, generator yielding shapely polygons for vertex\n grids.\n\n Returns\n -------\n generator :\n generator of shapely Polygons\n \"\"\"\n shapely_geo = import_optional_dependency(\"shapely.geometry\")\n\n # for cell2d rec-arrays\n if isinstance(self.mfgrid._cell2d, np.recarray):\n for icell in self.mfgrid._cell2d.icell2d:\n points = []\n icverts = [\n f\"icvert_{i}\"\n for i in range(self.mfgrid._cell2d[\"ncvert\"][icell])\n ]\n for iv in self.mfgrid._cell2d[icverts][icell]:\n points.append(\n (\n self.mfgrid._vertices.xv[iv],\n self.mfgrid._vertices.yv[iv],\n )\n )\n # close the polygon, if necessary\n if points[0] != points[-1]:\n points.append(points[0])\n p = shapely_geo.Polygon(points)\n p.name = icell\n yield p\n # for cell2d lists\n elif isinstance(self.mfgrid._cell2d, list):\n for icell in range(len(self.mfgrid._cell2d)):\n points = []\n for iv in self.mfgrid._cell2d[icell][4:]:\n points.append(\n (\n self.mfgrid._vertices[iv][1],\n self.mfgrid._vertices[iv][2],\n )\n )\n # close the polygon, if necessary\n if points[0] != points[-1]:\n points.append(points[0])\n p = shapely_geo.Polygon(points)\n p.name = icell\n yield p\n\n def _rect_grid_to_shape_list(self):\n \"\"\"internal method, list of shapely polygons for structured grid cells.\n\n Returns\n -------\n list :\n list of shapely Polygons\n \"\"\"\n return list(self._rect_grid_to_shape_generator())\n\n def _usg_grid_to_shape_list(self):\n \"\"\"internal method, convert unstructred grid to list of shapely\n polygons.\n\n Returns\n -------\n list\n list of shapely Polygons\n \"\"\"\n raise NotImplementedError()\n\n def _vtx_grid_to_shape_list(self):\n \"\"\"internal method, list of shapely polygons for vertex grids.\n\n Returns\n -------\n list :\n list of shapely Polygons\n \"\"\"\n return list(self._vtx_grid_to_shape_generator())\n\n def query_grid(self, shp):\n \"\"\"Perform spatial query on grid with shapely geometry. If no spatial\n query is possible returns all grid cells.\n\n Parameters\n ----------\n shp : shapely.geometry\n shapely geometry\n\n Returns\n -------\n list or generator expression\n list or generator containing grid cells in query result\n \"\"\"\n if self.rtree:\n result = self.strtree.query(shp)\n else:\n # no spatial query\n result = self._get_gridshapes()\n return result\n\n @staticmethod\n def filter_query_result(qresult, shp):\n \"\"\"Filter query result to obtain grid cells that intersect with shape.\n Used to (further) reduce query result to cells that definitely\n intersect with shape.\n\n Parameters\n ----------\n qresult : iterable\n query result, iterable of polygons\n shp : shapely.geometry\n shapely geometry that is prepared and used to filter\n query result\n\n Returns\n -------\n qfiltered\n filter or generator containing polygons that intersect with shape\n \"\"\"\n # prepare shape for efficient batch intersection check\n prepared = import_optional_dependency(\"shapely.prepared\")\n prepshp = prepared.prep(shp)\n # get only gridcells that intersect\n qfiltered = filter(prepshp.intersects, qresult)\n return qfiltered\n\n @staticmethod\n def sort_gridshapes(shape_iter):\n \"\"\"Sort query result by node id.\n\n Parameters\n ----------\n shape_iter : iterable\n list or iterable of gridcells\n\n Returns\n -------\n list\n sorted list of gridcells\n \"\"\"\n if not isinstance(shape_iter, list):\n shapelist = list(shape_iter)\n else:\n shapelist = shape_iter\n\n def sort_key(o):\n return o.name\n\n shapelist.sort(key=sort_key)\n return shapelist\n\n def _intersect_point_shapely(self, shp, sort_by_cellid=True):\n \"\"\"intersect grid with Point or MultiPoint.\n\n Parameters\n ----------\n shp : Point or MultiPoint\n shapely Point or MultiPoint to intersect with grid. Note,\n it is generally faster to loop over a MultiPoint and intersect\n per point than to intersect a MultiPoint directly.\n sort_by_cellid : bool, optional\n flag whether to sort cells by id, used to ensure node\n with lowest id is returned, by default True\n\n Returns\n -------\n numpy.recarray\n a record array containing information about the intersection\n \"\"\"\n shapely_geo = import_optional_dependency(\"shapely.geometry\")\n prepared = import_optional_dependency(\"shapely.prepared\")\n\n # query grid\n qresult = self.query_grid(shp)\n # prepare shape for efficient batch intersection check\n prepshp = prepared.prep(shp)\n # get only gridcells that intersect\n qfiltered = filter(prepshp.intersects, qresult)\n\n # sort cells to ensure lowest cell ids are returned\n if sort_by_cellid:\n qfiltered = self.sort_gridshapes(qfiltered)\n\n isectshp = []\n cellids = []\n vertices = []\n parsed_points = [] # for keeping track of points\n\n # loop over cells returned by filtered spatial query\n for r in qfiltered:\n name = r.name\n # do intersection\n intersect = shp.intersection(r)\n # parse result per Point\n collection = parse_shapely_ix_result(\n [], intersect, shptyps=[\"Point\"]\n )\n # loop over intersection result and store information\n cell_verts = []\n cell_shps = []\n for c in collection:\n verts = c.__geo_interface__[\"coordinates\"]\n # avoid returning multiple cells for points on boundaries\n if verts in parsed_points:\n continue\n parsed_points.append(verts)\n cell_shps.append(c) # collect only new points\n cell_verts.append(verts)\n # if any new ix found\n if len(cell_shps) > 0:\n # combine new points in MultiPoint\n isectshp.append(\n shapely_geo.MultiPoint(cell_shps)\n if len(cell_shps) > 1\n else cell_shps[0]\n )\n vertices.append(tuple(cell_verts))\n cellids.append(name)\n\n rec = np.recarray(\n len(isectshp),\n names=[\"cellids\", \"vertices\", \"ixshapes\"],\n formats=[\"O\", \"O\", \"O\"],\n )\n with ignore_shapely_warnings_for_object_array():\n rec.ixshapes = isectshp\n rec.vertices = vertices\n rec.cellids = cellids\n\n return rec\n\n def _intersect_linestring_shapely(\n self, shp, keepzerolengths=False, sort_by_cellid=True\n ):\n \"\"\"intersect with LineString or MultiLineString.\n\n Parameters\n ----------\n shp : shapely.geometry.LineString or MultiLineString\n LineString to intersect with the grid\n keepzerolengths : bool, optional\n keep linestrings with length zero, default is False\n sort_by_cellid : bool, optional\n flag whether to sort cells by id, used to ensure node\n with lowest id is returned, by default True\n\n Returns\n -------\n numpy.recarray\n a record array containing information about the intersection\n \"\"\"\n # query grid\n qresult = self.query_grid(shp)\n # filter result further if possible (only strtree and filter methods)\n qfiltered = self.filter_query_result(qresult, shp)\n # sort cells to ensure lowest cell ids are returned\n if sort_by_cellid:\n qfiltered = self.sort_gridshapes(qfiltered)\n\n # initialize empty lists for storing results\n isectshp = []\n cellids = []\n vertices = []\n lengths = []\n\n # loop over cells returned by filtered spatial query\n for r in qfiltered:\n name = r.name\n # do intersection\n intersect = shp.intersection(r)\n # parse result\n collection = parse_shapely_ix_result(\n [], intersect, shptyps=[\"LineString\", \"MultiLineString\"]\n )\n # loop over intersection result and store information\n for c in collection:\n verts = c.__geo_interface__[\"coordinates\"]\n # test if linestring was already processed (if on boundary)\n if verts in vertices:\n continue\n # if keep zero don't check length\n if not keepzerolengths:\n if c.length == 0.0:\n continue\n isectshp.append(c)\n lengths.append(c.length)\n vertices.append(verts)\n cellids.append(name)\n\n rec = np.recarray(\n len(isectshp),\n names=[\"cellids\", \"vertices\", \"lengths\", \"ixshapes\"],\n formats=[\"O\", \"O\", \"f8\", \"O\"],\n )\n with ignore_shapely_warnings_for_object_array():\n rec.ixshapes = isectshp\n rec.vertices = vertices\n rec.lengths = lengths\n rec.cellids = cellids\n\n return rec\n\n def _intersect_polygon_shapely(self, shp, sort_by_cellid=True):\n \"\"\"intersect with Polygon or MultiPolygon.\n\n Parameters\n ----------\n shp : shapely.geometry.Polygon or MultiPolygon\n shape to intersect with the grid\n sort_by_cellid : bool, optional\n flag whether to sort cells by id, used to ensure node\n with lowest id is returned, by default True\n\n Returns\n -------\n numpy.recarray\n a record array containing information about the intersection\n \"\"\"\n shapely_geo = import_optional_dependency(\"shapely.geometry\")\n\n # query grid\n qresult = self.query_grid(shp)\n # filter result further if possible (only strtree and filter methods)\n qfiltered = self.filter_query_result(qresult, shp)\n # sort cells to ensure lowest cell ids are returned\n if sort_by_cellid:\n qfiltered = self.sort_gridshapes(qfiltered)\n\n isectshp = []\n cellids = []\n vertices = []\n areas = []\n\n # loop over cells returned by filtered spatial query\n for r in qfiltered:\n name = r.name\n # do intersection\n intersect = shp.intersection(r)\n # parse result\n collection = parse_shapely_ix_result(\n [], intersect, shptyps=[\"Polygon\", \"MultiPolygon\"]\n )\n if len(collection) > 1:\n collection = [shapely_geo.MultiPolygon(collection)]\n # loop over intersection result and store information\n for c in collection:\n # don't store intersections with 0 area\n if c.area == 0.0:\n continue\n verts = c.__geo_interface__[\"coordinates\"]\n isectshp.append(c)\n areas.append(c.area)\n vertices.append(verts)\n cellids.append(name)\n\n rec = np.recarray(\n len(isectshp),\n names=[\"cellids\", \"vertices\", \"areas\", \"ixshapes\"],\n formats=[\"O\", \"O\", \"f8\", \"O\"],\n )\n with ignore_shapely_warnings_for_object_array():\n rec.ixshapes = isectshp\n rec.vertices = vertices\n rec.areas = areas\n rec.cellids = cellids\n\n return rec\n\n def intersects(self, shp, shapetype=None):\n \"\"\"Return cellIDs for shapes that intersect with shape.\n\n Parameters\n ----------\n shp : shapely.geometry, geojson geometry, shapefile.shape,\n or flopy geometry object\n shape to intersect with the grid\n shapetype : str, optional\n type of shape (i.e. \"point\", \"linestring\", \"polygon\" or\n their multi-variants), used by GeoSpatialUtil if shp is\n passed as a list of vertices, default is None\n Returns\n -------\n rec : numpy.recarray\n a record array containing cell IDs of the gridcells\n the shape intersects with\n \"\"\"\n # query grid\n shp = GeoSpatialUtil(shp, shapetype=shapetype).shapely\n\n qresult = self.query_grid(shp)\n # filter result further if possible (only strtree and filter methods)\n qfiltered = self.filter_query_result(qresult, shp)\n # get cellids\n cids = [cell.name for cell in qfiltered]\n # build rec-array\n rec = np.recarray(len(cids), names=[\"cellids\"], formats=[\"O\"])\n rec.cellids = cids\n return rec\n\n def _intersect_point_structured(self, shp):\n \"\"\"intersection method for intersecting points with structured grids.\n\n Parameters\n ----------\n shp : shapely.geometry.Point or MultiPoint\n point shape to intersect with grid\n\n Returns\n -------\n numpy.recarray\n a record array containing information about the intersection\n \"\"\"\n shapely_geo = import_optional_dependency(\"shapely.geometry\")\n\n nodelist = []\n\n Xe, Ye = self.mfgrid.xyedges\n\n if isinstance(shp, shapely_geo.Point):\n shp = [shp]\n elif isinstance(shp, shapely_geo.MultiPoint):\n shp = list(shp.geoms)\n else:\n raise ValueError(\"expected Point or MultiPoint\")\n\n ixshapes = []\n for p in shp:\n # if grid is rotated or offset transform point to local coords\n if (\n self.mfgrid.angrot != 0.0\n or self.mfgrid.xoffset != 0.0\n or self.mfgrid.yoffset != 0.0\n ):\n rx, ry = transform(\n p.x,\n p.y,\n self.mfgrid.xoffset,\n self.mfgrid.yoffset,\n self.mfgrid.angrot_radians,\n inverse=True,\n )\n else:\n rx = p.x\n ry = p.y\n\n # two dimensional point\n jpos = ModflowGridIndices.find_position_in_array(Xe, rx)\n ipos = ModflowGridIndices.find_position_in_array(Ye, ry)\n\n if jpos is not None and ipos is not None:\n # three dimensional point\n if p._ndim == 3:\n # find k\n kpos = ModflowGridIndices.find_position_in_array(\n self.mfgrid.botm[:, ipos, jpos], p.z\n )\n if kpos is not None:\n nodelist.append((kpos, ipos, jpos))\n ixshapes.append(p)\n else:\n nodelist.append((ipos, jpos))\n ixshapes.append(p)\n\n # remove duplicates\n tempnodes = []\n tempshapes = []\n for node, ixs in zip(nodelist, ixshapes):\n if node not in tempnodes:\n tempnodes.append(node)\n tempshapes.append(ixs)\n else:\n tempshapes[-1] = shapely_geo.MultiPoint([tempshapes[-1], ixs])\n\n ixshapes = tempshapes\n nodelist = tempnodes\n\n rec = np.recarray(\n len(nodelist), names=[\"cellids\", \"ixshapes\"], formats=[\"O\", \"O\"]\n )\n rec.cellids = nodelist\n with ignore_shapely_warnings_for_object_array():\n rec.ixshapes = ixshapes\n return rec\n\n def _intersect_linestring_structured(self, shp, keepzerolengths=False):\n \"\"\"method for intersecting linestrings with structured grids.\n\n Parameters\n ----------\n shp : shapely.geometry.Linestring or MultiLineString\n linestring to intersect with grid\n keepzerolengths : bool, optional\n if True keep intersection results with length=0, in\n other words, grid cells the linestring does not cross\n but does touch, by default False\n\n Returns\n -------\n numpy.recarray\n a record array containing information about the intersection\n \"\"\"\n shapely_geo = import_optional_dependency(\"shapely.geometry\")\n affinity_loc = import_optional_dependency(\"shapely.affinity\")\n\n # get local extent of grid\n if (\n self.mfgrid.angrot != 0.0\n or self.mfgrid.xoffset != 0.0\n or self.mfgrid.yoffset != 0.0\n ):\n xmin = np.min(self.mfgrid.xyedges[0])\n xmax = np.max(self.mfgrid.xyedges[0])\n ymin = np.min(self.mfgrid.xyedges[1])\n ymax = np.max(self.mfgrid.xyedges[1])\n else:\n xmin, xmax, ymin, ymax = self.mfgrid.extent\n pl = shapely_geo.box(xmin, ymin, xmax, ymax)\n\n # rotate and translate linestring to local coords\n if self.mfgrid.xoffset != 0.0 or self.mfgrid.yoffset != 0.0:\n shp = affinity_loc.translate(\n shp, xoff=-self.mfgrid.xoffset, yoff=-self.mfgrid.yoffset\n )\n if self.mfgrid.angrot != 0.0:\n shp = affinity_loc.rotate(\n shp, -self.mfgrid.angrot, origin=(0.0, 0.0)\n )\n\n # clip line to mfgrid bbox\n lineclip = shp.intersection(pl)\n\n if lineclip.length == 0.0: # linestring does not intersect modelgrid\n return np.recarray(\n 0,\n names=[\"cellids\", \"vertices\", \"lengths\", \"ixshapes\"],\n formats=[\"O\", \"O\", \"f8\", \"O\"],\n )\n if lineclip.geom_type == \"MultiLineString\": # there are multiple lines\n nodelist, lengths, vertices = [], [], []\n ixshapes = []\n for ls in lineclip.geoms:\n n, l, v, ixs = self._get_nodes_intersecting_linestring(ls)\n nodelist += n\n lengths += l\n # if necessary, transform coordinates back to real\n # world coordinates\n if (\n self.mfgrid.angrot != 0.0\n or self.mfgrid.xoffset != 0.0\n or self.mfgrid.yoffset != 0.0\n ):\n v_realworld = []\n for pt in v:\n pt = np.array(pt)\n rx, ry = transform(\n pt[:, 0],\n pt[:, 1],\n self.mfgrid.xoffset,\n self.mfgrid.yoffset,\n self.mfgrid.angrot_radians,\n inverse=False,\n )\n v_realworld.append(list(zip(rx, ry)))\n ixs_realworld = []\n for ix in ixs:\n ix_realworld = affinity_loc.rotate(\n ix, self.mfgrid.angrot, origin=(0.0, 0.0)\n )\n ix_realworld = affinity_loc.translate(\n ix_realworld,\n self.mfgrid.xoffset,\n self.mfgrid.yoffset,\n )\n ixs_realworld.append(ix_realworld)\n else:\n v_realworld = v\n ixs_realworld = ixs\n vertices += v_realworld\n ixshapes += ixs_realworld\n else: # linestring is fully within grid\n (\n nodelist,\n lengths,\n vertices,\n ixshapes,\n ) = self._get_nodes_intersecting_linestring(lineclip)\n # if necessary, transform coordinates back to real\n # world coordinates\n if (\n self.mfgrid.angrot != 0.0\n or self.mfgrid.xoffset != 0.0\n or self.mfgrid.yoffset != 0.0\n ):\n v_realworld = []\n for pt in vertices:\n pt = np.array(pt)\n rx, ry = transform(\n pt[:, 0],\n pt[:, 1],\n self.mfgrid.xoffset,\n self.mfgrid.yoffset,\n self.mfgrid.angrot_radians,\n inverse=False,\n )\n v_realworld.append(list(zip(rx, ry)))\n vertices = v_realworld\n\n ix_shapes_realworld = []\n for ixs in ixshapes:\n ixs = affinity_loc.rotate(\n ixs, self.mfgrid.angrot, origin=(0.0, 0.0)\n )\n ixs = affinity_loc.translate(\n ixs, self.mfgrid.xoffset, self.mfgrid.yoffset\n )\n ix_shapes_realworld.append(ixs)\n ixshapes = ix_shapes_realworld\n\n # bundle linestrings in same cell\n tempnodes = []\n templengths = []\n tempverts = []\n tempshapes = []\n unique_nodes = list(set(nodelist))\n if len(unique_nodes) < len(nodelist):\n for inode in unique_nodes:\n templengths.append(\n sum([l for l, i in zip(lengths, nodelist) if i == inode])\n )\n tempverts.append(\n [v for v, i in zip(vertices, nodelist) if i == inode]\n )\n tempshapes.append(\n [ix for ix, i in zip(ixshapes, nodelist) if i == inode]\n )\n\n nodelist = unique_nodes\n lengths = templengths\n vertices = tempverts\n ixshapes = tempshapes\n\n # eliminate any nodes that have a zero length\n if not keepzerolengths:\n tempnodes = []\n templengths = []\n tempverts = []\n tempshapes = []\n for i, _ in enumerate(nodelist):\n if lengths[i] > 0:\n tempnodes.append(nodelist[i])\n templengths.append(lengths[i])\n tempverts.append(vertices[i])\n tempshapes.append(ixshapes[i])\n nodelist = tempnodes\n lengths = templengths\n vertices = tempverts\n ixshapes = tempshapes\n\n rec = np.recarray(\n len(nodelist),\n names=[\"cellids\", \"vertices\", \"lengths\", \"ixshapes\"],\n formats=[\"O\", \"O\", \"f8\", \"O\"],\n )\n rec.vertices = vertices\n rec.lengths = lengths\n rec.cellids = nodelist\n with ignore_shapely_warnings_for_object_array():\n rec.ixshapes = ixshapes\n\n return rec\n\n def _get_nodes_intersecting_linestring(self, linestring):\n \"\"\"helper function, intersect the linestring with the a structured grid\n and return a list of node indices and the length of the line in that\n node.\n\n Parameters\n ----------\n linestring: shapely.geometry.LineString or MultiLineString\n shape to intersect with the grid\n\n Returns\n -------\n nodelist, lengths, vertices: lists\n lists containing node ids, lengths of intersects and the\n start and end points of the intersects\n \"\"\"\n shapely_geo = import_optional_dependency(\"shapely.geometry\")\n\n nodelist = []\n lengths = []\n vertices = []\n ixshapes = []\n\n # start at the beginning of the line\n x, y = linestring.xy\n\n # linestring already in local coords but\n # because intersect_point does transform again\n # we transform back to real world here if necessary\n if (\n self.mfgrid.angrot != 0.0\n or self.mfgrid.xoffset != 0.0\n or self.mfgrid.yoffset != 0.0\n ):\n x0, y0 = transform(\n [x[0]],\n [y[0]],\n self.mfgrid.xoffset,\n self.mfgrid.yoffset,\n self.mfgrid.angrot_radians,\n inverse=False,\n )\n else:\n x0 = [x[0]]\n y0 = [y[0]]\n\n (i, j) = self.intersect(shapely_geo.Point(x0[0], y0[0])).cellids[0]\n Xe, Ye = self.mfgrid.xyedges\n xmin = Xe[j]\n xmax = Xe[j + 1]\n ymax = Ye[i]\n ymin = Ye[i + 1]\n pl = shapely_geo.box(xmin, ymin, xmax, ymax)\n intersect = linestring.intersection(pl)\n # if linestring starts in cell, exits, and re-enters\n # a MultiLineString is returned.\n ixshapes.append(intersect)\n length = intersect.length\n lengths.append(length)\n if hasattr(intersect, \"geoms\"):\n x, y = [], []\n for igeom in intersect.geoms:\n x.append(igeom.xy[0])\n y.append(igeom.xy[1])\n x = np.concatenate(x)\n y = np.concatenate(y)\n else:\n x = intersect.xy[0]\n y = intersect.xy[1]\n verts = [(ixy[0], ixy[1]) for ixy in zip(x, y)]\n vertices.append(verts)\n nodelist.append((i, j))\n\n n = 0\n while True:\n (i, j) = nodelist[n]\n (\n node,\n length,\n verts,\n ixshape,\n ) = self._check_adjacent_cells_intersecting_line(\n linestring, (i, j), nodelist\n )\n\n for inode, ilength, ivert, ix in zip(node, length, verts, ixshape):\n if inode is not None:\n if ivert not in vertices:\n nodelist.append(inode)\n lengths.append(ilength)\n vertices.append(ivert)\n ixshapes.append(ix)\n\n if n == len(nodelist) - 1:\n break\n n += 1\n\n return nodelist, lengths, vertices, ixshapes\n\n def _check_adjacent_cells_intersecting_line(\n self, linestring, i_j, nodelist\n ):\n \"\"\"helper method that follows a line through a structured grid.\n\n Parameters\n ----------\n linestring : shapely.geometry.LineString\n shape to intersect with the grid\n i_j : tuple\n tuple containing (nrow, ncol)\n nodelist : list of tuples\n list of node ids that have already been added\n as intersections\n\n Returns\n -------\n node, length, verts: lists\n lists containing nodes, lengths and vertices of\n intersections with adjacent cells relative to the\n current cell (i, j)\n \"\"\"\n shapely_geo = import_optional_dependency(\"shapely.geometry\")\n\n i, j = i_j\n\n Xe, Ye = self.mfgrid.xyedges\n\n node = []\n length = []\n verts = []\n ixshape = []\n\n # check to left\n if j > 0:\n ii = i\n jj = j - 1\n if (ii, jj) not in nodelist:\n xmin = Xe[jj]\n xmax = Xe[jj + 1]\n ymax = Ye[ii]\n ymin = Ye[ii + 1]\n pl = shapely_geo.box(xmin, ymin, xmax, ymax)\n if linestring.intersects(pl):\n intersect = linestring.intersection(pl)\n ixshape.append(intersect)\n length.append(intersect.length)\n if hasattr(intersect, \"geoms\"):\n x, y = [], []\n for igeom in intersect.geoms:\n x.append(igeom.xy[0])\n y.append(igeom.xy[1])\n x = np.concatenate(x)\n y = np.concatenate(y)\n else:\n x = intersect.xy[0]\n y = intersect.xy[1]\n verts.append([(ixy[0], ixy[1]) for ixy in zip(x, y)])\n node.append((ii, jj))\n\n # check to right\n if j < self.mfgrid.ncol - 1:\n ii = i\n jj = j + 1\n if (ii, jj) not in nodelist:\n xmin = Xe[jj]\n xmax = Xe[jj + 1]\n ymax = Ye[ii]\n ymin = Ye[ii + 1]\n pl = shapely_geo.box(xmin, ymin, xmax, ymax)\n if linestring.intersects(pl):\n intersect = linestring.intersection(pl)\n ixshape.append(intersect)\n length.append(intersect.length)\n if hasattr(intersect, \"geoms\"):\n x, y = [], []\n for igeom in intersect.geoms:\n x.append(igeom.xy[0])\n y.append(igeom.xy[1])\n x = np.concatenate(x)\n y = np.concatenate(y)\n else:\n x = intersect.xy[0]\n y = intersect.xy[1]\n verts.append([(ixy[0], ixy[1]) for ixy in zip(x, y)])\n node.append((ii, jj))\n\n # check to back\n if i > 0:\n ii = i - 1\n jj = j\n if (ii, jj) not in nodelist:\n xmin = Xe[jj]\n xmax = Xe[jj + 1]\n ymax = Ye[ii]\n ymin = Ye[ii + 1]\n pl = shapely_geo.box(xmin, ymin, xmax, ymax)\n if linestring.intersects(pl):\n intersect = linestring.intersection(pl)\n ixshape.append(intersect)\n length.append(intersect.length)\n if hasattr(intersect, \"geoms\"):\n x, y = [], []\n for igeom in intersect.geoms:\n x.append(igeom.xy[0])\n y.append(igeom.xy[1])\n x = np.concatenate(x)\n y = np.concatenate(y)\n else:\n x = intersect.xy[0]\n y = intersect.xy[1]\n verts.append([(ixy[0], ixy[1]) for ixy in zip(x, y)])\n node.append((ii, jj))\n\n # check to front\n if i < self.mfgrid.nrow - 1:\n ii = i + 1\n jj = j\n if (ii, jj) not in nodelist:\n xmin = Xe[jj]\n xmax = Xe[jj + 1]\n ymax = Ye[ii]\n ymin = Ye[ii + 1]\n pl = shapely_geo.box(xmin, ymin, xmax, ymax)\n if linestring.intersects(pl):\n intersect = linestring.intersection(pl)\n ixshape.append(intersect)\n length.append(intersect.length)\n if hasattr(intersect, \"geoms\"):\n x, y = [], []\n for igeom in intersect.geoms:\n x.append(igeom.xy[0])\n y.append(igeom.xy[1])\n x = np.concatenate(x)\n y = np.concatenate(y)\n else:\n x = intersect.xy[0]\n y = intersect.xy[1]\n verts.append([(ixy[0], ixy[1]) for ixy in zip(x, y)])\n node.append((ii, jj))\n\n return node, length, verts, ixshape\n\n def _intersect_rectangle_structured(self, rectangle):\n \"\"\"intersect a rectangle with a structured grid to retrieve node ids of\n intersecting grid cells.\n\n Note: only works in local coordinates (i.e. non-rotated grid\n with origin at (0, 0))\n\n Parameters\n ----------\n rectangle : list of tuples\n list of lower-left coordinate and upper-right\n coordinate: [(xmin, ymin), (xmax, ymax)]\n\n Returns\n -------\n nodelist: list of tuples\n list of tuples containing node ids with which\n the rectangle intersects\n \"\"\"\n\n shapely_geo = import_optional_dependency(\"shapely.geometry\")\n\n nodelist = []\n\n # return if rectangle does not contain any cells\n if (\n self.mfgrid.angrot != 0.0\n or self.mfgrid.xoffset != 0.0\n or self.mfgrid.yoffset != 0.0\n ):\n minx = np.min(self.mfgrid.xyedges[0])\n maxx = np.max(self.mfgrid.xyedges[0])\n miny = np.min(self.mfgrid.xyedges[1])\n maxy = np.max(self.mfgrid.xyedges[1])\n local_extent = [minx, maxx, miny, maxy]\n else:\n local_extent = self.mfgrid.extent\n\n xmin, xmax, ymin, ymax = local_extent\n bgrid = shapely_geo.box(xmin, ymin, xmax, ymax)\n (rxmin, rymin), (rxmax, rymax) = rectangle\n b = shapely_geo.box(rxmin, rymin, rxmax, rymax)\n\n if not b.intersects(bgrid):\n # return with nodelist as an empty list\n return []\n\n Xe, Ye = self.mfgrid.xyedges\n\n jmin = ModflowGridIndices.find_position_in_array(Xe, xmin)\n if jmin is None:\n if xmin <= Xe[0]:\n jmin = 0\n elif xmin >= Xe[-1]:\n jmin = self.mfgrid.ncol - 1\n\n jmax = ModflowGridIndices.find_position_in_array(Xe, xmax)\n if jmax is None:\n if xmax <= Xe[0]:\n jmax = 0\n elif xmax >= Xe[-1]:\n jmax = self.mfgrid.ncol - 1\n\n imin = ModflowGridIndices.find_position_in_array(Ye, ymax)\n if imin is None:\n if ymax >= Ye[0]:\n imin = 0\n elif ymax <= Ye[-1]:\n imin = self.mfgrid.nrow - 1\n\n imax = ModflowGridIndices.find_position_in_array(Ye, ymin)\n if imax is None:\n if ymin >= Ye[0]:\n imax = 0\n elif ymin <= Ye[-1]:\n imax = self.mfgrid.nrow - 1\n\n for i in range(imin, imax + 1):\n for j in range(jmin, jmax + 1):\n nodelist.append((i, j))\n\n return nodelist\n\n def _intersect_polygon_structured(self, shp):\n \"\"\"intersect polygon with a structured grid. Uses bounding box of the\n Polygon to limit search space.\n\n Notes\n -----\n If performance is slow, try setting the method to 'vertex'\n in the GridIntersect object. For polygons this is often\n faster.\n\n Parameters\n ----------\n shp : shapely.geometry.Polygon\n polygon to intersect with the grid\n\n Returns\n -------\n numpy.recarray\n a record array containing information about the intersection\n \"\"\"\n shapely_geo = import_optional_dependency(\"shapely.geometry\")\n affinity_loc = import_optional_dependency(\"shapely.affinity\")\n\n # initialize the result lists\n nodelist = []\n areas = []\n vertices = []\n ixshapes = []\n\n # transform polygon to local grid coordinates\n if self.mfgrid.xoffset != 0.0 or self.mfgrid.yoffset != 0.0:\n shp = affinity_loc.translate(\n shp, xoff=-self.mfgrid.xoffset, yoff=-self.mfgrid.yoffset\n )\n if self.mfgrid.angrot != 0.0:\n shp = affinity_loc.rotate(\n shp, -self.mfgrid.angrot, origin=(0.0, 0.0)\n )\n\n # use the bounds of the polygon to restrict the cell search\n minx, miny, maxx, maxy = shp.bounds\n rectangle = ((minx, miny), (maxx, maxy))\n nodes = self._intersect_rectangle_structured(rectangle)\n\n for (i, j) in nodes:\n if (\n self.mfgrid.angrot != 0.0\n or self.mfgrid.xoffset != 0.0\n or self.mfgrid.yoffset != 0.0\n ):\n cell_coords = [\n (self.mfgrid.xyedges[0][j], self.mfgrid.xyedges[1][i]),\n (self.mfgrid.xyedges[0][j + 1], self.mfgrid.xyedges[1][i]),\n (\n self.mfgrid.xyedges[0][j + 1],\n self.mfgrid.xyedges[1][i + 1],\n ),\n (self.mfgrid.xyedges[0][j], self.mfgrid.xyedges[1][i + 1]),\n ]\n else:\n cell_coords = self.mfgrid.get_cell_vertices(i, j)\n node_polygon = shapely_geo.Polygon(cell_coords)\n if shp.intersects(node_polygon):\n intersect = shp.intersection(node_polygon)\n if intersect.area > 0.0:\n nodelist.append((i, j))\n areas.append(intersect.area)\n\n # if necessary, transform coordinates back to real\n # world coordinates\n if (\n self.mfgrid.angrot != 0.0\n or self.mfgrid.xoffset != 0.0\n or self.mfgrid.yoffset != 0.0\n ):\n v_realworld = []\n if intersect.geom_type.startswith(\"Multi\"):\n for ipoly in intersect:\n v_realworld += (\n self._transform_geo_interface_polygon(\n ipoly\n )\n )\n else:\n v_realworld += (\n self._transform_geo_interface_polygon(\n intersect\n )\n )\n intersect_realworld = affinity_loc.rotate(\n intersect, self.mfgrid.angrot, origin=(0.0, 0.0)\n )\n intersect_realworld = affinity_loc.translate(\n intersect_realworld,\n self.mfgrid.xoffset,\n self.mfgrid.yoffset,\n )\n else:\n v_realworld = intersect.__geo_interface__[\n \"coordinates\"\n ]\n intersect_realworld = intersect\n ixshapes.append(intersect_realworld)\n vertices.append(v_realworld)\n\n rec = np.recarray(\n len(nodelist),\n names=[\"cellids\", \"vertices\", \"areas\", \"ixshapes\"],\n formats=[\"O\", \"O\", \"f8\", \"O\"],\n )\n rec.vertices = vertices\n rec.areas = areas\n rec.cellids = nodelist\n with ignore_shapely_warnings_for_object_array():\n rec.ixshapes = ixshapes\n\n return rec\n\n def _transform_geo_interface_polygon(self, polygon):\n \"\"\"Internal method, helper function to transform geometry\n __geo_interface__.\n\n Used for translating intersection result coordinates back into\n real-world coordinates.\n\n Parameters\n ----------\n polygon : shapely.geometry.Polygon\n polygon to transform coordinates for\n\n Returns\n -------\n geom_list : list\n list containing transformed coordinates in same structure as\n the original __geo_interface__.\n \"\"\"\n\n if polygon.geom_type.startswith(\"Multi\"):\n raise TypeError(\"Does not support Multi geometries!\")\n\n geom_list = []\n for coords in polygon.__geo_interface__[\"coordinates\"]:\n geoms = []\n try:\n # test depth of list/tuple\n _ = coords[0][0][0]\n if len(coords) == 2:\n shell, holes = coords\n else:\n raise ValueError(\"Cannot parse __geo_interface__\")\n except TypeError:\n shell = coords\n holes = None\n except Exception as e:\n raise e\n # transform shell coordinates\n shell_pts = []\n for pt in shell:\n rx, ry = transform(\n [pt[0]],\n [pt[1]],\n self.mfgrid.xoffset,\n self.mfgrid.yoffset,\n self.mfgrid.angrot_radians,\n inverse=False,\n )\n shell_pts.append((rx, ry))\n geoms.append(shell_pts)\n # transform holes coordinates if necessary\n if holes:\n holes_pts = []\n for pt in holes:\n rx, ry = transform(\n [pt[0]],\n [pt[1]],\n self.mfgrid.xoffset,\n self.mfgrid.yoffset,\n self.mfgrid.angrot_radians,\n inverse=False,\n )\n # append (shells, holes) to transformed coordinates list\n geom_list.append(tuple(geoms))\n return geom_list\n\n @staticmethod\n def plot_polygon(rec, ax=None, **kwargs):\n \"\"\"method to plot the polygon intersection results from the resulting\n numpy.recarray.\n\n Note: only works when recarray has 'intersects' column!\n\n Parameters\n ----------\n rec : numpy.recarray\n record array containing intersection results\n (the resulting shapes)\n ax : matplotlib.pyplot.axes, optional\n axes to plot onto, if not provided, creates a new figure\n **kwargs:\n passed to the plot function\n\n Returns\n -------\n ax: matplotlib.pyplot.axes\n returns the axes handle\n \"\"\"\n\n import matplotlib.pyplot as plt\n\n import_optional_dependency(\"descartes\")\n from descartes import PolygonPatch\n\n if ax is None:\n _, ax = plt.subplots()\n\n for i, ishp in enumerate(rec.ixshapes):\n if \"facecolor\" in kwargs:\n fc = kwargs.pop(\"facecolor\")\n else:\n fc = f\"C{i % 10}\"\n ppi = PolygonPatch(ishp, facecolor=fc, **kwargs)\n ax.add_patch(ppi)\n\n return ax\n\n @staticmethod\n def plot_linestring(rec, ax=None, cmap=None, **kwargs):\n \"\"\"method to plot the linestring intersection results from the\n resulting numpy.recarray.\n\n Note: only works when recarray has 'intersects' column!\n\n Parameters\n ----------\n rec : numpy.recarray\n record array containing intersection results\n (the resulting shapes)\n ax : matplotlib.pyplot.axes, optional\n axes to plot onto, if not provided, creates a new figure\n cmap : str\n matplotlib colormap\n **kwargs:\n passed to the plot function\n\n Returns\n -------\n ax: matplotlib.pyplot.axes\n returns the axes handle\n \"\"\"\n import matplotlib.pyplot as plt\n\n if ax is None:\n _, ax = plt.subplots()\n\n specified_color = True\n if \"c\" in kwargs:\n c = kwargs.pop(\"c\")\n elif \"color\" in kwargs:\n c = kwargs.pop(\"color\")\n else:\n specified_color = False\n\n if cmap is not None:\n colormap = plt.get_cmap(cmap)\n colors = colormap(np.linspace(0, 1, rec.shape[0]))\n\n for i, ishp in enumerate(rec.ixshapes):\n if not specified_color:\n if cmap is None:\n c = f\"C{i % 10}\"\n else:\n c = colors[i]\n if ishp.type == \"MultiLineString\":\n for part in ishp:\n ax.plot(part.xy[0], part.xy[1], ls=\"-\", c=c, **kwargs)\n else:\n ax.plot(ishp.xy[0], ishp.xy[1], ls=\"-\", c=c, **kwargs)\n\n return ax\n\n @staticmethod\n def plot_point(rec, ax=None, **kwargs):\n \"\"\"method to plot the point intersection results from the resulting\n numpy.recarray.\n\n Note: only works when recarray has 'intersects' column!\n\n Parameters\n ----------\n rec : numpy.recarray\n record array containing intersection results\n ax : matplotlib.pyplot.axes, optional\n axes to plot onto, if not provided, creates a new figure\n **kwargs:\n passed to the scatter function\n\n Returns\n -------\n ax: matplotlib.pyplot.axes\n returns the axes handle\n \"\"\"\n import matplotlib.pyplot as plt\n\n shapely_geo = import_optional_dependency(\"shapely.geometry\")\n\n if ax is None:\n _, ax = plt.subplots()\n\n x, y = [], []\n geo_coll = shapely_geo.GeometryCollection(list(rec.ixshapes))\n collection = parse_shapely_ix_result([], geo_coll, [\"Point\"])\n for c in collection:\n x.append(c.x)\n y.append(c.y)\n ax.scatter(x, y, **kwargs)\n\n return ax\n\n\nclass ModflowGridIndices:\n \"\"\"Collection of methods that can be used to find cell indices for a\n structured, but irregularly spaced MODFLOW grid.\"\"\"\n\n @staticmethod\n def find_position_in_array(arr, x):\n \"\"\"If arr has x positions for the left edge of a cell, then return the\n cell index containing x.\n\n Parameters\n ----------\n arr : A one dimensional array (such as Xe) that contains\n coordinates for the left cell edge.\n\n x : float\n The x position to find in arr.\n \"\"\"\n jpos = None\n\n if x == arr[-1]:\n return len(arr) - 2\n\n if x < min(arr[0], arr[-1]):\n return None\n\n if x > max(arr[0], arr[-1]):\n return None\n\n # go through each position\n for j in range(len(arr) - 1):\n xl = arr[j]\n xr = arr[j + 1]\n frac = (x - xl) / (xr - xl)\n if 0.0 <= frac <= 1.0:\n # if min(xl, xr) <= x < max(xl, xr):\n jpos = j\n return jpos\n\n return jpos\n\n @staticmethod\n def kij_from_nodenumber(nodenumber, nlay, nrow, ncol):\n \"\"\"Convert the modflow node number to a zero-based layer, row and\n column format. Return (k0, i0, j0).\n\n Parameters\n ----------\n nodenumber: int\n The cell nodenumber, ranging from 1 to number of\n nodes.\n nlay: int\n The number of layers.\n nrow: int\n The number of rows.\n ncol: int\n The number of columns.\n \"\"\"\n if nodenumber > nlay * nrow * ncol:\n raise Exception(\"Error in function kij_from_nodenumber...\")\n n = nodenumber - 1\n k = int(n / nrow / ncol)\n i = int((n - k * nrow * ncol) / ncol)\n j = n - k * nrow * ncol - i * ncol\n return (k, i, j)\n\n @staticmethod\n def nodenumber_from_kij(k, i, j, nrow, ncol):\n \"\"\"Calculate the nodenumber using the zero-based layer, row, and column\n values. The first node has a value of 1.\n\n Parameters\n ----------\n k : int\n The model layer number as a zero-based value.\n i : int\n The model row number as a zero-based value.\n j : int\n The model column number as a zero-based value.\n nrow : int\n The number of model rows.\n ncol : int\n The number of model columns.\n \"\"\"\n return k * nrow * ncol + i * ncol + j + 1\n\n @staticmethod\n def nn0_from_kij(k, i, j, nrow, ncol):\n \"\"\"Calculate the zero-based nodenumber using the zero-based layer, row,\n and column values. The first node has a value of 0.\n\n Parameters\n ----------\n k : int\n The model layer number as a zero-based value.\n i : int\n The model row number as a zero-based value.\n j : int\n The model column number as a zero-based value.\n nrow : int\n The number of model rows.\n ncol : int\n The number of model columns.\n \"\"\"\n return k * nrow * ncol + i * ncol + j\n\n @staticmethod\n def kij_from_nn0(n, nlay, nrow, ncol):\n \"\"\"Convert the node number to a zero-based layer, row and column\n format. Return (k0, i0, j0).\n\n Parameters\n ----------\n nodenumber : int\n The cell nodenumber, ranging from 0 to number of\n nodes - 1.\n nlay : int\n The number of layers.\n nrow : int\n The number of rows.\n ncol : int\n The number of columns.\n \"\"\"\n if n > nlay * nrow * ncol:\n raise Exception(\"Error in function kij_from_nodenumber...\")\n k = int(n / nrow / ncol)\n i = int((n - k * nrow * ncol) / ncol)\n j = n - k * nrow * ncol - i * ncol\n return (k, i, j)\n",
"\"\"\"\nmfwel module. Contains the ModflowWel class. Note that the user can access\nthe ModflowWel class as `flopy.modflow.ModflowWel`.\n\nAdditional information for this MODFLOW package can be found at the `Online\nMODFLOW Guide\n<http://water.usgs.gov/ogw/modflow/MODFLOW-2005-Guide/index.html?wel.htm>`_.\n\n\"\"\"\nimport numpy as np\nfrom ..utils import MfList\nfrom ..pakbase import Package\nfrom ..utils.recarray_utils import create_empty_recarray\nfrom ..utils.optionblock import OptionBlock\nimport warnings\n\n\nclass ModflowWel(Package):\n \"\"\"\n MODFLOW Well Package Class.\n\n Parameters\n ----------\n model : model object\n The model object (of type :class:`flopy.modflow.mf.Modflow`) to which\n this package will be added.\n ipakcb : int\n A flag that is used to determine if cell-by-cell budget data should be\n saved. If ipakcb is non-zero cell-by-cell budget data will be saved.\n (default is 0).\n stress_period_data : list of boundaries, or recarray of boundaries, or\n dictionary of boundaries\n Each well is defined through definition of\n layer (int), row (int), column (int), flux (float).\n The simplest form is a dictionary with a lists of boundaries for each\n stress period, where each list of boundaries itself is a list of\n boundaries. Indices of the dictionary are the numbers of the stress\n period. This gives the form of:\n\n stress_period_data =\n {0: [\n [lay, row, col, flux],\n [lay, row, col, flux],\n [lay, row, col, flux]\n ],\n 1: [\n [lay, row, col, flux],\n [lay, row, col, flux],\n [lay, row, col, flux]\n ], ...\n kper:\n [\n [lay, row, col, flux],\n [lay, row, col, flux],\n [lay, row, col, flux]\n ]\n }\n\n Note that if the number of lists is smaller than the number of stress\n periods, then the last list of wells will apply until the end of the\n simulation. Full details of all options to specify stress_period_data\n can be found in the flopy3 boundaries Notebook in the basic\n subdirectory of the examples directory\n dtype : custom datatype of stress_period_data.\n If None the default well datatype will be applied (default is None).\n extension : string\n Filename extension (default is 'wel')\n options : list of strings\n Package options (default is None).\n unitnumber : int\n File unit number (default is None).\n filenames : str or list of str\n Filenames to use for the package and the output files. If\n filenames=None the package name will be created using the model name\n and package extension and the cbc output name will be created using\n the model name and .cbc extension (for example, modflowtest.cbc),\n if ipakcbc is a number greater than zero. If a single string is passed\n the package will be set to the string and cbc output names will be\n created using the model name and .cbc extension, if ipakcbc is a\n number greater than zero. To define the names for all package files\n (input and output) the length of the list of strings should be 2.\n Default is None.\n add_package : bool\n Flag to add the initialised package object to the parent model object.\n Default is True.\n\n Attributes\n ----------\n mxactw : int\n Maximum number of wells for a stress period. This is calculated\n automatically by FloPy based on the information in\n stress_period_data.\n\n Methods\n -------\n\n See Also\n --------\n\n Notes\n -----\n Parameters are not supported in FloPy.\n\n Examples\n --------\n\n >>> import flopy\n >>> m = flopy.modflow.Modflow()\n >>> lrcq = {0:[[2, 3, 4, -100.]], 1:[[2, 3, 4, -100.]]}\n >>> wel = flopy.modflow.ModflowWel(m, stress_period_data=lrcq)\n\n \"\"\"\n\n _options = dict(\n [\n (\n \"specify\",\n {\n OptionBlock.dtype: np.bool_,\n OptionBlock.nested: True,\n OptionBlock.n_nested: 2,\n OptionBlock.vars: dict(\n [\n (\"phiramp\", OptionBlock.simple_float),\n (\n \"iunitramp\",\n dict(\n [\n (OptionBlock.dtype, int),\n (OptionBlock.nested, False),\n (OptionBlock.optional, True),\n ]\n ),\n ),\n ]\n ),\n },\n ),\n (\"tabfiles\", OptionBlock.simple_tabfile),\n ]\n )\n\n def __init__(\n self,\n model,\n ipakcb=None,\n stress_period_data=None,\n dtype=None,\n extension=\"wel\",\n options=None,\n binary=False,\n unitnumber=None,\n filenames=None,\n add_package=True,\n ):\n # set default unit number of one is not specified\n if unitnumber is None:\n unitnumber = ModflowWel._defaultunit()\n\n # set filenames\n filenames = self._prepare_filenames(filenames, 2)\n\n # update external file information with cbc output, if necessary\n if ipakcb is not None:\n model.add_output_file(\n ipakcb, fname=filenames[1], package=self._ftype()\n )\n else:\n ipakcb = 0\n\n # call base package constructor\n super().__init__(\n model,\n extension=extension,\n name=self._ftype(),\n unit_number=unitnumber,\n filenames=filenames[0],\n )\n\n self._generate_heading()\n self.url = \"wel.htm\"\n\n self.ipakcb = ipakcb\n self.np = 0\n\n if options is None:\n options = []\n self.specify = False\n self.phiramp = None\n self.iunitramp = None\n self.options = options\n if isinstance(options, OptionBlock):\n if not self.options.specify:\n self.specify = self.options.specify\n else:\n self.specify = True\n\n self.phiramp = self.options.phiramp\n self.iunitramp = self.options.iunitramp\n # this is to grab the aux variables...\n options = []\n\n else:\n for idx, opt in enumerate(options):\n if \"specify\" in opt:\n t = opt.strip().split()\n self.specify = True\n self.phiramp = float(t[1])\n self.iunitramp = int(t[2])\n self.options.pop(idx)\n break\n\n if dtype is not None:\n self.dtype = dtype\n else:\n self.dtype = self.get_default_dtype(\n structured=self.parent.structured\n )\n\n # determine if any aux variables in dtype\n dt = self.get_default_dtype(structured=self.parent.structured)\n if len(self.dtype.names) > len(dt.names):\n for name in self.dtype.names[len(dt.names) :]:\n ladd = True\n for option in options:\n if name.lower() in option.lower():\n ladd = False\n break\n if ladd:\n options.append(f\"aux {name} \")\n\n if isinstance(self.options, OptionBlock):\n if not self.options.auxillary:\n self.options.auxillary = options\n else:\n self.options = options\n\n # initialize MfList\n self.stress_period_data = MfList(\n self, stress_period_data, binary=binary\n )\n\n if add_package:\n self.parent.add_package(self)\n\n def _ncells(self):\n \"\"\"Maximum number of cells that have wells (developed for\n MT3DMS SSM package).\n\n Returns\n -------\n ncells: int\n maximum number of wel cells\n\n \"\"\"\n return self.stress_period_data.mxact\n\n def write_file(self, f=None):\n \"\"\"\n Write the package file.\n\n Parameters:\n f: (str) optional file name\n\n Returns\n -------\n None\n\n \"\"\"\n if f is not None:\n if isinstance(f, str):\n f_wel = open(f, \"w\")\n else:\n f_wel = f\n else:\n f_wel = open(self.fn_path, \"w\")\n\n f_wel.write(f\"{self.heading}\\n\")\n\n if (\n isinstance(self.options, OptionBlock)\n and self.parent.version == \"mfnwt\"\n ):\n\n self.options.update_from_package(self)\n if self.options.block:\n self.options.write_options(f_wel)\n\n line = f\" {self.stress_period_data.mxact:9d} {self.ipakcb:9d} \"\n\n if isinstance(self.options, OptionBlock):\n if self.options.noprint:\n line += \"NOPRINT \"\n if self.options.auxillary:\n line += \" \".join(\n [str(aux).upper() for aux in self.options.auxillary]\n )\n\n else:\n for opt in self.options:\n line += \" \" + str(opt)\n\n line += \"\\n\"\n f_wel.write(line)\n\n if (\n isinstance(self.options, OptionBlock)\n and self.parent.version == \"mfnwt\"\n ):\n if not self.options.block:\n if isinstance(self.options.specify, np.ndarray):\n self.options.tabfiles = False\n self.options.write_options(f_wel)\n\n else:\n if self.specify and self.parent.version == \"mfnwt\":\n f_wel.write(\n f\"SPECIFY {self.phiramp:10.5g} {self.iunitramp:10d}\\n\"\n )\n\n self.stress_period_data.write_transient(f_wel)\n f_wel.close()\n\n def add_record(self, kper, index, values):\n try:\n self.stress_period_data.add_record(kper, index, values)\n except Exception as e:\n raise Exception(f\"mfwel error adding record to list: {e!s}\")\n\n @staticmethod\n def get_default_dtype(structured=True):\n if structured:\n dtype = np.dtype(\n [\n (\"k\", int),\n (\"i\", int),\n (\"j\", int),\n (\"flux\", np.float32),\n ]\n )\n else:\n dtype = np.dtype([(\"node\", int), (\"flux\", np.float32)])\n return dtype\n\n @staticmethod\n def get_empty(ncells=0, aux_names=None, structured=True):\n # get an empty recarray that corresponds to dtype\n dtype = ModflowWel.get_default_dtype(structured=structured)\n if aux_names is not None:\n dtype = Package.add_to_dtype(dtype, aux_names, np.float32)\n return create_empty_recarray(ncells, dtype, default_value=-1.0e10)\n\n @staticmethod\n def _get_sfac_columns():\n return [\"flux\"]\n\n @classmethod\n def load(cls, f, model, nper=None, ext_unit_dict=None, check=True):\n \"\"\"\n Load an existing package.\n\n Parameters\n ----------\n f : filename or file handle\n File to load.\n model : model object\n The model object (of type :class:`flopy.modflow.mf.Modflow`) to\n which this package will be added.\n nper : int\n The number of stress periods. If nper is None, then nper will be\n obtained from the model object. (default is None).\n ext_unit_dict : dictionary, optional\n If the arrays in the file are specified using EXTERNAL,\n or older style array control records, then `f` should be a file\n handle. In this case ext_unit_dict is required, which can be\n constructed using the function\n :class:`flopy.utils.mfreadnam.parsenamefile`.\n\n Returns\n -------\n wel : ModflowWel object\n ModflowWel object.\n\n Examples\n --------\n\n >>> import flopy\n >>> m = flopy.modflow.Modflow()\n >>> wel = flopy.modflow.ModflowWel.load('test.wel', m)\n\n \"\"\"\n\n if model.verbose:\n print(\"loading wel package file...\")\n\n return Package.load(\n f,\n model,\n cls,\n nper=nper,\n check=check,\n ext_unit_dict=ext_unit_dict,\n )\n\n @staticmethod\n def _ftype():\n return \"WEL\"\n\n @staticmethod\n def _defaultunit():\n return 20\n",
"\"\"\"\nThis is a set of classes for reading budget information out of MODFLOW-style\nlisting files. Cumulative and incremental budgets are returned as numpy\nrecarrays, which can then be easily plotted.\n\n\"\"\"\n\nimport os\nimport re\nimport numpy as np\nimport errno\n\nfrom ..utils.utils_def import totim_to_datetime\nfrom ..utils.flopy_io import get_ts_sp\nfrom ..utils import import_optional_dependency\n\n\nclass ListBudget:\n \"\"\"\n MODFLOW family list file handling\n\n Parameters\n ----------\n file_name : str\n the list file name\n budgetkey : str\n the text string identifying the budget table. (default is None)\n timeunit : str\n the time unit to return in the recarray. (default is 'days')\n\n Notes\n -----\n The ListBudget class should not be instantiated directly. Access is\n through derived classes: MfListBudget (MODFLOW), SwtListBudget (SEAWAT)\n and SwrListBudget (MODFLOW with the SWR process)\n\n Examples\n --------\n >>> mf_list = MfListBudget(\"my_model.list\")\n >>> incremental, cumulative = mf_list.get_budget()\n >>> df_in, df_out = mf_list.get_dataframes(start_datetime=\"10-21-2015\")\n\n \"\"\"\n\n def __init__(self, file_name, budgetkey=None, timeunit=\"days\"):\n\n # Set up file reading\n assert os.path.exists(file_name), f\"file_name {file_name} not found\"\n self.file_name = file_name\n self.f = open(file_name, \"r\", encoding=\"ascii\", errors=\"replace\")\n\n self.tssp_lines = 0\n\n # Assign the budgetkey, which should have been overridden\n if budgetkey is None:\n self.set_budget_key()\n else:\n self.budgetkey = budgetkey\n\n self.totim = []\n self.timeunit = timeunit\n self.idx_map = []\n self.entries = []\n self.null_entries = []\n\n self.time_line_idx = 20\n if timeunit.upper() == \"SECONDS\":\n self.timeunit = \"S\"\n self.time_idx = 0\n elif timeunit.upper() == \"MINUTES\":\n self.timeunit = \"M\"\n self.time_idx = 1\n elif timeunit.upper() == \"HOURS\":\n self.timeunit = \"H\"\n self.time_idx = 2\n elif timeunit.upper() == \"DAYS\":\n self.timeunit = \"D\"\n self.time_idx = 3\n elif timeunit.upper() == \"YEARS\":\n self.timeunit = \"Y\"\n self.time_idx = 4\n else:\n raise Exception(\n \"need to reset time_idxs attribute to \"\n \"use units other than days and check usage of \"\n \"timedelta\"\n )\n\n # Fill budget recarrays\n self._load()\n self._isvalid = False\n if len(self.idx_map) > 0:\n self._isvalid = True\n\n # Close the open file\n self.f.close()\n\n # return\n return\n\n def set_budget_key(self):\n raise Exception(\"Must be overridden...\")\n\n def isvalid(self):\n \"\"\"\n Get a boolean indicating if budget data are available in the file.\n\n Returns\n -------\n out : boolean\n Boolean indicating if budget data are available in the file.\n\n Examples\n --------\n >>> mf_list = MfListBudget('my_model.list')\n >>> valid = mf_list.isvalid()\n\n \"\"\"\n return self._isvalid\n\n def get_record_names(self):\n \"\"\"\n Get a list of water budget record names in the file.\n\n Returns\n -------\n out : list of strings\n List of unique text names in the binary file.\n\n Examples\n --------\n >>> mf_list = MfListBudget('my_model.list')\n >>> names = mf_list.get_record_names()\n\n \"\"\"\n if not self._isvalid:\n return None\n return self.inc.dtype.names\n\n def get_times(self):\n \"\"\"\n Get a list of unique water budget times in the list file.\n\n Returns\n -------\n out : list of floats\n List contains unique water budget simulation times (totim) in list\n file.\n\n Examples\n --------\n >>> mf_list = MfListBudget('my_model.list')\n >>> times = mf_list.get_times()\n\n \"\"\"\n if not self._isvalid:\n return None\n return self.inc[\"totim\"].tolist()\n\n def get_kstpkper(self):\n \"\"\"\n Get a list of unique stress periods and time steps in the list file\n water budgets.\n\n Returns\n ----------\n out : list of (kstp, kper) tuples\n List of unique kstp, kper combinations in list file. kstp and\n kper values are zero-based.\n\n Examples\n --------\n >>> mf_list = MfListBudget(\"my_model.list\")\n >>> kstpkper = mf_list.get_kstpkper()\n\n \"\"\"\n if not self._isvalid:\n return None\n kstpkper = []\n for kstp, kper in zip(\n self.inc[\"time_step\"], self.inc[\"stress_period\"]\n ):\n kstpkper.append((kstp, kper))\n return kstpkper\n\n def get_incremental(self, names=None):\n \"\"\"\n Get a recarray with the incremental water budget items in the list\n file.\n\n Parameters\n ----------\n names : str or list of strings\n Selection of column names to return. If names is not None then\n totim, time_step, stress_period, and selection(s) will be returned.\n (default is None).\n\n Returns\n -------\n out : recarray\n Numpy recarray with the water budget items in list file. The\n recarray also includes totim, time_step, and stress_period.\n\n Examples\n --------\n >>> mf_list = MfListBudget(\"my_model.list\")\n >>> incremental = mf_list.get_incremental()\n\n \"\"\"\n if not self._isvalid:\n return None\n if names is None:\n return self.inc\n else:\n if not isinstance(names, list):\n names = [names]\n names.insert(0, \"stress_period\")\n names.insert(0, \"time_step\")\n names.insert(0, \"totim\")\n return self.inc[names].view(np.recarray)\n\n def get_cumulative(self, names=None):\n \"\"\"\n Get a recarray with the cumulative water budget items in the list file.\n\n Parameters\n ----------\n names : str or list of strings\n Selection of column names to return. If names is not None then\n totim, time_step, stress_period, and selection(s) will be returned.\n (default is None).\n\n Returns\n -------\n out : recarray\n Numpy recarray with the water budget items in list file. The\n recarray also includes totim, time_step, and stress_period.\n\n Examples\n --------\n >>> mf_list = MfListBudget(\"my_model.list\")\n >>> cumulative = mf_list.get_cumulative()\n\n \"\"\"\n if not self._isvalid:\n return None\n if names is None:\n return self.cum\n else:\n if not isinstance(names, list):\n names = [names]\n names.insert(0, \"stress_period\")\n names.insert(0, \"time_step\")\n names.insert(0, \"totim\")\n return np.array(self.cum)[names].view(np.recarray)\n\n def get_model_runtime(self, units=\"seconds\"):\n \"\"\"\n Get the elapsed runtime of the model from the list file.\n\n Parameters\n ----------\n units : str\n Units in which to return the runtime. Acceptable values are\n 'seconds', 'minutes', 'hours' (default is 'seconds')\n\n Returns\n -------\n out : float\n Floating point value with the runtime in requested units. Returns\n NaN if runtime not found in list file\n\n Examples\n --------\n >>> mf_list = MfListBudget(\"my_model.list\")\n >>> budget = mf_list.get_model_runtime(units='hours')\n \"\"\"\n if not self._isvalid:\n return None\n\n # reopen the file\n self.f = open(self.file_name, \"r\", encoding=\"ascii\", errors=\"replace\")\n units = units.lower()\n if (\n not units == \"seconds\"\n and not units == \"minutes\"\n and not units == \"hours\"\n ):\n err = (\n '\"units\" input variable must be \"minutes\", \"hours\", '\n 'or \"seconds\": {0} was specified'.format(units)\n )\n raise AssertionError(err)\n try:\n seekpoint = self._seek_to_string(\"Elapsed run time:\")\n except:\n print(\"Elapsed run time not included in list file. Returning NaN\")\n return np.nan\n\n self.f.seek(seekpoint)\n line = self.f.readline()\n\n self.f.close()\n # yank out the floating point values from the Elapsed run time string\n times = list(map(float, re.findall(r\"[+-]?[0-9.]+\", line)))\n # pad an array with zeros and times with\n # [days, hours, minutes, seconds]\n times = np.array([0 for _ in range(4 - len(times))] + times)\n # convert all to seconds\n time2sec = np.array([24 * 60 * 60, 60 * 60, 60, 1])\n times_sec = np.sum(times * time2sec)\n # return in the requested units\n if units == \"seconds\":\n return times_sec\n elif units == \"minutes\":\n return times_sec / 60.0\n elif units == \"hours\":\n return times_sec / 60.0 / 60.0\n\n def get_budget(self, names=None):\n \"\"\"\n Get the recarrays with the incremental and cumulative water budget\n items in the list file.\n\n Parameters\n ----------\n names : str or list of strings\n Selection of column names to return. If names is not None then\n totim, time_step, stress_period, and selection(s) will be returned.\n (default is None).\n\n Returns\n -------\n out : recarrays\n Numpy recarrays with the water budget items in list file. The\n recarray also includes totim, time_step, and stress_period. A\n separate recarray is returned for the incremental and cumulative\n water budget entries.\n\n Examples\n --------\n >>> mf_list = MfListBudget(\"my_model.list\")\n >>> budget = mf_list.get_budget()\n\n \"\"\"\n if not self._isvalid:\n return None\n if names is None:\n return self.inc, self.cum\n else:\n if not isinstance(names, list):\n names = [names]\n names.insert(0, \"stress_period\")\n names.insert(0, \"time_step\")\n names.insert(0, \"totim\")\n return (\n self.inc[names].view(np.recarray),\n self.cum[names].view(np.recarray),\n )\n\n def get_data(self, kstpkper=None, idx=None, totim=None, incremental=False):\n \"\"\"\n Get water budget data from the list file for the specified conditions.\n\n Parameters\n ----------\n idx : int\n The zero-based record number. The first record is record 0.\n (default is None).\n kstpkper : tuple of ints\n A tuple containing the time step and stress period (kstp, kper).\n These are zero-based kstp and kper values. (default is None).\n totim : float\n The simulation time. (default is None).\n incremental : bool\n Boolean flag used to determine if incremental or cumulative water\n budget data for the specified conditions will be returned. If\n incremental=True, incremental water budget data will be returned.\n If incremental=False, cumulative water budget data will be\n returned. (default is False).\n\n Returns\n -------\n data : numpy recarray\n Array has size (number of budget items, 3). Recarray names are\n 'index', 'value', 'name'.\n\n See Also\n --------\n\n Notes\n -----\n if both kstpkper and totim are None, will return the last entry\n\n Examples\n --------\n >>> import matplotlib.pyplot as plt\n >>> import flopy\n >>> mf_list = flopy.utils.MfListBudget(\"my_model.list\")\n >>> data = mf_list.get_data(kstpkper=(0,0))\n >>> plt.bar(data['index'], data['value'])\n >>> plt.xticks(data['index'], data['name'], rotation=45, size=6)\n >>> plt.show()\n\n \"\"\"\n if not self._isvalid:\n return None\n ipos = None\n if kstpkper is not None:\n try:\n ipos = self.get_kstpkper().index(kstpkper)\n except:\n print(\n f\" could not retrieve kstpkper {kstpkper} from the lst file\"\n )\n elif totim is not None:\n try:\n ipos = self.get_times().index(totim)\n except:\n print(\n f\" could not retrieve totime {totim} from the lst file\"\n )\n elif idx is not None:\n ipos = idx\n else:\n ipos = -1\n\n if ipos is None:\n print(\"Could not find specified condition.\")\n print(f\" kstpkper = {kstpkper}\")\n print(f\" totim = {totim}\")\n # TODO: return zero-length array, or update docstring return type\n return None\n\n if incremental:\n t = self.inc[ipos]\n else:\n t = self.cum[ipos]\n\n dtype = np.dtype(\n [(\"index\", np.int32), (\"value\", np.float32), (\"name\", \"|S25\")]\n )\n v = np.recarray(shape=(len(self.inc.dtype.names[3:])), dtype=dtype)\n for i, name in enumerate(self.inc.dtype.names[3:]):\n mult = 1.0\n if \"_OUT\" in name:\n mult = -1.0\n v[i][\"index\"] = i\n v[i][\"value\"] = mult * t[name]\n v[i][\"name\"] = name\n return v\n\n def get_dataframes(self, start_datetime=\"1-1-1970\", diff=False):\n \"\"\"\n Get pandas dataframes with the incremental and cumulative water budget\n items in the list file.\n\n Parameters\n ----------\n start_datetime : str\n If start_datetime is passed as None, the rows are indexed on totim.\n Otherwise, a DatetimeIndex is set. (default is 1-1-1970).\n\n Returns\n -------\n out : pandas dataframes\n Pandas dataframes with the incremental and cumulative water budget\n items in list file. A separate pandas dataframe is returned for the\n incremental and cumulative water budget entries.\n\n Examples\n --------\n >>> mf_list = MfListBudget(\"my_model.list\")\n >>> incrementaldf, cumulativedf = mf_list.get_dataframes()\n\n \"\"\"\n\n pd = import_optional_dependency(\n \"pandas\",\n error_message=\"ListBudget.get_dataframes() requires pandas.\",\n )\n\n if not self._isvalid:\n return None\n totim = self.get_times()\n if start_datetime is not None:\n totim = totim_to_datetime(\n totim,\n start=pd.to_datetime(start_datetime),\n timeunit=self.timeunit,\n )\n\n df_flux = pd.DataFrame(self.inc, index=totim).loc[:, self.entries]\n df_vol = pd.DataFrame(self.cum, index=totim).loc[:, self.entries]\n\n if not diff:\n return df_flux, df_vol\n\n else:\n in_names = [col for col in df_flux.columns if col.endswith(\"_IN\")]\n\n base_names = [name.replace(\"_IN\", \"\") for name in in_names]\n for name in base_names:\n in_name = f\"{name}_IN\"\n out_name = f\"{name}_OUT\"\n df_flux.loc[:, name.lower()] = (\n df_flux.loc[:, in_name] - df_flux.loc[:, out_name]\n )\n df_flux.pop(in_name)\n df_flux.pop(out_name)\n df_vol.loc[:, name.lower()] = (\n df_vol.loc[:, in_name] - df_vol.loc[:, out_name]\n )\n df_vol.pop(in_name)\n df_vol.pop(out_name)\n cols = list(df_flux.columns)\n cols = [col.lower() for col in cols]\n df_flux.columns = cols\n df_vol.columns = cols\n df_flux.sort_index(axis=1, inplace=True)\n df_vol.sort_index(axis=1, inplace=True)\n return df_flux, df_vol\n\n def get_reduced_pumping(self):\n \"\"\"\n Get numpy recarray of reduced pumping data from a list file.\n Reduced pumping data most have been written to the list file\n during the model run. Works with MfListBudget and MfusgListBudget.\n\n Returns\n -------\n numpy recarray\n A numpy recarray with the reduced pumping data from the list\n file.\n\n Example\n --------\n >>> objLST = MfListBudget(\"my_model.lst\")\n >>> raryReducedPpg = objLST.get_reduced_pumping()\n >>> dfReducedPpg = pd.DataFrame.from_records(raryReducedPpg)\n\n \"\"\"\n from ..utils.observationfile import get_reduced_pumping\n\n # Ensure list file exists\n if not os.path.isfile(self.f.name):\n raise FileNotFoundError(\n errno.ENOENT, os.strerror(errno.ENOENT), self.f.name\n )\n\n # Eval based on model list type\n if isinstance(self, MfListBudget):\n structured = True\n # Check if reduced pumping data was set to be written\n # to list file\n check_str = (\n \"WELLS WITH REDUCED PUMPING WILL BE REPORTED \"\n \"TO THE MAIN LISTING FILE\"\n )\n\n check_str_ag = \"AG WELLS WITH REDUCED PUMPING FOR STRESS PERIOD\"\n\n if (\n not open(self.f.name).read().find(check_str) > 0\n and not open(self.f.name).read().find(check_str_ag) > 0\n ):\n err = (\n \"Pumping reductions not written to list file. \"\n 'Try removing \"noprint\" keyword from well file.'\n \"External pumping reduction files can be read using: \"\n \"flopy.utils.observationfile.get_pumping_reduction(<file>)\"\n )\n raise AssertionError(err)\n\n elif isinstance(self, MfusgListBudget):\n structured = False\n # Check if reduced pumping data was written and if set to\n # be written to list file\n check_str = \"WELL REDUCTION INFO WILL BE WRITTEN TO UNIT:\"\n bool_list_unit = False\n pump_reduction_flag = False\n for line in open(self.f.name):\n # Assumes LST unit always first\n if \"UNIT\" in line and not bool_list_unit:\n list_unit = int(line.strip().split()[-1])\n bool_list_unit = True\n if check_str in line:\n pump_reduction_flag = True\n\n if int(line.strip().split()[-1]) != list_unit:\n raise AssertionError(\n \"Pumping reductions not written to list file. \"\n \"External pumping reduction files can be \"\n \"read using: flopy.utils.observationfile.\"\n \"get_pumping_reduction(<file>, structured=False)\"\n )\n\n if not pump_reduction_flag:\n raise AssertionError(\"Auto pumping reductions not active.\")\n\n else:\n raise NotImplementedError(\n \"get_reduced_pumping() is only implemented for the \"\n \"MfListBudget or MfusgListBudget classes. Please \"\n \"feel free to expand the functionality to other \"\n \"ListBudget classes.\"\n )\n\n return get_reduced_pumping(self.f.name, structured)\n\n def _build_index(self, maxentries):\n self.idx_map = self._get_index(maxentries)\n return\n\n def _get_index(self, maxentries):\n # --parse through the file looking for matches and parsing ts and sp\n idxs = []\n l_count = 1\n while True:\n seekpoint = self.f.tell()\n line = self.f.readline()\n if line == \"\":\n break\n if self.budgetkey in line:\n for _ in range(self.tssp_lines):\n line = self.f.readline()\n try:\n ts, sp = get_ts_sp(line)\n except:\n print(\n \"unable to cast ts,sp on line number\",\n l_count,\n \" line: \",\n line,\n )\n break\n # print('info found for timestep stress period',ts,sp)\n\n idxs.append([ts, sp, seekpoint])\n\n if maxentries and len(idxs) >= maxentries:\n break\n\n return idxs\n\n def _seek_to_string(self, s):\n \"\"\"\n Parameters\n ----------\n s : str\n Seek through the file to the next occurrence of s. Return the\n seek location when found.\n\n Returns\n -------\n seekpoint : int\n Next location of the string\n\n \"\"\"\n while True:\n seekpoint = self.f.tell()\n line = self.f.readline()\n if line == \"\":\n break\n if s in line:\n break\n return seekpoint\n\n def _set_entries(self):\n if len(self.idx_map) < 1:\n return None, None\n if len(self.entries) > 0:\n raise Exception(f\"entries already set:{self.entries}\")\n if not self.idx_map:\n raise Exception(\"must call build_index before call set_entries\")\n try:\n incdict, cumdict = self._get_sp(\n self.idx_map[0][0], self.idx_map[0][1], self.idx_map[0][2]\n )\n except:\n raise Exception(\n \"unable to read budget information from first \"\n \"entry in list file\"\n )\n self.entries = incdict.keys()\n null_entries = {}\n incdict = {}\n cumdict = {}\n for entry in self.entries:\n incdict[entry] = []\n cumdict[entry] = []\n null_entries[entry] = np.NaN\n self.null_entries = [null_entries, null_entries]\n return incdict, cumdict\n\n def _load(self, maxentries=None):\n self._build_index(maxentries)\n incdict, cumdict = self._set_entries()\n if incdict is None and cumdict is None:\n return\n totim = []\n for ts, sp, seekpoint in self.idx_map:\n tinc, tcum = self._get_sp(ts, sp, seekpoint)\n for entry in self.entries:\n incdict[entry].append(tinc[entry])\n cumdict[entry].append(tcum[entry])\n\n # Get the time for this record\n seekpoint = self._seek_to_string(\"TIME SUMMARY AT END\")\n tslen, sptim, tt = self._get_totim(ts, sp, seekpoint)\n totim.append(tt)\n\n # get kstp and kper\n idx_array = np.array(self.idx_map)\n\n # build dtype for recarray\n dtype_tups = [\n (\"totim\", np.float32),\n (\"time_step\", np.int32),\n (\"stress_period\", np.int32),\n ]\n for entry in self.entries:\n dtype_tups.append((entry, np.float32))\n dtype = np.dtype(dtype_tups)\n\n # create recarray\n nentries = len(incdict[entry])\n self.inc = np.recarray(shape=(nentries,), dtype=dtype)\n self.cum = np.recarray(shape=(nentries,), dtype=dtype)\n\n # fill each column of the recarray\n for entry in self.entries:\n self.inc[entry] = incdict[entry]\n self.cum[entry] = cumdict[entry]\n\n # file the totim, time_step, and stress_period columns for the\n # incremental and cumulative recarrays (zero-based kstp,kper)\n self.inc[\"totim\"] = np.array(totim)[:]\n self.inc[\"time_step\"] = idx_array[:, 0] - 1\n self.inc[\"stress_period\"] = idx_array[:, 1] - 1\n\n self.cum[\"totim\"] = np.array(totim)[:]\n self.cum[\"time_step\"] = idx_array[:, 0] - 1\n self.cum[\"stress_period\"] = idx_array[:, 1] - 1\n\n return\n\n def _get_sp(self, ts, sp, seekpoint):\n self.f.seek(seekpoint)\n # --read to the start of the \"in\" budget information\n while True:\n line = self.f.readline()\n if line == \"\":\n print(\n \"end of file found while seeking budget \"\n \"information for ts,sp: {} {}\".format(ts, sp)\n )\n return self.null_entries\n\n # --if there are two '=' in this line, then it is a budget line\n if len(re.findall(\"=\", line)) == 2:\n break\n\n tag = \"IN\"\n incdict = {}\n cumdict = {}\n entrydict = {}\n while True:\n\n if line == \"\":\n print(\n \"end of file found while seeking budget \"\n \"information for ts,sp: {} {}\".format(ts, sp)\n )\n return self.null_entries\n if len(re.findall(\"=\", line)) == 2:\n try:\n entry, flux, cumu = self._parse_budget_line(line)\n except Exception:\n print(\"error parsing budget line in ts,sp\", ts, sp)\n return self.null_entries\n if flux is None:\n print(\n \"error casting in flux for\",\n entry,\n \" to float in ts,sp\",\n ts,\n sp,\n )\n return self.null_entries\n if cumu is None:\n print(\n \"error casting in cumu for\",\n entry,\n \" to float in ts,sp\",\n ts,\n sp,\n )\n return self.null_entries\n if entry.endswith(tag.upper()):\n if \" - \" in entry.upper():\n key = entry.replace(\" \", \"\")\n else:\n key = entry.replace(\" \", \"_\")\n elif \"PERCENT DISCREPANCY\" in entry.upper():\n key = entry.replace(\" \", \"_\")\n else:\n entry = entry.replace(\" \", \"_\")\n if entry in entrydict:\n entrydict[entry] += 1\n inum = entrydict[entry]\n entry = f\"{entry}{inum + 1}\"\n else:\n entrydict[entry] = 0\n key = f\"{entry}_{tag}\"\n incdict[key] = flux\n cumdict[key] = cumu\n else:\n if \"OUT:\" in line.upper():\n tag = \"OUT\"\n entrydict = {}\n line = self.f.readline()\n if entry.upper() == \"PERCENT DISCREPANCY\":\n break\n\n return incdict, cumdict\n\n def _parse_budget_line(self, line):\n\n # get the budget item name\n entry = line.strip().split(\"=\")[0].strip()\n\n # get the cumulative string\n idx = line.index(\"=\") + 1\n line2 = line[idx:]\n ll = line2.strip().split()\n cu_str = ll[0]\n\n idx = line2.index(\"=\") + 1\n fx_str = line2[idx:].split()[0].strip()\n\n flux, cumu = None, None\n try:\n cumu = float(cu_str)\n except:\n if \"NAN\" in cu_str.strip().upper():\n cumu = np.NaN\n try:\n flux = float(fx_str)\n except:\n if \"NAN\" in fx_str.strip().upper():\n flux = np.NaN\n return entry, flux, cumu\n\n def _get_totim(self, ts, sp, seekpoint):\n self.f.seek(seekpoint)\n # --read header lines\n ihead = 0\n while True:\n line = self.f.readline()\n ihead += 1\n if line == \"\":\n print(\n \"end of file found while seeking budget \"\n \"information for ts,sp: {} {}\".format(ts, sp)\n )\n return np.NaN, np.NaN, np.NaN\n elif (\n ihead == 2\n and \"SECONDS MINUTES HOURS DAYS YEARS\"\n not in line\n ):\n break\n elif (\n \"-----------------------------------------------------------\"\n in line\n ):\n line = self.f.readline()\n break\n\n if isinstance(self, SwtListBudget):\n translen = self._parse_time_line(line)\n line = self.f.readline()\n if translen is None:\n print(\"error parsing translen for ts,sp\", ts, sp)\n return np.NaN, np.NaN, np.NaN\n\n tslen = self._parse_time_line(line)\n if tslen is None:\n print(\"error parsing tslen for ts,sp\", ts, sp)\n return np.NaN, np.NaN, np.NaN\n\n sptim = self._parse_time_line(self.f.readline())\n if sptim is None:\n print(\"error parsing sptim for ts,sp\", ts, sp)\n return np.NaN, np.NaN, np.NaN\n\n totim = self._parse_time_line(self.f.readline())\n if totim is None:\n print(\"error parsing totim for ts,sp\", ts, sp)\n return np.NaN, np.NaN, np.NaN\n return tslen, sptim, totim\n\n def _parse_time_line(self, line):\n if line == \"\":\n print(\"end of file found while parsing time information\")\n return None\n try:\n time_str = line[self.time_line_idx :]\n raw = time_str.split()\n idx = self.time_idx\n # catch case where itmuni is undefined\n # in this case, the table format is different\n try:\n v = float(raw[0])\n except:\n time_str = line[45:]\n raw = time_str.split()\n idx = 0\n tval = float(raw[idx])\n except:\n print(\"error parsing tslen information: \", time_str)\n return None\n return tval\n\n\nclass SwtListBudget(ListBudget):\n \"\"\" \"\"\"\n\n def set_budget_key(self):\n self.budgetkey = \"MASS BUDGET FOR ENTIRE MODEL\"\n return\n\n\nclass MfListBudget(ListBudget):\n \"\"\" \"\"\"\n\n def set_budget_key(self):\n self.budgetkey = \"VOLUMETRIC BUDGET FOR ENTIRE MODEL\"\n return\n\n\nclass Mf6ListBudget(ListBudget):\n \"\"\" \"\"\"\n\n def set_budget_key(self):\n self.budgetkey = \"VOLUME BUDGET FOR ENTIRE MODEL\"\n return\n\n\nclass MfusgListBudget(ListBudget):\n \"\"\" \"\"\"\n\n def set_budget_key(self):\n self.budgetkey = \"VOLUMETRIC BUDGET FOR ENTIRE MODEL\"\n return\n\n\nclass SwrListBudget(ListBudget):\n \"\"\" \"\"\"\n\n def set_budget_key(self):\n self.budgetkey = \"VOLUMETRIC SURFACE WATER BUDGET FOR ENTIRE MODEL\"\n self.tssp_lines = 1\n return\n"
] |
[
[
"numpy.append"
],
[
"numpy.linspace",
"numpy.min",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.get_cmap",
"numpy.concatenate",
"numpy.max",
"numpy.array",
"numpy.recarray"
],
[
"numpy.dtype"
],
[
"numpy.array",
"numpy.sum",
"numpy.dtype",
"numpy.recarray"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
csutakbalazs/deepSI
|
[
"895030225937fb5fcbd4fc0eaba6c306ec0b5820",
"895030225937fb5fcbd4fc0eaba6c306ec0b5820"
] |
[
"deepSI/systems/narendra_li_benchmark.py",
"deepSI/systems/system.py"
] |
[
"import deepSI\nfrom deepSI.systems.system import System_ss, System_data\nimport numpy as np\n\nclass NarendraLiBenchmark(System_ss): #https://arxiv.org/pdf/2003.14162.pdf\n \"\"\"docstring for NarendraLiBenchmark\"\"\"\n def __init__(self):\n '''Noise, system setting and x0 settings'''\n super(NarendraLiBenchmark, self).__init__(nx=2)\n\n def f(self,x,u):\n x1,x2 = x\n x1new = (x1/(1+x1**2)+1)*np.sin(x2)\n x2new = x2*np.cos(x2) + x1*np.exp(-(x1**2+x2**2)/8) + u**3/(1+u**2+0.5*np.cos(x1+x2))\n return [x1new,x2new]\n\n def h(self,x):\n x1,x2 = x\n return x1/(1+0.5*np.sin(x2)) + x2/(1+0.5*np.sin(x1)) + self.random.normal(scale=0.1)\n\n def get_train_data(self):\n exp = System_data(u=self.random.uniform(low=-2.5,high=2.5,size=(2000,)))\n return self.apply_experiment(exp)\n\n def get_test_data(self):\n exp = System_data(u=self.random.uniform(low=-2.5,high=2.5,size=(2000,)))\n return self.apply_experiment(exp)\n\nif __name__ == '__main__':\n from deepSI import fit_systems\n sys = NarendraLiBenchmark()\n sys_data = sys.get_train_data()\n\n SYS = fit_systems.System_IO_fit_linear\n # sys_fit, score, kwargs = fit_systems.fit_system_tuner(SYS, sys_data, dict(na=range(0,7),nb=range(1,7)))\n score, sys_fit, kwargs, _ = fit_systems.grid_search(SYS, sys_data, dict(na=range(0,7),nb=range(1,7)))\n sys_data_predict = sys_fit.apply_experiment(sys_data)\n sys_data.plot()\n sys_data_predict.plot(show=True)\n",
"from deepSI.system_data import System_data, System_data_list, System_data_norm\nimport deepSI\nimport numpy as np\nimport pickle\nfrom secrets import token_urlsafe\nimport copy\nimport gym\nfrom gym.spaces import Box\n\ndef load_system(file):\n \"\"\"This is not a safe function, only use on trusted files\"\"\"\n try:\n return pickle.load(open(file,'rb'))\n except (pickle.UnpicklingError, EOFError): #maybe it was saved using torch systems\n import torch\n return torch.load(file)\n\n\nclass System(object):\n '''The base System class\n\n Attributes\n ----------\n action_space : gym.space or None\n the input shape of input u. (None is a single unbounded float)\n observation_space : gym.space or None\n The input shape of output y. (None is a single unbounded float)\n norm : instance of System_data_norm\n Used in most fittable systems to normalize the input output.\n fitted : Boole\n unique_code : str\n Some random unique 4 digit code (can be used for saving/loading)\n name : str\n concatenation of the the class name and the unique code\n use_norm : bool\n seed : int\n random seed\n random : np.random.RandomState\n unique random generated initialized with seed (only created ones called)\n '''\n def __init__(self, action_space=None, observation_space=None):\n '''Create a System\n\n Parameters\n ----------\n action_space : gym.space or None\n the input shape of input u. (None is a single unbounded float)\n observation_space : gym.space or None\n The input shape of output y. (None is a single unbounded float)\n '''\n self.action_space, self.observation_space = action_space, observation_space\n self.norm = System_data_norm()\n self.fitted = False\n self.unique_code = token_urlsafe(4).replace('_','0').replace('-','a') #random code\n self.seed = 42\n self.use_norm = True #can be changed later\n\n @property\n def name(self):\n return self.__class__.__name__ + '_' + self.unique_code\n @property\n def random(self): #gets created ones called, this is to make pickle more stable between different version of numpy\n if not hasattr(self,'_random'):\n self._random = np.random.RandomState(seed=self.seed)\n return self._random\n def get_state(self):\n '''state of the system (not the parameters)\n\n Returns\n -------\n state : the user defined state\n '''\n import warnings\n warnings.warn('Calling sys.state but no state has been set')\n return None\n\n def apply_experiment(self, sys_data, save_state=False): #can put this in apply controller\n '''Do a experiment with for given system data (fixed u)\n\n Parameters\n ----------\n sys_data : System_data or System_data_list (or list or tuple)\n The experiment which should be applied\n\n Notes\n -----\n This will initialize the state using self.init_state if sys_data.y (and u)\n is not None and skip the appropriate number of steps associated with it.\n If either is missing than self.reset() is used to initialize the state. \n Afterwards this state is advanced using sys_data.u and the output is saved at each step.\n Lastly, the number of skipped/copied steps in init_state is saved as sys_data.cheat_n such \n that it can be accounted for later.\n '''\n\n if isinstance(sys_data,(tuple,list,System_data_list)):\n return System_data_list([self.apply_experiment(sd) for sd in sys_data])\n Y = []\n sys_data_norm = self.norm.transform(sys_data)\n \n U = sys_data_norm.u\n if sys_data_norm.y is not None: #if y is not None than init state\n obs, k0 = self.init_state(sys_data_norm) #is reset if init_state is not defined #normed obs\n Y.extend(sys_data_norm.y[:k0]) #h(x_{k0-1})\n else:\n obs, k0 = self.reset(), 0\n if save_state:\n X = [self.get_state()]*(k0+1)\n\n for k in range(k0,len(U)):\n Y.append(obs) \n if k<len(U)-1: #skip last step\n action = U[k]\n obs = self.step(action)\n if save_state:\n X.append(self.get_state())\n return self.norm.inverse_transform(System_data(u=np.array(U),y=np.array(Y),x=np.array(X) if save_state else None,normed=True,cheat_n=k0)) \n \n def apply_controller(self,controller,N_samples):\n '''Same as self.apply_experiment but with a controller\n\n Parameters\n ----------\n controller : callable\n when called with the current output it return the next action/input that should be taken\n\n Notes\n -----\n This method is in a very early state and will probably be changed in the near future.\n '''\n Y = []\n U = []\n obs = self.reset() #normed obs\n for i in range(N_samples):\n Y.append(obs)\n action = (controller(obs*self.norm.ystd +self.norm.y0)-self.norm.u0)/self.norm.ustd #transform y and inverse transform resulting action\n U.append(action)\n obs = self.step(action)\n # Y = Y[:-1]\n return self.norm.inverse_transform(System_data(u=np.array(U),y=np.array(Y),normed=True))\n\n def init_state(self, sys_data):\n '''Initialize the internal state of the model using the start of sys_data\n\n Returns\n -------\n Output : an observation (e.g. floats)\n The observation/predicted state at time step k0\n k0 : int\n number of steps that should be skipped\n\n Notes\n -----\n Example: x0 = encoder(u[t-k0:k0],yhist[t-k0:k0]), and return h(x0), k0\n This function is often overwritten in child. As default it will return self.reset(), 0 \n '''\n return self.reset(), 0\n\n def init_state_multi(self, sys_data, nf=None, dilation=1):\n '''Similar to init_state but to initialize multiple states \n (used in self.n_step_error and self.one_step_ahead)\n\n Parameters\n ----------\n sys_data : System_data\n Data used to initialize the state\n nf : int\n skip the nf last states\n dilation: int\n number of states between each state\n '''\n raise NotImplementedError('init_state_multi should be implemented in subclass')\n\n def step(self, action):\n '''Applies the action to the system and returns the new observation, \n should always be overwritten in subclass'''\n raise NotImplementedError('one_step_ahead should be implemented in subclass')\n\n def step_multi(self,actions):\n '''Applies the actions to the system and returns the new observations'''\n return self.step(actions)\n\n def reset(self):\n '''Should reset the internal state and return the current obs'''\n raise NotImplementedError('one_step_ahead should be implemented in subclass')\n\n def one_step_ahead(self, sys_data):\n '''One step ahead prediction'''\n if isinstance(sys_data,(list,tuple,System_data_list)): #requires validation\n return System_data_list([self.apply_experiment(sd) for sd in sys_data])\n sys_data_norm = self.norm.transform(sys_data)\n obs, k0 = self.init_state_multi(sys_data_norm,nf=1)\n Y = np.concatenate([sys_data_norm.y[:k0],obs],axis=0)\n return self.norm.inverse_transform(System_data(u=np.array(sys_data_norm.u),y=np.array(Y),normed=True,cheat_n=k0)) \n # raise NotImplementedError('one_step_ahead is to be implemented')\n\n def n_step_error(self,sys_data,nf=100,dilation=1,RMS=False):\n '''Calculate the expected error after taking n=1...nf steps.\n\n Parameters\n ----------\n sys_data : System_data\n nf : int\n upper bound of n.\n dilation : int\n passed to init_state_multi to reduce memory cost.\n RMS : boole\n flag to toggle between NRMS and RMS\n '''\n if isinstance(sys_data,(list,tuple)):\n sys_data = System_data_list(sys_data)\n # [self.n_step_error(sd,return_weight=True) for sd in sys_data]\n sys_data = self.norm.transform(sys_data)\n obs, k0 = self.init_state_multi(sys_data, nf=nf, dilation=dilation)\n _, _, ufuture, yfuture = sys_data.to_hist_future_data(na=k0,nb=k0,nf=nf,dilation=dilation)\n\n Losses = []\n for unow, ynow in zip(np.swapaxes(ufuture,0,1), np.swapaxes(yfuture,0,1)):\n if RMS: #todo check this\n Losses.append(np.mean((ynow-obs)**2*self.norm.ystd**2)**0.5)\n else:\n Losses.append(np.mean((ynow-obs)**2)**0.5)\n obs = self.step_multi(unow)\n\n if isinstance(sys_data,System_data_list):\n self.init_state(sys_data[0]) #remove large state\n else:\n self.init_state(sys_data) #remove large state\n return np.array(Losses)\n\n def save_system(self,file):\n '''Save the system using pickle\n\n Notes\n -----\n This can be quite unstable for long term storage or switching between versions of this and other modules.\n Consider manually creating a save_system function for a long term solution.\n '''\n pickle.dump(self, open(file,'wb'))\n\n def __repr__(self):\n simple_action = (self.action_space is None) or (isinstance(self.action_space,gym.spaces.Box) and self.action_space.shape==tuple())\n simple_observation_space = (self.observation_space is None) or (isinstance(self.observation_space,gym.spaces.Box) and self.observation_space.shape==tuple())\n if simple_action and simple_observation_space:\n return f'System: {self.name}'\n else:\n return f'System: {self.name}, action_space={self.action_space}, observation_space={self.observation_space}'\n\n def sample_system(self,N_sampes=10**4):\n '''Mostly used for testing purposes it, will apply random actions on the system'''\n if self.action_space is None:\n exp = System_data(u=self.random.uniform(-2,2,size=N_sampes))\n else:\n s = copy.deepcopy(self.action_space)\n if isinstance(s,gym.spaces.Box):\n if np.isscalar(s.low):\n s.low[1 - np.isfinite(s.low)] = -2\n s.high[1 - np.isfinite(s.high)] = 2\n else:\n s.low = np.max([s.low, -2])\n s.high = np.min([s.high, 2])\n exp = System_data(u=[s.sample() for _ in range(N_sampes)])\n return self.apply_experiment(exp)\n\nclass Systems_gyms(System):\n \"\"\"docstring for Systems_gyms\"\"\"\n def __init__(self, env, env_kwargs=dict(), n=None):\n if isinstance(env,gym.Env):\n assert n==None, 'if env is already a gym environment than n cannot be given'\n self.env = env\n\n if n==None:\n self.env = gym.make(env,**env_kwargs)\n else:\n raise NotImplementedError('n requires implementation later')\n super(Systems_gyms, self).__init__(action_space=self.env.action_space, observation_space=self.env.observation_space)\n\n def reset(self):\n return self.env.reset()\n \n def step(self,action):\n '''Applies the action to the systems and returns the new observation'''\n obs, reward, done, info = self.env.step(action)\n self.done = done\n return obs\n\nclass System_ss(System): #simple state space systems\n '''Derived state-space system with continues u, x, y vectors or scalars'''\n def __init__(self, nx, nu=None, ny=None):\n action_shape = tuple() if nu is None else (nu,)\n observation_shape = tuple() if ny is None else (ny,)\n action_space = Box(-float('inf'),float('inf'),shape=action_shape)\n observation_space = Box(-float('inf'),float('inf'),shape=observation_shape)\n super(System_ss,self).__init__(action_space, observation_space)\n\n assert nx is not None\n self.nx = nx\n self.nu = nu\n self.ny = ny\n\n self.x = np.zeros((self.nx,) if isinstance(self.nx,int) else self.nx)\n\n def reset(self):\n self.x = np.zeros((self.nx,) if isinstance(self.nx,int) else self.nx)\n return self.h(self.x)\n\n def step(self,action):\n self.x = self.f(self.x,action)\n return self.h(self.x)\n # def step_multi(self,actions)\n\n def f(self,x,u):\n '''x[k+1] = f(x[k],u[k])'''\n raise NotImplementedError('f and h should be implemented in child')\n def h(self,x):\n '''y[k] = h(x[k])'''\n raise NotImplementedError('f and h should be implemented in child')\n\n def get_state(self):\n return self.x\n\n\nfrom scipy.integrate import solve_ivp\nclass System_deriv(System_ss):\n ''''''\n\n def __init__(self,dt=None,nx=None,nu=None,ny=None,method='RK4'):\n assert dt is not None\n self.dt = dt\n self.method = method\n super(System_deriv, self).__init__(nx, nu, ny)\n\n def f(self,x,u):\n #https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods\n #uses self.deriv and self.dt\n #RK4\n if self.method=='RK4': #this is a lot faster and quite accurate if dt is smaller than the shortest characteristic time-scale.\n x = np.array(x)\n k1 = self.dt*np.array(self.deriv(x,u))\n k2 = self.dt*np.array(self.deriv(x+k1/2,u))\n k3 = self.dt*np.array(self.deriv(x+k2/2,u))\n k4 = self.dt*np.array(self.deriv(x+k3,u))\n return x + (k1+2*k2+2*k3+k4)/6\n else:\n f = lambda t,x: self.deriv(x,u)\n sol = solve_ivp(f, [0, self.dt], x, method=self.method) #integration\n return sol.y[:,-1]\n\n def deriv(self,x,u):\n raise NotImplementedError('self.deriv should be implemented in child')\n\n\nclass System_io(System):\n def __init__(self,na, nb, nu=None, ny=None): #(u,y)\n action_shape = tuple() if nu is None else (nu,) #repeated code\n observation_shape = tuple() if ny is None else (ny,)\n action_space = Box(-float('inf'), float('inf'), shape=action_shape)\n observation_space = Box(-float('inf'), float('inf'), shape=observation_shape)\n super(System_io, self).__init__(action_space, observation_space)\n\n self.nb = nb #hist length of u\n self.na = na #hist length of y\n self.nu = nu\n self.ny = ny\n #y[k] = step(u[k-nb,k-1],y[k-na,...,k-1])\n #y[k+1] = step(u[k-nb+1,k],y[k-na-1,...,k])\n self.reset()\n\n def reset(self):\n self.yhist = [0]*self.na if self.ny is None else [[0]*self.ny for i in range(self.na)]\n self.uhist = [0]*(self.nb-1) if self.nu is None else [[0]*self.nu for i in range(self.nb-1)]\n return 0\n\n @property\n def k0(self):\n return max(self.na,self.nb)\n\n def init_state(self,sys_data):\n #sys_data already normed\n k0 = max(self.na,self.nb)\n self.yhist = list(sys_data.y[k0-self.na:k0])\n self.uhist = list(sys_data.u[k0-self.nb:k0-1]) #how it is saved, len(yhist) = na, len(uhist) = nb-1\n #when taking an action uhist gets appended to create the current state\n return sys_data.y[k0-1], k0\n\n def init_state_multi(self,sys_data,nf=100,dilation=1):\n k0 = max(self.na,self.nb)\n self.yhist = np.array([sys_data.y[k0-self.na+i:k0+i] for i in range(0,len(sys_data)-k0-nf+1,dilation)]) #+1? #shape = (N,na)\n self.uhist = np.array([sys_data.u[k0-self.nb+i:k0+i-1] for i in range(0,len(sys_data)-k0-nf+1,dilation)]) #+1? #shape = \n return self.yhist[:,-1], k0\n\n def step(self,action):\n self.uhist.append(action)\n uy = np.concatenate((np.array(self.uhist).flat,np.array(self.yhist).flat),axis=0) #might not be the quickest way\n yout = self.io_step(uy)\n self.yhist.append(yout)\n self.yhist.pop(0)\n self.uhist.pop(0)\n return yout\n\n def step_multi(self,actions):\n self.uhist = np.append(self.uhist,actions[:,None],axis=1)\n uy = np.concatenate([self.uhist.reshape(self.uhist.shape[0],-1),self.yhist.reshape(self.uhist.shape[0],-1)],axis=1) ######todo MIMO\n yout = self.multi_io_step(uy)\n self.yhist = np.append(self.yhist[:,1:],yout[:,None],axis=1)\n self.uhist = self.uhist[:,1:]\n return yout\n\n def io_step(self,uy):\n raise NotImplementedError('io_step should be implemented in child')\n\n def multi_io_step(self,uy):\n return self.io_step(uy)\n\n def get_state(self):\n return [copy.copy(self.uhist), copy.copy(self.yhist)]\n\nclass System_bj(System):\n #work in progress, use at own risk\n\n #yhat_{t} = f(u_{t-nb:t-1},yhat_{t-na:t-1},y_{t-nc:t-1})\n def __init__(self,na,nb,nc):\n #na = length of y hat\n #nb = length of u\n #nc = length of y real\n super(System_bj, self).__init__(None, None) #action_space=None, observation_space=None\n self.na = na\n self.nb = nb\n self.nc = nc\n\n @property\n def k0(self):\n return max(self.na,self.nb,self.nc)\n\n def reset(self):\n self.yhisthat = [0]*self.na if self.ny is None else [[0]*self.ny for i in range(self.na)]\n self.uhist = [0]*(self.nb-1) if self.nu is None else [[0]*self.nu for i in range(self.nb-1)]\n self.yhistreal = [0]*self.nb if self.ny is None else [[0]*self.ny for i in range(self.nb)]\n return 0\n\n def init_state(self,sys_data):\n #sys_data already normed\n k0 = max(self.na,self.nb,self.nc)\n self.yhisthat = list(sys_data.y[k0-self.na:k0])\n self.yhistreal = list(sys_data.y[k0-self.nc:k0-1])\n self.uhist = list(sys_data.u[k0-self.nb:k0-1]) #how it is saved, len(yhist) = na, len(uhist) = nb-1\n #when taking an action uhist gets appended to create the current state\n return self.yhistreal[-1], k0\n\n def init_state_multi(self,sys_data,nf=100):\n k0 = max(self.na,self.nb,self.nc)\n self.yhisthat = np.array([sys_data.y[k0-self.na+i:k0+i] for i in range(0,len(sys_data)-k0-nf+1)]) #+1? #shape = (N,na)\n self.yhistreal = np.array([sys_data.y[k0-self.nc+i:k0+i-1] for i in range(0,len(sys_data)-k0-nf+1)]) #+1? #shape = (N,nc)\n self.uhist = np.array([sys_data.u[k0-self.nb+i:k0+i-1] for i in range(0,len(sys_data)-k0-nf+1)]) #+1? #shape = \n return self.yhisthat[:,-1], k0\n\n def step(self,action): #normal step\n self.uhist.append(action)\n self.yhistreal.append(self.yhisthat[-1])\n\n uy = np.concatenate((np.array(self.uhist).flat,np.array(self.yhisthat).flat,np.array(self.yhistreal).flat),axis=0) #might not be the quickest way\n yout = self.BJ_step(uy)\n self.yhistreal.pop(0)\n self.yhisthat.pop(0)\n self.uhist.pop(0)\n\n self.yhisthat.append(yout)\n return yout\n\n def step_BJ(self,action,y): #normal step\n #y = the last output\n self.uhist.append(action) #append to [u[t-nb],...,u[t-1]]\n self.yhistreal.append(y) #append to [y[t-nc],...,y[t-1]]\n\n uy = np.concatenate((np.array(self.uhist).flat,np.array(self.yhisthat).flat,np.array(self.yhistreal).flat),axis=0) #might not be the quickest way\n yout = self.BJ_step(uy)\n self.yhisthat.append(yout)\n self.yhisthat.pop(0)\n self.yhistreal.pop(0) #[y[t-nc-1],...,y[t-1]]\n self.uhist.pop(0)\n return yout\n\n def step_multi(self,actions): #finish this function\n self.uhist = np.append(self.uhist,actions[:,None],axis=1)\n self.yhistreal = np.append(self.yhistreal,self.yhisthat[:,None],axis=1) #(N,nc)\n uy = np.concatenate([self.uhist,self.yhisthat,self.yhistreal],axis=1)\n yout = self.multi_BJ_step(uy)\n self.yhisthat = np.append(self.yhisthat[:,1:],yout[:,None],axis=1)\n self.uhist = self.uhist[:,1:]\n self.yhistreal = self.yhistreal[:,1:]\n return yout\n\n def step_BJ_multi(self,actions,ys): #normal step\n self.uhist = np.append(self.uhist,actions[:,None],axis=1)\n self.yhistreal = np.append(self.yhistreal,ys[:,None],axis=1) #(N,nc)\n uy = np.concatenate([self.uhist,self.yhisthat,self.yhistreal],axis=1)\n yout = self.multi_BJ_step(uy)\n self.yhisthat = np.append(self.yhisthat[:,1:],yout[:,None],axis=1)\n self.uhist = self.uhist[:,1:]\n self.yhistreal = self.yhistreal[:,1:]\n return yout\n\n def multi_BJ_step(self,uy):\n return self.BJ_step(uy)\n\n def apply_BJ_experiment(self,sys_data):\n if isinstance(sys_data,(tuple,list,System_data_list)):\n return System_data_list([self.apply_BJ_experiment(sd) for sd in sys_data])\n if sys_data.y==None:\n return self.apply_experiment(sys_data) #bail if y does not exist\n\n Yhat = []\n sys_data_norm = self.norm.transform(sys_data)\n U,Yreal = sys_data_norm.u,sys_data_norm.y\n obs, k0 = self.init_state(sys_data_norm) #is reset if init_state is not defined #normed obs\n Yhat.extend(sys_data_norm.y[:k0])\n\n for k in range(k0,len(U)):\n Yhat.append(obs)\n if k<len(U)-1: #skip last step\n obs = self.step_BJ(U[k],Yreal[k])\n return self.norm.inverse_transform(System_data(u=np.array(U),y=np.array(Yhat),normed=True,cheat_n=k0))\n #continue here\n # make apply_BJ_experiment\n # make make_fit_data or something\n # make loss\n\n\n\nif __name__ == '__main__':\n # sys = Systems_gyms('MountainCarContinuous-v0')\n pass\n # sys = Systems_gyms('LunarLander-v2')\n # print(sys.reset())\n # # exp = System_data(u=[[int(np.sin(2*np.pi*i/70)>0)*2-1] for i in range(500)]) #mountain car solve\n # print(sys)\n # exp = System_data(u=[sys.action_space.sample() for i in range(500)]) \n # print(exp.u.dtype)\n # sys_data =sys.apply_experiment(exp)\n # print(sys_data)\n # sys_data.plot(show=True)\n\n # sys = deepSI.systems.Nonlin_io_normals()\n # exp = System_data(u=np.random.normal(scale=2,size=100))\n # print(sys.step(1))\n # sys_data = sys.apply_experiment(exp)\n # # sys_data.plot(show=True)\n # sys = deepSI.systems.SS_test()\n # sys_data = sys.apply_experiment(exp)\n # sys_data.plot()\n\n # sys.save_system('../../testing/test.p')\n # del sys\n # sys = load_system('../../testing/test.p')\n\n # sys_data = sys.apply_experiment(exp)\n # sys_data.plot(show=True)\n\n #deriv testing\n # class barrier(System_deriv):\n # \"\"\"docstring for barrier\"\"\"\n # def __init__(self, method='RK4'):\n # super(barrier, self).__init__(nx=2,dt=0.1,method=method)\n \n # def deriv(self,x,u):\n # x,vx = x\n # dxdt = vx\n # alpha = 0.01\n # dvxdt = - 1e-3*vx + alpha*( - 1/(x-1)**2 + 1/(x+1)**2) + u\n # return [dxdt,dvxdt]\n\n # def h(self,x):\n # return x[0]\n\n # np.random.seed(32)\n # sys = barrier(method='RK45')\n # exp = deepSI.System_data(u=np.random.uniform(-1,1,size=500))\n # d = sys.apply_experiment(exp)\n # d.plot(show=True)\n"
] |
[
[
"numpy.exp",
"numpy.cos",
"numpy.sin"
],
[
"numpy.swapaxes",
"numpy.isfinite",
"torch.load",
"numpy.min",
"scipy.integrate.solve_ivp",
"numpy.concatenate",
"numpy.max",
"numpy.append",
"numpy.mean",
"numpy.isscalar",
"numpy.array",
"numpy.random.RandomState"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.6",
"1.10",
"1.4",
"1.9",
"1.5",
"1.2",
"1.7",
"1.0",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
lferraz/kornia
|
[
"c30ef6149bd92054d482339a2b0cd18f8272f5f5",
"c30ef6149bd92054d482339a2b0cd18f8272f5f5"
] |
[
"kornia/geometry/conversions.py",
"test/feature/test_hardnet.py"
] |
[
"from typing import Tuple\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom kornia.constants import pi\n\n__all__ = [\n # functional api\n \"rad2deg\",\n \"deg2rad\",\n \"pol2cart\",\n \"cart2pol\",\n \"convert_points_from_homogeneous\",\n \"convert_points_to_homogeneous\",\n \"convert_affinematrix_to_homography\",\n \"convert_affinematrix_to_homography3d\",\n \"angle_axis_to_rotation_matrix\",\n \"angle_axis_to_quaternion\",\n \"rotation_matrix_to_angle_axis\",\n \"rotation_matrix_to_quaternion\",\n \"quaternion_to_angle_axis\",\n \"quaternion_to_rotation_matrix\",\n \"quaternion_log_to_exp\",\n \"quaternion_exp_to_log\",\n \"denormalize_pixel_coordinates\",\n \"normalize_pixel_coordinates\",\n \"normalize_quaternion\",\n \"denormalize_pixel_coordinates3d\",\n \"normalize_pixel_coordinates3d\",\n]\n\n\ndef rad2deg(tensor: torch.Tensor) -> torch.Tensor:\n r\"\"\"Function that converts angles from radians to degrees.\n\n Args:\n tensor (torch.Tensor): Tensor of arbitrary shape.\n\n Returns:\n torch.Tensor: Tensor with same shape as input.\n\n Example:\n >>> input = torch.tensor(3.1415926535) * torch.rand(1, 3, 3)\n >>> output = rad2deg(input)\n \"\"\"\n if not isinstance(tensor, torch.Tensor):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(\n type(tensor)))\n\n return 180. * tensor / pi.to(tensor.device).type(tensor.dtype)\n\n\ndef deg2rad(tensor: torch.Tensor) -> torch.Tensor:\n r\"\"\"Function that converts angles from degrees to radians.\n\n Args:\n tensor (torch.Tensor): Tensor of arbitrary shape.\n\n Returns:\n torch.Tensor: tensor with same shape as input.\n\n Examples::\n\n >>> input = 360. * torch.rand(1, 3, 3)\n >>> output = deg2rad(input)\n \"\"\"\n if not isinstance(tensor, torch.Tensor):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(\n type(tensor)))\n\n return tensor * pi.to(tensor.device).type(tensor.dtype) / 180.\n\n\ndef pol2cart(rho: torch.Tensor, phi: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n r\"\"\"Function that converts polar coordinates to cartesian coordinates.\n\n Args:\n rho (torch.Tensor): Tensor of arbitrary shape.\n phi (torch.Tensor): Tensor of same arbitrary shape.\n\n Returns:\n torch.Tensor, torch.Tensor: Tensor with same shape as input.\n\n Example:\n >>> rho = torch.rand(1, 3, 3)\n >>> phi = torch.rand(1, 3, 3)\n >>> x, y = pol2cart(rho, phi)\n \"\"\"\n if not (isinstance(rho, torch.Tensor) & isinstance(phi, torch.Tensor)):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}, {}\".format(\n type(rho), type(phi)))\n\n x = rho * torch.cos(phi)\n y = rho * torch.sin(phi)\n return x, y\n\n\ndef cart2pol(x: torch.Tensor, y: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Function that converts cartesian coordinates to polar coordinates.\n\n Args:\n rho (torch.Tensor): Tensor of arbitrary shape.\n phi (torch.Tensor): Tensor of same arbitrary shape.\n eps (float): To avoid division by zero. Default is 1e-8\n\n Returns:\n torch.Tensor, torch.Tensor: Tensor with same shape as input.\n\n Example:\n >>> x = torch.rand(1, 3, 3)\n >>> y = torch.rand(1, 3, 3)\n >>> rho, phi = cart2pol(x, y)\n \"\"\"\n if not (isinstance(x, torch.Tensor) & isinstance(y, torch.Tensor)):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}, {}\".format(\n type(x), type(y)))\n\n rho = torch.sqrt(x**2 + y**2 + eps)\n phi = torch.atan2(y, x)\n return rho, phi\n\n\ndef convert_points_from_homogeneous(\n points: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:\n r\"\"\"Function that converts points from homogeneous to Euclidean space.\n\n Examples::\n\n >>> input = torch.rand(2, 4, 3) # BxNx3\n >>> output = convert_points_from_homogeneous(input) # BxNx2\n \"\"\"\n if not isinstance(points, torch.Tensor):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(\n type(points)))\n\n if len(points.shape) < 2:\n raise ValueError(\"Input must be at least a 2D tensor. Got {}\".format(\n points.shape))\n\n # we check for points at infinity\n z_vec: torch.Tensor = points[..., -1:]\n\n # set the results of division by zeror/near-zero to 1.0\n # follow the convention of opencv:\n # https://github.com/opencv/opencv/pull/14411/files\n mask: torch.Tensor = torch.abs(z_vec) > eps\n scale: torch.Tensor = torch.ones_like(z_vec).masked_scatter_(\n mask, torch.tensor(1.0).to(points.device) / z_vec[mask])\n\n return scale * points[..., :-1]\n\n\ndef convert_points_to_homogeneous(points: torch.Tensor) -> torch.Tensor:\n r\"\"\"Function that converts points from Euclidean to homogeneous space.\n\n Examples::\n\n >>> input = torch.rand(2, 4, 3) # BxNx3\n >>> output = convert_points_to_homogeneous(input) # BxNx4\n \"\"\"\n if not isinstance(points, torch.Tensor):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(\n type(points)))\n if len(points.shape) < 2:\n raise ValueError(\"Input must be at least a 2D tensor. Got {}\".format(\n points.shape))\n\n return torch.nn.functional.pad(points, [0, 1], \"constant\", 1.0)\n\n\ndef _convert_affinematrix_to_homography_impl(A: torch.Tensor) -> torch.Tensor:\n H: torch.Tensor = torch.nn.functional.pad(A, [0, 0, 0, 1], \"constant\", value=0.)\n H[..., -1, -1] += 1.0\n return H\n\n\ndef convert_affinematrix_to_homography(A: torch.Tensor) -> torch.Tensor:\n r\"\"\"Function that converts batch of affine matrices from [Bx2x3] to [Bx3x3].\n\n Examples::\n\n >>> input = torch.rand(2, 2, 3) # Bx2x3\n >>> output = convert_affinematrix_to_homography(input) # Bx3x3\n \"\"\"\n if not isinstance(A, torch.Tensor):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(\n type(A)))\n if not (len(A.shape) == 3 and A.shape[-2:] == (2, 3)):\n raise ValueError(\"Input matrix must be a Bx2x3 tensor. Got {}\"\n .format(A.shape))\n return _convert_affinematrix_to_homography_impl(A)\n\n\ndef convert_affinematrix_to_homography3d(A: torch.Tensor) -> torch.Tensor:\n r\"\"\"Function that converts batch of affine matrices from [Bx3x4] to [Bx4x4].\n\n Examples::\n\n >>> input = torch.rand(2, 3, 4) # Bx3x4\n >>> output = convert_affinematrix_to_homography3d(input) # Bx4x4\n \"\"\"\n if not isinstance(A, torch.Tensor):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(\n type(A)))\n if not (len(A.shape) == 3 and A.shape[-2:] == (3, 4)):\n raise ValueError(\"Input matrix must be a Bx3x4 tensor. Got {}\"\n .format(A.shape))\n return _convert_affinematrix_to_homography_impl(A)\n\n\ndef angle_axis_to_rotation_matrix(angle_axis: torch.Tensor) -> torch.Tensor:\n r\"\"\"Convert 3d vector of axis-angle rotation to 3x3 rotation matrix\n\n Args:\n angle_axis (torch.Tensor): tensor of 3d vector of axis-angle rotations.\n\n Returns:\n torch.Tensor: tensor of 3x3 rotation matrices.\n\n Shape:\n - Input: :math:`(N, 3)`\n - Output: :math:`(N, 3, 3)`\n\n Example:\n >>> input = torch.rand(1, 3) # Nx3\n >>> output = angle_axis_to_rotation_matrix(input) # Nx3x3\n \"\"\"\n if not isinstance(angle_axis, torch.Tensor):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(\n type(angle_axis)))\n\n if not angle_axis.shape[-1] == 3:\n raise ValueError(\n \"Input size must be a (*, 3) tensor. Got {}\".format(\n angle_axis.shape))\n\n def _compute_rotation_matrix(angle_axis, theta2, eps=1e-6):\n # We want to be careful to only evaluate the square root if the\n # norm of the angle_axis vector is greater than zero. Otherwise\n # we get a division by zero.\n k_one = 1.0\n theta = torch.sqrt(theta2)\n wxyz = angle_axis / (theta + eps)\n wx, wy, wz = torch.chunk(wxyz, 3, dim=1)\n cos_theta = torch.cos(theta)\n sin_theta = torch.sin(theta)\n\n r00 = cos_theta + wx * wx * (k_one - cos_theta)\n r10 = wz * sin_theta + wx * wy * (k_one - cos_theta)\n r20 = -wy * sin_theta + wx * wz * (k_one - cos_theta)\n r01 = wx * wy * (k_one - cos_theta) - wz * sin_theta\n r11 = cos_theta + wy * wy * (k_one - cos_theta)\n r21 = wx * sin_theta + wy * wz * (k_one - cos_theta)\n r02 = wy * sin_theta + wx * wz * (k_one - cos_theta)\n r12 = -wx * sin_theta + wy * wz * (k_one - cos_theta)\n r22 = cos_theta + wz * wz * (k_one - cos_theta)\n rotation_matrix = torch.cat(\n [r00, r01, r02, r10, r11, r12, r20, r21, r22], dim=1)\n return rotation_matrix.view(-1, 3, 3)\n\n def _compute_rotation_matrix_taylor(angle_axis):\n rx, ry, rz = torch.chunk(angle_axis, 3, dim=1)\n k_one = torch.ones_like(rx)\n rotation_matrix = torch.cat(\n [k_one, -rz, ry, rz, k_one, -rx, -ry, rx, k_one], dim=1)\n return rotation_matrix.view(-1, 3, 3)\n\n # stolen from ceres/rotation.h\n\n _angle_axis = torch.unsqueeze(angle_axis, dim=1)\n theta2 = torch.matmul(_angle_axis, _angle_axis.transpose(1, 2))\n theta2 = torch.squeeze(theta2, dim=1)\n\n # compute rotation matrices\n rotation_matrix_normal = _compute_rotation_matrix(angle_axis, theta2)\n rotation_matrix_taylor = _compute_rotation_matrix_taylor(angle_axis)\n\n # create mask to handle both cases\n eps = 1e-6\n mask = (theta2 > eps).view(-1, 1, 1).to(theta2.device)\n mask_pos = (mask).type_as(theta2)\n mask_neg = (mask == False).type_as(theta2) # noqa\n\n # create output pose matrix\n batch_size = angle_axis.shape[0]\n rotation_matrix = torch.eye(3).to(angle_axis.device).type_as(angle_axis)\n rotation_matrix = rotation_matrix.view(1, 3, 3).repeat(batch_size, 1, 1)\n # fill output matrix with masked values\n rotation_matrix[..., :3, :3] = \\\n mask_pos * rotation_matrix_normal + mask_neg * rotation_matrix_taylor\n return rotation_matrix # Nx3x3\n\n\ndef rotation_matrix_to_angle_axis(\n rotation_matrix: torch.Tensor) -> torch.Tensor:\n r\"\"\"Convert 3x3 rotation matrix to Rodrigues vector.\n\n Args:\n rotation_matrix (torch.Tensor): rotation matrix.\n\n Returns:\n torch.Tensor: Rodrigues vector transformation.\n\n Shape:\n - Input: :math:`(N, 3, 3)`\n - Output: :math:`(N, 3)`\n\n Example:\n >>> input = torch.rand(2, 3, 3) # Nx3x3\n >>> output = rotation_matrix_to_angle_axis(input) # Nx3\n \"\"\"\n if not isinstance(rotation_matrix, torch.Tensor):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(\n type(rotation_matrix)))\n\n if not rotation_matrix.shape[-2:] == (3, 3):\n raise ValueError(\n \"Input size must be a (*, 3, 3) tensor. Got {}\".format(\n rotation_matrix.shape))\n quaternion: torch.Tensor = rotation_matrix_to_quaternion(rotation_matrix)\n return quaternion_to_angle_axis(quaternion)\n\n\ndef rotation_matrix_to_quaternion(\n rotation_matrix: torch.Tensor,\n eps: float = 1e-8) -> torch.Tensor:\n r\"\"\"Convert 3x3 rotation matrix to 4d quaternion vector.\n The quaternion vector has components in (x, y, z, w) format.\n\n Args:\n rotation_matrix (torch.Tensor): the rotation matrix to convert.\n eps (float): small value to avoid zero division. Default: 1e-8.\n\n Return:\n torch.Tensor: the rotation in quaternion.\n\n Shape:\n - Input: :math:`(*, 3, 3)`\n - Output: :math:`(*, 4)`\n\n Example:\n >>> input = torch.rand(4, 3, 3) # Nx3x3\n >>> output = rotation_matrix_to_quaternion(input) # Nx4\n \"\"\"\n if not isinstance(rotation_matrix, torch.Tensor):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(\n type(rotation_matrix)))\n\n if not rotation_matrix.shape[-2:] == (3, 3):\n raise ValueError(\n \"Input size must be a (*, 3, 3) tensor. Got {}\".format(\n rotation_matrix.shape))\n\n def safe_zero_division(numerator: torch.Tensor,\n denominator: torch.Tensor) -> torch.Tensor:\n eps: float = torch.finfo(numerator.dtype).tiny # type: ignore\n return numerator / torch.clamp(denominator, min=eps)\n\n rotation_matrix_vec: torch.Tensor = rotation_matrix.view(\n *rotation_matrix.shape[:-2], 9)\n\n m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.chunk(\n rotation_matrix_vec, chunks=9, dim=-1)\n\n trace: torch.Tensor = m00 + m11 + m22\n\n def trace_positive_cond():\n sq = torch.sqrt(trace + 1.0) * 2. # sq = 4 * qw.\n qw = 0.25 * sq\n qx = safe_zero_division(m21 - m12, sq)\n qy = safe_zero_division(m02 - m20, sq)\n qz = safe_zero_division(m10 - m01, sq)\n return torch.cat([qx, qy, qz, qw], dim=-1)\n\n def cond_1():\n sq = torch.sqrt(1.0 + m00 - m11 - m22 + eps) * 2. # sq = 4 * qx.\n qw = safe_zero_division(m21 - m12, sq)\n qx = 0.25 * sq\n qy = safe_zero_division(m01 + m10, sq)\n qz = safe_zero_division(m02 + m20, sq)\n return torch.cat([qx, qy, qz, qw], dim=-1)\n\n def cond_2():\n sq = torch.sqrt(1.0 + m11 - m00 - m22 + eps) * 2. # sq = 4 * qy.\n qw = safe_zero_division(m02 - m20, sq)\n qx = safe_zero_division(m01 + m10, sq)\n qy = 0.25 * sq\n qz = safe_zero_division(m12 + m21, sq)\n return torch.cat([qx, qy, qz, qw], dim=-1)\n\n def cond_3():\n sq = torch.sqrt(1.0 + m22 - m00 - m11 + eps) * 2. # sq = 4 * qz.\n qw = safe_zero_division(m10 - m01, sq)\n qx = safe_zero_division(m02 + m20, sq)\n qy = safe_zero_division(m12 + m21, sq)\n qz = 0.25 * sq\n return torch.cat([qx, qy, qz, qw], dim=-1)\n\n where_2 = torch.where(m11 > m22, cond_2(), cond_3())\n where_1 = torch.where(\n (m00 > m11) & (m00 > m22), cond_1(), where_2)\n\n quaternion: torch.Tensor = torch.where(\n trace > 0., trace_positive_cond(), where_1)\n return quaternion\n\n\ndef normalize_quaternion(quaternion: torch.Tensor,\n eps: float = 1e-12) -> torch.Tensor:\n r\"\"\"Normalizes a quaternion.\n The quaternion should be in (x, y, z, w) format.\n\n Args:\n quaternion (torch.Tensor): a tensor containing a quaternion to be\n normalized. The tensor can be of shape :math:`(*, 4)`.\n eps (Optional[bool]): small value to avoid division by zero.\n Default: 1e-12.\n\n Return:\n torch.Tensor: the normalized quaternion of shape :math:`(*, 4)`.\n\n Example:\n >>> quaternion = torch.tensor([1., 0., 1., 0.])\n >>> normalize_quaternion(quaternion)\n tensor([0.7071, 0.0000, 0.7071, 0.0000])\n \"\"\"\n if not isinstance(quaternion, torch.Tensor):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(\n type(quaternion)))\n\n if not quaternion.shape[-1] == 4:\n raise ValueError(\n \"Input must be a tensor of shape (*, 4). Got {}\".format(\n quaternion.shape))\n return F.normalize(quaternion, p=2, dim=-1, eps=eps)\n\n\n# based on:\n# https://github.com/matthew-brett/transforms3d/blob/8965c48401d9e8e66b6a8c37c65f2fc200a076fa/transforms3d/quaternions.py#L101\n# https://github.com/tensorflow/graphics/blob/master/tensorflow_graphics/geometry/transformation/rotation_matrix_3d.py#L247\n\ndef quaternion_to_rotation_matrix(quaternion: torch.Tensor) -> torch.Tensor:\n r\"\"\"Converts a quaternion to a rotation matrix.\n The quaternion should be in (x, y, z, w) format.\n\n Args:\n quaternion (torch.Tensor): a tensor containing a quaternion to be\n converted. The tensor can be of shape :math:`(*, 4)`.\n\n Return:\n torch.Tensor: the rotation matrix of shape :math:`(*, 3, 3)`.\n\n Example:\n >>> quaternion = torch.tensor([0., 0., 1., 0.])\n >>> quaternion_to_rotation_matrix(quaternion)\n tensor([[-1., 0., 0.],\n [ 0., -1., 0.],\n [ 0., 0., 1.]])\n \"\"\"\n if not isinstance(quaternion, torch.Tensor):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(\n type(quaternion)))\n\n if not quaternion.shape[-1] == 4:\n raise ValueError(\n \"Input must be a tensor of shape (*, 4). Got {}\".format(\n quaternion.shape))\n # normalize the input quaternion\n quaternion_norm: torch.Tensor = normalize_quaternion(quaternion)\n\n # unpack the normalized quaternion components\n x, y, z, w = torch.chunk(quaternion_norm, chunks=4, dim=-1)\n\n # compute the actual conversion\n tx: torch.Tensor = 2.0 * x\n ty: torch.Tensor = 2.0 * y\n tz: torch.Tensor = 2.0 * z\n twx: torch.Tensor = tx * w\n twy: torch.Tensor = ty * w\n twz: torch.Tensor = tz * w\n txx: torch.Tensor = tx * x\n txy: torch.Tensor = ty * x\n txz: torch.Tensor = tz * x\n tyy: torch.Tensor = ty * y\n tyz: torch.Tensor = tz * y\n tzz: torch.Tensor = tz * z\n one: torch.Tensor = torch.tensor(1.)\n\n matrix: torch.Tensor = torch.stack([\n one - (tyy + tzz), txy - twz, txz + twy,\n txy + twz, one - (txx + tzz), tyz - twx,\n txz - twy, tyz + twx, one - (txx + tyy)\n ], dim=-1).view(-1, 3, 3)\n\n if len(quaternion.shape) == 1:\n matrix = torch.squeeze(matrix, dim=0)\n return matrix\n\n\ndef quaternion_to_angle_axis(quaternion: torch.Tensor) -> torch.Tensor:\n \"\"\"Convert quaternion vector to angle axis of rotation.\n The quaternion should be in (x, y, z, w) format.\n\n Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.h\n\n Args:\n quaternion (torch.Tensor): tensor with quaternions.\n\n Return:\n torch.Tensor: tensor with angle axis of rotation.\n\n Shape:\n - Input: :math:`(*, 4)` where `*` means, any number of dimensions\n - Output: :math:`(*, 3)`\n\n Example:\n >>> quaternion = torch.rand(2, 4) # Nx4\n >>> angle_axis = quaternion_to_angle_axis(quaternion) # Nx3\n \"\"\"\n if not torch.is_tensor(quaternion):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(\n type(quaternion)))\n\n if not quaternion.shape[-1] == 4:\n raise ValueError(\n \"Input must be a tensor of shape Nx4 or 4. Got {}\".format(\n quaternion.shape))\n # unpack input and compute conversion\n q1: torch.Tensor = quaternion[..., 1]\n q2: torch.Tensor = quaternion[..., 2]\n q3: torch.Tensor = quaternion[..., 3]\n sin_squared_theta: torch.Tensor = q1 * q1 + q2 * q2 + q3 * q3\n\n sin_theta: torch.Tensor = torch.sqrt(sin_squared_theta)\n cos_theta: torch.Tensor = quaternion[..., 0]\n two_theta: torch.Tensor = 2.0 * torch.where(\n cos_theta < 0.0, torch.atan2(-sin_theta, -cos_theta),\n torch.atan2(sin_theta, cos_theta))\n\n k_pos: torch.Tensor = two_theta / sin_theta\n k_neg: torch.Tensor = 2.0 * torch.ones_like(sin_theta)\n k: torch.Tensor = torch.where(sin_squared_theta > 0.0, k_pos, k_neg)\n\n angle_axis: torch.Tensor = torch.zeros_like(quaternion)[..., :3]\n angle_axis[..., 0] += q1 * k\n angle_axis[..., 1] += q2 * k\n angle_axis[..., 2] += q3 * k\n return angle_axis\n\n\ndef quaternion_log_to_exp(quaternion: torch.Tensor,\n eps: float = 1e-8) -> torch.Tensor:\n r\"\"\"Applies exponential map to log quaternion.\n The quaternion should be in (x, y, z, w) format.\n\n Args:\n quaternion (torch.Tensor): a tensor containing a quaternion to be\n converted. The tensor can be of shape :math:`(*, 3)`.\n\n Return:\n torch.Tensor: the quaternion exponential map of shape :math:`(*, 4)`.\n\n Example:\n >>> quaternion = torch.tensor([0., 0., 0.])\n >>> quaternion_log_to_exp(quaternion)\n tensor([0., 0., 0., 1.])\n \"\"\"\n if not isinstance(quaternion, torch.Tensor):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(\n type(quaternion)))\n\n if not quaternion.shape[-1] == 3:\n raise ValueError(\n \"Input must be a tensor of shape (*, 3). Got {}\".format(\n quaternion.shape))\n # compute quaternion norm\n norm_q: torch.Tensor = torch.norm(\n quaternion, p=2, dim=-1, keepdim=True).clamp(min=eps)\n\n # compute scalar and vector\n quaternion_vector: torch.Tensor = quaternion * torch.sin(norm_q) / norm_q\n quaternion_scalar: torch.Tensor = torch.cos(norm_q)\n\n # compose quaternion and return\n quaternion_exp: torch.Tensor = torch.cat(\n [quaternion_vector, quaternion_scalar], dim=-1)\n return quaternion_exp\n\n\ndef quaternion_exp_to_log(quaternion: torch.Tensor,\n eps: float = 1e-8) -> torch.Tensor:\n r\"\"\"Applies the log map to a quaternion.\n The quaternion should be in (x, y, z, w) format.\n\n Args:\n quaternion (torch.Tensor): a tensor containing a quaternion to be\n converted. The tensor can be of shape :math:`(*, 4)`.\n\n Return:\n torch.Tensor: the quaternion log map of shape :math:`(*, 3)`.\n\n Example:\n >>> quaternion = torch.tensor([0., 0., 0., 1.])\n >>> quaternion_exp_to_log(quaternion)\n tensor([0., 0., 0.])\n \"\"\"\n if not isinstance(quaternion, torch.Tensor):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(\n type(quaternion)))\n\n if not quaternion.shape[-1] == 4:\n raise ValueError(\n \"Input must be a tensor of shape (*, 4). Got {}\".format(\n quaternion.shape))\n # unpack quaternion vector and scalar\n quaternion_vector: torch.Tensor = quaternion[..., 0:3]\n quaternion_scalar: torch.Tensor = quaternion[..., 3:4]\n\n # compute quaternion norm\n norm_q: torch.Tensor = torch.norm(\n quaternion_vector, p=2, dim=-1, keepdim=True).clamp(min=eps)\n\n # apply log map\n quaternion_log: torch.Tensor = quaternion_vector * torch.acos(\n torch.clamp(quaternion_scalar, min=-1.0, max=1.0)) / norm_q\n return quaternion_log\n\n\n# based on:\n# https://github.com/facebookresearch/QuaterNet/blob/master/common/quaternion.py#L138\n\n\ndef angle_axis_to_quaternion(angle_axis: torch.Tensor) -> torch.Tensor:\n r\"\"\"Convert an angle axis to a quaternion.\n The quaternion vector has components in (x, y, z, w) format.\n\n Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.h\n\n Args:\n angle_axis (torch.Tensor): tensor with angle axis.\n\n Return:\n torch.Tensor: tensor with quaternion.\n\n Shape:\n - Input: :math:`(*, 3)` where `*` means, any number of dimensions\n - Output: :math:`(*, 4)`\n\n Example:\n >>> angle_axis = torch.rand(2, 3) # Nx3\n >>> quaternion = angle_axis_to_quaternion(angle_axis) # Nx4\n \"\"\"\n if not torch.is_tensor(angle_axis):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(\n type(angle_axis)))\n\n if not angle_axis.shape[-1] == 3:\n raise ValueError(\n \"Input must be a tensor of shape Nx3 or 3. Got {}\".format(\n angle_axis.shape))\n # unpack input and compute conversion\n a0: torch.Tensor = angle_axis[..., 0:1]\n a1: torch.Tensor = angle_axis[..., 1:2]\n a2: torch.Tensor = angle_axis[..., 2:3]\n theta_squared: torch.Tensor = a0 * a0 + a1 * a1 + a2 * a2\n\n theta: torch.Tensor = torch.sqrt(theta_squared)\n half_theta: torch.Tensor = theta * 0.5\n\n mask: torch.Tensor = theta_squared > 0.0\n ones: torch.Tensor = torch.ones_like(half_theta)\n\n k_neg: torch.Tensor = 0.5 * ones\n k_pos: torch.Tensor = torch.sin(half_theta) / theta\n k: torch.Tensor = torch.where(mask, k_pos, k_neg)\n w: torch.Tensor = torch.where(mask, torch.cos(half_theta), ones)\n\n quaternion: torch.Tensor = torch.zeros_like(angle_axis)\n quaternion[..., 0:1] += a0 * k\n quaternion[..., 1:2] += a1 * k\n quaternion[..., 2:3] += a2 * k\n return torch.cat([w, quaternion], dim=-1)\n\n\n# based on:\n# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L65-L71\n\ndef normalize_pixel_coordinates(\n pixel_coordinates: torch.Tensor,\n height: int,\n width: int,\n eps: float = 1e-8) -> torch.Tensor:\n r\"\"\"Normalize pixel coordinates between -1 and 1.\n\n Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1).\n\n Args:\n pixel_coordinates (torch.Tensor): the grid with pixel coordinates.\n Shape can be :math:`(*, 2)`.\n width (int): the maximum width in the x-axis.\n height (int): the maximum height in the y-axis.\n eps (float): safe division by zero. (default 1e-8).\n\n Return:\n torch.Tensor: the normalized pixel coordinates.\n \"\"\"\n if pixel_coordinates.shape[-1] != 2:\n raise ValueError(\"Input pixel_coordinates must be of shape (*, 2). \"\n \"Got {}\".format(pixel_coordinates.shape))\n # compute normalization factor\n hw: torch.Tensor = torch.stack([\n torch.tensor(width, device=pixel_coordinates.device, dtype=pixel_coordinates.dtype),\n torch.tensor(height, device=pixel_coordinates.device, dtype=pixel_coordinates.dtype)\n ])\n\n factor: torch.Tensor = torch.tensor(\n 2., device=pixel_coordinates.device, dtype=pixel_coordinates.dtype) / (hw - 1).clamp(eps)\n\n return factor * pixel_coordinates - 1\n\n\ndef denormalize_pixel_coordinates(\n pixel_coordinates: torch.Tensor,\n height: int,\n width: int,\n eps: float = 1e-8) -> torch.Tensor:\n r\"\"\"Denormalize pixel coordinates.\n\n The input is assumed to be -1 if on extreme left, 1 if on\n extreme right (x = w-1).\n\n Args:\n pixel_coordinates (torch.Tensor): the normalized grid coordinates.\n Shape can be :math:`(*, 2)`.\n width (int): the maximum width in the x-axis.\n height (int): the maximum height in the y-axis.\n eps (float): safe division by zero. (default 1e-8).\n\n Return:\n torch.Tensor: the denormalized pixel coordinates.\n \"\"\"\n if pixel_coordinates.shape[-1] != 2:\n raise ValueError(\"Input pixel_coordinates must be of shape (*, 2). \"\n \"Got {}\".format(pixel_coordinates.shape))\n # compute normalization factor\n hw: torch.Tensor = torch.stack([\n torch.tensor(width), torch.tensor(height)\n ]).to(pixel_coordinates.device).to(pixel_coordinates.dtype)\n\n factor: torch.Tensor = torch.tensor(2.) / (hw - 1).clamp(eps)\n\n return torch.tensor(1.) / factor * (pixel_coordinates + 1)\n\n\ndef normalize_pixel_coordinates3d(\n pixel_coordinates: torch.Tensor,\n depth: int,\n height: int,\n width: int,\n eps: float = 1e-8) -> torch.Tensor:\n r\"\"\"Normalize pixel coordinates between -1 and 1.\n\n Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1).\n\n Args:\n pixel_coordinates (torch.Tensor): the grid with pixel coordinates.\n Shape can be :math:`(*, 3)`.\n depth (int): the maximum depth in the z-axis.\n height (int): the maximum height in the y-axis.\n width (int): the maximum width in the x-axis.\n eps (float): safe division by zero. (default 1e-8).\n\n Return:\n torch.Tensor: the normalized pixel coordinates.\n \"\"\"\n if pixel_coordinates.shape[-1] != 3:\n raise ValueError(\"Input pixel_coordinates must be of shape (*, 3). \"\n \"Got {}\".format(pixel_coordinates.shape))\n # compute normalization factor\n dhw: torch.Tensor = torch.stack([\n torch.tensor(depth), torch.tensor(width), torch.tensor(height)\n ]).to(pixel_coordinates.device).to(pixel_coordinates.dtype)\n\n factor: torch.Tensor = torch.tensor(2.) / (dhw - 1).clamp(eps)\n\n return factor * pixel_coordinates - 1\n\n\ndef denormalize_pixel_coordinates3d(\n pixel_coordinates: torch.Tensor,\n depth: int,\n height: int,\n width: int,\n eps: float = 1e-8) -> torch.Tensor:\n r\"\"\"Denormalize pixel coordinates.\n\n The input is assumed to be -1 if on extreme left, 1 if on\n extreme right (x = w-1).\n\n Args:\n pixel_coordinates (torch.Tensor): the normalized grid coordinates.\n Shape can be :math:`(*, 3)`.\n depth (int): the maximum depth in the x-axis.\n height (int): the maximum height in the y-axis.\n width (int): the maximum width in the x-axis.\n eps (float): safe division by zero. (default 1e-8).\n\n\n Return:\n torch.Tensor: the denormalized pixel coordinates.\n \"\"\"\n if pixel_coordinates.shape[-1] != 3:\n raise ValueError(\"Input pixel_coordinates must be of shape (*, 3). \"\n \"Got {}\".format(pixel_coordinates.shape))\n # compute normalization factor\n dhw: torch.Tensor = torch.stack([\n torch.tensor(depth), torch.tensor(width), torch.tensor(height)\n ]).to(pixel_coordinates.device).to(pixel_coordinates.dtype)\n\n factor: torch.Tensor = torch.tensor(2.) / (dhw - 1).clamp(eps)\n\n return torch.tensor(1.) / factor * (pixel_coordinates + 1)\n",
"import pytest\n\nimport torch\nfrom torch.testing import assert_allclose\nfrom torch.autograd import gradcheck\n\nfrom kornia.feature import HardNet\nimport kornia.testing as utils # test utils\n\n\nclass TestHardNet:\n def test_shape(self, device):\n inp = torch.ones(1, 1, 32, 32, device=device)\n hardnet = HardNet().to(device)\n hardnet.eval() # batchnorm with size 1 is not allowed in train mode\n out = hardnet(inp)\n assert out.shape == (1, 128)\n\n def test_shape_batch(self, device):\n inp = torch.ones(16, 1, 32, 32, device=device)\n hardnet = HardNet().to(device)\n out = hardnet(inp)\n assert out.shape == (16, 128)\n\n @pytest.mark.skip(\"jacobian not well computed\")\n def test_gradcheck(self, device):\n patches = torch.rand(2, 1, 32, 32, device=device)\n patches = utils.tensor_to_gradcheck_var(patches) # to var\n hardnet = HardNet().to(patches.device, patches.dtype)\n assert gradcheck(hardnet, (patches,), eps=1e-4, atol=1e-4,\n raise_exception=True, )\n\n @pytest.mark.jit\n def test_jit(self, device, dtype):\n B, C, H, W = 2, 1, 32, 32\n patches = torch.ones(B, C, H, W, device=device, dtype=dtype)\n model = HardNet().to(patches.device, patches.dtype).eval()\n model_jit = torch.jit.script(HardNet().to(patches.device, patches.dtype).eval())\n assert_allclose(model(patches), model_jit(patches))\n"
] |
[
[
"torch.abs",
"torch.cat",
"torch.sin",
"torch.where",
"torch.finfo",
"torch.norm",
"torch.sqrt",
"torch.eye",
"torch.tensor",
"torch.ones_like",
"torch.cos",
"torch.squeeze",
"torch.nn.functional.pad",
"torch.zeros_like",
"torch.is_tensor",
"torch.unsqueeze",
"torch.stack",
"torch.atan2",
"torch.nn.functional.normalize",
"torch.chunk",
"torch.clamp"
],
[
"torch.autograd.gradcheck",
"torch.ones",
"torch.rand"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
WayneGame/InformationExtraction
|
[
"d593adc5ad02fa7046873c95a1b4af0befe08c5f"
] |
[
"classification/src/train.py"
] |
[
"\nimport config\nimport pandas as pd\nimport pickle\nimport numpy as np\nfrom keras.preprocessing.text import Tokenizer\n\nfrom keras.preprocessing.sequence import pad_sequences\n\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import classification_report\nimport tensorflow as tf\nfrom keras import Sequential\nfrom tensorflow.keras.layers import Embedding, SpatialDropout1D, LSTM, Dense\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras import regularizers\nfrom keras.models import load_model\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.metrics import confusion_matrix\n\n\n\n\"\"\"\nVersuch #1\n\"\"\"\n\n# Gibt den classification-report aus\ndef evaluate(model, X_test, Y_test):\n Y_pred = model.predict(X_test)\n\n Y_pred = Y_pred.argmax(axis=-1)\n Y_test = Y_test.argmax(axis=-1)\n\n print(classification_report([Y_test], [Y_pred]))\n\n# Nimmt ein history-Objekt und zeichnet den loss für\n# sowohl testing als auch training Daten.\ndef plot_model(history, fold):\n plt.title('Loss')\n plt.plot(history.history['loss'], label='train_loss')\n plt.plot(history.history['val_loss'], label='test_loss')\n plt.legend()\n plt.savefig(f\"../plots/covid_model_without_vaccine_loss_{config.EPOCHS}epochs_{fold}v{config.K_FOLD_SPLITS}fold.png\")\n clear_plot()\n plt.title('Accuracy')\n plt.plot(history.history['accuracy'], label='train_acc', c=\"r\")\n plt.plot(history.history['val_accuracy'], label='test_acc', c=\"b\")\n plt.legend()\n plt.savefig(f\"../plots/covid_model_without_vaccine_accuracy_{config.EPOCHS}epochs_{fold}v{config.K_FOLD_SPLITS}fold.png\")\n clear_plot()\n\ndef clear_plot():\n plt.close()\n plt.cla()\n plt.clf()\n\ndef plot_confusion_matrix(model, X_test, y_test, fold):\n y_pred = model.predict(X_test)\n\n y_pred = y_pred.argmax(axis=-1)\n y_test = y_test.argmax(axis=-1)\n cm = confusion_matrix(y_test, y_pred)\n\n ax=plt.subplot()\n sns.heatmap(cm, annot=True, fmt='g', ax=ax)\n\n # labels, title and ticks\n ax.set_xlabel('Predicted labels')\n ax.set_ylabel('True labels') \n ax.set_title(f'Confusion Matrix – {config.EPOCHS}|{fold}') \n ax.xaxis.set_ticklabels(['Negative', 'Positive'])\n ax.yaxis.set_ticklabels(['Negative', 'Positive'])\n\n plt.savefig(f\"../plots/covid_confusion_{config.EPOCHS}epochs_{fold}v{config.K_FOLD_SPLITS}fold.png\")\n clear_plot()\n\n# Erstellen eines Tokenizers für das LSTM Modell\ndef create_tokenizer(df, save_path):\n tokenizer = Tokenizer(num_words=config.MAX_NUM_WORDS, filters='!\"#$%&()*+,-./:;<=>?@[\\]^_`{|}~', lower=True)\n words = df.link.values.tolist()\n words.extend(df.meta_data.values.tolist())\n words.extend(df.title.values.tolist())\n words.extend(df.body.values.tolist())\n tokenizer.fit_on_texts(words)\n save_tokenizer(tokenizer, save_path)\n return tokenizer\n\n# Laden und speichern des Tokenizers\ndef save_tokenizer(tokenizer, filename):\n with open(filename, 'wb') as f:\n pickle.dump(tokenizer, f, protocol=pickle.HIGHEST_PROTOCOL)\n\ndef load_tokenizer(filename):\n with open(filename, 'rb') as f:\n tokenizer = pickle.load(f)\n return tokenizer \n\n\"\"\"\nDie in Tokens verwandelte Texte sehen so aus:\n [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10, 11, 12]]\ngepaddet sehen sie so aus:\n [[ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4]\n [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 6 7]\n [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 9 10 11 12]]\n\nwerden danach die Covid Count Zahlen angefügt, sieht die Repräsentation beispielsweise so aus\n [[ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 10 20 30]\n [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 6 7 40 50 60]\n [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 9 10 11 12 70 80 90]]\n\nDas np.expand ist notwendig, um das array in beispielsweise folgende Form zu bringen: [ 2 1 20] => [ [2] [1] [20]] \n\"\"\"\ndef transform_text(tokenizer, df):\n if (isinstance(tokenizer, str)):\n tokenizer = load_tokenizer(tokenizer)\n\n # Tokenizing der Link Informationen\n X_input = tokenizer.texts_to_sequences(df['link'].values)\n X_input = pad_sequences(X_input, maxlen=config.MAX_LINK_SEQUENCE_LENGTH)\n # Tokenizing der Meta Informationen\n X_meta = tokenizer.texts_to_sequences(df['meta_data'].values)\n X_meta = pad_sequences(X_meta, maxlen=config.MAX_META_SEQUENCE_LENGTH)\n # Tokenizing der Titel Informationen\n X_title = tokenizer.texts_to_sequences(df['title'].values)\n X_title = pad_sequences(X_title, maxlen=config.MAX_TITLE_SEQUENCE_LENGTH)\n # Tokenizing des Seiteninhalts\n X_body = tokenizer.texts_to_sequences(df['body'].values)\n X_body = pad_sequences(X_body, maxlen=config.MAX_BODY_SEQUENCE_LENGTH)\n covid_word_count = df['covid_word_count'].values\n covid_word_count_url = df['covid_word_count_url'].values\n restriction_word_count = df['restriction_word_count'].values\n restriction_word_count_url = df['restriction_word_count_url'].values\n\n X_input = np.concatenate([X_input, X_meta], axis=-1)\n X_input = np.concatenate([X_input, X_title], axis=-1)\n X_input = np.concatenate([X_input, X_body], axis=-1)\n\n covid_word_count = np.expand_dims(covid_word_count, axis=(-1))\n X_input = np.concatenate([X_input, covid_word_count], axis=-1)\n\n covid_word_count_url = np.expand_dims(covid_word_count_url, axis=(-1))\n X_input = np.concatenate([X_input, covid_word_count_url], axis=-1)\n\n restriction_word_count = np.expand_dims(restriction_word_count, axis=(-1))\n X_input = np.concatenate([X_input, restriction_word_count], axis=-1)\n\n restriction_word_count_url = np.expand_dims(restriction_word_count_url, axis=(-1))\n X_input = np.concatenate([X_input, restriction_word_count_url], axis=-1) # Schlussendlich alles zusammefügen\n\n return X_input\n\ndef remove_stopwords(df):\n ger = pd.read_csv(config.STOPWORDS_PATH)['stopwords'].values\n\n df['link'] = df['link'].apply(lambda x: ' '.join([word for word in str(x).split() if word not in (ger)]))\n df['meta_data'] = df['meta_data'].apply(lambda x: ' '.join([word for word in str(x).split() if word not in (ger)]))\n df['title'] = df['title'].apply(lambda x: ' '.join([word for word in str(x).split() if word not in (ger)]))\n df['body'] = df['body'].apply(lambda x: ' '.join([word for word in str(x).split() if word not in (ger)]))\n\n return df\n\n\n# Nimmt den input DataFrame und einen LabelEncoder Objekt, \n# trainiert ein LSTM Modell, speichert es, evaluiert es \n# und gibt den Loss aus.\ndef train_model(train_df, valid_df, tokenizer, fold):\n \n X_train = transform_text(tokenizer, train_df)\n X_valid = transform_text(tokenizer, valid_df)\n Y_train = pd.get_dummies(train_df['label'])\n Y_valid = pd.get_dummies(valid_df['label']).to_numpy()\n \n model = Sequential()\n optimizer = tf.keras.optimizers.Adam(1e-3) # 0.001\n model.add(Embedding(config.MAX_NUM_WORDS, config.EMBEDDING_DIM, input_length=X_train.shape[1]))\n model.add(SpatialDropout1D(0.2))\n model.add(LSTM(100, dropout=0.2, recurrent_dropout=0.2, bias_regularizer=regularizers.l2(1e-4),)) # TODO: damit rumspielen\n model.add(Dense(2, activation='softmax'))\n loss='categorical_crossentropy'\n model.compile(loss=loss, optimizer=optimizer, metrics=['accuracy'])\n epochs = config.EPOCHS\n batch_size = config.BATCH_SIZE # 64\n\n #es = EarlyStopping(monitor='val_loss', patience=3, min_delta=0.0001)\n history = model.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, validation_split=0.2) # , callbacks=[es]\n accr = model.evaluate(X_valid,Y_valid)\n print('Test set\\n Loss: {:0.3f}\\n Accuracy: {:0.3f}'.format(accr[0],accr[1]))\n model.save(f\"{config.MODEL_PATH}_without_vaccine_{fold}.h5\")\n evaluate(model, X_valid, Y_valid)\n plot_model(history, fold)\n\n plot_confusion_matrix(model, X_valid, Y_valid, fold)\n\n# Laden und evaluieren eines existierenden Modells\ndef load_and_evaluate_existing_model(model_path, tokenizer_path, df, le):\n model = load_model(model_path)\n tokenizer = load_tokenizer(tokenizer_path)\n X = transform_text(tokenizer, df['text'].values)\n Y = pd.get_dummies(df['label']).values\n evaluate(model, X, Y, le)\n\n# Testen eines neuen Beispiels. Hauptsächlich zu Testzwecken während der Entwicklung\n# Die Funktion nimmt einen String, den Classifier,\n# den Vectorizer und einen LabelEncoder und \n# gibt eine Vorhersage zurück.\ndef test_new_example(model, tokenizer, le, text_input):\n X_example = transform_text(tokenizer, [text_input])\n label_array = model.predict(X_example)\n new_label = np.argmax(label_array, axis=-1)\n print(new_label)\n print(le.inverse_transform(new_label))\n\ndef run(df, fold, use_vaccine):\n\n # der Trainingdataframe\n train_df = df[df.kfold != fold].reset_index(drop=True)\n print(f\"Länge Traing_DF {len(train_df)}\")\n # Validation Dataframe\n valid_df = df[df.kfold == fold].reset_index(drop=True)\n print(f\"Länge Valid_DF {len(valid_df)}\")\n\n # Das Validationset enthält weiterhin die Impf-Beispiele\n # Bei 10 Folds sind die Sets folgendermaßen aufgeteil:\n # 0 – 126\n # 1 – 78\n # 2 – 10\n if not use_vaccine:\n train_df = train_df[train_df['label'] != 2]\n\n # Jetzt müssen alle 2 er noch in einsergewandelt werden\n train_df['label'] = train_df['label'].apply(lambda x : 1 if x > 0 else 0)\n valid_df['label'] = valid_df['label'].apply(lambda x : 1 if x > 0 else 0)\n\n\n print(\"Fitting tokenizer\")\n # tf.keras Tokenizer\n tokenizer = create_tokenizer(train_df, f\"{config.TOKENIZER_SAVE_PATH}_{fold}.pickle\")\n \n train_model(train_df, valid_df, tokenizer, fold)\n \n # load_and_evaluate_existing_model(f\"{config.MODEL_PATH}_{fold}\", config.TOKENIZER_PATH, df, le)\n #model = load_model(config.MODEL_PATH)\n #tokenizer = config.TOKENIZER_PATH\n\nif (__name__ == \"__main__\"):\n\n tf.get_logger().setLevel('ERROR')\n\n # load data\n df = pd.read_csv(config.DATASET_PATH).sample(frac=1)\n df = remove_stopwords(df)\n\n \"\"\"\n # TODO: ein Test, Gleichverteilung\n \"\"\"\n df2 = df[df['label'] != 0]\n \n # Wir nehmen einfach den hinteren Teil des Körpers und den Metadaten\n df2['body'] = df2['body'].apply(lambda x : str(x)[config.MAX_BODY_SEQUENCE_LENGTH:])\n df2['meta_data'] = df2['meta_data'].apply(lambda x : str(x)[config.MAX_META_SEQUENCE_LENGTH:])\n\n df = df.append(df2, ignore_index=True).reset_index()\n \n\n # initiate the kfold class from the model_selection module\n kf = StratifiedKFold(n_splits=config.K_FOLD_SPLITS)\n\n # füllen den kfold Spalte\n for f, (t_, v_) in enumerate(kf.split(X=df, y=df.label.values)):\n df.loc[v_, 'kfold'] = f\n\n\n # training für alle Faltungen\n for i in range(config.K_FOLD_SPLITS):\n print(f\"\\n–––––––––––– FOLD {i} ––––––––––––\\n\")\n run(df, fold=i, use_vaccine=config.USE_VACCINE)"
] |
[
[
"matplotlib.pyplot.legend",
"numpy.expand_dims",
"sklearn.metrics.confusion_matrix",
"matplotlib.pyplot.plot",
"numpy.concatenate",
"sklearn.metrics.classification_report",
"pandas.read_csv",
"tensorflow.keras.layers.Embedding",
"tensorflow.keras.regularizers.l2",
"sklearn.model_selection.StratifiedKFold",
"matplotlib.pyplot.subplot",
"numpy.argmax",
"matplotlib.pyplot.close",
"matplotlib.pyplot.title",
"tensorflow.keras.layers.Dense",
"matplotlib.pyplot.savefig",
"tensorflow.keras.layers.SpatialDropout1D",
"matplotlib.pyplot.cla",
"tensorflow.get_logger",
"matplotlib.pyplot.clf",
"tensorflow.keras.optimizers.Adam",
"pandas.get_dummies"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": [
"2.2"
]
}
] |
dhetong/LogSampleTest
|
[
"7ae4cffd43ba6c90f4a5cf164eb44072ece5f08d"
] |
[
"benchmark/IPLoM_agreement.py"
] |
[
"import sys\nsys.path.append('../')\nfrom logparser import IPLoM, evaluator\nimport os\nimport pandas as pd\n\nCT = [0.25, 0.3, 0.4, 0.4, 0.35, 0.58, 0.3, 0.3, 0.9, 0.78, 0.35, 0.3, 0.4]\nlb = [0.3, 0.4, 0.01, 0.2, 0.25, 0.25, 0.3, 0.25, 0.25, 0.25, 0.3, 0.2, 0.7]\nn_para = 13\n\nbenchmark_settings = {\n 'HDFS': {\n 'log_file': 'HDFS/HDFS_2k.log',\n 'log_format': '<Date> <Time> <Pid> <Level> <Component>: <Content>',\n 'regex': [r'blk_-?\\d+', r'(\\d+\\.){3}\\d+(:\\d+)?'],\n 'st': 0.5,\n 'depth': 4\n },\n\n 'Hadoop': {\n 'log_file': 'Hadoop/Hadoop_2k.log',\n 'log_format': '<Date> <Time> <Level> \\[<Process>\\] <Component>: <Content>',\n 'regex': [r'(\\d+\\.){3}\\d+'],\n 'st': 0.5,\n 'depth': 4\n },\n\n 'Spark': {\n 'log_file': 'Spark/Spark_2k.log',\n 'log_format': '<Date> <Time> <Level> <Component>: <Content>',\n 'regex': [r'(\\d+\\.){3}\\d+', r'\\b[KGTM]?B\\b', r'([\\w-]+\\.){2,}[\\w-]+'],\n 'st': 0.5,\n 'depth': 4\n },\n\n 'Zookeeper': {\n 'log_file': 'Zookeeper/Zookeeper_2k.log',\n 'log_format': '<Date> <Time> - <Level> \\[<Node>:<Component>@<Id>\\] - <Content>',\n 'regex': [r'(/|)(\\d+\\.){3}\\d+(:\\d+)?'],\n 'st': 0.5,\n 'depth': 4\n },\n\n 'BGL': {\n 'log_file': 'BGL/BGL_2k.log',\n 'log_format': '<Label> <Timestamp> <Date> <Node> <Time> <NodeRepeat> <Type> <Component> <Level> <Content>',\n 'regex': [r'core\\.\\d+'],\n 'st': 0.5,\n 'depth': 4\n },\n\n 'HPC': {\n 'log_file': 'HPC/HPC_2k.log',\n 'log_format': '<LogId> <Node> <Component> <State> <Time> <Flag> <Content>',\n 'regex': [r'=\\d+'],\n 'st': 0.5,\n 'depth': 4\n },\n\n 'Thunderbird': {\n 'log_file': 'Thunderbird/Thunderbird_2k.log',\n 'log_format': '<Label> <Timestamp> <Date> <User> <Month> <Day> <Time> <Location> <Component>(\\[<PID>\\])?: <Content>',\n 'regex': [r'(\\d+\\.){3}\\d+'],\n 'st': 0.5,\n 'depth': 4\n },\n\n 'Windows': {\n 'log_file': 'Windows/Windows_2k.log',\n 'log_format': '<Date> <Time>, <Level> <Component> <Content>',\n 'regex': [r'0x.*?\\s'],\n 'st': 0.7,\n 'depth': 5\n },\n\n 'Linux': {\n 'log_file': 'Linux/Linux_2k.log',\n 'log_format': '<Month> <Date> <Time> <Level> <Component>(\\[<PID>\\])?: <Content>',\n 'regex': [r'(\\d+\\.){3}\\d+', r'\\d{2}:\\d{2}:\\d{2}'],\n 'st': 0.39,\n 'depth': 6\n },\n\n 'Andriod': {\n 'log_file': 'Andriod/Andriod_2k.log',\n 'log_format': '<Date> <Time> <Pid> <Tid> <Level> <Component>: <Content>',\n 'regex': [r'(/[\\w-]+)+', r'([\\w-]+\\.){2,}[\\w-]+', r'\\b(\\-?\\+?\\d+)\\b|\\b0[Xx][a-fA-F\\d]+\\b|\\b[a-fA-F\\d]{4,}\\b'],\n 'st': 0.2,\n 'depth': 6\n },\n\n 'HealthApp': {\n 'log_file': 'HealthApp/HealthApp_2k.log',\n 'log_format': '<Time>\\|<Component>\\|<Pid>\\|<Content>',\n 'regex': [],\n 'st': 0.2,\n 'depth': 4\n },\n\n 'Apache': {\n 'log_file': 'Apache/Apache_2k.log',\n 'log_format': '\\[<Time>\\] \\[<Level>\\] <Content>',\n 'regex': [r'(\\d+\\.){3}\\d+'],\n 'st': 0.5,\n 'depth': 4\n },\n\n 'Proxifier': {\n 'log_file': 'Proxifier/Proxifier_2k.log',\n 'log_format': '\\[<Time>\\] <Program> - <Content>',\n 'regex': [r'<\\d+\\ssec', r'([\\w-]+\\.)+[\\w-]+(:\\d+)?', r'\\d{2}:\\d{2}(:\\d{2})*', r'[KGTM]B'],\n 'st': 0.6,\n 'depth': 3\n },\n\n 'OpenSSH': {\n 'log_file': 'OpenSSH/OpenSSH_2k.log',\n 'log_format': '<Date> <Day> <Time> <Component> sshd\\[<Pid>\\]: <Content>',\n 'regex': [r'(\\d+\\.){3}\\d+', r'([\\w-]+\\.){2,}[\\w-]+'],\n 'st': 0.6,\n 'depth': 5\n },\n\n 'OpenStack': {\n 'log_file': 'OpenStack/OpenStack_2k.log',\n 'log_format': '<Logrecord> <Date> <Time> <Pid> <Level> <Component> \\[<ADDR>\\] <Content>',\n 'regex': [r'((\\d+\\.){3}\\d+,?)+', r'/.+?\\s', r'\\d+'],\n 'st': 0.5,\n 'depth': 5\n },\n\n 'Mac': {\n 'log_file': 'Mac/Mac_2k.log',\n 'log_format': '<Month> <Date> <Time> <User> <Component>\\[<PID>\\]( \\(<Address>\\))?: <Content>',\n 'regex': [r'([\\w-]+\\.){2,}[\\w-]+'],\n 'st': 0.7,\n 'depth': 6\n },\n}\n\ninput_dir = '../../AgreementData/'\noutput_dir_1 = 'result/file1'\noutput_dir_2 = 'result/file2'\n\nHDFS_dir = 'HDFS/'\nHadoop_dir = 'Hadoop/'\nSpark_dir = 'Spark/'\nZookeeper_dir = 'Zookeeper/'\nBGL_dir = 'BGL/'\nHPC_dir = 'HPC/'\nThunderbird_dir = 'Thunderbird/'\nWindows_dir = 'Windows/'\nLinux_dir = 'Linux/'\nAndroid_dir = 'Android/'\nApache_dir = 'Apache/'\nOpenSSH_dir = 'OpenSSH/'\nOpenStack_dir = 'OpenStack/'\nMac_dir = 'Mac/'\nHealthApp_dir = 'HealthApp/'\nProxifier_dir = 'Proxifier/'\n\nHDFS_file = 'HDFS.log'\nHadoop_file = 'Hadoop.log'\nSpark_file = 'Spark.log'\nZookeeper_file = 'Zookeeper.log'\nBGL_file = 'BGL.log'\nHPC_file = 'HPC.log'\nThunderbird_file = 'Thunderbird.log'\nWindows_file = 'Windows.log'\nLinux_file = 'Linux.log'\nAndroid_file = 'Android.log'\nApache_file = 'Apache.log'\nOpenSSH_file = 'SSH.log'\nOpenStack_file = 'OpenStack.log'\nMac_file = 'Mac.log'\nHealthApp_file = 'HealthApp.log'\nProxifier_file = 'Proxifier.log'\n\nAndroid_num = 10\nApache_num = 10\nBGL_num = 10\nHadoop_num = 10\nHDFS_num = 10\nHealthApp_num = 10\nHPC_num = 10\nLinux_num = 3\nMac_num = 10\nOpenSSH_num = 10\nOpenStack_num = 1\nProxifier_num = 2\nSpark_num = 10\nThunderbird_num = 10\nWindows_num = 10\nZookeeper_num = 10\n\nsetting = benchmark_settings['BGL']\n\nagreement_result = []\nfor index in range(0,BGL_num,1):\n logfile_1 = BGL_file + '.part' + str(index)\n logfile_2 = BGL_file + '.part' + str(index+1)\n indir = input_dir + BGL_dir\n\n print(logfile_1)\n print(logfile_2)\n\n for para_index in range(0,n_para-1,1):\n para_info = str(CT[para_index]) + ',' + str(lb[para_index])\n print(para_info)\n parser_1 = IPLoM.LogParser(log_format=setting['log_format'], indir=indir, outdir=output_dir_1,\n CT=CT[para_index], lowerBound=lb[para_index], rex=setting['regex'])\n parser_2 = IPLoM.LogParser(log_format=setting['log_format'], indir=indir, outdir=output_dir_2,\n CT=CT[para_index], lowerBound=lb[para_index], rex=setting['regex'])\n parser_1.parse(logfile_1)\n parser_2.parse(logfile_2)\n agreement = evaluator.evaluate_agreement(\n\t\tos.path.join(output_dir_1, logfile_1 + '_structured.csv'),\n\t\tos.path.join(output_dir_2, logfile_2 + '_structured.csv'))\n ratio = float(float(agreement)/5000.0)\n agreement_result.append([logfile_1,logfile_2,para_info,ratio])\n\ndf_result = pd.DataFrame(agreement_result, columns=['File1', 'File2', 'Para', 'Agreement'])\nprint(df_result)\ndf_result.to_csv('IPLoM_agreement_BGL.csv')\n"
] |
[
[
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
aiporre/whisk
|
[
"e07c381bc5d0df4e5dcabd7d75c0c97d0de3ad2c",
"e07c381bc5d0df4e5dcabd7d75c0c97d0de3ad2c"
] |
[
"whisk/test_merge3.py",
"pipeline/SconsPipeline.py"
] |
[
"\"\"\"\nAuthor: Nathan Clack\nDate : 2009\n\nCopyright (c) 2009 HHMI. Free downloads and distribution are allowed for any\nnon-profit research and educational purposes as long as proper credit is given\nto the author. All other rights reserved.\n\"\"\"\nfrom .tests import plot_whiskers\nfrom ui.whiskerdata.trace import Whisker_Seg\nfrom numpy import *\nimport pdb\nfrom functools import reduce\n\ndef load():\n from ui.whiskerdata import load_whiskers, load_trajectories\n from ui.genetiff import Reader\n movie = Reader('data/seq/whisker_data_0140.seq',adjuststipple=1)\n w,wid = load_whiskers('seq.whiskers')\n #movie = Reader('../../data/W0.tif',adjuststipple=1)\n #w,wid = load_whiskers('w0-grid.whiskers')\n #w,wid = load_whiskers('whisk-vc/whisk-vc/seq.whiskers')\n #movie = Reader('data/JF8410_041808_001.tif',adjuststipple=1)\n #w,wid = load_whiskers('test.whiskers')\n #movie = Reader('data/lorenz/090519-19a_0035.seq',adjuststipple=1)\n #w,wid = load_whiskers('lorenz.whiskers')\n #w,wid = load_whiskers('results/seq-hand.whiskers')\n #t,tid = load_trajectories('results/seq-hand.trajectories')\n return w,movie\n\ndef check_bounds(wvd,shape):\n for fid, wv in wvd.items():\n for i,w in wv.items():\n for x,y,t,s in w:\n if x<0 or x>=shape[1] or y<0 or y>=shape[0]:\n print(\"out of bounds\")\n pdb.set_trace()\n if not ( w.x.flags.contiguous and w.y.flags.contiguous ):\n print(\"not contiguous\")\n pdb.set_trace()\n \n\ndef fix(wvd,movie,scale=2, signal_per_pixel = 0, max_dist = 60, max_angle = 20.*pi/180.):\n shape = movie[0].shape\n for fid,wv in list(wvd.items()):\n print(fid)\n table = CollisionTable( wv, shape, scale )\n r = set( resolution( table, wv ) )\n for j,l in choose_gaps(movie[fid],r,signal_per_pixel,max_dist,max_angle):\n e = reduce( Whisker_Seg.join, j )\n r.discard( j[0] )\n r.discard( j[-1] )\n r.add(e)\n wvd[fid] = dict( [ p for p in enumerate(r) ] )\n return wvd\n \ndef compute_join_length( px, py, tlow = 0.0, thigh = 1.0 ):\n from scipy.integrate import quad\n xp = polyder( px, 1 )\n yp = polyder( py, 1 )\n xp2 = polymul( xp, xp )\n yp2 = polymul( yp, yp )\n p = polyadd( xp2, yp2 )\n integrand = lambda t: sqrt( polyval( p, t ) )\n return quad(integrand, tlow, thigh) [0]\n\ndef compute_join_curvature( px, py ):\n from scipy.integrate import quad\n xp = polyder( px, 1 )\n xpp = polyder( px, 2 )\n yp = polyder( py, 1 )\n ypp = polyder( py, 2 )\n pn = polyadd( polymul( xp, ypp ), polymul( yp, xpp )) #numerator\n pd = polyadd( polymul( xp, xp ) , polymul( yp, yp ) ) #denominator\n integrand = lambda t: fabs(polyval( pn, t )/( polyval( pd, t )**(1.5)) ) \n return quad(integrand, 0, 1) [0]\n\ndef compute_join_angle( px, py ):\n from scipy.integrate import quad\n xp = polyder( px, 1 )\n yp = polyder( py, 1 )\n integrand = lambda t: arctan2(polyval(yp, t), polyval(xp, t)) \n return quad(integrand, 0, 1) [0]\n\ndef _compute_intensity( im, x, y ):\n if ( x<0 ).any() or \\\n ( x>=im.shape[1] ).any() or \\\n ( y<0 ).any() or \\\n ( y>=im.shape[0] ).any():\n return inf\n p = set( p for p in zip(x,y) )\n score = 0\n for j,i in p:\n score += im[i,j]\n return score/len(p)\n\ndef compute_join_intensity( im, px, py ):\n tt = linspace(0,1,50)\n x = array( [round(polyval(px,t)) for t in tt] )\n y = array( [round(polyval(px,t)) for t in tt] )\n return _compute_intensity(im,x,y)\n\ndef compute_join_score( im, px, py, thick = 2 ):\n tt = linspace(0,1,50)\n dpx = polyder(px)\n dpy = polyder(py)\n dL2 = polymul(dpx,dpx) + polymul(dpy,dpy)\n ux = polyval( px,tt )\n uy = polyval( py,tt )\n dx = diff(ux) #polyval( px,tt )\n dy = diff(uy) #polyval( py,tt )\n dx = r_[dx[0],dx]\n dy = r_[dy[0],dy]\n dL = sqrt( dx**2 + dy**2 )\n\n a = _compute_intensity(im, ux, uy )\n b = _compute_intensity(im, ux + thick*dy/dL , uy - thick*dx/dL )\n c = _compute_intensity(im, ux - thick*dy/dL , uy + thick*dx/dL )\n return (2*a - b - c)/4.0\n\ndef solve_polynomial_join( left, right, reverse = 0):\n \"\"\"\n Solves for a parametric cubic polynomial curve joining the right side of left\n to the left side of right. The curve matches slope and position at it's\n boundaries and is parameterized from 0 to 1; 0 being the left boundary and 1\n being the right.\n\n method: parametric cubic matching position and slope of endpoints.\n This ends up being cheap to compute, since the matrix is\n known (interval of parameter is always 0 to 1) and so the \n inverse can be precomputed. \n minv is inverse of m, where:\n m = array( [ [ a**3, a**2, a, 1 ],\n [ b**3, b**2, b, 1 ], \n [ 3*a**2, 2*a , 1, 0 ],\n [ 3*b**2, 2*b , 1, 0 ] ] )\n is the matrix for the linear system:\n m * coeff = v,\n with v = [ x(0) x(1) dx/dt(0) dx/dt(1) ].\n Here a = 0 and b = 1 so m and it's inverse is always the same.\n \n \"\"\"\n minv = matrix( [[ 2., -2., 1., 1.],\n [-3., 3., -2., -1.],\n [ 0., 0., 1., 0.],\n [ 1., 0., 0., 0.]])\n #take care of cases joining very short segements\n lr = len(right)\n ll = len(left)\n #L = length( right.x, right.y ) + length( left.x, left.y )\n #dd = hypot( left.x[0] - right.x[-1], left.y[0] - right.y[-1] )\n nl = ll/4\n nr = lr/4\n slope = lambda v: v[ 0] - v[-1] # want the total change over the length\n #slope = lambda v: diff(v).mean()\n length = lambda x,y: hypot(diff(x),diff(y)).sum() # euclidian distance in pixels\n #\n # Compute slope at boundary.\n # Uses a number of points near the boundary to compute slope.\n # Need to account for edge cases where one or both sides\n # consist of very few points.\n #\n if nr < 2 and nl < 2: \n lnorm = length( left.x , left.y ) \n rnorm = length( right.x , right.y ) \n dly = diff( left.y ).mean() / lnorm\n dlx = diff( left.x ).mean() / lnorm\n dry = diff(right.y ).mean() / rnorm\n drx = diff(right.x ).mean() / rnorm\n nl = 0\n nr = lr - 1\n elif nr < 2: # use the derivative on the other side\n lnorm = length( left.x[:nl], left.y[:nl] ) \n rnorm = length( right.x , right.y ) \n dly = -slope( left.y[(-nl):] ) / lnorm\n dlx = -slope( left.x[(-nl):] ) / lnorm\n dry = diff(right.y ).mean() / rnorm\n drx = diff(right.x ).mean() / rnorm\n nr = lr - 1\n #print dly,dlx,dry,drx\n elif nl < 2: # use the derivative on the other side\n rnorm = length( right.x[:nr], right.y[:nr] ) \n lnorm = length( left.x , left.y ) \n dry = -slope(right.y[:nr] ) / rnorm\n drx = -slope(right.x[:nr] ) / rnorm\n dly = diff( left.y ).mean() / lnorm\n dlx = diff( left.x ).mean() / lnorm\n nl = 0\n else: # the \"normal\" case\n rnorm = length( right.x[:nr], right.y[:nr] ) # Compute path length of right border region\n lnorm = length( left.x[(-nl):], left.y[(-nl):] ) # Compute path length of left border region\n dry = -slope(right.y[:nr] ) / rnorm # Compute dy/dl for right side\n drx = -slope(right.x[:nr] ) / rnorm # etc...\n dly = -slope( left.y[(-nl):] ) / lnorm\n dlx = -slope( left.x[(-nl):] ) / lnorm\n rnorm = hypot( left.x[0] - right.x[0], left.y[0] - right.y[0] ) \n lnorm = hypot( left.x[-1]- right.x[0], left.y[-1]- right.y[0] )\n if not isfinite(dlx): dlx =(left.x[0] - right.x[0])/lnorm\n if not isfinite(dly): dly =(left.y[0] - right.y[0])/lnorm\n if not isfinite(drx): drx =(left.x[-1] - right.x[0])/rnorm\n if not isfinite(dry): dry =(left.y[-1] - right.y[0])/rnorm\n \n if reverse:\n dlx = -dlx\n dly = -dly\n drx = -drx\n dry = -dry\n\n ry = right.y[ 0] ## right.y[nr] \n ly = left.y[-1 ] ## left.y[-nl] \n rx = right.x[ 0] ## right.x[nr] \n lx = left.x[-1 ] ## left.x[-nl] \n L = hypot( rx-lx, ry-ly ) # Approximate dl/dt \n print(\"L:%g\"%L)\n yv = matrix( [[ ly ], \n [ ry ], \n [ dly * L ], # dy/dt = dy/dl * dl/dt\n [ dry * L ]])\n xv = matrix( [[ lx ], \n [ rx ], \n [ dlx * L ], \n [ drx * L ]])\n cx = minv*xv\n cy = minv*yv\n \n if not (isfinite(cx).any() and isfinite(cy).any()):\n pdb.set_trace()\n return [array(t).squeeze() for t in (cx,cy)]\n\ndef plot_join(px,py,*args,**kwargs):\n from pylab import plot, polyval\n tt = linspace(0,1,50)\n plot( polyval(px,tt), polyval(py,tt), *args, **kwargs )\n\ndef plot_test(px,py,thick=2):\n from pylab import plot \n tt = linspace(0,1,50)\n dpx = polyder(px)\n dpy = polyder(py)\n dL2 = polymul(dpx,dpx) + polymul(dpy,dpy)\n ux = polyval( px,tt )\n uy = polyval( py,tt )\n dx = diff(ux) #polyval( px,tt )\n dy = diff(uy) #polyval( py,tt )\n dx = r_[dx[0],dx]\n dy = r_[dy[0],dy]\n dL = sqrt( dx**2 + dy**2 )\n\n plot( ux, uy , '.-')\n plot( ux + thick*dy/dL , uy - thick*dx/dL ,'-')\n plot( ux - thick*dy/dL , uy + thick*dx/dL ,'-' )\n\ndef filter_ends( wv, min_score, shape, border = 10 ):\n \"\"\"\n Return candidate ends for joining.\n\n Returns an iterator yielding (Whisker_Seg, side).\n \"\"\"\n maxy, maxx = [x - border for x in shape]\n minx, miny = border, border\n test_point = lambda x,y: x>minx and x<maxx and y > miny and y < maxy\n bordertest = lambda e,side: test_point( e.x[side], e.y[side] )\n scoretest = lambda e,side: e.scores[side] > min_score\n sides = [0,-1]\n for e in wv:\n for s in sides:\n if bordertest(e,s) and scoretest(e,s):\n yield e,s\n\ndef plot_candidate_ends(im, wv, min_score, border = 10):\n from pylab import plot, imshow, cm, ion,ioff, show, text\n left,right = group_ends( list(filter_ends(wv,min_score,im.shape, border)) ) \n\n ioff()\n #imshow(im,cmap=cm.gray,hold=0)\n m = {0:'ro',-1:'gs'}\n for i,e in enumerate(left):\n s = 0\n text(e.x[s],e.y[s],str(i),color=m[s][0])\n plot([e.x[s]],[e.y[s]],m[s])\n for i,e in enumerate(right):\n s = -1\n text(e.x[s],e.y[s],str(i),color=m[s][0])\n plot([e.x[s]],[e.y[s]],m[s])\n show()\n ion()\n\ndef group_ends( ends ):\n return [e for e,s in ends if s == 0], [e for e,s in ends if s == -1]\n\ndef end_direction(w, side, n=16):\n a = 0\n b = min( n, len(w) )\n if side != 0:\n a = -b\n b = -1\n dx = diff( w.x[a:b] ).mean()\n dy = diff( w.y[a:b] ).mean()\n return dx,dy\n\ndef make_joining_whisker(px,py,dist,lthick,lscore,rthick,rscore):\n w = Whisker_Seg()\n tt = linspace(0,1,round(dist))\n w.x = polyval(px,tt).astype(float32)\n w.y = polyval(py,tt).astype(float32) \n w.thick = polyval( [rthick-lthick,lthick], tt ).astype(float32) \n w.scores = polyval( [rscore-lscore,lscore], tt ).astype(float32) \n return w\n\ndef choose_gaps(im,wv, signal_per_pixel = 0.0, max_dist=60, max_angle = pi/4.):\n left,right = group_ends( list(filter_ends(wv,100,im.shape)) ) \n theta = lambda w,side: reduce(arctan2, reversed( end_direction(w,side) ) ) \n dtheta = lambda left,right: fabs(theta(left,0) - theta(right,-1))\n for i,a in enumerate(left):\n for j,b in enumerate(right):\n dx = a.x[ 0]-b.x[-1]\n dy = a.y[ 0]-b.y[-1]\n d = hypot(dx,dy)\n dth = dtheta(a,b)\n v = end_direction(a,0)\n norm = hypot(*v)\n proj = dot( v/norm, (dx,dy) )\n # jth: angle change from a to direct line joining a,b\n jth = fabs(arctan2( hypot(*( dx-proj*v[0]/norm, dy-proj*v[1]/norm )) , proj )) \n #print i,j,\n #print \"\\tD: %g Proj: %g Theta: %g\"%(d,proj,jth*180/pi)\n l=0;\n if d < max_dist and jth < max_angle and proj > 0:\n px,py = solve_polynomial_join( b, a )\n l = compute_join_score(im,px,py)\n if l < -signal_per_pixel:\n #plot_test(px,py)\n print(\"\\tScore: %g Theta: %g\"%(l,jth*180/pi))\n e = make_joining_whisker(px,py,d,b.thick[-1],b.scores[-1],a.thick[ 0],a.scores[ 0])\n yield (b,e,a),l\n\ndef gap_measures(im,wv):\n pmetric = lambda p: sqrt(dot(p[:-1],p[:-1]))\n left,right = group_ends( list(filter_ends(wv,100,im.shape)) ) \n shape = (len(left),len(right) )\n d = zeros( shape )\n l = zeros( shape )\n c = zeros( shape )\n cx = zeros( shape )\n cy = zeros( shape )\n for i,a in enumerate(left):\n for j,b in enumerate(right):\n dx = a.x[0 ]-b.x[-1]\n dy = a.y[0 ]-b.y[-1]\n d[i,j] = hypot(dx,dy)\n px,py = solve_polynomial_join( b, a )\n lpx,lpy = solve_polynomial_join( a, a, reverse = 1 )\n rpx,rpy = solve_polynomial_join( b, b, reverse = 1 )\n cx[i,j] = max( pmetric( px - lpx ) , pmetric( px - rpx ) )\n cy[i,j] = max( pmetric( px - lpx ) , pmetric( py - rpy ) )\n #l[i,j] = compute_join_length(px,py)\n l[i,j] = compute_join_score(im,px,py)\n plot_test(px,py)\n #c[i,j] = compute_join_curvature(px,py)\n #if sqrt( px[0]**2 + py[0]**2 ) < 50.0:\n # plot_join(px,py)\n return d,l,cx,cy\n\ndef trace_overlap(xxx_todo_changeme, xxx_todo_changeme1, thresh = 2.0 ):\n # DONE: does not assume that indexes run along same direction\n (wa,i) = xxx_todo_changeme\n (wb,j) = xxx_todo_changeme1\n def dist(ia,ib):\n a,b = wa[ia], wb[ib]\n return hypot( a[0] - b[0], a[1] - b[1] )\n # determine relative direction of indexing\n ia,ib = i,j\n if ia == len(wa)-1 or ib == len(wb)-1:\n if ia != 0 and ib != 0:\n dax = wa.x[ia-1] - wa.x[ia]\n day = wa.y[ia-1] - wa.y[ia] \n dbx = wb.x[ib-1] - wb.x[ib] \n dby = wb.y[ib-1] - wb.y[ib]\n elif ia == 0:\n dax = wa.x[ia+1] - wa.x[ia]\n day = wa.y[ia+1] - wa.y[ia] \n dbx = - wb.x[ib-1] + wb.x[ib] \n dby = - wb.y[ib-1] + wb.y[ib]\n elif ib == 0:\n dax = - wa.x[ia-1] + wa.x[ia]\n day = - wa.y[ia-1] + wa.y[ia] \n dbx = wb.x[ib+1] - wb.x[ib] \n dby = wb.y[ib+1] - wb.y[ib]\n else:\n dax = wa.x[ia+1] - wa.x[ia]\n day = wa.y[ia+1] - wa.y[ia] \n dbx = wb.x[ib+1] - wb.x[ib] \n dby = wb.y[ib+1] - wb.y[ib]\n stepa = -1; #only need to keep track of one direction\n enda = 0; \n notend = lambda i,n: i>n\n if( abs(dax) > abs(day) ): #determine by x change\n if( dax*dbx < 0 ): #have different signs\n stepa = 1\n enda = len(wa)\n notend = lambda i,n: i<n-1\n else: #determine by y change\n if( day*dby < 0 ): #have different signs\n stepa = 1\n enda = len(wa)\n notend = lambda i,n: i<n-1\n \n bnda = [i,i]\n bndb = [j,j]\n ms = 0 \n while ms < thresh and notend(ia,enda) and ib > 0:\n moves = ( ( ia + stepa, ib - 1 ),\n ( ia + stepa, ib ),\n ( ia , ib - 1 ) )\n scores = [dist( iam, ibm ) for iam, ibm in moves]\n ms = min(scores)\n for idx,s in enumerate( scores ): #choose best move\n if s == ms:\n ia,ib = moves[idx]\n break\n #relax at boundary, move downhill\n if not notend(ia,enda) and ib == 0: \n pass\n elif not notend(ia,enda):\n last = ms\n s = dist( ia, ib - 1 )\n while s < last and ib > 1:\n ib -= 1\n last = s\n s = dist( ia, ib - 1 )\n elif ib == 0:\n last = ms\n s = dist( ia + stepa, ib )\n while s < last and notend(ia,enda-stepa):\n ia += stepa\n last = s\n s = dist( ia + stepa, ib )\n\n bnda[0] = ia\n bndb[0] = ib\n\n #flip direction\n if stepa == -1:\n stepa = 1\n enda = len(wa)\n notend = lambda i,n:i<n-1\n else:\n stepa = -1\n enda = 0\n notend = lambda i,n: i>n\n\n ia,ib = i,j\n ms = 0 \n while ms < thresh and notend(ia,enda) and ib < len(wb)-1:\n moves = ( ( ia + stepa, ib + 1 ),\n ( ia + stepa, ib ),\n ( ia , ib + 1 ) )\n scores = [dist( iam, ibm ) for iam, ibm in moves]\n ms = min(scores)\n for idx,s in enumerate(scores):\n if s == ms:\n ia,ib = moves[idx]\n break\n #relax at boundary, move downhill\n if not notend(ia,enda) and ib == len(wb)-1: \n pass\n elif not notend(ia,enda):\n last = ms\n s = dist( ia, ib + 1 )\n while s < last and ib < len(wb)-2:\n ib += 1\n last = s\n s = dist( ia, ib + 1 )\n elif ib == len(wb)-1:\n last = ms\n s = dist( ia + stepa, ib )\n while s < last and notend(ia,enda-stepa):\n ia += stepa\n last = s\n s = dist( ia + stepa, ib )\n\n bnda[1] = ia\n bndb[1] = ib\n bnda.sort()\n return bnda, bndb\n\ndef resolution(table, wvd):\n rest = set(wvd.values())\n match = next(table)\n while match:\n keep,discard = merge(match)\n if discard: \n for a in discard:\n table.remove( a )\n for a in keep:\n yield a\n for a,i in match:\n rest.discard(a)\n match = next(table)\n for a in rest:\n yield a\n\ndef pairwise_merge( match ):\n overhang = 8\n wa = match[0][0]\n wb = match[1][0]\n bnda, bndb = trace_overlap(*match)\n iscomplete = lambda bnd,w: bnd[0] < overhang and bnd[1] >= len(w)-overhang\n if iscomplete(bnda,wa) or iscomplete(bndb,wb):\n sa = wa.scores.sum()\n sb = wb.scores.sum()\n if sa > sb:\n return wa,None\n else:\n return None,wb\n return None,None\n\ndef merge( match ):\n dep = dict( [ (e[0],0) for e in match ] )\n\n #iterate through all pairs and mark those who are contained in another whisker\n # The pairwise merge should impose a strict ordering\n match = list(match)\n for i,ma in enumerate(match):\n for j,mb in enumerate(match[ (i+1): ]):\n ra,rb = pairwise_merge( (ma,mb) )\n if ra or rb:\n if not ra:\n dep[ma[0]] = 1\n if not rb:\n dep[mb[0]] = 1\n # partition into two sets. Those to keep and those to discard.\n # Those to keep depend on none of the others.\n return [ k for k,v in dep.items() if v==0 ], \\\n [ k for k,v in dep.items() if v!=0 ]\n\nclass CollisionTable(object):\n def __init__(self, wvd, shape, scale):\n \"\"\" `wvd` may be either a dict or list of whiskers \"\"\"\n object.__init__(self)\n self._map = {}\n self._shape = shape\n self._scale = scale\n self._stride = stride = shape[1]/scale\n self.topx = lambda p: int(p[0]/scale) + stride * int(p[1]/scale)\n self._build_inverse_table( wvd )\n \n def _build_inverse_table(self, wvd ):\n g = enumerate(wvd)\n if isinstance(wvd, dict):\n g = iter(wvd.items())\n for i,w in g:\n self.add(w)\n\n def update( self, changes ):\n \"\"\" Changes is a dict mapping old whisker segments to new segments \"\"\"\n last = None\n for w,p in changes.items():\n self.remove(w)\n if p:\n self.add(p[0]) # add back ends\n self.add(p[-1])\n last = p[1]\n if last:\n self.add(last) # add back last middle \n\n def add(self, w):\n if not w: return\n hash = lambda e: enumerate( map(self.topx,list(zip(e.x,e.y))) )\n for i,px in hash(w):\n self._map.setdefault(px,set()).add( (w,i) )\n for i,px in hash(w): # scan back through and remove repeat hits on a pixel\n for x in [e for e in self._map[px] if e[0] == w][1:]:\n self._map[px].remove(x)\n\n def remove(self, w):\n if not w: return\n hash = lambda e: enumerate( map(self.topx,list(zip(e.x,e.y))) )\n for i,px in hash(w):\n s = self._map.get(px)\n if s:\n s.discard( (w,i) )\n \n def __iter__(self):\n m = next(self)\n while m:\n yield m\n m = next(self)\n\n def __next__(self):\n \"\"\" This changes the inverse table by removing hits.\n\n Returns a (Whisker_Seg, index),(Whisker_Seg, index)... tuple\n or None, if done.\n \"\"\"\n todelete = []\n retval = None\n for px,s in self._map.items():\n todelete.append(px) # get rid of references to visited pixels\n if len(s) > 1:\n retval = s\n break\n\n for k in todelete:\n del self._map[k]\n\n return retval\n \n def counts( self ):\n tosc = lambda e: e/self._scale\n im = zeros(list(map(tosc, self._shape)))\n imr = im.ravel()\n for px,s in self._map.items():\n imr[px] = len(s) #len(set( [e for e,i in s] ))\n return im\n",
"from builtins import next\nfrom SCons.Script import *\nimport os\nimport re\n\ntry:\n from traj import MeasurementsTable\nexcept ImportError:\n def MeasurementsTable(x):\n raise Exception(\"No module named traj\")\n\ntry:\n from ui.genetiff import Reader\n def thumbnail(target, source, env):\n import Image\n Image.fromarray( Reader(source[0].path)[0] ).save( target[0].path )\nexcept ImportError:\n def thumbnail(target,source,env):\n raise Exception(\"No module named ui.genetiff\")\n\ndef change_label( name, newlabel ):\n if name.rfind(']')==-1:\n pfx,ext = os.path.splitext(name)\n return'%s[%s]%s'%(pfx,newlabel,ext)\n else:\n return re.sub( '(?<=\\[).*(?=\\]($|\\.))',newlabel, name ) #substitutes the last label before the dot\n\ndef change_ext( node, newext ):\n prefix,ext = os.path.splitext( node.path )\n target = env.File( os.path.split(prefix)[1] + newext )\n return target\n\n\ndef length_v_score_plot(target,source,env):\n import matplotlib\n matplotlib.use('Agg')\n from pylab import plot, savefig, figure, close\n data = MeasurementsTable( source[0].path ).get_shape_table()\n f = figure()\n plot(data[:,0],data[:,1],'k.',markersize=1, hold=0)\n savefig( target[0].path )\n close(f)\n\ndef dfs_consume_tuples(g,cur):\n while isinstance(cur,tuple):\n yield cur\n cur = next(g)\n def rest():\n yield cur\n for e in g:\n yield e\n yield rest()\n\ndef flatten(tree):\n isbranch = lambda y: any( [isinstance(y,x) for x in [tuple,\n list,\n SCons.Node.NodeList]])\n if not isbranch(tree):\n yield tree\n else:\n for node in tree:\n if isbranch(node):\n for e in flatten(node):\n yield e\n else:\n yield node\n\ndef dfs_reduce(f,tree):\n \"\"\"\n >>> a = (0,1,2,(3,4,(5,),(6,)),(7,8),9,0,1,2,(4,(5,),6),7)\n >>> f = lambda x,y: str(x)+str(y)\n >>> list(dfs_reduce(f,a))\n ['012345', '012346', '01278', '012901245', '012901246', '01290127']\n \"\"\"\n def _dfs_reduce(f,tree, a = None):\n tree = iter(tree)\n for node in tree:\n if isinstance(node,tuple):\n return tuple ( [_dfs_reduce( f, e, a ) for e in dfs_consume_tuples(tree,node)]\n )\n else:\n a = node if a is None else f(a,node) #process node\n return a\n res = flatten(_dfs_reduce(f,tree))\n #for e in map(str,res):\n # print e\n return res\n\ndef pipeline_standard(env, movie):\n def alter(j,subdir,ext):\n return env.File(j).Dir(subdir).File( os.path.splitext(os.path.split(j.path)[-1])[0]+ext )\n\n builders = [\n movie,\n ( env.Bar,\n (env.Precious,),\n ),\n env.Whisk,\n (env.Precious,),\n env.Measure,\n env.Classify,\n env.HmmLRTimeWatershedSolver,\n env.GreyAreaSolver,\n env.Summary \n ]\n\n compose = lambda a,b: b(a)\n jobs = dfs_reduce( compose, builders )\n return jobs\n\ndef pipeline_production(env, sources):\n def alter(j,subdir,ext):\n return env.File(j).Dir(subdir).File( os.path.splitext(os.path.split(j.path)[-1])[0]+ext ) \n\n builders = [ \n sources, #start with movie files\n env.Whisk,\n (env.Precious,),\n lambda j: env.Command( change_ext(j[0], '.measurements'), j, \n [ \"measure --face $FACEHINT $SOURCE $TARGET\" ,\n \"classify $TARGET $TARGET $FACEHINT -n $WHISKER_COUNT --px2mm $PX2MM\",\n \"reclassify -n $WHISKER_COUNT $TARGET $TARGET\"]),\n ]\n\n compose = lambda a,b: b(a)\n jobs = dfs_reduce( compose, builders ) \n return jobs\n\ndef pipeline_oconnor(env, movie):\n def start(mov):\n b = env.Bar(mov)\n env.Precious(b)\n w = env.Whisk(mov)\n env.Precious(w)\n return env.MeasureWithBar(w+b)\n builders = [\n movie,\n start,\n env.ClassifyNoHairs,\n ( env.MeasurementsAsTrajectories,),\n ( env.MeasurementsAsMatlab,),\n env.Summary\n ]\n\n compose = lambda a,b: b(a)\n jobs = dfs_reduce( compose, builders )\n return jobs\n\ndef pipeline_curated(env, source):\n def commit_traj(node):\n \"\"\" expects source to be a curated whiskers file\n generated target is a measurements file\n returns target node\n \"\"\"\n node = node[0]\n target = change_ext( node, '[traj].measurements' )\n sources = [change_ext(node, e) for e in ['.measurements',\n '.trajectories']]\n out = env.Command( target, sources, \"measure.py $SOURCES $TARGET\" )\n return out\n\n builders = [\n source,\n env.Measure,\n commit_traj,\n env.Summary\n ]\n compose = lambda a,b: b(a)\n jobs = dfs_reduce( compose, builders )\n return jobs\n\ndef lit(s):\n return lambda env,sources: s\n\ndef whisk_generator( source, target, env, for_signature ):\n if not target[0].exists():\n return Action(\"trace $SOURCE $TARGET\")\n else:\n return Action(\"\")\n\ndef bar_generator( source, target, env, for_signature ):\n if not target[0].exists():\n return Action(\"whisk $SOURCE $TARGET --no-whisk\")\n else:\n return Action(\"\")\n\nenv = Environment(\n ENV = {'PATH':os.environ['PATH']},\n PX2MM = 0,\n BUILDERS = {\n 'Thumbnail' : Builder(action = thumbnail),\n 'LengthVScorePlot': Builder(action = length_v_score_plot),\n 'Whisk' : Builder(generator = whisk_generator,\n suffix = '.whiskers',\n src_suffix = '.seq'\n ),\n 'Bar' : Builder(generator = bar_generator,\n #action = \"whisk $SOURCE $TARGET --no-whisk\",\n suffix = '.bar',\n src_suffix = '.seq'\n ),\n 'Heal' : Builder(action = \"test_merge_collisiontable_3 $SOURCE $TARGET\",\n suffix = '.whiskers',\n src_suffix = '.whiskers'\n ),\n 'Measure': Builder(action = \"test_measure_1 --face $FACEHINT $SOURCE $TARGET\",\n suffix = '.measurements',\n src_suffix = '.whiskers'\n ),\n 'MeasureWithBar': Builder(action = \"test_measure_1 --face $FACEHINT $SOURCES $TARGET\",\n suffix = '.measurements',\n src_suffix = '.whiskers'\n ),\n 'MeasureOld': Builder(action = \"measure.py $SOURCE $TARGET --face=$FACEHINT\",\n suffix = '.measurements',\n src_suffix = '.whiskers'\n ),\n 'MeasurementsAsMatlab': Builder(action = \"measure.py $SOURCE $TARGET\",\n suffix = '.mat',\n src_suffix = '.measurements'\n ),\n 'MeasurementsAsTrajectories': Builder(action = lambda source,target,env: 0 if MeasurementsTable(source[0].path).save_trajectories(target[0].path,excludes=[-1]) else 1,\n suffix = '.trajectories',\n src_suffix = '.measurements'),\n 'Classify': Builder(action = \"test_classify_1 $SOURCE $TARGET $FACEHINT -n $WHISKER_COUNT --px2mm $PX2MM --follicle $FOLLICLE_THRESH\",\n suffix = { '.measurements' : \"[autotraj].measurements\" },\n src_suffix = \".measurements\"\n ),\n 'ClassifyNoHairs': Builder(action = \"test_classify_3 $SOURCE $TARGET $FACEHINT -n $WHISKER_COUNT\",\n suffix = { '.measurements' : \"[autotraj].measurements\" },\n src_suffix = \".measurements\"\n ),\n 'Summary': Builder(action = \"summary.py $SOURCE $TARGET --px2mm=$PX2MM\",\n src_suffix = \".measurements\",\n suffix = \".png\"),\n 'SummaryPDF': Builder(action = \"summary.py $SOURCE $TARGET --px2mm=$PX2MM\",\n src_suffix = \".measurements\",\n suffix = \".pdf\"),\n 'GreyAreaSolver': Builder(action = \"test_traj_solve_gray_areas $SOURCE $TARGET\",\n src_suffix = \".measurements\",\n suffix = lit( \"[grey_v0].measurements\") ),\n 'HmmLRSolver': Builder(action = \"test_hmm_reclassify_1 -n $WHISKER_COUNT $SOURCE $TARGET\",\n src_suffix = \".measurements\",\n suffix = lit( \"[hmm-lr].measurements\")),\n 'HmmLRDelSolver': Builder(action = \"test_hmm_reclassify_2 -n $WHISKER_COUNT $SOURCE $TARGET\",\n src_suffix = \".measurements\",\n suffix = lit( \"[hmm-lrdel].measurements\")),\n 'HmmLRTimeSolver': Builder(action = \"test_hmm_reclassify_3 -n $WHISKER_COUNT $SOURCE $TARGET\",\n src_suffix = \".measurements\",\n suffix = lit( \"[hmm-lr-time].measurements\")),\n 'HmmLRTimeWatershedSolver': Builder(action = \"test_hmm_reclassify_5 -n $WHISKER_COUNT $SOURCE $TARGET\",\n src_suffix = \".measurements\",\n suffix = lit( \"[hmm-watershed].measurements\")),\n 'HmmLRDelTimeSolver': Builder(action = \"test_hmm_reclassify_4 -n $WHISKER_COUNT $SOURCE $TARGET\",\n src_suffix = \".measurements\",\n suffix = lit( \"[hmm-lrdel-time].measurements\")),\n }\n)\n\n#env.Decider('timestamp-newer')\nenv.AppendENVPath('PATH', os.getcwd())\nenv['WHISKER_COUNT'] = -1 # a count <1 tries to measure the count for each movie\n # a count >= 1 will identify that many whiskers in each movie\nenv['FOLLICLE_THRESH'] = 0 # all the follicle positions fall on one side of this line\n # whether the line lies in `x` or `y` depends on the\n # face orientation which is infered\n\nenv.AddMethod( pipeline_production, \"Pipeline\" )\nenv.AddMethod( pipeline_curated, \"CuratedPipeline\" )\nenv.AddMethod( pipeline_oconnor, \"OConnorPipeline\" )\n\nExport('env')\n\nif __name__=='__main__':\n import doctest\n doctest.testmod()\n"
] |
[
[
"scipy.integrate.quad"
],
[
"matplotlib.use"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
viniciusarruda/SHOT
|
[
"46e122026805833df36b40d68fe8d815f8d614af"
] |
[
"experiments/digit/unsupervised_digit_inspect.py"
] |
[
"import argparse\nimport os, sys\nimport os.path as osp\nimport torchvision\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision import transforms\nimport network, loss\nfrom torch.utils.data import DataLoader\nimport random, pdb, math, copy\nfrom tqdm import tqdm\nfrom scipy.spatial.distance import cdist\nimport pickle\nfrom data_load import mnist, svhn, usps\n\n# inverse_transform = None\n\n# class InverseTransform(torchvision.transforms.Normalize):\n# \"\"\"\n# Undoes the normalization and returns the reconstructed images in the input domain.\n# \"\"\"\n\n# def __init__(self, mean, std):\n# mean = torch.as_tensor(mean)\n# std = torch.as_tensor(std)\n# std_inv = 1 / (std + 1e-7)\n# mean_inv = -mean * std_inv\n# super().__init__(mean=mean_inv, std=std_inv)\n\n# def __call__(self, tensor):\n# t = super().__call__(tensor.clone())\n# # return transforms.ToPILImage()(t)\n# return t\n\n\ndef digit_load(args): \n global inverse_transform\n train_bs = args.batch_size\n if args.dset == 's':\n test_source = svhn.SVHN('./data/svhn/', split='test', download=True,\n transform=transforms.Compose([\n transforms.Resize(32),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ])) \n # assert inverse_transform == None\n # inverse_transform = InverseTransform((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n elif args.dset == 'u':\n test_source = usps.USPS('./data/usps/', train=False, download=True,\n transform=transforms.Compose([\n transforms.RandomCrop(28, padding=4),\n transforms.RandomRotation(10),\n transforms.ToTensor(),\n transforms.Normalize((0.5,), (0.5,))\n ])) \n # assert inverse_transform == None\n # inverse_transform = InverseTransform((0.5,), (0.5,))\n elif args.dset == 'm':\n test_source = mnist.MNIST('./data/mnist/', train=False, download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.5,), (0.5,))\n ]))\n # assert inverse_transform == None\n # inverse_transform = InverseTransform((0.5,), (0.5,))\n\n dset_loaders = {}\n dset_loaders[\"test\"] = DataLoader(test_source, batch_size=train_bs*2, shuffle=False, \n num_workers=args.worker, drop_last=False)\n \n return dset_loaders\n\ndef cal_acc(loader, netF, netB, netC):\n k = 0\n start_test = True\n with torch.no_grad():\n iter_test = iter(loader)\n for i in range(len(loader)):\n data = iter_test.next()\n input_images = []\n inputs = data[0]\n inputs_clone = inputs.clone()\n for j in range(inputs_clone.size(0)):\n x = transforms.Normalize((-1,), (2,))(inputs_clone[j])\n input_images.append(transforms.ToPILImage()(x))\n labels = data[1]\n outputs = netC(netB(netF(inputs)))\n #\n _, predict = torch.max(outputs.float().cpu(), 1)\n for j in range(inputs.size(0)):\n folder = args.output_dir + '/inspect/label-{}'.format(labels[j])\n if not osp.exists(folder):\n os.makedirs(folder)\n subfolder = folder + '/pred-{}'.format(predict[j])\n if not osp.exists(subfolder):\n os.makedirs(subfolder)\n input_images[j].save(subfolder + '/{}.jpg'.format(k))\n k += 1\n #\n if start_test:\n all_output = outputs.float().cpu()\n all_label = labels.float()\n start_test = False\n else:\n all_output = torch.cat((all_output, outputs.float().cpu()), 0)\n all_label = torch.cat((all_label, labels.float()), 0)\n _, predict = torch.max(all_output, 1)\n accuracy = torch.sum(torch.squeeze(predict).float() == all_label).item() / float(all_label.size()[0])\n mean_ent = torch.mean(loss.Entropy(nn.Softmax(dim=1)(all_output))).cpu().data.item()\n return accuracy*100, mean_ent\n\ndef test(args):\n dset_loaders = digit_load(args)\n ## set base network\n if args.dset == 'u':\n netF = network.LeNetBase()#.cuda()\n elif args.dset == 'm':\n netF = network.LeNetBase()#.cuda() \n elif args.dset == 's':\n netF = network.DTNBase()#.cuda()\n\n netB = network.feat_bootleneck(type=args.classifier, feature_dim=netF.in_features, bottleneck_dim=args.bottleneck)#.cuda()\n netC = network.feat_classifier(type=args.layer, class_num = args.class_num, bottleneck_dim=args.bottleneck)#.cuda()\n\n args.modelpath = args.output_dir + '/F.pt' \n netF.load_state_dict(torch.load(args.modelpath))\n args.modelpath = args.output_dir + '/B.pt' \n netB.load_state_dict(torch.load(args.modelpath))\n args.modelpath = args.output_dir + '/C.pt' \n netC.load_state_dict(torch.load(args.modelpath))\n netF.eval()\n netB.eval()\n netC.eval()\n\n acc, _ = cal_acc(dset_loaders['test'], netF, netB, netC)\n log_str = 'Task: {}, Accuracy = {:.2f}%'.format(args.dset, acc)\n try: \n args.out_file.write(log_str + '\\n')\n args.out_file.flush()\n except:\n pass\n print(log_str+'\\n')\n\ndef print_args(args):\n s = \"==========================================\\n\"\n for arg, content in args.__dict__.items():\n s += \"{}:{}\\n\".format(arg, content)\n return s\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='SHOT')\n parser.add_argument('--gpu_id', type=str, nargs='?', default='0', help=\"device id to run\")\n parser.add_argument('--s', type=int, default=0, help=\"source\")\n parser.add_argument('--t', type=int, default=1, help=\"target\")\n parser.add_argument('--max_epoch', type=int, default=30, help=\"maximum epoch\")\n parser.add_argument('--batch_size', type=int, default=64, help=\"batch_size\")\n parser.add_argument('--worker', type=int, default=4, help=\"number of workers\")\n parser.add_argument('--dset', type=str, default='s', choices=['u', 'm','s'])\n parser.add_argument('--lr', type=float, default=0.01, help=\"learning rate\")\n parser.add_argument('--seed', type=int, default=2020, help=\"random seed\")\n parser.add_argument('--bottleneck', type=int, default=256)\n parser.add_argument('--layer', type=str, default=\"wn\", choices=[\"linear\", \"wn\"])\n parser.add_argument('--classifier', type=str, default=\"bn\", choices=[\"ori\", \"bn\"])\n parser.add_argument('--output', type=str, default='')\n parser.add_argument('--issave', type=bool, default=True)\n args = parser.parse_args()\n args.class_num = 10\n\n # os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu_id\n SEED = args.seed\n torch.manual_seed(SEED)\n # torch.cuda.manual_seed(SEED)\n np.random.seed(SEED)\n random.seed(SEED)\n # torch.backends.cudnn.deterministic = True\n\n args.output_dir = osp.join(args.output, 'seed' + str(args.seed), args.dset)\n\n test(args)\n\n# python unsupervised_digit.py --dset m --gpu_id 0 --output ckps_unsupervised_digit\n# python unsupervised_digit.py --dset m --gpu_id 0 --ent --output ckps_unsupervised_digit_ent\n# python unsupervised_digit.py --dset m --gpu_id 0 --gent --output ckps_unsupervised_digit_gent\n# python unsupervised_digit.py --dset m --gpu_id 0 --ent --gent --output ckps_unsupervised_digit_ent_gent\n\n# na verdade n sem como saber qual classe vai sair .. ideal é ver tsne? ou mostrar as classificacoes primeiro?\n# show classification + gradcam (versao mais rapida)"
] |
[
[
"torch.nn.Softmax",
"torch.max",
"numpy.random.seed",
"torch.load",
"torch.manual_seed",
"torch.utils.data.DataLoader",
"torch.no_grad",
"torch.squeeze"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
einarf/ModernGL
|
[
"e4a7f53289043a0ac06130c67edc75b878484a0e"
] |
[
"examples/crate.py"
] |
[
"import os\n\nimport moderngl\nimport numpy as np\nfrom objloader import Obj\nfrom PIL import Image\nfrom pyrr import Matrix44\n\nimport data\nfrom window import Example, run_example\n\n\nclass CrateExample(Example):\n title = \"Crate\"\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n self.prog = self.ctx.program(\n vertex_shader='''\n #version 330\n\n uniform mat4 Mvp;\n\n in vec3 in_vert;\n in vec3 in_norm;\n in vec2 in_text;\n\n out vec3 v_vert;\n out vec3 v_norm;\n out vec2 v_text;\n\n void main() {\n gl_Position = Mvp * vec4(in_vert, 1.0);\n v_vert = in_vert;\n v_norm = in_norm;\n v_text = in_text;\n }\n ''',\n fragment_shader='''\n #version 330\n\n uniform vec3 Light;\n uniform sampler2D Texture;\n\n in vec3 v_vert;\n in vec3 v_norm;\n in vec2 v_text;\n\n out vec4 f_color;\n\n void main() {\n float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2;\n f_color = vec4(texture(Texture, v_text).rgb * lum, 1.0);\n }\n ''',\n )\n\n self.mvp = self.prog['Mvp']\n self.light = self.prog['Light']\n\n obj = Obj.open(data.find('crate.obj'))\n img = Image.open(data.find('crate.png')).transpose(Image.FLIP_TOP_BOTTOM).convert('RGB')\n self.texture = self.ctx.texture(img.size, 3, img.tobytes())\n self.texture.use()\n\n self.vbo = self.ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty'))\n self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo, 'in_vert', 'in_norm', 'in_text')\n\n def render(self, time, frame_time):\n angle = time\n self.ctx.clear(1.0, 1.0, 1.0)\n self.ctx.enable(moderngl.DEPTH_TEST)\n\n camera_pos = (np.cos(angle) * 5.0, np.sin(angle) * 5.0, 2.0)\n\n proj = Matrix44.perspective_projection(45.0, self.aspect_ratio, 0.1, 1000.0)\n lookat = Matrix44.look_at(\n camera_pos,\n (0.0, 0.0, 0.5),\n (0.0, 0.0, 1.0),\n )\n\n self.mvp.write((proj * lookat).astype('f4').tobytes())\n self.light.value = camera_pos\n self.vao.render()\n\n\nif __name__ == '__main__':\n run_example(CrateExample)\n"
] |
[
[
"numpy.cos",
"numpy.sin"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
treggit/pycryptobot
|
[
"47ed7f260d19fd1ec7e607e0654ebb768a3f035c"
] |
[
"pycryptobot.py"
] |
[
"\"\"\"Python Crypto Bot consuming Coinbase Pro or Binance APIs\"\"\"\n\nimport functools\nimport os\nimport sched\nimport sys\nimport time\nimport pandas as pd\nfrom datetime import datetime\nfrom models.PyCryptoBot import PyCryptoBot, truncate as _truncate\nfrom models.AppState import AppState\nfrom models.Trading import TechnicalAnalysis\nfrom models.TradingAccount import TradingAccount\nfrom models.helper.MarginHelper import calculate_margin\nfrom views.TradingGraphs import TradingGraphs\nfrom models.Strategy import Strategy\nfrom models.helper.LogHelper import Logger\n\n# minimal traceback\nsys.tracebacklimit = 1\n\napp = PyCryptoBot()\naccount = TradingAccount(app)\ntechnical_analysis = None\nstate = AppState(app, account)\nstate.initLastAction()\n\ns = sched.scheduler(time.time, time.sleep)\n\ndef executeJob(sc=None, app: PyCryptoBot=None, state: AppState=None, trading_data=pd.DataFrame()):\n \"\"\"Trading bot job which runs at a scheduled interval\"\"\"\n\n global technical_analysis\n\n # connectivity check (only when running live)\n if app.isLive() and app.getTime() is None:\n Logger.warning('Your connection to the exchange has gone down, will retry in 1 minute!')\n\n # poll every 5 minute\n list(map(s.cancel, s.queue))\n s.enter(300, 1, executeJob, (sc, app, state))\n return\n\n # increment state.iterations\n state.iterations = state.iterations + 1\n\n if not app.isSimulation():\n # retrieve the app.getMarket() data\n trading_data = app.getHistoricalData(app.getMarket(), app.getGranularity())\n else:\n if len(trading_data) == 0:\n return None\n\n # analyse the market data\n if app.isSimulation() and len(trading_data.columns) > 8:\n df = trading_data\n else:\n trading_dataCopy = trading_data.copy()\n technical_analysis = TechnicalAnalysis(trading_dataCopy)\n technical_analysis.addAll()\n df = technical_analysis.getDataFrame()\n\n if app.isSimulation():\n df_last = app.getInterval(df, state.iterations)\n else:\n df_last = app.getInterval(df)\n\n if len(df_last.index.format()) > 0:\n current_df_index = str(df_last.index.format()[0])\n else:\n current_df_index = state.last_df_index\n\n formatted_current_df_index = f'{current_df_index} 00:00:00' if len(current_df_index) == 10 else current_df_index\n\n if app.getSmartSwitch() == 1 and app.getGranularity() == 3600 and app.is1hEMA1226Bull() is True and app.is6hEMA1226Bull() is True:\n Logger.info('*** smart switch from granularity 3600 (1 hour) to 900 (15 min) ***')\n\n app.notifyTelegram(app.getMarket() + \" smart switch from granularity 3600 (1 hour) to 900 (15 min)\")\n\n app.setGranularity(900)\n list(map(s.cancel, s.queue))\n s.enter(5, 1, executeJob, (sc, app, state))\n\n if app.getSmartSwitch() == 1 and app.getGranularity() == 900 and app.is1hEMA1226Bull() is False and app.is6hEMA1226Bull() is False:\n Logger.info(\"*** smart switch from granularity 900 (15 min) to 3600 (1 hour) ***\")\n\n app.notifyTelegram(app.getMarket() + \" smart switch from granularity 900 (15 min) to 3600 (1 hour)\")\n\n app.setGranularity(3600)\n list(map(s.cancel, s.queue))\n s.enter(5, 1, executeJob, (sc, app, state))\n\n if app.getExchange() == 'binance' and app.getGranularity() == 86400:\n if len(df) < 250:\n # data frame should have 250 rows, if not retry\n Logger.error('error: data frame length is < 250 (' + str(len(df)) + ')')\n list(map(s.cancel, s.queue))\n s.enter(300, 1, executeJob, (sc, app, state))\n else:\n if len(df) < 300:\n if not app.isSimulation():\n # data frame should have 300 rows, if not retry\n Logger.error('error: data frame length is < 300 (' + str(len(df)) + ')')\n list(map(s.cancel, s.queue))\n s.enter(300, 1, executeJob, (sc, app, state))\n\n if len(df_last) > 0:\n now = datetime.today().strftime('%Y-%m-%d %H:%M:%S')\n\n if not app.isSimulation():\n ticker = app.getTicker(app.getMarket())\n now = ticker[0]\n price = ticker[1]\n if price < df_last['low'].values[0] or price == 0:\n price = float(df_last['close'].values[0])\n else:\n price = float(df_last['close'].values[0])\n\n if price < 0.0001:\n raise Exception(app.getMarket() + ' is unsuitable for trading, quote price is less than 0.0001!')\n\n # technical indicators\n ema12gtema26 = bool(df_last['ema12gtema26'].values[0])\n ema12gtema26co = bool(df_last['ema12gtema26co'].values[0])\n goldencross = bool(df_last['goldencross'].values[0])\n macdgtsignal = bool(df_last['macdgtsignal'].values[0])\n macdgtsignalco = bool(df_last['macdgtsignalco'].values[0])\n ema12ltema26 = bool(df_last['ema12ltema26'].values[0])\n ema12ltema26co = bool(df_last['ema12ltema26co'].values[0])\n macdltsignal = bool(df_last['macdltsignal'].values[0])\n macdltsignalco = bool(df_last['macdltsignalco'].values[0])\n obv = float(df_last['obv'].values[0])\n obv_pc = float(df_last['obv_pc'].values[0])\n elder_ray_buy = bool(df_last['eri_buy'].values[0])\n elder_ray_sell = bool(df_last['eri_sell'].values[0])\n\n # if simulation interations < 200 set goldencross to true\n if app.isSimulation() and state.iterations < 200:\n goldencross = True\n\n # candlestick detection\n hammer = bool(df_last['hammer'].values[0])\n inverted_hammer = bool(df_last['inverted_hammer'].values[0])\n hanging_man = bool(df_last['hanging_man'].values[0])\n shooting_star = bool(df_last['shooting_star'].values[0])\n three_white_soldiers = bool(df_last['three_white_soldiers'].values[0])\n three_black_crows = bool(df_last['three_black_crows'].values[0])\n morning_star = bool(df_last['morning_star'].values[0])\n evening_star = bool(df_last['evening_star'].values[0])\n three_line_strike = bool(df_last['three_line_strike'].values[0])\n abandoned_baby = bool(df_last['abandoned_baby'].values[0])\n morning_doji_star = bool(df_last['morning_doji_star'].values[0])\n evening_doji_star = bool(df_last['evening_doji_star'].values[0])\n two_black_gapping = bool(df_last['two_black_gapping'].values[0])\n\n strategy = Strategy(app, state, df, state.iterations)\n state.action = strategy.getAction()\n\n immediate_action = False\n margin, profit, sell_fee = 0, 0, 0\n\n if state.last_buy_size > 0 and state.last_buy_price > 0 and price > 0 and state.last_action == 'BUY':\n # update last buy high\n if price > state.last_buy_high:\n state.last_buy_high = price\n\n if state.last_buy_high > 0:\n change_pcnt_high = ((price / state.last_buy_high) - 1) * 100\n else:\n change_pcnt_high = 0\n\n # buy and sell calculations\n state.last_buy_fee = round(state.last_buy_size * app.getTakerFee(), 8)\n state.last_buy_filled = round(((state.last_buy_size - state.last_buy_fee) / state.last_buy_price), 8)\n\n # if not a simulation, sync with exchange orders\n if not app.isSimulation():\n exchange_last_buy = app.getLastBuy()\n if exchange_last_buy is not None:\n if state.last_buy_size != exchange_last_buy['size']:\n state.last_buy_size = exchange_last_buy['size']\n if state.last_buy_filled != exchange_last_buy['filled']:\n state.last_buy_filled = exchange_last_buy['filled']\n if state.last_buy_price != exchange_last_buy['price']:\n state.last_buy_price = exchange_last_buy['price']\n\n if app.getExchange() == 'coinbasepro':\n if state.last_buy_fee != exchange_last_buy['fee']:\n state.last_buy_fee = exchange_last_buy['fee']\n\n margin, profit, sell_fee = calculate_margin(\n buy_size=state.last_buy_size,\n buy_filled=state.last_buy_filled,\n buy_price=state.last_buy_price,\n buy_fee=state.last_buy_fee,\n sell_percent=app.getSellPercent(),\n sell_price=price,\n sell_taker_fee=app.getTakerFee())\n\n # handle immedate sell actions\n if strategy.isSellTrigger(price, technical_analysis.getTradeExit(price), margin, change_pcnt_high, obv_pc, macdltsignal):\n state.action = 'SELL'\n state.last_action = 'BUY'\n immediate_action = True\n\n # handle overriding wait actions (do not sell if sell at loss disabled!)\n if strategy.isWaitTrigger(margin):\n state.action = 'WAIT'\n state.last_action = 'BUY'\n immediate_action = False\n\n bullbeartext = ''\n if app.disableBullOnly() is True or (df_last['sma50'].values[0] == df_last['sma200'].values[0]):\n bullbeartext = ''\n elif goldencross is True:\n bullbeartext = ' (BULL)'\n elif goldencross is False:\n bullbeartext = ' (BEAR)'\n\n # polling is every 5 minutes (even for hourly intervals), but only process once per interval\n if (immediate_action is True or state.last_df_index != current_df_index):\n precision = 4\n\n if (price < 0.01):\n precision = 8\n\n # Since precision does not change after this point, it is safe to prepare a tailored `truncate()` that would\n # work with this precision. It should save a couple of `precision` uses, one for each `truncate()` call.\n truncate = functools.partial(_truncate, n=precision)\n\n price_text = 'Close: ' + truncate(price)\n ema_text = app.compare(df_last['ema12'].values[0], df_last['ema26'].values[0], 'EMA12/26', precision)\n\n macd_text = ''\n if app.disableBuyMACD() is False:\n macd_text = app.compare(df_last['macd'].values[0], df_last['signal'].values[0], 'MACD', precision)\n\n obv_text = ''\n if app.disableBuyOBV() is False:\n obv_text = 'OBV: ' + truncate(df_last['obv'].values[0]) + ' (' + str(\n truncate(df_last['obv_pc'].values[0])) + '%)'\n\n state.eri_text = ''\n if app.disableBuyElderRay() is False:\n if elder_ray_buy is True:\n state.eri_text = 'ERI: buy | '\n elif elder_ray_sell is True:\n state.eri_text = 'ERI: sell | '\n else:\n state.eri_text = 'ERI: | '\n\n if hammer is True:\n log_text = '* Candlestick Detected: Hammer (\"Weak - Reversal - Bullish Signal - Up\")'\n Logger.info(log_text)\n\n if shooting_star is True:\n log_text = '* Candlestick Detected: Shooting Star (\"Weak - Reversal - Bearish Pattern - Down\")'\n Logger.info(log_text)\n\n if hanging_man is True:\n log_text = '* Candlestick Detected: Hanging Man (\"Weak - Continuation - Bearish Pattern - Down\")'\n Logger.info(log_text)\n\n if inverted_hammer is True:\n log_text = '* Candlestick Detected: Inverted Hammer (\"Weak - Continuation - Bullish Pattern - Up\")'\n Logger.info(log_text)\n\n if three_white_soldiers is True:\n log_text = '*** Candlestick Detected: Three White Soldiers (\"Strong - Reversal - Bullish Pattern - Up\")'\n Logger.info(log_text)\n\n app.notifyTelegram(app.getMarket() + ' (' + app.printGranularity() + ') ' + log_text)\n\n if three_black_crows is True:\n log_text = '* Candlestick Detected: Three Black Crows (\"Strong - Reversal - Bearish Pattern - Down\")'\n Logger.info(log_text)\n\n app.notifyTelegram(app.getMarket() + ' (' + app.printGranularity() + ') ' + log_text)\n\n if morning_star is True:\n log_text = '*** Candlestick Detected: Morning Star (\"Strong - Reversal - Bullish Pattern - Up\")'\n Logger.info(log_text)\n\n app.notifyTelegram(app.getMarket() + ' (' + app.printGranularity() + ') ' + log_text)\n\n if evening_star is True:\n log_text = '*** Candlestick Detected: Evening Star (\"Strong - Reversal - Bearish Pattern - Down\")'\n Logger.info(log_text)\n\n app.notifyTelegram(app.getMarket() + ' (' + app.printGranularity() + ') ' + log_text)\n\n if three_line_strike is True:\n log_text = '** Candlestick Detected: Three Line Strike (\"Reliable - Reversal - Bullish Pattern - Up\")'\n Logger.info(log_text)\n\n app.notifyTelegram(app.getMarket() + ' (' + app.printGranularity() + ') ' + log_text)\n\n if abandoned_baby is True:\n log_text = '** Candlestick Detected: Abandoned Baby (\"Reliable - Reversal - Bullish Pattern - Up\")'\n Logger.info(log_text)\n\n app.notifyTelegram(app.getMarket() + ' (' + app.printGranularity() + ') ' + log_text)\n\n if morning_doji_star is True:\n log_text = '** Candlestick Detected: Morning Doji Star (\"Reliable - Reversal - Bullish Pattern - Up\")'\n Logger.info(log_text)\n\n app.notifyTelegram(app.getMarket() + ' (' + app.printGranularity() + ') ' + log_text)\n\n if evening_doji_star is True:\n log_text = '** Candlestick Detected: Evening Doji Star (\"Reliable - Reversal - Bearish Pattern - Down\")'\n Logger.info(log_text)\n\n app.notifyTelegram(app.getMarket() + ' (' + app.printGranularity() + ') ' + log_text)\n\n if two_black_gapping is True:\n log_text = '*** Candlestick Detected: Two Black Gapping (\"Reliable - Reversal - Bearish Pattern - Down\")'\n Logger.info(log_text)\n\n app.notifyTelegram(app.getMarket() + ' (' + app.printGranularity() + ') ' + log_text)\n\n ema_co_prefix = ''\n ema_co_suffix = ''\n if ema12gtema26co is True:\n ema_co_prefix = '*^ '\n ema_co_suffix = ' ^*'\n elif ema12ltema26co is True:\n ema_co_prefix = '*v '\n ema_co_suffix = ' v*'\n elif ema12gtema26 is True:\n ema_co_prefix = '^ '\n ema_co_suffix = ' ^'\n elif ema12ltema26 is True:\n ema_co_prefix = 'v '\n ema_co_suffix = ' v'\n\n macd_co_prefix = ''\n macd_co_suffix = ''\n if app.disableBuyMACD() is False:\n if macdgtsignalco is True:\n macd_co_prefix = '*^ '\n macd_co_suffix = ' ^*'\n elif macdltsignalco is True:\n macd_co_prefix = '*v '\n macd_co_suffix = ' v*'\n elif macdgtsignal is True:\n macd_co_prefix = '^ '\n macd_co_suffix = ' ^'\n elif macdltsignal is True:\n macd_co_prefix = 'v '\n macd_co_suffix = ' v'\n\n obv_prefix = ''\n obv_suffix = ''\n if app.disableBuyOBV() is False:\n if float(obv_pc) > 0:\n obv_prefix = '^ '\n obv_suffix = ' ^ | '\n elif float(obv_pc) < 0:\n obv_prefix = 'v '\n obv_suffix = ' v | '\n\n if not app.isVerbose():\n if state.last_action != '':\n output_text = formatted_current_df_index + ' | ' + app.getMarket() + bullbeartext + ' | ' + \\\n app.printGranularity() + ' | ' + price_text + ' | ' + ema_co_prefix + \\\n ema_text + ema_co_suffix + ' | ' + macd_co_prefix + macd_text + macd_co_suffix + \\\n obv_prefix + obv_text + obv_suffix + state.eri_text + ' | ' + state.action + \\\n ' | Last Action: ' + state.last_action\n else:\n output_text = formatted_current_df_index + ' | ' + app.getMarket() + bullbeartext + ' | ' + \\\n app.printGranularity() + ' | ' + price_text + ' | ' + ema_co_prefix + \\\n ema_text + ema_co_suffix + ' | ' + macd_co_prefix + macd_text + macd_co_suffix + \\\n obv_prefix + obv_text + obv_suffix + state.eri_text + ' | ' + state.action + ' '\n\n if state.last_action == 'BUY':\n if state.last_buy_size > 0:\n margin_text = truncate(margin) + '%'\n else:\n margin_text = '0%'\n\n output_text += ' | ' + margin_text + ' (delta: ' + str(round(price - state.last_buy_price, precision)) + ')'\n\n Logger.info(output_text)\n\n # Seasonal Autoregressive Integrated Moving Average (ARIMA) model (ML prediction for 3 intervals from now)\n if not app.isSimulation():\n try:\n prediction = technical_analysis.seasonalARIMAModelPrediction(int(app.getGranularity() / 60) * 3) # 3 intervals from now\n Logger.info(f'Seasonal ARIMA model predicts the closing price will be {str(round(prediction[1], 2))} at {prediction[0]} (delta: {round(prediction[1] - price, 2)})')\n except:\n pass\n\n if state.last_action == 'BUY':\n # display support, resistance and fibonacci levels\n Logger.info(technical_analysis.printSupportResistanceFibonacciLevels(price))\n\n else:\n Logger.debug('-- Iteration: ' + str(state.iterations) + ' --' + bullbeartext)\n\n if state.last_action == 'BUY':\n if state.last_buy_size > 0:\n margin_text = truncate(margin) + '%'\n else:\n margin_text = '0%'\n\n Logger.debug('-- Margin: ' + margin_text + ' --')\n\n Logger.debug('price: ' + truncate(price))\n Logger.debug('ema12: ' + truncate(float(df_last['ema12'].values[0])))\n Logger.debug('ema26: ' + truncate(float(df_last['ema26'].values[0])))\n Logger.debug('ema12gtema26co: ' + str(ema12gtema26co))\n Logger.debug('ema12gtema26: ' + str(ema12gtema26))\n Logger.debug('ema12ltema26co: ' + str(ema12ltema26co))\n Logger.debug('ema12ltema26: ' + str(ema12ltema26))\n Logger.debug('sma50: ' + truncate(float(df_last['sma50'].values[0])))\n Logger.debug('sma200: ' + truncate(float(df_last['sma200'].values[0])))\n Logger.debug('macd: ' + truncate(float(df_last['macd'].values[0])))\n Logger.debug('signal: ' + truncate(float(df_last['signal'].values[0])))\n Logger.debug('macdgtsignal: ' + str(macdgtsignal))\n Logger.debug('macdltsignal: ' + str(macdltsignal))\n Logger.debug('obv: ' + str(obv))\n Logger.debug('obv_pc: ' + str(obv_pc))\n Logger.debug('action: ' + state.action)\n\n # informational output on the most recent entry \n Logger.info('')\n Logger.info('================================================================================')\n txt = ' Iteration : ' + str(state.iterations) + bullbeartext\n Logger.info(' | ' + txt + (' ' * (75 - len(txt))) + ' | ')\n txt = ' Timestamp : ' + str(df_last.index.format()[0])\n Logger.info(' | ' + txt + (' ' * (75 - len(txt))) + ' | ')\n Logger.info('--------------------------------------------------------------------------------')\n txt = ' Close : ' + truncate(price)\n Logger.info(' | ' + txt + (' ' * (75 - len(txt))) + ' | ')\n txt = ' EMA12 : ' + truncate(float(df_last['ema12'].values[0]))\n Logger.info(' | ' + txt + (' ' * (75 - len(txt))) + ' | ')\n txt = ' EMA26 : ' + truncate(float(df_last['ema26'].values[0]))\n Logger.info(' | ' + txt + (' ' * (75 - len(txt))) + ' | ')\n txt = ' Crossing Above : ' + str(ema12gtema26co)\n Logger.info(' | ' + txt + (' ' * (75 - len(txt))) + ' | ')\n txt = ' Currently Above : ' + str(ema12gtema26)\n Logger.info(' | ' + txt + (' ' * (75 - len(txt))) + ' | ')\n txt = ' Crossing Below : ' + str(ema12ltema26co)\n Logger.info(' | ' + txt + (' ' * (75 - len(txt))) + ' | ')\n txt = ' Currently Below : ' + str(ema12ltema26)\n Logger.info(' | ' + txt + (' ' * (75 - len(txt))) + ' | ')\n\n if (ema12gtema26 is True and ema12gtema26co is True):\n txt = ' Condition : EMA12 is currently crossing above EMA26'\n elif (ema12gtema26 is True and ema12gtema26co is False):\n txt = ' Condition : EMA12 is currently above EMA26 and has crossed over'\n elif (ema12ltema26 is True and ema12ltema26co is True):\n txt = ' Condition : EMA12 is currently crossing below EMA26'\n elif (ema12ltema26 is True and ema12ltema26co is False):\n txt = ' Condition : EMA12 is currently below EMA26 and has crossed over'\n else:\n txt = ' Condition : -'\n Logger.info(' | ' + txt + (' ' * (75 - len(txt))) + ' | ')\n\n txt = ' SMA20 : ' + truncate(float(df_last['sma20'].values[0]))\n Logger.info(' | ' + txt + (' ' * (75 - len(txt))) + ' | ')\n txt = ' SMA200 : ' + truncate(float(df_last['sma200'].values[0]))\n Logger.info(' | ' + txt + (' ' * (75 - len(txt))) + ' | ')\n\n Logger.info('--------------------------------------------------------------------------------')\n txt = ' MACD : ' + truncate(float(df_last['macd'].values[0]))\n Logger.info(' | ' + txt + (' ' * (75 - len(txt))) + ' | ')\n txt = ' Signal : ' + truncate(float(df_last['signal'].values[0]))\n Logger.info(' | ' + txt + (' ' * (75 - len(txt))) + ' | ')\n txt = ' Currently Above : ' + str(macdgtsignal)\n Logger.info(' | ' + txt + (' ' * (75 - len(txt))) + ' | ')\n txt = ' Currently Below : ' + str(macdltsignal)\n Logger.info(' | ' + txt + (' ' * (75 - len(txt))) + ' | ')\n\n if (macdgtsignal is True and macdgtsignalco is True):\n txt = ' Condition : MACD is currently crossing above Signal'\n elif (macdgtsignal is True and macdgtsignalco is False):\n txt = ' Condition : MACD is currently above Signal and has crossed over'\n elif (macdltsignal is True and macdltsignalco is True):\n txt = ' Condition : MACD is currently crossing below Signal'\n elif (macdltsignal is True and macdltsignalco is False):\n txt = ' Condition : MACD is currently below Signal and has crossed over'\n else:\n txt = ' Condition : -'\n Logger.info(' | ' + txt + (' ' * (75 - len(txt))) + ' | ')\n\n Logger.info('--------------------------------------------------------------------------------')\n txt = ' Action : ' + state.action\n Logger.info(' | ' + txt + (' ' * (75 - len(txt))) + ' | ')\n Logger.info('================================================================================')\n if state.last_action == 'BUY':\n txt = ' Margin : ' + margin_text\n Logger.info(' | ' + txt + (' ' * (75 - len(txt))) + ' | ')\n Logger.info('================================================================================')\n\n # if a buy signal\n if state.action == 'BUY':\n state.last_buy_price = price\n state.last_buy_high = state.last_buy_price\n\n # if live\n if app.isLive():\n app.notifyTelegram(app.getMarket() + ' (' + app.printGranularity() + ') BUY at ' + price_text)\n\n if not app.isVerbose():\n Logger.info(formatted_current_df_index + ' | ' + app.getMarket() + ' | ' + app.printGranularity() + ' | ' + price_text + ' | BUY')\n else:\n Logger.info('--------------------------------------------------------------------------------')\n Logger.info('| *** Executing LIVE Buy Order *** |')\n Logger.info('--------------------------------------------------------------------------------')\n\n # display balances\n Logger.info(app.getBaseCurrency() + ' balance before order: ' + str(account.getBalance(app.getBaseCurrency())))\n Logger.info(app.getQuoteCurrency() + ' balance before order: ' + str(account.getBalance(app.getQuoteCurrency())))\n\n # execute a live market buy\n state.last_buy_size = float(account.getBalance(app.getQuoteCurrency()))\n if app.getBuyMaxSize() and state.last_buy_size > app.getBuyMaxSize():\n state.last_buy_size = app.getBuyMaxSize()\n\n resp = app.marketBuy(app.getMarket(), state.last_buy_size, app.getBuyPercent())\n Logger.debug(resp)\n\n # display balances\n Logger.info(app.getBaseCurrency() + ' balance after order: ' + str(account.getBalance(app.getBaseCurrency())))\n Logger.info(app.getQuoteCurrency() + ' balance after order: ' + str(account.getBalance(app.getQuoteCurrency())))\n # if not live\n else:\n app.notifyTelegram(app.getMarket() + ' (' + app.printGranularity() + ') TEST BUY at ' + price_text)\n # TODO: Improve simulator calculations by including calculations for buy and sell limit configurations. \n if state.last_buy_size == 0 and state.last_buy_filled == 0: \n state.last_buy_size = 1000\n state.first_buy_size = 1000\n\n state.buy_count = state.buy_count + 1\n state.buy_sum = state.buy_sum + state.last_buy_size \n\n if not app.isVerbose():\n Logger.info(formatted_current_df_index + ' | ' + app.getMarket() + ' | ' + app.printGranularity() + ' | ' + price_text + ' | BUY')\n\n bands = technical_analysis.getFibonacciRetracementLevels(float(price))\n Logger.info(' Fibonacci Retracement Levels:' + str(bands))\n technical_analysis.printSupportResistanceLevel(float(price))\n\n if len(bands) >= 1 and len(bands) <= 2:\n if len(bands) == 1:\n first_key = list(bands.keys())[0]\n if first_key == 'ratio1':\n state.fib_low = 0\n state.fib_high = bands[first_key]\n if first_key == 'ratio1_618':\n state.fib_low = bands[first_key]\n state.fib_high = bands[first_key] * 2\n else:\n state.fib_low = bands[first_key]\n\n elif len(bands) == 2:\n first_key = list(bands.keys())[0]\n second_key = list(bands.keys())[1]\n state.fib_low = bands[first_key]\n state.fib_high = bands[second_key]\n\n else:\n Logger.info('--------------------------------------------------------------------------------')\n Logger.info('| *** Executing TEST Buy Order *** |')\n Logger.info('--------------------------------------------------------------------------------')\n\n if app.shouldSaveGraphs():\n tradinggraphs = TradingGraphs(technical_analysis)\n ts = datetime.now().timestamp()\n filename = app.getMarket() + '_' + app.printGranularity() + '_buy_' + str(ts) + '.png'\n tradinggraphs.renderEMAandMACD(len(trading_data), 'graphs/' + filename, True)\n\n # if a sell signal\n elif state.action == 'SELL':\n # if live\n if app.isLive():\n app.notifyTelegram(app.getMarket() + ' (' + app.printGranularity() + ') SELL at ' +\n price_text + ' (margin: ' + margin_text + ', (delta: ' +\n str(round(price - state.last_buy_price, precision)) + ')')\n\n if not app.isVerbose():\n Logger.info(formatted_current_df_index + ' | ' + app.getMarket() + ' | ' + app.printGranularity() + ' | ' + price_text + ' | SELL')\n\n bands = technical_analysis.getFibonacciRetracementLevels(float(price))\n Logger.info(' Fibonacci Retracement Levels:' + str(bands))\n\n if len(bands) >= 1 and len(bands) <= 2:\n if len(bands) == 1:\n first_key = list(bands.keys())[0]\n if first_key == 'ratio1':\n state.fib_low = 0\n state.fib_high = bands[first_key]\n if first_key == 'ratio1_618':\n state.fib_low = bands[first_key]\n state.fib_high = bands[first_key] * 2\n else:\n state.fib_low = bands[first_key]\n\n elif len(bands) == 2:\n first_key = list(bands.keys())[0]\n second_key = list(bands.keys())[1]\n state.fib_low = bands[first_key]\n state.fib_high = bands[second_key]\n\n else:\n Logger.info('--------------------------------------------------------------------------------')\n Logger.info('| *** Executing LIVE Sell Order *** |')\n Logger.info('--------------------------------------------------------------------------------')\n\n # display balances\n Logger.info(app.getBaseCurrency() + ' balance before order: ' + str(account.getBalance(app.getBaseCurrency())))\n Logger.info(app.getQuoteCurrency() + ' balance before order: ' + str(account.getBalance(app.getQuoteCurrency())))\n\n # execute a live market sell\n resp = app.marketSell(app.getMarket(), float(account.getBalance(app.getBaseCurrency())),\n app.getSellPercent())\n Logger.debug(resp)\n\n # display balances\n Logger.info(app.getBaseCurrency() + ' balance after order: ' + str(account.getBalance(app.getBaseCurrency())))\n Logger.info(app.getQuoteCurrency() + ' balance after order: ' + str(account.getBalance(app.getQuoteCurrency())))\n\n # if not live\n else:\n margin, profit, sell_fee = calculate_margin(\n buy_size=state.last_buy_size, \n buy_filled=state.last_buy_filled, \n buy_price=state.last_buy_price, \n buy_fee=state.last_buy_fee, \n sell_percent=app.getSellPercent(), \n sell_price=price, \n sell_taker_fee=app.getTakerFee())\n\n if state.last_buy_size > 0:\n margin_text = truncate(margin) + '%'\n else:\n margin_text = '0%'\n app.notifyTelegram(app.getMarket() + ' (' + app.printGranularity() + ') TEST SELL at ' +\n price_text + ' (margin: ' + margin_text + ', (delta: ' +\n str(round(price - state.last_buy_price, precision)) + ')')\n\n # Preserve next buy values for simulator\n state.sell_count = state.sell_count + 1\n buy_size = ((app.getSellPercent() / 100) * ((price / state.last_buy_price) * (state.last_buy_size - state.last_buy_fee)))\n state.last_buy_size = buy_size - sell_fee\n state.sell_sum = state.sell_sum + state.last_buy_size\n\n if not app.isVerbose():\n if price > 0:\n margin_text = truncate(margin) + '%'\n else:\n margin_text = '0%'\n\n Logger.info(formatted_current_df_index + ' | ' + app.getMarket() + ' | ' +\n app.printGranularity() + ' | SELL | ' + str(price) + ' | BUY | ' +\n str(state.last_buy_price) + ' | DIFF | ' + str(price - state.last_buy_price) +\n ' | DIFF | ' + str(profit) + ' | MARGIN NO FEES | ' +\n margin_text + ' | MARGIN FEES | ' + str(round(sell_fee, precision)))\n\n else:\n Logger.info('--------------------------------------------------------------------------------')\n Logger.info('| *** Executing TEST Sell Order *** |')\n Logger.info('--------------------------------------------------------------------------------')\n\n if app.shouldSaveGraphs():\n tradinggraphs = TradingGraphs(technical_analysis)\n ts = datetime.now().timestamp()\n filename = app.getMarket() + '_' + app.printGranularity() + '_sell_' + str(ts) + '.png'\n tradinggraphs.renderEMAandMACD(len(trading_data), 'graphs/' + filename, True)\n\n # last significant action\n if state.action in ['BUY', 'SELL']:\n state.last_action = state.action\n\n state.last_df_index = str(df_last.index.format()[0])\n\n if not app.isLive() and state.iterations == len(df):\n Logger.info(\"\\nSimulation Summary: \")\n\n if state.buy_count > state.sell_count and app.allowSellAtLoss():\n # Calculate last sell size\n state.last_buy_size = ((app.getSellPercent() / 100) * ((price / state.last_buy_price) * (state.last_buy_size - state.last_buy_fee)))\n # Reduce sell fee from last sell size\n state.last_buy_size = state.last_buy_size - state.last_buy_price * app.getTakerFee()\n state.sell_sum = state.sell_sum + state.last_buy_size\n state.sell_count = state.sell_count + 1\n\n elif state.buy_count > state.sell_count and not app.allowSellAtLoss():\n Logger.info(\"\\n\")\n Logger.info(' Note : \"sell at loss\" is disabled and you have an open trade, if the margin')\n Logger.info(' result below is negative it will assume you sold at the end of the')\n Logger.info(' simulation which may not be ideal. Try setting --sellatloss 1')\n\n Logger.info(\"\\n\")\n Logger.info(' Buy Count : ' + str(state.buy_count)) \n Logger.info(' Sell Count : ' + str(state.sell_count))\n Logger.info(' First Buy : ' + str(state.first_buy_size))\n Logger.info(' Last Sell : ' + str(state.last_buy_size))\n\n app.notifyTelegram(f\"Simulation Summary\\n Buy Count: {state.buy_count}\\n Sell Count: {state.sell_count}\\n First Buy: {state.first_buy_size}\\n Last Sell: {state.last_buy_size}\\n\")\n\n if state.sell_count > 0:\n Logger.info(\"\\n\")\n Logger.info(' Margin : ' + _truncate((((state.last_buy_size - state.first_buy_size) / state.first_buy_size) * 100), 4) + '%')\n Logger.info(\"\\n\")\n Logger.info(' ** non-live simulation, assuming highest fees')\n app.notifyTelegram(f\" Margin: {_truncate((((state.last_buy_size - state.first_buy_size) / state.first_buy_size) * 100), 4)}%\\n ** non-live simulation, assuming highest fees\\n\")\n\n\n else:\n if state.last_buy_size > 0 and state.last_buy_price > 0 and price > 0 and state.last_action == 'BUY':\n # show profit and margin if already bought\n Logger.info(now + ' | ' + app.getMarket() + bullbeartext + ' | ' + app.printGranularity() + ' | Current Price: ' + str(price) + ' | Margin: ' + str(margin) + ' | Profit: ' + str(profit))\n else:\n Logger.info(now + ' | ' + app.getMarket() + bullbeartext + ' | ' + app.printGranularity() + ' | Current Price: ' + str(price))\n\n # decrement ignored iteration\n state.iterations = state.iterations - 1\n\n # if live\n if not app.disableTracker() and app.isLive():\n # update order tracker csv\n if app.getExchange() == 'binance':\n account.saveTrackerCSV(app.getMarket())\n elif app.getExchange() == 'coinbasepro':\n account.saveTrackerCSV()\n\n if app.isSimulation():\n if state.iterations < 300:\n if app.simuluationSpeed() in ['fast', 'fast-sample']:\n # fast processing\n list(map(s.cancel, s.queue))\n s.enter(0, 1, executeJob, (sc, app, state, df))\n else:\n # slow processing\n list(map(s.cancel, s.queue))\n s.enter(1, 1, executeJob, (sc, app, state, df))\n\n else:\n # poll every 1 minute\n list(map(s.cancel, s.queue))\n s.enter(60, 1, executeJob, (sc, app, state))\n\n\ndef main():\n try:\n\n message = 'Starting '\n if app.getExchange() == 'coinbasepro':\n message += 'Coinbase Pro bot'\n elif app.getExchange() == 'binance':\n message += 'Binance bot'\n\n message += ' for ' + app.getMarket() + ' using granularity ' + app.printGranularity()\n app.notifyTelegram(message)\n\n # initialise and start application\n trading_data = app.startApp(account, state.last_action)\n\n def runApp():\n # run the first job immediately after starting\n if app.isSimulation():\n executeJob(s, app, state, trading_data)\n else:\n executeJob(s, app, state)\n\n s.run()\n\n try:\n runApp()\n except KeyboardInterrupt:\n raise\n except(BaseException, Exception) as e:\n if app.autoRestart():\n # Wait 30 second and try to relaunch application\n time.sleep(30)\n Logger.critical('Restarting application after exception: ' + repr(e))\n\n app.notifyTelegram('Auto restarting bot for ' + app.getMarket() + ' after exception: ' + repr(e))\n\n # Cancel the events queue\n map(s.cancel, s.queue)\n\n # Restart the app\n runApp()\n else:\n raise\n\n # catches a keyboard break of app, exits gracefully\n except KeyboardInterrupt:\n Logger.warning(str(datetime.now()) + ' bot is closed via keyboard interrupt...')\n try:\n sys.exit(0)\n except SystemExit:\n os._exit(0)\n except(BaseException, Exception) as e:\n # catch all not managed exceptions and send a Telegram message if configured\n app.notifyTelegram('Bot for ' + app.getMarket() + ' got an exception: ' + repr(e))\n\n Logger.critical(repr(e))\n\n raise\n\n\nmain()\n"
] |
[
[
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
jkondic/overcooked_ai
|
[
"a8d5fb1f9c16c410c47ea4b639ddc20a64276e86"
] |
[
"testing/agent_test.py"
] |
[
"import unittest\nimport numpy as np\n\nfrom overcooked_ai_py.agents.agent import AgentPair, FixedPlanAgent, GreedyHumanModel, RandomAgent, SampleAgent\nfrom overcooked_ai_py.mdp.actions import Direction, Action\nfrom overcooked_ai_py.mdp.overcooked_mdp import OvercookedGridworld, OvercookedState, PlayerState, ObjectState\nfrom overcooked_ai_py.mdp.overcooked_env import OvercookedEnv\nfrom overcooked_ai_py.planning.planners import MediumLevelActionManager, NO_COUNTERS_PARAMS\nfrom overcooked_ai_py.agents.benchmarking import AgentEvaluator\n\nnp.random.seed(42)\n\nn, s = Direction.NORTH, Direction.SOUTH\ne, w = Direction.EAST, Direction.WEST\nstay, interact = Action.STAY, Action.INTERACT\nP, Obj = PlayerState, ObjectState\n\nforce_compute_large = False\nforce_compute = True\nDISPLAY = False\n\nsimple_mdp = OvercookedGridworld.from_layout_name('cramped_room')\nlarge_mdp = OvercookedGridworld.from_layout_name('corridor')\n\n\nclass TestAgentEvaluator(unittest.TestCase):\n\n def setUp(self):\n self.agent_eval = AgentEvaluator.from_layout_name({\"layout_name\": \"cramped_room\"}, {\"horizon\": 100})\n \n def test_human_model_pair(self):\n trajs = self.agent_eval.evaluate_human_model_pair()\n try:\n AgentEvaluator.check_trajectories(trajs, verbose=False)\n except AssertionError as e:\n self.fail(\"Trajectories were not returned in standard format:\\n{}\".format(e))\n\n def test_rollouts(self):\n ap = AgentPair(RandomAgent(), RandomAgent())\n trajs = self.agent_eval.evaluate_agent_pair(ap, num_games=5)\n try:\n AgentEvaluator.check_trajectories(trajs, verbose=False)\n except AssertionError as e:\n self.fail(\"Trajectories were not returned in standard format:\\n{}\".format(e))\n \n def test_mlam_computation(self):\n try:\n self.agent_eval.env.mlam\n except Exception as e:\n self.fail(\"Failed to compute MediumLevelActionManager:\\n{}\".format(e))\n\n\nclass TestBasicAgents(unittest.TestCase):\n\n def setUp(self):\n self.mlam_large = MediumLevelActionManager.from_pickle_or_compute(large_mdp, NO_COUNTERS_PARAMS, force_compute=force_compute_large)\n\n def test_fixed_plan_agents(self):\n a0 = FixedPlanAgent([s, e, n, w])\n a1 = FixedPlanAgent([s, w, n, e])\n agent_pair = AgentPair(a0, a1)\n env = OvercookedEnv.from_mdp(large_mdp, horizon=10)\n trajectory, time_taken, _, _ = env.run_agents(agent_pair, include_final_state=True, display=DISPLAY)\n end_state = trajectory[-1][0]\n self.assertEqual(time_taken, 10)\n self.assertEqual(env.mdp.get_standard_start_state().player_positions, end_state.player_positions)\n\n def test_two_greedy_human_open_map(self):\n scenario_2_mdp = OvercookedGridworld.from_layout_name('scenario2')\n mlam = MediumLevelActionManager.from_pickle_or_compute(scenario_2_mdp, NO_COUNTERS_PARAMS, force_compute=force_compute)\n a0 = GreedyHumanModel(mlam)\n a1 = GreedyHumanModel(mlam)\n agent_pair = AgentPair(a0, a1)\n start_state = OvercookedState(\n [P((8, 1), s),\n P((1, 1), s)],\n {},\n all_orders=scenario_2_mdp.start_all_orders\n )\n env = OvercookedEnv.from_mdp(scenario_2_mdp, start_state_fn=lambda: start_state, horizon=100)\n trajectory, time_taken, _, _ = env.run_agents(agent_pair, include_final_state=True, display=DISPLAY)\n\n def test_sample_agent(self):\n agent = SampleAgent([RandomAgent(all_actions=False), RandomAgent(all_actions=True)])\n probs = agent.action(None)[1][\"action_probs\"]\n expected_probs = np.array([0.18333333, 0.18333333, 0.18333333, 0.18333333, 0.18333333, 0.08333333])\n self.assertTrue(np.allclose(probs, expected_probs))\n\nclass TestAgentEvaluatorStatic(unittest.TestCase):\n\n layout_name_lst = [\"asymmetric_advantages\", \"asymmetric_advantages_tomato\", \"bonus_order_test\", \"bottleneck\",\n \"centre_objects\", \"centre_pots\", \"corridor\", \"forced_coordination_tomato\", \"unident\",\n \"marshmallow_experiment\", \"marshmallow_experiment_coordination\", \"you_shall_not_pass\"]\n\n def test_from_mdp(self):\n for layout_name in self.layout_name_lst:\n orignal_mdp = OvercookedGridworld.from_layout_name(layout_name)\n ae = AgentEvaluator.from_mdp(mdp=orignal_mdp, env_params={\"horizon\": 400})\n ae_mdp = ae.env.mdp\n self.assertEqual(orignal_mdp, ae_mdp, \"mdp with name \" + layout_name + \" experienced an inconsistency\")\n\n def test_from_mdp_params_layout(self):\n for layout_name in self.layout_name_lst:\n orignal_mdp = OvercookedGridworld.from_layout_name(layout_name)\n ae = AgentEvaluator.from_layout_name(mdp_params={\"layout_name\": layout_name}, env_params={\"horizon\": 400})\n ae_mdp = ae.env.mdp\n self.assertEqual(orignal_mdp, ae_mdp, \"mdp with name \" + layout_name + \" experienced an inconsistency\")\n\n mdp_gen_params_1 = {\n \"inner_shape\": (10, 7),\n \"prop_empty\": 0.95,\n \"prop_feats\": 0.1,\n \"start_all_orders\": [\n {\"ingredients\": [\"onion\", \"onion\", \"onion\"]}\n ],\n \"display\": False,\n }\n\n mdp_gen_params_2 = {\n \"inner_shape\": (10, 7),\n \"prop_empty\": 0.7,\n \"prop_feats\": 0.5,\n \"start_all_orders\": [\n {\"ingredients\": [\"onion\", \"onion\", \"onion\"]}\n ],\n \"display\": False,\n }\n\n mdp_gen_params_3 = {\n \"inner_shape\": (10, 7),\n \"prop_empty\": 0.5,\n \"prop_feats\": 0.4,\n \"start_all_orders\": [\n {\"ingredients\": [\"onion\", \"onion\", \"onion\"]}\n ],\n \"display\": False,\n }\n\n mdp_gen_params_lst = [mdp_gen_params_1, mdp_gen_params_2, mdp_gen_params_3]\n\n outer_shape = (10, 7)\n\n def test_from_mdp_params_variable_across(self):\n for mdp_gen_params in self.mdp_gen_params_lst:\n ae0 = AgentEvaluator.from_mdp_params_infinite(mdp_params=mdp_gen_params,\n env_params={\"horizon\": 400, \"num_mdp\": np.inf},\n outer_shape=self.outer_shape)\n ae1 = AgentEvaluator.from_mdp_params_infinite(mdp_params=mdp_gen_params,\n env_params={\"horizon\": 400, \"num_mdp\": np.inf},\n outer_shape=self.outer_shape)\n self.assertFalse(ae0.env.mdp == ae1.env.mdp,\n \"2 randomly generated layouts across 2 evaluators are the same, which is wrong\")\n\n def test_from_mdp_params_variable_infinite(self):\n for mdp_gen_params in self.mdp_gen_params_lst:\n ae = AgentEvaluator.from_mdp_params_infinite(mdp_params=mdp_gen_params,\n env_params={\"horizon\": 400, \"num_mdp\": np.inf},\n outer_shape=self.outer_shape)\n mdp_0 = ae.env.mdp.copy()\n for _ in range(5):\n ae.env.reset(regen_mdp=True)\n mdp_1 = ae.env.mdp\n self.assertFalse(mdp_0 == mdp_1,\n \"with infinite layout generator and regen_mdp=True, the 2 layouts should not be the same\")\n\n def test_from_mdp_params_variable_infinite_no_regen(self):\n for mdp_gen_params in self.mdp_gen_params_lst:\n ae = AgentEvaluator.from_mdp_params_infinite(mdp_params=mdp_gen_params,\n env_params={\"horizon\": 400, \"num_mdp\": np.inf},\n outer_shape=self.outer_shape)\n mdp_0 = ae.env.mdp.copy()\n for _ in range(5):\n ae.env.reset(regen_mdp=False)\n mdp_1 = ae.env.mdp\n self.assertTrue(mdp_0 == mdp_1,\n \"with infinite layout generator and regen_mdp=False, the 2 layouts should be the same\")\n\n def test_from_mdp_params_variable_infinite_specified(self):\n for mdp_gen_params in self.mdp_gen_params_lst:\n ae = AgentEvaluator.from_mdp_params_infinite(mdp_params=mdp_gen_params,\n env_params={\"horizon\": 400, \"num_mdp\": np.inf},\n outer_shape=self.outer_shape)\n mdp_0 = ae.env.mdp.copy()\n for _ in range(5):\n ae.env.reset(regen_mdp=True)\n mdp_1 = ae.env.mdp\n self.assertFalse(mdp_0 == mdp_1,\n \"with infinite layout generator and regen_mdp=True, the 2 layouts should not be the same\")\n\n def test_from_mdp_params_variable_finite(self):\n for mdp_gen_params in self.mdp_gen_params_lst:\n ae = AgentEvaluator.from_mdp_params_finite(mdp_params=mdp_gen_params,\n env_params={\"horizon\": 400, \"num_mdp\": 2},\n outer_shape=self.outer_shape)\n mdp_0 = ae.env.mdp.copy()\n seen = [mdp_0]\n for _ in range(20):\n ae.env.reset(regen_mdp=True)\n mdp_i = ae.env.mdp\n if len(seen) == 1:\n if mdp_i != seen[0]:\n seen.append(mdp_i.copy())\n elif len(seen) == 2:\n mdp_0, mdp_1 = seen\n self.assertTrue((mdp_i == mdp_0 or mdp_i == mdp_1),\n \"more than 2 mdp was created, the function failed to perform\")\n else:\n self.assertTrue(False, \"theoretically unreachable statement\")\n\n layout_name_short_lst = [\"cramped_room\", \"cramped_room_tomato\", \"simple_o\", \"simple_tomato\", \"simple_o_t\"]\n biased = [0.1, 0.15, 0.2, 0.25, 0.3]\n num_reset = 200000\n\n def test_from_mdp_lst_default(self):\n mdp_lst = [OvercookedGridworld.from_layout_name(name) for name in self.layout_name_short_lst]\n ae = AgentEvaluator.from_mdp_lst(mdp_lst=mdp_lst, env_params={\"horizon\": 400})\n counts = {}\n\n for _ in range(self.num_reset):\n ae.env.reset(regen_mdp=True)\n if ae.env.mdp.layout_name in counts:\n counts[ae.env.mdp.layout_name] += 1\n else:\n counts[ae.env.mdp.layout_name] = 1\n\n for k, v in counts.items():\n self.assertAlmostEqual(0.2, v/self.num_reset, 2, \"more than 2 places off for \" + k)\n\n def test_from_mdp_lst_uniform(self):\n mdp_lst = [OvercookedGridworld.from_layout_name(name) for name in self.layout_name_short_lst]\n ae = AgentEvaluator.from_mdp_lst(mdp_lst=mdp_lst, env_params={\"horizon\": 400}, sampling_freq=[0.2, 0.2, 0.2, 0.2, 0.2])\n counts = {}\n\n for _ in range(self.num_reset):\n ae.env.reset(regen_mdp=True)\n if ae.env.mdp.layout_name in counts:\n counts[ae.env.mdp.layout_name] += 1\n else:\n counts[ae.env.mdp.layout_name] = 1\n\n for k, v in counts.items():\n self.assertAlmostEqual(0.2, v/self.num_reset, 2, \"more than 2 places off for \" + k)\n\n def test_from_mdp_lst_biased(self):\n mdp_lst = [OvercookedGridworld.from_layout_name(name) for name in self.layout_name_short_lst]\n ae = AgentEvaluator.from_mdp_lst(mdp_lst=mdp_lst, env_params={\"horizon\": 400}, sampling_freq=self.biased)\n counts = {}\n\n for _ in range(self.num_reset):\n ae.env.reset(regen_mdp=True)\n if ae.env.mdp.layout_name in counts:\n counts[ae.env.mdp.layout_name] += 1\n else:\n counts[ae.env.mdp.layout_name] = 1\n\n # construct the ground truth\n gt = {self.layout_name_short_lst[i]: self.biased[i] for i in range(len(self.layout_name_short_lst))}\n\n for k, v in counts.items():\n self.assertAlmostEqual(gt[k], v/self.num_reset, 2, \"more than 2 places off for \" + k)\n\n\nif __name__ == '__main__':\n unittest.main()\n"
] |
[
[
"numpy.array",
"numpy.allclose",
"numpy.random.seed"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kaderghal/ADNI_Data_processing
|
[
"454462d3913d77e3bc4de2b9725b456301c7b351"
] |
[
"src/pytorch-template/old/models/baseline_3D_single.py"
] |
[
"import os\nimport sys\nimport errno\nimport random\nimport pickle\nimport numpy as np\n\nimport torch\nimport torchvision\nimport torch.nn.functional as F\n\nfrom torch.utils.data.dataset import Dataset\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.utils.data.sampler import BatchSampler\nfrom torchvision.datasets import DatasetFolder\nfrom torchvision import transforms\n\nfrom torch import nn\nfrom torch import optim\n\n\nimport matplotlib.pyplot as plt\n\n\n\n#==============================================================================\n# Network definition\n#==============================================================================\n\nclass SE_HIPP_3D_Net(nn.Module):\n def __init__(self):\n super(SE_HIPP_3D_Net, self).__init__()\n self.conv1 = nn.Conv2d(28, 32, kernel_size=4, stride=1, padding=1)\n self.bn1 = nn.BatchNorm2d(32)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = nn.Conv2d(32, 64, kernel_size=2, stride=1, padding=0)\n self.bn2 = nn.BatchNorm2d(64)\n \n self.fc1 = nn.Linear(64*7*7, 120)\n self.dropout = nn.Dropout(0.5) \n self.fc2 = nn.Linear(120, 2)\n\n def forward(self, x): \n \n x = self.conv1(x)\n x = F.max_pool2d(x, kernel_size=3, stride=2, padding=0)\n x = self.bn1(x)\n x = self.relu(x)\n \n x = self.conv2(x)\n x = F.max_pool2d(x, kernel_size=2, stride=2, padding=1)\n x = self.bn2(x)\n x = self.relu(x)\n # print(\"size\", x.size())\n x = x.view(-1, self.num_flat_features(x))\n x = self.dropout(x)\n # print(\"size\", x.size())\n x = F.relu(self.fc1(x))\n x = self.fc2(x)\n return x\n\n def num_flat_features(self, x):\n size = x.size()[1:]\n num_features = 1\n for s in size:\n num_features *= s\n return num_features"
] |
[
[
"torch.nn.Dropout",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.functional.max_pool2d"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Advanjef/espnet
|
[
"47f51a77906c4c44d0da23da04e68676e4b931ab"
] |
[
"espnet/bin/asr_train.py"
] |
[
"#!/usr/bin/env python3\n# encoding: utf-8\n\n# Copyright 2017 Tomoki Hayashi (Nagoya University)\n# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)\n\n\"\"\"Automatic speech recognition model training script.\"\"\"\n\nimport logging\nimport os\nimport random\nimport subprocess\nimport sys\n\nfrom distutils.version import LooseVersion\n\nimport configargparse\nimport numpy as np\nimport torch\n\nfrom espnet.utils.cli_utils import strtobool\nfrom espnet.utils.training.batchfy import BATCH_COUNT_CHOICES\n\nis_torch_1_2_plus = LooseVersion(torch.__version__) >= LooseVersion(\"1.2\")\n\n\n# NOTE: you need this func to generate our sphinx doc\ndef get_parser(parser=None, required=True):\n \"\"\"Get default arguments.\"\"\"\n if parser is None:\n parser = configargparse.ArgumentParser(\n description=\"Train an automatic speech recognition (ASR) model on one CPU, \"\n \"one or multiple GPUs\",\n config_file_parser_class=configargparse.YAMLConfigFileParser,\n formatter_class=configargparse.ArgumentDefaultsHelpFormatter,\n )\n # general configuration\n parser.add(\"--config\", is_config_file=True, help=\"config file path\")\n parser.add(\n \"--config2\",\n is_config_file=True,\n help=\"second config file path that overwrites the settings in `--config`.\",\n )\n parser.add(\n \"--config3\",\n is_config_file=True,\n help=\"third config file path that overwrites the settings in \"\n \"`--config` and `--config2`.\",\n )\n\n parser.add_argument(\n \"--ngpu\",\n default=None,\n type=int,\n help=\"Number of GPUs. If not given, use all visible devices\",\n )\n parser.add_argument(\n \"--train-dtype\",\n default=\"float32\",\n choices=[\"float16\", \"float32\", \"float64\", \"O0\", \"O1\", \"O2\", \"O3\"],\n help=\"Data type for training (only pytorch backend). \"\n \"O0,O1,.. flags require apex. \"\n \"See https://nvidia.github.io/apex/amp.html#opt-levels\",\n )\n parser.add_argument(\n \"--backend\",\n default=\"chainer\",\n type=str,\n choices=[\"chainer\", \"pytorch\"],\n help=\"Backend library\",\n )\n parser.add_argument(\n \"--outdir\", type=str, required=required, help=\"Output directory\"\n )\n parser.add_argument(\"--debugmode\", default=1, type=int, help=\"Debugmode\")\n parser.add_argument(\"--dict\", required=required, help=\"Dictionary\")\n parser.add_argument(\"--seed\", default=1, type=int, help=\"Random seed\")\n parser.add_argument(\"--debugdir\", type=str, help=\"Output directory for debugging\")\n parser.add_argument(\n \"--resume\",\n \"-r\",\n default=\"\",\n nargs=\"?\",\n help=\"Resume the training from snapshot\",\n )\n parser.add_argument(\n \"--minibatches\",\n \"-N\",\n type=int,\n default=\"-1\",\n help=\"Process only N minibatches (for debug)\",\n )\n parser.add_argument(\"--verbose\", \"-V\", default=0, type=int, help=\"Verbose option\")\n parser.add_argument(\n \"--tensorboard-dir\",\n default=None,\n type=str,\n nargs=\"?\",\n help=\"Tensorboard log dir path\",\n )\n parser.add_argument(\n \"--report-interval-iters\",\n default=100,\n type=int,\n help=\"Report interval iterations\",\n )\n parser.add_argument(\n \"--save-interval-iters\",\n default=0,\n type=int,\n help=\"Save snapshot interval iterations\",\n )\n # task related\n parser.add_argument(\n \"--train-json\",\n type=str,\n default=None,\n help=\"Filename of train label data (json)\",\n )\n parser.add_argument(\n \"--valid-json\",\n type=str,\n default=None,\n help=\"Filename of validation label data (json)\",\n )\n # network architecture\n parser.add_argument(\n \"--model-module\",\n type=str,\n default=None,\n help=\"model defined module (default: espnet.nets.xxx_backend.e2e_asr:E2E)\",\n )\n # encoder\n parser.add_argument(\n \"--num-encs\", default=1, type=int, help=\"Number of encoders in the model.\"\n )\n # loss related\n parser.add_argument(\n \"--ctc_type\",\n default=\"warpctc\",\n type=str,\n choices=[\"builtin\", \"warpctc\"],\n help=\"Type of CTC implementation to calculate loss.\",\n )\n parser.add_argument(\n \"--mtlalpha\",\n default=0.5,\n type=float,\n help=\"Multitask learning coefficient, \"\n \"alpha: alpha*ctc_loss + (1-alpha)*att_loss \",\n )\n parser.add_argument(\n \"--lsm-weight\", default=0.0, type=float, help=\"Label smoothing weight\"\n )\n # recognition options to compute CER/WER\n parser.add_argument(\n \"--report-cer\",\n default=False,\n action=\"store_true\",\n help=\"Compute CER on development set\",\n )\n parser.add_argument(\n \"--report-wer\",\n default=False,\n action=\"store_true\",\n help=\"Compute WER on development set\",\n )\n parser.add_argument(\"--nbest\", type=int, default=1, help=\"Output N-best hypotheses\")\n parser.add_argument(\"--beam-size\", type=int, default=4, help=\"Beam size\")\n parser.add_argument(\"--penalty\", default=0.0, type=float, help=\"Incertion penalty\")\n parser.add_argument(\n \"--maxlenratio\",\n default=0.0,\n type=float,\n help=\"\"\"Input length ratio to obtain max output length.\n If maxlenratio=0.0 (default), it uses a end-detect function\n to automatically find maximum hypothesis lengths\"\"\",\n )\n parser.add_argument(\n \"--minlenratio\",\n default=0.0,\n type=float,\n help=\"Input length ratio to obtain min output length\",\n )\n parser.add_argument(\n \"--ctc-weight\", default=0.3, type=float, help=\"CTC weight in joint decoding\"\n )\n parser.add_argument(\n \"--rnnlm\", type=str, default=None, help=\"RNNLM model file to read\"\n )\n parser.add_argument(\n \"--rnnlm-conf\", type=str, default=None, help=\"RNNLM model config file to read\"\n )\n parser.add_argument(\"--lm-weight\", default=0.1, type=float, help=\"RNNLM weight.\")\n parser.add_argument(\"--sym-space\", default=\"<space>\", type=str, help=\"Space symbol\")\n parser.add_argument(\"--sym-blank\", default=\"<blank>\", type=str, help=\"Blank symbol\")\n # minibatch related\n parser.add_argument(\n \"--sortagrad\",\n default=0,\n type=int,\n nargs=\"?\",\n help=\"How many epochs to use sortagrad for. 0 = deactivated, -1 = all epochs\",\n )\n parser.add_argument(\n \"--batch-count\",\n default=\"auto\",\n choices=BATCH_COUNT_CHOICES,\n help=\"How to count batch_size. \"\n \"The default (auto) will find how to count by args.\",\n )\n parser.add_argument(\n \"--batch-size\",\n \"--batch-seqs\",\n \"-b\",\n default=0,\n type=int,\n help=\"Maximum seqs in a minibatch (0 to disable)\",\n )\n parser.add_argument(\n \"--batch-bins\",\n default=0,\n type=int,\n help=\"Maximum bins in a minibatch (0 to disable)\",\n )\n parser.add_argument(\n \"--batch-frames-in\",\n default=0,\n type=int,\n help=\"Maximum input frames in a minibatch (0 to disable)\",\n )\n parser.add_argument(\n \"--batch-frames-out\",\n default=0,\n type=int,\n help=\"Maximum output frames in a minibatch (0 to disable)\",\n )\n parser.add_argument(\n \"--batch-frames-inout\",\n default=0,\n type=int,\n help=\"Maximum input+output frames in a minibatch (0 to disable)\",\n )\n parser.add_argument(\n \"--maxlen-in\",\n \"--batch-seq-maxlen-in\",\n default=800,\n type=int,\n metavar=\"ML\",\n help=\"When --batch-count=seq, \"\n \"batch size is reduced if the input sequence length > ML.\",\n )\n parser.add_argument(\n \"--maxlen-out\",\n \"--batch-seq-maxlen-out\",\n default=150,\n type=int,\n metavar=\"ML\",\n help=\"When --batch-count=seq, \"\n \"batch size is reduced if the output sequence length > ML\",\n )\n parser.add_argument(\n \"--n-iter-processes\",\n default=0,\n type=int,\n help=\"Number of processes of iterator\",\n )\n parser.add_argument(\n \"--preprocess-conf\",\n type=str,\n default=None,\n nargs=\"?\",\n help=\"The configuration file for the pre-processing\",\n )\n # optimization related\n parser.add_argument(\n \"--opt\",\n default=\"adadelta\",\n type=str,\n choices=[\"adadelta\", \"adam\", \"noam\"],\n help=\"Optimizer\",\n )\n parser.add_argument(\n \"--accum-grad\", default=1, type=int, help=\"Number of gradient accumuration\"\n )\n parser.add_argument(\n \"--eps\", default=1e-8, type=float, help=\"Epsilon constant for optimizer\"\n )\n parser.add_argument(\n \"--eps-decay\", default=0.01, type=float, help=\"Decaying ratio of epsilon\"\n )\n parser.add_argument(\n \"--weight-decay\", default=0.0, type=float, help=\"Weight decay ratio\"\n )\n parser.add_argument(\n \"--criterion\",\n default=\"acc\",\n type=str,\n choices=[\"loss\", \"acc\"],\n help=\"Criterion to perform epsilon decay\",\n )\n parser.add_argument(\n \"--threshold\", default=1e-4, type=float, help=\"Threshold to stop iteration\"\n )\n parser.add_argument(\n \"--epochs\", \"-e\", default=30, type=int, help=\"Maximum number of epochs\"\n )\n parser.add_argument(\n \"--early-stop-criterion\",\n default=\"validation/main/acc\",\n type=str,\n nargs=\"?\",\n help=\"Value to monitor to trigger an early stopping of the training\",\n )\n parser.add_argument(\n \"--patience\",\n default=3,\n type=int,\n nargs=\"?\",\n help=\"Number of epochs to wait without improvement \"\n \"before stopping the training\",\n )\n parser.add_argument(\n \"--grad-clip\", default=5, type=float, help=\"Gradient norm threshold to clip\"\n )\n parser.add_argument(\n \"--num-save-attention\",\n default=3,\n type=int,\n help=\"Number of samples of attention to be saved\",\n )\n parser.add_argument(\n \"--num-save-ctc\",\n default=3,\n type=int,\n help=\"Number of samples of CTC probability to be saved\",\n )\n parser.add_argument(\n \"--grad-noise\",\n type=strtobool,\n default=False,\n help=\"The flag to switch to use noise injection to gradients during training\",\n )\n # asr_mix related\n parser.add_argument(\n \"--num-spkrs\",\n default=1,\n type=int,\n choices=[1, 2],\n help=\"Number of speakers in the speech.\",\n )\n # decoder related\n parser.add_argument(\n \"--context-residual\",\n default=False,\n type=strtobool,\n nargs=\"?\",\n help=\"The flag to switch to use context vector residual in the decoder network\",\n )\n # finetuning related\n parser.add_argument(\n \"--enc-init\",\n default=None,\n type=str,\n help=\"Pre-trained ASR model to initialize encoder.\",\n )\n parser.add_argument(\n \"--enc-init-mods\",\n default=\"enc.enc.\",\n type=lambda s: [str(mod) for mod in s.split(\",\") if s != \"\"],\n help=\"List of encoder modules to initialize, separated by a comma.\",\n )\n parser.add_argument(\n \"--dec-init\",\n default=None,\n type=str,\n help=\"Pre-trained ASR, MT or LM model to initialize decoder.\",\n )\n parser.add_argument(\n \"--dec-init-mods\",\n default=\"att., dec.\",\n type=lambda s: [str(mod) for mod in s.split(\",\") if s != \"\"],\n help=\"List of decoder modules to initialize, separated by a comma.\",\n )\n parser.add_argument(\n \"--freeze-mods\",\n default=None,\n type=lambda s: [str(mod) for mod in s.split(\",\") if s != \"\"],\n help=\"List of modules to freeze, separated by a comma.\",\n )\n # front end related\n parser.add_argument(\n \"--use-frontend\",\n type=strtobool,\n default=False,\n help=\"The flag to switch to use frontend system.\",\n )\n\n # WPE related\n parser.add_argument(\n \"--use-wpe\",\n type=strtobool,\n default=False,\n help=\"Apply Weighted Prediction Error\",\n )\n parser.add_argument(\n \"--wtype\",\n default=\"blstmp\",\n type=str,\n choices=[\n \"lstm\",\n \"blstm\",\n \"lstmp\",\n \"blstmp\",\n \"vgglstmp\",\n \"vggblstmp\",\n \"vgglstm\",\n \"vggblstm\",\n \"gru\",\n \"bgru\",\n \"grup\",\n \"bgrup\",\n \"vgggrup\",\n \"vggbgrup\",\n \"vgggru\",\n \"vggbgru\",\n ],\n help=\"Type of encoder network architecture \"\n \"of the mask estimator for WPE. \"\n \"\",\n )\n parser.add_argument(\"--wlayers\", type=int, default=2, help=\"\")\n parser.add_argument(\"--wunits\", type=int, default=300, help=\"\")\n parser.add_argument(\"--wprojs\", type=int, default=300, help=\"\")\n parser.add_argument(\"--wdropout-rate\", type=float, default=0.0, help=\"\")\n parser.add_argument(\"--wpe-taps\", type=int, default=5, help=\"\")\n parser.add_argument(\"--wpe-delay\", type=int, default=3, help=\"\")\n parser.add_argument(\n \"--use-dnn-mask-for-wpe\",\n type=strtobool,\n default=False,\n help=\"Use DNN to estimate the power spectrogram. \"\n \"This option is experimental.\",\n )\n # Beamformer related\n parser.add_argument(\"--use-beamformer\", type=strtobool, default=True, help=\"\")\n parser.add_argument(\n \"--btype\",\n default=\"blstmp\",\n type=str,\n choices=[\n \"lstm\",\n \"blstm\",\n \"lstmp\",\n \"blstmp\",\n \"vgglstmp\",\n \"vggblstmp\",\n \"vgglstm\",\n \"vggblstm\",\n \"gru\",\n \"bgru\",\n \"grup\",\n \"bgrup\",\n \"vgggrup\",\n \"vggbgrup\",\n \"vgggru\",\n \"vggbgru\",\n ],\n help=\"Type of encoder network architecture \"\n \"of the mask estimator for Beamformer.\",\n )\n parser.add_argument(\"--blayers\", type=int, default=2, help=\"\")\n parser.add_argument(\"--bunits\", type=int, default=300, help=\"\")\n parser.add_argument(\"--bprojs\", type=int, default=300, help=\"\")\n parser.add_argument(\"--badim\", type=int, default=320, help=\"\")\n parser.add_argument(\n \"--bnmask\",\n type=int,\n default=2,\n help=\"Number of beamforming masks, \" \"default is 2 for [speech, noise].\",\n )\n parser.add_argument(\n \"--ref-channel\",\n type=int,\n default=-1,\n help=\"The reference channel used for beamformer. \"\n \"By default, the channel is estimated by DNN.\",\n )\n parser.add_argument(\"--bdropout-rate\", type=float, default=0.0, help=\"\")\n # Feature transform: Normalization\n parser.add_argument(\n \"--stats-file\",\n type=str,\n default=None,\n help=\"The stats file for the feature normalization\",\n )\n parser.add_argument(\n \"--apply-uttmvn\",\n type=strtobool,\n default=True,\n help=\"Apply utterance level mean \" \"variance normalization.\",\n )\n parser.add_argument(\"--uttmvn-norm-means\", type=strtobool, default=True, help=\"\")\n parser.add_argument(\"--uttmvn-norm-vars\", type=strtobool, default=False, help=\"\")\n # Feature transform: Fbank\n parser.add_argument(\n \"--fbank-fs\",\n type=int,\n default=16000,\n help=\"The sample frequency used for \" \"the mel-fbank creation.\",\n )\n parser.add_argument(\n \"--n-mels\", type=int, default=80, help=\"The number of mel-frequency bins.\"\n )\n parser.add_argument(\"--fbank-fmin\", type=float, default=0.0, help=\"\")\n parser.add_argument(\"--fbank-fmax\", type=float, default=None, help=\"\")\n return parser\n\n\ndef main(cmd_args):\n \"\"\"Run the main training function.\"\"\"\n parser = get_parser()\n args, _ = parser.parse_known_args(cmd_args)\n if args.backend == \"chainer\" and args.train_dtype != \"float32\":\n raise NotImplementedError(\n f\"chainer backend does not support --train-dtype {args.train_dtype}.\"\n \"Use --dtype float32.\"\n )\n if args.ngpu == 0 and args.train_dtype in (\"O0\", \"O1\", \"O2\", \"O3\", \"float16\"):\n raise ValueError(\n f\"--train-dtype {args.train_dtype} does not support the CPU backend.\"\n )\n\n from espnet.utils.dynamic_import import dynamic_import\n\n if args.model_module is None:\n model_module = \"espnet.nets.\" + args.backend + \"_backend.e2e_asr:E2E\"\n else:\n model_module = args.model_module\n model_class = dynamic_import(model_module)\n model_class.add_arguments(parser)\n\n args = parser.parse_args(cmd_args)\n args.model_module = model_module\n if \"chainer_backend\" in args.model_module:\n args.backend = \"chainer\"\n if \"pytorch_backend\" in args.model_module:\n args.backend = \"pytorch\"\n\n # logging info\n if args.verbose > 0:\n logging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s\",\n )\n else:\n logging.basicConfig(\n level=logging.WARN,\n format=\"%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s\",\n )\n logging.warning(\"Skip DEBUG/INFO messages\")\n\n # If --ngpu is not given,\n # 1. if CUDA_VISIBLE_DEVICES is set, all visible devices\n # 2. if nvidia-smi exists, use all devices\n # 3. else ngpu=0\n if args.ngpu is None:\n cvd = os.environ.get(\"CUDA_VISIBLE_DEVICES\")\n if cvd is not None:\n ngpu = len(cvd.split(\",\"))\n else:\n logging.warning(\"CUDA_VISIBLE_DEVICES is not set.\")\n try:\n p = subprocess.run(\n [\"nvidia-smi\", \"-L\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE\n )\n except (subprocess.CalledProcessError, FileNotFoundError):\n ngpu = 0\n else:\n ngpu = len(p.stderr.decode().split(\"\\n\")) - 1\n else:\n if is_torch_1_2_plus and args.ngpu != 1:\n logging.debug(\n \"There are some bugs with multi-GPU processing in PyTorch 1.2+\"\n + \" (see https://github.com/pytorch/pytorch/issues/21108)\"\n )\n ngpu = args.ngpu\n logging.info(f\"ngpu: {ngpu}\")\n\n # display PYTHONPATH\n logging.info(\"python path = \" + os.environ.get(\"PYTHONPATH\", \"(None)\"))\n\n # set random seed\n logging.info(\"random seed = %d\" % args.seed)\n random.seed(args.seed)\n np.random.seed(args.seed)\n\n # load dictionary for debug log\n if args.dict is not None:\n with open(args.dict, \"rb\") as f:\n dictionary = f.readlines()\n char_list = [entry.decode(\"utf-8\").split(\" \")[0] for entry in dictionary]\n char_list.insert(0, \"<blank>\")\n char_list.append(\"<eos>\")\n # for non-autoregressive training using Transformer\n if hasattr(args, \"decoder_mode\") and args.decoder_mode == \"maskctc\":\n char_list.append(\"<mask>\")\n args.char_list = char_list\n else:\n args.char_list = None\n\n # train\n logging.info(\"backend = \" + args.backend)\n\n if args.num_spkrs == 1:\n if args.backend == \"chainer\":\n from espnet.asr.chainer_backend.asr import train\n\n train(args)\n elif args.backend == \"pytorch\":\n from espnet.asr.pytorch_backend.asr import train\n\n train(args)\n else:\n raise ValueError(\"Only chainer and pytorch are supported.\")\n else:\n # FIXME(kamo): Support --model-module\n if args.backend == \"pytorch\":\n from espnet.asr.pytorch_backend.asr_mix import train\n\n train(args)\n else:\n raise ValueError(\"Only pytorch is supported.\")\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n"
] |
[
[
"numpy.random.seed"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
qiyunzhu/taxa-assign-benchmarking
|
[
"df0fbe6a84f20ac2e2febbbb21bd686ec90e84e3"
] |
[
"benchutils/transformers.py"
] |
[
"import pandas as pd\n\nkraken_rank_dictionary = {\n 'P': 'phylum',\n 'C': 'class',\n 'O': 'order',\n 'F': 'family',\n 'G': 'genus',\n 'S': 'species'\n}\n\ngreengenes_rank_dict = {\n 'k__': 'kingdom',\n 'p__': 'phylum',\n 'c__': 'class',\n 'o__': 'order',\n 'f__': 'family',\n 'g__': 'genus',\n 's__': 'species'\n}\n\nkraken_columns = ['PERCENTAGE', 'lca_read_count', 'read_count', 'rank',\n '@@TAXID', 'TAXNAME']\n\n\ndef kraken2_transformer(all_rank_summary, output_rank_summaries, ranks):\n # TODO finsih docs\n \"\"\"Converts a summary of all ranks from kraken into rank-wise profiles\n similar to the CAMI-SIM output\n\n Parameters\n ----------\n all_rank_summary\n output_rank_summaries\n ranks\n\n Returns\n -------\n\n \"\"\"\n # TODO COULD be split into two format functions: one to reformat,\n # and one to split on rank\n # TODO give error for invalid rank value\n all_ranks = pd.read_csv(all_rank_summary, sep='\\t')\n all_ranks.columns = kraken_columns\n # TODO for kraken is it okay to just take the first part (drop the number)\n all_ranks['rank'] = all_ranks['rank'].str[0]\n all_ranks = all_ranks.loc[all_ranks['rank'].isin(kraken_rank_dictionary)]\n all_ranks['RANK'] = [kraken_rank_dictionary[key] for key in\n all_ranks['rank']]\n keep_cols = ['@@TAXID', 'RANK', 'TAXNAME', 'PERCENTAGE']\n for output_, rank in zip(output_rank_summaries, ranks):\n sub_df = all_ranks.loc[all_ranks['RANK'] == rank]\n sub_df_matching = sub_df[keep_cols]\n sub_df_matching.to_csv(output_, sep='\\t', index=False)\n\n\ndef metaphlan2_transformer(all_rank_summary, output_rank_summaries, ranks):\n all_ranks = pd.read_csv(all_rank_summary, sep='\\t', skiprows=3)\n def last_entry(x): return x.split('|')[-1]\n all_ranks['last_clade'] = all_ranks['#clade_name'].map(last_entry)\n all_ranks['@@TAXID'] = all_ranks['NCBI_tax_id'].map(last_entry)\n all_ranks['RANK'] = all_ranks['last_clade'].map(\n lambda x: greengenes_rank_dict[x[:3]])\n all_ranks['TAXNAME'] = all_ranks['last_clade'].map(lambda x: x[3:])\n all_ranks['PERCENTAGE'] = all_ranks['relative_abundance']\n\n keep_cols = ['@@TAXID', 'RANK', 'TAXNAME', 'PERCENTAGE']\n for output_, rank in zip(output_rank_summaries, ranks):\n sub_df = all_ranks.loc[all_ranks['RANK'] == rank]\n sub_df_matching = sub_df[keep_cols]\n sub_df_matching.to_csv(output_, sep='\\t', index=False)\n"
] |
[
[
"pandas.read_csv"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
ishanic/MeshRCNN-keypoints
|
[
"fdc2c81ce57313207478ab9ff1699614addc5993"
] |
[
"demo/demo.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport argparse\nimport logging\nimport multiprocessing as mp\nimport numpy as np\nimport os\nimport torch\nfrom detectron2.config import get_cfg\nfrom detectron2.data import MetadataCatalog\nfrom detectron2.data.detection_utils import read_image\nfrom detectron2.engine.defaults import DefaultPredictor\nfrom detectron2.utils.logger import setup_logger\nfrom pytorch3d.io import save_obj\nfrom pytorch3d.structures import Meshes\n\n# required so that .register() calls are executed in module scope\nimport meshrcnn.data # noqa\nimport meshrcnn.modeling # noqa\nimport meshrcnn.utils # noqa\nfrom meshrcnn.config import get_meshrcnn_cfg_defaults\nfrom meshrcnn.evaluation import transform_meshes_to_camera_coord_system\n\ndef get_parser():\n parser = argparse.ArgumentParser(description=\"MeshRCNN Demo\")\n parser.add_argument(\n \"--config-file\",\n default=\"configs/pix3d/meshrcnn_R50_FPN.yaml\",\n metavar=\"FILE\",\n help=\"path to config file\",\n )\n parser.add_argument(\"--input\", help=\"A path to an input image\")\n parser.add_argument(\"--output\", help=\"A directory to save output visualizations\")\n parser.add_argument(\n \"--focal-length\", type=float, default=20.0, help=\"Focal length for the image\"\n )\n parser.add_argument(\n \"--onlyhighest\", action=\"store_true\", help=\"will return only the highest scoring detection\"\n )\n\n parser.add_argument(\n \"opts\",\n help=\"Modify model config options using the command-line\",\n default=None,\n nargs=argparse.REMAINDER,\n )\n return parser\n\nargs = get_parser().parse_args()\nfrom meshrcnn.data.datasets.register_pix3d import register_pix3d\nregister_pix3d(args.opts[1])\n\nimport cv2\n\nlogger = logging.getLogger(\"demo\")\n\n\nclass VisualizationDemo(object):\n def __init__(self, cfg, vis_highest_scoring=True, output_dir=\"./vis\"):\n \"\"\"\n Args:\n cfg (CfgNode):\n vis_highest_scoring (bool): If set to True visualizes only\n the highest scoring prediction\n \"\"\"\n self.metadata = MetadataCatalog.get(cfg.DATASETS.TEST[0])\n self.colors = self.metadata.thing_colors\n self.cat_names = self.metadata.thing_classes\n\n self.cpu_device = torch.device(\"cpu\")\n self.vis_highest_scoring = vis_highest_scoring\n self.predictor = DefaultPredictor(cfg)\n\n os.makedirs(output_dir, exist_ok=True)\n self.output_dir = output_dir\n\n def run_on_image(self, image, focal_length=10.0):\n \"\"\"\n Args:\n image (np.ndarray): an image of shape (H, W, C) (in BGR order).\n This is the format used by OpenCV.\n focal_length (float): the focal_length of the image\n\n Returns:\n predictions (dict): the output of the model.\n \"\"\"\n predictions = self.predictor(image)\n # Convert image from OpenCV BGR format to Matplotlib RGB format.\n image = image[:, :, ::-1]\n\n # camera matrix\n imsize = [image.shape[0], image.shape[1]]\n # focal <- focal * image_width / 32\n focal_length = image.shape[1] / 32 * focal_length\n K = [focal_length, image.shape[1] / 2, image.shape[0] / 2]\n\n if \"instances\" in predictions:\n instances = predictions[\"instances\"].to(self.cpu_device)\n scores = instances.scores\n boxes = instances.pred_boxes\n labels = instances.pred_classes\n masks = instances.pred_masks\n meshes = Meshes(\n verts=[mesh[0] for mesh in instances.pred_meshes],\n faces=[mesh[1] for mesh in instances.pred_meshes],\n )\n pred_dz = instances.pred_dz[:, 0] * (boxes.tensor[:, 3] - boxes.tensor[:, 1])\n tc = pred_dz.abs().max() + 1.0\n zranges = torch.stack(\n [\n torch.stack(\n [\n tc - tc * pred_dz[i] / 2.0 / focal_length,\n tc + tc * pred_dz[i] / 2.0 / focal_length,\n ]\n )\n for i in range(len(meshes))\n ],\n dim=0,\n )\n\n Ks = torch.tensor(K).to(self.cpu_device).view(1, 3).expand(len(meshes), 3)\n meshes = transform_meshes_to_camera_coord_system(\n meshes, boxes.tensor, zranges, Ks, imsize\n )\n\n if self.vis_highest_scoring:\n det_ids = [scores.argmax().item()]\n else:\n det_ids = range(len(scores))\n\n for det_id in det_ids:\n self.visualize_prediction(\n det_id,\n image,\n boxes.tensor[det_id],\n labels[det_id],\n scores[det_id],\n masks[det_id],\n meshes[det_id],\n )\n\n return predictions\n\n def visualize_prediction(\n self, det_id, image, box, label, score, mask, mesh, alpha=0.6, dpi=200\n ):\n\n mask_color = np.array(self.colors[label], dtype=np.float32)\n cat_name = self.cat_names[label]\n thickness = max([int(np.ceil(0.001 * image.shape[0])), 1])\n box_color = (0, 255, 0) # '#00ff00', green\n text_color = (218, 227, 218) # gray\n\n composite = image.copy().astype(np.float32)\n\n # overlay mask\n idx = mask.nonzero()\n composite[idx[:, 0], idx[:, 1], :] *= 1.0 - alpha\n composite[idx[:, 0], idx[:, 1], :] += alpha * mask_color\n\n # overlay box\n (x0, y0, x1, y1) = (int(x + 0.5) for x in box)\n composite = cv2.rectangle(\n composite, (x0, y0), (x1, y1), color=box_color, thickness=thickness\n )\n composite = composite.astype(np.uint8)\n\n # overlay text\n font_scale = 0.001 * image.shape[0]\n font_thickness = thickness\n font = cv2.FONT_HERSHEY_TRIPLEX\n text = \"%s %.3f\" % (cat_name, score)\n ((text_w, text_h), _) = cv2.getTextSize(text, font, font_scale, font_thickness)\n # Place text background.\n if x0 + text_w > composite.shape[1]:\n x0 = composite.shape[1] - text_w\n if y0 - int(1.2 * text_h) < 0:\n y0 = int(1.2 * text_h)\n back_topleft = x0, y0 - int(1.3 * text_h)\n back_bottomright = x0 + text_w, y0\n cv2.rectangle(composite, back_topleft, back_bottomright, box_color, -1)\n # Show text\n text_bottomleft = x0, y0 - int(0.2 * text_h)\n cv2.putText(\n composite,\n text,\n text_bottomleft,\n font,\n font_scale,\n text_color,\n thickness=font_thickness,\n lineType=cv2.LINE_AA,\n )\n\n save_file = os.path.join(self.output_dir, \"%d_mask_%s_%.3f.png\" % (det_id, cat_name, score))\n cv2.imwrite(save_file, composite[:, :, ::-1])\n\n save_file = os.path.join(self.output_dir, \"%d_mesh_%s_%.3f.obj\" % (det_id, cat_name, score))\n verts, faces = mesh.get_mesh_verts_faces(0)\n save_obj(save_file, verts, faces)\n\n\ndef setup_cfg(args):\n cfg = get_cfg()\n get_meshrcnn_cfg_defaults(cfg)\n cfg.merge_from_file(args.config_file)\n cfg.merge_from_list(args.opts)\n cfg.freeze()\n return cfg\n\nif __name__ == \"__main__\":\n mp.set_start_method(\"spawn\", force=True)\n args = get_parser().parse_args()\n logger = setup_logger(name=\"demo\")\n logger.info(\"Arguments: \" + str(args))\n\n cfg = setup_cfg(args)\n\n im_name = args.input.split(\"/\")[-1].split(\".\")[0]\n\n demo = VisualizationDemo(\n cfg, vis_highest_scoring=args.onlyhighest, output_dir=os.path.join(args.output, im_name)\n )\n\n # use PIL, to be consistent with evaluation\n img = read_image(args.input, format=\"BGR\")\n predictions = demo.run_on_image(img, focal_length=args.focal_length)\n logger.info(\"Predictions saved in %s\" % (os.path.join(args.output, im_name)))\n"
] |
[
[
"torch.tensor",
"numpy.ceil",
"torch.device",
"numpy.array",
"torch.stack"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
raharth/PyMatch
|
[
"93cf10fd9ca0fa104b0f2a30e613f75fd0561b92",
"93cf10fd9ca0fa104b0f2a30e613f75fd0561b92",
"93cf10fd9ca0fa104b0f2a30e613f75fd0561b92"
] |
[
"pymatch/utils/KFold.py",
"pymatch/ReinforcementLearning/sample.py",
"tests/utils/experiment/experiment.py"
] |
[
"import torch\n\n\nclass KFold:\n\n def __init__(self, dataset, n_fold=10, batch_size=32, num_workers=0, pin_memory=False):\n self.fold = 0\n self.batch_size = batch_size\n self.num_workers = num_workers\n self.pin_memory = pin_memory\n self.dataset = dataset\n self.n_fold = n_fold\n self.fold_size = len(self.dataset) // self.n_fold\n self.folded_size = self.n_fold * self.fold_size\n\n self.fold_idx = self.fold_split()\n\n def fold_split(self, random_seed=None):\n \"\"\"\n Splitting the folds.\n\n Args:\n random_seed: Random seed for reproducibility\n\n Returns:\n tensor containing indices for folds, where dim=0 is the fold number\n\n \"\"\"\n if random_seed is not None:\n torch.manual_seed(random_seed)\n fold_idx = torch.randperm(self.dataset.__len__())\n fold_idx = fold_idx[:self.folded_size].view(-1, self.fold_size)\n return fold_idx\n\n def fold_loaders(self, fold=-1):\n \"\"\"\n Loading a specific fold as train and test data loader. If no fold number is provided it returns the next fold. It returns a randomly sampled subset of\n the original data set.\n\n Args:\n fold: fold number to return\n\n Returns:\n (train data loader, test data loader)\n\n \"\"\"\n if fold == -1:\n fold = self.fold\n test_fold_idx = self.fold_idx[fold]\n train_fold_idx = self.fold_idx[[i for i in range(self.n_fold) if i != fold]].view(-1)\n train_loader = torch.utils.data.DataLoader(self.dataset,\n batch_size=self.batch_size, # args.batch_size,\n num_workers=self.num_workers, # args.loader_num_workers,\n pin_memory=self.pin_memory,\n sampler=torch.utils.data.SubsetRandomSampler(train_fold_idx))\n test_loader = torch.utils.data.DataLoader(self.dataset,\n batch_size=self.batch_size, # args.batch_size,\n num_workers=self.num_workers, # args.loader_num_workers,\n pin_memory=self.pin_memory,\n sampler=torch.utils.data.SubsetRandomSampler(test_fold_idx))\n self.fold = (self.fold + 1) % self.n_fold\n return train_loader, test_loader\n\n\n",
"import torch\nimport torch.nn as nn\n\n\nclass ReinforceMultivariant(nn.Module):\n def __init__(self, std=.1):\n super(ReinforceMultivariant, self).__init__()\n self.std = std\n\n def forward(self, actions):\n std = torch.eye(actions.shape[1]) * self.std**2\n dist = torch.distributions.MultivariateNormal(actions, std)\n action = dist.sample()\n return action, dist.log_prob(action)",
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom pymatch.utils.experiment import Experiment, with_experiment\nfrom pymatch.DeepLearning.ensemble import Ensemble\nfrom pymatch.ReinforcementLearning.loss import REINFORCELoss\nfrom pymatch.ReinforcementLearning.memory import MemoryUpdater\nfrom pymatch.ReinforcementLearning.torch_gym import CartPole\nimport pymatch.ReinforcementLearning.learner as rl\nimport pymatch.ReinforcementLearning.selection_policy as sp\n\n\nclass Core(nn.Module):\n\n def __init__(self, in_nodes):\n super(Core, self).__init__()\n self.fc1 = nn.Linear(in_nodes, 10)\n\n def forward(self, x):\n x = self.fc1(x)\n x = F.relu(x)\n return x\n\n\nclass Model(nn.Module):\n\n def __init__(self, core, out_nodes):\n super(Model, self).__init__()\n self.core = core\n self.do1 = nn.Dropout(.5)\n self.fc2 = nn.Linear(10, out_nodes)\n\n def forward(self, x):\n x = self.core(x)\n x = self.do1(x)\n x = self.fc2(x)\n x = F.softmax(x, dim=1)\n return x\n\n\ndef factory(Model, core, model_args, env_args, optim_args, memory_args, learner_args, name):\n model = Model(core, **model_args)\n env = CartPole(**env_args)\n optim = torch.optim.SGD(model.parameters(), **optim_args)\n crit = REINFORCELoss()\n memory_updater = MemoryUpdater(**memory_args)\n largs = dict(learner_args)\n largs['name'] = f\"{learner_args['name']}_{name}\"\n learner = rl.PolicyGradient(env=env,\n model=model,\n optimizer=optim,\n memory_updater=memory_updater,\n crit=crit,\n action_selector=sp.PolicyGradientActionSelection(),\n callbacks=[],\n **largs\n )\n return learner\n\n\nroot = 'tests/experiment'\n\nexperiment = Experiment(root=root)\nparams = experiment.get_params()\nparams['factory_args']['learner_args']['dump_path'] = root\nparams['factory_args']['core'] = Core(**params['core_args'])\n\nwith with_experiment(experiment=experiment, overwrite=params['overwrite']):\n learner = Ensemble(model_class=Model,\n trainer_factory=factory,\n trainer_args=params['factory_args'],\n n_model=params['n_learner'],\n callbacks=[])\n learner.fit(**params['fit'])\n print('done training')\n # raise NotImplemented\n"
] |
[
[
"torch.manual_seed",
"torch.utils.data.SubsetRandomSampler"
],
[
"torch.distributions.MultivariateNormal",
"torch.eye"
],
[
"torch.nn.Linear",
"torch.nn.Dropout",
"torch.nn.functional.relu",
"torch.nn.functional.softmax"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
FinFetChannel/PytracingMaze
|
[
"6ccb444c76ede7e48ac09a74d550f32884c7c74b",
"6ccb444c76ede7e48ac09a74d550f32884c7c74b"
] |
[
"RayTracingMazeEnem.py",
"pytracing render choices.py"
] |
[
"import numpy as np\r\nimport pygame as pg\r\nfrom numba import njit\r\n\r\ndef main():\r\n size = np.random.randint(20,60) # size of the map\r\n posx, posy, posz = 1.5, np.random.uniform(1, size -1), 0.5\r\n \r\n rot, rot_v = (np.pi/4, 0)\r\n lx, ly, lz = (size*20, size*30, 1000)\r\n mr, mg, mb, maph, mapr, exitx, exity, mapt, maps = maze_generator(int(posx), int(posy), size)\r\n enx, eny, seenx, seeny, lock = np.random.uniform(2, size-3 ), np.random.uniform(2, size-3), 0, 0, 0\r\n maph[int(enx)][int(eny)] = 0\r\n shoot, sx, sy, sdir = 1, -1, -1, rot\r\n\r\n res, res_o = 5, [96, 112, 160, 192, 224, 260, 300, 340, 400, 480, 540, 600, 800]\r\n width, height, mod, inc, rr, gg, bb = adjust_resol(24)\r\n\r\n running = True\r\n pg.init()\r\n \r\n font = pg.font.SysFont(\"Arial\", 18)\r\n font2 = pg.font.SysFont(\"Impact\", 48)\r\n screen = pg.display.set_mode((800, 600))\r\n rr, gg, bb = np.linspace(0,0.8, width*height), np.linspace(0.5,.1, width*height), np.linspace(1,0.1, width*height)\r\n pixels = np.dstack((rr,gg,bb))\r\n pixels = np.reshape(pixels, (height,width,3))\r\n surf = pg.surfarray.make_surface((np.rot90(pixels*255)).astype('uint8'))\r\n surf = pg.transform.scale(surf, (750, 550))\r\n screen.blit(surf, (25, 25))\r\n screen.blit(font2.render(\" FinFET's PyTracing Maze \", 1, pg.Color(\"red\")),(45,95))\r\n screen.blit(font2.render(\" FinFET's PyTracing Maze \", 1, pg.Color(\"blue\")),(55,105))\r\n screen.blit(font2.render(\" FinFET's PyTracing Maze \", 1, pg.Color(\"white\")),(50,100))\r\n screen.blit(font2.render(\" Loading, please wait... \", 1, pg.Color(\"black\"), pg.Color(\"grey\")),(50,300))\r\n pg.display.update()\r\n \r\n clock = pg.time.Clock()\r\n pg.mouse.set_visible(False)\r\n et = 0.1\r\n mplayer = np.zeros([size, size])\r\n enx, eny, mplayer, et, shoot, sx, sy, sdir, seenx, seeny, lock = agents(enx, eny, maph, posx, posy, rot, et, shoot, sx, sy, sdir, mplayer, seenx, seeny, lock)\r\n sstart, timer, count, autores, smooth = None, 0, -100, 1, 0\r\n pause = 0\r\n \r\n pg.mixer.set_num_channels(3)\r\n ambient = pg.mixer.Sound('soundfx/HauntSilentPartner.mp3')\r\n ambient.set_volume(0.5)\r\n runfx = pg.mixer.Sound('soundfx/run.mp3')\r\n shotfx = pg.mixer.Sound('soundfx/slap.mp3')\r\n killfx = pg.mixer.Sound('soundfx/shutdown.mp3')\r\n respawnfx = pg.mixer.Sound('soundfx/respawn.mp3')\r\n successfx = pg.mixer.Sound('soundfx/success.mp3')\r\n failfx = pg.mixer.Sound('soundfx/fail.mp3')\r\n pg.mixer.Channel(0).play(ambient, -1)\r\n pg.mixer.Channel(1).play(respawnfx)\r\n run = 1\r\n score = 0\r\n ticks = pg.time.get_ticks()/100000\r\n while running:\r\n count += 1\r\n for event in pg.event.get():\r\n if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE):\r\n if not pause:\r\n pause = 1\r\n pg.mixer.Channel(1).play(respawnfx)\r\n endmsg = \" Game paused. Current score: \" + str(score)\r\n else:\r\n endmsg = \" Thanks for playing! Total score: \" + str(score)\r\n pg.mixer.Channel(1).play(killfx)\r\n running = False\r\n if sstart == None and(event.type == pg.MOUSEBUTTONDOWN or event.type == pg.MOUSEBUTTONUP):\r\n shoot = 1\r\n if event.type == pg.KEYDOWN:\r\n if event.key == ord('p'): # pause\r\n if not pause:\r\n pause = 1\r\n endmsg = \" Game paused. Current score: \" + str(score)\r\n elif (int(posx) != exitx or int(posy) != exity):\r\n pause = 0\r\n if pause and event.key == ord('n'): # new game\r\n pause = 0\r\n size = np.random.randint(20,60)\r\n posx, posy, posz = 1.5, np.random.uniform(1, size -1), 0.5\r\n rot, rot_v = (np.pi/4, 0)\r\n mr, mg, mb, maph, mapr, exitx, exity, mapt, maps = maze_generator(int(posx), int(posy), size)\r\n enx, eny, seenx, seeny, lock, run = 0, 0, 0, 0, 0, 1\r\n shoot, sx, sy, sstart = 0, -1, -1, None\r\n mplayer = np.zeros([size, size])\r\n et = 0.1\r\n enx, eny, mplayer, et, shoot, sx, sy, sdir, seenx, seeny, lock = agents(enx, eny, maph, posx, posy, rot, et, shoot, sx, sy, sdir, mplayer, seenx, seeny, lock)\r\n count = -100\r\n if autores:\r\n width, height, mod, inc, rr, gg, bb = adjust_resol(24)\r\n pg.mixer.Channel(1).play(respawnfx)\r\n if event.key == ord('t'): # toggle auto resolution\r\n autores = not(autores)\r\n if event.key == ord('y'): # toggle auto resolution\r\n smooth = not(smooth)\r\n if not autores:\r\n if event.key == ord('q'): # manually change resolution\r\n if res > 0 :\r\n res = res-1\r\n width, height, mod, inc, rr, gg, bb = adjust_resol(res_o[res])\r\n if event.key == ord('e'):\r\n if res < len(res_o)-1 :\r\n res = res+1\r\n width, height, mod, inc, rr, gg, bb = adjust_resol(res_o[res])\r\n \r\n if not pause:\r\n rr, gg, bb = super_fast(width, height, mod, inc, posx, posy, posz, rot, rot_v, mr, mg, mb, lx, ly, lz, mplayer, exitx, exity, mapr, mapt, maps, rr, gg, bb, enx, eny, sx, sy, size)\r\n \r\n pixels = np.dstack((rr,gg,bb))\r\n\r\n pixels = np.reshape(pixels, (height,width,3))\r\n\r\n surf = pg.surfarray.make_surface((np.rot90(pixels*255)).astype('uint8'))\r\n if shoot or smooth:\r\n surf = pg.transform.smoothscale(surf, (800, 600))\r\n else:\r\n surf = pg.transform.scale(surf, (800, 600))\r\n \r\n screen.blit(surf, (0, 0))\r\n## fpss = int(clock.get_fps())pg.time.get_ticks()/100000\r\n fpss = int(1000/(pg.time.get_ticks() - ticks*100000))\r\n fps = font.render(str(fpss)+' w: '+ str(width) + ' Score: '+str(score), 1, pg.Color(\"coral\"))\r\n screen.blit(fps,(10,0))\r\n \r\n if autores and count > 10: #auto adjust render resolution\r\n if fpss < 50 and width > 100:\r\n count = 0\r\n width, height, mod, inc, rr, gg, bb = adjust_resol(int(width*0.8))\r\n if fpss > 65 and width < 728:\r\n count = 0\r\n width, height, mod, inc, rr, gg, bb = adjust_resol(int(width*1.1)) \r\n\r\n # player's movement\r\n if (int(posx) == exitx and int(posy) == exity):\r\n endmsg = \" You escaped safely! \"\r\n pg.mixer.Channel(1).play(successfx)\r\n score += 1\r\n pause = 1\r\n \r\n pressed_keys = pg.key.get_pressed()\r\n et = clock.tick()/500\r\n if et > 0.5:\r\n et = 0.5\r\n\r\n if shoot or sstart != None:\r\n if sstart == None:\r\n pg.mixer.Channel(2).play(shotfx)\r\n if fpss < 60 and autores:\r\n count = -50\r\n width, height, mod, inc, rr, gg, bb = adjust_resol(int(width*0.8))\r\n sstart = pg.time.get_ticks()\r\n elif pg.time.get_ticks() - sstart > 500:\r\n shoot, sx, sy, sstart = 0, -1, -1, None\r\n \r\n if enx == 0:\r\n if not run:\r\n pg.mixer.Channel(1).play(killfx)\r\n run = 1\r\n if np.random.uniform() > 0.999:\r\n cos, sin = np.cos(rot), np.sin(rot)\r\n for ee in range(100):\r\n enx = np.clip(np.random.normal(posx, 5), 1, size-2)\r\n eny = np.clip(np.random.normal(posy, 5), 1, size-2)\r\n dtp = (enx-posx)**2 + (eny-posy)**2\r\n if maph[int(enx)][int(eny)] == 0 and dtp > 16 and dtp < 49:\r\n break\r\n if maph[int(enx)][int(eny)] != 0:\r\n enx, eny = 0, 0\r\n else:\r\n seenx, seeny, lock = enx, eny, 0\r\n screen.blit(font2.render(\" Enemy Respawning! \", 1, pg.Color(\"red\"), pg.Color(\"grey\")),(300,50))\r\n pg.mixer.Channel(1).play(respawnfx)\r\n else:\r\n dtp = (enx-posx)**2 + (eny-posy)**2\r\n if dtp < 1:\r\n score -= 1\r\n endmsg = \" You died! Current score: \" + str(score)\r\n pg.mixer.Channel(1).play(failfx)\r\n enx, eny, seenx, seeny, lock = 0, 0, 0, 0, 0\r\n pause = 1\r\n surf = pg.surfarray.make_surface((np.rot90(255-pixels*255)).astype('uint8'))\r\n surf = pg.transform.smoothscale(surf, (800, 600))\r\n screen.blit(surf, (0, 0))\r\n elif dtp > 300:\r\n enx, eny, seenx, seeny, lock = 0, 0, 0, 0, 0\r\n run = 0\r\n\r\n ticks = pg.time.get_ticks()/100000\r\n lx = size/2 + 1000*np.cos(ticks)\r\n ly = size/2 + 1000*np.sin(ticks)\r\n posx, posy, rot, rot_v, shoot = movement(pressed_keys,posx, posy, rot, rot_v, maph, et, shoot, sstart)\r\n pg.mouse.set_pos([400, 300])\r\n mplayer = np.zeros([size, size])\r\n enx, eny, mplayer, et, shoot, sx, sy, sdir,seenx, seeny, lock = agents(enx, eny, maph, posx, posy, rot, et, shoot, sx, sy, sdir, mplayer, seenx, seeny, lock)\r\n if run and (seenx == posx or seeny == posy):\r\n run = False\r\n pg.mixer.Channel(1).play(runfx)\r\n else:\r\n clock.tick(30)\r\n screen.blit(font2.render(\" FinFET's PyTracing Maze \", 1, pg.Color(\"red\")),(45,45))\r\n screen.blit(font2.render(\" FinFET's PyTracing Maze \", 1, pg.Color(\"blue\")),(55,55))\r\n screen.blit(font2.render(\" FinFET's PyTracing Maze \", 1, pg.Color(\"white\")),(50,50))\r\n screen.blit(font2.render(endmsg, 1, pg.Color(\"salmon\"), (100, 34, 60)),(50,320))\r\n if (int(posx) == exitx and int(posy) == exity):\r\n screen.blit(font2.render(\" Your current score is \"+str(score), 1, pg.Color(\"grey\"), (80, 34, 80)),(50,390))\r\n else:\r\n screen.blit(font2.render(\" Press P to continue \", 1, pg.Color(\"grey\"), (80, 34, 80)),(50,390))\r\n screen.blit(font2.render(\" Press N for a new game \", 1, pg.Color(\"grey\"), (45, 34, 100)),(50,460))\r\n screen.blit(font2.render(\" Press ESC to leave \", 1, pg.Color(\"grey\"), (13, 34, 139)),(50,530))\r\n\r\n \r\n pg.display.update()\r\n\r\n screen.blit(font2.render(endmsg, 1, pg.Color(\"salmon\"), (100, 34, 60)),(50,320))\r\n pg.mixer.fadeout(1000)\r\n pg.display.update()\r\n print(endmsg)\r\n pg.time.wait(2000)\r\n pg.quit()\r\n\r\ndef maze_generator(x, y, size):\r\n \r\n mr = np.random.uniform(0,1, (size,size)) \r\n mg = np.random.uniform(0,1, (size,size)) \r\n mb = np.random.uniform(0,1, (size,size)) \r\n mapr = np.random.choice([0, 0, 0, 0, 1], (size,size))\r\n maps = np.random.choice([0, 0, 0, 0, 1], (size,size))\r\n mapt = np.random.choice([0, 0, 0, 1, 2], (size,size))\r\n maptemp = np.random.choice([0,0, 1], (size,size))\r\n maph = np.random.uniform(0.25, 0.99, (size,size))\r\n maph[np.where(maptemp == 0)] = 0\r\n maph[0,:], maph[size-1,:], maph[:,0], maph[:,size-1] = (1,1,1,1)\r\n maps[0,:], maps[size-1,:], maps[:,0], maps[:,size-1] = (0,0,0,0)\r\n\r\n maph[x][y], mapr[x][y] = (0, 0)\r\n count = 0 \r\n while 1:\r\n testx, testy = (x, y)\r\n if np.random.uniform() > 0.5:\r\n testx = testx + np.random.choice([-1, 1])\r\n else:\r\n testy = testy + np.random.choice([-1, 1])\r\n if testx > 0 and testx < size -1 and testy > 0 and testy < size -1:\r\n if maph[testx][testy] == 0 or count > 5:\r\n count = 0\r\n x, y = (testx, testy)\r\n maph[x][y], mapr[x][y] = (0, 0)\r\n if x == size-2:\r\n exitx, exity = (x, y)\r\n break\r\n else:\r\n count = count+1\r\n \r\n return mr, mg, mb, maph, mapr, exitx, exity, mapt, maps\r\n\r\ndef movement(pressed_keys,posx, posy, rot, rot_v, maph, et, shoot, sstart):\r\n \r\n x, y = (posx, posy)\r\n p_mouse = pg.mouse.get_pos()\r\n rot, rot_v = rot - np.clip((p_mouse[0]-400)/200, -0.2, .2), rot_v -(p_mouse[1]-300)/400\r\n rot_v = np.clip(rot_v, -1, 1)\r\n\r\n if pressed_keys[pg.K_UP] or pressed_keys[ord('w')]:\r\n x, y = (x + et*np.cos(rot), y + et*np.sin(rot))\r\n \r\n if pressed_keys[pg.K_DOWN] or pressed_keys[ord('s')]:\r\n x, y = (x - et*np.cos(rot), y - et*np.sin(rot))\r\n \r\n if pressed_keys[pg.K_LEFT] or pressed_keys[ord('a')]:\r\n x, y = (x - et*np.sin(rot), y + et*np.cos(rot))\r\n \r\n if pressed_keys[pg.K_RIGHT] or pressed_keys[ord('d')]:\r\n x, y = (x + et*np.sin(rot), y - et*np.cos(rot))\r\n \r\n if maph[int(x)][int(y)] == 0:\r\n posx, posy = (x, y)\r\n\r\n if not shoot and sstart == None and pressed_keys[pg.K_SPACE]:\r\n shoot = 1\r\n \r\n return posx, posy, rot, rot_v, shoot\r\n \r\n@njit(fastmath=True)\r\ndef super_fast(width, height, mod, inc, posx, posy, posz, rot, rot_v, mr, mg, mb, lx, ly, lz, maph, exitx, exity, mapr, mapt, maps, pr, pg, pb, enx, eny, sx, sy, size):\r\n \r\n texture=[[ .95, .99, .97, .8], # brick wall\r\n [ .97, .95, .96, .85],\r\n [.8, .85, .8, .8],\r\n [ .93, .8, .98, .96],\r\n [ .99, .8, .97, .95],\r\n [.8, .85, .8, .8]]\r\n\r\n idx = 0\r\n for j in range(height): #vertical loop \r\n rot_j = rot_v + np.deg2rad(24 - j/mod)\r\n sinzo = inc*np.sin(rot_j)\r\n coszo = inc*np.sqrt(abs(np.cos(rot_j))) \r\n for i in range(width): #horizontal vision loop\r\n rot_i = rot + np.deg2rad(i/mod - 30)\r\n x, y, z = (posx, posy, posz)\r\n sin, cos, sinz = coszo*np.sin(rot_i), coszo*np.cos(rot_i), sinzo\r\n \r\n modr = 1\r\n cx, cy, c1r, c2r, c3r = 1, 1, 1, 1, 1\r\n shot, enem, mapv = 0, 0, 0\r\n dtp = np.random.uniform(0.002,0.01)\r\n while 1:\r\n if (mapv == 0 or (sinz > 0 and (z > mapv or (mapv==6 and (z>0.4 or z <0.2)) or(z > 0.57 and mapv > 1)))): ## LoDev DDA for optimization\r\n \r\n norm = np.sqrt(cos**2 + sin**2 + sinz**2)\r\n rayDirX, rayDirY, rayDirZ = cos/norm + 1e-16, sin/norm + 1e-16, sinz/norm + 1e-16\r\n \r\n mapX, mapY = int(x), int(y)\r\n\r\n deltaDistX, deltaDistY, deltaDistZ= abs(1/rayDirX), abs(1/rayDirY), abs(1/rayDirZ)\r\n\r\n if (rayDirX < 0):\r\n stepX, sideDistX = -1, (x - mapX) * deltaDistX\r\n else:\r\n stepX, sideDistX = 1, (mapX + 1.0 - x) * deltaDistX\r\n \r\n if (rayDirY < 0):\r\n stepY, sideDistY = -1, (y - mapY) * deltaDistY\r\n else:\r\n stepY, sideDistY = 1, (mapY + 1 - y) * deltaDistY\r\n\r\n if (rayDirZ < 0):\r\n sideDistZ = z*deltaDistZ;\r\n else:\r\n sideDistZ = (1-z)*deltaDistZ\r\n\r\n while (1):\r\n if (sideDistX < sideDistY):\r\n sideDistX += deltaDistX; mapX += stepX\r\n dist = sideDistX; side = 0\r\n if mapX < 1 or mapX > size-2:\r\n break\r\n else:\r\n sideDistY += deltaDistY; mapY += stepY\r\n dist = sideDistY; side = 1\r\n if mapY < 1 or mapY > size-2:\r\n break\r\n if (maph[mapX][mapY] != 0):\r\n break\r\n \r\n if (side):\r\n dist = dist - deltaDistY\r\n else:\r\n dist = dist - deltaDistX\r\n \r\n if (dist > sideDistZ):\r\n dist = sideDistZ\r\n\r\n x = x + rayDirX*dist - cos/2\r\n y = y + rayDirY*dist - sin/2\r\n z = z + rayDirZ*dist - sinz/2\r\n \r\n ## end of LoDev DDA\r\n \r\n x += cos; y += sin; z += sinz\r\n if (z > 1 or z < 0): # check ceiling and floor\r\n break\r\n mapv = maph[int(x)][int(y)]\r\n if mapv > 1 and z < 0.57:\r\n if mapv == 2 or mapv == 8:\r\n if z> 0.45 and (x-posx)**2 + (y-posy)**2 + (z-0.5)**2 < 0.005 :\r\n break\r\n if z < 0.45 and z > 0.3 and (x-posx)**2 + (y-posy)**2 < (z/10 - 0.02):\r\n break\r\n if z < 0.3 and (x-posx)**2 + (y-posy)**2 + (z-0.15)**2 < 0.023 :\r\n break\r\n if mapv == 3 or mapv == 9:\r\n enem = 1\r\n if z> 0.45 and (x-enx)**2 + (y-eny)**2 + (z-0.5)**2 < 0.005 :\r\n break\r\n if z < 0.45 and z > 0.3 and (x-enx)**2 + (y-eny)**2 < (z/10 - 0.02):\r\n break\r\n if z < 0.3 and (x-enx)**2 + (y-eny)**2 + (z-0.15)**2 < 0.023 :\r\n break\r\n if mapv > 5 and z < 0.4 and z > 0.2:\r\n if ((x-sx)**2 + (y-sy)**2 + (z-0.3)**2 < dtp):#0.01):\r\n shot = 1\r\n break\r\n\r\n if mapv > z and mapv < 2: # check walls\r\n if maps[int(x)][int(y)]: # check spheres\r\n if ((x-int(x)-0.5)**2 + (y-int(y)-0.5)**2 + (z-int(z)-0.5)**2 < 0.25):\r\n if (mapr[int(x)][int(y)]): # spherical mirror\r\n if (modr == 1):\r\n cx, cy = int(x), int(y)\r\n modr = modr*0.7\r\n if (modr < 0.2):\r\n break\r\n if (mapv - z <= abs(sinz) ): ## horizontal surface\r\n sinz = -sinz\r\n else:\r\n nx = (x-int(x)-0.5)/0.5; ny = (y-int(y)-0.5)/0.5; nz =(z-int(z)-0.5)/0.5\r\n dot = 2*(cos*nx + sin*ny + sinz*nz)\r\n cos = (cos - nx*dot); sin = (sin - ny*dot); sinz = (sinz - nz*dot) \r\n x += cos; y += sin; z += sinz\r\n else:\r\n break\r\n \r\n \r\n elif mapr[int(x)][int(y)]: # check reflections\r\n if modr == 1:\r\n cx, cy = int(x), int(y)\r\n modr = modr*0.7\r\n if modr < 0.2:\r\n break\r\n if abs(z-maph[int(x)][int(y)]) < abs(sinz):\r\n sinz = -sinz\r\n elif maph[int(x+cos)][int(y-sin)] == maph[int(x)][int(y)]:\r\n cos = -cos\r\n else:\r\n sin = -sin\r\n else:\r\n break\r\n\r\n \r\n if z > 1: # ceiling\r\n deltaDistZ = (lz-z)*deltaDistZ\r\n x += deltaDistZ*rayDirX; y += deltaDistZ*rayDirY; z = lz\r\n dtol = np.sqrt((x-lx)**2+(y-ly)**2)\r\n\r\n if dtol < 50: #light source\r\n shot = 1\r\n c1, c2, c3 = 1, 1, 0.5\r\n else:\r\n angle = np.rad2deg(np.arctan((y-ly)/(x-lx)))/np.random.uniform(12,15)\r\n sh = (0.8+ abs(angle - int(angle))/5)/(dtol/1000)\r\n if sh > 1:\r\n sh = 1\r\n if int(angle)%2 == 1:\r\n c1, c2, c3 = 0.8*(1-sh), 0.86*(1-sh/4), (1-sh/10)\r\n else:\r\n c1, c2, c3 = 0.8*(1-sh), 0.9*(1-sh/4), (1-sh/10)\r\n if sx != -1:\r\n c1, c2, c3 = 0.7*c1, 0.7*c2, 0.7*c3\r\n \r\n elif z < 0: # floor\r\n z = 0\r\n if int(x*2)%2 == int(y*2)%2:\r\n c1, c2, c3 = .8,.8,.8\r\n else:\r\n if int(x) == exitx and int(y) == exity: #exit\r\n c1, c2, c3 = 0,0,.6\r\n else:\r\n c1, c2, c3 = .1,.1,.1\r\n \r\n elif mapv < 2: # walls\r\n c1, c2, c3 = mr[int(x)][int(y)], mg[int(x)][int(y)], mg[int(x)][int(y)]\r\n if mapt[int(x)][int(y)]: # textured walls\r\n if y%1 < 0.05 or y%1 > 0.95:\r\n ww = int((x*3)%1*4)\r\n else:\r\n ww = int((y*3)%1*4)\r\n if x%1 < 0.95 and x%1 > 0.05 and y%1 < 0.95 and y%1 > 0.05:\r\n zz = int(x*5%1*6)\r\n else:\r\n zz = int(z*5%1*6)\r\n text = texture[zz][ww]\r\n c1, c2, c3 = c1*text, c2*text, c3*text\r\n\r\n if mapv - z <= abs(sinz):\r\n z = mapv\r\n elif not maps[int(x)][int(y)]:\r\n if int(x-cos) != int(x):\r\n x = max(int(x-cos), int(x))\r\n modr = modr*0.80\r\n else:\r\n y = max(int(y-sin), int(y))\r\n modr = modr*0.9\r\n else:\r\n if shot:\r\n sh = ((x-sx)**2 + (y-sy)**2 + (z-0.3)**2)/0.012\r\n c1, c2, c3 = 1, 0.6*sh+0.2 , 0.2*sh+0.1 # shot\r\n elif z> 0.45:\r\n c1, c2, c3 = 0.6, 0.3, 0.3 # Head\r\n elif z > 0.3:\r\n c1, c2, c3 = 0.3, 0.5, 0.5 # Chest\r\n else:\r\n if enem:\r\n c1, c2, c3 = 1, 0.2, 0.2 # Roller red\r\n else:\r\n c1, c2, c3 = 0.2, 0.2, 1 # Roller blue\r\n\r\n if modr <= 0.7 and not shot:\r\n c1r, c2r, c3r = mr[cx][cy], mg[cx][cy], mg[cx][cy]\r\n\r\n if not shot and z < 1:\r\n dtp = np.sqrt((x-posx)**2+(y-posy)**2+(z-posz)**2)\r\n if dtp > 7:\r\n modr = modr/np.log((dtp-6)/4+np.e)\r\n\r\n if z < 1: # shadows\r\n if sx != -1 and maph[int(sx)][int(sy)] > 1:\r\n shot, c3 = 1, c3 * 0.9\r\n dtol = np.sqrt((x-sx)**2+(y-sy)**2+(z-0.35)**2)\r\n cos, sin, sinz = .01*(sx-x)/dtol, .01*(sy-y)/dtol, .01*(0.35-z)/dtol\r\n else:\r\n dtol = np.sqrt((x-lx)**2+(y-ly)**2+(z-lz)**2)\r\n cos, sin, sinz = .01*(lx-x)/dtol, .01*(ly-y)/dtol, .01*(lz-z)/dtol\r\n x += cos; y += sin; z += sinz\r\n mapv = maph[int(x)][int(y)]\r\n if z < mapv and mapv < 1 and not maps[int(x)][int(y)]:\r\n modr = modr*0.39\r\n while modr > 0.45:\r\n if (mapv == 0) or not shot and ((z > mapv) or (z > 0.57 and mapv > 1)): ## LoDev DDA for optimization\r\n \r\n norm = np.sqrt(cos**2 + sin**2 + sinz**2)\r\n rayDirX, rayDirY, rayDirZ = cos/norm + 1e-16, sin/norm + 1e-16, sinz/norm + 1e-16\r\n \r\n mapX, mapY = int(x), int(y)\r\n\r\n deltaDistX, deltaDistY, deltaDistZ= abs(1/rayDirX), abs(1/rayDirY), abs(1/rayDirZ)\r\n\r\n if (rayDirX < 0):\r\n stepX, sideDistX = -1, (x - mapX) * deltaDistX\r\n else:\r\n stepX, sideDistX = 1, (mapX + 1.0 - x) * deltaDistX\r\n \r\n if (rayDirY < 0):\r\n stepY, sideDistY = -1, (y - mapY) * deltaDistY\r\n else:\r\n stepY, sideDistY = 1, (mapY + 1 - y) * deltaDistY\r\n\r\n if (rayDirZ < 0):\r\n sideDistZ = z*deltaDistZ;\r\n else:\r\n sideDistZ = (1-z)*deltaDistZ\r\n\r\n while (1):\r\n if (sideDistX < sideDistY):\r\n sideDistX += deltaDistX; mapX += stepX\r\n dist = sideDistX; side = 0\r\n if mapX < 1 or mapX > size-2:\r\n break\r\n else:\r\n sideDistY += deltaDistY; mapY += stepY\r\n dist = sideDistY; side = 1\r\n if mapY < 1 or mapY > size-2:\r\n break\r\n if (maph[mapX][mapY] != 0):\r\n break\r\n \r\n if (side):\r\n dist = dist - deltaDistY\r\n else:\r\n dist = dist - deltaDistX\r\n \r\n if (dist > sideDistZ):\r\n dist = sideDistZ\r\n\r\n x = x + rayDirX*dist - cos/2\r\n y = y + rayDirY*dist - sin/2\r\n z = z + rayDirZ*dist - sinz/2\r\n \r\n ## end of LoDev DDA\r\n x += cos; y += sin; z += sinz\r\n mapv = maph[int(x)][int(y)]\r\n if shot:\r\n if mapv > 5 or (sinz > 0 and z > 0.35) or (sinz < 0 and z < 0.35):\r\n break\r\n elif z >1:\r\n break\r\n if z < 0.57 and mapv > 1:\r\n if mapv == 3 or mapv == 9:\r\n if z> 0.45 and (x-enx)**2 + (y-eny)**2 + (z-0.5)**2 < 0.005 :\r\n modr = modr*0.67\r\n elif z < 0.45 and z > 0.3 and (x-enx)**2 + (y-eny)**2 < (z/10 - 0.02):\r\n modr = modr*0.67\r\n elif z < 0.3 and (x-enx)**2 + (y-eny)**2 + (z-0.15)**2 < 0.023 :\r\n modr = modr*0.67\r\n elif mapv == 2 or mapv == 8:\r\n if z> 0.45 and (x-posx)**2 + (y-posy)**2 + (z-0.5)**2 < 0.005 :\r\n modr = modr*0.67\r\n elif z < 0.45 and z > 0.3 and (x-posx)**2 + (y-posy)**2 < (z/10 - 0.02):\r\n modr = modr*0.67\r\n elif z < 0.3 and (x-posx)**2 + (y-posy)**2 + (z-0.15)**2 < 0.023 :\r\n modr = modr*0.67\r\n \r\n if mapv > 0 and z <= mapv and mapv < 2: \r\n if maps[int(x)][int(y)]: # check spheres\r\n if ((x-int(x)-0.5)**2 + (y-int(y)-0.5)**2 + (z-int(z)-0.5)**2 < 0.25):\r\n modr = modr*0.9\r\n else: \r\n modr = modr*0.9 \r\n \r\n pr[idx] = modr*np.sqrt(c1*c1r)\r\n pg[idx] = modr*np.sqrt(c2*c2r)\r\n pb[idx] = modr*np.sqrt(c3*c3r)\r\n idx += 1\r\n \r\n return pr, pg, pb\r\n\r\ndef adjust_resol(width):\r\n height = int(0.75*width)\r\n mod = width/64\r\n inc = 0.02/mod\r\n rr = np.random.uniform(0,1,width * height)\r\n gg = np.random.uniform(0,1,width * height)\r\n bb = np.random.uniform(0,1,width * height)\r\n## print('Resolution: ', width, height)\r\n return width, height, mod, inc, rr, gg, bb\r\n\r\n@njit(fastmath=True)\r\ndef agents(enx, eny, maph, posx, posy, rot, et, shoot, sx, sy, sdir, mplayer, seenx, seeny, lock):\r\n \r\n if enx != 0:\r\n if not lock or np.random.uniform(0,1) > 0.99:\r\n dtp = np.sqrt((enx-posx)**2 + (eny-posy)**2)\r\n cos, sin = (posx-enx)/dtp, (posy-eny)/dtp\r\n x, y = enx, eny\r\n for i in range(300):\r\n x += 0.04*cos; y += 0.04*sin\r\n if maph[int(x)][int(y)] != 0:\r\n lock = 0\r\n break\r\n if(int(x) == int(posx) and int(y) == int(posy)):\r\n seenx, seeny = posx, posy\r\n lock = 1\r\n break\r\n\r\n if int(enx) == int(seenx) and int(eny) == int(seeny):\r\n if not lock:\r\n if shoot:\r\n seenx, seeny = np.random.uniform(enx, posx), np.random.uniform(eny, posy)\r\n else:\r\n seenx, seeny = np.random.normal(enx, 2), np.random.normal(eny, 2) \r\n else:\r\n seenx, seeny = np.random.normal(posx, 2), np.random.normal(posy, 2)\r\n \r\n dtp = np.sqrt((enx-seenx)**2 + (eny-seeny)**2) \r\n cos, sin = (seenx-enx)/dtp, (seeny-eny)/dtp \r\n x, y = enx + et*(cos+np.random.normal(0,.5)), eny + et*(sin+np.random.normal(0,.5))\r\n\r\n if maph[int(x)][int(y)] == 0:\r\n enx, eny = x, y\r\n else:\r\n if np.random.uniform(0,1) > 0.5:\r\n x, y = enx - et*(sin+np.random.normal(0,.5)), eny + et*(cos+np.random.normal(0,.5))\r\n else:\r\n x, y = enx + et*(sin+np.random.normal(0,.5)), eny - et*(cos+np.random.normal(0,.5))\r\n if maph[int(x)][int(y)] == 0:\r\n enx, eny = x, y\r\n else:\r\n seenx, seeny = enx+np.random.normal(0,3), eny+np.random.normal(0,3)\r\n lock = 0\r\n \r\n mplayer[int(enx)][int(eny)] = 3\r\n \r\n mplayer[int(posx)][int(posy)] = 2 \r\n if shoot:\r\n if sx == -1:\r\n sdir = rot+np.random.uniform(-.1,.1)\r\n sx, sy = posx + .5*np.cos(sdir), posy + .5*np.sin(sdir)\r\n sx, sy = sx + 5*et*np.cos(sdir), sy + 5*et*np.sin(sdir)\r\n if enx != 0 and (sx - enx)**2 + (sy - eny)**2 < 0.02:\r\n shoot, sx, sy, enx, eny, seenx, seeny = 0, -1, -1, 0, 0, 0, 0\r\n if maph[int(sx)][int(sy)] != 0:\r\n shoot, sx, sy = 0, -1, -1\r\n else: \r\n mplayer[int(sx)][int(sy)] += 6 \r\n \r\n \r\n mplayer = maph + mplayer\r\n return(enx, eny, mplayer, et, shoot, sx, sy, sdir, seenx, seeny, lock)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n",
"import numpy as np\nimport pygame as pg\nfrom numba import njit\n\ndef main():\n running, pause, fps_lock, score, maxscore, fullscreen = 1, 1, 59, 0, 0, 0\n timer, autores, checker, count, enhealth = 0, 1, 2, 0, 0\n renders = [' R: Standard. ', ' R: Doubled pixels. ', ' R: Checkerboard. ', ' R: Radial window. ', ' R: Squared window. ']\n endmsg = ' Numba compiling, please wait... '\n rr, gg, bb = np.linspace(0,0.8, 25*14), np.linspace(0.5,.1, 25*14), np.linspace(1,0.1, 25*14)\n drawing(rr, gg, bb, 14, 25, 1, endmsg, 0, 10, 10, np.zeros([3,3]), score, fullscreen, False)\n pg.time.wait(200)\n \n clock = pg.time.Clock()\n pg.mouse.set_visible(False)\n pg.mixer.init()\n ambient, runfx, shotfx, killfx, respawnfx, successfx, failfx, fr, fg, fb = sfx()\n ambient.set_volume(0.5)\n ambient.play(-1)\n endmsg = \" Numba may need more compiling...\"\n \n (mr, mg, mb, maph, mapr, exitx, exity, mapt, maps, posx, posy, posz, size, rot, rot_v, minimap,\n width, height, mod, rr, gg, bb, count, enx, eny, seenx, seeny, lock, run, shoot, sx, sy, sz, sstart,\n et, health, sdir, sdirz, sdir2, sdirz2, shoot2, sx2, sy2, sz2, sstart2, won, respawn, move) = new_game(fb, fg, fr, endmsg, score) \n\n while running:\n ticks = pg.time.get_ticks()/100000\n if np.random.uniform() > 0.99:\n pg.display.set_caption(endmsg + ' Options: P or C - Pause, F - Fulscreen, Q/W - FPS lock/Res, R - Render type, T - AutoRes ')\n for event in pg.event.get():\n if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE):\n if not pause:\n pause = 1\n respawnfx.play()\n endmsg = \" Game paused. Current score: \" + str(score) + ' '\n else:\n endmsg = \" Thanks for playing! Max score: \" + str(maxscore) + ' '\n killfx.play()\n running = False\n if sstart == None and(event.type == pg.MOUSEBUTTONDOWN or event.type == pg.MOUSEBUTTONUP):\n shoot = 1\n if event.type == pg.KEYDOWN:\n if event.key == ord('p') or event.key == ord('c'): # pause\n if not pause:\n pause = 1\n respawnfx.play()\n endmsg = \" Game paused. Current score: \" + str(score)\n elif (int(posx) != exitx or int(posy) != exity):\n if health == 0:\n health = 5\n animate(width, height, mod, move, posx, posy, .01, rot, rot_v, mr, mg, mb, lx, ly, lz,\n mplayer, exitx, exity, mapr, mapt, maps, rr, gg, bb, enx, eny, sx, sy, sx2, sy2,\n size, checker, count,fb, fg, fr, pause, endmsg, won, health, minimap, score, .5/61, fps)\n pause = 0\n respawnfx.play()\n if pause and event.key == ord('n'): # new game\n pause = 0\n (mr, mg, mb, maph, mapr, exitx, exity, mapt, maps, posx, posy, posz, size, rot, rot_v, minimap,\n width, height, mod, rr, gg, bb, count, enx, eny, seenx, seeny, lock, run, shoot, sx, sy, sz, sstart,\n et, health, sdir, sdirz, sdir2, sdirz2, shoot2, sx2, sy2, sz2, sstart2, won, respawn, move) = new_game(fb, fg, fr, endmsg, score)\n \n respawnfx.play()\n \n if event.key == ord('t'): # toggle auto resolution\n autores = not(autores)\n if event.key == ord('r'): # toggle rendering method\n checker += 1\n if checker > 4:\n checker = 0\n if event.key == ord('f'): # toggle fullscreen\n pg.display.toggle_fullscreen()\n fullscreen = not(fullscreen)\n if event.key == ord('q'): # change resolution or fps\n if autores:\n fps_lock = max(19, fps_lock - 10)\n else:\n if width > 100 :\n width, height, mod, rr, gg, bb, count = adjust_resol(int(width*0.8))\n if event.key == ord('e'): # change resolution or fps\n if autores:\n fps_lock = min(120, fps_lock + 10)\n else:\n width, height, mod, rr, gg, bb, count = adjust_resol(int(width*1.1))\n \n if pause:\n clock.tick(30)\n drawing(rr*.7, gg*.7, bb*.7, height, width, pause, endmsg, won, health, enhealth, minimap, score, fullscreen)\n\n else:\n mplayer = np.zeros([size, size])\n (enx, eny, mplayer, et, shoot, sx, sy, sz, sdir, sdirz, shoot2,\n sx2, sy2, sz2, sdir2, sdirz2, seenx, seeny, lock, enhealth, health) = agents(enx, eny, maph, posx, posy, rot, rot_v, et, shoot, sx, sy, sz, sdir,\n sdirz, shoot2, sx2, sy2, sz2, sdir2, sdirz2, mplayer,\n seenx, seeny, lock, size, enhealth, health, score)\n\n lx, ly, lz = size/2 + 1500*np.cos(ticks), size/2 + 1000*np.sin(ticks), 1000\n rwr = checker\n if shoot2:\n rwr = 3\n rr, gg, bb = super_fast(width, height, mod, move, posx, posy, posz, rot, rot_v, mr, mg, mb, lx, ly, lz,\n mplayer, exitx, exity, mapr, mapt, maps, rr, gg, bb, enx, eny, sx, sy, sx2, sy2,\n size, rwr, count, fb, fg, fr, sz, sz2)\n count += 1\n if enhealth != 0 and lock:\n endmsg = 'Pytracing Maze - Watch out! Score:'+str(score)+' Res: '+ str(width) +'x'+str(height)+' FPS: '+str(int(clock.get_fps()))+renders[checker]\n else:\n endmsg = 'Pytracing Maze - Find the exit! Score:'+str(score)+' Res: '+ str(width) +'x'+str(height)+' FPS: '+str(int(clock.get_fps()))+renders[checker]\n\n minimap[int(posy)][int(posx)] = (50, 50, 255)\n drawing(rr, gg, bb, height, width, pause, endmsg, won, health, enhealth, minimap, score, fullscreen)\n minimap[int(posy)][int(posx)] = (100, 100, 0)\n \n fps = int(1000/(pg.time.get_ticks() - ticks*100000 +1e-16))\n if autores and count > 10: #auto adjust render resolution\n if fps < fps_lock - 10 and width > 100:\n width, height, mod, rr, gg, bb, count = adjust_resol(int(width*0.8))\n elif fps > fps_lock + 15:\n width, height, mod, rr, gg, bb, count = adjust_resol(int(width*1.1)) \n\n if (int(posx) == exitx and int(posy) == exity):\n endmsg, won = \" You escaped safely! \", 1\n successfx.play()\n animate(width, height, mod, move, posx, posy, .5, rot, rot_v, mr, mg, mb, lx, ly, lz,\n mplayer, exitx, exity, mapr, mapt, maps, rr, gg, bb, enx, eny, sx, sy, sx2, sy2,\n size, checker, count,fb, fg, fr, pause, endmsg, won, health, minimap, score, .5/61, clock.get_fps())\n pause = 1\n score += 1\n maxscore = max(score, maxscore) \n \n et = min(clock.tick()/500, 0.1)*(0.8+move)\n\n if shoot or sstart != None:\n if sstart == None:\n shotfx.play()\n if fps < fps_lock and autores:\n width, height, mod, rr, gg, bb, count = adjust_resol(int(width*0.8))\n sstart = pg.time.get_ticks()\n elif pg.time.get_ticks() - sstart > 500:\n shoot, sx, sy, sstart = 0, -1, -1, None\n\n if enhealth == 0:\n if not respawn:\n if shoot:\n health = min(health+5, 10)\n shoot2, sx2, sy2, run, respawn, sstart2 = 0, -1, -1, 1, 1, None\n killfx.play()\n \n else:\n if respawn:\n respawn = 0\n respawnfx.play()\n if shoot2 or sy2 == 0 or sstart2 != None:\n if run:\n run = 0\n runfx.play()\n if sstart2 == None:\n shotfx.play()\n sstart2 = pg.time.get_ticks()\n elif pg.time.get_ticks() - sstart2 > 500:\n shoot2, sx2, sy2, sstart2 = 0, -1, -1, None\n\n if health <= 0:\n won, pause, health = -1, 1, 0\n if score > 0:\n score -= 1\n endmsg = \" You died! Current score: \" + str(score) + ' '\n failfx.play()\n animate(width, height, mod, move, posx, posy, .5, rot, rot_v, mr, mg, mb, lx, ly, lz,\n mplayer, exitx, exity, mapr, mapt, maps, rr, gg, bb, enx, eny, sx, sy, sx2, sy2,\n size, checker, count,fb, fg, fr, pause, endmsg, won, health, minimap, score, -.5/61, clock.get_fps())\n enx, eny, seenx, seeny, lock, won, enhealth = 0, 0, 0, 0, 0, 0, 0\n\n\n posx, posy, rot, rot_v, shoot, move = movement(pg.key.get_pressed(),posx, posy, rot, rot_v, maph, et, shoot, sstart, move)\n pg.mouse.set_pos([640, 360])\n \n \n \n pg.display.update()\n\n pg.mixer.fadeout(1000)\n print(endmsg)\n posz, ani = 0.5, .5/61\n if health <= 0:\n posz, ani = 0.01, .99/61\n elif int(posx) == exitx and int(posy) == exity:\n posz, ani = 0.99, -.99/61\n \n animate(width, height, mod, move, posx, posy, posz, rot, rot_v, mr, mg, mb, size/2 + 1500, size/2 + 1000, 1000,\n maph, exitx, exity, mapr, mapt, maps, rr, gg, bb, enx, eny, sx, sy, sx2, sy2,\n size, checker, count,fb, fg, fr, pause, endmsg, won, health, minimap, score, ani, fps)\n \n pg.quit()\n\ndef new_map(score):\n size = np.random.randint(20+score*5,30+score*10) # size of the map\n posx, posy, posz = np.random.randint(1, size -2)+0.5, np.random.randint(1, size -2)+0.5, 0.5\n x, y = int(posx), int(posy)\n rot, rot_v = (np.pi/4, 0)\n \n mr, mg, mb = np.random.uniform(0,1, (size,size)), np.random.uniform(0,1, (size,size)), np.random.uniform(0,1, (size,size)) \n mapr = np.random.choice([0, 0, 0, 0, 1], (size,size))\n maps = np.random.choice([0, 0, 0, 0, 1], (size,size))\n mapt = np.random.choice([0, 0, 0, 1, 2, 3], (size,size))\n maptemp = np.random.choice([0,0, 1], (size,size))\n maph = np.random.uniform(0.25, 0.99, (size,size))\n maph[np.where(maptemp == 0)] = 0\n maph[0,:], maph[size-1,:], maph[:,0], maph[:,size-1] = (1,1,1,1) # outer walls\n maps[0,:], maps[size-1,:], maps[:,0], maps[:,size-1] = (0,0,0,0) # no spheres\n\n maph[x][y], mapr[x][y] = (0, 0)\n count = 0 \n while 1:\n testx, testy = (x, y)\n if np.random.uniform() > 0.5:\n testx = testx + np.random.choice([-1, 1])\n else:\n testy = testy + np.random.choice([-1, 1])\n if testx > 0 and testx < size -1 and testy > 0 and testy < size -1:\n if maph[testx][testy] == 0 or count > 5:\n count = 0\n x, y = (testx, testy)\n maph[x][y], mapr[x][y] = (0, 0)\n dtx = np.sqrt((x-posx)**2 + (y-posy)**2)\n if (dtx > size*.6 and np.random.uniform() > .99) or np.random.uniform() > .99999:\n exitx, exity = (x, y)\n break\n else:\n count = count+1\n \n return mr, mg, mb, maph, mapr, exitx, exity, mapt, maps, posx, posy, posz, size, rot, rot_v\n\ndef new_game(fb, fg, fr, endmsg, score):\n width, height, mod, rr, gg, bb, count = adjust_resol(200)\n mr, mg, mb, maph, mapr, exitx, exity, mapt, maps, posx, posy, posz, size, rot, rot_v = new_map(score)\n minimap = np.zeros((size, size, 3))\n animate(width, height, mod, 0, posx, posy, .99, rot, rot_v, mr, mg, mb, size/2 + 1500, size/2 + 1000, 1000, maph, exitx, exity, mapr, mapt, maps,\n rr, gg, bb, 0, 0, -1, -1, -1, -1, size, 2, 0, fb, fg, fr, 0, endmsg, 0, 10, minimap, score, -.5/61)\n \n return (mr, mg, mb, maph, mapr, exitx, exity, mapt, maps, posx, posy, posz, size, rot, rot_v, minimap, width, height, mod, rr, gg, bb, count,\n -1, -1, 0, 0, 0, 1, 0, -1, -1, -1, None, 0.1, 10, 0, 0, 0, 0, 0, -1, -1, -1, None, 0, 1, 0)\n#enx, eny, seenx, seeny, lock, run, shoot, sx, sy, sz, sstart, et, health, sdir, sdirz, sdir2, sdirz2, shoot2, sx2, sy2, sz2, sstart2, won, respawn, move\n\ndef movement(pressed_keys,posx, posy, rot, rot_v, maph, et, shoot, sstart, move):\n x, y = (posx, posy)\n p_mouse = pg.mouse.get_pos()\n rot, rot_v = rot - np.clip((p_mouse[0]-640)/200, -0.2, .2), rot_v -(p_mouse[1]-360)/400\n rot_v = np.clip(rot_v, -1, 1)\n diag = 0\n\n if pressed_keys[pg.K_UP] or pressed_keys[ord('w')]:\n diag = 0.5\n x, y, move, diag = x + et*np.cos(rot), y + et*np.sin(rot), move + et/4, 1\n\n elif pressed_keys[pg.K_DOWN] or pressed_keys[ord('s')]:\n x, y, move, diag = x - et*np.cos(rot), y - et*np.sin(rot), move - et/2, 1\n \n if pressed_keys[pg.K_LEFT] or pressed_keys[ord('a')]:\n et = et/(diag+1)\n x, y = x - et*np.sin(rot), y + et*np.cos(rot)\n \n elif pressed_keys[pg.K_RIGHT] or pressed_keys[ord('d')]:\n et = et/(diag+1)\n x, y = x + et*np.sin(rot), y - et*np.cos(rot)\n\n if x == posx and y == posy:\n move = move - et/2\n\n if maph[int(x-0.05)][int(y)] == 0 and maph[int(x+0.05)][int(y)] == 0 and maph[int(x)][int(y+0.05)] == 0:\n posx, posy = x, y \n elif maph[int(posx-0.05)][int(y)] == 0 and maph[int(posx+0.05)][int(y)] == 0 and maph[int(posx)][int(y+0.05)] == 0:\n posy = y\n elif maph[int(x-0.05)][int(posy)] == 0 and maph[int(x+0.05)][int(posy)] == 0 and maph[int(x)][int(posy+0.05)] == 0:\n posx = x\n else:\n move = move - et/2\n \n if not shoot and sstart == None and pressed_keys[pg.K_SPACE]:\n shoot = 1\n move = np.clip(move, 0, 0.4)\n return posx, posy, rot, rot_v, shoot, move\n\n@njit(cache=True)\ndef lodev(x, y, z, cos, sin, sinz, maph, size):\n norm = np.sqrt(cos**2 + sin**2 + sinz**2)\n rayDirX, rayDirY, rayDirZ = cos/norm + 1e-16, sin/norm + 1e-16, sinz/norm + 1e-16\n \n mapX, mapY = int(x), int(y)\n\n deltaDistX, deltaDistY, deltaDistZ= abs(1/rayDirX), abs(1/rayDirY), abs(1/rayDirZ)\n\n if (rayDirX < 0):\n stepX, sideDistX = -1, (x - mapX) * deltaDistX\n else:\n stepX, sideDistX = 1, (mapX + 1.0 - x) * deltaDistX\n \n if (rayDirY < 0):\n stepY, sideDistY = -1, (y - mapY) * deltaDistY\n else:\n stepY, sideDistY = 1, (mapY + 1 - y) * deltaDistY\n\n if (rayDirZ < 0):\n sideDistZ = z*deltaDistZ;\n else:\n sideDistZ = (1-z)*deltaDistZ\n\n while (1):\n if (sideDistX < sideDistY):\n sideDistX += deltaDistX; mapX += stepX\n dist = sideDistX; side = 0\n if mapX < 2 or mapX > size-2:\n break\n else:\n sideDistY += deltaDistY; mapY += stepY\n dist = sideDistY; side = 1\n if mapY < 2 or mapY > size-2:\n break\n if (maph[mapX][mapY] != 0):\n break\n \n if (side):\n dist = dist - deltaDistY\n else:\n dist = dist - deltaDistX\n \n if (dist > sideDistZ):\n dist = sideDistZ\n\n x = x + rayDirX*dist - cos/2\n y = y + rayDirY*dist - sin/2\n z = z + rayDirZ*dist - sinz/2\n return x, y, z\n\n@njit(cache=True)\ndef ray_caster(posx, posy, posz, sin, cos, sinz, lx, ly, lz, maph, mapr, maps, enx, eny, sx, sy, sx2, sy2, size, sz, sz2):\n x, y, z = posx, posy, posz\n modr, cx, cy, shot, mapv = 1, 1, 1, 0, 0\n dtp = np.random.uniform(0.002,0.01)\n for k in range(2000):\n \n if (mapv == 0) or (sinz > 0 and (z > mapv or (mapv > 1 and mapv < 6 and z > 0.58))): ## LoDev DDA for optimization\n x, y, z = lodev(x, y, z, cos, sin, sinz, maph, size)\n \n x += cos; y += sin; z += sinz\n if (z > 1 or z < 0): # check ceiling and floor\n break\n mapv = maph[int(x)][int(y)]\n if (mapv == 2 or mapv == 8 or mapv == 14) and modr > 0.7:\n mapv = 0\n if mapv > 1 and z < 0.58: # check agents\n if mapv == 2 or mapv == 8 or mapv == 3 or mapv == 15:\n refx, refy, sh = posx, posy, .8\n if mapv%2 != 0:\n refx, refy, sh = enx, eny, .2 \n if z> 0.45 and (x-refx)**2 + (y-refy)**2 + (z-0.5)**2 < 0.003 +abs(z-0.47)/30 :\n break # head\n if z < 0.45 and z > 0.28 and (x-refx)**2 + (y-refy)**2 < (z/10 - 0.02):\n break # chest\n if z < 0.28 and (x-refx)**2 + (y-refy)**2 + (z-0.15)**2 < 0.023 :\n break #roller\n if mapv > 5:# and z < 0.4 and z > 0.2:\n refx, refy, refz = sx, sy, sz\n if mapv < 12:\n refx, refy, refz = sx2, sy2, sz2\n if ((x-refx)**2 + (y-refy)**2 + (z-refz)**2 < dtp):\n shot = 1\n break\n\n if mapv > z and mapv < 2: # check walls\n if maps[int(x)][int(y)]: # check spheres\n if ((x%1-0.5)**2 + (y%1-0.5)**2 + (z%1-0.5)**2 < 0.24):\n x, y, z = refine(x, y, z, sin, cos, sinz)\n if (mapr[int(x)][int(y)]): # spherical mirror\n if (modr == 1):\n cx, cy = int(x), int(y)\n modr = modr*0.7\n if (modr < 0.2):\n break\n if (mapv - z <= abs(sinz)): ## horizontal surface\n sinz = -sinz\n else:\n nx = (x%1-0.5)/0.5; ny = (y%1-0.5)/0.5; nz =(z%1-0.5)/0.5\n dot = 2*(cos*nx + sin*ny + sinz*nz)\n cos = (cos - nx*dot); sin = (sin - ny*dot); sinz = (sinz - nz*dot) \n x += cos; y += sin; z += sinz\n else:\n break\n \n elif mapr[int(x)][int(y)]: # check reflections\n if modr == 1:\n cx, cy = int(x), int(y)\n modr = modr*0.7\n if modr < 0.2:\n break\n if abs(z-maph[int(x)][int(y)]) < abs(sinz):\n sinz = -sinz\n elif maph[int(x+cos)][int(y-sin)] == maph[int(x)][int(y)]:\n cos = -cos\n else:\n sin = -sin\n else:\n break\n return x, y, z, modr, shot, mapv, refx, refy, refz, cx, cy, sin, cos, sinz, sh, shot\n\n@njit(cache=True)\ndef refine(x, y, z, sin, cos, sinz):\n x -= .9*cos; y -= .9*sin; z -= .9*sinz\n while ((x%1-0.5)**2 + (y%1-0.5)**2 + (z%1-0.5)**2 - 0.24 > 0):\n x += 0.1*cos; y += 0.1*sin; z += 0.1*sinz\n return x, y, z\n\n@njit(cache=True)\ndef shadow_ray(x, y, z, cos, sin, sinz, modr, shot, maps, enx, eny, posx, posy, posz, size, maph, limodr, refz):\n x += cos; y += sin; z += sinz # advance one step\n mapv = maph[int(x)][int(y)]\n if z < mapv and mapv < 1:# if already hit something apply dark shade\n if maps[int(x)][int(y)]:\n if ((x-int(x)-0.5)**2 + (y-int(y)-0.5)**2 + (z-int(z)-0.5)**2 < 0.24):\n modr = modr*0.39\n else:\n modr = modr*0.39\n\n for k in range(1000):\n if (mapv == 0) or not shot and ((z > mapv) or (z > 0.57 and mapv > 1)): ## LoDev DDA for optimization\n x, y, z = lodev(x, y, z, cos, sin, sinz, maph, size)\n x += cos; y += sin; z += sinz\n mapv = maph[int(x)][int(y)]\n if shot:\n if mapv > 5 or (sinz > 0 and z > refz) or (sinz < 0 and z < refz) or modr < limodr:\n break\n elif z >1 or modr < limodr:\n break\n if z < 0.58 and mapv > 1 and (mapv == 3 or mapv == 2 or mapv == 15 or mapv == 8):\n refx, refy, sh = enx, eny, .2\n if mapv%2 == 0:\n refx, refy, sh = posx, posy, .8\n if z> 0.45 and (x-refx)**2 + (y-refy)**2 + (z-0.5)**2 < 0.003 +abs(z-0.47)/30:\n modr = modr*0.67 # head\n if z < 0.45 and z > 0.28 and (x-refx)**2 + (y-refy)**2 < (z/10 - 0.02):\n modr = modr*0.67 # chest\n if z < 0.28 and (x-refx)**2 + (y-refy)**2 + (z-0.15)**2 < 0.023 :\n modr = modr*0.67 #roller\n \n if mapv > 0 and z <= mapv and mapv < 2: \n if maps[int(x)][int(y)]: # check spheres\n if ((x-int(x)-0.5)**2 + (y-int(y)-0.5)**2 + (z-int(z)-0.5)**2 < 0.25):\n modr = modr*0.9\n else: \n modr = modr*0.9\n return modr\n\n@njit(cache=True)\ndef get_color(x, y, z, modr, shot, mapv, refx, refy, refz, cx, cy, sin, cos, sinz, sh, mapt, maps, exitx, exity,\n mr, mg, mb, fr, fg, fb, lx, ly, lz, size):\n if z > 1: # ceiling\n norm = np.sqrt(cos**2 + sin**2 + sinz**2)\n rayDirX, rayDirY, rayDirZ = cos/norm + 1e-16, sin/norm + 1e-16, sinz/norm + 1e-16 \n deltaDistZ = (lz-z)/rayDirZ\n x += deltaDistZ*rayDirX; y += deltaDistZ*rayDirY; z = lz\n dtol = np.sqrt((x-lx)**2+(y-ly)**2)\n\n if dtol < 50: #light source\n c1, c2, c3, shot = 1, 1, 0.5, 1\n else:\n angle = np.rad2deg(np.arctan((y-ly)/(x-lx)))/np.random.uniform(12,15)\n sh = min((0.8+ abs(angle - int(angle))/5)/(dtol/1000), 1)\n if int(angle)%2 == 1:\n c1, c2, c3 = 0.82*(1-sh), 0.86*(1-sh/4), (1-sh/10)\n else:\n c1, c2, c3 = 0.8*(1-sh), 0.9*(1-sh/4), (1-sh/10)*0.9\n \n elif z < 0: # floor\n xx, sh = int(3*x%1*100) + int(3*y%1*100)*100, 0.3 + (x+y)/(3*size)\n c1, c2, c3, z = .85*(1-sh/2)*fg[xx], sh*fg[xx], 0.85*sh*fb[xx], 0\n if int(x) == exitx and int(y) == exity: #exit\n c3 = np.random.uniform(0.5, 1)\n \n elif mapv < 2: # walls\n c1, c2, c3 = mr[int(x)][int(y)], mg[int(x)][int(y)], mb[int(x)][int(y)]\n mapvt = mapt[int(x)][int(y)]\n if mapv - z <= abs(sinz): # round coordinates and pre shade\n z = mapv\n elif not maps[int(x)][int(y)]:\n if int(x-cos) != int(x):\n x = max(int(x-cos), int(x))\n modr = modr*0.80\n else:\n y = max(int(y-sin), int(y))\n modr = modr*0.9\n \n if mapvt > 1: # textured walls\n if z == mapv:\n xx = int(3*x%1*100) + 100*int(3*y%1*100)\n elif x%1 == 0:\n xx = int(3*z%1*100) + 100*int(3*y%1*100)\n else:\n xx = int(3*z%1*100) + 100*int(3*x%1*100)\n xx = fr[xx]\n c1, c2, c3 = c1*xx, c2*xx, c3*xx\n if mapvt%2 == 1: # gradient walls\n c1, c2, c3 = c1*(2+z)/3, c2*(3-z)/3, c3*(2+z**2)/3\n \n else: # agents\n if shot: # fireball\n sh = ((x-refx)**2 + (y-refy)**2 + (z-refz)**2)/0.012\n c1, c2, c3 = 1, 0.6*sh+0.2 , 0.2*sh+0.1 \n elif z> 0.45: # Head\n c1, c2, c3 = (1-z)*(1-sh), (1-z)*sh, z*sh \n elif z > 0.28: # Chest\n c1, c2, c3 = (z-0.28), (z-0.28)*(1-sh), (z-0.28)*sh \n else: # Roller\n c1, c2, c3 = refx%1*z*(1-sh), refy%1*0.2*sh, refy%1*z*sh\n\n return c1, c2, c3, modr, x, y, z, shot\n\n \n@njit(cache=True)\ndef super_fast(width, height, mod, move, posx, posy, posz, rot, rot_v, mr, mg, mb, lx, ly, lz,\n maph, exitx, exity, mapr, mapt, maps, pr, pg, pb, enx, eny, sx, sy, sx2, sy2,\n size, checker, count, fb, fg, fr, sz=0, sz2=0):\n \n inv, inv2, garbage, idx = (count%2), -(int(count/2)%2), not(count), 0\n if checker == 0:\n garbage = 0\n for j in range(height): #vertical loop \n rot_j = rot_v + (1+move**1.5)*np.deg2rad(24 - j/mod)\n sinzo = (0.04/mod)*np.sin(rot_j) \n coszo = (0.04/mod)*np.sqrt(abs(np.cos(rot_j))) \n for i in range(width): #horizontal vision loop\n if (checker == 1 or garbage) and idx%2 == 1:\n pr[idx], pg[idx], pb[idx] = pr[idx-1], pg[idx-1], pb[idx-1]\n else:\n if checker == 3: # radial\n rad = np.sqrt((i-width/2)**2 + (j-height/2)**2)\n elif checker == 4: # square\n rad = max(abs(i-width/2)*1, abs(j-height/2))\n \n if (checker < 2 or garbage or # standard and doubled pixels, first frame after res adjust\n (checker == 2 and ((inv and i%2 == j%2) or (not(inv) and i%2 != j%2))) or # checkerboard\n (checker > 2 and ((rad < height/2.9 and ((inv and i%2 == j%2) or (not(inv) and i%2 != j%2))) or # radial and square\n (rad > height/2.9 and rad < height/1.9 and (((i+2*inv)%3 == 0 and (j+2*inv2)%3 == 0))) or\n (rad > height/1.9 and (((i+3*inv)%5 == 0 and (j+3*inv2)%5 == 0)))))):\n \n rot_i = rot + (1+move**1.5)*np.deg2rad(i/mod - 30)\n si = 1\n if checker > 2:\n si = 2\n if rad > height/1.9:\n si = 3\n\n sin, cos, sinz = coszo*np.sin(rot_i), coszo*np.cos(rot_i), sinzo\n modr, cx, cy, c1r, c2r, c3r, shot, mapv = 1, 1, 1, 1, 1, 1, 0, 0\n \n x, y, z, modr, shot, mapv, refx, refy, refz, cx, cy, sin, cos, sinz, sh, shot = ray_caster(posx, posy, posz, sin, cos, sinz, lx, ly, lz, maph, mapr, maps,\n enx, eny, sx, sy, sx2, sy2, size, sz, sz2)\n\n c1, c2, c3, modr, x, y, z, shot = get_color(x, y, z, modr, shot, mapv, refx, refy, refz, cx, cy, sin, cos, sinz, sh, mapt, maps, exitx, exity,\n mr, mg, mb, fr, fg, fb, lx, ly, lz, size)\n\n if modr <= 0.7 and not shot: # tinted mirrors\n c1r, c2r, c3r = mr[cx][cy], mg[cx][cy], mg[cx][cy]\n\n if not shot and z < 1: # shadows\n limodr, refx, refy, refz = 0.4, lx, ly, lz\n dtp = np.sqrt((x-posx)**2+(y-posy)**2+(z-posz)**2)\n if dtp > 7:\n modr = modr/np.log((dtp-6)/4+np.e)\n if sx != -1 or sx2 != -1: # fireball\n refx, refy, refz, shot, c3 = sx2, sy2, sz2, 1, c3*0.9\n if sx != -1:\n refx, refy, refz = sx, sy, sz\n dtol = np.sqrt((x-refx)**2+(y-refy)**2+(z-refz)**2)\n cos, sin, sinz = .01*(refx-x)/dtol, .01*(refy-y)/dtol, .01*(refz-z)/dtol\n modr = shadow_ray(x, y, z, cos, sin, sinz, modr, shot, maps, enx, eny, posx, posy, posz, size, maph, limodr, refz)\n \n c1, c2, c3 = modr*np.sqrt(c1*c1r), modr*np.sqrt(c2*c2r), modr*np.sqrt(c3*c3r) \n\n\n \n if checker == 0 or garbage:\n pr[idx], pg[idx], pb[idx] = c1, c2, c3\n \n elif checker > 2 and rad > height/2.9 -1 :\n imin, imax, jmin, jmax = max(i-si, 0), min(i+si, width-1), max(j-si, 0), min(j+si, height-1)\n for jj in range(jmin, jmax):\n for ii in range(imin, imax):\n idx2 = ii + jj*width\n pr[idx2], pg[idx2], pb[idx2] = (3*c1 + pr[idx2])/4, (3*c2 + pg[idx2])/4, (3*c3 + pb[idx2])/4\n \n else:\n pr[idx], pg[idx], pb[idx] = (3*c1 + pr[idx])/4, (3*c2 + pg[idx])/4, (3*c3 + pb[idx])/4 \n idx += 1\n\n if checker != 0: # fill gaps and smoothing\n idx = 0\n for j in range(height): #vertical loop \n for i in range(width): #horizontal vision loop\n if (i > 0 and i < width -1 and j > 0 and j < height -1 and ((inv and i%2 != j%2) or (not(inv) and i%2 == j%2))):\n if abs(pr[idx-1] - pr[idx+1]) < 0.05 and abs(pg[idx-1] - pg[idx+1]) < 0.05 and abs(pb[idx-1] - pb[idx+1]) < 0.05 :\n pr[idx], pg[idx], pb[idx] = (pr[idx-1] + pr[idx+1])/2, (pg[idx-1] + pg[idx+1])/2, (pb[idx-1] + pb[idx+1])/2\n elif abs(pr[idx-width] - pr[idx+width]) < 0.05 and abs(pg[idx-width] - pg[idx+width]) < 0.05 and abs(pb[idx-width] - pb[idx+width]) < 0.05 :\n pr[idx], pg[idx], pb[idx] = (pr[idx-width] + pr[idx+width])/2, (pg[idx-width] + pg[idx+width])/2, (pb[idx-width] + pb[idx+width])/2\n else:\n pr[idx] = (pr[idx] + pr[idx-1] + pr[idx-width] + pr[idx+width] + pr[idx+1])/5\n pg[idx] = (pg[idx] + pg[idx-1] + pg[idx-width] + pg[idx+width] + pg[idx+1])/5\n pb[idx] = (pb[idx] + pb[idx-1] + pb[idx-width] + pb[idx+width] + pb[idx+1])/5\n idx += 1\n \n return pr, pg, pb\n\n@njit(cache=True)\ndef agents(enx, eny, maph, posx, posy, rot, rot_v, et, shoot, sx, sy, sz, sdir,\n sdirz, shoot2, sx2, sy2, sz2, sdir2, sdirz2, mplayer,\n seenx, seeny, lock, size, enhealth, health, score):\n\n mplayer[int(posx)][int(posy)] = 2 # player = 2, npc = 3, npc fireball >=6, player fireball >=12\n if (maph[int(posx+.1)][int(posy+.1)] == 0 and maph[int(posx-.1)][int(posy-.1)] == 0 and\n maph[int(posx-.1)][int(posy+.1)] == 0 and maph[int(posx+.1)][int(posy-.1)] == 0):\n mplayer[int(posx+0.1)][int(posy+0.1)], mplayer[int(posx+0.1)][int(posy-0.1)] = 2, 2\n mplayer[int(posx-0.1)][int(posy+0.1)], mplayer[int(posx-0.1)][int(posy-0.1)] = 2, 2\n \n # teleport or respawn npc\n if (enhealth == 0 and np.random.uniform(0,1) > 0.995) or (enhealth > 0 and (enx-posx)**2 + (eny-posy)**2 > 300) :\n x, y = np.random.normal(posx, 5), np.random.normal(posy, 5)\n dtp = (x-posx)**2 + (y-posy)**2\n if x > 0 and x < size-1 and y > 0 and y < size-1:\n if maph[int(x)][int(y)] == 0 and dtp > 49 :\n if enhealth == 0:\n enx, eny, seenx, seeny, lock, enhealth = x, y, x, y, 0, 10\n else:\n enx, eny, seenx, seeny, lock = x, y, x, y, 0\n if enhealth > 0: # look for player\n if not lock or np.random.uniform(0,1) > 0.99:\n dtp = np.sqrt((enx-posx)**2 + (eny-posy)**2)\n cos, sin = (posx-enx)/dtp, (posy-eny)/dtp\n x, y = enx, eny\n for i in range(300):\n x += 0.04*cos; y += 0.04*sin\n if (maph[int(x+.05)][int(y+.05)] != 0 or maph[int(x-.05)][int(y-.05)] != 0 or\n maph[int(x-.05)][int(y+.05)] != 0 or maph[int(x+.05)][int(y-.05)] != 0):\n lock = 0\n break\n if(int(x) == int(posx) and int(y) == int(posy)): # lock on player position\n seenx, seeny, lock = posx, posy, 1\n break\n\n if int(enx) == int(seenx) and int(eny) == int(seeny): # reached target\n if not lock:\n if shoot or np.random.uniform(0,1) > 0.7: #if the player is shooting, go towards him\n seenx, seeny = np.random.uniform(enx, posx), np.random.uniform(eny, posy)\n else: # just keep mooving\n seenx, seeny = np.random.normal(enx, 2), np.random.normal(eny, 2) \n else: # go near the player if locked\n seenx, seeny = np.random.normal(posx, 2), np.random.normal(posy, 2)\n \n dtp = np.sqrt((enx-seenx)**2 + (eny-seeny)**2) \n cos, sin = (seenx-enx)/dtp, (seeny-eny)/dtp \n x, y = enx + et*cos, eny + et*sin # set new npc position\n if maph[int(x)][int(y)] == 0: # check if position is valid\n enx, eny = x, y\n else: # if not, try to move sideways\n if np.random.uniform(0,1) > 0.5:\n x, y = enx - et*sin, eny + et*cos\n else:\n x, y = enx + et*sin, eny - et*cos\n if maph[int(x)][int(y)] == 0: # try again\n enx, eny = x, y\n elif np.random.uniform(0,1) > 0.5: # update target\n if lock and np.random.uniform(0,1) > 0.5:\n seenx, seeny = np.random.normal(posx, 2), np.random.normal(posy, 2)\n if np.random.uniform(0,1) > 0.99: # release lock if stuck\n lock = 0\n else:\n seenx, seeny = enx+np.random.normal(0,3), eny+np.random.normal(0,3)\n \n mplayer[int(enx)][int(eny)] = 3 # mark npc position and adjacent positions \n if (maph[int(enx+.1)][int(eny+.1)] == 0 and maph[int(enx-.1)][int(eny-.1)] == 0 and\n maph[int(enx-.1)][int(eny+.1)] == 0 and maph[int(enx+.1)][int(eny-.1)] == 0):\n mplayer[int(enx+0.1)][int(eny+0.1)], mplayer[int(enx+0.1)][int(eny-0.1)] = 3, 3\n mplayer[int(enx-0.1)][int(eny+0.1)], mplayer[int(enx-0.1)][int(eny-0.1)] = 3, 3\n \n if lock and not shoot2: # npc fireball initiate\n shoot2, sdirz2 = 1, np.sin(np.random.uniform(0,.2))\n sdir2 = np.arctan((posy-eny)/(posx-enx)) + np.random.uniform(-.1,.1)\n if abs(enx+np.cos(sdir2)-posx) > abs(enx-posx):\n sdir2 = sdir2 - np.pi\n \n if shoot2 and sy2 != 0: # npc fireball\n if sx2 == -1:\n sx2, sy2, sz2 = enx + .5*np.cos(sdir2), eny + .5*np.sin(sdir2), 0.35 + .5*sdirz2\n sx2, sy2, sz2 = sx2 + 5*et*np.cos(sdir2), sy2 + 5*et*np.sin(sdir2), sz2 + 5*et*sdirz2\n sdirz2 = sdirz2 - et/5\n if sx2 > 0 and sx2 < size-1 and sy2 > 0 and sy2 < size-1 and sz2 > 0 and sz2 < 1:\n if (maph[int(sx2+.05)][int(sy2+.05)] != 0 or maph[int(sx2-.05)][int(sy2-.05)] != 0 or\n maph[int(sx2-.05)][int(sy2+.05)] != 0 or maph[int(sx2+.05)][int(sy2-.05)] != 0):\n shoot2, sx2, sy2 = 0, -1, -1\n else:\n if (sx2 - posx)**2 + (sy2 - posy)**2 < 0.01:\n shoot2, sx2, sy2 = 0, -1, 0\n health -= min(1 + score/4, 5)\n else:\n mplayer[int(sx2)][int(sy2)] += 6\n else:\n shoot2, sx2, sy2 = 0, -1, 0\n \n if shoot: # player fireball\n if sx == -1:\n sdir, sdirz = rot+np.random.uniform(-.05,.05), np.sin(min(rot_v , 0)+np.random.uniform(.1,.2))\n sx, sy, sz = posx + .5*np.cos(sdir), posy + .5*np.sin(sdir), 0.35 + .5*sdirz\n sx, sy, sz = sx + 5*et*np.cos(sdir), sy + 5*et*np.sin(sdir), sz + 5*et*sdirz\n sdirz = sdirz - et/5\n if (sx > 0 and sy < size-1 and sy > 0 and sy < size-1 and sz > 0 and sz < 1 and\n maph[int(sx+.05)][int(sy+.05)] == 0 and maph[int(sx-.05)][int(sy-.05)] == 0 and\n maph[int(sx-.05)][int(sy+.05)] == 0 and maph[int(sx+.05)][int(sy-.05)] == 0):\n if enhealth > 0 and (sx - enx)**2 + (sy - eny)**2 < 0.02:\n shoot, sx, sy = 0, -1, -1\n enhealth -= max(5 -score/4, 1)\n if enhealth <= 0:\n enx, eny, seenx, seeny, enhealth = 0, 0, 0, 0, 0\n else:\n mplayer[int(sx)][int(sy)] += 12\n else:\n shoot, sx, sy = 0, -1, -1\n \n mplayer = maph + mplayer\n return(enx, eny, mplayer, et, shoot, sx, sy, sz, sdir, sdirz, shoot2,\n sx2, sy2, sz2, sdir2, sdirz2, seenx, seeny, lock, enhealth, health)\n\ndef adjust_resol(width):\n height = int(0.6*width)\n mod = width/64\n rr, gg, bb = np.ones(width * height)/2, np.ones(width * height)/2, np.ones(width * height)/2\n return width, height, mod, rr, gg, bb, 0\n\ndef drawing(rr, gg, bb, height, width, pause, endmsg, won, health, enhealth, minimap, score, fullscreen, nosplash=True):\n global font, font2, screen, surfbg\n\n surfbg.fill(pg.Color(\"darkgrey\"))\n pg.draw.rect(surfbg, (200-int(health*20), 50+int(health*20), 50+int(health*10)),(1205,int(700-62*health),30,int(63*health)))\n pg.draw.rect(surfbg, (enhealth*25, 200-enhealth*10, 50),(1245,700-62*enhealth,30,63*enhealth))\n \n pixels = np.dstack((rr,gg,bb))\n pixels = np.reshape(pixels, (height,width,3))\n surf = pg.surfarray.make_surface((np.rot90(pixels*255)).astype('uint8'))\n surf = pg.transform.scale(surf, (1200, 720))\n if not nosplash or pause:\n px, py = 1100, 360\n if nosplash:\n px, py = pg.mouse.get_pos()\n for i in range(3):\n pg.draw.circle(surf, (50, 70+i*20, 160+i*40), [px+i*10,py-i*10], 50-i*15)\n pg.draw.circle(surf, (60+i*10, 100+i*20, 100+i*10), [px+i*10,py+280-i*1], 90-i*15)\n pg.draw.polygon(surf, (150+i*30, 34+i*10, 60+i*10), [[px-100+i*20,py+40+i*15],[px+100-i*20,py+40+i*15],[px+50-i*15,py+205-i*15],[px-50+i*15,py+205-i*15]])\n screen.blit(surfbg, (0, 0))\n screen.blit(surf, (0, 0))\n \n if pause: \n screen.blit(font2.render(\" PyTracing Maze by FinFET \", 0, pg.Color(\"red\")),(45,45))\n screen.blit(font2.render(\" PyTracing Maze by FinFET \", 0, pg.Color(\"blue\")),(55,55))\n screen.blit(font2.render(\" PyTracing Maze by FinFET \", 0, pg.Color(\"white\")),(50,50))\n screen.blit(font2.render(endmsg, 0, pg.Color(\"salmon\"), (100, 34, 60)),(50,420))\n if nosplash:\n screen.blit(font2.render(\" Press N for a new game \", 0, pg.Color(\"grey\"), (45, 34, 100)),(50,560))\n screen.blit(font2.render(\" Press ESC to leave \", 0, pg.Color(\"grey\"), (13, 34, 139)),(50,630))\n if won == 1:\n screen.blit(font2.render(\" Your current score is \"+str(score) + ' ', 0, pg.Color(\"grey\"), (80, 34, 80)),(50,490))\n if won == 0:\n screen.blit(font2.render(\" Press P or C to continue \", 0, pg.Color(\"grey\"), (80, 34, 80)),(50,490))\n else:\n size = len(minimap)\n surfmap = pg.surfarray.make_surface(np.flip(minimap).astype('uint8'))\n surfmap = pg.transform.scale(surfmap, (size*4, size*4))\n screen.blit(surfmap,(1280-size*4 - 85, 5), special_flags=pg.BLEND_ADD)\n if fullscreen:\n fps = font.render(endmsg, 0, pg.Color(\"coral\"))\n screen.blit(fps,(100,1))\n screen.blit(font2.render(str(score), 0, pg.Color(\"white\")),(1210, 10))\n \n pg.display.update()\n\ndef animate(width, height, mod, move, posx, posy, posz, rot, rot_v, mr, mg, mb, lx, ly, lz, #simple up and down animation\n maph, exitx, exity, mapr, mapt, maps, pr, pg, pb, enx, eny, sx, sy, sx2, sy2,\n size, checker, count, fb, fg, fr, pause, endmsg, won, health, minimap, score, ani, fps=60):\n ani = ani*60/fps\n for i in range(int(fps)):\n rr, gg, bb = super_fast(width, height, mod, move, posx, posy, posz+ani*i, rot, rot_v, mr, mg, mb, lx, ly, lz,\n maph, exitx, exity, mapr, mapt, maps, pr, pg, pb, enx, eny, sx, sy, sx2, sy2,\n size, checker, count, fb, fg, fr)\n count += 1\n \n drawing(rr, gg, bb, height, width, pause, endmsg, won, health, 0, minimap, score, 0)\n \ndef sfx(): #load sounds and textures\n try:\n ambient = pg.mixer.Sound('soundfx/HauntSilentPartner.mp3') \n runfx = pg.mixer.Sound('soundfx/run.mp3')\n shotfx = pg.mixer.Sound('soundfx/slap.mp3')\n killfx = pg.mixer.Sound('soundfx/shutdown.mp3')\n respawnfx = pg.mixer.Sound('soundfx/respawn.mp3')\n successfx = pg.mixer.Sound('soundfx/success.mp3')\n failfx = pg.mixer.Sound('soundfx/fail.mp3')\n except:\n print(\"Sounds missing! Generating replacements...\")\n ambient = generate_sounds(75, 10000, 300)\n runfx = generate_sounds(200, 800, 150)\n shotfx = generate_sounds(200, 200, 250)\n killfx = generate_sounds(1620, 241, 230)\n respawnfx = generate_sounds(230, 350, 80)\n successfx = generate_sounds(300, 900, 100)\n failfx = generate_sounds(700, 200, 350)\n try: \n floor = pg.surfarray.array3d(pg.image.load('soundfx/textures.jpg'))\n fr, fg, fb = np.dsplit(floor,floor.shape[-1])\n fr, fg, fb = fr.flatten()/255, fg.flatten()/255, fb.flatten()/255\n except:\n print(\"Textures missing! Generating replacements...\")\n fr, fg, fb = generate_textures()\n \n\n return ambient, runfx, shotfx, killfx, respawnfx, successfx, failfx, fr, fg, fb\n\ndef generate_sounds(freq = 60, var = 500, n = 10):\n sound1, sound2, sound3, freq0, dir2 = [], [], [], freq, 1\n for i in range(n):\n freq = freq+20*dir2\n if freq > freq0*3 or freq < freq0/3+10:\n dir2 = -1*dir2\n freq = freq+20*dir2\n var2 = np.random.randint(int(var/2),var*2)\n samples1 = synth(np.random.randint(int(var),var*3), np.random.randint(freq,2*freq))\n samples2 = synth(np.random.randint(int(var/2),var*2), np.random.randint(int(freq/2),freq))\n samples3 = synth(np.random.randint(int(var/4),int(var/2)), np.random.randint(int(freq/3),3*freq))\n sound1 = sound1 + list(samples1/3)\n sound2 = sound2 + list(samples2/3)\n sound3 = sound3 + list(samples3/3)\n\n lens = min(len(sound1), len(sound2), len(sound3))\n sound = np.asarray(sound1[:lens]) + np.asarray(sound2[:lens]) + np.asarray(sound3[:lens])\n sound = np.asarray([sound,sound]).T.astype(np.int16)\n sound = pg.sndarray.make_sound(sound.copy())\n return sound\n\ndef synth(frames, freq):\n def frame(i):\n return 0.2 * 32767 * np.sin(2.0 * np.pi * freq * i / 44100)\n arr = np.array([frame(x) for x in range(0, frames)]).astype(np.int16)\n return arr\n\ndef generate_textures():\n fr, fg, fb = [], [], []\n for i in range(100):\n for j in range(100):\n ref1, ref2 = .2, 0.2\n if i < 50 and j < 50 or i > 50 and j > 50:\n ref1 = 1\n if (i-50)**2 + (j-50)**2 < 2000:\n ref2 = 1\n fr.append(3.5-abs(np.sin(i/5)+np.cos(j/5))*ref2*np.random.uniform(i/100,j/100)+0.3+ref1)\n fg.append(ref1+np.random.uniform(i/100,ref2*ref1)/3+0.1)\n fb.append(ref1+np.random.uniform(j/100,ref2*ref1)/3+0.1)\n fr, fg, fb = np.asarray(fr)/max(fr), np.asarray(fg)/3, np.asarray(fb)/3\n return fr, fg, fb\n\nif __name__ == '__main__':\n pg.init()\n pg.display.set_caption(\"Welcome to Pytracing maze! Stutters may occur on first run while Numba is compiling\")\n font = pg.font.SysFont(\"Arial\", 18)\n font2 = pg.font.SysFont(\"Impact\", 48)\n screen = pg.display.set_mode((1280, 720))\n surfbg = pg.Surface((1280,720))\n main()\n"
] |
[
[
"numpy.rot90",
"numpy.log",
"numpy.sqrt",
"numpy.linspace",
"numpy.random.choice",
"numpy.reshape",
"numpy.clip",
"numpy.arctan",
"numpy.cos",
"numpy.dstack",
"numpy.sin",
"numpy.deg2rad",
"numpy.random.normal",
"numpy.random.uniform",
"numpy.zeros",
"numpy.where",
"numpy.random.randint"
],
[
"numpy.sqrt",
"numpy.linspace",
"numpy.arctan",
"numpy.asarray",
"numpy.where",
"numpy.random.randint",
"numpy.clip",
"numpy.reshape",
"numpy.sin",
"numpy.zeros",
"numpy.rot90",
"numpy.log",
"numpy.random.choice",
"numpy.deg2rad",
"numpy.flip",
"numpy.cos",
"numpy.dstack",
"numpy.ones",
"numpy.random.normal",
"numpy.dsplit",
"numpy.random.uniform"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lesteve/robopose
|
[
"536e5317c891bf6bb2b8cbdda294533b3f111e09",
"536e5317c891bf6bb2b8cbdda294533b3f111e09"
] |
[
"robopose/evaluation/meters/utils.py",
"robopose/rendering/bullet_scene_renderer.py"
] |
[
"import numpy as np\nimport pandas as pd\nfrom collections import OrderedDict\n\n\ndef one_to_one_matching(pred_infos, gt_infos,\n keys=('scene_id', 'view_id'),\n allow_pred_missing=False):\n keys = list(keys)\n pred_infos['pred_id'] = np.arange(len(pred_infos))\n gt_infos['gt_id'] = np.arange(len(gt_infos))\n matches = pred_infos.merge(gt_infos, on=keys)\n\n matches_gb = matches.groupby(keys).groups\n assert all([len(v) == 1 for v in matches_gb.values()])\n if not allow_pred_missing:\n assert len(matches) == len(gt_infos)\n return matches\n\n\ndef get_candidate_matches(pred_infos, gt_infos,\n group_keys=['scene_id', 'view_id', 'label'],\n only_valids=True):\n pred_infos['pred_id'] = np.arange(len(pred_infos))\n gt_infos['gt_id'] = np.arange(len(gt_infos))\n group_keys = list(group_keys)\n cand_infos = pred_infos.merge(gt_infos, on=group_keys)\n if only_valids:\n cand_infos = cand_infos[cand_infos['valid']].reset_index(drop=True)\n cand_infos['cand_id'] = np.arange(len(cand_infos))\n return cand_infos\n\n\ndef match_poses(cand_infos, group_keys=['scene_id', 'view_id', 'label']):\n assert 'error' in cand_infos\n\n matches = []\n\n def match_label_preds(group):\n gt_ids_matched = set()\n group = group.reset_index(drop=True)\n gb_pred = group.groupby('pred_id', sort=False)\n ids_sorted = gb_pred.first().sort_values('score', ascending=False)\n gb_pred_groups = gb_pred.groups\n for idx, _ in ids_sorted.iterrows():\n pred_group = group.iloc[gb_pred_groups[idx]]\n best_error = np.inf\n best_match = None\n for _, tentative_match in pred_group.iterrows():\n if tentative_match['error'] < best_error and \\\n tentative_match['gt_id'] not in gt_ids_matched:\n best_match = tentative_match\n best_error = tentative_match['error']\n\n if best_match is not None:\n gt_ids_matched.add(best_match['gt_id'])\n matches.append(best_match)\n\n if len(cand_infos) > 0:\n cand_infos.groupby(group_keys).apply(match_label_preds)\n matches = pd.DataFrame(matches).reset_index(drop=True)\n else:\n matches = cand_infos\n return matches\n",
"import numpy as np\nimport pybullet as pb\n\nfrom robopose.datasets.datasets_cfg import make_urdf_dataset\nfrom robopose.lib3d import Transform\n\nfrom robopose.simulator.base_scene import BaseScene\nfrom robopose.simulator.caching import BodyCache\nfrom robopose.simulator.camera import Camera\n\n\nclass BulletSceneRenderer(BaseScene):\n def __init__(self,\n urdf_ds='ycbv',\n preload_cache=False,\n background_color=(0, 0, 0),\n gpu_renderer=True,\n gui=False):\n\n self.urdf_ds = make_urdf_dataset(urdf_ds)\n self.connect(gpu_renderer=gpu_renderer, gui=gui)\n self.body_cache = BodyCache(self.urdf_ds, self.client_id)\n if preload_cache:\n self.body_cache.get_bodies_by_ids(np.arange(len(self.urdf_ds)))\n self.background_color = background_color\n\n def setup_scene(self, obj_infos):\n labels = [obj['name'] for obj in obj_infos]\n bodies = self.body_cache.get_bodies_by_labels(labels)\n for (obj_info, body) in zip(obj_infos, bodies):\n TWO = Transform(obj_info['TWO'])\n body.pose = TWO\n q = obj_info.get('joints', None)\n if q is not None:\n body.q = q\n color = obj_info.get('color', None)\n if color is not None:\n pb.changeVisualShape(body.body_id, -1, physicsClientId=0, rgbaColor=color)\n return bodies\n\n def render_images(self, cam_infos, render_depth=False, render_mask=True):\n cam_obs = []\n for cam_info in cam_infos:\n K = cam_info['K']\n TWC = Transform(cam_info['TWC'])\n resolution = cam_info['resolution']\n cam = Camera(resolution=resolution, client_id=self.client_id)\n cam.set_intrinsic_K(K)\n cam.set_extrinsic_T(TWC)\n cam_obs_ = cam.get_state()\n if self.background_color is not None:\n im = cam_obs_['rgb']\n mask = cam_obs_['mask']\n im[np.logical_or(mask < 0, mask == 255)] = self.background_color\n if render_depth:\n depth = cam_obs_['depth']\n near, far = cam_obs_['near'], cam_obs_['far']\n z_n = 2 * depth - 1\n z_e = 2 * near * far / (far + near - z_n * (far - near))\n z_e[np.logical_or(mask < 0, mask == 255)] = 0.\n cam_obs_['depth'] = z_e\n cam_obs.append(cam_obs_)\n return cam_obs\n\n def render_scene(self, obj_infos, cam_infos, render_depth=False, render_mask=True):\n self.setup_scene(obj_infos)\n # NOTE: Mask is always rendered, flag is not used.\n cam_obs = self.render_images(cam_infos, render_depth=render_depth, render_mask=render_mask)\n return cam_obs\n"
] |
[
[
"pandas.DataFrame"
],
[
"numpy.logical_or"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
PritishSehzpaul/pennylane
|
[
"93ff1b2deeaf620db90ec91448fde64709a9fd9f"
] |
[
"tests/tape/interfaces/test_qnode_jax.py"
] |
[
"# Copyright 2018-2021 Xanadu Quantum Technologies Inc.\r\n\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\"\"\"Unit tests for the JAX interface\"\"\"\r\nimport pytest\r\njax = pytest.importorskip(\"jax\")\r\njnp = pytest.importorskip(\"jax.numpy\")\r\nimport numpy as np\r\nimport pennylane as qml\r\nfrom pennylane.tape import JacobianTape, qnode, QNode, QubitParamShiftTape\r\n\r\ndef test_qnode_intergration():\r\n\t\"\"\"Test a simple use of qnode with a JAX interface and non-JAX device\"\"\"\r\n\tdev = qml.device(\"default.mixed\", wires=2) # A non-JAX device\r\n\r\n\[email protected](dev, interface=\"jax\")\r\n\tdef circuit(weights):\r\n\t\tqml.RX(weights[0], wires=0)\r\n\t\tqml.RZ(weights[1], wires=1)\r\n\t\treturn qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))\r\n\r\n\tweights = jnp.array([0.1, 0.2])\r\n\tval = circuit(weights)\r\n\tassert \"DeviceArray\" in val.__repr__()\r\n\r\ndef test_to_jax():\r\n\t\"\"\"Test the to_jax method\"\"\"\r\n\tdev = qml.device(\"default.mixed\", wires=2) \r\n\r\n\[email protected](dev, interface=\"autograd\")\r\n\tdef circuit(weights):\r\n\t\tqml.RX(weights[0], wires=0)\r\n\t\tqml.RZ(weights[1], wires=1)\r\n\t\treturn qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))\r\n\r\n\tcircuit.to_jax()\r\n\tweights = jnp.array([0.1, 0.2])\r\n\tval = circuit(weights)\r\n\tassert \"DeviceArray\" in val.__repr__()\r\n\r\n\r\ndef test_simple_jacobian():\r\n\t\"\"\"Test the use of jax.jaxrev\"\"\"\r\n\tdev = qml.device(\"default.mixed\", wires=2) # A non-JAX device.\r\n\r\n\[email protected](dev, interface=\"jax\", diff_method=\"parameter-shift\")\r\n\tdef circuit(weights):\r\n\t\tqml.RX(weights[0], wires=0)\r\n\t\tqml.RY(weights[1], wires=1)\r\n\t\treturn qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))\r\n\r\n\tweights = jnp.array([0.1, 0.2])\r\n\tgrads = jax.jacrev(circuit)(weights)\r\n\t# This is the easiest way to ensure our object is a DeviceArray instead\r\n\t# of a numpy array.\r\n\tassert \"DeviceArray\" in grads.__repr__()\r\n\tassert grads.shape == (2,)\r\n\tnp.testing.assert_allclose(grads, np.array([-0.09784342, -0.19767685]))\r\n\r\ndef test_simple_grad():\r\n\t\"\"\"Test the use of jax.grad\"\"\"\r\n\tdev = qml.device(\"default.mixed\", wires=2) # A non-JAX device.\r\n\[email protected](dev, interface=\"jax\", diff_method=\"parameter-shift\")\r\n\tdef circuit(weights):\r\n\t\tqml.RX(weights[0], wires=0)\r\n\t\tqml.RZ(weights[1], wires=1)\r\n\t\treturn qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))\r\n\r\n\tweights = jnp.array([0.1, 0.2])\r\n\tval = jax.grad(circuit)(weights)\r\n\tassert \"DeviceArray\" in val.__repr__()\r\n\r\[email protected](\"diff_method\", ['parameter-shift', 'finite-diff'])\r\ndef test_differentiable_expand(diff_method):\r\n \"\"\"Test that operation and nested tapes expansion\r\n is differentiable\"\"\"\r\n class U3(qml.U3):\r\n def expand(self):\r\n theta, phi, lam = self.data\r\n wires = self.wires\r\n\r\n with JacobianTape() as tape:\r\n qml.Rot(lam, theta, -lam, wires=wires)\r\n qml.PhaseShift(phi + lam, wires=wires)\r\n\r\n return tape\r\n\r\n dev = qml.device(\"default.mixed\", wires=1)\r\n a = jnp.array(0.1)\r\n p = jnp.array([0.1, 0.2, 0.3])\r\n\r\n @qnode(dev, diff_method=diff_method, interface=\"jax\")\r\n def circuit(a, p):\r\n qml.RX(a, wires=0)\r\n U3(p[0], p[1], p[2], wires=0)\r\n return qml.expval(qml.PauliX(0))\r\n\r\n res = circuit(a, p)\r\n\r\n expected = np.cos(a) * np.cos(p[1]) * np.sin(p[0]) + np.sin(a) * (\r\n np.cos(p[2]) * np.sin(p[1]) + np.cos(p[0]) * np.cos(p[1]) * np.sin(p[2])\r\n )\r\n tol = 1e-5\r\n assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\n res = jax.grad(circuit, argnums=1)(a, p)\r\n expected = np.array(\r\n [\r\n np.cos(p[1]) * (np.cos(a) * np.cos(p[0]) - np.sin(a) * np.sin(p[0]) * np.sin(p[2])),\r\n np.cos(p[1]) * np.cos(p[2]) * np.sin(a)\r\n - np.sin(p[1])\r\n * (np.cos(a) * np.sin(p[0]) + np.cos(p[0]) * np.sin(a) * np.sin(p[2])),\r\n np.sin(a)\r\n * (np.cos(p[0]) * np.cos(p[1]) * np.cos(p[2]) - np.sin(p[1]) * np.sin(p[2])),\r\n ]\r\n )\r\n assert np.allclose(res, expected, atol=tol, rtol=0)\r\n\r\ndef qtransform(qnode, a, framework=jnp):\r\n \"\"\"Transforms every RY(y) gate in a circuit to RX(-a*cos(y))\"\"\"\r\n\r\n def construct(self, args, kwargs):\r\n \"\"\"New quantum tape construct method, that performs\r\n the transform on the tape in a define-by-run manner\"\"\"\r\n\r\n t_op = []\r\n\r\n QNode.construct(self, args, kwargs)\r\n\r\n new_ops = []\r\n for o in self.qtape.operations:\r\n # here, we loop through all tape operations, and make\r\n # the transformation if a RY gate is encountered.\r\n if isinstance(o, qml.RY):\r\n t_op.append(qml.RX(-a * framework.cos(o.data[0]), wires=o.wires))\r\n new_ops.append(t_op[-1])\r\n else:\r\n new_ops.append(o)\r\n\r\n self.qtape._ops = new_ops\r\n self.qtape._update()\r\n\r\n import copy\r\n\r\n new_qnode = copy.deepcopy(qnode)\r\n new_qnode.construct = construct.__get__(new_qnode, QNode)\r\n return new_qnode\r\n\r\n\r\[email protected](\r\n \"dev_name,diff_method\",\r\n [(\"default.mixed\", \"finite-diff\"), (\"default.qubit.autograd\", \"parameter-shift\")],\r\n)\r\ndef test_transform(dev_name, diff_method, monkeypatch, tol):\r\n \"\"\"Test an example transform\"\"\"\r\n monkeypatch.setattr(qml.operation.Operation, \"do_check_domain\", False)\r\n\r\n dev = qml.device(dev_name, wires=1)\r\n\r\n @qnode(dev, interface=\"jax\", diff_method=diff_method)\r\n def circuit(weights):\r\n op1 = qml.RY(weights[0], wires=0)\r\n op2 = qml.RX(weights[1], wires=0)\r\n return qml.expval(qml.PauliZ(wires=0))\r\n\r\n weights = np.array([0.32, 0.543])\r\n a = np.array(0.5)\r\n\r\n def loss(weights, a):\r\n # transform the circuit QNode with trainable weight 'a'\r\n new_circuit = qtransform(circuit, a)\r\n\r\n # evaluate the transformed QNode\r\n res = new_circuit(weights)\r\n\r\n # evaluate the original QNode with pre-processed parameters\r\n res2 = circuit(jnp.sin(weights))\r\n\r\n # return the sum of the two QNode evaluations\r\n return res + res2\r\n\r\n res = loss(weights, a)\r\n\r\n grad = jax.grad(loss, argnums=[0, 1])(weights, a)\r\n assert len(grad) == 2\r\n assert grad[0].shape == weights.shape\r\n assert grad[1].shape == a.shape\r\n\r\n # compare against the expected values\r\n tol = 1e-5\r\n assert np.allclose(res, 1.8244501889992706, atol=tol, rtol=0)\r\n assert np.allclose(grad[0], [-0.26610258, -0.47053553], atol=tol, rtol=0)\r\n assert np.allclose(grad[1], 0.06486032, atol=tol, rtol=0)\r\n"
] |
[
[
"numpy.cos",
"numpy.array",
"numpy.allclose",
"numpy.sin"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
suhasgupta791/mids-w251-final-project
|
[
"aa1ef80685c6d9b5fc8a444e438078150cc0d96c"
] |
[
"utils/utils.py"
] |
[
"#!/usr/bin/env python\n# coding: utf-8\n\nimport random\nimport numpy as np\nimport sys, os\nimport pandas as pd \nimport torch\nfrom torchsummary import summary\nfrom torchtext import data\nimport torch.nn as nn\nimport torch.utils.data\nfrom torch.utils.data import Dataset, TensorDataset,DataLoader, RandomSampler\nfrom torch.utils.tensorboard import SummaryWriter\nimport torchvision\nimport torch.nn.functional as F\nfrom sklearn.metrics import roc_auc_score\nfrom tqdm import tqdm\nimport pickle\nimport shutil\nfrom sklearn.model_selection import train_test_split\n\n\ndef tokenize(tokenizer,text_array,max_seq_len=64,pad_to_max_length=True,add_special_tokens=True):\n ''' Returns tokenized IDs and attention mask\n The transformers encode_plus method returns the following:\n {\n input_ids: list[int],\n token_type_ids: list[int] if return_token_type_ids is True (default)\n attention_mask: list[int] if return_attention_mask is True (default)\n overflowing_tokens: list[int] if a ``max_length`` is specified and return_overflowing_tokens is True\n num_truncated_tokens: int if a ``max_length`` is specified and return_overflowing_tokens is True\n special_tokens_mask: list[int] if ``add_special_tokens`` if set to ``True`` and return_special_tokens_mask is True\n }'''\n all_tokens=[]\n all_attention_mask=[]\n for i,text in enumerate(tqdm(text_array)):\n encoded = tokenizer.encode_plus(\n text,\n add_special_tokens=add_special_tokens,\n max_length=max_seq_len,\n pad_to_max_length=pad_to_max_length)\n tokens = torch.tensor(encoded['input_ids'])\n attention_mask = torch.tensor(encoded['attention_mask'])\n all_tokens.append(tokens)\n all_attention_mask.append(attention_mask)\n return all_tokens,all_attention_mask\n\nclass CreateDataset(Dataset):\n def __init__(self,data,atten_mask,labels,num_excl):\n self._dataset = [[data[i],atten_mask[i],labels.values[i],num_excl.values[i]] for i in range(0,len(data))]\n \n def __len__(self):\n return len(self._dataset)\n\n def __getitem__(self,idx):\n return self._dataset[idx]\n\ndef createTestTrainSplit(all_train_df,test_size=0.2,seed=1234):\n # Create train, validation dataset splits\n train_df, valid_df = train_test_split(all_train_df, test_size=0.2,random_state=seed)\n train_data = train_df.text.fillna(\"DUMMY_VALUE\")\n train_labels = train_df.label\n train_num_excl = train_df.num_exclamation_marks\n valid_data = valid_df.text.fillna(\"DUMMY_VALUE\")\n valid_labels = valid_df.label\n valid_num_excl = train_df.num_exclamation_marks\n return train_data,train_labels,train_num_excl,valid_data,valid_labels,valid_num_excl\n\ndef saveTokensToFiles(TOKEN_DATA_PATH,\n train_data_tokenized,train_attention_mask,\n valid_data_tokenized,valid_attention_mask,\n test_data_tokenized,test_attention_mask):\n # save to files for later use\n with open(TOKEN_DATA_PATH+'/train_data_tokenized.txt', 'wb') as fp:\n pickle.dump(train_data_tokenized, fp)\n with open(TOKEN_DATA_PATH+'/train_attention_mask.txt', 'wb') as fp:\n pickle.dump(train_attention_mask, fp)\n with open(TOKEN_DATA_PATH+'/valid_data_tokenized.txt', 'wb') as fp:\n pickle.dump(valid_data_tokenized, fp)\n with open(TOKEN_DATA_PATH+'/valid_attention_mask.txt', 'wb') as fp:\n pickle.dump(valid_attention_mask, fp)\n with open(TOKEN_DATA_PATH+'/test_data_tokenized.txt', 'wb') as fp:\n pickle.dump(test_data_tokenized, fp)\n with open(TOKEN_DATA_PATH+'/test_attention_mask.txt', 'wb') as fp:\n pickle.dump(test_attention_mask, fp)\n\ndef loadTokensFromFiles(TOKEN_DATA_PATH,\n train_data_tokenized,train_attention_mask,\n valid_data_tokenized,valid_attention_mask,\n test_data_tokenized,test_attention_mask):\n # read back tokenized data\n with open(TOKEN_DATA_PATH+'train_data_tokenized.txt', 'rb') as fp:\n train_data_tokenized=pickle.load(fp)\n with open(TOKEN_DATA_PATH+'train_attention_mask.txt', 'rb') as fp:\n train_attention_mask=pickle.load(fp)\n with open(TOKEN_DATA_PATH+'valid_data_tokenized.txt', 'rb') as fp:\n valid_data_tokenized=pickle.load(fp)\n with open(TOKEN_DATA_PATH+'valid_attention_mask.txt', 'rb') as fp:\n valid_attention_mask=pickle.load(fp)\n with open(TOKEN_DATA_PATH+'test_data_tokenized.txt', 'rb') as fp:\n test_data_tokenized=pickle.load(fp)\n with open(TOKEN_DATA_PATH+'test_attention_mask.txt', 'rb') as fp:\n test_attention_mask=pickle.load(fp)\n\ndef generateDataLoader(dataset,batch_size,shuffle=False,num_workers=16,pin_memory=False,drop_last=True):\n # print(\"Expected number of batches:\", int(len(train_data_tokenized)/params['batch_size']))\n sampler = RandomSampler(dataset)\n dataLoader = torch.utils.data.DataLoader(dataset=dataset,\n sampler=sampler,\n batch_size=batch_size,\n shuffle=shuffle,\n num_workers=num_workers)\n return dataLoader\n"
] |
[
[
"torch.utils.data.DataLoader",
"torch.utils.data.RandomSampler",
"sklearn.model_selection.train_test_split",
"torch.tensor"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sjkelly/openlane
|
[
"0fec8c8fb2382d3d487127face5109ec7d2baa51"
] |
[
"scripts/csv2html/csv2html.py"
] |
[
"# Copyright 2020 Efabless Corporation\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 csv\nimport os\nimport argparse\nimport pathlib\nimport pandas as pd\nfrom jinja2 import Environment, PackageLoader, select_autoescape\n\nparser = argparse.ArgumentParser(\n description='Takes an input csv report from the run_designs.py script and creates an html summary for it')\n\nparser.add_argument('--csv_file', '-i',required=True,\n help='The input csv file')\n\nparser.add_argument('--html_file', '-o', required=True,\n help='The output html file')\n\nargs = parser.parse_args()\ncsv_file = args.csv_file\nhtml_file = args.html_file\n\nenv = Environment(\n loader=PackageLoader('csv2html', 'templates'),\n autoescape=select_autoescape('html')\n)\n\ntemplate = env.get_template('main.html')\n\n\ndef get_static_folder(file_name):\n p = pathlib.Path('.')\n return pathlib.PosixPath(str(p) +'/scripts/csv2html/static/'+str(file_name))\n\n\ndef read_csv(csv_file):\n csv_file_opener = open(csv_file, 'r')\n csv_data = csv.reader(csv_file_opener)\n csv_headers = next(csv_data)\n return csv_headers, csv_data\n\n\ndef create_output_html(csv_file, html_file):\n colms = ['design','config','runtime','DIEAREA_mm^2','OpenDP_Util','cell_count','tritonRoute_violations',\n 'Short_violations',\t'Magic_violations', 'antenna_violations', 'wns', 'CLOCK_PERIOD']\n\n allData = pd.read_csv(csv_file, error_bad_lines=False)\n dataFrame = pd.DataFrame(data=allData)\n usedData = dataFrame[colms]\n usedData.to_csv(csv_file.split(\".csv\")[0]+\"_tmp_report.csv\")\n\n headers, data = read_csv(csv_file.split(\".csv\")[0]+\"_tmp_report.csv\")\n\n with open(html_file, 'w') as output:\n static_file = 'style.css'\n output.write(template.render(headers=headers, rows=data, style_url=get_static_folder(static_file).resolve()))\n\n os.remove(csv_file.split(\".csv\")[0]+\"_tmp_report.csv\")\n\n\n\nif __name__ == '__main__':\n create_output_html(csv_file, html_file)\n"
] |
[
[
"pandas.read_csv",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
hit-thusz-RookieCJ/flowtron
|
[
"3822bd0ed3226b001dd4ec1653809449f889b520"
] |
[
"flowtron_logger.py"
] |
[
"import random\nimport torch\nfrom torch.utils.tensorboard import SummaryWriter\nfrom flowtron_plotting_utils import plot_alignment_to_numpy\nfrom flowtron_plotting_utils import plot_gate_outputs_to_numpy\n\n\nclass FlowtronLogger(SummaryWriter):\n def __init__(self, logdir):\n super(FlowtronLogger, self).__init__(logdir)\n\n def log_training(self, loss, learning_rate, iteration):\n self.add_scalar(\"training/loss\", loss, iteration)\n self.add_scalar(\"learning_rate\", learning_rate, iteration)\n\n def log_validation(self, loss, loss_nll, loss_gate, attns, gate_pred,\n gate_out, iteration):\n self.add_scalar(\"validation/loss\", loss, iteration)\n self.add_scalar(\"validation/loss_nll\", loss_nll, iteration)\n self.add_scalar(\"validation/loss_gate\", loss_gate, iteration)\n\n # batch里随机抽一条看看效果\n idx = random.randint(0, len(gate_out) - 1)\n for i in range(len(attns)):\n self.add_image(\n 'attention_weights_{}'.format(i),\n plot_alignment_to_numpy(attns[i][idx].data.cpu().numpy().T),\n iteration,\n dataformats='HWC')\n\n if gate_pred is not None:\n gate_pred = gate_pred.transpose(0, 1)[:, :, 0]\n self.add_image(\n \"gate\",\n plot_gate_outputs_to_numpy(\n gate_out[idx].data.cpu().numpy(),\n torch.sigmoid(gate_pred[idx]).data.cpu().numpy()),\n iteration, dataformats='HWC')\n"
] |
[
[
"torch.sigmoid"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
brberg/stokes-crevasse-advection
|
[
"c5996d0330de5971381b4d0a9543c784b94a8918"
] |
[
"plotting/thumbnails_warm.py"
] |
[
"from __future__ import division\nimport numpy as np\nimport sys\nimport os\nimport shutil\nimport vtk\nfrom vtk.util.numpy_support import vtk_to_numpy\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport matplotlib.animation as animation\nimport matplotlib.colors as mcolors\nimport argparse\nimport paraview.simple as parasim\nimport multiprocessing as mp\nimport copy\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'model')))\nfrom geometry_generation import *\nmatplotlib.rcParams['font.size'] = 6\nimport scipy.interpolate as interpsci\nimport seaborn as sns\n\ndef truncate_colormap(cmap, minval=0.0, maxval=1.0, n=-1):\n if n == -1:\n n = cmap.N\n new_cmap = mcolors.LinearSegmentedColormap.from_list(\n 'trunc({name},{a:.2f},{b:.2f})'.format(name=cmap.name, a=minval, b=maxval),\n cmap(np.linspace(minval, maxval, n)))\n return new_cmap\n\ndef makeImage(snapshots, geometryX, geometryY, data_names, folder_name, times):\n\n fig = plt.figure(figsize=(7,4.72441/4*3))\n\n ax1 = fig.add_subplot(231)\n ax2 = fig.add_subplot(234)\n ax3 = fig.add_subplot(232)\n ax4 = fig.add_subplot(235)\n ax5 = fig.add_subplot(233)\n ax6 = fig.add_subplot(236)\n axes = [[ax1, ax2], [ax3, ax4], [ax5, ax6]]\n all_axes = [ax1, ax2, ax3, ax4, ax5, ax6]\n\n for k in range(len(snapshots[0])):\n axes_current = axes[k]\n values = [[],[]]\n for j in range(len(data_names)):\n i = snapshots[j][k]\n reader = vtk.vtkXMLUnstructuredGridReader()\n reader.SetFileName(data_names[j] + '{0:06d}.vtu'.format(i))\n reader.Update()\n data = reader.GetOutput()\n points = data.GetPoints()\n npts = points.GetNumberOfPoints()\n x = vtk_to_numpy(points.GetData())[:, 0]\n y = vtk_to_numpy(points.GetData())[:, 1]\n f = vtk_to_numpy(data.GetPointData().GetArray(0))\n triangles = vtk_to_numpy(data.GetCells().GetData())\n ntri = triangles.size//4\n tri = np.take(triangles,[m for m in range(triangles.size) if m%4 != 0]).reshape(ntri, 3)\n\n waterX = np.linspace(0, 60000, 100)\n waterY = np.zeros(100)\n values[j].append(x)\n values[j].append(y)\n values[j].append(tri)\n values[j].append(f)\n\n levels = np.linspace(0, 1.0, 100, endpoint=True)\n\n cmap_new = truncate_colormap(plt.get_cmap(\"BuPu\"), 0.25, 1.0)\n\n maxL = 51100\n bed_interpolator = interpsci.interp1d(geometryX, geometryY, fill_value='extrapolate')\n geometryX = np.linspace(0, 60000, 1000)\n geometryY = bed_interpolator(geometryX)\n axes_current[0].fill_between(waterX, -200, 0, color='#94aec4ff', zorder=-21)\n axes_current[1].fill_between(waterX, -200, 0, color='#94aec4ff', zorder=-21)\n axes_current[0].fill_between(geometryX, -200, geometryY, color='#c69d6eff', zorder=-18)\n axes_current[1].fill_between(geometryX, -200, geometryY, color='#c69d6eff', zorder=-18)\n\n cnt1 = axes_current[0].tricontourf(values[0][0], values[0][1], values[0][2], values[0][3]*100, 100, cmap=cmap_new, levels=levels, extend='both', zorder=-20)\n cnt2 = axes_current[1].tricontourf(values[1][0], values[1][1], values[1][2], values[1][3]*100, 100, cmap=cmap_new, levels=levels, extend='both', zorder=-20)\n\n for cnt in [cnt1, cnt2]:\n for c in cnt.collections:\n c.set_edgecolor(\"face\")\n\n axes_current[0].set_title(\"t = %.1f years\" % (times[k]-0.5))\n\n print(\"Processed file number \" + str(i) + \".\")\n\n labels = ['a', 'd', 'b', 'e', 'c', 'f']\n\n for ax in all_axes:\n ax.set_xlim([49400,maxL])\n ax.set_ylim([-200,100])\n ax.set_rasterization_zorder(-10)\n\n for j in range(len(all_axes)):\n all_axes[j].text(0.025, 0.97, labels[j], transform=all_axes[j].transAxes, va='top', fontsize=8, weight='bold')\n\n for ax in [ax3, ax4, ax5, ax6]:\n plt.sca(ax)\n ylims = plt.yticks()\n print(ylims)\n locs = ylims[0][1:-1]\n labels = []\n for j in range(len(locs)):\n labels.append('%.2f'%(locs[j]))\n plt.sca(ax)\n plt.yticks(locs, [\" \"]*len(locs))\n for ax in [ax1, ax3, ax5]:\n plt.sca(ax)\n xlims = plt.xticks()\n print(xlims)\n locs = xlims[0][1:-1]\n labels = []\n for j in range(len(locs)):\n labels.append('%.2f'%(locs[j]))\n plt.sca(ax)\n plt.xticks(locs, [\" \"]*len(locs))\n\n for ax in [ax2, ax4, ax6]:\n plt.sca(ax)\n labelsx = [num/1000 for num in locs]\n plt.xticks(locs, labelsx)\n\n for ax in [ax2, ax4, ax6]:\n ax.set_xlabel('Distance (km)')\n for ax in [ax1, ax2]:\n ax.set_ylabel('Height (m)')\n ax1.text(-0.5, 0.5, 'No Advection', transform=ax1.transAxes, va='center', fontsize=12, rotation='vertical')\n ax2.text(-0.5, 0.5, 'Advection', transform=ax2.transAxes, va='center', fontsize=12, rotation='vertical')\n\n plt.tight_layout(pad=1.0,h_pad=-1.0,w_pad=0.0)\n fig.savefig(folder_name + \"/\" + \"thumbnails_warm.eps\", transparent=False)\n plt.close(fig)\n\n\nif __name__ == \"__main__\":\n sns.set(palette='colorblind')\n sns.set(font_scale=0.8)\n sns.set_style(style='ticks')\n\n starting_directory = os.getcwd()\n os.chdir(os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'tests')))\n\n main_directory = os.getcwd()\n\n geometryX, geometryY, xz_boundary = make_geometry_grounded(-0.01, 50000, -150, 50, 100, 10)\n times = [0.5, 8.0, 15.5]\n directories = ['warm_noad', 'warm']\n dataName = 'width_timeseries'\n\n data_names = [os.path.join(directory, dataName) for directory in directories]\n\n snapshots = [[], []]\n for i in range(len(directories)):\n for j in range(len(times)):\n if times[j] == int(0):\n snapshots[i].append(int(0))\n else:\n os.chdir(directories[i])\n reader_paraview = parasim.PVDReader(FileName=dataName + '.pvd')\n times_imported = reader_paraview.GetPropertyValue('TimestepValues')\n times_temp = 0.0\n for k in range(len(times_imported)):\n if times_imported[k] >= times[j] and times_temp <= times[j]:\n snapshots[i].append(int(k))\n break\n else:\n times_temp = times_imported[k]\n os.chdir(main_directory)\n\n os.chdir(main_directory)\n\n print(snapshots)\n\n makeImage(snapshots, geometryX, geometryY, data_names, starting_directory, times)"
] |
[
[
"matplotlib.pyplot.tight_layout",
"numpy.linspace",
"matplotlib.pyplot.sca",
"matplotlib.pyplot.get_cmap",
"scipy.interpolate.interp1d",
"matplotlib.pyplot.close",
"matplotlib.pyplot.yticks",
"numpy.zeros",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
Quansight/pnumpy
|
[
"59d430f74168539a0710321c4eecb53d25db4833"
] |
[
"src/pnumpy/sort.py"
] |
[
"import os\nimport sys\n\n__all__ = [\n 'lexsort','sort', 'argsort','argmin', 'argmax', 'searchsorted']\n\nfrom pnumpy._pnumpy import getitem, lexsort32, lexsort64\nimport numpy as np\n\nfrom numpy import asarray, array, asanyarray\nfrom numpy import concatenate\n\n#array_function_dispatch = functools.partial(\n# overrides.array_function_dispatch, module='numpy')\n\n# functions that are now methods\ndef _wrapit(obj, method, *args, **kwds):\n try:\n wrap = obj.__array_wrap__\n except AttributeError:\n wrap = None\n result = getattr(asarray(obj), method)(*args, **kwds)\n if wrap:\n if not isinstance(result, mu.ndarray):\n result = asarray(result)\n result = wrap(result)\n return result\n\n\ndef _wrapfunc(obj, method, *args, **kwds):\n bound = getattr(obj, method, None)\n if bound is None:\n return _wrapit(obj, method, *args, **kwds)\n\n try:\n return bound(*args, **kwds)\n except TypeError:\n # A TypeError occurs if the object does have such a method in its\n # class, but its signature is not identical to that of NumPy's. This\n # situation has occurred in the case of a downstream library like\n # 'pandas'.\n #\n # Call _wrapit from within the except clause to ensure a potential\n # exception has a traceback chain.\n return _wrapit(obj, method, *args, **kwds)\n\n\ndef sort(a, axis=-1, kind=None, order=None):\n \"\"\"\n Return a sorted copy of an array.\n\n Parameters\n ----------\n a : array_like\n Array to be sorted.\n axis : int or None, optional\n Axis along which to sort. If None, the array is flattened before\n sorting. The default is -1, which sorts along the last axis.\n kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional\n Sorting algorithm. The default is 'quicksort'. Note that both 'stable'\n and 'mergesort' use timsort or radix sort under the covers and, in general,\n the actual implementation will vary with data type. The 'mergesort' option\n is retained for backwards compatibility.\n\n .. versionchanged:: 1.15.0.\n The 'stable' option was added.\n\n order : str or list of str, optional\n When `a` is an array with fields defined, this argument specifies\n which fields to compare first, second, etc. A single field can\n be specified as a string, and not all fields need be specified,\n but unspecified fields will still be used, in the order in which\n they come up in the dtype, to break ties.\n\n Returns\n -------\n sorted_array : ndarray\n Array of the same type and shape as `a`.\n\n Threading\n ---------\n Up to 8 threads\n\n See Also\n --------\n ndarray.sort : Method to sort an array in-place.\n argsort : Indirect sort.\n lexsort : Indirect stable sort on multiple keys.\n searchsorted : Find elements in a sorted array.\n partition : Partial sort.\n\n Notes\n -----\n The various sorting algorithms are characterized by their average speed,\n worst case performance, work space size, and whether they are stable. A\n stable sort keeps items with the same key in the same relative\n order. The four algorithms implemented in NumPy have the following\n properties:\n\n =========== ======= ============= ============ ========\n kind speed worst case work space stable\n =========== ======= ============= ============ ========\n 'quicksort' 1 O(n^2) 0 no\n 'heapsort' 3 O(n*log(n)) 0 no\n 'mergesort' 2 O(n*log(n)) ~n/2 yes\n 'timsort' 2 O(n*log(n)) ~n/2 yes\n =========== ======= ============= ============ ========\n\n .. note:: The datatype determines which of 'mergesort' or 'timsort'\n is actually used, even if 'mergesort' is specified. User selection\n at a finer scale is not currently available.\n\n All the sort algorithms make temporary copies of the data when\n sorting along any but the last axis. Consequently, sorting along\n the last axis is faster and uses less space than sorting along\n any other axis.\n\n The sort order for complex numbers is lexicographic. If both the real\n and imaginary parts are non-nan then the order is determined by the\n real parts except when they are equal, in which case the order is\n determined by the imaginary parts.\n\n Previous to numpy 1.4.0 sorting real and complex arrays containing nan\n values led to undefined behaviour. In numpy versions >= 1.4.0 nan\n values are sorted to the end. The extended sort order is:\n\n * Real: [R, nan]\n * Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj]\n\n where R is a non-nan real value. Complex values with the same nan\n placements are sorted according to the non-nan part if it exists.\n Non-nan values are sorted as before.\n\n .. versionadded:: 1.12.0\n\n quicksort has been changed to `introsort <https://en.wikipedia.org/wiki/Introsort>`_.\n When sorting does not make enough progress it switches to\n `heapsort <https://en.wikipedia.org/wiki/Heapsort>`_.\n This implementation makes quicksort O(n*log(n)) in the worst case.\n\n 'stable' automatically chooses the best stable sorting algorithm\n for the data type being sorted.\n It, along with 'mergesort' is currently mapped to\n `timsort <https://en.wikipedia.org/wiki/Timsort>`_\n or `radix sort <https://en.wikipedia.org/wiki/Radix_sort>`_\n depending on the data type.\n API forward compatibility currently limits the\n ability to select the implementation and it is hardwired for the different\n data types.\n\n .. versionadded:: 1.17.0\n\n Timsort is added for better performance on already or nearly\n sorted data. On random data timsort is almost identical to\n mergesort. It is now used for stable sort while quicksort is still the\n default sort if none is chosen. For timsort details, refer to\n `CPython listsort.txt <https://github.com/python/cpython/blob/3.7/Objects/listsort.txt>`_.\n 'mergesort' and 'stable' are mapped to radix sort for integer data types. Radix sort is an\n O(n) sort instead of O(n log n).\n\n .. versionchanged:: 1.18.0\n\n NaT now sorts to the end of arrays for consistency with NaN.\n\n Examples\n --------\n >>> a = np.array([[1,4],[3,1]])\n >>> np.sort(a) # sort along the last axis\n array([[1, 4],\n [1, 3]])\n >>> np.sort(a, axis=None) # sort the flattened array\n array([1, 1, 3, 4])\n >>> np.sort(a, axis=0) # sort along the first axis\n array([[1, 1],\n [3, 4]])\n\n Use the `order` keyword to specify a field to use when sorting a\n structured array:\n\n >>> dtype = [('name', 'S10'), ('height', float), ('age', int)]\n >>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),\n ... ('Galahad', 1.7, 38)]\n >>> a = np.array(values, dtype=dtype) # create a structured array\n >>> np.sort(a, order='height') # doctest: +SKIP\n array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),\n ('Lancelot', 1.8999999999999999, 38)],\n dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])\n\n Sort by age, then height if ages are equal:\n\n >>> np.sort(a, order=['age', 'height']) # doctest: +SKIP\n array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),\n ('Arthur', 1.8, 41)],\n dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])\n\n \"\"\"\n if axis is None:\n # flatten returns (1, N) for np.matrix, so always use the last axis\n a = asanyarray(a).flatten()\n axis = -1\n try:\n # attempt a parallel sort\n sort(a, kind=kind)\n return a\n except Exception:\n pass\n else:\n a = asanyarray(a).copy(order=\"K\")\n\n # normal numpy code\n a.sort(axis=axis, kind=kind, order=order)\n return a\n\ndef lexsort(*args, **kwargs):\n \"\"\"\n Perform an indirect stable sort using a sequence of keys.\n\n Given multiple sorting keys, which can be interpreted as columns in a\n spreadsheet, lexsort returns an array of integer indices that describes\n the sort order by multiple columns. The last key in the sequence is used\n for the primary sort order, the second-to-last key for the secondary sort\n order, and so on. The keys argument must be a sequence of objects that\n can be converted to arrays of the same shape. If a 2D array is provided\n for the keys argument, it's rows are interpreted as the sorting keys and\n sorting is according to the last row, second last row etc.\n\n Parameters\n ----------\n keys : (k, N) array or tuple containing k (N,)-shaped sequences\n The `k` different \"columns\" to be sorted. The last column (or row if\n `keys` is a 2D array) is the primary sort key.\n axis : int, optional\n Axis to be indirectly sorted. By default, sort over the last axis.\n\n Returns\n -------\n indices : (N,) ndarray of ints\n Array of indices that sort the keys along the specified axis.\n\n Threading\n ---------\n Up to 8 threads\n\n See Also\n --------\n argsort : Indirect sort.\n ndarray.sort : In-place sort.\n sort : Return a sorted copy of an array.\n\n Examples\n --------\n Sort names: first by surname, then by name.\n\n >>> surnames = ('Hertz', 'Galilei', 'Hertz')\n >>> first_names = ('Heinrich', 'Galileo', 'Gustav')\n >>> ind = np.lexsort((first_names, surnames))\n >>> ind\n array([1, 2, 0])\n\n >>> [surnames[i] + \", \" + first_names[i] for i in ind]\n ['Galilei, Galileo', 'Hertz, Gustav', 'Hertz, Heinrich']\n\n Sort two columns of numbers:\n\n >>> a = [1,5,1,4,3,4,4] # First column\n >>> b = [9,4,0,4,0,2,1] # Second column\n >>> ind = np.lexsort((b,a)) # Sort by a, then by b\n >>> ind\n array([2, 0, 4, 6, 5, 3, 1])\n\n >>> [(a[i],b[i]) for i in ind]\n [(1, 0), (1, 9), (3, 0), (4, 1), (4, 2), (4, 4), (5, 4)]\n\n Note that sorting is first according to the elements of ``a``.\n Secondary sorting is according to the elements of ``b``.\n\n A normal ``argsort`` would have yielded:\n\n >>> [(a[i],b[i]) for i in np.argsort(a)]\n [(1, 9), (1, 0), (3, 0), (4, 4), (4, 2), (4, 1), (5, 4)]\n\n Structured arrays are sorted lexically by ``argsort``:\n\n >>> x = np.array([(1,9), (5,4), (1,0), (4,4), (3,0), (4,2), (4,1)],\n ... dtype=np.dtype([('x', int), ('y', int)]))\n\n >>> np.argsort(x) # or np.argsort(x, order=('x', 'y'))\n array([2, 0, 4, 6, 5, 3, 1])\n \"\"\"\n\n try:\n return lexsort32(*args, **kwargs)\n except Exception:\n return np.lexsort(*args, **kwargs)\n\ndef argsort(a, axis=-1, kind=None, order=None):\n \"\"\"\n Returns the indices that would sort an array.\n\n Perform an indirect sort along the given axis using the algorithm specified\n by the `kind` keyword. It returns an array of indices of the same shape as\n `a` that index data along the given axis in sorted order.\n\n Parameters\n ----------\n a : array_like\n Array to sort.\n axis : int or None, optional\n Axis along which to sort. The default is -1 (the last axis). If None,\n the flattened array is used.\n kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional\n Sorting algorithm. The default is 'quicksort'. Note that both 'stable'\n and 'mergesort' use timsort under the covers and, in general, the\n actual implementation will vary with data type. The 'mergesort' option\n is retained for backwards compatibility.\n\n .. versionchanged:: 1.15.0.\n The 'stable' option was added.\n order : str or list of str, optional\n When `a` is an array with fields defined, this argument specifies\n which fields to compare first, second, etc. A single field can\n be specified as a string, and not all fields need be specified,\n but unspecified fields will still be used, in the order in which\n they come up in the dtype, to break ties.\n\n Returns\n -------\n index_array : ndarray, int\n Array of indices that sort `a` along the specified `axis`.\n If `a` is one-dimensional, ``a[index_array]`` yields a sorted `a`.\n More generally, ``np.take_along_axis(a, index_array, axis=axis)``\n always yields the sorted `a`, irrespective of dimensionality.\n\n See Also\n --------\n sort : Describes sorting algorithms used.\n lexsort : Indirect stable sort with multiple keys.\n ndarray.sort : Inplace sort.\n argpartition : Indirect partial sort.\n take_along_axis : Apply ``index_array`` from argsort\n to an array as if by calling sort.\n\n Notes\n -----\n See `sort` for notes on the different sorting algorithms.\n\n As of NumPy 1.4.0 `argsort` works with real/complex arrays containing\n nan values. The enhanced sort order is documented in `sort`.\n\n Examples\n --------\n One dimensional array:\n\n >>> x = np.array([3, 1, 2])\n >>> np.argsort(x)\n array([1, 2, 0])\n\n Two-dimensional array:\n\n >>> x = np.array([[0, 3], [2, 2]])\n >>> x\n array([[0, 3],\n [2, 2]])\n\n >>> ind = np.argsort(x, axis=0) # sorts along first axis (down)\n >>> ind\n array([[0, 1],\n [1, 0]])\n >>> np.take_along_axis(x, ind, axis=0) # same as np.sort(x, axis=0)\n array([[0, 2],\n [2, 3]])\n\n >>> ind = np.argsort(x, axis=1) # sorts along last axis (across)\n >>> ind\n array([[0, 1],\n [0, 1]])\n >>> np.take_along_axis(x, ind, axis=1) # same as np.sort(x, axis=1)\n array([[0, 3],\n [2, 2]])\n\n Indices of the sorted elements of a N-dimensional array:\n\n >>> ind = np.unravel_index(np.argsort(x, axis=None), x.shape)\n >>> ind\n (array([0, 1, 1, 0]), array([0, 0, 1, 1]))\n >>> x[ind] # same as np.sort(x, axis=None)\n array([0, 2, 2, 3])\n\n Sorting with keys:\n\n >>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])\n >>> x\n array([(1, 0), (0, 1)],\n dtype=[('x', '<i4'), ('y', '<i4')])\n\n >>> np.argsort(x, order=('x','y'))\n array([1, 0])\n\n >>> np.argsort(x, order=('y','x'))\n array([0, 1])\n\n \"\"\"\n return _wrapfunc(a, 'argsort', axis=axis, kind=kind, order=order)\n\n\ndef _argmax_dispatcher(a, axis=None, out=None):\n return (a, out)\n\n\ndef argmax(a, axis=None, out=None):\n \"\"\"\n Returns the indices of the maximum values along an axis.\n\n Parameters\n ----------\n a : array_like\n Input array.\n axis : int, optional\n By default, the index is into the flattened array, otherwise\n along the specified axis.\n out : array, optional\n If provided, the result will be inserted into this array. It should\n be of the appropriate shape and dtype.\n\n Returns\n -------\n index_array : ndarray of ints\n Array of indices into the array. It has the same shape as `a.shape`\n with the dimension along `axis` removed.\n\n See Also\n --------\n ndarray.argmax, argmin\n amax : The maximum value along a given axis.\n unravel_index : Convert a flat index into an index tuple.\n take_along_axis : Apply ``np.expand_dims(index_array, axis)``\n from argmax to an array as if by calling max.\n\n Notes\n -----\n In case of multiple occurrences of the maximum values, the indices\n corresponding to the first occurrence are returned.\n\n Examples\n --------\n >>> a = np.arange(6).reshape(2,3) + 10\n >>> a\n array([[10, 11, 12],\n [13, 14, 15]])\n >>> np.argmax(a)\n 5\n >>> np.argmax(a, axis=0)\n array([1, 1, 1])\n >>> np.argmax(a, axis=1)\n array([2, 2])\n\n Indexes of the maximal elements of a N-dimensional array:\n\n >>> ind = np.unravel_index(np.argmax(a, axis=None), a.shape)\n >>> ind\n (1, 2)\n >>> a[ind]\n 15\n\n >>> b = np.arange(6)\n >>> b[1] = 5\n >>> b\n array([0, 5, 2, 3, 4, 5])\n >>> np.argmax(b) # Only the first occurrence is returned.\n 1\n\n >>> x = np.array([[4,2,3], [1,0,3]])\n >>> index_array = np.argmax(x, axis=-1)\n >>> # Same as np.max(x, axis=-1, keepdims=True)\n >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)\n array([[4],\n [3]])\n >>> # Same as np.max(x, axis=-1)\n >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1).squeeze(axis=-1)\n array([4, 3])\n\n \"\"\"\n return _wrapfunc(a, 'argmax', axis=axis, out=out)\n\n\ndef _argmin_dispatcher(a, axis=None, out=None):\n return (a, out)\n\n\ndef argmin(a, axis=None, out=None):\n \"\"\"\n Returns the indices of the minimum values along an axis.\n\n Parameters\n ----------\n a : array_like\n Input array.\n axis : int, optional\n By default, the index is into the flattened array, otherwise\n along the specified axis.\n out : array, optional\n If provided, the result will be inserted into this array. It should\n be of the appropriate shape and dtype.\n\n Returns\n -------\n index_array : ndarray of ints\n Array of indices into the array. It has the same shape as `a.shape`\n with the dimension along `axis` removed.\n\n See Also\n --------\n ndarray.argmin, argmax\n amin : The minimum value along a given axis.\n unravel_index : Convert a flat index into an index tuple.\n take_along_axis : Apply ``np.expand_dims(index_array, axis)``\n from argmin to an array as if by calling min.\n\n Notes\n -----\n In case of multiple occurrences of the minimum values, the indices\n corresponding to the first occurrence are returned.\n\n Examples\n --------\n >>> a = np.arange(6).reshape(2,3) + 10\n >>> a\n array([[10, 11, 12],\n [13, 14, 15]])\n >>> np.argmin(a)\n 0\n >>> np.argmin(a, axis=0)\n array([0, 0, 0])\n >>> np.argmin(a, axis=1)\n array([0, 0])\n\n Indices of the minimum elements of a N-dimensional array:\n\n >>> ind = np.unravel_index(np.argmin(a, axis=None), a.shape)\n >>> ind\n (0, 0)\n >>> a[ind]\n 10\n\n >>> b = np.arange(6) + 10\n >>> b[4] = 10\n >>> b\n array([10, 11, 12, 13, 10, 15])\n >>> np.argmin(b) # Only the first occurrence is returned.\n 0\n\n >>> x = np.array([[4,2,3], [1,0,3]])\n >>> index_array = np.argmin(x, axis=-1)\n >>> # Same as np.min(x, axis=-1, keepdims=True)\n >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)\n array([[2],\n [0]])\n >>> # Same as np.max(x, axis=-1)\n >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1).squeeze(axis=-1)\n array([2, 0])\n\n \"\"\"\n return _wrapfunc(a, 'argmin', axis=axis, out=out)\n\n\ndef _searchsorted_dispatcher(a, v, side=None, sorter=None):\n return (a, v, sorter)\n\n\ndef searchsorted(a, v, side='left', sorter=None):\n \"\"\"\n Find indices where elements should be inserted to maintain order.\n\n Find the indices into a sorted array `a` such that, if the\n corresponding elements in `v` were inserted before the indices, the\n order of `a` would be preserved.\n\n Assuming that `a` is sorted:\n\n ====== ============================\n `side` returned index `i` satisfies\n ====== ============================\n left ``a[i-1] < v <= a[i]``\n right ``a[i-1] <= v < a[i]``\n ====== ============================\n\n Parameters\n ----------\n a : 1-D array_like\n Input array. If `sorter` is None, then it must be sorted in\n ascending order, otherwise `sorter` must be an array of indices\n that sort it.\n v : array_like\n Values to insert into `a`.\n side : {'left', 'right'}, optional\n If 'left', the index of the first suitable location found is given.\n If 'right', return the last such index. If there is no suitable\n index, return either 0 or N (where N is the length of `a`).\n sorter : 1-D array_like, optional\n Optional array of integer indices that sort array a into ascending\n order. They are typically the result of argsort.\n\n .. versionadded:: 1.7.0\n\n Returns\n -------\n indices : array of ints\n Array of insertion points with the same shape as `v`.\n\n See Also\n --------\n sort : Return a sorted copy of an array.\n histogram : Produce histogram from 1-D data.\n\n Notes\n -----\n Binary search is used to find the required insertion points.\n\n As of NumPy 1.4.0 `searchsorted` works with real/complex arrays containing\n `nan` values. The enhanced sort order is documented in `sort`.\n\n This function uses the same algorithm as the builtin python `bisect.bisect_left`\n (``side='left'``) and `bisect.bisect_right` (``side='right'``) functions,\n which is also vectorized in the `v` argument.\n\n Examples\n --------\n >>> np.searchsorted([1,2,3,4,5], 3)\n 2\n >>> np.searchsorted([1,2,3,4,5], 3, side='right')\n 3\n >>> np.searchsorted([1,2,3,4,5], [-10, 10, 2, 3])\n array([0, 5, 1, 2])\n\n \"\"\"\n return _wrapfunc(a, 'searchsorted', v, side=side, sorter=sorter)\n\n"
] |
[
[
"numpy.asarray",
"numpy.asanyarray",
"numpy.lexsort"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
YeWR/cogdl
|
[
"5be13cda808c44333f7059db11d13a1d0f190ffa"
] |
[
"cogdl/datasets/gtn_data.py"
] |
[
"import sys\nimport time\nimport os\nimport os.path as osp\nimport requests\nimport shutil\nimport tqdm\nimport pickle\nimport numpy as np\n\nimport torch\n\nfrom cogdl.data import Data, Dataset, download_url\n\nfrom . import register_dataset\n\n\ndef untar(path, fname, deleteTar=True):\n \"\"\"\n Unpacks the given archive file to the same directory, then (by default)\n deletes the archive file.\n \"\"\"\n print('unpacking ' + fname)\n fullpath = os.path.join(path, fname)\n shutil.unpack_archive(fullpath, path)\n if deleteTar:\n os.remove(fullpath)\n\nclass GTNDataset(Dataset):\n r\"\"\"The network datasets \"ACM\", \"DBLP\" and \"IMDB\" from the\n `\"Graph Transformer Networks\"\n <https://arxiv.org/abs/1911.06455>`_ paper.\n \n Args:\n root (string): Root directory where the dataset should be saved.\n name (string): The name of the dataset (:obj:`\"gtn-acm\"`,\n :obj:`\"gtn-dblp\"`, :obj:`\"gtn-imdb\"`).\n \"\"\"\n\n def __init__(self, root, name):\n self.name = name\n self.url = f'https://github.com/cenyk1230/gtn-data/blob/master/{name}.zip?raw=true'\n super(GTNDataset, self).__init__(root)\n self.data = torch.load(self.processed_paths[0])\n self.num_classes = torch.max(self.data.train_target).item() + 1\n self.num_edge = len(self.data.adj)\n self.num_nodes = self.data.x.shape[0]\n\n\n @property\n def raw_file_names(self):\n names = [\"edges.pkl\", \"labels.pkl\", \"node_features.pkl\"]\n return names\n\n @property\n def processed_file_names(self):\n return [\"data.pt\"]\n\n def read_gtn_data(self, folder):\n edges = pickle.load(open(osp.join(folder, 'edges.pkl'), 'rb'))\n labels = pickle.load(open(osp.join(folder, 'labels.pkl'), 'rb'))\n node_features = pickle.load(open(osp.join(folder, 'node_features.pkl'), 'rb'))\n\n data = Data()\n data.x = torch.from_numpy(node_features).type(torch.FloatTensor)\n\n num_nodes = edges[0].shape[0]\n\n node_type = np.zeros((num_nodes), dtype=int)\n assert len(edges)==4\n assert len(edges[0].nonzero())==2\n \n node_type[edges[0].nonzero()[0]] = 0\n node_type[edges[0].nonzero()[1]] = 1\n node_type[edges[1].nonzero()[0]] = 1\n node_type[edges[1].nonzero()[1]] = 0 \n node_type[edges[2].nonzero()[0]] = 0\n node_type[edges[2].nonzero()[1]] = 2\n node_type[edges[3].nonzero()[0]] = 2\n node_type[edges[3].nonzero()[1]] = 0\n \n print(node_type)\n data.pos = torch.from_numpy(node_type)\n \n edge_list = []\n for i, edge in enumerate(edges):\n edge_tmp = torch.from_numpy(np.vstack((edge.nonzero()[0], edge.nonzero()[1]))).type(torch.LongTensor)\n edge_list.append(edge_tmp)\n data.edge_index = torch.cat(edge_list, 1)\n \n A = [] \n for i,edge in enumerate(edges):\n edge_tmp = torch.from_numpy(np.vstack((edge.nonzero()[0], edge.nonzero()[1]))).type(torch.LongTensor)\n value_tmp = torch.ones(edge_tmp.shape[1]).type(torch.FloatTensor)\n A.append((edge_tmp,value_tmp))\n edge_tmp = torch.stack((torch.arange(0,num_nodes),torch.arange(0,num_nodes))).type(torch.LongTensor)\n value_tmp = torch.ones(num_nodes).type(torch.FloatTensor)\n A.append((edge_tmp,value_tmp))\n data.adj = A\n\n data.train_node = torch.from_numpy(np.array(labels[0])[:,0]).type(torch.LongTensor)\n data.train_target = torch.from_numpy(np.array(labels[0])[:,1]).type(torch.LongTensor)\n data.valid_node = torch.from_numpy(np.array(labels[1])[:,0]).type(torch.LongTensor)\n data.valid_target = torch.from_numpy(np.array(labels[1])[:,1]).type(torch.LongTensor)\n data.test_node = torch.from_numpy(np.array(labels[2])[:,0]).type(torch.LongTensor)\n data.test_target = torch.from_numpy(np.array(labels[2])[:,1]).type(torch.LongTensor)\n \n y = np.zeros((num_nodes), dtype=int)\n x_index = torch.cat((data.train_node, data.valid_node, data.test_node))\n y_index = torch.cat((data.train_target, data.valid_target, data.test_target))\n y[x_index.numpy()] = y_index.numpy()\n data.y = torch.from_numpy(y)\n self.data = data\n\n def get(self, idx):\n assert idx == 0\n return self.data\n \n def apply_to_device(self, device):\n self.data.x = self.data.x.to(device)\n\n self.data.train_node = self.data.train_node.to(device)\n self.data.valid_node = self.data.valid_node.to(device)\n self.data.test_node = self.data.test_node.to(device)\n\n self.data.train_target = self.data.train_target.to(device)\n self.data.valid_target = self.data.valid_target.to(device)\n self.data.test_target = self.data.test_target.to(device)\n\n new_adj = []\n for (t1, t2) in self.data.adj:\n new_adj.append((t1.to(device), t2.to(device)))\n self.data.adj = new_adj\n\n def download(self):\n download_url(self.url, self.raw_dir, name=self.name + '.zip')\n untar(self.raw_dir, self.name + '.zip')\n\n def process(self):\n self.read_gtn_data(self.raw_dir)\n torch.save(self.data, self.processed_paths[0])\n\n def __repr__(self):\n return \"{}()\".format(self.name)\n\n\n@register_dataset(\"gtn-acm\")\nclass ACM_GTNDataset(GTNDataset):\n def __init__(self):\n dataset = \"gtn-acm\"\n path = osp.join(osp.dirname(osp.realpath(__file__)), \"../..\", \"data\", dataset)\n super(ACM_GTNDataset, self).__init__(path, dataset)\n\n\n@register_dataset(\"gtn-dblp\")\nclass DBLP_GTNDataset(GTNDataset):\n def __init__(self):\n dataset = \"gtn-dblp\"\n path = osp.join(osp.dirname(osp.realpath(__file__)), \"../..\", \"data\", dataset)\n super(DBLP_GTNDataset, self).__init__(path, dataset)\n\n\n@register_dataset(\"gtn-imdb\")\nclass IMDB_GTNDataset(GTNDataset):\n def __init__(self):\n dataset = \"gtn-imdb\"\n path = osp.join(osp.dirname(osp.realpath(__file__)), \"../..\", \"data\", dataset)\n super(IMDB_GTNDataset, self).__init__(path, dataset)\n"
] |
[
[
"torch.ones",
"torch.max",
"torch.cat",
"torch.load",
"torch.from_numpy",
"torch.arange",
"numpy.array",
"numpy.zeros",
"torch.save"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
PiotrKrasnowski/Speech_Encryption
|
[
"305a01b82aabb03bedc9036dd69fe18df90ef57b"
] |
[
"a_full_model.py"
] |
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport time\nfrom copy import copy\nimport os\n\nfrom single_pitch import single_pitch\nfrom channel import channel \nfrom pseudo_speech import Pseudospeech_Synthetizer_class\nfrom encryption import Encryption_class\nfrom speech_analyzer import Speech_Analyzer_class\nfrom speech_synthesizer import Speech_Synthesizer_class\n\n################################################################\n\nmy_analyzer = Speech_Analyzer_class(\"speech_model.npz\",\"spherical_code.npz\") # model parameters generated by speech_model.py and spherical_code.py\nmy_encryptor = Encryption_class(\"spherical_code.npz\") # model parameters generated by spherical_code.py\nmy_ps_sp_synthetizer = Pseudospeech_Synthetizer_class(\"pseudospeech_model.npz\",\"spherical_code.npz\") # model parameters generated by pseudo_speech_model.py and spherical_code.py\nmy_sp_synthesizer = Speech_Synthesizer_class(\"speech_model.npz\") # model parameters generated by speech_model.py\n\n# pseudo random data used for enciphering/deciphering\nkeybits = np.random.randint(2, size = (160, 10000))\n\nprint(\"step 1\")\nspeech_samples = np.fromfile(\"temp/hts1a.raw\", dtype='int16')\n# print(speech_samples.shape)\n\n##### SPEECH ENCODING ######\nprint(\"step 2\")\npitch_indices, energy_indices, timbre_indices = my_analyzer.analyze_speech(speech_samples)\n\n###### ENCRYPTION ######\nprint(\"step 3\")\npitch_indices_enc, energy_indices_enc, timbre_indices_enc = my_encryptor.speech_encryption(pitch_indices, energy_indices, timbre_indices, keybits)\n\n###### PSEUDOSPEECH SYNTHESIS ######\nprint(\"step 4\")\nsignal = my_synthetizer.synthesize_pseudospeech(pitch_indices_enc, energy_indices_enc, timbre_indices_enc)\n\n###### CHANNEL DISTORTION ######\nprint(\"step 5\")\nsignal_rec = channel(signal, \"SILK\", 16000, 48000) # data samples, codec type, sampling frequency (Hz), compression rate (b/s)\n\n###### PSEUDOSPEECH ANALYSIS ######\nprint(\"step 6\")\npitch_indices_rec, energy_indices_rec, timbre_indices_rec = my_synthetizer.analyze_pseudospeech(signal_rec)\n\n# ###### DECRYPTION ######\nprint(\"step 7\")\npitch_indices_dec, energy_indices_dec, timbre_indices_dec = my_encryptor.speech_decryption(pitch_indices_rec, energy_indices_rec, timbre_indices_rec, keybits)\n\n# ###### SPEECH SYNTHESIS ######\nprint(\"step 8\")\nmy_speech_synthesizer.synthesize_speech(pitch_indices_dec, energy_indices_dec, timbre_indices_dec) # save to file / input of the narrowband (8kHz) LPCNet\n\nprint(\"Finished\")\n\n\n################\n\n# plt.figure()\n# plt.plot(energy_indices)\n\n# plt.figure()\n# plt.plot(pitch_indices)\n\n# plt.figure()\n# plt.plot(np.transpose(timbre_indices))\n\n################\n\n# plt.figure()\n# plt.plot(energy_indices_enc)\n\n# plt.figure()\n# plt.plot(pitch_indices_enc)\n\n# plt.figure()\n# plt.plot(np.transpose(timbre_indices_enc))\n\n################\n\n# plt.figure()\n# plt.plot(energy_indices_rec)\n\n# plt.figure()\n# plt.plot(pitch_indices_rec)\n\n# plt.figure()\n# plt.plot(np.transpose(timbre_indices_rec))\n\n################\n\n# plt.figure()\n# plt.plot(energy_indices_dec)\n\n# plt.figure()\n# plt.plot(pitch_indices_dec)\n\n# plt.figure()\n# plt.plot(np.transpose(timbre_indices_dec))\n\n################\n\nplt.show()\n\n"
] |
[
[
"numpy.fromfile",
"matplotlib.pyplot.show",
"numpy.random.randint"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
nifunk/GNNMushroomRL
|
[
"d0d8eefdc10bca62e7cb536d65ea619607be755b",
"d0d8eefdc10bca62e7cb536d65ea619607be755b"
] |
[
"mushroom_rl/core/parallelization_tools/step_sequence.py",
"mushroom_rl/algorithms/value/batch_td/lspi.py"
] |
[
"# Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and\n# Technical University of Darmstadt.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# 3. Neither the name of Fabio Muratore, Honda Research Institute Europe GmbH,\n# or Technical University of Darmstadt, nor the names of its contributors may\n# be used to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL FABIO MURATORE, HONDA RESEARCH INSTITUTE EUROPE GMBH,\n# OR TECHNICAL UNIVERSITY OF DARMSTADT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport functools\nimport numpy as np\nimport operator\nimport random\nimport scipy.signal as signal\nimport torch as to\nfrom collections.abc import Iterable\nfrom copy import deepcopy\nfrom math import ceil\nfrom typing import Sequence, Type, Optional, Union, Callable, Tuple\n\nimport pyrado\nfrom pyrado.sampling.data_format import stack_to_format, to_format, cat_to_format, new_tuple\nfrom pyrado.sampling.utils import gen_shuffled_batch_idcs, gen_ordered_batch_idcs\n\n\ndef _index_to_int(idx, n):\n # Index conversion\n idx = operator.index(idx)\n # Check negative index\n if idx < 0:\n idx += n\n # Check bounds\n if idx < 0 or idx >= n:\n raise IndexError\n return idx\n\n\nclass DictIndexProxy:\n \"\"\" Views a slice through a dict of lists or tensors. \"\"\"\n\n __slots__ = (\"__dict__\", \"_obj\", \"_index\", \"_prefix\")\n\n def __init__(self, obj: dict, index: int, path: Optional[str] = None):\n super().__init__()\n\n self._obj = obj\n self._index = index\n if path:\n self._prefix = path + \".\"\n else:\n self._prefix = \"\"\n\n def _process_key(self, key: str, index: int, error_type: Type[Exception]):\n return key, index\n\n def _get_keyed_value(self, key, error_type: Type[Exception] = RuntimeError):\n # Obtain keyed value from obj dict\n value = self._obj.get(key, None)\n\n if value is None:\n # Try pluralized keys\n value = self._obj.get(key + \"s\", None)\n if value is None:\n raise error_type(f\"No entry named {self._prefix}{key}\")\n\n return value\n\n def _index_value(self, key, value, index, error_type: Type[Exception] = RuntimeError):\n # Obtain indexed element from value\n if isinstance(value, dict):\n # Return subdict proxy\n return DictIndexProxy(value, index, self._prefix + key)\n elif isinstance(value, tuple):\n # Return tuple of slices\n # Since we can't proxy a tuple, we slice eagerly\n # Use type(value) to support named tuples. (the keys is still index though)\n return new_tuple(\n type(value), (self._index_value(f\"{key}[{i}]\", v, index, error_type) for i, v in enumerate(value))\n )\n elif isinstance(value, (to.Tensor, np.ndarray)):\n # Return slice of ndarray / tensor\n return value[index, ...]\n elif isinstance(value, list):\n # Return list item\n return value[index]\n else:\n # Unsupported type\n raise error_type(f\"Entry {self._prefix}{key} has un-gettable type {type(value)}\")\n\n def _get_indexed_value(self, key, error_type: Type[Exception] = RuntimeError):\n real_key, index = self._process_key(key, self._index, error_type)\n\n # Obtain keyed value list from obj dict\n value = self._get_keyed_value(real_key, error_type=error_type)\n\n return self._index_value(key, value, index, error_type)\n\n def _set_indexed_value(self, key, new_value, error_type: Type[Exception] = RuntimeError):\n real_key, index = self._process_key(key, self._index, error_type)\n\n # Obtain keyed value list from obj dict\n value = self._get_keyed_value(real_key, error_type=error_type)\n\n # Set value to data\n if isinstance(value, (to.Tensor, np.ndarray)):\n # Set slice of ndarray/tensor\n value[index, ...] = new_value\n elif isinstance(value, list):\n # Set list item\n value[index] = new_value\n else:\n # Don't support setting dict proxies\n raise error_type(f\"Entry {key} has un-settable type {type(value)}\")\n\n def __getattr__(self, key):\n if key.startswith(\"_\"):\n raise AttributeError\n result = self._get_indexed_value(key, error_type=AttributeError)\n self.__dict__[key] = result\n return result\n\n def __setattr__(self, key, value):\n if not key.startswith(\"_\"):\n try:\n self._set_indexed_value(key, value, error_type=AttributeError)\n except AttributeError:\n pass\n else:\n self.__dict__[key] = value\n return\n object.__setattr__(self, key, value)\n\n def __dir__(self):\n # List dict items not starting with _\n return [k for k in self._obj if not k.startswith(\"_\")]\n\n # Define getitem and setitem too, helps when return attr is a keyword\n def __getitem__(self, key):\n result = self._get_indexed_value(key, error_type=KeyError)\n self.__dict__[key] = result\n return result\n\n def __setitem__(self, key, value):\n self._set_indexed_value(key, value, error_type=KeyError)\n self.__dict__[key] = value\n\n # Serialize only dict and index\n def __getstate__(self):\n return {\"obj\", self._obj, \"index\", self._index}\n\n def __setstate__(self, state):\n self._obj = state[\"obj\"]\n self._index = state[\"index\"]\n\n\nclass Step(DictIndexProxy):\n \"\"\"\n A single step in a rollout.\n\n This object is a proxy, referring a specific index in the rollout. When querying an attribute from the step,\n it will try to return the corresponding slice from the rollout. Additionally, one can prefix attributes with `next_`\n to access the value for the next step, i.e. `next_observations` the observation made at the start of the next step.\n \"\"\"\n\n __slots__ = \"_rollout\"\n\n def __init__(self, rollout, index):\n \"\"\"\n Constructor\n\n :param rollout: `StepSequence` object to which this step belongs\n :param index: index of this step in the rollout\n \"\"\"\n # Call DictIndexProxy's constructor\n super(Step, self).__init__(rollout.__dict__, index)\n\n self._rollout = rollout\n\n def _process_key(self, key: str, index: int, error_type: Type[Exception]):\n if key.startswith(\"next_\"):\n if not self._rollout.continuous:\n raise error_type(\"Access to next element is not supported for non-continuous rollouts!\")\n key = key[5:]\n index += 1\n if key not in self._rollout.data_names and key + \"s\" not in self._rollout.data_names and key != \"done\":\n raise error_type(f\"No such rollout data field: {key}\")\n return key, index\n\n # Serialize rollout and index\n def __getstate__(self):\n return {\"rollout\", self._rollout, \"index\", self._index}\n\n def __setstate__(self, state):\n self._rollout = state[\"rollout\"]\n self._obj = self._rollout.__dict__\n self._index = state[\"index\"]\n\n\nclass StepSequence(Sequence[Step]):\n \"\"\"\n A sequence of steps.\n\n During the rollout, the values of different variables are recorded. This class provides efficient storage and\n access for these values. The constructor accepts a list of step entries for each variable. For every step,\n the list should contain a Tensor/ndarray of values for that step. The shape of these tensors must be the same for\n all step entries. The passed tensors are then stacked, so that the first dimension is the step count.\n Some values, like the observations, can have one more element then there are steps to encode the state after the\n last step. Additionally, the step entries may be dicts to support keyed storage. A list of dicts is converted to\n a dict of lists, each of which will be regularly stacked. Apart from the variable-based view, the rollout can also\n be seen as a sequence of steps. Each Step object is a proxy, it's attributes refer to the respective slice of the\n corresponding variable. The only required result variable are `rewards`, observations`, and `actions`.\n All other variables are optional. Common optional ones are `states` and `rollout_info`.\n\n .. note::\n Storing PyTorch tensors with gradient tracing is NOT supported. The rationale behind this is eager error\n avoidance. The only reason you would add them is to profit from the optimized slicing, but using that with\n gradient tracking risks lingering incomplete graphs.\n \"\"\"\n\n rewards: Union[np.ndarray, to.Tensor]\n observations: Union[np.ndarray, to.Tensor]\n actions: Union[np.ndarray, to.Tensor]\n\n # Set of required rollout fields in addition to rewards, observations, actions. Putting this into a class field\n # instead of using the constructor arguments reduces duplicate code and allows to override it during unit tests.\n required_fields = {}\n\n def __init__(\n self,\n *,\n complete: Optional[bool] = True,\n rollout_info=None,\n data_format: Optional[str] = None,\n done: Optional[np.ndarray] = None,\n continuous: Optional[bool] = True,\n rollout_bounds=None,\n rewards: Sequence,\n observations: Sequence,\n actions: Sequence,\n **data,\n ):\n # print (data)\n \"\"\"\n Constructor\n\n :param complete: `False` if the rollout is incomplete, i.e. as part of a mini-batch\n :param rollout_info: data staying constant through the whole episode\n :param data_format: 'torch' to use Tensors, 'numpy' to use ndarrays.\n Will use Tensors if any data argument does, else ndarrays\n :param done: boolean ndarray, specifying for each step whether it led to termination.\n The last step of continuous rollouts, i.e. not mini-batches, is done if `complete` is `True`.\n :param continuous: true if the steps form one continuous sequence.\n :param rewards: sequence of reward values, determines sequence length\n :param observations: sequence of observation values, the length must be `len(rewards) + 1`\n :param actions: sequence of action values, the length must be `len(rewards)`\n :param data: additional data lists, their length must be `len(rewards)` or `len(rewards) + 1`\n \"\"\"\n # Obtain rollout length from reward list\n self.length = len(rewards)\n if self.length == 0:\n raise pyrado.ShapeErr(msg=\"StepSequence cannot be empty!\")\n\n # Set singular attributes\n self.rollout_info = rollout_info\n self.continuous = continuous\n\n # Infer if this instance is using numpy arrays or PyTorch tensors\n if data_format is None:\n # We ignore rewards here since it's probably scalar\n for value in data.values():\n if isinstance(value, to.Tensor) or (isinstance(value, list) and isinstance(value[0], to.Tensor)):\n data_format = \"torch\"\n break\n else:\n # Use numpy by default\n data_format = \"numpy\"\n self._data_format = data_format\n\n # Check for missing extra fields\n missing_fields = StepSequence.required_fields - data.keys()\n if missing_fields:\n raise ValueError(f\"Missing required data fields: {missing_fields}\")\n\n # Set mandatory data fields\n self._data_names = []\n self.add_data(\"rewards\", rewards)\n self.add_data(\"observations\", observations)\n self.add_data(\"actions\", actions)\n\n # Set other data fields and verify their length\n for name, value in data.items():\n self.add_data(name, value)\n\n # Set done list if any. The done list is always a numpy array since torch doesn't support boolean tensors.\n if done is None:\n done = np.zeros(self.length, dtype=np.bool)\n if complete and continuous:\n done[-1] = True\n else:\n done = np.asarray(done, dtype=np.bool)\n assert done.shape[0] == self.length\n self.done = done\n\n # Compute rollout bounds from done list (yes this is not exactly safe...)\n # The bounds list has one extra entry 0, this simplifies queries greatly.\n # bounds[i] = start of rollout i; bounds[i+1]=end of rollout i\n if continuous:\n if rollout_bounds is None:\n rollout_bounds = [0]\n rollout_bounds.extend(np.flatnonzero(done) + 1)\n if not done[-1]:\n rollout_bounds.append(self.length)\n else:\n # Validate externally passed bounds.\n for i in range(len(rollout_bounds) - 1):\n assert rollout_bounds[i] < rollout_bounds[i + 1]\n assert rollout_bounds[0] == 0\n assert rollout_bounds[-1] == self.length\n self._rollout_bounds = np.array(rollout_bounds)\n else:\n self._rollout_bounds = None\n\n @property\n def data_format(self) -> str:\n \"\"\" Get the name of data format ('torch' or 'numpy'). \"\"\"\n return self._data_format\n\n @property\n def data_names(self) -> Sequence[str]:\n \"\"\" Get the list of data attribute names. \"\"\"\n return self._data_names\n\n @property\n def rollout_bounds(self) -> np.ndarray:\n return self._rollout_bounds\n\n @property\n def rollout_count(self):\n \"\"\" Count the number of sub-rollouts inside this step sequence. \"\"\"\n if not self.continuous:\n raise pyrado.ValueErr(msg=\"Sub-rollouts are only supported on continuous data.\")\n return len(self._rollout_bounds) - 1\n\n @property\n def rollout_lengths(self):\n \"\"\" Lengths of sub-rollouts. \"\"\"\n if not self.continuous:\n raise pyrado.ValueErr(msg=\"Sub-rollouts are only supported on continuous data.\")\n bounds = self._rollout_bounds\n return bounds[1:] - bounds[:-1]\n\n def __len__(self):\n \"\"\" Get the step sequence's length. \"\"\"\n return self.length\n\n def __getitem__(self, index):\n if isinstance(index, slice) or isinstance(index, Iterable):\n # Return a StepSequence object with the subset. Build sliced data dict.\n sliced_data = {name: self._slice_entry(self.__dict__[name], index) for name in self._data_names}\n sliced_data = {k: v for k, v in sliced_data.items() if v is not None}\n\n # Check if the slice is continuous\n continuous = isinstance(index, slice) and (index.step is None or index.step == 1)\n rollout_bounds = None\n if continuous:\n # Slice rollout bounds too.\n start, end, _ = index.indices(self.length)\n rollout_bounds = [0]\n for b in self._rollout_bounds:\n if start < b < end:\n rollout_bounds.append(b - start)\n rollout_bounds.append(end - start)\n\n return StepSequence(\n rollout_info=self.rollout_info,\n data_format=self._data_format,\n done=self.done[index],\n continuous=continuous,\n rollout_bounds=rollout_bounds,\n **sliced_data,\n )\n\n # Should be a singular element index. Return step proxy.\n return Step(self, _index_to_int(index, self.length))\n\n def __map_tensors(self, mapper, elem):\n if isinstance(elem, dict):\n # Modify dict in-place\n for k in elem.keys():\n elem[k] = self.__map_tensors(mapper, elem[k])\n return elem\n if isinstance(elem, tuple):\n # Can't modify in place since it's a tuple\n return new_tuple(type(elem), (self.__map_tensors(mapper, part) for part in elem))\n\n # Tensor element\n return mapper(elem)\n\n def _validate_data_size(self, name, value):\n # In torch case: check that we don't mess with gradients\n if isinstance(value, to.Tensor):\n assert not value.requires_grad, (\n \"Do not add gradient-sensitive tensors to SampleCollections. \"\n \"This is a fast road to weird retain_graph errors!\"\n )\n\n # Check type of data\n if isinstance(value, dict):\n # Validate dict entries\n for k, v in value.items():\n self._validate_data_size(f\"{name}.{k}\", v)\n return\n if isinstance(value, tuple):\n # Validate dict entries\n for i, v in enumerate(value):\n self._validate_data_size(f\"{name}[{i}]\", v)\n return\n if isinstance(value, (np.ndarray, to.Tensor)):\n # A single array. The first dimension must match\n vlen = value.shape[0]\n else:\n # Should be a sequence\n assert isinstance(value, Sequence)\n vlen = len(value)\n\n if self.continuous:\n if not (vlen == self.length or vlen == self.length + 1):\n raise pyrado.ShapeErr(\n msg=f\"The data list {name} must have {self.length} or {self.length}+1 elements,\"\n f\"but has {vlen} elements.\"\n )\n else:\n # Disallow +1 tensors\n if not vlen == self.length:\n raise pyrado.ShapeErr(\n msg=f\"The data list {name} must have {self.length} elements,\" f\"but has {vlen} elements.\"\n )\n\n def _slice_entry(self, entry, index: slice):\n if isinstance(entry, dict):\n return {k: self._slice_entry(v, index) for k, v in entry.items()}\n if isinstance(entry, tuple):\n return new_tuple(type(entry), (self._slice_entry(e, index) for e in entry))\n elif isinstance(entry, (to.Tensor, np.ndarray)):\n return entry[index, ...]\n elif isinstance(entry, list):\n return entry[index]\n else:\n return None # unsupported\n\n def _truncate_after_last(self, entry):\n if isinstance(entry, dict):\n return {k: self._truncate_after_last(v) for k, v in entry.items()}\n if isinstance(entry, tuple):\n return new_tuple(type(entry), (self._truncate_after_last(v) for v in entry))\n elif isinstance(entry, (to.Tensor, np.ndarray)):\n if entry.shape[0] == self.length + 1:\n return entry[:-1, ...]\n elif isinstance(entry, list):\n if len(entry) == self.length + 1:\n return entry[:-1]\n # No truncation\n return entry\n\n def add_data(self, name: str, value=None, item_shape: tuple = None, with_after_last: Optional[bool] = False):\n \"\"\"\n Add a new data field to the step sequence.\n\n :param name: string for the name\n :param value: the data\n :param item_shape: shape to store the data in\n :param with_after_last: `True` if there is one more element than the length (e.g. last observation)\n \"\"\"\n if name in self._data_names:\n raise pyrado.KeyErr(msg=f\"Trying to add a duplicate data field for {name}!\")\n\n if value is None:\n # Compute desired step length\n ro_length = self.length\n if with_after_last:\n ro_length += 1\n\n # Create zero-filled\n if self._data_format == \"torch\":\n value = to.zeros(to.Size([ro_length]) + to.Size(item_shape))\n else:\n value = np.array((ro_length,) + item_shape)\n\n else:\n # Check the data\n self._validate_data_size(name, value)\n\n if not isinstance(value, (np.ndarray, to.Tensor)):\n # Stack into one array/tensor\n value = stack_to_format(value, self._data_format)\n else:\n # Ensure right array format\n value = to_format(value, self._data_format)\n\n # Store in dict\n self._data_names.append(name)\n self.__dict__[name] = value\n\n def get_data_values(self, name: str, truncate_last: Optional[bool] = False):\n \"\"\"\n Return the data tensor stored under the given name.\n\n :param name: data name\n :param truncate_last: True to truncate the length+1 entry if present\n \"\"\"\n assert name in self._data_names\n entry = self.__dict__[name]\n\n # Truncate if needed\n if truncate_last:\n # Check length\n entry = self._truncate_after_last(entry)\n return entry\n\n def numpy(self, data_type=None):\n \"\"\"\n Convert data to numpy ndarrays.\n\n :param data_type: type to return data in. When None is passed, the data type is left unchanged.\n \"\"\"\n self.convert(\"numpy\", data_type)\n\n def torch(self, data_type=None):\n \"\"\"\n Convert data to PyTorch Tensors.\n\n :param data_type: type to return data in. When None is passed, the data type is left unchanged.\n \"\"\"\n self.convert(\"torch\", data_type)\n\n def convert(self, data_format: str, data_type=None):\n \"\"\"\n Convert data to specified format.\n\n :param data_format: torch to use Tensors, numpy to use ndarrays\n :param data_type: optional torch/numpy dtype for data. When `None` is passed, the data type is left unchanged.\n \"\"\"\n if data_format not in {\"torch\", \"numpy\"}:\n raise pyrado.ValueErr(given=data_format, eq_constraint=\"'torch' or 'numpy'\")\n\n if self._data_format == data_format:\n return\n self._data_format = data_format\n for dn in self._data_names:\n self.__dict__[dn] = self.__map_tensors(lambda t: to_format(t, data_format, data_type), self.__dict__[dn])\n\n def get_rollout(self, index):\n \"\"\"\n Get an indexed sub-rollout.\n\n :param index: generic index of sub-rollout, negative values, slices and iterables are allowed\n :return: selected subset.\n \"\"\"\n if not self.continuous:\n raise pyrado.ValueErr(msg=\"Sub-rollouts are only supported on continuous data.\")\n if isinstance(index, slice):\n # Analyze slice\n start, end, step = index.indices(self.rollout_count)\n if step == 1:\n # A simple, continuous slice\n bounds = self._rollout_bounds\n start_step = bounds[start]\n end_step = bounds[end]\n return self[start_step:end_step]\n\n # Convert nonstandard slice to range\n index = range(start, end, step)\n if isinstance(index, Iterable):\n # Nontrivial non-continuous slice, need to slice each element and concat them.\n return StepSequence.concat([self.get_rollout(i) for i in index], self.data_format)\n\n # Decode index\n index = _index_to_int(index, self.rollout_count)\n bounds = self._rollout_bounds\n start_step = bounds[index]\n end_step = bounds[index + 1]\n return self[start_step:end_step]\n\n def iterate_rollouts(self):\n \"\"\" Iterate over all sub-rollouts of a concatenated rollout. \"\"\"\n if not self.continuous:\n raise pyrado.ValueErr(msg=\"Sub-rollouts are only supported on continuous data.\")\n bounds = self._rollout_bounds\n count = len(bounds) - 1\n if count == 1:\n # Optimize for single rollout\n yield self\n else:\n for i in range(count):\n start_step = bounds[i]\n end_step = bounds[i + 1]\n yield self[start_step:end_step]\n\n def sample_w_next(self, batch_size: int) -> tuple:\n \"\"\"\n Sample a random batch of steps from a together with the associated next steps.\n Similar to `split_shuffled_batches` with `complete_rollouts=False`\n\n :param batch_size: number of steps to sample\n :return: randomly sampled batch of steps\n \"\"\"\n if not self.length >= 2:\n raise pyrado.ValueErr(given=self.length, ge_constraint=\"2\")\n\n shuffled_idcs = random.sample(range(self.length - 2), batch_size) # - 2 to always have a next step\n shuffled_next_idcs = [i + 1 for i in shuffled_idcs]\n steps = deepcopy(self[shuffled_idcs])\n next_steps = deepcopy(self[shuffled_next_idcs])\n\n return steps, next_steps\n\n def split_ordered_batches(self, batch_size: int = None, num_batches: int = None):\n \"\"\"\n Batch generation. Split the step collection into ordered mini-batches of size batch_size.\n\n :param batch_size: number of steps per batch, i.e. variable number of batches\n :param num_batches: number of batches to split the rollout in, i.e. variable batch size\n\n .. note::\n Left out the option to return complete rollouts like for `split_shuffled_batches`.\n \"\"\"\n if batch_size is None and num_batches is None or batch_size is not None and num_batches is not None:\n raise pyrado.ValueErr(msg=\"Either batch_size or num_batches must not be None, but not both or none!\")\n elif batch_size is not None and batch_size < 1:\n raise pyrado.ValueErr(given=batch_size, ge_constraint=\"1 (int)\")\n elif num_batches is not None and num_batches < 1:\n raise pyrado.ValueErr(given=num_batches, ge_constraint=\"1 (int)\")\n\n # Switch the splitting mode\n if num_batches is not None:\n batch_size = ceil(self.length / num_batches)\n\n if batch_size >= self.length:\n # Yield all at once if there are less steps than the batch size\n yield self\n\n else:\n # Split by steps\n for b in gen_ordered_batch_idcs(batch_size, self.length, sorted=True):\n yield self[b]\n\n def split_shuffled_batches(self, batch_size: int, complete_rollouts: Optional[bool] = False):\n \"\"\"\n Batch generation. Split the step collection into random mini-batches of size batch_size.\n\n :param batch_size: number of steps per batch\n :param complete_rollouts: if `complete_rollouts = True`, the batches will not contain partial rollouts.\n However, the size of the returned batches cannot be strictly maintained in this case.\n\n .. note::\n This method is also supposed to be called for recurrent networks, which have a different `evaluate()`\n method that recognized where the rollouts end within a batch.\n \"\"\"\n if batch_size >= self.length:\n # Yield all at once if there are less steps than the batch size\n yield self\n\n elif complete_rollouts and self.continuous:\n # Our goal here is to randomly shuffle the rollouts, while returning batches of batch_size steps.\n # The solution here is to take rollouts in a random order and yield a batch each time it exceeds batch_size.\n\n rollout_lengths = self.rollout_lengths\n shuffled_idcs = random.sample(range(len(rollout_lengths)), len(rollout_lengths))\n # Now, walk through the rollouts in a random order and split once batch size is full.\n batch = []\n cur_batch_size = 0\n for idx in shuffled_idcs:\n batch.append(idx)\n cur_batch_size += rollout_lengths[idx]\n if cur_batch_size >= batch_size:\n # Got a full batch\n yield self.get_rollout(batch)\n batch.clear()\n cur_batch_size = 0\n # Yield eventual final one\n if batch:\n yield self.get_rollout(batch)\n\n else:\n # Split by steps\n for b in gen_shuffled_batch_idcs(batch_size, self.length):\n yield self[b]\n\n def undiscounted_return(self) -> float:\n \"\"\"\n Compute the undiscounted return.\n\n :return: sum of rewards\n \"\"\"\n if not len(self._rollout_bounds) == 2:\n raise pyrado.ShapeErr(msg=\"The StepSequence must be a single continuous rollout.\")\n\n return self.rewards.sum()\n\n def discounted_return(self, gamma: float) -> (to.Tensor, np.ndarray):\n \"\"\"\n Compute the discounted return.\n\n :param gamma: temporal discount factor\n :return: exponentially weighted sum of rewards\n \"\"\"\n if not len(self._rollout_bounds) == 2:\n raise pyrado.ShapeErr(msg=\"The StepSequence must be a single continuous rollout.\")\n if not 0 <= gamma <= 1:\n raise pyrado.ValueErr(given=gamma, ge_constraint=\"0\", le_constraint=\"1\")\n\n if self.data_format == \"torch\":\n return to.dot(self.rewards, (gamma ** to.arange(self.length)))\n else:\n return np.dot(self.rewards, (gamma ** np.arange(self.length)))\n\n @classmethod\n def concat(\n cls, parts: Sequence[\"StepSequence\"], data_format: Optional[str] = None, truncate_last: Optional[bool] = True\n ):\n \"\"\"\n Concatenate multiple step sequences into one, truncating the last observation.\n\n :param parts: batch of sequences to concatenate\n :param data_format: torch to use Tensors, numpy to use ndarrays, `None` to choose automatically\n :param truncate_last: remove the last step from each part, highly recommended to be `True`\n :return: concatenated sequence of `Steps`\n \"\"\"\n # Obtain data attribute names\n data_names = parts[0].data_names\n\n # Deduce data format if is None\n if data_format is None:\n data_format = parts[0].data_format\n\n # Concat data fields\n data = {\n name: cat_to_format([ro.get_data_values(name, truncate_last) for ro in parts], data_format)\n for name in data_names\n }\n\n # Treat done separately since it should stay a ndarray\n done = np.concatenate([ro.done for ro in parts])\n\n # Check if parts are continuous\n continuous = all(ro.continuous for ro in parts)\n rollout_bounds = None\n if continuous:\n # Concatenate rollout separator indices for continuous rollouts\n rollout_bounds = [0]\n acc_len = 0\n for ro in parts:\n rollout_bounds.extend(ro.rollout_bounds[1:] + acc_len)\n acc_len += ro.rollout_bounds[-1]\n\n return StepSequence(\n data_format=data_format, done=done, continuous=continuous, rollout_bounds=rollout_bounds, **data\n )\n\n @classmethod\n def process_data(\n cls,\n rollout: \"StepSequence\",\n fcn: Callable,\n fcn_arg_name: str,\n fcn_arg_types: Union[type, Tuple[type]] = np.ndarray,\n include_fields: Sequence[str] = None,\n exclude_fields: Sequence[str] = None,\n **process_fcn_kwargs,\n ):\n \"\"\"\n Process all data fields of a rollouts using an arbitrary function. Optionally, some fields can be excluded.\n\n :param rollout: `StepSequence` holding the data\n :param fcn: function (of one remaining input) to used manipulate the data fields, e.g. `scipy.filtfilt()`\n :param fcn_arg_name: sting of the remaining input of `process_fcn()`, e.g. `x` for `scipy.filtfilt()`\n :param fcn_arg_types: type or tuple thereof which are expected as input to `fcn()`\n :param include_fields: list of field names to include for processing, pass `None` to not include everything.\n If specified, only fields from this selection will be considered\n :param exclude_fields: list of field names to exclude from processing, pass `None` to not exclude anything\n :param process_fcn_kwargs: keyword arguments forwarded to `process_fcn()`\n :return: new `StepSequence` instance with processed data\n \"\"\"\n\n @functools.wraps(fcn)\n def recursive_wrapper(inp, **kwargs):\n \"\"\" Wrap the processing function to call it recursivelyy for nested data structures. \"\"\"\n # Add to actual data input to the keyword arguments to make calling the function easier\n kwargs.update({fcn_arg_name: inp})\n\n if isinstance(inp, fcn_arg_types):\n # Process the data\n inp = fcn(**kwargs)\n\n elif isinstance(inp, dict):\n # Recursive call\n for key, value in inp.items():\n if isinstance(value, fcn_arg_types):\n inp[key] = recursive_wrapper(value, **kwargs)\n else:\n inp[key] = value\n\n elif isinstance(inp, list):\n # Recursive call\n for idx, item in enumerate(inp):\n if isinstance(item, fcn_arg_types):\n inp[idx] = recursive_wrapper(item, **kwargs)\n else:\n inp[idx] = item\n\n return inp\n\n # Go through all desired data fields and apply the processing function\n data_dict = dict()\n include_fields = include_fields or rollout.data_names\n exclude_fields = exclude_fields or []\n for name in rollout.data_names:\n # Extract data field\n data = rollout.get_data_values(name)\n\n # Process current data field if included and not explicitly excluded\n if name in include_fields and name not in exclude_fields:\n data = recursive_wrapper(data, **process_fcn_kwargs)\n\n # Collect the new/old data\n data_dict[name] = data\n\n # Create new object\n return StepSequence(**data_dict, rollout_info=rollout.rollout_info, continuous=rollout.continuous)\n\n\ndef discounted_reverse_cumsum(data, gamma: float):\n \"\"\"\n Use a linear filter to compute the reverse discounted cumulative sum.\n\n .. note::\n `scipy.signal.lfilter` assumes an initialization with 0 by default.\n\n :param data: input data with samples along the 0 axis (e.g. time series)\n :param gamma: discount factor\n :return: cumulative sums for every step\n \"\"\"\n return signal.lfilter([1], [1, -gamma], data[::-1], axis=0)[::-1]\n\n\ndef discounted_value(rollout: StepSequence, gamma: float):\n \"\"\"\n Compute the discounted state values for one rollout.\n\n :param rollout: input data\n :param gamma: temporal discount factor\n :return: state values for every time step in the rollout\n \"\"\"\n rewards = [step.reward for step in rollout]\n return discounted_reverse_cumsum(rewards, gamma)\n\n\ndef discounted_values(rollouts: Sequence[StepSequence], gamma: float, data_format: Optional[str] = \"torch\"):\n \"\"\"\n Compute the discounted state values for multiple rollouts.\n\n :param rollouts: input data\n :param gamma: temporal discount factor\n :param data_format: data format of the given\n :return: state values for every time step in the rollouts (concatenated sequence across rollouts)\n \"\"\"\n if data_format == \"torch\":\n # The ndarray.copy() is necessary due to (currently) unsupported negative strides\n return to.cat([to.from_numpy(discounted_value(ro, gamma).copy()).to(to.get_default_dtype()) for ro in rollouts])\n elif data_format == \"numpy\":\n raise np.array([discounted_value(ro, gamma) for ro in rollouts])\n else:\n raise pyrado.ValueErr(given=data_format, eq_constraint=\"'torch' or 'numpy'\")\n\n\ndef gae_returns(rollout: StepSequence, gamma: float = 0.99, lamb: float = 0.95):\n \"\"\"\n Compute returns using generalized advantage estimation.\n\n .. seealso::\n [1] J. Schulmann, P. Moritz, S. Levine, M. Jordan, P. Abbeel, 'High-Dimensional Continuous Control Using\n Generalized Advantage Estimation', ICLR 2016\n\n :param rollout: sequence of steps\n :param gamma: temporal discount factor\n :param lamb: discount factor\n :return: estimated advantage\n \"\"\"\n\n def _next_value(step: Step) -> float:\n \"\"\" Helper to return `next_value = 0` for last step \"\"\"\n if step.done:\n return 0.0\n return step.next_value\n\n deltas = [step.reward + gamma * _next_value(step) - step.value for step in rollout]\n cumsum = discounted_reverse_cumsum(deltas, gamma * lamb)\n return cumsum\n",
"import numpy as np\n\nfrom mushroom_rl.algorithms.value.batch_td import BatchTD\nfrom mushroom_rl.approximators.parametric import LinearApproximator\nfrom mushroom_rl.features import get_action_features\nfrom mushroom_rl.utils.dataset import parse_dataset\nfrom mushroom_rl.utils.parameters import to_parameter\n\n\nclass LSPI(BatchTD):\n \"\"\"\n Least-Squares Policy Iteration algorithm.\n \"Least-Squares Policy Iteration\". Lagoudakis M. G. and Parr R.. 2003.\n\n \"\"\"\n def __init__(self, mdp_info, policy, approximator_params=None,\n epsilon=1e-2, fit_params=None, features=None):\n \"\"\"\n Constructor.\n\n Args:\n epsilon ((float, Parameter), 1e-2): termination coefficient.\n\n \"\"\"\n self._epsilon = to_parameter(epsilon)\n\n k = features.size * mdp_info.action_space.n\n self._A = np.zeros((k, k))\n self._b = np.zeros((k, 1))\n\n self._add_save_attr(_epsilon='mushroom', _A='primitive', _b='primitive')\n\n super().__init__(mdp_info, policy, LinearApproximator,\n approximator_params, fit_params, features)\n\n def fit(self, dataset):\n phi_state, action, reward, phi_next_state, absorbing, _ = parse_dataset(\n dataset, self.phi)\n phi_state_action = get_action_features(phi_state, action,\n self.mdp_info.action_space.n)\n\n norm = np.inf\n while norm > self._epsilon():\n q = self.approximator.predict(phi_next_state)\n if np.any(absorbing):\n q *= 1 - absorbing.reshape(-1, 1)\n\n next_action = np.argmax(q, axis=1).reshape(-1, 1)\n phi_next_state_next_action = get_action_features(\n phi_next_state,\n next_action,\n self.mdp_info.action_space.n\n )\n\n tmp = phi_state_action - self.mdp_info.gamma *\\\n phi_next_state_next_action\n self._A += phi_state_action.T.dot(tmp)\n self._b += (phi_state_action.T.dot(reward)).reshape(-1, 1)\n\n old_w = self.approximator.get_weights()\n if np.linalg.matrix_rank(self._A) == self._A.shape[1]:\n w = np.linalg.solve(self._A, self._b).ravel()\n else:\n w = np.linalg.pinv(self._A).dot(self._b).ravel()\n self.approximator.set_weights(w)\n\n norm = np.linalg.norm(w - old_w)\n"
] |
[
[
"torch.Size",
"numpy.asarray",
"numpy.arange",
"numpy.flatnonzero",
"numpy.concatenate",
"torch.arange",
"scipy.signal.lfilter",
"torch.get_default_dtype",
"numpy.array",
"numpy.zeros"
],
[
"numpy.linalg.solve",
"numpy.linalg.matrix_rank",
"numpy.linalg.norm",
"numpy.linalg.pinv",
"numpy.argmax",
"numpy.any",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
nickjmiller/MLBenchmark
|
[
"f6c3865c2dd5b71a471789041f3d800705371531"
] |
[
"benchmark.py"
] |
[
"import csv\nfrom default_clf import DefaultNSL\nfrom itertools import chain\nfrom time import process_time\n\nimport numpy as np\nimport pandas as pd\n\nNUM_PASSES = 100\nNUM_ACC_PASSES = 50\nTRAIN_PATH = 'data/KDDTrain+.csv'\nTEST_PATH = 'data/KDDTest+.csv'\n\nATTACKS = {\n 'normal': 'normal',\n\n 'back': 'DoS',\n 'land': 'DoS',\n 'neptune': 'DoS',\n 'pod': 'DoS',\n 'smurf': 'DoS',\n 'teardrop': 'DoS',\n 'mailbomb': 'DoS',\n 'apache2': 'DoS',\n 'processtable': 'DoS',\n 'udpstorm': 'DoS',\n\n 'ipsweep': 'Probe',\n 'nmap': 'Probe',\n 'portsweep': 'Probe',\n 'satan': 'Probe',\n 'mscan': 'Probe',\n 'saint': 'Probe',\n\n 'ftp_write': 'R2L',\n 'guess_passwd': 'R2L',\n 'imap': 'R2L',\n 'multihop': 'R2L',\n 'phf': 'R2L',\n 'spy': 'R2L',\n 'warezclient': 'R2L',\n 'warezmaster': 'R2L',\n 'sendmail': 'R2L',\n 'named': 'R2L',\n 'snmpgetattack': 'R2L',\n 'snmpguess': 'R2L',\n 'xlock': 'R2L',\n 'xsnoop': 'R2L',\n 'worm': 'R2L',\n\n 'buffer_overflow': 'U2R',\n 'loadmodule': 'U2R',\n 'perl': 'U2R',\n 'rootkit': 'U2R',\n 'httptunnel': 'U2R',\n 'ps': 'U2R',\n 'sqlattack': 'U2R',\n 'xterm': 'U2R'\n}\n\n\ndef get_current_charge():\n try:\n with open('/sys/class/power_supply/BAT0/charge_now') as f:\n return int(f.readline())\n except IOError:\n print(\"Cannot find current battery charge.\")\n return 0\n\n\ndef check_load_training(clf, path):\n start = process_time()\n clf.load_training_data(path)\n end = process_time()\n return end - start\n\n\ndef check_load_testing(clf, path):\n start = process_time()\n clf.load_test_data(path)\n end = process_time()\n return end - start\n\n\ndef check_training(clf):\n start = process_time()\n clf.train_clf()\n end = process_time()\n return end - start\n\n\ndef check_testing_entire_dataset(clf, train=False):\n start = process_time()\n clf.test_clf(train)\n end = process_time()\n return end - start\n\n\ndef check_predict_row(clf, row):\n start = process_time()\n clf.predict(row)\n end = process_time()\n return end - start\n\n\ndef get_stats(arr, function, *args, **kwargs):\n charge_start = get_current_charge()\n for i in range(NUM_PASSES):\n arr[i] = function(*args, **kwargs)\n charge_end = get_current_charge()\n mean = arr.mean()\n std = arr.std()\n return [mean, std, (charge_start - charge_end)]\n\n\ndef evaluate_power(clf):\n res = np.empty(shape=(NUM_PASSES, 1))\n load_train = get_stats(res, check_load_training, clf, TRAIN_PATH)\n print('Loading Training: ', load_train)\n load_test = get_stats(res, check_load_testing, clf, TEST_PATH)\n print('Loading Testing: ', load_test)\n train = get_stats(res, check_training, clf)\n print('Training: ', train)\n test_dataset = get_stats(res, check_testing_entire_dataset, clf)\n print('Testing dataset: ', test_dataset)\n row = clf.testing[0].iloc[0].values.reshape(1, -1)\n test_row = get_stats(res, check_predict_row, clf, row)\n print('Testing one row: ', test_row)\n with open('results.csv', 'a', newline='') as csvf:\n csv_writer = csv.writer(csvf)\n csv_writer.writerow([clf.__class__.__name__, 'Number of Passes:', NUM_PASSES, 'Power'])\n csv_writer.writerow(['Function', 'Time (s) Mean', 'Time Std',\n 'Total Power (microwatt-hour)'])\n csv_writer.writerow(['Loading Training Data'] + load_train)\n csv_writer.writerow(['Loading Testing Data'] + load_test)\n csv_writer.writerow(['Training Classifier'] + train)\n csv_writer.writerow(['Testing Dataset'] + test_dataset)\n csv_writer.writerow(['Testing One Row'] + test_row)\n\n\ndef evaluate_accuracy(clf):\n acc = np.empty(shape=(NUM_ACC_PASSES, 1))\n clf.load_training_data(TRAIN_PATH)\n clf.load_test_data(TEST_PATH)\n cat_labels = clf.testing[1].apply(lambda x: ATTACKS[x])\n cats = {'U2R':[np.zeros(shape=(NUM_ACC_PASSES, 1)), np.zeros(shape=(NUM_ACC_PASSES, 1))],\n 'DoS':[np.zeros(shape=(NUM_ACC_PASSES, 1)), np.zeros(shape=(NUM_ACC_PASSES, 1))],\n 'R2L':[np.zeros(shape=(NUM_ACC_PASSES, 1)), np.zeros(shape=(NUM_ACC_PASSES, 1))],\n 'Probe':[np.zeros(shape=(NUM_ACC_PASSES, 1)), np.zeros(shape=(NUM_ACC_PASSES, 1))],\n 'normal':[np.zeros(shape=(NUM_ACC_PASSES, 1)), np.zeros(shape=(NUM_ACC_PASSES, 1))]}\n for i in range(0, NUM_ACC_PASSES):\n clf.train_clf()\n preds, acc[i] = clf.test_clf()\n for cat, pred in zip(cat_labels, preds):\n cats[cat][pred == 'normal'][i] += 1\n clf.shuffle_training_data()\n conf = calculate_category_accuracy(cats)\n mean = acc.mean()\n std = acc.std()\n write_acc_to_csv([mean, std], cats, conf, clf.__class__.__name__)\n return [mean, std]\n\n\ndef calculate_category_accuracy(cats):\n conf = {'TN':np.zeros(shape=(NUM_ACC_PASSES, 1)), 'TP':np.zeros(shape=(NUM_ACC_PASSES, 1)),\n 'FN':np.zeros(shape=(NUM_ACC_PASSES, 1)), 'FP':np.zeros(shape=(NUM_ACC_PASSES, 1))}\n for key, values in cats.items():\n correct = values[0]\n wrong = values[1]\n if key == 'normal':\n correct, wrong = wrong, correct\n conf['TN'] += correct\n conf['FP'] += wrong\n else:\n conf['TP'] += correct\n conf['FN'] += wrong\n avg = correct/(correct+wrong)\n cats[key] = [avg.mean(), avg.std()]\n return conf\n\n\ndef write_acc_to_csv(acc, cats, conf, name):\n with open('results.csv', 'a', newline='') as csvf:\n csv_writer = csv.writer(csvf)\n csv_writer.writerow([name, 'Number of Passes:', NUM_ACC_PASSES, 'Accuracy'])\n csv_writer.writerow(['Statistic', 'Mean', 'STD'])\n csv_writer.writerow(['Accuracy'] + acc)\n for key, values in cats.items():\n csv_writer.writerow([key] + values)\n for key, values in conf.items():\n csv_writer.writerow([key, values.mean(), values.std()])\n"
] |
[
[
"numpy.zeros",
"numpy.empty"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
nfkjsfoeif/AutoGCN
|
[
"4496bc066936d93b2e852c8010d95fb372910a80"
] |
[
"train/train_superpixels_graph_classification.py"
] |
[
"\"\"\"\n Utility functions for training one epoch \n and evaluating one epoch\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport math\n\nfrom train.metrics import accuracy_MNIST_CIFAR as accuracy\n\ndef train_epoch(model, optimizer, device, data_loader, epoch=0):\n model.train()\n epoch_loss = 0\n epoch_train_acc = 0\n nb_data = 0\n gpu_mem = 0\n for iter, (batch_graphs, batch_labels, batch_snorm_n, batch_snorm_e) in enumerate(data_loader):\n batch_x = batch_graphs.ndata['feat'].to(device) # num x feat\n batch_e = batch_graphs.edata['feat'].to(device)\n batch_snorm_e = batch_snorm_e.to(device)\n batch_labels = batch_labels.to(device)\n batch_snorm_n = batch_snorm_n.to(device) # num x 1\n optimizer.zero_grad()\n \n batch_scores = model.forward(batch_graphs, batch_x, batch_e, batch_snorm_n, batch_snorm_e)\n loss = model.loss(batch_scores, batch_labels)\n loss.backward()\n optimizer.step()\n epoch_loss += loss.detach().item()\n epoch_train_acc += accuracy(batch_scores, batch_labels)\n nb_data += batch_labels.size(0)\n epoch_loss /= (iter + 1)\n epoch_train_acc /= nb_data\n \n return epoch_loss, epoch_train_acc, optimizer\n\ndef evaluate_network(model, device, data_loader, epoch=0):\n model.eval()\n epoch_test_loss = 0\n epoch_test_acc = 0\n nb_data = 0\n with torch.no_grad():\n for iter, (batch_graphs, batch_labels, batch_snorm_n, batch_snorm_e) in enumerate(data_loader):\n batch_x = batch_graphs.ndata['feat'].to(device)\n batch_e = batch_graphs.edata['feat'].to(device)\n batch_snorm_e = batch_snorm_e.to(device)\n batch_labels = batch_labels.to(device)\n batch_snorm_n = batch_snorm_n.to(device)\n \n batch_scores = model.forward(batch_graphs, batch_x, batch_e, batch_snorm_n, batch_snorm_e)\n loss = model.loss(batch_scores, batch_labels) \n epoch_test_loss += loss.detach().item()\n epoch_test_acc += accuracy(batch_scores, batch_labels)\n nb_data += batch_labels.size(0)\n epoch_test_loss /= (iter + 1)\n epoch_test_acc /= nb_data\n \n return epoch_test_loss, epoch_test_acc"
] |
[
[
"torch.no_grad"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jlakkis/sciPENN
|
[
"34afb2008a076e13c40965a76d3dd31d0c331652"
] |
[
"src/sciPENN/Network/Model.py"
] |
[
"from math import log, exp\nfrom numpy import inf, zeros, zeros_like as np_zeros_like, arange, asarray, empty\nfrom pandas import concat\nfrom anndata import AnnData\n\nfrom torch import cat, no_grad, randn, zeros_like, zeros as torch_zeros, ones, argmax\nfrom torch.nn import Module, Linear, Sequential, RNNCell, Softplus, Parameter, Softmax\nfrom torch.optim import Adam\nfrom torch.optim.lr_scheduler import StepLR\n\nfrom .Layers import Input_Block, FF_Block, LambdaLayer, Dual_Forward\n\nclass sciPENN_Model(Module):\n def __init__(self, p_mod1, p_mod2, loss1, loss2, quantiles, categories):\n super(sciPENN_Model, self).__init__()\n \n h_size, drop_rate = 512, 0.25\n \n self.RNNCell = RNNCell(h_size, h_size)\n \n self.input_block = Input_Block(p_mod1, h_size, drop_rate, drop_rate)\n \n self.skip_1 = FF_Block(h_size, drop_rate)\n self.skip_2 = FF_Block(h_size, drop_rate)\n self.skip_3 = FF_Block(h_size, drop_rate)\n \n MSE_output = Linear(h_size, p_mod2)\n \n if len(quantiles) > 0:\n quantile_layer = []\n quantile_layer.append(Linear(h_size, p_mod2 * len(quantiles)))\n quantile_layer.append(LambdaLayer(lambda x: x.view(-1, p_mod2, len(quantiles))))\n quantile_layer = Sequential(*quantile_layer)\n\n self.mod2_out = Dual_Forward(MSE_output, quantile_layer)\n \n else:\n self.mod2_out = MSE_output\n \n if categories is not None:\n self.celltype_out = Sequential(Linear(h_size, len(categories)), Softmax(1))\n self.forward = self.forward_transfer\n \n self.categories_arr = empty((len(categories), ), dtype = 'object')\n for cat in categories:\n self.categories_arr[categories[cat]] = cat\n \n else:\n self.forward = self.forward_simple\n self.categories_arr = None\n \n self.quantiles = quantiles\n self.loss1, self.loss2 = loss1, loss2\n \n def forward_transfer(self, x):\n x = self.input_block(x)\n h = self.RNNCell(x, zeros_like(x))\n \n x = self.skip_1(x)\n h = self.RNNCell(x, h)\n \n x = self.skip_2(x)\n h = self.RNNCell(x, h)\n \n x = self.skip_3(x)\n h = self.RNNCell(x, h)\n \n return {'celltypes': self.celltype_out(h.detach()), 'modality 2': self.mod2_out(h), 'embedding': h}\n \n def forward_simple(self, x):\n x = self.input_block(x)\n h = self.RNNCell(x, zeros_like(x))\n \n x = self.skip_1(x)\n h = self.RNNCell(x, h)\n \n x = self.skip_2(x)\n h = self.RNNCell(x, h)\n \n x = self.skip_3(x)\n h = self.RNNCell(x, h)\n \n return {'celltypes': None, 'modality 2': self.mod2_out(h), 'embedding': h}\n \n def train_backprop(self, train_loader, val_loader, \n n_epoch = 10000, ES_max = 30, decay_max = 10, decay_step = 0.1, lr = 10**(-3)):\n optimizer = Adam(self.parameters(), lr = lr)\n scheduler = StepLR(optimizer, step_size = 1, gamma = decay_step)\n \n patience = 0\n bestloss = inf\n \n if self.categories_arr is None:\n get_correct = lambda x: 0\n else:\n get_correct = lambda outputs: (argmax(outputs['celltypes'], axis = 1) == celltypes).sum()\n \n for epoch in range(n_epoch):\n with no_grad():\n running_loss, rtype_acc = 0., 0.\n self.eval()\n \n for batch, inputs in enumerate(val_loader):\n mod1, mod2, protein_bools, celltypes = inputs\n outputs = self(mod1)\n \n n_correct = get_correct(outputs)\n mod2_loss = self.loss2(outputs['modality 2'], mod2, protein_bools)\n\n rtype_acc += n_correct\n running_loss += mod2_loss.item() * len(mod2)\n \n if self.categories_arr is None:\n print(f\"Epoch {epoch} prediction loss = {running_loss/len(val_loader):.3f}\")\n else:\n print(f\"Epoch {epoch} prediction loss = {running_loss/len(val_loader):.3f}, validation accuracy = {rtype_acc/len(val_loader):.3f}\")\n\n patience += 1\n \n if bestloss/1.005 > running_loss:\n bestloss, patience = running_loss, 0\n\n if (patience + 1) % decay_max == 0:\n scheduler.step()\n print(f\"Decaying loss to {optimizer.param_groups[0]['lr']}\")\n\n if (patience + 1) > ES_max:\n break\n\n self.train()\n for batch, inputs in enumerate(train_loader):\n optimizer.zero_grad()\n \n mod1, mod2, protein_bools, celltypes = inputs \n outputs = self(mod1)\n \n mod1_loss = self.loss1(outputs['celltypes'], celltypes)\n mod2_loss = self.loss2(outputs['modality 2'], mod2, protein_bools)\n \n loss = mod1_loss + mod2_loss\n loss.backward()\n \n optimizer.step()\n \n def impute(self, impute_loader, requested_quantiles, denoise_genes, proteins):\n imputed_test = proteins.copy()\n\n for quantile in requested_quantiles:\n imputed_test.layers['q' + str(round(100 * quantile))] = np_zeros_like(imputed_test.X)\n \n self.eval()\n start = 0\n \n for mod1, bools, celltypes in impute_loader:\n end = start + mod1.shape[0]\n \n with no_grad():\n outputs = self(mod1)\n\n if len(self.quantiles) > 0:\n mod2_impute, mod2_quantile = outputs['modality 2']\n else:\n mod2_impute = outputs['modality 2']\n\n imputed_test.X[start:end] = self.fill_predicted(imputed_test.X[start:end], mod2_impute, bools)\n\n for quantile in requested_quantiles:\n index = [i for i, q in enumerate(self.quantiles) if quantile == q][0]\n q_name = 'q' + str(round(100 * quantile))\n imputed_test.layers[q_name][start:end] = mod2_quantile[:, : , index].cpu().numpy()\n\n start = end\n \n return imputed_test\n \n def embed(self, impute_loader, test_loader, cells_train, cells_test):\n if cells_test is not None:\n embedding = AnnData(zeros(shape = (len(cells_train) + len(cells_test), 512)))\n embedding.obs = concat((cells_train, cells_test), join = 'inner')\n else:\n embedding = AnnData(zeros(shape = (len(cells_train), 512)))\n embedding.obs = cells_train\n \n self.eval()\n start = 0\n \n for mod1, bools, celltypes in impute_loader:\n end = start + mod1.shape[0]\n outputs = self(mod1)\n \n embedding[start:end] = outputs['embedding'].detach().cpu().numpy()\n \n start = end\n \n if cells_test is not None:\n for mod1 in test_loader:\n end = start + mod1.shape[0]\n outputs = self(mod1)\n\n embedding[start:end] = outputs['embedding'].detach().cpu().numpy()\n\n start = end\n \n return embedding\n \n def fill_predicted(self, array, predicted, bools):\n bools = bools.cpu().numpy()\n return (1. - bools) * predicted.cpu().numpy() + array\n \n def predict(self, test_loader, requested_quantiles, denoise_genes, proteins, cells):\n imputed_test = AnnData(zeros(shape = (len(cells), len(proteins.var))))\n imputed_test.obs = cells\n imputed_test.var.index = proteins.var.index\n \n if self.categories_arr is not None:\n celltypes = ['None'] * len(cells)\n \n for quantile in requested_quantiles:\n imputed_test.layers['q' + str(round(100 * quantile))] = np_zeros_like(imputed_test.X)\n \n self.eval()\n start = 0\n \n for mod1 in test_loader:\n end = start + mod1.shape[0]\n \n with no_grad():\n outputs = self(mod1)\n \n if self.categories_arr is not None:\n predicted_types = argmax(outputs['celltypes'], axis = 1).cpu().numpy()\n celltypes[start:end] = self.categories_arr[predicted_types].tolist()\n \n if len(self.quantiles) > 0:\n mod2_impute, mod2_quantile = outputs['modality 2']\n else:\n mod2_impute = outputs['modality 2']\n\n imputed_test.X[start:end] = mod2_impute.cpu().numpy()\n\n for quantile in requested_quantiles:\n index = [i for i, q in enumerate(self.quantiles) if quantile == q][0]\n q_name = 'q' + str(round(100 * quantile))\n imputed_test.layers[q_name][start:end] = mod2_quantile[:, : , index].cpu().numpy()\n\n start = end\n \n if self.categories_arr is not None:\n imputed_test.obs['transfered cell labels'] = celltypes\n \n return imputed_test"
] |
[
[
"torch.nn.Sequential",
"pandas.concat",
"torch.nn.Softmax",
"torch.argmax",
"torch.zeros_like",
"torch.nn.Linear",
"numpy.zeros_like",
"torch.no_grad",
"torch.nn.RNNCell",
"torch.optim.lr_scheduler.StepLR"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
decibelcooper/tensorflow
|
[
"e85f387c30384664f1006b3189a30702818ff354"
] |
[
"tensorflow/python/keras/engine/training_eager_test.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\"\"\"Tests for training routines.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python import keras\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util as tf_test_util\nfrom tensorflow.python.keras import testing_utils\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.training.rmsprop import RMSPropOptimizer\n\n\nclass TrainingTest(test.TestCase):\n\n def test_fit_on_arrays(self):\n a = keras.layers.Input(shape=(3,), name='input_a')\n b = keras.layers.Input(shape=(3,), name='input_b')\n\n dense = keras.layers.Dense(4, name='dense')\n c = dense(a)\n d = dense(b)\n e = keras.layers.Dropout(0.5, name='dropout')(c)\n\n model = keras.models.Model([a, b], [d, e])\n\n optimizer = RMSPropOptimizer(learning_rate=0.001)\n loss = 'mse'\n loss_weights = [1., 0.5]\n metrics = ['mae']\n model.compile(optimizer, loss, metrics=metrics, loss_weights=loss_weights)\n\n input_a_np = np.random.random((10, 3))\n input_b_np = np.random.random((10, 3))\n\n output_d_np = np.random.random((10, 4))\n output_e_np = np.random.random((10, 4))\n\n # Test fit at different verbosity\n model.fit(\n [input_a_np, input_b_np], [output_d_np, output_e_np],\n epochs=1,\n batch_size=5,\n verbose=0)\n model.fit(\n [input_a_np, input_b_np], [output_d_np, output_e_np],\n epochs=1,\n batch_size=5,\n verbose=1)\n model.fit(\n [input_a_np, input_b_np], [output_d_np, output_e_np],\n epochs=2,\n batch_size=5,\n verbose=2)\n\n # Test with validation data\n model.fit(\n [input_a_np, input_b_np], [output_d_np, output_e_np],\n validation_data=([input_a_np, input_b_np], [output_d_np,\n output_e_np]),\n epochs=1,\n batch_size=5,\n verbose=0)\n model.fit(\n [input_a_np, input_b_np], [output_d_np, output_e_np],\n validation_data=([input_a_np, input_b_np], [output_d_np,\n output_e_np]),\n epochs=2,\n batch_size=5,\n verbose=1)\n model.fit(\n [input_a_np, input_b_np], [output_d_np, output_e_np],\n validation_data=([input_a_np, input_b_np], [output_d_np,\n output_e_np]),\n epochs=2,\n batch_size=5,\n verbose=2)\n model.train_on_batch([input_a_np, input_b_np], [output_d_np, output_e_np])\n\n # Test with validation split\n model.fit(\n [input_a_np, input_b_np], [output_d_np, output_e_np],\n epochs=2,\n batch_size=5,\n verbose=0,\n validation_split=0.2)\n\n # Test with dictionary inputs\n model.fit(\n {\n 'input_a': input_a_np,\n 'input_b': input_b_np\n }, {'dense': output_d_np,\n 'dropout': output_e_np},\n epochs=1,\n batch_size=5,\n verbose=0)\n model.fit(\n {\n 'input_a': input_a_np,\n 'input_b': input_b_np\n }, {'dense': output_d_np,\n 'dropout': output_e_np},\n epochs=1,\n batch_size=5,\n verbose=1)\n model.fit(\n {\n 'input_a': input_a_np,\n 'input_b': input_b_np\n }, {'dense': output_d_np,\n 'dropout': output_e_np},\n validation_data=({'input_a': input_a_np,\n 'input_b': input_b_np\n },\n {\n 'dense': output_d_np,\n 'dropout': output_e_np\n }),\n epochs=1,\n batch_size=5,\n verbose=0)\n model.train_on_batch({\n 'input_a': input_a_np,\n 'input_b': input_b_np\n }, {'dense': output_d_np,\n 'dropout': output_e_np})\n # Test with lists for loss, metrics\n loss = ['mae', 'mse']\n metrics = ['acc', 'mae']\n model.compile(optimizer, loss, metrics=metrics)\n model.fit(\n [input_a_np, input_b_np], [output_d_np, output_e_np],\n epochs=1,\n batch_size=5,\n verbose=0)\n\n # Test with dictionaries for loss, metrics, loss weights\n loss = {'dense': 'mse', 'dropout': 'mae'}\n loss_weights = {'dense': 1., 'dropout': 0.5}\n metrics = {'dense': 'mse', 'dropout': 'mae'}\n model.compile(optimizer, loss, metrics=metrics, loss_weights=loss_weights)\n model.fit(\n [input_a_np, input_b_np], [output_d_np, output_e_np],\n epochs=1,\n batch_size=5,\n verbose=0)\n\n # Invalid use cases\n with self.assertRaises(AttributeError):\n model.fit(\n [input_a_np, input_b_np], [output_d_np, output_e_np],\n epochs=1,\n validation_data=([input_a_np, input_b_np], 0, 0),\n verbose=0)\n with self.assertRaises(ValueError):\n model.train_on_batch({'input_a': input_a_np},\n [output_d_np, output_e_np])\n with self.assertRaises(ValueError):\n model.train_on_batch([input_a_np], [output_d_np, output_e_np])\n with self.assertRaises(AttributeError):\n model.train_on_batch(1, [output_d_np, output_e_np])\n with self.assertRaises(ValueError):\n model.train_on_batch(input_a_np, [output_d_np, output_e_np])\n with self.assertRaises(ValueError):\n bad_input = np.random.random((11, 3))\n model.train_on_batch([bad_input, input_b_np],\n [output_d_np, output_e_np])\n with self.assertRaises(ValueError):\n bad_target = np.random.random((11, 4))\n model.train_on_batch([input_a_np, input_b_np],\n [bad_target, output_e_np])\n\n # Build single-input model\n x = keras.layers.Input(shape=(3,), name='input_a')\n y = keras.layers.Dense(4)(x)\n model = keras.models.Model(x, y)\n model.compile(optimizer=RMSPropOptimizer(learning_rate=0.001), loss='mse')\n # This will work\n model.fit([input_a_np], output_d_np, epochs=1)\n with self.assertRaises(ValueError):\n model.fit([input_a_np, input_a_np], output_d_np, epochs=1)\n\n def test_evaluate_predict_on_arrays(self):\n a = keras.layers.Input(shape=(3,), name='input_a')\n b = keras.layers.Input(shape=(3,), name='input_b')\n\n dense = keras.layers.Dense(4, name='dense')\n c = dense(a)\n d = dense(b)\n e = keras.layers.Dropout(0.5, name='dropout')(c)\n\n model = keras.models.Model([a, b], [d, e])\n\n optimizer = RMSPropOptimizer(learning_rate=0.001)\n loss = 'mse'\n loss_weights = [1., 0.5]\n metrics = ['acc', 'mae']\n model.compile(\n optimizer,\n loss,\n metrics=metrics,\n loss_weights=loss_weights,\n sample_weight_mode=None)\n\n input_a_np = np.random.random((10, 3))\n input_b_np = np.random.random((10, 3))\n\n output_d_np = np.random.random((10, 4))\n output_e_np = np.random.random((10, 4))\n\n # Test evaluate at different verbosity\n out = model.evaluate(\n [input_a_np, input_b_np], [output_d_np, output_e_np],\n batch_size=5,\n verbose=0)\n self.assertEqual(len(out), 7)\n out = model.evaluate(\n [input_a_np, input_b_np], [output_d_np, output_e_np],\n batch_size=5,\n verbose=1)\n self.assertEqual(len(out), 7)\n out = model.evaluate(\n [input_a_np, input_b_np], [output_d_np, output_e_np],\n batch_size=5,\n verbose=2)\n self.assertEqual(len(out), 7)\n out = model.test_on_batch([input_a_np, input_b_np],\n [output_d_np, output_e_np])\n self.assertEqual(len(out), 7)\n\n # Test evaluate with dictionary inputs\n model.evaluate(\n {\n 'input_a': input_a_np,\n 'input_b': input_b_np\n }, {'dense': output_d_np,\n 'dropout': output_e_np},\n batch_size=5,\n verbose=0)\n model.evaluate(\n {\n 'input_a': input_a_np,\n 'input_b': input_b_np\n }, {'dense': output_d_np,\n 'dropout': output_e_np},\n batch_size=5,\n verbose=1)\n\n # Test predict\n out = model.predict([input_a_np, input_b_np], batch_size=5)\n self.assertEqual(len(out), 2)\n out = model.predict({'input_a': input_a_np, 'input_b': input_b_np})\n self.assertEqual(len(out), 2)\n out = model.predict_on_batch({\n 'input_a': input_a_np,\n 'input_b': input_b_np\n })\n self.assertEqual(len(out), 2)\n\n def test_invalid_loss_or_metrics(self):\n num_classes = 5\n train_samples = 1000\n test_samples = 1000\n input_dim = 5\n\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(10, input_shape=(input_dim,)))\n model.add(keras.layers.Activation('relu'))\n model.add(keras.layers.Dense(num_classes))\n model.add(keras.layers.Activation('softmax'))\n model.compile(loss='categorical_crossentropy',\n optimizer=RMSPropOptimizer(learning_rate=0.001))\n np.random.seed(1337)\n\n (x_train, y_train), (_, _) = testing_utils.get_test_data(\n train_samples=train_samples,\n test_samples=test_samples,\n input_shape=(input_dim,),\n num_classes=num_classes)\n\n with self.assertRaises(ValueError):\n model.fit(x_train, np.concatenate([y_train, y_train], axis=-1))\n\n with self.assertRaises(TypeError):\n model.compile(loss='categorical_crossentropy',\n optimizer=RMSPropOptimizer(learning_rate=0.001),\n metrics=set(0))\n\n with self.assertRaises(ValueError):\n model.compile(loss=None,\n optimizer='rms')\n\n def test_model_methods_with_eager_tensors_multi_io(self):\n a = keras.layers.Input(shape=(3,), name='input_a')\n b = keras.layers.Input(shape=(3,), name='input_b')\n\n dense = keras.layers.Dense(4, name='dense')\n c = dense(a)\n d = dense(b)\n e = keras.layers.Dropout(0.5, name='dropout')(c)\n\n model = keras.models.Model([a, b], [d, e])\n\n optimizer = RMSPropOptimizer(learning_rate=0.001)\n loss = 'mse'\n loss_weights = [1., 0.5]\n metrics = ['mae']\n model.compile(\n optimizer,\n loss,\n metrics=metrics,\n loss_weights=loss_weights,\n sample_weight_mode=None)\n\n input_a = keras.backend.zeros(shape=(10, 3))\n input_b = keras.backend.zeros(shape=(10, 3))\n target_d = keras.backend.zeros(shape=(10, 4))\n target_e = keras.backend.zeros(shape=(10, 4))\n\n model.fit(\n [input_a, input_b], [target_d, target_e],\n epochs=1,\n batch_size=5,\n verbose=0)\n # Test: no shuffle.\n model.fit(\n [input_a, input_b], [target_d, target_e],\n epochs=1,\n batch_size=5,\n verbose=0,\n shuffle=False)\n # Test: validation data.\n model.fit([input_a, input_b], [target_d, target_e],\n epochs=1, batch_size=2, verbose=0,\n validation_data=([input_a, input_b], [target_d, target_e]))\n model.train_on_batch([input_a, input_b], [target_d, target_e])\n model.predict([input_a, input_b], batch_size=5)\n model.evaluate([input_a, input_b], [target_d, target_e],\n batch_size=2, verbose=0)\n model.test_on_batch([input_a, input_b], [target_d, target_e])\n\n # Test: mix np and tensors.\n input_b = np.zeros(shape=(10, 3)).astype('float32')\n target_e = np.zeros(shape=(10, 4)).astype('float32')\n model.fit(\n [input_a, input_b], [target_d, target_e],\n epochs=1,\n batch_size=5,\n verbose=0)\n model.fit([input_a, input_b], [target_d, target_e],\n epochs=1, batch_size=2, verbose=0,\n validation_data=([input_a, input_b], [target_d, target_e]))\n model.fit(\n [input_a, input_b], [target_d, target_e],\n epochs=1,\n batch_size=5,\n verbose=0,\n shuffle=False)\n model.train_on_batch([input_a, input_b], [target_d, target_e])\n model.predict([input_a, input_b], batch_size=5)\n model.evaluate([input_a, input_b], [target_d, target_e],\n batch_size=2, verbose=0)\n model.test_on_batch([input_a, input_b], [target_d, target_e])\n\n def test_model_methods_with_eager_tensors_single_io(self):\n x = keras.layers.Input(shape=(3,), name='input')\n y = keras.layers.Dense(4, name='dense')(x)\n model = keras.Model(x, y)\n\n optimizer = RMSPropOptimizer(learning_rate=0.001)\n loss = 'mse'\n metrics = ['mae']\n model.compile(optimizer, loss, metrics=metrics)\n\n inputs = keras.backend.zeros(shape=(10, 3))\n targets = keras.backend.zeros(shape=(10, 4))\n\n model.fit(inputs, targets, epochs=1, batch_size=2, verbose=0)\n model.fit(inputs, targets, epochs=1, batch_size=3, verbose=0, shuffle=False)\n model.fit(inputs, targets, epochs=1, batch_size=4, verbose=0,\n validation_data=(inputs, targets))\n model.evaluate(inputs, targets, batch_size=2, verbose=0)\n model.predict(inputs, batch_size=2)\n model.train_on_batch(inputs, targets)\n model.test_on_batch(inputs, targets)\n\n\nclass LossWeightingTest(test.TestCase):\n\n def test_class_weights(self):\n num_classes = 5\n batch_size = 5\n weighted_class = 3\n train_samples = 300\n test_samples = 300\n input_dim = 5\n\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(10, input_shape=(input_dim,)))\n model.add(keras.layers.Activation('relu'))\n model.add(keras.layers.Dense(num_classes))\n model.add(keras.layers.Activation('softmax'))\n model.compile(loss='categorical_crossentropy',\n optimizer=RMSPropOptimizer(learning_rate=0.001))\n\n np.random.seed(1337)\n (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data(\n train_samples=train_samples,\n test_samples=test_samples,\n input_shape=(input_dim,),\n num_classes=num_classes)\n int_y_test = y_test.copy()\n int_y_train = y_train.copy()\n # convert class vectors to binary class matrices\n y_train = keras.utils.to_categorical(y_train, num_classes)\n y_test = keras.utils.to_categorical(y_test, num_classes)\n test_ids = np.where(int_y_test == np.array(weighted_class))[0]\n\n class_weight = dict([(i, 1.) for i in range(num_classes)])\n class_weight[weighted_class] = 4.\n\n sample_weight = np.ones((y_train.shape[0]))\n sample_weight[int_y_train == weighted_class] = 4.\n\n model.fit(\n x_train,\n y_train,\n batch_size=batch_size,\n epochs=2,\n verbose=0,\n class_weight=class_weight,\n validation_data=(x_train, y_train, sample_weight))\n model.fit(\n x_train,\n y_train,\n batch_size=batch_size,\n epochs=2,\n verbose=0,\n class_weight=class_weight)\n model.fit(\n x_train,\n y_train,\n batch_size=batch_size,\n epochs=2,\n verbose=0,\n class_weight=class_weight,\n validation_split=0.1)\n\n model.train_on_batch(\n x_train[:batch_size], y_train[:batch_size], class_weight=class_weight)\n ref_score = model.evaluate(x_test, y_test, verbose=0)\n score = model.evaluate(\n x_test[test_ids, :], y_test[test_ids, :], verbose=0)\n self.assertLess(score, ref_score)\n\n def test_sample_weights(self):\n num_classes = 5\n batch_size = 5\n weighted_class = 3\n train_samples = 300\n test_samples = 300\n input_dim = 5\n\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(10, input_shape=(input_dim,)))\n model.add(keras.layers.Activation('relu'))\n model.add(keras.layers.Dense(num_classes))\n model.add(keras.layers.Activation('softmax'))\n model.compile(loss='categorical_crossentropy',\n optimizer=RMSPropOptimizer(learning_rate=0.001))\n\n np.random.seed(43)\n (x_train, y_train), _ = testing_utils.get_test_data(\n train_samples=train_samples,\n test_samples=test_samples,\n input_shape=(input_dim,),\n num_classes=num_classes)\n int_y_train = y_train.copy()\n y_train = keras.utils.to_categorical(y_train, num_classes)\n\n class_weight = dict([(i, 1.) for i in range(num_classes)])\n class_weight[weighted_class] = 4.\n\n sample_weight = np.ones((y_train.shape[0]))\n sample_weight[int_y_train == weighted_class] = 4.\n\n model.fit(\n x_train,\n y_train,\n batch_size=batch_size,\n epochs=2,\n verbose=0,\n sample_weight=sample_weight)\n model.fit(\n x_train,\n y_train,\n batch_size=batch_size,\n epochs=2,\n verbose=0,\n sample_weight=sample_weight,\n validation_split=0.1)\n model.train_on_batch(\n x_train[:batch_size],\n y_train[:batch_size],\n sample_weight=sample_weight[:batch_size])\n model.test_on_batch(\n x_train[:batch_size],\n y_train[:batch_size],\n sample_weight=sample_weight[:batch_size])\n\n def test_temporal_sample_weights(self):\n num_classes = 5\n weighted_class = 3\n train_samples = 1000\n test_samples = 1000\n input_dim = 5\n timesteps = 3\n\n model = keras.models.Sequential()\n model.add(\n keras.layers.TimeDistributed(\n keras.layers.Dense(num_classes),\n input_shape=(timesteps, input_dim)))\n model.add(keras.layers.Activation('softmax'))\n\n np.random.seed(1337)\n (_, y_train), _ = testing_utils.get_test_data(\n train_samples=train_samples,\n test_samples=test_samples,\n input_shape=(input_dim,),\n num_classes=num_classes)\n int_y_train = y_train.copy()\n # convert class vectors to binary class matrices\n y_train = keras.utils.to_categorical(y_train, num_classes)\n\n class_weight = dict([(i, 1.) for i in range(num_classes)])\n class_weight[weighted_class] = 2.\n\n sample_weight = np.ones((y_train.shape[0]))\n sample_weight[int_y_train == weighted_class] = 2.\n with self.assertRaises(ValueError):\n model.compile(\n loss='binary_crossentropy',\n optimizer=RMSPropOptimizer(learning_rate=0.001),\n sample_weight_mode='temporal')\n\n def test_class_weight_invalid_use_case(self):\n num_classes = 5\n train_samples = 1000\n test_samples = 1000\n input_dim = 5\n timesteps = 3\n\n model = keras.models.Sequential()\n model.add(\n keras.layers.TimeDistributed(\n keras.layers.Dense(num_classes),\n input_shape=(timesteps, input_dim)))\n model.add(keras.layers.Activation('softmax'))\n model.compile(\n loss='binary_crossentropy',\n optimizer=RMSPropOptimizer(learning_rate=0.001))\n\n (x_train, y_train), _ = testing_utils.get_test_data(\n train_samples=train_samples,\n test_samples=test_samples,\n input_shape=(input_dim,),\n num_classes=num_classes)\n # convert class vectors to binary class matrices\n y_train = keras.utils.to_categorical(y_train, num_classes)\n class_weight = dict([(i, 1.) for i in range(num_classes)])\n\n del class_weight[1]\n with self.assertRaises(ValueError):\n model.fit(x_train, y_train,\n epochs=0, verbose=0, class_weight=class_weight)\n\n with self.assertRaises(ValueError):\n model.compile(\n loss='binary_crossentropy',\n optimizer=RMSPropOptimizer(learning_rate=0.001),\n sample_weight_mode=[])\n\n # Build multi-output model\n x = keras.Input((3,))\n y1 = keras.layers.Dense(4, name='1')(x)\n y2 = keras.layers.Dense(4, name='2')(x)\n model = keras.models.Model(x, [y1, y2])\n model.compile(optimizer=RMSPropOptimizer(learning_rate=0.001), loss='mse')\n x_np = np.random.random((10, 3))\n y_np = np.random.random((10, 4))\n w_np = np.random.random((10,))\n # This will work\n model.fit(x_np, [y_np, y_np], epochs=1, sample_weight={'1': w_np})\n # These will not\n with self.assertRaises(ValueError):\n model.fit(x_np, [y_np, y_np], epochs=1, sample_weight=[w_np])\n with self.assertRaises(TypeError):\n model.fit(x_np, [y_np, y_np], epochs=1, sample_weight=w_np)\n with self.assertRaises(ValueError):\n bad_w_np = np.random.random((11,))\n model.fit(x_np, [y_np, y_np], epochs=1, sample_weight={'1': bad_w_np})\n with self.assertRaises(ValueError):\n bad_w_np = np.random.random((10, 2))\n model.fit(x_np, [y_np, y_np], epochs=1, sample_weight={'1': bad_w_np})\n with self.assertRaises(ValueError):\n bad_w_np = np.random.random((10, 2, 2))\n model.fit(x_np, [y_np, y_np], epochs=1, sample_weight={'1': bad_w_np})\n\n\nclass CorrectnessTest(test.TestCase):\n\n @tf_test_util.run_in_graph_and_eager_modes()\n def test_loss_correctness(self):\n # Test that training loss is the same in eager and graph\n # (by comparing it to a reference value in a deterministic case)\n model = keras.Sequential()\n model.add(keras.layers.Dense(3,\n activation='relu',\n input_dim=4,\n kernel_initializer='ones'))\n model.add(keras.layers.Dense(2,\n activation='softmax',\n kernel_initializer='ones'))\n model.compile(loss='sparse_categorical_crossentropy',\n optimizer=RMSPropOptimizer(learning_rate=0.001))\n x = np.ones((100, 4))\n np.random.seed(123)\n y = np.random.randint(0, 1, size=(100, 1))\n history = model.fit(x, y, epochs=1, batch_size=10)\n self.assertEqual(\n np.around(history.history['loss'][-1], decimals=4), 0.6173)\n\n @tf_test_util.run_in_graph_and_eager_modes()\n def test_metrics_correctness(self):\n model = keras.Sequential()\n model.add(keras.layers.Dense(3,\n activation='relu',\n input_dim=4,\n kernel_initializer='ones'))\n model.add(keras.layers.Dense(1,\n activation='sigmoid',\n kernel_initializer='ones'))\n model.compile(loss='mae',\n metrics=['acc'],\n optimizer=RMSPropOptimizer(learning_rate=0.001))\n x = np.ones((100, 4))\n y = np.ones((100, 1))\n outs = model.evaluate(x, y)\n self.assertEqual(outs[1], 1.)\n y = np.zeros((100, 1))\n outs = model.evaluate(x, y)\n self.assertEqual(outs[1], 0.)\n\n @tf_test_util.run_in_graph_and_eager_modes()\n def test_loss_correctness_with_iterator(self):\n # Test that training loss is the same in eager and graph\n # (by comparing it to a reference value in a deterministic case)\n model = keras.Sequential()\n model.add(\n keras.layers.Dense(\n 3, activation='relu', input_dim=4, kernel_initializer='ones'))\n model.add(\n keras.layers.Dense(2, activation='softmax', kernel_initializer='ones'))\n model.compile(\n loss='sparse_categorical_crossentropy',\n optimizer=RMSPropOptimizer(learning_rate=0.001))\n x = np.ones((100, 4), dtype=np.float32)\n np.random.seed(123)\n y = np.random.randint(0, 1, size=(100, 1))\n dataset = dataset_ops.Dataset.from_tensor_slices((x, y))\n dataset = dataset.repeat(100)\n dataset = dataset.batch(10)\n iterator = dataset.make_one_shot_iterator()\n history = model.fit(iterator, epochs=1, steps_per_epoch=10)\n self.assertEqual(np.around(history.history['loss'][-1], decimals=4), 0.6173)\n\n @tf_test_util.run_in_graph_and_eager_modes()\n def test_metrics_correctness_with_iterator(self):\n model = keras.Sequential()\n model.add(\n keras.layers.Dense(\n 8, activation='relu', input_dim=4, kernel_initializer='ones'))\n model.add(\n keras.layers.Dense(1, activation='sigmoid', kernel_initializer='ones'))\n model.compile(\n loss='binary_crossentropy',\n metrics=['accuracy'],\n optimizer=RMSPropOptimizer(learning_rate=0.001))\n np.random.seed(123)\n x = np.random.randint(10, size=(100, 4)).astype(np.float32)\n y = np.random.randint(2, size=(100, 1)).astype(np.float32)\n dataset = dataset_ops.Dataset.from_tensor_slices((x, y))\n dataset = dataset.batch(10)\n iterator = dataset.make_one_shot_iterator()\n outs = model.evaluate(iterator, steps=10)\n self.assertEqual(np.around(outs[1], decimals=1), 0.5)\n\n y = np.zeros((100, 1), dtype=np.float32)\n dataset = dataset_ops.Dataset.from_tensor_slices((x, y))\n dataset = dataset.repeat(100)\n dataset = dataset.batch(10)\n iterator = dataset.make_one_shot_iterator()\n outs = model.evaluate(iterator, steps=10)\n self.assertEqual(outs[1], 0.)\n\n\nif __name__ == '__main__':\n ops.enable_eager_execution()\n test.main()\n"
] |
[
[
"tensorflow.python.keras.backend.zeros",
"tensorflow.python.framework.test_util.run_in_graph_and_eager_modes",
"tensorflow.python.keras.layers.Dense",
"numpy.around",
"numpy.concatenate",
"numpy.random.randint",
"tensorflow.python.framework.ops.enable_eager_execution",
"tensorflow.python.keras.layers.Activation",
"tensorflow.python.platform.test.main",
"tensorflow.python.keras.Sequential",
"numpy.zeros",
"tensorflow.python.keras.utils.to_categorical",
"tensorflow.python.data.ops.dataset_ops.Dataset.from_tensor_slices",
"tensorflow.python.keras.Model",
"tensorflow.python.keras.models.Sequential",
"tensorflow.python.keras.layers.Dropout",
"tensorflow.python.training.rmsprop.RMSPropOptimizer",
"tensorflow.python.keras.layers.Input",
"numpy.array",
"tensorflow.python.keras.testing_utils.get_test_data",
"numpy.random.random",
"tensorflow.python.keras.Input",
"numpy.random.seed",
"numpy.ones",
"tensorflow.python.keras.models.Model"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.5",
"1.4"
]
}
] |
c0g/tomserflow
|
[
"f7b42f6ba58c3ff20ecd002535d2cca5d93bcf8e",
"f7b42f6ba58c3ff20ecd002535d2cca5d93bcf8e",
"f7b42f6ba58c3ff20ecd002535d2cca5d93bcf8e"
] |
[
"tensorflow/contrib/learn/python/learn/ops/dnn_ops.py",
"tensorflow/contrib/losses/python/losses/loss_ops.py",
"tensorflow/python/kernel_tests/cholesky_op_test.py"
] |
[
"\"\"\"TensorFlow ops for deep neural networks.\"\"\"\n# Copyright 2015-present The Scikit Flow 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.\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.ops import nn\nfrom tensorflow.python.ops import rnn_cell\nfrom tensorflow.python.ops import variable_scope as vs\nfrom tensorflow.contrib.learn.python.learn.ops import dropout_ops\n\n\ndef dnn(tensor_in, hidden_units, activation=nn.relu, dropout=None):\n \"\"\"Creates fully connected deep neural network subgraph.\n\n Args:\n tensor_in: tensor or placeholder for input features.\n hidden_units: list of counts of hidden units in each layer.\n activation: activation function between layers. Can be None.\n dropout: if not None, will add a dropout layer with given probability.\n\n Returns:\n A tensor which would be a deep neural network.\n \"\"\"\n with vs.variable_scope('dnn'):\n for i, n_units in enumerate(hidden_units):\n with vs.variable_scope('layer%d' % i):\n tensor_in = rnn_cell.linear(tensor_in, n_units, True)\n if activation is not None:\n tensor_in = activation(tensor_in)\n if dropout is not None:\n tensor_in = dropout_ops.dropout(tensor_in, prob=(1.0 - dropout))\n return tensor_in\n",
"# 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\"\"\"## Loss operations for use in neural networks.\n\nAll of the loss functions take a pair of predictions and ground truth labels,\nfrom which the loss is computed. It is assumed that the shape of both these\ntensors is of the form [batch_size, d1, ... dN] where `batch_size` is the number\nof samples in the batch and `d1` ... `dN` are the remaining dimensions.\n\nIt is common, when training with multiple loss functions, to adjust the relative\nstrengths of individual losses. This is performed by rescaling the losses via\na `weight` parameter passed to the loss functions. For example, if we were\ntraining with both log_loss and sum_of_squares_loss, and we wished that the\nlog_loss penalty be twice as severe as the sum_of_squares_loss, we would\nimplement this as:\n\n # Explicitely set the weight.\n tf.contrib.losses.log(predictions, targets, weight=2.0)\n\n # Uses default weight of 1.0\n tf.contrib.losses.sum_of_squares(predictions, targets)\n\nWhile specifying a scalar loss rescales the loss over the entire batch,\nwe sometimes want to rescale the loss per batch sample. For example, if we have\ncertain examples that matter more to us to get correctly, we might want to have\na higher loss that other samples whose mistakes matter less. In this case, we\ncan provide a weight vector of length `batch_size` which results in the loss\nfor each sample in the batch being scaled by the corresponding weight element.\nFor example, consider the case of a classification problem where we want to\nmaximize our accuracy but we especially interested in obtaining high accuracy\nfor a specific class:\n\n inputs, labels = LoadData(batch_size=3)\n logits = MyModelPredictions(inputs)\n\n # Ensures that the loss for examples whose ground truth class is `3` is 5x\n # higher than the loss for all other examples.\n weight = tf.mul(4, tf.cast(tf.equal(labels, 3), tf.float32)) + 1\n\n onehot_labels = tf.one_hot(labels, num_classes=5)\n tf.contrib.losses.softmax_cross_entropy(logits, onehot_labels, weight=weight)\n\nFinally, in certain cases, we may want to specify a different loss for every\nsingle measurable value. For example, if we are performing per-pixel depth\nprediction, or per-pixel denoising, a single batch sample has P values where P\nis the number of pixels in the image. For many losses, the number of measurable\nvalues matches the number of elements in the predictions and targets tensors.\nFor others, such as softmax_cross_entropy and cosine_distance, the\nloss functions reduces the dimensions of the inputs to produces a tensor of\nlosses for each measurable value. For example, softmax_cross_entropy takes as\ninput predictions and labels of dimension [batch_size, num_classes] but the\nnumber of measurable values is [batch_size]. Consequently, when passing a weight\ntensor to specify a different loss for every measurable value, the dimension of\nthe tensor will depend on the loss being used.\n\nFor a concrete example, consider the case of per-pixel depth prediction where\ncertain ground truth depth values are missing (due to sensor noise in the\ncapture process). In this case, we want to assign zero weight to losses for\nthese predictions.\n\n # 'depths' that are missing have a value of 0:\n images, depths = LoadData(...)\n predictions = MyModelPredictions(images)\n\n weight = tf.cast(tf.greater(depths, 0), tf.float32)\n tf.contrib.losses.sum_of_squares(predictions, depths, weight)\n\nNote that when using weights for the losses, the final average is computed\nby rescaling the losses by the weights and then dividing by the total number of\nnon-zero samples. For an arbitrary set of weights, this may not necessarily\nproduce a weighted average. Instead, it simply and transparently rescales the\nper-element losses before averaging over the number of observations. For example\nif the losses computed by the loss function is an array [4, 1, 2, 3] and the\nweights are an array [1, 0.5, 3, 9], then the average loss is:\n\n (4*1 + 1*0.5 + 2*3 + 3*9) / 4\n\nHowever, with a single loss function and an arbitrary set of weights, one can\nstill easily create a loss function such that the resulting loss is a\nweighted average over the individual prediction errors:\n\n images, labels = LoadData(...)\n predictions = MyModelPredictions(images)\n\n weight = MyComplicatedWeightingFunction(labels)\n weight = tf.div(weight, tf.size(weight))\n tf.contrib.losses.sum_of_squares(predictions, depths, weight)\n\n\n@@absolute_difference\n@@cosine_distance\n@@log\n@@sigmoid_cross_entropy\n@@softmax_cross_entropy\n@@sum_of_pairwise_squares\n@@sum_of_squares\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn\n\n__all__ = [\n \"absolute_difference\",\n \"cosine_distance\",\n \"log\",\n \"sigmoid_cross_entropy\",\n \"softmax_cross_entropy\",\n \"sum_of_pairwise_squares\",\n \"sum_of_squares\",\n]\n\n\ndef _scale_losses(losses, weight):\n \"\"\"Computes the scaled loss.\n\n Args:\n losses: A `Tensor` of size [batch_size, d1, ... dN].\n weight: A `Tensor` of size [1], [batch_size] or [batch_size, d1, ... dN].\n The `losses` are reduced (tf.reduce_sum) until its dimension matches\n that of `weight` at which point the reduced `losses` are element-wise\n multiplied by `weight` and a final reduce_sum is computed on the result.\n Conceptually, this operation is equivalent to broadcasting (tiling)\n `weight` to be the same size as `losses`, performing an element-wise\n multiplication, and summing the result.\n\n Returns:\n A scalar tf.float32 `Tensor` whose value represents the sum of the scaled\n `losses`.\n \"\"\"\n # First, compute the sum of the losses over all elements:\n start_index = max(0, weight.get_shape().ndims)\n reduction_indices = list(range(start_index, losses.get_shape().ndims))\n reduced_losses = math_ops.reduce_sum(losses,\n reduction_indices=reduction_indices)\n reduced_losses = math_ops.mul(reduced_losses, weight)\n return math_ops.reduce_sum(reduced_losses)\n\n\ndef _safe_mean(losses, num_present):\n \"\"\"Computes a safe mean of the losses.\n\n Args:\n losses: A tensor whose elements contain individual loss measurements.\n num_present: The number of measurable losses in the tensor.\n\n Returns:\n A scalar representing the mean of the losses. If `num_present` is zero,\n then zero is returned.\n \"\"\"\n total_loss = math_ops.reduce_sum(losses)\n return math_ops.select(\n math_ops.greater(num_present, 0),\n math_ops.div(total_loss, math_ops.select(\n math_ops.equal(num_present, 0), 1.0, num_present)),\n array_ops.zeros_like(total_loss),\n name=\"value\")\n\n\ndef _compute_weighted_loss(losses, weight):\n \"\"\"Computes the weighted loss.\n\n Args:\n losses: A tensor of size [batch_size, d1, ... dN].\n weight: A tensor of size [1] or [batch_size, d1, ... dK] where K < N.\n\n Returns:\n A scalar `Tensor` that returns the weighted loss.\n\n Raises:\n ValueError: If the weight shape is not compatible with the losses shape or\n if the number of dimensions (rank) of either losses or weight is missing.\n \"\"\"\n losses = math_ops.to_float(losses)\n weight = math_ops.to_float(ops.convert_to_tensor(weight))\n\n if losses.get_shape().ndims is None:\n raise ValueError(\"losses.get_shape().ndims cannot be None\")\n if weight.get_shape().ndims is None:\n raise ValueError(\"weight.get_shape().ndims cannot be None\")\n\n total_loss = _scale_losses(losses, weight)\n num_present = _num_present(losses, weight)\n return _safe_mean(total_loss, num_present)\n\n\ndef _num_present(losses, weight, per_batch=False):\n \"\"\"Computes the number of elements in the loss function induced by `weight`.\n\n A given weight tensor induces different numbers of usable elements in the\n `losses` tensor. The `weight` tensor is broadcast across `losses` for all\n possible dimensions. For example, if `losses` is a tensor of dimension\n [4, 5, 6, 3] and weight is a tensor of size [4, 5], then weight is, in effect,\n tiled to match the size of `losses`. Following this effective tile, the total\n number of present elements is the number of non-zero weights.\n\n Args:\n losses: A tensor of size [batch_size, d1, ... dN].\n weight: A tensor of size [1] or [batch_size, d1, ... dK] where K < N.\n per_batch: Whether to return the number of elements per batch or as a sum\n total.\n\n Returns:\n The number of present (non-zero) elements in the losses tensor. If\n `per_batch` is True, the value is returned as a tensor of size\n [batch_size]. Otherwise, a single scalar tensor is returned.\n \"\"\"\n # To ensure that dims of [2, 1] gets mapped to [2,]\n weight = array_ops.squeeze(weight)\n\n # If the weight is a scalar, its easy to compute:\n if weight.get_shape().ndims == 0:\n batch_size = array_ops.reshape(array_ops.slice(array_ops.shape(losses),\n [0], [1]), [])\n num_per_batch = math_ops.div(math_ops.to_float(array_ops.size(losses)),\n math_ops.to_float(batch_size))\n num_per_batch = math_ops.select(math_ops.equal(weight, 0),\n 0.0, num_per_batch)\n num_per_batch = math_ops.mul(array_ops.ones(\n array_ops.reshape(batch_size, [1])), num_per_batch)\n return num_per_batch if per_batch else math_ops.reduce_sum(num_per_batch)\n\n # First, count the number of nonzero weights:\n if weight.get_shape().ndims >= 1:\n reduction_indices = list(range(1, weight.get_shape().ndims))\n num_nonzero_per_batch = math_ops.reduce_sum(\n math_ops.to_float(math_ops.not_equal(weight, 0)),\n reduction_indices=reduction_indices)\n\n # Next, determine the number of elements that weight would broadcast to:\n broadcast_dims = array_ops.slice(array_ops.shape(losses),\n [weight.get_shape().ndims], [-1])\n num_to_broadcast = math_ops.to_float(math_ops.reduce_prod(broadcast_dims))\n\n num_per_batch = math_ops.mul(num_nonzero_per_batch, num_to_broadcast)\n return num_per_batch if per_batch else math_ops.reduce_sum(num_per_batch)\n\n\ndef absolute_difference(predictions, targets, weight=1.0, scope=None):\n \"\"\"Adds an Absolute Difference loss to the training procedure.\n\n `weight` acts as a coefficient for the loss. If a scalar is provided, then the\n loss is simply scaled by the given value. If `weight` is a tensor of size\n [batch_size], then the total loss for each sample of the batch is rescaled\n by the corresponding element in the `weight` vector. If the shape of\n `weight` matches the shape of `predictions`, then the loss of each\n measurable element of `predictions` is scaled by the corresponding value of\n `weight`.\n\n Args:\n predictions: The predicted outputs.\n targets: The ground truth output tensor, same dimensions as 'predictions'.\n weight: Coefficients for the loss a scalar, a tensor of shape\n [batch_size] or a tensor whose shape matches `predictions`.\n scope: The scope for the operations performed in computing the loss.\n\n Returns:\n A scalar `Tensor` representing the loss value.\n\n Raises:\n ValueError: If the shape of `predictions` doesn't match that of `targets` or\n if the shape of `weight` is invalid.\n \"\"\"\n with ops.op_scope([predictions, targets],\n scope, \"sum_of_squares_loss\") as scope:\n predictions.get_shape().assert_is_compatible_with(targets.get_shape())\n if weight is None:\n raise ValueError(\"`weight` cannot be None\")\n predictions = math_ops.to_float(predictions)\n targets = math_ops.to_float(targets)\n losses = math_ops.abs(math_ops.sub(predictions, targets))\n return _compute_weighted_loss(losses, weight)\n\n\ndef sigmoid_cross_entropy(logits, multi_class_labels, weight=1.0,\n label_smoothing=0, scope=None):\n \"\"\"Creates a cross-entropy loss using tf.nn.sigmoid_cross_entropy_with_logits.\n\n Args:\n logits: [batch_size, num_classes] logits outputs of the network .\n multi_class_labels: [batch_size, num_classes] target labels in (0, 1).\n weight: Coefficients for the loss. The tensor must be a scalar, a tensor of\n shape [batch_size] or shape [batch_size, num_classes].\n label_smoothing: If greater than 0 then smooth the labels.\n scope: The scope for the operations performed in computing the loss.\n\n Returns:\n A scalar `Tensor` representing the loss value.\n \"\"\"\n with ops.op_scope([logits, multi_class_labels],\n scope, \"sigmoid_cross_entropy_loss\"):\n return _cross_entropy(logits, multi_class_labels, weight,\n label_smoothing,\n activation_fn=nn.sigmoid_cross_entropy_with_logits)\n\n\ndef softmax_cross_entropy(logits, onehot_labels, weight=1.0,\n label_smoothing=0, scope=None):\n \"\"\"Creates a cross-entropy loss using tf.nn.softmax_cross_entropy_with_logits.\n\n It can scale the loss by weight factor, and smooth the labels.\n\n Args:\n logits: [batch_size, num_classes] logits outputs of the network .\n onehot_labels: [batch_size, num_classes] target one_hot_encoded labels.\n weight: Coefficients for the loss. The tensor must be a scalar or a tensor\n of shape [batch_size].\n label_smoothing: If greater than 0 then smooth the labels.\n scope: the scope for the operations performed in computing the loss.\n\n Returns:\n A scalar `Tensor` representing the loss value.\n \"\"\"\n with ops.op_scope([logits, onehot_labels],\n scope, \"softmax_cross_entropy_loss\"):\n return _cross_entropy(logits, onehot_labels, weight,\n label_smoothing,\n activation_fn=nn.softmax_cross_entropy_with_logits)\n\n\ndef _cross_entropy(logits, onehot_labels, weight, label_smoothing,\n activation_fn):\n \"\"\"Adds a CrossEntropyLoss to the losses collection.\n\n `weight` acts as a coefficient for the loss. If a scalar is provided,\n then the loss is simply scaled by the given value. If `weight` is a\n tensor of size [`batch_size`], then the loss weights apply to each\n corresponding sample.\n\n Args:\n logits: [batch_size, num_classes] logits outputs of the network .\n onehot_labels: [batch_size, num_classes] target one_hot_encoded labels.\n weight: Coefficients for the loss. If the activation is SIGMOID, then the\n weight shape must be one of [1], [batch_size] or logits.shape().\n Otherwise, the weight shape must be either [1] or [batch_size].\n label_smoothing: If greater than 0 then smooth the labels.\n activation_fn: The activation function to use. The method must take three\n arguments, the logits, the labels, and an operation name.\n\n Returns:\n A scalar `Tensor` representing the loss value.\n\n Raises:\n ValueError: If the shape of `predictions` doesn't match that of `targets` or\n if the shape of `weight` is invalid or if `weight` is None.\n \"\"\"\n logits.get_shape().assert_is_compatible_with(onehot_labels.get_shape())\n if weight is None:\n raise ValueError(\"`weight` cannot be None\")\n\n onehot_labels = math_ops.cast(onehot_labels, logits.dtype)\n\n if label_smoothing > 0:\n num_classes = onehot_labels.get_shape()[1].value\n smooth_positives = 1.0 - label_smoothing\n smooth_negatives = label_smoothing / num_classes\n onehot_labels = onehot_labels * smooth_positives + smooth_negatives\n\n losses = activation_fn(logits, onehot_labels, name=\"xentropy\")\n return _compute_weighted_loss(losses, weight)\n\n\ndef log(predictions, targets, weight=1.0, epsilon=1e-7, scope=None):\n \"\"\"Adds a Log Loss term to the training procedure.\n\n `weight` acts as a coefficient for the loss. If a scalar is provided, then the\n loss is simply scaled by the given value. If `weight` is a tensor of size\n [batch_size], then the total loss for each sample of the batch is rescaled\n by the corresponding element in the `weight` vector. If the shape of\n `weight` matches the shape of `predictions`, then the loss of each\n measurable element of `predictions` is scaled by the corresponding value of\n `weight`.\n\n Args:\n predictions: The predicted outputs.\n targets: The ground truth output tensor, same dimensions as 'predictions'.\n weight: Coefficients for the loss a scalar, a tensor of shape\n [batch_size] or a tensor whose shape matches `predictions`.\n epsilon: A small increment to add to avoid taking a log of zero.\n scope: The scope for the operations performed in computing the loss.\n\n Returns:\n A scalar `Tensor` representing the loss value.\n\n Raises:\n ValueError: If the shape of `predictions` doesn't match that of `targets` or\n if the shape of `weight` is invalid.\n \"\"\"\n with ops.op_scope([predictions, targets],\n scope, \"log_loss\") as scope:\n predictions.get_shape().assert_is_compatible_with(targets.get_shape())\n if weight is None:\n raise ValueError(\"`weight` cannot be None\")\n predictions = math_ops.to_float(predictions)\n targets = math_ops.to_float(targets)\n losses = -math_ops.mul(\n targets,\n math_ops.log(predictions + epsilon)) - math_ops.mul(\n (1 - targets), math_ops.log(1 - predictions + epsilon))\n return _compute_weighted_loss(losses, weight)\n\n\ndef sum_of_squares(predictions, targets, weight=1.0, scope=None):\n \"\"\"Adds a Sum-of-Squares loss to the training procedure.\n\n `weight` acts as a coefficient for the loss. If a scalar is provided, then the\n loss is simply scaled by the given value. If `weight` is a tensor of size\n [batch_size], then the total loss for each sample of the batch is rescaled\n by the corresponding element in the `weight` vector. If the shape of\n `weight` matches the shape of `predictions`, then the loss of each\n measurable element of `predictions` is scaled by the corresponding value of\n `weight`.\n\n Args:\n predictions: The predicted outputs.\n targets: The ground truth output tensor, same dimensions as 'predictions'.\n weight: Coefficients for the loss a scalar, a tensor of shape\n [batch_size] or a tensor whose shape matches `predictions`.\n scope: The scope for the operations performed in computing the loss.\n\n Returns:\n A scalar `Tensor` representing the loss value.\n\n Raises:\n ValueError: If the shape of `predictions` doesn't match that of `targets` or\n if the shape of `weight` is invalid.\n \"\"\"\n with ops.op_scope([predictions, targets],\n scope, \"sum_of_squares_loss\") as scope:\n predictions.get_shape().assert_is_compatible_with(targets.get_shape())\n if weight is None:\n raise ValueError(\"`weight` cannot be None\")\n predictions = math_ops.to_float(predictions)\n targets = math_ops.to_float(targets)\n losses = math_ops.square(math_ops.sub(predictions, targets))\n return _compute_weighted_loss(losses, weight)\n\n\ndef sum_of_pairwise_squares(predictions, targets, weight=1.0, scope=None):\n \"\"\"Adds a pairwise-errors-squared loss to the training procedure.\n\n Unlike the sum_of_squares loss, which is a measure of the differences between\n corresponding elements of `predictions` and `targets`, sum_of_pairwise_squares\n is a measure of the differences between pairs of corresponding elements of\n `predictions` and `targets`.\n\n For example, if `targets`=[a, b, c] and `predictions`=[x, y, z], there are\n three pairs of differences are summed to compute the loss:\n loss = [ ((a-b) - (x-y)).^2 + ((a-c) - (x-z)).^2 + ((b-c) - (y-z)).^2 ] / 3\n\n Note that since the inputs are of size [batch_size, d0, ... dN], the\n corresponding pairs are computed within each batch sample but not across\n samples within a batch. For example, if `predictions` represents a batch of\n 16 grayscale images of dimenion [batch_size, 100, 200], then the set of pairs\n is drawn from each image, but not across images.\n\n `weight` acts as a coefficient for the loss. If a scalar is provided, then the\n loss is simply scaled by the given value. If `weight` is a tensor of size\n [batch_size], then the total loss for each sample of the batch is rescaled\n by the corresponding element in the `weight` vector.\n\n Args:\n predictions: The predicted outputs, a tensor of size [batch_size, d0, .. dN]\n where N+1 is the total number of dimensions in `predictions`.\n targets: The ground truth output tensor, whose shape must match the shape of\n the `predictions` tensor.\n weight: Coefficients for the loss a scalar, a tensor of shape [batch_size]\n or a tensor whose shape matches `predictions`.\n scope: The scope for the operations performed in computing the loss.\n\n Returns:\n A scalar `Tensor` representing the loss value.\n\n Raises:\n ValueError: If the shape of `predictions` doesn't match that of `targets` or\n if the shape of `weight` is invalid.\n \"\"\"\n with ops.op_scope([predictions, targets],\n scope, \"sum_of_pairwise_squares_loss\") as scope:\n predictions.get_shape().assert_is_compatible_with(targets.get_shape())\n if weight is None:\n raise ValueError(\"`weight` cannot be None\")\n predictions = math_ops.to_float(predictions)\n targets = math_ops.to_float(targets)\n weight = math_ops.to_float(ops.convert_to_tensor(weight))\n\n diffs = math_ops.sub(predictions, targets)\n\n # Need to verify here since the function doesn't use _compute_weighted_loss\n if diffs.get_shape().ndims is None:\n raise ValueError(\"diffs.get_shape().ndims cannot be None\")\n if weight.get_shape().ndims is None:\n raise ValueError(\"weight.get_shape().ndims cannot be None\")\n\n reduction_indices = list(range(1, diffs.get_shape().ndims))\n\n sum_squares_diff_per_batch = math_ops.reduce_sum(\n math_ops.square(diffs),\n reduction_indices=reduction_indices)\n num_present_per_batch = _num_present(diffs, weight, per_batch=True)\n\n term1 = 2.0 * math_ops.div(sum_squares_diff_per_batch,\n num_present_per_batch)\n\n sum_diff = math_ops.reduce_sum(diffs, reduction_indices=reduction_indices)\n term2 = 2.0 * math_ops.div(math_ops.square(sum_diff),\n math_ops.square(num_present_per_batch))\n\n loss = _scale_losses(term1 - term2, weight)\n\n return math_ops.select(math_ops.reduce_sum(num_present_per_batch) > 0,\n loss,\n array_ops.zeros_like(loss),\n name=\"value\")\n\n\ndef cosine_distance(predictions, targets, dim, weight=1.0, scope=None):\n \"\"\"Adds a cosine-distance loss to the training procedure.\n\n Note that the function assumes that the predictions and targets are already\n unit-normalized.\n\n Args:\n predictions: An arbitrary matrix.\n targets: A `Tensor` whose shape matches 'predictions'\n dim: The dimension along which the cosine distance is computed.\n weight: Coefficients for the loss a scalar, a tensor of shape\n [batch_size] or a tensor whose shape matches `predictions`.\n scope: The scope for the operations performed in computing the loss.\n\n Returns:\n A scalar `Tensor` representing the loss value.\n\n Raises:\n ValueError: If predictions.shape doesn't match targets.shape, if the ignore\n mask is provided and its shape doesn't match targets.shape or if\n the ignore mask is not boolean valued.\n \"\"\"\n with ops.op_scope([predictions, targets],\n scope, \"cosine_distance_loss\") as scope:\n predictions.get_shape().assert_is_compatible_with(targets.get_shape())\n if weight is None:\n raise ValueError(\"`weight` cannot be None\")\n\n predictions = math_ops.to_float(predictions)\n targets = math_ops.to_float(targets)\n\n radial_diffs = math_ops.mul(predictions, targets)\n losses = 1 - math_ops.reduce_sum(radial_diffs, reduction_indices=[dim,])\n return _compute_weighted_loss(losses, weight)\n",
"# Copyright 2015 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\n\"\"\"Tests for tensorflow.ops.tf.Cholesky.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nfrom six.moves import xrange # pylint: disable=redefined-builtin\nimport tensorflow as tf\n\n#TODO: check if built with GPU\nclass CholeskyOpTest(tf.test.TestCase):\n\n def _verifyCholeskyBase(self, sess, x, chol, verification):\n chol_np, verification_np = sess.run([chol, verification])\n self.assertAllClose(x, verification_np)\n self.assertShapeEqual(x, chol)\n # Check that the cholesky is lower triangular, and has positive diagonal\n # elements.\n if chol_np.shape[-1] > 0:\n chol_reshaped = np.reshape(chol_np, (-1, chol_np.shape[-2],\n chol_np.shape[-1]))\n for chol_matrix in chol_reshaped:\n self.assertAllClose(chol_matrix, np.tril(chol_matrix))\n self.assertTrue((np.diag(chol_matrix) > 0.0).all())\n\n def _verifyCholesky(self, x):\n # Verify that LL^T == x.\n with self.test_session() as sess:\n for d in ['/cpu:0', 'gpu:0']:\n with tf.device(d):\n # Check the batch version, which works for ndim >= 2.\n chol = tf.batch_cholesky(x)\n verification = tf.batch_matmul(chol, chol, adj_x=False, adj_y=True)\n self._verifyCholeskyBase(sess, x, chol, verification)\n\n if x.ndim == 2: # Check the simple form of cholesky\n chol = tf.cholesky(x)\n verification = tf.matmul(\n chol, chol, transpose_a=False, transpose_b=True)\n self._verifyCholeskyBase(sess, x, chol, verification)\n\n def testBasic(self):\n self._verifyCholesky(np.array([[4., -1., 2.], [-1., 6., 0], [2., 0., 5.]]))\n\n def testBatch(self):\n simple_array = np.array([[[1., 0.], [0., 5.]]]) # shape (1, 2, 2)\n self._verifyCholesky(simple_array)\n self._verifyCholesky(np.vstack((simple_array, simple_array)))\n odd_sized_array = np.array([[[4., -1., 2.], [-1., 6., 0], [2., 0., 5.]]])\n self._verifyCholesky(np.vstack((odd_sized_array, odd_sized_array)))\n\n # Generate random positive-definite matrices.\n matrices = np.random.rand(10, 5, 5)\n for i in xrange(10):\n matrices[i] = np.dot(matrices[i].T, matrices[i])\n self._verifyCholesky(matrices)\n\n def testNonSquareMatrix(self):\n for d in ['/cpu:0', 'gpu:0']:\n with tf.device(d):\n with self.assertRaises(ValueError):\n tf.cholesky(np.array([[1., 2., 3.], [3., 4., 5.]]))\n\n def testWrongDimensions(self):\n for d in ['/cpu:0', 'gpu:0']:\n with tf.device(d):\n tensor3 = tf.constant([1., 2.])\n with self.assertRaises(ValueError):\n tf.cholesky(tensor3)\n\n def testNotInvertible(self):\n # The input should be invertible.\n with self.test_session():\n with self.assertRaisesOpError(\"LLT decomposition was not successful. The\"\n \" input might not be valid.\"):\n # All rows of the matrix below add to zero\n self._verifyCholesky(np.array([[1., -1., 0.], [-1., 1., -1.], [0., -1.,\n 1.]]))\n\n def testEmpty(self):\n self._verifyCholesky(np.empty([0, 2, 2]))\n self._verifyCholesky(np.empty([2, 0, 0]))\n\n\nclass CholeskyGradTest(tf.test.TestCase):\n _backprop_block_size = 32\n\n def getShapes(self, shapeList):\n return ((elem, int(np.floor(1.2 * elem))) for elem in shapeList)\n\n def testSmallMatrices(self):\n np.random.seed(0)\n shapes = self.getShapes([1, 2, 10])\n self.runFiniteDifferences(shapes)\n\n def testOneBlockMatrices(self):\n np.random.seed(0)\n shapes = self.getShapes([self._backprop_block_size + 1])\n self.runFiniteDifferences(shapes, dtypes=(tf.float32, tf.float64),\n scalarTest=True)\n\n def testTwoBlockMatrixFloat(self):\n np.random.seed(0)\n shapes = self.getShapes([2 * self._backprop_block_size + 1])\n self.runFiniteDifferences(shapes, dtypes=(tf.float32,), scalarTest=True)\n\n def testTwoBlockMatrixDouble(self):\n np.random.seed(0)\n shapes = self.getShapes([2 * self._backprop_block_size + 1])\n self.runFiniteDifferences(shapes, dtypes=(tf.float64,), scalarTest=True)\n\n def runFiniteDifferences(self, shapes, dtypes=(tf.float32, tf.float64),\n scalarTest=False):\n with self.test_session(use_gpu=True):\n for shape in shapes:\n for dtype in dtypes:\n for d in ['/cpu:0', 'gpu:0']:\n with tf.device(d):\n if not(scalarTest):\n x = tf.constant(np.random.randn(shape[0], shape[1]), dtype)\n K = tf.matmul(x, tf.transpose(x)) / shape[0] # K is posdef\n y = tf.cholesky(K)\n else: # This is designed to be a faster test for larger matrices.\n x = tf.constant(np.random.randn(), dtype)\n R = tf.constant(np.random.randn(shape[0], shape[1]), dtype)\n e = tf.mul(R, x)\n K = tf.matmul(e, tf.transpose(e)) / shape[0] # K is posdef\n y = tf.reduce_mean(tf.cholesky(K))\n error = tf.test.compute_gradient_error(x, x._shape_as_list(),\n y, y._shape_as_list())\n tf.logging.info(\"error = %f\", error)\n if dtype == tf.float64:\n self.assertLess(error, 1e-5)\n else:\n self.assertLess(error, 2e-3)\n\nif __name__ == \"__main__\":\n tf.test.main()\n"
] |
[
[
"tensorflow.contrib.learn.python.learn.ops.dropout_ops.dropout",
"tensorflow.python.ops.variable_scope.variable_scope",
"tensorflow.python.ops.rnn_cell.linear"
],
[
"tensorflow.python.ops.math_ops.log",
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.framework.ops.op_scope",
"tensorflow.python.ops.math_ops.greater",
"tensorflow.python.ops.array_ops.squeeze",
"tensorflow.python.ops.math_ops.not_equal",
"tensorflow.python.ops.math_ops.to_float",
"tensorflow.python.ops.math_ops.sub",
"tensorflow.python.ops.math_ops.reduce_prod",
"tensorflow.python.ops.array_ops.size",
"tensorflow.python.ops.math_ops.cast",
"tensorflow.python.ops.math_ops.square",
"tensorflow.python.ops.array_ops.zeros_like",
"tensorflow.python.ops.math_ops.equal",
"tensorflow.python.ops.math_ops.div",
"tensorflow.python.ops.math_ops.mul",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.ops.array_ops.reshape",
"tensorflow.python.ops.math_ops.reduce_sum"
],
[
"numpy.diag",
"numpy.dot",
"tensorflow.device",
"numpy.vstack",
"numpy.random.randn",
"numpy.tril",
"tensorflow.cholesky",
"tensorflow.batch_matmul",
"numpy.reshape",
"tensorflow.test.main",
"tensorflow.matmul",
"tensorflow.logging.info",
"numpy.random.rand",
"numpy.floor",
"numpy.array",
"tensorflow.batch_cholesky",
"tensorflow.constant",
"tensorflow.transpose",
"numpy.random.seed",
"tensorflow.mul",
"numpy.empty"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"2.9",
"1.7",
"2.5",
"0.12",
"2.8",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"0.12",
"1.7"
]
}
] |
evenmarbles/rlpy
|
[
"3c3c39a316285ca725268e81aef030e5c764f797",
"3c3c39a316285ca725268e81aef030e5c764f797"
] |
[
"rlpy/stats/models/_basic.py",
"rlpy/environment/mountaincar.py"
] |
[
"from __future__ import division, print_function, absolute_import\n# noinspection PyUnresolvedReferences\nfrom six.moves import range\n\nimport numpy as np\nfrom scipy.misc import doccer\n\nfrom ...stats import nonuniform\nfrom ...auxiliary.array import normalize, nunique, accum\n\n__all__ = ['markov']\n\n\n_doc_default_callparams = \"\"\"\\\nstartprob : array_like\n Start probabilities.\ntransmat : array_like\n Transition matrix.\n\"\"\"\n\n_doc_frozen_callparams = \"\"\n\n_doc_frozen_callparams_note = \\\n \"\"\"See class definition for a detailed description of parameters.\"\"\"\n\ndocdict_params = {\n '_doc_default_callparams': _doc_default_callparams,\n}\n\ndocdict_noparams = {\n '_doc_default_callparams': _doc_frozen_callparams,\n}\n\n\n# noinspection PyPep8Naming\nclass markov_gen(object):\n \"\"\"Markov model.\n\n The `startprob` keyword specifies the start probabilities for the model.\n The `transmat` keyword specifies the transition probabilities the model\n follows.\n\n Methods\n -------\n score(x, startprob, transmat)\n Log probability of the given data `x`.\n sample(x, startprob, transmat, size=1)\n Draw random samples from a Markov model.\n fit(x)\n Fits a Markov model from data via MLE or MAP.\n\n Parameters\n ----------\n %(_doc_default_callparams)s\n\n\n Alternatively, the object may be called (as a function) to fix the degrees\n of freedom and scale parameters, returning a \"frozen\" Markov model:\n\n rv = normal_invwishart(startprob=None, transmat=None)\n - Frozen object with the same methods but holding the given\n start probabilities and transitions fixed.\n\n Examples\n --------\n >>> from mlpy.stats.models import markov\n\n >>> startprob = np.array([0.1, 0.4, 0.5])\n >>> transmat = np.array([[0.3, 0.2, 0.5], [0.6, 0.3, 0.1], [0.1, 0.5, 0.4]])\n\n >>> m = markov(startprob, transmat)\n >>> m.sample(size=2)\n [[2 2]]\n\n .. note::\n Adapted from Matlab:\n\n | Project: `Probabilistic Modeling Toolkit for Matlab/Octave <https://github.com/probml/pmtk3>`_.\n | Copyright (2010) Kevin Murphy and Matt Dunham\n | License: `MIT <https://github.com/probml/pmtk3/blob/5fefd068a2e84ae508684d3e4750bd72a4164ba0/license.txt>`_\n\n \"\"\"\n\n def __init__(self):\n super(markov_gen, self).__init__()\n self.__doc__ = doccer.docformat(self.__doc__, docdict_params)\n\n def __call__(self, startprob, transmat):\n markov_frozen(startprob, transmat)\n\n def score(self, x, startprob, transmat):\n \"\"\"Log probability for a given data `x`.\n\n Attributes\n ----------\n x : ndarray\n Data to evaluate.\n %(_doc_default_callparams)s\n\n Returns\n -------\n log_prob : float\n The log probability of the data.\n\n \"\"\"\n log_transmat = np.log(transmat + np.finfo(float).eps)\n log_startprob = np.log(startprob + np.finfo(float).eps)\n log_prior = log_startprob[x[:, 0]]\n\n n = x.shape[0]\n nstates = log_startprob.shape[0]\n\n logp = np.zeros(n)\n for i in range(n):\n njk = accum(np.vstack([x[i, 0:-1], x[i, 1::]]).T, 1, size=(nstates, nstates), dtype=np.int32)\n logp[i] = np.sum(njk * log_transmat)\n return logp + log_prior\n\n def sample(self, startprob, transmat, size=1):\n \"\"\"Sample from a Markov model.\n\n Attributes\n ----------\n size: int\n Defining number of sampled variates. Defaults to `1`.\n\n Returns\n -------\n vals: ndarray\n The sampled sequences of size (nseq, seqlen).\n\n \"\"\"\n if np.isscalar(size):\n size = (1, size)\n\n vals = np.zeros(size, dtype=np.int32)\n\n nseq, seqlen = size\n for i in range(nseq):\n vals[i][0] = nonuniform.rvs(startprob)\n for t in range(1, seqlen):\n vals[i][t] = nonuniform.rvs(transmat[vals[i][t - 1]])\n return vals\n\n def fit(self, x):\n \"\"\"Fit a Markov model from data via MLE or MAP.\n\n Attributes\n ----------\n x : ndarray[int]\n Observed data\n\n Returns\n -------\n %(_doc_default_callparams)s\n\n \"\"\"\n # TODO: allow to pass pseudo_counts as parameter?\n nstates = nunique(x.ravel())\n pi_pseudo_counts = np.ones(nstates)\n transmat_pseudo_counts = np.ones((nstates, nstates))\n\n n = x.shape[0]\n\n startprob = normalize(np.bincount(x[:, 0])) + pi_pseudo_counts - 1\n counts = np.zeros((nstates, nstates))\n for i in range(n):\n counts += accum(np.vstack([x[i, 0:-1], x[i, 1::]]).T, 1, size=(nstates, nstates))\n transmat = normalize(counts + transmat_pseudo_counts - 1, 1)\n return startprob, transmat\n\nmarkov = markov_gen()\n\n\n# noinspection PyPep8Naming\nclass markov_frozen(object):\n\n def __init__(self, startprob, transmat):\n \"\"\"Create a \"frozen\" Markov model.\n\n Parameters\n ----------\n startprob : array_like\n Start probabilities\n transmat : array_like\n Transition matrix\n\n \"\"\"\n self._model = markov_gen()\n\n self.startprob = startprob\n self.transmat = transmat\n\n def score(self, x):\n return self._model.score(x, self.startprob, self.transmat)\n\n def sample(self, size=1):\n return self._model.sample(self.startprob, self.transmat, size)\n",
"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom rlglued.environment.environment import Environment\nfrom rlglued.environment import loader as env_loader\nfrom rlglued.utils.taskspecvrlglue3 import TaskSpec\nfrom rlglued.types import Observation\nfrom rlglued.types import Reward_observation_terminal\n\n\nclass MountainCar(Environment):\n\n def __init__(self, noise=0.0, reward_noise=0.0, random_start=False, visualize=False):\n self._noise = noise\n self._reward_noise = reward_noise\n self._random_start = random_start\n\n self._visualize = visualize\n self._fig = None\n self._ax = None\n self._t = np.arange(-1.2, .6, .01)\n\n self._sensors = np.zeros(2)\n self._limits = np.array([[-1.2, .6], [-.07, .07]])\n self._goal_pos = 0.5\n self._accel = .001\n self._gravity = -.0025\n self._hill_freq = 3.\n self._dt = 1.\n\n def init(self):\n ts = TaskSpec(discount_factor=1.0, reward_range=(-1.0, 0.0))\n ts.set_episodic()\n\n for i, (min_, max_) in enumerate(self._limits):\n if min_ == -np.inf:\n min_ = 'NEGINF'\n if max_ == np.inf:\n max_ = 'POSINF'\n ts.add_double_obs((min_, max_))\n\n ts.add_int_act((0, 2))\n\n extra = \" COPYRIGHT Mountain Car (Python) implemented by Astrid Jackson.\"\n state_descr = \"OBSDESCR {'descr':['car position','car velocity']}\"\n action_descr = \"ACTDESCR {2:'forward',1:'neutral',0:'reverse'}\"\n\n ts.set_extra(state_descr + \" \" + action_descr + extra)\n return ts.to_taskspec()\n\n def start(self):\n if self._random_start:\n self._sensors = np.random.random(self._sensors.shape)\n self._sensors *= (self._limits[:, 1] - self._limits[:, 0])\n self._sensors += self._limits[:, 0]\n else:\n self._sensors = np.zeros(self._sensors.shape)\n self._sensors[0] = -0.5\n\n self._render(self._sensors[0])\n\n return_obs = Observation()\n return_obs.doubleArray = self._sensors.tolist()\n return return_obs\n\n def step(self, action):\n return_ro = Reward_observation_terminal()\n self._apply(action)\n self._render(self._sensors[0])\n\n return_ro.terminal = self._is_terminal()\n\n return_ro.r = -1.\n if return_ro.terminal:\n return_ro.r = .0\n\n if self._reward_noise > 0:\n return_ro.r += np.random.normal(scale=self._reward_noise)\n\n obs = Observation()\n obs.doubleArray = self._sensors.tolist()\n return_ro.o = obs\n\n return return_ro\n\n def cleanup(self):\n pass\n\n def message(self, msg):\n return \"I don't know how to respond to your message\"\n\n def _apply(self, action):\n direction = action.intArray[0] - 1\n direction += self._accel * np.random.normal(scale=self._noise) if self._noise > 0 else 0.0\n\n self._sensors[1] += (self._accel * direction) + (self._gravity * np.cos(self._hill_freq * self._sensors[0]))\n self._sensors[1] = self._sensors[1].clip(min=self._limits[1, 0], max=self._limits[1, 1])\n self._sensors[0] += self._dt * self._sensors[1]\n self._sensors[0] = self._sensors[0].clip(min=self._limits[0, 0], max=self._limits[0, 1])\n if self._sensors[0] == self._limits[0, 0] and self._sensors[1] < 0.0:\n self._sensors[1] = 0.0\n\n def _is_terminal(self):\n return self._sensors[0] >= self._goal_pos\n\n def _render(self, pos):\n if self._visualize:\n if self._fig is None or not plt.fignum_exists(self._fig.number):\n self._fig = plt.figure()\n plt.rcParams['legend.fontsize'] = 10\n self._ax = self._fig.add_subplot(1, 1, 1)\n self._fig.show()\n\n self._ax.cla()\n self._ax.plot(self._t, np.sin(3 * self._t))\n\n car = plt.Circle((pos, np.sin(3 * pos)), radius=0.02, fc='r')\n self._ax.add_artist(car)\n\n self._ax.set_ylim(-1.05, 1.05)\n\n self._fig.canvas.draw()\n\n\nif __name__ == \"__main__\":\n env_loader.load_environment(MountainCar())\n"
] |
[
[
"numpy.vstack",
"numpy.ones",
"numpy.finfo",
"numpy.bincount",
"numpy.isscalar",
"numpy.zeros",
"numpy.sum",
"scipy.misc.doccer.docformat"
],
[
"matplotlib.pyplot.fignum_exists",
"numpy.random.random",
"numpy.arange",
"numpy.cos",
"numpy.sin",
"numpy.random.normal",
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"0.15",
"1.4",
"0.16",
"1.0",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"0.10",
"0.17",
"1.3"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
skysky77/MGNMT
|
[
"19dded399a310cd118eee09bd37d657746d11cf1"
] |
[
"src/tasks/lm.py"
] |
[
"# MIT License\n\n# Copyright (c) 2018 the NJUNMT-pytorch authors.\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport os\nimport random\nimport time\nfrom copy import deepcopy\n\nimport numpy as np\nimport torch\nimport yaml\nfrom tensorboardX import SummaryWriter\nfrom tqdm import tqdm\n\nfrom src.data.data_iterator import DataIterator\nfrom src.data.dataset import TextLineDataset, ZipDataset\nfrom src.data.vocabulary import Vocabulary\nfrom src.decoding import beam_search, ensemble_beam_search\nfrom src.decoding.beam_search import nmt_lm_fusion_beam_search\nfrom src.metric.bleu_scorer import SacreBLEUScorer\nfrom src.models import build_model\nfrom src.modules.criterions import NMTCriterion\nfrom src.optim import Optimizer\nfrom src.optim.lr_scheduler import ReduceOnPlateauScheduler, NoamScheduler, RsqrtScheduler\nfrom src.utils.common_utils import *\nfrom src.utils.configs import default_configs, pretty_configs\nfrom src.utils.logging import *\nfrom src.utils.moving_average import MovingAverage\n\nBOS = Vocabulary.BOS\nEOS = Vocabulary.EOS\nPAD = Vocabulary.PAD\n\n\ndef set_seed(seed):\n torch.manual_seed(seed)\n\n if torch.cuda.is_available():\n torch.cuda.manual_seed_all(seed)\n\n random.seed(seed)\n\n np.random.seed(seed)\n\n torch.backends.cudnn.deterministic = True\n\n\ndef load_model_parameters(path, map_location=\"cpu\"):\n state_dict = torch.load(path, map_location=map_location)\n\n if \"model\" in state_dict:\n return state_dict[\"model\"]\n return state_dict\n\n\ndef split_shard(*inputs, split_size=1):\n if split_size <= 1:\n yield inputs\n else:\n\n lengths = [len(s) for s in inputs[-1]] #\n sorted_indices = np.argsort(lengths)\n\n # sorting inputs\n\n inputs = [\n [inp[ii] for ii in sorted_indices]\n for inp in inputs\n ]\n\n # split shards\n total_batch = sorted_indices.shape[0] # total number of batches\n\n if split_size >= total_batch:\n yield inputs\n else:\n shard_size = total_batch // split_size\n\n _indices = list(range(total_batch))[::shard_size] + [total_batch]\n\n for beg, end in zip(_indices[:-1], _indices[1:]):\n yield (inp[beg:end] for inp in inputs)\n\n\ndef prepare_data(seqs_x, seqs_y=None, cuda=False, batch_first=True):\n \"\"\"\n Args:\n eval ('bool'): indicator for eval/infer.\n\n Returns:\n\n \"\"\"\n\n def _np_pad_batch_2D(samples, pad, batch_first=True, cuda=True):\n\n batch_size = len(samples)\n\n sizes = [len(s) for s in samples]\n max_size = max(sizes)\n\n x_np = np.full((batch_size, max_size), fill_value=pad, dtype='int64')\n\n for ii in range(batch_size):\n x_np[ii, :sizes[ii]] = samples[ii]\n\n if batch_first is False:\n x_np = np.transpose(x_np, [1, 0])\n\n x = torch.tensor(x_np)\n\n if cuda is True:\n x = x.cuda()\n return x\n\n seqs_x = list(map(lambda s: [BOS] + s + [EOS], seqs_x))\n x = _np_pad_batch_2D(samples=seqs_x, pad=PAD,\n cuda=cuda, batch_first=batch_first)\n\n if seqs_y is None:\n return x\n\n seqs_y = list(map(lambda s: [BOS] + s + [EOS], seqs_y))\n y = _np_pad_batch_2D(seqs_y, pad=PAD,\n cuda=cuda, batch_first=batch_first)\n\n return x, y\n\n\ndef compute_forward(model,\n critic,\n seqs_x,\n eval=False,\n normalization=1.0,\n norm_by_words=False\n ):\n \"\"\"\n :type model: nn.Module\n\n :type critic: NMTCriterion\n \"\"\"\n x_inp = seqs_x[:, :-1].contiguous()\n x_label = seqs_x[:, 1:].contiguous()\n\n words_norm = x_label.ne(PAD).float().sum(1)\n\n if not eval:\n model.train()\n critic.train()\n # For training\n with torch.enable_grad():\n log_probs = model(x_inp)\n loss = critic(inputs=log_probs, labels=x_label, reduce=False,\n normalization=normalization)\n\n if norm_by_words:\n loss = loss.div(words_norm).sum()\n else:\n loss = loss.sum()\n torch.autograd.backward(loss)\n return loss.item()\n else:\n model.eval()\n critic.eval()\n # For compute loss\n with torch.no_grad():\n log_probs = model(x_inp)\n loss = critic(inputs=log_probs, labels=x_label, normalization=normalization, reduce=True)\n return loss.item()\n\n\ndef loss_validation(model, critic, valid_iterator):\n \"\"\"\n :type model: Transformer\n\n :type critic: NMTCriterion\n\n :type valid_iterator: DataIterator\n \"\"\"\n\n n_sents = 0\n n_tokens = 0.0\n\n sum_loss = 0.0\n\n valid_iter = valid_iterator.build_generator()\n\n for batch in valid_iter:\n _, seqs_x = batch\n\n n_sents += len(seqs_x)\n n_tokens += sum(len(s) for s in seqs_x)\n\n x = prepare_data(seqs_x, cuda=GlobalNames.USE_GPU)\n\n loss = compute_forward(model=model,\n critic=critic,\n seqs_x=x,\n eval=True)\n\n if np.isnan(loss):\n WARN(\"NaN detected!\")\n\n sum_loss += float(loss)\n\n return float(sum_loss / n_sents)\n\n\ndef bleu_validation(uidx,\n valid_iterator,\n model,\n bleu_scorer,\n vocab_tgt,\n batch_size,\n valid_dir=\"./valid\",\n max_steps=10,\n beam_size=5,\n alpha=-1.0\n ):\n model.eval()\n\n numbers = []\n trans = []\n\n infer_progress_bar = tqdm(total=len(valid_iterator),\n desc=' - (Infer) ',\n unit=\"sents\")\n\n valid_iter = valid_iterator.build_generator(batch_size=batch_size)\n\n for batch in valid_iter:\n\n seq_nums = batch[0]\n numbers += seq_nums\n\n seqs_x = batch[1]\n\n infer_progress_bar.update(len(seqs_x))\n\n x = prepare_data(seqs_x, cuda=GlobalNames.USE_GPU)\n\n with torch.no_grad():\n word_ids = beam_search(nmt_model=model,\n beam_size=beam_size,\n max_steps=max_steps,\n src_seqs=x, alpha=alpha)\n\n word_ids = word_ids.cpu().numpy().tolist()\n\n # Append result\n for sent_t in word_ids:\n sent_t = [[wid for wid in line if wid != PAD] for line in sent_t]\n x_tokens = []\n\n for wid in sent_t[0]:\n if wid == EOS:\n break\n x_tokens.append(vocab_tgt.id2token(wid))\n\n if len(x_tokens) > 0:\n trans.append(vocab_tgt.tokenizer.detokenize(x_tokens))\n else:\n trans.append('%s' % vocab_tgt.id2token(EOS))\n\n origin_order = np.argsort(numbers).tolist()\n trans = [trans[ii] for ii in origin_order]\n\n infer_progress_bar.close()\n\n if not os.path.exists(valid_dir):\n os.mkdir(valid_dir)\n\n hyp_path = os.path.join(valid_dir, 'trans.iter{0}.txt'.format(uidx))\n\n with open(hyp_path, 'w') as f:\n for line in trans:\n f.write('%s\\n' % line)\n\n with open(hyp_path) as f:\n bleu_v = bleu_scorer.corpus_bleu(f)\n\n return bleu_v\n\n\ndef load_pretrained_model(nmt_model, pretrain_path, device, exclude_prefix=None):\n \"\"\"\n Args:\n nmt_model: model.\n pretrain_path ('str'): path to pretrained model.\n map_dict ('dict'): mapping specific parameter names to those names\n in current model.\n exclude_prefix ('dict'): excluding parameters with specific names\n for pretraining.\n\n Raises:\n ValueError: Size not match, parameter name not match or others.\n\n \"\"\"\n if exclude_prefix is None:\n exclude_prefix = []\n if pretrain_path != \"\":\n INFO(\"Loading pretrained model from {}\".format(pretrain_path))\n pretrain_params = torch.load(pretrain_path, map_location=device)\n for name, params in pretrain_params.items():\n flag = False\n for pp in exclude_prefix:\n if name.startswith(pp):\n flag = True\n break\n if flag:\n continue\n INFO(\"Loading param: {}...\".format(name))\n try:\n nmt_model.load_state_dict({name: params}, strict=False)\n except Exception as e:\n WARN(\"{}: {}\".format(str(Exception), e))\n\n INFO(\"Pretrained model loaded.\")\n\n\ndef train(FLAGS):\n \"\"\"\n FLAGS:\n saveto: str\n reload: store_true\n config_path: str\n pretrain_path: str, default=\"\"\n model_name: str\n log_path: str\n \"\"\"\n\n # write log of training to file.\n write_log_to_file(os.path.join(FLAGS.log_path, \"%s.log\" % time.strftime(\"%Y%m%d-%H%M%S\")))\n\n GlobalNames.USE_GPU = FLAGS.use_gpu\n\n if GlobalNames.USE_GPU:\n CURRENT_DEVICE = \"cpu\"\n else:\n CURRENT_DEVICE = \"cuda:0\"\n\n config_path = os.path.abspath(FLAGS.config_path)\n with open(config_path.strip()) as f:\n configs = yaml.load(f)\n\n INFO(pretty_configs(configs))\n\n # Add default configs\n configs = default_configs(configs)\n data_configs = configs['data_configs']\n model_configs = configs['model_configs']\n optimizer_configs = configs['optimizer_configs']\n training_configs = configs['training_configs']\n\n GlobalNames.SEED = training_configs['seed']\n\n set_seed(GlobalNames.SEED)\n\n best_model_prefix = os.path.join(FLAGS.saveto, FLAGS.model_name + GlobalNames.MY_BEST_MODEL_SUFFIX)\n\n timer = Timer()\n\n # ================================================================================== #\n # Load Data\n\n INFO('Loading data...')\n timer.tic()\n\n # Generate target dictionary\n vocab_src = Vocabulary(**data_configs[\"vocabularies\"][0])\n\n train_batch_size = training_configs[\"batch_size\"] * max(1, training_configs[\"update_cycle\"])\n train_buffer_size = training_configs[\"buffer_size\"] * max(1, training_configs[\"update_cycle\"])\n\n train_bitext_dataset = ZipDataset(\n TextLineDataset(data_path=data_configs['train_data'][0],\n vocabulary=vocab_src,\n max_len=data_configs['max_len'][0],\n ),\n shuffle=training_configs['shuffle']\n )\n\n valid_bitext_dataset = ZipDataset(\n TextLineDataset(data_path=data_configs['valid_data'][0],\n vocabulary=vocab_src,\n ),\n )\n\n training_iterator = DataIterator(dataset=train_bitext_dataset,\n batch_size=train_batch_size,\n use_bucket=training_configs['use_bucket'],\n buffer_size=train_buffer_size,\n batching_func=training_configs['batching_key'])\n\n valid_iterator = DataIterator(dataset=valid_bitext_dataset,\n batch_size=training_configs['valid_batch_size'],\n use_bucket=True, buffer_size=100000, numbering=True)\n\n\n INFO('Done. Elapsed time {0}'.format(timer.toc()))\n\n lrate = optimizer_configs['learning_rate']\n is_early_stop = False\n\n # ================================ Begin ======================================== #\n # Build Model & Optimizer\n # We would do steps below on after another\n # 1. build models & criterion\n # 2. move models & criterion to gpu if needed\n # 3. load pre-trained model if needed\n # 4. build optimizer\n # 5. build learning rate scheduler if needed\n # 6. load checkpoints if needed\n\n # 0. Initial\n model_collections = Collections()\n checkpoint_saver = Saver(save_prefix=\"{0}.ckpt\".format(os.path.join(FLAGS.saveto, FLAGS.model_name)),\n num_max_keeping=training_configs['num_kept_checkpoints']\n )\n\n best_model_saver = BestKSaver(save_prefix=\"{0}.best\".format(os.path.join(FLAGS.saveto, FLAGS.model_name)),\n num_max_keeping=training_configs[\"num_kept_best_checkpoints\"])\n\n # 1. Build Model & Criterion\n INFO('Building model...')\n timer.tic()\n nmt_model = build_model(n_words=vocab_src.max_n_words, **model_configs)\n INFO(nmt_model)\n\n params_total = sum([p.numel() for n, p in nmt_model.named_parameters()])\n params_with_embedding = sum([p.numel() for n, p in nmt_model.named_parameters() if n.find('embedding') == -1])\n INFO('Total parameters: {}'.format(params_total))\n INFO('Total parameters (excluding word embeddings): {}'.format(params_with_embedding))\n\n critic = NMTCriterion(label_smoothing=model_configs['label_smoothing'])\n\n INFO(critic)\n INFO('Done. Elapsed time {0}'.format(timer.toc()))\n\n # 2. Move to GPU\n if GlobalNames.USE_GPU:\n nmt_model = nmt_model.cuda()\n critic = critic.cuda()\n\n # 3. Load pretrained model if needed\n load_pretrained_model(nmt_model, FLAGS.pretrain_path, exclude_prefix=None, device=CURRENT_DEVICE)\n\n # 4. Build optimizer\n INFO('Building Optimizer...')\n optim = Optimizer(name=optimizer_configs['optimizer'],\n model=nmt_model,\n lr=lrate,\n grad_clip=optimizer_configs['grad_clip'],\n optim_args=optimizer_configs['optimizer_params']\n )\n # 5. Build scheduler for optimizer if needed\n if optimizer_configs['schedule_method'] is not None:\n\n if optimizer_configs['schedule_method'] == \"loss\":\n\n scheduler = ReduceOnPlateauScheduler(optimizer=optim,\n **optimizer_configs[\"scheduler_configs\"]\n )\n\n elif optimizer_configs['schedule_method'] == \"noam\":\n scheduler = NoamScheduler(optimizer=optim, **optimizer_configs['scheduler_configs'])\n elif optimizer_configs[\"schedule_method\"] == \"rsqrt\":\n scheduler = RsqrtScheduler(optimizer=optim, **optimizer_configs['scheduler_configs'])\n else:\n WARN(\"Unknown scheduler name {0}. Do not use lr_scheduling.\".format(optimizer_configs['schedule_method']))\n scheduler = None\n else:\n scheduler = None\n\n # 6. build moving average\n\n if training_configs['moving_average_method'] is not None:\n ma = MovingAverage(moving_average_method=training_configs['moving_average_method'],\n named_params=nmt_model.named_parameters(),\n alpha=training_configs['moving_average_alpha'])\n else:\n ma = None\n\n INFO('Done. Elapsed time {0}'.format(timer.toc()))\n\n # Reload from latest checkpoint\n if FLAGS.reload:\n checkpoint_saver.load_latest(model=nmt_model, optim=optim, lr_scheduler=scheduler,\n collections=model_collections, ma=ma)\n\n # ================================================================================== #\n # Prepare training\n\n eidx = model_collections.get_collection(\"eidx\", [0])[-1]\n uidx = model_collections.get_collection(\"uidx\", [0])[-1]\n bad_count = model_collections.get_collection(\"bad_count\", [0])[-1]\n oom_count = model_collections.get_collection(\"oom_count\", [0])[-1]\n\n summary_writer = SummaryWriter(log_dir=FLAGS.log_path)\n\n cum_samples = 0\n cum_words = 0\n valid_loss = best_valid_loss = float('inf') # Max Float\n saving_files = []\n\n # Timer for computing speed\n timer_for_speed = Timer()\n timer_for_speed.tic()\n\n INFO('Begin training...')\n\n while True:\n\n summary_writer.add_scalar(\"Epoch\", (eidx + 1), uidx)\n\n # Build iterator and progress bar\n training_iter = training_iterator.build_generator()\n training_progress_bar = tqdm(desc=' - (Epc {}, Upd {}) '.format(eidx, uidx),\n total=len(training_iterator),\n unit=\"sents\"\n )\n for batch in training_iter:\n\n uidx += 1\n\n if optimizer_configs[\"schedule_method\"] is not None and optimizer_configs[\"schedule_method\"] != \"loss\":\n scheduler.step(global_step=uidx)\n\n seqs_x = batch\n\n n_samples_t = len(seqs_x)\n n_words_t = sum(len(s) for s in seqs_x)\n\n cum_samples += n_samples_t\n cum_words += n_words_t\n\n train_loss = 0.\n optim.zero_grad()\n try:\n # Prepare data\n for seqs_x_t, in split_shard(seqs_x, split_size=training_configs['update_cycle']):\n x = prepare_data(seqs_x_t, cuda=GlobalNames.USE_GPU)\n\n loss = compute_forward(model=nmt_model,\n critic=critic,\n seqs_x=x,\n eval=False,\n normalization=n_samples_t,\n norm_by_words=training_configs[\"norm_by_words\"])\n train_loss += loss / x.size(1)\n optim.step()\n\n except RuntimeError as e:\n if 'out of memory' in str(e):\n print('| WARNING: ran out of memory, skipping batch')\n oom_count += 1\n optim.zero_grad()\n else:\n raise e\n\n if ma is not None and eidx >= training_configs['moving_average_start_epoch']:\n ma.step()\n\n training_progress_bar.update(n_samples_t)\n training_progress_bar.set_description(' - (Epc {}, Upd {}) '.format(eidx, uidx))\n training_progress_bar.set_postfix_str(\n 'TrainLoss: {:.2f}, ValidLoss(best): {:.2f} ({:.2f})'.format(train_loss, valid_loss, best_valid_loss))\n summary_writer.add_scalar(\"train_loss\", scalar_value=train_loss, global_step=uidx)\n\n # ================================================================================== #\n # Display some information\n if should_trigger_by_steps(uidx, eidx, every_n_step=training_configs['disp_freq']):\n # words per second and sents per second\n words_per_sec = cum_words / (timer.toc(return_seconds=True))\n sents_per_sec = cum_samples / (timer.toc(return_seconds=True))\n lrate = list(optim.get_lrate())[0]\n\n summary_writer.add_scalar(\"Speed(words/sec)\", scalar_value=words_per_sec, global_step=uidx)\n summary_writer.add_scalar(\"Speed(sents/sen)\", scalar_value=sents_per_sec, global_step=uidx)\n summary_writer.add_scalar(\"lrate\", scalar_value=lrate, global_step=uidx)\n summary_writer.add_scalar(\"oom_count\", scalar_value=oom_count, global_step=uidx)\n\n # Reset timer\n timer.tic()\n cum_words = 0\n cum_samples = 0\n\n # ================================================================================== #\n # Loss Validation & Learning rate annealing\n if should_trigger_by_steps(global_step=uidx, n_epoch=eidx, every_n_step=training_configs['loss_valid_freq'],\n debug=FLAGS.debug):\n\n if ma is not None:\n origin_state_dict = deepcopy(nmt_model.state_dict())\n nmt_model.load_state_dict(ma.export_ma_params(), strict=False)\n\n valid_loss = loss_validation(model=nmt_model,\n critic=critic,\n valid_iterator=valid_iterator,\n )\n\n model_collections.add_to_collection(\"history_losses\", valid_loss)\n\n min_history_loss = np.array(model_collections.get_collection(\"history_losses\")).min()\n\n summary_writer.add_scalar(\"loss\", valid_loss, global_step=uidx)\n summary_writer.add_scalar(\"best_loss\", min_history_loss, global_step=uidx)\n\n best_valid_loss = min_history_loss\n\n if ma is not None:\n nmt_model.load_state_dict(origin_state_dict)\n del origin_state_dict\n\n if optimizer_configs[\"schedule_method\"] == \"loss\":\n scheduler.step(global_step=uidx, metric=best_valid_loss)\n\n # If model get new best valid bleu score\n if valid_loss < best_valid_loss:\n bad_count = 0\n\n if is_early_stop is False:\n # 1. save the best model's parameters\n torch.save(nmt_model.state_dict(), best_model_prefix + \".final\")\n\n # 2. save the best checkpoint\n\n model_collections.add_to_collection(\"uidx\", uidx)\n model_collections.add_to_collection(\"eidx\", eidx)\n model_collections.add_to_collection(\"bad_count\", bad_count)\n\n best_model_saver.save(global_step=uidx, metric=valid_loss,\n model=nmt_model,\n optim=optim,\n lr_scheduler=scheduler,\n collections=model_collections,\n ma=ma)\n else:\n bad_count += 1\n\n # At least one epoch should be traversed\n if bad_count >= training_configs['early_stop_patience'] and eidx > 0:\n is_early_stop = True\n WARN(\"Early Stop!\")\n\n summary_writer.add_scalar(\"bad_count\", bad_count, uidx)\n\n INFO(\"{0} Loss: {1:.2f} lrate: {2:6f} patience: {3}\".format(\n uidx, valid_loss, lrate, bad_count\n ))\n\n # ================================================================================== #\n # Saving checkpoints\n if should_trigger_by_steps(uidx, eidx, every_n_step=training_configs['save_freq'], debug=FLAGS.debug):\n model_collections.add_to_collection(\"uidx\", uidx)\n model_collections.add_to_collection(\"eidx\", eidx)\n model_collections.add_to_collection(\"bad_count\", bad_count)\n\n if not is_early_stop:\n checkpoint_saver.save(global_step=uidx,\n model=nmt_model,\n optim=optim,\n lr_scheduler=scheduler,\n collections=model_collections,\n ma=ma)\n\n training_progress_bar.close()\n\n eidx += 1\n if eidx > training_configs[\"max_epochs\"]:\n break\n\n\ndef nmt_lm_fusion_translate(FLAGS):\n GlobalNames.USE_GPU = FLAGS.use_gpu\n\n config_path = os.path.abspath(FLAGS.config_path)\n\n with open(config_path.strip()) as f:\n configs = yaml.load(f)\n\n data_configs = configs['data_configs']\n nmt_model_configs = configs['nmt_model_configs']\n lm_model_configs = configs['lm_model_configs']\n\n timer = Timer()\n # ================================================================================== #\n # Load Data\n\n INFO('Loading data...')\n timer.tic()\n\n # Generate target dictionary\n vocab_src = Vocabulary(**data_configs[\"vocabularies\"][0])\n vocab_tgt = Vocabulary(**data_configs[\"vocabularies\"][1])\n\n valid_dataset = TextLineDataset(data_path=FLAGS.source_path,\n vocabulary=vocab_src)\n\n valid_iterator = DataIterator(dataset=valid_dataset,\n batch_size=FLAGS.batch_size,\n use_bucket=True, buffer_size=100000, numbering=True)\n\n INFO('Done. Elapsed time {0}'.format(timer.toc()))\n\n # ================================================================================== #\n # Build Model & Sampler & Validation\n INFO('Building model...')\n timer.tic()\n\n nmt_model_path = FLAGS.nmt_model_path\n lm_model_path = FLAGS.lm_model_path\n\n nmt_model = build_model(n_src_vocab=vocab_src.max_n_words,\n n_tgt_vocab=vocab_tgt.max_n_words, **nmt_model_configs)\n lm_model = build_model(n_words=vocab_tgt.max_n_words, **lm_model_configs)\n nmt_model.eval()\n lm_model.eval()\n\n INFO('Done. Elapsed time {0}'.format(timer.toc()))\n\n INFO('Reloading model parameters...')\n timer.tic()\n\n nmt_params = load_model_parameters(nmt_model_path, map_location=\"cpu\")\n lm_params = load_model_parameters(lm_model_path, map_location=\"cpu\")\n nmt_model.load_state_dict(nmt_params)\n lm_model.load_state_dict(lm_params)\n\n if GlobalNames.USE_GPU:\n nmt_model.cuda()\n lm_model.cuda()\n\n INFO('Done. Elapsed time {0}'.format(timer.toc()))\n\n INFO('Begin...')\n result_numbers = []\n result = []\n n_words = 0\n\n timer.tic()\n\n infer_progress_bar = tqdm(total=len(valid_iterator),\n desc=' - (Infer) ',\n unit=\"sents\")\n\n valid_iter = valid_iterator.build_generator()\n for batch in valid_iter:\n\n numbers, seqs_x = batch\n\n batch_size_t = len(seqs_x)\n\n x = prepare_data(seqs_x=seqs_x, cuda=GlobalNames.USE_GPU)\n\n with torch.no_grad():\n word_ids = nmt_lm_fusion_beam_search(nmt_model=nmt_model, lm_model=lm_model,\n beam_size=FLAGS.beam_size,\n max_steps=FLAGS.max_steps,\n src_seqs=x,\n alpha=FLAGS.alpha,\n beta=FLAGS.beta)\n\n word_ids = word_ids.cpu().numpy().tolist()\n result_numbers += numbers\n\n # Append result\n for sent_t in word_ids:\n sent_t = [[wid for wid in line if wid != PAD] for line in sent_t]\n result.append(sent_t)\n\n n_words += len(sent_t[0])\n\n infer_progress_bar.update(batch_size_t)\n\n infer_progress_bar.close()\n\n INFO('Done. Speed: {0:.2f} words/sec'.format(n_words / (timer.toc(return_seconds=True))))\n\n translation = []\n for sent in result:\n samples = []\n for trans in sent:\n sample = []\n for w in trans:\n if w == vocab_tgt.EOS:\n break\n sample.append(vocab_tgt.id2token(w))\n samples.append(vocab_tgt.tokenizer.detokenize(sample))\n translation.append(samples)\n # resume the ordering\n origin_order = np.argsort(result_numbers).tolist()\n translation = [translation[ii] for ii in origin_order]\n with open(FLAGS.saveto, 'w') as f:\n for trans in translation:\n f.write(\"%s\\n\"%trans[0])\n\n\nif __name__ == '__main__':\n _args = {\n \"model_name\": \"test_rnnlm\",\n \"reload\": False,\n \"config_path\": \"./configs/test_rnnlm.yaml\",\n \"debug\": True,\n \"use_gpu\": False,\n \"task\": \"lm\",\n \"log_path\": \"/tmp\",\n \"saveto\": \"/tmp\",\n \"valid_path\": \"/tmp\",\n }\n\n from src.bin import train as _train\n\n _train.run(**_args)"
] |
[
[
"torch.enable_grad",
"numpy.random.seed",
"torch.load",
"torch.autograd.backward",
"torch.manual_seed",
"numpy.isnan",
"numpy.transpose",
"numpy.full",
"torch.tensor",
"torch.no_grad",
"torch.cuda.manual_seed_all",
"torch.cuda.is_available",
"numpy.argsort"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
krishnaaxo/Finance-Forcasting-Dashboard
|
[
"6386247b7e661fb0804b80d4c77dd5dcd94a7e87"
] |
[
"app.py"
] |
[
"\n\nimport pandas as pd\nimport tweepy\nfrom textblob import TextBlob\nfrom wordcloud import WordCloud\nimport plotly.graph_objs as go\nimport os\nimport re\nimport pystan\nimport numpy as np\nimport streamlit as st\nimport matplotlib.pyplot as plt\nimport yfinance as yf\nfrom fbprophet import Prophet\nfrom fbprophet.plot import plot_plotly\nfrom GoogleNews import GoogleNews\nfrom ta.volatility import BollingerBands\nfrom ta.trend import MACD\nfrom ta.momentum import RSIIndicator\nimport datetime as datetime\nimport base64\nimport pandas as pd\nimport plotly.express as px\nimport datetime\nimport requests\nfrom bs4 import BeautifulSoup\n\nfrom datetime import date\nfrom plotly import graph_objs\n\n\n\n\n\n\n\n\nst.set_page_config( \nlayout=\"wide\", \ninitial_sidebar_state=\"auto\",\npage_title= \"Finance-Forcasting-Dashboard\", \npage_icon= \"Images/growth.png\", \n)\n\n\n\n \n\ncol1, col2, col3 = st.beta_columns([1,2,1])\ncol1.write(\"\")\ncol2.image(\"Images/LL.png\", width = 500)\ncol3.write(\"\")\n\n\n\nst.set_option('deprecation.showPyplotGlobalUse', False)\n\nmain_bg = \"Images/BACK.png\"\nmain_bg_ext = \"Images/BACK.png\"\n\n\nst.markdown(\n f\"\"\"\n <style>\n .reportview-container {{\n background: url(data:image/{main_bg_ext};base64,{base64.b64encode(open(main_bg, \"rb\").read()).decode()})\n }}\n </style>\n \"\"\",\n unsafe_allow_html=True\n)\n###############################Funtions############################\n\n# load data from yahoo finance\ndef load_data(ticker):\n start = \"2020-01-01\"\n today = date.today().strftime(\"%Y-%m-%d\")\n data = yf.download(ticker, start, today)\n data.reset_index(inplace=True)\n return data\n\n# Plot raw data\ndef plot_raw_data():\n fig = graph_objs.Figure()\n fig.add_trace(graph_objs.Scatter(x=data['Date'], y=data['Open'], name=\"stock_open\"))\n fig.add_trace(graph_objs.Scatter(x=data['Date'], y=data['Close'], name=\"stock_close\"))\n fig.layout.update(title_text='Time Series data with Rangeslider', xaxis_rangeslider_visible=True)\n st.plotly_chart(fig)\n\ndef get_forecast(data):\n model = Prophet()\n model.fit(data)\n future = model.make_future_dataframe(periods=7)\n forecast = model.predict(future)\n \n return model, forecast\n\[email protected]\ndef read_data():\n url = \"https://raw.githubusercontent.com/emrecanaltinsoy/forex_data/main/forex_usd_data.csv\"\n data = pd.read_csv(url)\n cols = data.columns\n return data, cols[1:]\n\n\[email protected]\ndef get_range(data, date_range):\n start_index = data.index[data[\"date(y-m-d)\"] == str(date_range[0])].tolist()[0]\n end_index = data.index[data[\"date(y-m-d)\"] == str(date_range[1])].tolist()[0]\n data = data.iloc[start_index : end_index + 1]\n cols = data.columns\n dates = data[\"date(y-m-d)\"]\n return data, dates\n\n\[email protected]\ndef scrape_currency():\n today = datetime.date.today()\n\n base_url = \"https://www.x-rates.com/historical/?from=USD&amount=1&date\"\n\n year = today.year\n month = today.month if today.month > 9 else f\"0{today.month}\"\n day = today.day if today.day > 9 else f\"0{today.day}\"\n\n URL = f\"{base_url}={year}-{month}-{day}\"\n\n page = requests.get(URL)\n\n soup = BeautifulSoup(page.content, \"html.parser\")\n\n table = soup.find_all(\"tr\")[12:]\n\n currencies = [table[i].text.split(\"\\n\")[1:3][0] for i in range(len(table))]\n currencies.insert(0, \"date(y-m-d)\")\n currencies.insert(1, \"American Dollar\")\n rates = [table[i].text.split(\"\\n\")[1:3][1] for i in range(len(table))]\n rates.insert(0, f\"{year}-{month}-{day}\")\n rates.insert(1, \"1\")\n curr_data = {currencies[i]: rates[i] for i in range(len(rates))}\n curr_data = pd.DataFrame(curr_data, index=[0])\n\n cols = curr_data.columns\n\n return curr_data, cols[1:]\n\n\[email protected]\ndef train_model(data, currency, period):\n df_train = data[[\"date(y-m-d)\", currency]]\n df_train = df_train.iloc[-365*2 :]\n df_train = df_train.rename(columns={\"date(y-m-d)\": \"ds\", currency: \"y\"})\n\n m = Prophet()\n m.fit(df_train)\n future = m.make_future_dataframe(periods=period)\n forecast = m.predict(future)\n\n return forecast, m\n\ndf_all, columns = read_data()\n\n################################################################################\n\n\n\nst.sidebar.image(\"Images/Menu.png\", width = 330)\n\n\nmenu = [\"Home\",\"STOCKS Live Forcasting\", \"Crypto-Live Forcasting\",\"View Historical Currency Charts\", \"Check Live Currency Exchange rates\", \"Forecast Currency Live Prices\"]\n\nchoice = st.sidebar.selectbox(\"Menu\", menu)\nif choice == \"Home\":\n \n st.write(\"\")\n\n st.write(\"\"\" <p style=\" font-size: 15px; font-weight:normal; font-family:verdana\"> Finance Dashboard is a special web service that allows you to view Cryptocurrencies,Stocks,and Live Currency Values by many useful methods (technical indicators, graphical patterns, sentimental analysis, and more). Trading and crypto investing requires constant analysis and monitoring. Traders need to track all their trades in order to improve results and find errors. If you don't use additional instruments, then trading will be unsystematic, and the results will be uncertain. Such a service will be useful and even extremely necessary for those who trade and invest in cryptocurrencies and Stocks. Competent selection of cryptocurrencies is at least half of investment success. Finance Dashboard has a simple interface and is great for quick analysis of the Stock market. </p>\n \"\"\", unsafe_allow_html=True)\n \n st.write(\"\")\n st.write(\"\")\n st.write(\"\")\n st.write(\"\") \n st.write(\"\")\n\n\n st.write(\"\"\" <p style=\" color:#E75480; font-size: 30px; font-weight:bold\"> How does it work? </p>\n \"\"\", unsafe_allow_html=True)\n\n st.write(\"\")\n\n\n\n\n st.image(\"Images/How.png\", width = 1300)\n\n st.sidebar.write(\" \")\n st.sidebar.write(\" \")\n \n st.sidebar.image(\"Images/info.png\", width = 300)\n\n\nelif choice == \"STOCKS Live Forcasting\":\n st.title('Stocks Weekly Forecast')\n st.subheader('Enter the stock ticker:')\n ticker = st.text_input('example: GOOG')\n ticket = ticker.upper()\n if len(ticker)>0:\n data_load_state = st.text('Loading data...')\n data = load_data(ticker)\n if data.empty:\n data_load_state.text(f'No ticker named {ticker}')\n ticker = ''\n else:\n data_load_state.text('Loading data... done!')\n\n st.subheader(f'Company: {yf.Ticker(ticker).info[\"longName\"]}')\n st.write(data.head())\n\n plot_raw_data()\n\n # prepare data for forecasting\n df_train = data[['Date','Close']]\n df_train = df_train.rename(columns={\"Date\": \"ds\", \"Close\": \"y\"})\n\n # train and forecast\n model, forecast = get_forecast(df_train)\n\n st.subheader('Forecast')\n \n # plot forecast\n st.write(f'Forecast plot for the next week')\n fig = plot_plotly(model, forecast)\n st.plotly_chart(fig)\n\n\n\n\n\n\n\n\n\n\n\n\n\nelif choice == \"View Historical Currency Charts\":\n st.write(\"This app can be used to view historical **currency** charts!\")\n\n date_range = st.date_input(\n \"Choose date range\",\n value=(\n datetime.date(2011, 1, 1),\n datetime.date(2011, 1, 1) + datetime.timedelta(df_all.shape[0] - 1),\n ),\n min_value=datetime.date(2011, 1, 1),\n max_value=datetime.date(2011, 1, 1) + datetime.timedelta(df_all.shape[0] - 1),\n )\n\n df, dates = get_range(df_all, date_range)\n\n selected_curr = st.multiselect(\"Select currencies\", columns)\n\n ok = st.button(\"View\")\n if ok:\n if selected_curr:\n # st.write(df[selected_curr])\n\n for curr in selected_curr:\n fig = px.line(\n x=dates,\n y=df[curr],\n )\n fig.update_layout(\n xaxis_title=\"Date\",\n yaxis_title=curr,\n )\n st.write(fig)\n\nelif choice == \"Check Live Currency Exchange rates\":\n st.write(\"This app can be used to check current **currency** data!\")\n daily_df, columns = scrape_currency()\n base_curr = st.selectbox(\"Select the base currency\", columns)\n selected_curr = st.multiselect(\"Select currencies\", columns)\n if selected_curr:\n base = daily_df[base_curr].astype(float)\n\n selected = daily_df[selected_curr].astype(float)\n\n converted = selected / float(base)\n st.write(converted)\n\nelif choice == \"Forecast Currency Live Prices\":\n currency = st.selectbox(\"Select the currency for prediction\", columns)\n\n n_weeks = st.slider(\"Weeks of prediction\", 4, 20, 8, 1)\n\n ok = st.button(\"Predict\")\n if ok:\n train_state = st.text(\"Training the model...\")\n pred, model = train_model(df_all, currency, period=n_weeks * 7)\n train_state.text(\"Model training completed!!\")\n\n st.subheader(\"Forecast data\")\n fig1 = plot_plotly(model, pred)\n st.plotly_chart(fig1)\n\n\n\n\n\nelif choice == \"Crypto-Live Forcasting\":\n st.sidebar.header(\"Please select cryptocurrency\")\n option = st.sidebar.selectbox(\"Ticker Symbol\",(\"BTC-USD\", \"ETH-USD\", \"XRP-USD\", \"DOGE-USD\", \"ADA-USD\", \"BNB-USD\", \"LTC-USD\",))\n today = datetime.date.today()\n before = today - datetime.timedelta(days=1400)\n start_date = st.sidebar.date_input('Start date', before)\n end_date = st.sidebar.date_input('End date', today)\n if start_date < end_date:\n st.sidebar.success(\"Start date: `%s`\\n\\nEnd date: `%s` \" % (start_date, end_date))\n else:\n st.sidebar.error(\"Error: End date must fall after start date.\")\n\n @st.cache(allow_output_mutation = True) \n def get_data(option, start_date, end_date):\n df = yf.download(option,start= start_date,end = end_date, progress=False)\n return df\n \n # Getting API_KEYS\n api_key = os.environ.get(\"Key\")\n api_secret = os.environ.get(\"Secret\")\n\n # Function for getting tweets\n # Create authentication\n @st.cache(allow_output_mutation = True) \n def get_tweets(key, secret, search_term):\n authentication = tweepy.OAuthHandler(api_key, api_secret)\n api = tweepy.API(authentication)\n term = search_term+\"-filter:retweets\"\n # Create a cursor object \n tweets = tweepy.Cursor(api.search, q = term, lang = \"en\",\n since = today, tweet_mode = \"extended\").items(100)\n # Store the tweets\n tweets_text = [tweet.full_text for tweet in tweets]\n df = pd.DataFrame(tweets_text, columns = [\"Tweets\"]) \n return df\n\n # Clean text\n @st.cache(allow_output_mutation = True) \n def Clean(twt):\n twt = re.sub(\"#cryptocurrency\", \"cryptocurrency\", twt)\n twt = re.sub(\"#Cryptocurrency\", \"Cryptocurrency\", twt)\n twt = re.sub(\"#[A-Za-z0-9]+\", \"\", twt)\n twt = re.sub(\"RT[\\s]+\", \"\", twt)\n twt = re.sub(\"\\\\n\", \"\", twt)\n twt = re.sub(\"https?\\://\\S+\", '', twt)\n twt = re.sub(\"<br />\", \"\", twt)\n twt = re.sub(\"\\d\",\"\", twt)\n twt = re.sub(\"it\\'s\", \"it is\", twt)\n twt = re.sub(\"can\\'t\", \"cannot\", twt)\n twt = re.sub(\"<(?:a\\b[^>]*>|/a>)\", \"\", twt)\n return twt\n\n # Subjectivity and Polarity\n @st.cache(allow_output_mutation = True)\n def subjectivity(text):\n return TextBlob(text).sentiment.subjectivity\n @st.cache(allow_output_mutation = True)\n def polarity(text):\n return TextBlob(text).sentiment.polarity\n\n\n # Create a function to get sentiment text\n @st.cache(allow_output_mutation = True)\n def sentiment(score):\n if score < 0:\n return \"Negative\"\n elif score == 0:\n return \"Neutral\"\n else:\n return \"Positive\" \n\n if option == \"BTC-USD\":\n df = get_data(option, start_date, end_date)\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Raw Data </p>\n \"\"\", unsafe_allow_html=True)\n\n st.write(\" \")\n st.write(df)\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Close Price </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n st.line_chart(df[\"Close\"])\n\n st.write(\" \")\n\n\n # MACD\n\n st.write(\" \")\n macd = MACD(df[\"Close\"]).macd()\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Moving Average Convergence Divergence </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n\n st.area_chart(macd)\n\n\n # Bollinger Bands\n bb_bands = BollingerBands(df[\"Close\"])\n bb = df\n bb[\"bb_h\"] = bb_bands.bollinger_hband()\n bb[\"bb_l\"] = bb_bands.bollinger_lband()\n bb = bb[[\"Close\",\"bb_h\",\"bb_l\"]]\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Bollinger Bands </p>\n \"\"\", unsafe_allow_html=True)\n st.line_chart(bb)\n\n\n st.write(\" \")\n\n\n # Resistence Strength Indicator\n \n rsi = RSIIndicator(df[\"Close\"]).rsi()\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Resistence Strength Indicator </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n st.line_chart(rsi)\n\n st.write(\" \")\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> BTC-USD Forecast using Facebook Prophet </p>\n \"\"\", unsafe_allow_html=True) \n \n st.write(\" \")\n\n\n\n data = df.reset_index()\n period = st.slider(\"Days of prediction:\", 1, 365)\n \n # Predict forecast with Prophet.\n df_train = data[[\"Date\",\"Close\"]]\n df_train = df_train.rename(columns={\"Date\": \"ds\", \"Close\": \"y\"})\n\n m = Prophet()\n m.fit(df_train)\n future = m.make_future_dataframe(periods=period)\n forecast = m.predict(future)\n \n #Plot\n st.write(f'Forecast plot for {period} days')\n fig1 = plot_plotly(m, forecast)\n st.plotly_chart(fig1)\n\n \n\n st.write(\" \")\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Latest News </p>\n \"\"\", unsafe_allow_html=True)\n\n st.write(\" \") \n\n news = GoogleNews()\n news = GoogleNews(\"en\", \"d\")\n news.search(\"Bitcoin\")\n news.get_page(1)\n result = news.result()\n st.write(\"1. \" + result[1][\"title\"])\n st.info(\"1. \" + result[1][\"link\"])\n st.write(\"2. \" + result[2][\"title\"])\n st.info(\"2. \" + result[2][\"link\"])\n st.write(\"3. \" + result[3][\"title\"])\n st.info(\"3. \" + result[3][\"link\"])\n st.write(\"4. \" + result[4][\"title\"])\n st.info(\"4. \" + result[4][\"link\"])\n st.write(\"5. \" + result[5][\"title\"])\n st.info(\"5. \" + result[5][\"link\"])\n\n \n\n\n \n\n\n \n\n\n\n elif option == \"ETH-USD\":\n df = get_data(option, start_date, end_date)\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Raw Data </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n\n st.write(df)\n\n st.write(\" \")\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Close Price </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n st.line_chart(df[\"Close\"])\n\n st.write(\" \")\n\n # MACD\n\n st.write(\" \")\n macd = MACD(df[\"Close\"]).macd()\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Moving Average Convergence Divergence </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n\n st.area_chart(macd)\n\n\n # Bollinger Bands\n bb_bands = BollingerBands(df[\"Close\"])\n bb = df\n bb[\"bb_h\"] = bb_bands.bollinger_hband()\n bb[\"bb_l\"] = bb_bands.bollinger_lband()\n bb = bb[[\"Close\",\"bb_h\",\"bb_l\"]]\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Bollinger Bands </p>\n \"\"\", unsafe_allow_html=True)\n st.line_chart(bb)\n\n\n st.write(\" \")\n\n\n # Resistence Strength Indicator\n \n rsi = RSIIndicator(df[\"Close\"]).rsi()\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Resistence Strength Indicator </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n st.line_chart(rsi)\n\n\n st.write(\" \")\n\n \n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> ETH-USD Forecast using Facebook Prophet </p>\n \"\"\", unsafe_allow_html=True)\n\n st.write(\" \") \n\n data = df.reset_index()\n period = st.slider(\"Days of prediction:\", 1, 365)\n \n # Predict forecast with Prophet.\n df_train = data[[\"Date\",\"Close\"]]\n df_train = df_train.rename(columns={\"Date\": \"ds\", \"Close\": \"y\"})\n\n m = Prophet()\n m.fit(df_train)\n future = m.make_future_dataframe(periods=period)\n forecast = m.predict(future)\n \n st.write(f'Forecast plot for {period} days')\n fig1 = plot_plotly(m, forecast)\n st.plotly_chart(fig1)\n\n\n\n st.write(\" \")\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Latest News </p>\n \"\"\", unsafe_allow_html=True)\n\n st.write(\" \") \n\n news = GoogleNews()\n news = GoogleNews(\"en\", \"d\")\n news.search(\"Etherium\")\n news.get_page(1)\n result = news.result()\n st.write(\"1. \" + result[1][\"title\"])\n st.info(\"1. \" + result[1][\"link\"])\n st.write(\"2. \" + result[2][\"title\"])\n st.info(\"2. \" + result[2][\"link\"])\n st.write(\"3. \" + result[3][\"title\"])\n st.info(\"3. \" + result[3][\"link\"])\n st.write(\"4. \" + result[4][\"title\"])\n st.info(\"4. \" + result[4][\"link\"])\n st.write(\"5. \" + result[5][\"title\"])\n st.info(\"5. \" + result[5][\"link\"])\n\n \n \n \n \n\n elif option == \"DOGE-USD\":\n df = get_data(option, start_date, end_date)\n \n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Raw Data </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n\n st.write(df)\n\n st.write(\" \")\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Close Price </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n st.line_chart(df[\"Close\"])\n\n st.write(\" \")\n\n # MACD\n\n st.write(\" \")\n macd = MACD(df[\"Close\"]).macd()\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Moving Average Convergence Divergence </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n\n st.area_chart(macd)\n\n\n # Bollinger Bands\n bb_bands = BollingerBands(df[\"Close\"])\n bb = df\n bb[\"bb_h\"] = bb_bands.bollinger_hband()\n bb[\"bb_l\"] = bb_bands.bollinger_lband()\n bb = bb[[\"Close\",\"bb_h\",\"bb_l\"]]\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Bollinger Bands </p>\n \"\"\", unsafe_allow_html=True)\n st.line_chart(bb)\n\n\n st.write(\" \")\n\n\n # Resistence Strength Indicator\n \n rsi = RSIIndicator(df[\"Close\"]).rsi()\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Resistence Strength Indicator </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n st.line_chart(rsi)\n\n st.write(\" \")\n\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> DOGE-USD Forecast using Facebook Prophet </p>\n \"\"\", unsafe_allow_html=True) \n \n st.write(\" \")\n\n data = df.reset_index()\n period = st.slider(\"Days of prediction:\", 1, 365)\n \n # Predict forecast with Prophet.\n df_train = data[[\"Date\",\"Close\"]]\n df_train = df_train.rename(columns={\"Date\": \"ds\", \"Close\": \"y\"})\n\n m = Prophet()\n m.fit(df_train)\n future = m.make_future_dataframe(periods=period)\n forecast = m.predict(future)\n \n st.write(f'Forecast plot for {period} days')\n fig1 = plot_plotly(m, forecast)\n st.plotly_chart(fig1)\n\n\n\n st.write(\" \")\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Latest News </p>\n \"\"\", unsafe_allow_html=True)\n\n st.write(\" \") \n\n news = GoogleNews()\n news = GoogleNews(\"en\", \"d\")\n news.search(\"Dogecoin\")\n news.get_page(1)\n result = news.result()\n st.write(\"1. \" + result[1][\"title\"])\n st.info(\"1. \" + result[1][\"link\"])\n st.write(\"2. \" + result[2][\"title\"])\n st.info(\"2. \" + result[2][\"link\"])\n st.write(\"3. \" + result[3][\"title\"])\n st.info(\"3. \" + result[3][\"link\"])\n st.write(\"4. \" + result[4][\"title\"])\n st.info(\"4. \" + result[4][\"link\"])\n st.write(\"5. \" + result[5][\"title\"])\n st.info(\"5. \" + result[5][\"link\"])\n\n st.write(\" \")\n\n \n\n\n elif option == \"XRP-USD\":\n df = get_data(option, start_date, end_date)\n \n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Raw Data </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n\n st.write(df)\n\n st.write(\" \")\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Close Price </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n st.line_chart(df[\"Close\"])\n\n st.write(\" \")\n\n # MACD\n\n st.write(\" \")\n macd = MACD(df[\"Close\"]).macd()\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Moving Average Convergence Divergence </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n\n st.area_chart(macd)\n\n\n # Bollinger Bands\n bb_bands = BollingerBands(df[\"Close\"])\n bb = df\n bb[\"bb_h\"] = bb_bands.bollinger_hband()\n bb[\"bb_l\"] = bb_bands.bollinger_lband()\n bb = bb[[\"Close\",\"bb_h\",\"bb_l\"]]\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Bollinger Bands </p>\n \"\"\", unsafe_allow_html=True)\n st.line_chart(bb)\n\n\n st.write(\" \")\n\n\n # Resistence Strength Indicator\n \n rsi = RSIIndicator(df[\"Close\"]).rsi()\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Resistence Strength Indicator </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n st.line_chart(rsi)\n\n\n st.write(\" \")\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> DOGE-USD Forecast using Facebook Prophet </p>\n \"\"\", unsafe_allow_html=True) \n \n st.write(\" \")\n\n data = df.reset_index()\n period = st.slider(\"Days of prediction:\", 1, 365)\n \n # Predict forecast with Prophet.\n df_train = data[[\"Date\",\"Close\"]]\n df_train = df_train.rename(columns={\"Date\": \"ds\", \"Close\": \"y\"})\n\n m = Prophet()\n m.fit(df_train)\n future = m.make_future_dataframe(periods=period)\n forecast = m.predict(future)\n \n st.write(f'Forecast plot for {period} days')\n fig1 = plot_plotly(m, forecast)\n st.plotly_chart(fig1)\n\n\n\n st.write(\" \")\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Latest News </p>\n \"\"\", unsafe_allow_html=True)\n\n st.write(\" \") \n\n news = GoogleNews()\n news = GoogleNews(\"en\", \"d\")\n news.search(\"XRP\")\n news.get_page(1)\n result = news.result()\n st.write(\"1. \" + result[1][\"title\"])\n st.info(\"1. \" + result[1][\"link\"])\n st.write(\"2. \" + result[2][\"title\"])\n st.info(\"2. \" + result[2][\"link\"])\n st.write(\"3. \" + result[3][\"title\"])\n st.info(\"3. \" + result[3][\"link\"])\n st.write(\"4. \" + result[4][\"title\"])\n st.info(\"4. \" + result[4][\"link\"])\n st.write(\"5. \" + result[5][\"title\"])\n st.info(\"5. \" + result[5][\"link\"])\n\n \n\n\n elif option == \"ADA-USD\":\n df = get_data(option, start_date, end_date)\n \n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Raw Data </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n\n st.write(df)\n\n st.write(\" \")\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Close Price </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n st.line_chart(df[\"Close\"])\n\n st.write(\" \")\n\n # MACD\n\n st.write(\" \")\n macd = MACD(df[\"Close\"]).macd()\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Moving Average Convergence Divergence </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n\n st.area_chart(macd)\n\n\n # Bollinger Bands\n bb_bands = BollingerBands(df[\"Close\"])\n bb = df\n bb[\"bb_h\"] = bb_bands.bollinger_hband()\n bb[\"bb_l\"] = bb_bands.bollinger_lband()\n bb = bb[[\"Close\",\"bb_h\",\"bb_l\"]]\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Bollinger Bands </p>\n \"\"\", unsafe_allow_html=True)\n st.line_chart(bb)\n\n\n st.write(\" \")\n\n\n # Resistence Strength Indicator\n \n rsi = RSIIndicator(df[\"Close\"]).rsi()\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Resistence Strength Indicator </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n st.line_chart(rsi)\n\n\n st.write(\" \")\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> ADA-USD Forecast using Facebook Prophet </p>\n \"\"\", unsafe_allow_html=True) \n \n st.write(\" \")\n\n data = df.reset_index()\n period = st.slider(\"Days of prediction:\", 1, 365)\n \n # Predict forecast with Prophet.\n df_train = data[[\"Date\",\"Close\"]]\n df_train = df_train.rename(columns={\"Date\": \"ds\", \"Close\": \"y\"})\n\n m = Prophet()\n m.fit(df_train)\n future = m.make_future_dataframe(periods=period)\n forecast = m.predict(future)\n \n st.write(f'Forecast plot for {period} days')\n fig1 = plot_plotly(m, forecast)\n st.plotly_chart(fig1)\n\n\n\n st.write(\" \")\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Latest News </p>\n \"\"\", unsafe_allow_html=True)\n\n st.write(\" \") \n\n news = GoogleNews()\n news = GoogleNews(\"en\", \"d\")\n news.search(\"cryptocurrency\")\n news.get_page(1)\n result = news.result()\n st.write(\"1. \" + result[1][\"title\"])\n st.info(\"1. \" + result[1][\"link\"])\n st.write(\"2. \" + result[2][\"title\"])\n st.info(\"2. \" + result[2][\"link\"])\n st.write(\"3. \" + result[3][\"title\"])\n st.info(\"3. \" + result[3][\"link\"])\n st.write(\"4. \" + result[4][\"title\"])\n st.info(\"4. \" + result[4][\"link\"])\n st.write(\"5. \" + result[5][\"title\"])\n st.info(\"5. \" + result[5][\"link\"])\n\n \n\n\n elif option == \"BNB-USD\":\n df = get_data(option, start_date, end_date)\n \n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Raw Data </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n\n st.write(df)\n\n st.write(\" \")\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Close Price </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n st.line_chart(df[\"Close\"])\n\n st.write(\" \")\n\n # MACD\n\n st.write(\" \")\n macd = MACD(df[\"Close\"]).macd()\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Moving Average Convergence Divergence </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n\n st.area_chart(macd)\n\n\n # Bollinger Bands\n bb_bands = BollingerBands(df[\"Close\"])\n bb = df\n bb[\"bb_h\"] = bb_bands.bollinger_hband()\n bb[\"bb_l\"] = bb_bands.bollinger_lband()\n bb = bb[[\"Close\",\"bb_h\",\"bb_l\"]]\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Bollinger Bands </p>\n \"\"\", unsafe_allow_html=True)\n st.line_chart(bb)\n\n\n st.write(\" \")\n\n\n # Resistence Strength Indicator\n \n rsi = RSIIndicator(df[\"Close\"]).rsi()\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Resistence Strength Indicator </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n st.line_chart(rsi)\n\n\n st.write(\" \")\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> BNB-USD Forecast using Facebook Prophet </p>\n \"\"\", unsafe_allow_html=True) \n \n st.write(\" \")\n\n data = df.reset_index()\n period = st.slider(\"Days of prediction:\", 1, 365)\n \n # Predict forecast with Prophet.\n df_train = data[[\"Date\",\"Close\"]]\n df_train = df_train.rename(columns={\"Date\": \"ds\", \"Close\": \"y\"})\n\n m = Prophet()\n m.fit(df_train)\n future = m.make_future_dataframe(periods=period)\n forecast = m.predict(future)\n \n st.write(f'Forecast plot for {period} days')\n fig1 = plot_plotly(m, forecast)\n st.plotly_chart(fig1)\n\n\n\n st.write(\" \")\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Latest News </p>\n \"\"\", unsafe_allow_html=True)\n\n st.write(\" \") \n\n news = GoogleNews()\n news = GoogleNews(\"en\", \"d\")\n news.search(\"BNB\")\n news.get_page(1)\n result = news.result()\n st.write(\"1. \" + result[1][\"title\"])\n st.info(\"1. \" + result[1][\"link\"])\n st.write(\"2. \" + result[2][\"title\"])\n st.info(\"2. \" + result[2][\"link\"])\n st.write(\"3. \" + result[3][\"title\"])\n st.info(\"3. \" + result[3][\"link\"])\n st.write(\"4. \" + result[4][\"title\"])\n st.info(\"4. \" + result[4][\"link\"])\n st.write(\"5. \" + result[5][\"title\"])\n st.info(\"5. \" + result[5][\"link\"])\n\n \n\n\n elif option == \"LTC-USD\":\n df = get_data(option, start_date, end_date)\n \n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Raw Data </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n\n st.write(df)\n\n st.write(\" \")\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Close Price </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n st.line_chart(df[\"Close\"])\n\n st.write(\" \")\n\n # MACD\n\n st.write(\" \")\n macd = MACD(df[\"Close\"]).macd()\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Moving Average Convergence Divergence </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n\n st.area_chart(macd)\n\n\n # Bollinger Bands\n bb_bands = BollingerBands(df[\"Close\"])\n bb = df\n bb[\"bb_h\"] = bb_bands.bollinger_hband()\n bb[\"bb_l\"] = bb_bands.bollinger_lband()\n bb = bb[[\"Close\",\"bb_h\",\"bb_l\"]]\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Bollinger Bands </p>\n \"\"\", unsafe_allow_html=True)\n st.line_chart(bb)\n\n\n st.write(\" \")\n\n\n # Resistence Strength Indicator\n \n rsi = RSIIndicator(df[\"Close\"]).rsi()\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Resistence Strength Indicator </p>\n \"\"\", unsafe_allow_html=True)\n st.write(\" \")\n st.line_chart(rsi)\n\n\n st.write(\" \")\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> LTC-USD Forecast using Facebook Prophet </p>\n \"\"\", unsafe_allow_html=True) \n \n st.write(\" \")\n\n data = df.reset_index()\n period = st.slider(\"Days of prediction:\", 1, 365)\n \n # Predict forecast with Prophet.\n df_train = data[[\"Date\",\"Close\"]]\n df_train = df_train.rename(columns={\"Date\": \"ds\", \"Close\": \"y\"})\n\n m = Prophet()\n m.fit(df_train)\n future = m.make_future_dataframe(periods=period)\n forecast = m.predict(future)\n \n st.write(f'Forecast plot for {period} days')\n fig1 = plot_plotly(m, forecast)\n st.plotly_chart(fig1)\n\n\n\n st.write(\" \")\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Latest News </p>\n \"\"\", unsafe_allow_html=True)\n\n st.write(\" \") \n\n news = GoogleNews()\n news = GoogleNews(\"en\", \"d\")\n news.search(\"Litecoin\")\n news.get_page(1)\n result = news.result()\n st.write(\"1. \" + result[1][\"title\"])\n st.info(\"1. \" + result[1][\"link\"])\n st.write(\"2. \" + result[2][\"title\"])\n st.info(\"2. \" + result[2][\"link\"])\n st.write(\"3. \" + result[3][\"title\"])\n st.info(\"3. \" + result[3][\"link\"])\n st.write(\"4. \" + result[4][\"title\"])\n st.info(\"4. \" + result[4][\"link\"])\n st.write(\"5. \" + result[5][\"title\"])\n st.info(\"5. \" + result[5][\"link\"])\n\n\n # Sentiment Analysis\n\n st.write(\" \")\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> How generally users feel about cryptocurrency? </p>\n \"\"\", unsafe_allow_html=True) \n \n st.write(\" \")\n\n\n df = get_tweets(api_key, api_secret, \"#cryptocurrency\")\n df[\"Tweets\"] = df[\"Tweets\"].apply(Clean)\n df[\"Subjectivity\"] = df[\"Tweets\"].apply(subjectivity)\n df[\"Polarity\"] = df[\"Tweets\"].apply(polarity)\n\n #WordCloud\n words = \" \".join([twts for twts in df[\"Tweets\"]])\n cloud = WordCloud(random_state = 21, max_font_size = 100).generate(words)\n plt.imshow(cloud, interpolation = \"bilinear\")\n plt.axis(\"off\")\n st.pyplot()\n\n \n st.write(\" \")\n\n st.write(\"\"\" <p style=\" color:#FFCC00; font-size: 30px; font-weight:bold\"> Sentiment Bar Plot </p>\n \"\"\", unsafe_allow_html=True)\n\n st.write(\" \") \n\n # Get Sentiment tweets\n df[\"Sentiment\"] = df[\"Polarity\"].apply(sentiment)\n df[\"Sentiment\"].value_counts().plot(kind = \"bar\", figsize = (10,5))\n plt.title(\"Sentiment Analysis Bar Plot\")\n plt.xlabel(\"Sentiment\")\n plt.ylabel(\"Number of Tweets\")\n st.pyplot()\n \n"
] |
[
[
"matplotlib.pyplot.imshow",
"pandas.read_csv",
"matplotlib.pyplot.title",
"pandas.DataFrame",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ylabel"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
gabrielpreviato/py4syn
|
[
"ac97c220d38e1aa630ff3ba4d9da030a0d3833d8"
] |
[
"py4syn/epics/DxpFakeClass.py"
] |
[
"\"\"\"Dxp Class\n\nPython Class for EPICS Fake Dxp Control.\n\n:platform: Unix\n:synopsis: Python Class for EPICS Spectro control.\n\n.. moduleauthor:: Gabriel Fedel <[email protected]>\n .. note:: 11/30/2016 [gabrielfedel] first version released\n\"\"\"\nimport os\n\nimport numpy as np\nimport h5py\nfrom py4syn.epics.ImageHDFClass import ImageHDF\n\nNUMPOINTS = 2048\n# constants used to parse PV name\nCHANNELPOSITION=3\nROIPOSITION=6\n\nclass DxpFake(ImageHDF):\n # CONSTRUCTOR OF DXP CLASS\n def __init__(self, mnemonic, numberOfChannels=4, numberOfRois=32,\n pv=None, dxpType=\"mca\", responseTimeout=15, output=\"out\"):\n \"\"\" Constructor\n responseTimeout : how much time to wait dxp answer\n \"\"\"\n super().__init__(mnemonic, NUMPOINTS, output, dxpType)\n self.acquiring = False\n self.rois = numberOfRois\n\n def statusChange(self, value, **kw):\n \"\"\"\n Helper callback used to wait for the end of the acquisition.\n \"\"\"\n pass\n\n def setCountTime(self, time):\n \"\"\"\n Method to set the count time of a scaler device.\n\n Parameters\n ----------\n time : `float`\n Count time to set to scaler device .\n\n Returns\n -------\n out : None\n \"\"\"\n pass\n\n def getCountTime(self):\n pass\n\n def getRealTime(self):\n return np.random.rand()\n\n def setCountStop(self):\n pass\n\n def getValueChannel(self, **kwargs):\n \"\"\"Return intensity\n channel is on format mcaC.Rr, where C is the channel and\n r is the ROI\"\"\"\n channel = kwargs['channel']\n c = int(channel[CHANNELPOSITION]) - 1\n if(len(channel) > ROIPOSITION):\n return np.random.rand()\n else:\n self.saveSpectrum(c, **kwargs)\n return 1.0\n\n def saveSpectrum(self, ch, **kwargs):\n self.spectrum = np.random.randint(100, size=(2048))\n self.ch = ch\n\n super().saveSpectrum()\n\n def isCountRunning(self):\n pass\n\n def wait(self):\n \"\"\"\n Blocks until the acquisition completes.\n \"\"\"\n pass\n\n def canMonitor(self):\n \"\"\" Returns false indcating Dxp cannot be use as a counter monitor\"\"\"\n return False\n\n def canStopCount(self):\n \"\"\"\n Returns true indicating that Dxp has a stop command.\n \"\"\"\n return True\n\n def getValue(self, **kwargs):\n \"\"\"\n This is a dummy method that always returns zero, which is part of the\n :class:`py4syn.epics.ICountable` interface. Dxp does not return\n a value while scanning. Instead, it stores a mca file with result .\n \"\"\"\n if(kwargs):\n return self.getValueChannel(**kwargs)\n return self.getValueChannel()\n\n def isCounting(self):\n pass\n\n def startCount(self):\n pass\n\n def stopCount(self):\n pass\n\n def setPresetValue(self, channel, val):\n \"\"\"Dummy method\"\"\"\n pass\n\n def close(self):\n pass\n\n def startCollectImage(self, rows=0, cols=0):\n \"\"\"Start to collect an image\n When collect an image, the points will be saved on a hdf file\"\"\"\n super().startCollectImage(\"int32\", rows, cols)\n"
] |
[
[
"numpy.random.rand",
"numpy.random.randint"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
govindjeevan/facenet
|
[
"70a7ee5c5836bc8a31935250eb2d9e818ebf1f2d"
] |
[
"src/train_softmax.py"
] |
[
"\"\"\"Training a face recognizer with TensorFlow using softmax cross entropy loss\n\"\"\"\n# MIT License\n# \n# Copyright (c) 2016 David Sandberg\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom datetime import datetime\nimport os.path\nimport time\nimport sys\nimport random\nimport tensorflow as tf\nimport numpy as np\nimport importlib\nimport argparse\nimport facenet\nimport lfw\nimport h5py\nimport math\nimport tensorflow.contrib.slim as slim\nfrom tensorflow.python.ops import data_flow_ops\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\n\ndef main(args):\n \n network = importlib.import_module(args.model_def)\n image_size = (args.image_size, args.image_size)\n\n subdir = datetime.strftime(datetime.now(), '%Y-%m-%d-%H-softmax-'+args.model_def.split(\".\")[-1]+\"-\"+args.data_dir.split(\"/\")[-1])\n log_dir = os.path.join(os.path.expanduser(args.logs_base_dir), subdir)\n if not os.path.isdir(log_dir): # Create the log directory if it doesn't exist\n os.makedirs(log_dir)\n model_dir = os.path.join(os.path.expanduser(args.models_base_dir), subdir)\n if not os.path.isdir(model_dir): # Create the model directory if it doesn't exist\n os.makedirs(model_dir)\n\n stat_file_name = os.path.join(log_dir, 'stat.h5')\n\n # Write arguments to a text file\n facenet.write_arguments_to_file(args, os.path.join(log_dir, 'arguments.txt'))\n \n # Store some git revision info in a text file in the log directory\n src_path,_ = os.path.split(os.path.realpath(__file__))\n facenet.store_revision_info(src_path, log_dir, ' '.join(sys.argv))\n\n np.random.seed(seed=args.seed)\n random.seed(args.seed)\n dataset = facenet.get_dataset(args.data_dir)\n if args.filter_filename:\n dataset = filter_dataset(dataset, os.path.expanduser(args.filter_filename), \n args.filter_percentile, args.filter_min_nrof_images_per_class)\n \n if args.validation_set_split_ratio>0.0:\n train_set, val_set = facenet.split_dataset(dataset, args.validation_set_split_ratio, args.min_nrof_val_images_per_class, 'SPLIT_IMAGES')\n else:\n train_set, val_set = dataset, []\n \n nrof_classes = len(train_set)\n \n print('Model directory: %s' % model_dir)\n print('Log directory: %s' % log_dir)\n pretrained_model = None\n if args.pretrained_model:\n pretrained_model = os.path.expanduser(args.pretrained_model)\n print('Pre-trained model: %s' % pretrained_model)\n \n if args.lfw_dir:\n print('LFW directory: %s' % args.lfw_dir)\n # Read the file containing the pairs used for testing\n pairs = lfw.read_pairs(os.path.expanduser(args.lfw_pairs))\n # Get the paths for the corresponding images\n lfw_paths, actual_issame = lfw.get_paths(os.path.expanduser(args.lfw_dir), pairs)\n \n with tf.Graph().as_default():\n tf.set_random_seed(args.seed)\n global_step = tf.Variable(0, trainable=False)\n \n # Get a list of image paths and their labels\n image_list, label_list = facenet.get_image_paths_and_labels(train_set)\n assert len(image_list)>0, 'The training set should not be empty'\n \n val_image_list, val_label_list = facenet.get_image_paths_and_labels(val_set)\n\n # Create a queue that produces indices into the image_list and label_list \n labels = ops.convert_to_tensor(label_list, dtype=tf.int32)\n range_size = array_ops.shape(labels)[0]\n index_queue = tf.train.range_input_producer(range_size, num_epochs=None,\n shuffle=True, seed=None, capacity=32)\n \n index_dequeue_op = index_queue.dequeue_many(args.batch_size*args.epoch_size, 'index_dequeue')\n \n learning_rate_placeholder = tf.placeholder(tf.float32, name='learning_rate')\n batch_size_placeholder = tf.placeholder(tf.int32, name='batch_size')\n phase_train_placeholder = tf.placeholder(tf.bool, name='phase_train')\n image_paths_placeholder = tf.placeholder(tf.string, shape=(None,1), name='image_paths')\n labels_placeholder = tf.placeholder(tf.int32, shape=(None,1), name='labels')\n control_placeholder = tf.placeholder(tf.int32, shape=(None,1), name='control')\n \n nrof_preprocess_threads = 4\n input_queue = data_flow_ops.FIFOQueue(capacity=2000000,\n dtypes=[tf.string, tf.int32, tf.int32],\n shapes=[(1,), (1,), (1,)],\n shared_name=None, name=None)\n enqueue_op = input_queue.enqueue_many([image_paths_placeholder, labels_placeholder, control_placeholder], name='enqueue_op')\n image_batch, label_batch = facenet.create_input_pipeline(input_queue, image_size, nrof_preprocess_threads, batch_size_placeholder)\n\n image_batch = tf.identity(image_batch, 'image_batch')\n image_batch = tf.identity(image_batch, 'input')\n label_batch = tf.identity(label_batch, 'label_batch')\n \n print('Number of classes in training set: %d' % nrof_classes)\n print('Number of examples in training set: %d' % len(image_list))\n\n print('Number of classes in validation set: %d' % len(val_set))\n print('Number of examples in validation set: %d' % len(val_image_list))\n \n print('Building training graph')\n \n # Build the inference graph\n prelogits, _ = network.inference(image_batch, args.keep_probability, \n phase_train=phase_train_placeholder, bottleneck_layer_size=args.embedding_size, \n weight_decay=args.weight_decay)\n logits = slim.fully_connected(prelogits, len(train_set), activation_fn=None, \n weights_initializer=slim.initializers.xavier_initializer(), \n weights_regularizer=slim.l2_regularizer(args.weight_decay),\n scope='Logits', reuse=False)\n\n embeddings = tf.nn.l2_normalize(prelogits, 1, 1e-10, name='embeddings')\n\n # Norm for the prelogits\n eps = 1e-4\n prelogits_norm = tf.reduce_mean(tf.norm(tf.abs(prelogits)+eps, ord=args.prelogits_norm_p, axis=1))\n tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES, prelogits_norm * args.prelogits_norm_loss_factor)\n\n # Add center loss\n prelogits_center_loss, _ = facenet.center_loss(prelogits, label_batch, args.center_loss_alfa, nrof_classes)\n tf.add_to_collection(tf.GraphKeys.REGULARIZATION_LOSSES, prelogits_center_loss * args.center_loss_factor)\n\n learning_rate = tf.train.exponential_decay(learning_rate_placeholder, global_step,\n args.learning_rate_decay_epochs*args.epoch_size, args.learning_rate_decay_factor, staircase=True)\n tf.summary.scalar('learning_rate', learning_rate)\n\n # Calculate the average cross entropy loss across the batch\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=label_batch, logits=logits, name='cross_entropy_per_example')\n cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')\n tf.add_to_collection('losses', cross_entropy_mean)\n \n correct_prediction = tf.cast(tf.equal(tf.argmax(logits, 1), tf.cast(label_batch, tf.int64)), tf.float32)\n accuracy = tf.reduce_mean(correct_prediction)\n \n # Calculate the total losses\n regularization_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)\n total_loss = tf.add_n([cross_entropy_mean] + regularization_losses, name='total_loss')\n\n # Build a Graph that trains the model with one batch of examples and updates the model parameters\n train_op = facenet.train(total_loss, global_step, args.optimizer, \n learning_rate, args.moving_average_decay, tf.global_variables(), args.log_histograms)\n \n # Create a saver\n saver = tf.train.Saver(tf.trainable_variables(), max_to_keep=3)\n\n # Build the summary operation based on the TF collection of Summaries.\n summary_op = tf.summary.merge_all()\n\n # Start running operations on the Graph.\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=args.gpu_memory_fraction)\n sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))\n sess.run(tf.global_variables_initializer())\n sess.run(tf.local_variables_initializer())\n summary_writer = tf.summary.FileWriter(log_dir, sess.graph)\n coord = tf.train.Coordinator()\n tf.train.start_queue_runners(coord=coord, sess=sess)\n\n with sess.as_default():\n\n if pretrained_model:\n print('Restoring pretrained model: %s' % pretrained_model)\n ckpt = tf.train.get_checkpoint_state(pretrained_model)\n if ckpt and ckpt.model_checkpoint_path:\n saver.restore(sess, ckpt.model_checkpoint_path)\n\n\n # Training and validation loop\n print('Running training')\n nrof_steps = args.max_nrof_epochs*args.epoch_size\n nrof_val_samples = int(math.ceil(args.max_nrof_epochs / args.validate_every_n_epochs)) # Validate every validate_every_n_epochs as well as in the last epoch\n stat = {\n 'loss': np.zeros((nrof_steps,), np.float32),\n 'center_loss': np.zeros((nrof_steps,), np.float32),\n 'reg_loss': np.zeros((nrof_steps,), np.float32),\n 'xent_loss': np.zeros((nrof_steps,), np.float32),\n 'prelogits_norm': np.zeros((nrof_steps,), np.float32),\n 'accuracy': np.zeros((nrof_steps,), np.float32),\n 'val_loss': np.zeros((nrof_val_samples,), np.float32),\n 'val_xent_loss': np.zeros((nrof_val_samples,), np.float32),\n 'val_accuracy': np.zeros((nrof_val_samples,), np.float32),\n 'lfw_accuracy': np.zeros((args.max_nrof_epochs,), np.float32),\n 'lfw_valrate2': np.zeros((args.max_nrof_epochs,), np.float32),\n 'lfw_valrate3': np.zeros((args.max_nrof_epochs,), np.float32),\n 'learning_rate': np.zeros((args.max_nrof_epochs,), np.float32),\n 'time_train': np.zeros((args.max_nrof_epochs,), np.float32),\n 'time_validate': np.zeros((args.max_nrof_epochs,), np.float32),\n 'time_evaluate': np.zeros((args.max_nrof_epochs,), np.float32),\n 'prelogits_hist': np.zeros((args.max_nrof_epochs, 1000), np.float32),\n }\n for epoch in range(1,args.max_nrof_epochs+1):\n step = sess.run(global_step, feed_dict=None)\n # Train for one epoch\n t = time.time()\n cont = train(args, sess, epoch, image_list, label_list, index_dequeue_op, enqueue_op, image_paths_placeholder, labels_placeholder,\n learning_rate_placeholder, phase_train_placeholder, batch_size_placeholder, control_placeholder, global_step, \n total_loss, train_op, summary_op, summary_writer, regularization_losses, args.learning_rate_schedule_file,\n stat, cross_entropy_mean, accuracy, learning_rate,\n prelogits, prelogits_center_loss, args.random_rotate, args.random_crop, args.random_flip, prelogits_norm, args.prelogits_hist_max, args.use_fixed_image_standardization)\n stat['time_train'][epoch-1] = time.time() - t\n \n if not cont:\n break\n \n t = time.time()\n if len(val_image_list)>0 and ((epoch-1) % args.validate_every_n_epochs == args.validate_every_n_epochs-1 or epoch==args.max_nrof_epochs):\n validate(args, sess, epoch, val_image_list, val_label_list, enqueue_op, image_paths_placeholder, labels_placeholder, control_placeholder,\n phase_train_placeholder, batch_size_placeholder, \n stat, total_loss, regularization_losses, cross_entropy_mean, accuracy, args.validate_every_n_epochs, args.use_fixed_image_standardization)\n stat['time_validate'][epoch-1] = time.time() - t\n\n # Save variables and the metagraph if it doesn't exist already\n save_variables_and_metagraph(sess, saver, summary_writer, model_dir, subdir, epoch)\n\n # Evaluate on LFW\n t = time.time()\n if args.lfw_dir:\n evaluate(sess, enqueue_op, image_paths_placeholder, labels_placeholder, phase_train_placeholder, batch_size_placeholder, control_placeholder, \n embeddings, label_batch, lfw_paths, actual_issame, args.lfw_batch_size, args.lfw_nrof_folds, log_dir, step, summary_writer, stat, epoch, \n args.lfw_distance_metric, args.lfw_subtract_mean, args.lfw_use_flipped_images, args.use_fixed_image_standardization)\n stat['time_evaluate'][epoch-1] = time.time() - t\n\n print('Saving statistics')\n with h5py.File(stat_file_name, 'w') as f:\n for key, value in stat.items():\n f.create_dataset(key, data=value)\n \n return model_dir\n \ndef find_threshold(var, percentile):\n hist, bin_edges = np.histogram(var, 100)\n cdf = np.float32(np.cumsum(hist)) / np.sum(hist)\n bin_centers = (bin_edges[:-1]+bin_edges[1:])/2\n #plt.plot(bin_centers, cdf)\n threshold = np.interp(percentile*0.01, cdf, bin_centers)\n return threshold\n \ndef filter_dataset(dataset, data_filename, percentile, min_nrof_images_per_class):\n with h5py.File(data_filename,'r') as f:\n distance_to_center = np.array(f.get('distance_to_center'))\n label_list = np.array(f.get('label_list'))\n image_list = np.array(f.get('image_list'))\n distance_to_center_threshold = find_threshold(distance_to_center, percentile)\n indices = np.where(distance_to_center>=distance_to_center_threshold)[0]\n filtered_dataset = dataset\n removelist = []\n for i in indices:\n label = label_list[i]\n image = image_list[i]\n if image in filtered_dataset[label].image_paths:\n filtered_dataset[label].image_paths.remove(image)\n if len(filtered_dataset[label].image_paths)<min_nrof_images_per_class:\n removelist.append(label)\n\n ix = sorted(list(set(removelist)), reverse=True)\n for i in ix:\n del(filtered_dataset[i])\n\n return filtered_dataset\n \ndef train(args, sess, epoch, image_list, label_list, index_dequeue_op, enqueue_op, image_paths_placeholder, labels_placeholder, \n learning_rate_placeholder, phase_train_placeholder, batch_size_placeholder, control_placeholder, step, \n loss, train_op, summary_op, summary_writer, reg_losses, learning_rate_schedule_file, \n stat, cross_entropy_mean, accuracy, \n learning_rate, prelogits, prelogits_center_loss, random_rotate, random_crop, random_flip, prelogits_norm, prelogits_hist_max, use_fixed_image_standardization):\n batch_number = 0\n \n if args.learning_rate>0.0:\n lr = args.learning_rate\n else:\n lr = facenet.get_learning_rate_from_file(learning_rate_schedule_file, epoch)\n \n if lr<=0:\n return False \n\n index_epoch = sess.run(index_dequeue_op)\n label_epoch = np.array(label_list)[index_epoch]\n image_epoch = np.array(image_list)[index_epoch]\n \n # Enqueue one epoch of image paths and labels\n labels_array = np.expand_dims(np.array(label_epoch),1)\n image_paths_array = np.expand_dims(np.array(image_epoch),1)\n control_value = facenet.RANDOM_ROTATE * random_rotate + facenet.RANDOM_CROP * random_crop + facenet.RANDOM_FLIP * random_flip + facenet.FIXED_STANDARDIZATION * use_fixed_image_standardization\n control_array = np.ones_like(labels_array) * control_value\n sess.run(enqueue_op, {image_paths_placeholder: image_paths_array, labels_placeholder: labels_array, control_placeholder: control_array})\n\n # Training loop\n train_time = 0\n while batch_number < args.epoch_size:\n start_time = time.time()\n feed_dict = {learning_rate_placeholder: lr, phase_train_placeholder:True, batch_size_placeholder:args.batch_size}\n tensor_list = [loss, train_op, step, reg_losses, prelogits, cross_entropy_mean, learning_rate, prelogits_norm, accuracy, prelogits_center_loss]\n if batch_number % 100 == 0:\n loss_, _, step_, reg_losses_, prelogits_, cross_entropy_mean_, lr_, prelogits_norm_, accuracy_, center_loss_, summary_str = sess.run(tensor_list + [summary_op], feed_dict=feed_dict)\n summary_writer.add_summary(summary_str, global_step=step_)\n else:\n loss_, _, step_, reg_losses_, prelogits_, cross_entropy_mean_, lr_, prelogits_norm_, accuracy_, center_loss_ = sess.run(tensor_list, feed_dict=feed_dict)\n \n duration = time.time() - start_time\n stat['loss'][step_-1] = loss_\n stat['center_loss'][step_-1] = center_loss_\n stat['reg_loss'][step_-1] = np.sum(reg_losses_)\n stat['xent_loss'][step_-1] = cross_entropy_mean_\n stat['prelogits_norm'][step_-1] = prelogits_norm_\n stat['learning_rate'][epoch-1] = lr_\n stat['accuracy'][step_-1] = accuracy_\n stat['prelogits_hist'][epoch-1,:] += np.histogram(np.minimum(np.abs(prelogits_), prelogits_hist_max), bins=1000, range=(0.0, prelogits_hist_max))[0]\n \n duration = time.time() - start_time\n print('Epoch: [%d][%d/%d]\\tTime %.3f\\tLoss %2.3f\\tXent %2.3f\\tRegLoss %2.3f\\tAccuracy %2.3f\\tLr %2.5f\\tCl %2.3f' %\n (epoch, batch_number+1, args.epoch_size, duration, loss_, cross_entropy_mean_, np.sum(reg_losses_), accuracy_, lr_, center_loss_))\n batch_number += 1\n train_time += duration\n # Add validation loss and accuracy to summary\n summary = tf.Summary()\n #pylint: disable=maybe-no-member\n summary.value.add(tag='time/total', simple_value=train_time)\n summary_writer.add_summary(summary, global_step=step_)\n return True\n\ndef validate(args, sess, epoch, image_list, label_list, enqueue_op, image_paths_placeholder, labels_placeholder, control_placeholder,\n phase_train_placeholder, batch_size_placeholder, \n stat, loss, regularization_losses, cross_entropy_mean, accuracy, validate_every_n_epochs, use_fixed_image_standardization):\n \n print('Running forward pass on validation set')\n\n nrof_batches = len(label_list) // args.lfw_batch_size\n nrof_images = nrof_batches * args.lfw_batch_size\n \n # Enqueue one epoch of image paths and labels\n labels_array = np.expand_dims(np.array(label_list[:nrof_images]),1)\n image_paths_array = np.expand_dims(np.array(image_list[:nrof_images]),1)\n control_array = np.ones_like(labels_array, np.int32)*facenet.FIXED_STANDARDIZATION * use_fixed_image_standardization\n sess.run(enqueue_op, {image_paths_placeholder: image_paths_array, labels_placeholder: labels_array, control_placeholder: control_array})\n\n loss_array = np.zeros((nrof_batches,), np.float32)\n xent_array = np.zeros((nrof_batches,), np.float32)\n accuracy_array = np.zeros((nrof_batches,), np.float32)\n\n # Training loop\n start_time = time.time()\n for i in range(nrof_batches):\n feed_dict = {phase_train_placeholder:False, batch_size_placeholder:args.lfw_batch_size}\n loss_, cross_entropy_mean_, accuracy_ = sess.run([loss, cross_entropy_mean, accuracy], feed_dict=feed_dict)\n loss_array[i], xent_array[i], accuracy_array[i] = (loss_, cross_entropy_mean_, accuracy_)\n if i % 10 == 9:\n print('.', end='')\n sys.stdout.flush()\n print('')\n\n duration = time.time() - start_time\n\n val_index = (epoch-1)//validate_every_n_epochs\n stat['val_loss'][val_index] = np.mean(loss_array)\n stat['val_xent_loss'][val_index] = np.mean(xent_array)\n stat['val_accuracy'][val_index] = np.mean(accuracy_array)\n\n print('Validation Epoch: %d\\tTime %.3f\\tLoss %2.3f\\tXent %2.3f\\tAccuracy %2.3f' %\n (epoch, duration, np.mean(loss_array), np.mean(xent_array), np.mean(accuracy_array)))\n\n\ndef evaluate(sess, enqueue_op, image_paths_placeholder, labels_placeholder, phase_train_placeholder, batch_size_placeholder, control_placeholder, \n embeddings, labels, image_paths, actual_issame, batch_size, nrof_folds, log_dir, step, summary_writer, stat, epoch, distance_metric, subtract_mean, use_flipped_images, use_fixed_image_standardization):\n start_time = time.time()\n # Run forward pass to calculate embeddings\n print('Runnning forward pass on LFW images')\n \n # Enqueue one epoch of image paths and labels\n nrof_embeddings = len(actual_issame)*2 # nrof_pairs * nrof_images_per_pair\n nrof_flips = 2 if use_flipped_images else 1\n nrof_images = nrof_embeddings * nrof_flips\n labels_array = np.expand_dims(np.arange(0,nrof_images),1)\n image_paths_array = np.expand_dims(np.repeat(np.array(image_paths),nrof_flips),1)\n control_array = np.zeros_like(labels_array, np.int32)\n if use_fixed_image_standardization:\n control_array += np.ones_like(labels_array)*facenet.FIXED_STANDARDIZATION\n if use_flipped_images:\n # Flip every second image\n control_array += (labels_array % 2)*facenet.FLIP\n sess.run(enqueue_op, {image_paths_placeholder: image_paths_array, labels_placeholder: labels_array, control_placeholder: control_array})\n \n embedding_size = int(embeddings.get_shape()[1])\n assert nrof_images % batch_size == 0, 'The number of LFW images must be an integer multiple of the LFW batch size'\n nrof_batches = nrof_images // batch_size\n emb_array = np.zeros((nrof_images, embedding_size))\n lab_array = np.zeros((nrof_images,))\n for i in range(nrof_batches):\n feed_dict = {phase_train_placeholder:False, batch_size_placeholder:batch_size}\n emb, lab = sess.run([embeddings, labels], feed_dict=feed_dict)\n lab_array[lab] = lab\n emb_array[lab, :] = emb\n if i % 10 == 9:\n print('.', end='')\n sys.stdout.flush()\n print('')\n embeddings = np.zeros((nrof_embeddings, embedding_size*nrof_flips))\n if use_flipped_images:\n # Concatenate embeddings for flipped and non flipped version of the images\n embeddings[:,:embedding_size] = emb_array[0::2,:]\n embeddings[:,embedding_size:] = emb_array[1::2,:]\n else:\n embeddings = emb_array\n\n assert np.array_equal(lab_array, np.arange(nrof_images))==True, 'Wrong labels used for evaluation, possibly caused by training examples left in the input pipeline'\n _, _, accuracy, val2, val_std2, far2, val3, val_std3, far3 = lfw.evaluate(embeddings, actual_issame, nrof_folds=nrof_folds, distance_metric=distance_metric, subtract_mean=subtract_mean)\n \n print('Accuracy: %1.3f+-%1.3f' % (np.mean(accuracy), np.std(accuracy)))\n print('Validation rate: %2.5f+-%2.5f @ FAR=%2.5f' % (val2, val_std2, far2))\n print('Validation rate: %2.5f+-%2.5f @ FAR=%2.5f' % (val3, val_std3, far3))\n \n lfw_time = time.time() - start_time\n # Add validation loss and accuracy to summary\n summary = tf.Summary()\n #pylint: disable=maybe-no-member\n summary.value.add(tag='lfw/accuracy', simple_value=np.mean(accuracy))\n summary.value.add(tag='lfw/val_rate2', simple_value=val2)\n summary.value.add(tag='lfw/val_rate3', simple_value=val3)\n summary.value.add(tag='time/lfw', simple_value=lfw_time)\n summary_writer.add_summary(summary, step)\n with open(os.path.join(log_dir,'lfw_result.txt'),'at') as f:\n f.write('%d\\t%.5f\\t%.5f\\t%.5f\\n' % (step, np.mean(accuracy), val2, val3))\n stat['lfw_accuracy'][epoch-1] = np.mean(accuracy)\n stat['lfw_valrate2'][epoch-1] = val2\n stat['lfw_valrate3'][epoch-1] = val3\n\ndef save_variables_and_metagraph(sess, saver, summary_writer, model_dir, model_name, step):\n # Save the model checkpoint\n print('Saving variables')\n start_time = time.time()\n checkpoint_path = os.path.join(model_dir, 'model-%s.ckpt' % model_name)\n saver.save(sess, checkpoint_path, global_step=step, write_meta_graph=False)\n save_time_variables = time.time() - start_time\n print('Variables saved in %.2f seconds' % save_time_variables)\n metagraph_filename = os.path.join(model_dir, 'model-%s.meta' % model_name)\n save_time_metagraph = 0 \n if not os.path.exists(metagraph_filename):\n print('Saving metagraph')\n start_time = time.time()\n saver.export_meta_graph(metagraph_filename)\n save_time_metagraph = time.time() - start_time\n print('Metagraph saved in %.2f seconds' % save_time_metagraph)\n summary = tf.Summary()\n #pylint: disable=maybe-no-member\n summary.value.add(tag='time/save_variables', simple_value=save_time_variables)\n summary.value.add(tag='time/save_metagraph', simple_value=save_time_metagraph)\n summary_writer.add_summary(summary, step)\n \n\ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n \n parser.add_argument('--logs_base_dir', type=str, \n help='Directory where to write event logs.', default='~/logs/facenet')\n parser.add_argument('--models_base_dir', type=str,\n help='Directory where to write trained models and checkpoints.', default='~/models/facenet')\n parser.add_argument('--gpu_memory_fraction', type=float,\n help='Upper bound on the amount of GPU memory that will be used by the process.', default=1.0)\n parser.add_argument('--pretrained_model', type=str,\n help='Load a pretrained model before training starts.')\n parser.add_argument('--data_dir', type=str,\n help='Path to the data directory containing aligned face patches.',\n default='~/datasets/casia/casia_maxpy_mtcnnalign_182_160')\n parser.add_argument('--model_def', type=str,\n help='Model definition. Points to a module containing the definition of the inference graph.', default='models.inception_resnet_v1')\n parser.add_argument('--max_nrof_epochs', type=int,\n help='Number of epochs to run.', default=500)\n parser.add_argument('--batch_size', type=int,\n help='Number of images to process in a batch.', default=90)\n parser.add_argument('--image_size', type=int,\n help='Image size (height, width) in pixels.', default=160)\n parser.add_argument('--epoch_size', type=int,\n help='Number of batches per epoch.', default=3860)\n parser.add_argument('--embedding_size', type=int,\n help='Dimensionality of the embedding.', default=128)\n parser.add_argument('--random_crop', \n help='Performs random cropping of training images. If false, the center image_size pixels from the training images are used. ' +\n 'If the size of the images in the data directory is equal to image_size no cropping is performed', action='store_true')\n parser.add_argument('--random_flip', \n help='Performs random horizontal flipping of training images.', action='store_true')\n parser.add_argument('--random_rotate', \n help='Performs random rotations of training images.', action='store_true')\n parser.add_argument('--use_fixed_image_standardization', \n help='Performs fixed standardization of images.', action='store_true')\n parser.add_argument('--keep_probability', type=float,\n help='Keep probability of dropout for the fully connected layer(s).', default=1.0)\n parser.add_argument('--weight_decay', type=float,\n help='L2 weight regularization.', default=0.0)\n parser.add_argument('--center_loss_factor', type=float,\n help='Center loss factor.', default=0.0)\n parser.add_argument('--center_loss_alfa', type=float,\n help='Center update rate for center loss.', default=0.95)\n parser.add_argument('--prelogits_norm_loss_factor', type=float,\n help='Loss based on the norm of the activations in the prelogits layer.', default=0.0)\n parser.add_argument('--prelogits_norm_p', type=float,\n help='Norm to use for prelogits norm loss.', default=1.0)\n parser.add_argument('--prelogits_hist_max', type=float,\n help='The max value for the prelogits histogram.', default=10.0)\n parser.add_argument('--optimizer', type=str, choices=['ADAGRAD', 'ADADELTA', 'ADAM', 'RMSPROP', 'MOM'],\n help='The optimization algorithm to use', default='ADAGRAD')\n parser.add_argument('--learning_rate', type=float,\n help='Initial learning rate. If set to a negative value a learning rate ' +\n 'schedule can be specified in the file \"learning_rate_schedule.txt\"', default=0.1)\n parser.add_argument('--learning_rate_decay_epochs', type=int,\n help='Number of epochs between learning rate decay.', default=100)\n parser.add_argument('--learning_rate_decay_factor', type=float,\n help='Learning rate decay factor.', default=1.0)\n parser.add_argument('--moving_average_decay', type=float,\n help='Exponential decay for tracking of training parameters.', default=0.9999)\n parser.add_argument('--seed', type=int,\n help='Random seed.', default=666)\n parser.add_argument('--nrof_preprocess_threads', type=int,\n help='Number of preprocessing (data loading and augmentation) threads.', default=4)\n parser.add_argument('--log_histograms', \n help='Enables logging of weight/bias histograms in tensorboard.', action='store_true')\n parser.add_argument('--learning_rate_schedule_file', type=str,\n help='File containing the learning rate schedule that is used when learning_rate is set to to -1.', default='data/learning_rate_schedule.txt')\n parser.add_argument('--filter_filename', type=str,\n help='File containing image data used for dataset filtering', default='')\n parser.add_argument('--filter_percentile', type=float,\n help='Keep only the percentile images closed to its class center', default=100.0)\n parser.add_argument('--filter_min_nrof_images_per_class', type=int,\n help='Keep only the classes with this number of examples or more', default=0)\n parser.add_argument('--validate_every_n_epochs', type=int,\n help='Number of epoch between validation', default=5)\n parser.add_argument('--validation_set_split_ratio', type=float,\n help='The ratio of the total dataset to use for validation', default=0.0)\n parser.add_argument('--min_nrof_val_images_per_class', type=float,\n help='Classes with fewer images will be removed from the validation set', default=0)\n \n # Parameters for validation on LFW\n parser.add_argument('--lfw_pairs', type=str,\n help='The file containing the pairs to use for validation.', default='data/pairs.txt')\n parser.add_argument('--lfw_dir', type=str,\n help='Path to the data directory containing aligned face patches.', default='')\n parser.add_argument('--lfw_batch_size', type=int,\n help='Number of images to process in a batch in the LFW test set.', default=100)\n parser.add_argument('--lfw_nrof_folds', type=int,\n help='Number of folds to use for cross validation. Mainly used for testing.', default=10)\n parser.add_argument('--lfw_distance_metric', type=int,\n help='Type of distance metric to use. 0: Euclidian, 1:Cosine similarity distance.', default=0)\n parser.add_argument('--lfw_use_flipped_images', \n help='Concatenates embeddings for the image and its horizontally flipped counterpart.', action='store_true')\n parser.add_argument('--lfw_subtract_mean', \n help='Subtract feature mean before calculating distance.', action='store_true')\n return parser.parse_args(argv)\n \n\nif __name__ == '__main__':\n main(parse_arguments(sys.argv[1:]))\n"
] |
[
[
"tensorflow.python.ops.array_ops.shape",
"tensorflow.global_variables",
"tensorflow.contrib.slim.l2_regularizer",
"numpy.cumsum",
"tensorflow.cast",
"numpy.mean",
"numpy.zeros_like",
"tensorflow.GPUOptions",
"numpy.histogram",
"tensorflow.summary.scalar",
"tensorflow.add_n",
"numpy.where",
"tensorflow.Graph",
"numpy.ones_like",
"tensorflow.Variable",
"tensorflow.get_collection",
"numpy.arange",
"tensorflow.train.exponential_decay",
"tensorflow.ConfigProto",
"numpy.std",
"numpy.interp",
"tensorflow.trainable_variables",
"tensorflow.Summary",
"tensorflow.argmax",
"numpy.zeros",
"tensorflow.nn.l2_normalize",
"tensorflow.train.Coordinator",
"tensorflow.identity",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits",
"tensorflow.summary.merge_all",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.set_random_seed",
"numpy.array",
"tensorflow.python.ops.data_flow_ops.FIFOQueue",
"tensorflow.add_to_collection",
"numpy.sum",
"tensorflow.train.get_checkpoint_state",
"tensorflow.summary.FileWriter",
"tensorflow.local_variables_initializer",
"numpy.random.seed",
"tensorflow.reduce_mean",
"numpy.abs",
"tensorflow.train.range_input_producer",
"tensorflow.train.start_queue_runners",
"tensorflow.contrib.slim.initializers.xavier_initializer",
"tensorflow.abs"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"1.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.8",
"1.2",
"2.10"
]
}
] |
zjzh/SALib
|
[
"95a3371e503f9253cb917b8f0101c0202b969c2b",
"95a3371e503f9253cb917b8f0101c0202b969c2b"
] |
[
"src/SALib/test_functions/Ishigami.py",
"src/SALib/test_functions/linear_model_2.py"
] |
[
"import numpy as np\r\n\r\n\r\ndef evaluate(X: np.ndarray, A: float = 7.0, B: float = 0.1) -> np.ndarray:\r\n \"\"\"Non-monotonic Ishigami-Homma three parameter test function:\r\n\r\n `f(x) = \\sin(x_{1}) + A \\sin(x_{2})^2 + Bx^{4}_{3}\\sin(x_{1})`\r\n\r\n This test function is commonly used to benchmark global sensitivity \r\n methods as variance-based sensitivities of this function can be \r\n analytically determined.\r\n\r\n See listed references below.\r\n\r\n In [2], the expected first-order indices are:\r\n\r\n x1: 0.3139\r\n x2: 0.4424\r\n x3: 0.0\r\n\r\n when A = 7, B = 0.1 when conducting Sobol' analysis with the\r\n Saltelli sampling method with a sample size of 1000.\r\n\r\n\r\n Parameters\r\n ----------\r\n X : np.ndarray\r\n An `N*D` array holding values for each parameter, where `N` is the \r\n number of samples and `D` is the number of parameters \r\n (in this case, three).\r\n A : float\r\n Constant `A` parameter\r\n B : float\r\n Constant `B` parameter\r\n\r\n Returns\r\n -------\r\n Y : np.ndarray\r\n\r\n References\r\n ----------\r\n .. [1] Ishigami, T., Homma, T., 1990. \r\n An importance quantification technique in uncertainty analysis for \r\n computer models. \r\n Proceedings. First International Symposium on Uncertainty Modeling \r\n and Analysis. \r\n https://doi.org/10.1109/ISUMA.1990.151285\r\n\r\n .. [2] Saltelli, A., Ratto, M., Andres, T., Campolongo, F., Cariboni, J., \r\n Gatelli, D., Saisana, M., Tarantola, S., 2008. \r\n Global Sensitivity Analysis: The Primer. Wiley, West Sussex, U.K.\r\n https://dx.doi.org/10.1002/9780470725184\r\n \"\"\"\r\n Y = np.zeros(X.shape[0])\r\n Y = np.sin(X[:, 0]) + A * np.power(np.sin(X[:, 1]), 2) + \\\r\n B * np.power(X[:, 2], 4) * np.sin(X[:, 0])\r\n\r\n return Y\r\n",
"import numpy as np\n\n\ndef evaluate(values):\n \"\"\"Linear model (#2) used in Li et al., (2010).\n\n y = 5x1 + 4x2 + 3x3 + 2x4 + x5\n\n Parameters\n ----------\n values : np.array\n\n\n References\n ----------\n .. [1] Genyuan Li, H. Rabitz, P.E. Yelvington, O.O. Oluwole, F. Bacon,\n C.E. Kolb, and J. Schoendorf, \"Global Sensitivity Analysis for\n Systems with Independent and/or Correlated Inputs\", Journal of\n Physical Chemistry A, Vol. 114 (19), pp. 6022 - 6032, 2010,\n https://doi.org/10.1021/jp9096919\n \"\"\"\n Y = np.zeros([values.shape[0]])\n Y = 5 * values[:,0] + 4 * values[:,1] + 3 * values[:,2] + 2 * values[:,3] + values[:,4] \n\n return Y\n"
] |
[
[
"numpy.zeros",
"numpy.power",
"numpy.sin"
],
[
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
cdfreeman-google/jax
|
[
"ca6f8186a36a8962845289ffc6baed3e96390f68"
] |
[
"tests/lax_control_flow_test.py"
] |
[
"# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://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\nimport collections\nfrom functools import partial\nimport itertools\nimport operator\nimport re\nfrom unittest import SkipTest\nimport textwrap\n\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n\nimport numpy as np\nimport numpy.random as npr\n\nimport jax\nfrom jax._src import api\nfrom jax import core\nfrom jax import lax\nfrom jax import random\nfrom jax import test_util as jtu\nfrom jax import tree_util\nfrom jax._src.util import unzip2\nfrom jax.lib import xla_bridge\nfrom jax.interpreters import xla\nimport jax.numpy as jnp # scan tests use numpy\nimport jax.scipy as jsp\n\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n\n\n# Some tests are useful for testing both lax.cond and lax.switch. This function\n# provides a lax.cond-compatible interface to a two-branch lax.switch. Several\n# tests in this file are parameterized such that they either call into lax.cond\n# or into this function.\ndef cond_via_switch(pred, true_fun, false_fun, op, *args):\n if len(args) > 0:\n assert len(args) == 1\n true_op, _true_fun, false_op, _false_fun = true_fun, false_fun, op, args[0]\n op = (false_op, true_op)\n false_fun = lambda op: _false_fun(op[0])\n true_fun = lambda op: _true_fun(op[1])\n index = lax.convert_element_type(pred, np.int32)\n return lax.switch(index, [false_fun, true_fun], op)\n\n\nCOND_IMPLS = [\n (lax.cond, 'cond'),\n (cond_via_switch, 'switch'),\n]\n\n\nSCAN_IMPLS = [\n (lax.scan, 'unroll1'),\n (partial(lax.scan, unroll=2), 'unroll2'),\n]\n\n\ndef while_loop_reference(cond, body, carry):\n while cond(carry):\n carry = body(carry)\n return carry\n\n\ndef scan_reference(f, init, xs):\n carry = init\n ys = []\n for x in xs:\n (carry, y) = f(carry, x)\n ys.append(lax.reshape(y, (1,) + np.shape(y)))\n ys = lax.concatenate(ys, 0)\n return carry, ys\n\n\ndef high_precision_dot(a, b):\n return lax.dot(a, b, precision=lax.Precision.HIGHEST)\n\n\ndef posify(matrix):\n return high_precision_dot(matrix, matrix.T.conj())\n\n\nclass LaxControlFlowTest(jtu.JaxTestCase):\n\n def setUp(self):\n super().setUp()\n jax._src.lax.control_flow._initial_style_open_jaxpr.cache_clear()\n jax._src.lax.control_flow._initial_style_jaxpr.cache_clear()\n jax._src.lax.control_flow._initial_style_jaxprs_with_common_consts.cache_clear()\n\n def testWhileWithTuple(self):\n limit = 10\n\n def loop_cond(state):\n pos, _ = state\n return lax.lt(pos, limit)\n\n def loop_body(state):\n pos, count = state\n return (lax.add(pos, 1), lax.add(count, 1))\n\n def loop(init):\n result = lax.while_loop(loop_cond, loop_body, (init, 0))\n _, count = result\n return count\n\n cloop = api.jit(loop)\n\n self.assertEqual(loop(2), limit - 2)\n self.assertEqual(cloop(2), limit - 2)\n self.assertEqual(cloop(2), limit - 2)\n self.assertEqual(cloop(3), limit - 3)\n\n def testWhileWithManyArgs(self):\n nargs = 256\n\n def loop_cond(state):\n return lax.lt(state[0], 2)\n\n def loop_body(state):\n return tuple(lax.add(s, 1) for s in state)\n\n _ = lax.while_loop(loop_cond, loop_body, (0,) * nargs)\n\n def testNestedWhile(self):\n\n def outer_loop(num): # pylint: disable=missing-docstring\n def cond_fun(state):\n num, i, _ = state\n return lax.lt(i, num)\n\n def body_fun(state):\n num, i, count = state\n return (num, lax.add(i, 1), inner_loop(i, count))\n\n init_val = (num, 0, 0)\n _, i, count = lax.while_loop(cond_fun, body_fun, init_val)\n return (i, count)\n\n def inner_loop(i, count): # pylint: disable=missing-docstring\n def cond_fun(state):\n i, j, _ = state\n return lax.le(j, i)\n\n def body_fun(state):\n i, j, count = state\n return (i, lax.add(j, 1), lax.add(count, 1))\n\n init_val = (i, 0, count)\n _, _, count = lax.while_loop(cond_fun, body_fun, init_val)\n return count\n\n cloop = api.jit(outer_loop)\n\n self.assertEqual(outer_loop(3), (3, 6))\n self.assertEqual(cloop(3), (3, 6))\n self.assertEqual(cloop(3), (3, 6))\n self.assertEqual(cloop(2), (2, 3))\n self.assertEqual(cloop(4), (4, 10))\n\n def testWhileWithClosure(self):\n\n def loop(init, local_limit, inc):\n\n def loop_cond(state):\n pos, _ = state\n return lax.lt(pos, local_limit)\n\n def loop_body(state):\n effect[0] = True\n pos, count = state\n return (lax.add(pos, 1), lax.add(count, inc))\n\n result = lax.while_loop(loop_cond, loop_body, (init, 0))\n _, count = result\n return count\n\n cloop = api.jit(loop)\n\n limit = 10\n effect = [False]\n self.assertEqual(loop(2, limit, 1), limit - 2)\n assert effect[0]\n effect[0] = False\n self.assertEqual(cloop(2, limit, 1), limit - 2)\n assert effect[0]\n effect[0] = False\n self.assertEqual(cloop(2, limit, 1), limit - 2)\n self.assertEqual(cloop(3, limit, 1), limit - 3)\n assert not effect[0]\n\n def testWhileWithClosureJit(self):\n\n def loop(init, local_limit, inc):\n\n def loop_cond(state):\n pos, _ = state\n return lax.lt(pos, local_limit)\n\n def loop_body(state):\n effect[0] = True\n pos, count = state\n f = lambda pos, inc: (lax.add(pos, 1), lax.add(count, inc))\n return api.jit(f)(pos, inc)\n\n result = lax.while_loop(loop_cond, loop_body, (init, 0))\n _, count = result\n return count\n\n cloop = api.jit(loop)\n\n limit = 10\n effect = [False]\n self.assertEqual(loop(2, limit, 1), limit - 2)\n assert effect[0]\n effect[0] = False\n self.assertEqual(cloop(2, limit, 1), limit - 2)\n assert effect[0]\n effect[0] = False\n self.assertEqual(cloop(2, limit, 1), limit - 2)\n self.assertEqual(cloop(3, limit, 1), limit - 3)\n assert not effect[0]\n\n def testWhileTypeErrors(self):\n \"\"\"Test typing error messages for while.\"\"\"\n tuple_treedef = tree_util.tree_structure((1., 1.))\n leaf_treedef = tree_util.tree_structure(0.)\n with self.assertRaisesRegex(TypeError,\n re.escape(f\"cond_fun must return a boolean scalar, but got pytree {tuple_treedef}.\")):\n lax.while_loop(lambda c: (1., 1.), lambda c: c, 0.)\n with self.assertRaisesRegex(TypeError,\n re.escape(\"cond_fun must return a boolean scalar, but got output type(s) [ShapedArray(float32[])].\")):\n lax.while_loop(lambda c: np.float32(1.), lambda c: c, np.float32(0.))\n with self.assertRaisesRegex(TypeError,\n re.escape(\"body_fun output and input must have same type structure, \"\n f\"got {tuple_treedef} and {leaf_treedef}.\")):\n lax.while_loop(lambda c: True, lambda c: (1., 1.), 0.)\n with self.assertRaisesWithLiteralMatch(TypeError,\n (\"body_fun output and input must have identical types, got\\n\"\n \"ShapedArray(bool[], weak_type=True)\\n\"\n \"and\\n\"\n \"ShapedArray(float32[]).\")):\n lax.while_loop(lambda c: True, lambda c: True, np.float32(0.))\n\n def testNestedWhileWithDynamicUpdateSlice(self):\n num = 5\n\n def update_entry(arr, val, i, j):\n val = lax.reshape(val, [1, 1])\n return lax.dynamic_update_slice(arr, val, (i, j))\n\n def outer_loop(arr): # pylint: disable=missing-docstring\n\n def cond_fun(state):\n i, num, _, _ = state\n return lax.lt(i, num)\n\n def body_fun(state):\n i, num, arr, out = state\n return (lax.add(i, 1), num, arr, inner_loop(i, arr, out))\n\n out = np.zeros(arr.shape, dtype=arr.dtype)\n init_val = (0, num, arr, out)\n _, _, _, out = lax.while_loop(cond_fun, body_fun, init_val)\n return out\n\n def inner_loop(i, arr, out): # pylint: disable=missing-docstring\n\n def cond_fun(state):\n i, j, _, _ = state\n return lax.le(j, i)\n\n def body_fun(state):\n i, j, arr, out = state\n arr_i = lax.dynamic_index_in_dim(arr, i, 0, False)\n arr_i_j = lax.dynamic_index_in_dim(arr_i, j, 0, False)\n out = update_entry(out, arr_i_j, i, j)\n return (i, lax.add(j, 1), arr, out)\n\n init_val = (i, 0, arr, out)\n _, _, _, out = lax.while_loop(cond_fun, body_fun, init_val)\n return out\n\n cloop = api.jit(outer_loop)\n arr = npr.RandomState(0).randn(5, 5)\n self.assertAllClose(outer_loop(arr), np.tril(arr), check_dtypes=False)\n self.assertAllClose(cloop(arr), np.tril(arr), check_dtypes=False)\n self.assertAllClose(cloop(arr), np.tril(arr), check_dtypes=False)\n\n def testLoopWithConjunctionCondition(self):\n def sum_first_n(arr, num): # pylint: disable=missing-docstring\n def cond_fun(state):\n arr, num, i, _ = state\n return lax.bitwise_and(lax.lt(i, num), lax.lt(i, arr.shape[0]))\n\n def body_fun(state):\n arr, num, i, total = state\n arr_i = lax.dynamic_index_in_dim(arr, i, 0, False)\n return (arr, num, lax.add(i, 1), lax.add(total, arr_i))\n\n init_val = (arr, num, 0, 0.)\n _, _, _, total = lax.while_loop(cond_fun, body_fun, init_val)\n return total\n\n cfun = api.jit(sum_first_n)\n x = npr.RandomState(0).randn(10).astype(jnp.float_)\n\n for num in [0, 5, 10, 15]:\n self.assertAllClose(sum_first_n(x, num), np.sum(x[:num]),\n check_dtypes=False)\n self.assertAllClose(cfun(x, num), np.sum(x[:num]), check_dtypes=False)\n self.assertAllClose(cfun(x, num), np.sum(x[:num]), check_dtypes=False)\n\n def testWhileLoopBatched(self):\n def fun(x):\n return lax.while_loop(lambda x: x < 3, lambda x: x + 2, x)\n\n ans = api.vmap(fun)(np.array([0, 1, 2, 3]))\n expected = np.array([4, 3, 4, 3])\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n fun = api.jit(fun)\n ans = api.vmap(fun)(np.array([0, 1, 2, 3]))\n expected = np.array([4, 3, 4, 3])\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testWhileLoopAxisIndexBatched(self):\n def fun(x):\n return lax.while_loop(lambda x: x < lax.axis_index('i'), lambda x: x + 2, x)\n\n ans = api.vmap(fun, axis_name='i')(np.array([0, 0, 0, 0]))\n expected = np.array([0, 2, 2, 4])\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n fun = api.jit(fun)\n ans = api.vmap(fun, axis_name='i')(np.array([0, 0, 0, 0]))\n expected = np.array([0, 2, 2, 4])\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testWhileLoopCondConstsBatched(self):\n def fun(x, y):\n return lax.while_loop(lambda x: x < y, lambda x: x + 2, x)\n\n ans = api.vmap(fun, in_axes=(None, 0))(0, np.array([2, 3]))\n expected = np.array([2, 4])\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testWhileLoopBodyConstsBatched(self):\n def fun(x, y):\n return lax.while_loop(lambda x: x < 3, lambda x: x + y, x)\n\n ans = api.vmap(fun, in_axes=(None, 0))(0, jnp.array([2, 3]))\n expected = np.array([4, 3])\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testWhileLoopTupleBatched(self):\n def cond_fun(loop_carry):\n x, y = loop_carry\n return x + y < 5\n\n def body_fun(loop_carry):\n x, y = loop_carry\n x = x + 1\n return x, y\n\n def fun(x, y):\n return lax.while_loop(cond_fun, body_fun, (x, y))\n\n ans = api.vmap(fun)(np.array([0, 0]), np.array([1, 2]))\n expected = (np.array([4, 3]), np.array([1, 2]))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_issue_3204(self):\n # Error during XLA code generation for vmap of nested loops\n def test(a, b):\n val = 0\n i = 0\n j = 0\n\n condfun_1 = lambda inp: inp[1] < a + 1\n condfun_2 = lambda inp: inp[2] < b + 1\n\n def bodyfun_1(inp):\n val, i, j = inp\n j = 0\n\n def bodyfun_2(inp):\n val, i, j = inp\n val += i + j\n j += 1\n return (val, i, j)\n\n result = lax.while_loop(condfun_2, bodyfun_2, (val, i, j))\n val = result[0]\n i += 1\n return (val, i, j)\n\n result = lax.while_loop(condfun_1, bodyfun_1, (val, i, j))\n return result[0]\n\n arr = np.arange(5)\n vmap_test = api.vmap(test, (0, 0))\n vmap_test(arr, arr)\n\n def testForiLoopErrors(self):\n \"\"\"Test typing error messages for while.\"\"\"\n with self.assertRaisesRegex(\n TypeError, \"arguments to fori_loop must have equal types\"):\n lax.fori_loop(np.int16(0), jnp.int32(10), (lambda i, c: c), jnp.float32(7))\n\n def testForiLoopBatched(self):\n def body_fun(i, loop_carry):\n x, y = loop_carry\n x = x + 1\n y = y + 2\n return x, y\n\n def fun(x):\n return lax.fori_loop(0, 10, body_fun, (x, 0))\n\n ans = api.vmap(fun)(np.array([0, 1]))\n expected = (np.array([10, 11]), np.array([20, 20]))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testForiLoopBatchedIssue1190(self):\n cond_fun = lambda carry: carry[0] < 4\n body_fun = lambda carry: (carry[0] + 1, carry[1] + 1)\n f = lambda x: lax.while_loop(cond_fun, body_fun, (0, x))\n jaxpr = api.make_jaxpr(api.vmap(f))(jnp.arange(3))\n eqn = jaxpr.jaxpr.eqns[0]\n self.assertIs(eqn.primitive, lax.while_p)\n self.assertEqual(eqn.params['cond_jaxpr'].in_avals[0].shape, ())\n\n def testForiLoopBasic(self):\n def body_fun(i, tot):\n return lax.add(tot, i)\n\n def count(num):\n return lax.fori_loop(0, num, body_fun, 0)\n\n self.assertEqual(count(2), 1)\n self.assertEqual(count(3), 3)\n self.assertEqual(count(4), 6)\n\n for args_maker in [lambda: [2], lambda: [3], lambda: [4]]:\n self._CompileAndCheck(count, args_maker)\n\n def testForiLoopClosure(self):\n def count(num):\n def body_fun(i, tot):\n return lax.add(num, lax.add(tot, i))\n return lax.fori_loop(0, num, body_fun, 0)\n\n cfun = api.jit(count)\n\n self.assertEqual(count(2), 1 + 2**2)\n self.assertEqual(count(2), cfun(2))\n self.assertEqual(count(3), 3 + 3**2)\n self.assertEqual(count(3), cfun(3))\n self.assertEqual(count(4), 6 + 4**2)\n self.assertEqual(count(4), cfun(4))\n\n def testForiLoopTupleState(self):\n def sum_first_n(arr, num):\n def body_fun(i, state):\n arr, total = state\n arr_i = lax.dynamic_index_in_dim(arr, i, 0, False)\n return (arr, lax.add(total, arr_i))\n\n init_val = (arr, 0.)\n _, total = lax.fori_loop(0, lax.min(arr.shape[0], num), body_fun,\n init_val)\n return total\n\n cfun = api.jit(sum_first_n)\n x = npr.RandomState(0).randn(10).astype(jnp.float_)\n\n for num in [0, 5, 10, 15]:\n self.assertAllClose(sum_first_n(x, num), np.sum(x[:num]),\n check_dtypes=False)\n self.assertAllClose(cfun(x, num), np.sum(x[:num]), check_dtypes=False)\n self.assertAllClose(cfun(x, num), np.sum(x[:num]), check_dtypes=False)\n\n def testForiLoopDictState(self):\n def sum_first_n(arr, num):\n def body_fun(i, state):\n arr, total = state['arr'], state['total']\n arr_i = lax.dynamic_index_in_dim(arr, i, 0, False)\n return {'arr': arr, 'total': lax.add(total, arr_i)}\n\n init_val = {'arr': arr, 'total': 0.}\n out_val = lax.fori_loop(0, lax.min(arr.shape[0], num), body_fun, init_val)\n return out_val['total']\n\n cfun = api.jit(sum_first_n)\n x = npr.RandomState(0).randn(10).astype(jnp.float_)\n\n for num in [0, 5, 10, 15]:\n self.assertAllClose(sum_first_n(x, num), np.sum(x[:num]),\n check_dtypes=False)\n self.assertAllClose(cfun(x, num), np.sum(x[:num]), check_dtypes=False)\n self.assertAllClose(cfun(x, num), np.sum(x[:num]), check_dtypes=False)\n\n def testForiLoopEmptyTupleInState(self):\n def sum_first_n(arr, num):\n def body_fun(i, state):\n arr, total, _ = state\n arr_i = lax.dynamic_index_in_dim(arr, i, 0, False)\n return (arr, lax.add(total, arr_i), ())\n\n init_val = (arr, 0., ())\n _, tot, _ = lax.fori_loop(0, lax.min(arr.shape[0], num), body_fun, init_val)\n return tot\n\n cfun = api.jit(sum_first_n)\n x = npr.RandomState(0).randn(10).astype(jnp.float_)\n\n for num in [0, 5, 10, 15]:\n self.assertAllClose(sum_first_n(x, num), np.sum(x[:num]),\n check_dtypes=False)\n self.assertAllClose(cfun(x, num), np.sum(x[:num]), check_dtypes=False)\n self.assertAllClose(cfun(x, num), np.sum(x[:num]), check_dtypes=False)\n\n def testCond(self):\n def fun(x):\n if x < 3:\n return (x, x)\n else:\n y = lax.mul(2, x)\n return y, lax.mul(2, y)\n\n @api.jit\n def cfun(x):\n def false_fun(x):\n y = lax.mul(2, x)\n return y, lax.mul(2, y)\n return lax.cond(lax.lt(x, 3), lambda x: (x, x), false_fun, x)\n\n self.assertEqual(fun(0), cfun(0))\n self.assertEqual(fun(0), (0, 0))\n self.assertEqual(fun(1), cfun(1))\n self.assertEqual(fun(1), (1, 1))\n self.assertEqual(fun(2), cfun(2))\n self.assertEqual(fun(2), (2, 2))\n self.assertEqual(fun(3), cfun(3))\n self.assertEqual(fun(3), (6, 12))\n self.assertEqual(fun(4), cfun(4))\n self.assertEqual(fun(4), (8, 16))\n\n def testSwitch(self):\n def branch(x):\n y = lax.mul(2, x)\n return y, lax.mul(2, y)\n\n branches = [lambda x: (x, x),\n branch,\n lambda x: (x, -x)]\n\n def fun(x):\n if x <= 0:\n return branches[0](x)\n elif x == 1:\n return branches[1](x)\n else:\n return branches[2](x)\n\n def cfun(x):\n return lax.switch(x, branches, x)\n\n self.assertEqual(fun(-1), cfun(-1))\n self.assertEqual(fun(0), cfun(0))\n self.assertEqual(fun(1), cfun(1))\n self.assertEqual(fun(2), cfun(2))\n self.assertEqual(fun(3), cfun(3))\n\n cfun = api.jit(cfun)\n\n self.assertEqual(fun(-1), cfun(-1))\n self.assertEqual(fun(0), cfun(0))\n self.assertEqual(fun(1), cfun(1))\n self.assertEqual(fun(2), cfun(2))\n self.assertEqual(fun(3), cfun(3))\n\n def testSwitchResidualsMerge(self):\n def get_conds(fun):\n jaxpr = api.make_jaxpr(api.grad(fun))(0., 0)\n return [eqn for eqn in jaxpr.jaxpr.eqns if eqn.primitive.name == 'cond']\n\n def branch_invars_len(cond_eqn):\n lens = [len(jaxpr.jaxpr.invars) for jaxpr in cond_eqn.params['branches']]\n assert len(set(lens)) == 1\n return lens[0]\n\n def branch_outvars_len(cond_eqn):\n lens = [len(jaxpr.jaxpr.outvars) for jaxpr in cond_eqn.params['branches']]\n assert len(set(lens)) == 1\n return lens[0]\n\n branches1 = [\n lambda x: jnp.sin(x),\n lambda x: jnp.cos(x)] # branch residuals overlap, should be reused\n branches2 = branches1 + [\n lambda x: jnp.sinh(x)] # another overlapping residual, expect reuse\n branches3 = branches2 + [\n lambda x: jnp.sin(x) + jnp.cos(x)] # requires one more residual slot\n def fun1(x, i):\n return lax.switch(i + 1, branches1, x)\n def fun2(x, i):\n return lax.switch(i + 1, branches2, x)\n def fun3(x, i):\n return lax.switch(i + 1, branches3, x)\n\n fwd1, bwd1 = get_conds(fun1)\n fwd2, bwd2 = get_conds(fun2)\n fwd3, bwd3 = get_conds(fun3)\n\n fwd1_num_out = branch_outvars_len(fwd1)\n fwd2_num_out = branch_outvars_len(fwd2)\n fwd3_num_out = branch_outvars_len(fwd3)\n assert fwd1_num_out == fwd2_num_out\n assert fwd3_num_out == fwd2_num_out + 1\n\n bwd1_num_in = branch_invars_len(bwd1)\n bwd2_num_in = branch_invars_len(bwd2)\n bwd3_num_in = branch_invars_len(bwd3)\n assert bwd1_num_in == bwd2_num_in\n assert bwd3_num_in == bwd2_num_in + 1\n\n def testOneBranchSwitch(self):\n branch = lambda x: -x\n f = lambda i, x: lax.switch(i, [branch], x)\n x = 7.\n self.assertEqual(f(-1, x), branch(x))\n self.assertEqual(f(0, x), branch(x))\n self.assertEqual(f(1, x), branch(x))\n cf = api.jit(f)\n self.assertEqual(cf(-1, x), branch(x))\n self.assertEqual(cf(0, x), branch(x))\n self.assertEqual(cf(1, x), branch(x))\n cf = api.jit(f, static_argnums=0)\n self.assertEqual(cf(-1, x), branch(x))\n self.assertEqual(cf(0, x), branch(x))\n self.assertEqual(cf(1, x), branch(x))\n\n def testIssue1379(self):\n\n def fun(pred):\n return lax.cond(pred, lambda x: (True, x), lambda x: (False, x), pred)\n\n @api.jit\n def cfun(pred):\n return fun(pred)\n\n self.assertEqual(fun(0), cfun(0), (False,0))\n self.assertEqual(fun(0.), cfun(0.), (False,0.))\n self.assertEqual(fun(1), cfun(1), (True,1))\n self.assertEqual(fun(1.), cfun(1.), (True,1.))\n\n # test that proper errors are raised for wrong types\n for pred in [\"abc\", [], [1,2]]:\n for f in [fun, cfun]:\n self.assertRaises(TypeError, f, pred)\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"_{name}\", \"cond\": cond}\n for cond, name in COND_IMPLS)\n def testNestedCond(self, cond):\n def fun(x):\n if x < 2:\n return lax.mul(2, x)\n else:\n if x < 5:\n return lax.mul(3, x)\n else:\n return lax.mul(4, x)\n\n @api.jit\n def cfun(x):\n return cond(\n lax.lt(x, 2),\n lambda x: lax.mul(2, x),\n lambda x: cond(lax.lt(x, 5),\n x, lambda x: lax.mul(3, x),\n 4, lambda y: lax.mul(y, x)),\n x)\n\n self.assertEqual(cfun(1), 2)\n self.assertEqual(cfun(3), 9)\n self.assertEqual(cfun(6), 24)\n self.assertEqual(cfun(1), fun(1))\n self.assertEqual(cfun(3), fun(3))\n self.assertEqual(cfun(6), fun(6))\n\n def testCondTypeErrors(self):\n \"\"\"Test typing error messages for cond.\"\"\"\n with self.assertRaisesRegex(TypeError,\n re.escape(\"Pred type must be either boolean or number, got <function\")):\n lax.cond(lambda x: True, lambda top: 2., lambda fop: 3., 1.)\n with self.assertRaisesRegex(TypeError,\n re.escape(\"Pred must be a scalar, got foo of type <class 'str'>\")):\n lax.cond(\"foo\", lambda top: 2., lambda fop: 3., 1.)\n with self.assertRaisesRegex(TypeError,\n re.escape(\"Pred must be a scalar, got (1.0, 1.0) of type <class 'tuple'>\")):\n lax.cond((1., 1.), lambda top: 2., lambda fop: 3., 1.)\n with self.assertRaisesRegex(TypeError,\n re.escape(\"true_fun and false_fun output must have same type structure, \"\n f\"got {tree_util.tree_structure(2.)} and {tree_util.tree_structure((3., 3.))}.\")):\n lax.cond(True, lambda top: 2., lambda fop: (3., 3.), 1.)\n with self.assertRaisesRegex(\n TypeError, textwrap.dedent(\n r\"\"\"\n true_fun and false_fun output must have identical types, got\n ShapedArray\\(float32\\[1\\]\\)\n and\n ShapedArray\\(float32\\[\\].*\\).\"\"\").strip()):\n lax.cond(True,\n lambda top: jnp.array([1.], jnp.float32),\n lambda fop: jnp.float32(1.),\n 1.)\n\n def testSwitchErrors(self):\n \"\"\"Test typing error messages for switch.\"\"\"\n with self.assertRaisesRegex(TypeError,\n re.escape(\"Index type must be an integer, got <function\")):\n lax.switch(lambda x: True, [lambda _: 2., lambda _: 3.], 1.)\n with self.assertRaisesRegex(TypeError,\n re.escape(\"Index type must be an integer, got foo.\")):\n lax.switch(\"foo\", [lambda _: 2., lambda _: 3.], 1.)\n with self.assertRaisesRegex(TypeError,\n re.escape(\"Branch index must be scalar, got (1.0, 1.0) of shape (2,).\")):\n lax.switch((1., 1.), [lambda _: 2., lambda _: 3.], 1.)\n with self.assertRaisesRegex(ValueError,\n re.escape(\"Empty branch sequence\")):\n lax.switch(0, [], 1.)\n with self.assertRaisesRegex(TypeError,\n re.escape(\"branch 0 and 1 outputs must have same type structure, \"\n f\"got {tree_util.tree_structure(2.)} and {tree_util.tree_structure((3., 3.))}.\")):\n lax.switch(1, [lambda _: 2., lambda _: (3., 3.)], 1.)\n with self.assertRaisesRegex(\n TypeError, textwrap.dedent(\n r\"\"\"\n branch 0 and 1 outputs must have identical types, got\n ShapedArray\\(float32\\[1\\]\\)\n and\n ShapedArray\\(float32\\[\\].*\\).\"\"\").strip()):\n lax.switch(1, [lambda _: jnp.array([1.], jnp.float32),\n lambda _: jnp.float32(1.)],\n 1.)\n\n def testCondOneBranchConstant(self):\n def fun(x):\n if x < 3:\n return 5.\n else:\n return x\n\n @api.jit\n def cfun(x):\n return lax.cond(lax.lt(x, 3), lambda x: 5, lambda x: x, x)\n\n self.assertEqual(fun(0), cfun(0))\n self.assertEqual(cfun(0), 5)\n self.assertEqual(fun(4), cfun(4))\n self.assertEqual(cfun(4), 4)\n\n def testCondOneBranchConstantTuple(self):\n def fun(x):\n if x < 3:\n return (1., 2., 3.)\n else:\n return (x, 2., 4.)\n\n @api.jit\n def cfun(x):\n return lax.cond(lax.lt(x, 3),\n lambda x: (1, 2., 3.),\n lambda x: (x, 2., 4.),\n x)\n\n self.assertEqual(fun(0), cfun(0))\n self.assertEqual(cfun(0), (1, 2., 3.))\n self.assertEqual(fun(4), cfun(4))\n self.assertEqual(cfun(4), (4, 2., 4.))\n\n def testCondBatched(self):\n def fun(x, y, z):\n pred = lax.lt(x, 3)\n true_fun = lambda y: y\n false_fun = lambda z: lax.neg(z)\n return lax.cond(pred, y, true_fun, z, false_fun)\n\n # these cases stay as cond\n x = jnp.array(2)\n y = jnp.array([1, 2])\n z = jnp.array([3, 4])\n ans = api.vmap(fun, (None, 0, 0))(x, y, z)\n jaxpr = api.make_jaxpr(api.vmap(fun, (None, 0, 0)))(x, y, z)\n expected = np.array([1, 2])\n self.assertAllClose(ans, expected, check_dtypes=False)\n assert \"select\" not in str(jaxpr)\n\n x = jnp.array(4)\n ans = api.vmap(fun, (None, 0, 0))(x, y, z)\n jaxpr = api.make_jaxpr(api.vmap(fun, (None, 0, 0)))(x, y, z)\n expected = np.array([-3, -4])\n self.assertAllClose(ans, expected, check_dtypes=False)\n assert \"select\" not in str(jaxpr)\n\n fun = api.jit(fun)\n ans = api.vmap(fun, (None, 0, 0))(x, y, z)\n expected = np.array([-3, -4])\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n z = jnp.array(5)\n ans = api.vmap(fun, (None, 0, None))(x, y, z)\n jaxpr = api.make_jaxpr(api.vmap(fun, (None, 0, None)))(x, y, z)\n expected = np.array([-5, -5])\n self.assertAllClose(ans, expected, check_dtypes=False)\n assert \"select\" not in str(jaxpr)\n\n\n # these cases become select\n x = jnp.array([2, 4])\n ans = api.vmap(fun, (0, 0, None))(x, y, z)\n jaxpr = api.make_jaxpr(api.vmap(fun, (0, 0, None)))(x, y, z)\n expected = np.array([1, -5])\n self.assertAllClose(ans, expected, check_dtypes=False)\n assert \"select\" in str(jaxpr)\n\n z = jnp.array([3, 4])\n ans = api.vmap(fun)(x, y, z)\n jaxpr = api.make_jaxpr(api.vmap(fun))(x, y, z)\n expected = np.array([1, -4])\n self.assertAllClose(ans, expected, check_dtypes=False)\n assert \"select\" in str(jaxpr)\n\n def testSwitchBatched(self):\n def fun(index, x, y, z):\n branches = [lambda xyz: xyz[0],\n lambda xyz: lax.neg(xyz[1]),\n lambda xyz: lax.sign(xyz[2])]\n return lax.switch(index, branches, (x, y, z))\n\n # these cases stay as cond\n x = jnp.array(0)\n y = jnp.array([1, 2])\n z = jnp.array([3, 4])\n w = jnp.array(9)\n ans = api.vmap(fun, (None, 0, 0, None))(x, y, z, w)\n jaxpr = api.make_jaxpr(api.vmap(fun, (None, 0, 0, None)))(x, y, z, w)\n expected = np.array([1, 2])\n self.assertAllClose(ans, expected, check_dtypes=False)\n assert \"select\" not in str(jaxpr)\n\n x = jnp.array(1)\n ans = api.vmap(fun, (None, 0, 0, None))(x, y, z, w)\n jaxpr = api.make_jaxpr(api.vmap(fun, (None, 0, 0, None)))(x, y, z, w)\n expected = np.array([-3, -4])\n self.assertAllClose(ans, expected, check_dtypes=False)\n assert \"select\" not in str(jaxpr)\n\n fun = api.jit(fun)\n ans = api.vmap(fun, (None, 0, 0, None))(x, y, z, w)\n expected = np.array([-3, -4])\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n z = jnp.array(5)\n ans = api.vmap(fun, (None, 0, None, None))(x, y, z, w)\n jaxpr = api.make_jaxpr(api.vmap(fun, (None, 0, None, None)))(x, y, z, w)\n expected = np.array([-5, -5])\n self.assertAllClose(ans, expected, check_dtypes=False)\n assert \"select\" not in str(jaxpr)\n\n\n # these cases become select\n x = jnp.array([0, 1])\n ans = api.vmap(fun, (0, 0, None, None))(x, y, z, w)\n jaxpr = api.make_jaxpr(api.vmap(fun, (0, 0, None, None)))(x, y, z, w)\n expected = np.array([1, -5])\n self.assertAllClose(ans, expected, check_dtypes=False)\n assert \"select\" in str(jaxpr)\n\n z = jnp.array([3, 4])\n w = jnp.array([9, 9])\n ans = api.vmap(fun)(x, y, z, w)\n jaxpr = api.make_jaxpr(api.vmap(fun))(x, y, z, w)\n expected = np.array([1, -4])\n self.assertAllClose(ans, expected, check_dtypes=False)\n assert \"select\" in str(jaxpr)\n\n def testCondJVP(self):\n def fun_ref(x):\n if x < 3:\n return (x, x)\n else:\n y = 2 * x\n return y, 2 * y\n\n def fun(x):\n def false_fun(x):\n y = 2 * x\n return y, 2 * y\n return lax.cond(x < 3, lambda x: (x, x), false_fun, x)\n\n x = 3.14\n ans = api.jvp(fun, (x,), (x,))\n expected = api.jvp(fun_ref, (x,), (x,))\n self.assertAllClose(ans, expected, check_dtypes=False)\n jtu.check_grads(fun, (x,), order=2, modes=[\"fwd\"])\n\n x = 2.72\n ans = api.jvp(fun, (x,), (x,))\n expected = api.jvp(fun_ref, (x,), (x,))\n self.assertAllClose(ans, expected, check_dtypes=False)\n jtu.check_grads(fun, (x,), order=2, modes=[\"fwd\"])\n\n def testSwitchJVP(self):\n def branch(x):\n y = 2 * x\n return y, 2 * y\n\n branches = [lambda x: (x, x),\n branch,\n lambda x: (x, -x)]\n\n def fun_ref(x):\n idx = x // 1\n if idx <= 0:\n return branches[0](x)\n elif idx == 1:\n return branches[1](x)\n else:\n return branches[2](x)\n\n def fun(x):\n idx = lax.convert_element_type(x // 1, np.int32)\n return lax.switch(idx, branches, x)\n\n for x in [-0.7, 0.7, 1.7, 2.7, 3.7]:\n ans = api.jvp(fun, (x,), (x,))\n expected = api.jvp(fun_ref, (x,), (x,))\n self.assertAllClose(ans, expected, check_dtypes=False)\n jtu.check_grads(fun, (x,), order=2, modes=[\"fwd\"])\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"_{name}\", \"cond\": cond}\n for cond, name in COND_IMPLS)\n def testCondJVP2(self, cond):\n def fun_ref(x):\n if x < 3:\n return 2.\n else:\n return 2. * x\n\n def fun(x):\n return cond(x < 3, (), lambda _: 2., x, lambda x: 2. * x)\n\n x = 3.14\n ans = api.jvp(fun, (x,), (x,))\n expected = api.jvp(fun_ref, (x,), (x,))\n self.assertAllClose(ans, expected, check_dtypes=False)\n jtu.check_grads(fun, (x,), order=2, modes=[\"fwd\"])\n\n x = 2.72\n ans = api.jvp(fun, (x,), (x,))\n expected = api.jvp(fun_ref, (x,), (x,))\n self.assertAllClose(ans, expected, check_dtypes=False)\n jtu.check_grads(fun, (x,), order=2, modes=[\"fwd\"])\n\n def testCondGrad(self):\n def f_ref(x):\n return 3. * x if x < 2 else jnp.sin(x)\n\n def f(x):\n return lax.cond(x < 2, lambda x: 3. * x, lambda x: jnp.sin(x), x)\n\n x = 2.14\n ans = api.grad(f)(x)\n expected = api.grad(f_ref)(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n jtu.check_grads(f, (x,), order=2, modes=[\"fwd\", \"rev\"])\n\n x = 1.72\n ans = api.grad(f)(x)\n expected = api.grad(f_ref)(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n jtu.check_grads(f, (x,), order=2, modes=[\"fwd\", \"rev\"])\n\n def testCondGradVmapNan(self):\n eps = 1e-3\n\n def safe1(x):\n return lax.cond(x < eps, lambda _: eps, lambda _: jnp.sqrt(x), ())\n\n out = api.grad(lambda x: api.vmap(safe1)(x).sum())(np.zeros(10))\n self.assertFalse(np.isnan(out).any())\n\n def testSwitchGrad(self):\n branches = [lambda x: 3. * x,\n lambda x: jnp.sin(x),\n lambda x: -x]\n\n def f_ref(x):\n idx = x // 1\n if idx <= 0:\n return branches[0](x)\n elif idx == 1:\n return branches[1](x)\n else:\n return branches[2](x)\n\n def f(x):\n idx = lax.convert_element_type(x // 1, np.int32)\n return lax.switch(idx, branches, x)\n\n for x in [-0.7, 0.7, 1.7, 2.7, 3.7]:\n ans = api.grad(f)(x)\n expected = api.grad(f_ref)(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n jtu.check_grads(f, (x,), order=2, modes=[\"fwd\", \"rev\"])\n\n def testSwitchGradWithWeakTypeMismatch(self): # issue #4696, PR #4896\n dtype = jnp.ones(1).dtype\n dtype = jnp.float32 if dtype == jnp.float32 else jnp.float64\n\n branches = [\n lambda x: x, # This preserves the weak type of x.\n lambda x: x + dtype(1), # This strips the weak type of x.\n ]\n\n def f_ref(x):\n i = x.astype(jnp.int32)\n return branches[i](x)\n\n def f(x):\n return lax.switch(x.astype(jnp.int32), branches, x)\n\n for x in [0., 1.]:\n ans = api.grad(f)(x)\n expected = api.grad(f_ref)(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"_{name}\", \"cond\": cond}\n for cond, name in COND_IMPLS)\n def testCondGrad2(self, cond):\n def f_ref(x):\n z = jnp.array([1., 2.]) * x if x[0] < 2 else jnp.sin(x)\n return z.sum()\n\n def _f(x):\n return cond(\n x[0] < 2,\n lambda x: jnp.array([1., 2.]) * x,\n lambda x: jnp.sin(x),\n x)\n\n f = lambda x: api.jit(_f)(x).sum()\n\n x = 2.14 * jnp.ones(2)\n ans = api.grad(f)(x)\n expected = api.grad(f_ref)(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n jtu.check_grads(f, (x,), order=2, modes=[\"fwd\", \"rev\"])\n\n x = 1.72 * jnp.ones(2)\n ans = api.grad(f)(x)\n expected = api.grad(f_ref)(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n jtu.check_grads(f, (x,), order=2, modes=[\"fwd\", \"rev\"],\n rtol={jnp.float32: 1e-2, jnp.float64: 2e-3})\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"_{name}\", \"cond\": cond}\n for cond, name in COND_IMPLS)\n def testCondGrad3(self, cond):\n def fun_ref(x):\n if x < 3:\n return 2.\n else:\n return 2. * x\n\n def fun(x):\n return cond(x < 3, (), lambda _: 2., x, lambda x: 2. * x)\n\n x = 3.14\n ans = api.grad(fun)(x)\n expected = api.grad(fun_ref)(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n jtu.check_grads(fun, (x,), order=2, modes=[\"fwd\", \"rev\"])\n\n x = 2.72\n ans = api.grad(fun)(x)\n expected = api.grad(fun_ref)(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n jtu.check_grads(fun, (x,), order=2, modes=[\"fwd\", \"rev\"])\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"_{name}\", \"cond\": cond}\n for cond, name in COND_IMPLS)\n def testCondGrad4(self, cond):\n def fun_ref(x, y):\n if x < 3:\n return 2. * jnp.sin(y)\n else:\n return 2. * jnp.cos(x)\n\n def fun(x, y):\n return cond(\n x < 3,\n (), lambda _: 2. * jnp.sin(y),\n x, lambda x: 2. * x)\n\n y = 5.8\n x = 3.14\n ans = api.grad(fun, 1)(x, y)\n expected = api.grad(fun_ref, 1)(x, y)\n self.assertAllClose(ans, expected, check_dtypes=False)\n jtu.check_grads(fun, (x, y), order=2, modes=[\"fwd\", \"rev\"])\n\n x = 2.72\n ans = api.grad(fun, 1)(x, y)\n expected = api.grad(fun_ref, 1)(x, y)\n self.assertAllClose(ans, expected, check_dtypes=False)\n jtu.check_grads(fun, (x, y), order=2, modes=[\"fwd\", \"rev\"])\n\n def testCondLinearize(self):\n def f(x):\n return lax.cond(x < 2, lambda x: 3. * x, lambda x: jnp.sin(x), x)\n y, f_lin = api.linearize(f, 1.)\n self.assertAllClose(y, 3., check_dtypes=False)\n self.assertAllClose(f_lin(2.), 6., check_dtypes=False)\n y, f_lin = api.linearize(f, 4.)\n self.assertAllClose(y, jnp.sin(4.), check_dtypes=False)\n self.assertAllClose(f_lin(2.), jnp.cos(4.) * 2., check_dtypes=False)\n\n def testSwitchLinearize(self):\n branches = [lambda x: 3. * x,\n lambda x: jnp.sin(x),\n lambda x: -x]\n def f(x):\n idx = lax.convert_element_type(x // 1, np.int32)\n return lax.switch(idx, branches, x)\n\n # branch 0\n y, f_lin = api.linearize(f, -1.)\n self.assertAllClose(y, -3., check_dtypes=False)\n self.assertAllClose(f_lin(2.), 6., check_dtypes=False)\n y, f_lin = api.linearize(f, 0.)\n self.assertAllClose(y, 0., check_dtypes=False)\n self.assertAllClose(f_lin(2.), 6., check_dtypes=False)\n\n # branch 1\n y, f_lin = api.linearize(f, 1.)\n self.assertAllClose(y, jnp.sin(1.), check_dtypes=False)\n self.assertAllClose(f_lin(2.), jnp.cos(1.) * 2., check_dtypes=False)\n\n # branch 2\n y, f_lin = api.linearize(f, 2.)\n self.assertAllClose(y, -2., check_dtypes=False)\n self.assertAllClose(f_lin(2.), -2., check_dtypes=False)\n y, f_lin = api.linearize(f, 3.)\n self.assertAllClose(y, -3., check_dtypes=False)\n self.assertAllClose(f_lin(2.), -2., check_dtypes=False)\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"_{name}\", \"cond\": cond}\n for cond, name in COND_IMPLS)\n def testCondLinearize2(self, cond):\n def f_ref(x):\n z = jnp.array([1., 2.]) * x if x[0] < 2 else jnp.cos(jnp.sin(x))\n return z.sum()\n\n def f(x):\n return cond(\n x[0] < 2,\n lambda x: jnp.array([1., 2.]) * x,\n lambda x: jnp.cos(jnp.sin(x)),\n x).sum()\n\n x = 2.14 * jnp.ones(2)\n y, f_lin = api.linearize(f, x)\n y_ref, f_lin_ref = api.linearize(f_ref, x)\n self.assertAllClose(y, y_ref, check_dtypes=False)\n self.assertAllClose(f_lin(x), f_lin_ref(x), check_dtypes=False)\n\n x = -2.14 * jnp.ones(2)\n y, f_lin = api.linearize(f, x)\n y_ref, f_lin_ref = api.linearize(f_ref, x)\n self.assertAllClose(y, y_ref, check_dtypes=False)\n self.assertAllClose(f_lin(x), f_lin_ref(x), check_dtypes=False)\n\n f = api.jit(f)\n x = 2.14 * jnp.ones(2)\n y, f_lin = api.linearize(f, x)\n y_ref, f_lin_ref = api.linearize(f_ref, x)\n self.assertAllClose(y, y_ref, check_dtypes=False)\n self.assertAllClose(f_lin(x), f_lin_ref(x), check_dtypes=False)\n\n def testCondJit(self):\n def f(x):\n return lax.cond(x < 2, lambda x: 3. * x, lambda x: jnp.sin(x), x)\n y = api.jit(f)(1.)\n expected = f(1.)\n self.assertAllClose(y, expected, check_dtypes=False)\n y = api.jit(f)(4.)\n expected = f(4.)\n self.assertAllClose(y, expected, check_dtypes=False)\n\n def testSwitchJit(self):\n branches = [lambda x: 3. * x,\n lambda x: jnp.sin(x),\n lambda x: -x]\n def f(x):\n idx = lax.convert_element_type(x // 1, np.int32)\n return lax.switch(idx, branches, x)\n for x in [-1., 0., 1., 2., 3.]:\n y = api.jit(f)(x)\n expected = f(x)\n self.assertAllClose(y, expected, check_dtypes=False)\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"_{name}\", \"cond\": cond}\n for cond, name in COND_IMPLS)\n def testCondJitDisabled(self, cond):\n def f_ref(x):\n return 3. * x if x < 2 else jnp.sin(x)\n def f(x):\n return cond(x < 2, lambda x: 3. * x, lambda x: jnp.sin(x), x)\n\n with api.disable_jit():\n y = f(1.)\n expected = f_ref(1.)\n self.assertAllClose(y, expected, check_dtypes=False)\n\n with api.disable_jit():\n y = api.jit(f)(1.)\n expected = f(1.)\n self.assertAllClose(y, expected, check_dtypes=False)\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"_{name}\", \"cond\": cond}\n for cond, name in COND_IMPLS)\n def testCondWithConsts(self, cond):\n def f(x):\n return cond(x < 2,\n lambda x: np.array([1., 2.]) * x,\n lambda x: np.array([3., 4.]) * jnp.sin(x),\n x)\n\n def f_ref(x):\n if x < 2:\n return np.array([1., 2.]) * x\n else:\n return np.array([3., 4.]) * np.sin(x)\n\n y = f(1.)\n expected = f_ref(1.)\n self.assertAllClose(y, expected, check_dtypes=False)\n y = f(4.)\n expected = f_ref(4.)\n self.assertAllClose(y, expected, check_dtypes=False)\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"_{name}\", \"cond\": cond}\n for cond, name in COND_IMPLS)\n def testCondJitWithConsts(self, cond):\n def f(x):\n return cond(x < 2,\n lambda x: np.array([1., 2.]) * x,\n lambda x: np.array([3., 4.]) * jnp.sin(x),\n x)\n\n y = api.jit(f)(1.)\n expected = f(1.)\n self.assertAllClose(y, expected, check_dtypes=False)\n y = api.jit(f)(4.)\n expected = f(4.)\n self.assertAllClose(y, expected, check_dtypes=False)\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"_{name}\", \"cond\": cond}\n for cond, name in COND_IMPLS)\n def testCondVmapGrad(self, cond):\n # https://github.com/google/jax/issues/2264\n def f_1(x): return x ** 2\n def f_2(x): return x ** 3\n\n def f(x): return cond(x > 0, f_1, f_2, x)\n def g(x): return jnp.where(x > 0, f_1(x), f_2(x))\n\n x = jnp.linspace(-1, 1, 20)\n ans = api.vmap(api.grad(f))(x)\n expected = api.vmap(api.grad(g))(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testIssue1263(self):\n def f(rng, x):\n cond = random.bernoulli(rng)\n return lax.cond(cond, x, lambda x: x, jnp.abs(x) - 1., lambda x: x)\n\n def body_fn(i, state):\n rng, x = state\n key, subkey = random.split(rng)\n return key, f(subkey, x)\n\n def g(rng, x):\n return lax.fori_loop(0, 10, body_fn, (rng, x))\n\n api.vmap(g)(random.split(random.PRNGKey(0), 3), jnp.ones((3, 4)))\n\n def testIssue514(self):\n # just check this doesn't crash\n lax.cond(True,\n (0, 0), lambda x: (x[0], 0),\n (1, 1), lambda x: x)\n\n def testIssue649(self):\n from jax import lax\n\n def body(x):\n a, b = x\n return (7, b + 1)\n\n def cond(x):\n a, b = x\n return b < 10\n\n out = lax.while_loop(cond, body, (33, 4))\n self.assertEqual(out, (7, 10))\n\n @parameterized.named_parameters(\n {\"testcase_name\": \"_jit_scan={}_jit_f={}_impl={}\".format(\n jit_scan, jit_f, scan_name),\n \"jit_scan\": jit_scan, \"jit_f\": jit_f, \"scan\": scan_impl}\n for jit_scan in [False, True]\n for jit_f in [False, True]\n for scan_impl, scan_name in SCAN_IMPLS)\n def testScanImpl(self, jit_scan, jit_f, scan):\n rng = np.random.RandomState(0)\n\n d = rng.randn(2)\n def f(c, a):\n assert a.shape == (3,)\n assert c.shape == (4,)\n b = jnp.cos(jnp.sum(jnp.sin(a)) + jnp.sum(jnp.cos(c)) + jnp.sum(jnp.tan(d)))\n c = jnp.sin(c * b)\n assert b.shape == ()\n return c, b\n\n if jit_f:\n f = api.jit(f)\n if jit_scan:\n scan = api.jit(scan, static_argnums=(0,))\n\n as_ = rng.randn(5, 3)\n c = rng.randn(4)\n\n ans = scan(f, c, as_)\n expected = scan_reference(f, c, as_)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @parameterized.named_parameters(\n {\"testcase_name\": \"_jit_scan={}_jit_f={}_impl={}\".format(\n jit_scan, jit_f, scan_name),\n \"jit_scan\": jit_scan, \"jit_f\": jit_f, \"scan\": scan_impl}\n for jit_scan in [False, True]\n for jit_f in [False, True]\n for scan_impl, scan_name in SCAN_IMPLS)\n def testScanJVP(self, jit_scan, jit_f, scan):\n rng = np.random.RandomState(0)\n\n d = rng.randn(2)\n def f(c, a):\n assert a.shape == (3,)\n assert c.shape == (4,)\n b = jnp.cos(jnp.sum(jnp.sin(a)) + jnp.sum(jnp.cos(c)) + jnp.sum(jnp.tan(d)))\n c = jnp.sin(c * b)\n assert b.shape == ()\n return c, b\n\n if jit_f:\n f = api.jit(f)\n if jit_scan:\n scan = api.jit(scan, static_argnums=(0,))\n\n as_ = rng.randn(5, 3)\n c = rng.randn(4)\n\n ans = api.jvp( lambda c, as_: scan(f, c, as_), (c, as_), (c, as_))\n expected = api.jvp(lambda c, as_: scan_reference(f, c, as_), (c, as_), (c, as_))\n self.assertAllClose(ans, expected, check_dtypes=False,\n rtol={np.float64: 1e-14, np.float32: 1e-5})\n\n jtu.check_grads(partial(scan, f), (c, as_), order=2, modes=[\"fwd\"])\n\n @parameterized.named_parameters(\n {\"testcase_name\": \"_jit_scan={}_jit_f={}_impl={}\".format(\n jit_scan, jit_f, scan_name),\n \"jit_scan\": jit_scan, \"jit_f\": jit_f, \"scan\": scan_impl}\n for jit_scan in [False, True]\n for jit_f in [False, True]\n for scan_impl, scan_name in SCAN_IMPLS)\n def testScanLinearize(self, jit_scan, jit_f, scan):\n rng = np.random.RandomState(0)\n\n d = rng.randn(2)\n def f(c, a):\n assert a.shape == (3,)\n assert c.shape == (4,)\n b = jnp.cos(jnp.sum(jnp.sin(a)) + jnp.sum(jnp.cos(c)) + jnp.sum(jnp.tan(d)))\n c = jnp.sin(c * b)\n assert b.shape == ()\n return c, b\n\n if jit_f:\n f = api.jit(f)\n if jit_scan:\n scan = api.jit(scan, static_argnums=(0,))\n\n as_ = rng.randn(5, 3)\n c = rng.randn(4)\n\n ans = api.linearize(lambda c, as_: scan(f, c, as_), c, as_)[1](c, as_)\n expected = api.linearize(lambda c, as_: scan_reference(f, c, as_), c, as_)[1](c, as_)\n self.assertAllClose(ans, expected, check_dtypes=False,\n rtol={np.float64: 1e-14})\n\n @parameterized.named_parameters(\n {\"testcase_name\": \"_jit_scan={}_jit_f={}_impl={}\".format(\n jit_scan, jit_f, scan_name),\n \"jit_scan\": jit_scan, \"jit_f\": jit_f, \"scan\": scan_impl}\n for jit_scan in [False, True]\n for jit_f in [False, True]\n for scan_impl, scan_name in SCAN_IMPLS)\n @jtu.skip_on_flag(\"jax_skip_slow_tests\", True)\n def testScanGrad(self, jit_scan, jit_f, scan):\n rng = np.random.RandomState(0)\n\n d = rng.randn(2)\n def f(c, a):\n assert a.shape == (3,)\n assert c.shape == (4,)\n b = jnp.sum(jnp.sin(a)) + jnp.sum(jnp.sin(c)) + jnp.sum(jnp.sin(d))\n c = jnp.sin(c * b)\n assert b.shape == ()\n return c, b\n\n if jit_f:\n f = api.jit(f)\n if jit_scan:\n scan = api.jit(scan, static_argnums=(0,))\n\n as_ = rng.randn(5, 3)\n c = rng.randn(4)\n\n ans = api.grad(lambda c, as_: list( scan(f, c, as_))[0].sum())(c, as_)\n expected = api.grad(lambda c, as_: list(scan_reference(f, c, as_))[0].sum())(c, as_)\n self.assertAllClose(ans, expected, check_dtypes=False,\n rtol={np.float32: 2e-5, np.float64: 1e-13})\n\n jtu.check_grads(partial(scan, f), (c, as_), order=2, modes=[\"rev\"],\n atol=1e-3, rtol=5e-3)\n\n @jtu.skip_on_flag(\"jax_skip_slow_tests\", True)\n def testScanRnn(self):\n r = npr.RandomState(0)\n\n n_in = 4\n n_hid = 2\n n_out = 1\n length = 3\n\n W_trans = r.randn(n_hid, n_hid + n_in).astype(jnp.float_)\n W_out = r.randn(n_out, n_hid + n_in).astype(jnp.float_)\n params = W_trans, W_out\n\n inputs = r.randn(length, n_in).astype(jnp.float_)\n targets = r.randn(length, n_out).astype(jnp.float_)\n\n def step(params, state, input):\n W_trans, W_out = params\n stacked = jnp.concatenate([state, input])\n output = jnp.tanh(jnp.dot(W_out, stacked))\n next_state = jnp.tanh(jnp.dot(W_trans, stacked))\n return next_state, output\n\n def rnn(params, inputs):\n init_state = jnp.zeros(n_hid)\n _, outputs = lax.scan(partial(step, params), init_state, inputs)\n return outputs\n\n def loss(params, inputs, targets):\n predictions = rnn(params, inputs)\n return jnp.sum((predictions - targets)**2)\n\n # evaluation doesn't crash\n loss(params, inputs, targets)\n\n # jvp evaluation doesn't crash\n api.jvp(lambda params: loss(params, inputs, targets), (params,), (params,))\n\n # jvp numerical check passes\n jtu.check_grads(loss, (params, inputs, targets), order=2, modes=[\"fwd\"],\n rtol={np.float32: 2e-2, np.float64: 1e-6})\n\n # linearize works\n _, expected = api.jvp(loss, (params, inputs, targets),\n (params, inputs, targets))\n _, linfun = api.linearize(loss, params, inputs, targets)\n ans = linfun(params, inputs, targets)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n # gradient evaluation doesn't crash\n api.grad(loss)(params, inputs, targets)\n\n # gradient check passes\n jtu.check_grads(loss, (params, inputs, targets), order=2, rtol=2e-2)\n\n # we can vmap to batch things\n batch_size = 7\n batched_inputs = r.randn(batch_size, length, n_in).astype(jnp.float_)\n batched_targets = r.randn(batch_size, length, n_out).astype(jnp.float_)\n batched_loss = api.vmap(lambda x, y: loss(params, x, y))\n losses = batched_loss(batched_inputs, batched_targets)\n expected = np.stack(list(map(lambda x, y: loss(params, x, y),\n batched_inputs, batched_targets)))\n self.assertAllClose(losses, expected, check_dtypes=False, rtol=1e-2)\n\n def testIssue711(self):\n # Tests reverse-mode differentiation through a scan for which the scanned\n # function also involves reverse-mode differentiation.\n # See https://github.com/google/jax/issues/711\n def harmonic_bond(conf, params):\n return jnp.sum(conf * params)\n\n def minimize_structure(test_params):\n energy_fn = partial(harmonic_bond, params=test_params)\n\n def apply_carry(carry, _):\n i, x = carry\n new_x = x - 0.1 * api.grad(energy_fn)(x)\n new_carry = (i+1, new_x)\n return new_carry, _\n\n x0 = jnp.array([1., 2., 3.])\n carry_final, _ = lax.scan(apply_carry, (0, x0), jnp.zeros((75, 0)))\n _, x_final = carry_final\n return x_final\n\n initial_params = 0.5\n minimize_structure(initial_params) # doesn't crash\n\n def loss(test_params):\n x_final = minimize_structure(test_params)\n return jnp.sum(jnp.sin(1.0 - x_final))\n\n api.grad(loss)(0.25) # doesn't crash\n\n def testIssue744(self):\n Point = collections.namedtuple('Point', ['x', 'y'])\n p0 = Point(x=jnp.array(1), y=jnp.array(2))\n\n def plus_one(p, iter_idx):\n return Point(p.x+1, p.y+1), iter_idx\n\n self.assertRaisesRegex(\n ValueError,\n 'scan got value with no leading axis to scan over.*',\n lambda: lax.scan(plus_one, p0, list(range(5))))\n\n def testScanTypeErrors(self):\n \"\"\"Test typing error messages for scan.\"\"\"\n a = jnp.arange(5)\n # Body output not a tuple\n with self.assertRaisesRegex(TypeError,\n re.escape(\"scan body output must be a pair, got ShapedArray(float32[]).\")):\n lax.scan(lambda c, x: np.float32(0.), 0, a)\n with self.assertRaisesRegex(TypeError,\n re.escape(\"scan carry output and input must have same type structure, \"\n f\"got {tree_util.tree_structure((0, 0, 0,))} \"\n f\"and {tree_util.tree_structure((1, (2, 3)))}\")):\n lax.scan(lambda c, x: ((0, 0, 0), x), (1, (2, 3)), a)\n with self.assertRaisesRegex(TypeError,\n re.escape(\"scan carry output and input must have same type structure, \"\n f\"got {tree_util.tree_structure(a)} and {tree_util.tree_structure(None)}.\")):\n lax.scan(lambda c, x: (0, x), None, a)\n with self.assertRaisesWithLiteralMatch(\n TypeError,\n \"scan carry output and input must have identical types, got\\n\"\n \"ShapedArray(int32[])\\n\"\n \"and\\n\"\n \"ShapedArray(float32[]).\"):\n lax.scan(lambda c, x: (np.int32(0), x), np.float32(1.0), a)\n with self.assertRaisesRegex(TypeError,\n re.escape(\"scan carry output and input must have same type structure, \"\n f\"got {tree_util.tree_structure(a)} and {tree_util.tree_structure((1, 2))}.\")):\n lax.scan(lambda c, x: (0, x), (1, 2), a)\n\n\n @parameterized.named_parameters(\n {\"testcase_name\": \"_{}\".format(scan_name),\n \"scan\": scan_impl}\n for scan_impl, scan_name in SCAN_IMPLS)\n def testScanHigherOrderDifferentiation(self, scan):\n d = 0.75\n def f(c, a):\n b = jnp.sin(c * jnp.sum(jnp.cos(d * a)))\n c = 0.9 * jnp.cos(d * jnp.sum(jnp.sin(c * a)))\n return c, b\n\n as_ = jnp.arange(6.).reshape((3, 2))\n c = 1.\n\n jtu.check_grads(lambda c, as_: scan(f, c, as_), (c, as_),\n modes=[\"rev\"], order=2, rtol={np.float32: 6e-3})\n\n @parameterized.named_parameters(\n {\"testcase_name\": \"_jit_scan={}_jit_f={}_in_axes={}_impl={}\".format(\n jit_scan, jit_f, in_axes, scan_name),\n \"jit_scan\": jit_scan, \"jit_f\": jit_f, \"in_axes\": in_axes,\n \"scan\": scan_impl}\n for jit_scan in [False, True]\n for jit_f in [False, True]\n for scan_impl, scan_name in SCAN_IMPLS\n for in_axes in itertools.product([None, 0, 1], [None, 0, 1, 2])\n if in_axes != (None, None))\n def testScanVmap(self, jit_scan, jit_f, in_axes, scan):\n rng = np.random.RandomState(0)\n\n d = rng.randn(2)\n def f(c, a):\n assert a.shape == (3,)\n assert c.shape == (4,)\n b = jnp.cos(jnp.sum(jnp.sin(a)) + jnp.sum(jnp.cos(c)) + jnp.sum(jnp.tan(d)))\n c = jnp.sin(c * b)\n assert b.shape == ()\n return c, b\n\n if jit_f:\n f = api.jit(f)\n if jit_scan:\n scan = api.jit(scan, static_argnums=(0,))\n\n as_shape = [5, 3]\n c_shape = [4]\n\n c_bdim, as_bdim = in_axes\n if c_bdim is not None:\n c_shape.insert(c_bdim, 7)\n if as_bdim is not None:\n as_shape.insert(as_bdim, 7)\n\n as_ = rng.randn(*as_shape)\n c = rng.randn(*c_shape)\n\n ans = api.vmap(lambda c, as_: scan(f, c, as_), in_axes)(c, as_)\n expected = api.vmap(lambda c, as_: scan_reference(f, c, as_), in_axes)(c, as_)\n self.assertAllClose(ans, expected, check_dtypes=False,\n rtol=1e-5, atol=1e-5)\n\n def testScanVmapTuples(self):\n def f(c, a):\n a1, a2 = a\n c1, c2 = c\n b = jnp.sum(jnp.cos(a1)) * jnp.sum(jnp.tan(c2 * a2))\n c = c1 * jnp.sin(jnp.sum(a1 * a2)), c2 * jnp.cos(jnp.sum(a1))\n return c, b\n\n in_axes = (0, (1, 2))\n\n r = np.random.RandomState(0)\n as_ = (r.randn(3, 7), r.randn(3, 4, 7))\n c = (r.randn(7, 2), r.randn(7))\n\n expected_c_out, expected_bs = [], []\n for i in range(7):\n c_out, bs = lax.scan(f, (c[0][i], c[1][i]), (as_[0][:,i], as_[1][:,:,i]))\n expected_c_out.append(c_out)\n expected_bs.append(bs)\n expected_c_out_0, expected_c_out_1 = unzip2(expected_c_out)\n expected_c_out = (jnp.stack(expected_c_out_0), jnp.stack(expected_c_out_1))\n expected_bs = jnp.stack(expected_bs)\n expected = expected_c_out, expected_bs\n\n ans = api.vmap(lambda c, as_: lax.scan(f, c, as_), in_axes)(c, as_)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testScanVmapFixpoint(self):\n def f(carry_init):\n def scan_body(c, x):\n # The carry is a 4-tuple, the last element starts batched,\n # and the carry is shifted left at each iteration.\n return ((c[1], c[2], c[3], 0.), None)\n return lax.scan(scan_body, (0., 1., 2., carry_init), jnp.zeros(2))\n carry_init = jnp.array([3., 4., 5.])\n carry_out, _ = api.vmap(f)(carry_init)\n self.assertAllClose(carry_out[3], jnp.array([0., 0., 0.]), check_dtypes=False)\n self.assertAllClose(carry_out[2], jnp.array([0., 0., 0.]), check_dtypes = False)\n # After two shifts, we get the carry_init\n self.assertAllClose(carry_out[1], carry_init, check_dtypes=False)\n self.assertAllClose(carry_out[0], jnp.array([2., 2., 2.]), check_dtypes = False)\n\n def testIssue757(self):\n # code from https://github.com/google/jax/issues/757\n def fn(a):\n return jnp.cos(a)\n\n def loop(val):\n iterations = 10\n def apply_carry(x, i):\n return api.grad(fn, argnums=(0,))(x)[0], i\n\n final_val, _ = lax.scan(\n apply_carry,\n val,\n jnp.arange(iterations)\n )\n return final_val\n\n arg = 0.5\n api.jit(api.jacfwd(loop, argnums=(0,)))(arg) # doesn't crash\n\n def testIssue804(self):\n num_devices = xla_bridge.device_count()\n f = partial(lax.scan, lambda c, x: (c + lax.psum(x, \"i\") , c), 0.)\n api.pmap(f, axis_name=\"i\")(jnp.ones((num_devices, 4))) # doesn't crash\n\n def testMap(self):\n f = lambda x: x ** 2\n xs = jnp.arange(10)\n expected = xs ** 2\n actual = lax.map(f, xs)\n self.assertAllClose(actual, expected)\n\n def testMapEmpty(self):\n # https://github.com/google/jax/issues/2412\n ans = lax.map(lambda x: x * x, jnp.array([]))\n expected = jnp.array([])\n self.assertAllClose(ans, expected)\n\n def testCaching(self):\n def cond(x):\n assert python_should_be_executing\n return x < 5\n\n def body(x):\n assert python_should_be_executing\n return x + 2\n\n python_should_be_executing = True\n lax.while_loop(cond, body, 0)\n\n python_should_be_executing = False\n lax.while_loop(cond, body, 0)\n\n def testCaching2(self):\n # This second caching test shows a different kind of caching that we haven't\n # implemented (but could!), namely that Python functions that are distinct\n # objects but are equivalent functions trigger cache hits. This kind of\n # caching could be salient when using lambda functions with control flow:\n #\n # lax.while_loop(lambda x: x < 5, lambda x: x + 2, 0)\n # lax.while_loop(lambda x: x < 5, lambda x: x + 2, 0)\n #\n # To get a cache hit on the second line we'd need to form a jaxpr and\n # compare them for equality (including the literals on identity). We could\n # implement that by adding a __hash__/__eq__ to core.Jaxpr and\n # core.ClosedJaxpr (see #1221).\n raise SkipTest(\"not implemented\")\n\n def cond(x):\n assert python_should_be_executing\n return x < 5\n\n def body(x):\n assert python_should_be_executing\n return x + 2\n\n python_should_be_executing = True\n lax.while_loop(cond, body, 0)\n\n def cond(x):\n assert python_should_be_executing\n return x < 5\n\n def body(x):\n assert python_should_be_executing\n return x + 2\n\n python_should_be_executing = False\n lax.while_loop(cond, body, 0)\n\n def testWhileCondConstant(self):\n out = lax.while_loop(lambda _: False, lambda _: (), ()) # doesn't crash\n self.assertEqual(out, ())\n\n @parameterized.named_parameters(\n {\"testcase_name\": \"_jit_loop={}_jit_body={}_jit_cond={}\".format(\n jit_loop, jit_body, jit_cond),\n \"jit_loop\": jit_loop, \"jit_body\": jit_body, \"jit_cond\": jit_cond}\n for jit_loop in [False, True]\n for jit_body in [False, True]\n for jit_cond in [False, True])\n def testWhileJVP(self, jit_loop=True, jit_body=False, jit_cond=True):\n cond = lambda x: x[0, 2] <= 8\n body = lambda x: x * x\n\n if jit_cond:\n cond = api.jit(cond)\n if jit_body:\n body = api.jit(body)\n\n loop = partial(lax.while_loop, cond, body)\n if jit_loop:\n loop = api.jit(loop)\n\n loop_ref = partial(while_loop_reference, cond, body)\n\n x = jnp.arange(9.).reshape((3, 3))\n ans = api.jvp(loop, (x,), (x,))\n expected = api.jvp(loop_ref, (x,), (x,))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n jtu.check_grads(loop, (x,), order=2, modes=[\"fwd\"])\n\n def testWhileJVPViaForiLoop(self):\n f = lambda x: lax.fori_loop(0, 3, lambda i, x: x * 2, x)\n self.assertAllClose(f(2.), 16., check_dtypes=False)\n self.assertAllClose(api.jvp(f, (2.,), (1.,)), (16., 8.), check_dtypes=False)\n jtu.check_grads(f, (2.,), order=2, modes=[\"fwd\"])\n\n f = lambda x: lax.fori_loop(0, 3, lambda i, x: x * (i + 1), x)\n self.assertAllClose(f(2.), 12., check_dtypes=False)\n self.assertAllClose(api.jvp(f, (2.,), (1.,)), (12., 6.), check_dtypes=False)\n jtu.check_grads(f, (2.,), order=2, modes=[\"fwd\"])\n\n def testWhileJVPWithGrowingNonzeroTangents(self):\n rng = np.random.RandomState(0)\n\n def cond(state):\n i, x, y, z = state\n return i < 2\n\n def body(state):\n i, x, y, z = state\n y = x * x\n z = y * y\n return i + 1, x, y, z\n\n y, z = rng.randn(2), rng.randn(2)\n def loop(loop_impl, x):\n return loop_impl(cond, body, (0, x, y, z))[1]\n\n loop_lax = partial(loop, lax.while_loop)\n loop_ref = partial(loop, while_loop_reference)\n\n x = rng.randn(2)\n ans = api.jvp(loop_lax, (x,), (x,))\n expected = api.jvp(loop_ref, (x,), (x,))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n jtu.check_grads(loop_lax, (x,), order=2, modes=[\"fwd\"])\n\n @parameterized.named_parameters(\n dict(testcase_name=\"_loop={}\".format(loop), loop=loop)\n for loop in [\"while\", \"fori\", \"fori_inside_cond\", \"fori_inside_scan\"])\n def testWhileGradError(self, loop: str = \"fori_inside_scan\"):\n # Raise error for vjp for loops\n if loop == \"while\":\n func = lambda x: lax.while_loop(lambda i: i < 5., lambda i: i + 1., x)\n elif loop == \"fori\":\n func = lambda x: lax.fori_loop(x, x + 2., lambda i, c: c, x)\n elif loop == \"fori_inside_jit\":\n func = api.jit(lambda x: lax.fori_loop(x, x + 2., lambda i, c: c, x))\n elif loop == \"fori_inside_cond\":\n func = lambda x: lax.cond(True, x,\n lambda x: lax.fori_loop(x, x + 2., lambda i, c: c, x),\n 1., lambda x: x)\n elif loop == \"fori_inside_scan\":\n func = lambda x: lax.scan(lambda c, x: (lax.fori_loop(x, x + 2., lambda i, c1: c1 * c, x),\n None),\n x, np.ones(2))[0]\n else:\n assert False\n\n with self.assertRaisesRegex(ValueError, \"Reverse-mode differentiation does not work for lax.while_loop\"):\n api.grad(func)(1.)\n\n api.linearize(func, 1.) # Linearization works\n\n def testIssue1316(self):\n def f(carry, _):\n c, key = carry\n key, _ = random.split(key)\n return (c, key), ()\n\n key = random.PRNGKey(0)\n api.grad(lambda c: lax.scan(f, (c, key), np.ones(3))[0][0])(0.) # doesn't crash\n\n def testIssue1361(self):\n @api.jit\n def jit_run_scan(x):\n def fun(carry, _):\n x, _ = carry\n return (2 * x, 0.), None\n (x, _), _ = lax.scan(fun, (x, 0.), jnp.arange(3))\n return x\n\n api.grad(lambda x: jit_run_scan(x))(0.) # doesn't crash\n\n def test_custom_root_scalar(self):\n\n def scalar_solve(f, y):\n return y / f(1.0)\n\n def binary_search(func, x0, low=0.0, high=100.0):\n del x0 # unused\n\n def cond(state):\n low, high = state\n midpoint = 0.5 * (low + high)\n return (low < midpoint) & (midpoint < high)\n\n def body(state):\n low, high = state\n midpoint = 0.5 * (low + high)\n update_upper = func(midpoint) > 0\n low = jnp.where(update_upper, low, midpoint)\n high = jnp.where(update_upper, midpoint, high)\n return (low, high)\n\n solution, _ = lax.while_loop(cond, body, (low, high))\n return solution\n\n def sqrt_cubed(x, tangent_solve=scalar_solve):\n f = lambda y: y ** 2 - x ** 3\n return lax.custom_root(f, 0.0, binary_search, tangent_solve)\n\n value, grad = api.value_and_grad(sqrt_cubed)(5.0)\n self.assertAllClose(value, 5 ** 1.5, check_dtypes=False, rtol=1e-6)\n self.assertAllClose(grad, api.grad(pow)(5.0, 1.5), check_dtypes=False,\n rtol=1e-7)\n jtu.check_grads(sqrt_cubed, (5.0,), order=2,\n rtol={jnp.float32: 1e-2, jnp.float64: 1e-3})\n\n inputs = jnp.array([4.0, 5.0])\n results = api.vmap(sqrt_cubed)(inputs)\n self.assertAllClose(results, inputs ** 1.5, check_dtypes=False)\n\n results = api.jit(sqrt_cubed)(5.0)\n self.assertAllClose(results, 5.0 ** 1.5, check_dtypes=False,\n rtol={np.float64:1e-7})\n\n @jtu.skip_on_flag(\"jax_skip_slow_tests\", True)\n def test_custom_root_vector_with_solve_closure(self):\n\n def vector_solve(f, y):\n return jnp.linalg.solve(api.jacobian(f)(y), y)\n\n def linear_solve(a, b):\n f = lambda y: high_precision_dot(a, y) - b\n x0 = jnp.zeros_like(b)\n solution = jnp.linalg.solve(a, b)\n oracle = lambda func, x0: solution\n return lax.custom_root(f, x0, oracle, vector_solve)\n\n rng = np.random.RandomState(0)\n a = rng.randn(2, 2)\n b = rng.randn(2)\n jtu.check_grads(linear_solve, (a, b), order=2,\n atol={np.float32: 1e-2, np.float64: 1e-11})\n\n actual = api.jit(linear_solve)(a, b)\n expected = jnp.linalg.solve(a, b)\n self.assertAllClose(expected, actual)\n\n def test_custom_root_with_custom_linear_solve(self):\n\n def linear_solve(a, b):\n f = lambda x: high_precision_dot(a, x) - b\n factors = jsp.linalg.cho_factor(a)\n cho_solve = lambda f, b: jsp.linalg.cho_solve(factors, b)\n def pos_def_solve(g, b):\n return lax.custom_linear_solve(g, b, cho_solve, symmetric=True)\n return lax.custom_root(f, b, cho_solve, pos_def_solve)\n\n rng = np.random.RandomState(0)\n a = rng.randn(2, 2)\n b = rng.randn(2)\n\n actual = linear_solve(high_precision_dot(a, a.T), b)\n expected = jnp.linalg.solve(high_precision_dot(a, a.T), b)\n self.assertAllClose(expected, actual)\n\n actual = api.jit(linear_solve)(high_precision_dot(a, a.T), b)\n expected = jnp.linalg.solve(high_precision_dot(a, a.T), b)\n self.assertAllClose(expected, actual)\n\n jtu.check_grads(lambda x, y: linear_solve(high_precision_dot(x, x.T), y),\n (a, b), order=2, rtol={jnp.float32: 1e-2})\n\n def test_custom_root_errors(self):\n with self.assertRaisesRegex(TypeError, re.escape(\"f() output pytree\")):\n lax.custom_root(lambda x: (x, x), 0.0, lambda f, x: x, lambda f, x: x)\n with self.assertRaisesRegex(TypeError, re.escape(\"solve() output pytree\")):\n lax.custom_root(lambda x: x, 0.0, lambda f, x: (x, x), lambda f, x: x)\n\n def dummy_root_usage(x):\n f = lambda y: x - y\n return lax.custom_root(f, 0.0, lambda f, x: x, lambda f, x: (x, x))\n\n with self.assertRaisesRegex(\n TypeError, re.escape(\"tangent_solve() output pytree\")):\n api.jvp(dummy_root_usage, (0.0,), (0.0,))\n\n @parameterized.named_parameters(\n {\"testcase_name\": \"nonsymmetric\", \"symmetric\": False},\n {\"testcase_name\": \"symmetric\", \"symmetric\": True},\n )\n @jtu.skip_on_flag(\"jax_skip_slow_tests\", True)\n def test_custom_linear_solve(self, symmetric):\n\n def explicit_jacobian_solve(matvec, b):\n return lax.stop_gradient(jnp.linalg.solve(api.jacobian(matvec)(b), b))\n\n def matrix_free_solve(matvec, b):\n return lax.custom_linear_solve(\n matvec, b, explicit_jacobian_solve, explicit_jacobian_solve,\n symmetric=symmetric)\n\n def linear_solve(a, b):\n return matrix_free_solve(partial(high_precision_dot, a), b)\n\n rng = np.random.RandomState(0)\n a = rng.randn(3, 3)\n if symmetric:\n a = a + a.T\n b = rng.randn(3)\n jtu.check_grads(linear_solve, (a, b), order=2, rtol=2e-3)\n\n expected = jnp.linalg.solve(a, b)\n actual = api.jit(linear_solve)(a, b)\n self.assertAllClose(expected, actual)\n\n c = rng.randn(3, 2)\n expected = jnp.linalg.solve(a, c)\n actual = api.vmap(linear_solve, (None, 1), 1)(a, c)\n self.assertAllClose(expected, actual)\n\n @jtu.skip_on_flag(\"jax_skip_slow_tests\", True)\n def test_custom_linear_solve_zeros(self):\n def explicit_jacobian_solve(matvec, b):\n return lax.stop_gradient(jnp.linalg.solve(api.jacobian(matvec)(b), b))\n\n def matrix_free_solve(matvec, b):\n return lax.custom_linear_solve(matvec, b, explicit_jacobian_solve,\n explicit_jacobian_solve)\n\n def linear_solve(a, b):\n return matrix_free_solve(partial(high_precision_dot, a), b)\n\n rng = np.random.RandomState(0)\n a = rng.randn(3, 3)\n b = rng.randn(3)\n jtu.check_grads(lambda x: linear_solve(x, b), (a,), order=2,\n rtol={np.float32: 5e-3})\n jtu.check_grads(lambda x: linear_solve(a, x), (b,), order=2,\n rtol={np.float32: 5e-3})\n\n @jtu.skip_on_flag(\"jax_skip_slow_tests\", True)\n def test_custom_linear_solve_iterative(self):\n\n def richardson_iteration(matvec, b, omega=0.1, tolerance=1e-6):\n # Equivalent to vanilla gradient descent:\n # https://en.wikipedia.org/wiki/Modified_Richardson_iteration\n def cond(x):\n return jnp.linalg.norm(matvec(x) - b) > tolerance\n def body(x):\n return x + omega * (b - matvec(x))\n return lax.while_loop(cond, body, b)\n\n def matrix_free_solve(matvec, b):\n return lax.custom_linear_solve(matvec, b, richardson_iteration,\n richardson_iteration)\n\n def build_and_solve(a, b):\n # intentionally non-linear in a and b\n matvec = partial(high_precision_dot, jnp.exp(a))\n return matrix_free_solve(matvec, jnp.cos(b))\n\n rng = np.random.RandomState(0)\n a = rng.randn(2, 2)\n b = rng.randn(2)\n expected = jnp.linalg.solve(jnp.exp(a), jnp.cos(b))\n actual = build_and_solve(a, b)\n self.assertAllClose(expected, actual, atol=1e-5)\n jtu.check_grads(build_and_solve, (a, b), atol=1e-5, order=2,\n rtol={jnp.float32: 6e-2, jnp.float64: 2e-3})\n\n # vmap across an empty dimension\n jtu.check_grads(\n api.vmap(build_and_solve), (a[None, :, :], b[None, :]),\n atol=1e-5,\n order=2,\n rtol={jnp.float32: 6e-2, jnp.float64: 2e-3})\n\n def test_custom_linear_solve_cholesky(self):\n\n def positive_definite_solve(a, b):\n factors = jsp.linalg.cho_factor(a)\n def solve(matvec, x):\n return jsp.linalg.cho_solve(factors, x)\n matvec = partial(high_precision_dot, a)\n return lax.custom_linear_solve(matvec, b, solve, symmetric=True)\n\n rng = np.random.RandomState(0)\n a = rng.randn(2, 2)\n b = rng.randn(2)\n\n expected = jnp.linalg.solve(np.asarray(posify(a)), b)\n actual = positive_definite_solve(posify(a), b)\n self.assertAllClose(expected, actual)\n\n actual = api.jit(positive_definite_solve)(posify(a), b)\n self.assertAllClose(expected, actual)\n\n # numerical gradients are only well defined if ``a`` is guaranteed to be\n # positive definite.\n jtu.check_grads(\n lambda x, y: positive_definite_solve(posify(x), y),\n (a, b), order=2, rtol=1e-2)\n\n def test_custom_linear_solve_complex(self):\n\n def solve(a, b):\n def solve(matvec, x):\n return jsp.linalg.solve(a, x)\n def tr_solve(matvec, x):\n return jsp.linalg.solve(a.T, x)\n matvec = partial(high_precision_dot, a)\n return lax.custom_linear_solve(matvec, b, solve, tr_solve)\n\n rng = np.random.RandomState(0)\n a = 0.5 * rng.randn(2, 2) + 0.5j * rng.randn(2, 2)\n b = 0.5 * rng.randn(2) + 0.5j * rng.randn(2)\n jtu.check_grads(solve, (a, b), order=2, rtol=1e-2)\n\n @jtu.skip_on_flag(\"jax_skip_slow_tests\", True)\n def test_custom_linear_solve_lu(self):\n\n def linear_solve(a, b):\n a_factors = jsp.linalg.lu_factor(a)\n at_factors = jsp.linalg.lu_factor(a.T)\n def solve(matvec, x):\n return jsp.linalg.lu_solve(a_factors, x)\n def transpose_solve(vecmat, x):\n return jsp.linalg.lu_solve(at_factors, x)\n return lax.custom_linear_solve(\n partial(high_precision_dot, a), b, solve, transpose_solve)\n\n rng = np.random.RandomState(0)\n a = rng.randn(3, 3)\n b = rng.randn(3)\n\n expected = jnp.linalg.solve(a, b)\n actual = linear_solve(a, b)\n self.assertAllClose(expected, actual)\n\n jtu.check_grads(linear_solve, (a, b), order=2, rtol=2e-3)\n\n # regression test for https://github.com/google/jax/issues/1536\n jtu.check_grads(api.jit(linear_solve), (a, b), order=2,\n rtol={np.float32: 2e-3})\n\n @jtu.skip_on_flag(\"jax_skip_slow_tests\", True)\n def test_custom_linear_solve_without_transpose_solve(self):\n\n def explicit_jacobian_solve(matvec, b):\n return lax.stop_gradient(jnp.linalg.solve(api.jacobian(matvec)(b), b))\n\n def loss(a, b):\n matvec = partial(high_precision_dot, a)\n x = lax.custom_linear_solve(matvec, b, explicit_jacobian_solve)\n return jnp.sum(x)\n\n rng = np.random.RandomState(0)\n a = rng.randn(2, 2)\n b = rng.randn(2)\n\n jtu.check_grads(loss, (a, b), order=2, modes=['fwd'],\n atol={np.float32: 2e-3, np.float64: 1e-11})\n jtu.check_grads(api.vmap(loss), (a[None,:,:], b[None,:]), order=2,\n modes=['fwd'], atol={np.float32: 2e-3, np.float64: 1e-11})\n\n with self.assertRaisesRegex(TypeError, \"transpose_solve required\"):\n api.grad(loss)(a, b)\n\n @jtu.skip_on_flag(\"jax_skip_slow_tests\", True)\n def test_custom_linear_solve_pytree(self):\n \"\"\"Test custom linear solve with inputs and outputs that are pytrees.\"\"\"\n\n def unrolled_matvec(mat, x):\n \"\"\"Apply a Python list of lists of scalars to a list of scalars.\"\"\"\n result = []\n for i in range(len(mat)):\n v = 0\n for j in range(len(x)):\n if mat[i][j] is not None:\n v += mat[i][j] * x[j]\n result.append(v)\n return result\n\n def unrolled_substitution_solve(matvec, b, lower_tri):\n \"\"\"Solve a triangular unrolled system with fwd/back substitution.\"\"\"\n zero = jnp.zeros(())\n one = jnp.ones(())\n x = [zero for _ in b]\n ordering = range(len(b)) if lower_tri else range(len(b) - 1, -1, -1)\n for i in ordering:\n residual = b[i] - matvec(x)[i]\n diagonal = matvec([one if i == j else zero for j in range(len(b))])[i]\n x[i] = residual / diagonal\n return x\n\n def custom_unrolled_lower_tri_solve(mat, b):\n return lax.custom_linear_solve(\n partial(unrolled_matvec, mat), b,\n partial(unrolled_substitution_solve, lower_tri=True),\n partial(unrolled_substitution_solve, lower_tri=False))\n\n mat = [[1.0, None, None, None, None, None, None],\n [1.0, 1.0, None, None, None, None, None],\n [None, 1.0, 1.0, None, None, None, None],\n [None, None, 1.0, 1.0, None, None, None],\n [None, None, None, 1.0, 1.0, None, None],\n [None, None, None, None, None, 2.0, None],\n [None, None, None, None, None, 4.0, 3.0]]\n\n rng = np.random.RandomState(0)\n b = list(rng.randn(7))\n\n # Non-batched\n jtu.check_grads(custom_unrolled_lower_tri_solve, (mat, b), order=2,\n rtol={jnp.float32: 2e-2})\n\n # Batch one element of b (which, because of unrolling, should only affect\n # the first block of outputs)\n b_bat = list(b)\n b_bat[3] = rng.randn(3)\n jtu.check_grads(\n api.vmap(\n custom_unrolled_lower_tri_solve,\n in_axes=(None, [None, None, None, 0, None, None, None]),\n out_axes=[0, 0, 0, 0, 0, None, None]), (mat, b_bat),\n order=2,\n rtol={jnp.float32: 1e-2})\n\n # Batch one element of mat (again only affecting first block)\n mat[2][1] = rng.randn(3)\n mat_axis_tree = [\n [0 if i == 2 and j == 1 else None for j in range(7)] for i in range(7)\n ]\n jtu.check_grads(\n api.vmap(\n custom_unrolled_lower_tri_solve,\n in_axes=(mat_axis_tree, None),\n out_axes=[0, 0, 0, 0, 0, None, None]), (mat, b),\n order=2)\n\n def test_custom_linear_solve_errors(self):\n\n solve = lambda f, x: x\n\n with self.assertRaisesRegex(TypeError, re.escape(\"matvec() output pytree\")):\n lax.custom_linear_solve(lambda x: [x], 1.0, solve, solve)\n with self.assertRaisesRegex(TypeError, re.escape(\"solve() output pytree\")):\n lax.custom_linear_solve(lambda x: x, 1.0, lambda f, x: [x], solve)\n with self.assertRaisesRegex(\n TypeError, re.escape(\"transpose_solve() output pytree\")):\n lax.custom_linear_solve(lambda x: x, 1.0, solve, lambda f, x: [x])\n\n with self.assertRaisesRegex(ValueError, re.escape(\"solve() output shapes\")):\n lax.custom_linear_solve(lambda x: x, 1.0, lambda f, x: jnp.ones(2), solve)\n\n def bad_matvec_usage(a):\n return lax.custom_linear_solve(\n lambda x: a * jnp.ones(2), 1.0, solve, solve)\n with self.assertRaisesRegex(ValueError, re.escape(\"matvec() output shapes\")):\n api.jvp(bad_matvec_usage, (1.0,), (1.0,))\n\n def testIssue810(self):\n def loss(A):\n def step(x, i):\n return jnp.matmul(A, x), None\n init_x = jnp.zeros(A.shape[-1:])\n last_x, _ = lax.scan(step, init_x, jnp.arange(10))\n return jnp.sum(last_x)\n\n A = jnp.zeros((3, 3))\n # The second DUS was unnecessarily replicating A across time.\n # We check XLA because _scan_impl is \"underneath\" the jaxpr language.\n s = str(api.xla_computation(api.grad(loss))(A).as_hlo_text())\n assert s.count(\"dynamic-update-slice(\") < 2\n\n def testScanLengthArg(self):\n def arange(n):\n return lax.scan(lambda c, _: (c + 1, c), 0, None, length=n)[1]\n\n ans = arange(10)\n expected = np.arange(10)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_while_loop_of_pmap(self):\n # code from jsnoek@\n\n def body(i, x):\n result = api.pmap(lambda z: lax.psum(jnp.sin(z), 'i'), axis_name='i')(x)\n return result + x\n f_loop = lambda x: lax.fori_loop(0, 3, body, x) # noqa: F821\n ans = f_loop(jnp.ones(api.device_count()))\n del body, f_loop\n\n def body2(i, x):\n result = jnp.broadcast_to(jnp.sin(x).sum(), x.shape)\n return result + x\n g_loop = lambda x: lax.fori_loop(0, 3, body2, x)\n expected = g_loop(jnp.ones(api.device_count()))\n\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_while_loop_of_pmap_error_message(self):\n\n def body(i, x):\n result = api.pmap(lambda z: lax.psum(jnp.sin(z), 'i'), axis_name='i')(x)\n return result + x\n f_loop = lambda x: lax.fori_loop(0, 3, body, x)\n\n too_big = 2 * api.device_count()\n\n self.assertRaisesRegex(\n ValueError,\n re.escape(\n \"compiling a primitive computation `while` that requires {} \"\n \"replicas, but only {} XLA devices are available on backend {}.\"\n .format(too_big, api.device_count(), jtu.device_under_test())),\n lambda: f_loop(jnp.ones(too_big)))\n\n @parameterized.named_parameters(\n {\"testcase_name\": \"_{}\".format(scan_name),\n \"scan\": scan_impl}\n for scan_impl, scan_name in SCAN_IMPLS)\n def test_scan_reverse(self, scan):\n def cumsum(x, reverse):\n return scan(lambda c, x: (c + x, c + x), 0, x, reverse=reverse)[1]\n\n x = np.array([3, 1, 4, 1, 5, 9])\n self.assertAllClose(np.cumsum(x), cumsum(x, False), check_dtypes=False)\n self.assertAllClose(np.cumsum(x[::-1])[::-1], cumsum(x, True), check_dtypes=False)\n\n with api.disable_jit():\n self.assertAllClose(np.cumsum(x), cumsum(x, False), check_dtypes=False)\n with api.disable_jit():\n self.assertAllClose(np.cumsum(x[::-1])[::-1], cumsum(x, True), check_dtypes=False)\n\n def test_scan_unroll(self):\n d = jnp.ones(2)\n def f(c, a):\n assert a.shape == (3,)\n assert c.shape == (4,)\n b = jnp.cos(jnp.sum(jnp.sin(a)) + jnp.sum(jnp.cos(c)) + jnp.sum(jnp.tan(d)))\n c = jnp.sin(c * b)\n assert b.shape == ()\n return c, b\n\n xs = jnp.ones((5, 3))\n c = jnp.ones(4)\n\n scan = lambda c, xs: lax.scan(f, c, xs)\n scan_unrolled = lambda c, xs: lax.scan(f, c, xs, unroll=2)\n\n # jaxprs should be the same size\n self.assertEqual(\n len(str(api.make_jaxpr(scan)(c, xs))),\n len(str(api.make_jaxpr(scan_unrolled)(c, xs))))\n\n # but HLO should grow due to unrolling\n self.assertLess(\n len(str(api.xla_computation(scan)(c, xs).as_hlo_text())),\n len(str(api.xla_computation(scan_unrolled)(c, xs).as_hlo_text())))\n\n def test_disable_jit_cond_with_vmap(self):\n # https://github.com/google/jax/issues/3093\n def fn(t):\n return lax.cond(t > 0, 0, lambda x: 0, 0, lambda x: 1)\n fn = api.vmap(fn)\n\n with api.disable_jit():\n _ = fn(jnp.array([1])) # doesn't crash\n\n def test_disable_jit_while_loop_with_vmap(self):\n # https://github.com/google/jax/issues/2823\n def trivial_while(y):\n return lax.while_loop(lambda x: x < 10.0, lambda x: x + 1.0, y)\n with api.disable_jit():\n api.vmap(trivial_while)(jnp.array([3.0,4.0])) # doesn't crash\n\n def test_vmaps_of_while_loop(self):\n # https://github.com/google/jax/issues/3164\n def f(x, n): return lax.fori_loop(0, n, lambda _, x: x + 1, x)\n x, n = jnp.arange(3), jnp.arange(4)\n api.vmap(api.vmap(f, (None, 0)), (0, None))(x, n) # doesn't crash\n\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"_{shape}_axis={axis}\",\n \"shape\": shape, \"axis\": axis}\n for shape in [\n [0], [1], [2], [3], [5], [10], [1000],\n [2, 3], [7, 5], [5, 6, 7]\n ]\n for axis in range(-len(shape), len(shape) - 1))\n def testAssociativeScanUnstructured(self, shape, axis):\n data = np.arange(np.prod(shape)).reshape(shape) + 7\n expected = np.cumsum(data, axis=axis)\n result = lax.associative_scan(operator.add, data, axis=axis)\n self.assertAllClose(result, expected, check_dtypes=False)\n\n def testAssociativeScanUnstructured1000Reverse(self):\n data = np.arange(1000) + 32\n expected = np.cumsum(data[::-1])[::-1]\n result = lax.associative_scan(operator.add, data, reverse=True)\n self.assertAllClose(result, expected, check_dtypes=False)\n\n def testAssociativeScanStructured3(self):\n pair = collections.namedtuple('pair', ('first', 'second'))\n data = pair(first=np.array([0., 1., 2.]),\n second=np.array([0., 10., 20.]))\n\n def fn(a, b):\n return pair(first=a.first + b.first,\n second=a.second + b.second)\n\n result = lax.associative_scan(fn, elems=data)\n self.assertAllClose(result.first, np.array([0., 1., 3.]),\n check_dtypes=False)\n self.assertAllClose(result.second, np.array([0., 10., 30.]),\n check_dtypes=False)\n\n def test_scan_typecheck_param(self):\n d = jnp.ones(2)\n def f(c, a):\n b = jnp.cos(jnp.sum(a) + jnp.sum(c) + jnp.sum(d))\n c = jnp.sin(c * b)\n return c, b\n\n xs = jnp.ones((5, 3))\n c = jnp.ones(4)\n scan_fun = lambda c, xs: lax.scan(f, c, xs)\n\n def new_jaxpr():\n jaxpr = api.make_jaxpr(scan_fun)(c, xs).jaxpr\n scan = next(eqn for eqn in jaxpr.eqns if eqn.primitive.name == 'scan')\n return jaxpr, scan\n\n jaxpr, eqn = new_jaxpr()\n eqn.params['reverse'] = 4\n self.assertRaisesRegex(\n core.JaxprTypeError,\n re.escape('invalid scan param reverse of type int, bool required: 4'),\n lambda: core.check_jaxpr(jaxpr))\n\n jaxpr, eqn = new_jaxpr()\n eqn.params['num_consts'] = -3\n self.assertRaisesRegex(\n core.JaxprTypeError,\n re.escape('invalid scan param num_consts of type int, '\n 'non-negative int required: -3'),\n lambda: core.check_jaxpr(jaxpr))\n\n def test_cond_typecheck_param(self):\n def new_jaxpr():\n jaxpr = api.make_jaxpr(\n lambda x: lax.switch(0, [jnp.sin, jnp.cos], x))(1.).jaxpr\n cond = next(eqn for eqn in jaxpr.eqns if eqn.primitive.name == 'cond')\n return jaxpr, cond\n\n jaxpr, eqn = new_jaxpr()\n eqn.params['branches'] = (4, 2)\n self.assertRaisesRegex(\n core.JaxprTypeError,\n re.escape('invalid cond param branches of type tuple, '\n 'tuple of ClosedJaxpr required: (4, 2)'),\n lambda: core.check_jaxpr(jaxpr))\n\n jaxpr, eqn = new_jaxpr()\n eqn.params['linear'] = (4, 2)\n self.assertRaisesRegex(\n core.JaxprTypeError,\n re.escape('invalid cond param linear of type tuple, '\n 'tuple of bool required: (4, 2)'),\n lambda: core.check_jaxpr(jaxpr))\n\n jaxpr, eqn = new_jaxpr()\n eqn.params['linear'] = 'multi\\nline'\n self.assertRaisesRegex(\n core.JaxprTypeError,\n r'invalid cond param linear of type str, '\n r'tuple of bool required:\\nmulti\\nline',\n lambda: core.check_jaxpr(jaxpr))\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"_dtype={dtype.__name__}\", \"dtype\": dtype}\n for dtype in jtu.dtypes.all_integer)\n def test_scan_init_weak_type(self, dtype):\n def func(carry, x):\n return carry + x, x\n init_weak = 0 # Python scalars are weakly-typed.\n x = jnp.ones(5, dtype=dtype)\n carry, result = lax.scan(func, init_weak, x)\n self.assertEqual(carry, x.sum())\n self.assertArraysEqual(result, x)\n\n @parameterized.named_parameters(\n {\"testcase_name\": f\"_dtype={dtype.__name__}\", \"dtype\": dtype}\n for dtype in jtu.dtypes.all_integer)\n def test_while_loop_init_weak_type(self, dtype):\n # This tests whether lax.while_loop can properly handle weakly-typed\n # initial values.\n def cond_fun(val):\n return val < 2\n def body_fun(val):\n return val + increment\n increment = jnp.array(1, dtype=dtype)\n init_weak = 0 # Python scalars are weakly-typed.\n result = lax.while_loop(cond_fun, body_fun, init_weak)\n self.assertArraysEqual(result, jnp.full_like(increment, 2))\n\n def test_scan_vjp_forwards_extensive_residuals(self):\n # https://github.com/google/jax/issues/4510\n def cumprod(x):\n s = jnp.ones((2, 32), jnp.float32)\n return lax.scan(lambda s, x: (x*s, s), s, x)\n\n rng = np.random.RandomState(1234)\n x = jnp.asarray(rng.randn(32, 2, 32).astype('float32'))\n _, vjp_fun = api.vjp(cumprod, x)\n\n # Need to spelunk into vjp_fun. This is fragile, and if it causes problems\n # just skip this test.\n *_, ext_res = vjp_fun.args[0].args[0]\n self.assertIs(ext_res, x)\n\n x = rng.randn(32, 2, 32).astype('float32') # numpy.ndarray, not DeviceArray\n _, vjp_fun = api.vjp(cumprod, x)\n *_, ext_res = vjp_fun.args[0].args[0]\n self.assertIsInstance(ext_res, xla.DeviceArray)\n\n def test_scan_vmap_collectives(self):\n def scan_f(state, x):\n s = lax.psum(state, 'i') * x\n return state, s\n\n def scan(state, xs):\n return lax.scan(scan_f, state, xs)\n\n scan_v = api.vmap(scan, in_axes=0, out_axes=0, axis_name='i')\n self.assertAllClose(\n scan_v(jnp.ones([1]), jnp.arange(5).reshape((1, 5))),\n (jnp.array([1.]), jnp.array([[0., 1., 2., 3., 4.]])))\n\n def test_xla_cpu_gpu_loop_cond_bug(self):\n # https://github.com/google/jax/issues/5900\n def deriv(f):\n return lambda x, *args: jax.linearize(lambda x: f(x, *args), x)[1](1.0)\n\n def _while_loop(cond_fun, body_fun, init_val, max_iter):\n def _iter(val):\n next_val = body_fun(val)\n next_cond = True\n return next_val, next_cond\n\n def _fun(tup, _):\n val, cond = tup\n return jax.lax.cond(cond, _iter, lambda x: (x, False), val), _\n\n init = (init_val, cond_fun(init_val))\n return jax.lax.scan(_fun, init, None, length=max_iter)[0][0]\n\n def my_pow(x, y):\n def body_fun(val):\n return val * x\n def cond_fun(val):\n return True\n return _while_loop(cond_fun, body_fun, 1.0, y)\n\n self.assertAllClose(deriv(my_pow)(3.0, 1), 1.0, check_dtypes=False)\n\n def test_unexpected_tracer_error(self):\n with self.assertRaisesRegex(core.UnexpectedTracerError,\n \"transformed by while_loop\"):\n lst = []\n def side_effecting_body(val):\n lst.append(val)\n return val+1\n lax.while_loop(lambda x: x < 2, side_effecting_body, 1)\n lst[0] += 1\n\n with self.assertRaisesRegex(core.UnexpectedTracerError,\n \"transformed by scan\"):\n lst = []\n def side_effecting_scan(carry, val):\n lst.append(val)\n return carry, val+1\n lax.scan(side_effecting_scan, None, jnp.ones((2, 2)))\n lst[0] += 1\n\nif __name__ == '__main__':\n absltest.main(testLoader=jtu.JaxTestLoader())\n"
] |
[
[
"numpy.tril",
"numpy.isnan",
"numpy.arange",
"numpy.int32",
"numpy.cumsum",
"numpy.int16",
"numpy.sin",
"numpy.ones",
"numpy.shape",
"numpy.float32",
"numpy.prod",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"numpy.random.RandomState"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
wadpac/mcfly
|
[
"c288ba227df0e7423dccde63f9886b025ceec269"
] |
[
"mcfly/modelgen.py"
] |
[
"#\n# mcfly\n#\n# Copyright 2017 Netherlands eScience Center\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\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation, Convolution1D, Lambda, \\\n Convolution2D, Flatten, \\\n Reshape, LSTM, Dropout, TimeDistributed, BatchNormalization, \\\n GlobalAveragePooling1D, Bidirectional\nfrom keras.layers import CuDNNLSTM # Comment on HPC\nfrom keras.regularizers import l2\nfrom keras.optimizers import Adam\nimport numpy as np\n\n\ndef generate_models(\n x_shape, number_of_classes, number_of_models=5, metrics=['accuracy'],\n model_type=None,\n cnn_min_layers=5, cnn_max_layers=10,\n cnn_min_filters=25, cnn_max_filters=100,\n cnn_min_fc_nodes=500, cnn_max_fc_nodes=1000,\n deepconvlstm_min_conv_layers=3, deepconvlstm_max_conv_layers=7,\n deepconvlstm_min_conv_filters=25, deepconvlstm_max_conv_filters=100,\n deepconvlstm_min_lstm_layers=1, deepconvlstm_max_lstm_layers=3,\n deepconvlstm_min_lstm_dims=100, deepconvlstm_max_lstm_dims=500,\n low_lr=1, high_lr=4, low_reg=1, high_reg=3\n):\n \"\"\"\n Generate one or multiple untrained Keras models with random hyperparameters.\n\n Parameters\n ----------\n x_shape : tuple\n Shape of the input dataset: (num_samples, num_timesteps, num_channels)\n number_of_classes : int\n Number of classes for classification task\n number_of_models : int\n Number of models to generate\n metrics : list\n Metrics to calculate on the validation set.\n See https://keras.io/metrics/ for possible values.\n model_type : str, optional\n Type of model to build: 'CNN' or 'DeepConvLSTM'.\n Default option None generates both models.\n cnn_min_layers : int\n minimum of Conv layers in CNN model\n cnn_max_layers : int\n maximum of Conv layers in CNN model\n cnn_min_filters : int\n minimum number of filters per Conv layer in CNN model\n cnn_max_filters : int\n maximum number of filters per Conv layer in CNN model\n cnn_min_fc_nodes : int\n minimum number of hidden nodes per Dense layer in CNN model\n cnn_max_fc_nodes : int\n maximum number of hidden nodes per Dense layer in CNN model\n deepconvlstm_min_conv_layers : int\n minimum number of Conv layers in DeepConvLSTM model\n deepconvlstm_max_conv_layers : int\n maximum number of Conv layers in DeepConvLSTM model\n deepconvlstm_min_conv_filters : int\n minimum number of filters per Conv layer in DeepConvLSTM model\n deepconvlstm_max_conv_filters : int\n maximum number of filters per Conv layer in DeepConvLSTM model\n deepconvlstm_min_lstm_layers : int\n minimum number of Conv layers in DeepConvLSTM model\n deepconvlstm_max_lstm_layers : int\n maximum number of Conv layers in DeepConvLSTM model\n deepconvlstm_min_lstm_dims : int\n minimum number of hidden nodes per LSTM layer in DeepConvLSTM model\n deepconvlstm_max_lstm_dims : int\n maximum number of hidden nodes per LSTM layer in DeepConvLSTM model\n low_lr : float\n minimum of log range for learning rate: learning rate is sampled\n between `10**(-low_reg)` and `10**(-high_reg)`\n high_lr : float\n maximum of log range for learning rate: learning rate is sampled\n between `10**(-low_reg)` and `10**(-high_reg)`\n low_reg : float\n minimum of log range for regularization rate: regularization rate is\n sampled between `10**(-low_reg)` and `10**(-high_reg)`\n high_reg : float\n maximum of log range for regularization rate: regularization rate is\n sampled between `10**(-low_reg)` and `10**(-high_reg)`\n\n Returns\n -------\n models : list\n List of compiled models\n \"\"\"\n models = []\n for _ in range(0, number_of_models):\n if model_type is None: # random model choice:\n current_model_type = 'CNN' if np.random.random(\n ) < 0.5 else 'DeepConvLSTM'\n else: # user-defined model choice:\n current_model_type = model_type\n generate_model = None\n if current_model_type == 'CNN':\n generate_model = generate_CNN_model # generate_model is a function\n hyperparameters = generate_CNN_hyperparameter_set(\n min_layers=cnn_min_layers, max_layers=cnn_max_layers,\n min_filters=cnn_min_filters, max_filters=cnn_max_filters,\n min_fc_nodes=cnn_min_fc_nodes, max_fc_nodes=cnn_max_fc_nodes,\n low_lr=low_lr, high_lr=high_lr, low_reg=low_reg,\n high_reg=high_reg)\n if current_model_type == 'DeepConvLSTM':\n generate_model = generate_DeepConvLSTM_model\n hyperparameters = generate_DeepConvLSTM_hyperparameter_set(\n min_conv_layers=deepconvlstm_min_conv_layers,\n max_conv_layers=deepconvlstm_max_conv_layers,\n min_conv_filters=deepconvlstm_min_conv_filters,\n max_conv_filters=deepconvlstm_max_conv_filters,\n min_lstm_layers=deepconvlstm_min_lstm_layers,\n max_lstm_layers=deepconvlstm_max_lstm_layers,\n min_lstm_dims=deepconvlstm_min_lstm_dims,\n max_lstm_dims=deepconvlstm_max_lstm_dims,\n low_lr=low_lr, high_lr=high_lr, low_reg=low_reg,\n high_reg=high_reg)\n models.append(\n (generate_model(x_shape, number_of_classes, metrics=metrics, **hyperparameters),\n hyperparameters, current_model_type))\n return models\n\n\ndef generate_DeepConvLSTM_model(\n x_shape, class_number, filters, lstm_dims, learning_rate=0.01,\n regularization_rate=0.01, metrics=['accuracy']):\n \"\"\"\n Generate a model with convolution and LSTM layers.\n See Ordonez et al., 2016, http://dx.doi.org/10.3390/s16010115\n\n Parameters\n ----------\n x_shape : tuple\n Shape of the input dataset: (num_samples, num_timesteps, num_channels)\n class_number : int\n Number of classes for classification task\n filters : list of ints\n number of filters for each convolutional layer\n lstm_dims : list of ints\n number of hidden nodes for each LSTM layer\n learning_rate : float\n learning rate\n regularization_rate : float\n regularization rate\n metrics : list\n Metrics to calculate on the validation set.\n See https://keras.io/metrics/ for possible values.\n\n Returns\n -------\n model : Keras model\n The compiled Keras model\n \"\"\"\n dim_length = x_shape[1] # number of samples in a time series\n dim_channels = x_shape[2] # number of channels\n output_dim = class_number # number of classes\n weightinit = 'lecun_uniform' # weight initialization\n model = Sequential() # initialize model\n model.add(BatchNormalization(input_shape=(dim_length, dim_channels)))\n # reshape a 2 dimensional array per file/person/object into a\n # 3 dimensional array\n model.add(\n Reshape(target_shape=(dim_length, dim_channels, 1)))\n for filt in filters:\n # filt: number of filters used in a layer\n # filters: vector of filt values\n model.add(\n Convolution2D(filt, kernel_size=(3, 1), padding='same',\n kernel_regularizer=l2(regularization_rate),\n kernel_initializer=weightinit))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n # reshape 3 dimensional array back into a 2 dimensional array,\n # but now with more dept as we have the the filters for each channel\n model.add(Reshape(target_shape=(dim_length, filters[-1] * dim_channels)))\n\n for lstm_dim in lstm_dims:\n #model.add(LSTM(units=lstm_dim, return_sequences=True,\n # activation='tanh'))\n # comment following line for HPC\n model.add(CuDNNLSTM(units=lstm_dim, return_sequences=True))\n\n model.add(Dropout(0.5)) # dropout before the dense layer\n\n# # set up final dense layer such that every timestamp is given one\n# # classification\n# model.add(\n# TimeDistributed(\n# Dense(units=output_dim, kernel_regularizer=l2(regularization_rate))))\n# model.add(Activation(\"softmax\"))\n# # Final classification layer - per timestep\n# model.add(Lambda(lambda x: x[:, -1, :], output_shape=[output_dim]))\n\n # Pool output of all timesteps and perform classification using pooled output\n model.add(GlobalAveragePooling1D())\n model.add(Dense(units=output_dim, kernel_initializer=weightinit))\n model.add(BatchNormalization())\n model.add(Activation(\"softmax\")) # Final classification layer\n\n# if class_number == 2:\n# loss = 'binary_crossentropy'\n# else:\n# loss = 'categorical_crossentropy'\n loss = 'categorical_crossentropy'\n model.compile(loss=loss,\n optimizer=Adam(lr=learning_rate),\n metrics=metrics)\n\n return model\n\n\ndef generate_CNN_model(x_shape, class_number, filters, fc_hidden_nodes,\n learning_rate=0.01, regularization_rate=0.01,\n metrics=['accuracy']):\n \"\"\"\n Generate a convolutional neural network (CNN) model.\n\n The compiled Keras model is returned.\n\n Parameters\n ----------\n x_shape : tuple\n Shape of the input dataset: (num_samples, num_timesteps, num_channels)\n class_number : int\n Number of classes for classification task\n filters : list of ints\n number of filters for each convolutional layer\n fc_hidden_nodes : int\n number of hidden nodes for the hidden dense layer\n learning_rate : float\n learning rate\n regularization_rate : float\n regularization rate\n metrics : list\n Metrics to calculate on the validation set.\n See https://keras.io/metrics/ for possible values.\n\n Returns\n -------\n model : Keras model\n The compiled Keras model\n \"\"\"\n dim_length = x_shape[1] # number of samples in a time series\n dim_channels = x_shape[2] # number of channels\n outputdim = class_number # number of classes\n weightinit = 'lecun_uniform' # weight initialization\n model = Sequential()\n model.add(\n BatchNormalization(\n input_shape=(\n dim_length,\n dim_channels)))\n for filter_number in filters:\n model.add(Convolution1D(filter_number, kernel_size=3, padding='same',\n kernel_regularizer=l2(regularization_rate),\n kernel_initializer=weightinit))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(Flatten())\n model.add(Dense(units=fc_hidden_nodes,\n kernel_regularizer=l2(regularization_rate),\n kernel_initializer=weightinit)) # Fully connected layer\n model.add(Activation('relu')) # Relu activation\n model.add(Dense(units=outputdim, kernel_initializer=weightinit))\n model.add(BatchNormalization())\n model.add(Activation(\"softmax\")) # Final classification layer\n\n# if class_number == 2:\n# loss = 'binary_crossentropy'\n# else:\n# loss = 'categorical_crossentropy'\n loss = 'categorical_crossentropy'\n model.compile(loss=loss,\n optimizer=Adam(lr=learning_rate),\n metrics=metrics)\n\n return model\n\n\ndef generate_CNN_hyperparameter_set(min_layers=1, max_layers=10,\n min_filters=10, max_filters=100,\n min_fc_nodes=10, max_fc_nodes=2000,\n low_lr=1, high_lr=4, low_reg=1,\n high_reg=4):\n \"\"\" Generate a hyperparameter set that define a CNN model.\n\n Parameters\n ----------\n min_layers : int\n minimum of Conv layers\n max_layers : int\n maximum of Conv layers\n min_filters : int\n minimum number of filters per Conv layer\n max_filters : int\n maximum number of filters per Conv layer\n min_fc_nodes : int\n minimum number of hidden nodes per Dense layer\n max_fc_nodes : int\n maximum number of hidden nodes per Dense layer\n low_lr : float\n minimum of log range for learning rate: learning rate is sampled\n between `10**(-low_reg)` and `10**(-high_reg)`\n high_lr : float\n maximum of log range for learning rate: learning rate is sampled\n between `10**(-low_reg)` and `10**(-high_reg)`\n low_reg : float\n minimum of log range for regularization rate: regularization rate is\n sampled between `10**(-low_reg)` and `10**(-high_reg)`\n high_reg : float\n maximum of log range for regularization rate: regularization rate is\n sampled between `10**(-low_reg)` and `10**(-high_reg)`\n\n Returns\n ----------\n hyperparameters : dict\n parameters for a CNN model\n \"\"\"\n hyperparameters = generate_base_hyper_parameter_set(\n low_lr, high_lr, low_reg, high_reg)\n number_of_layers = np.random.randint(min_layers, max_layers + 1)\n hyperparameters['filters'] = np.random.randint(\n min_filters, max_filters + 1, number_of_layers)\n hyperparameters['fc_hidden_nodes'] = np.random.randint(\n min_fc_nodes, max_fc_nodes + 1)\n return hyperparameters\n\n\ndef generate_DeepConvLSTM_hyperparameter_set(\n min_conv_layers=1, max_conv_layers=10,\n min_conv_filters=10, max_conv_filters=100,\n min_lstm_layers=1, max_lstm_layers=5,\n min_lstm_dims=10, max_lstm_dims=100,\n low_lr=1, high_lr=4, low_reg=1, high_reg=4):\n \"\"\" Generate a hyperparameter set that defines a DeepConvLSTM model.\n\n Parameters\n ----------\n min_conv_layers : int\n minimum number of Conv layers in DeepConvLSTM model\n max_conv_layers : int\n maximum number of Conv layers in DeepConvLSTM model\n min_conv_filters : int\n minimum number of filters per Conv layer in DeepConvLSTM model\n max_conv_filters : int\n maximum number of filters per Conv layer in DeepConvLSTM model\n min_lstm_layers : int\n minimum number of Conv layers in DeepConvLSTM model\n max_lstm_layers : int\n maximum number of Conv layers in DeepConvLSTM model\n min_lstm_dims : int\n minimum number of hidden nodes per LSTM layer in DeepConvLSTM model\n max_lstm_dims : int\n maximum number of hidden nodes per LSTM layer in DeepConvLSTM model\n low_lr : float\n minimum of log range for learning rate: learning rate is sampled\n between `10**(-low_reg)` and `10**(-high_reg)`\n high_lr : float\n maximum of log range for learning rate: learning rate is sampled\n between `10**(-low_reg)` and `10**(-high_reg)`\n low_reg : float\n minimum of log range for regularization rate: regularization rate is\n sampled between `10**(-low_reg)` and `10**(-high_reg)`\n high_reg : float\n maximum of log range for regularization rate: regularization rate is\n sampled between `10**(-low_reg)` and `10**(-high_reg)`\n\n Returns\n ----------\n hyperparameters: dict\n hyperparameters for a DeepConvLSTM model\n \"\"\"\n hyperparameters = generate_base_hyper_parameter_set(\n low_lr, high_lr, low_reg, high_reg)\n number_of_conv_layers = np.random.randint(\n min_conv_layers, max_conv_layers + 1)\n hyperparameters['filters'] = np.random.randint(\n min_conv_filters, max_conv_filters + 1, number_of_conv_layers).tolist()\n number_of_lstm_layers = np.random.randint(\n min_lstm_layers, max_lstm_layers + 1)\n hyperparameters['lstm_dims'] = np.random.randint(\n min_lstm_dims, max_lstm_dims + 1, number_of_lstm_layers).tolist()\n return hyperparameters\n\n\ndef generate_base_hyper_parameter_set(\n low_lr=1,\n high_lr=4,\n low_reg=1,\n high_reg=4):\n \"\"\" Generate a base set of hyperparameters that are necessary for any\n model, but sufficient for none.\n\n Parameters\n ----------\n low_lr : float\n minimum of log range for learning rate: learning rate is sampled\n between `10**(-low_reg)` and `10**(-high_reg)`\n high_lr : float\n maximum of log range for learning rate: learning rate is sampled\n between `10**(-low_reg)` and `10**(-high_reg)`\n low_reg : float\n minimum of log range for regularization rate: regularization rate is\n sampled between `10**(-low_reg)` and `10**(-high_reg)`\n high_reg : float\n maximum of log range for regularization rate: regularization rate is\n sampled between `10**(-low_reg)` and `10**(-high_reg)`\n\n Returns\n -------\n hyperparameters : dict\n basis hyperpameters\n \"\"\"\n hyperparameters = {}\n hyperparameters['learning_rate'] = get_learning_rate(low_lr, high_lr)\n hyperparameters['regularization_rate'] = get_regularization(\n low_reg, high_reg)\n return hyperparameters\n\n\ndef get_learning_rate(low=1, high=4):\n \"\"\" Return random learning rate 10^-n where n is sampled uniformly between\n low and high bounds.\n\n Parameters\n ----------\n low : float\n low bound\n high : float\n high bound\n\n Returns\n -------\n learning_rate : float\n learning rate\n \"\"\"\n result = 0.001 # Fixed learning rate for Adam #10 ** (-np.random.uniform(low, high))\n return result\n\n\ndef get_regularization(low=1, high=4):\n \"\"\" Return random regularization rate 10^-n where n is sampled uniformly\n between low and high bounds.\n\n Parameters\n ----------\n low : float\n low bound\n high : float\n high bound\n\n Returns\n -------\n regularization_rate : float\n regularization rate\n \"\"\"\n return 10 ** (-np.random.uniform(low, high))\n"
] |
[
[
"numpy.random.uniform",
"numpy.random.random",
"numpy.random.randint"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
joachimwolff/scHiCExplorer
|
[
"8aebb444f3968d398c260690c89c9cd0e3186f0e",
"8aebb444f3968d398c260690c89c9cd0e3186f0e"
] |
[
"schicexplorer/scHicCluster.py",
"schicexplorer/scHicClusterCompartments.py"
] |
[
"import argparse\nimport os\nfrom multiprocessing import Process, Queue\nimport time\n\n\nimport logging\nlog = logging.getLogger(__name__)\nfrom scipy import linalg\nimport cooler\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.cm import get_cmap\nfrom sklearn.cluster import KMeans, SpectralClustering\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.decomposition import PCA\nfrom hicmatrix import HiCMatrix as hm\n\nimport numpy as np\nfrom scipy.sparse import csr_matrix\n\nfrom holoviews.plotting.util import process_cmap\n\nfrom schicexplorer._version import __version__\nfrom schicexplorer.utilities import cell_name_list, create_csr_matrix_all_cells\n\n\ndef parse_arguments(args=None):\n\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n add_help=False,\n description='scHicCluster uses kmeans or spectral clustering to associate each cell to a cluster and therefore to its cell cycle. '\n 'The clustering can be run on the raw data, on a kNN computed via the exact euclidean distance or via PCA. '\n 'Please consider also the other clustering and dimension reduction approaches of the scHicExplorer suite. They can give you better results, '\n 'can be faster or less memory demanding.'\n )\n\n parserRequired = parser.add_argument_group('Required arguments')\n\n # define the arguments\n parserRequired.add_argument('--matrix', '-m',\n help='The single cell Hi-C interaction matrices to cluster. Needs to be in scool format',\n metavar='scool scHi-C matrix',\n required=True)\n parserRequired.add_argument('--numberOfClusters', '-c',\n help='Number of to be computed clusters',\n required=False,\n default=12,\n type=int)\n parserRequired.add_argument('--clusterMethod', '-cm',\n help='Algorithm to cluster the Hi-C matrices',\n choices=['spectral', 'kmeans'],\n default='spectral')\n parserOpt = parser.add_argument_group('Optional arguments')\n\n parserOpt.add_argument('--chromosomes',\n help='List of to be plotted chromosomes',\n nargs='+')\n parserOpt.add_argument('--intraChromosomalContactsOnly', '-ic',\n help='This option loads only the intra-chromosomal contacts. Can improve the cluster result if data is very noisy.',\n action='store_true')\n parserOpt.add_argument('--additionalPCA', '-pca',\n help='Computes PCA on top of a k-nn. Can improve the cluster result.',\n action='store_true')\n parserOpt.add_argument('--dimensionsPCA', '-dim_pca',\n help='The number of dimensions from the PCA matrix that should be considered for clustering. Can improve the cluster result.',\n default=20,\n type=int)\n parserOpt.add_argument('--dimensionReductionMethod', '-drm',\n help='Dimension reduction methods, knn with euclidean distance, pca',\n choices=['none', 'knn', 'pca'],\n default='none')\n parserOpt.add_argument('--createScatterPlot', '-csp',\n help='Create a scatter plot for the clustering, the x and y are the first and second principal component of the computed k-nn graph.',\n required=False,\n default=None)\n parserOpt.add_argument('--numberOfNearestNeighbors', '-k',\n help='Number of to be used computed nearest neighbors for the knn graph. Default is either the default value or the number of the provided cells, whatever is smaller.',\n required=False,\n default=100,\n type=int)\n parserOpt.add_argument('--dpi', '-d',\n help='The dpi of the scatter plot.',\n required=False,\n default=300,\n type=int)\n\n parserOpt.add_argument('--outFileName', '-o',\n help='File name to save the resulting clusters',\n required=True,\n default='clusters.txt')\n parserOpt.add_argument('--cell_coloring_type', '-cct',\n help='A two column list, first colum the cell names as stored in the scool file, second column the associated coloring for the scatter plot',\n required=False)\n parserOpt.add_argument('--cell_coloring_batch', '-ccb',\n help='A two column list, first colum the cell names as stored in the scool file, second column the associated coloring for the scatter plot',\n required=False)\n parserOpt.add_argument('--latexTable', '-lt',\n help='Return the overlap statistics if --cell_coloring_type is given as a latex table.')\n parserOpt.add_argument('--figuresize',\n help='Fontsize in the plot for x and y axis.',\n type=float,\n nargs=2,\n default=(15, 6),\n metavar=('x-size', 'y-size'))\n parserOpt.add_argument('--colorMap',\n help='Color map to use for the heatmap, supported are the categorical colormaps from holoviews: '\n 'http://holoviews.org/user_guide/Colormaps.html',\n default='glasbey_dark')\n parserOpt.add_argument('--fontsize',\n help='Fontsize in the plot for x and y axis.',\n type=float,\n default=15)\n parserOpt.add_argument('--threads', '-t',\n help='Number of threads. Using the python multiprocessing module.',\n required=False,\n default=8,\n type=int)\n parserOpt.add_argument('--help', '-h', action='help', help='show this help message and exit')\n parserOpt.add_argument('--version', action='version',\n version='%(prog)s {}'.format(__version__))\n return parser\n\n\ndef main(args=None):\n\n args = parse_arguments().parse_args(args)\n\n outputFolder = os.path.dirname(os.path.abspath(args.outFileName)) + '/'\n log.debug('outputFolder {}'.format(outputFolder))\n if args.cell_coloring_type:\n cell_name_cell_type_dict = {}\n\n cell_type_color_dict = {}\n color_cell_type_dict = {}\n cell_type_counter = 0\n with open(args.cell_coloring_type, 'r') as file:\n for i, line in enumerate(file.readlines()):\n line = line.strip()\n try:\n cell_name, cell_type = line.split('\\t')\n except Exception:\n cell_name, cell_type = line.split(' ')\n cell_name_cell_type_dict[cell_name] = cell_type\n if cell_type not in cell_type_color_dict:\n cell_type_color_dict[cell_type] = cell_type_counter\n color_cell_type_dict[cell_type_counter] = cell_type\n cell_type_counter += 1\n\n if args.cell_coloring_batch:\n cell_name_cell_type_dict_batch = {}\n\n cell_type_color_dict_batch = {}\n color_cell_type_dict_batch = {}\n cell_type_counter_batch = 0\n with open(args.cell_coloring_batch, 'r') as file:\n for i, line in enumerate(file.readlines()):\n line = line.strip()\n try:\n cell_name, cell_type = line.split('\\t')\n except Exception:\n cell_name, cell_type = line.split(' ')\n cell_name_cell_type_dict_batch[cell_name] = cell_type\n if cell_type not in cell_type_color_dict_batch:\n cell_type_color_dict_batch[cell_type] = cell_type_counter_batch\n color_cell_type_dict_batch[cell_type_counter_batch] = cell_type\n cell_type_counter_batch += 1\n\n raw_file_name = os.path.splitext(os.path.basename(args.outFileName))[0]\n neighborhood_matrix, matrices_list = create_csr_matrix_all_cells(args.matrix, args.threads, args.chromosomes, outputFolder, raw_file_name, args.intraChromosomalContactsOnly)\n\n reduce_to_dimension = neighborhood_matrix.shape[0] - 1\n if args.dimensionReductionMethod == 'knn':\n\n if args.numberOfNearestNeighbors > reduce_to_dimension:\n args.numberOfNearestNeighbors = reduce_to_dimension\n nbrs = NearestNeighbors(n_neighbors=args.numberOfNearestNeighbors, algorithm='ball_tree', n_jobs=args.threads).fit(neighborhood_matrix)\n neighborhood_matrix = nbrs.kneighbors_graph(mode='distance')\n\n if args.additionalPCA:\n pca = PCA(n_components=min(neighborhood_matrix.shape) - 1)\n neighborhood_matrix = pca.fit_transform(neighborhood_matrix.todense())\n if args.dimensionsPCA:\n args.dimensionsPCA = min(args.dimensionsPCA, neighborhood_matrix.shape[0])\n neighborhood_matrix = neighborhood_matrix[:, :args.dimensionsPCA]\n elif args.dimensionReductionMethod == 'pca':\n corrmatrix = np.cov(neighborhood_matrix.todense())\n evals, eigs = linalg.eig(corrmatrix)\n neighborhood_matrix = eigs[:, :reduce_to_dimension].transpose()\n\n if args.clusterMethod == 'spectral':\n spectralClustering_object = SpectralClustering(n_clusters=args.numberOfClusters, n_jobs=args.threads,\n n_neighbors=reduce_to_dimension, affinity='nearest_neighbors', random_state=0, eigen_solver=\"arpack\")\n\n labels_clustering = spectralClustering_object.fit_predict(neighborhood_matrix)\n elif args.clusterMethod == 'kmeans':\n kmeans_object = KMeans(n_clusters=args.numberOfClusters, random_state=0, n_jobs=args.threads, precompute_distances=True)\n labels_clustering = kmeans_object.fit_predict(neighborhood_matrix)\n\n if args.colorMap:\n colors = process_cmap(args.colorMap)\n if args.cell_coloring_type:\n if len(colors) < len(cell_type_color_dict):\n log.error('The chosen colormap offers too less values for the number of clusters.')\n exit(1)\n labels_clustering_cell_type = []\n for cell_name in matrices_list:\n labels_clustering_cell_type.append(cell_type_color_dict[cell_name_cell_type_dict[cell_name]])\n\n labels_clustering_cell_type = np.array(labels_clustering_cell_type)\n\n log.debug('labels_clustering_cell_type: {}'.format(len(labels_clustering_cell_type)))\n log.debug('matrices_list: {}'.format(len(matrices_list)))\n label_x = 'PC1'\n label_y = 'PC2'\n if args.createScatterPlot:\n if args.dimensionReductionMethod == 'none':\n log.warning('Raw matrix clustering scatter plot needs to compute a PCA and can request large amount (> 100 GB) of memory.')\n\n log.debug('args.additionalPCA {}'.format(args.additionalPCA))\n log.debug('args.dimensionReductionMethod {}'.format(args.dimensionReductionMethod))\n\n if args.dimensionReductionMethod == 'none' or (args.dimensionReductionMethod == 'knn' and not args.additionalPCA):\n log.debug('compute pca')\n\n pca = PCA(n_components=min(neighborhood_matrix.shape) - 1)\n neighborhood_matrix_knn = pca.fit_transform(neighborhood_matrix.todense())\n log.debug('compute pca')\n else:\n log.debug('already computed pca')\n\n neighborhood_matrix_knn = neighborhood_matrix\n\n if args.cell_coloring_type:\n plt.figure(figsize=(args.figuresize[0], args.figuresize[1]))\n for i, color in enumerate(colors[:len(cell_type_color_dict)]):\n mask = labels_clustering_cell_type == i\n log.debug('plot cluster: {} {}'.format(color_cell_type_dict[i], np.sum(mask)))\n plt.scatter(neighborhood_matrix_knn[:, 0].T[mask], neighborhood_matrix_knn[:, 1].T[mask], color=color, label=str(color_cell_type_dict[i]), s=20, alpha=0.7)\n\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', fontsize=args.fontsize)\n plt.xticks([])\n plt.yticks([])\n plt.xlabel(label_x, fontsize=args.fontsize)\n plt.ylabel(label_y, fontsize=args.fontsize)\n if '.' not in args.createScatterPlot:\n args.createScatterPlot += '.png'\n scatter_plot_name = '.'.join(args.createScatterPlot.split('.')[:-1]) + '_cell_color.' + args.createScatterPlot.split('.')[-1]\n plt.tight_layout()\n plt.savefig(scatter_plot_name, dpi=args.dpi)\n plt.close()\n if args.cell_coloring_batch:\n if len(colors) < len(cell_type_color_dict_batch):\n log.error('The chosen colormap offers too less values for the number of clusters.')\n exit(1)\n labels_clustering_cell_type_batch = []\n for cell_name in matrices_list:\n labels_clustering_cell_type_batch.append(cell_type_color_dict_batch[cell_name_cell_type_dict_batch[cell_name]])\n\n labels_clustering_cell_type_batch = np.array(labels_clustering_cell_type_batch)\n\n log.debug('labels_clustering_cell_type: {}'.format(len(labels_clustering_cell_type_batch)))\n log.debug('matrices_list: {}'.format(len(matrices_list)))\n\n plt.figure(figsize=(args.figuresize[0], args.figuresize[1]))\n for i, color in enumerate(colors[:len(cell_type_color_dict_batch)]):\n mask = labels_clustering_cell_type_batch == i\n log.debug('plot cluster: {} {}'.format(color_cell_type_dict_batch[i], np.sum(mask)))\n plt.scatter(neighborhood_matrix_knn[:, 0].T[mask], neighborhood_matrix_knn[:, 1].T[mask], color=color, label=str(color_cell_type_dict_batch[i]), s=20, alpha=0.7)\n\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', fontsize=args.fontsize)\n plt.xticks([])\n plt.yticks([])\n plt.xlabel(label_x, fontsize=args.fontsize)\n plt.ylabel(label_y, fontsize=args.fontsize)\n if '.' not in args.createScatterPlot:\n args.createScatterPlot += '.png'\n scatter_plot_name = '.'.join(args.createScatterPlot.split('.')[:-1]) + '_cell_color_batch.' + args.createScatterPlot.split('.')[-1]\n plt.tight_layout()\n plt.savefig(scatter_plot_name, dpi=args.dpi)\n plt.close()\n\n plt.figure(figsize=(args.figuresize[0], args.figuresize[1]))\n for i, color in enumerate(colors[:args.numberOfClusters]):\n mask = labels_clustering == i\n plt.scatter(neighborhood_matrix_knn[:, 0].T[mask], neighborhood_matrix_knn[:, 1].T[mask], color=color, label=str(i), s=20, alpha=0.7)\n plt.legend(fontsize=args.fontsize)\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', fontsize=args.fontsize)\n\n plt.xticks([])\n plt.yticks([])\n plt.xlabel(label_x, fontsize=args.fontsize)\n plt.ylabel(label_y, fontsize=args.fontsize)\n if '.' not in args.createScatterPlot:\n args.createScatterPlot += '.png'\n scatter_plot_name = '.'.join(args.createScatterPlot.split('.')[:-1]) + '.' + args.createScatterPlot.split('.')[-1]\n plt.tight_layout()\n plt.savefig(scatter_plot_name, dpi=args.dpi)\n plt.close()\n\n if args.latexTable and args.cell_coloring_type:\n # compute overlap of cell_type find found clusters\n computed_clusters = set(labels_clustering)\n cell_type_amounts_dict = {}\n # percentage_threshold = 0.8\n\n for threshold in [0.7, 0.8, 0.9]:\n cell_type_amounts_dict[threshold] = {}\n with open(args.latexTable, 'w') as matches_file:\n header = '\\\\begin{table}[!htb]\\n\\\\footnotesize\\n\\\\begin{tabular}{|l'\n body = '\\\\hline Cluster '\n for i in range(len(color_cell_type_dict)):\n mask_cell_type = labels_clustering_cell_type == i\n header += '|c'\n body += '& ' + str(color_cell_type_dict[i]) + ' (' + str(np.sum(mask_cell_type)) + ' cells)'\n header += '|}\\n'\n body += '\\\\\\\\\\n'\n # body = ''\n for i in computed_clusters:\n body += '\\\\hline Cluster ' + str(i)\n mask_computed_clusters = labels_clustering == i\n body += ' (' + str(np.sum(mask_computed_clusters)) + ' cells)'\n for j in range(len(cell_type_color_dict)):\n mask_cell_type = labels_clustering_cell_type == j\n mask = mask_computed_clusters & mask_cell_type\n number_of_matches = np.sum(mask)\n body += '& ' + str(number_of_matches)\n\n if number_of_matches != 1:\n body += ' cells / '\n else:\n body += ' cell / '\n\n body += '{:.2f}'.format((number_of_matches / np.sum(mask_computed_clusters)) * 100) + ' \\\\% '\n for threshold in [0.7, 0.8, 0.9]:\n\n if number_of_matches / np.sum(mask_computed_clusters) >= threshold:\n if color_cell_type_dict[j] in cell_type_amounts_dict[threshold]:\n cell_type_amounts_dict[threshold][color_cell_type_dict[j]] += number_of_matches\n else:\n cell_type_amounts_dict[threshold][color_cell_type_dict[j]] = number_of_matches\n else:\n if color_cell_type_dict[j] in cell_type_amounts_dict[threshold]:\n continue\n else:\n cell_type_amounts_dict[threshold][color_cell_type_dict[j]] = 0\n body += '\\\\\\\\\\n'\n body += '\\\\hline ' + '&' * len(cell_type_color_dict) + '\\\\\\\\\\n'\n\n for threshold in [0.7, 0.8, 0.9]:\n body += '\\\\hline Correct identified $>{}\\\\%$'.format(int(threshold * 100))\n for i in range(len(cell_type_color_dict)):\n mask_cell_type = labels_clustering_cell_type == i\n\n if color_cell_type_dict[i] in cell_type_amounts_dict[threshold]:\n body += '& ' + str(cell_type_amounts_dict[threshold][color_cell_type_dict[i]]) + ' / ' + str(np.sum(mask_cell_type)) + ' ('\n body += '{:.2f}'.format((cell_type_amounts_dict[threshold][color_cell_type_dict[i]] / np.sum(mask_cell_type)) * 100)\n else:\n body += '& ' + str(0) + ' / ' + str(np.sum(mask_cell_type)) + ' ('\n body += '{:.2f}'.format(0 / np.sum(mask_cell_type))\n\n body += ' \\\\%)'\n body += '\\\\\\\\\\n'\n body += '\\\\hline \\n'\n body += '\\\\end{tabular}\\n\\\\caption{}\\n\\\\end{table}'\n\n matches_file.write(header)\n matches_file.write(body)\n\n matrices_cluster = list(zip(matrices_list, labels_clustering))\n np.savetxt(args.outFileName, matrices_cluster, fmt=\"%s\")\n",
"import argparse\nimport os\nfrom multiprocessing import Process, Queue\nimport time\n\nimport logging\nlog = logging.getLogger(__name__)\n\nimport cooler\n\nfrom hicmatrix import HiCMatrix as hm\nfrom hicexplorer.utilities import obs_exp_matrix_lieberman, obs_exp_matrix_non_zero, convertInfsToZeros_ArrayFloat\nfrom hicexplorer.hicPCA import correlateEigenvectorWithGeneTrack, correlateEigenvectorWithHistonMarkTrack\nfrom hicexplorer.utilities import convertNansToZeros, convertInfsToZeros\nfrom sklearn.cluster import KMeans, SpectralClustering\n\nimport numpy as np\nimport pandas as pd\nfrom scipy.sparse import csr_matrix, lil_matrix\nfrom scipy import linalg\nfrom scipy.stats import pearsonr\nimport pyBigWig\n\nimport scipy.sparse\n\nfrom schicexplorer._version import __version__\nfrom schicexplorer.utilities import cell_name_list\n\n\ndef parse_arguments(args=None):\n\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n add_help=False,\n description='scHicClusterCompartments uses kmeans or spectral clustering to associate each cell to a cluster and therefore to its cell cycle. '\n 'The clustering is applied on dimension reduced data based on the A/B compartments track. This approach reduces the number of dimensions from samples * (number of bins)^2 to samples * (number of bins). '\n 'Please consider also the other clustering and dimension reduction approaches of the scHicExplorer suite. They can give you better results, '\n 'can be faster or less memory demanding.'\n )\n\n parserRequired = parser.add_argument_group('Required arguments')\n\n parserRequired.add_argument('--matrix', '-m',\n help='The single cell Hi-C interaction matrices to cluster. Needs to be in scool format',\n metavar='scool scHi-C matrix',\n required=True)\n\n parserRequired.add_argument('--numberOfClusters', '-c',\n help='Number of to be computed clusters',\n required=False,\n default=12,\n type=int)\n parserRequired.add_argument('--outFileName', '-o',\n help='File name to save the resulting clusters',\n required=True,\n default='clusters.txt')\n parserRequired.add_argument('--clusterMethod', '-cm',\n help='Algorithm to cluster the Hi-C matrices',\n choices=['spectral', 'kmeans'],\n default='spectral')\n parserOpt = parser.add_argument_group('Optional arguments')\n\n parserOpt.add_argument('--chromosomes',\n help='List of chromosomes to be included in the '\n 'correlation.',\n default=None,\n nargs='+')\n parserOpt.add_argument('--norm',\n help='Different obs-exp normalization as used by '\n 'Homer software.',\n action='store_true')\n parserOpt.add_argument('--binarization',\n help='Set all positive values of eigenvector to 1 and all negative ones to 0.',\n action='store_true')\n parserOpt.add_argument('--extraTrack',\n help='Either a gene track or a histon mark coverage'\n ' file(preferably a broad mark) is needed to decide'\n ' if the values of the eigenvector need a sign flip'\n ' or not.',\n default=None)\n parserOpt.add_argument('--histonMarkType',\n help='set it to active or inactive. This is only '\n 'necessary if a histon mark coverage file is given '\n 'as an extraTrack.',\n default='active')\n\n parserOpt.add_argument('--threads', '-t',\n help='Number of threads. Using the python multiprocessing module.',\n required=False,\n default=4,\n type=int)\n parserOpt.add_argument('--help', '-h', action='help', help='show this help message and exit')\n parserOpt.add_argument('--version', action='version',\n version='%(prog)s {}'.format(__version__))\n\n return parser\n\n\ndef open_and_store_matrix(pMatrixName, pMatricesList, pIndex, pXDimension, pChromosomes, pNorm, pExtraTrack, pHistonMarkType, pBinarization, pQueue):\n compartments_matrix = None\n\n for i, matrix in enumerate(pMatricesList):\n\n ma = hm.hiCMatrix(pMatrixName + '::' + matrix)\n\n # WARNING\n # DO NOT APPLY BIN MASKING, WILL LEAD TO DIFFERENT SIZES OF THE CHROMOSOMES\n # THIS IS CAUSING A FAIL OF THE COMPUTATION\n # ma.maskBins(ma.nan_bins)\n k = 1\n if pChromosomes:\n ma.keepOnlyTheseChr(pChromosomes)\n\n vecs_list = []\n chrom_list = []\n start_list = []\n end_list = []\n # PCA is computed per chromosome\n length_chromosome = 0\n chromosome_count = len(ma.getChrNames())\n\n for chrname in ma.getChrNames():\n chr_range = ma.getChrBinRange(chrname)\n length_chromosome += chr_range[1] - chr_range[0]\n\n if pExtraTrack and (pExtraTrack.endswith('.bw') or pExtraTrack.endswith('.bigwig')):\n bwTrack = pyBigWig.open(pExtraTrack, 'r')\n\n for chrname in ma.getChrNames():\n chr_range = ma.getChrBinRange(chrname)\n submatrix = ma.matrix[chr_range[0]:chr_range[1],\n chr_range[0]:chr_range[1]]\n if pNorm:\n obs_exp_matrix_ = obs_exp_matrix_non_zero(submatrix, ligation_factor=True)\n else:\n obs_exp_matrix_ = obs_exp_matrix_lieberman(submatrix,\n length_chromosome,\n chromosome_count)\n obs_exp_matrix_ = convertNansToZeros(csr_matrix(obs_exp_matrix_)).todense()\n obs_exp_matrix_ = convertInfsToZeros(csr_matrix(obs_exp_matrix_)).todense()\n\n pearson_correlation_matrix = np.corrcoef(obs_exp_matrix_)\n pearson_correlation_matrix = convertNansToZeros(csr_matrix(pearson_correlation_matrix)).todense()\n pearson_correlation_matrix = convertInfsToZeros(csr_matrix(pearson_correlation_matrix)).todense()\n\n corrmatrix = np.cov(pearson_correlation_matrix)\n corrmatrix = convertNansToZeros(csr_matrix(corrmatrix)).todense()\n corrmatrix = convertInfsToZeros(csr_matrix(corrmatrix)).todense()\n evals, eigs = linalg.eig(corrmatrix)\n\n chrom, start, end, _ = zip(*ma.cut_intervals[chr_range[0]:chr_range[1]])\n\n chrom_list += chrom\n start_list += start\n end_list += end\n if pExtraTrack and (pExtraTrack.endswith('.bw') or pExtraTrack.endswith('.bigwig')):\n assert(len(end) == len(start))\n correlateEigenvectorWithHistonMarkTrack(eigs[:, :k].transpose(),\n bwTrack, chrname, start,\n end, pExtraTrack,\n pHistonMarkType)\n\n vecs_list += eigs[:, :k].tolist()\n if compartments_matrix is None:\n compartments_matrix = np.zeros([pXDimension, len(np.array(vecs_list).flatten())], dtype=np.float)\n\n eigenvector = np.real(np.array(vecs_list).flatten())\n mask = np.isnan(eigenvector)\n if len(mask) > 0:\n eigenvector[mask] = 0\n mask = np.isinf(eigenvector)\n if len(mask) > 0:\n eigenvector[mask] = 0\n\n if pBinarization:\n mask = eigenvector <= 0\n eigenvector[mask] = -1\n mask = eigenvector > 0\n eigenvector[mask] = 1\n\n compartments_matrix[pIndex + i, :] = eigenvector\n\n pQueue.put(compartments_matrix)\n\n return\n\n\ndef main(args=None):\n\n args = parse_arguments().parse_args(args)\n\n matrices_name = args.matrix\n threads = args.threads\n matrices_list = cell_name_list(matrices_name)\n if threads > len(matrices_list):\n threads = len(matrices_list)\n compartments_matrix = None\n\n all_data_collected = False\n thread_done = [False] * threads\n length_index = [None] * threads\n length_index[0] = 0\n matricesPerThread = len(matrices_list) // threads\n queue = [None] * threads\n process = [None] * threads\n for i in range(threads):\n\n if i < threads - 1:\n matrices_name_list = matrices_list[i * matricesPerThread:(i + 1) * matricesPerThread]\n length_index[i + 1] = length_index[i] + len(matrices_name_list)\n else:\n matrices_name_list = matrices_list[i * matricesPerThread:]\n\n queue[i] = Queue()\n process[i] = Process(target=open_and_store_matrix, kwargs=dict(\n pMatrixName=matrices_name,\n pMatricesList=matrices_name_list,\n pIndex=length_index[i],\n pXDimension=len(matrices_list),\n pChromosomes=args.chromosomes,\n pNorm=args.norm,\n pExtraTrack=args.extraTrack,\n pHistonMarkType=args.histonMarkType,\n pBinarization=args.binarization,\n pQueue=queue[i]\n )\n )\n\n process[i].start()\n\n while not all_data_collected:\n for i in range(threads):\n if queue[i] is not None and not queue[i].empty():\n compartments_worker = queue[i].get()\n if compartments_matrix is None:\n compartments_matrix = compartments_worker\n else:\n compartments_matrix += compartments_worker\n\n queue[i] = None\n process[i].join()\n process[i].terminate()\n process[i] = None\n thread_done[i] = True\n all_data_collected = True\n for thread in thread_done:\n if not thread:\n all_data_collected = False\n time.sleep(1)\n\n if args.clusterMethod == 'spectral':\n spectral_clustering = SpectralClustering(n_clusters=args.numberOfClusters, n_jobs=args.threads, random_state=0)\n labels_clustering = spectral_clustering.fit_predict(compartments_matrix)\n elif args.clusterMethod == 'kmeans':\n kmeans_object = KMeans(n_clusters=args.numberOfClusters, random_state=0, n_jobs=args.threads, precompute_distances=True)\n labels_clustering = kmeans_object.fit_predict(compartments_matrix)\n\n matrices_cluster = list(zip(matrices_list, labels_clustering))\n np.savetxt(args.outFileName, matrices_cluster, fmt=\"%s\")\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.tight_layout",
"sklearn.cluster.KMeans",
"matplotlib.use",
"matplotlib.pyplot.savefig",
"sklearn.cluster.SpectralClustering",
"matplotlib.pyplot.ylabel",
"sklearn.neighbors.NearestNeighbors",
"matplotlib.pyplot.close",
"numpy.savetxt",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.xticks",
"numpy.array",
"numpy.sum",
"scipy.linalg.eig",
"matplotlib.pyplot.figure"
],
[
"sklearn.cluster.KMeans",
"numpy.isnan",
"scipy.sparse.csr_matrix",
"sklearn.cluster.SpectralClustering",
"numpy.cov",
"numpy.savetxt",
"numpy.array",
"numpy.isinf",
"scipy.linalg.eig",
"numpy.corrcoef"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"0.14",
"0.15",
"0.12",
"0.10"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"0.14",
"0.15",
"0.12",
"0.10"
],
"tensorflow": []
}
] |
rlaboulaye/transformer
|
[
"119195b2be1d2a3418141a73536d5167e97e06ed"
] |
[
"meta_logger.py"
] |
[
"import os\nimport json\nimport datetime\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\nclass MetaLogger(object):\n\n def __init__(self, meta_config, config, task_directory, load_directory=None, load_epoch=None):\n self.results_directory = os.path.join('meta_results', str(datetime.datetime.now()))\n self.results = {\n 'task_directory': task_directory,\n 'load_directory': load_directory,\n 'load_epoch': load_epoch,\n 'train_losses': [],\n 'train_accuracies': [],\n 'validation_losses': [],\n 'validation_accuracies': [],\n 'baseline_test_loss': 0,\n 'baseline_test_accuracy': 0,\n 'sgd_test_loss': 0,\n 'sgd_test_accuracy': 0,\n 'adam_test_loss': 0,\n 'adam_test_accuracy': 0,\n 'meta_optimizer_test_loss': 0,\n 'meta_optimizer_test_accuracy': 0,\n 'config': config,\n 'meta_config': meta_config\n }\n\n def load(self, file_path):\n self.results_directory, _ = os.path.split(file_path)\n with open(file_path, 'r') as file_obj:\n self.results = json.load(file_obj)\n\n def log(self):\n if not os.path.exists(self.results_directory):\n os.makedirs(self.results_directory)\n with open('{}/results.json'.format(self.results_directory), 'w') as file_obj:\n json.dump(self.results, file_obj, indent=4)\n\n def plot(self):\n plt.figure()\n plt.title('Loss')\n plt.xlabel('Meta Epochs')\n plt.ylabel('Loss')\n plt.xticks(np.arange(0, len(self.results['train_losses']) * .125, .25))\n plt.plot(np.arange(.125, (len(self.results['train_losses']) + 1) * .125, .125), self.results['train_losses'], label='train')\n plt.plot(np.arange(.125, (len(self.results['validation_losses']) + 1) * .125, .125), self.results['validation_losses'], label='validation')\n plt.legend()\n plt.savefig('{}/loss.pdf'.format(self.results_directory))\n plt.close()\n\n plt.figure()\n plt.title('Accuracy')\n plt.xlabel('Meta Epochs')\n plt.ylabel('Accuracy')\n plt.xticks(np.arange(0, len(self.results['train_accuracies']) * .125, .25))\n plt.plot(np.arange(.125, (len(self.results['train_accuracies']) + 1) * .125, .125), self.results['train_accuracies'], label='train')\n plt.plot(np.arange(.125, (len(self.results['validation_accuracies']) + 1) * .125, .125), self.results['validation_accuracies'], label='validation')\n plt.legend()\n plt.savefig('{}/accuracy.pdf'.format(self.results_directory))\n plt.close()\n\n plt.figure()\n plt.title('Test Losses')\n plt.ylabel('Mean Test Loss')\n x_labels = ('Baseline', 'SGD', 'Adam', 'Meta Optimizer')\n x_pos = np.arange(len(x_labels))\n performance = [self.results['{}_test_loss'.format('_'.join(label.lower().split(' ')))] for label in x_labels]\n plt.bar(x_pos, performance, align='center', alpha=0.5)\n plt.xticks(x_pos, x_labels)\n plt.savefig('{}/test_loss.pdf'.format(self.results_directory))\n plt.close()\n\n plt.figure()\n plt.title('Test Accuracies')\n plt.ylabel('Mean Test Accuracy')\n x_labels = ('Baseline', 'SGD', 'Adam', 'Meta Optimizer')\n x_pos = np.arange(len(x_labels))\n performance = [self.results['{}_test_accuracy'.format('_'.join(label.lower().split(' ')))] for label in x_labels]\n plt.bar(x_pos, performance, align='center', alpha=0.5)\n plt.xticks(x_pos, x_labels)\n plt.savefig('{}/test_accuracy.pdf'.format(self.results_directory))\n plt.close()\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.close",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jaywonchung/Learning-ML
|
[
"5298318686144a78bed42d979e10fbd9979c0159"
] |
[
"Implementations/Conditional-Variational-Autoencoder/plot_utils.py"
] |
[
"import torchvision\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n\ndef display_and_save_batch(title, batch, data, save=True, display=True):\n \"\"\"Display and save batch of image using plt\"\"\"\n im = torchvision.utils.make_grid(batch, nrow=int(batch.shape[0]**0.5))\n plt.title(title)\n plt.imshow(np.transpose(im.cpu().numpy(), (1, 2, 0)), cmap='gray')\n if save:\n plt.savefig('results/' + title + data + '.png', transparent=True, bbox_inches='tight')\n if display:\n plt.show()\n\ndef display_and_save_latent(batch, label, data, save=True, display=True):\n \"\"\"Display and save batch of 2-D latent variable using plt\"\"\"\n colors = ['black', 'red', 'green', 'blue', 'yellow', 'cyan', 'magenta', 'pink', 'violet', 'grey']\n z = batch.cpu().detach().numpy()\n l = label.cpu().numpy()\n\n plt.title('Latent variables')\n plt.scatter(z[:,0], z[:,1], c=l, cmap=matplotlib.colors.ListedColormap(colors))\n plt.xlim(-3, 3, )\n plt.ylim(-3, 3)\n if save:\n plt.savefig('results/latent-variable' + data + '.png', transparent=True, bbox_inches='tight')\n if display:\n plt.show()"
] |
[
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.xlim",
"matplotlib.colors.ListedColormap",
"matplotlib.pyplot.show"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ethantsai/nlwhistlers
|
[
"1b8cabf96e4fbb9a032bb4cd03797d65fe7a144b"
] |
[
"dataPlotter.py"
] |
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nlines = open(\"for_james.csv\").read().splitlines()\ndata = [[float(x) for x in lines[i].split(\", \")] for i in range(len(lines))]\n\n# each item in data is a list of floats that can be passed to plt.hist\n\nfor i in range(9):\n plt.hist(data[i], bins=np.logspace(1, 3, 20))\n plt.title(f'Precipitating Energy Distribution at t = {i+0.5} sec')\n plt.xscale(\"log\"); plt.yscale(\"log\"); plt.xlabel('Energy (KeV)'); plt.ylabel('Number of Particles')\n plt.ylim(10,600); plt.xlim(10,1000) \n plt.savefig(f'results/plots/preciphist{i}.png')\n plt.clf()"
] |
[
[
"matplotlib.pyplot.title",
"numpy.logspace",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.yscale",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.xscale",
"matplotlib.pyplot.ylabel"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Jwmc999/Transformers4Rec
|
[
"e6cdf13a7c0102303c0258120274f88b2d42c9c2"
] |
[
"transformers4rec/tf/block/dlrm.py"
] |
[
"#\n# Copyright (c) 2021, NVIDIA CORPORATION.\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\nfrom typing import List, Optional, Union, cast\n\nimport tensorflow as tf\n\nfrom merlin_standard_lib import Schema, Tag\n\nfrom ..features.continuous import ContinuousFeatures\nfrom ..features.embedding import EmbeddingFeatures\nfrom ..tabular.base import TabularBlock\nfrom .base import Block, BlockType\n\n\nclass ExpandDimsAndToTabular(tf.keras.layers.Lambda):\n def __init__(self, **kwargs):\n super().__init__(lambda x: dict(continuous=x), **kwargs)\n\n\[email protected]_keras_serializable(package=\"transformers4rec\")\nclass DLRMBlock(Block):\n def __init__(\n self,\n continuous_features: Union[List[str], Schema, Optional[TabularBlock]],\n embedding_layer: EmbeddingFeatures,\n bottom_mlp: BlockType,\n top_mlp: Optional[BlockType] = None,\n interaction_layer: Optional[tf.keras.layers.Layer] = None,\n **kwargs\n ):\n super().__init__(**kwargs)\n\n _continuous_features: Optional[TabularBlock]\n if isinstance(continuous_features, Schema):\n _continuous_features = cast(\n Optional[TabularBlock],\n ContinuousFeatures.from_schema(\n cast(Schema, continuous_features), aggregation=\"concat\"\n ),\n )\n if isinstance(continuous_features, list):\n _continuous_features = ContinuousFeatures.from_features(\n continuous_features, aggregation=\"concat\"\n )\n else:\n _continuous_features = cast(Optional[TabularBlock], continuous_features)\n\n if _continuous_features:\n continuous_embedding = _continuous_features >> bottom_mlp >> ExpandDimsAndToTabular()\n continuous_embedding.block_name = \"ContinuousEmbedding\"\n self.stack_features = embedding_layer.merge(continuous_embedding, aggregation=\"stack\")\n else:\n embedding_layer.set_aggregation(\"stack\")\n self.stack_features = embedding_layer\n\n # self.stack_features = tabular.MergeTabular(embedding_layer, continuous_embedding,\n # aggregation_registry=\"stack\")\n\n # self.stack_features = embedding_layer + continuous_embedding\n # self.stack_features.aggregation_registry = \"stack\"\n\n from ..layers import DotProductInteraction\n\n self.interaction_layer = interaction_layer or DotProductInteraction()\n\n self.top_mlp = top_mlp\n\n @classmethod\n def from_schema(\n cls, schema: Schema, bottom_mlp: BlockType, top_mlp: Optional[BlockType] = None, **kwargs\n ):\n embedding_layer = EmbeddingFeatures.from_schema(\n schema.select_by_tag(Tag.CATEGORICAL),\n infer_embedding_sizes=False,\n embedding_dim_default=bottom_mlp.layers[-1].units,\n )\n if not embedding_layer:\n raise ValueError(\"embedding_layer must be set.\")\n\n continuous_features = cast(\n Optional[TabularBlock],\n ContinuousFeatures.from_schema(\n schema.select_by_tag(Tag.CONTINUOUS), aggregation=\"concat\"\n ),\n )\n\n return cls(continuous_features, embedding_layer, bottom_mlp, top_mlp=top_mlp, **kwargs)\n\n def call(self, inputs, **kwargs):\n stacked = self.stack_features(inputs)\n interactions = self.interaction_layer(stacked)\n\n return interactions if not self.top_mlp else self.top_mlp(interactions)\n"
] |
[
[
"tensorflow.keras.utils.register_keras_serializable"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
getschomp/pandas
|
[
"85dc1713bc6a1064f4afdf2a907bc9c72cdc364b"
] |
[
"pandas/core/arrays/categorical.py"
] |
[
"# pylint: disable=E1101,W0232\n\nimport numpy as np\nfrom warnings import warn\nimport textwrap\n\nfrom pandas import compat\nfrom pandas.compat import u, lzip\nfrom pandas._libs import lib, algos as libalgos\n\nfrom pandas.core.dtypes.generic import (\n ABCSeries, ABCIndexClass, ABCCategoricalIndex)\nfrom pandas.core.dtypes.missing import isna, notna\nfrom pandas.core.dtypes.inference import is_hashable\nfrom pandas.core.dtypes.cast import (\n maybe_infer_to_datetimelike,\n coerce_indexer_dtype)\nfrom pandas.core.dtypes.dtypes import CategoricalDtype\nfrom pandas.core.dtypes.common import (\n ensure_int64,\n ensure_object,\n ensure_platform_int,\n is_extension_array_dtype,\n is_dtype_equal,\n is_datetimelike,\n is_datetime64_dtype,\n is_timedelta64_dtype,\n is_categorical,\n is_categorical_dtype,\n is_float_dtype,\n is_integer_dtype,\n is_list_like, is_sequence,\n is_scalar, is_iterator,\n is_dict_like)\n\nfrom pandas.core.algorithms import factorize, take_1d, unique1d, take\nfrom pandas.core.accessor import PandasDelegate, delegate_names\nfrom pandas.core.base import (PandasObject,\n NoNewAttributesMixin, _shared_docs)\nimport pandas.core.common as com\nfrom pandas.core.missing import interpolate_2d\nfrom pandas.compat.numpy import function as nv\nfrom pandas.util._decorators import (\n Appender, cache_readonly, deprecate_kwarg, Substitution)\n\nimport pandas.core.algorithms as algorithms\n\nfrom pandas.io.formats import console\nfrom pandas.io.formats.terminal import get_terminal_size\nfrom pandas.util._validators import validate_bool_kwarg, validate_fillna_kwargs\nfrom pandas.core.config import get_option\n\nfrom .base import ExtensionArray\n\n\n_take_msg = textwrap.dedent(\"\"\"\\\n Interpreting negative values in 'indexer' as missing values.\n In the future, this will change to meaning positional indices\n from the right.\n\n Use 'allow_fill=True' to retain the previous behavior and silence this\n warning.\n\n Use 'allow_fill=False' to accept the new behavior.\"\"\")\n\n\ndef _cat_compare_op(op):\n def f(self, other):\n # On python2, you can usually compare any type to any type, and\n # Categoricals can be seen as a custom type, but having different\n # results depending whether categories are the same or not is kind of\n # insane, so be a bit stricter here and use the python3 idea of\n # comparing only things of equal type.\n if isinstance(other, ABCSeries):\n return NotImplemented\n\n if not self.ordered:\n if op in ['__lt__', '__gt__', '__le__', '__ge__']:\n raise TypeError(\"Unordered Categoricals can only compare \"\n \"equality or not\")\n if isinstance(other, Categorical):\n # Two Categoricals can only be be compared if the categories are\n # the same (maybe up to ordering, depending on ordered)\n\n msg = (\"Categoricals can only be compared if \"\n \"'categories' are the same.\")\n if len(self.categories) != len(other.categories):\n raise TypeError(msg + \" Categories are different lengths\")\n elif (self.ordered and not (self.categories ==\n other.categories).all()):\n raise TypeError(msg)\n elif not set(self.categories) == set(other.categories):\n raise TypeError(msg)\n\n if not (self.ordered == other.ordered):\n raise TypeError(\"Categoricals can only be compared if \"\n \"'ordered' is the same\")\n if not self.ordered and not self.categories.equals(\n other.categories):\n # both unordered and different order\n other_codes = _get_codes_for_values(other, self.categories)\n else:\n other_codes = other._codes\n\n na_mask = (self._codes == -1) | (other_codes == -1)\n f = getattr(self._codes, op)\n ret = f(other_codes)\n if na_mask.any():\n # In other series, the leads to False, so do that here too\n ret[na_mask] = False\n return ret\n\n # Numpy-1.9 and earlier may convert a scalar to a zerodim array during\n # comparison operation when second arg has higher priority, e.g.\n #\n # cat[0] < cat\n #\n # With cat[0], for example, being ``np.int64(1)`` by the time it gets\n # into this function would become ``np.array(1)``.\n other = lib.item_from_zerodim(other)\n if is_scalar(other):\n if other in self.categories:\n i = self.categories.get_loc(other)\n return getattr(self._codes, op)(i)\n else:\n if op == '__eq__':\n return np.repeat(False, len(self))\n elif op == '__ne__':\n return np.repeat(True, len(self))\n else:\n msg = (\"Cannot compare a Categorical for op {op} with a \"\n \"scalar, which is not a category.\")\n raise TypeError(msg.format(op=op))\n else:\n\n # allow categorical vs object dtype array comparisons for equality\n # these are only positional comparisons\n if op in ['__eq__', '__ne__']:\n return getattr(np.array(self), op)(np.array(other))\n\n msg = (\"Cannot compare a Categorical for op {op} with type {typ}.\"\n \"\\nIf you want to compare values, use 'np.asarray(cat) \"\n \"<op> other'.\")\n raise TypeError(msg.format(op=op, typ=type(other)))\n\n f.__name__ = op\n\n return f\n\n\ndef _maybe_to_categorical(array):\n \"\"\"\n Coerce to a categorical if a series is given.\n\n Internal use ONLY.\n \"\"\"\n if isinstance(array, (ABCSeries, ABCCategoricalIndex)):\n return array._values\n elif isinstance(array, np.ndarray):\n return Categorical(array)\n return array\n\n\ndef contains(cat, key, container):\n \"\"\"\n Helper for membership check for ``key`` in ``cat``.\n\n This is a helper method for :method:`__contains__`\n and :class:`CategoricalIndex.__contains__`.\n\n Returns True if ``key`` is in ``cat.categories`` and the\n location of ``key`` in ``categories`` is in ``container``.\n\n Parameters\n ----------\n cat : :class:`Categorical`or :class:`categoricalIndex`\n key : a hashable object\n The key to check membership for.\n container : Container (e.g. list-like or mapping)\n The container to check for membership in.\n\n Returns\n -------\n is_in : bool\n True if ``key`` is in ``self.categories`` and location of\n ``key`` in ``categories`` is in ``container``, else False.\n\n Notes\n -----\n This method does not check for NaN values. Do that separately\n before calling this method.\n \"\"\"\n hash(key)\n\n # get location of key in categories.\n # If a KeyError, the key isn't in categories, so logically\n # can't be in container either.\n try:\n loc = cat.categories.get_loc(key)\n except KeyError:\n return False\n\n # loc is the location of key in categories, but also the *value*\n # for key in container. So, `key` may be in categories,\n # but still not in `container`. Example ('b' in categories,\n # but not in values):\n # 'b' in Categorical(['a'], categories=['a', 'b']) # False\n if is_scalar(loc):\n return loc in container\n else:\n # if categories is an IntervalIndex, loc is an array.\n return any(loc_ in container for loc_ in loc)\n\n\n_codes_doc = \"\"\"The category codes of this categorical.\n\nLevel codes are an array if integer which are the positions of the real\nvalues in the categories array.\n\nThere is not setter, use the other categorical methods and the normal item\nsetter to change values in the categorical.\n\"\"\"\n\n\nclass Categorical(ExtensionArray, PandasObject):\n \"\"\"\n Represents a categorical variable in classic R / S-plus fashion\n\n `Categoricals` can only take on only a limited, and usually fixed, number\n of possible values (`categories`). In contrast to statistical categorical\n variables, a `Categorical` might have an order, but numerical operations\n (additions, divisions, ...) are not possible.\n\n All values of the `Categorical` are either in `categories` or `np.nan`.\n Assigning values outside of `categories` will raise a `ValueError`. Order\n is defined by the order of the `categories`, not lexical order of the\n values.\n\n Parameters\n ----------\n values : list-like\n The values of the categorical. If categories are given, values not in\n categories will be replaced with NaN.\n categories : Index-like (unique), optional\n The unique categories for this categorical. If not given, the\n categories are assumed to be the unique values of `values` (sorted, if\n possible, otherwise in the order in which they appear).\n ordered : boolean, (default False)\n Whether or not this categorical is treated as a ordered categorical.\n If True, the resulting categorical will be ordered.\n An ordered categorical respects, when sorted, the order of its\n `categories` attribute (which in turn is the `categories` argument, if\n provided).\n dtype : CategoricalDtype\n An instance of ``CategoricalDtype`` to use for this categorical\n\n .. versionadded:: 0.21.0\n\n Attributes\n ----------\n categories : Index\n The categories of this categorical\n codes : ndarray\n The codes (integer positions, which point to the categories) of this\n categorical, read only.\n ordered : boolean\n Whether or not this Categorical is ordered.\n dtype : CategoricalDtype\n The instance of ``CategoricalDtype`` storing the ``categories``\n and ``ordered``.\n\n .. versionadded:: 0.21.0\n\n Methods\n -------\n from_codes\n __array__\n\n Raises\n ------\n ValueError\n If the categories do not validate.\n TypeError\n If an explicit ``ordered=True`` is given but no `categories` and the\n `values` are not sortable.\n\n Examples\n --------\n >>> pd.Categorical([1, 2, 3, 1, 2, 3])\n [1, 2, 3, 1, 2, 3]\n Categories (3, int64): [1, 2, 3]\n\n >>> pd.Categorical(['a', 'b', 'c', 'a', 'b', 'c'])\n [a, b, c, a, b, c]\n Categories (3, object): [a, b, c]\n\n Ordered `Categoricals` can be sorted according to the custom order\n of the categories and can have a min and max value.\n\n >>> c = pd.Categorical(['a','b','c','a','b','c'], ordered=True,\n ... categories=['c', 'b', 'a'])\n >>> c\n [a, b, c, a, b, c]\n Categories (3, object): [c < b < a]\n >>> c.min()\n 'c'\n\n Notes\n -----\n See the `user guide\n <http://pandas.pydata.org/pandas-docs/stable/categorical.html>`_ for more.\n\n See also\n --------\n pandas.api.types.CategoricalDtype : Type for categorical data\n CategoricalIndex : An Index with an underlying ``Categorical``\n \"\"\"\n\n # For comparisons, so that numpy uses our implementation if the compare\n # ops, which raise\n __array_priority__ = 1000\n _dtype = CategoricalDtype(ordered=False)\n _deprecations = frozenset(['labels'])\n _typ = 'categorical'\n\n def __init__(self, values, categories=None, ordered=None, dtype=None,\n fastpath=False):\n\n # Ways of specifying the dtype (prioritized ordered)\n # 1. dtype is a CategoricalDtype\n # a.) with known categories, use dtype.categories\n # b.) else with Categorical values, use values.dtype\n # c.) else, infer from values\n # d.) specifying dtype=CategoricalDtype and categories is an error\n # 2. dtype is a string 'category'\n # a.) use categories, ordered\n # b.) use values.dtype\n # c.) infer from values\n # 3. dtype is None\n # a.) use categories, ordered\n # b.) use values.dtype\n # c.) infer from values\n\n if dtype is not None:\n # The dtype argument takes precedence over values.dtype (if any)\n if isinstance(dtype, compat.string_types):\n if dtype == 'category':\n dtype = CategoricalDtype(categories, ordered)\n else:\n msg = \"Unknown `dtype` {dtype}\"\n raise ValueError(msg.format(dtype=dtype))\n elif categories is not None or ordered is not None:\n raise ValueError(\"Cannot specify both `dtype` and `categories`\"\n \" or `ordered`.\")\n\n categories = dtype.categories\n\n elif is_categorical(values):\n # If no \"dtype\" was passed, use the one from \"values\", but honor\n # the \"ordered\" and \"categories\" arguments\n dtype = values.dtype._from_categorical_dtype(values.dtype,\n categories, ordered)\n else:\n # If dtype=None and values is not categorical, create a new dtype\n dtype = CategoricalDtype(categories, ordered)\n\n # At this point, dtype is always a CategoricalDtype\n # if dtype.categories is None, we are inferring\n\n if fastpath:\n self._codes = coerce_indexer_dtype(values, categories)\n self._dtype = self._dtype.update_dtype(dtype)\n return\n\n # null_mask indicates missing values we want to exclude from inference.\n # This means: only missing values in list-likes (not arrays/ndframes).\n null_mask = np.array(False)\n\n # sanitize input\n if is_categorical_dtype(values):\n if dtype.categories is None:\n dtype = CategoricalDtype(values.categories, dtype.ordered)\n\n elif not isinstance(values, (ABCIndexClass, ABCSeries)):\n # _sanitize_array coerces np.nan to a string under certain versions\n # of numpy\n values = maybe_infer_to_datetimelike(values, convert_dates=True)\n if not isinstance(values, np.ndarray):\n values = _convert_to_list_like(values)\n from pandas.core.series import _sanitize_array\n # By convention, empty lists result in object dtype:\n if len(values) == 0:\n sanitize_dtype = 'object'\n else:\n sanitize_dtype = None\n null_mask = isna(values)\n if null_mask.any():\n values = [values[idx] for idx in np.where(~null_mask)[0]]\n values = _sanitize_array(values, None, dtype=sanitize_dtype)\n\n if dtype.categories is None:\n try:\n codes, categories = factorize(values, sort=True)\n except TypeError:\n codes, categories = factorize(values, sort=False)\n if dtype.ordered:\n # raise, as we don't have a sortable data structure and so\n # the user should give us one by specifying categories\n raise TypeError(\"'values' is not ordered, please \"\n \"explicitly specify the categories order \"\n \"by passing in a categories argument.\")\n except ValueError:\n\n # FIXME\n raise NotImplementedError(\"> 1 ndim Categorical are not \"\n \"supported at this time\")\n\n # we're inferring from values\n dtype = CategoricalDtype(categories, dtype.ordered)\n\n elif is_categorical_dtype(values):\n old_codes = (values.cat.codes if isinstance(values, ABCSeries)\n else values.codes)\n codes = _recode_for_categories(old_codes, values.dtype.categories,\n dtype.categories)\n\n else:\n codes = _get_codes_for_values(values, dtype.categories)\n\n if null_mask.any():\n # Reinsert -1 placeholders for previously removed missing values\n full_codes = - np.ones(null_mask.shape, dtype=codes.dtype)\n full_codes[~null_mask] = codes\n codes = full_codes\n\n self._dtype = self._dtype.update_dtype(dtype)\n self._codes = coerce_indexer_dtype(codes, dtype.categories)\n\n @property\n def categories(self):\n \"\"\"The categories of this categorical.\n\n Setting assigns new values to each category (effectively a rename of\n each individual category).\n\n The assigned value has to be a list-like object. All items must be\n unique and the number of items in the new categories must be the same\n as the number of items in the old categories.\n\n Assigning to `categories` is a inplace operation!\n\n Raises\n ------\n ValueError\n If the new categories do not validate as categories or if the\n number of new categories is unequal the number of old categories\n\n See also\n --------\n rename_categories\n reorder_categories\n add_categories\n remove_categories\n remove_unused_categories\n set_categories\n \"\"\"\n return self.dtype.categories\n\n @categories.setter\n def categories(self, categories):\n new_dtype = CategoricalDtype(categories, ordered=self.ordered)\n if (self.dtype.categories is not None and\n len(self.dtype.categories) != len(new_dtype.categories)):\n raise ValueError(\"new categories need to have the same number of \"\n \"items as the old categories!\")\n self._dtype = new_dtype\n\n @property\n def ordered(self):\n \"\"\"Whether the categories have an ordered relationship\"\"\"\n return self.dtype.ordered\n\n @property\n def dtype(self):\n \"\"\"The :class:`~pandas.api.types.CategoricalDtype` for this instance\"\"\"\n return self._dtype\n\n @property\n def _ndarray_values(self):\n return self.codes\n\n @property\n def _constructor(self):\n return Categorical\n\n @classmethod\n def _from_sequence(cls, scalars, dtype=None, copy=False):\n return Categorical(scalars, dtype=dtype)\n\n def copy(self):\n \"\"\" Copy constructor. \"\"\"\n return self._constructor(values=self._codes.copy(),\n dtype=self.dtype,\n fastpath=True)\n\n def astype(self, dtype, copy=True):\n \"\"\"\n Coerce this type to another dtype\n\n Parameters\n ----------\n dtype : numpy dtype or pandas type\n copy : bool, default True\n By default, astype always returns a newly allocated object.\n If copy is set to False and dtype is categorical, the original\n object is returned.\n\n .. versionadded:: 0.19.0\n\n \"\"\"\n if is_categorical_dtype(dtype):\n # GH 10696/18593\n dtype = self.dtype.update_dtype(dtype)\n self = self.copy() if copy else self\n if dtype == self.dtype:\n return self\n return self._set_dtype(dtype)\n return np.array(self, dtype=dtype, copy=copy)\n\n @cache_readonly\n def ndim(self):\n \"\"\"Number of dimensions of the Categorical \"\"\"\n return self._codes.ndim\n\n @cache_readonly\n def size(self):\n \"\"\" return the len of myself \"\"\"\n return len(self)\n\n @cache_readonly\n def itemsize(self):\n \"\"\" return the size of a single category \"\"\"\n return self.categories.itemsize\n\n def tolist(self):\n \"\"\"\n Return a list of the values.\n\n These are each a scalar type, which is a Python scalar\n (for str, int, float) or a pandas scalar\n (for Timestamp/Timedelta/Interval/Period)\n \"\"\"\n return list(self)\n\n @property\n def base(self):\n \"\"\" compat, we are always our own object \"\"\"\n return None\n\n @classmethod\n def _from_inferred_categories(cls, inferred_categories, inferred_codes,\n dtype):\n \"\"\"Construct a Categorical from inferred values\n\n For inferred categories (`dtype` is None) the categories are sorted.\n For explicit `dtype`, the `inferred_categories` are cast to the\n appropriate type.\n\n Parameters\n ----------\n\n inferred_categories : Index\n inferred_codes : Index\n dtype : CategoricalDtype or 'category'\n\n Returns\n -------\n Categorical\n \"\"\"\n from pandas import Index, to_numeric, to_datetime, to_timedelta\n\n cats = Index(inferred_categories)\n\n known_categories = (isinstance(dtype, CategoricalDtype) and\n dtype.categories is not None)\n\n if known_categories:\n # Convert to a specialzed type with `dtype` if specified\n if dtype.categories.is_numeric():\n cats = to_numeric(inferred_categories, errors='coerce')\n elif is_datetime64_dtype(dtype.categories):\n cats = to_datetime(inferred_categories, errors='coerce')\n elif is_timedelta64_dtype(dtype.categories):\n cats = to_timedelta(inferred_categories, errors='coerce')\n\n if known_categories:\n # recode from observation order to dtype.categories order\n categories = dtype.categories\n codes = _recode_for_categories(inferred_codes, cats, categories)\n elif not cats.is_monotonic_increasing:\n # sort categories and recode for unknown categories\n unsorted = cats.copy()\n categories = cats.sort_values()\n codes = _recode_for_categories(inferred_codes, unsorted,\n categories)\n dtype = CategoricalDtype(categories, ordered=False)\n else:\n dtype = CategoricalDtype(cats, ordered=False)\n codes = inferred_codes\n\n return cls(codes, dtype=dtype, fastpath=True)\n\n @classmethod\n def from_codes(cls, codes, categories, ordered=False):\n \"\"\"\n Make a Categorical type from codes and categories arrays.\n\n This constructor is useful if you already have codes and categories and\n so do not need the (computation intensive) factorization step, which is\n usually done on the constructor.\n\n If your data does not follow this convention, please use the normal\n constructor.\n\n Parameters\n ----------\n codes : array-like, integers\n An integer array, where each integer points to a category in\n categories or -1 for NaN\n categories : index-like\n The categories for the categorical. Items need to be unique.\n ordered : boolean, (default False)\n Whether or not this categorical is treated as a ordered\n categorical. If not given, the resulting categorical will be\n unordered.\n \"\"\"\n codes = np.asarray(codes) # #21767\n if not is_integer_dtype(codes):\n msg = \"codes need to be array-like integers\"\n if is_float_dtype(codes):\n icodes = codes.astype('i8')\n if (icodes == codes).all():\n msg = None\n codes = icodes\n warn((\"float codes will be disallowed in the future and \"\n \"raise a ValueError\"), FutureWarning, stacklevel=2)\n if msg:\n raise ValueError(msg)\n\n try:\n codes = coerce_indexer_dtype(codes, categories)\n except (ValueError, TypeError):\n raise ValueError(\n \"codes need to be convertible to an arrays of integers\")\n\n categories = CategoricalDtype.validate_categories(categories)\n\n if len(codes) and (codes.max() >= len(categories) or codes.min() < -1):\n raise ValueError(\"codes need to be between -1 and \"\n \"len(categories)-1\")\n\n return cls(codes, categories=categories, ordered=ordered,\n fastpath=True)\n\n _codes = None\n\n def _get_codes(self):\n \"\"\" Get the codes.\n\n Returns\n -------\n codes : integer array view\n A non writable view of the `codes` array.\n \"\"\"\n v = self._codes.view()\n v.flags.writeable = False\n return v\n\n def _set_codes(self, codes):\n \"\"\"\n Not settable by the user directly\n \"\"\"\n raise ValueError(\"cannot set Categorical codes directly\")\n\n codes = property(fget=_get_codes, fset=_set_codes, doc=_codes_doc)\n\n def _set_categories(self, categories, fastpath=False):\n \"\"\" Sets new categories inplace\n\n Parameters\n ----------\n fastpath : boolean (default: False)\n Don't perform validation of the categories for uniqueness or nulls\n\n Examples\n --------\n >>> c = pd.Categorical(['a', 'b'])\n >>> c\n [a, b]\n Categories (2, object): [a, b]\n\n >>> c._set_categories(pd.Index(['a', 'c']))\n >>> c\n [a, c]\n Categories (2, object): [a, c]\n \"\"\"\n\n if fastpath:\n new_dtype = CategoricalDtype._from_fastpath(categories,\n self.ordered)\n else:\n new_dtype = CategoricalDtype(categories, ordered=self.ordered)\n if (not fastpath and self.dtype.categories is not None and\n len(new_dtype.categories) != len(self.dtype.categories)):\n raise ValueError(\"new categories need to have the same number of \"\n \"items than the old categories!\")\n\n self._dtype = new_dtype\n\n def _set_dtype(self, dtype):\n \"\"\"Internal method for directly updating the CategoricalDtype\n\n Parameters\n ----------\n dtype : CategoricalDtype\n\n Notes\n -----\n We don't do any validation here. It's assumed that the dtype is\n a (valid) instance of `CategoricalDtype`.\n \"\"\"\n codes = _recode_for_categories(self.codes, self.categories,\n dtype.categories)\n return type(self)(codes, dtype=dtype, fastpath=True)\n\n def set_ordered(self, value, inplace=False):\n \"\"\"\n Sets the ordered attribute to the boolean value\n\n Parameters\n ----------\n value : boolean to set whether this categorical is ordered (True) or\n not (False)\n inplace : boolean (default: False)\n Whether or not to set the ordered attribute inplace or return a copy\n of this categorical with ordered set to the value\n \"\"\"\n inplace = validate_bool_kwarg(inplace, 'inplace')\n new_dtype = CategoricalDtype(self.categories, ordered=value)\n cat = self if inplace else self.copy()\n cat._dtype = new_dtype\n if not inplace:\n return cat\n\n def as_ordered(self, inplace=False):\n \"\"\"\n Sets the Categorical to be ordered\n\n Parameters\n ----------\n inplace : boolean (default: False)\n Whether or not to set the ordered attribute inplace or return a copy\n of this categorical with ordered set to True\n \"\"\"\n inplace = validate_bool_kwarg(inplace, 'inplace')\n return self.set_ordered(True, inplace=inplace)\n\n def as_unordered(self, inplace=False):\n \"\"\"\n Sets the Categorical to be unordered\n\n Parameters\n ----------\n inplace : boolean (default: False)\n Whether or not to set the ordered attribute inplace or return a copy\n of this categorical with ordered set to False\n \"\"\"\n inplace = validate_bool_kwarg(inplace, 'inplace')\n return self.set_ordered(False, inplace=inplace)\n\n def set_categories(self, new_categories, ordered=None, rename=False,\n inplace=False):\n \"\"\" Sets the categories to the specified new_categories.\n\n `new_categories` can include new categories (which will result in\n unused categories) or remove old categories (which results in values\n set to NaN). If `rename==True`, the categories will simple be renamed\n (less or more items than in old categories will result in values set to\n NaN or in unused categories respectively).\n\n This method can be used to perform more than one action of adding,\n removing, and reordering simultaneously and is therefore faster than\n performing the individual steps via the more specialised methods.\n\n On the other hand this methods does not do checks (e.g., whether the\n old categories are included in the new categories on a reorder), which\n can result in surprising changes, for example when using special string\n dtypes on python3, which does not considers a S1 string equal to a\n single char python string.\n\n Raises\n ------\n ValueError\n If new_categories does not validate as categories\n\n Parameters\n ----------\n new_categories : Index-like\n The categories in new order.\n ordered : boolean, (default: False)\n Whether or not the categorical is treated as a ordered categorical.\n If not given, do not change the ordered information.\n rename : boolean (default: False)\n Whether or not the new_categories should be considered as a rename\n of the old categories or as reordered categories.\n inplace : boolean (default: False)\n Whether or not to reorder the categories inplace or return a copy of\n this categorical with reordered categories.\n\n Returns\n -------\n cat : Categorical with reordered categories or None if inplace.\n\n See also\n --------\n rename_categories\n reorder_categories\n add_categories\n remove_categories\n remove_unused_categories\n \"\"\"\n inplace = validate_bool_kwarg(inplace, 'inplace')\n if ordered is None:\n ordered = self.dtype.ordered\n new_dtype = CategoricalDtype(new_categories, ordered=ordered)\n\n cat = self if inplace else self.copy()\n if rename:\n if (cat.dtype.categories is not None and\n len(new_dtype.categories) < len(cat.dtype.categories)):\n # remove all _codes which are larger and set to -1/NaN\n self._codes[self._codes >= len(new_dtype.categories)] = -1\n else:\n codes = _recode_for_categories(self.codes, self.categories,\n new_dtype.categories)\n cat._codes = codes\n cat._dtype = new_dtype\n\n if not inplace:\n return cat\n\n def rename_categories(self, new_categories, inplace=False):\n \"\"\" Renames categories.\n\n Raises\n ------\n ValueError\n If new categories are list-like and do not have the same number of\n items than the current categories or do not validate as categories\n\n Parameters\n ----------\n new_categories : list-like, dict-like or callable\n\n * list-like: all items must be unique and the number of items in\n the new categories must match the existing number of categories.\n\n * dict-like: specifies a mapping from\n old categories to new. Categories not contained in the mapping\n are passed through and extra categories in the mapping are\n ignored.\n\n .. versionadded:: 0.21.0\n\n * callable : a callable that is called on all items in the old\n categories and whose return values comprise the new categories.\n\n .. versionadded:: 0.23.0\n\n .. warning::\n\n Currently, Series are considered list like. In a future version\n of pandas they'll be considered dict-like.\n\n inplace : boolean (default: False)\n Whether or not to rename the categories inplace or return a copy of\n this categorical with renamed categories.\n\n Returns\n -------\n cat : Categorical or None\n With ``inplace=False``, the new categorical is returned.\n With ``inplace=True``, there is no return value.\n\n See also\n --------\n reorder_categories\n add_categories\n remove_categories\n remove_unused_categories\n set_categories\n\n Examples\n --------\n >>> c = pd.Categorical(['a', 'a', 'b'])\n >>> c.rename_categories([0, 1])\n [0, 0, 1]\n Categories (2, int64): [0, 1]\n\n For dict-like ``new_categories``, extra keys are ignored and\n categories not in the dictionary are passed through\n\n >>> c.rename_categories({'a': 'A', 'c': 'C'})\n [A, A, b]\n Categories (2, object): [A, b]\n\n You may also provide a callable to create the new categories\n\n >>> c.rename_categories(lambda x: x.upper())\n [A, A, B]\n Categories (2, object): [A, B]\n \"\"\"\n inplace = validate_bool_kwarg(inplace, 'inplace')\n cat = self if inplace else self.copy()\n\n if isinstance(new_categories, ABCSeries):\n msg = (\"Treating Series 'new_categories' as a list-like and using \"\n \"the values. In a future version, 'rename_categories' will \"\n \"treat Series like a dictionary.\\n\"\n \"For dict-like, use 'new_categories.to_dict()'\\n\"\n \"For list-like, use 'new_categories.values'.\")\n warn(msg, FutureWarning, stacklevel=2)\n new_categories = list(new_categories)\n\n if is_dict_like(new_categories):\n cat.categories = [new_categories.get(item, item)\n for item in cat.categories]\n elif callable(new_categories):\n cat.categories = [new_categories(item) for item in cat.categories]\n else:\n cat.categories = new_categories\n if not inplace:\n return cat\n\n def reorder_categories(self, new_categories, ordered=None, inplace=False):\n \"\"\" Reorders categories as specified in new_categories.\n\n `new_categories` need to include all old categories and no new category\n items.\n\n Raises\n ------\n ValueError\n If the new categories do not contain all old category items or any\n new ones\n\n Parameters\n ----------\n new_categories : Index-like\n The categories in new order.\n ordered : boolean, optional\n Whether or not the categorical is treated as a ordered categorical.\n If not given, do not change the ordered information.\n inplace : boolean (default: False)\n Whether or not to reorder the categories inplace or return a copy of\n this categorical with reordered categories.\n\n Returns\n -------\n cat : Categorical with reordered categories or None if inplace.\n\n See also\n --------\n rename_categories\n add_categories\n remove_categories\n remove_unused_categories\n set_categories\n \"\"\"\n inplace = validate_bool_kwarg(inplace, 'inplace')\n if set(self.dtype.categories) != set(new_categories):\n raise ValueError(\"items in new_categories are not the same as in \"\n \"old categories\")\n return self.set_categories(new_categories, ordered=ordered,\n inplace=inplace)\n\n def add_categories(self, new_categories, inplace=False):\n \"\"\" Add new categories.\n\n `new_categories` will be included at the last/highest place in the\n categories and will be unused directly after this call.\n\n Raises\n ------\n ValueError\n If the new categories include old categories or do not validate as\n categories\n\n Parameters\n ----------\n new_categories : category or list-like of category\n The new categories to be included.\n inplace : boolean (default: False)\n Whether or not to add the categories inplace or return a copy of\n this categorical with added categories.\n\n Returns\n -------\n cat : Categorical with new categories added or None if inplace.\n\n See also\n --------\n rename_categories\n reorder_categories\n remove_categories\n remove_unused_categories\n set_categories\n \"\"\"\n inplace = validate_bool_kwarg(inplace, 'inplace')\n if not is_list_like(new_categories):\n new_categories = [new_categories]\n already_included = set(new_categories) & set(self.dtype.categories)\n if len(already_included) != 0:\n msg = (\"new categories must not include old categories: \"\n \"{already_included!s}\")\n raise ValueError(msg.format(already_included=already_included))\n new_categories = list(self.dtype.categories) + list(new_categories)\n new_dtype = CategoricalDtype(new_categories, self.ordered)\n\n cat = self if inplace else self.copy()\n cat._dtype = new_dtype\n cat._codes = coerce_indexer_dtype(cat._codes, new_dtype.categories)\n if not inplace:\n return cat\n\n def remove_categories(self, removals, inplace=False):\n \"\"\" Removes the specified categories.\n\n `removals` must be included in the old categories. Values which were in\n the removed categories will be set to NaN\n\n Raises\n ------\n ValueError\n If the removals are not contained in the categories\n\n Parameters\n ----------\n removals : category or list of categories\n The categories which should be removed.\n inplace : boolean (default: False)\n Whether or not to remove the categories inplace or return a copy of\n this categorical with removed categories.\n\n Returns\n -------\n cat : Categorical with removed categories or None if inplace.\n\n See also\n --------\n rename_categories\n reorder_categories\n add_categories\n remove_unused_categories\n set_categories\n \"\"\"\n inplace = validate_bool_kwarg(inplace, 'inplace')\n if not is_list_like(removals):\n removals = [removals]\n\n removal_set = set(list(removals))\n not_included = removal_set - set(self.dtype.categories)\n new_categories = [c for c in self.dtype.categories\n if c not in removal_set]\n\n # GH 10156\n if any(isna(removals)):\n not_included = [x for x in not_included if notna(x)]\n new_categories = [x for x in new_categories if notna(x)]\n\n if len(not_included) != 0:\n msg = \"removals must all be in old categories: {not_included!s}\"\n raise ValueError(msg.format(not_included=not_included))\n\n return self.set_categories(new_categories, ordered=self.ordered,\n rename=False, inplace=inplace)\n\n def remove_unused_categories(self, inplace=False):\n \"\"\" Removes categories which are not used.\n\n Parameters\n ----------\n inplace : boolean (default: False)\n Whether or not to drop unused categories inplace or return a copy of\n this categorical with unused categories dropped.\n\n Returns\n -------\n cat : Categorical with unused categories dropped or None if inplace.\n\n See also\n --------\n rename_categories\n reorder_categories\n add_categories\n remove_categories\n set_categories\n \"\"\"\n inplace = validate_bool_kwarg(inplace, 'inplace')\n cat = self if inplace else self.copy()\n idx, inv = np.unique(cat._codes, return_inverse=True)\n\n if idx.size != 0 and idx[0] == -1: # na sentinel\n idx, inv = idx[1:], inv - 1\n\n new_categories = cat.dtype.categories.take(idx)\n new_dtype = CategoricalDtype._from_fastpath(new_categories,\n ordered=self.ordered)\n cat._dtype = new_dtype\n cat._codes = coerce_indexer_dtype(inv, new_dtype.categories)\n\n if not inplace:\n return cat\n\n def map(self, mapper):\n \"\"\"\n Map categories using input correspondence (dict, Series, or function).\n\n Maps the categories to new categories. If the mapping correspondence is\n one-to-one the result is a :class:`~pandas.Categorical` which has the\n same order property as the original, otherwise a :class:`~pandas.Index`\n is returned.\n\n If a `dict` or :class:`~pandas.Series` is used any unmapped category is\n mapped to `NaN`. Note that if this happens an :class:`~pandas.Index`\n will be returned.\n\n Parameters\n ----------\n mapper : function, dict, or Series\n Mapping correspondence.\n\n Returns\n -------\n pandas.Categorical or pandas.Index\n Mapped categorical.\n\n See Also\n --------\n CategoricalIndex.map : Apply a mapping correspondence on a\n :class:`~pandas.CategoricalIndex`.\n Index.map : Apply a mapping correspondence on an\n :class:`~pandas.Index`.\n Series.map : Apply a mapping correspondence on a\n :class:`~pandas.Series`.\n Series.apply : Apply more complex functions on a\n :class:`~pandas.Series`.\n\n Examples\n --------\n >>> cat = pd.Categorical(['a', 'b', 'c'])\n >>> cat\n [a, b, c]\n Categories (3, object): [a, b, c]\n >>> cat.map(lambda x: x.upper())\n [A, B, C]\n Categories (3, object): [A, B, C]\n >>> cat.map({'a': 'first', 'b': 'second', 'c': 'third'})\n [first, second, third]\n Categories (3, object): [first, second, third]\n\n If the mapping is one-to-one the ordering of the categories is\n preserved:\n\n >>> cat = pd.Categorical(['a', 'b', 'c'], ordered=True)\n >>> cat\n [a, b, c]\n Categories (3, object): [a < b < c]\n >>> cat.map({'a': 3, 'b': 2, 'c': 1})\n [3, 2, 1]\n Categories (3, int64): [3 < 2 < 1]\n\n If the mapping is not one-to-one an :class:`~pandas.Index` is returned:\n\n >>> cat.map({'a': 'first', 'b': 'second', 'c': 'first'})\n Index(['first', 'second', 'first'], dtype='object')\n\n If a `dict` is used, all unmapped categories are mapped to `NaN` and\n the result is an :class:`~pandas.Index`:\n\n >>> cat.map({'a': 'first', 'b': 'second'})\n Index(['first', 'second', nan], dtype='object')\n \"\"\"\n new_categories = self.categories.map(mapper)\n try:\n return self.from_codes(self._codes.copy(),\n categories=new_categories,\n ordered=self.ordered)\n except ValueError:\n return np.take(new_categories, self._codes)\n\n __eq__ = _cat_compare_op('__eq__')\n __ne__ = _cat_compare_op('__ne__')\n __lt__ = _cat_compare_op('__lt__')\n __gt__ = _cat_compare_op('__gt__')\n __le__ = _cat_compare_op('__le__')\n __ge__ = _cat_compare_op('__ge__')\n\n # for Series/ndarray like compat\n @property\n def shape(self):\n \"\"\" Shape of the Categorical.\n\n For internal compatibility with numpy arrays.\n\n Returns\n -------\n shape : tuple\n \"\"\"\n\n return tuple([len(self._codes)])\n\n def shift(self, periods):\n \"\"\"\n Shift Categorical by desired number of periods.\n\n Parameters\n ----------\n periods : int\n Number of periods to move, can be positive or negative\n\n Returns\n -------\n shifted : Categorical\n \"\"\"\n # since categoricals always have ndim == 1, an axis parameter\n # doesn't make any sense here.\n codes = self.codes\n if codes.ndim > 1:\n raise NotImplementedError(\"Categorical with ndim > 1.\")\n if np.prod(codes.shape) and (periods != 0):\n codes = np.roll(codes, ensure_platform_int(periods), axis=0)\n if periods > 0:\n codes[:periods] = -1\n else:\n codes[periods:] = -1\n\n return self.from_codes(codes, categories=self.categories,\n ordered=self.ordered)\n\n def __array__(self, dtype=None):\n \"\"\"\n The numpy array interface.\n\n Returns\n -------\n values : numpy array\n A numpy array of either the specified dtype or,\n if dtype==None (default), the same dtype as\n categorical.categories.dtype\n \"\"\"\n ret = take_1d(self.categories.values, self._codes)\n if dtype and not is_dtype_equal(dtype, self.categories.dtype):\n return np.asarray(ret, dtype)\n if is_extension_array_dtype(ret):\n # When we're a Categorical[ExtensionArray], like Interval,\n # we need to ensure __array__ get's all the way to an\n # ndarray.\n ret = np.asarray(ret)\n return ret\n\n def __setstate__(self, state):\n \"\"\"Necessary for making this object picklable\"\"\"\n if not isinstance(state, dict):\n raise Exception('invalid pickle state')\n\n # Provide compatibility with pre-0.15.0 Categoricals.\n if '_categories' not in state and '_levels' in state:\n state['_categories'] = self.dtype.validate_categories(state.pop(\n '_levels'))\n if '_codes' not in state and 'labels' in state:\n state['_codes'] = coerce_indexer_dtype(\n state.pop('labels'), state['_categories'])\n\n # 0.16.0 ordered change\n if '_ordered' not in state:\n\n # >=15.0 < 0.16.0\n if 'ordered' in state:\n state['_ordered'] = state.pop('ordered')\n else:\n state['_ordered'] = False\n\n # 0.21.0 CategoricalDtype change\n if '_dtype' not in state:\n state['_dtype'] = CategoricalDtype(state['_categories'],\n state['_ordered'])\n\n for k, v in compat.iteritems(state):\n setattr(self, k, v)\n\n @property\n def T(self):\n return self\n\n @property\n def nbytes(self):\n return self._codes.nbytes + self.dtype.categories.values.nbytes\n\n def memory_usage(self, deep=False):\n \"\"\"\n Memory usage of my values\n\n Parameters\n ----------\n deep : bool\n Introspect the data deeply, interrogate\n `object` dtypes for system-level memory consumption\n\n Returns\n -------\n bytes used\n\n Notes\n -----\n Memory usage does not include memory consumed by elements that\n are not components of the array if deep=False\n\n See Also\n --------\n numpy.ndarray.nbytes\n \"\"\"\n return self._codes.nbytes + self.dtype.categories.memory_usage(\n deep=deep)\n\n @Substitution(klass='Categorical')\n @Appender(_shared_docs['searchsorted'])\n def searchsorted(self, value, side='left', sorter=None):\n if not self.ordered:\n raise ValueError(\"Categorical not ordered\\nyou can use \"\n \".as_ordered() to change the Categorical to an \"\n \"ordered one\")\n\n from pandas.core.series import Series\n\n values_as_codes = _get_codes_for_values(Series(value).values,\n self.categories)\n\n if -1 in values_as_codes:\n raise ValueError(\"Value(s) to be inserted must be in categories.\")\n\n return self.codes.searchsorted(values_as_codes, side=side,\n sorter=sorter)\n\n def isna(self):\n \"\"\"\n Detect missing values\n\n Missing values (-1 in .codes) are detected.\n\n Returns\n -------\n a boolean array of whether my values are null\n\n See also\n --------\n isna : top-level isna\n isnull : alias of isna\n Categorical.notna : boolean inverse of Categorical.isna\n\n \"\"\"\n\n ret = self._codes == -1\n return ret\n isnull = isna\n\n def notna(self):\n \"\"\"\n Inverse of isna\n\n Both missing values (-1 in .codes) and NA as a category are detected as\n null.\n\n Returns\n -------\n a boolean array of whether my values are not null\n\n See also\n --------\n notna : top-level notna\n notnull : alias of notna\n Categorical.isna : boolean inverse of Categorical.notna\n\n \"\"\"\n return ~self.isna()\n notnull = notna\n\n def put(self, *args, **kwargs):\n \"\"\"\n Replace specific elements in the Categorical with given values.\n \"\"\"\n raise NotImplementedError((\"'put' is not yet implemented \"\n \"for Categorical\"))\n\n def dropna(self):\n \"\"\"\n Return the Categorical without null values.\n\n Missing values (-1 in .codes) are detected.\n\n Returns\n -------\n valid : Categorical\n \"\"\"\n result = self[self.notna()]\n\n return result\n\n def value_counts(self, dropna=True):\n \"\"\"\n Returns a Series containing counts of each category.\n\n Every category will have an entry, even those with a count of 0.\n\n Parameters\n ----------\n dropna : boolean, default True\n Don't include counts of NaN.\n\n Returns\n -------\n counts : Series\n\n See Also\n --------\n Series.value_counts\n\n \"\"\"\n from numpy import bincount\n from pandas import Series, CategoricalIndex\n\n code, cat = self._codes, self.categories\n ncat, mask = len(cat), 0 <= code\n ix, clean = np.arange(ncat), mask.all()\n\n if dropna or clean:\n obs = code if clean else code[mask]\n count = bincount(obs, minlength=ncat or None)\n else:\n count = bincount(np.where(mask, code, ncat))\n ix = np.append(ix, -1)\n\n ix = self._constructor(ix, dtype=self.dtype,\n fastpath=True)\n\n return Series(count, index=CategoricalIndex(ix), dtype='int64')\n\n def get_values(self):\n \"\"\" Return the values.\n\n For internal compatibility with pandas formatting.\n\n Returns\n -------\n values : numpy array\n A numpy array of the same dtype as categorical.categories.dtype or\n Index if datetime / periods\n \"\"\"\n # if we are a datetime and period index, return Index to keep metadata\n if is_datetimelike(self.categories):\n return self.categories.take(self._codes, fill_value=np.nan)\n return np.array(self)\n\n def check_for_ordered(self, op):\n \"\"\" assert that we are ordered \"\"\"\n if not self.ordered:\n raise TypeError(\"Categorical is not ordered for operation {op}\\n\"\n \"you can use .as_ordered() to change the \"\n \"Categorical to an ordered one\\n\".format(op=op))\n\n def _values_for_argsort(self):\n return self._codes.copy()\n\n def argsort(self, *args, **kwargs):\n # TODO(PY2): use correct signature\n # We have to do *args, **kwargs to avoid a a py2-only signature\n # issue since np.argsort differs from argsort.\n \"\"\"Return the indices that would sort the Categorical.\n\n Parameters\n ----------\n ascending : bool, default True\n Whether the indices should result in an ascending\n or descending sort.\n kind : {'quicksort', 'mergesort', 'heapsort'}, optional\n Sorting algorithm.\n *args, **kwargs:\n passed through to :func:`numpy.argsort`.\n\n Returns\n -------\n argsorted : numpy array\n\n See also\n --------\n numpy.ndarray.argsort\n\n Notes\n -----\n While an ordering is applied to the category values, arg-sorting\n in this context refers more to organizing and grouping together\n based on matching category values. Thus, this function can be\n called on an unordered Categorical instance unlike the functions\n 'Categorical.min' and 'Categorical.max'.\n\n Examples\n --------\n >>> pd.Categorical(['b', 'b', 'a', 'c']).argsort()\n array([2, 0, 1, 3])\n\n >>> cat = pd.Categorical(['b', 'b', 'a', 'c'],\n ... categories=['c', 'b', 'a'],\n ... ordered=True)\n >>> cat.argsort()\n array([3, 0, 1, 2])\n \"\"\"\n # Keep the implementation here just for the docstring.\n return super(Categorical, self).argsort(*args, **kwargs)\n\n def sort_values(self, inplace=False, ascending=True, na_position='last'):\n \"\"\" Sorts the Categorical by category value returning a new\n Categorical by default.\n\n While an ordering is applied to the category values, sorting in this\n context refers more to organizing and grouping together based on\n matching category values. Thus, this function can be called on an\n unordered Categorical instance unlike the functions 'Categorical.min'\n and 'Categorical.max'.\n\n Parameters\n ----------\n inplace : boolean, default False\n Do operation in place.\n ascending : boolean, default True\n Order ascending. Passing False orders descending. The\n ordering parameter provides the method by which the\n category values are organized.\n na_position : {'first', 'last'} (optional, default='last')\n 'first' puts NaNs at the beginning\n 'last' puts NaNs at the end\n\n Returns\n -------\n y : Categorical or None\n\n See Also\n --------\n Categorical.sort\n Series.sort_values\n\n Examples\n --------\n >>> c = pd.Categorical([1, 2, 2, 1, 5])\n >>> c\n [1, 2, 2, 1, 5]\n Categories (3, int64): [1, 2, 5]\n >>> c.sort_values()\n [1, 1, 2, 2, 5]\n Categories (3, int64): [1, 2, 5]\n >>> c.sort_values(ascending=False)\n [5, 2, 2, 1, 1]\n Categories (3, int64): [1, 2, 5]\n\n Inplace sorting can be done as well:\n\n >>> c.sort_values(inplace=True)\n >>> c\n [1, 1, 2, 2, 5]\n Categories (3, int64): [1, 2, 5]\n >>>\n >>> c = pd.Categorical([1, 2, 2, 1, 5])\n\n 'sort_values' behaviour with NaNs. Note that 'na_position'\n is independent of the 'ascending' parameter:\n\n >>> c = pd.Categorical([np.nan, 2, 2, np.nan, 5])\n >>> c\n [NaN, 2.0, 2.0, NaN, 5.0]\n Categories (2, int64): [2, 5]\n >>> c.sort_values()\n [2.0, 2.0, 5.0, NaN, NaN]\n Categories (2, int64): [2, 5]\n >>> c.sort_values(ascending=False)\n [5.0, 2.0, 2.0, NaN, NaN]\n Categories (2, int64): [2, 5]\n >>> c.sort_values(na_position='first')\n [NaN, NaN, 2.0, 2.0, 5.0]\n Categories (2, int64): [2, 5]\n >>> c.sort_values(ascending=False, na_position='first')\n [NaN, NaN, 5.0, 2.0, 2.0]\n Categories (2, int64): [2, 5]\n \"\"\"\n inplace = validate_bool_kwarg(inplace, 'inplace')\n if na_position not in ['last', 'first']:\n msg = 'invalid na_position: {na_position!r}'\n raise ValueError(msg.format(na_position=na_position))\n\n codes = np.sort(self._codes)\n if not ascending:\n codes = codes[::-1]\n\n # NaN handling\n na_mask = (codes == -1)\n if na_mask.any():\n n_nans = len(codes[na_mask])\n if na_position == \"first\":\n # in this case sort to the front\n new_codes = codes.copy()\n new_codes[0:n_nans] = -1\n new_codes[n_nans:] = codes[~na_mask]\n codes = new_codes\n elif na_position == \"last\":\n # ... and to the end\n new_codes = codes.copy()\n pos = len(codes) - n_nans\n new_codes[0:pos] = codes[~na_mask]\n new_codes[pos:] = -1\n codes = new_codes\n if inplace:\n self._codes = codes\n return\n else:\n return self._constructor(values=codes, dtype=self.dtype,\n fastpath=True)\n\n def _values_for_rank(self):\n \"\"\"\n For correctly ranking ordered categorical data. See GH#15420\n\n Ordered categorical data should be ranked on the basis of\n codes with -1 translated to NaN.\n\n Returns\n -------\n numpy array\n\n \"\"\"\n from pandas import Series\n if self.ordered:\n values = self.codes\n mask = values == -1\n if mask.any():\n values = values.astype('float64')\n values[mask] = np.nan\n elif self.categories.is_numeric():\n values = np.array(self)\n else:\n # reorder the categories (so rank can use the float codes)\n # instead of passing an object array to rank\n values = np.array(\n self.rename_categories(Series(self.categories).rank().values)\n )\n return values\n\n def ravel(self, order='C'):\n \"\"\" Return a flattened (numpy) array.\n\n For internal compatibility with numpy arrays.\n\n Returns\n -------\n raveled : numpy array\n \"\"\"\n return np.array(self)\n\n def view(self):\n \"\"\"Return a view of myself.\n\n For internal compatibility with numpy arrays.\n\n Returns\n -------\n view : Categorical\n Returns `self`!\n \"\"\"\n return self\n\n def to_dense(self):\n \"\"\"Return my 'dense' representation\n\n For internal compatibility with numpy arrays.\n\n Returns\n -------\n dense : array\n \"\"\"\n return np.asarray(self)\n\n @deprecate_kwarg(old_arg_name='fill_value', new_arg_name='value')\n def fillna(self, value=None, method=None, limit=None):\n \"\"\" Fill NA/NaN values using the specified method.\n\n Parameters\n ----------\n value : scalar, dict, Series\n If a scalar value is passed it is used to fill all missing values.\n Alternatively, a Series or dict can be used to fill in different\n values for each index. The value should not be a list. The\n value(s) passed should either be in the categories or should be\n NaN.\n method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None\n Method to use for filling holes in reindexed Series\n pad / ffill: propagate last valid observation forward to next valid\n backfill / bfill: use NEXT valid observation to fill gap\n limit : int, default None\n (Not implemented yet for Categorical!)\n If method is specified, this is the maximum number of consecutive\n NaN values to forward/backward fill. In other words, if there is\n a gap with more than this number of consecutive NaNs, it will only\n be partially filled. If method is not specified, this is the\n maximum number of entries along the entire axis where NaNs will be\n filled.\n\n Returns\n -------\n filled : Categorical with NA/NaN filled\n \"\"\"\n value, method = validate_fillna_kwargs(\n value, method, validate_scalar_dict_value=False\n )\n\n if value is None:\n value = np.nan\n if limit is not None:\n raise NotImplementedError(\"specifying a limit for fillna has not \"\n \"been implemented yet\")\n\n codes = self._codes\n\n # pad / bfill\n if method is not None:\n\n values = self.to_dense().reshape(-1, len(self))\n values = interpolate_2d(values, method, 0, None,\n value).astype(self.categories.dtype)[0]\n codes = _get_codes_for_values(values, self.categories)\n\n else:\n\n # If value is a dict or a Series (a dict value has already\n # been converted to a Series)\n if isinstance(value, ABCSeries):\n if not value[~value.isin(self.categories)].isna().all():\n raise ValueError(\"fill value must be in categories\")\n\n values_codes = _get_codes_for_values(value, self.categories)\n indexer = np.where(values_codes != -1)\n codes[indexer] = values_codes[values_codes != -1]\n\n # If value is not a dict or Series it should be a scalar\n elif is_hashable(value):\n if not isna(value) and value not in self.categories:\n raise ValueError(\"fill value must be in categories\")\n\n mask = codes == -1\n if mask.any():\n codes = codes.copy()\n if isna(value):\n codes[mask] = -1\n else:\n codes[mask] = self.categories.get_loc(value)\n\n else:\n raise TypeError('\"value\" parameter must be a scalar, dict '\n 'or Series, but you passed a '\n '\"{0}\"'.format(type(value).__name__))\n\n return self._constructor(codes, dtype=self.dtype, fastpath=True)\n\n def take_nd(self, indexer, allow_fill=None, fill_value=None):\n \"\"\"\n Take elements from the Categorical.\n\n Parameters\n ----------\n indexer : sequence of integers\n allow_fill : bool, default None.\n How to handle negative values in `indexer`.\n\n * False: negative values in `indices` indicate positional indices\n from the right. This is similar to\n :func:`numpy.take`.\n\n * True: negative values in `indices` indicate missing values\n (the default). These values are set to `fill_value`. Any other\n other negative values raise a ``ValueError``.\n\n .. versionchanged:: 0.23.0\n\n Deprecated the default value of `allow_fill`. The deprecated\n default is ``True``. In the future, this will change to\n ``False``.\n\n Returns\n -------\n Categorical\n This Categorical will have the same categories and ordered as\n `self`.\n \"\"\"\n indexer = np.asarray(indexer, dtype=np.intp)\n if allow_fill is None:\n if (indexer < 0).any():\n warn(_take_msg, FutureWarning, stacklevel=2)\n allow_fill = True\n\n if isna(fill_value):\n # For categorical, any NA value is considered a user-facing\n # NA value. Our storage NA value is -1.\n fill_value = -1\n\n codes = take(self._codes, indexer, allow_fill=allow_fill,\n fill_value=fill_value)\n result = self._constructor(codes, dtype=self.dtype, fastpath=True)\n return result\n\n take = take_nd\n\n def _slice(self, slicer):\n \"\"\" Return a slice of myself.\n\n For internal compatibility with numpy arrays.\n \"\"\"\n\n # only allow 1 dimensional slicing, but can\n # in a 2-d case be passd (slice(None),....)\n if isinstance(slicer, tuple) and len(slicer) == 2:\n if not com.is_null_slice(slicer[0]):\n raise AssertionError(\"invalid slicing for a 1-ndim \"\n \"categorical\")\n slicer = slicer[1]\n\n codes = self._codes[slicer]\n return self._constructor(values=codes, dtype=self.dtype, fastpath=True)\n\n def __len__(self):\n \"\"\"The length of this Categorical.\"\"\"\n return len(self._codes)\n\n def __iter__(self):\n \"\"\"Returns an Iterator over the values of this Categorical.\"\"\"\n return iter(self.get_values().tolist())\n\n def __contains__(self, key):\n \"\"\"Returns True if `key` is in this Categorical.\"\"\"\n # if key is a NaN, check if any NaN is in self.\n if isna(key):\n return self.isna().any()\n\n return contains(self, key, container=self._codes)\n\n def _tidy_repr(self, max_vals=10, footer=True):\n \"\"\" a short repr displaying only max_vals and an optional (but default\n footer)\n \"\"\"\n num = max_vals // 2\n head = self[:num]._get_repr(length=False, footer=False)\n tail = self[-(max_vals - num):]._get_repr(length=False, footer=False)\n\n result = u('{head}, ..., {tail}').format(head=head[:-1], tail=tail[1:])\n if footer:\n result = u('{result}\\n{footer}').format(result=result,\n footer=self._repr_footer())\n\n return compat.text_type(result)\n\n def _repr_categories(self):\n \"\"\" return the base repr for the categories \"\"\"\n max_categories = (10 if get_option(\"display.max_categories\") == 0 else\n get_option(\"display.max_categories\"))\n from pandas.io.formats import format as fmt\n if len(self.categories) > max_categories:\n num = max_categories // 2\n head = fmt.format_array(self.categories[:num], None)\n tail = fmt.format_array(self.categories[-num:], None)\n category_strs = head + [\"...\"] + tail\n else:\n category_strs = fmt.format_array(self.categories, None)\n\n # Strip all leading spaces, which format_array adds for columns...\n category_strs = [x.strip() for x in category_strs]\n return category_strs\n\n def _repr_categories_info(self):\n \"\"\" Returns a string representation of the footer.\"\"\"\n\n category_strs = self._repr_categories()\n dtype = getattr(self.categories, 'dtype_str',\n str(self.categories.dtype))\n\n levheader = \"Categories ({length}, {dtype}): \".format(\n length=len(self.categories), dtype=dtype)\n width, height = get_terminal_size()\n max_width = get_option(\"display.width\") or width\n if console.in_ipython_frontend():\n # 0 = no breaks\n max_width = 0\n levstring = \"\"\n start = True\n cur_col_len = len(levheader) # header\n sep_len, sep = (3, \" < \") if self.ordered else (2, \", \")\n linesep = sep.rstrip() + \"\\n\" # remove whitespace\n for val in category_strs:\n if max_width != 0 and cur_col_len + sep_len + len(val) > max_width:\n levstring += linesep + (\" \" * (len(levheader) + 1))\n cur_col_len = len(levheader) + 1 # header + a whitespace\n elif not start:\n levstring += sep\n cur_col_len += len(val)\n levstring += val\n start = False\n # replace to simple save space by\n return levheader + \"[\" + levstring.replace(\" < ... < \", \" ... \") + \"]\"\n\n def _repr_footer(self):\n\n return u('Length: {length}\\n{info}').format(\n length=len(self), info=self._repr_categories_info())\n\n def _get_repr(self, length=True, na_rep='NaN', footer=True):\n from pandas.io.formats import format as fmt\n formatter = fmt.CategoricalFormatter(self, length=length,\n na_rep=na_rep, footer=footer)\n result = formatter.to_string()\n return compat.text_type(result)\n\n def __unicode__(self):\n \"\"\" Unicode representation. \"\"\"\n _maxlen = 10\n if len(self._codes) > _maxlen:\n result = self._tidy_repr(_maxlen)\n elif len(self._codes) > 0:\n result = self._get_repr(length=len(self) > _maxlen)\n else:\n msg = self._get_repr(length=False, footer=True).replace(\"\\n\", \", \")\n result = ('[], {repr_msg}'.format(repr_msg=msg))\n\n return result\n\n def _maybe_coerce_indexer(self, indexer):\n \"\"\" return an indexer coerced to the codes dtype \"\"\"\n if isinstance(indexer, np.ndarray) and indexer.dtype.kind == 'i':\n indexer = indexer.astype(self._codes.dtype)\n return indexer\n\n def __getitem__(self, key):\n \"\"\" Return an item. \"\"\"\n if isinstance(key, (int, np.integer)):\n i = self._codes[key]\n if i == -1:\n return np.nan\n else:\n return self.categories[i]\n else:\n return self._constructor(values=self._codes[key],\n dtype=self.dtype, fastpath=True)\n\n def __setitem__(self, key, value):\n \"\"\" Item assignment.\n\n\n Raises\n ------\n ValueError\n If (one or more) Value is not in categories or if a assigned\n `Categorical` does not have the same categories\n \"\"\"\n\n # require identical categories set\n if isinstance(value, Categorical):\n if not value.categories.equals(self.categories):\n raise ValueError(\"Cannot set a Categorical with another, \"\n \"without identical categories\")\n\n rvalue = value if is_list_like(value) else [value]\n\n from pandas import Index\n to_add = Index(rvalue).difference(self.categories)\n\n # no assignments of values not in categories, but it's always ok to set\n # something to np.nan\n if len(to_add) and not isna(to_add).all():\n raise ValueError(\"Cannot setitem on a Categorical with a new \"\n \"category, set the categories first\")\n\n # set by position\n if isinstance(key, (int, np.integer)):\n pass\n\n # tuple of indexers (dataframe)\n elif isinstance(key, tuple):\n # only allow 1 dimensional slicing, but can\n # in a 2-d case be passd (slice(None),....)\n if len(key) == 2:\n if not com.is_null_slice(key[0]):\n raise AssertionError(\"invalid slicing for a 1-ndim \"\n \"categorical\")\n key = key[1]\n elif len(key) == 1:\n key = key[0]\n else:\n raise AssertionError(\"invalid slicing for a 1-ndim \"\n \"categorical\")\n\n # slicing in Series or Categorical\n elif isinstance(key, slice):\n pass\n\n # Array of True/False in Series or Categorical\n else:\n # There is a bug in numpy, which does not accept a Series as a\n # indexer\n # https://github.com/pandas-dev/pandas/issues/6168\n # https://github.com/numpy/numpy/issues/4240 -> fixed in numpy 1.9\n # FIXME: remove when numpy 1.9 is the lowest numpy version pandas\n # accepts...\n key = np.asarray(key)\n\n lindexer = self.categories.get_indexer(rvalue)\n lindexer = self._maybe_coerce_indexer(lindexer)\n self._codes[key] = lindexer\n\n def _reverse_indexer(self):\n \"\"\"\n Compute the inverse of a categorical, returning\n a dict of categories -> indexers.\n\n *This is an internal function*\n\n Returns\n -------\n dict of categories -> indexers\n\n Example\n -------\n In [1]: c = pd.Categorical(list('aabca'))\n\n In [2]: c\n Out[2]:\n [a, a, b, c, a]\n Categories (3, object): [a, b, c]\n\n In [3]: c.categories\n Out[3]: Index([u'a', u'b', u'c'], dtype='object')\n\n In [4]: c.codes\n Out[4]: array([0, 0, 1, 2, 0], dtype=int8)\n\n In [5]: c._reverse_indexer()\n Out[5]: {'a': array([0, 1, 4]), 'b': array([2]), 'c': array([3])}\n\n \"\"\"\n categories = self.categories\n r, counts = libalgos.groupsort_indexer(self.codes.astype('int64'),\n categories.size)\n counts = counts.cumsum()\n result = [r[counts[indexer]:counts[indexer + 1]]\n for indexer in range(len(counts) - 1)]\n result = dict(zip(categories, result))\n return result\n\n # reduction ops #\n def _reduce(self, name, axis=0, skipna=True, **kwargs):\n func = getattr(self, name, None)\n if func is None:\n msg = 'Categorical cannot perform the operation {op}'\n raise TypeError(msg.format(op=name))\n return func(**kwargs)\n\n def min(self, numeric_only=None, **kwargs):\n \"\"\" The minimum value of the object.\n\n Only ordered `Categoricals` have a minimum!\n\n Raises\n ------\n TypeError\n If the `Categorical` is not `ordered`.\n\n Returns\n -------\n min : the minimum of this `Categorical`\n \"\"\"\n self.check_for_ordered('min')\n if numeric_only:\n good = self._codes != -1\n pointer = self._codes[good].min(**kwargs)\n else:\n pointer = self._codes.min(**kwargs)\n if pointer == -1:\n return np.nan\n else:\n return self.categories[pointer]\n\n def max(self, numeric_only=None, **kwargs):\n \"\"\" The maximum value of the object.\n\n Only ordered `Categoricals` have a maximum!\n\n Raises\n ------\n TypeError\n If the `Categorical` is not `ordered`.\n\n Returns\n -------\n max : the maximum of this `Categorical`\n \"\"\"\n self.check_for_ordered('max')\n if numeric_only:\n good = self._codes != -1\n pointer = self._codes[good].max(**kwargs)\n else:\n pointer = self._codes.max(**kwargs)\n if pointer == -1:\n return np.nan\n else:\n return self.categories[pointer]\n\n def mode(self, dropna=True):\n \"\"\"\n Returns the mode(s) of the Categorical.\n\n Always returns `Categorical` even if only one value.\n\n Parameters\n ----------\n dropna : boolean, default True\n Don't consider counts of NaN/NaT.\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n modes : `Categorical` (sorted)\n \"\"\"\n\n import pandas._libs.hashtable as htable\n codes = self._codes\n if dropna:\n good = self._codes != -1\n codes = self._codes[good]\n codes = sorted(htable.mode_int64(ensure_int64(codes), dropna))\n return self._constructor(values=codes, dtype=self.dtype, fastpath=True)\n\n def unique(self):\n \"\"\"\n Return the ``Categorical`` which ``categories`` and ``codes`` are\n unique. Unused categories are NOT returned.\n\n - unordered category: values and categories are sorted by appearance\n order.\n - ordered category: values are sorted by appearance order, categories\n keeps existing order.\n\n Returns\n -------\n unique values : ``Categorical``\n\n Examples\n --------\n An unordered Categorical will return categories in the\n order of appearance.\n\n >>> pd.Categorical(list('baabc'))\n [b, a, c]\n Categories (3, object): [b, a, c]\n\n >>> pd.Categorical(list('baabc'), categories=list('abc'))\n [b, a, c]\n Categories (3, object): [b, a, c]\n\n An ordered Categorical preserves the category ordering.\n\n >>> pd.Categorical(list('baabc'),\n ... categories=list('abc'),\n ... ordered=True)\n [b, a, c]\n Categories (3, object): [a < b < c]\n\n See Also\n --------\n unique\n CategoricalIndex.unique\n Series.unique\n\n \"\"\"\n\n # unlike np.unique, unique1d does not sort\n unique_codes = unique1d(self.codes)\n cat = self.copy()\n\n # keep nan in codes\n cat._codes = unique_codes\n\n # exclude nan from indexer for categories\n take_codes = unique_codes[unique_codes != -1]\n if self.ordered:\n take_codes = np.sort(take_codes)\n return cat.set_categories(cat.categories.take(take_codes))\n\n def _values_for_factorize(self):\n codes = self.codes.astype('int64')\n return codes, -1\n\n @classmethod\n def _from_factorized(cls, uniques, original):\n return original._constructor(original.categories.take(uniques),\n categories=original.categories,\n ordered=original.ordered)\n\n def equals(self, other):\n \"\"\"\n Returns True if categorical arrays are equal.\n\n Parameters\n ----------\n other : `Categorical`\n\n Returns\n -------\n are_equal : boolean\n \"\"\"\n if self.is_dtype_equal(other):\n if self.categories.equals(other.categories):\n # fastpath to avoid re-coding\n other_codes = other._codes\n else:\n other_codes = _recode_for_categories(other.codes,\n other.categories,\n self.categories)\n return np.array_equal(self._codes, other_codes)\n return False\n\n def is_dtype_equal(self, other):\n \"\"\"\n Returns True if categoricals are the same dtype\n same categories, and same ordered\n\n Parameters\n ----------\n other : Categorical\n\n Returns\n -------\n are_equal : boolean\n \"\"\"\n\n try:\n return hash(self.dtype) == hash(other.dtype)\n except (AttributeError, TypeError):\n return False\n\n def describe(self):\n \"\"\" Describes this Categorical\n\n Returns\n -------\n description: `DataFrame`\n A dataframe with frequency and counts by category.\n \"\"\"\n counts = self.value_counts(dropna=False)\n freqs = counts / float(counts.sum())\n\n from pandas.core.reshape.concat import concat\n result = concat([counts, freqs], axis=1)\n result.columns = ['counts', 'freqs']\n result.index.name = 'categories'\n\n return result\n\n def repeat(self, repeats, *args, **kwargs):\n \"\"\"\n Repeat elements of a Categorical.\n\n See also\n --------\n numpy.ndarray.repeat\n\n \"\"\"\n nv.validate_repeat(args, kwargs)\n codes = self._codes.repeat(repeats)\n return self._constructor(values=codes, dtype=self.dtype, fastpath=True)\n\n # Implement the ExtensionArray interface\n @property\n def _can_hold_na(self):\n return True\n\n @classmethod\n def _concat_same_type(self, to_concat):\n from pandas.core.dtypes.concat import _concat_categorical\n\n return _concat_categorical(to_concat)\n\n def _formatting_values(self):\n return self\n\n def isin(self, values):\n \"\"\"\n Check whether `values` are contained in Categorical.\n\n Return a boolean NumPy Array showing whether each element in\n the Categorical matches an element in the passed sequence of\n `values` exactly.\n\n Parameters\n ----------\n values : set or list-like\n The sequence of values to test. Passing in a single string will\n raise a ``TypeError``. Instead, turn a single string into a\n list of one element.\n\n Returns\n -------\n isin : numpy.ndarray (bool dtype)\n\n Raises\n ------\n TypeError\n * If `values` is not a set or list-like\n\n See Also\n --------\n pandas.Series.isin : equivalent method on Series\n\n Examples\n --------\n\n >>> s = pd.Categorical(['lama', 'cow', 'lama', 'beetle', 'lama',\n ... 'hippo'])\n >>> s.isin(['cow', 'lama'])\n array([ True, True, True, False, True, False])\n\n Passing a single string as ``s.isin('lama')`` will raise an error. Use\n a list of one element instead:\n\n >>> s.isin(['lama'])\n array([ True, False, True, False, True, False])\n \"\"\"\n from pandas.core.series import _sanitize_array\n if not is_list_like(values):\n raise TypeError(\"only list-like objects are allowed to be passed\"\n \" to isin(), you passed a [{values_type}]\"\n .format(values_type=type(values).__name__))\n values = _sanitize_array(values, None, None)\n null_mask = np.asarray(isna(values))\n code_values = self.categories.get_indexer(values)\n code_values = code_values[null_mask | (code_values >= 0)]\n return algorithms.isin(self.codes, code_values)\n\n\n# The Series.cat accessor\n\n\n@delegate_names(delegate=Categorical,\n accessors=[\"categories\", \"ordered\"],\n typ=\"property\")\n@delegate_names(delegate=Categorical,\n accessors=[\"rename_categories\", \"reorder_categories\",\n \"add_categories\", \"remove_categories\",\n \"remove_unused_categories\", \"set_categories\",\n \"as_ordered\", \"as_unordered\"],\n typ=\"method\")\nclass CategoricalAccessor(PandasDelegate, PandasObject, NoNewAttributesMixin):\n \"\"\"\n Accessor object for categorical properties of the Series values.\n\n Be aware that assigning to `categories` is a inplace operation, while all\n methods return new categorical data per default (but can be called with\n `inplace=True`).\n\n Parameters\n ----------\n data : Series or CategoricalIndex\n\n Examples\n --------\n >>> s.cat.categories\n >>> s.cat.categories = list('abc')\n >>> s.cat.rename_categories(list('cab'))\n >>> s.cat.reorder_categories(list('cab'))\n >>> s.cat.add_categories(['d','e'])\n >>> s.cat.remove_categories(['d'])\n >>> s.cat.remove_unused_categories()\n >>> s.cat.set_categories(list('abcde'))\n >>> s.cat.as_ordered()\n >>> s.cat.as_unordered()\n\n \"\"\"\n\n def __init__(self, data):\n self._validate(data)\n self._parent = data.values\n self.index = data.index\n self.name = data.name\n self._freeze()\n\n @staticmethod\n def _validate(data):\n if not is_categorical_dtype(data.dtype):\n raise AttributeError(\"Can only use .cat accessor with a \"\n \"'category' dtype\")\n\n def _delegate_property_get(self, name):\n return getattr(self._parent, name)\n\n def _delegate_property_set(self, name, new_values):\n return setattr(self._parent, name, new_values)\n\n @property\n def codes(self):\n from pandas import Series\n return Series(self._parent.codes, index=self.index)\n\n def _delegate_method(self, name, *args, **kwargs):\n from pandas import Series\n method = getattr(self._parent, name)\n res = method(*args, **kwargs)\n if res is not None:\n return Series(res, index=self.index, name=self.name)\n\n\n# utility routines\n\n\ndef _get_codes_for_values(values, categories):\n \"\"\"\n utility routine to turn values into codes given the specified categories\n \"\"\"\n from pandas.core.algorithms import _get_data_algo, _hashtables\n if is_dtype_equal(values.dtype, categories.dtype):\n # To prevent erroneous dtype coercion in _get_data_algo, retrieve\n # the underlying numpy array. gh-22702\n values = getattr(values, 'values', values)\n categories = getattr(categories, 'values', categories)\n else:\n values = ensure_object(values)\n categories = ensure_object(categories)\n\n (hash_klass, vec_klass), vals = _get_data_algo(values, _hashtables)\n (_, _), cats = _get_data_algo(categories, _hashtables)\n t = hash_klass(len(cats))\n t.map_locations(cats)\n return coerce_indexer_dtype(t.lookup(vals), cats)\n\n\ndef _recode_for_categories(codes, old_categories, new_categories):\n \"\"\"\n Convert a set of codes for to a new set of categories\n\n Parameters\n ----------\n codes : array\n old_categories, new_categories : Index\n\n Returns\n -------\n new_codes : array\n\n Examples\n --------\n >>> old_cat = pd.Index(['b', 'a', 'c'])\n >>> new_cat = pd.Index(['a', 'b'])\n >>> codes = np.array([0, 1, 1, 2])\n >>> _recode_for_categories(codes, old_cat, new_cat)\n array([ 1, 0, 0, -1])\n \"\"\"\n from pandas.core.algorithms import take_1d\n\n if len(old_categories) == 0:\n # All null anyway, so just retain the nulls\n return codes.copy()\n indexer = coerce_indexer_dtype(new_categories.get_indexer(old_categories),\n new_categories)\n new_codes = take_1d(indexer, codes.copy(), fill_value=-1)\n return new_codes\n\n\ndef _convert_to_list_like(list_like):\n if hasattr(list_like, \"dtype\"):\n return list_like\n if isinstance(list_like, list):\n return list_like\n if (is_sequence(list_like) or isinstance(list_like, tuple) or\n is_iterator(list_like)):\n return list(list_like)\n elif is_scalar(list_like):\n return [list_like]\n else:\n # is this reached?\n return [list_like]\n\n\ndef _factorize_from_iterable(values):\n \"\"\"\n Factorize an input `values` into `categories` and `codes`. Preserves\n categorical dtype in `categories`.\n\n *This is an internal function*\n\n Parameters\n ----------\n values : list-like\n\n Returns\n -------\n codes : ndarray\n categories : Index\n If `values` has a categorical dtype, then `categories` is\n a CategoricalIndex keeping the categories and order of `values`.\n \"\"\"\n from pandas.core.indexes.category import CategoricalIndex\n\n if not is_list_like(values):\n raise TypeError(\"Input must be list-like\")\n\n if is_categorical(values):\n if isinstance(values, (ABCCategoricalIndex, ABCSeries)):\n values = values._values\n categories = CategoricalIndex(values.categories,\n categories=values.categories,\n ordered=values.ordered)\n codes = values.codes\n else:\n # The value of ordered is irrelevant since we don't use cat as such,\n # but only the resulting categories, the order of which is independent\n # from ordered. Set ordered to False as default. See GH #15457\n cat = Categorical(values, ordered=False)\n categories = cat.categories\n codes = cat.codes\n return codes, categories\n\n\ndef _factorize_from_iterables(iterables):\n \"\"\"\n A higher-level wrapper over `_factorize_from_iterable`.\n\n *This is an internal function*\n\n Parameters\n ----------\n iterables : list-like of list-likes\n\n Returns\n -------\n codes_list : list of ndarrays\n categories_list : list of Indexes\n\n Notes\n -----\n See `_factorize_from_iterable` for more info.\n \"\"\"\n if len(iterables) == 0:\n # For consistency, it should return a list of 2 lists.\n return [[], []]\n return map(list, lzip(*[_factorize_from_iterable(it) for it in iterables]))\n"
] |
[
[
"pandas.to_datetime",
"pandas.util._validators.validate_bool_kwarg",
"pandas.util._decorators.deprecate_kwarg",
"pandas.Series",
"numpy.take",
"numpy.asarray",
"pandas.core.dtypes.common.is_extension_array_dtype",
"pandas.core.dtypes.common.is_dtype_equal",
"pandas.core.dtypes.common.is_datetimelike",
"pandas.core.dtypes.inference.is_hashable",
"pandas.core.accessor.delegate_names",
"pandas.core.dtypes.missing.notna",
"pandas.compat.iteritems",
"pandas.core.dtypes.common.is_datetime64_dtype",
"pandas.core.dtypes.common.ensure_object",
"numpy.where",
"pandas.core.algorithms._get_data_algo",
"pandas.util._decorators.Substitution",
"pandas.core.config.get_option",
"numpy.unique",
"pandas.core.dtypes.concat._concat_categorical",
"pandas.compat.text_type",
"numpy.arange",
"pandas.Index",
"pandas.core.algorithms.factorize",
"pandas.core.dtypes.dtypes.CategoricalDtype._from_fastpath",
"pandas.io.formats.format.format_array",
"pandas.core.dtypes.common.ensure_int64",
"pandas.core.dtypes.common.is_dict_like",
"pandas.core.dtypes.dtypes.CategoricalDtype.validate_categories",
"pandas.core.dtypes.common.is_iterator",
"pandas.core.dtypes.common.is_float_dtype",
"pandas.core.dtypes.cast.coerce_indexer_dtype",
"pandas.to_numeric",
"pandas.core.dtypes.common.is_categorical_dtype",
"pandas.compat.numpy.function.validate_repeat",
"pandas.io.formats.terminal.get_terminal_size",
"pandas.core.dtypes.common.is_list_like",
"pandas.util._decorators.Appender",
"pandas.core.dtypes.common.is_categorical",
"pandas.core.dtypes.common.is_integer_dtype",
"pandas.compat.u",
"pandas.core.dtypes.common.is_timedelta64_dtype",
"pandas.core.dtypes.common.is_sequence",
"numpy.append",
"pandas.core.dtypes.common.ensure_platform_int",
"pandas.core.reshape.concat.concat",
"pandas.core.dtypes.dtypes.CategoricalDtype",
"pandas.core.series._sanitize_array",
"pandas.core.dtypes.cast.maybe_infer_to_datetimelike",
"numpy.array",
"pandas.core.algorithms.take",
"pandas.CategoricalIndex",
"numpy.array_equal",
"pandas.io.formats.console.in_ipython_frontend",
"pandas.core.algorithms.isin",
"pandas.core.algorithms.take_1d",
"pandas.core.dtypes.common.is_scalar",
"pandas.core.common.is_null_slice",
"numpy.sort",
"pandas.util._validators.validate_fillna_kwargs",
"pandas.io.formats.format.CategoricalFormatter",
"pandas.core.algorithms.unique1d",
"numpy.ones",
"numpy.bincount",
"pandas.core.dtypes.missing.isna",
"numpy.prod",
"pandas.to_timedelta",
"pandas._libs.lib.item_from_zerodim",
"pandas.core.missing.interpolate_2d"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
suiyizhao/Pytorch-speedup
|
[
"a9d4b0accc703035559ac6f42daddf8b1f0eb40a"
] |
[
"src/train_amp.py"
] |
[
"import sys\nimport time\nimport torch\nimport random\nimport argparse\n\nimport numpy as np\nimport torch.nn as nn\nimport torchvision.transforms as transforms\n\nfrom torchvision import datasets\nfrom torch.utils.data import DataLoader\n\n# new #\nimport torch.cuda.amp as amp\n\ndef printParaNum(model):\n \n '''\n function: print the number of total parameters and trainable parameters\n '''\n \n total_params = sum(p.numel() for p in model.parameters())\n total_trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n print('Total parameters: %d' % total_params)\n print('Trainable parameters: %d' % total_trainable_params)\n \ndef set_random_seed(seed, deterministic=False):\n '''\n function: Set random seed.\n\n Args:\n seed (int): Seed to be used.\n deterministic (bool): Whether to set the deterministic option for\n CUDNN backend, i.e., set `torch.backends.cudnn.deterministic`\n to True and `torch.backends.cudnn.benchmark` to False.\n Default: False.\n '''\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n if torch.cuda.is_available():\n torch.cuda.manual_seed_all(seed)\n if deterministic:\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n\nclass Model(nn.Module):\n def __init__(self):\n super(Model, self).__init__()\n \n self.model = nn.Sequential(\n nn.ReflectionPad2d(1), nn.Conv2d(1, 3, 3, 2), nn.BatchNorm2d(3), nn.LeakyReLU(0.2, inplace=True),\n nn.ReflectionPad2d(1), nn.Conv2d(3, 3, 3, 1), nn.BatchNorm2d(3), nn.LeakyReLU(0.2, inplace=True),\n nn.ReflectionPad2d(1), nn.Conv2d(3, 8, 3, 2), nn.BatchNorm2d(8), nn.LeakyReLU(0.2, inplace=True),\n nn.ReflectionPad2d(1), nn.Conv2d(8, 8, 3, 1), nn.BatchNorm2d(8), nn.LeakyReLU(0.2, inplace=True),\n nn.ReflectionPad2d(1), nn.Conv2d(8, 16, 3, 2), nn.BatchNorm2d(16), nn.LeakyReLU(0.2, inplace=True),\n nn.ReflectionPad2d(1), nn.Conv2d(16, 16, 3, 1), nn.BatchNorm2d(16), nn.LeakyReLU(0.2, inplace=True),\n nn.ReflectionPad2d(1), nn.Conv2d(16, 32, 3, 2), nn.BatchNorm2d(32), nn.LeakyReLU(0.2, inplace=True),\n nn.ReflectionPad2d(1), nn.Conv2d(32, 32, 3, 1), nn.BatchNorm2d(32), nn.LeakyReLU(0.2, inplace=True),\n nn.Flatten(), nn.Linear(128, 10)\n )\n \n self.initialize_weights()\n \n def forward(self, img):\n out = self.model(img)\n\n return out\n \n def initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.xavier_normal_(m.weight.data)\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 nn.init.normal_(m.weight.data, 0, 0.01)\n m.bias.data.zero_()\n\ntime_begin = time.time()\n\nprint('---------------------------------------- step 1/5 : parameters preparing... ----------------------------------------')\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--epochs\", type=int, default=5, help=\"number of epochs of training\")\nparser.add_argument(\"--lr\", type=float, default=0.0002, help=\"learning rate\")\nparser.add_argument(\"--batch_size\", type=int, default=2048, help=\"size of the batches\")\nparser.add_argument(\"--workers\", type=int, default=4, help=\"number of cpu threads to use during batch generation\")\nparser.add_argument(\"--dataset\", type=str, default='../dataset/mnist', help=\"dataset root\")\nparser.add_argument(\"--result_dir\", type=str, default='../result', help=\"dir for saving the results\")\nopt = parser.parse_args()\nprint(opt)\n\nset_random_seed(1234, deterministic=True)\n\ntime_1 = time.time()\n\nprint('---------------------------------------- step 2/5 : data loading... ------------------------------------------------')\ndataset = datasets.MNIST(opt.dataset, train=True, download=True,\n transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize([0.5], [0.5])]))\ndataloader = DataLoader(dataset=dataset, batch_size=opt.batch_size, shuffle=True, num_workers=opt.workers)\ntime_2 = time.time()\n\nprint('---------------------------------------- step 3/5 : model defining... ----------------------------------------------')\nmodel = Model().cuda()\nprintParaNum(model)\ntime_3 = time.time()\n\nprint('---------------------------------------- step 4/5 : requisites defining... -----------------------------------------')\n# Loss function\nloss_func = nn.CrossEntropyLoss()\n# Optimizers\noptimizer = torch.optim.Adam(model.parameters(), lr=opt.lr, betas=(0.5, 0.999))\n\n# NEW #\nscaler = amp.GradScaler()\n\ntime_4 = time.time()\n\nprint('---------------------------------------- step 5/5 : training... ----------------------------------------------------')\nf = open(opt.result_dir + '/log_' + sys.argv[0][0:-3] + '.txt', 'w')\nf.write('Type: single machine, single card, mixing precision' + '\\n')\nf.write('Parallel manner: none' + '\\n')\nf.write('Mixing manner: amp' + '\\n')\nf.write('Setting: epochs: {}, lr: {}, batch_size: {}, workers: {}'.format(opt.epochs, opt.lr, opt.batch_size, opt.workers) + '\\n')\nf.write('----------------------------' + '\\n')\nf.write('Training: ' + '\\n')\nf.write('----------------------------' + '\\n')\ntime_4_dataloading = 0\ntime_4_computing = 0\nfor epoch in range(opt.epochs):\n time_4_begin = time.time()\n for i, (imgs, labels) in enumerate(dataloader):\n imgs = imgs.cuda()\n labels = labels.cuda()\n time_temp = time.time()\n time_4_dataloading += time_temp - time_4_begin\n \n optimizer.zero_grad()\n \n # new #\n with amp.autocast():\n pred = model(imgs)\n loss = loss_func(pred, labels)\n scaler.scale(loss).backward()\n scaler.step(optimizer)\n scaler.update()\n \n _, pred = torch.max(pred, 1)\n acc = (pred == labels).sum().item() / len(labels)\n \n print('Training: Epoch[{:0>3}/{:0>3}] Iteration[{:0>4}/{:0>4}] Loss: {:.4f} Acc: {:.4f}'.format(\n epoch + 1, opt.epochs, i + 1, len(dataloader), loss, acc))\n f.write('Training: Epoch[{:0>3}/{:0>3}] Iteration[{:0>4}/{:0>4}] Loss: {:.4f} Acc: {:.4f}'.format(\n epoch + 1, opt.epochs, i + 1, len(dataloader), loss, acc) + '\\n')\n time_4_computing += time.time() - time_temp\n time_4_begin = time.time()\n \ntime_5 = time.time()\n\nf.write('\\n')\nf.write('TIME COST' + '\\n')\nf.write('Parameters preparing: {:.6f}(s)'.format(time_1 - time_begin) + '\\n')\nf.write('Data loading: {:.6f}(s)'.format(time_2 - time_1) + '\\n')\nf.write('Model defining: {:.6f}(s)'.format(time_3 - time_2) + '\\n')\nf.write('Requisites defining: {:.6f}(s)'.format(time_4 - time_3) + '\\n')\nf.write('Training: {:.6f}(s)'.format(time_5 - time_4) + '\\n')\nf.write(' Training (dataloading): {:.6f}(s)'.format(time_4_dataloading) + '\\n')\nf.write(' Training (computing): {:.6f}(s)'.format(time_4_computing) + '\\n')\nf.close()\n\ntorch.save(model.state_dict(), opt.result_dir + '/model_' + sys.argv[0][0:-3] + '.pkl')"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.nn.ReflectionPad2d",
"torch.max",
"numpy.random.seed",
"torch.manual_seed",
"torch.nn.Conv2d",
"torch.utils.data.DataLoader",
"torch.nn.Flatten",
"torch.nn.init.xavier_normal_",
"torch.cuda.amp.autocast",
"torch.nn.Linear",
"torch.cuda.amp.GradScaler",
"torch.nn.init.normal_",
"torch.nn.LeakyReLU",
"torch.cuda.is_available",
"torch.cuda.manual_seed_all",
"torch.nn.BatchNorm2d"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
michalkouril/PYNQ
|
[
"c72febc2decc83816f40b91a7f60e11fe707c248",
"c72febc2decc83816f40b91a7f60e11fe707c248"
] |
[
"pynq/lib/logictools/tests/test_fsm_generator.py",
"tests/test_registers.py"
] |
[
"# Copyright (c) 2016, Xilinx, Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder no r the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n# OR BUSINESS INTERRUPTION). HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\nfrom random import randint\nfrom math import ceil\nimport numpy as np\nimport pytest\nfrom pynq import Overlay\nfrom pynq.tests.util import user_answer_yes\nfrom pynq.lib.logictools.waveform import bitstring_to_int\nfrom pynq.lib.logictools.waveform import wave_to_bitstring\nfrom pynq.lib.logictools import FSMGenerator\nfrom pynq.lib.logictools import ARDUINO\nfrom pynq.lib.logictools import PYNQZ1_LOGICTOOLS_SPECIFICATION\nfrom pynq.lib.logictools import MAX_NUM_TRACE_SAMPLES\nfrom pynq.lib.logictools import FSM_MIN_NUM_STATES\nfrom pynq.lib.logictools import FSM_MAX_NUM_STATES\nfrom pynq.lib.logictools import FSM_MAX_INPUT_BITS\nfrom pynq.lib.logictools import FSM_MAX_STATE_INPUT_BITS\n\n\n__author__ = \"Yun Rock Qu\"\n__copyright__ = \"Copyright 2016, Xilinx\"\n__email__ = \"[email protected]\"\n\n\ntry:\n ol = Overlay('logictools.bit', download=False)\n flag0 = True\nexcept IOError:\n flag0 = False\nflag1 = user_answer_yes(\"\\nTest Finite State Machine (FSM) generator?\")\nif flag1:\n mb_info = ARDUINO\nflag = flag0 and flag1\n\n\npin_dict = PYNQZ1_LOGICTOOLS_SPECIFICATION['traceable_outputs']\ninterface_width = PYNQZ1_LOGICTOOLS_SPECIFICATION['interface_width']\n\n\ndef build_fsm_spec_4_state(direction_logic_value):\n \"\"\"Build an FSM spec with 4 states.\n\n The FSM built has 2 inputs, 1 output, and 4 states. It acts like a \n 2-bit counter, where the output goes to high only if the FSM is in the \n final state.\n\n When the direction pin is low, the counter counts up; if it is high, the\n counter counts down.\n\n Parameters\n ----------\n direction_logic_value : int\n The logic value of the direction pin.\n Returns\n -------\n dict\n The FSM spec that can be consumed by the FSM generator.\n list\n The output pattern corresponding to the direction value.\n list\n The state bit0 pattern corresponding to the direction value.\n list\n The state bit1 pattern corresponding to the direction value.\n\n \"\"\"\n out, rst, direction = list(pin_dict.keys())[0:3]\n fsm_spec_4_state = {'inputs': [('rst', rst), ('direction', direction)],\n 'outputs': [('test', out)],\n 'states': ['S0', 'S1', 'S2', 'S3'],\n 'transitions': [['00', 'S0', 'S1', '0'],\n ['01', 'S0', 'S3', '0'],\n ['00', 'S1', 'S2', '0'],\n ['01', 'S1', 'S0', '0'],\n ['00', 'S2', 'S3', '0'],\n ['01', 'S2', 'S1', '0'],\n ['00', 'S3', 'S0', '1'],\n ['01', 'S3', 'S2', '1'],\n ['1-', '*', 'S0', '']]}\n if not direction_logic_value:\n output_pattern = [0, 0, 0, 1]\n state_bit0_pattern = [0, 1, 0, 1]\n state_bit1_pattern = [0, 0, 1, 1]\n else:\n output_pattern = [0, 1, 0, 0]\n state_bit0_pattern = [0, 1, 0, 1]\n state_bit1_pattern = [0, 1, 1, 0]\n return fsm_spec_4_state, \\\n output_pattern, state_bit0_pattern, state_bit1_pattern\n\n\ndef build_fsm_spec_random(num_states):\n \"\"\"Build an FSM spec with the specified number of states.\n\n The FSM spec exploits only single input and single output. As a side \n product, a list of output patterns are also returned.\n\n Parameters\n ----------\n num_states : int\n The number of states of the FSM.\n\n Returns\n -------\n dict\n The FSM spec that can be consumed by the FSM generator.\n list\n The output patterns associated with this FSM spec.\n\n \"\"\"\n input_pin, output_pin = list(pin_dict.keys())[0:2]\n if num_states == 1:\n return {'inputs': [('rst', input_pin)],\n 'outputs': [('test', output_pin)],\n 'states': ['S0'],\n 'transitions': [['1', '*', 'S0', '']]}, None\n else:\n fsm_spec_state = {'inputs': [('rst', input_pin)],\n 'outputs': [('test', output_pin)],\n 'states': [],\n 'transitions': [['1', '*', 'S0', '']]}\n output_pattern_list = list()\n for i in range(num_states):\n current_state = 'S{}'.format(i)\n next_state = 'S{}'.format((i+1) % num_states)\n fsm_spec_state['states'] += [current_state]\n output_pattern = '{}'.format(randint(0, 1))\n transition = ['0', current_state, next_state, output_pattern]\n fsm_spec_state['transitions'] += [transition]\n output_pattern_list.append(int(output_pattern))\n return fsm_spec_state, output_pattern_list\n\n\ndef build_fsm_spec_max_in_out():\n \"\"\"Build an FSM spec using a maximum number of inputs and outputs.\n\n The returned FSM spec has a maximum number of inputs and \n outputs. At the same time, the largest available number of \n states will be implemented. For example, on PYNQ-Z1, if \n FSM_MAX_INPUT_BITS = 8, and FSM_MAX_STATE_INPUT_BITS = 13, we will \n implement 2**(13-8)-1 = 31 states. This is the largest number of states \n available for this setup, since there is always 1 dummy state that has\n to be reserved.\n\n Returns\n -------\n dict\n The FSM spec that can be consumed by the FSM generator.\n list\n The output patterns associated with this FSM spec.\n\n \"\"\"\n input_pins = list(pin_dict.keys())[:FSM_MAX_INPUT_BITS]\n output_pins = list(pin_dict.keys())[FSM_MAX_INPUT_BITS:interface_width]\n fsm_spec_inout = {'inputs': [],\n 'outputs': [],\n 'states': [],\n 'transitions': [['1' * len(input_pins), '*', 'S0', '']]}\n test_lanes = [[] for _ in range(len(output_pins))]\n num_states = 2 ** (FSM_MAX_STATE_INPUT_BITS - FSM_MAX_INPUT_BITS) - 1\n for i in range(len(input_pins)):\n fsm_spec_inout['inputs'].append(('input{}'.format(i),\n input_pins[i]))\n for i in range(len(output_pins)):\n fsm_spec_inout['outputs'].append(('output{}'.format(i),\n output_pins[i]))\n for i in range(num_states):\n current_state = 'S{}'.format(i)\n next_state = 'S{}'.format((i + 1) % num_states)\n fsm_spec_inout['states'].append(current_state)\n output_pattern = ''\n for test_lane in test_lanes:\n random_1bit = '{}'.format(randint(0, 1))\n output_pattern += random_1bit\n test_lane += random_1bit\n transition = ['0' * len(input_pins), current_state, next_state,\n output_pattern]\n fsm_spec_inout['transitions'].append(transition)\n\n test_patterns = []\n for i in range(len(output_pins)):\n temp_string = ''.join(test_lanes[i])\n test_patterns.append(np.array(bitstring_to_int(\n wave_to_bitstring(temp_string))))\n return fsm_spec_inout, test_patterns\n\n\ndef build_fsm_spec_free_run():\n \"\"\"Build a spec that results in a free-running FSM.\n\n This will return an FSM spec with no given inputs.\n In this case, the FSM is a free running state machine. \n A maximum number of states are deployed.\n\n Returns\n -------\n dict\n The FSM spec that can be consumed by the FSM generator.\n list\n The output patterns associated with this FSM spec.\n\n \"\"\"\n input_pin = list(pin_dict.keys())[0]\n output_pins = list(pin_dict.keys())[1:interface_width]\n\n fsm_spec_inout = {'inputs': [],\n 'outputs': [],\n 'states': [],\n 'transitions': []}\n test_lanes = [[] for _ in range(len(output_pins))]\n num_states = FSM_MAX_NUM_STATES\n fsm_spec_inout['inputs'].append(('input0', input_pin))\n for i in range(len(output_pins)):\n fsm_spec_inout['outputs'].append(('output{}'.format(i),\n output_pins[i]))\n for i in range(num_states):\n current_state = 'S{}'.format(i)\n next_state = 'S{}'.format((i + 1) % num_states)\n fsm_spec_inout['states'].append(current_state)\n output_pattern = ''\n for test_lane in test_lanes:\n random_1bit = '{}'.format(randint(0, 1))\n output_pattern += random_1bit\n test_lane += random_1bit\n transition = ['-', current_state, next_state, output_pattern]\n fsm_spec_inout['transitions'].append(transition)\n\n test_patterns = []\n for i in range(len(output_pins)):\n temp_string = ''.join(test_lanes[i])\n test_patterns.append(np.array(bitstring_to_int(\n wave_to_bitstring(temp_string))))\n return fsm_spec_inout, test_patterns\n\n\[email protected](not flag, reason=\"need correct overlay to run\")\ndef test_fsm_num_samples():\n \"\"\"Test for the Finite State Machine Generator class.\n\n In this test, the pattern generated by the FSM will be compared with the \n one specified. We will test a minimum number of (FSM period + 1) samples,\n and a maximum number of samples. 10MHz and 100MHz clocks are tested\n for each case.\n\n \"\"\"\n ol.download()\n\n rst, direction = list(pin_dict.keys())[1:3]\n print(\"\\nConnect {} to GND, and {} to VCC.\".format(rst, direction))\n input(\"Hit enter after done ...\")\n\n fsm_spec_4_state, output_pattern, _, _ = build_fsm_spec_4_state(1)\n fsm_period = len(fsm_spec_4_state['states'])\n for num_samples in [fsm_period, MAX_NUM_TRACE_SAMPLES]:\n test_tile = np.array(output_pattern)\n golden_test_array = np.tile(test_tile, ceil(num_samples / 4))\n\n for fsm_frequency_mhz in [10, 100]:\n fsm_generator = FSMGenerator(mb_info)\n assert fsm_generator.status == 'RESET'\n\n fsm_generator.trace(use_analyzer=True,\n num_analyzer_samples=num_samples)\n fsm_generator.setup(fsm_spec_4_state,\n frequency_mhz=fsm_frequency_mhz)\n assert fsm_generator.status == 'READY'\n assert 'bram_data_buf' not in \\\n fsm_generator.logictools_controller.buffers, \\\n 'bram_data_buf is not freed after use.'\n\n fsm_generator.run()\n assert fsm_generator.status == 'RUNNING'\n\n test_string = ''\n for wavegroup in fsm_generator.waveform.waveform_dict['signal']:\n if wavegroup and wavegroup[0] == 'analysis':\n for wavelane in wavegroup[1:]:\n if wavelane['name'] == 'test':\n test_string = wavelane['wave']\n test_array = np.array(bitstring_to_int(\n wave_to_bitstring(test_string)))\n\n assert np.array_equal(test_array,\n golden_test_array[:num_samples]), \\\n 'Data pattern not correct when running at {}MHz.'.format(\n fsm_frequency_mhz)\n\n fsm_generator.stop()\n assert fsm_generator.status == 'READY'\n\n fsm_generator.reset()\n assert fsm_generator.status == 'RESET'\n\n del fsm_generator\n\n\[email protected](not flag, reason=\"need correct overlay to run\")\ndef test_fsm_state_bits():\n \"\"\"Test for the Finite State Machine Generator class.\n\n This test is similar to the first test, but in this test,\n we will test the case when the state bits are also used as outputs.\n\n \"\"\"\n ol.download()\n\n rst, direction = list(pin_dict.keys())[1:3]\n print(\"\\nConnect both {} and {} to GND.\".format(rst, direction))\n input(\"Hit enter after done ...\")\n\n fsm_spec_4_state, output_pattern, \\\n state_bit0_pattern, state_bit1_pattern = build_fsm_spec_4_state(0)\n fsm_period = len(fsm_spec_4_state['states'])\n golden_test_array = np.array(output_pattern)\n golden_state_bit0_array = np.array(state_bit0_pattern)\n golden_state_bit1_array = np.array(state_bit1_pattern)\n\n for fsm_frequency_mhz in [10, 100]:\n fsm_generator = FSMGenerator(mb_info)\n fsm_generator.trace(use_analyzer=True,\n num_analyzer_samples=fsm_period)\n fsm_generator.setup(fsm_spec_4_state,\n use_state_bits=True,\n frequency_mhz=fsm_frequency_mhz)\n fsm_generator.run()\n\n test_string = state_bit0_string = state_bit1_string = ''\n for wavegroup in fsm_generator.waveform.waveform_dict['signal']:\n if wavegroup and wavegroup[0] == 'analysis':\n for wavelane in wavegroup[1:]:\n if wavelane['name'] == 'test':\n test_string = wavelane['wave']\n if wavelane['name'] == 'state_bit0':\n state_bit0_string = wavelane['wave']\n if wavelane['name'] == 'state_bit1':\n state_bit1_string = wavelane['wave']\n test_array = np.array(bitstring_to_int(\n wave_to_bitstring(test_string)))\n state_bit0_array = np.array(bitstring_to_int(\n wave_to_bitstring(state_bit0_string)))\n state_bit1_array = np.array(bitstring_to_int(\n wave_to_bitstring(state_bit1_string)))\n\n assert np.array_equal(golden_test_array, test_array), \\\n 'Data pattern not correct when running at {}MHz.'.format(\n fsm_frequency_mhz)\n assert np.array_equal(golden_state_bit0_array, state_bit0_array), \\\n 'State bit0 not correct when running at {}MHz.'.format(\n fsm_frequency_mhz)\n assert np.array_equal(golden_state_bit1_array, state_bit1_array), \\\n 'State bit1 not correct when running at {}MHz.'.format(\n fsm_frequency_mhz)\n\n fsm_generator.stop()\n fsm_generator.reset()\n del fsm_generator\n\n\[email protected](not flag, reason=\"need correct overlay to run\")\ndef test_fsm_step():\n \"\"\"Test for the Finite State Machine Generator class.\n\n This test is similar to the above test, but in this test,\n we will test the `step()` method, and ask users to change the input\n logic values in the middle of the test.\n\n \"\"\"\n ol.download()\n\n rst, direction = list(pin_dict.keys())[1:3]\n print(\"\")\n\n fsm_spec_4_state, output_pattern_up, \\\n state_bit0_pattern_up, \\\n state_bit1_pattern_up = build_fsm_spec_4_state(0)\n _, output_pattern_down, \\\n state_bit0_pattern_down, \\\n state_bit1_pattern_down = build_fsm_spec_4_state(1)\n output_pattern_down.append(output_pattern_down.pop(0))\n state_bit0_pattern_down.append(state_bit0_pattern_down.pop(0))\n state_bit1_pattern_down.append(state_bit1_pattern_down.pop(0))\n fsm_period = len(fsm_spec_4_state['states'])\n golden_test_array = np.array(output_pattern_up +\n output_pattern_down[1:])\n golden_state_bit0_array = np.array(state_bit0_pattern_up +\n state_bit0_pattern_down[1:])\n golden_state_bit1_array = np.array(state_bit1_pattern_up +\n state_bit1_pattern_down[1:])\n\n for fsm_frequency_mhz in [10, 100]:\n fsm_generator = FSMGenerator(mb_info)\n fsm_generator.trace(use_analyzer=True,\n num_analyzer_samples=fsm_period)\n fsm_generator.setup(fsm_spec_4_state,\n use_state_bits=True,\n frequency_mhz=fsm_frequency_mhz)\n print(\"Connect both {} and {} to GND.\".format(rst, direction))\n input(\"Hit enter after done ...\")\n for _ in range(len(output_pattern_up)-1):\n fsm_generator.step()\n print(\"Connect {} to GND, and {} to VCC.\".format(rst, direction))\n input(\"Hit enter after done ...\")\n for _ in range(len(output_pattern_down)):\n fsm_generator.step()\n\n test_string = state_bit0_string = state_bit1_string = ''\n for wavegroup in fsm_generator.waveform.waveform_dict['signal']:\n if wavegroup and wavegroup[0] == 'analysis':\n for wavelane in wavegroup[1:]:\n if wavelane['name'] == 'test':\n test_string = wavelane['wave']\n if wavelane['name'] == 'state_bit0':\n state_bit0_string = wavelane['wave']\n if wavelane['name'] == 'state_bit1':\n state_bit1_string = wavelane['wave']\n test_array = np.array(bitstring_to_int(\n wave_to_bitstring(test_string)))\n state_bit0_array = np.array(bitstring_to_int(\n wave_to_bitstring(state_bit0_string)))\n state_bit1_array = np.array(bitstring_to_int(\n wave_to_bitstring(state_bit1_string)))\n\n assert np.array_equal(golden_test_array, test_array), \\\n 'Data pattern not correct when stepping at {}MHz.'.format(\n fsm_frequency_mhz)\n assert np.array_equal(golden_state_bit0_array, state_bit0_array), \\\n 'State bit0 not correct when stepping at {}MHz.'.format(\n fsm_frequency_mhz)\n assert np.array_equal(golden_state_bit1_array, state_bit1_array), \\\n 'State bit1 not correct when stepping at {}MHz.'.format(\n fsm_frequency_mhz)\n\n fsm_generator.stop()\n fsm_generator.reset()\n del fsm_generator\n\n\[email protected](not flag, reason=\"need correct overlay to run\")\ndef test_fsm_no_trace():\n \"\"\"Test for the Finite State Machine Generator class.\n\n This is similar to the first test, but in this test,\n we will test the case when no analyzer is specified.\n\n \"\"\"\n ol.download()\n\n fsm_spec_4_state, _, _, _ = build_fsm_spec_4_state(0)\n fsm_generator = FSMGenerator(mb_info)\n fsm_generator.trace(use_analyzer=False)\n fsm_generator.setup(fsm_spec_4_state)\n fsm_generator.run()\n\n exception_raised = False\n try:\n fsm_generator.show_waveform()\n except ValueError:\n exception_raised = True\n assert exception_raised, 'Should raise exception for show_waveform().'\n\n fsm_generator.reset()\n del fsm_generator\n\n\[email protected](not flag, reason=\"need correct overlay to run\")\ndef test_fsm_num_states1():\n \"\"\"Test for the Finite State Machine Generator class.\n\n The 4th test will check 1 and (MAX_NUM_STATES + 1) states. \n These cases should raise exceptions. For these tests, we use the minimum \n number of input and output pins.\n\n \"\"\"\n ol.download()\n fsm_generator = None\n exception_raised = False\n fsm_spec_less_than_min_state, _ = build_fsm_spec_random(\n FSM_MIN_NUM_STATES - 1)\n fsm_spec_more_than_max_state, _ = build_fsm_spec_random(\n FSM_MAX_NUM_STATES + 1)\n for fsm_spec in [fsm_spec_less_than_min_state,\n fsm_spec_more_than_max_state]:\n num_states = len(fsm_spec['states'])\n try:\n fsm_generator = FSMGenerator(mb_info)\n fsm_generator.trace(use_analyzer=True,\n num_analyzer_samples=MAX_NUM_TRACE_SAMPLES)\n fsm_generator.setup(fsm_spec)\n except ValueError:\n exception_raised = True\n\n assert exception_raised, \\\n 'Should raise exception when ' \\\n 'there are {} states in the FSM.'.format(num_states)\n\n fsm_generator.reset()\n del fsm_generator\n\n\[email protected](not flag, reason=\"need correct overlay to run\")\ndef test_fsm_num_states2():\n \"\"\"Test for the Finite State Machine Generator class.\n\n This test will check 2 and MAX_NUM_STATES states. \n These cases should be able to pass random tests. \n For these tests, we use the minimum number of input and output pins.\n\n \"\"\"\n ol.download()\n\n input_pin = list(pin_dict.keys())[0]\n print(\"\\nConnect {} to GND, and disconnect other pins.\".format(input_pin))\n input(\"Hit enter after done ...\")\n\n for num_states in [2, FSM_MAX_NUM_STATES]:\n fsm_spec, test_pattern = build_fsm_spec_random(num_states)\n\n fsm_generator = FSMGenerator(mb_info)\n fsm_generator.trace(use_analyzer=True,\n num_analyzer_samples=MAX_NUM_TRACE_SAMPLES)\n fsm_generator.setup(fsm_spec, frequency_mhz=100)\n fsm_generator.run()\n\n test_string = ''\n for wavegroup in fsm_generator.waveform.waveform_dict['signal']:\n if wavegroup and wavegroup[0] == 'analysis':\n for wavelane in wavegroup[1:]:\n if wavelane['name'] == 'test':\n test_string = wavelane['wave']\n test_array = np.array(bitstring_to_int(\n wave_to_bitstring(test_string)))\n\n period = num_states\n test_tile = np.array(test_pattern)\n\n golden_test_array = np.tile(test_tile,\n ceil(MAX_NUM_TRACE_SAMPLES / period))\n assert np.array_equal(test_array,\n golden_test_array[:MAX_NUM_TRACE_SAMPLES]), \\\n 'Analysis not matching the generated pattern.'\n\n fsm_generator.stop()\n fsm_generator.reset()\n del fsm_generator\n\n\[email protected](not flag, reason=\"need correct overlay to run\")\ndef test_fsm_max_in_out():\n \"\"\"Test for the Finite State Machine Generator class.\n\n This test will test when maximum number of inputs and \n outputs are used. At the same time, the largest available number of \n states will be implemented.\n\n \"\"\"\n ol.download()\n\n input_pins = list(pin_dict.keys())[:FSM_MAX_INPUT_BITS]\n print(\"\\nConnect {} to GND.\".format(input_pins))\n print(\"Disconnect all other pins.\")\n input(\"Hit enter after done ...\")\n\n fsm_spec_inout, test_patterns = build_fsm_spec_max_in_out()\n period = 2 ** (FSM_MAX_STATE_INPUT_BITS - FSM_MAX_INPUT_BITS) - 1\n num_output_pins = interface_width - FSM_MAX_INPUT_BITS\n\n fsm_generator = FSMGenerator(mb_info)\n fsm_generator.trace(use_analyzer=True,\n num_analyzer_samples=MAX_NUM_TRACE_SAMPLES)\n fsm_generator.setup(fsm_spec_inout, frequency_mhz=100)\n fsm_generator.run()\n\n test_strings = ['' for _ in range(num_output_pins)]\n test_arrays = [[] for _ in range(num_output_pins)]\n for wavegroup in fsm_generator.waveform.waveform_dict['signal']:\n if wavegroup and wavegroup[0] == 'analysis':\n for wavelane in wavegroup[1:]:\n for j in range(num_output_pins):\n if wavelane['name'] == 'output{}'.format(j):\n test_strings[j] = wavelane['wave']\n test_arrays[j] = np.array(bitstring_to_int(\n wave_to_bitstring(test_strings[j])))\n break\n\n golden_arrays = [[] for _ in range(num_output_pins)]\n for i in range(num_output_pins):\n golden_arrays[i] = np.tile(test_patterns[i],\n ceil(MAX_NUM_TRACE_SAMPLES / period))\n assert np.array_equal(test_arrays[i],\n golden_arrays[i][:MAX_NUM_TRACE_SAMPLES]), \\\n 'Output{} not matching the generated pattern.'.format(i)\n\n fsm_generator.stop()\n fsm_generator.reset()\n del fsm_generator\n\n\[email protected](not flag, reason=\"need correct overlay to run\")\ndef test_fsm_free_run():\n \"\"\"Test for the Finite State Machine Generator class.\n\n This will examine a special scenario where no inputs are given.\n In this case, the FSM is a free running state machine. Since the FSM \n specification requires at least 1 input pin to be specified, 1 pin can \n be used as `don't care` input, while all the other pins are used as \n outputs. A maximum number of states are deployed.\n\n \"\"\"\n ol.download()\n\n print(\"\\nDisconnect all the pins.\")\n input(\"Hit enter after done ...\")\n\n fsm_spec_inout, test_patterns = build_fsm_spec_free_run()\n period = FSM_MAX_NUM_STATES\n num_output_pins = interface_width - 1\n fsm_generator = FSMGenerator(mb_info)\n fsm_generator.trace(use_analyzer=True,\n num_analyzer_samples=period)\n fsm_generator.setup(fsm_spec_inout, frequency_mhz=100)\n fsm_generator.run()\n\n test_strings = ['' for _ in range(num_output_pins)]\n test_arrays = [[] for _ in range(num_output_pins)]\n for wavegroup in fsm_generator.waveform.waveform_dict['signal']:\n if wavegroup and wavegroup[0] == 'analysis':\n for wavelane in wavegroup[1:]:\n for j in range(num_output_pins):\n if wavelane['name'] == 'output{}'.format(j):\n test_strings[j] = wavelane['wave']\n test_arrays[j] = np.array(bitstring_to_int(\n wave_to_bitstring(test_strings[j])))\n break\n\n golden_arrays = test_patterns\n for i in range(num_output_pins):\n assert np.array_equal(test_arrays[i], golden_arrays[i]), \\\n 'Output{} not matching the generated pattern.'.format(i)\n\n fsm_generator.stop()\n fsm_generator.reset()\n del fsm_generator\n",
"import pytest\nimport pynq\nimport operator\nimport struct\n\nimport numpy as np\n\n# Each vector is a tuple of\n# 1. Register length\n# 2. Starting value\n# 3. Slice\n# 4. Update Value\n# 5. Expected get_item pre-update\n# 6. Expected register value post-update\nTEST_VECTORS = {\n \"single-bit-set-32\":\n (32, 0x0000_0000, 4, 1, 0, 0x0000_0010, 1),\n \"single-bit-clear-32\":\n (32, 0x0000_0010, 4, 0, 1, 0x0000_0000, 1),\n \"single-bit-range-set-32\":\n (32, 0x0000_0000, slice(4, 4), 1, 0, 0x0000_0010, 1),\n \"single-bit-range-clear-32\":\n (32, 0x0000_0010, slice(4, 4), 0, 1, 0x0000_0000, 1),\n \"multi-bit-set-32\":\n (32, 0x0000_0000, slice(7, 4), 0xF, 0, 0x0000_00F0, 4),\n \"multi-bit-clear-32\":\n (32, 0x0000_00F0, slice(7, 4), 0x0, 0xF, 0x0000_0000, 4),\n \"multi-bit-normal-32\":\n (32, 0x0000_0010, slice(7, 4), 0x1, 0x1, 0x0000_0010, 4),\n \"multi-bit-reverse-32\":\n (32, 0x0000_0010, slice(4, 7), 0x1, 0x8, 0x0000_0080, 4),\n \"whole-reg-32\":\n (32, 0x1234_5678, slice(None, None, None),\n 0x8765_4321, 0x1234_5678, 0x8765_4321, 32),\n \"whole-reg-forward-32\":\n (32, 0x1234_5678, slice(None, None, -1),\n 0x8765_4321, 0x1234_5678, 0x8765_4321, 32),\n \"whole-reg-reverse-32\":\n (32, 0x1234_5678, slice(None, None, 1),\n 0x1234_5678, 0x1E6A_2C48, 0x1E6A_2C48, 32),\n \"lower-reg-32\":\n (32, 0x1234_5678, slice(15, None, None),\n 0x1234, 0x5678, 0x1234_1234, 16),\n \"lower-reg-forward-32\":\n (32, 0x1234_5678, slice(15, None, -1),\n 0x1234, 0x5678, 0x1234_1234, 16),\n \"lower-reg-reverse-32\":\n (32, 0x1234_5678, slice(None, 15, 1),\n 0x1234, 0x1E6A, 0x1234_2C48, 16),\n \"upper-reg-32\":\n (32, 0x1234_5678, slice(None, 16, None),\n 0x5678, 0x1234, 0x56785678, 16),\n \"upper-reg-forward-32\":\n (32, 0x1234_5678, slice(None, 16, -1),\n 0x5678, 0x1234, 0x5678_5678, 16),\n \"upper-reg-reverse-32\":\n (32, 0x1234_5678, slice(16, None, 1),\n 0x5678, 0x2C48, 0x1E6A_5678, 16),\n \"single-bit-set-64\":\n (64, 0x0000_0000, 4, 1, 0, 0x0000_0010, 1),\n \"single-bit-clear-64\":\n (64, 0x0000_0010, 4, 0, 1, 0x0000_0000, 1),\n \"single-bit-range-set-64\":\n (64, 0x0000_0000, slice(4, 4), 1, 0, 0x0000_0010, 1),\n \"single-bit-range-clear-64\":\n (64, 0x0000_0010, slice(4, 4), 0, 1, 0x0000_0000, 1),\n \"multi-bit-set-64\":\n (64, 0x0000_0000, slice(7, 4), 0xF, 0, 0x0000_00F0, 4),\n \"multi-bit-clear-64\":\n (64, 0x0000_00F0, slice(7, 4), 0x0, 0xF, 0x0000_0000, 4),\n \"multi-bit-normal-64\":\n (64, 0x0000_0010, slice(7, 4), 0x1, 0x1, 0x0000_0010, 4),\n \"multi-bit-reverse-64\":\n (64, 0x0000_0010, slice(4, 7), 0x1, 0x8, 0x0000_0080, 4),\n \"whole-reg-64\":\n (64, 0x1234_5678_9ABC_DEF0, slice(None, None, None),\n 0x0FED_CBA9_8765_4321, 0x1234_5678_9ABC_DEF0,\n 0x0FED_CBA9_8765_4321, 64),\n \"whole-reg-forward-64\":\n (64, 0x1234_5678_9ABC_DEF0, slice(None, None, -1),\n 0x0FED_CBA9_8765_4321, 0x1234_5678_9ABC_DEF0,\n 0x0FED_CBA9_8765_4321, 64),\n \"whole-reg-reverse-64\":\n (64, 0x1234_5678_9ABC_DEF0, slice(None, None, 1),\n 0x1234_5678_9ABC_DEF0, 0x0F7B_3D59_1E6A_2C48,\n 0x0F7B_3D59_1E6A_2C48, 64),\n \"lower-reg-64\":\n (64, 0x1234_5678_9ABC_DEF0, slice(31, None, None),\n 0x1234_5678, 0x9ABC_DEF0, 0x1234_5678_1234_5678, 32),\n \"lower-reg-forward-64\":\n (64, 0x1234_5678_9ABC_DEF0, slice(31, None, -1),\n 0x1234_5678, 0x9ABC_DEF0, 0x1234_5678_1234_5678, 32),\n \"lower-reg-reverse-64\":\n (64, 0x1234_5678_9ABC_DEF0, slice(None, 31, 1),\n 0x1234_5678, 0x0F7B_3D59, 0x1234_5678_1e6a_2C48, 32),\n \"upper-reg-64\":\n (64, 0x1234_5678_9ABC_DEF0, slice(None, 32, None),\n 0x9ABC_DEF0, 0x1234_5678, 0x9ABC_DEF0_9ABC_DEF0, 32),\n \"upper-reg-forward-64\":\n (64, 0x1234_5678_9ABC_DEF0, slice(None, 32, -1),\n 0x9ABC_DEF0, 0x1234_5678, 0x9ABC_DEF0_9ABC_DEF0, 32),\n \"upper-reg-reverse-64\":\n (64, 0x1234_5678_9ABC_DEF0, slice(32, None, 1),\n 0x9ABC_DEF0, 0x1E6A_2C48, 0x0F7B_3D59_9ABC_DEF0, 32),\n}\n\nADDRESS = 0x10000\n\n\ndef _create_register(length, debug=False):\n if length == 32:\n buf = np.ndarray((1,), 'u4')\n elif length == 64:\n buf = np.ndarray((1,), 'u8')\n reg = pynq.Register(ADDRESS, length, buffer=buf, debug=debug)\n return reg, buf\n\n\[email protected]('testname', TEST_VECTORS.keys())\ndef test_register_set_get(testname):\n length, start, idx, update, expected_get, expected_set, count = \\\n TEST_VECTORS[testname]\n reg, buf = _create_register(length)\n buf[:] = start\n val = reg[idx]\n assert val == expected_get\n reg[idx] = update\n assert buf[0] == expected_set\n assert str(reg) == hex(expected_set)\n assert int(reg) == expected_set\n assert operator.index(reg) == expected_set\n assert pynq.Register.count(idx, length) == count\n\n\ntest_register_desc = {\n 'address_offset': 16,\n 'access': 'read-write',\n 'size': 32,\n 'description': 'Test Register',\n 'type': None,\n 'id': None,\n 'fields': {\n 'read-field': {\n 'access': 'read-only',\n 'bit_offset': 0,\n 'bit_width': 4,\n 'description': 'Read only field'\n },\n 'write-field': {\n 'access': 'write-only',\n 'bit_offset': 4,\n 'bit_width': 4,\n 'description': 'Read only field 2'\n },\n 'rw-field-1': {\n 'access': 'read-write',\n 'bit_offset': 8,\n 'bit_width': 4,\n 'description': 'Read write field 1'\n },\n 'rw-field-2': {\n 'access': 'read-write',\n 'bit_offset': 12,\n 'bit_width': 4,\n 'description': 'Read write field 1'\n },\n '0-number-field': {\n 'access': 'read-write',\n 'bit_offset': 16,\n 'bit_width': 4,\n 'description': 'Field beginning with number'\n },\n 'space special !': {\n 'access': 'read-write',\n 'bit_offset': 20,\n 'bit_width': 4,\n 'description': 'Field with space and special character'\n },\n }\n}\n\nMockRegister = pynq.Register.create_subclass(\n \"Test\", test_register_desc['fields'], \"Test Register Documentation\")\n\n\[email protected](params=[32, 64])\ndef mock_register(request):\n width = request.param\n if width == 32:\n dtype = 'u4'\n elif width == 64:\n dtype = 'u8'\n buf = np.ndarray((1,), dtype)\n buf[0] = 0x87654321\n return MockRegister(ADDRESS, request.param, buffer=buf)\n\n\ndef test_nodoc():\n R = pynq.Register.create_subclass(\"NoDoc\", test_register_desc['fields'])\n assert R.__doc__ is None\n\n\[email protected](params=[32, 64])\ndef width(request):\n return request.param\n\n\ndef test_reg_readonly(mock_register):\n assert mock_register.read_field == 1\n with pytest.raises(AttributeError):\n mock_register.read_field = 9\n\n\ndef test_reg_writeonly(mock_register):\n assert mock_register.write_field == 2\n mock_register.write_field = 9\n assert int(mock_register) == 0x87654391\n\n\nNAMED_TESTS = {\n 'rw_field_1': (3, 0x87654921),\n 'rw_field_2': (4, 0x87659321),\n 'r0_number_field': (5, 0x87694321),\n 'space_special__': (6, 0x87954321),\n}\n\n\[email protected]('register_name', NAMED_TESTS.keys())\ndef test_reg_readwrite(mock_register, register_name):\n expected_field, expected_reg = NAMED_TESTS[register_name]\n assert getattr(mock_register, register_name) == expected_field\n setattr(mock_register, register_name, 9)\n assert int(mock_register) == expected_reg\n\n\nINVALID_TESTS = {\n \"slice-32\":\n (32, slice(0, 31, 2), \"Slicing step is not valid.\"),\n \"slice-64\":\n (64, slice(0, 31, 2), \"Slicing step is not valid.\"),\n \"small-start-32\":\n (32, slice(-1, 31), \"Slicing endpoint -1 not in range 0 - 31\"),\n \"small-end-32\":\n (32, slice(31, -1), \"Slicing endpoint -1 not in range 0 - 31\"),\n \"large-start-32\":\n (32, slice(32, 0), \"Slicing endpoint 32 not in range 0 - 31\"),\n \"large-end-32\":\n (32, slice(0, 32), \"Slicing endpoint 32 not in range 0 - 31\"),\n \"invalid-32\":\n (32, 1.0, \"Index must be int or slice.\"),\n \"small-start-64\":\n (64, slice(-1, 63), \"Slicing endpoint -1 not in range 0 - 63\"),\n \"small-end-64\":\n (64, slice(63, -1), \"Slicing endpoint -1 not in range 0 - 63\"),\n \"large-start-64\":\n (64, slice(64, 0), \"Slicing endpoint 64 not in range 0 - 63\"),\n \"large-end-64\":\n (64, slice(0, 64), \"Slicing endpoint 64 not in range 0 - 63\"),\n \"invalid-64\":\n (64, 1.0, \"Index must be int or slice.\"),\n}\n\n\[email protected]('test_name', INVALID_TESTS.keys())\ndef test_reg_invalid_read(test_name):\n width, idx, message = INVALID_TESTS[test_name]\n reg, buf = _create_register(width)\n with pytest.raises(ValueError) as excinfo:\n _ = reg[idx]\n assert str(excinfo.value) == message\n\n\[email protected]('test_name', INVALID_TESTS.keys())\ndef test_reg_invalid_write(test_name):\n width, idx, message = INVALID_TESTS[test_name]\n reg, buf = _create_register(width)\n with pytest.raises(ValueError) as excinfo:\n reg[idx] = 0\n assert str(excinfo.value) == message\n\n\ndef test_reg_large_write():\n reg, buf = _create_register(32)\n with pytest.raises(ValueError) as excinfo:\n reg[1:0] = 4\n assert str(excinfo.value) == \"Slicing range cannot represent value 4\"\n\n\ndef test_invalid_width():\n buf = np.ndarray((1,), 'u2')\n with pytest.raises(ValueError) as excinfo:\n reg = pynq.Register(ADDRESS, 16, buf) # NOQA\n assert str(excinfo.value) == \"Supported register width is 32 or 64.\"\n\n\ndef test_init_device(width):\n from .mock_devices import MockMemoryMappedDevice\n device = MockMemoryMappedDevice(\"test_active_device_\" + str(width))\n pynq.Device.active_device = device\n reg = pynq.Register(ADDRESS, width)\n assert (ADDRESS, width // 8) in device.regions\n region = device.regions[(ADDRESS, width // 8)]\n region[0] = 0x12\n assert reg[7:0] == 0x12\n reg[7:0] = 0x34\n assert region[0] == 0x34\n device.close()\n pynq.Device.active_device = None\n\n\ndef test_init_buffer(width):\n buf = bytearray(width // 8)\n reg = pynq.Register(ADDRESS, width, buffer=buf)\n buf[0] = 0x12\n assert reg[7:0] == 0x12\n reg[7:0] = 0x34\n assert buf[0] == 0x34\n\n\ndef test_big_bit(width):\n reg, buf = _create_register(width)\n with pytest.raises(ValueError) as excinfo:\n reg[1] = 2\n assert str(excinfo.value) == \"Value to be set should be either 0 or 1.\"\n\n\ndef test_repr_plain(width):\n reg, buf = _create_register(width)\n buf[0] = 0x1234_5678\n assert \"Register(value=305419896)\" == repr(reg)\n\n\ndef test_repr_fields(mock_register):\n assert \"Register(read_field=1, write_field=write-only, rw_field_1=3, rw_field_2=4, r0_number_field=5, space_special__=6)\" == repr(mock_register) # NOQA\n\n\ndef test_reg_debug_bit(width, capsys):\n reg, buf = _create_register(width, debug=True)\n reg[4] = 0\n out, err = capsys.readouterr()\n assert out == \"Register Debug: Setting bit 4 at address 0x10000 to 0\\n\"\n _ = reg[1]\n out, err = capsys.readouterr()\n assert out == \"Register Debug: Reading index 1 at address 0x10000\\n\"\n\n\ndef test_reg_debug_slice(width, capsys):\n reg, buf = _create_register(width, debug=True)\n reg[4:6] = 0\n out, err = capsys.readouterr()\n assert out == \"Register Debug: Setting bits 6:4 at address 0x10000 to 0\\n\"\n # assert out == \"Register Debug: Setting bits 4:6 at address 0x10000 to 0\\n\" # NOQA\n # assert out == \"Register Debug: Setting bits 7:4 at address 0x10000 to 0\\n\" # NOQA\n _ = reg[1:3]\n out, err = capsys.readouterr()\n # assert out == \"Register Debug: Reading bits 1:3 at address 0x10000\\n\"\n assert out == \"Register Debug: Reading bits 3:1 at address 0x10000\\n\"\n\n\ndef test_blank_regmap():\n buf = bytearray(16)\n with pytest.raises(RuntimeError) as excinfo:\n rm = pynq.registers.RegisterMap(buf) # NOQA\n assert str(excinfo.value) == \\\n \"Only subclasses of RegisterMap from create_subclass can be instantiated\" # NOQA\n\n\ntest_registermap_desc = {\n 'test_register': test_register_desc,\n 'out-of-order': {\n 'address_offset': 80,\n 'access': 'read-write',\n 'size': 32,\n 'description': 'Out of order register'\n },\n 'aligned_4': {\n 'address_offset': 32,\n 'access': 'read-write',\n 'size': 32,\n 'description': 'Aligned 32-bit register'\n },\n 'aligned_8': {\n 'address_offset': 40,\n 'access': 'read-write',\n 'size': 64,\n 'description': 'Aligned 64-bit register'\n },\n 'unaligned_8': {\n 'address_offset': 52,\n 'access': 'read-write',\n 'size': 64,\n 'description': 'Unaligned 64-bit register'\n },\n 'read-only': {\n 'address_offset': 64,\n 'access': 'read-only',\n 'size': 32,\n 'description': 'Read only 32-bit register'\n },\n 'write-only': {\n 'address_offset': 68,\n 'access': 'write-only',\n 'size': 32,\n 'description': 'Write-only 32-bit register'\n },\n 'space special !': {\n 'address_offset': 72,\n 'access': 'read-write',\n 'size': 32,\n 'description': 'Badly named 32-bit register'\n },\n '001_numbered': {\n 'address_offset': 76,\n 'access': 'read-write',\n 'size': 32,\n 'description': 'Badly named 32-bit register'\n },\n}\n\nMockRegisterMap = pynq.registers.RegisterMap.create_subclass(\n \"Mock\", test_registermap_desc)\n\n\[email protected](params=['bytearray', 'ndarray'])\ndef mock_registermap(request):\n if request.param == 'bytearray':\n buf = bytearray(96)\n elif request.param == 'ndarray':\n buf = np.ndarray((96,), 'u1')\n buf[16:20] = memoryview(b'\\x21\\x43\\x65\\x87')\n rm = MockRegisterMap(buf)\n return rm, buf\n\n\[email protected]('register_name', NAMED_TESTS.keys())\ndef test_regmap_fields(mock_registermap, register_name):\n expected_field, expected_reg = NAMED_TESTS[register_name]\n rm, buf = mock_registermap\n\n assert getattr(rm.test_register, register_name) == expected_field\n setattr(rm.test_register, register_name, 9)\n assert struct.unpack('I', buf[16:20])[0] == expected_reg\n\n\nREGMAP_TESTS = {\n 'aligned_4': (32, 'I', 0x12345678, 0x87654321),\n 'aligned_8': (40, 'Q', 0x123456789ABCDEF0, 0x0FEDCBA987654321),\n 'unaligned_8': (52, 'Q', 0x123456789ABCDEF0, 0x0FEDCBA987654321),\n 'write_only': (68, 'I', 0x12345678, 0x87654321),\n 'space_special__': (72, 'I', 0x12345678, 0x87654321),\n 'r001_numbered': (76, 'I', 0x12345678, 0x87654321),\n 'out_of_order': (80, 'I', 0x123456, 0x876543),\n}\n\n\[email protected]('register_name', REGMAP_TESTS.keys())\ndef test_regmap_rw(mock_registermap, register_name):\n offset, struct_string, start, end = REGMAP_TESTS[register_name]\n rm, buf = mock_registermap\n\n width = struct.calcsize(struct_string)\n buf[offset:offset+width] = memoryview(struct.pack(struct_string, start))\n if register_name == 'write_only':\n start = 'write-only'\n assert getattr(rm, register_name)[:] == start\n setattr(rm, register_name, end)\n assert struct.unpack(struct_string, buf[offset:offset+width])[0] == end\n\n\[email protected]('register_name', REGMAP_TESTS.keys())\ndef test_regmap_rw_mmio(register_name):\n from .mock_devices import MockRegisterDevice\n device = MockRegisterDevice('test_regmap_rw_mmio')\n mmio = pynq.MMIO(ADDRESS, 128, device=device)\n rm = MockRegisterMap(mmio.array)\n offset, struct_string, start, end = REGMAP_TESTS[register_name]\n read_transaction = (ADDRESS+offset, struct.pack(struct_string, start))\n write_transaction = (ADDRESS+offset, struct.pack(struct_string, end))\n if register_name == 'write_only':\n start = 'write-only'\n with device.check_transactions([read_transaction], []):\n value = getattr(rm, register_name)[:]\n assert value == start\n with device.check_transactions([], [write_transaction]):\n setattr(rm, register_name, end)\n device.close()\n\n\ndef test_regmap_read_only(mock_registermap):\n rm, buf = mock_registermap\n buf[64:68] = [0x21, 0x43, 0x65, 0x87]\n assert int(rm.read_only) == 0x87654321\n with pytest.raises(AttributeError):\n rm.read_only = 0x12345678\n\n\nexpected_regmap_repr = \"\"\"RegisterMap {\n test_register = Register(read_field=0, write_field=write-only, rw_field_1=1, rw_field_2=1, r0_number_field=2, space_special__=1),\n aligned_4 = Register(value=589439264),\n aligned_8 = Register(value=3399704436437297448),\n unaligned_8 = Register(value=4267786510494217524),\n read_only = Register(value=1128415552),\n write_only = Register(value=write-only),\n space_special__ = Register(value=1263159624),\n r001_numbered = Register(value=1330531660),\n out_of_order = Register(value=1397903696)\n}\"\"\" # NOQA\n\n\ndef test_regmap_repr(mock_registermap):\n rm, buf = mock_registermap\n buf[:] = range(96)\n print(repr(rm))\n assert expected_regmap_repr == repr(rm)\n\n\nbad_size_register_desc = {\n 'too_long': {\n 'address_offset': 0,\n 'access': 'read-write',\n 'size': 128,\n 'description': 'Aligned 128-bit register'\n },\n}\n\n\ndef test_too_long():\n RegClass = pynq.registers.RegisterMap.create_subclass(\n \"TooLong\", bad_size_register_desc)\n buf = bytearray(16)\n with pytest.warns(UserWarning):\n RegClass(buf)\n"
] |
[
[
"numpy.array",
"numpy.array_equal"
],
[
"numpy.ndarray"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
WenZhihao666/TREND
|
[
"ca4b17139b5f24d44d9421fed92021eb7a95ed6d"
] |
[
"main_test.py"
] |
[
"import sys\n\nsys.path.append('../')\nimport torch\nimport numpy as np\nimport random\nimport math\nimport time\nimport argparse\nfrom data_tlp_cite import DataHelper_t\nfrom torch.utils.data import DataLoader\nfrom model import Model\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import roc_auc_score, accuracy_score, f1_score\n\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n# device = torch.device(\"cpu\")\nFType = torch.FloatTensor\nLType = torch.LongTensor\n\ndef setup_seed(seed):\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n random.seed(seed)\n np.random.seed(seed)\n torch.backends.cudnn.deterministic = True\n\ndef main(args):\n setup_seed(args.seed)\n Data = DataHelper_t(args.file_path, args.node_feature_path, args.neg_size, args.hist_len, args.directed,\n tlp_flag=args.tlp_flag)\n\n loader = DataLoader(Data, batch_size=args.batch_size, shuffle=False, num_workers=5)\n\n model = Model(args).to(device)\n model.load_state_dict(torch.load('../res/cite/model.pkl'))\n\n s_emb_list = []\n t_emb_list = []\n dup_s_emb_list = []\n neg_embs_list = []\n loss_list = []\n\n model.eval()\n for i_batch, sample_batched in enumerate(loader):\n loss, s_emb, t_emb, dup_s_emb, neg_embs = model.forward(\n sample_batched['s_self_feat'].type(FType).reshape(-1, args.feat_dim).to(device),\n sample_batched['s_one_hop_feat'].type(FType).reshape(-1, args.feat_dim).to(device),\n sample_batched['s_two_hop_feat'].type(FType).reshape(-1, args.feat_dim).to(device),\n\n sample_batched['t_self_feat'].type(FType).reshape(-1, args.feat_dim).to(device),\n sample_batched['t_one_hop_feat'].type(FType).reshape(-1, args.feat_dim).to(device),\n sample_batched['t_two_hop_feat'].type(FType).reshape(-1, args.feat_dim).to(device),\n\n sample_batched['neg_self_feat'].type(FType).reshape(-1, args.feat_dim).to(device),\n sample_batched['neg_one_hop_feat'].type(FType).reshape(-1, args.feat_dim).to(device),\n sample_batched['neg_two_hop_feat'].type(FType).reshape(-1, args.feat_dim).to(device),\n\n sample_batched['event_time'].type(FType).to(device),\n sample_batched['s_history_times'].type(FType).to(device),\n sample_batched['s_his_his_times_list'].type(FType).to(device),\n sample_batched['t_history_times'].type(FType).to(device),\n sample_batched['t_his_his_times_list'].type(FType).to(device),\n sample_batched['neg_his_times_list'].type(FType).to(device),\n sample_batched['neg_his_his_times_list'].type(FType).to(device),\n sample_batched['s_edge_rate'].type(FType).to(device),\n training=False\n )\n s_emb_list.append(s_emb)\n t_emb_list.append(t_emb)\n dup_s_emb_list.append(dup_s_emb.reshape(-1, args.out_dim))\n neg_embs_list.append(neg_embs.reshape(-1, args.out_dim))\n loss_list.append(loss)\n\n s_emb_list = torch.cat(s_emb_list, dim=0)\n t_emb_list = torch.cat(t_emb_list, dim=0)\n dup_s_emb_list = torch.cat(dup_s_emb_list, dim=0)\n neg_embs_list = torch.cat(neg_embs_list, dim=0)\n truth = torch.ones(s_emb_list.size(0), dtype=torch.int)\n truth_neg = torch.zeros(neg_embs_list.size(0), dtype=torch.int)\n\n s_list = torch.cat((s_emb_list, dup_s_emb_list), dim=0)\n t_list = torch.cat((t_emb_list, neg_embs_list), dim=0)\n truth_list = torch.cat((truth, truth_neg), dim=0)\n\n dif_list = torch.abs(s_list - t_list)\n\n x_train, x_test, y_train, y_test = train_test_split(dif_list, truth_list, test_size=1 - args.train_ratio,\n random_state=args.seed, stratify=truth_list)\n\n lr = LogisticRegression(max_iter=10000)\n lr.fit(x_train, y_train)\n y_test_pred = lr.predict(x_test)\n acc = accuracy_score(y_test, y_test_pred)\n f1 = f1_score(y_test, y_test_pred)\n print('acc:{}'.format(round(acc, 4)))\n print('f1:{}'.format(round(f1, 4)))\n\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--file_path', type=str, default='./data/cite/emb_edges.pt')\n parser.add_argument('--node_feature_path', type=str, default='./data/cite/sorted_emb_feat.pt')\n parser.add_argument('--neg_size', type=int, default=1)\n parser.add_argument('--hist_len', type=int, default=10)\n parser.add_argument('--directed', type=bool, default=False)\n parser.add_argument('--epoch_num', type=int, default=10, help='epoch number')\n parser.add_argument('--tlp_flag', type=bool, default=True)\n parser.add_argument('--batch_size', type=int, default=100)\n parser.add_argument('--lr', type=float, default=0.001)\n parser.add_argument('--hid_dim', type=int, default=16)\n parser.add_argument('--feat_dim', type=int, default=128)\n parser.add_argument('--out_dim', type=int, default=16)\n parser.add_argument('--seed', type=int, default=4)\n parser.add_argument('--ncoef', type=float, default=0.01)\n parser.add_argument('--l2_reg', type=float, default=0.001)\n\n parser.add_argument('--train_ratio', type=float, default=0.8)\n\n args = parser.parse_args()\n\n start = time.perf_counter()\n\n main(args)"
] |
[
[
"torch.abs",
"sklearn.linear_model.LogisticRegression",
"numpy.random.seed",
"torch.cuda.manual_seed",
"torch.cat",
"torch.manual_seed",
"torch.load",
"torch.utils.data.DataLoader",
"sklearn.model_selection.train_test_split",
"torch.cuda.manual_seed_all",
"torch.cuda.is_available",
"sklearn.metrics.f1_score",
"sklearn.metrics.accuracy_score"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
khanhlvg/tensorflow
|
[
"a59b74ccaafae59d616ecf08204d63023ff6f49c",
"a59b74ccaafae59d616ecf08204d63023ff6f49c",
"a59b74ccaafae59d616ecf08204d63023ff6f49c",
"a59b74ccaafae59d616ecf08204d63023ff6f49c",
"a59b74ccaafae59d616ecf08204d63023ff6f49c"
] |
[
"tensorflow/contrib/model_pruning/python/pruning_test.py",
"tensorflow/python/keras/optimizer_v2/ftrl.py",
"tensorflow/python/keras/estimator/__init__.py",
"tensorflow/python/keras/optimizer_v2/rmsprop.py",
"tensorflow/python/kernel_tests/linalg/linear_operator_util_test.py"
] |
[
"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for the key functions in pruning library.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.contrib.model_pruning.python import pruning\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import partitioned_variables\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.training import training_util\n\n\nclass PruningHParamsTest(test.TestCase):\n PARAM_LIST = [\n \"name=test\", \"threshold_decay=0.9\", \"pruning_frequency=10\",\n \"sparsity_function_end_step=100\", \"target_sparsity=0.9\",\n \"weight_sparsity_map=[conv1:0.8,conv2/kernel:0.8]\"\n ]\n TEST_HPARAMS = \",\".join(PARAM_LIST)\n\n def setUp(self):\n super(PruningHParamsTest, self).setUp()\n # Add global step variable to the graph\n self.global_step = training_util.get_or_create_global_step()\n # Add sparsity\n self.sparsity = variables.VariableV1(0.5, name=\"sparsity\")\n # Parse hparams\n self.pruning_hparams = pruning.get_pruning_hparams().parse(\n self.TEST_HPARAMS)\n\n def testInit(self):\n p = pruning.Pruning(self.pruning_hparams)\n self.assertEqual(p._spec.name, \"test\")\n self.assertAlmostEqual(p._spec.threshold_decay, 0.9)\n self.assertEqual(p._spec.pruning_frequency, 10)\n self.assertEqual(p._spec.sparsity_function_end_step, 100)\n self.assertAlmostEqual(p._spec.target_sparsity, 0.9)\n self.assertEqual(p._weight_sparsity_map[\"conv1\"], 0.8)\n self.assertEqual(p._weight_sparsity_map[\"conv2/kernel\"], 0.8)\n\n def testInitWithExternalSparsity(self):\n with self.cached_session():\n p = pruning.Pruning(spec=self.pruning_hparams, sparsity=self.sparsity)\n variables.global_variables_initializer().run()\n sparsity = p._sparsity.eval()\n self.assertAlmostEqual(sparsity, 0.5)\n\n def testInitWithVariableReuse(self):\n with self.cached_session():\n p = pruning.Pruning(spec=self.pruning_hparams, sparsity=self.sparsity)\n p_copy = pruning.Pruning(\n spec=self.pruning_hparams, sparsity=self.sparsity)\n variables.global_variables_initializer().run()\n sparsity = p._sparsity.eval()\n self.assertAlmostEqual(sparsity, 0.5)\n self.assertEqual(p._sparsity.eval(), p_copy._sparsity.eval())\n\n\nclass PruningTest(test.TestCase):\n\n def setUp(self):\n super(PruningTest, self).setUp()\n self.global_step = training_util.get_or_create_global_step()\n\n def testCreateMask2D(self):\n width = 10\n height = 20\n with self.cached_session():\n weights = variables.VariableV1(\n random_ops.random_normal([width, height], stddev=1), name=\"weights\")\n masked_weights = pruning.apply_mask(weights,\n variable_scope.get_variable_scope())\n variables.global_variables_initializer().run()\n weights_val = weights.eval()\n masked_weights_val = masked_weights.eval()\n self.assertAllEqual(weights_val, masked_weights_val)\n\n def testUpdateSingleMask(self):\n with self.cached_session() as session:\n weights = variables.VariableV1(\n math_ops.linspace(1.0, 100.0, 100), name=\"weights\")\n masked_weights = pruning.apply_mask(weights)\n sparsity = variables.VariableV1(0.95, name=\"sparsity\")\n p = pruning.Pruning(sparsity=sparsity)\n p._spec.threshold_decay = 0.0\n mask_update_op = p.mask_update_op()\n variables.global_variables_initializer().run()\n masked_weights_val = masked_weights.eval()\n self.assertAllEqual(np.count_nonzero(masked_weights_val), 100)\n session.run(mask_update_op)\n masked_weights_val = masked_weights.eval()\n self.assertAllEqual(np.count_nonzero(masked_weights_val), 5)\n\n def _blockMasking(self, hparams, weights, expected_mask):\n\n threshold = variables.VariableV1(0.0, name=\"threshold\")\n sparsity = variables.VariableV1(0.5, name=\"sparsity\")\n test_spec = \",\".join(hparams)\n pruning_hparams = pruning.get_pruning_hparams().parse(test_spec)\n\n # Set up pruning\n p = pruning.Pruning(pruning_hparams, sparsity=sparsity)\n with self.cached_session():\n variables.global_variables_initializer().run()\n _, new_mask = p._maybe_update_block_mask(weights, threshold)\n # Check if the mask is the same size as the weights\n self.assertAllEqual(new_mask.get_shape(), weights.get_shape())\n mask_val = new_mask.eval()\n self.assertAllEqual(mask_val, expected_mask)\n\n def testBlockMasking(self):\n param_list = [\"block_height=2\", \"block_width=2\", \"threshold_decay=0\"]\n\n weights_avg = constant_op.constant(\n [[0.1, 0.1, 0.2, 0.2], [0.1, 0.1, 0.2, 0.2], [0.3, 0.3, 0.4, 0.4],\n [0.3, 0.3, 0.4, 0.4]])\n weights_max = constant_op.constant(\n [[0.1, 0.0, 0.2, 0.0], [0.0, -0.1, 0.0, -0.2], [0.3, 0.0, 0.4, 0.0],\n [0.0, -0.3, 0.0, -0.4]])\n expected_mask = [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0],\n [1., 1., 1., 1.], [1., 1., 1., 1.]]\n\n self._blockMasking(param_list + [\"block_pooling_function=MAX\"], weights_max,\n expected_mask)\n self._blockMasking(param_list + [\"block_pooling_function=AVG\"], weights_avg,\n expected_mask)\n\n def testBlockMaskingWithHigherDimensions(self):\n param_list = [\"block_height=2\", \"block_width=2\", \"threshold_decay=0\"]\n\n # Weights as in testBlockMasking, but with one extra dimension.\n weights_avg = constant_op.constant(\n [[[0.1, 0.1, 0.2, 0.2], [0.1, 0.1, 0.2, 0.2], [0.3, 0.3, 0.4, 0.4],\n [0.3, 0.3, 0.4, 0.4]]])\n weights_max = constant_op.constant(\n [[[0.1, 0.0, 0.2, 0.0], [0.0, -0.1, 0.0, -0.2], [0.3, 0.0, 0.4, 0.0],\n [0.0, -0.3, 0.0, -0.4]]])\n expected_mask = [[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0],\n [1., 1., 1., 1.], [1., 1., 1., 1.]]]\n\n self._blockMasking(param_list + [\"block_pooling_function=MAX\"], weights_max,\n expected_mask)\n self._blockMasking(param_list + [\"block_pooling_function=AVG\"],\n weights_avg, expected_mask)\n\n def testPartitionedVariableMasking(self):\n partitioner = partitioned_variables.variable_axis_size_partitioner(40)\n with self.cached_session() as session:\n with variable_scope.variable_scope(\"\", partitioner=partitioner):\n sparsity = variables.VariableV1(0.5, name=\"Sparsity\")\n weights = variable_scope.get_variable(\n \"weights\", initializer=math_ops.linspace(1.0, 100.0, 100))\n masked_weights = pruning.apply_mask(\n weights, scope=variable_scope.get_variable_scope())\n p = pruning.Pruning(sparsity=sparsity)\n p._spec.threshold_decay = 0.0\n mask_update_op = p.mask_update_op()\n variables.global_variables_initializer().run()\n masked_weights_val = masked_weights.eval()\n session.run(mask_update_op)\n masked_weights_val = masked_weights.eval()\n self.assertAllEqual(np.count_nonzero(masked_weights_val), 50)\n\n def testConditionalMaskUpdate(self):\n param_list = [\n \"pruning_frequency=2\", \"begin_pruning_step=1\", \"end_pruning_step=6\",\n \"nbins=100\"\n ]\n test_spec = \",\".join(param_list)\n pruning_hparams = pruning.get_pruning_hparams().parse(test_spec)\n weights = variables.VariableV1(\n math_ops.linspace(1.0, 100.0, 100), name=\"weights\")\n masked_weights = pruning.apply_mask(weights)\n sparsity = variables.VariableV1(0.00, name=\"sparsity\")\n # Set up pruning\n p = pruning.Pruning(pruning_hparams, sparsity=sparsity)\n p._spec.threshold_decay = 0.0\n mask_update_op = p.conditional_mask_update_op()\n sparsity_val = math_ops.linspace(0.0, 0.9, 10)\n increment_global_step = state_ops.assign_add(self.global_step, 1)\n non_zero_count = []\n with self.cached_session() as session:\n variables.global_variables_initializer().run()\n for i in range(10):\n session.run(state_ops.assign(sparsity, sparsity_val[i]))\n session.run(mask_update_op)\n session.run(increment_global_step)\n non_zero_count.append(np.count_nonzero(masked_weights.eval()))\n # Weights pruned at steps 0,2,4,and,6\n expected_non_zero_count = [100, 100, 80, 80, 60, 60, 40, 40, 40, 40]\n self.assertAllEqual(expected_non_zero_count, non_zero_count)\n\n def testWeightSpecificSparsity(self):\n param_list = [\n \"begin_pruning_step=1\", \"pruning_frequency=1\", \"end_pruning_step=100\",\n \"target_sparsity=0.5\",\n \"weight_sparsity_map=[layer1:0.6,layer2/weights:0.75,.*kernel:0.6]\",\n \"threshold_decay=0.0\"\n ]\n test_spec = \",\".join(param_list)\n pruning_hparams = pruning.get_pruning_hparams().parse(test_spec)\n\n with variable_scope.variable_scope(\"layer1\"):\n w1 = variables.VariableV1(\n math_ops.linspace(1.0, 100.0, 100), name=\"weights\")\n _ = pruning.apply_mask(w1)\n with variable_scope.variable_scope(\"layer2\"):\n w2 = variables.VariableV1(\n math_ops.linspace(1.0, 100.0, 100), name=\"weights\")\n _ = pruning.apply_mask(w2)\n with variable_scope.variable_scope(\"layer3\"):\n w3 = variables.VariableV1(\n math_ops.linspace(1.0, 100.0, 100), name=\"kernel\")\n _ = pruning.apply_mask(w3)\n\n p = pruning.Pruning(pruning_hparams)\n mask_update_op = p.conditional_mask_update_op()\n increment_global_step = state_ops.assign_add(self.global_step, 1)\n\n with self.cached_session() as session:\n variables.global_variables_initializer().run()\n for _ in range(110):\n session.run(mask_update_op)\n session.run(increment_global_step)\n\n self.assertAllClose(\n session.run(pruning.get_weight_sparsity()), [0.6, 0.75, 0.6])\n\n\nif __name__ == \"__main__\":\n test.main()\n",
"# 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\"\"\"Ftrl-proximal for TensorFlow.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.keras.optimizer_v2 import optimizer_v2\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.training import training_ops\nfrom tensorflow.python.util.tf_export import keras_export\n\n\n@keras_export('keras.optimizers.Ftrl')\nclass Ftrl(optimizer_v2.OptimizerV2):\n r\"\"\"Optimizer that implements the FTRL algorithm.\n\n See Algorithm 1 of this [paper](\n https://www.eecs.tufts.edu/~dsculley/papers/ad-click-prediction.pdf).\n This version has support for both online L2 (the L2 penalty given in the paper\n above) and shrinkage-type L2 (which is the addition of an L2 penalty to the\n loss function).\n\n Initialization:\n $$t = 0$$\n $$n_{0} = 0$$\n $$\\sigma_{0} = 0$$\n $$z_{0} = 0$$\n\n Update ($$i$$ is variable index):\n $$t = t + 1$$\n $$n_{t,i} = n_{t-1,i} + g_{t,i}^{2}$$\n $$\\sigma_{t,i} = (\\sqrt{n_{t,i}} - \\sqrt{n_{t-1,i}}) / \\alpha$$\n $$z_{t,i} = z_{t-1,i} + g_{t,i} - \\sigma_{t,i} * w_{t,i}$$\n $$w_{t,i} = - ((\\beta+\\sqrt{n+{t}}) / \\alpha + \\lambda_{2})^{-1} * (z_{i} -\n sgn(z_{i}) * \\lambda_{1}) if \\abs{z_{i}} > \\lambda_{i} else 0$$\n\n Check the documentation for the l2_shrinkage_regularization_strength\n parameter for more details when shrinkage is enabled, where gradient is\n replaced with gradient_with_shrinkage.\n \"\"\"\n\n def __init__(self,\n learning_rate=0.001,\n learning_rate_power=-0.5,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.0,\n l2_regularization_strength=0.0,\n name='Ftrl',\n l2_shrinkage_regularization_strength=0.0,\n **kwargs):\n r\"\"\"Construct a new FTRL optimizer.\n\n Args:\n learning_rate: A float value or a constant float `Tensor`.\n learning_rate_power: A float value, must be less or equal to zero.\n Controls how the learning rate decreases during training. Use zero for\n a fixed learning rate.\n initial_accumulator_value: The starting value for accumulators.\n Only zero or positive values are allowed.\n l1_regularization_strength: A float value, must be greater than or\n equal to zero.\n l2_regularization_strength: A float value, must be greater than or\n equal to zero.\n name: Optional name prefix for the operations created when applying\n gradients. Defaults to \"Ftrl\".\n l2_shrinkage_regularization_strength: A float value, must be greater than\n or equal to zero. This differs from L2 above in that the L2 above is a\n stabilization penalty, whereas this L2 shrinkage is a magnitude penalty.\n The FTRL formulation can be written as:\n w_{t+1} = argmin_w(\\hat{g}_{1:t}w + L1*||w||_1 + L2*||w||_2^2), where\n \\hat{g} = g + (2*L2_shrinkage*w), and g is the gradient of the loss\n function w.r.t. the weights w.\n Specifically, in the absence of L1 regularization, it is equivalent to\n the following update rule:\n w_{t+1} = w_t - lr_t / (1 + 2*L2*lr_t) * g_t -\n 2*L2_shrinkage*lr_t / (1 + 2*L2*lr_t) * w_t\n where lr_t is the learning rate at t.\n When input is sparse shrinkage will only happen on the active weights.\\\n **kwargs: keyword arguments. Allowed to be {`clipnorm`, `clipvalue`, `lr`,\n `decay`}. `clipnorm` is clip gradients by norm; `clipvalue` is clip\n gradients by value, `decay` is included for backward compatibility to\n allow time inverse decay of learning rate. `lr` is included for backward\n compatibility, recommended to use `learning_rate` instead.\n\n Raises:\n ValueError: If one of the arguments is invalid.\n\n References\n See [paper]\n (https://www.eecs.tufts.edu/~dsculley/papers/ad-click-prediction.pdf)\n \"\"\"\n super(Ftrl, self).__init__(name, **kwargs)\n\n if initial_accumulator_value < 0.0:\n raise ValueError(\n 'initial_accumulator_value %f needs to be positive or zero' %\n initial_accumulator_value)\n if learning_rate_power > 0.0:\n raise ValueError('learning_rate_power %f needs to be negative or zero' %\n learning_rate_power)\n if l1_regularization_strength < 0.0:\n raise ValueError(\n 'l1_regularization_strength %f needs to be positive or zero' %\n l1_regularization_strength)\n if l2_regularization_strength < 0.0:\n raise ValueError(\n 'l2_regularization_strength %f needs to be positive or zero' %\n l2_regularization_strength)\n if l2_shrinkage_regularization_strength < 0.0:\n raise ValueError(\n 'l2_shrinkage_regularization_strength %f needs to be positive'\n ' or zero' % l2_shrinkage_regularization_strength)\n\n self._set_hyper('learning_rate', learning_rate)\n self._set_hyper('decay', self._initial_decay)\n self._set_hyper('learning_rate_power', learning_rate_power)\n self._set_hyper('l1_regularization_strength', l1_regularization_strength)\n self._set_hyper('l2_regularization_strength', l2_regularization_strength)\n self._initial_accumulator_value = initial_accumulator_value\n self._l2_shrinkage_regularization_strength = (\n l2_shrinkage_regularization_strength)\n\n def _create_slots(self, var_list):\n # Create the \"accum\" and \"linear\" slots.\n for var in var_list:\n dtype = var.dtype.base_dtype\n init = init_ops.constant_initializer(\n self._initial_accumulator_value, dtype=dtype)\n self.add_slot(var, 'accumulator', init)\n self.add_slot(var, 'linear')\n\n def _resource_apply_dense(self, grad, var):\n var_dtype = var.dtype.base_dtype\n lr_t = self._decayed_lr_t[var_dtype]\n learning_rate_power = self._get_hyper('learning_rate_power', var_dtype)\n l1_regularization_strength = self._get_hyper('l1_regularization_strength',\n var_dtype)\n l2_regularization_strength = self._get_hyper('l2_regularization_strength',\n var_dtype)\n accum = self.get_slot(var, 'accumulator')\n linear = self.get_slot(var, 'linear')\n if self._l2_shrinkage_regularization_strength <= 0.0:\n return training_ops.resource_apply_ftrl(\n var.handle,\n accum.handle,\n linear.handle,\n grad,\n lr_t,\n l1_regularization_strength,\n l2_regularization_strength,\n learning_rate_power,\n use_locking=self._use_locking)\n else:\n return training_ops.resource_apply_ftrl_v2(\n var.handle,\n accum.handle,\n linear.handle,\n grad,\n lr_t,\n l1_regularization_strength,\n l2_regularization_strength,\n math_ops.cast(self._l2_shrinkage_regularization_strength, var_dtype),\n learning_rate_power,\n use_locking=self._use_locking)\n\n def _resource_apply_sparse(self, grad, var, indices):\n var_dtype = var.dtype.base_dtype\n lr_t = self._decayed_lr_t[var_dtype]\n learning_rate_power = self._get_hyper('learning_rate_power', var_dtype)\n l1_regularization_strength = self._get_hyper('l1_regularization_strength',\n var_dtype)\n l2_regularization_strength = self._get_hyper('l2_regularization_strength',\n var_dtype)\n accum = self.get_slot(var, 'accumulator')\n linear = self.get_slot(var, 'linear')\n if self._l2_shrinkage_regularization_strength <= 0.0:\n return training_ops.resource_sparse_apply_ftrl(\n var.handle,\n accum.handle,\n linear.handle,\n grad,\n indices,\n lr_t,\n l1_regularization_strength,\n l2_regularization_strength,\n learning_rate_power,\n use_locking=self._use_locking)\n else:\n return training_ops.resource_sparse_apply_ftrl_v2(\n var.handle,\n accum.handle,\n linear.handle,\n grad,\n indices,\n lr_t,\n l1_regularization_strength,\n l2_regularization_strength,\n math_ops.cast(self._l2_shrinkage_regularization_strength, var_dtype),\n learning_rate_power,\n use_locking=self._use_locking)\n\n def get_config(self):\n config = super(Ftrl, self).get_config()\n config.update({\n 'learning_rate':\n self._serialize_hyperparameter('learning_rate'),\n 'decay':\n self._serialize_hyperparameter('decay'),\n 'initial_accumulator_value':\n self._initial_accumulator_value,\n 'learning_rate_power':\n self._serialize_hyperparameter('learning_rate_power'),\n 'l1_regularization_strength':\n self._serialize_hyperparameter('l1_regularization_strength'),\n 'l2_regularization_strength':\n self._serialize_hyperparameter('l2_regularization_strength'),\n 'l2_shrinkage_regularization_strength':\n self._l2_shrinkage_regularization_strength,\n })\n return config\n",
"# 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\"\"\"Keras estimator API.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.util.tf_export import keras_export\n\n# Keras has undeclared dependency on tensorflow/estimator:estimator_py.\n# As long as you depend //third_party/py/tensorflow:tensorflow target\n# everything will work as normal.\n\n\n# LINT.IfChange\n@keras_export(v1=['keras.estimator.model_to_estimator'])\ndef model_to_estimator(\n keras_model=None,\n keras_model_path=None,\n custom_objects=None,\n model_dir=None,\n config=None,\n checkpoint_format='saver'):\n \"\"\"Constructs an `Estimator` instance from given keras model.\n\n For usage example, please see:\n [Creating estimators from Keras\n Models](https://tensorflow.org/guide/estimators#model_to_estimator).\n\n __Sample Weights__\n Estimators returned by `model_to_estimator` are configured to handle sample\n weights (similar to `keras_model.fit(x, y, sample_weights)`). To pass sample\n weights when training or evaluating the Estimator, the first item returned by\n the input function should be a dictionary with keys `features` and\n `sample_weights`. Example below:\n\n ```\n keras_model = tf.keras.Model(...)\n keras_model.compile(...)\n\n estimator = tf.keras.estimator.model_to_estimator(keras_model)\n\n def input_fn():\n return dataset_ops.Dataset.from_tensors(\n ({'features': features, 'sample_weights': sample_weights},\n targets))\n\n estimator.train(input_fn, steps=1)\n ```\n\n Args:\n keras_model: A compiled Keras model object. This argument is mutually\n exclusive with `keras_model_path`.\n keras_model_path: Path to a compiled Keras model saved on disk, in HDF5\n format, which can be generated with the `save()` method of a Keras model.\n This argument is mutually exclusive with `keras_model`.\n custom_objects: Dictionary for custom objects.\n model_dir: Directory to save `Estimator` model parameters, graph, summary\n files for TensorBoard, etc.\n config: `RunConfig` to config `Estimator`.\n checkpoint_format: Sets the format of the checkpoint saved by the estimator\n when training. May be `saver` or `checkpoint`, depending on whether to\n save checkpoints from `tf.train.Saver` or `tf.train.Checkpoint`. This\n argument currently defaults to `saver`. When 2.0 is released, the default\n will be `checkpoint`. Estimators use name-based `tf.train.Saver`\n checkpoints, while Keras models use object-based checkpoints from\n `tf.train.Checkpoint`. Currently, saving object-based checkpoints from\n `model_to_estimator` is only supported by Functional and Sequential\n models.\n\n Returns:\n An Estimator from given keras model.\n\n Raises:\n ValueError: if neither keras_model nor keras_model_path was given.\n ValueError: if both keras_model and keras_model_path was given.\n ValueError: if the keras_model_path is a GCS URI.\n ValueError: if keras_model has not been compiled.\n ValueError: if an invalid checkpoint_format was given.\n \"\"\"\n try:\n from tensorflow_estimator.python.estimator import keras as keras_lib # pylint: disable=g-import-not-at-top\n except ImportError:\n raise NotImplementedError(\n 'tf.keras.estimator.model_to_estimator function not available in your '\n 'installation.')\n return keras_lib.model_to_estimator( # pylint:disable=unexpected-keyword-arg\n keras_model=keras_model,\n keras_model_path=keras_model_path,\n custom_objects=custom_objects,\n model_dir=model_dir,\n config=config,\n checkpoint_format=checkpoint_format)\n\n\n@keras_export('keras.estimator.model_to_estimator', v1=[])\ndef model_to_estimator_v2(\n keras_model=None,\n keras_model_path=None,\n custom_objects=None,\n model_dir=None,\n config=None,\n checkpoint_format='checkpoint'):\n \"\"\"Constructs an `Estimator` instance from given keras model.\n\n For usage example, please see:\n [Creating estimators from Keras\n Models](https://tensorflow.org/guide/estimators#model_to_estimator).\n\n Args:\n keras_model: A compiled Keras model object. This argument is mutually\n exclusive with `keras_model_path`.\n keras_model_path: Path to a compiled Keras model saved on disk, in HDF5\n format, which can be generated with the `save()` method of a Keras model.\n This argument is mutually exclusive with `keras_model`.\n custom_objects: Dictionary for custom objects.\n model_dir: Directory to save `Estimator` model parameters, graph, summary\n files for TensorBoard, etc.\n config: `RunConfig` to config `Estimator`.\n checkpoint_format: Sets the format of the checkpoint saved by the estimator\n when training. May be `saver` or `checkpoint`, depending on whether to\n save checkpoints from `tf.compat.v1.train.Saver` or `tf.train.Checkpoint`.\n The default is `checkpoint`. Estimators use name-based `tf.train.Saver`\n checkpoints, while Keras models use object-based checkpoints from\n `tf.train.Checkpoint`. Currently, saving object-based checkpoints from\n `model_to_estimator` is only supported by Functional and Sequential\n models.\n\n Returns:\n An Estimator from given keras model.\n\n Raises:\n ValueError: if neither keras_model nor keras_model_path was given.\n ValueError: if both keras_model and keras_model_path was given.\n ValueError: if the keras_model_path is a GCS URI.\n ValueError: if keras_model has not been compiled.\n ValueError: if an invalid checkpoint_format was given.\n \"\"\"\n try:\n from tensorflow_estimator.python.estimator import keras as keras_lib # pylint: disable=g-import-not-at-top\n except ImportError:\n raise NotImplementedError(\n 'tf.keras.estimator.model_to_estimator function not available in your '\n 'installation.')\n return keras_lib.model_to_estimator( # pylint:disable=unexpected-keyword-arg\n keras_model=keras_model,\n keras_model_path=keras_model_path,\n custom_objects=custom_objects,\n model_dir=model_dir,\n config=config,\n checkpoint_format=checkpoint_format)\n# LINT.ThenChange(//tensorflow_estimator/python/estimator/keras.py)\n\n\n",
"# 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\"\"\"RMSprop for TensorFlow.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.keras import backend_config\nfrom tensorflow.python.keras.optimizer_v2 import optimizer_v2\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.training import training_ops\nfrom tensorflow.python.util.tf_export import keras_export\n\n\n@keras_export(\"keras.optimizers.RMSprop\")\nclass RMSprop(optimizer_v2.OptimizerV2):\n r\"\"\"Optimizer that implements the RMSprop algorithm.\n\n A detailed description of rmsprop.\n\n - maintain a moving (discounted) average of the square of gradients\n - divide gradient by the root of this average\n\n $$mean_square_t = rho * mean_square{t-1} + (1-rho) * gradient ** 2$$\n $$mom_t = momentum * mom_{t-1} + learning_rate * gradient / \\sqrt{ /\n mean_square_t + \\epsilon}$$\n $$variable_t := variable_{t-1} - mom_t$$\n\n This implementation of RMSprop uses plain momentum, not Nesterov momentum.\n\n The centered version additionally maintains a moving average of the\n gradients, and uses that average to estimate the variance:\n\n $$mean_grad_t = rho * mean_grad_{t-1} + (1-rho) * gradient$$\n $$mean_square_t = rho * mean_square_{t-1} + (1-rho) * gradient ** 2$$\n $$mom_t = momentum * mom_{t-1} + learning_rate * gradient /\n sqrt(mean_square_t - mean_grad_t**2 + epsilon)$$\n $$variable_t := variable_{t-1} - mom_t$$\n\n References\n See ([pdf]\n http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf).\n \"\"\"\n\n def __init__(self,\n learning_rate=0.001,\n rho=0.9,\n momentum=0.0,\n epsilon=1e-7,\n centered=False,\n name=\"RMSprop\",\n **kwargs):\n \"\"\"Construct a new RMSprop optimizer.\n\n Note that in the dense implementation of this algorithm, variables and their\n corresponding accumulators (momentum, gradient moving average, square\n gradient moving average) will be updated even if the gradient is zero\n (i.e. accumulators will decay, momentum will be applied). The sparse\n implementation (used when the gradient is an `IndexedSlices` object,\n typically because of `tf.gather` or an embedding lookup in the forward pass)\n will not update variable slices or their accumulators unless those slices\n were used in the forward pass (nor is there an \"eventual\" correction to\n account for these omitted updates). This leads to more efficient updates for\n large embedding lookup tables (where most of the slices are not accessed in\n a particular graph execution), but differs from the published algorithm.\n\n Args:\n learning_rate: A Tensor or a floating point value. The learning rate.\n rho: Discounting factor for the history/coming gradient\n momentum: A scalar tensor.\n epsilon: Small value to avoid zero denominator.\n centered: If True, gradients are normalized by the estimated variance of\n the gradient; if False, by the uncentered second moment. Setting this to\n True may help with training, but is slightly more expensive in terms of\n computation and memory. Defaults to False.\n name: Optional name prefix for the operations created when applying\n gradients. Defaults to \"RMSprop\". @compatibility(eager) When eager\n execution is enabled, `learning_rate`, `decay`, `momentum`, and\n `epsilon` can each be a callable that takes no arguments and returns the\n actual value to use. This can be useful for changing these values across\n different invocations of optimizer functions. @end_compatibility\n **kwargs: keyword arguments. Allowed to be {`clipnorm`, `clipvalue`, `lr`,\n `decay`}. `clipnorm` is clip gradients by norm; `clipvalue` is clip\n gradients by value, `decay` is included for backward compatibility to\n allow time inverse decay of learning rate. `lr` is included for backward\n compatibility, recommended to use `learning_rate` instead.\n \"\"\"\n super(RMSprop, self).__init__(name, **kwargs)\n self._set_hyper(\"learning_rate\", kwargs.get(\"lr\", learning_rate))\n self._set_hyper(\"decay\", self._initial_decay)\n self._set_hyper(\"rho\", rho)\n\n self._momentum = False\n if isinstance(momentum, ops.Tensor) or callable(momentum) or momentum > 0:\n self._momentum = True\n if isinstance(momentum, (int, float)) and (momentum < 0 or momentum > 1):\n raise ValueError(\"`momentum` must be between [0, 1].\")\n self._set_hyper(\"momentum\", momentum)\n\n self.epsilon = epsilon or backend_config.epsilon()\n self.centered = centered\n\n def _create_slots(self, var_list):\n for var in var_list:\n self.add_slot(var, \"rms\")\n if self._momentum:\n for var in var_list:\n self.add_slot(var, \"momentum\")\n if self.centered:\n for var in var_list:\n self.add_slot(var, \"mg\")\n\n def _resource_apply_dense(self, grad, var):\n var_dtype = var.dtype.base_dtype\n lr_t = self._decayed_lr_t[var_dtype]\n rms = self.get_slot(var, \"rms\")\n rho = self._get_hyper(\"rho\", var_dtype)\n momentum = self._get_hyper(\"momentum\", var_dtype)\n epsilon_t = ops.convert_to_tensor(self.epsilon, var_dtype)\n if self._momentum:\n mom = self.get_slot(var, \"momentum\")\n if self.centered:\n mg = self.get_slot(var, \"mg\")\n return training_ops.resource_apply_centered_rms_prop(\n var.handle,\n mg.handle,\n rms.handle,\n mom.handle,\n lr_t,\n rho,\n momentum,\n epsilon_t,\n grad,\n use_locking=self._use_locking)\n else:\n return training_ops.resource_apply_rms_prop(\n var.handle,\n rms.handle,\n mom.handle,\n lr_t,\n rho,\n momentum,\n epsilon_t,\n grad,\n use_locking=self._use_locking)\n else:\n rms_t = rho * rms + (1. - rho) * math_ops.square(grad)\n rms_t = state_ops.assign(rms, rms_t, use_locking=self._use_locking)\n denom_t = rms_t\n if self.centered:\n mg = self.get_slot(var, \"mg\")\n mg_t = rho * mg + (1. - rho) * grad\n mg_t = state_ops.assign(mg, mg_t, use_locking=self._use_locking)\n denom_t = rms_t - math_ops.square(mg_t)\n var_t = var - lr_t * grad / (math_ops.sqrt(denom_t) + epsilon_t)\n return state_ops.assign(var, var_t, use_locking=self._use_locking).op\n\n def _resource_apply_sparse(self, grad, var, indices):\n var_dtype = var.dtype.base_dtype\n lr_t = self._decayed_lr_t[var_dtype]\n rms = self.get_slot(var, \"rms\")\n rho = self._get_hyper(\"rho\", var_dtype)\n momentum = self._get_hyper(\"momentum\", var_dtype)\n epsilon_t = ops.convert_to_tensor(self.epsilon, var_dtype)\n if self._momentum:\n mom = self.get_slot(var, \"momentum\")\n if self.centered:\n mg = self.get_slot(var, \"mg\")\n return training_ops.resource_sparse_apply_centered_rms_prop(\n var.handle,\n mg.handle,\n rms.handle,\n mom.handle,\n lr_t,\n rho,\n momentum,\n epsilon_t,\n grad,\n indices,\n use_locking=self._use_locking)\n else:\n return training_ops.resource_sparse_apply_rms_prop(\n var.handle,\n rms.handle,\n mom.handle,\n lr_t,\n rho,\n momentum,\n epsilon_t,\n grad,\n indices,\n use_locking=self._use_locking)\n else:\n rms_scaled_g_values = (grad * grad) * (1. - rho)\n rms_t = state_ops.assign(rms, rms * rho, use_locking=self._use_locking)\n with ops.control_dependencies([rms_t]):\n rms_t = self._resource_scatter_add(rms, indices, rms_scaled_g_values)\n rms_slice = array_ops.gather(rms_t, indices)\n denom_slice = rms_slice\n if self.centered:\n mg = self.get_slot(var, \"mg\")\n mg_scaled_g_values = grad * (1. - rho)\n mg_t = state_ops.assign(mg, mg * rho, use_locking=self._use_locking)\n with ops.control_dependencies([mg_t]):\n mg_t = self._resource_scatter_add(mg, indices, mg_scaled_g_values)\n mg_slice = array_ops.gather(mg_t, indices)\n denom_slice = rms_slice - math_ops.square(mg_slice)\n var_update = self._resource_scatter_add(\n var, indices, -lr_t * grad / (math_ops.sqrt(denom_slice) + epsilon_t))\n if self.centered:\n return control_flow_ops.group(*[var_update, rms_t, mg_t])\n return control_flow_ops.group(*[var_update, rms_t])\n\n def set_weights(self, weights):\n params = self.weights\n # Override set_weights for backward compatibility of Keras V1 optimizer\n # since it does not include iteration at head of the weight list. Set\n # iteration to 0.\n if len(params) == len(weights) + 1:\n weights = [np.array(0)] + weights\n super(RMSprop, self).set_weights(weights)\n\n def get_config(self):\n config = super(RMSprop, self).get_config()\n config.update({\n \"learning_rate\": self._serialize_hyperparameter(\"learning_rate\"),\n \"decay\": self._serialize_hyperparameter(\"decay\"),\n \"rho\": self._serialize_hyperparameter(\"rho\"),\n \"momentum\": self._serialize_hyperparameter(\"momentum\"),\n \"epsilon\": self.epsilon,\n \"centered\": self.centered,\n })\n return config\n\n\nRMSProp = RMSprop\n",
"# 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\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import linalg_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops.linalg import linear_operator_util\nfrom tensorflow.python.platform import test\n\nrng = np.random.RandomState(0)\n\n\nclass AssertZeroImagPartTest(test.TestCase):\n\n @test_util.run_deprecated_v1\n def test_real_tensor_doesnt_raise(self):\n x = ops.convert_to_tensor([0., 2, 3])\n with self.cached_session():\n # Should not raise.\n linear_operator_util.assert_zero_imag_part(x, message=\"ABC123\").run()\n\n @test_util.run_deprecated_v1\n def test_complex_tensor_with_imag_zero_doesnt_raise(self):\n x = ops.convert_to_tensor([1., 0, 3])\n y = ops.convert_to_tensor([0., 0, 0])\n z = math_ops.complex(x, y)\n with self.cached_session():\n # Should not raise.\n linear_operator_util.assert_zero_imag_part(z, message=\"ABC123\").run()\n\n def test_complex_tensor_with_nonzero_imag_raises(self):\n x = ops.convert_to_tensor([1., 2, 0])\n y = ops.convert_to_tensor([1., 2, 0])\n z = math_ops.complex(x, y)\n with self.cached_session():\n with self.assertRaisesOpError(\"ABC123\"):\n linear_operator_util.assert_zero_imag_part(z, message=\"ABC123\").run()\n\n\nclass AssertNoEntriesWithModulusZeroTest(test.TestCase):\n\n @test_util.run_deprecated_v1\n def test_nonzero_real_tensor_doesnt_raise(self):\n x = ops.convert_to_tensor([1., 2, 3])\n with self.cached_session():\n # Should not raise.\n linear_operator_util.assert_no_entries_with_modulus_zero(\n x, message=\"ABC123\").run()\n\n @test_util.run_deprecated_v1\n def test_nonzero_complex_tensor_doesnt_raise(self):\n x = ops.convert_to_tensor([1., 0, 3])\n y = ops.convert_to_tensor([1., 2, 0])\n z = math_ops.complex(x, y)\n with self.cached_session():\n # Should not raise.\n linear_operator_util.assert_no_entries_with_modulus_zero(\n z, message=\"ABC123\").run()\n\n def test_zero_real_tensor_raises(self):\n x = ops.convert_to_tensor([1., 0, 3])\n with self.cached_session():\n with self.assertRaisesOpError(\"ABC123\"):\n linear_operator_util.assert_no_entries_with_modulus_zero(\n x, message=\"ABC123\").run()\n\n def test_zero_complex_tensor_raises(self):\n x = ops.convert_to_tensor([1., 2, 0])\n y = ops.convert_to_tensor([1., 2, 0])\n z = math_ops.complex(x, y)\n with self.cached_session():\n with self.assertRaisesOpError(\"ABC123\"):\n linear_operator_util.assert_no_entries_with_modulus_zero(\n z, message=\"ABC123\").run()\n\n\nclass BroadcastMatrixBatchDimsTest(test.TestCase):\n\n def test_zero_batch_matrices_returned_as_empty_list(self):\n self.assertAllEqual([],\n linear_operator_util.broadcast_matrix_batch_dims([]))\n\n def test_one_batch_matrix_returned_after_tensor_conversion(self):\n arr = rng.rand(2, 3, 4)\n tensor, = linear_operator_util.broadcast_matrix_batch_dims([arr])\n self.assertTrue(isinstance(tensor, ops.Tensor))\n\n with self.cached_session():\n self.assertAllClose(arr, self.evaluate(tensor))\n\n @test_util.run_deprecated_v1\n def test_static_dims_broadcast(self):\n # x.batch_shape = [3, 1, 2]\n # y.batch_shape = [4, 1]\n # broadcast batch shape = [3, 4, 2]\n x = rng.rand(3, 1, 2, 1, 5)\n y = rng.rand(4, 1, 3, 7)\n batch_of_zeros = np.zeros((3, 4, 2, 1, 1))\n x_bc_expected = x + batch_of_zeros\n y_bc_expected = y + batch_of_zeros\n\n x_bc, y_bc = linear_operator_util.broadcast_matrix_batch_dims([x, y])\n\n with self.cached_session() as sess:\n self.assertAllEqual(x_bc_expected.shape, x_bc.get_shape())\n self.assertAllEqual(y_bc_expected.shape, y_bc.get_shape())\n x_bc_, y_bc_ = self.evaluate([x_bc, y_bc])\n self.assertAllClose(x_bc_expected, x_bc_)\n self.assertAllClose(y_bc_expected, y_bc_)\n\n def test_static_dims_broadcast_second_arg_higher_rank(self):\n # x.batch_shape = [1, 2]\n # y.batch_shape = [1, 3, 1]\n # broadcast batch shape = [1, 3, 2]\n x = rng.rand(1, 2, 1, 5)\n y = rng.rand(1, 3, 2, 3, 7)\n batch_of_zeros = np.zeros((1, 3, 2, 1, 1))\n x_bc_expected = x + batch_of_zeros\n y_bc_expected = y + batch_of_zeros\n\n x_bc, y_bc = linear_operator_util.broadcast_matrix_batch_dims([x, y])\n\n with self.cached_session() as sess:\n self.assertAllEqual(x_bc_expected.shape, x_bc.get_shape())\n self.assertAllEqual(y_bc_expected.shape, y_bc.get_shape())\n x_bc_, y_bc_ = self.evaluate([x_bc, y_bc])\n self.assertAllClose(x_bc_expected, x_bc_)\n self.assertAllClose(y_bc_expected, y_bc_)\n\n @test_util.run_deprecated_v1\n def test_dynamic_dims_broadcast_32bit(self):\n # x.batch_shape = [3, 1, 2]\n # y.batch_shape = [4, 1]\n # broadcast batch shape = [3, 4, 2]\n x = rng.rand(3, 1, 2, 1, 5).astype(np.float32)\n y = rng.rand(4, 1, 3, 7).astype(np.float32)\n batch_of_zeros = np.zeros((3, 4, 2, 1, 1)).astype(np.float32)\n x_bc_expected = x + batch_of_zeros\n y_bc_expected = y + batch_of_zeros\n\n x_ph = array_ops.placeholder(dtypes.float32)\n y_ph = array_ops.placeholder(dtypes.float32)\n\n x_bc, y_bc = linear_operator_util.broadcast_matrix_batch_dims([x_ph, y_ph])\n\n with self.cached_session() as sess:\n x_bc_, y_bc_ = sess.run([x_bc, y_bc], feed_dict={x_ph: x, y_ph: y})\n self.assertAllClose(x_bc_expected, x_bc_)\n self.assertAllClose(y_bc_expected, y_bc_)\n\n @test_util.run_deprecated_v1\n def test_dynamic_dims_broadcast_32bit_second_arg_higher_rank(self):\n # x.batch_shape = [1, 2]\n # y.batch_shape = [3, 4, 1]\n # broadcast batch shape = [3, 4, 2]\n x = rng.rand(1, 2, 1, 5).astype(np.float32)\n y = rng.rand(3, 4, 1, 3, 7).astype(np.float32)\n batch_of_zeros = np.zeros((3, 4, 2, 1, 1)).astype(np.float32)\n x_bc_expected = x + batch_of_zeros\n y_bc_expected = y + batch_of_zeros\n\n x_ph = array_ops.placeholder(dtypes.float32)\n y_ph = array_ops.placeholder(dtypes.float32)\n\n x_bc, y_bc = linear_operator_util.broadcast_matrix_batch_dims([x_ph, y_ph])\n\n with self.cached_session() as sess:\n x_bc_, y_bc_ = sess.run([x_bc, y_bc], feed_dict={x_ph: x, y_ph: y})\n self.assertAllClose(x_bc_expected, x_bc_)\n self.assertAllClose(y_bc_expected, y_bc_)\n\n def test_less_than_two_dims_raises_static(self):\n x = rng.rand(3)\n y = rng.rand(1, 1)\n\n with self.assertRaisesRegexp(ValueError, \"at least two dimensions\"):\n linear_operator_util.broadcast_matrix_batch_dims([x, y])\n\n with self.assertRaisesRegexp(ValueError, \"at least two dimensions\"):\n linear_operator_util.broadcast_matrix_batch_dims([y, x])\n\n\nclass CholeskySolveWithBroadcastTest(test.TestCase):\n\n @test_util.run_deprecated_v1\n def test_static_dims_broadcast(self):\n # batch_shape = [2]\n chol = rng.rand(3, 3)\n rhs = rng.rand(2, 3, 7)\n chol_broadcast = chol + np.zeros((2, 1, 1))\n\n with self.cached_session():\n result = linear_operator_util.cholesky_solve_with_broadcast(chol, rhs)\n self.assertAllEqual((2, 3, 7), result.get_shape())\n expected = linalg_ops.cholesky_solve(chol_broadcast, rhs)\n self.assertAllClose(expected.eval(), self.evaluate(result))\n\n @test_util.run_deprecated_v1\n def test_dynamic_dims_broadcast_64bit(self):\n # batch_shape = [2, 2]\n chol = rng.rand(2, 3, 3)\n rhs = rng.rand(2, 1, 3, 7)\n chol_broadcast = chol + np.zeros((2, 2, 1, 1))\n rhs_broadcast = rhs + np.zeros((2, 2, 1, 1))\n\n chol_ph = array_ops.placeholder(dtypes.float64)\n rhs_ph = array_ops.placeholder(dtypes.float64)\n\n with self.cached_session() as sess:\n result, expected = sess.run(\n [\n linear_operator_util.cholesky_solve_with_broadcast(\n chol_ph, rhs_ph),\n linalg_ops.cholesky_solve(chol_broadcast, rhs_broadcast)\n ],\n feed_dict={\n chol_ph: chol,\n rhs_ph: rhs,\n })\n self.assertAllClose(expected, result)\n\n\nclass MatrixSolveWithBroadcastTest(test.TestCase):\n\n @test_util.run_deprecated_v1\n def test_static_dims_broadcast_matrix_has_extra_dims(self):\n # batch_shape = [2]\n matrix = rng.rand(2, 3, 3)\n rhs = rng.rand(3, 7)\n rhs_broadcast = rhs + np.zeros((2, 1, 1))\n\n with self.cached_session():\n result = linear_operator_util.matrix_solve_with_broadcast(\n matrix, rhs)\n self.assertAllEqual((2, 3, 7), result.get_shape())\n expected = linalg_ops.matrix_solve(matrix, rhs_broadcast)\n self.assertAllClose(expected.eval(), self.evaluate(result))\n\n @test_util.run_deprecated_v1\n def test_static_dims_broadcast_rhs_has_extra_dims(self):\n # Since the second arg has extra dims, and the domain dim of the first arg\n # is larger than the number of linear equations, code will \"flip\" the extra\n # dims of the first arg to the far right, making extra linear equations\n # (then call the matrix function, then flip back).\n # We have verified that this optimization indeed happens. How? We stepped\n # through with a debugger.\n # batch_shape = [2]\n matrix = rng.rand(3, 3)\n rhs = rng.rand(2, 3, 2)\n matrix_broadcast = matrix + np.zeros((2, 1, 1))\n\n with self.cached_session():\n result = linear_operator_util.matrix_solve_with_broadcast(matrix, rhs)\n self.assertAllEqual((2, 3, 2), result.get_shape())\n expected = linalg_ops.matrix_solve(matrix_broadcast, rhs)\n self.assertAllClose(expected.eval(), self.evaluate(result))\n\n @test_util.run_deprecated_v1\n def test_static_dims_broadcast_rhs_has_extra_dims_dynamic(self):\n # Since the second arg has extra dims, and the domain dim of the first arg\n # is larger than the number of linear equations, code will \"flip\" the extra\n # dims of the first arg to the far right, making extra linear equations\n # (then call the matrix function, then flip back).\n # We have verified that this optimization indeed happens. How? We stepped\n # through with a debugger.\n # batch_shape = [2]\n matrix = rng.rand(3, 3)\n rhs = rng.rand(2, 3, 2)\n matrix_broadcast = matrix + np.zeros((2, 1, 1))\n\n matrix_ph = array_ops.placeholder(dtypes.float64, shape=[None, None])\n rhs_ph = array_ops.placeholder(dtypes.float64, shape=[None, None, None])\n\n with self.cached_session():\n result = linear_operator_util.matrix_solve_with_broadcast(matrix_ph,\n rhs_ph)\n self.assertAllEqual(3, result.shape.ndims)\n expected = linalg_ops.matrix_solve(matrix_broadcast, rhs)\n self.assertAllClose(\n self.evaluate(expected),\n result.eval(feed_dict={\n matrix_ph: matrix,\n rhs_ph: rhs\n }))\n\n @test_util.run_deprecated_v1\n def test_static_dims_broadcast_rhs_has_extra_dims_and_adjoint(self):\n # Since the second arg has extra dims, and the domain dim of the first arg\n # is larger than the number of linear equations, code will \"flip\" the extra\n # dims of the first arg to the far right, making extra linear equations\n # (then call the matrix function, then flip back).\n # We have verified that this optimization indeed happens. How? We stepped\n # through with a debugger.\n # batch_shape = [2]\n matrix = rng.rand(3, 3)\n rhs = rng.rand(2, 3, 2)\n matrix_broadcast = matrix + np.zeros((2, 1, 1))\n\n with self.cached_session():\n result = linear_operator_util.matrix_solve_with_broadcast(\n matrix, rhs, adjoint=True)\n self.assertAllEqual((2, 3, 2), result.get_shape())\n expected = linalg_ops.matrix_solve(matrix_broadcast, rhs, adjoint=True)\n self.assertAllClose(expected.eval(), self.evaluate(result))\n\n @test_util.run_deprecated_v1\n def test_dynamic_dims_broadcast_64bit(self):\n # batch_shape = [2, 2]\n matrix = rng.rand(2, 3, 3)\n rhs = rng.rand(2, 1, 3, 7)\n matrix_broadcast = matrix + np.zeros((2, 2, 1, 1))\n rhs_broadcast = rhs + np.zeros((2, 2, 1, 1))\n\n matrix_ph = array_ops.placeholder(dtypes.float64)\n rhs_ph = array_ops.placeholder(dtypes.float64)\n\n with self.cached_session() as sess:\n result, expected = sess.run(\n [\n linear_operator_util.matrix_solve_with_broadcast(\n matrix_ph, rhs_ph),\n linalg_ops.matrix_solve(matrix_broadcast, rhs_broadcast)\n ],\n feed_dict={\n matrix_ph: matrix,\n rhs_ph: rhs,\n })\n self.assertAllClose(expected, result)\n\n\nclass MatrixTriangularSolveWithBroadcastTest(test.TestCase):\n\n @test_util.run_deprecated_v1\n def test_static_dims_broadcast_matrix_has_extra_dims(self):\n # batch_shape = [2]\n matrix = rng.rand(2, 3, 3)\n rhs = rng.rand(3, 7)\n rhs_broadcast = rhs + np.zeros((2, 1, 1))\n\n with self.cached_session():\n result = linear_operator_util.matrix_triangular_solve_with_broadcast(\n matrix, rhs)\n self.assertAllEqual((2, 3, 7), result.get_shape())\n expected = linalg_ops.matrix_triangular_solve(matrix, rhs_broadcast)\n self.assertAllClose(expected.eval(), self.evaluate(result))\n\n @test_util.run_deprecated_v1\n def test_static_dims_broadcast_rhs_has_extra_dims(self):\n # Since the second arg has extra dims, and the domain dim of the first arg\n # is larger than the number of linear equations, code will \"flip\" the extra\n # dims of the first arg to the far right, making extra linear equations\n # (then call the matrix function, then flip back).\n # We have verified that this optimization indeed happens. How? We stepped\n # through with a debugger.\n # batch_shape = [2]\n matrix = rng.rand(3, 3)\n rhs = rng.rand(2, 3, 2)\n matrix_broadcast = matrix + np.zeros((2, 1, 1))\n\n with self.cached_session():\n result = linear_operator_util.matrix_triangular_solve_with_broadcast(\n matrix, rhs)\n self.assertAllEqual((2, 3, 2), result.get_shape())\n expected = linalg_ops.matrix_triangular_solve(matrix_broadcast, rhs)\n self.assertAllClose(expected.eval(), self.evaluate(result))\n\n @test_util.run_deprecated_v1\n def test_static_dims_broadcast_rhs_has_extra_dims_and_adjoint(self):\n # Since the second arg has extra dims, and the domain dim of the first arg\n # is larger than the number of linear equations, code will \"flip\" the extra\n # dims of the first arg to the far right, making extra linear equations\n # (then call the matrix function, then flip back).\n # We have verified that this optimization indeed happens. How? We stepped\n # through with a debugger.\n # batch_shape = [2]\n matrix = rng.rand(3, 3)\n rhs = rng.rand(2, 3, 2)\n matrix_broadcast = matrix + np.zeros((2, 1, 1))\n\n with self.cached_session():\n result = linear_operator_util.matrix_triangular_solve_with_broadcast(\n matrix, rhs, adjoint=True)\n self.assertAllEqual((2, 3, 2), result.get_shape())\n expected = linalg_ops.matrix_triangular_solve(\n matrix_broadcast, rhs, adjoint=True)\n self.assertAllClose(expected.eval(), self.evaluate(result))\n\n @test_util.run_deprecated_v1\n def test_dynamic_dims_broadcast_64bit(self):\n # batch_shape = [2]\n matrix = rng.rand(2, 3, 3)\n rhs = rng.rand(3, 7)\n rhs_broadcast = rhs + np.zeros((2, 1, 1))\n\n matrix_ph = array_ops.placeholder(dtypes.float64)\n rhs_ph = array_ops.placeholder(dtypes.float64)\n\n with self.cached_session() as sess:\n result, expected = sess.run(\n [\n linear_operator_util.matrix_triangular_solve_with_broadcast(\n matrix_ph, rhs_ph),\n linalg_ops.matrix_triangular_solve(matrix, rhs_broadcast)\n ],\n feed_dict={\n matrix_ph: matrix,\n rhs_ph: rhs,\n })\n self.assertAllClose(expected, result)\n\n\nclass DomainDimensionStubOperator(object):\n\n def __init__(self, domain_dimension):\n self._domain_dimension = ops.convert_to_tensor(domain_dimension)\n\n def domain_dimension_tensor(self):\n return self._domain_dimension\n\n\nclass AssertCompatibleMatrixDimensionsTest(test.TestCase):\n\n @test_util.run_deprecated_v1\n def test_compatible_dimensions_do_not_raise(self):\n with self.cached_session():\n x = ops.convert_to_tensor(rng.rand(2, 3, 4))\n operator = DomainDimensionStubOperator(3)\n # Should not raise\n linear_operator_util.assert_compatible_matrix_dimensions(\n operator, x).run() # pyformat: disable\n\n def test_incompatible_dimensions_raise(self):\n with self.cached_session():\n x = ops.convert_to_tensor(rng.rand(2, 4, 4))\n operator = DomainDimensionStubOperator(3)\n with self.assertRaisesOpError(\"Incompatible matrix dimensions\"):\n linear_operator_util.assert_compatible_matrix_dimensions(\n operator, x).run() # pyformat: disable\n\n\nclass DummyOperatorWithHint(object):\n\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\n\n\nclass UseOperatorOrProvidedHintUnlessContradictingTest(test.TestCase,\n parameterized.TestCase):\n\n @parameterized.named_parameters(\n (\"none_none\", None, None, None),\n (\"none_true\", None, True, True),\n (\"true_none\", True, None, True),\n (\"true_true\", True, True, True),\n (\"none_false\", None, False, False),\n (\"false_none\", False, None, False),\n (\"false_false\", False, False, False),\n )\n def test_computes_an_or_if_non_contradicting(self, operator_hint_value,\n provided_hint_value,\n expected_result):\n self.assertEqual(\n expected_result,\n linear_operator_util.use_operator_or_provided_hint_unless_contradicting(\n operator=DummyOperatorWithHint(my_hint=operator_hint_value),\n hint_attr_name=\"my_hint\",\n provided_hint_value=provided_hint_value,\n message=\"should not be needed here\"))\n\n @parameterized.named_parameters(\n (\"true_false\", True, False),\n (\"false_true\", False, True),\n )\n def test_raises_if_contradicting(self, operator_hint_value,\n provided_hint_value):\n with self.assertRaisesRegexp(ValueError, \"my error message\"):\n linear_operator_util.use_operator_or_provided_hint_unless_contradicting(\n operator=DummyOperatorWithHint(my_hint=operator_hint_value),\n hint_attr_name=\"my_hint\",\n provided_hint_value=provided_hint_value,\n message=\"my error message\")\n\n\nif __name__ == \"__main__\":\n test.main()\n"
] |
[
[
"tensorflow.contrib.model_pruning.python.pruning.Pruning",
"tensorflow.contrib.model_pruning.python.pruning.get_weight_sparsity",
"tensorflow.python.training.training_util.get_or_create_global_step",
"tensorflow.python.ops.math_ops.linspace",
"tensorflow.python.ops.state_ops.assign_add",
"tensorflow.python.ops.variable_scope.get_variable_scope",
"tensorflow.contrib.model_pruning.python.pruning.apply_mask",
"tensorflow.python.ops.variables.VariableV1",
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.variable_scope.variable_scope",
"tensorflow.python.ops.random_ops.random_normal",
"numpy.count_nonzero",
"tensorflow.contrib.model_pruning.python.pruning.get_pruning_hparams",
"tensorflow.python.ops.variables.global_variables_initializer",
"tensorflow.python.ops.state_ops.assign",
"tensorflow.python.ops.partitioned_variables.variable_axis_size_partitioner",
"tensorflow.python.framework.constant_op.constant"
],
[
"tensorflow.python.training.training_ops.resource_apply_ftrl",
"tensorflow.python.util.tf_export.keras_export",
"tensorflow.python.training.training_ops.resource_sparse_apply_ftrl",
"tensorflow.python.ops.init_ops.constant_initializer",
"tensorflow.python.ops.math_ops.cast"
],
[
"tensorflow.python.util.tf_export.keras_export"
],
[
"tensorflow.python.training.training_ops.resource_sparse_apply_centered_rms_prop",
"tensorflow.python.ops.control_flow_ops.group",
"tensorflow.python.ops.math_ops.square",
"tensorflow.python.util.tf_export.keras_export",
"tensorflow.python.training.training_ops.resource_sparse_apply_rms_prop",
"tensorflow.python.training.training_ops.resource_apply_rms_prop",
"tensorflow.python.ops.array_ops.gather",
"tensorflow.python.training.training_ops.resource_apply_centered_rms_prop",
"tensorflow.python.ops.math_ops.sqrt",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.ops.state_ops.assign",
"tensorflow.python.keras.backend_config.epsilon",
"tensorflow.python.framework.ops.control_dependencies",
"numpy.array"
],
[
"tensorflow.python.ops.linalg.linear_operator_util.cholesky_solve_with_broadcast",
"tensorflow.python.ops.linalg.linear_operator_util.matrix_solve_with_broadcast",
"tensorflow.python.ops.linalg_ops.matrix_solve",
"tensorflow.python.ops.linalg.linear_operator_util.assert_zero_imag_part",
"tensorflow.python.ops.math_ops.complex",
"tensorflow.python.ops.linalg.linear_operator_util.matrix_triangular_solve_with_broadcast",
"tensorflow.python.ops.linalg.linear_operator_util.broadcast_matrix_batch_dims",
"tensorflow.python.ops.array_ops.placeholder",
"tensorflow.python.ops.linalg.linear_operator_util.assert_no_entries_with_modulus_zero",
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.linalg_ops.matrix_triangular_solve",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.ops.linalg.linear_operator_util.assert_compatible_matrix_dimensions",
"tensorflow.python.ops.linalg_ops.cholesky_solve",
"numpy.random.RandomState",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.13",
"1.12"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"1.4",
"1.13",
"2.3",
"2.4",
"2.2",
"2.9",
"1.5",
"1.7",
"2.5",
"1.0",
"2.8",
"1.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.2",
"2.3",
"2.4",
"2.9",
"2.5",
"2.8",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.13",
"1.10",
"1.12"
]
}
] |
wbkang/rpi-repo
|
[
"fc2b770f99cc2405fbf6855f9f961c4f6aed99cb"
] |
[
"rpiweather/server.py"
] |
[
"#!/usr/bin/env python3\n\nimport RPi.GPIO as GPIO\nimport time\nimport threading\nimport logging\nimport pandas as pd\nimport numpy as np\nfrom tzlocal import get_localzone\nfrom flask import Flask, render_template, url_for, request\n\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s - %(threadName)s - %(name)s - %(levelname)s - %(message)s')\nGPIO.setmode(GPIO.BCM)\nlogger = logging.getLogger(__name__)\n\nfrom rpiweather import temphumid\nfrom rpiweather import temppressure\nfrom rpiweather import data\nfrom rpiweather import outside_weather\nfrom rpiweather import dust\n\ntemppressure.start_recording()\ntemphumid.start_recording()\noutside_weather.start_recording()\ndust.start_recording()\n\napp = Flask(\"rpiweather\")\n\n\ndef format_timestamps(series):\n local_tz = get_localzone()\n return list(\n str(dt.tz_localize(\"UTC\").tz_convert(local_tz)) for dt in series\n )\n\n\[email protected](\"/\")\ndef index():\n lookbehind = int(request.args.get('lookbehind', 24))\n\n bigarray = data.get_recent_datapoints(lookbehind)\n logger.info(\"Total datapoint count: %d\" % len(bigarray))\n df = pd.DataFrame(bigarray, columns=['time', 'type', 'value'])\n df['time'] = pd.to_datetime(df['time'])\n df = df.set_index('time')\n agg_interval = \"15T\" if lookbehind < 168 else \"1H\" if lookbehind < 5040 else \"1D\"\n df2 = df.pivot(columns='type', values='value').resample(agg_interval).mean()\n\n temp_df = df2['temperature'].dropna()\n temp_values = {\n 'x': format_timestamps(temp_df.index),\n 'y': list(temp_df),\n 'name': 'Temperature',\n 'type': 'line',\n 'line': {\n 'color': 'rgb(244, 66, 98)'\n }\n }\n\n outside_temp_df = df2['outside_temperature'].dropna()\n ot_values = {\n 'x': format_timestamps(outside_temp_df.index),\n 'y': list(outside_temp_df),\n 'name': 'Temperature Outside',\n 'type': 'line',\n 'line': {\n 'color': 'rgb(244, 66, 98)',\n 'dash': 'longdash'\n }\n }\n\n pres_df = df2['pressure'].dropna()\n pressure_values = {\n 'x': format_timestamps(pres_df.index),\n 'y': list(pres_df),\n 'name': 'Pressure',\n 'type': 'line',\n 'yaxis': 'y2',\n 'line': {\n 'dash': 'dot',\n 'color': 'rgb(151,138,155)'\n }\n }\n hum_df = df2['humidity'].dropna()\n humidity_values = {\n 'x': format_timestamps(hum_df.index),\n 'y': list(hum_df),\n 'name': 'Humidity',\n 'type': 'scatter',\n 'fill': 'tozeroy',\n 'yaxis': 'y3',\n 'marker': {\n 'color': 'rgb(66,131,244)'\n }\n }\n dust_df = df2['dust'].dropna()\n dust_values = {\n 'x': format_timestamps(dust_df.index),\n 'y': list(dust_df),\n 'name': 'Dust level',\n 'type': 'line',\n 'yaxis': 'y4',\n 'line': {\n 'dash': 'dot',\n 'color': 'rgb(224, 205, 31)'\n }\n }\n\n chart_data = [\n temp_values, pressure_values, humidity_values, ot_values, dust_values\n ]\n\n #import pdb; pdb.set_trace()\n lookbehind_options = [(24, \"1d\"),\n (24*7, \"1w\"),\n (24*7*30, \"30d\")]\n return render_template(\"index.html\",\n weather_data=chart_data,\n lookbehind_options=lookbehind_options,\n lookbehind=lookbehind)\n\n\ndef make_agg_df(rec):\n df = pd.DataFrame.from_records(rec, index=\"time\")\n df.index = pd.to_datetime(df.index, unit=\"s\")\n return df.resample(\"T\").mean()\n\n\ndef magic():\n df_tp = make_agg_df(temppressure.get_records())\n df_th = make_agg_df(temphumid.get_records())\n df_th = df_th.rename(columns={'temp': 'bad_temp'})\n total_view = pd.concat([df_tp, df_th], axis=1)\n return total_view\n\n\n#import IPython\n# IPython.embed()\nif False:\n bigarray = data.get_recent_datapoints()\n df = pd.DataFrame(bigarray, columns=['time', 'type', 'value'])\n df['time'] = pd.to_datetime(df['time'])\n df = df.set_index('time')\n df2 = df.pivot(columns='type', values='value').resample(\"5T\").mean()\n\n temp_values = list(zip(\n (dt.timestamp() for dt in df2.index),\n df2['temperature']\n ))\n pressure_values = list(zip(\n (dt.timestamp() for dt in df2.index),\n df2['pressure']\n ))\n humidity_values = list(zip(\n (dt.timestamp() for dt in df2.index),\n df2['humidity']\n ))\n"
] |
[
[
"pandas.DataFrame.from_records",
"pandas.concat",
"pandas.to_datetime",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
vg2691994/mock_frb_injection_results
|
[
"a4747e5ef38ed2171af22e40816bf75afc7e192d"
] |
[
"helpers.py"
] |
[
"#!/home/observer/miniconda2/bin/python\n\nimport numpy as N\nimport sys, os\nimport logging as L\nimport subprocess as S\nfrom collections import namedtuple\nfrom sigpyproc.Readers import FilReader as F\nsys.path.append(\"/home/vgupta/Codes/Fake_FRBs/\")\nfrom Furby_reader import Furby_reader\n\nclass FileNotFound(Exception):\n pass\n\nclass Observation():\n def __init__(self, utc, cfg_file = \"/home/vgupta/resources/observations.cfg\"):\n self.utc = utc\n self.cfg_file = cfg_file\n self.read_conf()\n self.get_results_dir()\n self.get_archives_dir()\n self.is_failed = self.if_failed()\n self.read_info()\n self.processed_offline()\n self.annotation = self.read_annotation()\n\n def __str__(self):\n return self.utc\n\n def __repr__(self):\n return self.utc\n\n def read_annotation(self):\n afile = os.path.join(self.results_dir, \"obs.txt\")\n if not os.path.exists(afile):\n return None\n with open(afile, 'r') as f:\n return f.read()\n\n def read_conf(self):\n if not os.path.exists(self.cfg_file):\n raise Exception(\"Cannot find observation configuration file - {0}\".format(self.cfg_file))\n #raise FileNotFound(\"Cannot find observation configuration file - {0}\".format(self.cfg_file))\n conf_tmp = {}\n with open(self.cfg_file) as c:\n lines = c.readlines()\n\n for line in lines:\n if (line.startswith(\"#\") or line == \"\" or line == \"\\n\"):\n continue\n key = line.strip().split()[0].strip()\n val = line.strip().split()[1].strip()\n val = self.check_type(val)\n conf_tmp[key] = val\n\n tmp = namedtuple(\"CONF\", conf_tmp.keys())\n self.conf = tmp(*conf_tmp.values()) \n\n def get_results_dir(self):\n path1 = os.path.join(self.conf.results_dir, self.utc)\n path2 = os.path.join(self.conf.old_results_dir, self.utc)\n if os.path.isdir(path1):\n self.results_dir = self.conf.results_dir\n elif os.path.isdir(path2):\n self.results_dir = self.conf.old_results_dir\n else:\n raise IOError(\"Directory for UTC: {0} does not exist in any of the new or old results. Neither {1} nor {2} exists\".format(self.utc, path1, path2))\n\n def get_archives_dir(self):\n path1 = os.path.join(self.conf.archives_dir, self.utc)\n path2 = os.path.join(self.conf.old_archives_dir, self.utc)\n if os.path.isdir(path1):\n self.archives_dir = self.conf.archives_dir\n elif os.path.isdir(path2):\n self.archives_dir = self.conf.old_archives_dir\n else:\n raise IOError(\"Directory for UTC: {0} does not exist in any of the new or old archives\".format(self.utc))\n\n def processed_offline(self):\n self.offline_cand_file = os.path.join(self.archives_dir, self.utc, self.conf.offline_output_dir, self.conf.offline_output_file)\n self.processed_offline = os.path.exists(self.offline_cand_file) and not self.is_failed\n \n def read_header(self):\n if self.is_failed:\n self.header = None\n return\n self.header_file = os.path.join(self.results_dir, self.utc, \"FB\", self.conf.header_file)\n if not os.path.exists(self.header_file):\n raise Exception(\"Header file({0}) does not exist\".format(self.header_file))\n\n with open(self.header_file) as h:\n lines = h.readlines()\n \n hdr_tmp = {} \n for line in lines:\n key = line.split()[0].strip()\n val = line.split()[1].strip()\n cval = self.check_type(val)\n if key.startswith(\"FURBY\"):\n cval = str(val)\n hdr_tmp[key] = cval\n \n keys = hdr_tmp.keys()\n values = hdr_tmp.values()\n tmp = namedtuple(\"HEADER\", keys)\n self.header = tmp(*values)\n self.tres = self.header.TSAMP * 1e-6\n \n return self.header\n\n def read_info(self):\n self.obs_info_file = os.path.join(self.results_dir, self.utc, \"obs.info\")\n if not os.path.exists(self.obs_info_file):\n raise Exception(\"obs.info file({0}) does not exist\".format(self.obs_info_file))\n \n with open(self.obs_info_file) as h:\n lines = h.readlines()\n \n hdr_tmp = {} \n for line in lines:\n if line.startswith(\"#\") or line == \"\" or line == \"\\n\":\n continue\n key = line.split()[0].strip()\n val = line.split()[1].strip()\n val = self.check_type(val)\n hdr_tmp[key] = val\n if key==\"INT\" and self.is_failed:\n val = 0\n \n keys = hdr_tmp.keys()\n values = hdr_tmp.values()\n tmp = namedtuple(\"INFO\", keys)\n self.info = tmp(*values)\n #Getting Tobs-----------------\n filterbank_name = self.utc + \".fil\"\n filterbank_file = os.path.join(self.archives_dir, self.utc, \"FB/BEAM_001/\", filterbank_name)\n if os.path.exists(filterbank_file):\n filt_header = F(filterbank_file).header\n self.tobs = filt_header.tobs\n if self.info.INT > self.tobs:\n self.tobs = self.info.INT\n else:\n self.tobs = self.info.INT\n #-----------------------------\n return self.info\n \n def check_type(self, val):\n try:\n ans=int(val)\n return ans\n except ValueError:\n try: \n ans=float(val)\n return ans\n except ValueError:\n if val.lower()==\"false\":\n return False\n elif val.lower()==\"true\": \n return True\n else:\n return val\n\n def if_processing(self):\n processing_file = os.path.join(self.results_dir, self.utc, \"obs.processing\")\n return os.path.exists(processing_file)\n\n def if_failed(self):\n obs_failed_file = os.path.join(self.results_dir, self.utc, \"obs.failed\")\n return os.path.exists(obs_failed_file)\n\n def read_furby_params(self):\n if self.is_failed:\n self.inj_furbys = -1\n return\n if (self.info.MB_ENABLED or self.info.CORR_ENABLED):\n self.inj_furbys = -1\n else:\n self.read_header()\n try:\n\n self.inj_furbys = self.header.INJECTED_FURBYS\n\n except AttributeError as e:\n\n #log.warn(\"Could not find INJECTED_FURBYS in the header file for UTC: {0}\".format(self.utc))\n #log.warn(\"Assuming no furby injection happened in this observation ({0})\".format(self.utc))\n self.inj_furbys = 0\n\n else:\n if self.inj_furbys > 0:\n self.furby_beams = self.header.FURBY_BEAMS.strip(\",\")\n self.furby_ids = self.header.FURBY_IDS.strip(\",\")\n self.furby_tstamps = self.header.FURBY_TSTAMPS.strip(\",\")\n\n #log.debug(\"Found: injected_furbys: {0}, furby_ids: {1}, furby_beams: {2}, furby_tstamps: {3}\".format(self.inj_furbys, self.furby_ids, self.furby_beams, self.furby_tstamps))\n\n def split_and_filter_furby_params(self):\n if self.inj_furbys < 1:\n raise ValueError(\"No furbies to split\")\n\n f_ids = N.array(self.furby_ids.split(\",\"))\n f_beams = N.array(self.furby_beams.split(\",\"))\n f_tstamps = N.array(self.furby_tstamps.split(\",\"))\n \n f_ids = f_ids[N.where(f_ids!='')]\n f_beams = f_beams[N.where(f_beams!='')]\n f_tstamps = f_tstamps[N.where(f_tstamps!='')]\n \n test = N.array([len(f_ids), len(f_beams), len(f_tstamps)])\n if N.any(test-self.inj_furbys):\n raise ValueError(\"Incorrect number of furby params, observation should have failed\")\n \n self.furbies = []\n self.dropped_furbies = []\n for i in range(self.inj_furbys):\n furby = Furby(f_ids[i], db = os.path.join(self.archives_dir, self.utc, \"Furbys\"))\n furby.i_beam = int(f_beams[i])\n furby.i_tstamp = float(f_tstamps[i])\n furby.calc_times()\n \n if (self.check_if_dropped(furby)):\n self.dropped_furbies.append(furby)\n else:\n self.furbies.append(furby)\n\n def check_if_dropped(self, furby):\n if not hasattr(furby, 'header'):\n furby.read_fheader()\n if not hasattr(furby, 'length'):\n furby.calc_times()\n\n if furby.i_tstamp < furby.length/2:\n return True\n if (furby.i_tstamp - furby.length/2) > self.tobs:\n return True\n \n all_furby_tstamps = N.array([float(i.i_tstamp) for i in self.furbies])\n diff = furby.i_tstamp - all_furby_tstamps\n if N.any((diff < (furby.length + 512*self.tres)) & (diff > 0)):\n return True\n\n return False\n\n\n#----------------------------------------------------------------------------------------#\n\n\nclass Furby(Furby_reader):\n def __init__(self, ID, db = \"/home/dada/furby_database\"):\n self.ID = ID\n self.name = \"furby_\"+ID\n self.DB = db\n self.file = os.path.join(self.DB, self.name)\n self.i_beam = None\n self.i_tstamp = None\n self.i_snr = None\n\n def __repr__(self):\n return str(self.ID)\n\n def read_fheader(self):\n #self.header = self.read_header(self.file)\n self.read_header(self.file)\n\n def calc_times(self):\n log = L.getLogger(\"furby_manager\")\n if not hasattr(self, 'header'):\n self.read_fheader()\n chw = (self.header.FTOP - self.header.FBOTTOM) / self.header.NCHAN\n f_chtop = self.header.FTOP - chw/2\n f_chmid = f_chtop - (self.header.NCHAN/2 * chw)\n f_chbottom = self.header.FBOTTOM + chw/2\n\n delay_to_top = 4.14881 * 1e6 * self.header.DM * ( f_chtop**(-2) - f_chmid**(-2) ) *1e-3 #in s\n delay_to_bottom = 4.14881 * 1e6 * self.header.DM * ( f_chbottom**(-2) - f_chmid**(-2) ) *1e-3 #in s\n\n self.s_time = self.i_tstamp + delay_to_top\n self.e_time = self.i_tstamp + delay_to_bottom\n self.c_time = self.i_tstamp\n\n self.length = self.header.NSAMPS * self.header.TSAMP * 1e-6\n\n#---------------------------------------------------------------------------------------#\n\ndef list_UTCs_from(start_utc):\n #Note to someone editing this in future: Keep in mind that other scripts depend upon that fact that this function returns the list of UTCs in correctly sorted order. Do not change that, even if that costs speed. Or make sure that the scripts using this can be edited accordingly.\n start = Observation(start_utc)\n cmd = \"ls -1d \"+start.results_dir+\"/202* | grep -A 999999 \"+start_utc+\" | awk -F/ '{print $5}'\"\n utcs = S.Popen(cmd, shell=True, stdout=S.PIPE).communicate()[0].strip().split(\"\\n\")\n\n #VG: 02/05/2020 -- disabling the section below -- It doesn't work, and I don't have a quick fix either. \n '''\n if start.results_dir == start.conf.old_results_dir:\n #Also append utcs from the new results directory\n cmd = \"ls -1d \"+conf.results_dir+\"/20* | grep -A 999999 \"+start_utc+\" | awk -F/ '{print $5}'\"\n utcs.extend(S.Popen(cmd, shell=True, stdout=S.PIPE).communicate()[0].strip().split(\"\\n\"))\n '''\n if len(utcs) == 0:\n raise Exception(\"Given start UTC ({}) not found in {}\".format(start_utc, start.results_dir))\n\n return utcs\n\ndef list_UTCs_until(utc):\n check = Observation(utc)\n \n start_utc = get_first_UTC()\n UTCs_from_start = list_UTCs_from(start_utc)\n #Assume that list_UTCs_from() returns UTCs sorted in correct order, which it should.\n end_utc = utc\n index = N.where(UTCs_from_start == end_utc)[0]\n UTCs_until = UTCs_from_start[:index+1]\n return UTCs_until\n \ndef list_UTCs_after(utc):\n inclusive_utcs = list_UTCS_from(utc)\n return inclusive_utcs[1:]\n\ndef get_latest_UTC():\n cmd = \"ls -1d -rt \"+conf.results_dir+\"/20* | tail -1 | awk -F/ '{print $5}'\"\n utc = S.Popen(cmd, shell=True, stdout=S.PIPE).communcate()[0].strip()\n return utc\n\ndef get_first_UTC():\n '''\n Returns the first UTC recorded by Molonglo after the disk crash in October 2017\n '''\n return \"2017-10-31-08:49:32\"\n"
] |
[
[
"numpy.where",
"numpy.any"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
DagothHertil/NNVEP-SRN-Deblur
|
[
"c092fec78dfe73ce6247a56f1e16ab4f4576d6b0"
] |
[
"models/model.py"
] |
[
"from __future__ import print_function\nimport os\nimport time\nimport random\nimport datetime\nimport scipy.misc\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\nfrom datetime import datetime\nfrom util.util import *\nfrom util.BasicConvLSTMCell import *\n\n\nclass DEBLUR(object):\n def __init__(self, args):\n self.args = args\n self.n_levels = 3\n self.scale = 0.5\n self.chns = 3 if self.args.model == 'color' else 1 # input / output channels\n\n # if args.phase == 'train':\n self.crop_size = 256\n self.data_list = open(args.datalist, 'rt').read().splitlines()\n self.data_list = list(map(lambda x: x.split(' '), self.data_list))\n random.shuffle(self.data_list)\n self.train_dir = os.path.join('./checkpoints', args.model)\n if not os.path.exists(self.train_dir):\n os.makedirs(self.train_dir)\n\n self.batch_size = args.batch_size\n self.epoch = args.epoch\n self.data_size = (len(self.data_list)) // self.batch_size\n self.max_steps = int(self.epoch * self.data_size)\n self.learning_rate = args.learning_rate\n\n def input_producer(self, batch_size=10):\n def read_data():\n img_a = tf.image.decode_image(tf.read_file(tf.string_join(['./training_set/', self.data_queue[0]])),\n channels=3)\n img_b = tf.image.decode_image(tf.read_file(tf.string_join(['./training_set/', self.data_queue[1]])),\n channels=3)\n img_a, img_b = preprocessing([img_a, img_b])\n return img_a, img_b\n\n def preprocessing(imgs):\n imgs = [tf.cast(img, tf.float32) / 255.0 for img in imgs]\n if self.args.model != 'color':\n imgs = [tf.image.rgb_to_grayscale(img) for img in imgs]\n img_crop = tf.unstack(tf.random_crop(tf.stack(imgs, axis=0), [2, self.crop_size, self.crop_size, self.chns]),\n axis=0)\n return img_crop\n\n with tf.variable_scope('input'):\n List_all = tf.convert_to_tensor(self.data_list, dtype=tf.string)\n gt_list = List_all[:, 0]\n in_list = List_all[:, 1]\n\n self.data_queue = tf.train.slice_input_producer([in_list, gt_list], capacity=20)\n image_in, image_gt = read_data()\n batch_in, batch_gt = tf.train.batch([image_in, image_gt], batch_size=batch_size, num_threads=8, capacity=20)\n\n return batch_in, batch_gt\n\n def generator(self, inputs, reuse=False, scope='g_net'):\n n, h, w, c = inputs.get_shape().as_list()\n\n if self.args.model == 'lstm':\n with tf.variable_scope('LSTM'):\n cell = BasicConvLSTMCell([h / 4, w / 4], [3, 3], 128)\n rnn_state = cell.zero_state(batch_size=self.batch_size, dtype=tf.float32)\n\n x_unwrap = []\n with tf.variable_scope(scope, reuse=reuse):\n with slim.arg_scope([slim.conv2d, slim.conv2d_transpose],\n activation_fn=tf.nn.relu, padding='SAME', normalizer_fn=None,\n weights_initializer=tf.contrib.layers.xavier_initializer(uniform=True),\n biases_initializer=tf.constant_initializer(0.0)):\n\n inp_pred = inputs\n for i in xrange(self.n_levels):\n scale = self.scale ** (self.n_levels - i - 1)\n hi = int(round(h * scale))\n wi = int(round(w * scale))\n inp_blur = tf.image.resize_images(inputs, [hi, wi], method=0)\n inp_pred = tf.stop_gradient(tf.image.resize_images(inp_pred, [hi, wi], method=0))\n inp_all = tf.concat([inp_blur, inp_pred], axis=3, name='inp')\n if self.args.model == 'lstm':\n rnn_state = tf.image.resize_images(rnn_state, [hi // 4, wi // 4], method=0)\n\n # encoder\n conv1_1 = slim.conv2d(inp_all, 32, [5, 5], scope='enc1_1')\n conv1_2 = ResnetBlock(conv1_1, 32, 5, scope='enc1_2')\n conv1_3 = ResnetBlock(conv1_2, 32, 5, scope='enc1_3')\n conv1_4 = ResnetBlock(conv1_3, 32, 5, scope='enc1_4')\n conv2_1 = slim.conv2d(conv1_4, 64, [5, 5], stride=2, scope='enc2_1')\n conv2_2 = ResnetBlock(conv2_1, 64, 5, scope='enc2_2')\n conv2_3 = ResnetBlock(conv2_2, 64, 5, scope='enc2_3')\n conv2_4 = ResnetBlock(conv2_3, 64, 5, scope='enc2_4')\n conv3_1 = slim.conv2d(conv2_4, 128, [5, 5], stride=2, scope='enc3_1')\n conv3_2 = ResnetBlock(conv3_1, 128, 5, scope='enc3_2')\n conv3_3 = ResnetBlock(conv3_2, 128, 5, scope='enc3_3')\n conv3_4 = ResnetBlock(conv3_3, 128, 5, scope='enc3_4')\n\n if self.args.model == 'lstm':\n deconv3_4, rnn_state = cell(conv3_4, rnn_state)\n else:\n deconv3_4 = conv3_4\n\n # decoder\n deconv3_3 = ResnetBlock(deconv3_4, 128, 5, scope='dec3_3')\n deconv3_2 = ResnetBlock(deconv3_3, 128, 5, scope='dec3_2')\n deconv3_1 = ResnetBlock(deconv3_2, 128, 5, scope='dec3_1')\n deconv2_4 = slim.conv2d_transpose(deconv3_1, 64, [4, 4], stride=2, scope='dec2_4')\n cat2 = deconv2_4 + conv2_4\n deconv2_3 = ResnetBlock(cat2, 64, 5, scope='dec2_3')\n deconv2_2 = ResnetBlock(deconv2_3, 64, 5, scope='dec2_2')\n deconv2_1 = ResnetBlock(deconv2_2, 64, 5, scope='dec2_1')\n deconv1_4 = slim.conv2d_transpose(deconv2_1, 32, [4, 4], stride=2, scope='dec1_4')\n cat1 = deconv1_4 + conv1_4\n deconv1_3 = ResnetBlock(cat1, 32, 5, scope='dec1_3')\n deconv1_2 = ResnetBlock(deconv1_3, 32, 5, scope='dec1_2')\n deconv1_1 = ResnetBlock(deconv1_2, 32, 5, scope='dec1_1')\n inp_pred = slim.conv2d(deconv1_1, self.chns, [5, 5], activation_fn=None, scope='dec1_0')\n\n if i >= 0:\n x_unwrap.append(inp_pred)\n if i == 0:\n tf.get_variable_scope().reuse_variables()\n\n return x_unwrap\n\n def build_model(self):\n img_in, img_gt = self.input_producer(self.batch_size)\n\n tf.summary.image('img_in', im2uint8(img_in))\n tf.summary.image('img_gt', im2uint8(img_gt))\n print('img_in, img_gt', img_in.get_shape(), img_gt.get_shape())\n\n # generator\n x_unwrap = self.generator(img_in, reuse=False, scope='g_net')\n # calculate multi-scale loss\n self.loss_total = 0\n for i in xrange(self.n_levels):\n _, hi, wi, _ = x_unwrap[i].get_shape().as_list()\n gt_i = tf.image.resize_images(img_gt, [hi, wi], method=0)\n loss = tf.reduce_mean((gt_i - x_unwrap[i]) ** 2)\n self.loss_total += loss\n\n tf.summary.image('out_' + str(i), im2uint8(x_unwrap[i]))\n tf.summary.scalar('loss_' + str(i), loss)\n\n # losses\n tf.summary.scalar('loss_total', self.loss_total)\n\n # training vars\n all_vars = tf.trainable_variables()\n self.all_vars = all_vars\n self.g_vars = [var for var in all_vars if 'g_net' in var.name]\n self.lstm_vars = [var for var in all_vars if 'LSTM' in var.name]\n for var in all_vars:\n print(var.name)\n\n def train(self):\n def get_optimizer(loss, global_step=None, var_list=None, is_gradient_clip=False):\n train_op = tf.train.AdamOptimizer(self.lr)\n if is_gradient_clip:\n grads_and_vars = train_op.compute_gradients(loss, var_list=var_list)\n unchanged_gvs = [(grad, var) for grad, var in grads_and_vars if not 'LSTM' in var.name]\n rnn_grad = [grad for grad, var in grads_and_vars if 'LSTM' in var.name]\n rnn_var = [var for grad, var in grads_and_vars if 'LSTM' in var.name]\n capped_grad, _ = tf.clip_by_global_norm(rnn_grad, clip_norm=3)\n capped_gvs = list(zip(capped_grad, rnn_var))\n train_op = train_op.apply_gradients(grads_and_vars=capped_gvs + unchanged_gvs, global_step=global_step)\n else:\n train_op = train_op.minimize(loss, global_step, var_list)\n return train_op\n\n global_step = tf.Variable(initial_value=0, dtype=tf.int32, trainable=False)\n self.global_step = global_step\n\n # build model\n self.build_model()\n\n # learning rate decay\n self.lr = tf.train.polynomial_decay(self.learning_rate, global_step, self.max_steps, end_learning_rate=0.0,\n power=0.3)\n tf.summary.scalar('learning_rate', self.lr)\n\n # training operators\n train_gnet = get_optimizer(self.loss_total, global_step, self.all_vars)\n\n # session and thread\n gpu_options = tf.GPUOptions(allow_growth=True)\n sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\n self.sess = sess\n sess.run(tf.global_variables_initializer())\n self.saver = tf.train.Saver(max_to_keep=50, keep_checkpoint_every_n_hours=1)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n\n # training summary\n summary_op = tf.summary.merge_all()\n summary_writer = tf.summary.FileWriter(self.train_dir, sess.graph, flush_secs=30)\n\n for step in xrange(sess.run(global_step), self.max_steps + 1):\n\n start_time = time.time()\n\n # update G network\n _, loss_total_val = sess.run([train_gnet, self.loss_total])\n\n duration = time.time() - start_time\n # print loss_value\n assert not np.isnan(loss_total_val), 'Model diverged with loss = NaN'\n\n if step % 5 == 0:\n num_examples_per_step = self.batch_size\n examples_per_sec = num_examples_per_step / duration\n sec_per_batch = float(duration)\n\n format_str = ('%s: step %d, loss = (%.5f; %.5f, %.5f)(%.1f data/s; %.3f s/bch)')\n print(format_str % (datetime.now().strftime('%Y-%m-%d %H:%M:%S'), step, loss_total_val, 0.0,\n 0.0, examples_per_sec, sec_per_batch))\n\n if step % 20 == 0:\n # summary_str = sess.run(summary_op, feed_dict={inputs:batch_input, gt:batch_gt})\n summary_str = sess.run(summary_op)\n summary_writer.add_summary(summary_str, global_step=step)\n\n # Save the model checkpoint periodically.\n if step % 1000 == 0 or step == self.max_steps:\n checkpoint_path = os.path.join(self.train_dir, 'checkpoints')\n self.save(sess, checkpoint_path, step)\n\n def save(self, sess, checkpoint_dir, step):\n model_name = \"deblur.model\"\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n self.saver.save(sess, os.path.join(checkpoint_dir, model_name), global_step=step)\n\n def load(self, sess, checkpoint_dir, step=None):\n print(\" [*] Reading checkpoints...\")\n model_name = \"deblur.model\"\n ckpt = tf.train.get_checkpoint_state(checkpoint_dir)\n\n if step is not None:\n ckpt_name = model_name + '-' + str(step)\n self.saver.restore(sess, os.path.join(checkpoint_dir, ckpt_name))\n print(\" [*] Reading intermediate checkpoints... Success\")\n return str(step)\n elif ckpt and ckpt.model_checkpoint_path:\n ckpt_name = os.path.basename(ckpt.model_checkpoint_path)\n ckpt_iter = ckpt_name.split('-')[1]\n self.saver.restore(sess, os.path.join(checkpoint_dir, ckpt_name))\n print(\" [*] Reading updated checkpoints... Success\")\n return ckpt_iter\n else:\n print(\" [*] Reading checkpoints... ERROR\")\n return False\n\n def test(self, height, width, input_path, output_path):\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n imgsName = sorted(os.listdir(input_path))\n H, W = height, width\n inp_chns = 3 if self.args.model == 'color' else 1\n self.batch_size = 1 if self.args.model == 'color' else 3\n inputs = tf.placeholder(shape=[self.batch_size, H, W, inp_chns], dtype=tf.float32)\n outputs = self.generator(inputs, reuse=False)\n\n sess = tf.Session(config=tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True)))\n\n self.saver = tf.train.Saver()\n self.load(sess, self.train_dir, step=523000)\n\n for imgName in imgsName:\n blur = scipy.misc.imread(os.path.join(input_path, imgName))\n h, w, c = blur.shape\n # make sure the width is larger than the height\n rot = False\n if h > w:\n blur = np.transpose(blur, [1, 0, 2])\n rot = True\n h = int(blur.shape[0])\n w = int(blur.shape[1])\n resize = False\n if h > H or w > W:\n scale = min(1.0 * H / h, 1.0 * W / w)\n new_h = int(h * scale)\n new_w = int(w * scale)\n blur = scipy.misc.imresize(blur, [new_h, new_w], 'bicubic')\n resize = True\n blurPad = np.pad(blur, ((0, H - new_h), (0, W - new_w), (0, 0)), 'edge')\n else:\n blurPad = np.pad(blur, ((0, H - h), (0, W - w), (0, 0)), 'edge')\n blurPad = np.expand_dims(blurPad, 0)\n if self.args.model != 'color':\n blurPad = np.transpose(blurPad, (3, 1, 2, 0))\n\n start = time.time()\n deblur = sess.run(outputs, feed_dict={inputs: blurPad / 255.0})\n duration = time.time() - start\n print('Saving results: %s ... %4.3fs' % (os.path.join(output_path, imgName), duration))\n res = deblur[-1]\n if self.args.model != 'color':\n res = np.transpose(res, (3, 1, 2, 0))\n res = im2uint8(res[0, :, :, :])\n # crop the image into original size\n if resize:\n res = res[:new_h, :new_w, :]\n res = scipy.misc.imresize(res, [h, w], 'bicubic')\n else:\n res = res[:h, :w, :]\n\n if rot:\n res = np.transpose(res, [1, 0, 2])\n scipy.misc.imsave(os.path.join(output_path, imgName), res)\n"
] |
[
[
"tensorflow.convert_to_tensor",
"numpy.expand_dims",
"tensorflow.concat",
"tensorflow.stack",
"tensorflow.cast",
"tensorflow.GPUOptions",
"tensorflow.train.AdamOptimizer",
"tensorflow.train.batch",
"tensorflow.summary.scalar",
"numpy.pad",
"tensorflow.Variable",
"tensorflow.ConfigProto",
"tensorflow.image.rgb_to_grayscale",
"tensorflow.contrib.layers.xavier_initializer",
"tensorflow.trainable_variables",
"tensorflow.train.Saver",
"numpy.isnan",
"tensorflow.image.resize_images",
"tensorflow.train.Coordinator",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.summary.merge_all",
"numpy.transpose",
"tensorflow.contrib.slim.conv2d_transpose",
"tensorflow.train.polynomial_decay",
"tensorflow.train.get_checkpoint_state",
"tensorflow.summary.FileWriter",
"tensorflow.reduce_mean",
"tensorflow.train.start_queue_runners",
"tensorflow.string_join",
"tensorflow.constant_initializer",
"tensorflow.clip_by_global_norm",
"tensorflow.train.slice_input_producer",
"tensorflow.contrib.slim.conv2d",
"tensorflow.variable_scope",
"tensorflow.get_variable_scope"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
navaneethsdk/qiskit-terra
|
[
"66a029f2a67c14dbf34857d172b088d75d152b55",
"66a029f2a67c14dbf34857d172b088d75d152b55"
] |
[
"qiskit/visualization/gate_map.py",
"qiskit/visualization/state_visualization.py"
] |
[
"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017, 2018.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"A module for visualizing device coupling maps\"\"\"\n\nimport math\nimport numpy as np\nfrom qiskit.exceptions import QiskitError\nfrom .matplotlib import HAS_MATPLOTLIB\nfrom .exceptions import VisualizationError\n\n\nclass _GraphDist():\n \"\"\"Transform the circles properly for non-square axes.\n \"\"\"\n\n def __init__(self, size, ax, x=True):\n self.size = size\n self.ax = ax # pylint: disable=invalid-name\n self.x = x\n\n @property\n def dist_real(self):\n \"\"\"Compute distance.\n \"\"\"\n x0, y0 = self.ax.transAxes.transform( # pylint: disable=invalid-name\n (0, 0))\n x1, y1 = self.ax.transAxes.transform( # pylint: disable=invalid-name\n (1, 1))\n value = x1 - x0 if self.x else y1 - y0\n return value\n\n @property\n def dist_abs(self):\n \"\"\"Distance abs\n \"\"\"\n bounds = self.ax.get_xlim() if self.x else self.ax.get_ylim()\n return bounds[0] - bounds[1]\n\n @property\n def value(self):\n \"\"\"Return value.\n \"\"\"\n return (self.size / self.dist_real) * self.dist_abs\n\n def __mul__(self, obj):\n return self.value * obj\n\n\ndef plot_gate_map(backend, figsize=None,\n plot_directed=False,\n label_qubits=True,\n qubit_size=24,\n line_width=4,\n font_size=12,\n qubit_color=None,\n qubit_labels=None,\n line_color=None,\n font_color='w',\n ax=None):\n \"\"\"Plots the gate map of a device.\n\n Args:\n backend (BaseBackend): A backend instance,\n figsize (tuple): Output figure size (wxh) in inches.\n plot_directed (bool): Plot directed coupling map.\n label_qubits (bool): Label the qubits.\n qubit_size (float): Size of qubit marker.\n line_width (float): Width of lines.\n font_size (int): Font size of qubit labels.\n qubit_color (list): A list of colors for the qubits\n qubit_labels (list): A list of qubit labels\n line_color (list): A list of colors for each line from coupling_map.\n font_color (str): The font color for the qubit labels.\n ax (Axes): A Matplotlib axes instance.\n\n Returns:\n Figure: A Matplotlib figure instance.\n\n Raises:\n QiskitError: if tried to pass a simulator.\n ImportError: if matplotlib not installed.\n\n Example:\n .. jupyter-execute::\n :hide-code:\n :hide-output:\n\n from qiskit.test.ibmq_mock import mock_get_backend\n mock_get_backend('FakeVigo')\n\n .. jupyter-execute::\n\n from qiskit import QuantumCircuit, execute, IBMQ\n from qiskit.visualization import plot_gate_map\n %matplotlib inline\n\n provider = IBMQ.load_account()\n accountProvider = IBMQ.get_provider(hub='ibm-q')\n backend = accountProvider.get_backend('ibmq_vigo')\n plot_gate_map(backend)\n \"\"\"\n if not HAS_MATPLOTLIB:\n raise ImportError('Must have Matplotlib installed. To install, '\n 'run \"pip install matplotlib\".')\n from matplotlib import get_backend\n import matplotlib.pyplot as plt # pylint: disable=import-error\n import matplotlib.patches as mpatches\n\n if backend.configuration().simulator:\n raise QiskitError('Requires a device backend, not simulator.')\n\n input_axes = False\n if ax:\n input_axes = True\n\n mpl_data = {}\n\n mpl_data[1] = [[0, 0]]\n\n mpl_data[5] = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]]\n\n mpl_data[7] = [[0, 0], [0, 1], [0, 2],\n [1, 1],\n [2, 0], [2, 1], [2, 2]]\n\n mpl_data[20] = [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4],\n [1, 0], [1, 1], [1, 2], [1, 3], [1, 4],\n [2, 0], [2, 1], [2, 2], [2, 3], [2, 4],\n [3, 0], [3, 1], [3, 2], [3, 3], [3, 4]]\n\n mpl_data[15] = [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4],\n [0, 5], [0, 6], [1, 7], [1, 6], [1, 5],\n [1, 4], [1, 3], [1, 2], [1, 1], [1, 0]]\n\n mpl_data[16] = [[1, 0], [0, 0], [0, 1], [0, 2], [0, 3],\n [0, 4], [0, 5], [0, 6], [0, 7], [1, 7],\n [1, 6], [1, 5], [1, 4], [1, 3], [1, 2], [1, 1]]\n\n mpl_data[27] = [[1, 0], [1, 1], [2, 1], [3, 1], [1, 2],\n [3, 2], [0, 3], [1, 3], [3, 3], [4, 3],\n [1, 4], [3, 4], [1, 5], [2, 5], [3, 5],\n [1, 6], [3, 6], [0, 7], [1, 7], [3, 7],\n [4, 7], [1, 8], [3, 8], [1, 9], [2, 9],\n [3, 9], [3, 10]]\n\n mpl_data[28] = [[0, 2], [0, 3], [0, 4], [0, 5], [0, 6],\n [1, 2], [1, 6],\n [2, 0], [2, 1], [2, 2], [2, 3], [2, 4],\n [2, 5], [2, 6], [2, 7], [2, 8],\n [3, 0], [3, 4], [3, 8],\n [4, 0], [4, 1], [4, 2], [4, 3], [4, 4],\n [4, 5], [4, 6], [4, 7], [4, 8]]\n\n mpl_data[53] = [[0, 2], [0, 3], [0, 4], [0, 5], [0, 6],\n [1, 2], [1, 6],\n [2, 0], [2, 1], [2, 2], [2, 3], [2, 4],\n [2, 5], [2, 6], [2, 7], [2, 8],\n [3, 0], [3, 4], [3, 8],\n [4, 0], [4, 1], [4, 2], [4, 3], [4, 4],\n [4, 5], [4, 6], [4, 7], [4, 8],\n [5, 2], [5, 6],\n [6, 0], [6, 1], [6, 2], [6, 3], [6, 4],\n [6, 5], [6, 6], [6, 7], [6, 8],\n [7, 0], [7, 4], [7, 8],\n [8, 0], [8, 1], [8, 2], [8, 3], [8, 4],\n [8, 5], [8, 6], [8, 7], [8, 8],\n [9, 2], [9, 6]]\n\n mpl_data[65] = [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4],\n [0, 5], [0, 6], [0, 7], [0, 8], [0, 9],\n [1, 0], [1, 4], [1, 8],\n [2, 0], [2, 1], [2, 2], [2, 3], [2, 4],\n [2, 5], [2, 6], [2, 7], [2, 8], [2, 9], [2, 10],\n [3, 2], [3, 6], [3, 10],\n [4, 0], [4, 1], [4, 2], [4, 3], [4, 4],\n [4, 5], [4, 6], [4, 7], [4, 8], [4, 9], [4, 10],\n [5, 0], [5, 4], [5, 8],\n [6, 0], [6, 1], [6, 2], [6, 3], [6, 4],\n [6, 5], [6, 6], [6, 7], [6, 8], [6, 9], [6, 10],\n [7, 2], [7, 6], [7, 10],\n [8, 1], [8, 2], [8, 3], [8, 4],\n [8, 5], [8, 6], [8, 7], [8, 8], [8, 9], [8, 10]]\n\n config = backend.configuration()\n num_qubits = config.n_qubits\n cmap = config.coupling_map\n\n if qubit_labels is None:\n qubit_labels = list(range(num_qubits))\n else:\n if len(qubit_labels) != num_qubits:\n raise QiskitError('Length of qubit labels '\n 'does not equal number '\n 'of qubits.')\n\n if num_qubits in mpl_data.keys():\n grid_data = mpl_data[num_qubits]\n else:\n if not input_axes:\n fig, ax = plt.subplots(figsize=(5, 5)) # pylint: disable=invalid-name\n ax.axis('off')\n return fig\n\n x_max = max([d[1] for d in grid_data])\n y_max = max([d[0] for d in grid_data])\n max_dim = max(x_max, y_max)\n\n if figsize is None:\n if num_qubits == 1 or (x_max / max_dim > 0.33 and y_max / max_dim > 0.33):\n figsize = (5, 5)\n else:\n figsize = (9, 3)\n\n if ax is None:\n fig, ax = plt.subplots(figsize=figsize) # pylint: disable=invalid-name\n ax.axis('off')\n\n # set coloring\n if qubit_color is None:\n qubit_color = ['#648fff'] * config.n_qubits\n if line_color is None:\n line_color = ['#648fff'] * len(cmap) if cmap else []\n\n # Add lines for couplings\n if num_qubits != 1:\n for ind, edge in enumerate(cmap):\n is_symmetric = False\n if edge[::-1] in cmap:\n is_symmetric = True\n y_start = grid_data[edge[0]][0]\n x_start = grid_data[edge[0]][1]\n y_end = grid_data[edge[1]][0]\n x_end = grid_data[edge[1]][1]\n\n if is_symmetric:\n if y_start == y_end:\n x_end = (x_end - x_start) / 2 + x_start\n\n elif x_start == x_end:\n y_end = (y_end - y_start) / 2 + y_start\n\n else:\n x_end = (x_end - x_start) / 2 + x_start\n y_end = (y_end - y_start) / 2 + y_start\n ax.add_artist(plt.Line2D([x_start, x_end], [-y_start, -y_end],\n color=line_color[ind], linewidth=line_width,\n zorder=0))\n if plot_directed:\n dx = x_end - x_start # pylint: disable=invalid-name\n dy = y_end - y_start # pylint: disable=invalid-name\n if is_symmetric:\n x_arrow = x_start + dx * 0.95\n y_arrow = -y_start - dy * 0.95\n dx_arrow = dx * 0.01\n dy_arrow = -dy * 0.01\n head_width = 0.15\n else:\n x_arrow = x_start + dx * 0.5\n y_arrow = -y_start - dy * 0.5\n dx_arrow = dx * 0.2\n dy_arrow = -dy * 0.2\n head_width = 0.2\n ax.add_patch(mpatches.FancyArrow(x_arrow,\n y_arrow,\n dx_arrow,\n dy_arrow,\n head_width=head_width,\n length_includes_head=True,\n edgecolor=None,\n linewidth=0,\n facecolor=line_color[ind],\n zorder=1))\n\n # Add circles for qubits\n for var, idx in enumerate(grid_data):\n _idx = [idx[1], -idx[0]]\n width = _GraphDist(qubit_size, ax, True)\n height = _GraphDist(qubit_size, ax, False)\n ax.add_artist(mpatches.Ellipse(\n _idx, width, height, color=qubit_color[var], zorder=1))\n if label_qubits:\n ax.text(*_idx, s=qubit_labels[var],\n horizontalalignment='center',\n verticalalignment='center',\n color=font_color, size=font_size, weight='bold')\n ax.set_xlim([-1, x_max + 1])\n ax.set_ylim([-(y_max + 1), 1])\n if not input_axes:\n if get_backend() in ['module://ipykernel.pylab.backend_inline',\n 'nbAgg']:\n plt.close(fig)\n return fig\n return None\n\n\ndef plot_circuit_layout(circuit, backend, view='virtual'):\n \"\"\"Plot the layout of a circuit transpiled for a given\n target backend.\n\n Args:\n circuit (QuantumCircuit): Input quantum circuit.\n backend (BaseBackend): Target backend.\n view (str): Layout view: either 'virtual' or 'physical'.\n\n Returns:\n Figure: A matplotlib figure showing layout.\n\n Raises:\n QiskitError: Invalid view type given.\n VisualizationError: Circuit has no layout attribute.\n\n Example:\n .. jupyter-execute::\n :hide-code:\n :hide-output:\n\n from qiskit.test.ibmq_mock import mock_get_backend\n mock_get_backend('FakeVigo')\n\n .. jupyter-execute::\n\n import numpy as np\n from qiskit import QuantumCircuit, IBMQ, transpile\n from qiskit.visualization import plot_histogram, plot_gate_map, plot_circuit_layout\n from qiskit.tools.monitor import job_monitor\n import matplotlib.pyplot as plt\n %matplotlib inline\n\n IBMQ.load_account()\n\n ghz = QuantumCircuit(3, 3)\n ghz.h(0)\n for idx in range(1,3):\n ghz.cx(0,idx)\n ghz.measure(range(3), range(3))\n\n provider = IBMQ.get_provider(hub='ibm-q')\n backend = provider.get_backend('ibmq_vigo')\n new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)\n plot_circuit_layout(new_circ_lv3, backend)\n \"\"\"\n if circuit._layout is None:\n raise QiskitError('Circuit has no layout. '\n 'Perhaps it has not been transpiled.')\n\n num_qubits = backend.configuration().n_qubits\n\n qubits = []\n qubit_labels = [None] * num_qubits\n\n if view == 'virtual':\n for key, val in circuit._layout.get_virtual_bits().items():\n if key.register.name != 'ancilla':\n qubits.append(val)\n qubit_labels[val] = key.index\n\n elif view == 'physical':\n for key, val in circuit._layout.get_physical_bits().items():\n if val.register.name != 'ancilla':\n qubits.append(key)\n qubit_labels[key] = key\n\n else:\n raise VisualizationError(\"Layout view must be 'virtual' or 'physical'.\")\n\n qcolors = ['#648fff'] * num_qubits\n for k in qubits:\n qcolors[k] = 'k'\n\n cmap = backend.configuration().coupling_map\n\n lcolors = ['#648fff'] * len(cmap)\n\n for idx, edge in enumerate(cmap):\n if edge[0] in qubits and edge[1] in qubits:\n lcolors[idx] = 'k'\n\n fig = plot_gate_map(backend,\n qubit_color=qcolors,\n qubit_labels=qubit_labels,\n line_color=lcolors)\n return fig\n\n\ndef plot_error_map(backend, figsize=(12, 9), show_title=True):\n \"\"\"Plots the error map of a given backend.\n\n Args:\n backend (IBMQBackend): Given backend.\n figsize (tuple): Figure size in inches.\n show_title (bool): Show the title or not.\n\n Returns:\n Figure: A matplotlib figure showing error map.\n\n Raises:\n VisualizationError: Input is not IBMQ backend.\n ImportError: If seaborn is not installed\n\n Example:\n .. jupyter-execute::\n :hide-code:\n :hide-output:\n\n from qiskit.test.ibmq_mock import mock_get_backend\n mock_get_backend('FakeVigo')\n\n .. jupyter-execute::\n\n from qiskit import QuantumCircuit, execute, IBMQ\n from qiskit.visualization import plot_error_map\n %matplotlib inline\n\n IBMQ.load_account()\n provider = IBMQ.get_provider(hub='ibm-q')\n backend = provider.get_backend('ibmq_vigo')\n plot_error_map(backend)\n \"\"\"\n try:\n import seaborn as sns\n except ImportError:\n raise ImportError('Must have seaborn installed to use plot_error_map. '\n 'To install, run \"pip install seaborn\".')\n if not HAS_MATPLOTLIB:\n raise ImportError('Must have Matplotlib installed. To install, '\n 'run \"pip install matplotlib\".')\n import matplotlib\n from matplotlib import get_backend\n import matplotlib.pyplot as plt # pylint: disable=import-error\n import matplotlib.gridspec as gridspec\n from matplotlib import ticker\n\n color_map = sns.cubehelix_palette(reverse=True, as_cmap=True)\n\n props = backend.properties().to_dict()\n config = backend.configuration().to_dict()\n\n num_qubits = config['n_qubits']\n\n # U2 error rates\n single_gate_errors = [0]*num_qubits\n for gate in props['gates']:\n if gate['gate'] == 'u2':\n _qubit = gate['qubits'][0]\n single_gate_errors[_qubit] = gate['parameters'][0]['value']\n\n # Convert to percent\n single_gate_errors = 100 * np.asarray(single_gate_errors)\n avg_1q_err = np.mean(single_gate_errors)\n\n single_norm = matplotlib.colors.Normalize(\n vmin=min(single_gate_errors), vmax=max(single_gate_errors))\n q_colors = [color_map(single_norm(err)) for err in single_gate_errors]\n\n cmap = config['coupling_map']\n\n directed = False\n line_colors = []\n if cmap:\n directed = False\n if num_qubits < 20:\n for edge in cmap:\n if not [edge[1], edge[0]] in cmap:\n directed = True\n break\n\n cx_errors = []\n for line in cmap:\n for item in props['gates']:\n if item['qubits'] == line:\n cx_errors.append(item['parameters'][0]['value'])\n break\n else:\n continue\n\n # Convert to percent\n cx_errors = 100 * np.asarray(cx_errors)\n avg_cx_err = np.mean(cx_errors)\n\n cx_norm = matplotlib.colors.Normalize(\n vmin=min(cx_errors), vmax=max(cx_errors))\n line_colors = [color_map(cx_norm(err)) for err in cx_errors]\n\n # Measurement errors\n\n read_err = []\n\n for qubit in range(num_qubits):\n for item in props['qubits'][qubit]:\n if item['name'] == 'readout_error':\n read_err.append(item['value'])\n\n read_err = 100 * np.asarray(read_err)\n avg_read_err = np.mean(read_err)\n max_read_err = np.max(read_err)\n\n fig = plt.figure(figsize=figsize)\n gridspec.GridSpec(nrows=2, ncols=3)\n\n grid_spec = gridspec.GridSpec(12, 12, height_ratios=[1] * 11 + [0.5],\n width_ratios=[2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2])\n\n left_ax = plt.subplot(grid_spec[2:10, :1])\n main_ax = plt.subplot(grid_spec[:11, 1:11])\n right_ax = plt.subplot(grid_spec[2:10, 11:])\n bleft_ax = plt.subplot(grid_spec[-1, :5])\n if cmap:\n bright_ax = plt.subplot(grid_spec[-1, 7:])\n\n plot_gate_map(backend, qubit_color=q_colors,\n line_color=line_colors,\n qubit_size=28,\n line_width=5,\n plot_directed=directed,\n ax=main_ax)\n main_ax.axis('off')\n main_ax.set_aspect(1)\n if cmap:\n single_cb = matplotlib.colorbar.ColorbarBase(bleft_ax, cmap=color_map,\n norm=single_norm,\n orientation='horizontal')\n tick_locator = ticker.MaxNLocator(nbins=5)\n single_cb.locator = tick_locator\n single_cb.update_ticks()\n single_cb.update_ticks()\n bleft_ax.set_title('H error rate (%) [Avg. = {}]'.format(round(avg_1q_err, 3)))\n\n if cmap is None:\n bleft_ax.axis('off')\n bleft_ax.set_title('H error rate (%) = {}'.format(round(avg_1q_err, 3)))\n\n if cmap:\n cx_cb = matplotlib.colorbar.ColorbarBase(bright_ax, cmap=color_map,\n norm=cx_norm,\n orientation='horizontal')\n tick_locator = ticker.MaxNLocator(nbins=5)\n cx_cb.locator = tick_locator\n cx_cb.update_ticks()\n bright_ax.set_title('CNOT error rate (%) [Avg. = {}]'.format(round(avg_cx_err, 3)))\n\n if num_qubits < 10:\n num_left = num_qubits\n num_right = 0\n else:\n num_left = math.ceil(num_qubits / 2)\n num_right = num_qubits - num_left\n\n left_ax.barh(range(num_left), read_err[:num_left], align='center', color='#DDBBBA')\n left_ax.axvline(avg_read_err, linestyle='--', color='#212121')\n left_ax.set_yticks(range(num_left))\n left_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)])\n left_ax.set_yticklabels([str(kk) for kk in range(num_left)], fontsize=12)\n left_ax.invert_yaxis()\n left_ax.set_title('Readout Error (%)', fontsize=12)\n\n for spine in left_ax.spines.values():\n spine.set_visible(False)\n\n if num_right:\n right_ax.barh(range(num_left, num_qubits), read_err[num_left:],\n align='center', color='#DDBBBA')\n right_ax.axvline(avg_read_err, linestyle='--', color='#212121')\n right_ax.set_yticks(range(num_left, num_qubits))\n right_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)])\n right_ax.set_yticklabels([str(kk) for kk in range(num_left, num_qubits)],\n fontsize=12)\n right_ax.invert_yaxis()\n right_ax.invert_xaxis()\n right_ax.yaxis.set_label_position(\"right\")\n right_ax.yaxis.tick_right()\n right_ax.set_title('Readout Error (%)', fontsize=12)\n else:\n right_ax.axis('off')\n\n for spine in right_ax.spines.values():\n spine.set_visible(False)\n\n if show_title:\n fig.suptitle('{name} Error Map'.format(name=backend.name()),\n fontsize=24, y=0.9)\n if get_backend() in ['module://ipykernel.pylab.backend_inline',\n 'nbAgg']:\n plt.close(fig)\n return fig\n",
"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017, 2018.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n# pylint: disable=invalid-name,ungrouped-imports,import-error\n# pylint: disable=inconsistent-return-statements,unsubscriptable-object\n# pylint: disable=missing-param-doc,missing-type-doc,unused-argument\n\n\"\"\"\nVisualization functions for quantum states.\n\"\"\"\n\nfrom functools import reduce\nimport colorsys\nimport numpy as np\nfrom scipy import linalg\nfrom qiskit.quantum_info.states import DensityMatrix\nfrom qiskit.utils.deprecation import deprecate_arguments\nfrom qiskit.visualization.matplotlib import HAS_MATPLOTLIB\nfrom qiskit.visualization.exceptions import VisualizationError\nfrom qiskit.visualization.utils import _bloch_multivector_data, _paulivec_data\nfrom qiskit.circuit.tools.pi_check import pi_check\n\n\n@deprecate_arguments({'rho': 'state'})\ndef plot_state_hinton(state, title='', figsize=None, ax_real=None, ax_imag=None, *, rho=None):\n \"\"\"Plot a hinton diagram for the density matrix of a quantum state.\n\n Args:\n state (Statevector or DensityMatrix or ndarray): An N-qubit quantum state.\n title (str): a string that represents the plot title\n figsize (tuple): Figure size in inches.\n ax_real (matplotlib.axes.Axes): An optional Axes object to be used for\n the visualization output. If none is specified a new matplotlib\n Figure will be created and used. If this is specified without an\n ax_imag only the real component plot will be generated.\n Additionally, if specified there will be no returned Figure since\n it is redundant.\n ax_imag (matplotlib.axes.Axes): An optional Axes object to be used for\n the visualization output. If none is specified a new matplotlib\n Figure will be created and used. If this is specified without an\n ax_imag only the real component plot will be generated.\n Additionally, if specified there will be no returned Figure since\n it is redundant.\n\n Returns:\n matplotlib.Figure:\n The matplotlib.Figure of the visualization if\n neither ax_real or ax_imag is set.\n\n Raises:\n ImportError: Requires matplotlib.\n VisualizationError: if input is not a valid N-qubit state.\n\n Example:\n .. jupyter-execute::\n\n from qiskit import QuantumCircuit\n from qiskit.quantum_info import DensityMatrix\n from qiskit.visualization import plot_state_hinton\n %matplotlib inline\n\n qc = QuantumCircuit(2)\n qc.h(0)\n qc.cx(0, 1)\n\n state = DensityMatrix.from_instruction(qc)\n plot_state_hinton(state, title=\"New Hinton Plot\")\n \"\"\"\n if not HAS_MATPLOTLIB:\n raise ImportError('Must have Matplotlib installed. To install, run '\n '\"pip install matplotlib\".')\n from matplotlib import pyplot as plt\n from matplotlib import get_backend\n\n # Figure data\n rho = DensityMatrix(state)\n num = rho.num_qubits\n if num is None:\n raise VisualizationError(\"Input is not a multi-qubit quantum state.\")\n max_weight = 2 ** np.ceil(np.log(np.abs(rho.data).max()) / np.log(2))\n datareal = np.real(rho.data)\n dataimag = np.imag(rho.data)\n\n if figsize is None:\n figsize = (8, 5)\n if not ax_real and not ax_imag:\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize)\n else:\n if ax_real:\n fig = ax_real.get_figure()\n else:\n fig = ax_imag.get_figure()\n ax1 = ax_real\n ax2 = ax_imag\n column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]\n row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]\n ly, lx = datareal.shape\n # Real\n if ax1:\n ax1.patch.set_facecolor('gray')\n ax1.set_aspect('equal', 'box')\n ax1.xaxis.set_major_locator(plt.NullLocator())\n ax1.yaxis.set_major_locator(plt.NullLocator())\n\n for (x, y), w in np.ndenumerate(datareal):\n color = 'white' if w > 0 else 'black'\n size = np.sqrt(np.abs(w) / max_weight)\n rect = plt.Rectangle([0.5 + x - size / 2, 0.5 + y - size / 2], size, size,\n facecolor=color, edgecolor=color)\n ax1.add_patch(rect)\n\n ax1.set_xticks(0.5 + np.arange(lx))\n ax1.set_yticks(0.5 + np.arange(ly))\n ax1.set_xlim([0, lx])\n ax1.set_ylim([ly, 0])\n ax1.set_yticklabels(row_names, fontsize=14)\n ax1.set_xticklabels(column_names, fontsize=14, rotation=90)\n ax1.invert_yaxis()\n ax1.set_title('Re[$\\\\rho$]', fontsize=14)\n # Imaginary\n if ax2:\n ax2.patch.set_facecolor('gray')\n ax2.set_aspect('equal', 'box')\n ax2.xaxis.set_major_locator(plt.NullLocator())\n ax2.yaxis.set_major_locator(plt.NullLocator())\n\n for (x, y), w in np.ndenumerate(dataimag):\n color = 'white' if w > 0 else 'black'\n size = np.sqrt(np.abs(w) / max_weight)\n rect = plt.Rectangle([0.5 + x - size / 2, 0.5 + y - size / 2], size, size,\n facecolor=color, edgecolor=color)\n ax2.add_patch(rect)\n\n ax2.set_xticks(0.5 + np.arange(lx))\n ax2.set_yticks(0.5 + np.arange(ly))\n ax1.set_xlim([0, lx])\n ax1.set_ylim([ly, 0])\n ax2.set_yticklabels(row_names, fontsize=14)\n ax2.set_xticklabels(column_names, fontsize=14, rotation=90)\n ax2.invert_yaxis()\n ax2.set_title('Im[$\\\\rho$]', fontsize=14)\n if title:\n fig.suptitle(title, fontsize=16)\n if ax_real is None and ax_imag is None:\n if get_backend() in ['module://ipykernel.pylab.backend_inline',\n 'nbAgg']:\n plt.close(fig)\n return fig\n\n\ndef plot_bloch_vector(bloch, title=\"\", ax=None, figsize=None, coord_type=\"cartesian\"):\n \"\"\"Plot the Bloch sphere.\n\n Plot a sphere, axes, the Bloch vector, and its projections onto each axis.\n\n Args:\n bloch (list[double]): array of three elements where [<x>, <y>, <z>] (cartesian)\n or [<r>, <theta>, <phi>] (spherical in radians)\n <theta> is inclination angle from +z direction\n <phi> is azimuth from +x direction\n title (str): a string that represents the plot title\n ax (matplotlib.axes.Axes): An Axes to use for rendering the bloch\n sphere\n figsize (tuple): Figure size in inches. Has no effect is passing ``ax``.\n coord_type (str): a string that specifies coordinate type for bloch\n (cartesian or spherical), default is cartesian\n\n Returns:\n Figure: A matplotlib figure instance if ``ax = None``.\n\n Raises:\n ImportError: Requires matplotlib.\n\n Example:\n .. jupyter-execute::\n\n from qiskit.visualization import plot_bloch_vector\n %matplotlib inline\n\n plot_bloch_vector([0,1,0], title=\"New Bloch Sphere\")\n \"\"\"\n if not HAS_MATPLOTLIB:\n raise ImportError('Must have Matplotlib installed. To install, run '\n '\"pip install matplotlib\".')\n from qiskit.visualization.bloch import Bloch\n from matplotlib import get_backend\n from matplotlib import pyplot as plt\n\n if figsize is None:\n figsize = (5, 5)\n B = Bloch(axes=ax)\n if coord_type == \"spherical\":\n r, theta, phi = bloch[0], bloch[1], bloch[2]\n bloch[0] = r*np.sin(theta)*np.cos(phi)\n bloch[1] = r*np.sin(theta)*np.sin(phi)\n bloch[2] = r*np.cos(theta)\n B.add_vectors(bloch)\n B.render(title=title)\n if ax is None:\n fig = B.fig\n fig.set_size_inches(figsize[0], figsize[1])\n if get_backend() in ['module://ipykernel.pylab.backend_inline',\n 'nbAgg']:\n plt.close(fig)\n return fig\n return None\n\n\n@deprecate_arguments({'rho': 'state'})\ndef plot_bloch_multivector(state, title='', figsize=None, *, rho=None):\n \"\"\"Plot the Bloch sphere.\n\n Plot a sphere, axes, the Bloch vector, and its projections onto each axis.\n\n Args:\n state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state.\n title (str): a string that represents the plot title\n figsize (tuple): Has no effect, here for compatibility only.\n\n Returns:\n matplotlib.Figure:\n A matplotlib figure instance.\n\n Raises:\n ImportError: Requires matplotlib.\n VisualizationError: if input is not a valid N-qubit state.\n\n Example:\n .. jupyter-execute::\n\n from qiskit import QuantumCircuit\n from qiskit.quantum_info import Statevector\n from qiskit.visualization import plot_bloch_multivector\n %matplotlib inline\n\n qc = QuantumCircuit(2)\n qc.h(0)\n qc.cx(0, 1)\n\n state = Statevector.from_instruction(qc)\n plot_bloch_multivector(state, title=\"New Bloch Multivector\")\n \"\"\"\n if not HAS_MATPLOTLIB:\n raise ImportError('Must have Matplotlib installed. To install, run '\n '\"pip install matplotlib\".')\n from matplotlib import get_backend\n from matplotlib import pyplot as plt\n\n # Data\n bloch_data = _bloch_multivector_data(state)\n num = len(bloch_data)\n width, height = plt.figaspect(1/num)\n fig = plt.figure(figsize=(width, height))\n for i in range(num):\n ax = fig.add_subplot(1, num, i + 1, projection='3d')\n plot_bloch_vector(bloch_data[i], \"qubit \" + str(i), ax=ax,\n figsize=figsize)\n fig.suptitle(title, fontsize=16)\n if get_backend() in ['module://ipykernel.pylab.backend_inline',\n 'nbAgg']:\n plt.close(fig)\n return fig\n\n\n@deprecate_arguments({'rho': 'state'})\ndef plot_state_city(state, title=\"\", figsize=None, color=None,\n alpha=1, ax_real=None, ax_imag=None, *, rho=None):\n \"\"\"Plot the cityscape of quantum state.\n\n Plot two 3d bar graphs (two dimensional) of the real and imaginary\n part of the density matrix rho.\n\n Args:\n state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state.\n title (str): a string that represents the plot title\n figsize (tuple): Figure size in inches.\n color (list): A list of len=2 giving colors for real and\n imaginary components of matrix elements.\n alpha (float): Transparency value for bars\n ax_real (matplotlib.axes.Axes): An optional Axes object to be used for\n the visualization output. If none is specified a new matplotlib\n Figure will be created and used. If this is specified without an\n ax_imag only the real component plot will be generated.\n Additionally, if specified there will be no returned Figure since\n it is redundant.\n ax_imag (matplotlib.axes.Axes): An optional Axes object to be used for\n the visualization output. If none is specified a new matplotlib\n Figure will be created and used. If this is specified without an\n ax_imag only the real component plot will be generated.\n Additionally, if specified there will be no returned Figure since\n it is redundant.\n\n Returns:\n matplotlib.Figure:\n The matplotlib.Figure of the visualization if the\n ``ax_real`` and ``ax_imag`` kwargs are not set\n\n Raises:\n ImportError: Requires matplotlib.\n ValueError: When 'color' is not a list of len=2.\n VisualizationError: if input is not a valid N-qubit state.\n\n Example:\n .. jupyter-execute::\n\n from qiskit import QuantumCircuit\n from qiskit.quantum_info import DensityMatrix\n from qiskit.visualization import plot_state_city\n %matplotlib inline\n\n qc = QuantumCircuit(2)\n qc.h(0)\n qc.cx(0, 1)\n\n state = DensityMatrix.from_instruction(qc)\n plot_state_city(state, color=['midnightblue', 'midnightblue'],\n title=\"New State City\")\n \"\"\"\n if not HAS_MATPLOTLIB:\n raise ImportError('Must have Matplotlib installed. To install, run '\n '\"pip install matplotlib\".')\n from matplotlib import get_backend\n from matplotlib import pyplot as plt\n from mpl_toolkits.mplot3d.art3d import Poly3DCollection\n\n rho = DensityMatrix(state)\n num = rho.num_qubits\n if num is None:\n raise VisualizationError(\"Input is not a multi-qubit quantum state.\")\n\n # get the real and imag parts of rho\n datareal = np.real(rho.data)\n dataimag = np.imag(rho.data)\n\n # get the labels\n column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]\n row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]\n\n lx = len(datareal[0]) # Work out matrix dimensions\n ly = len(datareal[:, 0])\n xpos = np.arange(0, lx, 1) # Set up a mesh of positions\n ypos = np.arange(0, ly, 1)\n xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25)\n\n xpos = xpos.flatten()\n ypos = ypos.flatten()\n zpos = np.zeros(lx*ly)\n\n dx = 0.5 * np.ones_like(zpos) # width of bars\n dy = dx.copy()\n dzr = datareal.flatten()\n dzi = dataimag.flatten()\n\n if color is None:\n color = [\"#648fff\", \"#648fff\"]\n else:\n if len(color) != 2:\n raise ValueError(\"'color' must be a list of len=2.\")\n if color[0] is None:\n color[0] = \"#648fff\"\n if color[1] is None:\n color[1] = \"#648fff\"\n if ax_real is None and ax_imag is None:\n # set default figure size\n if figsize is None:\n figsize = (15, 5)\n\n fig = plt.figure(figsize=figsize)\n ax1 = fig.add_subplot(1, 2, 1, projection='3d')\n ax2 = fig.add_subplot(1, 2, 2, projection='3d')\n elif ax_real is not None:\n fig = ax_real.get_figure()\n ax1 = ax_real\n if ax_imag is not None:\n ax2 = ax_imag\n else:\n fig = ax_imag.get_figure()\n ax1 = None\n ax2 = ax_imag\n\n max_dzr = max(dzr)\n min_dzr = min(dzr)\n min_dzi = np.min(dzi)\n max_dzi = np.max(dzi)\n\n if ax1 is not None:\n fc1 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzr, color[0])\n for idx, cur_zpos in enumerate(zpos):\n if dzr[idx] > 0:\n zorder = 2\n else:\n zorder = 0\n b1 = ax1.bar3d(xpos[idx], ypos[idx], cur_zpos,\n dx[idx], dy[idx], dzr[idx],\n alpha=alpha, zorder=zorder)\n b1.set_facecolors(fc1[6*idx:6*idx+6])\n\n xlim, ylim = ax1.get_xlim(), ax1.get_ylim()\n x = [xlim[0], xlim[1], xlim[1], xlim[0]]\n y = [ylim[0], ylim[0], ylim[1], ylim[1]]\n z = [0, 0, 0, 0]\n verts = [list(zip(x, y, z))]\n\n pc1 = Poly3DCollection(verts, alpha=0.15, facecolor='k',\n linewidths=1, zorder=1)\n\n if min(dzr) < 0 < max(dzr):\n ax1.add_collection3d(pc1)\n ax1.set_xticks(np.arange(0.5, lx+0.5, 1))\n ax1.set_yticks(np.arange(0.5, ly+0.5, 1))\n if max_dzr != min_dzr:\n ax1.axes.set_zlim3d(np.min(dzr), max(np.max(dzr) + 1e-9, max_dzi))\n else:\n if min_dzr == 0:\n ax1.axes.set_zlim3d(np.min(dzr), max(np.max(dzr)+1e-9, np.max(dzi)))\n else:\n ax1.axes.set_zlim3d(auto=True)\n ax1.get_autoscalez_on()\n ax1.w_xaxis.set_ticklabels(row_names, fontsize=14, rotation=45,\n ha='right', va='top')\n ax1.w_yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5,\n ha='left', va='center')\n ax1.set_zlabel('Re[$\\\\rho$]', fontsize=14)\n for tick in ax1.zaxis.get_major_ticks():\n tick.label.set_fontsize(14)\n\n if ax2 is not None:\n fc2 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzi, color[1])\n for idx, cur_zpos in enumerate(zpos):\n if dzi[idx] > 0:\n zorder = 2\n else:\n zorder = 0\n b2 = ax2.bar3d(xpos[idx], ypos[idx], cur_zpos,\n dx[idx], dy[idx], dzi[idx],\n alpha=alpha, zorder=zorder)\n b2.set_facecolors(fc2[6*idx:6*idx+6])\n\n xlim, ylim = ax2.get_xlim(), ax2.get_ylim()\n x = [xlim[0], xlim[1], xlim[1], xlim[0]]\n y = [ylim[0], ylim[0], ylim[1], ylim[1]]\n z = [0, 0, 0, 0]\n verts = [list(zip(x, y, z))]\n\n pc2 = Poly3DCollection(verts, alpha=0.2, facecolor='k',\n linewidths=1, zorder=1)\n\n if min(dzi) < 0 < max(dzi):\n ax2.add_collection3d(pc2)\n ax2.set_xticks(np.arange(0.5, lx+0.5, 1))\n ax2.set_yticks(np.arange(0.5, ly+0.5, 1))\n if min_dzi != max_dzi:\n eps = 0\n ax2.axes.set_zlim3d(np.min(dzi), max(np.max(dzr)+1e-9, np.max(dzi)+eps))\n else:\n if min_dzi == 0:\n ax2.set_zticks([0])\n eps = 1e-9\n ax2.axes.set_zlim3d(np.min(dzi), max(np.max(dzr)+1e-9, np.max(dzi)+eps))\n else:\n ax2.axes.set_zlim3d(auto=True)\n\n ax2.w_xaxis.set_ticklabels(row_names, fontsize=14, rotation=45,\n ha='right', va='top')\n ax2.w_yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5,\n ha='left', va='center')\n ax2.set_zlabel('Im[$\\\\rho$]', fontsize=14)\n for tick in ax2.zaxis.get_major_ticks():\n tick.label.set_fontsize(14)\n ax2.get_autoscalez_on()\n\n fig.suptitle(title, fontsize=16)\n if ax_real is None and ax_imag is None:\n if get_backend() in ['module://ipykernel.pylab.backend_inline',\n 'nbAgg']:\n plt.close(fig)\n return fig\n\n\n@deprecate_arguments({'rho': 'state'})\ndef plot_state_paulivec(state, title=\"\", figsize=None, color=None, ax=None, *, rho=None):\n \"\"\"Plot the paulivec representation of a quantum state.\n\n Plot a bargraph of the mixed state rho over the pauli matrices\n\n Args:\n state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state.\n title (str): a string that represents the plot title\n figsize (tuple): Figure size in inches.\n color (list or str): Color of the expectation value bars.\n ax (matplotlib.axes.Axes): An optional Axes object to be used for\n the visualization output. If none is specified a new matplotlib\n Figure will be created and used. Additionally, if specified there\n will be no returned Figure since it is redundant.\n\n Returns:\n matplotlib.Figure:\n The matplotlib.Figure of the visualization if the\n ``ax`` kwarg is not set\n\n Raises:\n ImportError: Requires matplotlib.\n VisualizationError: if input is not a valid N-qubit state.\n\n Example:\n .. jupyter-execute::\n\n from qiskit import QuantumCircuit\n from qiskit.quantum_info import Statevector\n from qiskit.visualization import plot_state_paulivec\n %matplotlib inline\n\n qc = QuantumCircuit(2)\n qc.h(0)\n qc.cx(0, 1)\n\n state = Statevector.from_instruction(qc)\n plot_state_paulivec(state, color='midnightblue',\n title=\"New PauliVec plot\")\n \"\"\"\n if not HAS_MATPLOTLIB:\n raise ImportError('Must have Matplotlib installed. To install, run '\n '\"pip install matplotlib\".')\n from matplotlib import get_backend\n from matplotlib import pyplot as plt\n\n labels, values = _paulivec_data(state)\n numelem = len(values)\n\n if figsize is None:\n figsize = (7, 5)\n if color is None:\n color = \"#648fff\"\n\n ind = np.arange(numelem) # the x locations for the groups\n width = 0.5 # the width of the bars\n if ax is None:\n return_fig = True\n fig, ax = plt.subplots(figsize=figsize)\n else:\n return_fig = False\n fig = ax.get_figure()\n ax.grid(zorder=0, linewidth=1, linestyle='--')\n ax.bar(ind, values, width, color=color, zorder=2)\n ax.axhline(linewidth=1, color='k')\n # add some text for labels, title, and axes ticks\n ax.set_ylabel('Expectation value', fontsize=14)\n ax.set_xticks(ind)\n ax.set_yticks([-1, -0.5, 0, 0.5, 1])\n ax.set_xticklabels(labels, fontsize=14, rotation=70)\n ax.set_xlabel('Pauli', fontsize=14)\n ax.set_ylim([-1, 1])\n ax.set_facecolor('#eeeeee')\n for tick in ax.xaxis.get_major_ticks()+ax.yaxis.get_major_ticks():\n tick.label.set_fontsize(14)\n ax.set_title(title, fontsize=16)\n if return_fig:\n if get_backend() in ['module://ipykernel.pylab.backend_inline',\n 'nbAgg']:\n plt.close(fig)\n return fig\n\n\ndef n_choose_k(n, k):\n \"\"\"Return the number of combinations for n choose k.\n\n Args:\n n (int): the total number of options .\n k (int): The number of elements.\n\n Returns:\n int: returns the binomial coefficient\n \"\"\"\n if n == 0:\n return 0\n return reduce(lambda x, y: x * y[0] / y[1],\n zip(range(n - k + 1, n + 1),\n range(1, k + 1)), 1)\n\n\ndef lex_index(n, k, lst):\n \"\"\"Return the lex index of a combination..\n\n Args:\n n (int): the total number of options .\n k (int): The number of elements.\n lst (list): list\n\n Returns:\n int: returns int index for lex order\n\n Raises:\n VisualizationError: if length of list is not equal to k\n \"\"\"\n if len(lst) != k:\n raise VisualizationError(\"list should have length k\")\n comb = list(map(lambda x: n - 1 - x, lst))\n dualm = sum([n_choose_k(comb[k - 1 - i], i + 1) for i in range(k)])\n return int(dualm)\n\n\ndef bit_string_index(s):\n \"\"\"Return the index of a string of 0s and 1s.\"\"\"\n n = len(s)\n k = s.count(\"1\")\n if s.count(\"0\") != n - k:\n raise VisualizationError(\"s must be a string of 0 and 1\")\n ones = [pos for pos, char in enumerate(s) if char == \"1\"]\n return lex_index(n, k, ones)\n\n\ndef phase_to_rgb(complex_number):\n \"\"\"Map a phase of a complexnumber to a color in (r,g,b).\n\n complex_number is phase is first mapped to angle in the range\n [0, 2pi] and then to the HSL color wheel\n \"\"\"\n angles = (np.angle(complex_number) + (np.pi * 4)) % (np.pi * 2)\n rgb = colorsys.hls_to_rgb(angles / (np.pi * 2), 0.5, 0.5)\n return rgb\n\n\n@deprecate_arguments({'rho': 'state'})\ndef plot_state_qsphere(state, figsize=None, ax=None, show_state_labels=True,\n show_state_phases=False, use_degrees=False, *, rho=None):\n \"\"\"Plot the qsphere representation of a quantum state.\n Here, the size of the points is proportional to the probability\n of the corresponding term in the state and the color represents\n the phase.\n\n Args:\n state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state.\n figsize (tuple): Figure size in inches.\n ax (matplotlib.axes.Axes): An optional Axes object to be used for\n the visualization output. If none is specified a new matplotlib\n Figure will be created and used. Additionally, if specified there\n will be no returned Figure since it is redundant.\n show_state_labels (bool): An optional boolean indicating whether to\n show labels for each basis state.\n show_state_phases (bool): An optional boolean indicating whether to\n show the phase for each basis state.\n use_degrees (bool): An optional boolean indicating whether to use\n radians or degrees for the phase values in the plot.\n\n Returns:\n Figure: A matplotlib figure instance if the ``ax`` kwag is not set\n\n Raises:\n ImportError: Requires matplotlib.\n VisualizationError: if input is not a valid N-qubit state.\n\n QiskitError: Input statevector does not have valid dimensions.\n\n Example:\n .. jupyter-execute::\n\n from qiskit import QuantumCircuit\n from qiskit.quantum_info import Statevector\n from qiskit.visualization import plot_state_qsphere\n %matplotlib inline\n\n qc = QuantumCircuit(2)\n qc.h(0)\n qc.cx(0, 1)\n\n state = Statevector.from_instruction(qc)\n plot_state_qsphere(state)\n \"\"\"\n if not HAS_MATPLOTLIB:\n raise ImportError('Must have Matplotlib installed. To install, run '\n '\"pip install matplotlib\".')\n\n from mpl_toolkits.mplot3d import proj3d\n from matplotlib.patches import FancyArrowPatch\n import matplotlib.gridspec as gridspec\n from matplotlib import pyplot as plt\n from matplotlib.patches import Circle\n from matplotlib import get_backend\n\n class Arrow3D(FancyArrowPatch):\n \"\"\"Standard 3D arrow.\"\"\"\n\n def __init__(self, xs, ys, zs, *args, **kwargs):\n \"\"\"Create arrow.\"\"\"\n FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)\n self._verts3d = xs, ys, zs\n\n def draw(self, renderer):\n \"\"\"Draw the arrow.\"\"\"\n xs3d, ys3d, zs3d = self._verts3d\n xs, ys, _ = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\n self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))\n FancyArrowPatch.draw(self, renderer)\n\n try:\n import seaborn as sns\n except ImportError:\n raise ImportError('Must have seaborn installed to use '\n 'plot_state_qsphere. To install, run \"pip install seaborn\".')\n rho = DensityMatrix(state)\n num = rho.num_qubits\n if num is None:\n raise VisualizationError(\"Input is not a multi-qubit quantum state.\")\n # get the eigenvectors and eigenvalues\n eigvals, eigvecs = linalg.eigh(rho.data)\n\n if figsize is None:\n figsize = (7, 7)\n\n if ax is None:\n return_fig = True\n fig = plt.figure(figsize=figsize)\n else:\n return_fig = False\n fig = ax.get_figure()\n\n gs = gridspec.GridSpec(nrows=3, ncols=3)\n\n ax = fig.add_subplot(gs[0:3, 0:3], projection='3d')\n ax.axes.set_xlim3d(-1.0, 1.0)\n ax.axes.set_ylim3d(-1.0, 1.0)\n ax.axes.set_zlim3d(-1.0, 1.0)\n ax.axes.grid(False)\n ax.view_init(elev=5, azim=275)\n\n # Force aspect ratio\n # MPL 3.2 or previous do not have set_box_aspect\n if hasattr(ax.axes, 'set_box_aspect'):\n ax.axes.set_box_aspect((1, 1, 1))\n\n # start the plotting\n # Plot semi-transparent sphere\n u = np.linspace(0, 2 * np.pi, 25)\n v = np.linspace(0, np.pi, 25)\n x = np.outer(np.cos(u), np.sin(v))\n y = np.outer(np.sin(u), np.sin(v))\n z = np.outer(np.ones(np.size(u)), np.cos(v))\n ax.plot_surface(x, y, z, rstride=1, cstride=1, color=plt.rcParams['grid.color'],\n alpha=0.2, linewidth=0)\n\n # Get rid of the panes\n ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n\n # Get rid of the spines\n ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0))\n ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0))\n ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))\n\n # Get rid of the ticks\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_zticks([])\n\n # traversing the eigvals/vecs backward as sorted low->high\n for idx in range(eigvals.shape[0]-1, -1, -1):\n if eigvals[idx] > 0.001:\n # get the max eigenvalue\n state = eigvecs[:, idx]\n loc = np.absolute(state).argmax()\n # remove the global phase from max element\n angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)\n angleset = np.exp(-1j * angles)\n state = angleset * state\n\n d = num\n for i in range(2 ** num):\n # get x,y,z points\n element = bin(i)[2:].zfill(num)\n weight = element.count(\"1\")\n zvalue = -2 * weight / d + 1\n number_of_divisions = n_choose_k(d, weight)\n weight_order = bit_string_index(element)\n angle = (float(weight) / d) * (np.pi * 2) + \\\n (weight_order * 2 * (np.pi / number_of_divisions))\n\n if (weight > d / 2) or ((weight == d / 2) and\n (weight_order >= number_of_divisions / 2)):\n angle = np.pi - angle - (2 * np.pi / number_of_divisions)\n\n xvalue = np.sqrt(1 - zvalue ** 2) * np.cos(angle)\n yvalue = np.sqrt(1 - zvalue ** 2) * np.sin(angle)\n\n # get prob and angle - prob will be shade and angle color\n prob = np.real(np.dot(state[i], state[i].conj()))\n if prob > 1: # See https://github.com/Qiskit/qiskit-terra/issues/4666\n prob = 1\n colorstate = phase_to_rgb(state[i])\n\n alfa = 1\n if yvalue >= 0.1:\n alfa = 1.0 - yvalue\n\n if not np.isclose(prob, 0) and show_state_labels:\n rprime = 1.3\n angle_theta = np.arctan2(np.sqrt(1 - zvalue ** 2), zvalue)\n xvalue_text = rprime * np.sin(angle_theta) * np.cos(angle)\n yvalue_text = rprime * np.sin(angle_theta) * np.sin(angle)\n zvalue_text = rprime * np.cos(angle_theta)\n element_text = '$\\\\vert' + element + '\\\\rangle$'\n if show_state_phases:\n element_angle = (np.angle(state[i]) + (np.pi * 4)) % (np.pi * 2)\n if use_degrees:\n element_text += '\\n$%.1f^\\\\circ$' % (element_angle * 180/np.pi)\n else:\n element_angle = pi_check(element_angle, ndigits=3).replace('pi', '\\\\pi')\n element_text += '\\n$%s$' % (element_angle)\n ax.text(xvalue_text, yvalue_text, zvalue_text, element_text,\n ha='center', va='center', size=12)\n\n ax.plot([xvalue], [yvalue], [zvalue],\n markerfacecolor=colorstate,\n markeredgecolor=colorstate,\n marker='o', markersize=np.sqrt(prob) * 30, alpha=alfa)\n\n a = Arrow3D([0, xvalue], [0, yvalue], [0, zvalue],\n mutation_scale=20, alpha=prob, arrowstyle=\"-\",\n color=colorstate, lw=2)\n ax.add_artist(a)\n\n # add weight lines\n for weight in range(d + 1):\n theta = np.linspace(-2 * np.pi, 2 * np.pi, 100)\n z = -2 * weight / d + 1\n r = np.sqrt(1 - z ** 2)\n x = r * np.cos(theta)\n y = r * np.sin(theta)\n ax.plot(x, y, z, color=(.5, .5, .5), lw=1, ls=':', alpha=.5)\n\n # add center point\n ax.plot([0], [0], [0], markerfacecolor=(.5, .5, .5),\n markeredgecolor=(.5, .5, .5), marker='o', markersize=3,\n alpha=1)\n else:\n break\n\n n = 64\n theta = np.ones(n)\n\n ax2 = fig.add_subplot(gs[2:, 2:])\n ax2.pie(theta, colors=sns.color_palette(\"hls\", n), radius=0.75)\n ax2.add_artist(Circle((0, 0), 0.5, color=plt.rcParams['figure.facecolor'], zorder=1))\n offset = 0.95 # since radius of sphere is one.\n\n if use_degrees:\n labels = ['Phase\\n(Deg)', '0', '90', '180 ', '270']\n else:\n labels = ['Phase', '$0$', '$\\\\pi/2$', '$\\\\pi$', '$3\\\\pi/2$']\n\n ax2.text(0, 0, labels[0], horizontalalignment='center',\n verticalalignment='center', fontsize=14)\n ax2.text(offset, 0, labels[1], horizontalalignment='center',\n verticalalignment='center', fontsize=14)\n ax2.text(0, offset, labels[2], horizontalalignment='center',\n verticalalignment='center', fontsize=14)\n ax2.text(-offset, 0, labels[3], horizontalalignment='center',\n verticalalignment='center', fontsize=14)\n ax2.text(0, -offset, labels[4], horizontalalignment='center',\n verticalalignment='center', fontsize=14)\n\n if return_fig:\n if get_backend() in ['module://ipykernel.pylab.backend_inline',\n 'nbAgg']:\n plt.close(fig)\n return fig\n\n\ndef generate_facecolors(x, y, z, dx, dy, dz, color):\n \"\"\"Generates shaded facecolors for shaded bars.\n\n This is here to work around a Matplotlib bug\n where alpha does not work in Bar3D.\n\n Args:\n x (array_like): The x- coordinates of the anchor point of the bars.\n y (array_like): The y- coordinates of the anchor point of the bars.\n z (array_like): The z- coordinates of the anchor point of the bars.\n dx (array_like): Width of bars.\n dy (array_like): Depth of bars.\n dz (array_like): Height of bars.\n color (array_like): sequence of valid color specifications, optional\n Returns:\n list: Shaded colors for bars.\n Raises:\n ImportError: If matplotlib is not installed\n \"\"\"\n if not HAS_MATPLOTLIB:\n raise ImportError('Must have Matplotlib installed. To install, run '\n '\"pip install matplotlib\".')\n import matplotlib.colors as mcolors\n\n cuboid = np.array([\n # -z\n (\n (0, 0, 0),\n (0, 1, 0),\n (1, 1, 0),\n (1, 0, 0),\n ),\n # +z\n (\n (0, 0, 1),\n (1, 0, 1),\n (1, 1, 1),\n (0, 1, 1),\n ),\n # -y\n (\n (0, 0, 0),\n (1, 0, 0),\n (1, 0, 1),\n (0, 0, 1),\n ),\n # +y\n (\n (0, 1, 0),\n (0, 1, 1),\n (1, 1, 1),\n (1, 1, 0),\n ),\n # -x\n (\n (0, 0, 0),\n (0, 0, 1),\n (0, 1, 1),\n (0, 1, 0),\n ),\n # +x\n (\n (1, 0, 0),\n (1, 1, 0),\n (1, 1, 1),\n (1, 0, 1),\n ),\n ])\n\n # indexed by [bar, face, vertex, coord]\n polys = np.empty(x.shape + cuboid.shape)\n # handle each coordinate separately\n for i, p, dp in [(0, x, dx), (1, y, dy), (2, z, dz)]:\n p = p[..., np.newaxis, np.newaxis]\n dp = dp[..., np.newaxis, np.newaxis]\n polys[..., i] = p + dp * cuboid[..., i]\n\n # collapse the first two axes\n polys = polys.reshape((-1,) + polys.shape[2:])\n\n facecolors = []\n if len(color) == len(x):\n # bar colors specified, need to expand to number of faces\n for c in color:\n facecolors.extend([c] * 6)\n else:\n # a single color specified, or face colors specified explicitly\n facecolors = list(mcolors.to_rgba_array(color))\n if len(facecolors) < len(x):\n facecolors *= (6 * len(x))\n\n normals = _generate_normals(polys)\n return _shade_colors(facecolors, normals)\n\n\ndef _generate_normals(polygons):\n \"\"\"Takes a list of polygons and return an array of their normals.\n\n Normals point towards the viewer for a face with its vertices in\n counterclockwise order, following the right hand rule.\n Uses three points equally spaced around the polygon.\n This normal of course might not make sense for polygons with more than\n three points not lying in a plane, but it's a plausible and fast\n approximation.\n\n Args:\n polygons (list): list of (M_i, 3) array_like, or (..., M, 3) array_like\n A sequence of polygons to compute normals for, which can have\n varying numbers of vertices. If the polygons all have the same\n number of vertices and array is passed, then the operation will\n be vectorized.\n Returns:\n normals: (..., 3) array_like\n A normal vector estimated for the polygon.\n \"\"\"\n if isinstance(polygons, np.ndarray):\n # optimization: polygons all have the same number of points, so can\n # vectorize\n n = polygons.shape[-2]\n i1, i2, i3 = 0, n//3, 2*n//3\n v1 = polygons[..., i1, :] - polygons[..., i2, :]\n v2 = polygons[..., i2, :] - polygons[..., i3, :]\n else:\n # The subtraction doesn't vectorize because polygons is jagged.\n v1 = np.empty((len(polygons), 3))\n v2 = np.empty((len(polygons), 3))\n for poly_i, ps in enumerate(polygons):\n n = len(ps)\n i1, i2, i3 = 0, n//3, 2*n//3\n v1[poly_i, :] = ps[i1, :] - ps[i2, :]\n v2[poly_i, :] = ps[i2, :] - ps[i3, :]\n\n return np.cross(v1, v2)\n\n\ndef _shade_colors(color, normals, lightsource=None):\n \"\"\"\n Shade *color* using normal vectors given by *normals*.\n *color* can also be an array of the same length as *normals*.\n \"\"\"\n if not HAS_MATPLOTLIB:\n raise ImportError('Must have Matplotlib installed. To install, run '\n '\"pip install matplotlib\".')\n\n from matplotlib.colors import Normalize, LightSource\n import matplotlib.colors as mcolors\n\n if lightsource is None:\n # chosen for backwards-compatibility\n lightsource = LightSource(azdeg=225, altdeg=19.4712)\n\n def mod(v):\n return np.sqrt(v[0] ** 2 + v[1] ** 2 + v[2] ** 2)\n\n shade = np.array([np.dot(n / mod(n), lightsource.direction)\n if mod(n) else np.nan for n in normals])\n mask = ~np.isnan(shade)\n\n if mask.any():\n norm = Normalize(min(shade[mask]), max(shade[mask]))\n shade[~mask] = min(shade[mask])\n color = mcolors.to_rgba_array(color)\n # shape of color should be (M, 4) (where M is number of faces)\n # shape of shade should be (M,)\n # colors should have final shape of (M, 4)\n alpha = color[:, 3]\n colors = (0.5 + norm(shade)[:, np.newaxis] * 0.5) * color\n colors[:, 3] = alpha\n else:\n colors = np.asanyarray(color).copy()\n\n return colors\n"
] |
[
[
"matplotlib.patches.Ellipse",
"matplotlib.patches.FancyArrow",
"numpy.asarray",
"matplotlib.pyplot.Line2D",
"matplotlib.pyplot.subplots",
"matplotlib.get_backend",
"numpy.max",
"matplotlib.colorbar.ColorbarBase",
"matplotlib.pyplot.subplot",
"numpy.mean",
"matplotlib.gridspec.GridSpec",
"matplotlib.ticker.MaxNLocator",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure"
],
[
"numpy.imag",
"numpy.sqrt",
"numpy.linspace",
"numpy.max",
"numpy.cross",
"matplotlib.patches.FancyArrowPatch.__init__",
"numpy.exp",
"numpy.ones_like",
"numpy.arange",
"numpy.sin",
"scipy.linalg.eigh",
"numpy.real",
"numpy.size",
"numpy.asanyarray",
"matplotlib.gridspec.GridSpec",
"matplotlib.pyplot.close",
"numpy.zeros",
"matplotlib.pyplot.NullLocator",
"matplotlib.pyplot.figure",
"numpy.isclose",
"numpy.log",
"numpy.min",
"numpy.isnan",
"matplotlib.patches.Circle",
"matplotlib.colors.LightSource",
"matplotlib.get_backend",
"numpy.ndenumerate",
"numpy.array",
"numpy.meshgrid",
"matplotlib.patches.FancyArrowPatch.draw",
"matplotlib.pyplot.Rectangle",
"matplotlib.pyplot.figaspect",
"numpy.absolute",
"numpy.abs",
"matplotlib.pyplot.subplots",
"numpy.cos",
"numpy.ones",
"numpy.angle",
"numpy.empty",
"matplotlib.colors.to_rgba_array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"0.14",
"0.15",
"0.12",
"0.10"
],
"tensorflow": []
}
] |
maldins46/CovidTracker
|
[
"6a50e780935de62e07c691fae2363c290aae5795"
] |
[
"chart-generation/charts/vaccines.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCharts about the national vaccines data.\n@author: riccardomaldini\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mtick\nfrom data_extractors.vaccines_regions import benchmark_dict, marche_df\nfrom data_extractors.vaccines_italy import italy_df\nfrom data_extractors.area_names import area_names_dict\nfrom matplotlib.dates import MonthLocator\nimport utils\n\n\ndef adm_doses_italy(save_image=False, show=False):\n \"\"\"\n Administration data about Italy.\n \"\"\"\n\n # plt.stackplot(data['data_somministrazione'], data['prima_dose'],data['seconda_dose'],\n # labels=['Prime dosi', 'Seconde dosi'])\n plt.bar(italy_df['data_somministrazione'], italy_df['prima_dose'], label='Prime dosi')\n plt.bar(italy_df['data_somministrazione'], italy_df['seconda_dose'], bottom=italy_df['prima_dose'],\n label='Seconde dosi')\n\n plt.title(\"Somministrazioni giornaliere Italia,\\ncon distinzione prima dose/richiamo\\n\")\n plt.gca().xaxis.set_major_locator(MonthLocator())\n plt.gca().xaxis.set_minor_locator(MonthLocator(bymonthday=15))\n plt.gca().xaxis.set_major_formatter(utils.std_date_formatter)\n plt.gca().xaxis.set_minor_formatter(utils.std_date_formatter)\n plt.gcf().autofmt_xdate(which='both')\n plt.grid(True, which='both', axis='both')\n plt.legend(loc='upper left')\n\n if save_image:\n plt.savefig('./charts/vaccines/dosi_italia.png', dpi=300, transparent=True, bbox_inches='tight')\n\n if show:\n plt.show()\n\n plt.close()\n\n\ndef adm_doses_marche(save_image=False, show=False):\n \"\"\"\n Administration data about Italy.\n \"\"\"\n\n plt.bar(marche_df['data_somministrazione'], marche_df['prima_dose'], label='Prime dosi')\n plt.bar(marche_df['data_somministrazione'], marche_df['seconda_dose'], bottom=marche_df['prima_dose'],\n label='Seconde dosi')\n\n plt.title(\"Somministrazioni giornaliere Marche,\\ncon distinzione prima dose/richiamo\\n\")\n plt.gca().xaxis.set_major_locator(MonthLocator())\n plt.gca().xaxis.set_minor_locator(MonthLocator(bymonthday=15))\n plt.gca().xaxis.set_major_formatter(utils.std_date_formatter)\n plt.gca().xaxis.set_minor_formatter(utils.std_date_formatter)\n plt.gcf().autofmt_xdate(which='both')\n plt.grid(True, which='both', axis='both')\n plt.legend(loc='upper left')\n\n if save_image:\n plt.savefig('./charts/vaccines/dosi_marche.png', dpi=300, transparent=True, bbox_inches='tight')\n\n if show:\n plt.show()\n\n plt.close()\n\n\ndef regional_doses(save_image=False, show=False):\n \"\"\"\n Comparation between doses administrated in various regions\n \"\"\"\n\n for area_code, region_data in benchmark_dict.items():\n rolling_avg_adm = region_data['totale_per_100000_ab'].rolling(7, center=True).mean()\n plt.plot(region_data['data_somministrazione'], rolling_avg_adm, label=area_names_dict[area_code])\n\n rolling_avg_adm = italy_df['totale_per_100000_ab'].rolling(7, center=True).mean()\n plt.plot(italy_df['data_somministrazione'], rolling_avg_adm, alpha=0.5, linestyle=':',\n label=\"Italia\")\n\n plt.title('Andamento delle somministrazioni giornaliere\\nper 100.000 abitanti, confronto tra le regioni del benchmark\\n')\n plt.gca().xaxis.set_major_locator(MonthLocator())\n plt.gca().xaxis.set_minor_locator(MonthLocator(bymonthday=15))\n plt.gca().xaxis.set_major_formatter(utils.std_date_formatter)\n plt.gca().xaxis.set_minor_formatter(utils.std_date_formatter)\n plt.gcf().autofmt_xdate(which='both')\n plt.grid(True, which='both', axis='both')\n plt.legend(loc='upper left')\n\n if save_image:\n plt.savefig('./charts/vaccines/dosi_per_regioni.png', dpi=300, transparent=True, bbox_inches='tight')\n\n if show:\n plt.show()\n\n plt.close()\n\n\ndef immunes_percentage(save_image=False, show=False):\n \"\"\"\n Computes and plots relations between the population of a place and people that took the second shot.\n \"\"\"\n\n for area_code, region_data in benchmark_dict.items():\n plt.plot(region_data['data_somministrazione'], region_data['seconda_dose_totale_storico_su_pop'],\n label=area_names_dict[area_code])\n\n plt.plot(italy_df['data_somministrazione'], italy_df['seconda_dose_totale_storico_su_pop'], alpha=0.5, linestyle=':',\n label=\"Italia\")\n\n plt.title('Percentuale popolazione immunizzata,\\nconfronto tra le regioni del benchmark\\n')\n plt.gca().yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1))\n plt.gca().xaxis.set_major_locator(MonthLocator())\n plt.gca().xaxis.set_minor_locator(MonthLocator(bymonthday=15))\n plt.gca().xaxis.set_major_formatter(utils.std_date_formatter)\n plt.gca().xaxis.set_minor_formatter(utils.std_date_formatter)\n plt.gcf().autofmt_xdate(which='both')\n plt.grid(True, which='both', axis='both')\n plt.legend(loc='upper left')\n\n if save_image:\n plt.savefig('./charts/vaccines/immunizzati.png', dpi=300, transparent=True, bbox_inches='tight')\n\n if show:\n plt.show()\n\n plt.close()\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.title",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.show",
"matplotlib.dates.MonthLocator",
"matplotlib.ticker.PercentFormatter"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
SuwoongHeo/models
|
[
"10ef6bbe39bb5ac3d0e2755dc60b6843d39d395c"
] |
[
"official/vision/beta/modeling/layers/detection_generator.py"
] |
[
"# Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Contains definitions of generators to generate the final detections.\"\"\"\nimport contextlib\nfrom typing import List, Optional, Mapping\n# Import libraries\nimport tensorflow as tf\n\nfrom official.vision.beta.ops import box_ops\nfrom official.vision.beta.ops import nms\nfrom official.vision.beta.ops import preprocess_ops\n\n\ndef _generate_detections_v1(boxes: tf.Tensor,\n scores: tf.Tensor,\n attributes: Optional[Mapping[str,\n tf.Tensor]] = None,\n pre_nms_top_k: int = 5000,\n pre_nms_score_threshold: float = 0.05,\n nms_iou_threshold: float = 0.5,\n max_num_detections: int = 100,\n soft_nms_sigma: Optional[float] = None):\n \"\"\"Generates the final detections given the model outputs.\n\n The implementation unrolls the batch dimension and process images one by one.\n It required the batch dimension to be statically known and it is TPU\n compatible.\n\n Args:\n boxes: A `tf.Tensor` with shape `[batch_size, N, num_classes, 4]` or\n `[batch_size, N, 1, 4]` for box predictions on all feature levels. The\n N is the number of total anchors on all levels.\n scores: A `tf.Tensor` with shape `[batch_size, N, num_classes]`, which\n stacks class probability on all feature levels. The N is the number of\n total anchors on all levels. The num_classes is the number of classes\n predicted by the model. Note that the class_outputs here is the raw score.\n attributes: None or a dict of (attribute_name, attributes) pairs. Each\n attributes is a `tf.Tensor` with shape\n `[batch_size, N, num_classes, attribute_size]` or\n `[batch_size, N, 1, attribute_size]` for attribute predictions on all\n feature levels. The N is the number of total anchors on all levels. Can\n be None if no attribute learning is required.\n pre_nms_top_k: An `int` number of top candidate detections per class before\n NMS.\n pre_nms_score_threshold: A `float` representing the threshold for deciding\n when to remove boxes based on score.\n nms_iou_threshold: A `float` representing the threshold for deciding whether\n boxes overlap too much with respect to IOU.\n max_num_detections: A scalar representing maximum number of boxes retained\n over all classes.\n soft_nms_sigma: A `float` representing the sigma parameter for Soft NMS.\n When soft_nms_sigma=0.0 (which is default), we fall back to standard NMS.\n\n Returns:\n nms_boxes: A `float` type `tf.Tensor` of shape\n `[batch_size, max_num_detections, 4]` representing top detected boxes in\n `[y1, x1, y2, x2]`.\n nms_scores: A `float` type `tf.Tensor` of shape\n `[batch_size, max_num_detections]` representing sorted confidence scores\n for detected boxes. The values are between `[0, 1]`.\n nms_classes: An `int` type `tf.Tensor` of shape\n `[batch_size, max_num_detections]` representing classes for detected\n boxes.\n valid_detections: An `int` type `tf.Tensor` of shape `[batch_size]` only the\n top `valid_detections` boxes are valid detections.\n nms_attributes: None or a dict of (attribute_name, attributes). Each\n attribute is a `float` type `tf.Tensor` of shape\n `[batch_size, max_num_detections, attribute_size]` representing attribute\n predictions for detected boxes. Can be an empty dict if no attribute\n learning is required.\n \"\"\"\n with tf.name_scope('generate_detections'):\n batch_size = scores.get_shape().as_list()[0]\n nmsed_boxes = []\n nmsed_classes = []\n nmsed_scores = []\n valid_detections = []\n if attributes:\n nmsed_attributes = {att_name: [] for att_name in attributes.keys()}\n else:\n nmsed_attributes = {}\n\n for i in range(batch_size):\n (nmsed_boxes_i, nmsed_scores_i, nmsed_classes_i, valid_detections_i,\n nmsed_att_i) = _generate_detections_per_image(\n boxes[i],\n scores[i],\n attributes={\n att_name: att[i] for att_name, att in attributes.items()\n } if attributes else {},\n pre_nms_top_k=pre_nms_top_k,\n pre_nms_score_threshold=pre_nms_score_threshold,\n nms_iou_threshold=nms_iou_threshold,\n max_num_detections=max_num_detections,\n soft_nms_sigma=soft_nms_sigma)\n nmsed_boxes.append(nmsed_boxes_i)\n nmsed_scores.append(nmsed_scores_i)\n nmsed_classes.append(nmsed_classes_i)\n valid_detections.append(valid_detections_i)\n if attributes:\n for att_name in attributes.keys():\n nmsed_attributes[att_name].append(nmsed_att_i[att_name])\n\n nmsed_boxes = tf.stack(nmsed_boxes, axis=0)\n nmsed_scores = tf.stack(nmsed_scores, axis=0)\n nmsed_classes = tf.stack(nmsed_classes, axis=0)\n valid_detections = tf.stack(valid_detections, axis=0)\n if attributes:\n for att_name in attributes.keys():\n nmsed_attributes[att_name] = tf.stack(nmsed_attributes[att_name], axis=0)\n\n return nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections, nmsed_attributes\n\n\ndef _generate_detections_per_image(\n boxes: tf.Tensor,\n scores: tf.Tensor,\n attributes: Optional[Mapping[str, tf.Tensor]] = None,\n pre_nms_top_k: int = 5000,\n pre_nms_score_threshold: float = 0.05,\n nms_iou_threshold: float = 0.5,\n max_num_detections: int = 100,\n soft_nms_sigma: Optional[float] = None):\n \"\"\"Generates the final detections per image given the model outputs.\n\n Args:\n boxes: A `tf.Tensor` with shape `[N, num_classes, 4]` or `[N, 1, 4]`, which\n box predictions on all feature levels. The N is the number of total\n anchors on all levels.\n scores: A `tf.Tensor` with shape `[N, num_classes]`, which stacks class\n probability on all feature levels. The N is the number of total anchors on\n all levels. The num_classes is the number of classes predicted by the\n model. Note that the class_outputs here is the raw score.\n attributes: If not None, a dict of `tf.Tensor`. Each value is in shape\n `[N, num_classes, attribute_size]` or `[N, 1, attribute_size]` of\n attribute predictions on all feature levels. The N is the number of total\n anchors on all levels.\n pre_nms_top_k: An `int` number of top candidate detections per class before\n NMS.\n pre_nms_score_threshold: A `float` representing the threshold for deciding\n when to remove boxes based on score.\n nms_iou_threshold: A `float` representing the threshold for deciding whether\n boxes overlap too much with respect to IOU.\n max_num_detections: A `scalar` representing maximum number of boxes retained\n over all classes.\n soft_nms_sigma: A `float` representing the sigma parameter for Soft NMS.\n When soft_nms_sigma=0.0, we fall back to standard NMS.\n If set to None, `tf.image.non_max_suppression_padded` is called instead.\n\n Returns:\n nms_boxes: A `float` tf.Tensor of shape `[max_num_detections, 4]`\n representing top detected boxes in `[y1, x1, y2, x2]`.\n nms_scores: A `float` tf.Tensor of shape `[max_num_detections]` representing\n sorted confidence scores for detected boxes. The values are between [0,\n 1].\n nms_classes: An `int` tf.Tensor of shape `[max_num_detections]` representing\n classes for detected boxes.\n valid_detections: An `int` tf.Tensor of shape [1] only the top\n `valid_detections` boxes are valid detections.\n nms_attributes: None or a dict. Each value is a `float` tf.Tensor of shape\n `[max_num_detections, attribute_size]` representing attribute predictions\n for detected boxes. Can be an empty dict if `attributes` is None.\n \"\"\"\n nmsed_boxes = []\n nmsed_scores = []\n nmsed_classes = []\n num_classes_for_box = boxes.get_shape().as_list()[1]\n num_classes = scores.get_shape().as_list()[1]\n if attributes:\n nmsed_attributes = {att_name: [] for att_name in attributes.keys()}\n else:\n nmsed_attributes = {}\n\n for i in range(num_classes):\n boxes_i = boxes[:, min(num_classes_for_box - 1, i)]\n scores_i = scores[:, i]\n # Obtains pre_nms_top_k before running NMS.\n scores_i, indices = tf.nn.top_k(\n scores_i, k=tf.minimum(tf.shape(scores_i)[-1], pre_nms_top_k))\n boxes_i = tf.gather(boxes_i, indices)\n\n if soft_nms_sigma is not None:\n (nmsed_indices_i,\n nmsed_scores_i) = tf.image.non_max_suppression_with_scores(\n tf.cast(boxes_i, tf.float32),\n tf.cast(scores_i, tf.float32),\n max_num_detections,\n iou_threshold=nms_iou_threshold,\n score_threshold=pre_nms_score_threshold,\n soft_nms_sigma=soft_nms_sigma,\n name='nms_detections_' + str(i))\n nmsed_boxes_i = tf.gather(boxes_i, nmsed_indices_i)\n nmsed_boxes_i = preprocess_ops.clip_or_pad_to_fixed_size(\n nmsed_boxes_i, max_num_detections, 0.0)\n nmsed_scores_i = preprocess_ops.clip_or_pad_to_fixed_size(\n nmsed_scores_i, max_num_detections, -1.0)\n else:\n (nmsed_indices_i,\n nmsed_num_valid_i) = tf.image.non_max_suppression_padded(\n tf.cast(boxes_i, tf.float32),\n tf.cast(scores_i, tf.float32),\n max_num_detections,\n iou_threshold=nms_iou_threshold,\n score_threshold=pre_nms_score_threshold,\n pad_to_max_output_size=True,\n name='nms_detections_' + str(i))\n nmsed_boxes_i = tf.gather(boxes_i, nmsed_indices_i)\n nmsed_scores_i = tf.gather(scores_i, nmsed_indices_i)\n # Sets scores of invalid boxes to -1.\n nmsed_scores_i = tf.where(\n tf.less(tf.range(max_num_detections), [nmsed_num_valid_i]),\n nmsed_scores_i, -tf.ones_like(nmsed_scores_i))\n\n nmsed_classes_i = tf.fill([max_num_detections], i)\n nmsed_boxes.append(nmsed_boxes_i)\n nmsed_scores.append(nmsed_scores_i)\n nmsed_classes.append(nmsed_classes_i)\n if attributes:\n for att_name, att in attributes.items():\n num_classes_for_attr = att.get_shape().as_list()[1]\n att_i = att[:, min(num_classes_for_attr - 1, i)]\n att_i = tf.gather(att_i, indices)\n nmsed_att_i = tf.gather(att_i, nmsed_indices_i)\n nmsed_att_i = preprocess_ops.clip_or_pad_to_fixed_size(\n nmsed_att_i, max_num_detections, 0.0)\n nmsed_attributes[att_name].append(nmsed_att_i)\n\n # Concats results from all classes and sort them.\n nmsed_boxes = tf.concat(nmsed_boxes, axis=0)\n nmsed_scores = tf.concat(nmsed_scores, axis=0)\n nmsed_classes = tf.concat(nmsed_classes, axis=0)\n nmsed_scores, indices = tf.nn.top_k(\n nmsed_scores, k=max_num_detections, sorted=True)\n nmsed_boxes = tf.gather(nmsed_boxes, indices)\n nmsed_classes = tf.gather(nmsed_classes, indices)\n valid_detections = tf.reduce_sum(\n tf.cast(tf.greater(nmsed_scores, -1), tf.int32))\n if attributes:\n for att_name in attributes.keys():\n nmsed_attributes[att_name] = tf.concat(nmsed_attributes[att_name], axis=0)\n nmsed_attributes[att_name] = tf.gather(nmsed_attributes[att_name],\n indices)\n\n return nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections, nmsed_attributes\n\n\ndef _select_top_k_scores(scores_in: tf.Tensor, pre_nms_num_detections: int):\n \"\"\"Selects top_k scores and indices for each class.\n\n Args:\n scores_in: A `tf.Tensor` with shape `[batch_size, N, num_classes]`, which\n stacks class logit outputs on all feature levels. The N is the number of\n total anchors on all levels. The num_classes is the number of classes\n predicted by the model.\n pre_nms_num_detections: Number of candidates before NMS.\n\n Returns:\n scores and indices: A `tf.Tensor` with shape\n `[batch_size, pre_nms_num_detections, num_classes]`.\n \"\"\"\n batch_size, num_anchors, num_class = scores_in.get_shape().as_list()\n if batch_size is None:\n batch_size = tf.shape(scores_in)[0]\n scores_trans = tf.transpose(scores_in, perm=[0, 2, 1])\n scores_trans = tf.reshape(scores_trans, [-1, num_anchors])\n\n top_k_scores, top_k_indices = tf.nn.top_k(\n scores_trans, k=pre_nms_num_detections, sorted=True)\n\n top_k_scores = tf.reshape(top_k_scores,\n [batch_size, num_class, pre_nms_num_detections])\n top_k_indices = tf.reshape(top_k_indices,\n [batch_size, num_class, pre_nms_num_detections])\n\n return tf.transpose(top_k_scores,\n [0, 2, 1]), tf.transpose(top_k_indices, [0, 2, 1])\n\n\ndef _generate_detections_v2(boxes: tf.Tensor,\n scores: tf.Tensor,\n pre_nms_top_k: int = 5000,\n pre_nms_score_threshold: float = 0.05,\n nms_iou_threshold: float = 0.5,\n max_num_detections: int = 100):\n \"\"\"Generates the final detections given the model outputs.\n\n This implementation unrolls classes dimension while using the tf.while_loop\n to implement the batched NMS, so that it can be parallelized at the batch\n dimension. It should give better performance comparing to v1 implementation.\n It is TPU compatible.\n\n Args:\n boxes: A `tf.Tensor` with shape `[batch_size, N, num_classes, 4]` or\n `[batch_size, N, 1, 4]`, which box predictions on all feature levels. The\n N is the number of total anchors on all levels.\n scores: A `tf.Tensor` with shape `[batch_size, N, num_classes]`, which\n stacks class probability on all feature levels. The N is the number of\n total anchors on all levels. The num_classes is the number of classes\n predicted by the model. Note that the class_outputs here is the raw score.\n pre_nms_top_k: An `int` number of top candidate detections per class before\n NMS.\n pre_nms_score_threshold: A `float` representing the threshold for deciding\n when to remove boxes based on score.\n nms_iou_threshold: A `float` representing the threshold for deciding whether\n boxes overlap too much with respect to IOU.\n max_num_detections: A `scalar` representing maximum number of boxes retained\n over all classes.\n\n Returns:\n nms_boxes: A `float` tf.Tensor of shape [batch_size, max_num_detections, 4]\n representing top detected boxes in [y1, x1, y2, x2].\n nms_scores: A `float` tf.Tensor of shape [batch_size, max_num_detections]\n representing sorted confidence scores for detected boxes. The values are\n between [0, 1].\n nms_classes: An `int` tf.Tensor of shape [batch_size, max_num_detections]\n representing classes for detected boxes.\n valid_detections: An `int` tf.Tensor of shape [batch_size] only the top\n `valid_detections` boxes are valid detections.\n \"\"\"\n with tf.name_scope('generate_detections'):\n nmsed_boxes = []\n nmsed_classes = []\n nmsed_scores = []\n valid_detections = []\n batch_size, _, num_classes_for_box, _ = boxes.get_shape().as_list()\n if batch_size is None:\n batch_size = tf.shape(boxes)[0]\n _, total_anchors, num_classes = scores.get_shape().as_list()\n # Selects top pre_nms_num scores and indices before NMS.\n scores, indices = _select_top_k_scores(\n scores, min(total_anchors, pre_nms_top_k))\n for i in range(num_classes):\n boxes_i = boxes[:, :, min(num_classes_for_box - 1, i), :]\n scores_i = scores[:, :, i]\n # Obtains pre_nms_top_k before running NMS.\n boxes_i = tf.gather(boxes_i, indices[:, :, i], batch_dims=1, axis=1)\n\n # Filter out scores.\n boxes_i, scores_i = box_ops.filter_boxes_by_scores(\n boxes_i, scores_i, min_score_threshold=pre_nms_score_threshold)\n\n (nmsed_scores_i, nmsed_boxes_i) = nms.sorted_non_max_suppression_padded(\n tf.cast(scores_i, tf.float32),\n tf.cast(boxes_i, tf.float32),\n max_num_detections,\n iou_threshold=nms_iou_threshold)\n nmsed_classes_i = tf.fill([batch_size, max_num_detections], i)\n nmsed_boxes.append(nmsed_boxes_i)\n nmsed_scores.append(nmsed_scores_i)\n nmsed_classes.append(nmsed_classes_i)\n nmsed_boxes = tf.concat(nmsed_boxes, axis=1)\n nmsed_scores = tf.concat(nmsed_scores, axis=1)\n nmsed_classes = tf.concat(nmsed_classes, axis=1)\n nmsed_scores, indices = tf.nn.top_k(\n nmsed_scores, k=max_num_detections, sorted=True)\n nmsed_boxes = tf.gather(nmsed_boxes, indices, batch_dims=1, axis=1)\n nmsed_classes = tf.gather(nmsed_classes, indices, batch_dims=1)\n valid_detections = tf.reduce_sum(\n input_tensor=tf.cast(tf.greater(nmsed_scores, -1), tf.int32), axis=1)\n return nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections\n\n\ndef _generate_detections_batched(boxes: tf.Tensor, scores: tf.Tensor,\n pre_nms_score_threshold: float,\n nms_iou_threshold: float,\n max_num_detections: int):\n \"\"\"Generates detected boxes with scores and classes for one-stage detector.\n\n The function takes output of multi-level ConvNets and anchor boxes and\n generates detected boxes. Note that this used batched nms, which is not\n supported on TPU currently.\n\n Args:\n boxes: A `tf.Tensor` with shape `[batch_size, N, num_classes, 4]` or\n `[batch_size, N, 1, 4]`, which box predictions on all feature levels. The\n N is the number of total anchors on all levels.\n scores: A `tf.Tensor` with shape `[batch_size, N, num_classes]`, which\n stacks class probability on all feature levels. The N is the number of\n total anchors on all levels. The num_classes is the number of classes\n predicted by the model. Note that the class_outputs here is the raw score.\n pre_nms_score_threshold: A `float` representing the threshold for deciding\n when to remove boxes based on score.\n nms_iou_threshold: A `float` representing the threshold for deciding whether\n boxes overlap too much with respect to IOU.\n max_num_detections: A `scalar` representing maximum number of boxes retained\n over all classes.\n\n Returns:\n nms_boxes: A `float` tf.Tensor of shape [batch_size, max_num_detections, 4]\n representing top detected boxes in [y1, x1, y2, x2].\n nms_scores: A `float` tf.Tensor of shape [batch_size, max_num_detections]\n representing sorted confidence scores for detected boxes. The values are\n between [0, 1].\n nms_classes: An `int` tf.Tensor of shape [batch_size, max_num_detections]\n representing classes for detected boxes.\n valid_detections: An `int` tf.Tensor of shape [batch_size] only the top\n `valid_detections` boxes are valid detections.\n \"\"\"\n with tf.name_scope('generate_detections'):\n nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections = (\n tf.image.combined_non_max_suppression(\n boxes,\n scores,\n max_output_size_per_class=max_num_detections,\n max_total_size=max_num_detections,\n iou_threshold=nms_iou_threshold,\n score_threshold=pre_nms_score_threshold,\n pad_per_class=False,\n clip_boxes=False))\n nmsed_classes = tf.cast(nmsed_classes, tf.int32)\n return nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections\n\n\[email protected]_keras_serializable(package='Vision')\nclass DetectionGenerator(tf.keras.layers.Layer):\n \"\"\"Generates the final detected boxes with scores and classes.\"\"\"\n\n def __init__(self,\n apply_nms: bool = True,\n pre_nms_top_k: int = 5000,\n pre_nms_score_threshold: float = 0.05,\n nms_iou_threshold: float = 0.5,\n max_num_detections: int = 100,\n nms_version: str = 'v2',\n use_cpu_nms: bool = False,\n soft_nms_sigma: Optional[float] = None,\n **kwargs):\n \"\"\"Initializes a detection generator.\n\n Args:\n apply_nms: A `bool` of whether or not apply non maximum suppression.\n If False, the decoded boxes and their scores are returned.\n pre_nms_top_k: An `int` of the number of top scores proposals to be kept\n before applying NMS.\n pre_nms_score_threshold: A `float` of the score threshold to apply before\n applying NMS. Proposals whose scores are below this threshold are\n thrown away.\n nms_iou_threshold: A `float` in [0, 1], the NMS IoU threshold.\n max_num_detections: An `int` of the final number of total detections to\n generate.\n nms_version: A string of `batched`, `v1` or `v2` specifies NMS version.\n use_cpu_nms: A `bool` of whether or not enforce NMS to run on CPU.\n soft_nms_sigma: A `float` representing the sigma parameter for Soft NMS.\n When soft_nms_sigma=0.0, we fall back to standard NMS.\n **kwargs: Additional keyword arguments passed to Layer.\n \"\"\"\n self._config_dict = {\n 'apply_nms': apply_nms,\n 'pre_nms_top_k': pre_nms_top_k,\n 'pre_nms_score_threshold': pre_nms_score_threshold,\n 'nms_iou_threshold': nms_iou_threshold,\n 'max_num_detections': max_num_detections,\n 'nms_version': nms_version,\n 'use_cpu_nms': use_cpu_nms,\n 'soft_nms_sigma': soft_nms_sigma,\n }\n super(DetectionGenerator, self).__init__(**kwargs)\n\n def __call__(self,\n raw_boxes: tf.Tensor,\n raw_scores: tf.Tensor,\n anchor_boxes: tf.Tensor,\n image_shape: tf.Tensor,\n regression_weights: Optional[List[float]] = None,\n bbox_per_class: bool = True):\n \"\"\"Generates final detections.\n\n Args:\n raw_boxes: A `tf.Tensor` of shape of `[batch_size, K, num_classes * 4]`\n representing the class-specific box coordinates relative to anchors.\n raw_scores: A `tf.Tensor` of shape of `[batch_size, K, num_classes]`\n representing the class logits before applying score activiation.\n anchor_boxes: A `tf.Tensor` of shape of `[batch_size, K, 4]` representing\n the corresponding anchor boxes w.r.t `box_outputs`.\n image_shape: A `tf.Tensor` of shape of `[batch_size, 2]` storing the image\n height and width w.r.t. the scaled image, i.e. the same image space as\n `box_outputs` and `anchor_boxes`.\n regression_weights: A list of four float numbers to scale coordinates.\n bbox_per_class: A `bool`. If True, perform per-class box regression.\n\n Returns:\n If `apply_nms` = True, the return is a dictionary with keys:\n `detection_boxes`: A `float` tf.Tensor of shape\n [batch, max_num_detections, 4] representing top detected boxes in\n [y1, x1, y2, x2].\n `detection_scores`: A `float` `tf.Tensor` of shape\n [batch, max_num_detections] representing sorted confidence scores for\n detected boxes. The values are between [0, 1].\n `detection_classes`: An `int` tf.Tensor of shape\n [batch, max_num_detections] representing classes for detected boxes.\n `num_detections`: An `int` tf.Tensor of shape [batch] only the first\n `num_detections` boxes are valid detections\n If `apply_nms` = False, the return is a dictionary with keys:\n `decoded_boxes`: A `float` tf.Tensor of shape [batch, num_raw_boxes, 4]\n representing all the decoded boxes.\n `decoded_box_scores`: A `float` tf.Tensor of shape\n [batch, num_raw_boxes] representing socres of all the decoded boxes.\n \"\"\"\n box_scores = tf.nn.softmax(raw_scores, axis=-1)\n\n # Removes the background class.\n box_scores_shape = tf.shape(box_scores)\n box_scores_shape_list = box_scores.get_shape().as_list()\n batch_size = box_scores_shape[0]\n num_locations = box_scores_shape_list[1]\n num_classes = box_scores_shape_list[-1]\n\n box_scores = tf.slice(box_scores, [0, 0, 1], [-1, -1, -1])\n\n if bbox_per_class:\n num_detections = num_locations * (num_classes - 1)\n raw_boxes = tf.reshape(raw_boxes,\n [batch_size, num_locations, num_classes, 4])\n raw_boxes = tf.slice(raw_boxes, [0, 0, 1, 0], [-1, -1, -1, -1])\n anchor_boxes = tf.tile(\n tf.expand_dims(anchor_boxes, axis=2), [1, 1, num_classes - 1, 1])\n raw_boxes = tf.reshape(raw_boxes, [batch_size, num_detections, 4])\n anchor_boxes = tf.reshape(anchor_boxes, [batch_size, num_detections, 4])\n\n # Box decoding.\n decoded_boxes = box_ops.decode_boxes(\n raw_boxes, anchor_boxes, weights=regression_weights)\n\n # Box clipping\n decoded_boxes = box_ops.clip_boxes(\n decoded_boxes, tf.expand_dims(image_shape, axis=1))\n\n if bbox_per_class:\n decoded_boxes = tf.reshape(\n decoded_boxes, [batch_size, num_locations, num_classes - 1, 4])\n else:\n decoded_boxes = tf.expand_dims(decoded_boxes, axis=2)\n\n if not self._config_dict['apply_nms']:\n return {\n 'decoded_boxes': decoded_boxes,\n 'decoded_box_scores': box_scores,\n }\n\n # Optionally force the NMS be run on CPU.\n if self._config_dict['use_cpu_nms']:\n nms_context = tf.device('cpu:0')\n else:\n nms_context = contextlib.nullcontext()\n\n with nms_context:\n if self._config_dict['nms_version'] == 'batched':\n (nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections) = (\n _generate_detections_batched(\n decoded_boxes, box_scores,\n self._config_dict['pre_nms_score_threshold'],\n self._config_dict['nms_iou_threshold'],\n self._config_dict['max_num_detections']))\n elif self._config_dict['nms_version'] == 'v1':\n (nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections, _) = (\n _generate_detections_v1(\n decoded_boxes,\n box_scores,\n pre_nms_top_k=self._config_dict['pre_nms_top_k'],\n pre_nms_score_threshold=self\n ._config_dict['pre_nms_score_threshold'],\n nms_iou_threshold=self._config_dict['nms_iou_threshold'],\n max_num_detections=self._config_dict['max_num_detections'],\n soft_nms_sigma=self._config_dict['soft_nms_sigma']))\n elif self._config_dict['nms_version'] == 'v2':\n (nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections) = (\n _generate_detections_v2(\n decoded_boxes,\n box_scores,\n pre_nms_top_k=self._config_dict['pre_nms_top_k'],\n pre_nms_score_threshold=self\n ._config_dict['pre_nms_score_threshold'],\n nms_iou_threshold=self._config_dict['nms_iou_threshold'],\n max_num_detections=self._config_dict['max_num_detections']))\n else:\n raise ValueError('NMS version {} not supported.'.format(\n self._config_dict['nms_version']))\n\n # Adds 1 to offset the background class which has index 0.\n nmsed_classes += 1\n\n return {\n 'num_detections': valid_detections,\n 'detection_boxes': nmsed_boxes,\n 'detection_classes': nmsed_classes,\n 'detection_scores': nmsed_scores,\n }\n\n def get_config(self):\n return self._config_dict\n\n @classmethod\n def from_config(cls, config):\n return cls(**config)\n\n\[email protected]_keras_serializable(package='Vision')\nclass MultilevelDetectionGenerator(tf.keras.layers.Layer):\n \"\"\"Generates detected boxes with scores and classes for one-stage detector.\"\"\"\n\n def __init__(self,\n apply_nms: bool = True,\n pre_nms_top_k: int = 5000,\n pre_nms_score_threshold: float = 0.05,\n nms_iou_threshold: float = 0.5,\n max_num_detections: int = 100,\n nms_version: str = 'v1',\n use_cpu_nms: bool = False,\n soft_nms_sigma: Optional[float] = None,\n **kwargs):\n \"\"\"Initializes a multi-level detection generator.\n\n Args:\n apply_nms: A `bool` of whether or not apply non maximum suppression. If\n False, the decoded boxes and their scores are returned.\n pre_nms_top_k: An `int` of the number of top scores proposals to be kept\n before applying NMS.\n pre_nms_score_threshold: A `float` of the score threshold to apply before\n applying NMS. Proposals whose scores are below this threshold are thrown\n away.\n nms_iou_threshold: A `float` in [0, 1], the NMS IoU threshold.\n max_num_detections: An `int` of the final number of total detections to\n generate.\n nms_version: A string of `batched`, `v1` or `v2` specifies NMS version\n use_cpu_nms: A `bool` of whether or not enforce NMS to run on CPU.\n soft_nms_sigma: A `float` representing the sigma parameter for Soft NMS.\n When soft_nms_sigma=0.0, we fall back to standard NMS.\n **kwargs: Additional keyword arguments passed to Layer.\n \"\"\"\n self._config_dict = {\n 'apply_nms': apply_nms,\n 'pre_nms_top_k': pre_nms_top_k,\n 'pre_nms_score_threshold': pre_nms_score_threshold,\n 'nms_iou_threshold': nms_iou_threshold,\n 'max_num_detections': max_num_detections,\n 'nms_version': nms_version,\n 'use_cpu_nms': use_cpu_nms,\n 'soft_nms_sigma': soft_nms_sigma,\n }\n super(MultilevelDetectionGenerator, self).__init__(**kwargs)\n\n def _decode_multilevel_outputs(\n self,\n raw_boxes: Mapping[str, tf.Tensor],\n raw_scores: Mapping[str, tf.Tensor],\n anchor_boxes: tf.Tensor,\n image_shape: tf.Tensor,\n raw_attributes: Optional[Mapping[str, tf.Tensor]] = None):\n \"\"\"Collects dict of multilevel boxes, scores, attributes into lists.\"\"\"\n boxes = []\n scores = []\n if raw_attributes:\n attributes = {att_name: [] for att_name in raw_attributes.keys()}\n else:\n attributes = {}\n\n levels = list(raw_boxes.keys())\n min_level = int(min(levels))\n max_level = int(max(levels))\n for i in range(min_level, max_level + 1):\n raw_boxes_i = raw_boxes[str(i)]\n raw_scores_i = raw_scores[str(i)]\n batch_size = tf.shape(raw_boxes_i)[0]\n (_, feature_h_i, feature_w_i,\n num_anchors_per_locations_times_4) = raw_boxes_i.get_shape().as_list()\n num_locations = feature_h_i * feature_w_i\n num_anchors_per_locations = num_anchors_per_locations_times_4 // 4\n num_classes = raw_scores_i.get_shape().as_list(\n )[-1] // num_anchors_per_locations\n\n # Applies score transformation and remove the implicit background class.\n scores_i = tf.sigmoid(\n tf.reshape(raw_scores_i, [\n batch_size, num_locations * num_anchors_per_locations, num_classes\n ]))\n scores_i = tf.slice(scores_i, [0, 0, 1], [-1, -1, -1])\n\n # Box decoding.\n # The anchor boxes are shared for all data in a batch.\n # One stage detector only supports class agnostic box regression.\n anchor_boxes_i = tf.reshape(\n anchor_boxes[str(i)],\n [batch_size, num_locations * num_anchors_per_locations, 4])\n raw_boxes_i = tf.reshape(\n raw_boxes_i,\n [batch_size, num_locations * num_anchors_per_locations, 4])\n boxes_i = box_ops.decode_boxes(raw_boxes_i, anchor_boxes_i)\n\n # Box clipping.\n boxes_i = box_ops.clip_boxes(\n boxes_i, tf.expand_dims(image_shape, axis=1))\n\n boxes.append(boxes_i)\n scores.append(scores_i)\n\n if raw_attributes:\n for att_name, raw_att in raw_attributes.items():\n attribute_size = raw_att[str(\n i)].get_shape().as_list()[-1] // num_anchors_per_locations\n att_i = tf.reshape(raw_att[str(i)], [\n batch_size, num_locations * num_anchors_per_locations,\n attribute_size\n ])\n attributes[att_name].append(att_i)\n\n boxes = tf.concat(boxes, axis=1)\n boxes = tf.expand_dims(boxes, axis=2)\n scores = tf.concat(scores, axis=1)\n\n if raw_attributes:\n for att_name in raw_attributes.keys():\n attributes[att_name] = tf.concat(attributes[att_name], axis=1)\n attributes[att_name] = tf.expand_dims(attributes[att_name], axis=2)\n\n return boxes, scores, attributes\n\n def __call__(self,\n raw_boxes: Mapping[str, tf.Tensor],\n raw_scores: Mapping[str, tf.Tensor],\n anchor_boxes: tf.Tensor,\n image_shape: tf.Tensor,\n raw_attributes: Optional[Mapping[str, tf.Tensor]] = None):\n \"\"\"Generates final detections.\n\n Args:\n raw_boxes: A `dict` with keys representing FPN levels and values\n representing box tenors of shape `[batch, feature_h, feature_w,\n num_anchors * 4]`.\n raw_scores: A `dict` with keys representing FPN levels and values\n representing logit tensors of shape `[batch, feature_h, feature_w,\n num_anchors]`.\n anchor_boxes: A `tf.Tensor` of shape of [batch_size, K, 4] representing\n the corresponding anchor boxes w.r.t `box_outputs`.\n image_shape: A `tf.Tensor` of shape of [batch_size, 2] storing the image\n height and width w.r.t. the scaled image, i.e. the same image space as\n `box_outputs` and `anchor_boxes`.\n raw_attributes: If not None, a `dict` of (attribute_name,\n attribute_prediction) pairs. `attribute_prediction` is a dict that\n contains keys representing FPN levels and values representing tenors of\n shape `[batch, feature_h, feature_w, num_anchors * attribute_size]`.\n\n Returns:\n If `apply_nms` = True, the return is a dictionary with keys:\n `detection_boxes`: A `float` tf.Tensor of shape\n [batch, max_num_detections, 4] representing top detected boxes in\n [y1, x1, y2, x2].\n `detection_scores`: A `float` tf.Tensor of shape\n [batch, max_num_detections] representing sorted confidence scores for\n detected boxes. The values are between [0, 1].\n `detection_classes`: An `int` tf.Tensor of shape\n [batch, max_num_detections] representing classes for detected boxes.\n `num_detections`: An `int` tf.Tensor of shape [batch] only the first\n `num_detections` boxes are valid detections\n `detection_attributes`: A dict. Values of the dict is a `float`\n tf.Tensor of shape [batch, max_num_detections, attribute_size]\n representing attribute predictions for detected boxes.\n If `apply_nms` = False, the return is a dictionary with keys:\n `decoded_boxes`: A `float` tf.Tensor of shape [batch, num_raw_boxes, 4]\n representing all the decoded boxes.\n `decoded_box_scores`: A `float` tf.Tensor of shape\n [batch, num_raw_boxes] representing socres of all the decoded boxes.\n `decoded_box_attributes`: A dict. Values in the dict is a\n `float` tf.Tensor of shape [batch, num_raw_boxes, attribute_size]\n representing attribute predictions of all the decoded boxes.\n \"\"\"\n boxes, scores, attributes = self._decode_multilevel_outputs(\n raw_boxes, raw_scores, anchor_boxes, image_shape, raw_attributes)\n\n if not self._config_dict['apply_nms']:\n return {\n 'decoded_boxes': boxes,\n 'decoded_box_scores': scores,\n 'decoded_box_attributes': attributes,\n }\n\n # Optionally force the NMS to run on CPU.\n if self._config_dict['use_cpu_nms']:\n nms_context = tf.device('cpu:0')\n else:\n nms_context = contextlib.nullcontext()\n\n with nms_context:\n if raw_attributes and (self._config_dict['nms_version'] != 'v1'):\n raise ValueError(\n 'Attribute learning is only supported for NMSv1 but NMS {} is used.'\n .format(self._config_dict['nms_version']))\n if self._config_dict['nms_version'] == 'batched':\n (nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections) = (\n _generate_detections_batched(\n boxes, scores, self._config_dict['pre_nms_score_threshold'],\n self._config_dict['nms_iou_threshold'],\n self._config_dict['max_num_detections']))\n # Set `nmsed_attributes` to None for batched NMS.\n nmsed_attributes = {}\n elif self._config_dict['nms_version'] == 'v1':\n (nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections,\n nmsed_attributes) = (\n _generate_detections_v1(\n boxes,\n scores,\n attributes=attributes if raw_attributes else None,\n pre_nms_top_k=self._config_dict['pre_nms_top_k'],\n pre_nms_score_threshold=self\n ._config_dict['pre_nms_score_threshold'],\n nms_iou_threshold=self._config_dict['nms_iou_threshold'],\n max_num_detections=self._config_dict['max_num_detections'],\n soft_nms_sigma=self._config_dict['soft_nms_sigma']))\n elif self._config_dict['nms_version'] == 'v2':\n (nmsed_boxes, nmsed_scores, nmsed_classes, valid_detections) = (\n _generate_detections_v2(\n boxes,\n scores,\n pre_nms_top_k=self._config_dict['pre_nms_top_k'],\n pre_nms_score_threshold=self\n ._config_dict['pre_nms_score_threshold'],\n nms_iou_threshold=self._config_dict['nms_iou_threshold'],\n max_num_detections=self._config_dict['max_num_detections']))\n # Set `nmsed_attributes` to None for v2.\n nmsed_attributes = {}\n else:\n raise ValueError('NMS version {} not supported.'.format(\n self._config_dict['nms_version']))\n\n # Adds 1 to offset the background class which has index 0.\n nmsed_classes += 1\n\n return {\n 'num_detections': valid_detections,\n 'detection_boxes': nmsed_boxes,\n 'detection_classes': nmsed_classes,\n 'detection_scores': nmsed_scores,\n 'detection_attributes': nmsed_attributes,\n }\n\n def get_config(self):\n return self._config_dict\n\n @classmethod\n def from_config(cls, config):\n return cls(**config)\n"
] |
[
[
"tensorflow.device",
"tensorflow.concat",
"tensorflow.stack",
"tensorflow.cast",
"tensorflow.keras.utils.register_keras_serializable",
"tensorflow.image.combined_non_max_suppression",
"tensorflow.greater",
"tensorflow.gather",
"tensorflow.nn.top_k",
"tensorflow.name_scope",
"tensorflow.fill",
"tensorflow.shape",
"tensorflow.nn.softmax",
"tensorflow.transpose",
"tensorflow.range",
"tensorflow.slice",
"tensorflow.reshape",
"tensorflow.ones_like",
"tensorflow.expand_dims"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
zhaoy17/Macro_lib
|
[
"44c1fd16ae139bbfe6616d1bdca55420fd1695f7"
] |
[
"macro_lib/growth/solow.py"
] |
[
"import numpy as np\nimport pandas as pd\nimport matlibplot.pyplot as plt\n\n\n'''\nSimulating Solow-Swan model, which attempts to model the long-run economic growth\nby looking at capital accumulation (K), population growth (L) and technological \nprogress, which results in increase in productivity. It models the total production\nof the economy using the constant-returns-to-scale Cobb-Douglas production function\n\n Y(t) = K(t)^{alpha} * (A(t)L(t))^{1-alpha}, where\n \n Y(t): a single good output at time t\n K(t): the amount of capital at time t\n L(t): population at time t\n A(t): total factor productivity at time t\n alpha: output elasticity of capital\n\nwith a law of motion:\n I(t) = sY(t)\n C(t) = (1-s)Y(t)\n K(t+1) = (1-delta)K(t) + I(t)\n L(t+1) = (1+n)L(t)\n\nwe can derive the law of motion for k(t) capital per capita:\n k(t+1) = K(t+1)/N(t+1)\n = ((1-delta)K(t) + I(t))/ (1+n)N(t)\n = (1-delta)/(1+n) * k(t) + s/(1+n) A*K_t^alpha\n\nas well as per capita output:\n y(t) = Y(t)/N(t)\n = Ak_t^alpha\n\nwhere, I(t): total investment at time t\n C(t): total consumption at time t\n K(t): total capital at time t\n L(t): total population at time t\n s: the saving rate\n delta: rate of capital depreciation\n n: rate of population growth\n\nThis simulation allows user to take controls of those parameters and plot the simulated\ntotal output growth. The program also enables user to query data from the Federal Reserve\nEconomic Data\n'''\nclass solow:\n '''\n A: total factor productivity\n k0: the initial amount of capital\n delta: rate of depreciation of cpiatal\n s: the saving rate\n n: the population growth rate\n alpha: output elasticity of capital\n starting_year: \n '''\n def __init__(self, A=2.87, k0=3.5, delta = 0.08, s = 0.1, n = 0.015, alpha = 0.36, t0 = 1956, tmax = 2060):\n self._A = A\n self._k0 = k0\n self._k = k0\n self._delta = delta\n self._s = s\n self._n = n\n self._alpha = alpha\n self._t0 = t0\n self._tmax = tmax\n self._t = range(t0, tmax + 1)\n self._y = np.zeros(len(self._t))\n self._y[0] = self._A * (self._k0 ** self._alpha)\n self._time_passed = 0\n\n '''\n this method returns all the variables in this model, which includes A, k0,\n delta, s, n, alpha, t0, tax, Y, and t as a dictionary\n '''\n def get_variables(self):\n return {\n 'A' : self._A, \n 'k0': self._k0, \n 'delta': self._delta,\n 's' : self._s,\n 'n' : self._n,\n 'alpha': self._alpha,\n 't0' : self._t0,\n 'tmax': self._tmax,\n 'y' : self._y,\n 't' : self._t }\n \n '''\n this method takes a list or dictionary as input and set the variables based on\n the user's input. If the user inputs a list, it will treats the entries of list\n as the values of A, k0, delta, s, n, alpha, t0, tmax, Y, t the user wants to \n change into. If the user inputs a dictionary, the fields will be set according\n to the keys.\n\n Example:\n set_variables({A: 2.87, k0: 3.5, delta:0.08, s:0.1, n:0.015, alpha:0.36, t0:1956, tmax:2060})\n set_variables(2.87,3.5,0.08,0.1,0.015,0.36,1956,2060)\n both achieve the same output\n '''\n def set_variables(self, vars):\n if (type(vars) != type([]) or type(vars) != type({})):\n raise ValueError('arguments must be either a dictionary or a list')\n if (type(vars) == type([])):\n if (len(vars) != 8):\n raise ValueError('You must enter the following arguments: A, k0, delta, s, n, alpha, t0, tmax')\n else:\n self.setA(vars[0])\n self.setK0(vars[1])\n self.setDelta(vars[2])\n self.setS(vars[3])\n self.setN(vars[4])\n self.setAlpha(vars[5])\n self.setTRange(vars[6], vars[7])\n if (type(vars) == type({})):\n try:\n self.setA(vars['A'])\n self.setK0(vars['k0'])\n self.setDelta(vars['delta'])\n self.setS(vars['s'])\n self.setN(vars['n'])\n self.setAlpha(vars['alpha'])\n self.setTRange(vars['t0'], vars['tmax'])\n except KeyError:\n raise ValueError(\"Your dictionary must have the keys A, k0, delta, s, n, alpha, t0, and tmax\")\n '''\n setter for the field A (total factor productivity)\n '''\n def setA(self, A):\n if (A < 0):\n raise ValueError(\"A must be positive\")\n self._A = A\n \n '''\n setter for the field k0 (the initial amount of capital)\n '''\n def setK0(self,k0):\n if(k0 < 0):\n raise ValueError(\"k0 must be positive\")\n \n '''\n setter for Delta (rate of depreciation of cpiatal)\n '''\n def setDelta(self, delta):\n if (delta > 1 or delta < 0):\n raise ValueError(\"depreciation rate must be in between 0 and 1\")\n self._delta = delta\n \n '''\n setter for S (saving rate)\n '''\n def setS(self, s):\n if (s > 1 or s < 0):\n raise ValueError(\"saving rate must be in between 0 and 1\")\n self.S = S\n \n '''\n setter for N (population growth rate)\n '''\n def setN(self,n):\n self._n = n\n \n '''\n setter for alpha (output elasticity of capital)\n '''\n def setAlpha(self, alpha):\n if (alpha < 0 or alpha > 1):\n raise ValueError(\"alpha must be in between 0 and 1\")\n self._alpha = alpha\n \n '''\n setter for the time range\n\n Example:\n setTRange(1956, 2060): set the time range starting from 1956 to 2060\n '''\n def setTRange(self, start, end):\n if (end < start):\n raise ValueError(\"tmax must be greater than t0\")\n self._t0 = start\n self._tmax = end\n self._t = range(start, end+1)\n\n '''\n Start the simulation, and return the predicted value of Y \n from the start period to the end period\n\n TO BE IMPLEMENTED\n '''\n def simulate(self):\n for t in self._t:\n self._update()\n return [self._y, self._t]\n\n '''\n Plot the prediction using matlibplot. x-axis would be year, y-axis would \n the predicted GDP\n\n TO BE IMPLEMENTED\n '''\n def plot(self):\n pass\n\n '''\n store the output as a pandas dataframe\n '''\n def to_df(self):\n return pd.DataFrame({'year' : self._t, 'gdp_per_capita' : self._y})\n\n '''\n export the output as a csv file to the user-provided location\n\n TO BE IMPLEMENTED\n '''\n def to_csv(self, dir):\n pass\n \n '''\n lunch the GUI, that enables more user-friendly interaction with the software\n \n TO BE IMPLEMENTED\n '''\n def gui(self):\n pass\n\n '''\n update all the fields according to the law of motion\n\n TO BE IMPLEMENTED\n '''\n def _update(self):\n #update k\n self._k = (1-self._delta)/(1+self._n) * self._k + (self._s)/(1+n) * self._A * (self._k ** self._alpha)\n # update t\n self._time_passed += 1\n #update y\n self._y[self._time_passed] = self._A * (self._k ** self._alpha)\n"
] |
[
[
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
sinhaharsh/pytorch-CycleGAN-and-pix2pix
|
[
"7a38c79f4344c954dd28d041c82c121c92465d3d"
] |
[
"data/unaligned_dataset.py"
] |
[
"import os.path\nfrom data.base_dataset import BaseDataset, get_transform\nfrom data.image_folder import make_dataset\nfrom PIL import Image\nimport random\nimport h5py\nimport numpy as np\nfrom skimage.transform import resize as skResize\nfrom util.util import normalize, adaptive_instance_normalization\n\nclass UnalignedDataset(BaseDataset):\n \"\"\"\n This dataset class can load unaligned/unpaired datasets.\n\n It requires two directories to host training images from domain A '/path/to/data/trainA'\n and from domain B '/path/to/data/trainB' respectively.\n You can train the model with the dataset flag '--dataroot /path/to/data'.\n Similarly, you need to prepare two directories:\n '/path/to/data/testA' and '/path/to/data/testB' during test time.\n \"\"\"\n\n def __init__(self, opt):\n \"\"\"Initialize this dataset class.\n\n Parameters:\n opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions\n \"\"\"\n BaseDataset.__init__(self, opt)\n self.dir_A = os.path.join(opt.dataroot, opt.phase + 'A') # create a path '/path/to/data/trainA'\n self.dir_B = os.path.join(opt.dataroot_B, opt.phase + 'B') # create a path '/path/to/data/trainB'\n\n self.A_paths = sorted(make_dataset(self.dir_A, opt.max_dataset_size)) # load images from '/path/to/data/trainA'\n self.B_paths = sorted(make_dataset(self.dir_B, opt.max_dataset_size)) # load images from '/path/to/data/trainB'\n self.A_size = len(self.A_paths) # get the size of dataset A\n self.B_size = len(self.B_paths) # get the size of dataset B\n btoA = self.opt.direction == 'BtoA'\n input_nc = self.opt.output_nc if btoA else self.opt.input_nc # get the number of channels of input image\n output_nc = self.opt.input_nc if btoA else self.opt.output_nc # get the number of channels of output image\n self.transform_A = get_transform(self.opt, grayscale=(input_nc == 1))\n self.transform_B = get_transform(self.opt, grayscale=(output_nc == 1))\n\n def __getitem__(self, index):\n \"\"\"Return a data point and its metadata information.\n\n Parameters:\n index (int) -- a random integer for data indexing\n\n Returns a dictionary that contains A, B, A_paths and B_paths\n A (tensor) -- an image in the input domain\n B (tensor) -- its corresponding image in the target domain\n A_paths (str) -- image paths\n B_paths (str) -- image paths\n \"\"\"\n A_path = self.A_paths[index % self.A_size] # make sure index is within then range\n if self.opt.serial_batches: # make sure index is within then range\n index_B = index % self.B_size\n else: # randomize the index for domain B to avoid fixed pairs.\n index_B = random.randint(0, self.B_size - 1)\n B_path = self.B_paths[index_B]\n \n A_img = np.array(Image.open(A_path).convert('RGB'))\n A_img = self.stack(A_img)\n \n #Added a new loader for loading hsi images. Uncomment the following line for normal images.\n try:\n B_img = self.hsi_loader(B_path)\n except KeyError:\n print(B_path)\n\n B = normalize(B_img, max_=4096)\n A = normalize(A_img, max_=1)\n A = adaptive_instance_normalization(A, B)\n del A_img, B_img\n return {'A': A, 'B': B, 'A_paths': A_path, 'B_paths': B_path}\n\n def __len__(self):\n \"\"\"Return the total number of images in the dataset.\n\n As we have two datasets with potentially different number of images,\n we take a maximum of\n \"\"\"\n return max(self.A_size, self.B_size)\n \n def stack(self, img, resize=True):\n \n _R = img[:,:,0]\n _G = img[:,:,1]\n _B = img[:,:,2]\n \n R_img = np.stack((_R,)*10, axis=2)\n G_img = np.stack((_G,)*10, axis=2)\n B_img = np.stack((_B,)*11, axis=2)\n\n hsi_img = np.concatenate((B_img, G_img, R_img), axis=2)\n hsi_img = self.resize(hsi_img)\n hsi_img = np.einsum('abc->cab', hsi_img)\n return hsi_img\n \n def resize(self, img):\n img = skResize(img, (self.opt.crop_size, self.opt.crop_size))\n return img\n \n def hsi_loader(self, path):\n with h5py.File(path, 'r') as f:\n d = np.array(f['data'])\n hs_data = np.einsum('abc -> cab',self.resize(d))\n #print('Inside hsi loader, {0}'.format(np.shape(hs_data)))\n return hs_data\n \n"
] |
[
[
"numpy.concatenate",
"numpy.array",
"numpy.einsum",
"numpy.stack"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
carolinscholl/SORN
|
[
"99f908c88265ecc26dad195b56bebfa12838591f"
] |
[
"utils/backup.py"
] |
[
"\"\"\"Backup handler\n\nThis script is contains the backup handling functions.\n\"\"\"\n\nimport os\nimport time\nimport pickle\nimport shutil\nfrom shutil import ignore_patterns\nimport pypianoroll\nimport numpy as np\n\n\ndef backup_pickle(experiment, stats):\n ''''\n Back up handling function.\n\n Arguments:\n experiment -- Experiment object, contains the initial sorn parameters\n stats -- bunch of stats stored during the simulation\n '''\n\n params = experiment.init_params\n results_dir = experiment.results_dir\n files_tosave = experiment.files_tosave\n directory = ('backup/{}'.format(results_dir))\n\n # creates a new directory for storing the results\n # sleeps for a short time to avoid conflicts when running in parallel\n time.sleep(np.random.rand())\n for n_sim in range(1, 1000):\n final_dir = '{}_{}/'.format(directory, str(n_sim))\n if not os.path.exists(final_dir):\n try:\n os.makedirs(final_dir)\n break\n except:\n pass\n\n if 'params' in files_tosave:\n with open(final_dir+'init_params.p', 'wb') as f:\n pickle.dump(params, f)\n\n if 'stats' in files_tosave:\n # generate MIDI track if MusicTask\n if hasattr(stats, 'track'):\n stats.track.write(final_dir+'sample.mid')\n\n # delete attributes that occupy a lot of memory space\n if hasattr(stats, 'input_index_readout'):\n del stats.input_index_readout\n if hasattr(stats, 'input_readout'):\n del stats.input_readout\n if hasattr(stats, 'raster_readout'):\n del stats.raster_readout\n if hasattr(stats, 't_past'):\n del stats.t_past\n\n with open(final_dir+'stats.p', 'wb') as f:\n pickle.dump(stats, f)\n\n if 'scripts' in files_tosave:\n # TODO: this should not need a '_'\n for f in ['utils', 'common', results_dir.split('_')[0]]:\n shutil.copytree(f, final_dir+f,\n ignore=ignore_patterns('*.pyc', '*.git'))\n"
] |
[
[
"numpy.random.rand"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
monocilindro/torchsat
|
[
"5ac62e1aa9fee1d7a5a4a58914c128cf8e18cc09"
] |
[
"scripts/train_cd.py"
] |
[
"import argparse\nimport os\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\nfrom ignite.metrics import IoU, Precision, Recall\n\nimport torchsat.transforms.transforms_cd as T\nfrom torchsat.datasets.folder import ChangeDetectionDataset\nfrom torchsat.models import FC_EF, FC_Siam_Conc, FC_Siam_Diff\n\ndef train_one_epoch(epoch, dataloader, model, criterion, optimizer, device, writer):\n print('train epoch {}'.format(epoch))\n model.train()\n for idx, (pre_img, post_img, targets) in enumerate(dataloader):\n pre_img, post_img, targets = pre_img.to(device), post_img.to(device), targets.to(device)\n outputs = model(pre_img, post_img)\n loss = criterion(outputs, targets)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n print('train-epoch:{} [{}/{}], loss: {:5.3}'.format(epoch, idx+1, len(dataloader), loss.item()))\n writer.add_scalar('train/loss', loss.item(), len(dataloader)*epoch+idx)\n\n\ndef evalidation(epoch, dataloader, model, criterion, device, writer, tb_test_imgs):\n print('\\neval epoch {}'.format(epoch))\n model.eval()\n recall = Recall(lambda x: (x[0], x[1]))\n precision = Precision(lambda x: (x[0], x[1]))\n mean_recall = []\n mean_precision = []\n mean_loss = []\n with torch.no_grad():\n for idx, (pre_img, post_img, targets) in enumerate(dataloader):\n pre_img, post_img, targets = pre_img.to(device), post_img.to(device), targets.to(device)\n outputs = model(pre_img, post_img)\n loss = criterion(outputs, targets)\n\n preds = outputs.argmax(1)\n\n precision.update((preds, targets))\n recall.update((preds, targets))\n mean_loss.append(loss.item())\n mean_recall.append(recall.compute().item())\n mean_precision.append(precision.compute().item())\n\n # print('val-epoch:{} [{}/{}], loss: {:5.3}'.format(epoch, idx + 1, len(dataloader), loss.item()))\n writer.add_scalar('test/loss', loss.item(), len(dataloader) * epoch + idx)\n if idx < tb_test_imgs:\n writer.add_image('test/pre', pre_img[0], idx)\n writer.add_image('test/post', post_img[0], idx)\n writer.add_image('test/label', label[0], idx)\n writer.add_image('test/pred', preds, idx)\n\n mean_precision, mean_recall = np.array(mean_precision).mean(), np.array(mean_recall).mean()\n f1 = mean_precision * mean_recall * 2 / (mean_precision + mean_recall + 1e-20)\n\n print('precision: {:07.5}, recall: {:07.5}, f1: {:07.5}\\n'.format(mean_precision, mean_recall, f1))\n writer.add_scalar('test/epoch-loss', np.array(mean_loss).mean(), epoch)\n writer.add_scalar('test/f1', f1, epoch)\n writer.add_scalar('test/precision', mean_precision, epoch)\n writer.add_scalar('test/recall', mean_recall, epoch)\n\n\ndef load_data(traindir, valdir, **kwargs):\n \"\"\"generate the train and val dataloader, you can change this for your specific task\n\n Args:\n traindir (str): train dataset dir\n valdir (str): validation dataset dir\n\n Returns:\n tuple: the train dataset and validation dataset\n \"\"\"\n train_transform = T.Compose([\n T.RandomCrop(512),\n T.RandomHorizontalFlip(),\n T.RandomVerticalFlip(),\n T.ToTensor(),\n T.Normalize(),\n ])\n val_transform = T.Compose([\n T.ToTensor(),\n T.Normalize(),\n ])\n dataset_train = ChangeDetectionDataset(traindir, extentions=kwargs['extensions'], transforms=train_transform, )\n dataset_val = ChangeDetectionDataset(valdir, extentions=kwargs['extensions'], transforms=val_transform)\n\n return dataset_train, dataset_val\n\n\ndef main(args):\n torch.backends.cudnn.benchmark = True\n device = torch.device('cuda' if args.device == 'cuda' else 'cpu')\n\n # dataset and dataloader\n train_data, val_data = load_data(args.train_path, args.val_path, extensions=args.extensions)\n train_loader = DataLoader(train_data, batch_size=args.batch_size, shuffle=True)\n val_loader = DataLoader(val_data, batch_size=1, shuffle=False)\n\n # model\n # model = get_model(args.model, args.num_classes, pretrained=args.pretrained)\n # model = FC_EF(num_classes=args.num_classes)\n model = FC_Siam_Diff(num_classes=args.num_classes)\n model.to(device)\n if args.resume:\n model.load_state_dict(torch.load(args.resume, map_location=device))\n # TODO: resume learning rate\n\n # loss\n criterion = nn.CrossEntropyLoss().to(device)\n criterion = nn.BCELoss()\n\n # optim and lr scheduler\n optimizer = optim.Adam(model.parameters(), lr=args.lr)\n lr_scheduler = optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0=10, T_mult=1, eta_min=1e-8)\n # lr_scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1)\n\n writer = SummaryWriter(args.ckp_dir)\n for epoch in range(args.epochs):\n writer.add_scalar('train/lr', lr_scheduler.get_lr()[0], epoch)\n train_one_epoch(epoch, train_loader, model, criterion, optimizer, device, writer)\n evalidation(epoch, val_loader, model, criterion, device, writer, args.tb_test_imgs)\n lr_scheduler.step()\n if epoch % 2 == 0:\n torch.save(model.state_dict(), os.path.join(args.ckp_dir, 'cd_epoch_{}.pth'.format(epoch)))\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='TorchSat Change Detection Training Script')\n parser.add_argument('--train-path', help='train dataset path')\n parser.add_argument('--val-path', help='validate dataset path')\n parser.add_argument('--extensions', nargs='+', default='jpg', help='the train image extension')\n parser.add_argument('--model', default=\"unet34\", help='model name. default, unet34')\n parser.add_argument('--pretrained', default=True, help='use ImageNet pretrained params')\n\n parser.add_argument('--resume', default='', type=str, metavar='PATH',\n help='path to latest checkpoint (default: none)')\n parser.add_argument('--num-classes', default=3, type=int, help='num of classes')\n parser.add_argument('--in-channels', default=3, type=int, help='input image channels')\n\n parser.add_argument('--device', default='cpu', help='device')\n parser.add_argument('-b', '--batch-size', default=16, type=int, help='batch size')\n parser.add_argument('--epochs', default=90, type=int, help='epochs')\n parser.add_argument('--lr', default=0.01, type=float, help='initial learning rate')\n\n parser.add_argument('--print-freq', default=10, type=int, help='print frequency')\n parser.add_argument('--ckp-dir', default='./', help='path to save checkpoint')\n parser.add_argument('--tb-test-imgs', default=10, help='the num of test image show in tensorboard')\n\n args = parser.parse_args()\n return args\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n main(args)\n"
] |
[
[
"torch.optim.lr_scheduler.CosineAnnealingWarmRestarts",
"torch.nn.CrossEntropyLoss",
"torch.load",
"torch.utils.data.DataLoader",
"torch.nn.BCELoss",
"torch.no_grad",
"torch.utils.tensorboard.SummaryWriter",
"torch.device",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jess010/pandas
|
[
"9872d6757e5117dce070981141cee562f675694e",
"9872d6757e5117dce070981141cee562f675694e",
"9872d6757e5117dce070981141cee562f675694e"
] |
[
"pandas/tests/frame/test_reshape.py",
"pandas/tests/categorical/test_missing.py",
"asv_bench/benchmarks/offset.py"
] |
[
"# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\n\nfrom warnings import catch_warnings\nfrom datetime import datetime\n\nimport itertools\nimport pytest\n\nfrom numpy.random import randn\nfrom numpy import nan\nimport numpy as np\n\nfrom pandas.compat import u\nfrom pandas import (DataFrame, Index, Series, MultiIndex, date_range,\n Timedelta, Period)\nimport pandas as pd\n\nfrom pandas.util.testing import assert_series_equal, assert_frame_equal\n\nimport pandas.util.testing as tm\n\nfrom pandas.tests.frame.common import TestData\n\n\nclass TestDataFrameReshape(TestData):\n\n def test_pivot(self):\n data = {\n 'index': ['A', 'B', 'C', 'C', 'B', 'A'],\n 'columns': ['One', 'One', 'One', 'Two', 'Two', 'Two'],\n 'values': [1., 2., 3., 3., 2., 1.]\n }\n\n frame = DataFrame(data)\n pivoted = frame.pivot(\n index='index', columns='columns', values='values')\n\n expected = DataFrame({\n 'One': {'A': 1., 'B': 2., 'C': 3.},\n 'Two': {'A': 1., 'B': 2., 'C': 3.}\n })\n\n expected.index.name, expected.columns.name = 'index', 'columns'\n tm.assert_frame_equal(pivoted, expected)\n\n # name tracking\n assert pivoted.index.name == 'index'\n assert pivoted.columns.name == 'columns'\n\n # don't specify values\n pivoted = frame.pivot(index='index', columns='columns')\n assert pivoted.index.name == 'index'\n assert pivoted.columns.names == (None, 'columns')\n\n with catch_warnings(record=True):\n # pivot multiple columns\n wp = tm.makePanel()\n lp = wp.to_frame()\n df = lp.reset_index()\n tm.assert_frame_equal(df.pivot('major', 'minor'), lp.unstack())\n\n def test_pivot_duplicates(self):\n data = DataFrame({'a': ['bar', 'bar', 'foo', 'foo', 'foo'],\n 'b': ['one', 'two', 'one', 'one', 'two'],\n 'c': [1., 2., 3., 3., 4.]})\n with tm.assert_raises_regex(ValueError, 'duplicate entries'):\n data.pivot('a', 'b', 'c')\n\n def test_pivot_empty(self):\n df = DataFrame({}, columns=['a', 'b', 'c'])\n result = df.pivot('a', 'b', 'c')\n expected = DataFrame({})\n tm.assert_frame_equal(result, expected, check_names=False)\n\n def test_pivot_integer_bug(self):\n df = DataFrame(data=[(\"A\", \"1\", \"A1\"), (\"B\", \"2\", \"B2\")])\n\n result = df.pivot(index=1, columns=0, values=2)\n repr(result)\n tm.assert_index_equal(result.columns, Index(['A', 'B'], name=0))\n\n def test_pivot_index_none(self):\n # gh-3962\n data = {\n 'index': ['A', 'B', 'C', 'C', 'B', 'A'],\n 'columns': ['One', 'One', 'One', 'Two', 'Two', 'Two'],\n 'values': [1., 2., 3., 3., 2., 1.]\n }\n\n frame = DataFrame(data).set_index('index')\n result = frame.pivot(columns='columns', values='values')\n expected = DataFrame({\n 'One': {'A': 1., 'B': 2., 'C': 3.},\n 'Two': {'A': 1., 'B': 2., 'C': 3.}\n })\n\n expected.index.name, expected.columns.name = 'index', 'columns'\n assert_frame_equal(result, expected)\n\n # omit values\n result = frame.pivot(columns='columns')\n\n expected.columns = pd.MultiIndex.from_tuples([('values', 'One'),\n ('values', 'Two')],\n names=[None, 'columns'])\n expected.index.name = 'index'\n tm.assert_frame_equal(result, expected, check_names=False)\n assert result.index.name == 'index'\n assert result.columns.names == (None, 'columns')\n expected.columns = expected.columns.droplevel(0)\n result = frame.pivot(columns='columns', values='values')\n\n expected.columns.name = 'columns'\n tm.assert_frame_equal(result, expected)\n\n def test_stack_unstack(self):\n df = self.frame.copy()\n df[:] = np.arange(np.prod(df.shape)).reshape(df.shape)\n\n stacked = df.stack()\n stacked_df = DataFrame({'foo': stacked, 'bar': stacked})\n\n unstacked = stacked.unstack()\n unstacked_df = stacked_df.unstack()\n\n assert_frame_equal(unstacked, df)\n assert_frame_equal(unstacked_df['bar'], df)\n\n unstacked_cols = stacked.unstack(0)\n unstacked_cols_df = stacked_df.unstack(0)\n assert_frame_equal(unstacked_cols.T, df)\n assert_frame_equal(unstacked_cols_df['bar'].T, df)\n\n def test_stack_mixed_level(self):\n # GH 18310\n levels = [range(3), [3, 'a', 'b'], [1, 2]]\n\n # flat columns:\n df = DataFrame(1, index=levels[0], columns=levels[1])\n result = df.stack()\n expected = Series(1, index=MultiIndex.from_product(levels[:2]))\n assert_series_equal(result, expected)\n\n # MultiIndex columns:\n df = DataFrame(1, index=levels[0],\n columns=MultiIndex.from_product(levels[1:]))\n result = df.stack(1)\n expected = DataFrame(1, index=MultiIndex.from_product([levels[0],\n levels[2]]),\n columns=levels[1])\n assert_frame_equal(result, expected)\n\n # as above, but used labels in level are actually of homogeneous type\n result = df[['a', 'b']].stack(1)\n expected = expected[['a', 'b']]\n assert_frame_equal(result, expected)\n\n def test_unstack_fill(self):\n\n # GH #9746: fill_value keyword argument for Series\n # and DataFrame unstack\n\n # From a series\n data = Series([1, 2, 4, 5], dtype=np.int16)\n data.index = MultiIndex.from_tuples(\n [('x', 'a'), ('x', 'b'), ('y', 'b'), ('z', 'a')])\n\n result = data.unstack(fill_value=-1)\n expected = DataFrame({'a': [1, -1, 5], 'b': [2, 4, -1]},\n index=['x', 'y', 'z'], dtype=np.int16)\n assert_frame_equal(result, expected)\n\n # From a series with incorrect data type for fill_value\n result = data.unstack(fill_value=0.5)\n expected = DataFrame({'a': [1, 0.5, 5], 'b': [2, 4, 0.5]},\n index=['x', 'y', 'z'], dtype=np.float)\n assert_frame_equal(result, expected)\n\n # GH #13971: fill_value when unstacking multiple levels:\n df = DataFrame({'x': ['a', 'a', 'b'],\n 'y': ['j', 'k', 'j'],\n 'z': [0, 1, 2],\n 'w': [0, 1, 2]}).set_index(['x', 'y', 'z'])\n unstacked = df.unstack(['x', 'y'], fill_value=0)\n key = ('w', 'b', 'j')\n expected = unstacked[key]\n result = pd.Series([0, 0, 2], index=unstacked.index, name=key)\n assert_series_equal(result, expected)\n\n stacked = unstacked.stack(['x', 'y'])\n stacked.index = stacked.index.reorder_levels(df.index.names)\n # Workaround for GH #17886 (unnecessarily casts to float):\n stacked = stacked.astype(np.int64)\n result = stacked.loc[df.index]\n assert_frame_equal(result, df)\n\n # From a series\n s = df['w']\n result = s.unstack(['x', 'y'], fill_value=0)\n expected = unstacked['w']\n assert_frame_equal(result, expected)\n\n def test_unstack_fill_frame(self):\n\n # From a dataframe\n rows = [[1, 2], [3, 4], [5, 6], [7, 8]]\n df = DataFrame(rows, columns=list('AB'), dtype=np.int32)\n df.index = MultiIndex.from_tuples(\n [('x', 'a'), ('x', 'b'), ('y', 'b'), ('z', 'a')])\n\n result = df.unstack(fill_value=-1)\n\n rows = [[1, 3, 2, 4], [-1, 5, -1, 6], [7, -1, 8, -1]]\n expected = DataFrame(rows, index=list('xyz'), dtype=np.int32)\n expected.columns = MultiIndex.from_tuples(\n [('A', 'a'), ('A', 'b'), ('B', 'a'), ('B', 'b')])\n assert_frame_equal(result, expected)\n\n # From a mixed type dataframe\n df['A'] = df['A'].astype(np.int16)\n df['B'] = df['B'].astype(np.float64)\n\n result = df.unstack(fill_value=-1)\n expected['A'] = expected['A'].astype(np.int16)\n expected['B'] = expected['B'].astype(np.float64)\n assert_frame_equal(result, expected)\n\n # From a dataframe with incorrect data type for fill_value\n result = df.unstack(fill_value=0.5)\n\n rows = [[1, 3, 2, 4], [0.5, 5, 0.5, 6], [7, 0.5, 8, 0.5]]\n expected = DataFrame(rows, index=list('xyz'), dtype=np.float)\n expected.columns = MultiIndex.from_tuples(\n [('A', 'a'), ('A', 'b'), ('B', 'a'), ('B', 'b')])\n assert_frame_equal(result, expected)\n\n def test_unstack_fill_frame_datetime(self):\n\n # Test unstacking with date times\n dv = pd.date_range('2012-01-01', periods=4).values\n data = Series(dv)\n data.index = MultiIndex.from_tuples(\n [('x', 'a'), ('x', 'b'), ('y', 'b'), ('z', 'a')])\n\n result = data.unstack()\n expected = DataFrame({'a': [dv[0], pd.NaT, dv[3]],\n 'b': [dv[1], dv[2], pd.NaT]},\n index=['x', 'y', 'z'])\n assert_frame_equal(result, expected)\n\n result = data.unstack(fill_value=dv[0])\n expected = DataFrame({'a': [dv[0], dv[0], dv[3]],\n 'b': [dv[1], dv[2], dv[0]]},\n index=['x', 'y', 'z'])\n assert_frame_equal(result, expected)\n\n def test_unstack_fill_frame_timedelta(self):\n\n # Test unstacking with time deltas\n td = [Timedelta(days=i) for i in range(4)]\n data = Series(td)\n data.index = MultiIndex.from_tuples(\n [('x', 'a'), ('x', 'b'), ('y', 'b'), ('z', 'a')])\n\n result = data.unstack()\n expected = DataFrame({'a': [td[0], pd.NaT, td[3]],\n 'b': [td[1], td[2], pd.NaT]},\n index=['x', 'y', 'z'])\n assert_frame_equal(result, expected)\n\n result = data.unstack(fill_value=td[1])\n expected = DataFrame({'a': [td[0], td[1], td[3]],\n 'b': [td[1], td[2], td[1]]},\n index=['x', 'y', 'z'])\n assert_frame_equal(result, expected)\n\n def test_unstack_fill_frame_period(self):\n\n # Test unstacking with period\n periods = [Period('2012-01'), Period('2012-02'), Period('2012-03'),\n Period('2012-04')]\n data = Series(periods)\n data.index = MultiIndex.from_tuples(\n [('x', 'a'), ('x', 'b'), ('y', 'b'), ('z', 'a')])\n\n result = data.unstack()\n expected = DataFrame({'a': [periods[0], None, periods[3]],\n 'b': [periods[1], periods[2], None]},\n index=['x', 'y', 'z'])\n assert_frame_equal(result, expected)\n\n result = data.unstack(fill_value=periods[1])\n expected = DataFrame({'a': [periods[0], periods[1], periods[3]],\n 'b': [periods[1], periods[2], periods[1]]},\n index=['x', 'y', 'z'])\n assert_frame_equal(result, expected)\n\n def test_unstack_fill_frame_categorical(self):\n\n # Test unstacking with categorical\n data = pd.Series(['a', 'b', 'c', 'a'], dtype='category')\n data.index = pd.MultiIndex.from_tuples(\n [('x', 'a'), ('x', 'b'), ('y', 'b'), ('z', 'a')])\n\n # By default missing values will be NaN\n result = data.unstack()\n expected = DataFrame({'a': pd.Categorical(list('axa'),\n categories=list('abc')),\n 'b': pd.Categorical(list('bcx'),\n categories=list('abc'))},\n index=list('xyz'))\n assert_frame_equal(result, expected)\n\n # Fill with non-category results in NaN entries similar to above\n result = data.unstack(fill_value='d')\n assert_frame_equal(result, expected)\n\n # Fill with category value replaces missing values as expected\n result = data.unstack(fill_value='c')\n expected = DataFrame({'a': pd.Categorical(list('aca'),\n categories=list('abc')),\n 'b': pd.Categorical(list('bcc'),\n categories=list('abc'))},\n index=list('xyz'))\n assert_frame_equal(result, expected)\n\n def test_unstack_preserve_dtypes(self):\n # Checks fix for #11847\n df = pd.DataFrame(dict(state=['IL', 'MI', 'NC'],\n index=['a', 'b', 'c'],\n some_categories=pd.Series(['a', 'b', 'c']\n ).astype('category'),\n A=np.random.rand(3),\n B=1,\n C='foo',\n D=pd.Timestamp('20010102'),\n E=pd.Series([1.0, 50.0, 100.0]\n ).astype('float32'),\n F=pd.Series([3.0, 4.0, 5.0]).astype('float64'),\n G=False,\n H=pd.Series([1, 200, 923442], dtype='int8')))\n\n def unstack_and_compare(df, column_name):\n unstacked1 = df.unstack([column_name])\n unstacked2 = df.unstack(column_name)\n assert_frame_equal(unstacked1, unstacked2)\n\n df1 = df.set_index(['state', 'index'])\n unstack_and_compare(df1, 'index')\n\n df1 = df.set_index(['state', 'some_categories'])\n unstack_and_compare(df1, 'some_categories')\n\n df1 = df.set_index(['F', 'C'])\n unstack_and_compare(df1, 'F')\n\n df1 = df.set_index(['G', 'B', 'state'])\n unstack_and_compare(df1, 'B')\n\n df1 = df.set_index(['E', 'A'])\n unstack_and_compare(df1, 'E')\n\n df1 = df.set_index(['state', 'index'])\n s = df1['A']\n unstack_and_compare(s, 'index')\n\n def test_stack_ints(self):\n columns = MultiIndex.from_tuples(list(itertools.product(range(3),\n repeat=3)))\n df = DataFrame(np.random.randn(30, 27), columns=columns)\n\n assert_frame_equal(df.stack(level=[1, 2]),\n df.stack(level=1).stack(level=1))\n assert_frame_equal(df.stack(level=[-2, -1]),\n df.stack(level=1).stack(level=1))\n\n df_named = df.copy()\n df_named.columns.set_names(range(3), inplace=True)\n\n assert_frame_equal(df_named.stack(level=[1, 2]),\n df_named.stack(level=1).stack(level=1))\n\n def test_stack_mixed_levels(self):\n columns = MultiIndex.from_tuples(\n [('A', 'cat', 'long'), ('B', 'cat', 'long'),\n ('A', 'dog', 'short'), ('B', 'dog', 'short')],\n names=['exp', 'animal', 'hair_length']\n )\n df = DataFrame(randn(4, 4), columns=columns)\n\n animal_hair_stacked = df.stack(level=['animal', 'hair_length'])\n exp_hair_stacked = df.stack(level=['exp', 'hair_length'])\n\n # GH #8584: Need to check that stacking works when a number\n # is passed that is both a level name and in the range of\n # the level numbers\n df2 = df.copy()\n df2.columns.names = ['exp', 'animal', 1]\n assert_frame_equal(df2.stack(level=['animal', 1]),\n animal_hair_stacked, check_names=False)\n assert_frame_equal(df2.stack(level=['exp', 1]),\n exp_hair_stacked, check_names=False)\n\n # When mixed types are passed and the ints are not level\n # names, raise\n pytest.raises(ValueError, df2.stack, level=['animal', 0])\n\n # GH #8584: Having 0 in the level names could raise a\n # strange error about lexsort depth\n df3 = df.copy()\n df3.columns.names = ['exp', 'animal', 0]\n assert_frame_equal(df3.stack(level=['animal', 0]),\n animal_hair_stacked, check_names=False)\n\n def test_stack_int_level_names(self):\n columns = MultiIndex.from_tuples(\n [('A', 'cat', 'long'), ('B', 'cat', 'long'),\n ('A', 'dog', 'short'), ('B', 'dog', 'short')],\n names=['exp', 'animal', 'hair_length']\n )\n df = DataFrame(randn(4, 4), columns=columns)\n\n exp_animal_stacked = df.stack(level=['exp', 'animal'])\n animal_hair_stacked = df.stack(level=['animal', 'hair_length'])\n exp_hair_stacked = df.stack(level=['exp', 'hair_length'])\n\n df2 = df.copy()\n df2.columns.names = [0, 1, 2]\n assert_frame_equal(df2.stack(level=[1, 2]), animal_hair_stacked,\n check_names=False)\n assert_frame_equal(df2.stack(level=[0, 1]), exp_animal_stacked,\n check_names=False)\n assert_frame_equal(df2.stack(level=[0, 2]), exp_hair_stacked,\n check_names=False)\n\n # Out-of-order int column names\n df3 = df.copy()\n df3.columns.names = [2, 0, 1]\n assert_frame_equal(df3.stack(level=[0, 1]), animal_hair_stacked,\n check_names=False)\n assert_frame_equal(df3.stack(level=[2, 0]), exp_animal_stacked,\n check_names=False)\n assert_frame_equal(df3.stack(level=[2, 1]), exp_hair_stacked,\n check_names=False)\n\n def test_unstack_bool(self):\n df = DataFrame([False, False],\n index=MultiIndex.from_arrays([['a', 'b'], ['c', 'l']]),\n columns=['col'])\n rs = df.unstack()\n xp = DataFrame(np.array([[False, np.nan], [np.nan, False]],\n dtype=object),\n index=['a', 'b'],\n columns=MultiIndex.from_arrays([['col', 'col'],\n ['c', 'l']]))\n assert_frame_equal(rs, xp)\n\n def test_unstack_level_binding(self):\n # GH9856\n mi = pd.MultiIndex(\n levels=[[u('foo'), u('bar')], [u('one'), u('two')],\n [u('a'), u('b')]],\n labels=[[0, 0, 1, 1], [0, 1, 0, 1], [1, 0, 1, 0]],\n names=[u('first'), u('second'), u('third')])\n s = pd.Series(0, index=mi)\n result = s.unstack([1, 2]).stack(0)\n\n expected_mi = pd.MultiIndex(\n levels=[['foo', 'bar'], ['one', 'two']],\n labels=[[0, 0, 1, 1], [0, 1, 0, 1]],\n names=['first', 'second'])\n\n expected = pd.DataFrame(np.array([[np.nan, 0],\n [0, np.nan],\n [np.nan, 0],\n [0, np.nan]],\n dtype=np.float64),\n index=expected_mi,\n columns=pd.Index(['a', 'b'], name='third'))\n\n assert_frame_equal(result, expected)\n\n def test_unstack_to_series(self):\n # check reversibility\n data = self.frame.unstack()\n\n assert isinstance(data, Series)\n undo = data.unstack().T\n assert_frame_equal(undo, self.frame)\n\n # check NA handling\n data = DataFrame({'x': [1, 2, np.NaN], 'y': [3.0, 4, np.NaN]})\n data.index = Index(['a', 'b', 'c'])\n result = data.unstack()\n\n midx = MultiIndex(levels=[['x', 'y'], ['a', 'b', 'c']],\n labels=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]])\n expected = Series([1, 2, np.NaN, 3, 4, np.NaN], index=midx)\n\n assert_series_equal(result, expected)\n\n # check composability of unstack\n old_data = data.copy()\n for _ in range(4):\n data = data.unstack()\n assert_frame_equal(old_data, data)\n\n def test_unstack_dtypes(self):\n\n # GH 2929\n rows = [[1, 1, 3, 4],\n [1, 2, 3, 4],\n [2, 1, 3, 4],\n [2, 2, 3, 4]]\n\n df = DataFrame(rows, columns=list('ABCD'))\n result = df.get_dtype_counts()\n expected = Series({'int64': 4})\n assert_series_equal(result, expected)\n\n # single dtype\n df2 = df.set_index(['A', 'B'])\n df3 = df2.unstack('B')\n result = df3.get_dtype_counts()\n expected = Series({'int64': 4})\n assert_series_equal(result, expected)\n\n # mixed\n df2 = df.set_index(['A', 'B'])\n df2['C'] = 3.\n df3 = df2.unstack('B')\n result = df3.get_dtype_counts()\n expected = Series({'int64': 2, 'float64': 2})\n assert_series_equal(result, expected)\n\n df2['D'] = 'foo'\n df3 = df2.unstack('B')\n result = df3.get_dtype_counts()\n expected = Series({'float64': 2, 'object': 2})\n assert_series_equal(result, expected)\n\n # GH7405\n for c, d in (np.zeros(5), np.zeros(5)), \\\n (np.arange(5, dtype='f8'), np.arange(5, 10, dtype='f8')):\n\n df = DataFrame({'A': ['a'] * 5, 'C': c, 'D': d,\n 'B': pd.date_range('2012-01-01', periods=5)})\n\n right = df.iloc[:3].copy(deep=True)\n\n df = df.set_index(['A', 'B'])\n df['D'] = df['D'].astype('int64')\n\n left = df.iloc[:3].unstack(0)\n right = right.set_index(['A', 'B']).unstack(0)\n right[('D', 'a')] = right[('D', 'a')].astype('int64')\n\n assert left.shape == (3, 2)\n tm.assert_frame_equal(left, right)\n\n def test_unstack_unused_levels(self):\n # GH 17845: unused labels in index make unstack() cast int to float\n idx = pd.MultiIndex.from_product([['a'], ['A', 'B', 'C', 'D']])[:-1]\n df = pd.DataFrame([[1, 0]] * 3, index=idx)\n\n result = df.unstack()\n exp_col = pd.MultiIndex.from_product([[0, 1], ['A', 'B', 'C']])\n expected = pd.DataFrame([[1, 1, 1, 0, 0, 0]], index=['a'],\n columns=exp_col)\n tm.assert_frame_equal(result, expected)\n assert((result.columns.levels[1] == idx.levels[1]).all())\n\n # Unused items on both levels\n levels = [[0, 1, 7], [0, 1, 2, 3]]\n labels = [[0, 0, 1, 1], [0, 2, 0, 2]]\n idx = pd.MultiIndex(levels, labels)\n block = np.arange(4).reshape(2, 2)\n df = pd.DataFrame(np.concatenate([block, block + 4]), index=idx)\n result = df.unstack()\n expected = pd.DataFrame(np.concatenate([block * 2, block * 2 + 1],\n axis=1),\n columns=idx)\n tm.assert_frame_equal(result, expected)\n assert((result.columns.levels[1] == idx.levels[1]).all())\n\n # With mixed dtype and NaN\n levels = [['a', 2, 'c'], [1, 3, 5, 7]]\n labels = [[0, -1, 1, 1], [0, 2, -1, 2]]\n idx = pd.MultiIndex(levels, labels)\n data = np.arange(8)\n df = pd.DataFrame(data.reshape(4, 2), index=idx)\n\n cases = ((0, [13, 16, 6, 9, 2, 5, 8, 11],\n [np.nan, 'a', 2], [np.nan, 5, 1]),\n (1, [8, 11, 1, 4, 12, 15, 13, 16],\n [np.nan, 5, 1], [np.nan, 'a', 2]))\n for level, idces, col_level, idx_level in cases:\n result = df.unstack(level=level)\n exp_data = np.zeros(18) * np.nan\n exp_data[idces] = data\n cols = pd.MultiIndex.from_product([[0, 1], col_level])\n expected = pd.DataFrame(exp_data.reshape(3, 6),\n index=idx_level, columns=cols)\n # Broken (GH 18455):\n # tm.assert_frame_equal(result, expected)\n diff = result - expected\n assert(diff.sum().sum() == 0)\n assert((diff + 1).sum().sum() == 8)\n\n assert((result.columns.levels[1] == idx.levels[level]).all())\n\n @pytest.mark.parametrize(\"cols\", [['A', 'C'], slice(None)])\n def test_unstack_unused_level(self, cols):\n # GH 18562 : unused labels on the unstacked level\n df = pd.DataFrame([[2010, 'a', 'I'],\n [2011, 'b', 'II']],\n columns=['A', 'B', 'C'])\n\n ind = df.set_index(['A', 'B', 'C'], drop=False)\n selection = ind.loc[(slice(None), slice(None), 'I'), cols]\n result = selection.unstack()\n\n expected = ind.iloc[[0]][cols]\n expected.columns = MultiIndex.from_product([expected.columns, ['I']],\n names=[None, 'C'])\n expected.index = expected.index.droplevel('C')\n tm.assert_frame_equal(result, expected)\n\n def test_unstack_nan_index(self): # GH7466\n cast = lambda val: '{0:1}'.format('' if val != val else val)\n nan = np.nan\n\n def verify(df):\n mk_list = lambda a: list(a) if isinstance(a, tuple) else [a]\n rows, cols = df.notna().values.nonzero()\n for i, j in zip(rows, cols):\n left = sorted(df.iloc[i, j].split('.'))\n right = mk_list(df.index[i]) + mk_list(df.columns[j])\n right = sorted(list(map(cast, right)))\n assert left == right\n\n df = DataFrame({'jim': ['a', 'b', nan, 'd'],\n 'joe': ['w', 'x', 'y', 'z'],\n 'jolie': ['a.w', 'b.x', ' .y', 'd.z']})\n\n left = df.set_index(['jim', 'joe']).unstack()['jolie']\n right = df.set_index(['joe', 'jim']).unstack()['jolie'].T\n assert_frame_equal(left, right)\n\n for idx in itertools.permutations(df.columns[:2]):\n mi = df.set_index(list(idx))\n for lev in range(2):\n udf = mi.unstack(level=lev)\n assert udf.notna().values.sum() == len(df)\n verify(udf['jolie'])\n\n df = DataFrame({'1st': ['d'] * 3 + [nan] * 5 + ['a'] * 2 +\n ['c'] * 3 + ['e'] * 2 + ['b'] * 5,\n '2nd': ['y'] * 2 + ['w'] * 3 + [nan] * 3 +\n ['z'] * 4 + [nan] * 3 + ['x'] * 3 + [nan] * 2,\n '3rd': [67, 39, 53, 72, 57, 80, 31, 18, 11, 30, 59,\n 50, 62, 59, 76, 52, 14, 53, 60, 51]})\n\n df['4th'], df['5th'] = \\\n df.apply(lambda r: '.'.join(map(cast, r)), axis=1), \\\n df.apply(lambda r: '.'.join(map(cast, r.iloc[::-1])), axis=1)\n\n for idx in itertools.permutations(['1st', '2nd', '3rd']):\n mi = df.set_index(list(idx))\n for lev in range(3):\n udf = mi.unstack(level=lev)\n assert udf.notna().values.sum() == 2 * len(df)\n for col in ['4th', '5th']:\n verify(udf[col])\n\n # GH7403\n df = pd.DataFrame(\n {'A': list('aaaabbbb'), 'B': range(8), 'C': range(8)})\n df.iloc[3, 1] = np.NaN\n left = df.set_index(['A', 'B']).unstack(0)\n\n vals = [[3, 0, 1, 2, nan, nan, nan, nan],\n [nan, nan, nan, nan, 4, 5, 6, 7]]\n vals = list(map(list, zip(*vals)))\n idx = Index([nan, 0, 1, 2, 4, 5, 6, 7], name='B')\n cols = MultiIndex(levels=[['C'], ['a', 'b']],\n labels=[[0, 0], [0, 1]],\n names=[None, 'A'])\n\n right = DataFrame(vals, columns=cols, index=idx)\n assert_frame_equal(left, right)\n\n df = DataFrame({'A': list('aaaabbbb'), 'B': list(range(4)) * 2,\n 'C': range(8)})\n df.iloc[2, 1] = np.NaN\n left = df.set_index(['A', 'B']).unstack(0)\n\n vals = [[2, nan], [0, 4], [1, 5], [nan, 6], [3, 7]]\n cols = MultiIndex(levels=[['C'], ['a', 'b']],\n labels=[[0, 0], [0, 1]],\n names=[None, 'A'])\n idx = Index([nan, 0, 1, 2, 3], name='B')\n right = DataFrame(vals, columns=cols, index=idx)\n assert_frame_equal(left, right)\n\n df = pd.DataFrame({'A': list('aaaabbbb'), 'B': list(range(4)) * 2,\n 'C': range(8)})\n df.iloc[3, 1] = np.NaN\n left = df.set_index(['A', 'B']).unstack(0)\n\n vals = [[3, nan], [0, 4], [1, 5], [2, 6], [nan, 7]]\n cols = MultiIndex(levels=[['C'], ['a', 'b']],\n labels=[[0, 0], [0, 1]],\n names=[None, 'A'])\n idx = Index([nan, 0, 1, 2, 3], name='B')\n right = DataFrame(vals, columns=cols, index=idx)\n assert_frame_equal(left, right)\n\n # GH7401\n df = pd.DataFrame({'A': list('aaaaabbbbb'), 'C': np.arange(10),\n 'B': (date_range('2012-01-01', periods=5)\n .tolist() * 2)})\n\n df.iloc[3, 1] = np.NaN\n left = df.set_index(['A', 'B']).unstack()\n\n vals = np.array([[3, 0, 1, 2, nan, 4], [nan, 5, 6, 7, 8, 9]])\n idx = Index(['a', 'b'], name='A')\n cols = MultiIndex(levels=[['C'], date_range('2012-01-01', periods=5)],\n labels=[[0, 0, 0, 0, 0, 0], [-1, 0, 1, 2, 3, 4]],\n names=[None, 'B'])\n\n right = DataFrame(vals, columns=cols, index=idx)\n assert_frame_equal(left, right)\n\n # GH4862\n vals = [['Hg', nan, nan, 680585148],\n ['U', 0.0, nan, 680585148],\n ['Pb', 7.07e-06, nan, 680585148],\n ['Sn', 2.3614e-05, 0.0133, 680607017],\n ['Ag', 0.0, 0.0133, 680607017],\n ['Hg', -0.00015, 0.0133, 680607017]]\n df = DataFrame(vals, columns=['agent', 'change', 'dosage', 's_id'],\n index=[17263, 17264, 17265, 17266, 17267, 17268])\n\n left = df.copy().set_index(['s_id', 'dosage', 'agent']).unstack()\n\n vals = [[nan, nan, 7.07e-06, nan, 0.0],\n [0.0, -0.00015, nan, 2.3614e-05, nan]]\n\n idx = MultiIndex(levels=[[680585148, 680607017], [0.0133]],\n labels=[[0, 1], [-1, 0]],\n names=['s_id', 'dosage'])\n\n cols = MultiIndex(levels=[['change'], ['Ag', 'Hg', 'Pb', 'Sn', 'U']],\n labels=[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4]],\n names=[None, 'agent'])\n\n right = DataFrame(vals, columns=cols, index=idx)\n assert_frame_equal(left, right)\n\n left = df.loc[17264:].copy().set_index(['s_id', 'dosage', 'agent'])\n assert_frame_equal(left.unstack(), right)\n\n # GH9497 - multiple unstack with nulls\n df = DataFrame({'1st': [1, 2, 1, 2, 1, 2],\n '2nd': pd.date_range('2014-02-01', periods=6,\n freq='D'),\n 'jim': 100 + np.arange(6),\n 'joe': (np.random.randn(6) * 10).round(2)})\n\n df['3rd'] = df['2nd'] - pd.Timestamp('2014-02-02')\n df.loc[1, '2nd'] = df.loc[3, '2nd'] = nan\n df.loc[1, '3rd'] = df.loc[4, '3rd'] = nan\n\n left = df.set_index(['1st', '2nd', '3rd']).unstack(['2nd', '3rd'])\n assert left.notna().values.sum() == 2 * len(df)\n\n for col in ['jim', 'joe']:\n for _, r in df.iterrows():\n key = r['1st'], (col, r['2nd'], r['3rd'])\n assert r[col] == left.loc[key]\n\n def test_stack_datetime_column_multiIndex(self):\n # GH 8039\n t = datetime(2014, 1, 1)\n df = DataFrame(\n [1, 2, 3, 4], columns=MultiIndex.from_tuples([(t, 'A', 'B')]))\n result = df.stack()\n\n eidx = MultiIndex.from_product([(0, 1, 2, 3), ('B',)])\n ecols = MultiIndex.from_tuples([(t, 'A')])\n expected = DataFrame([1, 2, 3, 4], index=eidx, columns=ecols)\n assert_frame_equal(result, expected)\n\n def test_stack_partial_multiIndex(self):\n # GH 8844\n def _test_stack_with_multiindex(multiindex):\n df = DataFrame(np.arange(3 * len(multiindex))\n .reshape(3, len(multiindex)),\n columns=multiindex)\n for level in (-1, 0, 1, [0, 1], [1, 0]):\n result = df.stack(level=level, dropna=False)\n\n if isinstance(level, int):\n # Stacking a single level should not make any all-NaN rows,\n # so df.stack(level=level, dropna=False) should be the same\n # as df.stack(level=level, dropna=True).\n expected = df.stack(level=level, dropna=True)\n if isinstance(expected, Series):\n assert_series_equal(result, expected)\n else:\n assert_frame_equal(result, expected)\n\n df.columns = MultiIndex.from_tuples(df.columns.get_values(),\n names=df.columns.names)\n expected = df.stack(level=level, dropna=False)\n if isinstance(expected, Series):\n assert_series_equal(result, expected)\n else:\n assert_frame_equal(result, expected)\n\n full_multiindex = MultiIndex.from_tuples([('B', 'x'), ('B', 'z'),\n ('A', 'y'),\n ('C', 'x'), ('C', 'u')],\n names=['Upper', 'Lower'])\n for multiindex_columns in ([0, 1, 2, 3, 4],\n [0, 1, 2, 3], [0, 1, 2, 4],\n [0, 1, 2], [1, 2, 3], [2, 3, 4],\n [0, 1], [0, 2], [0, 3],\n [0], [2], [4]):\n _test_stack_with_multiindex(full_multiindex[multiindex_columns])\n if len(multiindex_columns) > 1:\n multiindex_columns.reverse()\n _test_stack_with_multiindex(\n full_multiindex[multiindex_columns])\n\n df = DataFrame(np.arange(6).reshape(2, 3),\n columns=full_multiindex[[0, 1, 3]])\n result = df.stack(dropna=False)\n expected = DataFrame([[0, 2], [1, nan], [3, 5], [4, nan]],\n index=MultiIndex(\n levels=[[0, 1], ['u', 'x', 'y', 'z']],\n labels=[[0, 0, 1, 1],\n [1, 3, 1, 3]],\n names=[None, 'Lower']),\n columns=Index(['B', 'C'], name='Upper'),\n dtype=df.dtypes[0])\n assert_frame_equal(result, expected)\n\n def test_stack_preserve_categorical_dtype(self):\n # GH13854\n for ordered in [False, True]:\n for labels in [list(\"yxz\"), list(\"yxy\")]:\n cidx = pd.CategoricalIndex(labels, categories=list(\"xyz\"),\n ordered=ordered)\n df = DataFrame([[10, 11, 12]], columns=cidx)\n result = df.stack()\n\n # `MutliIndex.from_product` preserves categorical dtype -\n # it's tested elsewhere.\n midx = pd.MultiIndex.from_product([df.index, cidx])\n expected = Series([10, 11, 12], index=midx)\n\n tm.assert_series_equal(result, expected)\n\n\ndef test_unstack_fill_frame_object():\n # GH12815 Test unstacking with object.\n data = pd.Series(['a', 'b', 'c', 'a'], dtype='object')\n data.index = pd.MultiIndex.from_tuples(\n [('x', 'a'), ('x', 'b'), ('y', 'b'), ('z', 'a')])\n\n # By default missing values will be NaN\n result = data.unstack()\n expected = pd.DataFrame(\n {'a': ['a', np.nan, 'a'], 'b': ['b', 'c', np.nan]},\n index=list('xyz')\n )\n assert_frame_equal(result, expected)\n\n # Fill with any value replaces missing values as expected\n result = data.unstack(fill_value='d')\n expected = pd.DataFrame(\n {'a': ['a', 'd', 'a'], 'b': ['b', 'c', 'd']},\n index=list('xyz')\n )\n assert_frame_equal(result, expected)\n",
"# -*- coding: utf-8 -*-\n\nimport numpy as np\n\nimport pandas.util.testing as tm\nfrom pandas import (Categorical, Index, isna)\nfrom pandas.compat import lrange\nfrom pandas.core.dtypes.dtypes import CategoricalDtype\n\n\nclass TestCategoricalMissing(object):\n\n def test_na_flags_int_categories(self):\n # #1457\n\n categories = lrange(10)\n labels = np.random.randint(0, 10, 20)\n labels[::5] = -1\n\n cat = Categorical(labels, categories, fastpath=True)\n repr(cat)\n\n tm.assert_numpy_array_equal(isna(cat), labels == -1)\n\n def test_nan_handling(self):\n\n # Nans are represented as -1 in codes\n c = Categorical([\"a\", \"b\", np.nan, \"a\"])\n tm.assert_index_equal(c.categories, Index([\"a\", \"b\"]))\n tm.assert_numpy_array_equal(c._codes, np.array([0, 1, -1, 0],\n dtype=np.int8))\n c[1] = np.nan\n tm.assert_index_equal(c.categories, Index([\"a\", \"b\"]))\n tm.assert_numpy_array_equal(c._codes, np.array([0, -1, -1, 0],\n dtype=np.int8))\n\n # Adding nan to categories should make assigned nan point to the\n # category!\n c = Categorical([\"a\", \"b\", np.nan, \"a\"])\n tm.assert_index_equal(c.categories, Index([\"a\", \"b\"]))\n tm.assert_numpy_array_equal(c._codes, np.array([0, 1, -1, 0],\n dtype=np.int8))\n\n def test_set_dtype_nans(self):\n c = Categorical(['a', 'b', np.nan])\n result = c._set_dtype(CategoricalDtype(['a', 'c']))\n tm.assert_numpy_array_equal(result.codes, np.array([0, -1, -1],\n dtype='int8'))\n\n def test_set_item_nan(self):\n cat = Categorical([1, 2, 3])\n cat[1] = np.nan\n\n exp = Categorical([1, np.nan, 3], categories=[1, 2, 3])\n tm.assert_categorical_equal(cat, exp)\n",
"# -*- coding: utf-8 -*-\nfrom datetime import datetime\n\nimport numpy as np\nimport pandas as pd\ntry:\n import pandas.tseries.holiday # noqa\nexcept ImportError:\n pass\n\nhcal = pd.tseries.holiday.USFederalHolidayCalendar()\n# These offests currently raise a NotImplimentedError with .apply_index()\nnon_apply = [pd.offsets.Day(),\n pd.offsets.BYearEnd(),\n pd.offsets.BYearBegin(),\n pd.offsets.BQuarterEnd(),\n pd.offsets.BQuarterBegin(),\n pd.offsets.BMonthEnd(),\n pd.offsets.BMonthBegin(),\n pd.offsets.CustomBusinessDay(),\n pd.offsets.CustomBusinessDay(calendar=hcal),\n pd.offsets.CustomBusinessMonthBegin(calendar=hcal),\n pd.offsets.CustomBusinessMonthEnd(calendar=hcal),\n pd.offsets.CustomBusinessMonthEnd(calendar=hcal)]\nother_offsets = [pd.offsets.YearEnd(), pd.offsets.YearBegin(),\n pd.offsets.QuarterEnd(), pd.offsets.QuarterBegin(),\n pd.offsets.MonthEnd(), pd.offsets.MonthBegin(),\n pd.offsets.DateOffset(months=2, days=2),\n pd.offsets.BusinessDay(), pd.offsets.SemiMonthEnd(),\n pd.offsets.SemiMonthBegin()]\noffsets = non_apply + other_offsets\n\n\nclass ApplyIndex(object):\n\n goal_time = 0.2\n\n params = other_offsets\n param_names = ['offset']\n\n def setup(self, offset):\n N = 10000\n self.rng = pd.date_range(start='1/1/2000', periods=N, freq='T')\n\n def time_apply_index(self, offset):\n offset.apply_index(self.rng)\n\n\nclass OnOffset(object):\n\n goal_time = 0.2\n\n params = offsets\n param_names = ['offset']\n\n def setup(self, offset):\n self.dates = [datetime(2016, m, d)\n for m in [10, 11, 12]\n for d in [1, 2, 3, 28, 29, 30, 31]\n if not (m == 11 and d == 31)]\n\n def time_on_offset(self, offset):\n for date in self.dates:\n offset.onOffset(date)\n\n\nclass OffsetSeriesArithmetic(object):\n\n goal_time = 0.2\n params = offsets\n param_names = ['offset']\n\n def setup(self, offset):\n N = 1000\n rng = pd.date_range(start='1/1/2000', periods=N, freq='T')\n self.data = pd.Series(rng)\n\n def time_add_offset(self, offset):\n self.data + offset\n\n\nclass OffsetDatetimeIndexArithmetic(object):\n\n goal_time = 0.2\n params = offsets\n param_names = ['offset']\n\n def setup(self, offset):\n N = 1000\n self.data = pd.date_range(start='1/1/2000', periods=N, freq='T')\n\n def time_add_offset(self, offset):\n self.data + offset\n\n\nclass OffestDatetimeArithmetic(object):\n\n goal_time = 0.2\n params = offsets\n param_names = ['offset']\n\n def setup(self, offset):\n self.date = datetime(2011, 1, 1)\n self.dt64 = np.datetime64('2011-01-01 09:00Z')\n\n def time_apply(self, offset):\n offset.apply(self.date)\n\n def time_apply_np_dt64(self, offset):\n offset.apply(self.dt64)\n\n def time_add(self, offset):\n self.date + offset\n\n def time_add_10(self, offset):\n self.date + (10 * offset)\n\n def time_subtract(self, offset):\n self.date - offset\n\n def time_subtract_10(self, offset):\n self.date - (10 * offset)\n"
] |
[
[
"pandas.Series",
"pandas.MultiIndex.from_tuples",
"pandas.DataFrame",
"pandas.util.testing.assert_frame_equal",
"numpy.concatenate",
"pandas.util.testing.makePanel",
"numpy.random.randn",
"numpy.arange",
"pandas.util.testing.assert_series_equal",
"pandas.Index",
"numpy.zeros",
"pandas.compat.u",
"pandas.MultiIndex",
"pandas.Timedelta",
"pandas.MultiIndex.from_product",
"numpy.random.rand",
"pandas.date_range",
"numpy.array",
"pandas.util.testing.assert_raises_regex",
"pandas.MultiIndex.from_arrays",
"pandas.Period",
"numpy.prod",
"pandas.Timestamp"
],
[
"pandas.util.testing.assert_categorical_equal",
"pandas.Categorical",
"pandas.Index",
"pandas.core.dtypes.dtypes.CategoricalDtype",
"pandas.isna",
"numpy.array",
"pandas.compat.lrange",
"numpy.random.randint"
],
[
"pandas.Series",
"pandas.offsets.Day",
"pandas.offsets.BQuarterEnd",
"pandas.offsets.DateOffset",
"pandas.offsets.CustomBusinessMonthBegin",
"pandas.offsets.QuarterBegin",
"pandas.offsets.CustomBusinessDay",
"pandas.offsets.MonthBegin",
"pandas.offsets.BYearEnd",
"pandas.offsets.QuarterEnd",
"pandas.offsets.MonthEnd",
"pandas.offsets.BMonthBegin",
"pandas.offsets.BMonthEnd",
"pandas.offsets.BQuarterBegin",
"pandas.offsets.SemiMonthEnd",
"pandas.offsets.YearBegin",
"pandas.tseries.holiday.USFederalHolidayCalendar",
"pandas.date_range",
"pandas.offsets.YearEnd",
"pandas.offsets.SemiMonthBegin",
"pandas.offsets.CustomBusinessMonthEnd",
"numpy.datetime64",
"pandas.offsets.BYearBegin",
"pandas.offsets.BusinessDay"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.24",
"0.23",
"0.21"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jray319/tensorflow
|
[
"5cdf8f26c806e893e0773ad34e2b59008cc6f8ec",
"5cdf8f26c806e893e0773ad34e2b59008cc6f8ec",
"5cdf8f26c806e893e0773ad34e2b59008cc6f8ec",
"5cdf8f26c806e893e0773ad34e2b59008cc6f8ec"
] |
[
"tensorflow/python/kernel_tests/variables_test.py",
"tensorflow/python/kernel_tests/padding_fifo_queue_test.py",
"tensorflow/python/data/experimental/kernel_tests/optimization/map_vectorization_test.py",
"tensorflow/python/keras/tests/tracking_util_test.py"
] |
[
"# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for tf.py.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\nimport operator\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import function\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors_impl\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import gen_state_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.training import gradient_descent\nfrom tensorflow.python.util import compat\n\n\nclass VariablesTestCase(test.TestCase, parameterized.TestCase):\n\n @test_util.run_deprecated_v1\n def testDistributeStrategy(self):\n v = variables.VariableV1(0.0)\n self.assertIsNone(v._distribute_strategy)\n\n @test_util.run_v1_only(\"b/120545219\")\n def testInitialization(self):\n with self.cached_session():\n var0 = variables.VariableV1(0.0)\n self.assertEqual(\"Variable:0\", var0.name)\n self.assertEqual(\"Variable\", var0._shared_name)\n self.assertEqual([], var0.get_shape())\n self.assertEqual([], var0.get_shape())\n self.assertEqual([], var0.shape)\n\n var1 = variables.VariableV1(1.1)\n self.assertEqual(\"Variable_1:0\", var1.name)\n self.assertEqual(\"Variable_1\", var1._shared_name)\n self.assertEqual([], var1.get_shape())\n self.assertEqual([], var1.get_shape())\n self.assertEqual([], var1.shape)\n\n with self.assertRaisesOpError(\"Attempting to use uninitialized value\"):\n self.evaluate(var0)\n\n with self.assertRaisesOpError(\"Attempting to use uninitialized value\"):\n self.evaluate(var1)\n\n self.evaluate(variables.global_variables_initializer())\n\n self.assertAllClose(0.0, self.evaluate(var0))\n self.assertAllClose(1.1, self.evaluate(var1))\n\n @test_util.run_v1_only(\"b/120545219\")\n def testInitializationOrder(self):\n with self.cached_session():\n rnd = variables.Variable(random_ops.random_uniform([3, 6]), name=\"rnd\")\n self.assertEqual(\"rnd:0\", rnd.name)\n self.assertEqual([3, 6], rnd.get_shape())\n self.assertEqual([3, 6], rnd.get_shape())\n self.assertEqual([3, 6], rnd.shape)\n\n dep = variables.Variable(rnd.initialized_value(), name=\"dep\")\n self.assertEqual(\"dep:0\", dep.name)\n self.assertEqual([3, 6], dep.get_shape())\n self.assertEqual([3, 6], dep.get_shape())\n self.assertEqual([3, 6], dep.shape)\n\n # Currently have to set the shape manually for Add.\n added_val = rnd.initialized_value() + dep.initialized_value() + 2.0\n added_val.set_shape(rnd.get_shape())\n\n depdep = variables.Variable(added_val, name=\"depdep\")\n self.assertEqual(\"depdep:0\", depdep.name)\n self.assertEqual([3, 6], depdep.get_shape())\n self.assertEqual([3, 6], depdep.get_shape())\n self.assertEqual([3, 6], depdep.shape)\n\n self.evaluate(variables.global_variables_initializer())\n\n self.assertAllClose(self.evaluate(rnd), self.evaluate(dep))\n self.assertAllClose(\n self.evaluate(rnd) + self.evaluate(dep) + 2.0, self.evaluate(depdep))\n\n @test_util.run_deprecated_v1\n def testCyclicInitializer(self):\n with self.cached_session():\n cyclic = control_flow_ops.while_loop(\n cond=lambda i: i < 10,\n body=lambda i: i + 1,\n loop_vars=(constant_op.constant(0),))\n initial_value = variables._try_guard_against_uninitialized_dependencies(\n \"test\", cyclic)\n self.assertIs(initial_value, cyclic)\n\n def testIterable(self):\n with self.assertRaisesRegex(TypeError, \"not iterable\"):\n for _ in variables.Variable(0.0):\n pass\n with self.assertRaisesRegex(TypeError, \"not iterable\"):\n for _ in variables.Variable([0.0, 1.0]):\n pass\n\n @test_util.run_deprecated_v1\n def testAssignments(self):\n with self.cached_session():\n var = variables.Variable(0.0)\n plus_one = var.assign_add(1.0)\n minus_one = var.assign_sub(2.0)\n four = var.assign(4.0)\n self.evaluate(variables.global_variables_initializer())\n self.assertAllClose(0.0, self.evaluate(var))\n\n self.assertAllClose(1.0, self.evaluate(plus_one))\n self.assertAllClose(1.0, self.evaluate(var))\n\n self.assertAllClose(-1.0, self.evaluate(minus_one))\n self.assertAllClose(-1.0, self.evaluate(var))\n\n self.assertAllClose(4.0, self.evaluate(four))\n self.assertAllClose(4.0, self.evaluate(var))\n\n @test_util.run_deprecated_v1\n def testResourceAssignments(self):\n with self.session(use_gpu=True):\n var = resource_variable_ops.ResourceVariable(0.0)\n plus_one = var.assign_add(1.0)\n minus_one = var.assign_sub(2.0)\n four = var.assign(4.0)\n self.evaluate(variables.global_variables_initializer())\n self.assertAllClose(0.0, self.evaluate(var))\n\n self.evaluate(plus_one)\n self.assertAllClose(1.0, self.evaluate(var))\n\n self.evaluate(minus_one)\n self.assertAllClose(-1.0, self.evaluate(var))\n\n self.evaluate(four)\n self.assertAllClose(4.0, self.evaluate(var))\n\n def testAssignDifferentShapesEagerNotAllowed(self):\n with context.eager_mode():\n var = variables.Variable(np.zeros(shape=[1, 1]))\n with self.assertRaisesRegex(ValueError, \"Shapes.*and.*are incompatible\"):\n var.assign(np.zeros(shape=[2, 2]))\n\n @test_util.disable_tfrt(\"Graph is not supported yet. b/156187905\")\n @test_util.run_in_graph_and_eager_modes\n def testAssignDifferentShapesAllowed(self):\n var = variables.Variable(np.zeros(shape=[1, 1]),\n shape=tensor_shape.TensorShape(None))\n self.evaluate(variables.global_variables_initializer())\n self.assertAllEqual(np.zeros(shape=[1, 1]), var.read_value())\n self.evaluate(var.assign(np.zeros(shape=[2, 2])))\n self.assertAllEqual(np.zeros(shape=[2, 2]), var.read_value())\n\n @test_util.disable_tfrt(\"GetHostSize() is not expected to be called with \"\n \"string type. b/156761465\")\n def testZeroSizeStringAssign(self):\n with self.cached_session() as sess:\n array = variables.VariableV1(\n initial_value=array_ops.zeros((0,), dtype=dtypes.string),\n name=\"foo\",\n trainable=False,\n collections=[ops.GraphKeys.LOCAL_VARIABLES])\n self.evaluate(variables.local_variables_initializer())\n old_value = array.value()\n copy_op = array.assign(old_value)\n self.assertEqual([], list(self.evaluate(copy_op)))\n\n def _countUpToTest(self, dtype):\n with self.cached_session():\n zero = constant_op.constant(0, dtype=dtype)\n var = variables.Variable(zero)\n count_up_to = var.count_up_to(3)\n\n self.evaluate(variables.global_variables_initializer())\n self.assertEqual(0, self.evaluate(var))\n\n self.assertEqual(0, self.evaluate(count_up_to))\n self.assertEqual(1, self.evaluate(var))\n\n self.assertEqual(1, self.evaluate(count_up_to))\n self.assertEqual(2, self.evaluate(var))\n\n self.assertEqual(2, self.evaluate(count_up_to))\n self.assertEqual(3, self.evaluate(var))\n\n with self.assertRaisesOpError(\"Reached limit of 3\"):\n self.evaluate(count_up_to)\n self.assertEqual(3, self.evaluate(var))\n\n with self.assertRaisesOpError(\"Reached limit of 3\"):\n self.evaluate(count_up_to)\n self.assertEqual(3, self.evaluate(var))\n\n @test_util.run_deprecated_v1\n def testCountUpToInt32(self):\n self._countUpToTest(dtypes.int32)\n\n @test_util.run_deprecated_v1\n def testCountUpToInt64(self):\n self._countUpToTest(dtypes.int64)\n\n @test_util.run_v1_only(\"b/120545219\")\n def testControlDepsNone(self):\n with self.cached_session():\n c = constant_op.constant(1.0)\n with ops.control_dependencies([c]):\n # d get the control dep.\n d = constant_op.constant(2.0)\n # variables do not.\n var_x = variables.VariableV1(2.0)\n self.assertEqual([c.op], d.op.control_inputs)\n self.assertEqual([], var_x.initializer.control_inputs)\n self.assertEqual([], var_x.value().op.control_inputs)\n self.assertEqual([], var_x._ref().op.control_inputs) # pylint: disable=protected-access\n\n @test_util.run_v1_only(\"b/120545219\")\n def testControlFlow(self):\n with self.cached_session() as sess:\n v0 = variables.Variable(0, name=\"v0\")\n var_dict = {}\n\n # Call get_variable in each of the cond clauses.\n def var_in_then_clause():\n v1 = variables.Variable(1, name=\"v1\")\n var_dict[\"v1\"] = v1\n return v1 + v0\n\n def var_in_else_clause():\n v2 = variables.Variable(2, name=\"v2\")\n var_dict[\"v2\"] = v2\n return v2 + v0\n\n add = control_flow_ops.cond(\n math_ops.less(v0, 10), var_in_then_clause, var_in_else_clause)\n v1 = var_dict[\"v1\"]\n v2 = var_dict[\"v2\"]\n # We should be able to initialize and run v1 and v2 without initializing\n # v0, even if the variable was created with a control dep on v0.\n self.evaluate(v1.initializer)\n self.assertEqual([1], self.evaluate(v1))\n self.evaluate(v2.initializer)\n self.assertEqual([2], self.evaluate(v2))\n # v0 should still be uninitialized.\n with self.assertRaisesRegex(errors_impl.OpError, \"uninitialized\"):\n self.evaluate(v0)\n # We should not be able to run 'add' yet.\n with self.assertRaisesRegex(errors_impl.OpError, \"uninitialized\"):\n self.evaluate(add)\n # If we initialize v0 we should be able to run 'add'.\n self.evaluate(v0.initializer)\n self.evaluate(add)\n\n @test_util.run_v1_only(\"b/120545219\")\n def testControlFlowInitialization(self):\n \"\"\"Expects an error if an initializer is in a control-flow scope.\"\"\"\n def cond(i, _):\n return i < 10\n\n def body(i, _):\n zero = array_ops.zeros([], dtype=dtypes.int32)\n v = variables.Variable(initial_value=zero)\n return (i + 1, v.read_value())\n\n with self.assertRaisesRegex(ValueError, \"inside a control-flow\"):\n control_flow_ops.while_loop(cond, body, [0, 0])\n\n @test_util.run_deprecated_v1\n def testUseVariableAsTensor(self):\n with self.cached_session():\n var_x = variables.Variable(2.0)\n var_y = variables.Variable(3.0)\n self.evaluate(variables.global_variables_initializer())\n self.assertAllClose(2.0, self.evaluate(var_x))\n self.assertAllClose(3.0, self.evaluate(var_y))\n self.assertAllClose(5.0, self.evaluate(math_ops.add(var_x, var_y)))\n\n @test_util.run_deprecated_v1\n def testZeroSizeVarSameAsConst(self):\n with self.cached_session():\n zero_size_var = variables.Variable(array_ops.zeros([0, 2]))\n zero_size_const = array_ops.ones([2, 0])\n variable_mul = math_ops.matmul(zero_size_const, zero_size_var)\n const_mul = math_ops.matmul(\n zero_size_const, zero_size_const, transpose_b=True)\n self.evaluate(variables.global_variables_initializer())\n variable_output = self.evaluate(variable_mul)\n self.assertAllClose(self.evaluate(const_mul), variable_output)\n self.assertAllClose([[0., 0.], [0., 0.]], variable_output)\n\n @test_util.run_deprecated_v1\n def testCachingDevice(self):\n with self.cached_session():\n var = variables.Variable(2.0)\n self.assertEqual(var.device, var.initialized_value().device)\n\n var_cached = variables.Variable(2.0, caching_device=\"/job:foo\")\n self.assertFalse(var_cached.device.startswith(\"/job:foo\"))\n self.assertTrue(var_cached.value().device.startswith(\"/job:foo\"))\n\n @test_util.run_deprecated_v1\n def testCollections(self):\n with self.cached_session():\n var_x = variables.VariableV1(2.0)\n var_y = variables.VariableV1(2.0, trainable=False)\n var_z = variables.VariableV1(2.0, trainable=True)\n var_t = variables.VariableV1(\n 2.0,\n trainable=True,\n collections=[\n ops.GraphKeys.TRAINABLE_VARIABLES, ops.GraphKeys.GLOBAL_VARIABLES\n ])\n self.assertEqual([var_x, var_y, var_z, var_t],\n variables.global_variables())\n self.assertEqual([var_x, var_z, var_t], variables.trainable_variables())\n\n @test_util.run_deprecated_v1\n def testCollectionsWithScope(self):\n with self.cached_session():\n with ops.name_scope(\"scope_1\"):\n var_x = variables.VariableV1(2.0)\n with ops.name_scope(\"scope_2\"):\n var_y = variables.VariableV1(2.0)\n\n self.assertEqual([var_x, var_y], variables.global_variables())\n self.assertEqual([var_x], variables.global_variables(\"scope_1\"))\n self.assertEqual([var_y], variables.global_variables(\"scope_2\"))\n\n self.assertEqual([var_x, var_y], variables.trainable_variables())\n self.assertEqual([var_x], variables.trainable_variables(\"scope_1\"))\n self.assertEqual([var_y], variables.trainable_variables(\"scope_2\"))\n\n def testOperatorWrapping(self):\n for attr in functools.WRAPPER_ASSIGNMENTS:\n self.assertEqual(\n getattr(variables.Variable.__add__, attr),\n getattr(ops.Tensor.__add__, attr))\n\n @test_util.run_deprecated_v1\n def testOperators(self):\n with self.cached_session():\n var_f = variables.Variable([2.0])\n add = var_f + 0.0\n radd = 1.0 + var_f\n sub = var_f - 1.0\n rsub = 1.0 - var_f\n mul = var_f * 10.0\n rmul = 10.0 * var_f\n div = var_f / 10.0\n rdiv = 10.0 / var_f\n lt = var_f < 3.0\n rlt = 3.0 < var_f\n le = var_f <= 2.0\n rle = 2.0 <= var_f\n gt = var_f > 3.0\n rgt = 3.0 > var_f\n ge = var_f >= 2.0\n rge = 2.0 >= var_f\n neg = -var_f\n abs_v = abs(var_f)\n\n var_i = variables.Variable([20])\n mod = var_i % 7\n rmod = 103 % var_i\n\n var_b = variables.Variable([True, False])\n and_v = operator.and_(var_b, [True, True])\n or_v = operator.or_(var_b, [False, True])\n xor_v = operator.xor(var_b, [False, False])\n invert_v = ~var_b\n\n rnd = np.random.rand(4, 4).astype(\"f\")\n var_t = variables.Variable(rnd)\n slice_v = var_t[2, 0:0]\n\n var_m = variables.Variable([[2.0, 3.0]])\n matmul = var_m.__matmul__([[10.0], [20.0]])\n rmatmul = var_m.__rmatmul__([[10.0], [20.0]])\n\n self.evaluate(variables.global_variables_initializer())\n self.assertAllClose([2.0], self.evaluate(add))\n self.assertAllClose([3.0], self.evaluate(radd))\n self.assertAllClose([1.0], self.evaluate(sub))\n self.assertAllClose([-1.0], self.evaluate(rsub))\n self.assertAllClose([20.0], self.evaluate(mul))\n self.assertAllClose([20.0], self.evaluate(rmul))\n self.assertAllClose([0.2], self.evaluate(div))\n self.assertAllClose([5.0], self.evaluate(rdiv))\n self.assertAllClose([-2.0], self.evaluate(neg))\n self.assertAllClose([2.0], self.evaluate(abs_v))\n self.assertAllClose([True], self.evaluate(lt))\n self.assertAllClose([False], self.evaluate(rlt))\n self.assertAllClose([True], self.evaluate(le))\n self.assertAllClose([True], self.evaluate(rle))\n self.assertAllClose([False], self.evaluate(gt))\n self.assertAllClose([True], self.evaluate(rgt))\n self.assertAllClose([True], self.evaluate(ge))\n self.assertAllClose([True], self.evaluate(rge))\n\n self.assertAllClose([6], self.evaluate(mod))\n self.assertAllClose([3], self.evaluate(rmod))\n\n self.assertAllClose([True, False], self.evaluate(and_v))\n self.assertAllClose([True, True], self.evaluate(or_v))\n self.assertAllClose([True, False], self.evaluate(xor_v))\n self.assertAllClose([False, True], self.evaluate(invert_v))\n\n self.assertAllClose(rnd[2, 0:0], self.evaluate(slice_v))\n\n self.assertAllClose([[80.0]], self.evaluate(matmul))\n self.assertAllClose([[20.0, 30.0], [40.0, 60.0]], self.evaluate(rmatmul))\n\n @test_util.run_deprecated_v1\n def testSession(self):\n with self.cached_session() as sess:\n var = variables.Variable([1, 12])\n self.evaluate(variables.global_variables_initializer())\n self.assertAllClose([1, 12], self.evaluate(var))\n\n @test_util.run_v1_only(\"b/120545219\")\n def testColocation(self):\n with ops.device(\"/job:ps\"):\n var = variables.VariableV1(0, name=\"v\")\n with ops.device(\"/job:worker/task:7\"):\n assign_op = var.assign(1)\n self.assertDeviceEqual(\"/job:ps\", assign_op.device)\n self.assertEqual([b\"loc:@v\"], assign_op.op.colocation_groups())\n\n @test_util.run_v1_only(\"b/120545219\")\n def testInitializerFunction(self):\n value = [[-42], [133.7]]\n shape = [2, 1]\n with self.cached_session():\n initializer = lambda: constant_op.constant(value)\n\n v1 = variables.Variable(initializer, dtype=dtypes.float32)\n self.assertEqual(shape, v1.get_shape())\n self.assertEqual(shape, v1.shape)\n self.assertAllClose(value, self.evaluate(v1.initial_value))\n with self.assertRaises(errors_impl.FailedPreconditionError):\n self.evaluate(v1)\n\n v2 = variables.Variable(\n math_ops.negative(v1.initialized_value()), dtype=dtypes.float32)\n self.assertEqual(v1.get_shape(), v2.get_shape())\n self.assertEqual(v1.shape, v2.shape)\n self.assertAllClose(np.negative(value), self.evaluate(v2.initial_value))\n\n with self.assertRaises(errors_impl.FailedPreconditionError):\n self.evaluate(v2)\n self.evaluate(variables.global_variables_initializer())\n self.assertAllClose(np.negative(value), self.evaluate(v2))\n\n def testConstraintArg(self):\n constraint = lambda x: x\n v = variables.Variable(\n lambda: constant_op.constant(1.),\n constraint=constraint)\n self.assertEqual(v.constraint, constraint)\n\n constraint = 0\n with self.assertRaises(ValueError):\n v = variables.Variable(\n lambda: constant_op.constant(1.),\n constraint=constraint)\n\n @test_util.run_v1_only(\"b/120545219\")\n def testNoRefDataRace(self):\n with self.cached_session():\n a = variables.Variable([1, 2, 3], dtype=dtypes.float32)\n b = variables.Variable(a.initialized_value() + 2)\n c = variables.Variable(b.initialized_value() + 2)\n self.evaluate(variables.global_variables_initializer())\n self.assertAllEqual(self.evaluate(a), [1, 2, 3])\n self.assertAllEqual(self.evaluate(b), [3, 4, 5])\n self.assertAllEqual(self.evaluate(c), [5, 6, 7])\n\n @test_util.run_deprecated_v1\n def testInitializerFunctionDevicePlacement(self):\n with self.cached_session():\n initializer = lambda: constant_op.constant(42.0)\n with ops.device(\"/cpu:100\"):\n v1 = variables.Variable(initializer, dtype=dtypes.float32, name=\"v1\")\n expected_device = \"/device:CPU:100\"\n expected_group_v1 = [b\"loc:@v1\"]\n self.assertEqual(expected_device, v1.op.device)\n self.assertEqual(expected_group_v1, v1.op.colocation_groups())\n for i in v1.initializer.inputs:\n self.assertEqual(expected_group_v1, i.op.colocation_groups())\n\n v2 = variables.Variable(initializer, dtype=dtypes.float32, name=\"v2\")\n expected_group_v2 = [b\"loc:@v2\"]\n self.assertEqual(expected_group_v2, v2.op.colocation_groups())\n for i in v2.initializer.inputs:\n self.assertEqual(expected_group_v2, i.op.colocation_groups())\n\n @test_util.run_v1_only(\"b/120545219\")\n def testVariableDefInitializedInstances(self):\n with ops.Graph().as_default(), self.cached_session() as sess:\n v_def = variables.Variable(\n initial_value=constant_op.constant(3.0)).to_proto()\n\n with ops.Graph().as_default(), self.cached_session() as sess:\n # v describes a VariableDef-based variable without an initial value.\n v = variables.Variable(variable_def=v_def)\n self.assertEqual(3.0, self.evaluate(v.initialized_value()))\n\n # initialized_value should not rerun the initializer_op if the variable\n # has already been initialized elsewhere.\n self.evaluate(v.assign(1.0))\n self.assertEqual(1.0, self.evaluate(v.initialized_value()))\n\n v_def.ClearField(\"initial_value_name\")\n with ops.Graph().as_default(), self.cached_session() as sess:\n # Restoring a legacy VariableDef proto that does not have\n # initial_value_name set should still work.\n v = variables.Variable(variable_def=v_def)\n # We should also be able to re-export the variable to a new meta graph.\n self.assertProtoEquals(v_def, v.to_proto())\n # But attempts to use initialized_value will result in errors.\n with self.assertRaises(ValueError):\n self.evaluate(v.initialized_value())\n\n def testTrainableInProto(self):\n with ops.Graph().as_default():\n non_trainable_variable = variables.Variable(\n trainable=False,\n initial_value=constant_op.constant(10.0))\n self.assertEqual(\n False,\n variables.Variable(variable_def=non_trainable_variable.to_proto())\n .trainable)\n trainable_variable = variables.Variable(\n trainable=True,\n initial_value=constant_op.constant(10.0))\n self.assertEqual(\n True,\n variables.Variable(variable_def=trainable_variable.to_proto())\n .trainable)\n\n def testSynchronizationAndAggregationSaved(self):\n with ops.Graph().as_default():\n original_variable = variables.Variable(\n initial_value=constant_op.constant(10.0),\n synchronization=variables.VariableSynchronization.NONE,\n aggregation=variables.VariableAggregationV2.ONLY_FIRST_REPLICA)\n self.assertEqual(variables.VariableSynchronization.NONE,\n original_variable.synchronization)\n self.assertEqual(variables.VariableAggregation.ONLY_FIRST_REPLICA,\n original_variable.aggregation)\n\n laundered = variables.Variable(\n variable_def=original_variable.to_proto())\n self.assertEqual(\n variables.VariableSynchronization.NONE,\n laundered.synchronization)\n self.assertEqual(variables.VariableAggregationV2.ONLY_FIRST_REPLICA,\n laundered.aggregation)\n\n @test_util.run_deprecated_v1\n def testLoad(self):\n with self.cached_session():\n var = variables.Variable(np.zeros((5, 5), np.float32))\n self.evaluate(variables.global_variables_initializer())\n var.load(np.ones((5, 5), np.float32))\n\n self.assertAllClose(np.ones((5, 5), np.float32), self.evaluate(var))\n\n @test_util.run_v1_only(\"b/120545219\")\n def testRepr(self):\n var = variables.VariableV1(np.zeros((5, 5), np.float32), name=\"noop\")\n self.assertEqual(\n \"<tf.Variable 'noop:0' shape=(5, 5) dtype=float32_ref>\",\n repr(var))\n\n def testVariableNamesPreserveNameScopesWithDefun(self):\n @function.defun\n def create_variable():\n with ops.name_scope(\"foo\"):\n v = variables.Variable(0.0, name=\"bar\")\n self.assertEqual(v.name, \"foo/bar:0\")\n with ops.get_default_graph().as_default():\n create_variable()\n\n @parameterized.parameters(variables.VariableV1, variables.Variable)\n def testTrainableVariable(self, cls):\n v1 = cls(1.0)\n self.assertEqual(True, v1.trainable)\n\n v2 = cls(1.0, synchronization=variables.VariableSynchronization.ON_READ)\n self.assertEqual(False, v2.trainable)\n\n v3 = cls(1.0, synchronization=variables.VariableSynchronization.ON_READ,\n trainable=True)\n self.assertEqual(True, v3.trainable)\n\n v4 = cls(1.0, synchronization=variables.VariableSynchronization.ON_READ,\n trainable=False)\n self.assertEqual(False, v4.trainable)\n\n\nclass IsInitializedTest(test.TestCase):\n\n def testNoVars(self):\n with ops.Graph().as_default(), self.cached_session() as sess:\n uninited = variables.report_uninitialized_variables()\n self.assertEqual(0, self.evaluate(uninited).size)\n\n def testAssertVariablesInitialized(self):\n with ops.Graph().as_default(), self.cached_session() as sess:\n v = variables.Variable([1, 2], name=\"v\")\n w = variables.Variable([3, 4], name=\"w\")\n _ = v, w\n uninited = variables.report_uninitialized_variables()\n self.assertAllEqual(np.array([b\"v\", b\"w\"]), self.evaluate(uninited))\n self.evaluate(variables.global_variables_initializer())\n self.assertEqual(0, self.evaluate(uninited).size)\n\n @test_util.run_v1_only(\"b/120545219\")\n def testVariableList(self):\n with ops.Graph().as_default(), self.cached_session() as sess:\n v = variables.VariableV1([1, 2], name=\"v\")\n w = variables.VariableV1([3, 4], name=\"w\")\n uninited = variables.report_uninitialized_variables()\n self.assertAllEqual(np.array([b\"v\", b\"w\"]), self.evaluate(uninited))\n self.evaluate(w.initializer)\n self.assertAllEqual(np.array([b\"v\"]), self.evaluate(uninited))\n v.initializer.run()\n self.assertEqual(0, self.evaluate(uninited).size)\n\n def testZeroSizeVarInitialized(self):\n with ops.Graph().as_default(), self.cached_session() as sess:\n v = variables.Variable(array_ops.zeros([0, 2]), name=\"v\")\n uninited = variables.report_uninitialized_variables()\n v.initializer.run() # not strictly necessary\n self.assertEqual(0, self.evaluate(uninited).size)\n\n def testTrainingWithZeroSizeVar(self):\n with ops.Graph().as_default(), self.cached_session() as sess:\n a = variables.Variable(array_ops.zeros([0, 2]))\n b = variables.Variable(array_ops.ones([2, 2]))\n objective = math_ops.reduce_sum(b + math_ops.matmul(\n a, a, transpose_a=True))\n self.evaluate(variables.global_variables_initializer())\n do_opt = gradient_descent.GradientDescentOptimizer(0.1).minimize(\n objective)\n self.evaluate([do_opt])\n self.assertAllClose([[0.9, 0.9], [0.9, 0.9]], self.evaluate(b))\n\n\n@test_util.run_v1_only(\"b/120545219\")\nclass ObsoleteIsInitializedTest(test.TestCase):\n\n def testNoVars(self):\n with ops.Graph().as_default():\n self.assertEqual(None, variables.assert_variables_initialized())\n\n def testVariables(self):\n with ops.Graph().as_default(), self.cached_session() as sess:\n v = variables.VariableV1([1, 2])\n w = variables.VariableV1([3, 4])\n _ = v, w\n inited = variables.assert_variables_initialized()\n with self.assertRaisesOpError(\"Attempting to use uninitialized value\"):\n self.evaluate(inited)\n self.evaluate(variables.global_variables_initializer())\n self.evaluate(inited)\n\n def testVariableList(self):\n with ops.Graph().as_default(), self.cached_session() as sess:\n v = variables.VariableV1([1, 2])\n w = variables.VariableV1([3, 4])\n inited = variables.assert_variables_initialized([v])\n with self.assertRaisesOpError(\"Attempting to use uninitialized value\"):\n inited.op.run()\n self.evaluate(w.initializer)\n with self.assertRaisesOpError(\"Attempting to use uninitialized value\"):\n inited.op.run()\n v.initializer.run()\n inited.op.run()\n\n\nclass PartitionedVariableTest(test.TestCase):\n\n def testPartitionedVariable(self):\n with ops.Graph().as_default():\n v0 = variables.Variable([0])\n v1 = variables.Variable([1])\n v0._set_save_slice_info(\n variables.Variable.SaveSliceInfo(v0.name, [2], [0], [1]))\n v1._set_save_slice_info(\n variables.Variable.SaveSliceInfo(v0.name, [2], [1], [1]))\n partitions = [2]\n\n # Pass variable_list as [v1, v0] to ensure they are properly\n # re-sorted to [v0, v1] based on their slice info offsets.\n partitioned_variable = variables.PartitionedVariable(\n name=\"two_vars\",\n shape=[2],\n dtype=v0.dtype,\n variable_list=[v1, v0],\n partitions=partitions)\n\n concatenated = ops.convert_to_tensor(partitioned_variable)\n num_partitions = len(partitioned_variable)\n iterated_partitions = list(partitioned_variable)\n self.assertEqual(2, num_partitions)\n self.assertEqual([v0, v1], iterated_partitions)\n self.assertEqual([2], partitioned_variable.get_shape())\n self.assertEqual([2], partitioned_variable.shape)\n self.assertEqual([2], concatenated.get_shape())\n self.assertEqual([2], concatenated.shape)\n\n def testPartitionedVariableFailures(self):\n with ops.Graph().as_default():\n with self.assertRaisesRegex(ValueError, \"empty\"):\n variables.PartitionedVariable(\n name=\"fail\",\n shape=2,\n dtype=dtypes.int32,\n variable_list=[],\n partitions=[])\n\n with self.assertRaisesRegex(ValueError, \"must have a save_slice_info\"):\n v0 = variables.Variable([0])\n partitions = [1]\n variables.PartitionedVariable(\n name=\"two_vars\",\n shape=[1],\n dtype=v0.dtype,\n variable_list=[v0],\n partitions=partitions)\n\n with self.assertRaisesRegex(ValueError, \"full shapes must match\"):\n v0 = variables.Variable([0])\n v1 = variables.Variable([1])\n v0._set_save_slice_info(\n variables.Variable.SaveSliceInfo(v0.name, [2], [0], [1]))\n v1._set_save_slice_info(\n variables.Variable.SaveSliceInfo(v0.name, [2], [1], [1]))\n partitions = [2]\n\n variables.PartitionedVariable(\n name=\"two_vars\",\n shape=[3],\n dtype=v0.dtype,\n variable_list=[v1, v0],\n partitions=partitions)\n\n with self.assertRaisesRegex(ValueError, \"must be positive\"):\n v0 = variables.Variable([0])\n v0._set_save_slice_info(\n variables.Variable.SaveSliceInfo(v0.name, [2], [0], [1]))\n partitions = [0]\n\n variables.PartitionedVariable(\n name=\"two_vars\",\n shape=[2],\n dtype=v0.dtype,\n variable_list=[v0],\n partitions=partitions)\n\n def testPartitionedVariableAssignments(self):\n with ops.Graph().as_default(), self.cached_session():\n v0 = variables.Variable(initial_value=[0.0])\n v1 = variables.Variable(initial_value=[1.0])\n v2 = variables.Variable(initial_value=[20.0])\n v3 = variables.Variable(initial_value=[30.0])\n v0._set_save_slice_info(\n variables.Variable.SaveSliceInfo(v0.name, [2], [0], [1]))\n v1._set_save_slice_info(\n variables.Variable.SaveSliceInfo(v1.name, [2], [1], [1]))\n v2._set_save_slice_info(\n variables.Variable.SaveSliceInfo(v2.name, [2], [0], [1]))\n v3._set_save_slice_info(\n variables.Variable.SaveSliceInfo(v3.name, [2], [1], [1]))\n\n partitions = [2]\n\n # Pass variable_list as [v1, v0] to ensure they are properly\n # re-sorted to [v0, v1] based on their slice info offsets.\n pv_0 = variables.PartitionedVariable(\n name=\"two_vars\",\n shape=[2],\n dtype=v0.dtype,\n variable_list=[v0, v1],\n partitions=partitions)\n\n pv_1 = variables.PartitionedVariable(\n name=\"two_vars\",\n shape=[2],\n dtype=v0.dtype,\n variable_list=[v2, v3],\n partitions=partitions)\n\n deltas_a = constant_op.constant([1.0, 2.0])\n deltas_b = constant_op.constant([3.0, 4.0])\n ones = array_ops.ones([2])\n plus_delta = pv_0.assign_add(deltas_a)\n minus_delta = pv_0.assign_sub(deltas_b)\n assign_ones = pv_0.assign(ones)\n\n c_0 = constant_op.constant([2.0])\n c_1 = constant_op.constant([3.0])\n assign_list = pv_1.assign([c_0, c_1])\n assign_part_value = pv_1.assign_add(assign_ones)\n assign_part_var = pv_1.assign_sub(pv_0)\n self.evaluate(variables.global_variables_initializer())\n\n self.assertEqual([1.0], self.evaluate(plus_delta[0]))\n self.assertEqual([1.0], self.evaluate(v0))\n self.assertEqual([3.0], self.evaluate(plus_delta[1]))\n self.assertEqual([3.0], self.evaluate(v1))\n\n self.assertEqual([-2.0], self.evaluate(minus_delta[0]))\n self.assertEqual([-2.0], self.evaluate(v0))\n self.assertEqual([-1.0], self.evaluate(minus_delta[1]))\n self.assertEqual([-1.0], self.evaluate(v1))\n\n self.assertEqual([1.0], self.evaluate(assign_ones[0]))\n self.assertEqual([1.0], self.evaluate(v0))\n self.assertEqual([1.0], self.evaluate(assign_ones[1]))\n self.assertEqual([1.0], self.evaluate(v1))\n\n self.assertEqual([2.0], self.evaluate(assign_list[0]))\n self.assertEqual([2.0], self.evaluate(v2))\n self.assertEqual([3.0], self.evaluate(assign_list[1]))\n self.assertEqual([3.0], self.evaluate(v3))\n\n self.assertEqual([3.0], self.evaluate(assign_part_value[0]))\n self.assertEqual([3.0], self.evaluate(v2))\n self.assertEqual([4.0], self.evaluate(assign_part_value[1]))\n self.assertEqual([4.0], self.evaluate(v3))\n\n self.assertEqual([2.0], self.evaluate(assign_part_var[0]))\n self.assertEqual([2.0], self.evaluate(v2))\n self.assertEqual([3.0], self.evaluate(assign_part_var[1]))\n self.assertEqual([3.0], self.evaluate(v3))\n\n\nclass VariableContainerTest(test.TestCase):\n\n def testContainer(self):\n with ops.Graph().as_default():\n v0 = variables.Variable([0])\n with ops.container(\"l1\"):\n v1 = variables.Variable([1])\n with ops.container(\"l2\"):\n v2 = variables.Variable([2])\n special_v = gen_state_ops.variable(\n shape=[1],\n dtype=dtypes.float32,\n name=\"VariableInL3\",\n container=\"l3\",\n shared_name=\"\")\n v3 = variables.Variable([3])\n v4 = variables.Variable([4])\n self.assertEqual(compat.as_bytes(\"\"), v0.op.get_attr(\"container\"))\n self.assertEqual(compat.as_bytes(\"l1\"), v1.op.get_attr(\"container\"))\n self.assertEqual(compat.as_bytes(\"l2\"), v2.op.get_attr(\"container\"))\n self.assertEqual(compat.as_bytes(\"l3\"), special_v.op.get_attr(\"container\"))\n self.assertEqual(compat.as_bytes(\"l1\"), v3.op.get_attr(\"container\"))\n self.assertEqual(compat.as_bytes(\"\"), v4.op.get_attr(\"container\"))\n\n\nclass AggregationModesTest(test.TestCase):\n\n def testV1V2Equal(self):\n v1 = variables.VariableAggregation\n v2 = variables.VariableAggregationV2\n\n self.assertEqual(v1.NONE, v2.NONE)\n self.assertEqual(v1.SUM, v2.SUM)\n self.assertEqual(v1.MEAN, v2.MEAN)\n self.assertEqual(v1.ONLY_FIRST_REPLICA, v2.ONLY_FIRST_REPLICA)\n self.assertEqual(v1.ONLY_FIRST_TOWER, v2.ONLY_FIRST_REPLICA)\n\n self.assertEqual(v2.NONE, v1.NONE)\n self.assertEqual(v2.SUM, v1.SUM)\n self.assertEqual(v2.MEAN, v1.MEAN)\n self.assertEqual(v2.ONLY_FIRST_REPLICA, v1.ONLY_FIRST_REPLICA)\n self.assertEqual(v2.ONLY_FIRST_REPLICA, v1.ONLY_FIRST_TOWER)\n\n self.assertEqual(hash(v1.NONE), hash(v2.NONE))\n self.assertEqual(hash(v1.SUM), hash(v2.SUM))\n self.assertEqual(hash(v1.MEAN), hash(v2.MEAN))\n self.assertEqual(hash(v1.ONLY_FIRST_REPLICA), hash(v2.ONLY_FIRST_REPLICA))\n self.assertEqual(hash(v1.ONLY_FIRST_TOWER), hash(v2.ONLY_FIRST_REPLICA))\n\nif __name__ == \"__main__\":\n test.main()\n",
"# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for tensorflow.ops.data_flow_ops.PaddingFIFOQueue.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport random\nimport time\n\nimport numpy as np\nfrom six.moves import xrange # pylint: disable=redefined-builtin\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes as dtypes_lib\nfrom tensorflow.python.framework import errors_impl\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import data_flow_ops\nfrom tensorflow.python.platform import test\n\n\n@test_util.run_v1_only(\"PaddingFIFOQueue removed from v2\")\nclass PaddingFIFOQueueTest(test.TestCase):\n\n def testConstructor(self):\n with ops.Graph().as_default():\n q = data_flow_ops.PaddingFIFOQueue(\n 10, dtypes_lib.float32, ((None,),), name=\"Q\")\n self.assertTrue(isinstance(q.queue_ref, ops.Tensor))\n self.assertProtoEquals(\"\"\"\n name:'Q' op:'PaddingFIFOQueueV2'\n attr { key: 'component_types' value { list { type: DT_FLOAT } } }\n attr { key: 'shapes' value { list { shape { dim { size: -1 } } } } }\n attr { key: 'capacity' value { i: 10 } }\n attr { key: 'container' value { s: '' } }\n attr { key: 'shared_name' value { s: '' } }\n \"\"\", q.queue_ref.op.node_def)\n\n def testMultiQueueConstructor(self):\n with ops.Graph().as_default():\n q = data_flow_ops.PaddingFIFOQueue(\n 5, (dtypes_lib.int32, dtypes_lib.float32), ((), ()),\n shared_name=\"foo\",\n name=\"Q\")\n self.assertTrue(isinstance(q.queue_ref, ops.Tensor))\n self.assertProtoEquals(\"\"\"\n name:'Q' op:'PaddingFIFOQueueV2'\n attr { key: 'component_types' value { list {\n type: DT_INT32 type : DT_FLOAT\n } } }\n attr { key: 'shapes' value { list { shape { } shape { } } } }\n attr { key: 'capacity' value { i: 5 } }\n attr { key: 'container' value { s: '' } }\n attr { key: 'shared_name' value { s: 'foo' } }\n \"\"\", q.queue_ref.op.node_def)\n\n def testConstructorWithShapes(self):\n with ops.Graph().as_default():\n q = data_flow_ops.PaddingFIFOQueue(\n 5, (dtypes_lib.int32, dtypes_lib.float32),\n shapes=(tensor_shape.TensorShape([1, 1, 2, 3]),\n tensor_shape.TensorShape([5, 8])),\n name=\"Q\")\n self.assertTrue(isinstance(q.queue_ref, ops.Tensor))\n self.assertProtoEquals(\"\"\"\n name:'Q' op:'PaddingFIFOQueueV2'\n attr { key: 'component_types' value { list {\n type: DT_INT32 type : DT_FLOAT\n } } }\n attr { key: 'shapes' value { list {\n shape { dim { size: 1 }\n dim { size: 1 }\n dim { size: 2 }\n dim { size: 3 } }\n shape { dim { size: 5 }\n dim { size: 8 } }\n } } }\n attr { key: 'capacity' value { i: 5 } }\n attr { key: 'container' value { s: '' } }\n attr { key: 'shared_name' value { s: '' } }\n \"\"\", q.queue_ref.op.node_def)\n\n def testEnqueue(self):\n with self.cached_session():\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n enqueue_op = q.enqueue((10.0,))\n enqueue_op.run()\n\n def testEnqueueWithShape(self):\n with self.cached_session():\n q = data_flow_ops.PaddingFIFOQueue(\n 10, dtypes_lib.float32, shapes=((3, 2),))\n enqueue_correct_op = q.enqueue(([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],))\n enqueue_correct_op.run()\n with self.assertRaises(ValueError):\n q.enqueue(([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]],))\n self.assertEqual(1, q.size().eval())\n\n def testEnqueueManyWithShape(self):\n with self.cached_session():\n q = data_flow_ops.PaddingFIFOQueue(\n 10, [dtypes_lib.int32, dtypes_lib.int32], shapes=[(), (2,)])\n q.enqueue_many([[1, 2, 3, 4], [[1, 1], [2, 2], [3, 3], [4, 4]]]).run()\n self.assertEqual(4, q.size().eval())\n\n def testParallelEnqueue(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n elems = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0]\n enqueue_ops = [q.enqueue((x,)) for x in elems]\n dequeued_t = q.dequeue()\n\n # Run one producer thread for each element in elems.\n def enqueue(enqueue_op):\n self.evaluate(enqueue_op)\n\n threads = [\n self.checkedThread(\n target=enqueue, args=(e,)) for e in enqueue_ops\n ]\n for thread in threads:\n thread.start()\n for thread in threads:\n thread.join()\n\n # Dequeue every element using a single thread.\n results = []\n for _ in xrange(len(elems)):\n results.append(dequeued_t.eval())\n self.assertItemsEqual(elems, results)\n\n def testParallelDequeue(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n elems = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0]\n enqueue_ops = [q.enqueue((x,)) for x in elems]\n dequeued_t = q.dequeue()\n\n # Enqueue every element using a single thread.\n for enqueue_op in enqueue_ops:\n enqueue_op.run()\n\n # Run one consumer thread for each element in elems.\n results = []\n\n def dequeue():\n results.append(self.evaluate(dequeued_t))\n\n threads = [self.checkedThread(target=dequeue) for _ in enqueue_ops]\n for thread in threads:\n thread.start()\n for thread in threads:\n thread.join()\n self.assertItemsEqual(elems, results)\n\n def testDequeue(self):\n with self.cached_session():\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n elems = [10.0, 20.0, 30.0]\n enqueue_ops = [q.enqueue((x,)) for x in elems]\n dequeued_t = q.dequeue()\n\n for enqueue_op in enqueue_ops:\n enqueue_op.run()\n\n for i in xrange(len(elems)):\n vals = self.evaluate(dequeued_t)\n self.assertEqual([elems[i]], vals)\n\n def testEnqueueAndBlockingDequeue(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(3, dtypes_lib.float32, ((),))\n elems = [10.0, 20.0, 30.0]\n enqueue_ops = [q.enqueue((x,)) for x in elems]\n dequeued_t = q.dequeue()\n\n def enqueue():\n # The enqueue_ops should run after the dequeue op has blocked.\n # TODO(mrry): Figure out how to do this without sleeping.\n time.sleep(0.1)\n for enqueue_op in enqueue_ops:\n self.evaluate(enqueue_op)\n\n results = []\n\n def dequeue():\n for _ in xrange(len(elems)):\n results.append(self.evaluate(dequeued_t))\n\n enqueue_thread = self.checkedThread(target=enqueue)\n dequeue_thread = self.checkedThread(target=dequeue)\n enqueue_thread.start()\n dequeue_thread.start()\n enqueue_thread.join()\n dequeue_thread.join()\n\n for elem, result in zip(elems, results):\n self.assertEqual([elem], result)\n\n def testMultiEnqueueAndDequeue(self):\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(10,\n (dtypes_lib.int32, dtypes_lib.float32),\n ((), ()))\n elems = [(5, 10.0), (10, 20.0), (15, 30.0)]\n enqueue_ops = [q.enqueue((x, y)) for x, y in elems]\n dequeued_t = q.dequeue()\n\n for enqueue_op in enqueue_ops:\n enqueue_op.run()\n\n for i in xrange(len(elems)):\n x_val, y_val = self.evaluate(dequeued_t)\n x, y = elems[i]\n self.assertEqual([x], x_val)\n self.assertEqual([y], y_val)\n\n def testQueueSizeEmpty(self):\n with self.cached_session():\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n self.assertEqual([0], q.size().eval())\n\n def testQueueSizeAfterEnqueueAndDequeue(self):\n with self.cached_session():\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n enqueue_op = q.enqueue((10.0,))\n dequeued_t = q.dequeue()\n size = q.size()\n self.assertEqual([], size.get_shape())\n\n enqueue_op.run()\n self.assertEqual(1, self.evaluate(size))\n dequeued_t.op.run()\n self.assertEqual(0, self.evaluate(size))\n\n def testEnqueueMany(self):\n with self.cached_session():\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n elems = [10.0, 20.0, 30.0, 40.0]\n enqueue_op = q.enqueue_many((elems,))\n dequeued_t = q.dequeue()\n enqueue_op.run()\n enqueue_op.run()\n\n for i in range(8):\n vals = self.evaluate(dequeued_t)\n self.assertEqual([elems[i % 4]], vals)\n\n def testEmptyEnqueueMany(self):\n with self.cached_session():\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, (\n (None, None),))\n empty_t = constant_op.constant(\n [], dtype=dtypes_lib.float32, shape=[0, 2, 3])\n enqueue_op = q.enqueue_many((empty_t,))\n size_t = q.size()\n\n self.assertEqual([0], self.evaluate(size_t))\n enqueue_op.run()\n self.assertEqual([0], self.evaluate(size_t))\n\n def testEmptyDequeueMany(self):\n with self.cached_session():\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, shapes=((),))\n enqueue_op = q.enqueue((10.0,))\n dequeued_t = q.dequeue_many(0)\n\n self.assertEqual([], self.evaluate(dequeued_t).tolist())\n enqueue_op.run()\n self.assertEqual([], self.evaluate(dequeued_t).tolist())\n\n def testEmptyDequeueManyWithDynamicShape(self):\n with self.cached_session():\n q = data_flow_ops.PaddingFIFOQueue(\n 10, dtypes_lib.float32, shapes=((None,),))\n enqueue_op = q.enqueue(([10.0],))\n dequeued_t = q.dequeue_many(0)\n\n self.assertEqual([], self.evaluate(dequeued_t).tolist())\n enqueue_op.run()\n self.assertEqual([], self.evaluate(dequeued_t).tolist())\n\n def testEmptyDequeueUpToWithDynamicShape(self):\n with self.cached_session():\n q = data_flow_ops.PaddingFIFOQueue(\n 10, dtypes_lib.float32, shapes=((None,),))\n enqueue_op = q.enqueue(([10.0],))\n dequeued_t = q.dequeue_up_to(0)\n\n self.assertEqual([], self.evaluate(dequeued_t).tolist())\n enqueue_op.run()\n self.assertEqual([], self.evaluate(dequeued_t).tolist())\n\n def testConstructPaddingFIFOQueueWithNoShape(self):\n with self.cached_session():\n with self.assertRaisesRegex(\n ValueError,\n r\"When providing partial shapes, a list of shapes must be provided.\"):\n data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32,\n None).queue_ref.eval()\n\n def testMultiEnqueueMany(self):\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(10,\n (dtypes_lib.float32, dtypes_lib.int32),\n ((), (2,)))\n float_elems = [10.0, 20.0, 30.0, 40.0]\n int_elems = [[1, 2], [3, 4], [5, 6], [7, 8]]\n enqueue_op = q.enqueue_many((float_elems, int_elems))\n dequeued_t = q.dequeue()\n\n enqueue_op.run()\n enqueue_op.run()\n\n for i in range(8):\n float_val, int_val = self.evaluate(dequeued_t)\n self.assertEqual(float_elems[i % 4], float_val)\n self.assertAllEqual(int_elems[i % 4], int_val)\n\n def testMultiEnqueueManyWithPartiallyKnownShapes(self):\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(\n 10, (dtypes_lib.float32, dtypes_lib.int32), shapes=((), (None,)))\n float_elems = [10.0, 20.0, 30.0, 40.0]\n int_elems = [[1, 2], [3, 4], [5, 6], [7, 8]]\n enqueue_op = q.enqueue_many((float_elems, int_elems))\n dequeued_t = q.dequeue()\n\n enqueue_op.run()\n enqueue_op.run()\n\n for i in range(8):\n float_val, int_val = self.evaluate(dequeued_t)\n self.assertEqual(float_elems[i % 4], float_val)\n self.assertAllEqual(int_elems[i % 4], int_val)\n\n def testDequeueMany(self):\n with self.cached_session():\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n elems = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0]\n enqueue_op = q.enqueue_many((elems,))\n dequeued_t = q.dequeue_many(4)\n\n enqueue_op.run()\n\n self.assertAllEqual(elems[0:4], self.evaluate(dequeued_t))\n self.assertAllEqual(elems[4:8], self.evaluate(dequeued_t))\n\n def testDequeueUpToNoBlocking(self):\n with self.cached_session():\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n elems = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0]\n enqueue_op = q.enqueue_many((elems,))\n dequeued_t = q.dequeue_up_to(4)\n\n enqueue_op.run()\n\n self.assertAllEqual(elems[0:4], self.evaluate(dequeued_t))\n self.assertAllEqual(elems[4:8], self.evaluate(dequeued_t))\n\n def testMultiDequeueMany(self):\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(\n 10, (dtypes_lib.float32, dtypes_lib.int32), shapes=((), (2,)))\n float_elems = [\n 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0\n ]\n int_elems = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [13, 14],\n [15, 16], [17, 18], [19, 20]]\n enqueue_op = q.enqueue_many((float_elems, int_elems))\n dequeued_t = q.dequeue_many(4)\n dequeued_single_t = q.dequeue()\n\n enqueue_op.run()\n\n float_val, int_val = self.evaluate(dequeued_t)\n self.assertAllEqual(float_elems[0:4], float_val)\n self.assertAllEqual(int_elems[0:4], int_val)\n self.assertEqual(float_val.shape, dequeued_t[0].get_shape())\n self.assertEqual(int_val.shape, dequeued_t[1].get_shape())\n\n float_val, int_val = self.evaluate(dequeued_t)\n self.assertAllEqual(float_elems[4:8], float_val)\n self.assertAllEqual(int_elems[4:8], int_val)\n\n float_val, int_val = self.evaluate(dequeued_single_t)\n self.assertAllEqual(float_elems[8], float_val)\n self.assertAllEqual(int_elems[8], int_val)\n self.assertEqual(float_val.shape, dequeued_single_t[0].get_shape())\n self.assertEqual(int_val.shape, dequeued_single_t[1].get_shape())\n\n def testMultiDequeueManyWithPartiallyKnownShapes(self):\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(\n 10, (dtypes_lib.float32, dtypes_lib.int32), shapes=((), (None,)))\n float_elems = [\n 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0\n ]\n int_elems = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [13, 14],\n [15, 16], [17, 18], [19, 20]]\n enqueue_op = q.enqueue_many((float_elems, int_elems))\n dequeued_t = q.dequeue_many(4)\n dequeued_single_t = q.dequeue()\n\n enqueue_op.run()\n\n float_val, int_val = self.evaluate(dequeued_t)\n self.assertAllEqual(float_elems[0:4], float_val)\n self.assertAllEqual(int_elems[0:4], int_val)\n self.assertTrue(\n tensor_shape.TensorShape(float_val.shape).is_compatible_with(\n dequeued_t[0].get_shape()))\n self.assertTrue(\n tensor_shape.TensorShape(int_val.shape).is_compatible_with(dequeued_t[\n 1].get_shape()))\n\n float_val, int_val = self.evaluate(dequeued_t)\n self.assertAllEqual(float_elems[4:8], float_val)\n self.assertAllEqual(int_elems[4:8], int_val)\n\n float_val, int_val = self.evaluate(dequeued_single_t)\n self.assertAllEqual(float_elems[8], float_val)\n self.assertAllEqual(int_elems[8], int_val)\n self.assertTrue(\n tensor_shape.TensorShape(float_val.shape).is_compatible_with(\n dequeued_single_t[0].get_shape()))\n self.assertTrue(\n tensor_shape.TensorShape(int_val.shape).is_compatible_with(\n dequeued_single_t[1].get_shape()))\n\n def testMultiDequeueManyWithPartiallyKnownShapesAndVariableSizeInput(self):\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(\n 10, (dtypes_lib.string, dtypes_lib.int32),\n shapes=((None,), (1, None)))\n str_elems = [[\"a\"], [\"ab\"], [\"abc\"], [\"abc\", \"d\"], [\"abc\", \"d\", \"e\"],\n [\"abc\", \"d\", \"e\", \"f\"]]\n\n int_elems = [[[1]], [[2]], [[3]], [[1, 2]], [[1, 2, 3]], [[1, 2, 3, 4]]]\n\n enqueue_ops = [q.enqueue((str_elems[i], int_elems[i])) for i in range(6)]\n\n dequeued_t = q.dequeue_many(5)\n dequeued_single_t = q.dequeue()\n\n for enqueue_op in enqueue_ops:\n enqueue_op.run()\n string_val, int_val = self.evaluate(dequeued_t)\n\n self.assertAllEqual([[b\"a\", b\"\", b\"\"], [b\"ab\", b\"\", b\"\"],\n [b\"abc\", b\"\", b\"\"], [b\"abc\", b\"d\", b\"\"],\n [b\"abc\", b\"d\", b\"e\"]], string_val)\n self.assertAllEqual([[[1, 0, 0]], [[2, 0, 0]], [[3, 0, 0]], [[1, 2, 0]],\n [[1, 2, 3]]], int_val)\n self.assertTrue(\n tensor_shape.TensorShape(string_val.shape).is_compatible_with(\n dequeued_t[0].get_shape()))\n self.assertTrue(\n tensor_shape.TensorShape(int_val.shape).is_compatible_with(dequeued_t[\n 1].get_shape()))\n\n string_val, int_val = self.evaluate(dequeued_single_t)\n self.assertAllEqual([b\"abc\", b\"d\", b\"e\", b\"f\"], string_val)\n self.assertAllEqual([[1, 2, 3, 4]], int_val)\n self.assertTrue(\n tensor_shape.TensorShape(string_val.shape).is_compatible_with(\n dequeued_single_t[0].get_shape()))\n self.assertTrue(\n tensor_shape.TensorShape(int_val.shape).is_compatible_with(\n dequeued_single_t[1].get_shape()))\n\n def testMultiDequeueUpToPartiallyKnownShapesAndVariableInputNoBlocking(self):\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(\n 10, (dtypes_lib.string, dtypes_lib.int32),\n shapes=((None,), (1, None)))\n str_elems = [[\"a\"], [\"ab\"], [\"abc\"], [\"abc\", \"d\"], [\"abc\", \"d\", \"e\"],\n [\"abc\", \"d\", \"e\", \"f\"]]\n\n int_elems = [[[1]], [[2]], [[3]], [[1, 2]], [[1, 2, 3]], [[1, 2, 3, 4]]]\n\n enqueue_ops = [q.enqueue((str_elems[i], int_elems[i])) for i in range(6)]\n\n dequeued_t = q.dequeue_up_to(5)\n dequeued_single_t = q.dequeue()\n\n for enqueue_op in enqueue_ops:\n enqueue_op.run()\n string_val, int_val = self.evaluate(dequeued_t)\n\n self.assertAllEqual([[b\"a\", b\"\", b\"\"], [b\"ab\", b\"\", b\"\"],\n [b\"abc\", b\"\", b\"\"], [b\"abc\", b\"d\", b\"\"],\n [b\"abc\", b\"d\", b\"e\"]], string_val)\n self.assertAllEqual([[[1, 0, 0]], [[2, 0, 0]], [[3, 0, 0]], [[1, 2, 0]],\n [[1, 2, 3]]], int_val)\n self.assertTrue(\n tensor_shape.TensorShape(string_val.shape).is_compatible_with(\n dequeued_t[0].get_shape()))\n self.assertTrue(\n tensor_shape.TensorShape(int_val.shape).is_compatible_with(dequeued_t[\n 1].get_shape()))\n\n string_val, int_val = self.evaluate(dequeued_single_t)\n self.assertAllEqual([b\"abc\", b\"d\", b\"e\", b\"f\"], string_val)\n self.assertAllEqual([[1, 2, 3, 4]], int_val)\n self.assertTrue(\n tensor_shape.TensorShape(string_val.shape).is_compatible_with(\n dequeued_single_t[0].get_shape()))\n self.assertTrue(\n tensor_shape.TensorShape(int_val.shape).is_compatible_with(\n dequeued_single_t[1].get_shape()))\n\n def testHighDimension(self):\n with self.cached_session():\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.int32, ((4, 4, 4, 4),))\n elems = np.array([[[[[x] * 4] * 4] * 4] * 4 for x in range(10)], np.int32)\n enqueue_op = q.enqueue_many((elems,))\n dequeued_t = q.dequeue_many(10)\n\n enqueue_op.run()\n self.assertAllEqual(dequeued_t, elems)\n\n def testPartiallyKnownHighDimension(self):\n with self.cached_session():\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.int32, (\n (4, None, 4, None),))\n elems = np.array([[[[[x] * 4] * 4] * 4] * 4 for x in range(10)], np.int32)\n enqueue_op = q.enqueue_many((elems,))\n dequeued_t = q.dequeue_many(10)\n\n enqueue_op.run()\n self.assertAllEqual(dequeued_t, elems)\n\n def testEnqueueWrongShape(self):\n q = data_flow_ops.PaddingFIFOQueue(10, (dtypes_lib.int32, dtypes_lib.int32),\n ((), (2,)))\n\n with self.assertRaises(ValueError):\n q.enqueue(([1, 2], [2, 2]))\n\n with self.assertRaises(ValueError):\n q.enqueue_many((7, [[1, 2], [3, 4], [5, 6]]))\n\n def testBatchSizeMismatch(self):\n q = data_flow_ops.PaddingFIFOQueue(10, (dtypes_lib.int32, dtypes_lib.int32,\n dtypes_lib.int32), ((), (), ()))\n\n with self.assertRaises(ValueError):\n q.enqueue_many(([1, 2, 3], [1, 2], [1, 2, 3]))\n\n with self.assertRaises(ValueError):\n q.enqueue_many(\n ([1, 2, 3], [1, 2], array_ops.placeholder(dtypes_lib.int32)))\n\n with self.assertRaises(ValueError):\n q.enqueue_many(\n (array_ops.placeholder(dtypes_lib.int32), [1, 2], [1, 2, 3]))\n\n def testEnqueueManyEmptyTypeConversion(self):\n q = data_flow_ops.PaddingFIFOQueue(10,\n (dtypes_lib.int32, dtypes_lib.float32), (\n (), ()))\n enq = q.enqueue_many(([], []))\n self.assertEqual(dtypes_lib.int32, enq.inputs[1].dtype)\n self.assertEqual(dtypes_lib.float32, enq.inputs[2].dtype)\n\n def testEnqueueWrongType(self):\n q = data_flow_ops.PaddingFIFOQueue(10,\n (dtypes_lib.int32, dtypes_lib.float32), (\n (), ()))\n\n with self.assertRaises(ValueError):\n q.enqueue((array_ops.placeholder(dtypes_lib.int32),\n array_ops.placeholder(dtypes_lib.int32)))\n\n with self.assertRaises(ValueError):\n q.enqueue_many((array_ops.placeholder(dtypes_lib.int32),\n array_ops.placeholder(dtypes_lib.int32)))\n\n def testEnqueueWrongPartiallyKnownShapeAtRuntime(self):\n with self.cached_session() as sess:\n # First dimension of second component is unknown, second\n # dimension must be 3.\n q = data_flow_ops.PaddingFIFOQueue(10,\n (dtypes_lib.int32, dtypes_lib.int32), (\n (2, 2), (None, 3)))\n elems_ok = np.array([1] * 4).reshape((2, 2)).astype(np.int32)\n elems_bad = array_ops.placeholder(dtypes_lib.int32)\n enqueue_op = q.enqueue((elems_ok, elems_bad))\n with self.assertRaisesRegex(errors_impl.InvalidArgumentError,\n r\"Expected \\[\\?,3\\], got \\[3,4\\]\"):\n sess.run([enqueue_op],\n feed_dict={elems_bad: np.array([1] * 12).reshape((3, 4))})\n\n def testEnqueueDequeueManyWrongPartiallyKnownShape(self):\n with self.cached_session() as sess:\n # First dimension of second component is unknown, second\n # dimension must be 3.\n q = data_flow_ops.PaddingFIFOQueue(10,\n (dtypes_lib.int32, dtypes_lib.int32), (\n (2, 2), (None, 3)))\n elems_ok = np.array([1] * 8).reshape((2, 2, 2)).astype(np.int32)\n elems_bad = array_ops.placeholder(dtypes_lib.int32)\n enqueue_op = q.enqueue_many((elems_ok, elems_bad))\n dequeued_t = q.dequeue_many(2)\n with self.assertRaisesRegex(\n errors_impl.InvalidArgumentError,\n \"Shape mismatch in tuple component 1. \"\n r\"Expected \\[2,\\?,3\\], got \\[2,3,4\\]\"):\n sess.run([enqueue_op],\n feed_dict={elems_bad: np.array([1] * 24).reshape((2, 3, 4))})\n self.evaluate(dequeued_t)\n\n def testParallelEnqueueMany(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(1000, dtypes_lib.float32, shapes=((),))\n elems = [10.0 * x for x in range(100)]\n enqueue_op = q.enqueue_many((elems,))\n dequeued_t = q.dequeue_many(1000)\n\n # Enqueue 100 items in parallel on 10 threads.\n def enqueue():\n self.evaluate(enqueue_op)\n\n threads = [self.checkedThread(target=enqueue) for _ in range(10)]\n for thread in threads:\n thread.start()\n for thread in threads:\n thread.join()\n\n self.assertItemsEqual(dequeued_t.eval(), elems * 10)\n\n def testParallelDequeueMany(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(1000, dtypes_lib.float32, shapes=((),))\n elems = [10.0 * x for x in range(1000)]\n enqueue_op = q.enqueue_many((elems,))\n dequeued_t = q.dequeue_many(100)\n\n enqueue_op.run()\n\n # Dequeue 100 items in parallel on 10 threads.\n dequeued_elems = []\n\n def dequeue():\n dequeued_elems.extend(self.evaluate(dequeued_t))\n\n threads = [self.checkedThread(target=dequeue) for _ in range(10)]\n for thread in threads:\n thread.start()\n for thread in threads:\n thread.join()\n self.assertItemsEqual(elems, dequeued_elems)\n\n def testParallelDequeueUpTo(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(1000, dtypes_lib.float32, shapes=((),))\n elems = [10.0 * x for x in range(1000)]\n enqueue_op = q.enqueue_many((elems,))\n close_op = q.close()\n dequeued_t = q.dequeue_up_to(101)\n\n enqueue_op.run()\n close_op.run()\n\n # Dequeue up to 101 items in parallel on 10 threads, from closed queue.\n dequeued_elems = []\n\n def dequeue():\n dequeued_elems.extend(self.evaluate(dequeued_t))\n\n threads = [self.checkedThread(target=dequeue) for _ in range(10)]\n for thread in threads:\n thread.start()\n for thread in threads:\n thread.join()\n self.assertItemsEqual(elems, dequeued_elems)\n\n def testParallelEnqueueAndDequeue(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(50, dtypes_lib.float32, shapes=((),))\n initial_elements = [10.0] * 49\n q.enqueue_many((initial_elements,)).run()\n\n enqueue_op = q.enqueue((20.0,))\n dequeued_t = q.dequeue()\n\n def enqueue():\n for _ in xrange(100):\n self.evaluate(enqueue_op)\n\n def dequeue():\n for _ in xrange(100):\n self.assertTrue(self.evaluate(dequeued_t) in (10.0, 20.0))\n\n enqueue_threads = [self.checkedThread(target=enqueue) for _ in range(10)]\n dequeue_threads = [self.checkedThread(target=dequeue) for _ in range(10)]\n for enqueue_thread in enqueue_threads:\n enqueue_thread.start()\n for dequeue_thread in dequeue_threads:\n dequeue_thread.start()\n for enqueue_thread in enqueue_threads:\n enqueue_thread.join()\n for dequeue_thread in dequeue_threads:\n dequeue_thread.join()\n\n # Dequeue the initial count of elements to clean up.\n cleanup_elems = q.dequeue_many(49).eval()\n for elem in cleanup_elems:\n self.assertTrue(elem in (10.0, 20.0))\n\n def testMixtureOfEnqueueAndEnqueueMany(self):\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.int32, shapes=((),))\n enqueue_placeholder = array_ops.placeholder(dtypes_lib.int32, shape=())\n enqueue_op = q.enqueue((enqueue_placeholder,))\n enqueuemany_placeholder = array_ops.placeholder(\n dtypes_lib.int32, shape=(None,))\n enqueuemany_op = q.enqueue_many((enqueuemany_placeholder,))\n\n dequeued_t = q.dequeue()\n close_op = q.close()\n\n def dequeue():\n for i in xrange(250):\n self.assertEqual(i, self.evaluate(dequeued_t))\n\n dequeue_thread = self.checkedThread(target=dequeue)\n dequeue_thread.start()\n\n elements_enqueued = 0\n while elements_enqueued < 250:\n # With equal probability, run Enqueue or enqueue_many.\n if random.random() > 0.5:\n enqueue_op.run({enqueue_placeholder: elements_enqueued})\n elements_enqueued += 1\n else:\n count = random.randint(0, min(20, 250 - elements_enqueued))\n range_to_enqueue = np.arange(\n elements_enqueued, elements_enqueued + count, dtype=np.int32)\n enqueuemany_op.run({enqueuemany_placeholder: range_to_enqueue})\n elements_enqueued += count\n\n close_op.run()\n dequeue_thread.join()\n self.assertEqual(0, q.size().eval())\n\n def testMixtureOfDequeueAndDequeueMany(self):\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.int32, shapes=((),))\n enqueue_op = q.enqueue_many((np.arange(250, dtype=np.int32),))\n dequeued_t = q.dequeue()\n count_placeholder = array_ops.placeholder(dtypes_lib.int32, shape=())\n dequeuemany_t = q.dequeue_many(count_placeholder)\n\n def enqueue():\n self.evaluate(enqueue_op)\n\n enqueue_thread = self.checkedThread(target=enqueue)\n enqueue_thread.start()\n\n elements_dequeued = 0\n while elements_dequeued < 250:\n # With equal probability, run Dequeue or dequeue_many.\n if random.random() > 0.5:\n self.assertEqual(elements_dequeued, self.evaluate(dequeued_t))\n elements_dequeued += 1\n else:\n count = random.randint(0, min(20, 250 - elements_dequeued))\n expected_range = np.arange(\n elements_dequeued, elements_dequeued + count, dtype=np.int32)\n self.assertAllEqual(expected_range,\n dequeuemany_t.eval({\n count_placeholder: count\n }))\n elements_dequeued += count\n\n q.close().run()\n enqueue_thread.join()\n self.assertEqual(0, q.size().eval())\n\n def testBlockingDequeueMany(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n elems = [10.0, 20.0, 30.0, 40.0]\n enqueue_op = q.enqueue_many((elems,))\n dequeued_t = q.dequeue_many(4)\n\n dequeued_elems = []\n\n def enqueue():\n # The enqueue_op should run after the dequeue op has blocked.\n # TODO(mrry): Figure out how to do this without sleeping.\n time.sleep(0.1)\n self.evaluate(enqueue_op)\n\n def dequeue():\n dequeued_elems.extend(self.evaluate(dequeued_t).tolist())\n\n enqueue_thread = self.checkedThread(target=enqueue)\n dequeue_thread = self.checkedThread(target=dequeue)\n enqueue_thread.start()\n dequeue_thread.start()\n enqueue_thread.join()\n dequeue_thread.join()\n\n self.assertAllEqual(elems, dequeued_elems)\n\n def testBlockingDequeueUpTo(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n elems = [10.0, 20.0, 30.0, 40.0]\n enqueue_op = q.enqueue_many((elems,))\n dequeued_t = q.dequeue_up_to(4)\n\n dequeued_elems = []\n\n def enqueue():\n # The enqueue_op should run after the dequeue op has blocked.\n # TODO(mrry): Figure out how to do this without sleeping.\n time.sleep(0.1)\n self.evaluate(enqueue_op)\n\n def dequeue():\n dequeued_elems.extend(self.evaluate(dequeued_t).tolist())\n\n enqueue_thread = self.checkedThread(target=enqueue)\n dequeue_thread = self.checkedThread(target=dequeue)\n enqueue_thread.start()\n dequeue_thread.start()\n enqueue_thread.join()\n dequeue_thread.join()\n\n self.assertAllEqual(elems, dequeued_elems)\n\n def testDequeueManyWithTensorParameter(self):\n with self.cached_session():\n # Define a first queue that contains integer counts.\n dequeue_counts = [random.randint(1, 10) for _ in range(100)]\n count_q = data_flow_ops.PaddingFIFOQueue(100, dtypes_lib.int32, ((),))\n enqueue_counts_op = count_q.enqueue_many((dequeue_counts,))\n total_count = sum(dequeue_counts)\n\n # Define a second queue that contains total_count elements.\n elems = [random.randint(0, 100) for _ in range(total_count)]\n q = data_flow_ops.PaddingFIFOQueue(total_count, dtypes_lib.int32, ((),))\n enqueue_elems_op = q.enqueue_many((elems,))\n\n # Define a subgraph that first dequeues a count, then DequeuesMany\n # that number of elements.\n dequeued_t = q.dequeue_many(count_q.dequeue())\n\n enqueue_counts_op.run()\n enqueue_elems_op.run()\n\n dequeued_elems = []\n for _ in dequeue_counts:\n dequeued_elems.extend(dequeued_t.eval())\n self.assertEqual(elems, dequeued_elems)\n\n def testDequeueFromClosedQueue(self):\n with self.cached_session():\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n elems = [10.0, 20.0, 30.0, 40.0]\n enqueue_op = q.enqueue_many((elems,))\n close_op = q.close()\n dequeued_t = q.dequeue()\n\n enqueue_op.run()\n close_op.run()\n for elem in elems:\n self.assertEqual([elem], self.evaluate(dequeued_t))\n\n # Expect the operation to fail due to the queue being closed.\n with self.assertRaisesRegex(errors_impl.OutOfRangeError,\n \"is closed and has insufficient\"):\n self.evaluate(dequeued_t)\n\n def testBlockingDequeueFromClosedQueue(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n elems = [10.0, 20.0, 30.0, 40.0]\n enqueue_op = q.enqueue_many((elems,))\n close_op = q.close()\n dequeued_t = q.dequeue()\n\n enqueue_op.run()\n\n def dequeue():\n for elem in elems:\n self.assertEqual([elem], self.evaluate(dequeued_t))\n # Expect the operation to fail due to the queue being closed.\n with self.assertRaisesRegex(errors_impl.OutOfRangeError,\n \"is closed and has insufficient\"):\n self.evaluate(dequeued_t)\n\n dequeue_thread = self.checkedThread(target=dequeue)\n dequeue_thread.start()\n # The close_op should run after the dequeue_thread has blocked.\n # TODO(mrry): Figure out how to do this without sleeping.\n time.sleep(0.1)\n close_op.run()\n dequeue_thread.join()\n\n def testDequeueUpToFromClosedQueueReturnsRemainder(self):\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n elems = [10.0, 20.0, 30.0, 40.0]\n enqueue_op = q.enqueue_many((elems,))\n close_op = q.close()\n dequeued_t = q.dequeue_up_to(3)\n\n enqueue_op.run()\n\n def dequeue():\n self.assertAllEqual(elems[:3], self.evaluate(dequeued_t))\n self.assertAllEqual(elems[3:], self.evaluate(dequeued_t))\n\n dequeue_thread = self.checkedThread(target=dequeue)\n dequeue_thread.start()\n # The close_op should run after the dequeue_thread has blocked.\n # TODO(mrry): Figure out how to do this without sleeping.\n time.sleep(0.1)\n close_op.run()\n dequeue_thread.join()\n\n def testBlockingDequeueFromClosedEmptyQueue(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n close_op = q.close()\n dequeued_t = q.dequeue()\n\n def dequeue():\n # Expect the operation to fail due to the queue being closed.\n with self.assertRaisesRegex(errors_impl.OutOfRangeError,\n \"is closed and has insufficient\"):\n self.evaluate(dequeued_t)\n\n dequeue_thread = self.checkedThread(target=dequeue)\n dequeue_thread.start()\n # The close_op should run after the dequeue_thread has blocked.\n # TODO(mrry): Figure out how to do this without sleeping.\n time.sleep(0.1)\n close_op.run()\n dequeue_thread.join()\n\n def testBlockingDequeueManyFromClosedQueue(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n elems = [10.0, 20.0, 30.0, 40.0]\n enqueue_op = q.enqueue_many((elems,))\n close_op = q.close()\n dequeued_t = q.dequeue_many(4)\n\n enqueue_op.run()\n\n def dequeue():\n self.assertAllEqual(elems, self.evaluate(dequeued_t))\n # Expect the operation to fail due to the queue being closed.\n with self.assertRaisesRegex(errors_impl.OutOfRangeError,\n \"is closed and has insufficient\"):\n self.evaluate(dequeued_t)\n\n dequeue_thread = self.checkedThread(target=dequeue)\n dequeue_thread.start()\n # The close_op should run after the dequeue_thread has blocked.\n # TODO(mrry): Figure out how to do this without sleeping.\n time.sleep(0.1)\n close_op.run()\n dequeue_thread.join()\n\n def testBlockingDequeueManyButNotAllFromClosedQueue(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n elems = [10.0, 20.0, 30.0, 40.0]\n enqueue_op = q.enqueue_many((elems,))\n close_op = q.close()\n dequeued_t = q.dequeue_many(3)\n\n enqueue_op.run()\n\n def dequeue():\n self.assertAllEqual(elems[:3], self.evaluate(dequeued_t))\n # Expect the operation to fail due to the queue being closed.\n with self.assertRaisesRegex(errors_impl.OutOfRangeError,\n \"is closed and has insufficient\"):\n self.evaluate(dequeued_t)\n\n dequeue_thread = self.checkedThread(target=dequeue)\n dequeue_thread.start()\n # The close_op should run after the dequeue_thread has blocked.\n # TODO(mrry): Figure out how to do this without sleeping.\n time.sleep(0.1)\n close_op.run()\n dequeue_thread.join()\n\n def testEnqueueManyLargerThanCapacityWithConcurrentDequeueMany(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(4, dtypes_lib.float32, ((),))\n elems = [10.0, 20.0, 30.0, 40.0]\n enqueue_op = q.enqueue_many((elems,))\n close_op = q.close()\n dequeued_t = q.dequeue_many(3)\n cleanup_dequeue_t = q.dequeue()\n\n def enqueue():\n self.evaluate(enqueue_op)\n\n def dequeue():\n self.assertAllEqual(elems[0:3], self.evaluate(dequeued_t))\n with self.assertRaises(errors_impl.OutOfRangeError):\n self.evaluate(dequeued_t)\n self.assertEqual(elems[3], self.evaluate(cleanup_dequeue_t))\n\n def close():\n self.evaluate(close_op)\n\n enqueue_thread = self.checkedThread(target=enqueue)\n enqueue_thread.start()\n\n dequeue_thread = self.checkedThread(target=dequeue)\n dequeue_thread.start()\n # The close_op should run after the dequeue_thread has blocked.\n # TODO(mrry): Figure out how to do this without sleeping.\n time.sleep(0.1)\n\n close_thread = self.checkedThread(target=close)\n close_thread.start()\n\n enqueue_thread.join()\n dequeue_thread.join()\n close_thread.join()\n\n def testClosedBlockingDequeueManyRestoresPartialBatch(self):\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(4, (dtypes_lib.float32,\n dtypes_lib.float32), ((), ()))\n elems_a = [1.0, 2.0, 3.0]\n elems_b = [10.0, 20.0, 30.0]\n enqueue_op = q.enqueue_many((elems_a, elems_b))\n dequeued_a_t, dequeued_b_t = q.dequeue_many(4)\n cleanup_dequeue_a_t, cleanup_dequeue_b_t = q.dequeue()\n close_op = q.close()\n\n enqueue_op.run()\n\n def dequeue():\n with self.assertRaises(errors_impl.OutOfRangeError):\n self.evaluate([dequeued_a_t, dequeued_b_t])\n\n dequeue_thread = self.checkedThread(target=dequeue)\n dequeue_thread.start()\n # The close_op should run after the dequeue_thread has blocked.\n # TODO(mrry): Figure out how to do this without sleeping.\n time.sleep(0.1)\n\n close_op.run()\n dequeue_thread.join()\n # Test that the elements in the partially-dequeued batch are\n # restored in the correct order.\n for elem_a, elem_b in zip(elems_a, elems_b):\n val_a, val_b = self.evaluate([cleanup_dequeue_a_t, cleanup_dequeue_b_t])\n self.assertEqual(elem_a, val_a)\n self.assertEqual(elem_b, val_b)\n self.assertEqual(0, q.size().eval())\n\n def testBlockingDequeueManyFromClosedEmptyQueue(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n close_op = q.close()\n dequeued_t = q.dequeue_many(4)\n\n def dequeue():\n # Expect the operation to fail due to the queue being closed.\n with self.assertRaisesRegex(errors_impl.OutOfRangeError,\n \"is closed and has insufficient\"):\n self.evaluate(dequeued_t)\n\n dequeue_thread = self.checkedThread(target=dequeue)\n dequeue_thread.start()\n # The close_op should run after the dequeue_thread has blocked.\n # TODO(mrry): Figure out how to do this without sleeping.\n time.sleep(0.1)\n close_op.run()\n dequeue_thread.join()\n\n def testBlockingDequeueUpToFromClosedEmptyQueue(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n close_op = q.close()\n dequeued_t = q.dequeue_up_to(4)\n\n def dequeue():\n # Expect the operation to fail due to the queue being closed.\n with self.assertRaisesRegex(errors_impl.OutOfRangeError,\n \"is closed and has insufficient\"):\n self.evaluate(dequeued_t)\n\n dequeue_thread = self.checkedThread(target=dequeue)\n dequeue_thread.start()\n # The close_op should run after the dequeue_thread has blocked.\n # TODO(mrry): Figure out how to do this without sleeping.\n time.sleep(0.1)\n close_op.run()\n dequeue_thread.join()\n\n def testEnqueueToClosedQueue(self):\n with self.cached_session():\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n enqueue_op = q.enqueue((10.0,))\n close_op = q.close()\n\n enqueue_op.run()\n close_op.run()\n\n # Expect the operation to fail due to the queue being closed.\n with self.assertRaisesRegex(errors_impl.CancelledError, \"is closed\"):\n enqueue_op.run()\n\n def testEnqueueManyToClosedQueue(self):\n with self.cached_session():\n q = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n elems = [10.0, 20.0, 30.0, 40.0]\n enqueue_op = q.enqueue_many((elems,))\n close_op = q.close()\n\n enqueue_op.run()\n close_op.run()\n\n # Expect the operation to fail due to the queue being closed.\n with self.assertRaisesRegex(errors_impl.CancelledError, \"is closed\"):\n enqueue_op.run()\n\n def testBlockingEnqueueToFullQueue(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(4, dtypes_lib.float32, ((),))\n elems = [10.0, 20.0, 30.0, 40.0]\n enqueue_op = q.enqueue_many((elems,))\n blocking_enqueue_op = q.enqueue((50.0,))\n dequeued_t = q.dequeue()\n\n enqueue_op.run()\n\n def blocking_enqueue():\n self.evaluate(blocking_enqueue_op)\n\n thread = self.checkedThread(target=blocking_enqueue)\n thread.start()\n # The dequeue ops should run after the blocking_enqueue_op has blocked.\n # TODO(mrry): Figure out how to do this without sleeping.\n time.sleep(0.1)\n for elem in elems:\n self.assertEqual([elem], self.evaluate(dequeued_t))\n self.assertEqual([50.0], self.evaluate(dequeued_t))\n thread.join()\n\n def testBlockingEnqueueManyToFullQueue(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(4, dtypes_lib.float32, ((),))\n elems = [10.0, 20.0, 30.0, 40.0]\n enqueue_op = q.enqueue_many((elems,))\n blocking_enqueue_op = q.enqueue_many(([50.0, 60.0],))\n dequeued_t = q.dequeue()\n\n enqueue_op.run()\n\n def blocking_enqueue():\n self.evaluate(blocking_enqueue_op)\n\n thread = self.checkedThread(target=blocking_enqueue)\n thread.start()\n # The dequeue ops should run after the blocking_enqueue_op has blocked.\n # TODO(mrry): Figure out how to do this without sleeping.\n time.sleep(0.1)\n for elem in elems:\n self.assertEqual([elem], self.evaluate(dequeued_t))\n time.sleep(0.01)\n self.assertEqual([50.0], self.evaluate(dequeued_t))\n self.assertEqual([60.0], self.evaluate(dequeued_t))\n\n # Make sure the thread finishes before exiting.\n thread.join()\n\n def testBlockingEnqueueBeforeClose(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(4, dtypes_lib.float32, ((),))\n elems = [10.0, 20.0, 30.0, 40.0]\n enqueue_op = q.enqueue_many((elems,))\n blocking_enqueue_op = q.enqueue((50.0,))\n close_op = q.close()\n dequeued_t = q.dequeue()\n\n enqueue_op.run()\n\n def blocking_enqueue():\n # Expect the operation to succeed once the dequeue op runs.\n self.evaluate(blocking_enqueue_op)\n\n enqueue_thread = self.checkedThread(target=blocking_enqueue)\n enqueue_thread.start()\n\n # The close_op should run after the blocking_enqueue_op has blocked.\n # TODO(mrry): Figure out how to do this without sleeping.\n time.sleep(0.1)\n\n def close():\n self.evaluate(close_op)\n\n close_thread = self.checkedThread(target=close)\n close_thread.start()\n\n # The dequeue will unblock both threads.\n self.assertEqual(10.0, self.evaluate(dequeued_t))\n enqueue_thread.join()\n close_thread.join()\n\n for elem in [20.0, 30.0, 40.0, 50.0]:\n self.assertEqual(elem, self.evaluate(dequeued_t))\n self.assertEqual(0, q.size().eval())\n\n def testBlockingEnqueueManyBeforeClose(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(4, dtypes_lib.float32, ((),))\n elems = [10.0, 20.0, 30.0]\n enqueue_op = q.enqueue_many((elems,))\n blocking_enqueue_op = q.enqueue_many(([50.0, 60.0],))\n close_op = q.close()\n dequeued_t = q.dequeue()\n enqueue_op.run()\n\n def blocking_enqueue():\n self.evaluate(blocking_enqueue_op)\n\n enqueue_thread = self.checkedThread(target=blocking_enqueue)\n enqueue_thread.start()\n\n # The close_op should run after the blocking_enqueue_op has blocked.\n # TODO(mrry): Figure out how to do this without sleeping.\n time.sleep(0.1)\n\n def close():\n self.evaluate(close_op)\n\n close_thread = self.checkedThread(target=close)\n close_thread.start()\n\n # The dequeue will unblock both threads.\n self.assertEqual(10.0, self.evaluate(dequeued_t))\n enqueue_thread.join()\n close_thread.join()\n for elem in [20.0, 30.0, 50.0, 60.0]:\n self.assertEqual(elem, self.evaluate(dequeued_t))\n\n def testDoesNotLoseValue(self):\n with self.cached_session():\n q = data_flow_ops.PaddingFIFOQueue(1, dtypes_lib.float32, ((),))\n enqueue_op = q.enqueue((10.0,))\n size_t = q.size()\n\n enqueue_op.run()\n for _ in range(500):\n self.assertEqual(size_t.eval(), [1])\n\n def testSharedQueueSameSession(self):\n with self.cached_session():\n q1 = data_flow_ops.PaddingFIFOQueue(\n 1, dtypes_lib.float32, ((),), shared_name=\"shared_queue\")\n q1.enqueue((10.0,)).run()\n\n q2 = data_flow_ops.PaddingFIFOQueue(\n 1, dtypes_lib.float32, ((),), shared_name=\"shared_queue\")\n\n q1_size_t = q1.size()\n q2_size_t = q2.size()\n\n self.assertEqual(q1_size_t.eval(), [1])\n self.assertEqual(q2_size_t.eval(), [1])\n\n self.assertEqual(q2.dequeue().eval(), [10.0])\n\n self.assertEqual(q1_size_t.eval(), [0])\n self.assertEqual(q2_size_t.eval(), [0])\n\n q2.enqueue((20.0,)).run()\n\n self.assertEqual(q1_size_t.eval(), [1])\n self.assertEqual(q2_size_t.eval(), [1])\n\n self.assertEqual(q1.dequeue().eval(), [20.0])\n\n self.assertEqual(q1_size_t.eval(), [0])\n self.assertEqual(q2_size_t.eval(), [0])\n\n def testIncompatibleSharedQueueErrors(self):\n with self.cached_session():\n q_a_1 = data_flow_ops.PaddingFIFOQueue(\n 10, dtypes_lib.float32, ((),), shared_name=\"q_a\")\n q_a_2 = data_flow_ops.PaddingFIFOQueue(\n 15, dtypes_lib.float32, ((),), shared_name=\"q_a\")\n q_a_1.queue_ref.op.run()\n with self.assertRaisesOpError(\"capacity\"):\n q_a_2.queue_ref.op.run()\n\n q_b_1 = data_flow_ops.PaddingFIFOQueue(\n 10, dtypes_lib.float32, ((),), shared_name=\"q_b\")\n q_b_2 = data_flow_ops.PaddingFIFOQueue(\n 10, dtypes_lib.int32, ((),), shared_name=\"q_b\")\n q_b_1.queue_ref.op.run()\n with self.assertRaisesOpError(\"component types\"):\n q_b_2.queue_ref.op.run()\n\n q_c_1 = data_flow_ops.PaddingFIFOQueue(\n 10, dtypes_lib.float32, ((),), shared_name=\"q_c\")\n q_c_2 = data_flow_ops.PaddingFIFOQueue(\n 10, dtypes_lib.float32, shapes=[(1, 1, 2, 3)], shared_name=\"q_c\")\n q_c_1.queue_ref.op.run()\n with self.assertRaisesOpError(\"component shapes\"):\n q_c_2.queue_ref.op.run()\n\n q_d_1 = data_flow_ops.PaddingFIFOQueue(\n 10, dtypes_lib.float32, shapes=[(1, 1, 2, 3)], shared_name=\"q_d\")\n q_d_2 = data_flow_ops.PaddingFIFOQueue(\n 10, dtypes_lib.float32, ((),), shared_name=\"q_d\")\n q_d_1.queue_ref.op.run()\n with self.assertRaisesOpError(\"component shapes\"):\n q_d_2.queue_ref.op.run()\n\n q_e_1 = data_flow_ops.PaddingFIFOQueue(\n 10, dtypes_lib.float32, shapes=[(1, 1, 2, 3)], shared_name=\"q_e\")\n q_e_2 = data_flow_ops.PaddingFIFOQueue(\n 10, dtypes_lib.float32, shapes=[(1, 1, 2, 4)], shared_name=\"q_e\")\n q_e_1.queue_ref.op.run()\n with self.assertRaisesOpError(\"component shapes\"):\n q_e_2.queue_ref.op.run()\n\n q_f_1 = data_flow_ops.PaddingFIFOQueue(\n 10, dtypes_lib.float32, ((),), shared_name=\"q_f\")\n q_f_2 = data_flow_ops.PaddingFIFOQueue(\n 10, (dtypes_lib.float32, dtypes_lib.int32), ((), ()),\n shared_name=\"q_f\")\n q_f_1.queue_ref.op.run()\n with self.assertRaisesOpError(\"component types\"):\n q_f_2.queue_ref.op.run()\n\n def testSelectQueue(self):\n with self.cached_session():\n num_queues = 10\n qlist = []\n for _ in xrange(num_queues):\n qlist.append(\n data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),)))\n # Enqueue/Dequeue into a dynamically selected queue\n for _ in xrange(20):\n index = np.random.randint(num_queues)\n q = data_flow_ops.PaddingFIFOQueue.from_list(index, qlist)\n q.enqueue((10.,)).run()\n self.assertEqual(q.dequeue().eval(), 10.0)\n\n def testSelectQueueOutOfRange(self):\n with self.cached_session():\n q1 = data_flow_ops.PaddingFIFOQueue(10, dtypes_lib.float32, ((),))\n q2 = data_flow_ops.PaddingFIFOQueue(15, dtypes_lib.float32, ((),))\n enq_q = data_flow_ops.PaddingFIFOQueue.from_list(3, [q1, q2])\n with self.assertRaisesOpError(\"is not in\"):\n enq_q.dequeue().eval()\n\n def _blockingDequeue(self, sess, dequeue_op):\n with self.assertRaisesOpError(\"was cancelled\"):\n self.evaluate(dequeue_op)\n\n def _blockingDequeueMany(self, sess, dequeue_many_op):\n with self.assertRaisesOpError(\"was cancelled\"):\n self.evaluate(dequeue_many_op)\n\n def _blockingEnqueue(self, sess, enqueue_op):\n with self.assertRaisesOpError(\"was cancelled\"):\n self.evaluate(enqueue_op)\n\n def _blockingEnqueueMany(self, sess, enqueue_many_op):\n with self.assertRaisesOpError(\"was cancelled\"):\n self.evaluate(enqueue_many_op)\n\n @test_util.run_deprecated_v1\n def testResetOfBlockingOperation(self):\n # We need each thread to keep its own device stack or the device scopes\n # won't be properly nested.\n ops.get_default_graph().switch_to_thread_local()\n with self.cached_session() as sess:\n q_empty = data_flow_ops.PaddingFIFOQueue(5, dtypes_lib.float32, ((),))\n dequeue_op = q_empty.dequeue()\n dequeue_many_op = q_empty.dequeue_many(1)\n\n q_full = data_flow_ops.PaddingFIFOQueue(5, dtypes_lib.float32, ((),))\n sess.run(q_full.enqueue_many(([1.0, 2.0, 3.0, 4.0, 5.0],)))\n enqueue_op = q_full.enqueue((6.0,))\n enqueue_many_op = q_full.enqueue_many(([6.0],))\n\n threads = [\n self.checkedThread(\n self._blockingDequeue, args=(sess, dequeue_op)),\n self.checkedThread(\n self._blockingDequeueMany, args=(sess, dequeue_many_op)),\n self.checkedThread(\n self._blockingEnqueue, args=(sess, enqueue_op)),\n self.checkedThread(\n self._blockingEnqueueMany, args=(sess, enqueue_many_op))\n ]\n for t in threads:\n t.start()\n time.sleep(0.1)\n sess.close() # Will cancel the blocked operations.\n for t in threads:\n t.join()\n\n def testBigEnqueueMany(self):\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(5, dtypes_lib.int32, ((),))\n elem = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n enq = q.enqueue_many((elem,))\n deq = q.dequeue()\n size_op = q.size()\n\n enq_done = []\n\n def blocking_enqueue():\n enq_done.append(False)\n # This will fill the queue and then block until enough dequeues happen.\n self.evaluate(enq)\n enq_done.append(True)\n\n thread = self.checkedThread(target=blocking_enqueue)\n thread.start()\n\n # The enqueue should start and then block.\n results = []\n results.append(deq.eval()) # Will only complete after the enqueue starts.\n self.assertEqual(len(enq_done), 1)\n self.assertEqual(self.evaluate(size_op), 5)\n\n for _ in range(3):\n results.append(deq.eval())\n\n time.sleep(0.1)\n self.assertEqual(len(enq_done), 1)\n self.assertEqual(self.evaluate(size_op), 5)\n\n # This dequeue will unblock the thread.\n results.append(deq.eval())\n time.sleep(0.1)\n self.assertEqual(len(enq_done), 2)\n thread.join()\n\n for i in range(5):\n self.assertEqual(size_op.eval(), 5 - i)\n results.append(deq.eval())\n self.assertEqual(size_op.eval(), 5 - i - 1)\n\n self.assertAllEqual(elem, results)\n\n def testBigDequeueMany(self):\n with self.cached_session() as sess:\n q = data_flow_ops.PaddingFIFOQueue(2, dtypes_lib.int32, ((),))\n elem = np.arange(4, dtype=np.int32)\n enq_list = [q.enqueue((e,)) for e in elem]\n deq = q.dequeue_many(4)\n\n results = []\n\n def blocking_dequeue():\n # Will only complete after 4 enqueues complete.\n results.extend(self.evaluate(deq))\n\n thread = self.checkedThread(target=blocking_dequeue)\n thread.start()\n # The dequeue should start and then block.\n for enq in enq_list:\n # TODO(mrry): Figure out how to do this without sleeping.\n time.sleep(0.1)\n self.assertEqual(len(results), 0)\n self.evaluate(enq)\n\n # Enough enqueued to unblock the dequeue\n thread.join()\n self.assertAllEqual(elem, results)\n\n def testDtypes(self):\n with self.cached_session() as sess:\n dtypes = [\n dtypes_lib.float32, dtypes_lib.float64, dtypes_lib.int32,\n dtypes_lib.uint8, dtypes_lib.int16, dtypes_lib.int8, dtypes_lib.int64,\n dtypes_lib.bool, dtypes_lib.complex64, dtypes_lib.complex128\n ]\n shape = (32, 4, 128)\n q = data_flow_ops.PaddingFIFOQueue(32, dtypes, [shape[1:]] * len(dtypes))\n\n input_tuple = []\n for dtype in dtypes:\n np_dtype = dtype.as_numpy_dtype\n np_array = np.random.randint(-10, 10, shape)\n if dtype == dtypes_lib.bool:\n np_array = np_array > 0\n elif dtype in (dtypes_lib.complex64, dtypes_lib.complex128):\n np_array = np.sqrt(np_array.astype(np_dtype))\n else:\n np_array = np_array.astype(np_dtype)\n input_tuple.append(np_array)\n\n q.enqueue_many(input_tuple).run()\n\n output_tuple_t = q.dequeue_many(32)\n output_tuple = self.evaluate(output_tuple_t)\n\n for (input_elem, output_elem) in zip(input_tuple, output_tuple):\n self.assertAllEqual(input_elem, output_elem)\n\n def testUnknownRank(self):\n with self.assertRaisesRegex(ValueError, \"must have a defined rank\"):\n data_flow_ops.PaddingFIFOQueue(32, [dtypes_lib.float32],\n [tensor_shape.TensorShape(None)])\n\n\nclass QueueFromListTest(test.TestCase):\n\n def testQueueFromListShapes(self):\n which = constant_op.constant(1)\n\n def _cmp(expected, *shapes):\n qs = [\n data_flow_ops.PaddingFIFOQueue(10, [dtypes_lib.float32],\n [tensor_shape.TensorShape(s)])\n for s in shapes\n ]\n s_expected = tensor_shape.TensorShape(expected)\n s = data_flow_ops.QueueBase.from_list(which, qs).shapes[0]\n if s_expected.ndims is None:\n self.assertEqual(s_expected.ndims, s.ndims)\n else:\n self.assertEqual(s_expected.as_list(), s.as_list())\n\n _cmp(None, [1, None], [None])\n _cmp([None], [1], [2])\n _cmp([1, None], [1, 1], [1, 2])\n _cmp([1, None], [1, 1], [1, None])\n _cmp([None, None], [None, 1], [1, None])\n _cmp([1], [1], [1], [1])\n _cmp([None], [1], [None], [1])\n _cmp(None, [1, None], [1], [1])\n\n def testQueueFromListShapesMultipleComponents(self):\n q_u_u = data_flow_ops.PaddingFIFOQueue(\n 10, [dtypes_lib.float32, dtypes_lib.int32],\n [tensor_shape.TensorShape([None]), tensor_shape.TensorShape([None])])\n q_u_f = data_flow_ops.PaddingFIFOQueue(\n 10, [dtypes_lib.float32, dtypes_lib.int32],\n [tensor_shape.TensorShape([None]), tensor_shape.TensorShape([1, 2])])\n q_f_f = data_flow_ops.PaddingFIFOQueue(\n 10, [dtypes_lib.float32, dtypes_lib.int32],\n [tensor_shape.TensorShape([3, 4]), tensor_shape.TensorShape([1, 2])])\n which = constant_op.constant(1)\n\n s_cmp_1 = data_flow_ops.QueueBase.from_list(which,\n [q_u_u, q_u_u, q_u_u]).shapes\n self.assertEqual([1, 1], [x.ndims for x in s_cmp_1])\n self.assertEqual([None, None], [x.as_list()[0] for x in s_cmp_1])\n\n s_cmp_2 = data_flow_ops.QueueBase.from_list(which,\n [q_u_u, q_u_u, q_u_f]).shapes\n self.assertEqual([1, None], [x.ndims for x in s_cmp_2])\n self.assertEqual([None], s_cmp_2[0].as_list())\n\n s_cmp_3 = data_flow_ops.QueueBase.from_list(which, [q_f_f, q_f_f]).shapes\n self.assertEqual([2, 2], [x.ndims for x in s_cmp_3])\n self.assertEqual([[3, 4], [1, 2]], [x.as_list() for x in s_cmp_3])\n\n\nif __name__ == \"__main__\":\n test.main()\n",
"# 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\"\"\"Tests for the `MapVectorization` optimization.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\nimport time\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.core.example import example_pb2\nfrom tensorflow.core.example import feature_pb2\nfrom tensorflow.python.data.experimental.ops import batching\nfrom tensorflow.python.data.experimental.ops import testing\nfrom tensorflow.python.data.kernel_tests import test_base\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import combinations\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import bitwise_ops\nfrom tensorflow.python.ops import check_ops\nfrom tensorflow.python.ops import clip_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn\nfrom tensorflow.python.ops import parsing_ops\nfrom tensorflow.python.ops import script_ops\nfrom tensorflow.python.ops import special_math_ops\nfrom tensorflow.python.platform import test\n\n\ndef _generate_test_combinations(cases):\n\n def reduce_fn(x, y):\n name, fn = y\n return x + combinations.combine(map_fn=combinations.NamedObject(name, fn))\n\n return functools.reduce(reduce_fn, cases, [])\n\n\ndef _unary_bitwise_test_combinations():\n cases = [(\"Invert\", bitwise_ops.invert)]\n return _generate_test_combinations(cases)\n\n\ndef _unary_logical_test_combinations():\n cases = [(\"LogicalNot\", math_ops.logical_not)]\n return _generate_test_combinations(cases)\n\n\ndef _unary_complex_test_combinations():\n cases = [\n (\"Angle\", math_ops.angle),\n (\"ComplexAbs\", math_ops.abs),\n (\"Conj\", math_ops.conj),\n (\"Imag\", math_ops.imag),\n (\"Real\", math_ops.real),\n ]\n return _generate_test_combinations(cases)\n\n\ndef _unary_real_test_combinations():\n # acosh requires values x >= 1\n def safe_acosh(x):\n return math_ops.acosh(1 + math_ops.square(x))\n\n cases = [\n (\"Abs\", math_ops.abs),\n (\"Acos\", math_ops.acos),\n (\"Acosh\", safe_acosh),\n (\"Asin\", math_ops.asin),\n (\"Asinh\", math_ops.asinh),\n (\"Atan\", math_ops.atan),\n (\"Atanh\", math_ops.atanh),\n # TODO(b/157272291): Add testing for more special functions.\n (\"BesselI0e\", special_math_ops.bessel_i0e),\n (\"BesselI1e\", special_math_ops.bessel_i1e),\n (\"Ceil\", math_ops.ceil),\n (\"Cos\", math_ops.cos),\n (\"Cosh\", math_ops.cosh),\n (\"Digamma\", math_ops.digamma),\n (\"Elu\", nn.elu),\n (\"Erf\", math_ops.erf),\n (\"Erfc\", math_ops.erfc),\n (\"Exp\", math_ops.exp),\n (\"Expm1\", math_ops.expm1),\n (\"Floor\", math_ops.floor),\n (\"Inv\", math_ops.inv),\n (\"IsFinite\", math_ops.is_finite),\n (\"IsInf\", math_ops.is_inf),\n (\"Lgamma\", math_ops.lgamma),\n (\"Log\", math_ops.log),\n (\"Log1p\", math_ops.log1p),\n (\"Neg\", math_ops.negative),\n (\"Reciprocal\", math_ops.reciprocal),\n (\"Relu\", nn.relu),\n (\"Relu6\", nn.relu6),\n (\"Rint\", math_ops.rint),\n (\"Round\", math_ops.round),\n (\"Rsqrt\", math_ops.rsqrt),\n (\"Selu\", nn.selu),\n (\"Sigmoid\", math_ops.sigmoid),\n (\"Sign\", math_ops.sign),\n (\"Sin\", math_ops.sin),\n (\"Sinh\", math_ops.sinh),\n (\"Softplus\", nn.softplus),\n (\"Softsign\", nn.softsign),\n (\"Sqrt\", math_ops.sqrt),\n (\"Square\", math_ops.square),\n (\"Tan\", math_ops.tan),\n (\"Tanh\", math_ops.tanh),\n ]\n return _generate_test_combinations(cases)\n\n\ndef _binary_bitwise_test_combinations():\n cases = [(\"BitwiseAnd\", bitwise_ops.bitwise_and),\n (\"BitwiseOr\", bitwise_ops.bitwise_or),\n (\"BitwiseXor\", bitwise_ops.bitwise_xor),\n (\"LeftShift\", bitwise_ops.left_shift),\n (\"RightShift\", bitwise_ops.right_shift)]\n return _generate_test_combinations(cases)\n\n\ndef _binary_logical_test_combinations():\n cases = [(\"LogicalAnd\", math_ops.logical_and),\n (\"LogicalOr\", math_ops.logical_or)]\n return _generate_test_combinations(cases)\n\n\ndef _binary_real_test_combinations():\n\n def safe_polygamma(x, y):\n return math_ops.polygamma(\n math_ops.round(clip_ops.clip_by_value(y, 1, 10)), x * x + 1)\n\n def safe_zeta(x, y):\n return math_ops.zeta(x * x + 1, y * y)\n\n cases = [\n (\"Add\", math_ops.add),\n (\"AddV2\", math_ops.add_v2),\n (\"Atan2\", math_ops.atan2),\n (\"Complex\", math_ops.complex),\n (\"DivNoNan\", math_ops.div_no_nan),\n (\"Equal\", math_ops.equal),\n (\"FloorDiv\", math_ops.floor_div),\n (\"FloorMod\", math_ops.floor_mod),\n (\"Greater\", math_ops.greater),\n (\"GreaterEqual\", math_ops.greater_equal),\n (\"Igamma\", math_ops.igamma),\n (\"Igammac\", math_ops.igammac),\n (\"IgammaGradA\", math_ops.igamma_grad_a),\n (\"Less\", math_ops.less),\n (\"LessEqual\", math_ops.less_equal),\n (\"Maximum\", math_ops.maximum),\n (\"Minimum\", math_ops.minimum),\n (\"Mod\", math_ops.mod),\n (\"Mul\", math_ops.multiply),\n (\"NotEqual\", math_ops.not_equal),\n (\"Polygamma\", safe_polygamma),\n (\"Pow\", math_ops.pow),\n (\"RealDiv\", math_ops.divide),\n (\"SquareDifference\", math_ops.squared_difference),\n (\"Sub\", math_ops.subtract),\n (\"TruncateMod\", math_ops.truncate_mod),\n (\"Zeta\", safe_zeta),\n ]\n return _generate_test_combinations(cases)\n\n\n# TODO(rachelim): Consolidate tests with pfor when APIs are somewhat shared.\nclass MapVectorizationTest(test_base.DatasetTestBase, parameterized.TestCase):\n\n def _enable_map_vectorization(self, dataset, use_choose=True):\n options = dataset_ops.Options()\n opt_options = options.experimental_optimization\n opt_options.map_vectorization.enabled = True\n opt_options.map_vectorization.use_choose_fastest = use_choose\n return dataset.with_options(options)\n\n def _get_test_datasets(self,\n base_dataset,\n map_fn,\n num_parallel_calls=None,\n expect_optimized=True):\n \"\"\"Given base dataset and map fn, creates test datasets.\n\n Returns a tuple of (unoptimized dataset, optimized dataset). The\n unoptimized dataset has the assertion that Batch follows Map. The optimized\n dataset has the assertion that Map follows Batch, and has the\n \"map_vectorization\" optimization applied.\n\n Args:\n base_dataset: Input dataset to map->batch\n map_fn: Map function to use\n num_parallel_calls: (Optional.) num_parallel_calls argument for map\n expect_optimized: (Optional.) Whether we expect the optimization to take\n place, in which case we will assert that Batch is followed by Map,\n otherwise Map followed by Batch. Defaults to True.\n\n Returns:\n Tuple of (unoptimized dataset, optimized dataset).\n \"\"\"\n map_node_name = \"Map\"\n if num_parallel_calls is not None:\n map_node_name = \"ParallelMapV2\"\n\n def _make_dataset(node_names):\n dataset = base_dataset.apply(testing.assert_next(node_names))\n dataset = dataset.map(map_fn, num_parallel_calls)\n dataset = dataset.batch(100)\n options = dataset_ops.Options()\n options.experimental_optimization.apply_default_optimizations = False\n options.experimental_optimization.map_and_batch_fusion = False\n dataset = dataset.with_options(options)\n return dataset\n\n unoptimized = _make_dataset([map_node_name, \"BatchV2\"])\n # Note that because of the `ChooseDataset` fork, we can't use `assert_next`\n # to verify the optimization result.\n optimized = _make_dataset([\"ChooseFastestBranch\"] if expect_optimized else\n [map_node_name, \"BatchV2\"])\n optimized = self._enable_map_vectorization(optimized)\n return unoptimized, optimized\n\n def _testOptimization(self, map_fn, dataset_factory, num_parallel_calls):\n dataset = dataset_factory()\n unoptimized, optimized = self._get_test_datasets(dataset, map_fn,\n num_parallel_calls)\n self.assertDatasetsEqual(unoptimized, optimized)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n combinations.combine(num_parallel_calls=[None, 12])))\n def testBasic(self, num_parallel_calls):\n data = np.random.rand(10, 3)\n dataset_factory = lambda: dataset_ops.Dataset.from_tensors(data).repeat(5)\n map_fn = lambda x: (x, x + 1)\n self._testOptimization(map_fn, dataset_factory, num_parallel_calls)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n combinations.combine(num_parallel_calls=[None, 12])))\n def testBroadcast(self, num_parallel_calls):\n data = np.random.rand(10, 3)\n dataset_factory = lambda: dataset_ops.Dataset.from_tensors(data).repeat(5)\n value = np.random.rand(1, 1, 1, 1, 1, 1)\n map_fn = lambda x: x + value\n self._testOptimization(map_fn, dataset_factory, num_parallel_calls)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n combinations.combine(num_parallel_calls=[None, 12])))\n def testCast(self, num_parallel_calls):\n data = np.random.rand(10, 3)\n dataset_factory = lambda: dataset_ops.Dataset.from_tensors(data).repeat(5)\n map_fn = lambda x: math_ops.cast(x, dtypes.float64)\n self._testOptimization(map_fn, dataset_factory, num_parallel_calls)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n combinations.combine(num_parallel_calls=[None, 12])))\n def testConst(self, num_parallel_calls):\n data = np.random.rand(10, 3)\n dataset_factory = lambda: dataset_ops.Dataset.from_tensors(data).repeat(5)\n map_fn = lambda x: 2\n self._testOptimization(map_fn, dataset_factory, num_parallel_calls)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n combinations.combine(num_parallel_calls=[None, 12])))\n def testCycle(self, num_parallel_calls):\n dataset_factory = lambda: dataset_ops.Dataset.from_tensors(1)\n\n def map_fn(x):\n c = lambda i: math_ops.less(i, 10)\n b = lambda i: math_ops.add(i, 1)\n return control_flow_ops.while_loop(c, b, [x])\n\n self._testOptimization(map_fn, dataset_factory, num_parallel_calls)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n combinations.combine(num_parallel_calls=[None, 12])))\n def testReshape(self, num_parallel_calls):\n data = np.random.rand(10, 3)\n dataset_factory = lambda: dataset_ops.Dataset.from_tensors(data).repeat(5)\n map_fn = lambda x: array_ops.reshape(x, (-1, 30))\n self._testOptimization(map_fn, dataset_factory, num_parallel_calls)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n combinations.combine(num_parallel_calls=[None, 12])))\n def testTranspose(self, num_parallel_calls):\n data = np.random.rand(10, 3)\n dataset_factory = lambda: dataset_ops.Dataset.from_tensors(data).repeat(5)\n map_fn = array_ops.transpose\n self._testOptimization(map_fn, dataset_factory, num_parallel_calls)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n combinations.combine(num_parallel_calls=[None, 12])))\n def testUnstack(self, num_parallel_calls):\n data = np.random.rand(10, 3)\n dataset_factory = lambda: dataset_ops.Dataset.from_tensors(data).repeat(5)\n map_fns = [array_ops.unstack, lambda x: array_ops.unstack(x, axis=-1)]\n for map_fn in map_fns:\n self._testOptimization(map_fn, dataset_factory, num_parallel_calls)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n _unary_bitwise_test_combinations(),\n combinations.combine(num_parallel_calls=[None, 12])))\n def testUnaryBitwiseOperations(self, map_fn, num_parallel_calls):\n x = np.random.randint(0, 10, (7, 3, 5))\n dataset_factory = lambda: dataset_ops.Dataset.from_tensor_slices(x)\n self._testOptimization(map_fn, dataset_factory, num_parallel_calls)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n _unary_logical_test_combinations(),\n combinations.combine(num_parallel_calls=[None, 12])))\n def testUnaryLogicalOperations(self, map_fn, num_parallel_calls):\n x = np.random.rand(3, 5)\n dataset_factory = lambda: dataset_ops.Dataset.from_tensor_slices(x > 0)\n self._testOptimization(map_fn, dataset_factory, num_parallel_calls)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n _unary_complex_test_combinations(),\n combinations.combine(num_parallel_calls=[None, 12])))\n def testUnaryComplexOperations(self, map_fn, num_parallel_calls):\n x = math_ops.complex(np.random.rand(3, 5), np.random.rand(3, 5))\n dataset_factory = lambda: dataset_ops.Dataset.from_tensor_slices(x)\n self._testOptimization(map_fn, dataset_factory, num_parallel_calls)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n _unary_real_test_combinations(),\n combinations.combine(num_parallel_calls=[None, 12])))\n def testUnaryRealOperations(self, map_fn, num_parallel_calls):\n x = np.random.rand(3, 5)\n dataset_factory = lambda: dataset_ops.Dataset.from_tensor_slices(x)\n self._testOptimization(map_fn, dataset_factory, num_parallel_calls)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n _binary_bitwise_test_combinations(),\n combinations.combine(num_parallel_calls=[None, 12])))\n def testBinaryBitwiseOperations(self, map_fn, num_parallel_calls):\n x = np.random.randint(0, 10, (7, 3, 5))\n y = np.random.randint(0, 10, (3, 5))\n dataset_factory = lambda: dataset_ops.Dataset.from_tensors((x, y))\n self._testOptimization(map_fn, dataset_factory, num_parallel_calls)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n _binary_logical_test_combinations(),\n combinations.combine(num_parallel_calls=[None, 12])))\n def testBinaryLogicalOperations(self, map_fn, num_parallel_calls):\n x = np.random.rand(7, 3, 5)\n y = np.random.rand(3, 5)\n dataset_factory = lambda: dataset_ops.Dataset.from_tensors((x > 0, y > 0))\n self._testOptimization(map_fn, dataset_factory, num_parallel_calls)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n _binary_real_test_combinations(),\n combinations.combine(num_parallel_calls=[None, 12])))\n def testBinaryRealOperations(self, map_fn, num_parallel_calls):\n x = np.random.rand(7, 3, 5)\n y = np.random.rand(3, 5)\n dataset_factory = lambda: dataset_ops.Dataset.from_tensors((x, y))\n self._testOptimization(map_fn, dataset_factory, num_parallel_calls)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n combinations.combine(num_parallel_calls=[None, 12])))\n def testDecodeCsv(self, num_parallel_calls):\n\n def dataset_factory():\n return dataset_ops.Dataset.from_tensor_slices([\"1.0:2:a\",\n \"2.4:5:c\"]).repeat(5)\n\n def decode_csv_fn(x):\n return parsing_ops.decode_csv(\n x,\n record_defaults=[\n constant_op.constant([], dtypes.float32),\n constant_op.constant([], dtypes.int32),\n constant_op.constant([], dtypes.string)\n ],\n field_delim=\":\")\n\n self._testOptimization(decode_csv_fn, dataset_factory, num_parallel_calls)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n combinations.combine(num_parallel_calls=[None, 12])))\n def testParseSingleExample(self, num_parallel_calls):\n\n def dataset_factory():\n\n def _int64_feature(*values):\n return feature_pb2.Feature(\n int64_list=feature_pb2.Int64List(value=values))\n\n def _bytes_feature(*values):\n return feature_pb2.Feature(\n bytes_list=feature_pb2.BytesList(\n value=[v.encode(\"utf-8\") for v in values]))\n\n # pylint:disable=g-complex-comprehension\n return dataset_ops.Dataset.from_tensor_slices(\n constant_op.constant([\n example_pb2.Example(\n features=feature_pb2.Features(\n feature={\n \"dense_int\": _int64_feature(i),\n \"dense_str\": _bytes_feature(str(i)),\n })).SerializeToString() for i in range(10)\n ]))\n\n def parse_fn(x):\n features = {\n \"dense_int\": parsing_ops.FixedLenFeature((), dtypes.int64, 0),\n \"dense_str\": parsing_ops.FixedLenFeature((), dtypes.string, \"\"),\n }\n return parsing_ops.parse_single_example(x, features)\n\n def dense_only_parse_fn(x):\n return [\n y for y in parse_fn(x)\n if not isinstance(y, sparse_tensor.SparseTensor)\n ]\n\n map_fns = [parse_fn, dense_only_parse_fn]\n\n for map_fn in map_fns:\n self._testOptimization(map_fn, dataset_factory, num_parallel_calls)\n\n @combinations.generate(test_base.default_test_combinations())\n def testOptimizationBadMapFn(self):\n # Test map functions that give an error\n def map_fn(x):\n # x has leading dimension 5, this will raise an error\n return array_ops.gather(x, 10)\n\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n r\"indices = 10 is not in \\[0, 5\\)\"):\n base_dataset = dataset_ops.Dataset.range(5).repeat(5).batch(\n 5, drop_remainder=True)\n _, optimized = self._get_test_datasets(base_dataset, map_fn)\n nxt = dataset_ops.make_one_shot_iterator(optimized).get_next()\n self.evaluate(nxt)\n\n @combinations.generate(test_base.default_test_combinations())\n def testOptimizationWithCapturedInputs(self):\n # Tests that vectorization works with captured inputs.\n y = constant_op.constant(1, shape=(2,))\n z = constant_op.constant(2, shape=(2,))\n\n def map_fn(x):\n return x, y, z\n\n base_dataset = dataset_ops.Dataset.from_tensor_slices([[1, 2],\n [3, 4]]).repeat(5)\n unoptimized, optimized = self._get_test_datasets(\n base_dataset, map_fn, expect_optimized=True)\n self.assertDatasetsEqual(optimized, unoptimized)\n\n @combinations.generate(test_base.default_test_combinations())\n def testOptimizationWithMapAndBatchFusion(self):\n # Tests that vectorization works on fused map and batch.\n def map_fn(x):\n return x**2\n\n base_dataset = dataset_ops.Dataset.range(1000)\n options = dataset_ops.Options()\n options.experimental_optimization.apply_default_optimizations = False\n base_dataset = base_dataset.with_options(options)\n\n def _make_dataset(node_names):\n dataset = base_dataset.apply(testing.assert_next(node_names))\n dataset = dataset.apply(batching.map_and_batch(map_fn, 100))\n return dataset\n\n unoptimized = _make_dataset([\"MapAndBatch\"])\n optimized = _make_dataset([\"ChooseFastestBranch\"])\n optimized = self._enable_map_vectorization(optimized)\n self.assertDatasetsEqual(optimized, unoptimized)\n\n @combinations.generate(\n combinations.times(\n test_base.default_test_combinations(),\n combinations.combine(\n fuse_first=[True, False], fuse_second=[True, False])))\n def testOptimizationWithChainedMapAndBatch(self, fuse_first, fuse_second):\n # Tests that vectorization works on chained map and batch functions.\n def map_fn(x):\n return x * 2\n\n def make_apply_fn(is_fused):\n if is_fused:\n\n def apply_fn(dataset):\n return dataset.apply(\n batching.map_and_batch(map_fn, 2, 12, drop_remainder=True))\n\n return apply_fn\n else:\n\n def apply_fn(dataset):\n return dataset.map(map_fn, 12).batch(2, drop_remainder=True)\n\n return apply_fn\n\n base_dataset = dataset_ops.Dataset.range(1000)\n options = dataset_ops.Options()\n options.experimental_optimization.apply_default_optimizations = False\n base_dataset = base_dataset.with_options(options)\n\n apply_fn_1 = make_apply_fn(fuse_first)\n apply_fn_2 = make_apply_fn(fuse_second)\n\n def make_dataset():\n dataset = base_dataset\n dataset = apply_fn_1(dataset)\n dataset = apply_fn_2(dataset)\n return dataset\n\n unoptimized = make_dataset()\n optimized = make_dataset()\n optimized = self._enable_map_vectorization(optimized)\n self.assertDatasetsEqual(optimized, unoptimized)\n\n @combinations.generate(\n combinations.times(\n test_base.default_test_combinations(),\n combinations.combine(\n local_determinism=[True, False, None],\n global_determinism=[True, False])))\n def testOptimizationDeterminism(self, local_determinism, global_determinism):\n # Tests that vectorization maintains the determinism setting.\n expect_determinism = local_determinism or (local_determinism is None and\n global_determinism)\n elements = list(range(1000))\n\n def dataset_fn(delay_ms):\n\n def sleep(x):\n time.sleep(delay_ms / 1000)\n return x\n\n def map_function(x):\n if math_ops.equal(x, 0):\n return check_ops.ensure_shape(\n script_ops.py_func(sleep, [x], x.dtype, stateful=False), ())\n else:\n return x\n\n dataset = dataset_ops.Dataset.from_tensor_slices(elements)\n dataset = dataset.map(\n map_function, num_parallel_calls=10, deterministic=local_determinism)\n dataset = dataset.batch(1)\n\n opts = dataset_ops.Options()\n opts.experimental_deterministic = global_determinism\n # Prevent the map/batch from being rewritten as MapAndBatch.\n opts.experimental_optimization.apply_default_optimizations = False\n dataset = dataset.with_options(opts)\n dataset = self._enable_map_vectorization(dataset)\n return dataset\n\n self.checkDeterminism(\n dataset_fn,\n expect_determinism,\n expected_elements=[[element] for element in elements])\n\n @combinations.generate(test_base.default_test_combinations())\n def testOptimizationIgnoreStateful(self):\n\n def map_fn(x):\n with ops.control_dependencies([check_ops.assert_equal(x, np.int64(0))]):\n return array_ops.identity(x)\n\n dataset = dataset_ops.Dataset.range(10)\n dataset = dataset.map(map_fn)\n dataset = dataset.batch(10)\n dataset = self._enable_map_vectorization(dataset, use_choose=False)\n with self.assertRaises(errors.InvalidArgumentError):\n get_next = self.getNext(dataset)\n self.evaluate(get_next())\n\n @combinations.generate(test_base.default_test_combinations())\n def testOptimizationIgnoreRagged(self):\n # Make sure we ignore inputs that might not be uniformly sized\n def map_fn(x):\n return array_ops.gather(x, np.int64(0))\n\n # output_shape = (?,)\n base_dataset = dataset_ops.Dataset.range(20).batch(3, drop_remainder=False)\n unoptimized, optimized = self._get_test_datasets(\n base_dataset, map_fn, expect_optimized=False)\n self.assertDatasetsEqual(unoptimized, optimized)\n\n @combinations.generate(test_base.default_test_combinations())\n def testOptimizationIgnoreRaggedMap(self):\n # Don't optimize when the output of the map fn shapes are unknown.\n def map_fn(x):\n return array_ops.tile(x, x)\n\n dataset = dataset_ops.Dataset.range(10).batch(1)\n dataset = dataset.map(map_fn)\n dataset = dataset.batch(10)\n dataset = self._enable_map_vectorization(dataset, use_choose=False)\n with self.assertRaises(errors.InvalidArgumentError):\n get_next = self.getNext(dataset)\n self.evaluate(get_next())\n\n @combinations.generate(test_base.default_test_combinations())\n def testOptimizationWithUnknownBatchShape(self):\n tensor = sparse_tensor.SparseTensor(\n indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])\n\n # Datasets with sparse tensors have unknown output shapes.\n base_dataset = dataset_ops.Dataset.from_tensors(tensor)\n unoptimized = base_dataset.apply(batching.map_and_batch(lambda x: x, 2))\n options = dataset_ops.Options()\n options.experimental_optimization.apply_default_optimizations = False\n unoptimized = unoptimized.with_options(options)\n\n optimized = self._enable_map_vectorization(unoptimized)\n self.assertDatasetsEqual(unoptimized, optimized)\n\n @combinations.generate(test_base.default_test_combinations())\n def testOptimizationWithSparseTensor(self):\n base_dataset = dataset_ops.Dataset.from_tensors(0)\n\n def map_fn(x):\n del x\n return sparse_tensor.SparseTensor(\n indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])\n\n # Datasets with sparse tensors have unknown output shapes.\n unoptimized = base_dataset.apply(batching.map_and_batch(map_fn, 2))\n options = dataset_ops.Options()\n options.experimental_optimization.apply_default_optimizations = False\n unoptimized = unoptimized.with_options(options)\n optimized = self._enable_map_vectorization(unoptimized)\n self.assertDatasetsEqual(unoptimized, optimized)\n\n @combinations.generate(test_base.default_test_combinations())\n def testOptimizationWithPrefetch(self):\n dataset = dataset_ops.Dataset.range(10)\n dataset = dataset.map(lambda x: x)\n dataset = dataset.prefetch(1)\n dataset = dataset.batch(10)\n dataset = self._enable_map_vectorization(dataset)\n self.assertDatasetProduces(dataset, [list(range(10))])\n\n @combinations.generate(test_base.default_test_combinations())\n def testOptimizationWithoutChooseFastest(self):\n dataset = dataset_ops.Dataset.range(10)\n dataset = dataset.map(lambda x: x**2)\n dataset = dataset.batch(10)\n dataset = self._enable_map_vectorization(dataset, use_choose=False)\n self.assertDatasetProduces(dataset, [[x**2 for x in range(10)]])\n\n\nif __name__ == \"__main__\":\n test.main()\n",
"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\nimport os\nimport weakref\n\nfrom absl.testing import parameterized\nimport six\n\nfrom tensorflow.python.eager import backprop\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.keras.engine import input_layer\nfrom tensorflow.python.keras.engine import sequential\nfrom tensorflow.python.keras.engine import training\nfrom tensorflow.python.keras.layers import core\nfrom tensorflow.python.keras.optimizer_v2 import adam\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops import template\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables as variables_lib\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.training import checkpoint_management\nfrom tensorflow.python.training import saver as saver_lib\nfrom tensorflow.python.training import training_util\nfrom tensorflow.python.training.tracking import graph_view\nfrom tensorflow.python.training.tracking import tracking\nfrom tensorflow.python.training.tracking import util as trackable_utils\n\n\n# pylint: disable=not-callable\nclass MyModel(training.Model):\n \"\"\"A concrete Model for testing.\"\"\"\n\n def __init__(self):\n super(MyModel, self).__init__()\n self._named_dense = core.Dense(1, use_bias=True)\n self._second = core.Dense(1, use_bias=False)\n # We can still track Trackables which aren't Layers.\n self._non_layer = NonLayerTrackable()\n\n def call(self, values):\n ret = self._second(self._named_dense(values))\n return ret\n\n\nclass NonLayerTrackable(tracking.AutoTrackable):\n\n def __init__(self):\n super(NonLayerTrackable, self).__init__()\n self.a_variable = trackable_utils.add_variable(\n self, name=\"a_variable\", shape=[])\n\n\nclass InterfaceTests(test.TestCase):\n\n def testLayerDeduplication(self):\n model = training.Model()\n layer_one = core.Dense(1)\n layer_two = core.Dense(1)\n model.other_path = [layer_one, layer_two]\n model.l2 = layer_two\n model.l1 = layer_one\n self.assertEqual([layer_one, layer_two], model.layers)\n\n def testSaveWithOnlyKerasSession(self):\n\n with ops.Graph().as_default():\n inp = input_layer.Input([1])\n dense = core.Dense(1)(inp)\n model = training.Model(inp, dense)\n model.compile(optimizer=\"sgd\", loss=\"mse\")\n model.fit([1.], [2.])\n checkpoint = trackable_utils.Checkpoint(model=model)\n checkpoint.save(os.path.join(self.get_temp_dir(), \"ckpt\"))\n\n def testObjectMetadata(self):\n with context.eager_mode():\n checkpoint_directory = self.get_temp_dir()\n checkpoint_prefix = os.path.join(checkpoint_directory, \"ckpt\")\n dense = core.Dense(1)\n checkpoint = trackable_utils.Checkpoint(dense=dense)\n dense(constant_op.constant([[1.]]))\n save_path = checkpoint.save(checkpoint_prefix)\n\n objects = trackable_utils.object_metadata(save_path)\n all_variable_names = []\n for obj in objects.nodes:\n for attribute in obj.attributes:\n all_variable_names.append(attribute.full_name)\n self.assertIn(\"dense/kernel\", all_variable_names)\n\n\nclass CheckpointingTests(parameterized.TestCase, test.TestCase):\n\n @test_util.run_in_graph_and_eager_modes(assert_no_eager_garbage=True)\n def testNamingWithOptimizer(self):\n input_value = constant_op.constant([[3.]])\n model = MyModel()\n # A nuisance Model using the same optimizer. Its slot variables should not\n # go in the checkpoint, since it is never depended on.\n other_model = MyModel()\n optimizer = adam.Adam(0.001)\n step = training_util.get_or_create_global_step()\n root_trackable = trackable_utils.Checkpoint(\n optimizer=optimizer, model=model, step=step)\n\n with backprop.GradientTape() as tape:\n loss = model(input_value)\n variables = model.trainable_variables\n gradients = tape.gradient(loss, variables)\n train_op = control_flow_ops.group(\n optimizer.apply_gradients(zip(gradients, variables)),\n step.assign_add(1))\n\n with backprop.GradientTape() as tape:\n loss = other_model(input_value)\n variables = other_model.trainable_variables\n gradients = tape.gradient(loss, variables)\n optimizer.apply_gradients(zip(gradients, variables))\n\n self.evaluate(trackable_utils.gather_initializers(\n root_trackable))\n self.evaluate(train_op)\n named_variables, serialized_graph, _ = graph_view.ObjectGraphView(\n root_trackable).serialize_object_graph()\n expected_slot_keys = (\n \"model/_second/kernel/.OPTIMIZER_SLOT/optimizer/m\",\n \"model/_second/kernel/.OPTIMIZER_SLOT/optimizer/v\",\n \"model/_named_dense/kernel/.OPTIMIZER_SLOT/optimizer/m\",\n \"model/_named_dense/kernel/.OPTIMIZER_SLOT/optimizer/v\",\n \"model/_named_dense/bias/.OPTIMIZER_SLOT/optimizer/m\",\n \"model/_named_dense/bias/.OPTIMIZER_SLOT/optimizer/v\",\n )\n expected_checkpoint_names = (\n # Created in the root node, so no prefix.\n \"step\",\n \"model/_second/kernel\",\n \"model/_named_dense/kernel\",\n \"model/_named_dense/bias\",\n # non-Layer dependency of the model\n \"model/_non_layer/a_variable\",\n \"optimizer/learning_rate\",\n \"optimizer/beta_1\",\n \"optimizer/beta_2\",\n \"optimizer/iter\",\n \"optimizer/decay\",\n ) + expected_slot_keys\n suffix = \"/.ATTRIBUTES/VARIABLE_VALUE\"\n expected_checkpoint_names = [\n name + suffix for name in expected_checkpoint_names]\n named_variables = {v.name: v for v in named_variables}\n six.assertCountEqual(self, expected_checkpoint_names,\n named_variables.keys())\n # Check that we've mapped to the right variable objects (not exhaustive)\n self.assertEqual(\n \"global_step\",\n named_variables[\"step\" + suffix].full_name)\n self.assertEqual(\n \"my_model/dense_1/kernel\",\n named_variables[\"model/_second/kernel\" + suffix].full_name)\n self.assertEqual(\n \"my_model/dense/kernel\",\n named_variables[\"model/_named_dense/kernel\" + suffix].full_name)\n self.assertEqual(\"Adam/beta_1\",\n named_variables[\"optimizer/beta_1\" + suffix].full_name)\n self.assertEqual(\"Adam/beta_2\",\n named_variables[\"optimizer/beta_2\" + suffix].full_name)\n # Spot check the generated protocol buffers.\n self.assertEqual(\"optimizer\",\n serialized_graph.nodes[0].children[1].local_name)\n optimizer_node = serialized_graph.nodes[\n serialized_graph.nodes[0].children[1].node_id]\n children = [node.local_name for node in optimizer_node.children]\n six.assertCountEqual(\n self,\n # hyper variable dependencies\n [\"beta_1\", \"beta_2\", \"iter\", \"decay\", \"learning_rate\"],\n children)\n serialized_slot_keys = []\n for slot in optimizer_node.slot_variables:\n for attribute in (\n serialized_graph.nodes[slot.slot_variable_node_id].attributes):\n serialized_slot_keys.append(attribute.checkpoint_key)\n six.assertCountEqual(\n self,\n [key + suffix for key in expected_slot_keys],\n serialized_slot_keys)\n\n @test_util.run_in_graph_and_eager_modes\n def testSaveRestore(self):\n model = MyModel()\n optimizer = adam.Adam(0.001)\n root_trackable = trackable_utils.Checkpoint(\n optimizer=optimizer, model=model)\n input_value = constant_op.constant([[3.]])\n with backprop.GradientTape() as tape:\n loss = model(input_value)\n variables = model.trainable_variables\n gradients = tape.gradient(loss, variables)\n train_op = optimizer.apply_gradients(zip(gradients, variables))\n self.assertFalse(root_trackable.save_counter.trainable)\n self.evaluate(trackable_utils.gather_initializers(\n root_trackable))\n self.evaluate(train_op)\n prefix = os.path.join(self.get_temp_dir(), \"ckpt\")\n self.evaluate(state_ops.assign(model._named_dense.variables[1], [42.]))\n m_bias_slot = optimizer.get_slot(model._named_dense.variables[1], \"m\")\n self.evaluate(state_ops.assign(m_bias_slot, [1.5]))\n save_path = root_trackable.save(file_prefix=prefix)\n self.evaluate(state_ops.assign(model._named_dense.variables[1], [43.]))\n self.evaluate(state_ops.assign(root_trackable.save_counter, 3))\n optimizer_variables = self.evaluate(\n sorted(optimizer.variables(), key=lambda v: v.name))\n self.evaluate(state_ops.assign(m_bias_slot, [-2.]))\n # Immediate restoration\n status = root_trackable.restore(save_path=save_path).assert_consumed()\n status.run_restore_ops()\n self.assertAllEqual([42.], self.evaluate(model._named_dense.variables[1]))\n self.assertAllEqual(1, self.evaluate(root_trackable.save_counter))\n self.assertAllEqual([1.5], self.evaluate(m_bias_slot))\n if not context.executing_eagerly():\n return # Restore-on-create is only supported when executing eagerly\n on_create_model = MyModel()\n on_create_optimizer = adam.Adam(0.001)\n on_create_root = trackable_utils.Checkpoint(\n optimizer=on_create_optimizer, model=on_create_model)\n # Deferred restoration\n status = on_create_root.restore(save_path=save_path)\n status.assert_nontrivial_match()\n status.assert_existing_objects_matched()\n with self.assertRaises(AssertionError):\n status.assert_consumed()\n on_create_model(constant_op.constant([[3.]])) # create variables\n self.assertAllEqual(1, self.evaluate(on_create_root.save_counter))\n self.assertAllEqual([42.],\n self.evaluate(\n on_create_model._named_dense.variables[1]))\n on_create_m_bias_slot = on_create_optimizer.get_slot(\n on_create_model._named_dense.variables[1], \"m\")\n status.assert_existing_objects_matched()\n if not context.executing_eagerly():\n with self.assertRaises(AssertionError):\n status.assert_consumed()\n # Optimizer slot variables are created when the original variable is\n # restored.\n self.assertAllEqual([1.5], self.evaluate(on_create_m_bias_slot))\n dummy_var = resource_variable_ops.ResourceVariable([1.])\n on_create_optimizer.minimize(loss=dummy_var.read_value,\n var_list=[dummy_var])\n status.assert_existing_objects_matched()\n status.assert_consumed()\n self.assertAllEqual(\n optimizer_variables,\n # Creation order is different, so .variables() needs to be re-sorted.\n self.evaluate(sorted(optimizer.variables(), key=lambda v: v.name)))\n\n # TODO(allenl): Debug garbage created by this test in python3.\n def testDeferredRestorationUsageEager(self):\n \"\"\"An idiomatic eager execution example.\"\"\"\n num_training_steps = 10\n checkpoint_directory = self.get_temp_dir()\n checkpoint_prefix = os.path.join(checkpoint_directory, \"ckpt\")\n for training_continuation in range(3):\n model = MyModel()\n optimizer = adam.Adam(0.001)\n root = trackable_utils.Checkpoint(\n optimizer=optimizer, model=model)\n root.restore(checkpoint_management.latest_checkpoint(\n checkpoint_directory))\n for _ in range(num_training_steps):\n # TODO(allenl): Use a Dataset and serialize/checkpoint it.\n input_value = constant_op.constant([[3.]])\n with backprop.GradientTape() as tape:\n loss = model(input_value)\n variables = model.trainable_variables\n gradients = tape.gradient(loss, variables)\n optimizer.apply_gradients(zip(gradients, variables))\n root.save(file_prefix=checkpoint_prefix)\n self.assertEqual((training_continuation + 1) * num_training_steps,\n root.optimizer.iterations.numpy())\n\n def testUsageGraph(self):\n \"\"\"Expected usage when graph building.\"\"\"\n with context.graph_mode():\n num_training_steps = 10\n checkpoint_directory = self.get_temp_dir()\n checkpoint_prefix = os.path.join(checkpoint_directory, \"ckpt\")\n for training_continuation in range(3):\n with ops.Graph().as_default():\n model = MyModel()\n optimizer = adam.Adam(0.001)\n root = trackable_utils.CheckpointV1(\n optimizer=optimizer, model=model)\n input_value = constant_op.constant([[3.]])\n with backprop.GradientTape() as tape:\n loss = model(input_value)\n variables = model.trainable_variables\n gradients = tape.gradient(loss, variables)\n train_op = optimizer.apply_gradients(zip(gradients, variables))\n\n checkpoint_path = checkpoint_management.latest_checkpoint(\n checkpoint_directory)\n with self.session(graph=ops.get_default_graph()) as session:\n status = root.restore(save_path=checkpoint_path)\n status.initialize_or_restore(session=session)\n if checkpoint_path is None:\n self.assertEqual(0, training_continuation)\n with self.assertRaises(AssertionError):\n status.assert_consumed()\n with self.assertRaises(AssertionError):\n status.assert_existing_objects_matched()\n else:\n status.assert_consumed()\n status.assert_existing_objects_matched()\n for _ in range(num_training_steps):\n session.run(train_op)\n root.save(file_prefix=checkpoint_prefix, session=session)\n self.assertEqual((training_continuation + 1) * num_training_steps,\n session.run(root.optimizer.iterations))\n self.assertEqual(training_continuation + 1,\n session.run(root.save_counter))\n\n @test_util.run_in_graph_and_eager_modes\n def testAgnosticUsage(self):\n \"\"\"Graph/eager agnostic usage.\"\"\"\n # Does create garbage when executing eagerly due to ops.Graph() creation.\n num_training_steps = 10\n checkpoint_directory = self.get_temp_dir()\n def _train_fn(model, input_value):\n with backprop.GradientTape() as tape:\n loss = model(input_value)\n variables = model.trainable_variables\n gradients = tape.gradient(loss, variables)\n return optimizer.apply_gradients(zip(gradients, variables))\n for training_continuation in range(3):\n with test_util.device(use_gpu=True):\n model = MyModel()\n optimizer = adam.Adam(0.001)\n root = trackable_utils.Checkpoint(\n optimizer=optimizer, model=model)\n manager = checkpoint_management.CheckpointManager(\n root, checkpoint_directory, max_to_keep=1)\n status = root.restore(save_path=manager.latest_checkpoint)\n input_value = constant_op.constant([[3.]])\n train_fn = functools.partial(_train_fn, model, input_value)\n if not context.executing_eagerly():\n train_fn = functools.partial(self.evaluate, train_fn())\n status.initialize_or_restore()\n for _ in range(num_training_steps):\n train_fn()\n manager.save()\n self.assertEqual((training_continuation + 1) * num_training_steps,\n self.evaluate(root.optimizer.iterations))\n self.assertEqual(training_continuation + 1,\n self.evaluate(root.save_counter))\n\n def testPartialRestoreWarningObject(self):\n with context.eager_mode():\n optimizer = adam.Adam(0.0)\n original_root = trackable_utils.Checkpoint(v1=variables_lib.Variable(2.),\n v2=variables_lib.Variable(3.),\n optimizer=optimizer)\n # Create a slot variable to save\n optimizer.minimize(original_root.v1.read_value, [original_root.v1])\n prefix = os.path.join(self.get_temp_dir(), \"ckpt\")\n save_path = original_root.save(prefix)\n partial_root = trackable_utils.Checkpoint(v1=variables_lib.Variable(0.))\n weak_partial_root = weakref.ref(partial_root)\n weak_v1 = weakref.ref(partial_root.v1)\n partial_root.restore(save_path)\n self.assertEqual(2., partial_root.v1.numpy())\n with test.mock.patch.object(logging, \"warning\") as mock_log:\n del partial_root\n self.assertIsNone(weak_partial_root())\n self.assertIsNone(weak_v1())\n messages = str(mock_log.call_args_list)\n self.assertIn(\"(root).v2'\", messages)\n self.assertIn(\"(root).optimizer's state 'm' for (root).v1\", messages)\n self.assertNotIn(\"(root).v1'\", messages)\n self.assertIn(\"expect_partial()\", messages)\n\n # pylint: disable=cell-var-from-loop\n @test_util.run_in_graph_and_eager_modes\n @test_util.run_v1_only(\"b/120545219\")\n def testWithDefun(self):\n num_training_steps = 2\n checkpoint_directory = self.get_temp_dir()\n checkpoint_prefix = os.path.join(checkpoint_directory, \"ckpt\")\n for training_continuation in range(3):\n with test_util.device(use_gpu=True):\n model = MyModel()\n # Don't actually train so we can test variable values\n optimizer = adam.Adam(0.)\n root = trackable_utils.Checkpoint(\n optimizer=optimizer, model=model)\n checkpoint_path = checkpoint_management.latest_checkpoint(\n checkpoint_directory)\n status = root.restore(save_path=checkpoint_path)\n def train_fn():\n @def_function.function\n def _call_model(x):\n return model(x)\n with backprop.GradientTape() as tape:\n loss = _call_model(constant_op.constant([[3.]]))\n gradients = tape.gradient(loss, model.variables)\n return optimizer.apply_gradients(zip(gradients, model.variables))\n if not context.executing_eagerly():\n train_fn = functools.partial(\n self.evaluate, train_fn())\n status.initialize_or_restore()\n for _ in range(num_training_steps):\n train_fn()\n if training_continuation > 0:\n status.assert_consumed()\n self.assertAllClose([[42.]], self.evaluate(model.variables[0]))\n else:\n self.evaluate(model.variables[0].assign([[42.]]))\n root.save(file_prefix=checkpoint_prefix)\n self.assertEqual((training_continuation + 1) * num_training_steps,\n self.evaluate(optimizer.iterations))\n self.assertEqual(training_continuation + 1,\n self.evaluate(root.save_counter))\n # pylint: enable=cell-var-from-loop\n\n def testAnonymousVarsInInit(self):\n\n class Model(training.Model):\n\n def __init__(self):\n super(Model, self).__init__()\n self.w = resource_variable_ops.ResourceVariable(0.0)\n self.b = resource_variable_ops.ResourceVariable(0.0)\n self.vars = [self.w, self.b]\n\n def call(self, x):\n return x * self.w + self.b\n\n with context.eager_mode():\n model = Model()\n optimizer = adam.Adam(learning_rate=0.05)\n checkpoint_directory = self.get_temp_dir()\n checkpoint_prefix = os.path.join(checkpoint_directory, \"ckpt\")\n checkpoint = trackable_utils.Checkpoint(\n model=model, optimizer=optimizer)\n for _ in range(2):\n checkpoint.save(checkpoint_prefix)\n with backprop.GradientTape() as tape:\n loss = (constant_op.constant(1.)\n - model(constant_op.constant(1.))) ** 2\n grad = tape.gradient(loss, model.vars)\n optimizer.apply_gradients(\n [(g, v) for g, v in zip(grad, model.vars)])\n\n @test_util.run_in_graph_and_eager_modes\n def testDeferredSlotRestoration(self):\n checkpoint_directory = self.get_temp_dir()\n\n root = trackable_utils.Checkpoint()\n root.var = trackable_utils.add_variable(\n root, name=\"var\", initializer=0.)\n optimizer = adam.Adam(0.1)\n variables = [root.var]\n gradients = [1.]\n train_op = optimizer.apply_gradients(zip(gradients, variables))\n # Note that `optimizer` has not been added as a dependency of\n # `root`. Create a one-off grouping so that slot variables for `root.var`\n # get initialized too.\n self.evaluate(trackable_utils.gather_initializers(\n trackable_utils.Checkpoint(root=root, optimizer=optimizer)))\n self.evaluate(train_op)\n self.evaluate(state_ops.assign(root.var, 12.))\n no_slots_path = root.save(os.path.join(checkpoint_directory, \"no_slots\"))\n root.optimizer = optimizer\n self.evaluate(state_ops.assign(root.var, 13.))\n self.evaluate(state_ops.assign(\n optimizer.get_slot(slot_name=\"m\", var=root.var),\n 14.))\n slots_path = root.save(os.path.join(checkpoint_directory, \"with_slots\"))\n new_root = trackable_utils.Checkpoint()\n # Load the slot-containing checkpoint (deferred), then immediately overwrite\n # the non-slot variable (also deferred).\n slot_status = new_root.restore(slots_path)\n no_slot_status = new_root.restore(no_slots_path)\n with self.assertRaises(AssertionError):\n no_slot_status.assert_consumed()\n new_root.var = trackable_utils.add_variable(\n new_root, name=\"var\", shape=[])\n no_slot_status.assert_consumed()\n no_slot_status.run_restore_ops()\n self.assertEqual(12., self.evaluate(new_root.var))\n new_root.optimizer = adam.Adam(0.1)\n slot_status.assert_existing_objects_matched()\n if not context.executing_eagerly():\n with self.assertRaisesRegex(AssertionError, \"Unresolved object\"):\n slot_status.assert_consumed()\n self.assertEqual(12., self.evaluate(new_root.var))\n if context.executing_eagerly():\n # Slot variables are only created with restoring initializers when\n # executing eagerly.\n self.assertEqual(14., self.evaluate(\n new_root.optimizer.get_slot(slot_name=\"m\", var=new_root.var)))\n else:\n # Slot variables are not created eagerly when graph building.\n with self.assertRaises(KeyError):\n new_root.optimizer.get_slot(slot_name=\"m\", var=new_root.var)\n variables = [new_root.var]\n gradients = [1.]\n train_op = new_root.optimizer.apply_gradients(zip(gradients, variables))\n # The slot variable now exists; restore() didn't create it, but we should\n # now have a restore op for it.\n slot_status.run_restore_ops()\n if not context.executing_eagerly():\n # The train op hasn't run when graph building, so the slot variable has\n # its restored value. It has run in eager, so the value will be different.\n self.assertEqual(14., self.evaluate(\n new_root.optimizer.get_slot(slot_name=\"m\", var=new_root.var)))\n self.evaluate(train_op)\n slot_status.assert_consumed()\n\n def testManySavesGraph(self):\n \"\"\"Saves after the first should not modify the graph.\"\"\"\n with context.graph_mode():\n graph = ops.Graph()\n with graph.as_default(), self.session(graph):\n checkpoint_directory = self.get_temp_dir()\n checkpoint_prefix = os.path.join(checkpoint_directory, \"ckpt\")\n obj = trackable_utils.Checkpoint()\n obj.var = variables_lib.Variable(0., name=\"v\")\n obj.opt = adam.Adam(0.1)\n variables = [obj.var]\n gradients = [1.]\n obj.opt.apply_gradients(zip(gradients, variables))\n self.evaluate(trackable_utils.gather_initializers(obj))\n obj.save(checkpoint_prefix)\n graph.finalize()\n obj.save(checkpoint_prefix)\n\n def testManyRestoresGraph(self):\n \"\"\"Restores after the first should not modify the graph.\"\"\"\n with context.graph_mode():\n graph = ops.Graph()\n with graph.as_default(), self.session(graph):\n checkpoint_directory = self.get_temp_dir()\n checkpoint_prefix = os.path.join(checkpoint_directory, \"ckpt\")\n obj = trackable_utils.Checkpoint()\n obj.var = variables_lib.Variable(0., name=\"v\")\n obj.opt = adam.Adam(0.1)\n variables = [obj.var]\n gradients = [1.]\n obj.opt.apply_gradients(zip(gradients, variables))\n self.evaluate(trackable_utils.gather_initializers(obj))\n save_path = obj.save(checkpoint_prefix)\n obj.restore(save_path)\n graph.finalize()\n obj.restore(save_path)\n\n @test_util.run_in_graph_and_eager_modes\n def test_sequential(self):\n model = sequential.Sequential()\n checkpoint = trackable_utils.Checkpoint(model=model)\n model.add(core.Dense(4))\n second_dense = core.Dense(5)\n model.add(second_dense)\n model(constant_op.constant([[1.]]))\n checkpoint.restore(None).initialize_or_restore()\n self.evaluate(second_dense.bias.assign(\n constant_op.constant([1., 2., 3., 4., 5.])))\n checkpoint_directory = self.get_temp_dir()\n checkpoint_prefix = os.path.join(checkpoint_directory, \"ckpt\")\n save_path = checkpoint.save(checkpoint_prefix)\n self.evaluate(second_dense.bias.assign(\n constant_op.constant([5., 6., 7., 8., 9.])))\n checkpoint.restore(save_path).assert_consumed().run_restore_ops()\n self.assertAllEqual([1., 2., 3., 4., 5.], self.evaluate(second_dense.bias))\n\n deferred_sequential = sequential.Sequential()\n deferred_sequential_checkpoint = trackable_utils.Checkpoint(\n model=deferred_sequential)\n status = deferred_sequential_checkpoint.restore(save_path)\n deferred_sequential.add(core.Dense(4))\n deferred_second_dense = core.Dense(5)\n deferred_sequential.add(deferred_second_dense)\n deferred_sequential(constant_op.constant([[1.]]))\n status.run_restore_ops()\n self.assertAllEqual([1., 2., 3., 4., 5.],\n self.evaluate(deferred_second_dense.bias))\n\n @test_util.run_in_graph_and_eager_modes\n def test_initialize_if_not_restoring(self):\n checkpoint_directory = self.get_temp_dir()\n checkpoint_prefix = os.path.join(checkpoint_directory, \"ckpt\")\n optimizer_only_prefix = os.path.join(checkpoint_directory, \"opt\")\n with test_util.device(use_gpu=True):\n model = MyModel()\n optimizer = adam.Adam(0.001)\n root = trackable_utils.Checkpoint(\n model=model) # Do not save the optimizer with the checkpoint.\n optimizer_checkpoint = trackable_utils.Checkpoint(\n optimizer=optimizer)\n\n checkpoint_path = checkpoint_management.latest_checkpoint(\n checkpoint_directory)\n status = root.restore(save_path=checkpoint_path)\n input_value = constant_op.constant([[3.]])\n def train_fn():\n with backprop.GradientTape() as tape:\n loss = model(input_value)\n variables = model.trainable_variables\n gradients = tape.gradient(loss, variables)\n return optimizer.apply_gradients(zip(gradients, variables))\n if not context.executing_eagerly():\n train_fn = functools.partial(self.evaluate, train_fn())\n status.initialize_or_restore()\n # TODO(tanzheny): Add hyper variables to .variables(), and set them with\n # set_weights etc.\n variables_not_in_the_variables_property = [\n obj for obj in optimizer._hyper.values()\n if isinstance(obj, variables_lib.Variable)]\n self.evaluate([v.initializer for v\n in optimizer.variables()\n + variables_not_in_the_variables_property])\n train_fn()\n model_save_path = root.save(file_prefix=checkpoint_prefix)\n self.evaluate(optimizer.beta_1.assign(42.))\n optimizer_save_path = optimizer_checkpoint.save(optimizer_only_prefix)\n del train_fn\n\n # Restore into a graph with the optimizer\n with test_util.device(use_gpu=True):\n model = MyModel()\n optimizer = adam.Adam(0.001)\n root = trackable_utils.Checkpoint(\n optimizer=optimizer, model=model)\n status = root.restore(save_path=model_save_path)\n input_value = constant_op.constant([[3.]])\n def train_fn1():\n with backprop.GradientTape() as tape:\n loss = model(input_value)\n variables = model.trainable_variables\n gradients = tape.gradient(loss, variables)\n return optimizer.apply_gradients(zip(gradients, variables))\n if not context.executing_eagerly():\n train_fn1 = functools.partial(self.evaluate, train_fn1())\n status.initialize_or_restore()\n train_fn1()\n with self.assertRaises(AssertionError):\n status.assert_existing_objects_matched()\n with self.assertRaises(AssertionError):\n status.assert_consumed()\n del train_fn1\n\n # Make sure initialization doesn't clobber later restores\n with test_util.device(use_gpu=True):\n model = MyModel()\n optimizer = adam.Adam(0.001, beta_1=1.0)\n root = trackable_utils.Checkpoint(\n optimizer=optimizer, model=model)\n opt_root = trackable_utils.Checkpoint(\n optimizer=optimizer)\n status = root.restore(save_path=model_save_path)\n init_only_optimizer_status = opt_root.restore(save_path=None)\n optimizer_status = opt_root.restore(save_path=optimizer_save_path)\n input_value = constant_op.constant([[3.]])\n def train_fn2():\n with backprop.GradientTape() as tape:\n loss = model(input_value)\n variables = model.trainable_variables\n gradients = tape.gradient(loss, variables)\n return optimizer.apply_gradients(zip(gradients, variables))\n if not context.executing_eagerly():\n train_fn2 = functools.partial(self.evaluate, train_fn2())\n optimizer_status.run_restore_ops()\n status.initialize_or_restore()\n init_only_optimizer_status.initialize_or_restore()\n train_fn2()\n self.assertEqual(42., self.evaluate(optimizer.beta_1))\n\n\nclass _ManualScope(tracking.AutoTrackable):\n\n def __call__(self):\n with variable_scope.variable_scope(\"ManualScope\") as vs:\n self.variable_scope = vs\n with trackable_utils.capture_dependencies(template=self):\n return self._build()\n\n def _build(self):\n return variable_scope.get_variable(name=\"in_manual_scope\", shape=[])\n\n\nclass TemplateTests(parameterized.TestCase, test.TestCase):\n\n @test_util.run_in_graph_and_eager_modes\n def test_trackable_save_restore(self):\n\n def _templated():\n v = variable_scope.get_variable(\n \"v\", shape=[1], initializer=init_ops.zeros_initializer(),\n use_resource=True)\n v2 = variable_scope.get_variable(\n \"v2\", shape=[1], initializer=init_ops.zeros_initializer(),\n use_resource=True)\n manual = _ManualScope()\n return v, v + 1., v2, manual, manual()\n\n save_template = template.make_template(\"s1\", _templated)\n v1_save, _, v2_save, manual_scope, manual_scope_v = save_template()\n six.assertCountEqual(\n self,\n [id(v1_save), id(v2_save), id(manual_scope),\n id(manual_scope_v), id(save_template)],\n map(id, trackable_utils.list_objects(save_template)))\n manual_dep, = manual_scope._checkpoint_dependencies\n self.assertEqual(\"in_manual_scope\", manual_dep.name)\n self.assertIs(manual_scope_v, manual_dep.ref)\n optimizer = adam.Adam(0.0)\n save_root = trackable_utils.Checkpoint(\n my_template=save_template, optimizer=optimizer)\n optimizer.minimize(v1_save.read_value,\n var_list=[v1_save])\n self.evaluate([v.initializer for v in save_template.variables])\n optimizer_variables = optimizer.variables() + list(\n optimizer._hyper.values())\n self.evaluate([v.initializer for v in optimizer_variables])\n self.evaluate(v1_save.assign([12.]))\n self.evaluate(v2_save.assign([14.]))\n checkpoint_directory = self.get_temp_dir()\n checkpoint_prefix = os.path.join(checkpoint_directory, \"ckpt\")\n save_path = save_root.save(checkpoint_prefix)\n\n load_template = template.make_template(\"s2\", _templated)\n load_optimizer = adam.Adam(0.0)\n load_root = trackable_utils.Checkpoint(\n my_template=load_template, optimizer=load_optimizer)\n status = load_root.restore(save_path)\n var, var_plus_one, var2, _, _ = load_template()\n load_optimizer.minimize(var.read_value, var_list=[var])\n self.assertLen(load_template._checkpoint_dependencies, 3)\n self.assertEqual(\"v\", load_template._checkpoint_dependencies[0].name)\n self.assertEqual(\"v2\", load_template._checkpoint_dependencies[1].name)\n self.assertEqual(\"ManualScope\",\n load_template._checkpoint_dependencies[2].name)\n status.assert_consumed().run_restore_ops()\n self.assertAllEqual([12.], self.evaluate(var))\n self.assertAllEqual([13.], self.evaluate(var_plus_one))\n self.assertAllEqual([14.], self.evaluate(var2))\n\n\nclass CheckpointCompatibilityTests(test.TestCase):\n\n def _initialized_model(self):\n input_value = constant_op.constant([[3.]])\n model = MyModel()\n optimizer = adam.Adam(0.001)\n root_trackable = trackable_utils.Checkpoint(\n optimizer=optimizer, model=model)\n with backprop.GradientTape() as tape:\n loss = model(input_value)\n variables = model.trainable_variables\n gradients = tape.gradient(loss, variables)\n train_op = optimizer.apply_gradients(zip(gradients, variables))\n self.evaluate(trackable_utils.gather_initializers(\n root_trackable))\n self.evaluate(train_op)\n # A regular variable, a slot variable, and a non-slot Optimizer variable\n # with known values to check when loading.\n self.evaluate(model._named_dense.bias.assign([1.]))\n self.evaluate(optimizer.get_slot(\n var=model._named_dense.bias, slot_name=\"m\").assign([2.]))\n self.evaluate(optimizer.beta_1.assign(3.))\n return root_trackable\n\n def _set_sentinels(self, root_trackable):\n self.evaluate(root_trackable.model._named_dense.bias.assign([101.]))\n self.evaluate(\n root_trackable.optimizer.get_slot(\n var=root_trackable.model._named_dense.bias, slot_name=\"m\")\n .assign([102.]))\n self.evaluate(root_trackable.optimizer.beta_1.assign(103.))\n\n def _check_sentinels(self, root_trackable):\n self.assertAllEqual(\n [1.], self.evaluate(root_trackable.model._named_dense.bias))\n self.assertAllEqual([2.], self.evaluate(\n root_trackable.optimizer.get_slot(\n var=root_trackable.model._named_dense.bias, slot_name=\"m\")))\n self.assertAllEqual(3.,\n self.evaluate(root_trackable.optimizer.beta_1))\n\n def _write_name_based_checkpoint(self):\n checkpoint_directory = self.get_temp_dir()\n checkpoint_prefix = os.path.join(checkpoint_directory, \"ckpt\")\n with context.graph_mode():\n save_graph = ops.Graph()\n with save_graph.as_default(), self.session(\n graph=save_graph) as session:\n root = self._initialized_model()\n name_saver = saver_lib.Saver()\n return name_saver.save(\n sess=session,\n save_path=checkpoint_prefix,\n global_step=root.optimizer.iterations)\n\n @test_util.run_in_graph_and_eager_modes\n def testLoadFromNameBasedSaver(self):\n \"\"\"Save a name-based checkpoint, load it using the object-based API.\"\"\"\n with test_util.device(use_gpu=True):\n save_path = self._write_name_based_checkpoint()\n root = self._initialized_model()\n self._set_sentinels(root)\n with self.assertRaises(AssertionError):\n self._check_sentinels(root)\n object_saver = trackable_utils.TrackableSaver(\n graph_view.ObjectGraphView(root))\n self._set_sentinels(root)\n status = object_saver.restore(save_path)\n if context.executing_eagerly():\n self._check_sentinels(root)\n if context.executing_eagerly():\n status.assert_consumed()\n status.assert_existing_objects_matched()\n status.assert_nontrivial_match()\n else:\n # When graph building, we haven't read any keys, so we don't know\n # whether the restore will be complete.\n with self.assertRaisesRegex(AssertionError, \"not restored\"):\n status.assert_consumed()\n with self.assertRaisesRegex(AssertionError, \"not restored\"):\n status.assert_existing_objects_matched()\n with self.assertRaisesRegex(AssertionError, \"not restored\"):\n status.assert_nontrivial_match()\n status.run_restore_ops()\n self._check_sentinels(root)\n self._set_sentinels(root)\n status = object_saver.restore(save_path)\n status.initialize_or_restore()\n status.assert_nontrivial_match()\n self._check_sentinels(root)\n # Check that there is no error when keys are missing from the name-based\n # checkpoint.\n root.not_in_name_checkpoint = resource_variable_ops.ResourceVariable([1.])\n status = object_saver.restore(save_path)\n with self.assertRaises(AssertionError):\n status.assert_existing_objects_matched()\n\n def testSaveGraphLoadEager(self):\n checkpoint_directory = self.get_temp_dir()\n checkpoint_prefix = os.path.join(checkpoint_directory, \"ckpt\")\n with context.graph_mode():\n save_graph = ops.Graph()\n with save_graph.as_default(), self.session(\n graph=save_graph):\n root = self._initialized_model()\n save_path = root.save(file_prefix=checkpoint_prefix)\n with context.eager_mode():\n root = self._initialized_model()\n self._set_sentinels(root)\n root.restore(save_path).assert_consumed()\n self._check_sentinels(root)\n\n def testSaveEagerLoadGraph(self):\n checkpoint_directory = self.get_temp_dir()\n checkpoint_prefix = os.path.join(checkpoint_directory, \"ckpt\")\n with context.eager_mode():\n root = self._initialized_model()\n save_path = root.save(file_prefix=checkpoint_prefix)\n with context.graph_mode():\n save_graph = ops.Graph()\n with save_graph.as_default(), self.session(\n graph=save_graph):\n root = self._initialized_model()\n self._set_sentinels(root)\n root.restore(save_path).assert_consumed().run_restore_ops()\n self._check_sentinels(root)\n\n def testIgnoreSaveCounter(self):\n checkpoint_directory = self.get_temp_dir()\n checkpoint_prefix = os.path.join(checkpoint_directory, \"ckpt\")\n with self.cached_session() as session:\n # Create and save a model using Saver() before using a Checkpoint. This\n # generates a snapshot without the Checkpoint's `save_counter`.\n model = sequential.Sequential()\n model.add(core.Flatten(input_shape=(1,)))\n model.add(core.Dense(1))\n name_saver = saver_lib.Saver(model.trainable_variables)\n save_path = name_saver.save(\n sess=session, save_path=checkpoint_prefix, global_step=1)\n # Checkpoint.restore must successfully load that checkpoint.\n ckpt = trackable_utils.Checkpoint(model=model)\n status = ckpt.restore(save_path)\n status.assert_existing_objects_matched()\n # It should, however, refuse to load a checkpoint where an unrelated\n # `save_counter` variable is missing.\n model.layers[1].var = variables_lib.Variable(0., name=\"save_counter\")\n status = ckpt.restore(save_path)\n with self.assertRaises(AssertionError):\n status.assert_existing_objects_matched()\n\n\nif __name__ == \"__main__\":\n ops.enable_eager_execution()\n test.main()\n"
] |
[
[
"tensorflow.python.ops.variables.assert_variables_initialized",
"tensorflow.python.framework.tensor_shape.TensorShape",
"tensorflow.python.ops.variables.Variable.SaveSliceInfo",
"tensorflow.python.ops.control_flow_ops.while_loop",
"tensorflow.python.ops.variables.Variable",
"tensorflow.python.ops.variables._try_guard_against_uninitialized_dependencies",
"tensorflow.python.ops.array_ops.zeros",
"tensorflow.python.framework.ops.device",
"tensorflow.python.ops.variables.trainable_variables",
"numpy.negative",
"tensorflow.python.ops.gen_state_ops.variable",
"tensorflow.python.ops.variables.report_uninitialized_variables",
"tensorflow.python.framework.ops.container",
"tensorflow.python.framework.test_util.run_v1_only",
"tensorflow.python.ops.resource_variable_ops.ResourceVariable",
"tensorflow.python.ops.math_ops.less",
"tensorflow.python.ops.math_ops.add",
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.array_ops.ones",
"tensorflow.python.ops.math_ops.matmul",
"tensorflow.python.framework.ops.control_dependencies",
"numpy.zeros",
"tensorflow.python.eager.context.eager_mode",
"tensorflow.python.ops.variables.global_variables",
"tensorflow.python.ops.variables.VariableV1",
"numpy.random.rand",
"tensorflow.python.framework.ops.convert_to_tensor",
"numpy.array",
"tensorflow.python.training.gradient_descent.GradientDescentOptimizer",
"tensorflow.python.ops.variables.PartitionedVariable",
"tensorflow.python.framework.ops.Graph",
"tensorflow.python.util.compat.as_bytes",
"numpy.ones",
"tensorflow.python.framework.test_util.disable_tfrt",
"tensorflow.python.framework.ops.name_scope",
"tensorflow.python.framework.ops.get_default_graph",
"tensorflow.python.ops.variables.global_variables_initializer",
"tensorflow.python.ops.variables.local_variables_initializer",
"tensorflow.python.ops.random_ops.random_uniform",
"tensorflow.python.framework.constant_op.constant"
],
[
"tensorflow.python.framework.tensor_shape.TensorShape",
"tensorflow.python.framework.test_util.run_v1_only",
"numpy.arange",
"tensorflow.python.framework.ops.Graph",
"tensorflow.python.ops.data_flow_ops.PaddingFIFOQueue.from_list",
"tensorflow.python.ops.array_ops.placeholder",
"tensorflow.python.ops.data_flow_ops.QueueBase.from_list",
"tensorflow.python.framework.ops.get_default_graph",
"tensorflow.python.platform.test.main",
"numpy.random.randint",
"tensorflow.python.ops.data_flow_ops.PaddingFIFOQueue",
"numpy.array",
"tensorflow.python.framework.constant_op.constant"
],
[
"tensorflow.python.data.ops.dataset_ops.Dataset.from_tensors",
"tensorflow.python.data.kernel_tests.test_base.default_test_combinations",
"tensorflow.python.ops.control_flow_ops.while_loop",
"tensorflow.python.ops.parsing_ops.parse_single_example",
"tensorflow.python.data.ops.dataset_ops.make_one_shot_iterator",
"tensorflow.python.framework.combinations.NamedObject",
"tensorflow.python.data.ops.dataset_ops.Dataset.range",
"tensorflow.python.ops.array_ops.identity",
"numpy.random.randint",
"tensorflow.python.ops.math_ops.less",
"tensorflow.python.ops.array_ops.unstack",
"tensorflow.python.ops.array_ops.gather",
"tensorflow.python.ops.clip_ops.clip_by_value",
"tensorflow.python.framework.sparse_tensor.SparseTensor",
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.math_ops.add",
"tensorflow.python.ops.math_ops.cast",
"tensorflow.python.ops.parsing_ops.FixedLenFeature",
"tensorflow.python.ops.array_ops.tile",
"tensorflow.python.data.ops.dataset_ops.Dataset.from_tensor_slices",
"tensorflow.python.ops.math_ops.square",
"tensorflow.python.ops.script_ops.py_func",
"tensorflow.python.ops.math_ops.equal",
"tensorflow.python.data.experimental.ops.testing.assert_next",
"numpy.int64",
"numpy.random.rand",
"tensorflow.core.example.feature_pb2.Int64List",
"tensorflow.python.data.experimental.ops.batching.map_and_batch",
"tensorflow.python.framework.combinations.combine",
"tensorflow.python.data.ops.dataset_ops.Options",
"tensorflow.python.ops.array_ops.reshape",
"tensorflow.python.ops.math_ops.zeta",
"tensorflow.python.framework.constant_op.constant"
],
[
"tensorflow.python.keras.engine.sequential.Sequential",
"tensorflow.python.framework.test_util.run_in_graph_and_eager_modes",
"tensorflow.python.training.tracking.util.list_objects",
"tensorflow.python.ops.variables.Variable",
"tensorflow.python.training.checkpoint_management.latest_checkpoint",
"tensorflow.python.eager.backprop.GradientTape",
"tensorflow.python.ops.state_ops.assign",
"tensorflow.python.training.tracking.util.add_variable",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.framework.ops.enable_eager_execution",
"tensorflow.python.training.tracking.util.CheckpointV1",
"tensorflow.python.ops.template.make_template",
"tensorflow.python.framework.test_util.run_v1_only",
"tensorflow.python.ops.resource_variable_ops.ResourceVariable",
"tensorflow.python.training.tracking.util.gather_initializers",
"tensorflow.python.training.tracking.util.capture_dependencies",
"tensorflow.python.training.tracking.graph_view.ObjectGraphView",
"tensorflow.python.training.checkpoint_management.CheckpointManager",
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.variable_scope.variable_scope",
"tensorflow.python.framework.test_util.device",
"tensorflow.python.keras.engine.training.Model",
"tensorflow.python.keras.optimizer_v2.adam.Adam",
"tensorflow.python.eager.context.graph_mode",
"tensorflow.python.eager.context.eager_mode",
"tensorflow.python.keras.engine.input_layer.Input",
"tensorflow.python.training.tracking.util.object_metadata",
"tensorflow.python.keras.layers.core.Flatten",
"tensorflow.python.keras.layers.core.Dense",
"tensorflow.python.training.training_util.get_or_create_global_step",
"tensorflow.python.framework.ops.Graph",
"tensorflow.python.ops.variable_scope.get_variable",
"tensorflow.python.ops.init_ops.zeros_initializer",
"tensorflow.python.framework.ops.get_default_graph",
"tensorflow.python.platform.test.mock.patch.object",
"tensorflow.python.training.tracking.util.Checkpoint",
"tensorflow.python.training.saver.Saver",
"tensorflow.python.framework.constant_op.constant"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"2.7",
"2.4",
"2.3",
"2.9",
"2.5",
"2.6",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"2.7",
"2.6",
"1.13",
"2.3",
"2.4",
"2.9",
"2.5",
"2.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.12",
"2.6",
"1.13",
"2.3",
"2.4",
"2.5",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.2",
"2.3",
"2.4",
"2.9",
"2.5",
"2.8"
]
}
] |
omkarsutar1255/Python-Data
|
[
"169d0c54b23d9dd5a7f1aea41ab385121c3b3c63",
"169d0c54b23d9dd5a7f1aea41ab385121c3b3c63"
] |
[
"Python/Machine Learning/Indian AI Production/Feature Engineering/05-Categorical Missing value imputation.py",
"Python/Deep Learning/Code Basics/7 Neural Network For Handwritten Digits Classification.py"
] |
[
"# todo : Data Cleaning\n# todo : Categorical Missing value imputation Part-5\n\n# todo : Importing library\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# todo : import data\ndf = pd.read_csv(r\"G:\\DataSet\\House Price Prediction\\train.csv\")\n\n# todo : analysis data\ndf.head()\n\n# todo : selecting categorical columns\ncat_vars = df.select_dtypes(include='object')\n\n# todo : analysis of categorical data\ncat_vars.head()\ncat_vars.isnull().sum()\nmiss_val_per = cat_vars.isnull().mean() * 100\nprint(miss_val_per)\n\n# todo : dropping column that has more missing values\ndrop_vars = ['Alley', 'FireplaceQu', 'PoolQC', 'Fence', 'MiscFeature']\ncat_vars.drop(columns=drop_vars, axis=1, inplace=True)\nprint(cat_vars.shape)\n\n# todo : getting column name that has missing values in less amount\nisnull_per = cat_vars.isnull().mean() * 100\nmiss_vars = isnull_per[isnull_per > 0].keys()\nprint(miss_vars)\n\n\ncat_vars['MasVnrType'].fillna('Missing')\n\n# todo : it shows mode value of that column\ncat_vars['MasVnrType'].mode()\n\n# todo : it shows how much which value is present\ncat_vars['MasVnrType'].value_counts()\n\n# todo : filling mode value in missing values of column\ncat_vars['MasVnrType'].fillna(cat_vars['MasVnrType'].mode()[0])\n\n\ncat_vars['MasVnrType'].fillna(cat_vars['MasVnrType'].mode()[0]).value_counts()\n\ncat_vars_copy = cat_vars.copy()\n\n# todo : filling mode values in each categorical column\nfor var in miss_vars:\n cat_vars_copy[var].fillna(cat_vars[var].mode()[0], inplace=True)\n print(var, \"=\", cat_vars[var].mode()[0])\n\n# todo : check how null values are present in data\ncat_vars_copy.isnull().sum().sum()\n\n# todo : checking changes in original dataset after impute mode value in visualize format\nplt.figure(figsize=(16, 9))\nfor i, var in enumerate(miss_vars):\n plt.subplot(4, 3, i + 1)\n plt.hist(cat_vars_copy[var], label=\"Impute\")\n plt.hist(cat_vars[var].dropna(), label=\"Original\")\n plt.legend()\n\n# todo : updating main dataset\ndf.update(cat_vars_copy)\n\n# todo : deleting column from main dataset that has more missing values\ndf.drop(columns=drop_vars, inplace=True)\n\n# todo : checking now which categorical column has null values\ndf.select_dtypes(include='object').isnull().sum()\n",
"# todo: import DataSet\nimport tensorflow as tf\nfrom tensorflow import keras\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# todo: Splitting data into train test\n(X_train, y_train), (X_test, y_test) = keras.datasets.mnist.load_data()\n\n# todo: analysis of data\n# print(len(X_train))\n# print(len(X_test))\n# print(X_train[0].shape)\n# print(X_train[0])\n\n# todo: visualization of data\nplt.matshow(X_train[1])\n# plt.show()\n# print(y_train[:5]) # actual values of data\n\n# todo: feature scaling (converting values between 0-1)\nX_train = X_train/255\nX_test = X_test/255\n\n# todo: Flatten 2D array of train and test data\n# print(X_train.shape)\nX_train_flattened = X_train.reshape(len(X_train), 28*28)\n# print(X_train_Flatten.shape)\n\n# print(X_test.shape)\nX_test_flattened = X_test.reshape(len(X_test), 28*28)\n# print(X_test_flattened.shape)\n# print(X_test_flattened[0]) # all values are flatten in 784\n\n# todo: Creating Neural Network\nmodel = keras.Sequential([\n keras.layers.Dense(10, input_shape=(784,), activation='sigmoid')\n # 10 is output neural network and 784 is input neural network\n])\n\n# todo: optimizing neural network to reduce loss\nmodel.compile(optimizer='adam', # to reach global minima faster\n loss='sparse_categorical_crossentropy', # way to calculate loss\n metrics=['accuracy']) # find accuracy of model regarding given data\n\n# todo: training DL model\nmodel.fit(X_train_flattened, y_train, epochs=5) # epochs is no. of iteration of train model\n\n# todo: prediction of model\nmodel.evaluate(X_test_flattened, y_test)\ny_predicted = model.predict(X_test_flattened)\nprint(y_predicted[0]) # prediction of 0th features of test data\nplt.matshow(X_test[0]) # visualization of 0th feature of test data\nplt.show()\nprint(np.argmax(y_predicted[0])) # predication by model of 0th values of test data\ny_predicted_labels = [np.argmax(i) for i in y_predicted]\nprint(y_predicted_labels[:5])\n\n# todo: creating Confusion matrix\ncm = tf.math.confusion_matrix(labels=y_test, predictions=y_predicted_labels)\nprint(cm)\nimport seaborn as sn\nplt.figure(figsize=(10, 7))\nsn.heatmap(cm, annot=True, fmt='d')\nplt.xlabel('Predicted')\nplt.ylabel('Truth')\nplt.show()\n\n# todo: Creating Neural Network\nmodel = keras.Sequential([\n keras.layers.Dense(100, input_shape=(784,), activation='relu'),\n keras.layers.Dense(10, activation='sigmoid')\n])\n\n# todo: optimizing neural network to reduce loss\nmodel.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\n# todo: training DL model\nmodel.fit(X_train_flattened, y_train, epochs=5)\n\n# todo: prediction of model\nmodel.evaluate(X_test_flattened, y_test)\ny_predicted = model.predict(X_test_flattened)\ny_predicted_labels = [np.argmax(i) for i in y_predicted]\n\n# todo: creating Confusion matrix\ncm = tf.math.confusion_matrix(labels=y_test, predictions=y_predicted_labels)\nplt.figure(figsize=(10, 7))\nsn.heatmap(cm, annot=True, fmt='d')\nplt.xlabel('Predicted')\nplt.ylabel('Truth')\nplt.show()\n\n# todo: Creating Neural Network\nmodel = keras.Sequential([\n keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(100, activation='relu'),\n keras.layers.Dense(10, activation='sigmoid')\n])\n\n# todo: optimizing neural network to reduce loss\nmodel.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\n# todo: training DL model\nmodel.fit(X_train, y_train, epochs=10)\nmodel.evaluate(X_test, y_test)\n"
] |
[
[
"matplotlib.pyplot.legend",
"pandas.read_csv",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.figure"
],
[
"tensorflow.keras.layers.Dense",
"tensorflow.keras.datasets.mnist.load_data",
"matplotlib.pyplot.ylabel",
"numpy.argmax",
"matplotlib.pyplot.xlabel",
"tensorflow.math.confusion_matrix",
"matplotlib.pyplot.matshow",
"matplotlib.pyplot.show",
"tensorflow.keras.layers.Flatten",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
billhhh/model-quantization-1
|
[
"e816c3ffd36426810e31de04dfdec1894a600c2d"
] |
[
"tools.py"
] |
[
"import os, sys, glob, argparse\nimport logging\nimport types\nfrom collections import OrderedDict\n\nimport torch\nimport torch.nn.functional as F\n\nimport utils\nimport models\nimport main as entry\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\n\ndef export_onnx(args):\n model_name = args.model\n if model_name in models.model_zoo:\n model, args = models.get_model(args)\n else:\n print(\"model(%s) not support, available models: %r\" % (model_name, models.model_zoo))\n return\n\n if utils.check_file(args.old):\n print(\"load pretrained from %s\" % args.old)\n if torch.cuda.is_available():\n checkpoint = torch.load(args.old)\n else: # force cpu mode\n checkpoint = torch.load(args.old, map_location='cpu')\n print(\"load pretrained ==> last epoch: %d\" % checkpoint.get('epoch', 0))\n print(\"load pretrained ==> last best_acc: %f\" % checkpoint.get('best_acc', 0))\n print(\"load pretrained ==> last learning_rate: %f\" % checkpoint.get('learning_rate', 0))\n try:\n utils.load_state_dict(model, checkpoint.get('state_dict', None))\n except RuntimeError:\n print(\"Loading pretrained model failed\")\n else:\n print(\"no pretrained file exists({}), init model with default initlizer\".\n format(args.old))\n\n onnx_model = torch.nn.Sequential(OrderedDict([\n ('network', model),\n ('softmax', torch.nn.Softmax()),\n ]))\n\n onnx_path = \"onnx/\" + model_name\n if not os.path.exists(onnx_path):\n os.makedirs(onnx_path)\n onnx_save = onnx_path + \"/\" + model_name + '.onnx'\n\n input_names = [\"input\"]\n dummy_input = torch.zeros((1, 3, args.input_size, args.input_size))\n output_names = ['prob']\n torch.onnx.export(\n onnx_model,\n dummy_input,\n onnx_save,\n verbose=True,\n input_names=input_names,\n output_names=output_names,\n opset_version=7,\n keep_initializers_as_inputs=True\n )\n\ndef inference(args):\n from models.quant import custom_conv\n def init(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=False,\n args=None, force_fp=False, feature_stride=1):\n super(custom_conv, self).__init__(in_channels, out_channels, kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias)\n self.args = args\n self.force_fp = True\n\n custom_conv.__init__ = init\n\n model_name = args.model\n if model_name in models.model_zoo:\n model, args = models.get_model(args)\n else:\n print(\"model(%s) not support, available models: %r\" % (model_name, models.model_zoo))\n return\n\n def forward(self, x):\n print(x.shape, self.weight.shape, self.kernel_size, self.stride, self.padding, self.dilation, self.groups)\n output = F.conv2d(x, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups)\n return output\n\n for m in model.modules():\n if isinstance(m, torch.nn.Conv2d):\n m.forward = types.MethodType(forward, m)\n\n input = torch.rand(1, 3, args.input_size, args.input_size)\n model.forward(input)\n\ndef get_parameter():\n parser = entry.get_parser()\n parser.add_argument('--old', type=str, default='')\n parser.add_argument('--new', type=str, default='')\n parser.add_argument('--mapping_from', '--mf', type=str, default='')\n parser.add_argument('--mapping_to', '--mt', type=str, default='')\n parser.add_argument('--verbose_list', default='ratio,sep', type=str)\n args = parser.parse_args()\n if isinstance(args.verbose_list, str):\n args.verbose_list = [x.strip() for x in args.verbose_list.split(',')]\n if isinstance(args.keyword, str):\n args.keyword = [x.strip() for x in args.keyword.split(',')]\n return args\n\ndef main():\n args = get_parameter()\n args.weights_dir = os.path.join(args.weights_dir, args.model)\n utils.check_folder(args.weights_dir)\n\n if os.path.exists(args.log_dir):\n utils.setup_logging(os.path.join(args.log_dir, 'tools.txt'), resume=True)\n\n config = dict()\n for i in args.keyword:\n config[i] = True\n\n if 'export_onnx' in config.keys():\n export_onnx(args)\n\n if 'inference' in config.keys():\n inference(args)\n\n if 'verbose' in config.keys():\n if torch.cuda.is_available():\n checkpoint = torch.load(args.old)\n else: # force cpu mode\n checkpoint = torch.load(args.old, map_location='cpu')\n if 'state_dict' in checkpoint:\n checkpoint = checkpoint['state_dict']\n if 'model' in checkpoint:\n checkpoint = checkpoint['model']\n for name, value in checkpoint.items():\n if ('quant_activation' in name or 'quant_weight' in name) and name.split('.')[-1] in args.verbose_list:\n print(name, value.shape, value.requires_grad)\n print(value.data)\n elif \"all\" in args.verbose_list:\n if 'num_batches_tracked' not in name:\n if isinstance(value, torch.Tensor):\n print(name, value.shape, value.requires_grad)\n elif isinstance(value, int) or isinstance(value, float) or isinstance(value, str):\n print(name, value, type(value))\n else:\n print(name, type(value))\n\n if 'load' in config.keys() or 'save' in config.keys():\n model_name = args.model\n if model_name in models.model_zoo:\n model, args = models.get_model(args)\n else:\n print(\"model(%s) not support, available models: %r\" % (model_name, models.model_zoo))\n return\n if utils.check_file(args.old):\n raw = 'raw' in config.keys()\n if torch.cuda.is_available():\n checkpoint = torch.load(args.old)\n else: # force cpu mode\n checkpoint = torch.load(args.old, map_location='cpu')\n try:\n utils.load_state_dict(model, checkpoint.get('state_dict', None) if not raw else checkpoint, verbose=False)\n except RuntimeError:\n print(\"Loading pretrained model failed\")\n print(\"Loading pretrained model OK\")\n\n if 'save' in config.keys() and args.new != '':\n torch.save(model.state_dict(), args.new)\n print(\"Save pretrained model into %s\" % args.new)\n else:\n print(\"file not exist %s\" % args.old)\n\n if 'update' in config.keys():\n mapping_from = []\n mapping_to = []\n if os.path.isfile(args.mapping_from):\n with open(args.mapping_from) as f:\n mapping_from = f.readlines()\n f.close()\n if os.path.isfile(args.mapping_to):\n with open(args.mapping_to) as f:\n mapping_to = f.readlines()\n f.close()\n mapping_from = [ i.strip().strip('\\n').strip('\"').strip(\"'\") for i in mapping_from]\n mapping_from = [ i for i in mapping_from if len(i) > 0 and i[0] != '#'] \n mapping_to = [ i.strip().strip('\\n').strip('\"').strip(\"'\") for i in mapping_to]\n mapping_to = [ i for i in mapping_to if len(i) > 0 and i[0] != '#']\n if len(mapping_to) != len(mapping_from) or len(mapping_to) == 0 or len(mapping_from) == 0:\n mapping = None\n logging.info('no valid mapping')\n else:\n mapping = dict()\n for i, k in enumerate(mapping_from):\n if '{' in k and '}' in k and '{' in mapping_to[i] and '}' in mapping_to[i]:\n item = k.split('{')\n for v in item[1].strip('}').split(\",\"):\n v = v.strip()\n mapping[item[0] + v] = mapping_to[i].split('{')[0] + v\n else:\n mapping[k] = mapping_to[i] \n\n raw = 'raw' in config.keys()\n if not os.path.isfile(args.old):\n args.old = args.pretrained\n utils.import_state_dict(args.old, args.new, mapping, raw, raw_prefix=args.case)\n\n if 'det-load' in config.keys():\n from third_party.checkpoint import DetectionCheckpointer\n model_name = args.model\n if model_name in models.model_zoo:\n model, args = models.get_model(args)\n else:\n print(\"model(%s) not support, available models: %r\" % (model_name, models.model_zoo))\n return\n split = os.path.split(args.old)\n checkpointer = DetectionCheckpointer(model, split[0], save_to_disk=True)\n checkpointer.resume_or_load(args.old, resume=True)\n checkpointer.save(split[1])\n\n if 'swap' in config.keys():\n mapping_from = []\n if os.path.isfile(args.mapping_from):\n with open(args.mapping_from) as f:\n mapping_from = f.readlines()\n f.close()\n mapping_from = [ i.strip().strip('\\n').strip('\"').strip(\"'\") for i in mapping_from]\n mapping_from = [ i for i in mapping_from if len(i) > 0 and i[0] != '#']\n lists = args.verbose_list\n for i in lists:\n item = i.split('/')\n interval = (int)(item[0])\n index = item[1].split('-')\n index = [(int)(x) for x in index]\n if len(mapping_from) % interval == 0 and len(index) <= interval:\n mapping_to = mapping_from.copy()\n for j, k in enumerate(index):\n k = k % interval\n mapping_to[j::interval] = mapping_from[k::interval]\n\n mapping_to= [ i + '\\n' for i in mapping_to]\n with open(args.mapping_from + \"-swap\", 'w') as f:\n f.writelines(mapping_to)\n f.close()\n\n if 'sort' in config.keys():\n mapping_from = []\n if os.path.isfile(args.mapping_from):\n with open(args.mapping_from) as f:\n mapping_from = f.readlines()\n f.close()\n mapping_from.sort()\n with open(args.mapping_from + \"-sort\", 'w') as f:\n f.writelines(mapping_from)\n f.close()\n\n if 'verify-data' in config.keys() or 'verify-image' in config.keys():\n if 'verify-image' in config.keys():\n lists = args.verbose_list\n else:\n with open(os.path.join(args.root, 'train.txt')) as f:\n lists = f.readlines()\n f.close()\n from PIL import Image\n from threading import Thread\n print(\"going to check %d files\" % len(lists))\n def check(lists, start, end, index):\n for i, item in enumerate(lists[start:end]):\n try:\n items = item.split()\n if len(items) >= 1:\n path = items[0].strip().strip('\\n')\n else:\n print(\"skip line %s\" % i)\n continue\n path = os.path.join(args.root, os.path.join(\"train\", path))\n imgs = Image.open(path)\n imgs.resize((256,256))\n if index == 0:\n print(i, end =\"\\r\", file=sys.stderr)\n except (RuntimeError, IOError):\n print(\"\\nError when read image %s\" % path)\n print(\"\\nFinish checking\", index)\n #lists = lists[45000:]\n num = min(len(lists), 20)\n for i in range(num):\n start = len(lists) // num * i\n end = min(start + len(lists) // num, len(lists))\n th = Thread(target=check, args=(lists, start, end, i))\n th.start()\n\nif __name__ == '__main__':\n main()\n\n"
] |
[
[
"torch.nn.Softmax",
"torch.onnx.export",
"torch.zeros",
"torch.load",
"torch.nn.functional.conv2d",
"torch.rand",
"torch.cuda.is_available"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
narendasan/neural-mmo
|
[
"36a588db0021cccd7275cebef2cbdc5ee8eb40d5",
"36a588db0021cccd7275cebef2cbdc5ee8eb40d5",
"36a588db0021cccd7275cebef2cbdc5ee8eb40d5"
] |
[
"evolution/diversity.py",
"forge/blade/io/stimulus/node.py",
"pcgrl/game/core/tile.py"
] |
[
"from pdb import set_trace as TT\nimport numpy as np\nimport scipy\nfrom scipy.spatial import ConvexHull\nimport skimage\nfrom skimage.morphology import disk\nimport skbio\n\nglobal trg_image\ntrg_image = None\n\ndef diversity_calc(config):\n div_calc_name = config.FITNESS_METRIC\n return get_div_calc(div_calc_name)\n\ndef get_div_calc(div_calc_name):\n if div_calc_name == 'L2':\n calc_diversity = calc_diversity_l2\n elif div_calc_name == 'InvL2':\n calc_diversity = calc_homogeneity_l2\n elif div_calc_name == 'Differential':\n calc_diversity = calc_differential_entropy\n elif div_calc_name == 'Discrete':\n calc_diversity = calc_discrete_entropy_2\n elif div_calc_name == 'Hull':\n calc_diversity = calc_convex_hull\n elif div_calc_name == 'Sum':\n calc_diversity = sum_experience\n elif div_calc_name == 'Lifespans': # or config.FITNESS_METRIC == 'ALP':\n calc_diversity = sum_lifespans\n elif div_calc_name == 'Lifetimes':\n calc_diversity = calc_mean_lifetime\n elif div_calc_name == 'Actions':\n calc_diversity = calc_mean_actions_matched\n elif div_calc_name == 'MapTest':\n calc_diversity = calc_local_map_entropy\n elif div_calc_name == 'MapTestText':\n calc_diversity = ham_text\n get_trg_image()\n elif div_calc_name == 'y_deltas':\n calc_diversity = calc_y_deltas\n elif div_calc_name == 'Scores' or config.FITNESS_METRIC == 'ALP':\n calc_diversity = calc_scores\n else:\n raise Exception('Unsupported fitness function: {}'.format(config.FITNESS_METRIC))\n return calc_diversity\n\ndef get_trg_image():\n from PIL import Image, ImageDraw, ImageFont\n font_size = 15\n try:\n font = ImageFont.truetype(\"arial.ttf\", font_size)\n except OSError:\n try:\n font = ImageFont.truetype(\"LiberationMono-Regular.ttf\", font_size)\n except OSError:\n font = ImageFont.truetype(\"SFNSMono.ttf\", 32)\n global trg_image\n trg_image = Image.new(mode = \"RGB\", size=(50, 50))\n draw = ImageDraw.Draw(trg_image)\n draw.text((1,1), \"Evo\", font=font, fill=(255,0,0))\n draw.text((1,15), \"NMMO\", font=font, fill=(255,0,0))\n draw.text((1,32), \"¯\\_(ツ)_/¯\", font=font, fill=(255,0,0))\n trg_image.save(\"trg_img.png\")\n trg_image = (np.array(trg_image)[:, :, 0] / 255 * 8).astype(np.uint8)\n\ndef ham_text(individual, config):\n if trg_image is None:\n get_trg_image()\n map_arr = individual.chromosome.map_arr[10:-10, 10:-10]\n return -(trg_image != map_arr).sum()\n\ndef calc_map_entropies(individual, config, verbose=False):\n glob_ent = calc_global_map_entropy(individual, config)\n loc_ent = calc_local_map_entropy(individual, config)\n if verbose:\n print('global entropy: {}\\nlocal entropy: {}'.format(glob_ent, loc_ent))\n\n return [glob_ent[0], loc_ent]\n\ndef calc_global_map_entropy(individual, config):\n # FIXME: hack to ignore lava borders\n b = config.TERRAIN_BORDER\n map_arr = individual.chromosome.map_arr[b:-b, b:-b]\n ent = scipy.stats.entropy(np.bincount(map_arr.reshape(-1), minlength=individual.n_tiles))\n ent = ent * 100 / np.log(individual.n_tiles)\n\n return [ent]\n\ndef calc_local_map_entropy(individual, config):\n # FIXME: hack to ignore lava borders\n b = config.TERRAIN_BORDER\n map_arr = individual.chromosome.map_arr[b:-b, b:-b]\n local_ent = skimage.filters.rank.entropy(map_arr, disk(3))\n local_ent = local_ent.mean() * 100 / np.log2(individual.n_tiles)\n\n return local_ent.item()\n\ndef get_pop_stats(agent_stats, pop=None):\n # Get list of all populations for which we need stats\n pops = agent_stats[0].keys() if pop is None else [pop]\n # Get 1D array of agent stats\n stats = [stats_i[p] for p in pops for stats_i in agent_stats]\n if len(stats[0].shape) == 2:\n # then rows correspond to agents so we stack them vertically (concatenate along axis 1)\n return np.vstack(stats)\n elif len(stats[0].shape) == 1:\n # then each agent has a scalar value so we concatenate along axis 0\n return np.hstack(stats)\n raise Exception(\"Oy! Dafuk type o' agent data is this?\")\n\ndef contract_by_lifespan(agent_stats, lifespans):\n '''Pull agents close to their mean according to how short-lived they were. For punishing abundance of premature death\n when rewarding diversity.'''\n weights = sigmoid_lifespan(lifespans)\n n_agents = lifespans.shape[0]\n mean_agent = agent_stats.mean(axis=0)\n mean_agents = np.repeat(mean_agent.reshape(1, mean_agent.shape[0]), n_agents, axis=0)\n agent_deltas = mean_agents - agent_stats\n agent_skills = agent_stats + (weights * agent_deltas.T).T\n\n return agent_skills\n\ndef expand_by_lifespan(agent_stats, lifespans):\n '''Push agents further from their mean according to how short-lived they were. For punishing abundance of premature\n death when rewarding homogeneity.'''\n weights = sigmoid_lifespan(lifespans)\n n_agents = lifespans.shape[0]\n mean_agent = agent_stats.mean(axis=0)\n mean_agents = np.repeat(mean_agent.reshape(1, mean_agent.shape[0]), n_agents, axis=0)\n agent_deltas = mean_agents - agent_stats\n # Displace agents by at most 100 units (otherwise we will not punish agents at all if they are already perfectly\n # homogenous, for example.\n agent_deltas = agent_deltas / np.linalg.norm(agent_deltas) * 100\n agent_skills = agent_stats - (weights * agent_deltas.T).T\n\n return agent_skills\n\ndef calc_scores(agent_stats, skill_headers=None, verbose=False):\n scores = np.hstack(agent_stats['scores'])\n if verbose:\n print('scores: {}'.format(scores))\n return np.mean(scores)\n\ndef calc_mean_actions_matched(agent_stats, skill_headers=None, verbose=False):\n actions_matched = np.hstack(agent_stats['actions_matched'])\n if verbose:\n print(actions_matched)\n# print(agent_stats['lifespans'])\n return np.mean(actions_matched)\n\ndef calc_y_deltas(agent_stats, skill_headers=None, verbose=False):\n y_deltas = np.hstack(agent_stats['y_deltas'])\n if verbose:\n print('y_deltas: {}'.format(y_deltas))\n return np.mean(y_deltas)\n\ndef calc_mean_lifetime(agent_stats, skill_headers=None, verbose=False, pop=None):\n lifetimes = get_pop_stats(agent_stats['lifespans'], pop)\n if len(lifetimes) != 0:\n lifetimes = np.hstack(lifetimes)\n else:\n lifetimes = [0]\n mean_lifetime = lifetimes.mean()\n\n return mean_lifetime\n\ndef sum_lifespans(agent_stats, skill_headers=None, n_policies=1, verbose=False, pop=None):\n lifespans = get_pop_stats(agent_stats['lifespans'], pop=pop)\n score = lifespans.mean()\n if verbose:\n print('Mean lifespan, pop {}: {}'.format(pop, score))\n\n return score\n\ndef sum_experience(agent_stats, skill_headers=None, verbose=False, pop=None):\n '''Simply take the sum of XP over skills and agents.'''\n # No need to weight by lifespan, since high lifespan is a prerequisite for high XP.\n agent_skills = get_pop_stats(agent_stats['skills'], pop)\n lifespans = get_pop_stats(agent_stats['lifespans'], pop)\n a_skills = np.vstack(agent_skills)\n a_lifespans = np.hstack(lifespans)\n n_agents, n_skills = a_skills.shape\n mean_xp = a_skills.sum() / (n_agents * n_skills)\n\n if verbose:\n print('skills')\n print(a_skills.T)\n print('lifespans')\n print(a_lifespans)\n print('mean xp:', mean_xp)\n print()\n\n return mean_xp\n\ndef sigmoid_lifespan(x):\n # This basically assumes max lifespan is at least 100. Larger max lifespans won't really be a problem since this\n # function converges to 1.\n res = 1 / (1 + np.exp(0.1*(-x+50)))\n\n return res\n\ndef calc_differential_entropy(agent_stats, skill_headers=None, verbose=False, infos={}, pop=None, punish_youth=True):\n agent_skills = get_pop_stats(agent_stats['skills'], pop)\n lifespans = get_pop_stats(agent_stats['lifespans'], pop)\n\n a_skills = agent_skills\n a_lifespans = lifespans\n assert a_skills.shape[0] == a_lifespans.shape[0]\n\n if verbose:\n print(skill_headers)\n print(a_skills.transpose())\n print(len(agent_skills), 'populations')\n print('lifespans')\n print(a_lifespans)\n\n if punish_youth:\n # Below is an alternative way of weighting by lifespan\n # weights = sigmoid_lifespan(a_lifespans)\n # mean = np.average(a_skills, axis=0, weights=weights)\n # cov = np.cov(a_skills,rowvar=0, aweights=weights)\n\n # Instead, we'll just contract as usual\n a_skills = contract_by_lifespan(a_skills, a_lifespans)\n mean = np.average(a_skills, axis=0)\n cov = np.cov(a_skills,rowvar=0)\n gaussian = scipy.stats.multivariate_normal(mean=mean, cov=cov, allow_singular=True)\n infos['gaussian'] = gaussian\n score = gaussian.entropy()\n\n if verbose:\n print('score:', score)\n\n return score\n\n\ndef calc_convex_hull(agent_stats, skill_headers=None, verbose=False, infos={}, pop=None, punish_youth=True):\n '''Calculate the diversity of a population of agents in skill-space by computing the volume inside the convex hull of\n the agents when treated as points in this space.'''\n agent_skills = get_pop_stats(agent_stats['skills'], pop)\n lifespans = get_pop_stats(agent_stats['lifespans'], pop)\n agent_skills = np.vstack(agent_skills)\n n_skills = agent_skills.shape[1]\n\n lifespans = np.hstack(lifespans)\n if verbose:\n print('skills:')\n print(agent_skills.transpose())\n print('lifespans:')\n print(lifespans)\n print(len(agent_stats['lifespans']), 'populations')\n if punish_youth:\n agent_skills = contract_by_lifespan(agent_skills, lifespans)\n if n_skills == 1:\n # Max distance, i.e. a 1D hull\n score = agent_skills.max() - agent_skills.mean()\n else:\n try:\n hull = ConvexHull(agent_skills, qhull_options='QJ')\n infos['hull'] = hull\n score = hull.volume\n score = score ** (1 / n_skills)\n except Exception as e:\n print(e)\n score = 0\n if verbose:\n print('score:', score)\n\n return score\n\ndef calc_discrete_entropy_2(agent_stats, skill_headers=None, verbose=False, pop=None, punish_youth=True):\n agent_skills = get_pop_stats(agent_stats['skills'], pop)\n lifespans = get_pop_stats(agent_stats['lifespans'], pop)\n agent_skills_0 = agent_skills= np.vstack(agent_skills)\n lifespans = np.hstack(lifespans)\n n_agents = lifespans.shape[0]\n if n_agents == 1:\n return -np.float('inf')\n n_skills = agent_skills.shape[1]\n if verbose:\n print('skills')\n print(agent_skills_0.transpose())\n print('lifespans')\n print(lifespans)\n agent_skills = np.where(agent_skills == 0, 0.0000001, agent_skills)\n if punish_youth:\n # Below is a v funky way of punishing by lifespan\n # weights = sigmoid_lifespan(lifespans)\n # # contract population toward mean according to lifespan\n # # mean experience level for each agent\n # mean_skill = agent_skills.mean(axis=1)\n # # mean skill vector of an agent\n # mean_agent = agent_skills.mean(axis=0)\n # assert mean_skill.shape[0] == n_agents\n # assert mean_agent.shape[0] == n_skills\n # mean_skills = np.repeat(mean_skill.reshape(mean_skill.shape[0], 1), n_skills, axis=1)\n # mean_agents = np.repeat(mean_agent.reshape(1, mean_agent.shape[0]), n_agents, axis=0)\n # agent_deltas = agent_skills - mean_agents\n # skill_deltas = agent_skills - mean_skills\n # a_skills_skills = mean_agents + (weights * agent_deltas.transpose()).transpose()\n # a_skills_agents = mean_skills + (weights * skill_deltas.transpose()).transpose()\n # div_agents = skbio.diversity.alpha_diversity('shannon', a_skills_agents).mean()\n # div_skills = skbio.diversity.alpha_diversity('shannon', a_skills_skills.transpose()).mean()\n\n # We'll just do the usual\n a_skills = contract_by_lifespan(agent_skills, lifespans)\n div_agents = skbio.diversity.alpha_diversity('shannon', a_skills).mean()\n div_skills = skbio.diversity.alpha_diversity('shannon', a_skills.transpose()).mean()\n\n # div_lifespans = skbio.diversity.alpha_diversity('shannon', lifespans)\n score = -(div_agents * div_skills)#/ div_lifespans#/ len(agent_skills)**2\n score = score#* 100 #/ (n_agents * n_skills)\n if verbose:\n print('Score:', score)\n\n return score\n\n\ndef calc_discrete_entropy(agent_stats, skill_headers=None, pop=None):\n agent_skills = get_pop_stats(agent_stats['skills'], pop)\n lifespans = get_pop_stats(agent_stats['lifespans'], pop)\n agent_skills_0 = np.vstack(agent_skills)\n agent_lifespans = np.hstack(lifespans)\n weights = sigmoid_lifespan(agent_lifespans)\n agent_skills = agent_skills_0.transpose() * weights\n agent_skills = agent_skills.transpose()\n BASE_VAL = 0.0001\n # split between skill and agent entropy\n n_skills = len(agent_skills[0])\n n_pop = len(agent_skills)\n agent_sums = [sum(skills) for skills in agent_skills]\n i = 0\n\n # ensure that we will not be dividing by zero when computing probabilities\n\n for a in agent_sums:\n if a == 0:\n agent_sums[i] = BASE_VAL * n_skills\n i += 1\n skill_sums = [0 for i in range(n_skills)]\n\n for i in range(n_skills):\n\n for a_skills in agent_skills:\n skill_sums[i] += a_skills[i]\n\n if skill_sums[i] == 0:\n skill_sums[i] = BASE_VAL * n_pop\n\n skill_ents = []\n\n for i in range(n_skills):\n skill_ent = 0\n\n for j in range(n_pop):\n\n a_skill = agent_skills[j][i]\n\n if a_skill == 0:\n a_skill = BASE_VAL\n p = a_skill / skill_sums[i]\n\n if p == 0:\n skill_ent += 0\n else:\n skill_ent += p * np.log(p)\n skill_ent = skill_ent / (n_pop)\n skill_ents.append(skill_ent)\n\n agent_ents = []\n\n for j in range(n_pop):\n agent_ent = 0\n\n for i in range(n_skills):\n\n a_skill = agent_skills[j][i]\n\n if a_skill == 0:\n a_skill = BASE_VAL\n p = a_skill / agent_sums[j]\n\n if p == 0:\n agent_ent += 0\n else:\n agent_ent += p * np.log(p)\n agent_ent = agent_ent / (n_skills)\n agent_ents.append(agent_ent)\n agent_score = np.mean(agent_ents)\n skill_score = np.mean(skill_ents)\n# score = (alpha * skill_score + (1 - alpha) * agent_score)\n score = -(skill_score * agent_score)\n score = score * 100#/ n_pop**2\n print('agent skills:\\n{}\\n{}'.format(skill_headers, np.array(agent_skills_0.transpose())))\n print('lifespans:\\n{}'.format(lifespans))\n# print('skill_ents:\\n{}\\nskill_mean:\\n{}\\nagent_ents:\\n{}\\nagent_mean:{}\\nscore:\\n{}\\n'.format(\n# np.array(skill_ents), skill_score, np.array(agent_ents), agent_score, score))\n print('score:\\n{}'.format(score))\n\n return score\n\ndef calc_homogeneity_l2(agent_stats, skill_headers=None, verbose=False, pop=None, punish_youth=True):\n '''Use L2 distance to punish agents for having high mean pairwise distance. Optimal state is all agents at the same\n point in skill-space, with maximal lifespans.'''\n if 'skills' not in agent_stats:\n raise Exception('We should be including dead agents in this calculation, so we should get at least some skill '\n 'stats back here')\n agent_skills = get_pop_stats(agent_stats['skills'], pop)\n lifespans = get_pop_stats(agent_stats['lifespans'], pop)\n assert len(agent_skills) == len(lifespans)\n if punish_youth:\n agent_skills = expand_by_lifespan(agent_skills, lifespans)\n n_agents = agent_skills.shape[0]\n a = agent_skills\n b = a.reshape(n_agents, 1, a.shape[1])\n # https://stackoverflow.com/questions/43367001/how-to-calculate-euclidean-distance-between-pair-of-rows-of-a-numpy-array\n distances = np.sqrt(np.einsum('ijk, ijk->ij', a - b, a - b))\n score = np.sum(distances) / n_agents ** 2\n\n if verbose:\n # print(skill_headers)\n print('agent skills:\\n{}'.format(a.transpose()))\n print('lifespans:\\n{}'.format(lifespans))\n print('score:\\n{}\\n'.format(\n score))\n\n return -score\n\n\ndef calc_diversity_l2(agent_stats, skill_headers=None, verbose=False, pop=None, punish_youth=False):\n if 'skills' not in agent_stats:\n return 0\n agent_skills = get_pop_stats(agent_stats['skills'], pop)\n lifespans = get_pop_stats(agent_stats['lifespans'], pop)\n assert len(agent_skills) == len(lifespans)\n if punish_youth:\n agent_skills = contract_by_lifespan(agent_skills, lifespans)\n n_agents = agent_skills.shape[0]\n a = agent_skills\n b = a.reshape(n_agents, 1, a.shape[1])\n # https://stackoverflow.com/questions/43367001/how-to-calculate-euclidean-distance-between-pair-of-rows-of-a-numpy-array\n distances = np.sqrt(np.einsum('ijk, ijk->ij', a-b, a-b))\n score = np.sum(distances) / n_agents ** 2\n\n if verbose:\n# print(skill_headers)\n print('agent skills:\\n{}'.format(a.transpose()))\n print('lifespans:\\n{}'.format(lifespans))\n print('score:\\n{}\\n'.format(\n score))\n\n return score\n\nDIV_CALCS = [(calc_diversity_l2, 'mean pairwise L2'), (calc_differential_entropy, 'differential entropy'), (calc_discrete_entropy_2, 'discrete entropy'), (calc_convex_hull, 'convex hull volume'), (sum_lifespans, 'lifespans')]\n",
"from pdb import set_trace as TT\nimport numpy as np\nimport gym\n\nfrom forge.blade.lib.utils import classproperty\nfrom forge.blade.io.comparable import IterableTypeCompare\n\nclass Flat:\n pass\n\nclass Stim(metaclass=IterableTypeCompare):\n default = 0\n max = np.inf\n min = 0\n\n def __init__(self, config):\n cls = self.__class__\n self.min = cls.min\n self.max = cls.max\n self.default = cls.default\n\n self.init(config)\n self._val = self.default\n\n def init(self, config):\n pass\n\n @classproperty\n def name(self):\n name = self.__name__\n return name[0].lower() + name[1:]\n\n @property\n def val(self):\n if self._val is None:\n return 0\n return self._val\n\n def asserts(self, val):\n if val is not None:\n #assert val >= self.min and val <= self.max, str(self) + ': ' + str(val)\n pass\n return val\n \n def update(self, val):\n self._val = val\n return self #for convenience\n\n def packet(self):\n return {\n 'val': self.val, \n 'max': self.max if self.max != float('inf') else None}\n\n def get(self, *args):\n return self.asserts(self.val)\n\n @property\n def missing(self):\n return self.max - self.val\n\n def increment(self, amt=1):\n self._val = min(self.max, self.val + amt)\n\n def decrement(self, amt=1):\n self._val = max(0, self.val - amt)\n\n def __add__(self, other):\n self.increment(other)\n return self\n\n def __sub__(self, other):\n self.decrement(other)\n return self\n\n def __lt__(self, other):\n return self.val < other\n\n def __le__(self, other):\n return self.val <= other\n\n def __gt__(self, other):\n return self.val > other\n\n def __ge__(self, other):\n return self.val >= other\n\nclass Discrete(Stim):\n def __init__(self, config):\n super().__init__(config) \n self.space = gym.spaces.Box(\n low=np.float32(0.0),\n high=np.float32(self.range),\n shape=(1,))\n\n @property\n def range(self):\n return self.max - self.min + 1\n\n def oneHot(self):\n ary = np.zeros(self.range)\n ary[self.norm()] = 1\n return ary\n\n def norm(self):\n val = self.val# - self.min\n assert val == int(val)\n return int(val)\n\n def get(self, *args):\n self.asserts(self.val)\n return np.array([self.norm()])\n return self.norm()\n\n #No norm needed for discrete vars. Below is for\n #current hack where RLlib treats everything as continuous\n #The default preprocessor won't norm, so we can still embed\n return self.norm()\n\nclass Continuous(Stim):\n def __init__(self, config):\n super().__init__(config) \n self.space = gym.spaces.Box(\n low=np.float32(-1.0),\n high=np.float32(1.0),\n shape=(1,))\n\n @property\n def range(self):\n return self.max - self.min\n\n def norm(self):\n assert self.val >= self.min and self.val <= self.max\n val = self.val - self.min\n if self.range == np.inf:\n val = self.scaled(val)\n else:\n val = 2*(val / self.range) - 1\n assert val >= -1 and val <= 1, self\n return val\n\n def scaled(self, val):\n return self.scale * val\n\n def get(self, *args):\n self.asserts(self.val)\n val = self.norm()\n return np.array([val])\n\n",
"from pdb import set_trace as T\nimport numpy as np\n\nfrom forge.blade.io.stimulus.hook import StimHook\nfrom forge.blade.io.stimulus.static import Stimulus\n\ndef camel(string):\n return string[0].lower() + string[1:]\n\nclass Tile(StimHook):\n SERIAL = 1\n def __init__(self, config, mat, r, c, nCounts, tex):\n super().__init__(Stimulus.Tile, config)\n self.r, self.c = r, c\n self.mat = mat()\n self.ents = {}\n self.state = mat()\n self.capacity = self.mat.capacity\n self.tex = tex\n self.terraformable = True\n\n self.counts = [0 for _ in range(config.NPOP)]\n\n @property\n def serial(self):\n return self.r, self.c\n\n def addEnt(self, entID, ent):\n assert entID not in self.ents\n self.ents[entID] = ent\n\n def delEnt(self, entID):\n assert entID in self.ents\n del self.ents[entID]\n\n def step(self):\n if (not self.static and \n np.random.rand() < self.mat.respawnProb):\n self.capacity += 1\n\n #Try inserting a pass\n if self.static:\n self.state = self.mat\n\n @property\n def static(self):\n assert self.capacity <= self.mat.capacity\n return self.capacity == self.mat.capacity\n\n def harvest(self):\n if self.capacity == 0:\n return False\n elif self.capacity <= 1:\n self.state = self.mat.degen()\n self.capacity -= 1\n return True\n return self.mat.dropTable.roll()\n\n def terraform(self, config, mat):\n super().__init__(Stimulus.Tile, config)\n self.mat = mat()\n# self.capacity = self.mat.capacity\n \n \n"
] |
[
[
"numpy.hstack",
"numpy.log",
"numpy.log2",
"numpy.einsum",
"numpy.linalg.norm",
"numpy.cov",
"numpy.mean",
"scipy.stats.multivariate_normal",
"numpy.float",
"scipy.spatial.ConvexHull",
"numpy.exp",
"numpy.array",
"numpy.average",
"numpy.where",
"numpy.sum",
"numpy.vstack"
],
[
"numpy.array",
"numpy.zeros",
"numpy.float32"
],
[
"numpy.random.rand"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jnwei/deep-molecular-massspec
|
[
"b82b40b57441b939da5899dfb575b284d20cea8e"
] |
[
"make_train_test_split.py"
] |
[
"# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nr\"\"\"Creates datasets from the NIST sdf files and makes experiment setup jsons.\n\nThis module first breaks up the main NIST library dataset into a train/\nvalidation/test set, and the replicates library into a validation and test set.\nAs all the molecules in the replicates file are also in the main NIST library,\nthe mainlib datasets will exclude inchikeys from the replicates library. All the\nmolecules in both datasets are to be included in one of these datasets, unless\nan argument is passed for mainlib_maximum_num_molecules_to_use or\nreplicates_maximum_num_molecules_to_use.\n\nThe component datasets are saved as TFRecords, by the names defined in\ndataset_setup_constants and the library from which the data came\n(e.g. mainlib_train_from_mainlib.tfrecord). This will result in 7 TFRecord files\ntotal, one each for the train/validation/test splits from the main library, and\ntwo each for the replicates validation/test splits, one with its data from the\nmainlib NIST file, and the other from the replicates file.\n\nFor each experiment setup included in\ndataset_setup_constants.EXPERIMENT_SETUPS_LIST, a json file is written. This\njson file name the files to be used for each part of the experiment, i.e.\nlibrary matching, spectra prediction.\n\nNote: Reading sdf files from cns currently not supported.\n\nExample usage:\nmake_train_test_split.py \\\n--main_sdf_name=testdata/test_14_mend.sdf\n--replicates_sdf_name=testdata/test_2_mend.sdf \\\n--output_master_dir=<output_dir_name>\n\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport json\nimport os\nimport random\n\nfrom absl import app\nfrom absl import flags\nimport dataset_setup_constants as ds_constants\nimport mass_spec_constants as ms_constants\nimport parse_sdf_utils\nimport train_test_split_utils\nimport six\nimport tensorflow as tf\n\nFLAGS = flags.FLAGS\nflags.DEFINE_string(\n 'main_sdf_name', 'testdata/test_14_mend.sdf',\n 'specify full path of sdf file to parse, to be used for'\n ' training sets, and validation/test sets')\nflags.DEFINE_string(\n 'replicates_sdf_name',\n 'testdata/test_2_mend.sdf',\n 'specify full path of a second sdf file to parse, to be'\n ' used for the vaildation/test set. Molecules in this sdf'\n ' will be excluded from the main train/val/test sets.')\n# Note: For family based splitting, all molecules passing the filter will be\n# placed in validation/test datasets, and then split according to the relative\n# ratio between the validation/test fractions. If these are both equal to 0.0,\n# these values will be over written to 0.5 and 0.5.\nflags.DEFINE_list(\n 'main_train_val_test_fractions', '1.0,0.0,0.0',\n 'specify how large to make the train, val, and test sets'\n ' as a fraction of the whole dataset.')\nflags.DEFINE_integer('mainlib_maximum_num_molecules_to_use', None,\n 'specify how many total samples to use for parsing')\nflags.DEFINE_integer('replicates_maximum_num_molecules_to_use', None,\n 'specify how many total samples to use for parsing')\nflags.DEFINE_list(\n 'replicates_train_val_test_fractions', '0.0,0.5,0.5',\n 'specify fraction of replicates molecules to use for'\n ' for the three replicates sample files.')\nflags.DEFINE_enum(\n 'splitting_type', 'random', ['random', 'steroid', 'diazo'],\n 'specify splitting method to use for creating '\n 'training/validation/test sets')\nflags.DEFINE_string('output_master_dir', '/tmp/output_dataset_dir',\n 'specify directory to save records')\nflags.DEFINE_integer('max_atoms', ms_constants.MAX_ATOMS,\n 'specify maximum number of atoms to allow')\nflags.DEFINE_integer('max_mass_spec_peak_loc', ms_constants.MAX_PEAK_LOC,\n 'specify greatest m/z spectrum peak to allow')\n\nINCHIKEY_FILENAME_END = '.inchikey.txt'\nTFRECORD_FILENAME_END = '.tfrecord'\nNP_LIBRARY_ARRAY_END = '.spectra_library.npy'\nFROM_MAINLIB_FILENAME_MODIFIER = '_from_mainlib'\nFROM_REPLICATES_FILENAME_MODIFIER = '_from_replicates'\n\n\ndef make_mainlib_replicates_train_test_split(\n mainlib_mol_list,\n replicates_mol_list,\n splitting_type,\n mainlib_fractions,\n replicates_fractions,\n mainlib_maximum_num_molecules_to_use=None,\n replicates_maximum_num_molecules_to_use=None,\n rseed=42):\n \"\"\"Makes train/validation/test inchikey lists from two lists of rdkit.Mol.\n\n Args:\n mainlib_mol_list : list of molecules from main library\n replicates_mol_list : list of molecules from replicates library\n splitting_type : type of splitting to use for validation splits.\n mainlib_fractions : TrainValTestFractions namedtuple\n holding desired fractions for train/val/test split of mainlib\n replicates_fractions : TrainValTestFractions namedtuple\n holding desired fractions for train/val/test split of replicates.\n For the replicates set, the train fraction should be set to 0.\n mainlib_maximum_num_molecules_to_use : Largest number of molecules to use\n when making datasets from mainlib\n replicates_maximum_num_molecules_to_use : Largest number of molecules to use\n when making datasets from replicates\n rseed : random seed for shuffling\n\n Returns:\n main_inchikey_dict : Dict that is keyed by inchikey, containing a list of\n rdkit.Mol objects corresponding to that inchikey from the mainlib\n replicates_inchikey_dict : Dict that is keyed by inchikey, containing a list\n of rdkit.Mol objects corresponding to that inchikey from the replicates\n library\n main_replicates_split_inchikey_lists_dict : dict with keys :\n 'mainlib_train', 'mainlib_validation', 'mainlib_test',\n 'replicates_train', 'replicates_validation', 'replicates_test'\n Values are lists of inchikeys corresponding to each dataset.\n\n \"\"\"\n random.seed(rseed)\n main_inchikey_dict = train_test_split_utils.make_inchikey_dict(\n mainlib_mol_list)\n main_inchikey_list = main_inchikey_dict.keys()\n\n if six.PY3:\n main_inchikey_list = list(main_inchikey_list)\n\n if mainlib_maximum_num_molecules_to_use is not None:\n main_inchikey_list = random.sample(main_inchikey_list,\n mainlib_maximum_num_molecules_to_use)\n\n replicates_inchikey_dict = train_test_split_utils.make_inchikey_dict(\n replicates_mol_list)\n replicates_inchikey_list = replicates_inchikey_dict.keys()\n\n if six.PY3:\n replicates_inchikey_list = list(replicates_inchikey_list)\n\n if replicates_maximum_num_molecules_to_use is not None:\n replicates_inchikey_list = random.sample(\n replicates_inchikey_list, replicates_maximum_num_molecules_to_use)\n\n # Make train/val/test splits for main dataset.\n main_train_validation_test_inchikeys = (\n train_test_split_utils.make_train_val_test_split_inchikey_lists(\n main_inchikey_list,\n main_inchikey_dict,\n mainlib_fractions,\n holdout_inchikey_list=replicates_inchikey_list,\n splitting_type=splitting_type))\n\n # Make train/val/test splits for replicates dataset.\n replicates_validation_test_inchikeys = (\n train_test_split_utils.make_train_val_test_split_inchikey_lists(\n replicates_inchikey_list,\n replicates_inchikey_dict,\n replicates_fractions,\n splitting_type=splitting_type))\n\n component_inchikey_dict = {\n ds_constants.MAINLIB_TRAIN_BASENAME:\n main_train_validation_test_inchikeys.train,\n ds_constants.MAINLIB_VALIDATION_BASENAME:\n main_train_validation_test_inchikeys.validation,\n ds_constants.MAINLIB_TEST_BASENAME:\n main_train_validation_test_inchikeys.test,\n ds_constants.REPLICATES_TRAIN_BASENAME:\n replicates_validation_test_inchikeys.train,\n ds_constants.REPLICATES_VALIDATION_BASENAME:\n replicates_validation_test_inchikeys.validation,\n ds_constants.REPLICATES_TEST_BASENAME:\n replicates_validation_test_inchikeys.test\n }\n\n train_test_split_utils.assert_all_lists_mutally_exclusive(\n list(component_inchikey_dict.values()))\n # Test that the set of the 5 component inchikey lists is equal to the set of\n # inchikeys in the main library.\n all_inchikeys_in_components = []\n for ikey_list in list(component_inchikey_dict.values()):\n for ikey in ikey_list:\n all_inchikeys_in_components.append(ikey)\n\n assert set(main_inchikey_list + replicates_inchikey_list) == set(\n all_inchikeys_in_components\n ), ('The inchikeys in the original inchikey dictionary are not all included'\n ' in the train/val/test component libraries')\n\n return (main_inchikey_dict, replicates_inchikey_dict, component_inchikey_dict)\n\n\ndef write_list_of_inchikeys(inchikey_list, base_name, output_dir):\n \"\"\"Write list of inchikeys as a text file.\"\"\"\n inchikey_list_name = base_name + INCHIKEY_FILENAME_END\n\n with tf.gfile.Open(os.path.join(output_dir, inchikey_list_name),\n 'w') as writer:\n for inchikey in inchikey_list:\n writer.write('%s\\n' % inchikey)\n\n\ndef write_all_dataset_files(inchikey_dict,\n inchikey_list,\n base_name,\n output_dir,\n max_atoms,\n max_mass_spec_peak_loc,\n make_library_array=False):\n \"\"\"Helper function for writing all the files associated with a TFRecord.\n\n Args:\n inchikey_dict : Full dictionary keyed by inchikey containing lists of\n rdkit.Mol objects\n inchikey_list : List of inchikeys to include in dataset\n base_name : Base name for the dataset\n output_dir : Path for saving all TFRecord files\n max_atoms : Maximum number of atoms to include for a given molecule\n max_mass_spec_peak_loc : Largest m/z peak to include in a spectra.\n make_library_array : Flag for whether to make library array\n Returns:\n Saves 3 files:\n basename.tfrecord : a TFRecord file,\n basename.inchikey.txt : a text file with all the inchikeys in the dataset\n basename.tfrecord.info: a text file with one line describing\n the length of the TFRecord file.\n Also saves if make_library_array is set:\n basename.npz : see parse_sdf_utils.write_dicts_to_example\n \"\"\"\n record_name = base_name + TFRECORD_FILENAME_END\n\n mol_list = train_test_split_utils.make_mol_list_from_inchikey_dict(\n inchikey_dict, inchikey_list)\n\n if make_library_array:\n library_array_pathname = base_name + NP_LIBRARY_ARRAY_END\n parse_sdf_utils.write_dicts_to_example(\n mol_list, os.path.join(output_dir, record_name),\n max_atoms, max_mass_spec_peak_loc,\n os.path.join(output_dir, library_array_pathname))\n else:\n parse_sdf_utils.write_dicts_to_example(\n mol_list, os.path.join(output_dir, record_name), max_atoms,\n max_mass_spec_peak_loc)\n write_list_of_inchikeys(inchikey_list, base_name, output_dir)\n parse_sdf_utils.write_info_file(mol_list, os.path.join(\n output_dir, record_name))\n\n\ndef write_mainlib_split_datasets(component_inchikey_dict, mainlib_inchikey_dict,\n output_dir, max_atoms, max_mass_spec_peak_loc):\n \"\"\"Write all train/val/test set TFRecords from main NIST sdf file.\"\"\"\n for component_kwarg in component_inchikey_dict.keys():\n component_mainlib_filename = (\n component_kwarg + FROM_MAINLIB_FILENAME_MODIFIER)\n if component_kwarg == ds_constants.MAINLIB_TRAIN_BASENAME:\n write_all_dataset_files(\n mainlib_inchikey_dict,\n component_inchikey_dict[component_kwarg],\n component_mainlib_filename,\n output_dir,\n max_atoms,\n max_mass_spec_peak_loc,\n make_library_array=True)\n else:\n write_all_dataset_files(mainlib_inchikey_dict,\n component_inchikey_dict[component_kwarg],\n component_mainlib_filename, output_dir, max_atoms,\n max_mass_spec_peak_loc)\n\n\ndef write_replicates_split_datasets(component_inchikey_dict,\n replicates_inchikey_dict, output_dir,\n max_atoms, max_mass_spec_peak_loc):\n \"\"\"Write replicates val/test set TFRecords from replicates sdf file.\"\"\"\n for component_kwarg in [\n ds_constants.REPLICATES_VALIDATION_BASENAME,\n ds_constants.REPLICATES_TEST_BASENAME\n ]:\n component_replicates_filename = (\n component_kwarg + FROM_REPLICATES_FILENAME_MODIFIER)\n write_all_dataset_files(replicates_inchikey_dict,\n component_inchikey_dict[component_kwarg],\n component_replicates_filename, output_dir,\n max_atoms, max_mass_spec_peak_loc)\n\n\ndef combine_inchikey_sets(dataset_subdivision_list, dataset_split_dict):\n \"\"\"A function to combine lists of inchikeys that are values from a dict.\n\n Args:\n dataset_subdivision_list: List of keys in dataset_split_dict to combine\n into one list\n dataset_split_dict: dict containing keys in dataset_subdivision_list, with\n lists of inchikeys as values.\n Returns:\n A list of inchikeys.\n \"\"\"\n dataset_inchikey_list = []\n for dataset_subdivision_name in dataset_subdivision_list:\n dataset_inchikey_list.extend(dataset_split_dict[dataset_subdivision_name])\n return dataset_inchikey_list\n\n\ndef check_experiment_setup(experiment_setup_dict, component_inchikey_dict):\n \"\"\"Validates experiment setup for given lists of inchikeys.\"\"\"\n\n # Check that the union of the library matching observed and library\n # matching predicted sets are equal to the set of inchikeys in the\n # mainlib_inchikey_dict\n all_inchikeys_in_library = (\n combine_inchikey_sets(\n experiment_setup_dict[ds_constants.LIBRARY_MATCHING_OBSERVED_KEY],\n component_inchikey_dict) +\n combine_inchikey_sets(\n experiment_setup_dict[ds_constants.LIBRARY_MATCHING_PREDICTED_KEY],\n component_inchikey_dict))\n\n all_inchikeys_in_use = []\n for kwarg in component_inchikey_dict.keys():\n all_inchikeys_in_use.extend(component_inchikey_dict[kwarg])\n\n assert set(all_inchikeys_in_use) == set(all_inchikeys_in_library), (\n 'Inchikeys in library for library matching does not match full dataset.')\n\n # Check that all inchikeys in query are found in full library of inchikeys.\n assert set(\n combine_inchikey_sets(\n experiment_setup_dict[ds_constants.LIBRARY_MATCHING_QUERY_KEY],\n component_inchikey_dict)).issubset(set(all_inchikeys_in_library)), (\n 'Inchikeys in query set for library matching not'\n 'found in library.')\n\n\ndef write_json_for_experiment(experiment_setup, output_dir):\n \"\"\"Writes json for experiment, recording relevant files for each component.\n\n Writes a json containing a list of TFRecord file names to read\n for each experiment component, i.e. spectrum_prediction, library_matching.\n\n Args:\n experiment_setup: A dataset_setup_constants.ExperimentSetup tuple\n output_dir: directory to write json\n Returns:\n Writes json recording which files to load for each component\n of the experiment\n Raises:\n ValueError: if the experiment component is not specified to be taken from\n either the main NIST library or the replicates library.\n\n \"\"\"\n experiment_json_dict = {}\n for dataset_kwarg in experiment_setup.experiment_setup_dataset_dict:\n if dataset_kwarg in experiment_setup.data_to_get_from_mainlib:\n experiment_json_dict[dataset_kwarg] = [\n (component_basename + FROM_MAINLIB_FILENAME_MODIFIER +\n TFRECORD_FILENAME_END) for component_basename in\n experiment_setup.experiment_setup_dataset_dict[dataset_kwarg]\n ]\n elif dataset_kwarg in experiment_setup.data_to_get_from_replicates:\n experiment_json_dict[dataset_kwarg] = [\n (component_basename + FROM_REPLICATES_FILENAME_MODIFIER +\n TFRECORD_FILENAME_END) for component_basename in\n experiment_setup.experiment_setup_dataset_dict[dataset_kwarg]\n ]\n else:\n raise ValueError('Did not specify origin for {}.'.format(dataset_kwarg))\n\n training_spectra_filename = (\n ds_constants.MAINLIB_TRAIN_BASENAME + FROM_MAINLIB_FILENAME_MODIFIER +\n NP_LIBRARY_ARRAY_END)\n experiment_json_dict[\n ds_constants.TRAINING_SPECTRA_ARRAY_KEY] = training_spectra_filename\n\n with tf.gfile.Open(os.path.join(output_dir, experiment_setup.json_name),\n 'w') as writer:\n experiment_json = json.dumps(experiment_json_dict)\n writer.write(experiment_json)\n\n\ndef main(_):\n tf.gfile.MkDir(FLAGS.output_master_dir)\n\n main_train_val_test_fractions_tuple = tuple(\n [float(elem) for elem in FLAGS.main_train_val_test_fractions])\n main_train_val_test_fractions = train_test_split_utils.TrainValTestFractions(\n *main_train_val_test_fractions_tuple)\n\n replicates_train_val_test_fractions_tuple = tuple(\n [float(elem) for elem in FLAGS.replicates_train_val_test_fractions])\n replicates_train_val_test_fractions = (\n train_test_split_utils.TrainValTestFractions(\n *replicates_train_val_test_fractions_tuple))\n\n mainlib_mol_list = parse_sdf_utils.get_sdf_to_mol(\n FLAGS.main_sdf_name, max_atoms=FLAGS.max_atoms)\n replicates_mol_list = parse_sdf_utils.get_sdf_to_mol(\n FLAGS.replicates_sdf_name, max_atoms=FLAGS.max_atoms)\n\n # Breaks the inchikeys lists into train/validation/test splits.\n (mainlib_inchikey_dict, replicates_inchikey_dict, component_inchikey_dict) = (\n make_mainlib_replicates_train_test_split(\n mainlib_mol_list,\n replicates_mol_list,\n FLAGS.splitting_type,\n main_train_val_test_fractions,\n replicates_train_val_test_fractions,\n mainlib_maximum_num_molecules_to_use=FLAGS.\n mainlib_maximum_num_molecules_to_use,\n replicates_maximum_num_molecules_to_use=FLAGS.\n replicates_maximum_num_molecules_to_use))\n\n # Writes TFRecords for each component using info from the main library file\n write_mainlib_split_datasets(component_inchikey_dict, mainlib_inchikey_dict,\n FLAGS.output_master_dir, FLAGS.max_atoms,\n FLAGS.max_mass_spec_peak_loc)\n\n # Writes TFRecords for each component using info from the replicates file\n write_replicates_split_datasets(\n component_inchikey_dict, replicates_inchikey_dict,\n FLAGS.output_master_dir, FLAGS.max_atoms, FLAGS.max_mass_spec_peak_loc)\n\n for experiment_setup in ds_constants.EXPERIMENT_SETUPS_LIST:\n # Check that experiment setup is valid.\n check_experiment_setup(experiment_setup.experiment_setup_dataset_dict,\n component_inchikey_dict)\n\n # Write a json for the experiment setups, pointing to local files.\n write_json_for_experiment(experiment_setup, FLAGS.output_master_dir)\n\n\nif __name__ == '__main__':\n app.run(main)\n"
] |
[
[
"tensorflow.gfile.MkDir"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
patcao/ibis
|
[
"661bbd20081285f3c29267793f3d070d0c8a0db8"
] |
[
"ibis/expr/operations.py"
] |
[
"import collections\nimport functools\nimport itertools\nimport operator\nfrom contextlib import suppress\nfrom typing import Any, Dict, List\n\nimport numpy as np\nimport toolz\nfrom cached_property import cached_property\n\nimport ibis.common.exceptions as com\nimport ibis.expr.datatypes as dt\nimport ibis.expr.rules as rlz\nimport ibis.expr.schema as sch\nimport ibis.expr.types as ir\nfrom ibis import util\nfrom ibis.expr.schema import HasSchema, Schema\nfrom ibis.expr.signature import Annotable\nfrom ibis.expr.signature import Argument as Arg\n\n\ndef _safe_repr(x, memo=None):\n return x._repr(memo=memo) if isinstance(x, (ir.Expr, Node)) else repr(x)\n\n\n# TODO: move to analysis\ndef distinct_roots(*expressions):\n roots = toolz.concat(expr.op().root_tables() for expr in expressions)\n return list(toolz.unique(roots))\n\n\nclass Node(Annotable):\n __slots__ = '_expr_cached', '_hash'\n\n def __repr__(self):\n return self._repr()\n\n def _repr(self, memo=None):\n if memo is None:\n from ibis.expr.format import FormatMemo\n\n memo = FormatMemo()\n\n opname = type(self).__name__\n pprint_args = []\n\n def _pp(x):\n return _safe_repr(x, memo=memo)\n\n for x in self.args:\n if isinstance(x, (tuple, list)):\n pp = repr(list(map(_pp, x)))\n else:\n pp = _pp(x)\n pprint_args.append(pp)\n\n return '{}({})'.format(opname, ', '.join(pprint_args))\n\n def __getstate__(self) -> Dict[str, Any]:\n \"\"\"The attributes _expr_cached and _hash are\n used as caches; they can be excluded from\n serialization without affecting correctness.\n\n Excluding _expr_cached and _hash from serialization\n will allow the serialized bytes to be the same for\n equivalent Node objets.\n\n Returns\n -------\n Dict[str, Any]\n A dictionary storing the objects attributes.\n \"\"\"\n excluded_slots = {'_expr_cached', '_hash'}\n return {\n slot: getattr(self, slot)\n for slot in self.__slots__\n if slot not in excluded_slots\n }\n\n def __setstate__(self, state: Dict[str, Any]) -> None:\n \"\"\"\n Parameters\n ----------\n state: Dict[str, Any]\n A dictionary storing the objects attributes.\n \"\"\"\n for slot in state:\n setattr(self, slot, state[slot])\n\n @property\n def inputs(self):\n return tuple(self.args)\n\n def blocks(self):\n # The contents of this node at referentially distinct and may not be\n # analyzed deeper\n return False\n\n def flat_args(self):\n for arg in self.args:\n if not isinstance(arg, str) and isinstance(\n arg, collections.abc.Iterable\n ):\n for x in arg:\n yield x\n else:\n yield arg\n\n def __hash__(self):\n if not hasattr(self, '_hash'):\n self._hash = hash(\n (type(self),)\n + tuple(\n element.op() if isinstance(element, ir.Expr) else element\n for element in self.flat_args()\n )\n )\n return self._hash\n\n def __eq__(self, other):\n return self.equals(other)\n\n def equals(self, other, cache=None):\n if cache is None:\n cache = {}\n\n key = self, other\n\n try:\n return cache[key]\n except KeyError:\n cache[key] = result = self is other or (\n type(self) == type(other)\n and all_equal(self.args, other.args, cache=cache)\n )\n return result\n\n def compatible_with(self, other):\n return self.equals(other)\n\n def is_ancestor(self, other):\n if isinstance(other, ir.Expr):\n other = other.op()\n\n return self.equals(other)\n\n def to_expr(self):\n if not hasattr(self, '_expr_cached'):\n self._expr_cached = self._make_expr()\n return self._expr_cached\n\n def _make_expr(self):\n klass = self.output_type()\n return klass(self)\n\n def output_type(self):\n \"\"\"\n This function must resolve the output type of the expression and return\n the node wrapped in the appropriate ValueExpr type.\n \"\"\"\n raise NotImplementedError\n\n\nclass ValueOp(Node):\n def root_tables(self):\n exprs = [arg for arg in self.args if isinstance(arg, ir.Expr)]\n return distinct_roots(*exprs)\n\n def resolve_name(self):\n raise com.ExpressionError(f'Expression is not named: {type(self)}')\n\n def has_resolved_name(self):\n return False\n\n\ndef all_equal(left, right, cache=None):\n \"\"\"Check whether two objects `left` and `right` are equal.\n\n Parameters\n ----------\n left : Union[object, Expr, Node]\n right : Union[object, Expr, Node]\n cache : Optional[Dict[Tuple[Node, Node], bool]]\n A dictionary indicating whether two Nodes are equal\n \"\"\"\n if cache is None:\n cache = {}\n\n if util.is_iterable(left):\n # check that left and right are equal length iterables and that all\n # of their elements are equal\n return (\n util.is_iterable(right)\n and len(left) == len(right)\n and all(\n itertools.starmap(\n functools.partial(all_equal, cache=cache), zip(left, right)\n )\n )\n )\n\n if hasattr(left, 'equals'):\n return left.equals(right, cache=cache)\n return left == right\n\n\n_table_names = ('unbound_table_{:d}'.format(i) for i in itertools.count())\n\n\ndef genname():\n return next(_table_names)\n\n\nclass TableNode(Node):\n def get_type(self, name):\n return self.schema[name]\n\n def output_type(self):\n return ir.TableExpr\n\n def aggregate(self, this, metrics, by=None, having=None):\n return Aggregation(this, metrics, by=by, having=having)\n\n def sort_by(self, expr, sort_exprs):\n return Selection(expr, [], sort_keys=sort_exprs)\n\n def is_ancestor(self, other):\n import ibis.expr.lineage as lin\n\n if isinstance(other, ir.Expr):\n other = other.op()\n\n if self.equals(other):\n return True\n\n fn = lambda e: (lin.proceed, e.op()) # noqa: E731\n expr = self.to_expr()\n for child in lin.traverse(fn, expr):\n if child.equals(other):\n return True\n return False\n\n\nclass TableColumn(ValueOp):\n \"\"\"Selects a column from a TableExpr\"\"\"\n\n name = Arg((str, int))\n table = Arg(ir.TableExpr)\n\n def __init__(self, name, table):\n schema = table.schema()\n if isinstance(name, int):\n name = schema.name_at_position(name)\n super().__init__(name, table)\n\n def _validate(self):\n if self.name not in self.table.schema():\n raise com.IbisTypeError(\n \"'{}' is not a field in {}\".format(\n self.name, self.table.columns\n )\n )\n\n def parent(self):\n return self.table\n\n def resolve_name(self):\n return self.name\n\n def has_resolved_name(self):\n return True\n\n def root_tables(self):\n return self.table.op().root_tables()\n\n def _make_expr(self):\n dtype = self.table._get_type(self.name)\n klass = dtype.column_type()\n return klass(self, name=self.name)\n\n\nclass RowID(ValueOp):\n \"\"\"The row number (an autonumeric) of the returned result.\"\"\"\n\n def output_type(self):\n return dt.int64.column_type()\n\n def resolve_name(self):\n return 'rowid'\n\n def has_resolved_name(self):\n return True\n\n\ndef find_all_base_tables(expr, memo=None):\n if memo is None:\n memo = {}\n\n node = expr.op()\n\n if isinstance(expr, ir.TableExpr) and node.blocks():\n if expr not in memo:\n memo[node] = expr\n return memo\n\n for arg in expr.op().flat_args():\n if isinstance(arg, ir.Expr):\n find_all_base_tables(arg, memo)\n\n return memo\n\n\nclass PhysicalTable(TableNode, HasSchema):\n def blocks(self):\n return True\n\n\nclass UnboundTable(PhysicalTable):\n schema = Arg(sch.Schema)\n name = Arg(str, default=genname)\n\n\nclass DatabaseTable(PhysicalTable):\n name = Arg(str)\n schema = Arg(sch.Schema)\n source = Arg(rlz.client)\n\n def change_name(self, new_name):\n return type(self)(new_name, self.args[1], self.source)\n\n\nclass SQLQueryResult(TableNode, HasSchema):\n \"\"\"A table sourced from the result set of a select query\"\"\"\n\n query = Arg(rlz.noop)\n schema = Arg(sch.Schema)\n source = Arg(rlz.client)\n\n def blocks(self):\n return True\n\n\nclass TableArrayView(ValueOp):\n\n \"\"\"\n (Temporary?) Helper operation class for SQL translation (fully formed table\n subqueries to be viewed as arrays)\n \"\"\"\n\n table = Arg(ir.TableExpr)\n name = Arg(str)\n\n def __init__(self, table):\n schema = table.schema()\n if len(schema) > 1:\n raise com.ExpressionError('Table can only have a single column')\n\n name = schema.names[0]\n return super().__init__(table, name)\n\n def _make_expr(self):\n ctype = self.table._get_type(self.name)\n klass = ctype.column_type()\n return klass(self, name=self.name)\n\n\nclass UnaryOp(ValueOp):\n arg = Arg(rlz.any)\n\n\nclass BinaryOp(ValueOp):\n \"\"\"A binary operation\"\"\"\n\n left = Arg(rlz.any)\n right = Arg(rlz.any)\n\n\nclass Cast(ValueOp):\n arg = Arg(rlz.any)\n to = Arg(dt.dtype)\n\n # see #396 for the issue preventing this\n # def resolve_name(self):\n # return self.args[0].get_name()\n\n def output_type(self):\n return rlz.shape_like(self.arg, dtype=self.to)\n\n\nclass TypeOf(UnaryOp):\n output_type = rlz.shape_like('arg', dt.string)\n\n\nclass Negate(UnaryOp):\n arg = Arg(rlz.one_of((rlz.numeric(), rlz.interval())))\n output_type = rlz.typeof('arg')\n\n\nclass IsNull(UnaryOp):\n \"\"\"Returns true if values are null\n\n Returns\n -------\n isnull : boolean with dimension of caller\n \"\"\"\n\n output_type = rlz.shape_like('arg', dt.boolean)\n\n\nclass NotNull(UnaryOp):\n \"\"\"Returns true if values are not null\n\n Returns\n -------\n notnull : boolean with dimension of caller\n \"\"\"\n\n output_type = rlz.shape_like('arg', dt.boolean)\n\n\nclass ZeroIfNull(UnaryOp):\n output_type = rlz.typeof('arg')\n\n\nclass IfNull(ValueOp):\n \"\"\"Equivalent to (but perhaps implemented differently):\n\n case().when(expr.notnull(), expr)\n .else_(null_substitute_expr)\n \"\"\"\n\n arg = Arg(rlz.any)\n ifnull_expr = Arg(rlz.any)\n output_type = rlz.shape_like('args')\n\n\nclass NullIf(ValueOp):\n \"\"\"Set values to NULL if they equal the null_if_expr\"\"\"\n\n arg = Arg(rlz.any)\n null_if_expr = Arg(rlz.any)\n output_type = rlz.shape_like('args')\n\n\nclass NullIfZero(ValueOp):\n\n \"\"\"\n Set values to NULL if they equal to zero. Commonly used in cases where\n divide-by-zero would produce an overflow or infinity.\n\n Equivalent to (value == 0).ifelse(ibis.NA, value)\n\n Returns\n -------\n maybe_nulled : type of caller\n \"\"\"\n\n arg = Arg(rlz.numeric)\n output_type = rlz.typeof('arg')\n\n\nclass IsNan(ValueOp):\n arg = Arg(rlz.floating)\n output_type = rlz.shape_like('arg', dt.boolean)\n\n\nclass IsInf(ValueOp):\n arg = Arg(rlz.floating)\n output_type = rlz.shape_like('arg', dt.boolean)\n\n\nclass CoalesceLike(ValueOp):\n\n # According to Impala documentation:\n # Return type: same as the initial argument value, except that integer\n # values are promoted to BIGINT and floating-point values are promoted to\n # DOUBLE; use CAST() when inserting into a smaller numeric column\n arg = Arg(rlz.list_of(rlz.any))\n\n def output_type(self):\n first = self.arg[0]\n if isinstance(first, (ir.IntegerValue, ir.FloatingValue)):\n dtype = first.type().largest\n else:\n dtype = first.type()\n\n # self.arg is a list of value expressions\n return rlz.shape_like(self.arg, dtype)\n\n\nclass Coalesce(CoalesceLike):\n pass\n\n\nclass Greatest(CoalesceLike):\n pass\n\n\nclass Least(CoalesceLike):\n pass\n\n\nclass Abs(UnaryOp):\n \"\"\"Absolute value\"\"\"\n\n output_type = rlz.typeof('arg')\n\n\nclass Ceil(UnaryOp):\n\n \"\"\"\n Round up to the nearest integer value greater than or equal to this value\n\n Returns\n -------\n ceiled : type depending on input\n Decimal values: yield decimal\n Other numeric values: yield integer (int32)\n \"\"\"\n\n arg = Arg(rlz.numeric)\n\n def output_type(self):\n if isinstance(self.arg.type(), dt.Decimal):\n return self.arg._factory\n return rlz.shape_like(self.arg, dt.int64)\n\n\nclass Floor(UnaryOp):\n\n \"\"\"\n Round down to the nearest integer value less than or equal to this value\n\n Returns\n -------\n floored : type depending on input\n Decimal values: yield decimal\n Other numeric values: yield integer (int32)\n \"\"\"\n\n arg = Arg(rlz.numeric)\n\n def output_type(self):\n if isinstance(self.arg.type(), dt.Decimal):\n return self.arg._factory\n return rlz.shape_like(self.arg, dt.int64)\n\n\nclass Round(ValueOp):\n arg = Arg(rlz.numeric)\n digits = Arg(rlz.numeric, default=None)\n\n def output_type(self):\n if isinstance(self.arg, ir.DecimalValue):\n return self.arg._factory\n elif self.digits is None:\n return rlz.shape_like(self.arg, dt.int64)\n else:\n return rlz.shape_like(self.arg, dt.double)\n\n\nclass Clip(ValueOp):\n arg = Arg(rlz.strict_numeric)\n lower = Arg(rlz.strict_numeric, default=None)\n upper = Arg(rlz.strict_numeric, default=None)\n output_type = rlz.typeof('arg')\n\n\nclass BaseConvert(ValueOp):\n arg = Arg(rlz.one_of([rlz.integer, rlz.string]))\n from_base = Arg(rlz.integer)\n to_base = Arg(rlz.integer)\n\n def output_type(self):\n return rlz.shape_like(tuple(self.flat_args()), dt.string)\n\n\nclass MathUnaryOp(UnaryOp):\n arg = Arg(rlz.numeric)\n\n def output_type(self):\n arg = self.arg\n if isinstance(self.arg, ir.DecimalValue):\n dtype = arg.type()\n else:\n dtype = dt.double\n return rlz.shape_like(arg, dtype)\n\n\nclass ExpandingTypeMathUnaryOp(MathUnaryOp):\n def output_type(self):\n if not isinstance(self.arg, ir.DecimalValue):\n return super().output_type()\n arg = self.arg\n return rlz.shape_like(arg, arg.type().largest)\n\n\nclass Exp(ExpandingTypeMathUnaryOp):\n pass\n\n\nclass Sign(UnaryOp):\n arg = Arg(rlz.numeric)\n output_type = rlz.typeof('arg')\n\n\nclass Sqrt(MathUnaryOp):\n pass\n\n\nclass Logarithm(MathUnaryOp):\n arg = Arg(rlz.strict_numeric)\n\n\nclass Log(Logarithm):\n arg = Arg(rlz.strict_numeric)\n base = Arg(rlz.strict_numeric, default=None)\n\n\nclass Ln(Logarithm):\n \"\"\"Natural logarithm\"\"\"\n\n\nclass Log2(Logarithm):\n \"\"\"Logarithm base 2\"\"\"\n\n\nclass Log10(Logarithm):\n \"\"\"Logarithm base 10\"\"\"\n\n\nclass Degrees(ExpandingTypeMathUnaryOp):\n \"\"\"Converts radians to degrees\"\"\"\n\n arg = Arg(rlz.numeric)\n\n\nclass Radians(MathUnaryOp):\n \"\"\"Converts degrees to radians\"\"\"\n\n arg = Arg(rlz.numeric)\n\n\n# TRIGONOMETRIC OPERATIONS\n\n\nclass TrigonometricUnary(MathUnaryOp):\n \"\"\"Trigonometric base unary\"\"\"\n\n arg = Arg(rlz.numeric)\n\n\nclass TrigonometricBinary(BinaryOp):\n \"\"\"Trigonometric base binary\"\"\"\n\n left = Arg(rlz.numeric)\n right = Arg(rlz.numeric)\n output_type = rlz.shape_like('args', dt.float64)\n\n\nclass Acos(TrigonometricUnary):\n \"\"\"Returns the arc cosine of x\"\"\"\n\n\nclass Asin(TrigonometricUnary):\n \"\"\"Returns the arc sine of x\"\"\"\n\n\nclass Atan(TrigonometricUnary):\n \"\"\"Returns the arc tangent of x\"\"\"\n\n\nclass Atan2(TrigonometricBinary):\n \"\"\"Returns the arc tangent of x and y\"\"\"\n\n\nclass Cos(TrigonometricUnary):\n \"\"\"Returns the cosine of x\"\"\"\n\n\nclass Cot(TrigonometricUnary):\n \"\"\"Returns the cotangent of x\"\"\"\n\n\nclass Sin(TrigonometricUnary):\n \"\"\"Returns the sine of x\"\"\"\n\n\nclass Tan(TrigonometricUnary):\n \"\"\"Returns the tangent of x\"\"\"\n\n\nclass StringUnaryOp(UnaryOp):\n arg = Arg(rlz.string)\n output_type = rlz.shape_like('arg', dt.string)\n\n\nclass Uppercase(StringUnaryOp):\n \"\"\"Convert string to all uppercase\"\"\"\n\n\nclass Lowercase(StringUnaryOp):\n \"\"\"Convert string to all lowercase\"\"\"\n\n\nclass Reverse(StringUnaryOp):\n \"\"\"Reverse string\"\"\"\n\n\nclass Strip(StringUnaryOp):\n \"\"\"Remove whitespace from left and right sides of string\"\"\"\n\n\nclass LStrip(StringUnaryOp):\n \"\"\"Remove whitespace from left side of string\"\"\"\n\n\nclass RStrip(StringUnaryOp):\n \"\"\"Remove whitespace from right side of string\"\"\"\n\n\nclass Capitalize(StringUnaryOp):\n \"\"\"Return a capitalized version of input string\"\"\"\n\n\nclass Substring(ValueOp):\n arg = Arg(rlz.string)\n start = Arg(rlz.integer)\n length = Arg(rlz.integer, default=None)\n output_type = rlz.shape_like('arg', dt.string)\n\n\nclass StrRight(ValueOp):\n arg = Arg(rlz.string)\n nchars = Arg(rlz.integer)\n output_type = rlz.shape_like('arg', dt.string)\n\n\nclass Repeat(ValueOp):\n arg = Arg(rlz.string)\n times = Arg(rlz.integer)\n output_type = rlz.shape_like('arg', dt.string)\n\n\nclass StringFind(ValueOp):\n arg = Arg(rlz.string)\n substr = Arg(rlz.string)\n start = Arg(rlz.integer, default=None)\n end = Arg(rlz.integer, default=None)\n output_type = rlz.shape_like('arg', dt.int64)\n\n\nclass Translate(ValueOp):\n arg = Arg(rlz.string)\n from_str = Arg(rlz.string)\n to_str = Arg(rlz.string)\n output_type = rlz.shape_like('arg', dt.string)\n\n\nclass LPad(ValueOp):\n arg = Arg(rlz.string)\n length = Arg(rlz.integer)\n pad = Arg(rlz.string, default=None)\n output_type = rlz.shape_like('arg', dt.string)\n\n\nclass RPad(ValueOp):\n arg = Arg(rlz.string)\n length = Arg(rlz.integer)\n pad = Arg(rlz.string, default=None)\n output_type = rlz.shape_like('arg', dt.string)\n\n\nclass FindInSet(ValueOp):\n needle = Arg(rlz.string)\n values = Arg(rlz.list_of(rlz.string, min_length=1))\n output_type = rlz.shape_like('needle', dt.int64)\n\n\nclass StringJoin(ValueOp):\n sep = Arg(rlz.string)\n arg = Arg(rlz.list_of(rlz.string, min_length=1))\n\n def output_type(self):\n return rlz.shape_like(tuple(self.flat_args()), dt.string)\n\n\nclass StartsWith(ValueOp):\n arg = Arg(rlz.string)\n start = Arg(rlz.string)\n output_type = rlz.shape_like(\"arg\", dt.boolean)\n\n\nclass EndsWith(ValueOp):\n arg = Arg(rlz.string)\n end = Arg(rlz.string)\n output_type = rlz.shape_like(\"arg\", dt.boolean)\n\n\nclass BooleanValueOp:\n pass\n\n\nclass FuzzySearch(ValueOp, BooleanValueOp):\n arg = Arg(rlz.string)\n pattern = Arg(rlz.string)\n output_type = rlz.shape_like('arg', dt.boolean)\n\n\nclass StringSQLLike(FuzzySearch):\n arg = Arg(rlz.string)\n pattern = Arg(rlz.string)\n escape = Arg(str, default=None)\n\n\nclass StringSQLILike(StringSQLLike):\n \"\"\"SQL ilike operation\"\"\"\n\n\nclass RegexSearch(FuzzySearch):\n pass\n\n\nclass RegexExtract(ValueOp):\n arg = Arg(rlz.string)\n pattern = Arg(rlz.string)\n index = Arg(rlz.integer)\n output_type = rlz.shape_like('arg', dt.string)\n\n\nclass RegexReplace(ValueOp):\n arg = Arg(rlz.string)\n pattern = Arg(rlz.string)\n replacement = Arg(rlz.string)\n output_type = rlz.shape_like('arg', dt.string)\n\n\nclass StringReplace(ValueOp):\n arg = Arg(rlz.string)\n pattern = Arg(rlz.string)\n replacement = Arg(rlz.string)\n output_type = rlz.shape_like('arg', dt.string)\n\n\nclass StringSplit(ValueOp):\n arg = Arg(rlz.string)\n delimiter = Arg(rlz.string)\n output_type = rlz.shape_like('arg', dt.Array(dt.string))\n\n\nclass StringConcat(ValueOp):\n arg = Arg(rlz.list_of(rlz.string))\n output_type = rlz.shape_like('arg', dt.string)\n\n\nclass ParseURL(ValueOp):\n arg = Arg(rlz.string)\n extract = Arg(\n rlz.isin(\n {\n 'PROTOCOL',\n 'HOST',\n 'PATH',\n 'REF',\n 'AUTHORITY',\n 'FILE',\n 'USERINFO',\n 'QUERY',\n }\n )\n )\n key = Arg(rlz.string, default=None)\n output_type = rlz.shape_like('arg', dt.string)\n\n\nclass StringLength(UnaryOp):\n\n \"\"\"\n Compute length of strings\n\n Returns\n -------\n length : int32\n \"\"\"\n\n output_type = rlz.shape_like('arg', dt.int32)\n\n\nclass StringAscii(UnaryOp):\n\n output_type = rlz.shape_like('arg', dt.int32)\n\n\n# ----------------------------------------------------------------------\n\n\nclass Reduction(ValueOp):\n _reduction = True\n\n\nclass Count(Reduction):\n arg = Arg((ir.ColumnExpr, ir.TableExpr))\n where = Arg(rlz.boolean, default=None)\n\n def output_type(self):\n return functools.partial(ir.IntegerScalar, dtype=dt.int64)\n\n\nclass Arbitrary(Reduction):\n arg = Arg(rlz.column(rlz.any))\n how = Arg(rlz.isin({'first', 'last', 'heavy'}), default=None)\n where = Arg(rlz.boolean, default=None)\n output_type = rlz.scalar_like('arg')\n\n\nclass BitAnd(Reduction):\n \"\"\"Aggregate bitwise AND operation.\n\n All elements in an integer column are ANDed together. This can be used\n to determine which bit flags are set on all elements.\n\n Resources:\n\n * `BigQuery BIT_AND\n <https://cloud.google.com/bigquery/docs/reference/standard-sql/aggregate_functions#bit_and>`_\n * `MySQL BIT_AND\n <https://dev.mysql.com/doc/refman/5.7/en/aggregate-functions.html#function_bit-and>`_\n \"\"\"\n\n arg = Arg(rlz.column(rlz.integer))\n where = Arg(rlz.boolean, default=None)\n output_type = rlz.scalar_like('arg')\n\n\nclass BitOr(Reduction):\n \"\"\"Aggregate bitwise OR operation.\n\n All elements in an integer column are ORed together. This can be used\n to determine which bit flags are set on any element.\n\n Resources:\n\n * `BigQuery BIT_OR\n <https://cloud.google.com/bigquery/docs/reference/standard-sql/aggregate_functions#bit_or>`_\n * `MySQL BIT_OR\n <https://dev.mysql.com/doc/refman/5.7/en/aggregate-functions.html#function_bit-or>`_\n \"\"\"\n\n arg = Arg(rlz.column(rlz.integer))\n where = Arg(rlz.boolean, default=None)\n output_type = rlz.scalar_like('arg')\n\n\nclass BitXor(Reduction):\n \"\"\"Aggregate bitwise XOR operation.\n\n All elements in an integer column are XORed together. This can be used\n as a parity checksum of element values.\n\n Resources:\n\n * `BigQuery BIT_XOR\n <https://cloud.google.com/bigquery/docs/reference/standard-sql/aggregate_functions#bit_xor>`_\n * `MySQL BIT_XOR\n <https://dev.mysql.com/doc/refman/5.7/en/aggregate-functions.html#function_bit-xor>`_\n \"\"\"\n\n arg = Arg(rlz.column(rlz.integer))\n where = Arg(rlz.boolean, default=None)\n output_type = rlz.scalar_like('arg')\n\n\nclass Sum(Reduction):\n arg = Arg(rlz.column(rlz.numeric))\n where = Arg(rlz.boolean, default=None)\n\n def output_type(self):\n if isinstance(self.arg, ir.BooleanValue):\n dtype = dt.int64\n else:\n dtype = self.arg.type().largest\n return dtype.scalar_type()\n\n\nclass Mean(Reduction):\n arg = Arg(rlz.column(rlz.numeric))\n where = Arg(rlz.boolean, default=None)\n\n def output_type(self):\n if isinstance(self.arg, ir.DecimalValue):\n dtype = self.arg.type()\n else:\n dtype = dt.float64\n return dtype.scalar_type()\n\n\nclass Quantile(Reduction):\n arg = Arg(rlz.any)\n quantile = Arg(rlz.strict_numeric)\n interpolation = Arg(\n rlz.isin({'linear', 'lower', 'higher', 'midpoint', 'nearest'}),\n default='linear',\n )\n\n def output_type(self):\n return dt.float64.scalar_type()\n\n\nclass MultiQuantile(Quantile):\n arg = Arg(rlz.any)\n quantile = Arg(rlz.value(dt.Array(dt.float64)))\n interpolation = Arg(\n rlz.isin({'linear', 'lower', 'higher', 'midpoint', 'nearest'}),\n default='linear',\n )\n\n def output_type(self):\n return dt.Array(dt.float64).scalar_type()\n\n\nclass VarianceBase(Reduction):\n arg = Arg(rlz.column(rlz.numeric))\n how = Arg(rlz.isin({'sample', 'pop'}), default=None)\n where = Arg(rlz.boolean, default=None)\n\n def output_type(self):\n if isinstance(self.arg, ir.DecimalValue):\n dtype = self.arg.type().largest\n else:\n dtype = dt.float64\n return dtype.scalar_type()\n\n\nclass StandardDev(VarianceBase):\n pass\n\n\nclass Variance(VarianceBase):\n pass\n\n\nclass Correlation(Reduction):\n \"\"\"Coefficient of correlation of a set of number pairs.\"\"\"\n\n left = Arg(rlz.column(rlz.numeric))\n right = Arg(rlz.column(rlz.numeric))\n how = Arg(rlz.isin({'sample', 'pop'}), default=None)\n where = Arg(rlz.boolean, default=None)\n\n def output_type(self):\n return dt.float64.scalar_type()\n\n\nclass Covariance(Reduction):\n \"\"\"Covariance of a set of number pairs.\"\"\"\n\n left = Arg(rlz.column(rlz.numeric))\n right = Arg(rlz.column(rlz.numeric))\n how = Arg(rlz.isin({'sample', 'pop'}), default=None)\n where = Arg(rlz.boolean, default=None)\n\n def output_type(self):\n return dt.float64.scalar_type()\n\n\nclass Max(Reduction):\n arg = Arg(rlz.column(rlz.any))\n where = Arg(rlz.boolean, default=None)\n output_type = rlz.scalar_like('arg')\n\n\nclass Min(Reduction):\n arg = Arg(rlz.column(rlz.any))\n where = Arg(rlz.boolean, default=None)\n output_type = rlz.scalar_like('arg')\n\n\nclass HLLCardinality(Reduction):\n \"\"\"Approximate number of unique values using HyperLogLog algorithm.\n\n Impala offers the NDV built-in function for this.\n \"\"\"\n\n arg = Arg(rlz.column(rlz.any))\n where = Arg(rlz.boolean, default=None)\n\n def output_type(self):\n # Impala 2.0 and higher returns a DOUBLE\n # return ir.DoubleScalar\n return functools.partial(ir.IntegerScalar, dtype=dt.int64)\n\n\nclass GroupConcat(Reduction):\n arg = Arg(rlz.column(rlz.any))\n sep = Arg(rlz.string, default=',')\n where = Arg(rlz.boolean, default=None)\n\n def output_type(self):\n return dt.string.scalar_type()\n\n\nclass CMSMedian(Reduction):\n \"\"\"\n Compute the approximate median of a set of comparable values using the\n Count-Min-Sketch algorithm. Exposed in Impala using APPX_MEDIAN.\n \"\"\"\n\n arg = Arg(rlz.column(rlz.any))\n where = Arg(rlz.boolean, default=None)\n output_type = rlz.scalar_like('arg')\n\n\n# ----------------------------------------------------------------------\n# Analytic functions\n\n\nclass AnalyticOp(ValueOp):\n pass\n\n\nclass WindowOp(ValueOp):\n expr = Arg(rlz.noop)\n window = Arg(rlz.noop)\n output_type = rlz.array_like('expr')\n\n display_argnames = False\n\n def __init__(self, expr, window):\n from ibis.expr.analysis import is_analytic\n from ibis.expr.window import propagate_down_window\n\n if not is_analytic(expr):\n raise com.IbisInputError(\n 'Expression does not contain a valid window operation'\n )\n\n table = ir.find_base_table(expr)\n if table is not None:\n window = window.bind(table)\n\n if window.max_lookback is not None:\n error_msg = (\n \"'max lookback' windows must be ordered \"\n \"by a timestamp column\"\n )\n if len(window._order_by) != 1:\n raise com.IbisInputError(error_msg)\n order_var = window._order_by[0].op().args[0]\n if not isinstance(order_var.type(), dt.Timestamp):\n raise com.IbisInputError(error_msg)\n\n expr = propagate_down_window(expr, window)\n super().__init__(expr, window)\n\n def over(self, window):\n new_window = self.window.combine(window)\n return WindowOp(self.expr, new_window)\n\n @property\n def inputs(self):\n return self.expr.op().inputs[0], self.window\n\n def root_tables(self):\n return distinct_roots(\n self.expr, *self.window._order_by, *self.window._group_by\n )\n\n\nclass ShiftBase(AnalyticOp):\n arg = Arg(rlz.column(rlz.any))\n offset = Arg(rlz.one_of((rlz.integer, rlz.interval)), default=None)\n default = Arg(rlz.any, default=None)\n output_type = rlz.typeof('arg')\n\n\nclass Lag(ShiftBase):\n pass\n\n\nclass Lead(ShiftBase):\n pass\n\n\nclass RankBase(AnalyticOp):\n def output_type(self):\n return dt.int64.column_type()\n\n\nclass MinRank(RankBase):\n \"\"\"\n Compute position of first element within each equal-value group in sorted\n order.\n\n Examples\n --------\n values ranks\n 1 0\n 1 0\n 2 2\n 2 2\n 2 2\n 3 5\n\n Returns\n -------\n ranks : Int64Column, starting from 0\n \"\"\"\n\n # Equivalent to SQL RANK()\n arg = Arg(rlz.column(rlz.any))\n\n\nclass DenseRank(RankBase):\n \"\"\"\n Compute position of first element within each equal-value group in sorted\n order, ignoring duplicate values.\n\n Examples\n --------\n values ranks\n 1 0\n 1 0\n 2 1\n 2 1\n 2 1\n 3 2\n\n Returns\n -------\n ranks : Int64Column, starting from 0\n \"\"\"\n\n # Equivalent to SQL DENSE_RANK()\n arg = Arg(rlz.column(rlz.any))\n\n\nclass RowNumber(RankBase):\n \"\"\"\n Compute row number starting from 0 after sorting by column expression\n\n Examples\n --------\n >>> import ibis\n >>> t = ibis.table([('values', dt.int64)])\n >>> w = ibis.window(order_by=t.values)\n >>> row_num = ibis.row_number().over(w)\n >>> result = t[t.values, row_num.name('row_num')]\n\n Returns\n -------\n row_number : Int64Column, starting from 0\n \"\"\"\n\n # Equivalent to SQL ROW_NUMBER()\n\n\nclass CumulativeOp(AnalyticOp):\n pass\n\n\nclass CumulativeSum(CumulativeOp):\n \"\"\"Cumulative sum. Requires an order window.\"\"\"\n\n arg = Arg(rlz.column(rlz.numeric))\n\n def output_type(self):\n if isinstance(self.arg, ir.BooleanValue):\n dtype = dt.int64\n else:\n dtype = self.arg.type().largest\n return dtype.column_type()\n\n\nclass CumulativeMean(CumulativeOp):\n \"\"\"Cumulative mean. Requires an order window.\"\"\"\n\n arg = Arg(rlz.column(rlz.numeric))\n\n def output_type(self):\n if isinstance(self.arg, ir.DecimalValue):\n dtype = self.arg.type().largest\n else:\n dtype = dt.float64\n return dtype.column_type()\n\n\nclass CumulativeMax(CumulativeOp):\n \"\"\"Cumulative max. Requires an order window.\"\"\"\n\n arg = Arg(rlz.column(rlz.any))\n output_type = rlz.array_like('arg')\n\n\nclass CumulativeMin(CumulativeOp):\n \"\"\"Cumulative min. Requires an order window.\"\"\"\n\n arg = Arg(rlz.column(rlz.any))\n output_type = rlz.array_like('arg')\n\n\nclass PercentRank(AnalyticOp):\n arg = Arg(rlz.column(rlz.any))\n output_type = rlz.shape_like('arg', dt.double)\n\n\nclass NTile(AnalyticOp):\n arg = Arg(rlz.column(rlz.any))\n buckets = Arg(rlz.integer)\n output_type = rlz.shape_like('arg', dt.int64)\n\n\nclass FirstValue(AnalyticOp):\n arg = Arg(rlz.column(rlz.any))\n output_type = rlz.typeof('arg')\n\n\nclass LastValue(AnalyticOp):\n arg = Arg(rlz.column(rlz.any))\n output_type = rlz.typeof('arg')\n\n\nclass NthValue(AnalyticOp):\n arg = Arg(rlz.column(rlz.any))\n nth = Arg(rlz.integer)\n output_type = rlz.typeof('arg')\n\n\n# ----------------------------------------------------------------------\n# Distinct stuff\n\n\nclass Distinct(TableNode, HasSchema):\n \"\"\"\n Distinct is a table-level unique-ing operation.\n\n In SQL, you might have:\n\n SELECT DISTINCT foo\n FROM table\n\n SELECT DISTINCT foo, bar\n FROM table\n \"\"\"\n\n table = Arg(ir.TableExpr)\n\n def _validate(self):\n # check whether schema has overlapping columns or not\n assert self.schema\n\n @cached_property\n def schema(self):\n return self.table.schema()\n\n def blocks(self):\n return True\n\n\nclass DistinctColumn(ValueOp):\n\n \"\"\"\n COUNT(DISTINCT ...) is really just syntactic suger, but we provide a\n distinct().count() nicety for users nonetheless.\n\n For all intents and purposes, like Distinct, but can be distinguished later\n for evaluation if the result should be array-like versus table-like. Also\n for calling count()\n \"\"\"\n\n arg = Arg(rlz.noop)\n output_type = rlz.typeof('arg')\n\n def count(self):\n \"\"\"Only valid if the distinct contains a single column\"\"\"\n return CountDistinct(self.arg)\n\n\nclass CountDistinct(Reduction):\n arg = Arg(rlz.column(rlz.any))\n where = Arg(rlz.boolean, default=None)\n\n def output_type(self):\n return dt.int64.scalar_type()\n\n\n# ---------------------------------------------------------------------\n# Boolean reductions and semi/anti join support\n\n\nclass Any(ValueOp):\n\n # Depending on the kind of input boolean array, the result might either be\n # array-like (an existence-type predicate) or scalar (a reduction)\n arg = Arg(rlz.column(rlz.boolean))\n\n @property\n def _reduction(self):\n roots = self.arg.op().root_tables()\n return len(roots) < 2\n\n def output_type(self):\n if self._reduction:\n return dt.boolean.scalar_type()\n else:\n return dt.boolean.column_type()\n\n def negate(self):\n return NotAny(self.arg)\n\n\nclass All(ValueOp):\n arg = Arg(rlz.column(rlz.boolean))\n output_type = rlz.scalar_like('arg')\n _reduction = True\n\n def negate(self):\n return NotAll(self.arg)\n\n\nclass NotAny(Any):\n def negate(self):\n return Any(self.arg)\n\n\nclass NotAll(All):\n def negate(self):\n return All(self.arg)\n\n\nclass CumulativeAny(CumulativeOp):\n arg = Arg(rlz.column(rlz.boolean))\n output_type = rlz.typeof('arg')\n\n\nclass CumulativeAll(CumulativeOp):\n arg = Arg(rlz.column(rlz.boolean))\n output_type = rlz.typeof('arg')\n\n\n# ---------------------------------------------------------------------\n\n\nclass TypedCaseBuilder:\n __slots__ = ()\n\n def type(self):\n types = [result.type() for result in self.results]\n return dt.highest_precedence(types)\n\n def else_(self, result_expr):\n \"\"\"\n Specify\n\n Returns\n -------\n builder : CaseBuilder\n \"\"\"\n kwargs = {\n slot: getattr(self, slot)\n for slot in self.__slots__\n if slot != 'default'\n }\n\n result_expr = ir.as_value_expr(result_expr)\n kwargs['default'] = result_expr\n # Maintain immutability\n return type(self)(**kwargs)\n\n def end(self):\n default = self.default\n if default is None:\n default = ir.null().cast(self.type())\n\n args = [\n getattr(self, slot) for slot in self.__slots__ if slot != 'default'\n ]\n args.append(default)\n op = self.__class__.case_op(*args)\n return op.to_expr()\n\n\nclass SimpleCase(ValueOp):\n base = Arg(rlz.any)\n cases = Arg(rlz.list_of(rlz.any))\n results = Arg(rlz.list_of(rlz.any))\n default = Arg(rlz.any)\n\n def _validate(self):\n assert len(self.cases) == len(self.results)\n\n def root_tables(self):\n return distinct_roots(\n *itertools.chain(\n [self.base],\n self.cases,\n self.results,\n [] if self.default is None else [self.default],\n )\n )\n\n def output_type(self):\n exprs = self.results + [self.default]\n return rlz.shape_like(self.base, dtype=exprs.type())\n\n\nclass SimpleCaseBuilder(TypedCaseBuilder):\n __slots__ = 'base', 'cases', 'results', 'default'\n\n case_op = SimpleCase\n\n def __init__(self, base, cases=None, results=None, default=None):\n self.base = base\n self.cases = list(cases if cases is not None else [])\n self.results = list(results if results is not None else [])\n self.default = default\n\n def when(self, case_expr, result_expr):\n \"\"\"\n Add a new case-result pair.\n\n Parameters\n ----------\n case : Expr\n Expression to equality-compare with base expression. Must be\n comparable with the base.\n result : Expr\n Value when the case predicate evaluates to true.\n\n Returns\n -------\n builder : CaseBuilder\n \"\"\"\n case_expr = ir.as_value_expr(case_expr)\n result_expr = ir.as_value_expr(result_expr)\n\n if not rlz.comparable(self.base, case_expr):\n raise TypeError(\n 'Base expression and passed case are not ' 'comparable'\n )\n\n cases = list(self.cases)\n cases.append(case_expr)\n\n results = list(self.results)\n results.append(result_expr)\n\n # Maintain immutability\n return type(self)(self.base, cases, results, self.default)\n\n\nclass SearchedCase(ValueOp):\n cases = Arg(rlz.list_of(rlz.boolean))\n results = Arg(rlz.list_of(rlz.any))\n default = Arg(rlz.any)\n\n def _validate(self):\n assert len(self.cases) == len(self.results)\n\n def root_tables(self):\n cases, results, default = self.args\n return distinct_roots(\n *itertools.chain(\n cases.values,\n results.values,\n [] if default is None else [default],\n )\n )\n\n def output_type(self):\n exprs = self.results + [self.default]\n dtype = rlz.highest_precedence_dtype(exprs)\n return rlz.shape_like(self.cases, dtype)\n\n\nclass SearchedCaseBuilder(TypedCaseBuilder):\n __slots__ = 'cases', 'results', 'default'\n\n case_op = SearchedCase\n\n def __init__(self, cases=None, results=None, default=None):\n self.cases = list(cases if cases is not None else [])\n self.results = list(results if results is not None else [])\n self.default = default\n\n def when(self, case_expr, result_expr):\n \"\"\"\n Add a new case-result pair.\n\n Parameters\n ----------\n case : Expr\n Expression to equality-compare with base expression. Must be\n comparable with the base.\n result : Expr\n Value when the case predicate evaluates to true.\n\n Returns\n -------\n builder : CaseBuilder\n \"\"\"\n case_expr = ir.as_value_expr(case_expr)\n result_expr = ir.as_value_expr(result_expr)\n\n if not isinstance(case_expr, ir.BooleanValue):\n raise TypeError(case_expr)\n\n cases = list(self.cases)\n cases.append(case_expr)\n\n results = list(self.results)\n results.append(result_expr)\n\n # Maintain immutability\n return type(self)(cases, results, self.default)\n\n\nclass Where(ValueOp):\n\n \"\"\"\n Ternary case expression, equivalent to\n\n bool_expr.case()\n .when(True, true_expr)\n .else_(false_or_null_expr)\n \"\"\"\n\n bool_expr = Arg(rlz.boolean)\n true_expr = Arg(rlz.any)\n false_null_expr = Arg(rlz.any)\n\n def output_type(self):\n return rlz.shape_like(self.bool_expr, self.true_expr.type())\n\n\ndef _validate_join_tables(left, right):\n if not isinstance(left, ir.TableExpr):\n raise TypeError(\n 'Can only join table expressions, got {} for '\n 'left table'.format(type(left).__name__)\n )\n\n if not isinstance(right, ir.TableExpr):\n raise TypeError(\n 'Can only join table expressions, got {} for '\n 'right table'.format(type(right).__name__)\n )\n\n\ndef _make_distinct_join_predicates(left, right, predicates):\n # see GH #667\n\n # If left and right table have a common parent expression (e.g. they\n # have different filters), must add a self-reference and make the\n # appropriate substitution in the join predicates\n\n if left.equals(right):\n right = right.view()\n\n predicates = _clean_join_predicates(left, right, predicates)\n return left, right, predicates\n\n\ndef _clean_join_predicates(left, right, predicates):\n import ibis.expr.analysis as L\n\n result = []\n\n if not isinstance(predicates, (list, tuple)):\n predicates = [predicates]\n\n for pred in predicates:\n if isinstance(pred, tuple):\n if len(pred) != 2:\n raise com.ExpressionError('Join key tuple must be ' 'length 2')\n lk, rk = pred\n lk = left._ensure_expr(lk)\n rk = right._ensure_expr(rk)\n pred = lk == rk\n elif isinstance(pred, str):\n pred = left[pred] == right[pred]\n elif not isinstance(pred, ir.Expr):\n raise NotImplementedError\n\n if not isinstance(pred, ir.BooleanColumn):\n raise com.ExpressionError('Join predicate must be comparison')\n\n preds = L.flatten_predicate(pred)\n result.extend(preds)\n\n _validate_join_predicates(left, right, result)\n return result\n\n\ndef _validate_join_predicates(left, right, predicates):\n from ibis.expr.analysis import fully_originate_from\n\n # Validate join predicates. Each predicate must be valid jointly when\n # considering the roots of each input table\n for predicate in predicates:\n if not fully_originate_from(predicate, [left, right]):\n raise com.RelationError(\n 'The expression {!r} does not fully '\n 'originate from dependencies of the table '\n 'expression.'.format(predicate)\n )\n\n\nclass Join(TableNode):\n left = Arg(rlz.noop)\n right = Arg(rlz.noop)\n predicates = Arg(rlz.noop)\n\n def __init__(self, left, right, predicates):\n _validate_join_tables(left, right)\n left, right, predicates = _make_distinct_join_predicates(\n left, right, predicates\n )\n super().__init__(left, right, predicates)\n\n def _get_schema(self):\n # For joins retaining both table schemas, merge them together here\n left = self.left\n right = self.right\n\n if not left._is_materialized():\n left = left.materialize()\n\n if not right._is_materialized():\n right = right.materialize()\n\n sleft = left.schema()\n sright = right.schema()\n\n overlap = set(sleft.names) & set(sright.names)\n if overlap:\n raise com.RelationError(\n 'Joined tables have overlapping names: %s' % str(list(overlap))\n )\n\n return sleft.append(sright)\n\n def has_schema(self):\n return False\n\n def root_tables(self):\n if util.all_of([self.left.op(), self.right.op()], (Join, Selection)):\n # Unraveling is not possible\n return [self.left.op(), self.right.op()]\n else:\n return distinct_roots(self.left, self.right)\n\n\nclass InnerJoin(Join):\n pass\n\n\nclass LeftJoin(Join):\n pass\n\n\nclass RightJoin(Join):\n pass\n\n\nclass OuterJoin(Join):\n pass\n\n\nclass AnyInnerJoin(Join):\n pass\n\n\nclass AnyLeftJoin(Join):\n pass\n\n\nclass LeftSemiJoin(Join):\n def _get_schema(self):\n return self.left.schema()\n\n\nclass LeftAntiJoin(Join):\n def _get_schema(self):\n return self.left.schema()\n\n\nclass MaterializedJoin(TableNode, HasSchema):\n join = Arg(ir.TableExpr)\n\n def _validate(self):\n assert isinstance(self.join.op(), Join)\n # check whether the underlying schema has overlapping columns or not\n assert self.schema\n\n @cached_property\n def schema(self):\n return self.join.op()._get_schema()\n\n def root_tables(self):\n return self.join.op().root_tables()\n\n def blocks(self):\n return True\n\n\nclass CrossJoin(InnerJoin):\n\n \"\"\"\n Some databases have a CROSS JOIN operator, that may be preferential to use\n over an INNER JOIN with no predicates.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n if 'prefixes' in kwargs:\n raise NotImplementedError\n\n if len(args) < 2:\n raise com.IbisInputError('Must pass at least 2 tables')\n\n left = args[0]\n right = args[1]\n for t in args[2:]:\n right = right.cross_join(t)\n InnerJoin.__init__(self, left, right, [])\n\n\nclass AsOfJoin(Join):\n left = Arg(rlz.noop)\n right = Arg(rlz.noop)\n predicates = Arg(rlz.noop)\n by = Arg(rlz.noop, default=None)\n tolerance = Arg(rlz.interval(), default=None)\n\n def __init__(self, left, right, predicates, by, tolerance):\n super().__init__(left, right, predicates)\n self.by = _clean_join_predicates(self.left, self.right, by)\n self.tolerance = tolerance\n self._validate_args(['by', 'tolerance'])\n\n def _validate_args(self, args: List[str]):\n for arg in args:\n argument = self.signature[arg]\n value = argument.validate(getattr(self, arg))\n setattr(self, arg, value)\n\n\nclass SetOp(TableNode, HasSchema):\n left = Arg(rlz.noop)\n right = Arg(rlz.noop)\n\n def _validate(self):\n if not self.left.schema().equals(self.right.schema()):\n raise com.RelationError(\n 'Table schemas must be equal for set operations'\n )\n\n @cached_property\n def schema(self):\n return self.left.schema()\n\n def blocks(self):\n return True\n\n\nclass Union(SetOp):\n distinct = Arg(rlz.validator(bool), default=False)\n\n\nclass Intersection(SetOp):\n pass\n\n\nclass Difference(SetOp):\n pass\n\n\nclass Limit(TableNode):\n table = Arg(ir.TableExpr)\n n = Arg(rlz.validator(int))\n offset = Arg(rlz.validator(int))\n\n def blocks(self):\n return True\n\n @property\n def schema(self):\n return self.table.schema()\n\n def has_schema(self):\n return self.table.op().has_schema()\n\n def root_tables(self):\n return [self]\n\n\n# --------------------------------------------------------------------\n# Sorting\n\n\ndef to_sort_key(table, key):\n if isinstance(key, DeferredSortKey):\n key = key.resolve(table)\n\n if isinstance(key, ir.SortExpr):\n return key\n\n if isinstance(key, (tuple, list)):\n key, sort_order = key\n else:\n sort_order = True\n\n if not isinstance(key, ir.Expr):\n key = table._ensure_expr(key)\n if isinstance(key, (ir.SortExpr, DeferredSortKey)):\n return to_sort_key(table, key)\n\n if isinstance(sort_order, str):\n if sort_order.lower() in ('desc', 'descending'):\n sort_order = False\n elif not isinstance(sort_order, bool):\n sort_order = bool(sort_order)\n\n return SortKey(key, ascending=sort_order).to_expr()\n\n\nclass SortKey(Node):\n expr = Arg(rlz.column(rlz.any))\n ascending = Arg(rlz.validator(bool), default=True)\n\n def __repr__(self):\n # Temporary\n rows = [\n 'Sort key:',\n ' ascending: {0!s}'.format(self.ascending),\n util.indent(_safe_repr(self.expr), 2),\n ]\n return '\\n'.join(rows)\n\n def output_type(self):\n return ir.SortExpr\n\n def root_tables(self):\n return self.expr.op().root_tables()\n\n def equals(self, other, cache=None):\n # TODO: might generalize this equals based on fields\n # requires a proxy class with equals for non expr values\n return (\n isinstance(other, SortKey)\n and self.expr.equals(other.expr, cache=cache)\n and self.ascending == other.ascending\n )\n\n def resolve_name(self):\n return self.expr.get_name()\n\n\nclass DeferredSortKey:\n def __init__(self, what, ascending=True):\n self.what = what\n self.ascending = ascending\n\n def resolve(self, parent):\n what = parent._ensure_expr(self.what)\n return SortKey(what, ascending=self.ascending).to_expr()\n\n\nclass SelfReference(TableNode, HasSchema):\n table = Arg(ir.TableExpr)\n\n @cached_property\n def schema(self):\n return self.table.schema()\n\n def root_tables(self):\n # The dependencies of this operation are not walked, which makes the\n # table expression holding this relationally distinct from other\n # expressions, so things like self-joins are possible\n return [self]\n\n def blocks(self):\n return True\n\n\nclass Selection(TableNode, HasSchema):\n table = Arg(ir.TableExpr)\n selections = Arg(rlz.noop, default=None)\n predicates = Arg(rlz.noop, default=None)\n sort_keys = Arg(rlz.noop, default=None)\n\n def __init__(\n self, table, selections=None, predicates=None, sort_keys=None\n ):\n import ibis.expr.analysis as L\n\n # Argument cleaning\n selections = util.promote_list(\n selections if selections is not None else []\n )\n\n projections = []\n for selection in selections:\n if isinstance(selection, str):\n projection = table[selection]\n else:\n projection = selection\n projections.append(projection)\n\n sort_keys = [\n to_sort_key(table, k)\n for k in util.promote_list(\n sort_keys if sort_keys is not None else []\n )\n ]\n\n predicates = list(\n toolz.concat(\n map(\n L.flatten_predicate,\n predicates if predicates is not None else [],\n )\n )\n )\n\n super().__init__(\n table=table,\n selections=projections,\n predicates=predicates,\n sort_keys=sort_keys,\n )\n\n def _validate(self):\n from ibis.expr.analysis import FilterValidator\n\n # Need to validate that the column expressions are compatible with the\n # input table; this means they must either be scalar expressions or\n # array expressions originating from the same root table expression\n dependent_exprs = self.selections + self.sort_keys\n self.table._assert_valid(dependent_exprs)\n\n # Validate predicates\n validator = FilterValidator([self.table])\n validator.validate_all(self.predicates)\n\n # Validate no overlapping columns in schema\n assert self.schema\n\n @cached_property\n def schema(self):\n # Resolve schema and initialize\n if not self.selections:\n return self.table.schema()\n\n types = []\n names = []\n\n for projection in self.selections:\n if isinstance(projection, ir.DestructColumn):\n # If this is a destruct, then we destructure\n # the result and assign to multiple columns\n struct_type = projection.type()\n for name in struct_type.names:\n names.append(name)\n types.append(struct_type[name])\n elif isinstance(projection, ir.ValueExpr):\n names.append(projection.get_name())\n types.append(projection.type())\n elif isinstance(projection, ir.TableExpr):\n schema = projection.schema()\n names.extend(schema.names)\n types.extend(schema.types)\n\n return Schema(names, types)\n\n def blocks(self):\n return bool(self.selections)\n\n def substitute_table(self, table_expr):\n return Selection(table_expr, self.selections)\n\n def root_tables(self):\n return [self]\n\n def can_add_filters(self, wrapped_expr, predicates):\n pass\n\n @staticmethod\n def empty_or_equal(lefts, rights):\n return not lefts or not rights or all_equal(lefts, rights)\n\n def compatible_with(self, other):\n # self and other are equivalent except for predicates, selections, or\n # sort keys any of which is allowed to be empty. If both are not empty\n # then they must be equal\n if self.equals(other):\n return True\n\n if not isinstance(other, type(self)):\n return False\n\n return self.table.equals(other.table) and (\n self.empty_or_equal(self.predicates, other.predicates)\n and self.empty_or_equal(self.selections, other.selections)\n and self.empty_or_equal(self.sort_keys, other.sort_keys)\n )\n\n # Operator combination / fusion logic\n\n def aggregate(self, this, metrics, by=None, having=None):\n if len(self.selections) > 0:\n return Aggregation(this, metrics, by=by, having=having)\n else:\n helper = AggregateSelection(this, metrics, by, having)\n return helper.get_result()\n\n def sort_by(self, expr, sort_exprs):\n sort_exprs = util.promote_list(sort_exprs)\n if not self.blocks():\n resolved_keys = _maybe_convert_sort_keys(self.table, sort_exprs)\n if resolved_keys and self.table._is_valid(resolved_keys):\n return Selection(\n self.table,\n self.selections,\n predicates=self.predicates,\n sort_keys=self.sort_keys + resolved_keys,\n )\n\n return Selection(expr, [], sort_keys=sort_exprs)\n\n\nclass AggregateSelection:\n # sort keys cannot be discarded because of order-dependent\n # aggregate functions like GROUP_CONCAT\n\n def __init__(self, parent, metrics, by, having):\n self.parent = parent\n self.op = parent.op()\n self.metrics = metrics\n self.by = by\n self.having = having\n\n def get_result(self):\n if self.op.blocks():\n return self._plain_subquery()\n else:\n return self._attempt_pushdown()\n\n def _plain_subquery(self):\n return Aggregation(\n self.parent, self.metrics, by=self.by, having=self.having\n )\n\n def _attempt_pushdown(self):\n metrics_valid, lowered_metrics = self._pushdown_exprs(self.metrics)\n by_valid, lowered_by = self._pushdown_exprs(self.by)\n having_valid, lowered_having = self._pushdown_exprs(\n self.having or None\n )\n\n if metrics_valid and by_valid and having_valid:\n return Aggregation(\n self.op.table,\n lowered_metrics,\n by=lowered_by,\n having=lowered_having,\n predicates=self.op.predicates,\n sort_keys=self.op.sort_keys,\n )\n else:\n return self._plain_subquery()\n\n def _pushdown_exprs(self, exprs):\n import ibis.expr.analysis as L\n\n if exprs is None:\n return True, []\n\n resolved = self.op.table._resolve(exprs)\n subbed_exprs = []\n\n valid = False\n if resolved:\n for x in util.promote_list(resolved):\n subbed = L.sub_for(x, [(self.parent, self.op.table)])\n subbed_exprs.append(subbed)\n valid = self.op.table._is_valid(subbed_exprs)\n else:\n valid = False\n\n return valid, subbed_exprs\n\n\ndef _maybe_convert_sort_keys(table, exprs):\n try:\n return [to_sort_key(table, k) for k in util.promote_list(exprs)]\n except com.IbisError:\n return None\n\n\nclass Aggregation(TableNode, HasSchema):\n\n \"\"\"\n metrics : per-group scalar aggregates\n by : group expressions\n having : post-aggregation predicate\n\n TODO: not putting this in the aggregate operation yet\n where : pre-aggregation predicate\n \"\"\"\n\n table = Arg(ir.TableExpr)\n metrics = Arg(rlz.noop)\n by = Arg(rlz.noop)\n having = Arg(rlz.noop, default=None)\n predicates = Arg(rlz.noop, default=None)\n sort_keys = Arg(rlz.noop, default=None)\n\n def __init__(\n self,\n table,\n metrics,\n by=None,\n having=None,\n predicates=None,\n sort_keys=None,\n ):\n # For tables, like joins, that are not materialized\n metrics = self._rewrite_exprs(table, metrics)\n\n by = [] if by is None else by\n by = table._resolve(by)\n\n having = [] if having is None else having\n predicates = [] if predicates is None else predicates\n\n # order by only makes sense with group by in an aggregation\n sort_keys = [] if not by or sort_keys is None else sort_keys\n sort_keys = [\n to_sort_key(table, k) for k in util.promote_list(sort_keys)\n ]\n\n by = self._rewrite_exprs(table, by)\n having = self._rewrite_exprs(table, having)\n predicates = self._rewrite_exprs(table, predicates)\n sort_keys = self._rewrite_exprs(table, sort_keys)\n\n super().__init__(\n table=table,\n metrics=metrics,\n by=by,\n having=having,\n predicates=predicates,\n sort_keys=sort_keys,\n )\n\n def _validate(self):\n from ibis.expr.analysis import FilterValidator, is_reduction\n\n # All aggregates are valid\n for expr in self.metrics:\n if not isinstance(expr, ir.ScalarExpr) or not is_reduction(expr):\n raise TypeError(\n 'Passed a non-aggregate expression: %s' % _safe_repr(expr)\n )\n\n for expr in self.having:\n if not isinstance(expr, ir.BooleanScalar):\n raise com.ExpressionError(\n 'Having clause must be boolean '\n 'expression, was: {0!s}'.format(_safe_repr(expr))\n )\n\n # All non-scalar refs originate from the input table\n all_exprs = self.metrics + self.by + self.having + self.sort_keys\n self.table._assert_valid(all_exprs)\n\n # Validate predicates\n validator = FilterValidator([self.table])\n validator.validate_all(self.predicates)\n\n # Validate schema has no overlapping columns\n assert self.schema\n\n def _rewrite_exprs(self, table, what):\n what = util.promote_list(what)\n\n all_exprs = []\n for expr in what:\n if isinstance(expr, ir.ExprList):\n all_exprs.extend(expr.exprs())\n else:\n bound_expr = ir.bind_expr(table, expr)\n all_exprs.append(bound_expr)\n\n return all_exprs\n # TODO - #2832\n # this optimization becomes O(n^2) when it calls into\n # _lift_TableColumn in analysis.py, which itself is O(n) and is\n # called on each input to the aggregation - thus creating the\n # aggregation expression can be extremely slow on wide tables\n # that contain a Selection.\n # return [\n # substitute_parents(x, past_projection=False) for x in all_exprs\n # ]\n\n def blocks(self):\n return True\n\n def substitute_table(self, table_expr):\n return Aggregation(\n table_expr, self.metrics, by=self.by, having=self.having\n )\n\n @cached_property\n def schema(self):\n names = []\n types = []\n\n for e in self.by + self.metrics:\n if isinstance(e, ir.DestructValue):\n # If this is a destruct, then we destructure\n # the result and assign to multiple columns\n struct_type = e.type()\n for name in struct_type.names:\n names.append(name)\n types.append(struct_type[name])\n else:\n names.append(e.get_name())\n types.append(e.type())\n\n return Schema(names, types)\n\n def sort_by(self, expr, sort_exprs):\n sort_exprs = util.promote_list(sort_exprs)\n\n resolved_keys = _maybe_convert_sort_keys(self.table, sort_exprs)\n if resolved_keys and self.table._is_valid(resolved_keys):\n return Aggregation(\n self.table,\n self.metrics,\n by=self.by,\n having=self.having,\n predicates=self.predicates,\n sort_keys=self.sort_keys + resolved_keys,\n )\n\n return Selection(expr, [], sort_keys=sort_exprs)\n\n\nclass NumericBinaryOp(BinaryOp):\n left = Arg(rlz.numeric)\n right = Arg(rlz.numeric)\n\n\nclass Add(NumericBinaryOp):\n output_type = rlz.numeric_like('args', operator.add)\n\n\nclass Multiply(NumericBinaryOp):\n output_type = rlz.numeric_like('args', operator.mul)\n\n\nclass Power(NumericBinaryOp):\n def output_type(self):\n if util.all_of(self.args, ir.IntegerValue):\n return rlz.shape_like(self.args, dt.float64)\n else:\n return rlz.shape_like(self.args)\n\n\nclass Subtract(NumericBinaryOp):\n output_type = rlz.numeric_like('args', operator.sub)\n\n\nclass Divide(NumericBinaryOp):\n output_type = rlz.shape_like('args', dt.float64)\n\n\nclass FloorDivide(Divide):\n output_type = rlz.shape_like('args', dt.int64)\n\n\nclass LogicalBinaryOp(BinaryOp):\n left = Arg(rlz.boolean)\n right = Arg(rlz.boolean)\n output_type = rlz.shape_like('args', dt.boolean)\n\n\nclass Not(UnaryOp):\n arg = Arg(rlz.boolean)\n output_type = rlz.shape_like('arg', dt.boolean)\n\n\nclass Modulus(NumericBinaryOp):\n output_type = rlz.numeric_like('args', operator.mod)\n\n\nclass And(LogicalBinaryOp):\n pass\n\n\nclass Or(LogicalBinaryOp):\n pass\n\n\nclass Xor(LogicalBinaryOp):\n pass\n\n\nclass Comparison(BinaryOp, BooleanValueOp):\n left = Arg(rlz.any)\n right = Arg(rlz.any)\n\n def __init__(self, left, right):\n \"\"\"\n Casting rules for type promotions (for resolving the output type) may\n depend in some cases on the target backend.\n\n TODO: how will overflows be handled? Can we provide anything useful in\n Ibis to help the user avoid them?\n\n :param left:\n :param right:\n \"\"\"\n super().__init__(*self._maybe_cast_args(left, right))\n\n def _maybe_cast_args(self, left, right):\n # it might not be necessary?\n with suppress(com.IbisTypeError):\n return left, rlz.cast(right, left)\n\n with suppress(com.IbisTypeError):\n return rlz.cast(left, right), right\n\n return left, right\n\n def output_type(self):\n if not rlz.comparable(self.left, self.right):\n raise TypeError(\n 'Arguments with datatype {} and {} are '\n 'not comparable'.format(self.left.type(), self.right.type())\n )\n return rlz.shape_like(self.args, dt.boolean)\n\n\nclass Equals(Comparison):\n pass\n\n\nclass NotEquals(Comparison):\n pass\n\n\nclass GreaterEqual(Comparison):\n pass\n\n\nclass Greater(Comparison):\n pass\n\n\nclass LessEqual(Comparison):\n pass\n\n\nclass Less(Comparison):\n pass\n\n\nclass IdenticalTo(Comparison):\n pass\n\n\nclass Between(ValueOp, BooleanValueOp):\n arg = Arg(rlz.any)\n lower_bound = Arg(rlz.any)\n upper_bound = Arg(rlz.any)\n\n def output_type(self):\n arg, lower, upper = self.args\n\n if not (rlz.comparable(arg, lower) and rlz.comparable(arg, upper)):\n raise TypeError('Arguments are not comparable')\n\n return rlz.shape_like(self.args, dt.boolean)\n\n\nclass BetweenTime(Between):\n arg = Arg(rlz.one_of([rlz.timestamp, rlz.time]))\n lower_bound = Arg(rlz.one_of([rlz.time, rlz.string]))\n upper_bound = Arg(rlz.one_of([rlz.time, rlz.string]))\n\n\nclass Contains(ValueOp, BooleanValueOp):\n value = Arg(rlz.any)\n options = Arg(\n rlz.one_of(\n [\n rlz.list_of(rlz.any),\n rlz.set_,\n rlz.column(rlz.any),\n rlz.array_of(rlz.any),\n ]\n )\n )\n\n def __init__(self, value, options):\n # it can be a single expression, like a column\n if not isinstance(options, ir.Expr):\n if util.any_of(options, ir.Expr):\n # or a list of expressions\n options = ir.sequence(options)\n else:\n # or a set of scalar values\n options = frozenset(options)\n super().__init__(value, options)\n\n def output_type(self):\n all_args = [self.value]\n\n if isinstance(self.options, ir.ListExpr):\n all_args += self.options\n else:\n all_args += [self.options]\n\n return rlz.shape_like(all_args, dt.boolean)\n\n\nclass NotContains(Contains):\n pass\n\n\nclass ReplaceValues(ValueOp):\n\n \"\"\"\n Apply a multi-value replacement on a particular column. As an example from\n SQL, given DAYOFWEEK(timestamp_col), replace 1 through 5 to \"WEEKDAY\" and 6\n and 7 to \"WEEKEND\"\n \"\"\"\n\n pass\n\n\nclass SummaryFilter(ValueOp):\n expr = Arg(rlz.noop)\n\n def output_type(self):\n return dt.boolean.column_type()\n\n\nclass TopK(ValueOp):\n arg = Arg(rlz.noop)\n k = Arg(int)\n by = Arg(rlz.noop)\n\n def __init__(self, arg, k, by=None):\n if by is None:\n by = arg.count()\n\n if not isinstance(arg, ir.ColumnExpr):\n raise TypeError(arg)\n\n if not isinstance(k, int) or k < 0:\n raise ValueError('k must be positive integer, was: {0}'.format(k))\n\n super().__init__(arg, k, by)\n\n def output_type(self):\n return ir.TopKExpr\n\n def blocks(self):\n return True\n\n\nclass Constant(ValueOp):\n pass\n\n\nclass TimestampNow(Constant):\n def output_type(self):\n return dt.timestamp.scalar_type()\n\n\nclass RandomScalar(Constant):\n def output_type(self):\n return dt.float64.scalar_type()\n\n\nclass E(Constant):\n def output_type(self):\n return functools.partial(ir.FloatingScalar, dtype=dt.float64)\n\n\nclass Pi(Constant):\n \"\"\"\n The constant pi\n \"\"\"\n\n def output_type(self):\n return functools.partial(ir.FloatingScalar, dtype=dt.float64)\n\n\nclass TemporalUnaryOp(UnaryOp):\n arg = Arg(rlz.temporal)\n\n\nclass TimestampUnaryOp(UnaryOp):\n arg = Arg(rlz.timestamp)\n\n\n_date_units = {\n 'Y': 'Y',\n 'y': 'Y',\n 'year': 'Y',\n 'YEAR': 'Y',\n 'YYYY': 'Y',\n 'SYYYY': 'Y',\n 'YYY': 'Y',\n 'YY': 'Y',\n 'Q': 'Q',\n 'q': 'Q',\n 'quarter': 'Q',\n 'QUARTER': 'Q',\n 'M': 'M',\n 'month': 'M',\n 'MONTH': 'M',\n 'w': 'W',\n 'W': 'W',\n 'week': 'W',\n 'WEEK': 'W',\n 'd': 'D',\n 'D': 'D',\n 'J': 'D',\n 'day': 'D',\n 'DAY': 'D',\n}\n\n_time_units = {\n 'h': 'h',\n 'H': 'h',\n 'HH24': 'h',\n 'hour': 'h',\n 'HOUR': 'h',\n 'm': 'm',\n 'MI': 'm',\n 'minute': 'm',\n 'MINUTE': 'm',\n 's': 's',\n 'second': 's',\n 'SECOND': 's',\n 'ms': 'ms',\n 'millisecond': 'ms',\n 'MILLISECOND': 'ms',\n 'us': 'us',\n 'microsecond': 'ms',\n 'MICROSECOND': 'ms',\n 'ns': 'ns',\n 'nanosecond': 'ns',\n 'NANOSECOND': 'ns',\n}\n\n_timestamp_units = toolz.merge(_date_units, _time_units)\n\n\nclass TimestampTruncate(ValueOp):\n arg = Arg(rlz.timestamp)\n unit = Arg(rlz.isin(_timestamp_units))\n output_type = rlz.shape_like('arg', dt.timestamp)\n\n\nclass DateTruncate(ValueOp):\n arg = Arg(rlz.date)\n unit = Arg(rlz.isin(_date_units))\n output_type = rlz.shape_like('arg', dt.date)\n\n\nclass TimeTruncate(ValueOp):\n arg = Arg(rlz.time)\n unit = Arg(rlz.isin(_time_units))\n output_type = rlz.shape_like('arg', dt.time)\n\n\nclass Strftime(ValueOp):\n arg = Arg(rlz.temporal)\n format_str = Arg(rlz.string)\n output_type = rlz.shape_like('arg', dt.string)\n\n\nclass StringToTimestamp(ValueOp):\n arg = Arg(rlz.string)\n format_str = Arg(rlz.string)\n timezone = Arg(rlz.string, default=None)\n output_type = rlz.shape_like('arg', dt.Timestamp(timezone='UTC'))\n\n\nclass ExtractTemporalField(TemporalUnaryOp):\n output_type = rlz.shape_like('arg', dt.int32)\n\n\nExtractTimestampField = ExtractTemporalField\n\n\nclass ExtractDateField(ExtractTemporalField):\n arg = Arg(rlz.one_of([rlz.date, rlz.timestamp]))\n\n\nclass ExtractTimeField(ExtractTemporalField):\n arg = Arg(rlz.one_of([rlz.time, rlz.timestamp]))\n\n\nclass ExtractYear(ExtractDateField):\n pass\n\n\nclass ExtractMonth(ExtractDateField):\n pass\n\n\nclass ExtractDay(ExtractDateField):\n pass\n\n\nclass ExtractDayOfYear(ExtractDateField):\n pass\n\n\nclass ExtractQuarter(ExtractDateField):\n pass\n\n\nclass ExtractEpochSeconds(ExtractDateField):\n pass\n\n\nclass ExtractWeekOfYear(ExtractDateField):\n pass\n\n\nclass ExtractHour(ExtractTimeField):\n pass\n\n\nclass ExtractMinute(ExtractTimeField):\n pass\n\n\nclass ExtractSecond(ExtractTimeField):\n pass\n\n\nclass ExtractMillisecond(ExtractTimeField):\n pass\n\n\nclass DayOfWeekIndex(UnaryOp):\n arg = Arg(rlz.one_of([rlz.date, rlz.timestamp]))\n output_type = rlz.shape_like('arg', dt.int16)\n\n\nclass DayOfWeekName(UnaryOp):\n arg = Arg(rlz.one_of([rlz.date, rlz.timestamp]))\n output_type = rlz.shape_like('arg', dt.string)\n\n\nclass DayOfWeekNode(Node):\n arg = Arg(rlz.one_of([rlz.date, rlz.timestamp]))\n\n def output_type(self):\n return ir.DayOfWeek\n\n\nclass Time(UnaryOp):\n output_type = rlz.shape_like('arg', dt.time)\n\n\nclass Date(UnaryOp):\n output_type = rlz.shape_like('arg', dt.date)\n\n\nclass TimestampFromUNIX(ValueOp):\n arg = Arg(rlz.any)\n # Only pandas-based backends support 'ns'\n unit = Arg(rlz.isin({'s', 'ms', 'us', 'ns'}))\n output_type = rlz.shape_like('arg', dt.timestamp)\n\n\nclass DecimalUnaryOp(UnaryOp):\n arg = Arg(rlz.decimal)\n\n\nclass DecimalPrecision(DecimalUnaryOp):\n output_type = rlz.shape_like('arg', dt.int32)\n\n\nclass DecimalScale(UnaryOp):\n output_type = rlz.shape_like('arg', dt.int32)\n\n\nclass Hash(ValueOp):\n arg = Arg(rlz.any)\n how = Arg(rlz.isin({'fnv', 'farm_fingerprint'}))\n output_type = rlz.shape_like('arg', dt.int64)\n\n\nclass HashBytes(ValueOp):\n arg = Arg(rlz.one_of({rlz.value(dt.string), rlz.value(dt.binary)}))\n how = Arg(rlz.isin({'md5', 'sha1', 'sha256', 'sha512'}))\n output_type = rlz.shape_like('arg', dt.binary)\n\n\nclass DateAdd(BinaryOp):\n left = Arg(rlz.date)\n right = Arg(rlz.interval(units={'Y', 'Q', 'M', 'W', 'D'}))\n output_type = rlz.shape_like('left')\n\n\nclass DateSub(BinaryOp):\n left = Arg(rlz.date)\n right = Arg(rlz.interval(units={'Y', 'Q', 'M', 'W', 'D'}))\n output_type = rlz.shape_like('left')\n\n\nclass DateDiff(BinaryOp):\n left = Arg(rlz.date)\n right = Arg(rlz.date)\n output_type = rlz.shape_like('left', dt.Interval('D'))\n\n\nclass TimeAdd(BinaryOp):\n left = Arg(rlz.time)\n right = Arg(rlz.interval(units={'h', 'm', 's', 'ms', 'us', 'ns'}))\n output_type = rlz.shape_like('left')\n\n\nclass TimeSub(BinaryOp):\n left = Arg(rlz.time)\n right = Arg(rlz.interval(units={'h', 'm', 's', 'ms', 'us', 'ns'}))\n output_type = rlz.shape_like('left')\n\n\nclass TimeDiff(BinaryOp):\n left = Arg(rlz.time)\n right = Arg(rlz.time)\n output_type = rlz.shape_like('left', dt.Interval('s'))\n\n\nclass TimestampAdd(BinaryOp):\n left = Arg(rlz.timestamp)\n right = Arg(\n rlz.interval(\n units={'Y', 'Q', 'M', 'W', 'D', 'h', 'm', 's', 'ms', 'us', 'ns'}\n )\n )\n output_type = rlz.shape_like('left')\n\n\nclass TimestampSub(BinaryOp):\n left = Arg(rlz.timestamp)\n right = Arg(\n rlz.interval(\n units={'Y', 'Q', 'M', 'W', 'D', 'h', 'm', 's', 'ms', 'us', 'ns'}\n )\n )\n output_type = rlz.shape_like('left')\n\n\nclass TimestampDiff(BinaryOp):\n left = Arg(rlz.timestamp)\n right = Arg(rlz.timestamp)\n output_type = rlz.shape_like('left', dt.Interval('s'))\n\n\nclass IntervalBinaryOp(BinaryOp):\n def output_type(self):\n args = [\n arg.cast(arg.type().value_type)\n if isinstance(arg.type(), dt.Interval)\n else arg\n for arg in self.args\n ]\n expr = rlz.numeric_like(args, self.__class__.op)(self)\n left_dtype = self.left.type()\n dtype_type = type(left_dtype)\n additional_args = {\n attr: getattr(left_dtype, attr)\n for attr in dtype_type.__slots__\n if attr not in {'unit', 'value_type'}\n }\n dtype = dtype_type(left_dtype.unit, expr.type(), **additional_args)\n return rlz.shape_like(self.args, dtype=dtype)\n\n\nclass IntervalAdd(IntervalBinaryOp):\n left = Arg(rlz.interval)\n right = Arg(rlz.interval)\n op = operator.add\n\n\nclass IntervalSubtract(IntervalBinaryOp):\n left = Arg(rlz.interval)\n right = Arg(rlz.interval)\n op = operator.sub\n\n\nclass IntervalMultiply(IntervalBinaryOp):\n left = Arg(rlz.interval)\n right = Arg(rlz.numeric)\n op = operator.mul\n\n\nclass IntervalFloorDivide(IntervalBinaryOp):\n left = Arg(rlz.interval)\n right = Arg(rlz.numeric)\n op = operator.floordiv\n\n\nclass IntervalFromInteger(ValueOp):\n arg = Arg(rlz.integer)\n unit = Arg(\n rlz.isin({'Y', 'Q', 'M', 'W', 'D', 'h', 'm', 's', 'ms', 'us', 'ns'})\n )\n\n @property\n def resolution(self):\n return dt.Interval(self.unit).resolution\n\n def output_type(self):\n dtype = dt.Interval(self.unit, self.arg.type())\n return rlz.shape_like(self.arg, dtype=dtype)\n\n\nclass ArrayColumn(ValueOp):\n cols = Arg(rlz.list_of(rlz.column(rlz.any), min_length=1))\n\n def _validate(self):\n if len({col.type() for col in self.cols}) > 1:\n raise com.IbisTypeError(\n f'The types of all input columns must match exactly in a '\n f'{type(self).__name__} operation.'\n )\n\n def output_type(self):\n first_dtype = self.cols[0].type()\n return dt.Array(first_dtype).column_type()\n\n\nclass ArrayLength(UnaryOp):\n arg = Arg(rlz.array)\n output_type = rlz.shape_like('arg', dt.int64)\n\n\nclass ArraySlice(ValueOp):\n arg = Arg(rlz.array)\n start = Arg(rlz.integer)\n stop = Arg(rlz.integer, default=None)\n output_type = rlz.typeof('arg')\n\n\nclass ArrayIndex(ValueOp):\n arg = Arg(rlz.array)\n index = Arg(rlz.integer)\n\n def output_type(self):\n value_dtype = self.arg.type().value_type\n return rlz.shape_like(self.arg, value_dtype)\n\n\nclass ArrayConcat(ValueOp):\n left = Arg(rlz.array)\n right = Arg(rlz.array)\n output_type = rlz.shape_like('left')\n\n def _validate(self):\n left_dtype, right_dtype = self.left.type(), self.right.type()\n if left_dtype != right_dtype:\n raise com.IbisTypeError(\n 'Array types must match exactly in a {} operation. '\n 'Left type {} != Right type {}'.format(\n type(self).__name__, left_dtype, right_dtype\n )\n )\n\n\nclass ArrayRepeat(ValueOp):\n arg = Arg(rlz.array)\n times = Arg(rlz.integer)\n output_type = rlz.typeof('arg')\n\n\nclass ArrayCollect(Reduction):\n arg = Arg(rlz.column(rlz.any))\n\n def output_type(self):\n dtype = dt.Array(self.arg.type())\n return dtype.scalar_type()\n\n\nclass MapLength(ValueOp):\n arg = Arg(rlz.mapping)\n output_type = rlz.shape_like('arg', dt.int64)\n\n\nclass MapValueForKey(ValueOp):\n arg = Arg(rlz.mapping)\n key = Arg(rlz.one_of([rlz.string, rlz.integer]))\n\n def output_type(self):\n return rlz.shape_like(tuple(self.args), self.arg.type().value_type)\n\n\nclass MapValueOrDefaultForKey(ValueOp):\n arg = Arg(rlz.mapping)\n key = Arg(rlz.one_of([rlz.string, rlz.integer]))\n default = Arg(rlz.any)\n\n def output_type(self):\n arg = self.arg\n default = self.default\n map_type = arg.type()\n value_type = map_type.value_type\n default_type = default.type()\n\n if default is not None and not dt.same_kind(default_type, value_type):\n raise com.IbisTypeError(\n \"Default value\\n{}\\nof type {} cannot be cast to map's value \"\n \"type {}\".format(default, default_type, value_type)\n )\n\n result_type = dt.highest_precedence((default_type, value_type))\n return rlz.shape_like(tuple(self.args), result_type)\n\n\nclass MapKeys(ValueOp):\n arg = Arg(rlz.mapping)\n\n def output_type(self):\n arg = self.arg\n return rlz.shape_like(arg, dt.Array(arg.type().key_type))\n\n\nclass MapValues(ValueOp):\n arg = Arg(rlz.mapping)\n\n def output_type(self):\n arg = self.arg\n return rlz.shape_like(arg, dt.Array(arg.type().value_type))\n\n\nclass MapConcat(ValueOp):\n left = Arg(rlz.mapping)\n right = Arg(rlz.mapping)\n output_type = rlz.typeof('left')\n\n\nclass StructField(ValueOp):\n arg = Arg(rlz.struct)\n field = Arg(str)\n\n def output_type(self):\n struct_dtype = self.arg.type()\n value_dtype = struct_dtype[self.field]\n return rlz.shape_like(self.arg, value_dtype)\n\n\nclass Literal(ValueOp):\n value = Arg(rlz.noop)\n dtype = Arg(dt.dtype)\n\n def __repr__(self):\n return '{}({})'.format(\n type(self).__name__, ', '.join(map(repr, self.args))\n )\n\n def equals(self, other, cache=None):\n # Check types\n if not (\n isinstance(other, Literal)\n and isinstance(other.value, type(self.value))\n and self.dtype == other.dtype\n ):\n return False\n\n # Check values\n if isinstance(self.value, np.ndarray):\n return np.array_equal(self.value, other.value)\n else:\n return self.value == other.value\n\n def output_type(self):\n return self.dtype.scalar_type()\n\n def root_tables(self):\n return []\n\n def __hash__(self) -> int:\n \"\"\"Return the hash of a literal value.\n\n We override this method to make sure that we can handle things that\n aren't eminently hashable like an ``array<array<int64>>``.\n\n \"\"\"\n return hash(self.dtype._literal_value_hash_key(self.value))\n\n\nclass NullLiteral(Literal):\n \"\"\"Typeless NULL literal\"\"\"\n\n value = Arg(type(None), default=None)\n dtype = Arg(dt.Null, default=dt.null)\n\n\nclass ScalarParameter(ValueOp):\n _counter = itertools.count()\n\n dtype = Arg(dt.dtype)\n counter = Arg(int, default=lambda: next(ScalarParameter._counter))\n\n def resolve_name(self):\n return 'param_{:d}'.format(self.counter)\n\n def __repr__(self):\n return '{}(type={})'.format(type(self).__name__, self.dtype)\n\n def __hash__(self):\n return hash((self.dtype, self.counter))\n\n def output_type(self):\n return self.dtype.scalar_type()\n\n def equals(self, other, cache=None):\n return (\n isinstance(other, ScalarParameter)\n and self.counter == other.counter\n and self.dtype.equals(other.dtype, cache=cache)\n )\n\n @property\n def inputs(self):\n return ()\n\n def root_tables(self):\n return []\n\n\nclass ExpressionList(Node):\n \"\"\"Data structure for a list of arbitrary expressions\"\"\"\n\n exprs = Arg(rlz.noop)\n\n def __init__(self, values):\n super().__init__(list(map(rlz.any, values)))\n\n @property\n def inputs(self):\n return (tuple(self.exprs),)\n\n def root_tables(self):\n return distinct_roots(self.exprs)\n\n def output_type(self):\n return ir.ExprList\n\n\nclass ValueList(ValueOp):\n \"\"\"Data structure for a list of value expressions\"\"\"\n\n values = Arg(rlz.noop)\n display_argnames = False # disable showing argnames in repr\n\n def __init__(self, values):\n super().__init__(tuple(map(rlz.any, values)))\n\n def output_type(self):\n dtype = rlz.highest_precedence_dtype(self.values)\n return functools.partial(ir.ListExpr, dtype=dtype)\n\n def root_tables(self):\n return distinct_roots(*self.values)\n\n\n# ----------------------------------------------------------------------\n# GeoSpatial operations\n\n\nclass GeoSpatialBinOp(BinaryOp):\n \"\"\"Geo Spatial base binary\"\"\"\n\n left = Arg(rlz.geospatial)\n right = Arg(rlz.geospatial)\n\n\nclass GeoSpatialUnOp(UnaryOp):\n \"\"\"Geo Spatial base unary\"\"\"\n\n arg = Arg(rlz.geospatial)\n\n\nclass GeoDistance(GeoSpatialBinOp):\n \"\"\"Returns minimum distance between two geo spatial data\"\"\"\n\n output_type = rlz.shape_like('args', dt.float64)\n\n\nclass GeoContains(GeoSpatialBinOp):\n \"\"\"Check if the first geo spatial data contains the second one\"\"\"\n\n output_type = rlz.shape_like('args', dt.boolean)\n\n\nclass GeoContainsProperly(GeoSpatialBinOp):\n \"\"\"Check if the first geo spatial data contains the second one,\n and no boundary points are shared.\"\"\"\n\n output_type = rlz.shape_like('args', dt.boolean)\n\n\nclass GeoCovers(GeoSpatialBinOp):\n \"\"\"Returns True if no point in Geometry B is outside Geometry A\"\"\"\n\n output_type = rlz.shape_like('args', dt.boolean)\n\n\nclass GeoCoveredBy(GeoSpatialBinOp):\n \"\"\"Returns True if no point in Geometry/Geography A is\n outside Geometry/Geography B\"\"\"\n\n output_type = rlz.shape_like('args', dt.boolean)\n\n\nclass GeoCrosses(GeoSpatialBinOp):\n \"\"\"Returns True if the supplied geometries have some, but not all,\n interior points in common.\"\"\"\n\n output_type = rlz.shape_like('args', dt.boolean)\n\n\nclass GeoDisjoint(GeoSpatialBinOp):\n \"\"\"Returns True if the Geometries do not “spatially intersect” -\n if they do not share any space together.\"\"\"\n\n output_type = rlz.shape_like('args', dt.boolean)\n\n\nclass GeoEquals(GeoSpatialBinOp):\n \"\"\"Returns True if the given geometries represent the same geometry.\"\"\"\n\n output_type = rlz.shape_like('args', dt.boolean)\n\n\nclass GeoGeometryN(GeoSpatialUnOp):\n \"\"\"Returns the Nth Geometry of a Multi geometry.\"\"\"\n\n n = Arg(rlz.integer)\n\n output_type = rlz.shape_like('args', dt.geometry)\n\n\nclass GeoGeometryType(GeoSpatialUnOp):\n \"\"\"Returns the type of the geometry.\"\"\"\n\n output_type = rlz.shape_like('args', dt.string)\n\n\nclass GeoIntersects(GeoSpatialBinOp):\n \"\"\"Returns True if the Geometries/Geography “spatially intersect in 2D”\n - (share any portion of space) and False if they don’t (they are Disjoint).\n \"\"\"\n\n output_type = rlz.shape_like('args', dt.boolean)\n\n\nclass GeoIsValid(GeoSpatialUnOp):\n \"\"\"Returns true if the geometry is well-formed.\"\"\"\n\n output_type = rlz.shape_like('args', dt.boolean)\n\n\nclass GeoLineLocatePoint(GeoSpatialBinOp):\n \"\"\"\n Locate the distance a point falls along the length of a line.\n\n Returns a float between zero and one representing the location of the\n closest point on the linestring to the given point, as a fraction of the\n total 2d line length.\n \"\"\"\n\n left = Arg(rlz.linestring)\n right = Arg(rlz.point)\n\n output_type = rlz.shape_like('args', dt.halffloat)\n\n\nclass GeoLineMerge(GeoSpatialUnOp):\n \"\"\"\n Merge a MultiLineString into a LineString.\n\n Returns a (set of) LineString(s) formed by sewing together the\n constituent line work of a multilinestring. If a geometry other than\n a linestring or multilinestring is given, this will return an empty\n geometry collection.\n \"\"\"\n\n output_type = rlz.shape_like('args', dt.geometry)\n\n\nclass GeoLineSubstring(GeoSpatialUnOp):\n \"\"\"\n Clip a substring from a LineString.\n\n Returns a linestring that is a substring of the input one, starting\n and ending at the given fractions of the total 2d length. The second\n and third arguments are floating point values between zero and one.\n This only works with linestrings.\n \"\"\"\n\n arg = Arg(rlz.linestring)\n\n start = Arg(rlz.floating)\n end = Arg(rlz.floating)\n\n output_type = rlz.shape_like('args', dt.linestring)\n\n\nclass GeoOrderingEquals(GeoSpatialBinOp):\n \"\"\"\n Check if two geometries are equal and have the same point ordering.\n\n Returns true if the two geometries are equal and the coordinates\n are in the same order.\n \"\"\"\n\n output_type = rlz.shape_like('args', dt.boolean)\n\n\nclass GeoOverlaps(GeoSpatialBinOp):\n \"\"\"Returns True if the Geometries share space, are of the same dimension,\n but are not completely contained by each other.\"\"\"\n\n output_type = rlz.shape_like('args', dt.boolean)\n\n\nclass GeoTouches(GeoSpatialBinOp):\n \"\"\"Returns True if the geometries have at least one point in common,\n but their interiors do not intersect.\"\"\"\n\n output_type = rlz.shape_like('args', dt.boolean)\n\n\nclass GeoUnaryUnion(Reduction):\n \"\"\"Returns the pointwise union of the geometries in the column.\"\"\"\n\n arg = Arg(rlz.column(rlz.geospatial))\n\n def output_type(self):\n return dt.geometry.scalar_type()\n\n\nclass GeoUnion(GeoSpatialBinOp):\n \"\"\"Returns the pointwise union of the two geometries.\"\"\"\n\n output_type = rlz.shape_like('args', dt.geometry)\n\n\nclass GeoArea(GeoSpatialUnOp):\n \"\"\"Area of the geo spatial data\"\"\"\n\n output_type = rlz.shape_like('args', dt.float64)\n\n\nclass GeoPerimeter(GeoSpatialUnOp):\n \"\"\"Perimeter of the geo spatial data\"\"\"\n\n output_type = rlz.shape_like('args', dt.float64)\n\n\nclass GeoLength(GeoSpatialUnOp):\n \"\"\"Length of geo spatial data\"\"\"\n\n output_type = rlz.shape_like('args', dt.float64)\n\n\nclass GeoMaxDistance(GeoSpatialBinOp):\n \"\"\"Returns the 2-dimensional maximum distance between two geometries in\n projected units. If g1 and g2 is the same geometry the function will\n return the distance between the two vertices most far from each other\n in that geometry\n \"\"\"\n\n output_type = rlz.shape_like('args', dt.float64)\n\n\nclass GeoX(GeoSpatialUnOp):\n \"\"\"Return the X coordinate of the point, or NULL if not available.\n Input must be a point\n \"\"\"\n\n output_type = rlz.shape_like('args', dt.float64)\n\n\nclass GeoY(GeoSpatialUnOp):\n \"\"\"Return the Y coordinate of the point, or NULL if not available.\n Input must be a point\n \"\"\"\n\n output_type = rlz.shape_like('args', dt.float64)\n\n\nclass GeoXMin(GeoSpatialUnOp):\n \"\"\"Returns Y minima of a bounding box 2d or 3d or a geometry\"\"\"\n\n output_type = rlz.shape_like('args', dt.float64)\n\n\nclass GeoXMax(GeoSpatialUnOp):\n \"\"\"Returns X maxima of a bounding box 2d or 3d or a geometry\"\"\"\n\n output_type = rlz.shape_like('args', dt.float64)\n\n\nclass GeoYMin(GeoSpatialUnOp):\n \"\"\"Returns Y minima of a bounding box 2d or 3d or a geometry\"\"\"\n\n output_type = rlz.shape_like('args', dt.float64)\n\n\nclass GeoYMax(GeoSpatialUnOp):\n \"\"\"Returns Y maxima of a bounding box 2d or 3d or a geometry\"\"\"\n\n output_type = rlz.shape_like('args', dt.float64)\n\n\nclass GeoStartPoint(GeoSpatialUnOp):\n \"\"\"Returns the first point of a LINESTRING geometry as a POINT or\n NULL if the input parameter is not a LINESTRING\n \"\"\"\n\n output_type = rlz.shape_like('arg', dt.point)\n\n\nclass GeoEndPoint(GeoSpatialUnOp):\n \"\"\"Returns the last point of a LINESTRING geometry as a POINT or\n NULL if the input parameter is not a LINESTRING\n \"\"\"\n\n output_type = rlz.shape_like('arg', dt.point)\n\n\nclass GeoPoint(GeoSpatialBinOp):\n \"\"\"\n Return a point constructed on the fly from the provided coordinate values.\n Constant coordinates result in construction of a POINT literal.\n \"\"\"\n\n left = Arg(rlz.numeric)\n right = Arg(rlz.numeric)\n output_type = rlz.shape_like('args', dt.point)\n\n\nclass GeoPointN(GeoSpatialUnOp):\n \"\"\"Return the Nth point in a single linestring in the geometry.\n Negative values are counted backwards from the end of the LineString,\n so that -1 is the last point. Returns NULL if there is no linestring in\n the geometry\n \"\"\"\n\n n = Arg(rlz.integer)\n output_type = rlz.shape_like('args', dt.point)\n\n\nclass GeoNPoints(GeoSpatialUnOp):\n \"\"\"Return the number of points in a geometry. Works for all geometries\"\"\"\n\n output_type = rlz.shape_like('args', dt.int64)\n\n\nclass GeoNRings(GeoSpatialUnOp):\n \"\"\"If the geometry is a polygon or multi-polygon returns the number of\n rings. It counts the outer rings as well\n \"\"\"\n\n output_type = rlz.shape_like('args', dt.int64)\n\n\nclass GeoSRID(GeoSpatialUnOp):\n \"\"\"Returns the spatial reference identifier for the ST_Geometry.\"\"\"\n\n output_type = rlz.shape_like('args', dt.int64)\n\n\nclass GeoSetSRID(GeoSpatialUnOp):\n \"\"\"Set the spatial reference identifier for the ST_Geometry.\"\"\"\n\n srid = Arg(rlz.integer)\n output_type = rlz.shape_like('args', dt.geometry)\n\n\nclass GeoBuffer(GeoSpatialUnOp):\n \"\"\"Returns a geometry that represents all points whose distance from this\n Geometry is less than or equal to distance. Calculations are in the\n Spatial Reference System of this Geometry.\n \"\"\"\n\n radius = Arg(rlz.floating)\n\n output_type = rlz.shape_like('args', dt.geometry)\n\n\nclass GeoCentroid(GeoSpatialUnOp):\n \"\"\"Returns the geometric center of a geometry.\"\"\"\n\n output_type = rlz.shape_like('arg', dt.point)\n\n\nclass GeoDFullyWithin(GeoSpatialBinOp):\n \"\"\"Returns True if the geometries are fully within the specified distance\n of one another.\n \"\"\"\n\n distance = Arg(rlz.floating)\n\n output_type = rlz.shape_like('args', dt.boolean)\n\n\nclass GeoDWithin(GeoSpatialBinOp):\n \"\"\"Returns True if the geometries are within the specified distance\n of one another.\n \"\"\"\n\n distance = Arg(rlz.floating)\n\n output_type = rlz.shape_like('args', dt.boolean)\n\n\nclass GeoEnvelope(GeoSpatialUnOp):\n \"\"\"Returns a geometry representing the boundingbox of the supplied geometry.\n \"\"\"\n\n output_type = rlz.shape_like('arg', dt.polygon)\n\n\nclass GeoAzimuth(GeoSpatialBinOp):\n \"\"\"Returns the angle in radians from the horizontal of the vector defined\n by pointA and pointB. Angle is computed clockwise from down-to-up:\n on the clock: 12=0; 3=PI/2; 6=PI; 9=3PI/2.\n \"\"\"\n\n left = Arg(rlz.point)\n right = Arg(rlz.point)\n\n output_type = rlz.shape_like('args', dt.float64)\n\n\nclass GeoWithin(GeoSpatialBinOp):\n \"\"\"Returns True if the geometry A is completely inside geometry B\"\"\"\n\n output_type = rlz.shape_like('args', dt.boolean)\n\n\nclass GeoIntersection(GeoSpatialBinOp):\n \"\"\"Returns a geometry that represents the point set intersection\n of the Geometries.\n \"\"\"\n\n output_type = rlz.shape_like('args', dt.geometry)\n\n\nclass GeoDifference(GeoSpatialBinOp):\n \"\"\"Returns a geometry that represents that part of geometry A\n that does not intersect with geometry B\n \"\"\"\n\n output_type = rlz.shape_like('args', dt.geometry)\n\n\nclass GeoSimplify(GeoSpatialUnOp):\n \"\"\"Returns a simplified version of the given geometry.\"\"\"\n\n tolerance = Arg(rlz.floating)\n preserve_collapsed = Arg(rlz.boolean)\n\n output_type = rlz.shape_like('arg', dt.geometry)\n\n\nclass GeoTransform(GeoSpatialUnOp):\n \"\"\"Returns a transformed version of the given geometry into a new SRID.\"\"\"\n\n srid = Arg(rlz.integer)\n\n output_type = rlz.shape_like('arg', dt.geometry)\n\n\nclass GeoAsBinary(GeoSpatialUnOp):\n \"\"\"Return the Well-Known Binary (WKB) representation of the\n geometry/geography without SRID meta data.\n \"\"\"\n\n output_type = rlz.shape_like('arg', dt.binary)\n\n\nclass GeoAsEWKB(GeoSpatialUnOp):\n \"\"\"Return the Well-Known Binary (WKB) representation of the\n geometry/geography with SRID meta data.\n \"\"\"\n\n output_type = rlz.shape_like('arg', dt.binary)\n\n\nclass GeoAsEWKT(GeoSpatialUnOp):\n \"\"\"Return the Well-Known Text (WKT) representation of the\n geometry/geography with SRID meta data.\n \"\"\"\n\n output_type = rlz.shape_like('arg', dt.string)\n\n\nclass GeoAsText(GeoSpatialUnOp):\n \"\"\"Return the Well-Known Text (WKT) representation of the\n geometry/geography without SRID metadata.\n \"\"\"\n\n output_type = rlz.shape_like('arg', dt.string)\n\n\nclass ElementWiseVectorizedUDF(ValueOp):\n \"\"\"Node for element wise UDF.\"\"\"\n\n func = Arg(callable)\n func_args = Arg(tuple)\n input_type = Arg(rlz.shape_like('func_args'))\n _output_type = Arg(rlz.noop)\n\n def __init__(self, func, args, input_type, output_type):\n self.func = func\n self.func_args = args\n self.input_type = input_type\n self._output_type = output_type\n\n @property\n def inputs(self):\n return self.func_args\n\n def output_type(self):\n return self._output_type.column_type()\n\n def root_tables(self):\n return distinct_roots(*self.func_args)\n\n\nclass ReductionVectorizedUDF(Reduction):\n \"\"\"Node for reduction UDF.\"\"\"\n\n func = Arg(callable)\n func_args = Arg(tuple)\n input_type = Arg(rlz.shape_like('func_args'))\n _output_type = Arg(rlz.noop)\n\n def __init__(self, func, args, input_type, output_type):\n self.func = func\n self.func_args = args\n self.input_type = input_type\n self._output_type = output_type\n\n @property\n def inputs(self):\n return self.func_args\n\n def output_type(self):\n return self._output_type.scalar_type()\n\n def root_tables(self):\n return distinct_roots(*self.func_args)\n\n\nclass AnalyticVectorizedUDF(AnalyticOp):\n \"\"\"Node for analytics UDF.\"\"\"\n\n func = Arg(callable)\n func_args = Arg(tuple)\n input_type = Arg(rlz.shape_like('func_args'))\n _output_type = Arg(rlz.noop)\n\n def __init__(self, func, args, input_type, output_type):\n self.func = func\n self.func_args = args\n self.input_type = input_type\n self._output_type = output_type\n\n @property\n def inputs(self):\n return self.func_args\n\n def output_type(self):\n return self._output_type.column_type()\n\n def root_tables(self):\n return distinct_roots(*self.func_args)\n\n\nclass ExistsSubquery(Node):\n \"\"\"Helper class\"\"\"\n\n foreign_table = Arg(rlz.noop)\n predicates = Arg(rlz.noop)\n\n def output_type(self):\n return ir.ExistsExpr\n\n\nclass NotExistsSubquery(Node):\n foreign_table = Arg(rlz.noop)\n predicates = Arg(rlz.noop)\n\n def output_type(self):\n return ir.ExistsExpr\n"
] |
[
[
"numpy.array_equal"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
huggingface/neural-compressor
|
[
"16a4a12045fcb468da4d33769aff2c1a5e2ba6ba",
"16a4a12045fcb468da4d33769aff2c1a5e2ba6ba",
"16a4a12045fcb468da4d33769aff2c1a5e2ba6ba",
"aaad4c357a86914ffa583753c9a26d949838a2a5",
"16a4a12045fcb468da4d33769aff2c1a5e2ba6ba",
"aaad4c357a86914ffa583753c9a26d949838a2a5"
] |
[
"test/test_model_conversion.py",
"examples/pytorch/recommendation/dlrm/quantization/ptq/fx/dlrm_s_pytorch_tune.py",
"examples/pytorch/image_recognition/torchvision_models/quantization/ptq/cpu/fx/main.py",
"test/test_basic.py",
"examples/pytorch/nlp/huggingface_models/common/src/transformers/trainer.py",
"test/test_bf16_convert.py"
] |
[
"#\n# -*- coding: utf-8 -*-\n#\nimport unittest\nimport os\nimport shutil\nimport yaml\nimport tensorflow as tf\n\nfrom neural_compressor.experimental import model_conversion\ntf.compat.v1.enable_eager_execution()\nfrom tensorflow import keras\n\nfrom tensorflow.python.framework import graph_util\nfrom neural_compressor.adaptor.tf_utils.util import disable_random\n\ndef build_fake_yaml():\n fake_yaml = '''\n model:\n name: fake_yaml\n framework: tensorflow\n device: cpu\n model_conversion:\n source: qat\n destination: default\n '''\n y = yaml.load(fake_yaml, Loader=yaml.SafeLoader)\n with open('fake_yaml.yaml', \"w\", encoding=\"utf-8\") as f:\n yaml.dump(y, f)\n f.close()\n\ndef prepare_dataset():\n \n # Load MNIST dataset\n mnist = keras.datasets.mnist\n (train_images, train_labels), (test_images, test_labels) = mnist.load_data()\n \n # Normalize the input image so that each pixel value is between 0 to 1.\n train_images = train_images / 255.0\n test_images = test_images / 255.0\n\n return train_images, train_labels\n\ndef prepare_model(model_out_path, train_images, train_labels):\n \n # Define the model architecture.\n model = keras.Sequential([\n keras.layers.InputLayer(input_shape=(28, 28)),\n keras.layers.Reshape(target_shape=(28, 28, 1)),\n keras.layers.Conv2D(filters=12, kernel_size=(3, 3), activation='relu'),\n keras.layers.MaxPooling2D(pool_size=(2, 2)),\n keras.layers.Flatten(),\n keras.layers.Dense(10)\n ])\n \n # Train the digit classification model\n model.compile(optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\n \n model.fit(\n train_images,\n train_labels,\n epochs=1,\n validation_split=0.1,\n )\n\n model.save(model_out_path)\n\ndef prepare_qat_model(model_in_path, model_out_path, train_images, train_labels):\n import tensorflow_model_optimization as tfmot\n quantize_model = tfmot.quantization.keras.quantize_model\n \n # q_aware stands for for quantization aware.\n model = tf.keras.models.load_model(model_in_path)\n q_aware_model = quantize_model(model)\n \n # `quantize_model` requires a recompile.\n q_aware_model.compile(optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\n \n train_images_subset = train_images[0:1000] # out of 60000\n train_labels_subset = train_labels[0:1000]\n \n q_aware_model.fit(train_images_subset, train_labels_subset,\n batch_size=500, epochs=1, validation_split=0.1)\n \n q_aware_model.save(model_out_path)\n\[email protected](tf.version.VERSION < '2.4.0', \"Only supports tf 2.4.0 or above\")\nclass TestModelConversion(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n self._baseline_temp_path = './temp_baseline'\n self._qat_temp_path = './temp_qat'\n self._quantized_temp_path = './temp_quantized'\n build_fake_yaml()\n train_images, train_labels = prepare_dataset()\n prepare_model(self._baseline_temp_path, train_images, train_labels)\n prepare_qat_model(self._baseline_temp_path, self._qat_temp_path, train_images, train_labels)\n\n @classmethod\n def tearDownClass(self):\n os.remove('fake_yaml.yaml')\n shutil.rmtree(self._qat_temp_path, ignore_errors=True)\n shutil.rmtree(self._baseline_temp_path, ignore_errors=True)\n shutil.rmtree(self._quantized_temp_path, ignore_errors=True)\n\n def test_model_conversion(self):\n from neural_compressor.experimental import ModelConversion, common\n from neural_compressor.conf.config import Conf\n conversion = ModelConversion()\n conversion.source = 'qat'\n conversion.destination = 'default'\n conversion.model = self._qat_temp_path\n q_model = conversion.fit()\n q_model.save(self._quantized_temp_path)\n conf = Conf('fake_yaml.yaml')\n conversion = ModelConversion(conf)\n conversion.source = 'qat'\n conversion.destination = 'default'\n conversion.model = self._qat_temp_path\n q_model = conversion.fit()\n conversion = ModelConversion('fake_yaml.yaml')\n conversion.source = 'qat'\n conversion.destination = 'default'\n conversion.model = self._qat_temp_path\n q_model = conversion.fit()\n\n graph = tf.compat.v1.Graph()\n with graph.as_default():\n with tf.compat.v1.Session() as sess:\n meta_graph=tf.compat.v1.saved_model.loader.load(sess, [tf.compat.v1.saved_model.tag_constants.SERVING], self._quantized_temp_path)\n print(meta_graph.graph_def.node)\n for i in meta_graph.graph_def.node:\n if 'MatMul' in i.op:\n self.assertTrue('QuantizedMatMul' in i.op)\n if 'MaxPool' in i.op:\n self.assertTrue('QuantizedMaxPool' in i.op)\n if 'Conv2D' in i.op:\n self.assertTrue('QuantizedConv2D' in i.op)\n\nif __name__ == \"__main__\":\n unittest.main()\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#\n# Description: an implementation of a deep learning recommendation model (DLRM)\n# The model input consists of dense and sparse features. The former is a vector\n# of floating point values. The latter is a list of sparse indices into\n# embedding tables, which consist of vectors of floating point values.\n# The selected vectors are passed to mlp networks denoted by triangles,\n# in some cases the vectors are interacted through operators (Ops).\n#\n# output:\n# vector of values\n# model: |\n# /\\\n# /__\\\n# |\n# _____________________> Op <___________________\n# / | \\\n# /\\ /\\ /\\\n# /__\\ /__\\ ... /__\\\n# | | |\n# | Op Op\n# | ____/__\\_____ ____/__\\____\n# | |_Emb_|____|__| ... |_Emb_|__|___|\n# input:\n# [ dense features ] [sparse indices] , ..., [sparse indices]\n#\n# More precise definition of model layers:\n# 1) fully connected layers of an mlp\n# z = f(y)\n# y = Wx + b\n#\n# 2) embedding lookup (for a list of sparse indices p=[p1,...,pk])\n# z = Op(e1,...,ek)\n# obtain vectors e1=E[:,p1], ..., ek=E[:,pk]\n#\n# 3) Operator Op can be one of the following\n# Sum(e1,...,ek) = e1 + ... + ek\n# Dot(e1,...,ek) = [e1'e1, ..., e1'ek, ..., ek'e1, ..., ek'ek]\n# Cat(e1,...,ek) = [e1', ..., ek']'\n# where ' denotes transpose operation\n#\n# References:\n# [1] Maxim Naumov, Dheevatsa Mudigere, Hao-Jun Michael Shi, Jianyu Huang,\n# Narayanan Sundaram, Jongsoo Park, Xiaodong Wang, Udit Gupta, Carole-Jean Wu,\n# Alisson G. Azzolini, Dmytro Dzhulgakov, Andrey Mallevich, Ilia Cherniavskii,\n# Yinghai Lu, Raghuraman Krishnamoorthi, Ansha Yu, Volodymyr Kondratenko,\n# Stephanie Pereira, Xianjie Chen, Wenlin Chen, Vijay Rao, Bill Jia, Liang Xiong,\n# Misha Smelyanskiy, \"Deep Learning Recommendation Model for Personalization and\n# Recommendation Systems\", CoRR, arXiv:1906.00091, 2019\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\n# miscellaneous\nimport builtins\nimport functools\nimport time\nimport json\n# data generation\nimport dlrm_data_pytorch as dp\n\n# numpy\nimport numpy as np\n\n# onnx\n# The onnx import causes deprecation warnings every time workers\n# are spawned during testing. So, we filter out those warnings.\nimport warnings\nwith warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\nimport onnx\n\n# pytorch\nimport torch\nimport torch.fx\nimport torch.nn as nn\nfrom torch.nn.parallel.parallel_apply import parallel_apply\nfrom torch.nn.parallel.replicate import replicate\nfrom torch.nn.parallel.scatter_gather import gather, scatter\nfrom torch.utils.data import DataLoader\n# quotient-remainder trick\nfrom tricks.qr_embedding_bag import QREmbeddingBag\n# mixed-dimension trick\nfrom tricks.md_embedding_bag import PrEmbeddingBag, md_solver\n\nimport sklearn.metrics\n\nfrom torch.quantization import \\\n quantize, prepare, convert, fuse_modules\nfrom torch.quantization import QuantWrapper, QuantStub, DeQuantStub, \\\n default_per_channel_qconfig, QConfig, default_qconfig\n\nexc = getattr(builtins, \"IOError\", \"FileNotFoundError\")\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self, name, fmt=':f'):\n self.name = name\n self.fmt = fmt\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n def __str__(self):\n fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})'\n return fmtstr.format(**self.__dict__)\n\n\[email protected]\ndef interact_features(arch_interaction_op, arch_interaction_itself, x, ly):\n if arch_interaction_op == \"dot\":\n # concatenate dense and sparse features\n (batch_size, d) = x.shape\n T = torch.cat([x] + ly, dim=1).view((batch_size, -1, d))\n # perform a dot product\n Z = torch.bmm(T, torch.transpose(T, 1, 2))\n # append dense feature with the interactions (into a row vector)\n # approach 1: all\n # Zflat = Z.view((batch_size, -1))\n # approach 2: unique\n _, ni, nj = Z.shape\n # approach 1: tril_indices\n # offset = 0 if self.arch_interaction_itself else -1\n # li, lj = torch.tril_indices(ni, nj, offset=offset)\n # approach 2: custom\n offset = 1 if arch_interaction_itself else 0\n li = torch.tensor([i for i in range(ni) for j in range(i + offset)])\n lj = torch.tensor([j for i in range(nj) for j in range(i + offset)])\n Zflat = Z[:, li, lj]\n # concatenate dense features and interactions\n R = torch.cat([x] + [Zflat], dim=1)\n elif arch_interaction_op == \"cat\":\n # concatenation features (into a row vector)\n R = torch.cat([x] + ly, dim=1)\n else:\n sys.exit(\n \"ERROR: --arch-interaction-op=\"\n + arch_interaction_op\n + \" is not supported\"\n )\n return R\n\n\n### define dlrm in PyTorch ###\nclass DLRM_Net(nn.Module):\n def create_mlp(self, ln, sigmoid_layer):\n # build MLP layer by layer\n layers = nn.ModuleList()\n for i in range(0, ln.size - 1):\n n = ln[i]\n m = ln[i + 1]\n\n # construct fully connected operator\n LL = nn.Linear(int(n), int(m), bias=True)\n\n layers.append(LL)\n\n # construct sigmoid or relu operator\n if i == sigmoid_layer:\n layers.append(nn.Sigmoid())\n else:\n layers.append(nn.ReLU())\n\n # approach 1: use ModuleList\n return layers\n # approach 2: use Sequential container to wrap all layers\n # return torch.nn.Sequential(*layers)\n\n def create_emb(self, m, ln):\n emb_l = nn.ModuleList()\n for i in range(0, ln.size):\n n = ln[i]\n # construct embedding operator\n if self.qr_flag and n > self.qr_threshold:\n EE = QREmbeddingBag(n, m, self.qr_collisions,\n operation=self.qr_operation, mode=\"sum\", sparse=True)\n elif self.md_flag and n > self.md_threshold:\n _m = m[i]\n base = max(m)\n EE = PrEmbeddingBag(n, _m, base)\n else:\n EE = nn.EmbeddingBag(n, m, mode=\"sum\", sparse=True)\n\n emb_l.append(EE)\n\n return emb_l\n\n def __init__(\n self,\n m_spa=None,\n ln_emb=None,\n ln_bot=None,\n ln_top=None,\n arch_interaction_op=None,\n arch_interaction_itself=False,\n sigmoid_bot=-1,\n sigmoid_top=-1,\n sync_dense_params=True,\n loss_threshold=0.0,\n ndevices=-1,\n qr_flag=False,\n qr_operation=\"mult\",\n qr_collisions=0,\n qr_threshold=200,\n md_flag=False,\n md_threshold=200,\n ):\n super(DLRM_Net, self).__init__()\n\n if (\n (m_spa is not None)\n and (ln_emb is not None)\n and (ln_bot is not None)\n and (ln_top is not None)\n and (arch_interaction_op is not None)\n ):\n\n # save arguments\n self.ndevices = ndevices\n self.output_d = 0\n self.parallel_model_batch_size = -1\n self.parallel_model_is_not_prepared = True\n self.arch_interaction_op = arch_interaction_op\n self.arch_interaction_itself = arch_interaction_itself\n self.sync_dense_params = sync_dense_params\n self.loss_threshold = loss_threshold\n # create variables for QR embedding if applicable\n self.qr_flag = qr_flag\n if self.qr_flag:\n self.qr_collisions = qr_collisions\n self.qr_operation = qr_operation\n self.qr_threshold = qr_threshold\n # create variables for MD embedding if applicable\n self.md_flag = md_flag\n if self.md_flag:\n self.md_threshold = md_threshold\n # create operators\n if ndevices <= 1:\n self.emb_l = self.create_emb(m_spa, ln_emb)\n self.bot_l = self.create_mlp(ln_bot, sigmoid_bot)\n self.top_l = self.create_mlp(ln_top, sigmoid_top)\n\n def apply_mlp(self, x, layers):\n # approach 1: use ModuleList\n for layer in layers:\n x = layer(x)\n return x\n # approach 2: use Sequential container to wrap all layers\n # return layers(x)\n\n def apply_emb(self, lS_o, lS_i, emb_l):\n # WARNING: notice that we are processing the batch at once. We implicitly\n # assume that the data is laid out such that:\n # 1. each embedding is indexed with a group of sparse indices,\n # corresponding to a single lookup\n # 2. for each embedding the lookups are further organized into a batch\n # 3. for a list of embedding tables there is a list of batched lookups\n\n ly = []\n # 26 obtained from len(lS_i)\n # for k, sparse_index_group_batch in enumerate(lS_i):\n for k in range(26):\n sparse_index_group_batch = lS_i[k]\n sparse_offset_group_batch = lS_o[k]\n\n # embedding lookup\n # We are using EmbeddingBag, which implicitly uses sum operator.\n # The embeddings are represented as tall matrices, with sum\n # happening vertically across 0 axis, resulting in a row vector\n E = emb_l[k]\n V = E(sparse_index_group_batch, sparse_offset_group_batch)\n\n ly.append(V)\n\n # print(ly)\n return ly\n\n def forward(self, dense_x, lS_o, lS_i):\n if self.ndevices <= 1:\n return self.sequential_forward(dense_x, lS_o, lS_i)\n else:\n return self.parallel_forward(dense_x, lS_o, lS_i)\n\n def sequential_forward(self, dense_x, lS_o, lS_i):\n # process dense features (using bottom mlp), resulting in a row vector\n x = self.apply_mlp(dense_x, self.bot_l)\n\n # process sparse features(using embeddings), resulting in a list of row vectors\n ly = self.apply_emb(lS_o, lS_i, self.emb_l)\n\n # interact features (dense and sparse)\n z = interact_features(self.arch_interaction_op, self.arch_interaction_itself, x, ly)\n\n # obtain probability of a click (using top mlp)\n p = self.apply_mlp(z, self.top_l)\n\n # clamp output if needed\n if 0.0 < self.loss_threshold and self.loss_threshold < 1.0:\n z = torch.clamp(p, min=self.loss_threshold, max=(1.0 - self.loss_threshold))\n else:\n z = p\n\n return z\n\n def parallel_forward(self, dense_x, lS_o, lS_i):\n ### prepare model (overwrite) ###\n # WARNING: # of devices must be >= batch size in parallel_forward call\n batch_size = dense_x.size()[0]\n ndevices = min(self.ndevices, batch_size, len(self.emb_l))\n device_ids = range(ndevices)\n # WARNING: must redistribute the model if mini-batch size changes(this is common\n # for last mini-batch, when # of elements in the dataset/batch size is not even\n if self.parallel_model_batch_size != batch_size:\n self.parallel_model_is_not_prepared = True\n\n if self.parallel_model_is_not_prepared or self.sync_dense_params:\n # replicate mlp (data parallelism)\n self.bot_l_replicas = replicate(self.bot_l, device_ids)\n self.top_l_replicas = replicate(self.top_l, device_ids)\n self.parallel_model_batch_size = batch_size\n\n if self.parallel_model_is_not_prepared:\n # distribute embeddings (model parallelism)\n t_list = []\n for k, emb in enumerate(self.emb_l):\n d = torch.device(\"cuda:\" + str(k % ndevices))\n emb.to(d)\n t_list.append(emb.to(d))\n self.emb_l = nn.ModuleList(t_list)\n self.parallel_model_is_not_prepared = False\n\n ### prepare input (overwrite) ###\n # scatter dense features (data parallelism)\n # print(dense_x.device)\n dense_x = scatter(dense_x, device_ids, dim=0)\n # distribute sparse features (model parallelism)\n if (len(self.emb_l) != len(lS_o)) or (len(self.emb_l) != len(lS_i)):\n sys.exit(\"ERROR: corrupted model input detected in parallel_forward call\")\n\n t_list = []\n i_list = []\n for k, _ in enumerate(self.emb_l):\n d = torch.device(\"cuda:\" + str(k % ndevices))\n t_list.append(lS_o[k].to(d))\n i_list.append(lS_i[k].to(d))\n lS_o = t_list\n lS_i = i_list\n\n ### compute results in parallel ###\n # bottom mlp\n # WARNING: Note that the self.bot_l is a list of bottom mlp modules\n # that have been replicated across devices, while dense_x is a tuple of dense\n # inputs that has been scattered across devices on the first (batch) dimension.\n # The output is a list of tensors scattered across devices according to the\n # distribution of dense_x.\n x = parallel_apply(self.bot_l_replicas, dense_x, None, device_ids)\n\n # embeddings\n ly = self.apply_emb(lS_o, lS_i, self.emb_l)\n\n # butterfly shuffle (implemented inefficiently for now)\n # WARNING: Note that at this point we have the result of the embedding lookup\n # for the entire batch on each device. We would like to obtain partial results\n # corresponding to all embedding lookups, but part of the batch on each device.\n # Therefore, matching the distribution of output of bottom mlp, so that both\n # could be used for subsequent interactions on each device.\n if len(self.emb_l) != len(ly):\n sys.exit(\"ERROR: corrupted intermediate result in parallel_forward call\")\n\n t_list = []\n for k, _ in enumerate(self.emb_l):\n d = torch.device(\"cuda:\" + str(k % ndevices))\n y = scatter(ly[k], device_ids, dim=0)\n t_list.append(y)\n # adjust the list to be ordered per device\n ly = list(map(lambda y: list(y), zip(*t_list)))\n\n # interactions\n z = []\n for k in range(ndevices):\n zk = interact_features(x[k], ly[k])\n z.append(zk)\n\n # top mlp\n # WARNING: Note that the self.top_l is a list of top mlp modules that\n # have been replicated across devices, while z is a list of interaction results\n # that by construction are scattered across devices on the first (batch) dim.\n # The output is a list of tensors scattered across devices according to the\n # distribution of z.\n p = parallel_apply(self.top_l_replicas, z, None, device_ids)\n\n ### gather the distributed results ###\n p0 = gather(p, self.output_d, dim=0)\n\n # clamp output if needed\n if 0.0 < self.loss_threshold and self.loss_threshold < 1.0:\n z0 = torch.clamp(\n p0, min=self.loss_threshold, max=(1.0 - self.loss_threshold)\n )\n else:\n z0 = p0\n\n return z0\n\n\nclass DLRM_DataLoader(object):\n def __init__(self, loader=None):\n self.loader = loader\n self.batch_size = loader.dataset.batch_size\n def __iter__(self):\n for X_test, lS_o_test, lS_i_test, T in self.loader:\n yield (X_test, lS_o_test, lS_i_test), T\n\nif __name__ == \"__main__\":\n ### import packages ###\n import sys\n import argparse\n\n ### parse arguments ###\n parser = argparse.ArgumentParser(\n description=\"Train Deep Learning Recommendation Model (DLRM)\"\n )\n # model related parameters\n parser.add_argument(\"--arch-sparse-feature-size\", type=int, default=2)\n parser.add_argument(\"--arch-embedding-size\", type=str, default=\"4-3-2\")\n # int8_inference\n parser.add_argument(\"--do-int8-inference\", action=\"store_true\", default=False)\n parser.add_argument(\"--per-tensor-linear\", action=\"store_true\", default=False)\n # j will be replaced with the table number\n parser.add_argument(\"--arch-mlp-bot\", type=str, default=\"4-3-2\")\n parser.add_argument(\"--arch-mlp-top\", type=str, default=\"4-2-1\")\n parser.add_argument(\"--arch-interaction-op\", type=str, default=\"dot\")\n parser.add_argument(\"--arch-interaction-itself\", action=\"store_true\", default=False)\n # embedding table options\n parser.add_argument(\"--md-flag\", action=\"store_true\", default=False)\n parser.add_argument(\"--md-threshold\", type=int, default=200)\n parser.add_argument(\"--md-temperature\", type=float, default=0.3)\n parser.add_argument(\"--md-round-dims\", action=\"store_true\", default=False)\n parser.add_argument(\"--qr-flag\", action=\"store_true\", default=False)\n parser.add_argument(\"--qr-threshold\", type=int, default=200)\n parser.add_argument(\"--qr-operation\", type=str, default=\"mult\")\n parser.add_argument(\"--qr-collisions\", type=int, default=4)\n # activations and loss\n parser.add_argument(\"--activation-function\", type=str, default=\"relu\")\n parser.add_argument(\"--loss-function\", type=str, default=\"mse\") # or bce or wbce\n parser.add_argument(\"--loss-weights\", type=str, default=\"1.0-1.0\") # for wbce\n parser.add_argument(\"--loss-threshold\", type=float, default=0.0) # 1.0e-7\n parser.add_argument(\"--round-targets\", type=bool, default=False)\n # data\n parser.add_argument(\"--data-size\", type=int, default=1)\n parser.add_argument(\"--num-batches\", type=int, default=0)\n parser.add_argument(\n \"--data-generation\", type=str, default=\"random\"\n ) # synthetic or dataset\n parser.add_argument(\"--data-trace-file\", type=str, default=\"./input/dist_emb_j.log\")\n parser.add_argument(\"--data-set\", type=str, default=\"kaggle\") # or terabyte\n parser.add_argument(\"--raw-data-file\", type=str, default=\"\")\n parser.add_argument(\"--processed-data-file\", type=str, default=\"\")\n parser.add_argument(\"--data-randomize\", type=str, default=\"total\") # or day or none\n parser.add_argument(\"--data-trace-enable-padding\", type=bool, default=False)\n parser.add_argument(\"--max-ind-range\", type=int, default=-1)\n parser.add_argument(\"--data-sub-sample-rate\", type=float, default=0.0) # in [0, 1]\n parser.add_argument(\"--num-indices-per-lookup\", type=int, default=10)\n parser.add_argument(\"--num-indices-per-lookup-fixed\", type=bool, default=False)\n parser.add_argument(\"--num-workers\", type=int, default=0)\n parser.add_argument(\"--memory-map\", action=\"store_true\", default=False)\n # training\n parser.add_argument(\"--mini-batch-size\", type=int, default=1)\n parser.add_argument(\"--nepochs\", type=int, default=1)\n parser.add_argument(\"--learning-rate\", type=float, default=0.01)\n parser.add_argument(\"--print-precision\", type=int, default=5)\n parser.add_argument(\"--numpy-rand-seed\", type=int, default=123)\n parser.add_argument(\"--sync-dense-params\", type=bool, default=True)\n # inference\n parser.add_argument(\"--inference-only\", action=\"store_true\", default=False)\n # onnx\n parser.add_argument(\"--save-onnx\", action=\"store_true\", default=False)\n # gpu\n parser.add_argument(\"--use-gpu\", action=\"store_true\", default=False)\n # debugging and profiling\n parser.add_argument(\"--print-freq\", type=int, default=1)\n parser.add_argument(\"--test-freq\", type=int, default=-1)\n parser.add_argument(\"--test-mini-batch-size\", type=int, default=-1)\n parser.add_argument(\"--test-num-workers\", type=int, default=-1)\n parser.add_argument(\"--print-time\", action=\"store_true\", default=False)\n parser.add_argument(\"--debug-mode\", action=\"store_true\", default=False)\n parser.add_argument(\"--enable-profiling\", action=\"store_true\", default=False)\n parser.add_argument(\"--plot-compute-graph\", action=\"store_true\", default=False)\n # store/load model\n parser.add_argument(\"--save-int8\", type=str, default=\"\")\n parser.add_argument(\"--save-model\", type=str, default=\"\")\n parser.add_argument(\"--load-model\", type=str, default=\"\")\n # mlperf logging (disables other output and stops early)\n parser.add_argument(\"--mlperf-logging\", action=\"store_true\", default=False)\n # stop at target accuracy Kaggle 0.789, Terabyte (sub-sampled=0.875) 0.8107\n parser.add_argument(\"--mlperf-acc-threshold\", type=float, default=0.0)\n # stop at target AUC Terabyte (no subsampling) 0.8025\n parser.add_argument(\"--mlperf-auc-threshold\", type=float, default=0.0)\n parser.add_argument(\"--mlperf-bin-loader\", action='store_true', default=False)\n parser.add_argument(\"--mlperf-bin-shuffle\", action='store_true', default=False)\n parser.add_argument(\"--tune\", action='store_true', default=False)\n parser.add_argument(\"--output-model\", type=str, default=\"\")\n parser.add_argument('-i', \"--iter\", default=0, type=int,\n help='For accuracy measurement only.')\n parser.add_argument('-w', \"--warmup_iter\", default=5, type=int,\n help='For benchmark measurement only.')\n parser.add_argument('--benchmark', dest='benchmark', action='store_true',\n help='run benchmark')\n parser.add_argument(\"--tuned_checkpoint\", default='./saved_results', type=str, metavar='PATH',\n help='path to checkpoint tuned by Neural Compressor (default: ./)')\n parser.add_argument('--int8', dest='int8', action='store_true',\n help='run benchmark for int8')\n args = parser.parse_args()\n\n if args.mlperf_logging:\n print('command line args: ', json.dumps(vars(args)))\n\n ### some basic setup ###\n np.random.seed(args.numpy_rand_seed)\n np.set_printoptions(precision=args.print_precision)\n torch.set_printoptions(precision=args.print_precision)\n torch.manual_seed(args.numpy_rand_seed)\n\n if (args.test_mini_batch_size < 0):\n # if the parameter is not set, use the training batch size\n args.test_mini_batch_size = args.mini_batch_size\n if (args.test_num_workers < 0):\n # if the parameter is not set, use the same parameter for training\n args.test_num_workers = args.num_workers\n\n use_gpu = args.use_gpu and torch.cuda.is_available()\n if use_gpu:\n torch.cuda.manual_seed_all(args.numpy_rand_seed)\n torch.backends.cudnn.deterministic = True\n device = torch.device(\"cuda\", 0)\n ngpus = torch.cuda.device_count() # 1\n print(\"Using {} GPU(s)...\".format(ngpus))\n else:\n device = torch.device(\"cpu\")\n print(\"Using CPU...\")\n\n ### prepare training data ###\n ln_bot = np.fromstring(args.arch_mlp_bot, dtype=int, sep=\"-\")\n # input data\n if (args.data_generation == \"dataset\"):\n\n train_data, train_ld, test_data, test_ld = \\\n dp.make_criteo_data_and_loaders(args)\n nbatches = args.num_batches if args.num_batches > 0 else len(test_ld)\n nbatches_test = len(test_ld)\n\n ln_emb = train_data.counts\n # enforce maximum limit on number of vectors per embedding\n if args.max_ind_range > 0:\n ln_emb = np.array(list(map(\n lambda x: x if x < args.max_ind_range else args.max_ind_range,\n ln_emb\n )))\n m_den = train_data.m_den\n ln_bot[0] = m_den\n else:\n # input and target at random\n ln_emb = np.fromstring(args.arch_embedding_size, dtype=int, sep=\"-\")\n m_den = ln_bot[0]\n train_data, train_ld = dp.make_random_data_and_loader(args, ln_emb, m_den)\n nbatches = args.num_batches if args.num_batches > 0 else len(train_ld)\n\n ### parse command line arguments ###\n m_spa = args.arch_sparse_feature_size\n num_fea = ln_emb.size + 1 # num sparse + num dense features\n m_den_out = ln_bot[ln_bot.size - 1]\n if args.arch_interaction_op == \"dot\":\n # approach 1: all\n # num_int = num_fea * num_fea + m_den_out\n # approach 2: unique\n if args.arch_interaction_itself:\n num_int = (num_fea * (num_fea + 1)) // 2 + m_den_out\n else:\n num_int = (num_fea * (num_fea - 1)) // 2 + m_den_out\n elif args.arch_interaction_op == \"cat\":\n num_int = num_fea * m_den_out\n else:\n sys.exit(\n \"ERROR: --arch-interaction-op=\"\n + args.arch_interaction_op\n + \" is not supported\"\n )\n arch_mlp_top_adjusted = str(num_int) + \"-\" + args.arch_mlp_top\n ln_top = np.fromstring(arch_mlp_top_adjusted, dtype=int, sep=\"-\")\n\n # sanity check: feature sizes and mlp dimensions must match\n if m_den != ln_bot[0]:\n sys.exit(\n \"ERROR: arch-dense-feature-size \"\n + str(m_den)\n + \" does not match first dim of bottom mlp \"\n + str(ln_bot[0])\n )\n if args.qr_flag:\n if args.qr_operation == \"concat\" and 2 * m_spa != m_den_out:\n sys.exit(\n \"ERROR: 2 arch-sparse-feature-size \"\n + str(2 * m_spa)\n + \" does not match last dim of bottom mlp \"\n + str(m_den_out)\n + \" (note that the last dim of bottom mlp must be 2x the embedding dim)\"\n )\n if args.qr_operation != \"concat\" and m_spa != m_den_out:\n sys.exit(\n \"ERROR: arch-sparse-feature-size \"\n + str(m_spa)\n + \" does not match last dim of bottom mlp \"\n + str(m_den_out)\n )\n else:\n if m_spa != m_den_out:\n sys.exit(\n \"ERROR: arch-sparse-feature-size \"\n + str(m_spa)\n + \" does not match last dim of bottom mlp \"\n + str(m_den_out)\n )\n if num_int != ln_top[0]:\n sys.exit(\n \"ERROR: # of feature interactions \"\n + str(num_int)\n + \" does not match first dimension of top mlp \"\n + str(ln_top[0])\n )\n\n # assign mixed dimensions if applicable\n if args.md_flag:\n m_spa = md_solver(\n torch.tensor(ln_emb),\n args.md_temperature, # alpha\n d0=m_spa,\n round_dim=args.md_round_dims\n ).tolist()\n\n # test prints (model arch)\n if args.debug_mode:\n print(\"model arch:\")\n print(\n \"mlp top arch \"\n + str(ln_top.size - 1)\n + \" layers, with input to output dimensions:\"\n )\n print(ln_top)\n print(\"# of interactions\")\n print(num_int)\n print(\n \"mlp bot arch \"\n + str(ln_bot.size - 1)\n + \" layers, with input to output dimensions:\"\n )\n print(ln_bot)\n print(\"# of features (sparse and dense)\")\n print(num_fea)\n print(\"dense feature size\")\n print(m_den)\n print(\"sparse feature size\")\n print(m_spa)\n print(\n \"# of embeddings (= # of sparse features) \"\n + str(ln_emb.size)\n + \", with dimensions \"\n + str(m_spa)\n + \"x:\"\n )\n print(ln_emb)\n\n print(\"data (inputs and targets):\")\n for j, (X, lS_o, lS_i, T) in enumerate(train_ld):\n # early exit if nbatches was set by the user and has been exceeded\n if nbatches > 0 and j >= nbatches:\n break\n\n print(\"mini-batch: %d\" % j)\n print(X.detach().cpu().numpy())\n # transform offsets to lengths when printing\n print(\n [\n np.diff(\n S_o.detach().cpu().tolist() + list(lS_i[i].shape)\n ).tolist()\n for i, S_o in enumerate(lS_o)\n ]\n )\n print([S_i.detach().cpu().tolist() for S_i in lS_i])\n print(T.detach().cpu().numpy())\n\n ndevices = min(ngpus, args.mini_batch_size, num_fea - 1) if use_gpu else -1\n\n ### construct the neural network specified above ###\n # WARNING: to obtain exactly the same initialization for\n # the weights we need to start from the same random seed.\n # np.random.seed(args.numpy_rand_seed)\n dlrm = DLRM_Net(\n m_spa,\n ln_emb,\n ln_bot,\n ln_top,\n arch_interaction_op=args.arch_interaction_op,\n arch_interaction_itself=args.arch_interaction_itself,\n sigmoid_bot=-1,\n sigmoid_top=ln_top.size - 2,\n sync_dense_params=args.sync_dense_params,\n loss_threshold=args.loss_threshold,\n ndevices=ndevices,\n qr_flag=args.qr_flag,\n qr_operation=args.qr_operation,\n qr_collisions=args.qr_collisions,\n qr_threshold=args.qr_threshold,\n md_flag=args.md_flag,\n md_threshold=args.md_threshold,\n )\n # test prints\n if args.debug_mode:\n print(\"initial parameters (weights and bias):\")\n for param in dlrm.parameters():\n print(param.detach().cpu().numpy())\n\n if use_gpu:\n # Custom Model-Data Parallel\n # the mlps are replicated and use data parallelism, while\n # the embeddings are distributed and use model parallelism\n dlrm = dlrm.to(device) # .cuda()\n if dlrm.ndevices > 1:\n dlrm.emb_l = dlrm.create_emb(m_spa, ln_emb)\n\n # specify the loss function\n if args.loss_function == \"mse\":\n loss_fn = torch.nn.MSELoss(reduction=\"mean\")\n elif args.loss_function == \"bce\":\n loss_fn = torch.nn.BCELoss(reduction=\"mean\")\n elif args.loss_function == \"wbce\":\n loss_ws = torch.tensor(np.fromstring(args.loss_weights, dtype=float, sep=\"-\"))\n loss_fn = torch.nn.BCELoss(reduction=\"none\")\n else:\n sys.exit(\"ERROR: --loss-function=\" + args.loss_function + \" is not supported\")\n\n if not args.inference_only:\n # specify the optimizer algorithm\n optimizer = torch.optim.SGD(dlrm.parameters(), lr=args.learning_rate)\n\n ### main loop ###\n def time_wrap(use_gpu):\n if use_gpu:\n torch.cuda.synchronize()\n return time.time()\n\n def dlrm_wrap(X, lS_o, lS_i, use_gpu, device):\n if use_gpu: # .cuda()\n # lS_i can be either a list of tensors or a stacked tensor.\n # Handle each case below:\n lS_i = [S_i.to(device) for S_i in lS_i] if isinstance(lS_i, list) \\\n else lS_i.to(device)\n lS_o = [S_o.to(device) for S_o in lS_o] if isinstance(lS_o, list) \\\n else lS_o.to(device)\n return dlrm(\n (X.to(device),\n lS_o,\n lS_i)\n )\n else:\n return dlrm(X, lS_o, lS_i)\n\n def loss_fn_wrap(Z, T, use_gpu, device):\n if args.loss_function == \"mse\" or args.loss_function == \"bce\":\n if use_gpu:\n return loss_fn(Z, T.to(device))\n else:\n return loss_fn(Z, T)\n elif args.loss_function == \"wbce\":\n if use_gpu:\n loss_ws_ = loss_ws[T.data.view(-1).long()].view_as(T).to(device)\n loss_fn_ = loss_fn(Z, T.to(device))\n else:\n loss_ws_ = loss_ws[T.data.view(-1).long()].view_as(T)\n loss_fn_ = loss_fn(Z, T.to(device))\n loss_sc_ = loss_ws_ * loss_fn_\n return loss_sc_.mean()\n\n # training or inference\n best_gA_test = 0\n best_auc_test = 0\n skip_upto_epoch = 0\n skip_upto_batch = 0\n total_time = 0\n total_loss = 0\n total_accu = 0\n total_iter = 0\n total_samp = 0\n k = 0\n\n # Load model is specified\n if not (args.load_model == \"\"):\n print(\"Loading saved model {}\".format(args.load_model))\n if use_gpu:\n if dlrm.ndevices > 1:\n # NOTE: when targeting inference on multiple GPUs,\n # load the model as is on CPU or GPU, with the move\n # to multiple GPUs to be done in parallel_forward\n ld_model = torch.load(args.load_model)\n else:\n # NOTE: when targeting inference on single GPU,\n # note that the call to .to(device) has already happened\n ld_model = torch.load(\n args.load_model,\n map_location=torch.device('cuda')\n )\n else:\n # when targeting inference on CPU\n ld_model = torch.load(args.load_model, map_location=torch.device('cpu'))\n dlrm.load_state_dict(ld_model[\"state_dict\"])\n ld_j = ld_model[\"iter\"]\n ld_k = ld_model[\"epoch\"]\n ld_nepochs = ld_model[\"nepochs\"]\n ld_nbatches = ld_model[\"nbatches\"]\n ld_nbatches_test = ld_model[\"nbatches_test\"]\n ld_gA = ld_model[\"train_acc\"]\n ld_gL = ld_model[\"train_loss\"]\n ld_total_loss = ld_model[\"total_loss\"]\n ld_total_accu = ld_model[\"total_accu\"]\n ld_gA_test = ld_model[\"test_acc\"]\n ld_gL_test = ld_model[\"test_loss\"]\n if not args.inference_only:\n optimizer.load_state_dict(ld_model[\"opt_state_dict\"])\n best_gA_test = ld_gA_test\n total_loss = ld_total_loss\n total_accu = ld_total_accu\n skip_upto_epoch = ld_k # epochs\n skip_upto_batch = ld_j # batches\n else:\n args.print_freq = ld_nbatches\n args.test_freq = 0\n\n del ld_model\n\n print(\n \"Saved at: epoch = {:d}/{:d}, batch = {:d}/{:d}, ntbatch = {:d}\".format(\n ld_k, ld_nepochs, ld_j, ld_nbatches, ld_nbatches_test\n )\n )\n print(\n \"Training state: loss = {:.6f}, accuracy = {:3.3f} %\".format(\n ld_gL, ld_gA * 100\n )\n )\n print(\n \"Testing state: loss = {:.6f}, accuracy = {:3.3f} %\".format(\n ld_gL_test, ld_gA_test * 100\n )\n )\n\n def eval_func(model):\n batch_time = AverageMeter('Time', ':6.3f')\n scores = []\n targets = []\n for j, (X_test, lS_o_test, lS_i_test, T) in enumerate(test_ld):\n if j >= args.warmup_iter:\n start = time_wrap(False)\n if not lS_i_test.is_contiguous():\n lS_i_test = lS_i_test.contiguous()\n Z = model(X_test, lS_o_test, lS_i_test)\n S = Z.detach().cpu().numpy() # numpy array\n T = T.detach().cpu().numpy() # numpy array\n scores.append(S)\n targets.append(T)\n if j >= args.warmup_iter:\n batch_time.update(time_wrap(False) - start)\n if args.iter > 0 and j >= args.warmup_iter + args.iter - 1:\n break\n\n scores = np.concatenate(scores, axis=0)\n targets = np.concatenate(targets, axis=0)\n roc_auc = sklearn.metrics.roc_auc_score(targets, scores)\n print('Batch size = %d' % args.test_mini_batch_size)\n print('Latency: %.3f ms' % (batch_time.avg / args.test_mini_batch_size * 1000))\n print('Throughput: %.3f images/sec' % (args.test_mini_batch_size / batch_time.avg))\n print('Accuracy: {roc_auc:.5f}'.format(roc_auc=roc_auc))\n return roc_auc\n\n if args.tune:\n print('tune')\n eval_dataloader = DLRM_DataLoader(test_ld)\n dlrm.eval()\n from neural_compressor.experimental import Quantization, common\n quantizer = Quantization(\"./conf.yaml\")\n quantizer.model = common.Model(dlrm)\n quantizer.calib_dataloader = eval_dataloader\n quantizer.eval_func = eval_func\n q_model = quantizer.fit()\n q_model.save(args.tuned_checkpoint)\n exit(0)\n\n if args.benchmark:\n dlrm.eval()\n if args.int8:\n from neural_compressor.utils.pytorch import load\n import os\n dlrm = load(\n os.path.abspath(os.path.expanduser(args.tuned_checkpoint)), dlrm)\n eval_func(dlrm)\n exit(0)\n\n\n if args.do_int8_inference and args.inference_only:\n print('do_int8_inference')\n fuse_list = []\n for i in range(0, len(dlrm.bot_l), 2):\n fuse_list.append([\"bot_l.%d\" % (i), \"bot_l.%d\" % (i + 1)])\n dlrm = fuse_modules(dlrm, fuse_list, inplace=True)\n fuse_list = []\n for i in range(0, len(dlrm.top_l) - 2, 2):\n fuse_list.append([\"top_l.%d\" % (i), \"top_l.%d\" % (i + 1)])\n dlrm = fuse_modules(dlrm, fuse_list, inplace=True)\n dlrm.bot_l.insert(0, QuantStub())\n dlrm.bot_l.append(DeQuantStub())\n dlrm.top_l.insert(0, QuantStub())\n dlrm.top_l.insert(len(dlrm.top_l) - 1, DeQuantStub())\n dlrm.qconfig = torch.quantization.QConfig(activation=torch.quantization.observer.MinMaxObserver.with_args(reduce_range=False),\n weight=torch.quantization.default_weight_observer)\n if args.per_tensor_linear:\n dlrm.bot_l.qconfig = default_qconfig\n dlrm.top_l.qconfig = default_qconfig\n dlrm = prepare(dlrm, inplace=True)\n j = 0\n for j, (X_test, lS_o_test, lS_i_test, T) in enumerate(test_ld):\n Z = dlrm_wrap(X_test, lS_o_test, lS_i_test, use_gpu, device)\n if j > nbatches * 0.05:\n break\n print(\"convert\")\n dlrm = convert(dlrm, inplace=True)\n print(\"convert done\")\n if not (args.save_int8 == \"\"):\n print(\"Saving model to {}\".format(args.save_int8))\n torch.save(\n {\n \"epoch\": ld_k,\n \"nepochs\": ld_nepochs,\n \"nbatches\": ld_nbatches,\n \"nbatches_test\": ld_nbatches_test,\n \"iter\": ld_j,\n \"state_dict\": dlrm.state_dict(),\n \"train_acc\": ld_gA,\n \"train_loss\": ld_gL,\n \"test_acc\": ld_gA_test,\n \"test_loss\": ld_gL_test,\n \"total_loss\": ld_total_loss,\n \"total_accu\": ld_total_accu,\n },\n args.save_int8,\n )\n\n print(\"time/loss/accuracy (if enabled):\")\n with torch.autograd.profiler.profile(args.enable_profiling, use_gpu) as prof:\n while k < args.nepochs:\n if k < skip_upto_epoch:\n continue\n\n accum_time_begin = time_wrap(use_gpu)\n\n if args.mlperf_logging:\n previous_iteration_time = None\n if args.mlperf_logging:\n scores = []\n targets = []\n for j, (X_test, lS_o_test, lS_i_test, T) in enumerate(test_ld):\n if j < skip_upto_batch:\n continue\n\n if args.mlperf_logging:\n current_time = time_wrap(use_gpu)\n if previous_iteration_time:\n iteration_time = current_time - previous_iteration_time\n else:\n iteration_time = 0\n previous_iteration_time = current_time\n else:\n t1 = time_wrap(use_gpu)\n\n # early exit if nbatches was set by the user and has been exceeded\n if nbatches > 0 and j >= nbatches:\n break\n '''\n # debug prints\n print(\"input and targets\")\n print(X.detach().cpu().numpy())\n print([np.diff(S_o.detach().cpu().tolist()\n + list(lS_i[i].shape)).tolist() for i, S_o in enumerate(lS_o)])\n print([S_i.detach().cpu().numpy().tolist() for S_i in lS_i])\n print(T.detach().cpu().numpy())\n '''\n\n # forward pass\n Z = dlrm_wrap(X_test, lS_o_test, lS_i_test, use_gpu, device)\n\n # loss\n E = loss_fn_wrap(Z, T, use_gpu, device)\n '''\n # debug prints\n print(\"output and loss\")\n print(Z.detach().cpu().numpy())\n print(E.detach().cpu().numpy())\n '''\n # compute loss and accuracy\n L = E.detach().cpu().numpy() # numpy array\n S = Z.detach().cpu().numpy() # numpy array\n T = T.detach().cpu().numpy() # numpy array\n if args.mlperf_logging:\n scores.append(S)\n targets.append(T)\n mbs = T.shape[0] # = args.mini_batch_size except maybe for last\n A = np.sum((np.round(S, 0) == T).astype(np.uint8))\n\n if not args.inference_only:\n # scaled error gradient propagation\n # (where we do not accumulate gradients across mini-batches)\n optimizer.zero_grad()\n # backward pass\n E.backward()\n\n # optimizer\n optimizer.step()\n\n if args.mlperf_logging:\n total_time += iteration_time\n else:\n t2 = time_wrap(use_gpu)\n total_time += t2 - t1\n total_accu += A\n total_loss += L * mbs\n total_iter += 1\n total_samp += mbs\n\n should_print = ((j + 1) % args.print_freq == 0) or (j + 1 == nbatches)\n should_test = (\n (args.test_freq > 0)\n and (args.data_generation == \"dataset\")\n and (((j + 1) % args.test_freq == 0) or (j + 1 == nbatches))\n )\n\n # print time, loss and accuracy\n if should_print or should_test:\n if args.mlperf_logging:\n scores = np.concatenate(scores, axis=0)\n targets = np.concatenate(targets, axis=0)\n metrics = {\n 'loss' : sklearn.metrics.log_loss,\n 'recall' : lambda y_true, y_score:\n sklearn.metrics.recall_score(\n y_true=y_true,\n y_pred=np.round(y_score)\n ),\n 'precision' : lambda y_true, y_score:\n sklearn.metrics.precision_score(\n y_true=y_true,\n y_pred=np.round(y_score)\n ),\n 'f1' : lambda y_true, y_score:\n sklearn.metrics.f1_score(\n y_true=y_true,\n y_pred=np.round(y_score)\n ),\n 'ap' : sklearn.metrics.average_precision_score,\n 'roc_auc' : sklearn.metrics.roc_auc_score,\n }\n\n validation_results = {}\n for metric_name, metric_function in metrics.items():\n validation_results[metric_name] = metric_function(\n targets,\n scores\n )\n gT = 1000.0 * total_time / total_iter if args.print_time else -1\n total_time = 0\n\n gA = total_accu / total_samp\n total_accu = 0\n\n gL = total_loss / total_samp\n total_loss = 0\n\n str_run_type = \"inference\" if args.inference_only else \"training\"\n print(\n \"Finished {} it {}/{} of epoch {}, {:.2f} ms/it, \".format(\n str_run_type, j + 1, nbatches, k, gT\n )\n + \"loss {:.6f}, accuracy {:3.3f} %\".format(gL, gA * 100)\n )\n print(\n \" loss {:.6f}, recall {:.4f}, precision {:.4f},\".format(\n validation_results['loss'],\n validation_results['recall'],\n validation_results['precision']\n )\n + \" f1 {:.4f}, ap {:.4f},\".format(\n validation_results['f1'],\n validation_results['ap'],\n )\n + \" auc {:.4f},\".format(\n validation_results['roc_auc'],\n )\n )\n total_iter = 0\n total_samp = 0\n\n # testing\n if should_test and not args.inference_only:\n # don't measure training iter time in a test iteration\n if args.mlperf_logging:\n previous_iteration_time = None\n\n test_accu = 0\n test_loss = 0\n test_samp = 0\n\n accum_test_time_begin = time_wrap(use_gpu)\n if args.mlperf_logging:\n scores = []\n targets = []\n\n for i, (X_test, lS_o_test, lS_i_test, T_test) in enumerate(test_ld):\n # early exit if nbatches was set by the user and was exceeded\n if nbatches > 0 and i >= nbatches:\n break\n\n t1_test = time_wrap(use_gpu)\n\n # forward pass\n Z_test = dlrm_wrap(\n X_test, lS_o_test, lS_i_test, use_gpu, device\n )\n if args.mlperf_logging:\n S_test = Z_test.detach().cpu().numpy() # numpy array\n T_test = T_test.detach().cpu().numpy() # numpy array\n scores.append(S_test)\n targets.append(T_test)\n else:\n # loss\n E_test = loss_fn_wrap(Z_test, T_test, use_gpu, device)\n\n # compute loss and accuracy\n L_test = E_test.detach().cpu().numpy() # numpy array\n S_test = Z_test.detach().cpu().numpy() # numpy array\n T_test = T_test.detach().cpu().numpy() # numpy array\n mbs_test = T_test.shape[0] # = mini_batch_size except last\n A_test = np.sum((np.round(S_test, 0) == T_test).astype(np.uint8))\n test_accu += A_test\n test_loss += L_test * mbs_test\n test_samp += mbs_test\n\n t2_test = time_wrap(use_gpu)\n\n if args.mlperf_logging:\n scores = np.concatenate(scores, axis=0)\n targets = np.concatenate(targets, axis=0)\n\n metrics = {\n 'loss' : sklearn.metrics.log_loss,\n 'recall' : lambda y_true, y_score:\n sklearn.metrics.recall_score(\n y_true=y_true,\n y_pred=np.round(y_score)\n ),\n 'precision' : lambda y_true, y_score:\n sklearn.metrics.precision_score(\n y_true=y_true,\n y_pred=np.round(y_score)\n ),\n 'f1' : lambda y_true, y_score:\n sklearn.metrics.f1_score(\n y_true=y_true,\n y_pred=np.round(y_score)\n ),\n 'ap' : sklearn.metrics.average_precision_score,\n 'roc_auc' : sklearn.metrics.roc_auc_score,\n 'accuracy' : lambda y_true, y_score:\n sklearn.metrics.accuracy_score(\n y_true=y_true,\n y_pred=np.round(y_score)\n ),\n # 'pre_curve' : sklearn.metrics.precision_recall_curve,\n # 'roc_curve' : sklearn.metrics.roc_curve,\n }\n\n validation_results = {}\n for metric_name, metric_function in metrics.items():\n validation_results[metric_name] = metric_function(\n targets,\n scores\n )\n gA_test = validation_results['accuracy']\n gL_test = validation_results['loss']\n else:\n gA_test = test_accu / test_samp\n gL_test = test_loss / test_samp\n\n is_best = gA_test > best_gA_test\n if is_best:\n best_gA_test = gA_test\n if not (args.save_model == \"\"):\n print(\"Saving model to {}\".format(args.save_model))\n torch.save(\n {\n \"epoch\": k,\n \"nepochs\": args.nepochs,\n \"nbatches\": nbatches,\n \"nbatches_test\": nbatches_test,\n \"iter\": j + 1,\n \"state_dict\": dlrm.state_dict(),\n \"train_acc\": gA,\n \"train_loss\": gL,\n \"test_acc\": gA_test,\n \"test_loss\": gL_test,\n \"total_loss\": total_loss,\n \"total_accu\": total_accu,\n \"opt_state_dict\": optimizer.state_dict(),\n },\n args.save_model,\n )\n\n if args.mlperf_logging:\n is_best = validation_results['roc_auc'] > best_auc_test\n if is_best:\n best_auc_test = validation_results['roc_auc']\n\n print(\n \"Testing at - {}/{} of epoch {},\".format(j + 1, nbatches, k)\n + \" loss {:.6f}, recall {:.4f}, precision {:.4f},\".format(\n validation_results['loss'],\n validation_results['recall'],\n validation_results['precision']\n )\n + \" f1 {:.4f}, ap {:.4f},\".format(\n validation_results['f1'],\n validation_results['ap'],\n )\n + \" auc {:.4f}, best auc {:.4f},\".format(\n validation_results['roc_auc'],\n best_auc_test\n )\n + \" accuracy {:3.3f} %, best accuracy {:3.3f} %\".format(\n validation_results['accuracy'] * 100,\n best_gA_test * 100\n )\n )\n else:\n print(\n \"Testing at - {}/{} of epoch {},\".format(j + 1, nbatches, 0)\n + \" loss {:.6f}, accuracy {:3.3f} %, best {:3.3f} %\".format(\n gL_test, gA_test * 100, best_gA_test * 100\n )\n )\n\n if (args.mlperf_logging\n and (args.mlperf_acc_threshold > 0)\n and (best_gA_test > args.mlperf_acc_threshold)):\n print(\"MLPerf testing accuracy threshold \"\n + str(args.mlperf_acc_threshold)\n + \" reached, stop training\")\n break\n\n if (args.mlperf_logging\n and (args.mlperf_auc_threshold > 0)\n and (best_auc_test > args.mlperf_auc_threshold)):\n print(\"MLPerf testing auc threshold \"\n + str(args.mlperf_auc_threshold)\n + \" reached, stop training\")\n break\n\n k += 1 # nepochs\n\n # profiling\n if args.enable_profiling:\n with open(\"dlrm_s_pytorch.prof\", \"w\") as prof_f:\n prof_f.write(prof.key_averages().table(sort_by=\"cpu_time_total\"))\n prof.export_chrome_trace(\"./dlrm_s_pytorch.json\")\n print(prof.key_averages().table(sort_by=\"cpu_time_total\"))\n\n # plot compute graph\n if args.plot_compute_graph:\n sys.exit(\n \"ERROR: Please install pytorchviz package in order to use the\"\n + \" visualization. Then, uncomment its import above as well as\"\n + \" three lines below and run the code again.\"\n )\n\n # test prints\n if not args.inference_only and args.debug_mode:\n print(\"updated parameters (weights and bias):\")\n for param in dlrm.parameters():\n print(param.detach().cpu().numpy())\n\n # export the model in onnx\n if args.save_onnx:\n with open(\"dlrm_s_pytorch.onnx\", \"w+b\") as dlrm_pytorch_onnx_file:\n (X, lS_o, lS_i, _) = train_data[0] # get first batch of elements\n torch.onnx._export(\n dlrm, (X, lS_o, lS_i), dlrm_pytorch_onnx_file, verbose=True\n )\n # recover the model back\n dlrm_pytorch_onnx = onnx.load(\"dlrm_s_pytorch.onnx\")\n # check the onnx model\n onnx.checker.check_model(dlrm_pytorch_onnx)\n",
"import argparse\nimport os\nimport random\nimport shutil\nimport time\nimport warnings\nimport sys\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.distributed as dist\nimport torch.optim\nimport torch.multiprocessing as mp\nimport torch.utils.data\nimport torch.utils.data.distributed\nimport torchvision.transforms as transforms\nimport torchvision.datasets as datasets\nimport torchvision.models as models\n\nmodel_names = sorted(name for name in models.__dict__\n if name.islower() and not name.startswith(\"__\")\n and callable(models.__dict__[name]))\n\nparser = argparse.ArgumentParser(description='PyTorch ImageNet Training')\nparser.add_argument('data', metavar='DIR',\n help='path to dataset')\nparser.add_argument('-a', '--arch', metavar='ARCH', default='resnet18',\n choices=model_names,\n help='model architecture: ' +\n ' | '.join(model_names) +\n ' (default: resnet18)')\nparser.add_argument('-j', '--workers', default=4, type=int, metavar='N',\n help='number of data loading workers (default: 4)')\nparser.add_argument('--epochs', default=90, type=int, metavar='N',\n help='number of total epochs to run')\nparser.add_argument('--start-epoch', default=0, type=int, metavar='N',\n help='manual epoch number (useful on restarts)')\nparser.add_argument('-b', '--batch-size', default=256, type=int,\n metavar='N',\n help='mini-batch size (default: 256), this is the total '\n 'batch size of all GPUs on the current node when '\n 'using Data Parallel or Distributed Data Parallel')\nparser.add_argument('--lr', '--learning-rate', default=0.1, type=float,\n metavar='LR', help='initial learning rate', dest='lr')\nparser.add_argument('--momentum', default=0.9, type=float, metavar='M',\n help='momentum')\nparser.add_argument('--wd', '--weight-decay', default=1e-4, type=float,\n metavar='W', help='weight decay (default: 1e-4)',\n dest='weight_decay')\nparser.add_argument('-p', '--print-freq', default=10, type=int,\n metavar='N', help='print frequency (default: 10)')\nparser.add_argument('--resume', default='', type=str, metavar='PATH',\n help='path to latest checkpoint (default: none)')\nparser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true',\n help='evaluate model on validation set')\nparser.add_argument('-t', '--tune', dest='tune', action='store_true',\n help='tune best int8 model on calibration dataset')\nparser.add_argument('--pretrained', dest='pretrained', action='store_true',\n help='use pre-trained model')\nparser.add_argument('--world-size', default=-1, type=int,\n help='number of nodes for distributed training')\nparser.add_argument('--rank', default=-1, type=int,\n help='node rank for distributed training')\nparser.add_argument('--dist-url', default='tcp://224.66.41.62:23456', type=str,\n help='url used to set up distributed training')\nparser.add_argument('--dist-backend', default='nccl', type=str,\n help='distributed backend')\nparser.add_argument('--seed', default=None, type=int,\n help='seed for initializing training. ')\nparser.add_argument('--gpu', default=None, type=int,\n help='GPU id to use.')\nparser.add_argument('--ppn', default=1, type=int,\n help='number of processes on each node of distributed training')\nparser.add_argument('--multiprocessing-distributed', action='store_true',\n help='Use multi-processing distributed training to launch '\n 'N processes per node, which has N GPUs. This is the '\n 'fastest way to use PyTorch for either single node or '\n 'multi node data parallel training')\nparser.add_argument('-i', \"--iter\", default=0, type=int,\n help='For accuracy measurement only.')\nparser.add_argument('-w', \"--warmup_iter\", default=5, type=int,\n help='For benchmark measurement only.')\nparser.add_argument('--benchmark', dest='benchmark', action='store_true',\n help='run benchmark')\nparser.add_argument('-r', \"--accuracy_only\", dest='accuracy_only', action='store_true',\n help='For accuracy measurement only.')\nparser.add_argument(\"--tuned_checkpoint\", default='./saved_results', type=str, metavar='PATH',\n help='path to checkpoint tuned by Neural Compressor (default: ./)')\nparser.add_argument('--int8', dest='int8', action='store_true',\n help='run benchmark')\n\nbest_acc1 = 0\n\n\ndef main():\n args = parser.parse_args()\n\n if args.seed is not None:\n random.seed(args.seed)\n torch.manual_seed(args.seed)\n\n if args.pretrained:\n print(\"=> using pre-trained model '{}'\".format(args.arch))\n model = models.__dict__[args.arch](pretrained=True)\n else:\n print(\"=> creating model '{}'\".format(args.arch))\n model = models.__dict__[args.arch]()\n\n # define loss function (criterion) and optimizer\n criterion = nn.CrossEntropyLoss()\n\n optimizer = torch.optim.SGD(model.parameters(), args.lr,\n momentum=args.momentum,\n weight_decay=args.weight_decay)\n\n # optionally resume from a checkpoint\n if args.resume:\n if os.path.isfile(args.resume):\n print(\"=> loading checkpoint '{}'\".format(args.resume))\n checkpoint = torch.load(args.resume)\n args.start_epoch = checkpoint['epoch']\n best_acc1 = checkpoint['best_acc1']\n if args.gpu is not None:\n # best_acc1 may be from a checkpoint from a different GPU\n best_acc1 = best_acc1.to(args.gpu)\n model.load_state_dict(checkpoint['state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n print(\"=> loaded checkpoint '{}' (epoch {})\"\n .format(args.resume, checkpoint['epoch']))\n else:\n print(\"=> no checkpoint found at '{}'\".format(args.resume))\n\n # Data loading code\n traindir = os.path.join(args.data, 'train')\n valdir = os.path.join(args.data, 'val')\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n train_dataset = datasets.ImageFolder(\n traindir,\n transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ]))\n\n train_loader = torch.utils.data.DataLoader(\n train_dataset, batch_size=args.batch_size, shuffle=True,\n num_workers=args.workers, pin_memory=True, sampler=None)\n\n val_dataset = datasets.ImageFolder(valdir, transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize,\n ]))\n\n val_loader = torch.utils.data.DataLoader(\n val_dataset,\n batch_size=args.batch_size, shuffle=False,\n num_workers=args.workers, pin_memory=True)\n\n if args.evaluate:\n validate(val_loader, model, criterion, args)\n return\n\n if args.tune:\n from neural_compressor.experimental import Quantization, common\n model.eval()\n quantizer = Quantization(\"./conf.yaml\")\n quantizer.model = common.Model(model)\n q_model = quantizer.fit()\n q_model.save(args.tuned_checkpoint)\n return\n\n if args.benchmark or args.accuracy_only:\n model.eval()\n if args.int8:\n from neural_compressor.utils.pytorch import load\n new_model = load(\n os.path.abspath(os.path.expanduser(args.tuned_checkpoint)), model)\n else:\n new_model = model\n validate(val_loader, new_model, criterion, args)\n return\n\n\ndef train(train_loader, model, criterion, optimizer, epoch, args):\n batch_time = AverageMeter('Time', ':6.3f')\n data_time = AverageMeter('Data', ':6.3f')\n losses = AverageMeter('Loss', ':.4e')\n top1 = AverageMeter('Acc@1', ':6.2f')\n top5 = AverageMeter('Acc@5', ':6.2f')\n progress = ProgressMeter(len(train_loader), batch_time, data_time, losses, top1,\n top5, prefix=\"Epoch: [{}]\".format(epoch))\n\n # switch to train mode\n model.train()\n\n end = time.time()\n for i, (input, target) in enumerate(train_loader):\n # measure data loading time\n data_time.update(time.time() - end)\n\n if args.gpu is not None:\n input = input.cuda(args.gpu, non_blocking=True)\n target = target.cuda(args.gpu, non_blocking=True)\n\n # compute output\n output = model(input)\n loss = criterion(output, target)\n\n # measure accuracy and record loss\n acc1, acc5 = accuracy(output, target, topk=(1, 5))\n losses.update(loss.item(), input.size(0))\n top1.update(acc1[0], input.size(0))\n top5.update(acc5[0], input.size(0))\n\n # compute gradient and do SGD step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if i % args.print_freq == 0:\n progress.print(i)\n\n\ndef validate(val_loader, model, criterion, args):\n batch_time = AverageMeter('Time', ':6.3f')\n losses = AverageMeter('Loss', ':.4e')\n top1 = AverageMeter('Acc@1', ':6.2f')\n top5 = AverageMeter('Acc@5', ':6.2f')\n progress = ProgressMeter(len(val_loader), batch_time, losses, top1, top5,\n prefix='Test: ')\n\n # switch to evaluate mode\n model.eval()\n\n with torch.no_grad():\n for i, (input, target) in enumerate(val_loader):\n if i >= args.warmup_iter:\n start = time.time()\n if args.gpu is not None:\n input = input.cuda(args.gpu, non_blocking=True)\n target = target.cuda(args.gpu, non_blocking=True)\n\n # compute output\n output = model(input)\n loss = criterion(output, target)\n\n # measure accuracy and record loss\n acc1, acc5 = accuracy(output, target, topk=(1, 5))\n losses.update(loss.item(), input.size(0))\n top1.update(acc1[0], input.size(0))\n top5.update(acc5[0], input.size(0))\n\n # measure elapsed time\n if i >= args.warmup_iter:\n batch_time.update(time.time() - start)\n\n if i % args.print_freq == 0:\n progress.print(i)\n\n if args.iter > 0 and i >= (args.warmup_iter + args.iter - 1):\n break\n\n print('Batch size = %d' % args.batch_size)\n if args.batch_size == 1:\n print('Latency: %.3f ms' % (batch_time.avg * 1000))\n print('Throughput: %.3f images/sec' % (args.batch_size / batch_time.avg))\n\n # TODO: this should also be done with the ProgressMeter\n print('Accuracy: {top1:.5f} Accuracy@5 {top5:.5f}'\n .format(top1=(top1.avg / 100), top5=(top5.avg / 100)))\n\n return top1.avg\n\n\ndef save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):\n torch.save(state, filename)\n if is_best:\n shutil.copyfile(filename, 'model_best.pth.tar')\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self, name, fmt=':f'):\n self.name = name\n self.fmt = fmt\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n def __str__(self):\n fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})'\n return fmtstr.format(**self.__dict__)\n\n\nclass ProgressMeter(object):\n def __init__(self, num_batches, *meters, prefix=\"\"):\n self.batch_fmtstr = self._get_batch_fmtstr(num_batches)\n self.meters = meters\n self.prefix = prefix\n\n def print(self, batch):\n entries = [self.prefix + self.batch_fmtstr.format(batch)]\n entries += [str(meter) for meter in self.meters]\n print('\\t'.join(entries))\n\n def _get_batch_fmtstr(self, num_batches):\n num_digits = len(str(num_batches // 1))\n fmt = '{:' + str(num_digits) + 'd}'\n return '[' + fmt + '/' + fmt.format(num_batches) + ']'\n\n\ndef adjust_learning_rate(optimizer, epoch, args):\n \"\"\"Sets the learning rate to the initial LR decayed by 10 every 30 epochs\"\"\"\n lr = args.lr * (0.1 ** (epoch // 30))\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\ndef accuracy(output, target, topk=(1,)):\n \"\"\"Computes the accuracy over the k top predictions for the specified values of k\"\"\"\n with torch.no_grad():\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)\n res.append(correct_k.mul_(100.0 / batch_size))\n return res\n\n\nif __name__ == '__main__':\n main()\n",
"\"\"\"Tests for quantization\"\"\"\r\nimport numpy as np\r\nimport unittest\r\nimport shutil\r\nimport os\r\nimport yaml\r\nimport tensorflow as tf\r\n\r\ndef build_fake_yaml():\r\n fake_yaml = '''\r\n model:\r\n name: fake_yaml\r\n framework: tensorflow\r\n inputs: x\r\n outputs: op2_to_store\r\n device: cpu\r\n evaluation:\r\n accuracy:\r\n metric:\r\n topk: 1\r\n tuning:\r\n strategy:\r\n name: basic\r\n accuracy_criterion:\r\n relative: 0.01\r\n workspace:\r\n path: saved\r\n '''\r\n y = yaml.load(fake_yaml, Loader=yaml.SafeLoader)\r\n with open('fake_yaml.yaml',\"w\",encoding=\"utf-8\") as f:\r\n yaml.dump(y,f)\r\n f.close()\r\n\r\ndef build_fake_yaml2():\r\n fake_yaml = '''\r\n model:\r\n name: fake_yaml\r\n framework: tensorflow\r\n inputs: x\r\n outputs: op2_to_store\r\n device: cpu\r\n evaluation:\r\n accuracy:\r\n metric:\r\n topk: 1\r\n tuning:\r\n strategy:\r\n name: basic\r\n exit_policy:\r\n max_trials: 10\r\n accuracy_criterion:\r\n relative: -0.01\r\n workspace:\r\n path: saved\r\n '''\r\n y = yaml.load(fake_yaml, Loader=yaml.SafeLoader)\r\n with open('fake_yaml2.yaml',\"w\",encoding=\"utf-8\") as f:\r\n yaml.dump(y,f)\r\n f.close()\r\n\r\ndef build_fake_model():\r\n try:\r\n graph = tf.Graph()\r\n graph_def = tf.compat.v1.GraphDef()\r\n with tf.compat.v1.Session() as sess:\r\n x = tf.compat.v1.placeholder(tf.float32, shape=(1,3,3,1), name='x')\r\n y = tf.constant(np.random.random((2,2,1,1)).astype(np.float32), name='y')\r\n z = tf.constant(np.random.random((1,1,1,1)).astype(np.float32), name='z')\r\n op = tf.nn.conv2d(input=x, filters=y, strides=[1,1,1,1], padding='VALID', name='op_to_store')\r\n op2 = tf.nn.conv2d(input=op, filters=z, strides=[1,1,1,1], padding='VALID', name='op2_to_store')\r\n\r\n sess.run(tf.compat.v1.global_variables_initializer())\r\n constant_graph = tf.compat.v1.graph_util.convert_variables_to_constants(sess, sess.graph_def, ['op2_to_store'])\r\n\r\n graph_def.ParseFromString(constant_graph.SerializeToString())\r\n with graph.as_default():\r\n tf.import_graph_def(graph_def, name='')\r\n except:\r\n graph = tf.Graph()\r\n graph_def = tf.compat.v1.GraphDef()\r\n with tf.compat.v1.Session() as sess:\r\n x = tf.compat.v1.placeholder(tf.float32, shape=(1,3,3,1), name='x')\r\n y = tf.constant(np.random.random((2,2,1,1)).astype(np.float32), name='y')\r\n z = tf.constant(np.random.random((1,1,1,1)).astype(np.float32), name='z')\r\n op = tf.nn.conv2d(input=x, filters=y, strides=[1,1,1,1], padding='VALID', name='op_to_store')\r\n op2 = tf.nn.conv2d(input=op, filters=z, strides=[1,1,1,1], padding='VALID', name='op2_to_store')\r\n\r\n sess.run(tf.compat.v1.global_variables_initializer())\r\n constant_graph = tf.compat.v1.graph_util.convert_variables_to_constants(sess, sess.graph_def, ['op2_to_store'])\r\n\r\n graph_def.ParseFromString(constant_graph.SerializeToString())\r\n with graph.as_default():\r\n tf.import_graph_def(graph_def, name='')\r\n return graph\r\n\r\nclass TestQuantization(unittest.TestCase):\r\n\r\n @classmethod\r\n def setUpClass(self):\r\n self.constant_graph = build_fake_model()\r\n build_fake_yaml()\r\n build_fake_yaml2()\r\n\r\n @classmethod\r\n def tearDownClass(self):\r\n os.remove('fake_yaml.yaml')\r\n os.remove('fake_yaml2.yaml')\r\n shutil.rmtree('saved', ignore_errors=True)\r\n\r\n def test_run_basic_one_trial(self):\r\n from neural_compressor.experimental import Quantization, common\r\n\r\n quantizer = Quantization('fake_yaml.yaml')\r\n dataset = quantizer.dataset('dummy', (100, 3, 3, 1), label=True)\r\n quantizer.calib_dataloader = common.DataLoader(dataset)\r\n quantizer.eval_dataloader = common.DataLoader(dataset)\r\n quantizer.model = self.constant_graph\r\n quantizer.fit()\r\n\r\n\r\n def test_run_basic_max_trials(self):\r\n from neural_compressor.experimental import Quantization, common\r\n\r\n quantizer = Quantization('fake_yaml2.yaml')\r\n dataset = quantizer.dataset('dummy', (100, 3, 3, 1), label=True)\r\n quantizer.calib_dataloader = common.DataLoader(dataset)\r\n quantizer.eval_dataloader = common.DataLoader(dataset)\r\n quantizer.model = self.constant_graph\r\n quantizer.fit()\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main()\r\n",
"# coding=utf-8\n# Copyright 2020-present the HuggingFace Inc. 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\"\"\"\nThe Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task.\n\"\"\"\n\nimport collections\nimport gc\nimport inspect\nimport math\nimport os\nimport re\nimport shutil\nimport time\nimport warnings\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union\n\n\n# Integrations must be imported before ML frameworks:\nfrom .integrations import ( # isort: split\n default_hp_search_backend,\n get_reporting_integration_callbacks,\n hp_params,\n is_fairscale_available,\n is_optuna_available,\n is_ray_tune_available,\n run_hp_search_optuna,\n run_hp_search_ray,\n init_deepspeed,\n)\n\nimport numpy as np\nimport torch\nfrom packaging import version\nfrom torch import nn\nfrom torch.utils.data.dataloader import DataLoader\nfrom torch.utils.data.dataset import Dataset\nfrom torch.utils.data.distributed import DistributedSampler\nfrom torch.utils.data.sampler import RandomSampler, SequentialSampler\n\nfrom .data.data_collator import DataCollator, DataCollatorWithPadding, default_data_collator\nfrom .file_utils import (\n WEIGHTS_NAME,\n is_apex_available,\n is_datasets_available,\n is_in_notebook,\n is_sagemaker_distributed_available,\n is_torch_tpu_available,\n)\nfrom .modeling_utils import PreTrainedModel\nfrom .models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING\nfrom .optimization import Adafactor, AdamW, get_scheduler\nfrom .tokenization_utils_base import PreTrainedTokenizerBase\nfrom .trainer_callback import (\n CallbackHandler,\n DefaultFlowCallback,\n PrinterCallback,\n ProgressCallback,\n TrainerCallback,\n TrainerControl,\n TrainerState,\n)\nfrom .trainer_pt_utils import (\n DistributedLengthGroupedSampler,\n DistributedTensorGatherer,\n LabelSmoother,\n LengthGroupedSampler,\n SequentialDistributedSampler,\n distributed_broadcast_scalars,\n distributed_concat,\n nested_concat,\n nested_detach,\n nested_numpify,\n nested_xla_mesh_reduce,\n reissue_pt_warnings,\n)\nfrom .trainer_utils import (\n PREFIX_CHECKPOINT_DIR,\n BestRun,\n EvalPrediction,\n HPSearchBackend,\n PredictionOutput,\n ShardedDDPOption,\n TrainerMemoryTracker,\n TrainOutput,\n default_compute_objective,\n default_hp_space,\n get_last_checkpoint,\n set_seed,\n speed_metrics,\n)\nfrom .training_args import ParallelMode, TrainingArguments\nfrom .utils import logging\n\n\n_is_native_amp_available = False\n\nDEFAULT_CALLBACKS = [DefaultFlowCallback]\nDEFAULT_PROGRESS_CALLBACK = ProgressCallback\n\nif is_in_notebook():\n from .utils.notebook import NotebookProgressCallback\n\n DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback\n\nif is_apex_available():\n from apex import amp\n\nif version.parse(torch.__version__) >= version.parse(\"1.6\"):\n _is_native_amp_available = True\n from torch.cuda.amp import autocast\n\nif is_datasets_available():\n import datasets\n\nif is_torch_tpu_available():\n import torch_xla.core.xla_model as xm\n import torch_xla.debug.metrics as met\n import torch_xla.distributed.parallel_loader as pl\n\nif is_fairscale_available():\n import fairscale\n from fairscale.nn.data_parallel import ShardedDataParallel as ShardedDDP\n from fairscale.optim import OSS\n from fairscale.optim.grad_scaler import ShardedGradScaler\n\n if version.parse(fairscale.__version__) >= version.parse(\"0.3\"):\n from fairscale.nn.data_parallel import FullyShardedDataParallel as FullyShardedDDP\n else:\n FullyShardedDDP = None\n\nif is_sagemaker_distributed_available():\n import smdistributed.dataparallel.torch.distributed as dist\n from smdistributed.dataparallel.torch.parallel.distributed import DistributedDataParallel as DDP\nelse:\n import torch.distributed as dist\n\nif TYPE_CHECKING:\n import optuna\n\nlogger = logging.get_logger(__name__)\n\n\ndef _model_unwrap(model: nn.Module) -> nn.Module:\n # since there could be multiple levels of wrapping, unwrap recursively\n if hasattr(model, \"module\"):\n return _model_unwrap(model.module)\n else:\n return model\n\n\nclass Trainer:\n \"\"\"\n Trainer is a simple but feature-complete training and eval loop for PyTorch, optimized for 🤗 Transformers.\n\n Args:\n model (:class:`~transformers.PreTrainedModel` or :obj:`torch.nn.Module`, `optional`):\n The model to train, evaluate or use for predictions. If not provided, a ``model_init`` must be passed.\n\n .. note::\n\n :class:`~transformers.Trainer` is optimized to work with the :class:`~transformers.PreTrainedModel`\n provided by the library. You can still use your own models defined as :obj:`torch.nn.Module` as long as\n they work the same way as the 🤗 Transformers models.\n args (:class:`~transformers.TrainingArguments`, `optional`):\n The arguments to tweak for training. Will default to a basic instance of\n :class:`~transformers.TrainingArguments` with the ``output_dir`` set to a directory named `tmp_trainer` in\n the current directory if not provided.\n data_collator (:obj:`DataCollator`, `optional`):\n The function to use to form a batch from a list of elements of :obj:`train_dataset` or :obj:`eval_dataset`.\n Will default to :func:`~transformers.default_data_collator` if no ``tokenizer`` is provided, an instance of\n :func:`~transformers.DataCollatorWithPadding` otherwise.\n train_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`):\n The dataset to use for training. If it is an :obj:`datasets.Dataset`, columns not accepted by the\n ``model.forward()`` method are automatically removed.\n eval_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`):\n The dataset to use for evaluation. If it is an :obj:`datasets.Dataset`, columns not accepted by the\n ``model.forward()`` method are automatically removed.\n tokenizer (:class:`PreTrainedTokenizerBase`, `optional`):\n The tokenizer used to preprocess the data. If provided, will be used to automatically pad the inputs the\n maximum length when batching inputs, and it will be saved along the model to make it easier to rerun an\n interrupted training or reuse the fine-tuned model.\n model_init (:obj:`Callable[[], PreTrainedModel]`, `optional`):\n A function that instantiates the model to be used. If provided, each call to\n :meth:`~transformers.Trainer.train` will start from a new instance of the model as given by this function.\n\n The function may have zero argument, or a single one containing the optuna/Ray Tune trial object, to be\n able to choose different architectures according to hyper parameters (such as layer count, sizes of inner\n layers, dropout probabilities etc).\n compute_metrics (:obj:`Callable[[EvalPrediction], Dict]`, `optional`):\n The function that will be used to compute metrics at evaluation. Must take a\n :class:`~transformers.EvalPrediction` and return a dictionary string to metric values.\n callbacks (List of :obj:`~transformers.TrainerCallback`, `optional`):\n A list of callbacks to customize the training loop. Will add those to the list of default callbacks\n detailed in :doc:`here <callback>`.\n\n If you want to remove one of the default callbacks used, use the :meth:`Trainer.remove_callback` method.\n optimizers (:obj:`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR`, `optional`): A tuple\n containing the optimizer and the scheduler to use. Will default to an instance of\n :class:`~transformers.AdamW` on your model and a scheduler given by\n :func:`~transformers.get_linear_schedule_with_warmup` controlled by :obj:`args`.\n\n Important attributes:\n\n - **model** -- Always points to the core model. If using a transformers model, it will be a\n :class:`~transformers.PreTrainedModel` subclass.\n - **model_wrapped** -- Always points to the most external model in case one or more other modules wrap the\n original model. This is the model that should be used for the forward pass. For example, under ``DeepSpeed``,\n the inner model is wrapped in ``DeepSpeed`` and then again in ``torch.nn.DistributedDataParallel``. If the\n inner model hasn't been wrapped, then ``self.model_wrapped`` is the same as ``self.model``.\n - **is_model_parallel** -- Whether or not a model has been switched to a model parallel mode (different from\n data parallelism, this means some of the model layers are split on different GPUs).\n - **place_model_on_device** -- Whether or not to automatically place the model on the device - it will be set\n to :obj:`False` if model parallel or deepspeed is used, or if the default\n ``TrainingArguments.place_model_on_device`` is overridden to return :obj:`False` .\n - **is_in_train** -- Whether or not a model is currently running ``train`` (e.g. when ``evaluate`` is called\n while in ``train``)\n\n \"\"\"\n\n from .trainer_pt_utils import _get_learning_rate\n\n def __init__(\n self,\n model: Union[PreTrainedModel, torch.nn.Module] = None,\n args: TrainingArguments = None,\n data_collator: Optional[DataCollator] = None,\n train_dataset: Optional[Dataset] = None,\n eval_dataset: Optional[Dataset] = None,\n tokenizer: Optional[\"PreTrainedTokenizerBase\"] = None,\n model_init: Callable[[], PreTrainedModel] = None,\n compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None,\n callbacks: Optional[List[TrainerCallback]] = None,\n optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),\n ):\n if args is None:\n output_dir = \"tmp_trainer\"\n logger.info(f\"No `TrainingArguments` passed, using `output_dir={output_dir}`.\")\n args = TrainingArguments(output_dir=output_dir)\n self.args = args\n # Seed must be set before instantiating the model when using model\n set_seed(self.args.seed)\n self.hp_name = None\n self.deepspeed = None\n self.is_in_train = False\n\n # memory metrics - must set up as early as possible\n self._memory_tracker = TrainerMemoryTracker(self.args.skip_memory_metrics)\n self._memory_tracker.start()\n\n # force device and distributed setup init explicitly\n args._setup_devices\n\n if model is None:\n if model_init is not None:\n self.model_init = model_init\n model = self.call_model_init()\n else:\n raise RuntimeError(\"`Trainer` requires either a `model` or `model_init` argument\")\n else:\n if model_init is not None:\n warnings.warn(\n \"`Trainer` requires either a `model` or `model_init` argument, but not both. \"\n \"`model_init` will overwrite your model when calling the `train` method. This will become a fatal error in the next release.\",\n FutureWarning,\n )\n self.model_init = model_init\n\n if hasattr(model, \"is_parallelizable\") and model.is_parallelizable and model.model_parallel:\n self.is_model_parallel = True\n else:\n self.is_model_parallel = False\n\n # Setup Sharded DDP training\n self.sharded_ddp = None\n if len(args.sharded_ddp) > 0:\n if args.deepspeed:\n raise ValueError(\n \"Using --sharded_ddp xxx together with --deepspeed is not possible, deactivate one of those flags.\"\n )\n\n if args.local_rank == -1:\n raise ValueError(\"Using sharded DDP only works in distributed training.\")\n elif not is_fairscale_available():\n raise ImportError(\"Sharded DDP training requires fairscale: `pip install fairscale`.\")\n elif ShardedDDPOption.SIMPLE not in args.sharded_ddp and FullyShardedDDP is None:\n raise ImportError(\n \"Sharded DDP in a mode other than simple training requires fairscale version >= 0.3, found \"\n f\"{fairscale.__version__}. Upgrade your fairscale library: `pip install --upgrade fairscale`.\"\n )\n elif ShardedDDPOption.SIMPLE in args.sharded_ddp:\n self.sharded_ddp = ShardedDDPOption.SIMPLE\n elif ShardedDDPOption.ZERO_DP_2 in args.sharded_ddp:\n self.sharded_ddp = ShardedDDPOption.ZERO_DP_2\n elif ShardedDDPOption.ZERO_DP_3 in args.sharded_ddp:\n self.sharded_ddp = ShardedDDPOption.ZERO_DP_3\n\n # one place to sort out whether to place the model on device or not\n self.place_model_on_device = args.place_model_on_device\n if (\n self.is_model_parallel\n or (args.deepspeed and args.do_train)\n or (args.fp16_full_eval and not args.do_train)\n or (self.sharded_ddp in [ShardedDDPOption.ZERO_DP_2, ShardedDDPOption.ZERO_DP_3])\n ):\n self.place_model_on_device = False\n\n default_collator = default_data_collator if tokenizer is None else DataCollatorWithPadding(tokenizer)\n self.data_collator = data_collator if data_collator is not None else default_collator\n self.train_dataset = train_dataset\n self.eval_dataset = eval_dataset\n self.tokenizer = tokenizer\n\n # postpone switching model to cuda when:\n # 1. MP - since we are trying to fit a much bigger than 1 gpu model\n # 2. fp16-enabled DeepSpeed loads the model in half the size and it doesn't need .to() anyway,\n # and we only use deepspeed for training at the moment\n if self.place_model_on_device:\n model = model.to(args.device)\n\n # Force n_gpu to 1 to avoid DataParallel as MP will manage the GPUs\n if self.is_model_parallel:\n self.args._n_gpu = 1\n\n # later use `self.model is self.model_wrapped` to check if it's wrapped or not\n self.model_wrapped = model\n self.model = model\n\n self.compute_metrics = compute_metrics\n self.optimizer, self.lr_scheduler = optimizers\n if model_init is not None and (self.optimizer is not None or self.lr_scheduler is not None):\n raise RuntimeError(\n \"Passing a `model_init` is incompatible with providing the `optimizers` argument.\"\n \"You should subclass `Trainer` and override the `create_optimizer_and_scheduler` method.\"\n )\n default_callbacks = DEFAULT_CALLBACKS + get_reporting_integration_callbacks(self.args.report_to)\n callbacks = default_callbacks if callbacks is None else default_callbacks + callbacks\n self.callback_handler = CallbackHandler(\n callbacks, self.model, self.tokenizer, self.optimizer, self.lr_scheduler\n )\n self.add_callback(PrinterCallback if self.args.disable_tqdm else DEFAULT_PROGRESS_CALLBACK)\n\n # Will be set to True by `self._setup_loggers()` on first call to `self.log()`.\n self._loggers_initialized = False\n\n # Create output directory if needed\n if self.is_world_process_zero():\n os.makedirs(self.args.output_dir, exist_ok=True)\n if is_torch_tpu_available() and isinstance(self.model, PreTrainedModel):\n # Set an xla_device flag on the model's config.\n # We'll find a more elegant and not need to do this in the future.\n self.model.config.xla_device = True\n if not callable(self.data_collator) and callable(getattr(self.data_collator, \"collate_batch\", None)):\n raise ValueError(\"The `data_collator` should be a simple callable (function, class with `__call__`).\")\n\n if args.max_steps > 0:\n logger.info(\"max_steps is given, it will override any value given in num_train_epochs\")\n\n # Enforce rules on using datasets with no __len__\n if train_dataset is not None and not isinstance(train_dataset, collections.abc.Sized) and args.max_steps <= 0:\n raise ValueError(\"train_dataset does not implement __len__, max_steps has to be specified\")\n if eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized):\n raise ValueError(\"eval_dataset must implement __len__\")\n\n self._signature_columns = None\n if is_datasets_available():\n if isinstance(train_dataset, datasets.Dataset):\n self._remove_unused_columns(self.train_dataset, description=\"training\")\n if isinstance(eval_dataset, datasets.Dataset):\n self._remove_unused_columns(self.eval_dataset, description=\"evaluation\")\n\n # Mixed precision setup\n self.use_apex = False\n self.use_amp = False\n self.fp16_backend = None\n\n if args.fp16:\n if args.fp16_backend == \"auto\":\n self.fp16_backend = \"amp\" if _is_native_amp_available else \"apex\"\n else:\n self.fp16_backend = args.fp16_backend\n logger.info(f\"Using {self.fp16_backend} fp16 backend\")\n\n if args.fp16 and not args.deepspeed: # deepspeed manages its own fp16\n if self.fp16_backend == \"amp\":\n self.use_amp = True\n self.scaler = ShardedGradScaler() if self.sharded_ddp is not None else torch.cuda.amp.GradScaler()\n else:\n if not is_apex_available():\n raise ImportError(\n \"Using FP16 with APEX but APEX is not installed, please refer to https://www.github.com/nvidia/apex.\"\n )\n self.use_apex = True\n\n # Label smoothing\n if self.args.label_smoothing_factor != 0:\n self.label_smoother = LabelSmoother(epsilon=self.args.label_smoothing_factor)\n else:\n self.label_smoother = None\n\n self.state = TrainerState()\n self.control = TrainerControl()\n # Internal variable for total_flos used to count as tensors (for distributed + TPU), will be sent in the\n # state at each call to self.log.\n self._total_flos = None\n self.hp_search_backend = None\n self.use_tune_checkpoints = False\n default_label_names = (\n [\"start_positions\", \"end_positions\"]\n if type(self.model) in MODEL_FOR_QUESTION_ANSWERING_MAPPING.values()\n else [\"labels\"]\n )\n self.label_names = default_label_names if self.args.label_names is None else self.args.label_names\n self.control = self.callback_handler.on_init_end(self.args, self.state, self.control)\n\n # very last\n self._memory_tracker.stop_and_update_metrics()\n\n def add_callback(self, callback):\n \"\"\"\n Add a callback to the current list of :class:`~transformer.TrainerCallback`.\n\n Args:\n callback (:obj:`type` or :class:`~transformer.TrainerCallback`):\n A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`.\n In the first case, will instantiate a member of that class.\n \"\"\"\n self.callback_handler.add_callback(callback)\n\n def pop_callback(self, callback):\n \"\"\"\n Remove a callback from the current list of :class:`~transformer.TrainerCallback` and returns it.\n\n If the callback is not found, returns :obj:`None` (and no error is raised).\n\n Args:\n callback (:obj:`type` or :class:`~transformer.TrainerCallback`):\n A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`.\n In the first case, will pop the first member of that class found in the list of callbacks.\n\n Returns:\n :class:`~transformer.TrainerCallback`: The callback removed, if found.\n \"\"\"\n return self.callback_handler.pop_callback(callback)\n\n def remove_callback(self, callback):\n \"\"\"\n Remove a callback from the current list of :class:`~transformer.TrainerCallback`.\n\n Args:\n callback (:obj:`type` or :class:`~transformer.TrainerCallback`):\n A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`.\n In the first case, will remove the first member of that class found in the list of callbacks.\n \"\"\"\n self.callback_handler.remove_callback(callback)\n\n def _remove_unused_columns(self, dataset: \"datasets.Dataset\", description: Optional[str] = None):\n if not self.args.remove_unused_columns:\n return\n if self._signature_columns is None:\n # Inspect model forward signature to keep only the arguments it accepts.\n signature = inspect.signature(self.model.forward)\n self._signature_columns = list(signature.parameters.keys())\n # Labels may be named label or label_ids, the default data collator handles that.\n self._signature_columns += [\"label\", \"label_ids\"]\n columns = [k for k in self._signature_columns if k in dataset.column_names]\n ignored_columns = list(set(dataset.column_names) - set(self._signature_columns))\n if len(ignored_columns) > 0:\n dset_description = \"\" if description is None else f\"in the {description} set \"\n logger.info(\n f\"The following columns {dset_description} don't have a corresponding argument in \"\n f\"`{self.model.__class__.__name__}.forward` and have been ignored: {', '.join(ignored_columns)}.\"\n )\n\n dataset.set_format(type=dataset.format[\"type\"], columns=columns, format_kwargs=dataset.format[\"format_kwargs\"])\n\n def _get_train_sampler(self) -> Optional[torch.utils.data.sampler.Sampler]:\n if isinstance(self.train_dataset, torch.utils.data.IterableDataset) or not isinstance(\n self.train_dataset, collections.abc.Sized\n ):\n return None\n\n # Gather the number of processes and this process index.\n if self.args.parallel_mode == ParallelMode.TPU:\n num_processes = xm.xrt_world_size()\n process_index = xm.get_ordinal()\n elif (\n self.args.parallel_mode == ParallelMode.DISTRIBUTED\n or self.args.parallel_mode == ParallelMode.SAGEMAKER_DISTRIBUTED\n ):\n num_processes = dist.get_world_size()\n process_index = dist.get_rank()\n else:\n num_processes = 1\n process_index = 0\n\n # Build the sampler.\n if self.args.group_by_length:\n if num_processes <= 1:\n return LengthGroupedSampler(self.train_dataset, self.args.train_batch_size)\n else:\n return DistributedLengthGroupedSampler(\n self.train_dataset, self.args.train_batch_size, num_replicas=num_processes, rank=process_index\n )\n\n else:\n if num_processes <= 1:\n return RandomSampler(self.train_dataset)\n else:\n return DistributedSampler(self.train_dataset, num_replicas=num_processes, rank=process_index)\n\n def get_train_dataloader(self) -> DataLoader:\n \"\"\"\n Returns the training :class:`~torch.utils.data.DataLoader`.\n\n Will use no sampler if :obj:`self.train_dataset` does not implement :obj:`__len__`, a random sampler (adapted\n to distributed training if necessary) otherwise.\n\n Subclass and override this method if you want to inject some custom behavior.\n \"\"\"\n if self.train_dataset is None:\n raise ValueError(\"Trainer: training requires a train_dataset.\")\n train_sampler = self._get_train_sampler()\n\n return DataLoader(\n self.train_dataset,\n batch_size=self.args.train_batch_size,\n sampler=train_sampler,\n collate_fn=self.data_collator,\n drop_last=self.args.dataloader_drop_last,\n num_workers=self.args.dataloader_num_workers,\n pin_memory=self.args.dataloader_pin_memory,\n )\n\n def _get_eval_sampler(self, eval_dataset: Dataset) -> Optional[torch.utils.data.sampler.Sampler]:\n if is_torch_tpu_available():\n return SequentialDistributedSampler(eval_dataset, num_replicas=xm.xrt_world_size(), rank=xm.get_ordinal())\n elif self.args.local_rank != -1:\n return SequentialDistributedSampler(eval_dataset)\n else:\n return SequentialSampler(eval_dataset)\n\n def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader:\n \"\"\"\n Returns the evaluation :class:`~torch.utils.data.DataLoader`.\n\n Subclass and override this method if you want to inject some custom behavior.\n\n Args:\n eval_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`):\n If provided, will override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`, columns not\n accepted by the ``model.forward()`` method are automatically removed. It must implement :obj:`__len__`.\n \"\"\"\n if eval_dataset is None and self.eval_dataset is None:\n raise ValueError(\"Trainer: evaluation requires an eval_dataset.\")\n elif eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized):\n raise ValueError(\"eval_dataset must implement __len__\")\n elif is_datasets_available() and isinstance(eval_dataset, datasets.Dataset):\n self._remove_unused_columns(eval_dataset, description=\"evaluation\")\n eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset\n eval_sampler = self._get_eval_sampler(eval_dataset)\n\n return DataLoader(\n eval_dataset,\n sampler=eval_sampler,\n batch_size=self.args.eval_batch_size,\n collate_fn=self.data_collator,\n drop_last=self.args.dataloader_drop_last,\n num_workers=self.args.dataloader_num_workers,\n pin_memory=self.args.dataloader_pin_memory,\n )\n\n def get_test_dataloader(self, test_dataset: Dataset) -> DataLoader:\n \"\"\"\n Returns the test :class:`~torch.utils.data.DataLoader`.\n\n Subclass and override this method if you want to inject some custom behavior.\n\n Args:\n test_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`):\n The test dataset to use. If it is an :obj:`datasets.Dataset`, columns not accepted by the\n ``model.forward()`` method are automatically removed. It must implement :obj:`__len__`.\n \"\"\"\n if not isinstance(test_dataset, collections.abc.Sized):\n raise ValueError(\"test_dataset must implement __len__\")\n elif is_datasets_available() and isinstance(test_dataset, datasets.Dataset):\n self._remove_unused_columns(test_dataset, description=\"test\")\n test_sampler = self._get_eval_sampler(test_dataset)\n\n # We use the same batch_size as for eval.\n return DataLoader(\n test_dataset,\n sampler=test_sampler,\n batch_size=self.args.eval_batch_size,\n collate_fn=self.data_collator,\n drop_last=self.args.dataloader_drop_last,\n pin_memory=self.args.dataloader_pin_memory,\n )\n\n def create_optimizer_and_scheduler(self, num_training_steps: int):\n \"\"\"\n Setup the optimizer and the learning rate scheduler.\n\n We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the\n Trainer's init through :obj:`optimizers`, or subclass and override this method in a subclass.\n \"\"\"\n if self.optimizer is None:\n no_decay = [\"bias\", \"LayerNorm.weight\"]\n optimizer_grouped_parameters = [\n {\n \"params\": [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay)],\n \"weight_decay\": self.args.weight_decay,\n },\n {\n \"params\": [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay)],\n \"weight_decay\": 0.0,\n },\n ]\n optimizer_cls = Adafactor if self.args.adafactor else AdamW\n if self.args.adafactor:\n optimizer_cls = Adafactor\n optimizer_kwargs = {\"scale_parameter\": False, \"relative_step\": False}\n else:\n optimizer_cls = AdamW\n optimizer_kwargs = {\n \"betas\": (self.args.adam_beta1, self.args.adam_beta2),\n \"eps\": self.args.adam_epsilon,\n }\n optimizer_kwargs[\"lr\"] = self.args.learning_rate\n if self.sharded_ddp == ShardedDDPOption.SIMPLE:\n self.optimizer = OSS(\n params=optimizer_grouped_parameters,\n optim=optimizer_cls,\n **optimizer_kwargs,\n )\n else:\n self.optimizer = optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs)\n\n if self.lr_scheduler is None:\n warmup_steps = (\n self.args.warmup_steps\n if self.args.warmup_steps > 0\n else math.ceil(num_training_steps * self.args.warmup_ratio)\n )\n\n self.lr_scheduler = get_scheduler(\n self.args.lr_scheduler_type,\n self.optimizer,\n num_warmup_steps=warmup_steps,\n num_training_steps=num_training_steps,\n )\n\n def num_examples(self, dataloader: DataLoader) -> int:\n \"\"\"\n Helper to get number of samples in a :class:`~torch.utils.data.DataLoader` by accessing its dataset.\n\n Will raise an exception if the underlying dataset dese not implement method :obj:`__len__`\n \"\"\"\n return len(dataloader.dataset)\n\n def _hp_search_setup(self, trial: Union[\"optuna.Trial\", Dict[str, Any]]):\n \"\"\" HP search setup code \"\"\"\n self._trial = trial\n\n if self.hp_search_backend is None or trial is None:\n return\n\n params = self.hp_space(trial) if self.hp_search_backend == HPSearchBackend.OPTUNA else trial\n for key, value in params.items():\n if not hasattr(self.args, key):\n raise AttributeError(\n f\"Trying to set {key} in the hyperparameter search but there is no corresponding field in `TrainingArguments`.\"\n )\n old_attr = getattr(self.args, key, None)\n # Casting value to the proper type\n if old_attr is not None:\n value = type(old_attr)(value)\n setattr(self.args, key, value)\n if self.hp_search_backend == HPSearchBackend.OPTUNA:\n logger.info(\"Trial:\", trial.params)\n\n def _report_to_hp_search(\n self, trial: Union[\"optuna.Trial\", Dict[str, Any]], epoch: int, metrics: Dict[str, float]\n ):\n if self.hp_search_backend is None or trial is None:\n return\n self.objective = self.compute_objective(metrics.copy())\n if self.hp_search_backend == HPSearchBackend.OPTUNA:\n import optuna\n\n trial.report(self.objective, epoch)\n if trial.should_prune():\n raise optuna.TrialPruned()\n elif self.hp_search_backend == HPSearchBackend.RAY:\n from ray import tune\n\n if self.control.should_save:\n self._tune_save_checkpoint()\n tune.report(objective=self.objective, **metrics)\n\n def _tune_save_checkpoint(self):\n from ray import tune\n\n if not self.use_tune_checkpoints:\n return\n with tune.checkpoint_dir(step=self.state.global_step) as checkpoint_dir:\n output_dir = os.path.join(checkpoint_dir, f\"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}\")\n self.save_model(output_dir)\n if self.is_world_process_zero():\n self.state.save_to_json(os.path.join(output_dir, \"trainer_state.json\"))\n torch.save(self.optimizer.state_dict(), os.path.join(output_dir, \"optimizer.pt\"))\n torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, \"scheduler.pt\"))\n\n def call_model_init(self, trial=None):\n model_init_argcount = len(inspect.signature(self.model_init).parameters)\n if model_init_argcount == 0:\n model = self.model_init()\n elif model_init_argcount == 1:\n model = self.model_init(trial)\n else:\n raise RuntimeError(\"model_init should have 0 or 1 argument.\")\n\n if model is None:\n raise RuntimeError(\"model_init should not return None.\")\n\n return model\n\n def _wrap_model(self, model, training=True):\n # already initialized its own DDP and AMP\n if self.deepspeed:\n return self.deepspeed\n\n # Mixed precision training with apex (torch < 1.6)\n if self.use_apex and training:\n model, self.optimizer = amp.initialize(model, self.optimizer, opt_level=self.args.fp16_opt_level)\n\n # Multi-gpu training (should be after apex fp16 initialization)\n if self.args.n_gpu > 1:\n model = torch.nn.DataParallel(model)\n\n # Note: in torch.distributed mode, there's no point in wrapping the model\n # inside a DistributedDataParallel as we'll be under `no_grad` anyways.\n if not training:\n return model\n\n # Distributed training (should be after apex fp16 initialization)\n if self.sharded_ddp is not None:\n # Sharded DDP!\n if self.sharded_ddp == ShardedDDPOption.SIMPLE:\n model = ShardedDDP(model, self.optimizer)\n else:\n mixed_precision = self.args.fp16\n cpu_offload = ShardedDDPOption.OFFLOAD in self.args.sharded_ddp\n zero_3 = self.sharded_ddp == ShardedDDPOption.ZERO_DP_3\n # XXX: Breaking the self.model convention but I see no way around it for now.\n self.model = model = FullyShardedDDP(\n model, mixed_precision=mixed_precision, reshard_after_forward=zero_3, cpu_offload=cpu_offload\n ).to(self.args.device)\n\n elif is_sagemaker_distributed_available():\n model = DDP(model, device_ids=[dist.get_local_rank()], broadcast_buffers=False)\n elif self.args.local_rank != -1:\n if self.args.ddp_find_unused_parameters is not None:\n find_unused_parameters = self.args.ddp_find_unused_parameters\n elif isinstance(model, PreTrainedModel):\n # find_unused_parameters breaks checkpointing as per\n # https://github.com/huggingface/transformers/pull/4659#issuecomment-643356021\n find_unused_parameters = not getattr(model.config, \"gradient_checkpointing\", False)\n else:\n find_unused_parameters = True\n model = torch.nn.parallel.DistributedDataParallel(\n model,\n device_ids=[self.args.local_rank],\n output_device=self.args.local_rank,\n find_unused_parameters=find_unused_parameters,\n )\n\n return model\n\n def train(\n self,\n resume_from_checkpoint: Optional[Union[str, bool]] = None,\n trial: Union[\"optuna.Trial\", Dict[str, Any]] = None,\n **kwargs,\n ):\n \"\"\"\n Main training entry point.\n\n Args:\n resume_from_checkpoint (:obj:`str` or :obj:`bool`, `optional`):\n If a :obj:`str`, local path to a saved checkpoint as saved by a previous instance of\n :class:`~transformers.Trainer`. If a :obj:`bool` and equals `True`, load the last checkpoint in\n `args.output_dir` as saved by a previous instance of :class:`~transformers.Trainer`. If present,\n training will resume from the model/optimizer/scheduler states loaded here.\n trial (:obj:`optuna.Trial` or :obj:`Dict[str, Any]`, `optional`):\n The trial run or the hyperparameter dictionary for hyperparameter search.\n kwargs:\n Additional keyword arguments used to hide deprecated arguments\n \"\"\"\n\n # memory metrics - must set up as early as possible\n self._memory_tracker.start()\n\n self.is_in_train = True\n\n if \"model_path\" in kwargs:\n resume_from_checkpoint = kwargs.pop(\"model_path\")\n warnings.warn(\n \"`model_path` is deprecated and will be removed in a future version. Use `resume_from_checkpoint` \"\n \"instead.\",\n FutureWarning,\n )\n if len(kwargs) > 0:\n raise TypeError(f\"train() received got unexpected keyword arguments: {', '.join(list(kwargs.keys()))}.\")\n # This might change the seed so needs to run first.\n self._hp_search_setup(trial)\n\n # Model re-init\n model_reloaded = False\n if self.model_init is not None:\n # Seed must be set before instantiating the model when using model_init.\n set_seed(self.args.seed)\n self.model = self.call_model_init(trial)\n model_reloaded = True\n # Reinitializes optimizer and scheduler\n self.optimizer, self.lr_scheduler = None, None\n\n # Load potential model checkpoint\n if isinstance(resume_from_checkpoint, bool) and resume_from_checkpoint:\n resume_from_checkpoint = get_last_checkpoint(self.args.output_dir)\n if resume_from_checkpoint is None:\n raise ValueError(f\"No valid checkpoint found in output directory ({self.args.output_dir})\")\n\n if resume_from_checkpoint is not None and os.path.isfile(os.path.join(resume_from_checkpoint, WEIGHTS_NAME)):\n logger.info(f\"Loading model from {resume_from_checkpoint}).\")\n if isinstance(self.model, PreTrainedModel):\n self.model = self.model.from_pretrained(resume_from_checkpoint)\n model_reloaded = True\n else:\n state_dict = torch.load(os.path.join(resume_from_checkpoint, WEIGHTS_NAME))\n self.model.load_state_dict(state_dict)\n\n # If model was re-initialized, put it on the right device and update self.model_wrapped\n if model_reloaded:\n if self.place_model_on_device:\n self.model = self.model.to(self.args.device)\n self.model_wrapped = self.model\n\n # Keeping track whether we can can len() on the dataset or not\n train_dataset_is_sized = isinstance(self.train_dataset, collections.abc.Sized)\n\n # Data loader and number of training steps\n train_dataloader = self.get_train_dataloader()\n\n # Setting up training control variables:\n # number of training epochs: num_train_epochs\n # number of training steps per epoch: num_update_steps_per_epoch\n # total number of training steps to execute: max_steps\n if train_dataset_is_sized:\n num_update_steps_per_epoch = len(train_dataloader) // self.args.gradient_accumulation_steps\n num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1)\n if self.args.max_steps > 0:\n max_steps = self.args.max_steps\n num_train_epochs = self.args.max_steps // num_update_steps_per_epoch + int(\n self.args.max_steps % num_update_steps_per_epoch > 0\n )\n else:\n max_steps = math.ceil(self.args.num_train_epochs * num_update_steps_per_epoch)\n num_train_epochs = math.ceil(self.args.num_train_epochs)\n else:\n # see __init__. max_steps is set when the dataset has no __len__\n max_steps = self.args.max_steps\n num_train_epochs = 1\n num_update_steps_per_epoch = max_steps\n\n delay_optimizer_creation = self.sharded_ddp is not None and self.sharded_ddp != ShardedDDPOption.SIMPLE\n if self.args.deepspeed:\n model, optimizer, lr_scheduler = init_deepspeed(self, num_training_steps=max_steps)\n self.model = model.module\n self.model_wrapped = model # will get further wrapped in DDP\n self.deepspeed = model # DeepSpeedEngine object\n self.optimizer = optimizer\n self.lr_scheduler = lr_scheduler\n elif not delay_optimizer_creation:\n self.create_optimizer_and_scheduler(num_training_steps=max_steps)\n\n self.state = TrainerState()\n self.state.is_hyper_param_search = trial is not None\n\n # Check if saved optimizer or scheduler states exist\n self._load_optimizer_and_scheduler(resume_from_checkpoint)\n\n model = self._wrap_model(self.model_wrapped)\n\n # for the rest of this function `model` is the outside model, whether it was wrapped or not\n if model is not self.model:\n self.model_wrapped = model\n\n if delay_optimizer_creation:\n self.create_optimizer_and_scheduler(num_training_steps=max_steps)\n\n # important: at this point:\n # self.model is the Transformers Model\n # self.model_wrapped is DDP(Transformers Model), Deepspeed(Transformers Model), etc.\n\n # Train!\n if is_torch_tpu_available():\n world_size = xm.xrt_world_size()\n elif self.args.local_rank != -1:\n world_size = dist.get_world_size()\n else:\n world_size = 1\n\n total_train_batch_size = self.args.train_batch_size * self.args.gradient_accumulation_steps * world_size\n num_examples = (\n self.num_examples(train_dataloader)\n if train_dataset_is_sized\n else total_train_batch_size * self.args.max_steps\n )\n\n logger.info(\"***** Running training *****\")\n logger.info(f\" Num examples = {num_examples}\")\n logger.info(f\" Num Epochs = {num_train_epochs}\")\n logger.info(f\" Instantaneous batch size per device = {self.args.per_device_train_batch_size}\")\n logger.info(f\" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}\")\n logger.info(f\" Gradient Accumulation steps = {self.args.gradient_accumulation_steps}\")\n logger.info(f\" Total optimization steps = {max_steps}\")\n\n self.state.epoch = 0\n start_time = time.time()\n epochs_trained = 0\n steps_trained_in_current_epoch = 0\n\n # Check if continuing training from a checkpoint\n if resume_from_checkpoint is not None and os.path.isfile(\n os.path.join(resume_from_checkpoint, \"trainer_state.json\")\n ):\n self.state = TrainerState.load_from_json(os.path.join(resume_from_checkpoint, \"trainer_state.json\"))\n epochs_trained = self.state.global_step // num_update_steps_per_epoch\n if not self.args.ignore_data_skip:\n steps_trained_in_current_epoch = self.state.global_step % (num_update_steps_per_epoch)\n steps_trained_in_current_epoch *= self.args.gradient_accumulation_steps\n else:\n steps_trained_in_current_epoch = 0\n\n logger.info(\" Continuing training from checkpoint, will skip to saved global_step\")\n logger.info(f\" Continuing training from epoch {epochs_trained}\")\n logger.info(f\" Continuing training from global step {self.state.global_step}\")\n if not self.args.ignore_data_skip:\n logger.info(\n f\" Will skip the first {epochs_trained} epochs then the first {steps_trained_in_current_epoch} \"\n \"batches in the first epoch.\"\n )\n\n # Update the references\n self.callback_handler.model = self.model\n self.callback_handler.optimizer = self.optimizer\n self.callback_handler.lr_scheduler = self.lr_scheduler\n self.callback_handler.train_dataloader = train_dataloader\n self.state.trial_name = self.hp_name(trial) if self.hp_name is not None else None\n self.state.trial_params = hp_params(trial) if trial is not None else None\n # This should be the same if the state has been saved but in case the training arguments changed, it's safer\n # to set this after the load.\n self.state.max_steps = max_steps\n self.state.num_train_epochs = num_train_epochs\n self.state.is_local_process_zero = self.is_local_process_zero()\n self.state.is_world_process_zero = self.is_world_process_zero()\n\n # tr_loss is a tensor to avoid synchronization of TPUs through .item()\n tr_loss = torch.tensor(0.0).to(self.args.device)\n # _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses\n self._total_loss_scalar = 0.0\n self._globalstep_last_logged = self.state.global_step\n self._total_flos = self.state.total_flos\n model.zero_grad()\n\n self.control = self.callback_handler.on_train_begin(self.args, self.state, self.control)\n\n # Skip the first epochs_trained epochs to get the random state of the dataloader at the right point.\n if not self.args.ignore_data_skip:\n for epoch in range(epochs_trained):\n # We just need to begin an iteration to create the randomization of the sampler.\n for _ in train_dataloader:\n break\n\n for epoch in range(epochs_trained, num_train_epochs):\n if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler):\n train_dataloader.sampler.set_epoch(epoch)\n\n if is_torch_tpu_available():\n parallel_loader = pl.ParallelLoader(train_dataloader, [self.args.device]).per_device_loader(\n self.args.device\n )\n epoch_iterator = parallel_loader\n else:\n epoch_iterator = train_dataloader\n\n # Reset the past mems state at the beginning of each epoch if necessary.\n if self.args.past_index >= 0:\n self._past = None\n\n steps_in_epoch = (\n len(epoch_iterator)\n if train_dataset_is_sized\n else self.args.max_steps * self.args.gradient_accumulation_steps\n )\n self.control = self.callback_handler.on_epoch_begin(self.args, self.state, self.control)\n\n for step, inputs in enumerate(epoch_iterator):\n\n # Skip past any already trained steps if resuming training\n if steps_trained_in_current_epoch > 0:\n steps_trained_in_current_epoch -= 1\n continue\n\n if (step + 1) % self.args.gradient_accumulation_steps == 0:\n self.control = self.callback_handler.on_step_begin(self.args, self.state, self.control)\n\n if (\n ((step + 1) % self.args.gradient_accumulation_steps != 0)\n and self.args.local_rank != -1\n and not self.args.deepspeed\n ):\n # Avoid unnecessary DDP synchronization since there will be no backward pass on this example.\n with model.no_sync():\n tr_loss += self.training_step(model, inputs)\n else:\n tr_loss += self.training_step(model, inputs)\n self._total_flos += float(self.floating_point_ops(inputs))\n\n # Optimizer step for deepspeed must be called on every step regardless of the value of gradient_accumulation_steps\n if self.deepspeed:\n self.deepspeed.step()\n\n if (step + 1) % self.args.gradient_accumulation_steps == 0 or (\n # last step in epoch but step is always smaller than gradient_accumulation_steps\n steps_in_epoch <= self.args.gradient_accumulation_steps\n and (step + 1) == steps_in_epoch\n ):\n # Gradient clipping\n if self.args.max_grad_norm is not None and self.args.max_grad_norm > 0 and not self.deepspeed:\n # deepspeed does its own clipping\n\n if self.use_amp:\n # AMP: gradients need unscaling\n self.scaler.unscale_(self.optimizer)\n\n if hasattr(self.optimizer, \"clip_grad_norm\"):\n # Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping\n self.optimizer.clip_grad_norm(self.args.max_grad_norm)\n elif hasattr(model, \"clip_grad_norm_\"):\n # Some models (like FullyShardedDDP) have a specific way to do gradient clipping\n model.clip_grad_norm_(self.args.max_grad_norm)\n else:\n # Revert to normal clipping otherwise, handling Apex or full precision\n torch.nn.utils.clip_grad_norm_(\n amp.master_params(self.optimizer) if self.use_apex else model.parameters(),\n self.args.max_grad_norm,\n )\n\n # Optimizer step\n if self.deepspeed:\n pass # called outside the loop\n elif is_torch_tpu_available():\n xm.optimizer_step(self.optimizer)\n elif self.use_amp:\n self.scaler.step(self.optimizer)\n self.scaler.update()\n else:\n self.optimizer.step()\n\n if not self.deepspeed:\n self.lr_scheduler.step()\n\n model.zero_grad()\n self.state.global_step += 1\n self.state.epoch = epoch + (step + 1) / steps_in_epoch\n self.control = self.callback_handler.on_step_end(self.args, self.state, self.control)\n\n self._maybe_log_save_evaluate(tr_loss, model, trial, epoch)\n\n if self.control.should_epoch_stop or self.control.should_training_stop:\n break\n\n self.control = self.callback_handler.on_epoch_end(self.args, self.state, self.control)\n self._maybe_log_save_evaluate(tr_loss, model, trial, epoch)\n\n if self.args.tpu_metrics_debug or self.args.debug:\n if is_torch_tpu_available():\n # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)\n xm.master_print(met.metrics_report())\n else:\n logger.warning(\n \"You enabled PyTorch/XLA debug metrics but you don't have a TPU \"\n \"configured. Check your training configuration if this is unexpected.\"\n )\n if self.control.should_training_stop:\n break\n\n if self.args.past_index and hasattr(self, \"_past\"):\n # Clean the state at the end of training\n delattr(self, \"_past\")\n\n logger.info(\"\\n\\nTraining completed. Do not forget to share your model on huggingface.co/models =)\\n\\n\")\n if self.args.load_best_model_at_end and self.state.best_model_checkpoint is not None:\n logger.info(\n f\"Loading best model from {self.state.best_model_checkpoint} (score: {self.state.best_metric}).\"\n )\n if isinstance(self.model, PreTrainedModel):\n self.model = self.model.from_pretrained(self.state.best_model_checkpoint)\n if self.place_model_on_device:\n self.model = self.model.to(self.args.device)\n else:\n state_dict = torch.load(os.path.join(self.state.best_model_checkpoint, WEIGHTS_NAME))\n self.model.load_state_dict(state_dict)\n\n if self.deepspeed:\n self.deepspeed.load_checkpoint(\n self.state.best_model_checkpoint, load_optimizer_states=False, load_lr_scheduler_states=False\n )\n\n metrics = speed_metrics(\"train\", start_time, self.state.max_steps)\n if self._total_flos is not None:\n self.store_flos()\n metrics[\"total_flos\"] = self.state.total_flos\n self.log(metrics)\n\n self.control = self.callback_handler.on_train_end(self.args, self.state, self.control)\n # add remaining tr_loss\n self._total_loss_scalar += tr_loss.item()\n\n if self.deepspeed:\n # free up any memory that might be useful for eval\n self.deepspeed = None\n self.optimizer = None\n self.lr_scheduler = None\n self.model_wrapped = self.model\n gc.collect() # force memory release\n # to restore normal behavior outside of train replay the place_model_on_device logic w/o deepspeed\n self.place_model_on_device = self.args.place_model_on_device\n if self.is_model_parallel:\n self.place_model_on_device = False\n\n self.is_in_train = False\n\n self._memory_tracker.stop_and_update_metrics(metrics)\n\n return TrainOutput(self.state.global_step, self._total_loss_scalar / self.state.global_step, metrics)\n\n def _maybe_log_save_evaluate(self, tr_loss, model, trial, epoch):\n if self.control.should_log:\n logs: Dict[str, float] = {}\n tr_loss_scalar = tr_loss.item()\n # reset tr_loss to zero\n tr_loss -= tr_loss\n\n logs[\"loss\"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4)\n logs[\"learning_rate\"] = self._get_learning_rate()\n\n self._total_loss_scalar += tr_loss_scalar\n self._globalstep_last_logged = self.state.global_step\n\n self.log(logs)\n\n metrics = None\n if self.control.should_evaluate:\n metrics = self.evaluate()\n self._report_to_hp_search(trial, epoch, metrics)\n\n if self.control.should_save:\n self._save_checkpoint(model, trial, metrics=metrics)\n self.control = self.callback_handler.on_save(self.args, self.state, self.control)\n\n def _save_checkpoint(self, model, trial, metrics=None):\n # In all cases, including ddp/dp/deepspeed, self.model is always a reference to the model we\n # want to save except FullyShardedDDP.\n # assert _model_unwrap(model) is self.model, \"internal model should be a reference to self.model\"\n\n # Save model checkpoint\n checkpoint_folder = f\"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}\"\n\n if self.hp_search_backend is not None and trial is not None:\n if self.hp_search_backend == HPSearchBackend.OPTUNA:\n run_id = trial.number\n else:\n from ray import tune\n\n run_id = tune.get_trial_id()\n run_name = self.hp_name(trial) if self.hp_name is not None else f\"run-{run_id}\"\n run_dir = os.path.join(self.args.output_dir, run_name)\n else:\n run_dir = self.args.output_dir\n self.store_flos()\n\n output_dir = os.path.join(run_dir, checkpoint_folder)\n self.save_model(output_dir)\n if self.deepspeed:\n self.deepspeed.save_checkpoint(output_dir)\n\n # Save optimizer and scheduler\n if self.sharded_ddp == ShardedDDPOption.SIMPLE:\n self.optimizer.consolidate_state_dict()\n\n if is_torch_tpu_available():\n xm.rendezvous(\"saving_optimizer_states\")\n xm.save(self.optimizer.state_dict(), os.path.join(output_dir, \"optimizer.pt\"))\n with warnings.catch_warnings(record=True) as caught_warnings:\n xm.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, \"scheduler.pt\"))\n reissue_pt_warnings(caught_warnings)\n elif self.is_world_process_zero() and not self.deepspeed:\n # deepspeed.save_checkpoint above saves model/optim/sched\n torch.save(self.optimizer.state_dict(), os.path.join(output_dir, \"optimizer.pt\"))\n with warnings.catch_warnings(record=True) as caught_warnings:\n torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, \"scheduler.pt\"))\n reissue_pt_warnings(caught_warnings)\n\n # Determine the new best metric / best model checkpoint\n if metrics is not None and self.args.metric_for_best_model is not None:\n metric_to_check = self.args.metric_for_best_model\n if not metric_to_check.startswith(\"eval_\"):\n metric_to_check = f\"eval_{metric_to_check}\"\n metric_value = metrics[metric_to_check]\n\n operator = np.greater if self.args.greater_is_better else np.less\n if (\n self.state.best_metric is None\n or self.state.best_model_checkpoint is None\n or operator(metric_value, self.state.best_metric)\n ):\n self.state.best_metric = metric_value\n self.state.best_model_checkpoint = output_dir\n\n # Save the Trainer state\n if self.is_world_process_zero():\n self.state.save_to_json(os.path.join(output_dir, \"trainer_state.json\"))\n\n # Maybe delete some older checkpoints.\n if self.is_world_process_zero():\n self._rotate_checkpoints(use_mtime=True, output_dir=run_dir)\n\n def _load_optimizer_and_scheduler(self, checkpoint):\n \"\"\"If optimizer and scheduler states exist, load them.\"\"\"\n if checkpoint is None:\n return\n\n if os.path.isfile(os.path.join(checkpoint, \"optimizer.pt\")) and os.path.isfile(\n os.path.join(checkpoint, \"scheduler.pt\")\n ):\n # Load in optimizer and scheduler states\n if is_torch_tpu_available():\n # On TPU we have to take some extra precautions to properly load the states on the right device.\n optimizer_state = torch.load(os.path.join(checkpoint, \"optimizer.pt\"), map_location=\"cpu\")\n with warnings.catch_warnings(record=True) as caught_warnings:\n lr_scheduler_state = torch.load(os.path.join(checkpoint, \"scheduler.pt\"), map_location=\"cpu\")\n reissue_pt_warnings(caught_warnings)\n\n xm.send_cpu_data_to_device(optimizer_state, self.args.device)\n xm.send_cpu_data_to_device(lr_scheduler_state, self.args.device)\n\n self.optimizer.load_state_dict(optimizer_state)\n self.lr_scheduler.load_state_dict(lr_scheduler_state)\n else:\n self.optimizer.load_state_dict(\n torch.load(os.path.join(checkpoint, \"optimizer.pt\"), map_location=self.args.device)\n )\n with warnings.catch_warnings(record=True) as caught_warnings:\n self.lr_scheduler.load_state_dict(torch.load(os.path.join(checkpoint, \"scheduler.pt\")))\n reissue_pt_warnings(caught_warnings)\n\n if self.deepspeed:\n # Not sure how to check if there is a saved deepspeed checkpoint, but since it just return None if it fails to find a deepspeed checkpoint this is sort of a check-n-load function\n self.deepspeed.load_checkpoint(checkpoint, load_optimizer_states=True, load_lr_scheduler_states=True)\n\n def hyperparameter_search(\n self,\n hp_space: Optional[Callable[[\"optuna.Trial\"], Dict[str, float]]] = None,\n compute_objective: Optional[Callable[[Dict[str, float]], float]] = None,\n n_trials: int = 20,\n direction: str = \"minimize\",\n backend: Optional[Union[\"str\", HPSearchBackend]] = None,\n hp_name: Optional[Callable[[\"optuna.Trial\"], str]] = None,\n **kwargs,\n ) -> BestRun:\n \"\"\"\n Launch an hyperparameter search using ``optuna`` or ``Ray Tune``. The optimized quantity is determined by\n :obj:`compute_objective`, which defaults to a function returning the evaluation loss when no metric is\n provided, the sum of all metrics otherwise.\n\n .. warning::\n\n To use this method, you need to have provided a ``model_init`` when initializing your\n :class:`~transformers.Trainer`: we need to reinitialize the model at each new run. This is incompatible\n with the ``optimizers`` argument, so you need to subclass :class:`~transformers.Trainer` and override the\n method :meth:`~transformers.Trainer.create_optimizer_and_scheduler` for custom optimizer/scheduler.\n\n Args:\n hp_space (:obj:`Callable[[\"optuna.Trial\"], Dict[str, float]]`, `optional`):\n A function that defines the hyperparameter search space. Will default to\n :func:`~transformers.trainer_utils.default_hp_space_optuna` or\n :func:`~transformers.trainer_utils.default_hp_space_ray` depending on your backend.\n compute_objective (:obj:`Callable[[Dict[str, float]], float]`, `optional`):\n A function computing the objective to minimize or maximize from the metrics returned by the\n :obj:`evaluate` method. Will default to :func:`~transformers.trainer_utils.default_compute_objective`.\n n_trials (:obj:`int`, `optional`, defaults to 100):\n The number of trial runs to test.\n direction(:obj:`str`, `optional`, defaults to :obj:`\"minimize\"`):\n Whether to optimize greater or lower objects. Can be :obj:`\"minimize\"` or :obj:`\"maximize\"`, you should\n pick :obj:`\"minimize\"` when optimizing the validation loss, :obj:`\"maximize\"` when optimizing one or\n several metrics.\n backend(:obj:`str` or :class:`~transformers.training_utils.HPSearchBackend`, `optional`):\n The backend to use for hyperparameter search. Will default to optuna or Ray Tune, depending on which\n one is installed. If both are installed, will default to optuna.\n kwargs:\n Additional keyword arguments passed along to :obj:`optuna.create_study` or :obj:`ray.tune.run`. For\n more information see:\n\n - the documentation of `optuna.create_study\n <https://optuna.readthedocs.io/en/stable/reference/alias_generated/optuna.create_study.html#optuna.create_study>`__\n - the documentation of `tune.run\n <https://docs.ray.io/en/latest/tune/api_docs/execution.html#tune-run>`__\n\n Returns:\n :class:`transformers.trainer_utils.BestRun`: All the information about the best run.\n \"\"\"\n if backend is None:\n backend = default_hp_search_backend()\n if backend is None:\n raise RuntimeError(\n \"At least one of optuna or ray should be installed. \"\n \"To install optuna run `pip install optuna`.\"\n \"To install ray run `pip install ray[tune]`.\"\n )\n backend = HPSearchBackend(backend)\n if backend == HPSearchBackend.OPTUNA and not is_optuna_available():\n raise RuntimeError(\"You picked the optuna backend, but it is not installed. Use `pip install optuna`.\")\n if backend == HPSearchBackend.RAY and not is_ray_tune_available():\n raise RuntimeError(\n \"You picked the Ray Tune backend, but it is not installed. Use `pip install 'ray[tune]'`.\"\n )\n self.hp_search_backend = backend\n if self.model_init is None:\n raise RuntimeError(\n \"To use hyperparameter search, you need to pass your model through a model_init function.\"\n )\n\n self.hp_space = default_hp_space[backend] if hp_space is None else hp_space\n self.hp_name = hp_name\n self.compute_objective = default_compute_objective if compute_objective is None else compute_objective\n\n run_hp_search = run_hp_search_optuna if backend == HPSearchBackend.OPTUNA else run_hp_search_ray\n best_run = run_hp_search(self, n_trials, direction, **kwargs)\n\n self.hp_search_backend = None\n return best_run\n\n def log(self, logs: Dict[str, float]) -> None:\n \"\"\"\n Log :obj:`logs` on the various objects watching training.\n\n Subclass and override this method to inject custom behavior.\n\n Args:\n logs (:obj:`Dict[str, float]`):\n The values to log.\n \"\"\"\n if self.state.epoch is not None:\n logs[\"epoch\"] = round(self.state.epoch, 2)\n\n output = {**logs, **{\"step\": self.state.global_step}}\n self.state.log_history.append(output)\n self.control = self.callback_handler.on_log(self.args, self.state, self.control, logs)\n\n def _prepare_inputs(self, inputs: Dict[str, Union[torch.Tensor, Any]]) -> Dict[str, Union[torch.Tensor, Any]]:\n \"\"\"\n Prepare :obj:`inputs` before feeding them to the model, converting them to tensors if they are not already and\n handling potential state.\n \"\"\"\n for k, v in inputs.items():\n if isinstance(v, torch.Tensor):\n inputs[k] = v.to(self.args.device)\n\n if self.args.past_index >= 0 and self._past is not None:\n inputs[\"mems\"] = self._past\n\n return inputs\n\n def training_step(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]) -> torch.Tensor:\n \"\"\"\n Perform a training step on a batch of inputs.\n\n Subclass and override to inject custom behavior.\n\n Args:\n model (:obj:`nn.Module`):\n The model to train.\n inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):\n The inputs and targets of the model.\n\n The dictionary will be unpacked before being fed to the model. Most models expect the targets under the\n argument :obj:`labels`. Check your model's documentation for all accepted arguments.\n\n Return:\n :obj:`torch.Tensor`: The tensor with training loss on this batch.\n \"\"\"\n model.train()\n inputs = self._prepare_inputs(inputs)\n\n if self.use_amp:\n with autocast():\n loss = self.compute_loss(model, inputs)\n else:\n loss = self.compute_loss(model, inputs)\n\n if self.args.n_gpu > 1:\n loss = loss.mean() # mean() to average on multi-gpu parallel training\n\n if self.args.gradient_accumulation_steps > 1 and not self.deepspeed:\n # deepspeed handles loss scaling by gradient_accumulation_steps in its `backward`\n loss = loss / self.args.gradient_accumulation_steps\n\n if self.use_amp:\n self.scaler.scale(loss).backward()\n elif self.use_apex:\n with amp.scale_loss(loss, self.optimizer) as scaled_loss:\n scaled_loss.backward()\n elif self.deepspeed:\n # loss gets scaled under gradient_accumulation_steps in deepspeed\n loss = self.deepspeed.backward(loss)\n else:\n loss.backward()\n\n return loss.detach()\n\n def compute_loss(self, model, inputs, return_outputs=False):\n \"\"\"\n How the loss is computed by Trainer. By default, all models return the loss in the first element.\n\n Subclass and override for custom behavior.\n \"\"\"\n if self.label_smoother is not None and \"labels\" in inputs:\n labels = inputs.pop(\"labels\")\n else:\n labels = None\n outputs = model(**inputs)\n # Save past state if it exists\n # TODO: this needs to be fixed and made cleaner later.\n if self.args.past_index >= 0:\n self._past = outputs[self.args.past_index]\n\n if labels is not None:\n loss = self.label_smoother(outputs, labels)\n else:\n # We don't use .loss here since the model may return tuples instead of ModelOutput.\n loss = outputs[\"loss\"] if isinstance(outputs, dict) else outputs[0]\n\n return (loss, outputs) if return_outputs else loss\n\n def is_local_process_zero(self) -> bool:\n \"\"\"\n Whether or not this process is the local (e.g., on one machine if training in a distributed fashion on several\n machines) main process.\n \"\"\"\n if is_torch_tpu_available():\n return xm.is_master_ordinal(local=True)\n else:\n return self.args.local_rank in [-1, 0]\n\n def is_world_process_zero(self) -> bool:\n \"\"\"\n Whether or not this process is the global main process (when training in a distributed fashion on several\n machines, this is only going to be :obj:`True` for one process).\n \"\"\"\n if is_torch_tpu_available():\n return xm.is_master_ordinal(local=False)\n else:\n return self.args.local_rank == -1 or dist.get_rank() == 0\n\n def save_model(self, output_dir: Optional[str] = None):\n \"\"\"\n Will save the model, so you can reload it using :obj:`from_pretrained()`.\n\n Will only save from the world_master process (unless in TPUs).\n \"\"\"\n\n if is_torch_tpu_available():\n self._save_tpu(output_dir)\n elif self.is_world_process_zero():\n self._save(output_dir)\n\n # If on sagemaker and we are saving the main model (not a checkpoint so output_dir=None), save a copy to\n # SM_MODEL_DIR for easy deployment.\n if output_dir is None and os.getenv(\"SM_MODEL_DIR\") is not None:\n self.save_model(output_dir=os.getenv(\"SM_MODEL_DIR\"))\n\n def _save_tpu(self, output_dir: Optional[str] = None):\n output_dir = output_dir if output_dir is not None else self.args.output_dir\n logger.info(\"Saving model checkpoint to %s\", output_dir)\n\n if xm.is_master_ordinal():\n os.makedirs(output_dir, exist_ok=True)\n torch.save(self.args, os.path.join(output_dir, \"training_args.bin\"))\n\n # Save a trained model and configuration using `save_pretrained()`.\n # They can then be reloaded using `from_pretrained()`\n xm.rendezvous(\"saving_checkpoint\")\n if not isinstance(self.model, PreTrainedModel):\n if isinstance(_model_unwrap(self.model), PreTrainedModel):\n if xm.is_master_ordinal():\n _model_unwrap(self.model).config.save_pretrained(output_dir)\n else:\n logger.info(\"Trainer.model is not a `PreTrainedModel`, only saving its state dict.\")\n state_dict = self.model.state_dict()\n xm.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME))\n else:\n self.model.save_pretrained(output_dir)\n if self.tokenizer is not None and self.is_world_process_zero():\n self.tokenizer.save_pretrained(output_dir)\n\n def _save(self, output_dir: Optional[str] = None):\n output_dir = output_dir if output_dir is not None else self.args.output_dir\n os.makedirs(output_dir, exist_ok=True)\n logger.info(\"Saving model checkpoint to %s\", output_dir)\n # Save a trained model and configuration using `save_pretrained()`.\n # They can then be reloaded using `from_pretrained()`\n if not isinstance(self.model, PreTrainedModel):\n if isinstance(_model_unwrap(self.model), PreTrainedModel):\n _model_unwrap(self.model).config.save_pretrained(output_dir)\n else:\n logger.info(\"Trainer.model is not a `PreTrainedModel`, only saving its state dict.\")\n state_dict = self.model.state_dict()\n torch.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME))\n else:\n self.model.save_pretrained(output_dir)\n if self.tokenizer is not None and self.is_world_process_zero():\n self.tokenizer.save_pretrained(output_dir)\n\n # Good practice: save your training arguments together with the trained model\n torch.save(self.args, os.path.join(output_dir, \"training_args.bin\"))\n\n def store_flos(self):\n # Storing the number of floating-point operations that went into the model\n if self._total_flos is not None:\n if self.args.local_rank != -1:\n self.state.total_flos = distributed_broadcast_scalars([self._total_flos]).sum().item()\n else:\n self.state.total_flos = self._total_flos\n\n def _sorted_checkpoints(\n self, output_dir=None, checkpoint_prefix=PREFIX_CHECKPOINT_DIR, use_mtime=False\n ) -> List[str]:\n ordering_and_checkpoint_path = []\n\n glob_checkpoints = [str(x) for x in Path(output_dir).glob(f\"{checkpoint_prefix}-*\")]\n\n for path in glob_checkpoints:\n if use_mtime:\n ordering_and_checkpoint_path.append((os.path.getmtime(path), path))\n else:\n regex_match = re.match(f\".*{checkpoint_prefix}-([0-9]+)\", path)\n if regex_match and regex_match.groups():\n ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path))\n\n checkpoints_sorted = sorted(ordering_and_checkpoint_path)\n checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted]\n # Make sure we don't delete the best model.\n if self.state.best_model_checkpoint is not None:\n best_model_index = checkpoints_sorted.index(str(Path(self.state.best_model_checkpoint)))\n checkpoints_sorted[best_model_index], checkpoints_sorted[-1] = (\n checkpoints_sorted[-1],\n checkpoints_sorted[best_model_index],\n )\n return checkpoints_sorted\n\n def _rotate_checkpoints(self, use_mtime=False, output_dir=None) -> None:\n if self.args.save_total_limit is None or self.args.save_total_limit <= 0:\n return\n\n # Check if we should delete older checkpoint(s)\n checkpoints_sorted = self._sorted_checkpoints(use_mtime=use_mtime, output_dir=output_dir)\n if len(checkpoints_sorted) <= self.args.save_total_limit:\n return\n\n number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - self.args.save_total_limit)\n checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete]\n for checkpoint in checkpoints_to_be_deleted:\n logger.info(\"Deleting older checkpoint [{}] due to args.save_total_limit\".format(checkpoint))\n shutil.rmtree(checkpoint)\n\n def evaluate(\n self,\n eval_dataset: Optional[Dataset] = None,\n ignore_keys: Optional[List[str]] = None,\n metric_key_prefix: str = \"eval\",\n iters: int = 0,\n warmup_iter: int = 0,\n ) -> Dict[str, float]:\n \"\"\"\n Run evaluation and returns metrics.\n\n The calling script will be responsible for providing a method to compute metrics, as they are task-dependent\n (pass it to the init :obj:`compute_metrics` argument).\n\n You can also subclass and override this method to inject custom behavior.\n\n Args:\n eval_dataset (:obj:`Dataset`, `optional`):\n Pass a dataset if you wish to override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`,\n columns not accepted by the ``model.forward()`` method are automatically removed. It must implement the\n :obj:`__len__` method.\n ignore_keys (:obj:`Lst[str]`, `optional`):\n A list of keys in the output of your model (if it is a dictionary) that should be ignored when\n gathering predictions.\n metric_key_prefix (:obj:`str`, `optional`, defaults to :obj:`\"eval\"`):\n An optional prefix to be used as the metrics key prefix. For example the metrics \"bleu\" will be named\n \"eval_bleu\" if the prefix is \"eval\" (default)\n\n Returns:\n A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The\n dictionary also contains the epoch number which comes from the training state.\n \"\"\"\n # memory metrics - must set up as early as possible\n self._memory_tracker.start()\n\n if eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized):\n raise ValueError(\"eval_dataset must implement __len__\")\n\n eval_dataloader = self.get_eval_dataloader(eval_dataset)\n global eval_start_time \n n_samples = len(eval_dataset if eval_dataset is not None else self.eval_dataset)\n tot_iters = (n_samples + eval_dataloader.batch_size - 1) // eval_dataloader.batch_size\n warmup_iter = min(warmup_iter,tot_iters - 1,iters-1)\n eval_start_time = time.time()\n output = self.prediction_loop(\n eval_dataloader,\n description=\"Evaluation\",\n # No point gathering the predictions if there are no metrics, otherwise we defer to\n # self.args.prediction_loss_only\n prediction_loss_only=True if self.compute_metrics is None else None,\n ignore_keys=ignore_keys,\n metric_key_prefix=metric_key_prefix,\n iters=iters,\n warmup_iter=warmup_iter,\n )\n if warmup_iter > 0:\n if iters < tot_iters:\n valid_samples = (iters - warmup_iter) * eval_dataloader.batch_size\n else:\n valid_samples = n_samples - warmup_iter * eval_dataloader.batch_size\n else:\n valid_samples = n_samples\n output.metrics.update(speed_metrics(metric_key_prefix, eval_start_time, valid_samples))\n self.log(output.metrics)\n\n if self.args.tpu_metrics_debug or self.args.debug:\n # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)\n xm.master_print(met.metrics_report())\n\n self.control = self.callback_handler.on_evaluate(self.args, self.state, self.control, output.metrics)\n\n self._memory_tracker.stop_and_update_metrics(output.metrics)\n\n return output.metrics\n\n def predict(\n self, test_dataset: Dataset, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = \"eval\"\n ) -> PredictionOutput:\n \"\"\"\n Run prediction and returns predictions and potential metrics.\n\n Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method\n will also return metrics, like in :obj:`evaluate()`.\n\n Args:\n test_dataset (:obj:`Dataset`):\n Dataset to run the predictions on. If it is an :obj:`datasets.Dataset`, columns not accepted by the\n ``model.forward()`` method are automatically removed. Has to implement the method :obj:`__len__`\n ignore_keys (:obj:`Lst[str]`, `optional`):\n A list of keys in the output of your model (if it is a dictionary) that should be ignored when\n gathering predictions.\n metric_key_prefix (:obj:`str`, `optional`, defaults to :obj:`\"eval\"`):\n An optional prefix to be used as the metrics key prefix. For example the metrics \"bleu\" will be named\n \"eval_bleu\" if the prefix is \"eval\" (default)\n\n .. note::\n\n If your predictions or labels have different sequence length (for instance because you're doing dynamic\n padding in a token classification task) the predictions will be padded (on the right) to allow for\n concatenation into one array. The padding index is -100.\n\n Returns: `NamedTuple` A namedtuple with the following keys:\n\n - predictions (:obj:`np.ndarray`): The predictions on :obj:`test_dataset`.\n - label_ids (:obj:`np.ndarray`, `optional`): The labels (if the dataset contained some).\n - metrics (:obj:`Dict[str, float]`, `optional`): The potential dictionary of metrics (if the dataset\n contained labels).\n \"\"\"\n # memory metrics - must set up as early as possible\n self._memory_tracker.start()\n\n if test_dataset is not None and not isinstance(test_dataset, collections.abc.Sized):\n raise ValueError(\"test_dataset must implement __len__\")\n\n test_dataloader = self.get_test_dataloader(test_dataset)\n start_time = time.time()\n\n output = self.prediction_loop(\n test_dataloader, description=\"Prediction\", ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix\n )\n output.metrics.update(speed_metrics(metric_key_prefix, start_time, len(test_dataset)))\n\n self._memory_tracker.stop_and_update_metrics(output.metrics)\n\n return output\n\n def prediction_loop(\n self,\n dataloader: DataLoader,\n description: str,\n prediction_loss_only: Optional[bool] = None,\n ignore_keys: Optional[List[str]] = None,\n metric_key_prefix: str = \"eval\",\n iters: int = 0,\n warmup_iter: int = 0,\n ) -> PredictionOutput:\n \"\"\"\n Prediction/evaluation loop, shared by :obj:`Trainer.evaluate()` and :obj:`Trainer.predict()`.\n\n Works both with or without labels.\n \"\"\"\n if not isinstance(dataloader.dataset, collections.abc.Sized):\n raise ValueError(\"dataset must implement __len__\")\n prediction_loss_only = (\n prediction_loss_only if prediction_loss_only is not None else self.args.prediction_loss_only\n )\n\n if self.args.deepspeed and not self.args.do_train:\n # no harm, but flagging to the user that deepspeed config is ignored for eval\n # flagging only for when --do_train wasn't passed as only then it's redundant\n logger.info(\"Detected the deepspeed argument but it will not be used for evaluation\")\n\n model = self._wrap_model(self.model, training=False)\n\n # if full fp16 is wanted on eval and this ``evaluation`` or ``predict`` isn't called while\n # ``train`` is running, half it first and then put on device\n if not self.is_in_train and self.args.fp16_full_eval:\n model = model.half().to(self.args.device)\n\n batch_size = dataloader.batch_size\n num_examples = self.num_examples(dataloader) \n if iters > 0 and iters < (num_examples + batch_size - 1) // batch_size:\n num_examples = batch_size * iters\n logger.info(\"***** Running %s *****\", description)\n logger.info(\" Num examples = %d\", num_examples)\n logger.info(\" Batch size = %d\", batch_size)\n losses_host: torch.Tensor = None\n preds_host: Union[torch.Tensor, List[torch.Tensor]] = None\n labels_host: Union[torch.Tensor, List[torch.Tensor]] = None\n\n world_size = 1\n if is_torch_tpu_available():\n world_size = xm.xrt_world_size()\n elif self.args.local_rank != -1:\n world_size = dist.get_world_size()\n world_size = max(1, world_size)\n\n eval_losses_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=batch_size)\n if not prediction_loss_only:\n preds_gatherer = DistributedTensorGatherer(world_size, num_examples)\n labels_gatherer = DistributedTensorGatherer(world_size, num_examples)\n\n model.eval()\n\n if is_torch_tpu_available():\n dataloader = pl.ParallelLoader(dataloader, [self.args.device]).per_device_loader(self.args.device)\n\n if self.args.past_index >= 0:\n self._past = None\n\n self.callback_handler.eval_dataloader = dataloader\n for step, inputs in enumerate(dataloader):\n loss, logits, labels = self.prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys)\n if warmup_iter>0 and (step+1)==warmup_iter:\n global eval_start_time\n eval_start_time=time.time()\n if loss is not None:\n losses = loss.repeat(batch_size)\n losses_host = losses if losses_host is None else torch.cat((losses_host, losses), dim=0)\n if logits is not None:\n preds_host = logits if preds_host is None else nested_concat(preds_host, logits, padding_index=-100)\n if labels is not None:\n labels_host = labels if labels_host is None else nested_concat(labels_host, labels, padding_index=-100)\n self.control = self.callback_handler.on_prediction_step(self.args, self.state, self.control)\n\n # Gather all tensors and put them back on the CPU if we have done enough accumulation steps.\n if (self.args.eval_accumulation_steps is not None and (step + 1) % self.args.eval_accumulation_steps == 0) \\\n or (iters > 0 and (step + 1) >= iters):\n eval_losses_gatherer.add_arrays(self._gather_and_numpify(losses_host, \"eval_losses\"))\n if not prediction_loss_only:\n preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, \"eval_preds\"))\n labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, \"eval_label_ids\"))\n\n # Set back to None to begin a new accumulation\n losses_host, preds_host, labels_host = None, None, None\n if iters > 0 and (step + 1) >= iters:\n break\n if self.args.past_index and hasattr(self, \"_past\"):\n # Clean the state at the end of the evaluation loop\n delattr(self, \"_past\")\n\n # Gather all remaining tensors and put them back on the CPU\n eval_losses_gatherer.add_arrays(self._gather_and_numpify(losses_host, \"eval_losses\"))\n if not prediction_loss_only:\n preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, \"eval_preds\"))\n labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, \"eval_label_ids\"))\n\n eval_loss = eval_losses_gatherer.finalize()\n preds = preds_gatherer.finalize() if not prediction_loss_only else None\n label_ids = labels_gatherer.finalize() if not prediction_loss_only else None\n\n if self.compute_metrics is not None and preds is not None and label_ids is not None:\n metrics = self.compute_metrics(EvalPrediction(predictions=preds, label_ids=label_ids))\n else:\n metrics = {}\n\n if eval_loss is not None:\n metrics[f\"{metric_key_prefix}_loss\"] = eval_loss.mean().item()\n\n # Prefix all keys with metric_key_prefix + '_'\n for key in list(metrics.keys()):\n if not key.startswith(f\"{metric_key_prefix}_\"):\n metrics[f\"{metric_key_prefix}_{key}\"] = metrics.pop(key)\n\n return PredictionOutput(predictions=preds, label_ids=label_ids, metrics=metrics)\n\n def _gather_and_numpify(self, tensors, name):\n \"\"\"\n Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before\n concatenating them to `gathered`\n \"\"\"\n if tensors is None:\n return\n if is_torch_tpu_available():\n tensors = nested_xla_mesh_reduce(tensors, name)\n elif self.args.local_rank != -1:\n tensors = distributed_concat(tensors)\n\n return nested_numpify(tensors)\n\n def prediction_step(\n self,\n model: nn.Module,\n inputs: Dict[str, Union[torch.Tensor, Any]],\n prediction_loss_only: bool,\n ignore_keys: Optional[List[str]] = None,\n ) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]:\n \"\"\"\n Perform an evaluation step on :obj:`model` using obj:`inputs`.\n\n Subclass and override to inject custom behavior.\n\n Args:\n model (:obj:`nn.Module`):\n The model to evaluate.\n inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):\n The inputs and targets of the model.\n\n The dictionary will be unpacked before being fed to the model. Most models expect the targets under the\n argument :obj:`labels`. Check your model's documentation for all accepted arguments.\n prediction_loss_only (:obj:`bool`):\n Whether or not to return the loss only.\n ignore_keys (:obj:`Lst[str]`, `optional`):\n A list of keys in the output of your model (if it is a dictionary) that should be ignored when\n gathering predictions.\n\n Return:\n Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: A tuple with the loss, logits and\n labels (each being optional).\n \"\"\"\n has_labels = all(inputs.get(k) is not None for k in self.label_names)\n inputs = self._prepare_inputs(inputs)\n if ignore_keys is None:\n if hasattr(self.model, \"config\"):\n ignore_keys = getattr(self.model.config, \"keys_to_ignore_at_inference\", [])\n else:\n ignore_keys = []\n\n # labels may be popped when computing the loss (label smoothing for instance) so we grab them first.\n if has_labels:\n labels = nested_detach(tuple(inputs.get(name) for name in self.label_names))\n if len(labels) == 1:\n labels = labels[0]\n else:\n labels = None\n\n with torch.no_grad():\n if has_labels:\n loss, outputs = self.compute_loss(model, inputs, return_outputs=True)\n loss = loss.mean().detach()\n if isinstance(outputs, dict):\n logits = tuple(v for k, v in outputs.items() if k not in ignore_keys + [\"loss\"])\n else:\n logits = outputs[1:]\n else:\n loss = None\n if self.use_amp:\n with autocast():\n outputs = model(**inputs)\n else:\n outputs = model(**inputs)\n if isinstance(outputs, dict):\n logits = tuple(v for k, v in outputs.items() if k not in ignore_keys)\n else:\n logits = outputs\n # TODO: this needs to be fixed and made cleaner later.\n if self.args.past_index >= 0:\n self._past = outputs[self.args.past_index - 1]\n\n if prediction_loss_only:\n return (loss, None, None)\n\n logits = nested_detach(logits)\n if len(logits) == 1:\n logits = logits[0]\n\n return (loss, logits, labels)\n\n def floating_point_ops(self, inputs: Dict[str, Union[torch.Tensor, Any]]):\n \"\"\"\n For models that inherit from :class:`~transformers.PreTrainedModel`, uses that method to compute the number of\n floating point operations for every backward + forward pass. If using another model, either implement such a\n method in the model or subclass and override this method.\n\n Args:\n inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):\n The inputs and targets of the model.\n\n Returns:\n :obj:`int`: The number of floating-point operations.\n \"\"\"\n if hasattr(self.model, \"floating_point_ops\"):\n return self.model.floating_point_ops(inputs)\n else:\n return 0\n",
"import os\nimport shutil\nimport unittest\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.core.framework import graph_pb2\nfrom tensorflow.core.framework import node_def_pb2\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.framework import dtypes\nfrom neural_compressor.adaptor.tf_utils.graph_rewriter.bf16.bf16_convert import BF16Convert\n\ndef build_fake_yaml():\n fake_yaml = '''\n model:\n name: fake_yaml\n framework: tensorflow\n inputs: input \n outputs: final\n device: cpu\n quantization: \n op_wise: {\n \\\"conv1\\\": {\n \\\"activation\\\": {\\\"dtype\\\": [\\\"fp32\\\"]},\n },\n }\n evaluation:\n accuracy:\n metric:\n topk: 1\n tuning:\n strategy:\n name: basic\n exit_policy:\n timeout: 200\n accuracy_criterion:\n relative: 0.01\n workspace:\n path: saved\n '''\n with open('fake_yaml.yaml',\"w\",encoding=\"utf-8\") as f:\n f.write(fake_yaml)\n f.close()\n\ndef build_fake_bf16_rnn_yaml():\n fake_yaml = '''\n model:\n name: fake_yaml\n framework: tensorflow\n inputs: input_1\n outputs: dense/BiasAdd \n device: cpu\n quantization: \n op_wise: {\n \\\"lstm/while/MatMul\\\": {\n \\\"activation\\\": {\\\"dtype\\\": [\\\"bf16\\\"]},\n },\n \\\"lstm/while/MatMul_1\\\": {\n \\\"activation\\\": {\\\"dtype\\\": [\\\"bf16\\\"]},\n },\n \\\"lstm/while/MatMul_2\\\": {\n \\\"activation\\\": {\\\"dtype\\\": [\\\"bf16\\\"]},\n },\n \\\"lstm/while/MatMul_3\\\": {\n \\\"activation\\\": {\\\"dtype\\\": [\\\"bf16\\\"]},\n },\n \\\"lstm_1/while/MatMul\\\": {\n \\\"activation\\\": {\\\"dtype\\\": [\\\"bf16\\\"]},\n },\n \\\"lstm_1/while/MatMul_1\\\": {\n \\\"activation\\\": {\\\"dtype\\\": [\\\"bf16\\\"]},\n },\n \\\"lstm_1/while/MatMul_2\\\": {\n \\\"activation\\\": {\\\"dtype\\\": [\\\"bf16\\\"]},\n },\n \\\"lstm_1/while/MatMul_3\\\": {\n \\\"activation\\\": {\\\"dtype\\\": [\\\"bf16\\\"]},\n },\n }\n evaluation:\n accuracy:\n metric:\n topk: 1\n tuning:\n accuracy_criterion:\n relative: 0.05\n exit_policy:\n performance_only: True\n '''\n with open('fake_bf16_rnn.yaml',\"w\",encoding=\"utf-8\") as f:\n f.write(fake_yaml)\n f.close()\n\ndef create_test_graph():\n input_node = node_def_pb2.NodeDef()\n input_node.name = \"input\"\n input_node.op = \"Placeholder\"\n input_node.attr[\"dtype\"].CopyFrom(attr_value_pb2.AttrValue(\n type=dtypes.float32.as_datatype_enum))\n \n conv1_weight_node = node_def_pb2.NodeDef()\n conv1_weight_node.name = \"conv1_weights\"\n conv1_weight_node.op = \"Const\"\n conv1_weight_value = np.float32(np.abs(np.random.randn(3,3,3,32)))\n conv1_weight_node.attr['dtype'].CopyFrom(attr_value_pb2.AttrValue(type=dtypes.float32.as_datatype_enum))\n conv1_weight_node.attr['value'].CopyFrom(attr_value_pb2.AttrValue(\n tensor=tensor_util.make_tensor_proto(\n conv1_weight_value, conv1_weight_value.dtype.type, conv1_weight_value.shape)))\n \n conv1_node = node_def_pb2.NodeDef()\n conv1_node.name = \"conv1\"\n conv1_node.op = \"Conv2D\"\n conv1_node.attr['T'].CopyFrom(attr_value_pb2.AttrValue(\n type=dtypes.float32.as_datatype_enum))\n conv1_node.input.extend([input_node.name, conv1_weight_node.name])\n conv1_node.attr['strides'].CopyFrom(attr_value_pb2.AttrValue(\n list=attr_value_pb2.AttrValue.ListValue(i=[1,1,1,1])))\n conv1_node.attr['dilations'].CopyFrom(attr_value_pb2.AttrValue(\n list=attr_value_pb2.AttrValue.ListValue(i=[1,1,1,1])))\n conv1_node.attr['padding'].CopyFrom(attr_value_pb2.AttrValue(s=b'SAME'))\n conv1_node.attr['data_format'].CopyFrom(attr_value_pb2.AttrValue(s=b'NHWC'))\n \n bias_node = node_def_pb2.NodeDef()\n bias_node.name = \"conv1_bias\"\n bias_node.op = \"Const\"\n bias_value = np.float32(np.abs(np.random.randn(32)))\n bias_node.attr['dtype'].CopyFrom(attr_value_pb2.AttrValue(type=dtypes.float32.as_datatype_enum))\n bias_node.attr['value'].CopyFrom(attr_value_pb2.AttrValue(tensor=tensor_util.make_tensor_proto(\n bias_value, bias_value.dtype.type, bias_value.shape)))\n \n bias_add_node = node_def_pb2.NodeDef()\n bias_add_node.name = \"conv1_bias_add\"\n bias_add_node.op = \"BiasAdd\"\n bias_add_node.attr['T'].CopyFrom(attr_value_pb2.AttrValue(type=dtypes.float32.as_datatype_enum))\n bias_add_node.input.extend([conv1_node.name, bias_node.name])\n bias_add_node.attr['data_format'].CopyFrom(attr_value_pb2.AttrValue(s=b'NHWC'))\n\n cast_node = node_def_pb2.NodeDef()\n cast_node.op = \"Cast\"\n cast_node.name = \"cast\"\n cast_node.attr['SrcT'].CopyFrom(attr_value_pb2.AttrValue(type=dtypes.float32.as_datatype_enum))\n cast_node.attr['DstT'].CopyFrom(attr_value_pb2.AttrValue(type=dtypes.bfloat16.as_datatype_enum))\n cast_node.input.extend([bias_add_node.name])\n \n relu_node = node_def_pb2.NodeDef()\n relu_node.op = \"Relu\"\n relu_node.name = \"relu\"\n relu_node.attr['T'].CopyFrom(attr_value_pb2.AttrValue(type=dtypes.bfloat16.as_datatype_enum))\n relu_node.input.extend([cast_node.name])\n \n cast2_node = node_def_pb2.NodeDef()\n cast2_node.op = \"Cast\"\n cast2_node.name = \"cast2\"\n cast2_node.attr['SrcT'].CopyFrom(attr_value_pb2.AttrValue(type=dtypes.bfloat16.as_datatype_enum))\n cast2_node.attr['DstT'].CopyFrom(attr_value_pb2.AttrValue(type=dtypes.float32.as_datatype_enum))\n cast2_node.input.extend([relu_node.name])\n\n conv2_weight_node = node_def_pb2.NodeDef()\n conv2_weight_node.name = \"conv2_weights\"\n conv2_weight_node.op = \"Const\"\n conv2_weight_value = np.float32(np.abs(np.random.randn(3,3,32,32)))\n conv2_weight_node.attr['dtype'].CopyFrom(attr_value_pb2.AttrValue(type=dtypes.float32.as_datatype_enum))\n conv2_weight_node.attr['value'].CopyFrom(attr_value_pb2.AttrValue(\n tensor=tensor_util.make_tensor_proto(\n conv2_weight_value, conv2_weight_value.dtype.type, conv2_weight_value.shape)))\n \n conv2_node = node_def_pb2.NodeDef()\n conv2_node.name = \"conv2\"\n conv2_node.op = \"Conv2D\"\n conv2_node.attr['T'].CopyFrom(attr_value_pb2.AttrValue(\n type=dtypes.float32.as_datatype_enum))\n conv2_node.input.extend([cast2_node.name, conv2_weight_node.name])\n conv2_node.attr['strides'].CopyFrom(attr_value_pb2.AttrValue(\n list=attr_value_pb2.AttrValue.ListValue(i=[1,1,1,1])))\n conv2_node.attr['dilations'].CopyFrom(attr_value_pb2.AttrValue(\n list=attr_value_pb2.AttrValue.ListValue(i=[1,1,1,1])))\n conv2_node.attr['padding'].CopyFrom(attr_value_pb2.AttrValue(s=b'SAME'))\n conv2_node.attr['data_format'].CopyFrom(attr_value_pb2.AttrValue(s=b'NHWC'))\n\n bias_node2 = node_def_pb2.NodeDef()\n bias_node2.name = \"conv2_bias\"\n bias_node2.op = \"Const\"\n bias_value2 = np.float32(np.abs(np.random.randn(32)))\n bias_node2.attr['dtype'].CopyFrom(attr_value_pb2.AttrValue(type=dtypes.float32.as_datatype_enum))\n bias_node2.attr['value'].CopyFrom(attr_value_pb2.AttrValue(tensor=tensor_util.make_tensor_proto(\n bias_value2, bias_value2.dtype.type, bias_value2.shape)))\n \n bias_add_node2 = node_def_pb2.NodeDef()\n bias_add_node2.name = \"conv2_bias_add\"\n bias_add_node2.op = \"BiasAdd\"\n bias_add_node2.attr['T'].CopyFrom(attr_value_pb2.AttrValue(type=dtypes.float32.as_datatype_enum))\n bias_add_node2.input.extend([conv2_node.name, bias_node2.name])\n bias_add_node2.attr['data_format'].CopyFrom(attr_value_pb2.AttrValue(s=b'NHWC'))\n \n relu_node2 = node_def_pb2.NodeDef()\n relu_node2.op = \"Relu\"\n relu_node2.name = \"relu2\"\n relu_node2.attr['T'].CopyFrom(attr_value_pb2.AttrValue(type=dtypes.float32.as_datatype_enum))\n relu_node2.input.extend([bias_add_node2.name])\n \n conv3_weight_node = node_def_pb2.NodeDef()\n conv3_weight_node.name = \"conv3_weights\"\n conv3_weight_node.op = \"Const\"\n conv3_weight_value = np.float32(np.abs(np.random.randn(3,3,32,32)))\n conv3_weight_node.attr['dtype'].CopyFrom(attr_value_pb2.AttrValue(type=dtypes.float32.as_datatype_enum))\n conv3_weight_node.attr['value'].CopyFrom(attr_value_pb2.AttrValue(\n tensor=tensor_util.make_tensor_proto(\n conv3_weight_value, conv3_weight_value.dtype.type, conv3_weight_value.shape)))\n \n conv3_node = node_def_pb2.NodeDef()\n conv3_node.name = \"conv3\"\n conv3_node.op = \"Conv2D\"\n conv3_node.attr['T'].CopyFrom(attr_value_pb2.AttrValue(\n type=dtypes.float32.as_datatype_enum))\n conv3_node.input.extend([relu_node2.name, conv3_weight_node.name])\n conv3_node.attr['strides'].CopyFrom(attr_value_pb2.AttrValue(\n list=attr_value_pb2.AttrValue.ListValue(i=[1,1,1,1])))\n conv3_node.attr['dilations'].CopyFrom(attr_value_pb2.AttrValue(\n list=attr_value_pb2.AttrValue.ListValue(i=[1,1,1,1])))\n conv3_node.attr['padding'].CopyFrom(attr_value_pb2.AttrValue(s=b'SAME'))\n conv3_node.attr['data_format'].CopyFrom(attr_value_pb2.AttrValue(s=b'NHWC'))\n\n identity_node = node_def_pb2.NodeDef()\n identity_node.name = \"final\"\n identity_node.op = \"Identity\"\n identity_node.attr['T'].CopyFrom(attr_value_pb2.AttrValue(\n type=dtypes.float32.as_datatype_enum))\n identity_node.input.extend([conv3_node.name])\n\n test_graph = graph_pb2.GraphDef()\n\n test_graph.node.extend([input_node, \n conv1_weight_node, \n conv1_node, \n bias_node, \n bias_add_node, \n cast_node,\n relu_node,\n cast2_node,\n conv2_weight_node, \n conv2_node, \n bias_node2, \n bias_add_node2, \n relu_node2,\n conv3_weight_node, \n conv3_node,\n identity_node\n ])\n return test_graph\n\nclass TestBF16Convert(unittest.TestCase):\n rn50_fp32_pb_url = 'https://storage.googleapis.com/intel-optimized-tensorflow/models/v1_6/resnet50_fp32_pretrained_model.pb'\n pb_path = '/tmp/.neural_compressor/resnet50_fp32_pretrained_model.pb'\n\n @classmethod\n def setUpClass(self):\n if not os.path.exists(self.pb_path):\n os.system('mkdir -p /tmp/.neural_compressor && wget {} -O {} '.format(self.rn50_fp32_pb_url, self.pb_path))\n self.input_graph = tf.compat.v1.GraphDef()\n with open(self.pb_path, \"rb\") as f:\n self.input_graph.ParseFromString(f.read())\n self.test_graph = create_test_graph()\n build_fake_yaml()\n build_fake_bf16_rnn_yaml()\n\n @classmethod\n def tearDownClass(self):\n os.remove('fake_yaml.yaml')\n os.remove('fake_bf16_rnn.yaml')\n shutil.rmtree(\"saved\", ignore_errors=True)\n\n def test_rn50_convert(self):\n bf16_nodes = [node.name for node in self.input_graph.node if node.op in [\"Conv2D\", \"AvgPool\", \"MatMul\"]]\n bf16_nodes.remove(\"v0/resnet_v13/conv14/conv2d/Conv2D\")\n rn50_bf16_converter = BF16Convert(self.input_graph, [\"v0/resnet_v13/conv14/conv2d/Conv2D\"], bf16_nodes)\n rn50_bf16_converter.do_transformation()\n new_conv11 = rn50_bf16_converter.cur_graph.node_name_details[\"v0/resnet_v13/conv11/conv2d/Conv2D\"].node\n new_conv14 = rn50_bf16_converter.cur_graph.node_name_details[\"v0/resnet_v13/conv14/conv2d/Conv2D\"].node\n new_conv52 = rn50_bf16_converter.cur_graph.node_name_details[\"v0/resnet_v115/conv52/conv2d/Conv2D\"].node\n self.assertEqual(new_conv11.attr[\"T\"].type, new_conv52.attr[\"T\"].type)\n self.assertNotEqual(new_conv11.attr[\"T\"].type, new_conv14.attr[\"T\"].type)\n\n\n def test_do_transform(self):\n bf16_converter = BF16Convert(self.test_graph, [\"conv3\"], [\"conv2\"])\n new_graph = bf16_converter.do_transformation()\n new_conv1 = bf16_converter.cur_graph.node_name_details[\"conv1\"].node\n new_relu2 = bf16_converter.cur_graph.node_name_details[\"relu2\"].node\n new_conv3 = bf16_converter.cur_graph.node_name_details[\"conv3\"].node\n self.assertEqual(new_relu2.attr[\"T\"].type, dtypes.bfloat16)\n self.assertTrue(\"relu2_BF16toFP32\" in new_conv3.input)\n\n @unittest.skipIf(tf.version.VERSION > '2.5.0', \" Skip test_bf16_fallback case for tf 2.6.0 and above.\")\n def test_bf16_fallback(self):\n os.environ['FORCE_BF16'] = '1'\n\n from neural_compressor.experimental import Quantization, common\n quantizer = Quantization('fake_yaml.yaml')\n dataset = quantizer.dataset('dummy', shape=(1, 224, 224, 3), label=True)\n quantizer.eval_dataloader = common.DataLoader(dataset)\n quantizer.calib_dataloader = common.DataLoader(dataset)\n quantizer.model = self.test_graph\n output_graph = quantizer.fit()\n cast_op_count = 0\n for node in output_graph.graph_def.node:\n if node.op == 'Cast':\n cast_op_count += 1\n self.assertTrue(cast_op_count >= 1)\n\n @unittest.skipIf(tf.version.VERSION.find('up') == -1, \"Only supports tf 1.x\")\n def test_bf16_rnn(self):\n os.environ['FORCE_BF16'] = '1'\n\n inp = tf.keras.layers.Input(shape=(None, 4))\n lstm_1 = tf.keras.layers.LSTM(units=10,\n return_sequences=True)(inp)\n dropout_1 = tf.keras.layers.Dropout(0.2)(lstm_1)\n lstm_2 = tf.keras.layers.LSTM(units=10,\n return_sequences=False)(dropout_1)\n dropout_2 = tf.keras.layers.Dropout(0.2)(lstm_2)\n out = tf.keras.layers.Dense(1)(dropout_2)\n model = tf.keras.models.Model(inputs=inp, outputs=out)\n\n model.compile(loss=\"mse\",\n optimizer=tf.keras.optimizers.RMSprop())\n\n # input_names = [t.name.split(\":\")[0] for t in model.inputs]\n output_names = [t.name.split(\":\")[0] for t in model.outputs]\n\n q_data = np.random.randn(64, 10, 4)\n label = np.random.randn(64, 1)\n model.predict(q_data)\n\n sess = tf.keras.backend.get_session()\n\n graph = sess.graph\n\n from tensorflow.python.framework import graph_util\n graph_def = graph_util.convert_variables_to_constants(\n sess,\n graph.as_graph_def(),\n output_names,\n )\n quant_data = (q_data, label)\n evl_data = (q_data, label)\n\n from neural_compressor.experimental import Quantization, common\n\n quantizer = Quantization('fake_bf16_rnn.yaml')\n quantizer.calib_dataloader = common.DataLoader(\n dataset=list(zip(quant_data[0], quant_data[1])))\n quantizer.eval_dataloader = common.DataLoader(\n dataset=list(zip(evl_data[0], evl_data[1])))\n quantizer.model = graph_def\n quantized_model = quantizer.fit()\n\n convert_to_bf16_flag = False\n for i in quantized_model.graph_def.node:\n if i.name == 'lstm/while/MatMul_3' and \\\n i.attr['T'].type == dtypes.bfloat16.as_datatype_enum:\n convert_to_bf16_flag = True\n \n self.assertEqual(convert_to_bf16_flag, True)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n"
] |
[
[
"tensorflow.keras.models.load_model",
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.Conv2D",
"tensorflow.compat.v1.enable_eager_execution",
"tensorflow.keras.layers.InputLayer",
"tensorflow.compat.v1.saved_model.loader.load",
"tensorflow.compat.v1.Session",
"tensorflow.compat.v1.Graph",
"tensorflow.keras.layers.Reshape",
"tensorflow.keras.layers.MaxPooling2D",
"tensorflow.keras.layers.Flatten"
],
[
"torch.transpose",
"torch.cat",
"torch.load",
"torch.quantization.DeQuantStub",
"numpy.concatenate",
"numpy.round",
"torch.quantization.observer.MinMaxObserver.with_args",
"torch.cuda.is_available",
"torch.cuda.manual_seed_all",
"torch.device",
"torch.nn.EmbeddingBag",
"torch.cuda.synchronize",
"torch.quantization.prepare",
"torch.quantization.fuse_modules",
"torch.nn.Sigmoid",
"torch.tensor",
"torch.quantization.QuantStub",
"torch.nn.parallel.scatter_gather.scatter",
"torch.set_printoptions",
"torch.nn.ModuleList",
"torch.nn.ReLU",
"torch.nn.BCELoss",
"torch.nn.parallel.parallel_apply.parallel_apply",
"torch.nn.parallel.scatter_gather.gather",
"torch.quantization.convert",
"torch.cuda.device_count",
"numpy.random.seed",
"torch.manual_seed",
"numpy.set_printoptions",
"numpy.fromstring",
"torch.nn.parallel.replicate.replicate",
"torch.onnx._export",
"torch.clamp",
"torch.autograd.profiler.profile",
"torch.nn.MSELoss"
],
[
"torch.nn.CrossEntropyLoss",
"torch.load",
"torch.manual_seed",
"torch.utils.data.DataLoader",
"torch.no_grad",
"torch.save"
],
[
"tensorflow.Graph",
"tensorflow.import_graph_def",
"numpy.random.random",
"tensorflow.compat.v1.graph_util.convert_variables_to_constants",
"tensorflow.compat.v1.global_variables_initializer",
"tensorflow.compat.v1.Session",
"tensorflow.compat.v1.placeholder",
"tensorflow.compat.v1.GraphDef",
"tensorflow.nn.conv2d"
],
[
"torch.utils.data.distributed.DistributedSampler",
"torch.cat",
"torch.utils.data.sampler.SequentialSampler",
"torch.tensor",
"torch.cuda.amp.autocast",
"torch.nn.DataParallel",
"torch.cuda.amp.GradScaler",
"torch.no_grad",
"torch.distributed.get_rank",
"torch.utils.data.dataloader.DataLoader",
"torch.utils.data.sampler.RandomSampler",
"torch.distributed.get_local_rank",
"torch.distributed.get_world_size",
"torch.nn.parallel.DistributedDataParallel"
],
[
"tensorflow.keras.models.Model",
"tensorflow.keras.backend.get_session",
"tensorflow.keras.layers.Dense",
"tensorflow.version.VERSION.find",
"tensorflow.keras.optimizers.RMSprop",
"tensorflow.core.framework.node_def_pb2.NodeDef",
"tensorflow.keras.layers.LSTM",
"numpy.random.randn",
"tensorflow.python.framework.tensor_util.make_tensor_proto",
"tensorflow.core.framework.attr_value_pb2.AttrValue.ListValue",
"tensorflow.core.framework.attr_value_pb2.AttrValue",
"tensorflow.compat.v1.GraphDef",
"tensorflow.keras.layers.Dropout",
"tensorflow.core.framework.graph_pb2.GraphDef",
"tensorflow.keras.layers.Input"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
VitorGDellino/Neural-Network
|
[
"fb2ff335656145d385c0fbf6e68b0840efe51dd2"
] |
[
"MNIST/mnist.py"
] |
[
"import tensorflow as tf\nfrom tensorflow import keras\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#print(tf.__version__)\n\ndef plot_image(i, predictions_array, true_label, img):\n predictions_array, true_label, img = predictions_array[i], true_label[i], img[i]\n plt.grid(False)\n plt.xticks([])\n plt.yticks([])\n \n plt.imshow(img, cmap=plt.cm.binary)\n\n predicted_label = np.argmax(predictions_array)\n if predicted_label == true_label:\n color = 'blue'\n else:\n color = 'red'\n \n plt.xlabel(\"{} {:2.0f}% ({})\".format(class_names[predicted_label],\n 100*np.max(predictions_array),\n class_names[true_label]),\n color=color)\n\ndef plot_value_array(i, predictions_array, true_label):\n predictions_array, true_label = predictions_array[i], true_label[i]\n plt.grid(False)\n plt.xticks([])\n plt.yticks([])\n thisplot = plt.bar(range(10), predictions_array, color=\"#777777\")\n plt.ylim([0, 1]) \n predicted_label = np.argmax(predictions_array)\n \n thisplot[predicted_label].set_color('red')\n thisplot[true_label].set_color('blue')\n\nfashion_mnist = keras.datasets.fashion_mnist\n\n(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()\n\nclass_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', \n 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']\n\ntrain_images = train_images / 255.0\n\ntest_images = test_images / 255.0\n\nplt.figure(figsize=(10,10))\n\nfor i in range(25):\n plt.subplot(5,5,i+1)\n plt.xticks([])\n plt.yticks([])\n plt.grid(False)\n plt.imshow(train_images[i], cmap=plt.cm.binary)\n plt.xlabel(class_names[train_labels[i]])\n\nplt.show()\n\nmodel = keras.Sequential([\n keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(128, activation=tf.nn.relu),\n keras.layers.Dense(10, activation=tf.nn.softmax)\n])\n\nmodel.compile(optimizer=tf.train.AdamOptimizer(), \n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\n\nmodel.fit(train_images, train_labels, epochs=10)\n\n\ntest_loss, test_acc = model.evaluate(test_images, test_labels)\n\nprint('Test accuracy:', test_acc)\n\npredictions = model.predict(test_images)\nprint(predictions[0])\n\n\"\"\"num_rows = 5\nnum_cols = 3\nnum_images = num_rows*num_cols\nplt.figure(figsize=(2*2*num_cols, 2*num_rows))\nfor i in range(num_images):\n plt.subplot(num_rows, 2*num_cols, 2*i+1)\n plot_image(i, predictions, test_labels, test_images)\n plt.subplot(num_rows, 2*num_cols, 2*i+2)\n plot_value_array(i, predictions, test_labels)\n\nplt.show()\n\"\"\"\n\n\n\n"
] |
[
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.ylim",
"tensorflow.keras.layers.Dense",
"numpy.max",
"numpy.argmax",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.grid",
"tensorflow.train.AdamOptimizer",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.show",
"tensorflow.keras.layers.Flatten",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
kiyoon/GulpIO2
|
[
"143d53dbb7091b0938832415e32e04992439faf6"
] |
[
"src/gulpio2/fileio.py"
] |
[
"#!/usr/bin/env python\n\nimport os\nimport re\nimport pickle\nimport json\nimport glob\nimport numpy as np\n\nfrom abc import ABC, abstractmethod\nfrom concurrent.futures import ProcessPoolExecutor\nfrom contextlib import contextmanager\nfrom collections import namedtuple, OrderedDict\n\nfrom tqdm import tqdm\n\nfrom .utils import img_to_jpeg_bytes, jpeg_bytes_to_img, _DEFAULT_JPEG_QUALITY\nfrom pathlib import Path\n#from simplejpeg import is_jpeg\n\ndef is_jpeg(data):\n \"\"\"\n Check whether a bytes object (or similar) contains JPEG (JFIF) data.\n Returns False for truncated files.\n Taken from simplejpeg.is_jpeg, but less strict because it doesn't check EOI, as most JPEG viewers don't really throw error for missing EOI.\n\n :param data: JPEG (JFIF) data\n :return: True if JPEG\n \"\"\"\n return data[:2] == b'\\xFF\\xD8'\n\n\nImgInfo = namedtuple('ImgInfo', ['loc',\n 'pad',\n 'length'])\n\n\nclass FileFormatException(Exception):\n pass\n\n\nclass AbstractSerializer(ABC): # pragma: no cover\n\n @abstractmethod\n def load(self, file_name):\n pass\n\n @abstractmethod\n def dump(self, thing, file_name):\n pass\n\n\nclass PickleSerializer(AbstractSerializer):\n\n def load(self, file_name):\n with open(file_name, 'rb') as file_pointer:\n return pickle.load(file_pointer)\n\n def dump(self, thing, file_name):\n with open(file_name, 'wb') as file_pointer:\n pickle.dump(thing, file_pointer)\n\n\nclass JSONSerializer(AbstractSerializer):\n\n def load(self, file_name):\n with open(file_name, 'r') as file_pointer:\n return json.load(file_pointer, object_pairs_hook=OrderedDict)\n\n def dump(self, thing, file_name):\n with open(file_name, 'w') as file_pointer:\n json.dump(thing, file_pointer)\n\n\npickle_serializer = PickleSerializer()\njson_serializer = JSONSerializer()\n\n\ndef extract_input_for_getitem(element):\n if isinstance(element, tuple) and len(element) == 2:\n id_, slice_ = element\n elif isinstance(element, (int, str)):\n id_, slice_ = element, None\n else:\n raise TypeError(\"Undefined input type! id or (id, slice) expected\")\n id_ = str(id_)\n return id_, slice_\n\n\nclass GulpDirectory(object):\n \"\"\" Represents a directory containing *.gulp and *.gmeta files.\n\n Parameters\n ----------\n output_dir: str\n Path to the directory containing the files.\n jpeg_decoder: callable that takes a JPEG stored as :py:class:`bytes` and returns\n the desired decoded image format (e.g. np.ndarray)\n\n Attributes\n ----------\n all_meta_dicts: list of dicts\n All meta dicts from all chunks as a list.\n chunk_lookup: dict: int -> str\n Mapping element id to chunk index.\n chunk_objs_lookup: dict: int -> GulpChunk\n Mapping element id to chunk index.\n merged_meta_dict: dict: id -> meta dict\n all meta dicts merged\n\n \"\"\"\n\n def __init__(self, output_dir, jpeg_decoder=jpeg_bytes_to_img):\n self.output_dir = output_dir\n self.jpeg_decoder = jpeg_decoder\n self.chunk_objs_lookup = OrderedDict(zip(self._chunk_ids(), self._chunks()))\n self.all_meta_dicts = [c.meta_dict for c in self.chunk_objs_lookup.values()]\n self.num_chunks = len(self.chunk_objs_lookup)\n self.chunk_lookup = {}\n for chunk_id, chunk in self.chunk_objs_lookup.items():\n for id_ in chunk.meta_dict:\n self.chunk_lookup[id_] = chunk_id\n self.merged_meta_dict = {}\n for d in self.all_meta_dicts:\n for k in d.keys():\n assert k not in self.merged_meta_dict,\\\n \"Duplicate id detected {}\".format(k)\n else:\n self.merged_meta_dict.update(d)\n\n def __iter__(self):\n return iter(self.chunk_objs_lookup.values())\n\n def chunks(self):\n \"\"\" Return a generator over existing GulpChunk objects which are ready\n to be opened and read from. \"\"\"\n return self.__iter__()\n\n def _chunks(self):\n return (GulpChunk(*paths, jpeg_decoder=self.jpeg_decoder) for paths in\n self._existing_file_paths())\n\n def new_chunks(self, total_new_chunks):\n \"\"\" Return a generator over freshly setup GulpChunk objects which are ready\n to be opened and written to.\n\n Parameters\n ----------\n total_new_chunks: int\n The total number of new chunks to initialize.\n \"\"\"\n return ((GulpChunk(*paths, jpeg_decoder=self.jpeg_decoder) for paths in\n self._allocate_new_file_paths(total_new_chunks)))\n\n def __getitem__(self, element):\n id_, _ = extract_input_for_getitem(element)\n chunk_id = self.chunk_lookup[id_]\n gulp_chunk = self.chunk_objs_lookup[chunk_id]\n with gulp_chunk.open():\n return gulp_chunk[element]\n\n def _find_existing_data_paths(self):\n return sorted(glob.glob(os.path.join(self.output_dir, 'data*.gulp')))\n\n def _find_existing_meta_paths(self):\n return sorted(glob.glob(os.path.join(self.output_dir, 'meta*.gmeta')))\n\n def _load_label_dict(self):\n return json.load(open(os.path.join(self.output_dir, 'label2idx.json'),\n 'rb'))\n\n def _existing_file_paths(self):\n data_paths = self._find_existing_data_paths()\n meta_paths = self._find_existing_meta_paths()\n assert len(data_paths) == len(meta_paths)\n return zip(data_paths, meta_paths)\n\n def _find_ids_from_paths(self, paths):\n return [int(re.findall(r'\\d+', os.path.basename(p))[0]) for p in paths]\n\n def _chunk_ids(self):\n data_paths = self._find_existing_data_paths()\n meta_paths = self._find_existing_meta_paths()\n data_ids = self._find_ids_from_paths(data_paths)\n meta_ids = self._find_ids_from_paths(meta_paths)\n assert data_ids == meta_ids\n return data_ids\n\n def _next_chunk_id(self):\n existing_chunk_ids = self._chunk_ids()\n next_chunk_id = 0\n if len(existing_chunk_ids) > 0:\n next_chunk_id = max([int(i) for i in existing_chunk_ids]) + 1\n return next_chunk_id\n\n def _allocate_new_file_paths(self, total_new_chunks):\n next_chunk_id = self._next_chunk_id()\n return [self._initialize_filenames(i)\n for i in range(next_chunk_id,\n next_chunk_id + total_new_chunks)]\n\n def _initialize_filenames(self, chunk_id):\n data_file_path = os.path.join(\n self.output_dir, 'data_{}.gulp'.format(chunk_id))\n meta_file_path = os.path.join(\n self.output_dir, 'meta_{}.gmeta'.format(chunk_id))\n return data_file_path, meta_file_path\n\n\nclass GulpChunk(object):\n \"\"\" Represents a gulp chunk on disk.\n\n Parameters\n ----------\n data_file_path: str\n Path to the *.gulp file.\n meta_file_path: str\n Path to the *.gmeta file.\n serializer: subclass of AbstractSerializer\n The type of serializer to use.\n jpeg_decoder: callable that takes a JPEG stored as :py:class:`bytes` and returns\n the desired decoded image format (e.g. np.ndarray)\n \"\"\"\n\n def __init__(self, data_file_path, meta_file_path,\n serializer=json_serializer, jpeg_decoder=jpeg_bytes_to_img):\n self.jpeg_decoder = jpeg_decoder\n self.serializer = serializer\n self.data_file_path = data_file_path\n self.meta_file_path = meta_file_path\n self.meta_dict = self._get_or_create_dict()\n\n self._img_info = {}\n self.fp = None\n\n def __contains__(self, id_):\n return str(id_) in self.meta_dict\n\n def __getitem__(self, element):\n id_, slice_ = extract_input_for_getitem(element)\n return self.read_frames(id_, slice_)\n\n def __iter__(self):\n return self.iter_all()\n\n def _get_frame_infos(self, id_):\n id_ = str(id_)\n if id_ in self.meta_dict:\n return (self._get_or_create_img_info(id_),\n self._copy_meta_data(id_))\n\n def _copy_meta_data(self, id_):\n return dict(self.meta_dict[id_]['meta_data'][0])\n\n def _get_or_create_img_info(self, id_):\n if id_ not in self._img_info:\n self._img_info[id_] = [ImgInfo(*info) for info in self.meta_dict[id_]['frame_info']]\n return self._img_info[id_]\n\n def _get_or_create_dict(self):\n if os.path.exists(self.meta_file_path):\n return self.serializer.load(self.meta_file_path)\n else:\n return OrderedDict()\n\n @staticmethod\n def _default_factory():\n return OrderedDict([('frame_info', []), ('meta_data', [])])\n\n @staticmethod\n def _pad_image(number):\n return (4 - (number % 4)) % 4\n\n def _append_meta(self, id_, meta_data):\n id_ = str(id_)\n if id_ not in self.meta_dict: # implements an OrderedDefaultDict\n self.meta_dict[id_] = self._default_factory()\n self.meta_dict[id_]['meta_data'].append(meta_data)\n\n def _write_frame(self, id_, image, jpeg_encode_quality=_DEFAULT_JPEG_QUALITY):\n loc = self.fp.tell()\n\n if isinstance(image, (str, Path)):\n # If image is a string or pathlib Path, assume that it is a path to a jpeg file\n # and add it directly without decoding and encoding it.\n with open(str(image), 'rb') as image_file:\n img_str = image_file.read()\n\n if not is_jpeg(img_str):\n raise FileFormatException(f'Image file from path {image} does not appear to be a JPEG file.')\n else: # np.array\n img_str = img_to_jpeg_bytes(image, jpeg_encode_quality)\n assert len(img_str) > 0\n\n pad = self._pad_image(len(img_str))\n record = img_str.ljust(len(img_str) + pad, b'\\0')\n assert len(record) > 0\n img_info = ImgInfo(loc=loc,\n length=len(record),\n pad=pad)\n id_ = str(id_)\n if id_ not in self.meta_dict: # implements an OrderedDefaultDict\n self.meta_dict[id_] = self._default_factory()\n self.meta_dict[id_]['frame_info'].append(img_info)\n self.fp.write(record)\n\n def _write_frames(self, id_, frames, jpeg_encode_quality=_DEFAULT_JPEG_QUALITY):\n for frame in frames:\n self._write_frame(id_, frame, jpeg_encode_quality)\n\n @contextmanager\n def open(self, flag='rb'):\n \"\"\"Open the gulp chunk for reading.\n\n Parameters\n ----------\n flag: str\n 'rb': Read binary\n 'wb': Write binary\n 'ab': Append to binary\n\n Notes\n -----\n Works as a context manager but returns None.\n\n \"\"\"\n if flag in ['wb', 'rb', 'ab']:\n self.fp = open(self.data_file_path, flag)\n else:\n m = \"This file does not support the mode: '{}'\".format(flag)\n raise NotImplementedError(m)\n yield\n if flag in ['wb', 'ab']:\n self.flush()\n self.fp.close()\n\n def flush(self):\n \"\"\"Flush all buffers and write the meta file.\"\"\"\n self.fp.flush()\n self.serializer.dump(self.meta_dict, self.meta_file_path)\n\n def append(self, id_, meta_data, frames, jpeg_encode_quality=_DEFAULT_JPEG_QUALITY):\n \"\"\" Append an item to the gulp.\n\n Parameters\n ----------\n id_ : str\n The ID of the item\n meta_data: dict\n The meta-data associated with the item.\n frames: list of numpy arrays\n The frames of the item as a list of numpy dictionaries consisting\n of image pixel values.\n\n \"\"\"\n self._append_meta(id_, meta_data)\n self._write_frames(id_, frames, jpeg_encode_quality=jpeg_encode_quality)\n\n def read_frames(self, id_, slice_=None):\n \"\"\" Read frames for a single item.\n\n Parameters\n ----------\n id_: str\n The ID of the item\n slice_: slice or list of ints:\n A slice or list of indices with which to select frames.\n\n Returns\n -------\n frames (int), meta(dict)\n The frames of the item as a list of numpy arrays consisting of\n image pixel values. And the metadata.\n\n \"\"\"\n frame_infos, meta_data = self._get_frame_infos(id_)\n slice_element = slice_ if slice_ is not None else slice(0, len(frame_infos))\n\n def extract_frame(frame_info):\n self.fp.seek(frame_info.loc)\n record = self.fp.read(frame_info.length)\n img_str = record[:len(record)-frame_info.pad]\n img = self.jpeg_decoder(img_str)\n return img\n if isinstance(slice_element, (list, np.ndarray)):\n selected_frame_infos = [frame_infos[idx] for idx in slice_element]\n else:\n selected_frame_infos = frame_infos[slice_element]\n frames = [extract_frame(frame_info)\n for frame_info in selected_frame_infos]\n return frames, meta_data\n\n def iter_all(self, accepted_ids=None, shuffle=False):\n \"\"\" Iterate over all frames in the gulp.\n\n Parameters\n ----------\n accepted_ids: list of str\n A filter for accepted ids.\n shuffle: bool\n Shuffle the items or not.\n\n Returns\n -------\n iterator\n An iterator that yield a series of frames,meta tuples. See\n `read_frames` for details.\n \"\"\"\n\n ids = self.meta_dict.keys()\n\n if accepted_ids is not None:\n intersection = list(set(ids) & set(accepted_ids))\n ids = [id_ for id_ in ids if id_ in intersection]\n\n if shuffle:\n ids = list(ids)\n np.random.shuffle(ids)\n\n with self.open('rb'):\n for id_ in ids:\n frames, meta = self.read_frames(id_)\n yield frames, meta\n\n\nclass ChunkWriter(object):\n \"\"\"Can write from an adapter to a gulp chunk.\n\n Parameters\n ----------\n adapter: subclass of AbstractDatasetAdapter\n The adapter to get items from.\n\n \"\"\"\n\n def __init__(self, adapter):\n self.adapter = adapter\n\n def write_chunk(self, output_chunk, input_slice):\n \"\"\"Write from an input slice in the adapter to an output chunk.\n\n Parameters\n ----------\n output_chunk: GulpChunk\n The chunk to write to\n input_slice: slice\n The slice to use from the adapter.\n\n \"\"\"\n with output_chunk.open('wb'):\n for video in self.adapter.iter_data(input_slice):\n id_ = video['id']\n meta_data = video['meta']\n frames = video['frames']\n if len(frames) > 0:\n output_chunk.append(id_, meta_data, frames, self.adapter.jpeg_encode_quality())\n else:\n print(\"Failed to write video with id: {}; no frames\"\n .format(id_))\n\n\ndef calculate_chunk_slices(items_per_chunk, num_items):\n \"\"\"Calculate slices for indexing an adapter.\n\n Parameters\n ----------\n items_per_chunk: int\n Approximate number of items per chunk.\n num_items: int\n Total number of items.\n\n Returns\n -------\n list of slices\n\n \"\"\"\n assert items_per_chunk > 0\n assert num_items > 0\n return [slice(i, min(i + items_per_chunk, num_items))\n for i in range(0, num_items, items_per_chunk)]\n\n\nclass GulpIngestor(object):\n \"\"\"Ingest items from an adapter into an gulp chunks.\n\n Parameters\n ----------\n adapter: subclass of AbstractDatasetAdapter\n The adapter to ingest from.\n output_folder: str\n The folder/directory to write to.\n videos_per_chunk: int\n The total number of items per chunk.\n num_workers: int\n The level of parallelism.\n\n \"\"\"\n def __init__(self, adapter, output_folder, videos_per_chunk, num_workers):\n assert int(num_workers) > 0\n self.adapter = adapter\n self.output_folder = output_folder\n self.videos_per_chunk = int(videos_per_chunk)\n self.num_workers = int(num_workers)\n\n def __call__(self):\n os.makedirs(self.output_folder, exist_ok=True)\n chunk_slices = calculate_chunk_slices(self.videos_per_chunk,\n len(self.adapter))\n gulp_directory = GulpDirectory(self.output_folder)\n new_chunks = gulp_directory.new_chunks(len(chunk_slices))\n chunk_writer = ChunkWriter(self.adapter)\n with ProcessPoolExecutor(max_workers=self.num_workers) as executor:\n result = executor.map(chunk_writer.write_chunk,\n new_chunks,\n chunk_slices)\n for r in tqdm(result,\n desc='Chunks finished',\n unit='chunk',\n dynamic_ncols=True,\n total=len(chunk_slices)):\n pass\n"
] |
[
[
"numpy.random.shuffle"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
MartimChaves/ret_detect
|
[
"774521a079be4324d542a841c7b3be808c18356b"
] |
[
"main.py"
] |
[
"import cv2.cv2 as cv2\r\nimport skimage.io as io\r\nfrom skimage.transform import downscale_local_mean\r\nimport numpy as np\r\nfrom model import *\r\n\r\nfrom sklearn.naive_bayes import GaussianNB\r\n\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nimport numpy as np\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.svm import SVC\r\n\r\nfrom images_to_arr import *\r\n\r\nimport pickle\r\nimport csv\r\n\r\ndef removeBackground(img_in):\r\n Img_backless = np.copy(img_in)\r\n Img_backless = np.subtract(np.multiply(Img_backless,1.11),0.11)\r\n Img_backless[Img_backless < 0] = 0\r\n return Img_backless\r\n\r\ndef newBBcoords(img_pred_Log,test_image):\r\n # returns coordinates of the bounding box for the region with the largest area\r\n\r\n kernel_ones = np.ones([3,3],np.uint8)\r\n closing_Log = cv2.morphologyEx(img_pred_Log, cv2.MORPH_CLOSE, kernel_ones)\r\n\r\n labelsLog, numLog = label(closing_Log, neighbors=8, background = 0, return_num = True)\r\n regionsLog = regionprops(labelsLog)\r\n\r\n areasLog = [region['area'] for region in regionsLog]\r\n areasLogArr = np.array(areasLog)\r\n maxIndex = np.argmax(areasLogArr)\r\n\r\n value = labelsLog[regionsLog[maxIndex]['coords'][0][0],regionsLog[maxIndex]['coords'][0][1]]\r\n labelsLog[labelsLog != value] = 0\r\n labelsLog[labelsLog == value] = 1\r\n\r\n labelsImg = np.multiply(np.array(labelsLog, np.uint8),255)\r\n #myShowImage(labelsImg)\r\n\r\n sizeBoxX = regionsLog[maxIndex]['bbox'][3]-regionsLog[maxIndex]['bbox'][1]\r\n sizeBoxY = regionsLog[maxIndex]['bbox'][2]-regionsLog[maxIndex]['bbox'][0]\r\n\r\n coordsBbox = list(regionsLog[maxIndex]['bbox'])\r\n if sizeBoxX <= 0.5 * img_pred_Log.shape[1]:\r\n newSizeBoxX = 0.3 / (sizeBoxX / img_pred_Log.shape[1])\r\n coordsBbox[1] = coordsBbox[1] - sizeBoxX*(0.5*(newSizeBoxX-1)) \r\n coordsBbox[3] = coordsBbox[3] + sizeBoxX*(0.5*(newSizeBoxX-1)) \r\n\r\n if sizeBoxY <= 0.5 * img_pred_Log.shape[0]:\r\n newSizeBoxY = 0.5 / (sizeBoxY / img_pred_Log.shape[0])\r\n coordsBbox[0] = coordsBbox[0] - sizeBoxY*(0.5*(newSizeBoxY-1))\r\n coordsBbox[2] = coordsBbox[2] + sizeBoxY*(0.5*(newSizeBoxY-1))\r\n\r\n if coordsBbox[0] < 0:\r\n coordsBbox[0] = 0\r\n if coordsBbox[1] < 0:\r\n coordsBbox[1] = 0\r\n if coordsBbox[2] > test_image.shape[0]:\r\n coordsBbox[2] = test_image.shape[0] - 1\r\n if coordsBbox[3] > test_image.shape[1]:\r\n coordsBbox[3] = test_image.shape[1] - 1\r\n\r\n coordsBboxInt = [round(x) for x in coordsBbox]\r\n\r\n return coordsBboxInt\r\n\r\ndef getLargestAreaEcentroid(img_pred_Log):\r\n # returns mask with the regions with the largest area, coords of centroid and radius\r\n\r\n kernel_ones = np.ones([3,3],np.uint8)\r\n closing_Log = cv2.morphologyEx(img_pred_Log, cv2.MORPH_CLOSE, kernel_ones)\r\n\r\n labelsLog, numLog = label(closing_Log, neighbors=8, background = 0, return_num = True)\r\n regionsLog = regionprops(labelsLog)\r\n\r\n areasLog = [region['area'] for region in regionsLog]\r\n areasLogArr = np.array(areasLog)\r\n maxIndex = np.argmax(areasLogArr)\r\n\r\n value = labelsLog[regionsLog[maxIndex]['coords'][0][0],regionsLog[maxIndex]['coords'][0][1]]\r\n labelsLog[labelsLog != value] = 0\r\n labelsLog[labelsLog == value] = 1\r\n\r\n centreCoords = np.round(regionsLog[maxIndex]['centroid'])\r\n centreCoords = centreCoords.astype(np.uint)\r\n\r\n radius = (regionsLog[maxIndex]['major_axis_length'] + regionsLog[maxIndex]['minor_axis_length']) / 4\r\n colsCoord = [regionsLog[maxIndex]['bbox'][1],regionsLog[maxIndex]['bbox'][3]]\r\n\r\n labelsArr = np.array(labelsLog)\r\n\r\n return labelsArr, centreCoords, radius, colsCoord\r\n\r\n\r\n\r\nimage_arr = np.load('image_arr.npy')\r\nmask_arr = np.load('mask_arr.npy')\r\nimage_arr_red_channels = np.load('image_arr_red_channels.npy')\r\nimage_arr_green_channels = np.load('image_arr_green_channels.npy')\r\nimage_arr_blue_channels = np.load('image_arr_blue_channels.npy')\r\nentropy = np.load('entropy_arr.npy')\r\nelips = np.load('elips_arr.npy')\r\nvessels = np.load('vessels_arr.npy')\r\n\r\n\r\ntest_image = np.zeros(image_arr[0].shape)\r\ntest_image_mask = np.zeros(mask_arr[0].shape)\r\ntest_img_RC = np.zeros(image_arr[0].shape)\r\ntest_img_GC = np.zeros(image_arr[0].shape)\r\ntest_img_BC = np.zeros(image_arr[0].shape)\r\nentropy_arr = np.zeros(image_arr[0].shape)\r\nelips_arr = np.zeros(image_arr[0].shape)\r\n\r\nODROILog = []\r\nODROIBay = []\r\ngetClassifiers = False\r\nif getClassifiers:\r\n X_train = np.zeros([image_arr[0].shape[0]*image_arr[0].shape[1]*40,4])\r\n Y_train = np.zeros([image_arr[0].shape[0]*image_arr[0].shape[1]*40,1])\r\n for j in range(0,40):\r\n\r\n for i in range(0,40): # Get train data\r\n\r\n if i == j:\r\n continue\r\n\r\n test_image = image_arr[i]\r\n test_image_mask = mask_arr[i]\r\n\r\n labels, num = label(test_image_mask, neighbors=8, background = 0, return_num = True)\r\n regions = regionprops(labels)\r\n centreCoords = np.round(regions[0]['centroid'])\r\n centreCoords = centreCoords.astype(np.uint)\r\n\r\n centreMask = np.zeros(test_image_mask.shape)\r\n centreMask[centreCoords[0],centreCoords[1]] = 1\r\n\r\n #Change here!\r\n #test_image_mask = centreMask\r\n\r\n test_image_RC = image_arr_red_channels[i]\r\n test_image_GC = image_arr_green_channels[i]\r\n test_image_BC = image_arr_blue_channels[i]\r\n entropy_arr = entropy[i]\r\n elips_arr = elips[i]\r\n\r\n #test_image_RC = removeBackground(test_image_RC)\r\n #test_image = removeBackground(test_image)\r\n\r\n imageIndxs = np.where(test_image != 0)\r\n\r\n intensityColumn_Arr = np.squeeze(test_image.reshape([1,test_image.shape[0]*test_image.shape[1]])).T\r\n intensityColumn_Arr = (intensityColumn_Arr-np.average(intensityColumn_Arr)) / np.std(intensityColumn_Arr)\r\n redChannel_Arr = np.squeeze(test_image_RC.reshape([1,test_image.shape[0]*test_image.shape[1]])).T\r\n redChannel_Arr = (redChannel_Arr-np.average(redChannel_Arr)) / np.std(redChannel_Arr)\r\n entropy_arr = np.squeeze(entropy_arr.reshape([1,test_image.shape[0]*test_image.shape[1]])).T\r\n #entropy_arr = (entropy_arr-np.average(entropy_arr)) / np.std(entropy_arr)\r\n\r\n # Distance Array\r\n indices_Arr = np.indices((test_image.shape[0],test_image.shape[1])).transpose((1,2,0))\r\n centreCoords = np.array([test_image.shape[0]/2,test_image.shape[1]/2])\r\n distance_Arr = np.sqrt(np.add(np.power(indices_Arr[...,0]-centreCoords[0],2),np.power(indices_Arr[...,1]-centreCoords[1],2)))\r\n normDistance_Arr = distance_Arr / np.max(distance_Arr)\r\n normDistanceColumn_Arr = np.squeeze(normDistance_Arr.reshape([1,normDistance_Arr.shape[0]*normDistance_Arr.shape[1]])).T\r\n\r\n\r\n X_train[i*image_arr[0].shape[0]*image_arr[0].shape[1]:(i+1)*image_arr[0].shape[0]*image_arr[0].shape[1],...] = np.column_stack((redChannel_Arr,entropy_arr,normDistanceColumn_Arr, intensityColumn_Arr))#,\r\n Y_train[i*image_arr[0].shape[0]*image_arr[0].shape[1]:(i+1)*image_arr[0].shape[0]*image_arr[0].shape[1],0] = np.squeeze(test_image_mask.reshape([1,test_image_mask.shape[0]*test_image_mask.shape[1]])).T\r\n\r\n\r\n X_train_2 = X_train\r\n y_train_2 = Y_train\r\n\r\n clf_bayes = GaussianNB()\r\n clf_bayes.fit(X_train_2,y_train_2)\r\n\r\n paramsBayes = clf_bayes.get_params\r\n\r\n # Logistic regression\r\n clf_log = LogisticRegression()\r\n clf_log.fit(X_train_2,y_train_2)\r\n\r\n log = open('Classifiers/Log/LogClf_excluding_' + str(j) + '.pickle', 'wb')\r\n pickle.dump(clf_log, log)\r\n log.close()\r\n\r\n bay = open('Classifiers/Bay/BayClf_excluding_' + str(j) + '.pickle', 'wb')\r\n pickle.dump(clf_bayes, bay)\r\n bay.close()\r\n\r\n '''\r\n f = open('my_classifier.pickle', 'rb')\r\n classifier = pickle.load(f)\r\n f.close()\r\n '''\r\n\r\n test_image2 = np.zeros(image_arr[0].shape)\r\n test_image_mask2 = np.zeros(mask_arr[0].shape)\r\n test_img_RC2 = np.zeros(image_arr[0].shape)\r\n # test_img_GC2 = np.zeros(image_arr[0].shape)\r\n \r\n test_image2 = image_arr[j]\r\n test_image_mask2 = mask_arr[j]\r\n\r\n\r\n test_image_RC2 = image_arr_red_channels[j]\r\n test_image_GC2 = image_arr_green_channels[j]\r\n test_image_BC2 = image_arr_blue_channels[j]\r\n entropy_arr2 = entropy[j]\r\n\r\n intensityColumn_Arr2 = np.squeeze(test_image2.reshape([1,test_image2.shape[0]*test_image2.shape[1]])).T\r\n intensityColumn_Arr2 = (intensityColumn_Arr2-np.average(intensityColumn_Arr2)) / np.std(intensityColumn_Arr2)\r\n redChannel_Arr2 = np.squeeze(test_image_RC2.reshape([1,test_image2.shape[0]*test_image2.shape[1]])).T\r\n redChannel_Arr2 = ( redChannel_Arr2 - np.average(redChannel_Arr2) ) / np.std(redChannel_Arr2)\r\n entropy_arr = np.squeeze(entropy_arr2.reshape([1,test_image.shape[0]*test_image.shape[1]])).T\r\n\r\n X_val = np.column_stack((redChannel_Arr2,entropy_arr,normDistanceColumn_Arr,intensityColumn_Arr2))#,,greenChannel_Arr2))\r\n Y_val = np.squeeze(test_image_mask2.reshape([1,test_image_mask2.shape[0]*test_image_mask2.shape[1]])).T\r\n\r\n\r\n # predicts\r\n predictsBayes = clf_bayes.predict(X_val)\r\n predictsLog = clf_log.predict(X_val)\r\n\r\n img_pred_Log = predictsLog.reshape([test_image.shape[0],test_image.shape[1]])\r\n img_pred_Bayes = predictsBayes.reshape([test_image.shape[0],test_image.shape[1]])\r\n\r\n # Y_train_reshaped = Y_train.reshape([test_image.shape[0],test_image.shape[1]])\r\n\r\n #myShowImage(img_pred_Log,\"img_pred_Log_\" + str(j))\r\n #myShowImage(img_pred_Bayes,\"img_pred_Bayes_\" + str(j))\r\n\r\n try:\r\n coordsBBLog = newBBcoords(img_pred_Log,test_image)\r\n except:\r\n coordsBBLog = []\r\n\r\n try:\r\n coordsBBBay = newBBcoords(img_pred_Bayes,test_image)\r\n except:\r\n coordsBBBay = []\r\n\r\n ODROILog.append(coordsBBLog)\r\n ODROIBay.append(coordsBBBay)\r\n\r\n ODROILog_Arr = np.array(ODROILog)\r\n ODROIBay_Arr = np.array(ODROIBay)\r\n\r\n np.save('ODROILog_Arr.npy',ODROILog_Arr)\r\n np.save('ODROIBay_Arr.npy',ODROIBay_Arr)\r\n\r\nprepareSegments = False\r\n\r\nif prepareSegments:\r\n ODROILog_Arr = np.load('ODROILog_Arr.npy')\r\n ODROIBay_Arr = np.load('ODROIBay_Arr.npy')\r\n OD_section = []\r\n OD_mask = []\r\n OD_section_RC = []\r\n\r\n lenX_Arr = 0\r\n\r\n for i in range(0,40):\r\n try:\r\n coords = ODROILog_Arr[i]\r\n #myShowImage(image_arr[i][coords[0]:coords[2],coords[1]:coords[3]],\"LOG\" +str(i))\r\n\r\n segMask = np.array(mask_arr[i][coords[0]:coords[2],coords[1]:coords[3]])\r\n segRC = np.array(image_arr_red_channels[i][coords[0]:coords[2],coords[1]:coords[3]])\r\n\r\n imgSegment = np.array(image_arr[i][coords[0]:coords[2],coords[1]:coords[3]])\r\n vesslesSeg = np.array(vessels[i][coords[0]:coords[2],coords[1]:coords[3]])\r\n\r\n kernel_ones = np.ones([3,3],np.uint8)\r\n vesslesSeg = cv2.morphologyEx(vesslesSeg, cv2.MORPH_DILATE, kernel_ones)\r\n\r\n indxsVesl = np.where(vesslesSeg != 0)\r\n\r\n medianFiltered = median(imgSegment,disk(25))\r\n maxFiltered = maximum_filter(imgSegment, size=15)\r\n smoothVessels = np.copy(imgSegment)\r\n smoothVessels[indxsVesl[0],indxsVesl[1]] = np.multiply(maxFiltered[indxsVesl[0],indxsVesl[1]],0.97)\r\n #smoothDisk = mean(smoothVessels, disk(5)) \r\n\r\n OD_section.append(smoothVessels)\r\n OD_mask.append(segMask)\r\n OD_section_RC.append(segRC)\r\n lenX_Arr = lenX_Arr + (imgSegment.shape[0]*imgSegment.shape[1]) \r\n\r\n #coords = ODROIBay_Arr[i]\r\n #myShowImage(image_arr[i][coords[0]:coords[2],coords[1]:coords[3]],\"BAY\" + str(i))\r\n except:\r\n coords = ODROIBay_Arr[i]\r\n\r\n segMask = np.array(mask_arr[i][coords[0]:coords[2],coords[1]:coords[3]])\r\n segRC = np.array(image_arr_red_channels[i][coords[0]:coords[2],coords[1]:coords[3]])\r\n\r\n imgSegment = np.array(image_arr[i][coords[0]:coords[2],coords[1]:coords[3]])\r\n vesslesSeg = np.array(vessels[i][coords[0]:coords[2],coords[1]:coords[3]])\r\n\r\n kernel_ones = np.ones([3,3],np.uint8)\r\n vesslesSeg = cv2.morphologyEx(vesslesSeg, cv2.MORPH_DILATE, kernel_ones)\r\n\r\n indxsVesl = np.where(vesslesSeg != 0)\r\n\r\n #medianFiltered = median(imgSegment,disk(25))\r\n maxFiltered = maximum_filter(imgSegment, size=15)\r\n smoothVessels = np.copy(imgSegment)\r\n smoothVessels[indxsVesl[0],indxsVesl[1]] = np.multiply(maxFiltered[indxsVesl[0],indxsVesl[1]],0.97)\r\n\r\n #myShowImage(image_arr[i][coords[0]:coords[2],coords[1]:coords[3]],\"EXCEPT\" + str(i))\r\n OD_section.append(smoothVessels)\r\n OD_mask.append(segMask)\r\n OD_section_RC.append(segRC)\r\n #print('except')\r\n lenX_Arr = lenX_Arr + (imgSegment.shape[0]*imgSegment.shape[1]) \r\n\r\n #myShowImage(smoothVessels)\r\n\r\n OD_section_Arr = np.array(OD_section)\r\n OD_mask_Arr = np.array(OD_mask)\r\n OD_section_RC = np.array(OD_section_RC)\r\n\r\n np.save('OD_section_Arr.npy',OD_section_Arr)\r\n np.save('OD_mask_Arr.npy',OD_mask_Arr)\r\n np.save('OD_section_RC.npy',OD_section_RC)\r\n\r\n print(lenX_Arr) # len = 4577126\r\n\r\nfinalSegmentation = False\r\n\r\nfinalMaskPredicts = []\r\n\r\nif finalSegmentation:\r\n\r\n OD_section_Arr = np.load('OD_section_Arr.npy')\r\n OD_mask_Arr = np.load('OD_mask_Arr.npy')\r\n OD_section_RC = np.load('OD_section_RC.npy')\r\n\r\n clahe = cv2.createCLAHE(clipLimit=1, tileGridSize=(8, 8))\r\n \r\n for j in range(0,40):\r\n\r\n removeLen = OD_section_Arr[j].shape[0] * OD_section_Arr[j].shape[1]\r\n X_train = np.zeros([4577126-removeLen,2])\r\n Y_train = np.zeros([4577126-removeLen,1])\r\n \r\n for i in range(0,40):\r\n\r\n if i == j:\r\n continue\r\n\r\n test_image = OD_section_Arr[i]\r\n test_image_mask = OD_mask_Arr[i]\r\n segRC = OD_section_RC[i]\r\n clahePrep = np.multiply(np.copy(test_image),255)\r\n clahePrep = clahePrep.astype(np.uint8)\r\n highContrast = clahe.apply(clahePrep)\r\n\r\n intensityColumn_Arr = np.squeeze(test_image.reshape([1,test_image.shape[0]*test_image.shape[1]])).T\r\n intensityColumn_Arr = (intensityColumn_Arr-np.average(intensityColumn_Arr)) / np.std(intensityColumn_Arr)\r\n segRC = np.squeeze(segRC.reshape([1,test_image.shape[0]*test_image.shape[1]])).T\r\n #segRC = (segRC-np.average(segRC)) / np.std(segRC)\r\n\r\n if (i-1)*test_image.shape[0]*test_image.shape[1] < 0 and (i)*test_image.shape[0]*test_image.shape[1] == 0:\r\n X_train[(i-1)*test_image.shape[0]*test_image.shape[1]::,...] = np.column_stack((intensityColumn_Arr,segRC))#,\r\n Y_train[(i-1)*test_image.shape[0]*test_image.shape[1]::,0] = np.squeeze(test_image_mask.reshape([1,test_image_mask.shape[0]*test_image_mask.shape[1]])).T\r\n continue\r\n\r\n X_train[(i-1)*test_image.shape[0]*test_image.shape[1]:(i)*test_image.shape[0]*test_image.shape[1],...] = np.column_stack((intensityColumn_Arr,segRC))#,\r\n Y_train[(i-1)*test_image.shape[0]*test_image.shape[1]:(i)*test_image.shape[0]*test_image.shape[1],0] = np.squeeze(test_image_mask.reshape([1,test_image_mask.shape[0]*test_image_mask.shape[1]])).T\r\n\r\n X_train_2 = X_train\r\n y_train_2 = Y_train\r\n\r\n clf_bayes = GaussianNB()\r\n clf_bayes.fit(X_train_2,y_train_2)\r\n\r\n paramsBayes = clf_bayes.get_params\r\n\r\n # Logistic regression\r\n clf_log = LogisticRegression()\r\n clf_log.fit(X_train_2,y_train_2)\r\n\r\n log = open('Classifiers/Segments/Log/LogClf_excluding_' + str(j) + '.pickle', 'wb')\r\n pickle.dump(clf_log, log)\r\n log.close()\r\n\r\n bay = open('Classifiers/Segments/Bay/BayClf_excluding_' + str(j) + '.pickle', 'wb')\r\n pickle.dump(clf_bayes, bay)\r\n bay.close()\r\n\r\n test_image = OD_section_Arr[j]\r\n test_image_mask = OD_mask_Arr[j]\r\n segRC = OD_section_RC[j]\r\n clahePrep = np.multiply(np.copy(test_image),255)\r\n clahePrep = clahePrep.astype(np.uint8)\r\n highContrast = clahe.apply(clahePrep)\r\n\r\n intensityColumn_Arr = np.squeeze(test_image.reshape([1,test_image.shape[0]*test_image.shape[1]])).T\r\n intensityColumn_Arr = (intensityColumn_Arr-np.average(intensityColumn_Arr)) / np.std(intensityColumn_Arr)\r\n segRC = np.squeeze(segRC.reshape([1,test_image.shape[0]*test_image.shape[1]])).T\r\n #segRC = (segRC-np.average(segRC)) / np.std(segRC)\r\n\r\n X_val = np.column_stack((intensityColumn_Arr,segRC))\r\n\r\n predictsBayes = clf_bayes.predict(X_val)\r\n predictsLog = clf_log.predict(X_val)\r\n\r\n img_pred_Log = predictsLog.reshape([test_image.shape[0],test_image.shape[1]])\r\n img_pred_Bayes = predictsBayes.reshape([test_image.shape[0],test_image.shape[1]])\r\n\r\n #myShowImage(img_pred_Log,\"Log\")\r\n #myShowImage(img_pred_Bayes,\"Bayes\")\r\n #myShowImage(test_image,\"Actual\")\r\n\r\n finalMaskPredicts.append(predictsBayes)\r\n\r\n #print('ok')\r\n\r\n finalMaskPredicts_Arr = np.array(finalMaskPredicts)\r\n np.save(\"finalMaskPredicts_Bayes.npy\",finalMaskPredicts_Arr)\r\n\r\nloadFinalSegs = False\r\n\r\nif loadFinalSegs:\r\n foveaBBoxCoords = []\r\n centroidCoord = []\r\n ODmaskPredicts = []\r\n elips = np.load('elips_arr.npy')\r\n originalDimsBase = np.zeros(image_arr[0].shape)\r\n OD_section_Arr = np.load('OD_section_Arr.npy')\r\n finalMaskPredicts_Arr = np.load(\"finalMaskPredicts_Bayes.npy\")\r\n ODROILog_Arr = np.load('ODROILog_Arr.npy')\r\n ODROIBay_Arr = np.load('ODROIBay_Arr.npy')\r\n for i in range(0,40):\r\n originalDims = np.copy(originalDimsBase)\r\n test_image = OD_section_Arr[i]\r\n maskPred = finalMaskPredicts_Arr[i].reshape([test_image.shape[0],test_image.shape[1]])\r\n finalMask, centroidCoords, radius, colsCoord = getLargestAreaEcentroid(maskPred)\r\n finalMaskImg = np.multiply(finalMask,255)\r\n finalMaskImg[centroidCoords[0],centroidCoords[1]] = 255\r\n\r\n try:\r\n coords = ODROILog_Arr[i]\r\n failTest = (coords[2])\r\n except:\r\n coords = ODROIBay_Arr[i]\r\n failTest = (coords[2])\r\n\r\n coordsReal =[centroidCoords[0] + coords[0],centroidCoords[1] + coords[1]] \r\n colsCoordReal = [colsCoord[0] + coords[1],colsCoord[1] + coords[1]]\r\n\r\n originalDims[coords[0]:coords[2],coords[1]:coords[3]] = finalMaskImg\r\n #originalDims = originalDims or elips[i]\r\n\r\n elipsResized = cv2.resize(elips[i], dsize=(originalDims.shape[1],originalDims.shape[0]), interpolation=cv2.INTER_CUBIC)\r\n elipsResized = np.average(elipsResized,axis = 2) # 3 channels -> 1 channel\r\n elipsResized[elipsResized>0.5] = 1\r\n elipsResized[elipsResized<1] = 0\r\n\r\n elipsResized = thin(elipsResized)\r\n\r\n elipsIndexs = np.where(elipsResized != 0)\r\n\r\n\r\n originalDims = originalDims.astype(np.uint8)\r\n #originalDims[elipsIndexs] = 255\r\n indexsOD_ELi = np.where(originalDims != 0)\r\n #myShowImage(originalDims,str(i))\r\n\r\n checkResults = np.copy(image_arr[i])\r\n checkResults[indexsOD_ELi] = originalDims[indexsOD_ELi]\r\n #checkResults[0::,np.min(elipsIndexs[1])] = 255 # left\r\n #checkResults[0::,np.max(elipsIndexs[1])] = 255 # right\r\n\r\n if abs(coordsReal[1]-np.min(elipsIndexs[1])) < abs(coordsReal[1]-np.max(elipsIndexs[1])):\r\n #isleft -> walk right\r\n #relevantColumn = coordsReal[1] + 30 # based on centroid\r\n relevantColumn = colsCoordReal[1] - 10 # based on \r\n columnROI_f = [coordsReal[1] + round(3*radius),coordsReal[1] + round(6*radius)]\r\n\r\n else:\r\n #isright -> walk left\r\n #relevantColumn = coordsReal[1] - 30\r\n relevantColumn = colsCoordReal[0] + 10\r\n columnROI_f = [coordsReal[1] - round(6*radius),coordsReal[1] - round(3*radius)]\r\n\r\n relevantRows = np.where(elipsResized[...,relevantColumn]!=0)\r\n\r\n checkResults[relevantRows[0][0]:relevantRows[0][-1],columnROI_f[0]] = 0 # 1 - columnROI_f[0]\r\n checkResults[relevantRows[0][0]:relevantRows[0][-1],columnROI_f[1]] = 0 # 3 - columnROI_f[1]\r\n checkResults[relevantRows[0][0],columnROI_f[0]:columnROI_f[1]] = 0 # 0 - relevantRows[0][0]\r\n checkResults[relevantRows[0][-1],columnROI_f[0]:columnROI_f[1]] = 0 # 2 - relevantRows[0][-1]\r\n\r\n foveaBBoxCoords.append((relevantRows[0][0],columnROI_f[0],relevantRows[0][-1],columnROI_f[1]))\r\n centroidCoord.append(coordsReal)\r\n originalDims = np.divide(originalDims,255)\r\n ODmaskPredicts.append(originalDims)\r\n\r\n #myShowImage(originalDims,str(i))\r\n #myShowImage(checkResults,str(i))\r\n\r\n foveaBBoxCoords_Arr = np.array(foveaBBoxCoords)\r\n centroidCoord_Arr = np.array(centroidCoord)\r\n ODmaskPredicts_Arr = np.array(ODmaskPredicts)\r\n \r\n np.save(\"bbox_fovea.npy\",foveaBBoxCoords_Arr)\r\n np.save(\"centroidCoord_Arr.npy\",centroidCoord_Arr)\r\n np.save(\"ODmaskPredicts_Arr.npy\",ODmaskPredicts_Arr)\r\n \r\ngetFoveaGTCoords = True\r\n\r\nif getFoveaGTCoords:\r\n \r\n foveCoordsGT = []\r\n tempCoords =[]\r\n imgNo = 0\r\n\r\n with open('Datasets/fovea_location.csv') as f:\r\n reader = csv.reader(f)\r\n next(reader)\r\n for row in reader:\r\n #print(row)\r\n tempCoords.append(float(row[1]))\r\n tempCoords.append(float(row[2]))\r\n foveCoordsGT.append(tempCoords)\r\n tempCoords =[]\r\n imgNo += 1\r\n if imgNo == 40:\r\n break\r\n \r\ngetFoveaCoordsPred = False\r\n\r\n'''for i in range(0,40):\r\n\r\n myShowImage(image_arr[i])\r\n myShowImage(image_arr_red_channels[i])\r\n myShowImage(image_arr_green_channels[i])\r\n myShowImage(vessels[i])\r\n myShowImage(entropy_arr[i])'''\r\n\r\nif getFoveaCoordsPred:\r\n\r\n foveaBBoxCoords_Arr = np.load(\"bbox_fovea.npy\")\r\n foveaBBoxCoords_Arr = np.absolute(foveaBBoxCoords_Arr)\r\n removeLen = 0\r\n realCentroidCoords_Arr = []\r\n clahe = cv2.createCLAHE(clipLimit=1, tileGridSize=(8, 8))\r\n\r\n for i in range(0,40): # not the best way...\r\n\r\n if foveaBBoxCoords_Arr[i][3] < foveaBBoxCoords_Arr[i][1]:\r\n temp = foveaBBoxCoords_Arr[i][1]\r\n foveaBBoxCoords_Arr[i][1] = foveaBBoxCoords_Arr[i][3]\r\n foveaBBoxCoords_Arr[i][3] = temp\r\n \r\n if foveaBBoxCoords_Arr[i][2] < foveaBBoxCoords_Arr[i][0]:\r\n temp = foveaBBoxCoords_Arr[i][0]\r\n foveaBBoxCoords_Arr[i][0] = foveaBBoxCoords_Arr[i][2]\r\n foveaBBoxCoords_Arr[i][2] = temp\r\n\r\n test_image = image_arr[i]\r\n\r\n fovea_region = test_image[foveaBBoxCoords_Arr[i][0]:foveaBBoxCoords_Arr[i][2],foveaBBoxCoords_Arr[i][1]:foveaBBoxCoords_Arr[i][3]] \r\n bboxShape = fovea_region.shape\r\n\r\n removeLen += bboxShape[0]*bboxShape[1] \r\n\r\n #print(removeLen)\r\n\r\n for j in range(0,40):\r\n\r\n removeLen = (foveaBBoxCoords_Arr[j][2]-foveaBBoxCoords_Arr[j][0]) * (foveaBBoxCoords_Arr[j][3]-foveaBBoxCoords_Arr[j][1]) \r\n X_train = np.zeros([3187816-removeLen,3]) # 3187816 = number of points in all fovea bboxs\r\n Y_train = np.zeros([3187816-removeLen,1])\r\n \r\n first = 0\r\n\r\n for i in range(0,40):\r\n\r\n if i == j:\r\n continue\r\n\r\n '''if foveaBBoxCoords_Arr[i][3] < foveaBBoxCoords_Arr[i][1]:\r\n temp = foveaBBoxCoords_Arr[i][1]\r\n foveaBBoxCoords_Arr[i][1] = foveaBBoxCoords_Arr[i][3]\r\n foveaBBoxCoords_Arr[i][3] = temp\r\n \r\n if foveaBBoxCoords_Arr[i][2] < foveaBBoxCoords_Arr[i][0]:\r\n temp = foveaBBoxCoords_Arr[i][0]\r\n foveaBBoxCoords_Arr[i][0] = foveaBBoxCoords_Arr[i][2]\r\n foveaBBoxCoords_Arr[i][2] = temp'''\r\n \r\n test_image = image_arr[i]\r\n\r\n fovea_region = test_image[foveaBBoxCoords_Arr[i][0]:foveaBBoxCoords_Arr[i][2],foveaBBoxCoords_Arr[i][1]:foveaBBoxCoords_Arr[i][3]] \r\n bboxShape = fovea_region.shape\r\n last = bboxShape[0]*bboxShape[1] + first\r\n foveaRegionGC = image_arr_green_channels[i][foveaBBoxCoords_Arr[i][0]:foveaBBoxCoords_Arr[i][2],foveaBBoxCoords_Arr[i][1]:foveaBBoxCoords_Arr[i][3]]\r\n\r\n clahePrep = np.multiply(np.copy(foveaRegionGC),255)\r\n clahePrep = clahePrep.astype(np.uint8)\r\n highContrast = clahe.apply(clahePrep)\r\n\r\n #mask\r\n maskBig = np.zeros(test_image.shape)\r\n coordsFoveaCenter = [round(foveCoordsGT[i][1]/4),round(foveCoordsGT[i][0]/4)]\r\n maskBig[coordsFoveaCenter[0]-10:coordsFoveaCenter[0]+10,coordsFoveaCenter[1]-10:coordsFoveaCenter[1]+10] = 1\r\n mask = maskBig[foveaBBoxCoords_Arr[i][0]:foveaBBoxCoords_Arr[i][2],foveaBBoxCoords_Arr[i][1]:foveaBBoxCoords_Arr[i][3]]\r\n\r\n fovea_region = np.squeeze(fovea_region.reshape([1,bboxShape[0]*bboxShape[1]])).T\r\n fovea_region = (fovea_region-np.average(fovea_region)) / np.std(fovea_region)\r\n\r\n foveaRegionGC = np.squeeze(foveaRegionGC.reshape([1,bboxShape[0]*bboxShape[1]])).T\r\n foveaRegionGC = (foveaRegionGC-np.average(foveaRegionGC)) / np.std(foveaRegionGC)\r\n\r\n highContrast = np.squeeze(highContrast.reshape([1,bboxShape[0]*bboxShape[1]])).T\r\n highContrast = (highContrast-np.average(highContrast)) / np.std(highContrast)\r\n\r\n '''if (i-1)*bboxShape[0]*bboxShape[1] < 0 and (i)*bboxShape[0]*bboxShape[1] == 0:\r\n X_train[(i-1)*bboxShape[0]*bboxShape[1]::,...] = np.column_stack((fovea_region,foveaRegionGC,highContrast))#,\r\n Y_train[(i-1)*bboxShape[0]*bboxShape[1]::,0] = np.squeeze(mask.reshape([1,bboxShape[0]*bboxShape[1]])).T\r\n continue'''\r\n\r\n X_train[first:last,...] = np.column_stack((fovea_region,foveaRegionGC,highContrast))#,\r\n Y_train[first:last,0] = np.squeeze(mask.reshape([1,bboxShape[0]*bboxShape[1]])).T\r\n\r\n first = last\r\n\r\n X_train_2 = X_train\r\n y_train_2 = Y_train\r\n\r\n clf_bayes = GaussianNB()\r\n clf_bayes.fit(X_train_2,y_train_2)\r\n\r\n paramsBayes = clf_bayes.get_params\r\n\r\n # Logistic regression\r\n clf_log = LogisticRegression()\r\n clf_log.fit(X_train_2,y_train_2)\r\n\r\n '''log = open('Classifiers/Segments/Log/LogClf_excluding_' + str(j) + '.pickle', 'wb')\r\n pickle.dump(clf_log, log)\r\n log.close()\r\n\r\n bay = open('Classifiers/Segments/Bay/BayClf_excluding_' + str(j) + '.pickle', 'wb')\r\n pickle.dump(clf_bayes, bay)\r\n bay.close()'''\r\n\r\n test_image = image_arr[j]\r\n\r\n fovea_region = test_image[foveaBBoxCoords_Arr[j][0]:foveaBBoxCoords_Arr[j][2],foveaBBoxCoords_Arr[j][1]:foveaBBoxCoords_Arr[j][3]] \r\n bboxShape = fovea_region.shape\r\n \r\n foveaRegionGC = image_arr_green_channels[j][foveaBBoxCoords_Arr[j][0]:foveaBBoxCoords_Arr[j][2],foveaBBoxCoords_Arr[j][1]:foveaBBoxCoords_Arr[j][3]]\r\n\r\n clahePrep = np.multiply(np.copy(foveaRegionGC),255)\r\n clahePrep = clahePrep.astype(np.uint8)\r\n highContrast = clahe.apply(clahePrep)\r\n\r\n fovea_region = np.squeeze(fovea_region.reshape([1,bboxShape[0]*bboxShape[1]])).T\r\n fovea_region = (fovea_region-np.average(fovea_region)) / np.std(fovea_region)\r\n\r\n foveaRegionGC = np.squeeze(foveaRegionGC.reshape([1,bboxShape[0]*bboxShape[1]])).T\r\n foveaRegionGC = (foveaRegionGC-np.average(foveaRegionGC)) / np.std(foveaRegionGC)\r\n\r\n highContrast = np.squeeze(highContrast.reshape([1,bboxShape[0]*bboxShape[1]])).T\r\n highContrast = (highContrast-np.average(highContrast)) / np.std(highContrast)\r\n\r\n X_val = np.column_stack((fovea_region,foveaRegionGC,highContrast))\r\n\r\n predictsBayes = clf_bayes.predict(X_val)\r\n predictsLog = clf_log.predict(X_val)\r\n\r\n img_pred_Log = predictsLog.reshape(bboxShape)\r\n img_pred_Bayes = predictsBayes.reshape(bboxShape)\r\n\r\n try:\r\n finalMask, centroidCoords, radius, colsCoord = getLargestAreaEcentroid(img_pred_Bayes)\r\n if centroidCoords.size == 0:\r\n finalMask = np.zeros(img_pred_Bayes.shape)\r\n finalMask[round(finalMask.shape[0]/2),round(finalMask.shape[1]/2)] = 1\r\n centroidCoords = np.array([round(finalMask.shape[0]/2),round(finalMask.shape[1]/2)])\r\n\r\n except:\r\n finalMask = np.zeros(img_pred_Bayes.shape)\r\n finalMask[round(finalMask.shape[0]/2),round(finalMask.shape[1]/2)] = 1\r\n centroidCoords = np.array([round(finalMask.shape[0]/2),round(finalMask.shape[1]/2)])\r\n\r\n maskEyes = np.copy(finalMask)\r\n maskEyes = np.multiply(maskEyes,255)\r\n maskEyes = maskEyes.astype(np.uint8) \r\n #myShowImage(test_image[foveaBBoxCoords_Arr[j][0]:foveaBBoxCoords_Arr[j][2],foveaBBoxCoords_Arr[j][1]:foveaBBoxCoords_Arr[j][3]],\"fovea\")\r\n #myShowImage(maskEyes,\"Mask\")\r\n #myShowImage(img_pred_Bayes,\"Bay\") \r\n\r\n realCentroidCoords = [centroidCoords[0] + foveaBBoxCoords_Arr[j][0],centroidCoords[1] + foveaBBoxCoords_Arr[j][1]]\r\n\r\n realCentroidCoords_Arr.append(realCentroidCoords)\r\n\r\n realCentroidCoords_Arr = np.array(realCentroidCoords_Arr)\r\n np.save('fovea_centre_coords.npy',realCentroidCoords_Arr)\r\n\r\n \r\n\r\n #centroidCoord_Arr = np.load(\"centroidCoord_Arr.npy\")\r\n #ODmaskPredicts_Arr = np.load(\"ODmaskPredicts_Arr.npy\")\r\n\r\n #for i in range(0,40):\r\n \r\n\r\n\r\n\r\n\r\nshowGraphsClass= False\r\nif showGraphsClass:\r\n\r\n import matplotlib.pyplot as plt\r\n from sklearn import svm, datasets\r\n\r\n def make_meshgrid(x, y, h=.02):\r\n \"\"\"Create a mesh of points to plot in\r\n\r\n Parameters\r\n ----------\r\n x: data to base x-axis meshgrid on\r\n y: data to base y-axis meshgrid on\r\n h: stepsize for meshgrid, optional\r\n\r\n Returns\r\n -------\r\n xx, yy : ndarray\r\n \"\"\"\r\n x_min, x_max = x.min() - 1, x.max() + 1\r\n y_min, y_max = y.min() - 1, y.max() + 1\r\n xx, yy = np.meshgrid(np.arange(x_min, x_max, h),\r\n np.arange(y_min, y_max, h))\r\n return xx, yy\r\n\r\n\r\n def plot_contours(ax, clf, xx, yy, proba=False, **params):\r\n \"\"\"Plot the decision boundaries for a classifier.\r\n\r\n Parameters\r\n ----------\r\n ax: matplotlib axes object\r\n clf: a classifier\r\n xx: meshgrid ndarray\r\n yy: meshgrid ndarray\r\n params: dictionary of params to pass to contourf, optional\r\n \"\"\"\r\n if proba:\r\n Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:,-1]\r\n else:\r\n Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) \r\n Z = Z.reshape(xx.shape)\r\n out = ax.contourf(xx, yy, Z,20, **params)\r\n return out\r\n\r\n ## import some data to play with\r\n #iris = datasets.load_iris()\r\n ## Take the first two features. We could avoid this by using a two-dim dataset\r\n #X = iris.data[:, :2]\r\n #y = iris.target\r\n\r\n X = X_train_2\r\n y = y_train_2\r\n\r\n # we create an instance of SVM and fit out data. We do not scale our\r\n # data since we want to plot the support vectors\r\n models = (clf_bayes, clf_log) #, clf_svm, clf_svm_rbf)\r\n\r\n # title for the plots\r\n titles = ('Bayes',\r\n 'Logistic regression')\r\n ''' ,\r\n 'SVC with linear kernel',\r\n 'SVM with RBF kernel')'''\r\n\r\n # Set-up 2x2 grid for plotting.\r\n #fig, sub = \r\n #plt.subplots_adjust(wspace=0.4, hspace=0.4)\r\n\r\n X0, X1 = X[0::500, 0], X[0::500, 1]\r\n xx, yy = make_meshgrid(X0, X1,h=0.005)\r\n\r\n '''_,ax_all = plt.subplots(1,2)\r\n ax = ax_all[1]\r\n plot_contours(ax, clf_bayes, xx, yy,\r\n cmap=plt.cm.coolwarm, alpha=0.8)\r\n ax.scatter(X0, X1, c=y[0::500], cmap=plt.cm.coolwarm, s=20)\r\n ax.set_xlim(X0.min(), X0.max())\r\n ax.set_ylim(X1.min(), X1.max())\r\n ax.set_xlabel('Distance')\r\n ax.set_ylabel('Intensity')\r\n ax.set_xticks(())\r\n ax.set_yticks(())\r\n ax.set_title(\"Bayes\")\r\n\r\n plt.show()'''\r\n showPlots = False\r\n\r\n if showPlots:\r\n\r\n for clf, title in zip(models, titles):\r\n _,ax_all = plt.subplots(1,2)\r\n \r\n \r\n ax = ax_all[0]\r\n plot_contours(ax, clf, xx, yy, proba=True, # changed proba to probability\r\n cmap=plt.cm.coolwarm, alpha=0.8)\r\n ax.scatter(X0, X1, c=y[0::500], cmap=plt.cm.coolwarm, s=20)\r\n ax.set_xlim(X0.min(), X0.max())\r\n ax.set_ylim(X1.min(), X1.max())\r\n ax.set_xlabel('Distance')\r\n ax.set_ylabel('Intensity')\r\n ax.set_xticks(())\r\n ax.set_yticks(())\r\n ax.set_title(title)\r\n\r\n ax = ax_all[1]\r\n plot_contours(ax, clf, xx, yy,\r\n cmap=plt.cm.coolwarm, alpha=0.8)\r\n ax.scatter(X0, X1, c=y[0::500], cmap=plt.cm.coolwarm, s=20)\r\n ax.set_xlim(X0.min(), X0.max())\r\n ax.set_ylim(X1.min(), X1.max())\r\n ax.set_xlabel('Distance')\r\n ax.set_ylabel('Intensity')\r\n ax.set_xticks(())\r\n ax.set_yticks(())\r\n ax.set_title(title)\r\n \r\n plt.show()\r\n\r\n\r\nprint(\"Done\")"
] |
[
[
"numpy.round",
"numpy.max",
"numpy.where",
"numpy.divide",
"numpy.arange",
"numpy.save",
"numpy.copy",
"numpy.argmax",
"numpy.std",
"numpy.column_stack",
"numpy.load",
"numpy.zeros",
"sklearn.naive_bayes.GaussianNB",
"numpy.multiply",
"numpy.power",
"numpy.min",
"matplotlib.pyplot.show",
"numpy.array",
"numpy.absolute",
"sklearn.linear_model.LogisticRegression",
"matplotlib.pyplot.subplots",
"numpy.indices",
"numpy.ones",
"numpy.average"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mendesmiguel/keras
|
[
"bf1378f39d02b7d0b53ece5458f9275ac8208046"
] |
[
"keras/preprocessing/image.py"
] |
[
"\"\"\"Fairly basic set of tools for real-time data augmentation on image data.\n\nCan easily be extended to include new transformations,\nnew preprocessing methods, etc...\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport re\nfrom scipy import linalg\nimport scipy.ndimage as ndi\nfrom six.moves import range\nimport os\nimport threading\nimport warnings\nimport multiprocessing.pool\nfrom functools import partial\n\nfrom .. import backend as K\nfrom ..utils.data_utils import Sequence\n\ntry:\n from PIL import ImageEnhance\n from PIL import Image as pil_image\nexcept ImportError:\n pil_image = None\n\nif pil_image is not None:\n _PIL_INTERPOLATION_METHODS = {\n 'nearest': pil_image.NEAREST,\n 'bilinear': pil_image.BILINEAR,\n 'bicubic': pil_image.BICUBIC,\n }\n # These methods were only introduced in version 3.4.0 (2016).\n if hasattr(pil_image, 'HAMMING'):\n _PIL_INTERPOLATION_METHODS['hamming'] = pil_image.HAMMING\n if hasattr(pil_image, 'BOX'):\n _PIL_INTERPOLATION_METHODS['box'] = pil_image.BOX\n # This method is new in version 1.1.3 (2013).\n if hasattr(pil_image, 'LANCZOS'):\n _PIL_INTERPOLATION_METHODS['lanczos'] = pil_image.LANCZOS\n\n\ndef random_rotation(x, rg, row_axis=1, col_axis=2, channel_axis=0,\n fill_mode='nearest', cval=0.):\n \"\"\"Performs a random rotation of a Numpy image tensor.\n\n # Arguments\n x: Input tensor. Must be 3D.\n rg: Rotation range, in degrees.\n row_axis: Index of axis for rows in the input tensor.\n col_axis: Index of axis for columns in the input tensor.\n channel_axis: Index of axis for channels in the input tensor.\n fill_mode: Points outside the boundaries of the input\n are filled according to the given mode\n (one of `{'constant', 'nearest', 'reflect', 'wrap'}`).\n cval: Value used for points outside the boundaries\n of the input if `mode='constant'`.\n\n # Returns\n Rotated Numpy image tensor.\n \"\"\"\n theta = np.deg2rad(np.random.uniform(-rg, rg))\n rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), 0],\n [np.sin(theta), np.cos(theta), 0],\n [0, 0, 1]])\n\n h, w = x.shape[row_axis], x.shape[col_axis]\n transform_matrix = transform_matrix_offset_center(rotation_matrix, h, w)\n x = apply_transform(x, transform_matrix, channel_axis, fill_mode, cval)\n return x\n\n\ndef random_shift(x, wrg, hrg, row_axis=1, col_axis=2, channel_axis=0,\n fill_mode='nearest', cval=0.):\n \"\"\"Performs a random spatial shift of a Numpy image tensor.\n\n # Arguments\n x: Input tensor. Must be 3D.\n wrg: Width shift range, as a float fraction of the width.\n hrg: Height shift range, as a float fraction of the height.\n row_axis: Index of axis for rows in the input tensor.\n col_axis: Index of axis for columns in the input tensor.\n channel_axis: Index of axis for channels in the input tensor.\n fill_mode: Points outside the boundaries of the input\n are filled according to the given mode\n (one of `{'constant', 'nearest', 'reflect', 'wrap'}`).\n cval: Value used for points outside the boundaries\n of the input if `mode='constant'`.\n\n # Returns\n Shifted Numpy image tensor.\n \"\"\"\n h, w = x.shape[row_axis], x.shape[col_axis]\n tx = np.random.uniform(-hrg, hrg) * h\n ty = np.random.uniform(-wrg, wrg) * w\n translation_matrix = np.array([[1, 0, tx],\n [0, 1, ty],\n [0, 0, 1]])\n\n transform_matrix = translation_matrix # no need to do offset\n x = apply_transform(x, transform_matrix, channel_axis, fill_mode, cval)\n return x\n\n\ndef random_shear(x, intensity, row_axis=1, col_axis=2, channel_axis=0,\n fill_mode='nearest', cval=0.):\n \"\"\"Performs a random spatial shear of a Numpy image tensor.\n\n # Arguments\n x: Input tensor. Must be 3D.\n intensity: Transformation intensity in degrees.\n row_axis: Index of axis for rows in the input tensor.\n col_axis: Index of axis for columns in the input tensor.\n channel_axis: Index of axis for channels in the input tensor.\n fill_mode: Points outside the boundaries of the input\n are filled according to the given mode\n (one of `{'constant', 'nearest', 'reflect', 'wrap'}`).\n cval: Value used for points outside the boundaries\n of the input if `mode='constant'`.\n\n # Returns\n Sheared Numpy image tensor.\n \"\"\"\n shear = np.deg2rad(np.random.uniform(-intensity, intensity))\n shear_matrix = np.array([[1, -np.sin(shear), 0],\n [0, np.cos(shear), 0],\n [0, 0, 1]])\n\n h, w = x.shape[row_axis], x.shape[col_axis]\n transform_matrix = transform_matrix_offset_center(shear_matrix, h, w)\n x = apply_transform(x, transform_matrix, channel_axis, fill_mode, cval)\n return x\n\n\ndef random_zoom(x, zoom_range, row_axis=1, col_axis=2, channel_axis=0,\n fill_mode='nearest', cval=0.):\n \"\"\"Performs a random spatial zoom of a Numpy image tensor.\n\n # Arguments\n x: Input tensor. Must be 3D.\n zoom_range: Tuple of floats; zoom range for width and height.\n row_axis: Index of axis for rows in the input tensor.\n col_axis: Index of axis for columns in the input tensor.\n channel_axis: Index of axis for channels in the input tensor.\n fill_mode: Points outside the boundaries of the input\n are filled according to the given mode\n (one of `{'constant', 'nearest', 'reflect', 'wrap'}`).\n cval: Value used for points outside the boundaries\n of the input if `mode='constant'`.\n\n # Returns\n Zoomed Numpy image tensor.\n\n # Raises\n ValueError: if `zoom_range` isn't a tuple.\n \"\"\"\n if len(zoom_range) != 2:\n raise ValueError('`zoom_range` should be a tuple or list of two'\n ' floats. Received: ', zoom_range)\n\n if zoom_range[0] == 1 and zoom_range[1] == 1:\n zx, zy = 1, 1\n else:\n zx, zy = np.random.uniform(zoom_range[0], zoom_range[1], 2)\n zoom_matrix = np.array([[zx, 0, 0],\n [0, zy, 0],\n [0, 0, 1]])\n\n h, w = x.shape[row_axis], x.shape[col_axis]\n transform_matrix = transform_matrix_offset_center(zoom_matrix, h, w)\n x = apply_transform(x, transform_matrix, channel_axis, fill_mode, cval)\n return x\n\n\ndef random_channel_shift(x, intensity, channel_axis=0):\n \"\"\"Performs a random channel shift.\n\n # Arguments\n x: Input tensor. Must be 3D.\n intensity: Transformation intensity.\n channel_axis: Index of axis for channels in the input tensor.\n\n # Returns\n Numpy image tensor.\n\n \"\"\"\n x = np.rollaxis(x, channel_axis, 0)\n min_x, max_x = np.min(x), np.max(x)\n channel_images = [\n np.clip(x_channel + np.random.uniform(-intensity, intensity),\n min_x,\n max_x)\n for x_channel in x]\n x = np.stack(channel_images, axis=0)\n x = np.rollaxis(x, 0, channel_axis + 1)\n return x\n\n\ndef random_brightness(x, brightness_range):\n \"\"\"Performs a random brightness shift.\n\n # Arguments\n x: Input tensor. Must be 3D.\n brightness_range: Tuple of floats; brightness range.\n channel_axis: Index of axis for channels in the input tensor.\n\n # Returns\n Numpy image tensor.\n\n # Raises\n ValueError if `brightness_range` isn't a tuple.\n\n \"\"\"\n if len(brightness_range) != 2:\n raise ValueError(\n '`brightness_range should be tuple or list of two floats. '\n 'Received: %s' % brightness_range)\n\n x = array_to_img(x)\n x = imgenhancer_Brightness = ImageEnhance.Brightness(x)\n u = np.random.uniform(brightness_range[0], brightness_range[1])\n x = imgenhancer_Brightness.enhance(u)\n x = img_to_array(x)\n return x\n\n\ndef transform_matrix_offset_center(matrix, x, y):\n o_x = float(x) / 2 + 0.5\n o_y = float(y) / 2 + 0.5\n offset_matrix = np.array([[1, 0, o_x], [0, 1, o_y], [0, 0, 1]])\n reset_matrix = np.array([[1, 0, -o_x], [0, 1, -o_y], [0, 0, 1]])\n transform_matrix = np.dot(np.dot(offset_matrix, matrix), reset_matrix)\n return transform_matrix\n\n\ndef apply_transform(x,\n transform_matrix,\n channel_axis=0,\n fill_mode='nearest',\n cval=0.):\n \"\"\"Applies the image transformation specified by a matrix.\n\n # Arguments\n x: 2D numpy array, single image.\n transform_matrix: Numpy array specifying the geometric transformation.\n channel_axis: Index of axis for channels in the input tensor.\n fill_mode: Points outside the boundaries of the input\n are filled according to the given mode\n (one of `{'constant', 'nearest', 'reflect', 'wrap'}`).\n cval: Value used for points outside the boundaries\n of the input if `mode='constant'`.\n\n # Returns\n The transformed version of the input.\n \"\"\"\n x = np.rollaxis(x, channel_axis, 0)\n final_affine_matrix = transform_matrix[:2, :2]\n final_offset = transform_matrix[:2, 2]\n channel_images = [ndi.interpolation.affine_transform(\n x_channel,\n final_affine_matrix,\n final_offset,\n order=1,\n mode=fill_mode,\n cval=cval) for x_channel in x]\n x = np.stack(channel_images, axis=0)\n x = np.rollaxis(x, 0, channel_axis + 1)\n return x\n\n\ndef flip_axis(x, axis):\n x = np.asarray(x).swapaxes(axis, 0)\n x = x[::-1, ...]\n x = x.swapaxes(0, axis)\n return x\n\n\ndef array_to_img(x, data_format=None, scale=True):\n \"\"\"Converts a 3D Numpy array to a PIL Image instance.\n\n # Arguments\n x: Input Numpy array.\n data_format: Image data format.\n either \"channels_first\" or \"channels_last\".\n scale: Whether to rescale image values\n to be within `[0, 255]`.\n\n # Returns\n A PIL Image instance.\n\n # Raises\n ImportError: if PIL is not available.\n ValueError: if invalid `x` or `data_format` is passed.\n \"\"\"\n if pil_image is None:\n raise ImportError('Could not import PIL.Image. '\n 'The use of `array_to_img` requires PIL.')\n x = np.asarray(x, dtype=K.floatx())\n if x.ndim != 3:\n raise ValueError('Expected image array to have rank 3 (single image). '\n 'Got array with shape:', x.shape)\n\n if data_format is None:\n data_format = K.image_data_format()\n if data_format not in {'channels_first', 'channels_last'}:\n raise ValueError('Invalid data_format:', data_format)\n\n # Original Numpy array x has format (height, width, channel)\n # or (channel, height, width)\n # but target PIL image has format (width, height, channel)\n if data_format == 'channels_first':\n x = x.transpose(1, 2, 0)\n if scale:\n x = x + max(-np.min(x), 0)\n x_max = np.max(x)\n if x_max != 0:\n x /= x_max\n x *= 255\n if x.shape[2] == 3:\n # RGB\n return pil_image.fromarray(x.astype('uint8'), 'RGB')\n elif x.shape[2] == 1:\n # grayscale\n return pil_image.fromarray(x[:, :, 0].astype('uint8'), 'L')\n else:\n raise ValueError('Unsupported channel number: ', x.shape[2])\n\n\ndef img_to_array(img, data_format=None):\n \"\"\"Converts a PIL Image instance to a Numpy array.\n\n # Arguments\n img: PIL Image instance.\n data_format: Image data format,\n either \"channels_first\" or \"channels_last\".\n\n # Returns\n A 3D Numpy array.\n\n # Raises\n ValueError: if invalid `img` or `data_format` is passed.\n \"\"\"\n if data_format is None:\n data_format = K.image_data_format()\n if data_format not in {'channels_first', 'channels_last'}:\n raise ValueError('Unknown data_format: ', data_format)\n # Numpy array x has format (height, width, channel)\n # or (channel, height, width)\n # but original PIL image has format (width, height, channel)\n x = np.asarray(img, dtype=K.floatx())\n if len(x.shape) == 3:\n if data_format == 'channels_first':\n x = x.transpose(2, 0, 1)\n elif len(x.shape) == 2:\n if data_format == 'channels_first':\n x = x.reshape((1, x.shape[0], x.shape[1]))\n else:\n x = x.reshape((x.shape[0], x.shape[1], 1))\n else:\n raise ValueError('Unsupported image shape: ', x.shape)\n return x\n\n\ndef save_img(path,\n x,\n data_format=None,\n file_format=None,\n scale=True, **kwargs):\n \"\"\"Saves an image stored as a Numpy array to a path or file object.\n\n # Arguments\n path: Path or file object.\n x: Numpy array.\n data_format: Image data format,\n either \"channels_first\" or \"channels_last\".\n file_format: Optional file format override. If omitted, the\n format to use is determined from the filename extension.\n If a file object was used instead of a filename, this\n parameter should always be used.\n scale: Whether to rescale image values to be within `[0, 255]`.\n **kwargs: Additional keyword arguments passed to `PIL.Image.save()`.\n \"\"\"\n img = array_to_img(x, data_format=data_format, scale=scale)\n img.save(path, format=file_format, **kwargs)\n\n\ndef load_img(path, grayscale=False, target_size=None,\n interpolation='nearest'):\n \"\"\"Loads an image into PIL format.\n\n # Arguments\n path: Path to image file.\n grayscale: Boolean, whether to load the image as grayscale.\n target_size: Either `None` (default to original size)\n or tuple of ints `(img_height, img_width)`.\n interpolation: Interpolation method used to resample the image if the\n target size is different from that of the loaded image.\n Supported methods are \"nearest\", \"bilinear\", and \"bicubic\".\n If PIL version 1.1.3 or newer is installed, \"lanczos\" is also\n supported. If PIL version 3.4.0 or newer is installed, \"box\" and\n \"hamming\" are also supported. By default, \"nearest\" is used.\n\n # Returns\n A PIL Image instance.\n\n # Raises\n ImportError: if PIL is not available.\n ValueError: if interpolation method is not supported.\n \"\"\"\n if pil_image is None:\n raise ImportError('Could not import PIL.Image. '\n 'The use of `array_to_img` requires PIL.')\n img = pil_image.open(path)\n if grayscale:\n if img.mode != 'L':\n img = img.convert('L')\n else:\n if img.mode != 'RGB':\n img = img.convert('RGB')\n if target_size is not None:\n width_height_tuple = (target_size[1], target_size[0])\n if img.size != width_height_tuple:\n if interpolation not in _PIL_INTERPOLATION_METHODS:\n raise ValueError(\n 'Invalid interpolation method {} specified. Supported '\n 'methods are {}'.format(\n interpolation,\n \", \".join(_PIL_INTERPOLATION_METHODS.keys())))\n resample = _PIL_INTERPOLATION_METHODS[interpolation]\n img = img.resize(width_height_tuple, resample)\n return img\n\n\ndef list_pictures(directory, ext='jpg|jpeg|bmp|png|ppm'):\n return [os.path.join(root, f)\n for root, _, files in os.walk(directory) for f in files\n if re.match(r'([\\w]+\\.(?:' + ext + '))', f)]\n\n\nclass ImageDataGenerator(object):\n \"\"\"Generate batches of tensor image data with real-time data augmentation.\n The data will be looped over (in batches).\n\n # Arguments\n featurewise_center: Boolean.\n Set input mean to 0 over the dataset, feature-wise.\n samplewise_center: Boolean. Set each sample mean to 0.\n featurewise_std_normalization: Boolean.\n Divide inputs by std of the dataset, feature-wise.\n samplewise_std_normalization: Boolean. Divide each input by its std.\n zca_epsilon: epsilon for ZCA whitening. Default is 1e-6.\n zca_whitening: Boolean. Apply ZCA whitening.\n rotation_range: Int. Degree range for random rotations.\n width_shift_range: Float, 1-D array-like or int\n - float: fraction of total width, if < 1, or pixels if >= 1.\n - 1-D array-like: random elements from the array.\n - int: integer number of pixels from interval\n `(-width_shift_range, +width_shift_range)`\n - With `width_shift_range=2` possible values\n are integers `[-1, 0, +1]`,\n same as with `width_shift_range=[-1, 0, +1]`,\n while with `width_shift_range=1.0` possible values are floats in\n the interval [-1.0, +1.0).\n height_shift_range: Float, 1-D array-like or int\n - float: fraction of total height, if < 1, or pixels if >= 1.\n - 1-D array-like: random elements from the array.\n - int: integer number of pixels from interval\n `(-height_shift_range, +height_shift_range)`\n - With `height_shift_range=2` possible values\n are integers `[-1, 0, +1]`,\n same as with `height_shift_range=[-1, 0, +1]`,\n while with `height_shift_range=1.0` possible values are floats in\n the interval [-1.0, +1.0).\n shear_range: Float. Shear Intensity\n (Shear angle in counter-clockwise direction in degrees)\n zoom_range: Float or [lower, upper]. Range for random zoom.\n If a float, `[lower, upper] = [1-zoom_range, 1+zoom_range]`.\n channel_shift_range: Float. Range for random channel shifts.\n fill_mode: One of {\"constant\", \"nearest\", \"reflect\" or \"wrap\"}.\n Default is 'nearest'.\n Points outside the boundaries of the input are filled\n according to the given mode:\n - 'constant': kkkkkkkk|abcd|kkkkkkkk (cval=k)\n - 'nearest': aaaaaaaa|abcd|dddddddd\n - 'reflect': abcddcba|abcd|dcbaabcd\n - 'wrap': abcdabcd|abcd|abcdabcd\n cval: Float or Int.\n Value used for points outside the boundaries\n when `fill_mode = \"constant\"`.\n horizontal_flip: Boolean. Randomly flip inputs horizontally.\n vertical_flip: Boolean. Randomly flip inputs vertically.\n rescale: rescaling factor. Defaults to None.\n If None or 0, no rescaling is applied,\n otherwise we multiply the data by the value provided\n (before applying any other transformation).\n preprocessing_function: function that will be implied on each input.\n The function will run after the image is resized and augmented.\n The function should take one argument:\n one image (Numpy tensor with rank 3),\n and should output a Numpy tensor with the same shape.\n data_format: Image data format,\n either \"channels_first\" or \"channels_last\".\n \"channels_last\" mode means that the images should have shape\n `(samples, height, width, channels)`,\n \"channels_first\" mode means that the images should have shape\n `(samples, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n validation_split: Float. Fraction of images reserved for validation\n (strictly between 0 and 1).\n\n # Examples\n Example of using `.flow(x, y)`:\n\n ```python\n (x_train, y_train), (x_test, y_test) = cifar10.load_data()\n y_train = np_utils.to_categorical(y_train, num_classes)\n y_test = np_utils.to_categorical(y_test, num_classes)\n\n datagen = ImageDataGenerator(\n featurewise_center=True,\n featurewise_std_normalization=True,\n rotation_range=20,\n width_shift_range=0.2,\n height_shift_range=0.2,\n horizontal_flip=True)\n\n # compute quantities required for featurewise normalization\n # (std, mean, and principal components if ZCA whitening is applied)\n datagen.fit(x_train)\n\n # fits the model on batches with real-time data augmentation:\n model.fit_generator(datagen.flow(x_train, y_train, batch_size=32),\n steps_per_epoch=len(x_train) / 32, epochs=epochs)\n\n # here's a more \"manual\" example\n for e in range(epochs):\n print('Epoch', e)\n batches = 0\n for x_batch, y_batch in datagen.flow(x_train, y_train, batch_size=32):\n model.fit(x_batch, y_batch)\n batches += 1\n if batches >= len(x_train) / 32:\n # we need to break the loop by hand because\n # the generator loops indefinitely\n break\n ```\n Example of using `.flow_from_directory(directory)`:\n\n ```python\n train_datagen = ImageDataGenerator(\n rescale=1./255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True)\n\n test_datagen = ImageDataGenerator(rescale=1./255)\n\n train_generator = train_datagen.flow_from_directory(\n 'data/train',\n target_size=(150, 150),\n batch_size=32,\n class_mode='binary')\n\n validation_generator = test_datagen.flow_from_directory(\n 'data/validation',\n target_size=(150, 150),\n batch_size=32,\n class_mode='binary')\n\n model.fit_generator(\n train_generator,\n steps_per_epoch=2000,\n epochs=50,\n validation_data=validation_generator,\n validation_steps=800)\n ```\n\n Example of transforming images and masks together.\n\n ```python\n # we create two instances with the same arguments\n data_gen_args = dict(featurewise_center=True,\n featurewise_std_normalization=True,\n rotation_range=90.,\n width_shift_range=0.1,\n height_shift_range=0.1,\n zoom_range=0.2)\n image_datagen = ImageDataGenerator(**data_gen_args)\n mask_datagen = ImageDataGenerator(**data_gen_args)\n\n # Provide the same seed and keyword arguments to the fit and flow methods\n seed = 1\n image_datagen.fit(images, augment=True, seed=seed)\n mask_datagen.fit(masks, augment=True, seed=seed)\n\n image_generator = image_datagen.flow_from_directory(\n 'data/images',\n class_mode=None,\n seed=seed)\n\n mask_generator = mask_datagen.flow_from_directory(\n 'data/masks',\n class_mode=None,\n seed=seed)\n\n # combine generators into one which yields image and masks\n train_generator = zip(image_generator, mask_generator)\n\n model.fit_generator(\n train_generator,\n steps_per_epoch=2000,\n epochs=50)\n ```\n \"\"\"\n\n def __init__(self,\n featurewise_center=False,\n samplewise_center=False,\n featurewise_std_normalization=False,\n samplewise_std_normalization=False,\n zca_whitening=False,\n zca_epsilon=1e-6,\n rotation_range=0.,\n width_shift_range=0.,\n height_shift_range=0.,\n brightness_range=None,\n shear_range=0.,\n zoom_range=0.,\n channel_shift_range=0.,\n fill_mode='nearest',\n cval=0.,\n horizontal_flip=False,\n vertical_flip=False,\n rescale=None,\n preprocessing_function=None,\n data_format=None,\n validation_split=0.0):\n if data_format is None:\n data_format = K.image_data_format()\n self.featurewise_center = featurewise_center\n self.samplewise_center = samplewise_center\n self.featurewise_std_normalization = featurewise_std_normalization\n self.samplewise_std_normalization = samplewise_std_normalization\n self.zca_whitening = zca_whitening\n self.zca_epsilon = zca_epsilon\n self.rotation_range = rotation_range\n self.width_shift_range = width_shift_range\n self.height_shift_range = height_shift_range\n self.brightness_range = brightness_range\n self.shear_range = shear_range\n self.zoom_range = zoom_range\n self.channel_shift_range = channel_shift_range\n self.fill_mode = fill_mode\n self.cval = cval\n self.horizontal_flip = horizontal_flip\n self.vertical_flip = vertical_flip\n self.rescale = rescale\n self.preprocessing_function = preprocessing_function\n\n if data_format not in {'channels_last', 'channels_first'}:\n raise ValueError(\n '`data_format` should be `\"channels_last\"` '\n '(channel after row and column) or '\n '`\"channels_first\"` (channel before row and column). '\n 'Received: %s' % data_format)\n self.data_format = data_format\n if data_format == 'channels_first':\n self.channel_axis = 1\n self.row_axis = 2\n self.col_axis = 3\n if data_format == 'channels_last':\n self.channel_axis = 3\n self.row_axis = 1\n self.col_axis = 2\n if validation_split and not 0 < validation_split < 1:\n raise ValueError(\n '`validation_split` must be strictly between 0 and 1. '\n ' Received: %s' % validation_split)\n self._validation_split = validation_split\n\n self.mean = None\n self.std = None\n self.principal_components = None\n\n if np.isscalar(zoom_range):\n self.zoom_range = [1 - zoom_range, 1 + zoom_range]\n elif len(zoom_range) == 2:\n self.zoom_range = [zoom_range[0], zoom_range[1]]\n else:\n raise ValueError('`zoom_range` should be a float or '\n 'a tuple or list of two floats. '\n 'Received: %s' % zoom_range)\n if zca_whitening:\n if not featurewise_center:\n self.featurewise_center = True\n warnings.warn('This ImageDataGenerator specifies '\n '`zca_whitening`, which overrides '\n 'setting of `featurewise_center`.')\n if featurewise_std_normalization:\n self.featurewise_std_normalization = False\n warnings.warn('This ImageDataGenerator specifies '\n '`zca_whitening` '\n 'which overrides setting of'\n '`featurewise_std_normalization`.')\n if featurewise_std_normalization:\n if not featurewise_center:\n self.featurewise_center = True\n warnings.warn('This ImageDataGenerator specifies '\n '`featurewise_std_normalization`, '\n 'which overrides setting of '\n '`featurewise_center`.')\n if samplewise_std_normalization:\n if not samplewise_center:\n self.samplewise_center = True\n warnings.warn('This ImageDataGenerator specifies '\n '`samplewise_std_normalization`, '\n 'which overrides setting of '\n '`samplewise_center`.')\n\n def flow(self, x, y=None, batch_size=32, shuffle=True, sample_weight=None, seed=None,\n save_to_dir=None, save_prefix='', save_format='png', subset=None):\n \"\"\"Takes numpy data & label arrays, and generates batches of augmented data.\n\n # Arguments\n x: Input data. Numpy array of rank 4 or a tuple.\n If tuple, the first element\n should contain the images and the second element\n another numpy array or a list of numpy arrays\n that gets passed to the output\n without any modifications.\n Can be used to feed the model miscellaneous data\n along with the images.\n In case of grayscale data, the channels axis of the image array\n should have value 1, and in case\n of RGB data, it should have value 3.\n y: Labels.\n batch_size: Int (default: 32).\n shuffle: Boolean (default: True).\n sample_weight: Sample weights.\n seed: Int (default: None).\n save_to_dir: None or str (default: None).\n This allows you to optionally specify a directory\n to which to save the augmented pictures being generated\n (useful for visualizing what you are doing).\n save_prefix: Str (default: `''`).\n Prefix to use for filenames of saved pictures\n (only relevant if `save_to_dir` is set).\n save_format: one of \"png\", \"jpeg\"\n (only relevant if `save_to_dir` is set). Default: \"png\".\n subset: Subset of data (`\"training\"` or `\"validation\"`) if\n `validation_split` is set in `ImageDataGenerator`.\n\n # Returns\n An `Iterator` yielding tuples of `(x, y)`\n where `x` is a numpy array of image data\n (in the case of a single image input) or a list\n of numpy arrays (in the case with\n additional inputs) and `y` is a numpy array\n of corresponding labels. If 'sample_weight' is not None,\n the yielded tuples are of the form `(x, y, sample_weight)`.\n If `y` is None, only the numpy array `x` is returned.\n \"\"\"\n return NumpyArrayIterator(\n x, y, self,\n batch_size=batch_size,\n shuffle=shuffle,\n sample_weight=sample_weight,\n seed=seed,\n data_format=self.data_format,\n save_to_dir=save_to_dir,\n save_prefix=save_prefix,\n save_format=save_format,\n subset=subset)\n\n def flow_from_directory(self, directory,\n target_size=(256, 256), color_mode='rgb',\n classes=None, class_mode='categorical',\n batch_size=32, shuffle=True, seed=None,\n save_to_dir=None,\n save_prefix='',\n save_format='png',\n follow_links=False,\n subset=None,\n interpolation='nearest'):\n \"\"\"Takes the path to a directory & generates batches of augmented data.\n\n # Arguments\n directory: Path to the target directory.\n It should contain one subdirectory per class.\n Any PNG, JPG, BMP, PPM or TIF images\n inside each of the subdirectories directory tree\n will be included in the generator.\n See [this script](https://gist.github.com/fchollet/0830affa1f7f19fd47b06d4cf89ed44d)\n for more details.\n target_size: Tuple of integers `(height, width)`,\n default: `(256, 256)`.\n The dimensions to which all images found will be resized.\n color_mode: One of \"grayscale\", \"rbg\". Default: \"rgb\".\n Whether the images will be converted to\n have 1 or 3 color channels.\n classes: Optional list of class subdirectories\n (e.g. `['dogs', 'cats']`). Default: None.\n If not provided, the list of classes will be automatically\n inferred from the subdirectory names/structure\n under `directory`, where each subdirectory will\n be treated as a different class\n (and the order of the classes, which will map to the label\n indices, will be alphanumeric).\n The dictionary containing the mapping from class names to class\n indices can be obtained via the attribute `class_indices`.\n class_mode: One of \"categorical\", \"binary\", \"sparse\",\n \"input\", or None. Default: \"categorical\".\n Determines the type of label arrays that are returned:\n - \"categorical\" will be 2D one-hot encoded labels,\n - \"binary\" will be 1D binary labels,\n \"sparse\" will be 1D integer labels,\n - \"input\" will be images identical\n to input images (mainly used to work with autoencoders).\n - If None, no labels are returned\n (the generator will only yield batches of image data,\n which is useful to use with `model.predict_generator()`,\n `model.evaluate_generator()`, etc.).\n Please note that in case of class_mode None,\n the data still needs to reside in a subdirectory\n of `directory` for it to work correctly.\n batch_size: Size of the batches of data (default: 32).\n shuffle: Whether to shuffle the data (default: True)\n seed: Optional random seed for shuffling and transformations.\n save_to_dir: None or str (default: None).\n This allows you to optionally specify\n a directory to which to save\n the augmented pictures being generated\n (useful for visualizing what you are doing).\n save_prefix: Str. Prefix to use for filenames of saved pictures\n (only relevant if `save_to_dir` is set).\n save_format: One of \"png\", \"jpeg\"\n (only relevant if `save_to_dir` is set). Default: \"png\".\n follow_links: Whether to follow symlinks inside\n class subdirectories (default: False).\n subset: Subset of data (`\"training\"` or `\"validation\"`) if\n `validation_split` is set in `ImageDataGenerator`.\n interpolation: Interpolation method used to\n resample the image if the\n target size is different from that of the loaded image.\n Supported methods are `\"nearest\"`, `\"bilinear\"`,\n and `\"bicubic\"`.\n If PIL version 1.1.3 or newer is installed, `\"lanczos\"` is also\n supported. If PIL version 3.4.0 or newer is installed,\n `\"box\"` and `\"hamming\"` are also supported.\n By default, `\"nearest\"` is used.\n\n # Returns\n A `DirectoryIterator` yielding tuples of `(x, y)`\n where `x` is a numpy array containing a batch\n of images with shape `(batch_size, *target_size, channels)`\n and `y` is a numpy array of corresponding labels.\n \"\"\"\n return DirectoryIterator(\n directory, self,\n target_size=target_size, color_mode=color_mode,\n classes=classes, class_mode=class_mode,\n data_format=self.data_format,\n batch_size=batch_size, shuffle=shuffle, seed=seed,\n save_to_dir=save_to_dir,\n save_prefix=save_prefix,\n save_format=save_format,\n follow_links=follow_links,\n subset=subset,\n interpolation=interpolation)\n\n def standardize(self, x):\n \"\"\"Applies the normalization configuration to a batch of inputs.\n\n # Arguments\n x: Batch of inputs to be normalized.\n\n # Returns\n The inputs, normalized.\n \"\"\"\n if self.preprocessing_function:\n x = self.preprocessing_function(x)\n if self.rescale:\n x *= self.rescale\n if self.samplewise_center:\n x -= np.mean(x, keepdims=True)\n if self.samplewise_std_normalization:\n x /= (np.std(x, keepdims=True) + K.epsilon())\n\n if self.featurewise_center:\n if self.mean is not None:\n x -= self.mean\n else:\n warnings.warn('This ImageDataGenerator specifies '\n '`featurewise_center`, but it hasn\\'t '\n 'been fit on any training data. Fit it '\n 'first by calling `.fit(numpy_data)`.')\n if self.featurewise_std_normalization:\n if self.std is not None:\n x /= (self.std + K.epsilon())\n else:\n warnings.warn('This ImageDataGenerator specifies '\n '`featurewise_std_normalization`, '\n 'but it hasn\\'t '\n 'been fit on any training data. Fit it '\n 'first by calling `.fit(numpy_data)`.')\n if self.zca_whitening:\n if self.principal_components is not None:\n flatx = np.reshape(x, (-1, np.prod(x.shape[-3:])))\n whitex = np.dot(flatx, self.principal_components)\n x = np.reshape(whitex, x.shape)\n else:\n warnings.warn('This ImageDataGenerator specifies '\n '`zca_whitening`, but it hasn\\'t '\n 'been fit on any training data. Fit it '\n 'first by calling `.fit(numpy_data)`.')\n return x\n\n def random_transform(self, x, seed=None):\n \"\"\"Randomly augments a single image tensor.\n\n # Arguments\n x: 3D tensor, single image.\n seed: Random seed.\n\n # Returns\n A randomly transformed version of the input (same shape).\n \"\"\"\n # x is a single image, so it doesn't have image number at index 0\n img_row_axis = self.row_axis - 1\n img_col_axis = self.col_axis - 1\n img_channel_axis = self.channel_axis - 1\n\n if seed is not None:\n np.random.seed(seed)\n\n # Use composition of homographies\n # to generate final transform that needs to be applied\n if self.rotation_range:\n theta = np.deg2rad(np.random.uniform(\n -self.rotation_range,\n self.rotation_range))\n else:\n theta = 0\n\n if self.height_shift_range:\n try: # 1-D array-like or int\n tx = np.random.choice(self.height_shift_range)\n tx *= np.random.choice([-1, 1])\n except ValueError: # floating point\n tx = np.random.uniform(-self.height_shift_range,\n self.height_shift_range)\n if np.max(self.height_shift_range) < 1:\n tx *= x.shape[img_row_axis]\n else:\n tx = 0\n\n if self.width_shift_range:\n try: # 1-D array-like or int\n ty = np.random.choice(self.width_shift_range)\n ty *= np.random.choice([-1, 1])\n except ValueError: # floating point\n ty = np.random.uniform(-self.width_shift_range,\n self.width_shift_range)\n if np.max(self.width_shift_range) < 1:\n ty *= x.shape[img_col_axis]\n else:\n ty = 0\n\n if self.shear_range:\n shear = np.deg2rad(np.random.uniform(\n -self.shear_range,\n self.shear_range))\n else:\n shear = 0\n\n if self.zoom_range[0] == 1 and self.zoom_range[1] == 1:\n zx, zy = 1, 1\n else:\n zx, zy = np.random.uniform(\n self.zoom_range[0],\n self.zoom_range[1],\n 2)\n transform_matrix = None\n if theta != 0:\n rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), 0],\n [np.sin(theta), np.cos(theta), 0],\n [0, 0, 1]])\n transform_matrix = rotation_matrix\n\n if tx != 0 or ty != 0:\n shift_matrix = np.array([[1, 0, tx],\n [0, 1, ty],\n [0, 0, 1]])\n transform_matrix = shift_matrix if transform_matrix is None else np.dot(transform_matrix, shift_matrix)\n\n if shear != 0:\n shear_matrix = np.array([[1, -np.sin(shear), 0],\n [0, np.cos(shear), 0],\n [0, 0, 1]])\n transform_matrix = shear_matrix if transform_matrix is None else np.dot(transform_matrix, shear_matrix)\n\n if zx != 1 or zy != 1:\n zoom_matrix = np.array([[zx, 0, 0],\n [0, zy, 0],\n [0, 0, 1]])\n transform_matrix = zoom_matrix if transform_matrix is None else np.dot(transform_matrix, zoom_matrix)\n\n if transform_matrix is not None:\n h, w = x.shape[img_row_axis], x.shape[img_col_axis]\n transform_matrix = transform_matrix_offset_center(\n transform_matrix, h, w)\n x = apply_transform(x, transform_matrix, img_channel_axis,\n fill_mode=self.fill_mode, cval=self.cval)\n\n if self.channel_shift_range != 0:\n x = random_channel_shift(x,\n self.channel_shift_range,\n img_channel_axis)\n if self.horizontal_flip:\n if np.random.random() < 0.5:\n x = flip_axis(x, img_col_axis)\n\n if self.vertical_flip:\n if np.random.random() < 0.5:\n x = flip_axis(x, img_row_axis)\n\n if self.brightness_range is not None:\n x = random_brightness(x, self.brightness_range)\n\n return x\n\n def fit(self, x,\n augment=False,\n rounds=1,\n seed=None):\n \"\"\"Computes the internal data stats related to the data-dependent transformations, based on an array of sample data.\n\n Only required if `featurewise_center` or\n `featurewise_std_normalization` or `zca_whitening` are set to True.\n\n # Arguments\n x: Sample data. Should have rank 4.\n In case of grayscale data,\n the channels axis should have value 1, and in case\n of RGB data, it should have value 3.\n augment: Boolean (default: False).\n Whether to fit on randomly augmented samples.\n rounds: Int (default: 1).\n If using data augmentation (`augment=True`),\n this is how many augmentation passes over the data to use.\n seed: Int (default: None). Random seed.\n \"\"\"\n x = np.asarray(x, dtype=K.floatx())\n if x.ndim != 4:\n raise ValueError('Input to `.fit()` should have rank 4. '\n 'Got array with shape: ' + str(x.shape))\n if x.shape[self.channel_axis] not in {1, 3, 4}:\n warnings.warn(\n 'Expected input to be images (as Numpy array) '\n 'following the data format convention \"' +\n self.data_format + '\" (channels on axis ' +\n str(self.channel_axis) + '), i.e. expected '\n 'either 1, 3 or 4 channels on axis ' +\n str(self.channel_axis) + '. '\n 'However, it was passed an array with shape ' +\n str(x.shape) + ' (' + str(x.shape[self.channel_axis]) +\n ' channels).')\n\n if seed is not None:\n np.random.seed(seed)\n\n x = np.copy(x)\n if augment:\n ax = np.zeros(\n tuple([rounds * x.shape[0]] + list(x.shape)[1:]),\n dtype=K.floatx())\n for r in range(rounds):\n for i in range(x.shape[0]):\n ax[i + r * x.shape[0]] = self.random_transform(x[i])\n x = ax\n\n if self.featurewise_center:\n self.mean = np.mean(x, axis=(0, self.row_axis, self.col_axis))\n broadcast_shape = [1, 1, 1]\n broadcast_shape[self.channel_axis - 1] = x.shape[self.channel_axis]\n self.mean = np.reshape(self.mean, broadcast_shape)\n x -= self.mean\n\n if self.featurewise_std_normalization:\n self.std = np.std(x, axis=(0, self.row_axis, self.col_axis))\n broadcast_shape = [1, 1, 1]\n broadcast_shape[self.channel_axis - 1] = x.shape[self.channel_axis]\n self.std = np.reshape(self.std, broadcast_shape)\n x /= (self.std + K.epsilon())\n\n if self.zca_whitening:\n flat_x = np.reshape(\n x, (x.shape[0], x.shape[1] * x.shape[2] * x.shape[3]))\n sigma = np.dot(flat_x.T, flat_x) / flat_x.shape[0]\n u, s, _ = linalg.svd(sigma)\n s_inv = 1. / np.sqrt(s[np.newaxis] + self.zca_epsilon)\n self.principal_components = (u * s_inv).dot(u.T)\n\n\nclass Iterator(Sequence):\n \"\"\"Base class for image data iterators.\n\n Every `Iterator` must implement the `_get_batches_of_transformed_samples`\n method.\n\n # Arguments\n n: Integer, total number of samples in the dataset to loop over.\n batch_size: Integer, size of a batch.\n shuffle: Boolean, whether to shuffle the data between epochs.\n seed: Random seeding for data shuffling.\n \"\"\"\n\n def __init__(self, n, batch_size, shuffle, seed):\n self.n = n\n self.batch_size = batch_size\n self.seed = seed\n self.shuffle = shuffle\n self.batch_index = 0\n self.total_batches_seen = 0\n self.lock = threading.Lock()\n self.index_array = None\n self.index_generator = self._flow_index()\n\n def _set_index_array(self):\n self.index_array = np.arange(self.n)\n if self.shuffle:\n self.index_array = np.random.permutation(self.n)\n\n def __getitem__(self, idx):\n if idx >= len(self):\n raise ValueError('Asked to retrieve element {idx}, '\n 'but the Sequence '\n 'has length {length}'.format(idx=idx,\n length=len(self)))\n if self.seed is not None:\n np.random.seed(self.seed + self.total_batches_seen)\n self.total_batches_seen += 1\n if self.index_array is None:\n self._set_index_array()\n index_array = self.index_array[self.batch_size * idx:\n self.batch_size * (idx + 1)]\n return self._get_batches_of_transformed_samples(index_array)\n\n def __len__(self):\n return (self.n + self.batch_size - 1) // self.batch_size # round up\n\n def on_epoch_end(self):\n self._set_index_array()\n\n def reset(self):\n self.batch_index = 0\n\n def _flow_index(self):\n # Ensure self.batch_index is 0.\n self.reset()\n while 1:\n if self.seed is not None:\n np.random.seed(self.seed + self.total_batches_seen)\n if self.batch_index == 0:\n self._set_index_array()\n\n current_index = (self.batch_index * self.batch_size) % self.n\n if self.n > current_index + self.batch_size:\n self.batch_index += 1\n else:\n self.batch_index = 0\n self.total_batches_seen += 1\n yield self.index_array[current_index:\n current_index + self.batch_size]\n\n def __iter__(self):\n # Needed if we want to do something like:\n # for x, y in data_gen.flow(...):\n return self\n\n def __next__(self, *args, **kwargs):\n return self.next(*args, **kwargs)\n\n def _get_batches_of_transformed_samples(self, index_array):\n \"\"\"Gets a batch of transformed samples.\n\n # Arguments\n index_array: Array of sample indices to include in batch.\n\n # Returns\n A batch of transformed samples.\n \"\"\"\n raise NotImplementedError\n\n\nclass NumpyArrayIterator(Iterator):\n \"\"\"Iterator yielding data from a Numpy array.\n\n # Arguments\n x: Numpy array of input data or tuple.\n If tuple, the second elements is either\n another numpy array or a list of numpy arrays,\n each of which gets passed\n through as an output without any modifications.\n y: Numpy array of targets data.\n image_data_generator: Instance of `ImageDataGenerator`\n to use for random transformations and normalization.\n batch_size: Integer, size of a batch.\n shuffle: Boolean, whether to shuffle the data between epochs.\n sample_weight: Numpy array of sample weights.\n seed: Random seed for data shuffling.\n data_format: String, one of `channels_first`, `channels_last`.\n save_to_dir: Optional directory where to save the pictures\n being yielded, in a viewable format. This is useful\n for visualizing the random transformations being\n applied, for debugging purposes.\n save_prefix: String prefix to use for saving sample\n images (if `save_to_dir` is set).\n save_format: Format to use for saving sample images\n (if `save_to_dir` is set).\n subset: Subset of data (`\"training\"` or `\"validation\"`) if\n validation_split is set in ImageDataGenerator.\n \"\"\"\n\n def __init__(self, x, y, image_data_generator,\n batch_size=32, shuffle=False, sample_weight=None,\n seed=None, data_format=None,\n save_to_dir=None, save_prefix='', save_format='png',\n subset=None):\n if (type(x) is tuple) or (type(x) is list):\n if type(x[1]) is not list:\n x_misc = [np.asarray(x[1])]\n else:\n x_misc = [np.asarray(xx) for xx in x[1]]\n x = x[0]\n for xx in x_misc:\n if len(x) != len(xx):\n raise ValueError(\n 'All of the arrays in `x` '\n 'should have the same length. '\n 'Found a pair with: len(x[0]) = %s, len(x[?]) = %s' %\n (len(x), len(xx)))\n else:\n x_misc = []\n\n if y is not None and len(x) != len(y):\n raise ValueError('`x` (images tensor) and `y` (labels) '\n 'should have the same length. '\n 'Found: x.shape = %s, y.shape = %s' %\n (np.asarray(x).shape, np.asarray(y).shape))\n if sample_weight is not None and len(x) != len(sample_weight):\n raise ValueError('`x` (images tensor) and `sample_weight` '\n 'should have the same length. '\n 'Found: x.shape = %s, sample_weight.shape = %s' %\n (np.asarray(x).shape, np.asarray(sample_weight).shape))\n if subset is not None:\n if subset not in {'training', 'validation'}:\n raise ValueError('Invalid subset name:', subset,\n '; expected \"training\" or \"validation\".')\n split_idx = int(len(x) * image_data_generator._validation_split)\n if subset == 'validation':\n x = x[:split_idx]\n x_misc = [np.asarray(xx[:split_idx]) for xx in x_misc]\n if y is not None:\n y = y[:split_idx]\n else:\n x = x[split_idx:]\n x_misc = [np.asarray(xx[split_idx:]) for xx in x_misc]\n if y is not None:\n y = y[split_idx:]\n if data_format is None:\n data_format = K.image_data_format()\n self.x = np.asarray(x, dtype=K.floatx())\n self.x_misc = x_misc\n if self.x.ndim != 4:\n raise ValueError('Input data in `NumpyArrayIterator` '\n 'should have rank 4. You passed an array '\n 'with shape', self.x.shape)\n channels_axis = 3 if data_format == 'channels_last' else 1\n if self.x.shape[channels_axis] not in {1, 3, 4}:\n warnings.warn('NumpyArrayIterator is set to use the '\n 'data format convention \"' + data_format + '\" '\n '(channels on axis ' + str(channels_axis) +\n '), i.e. expected either 1, 3 or 4 '\n 'channels on axis ' + str(channels_axis) + '. '\n 'However, it was passed an array with shape ' +\n str(self.x.shape) + ' (' +\n str(self.x.shape[channels_axis]) + ' channels).')\n if y is not None:\n self.y = np.asarray(y)\n else:\n self.y = None\n if sample_weight is not None:\n self.sample_weight = np.asarray(sample_weight)\n else:\n self.sample_weight = None\n self.image_data_generator = image_data_generator\n self.data_format = data_format\n self.save_to_dir = save_to_dir\n self.save_prefix = save_prefix\n self.save_format = save_format\n super(NumpyArrayIterator, self).__init__(x.shape[0],\n batch_size,\n shuffle,\n seed)\n\n def _get_batches_of_transformed_samples(self, index_array):\n batch_x = np.zeros(tuple([len(index_array)] + list(self.x.shape)[1:]),\n dtype=K.floatx())\n for i, j in enumerate(index_array):\n x = self.x[j]\n x = self.image_data_generator.random_transform(\n x.astype(K.floatx()))\n x = self.image_data_generator.standardize(x)\n batch_x[i] = x\n\n if self.save_to_dir:\n for i, j in enumerate(index_array):\n img = array_to_img(batch_x[i], self.data_format, scale=True)\n fname = '{prefix}_{index}_{hash}.{format}'.format(\n prefix=self.save_prefix,\n index=j,\n hash=np.random.randint(1e4),\n format=self.save_format)\n img.save(os.path.join(self.save_to_dir, fname))\n batch_x_miscs = [xx[index_array] for xx in self.x_misc]\n output = (batch_x if batch_x_miscs == []\n else [batch_x] + batch_x_miscs,)\n if self.y is None:\n return output[0]\n output += (self.y[index_array],)\n if self.sample_weight is not None:\n output += (self.sample_weight[index_array],)\n return output\n\n def next(self):\n \"\"\"For python 2.x.\n\n # Returns\n The next batch.\n \"\"\"\n # Keeps under lock only the mechanism which advances\n # the indexing of each batch.\n with self.lock:\n index_array = next(self.index_generator)\n # The transformation of images is not under thread lock\n # so it can be done in parallel\n return self._get_batches_of_transformed_samples(index_array)\n\n\ndef _iter_valid_files(directory, white_list_formats, follow_links):\n \"\"\"Iterates on files with extension in `white_list_formats` contained in `directory`.\n\n # Arguments\n directory: Absolute path to the directory\n containing files to be counted\n white_list_formats: Set of strings containing allowed extensions for\n the files to be counted.\n follow_links: Boolean.\n\n # Yields\n Tuple of (root, filename) with extension in `white_list_formats`.\n \"\"\"\n def _recursive_list(subpath):\n return sorted(os.walk(subpath, followlinks=follow_links),\n key=lambda x: x[0])\n\n for root, _, files in _recursive_list(directory):\n for fname in sorted(files):\n for extension in white_list_formats:\n if fname.lower().endswith('.tiff'):\n warnings.warn('Using \\'.tiff\\' files with multiple bands '\n 'will cause distortion. '\n 'Please verify your output.')\n if fname.lower().endswith('.' + extension):\n yield root, fname\n\n\ndef _count_valid_files_in_directory(directory,\n white_list_formats,\n split,\n follow_links):\n \"\"\"Counts files with extension in `white_list_formats` contained in `directory`.\n\n # Arguments\n directory: absolute path to the directory\n containing files to be counted\n white_list_formats: set of strings containing allowed extensions for\n the files to be counted.\n split: tuple of floats (e.g. `(0.2, 0.6)`) to only take into\n account a certain fraction of files in each directory.\n E.g.: `segment=(0.6, 1.0)` would only account for last 40 percent\n of images in each directory.\n follow_links: boolean.\n\n # Returns\n the count of files with extension in `white_list_formats` contained in\n the directory.\n \"\"\"\n num_files = len(list(\n _iter_valid_files(directory, white_list_formats, follow_links)))\n if split:\n start, stop = int(split[0] * num_files), int(split[1] * num_files)\n else:\n start, stop = 0, num_files\n return stop - start\n\n\ndef _list_valid_filenames_in_directory(directory, white_list_formats, split,\n class_indices, follow_links):\n \"\"\"Lists paths of files in `subdir` with extensions in `white_list_formats`.\n\n # Arguments\n directory: absolute path to a directory containing the files to list.\n The directory name is used as class label\n and must be a key of `class_indices`.\n white_list_formats: set of strings containing allowed extensions for\n the files to be counted.\n split: tuple of floats (e.g. `(0.2, 0.6)`) to only take into\n account a certain fraction of files in each directory.\n E.g.: `segment=(0.6, 1.0)` would only account for last 40 percent\n of images in each directory.\n class_indices: dictionary mapping a class name to its index.\n follow_links: boolean.\n\n # Returns\n classes: a list of class indices\n filenames: the path of valid files in `directory`, relative from\n `directory`'s parent (e.g., if `directory` is \"dataset/class1\",\n the filenames will be\n `[\"class1/file1.jpg\", \"class1/file2.jpg\", ...]`).\n \"\"\"\n dirname = os.path.basename(directory)\n if split:\n num_files = len(list(\n _iter_valid_files(directory, white_list_formats, follow_links)))\n start, stop = int(split[0] * num_files), int(split[1] * num_files)\n valid_files = list(\n _iter_valid_files(\n directory, white_list_formats, follow_links))[start: stop]\n else:\n valid_files = _iter_valid_files(\n directory, white_list_formats, follow_links)\n\n classes = []\n filenames = []\n for root, fname in valid_files:\n classes.append(class_indices[dirname])\n absolute_path = os.path.join(root, fname)\n relative_path = os.path.join(\n dirname, os.path.relpath(absolute_path, directory))\n filenames.append(relative_path)\n\n return classes, filenames\n\n\nclass DirectoryIterator(Iterator):\n \"\"\"Iterator capable of reading images from a directory on disk.\n\n # Arguments\n directory: Path to the directory to read images from.\n Each subdirectory in this directory will be\n considered to contain images from one class,\n or alternatively you could specify class subdirectories\n via the `classes` argument.\n image_data_generator: Instance of `ImageDataGenerator`\n to use for random transformations and normalization.\n target_size: tuple of integers, dimensions to resize input images to.\n color_mode: One of `\"rgb\"`, `\"grayscale\"`. Color mode to read images.\n classes: Optional list of strings, names of subdirectories\n containing images from each class (e.g. `[\"dogs\", \"cats\"]`).\n It will be computed automatically if not set.\n class_mode: Mode for yielding the targets:\n `\"binary\"`: binary targets (if there are only two classes),\n `\"categorical\"`: categorical targets,\n `\"sparse\"`: integer targets,\n `\"input\"`: targets are images identical to input images (mainly\n used to work with autoencoders),\n `None`: no targets get yielded (only input images are yielded).\n batch_size: Integer, size of a batch.\n shuffle: Boolean, whether to shuffle the data between epochs.\n seed: Random seed for data shuffling.\n data_format: String, one of `channels_first`, `channels_last`.\n save_to_dir: Optional directory where to save the pictures\n being yielded, in a viewable format. This is useful\n for visualizing the random transformations being\n applied, for debugging purposes.\n save_prefix: String prefix to use for saving sample\n images (if `save_to_dir` is set).\n save_format: Format to use for saving sample images\n (if `save_to_dir` is set).\n subset: Subset of data (`\"training\"` or `\"validation\"`) if\n validation_split is set in ImageDataGenerator.\n interpolation: Interpolation method used to resample the image if the\n target size is different from that of the loaded image.\n Supported methods are \"nearest\", \"bilinear\", and \"bicubic\".\n If PIL version 1.1.3 or newer is installed, \"lanczos\" is also\n supported. If PIL version 3.4.0 or newer is installed, \"box\" and\n \"hamming\" are also supported. By default, \"nearest\" is used.\n \"\"\"\n\n def __init__(self, directory, image_data_generator,\n target_size=(256, 256), color_mode='rgb',\n classes=None, class_mode='categorical',\n batch_size=32, shuffle=True, seed=None,\n data_format=None,\n save_to_dir=None, save_prefix='', save_format='png',\n follow_links=False,\n subset=None,\n interpolation='nearest'):\n if data_format is None:\n data_format = K.image_data_format()\n self.directory = directory\n self.image_data_generator = image_data_generator\n self.target_size = tuple(target_size)\n if color_mode not in {'rgb', 'grayscale'}:\n raise ValueError('Invalid color mode:', color_mode,\n '; expected \"rgb\" or \"grayscale\".')\n self.color_mode = color_mode\n self.data_format = data_format\n if self.color_mode == 'rgb':\n if self.data_format == 'channels_last':\n self.image_shape = self.target_size + (3,)\n else:\n self.image_shape = (3,) + self.target_size\n else:\n if self.data_format == 'channels_last':\n self.image_shape = self.target_size + (1,)\n else:\n self.image_shape = (1,) + self.target_size\n self.classes = classes\n if class_mode not in {'categorical', 'binary', 'sparse',\n 'input', None}:\n raise ValueError('Invalid class_mode:', class_mode,\n '; expected one of \"categorical\", '\n '\"binary\", \"sparse\", \"input\"'\n ' or None.')\n self.class_mode = class_mode\n self.save_to_dir = save_to_dir\n self.save_prefix = save_prefix\n self.save_format = save_format\n self.interpolation = interpolation\n\n if subset is not None:\n validation_split = self.image_data_generator._validation_split\n if subset == 'validation':\n split = (0, validation_split)\n elif subset == 'training':\n split = (validation_split, 1)\n else:\n raise ValueError('Invalid subset name: ', subset,\n '; expected \"training\" or \"validation\"')\n else:\n split = None\n self.subset = subset\n\n white_list_formats = {'png', 'jpg', 'jpeg', 'bmp',\n 'ppm', 'tif', 'tiff'}\n # First, count the number of samples and classes.\n self.samples = 0\n\n if not classes:\n classes = []\n for subdir in sorted(os.listdir(directory)):\n if os.path.isdir(os.path.join(directory, subdir)):\n classes.append(subdir)\n self.num_classes = len(classes)\n self.class_indices = dict(zip(classes, range(len(classes))))\n\n pool = multiprocessing.pool.ThreadPool()\n function_partial = partial(_count_valid_files_in_directory,\n white_list_formats=white_list_formats,\n follow_links=follow_links,\n split=split)\n self.samples = sum(pool.map(function_partial,\n (os.path.join(directory, subdir)\n for subdir in classes)))\n\n print('Found %d images belonging to %d classes.' %\n (self.samples, self.num_classes))\n\n # Second, build an index of the images\n # in the different class subfolders.\n results = []\n self.filenames = []\n self.classes = np.zeros((self.samples,), dtype='int32')\n i = 0\n for dirpath in (os.path.join(directory, subdir) for subdir in classes):\n results.append(\n pool.apply_async(_list_valid_filenames_in_directory,\n (dirpath, white_list_formats, split,\n self.class_indices, follow_links)))\n for res in results:\n classes, filenames = res.get()\n self.classes[i:i + len(classes)] = classes\n self.filenames += filenames\n i += len(classes)\n\n pool.close()\n pool.join()\n super(DirectoryIterator, self).__init__(self.samples,\n batch_size,\n shuffle,\n seed)\n\n def _get_batches_of_transformed_samples(self, index_array):\n batch_x = np.zeros(\n (len(index_array),) + self.image_shape,\n dtype=K.floatx())\n grayscale = self.color_mode == 'grayscale'\n # build batch of image data\n for i, j in enumerate(index_array):\n fname = self.filenames[j]\n img = load_img(os.path.join(self.directory, fname),\n grayscale=grayscale,\n target_size=self.target_size,\n interpolation=self.interpolation)\n x = img_to_array(img, data_format=self.data_format)\n x = self.image_data_generator.random_transform(x)\n x = self.image_data_generator.standardize(x)\n batch_x[i] = x\n # optionally save augmented images to disk for debugging purposes\n if self.save_to_dir:\n for i, j in enumerate(index_array):\n img = array_to_img(batch_x[i], self.data_format, scale=True)\n fname = '{prefix}_{index}_{hash}.{format}'.format(\n prefix=self.save_prefix,\n index=j,\n hash=np.random.randint(1e7),\n format=self.save_format)\n img.save(os.path.join(self.save_to_dir, fname))\n # build batch of labels\n if self.class_mode == 'input':\n batch_y = batch_x.copy()\n elif self.class_mode == 'sparse':\n batch_y = self.classes[index_array]\n elif self.class_mode == 'binary':\n batch_y = self.classes[index_array].astype(K.floatx())\n elif self.class_mode == 'categorical':\n batch_y = np.zeros(\n (len(batch_x), self.num_classes),\n dtype=K.floatx())\n for i, label in enumerate(self.classes[index_array]):\n batch_y[i, label] = 1.\n else:\n return batch_x\n return batch_x, batch_y\n\n def next(self):\n \"\"\"For python 2.x.\n\n # Returns\n The next batch.\n \"\"\"\n with self.lock:\n index_array = next(self.index_generator)\n # The transformation of images is not under thread lock\n # so it can be done in parallel\n return self._get_batches_of_transformed_samples(index_array)\n"
] |
[
[
"numpy.rollaxis",
"numpy.dot",
"scipy.linalg.svd",
"numpy.sqrt",
"numpy.asarray",
"numpy.max",
"numpy.mean",
"numpy.random.randint",
"numpy.reshape",
"numpy.arange",
"numpy.stack",
"numpy.sin",
"numpy.copy",
"numpy.std",
"numpy.zeros",
"scipy.ndimage.interpolation.affine_transform",
"numpy.min",
"numpy.random.choice",
"numpy.array",
"numpy.random.random",
"numpy.random.seed",
"numpy.cos",
"numpy.random.permutation",
"numpy.isscalar",
"numpy.prod",
"numpy.random.uniform"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"0.14",
"0.15",
"0.12",
"0.10"
],
"tensorflow": []
}
] |
qiubit/openpilot
|
[
"013e49bf907539d119fbebcf02f4ce3749849065"
] |
[
"selfdrive/locationd/models/car_kf.py"
] |
[
"#!/usr/bin/env python3\nimport sys\n\nimport math\nimport numpy as np\nimport sympy as sp\n\nfrom selfdrive.locationd.models.constants import ObservationKind\nfrom rednose.helpers.ekf_sym import EKF_sym, gen_code\n\ni = 0\n\n\ndef _slice(n):\n global i\n s = slice(i, i + n)\n i += n\n\n return s\n\n\nclass States():\n # Vehicle model params\n STIFFNESS = _slice(1) # [-]\n STEER_RATIO = _slice(1) # [-]\n ANGLE_OFFSET = _slice(1) # [rad]\n ANGLE_OFFSET_FAST = _slice(1) # [rad]\n\n VELOCITY = _slice(2) # (x, y) [m/s]\n YAW_RATE = _slice(1) # [rad/s]\n STEER_ANGLE = _slice(1) # [rad]\n\n\nclass CarKalman():\n name = 'car'\n\n x_initial = np.array([\n 1.0,\n 15.0,\n 0.0,\n 0.0,\n\n 10.0, 0.0,\n 0.0,\n 0.0,\n ])\n\n # process noise\n Q = np.diag([\n (.05/100)**2,\n .01**2,\n math.radians(0.002)**2,\n math.radians(0.1)**2,\n\n .1**2, .01**2,\n math.radians(0.1)**2,\n math.radians(0.1)**2,\n ])\n P_initial = Q.copy()\n\n obs_noise = {\n ObservationKind.STEER_ANGLE: np.atleast_2d(math.radians(0.01)**2),\n ObservationKind.ANGLE_OFFSET_FAST: np.atleast_2d(math.radians(5.0)**2),\n ObservationKind.STEER_RATIO: np.atleast_2d(5.0**2),\n ObservationKind.STIFFNESS: np.atleast_2d(5.0**2),\n ObservationKind.ROAD_FRAME_X_SPEED: np.atleast_2d(0.1**2),\n }\n\n maha_test_kinds = [] # [ObservationKind.ROAD_FRAME_YAW_RATE, ObservationKind.ROAD_FRAME_XY_SPEED]\n global_vars = [\n sp.Symbol('mass'),\n sp.Symbol('rotational_inertia'),\n sp.Symbol('center_to_front'),\n sp.Symbol('center_to_rear'),\n sp.Symbol('stiffness_front'),\n sp.Symbol('stiffness_rear'),\n ]\n\n @staticmethod\n def generate_code(generated_dir):\n dim_state = CarKalman.x_initial.shape[0]\n name = CarKalman.name\n maha_test_kinds = CarKalman.maha_test_kinds\n\n # globals\n m, j, aF, aR, cF_orig, cR_orig = CarKalman.global_vars\n\n # make functions and jacobians with sympy\n # state variables\n state_sym = sp.MatrixSymbol('state', dim_state, 1)\n state = sp.Matrix(state_sym)\n\n # Vehicle model constants\n x = state[States.STIFFNESS, :][0, 0]\n\n cF, cR = x * cF_orig, x * cR_orig\n angle_offset = state[States.ANGLE_OFFSET, :][0, 0]\n angle_offset_fast = state[States.ANGLE_OFFSET_FAST, :][0, 0]\n sa = state[States.STEER_ANGLE, :][0, 0]\n\n sR = state[States.STEER_RATIO, :][0, 0]\n u, v = state[States.VELOCITY, :]\n r = state[States.YAW_RATE, :][0, 0]\n\n A = sp.Matrix(np.zeros((2, 2)))\n A[0, 0] = -(cF + cR) / (m * u)\n A[0, 1] = -(cF * aF - cR * aR) / (m * u) - u\n A[1, 0] = -(cF * aF - cR * aR) / (j * u)\n A[1, 1] = -(cF * aF**2 + cR * aR**2) / (j * u)\n\n B = sp.Matrix(np.zeros((2, 1)))\n B[0, 0] = cF / m / sR\n B[1, 0] = (cF * aF) / j / sR\n\n x = sp.Matrix([v, r]) # lateral velocity, yaw rate\n x_dot = A * x + B * (sa - angle_offset - angle_offset_fast)\n\n dt = sp.Symbol('dt')\n state_dot = sp.Matrix(np.zeros((dim_state, 1)))\n state_dot[States.VELOCITY.start + 1, 0] = x_dot[0]\n state_dot[States.YAW_RATE.start, 0] = x_dot[1]\n\n # Basic descretization, 1st order integrator\n # Can be pretty bad if dt is big\n f_sym = state + dt * state_dot\n\n #\n # Observation functions\n #\n obs_eqs = [\n [sp.Matrix([r]), ObservationKind.ROAD_FRAME_YAW_RATE, None],\n [sp.Matrix([u, v]), ObservationKind.ROAD_FRAME_XY_SPEED, None],\n [sp.Matrix([u]), ObservationKind.ROAD_FRAME_X_SPEED, None],\n [sp.Matrix([sa]), ObservationKind.STEER_ANGLE, None],\n [sp.Matrix([angle_offset_fast]), ObservationKind.ANGLE_OFFSET_FAST, None],\n [sp.Matrix([sR]), ObservationKind.STEER_RATIO, None],\n [sp.Matrix([x]), ObservationKind.STIFFNESS, None],\n ]\n\n gen_code(generated_dir, name, f_sym, dt, state_sym, obs_eqs, dim_state, dim_state, maha_test_kinds=maha_test_kinds, global_vars=CarKalman.global_vars)\n\n def __init__(self, generated_dir, steer_ratio=15, stiffness_factor=1, angle_offset=0):\n self.dim_state = self.x_initial.shape[0]\n x_init = self.x_initial\n x_init[States.STEER_RATIO] = steer_ratio\n x_init[States.STIFFNESS] = stiffness_factor\n x_init[States.ANGLE_OFFSET] = angle_offset\n\n # init filter\n self.filter = EKF_sym(generated_dir, self.name, self.Q, self.x_initial, self.P_initial, self.dim_state, self.dim_state, maha_test_kinds=self.maha_test_kinds, global_vars=self.global_vars)\n\n @property\n def x(self):\n return self.filter.state()\n\n @property\n def P(self):\n return self.filter.covs()\n\n def predict(self, t):\n return self.filter.predict(t)\n\n def rts_smooth(self, estimates):\n return self.filter.rts_smooth(estimates, norm_quats=False)\n\n def get_R(self, kind, n):\n obs_noise = self.obs_noise[kind]\n dim = obs_noise.shape[0]\n R = np.zeros((n, dim, dim))\n for i in range(n):\n R[i, :, :] = obs_noise\n return R\n\n def init_state(self, state, covs_diag=None, covs=None, filter_time=None):\n if covs_diag is not None:\n P = np.diag(covs_diag)\n elif covs is not None:\n P = covs\n else:\n P = self.filter.covs()\n self.filter.init_state(state, P, filter_time)\n\n def predict_and_observe(self, t, kind, data, R=None):\n if len(data) > 0:\n data = np.atleast_2d(data)\n\n if R is None:\n R = self.get_R(kind, len(data))\n\n self.filter.predict_and_update_batch(t, kind, data, R)\n\n\nif __name__ == \"__main__\":\n generated_dir = sys.argv[2]\n CarKalman.generate_code(generated_dir)\n"
] |
[
[
"numpy.diag",
"numpy.atleast_2d",
"numpy.array",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
SelectLOL1/BeagleBoneBlack_PRU_PowerMeter
|
[
"ee027e2713e1649ca7c4b68a737cd611695a6855",
"ee027e2713e1649ca7c4b68a737cd611695a6855"
] |
[
"RRDGraphs/rrd_1month.py",
"RRDGraphs/rrdintegral_8years.py"
] |
[
"import time\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdate\nimport numpy as np\nimport rrdtool\n\nstart = 2628000\nend = 0\n\nif int(end) <= 0:\n end = 2\nif int(start) <= 0:\n start = 600\n\nepochTimeNow = int(time.time()-1)\ndata = rrdtool.fetch('/home/bca/rrdtoolfilesave/powerCapturenew.rrd', 'AVERAGE',\n '--start', f'-{start}',\n '--end', f'-{end}')\n\nvalues = np.array(data[2])\nvalues[values == None] = 0\nepochEndTime = epochTimeNow - int(end)\nepochStartTime = epochTimeNow - int(start)\ntimeseries = np.zeros(shape=((epochEndTime-epochStartTime + 1), 1))\n\nfor i in range (epochEndTime - epochStartTime + 1):\n timeseries[i] = epochStartTime + 7200 + i\n\nfig, ax = plt.subplots()\ntimeseries = mdate.epoch2num(timeseries)\nax.plot_date(timeseries, values, linestyle = '-', marker = '', label=f'AllThePower')\ntimeseriesFormat = '%d-%m-%y %H:%M:%S'\ntimeseriesFormatted = mdate.DateFormatter(timeseriesFormat)\nax.xaxis.set_major_formatter(timeseriesFormatted)\nfig.autofmt_xdate()\nplt.ylim(bottom = 0)\nStartTime = time.strftime('%Y-%m-%d [%H:%M:%S]', time.localtime(epochStartTime))\nEndTime = time.strftime('%Y-%m-%d [%H:%M:%S]', time.localtime(epochEndTime))\nplt.ylabel('Watt')\n\nplt.title(f'Time range: {StartTime} - {EndTime}')\nplt.tight_layout()\nplt.legend()\nplt.show()\nplt.close()\n",
"import time\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdate\nimport numpy as np\nimport rrdtool\n\nstart = 252288000\nend = 0\n\nif int(end) <= 0:\n end = 2\nif int(start) <= 0:\n start = 600\n\nepochTimeNow = int(time.time()-1)\ndata = rrdtool.fetch('/home/bca/rrdtoolfilesave/powerCapturenew.rrd', 'AVERAGE',\n '--start', f'-{start}',\n '--end', f'-{end}')\n\nvalues = np.array(data[2])\nvalues[values == None] = 0\nepochEndTime = epochTimeNow - int(end)\nepochStartTime = epochTimeNow - int(start)\ntimeseries = np.zeros(shape=((epochEndTime-epochStartTime + 1), 1))\n\nfor i in range (epochEndTime - epochStartTime + 1):\n timeseries[i] = epochStartTime + 7200 + i\n\nfig, ax = plt.subplots()\ntimeseries = mdate.epoch2num(timeseries)\nax.plot_date(timeseries, values, linestyle = '-', marker = '', label=f'AllThePower')\ntimeseriesFormat = '%d-%m-%y %H:%M:%S'\ntimeseriesFormatted = mdate.DateFormatter(timeseriesFormat)\nax.xaxis.set_major_formatter(timeseriesFormatted)\nfig.autofmt_xdate()\nplt.ylim(bottom = 0)\nStartTime = time.strftime('%Y-%m-%d [%H:%M:%S]', time.localtime(epochStartTime))\nEndTime = time.strftime('%Y-%m-%d [%H:%M:%S]', time.localtime(epochEndTime))\nplt.ylabel('Watt')\n\nplt.title(f'Time range: {StartTime} - {EndTime}')\nplt.tight_layout()\nplt.legend()\nplt.show()\nplt.close()\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.dates.epoch2num",
"matplotlib.dates.DateFormatter",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.close",
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
],
[
"matplotlib.pyplot.legend",
"matplotlib.dates.epoch2num",
"matplotlib.dates.DateFormatter",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.close",
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
samiemostafavi/conditional-latency-probability-prediction
|
[
"a196f2db8c6f30f8613797b6a23bffd77a01e1e3"
] |
[
"plot_conditionals_with_tis.py"
] |
[
"import numpy as np\nimport pyarrow as pa\nimport pyarrow.parquet as pq\nimport pyarrow.compute as pc\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom pr3d.nonbayesian import ConditionalGammaEVM\n\n# load dataset first\nfile_addresses = ['dataset_onehop_processed.parquet']\ntable = pa.concat_tables(\n pq.read_table(\n file_address,columns=None,\n ) for file_address in file_addresses\n)\ndf = table.to_pandas()\nprint(df)\n\n# load the trained model\ndtype = 'float64'\nconditional_delay_model = ConditionalGammaEVM(\n h5_addr = \"onehop_tis_model.h5\",\n)\n\n# find n most common queue_length occurances\nn = 3\nvalues_count = df[['queue_length']].value_counts()[:n].index.tolist()\nprint(\"{0} most common queue states: {1}\".format(n,values_count))\n\n# divide the service delay into n segments based on quantiles\nm = 5\nservice_delays = np.squeeze(df[['service_delay']].to_numpy())\nquants = np.linspace(0, 1, num=m+1)\nintervals = [ (quant,quants[idx+1]) for idx, quant in enumerate(quants) if (idx+1)<len(quants) ]\nprint(\"{0} longer_delay_prob intervals: {1}\".format(n,intervals))\n\n#sns.set_palette(\"rocket\")\n\n# plot the conditional distributions of them\nfig, axes = plt.subplots(nrows=n, ncols=m, figsize=(m*4,n*4))\n\nfor i in range(n):\n for j in range(m):\n ax = axes[i,j]\n\n # take the empirical samples\n conditional_df = df[\n (df.queue_length==values_count[i][0]) & \n (df.longer_delay_prob>=intervals[j][0]) & \n (df.longer_delay_prob<intervals[j][1])\n ]\n\n # sample the predictor with x (conditions) from the empirical data\n X = np.squeeze(conditional_df[['queue_length','longer_delay_prob']].to_numpy())\n conditional_samples = conditional_delay_model.sample_n(\n x = X,\n random_generator=np.random.default_rng(0),\n )\n\n # insert it to the dataset\n conditional_df['predicted distribution'] = conditional_samples\n\n conditional_df.rename(columns = {'end2end_delay':'empirical distribution'}, inplace = True)\n\n # plot\n sns.histplot(\n conditional_df[['empirical distribution','predicted distribution']],\n kde=True, \n ax=ax,\n stat=\"density\",\n ).set(title=\"x={}, interval={}, count={}\".format(\n values_count[i],\n [\"{:0.2f}\".format(inter) for inter in intervals[j]],\n len(conditional_df))\n )\n ax.title.set_size(10)\n\n\nfig.tight_layout()\nplt.savefig('conditional_delay_tis.png')"
] |
[
[
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.subplots",
"numpy.linspace",
"numpy.random.default_rng"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mjhyman/bmtk
|
[
"42dcce944fe8ff8cab02b19d2d983f73a8cbc0d1",
"42dcce944fe8ff8cab02b19d2d983f73a8cbc0d1",
"42dcce944fe8ff8cab02b19d2d983f73a8cbc0d1",
"42dcce944fe8ff8cab02b19d2d983f73a8cbc0d1"
] |
[
"bmtk/utils/reports/spike_trains/plotting.py",
"bmtk/builder/network_adaptors/dm_network.py",
"bmtk/simulator/pointnet/glif_utils.py",
"bmtk/simulator/bionet/modules/record_clamp.py"
] |
[
"# Copyright 2020. Allen Institute. All rights reserved\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n# following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n# disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote\n# products derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\nimport numpy as np\nimport six\nimport matplotlib.pyplot as plt\nimport types\nimport copy\nfrom functools import partial\n\nfrom .spike_trains import SpikeTrains\nfrom .spike_trains_api import SpikeTrainsAPI\n\n\ndef __get_spike_trains(spike_trains):\n \"\"\"Make sure SpikeTrainsAPI object is always returned\"\"\"\n if isinstance(spike_trains, six.string_types):\n # Load spikes from file\n return SpikeTrains.load(spike_trains)\n\n elif isinstance(spike_trains, (SpikeTrains, SpikeTrainsAPI)):\n return spike_trains\n\n raise AttributeError('Could not parse spiketrains. Pass in file-path, SpikeTrains object, or list of the previous')\n\n\ndef __get_population(spike_trains, population):\n \"\"\"Helper function to figure out which population of nodes to use.\"\"\"\n pops = spike_trains.populations\n if population is None:\n # If only one population exists in spikes object/file select that one\n if len(pops) > 1:\n raise Exception('SpikeTrains contains more than one population of nodes. Use \"population\" parameter '\n 'to specify population to display.')\n\n else:\n return pops[0]\n\n elif population not in pops:\n raise Exception('Could not find node population \"{}\" in SpikeTrains, only found {}'.format(population, pops))\n\n else:\n return population\n\n\ndef __get_node_groups(spike_trains, node_groups, population):\n \"\"\"Helper function for parsing the 'node_groups' params\"\"\"\n if node_groups is None:\n # If none are specified by user make a 'node_group' consisting of all nodes\n selected_nodes = spike_trains.node_ids(population=population)\n return [{'node_ids': selected_nodes, 'c': 'b'}], selected_nodes\n else:\n # Fetch all node_ids which can be used to filter the data.\n node_groups = copy.deepcopy(node_groups) # Make a copy since later we may be altering the dictionary\n selected_nodes = np.array(node_groups[0]['node_ids'])\n for grp in node_groups[1:]:\n if 'node_ids' not in grp:\n raise AttributeError('Could not find \"node_ids\" key in node_groups parameter.')\n selected_nodes = np.concatenate((selected_nodes, np.array(grp['node_ids'])))\n\n return node_groups, selected_nodes\n\n\ndef plot_raster(spike_trains, with_histogram=True, population=None, node_groups=None, times=None, title=None,\n show=True, save_as=None):\n \"\"\"will create a raster plot (plus optional histogram) from a SpikeTrains object or SONATA Spike-Trains file. Will\n return the figure\n\n By default will display all nodes, if you want to only display a subset of nodes and/or group together different\n nodes (by node_id) by dot colors and labels then you can use the node_groups, which should be a list of dicts::\n\n plot_raster('/path/to/my/spike.h5',\n node_groups=[{'node_ids': range(0, 70), 'c': 'b', 'label': 'pyr'}, # first 70 nodes are blue pyr cells\n {'node_ids': range(70, 100), 'c': 'r', 'label': 'inh'}]) # last 30 nodes are red inh cells\n\n The histogram will not be grouped.\n\n :param spike_trains: SpikeTrains object or path to a (SONATA) spikes file.\n :param with_histogram: If True the a histogram will be shown as a small subplot below the scatter plot. Default\n True.\n :param population: string. If a spikes-file contains more than one population of nodes, use this to determine which\n nodes to actually plot. If only one population exists and population=None then the function will find it by\n default.\n :param node_groups: None or list of dicts. Used to group sets of nodes by labels and color. Each grouping should\n be a dictionary with a 'node_ids' key with a list of the ids. You can also add 'label' and 'c' keys for\n label and color. If None all nodes will be labeled and colored the same.\n :param times: (float, float). Used to set start and stop time. If not specified will try to find values from spiking\n data.\n :param title: str, Use to add a title. Default no tile\n :param show: bool to display or not display plot. default True.\n :param save_as: None or str: file-name/path to save the plot as a png/jpeg/etc. If None or empty string will not\n save plot.\n :return: matplotlib figure.Figure object\n \"\"\"\n\n spike_trains = __get_spike_trains(spike_trains=spike_trains)\n pop = __get_population(spike_trains=spike_trains, population=population)\n node_groups, selected_ids = __get_node_groups(spike_trains=spike_trains, node_groups=node_groups, population=pop)\n\n # Only show a legend if one of the node_groups have an explicit label, otherwise matplotlib will show an empty\n # legend box which looks bad\n show_legend = False\n\n # Situation where if the last (or first) M nodes don't spike matplotlib will cut off the y range, but it should\n # show these as empty rows. To do this need to keep track of range of all node_ids\n min_id, max_id = np.inf, -1\n\n spikes_df = spike_trains.to_dataframe(population=pop, with_population_col=False)\n spikes_df = spikes_df[spikes_df['node_ids'].isin(selected_ids)]\n if times is not None:\n min_ts, max_ts = times[0], times[1]\n spikes_df = spikes_df[(spikes_df['timestamps'] >= times[0]) & (spikes_df['timestamps'] <= times[1])]\n else:\n min_ts = np.min(spikes_df['timestamps'])\n max_ts = np.max(spikes_df['timestamps'])\n\n # Used to determine\n if with_histogram:\n fig, axes = plt.subplots(2, 1, gridspec_kw={'height_ratios': [7, 1]}, squeeze=True)\n raster_axes = axes[0]\n bottom_axes = hist_axes = axes[1]\n else:\n fig, axes = plt.subplots(1, 1)\n bottom_axes = raster_axes = axes\n hist_axes = None\n\n for node_grp in node_groups:\n grp_ids = node_grp.pop('node_ids')\n grp_spikes = spikes_df[spikes_df['node_ids'].isin(grp_ids)]\n\n # If label exists for at-least one group we want to show\n show_legend = show_legend or 'label' in node_grp\n\n # Finds min/max node_id for all node groups\n min_id = np.min([np.min(grp_ids), min_id])\n max_id = np.max([np.max(grp_ids), max_id])\n\n raster_axes.scatter(grp_spikes['timestamps'], grp_spikes['node_ids'], lw=0, s=8, **node_grp)\n\n if show_legend:\n raster_axes.legend(loc='upper right')\n\n if title:\n raster_axes.set_title(title)\n\n raster_axes.set_ylabel('node_ids')\n raster_axes.set_ylim(min_id - 0.5, max_id + 1) # add buffering to range else the rows at the ends look cut-off.\n raster_axes.set_xlim(min_ts, max_ts + 1)\n bottom_axes.set_xlabel('timestamps ({})'.format(spike_trains.units(population=pop)))\n\n if with_histogram:\n # Add a histogram if necessarry\n hist_axes.hist(spikes_df['timestamps'], 100)\n hist_axes.set_xlim(min_ts - 0.5, max_ts + 1)\n hist_axes.axes.get_yaxis().set_visible(False)\n raster_axes.set_xticks([])\n\n if save_as:\n plt.savefig(save_as)\n\n if show:\n plt.show()\n\n return fig\n\n\ndef moving_average(data, window_size=10):\n h = int(window_size / 2)\n x_max = len(data)\n return [np.mean(data[max(0, x - h):min(x_max, x + h)]) for x in range(0, x_max)]\n\n\ndef plot_rates(spike_trains, population=None, node_groups=None, times=None, smoothing=False,\n smoothing_params=None, title=None, show=True, save_as=None):\n \"\"\"Calculate and plot the rates of each node in a SpikeTrains object or SONATA Spike-Trains file. If start and stop\n times are not specified from the \"times\" parameter, will try to parse values from the timestamps data.\n\n If you want to only display a subset of nodes and/or group together different nodes (by node_id) by dot colors and\n labels then you can use the node_groups, which should be a list of dicts::\n\n plot_rates('/path/to/my/spike.h5',\n node_groups=[{'node_ids': range(0, 70), 'c': 'b', 'label': 'pyr'},\n {'node_ids': range(70, 100), 'c': 'r', 'label': 'inh'}])\n\n :param spike_trains: SpikeTrains object or path to a (SONATA) spikes file.\n :param population: string. If a spikes-file contains more than one population of nodes, use this to determine which\n nodes to actually plot. If only one population exists and population=None then the function will find it by\n default.\n :param node_groups: None or list of dicts. Used to group sets of nodes by labels and color. Each grouping should\n be a dictionary with a 'node_ids' key with a list of the ids. You can also add 'label' and 'c' keys for\n label and color. If None all nodes will be labeled and colored the same.\n :param times: (float, float). Used to set start and stop time. If not specified will try to find values from spiking\n data.\n :param smoothing: Bool or function. Used to smooth the data. By default (False) no smoothing will be done. If True\n will using a moving average smoothing function. Or use a function pointer.\n :param smoothing_params: dict, parameters when using a function pointer smoothing value.\n :param title: str, Use to add a title. Default no tile\n :param show: bool to display or not display plot. default True.\n :param save_as: None or str: file-name/path to save the plot as a png/jpeg/etc. If None or empty string will not\n save plot.\n :return: matplotlib figure.Figure object\n \"\"\"\n\n spike_trains = __get_spike_trains(spike_trains=spike_trains)\n pop = __get_population(spike_trains=spike_trains, population=population)\n node_groups, selected_ids = __get_node_groups(spike_trains=spike_trains, node_groups=node_groups, population=pop)\n\n # Determine if smoothing will be applied to the data\n smoothing_params = smoothing_params or {} # pass in empty parameters\n if isinstance(smoothing, types.FunctionType):\n smoothing_fnc = partial(smoothing, **smoothing_params)\n elif smoothing:\n smoothing_fnc = partial(moving_average, **smoothing_params)\n else:\n smoothing_fnc = lambda d: d # Use a filler function that won't do anything\n\n # get data\n spikes_df = spike_trains.to_dataframe(population=pop, with_population_col=False)\n spikes_df = spikes_df[spikes_df['node_ids'].isin(selected_ids)]\n if times is not None:\n recording_interval = times[1] - times[0]\n spikes_df = spikes_df[(spikes_df['timestamps'] >= times[0]) & (spikes_df['timestamps'] <= times[1])]\n else:\n recording_interval = np.max(spikes_df['timestamps']) - np.min(spikes_df['timestamps'])\n\n # Iterate through each group of nodes and add to the same plot\n fig, axes = plt.subplots()\n show_legend = False # Only show labels if one of the node group has label value\n for node_grp in node_groups:\n show_legend = show_legend or 'label' in node_grp # If label exists for at-least one group we want to show\n\n grp_ids = node_grp.pop('node_ids')\n grp_spikes = spikes_df[spikes_df['node_ids'].isin(grp_ids)]\n spike_rates = grp_spikes.groupby('node_ids').size() / (recording_interval / 1000.0)\n axes.plot(np.array(spike_rates.index), smoothing_fnc(spike_rates), '.', **node_grp)\n\n axes.set_ylabel('Firing Rates (Hz)')\n axes.set_xlabel('node_ids')\n if show_legend:\n axes.legend() # loc='upper right')\n\n if title:\n axes.set_title(title)\n\n if save_as:\n plt.savefig(save_as)\n\n if show:\n plt.show()\n\n return fig\n\n\ndef plot_rates_boxplot(spike_trains, population=None, node_groups=None, times=None, title=None, show=True,\n save_as=None):\n \"\"\"Creates a box plot of the firing rates taken from a SpikeTrains object or SONATA Spike-Trains file. If start\n and stop times are not specified from the \"times\" parameter, will try to parse values from the timestamps data.\n\n By default will plot all nodes together. To only display a subset of the nodes and/or create groups of nodes use\n the node_groups options::\n\n plot_rates_boxplot(\n '/path/to/my/spike.h5',\n node_groups=[{'node_ids': range(0, 70), 'label': 'pyr'},\n {'node_ids': range(70, 100), 'label': 'inh'}]\n )\n\n :param spike_trains: SpikeTrains object or path to a (SONATA) spikes file.\n :param population: string. If a spikes-file contains more than one population of nodes, use this to determine which\n nodes to actually plot. If only one population exists and population=None then the function will find it by\n default.\n :param node_groups: None or list of dicts. Used to group sets of nodes by labels and color. Each grouping should\n be a dictionary with a 'node_ids' key with a list of the ids. You can also add 'label' and 'c' keys for\n label and color. If None all nodes will be labeled and colored the same.\n :param title: str, Use to add a title. Default no tile\n :param show: bool to display or not display plot. default True.\n :param save_as: None or str: file-name/path to save the plot as a png/jpeg/etc. If None or empty string will not\n save plot.\n :return: matplotlib figure.Figure object\n \"\"\"\n spike_trains = __get_spike_trains(spike_trains=spike_trains)\n pop = __get_population(spike_trains=spike_trains, population=population)\n node_groups, selected_ids = __get_node_groups(spike_trains=spike_trains, node_groups=node_groups, population=pop)\n\n spikes_df = spike_trains.to_dataframe(population=pop, with_population_col=False)\n spikes_df = spikes_df[spikes_df['node_ids'].isin(selected_ids)]\n if times is not None:\n recording_interval = times[1] - times[0]\n spikes_df = spikes_df[(spikes_df['timestamps'] >= times[0]) & (spikes_df['timestamps'] <= times[1])]\n else:\n recording_interval = np.max(spikes_df['timestamps']) - np.min(spikes_df['timestamps'])\n\n fig, axes = plt.subplots()\n rates_data = []\n rates_labels = []\n\n if len(node_groups) == 1 and 'label' not in node_groups[0]:\n node_groups[0]['label'] = 'All Nodes'\n\n for i, node_grp in enumerate(node_groups):\n rates_labels.append(node_grp.get('label', 'Node Group {}'.format(i)))\n\n grp_ids = node_grp.pop('node_ids')\n grp_spikes = spikes_df[spikes_df['node_ids'].isin(grp_ids)]\n spike_rates = grp_spikes.groupby('node_ids').size() / (recording_interval / 1000.0)\n\n rates_data.append(spike_rates)\n\n axes.boxplot(rates_data)\n axes.set_ylabel('Firing Rates (Hz)')\n axes.set_xticklabels(rates_labels)\n\n if title:\n axes.set_title(title)\n\n if save_as:\n plt.savefig(save_as)\n\n if show:\n plt.show()\n\n return fig",
"# Copyright 2017. Allen Institute. All rights reserved\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n# following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n# disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote\n# products derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\nimport os\nimport numpy as np\nimport h5py\nimport logging\n\nfrom .network import Network\nfrom bmtk.builder.node import Node\nfrom bmtk.builder.edge import Edge\nfrom bmtk.utils import sonata\n\nfrom .edges_collator import EdgesCollator\nfrom .edge_props_table import EdgeTypesTable\nfrom ..index_builders import create_index_in_memory, create_index_on_disk\nfrom ..builder_utils import mpi_rank, mpi_size, barrier\nfrom ..edges_sorter import sort_edges\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass DenseNetwork(Network):\n def __init__(self, name, **network_props):\n super(DenseNetwork, self).__init__(name, **network_props or {})\n # self.__edges_types = {}\n # self.__src_mapping = {}\n # self.__networks = {}\n # self.__node_count = 0\n self._nodes = []\n self.__edges_tables = []\n self._target_networks = {}\n\n def _initialize(self):\n self.__id_map = []\n self.__lookup = []\n\n def _add_nodes(self, nodes):\n self._nodes.extend(nodes)\n self._nnodes = len(self._nodes)\n\n def edges_table(self):\n return self.__edges_tables\n\n def _save_nodes(self, nodes_file_name):\n if not self._nodes_built:\n self._build_nodes()\n\n # save the node_types file\n group_indx = 0\n groups_lookup = {}\n group_indicies = {}\n group_props = {}\n for ns in self._node_sets:\n if ns.params_hash in groups_lookup:\n continue\n else:\n groups_lookup[ns.params_hash] = group_indx\n group_indicies[group_indx] = 0\n group_props[group_indx] = {k: [] for k in ns.params_keys if k != 'node_id'}\n group_indx += 1\n\n node_gid_table = np.zeros(self._nnodes) # todo: set dtypes\n node_type_id_table = np.zeros(self._nnodes)\n node_group_table = np.zeros(self._nnodes)\n node_group_index_tables = np.zeros(self._nnodes)\n\n for i, node in enumerate(self.nodes()):\n node_gid_table[i] = node.node_id\n node_type_id_table[i] = node.node_type_id\n group_id = groups_lookup[node.params_hash]\n node_group_table[i] = group_id\n node_group_index_tables[i] = group_indicies[group_id]\n group_indicies[group_id] += 1\n\n group_dict = group_props[group_id]\n for key, prop_ds in group_dict.items():\n prop_ds.append(node.params[key])\n\n if mpi_rank == 0:\n with h5py.File(nodes_file_name, 'w') as hf:\n # Add magic and version attribute\n add_hdf5_attrs(hf)\n\n pop_grp = hf.create_group('/nodes/{}'.format(self.name))\n pop_grp.create_dataset('node_id', data=node_gid_table, dtype='uint64')\n pop_grp.create_dataset('node_type_id', data=node_type_id_table, dtype='uint64')\n pop_grp.create_dataset('node_group_id', data=node_group_table, dtype='uint32')\n pop_grp.create_dataset('node_group_index', data=node_group_index_tables, dtype='uint64')\n\n for grp_id, props in group_props.items():\n model_grp = pop_grp.create_group('{}'.format(grp_id))\n\n for key, dataset in props.items():\n try:\n model_grp.create_dataset(key, data=dataset)\n except TypeError:\n str_list = [str(d) for d in dataset]\n hf.create_dataset(key, data=str_list)\n barrier()\n\n def nodes_iter(self, node_ids=None):\n if node_ids is not None:\n return [n for n in self._nodes if n.node_id in node_ids]\n else:\n return self._nodes\n\n def _process_nodepool(self, nodepool):\n return nodepool\n\n def import_nodes(self, nodes_file_name, node_types_file_name, population=None):\n sonata_file = sonata.File(data_files=nodes_file_name, data_type_files=node_types_file_name)\n if sonata_file.nodes is None:\n raise Exception('nodes file {} does not have any nodes.'.format(nodes_file_name))\n\n populations = sonata_file.nodes.populations\n if len(populations) == 1:\n node_pop = populations[0]\n elif population is None:\n raise Exception('The nodes file {} contains multiple populations.'.format(nodes_file_name) +\n 'Please specify population parameter.')\n else:\n for pop in populations:\n if pop.name == population:\n node_pop = pop\n break\n else:\n raise Exception('Nodes file {} does not contain population {}.'.format(nodes_file_name, population))\n\n for node_type_props in node_pop.node_types_table:\n self._add_node_type(node_type_props)\n\n for node in node_pop:\n self._node_id_gen.remove_id(node.node_id)\n self._nodes.append(Node(node.node_id, node.group_props, node.node_type_properties))\n\n def _add_edges(self, connection_map, i):\n \"\"\"\n\n :param connection_map:\n :param i:\n \"\"\"\n edge_type_id = connection_map.edge_type_properties['edge_type_id']\n logger.debug('Generating edges data for edge_types_id {}.'.format(edge_type_id))\n edges_table = EdgeTypesTable(connection_map, network_name=self.name)\n connections = connection_map.connection_itr()\n\n # iterate through all possible SxT source/target pairs and use the user-defined function/list/value to update\n # the number of syns between each pair. TODO: See if this can be vectorized easily.\n for conn in connections:\n if conn[2]:\n edges_table.set_nsyns(source_id=conn[0], target_id=conn[1], nsyns=conn[2])\n\n target_net = connection_map.target_nodes\n self._target_networks[target_net.network_name] = target_net.network\n\n # For when the user specified individual edge properties to be put in the hdf5 (syn_weight, syn_location, etc),\n # get prop value and add it to the edge-types table. Need to fetch and store SxTxN value (where N is the avg\n # num of nsyns between each source/target pair) and it is necessary that the nsyns table be finished.\n for param in connection_map.params:\n rule = param.rule\n rets_multiple_vals = isinstance(param.names, (list, tuple, np.ndarray))\n\n if not rets_multiple_vals:\n prop_name = param.names # name of property\n prop_type = param.dtypes.get(prop_name, None)\n edges_table.create_property(prop_name=param.names, prop_type=prop_type) # initialize property array\n\n for source_node, target_node, edge_index in edges_table.iter_edges():\n # calls connection map rule and saves value to edge table\n pval = rule(source_node, target_node)\n edges_table.set_property_value(prop_name=prop_name, edge_index=edge_index, prop_value=pval)\n\n else:\n # Same as loop above, but some connection-map 'rules' will return multiple properties for each edge.\n pnames = param.names\n ptypes = [param.dtypes[pn] for pn in pnames]\n for prop_name, prop_type in zip(pnames, ptypes):\n edges_table.create_property(prop_name=prop_name, prop_type=prop_type) # initialize property arrays\n\n for source_node, target_node, edge_index in edges_table.iter_edges():\n pvals = rule(source_node, target_node)\n for pname, pval in zip(pnames, pvals):\n edges_table.set_property_value(prop_name=pname, edge_index=edge_index, prop_value=pval)\n\n logger.debug('Edge-types {} data built with {} connection ({} synapses)'.format(\n edge_type_id, edges_table.n_edges, edges_table.n_syns)\n )\n\n edges_table.save()\n\n # To EdgeTypesTable the number of synaptic/gap connections between all source/target paris, which can be more\n # than the number of actual edges stored (for efficency), may be a better user-representation.\n self._nedges += edges_table.n_syns # edges_table.n_edges\n self.__edges_tables.append(edges_table)\n\n def _get_edge_group_id(self, params_hash):\n return int(params_hash)\n\n def _save_gap_junctions(self, gj_file_name):\n source_ids = []\n target_ids = []\n src_gap_ids = []\n trg_gap_ids = []\n\n for et in self.__edges_tables:\n try:\n is_gap = et['edge_types']['is_gap_junction']\n except:\n continue\n if is_gap:\n if et['source_network'] != et['target_network']:\n raise Exception(\"All gap junctions must be two cells in the same network builder.\")\n\n table = et['syn_table']\n junc_table = table.nsyn_table\n locs = np.where(junc_table > 0)\n for i in range(len(locs[0])):\n source_ids.append(table.source_ids[locs[0][i]])\n target_ids.append(table.target_ids[locs[1][i]])\n src_gap_ids.append(self._gj_id_gen.next())\n trg_gap_ids.append(self._gj_id_gen.next())\n else:\n continue\n\n if len(source_ids) > 0:\n with h5py.File(gj_file_name, 'w') as f:\n add_hdf5_attrs(f)\n f.create_dataset('source_ids', data=np.array(source_ids))\n f.create_dataset('target_ids', data=np.array(target_ids))\n f.create_dataset('src_gap_ids', data=np.array(src_gap_ids))\n f.create_dataset('trg_gap_ids', data=np.array(trg_gap_ids))\n\n def _save_edges(self, edges_file_name, src_network, trg_network, pop_name=None, sort_by='target_node_id',\n index_by=('target_node_id', 'source_node_id')):\n barrier()\n\n if mpi_rank == 0:\n logger.debug('Saving {} --> {} edges to {}.'.format(src_network, trg_network, edges_file_name))\n\n filtered_edge_types = [\n # Some edges may not match the source/target population\n et for et in self.__edges_tables\n if et.source_network == src_network and et.target_network == trg_network\n ]\n\n merged_edges = EdgesCollator(filtered_edge_types, network_name=self.name)\n merged_edges.process()\n n_total_conns = merged_edges.n_total_edges\n barrier()\n\n if n_total_conns == 0:\n if mpi_rank == 0:\n logger.warning('Was not able to generate any edges using the \"connection_rule\". Not saving.')\n return\n\n # Try to sort before writing file, If edges are split across ranks/files for MPI/size issues then we need to\n # write to disk first then sort the hdf5 file\n sort_on_disk = False\n edges_file_name_final = edges_file_name\n if sort_by:\n if merged_edges.can_sort:\n merged_edges.sort(sort_by=sort_by)\n else:\n sort_on_disk = True\n edges_file_name_final = edges_file_name\n\n edges_file_basename = os.path.basename(edges_file_name)\n edges_file_dirname = os.path.dirname(edges_file_name)\n edges_file_name = os.path.join(edges_file_dirname, '.unsorted.{}'.format(edges_file_basename))\n if mpi_rank == 0:\n logger.debug('Unable to sort edges in memory, will temporarly save to {}'.format(edges_file_name) +\n ' before sorting hdf5 file.')\n barrier()\n\n if mpi_rank == 0:\n logger.debug('Saving {} edges to disk'.format(n_total_conns))\n pop_name = '{}_to_{}'.format(src_network, trg_network) if pop_name is None else pop_name\n with h5py.File(edges_file_name, 'w') as hf:\n # Initialize the hdf5 groups and datasets\n add_hdf5_attrs(hf)\n pop_grp = hf.create_group('/edges/{}'.format(pop_name))\n\n pop_grp.create_dataset('source_node_id', (n_total_conns,), dtype='uint64')\n pop_grp['source_node_id'].attrs['node_population'] = src_network\n pop_grp.create_dataset('target_node_id', (n_total_conns,), dtype='uint64')\n pop_grp['target_node_id'].attrs['node_population'] = trg_network\n pop_grp.create_dataset('edge_group_id', (n_total_conns,), dtype='uint16')\n pop_grp.create_dataset('edge_group_index', (n_total_conns,), dtype='uint32')\n pop_grp.create_dataset('edge_type_id', (n_total_conns,), dtype='uint32')\n\n for group_id in merged_edges.group_ids:\n # different model-groups will have different datasets/properties depending on what edge information\n # is being saved for each edges\n model_grp = pop_grp.create_group(str(group_id))\n for prop_mdata in merged_edges.get_group_metadata(group_id):\n model_grp.create_dataset(prop_mdata['name'], shape=prop_mdata['dim'], dtype=prop_mdata['type'])\n\n # Uses the collated edges (eg combined edges across all edge-types) to actually write the data to hdf5,\n # potentially in multiple chunks. For small networks doing it this way isn't very effiecent, however\n # this has the benefits:\n # * For very large networks it won't always be possible to store all the data in memory.\n # * When using MPI/multi-node the chunks can represent data from different ranks.\n for chunk_id, idx_beg, idx_end in merged_edges.itr_chunks():\n pop_grp['source_node_id'][idx_beg:idx_end] = merged_edges.get_source_node_ids(chunk_id)\n pop_grp['target_node_id'][idx_beg:idx_end] = merged_edges.get_target_node_ids(chunk_id)\n pop_grp['edge_type_id'][idx_beg:idx_end] = merged_edges.get_edge_type_ids(chunk_id)\n pop_grp['edge_group_id'][idx_beg:idx_end] = merged_edges.get_edge_group_ids(chunk_id)\n pop_grp['edge_group_index'][idx_beg:idx_end] = merged_edges.get_edge_group_indices(chunk_id)\n\n for group_id, prop_name, grp_idx_beg, grp_idx_end in merged_edges.get_group_data(chunk_id):\n prop_array = merged_edges.get_group_property(prop_name, group_id, chunk_id)\n pop_grp[str(group_id)][prop_name][grp_idx_beg:grp_idx_end] = prop_array\n\n if sort_on_disk:\n logger.debug('Sorting {} by {} to {}'.format(edges_file_name, sort_by, edges_file_name_final))\n sort_edges(\n input_edges_path=edges_file_name,\n output_edges_path=edges_file_name_final,\n edges_population='/edges/{}'.format(pop_name),\n sort_by=sort_by,\n # sort_on_disk=True,\n )\n try:\n logger.debug('Deleting intermediate edges file {}.'.format(edges_file_name))\n os.remove(edges_file_name)\n except OSError as e:\n logger.warning('Unable to remove intermediate edges file {}.'.format(edges_file_name))\n\n if index_by:\n index_by = index_by if isinstance(index_by, (list, tuple)) else [index_by]\n for index_type in index_by:\n logger.debug('Creating index {}'.format(index_type))\n create_index_in_memory(\n edges_file=edges_file_name_final,\n edges_population='/edges/{}'.format(pop_name),\n index_type=index_type\n )\n\n barrier()\n del merged_edges\n\n if mpi_rank == 0:\n logger.debug('Saving completed.')\n\n def _clear(self):\n self._nedges = 0\n self._nnodes = 0\n\n def edges_iter(self, trg_gids, src_network=None, trg_network=None):\n matching_edge_tables = self.__edges_tables\n if trg_network is not None:\n matching_edge_tables = [et for et in self.__edges_tables if et.target_network == trg_network]\n\n if src_network is not None:\n matching_edge_tables = [et for et in matching_edge_tables if et.source_network == src_network]\n\n for edge_type_table in matching_edge_tables:\n et_df = edge_type_table.to_dataframe()\n et_df = et_df[et_df['target_node_id'].isin(trg_gids)]\n if len(et_df) == 0:\n continue\n\n edge_type_props = edge_type_table.edge_type_properties\n for row in et_df.to_dict(orient='records'):\n yield Edge(\n src_gid=row['source_node_id'],\n trg_gid=row['target_node_id'],\n edge_type_props=edge_type_props,\n syn_props=row\n )\n\n @property\n def nnodes(self):\n if not self.nodes_built:\n return 0\n return self._nnodes\n\n @property\n def nedges(self):\n return self._nedges\n\n\ndef add_hdf5_attrs(hdf5_handle):\n # TODO: move this as a utility function\n hdf5_handle['/'].attrs['magic'] = np.uint32(0x0A7A)\n hdf5_handle['/'].attrs['version'] = [np.uint32(0), np.uint32(1)]\n",
"# Copyright 2017. Allen Institute. All rights reserved\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n# following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n# disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote\n# products derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\nimport numpy as np\nimport re\n\nfrom .nest_utils import nest_version\n\n# GLIFs are built-in NEST models in version 2.20 and above.\nver_major = nest_version[0]\nver_minor = nest_version[1] if nest_version[1] is not None else 0\nbuilt_in_glifs = ver_major >= 3 or (ver_major == 2 and ver_minor >= 20)\n\n\ndef lif_aibs_converter(config, tau_syn=[5.5, 8.5, 2.8, 5.8]):\n \"\"\"\n\n :param config:\n :return:\n \"\"\"\n coeffs = config['coeffs']\n params = {'V_th': coeffs['th_inf'] * config['th_inf'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'g': coeffs['G'] / config['R_input'] * 1.0e09,\n 'E_L': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'C_m': coeffs['C'] * config['C'] * 1.0e12,\n 't_ref': config['spike_cut_length'] * config['dt'] * 1.0e03,\n 'V_reset': config['El_reference'] * 1.0e03,\n 'tau_syn': tau_syn,\n 'V_dynamics_method': 'linear_exact'} # 'linear_forward_euler' or 'linear_exact'\n return params\n\n\ndef lif_asc_aibs_converter(config, tau_syn=[5.5, 8.5, 2.8, 5.8]):\n \"\"\"\n\n :param config:\n :return:\n \"\"\"\n coeffs = config['coeffs']\n params = {'V_th': coeffs['th_inf'] * config['th_inf'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'g': coeffs['G'] / config['R_input'] * 1.0e09,\n 'E_L': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'C_m': coeffs['C'] * config['C'] * 1.0e12,\n 't_ref': config['spike_cut_length'] * config['dt'] * 1.0e03,\n 'V_reset': config['El_reference'] * 1.0e03,\n 'asc_init': np.array(config['init_AScurrents']) * 1.0e12,\n 'k': 1.0 / np.array(config['asc_tau_array']) * 1.0e-03,\n 'tau_syn': tau_syn,\n 'asc_decay': 1.0 / np.array(config['asc_tau_array']) * 1.0e-03,\n 'asc_amps': np.array(config['asc_amp_array']) * np.array(coeffs['asc_amp_array']) * 1.0e12,\n 'V_dynamics_method': 'linear_exact'\n }\n return params\n\n\ndef lif_r_aibs_converter(config):\n \"\"\"\n\n :param config:\n :return:\n \"\"\"\n coeffs = config['coeffs']\n threshold_params = config['threshold_dynamics_method']['params']\n reset_params = config['voltage_reset_method']['params']\n params = {'V_th': coeffs['th_inf'] * config['th_inf'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'g': coeffs['G'] / config['R_input'] * 1.0e09,\n 'E_L': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'C_m': coeffs['C'] * config['C'] * 1.0e12,\n 't_ref': config['spike_cut_length'] * config['dt'] * 1.0e03,\n 'a_spike': threshold_params['a_spike'] * 1.0e03,\n 'b_spike': threshold_params['b_spike'] * 1.0e-03,\n 'a_reset': reset_params['a'],\n 'b_reset': reset_params['b'] * 1.0e03,\n 'V_dynamics_method': 'linear_exact'}\n return params\n\n\ndef lif_r_asc_aibs_converter(config):\n \"\"\"Creates a nest glif_lif_r_asc object\"\"\"\n coeffs = config['coeffs']\n threshold_params = config['threshold_dynamics_method']['params']\n reset_params = config['voltage_reset_method']['params']\n params={'V_th': coeffs['th_inf'] * config['th_inf'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'g': coeffs['G'] / config['R_input'] * 1.0e09,\n 'E_L': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'C_m': coeffs['C'] * config['C'] * 1.0e12,\n 't_ref': config['spike_cut_length'] * config['dt'] * 1.0e03,\n 'a_spike': threshold_params['a_spike'] * 1.0e03,\n 'b_spike': threshold_params['b_spike'] * 1.0e-03,\n 'a_reset': reset_params['a'],\n 'b_reset': reset_params['b'] * 1.0e03,\n 'asc_init': np.array(config['init_AScurrents']) * 1.0e12,\n 'k': 1.0 / np.array(config['asc_tau_array']) * 1.0e-03,\n 'asc_amps': np.array(config['asc_amp_array']) * np.array(coeffs['asc_amp_array']) * 1.0e12,\n 'V_dynamics_method': 'linear_exact'}\n return params\n\n\ndef lif_r_asc_a_aibs_converter(config):\n \"\"\"Creates a nest glif_lif_r_asc_a object\"\"\"\n coeffs = config['coeffs']\n threshold_params = config['threshold_dynamics_method']['params']\n reset_params = config['voltage_reset_method']['params']\n params = {'V_th': coeffs['th_inf'] * config['th_inf'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'g': coeffs['G'] / config['R_input'] * 1.0e09,\n 'E_L': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'C_m': coeffs['C'] * config['C'] * 1.0e12,\n 't_ref': config['spike_cut_length'] * config['dt'] * 1.0e03,\n 'a_spike': threshold_params['a_spike'] * 1.0e03,\n 'b_spike': threshold_params['b_spike'] * 1.0e-03,\n 'a_voltage': threshold_params['a_voltage'] * coeffs['a'] * 1.0e-03,\n 'b_voltage': threshold_params['b_voltage'] * coeffs['b'] * 1.0e-03,\n 'a_reset': reset_params['a'],\n 'b_reset': reset_params['b'] * 1.0e03,\n 'asc_init': np.array(config['init_AScurrents']) * 1.0e12,\n 'k': 1.0 / np.array(config['asc_tau_array']) * 1.0e-03,\n 'asc_amps': np.array(config['asc_amp_array']) * np.array(coeffs['asc_amp_array']) * 1.0e12,\n 'V_dynamics_method': 'linear_exact'}\n return params\n\n\n# synaptic ports testing\ndef lif_psc_aibs_converter(config, syn_tau=[5.5, 8.5, 2.8, 5.8]):\n \"\"\"Creates a nest glif_lif_psc object\"\"\"\n coeffs = config['coeffs']\n params = {'V_th': coeffs['th_inf'] * config['th_inf'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'g': coeffs['G'] / config['R_input'] * 1.0e09,\n 'E_L': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'C_m': coeffs['C'] * config['C'] * 1.0e12,\n 't_ref': config['spike_cut_length'] * config['dt'] * 1.0e03,\n 'V_reset': config['El_reference'] * 1.0e03,\n 'tau_syn': syn_tau, # in ms\n 'V_dynamics_method': 'linear_exact'} # 'linear_forward_euler' or 'linear_exact'\n return params\n\n\ndef lif_r_psc_aibs_converter(config, syn_tau=[5.5, 8.5, 2.8, 5.8]):\n \"\"\"Creates a nest glif_lif_r_psc object\"\"\"\n coeffs = config['coeffs']\n threshold_params = config['threshold_dynamics_method']['params']\n reset_params = config['voltage_reset_method']['params']\n params = {'V_th': coeffs['th_inf'] * config['th_inf'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'g': coeffs['G'] / config['R_input'] * 1.0e09,\n 'E_L': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'C_m': coeffs['C'] * config['C'] * 1.0e12,\n 't_ref': config['spike_cut_length'] * config['dt'] * 1.0e03,\n 'a_spike': threshold_params['a_spike'] * 1.0e03,\n 'b_spike': threshold_params['b_spike'] * 1.0e-03,\n 'a_reset': reset_params['a'],\n 'b_reset': reset_params['b'] * 1.0e03,\n 'tau_syn': syn_tau, # in ms\n 'V_dynamics_method': 'linear_exact'}\n return params\n\n\ndef lif_asc_psc_aibs_converter(config, syn_tau=[5.5, 8.5, 2.8, 5.8]):\n \"\"\"Creates a nest glif_lif_asc_psc object\"\"\"\n coeffs = config['coeffs']\n params={'V_th': coeffs['th_inf'] * config['th_inf'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'g': coeffs['G'] / config['R_input'] * 1.0e09,\n 'E_L': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'C_m': coeffs['C'] * config['C'] * 1.0e12,\n 't_ref': config['spike_cut_length'] * config['dt'] * 1.0e03,\n 'V_reset': config['El_reference'] * 1.0e03,\n 'asc_init': np.array(config['init_AScurrents']) * 1.0e12,\n 'k': 1.0 / np.array(config['asc_tau_array']) * 1.0e-03,\n 'asc_amps': np.array(config['asc_amp_array']) * np.array(coeffs['asc_amp_array']) * 1.0e12,\n 'tau_syn': syn_tau, # in ms\n 'V_dynamics_method': 'linear_exact'}\n return params\n\n\ndef lif_r_asc_psc_aibs_converter(config, syn_tau=[5.5, 8.5, 2.8, 5.8]):\n \"\"\"Creates a nest glif_lif_r_asc_psc object\"\"\"\n coeffs = config['coeffs']\n threshold_params = config['threshold_dynamics_method']['params']\n reset_params = config['voltage_reset_method']['params']\n params = {'V_th': coeffs['th_inf'] * config['th_inf'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'g': coeffs['G'] / config['R_input'] * 1.0e09,\n 'E_L': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'C_m': coeffs['C'] * config['C'] * 1.0e12,\n 't_ref': config['spike_cut_length'] * config['dt'] * 1.0e03,\n 'a_spike': threshold_params['a_spike'] * 1.0e03,\n 'b_spike': threshold_params['b_spike'] * 1.0e-03,\n 'a_reset': reset_params['a'],\n 'b_reset': reset_params['b'] * 1.0e03,\n 'asc_init': np.array(config['init_AScurrents']) * 1.0e12,\n 'k': 1.0 / np.array(config['asc_tau_array']) * 1.0e-03,\n 'asc_amps': np.array(config['asc_amp_array']) * np.array(coeffs['asc_amp_array']) * 1.0e12,\n 'tau_syn': syn_tau, # in ms\n 'V_dynamics_method': 'linear_exact'}\n return params\n\n\ndef lif_r_asc_a_psc_aibs_converter(config, syn_tau=[5.5, 8.5, 2.8, 5.8]):\n \"\"\"Creates a nest glif_lif_r_asc_a_psc object\"\"\"\n coeffs = config['coeffs']\n threshold_params = config['threshold_dynamics_method']['params']\n reset_params = config['voltage_reset_method']['params']\n params = {'V_th': coeffs['th_inf'] * config['th_inf'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'g': coeffs['G'] / config['R_input'] * 1.0e09,\n 'E_L': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'C_m': coeffs['C'] * config['C'] * 1.0e12,\n 't_ref': config['spike_cut_length'] * config['dt'] * 1.0e03,\n 'a_spike': threshold_params['a_spike'] * 1.0e03,\n 'b_spike': threshold_params['b_spike'] * 1.0e-03,\n 'a_voltage': threshold_params['a_voltage'] * coeffs['a'] * 1.0e-03,\n 'b_voltage': threshold_params['b_voltage'] * coeffs['b'] * 1.0e-03,\n 'a_reset': reset_params['a'],\n 'b_reset': reset_params['b'] * 1.0e03,\n 'asc_init': np.array(config['init_AScurrents']) * 1.0e12,\n 'k': 1.0 / np.array(config['asc_tau_array']) * 1.0e-03,\n 'asc_amps': np.array(config['asc_amp_array']) * np.array(coeffs['asc_amp_array']) * 1.0e12,\n 'tau_syn': syn_tau, # in ms\n 'V_dynamics_method': 'linear_exact'}\n return params\n\n\nconverter_map = {\n 'nest:glif_lif': lif_aibs_converter,\n 'nest:glif_lif_r': lif_r_aibs_converter,\n 'nest:glif_lif_asc': lif_asc_aibs_converter,\n 'nest:glif_lif_r_asc': lif_r_asc_aibs_converter,\n 'nest:glif_lif_r_asc_a': lif_r_asc_a_aibs_converter,\n 'nest:glif_lif_psc': lif_psc_aibs_converter,\n 'nest:glif_lif_r_psc': lif_r_psc_aibs_converter,\n 'nest:glif_lif_asc_psc': lif_asc_psc_aibs_converter,\n 'nest:glif_lif_r_asc_psc': lif_r_asc_psc_aibs_converter,\n 'nest:glif_lif_r_asc_a_psc': lif_r_asc_a_psc_aibs_converter\n}\n\n\ndef converter_modules(model_template, dynamics_params):\n if model_template in converter_map:\n return model_template, converter_map[model_template](dynamics_params)\n else:\n return model_template, dynamics_params\n\n\ndef converter_builtin(model_template, dynamics_params):\n if model_template == 'nest:glif_lif_psc':\n config = dynamics_params\n coeffs = config['coeffs']\n model_params = {\n 'V_m': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'V_th': coeffs['th_inf'] * config['th_inf'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'g': coeffs['G'] / config['R_input'] * 1.0e09,\n 'E_L': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'C_m': coeffs['C'] * config['C'] * 1.0e12,\n 't_ref': config['spike_cut_length'] * config['dt'] * 1.0e03,\n 'V_reset': config['El_reference'] * 1.0e03,\n 'tau_syn': np.array([5.5, 8.5, 2.8, 5.8]), # in ms\n 'spike_dependent_threshold': False,\n 'after_spike_currents': False,\n 'adapting_threshold': False\n }\n return 'nest:glif_psc', model_params\n\n elif model_template == 'nest:glif_lif_r_psc':\n config = dynamics_params\n coeffs = config['coeffs']\n threshold_params = config['threshold_dynamics_method']['params']\n reset_params = config['voltage_reset_method']['params']\n model_params = {\n 'V_m': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'V_th': coeffs['th_inf'] * config['th_inf'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'g': coeffs['G'] / config['R_input'] * 1.0e09,\n 'E_L': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'C_m': coeffs['C'] * config['C'] * 1.0e12,\n 't_ref': config['spike_cut_length'] * config['dt'] * 1.0e03,\n 'th_spike_add': threshold_params['a_spike'] * 1.0e03,\n 'th_spike_decay': threshold_params['b_spike'] * 1.0e-03,\n 'voltage_reset_fraction': reset_params['a'],\n 'voltage_reset_add': reset_params['b'] * 1.0e03,\n 'tau_syn': np.array([5.5, 8.5, 2.8, 5.8]), # in ms\n 'spike_dependent_threshold': True,\n 'after_spike_currents': False,\n 'adapting_threshold': False\n }\n return 'nest:glif_psc', model_params\n\n elif model_template == 'nest:glif_lif_asc_psc':\n config = dynamics_params\n coeffs = config['coeffs']\n model_params = {\n 'V_m': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'V_th': coeffs['th_inf'] * config['th_inf'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'g': coeffs['G'] / config['R_input'] * 1.0e09,\n 'E_L': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'C_m': coeffs['C'] * config['C'] * 1.0e12,\n 't_ref': config['spike_cut_length'] * config['dt'] * 1.0e03,\n 'V_reset': config['El_reference'] * 1.0e03,\n 'asc_init': np.array(config['init_AScurrents']) * 1.0e12,\n 'asc_decay': 1.0 / np.array(config['asc_tau_array']) * 1.0e-03,\n 'asc_amps': np.array(config['asc_amp_array']) * np.array(coeffs['asc_amp_array']) * 1.0e12,\n 'tau_syn': np.array([5.5, 8.5, 2.8, 5.8]), # in ms\n 'spike_dependent_threshold': False,\n 'after_spike_currents': True,\n 'adapting_threshold': False\n }\n return 'nest:glif_psc', model_params\n\n elif model_template == 'nest:glif_lif_r_asc_psc':\n config = dynamics_params\n coeffs = config['coeffs']\n threshold_params = config['threshold_dynamics_method']['params']\n reset_params = config['voltage_reset_method']['params']\n model_params = {\n 'V_m': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'V_th': coeffs['th_inf'] * config['th_inf'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'g': coeffs['G'] / config['R_input'] * 1.0e09,\n 'E_L': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'C_m': coeffs['C'] * config['C'] * 1.0e12,\n 't_ref': config['spike_cut_length'] * config['dt'] * 1.0e03,\n 'th_spike_add': threshold_params['a_spike'] * 1.0e03,\n 'th_spike_decay': threshold_params['b_spike'] * 1.0e-03,\n 'voltage_reset_fraction': reset_params['a'],\n 'voltage_reset_add': reset_params['b'] * 1.0e03,\n 'asc_init': np.array(config['init_AScurrents']) * 1.0e12,\n 'asc_decay': 1.0 / np.array(config['asc_tau_array']) * 1.0e-03,\n 'asc_amps': np.array(config['asc_amp_array']) * np.array(coeffs['asc_amp_array']) * 1.0e12,\n 'tau_syn': np.array([5.5, 8.5, 2.8, 5.8]),\n 'asc_r': (1.0, 1.0),\n 'spike_dependent_threshold': True,\n 'after_spike_currents': True,\n 'adapting_threshold': False\n }\n return 'nest:glif_psc', model_params\n\n elif model_template == 'nest:glif_lif_r_asc_a_psc':\n config = dynamics_params\n coeffs = config['coeffs']\n threshold_params = config['threshold_dynamics_method']['params']\n reset_params = config['voltage_reset_method']['params']\n model_params = {\n 'V_m': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'V_th': coeffs['th_inf'] * config['th_inf'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'g': coeffs['G'] / config['R_input'] * 1.0e09,\n 'E_L': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,\n 'C_m': coeffs['C'] * config['C'] * 1.0e12,\n 't_ref': config['spike_cut_length'] * config['dt'] * 1.0e03,\n 'th_spike_add': threshold_params['a_spike'] * 1.0e03,\n 'th_spike_decay': threshold_params['b_spike'] * 1.0e-03,\n 'th_voltage_index': threshold_params['a_voltage'] * coeffs['a'] * 1.0e-03,\n 'th_voltage_decay': threshold_params['b_voltage'] * coeffs['b'] * 1.0e-03,\n 'voltage_reset_fraction': reset_params['a'],\n 'voltage_reset_add': reset_params['b'] * 1.0e03,\n 'asc_init': np.array(config['init_AScurrents']) * 1.0e12,\n 'asc_decay': 1.0 / np.array(config['asc_tau_array']) * 1.0e-03,\n 'asc_amps': np.array(config['asc_amp_array']) * np.array(coeffs['asc_amp_array']) * 1.0e12,\n 'tau_syn': np.array([5.5, 8.5, 2.8, 5.8]),\n 'asc_r': (1.0, 1.0),\n 'spike_dependent_threshold': True,\n 'after_spike_currents': True,\n 'adapting_threshold': True\n }\n return 'nest:glif_psc', model_params\n\n else:\n return model_template, dynamics_params\n\n\nconvert_aibs2nest = converter_builtin if built_in_glifs else converter_modules",
"# Copyright 2017. Allen Institute. All rights reserved\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n# following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n# disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote\n# products derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\nimport os\nfrom neuron import h\nimport h5py\nimport numpy as np\n\nfrom bmtk.simulator.bionet.modules.sim_module import SimulatorMod\nfrom bmtk.utils.reports.current_writer import CurrentWriterv01\n\npc = h.ParallelContext()\nMPI_RANK = int(pc.id())\nN_HOSTS = int(pc.nhost())\n\n\nclass ClampReport(SimulatorMod):\n def __init__(self, tmp_dir, file_name, variable_name, buffer_data=True, **kwargs):\n \"\"\"Module used for saving NEURON clamp currents at each given step of the simulation.\n\n :param variable_name: which type of clamp it is a report of. As of now options are se, ic, and f_ic.\n :param clamps: indexes of the clamp list to make a report of.\n :param tmp_dir:\n :param file_name: name of h5 file to save variable to.\n :param buffer_data: Set to true then data will be saved to memory until written to disk during each block, reqs.\n more memory but faster. Set to false and data will be written to disk on each step (default: True)\n \"\"\"\n\n self._tmp_dir = tmp_dir\n\n self._file_name = file_name if os.path.isabs(file_name) else os.path.join(tmp_dir, file_name)\n\n if N_HOSTS > 1:\n self._tmp_files = []\n for i in range(N_HOSTS):\n tmp_name = variable_name + str(i)\n self._tmp_files.append(os.path.join(self._tmp_dir, tmp_name))\n self._rank_file = self._tmp_files[MPI_RANK]\n else:\n self._rank_file = self._file_name\n\n self._var_recorder = None\n self._variable_name = variable_name\n\n self._buffer_data = buffer_data\n \n @property\n def variable(self):\n return self._variable_name\n\n def initialize(self, sim, clamps):\n self._clamps = clamps\n\n self._var_recorder = CurrentWriterv01(self._rank_file, num_currents=len(self._clamps),\n buffer_size=sim.nsteps_block, buffer_data=self._buffer_data, tstart=0.0,\n tstop=sim.tstop, dt=sim.dt)\n\n self._var_recorder.initialize()\n\n def step(self, sim, tstep):\n # save the current of each clamp at the current time-step.\n vals = []\n for clamp in self._clamps:\n vals.append(clamp._stim.i)\n self._var_recorder.record_clamps(vals, tstep)\n\n def block(self, sim, block_interval):\n # write variables in memory to file\n self._var_recorder.flush()\n\n def finalize(self, sim):\n # TODO: Build in mpi signaling into var_recorder\n pc.barrier()\n self._var_recorder.close()\n\n if MPI_RANK == 0:\n self.merge()\n\n def merge(self):\n if N_HOSTS > 1:\n h5final = h5py.File(self._file_name, 'w')\n all_currents = []\n for i in range(N_HOSTS):\n tmp_file = h5py.File(self._tmp_files[i], 'r')\n data = tmp_file['data'][()]\n for current in data:\n if len(current) > 0:\n all_currents.append(current)\n tmp_file.close()\n os.remove(self._tmp_files[i])\n h5final.create_dataset('data', data=np.array(all_currents))\n h5final.close()\n\n"
] |
[
[
"numpy.min",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"numpy.max",
"numpy.array",
"matplotlib.pyplot.show"
],
[
"numpy.array",
"numpy.zeros",
"numpy.where",
"numpy.uint32"
],
[
"numpy.array"
],
[
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
0xtristan/deep-reinforcement-learning
|
[
"fb943ddb2796d85cc876ea076a26d850b7b87919"
] |
[
"dqn/exercise/dqn_agent.py"
] |
[
"import numpy as np\nimport random\nfrom collections import namedtuple, deque\n\nfrom model import QNetwork\n\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nBUFFER_SIZE = int(1e5) # replay buffer size\nBATCH_SIZE = 64 # minibatch size\nGAMMA = 0.99 # discount factor\nTAU = 1e-3 # for soft update of target parameters\nLR = 5e-4 # learning rate \nUPDATE_EVERY = 4 # how often to update the network\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nclass Agent():\n \"\"\"Interacts with and learns from the environment.\"\"\"\n\n def __init__(self, state_size, action_size, seed):\n \"\"\"Initialize an Agent object.\n \n Params\n ======\n state_size (int): dimension of each state\n action_size (int): dimension of each action\n seed (int): random seed\n \"\"\"\n self.state_size = state_size\n self.action_size = action_size\n self.seed = random.seed(seed)\n\n # Q-Network\n self.qnetwork_local = QNetwork(state_size, action_size, seed).to(device)\n self.qnetwork_target = QNetwork(state_size, action_size, seed).to(device)\n self.optimizer = optim.Adam(self.qnetwork_local.parameters(), lr=LR)\n\n # Replay memory\n self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, seed)\n # Initialize time step (for updating every UPDATE_EVERY steps)\n self.t_step = 0\n \n def step(self, state, action, reward, next_state, done):\n # Save experience in replay memory\n self.memory.add(state, action, reward, next_state, done)\n \n # Learn every UPDATE_EVERY time steps.\n self.t_step = (self.t_step + 1) % UPDATE_EVERY\n if self.t_step == 0:\n # If enough samples are available in memory, get random subset and learn\n if len(self.memory) > BATCH_SIZE:\n experiences = self.memory.sample()\n self.learn(experiences, GAMMA)\n\n def act(self, state, eps=0.):\n \"\"\"Returns actions for given state as per current policy.\n \n Params\n ======\n state (array_like): current state\n eps (float): epsilon, for epsilon-greedy action selection\n \"\"\"\n # from_numpy creates tensor without copying numpy array data\n # float == to(float), to() can be used for dtype and device conversions\n state = torch.from_numpy(state).float().unsqueeze(0).to(device)\n # eval mode as opposed to training (ignores dropout, batchnorm)\n self.qnetwork_local.eval()\n with torch.no_grad():\n # call the nn.Module rather than explicitly using nn.Module.forward()\n action_values = self.qnetwork_local(state)\n self.qnetwork_local.train()\n\n # Epsilon-greedy action selection\n if random.random() > eps:\n return np.argmax(action_values.cpu().data.numpy())\n else:\n return random.choice(np.arange(self.action_size))\n\n def learn(self, experiences, gamma):\n \"\"\"Update value parameters using given batch of experience tuples.\n\n Params\n ======\n experiences (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples \n gamma (float): discount factor\n \"\"\"\n states, actions, rewards, next_states, dones = experiences\n\n ## TODO: compute and minimize the loss\n \"*** YOUR CODE HERE ***\"\n # Max q value over all next actions given their next states (this is for a whole batch)\n # i.e. max_a(Q(s_{j+1}, a, w-)) from the one step look ahead\n Q_targets_next = self.qnetwork_local(next_states).detach().max(1)[0].unsqueeze(1)\n # Compute Q targets for current states\n Q_targets = rewards + gamma * Q_targets_next * (1 - dones) # set y_i = r if done\n # Get expected Q values from local model - used in gradient update as diff from target\n Q_expected = self.qnetwork_local(states).gather(1, actions)\n \n # Compute Loss\n loss = F.mse_loss(Q_expected, Q_targets)\n # Minimise loss by backprop\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n # ------------------- update target network ------------------- #\n self.soft_update(self.qnetwork_local, self.qnetwork_target, TAU) \n\n def soft_update(self, local_model, target_model, tau):\n \"\"\"Soft update model parameters.\n θ_target = τ*θ_local + (1 - τ)*θ_target\n\n Params\n ======\n local_model (PyTorch model): weights will be copied from\n target_model (PyTorch model): weights will be copied to\n tau (float): interpolation parameter \n \"\"\"\n for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):\n target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data)\n\n\nclass ReplayBuffer:\n \"\"\"Fixed-size buffer to store experience tuples.\"\"\"\n\n def __init__(self, action_size, buffer_size, batch_size, seed):\n \"\"\"Initialize a ReplayBuffer object.\n\n Params\n ======\n action_size (int): dimension of each action\n buffer_size (int): maximum size of buffer\n batch_size (int): size of each training batch\n seed (int): random seed\n \"\"\"\n self.action_size = action_size\n self.memory = deque(maxlen=buffer_size) \n self.batch_size = batch_size\n self.experience = namedtuple(\"Experience\", field_names=[\"state\", \"action\", \"reward\", \"next_state\", \"done\"])\n self.seed = random.seed(seed)\n \n def add(self, state, action, reward, next_state, done):\n \"\"\"Add a new experience to memory.\"\"\"\n e = self.experience(state, action, reward, next_state, done)\n self.memory.append(e)\n \n def sample(self):\n \"\"\"Randomly sample a batch of experiences from memory.\"\"\"\n experiences = random.sample(self.memory, k=self.batch_size)\n\n states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(device)\n actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).long().to(device)\n rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(device)\n next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences if e is not None])).float().to(device)\n dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(device)\n \n return (states, actions, rewards, next_states, dones)\n\n def __len__(self):\n \"\"\"Return the current size of internal memory.\"\"\"\n return len(self.memory)"
] |
[
[
"numpy.arange",
"torch.from_numpy",
"torch.nn.functional.mse_loss",
"torch.no_grad",
"torch.cuda.is_available",
"numpy.vstack"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
rgaensler/gcode
|
[
"c6a6b617a04490dedefb2bae7b596a2e12ab4ab1"
] |
[
"test/test_spatial_interpolation.py"
] |
[
"from math import pi, sqrt\nfrom typing import List\n\nimport numpy as np\nimport pytest\n\nfrom src.kinematics.forward_kinematics import get_tform\nfrom src.prechecks.spatial_interpolation import linear_interpolation, circular_interpolation\n\n\[email protected](\"start,end,ds,expected_points\",\n [\n (\n [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],\n [[0, 0, 0], [0, 0, 0], [0, 0, 0], [300, 0, 0]],\n 50,\n 7\n ),\n (\n [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],\n [[0, 0, 0], [0, 0, 0], [0, 0, 0], [50, 0, 0]],\n 50,\n 2\n )\n ]\n )\ndef test_linear_interpolation(start, end, ds, expected_points):\n # Create the start and end point matrices\n start = get_tform(*start)\n end = get_tform(*end)\n\n # Calculate the interpolated tforms\n interpolated_tforms = list(linear_interpolation(start, end, ds=ds))\n helper_spatial_interpolation_test(interpolated_tforms, start, end, expected_points)\n\n # Check that the points are equidistant\n if expected_points > 2:\n for i in range(expected_points - 1):\n ds_actual = np.linalg.norm(interpolated_tforms[i + 1][0:3, 3] - interpolated_tforms[i][0:3, 3])\n assert pytest.approx(ds, rel=0.1) == ds_actual\n\n\[email protected](\"start,end,nvec,cw,ds,expected_points\",\n [\n # XY plane half circle (start, intermediate, end)\n (\n [[1, 0, 0], [0, 1, 0], [0, 0, 1], [-1, 0, 0]],\n [[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0]],\n [0, 0, 1],\n True,\n pi / 2,\n 3\n ),\n # XY plane half circle (start, end)\n (\n [[1, 0, 0], [0, 1, 0], [0, 0, 1], [-1, 0, 0]],\n [[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0]],\n [0, 0, 1],\n True,\n pi,\n 2\n ),\n # XY plane half circle (start, end) rounded\n (\n [[1, 0, 0], [0, 1, 0], [0, 0, 1], [-1, 0, 0]],\n [[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0]],\n [0, 0, 1],\n True,\n pi / 2 * 1.1,\n 2\n ),\n # XY plane half circle (start, end) rounded\n (\n [[1, 0, 0], [0, 1, 0], [0, 0, 1], [-1, 0, 0]],\n [[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0]],\n [0, 0, 1],\n False,\n pi / 5,\n 6\n ),\n # XY plane 3/4 circle, five points\n (\n [[1, 0, 0], [0, 1, 0], [0, 0, 1], [-1, 0, 0]],\n [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, -1, 0]],\n [0, 0, 1],\n True,\n 6 / 16 * pi,\n 5\n ),\n # XY plane full circle, five points\n (\n [[1, 0, 0], [0, 1, 0], [0, 0, 1], [-1, 0, 0]],\n [[1, 0, 0], [0, 1, 0], [0, 0, 1], [-1, 0, 0]],\n [0, 0, 1],\n False,\n 2 / 3 * pi,\n 4\n ),\n # YZ plane 3/4 circle, five points\n (\n [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, -1, 0]],\n [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, -1]],\n [1, 0, 0],\n True,\n 6 / 16 * pi,\n 5\n ),\n # XY plane half circle (start, end) rounded\n (\n [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, -0.5 * sqrt(2), 0.5 * sqrt(2)]],\n [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0.5 * sqrt(2), -0.5 * sqrt(2)]],\n [0, 1, 1],\n False,\n pi / 5,\n 6\n )\n ]\n )\ndef test_circular_interpolation(start, end, nvec, cw, ds, expected_points):\n # Create the start and end point matrices\n start = get_tform(*start)\n end = get_tform(*end)\n\n # Calculate the interpolated tforms\n interpolated_tforms = list(circular_interpolation(start, end, [0, 0, 0], nvec, cw, ds=ds))\n print(interpolated_tforms)\n\n helper_spatial_interpolation_test(interpolated_tforms, start, end, expected_points)\n\n # Check that the points all have distance of the radius to the center point\n r = np.linalg.norm(start[0:3, 3])\n for tform in interpolated_tforms:\n assert pytest.approx(r, rel=0.01) == np.linalg.norm(tform[0:3, 3])\n\n # Check that the points are equidistant\n if expected_points > 3:\n ds_straight_line_ref = np.linalg.norm(interpolated_tforms[1][0:3, 3] - interpolated_tforms[0][0:3, 3])\n for i in range(1, expected_points - 1):\n ds_actual = np.linalg.norm(interpolated_tforms[i + 1][0:3, 3] - interpolated_tforms[i][0:3, 3])\n assert pytest.approx(ds_straight_line_ref, rel=0.1) == ds_actual\n\n\ndef helper_spatial_interpolation_test(interpolated_tforms: List[np.ndarray], start, end, expected_points):\n # Test that the number of interpolated points is correct\n assert len(interpolated_tforms) == expected_points\n\n # Test that the start and end points are included\n np.testing.assert_allclose(interpolated_tforms[0], start)\n np.testing.assert_allclose(interpolated_tforms[-1], end)\n"
] |
[
[
"numpy.linalg.norm",
"numpy.testing.assert_allclose"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jdmonaco/neuroswarms
|
[
"a2bfaa4e9b84baecdb41e01a32a028665e8886d7"
] |
[
"neuroswarms/matrix.py"
] |
[
"\"\"\"\nMatrix operations for neuroswarms models.\n\nAuthor: Joseph Monaco ([email protected])\nAffiliation: Johns Hopkins University\nCreated: 2019-05-12\nUpdated: 2020-11-16\n\nRelated paper:\n\n Monaco, J.D., Hwang, G.M., Schultz, K.M. et al. Cognitive swarming in complex\n environments with attractor dynamics and oscillatory computing. Biol Cybern\n 114, 269–284 (2020). https://doi.org/10.1007/s00422-020-00823-z\n\nThis software is provided AS IS under the terms of the Open Source MIT License.\nSee http://www.opensource.org/licenses/mit-license.php\n\"\"\"\n\n__all__ = ('tile_index', 'pairwise_tile_index', 'pairwise_distances',\n 'distances', 'pairwise_phasediffs', 'pairwise_unit_diffs',\n 'somatic_motion_update', 'reward_motion_update')\n\nfrom numpy import (empty, zeros, newaxis as AX, swapaxes, hypot, sin, inf,\n broadcast_arrays, broadcast_to)\n\nfrom .utils.types import *\n\n\nDEBUGGING = False\n\n\ndef _check_ndim(Mstr, M, ndim):\n assert M.ndim == ndim, f'{Mstr}.ndim != {ndim}'\n\ndef _check_shape(Mstr, M, shape, axis=None):\n if axis is None:\n assert M.shape == shape, f'{Mstr}.shape != {shape}'\n else:\n assert M.shape[axis] == shape, f'{Mstr}.shape[{axis}] != {shape}'\n\n\ndef tile_index(A, B):\n \"\"\"\n Entrywise comparison index of tile index (column) vectors.\n \"\"\"\n AA, BB = broadcast_arrays(A, B)\n if DEBUGGING:\n shape = (max(A.shape[0], B.shape[0]), 1)\n _check_shape('AA', AA, shape)\n _check_shape('BB', BB, shape)\n\n return (AA, BB)\n\ndef pairwise_tile_index(A, B):\n \"\"\"\n Pairwise comparison index of tile index (column) vectors.\n \"\"\"\n AA, BB = broadcast_arrays(A, B.T)\n if DEBUGGING:\n shape = (len(A), len(B))\n _check_shape('AA', AA, shape)\n _check_shape('BB', BB, shape)\n\n return (AA, BB)\n\ndef pairwise_phasediffs(A, B):\n \"\"\"\n Compute synchronizing phase differences between phase pairs.\n \"\"\"\n N_A = len(A)\n N_B = len(B)\n DD_shape = (N_A, N_B)\n if DEBUGGING:\n _check_ndim('A', A, 2)\n _check_ndim('B', B, 2)\n _check_shape('A', A, 1, axis=1)\n _check_shape('B', B, 1, axis=1)\n\n return B.T - A\n\ndef distances(A, B):\n \"\"\"\n Compute distances between points in entrywise order.\n \"\"\"\n AA, BB = broadcast_arrays(A, B)\n shape = AA.shape\n if DEBUGGING:\n _check_ndim('AA', AA, 2)\n _check_ndim('BB', BB, 2)\n _check_shape('AA', AA, 2, axis=1)\n _check_shape('BB', BB, 2, axis=1)\n\n return hypot(AA[:,0] - BB[:,0], AA[:,1] - BB[:,1])[:,AX]\n\ndef pairwise_unit_diffs(A, B):\n \"\"\"\n Compute attracting unit-vector differences between pairs of points.\n \"\"\"\n DD = pairwise_position_deltas(A, B)\n D_norm = hypot(DD[...,0], DD[...,1])\n nz = D_norm.nonzero()\n DD[nz] /= D_norm[nz][...,AX]\n return DD\n\ndef pairwise_distances(A, B):\n \"\"\"\n Compute distances between pairs of points.\n \"\"\"\n DD = pairwise_position_deltas(A, B)\n return hypot(DD[...,0], DD[...,1])\n\ndef pairwise_position_deltas(A, B):\n \"\"\"\n Compute attracting component deltas between pairs of points.\n \"\"\"\n N_A = len(A)\n N_B = len(B)\n if DEBUGGING:\n _check_ndim('A', A, 2)\n _check_ndim('B', B, 2)\n _check_shape('A', A, 2, axis=1)\n _check_shape('B', B, 2, axis=1)\n\n # Broadcast the first position matrix\n AA = empty((N_A,N_B,2), DISTANCE_DTYPE)\n AA[:] = A[:,AX,:]\n\n return B[AX,...] - AA\n\ndef somatic_motion_update(D_up, D_cur, X, V):\n \"\"\"\n Compute updated positions by averaging pairwise difference vectors for\n mutually visible pairs with equal bidirectional adjustments within each\n pair. The updated distance matrix does not need to be symmetric; it\n represents 'desired' updates based on recurrent learning.\n\n :D_up: R(N,N)-matrix of updated distances\n :D_cur: R(N,N)-matrix of current distances\n :X: R(N,2)-matrix of current positions\n :V: {0,1}(N,2)-matrix of current agent visibility\n :returns: R(N,2)-matrix of updated positions\n \"\"\"\n N = len(X)\n D_shape = (N, N)\n if DEBUGGING:\n _check_ndim('X', X, 2)\n _check_shape('X', X, 2, axis=1)\n _check_shape('D_up', D_up, D_shape)\n _check_shape('D_cur', D_cur, D_shape)\n _check_shape('V', V, D_shape)\n\n # Broadcast field position matrix and its transpose\n XX = empty((N,N,2))\n XX[:] = X[:,AX,:]\n XT = swapaxes(XX, 0, 1)\n\n # Find visible & valid values (i.e., corresponding to non-zero weights)\n #\n # NOTE: The normalizing factor is divided by 2 because the somatic update\n # represents one half of the change in distance between a pair of units.\n D_inf = D_up == inf\n norm = V * ~D_inf\n N = norm.sum(axis=1)\n valid = N.nonzero()[0]\n norm[valid] /= 2*N[valid,AX]\n\n # Zero out the inf elements of the updated distance matrix and corresponding\n # elements in the current distance matrix\n D_up[D_inf] = D_cur[D_inf] = 0.0\n\n # Construct the agent-agent avoidant unit vectors\n DX = XX - XT\n DX_norm = hypot(DX[...,0], DX[...,1])\n valid = DX_norm.nonzero()\n DX[valid] /= DX_norm[valid][:,AX]\n\n return (norm[...,AX]*(D_up - D_cur)[...,AX]*DX).sum(axis=1)\n\ndef reward_motion_update(D_up, D_cur, X, R, V):\n \"\"\"\n Compute updated positions by averaging reward-based unit vectors for\n adjustments of the point only. The updated distance matrix represents\n 'desired' updates based on reward learning.\n\n :D_up: R(N,N_R)-matrix of updated distances between points and rewards\n :D_cur: R(N,N_R)-matrix of current distances between points and rewards\n :X: R(N,2)-matrix of current point positions\n :R: R(N_R,2)-matrix of current reward positions\n :V: {0,1}(N_R,2)-matrix of current agent-reward visibility\n :returns: R(N,2)-matrix of updated positions\n \"\"\"\n N = len(X)\n N_R = len(R)\n D_shape = (N, N_R)\n if DEBUGGING:\n _check_ndim('X', X, 2)\n _check_ndim('R', R, 2)\n _check_shape('X', X, 2, axis=1)\n _check_shape('R', R, 2, axis=1)\n _check_shape('D_up', D_up, D_shape)\n _check_shape('D_cur', D_cur, D_shape)\n _check_shape('V', V, D_shape)\n\n # Broadcast field position matrix\n XX = empty((N,N_R,2))\n XX[:] = X[:,AX,:]\n\n # Find valid values (i.e., corresponding to non-zero weights)\n D_inf = D_up == inf\n norm = V * ~D_inf\n N = norm.sum(axis=1)\n valid = N.nonzero()[0]\n norm[valid] /= N[valid,AX]\n\n # Zero out the inf elements of the updated distance matrix and corresponding\n # elements in the current distance matrix\n D_up[D_inf] = D_cur[D_inf] = 0.0\n\n # Construct the agent-reward avoidant unit vectors\n DR = XX - R[AX]\n DR_norm = hypot(DR[...,0], DR[...,1])\n valid = DR_norm.nonzero()\n DR[valid] /= DR_norm[valid][:,AX]\n\n return (norm[...,AX]*(D_up - D_cur)[...,AX]*DR).sum(axis=1)\n"
] |
[
[
"numpy.empty",
"numpy.swapaxes",
"numpy.hypot",
"numpy.broadcast_arrays"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
hudua/azureml
|
[
"51f67380aa773184ef1710a3983ce017c29e68e8"
] |
[
"azure-ml-pipelines/pytorch/training-folder/pytorch_train.py"
] |
[
"\nfrom __future__ import print_function, division\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nfrom torchvision import datasets, models, transforms\nimport numpy as np\nimport time\nimport os\nimport copy\nimport argparse\n\nfrom azureml.core.run import Run\nfrom azureml.core import Dataset, Workspace\nfrom azureml.core.model import Model\n\n# get the Azure ML run object\nrun = Run.get_context()\nws = run.experiment.workspace\n\ndef load_data(data_dir):\n \"\"\"Load the train/val data.\"\"\"\n\n # Data augmentation and normalization for training\n # Just normalization for validation\n data_transforms = {\n 'train': transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ]),\n 'val': transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ]),\n }\n\n image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),\n data_transforms[x])\n for x in ['train', 'val']}\n dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=4,\n shuffle=True, num_workers=4)\n for x in ['train', 'val']}\n dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}\n class_names = image_datasets['train'].classes\n\n return dataloaders, dataset_sizes, class_names\n\n\ndef train_model(model, criterion, optimizer, scheduler, num_epochs, data_dir):\n \"\"\"Train the model.\"\"\"\n\n # load training/validation data\n dataloaders, dataset_sizes, class_names = load_data(data_dir)\n\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n since = time.time()\n\n best_model_wts = copy.deepcopy(model.state_dict())\n best_acc = 0.0\n\n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch, num_epochs - 1))\n print('-' * 10)\n\n # Each epoch has a training and validation phase\n for phase in ['train', 'val']:\n if phase == 'train':\n scheduler.step()\n model.train() # Set model to training mode\n else:\n model.eval() # Set model to evaluate mode\n\n running_loss = 0.0\n running_corrects = 0\n\n # Iterate over data.\n for inputs, labels in dataloaders[phase]:\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward\n # track history if only in train\n with torch.set_grad_enabled(phase == 'train'):\n outputs = model(inputs)\n _, preds = torch.max(outputs, 1)\n loss = criterion(outputs, labels)\n\n # backward + optimize only if in training phase\n if phase == 'train':\n loss.backward()\n optimizer.step()\n\n # statistics\n running_loss += loss.item() * inputs.size(0)\n running_corrects += torch.sum(preds == labels.data)\n\n epoch_loss = running_loss / dataset_sizes[phase]\n epoch_acc = running_corrects.double() / dataset_sizes[phase]\n\n print('{} Loss: {:.4f} Acc: {:.4f}'.format(\n phase, epoch_loss, epoch_acc))\n\n # deep copy the model\n if phase == 'val' and epoch_acc > best_acc:\n best_acc = epoch_acc\n best_model_wts = copy.deepcopy(model.state_dict())\n\n # log the best val accuracy to AML run\n run.log('best_val_acc', np.float(best_acc))\n\n print()\n\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(\n time_elapsed // 60, time_elapsed % 60))\n print('Best val Acc: {:4f}'.format(best_acc))\n\n # load best model weights\n model.load_state_dict(best_model_wts)\n return model\n\n\ndef fine_tune_model(num_epochs, data_dir, learning_rate, momentum):\n \"\"\"Load a pretrained model and reset the final fully connected layer.\"\"\"\n\n # log the hyperparameter metrics to the AML run\n run.log('lr', np.float(learning_rate))\n run.log('momentum', np.float(momentum))\n\n model_ft = models.resnet18(pretrained=True)\n num_ftrs = model_ft.fc.in_features\n model_ft.fc = nn.Linear(num_ftrs, 2) # only 2 classes to predict\n\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n model_ft = model_ft.to(device)\n\n criterion = nn.CrossEntropyLoss()\n\n # Observe that all parameters are being optimized\n optimizer_ft = optim.SGD(model_ft.parameters(),\n lr=learning_rate, momentum=momentum)\n\n # Decay LR by a factor of 0.1 every 7 epochs\n exp_lr_scheduler = lr_scheduler.StepLR(\n optimizer_ft, step_size=7, gamma=0.1)\n\n model = train_model(model_ft, criterion, optimizer_ft,\n exp_lr_scheduler, num_epochs, data_dir)\n\n return model\n\n\ndef download_data():\n dataset = Dataset.get_by_name(ws, name='pytorchdataset')\n dataset.download(target_path='fowl_data', overwrite=True)\n return 'fowl_data'\n\n# def download_data():\n# \"\"\"Download and extract the training data.\"\"\"\n# import urllib\n# from zipfile import ZipFile\n# # download data\n# data_file = './fowl_data.zip'\n# download_url = 'https://azureopendatastorage.blob.core.windows.net/testpublic/temp/fowl_data.zip'\n# urllib.request.urlretrieve(download_url, filename=data_file)\n\n# # extract files\n# with ZipFile(data_file, 'r') as zip:\n# print('extracting files...')\n# zip.extractall()\n# print('finished extracting')\n# data_dir = zip.namelist()[0]\n\n# # delete zip file\n# os.remove(data_file)\n# return data_dir\n\ndef main():\n import torch\n print(\"Torch version:\", torch.__version__)\n print(torch.cuda.is_available())\n \n # get command-line arguments\n parser = argparse.ArgumentParser()\n parser.add_argument('--num_epochs', type=int, default=25,\n help='number of epochs to train')\n parser.add_argument('--output_dir', type=str, help='output directory')\n parser.add_argument('--learning_rate', type=float,\n default=0.001, help='learning rate')\n parser.add_argument('--momentum', type=float, default=0.9, help='momentum')\n args = parser.parse_args()\n\n data_dir = download_data()\n print(\"data directory is: \" + data_dir)\n model = fine_tune_model(args.num_epochs, data_dir,\n args.learning_rate, args.momentum)\n os.makedirs(args.output_dir, exist_ok=True)\n torch.save(model, os.path.join(args.output_dir, 'model.pt'))\n\n model = Model.register(model_name='my_model', model_path=os.path.join(args.output_dir, 'model.pt'), workspace = ws)\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.max",
"torch.utils.data.DataLoader",
"torch.sum",
"torch.nn.Linear",
"torch.set_grad_enabled",
"torch.cuda.is_available",
"numpy.float",
"torch.optim.lr_scheduler.StepLR"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
SantiLJ/strategy-template
|
[
"28ec389a7ebac93e85e07b5310976bb08445f230"
] |
[
"app.py"
] |
[
"# Fetches and displays a basic candlestick app.\r\n\r\nimport dash\r\nimport plotly.graph_objects as go\r\nimport plotly.express as px\r\nimport dash_core_components as dcc\r\nimport dash_html_components as html\r\nfrom dash_table import DataTable, FormatTemplate\r\nfrom utils import *\r\nfrom datetime import date, timedelta\r\nfrom math import ceil\r\nfrom backtest import *\r\nfrom bloomberg_functions import req_historical_data\r\nimport numpy as np\r\nfrom sklearn import linear_model\r\nfrom statistics import mean\r\n\r\n# Create a Dash app\r\napp = dash.Dash(__name__)\r\n\r\n# Create the page layout\r\napp.layout = html.Div([\r\n html.H1(\r\n 'Trading Strategy Example Template',\r\n style={'display': 'block', 'text-align': 'center'}\r\n ),\r\n html.Div([\r\n html.H2('Strategy'),\r\n html.P('This app explores a simple strategy that works as follows:'),\r\n html.Ol([\r\n html.Li([\r\n \"While the market is not open, retrieve the past N days' \" + \\\r\n \"worth of data for:\",\r\n html.Ul([\r\n html.Li(\"IVV: daily open, high, low, & close prices\"),\r\n html.Li(\r\n \"US Treasury CMT Rates for 1 mo, 2 mo, 3 mo, 6 mo, \" + \\\r\n \"1 yr and 2 yr maturities.\"\r\n )\r\n ])\r\n ]),\r\n html.Li([\r\n 'Fit a linear trend line through the yield curve defined ' + \\\r\n 'by the CMT rates and record in a dataframe:',\r\n html.Ul([\r\n html.Li('the y-intercept (\"a\")'),\r\n html.Li('the slope (\"b\")'),\r\n html.Li('the coefficient of determination (\"R^2\")')\r\n ]),\r\n '...for the fitted line.'\r\n ]),\r\n html.Li(\r\n 'Repeat 2. for past CMT data to create a FEATURES ' + \\\r\n 'dataframe containing historical values of a, b, and R^2 '\r\n ),\r\n html.Li(\r\n 'Add volatility of day-over-day log returns of IVV ' + \\\r\n 'closing prices -- observed over the past N days -- to ' + \\\r\n 'each historical data row in the FEATURES dataframe.'\r\n ),\r\n html.Li(\r\n 'Add RESPONSE data to the historical FEATURES dataframe.' + \\\r\n 'The RESPONSE data includes information that communicates ' + \\\r\n 'whether when, and how a limit order to SELL IVV at a ' + \\\r\n 'price equal to (IVV Open Price of Next Trading Day) * ' + \\\r\n '(1 + alpha) would have filled over the next n trading days.'\r\n ),\r\n html.Li(\r\n 'Using the features a, b, R^2, and IVV vol alongside the ' + \\\r\n 'RESPONSE data for the past N observed trading days, ' + \\\r\n 'train a logistic regression. Use it to predict whether a ' + \\\r\n 'limit order to SELL IVV at a price equal to (IVV Open ' + \\\r\n 'Price of Next Trading Day) * (1 + alpha) would have ' + \\\r\n 'filled over the next n trading days.'\r\n ),\r\n html.Li(\r\n 'If the regression in 6. predicts TRUE, submit two trades:'),\r\n html.Ul([\r\n html.Li(\r\n 'A market order to BUY lot_size shares of IVV, which ' + \\\r\n 'fills at open price the next trading day.'\r\n ),\r\n html.Li(\r\n 'A limit order to SELL lot_size shares of IVV at ' + \\\r\n '(next day\\'s opening price * (1+alpha)'\r\n )\r\n ]),\r\n html.Li(\r\n 'If the limit order does not fill after n days, issue a ' + \\\r\n 'market order to sell lot_size shares of IVV at close of ' + \\\r\n 'the nth day.'\r\n )\r\n ])\r\n ],\r\n style={'display': 'inline-block', 'width': '50%'}\r\n ),\r\n html.Div([\r\n html.H2('Data Note & Disclaimer'),\r\n html.P(\r\n 'This Dash app makes use of Bloomberg\\'s Python API to append ' + \\\r\n 'the latest historical data to what\\'s already provided in the ' + \\\r\n '.csv files in the directory \\'bbg_data\\'. These initial data ' + \\\r\n 'files were compiled using publicly available information on ' + \\\r\n 'the Internet and do not contain historical stock market data ' + \\\r\n 'from Bloomberg. This app does NOT need a Bloomberg ' + \\\r\n 'subscription to work -- only to update data. Always know and ' + \\\r\n 'obey your data stewardship obligations!'\r\n ),\r\n html.H2('Parameters'),\r\n html.Ol([\r\n html.Li(\r\n \"n: number of days a limit order to exit a position is \" + \\\r\n \"kept open\"\r\n ),\r\n html.Li(\r\n \"N: number of observed historical trading days to use in \" + \\\r\n \"training the logistic regression model.\"\r\n ),\r\n html.Li(\r\n 'alpha: a percentage in numeric form ' + \\\r\n '(e.g., \"0.02\" == \"2%\") that defines the profit sought by ' + \\\r\n 'entering a trade; for example, if IVV is bought at ' + \\\r\n 'price X, then a limit order to sell the shares will be put' + \\\r\n ' in place at a price = X*(1+alpha)'\r\n ),\r\n html.Li(\r\n 'lot_size: number of shares traded in each round-trip ' + \\\r\n 'trade. Kept constant for simplicity.'\r\n ),\r\n html.Li(\r\n 'date_range: Date range over which to perform the backtest.'\r\n )\r\n ]),\r\n html.Div(\r\n [\r\n html.Div(\r\n [\r\n html.Button(\r\n \"RUN BACKTEST\", id='run-backtest', n_clicks=0\r\n ),\r\n html.Table(\r\n [html.Tr([\r\n html.Th('Alpha'), html.Th('Beta'),\r\n html.Th('Geometric Mean Return'),\r\n html.Th('Average Trades per Year'),\r\n html.Th('Volatility'), html.Th('Sharpe')\r\n ])] + [html.Tr([\r\n html.Td(html.Div(id='strategy-alpha')),\r\n html.Td(html.Div(id='strategy-beta')),\r\n html.Td(html.Div(id='strategy-gmrr')),\r\n html.Td(html.Div(id='strategy-trades-per-yr')),\r\n html.Td(html.Div(id='strategy-vol')),\r\n html.Td(html.Div(id='strategy-sharpe'))\r\n ])],\r\n className='main-summary-table'\r\n ),\r\n html.Table(\r\n # Header\r\n [html.Tr([\r\n html.Th('Date Range'),\r\n html.Th('Bloomberg Identifier'),\r\n html.Th('n'), html.Th('N'), html.Th('alpha'),\r\n html.Th('Lot Size'),\r\n html.Th('Starting Cash')\r\n ])] +\r\n # Body\r\n [html.Tr([\r\n html.Td(\r\n dcc.DatePickerRange(\r\n id='hist-data-range',\r\n min_date_allowed=date(2015, 1, 1),\r\n max_date_allowed=date.today(),\r\n initial_visible_month=date.today(),\r\n start_date=date(2019, 3, 16),\r\n end_date=date(2021, 4, 12)\r\n )\r\n ),\r\n html.Td(dcc.Input(\r\n id='bbg-identifier-1', type=\"text\",\r\n value=\"IVV US Equity\",\r\n style={'text-align': 'center'}\r\n )),\r\n html.Td(\r\n dcc.Input(\r\n id='lil-n', type=\"number\", value=5,\r\n style={'text-align': 'center',\r\n 'width': '30px'}\r\n )\r\n ),\r\n html.Td(\r\n dcc.Input(\r\n id='big-N', type=\"number\", value=10,\r\n style={'text-align': 'center',\r\n 'width': '50px'}\r\n )\r\n ),\r\n html.Td(\r\n dcc.Input(\r\n id=\"alpha\", type=\"number\", value=0.02,\r\n style={'text-align': 'center',\r\n 'width': '50px'}\r\n )\r\n ),\r\n html.Td(\r\n dcc.Input(\r\n id=\"lot-size\", type=\"number\", value=100,\r\n style={'text-align': 'center',\r\n 'width': '50px'}\r\n )\r\n ),\r\n html.Td(\r\n dcc.Input(\r\n id=\"starting-cash\", type=\"number\",\r\n value=50000,\r\n style={'text-align': 'center',\r\n 'width': '100px'}\r\n )\r\n )\r\n ])]\r\n )\r\n ],\r\n style={'display': 'inline-block', 'width': '50%'}\r\n )\r\n ],\r\n style={'display': 'block'}\r\n )\r\n ],\r\n style={\r\n 'display': 'inline-block', 'width': '50%', 'vertical-align': 'top'\r\n }\r\n ),\r\n ##### Intermediate Variables (hidden in divs as JSON) ######################\r\n ############################################################################\r\n # Hidden div inside the app that stores IVV historical data\r\n html.Div(id='ivv-hist', style={'display': 'none'}),\r\n # Hidden div inside the app that stores bonds historical data\r\n html.Div(id='bonds-hist', style={'display': 'none'}),\r\n ############################################################################\r\n ############################################################################\r\n html.Div(\r\n [dcc.Graph(id='alpha-beta')],\r\n style={'display': 'inline-block', 'width': '50%'}\r\n ),\r\n # Display the current selected date range\r\n html.Div(id='date-range-output'),\r\n html.Div([\r\n html.H2(\r\n 'Trade Ledger',\r\n style={\r\n 'display': 'inline-block', 'text-align': 'center',\r\n 'width': '100%'\r\n }\r\n ),\r\n DataTable(\r\n id='trade-ledger',\r\n fixed_rows={'headers': True},\r\n style_cell={'textAlign': 'center'},\r\n style_table={'height': '300px', 'overflowY': 'auto'}\r\n )\r\n ]),\r\n html.Div([\r\n html.Div([\r\n html.H2(\r\n 'Calendar Ledger',\r\n style={\r\n 'display': 'inline-block', 'width': '45%',\r\n 'text-align': 'center'\r\n }\r\n ),\r\n html.H2(\r\n 'Trade Blotter',\r\n style={\r\n 'display': 'inline-block', 'width': '55%',\r\n 'text-align': 'center'\r\n }\r\n )\r\n ]),\r\n html.Div(\r\n DataTable(\r\n id='calendar-ledger',\r\n fixed_rows={'headers': True},\r\n style_cell={'textAlign': 'center'},\r\n style_table={'height': '300px', 'overflowY': 'auto'}\r\n ),\r\n style={'display': 'inline-block', 'width': '45%'}\r\n ),\r\n html.Div(\r\n DataTable(\r\n id='blotter',\r\n fixed_rows={'headers': True},\r\n style_cell={'textAlign': 'center'},\r\n style_table={'height': '300px', 'overflowY': 'auto'}\r\n ),\r\n style={'display': 'inline-block', 'width': '55%'}\r\n )\r\n ]),\r\n html.Div([\r\n html.H2(\r\n 'Features and Responses',\r\n style={\r\n 'display': 'inline-block', 'text-align': 'center',\r\n 'width': '100%'\r\n }\r\n ),\r\n DataTable(\r\n id='features-and-responses',\r\n fixed_rows={'headers': True},\r\n style_cell={'textAlign': 'center'},\r\n style_table={'height': '300px', 'overflowY': 'auto'}\r\n )\r\n ]),\r\n html.Div([\r\n html.Div(\r\n dcc.Graph(id='bonds-3d-graph', style={'display': 'none'}),\r\n style={'display': 'inline-block', 'width': '50%'}\r\n ),\r\n html.Div(\r\n dcc.Graph(id='candlestick', style={'display': 'none'}),\r\n style={'display': 'inline-block', 'width': '50%'}\r\n )\r\n ]),\r\n html.Div(id='proposed-trade'),\r\n ############################################################################\r\n ############################################################################\r\n])\r\n\r\n\r\[email protected](\r\n #### Update Historical Bloomberg Data\r\n [dash.dependencies.Output('ivv-hist', 'children'),\r\n dash.dependencies.Output('date-range-output', 'children'),\r\n dash.dependencies.Output('candlestick', 'figure'),\r\n dash.dependencies.Output('candlestick', 'style')],\r\n dash.dependencies.Input(\"run-backtest\", 'n_clicks'),\r\n [dash.dependencies.State(\"bbg-identifier-1\", \"value\"),\r\n dash.dependencies.State(\"big-N\", \"value\"),\r\n dash.dependencies.State(\"lil-n\", \"value\"),\r\n dash.dependencies.State('hist-data-range', 'start_date'),\r\n dash.dependencies.State('hist-data-range', 'end_date')],\r\n prevent_initial_call=True\r\n)\r\ndef update_bbg_data(nclicks, bbg_id_1, N, n, start_date, end_date):\r\n # Need to query enough days to run the backtest on every date in the\r\n # range start_date to end_date\r\n start_date = pd.to_datetime(start_date).date() - timedelta(\r\n days=ceil((N + n) * (365 / 252))\r\n )\r\n start_date = start_date.strftime(\"%Y-%m-%d\")\r\n\r\n historical_data = req_historical_data(bbg_id_1, start_date, end_date)\r\n\r\n date_output_msg = 'Backtesting from '\r\n\r\n if start_date is not None:\r\n start_date_object = date.fromisoformat(start_date)\r\n start_date_string = start_date_object.strftime('%B %d, %Y')\r\n date_output_msg = date_output_msg + 'Start Date: ' + \\\r\n start_date_string + ' to '\r\n\r\n if end_date is not None:\r\n end_date_object = date.fromisoformat(end_date)\r\n end_date_string = end_date_object.strftime('%B %d, %Y')\r\n date_output_msg = date_output_msg + 'End Date: ' + end_date_string\r\n if len(date_output_msg) == len('You have selected: '):\r\n date_output_msg = 'Select a date to see it displayed here'\r\n\r\n fig = go.Figure(\r\n data=[\r\n go.Candlestick(\r\n x=historical_data['Date'],\r\n open=historical_data['Open'],\r\n high=historical_data['High'],\r\n low=historical_data['Low'],\r\n close=historical_data['Close']\r\n )\r\n ]\r\n )\r\n\r\n return historical_data.to_json(), date_output_msg, fig, {'display': 'block'}\r\n\r\n\r\[email protected](\r\n [dash.dependencies.Output('bonds-hist', 'children'),\r\n dash.dependencies.Output('bonds-3d-graph', 'figure'),\r\n dash.dependencies.Output('bonds-3d-graph', 'style')],\r\n dash.dependencies.Input(\"run-backtest\", 'n_clicks'),\r\n [dash.dependencies.State('hist-data-range', 'start_date'),\r\n dash.dependencies.State('hist-data-range', 'end_date'),\r\n dash.dependencies.State('big-N', 'value'),\r\n dash.dependencies.State('lil-n', 'value')\r\n ],\r\n prevent_initial_call=True\r\n)\r\ndef update_bonds_hist(n_clicks, startDate, endDate, N, n):\r\n # Need to query enough days to run the backtest on every date in the\r\n # range start_date to end_date\r\n startDate = pd.to_datetime(startDate).date() - timedelta(\r\n days=ceil((N + n) * (365 / 252))\r\n )\r\n startDate = startDate.strftime(\"%Y-%m-%d\")\r\n\r\n data_years = list(\r\n range(pd.to_datetime(startDate).date().year,\r\n pd.to_datetime(endDate).date().year + 1, 1)\r\n )\r\n\r\n bonds_data = fetch_usdt_rates(data_years[0])\r\n\r\n if len(data_years) > 1:\r\n for year in data_years[1:]:\r\n bonds_data = pd.concat([bonds_data, fetch_usdt_rates(year)],\r\n axis=0, ignore_index=True)\r\n\r\n # How to filter a dataframe for rows that you want\r\n bonds_data = bonds_data[bonds_data.Date >= pd.to_datetime(startDate)]\r\n bonds_data = bonds_data[bonds_data.Date <= pd.to_datetime(endDate)]\r\n\r\n fig = go.Figure(\r\n data=[\r\n go.Surface(\r\n z=bonds_data,\r\n y=bonds_data.Date,\r\n x=[\r\n to_years(cmt_colname) for cmt_colname in list(\r\n filter(lambda x: ' ' in x, bonds_data.columns.values)\r\n )\r\n ]\r\n )\r\n ]\r\n )\r\n\r\n fig.update_layout(\r\n scene=dict(\r\n xaxis_title='Maturity (years)',\r\n yaxis_title='Date',\r\n zaxis_title='APR (%)',\r\n zaxis=dict(ticksuffix='%')\r\n )\r\n )\r\n\r\n bonds_data.reset_index(drop=True, inplace=True)\r\n\r\n return bonds_data.to_json(), fig, {'display': 'block'}\r\n\r\n\r\[email protected](\r\n [\r\n dash.dependencies.Output('features-and-responses', 'data'),\r\n dash.dependencies.Output('features-and-responses', 'columns'),\r\n dash.dependencies.Output('blotter', 'data'),\r\n dash.dependencies.Output('blotter', 'columns'),\r\n dash.dependencies.Output('calendar-ledger', 'data'),\r\n dash.dependencies.Output('calendar-ledger', 'columns'),\r\n dash.dependencies.Output('trade-ledger', 'data'),\r\n dash.dependencies.Output('trade-ledger', 'columns')\r\n ],\r\n [dash.dependencies.Input('ivv-hist', 'children'),\r\n dash.dependencies.Input('bonds-hist', 'children'),\r\n dash.dependencies.Input('lil-n', 'value'),\r\n dash.dependencies.Input('big-N', 'value'),\r\n dash.dependencies.Input('alpha', 'value'),\r\n dash.dependencies.Input('lot-size', 'value'),\r\n dash.dependencies.Input('starting-cash', 'value'),\r\n dash.dependencies.State('hist-data-range', 'start_date'),\r\n dash.dependencies.State('hist-data-range', 'end_date')],\r\n prevent_initial_call=True\r\n)\r\ndef calculate_backtest(ivv_hist, bonds_hist, n, N, alpha, lot_size,\r\n starting_cash, start_date, end_date):\r\n features_and_responses, blotter, calendar_ledger, trade_ledger = backtest(\r\n ivv_hist, bonds_hist, n, N, alpha, lot_size, start_date, end_date,\r\n starting_cash\r\n )\r\n\r\n features_and_responses_columns = [\r\n {\"name\": i, \"id\": i} for i in features_and_responses.columns\r\n ]\r\n features_and_responses = features_and_responses.to_dict('records')\r\n\r\n blotter = blotter.to_dict('records')\r\n blotter_columns = [\r\n dict(id='ID', name='ID'),\r\n dict(id='ls', name='long/short'),\r\n dict(id='submitted', name='Created'),\r\n dict(id='action', name='Action'),\r\n dict(id='size', name='Size'),\r\n dict(id='symbol', name='Symb'),\r\n dict(\r\n id='price', name='Order Price', type='numeric',\r\n format=FormatTemplate.money(2)\r\n ),\r\n dict(id='type', name='Type'),\r\n dict(id='status', name='Status'),\r\n dict(id='fill_price', name='Fill Price', type='numeric',\r\n format=FormatTemplate.money(2)\r\n ),\r\n dict(id='filled_or_cancelled', name='Filled/Cancelled')\r\n ]\r\n\r\n calendar_ledger = calendar_ledger.to_dict('records')\r\n calendar_ledger_columns = [\r\n dict(id='Date', name='Date'),\r\n dict(id='position', name='position'),\r\n dict(id='ivv_close', name='IVV Close', type='numeric',\r\n format=FormatTemplate.money(2)),\r\n dict(id='cash', name='Cash', type='numeric',\r\n format=FormatTemplate.money(2)),\r\n dict(id='stock_value', name='Stock Value', type='numeric',\r\n format=FormatTemplate.money(2)),\r\n dict(id='total_value', name='Total Value', type='numeric',\r\n format=FormatTemplate.money(2))\r\n ]\r\n\r\n trade_ledger = trade_ledger.to_dict('records')\r\n trade_ledger_columns = [\r\n dict(id='trade_id', name=\"ID\"),\r\n dict(id='open_dt', name='Trade Opened'),\r\n dict(id='close_dt', name='Trade Closed'),\r\n dict(id='trading_days_open', name='Trading Days Open'),\r\n dict(id='buy_price', name='Entry Price', type='numeric',\r\n format=FormatTemplate.money(2)),\r\n dict(id='sell_price', name='Exit Price', type='numeric',\r\n format=FormatTemplate.money(2)),\r\n dict(id='benchmark_buy_price', name='Benchmark Buy Price',\r\n type='numeric', format=FormatTemplate.money(2)),\r\n dict(id='benchmark_sell_price', name='Benchmark sell Price',\r\n type='numeric', format=FormatTemplate.money(2)),\r\n dict(id='trade_rtn', name='Return on Trade', type='numeric',\r\n format=FormatTemplate.percentage(3)),\r\n dict(id='benchmark_rtn', name='Benchmark Return', type='numeric',\r\n format=FormatTemplate.percentage(3)),\r\n dict(id='trade_rtn_per_trading_day', name='Trade Rtn / trd day',\r\n type='numeric', format=FormatTemplate.percentage(3)),\r\n dict(id='benchmark_rtn_per_trading_day', name='Benchmark Rtn / trd day',\r\n type='numeric', format=FormatTemplate.percentage(3))\r\n ]\r\n\r\n return features_and_responses, features_and_responses_columns, blotter, \\\r\n blotter_columns, calendar_ledger, calendar_ledger_columns, \\\r\n trade_ledger, trade_ledger_columns\r\n\r\n\r\[email protected](\r\n [\r\n dash.dependencies.Output('alpha-beta', 'figure'),\r\n dash.dependencies.Output('strategy-alpha', 'children'),\r\n dash.dependencies.Output('strategy-beta', 'children'),\r\n dash.dependencies.Output('strategy-gmrr', 'children'),\r\n dash.dependencies.Output('strategy-trades-per-yr', 'children'),\r\n dash.dependencies.Output('strategy-vol', 'children'),\r\n dash.dependencies.Output('strategy-sharpe', 'children')\r\n ],\r\n dash.dependencies.Input('trade-ledger', 'data'),\r\n prevent_initial_call=True\r\n)\r\ndef update_performance_metrics(trade_ledger):\r\n trade_ledger = pd.DataFrame(trade_ledger)\r\n trade_ledger = trade_ledger[1:]\r\n\r\n X = trade_ledger['benchmark_rtn_per_trading_day'].values.reshape(-1, 1)\r\n\r\n linreg_model = linear_model.LinearRegression()\r\n linreg_model.fit(X, trade_ledger['trade_rtn_per_trading_day'])\r\n\r\n x_range = np.linspace(X.min(), X.max(), 100)\r\n y_range = linreg_model.predict(x_range.reshape(-1, 1))\r\n\r\n fig = px.scatter(\r\n trade_ledger,\r\n title=\"Performance against Benchmark\",\r\n x='benchmark_rtn_per_trading_day',\r\n y='trade_rtn_per_trading_day'\r\n )\r\n\r\n fig.add_traces(go.Scatter(x=x_range, y=y_range, name='OLS Fit'))\r\n\r\n alpha = str(round(linreg_model.intercept_ * 100, 3)) + \"% / trade\"\r\n beta = round(linreg_model.coef_[0], 3)\r\n\r\n gmrr = (trade_ledger['trade_rtn_per_trading_day'] + 1).product() ** (\r\n 1 / len(\r\n trade_ledger)) - 1\r\n\r\n avg_trades_per_yr = round(\r\n trade_ledger['open_dt'].groupby(\r\n pd.DatetimeIndex(trade_ledger['open_dt']).year\r\n ).agg('count').mean(),\r\n 0\r\n )\r\n\r\n vol = stdev(trade_ledger['trade_rtn_per_trading_day'])\r\n\r\n sharpe = round(gmrr / vol, 3)\r\n\r\n gmrr_str = str(round(gmrr, 3)) + \"% / trade\"\r\n\r\n vol_str = str(round(vol, 3)) + \"% / trade\"\r\n\r\n return fig, alpha, beta, gmrr_str, avg_trades_per_yr, vol_str, sharpe\r\n\r\n\r\n# Run it!\r\nif __name__ == '__main__':\r\n app.run_server(debug=True)\r\n"
] |
[
[
"sklearn.linear_model.LinearRegression"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Lovestarni/asv_simulator
|
[
"824c832f071c51212367569a07f67e2dadfc1401"
] |
[
"nodes/teleop_joy.py"
] |
[
"#!/usr/bin/env python\n## @package teleop_joy A node for controlling the P3DX with an XBox controller\n\nimport rospy\n\nfrom geometry_msgs.msg import Twist\nfrom nav_msgs.msg import Odometry\n\nfrom sensor_msgs.msg import Joy\nimport numpy as np\n\ndef quat2yaw(q):\n return np.arctan2(2*(q.y*q.z + q.w*q.x), 1 - 2*(q.z**2 + q.w**2))\n\ndef joyCallback(msg):\n global cmd_vel_pub\n\n global linear_axis\n global linear_scale\n global rotation_axis\n global rotation_scale\n global yaw\n\n cmd_vel_msg = Twist()\n cmd_vel_msg.linear.x = msg.axes[linear_axis] * linear_scale\n cmd_vel_msg.angular.z = msg.axes[rotation_axis] * rotation_scale\n cmd_vel_msg.angular.y = np.inf\n cmd_vel_pub.publish(cmd_vel_msg)\n\n\n\nif __name__ == '__main__':\n rospy.init_node('teleop_joy')\n global cmd_vel_pub\n\n global linear_axis\n global linear_scale\n global rotation_axis\n global rotation_scale\n global yaw\n\n linear_axis = rospy.get_param('linear_axis' , 1)\n linear_scale = rospy.get_param('linear_scale' , 5)\n\n rotation_axis = rospy.get_param('rotation_axis' , 3)\n rotation_scale = rospy.get_param('rotation_scale', 1)\n\n cmd_vel_pub = rospy.Publisher(\"/asv/cmd_vel\", Twist, queue_size=1)\n\n rospy.Subscriber(\"joy\", Joy, joyCallback)\n rospy.spin()\n"
] |
[
[
"numpy.arctan2"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
zhyongquan/Automotive-Software-Blog
|
[
"c35bed037190fd6181f20c55d1621fd11f01480b"
] |
[
"002_Particle_Filter/Particle_Filter.py"
] |
[
"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef estimate(particles, weights):\r\n \"\"\"returns mean and variance of the weighted particles\"\"\"\r\n pos = particles\r\n mean = np.average(pos, weights=weights, axis=0)\r\n var = np.average((pos - mean)**2, weights=weights, axis=0)\r\n return mean, var\r\n\r\ndef simple_resample(particles, weights):\r\n N = len(particles)\r\n cumulative_sum = np.cumsum(weights)\r\n cumulative_sum[-1] = 1. # avoid round-off error\r\n indexes = np.searchsorted(cumulative_sum, np.random.rand(N))\r\n # resample according to indexes\r\n particles[:] = particles[indexes]\r\n weights.fill(1.0 / N)\r\n return particles,weights\r\n\r\nx=0.1#初始真实状态\r\nx_N=1#系统过程噪声的协方差(由于是一维的,这里就是方差)\r\nx_R=1#测量的协方差\r\nT=75#共进行75次\r\nN=100#粒子数,越大效果越好,计算量也越大\r\n\r\nV=2#初始分布的方差\r\nx_P=x+np.random.randn(N)*np.sqrt(V)\r\n#plt.hist(x_P,N, normed=True)\r\n\r\nz_out=[x**2/20+np.random.randn(1)*np.sqrt(x_R)]#实际测量值\r\nx_out=[x]#测量值的输出向量\r\nx_est=x#估计值\r\nx_est_out=[x_est]\r\n#print(x_out)\r\n\r\nfor t in range(1,T):\r\n x=0.5*x+25*x/(1+x**2)+8*np.cos(1.2*(t-1))+np.random.randn()*np.sqrt(x_N)\r\n z=x**2/20+np.random.randn()*np.sqrt(x_R)\r\n #更新粒子\r\n x_P_update=0.5*x_P+25*x_P/(1+x_P**2)+8*np.cos(1.2*(t-1))+np.random.randn(N)*np.sqrt(x_N)\r\n z_update=x_P_update**2/20+np.random.randn(N)*np.sqrt(x_R)\r\n #print(z_update)\r\n #计算权重\r\n P_w=(1/np.sqrt(2*np.pi*x_R))*np.exp(-(z-z_update)**2/(2*x_R))\r\n #估计\r\n x_est,var=estimate(z_update,P_w)\r\n #重采样\r\n x_P,P_w=simple_resample(x_P,P_w)\r\n #保存数据\r\n x_out.append(x)\r\n z_out.append(z)\r\n x_est_out.append(x_est)\r\n\r\n#print(x_out)\r\nt=np.arange(0,T)\r\nplt.plot(t,x_out,color='blue',label='true value')\r\nplt.plot(t,x_est_out,color='red',label='estimate value')\r\nplt.legend()\r\nplt.show()"
] |
[
[
"matplotlib.pyplot.legend",
"numpy.sqrt",
"numpy.arange",
"numpy.cumsum",
"numpy.cos",
"matplotlib.pyplot.plot",
"numpy.random.randn",
"numpy.random.rand",
"numpy.average",
"numpy.exp",
"matplotlib.pyplot.show"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
qingdujun/manual-nre
|
[
"c32ecc9397e2533dfd2cb8d7e5b9e748293028f8"
] |
[
"nrekit/rl.py"
] |
[
"import tensorflow as tf\nimport os\nimport sklearn.metrics\nimport numpy as np\nimport sys\nimport math\nimport time\nfrom . import framework\nimport network\n\nclass policy_agent(framework.re_model):\n def __init__(self, train_data_loader, batch_size, max_length=120):\n framework.re_model.__init__(self, train_data_loader, batch_size, max_length)\n self.weights = tf.placeholder(tf.float32, shape=(), name=\"weights_scalar\")\n\n x = network.embedding.word_position_embedding(self.word, self.word_vec_mat, self.pos1, self.pos2)\n x_train = network.encoder.cnn(x, keep_prob=0.5)\n x_test = network.encoder.cnn(x, keep_prob=1.0)\n self._train_logit = network.selector.instance(x_train, 2, keep_prob=0.5)\n self._test_logit = network.selector.instance(x_test, 2, keep_prob=1.0)\n self._loss = network.classifier.softmax_cross_entropy(self._train_logit, self.ins_label, 2, weights=self.weights)\n\n def loss(self):\n return self._loss\n\n def train_logit(self):\n return self._train_logit\n\n def test_logit(self):\n return self._test_logit\n\nclass rl_re_framework(framework.re_framework):\n def __init__(self, train_data_loader, test_data_loader, max_length=120, batch_size=160):\n framework.re_framework.__init__(self, train_data_loader, test_data_loader, max_length, batch_size)\n\n def agent_one_step(self, sess, agent_model, batch_data, run_array, weights=1):\n feed_dict = {\n agent_model.word: batch_data['word'],\n agent_model.pos1: batch_data['pos1'],\n agent_model.pos2: batch_data['pos2'],\n agent_model.ins_label: batch_data['agent_label'],\n agent_model.length: batch_data['length'],\n agent_model.weights: weights\n }\n if 'mask' in batch_data and hasattr(agent_model, \"mask\"):\n feed_dict.update({agent_model.mask: batch_data['mask']})\n result = sess.run(run_array, feed_dict)\n return result\n\n def pretrain_main_model(self, max_epoch):\n for epoch in range(max_epoch):\n print('###### Epoch ' + str(epoch) + ' ######')\n tot_correct = 0\n tot_not_na_correct = 0\n tot = 0\n tot_not_na = 0\n i = 0\n time_sum = 0\n \n for i, batch_data in enumerate(self.train_data_loader):\n time_start = time.time()\n iter_loss, iter_logit, _train_op = self.one_step(self.sess, self.model, batch_data, [self.model.loss(), self.model.train_logit(), self.train_op])\n time_end = time.time()\n t = time_end - time_start\n time_sum += t\n iter_output = iter_logit.argmax(-1)\n iter_label = batch_data['rel']\n iter_correct = (iter_output == iter_label).sum()\n iter_not_na_correct = np.logical_and(iter_output == iter_label, iter_label != 0).sum()\n tot_correct += iter_correct\n tot_not_na_correct += iter_not_na_correct\n tot += iter_label.shape[0]\n tot_not_na += (iter_label != 0).sum()\n if tot_not_na > 0:\n sys.stdout.write(\"[pretrain main model] epoch %d step %d time %.2f | loss: %f, not NA accuracy: %f, accuracy: %f\\r\" % (epoch, i, t, iter_loss, float(tot_not_na_correct) / tot_not_na, float(tot_correct) / tot))\n sys.stdout.flush()\n i += 1\n print(\"\\nAverage iteration time: %f\" % (time_sum / i))\n\n def pretrain_agent_model(self, max_epoch):\n # Pre-train policy agent\n for epoch in range(max_epoch):\n print('###### [Pre-train Policy Agent] Epoch ' + str(epoch) + ' ######')\n tot_correct = 0\n tot_not_na_correct = 0\n tot = 0\n tot_not_na = 0\n time_sum = 0\n \n for i, batch_data in enumerate(self.train_data_loader):\n time_start = time.time()\n batch_data['agent_label'] = batch_data['ins_rel'] + 0\n batch_data['agent_label'][batch_data['agent_label'] > 0] = 1\n iter_loss, iter_logit, _train_op = self.agent_one_step(self.sess, self.agent_model, batch_data, [self.agent_model.loss(), self.agent_model.train_logit(), self.agent_train_op])\n time_end = time.time()\n t = time_end - time_start\n time_sum += t\n iter_output = iter_logit.argmax(-1)\n iter_label = batch_data['ins_rel']\n iter_correct = (iter_output == iter_label).sum()\n iter_not_na_correct = np.logical_and(iter_output == iter_label, iter_label != 0).sum()\n tot_correct += iter_correct\n tot_not_na_correct += iter_not_na_correct\n tot += iter_label.shape[0]\n tot_not_na += (iter_label != 0).sum()\n if tot_not_na > 0:\n sys.stdout.write(\"[pretrain policy agent] epoch %d step %d time %.2f | loss: %f, not NA accuracy: %f, accuracy: %f\\r\" % (epoch, i, t, iter_loss, float(tot_not_na_correct) / tot_not_na, float(tot_correct) / tot))\n sys.stdout.flush()\n i += 1\n\n def train(self,\n model, # The main model\n agent_model, # The model of policy agent\n model_name,\n ckpt_dir='./checkpoint',\n summary_dir='./summary',\n test_result_dir='./test_result',\n learning_rate=0.5,\n max_epoch=60,\n pretrain_agent_epoch=1,\n pretrain_model=None,\n test_epoch=1,\n optimizer=tf.train.GradientDescentOptimizer):\n \n print(\"Start training...\")\n \n # Init\n self.model = model(self.train_data_loader, self.train_data_loader.batch_size, self.train_data_loader.max_length)\n model_optimizer = optimizer(learning_rate)\n grads = model_optimizer.compute_gradients(self.model.loss())\n self.train_op = model_optimizer.apply_gradients(grads)\n\n # Init policy agent\n self.agent_model = agent_model(self.train_data_loader, self.train_data_loader.batch_size, self.train_data_loader.max_length)\n agent_optimizer = optimizer(learning_rate)\n agent_grads = agent_optimizer.compute_gradients(self.agent_model.loss())\n self.agent_train_op = agent_optimizer.apply_gradients(agent_grads)\n\n # Session, writer and saver\n self.sess = tf.Session()\n summary_writer = tf.summary.FileWriter(summary_dir, self.sess.graph)\n saver = tf.train.Saver(max_to_keep=None)\n if pretrain_model is None:\n self.sess.run(tf.global_variables_initializer())\n else:\n saver.restore(self.sess, pretrain_model)\n\n self.pretrain_main_model(max_epoch=5) # Pre-train main model\n self.pretrain_agent_model(max_epoch=1) # Pre-train policy agent \n\n # Train\n tot_delete = 0\n batch_count = 0\n instance_count = 0\n reward = 0.0\n best_metric = 0\n best_prec = None\n best_recall = None\n not_best_count = 0 # Stop training after several epochs without improvement.\n for epoch in range(max_epoch):\n print('###### Epoch ' + str(epoch) + ' ######')\n tot_correct = 0\n tot_not_na_correct = 0\n tot = 0\n tot_not_na = 0\n i = 0\n time_sum = 0\n batch_stack = []\n \n # Update policy agent\n for i, batch_data in enumerate(self.train_data_loader):\n # Make action\n batch_data['agent_label'] = batch_data['ins_rel'] + 0\n batch_data['agent_label'][batch_data['agent_label'] > 0] = 1\n batch_stack.append(batch_data)\n iter_logit = self.agent_one_step(self.sess, self.agent_model, batch_data, [self.agent_model.train_logit()])[0]\n action_result = iter_logit.argmax(-1)\n \n # Calculate reward\n batch_delete = np.sum(np.logical_and(batch_data['ins_rel'] != 0, action_result == 0))\n batch_data['ins_rel'][action_result == 0] = 0\n iter_loss = self.one_step(self.sess, self.model, batch_data, [self.model.loss()])[0]\n reward += iter_loss\n tot_delete += batch_delete\n batch_count += 1\n\n # Update parameters of policy agent\n alpha = 0.1\n if batch_count == 100:\n reward = reward / float(batch_count)\n average_loss = reward\n reward = - math.log(1 - math.e ** (-reward))\n sys.stdout.write('tot delete : %f | reward : %f | average loss : %f\\r' % (tot_delete, reward, average_loss))\n sys.stdout.flush()\n for batch_data in batch_stack:\n self.agent_one_step(self.sess, self.agent_model, batch_data, [self.agent_train_op], weights=reward * alpha)\n batch_count = 0\n reward = 0\n tot_delete = 0\n batch_stack = []\n i += 1\n\n # Train the main model\n for i, batch_data in enumerate(self.train_data_loader):\n batch_data['agent_label'] = batch_data['ins_rel'] + 0\n batch_data['agent_label'][batch_data['agent_label'] > 0] = 1\n time_start = time.time()\n\n # Make actions\n iter_logit = self.agent_one_step(self.sess, self.agent_model, batch_data, [self.agent_model.train_logit()])[0]\n action_result = iter_logit.argmax(-1)\n batch_data['ins_rel'][action_result == 0] = 0\n \n # Real training\n iter_loss, iter_logit, _train_op = self.agent_one_step(self.sess, self.agent_model, batch_data, [self.agent_model.loss(), self.agent_model.train_logit(), self.agent_train_op])\n time_end = time.time()\n t = time_end - time_start\n time_sum += t\n iter_output = iter_logit.argmax(-1)\n if tot_not_na > 0:\n sys.stdout.write(\"epoch %d step %d time %.2f | loss: %f, not NA accuracy: %f, accuracy: %f\\r\" % (epoch, i, t, iter_loss, float(tot_not_na_correct) / tot_not_na, float(tot_correct) / tot))\n sys.stdout.flush()\n i += 1\n print(\"\\nAverage iteration time: %f\" % (time_sum / i))\n\n if (epoch + 1) % test_epoch == 0:\n metric = self.test(model)\n if metric > best_metric:\n best_metric = metric\n best_prec = self.cur_prec\n best_recall = self.cur_recall\n print(\"Best model, storing...\")\n if not os.path.isdir(ckpt_dir):\n os.mkdir(ckpt_dir)\n path = saver.save(self.sess, os.path.join(ckpt_dir, model_name))\n print(\"Finish storing\")\n not_best_count = 0\n else:\n not_best_count += 1\n\n if not_best_count >= 20:\n break\n\n print(\"######\")\n print(\"Finish training \" + model_name)\n print(\"Best epoch auc = %f\" % (best_metric))\n if (not best_prec is None) and (not best_recall is None):\n if not os.path.isdir(test_result_dir):\n os.mkdir(test_result_dir)\n np.save(os.path.join(test_result_dir, model_name + \"_x.npy\"), best_recall)\n np.save(os.path.join(test_result_dir, model_name + \"_y.npy\"), best_prec)\n\n"
] |
[
[
"tensorflow.summary.FileWriter",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"tensorflow.train.Saver",
"numpy.logical_and"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.