repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list | possible_versions
list |
---|---|---|---|---|---|
hin1115/building_extraction_in_satellite_image | [
"d4ed2c0f95bbee435abc97389df1357393b7e570"
] | [
"nets/zoo/enru_BE.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom collections import OrderedDict\nimport math\nimport numpy as np\ndef conv3x3(in_planes, out_planes, stride=1):\n \"3x3 convolution with padding\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, norm_type=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = ModuleHelper.BatchNorm2d(norm_type=norm_type)(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = ModuleHelper.BatchNorm2d(norm_type=norm_type)(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, norm_type=None):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n self.bn1 = bn(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n self.bn2 = bn(planes)\n self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)\n self.bn3 = bn(planes * 4)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n \n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n\n def __init__(self, block, layers, num_classes=1000, deep_base=False, norm_type=None):\n super(ResNet, self).__init__()\n self.inplanes = 128 if deep_base else 16\n if deep_base:\n self.prefix = nn.Sequential(OrderedDict([\n ('conv1', nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1, bias=False)),\n ('bn1', bn(64)),\n ('relu1', nn.ReLU(inplace=False)),\n ('conv2', nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1, bias=False)),\n ('bn2', bn(64)),\n ('relu2', nn.ReLU(inplace=False)),\n ('conv3', nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1, bias=False)),\n ('bn3', bn(self.inplanes)),\n ('relu3', nn.ReLU(inplace=False))]\n ))\n else:\n self.prefix = nn.Sequential(OrderedDict([\n ('conv1', nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False)),\n ('bn1', bn(self.inplanes)),\n ('relu', nn.ReLU(inplace=False))]\n ))\n\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1, ceil_mode=True) # change.\n\n self.layer1 = self._make_layer(block, 16, layers[0], norm_type=norm_type)\n self.layer2 = self._make_layer(block, 32, layers[1], stride=2, norm_type=norm_type)\n self.layer3 = self._make_layer(block, 64, layers[2], stride=2, norm_type=norm_type)\n self.layer4 = self._make_layer(block, 128, layers[3], stride=2, norm_type=norm_type)\n self.avgpool = nn.AvgPool2d(7, stride=1)\n self.fc = nn.Linear(128 * block.expansion, num_classes)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n# elif isinstance(m, ModuleHelper.BatchNorm2d(norm_type=norm_type, ret_cls=True)):\n# m.weight.data.fill_(1)\n# m.bias.data.zero_()\n\n def _make_layer(self, block, planes, blocks, stride=1, norm_type=None):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n bn(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample, norm_type=norm_type))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes, norm_type=norm_type))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n \n x = self.layer2(x)\n \n x = self.layer3(x)\n x = self.layer4(x)\n\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n\n return x\n\n \nclass NormalResnetBackbone(nn.Module):\n def __init__(self, orig_resnet):\n super(NormalResnetBackbone, self).__init__()\n\n self.num_features = 512\n # take pretrained resnet, except AvgPool and FC\n self.prefix = orig_resnet.prefix\n self.maxpool = orig_resnet.maxpool\n self.layer1 = orig_resnet.layer1\n self.layer2 = orig_resnet.layer2\n self.layer3 = orig_resnet.layer3\n self.layer4 = orig_resnet.layer4\n\n def get_num_features(self):\n return self.num_features\n\n def forward(self, x):\n tuple_features = list()\n x = self.prefix(x)\n x = self.maxpool(x)\n x0 = x\n x1 = self.layer1(x)\n tuple_features.append(x1)\n \n x2 = self.layer2(x1)\n tuple_features.append(x2)\n x3 = self.layer3(x2)\n tuple_features.append(x3)\n x4 = self.layer4(x3)\n tuple_features.append(x4)\n\n return x0, x1, x2, x3, x4\n \ndef resnet50(**kwargs):\n \"\"\"Constructs a ResNet-50 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on Places\n \"\"\"\n model = ResNet(Bottleneck, [3, 4, 6, 3], deep_base=False, **kwargs)\n\n return model\n\ndef bn(num_features):\n return nn.Sequential(\n nn.BatchNorm2d(num_features),\n nn.ReLU()\n )\n\nclass PSPModule(nn.Module):\n # (1, 2, 3, 6)\n def __init__(self, sizes=(1, 3, 6, 8), dimension=2):\n super(PSPModule, self).__init__()\n self.stages = nn.ModuleList([self._make_stage(size, dimension) for size in sizes])\n\n def _make_stage(self, size, dimension=2):\n if dimension == 1:\n prior = nn.AdaptiveAvgPool1d(output_size=size)\n elif dimension == 2:\n prior = nn.AdaptiveAvgPool2d(output_size=(size, size))\n elif dimension == 3:\n prior = nn.AdaptiveAvgPool3d(output_size=(size, size, size))\n return prior\n\n def forward(self, feats):\n n, c, _, _ = feats.size()\n priors = [stage(feats).view(n, c, -1) for stage in self.stages]\n center = torch.cat(priors, -1)\n return center\n\n\nclass _SelfAttentionBlock(nn.Module):\n '''\n The basic implementation for self-attention block/non-local block\n Input:\n N X C X H X W\n Parameters:\n in_channels : the dimension of the input feature map\n key_channels : the dimension after the key/query transform\n value_channels : the dimension after the value transform\n scale : choose the scale to downsample the input feature maps (save memory cost)\n Return:\n N X C X H X W\n position-aware context features.(w/o concate or add with the input)\n '''\n\n def __init__(self, in_channels, key_channels, value_channels, out_channels=None, scale=1,psp_size=(1,3,6,8)):\n super(_SelfAttentionBlock, self).__init__()\n self.scale = scale\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.key_channels = key_channels\n self.value_channels = value_channels\n if out_channels == None:\n self.out_channels = in_channels\n self.pool = nn.MaxPool2d(kernel_size=(scale, scale))\n self.f_key = nn.Sequential(\n nn.Conv2d(in_channels=self.in_channels, out_channels=self.key_channels,\n kernel_size=1, stride=1, padding=0),\n bn(self.key_channels),\n# ModuleHelper.BNReLU(self.key_channels, norm_type=norm_type),\n )\n self.f_query = self.f_key\n self.f_value = nn.Conv2d(in_channels=self.in_channels, out_channels=self.value_channels,\n kernel_size=1, stride=1, padding=0)\n self.W = nn.Conv2d(in_channels=self.value_channels, out_channels=self.out_channels,\n kernel_size=1, stride=1, padding=0)\n\n self.psp = PSPModule(psp_size)\n nn.init.constant_(self.W.weight, 0)\n nn.init.constant_(self.W.bias, 0)\n\n def forward(self, x):\n batch_size, h, w = x.size(0), x.size(2), x.size(3)\n if self.scale > 1:\n x = self.pool(x)\n\n value = self.psp(self.f_value(x))\n\n query = self.f_query(x).view(batch_size, self.key_channels, -1)\n query = query.permute(0, 2, 1)\n key = self.f_key(x)\n # value=self.psp(value)#.view(batch_size, self.value_channels, -1)\n value = value.permute(0, 2, 1)\n key = self.psp(key) # .view(batch_size, self.key_channels, -1)\n sim_map = torch.matmul(query, key)\n sim_map = (self.key_channels ** -.5) * sim_map\n sim_map = F.softmax(sim_map, dim=-1)\n\n context = torch.matmul(sim_map, value)\n context = context.permute(0, 2, 1).contiguous()\n context = context.view(batch_size, self.value_channels, *x.size()[2:])\n context = self.W(context)\n return context\n\n\nclass SelfAttentionBlock2D(_SelfAttentionBlock):\n def __init__(self, in_channels, key_channels, value_channels, out_channels=None, scale=1,psp_size=(1,3,6,8)):\n super(SelfAttentionBlock2D, self).__init__(in_channels,\n key_channels,\n value_channels,\n out_channels,\n scale,\n \n psp_size=psp_size)\n\n\nclass APNB(nn.Module):\n \"\"\"\n Parameters:\n in_features / out_features: the channels of the input / output feature maps.\n dropout: we choose 0.05 as the default value.\n size: you can apply multiple sizes. Here we only use one size.\n Return:\n features fused with Object context information.\n \"\"\"\n\n def __init__(self, in_channels, out_channels, key_channels, value_channels, dropout, sizes=([1]), psp_size=(1,3,6,8)):\n super(APNB, self).__init__()\n self.stages = []\n \n self.psp_size=psp_size\n self.stages = nn.ModuleList(\n [self._make_stage(in_channels, out_channels, key_channels, value_channels, size) for size in sizes])\n self.conv_bn_dropout = nn.Sequential(\n nn.Conv2d(2 * in_channels, out_channels, kernel_size=1, padding=0),\n# ModuleHelper.BNReLU(out_channels, norm_type=norm_type),\n bn(out_channels),\n nn.Dropout2d(dropout)\n )\n\n def _make_stage(self, in_channels, output_channels, key_channels, value_channels, size):\n return SelfAttentionBlock2D(in_channels,\n key_channels,\n value_channels,\n output_channels,\n size,\n \n self.psp_size)\n\n def forward(self, feats):\n priors = [stage(feats) for stage in self.stages]\n context = priors[0]\n for i in range(1, len(priors)):\n context += priors[i]\n output = self.conv_bn_dropout(torch.cat([context, feats], 1))\n return output\n \n\ndef double_conv(in_channels, out_channels):\n return nn.Sequential(\n nn.Conv2d(in_channels, out_channels, 3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(out_channels, out_channels, 3, padding=1),\n nn.ReLU(inplace=True)\n ) \n \n \nclass ENRUNet_BE(nn.Sequential):\n def __init__(self,pretrained=False, mode='Train'):\n super(ENRUNet_BE, self).__init__()\n self.mode = mode\n self.backbone = NormalResnetBackbone(resnet50())\n # low_in_channels, high_in_channels, out_channels, key_channels, value_channels, dropout\n self.dconv_up4 = double_conv(512+256, 256)\n self.dconv_up3 = double_conv(256+128, 128)\n self.dconv_up2 = double_conv(128+64, 64)\n self.dconv_up1 = double_conv(64 + 16, 64)\n self.APNB = nn.Sequential(\n APNB(in_channels=64, out_channels=64, key_channels=32, value_channels=32,\n dropout=0.05, sizes=([1]))\n )\n \n self.conv_last = nn.Conv2d(64, 1, 1)\n \n self.dsn1 = nn.Conv2d(16, 1, 1)\n self.dsn2 = nn.Conv2d(64, 1, 1)\n self.dsn3 = nn.Conv2d(128, 1, 1)\n self.dsn4 = nn.Conv2d(256, 1, 1)\n self.dsn5 = nn.Conv2d(512, 1, 1)\n\n #boundary enhancement part \n self.fuse = nn.Sequential(nn.Conv2d(5, 64, 1),nn.ReLU(inplace=True))\n# self.fuse = nn.Conv2d(5, 64, 1)\n \n self.SE_mimic = nn.Sequential( \n nn.Linear(64, 64, bias=False),\n nn.ReLU(inplace=True),\n nn.Linear(64, 5, bias=False),\n nn.Sigmoid()\n )\n self.final_boundary = nn.Conv2d(5,2,1)\n \n self.final_conv = nn.Sequential(\n nn.Conv2d(128,64,3, padding=1),\n nn.ReLU(inplace=True) \n )\n self.final_mask = nn.Conv2d(64,2,1)\n \n \n\n self.relu = nn.ReLU() \n self.out = nn.Conv2d(64,1,1)\n\n def forward(self, x_):\n h = x_.size(2)\n w = x_.size(3)\n x0, x1, x2, x3, x4 = self.backbone(x_)\n up4 = F.interpolate(x4, size=(x3.size(2), x3.size(3)), mode=\"bilinear\", align_corners=True)\n x = torch.cat([up4, x3], dim=1) \n x = self.dconv_up4(x)\n up3 = F.interpolate(x, size=(x2.size(2), x2.size(3)), mode=\"bilinear\", align_corners=True)\n x = torch.cat([up3, x2], dim=1) \n x = self.dconv_up3(x)\n up2 = F.interpolate(x, size=(x1.size(2), x1.size(3)), mode=\"bilinear\", align_corners=True)\n x = torch.cat([up2, x1], dim=1) \n x = self.dconv_up2(x)\n up1 = F.interpolate(x, size=(x0.size(2), x0.size(3)), mode=\"bilinear\", align_corners=True)\n x = torch.cat([up1, x0], dim=1) \n x = self.dconv_up1(x)\n x = F.interpolate(x, size=(x_.size(2), x_.size(3)), mode=\"bilinear\", align_corners=True)\n out = self.APNB(x)\n# out = self.conv_last(x)\n \n ## side output\n d1 = F.upsample_bilinear(self.dsn1(x0), size=(h,w))\n d2 = F.upsample_bilinear(self.dsn2(x1), size=(h,w))\n d3 = F.upsample_bilinear(self.dsn3(x2), size=(h,w))\n d4 = F.upsample_bilinear(self.dsn4(x3), size=(h,w))\n d5 = F.upsample_bilinear(self.dsn5(x4), size=(h,w))\n\n ###########sigmoid ver\n d1_out = F.sigmoid(d1)\n d2_out = F.sigmoid(d2)\n d3_out = F.sigmoid(d3)\n d4_out = F.sigmoid(d4)\n d5_out = F.sigmoid(d5)\n\n concat = torch.cat((d1_out, d2_out, d3_out, d4_out, d5_out), 1)\n\n \n fuse_box = self.fuse(concat)\n GAP = F.adaptive_avg_pool2d(fuse_box,(1,1))\n GAP = GAP.view(-1, 64) \n se_like = self.SE_mimic(GAP) \n se_like = torch.unsqueeze(se_like, 2)\n se_like = torch.unsqueeze(se_like, 3)\n\n feat_se = concat * se_like.expand_as(concat)\n boundary = self.final_boundary(feat_se)\n boundary_out = torch.unsqueeze(boundary[:,1,:,:],1) \n bd_sftmax = F.softmax(boundary, dim=1)\n boundary_scale = torch.unsqueeze(bd_sftmax[:,1,:,:],1) \n \n feat_concat = torch.cat( [out, fuse_box], 1)\n feat_concat_conv = self.final_conv(feat_concat)\n mask = self.final_mask(feat_concat_conv)\n mask_sftmax = F.softmax(mask,dim=1) \n mask_scale = torch.unsqueeze(mask_sftmax[:,1,:,:],1)\n\n if self.mode == 'Train':\n scalefactor = torch.clamp(mask_scale+boundary_scale,0,1) \n elif self.mode == 'Infer':\n scalefactor = torch.clamp(mask_scale+5*boundary_scale,0,1)\n \n \n mask_out = torch.unsqueeze(mask[:,1,:,:],1)\n relu = self.relu(mask_out) \n scalar = relu.cpu().detach().numpy()\n if np.sum(scalar) == 0:\n average = 0\n else : \n average = scalar[np.nonzero(scalar)].mean()\n mask_out = mask_out-relu + (average*scalefactor)\n \n if self.mode == 'Train':\n mask_out = F.sigmoid(mask_out)\n boundary_out = F.sigmoid(boundary_out)\n\n return d1_out, d2_out, d3_out, d4_out, d5_out, boundary_out, mask_out\n elif self.mode =='Infer':\n return mask_out"
] | [
[
"torch.nn.functional.softmax",
"torch.nn.Dropout2d",
"torch.cat",
"torch.nn.Sigmoid",
"torch.nn.functional.sigmoid",
"torch.nn.Sequential",
"numpy.nonzero",
"torch.nn.init.constant_",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.unsqueeze",
"torch.nn.functional.adaptive_avg_pool2d",
"torch.nn.Linear",
"torch.nn.AvgPool2d",
"torch.nn.BatchNorm2d",
"torch.nn.AdaptiveAvgPool1d",
"numpy.sum",
"torch.nn.AdaptiveAvgPool3d",
"torch.nn.MaxPool2d",
"torch.matmul",
"torch.nn.AdaptiveAvgPool2d",
"torch.clamp"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
fraudies/tensorflow | [
"a42423e302b71893bbd24aa896869941013c07fb",
"3e21fe5faedab3a8258d344c8ad1cec2612a8aa8",
"a42423e302b71893bbd24aa896869941013c07fb",
"a42423e302b71893bbd24aa896869941013c07fb",
"a42423e302b71893bbd24aa896869941013c07fb",
"6aa83398ab03bfae822f36772757097bcb98b6ed",
"a42423e302b71893bbd24aa896869941013c07fb",
"a42423e302b71893bbd24aa896869941013c07fb",
"a42423e302b71893bbd24aa896869941013c07fb",
"a42423e302b71893bbd24aa896869941013c07fb",
"a42423e302b71893bbd24aa896869941013c07fb",
"a42423e302b71893bbd24aa896869941013c07fb",
"a42423e302b71893bbd24aa896869941013c07fb",
"a42423e302b71893bbd24aa896869941013c07fb",
"6aa83398ab03bfae822f36772757097bcb98b6ed",
"a42423e302b71893bbd24aa896869941013c07fb",
"a42423e302b71893bbd24aa896869941013c07fb",
"a42423e302b71893bbd24aa896869941013c07fb",
"a42423e302b71893bbd24aa896869941013c07fb",
"a42423e302b71893bbd24aa896869941013c07fb",
"a42423e302b71893bbd24aa896869941013c07fb"
] | [
"tensorflow/python/kernel_tests/gather_op_test.py",
"tensorflow/python/ops/init_ops_v2.py",
"tensorflow/python/kernel_tests/relu_op_test.py",
"tensorflow/python/ops/quantized_conv_ops_test.py",
"tensorflow/python/data/experimental/kernel_tests/directed_interleave_dataset_test.py",
"tensorflow/python/data/experimental/kernel_tests/indexed_dataset_ops_test.py",
"tensorflow/python/keras/mixed_precision/experimental/loss_scale_optimizer.py",
"tensorflow/python/layers/core_test.py",
"tensorflow/python/training/learning_rate_decay_test.py",
"tensorflow/python/keras/optimizers_test.py",
"tensorflow/python/kernel_tests/session_ops_test.py",
"tensorflow/python/kernel_tests/batchtospace_op_test.py",
"tensorflow/python/ops/ragged/ragged_gather_ops.py",
"tensorflow/python/data/experimental/kernel_tests/dense_to_sparse_batch_test.py",
"tensorflow/python/keras/saving/saved_model.py",
"tensorflow/python/keras/callbacks_test.py",
"tensorflow/contrib/kinesis/python/ops/kinesis_dataset_ops.py",
"tensorflow/python/autograph/utils/py_func_test.py",
"tensorflow/python/training/device_setter.py",
"tensorflow/python/kernel_tests/decode_compressed_op_test.py",
"tensorflow/contrib/layers/python/layers/optimizers.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 tensorflow.ops.tf.gather.\"\"\"\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.eager import context\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\n\n_TEST_TYPES = (dtypes.int64, dtypes.float32,\n dtypes.complex64, dtypes.complex128)\n\n\nclass GatherTest(test.TestCase, parameterized.TestCase):\n\n def _buildParams(self, data, dtype):\n data = data.astype(dtype.as_numpy_dtype)\n # For complex types, add an index-dependent imaginary component so we can\n # tell we got the right value.\n if dtype.is_complex:\n return data + 10j * data\n return data\n\n def testScalar1D(self):\n with self.test_session(use_gpu=True):\n data = np.array([0, 1, 2, 3, 7, 5])\n for dtype in _TEST_TYPES:\n for indices in 4, [1, 2, 2, 4, 5]:\n params_np = self._buildParams(data, dtype)\n params = constant_op.constant(params_np)\n indices_tf = constant_op.constant(indices)\n gather_t = array_ops.gather(params, indices_tf)\n gather_val = gather_t.eval()\n np_val = params_np[indices]\n self.assertAllEqual(np_val, gather_val)\n self.assertEqual(np_val.shape, gather_t.get_shape())\n\n def testScalar2D(self):\n with self.test_session(use_gpu=True):\n data = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8],\n [9, 10, 11], [12, 13, 14]])\n for dtype in _TEST_TYPES:\n for axis in range(data.ndim):\n params_np = self._buildParams(data, dtype)\n params = constant_op.constant(params_np)\n indices = constant_op.constant(2)\n gather_t = array_ops.gather(params, indices, axis=axis)\n gather_val = gather_t.eval()\n self.assertAllEqual(np.take(params_np, 2, axis=axis), gather_val)\n expected_shape = data.shape[:axis] + data.shape[axis + 1:]\n self.assertEqual(expected_shape, gather_t.get_shape())\n\n def testSimpleTwoD32(self):\n with self.test_session(use_gpu=True):\n data = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8],\n [9, 10, 11], [12, 13, 14]])\n for dtype in _TEST_TYPES:\n for axis in range(data.ndim):\n params_np = self._buildParams(data, dtype)\n params = constant_op.constant(params_np)\n # The indices must be in bounds for any axis.\n indices = constant_op.constant([0, 1, 0, 2])\n gather_t = array_ops.gather(params, indices, axis=axis)\n gather_val = gather_t.eval()\n self.assertAllEqual(np.take(params_np, [0, 1, 0, 2], axis=axis),\n gather_val)\n expected_shape = data.shape[:axis] + (4,) + data.shape[axis + 1:]\n self.assertEqual(expected_shape, gather_t.get_shape())\n\n def testHigherRank(self):\n # We check that scalar and empty indices shapes work as well\n shape = (2, 1, 3, 2)\n for indices_shape in (), (0,), (2, 0), (2, 3):\n for dtype in _TEST_TYPES:\n for axis in range(len(shape)):\n params = self._buildParams(np.random.randn(*shape), dtype)\n indices = np.random.randint(shape[axis], size=indices_shape)\n with self.test_session(use_gpu=True) as sess:\n tf_params = constant_op.constant(params)\n tf_indices = constant_op.constant(indices)\n # Check that both positive and negative indices for axis work.\n tf_axis = constant_op.constant(axis)\n tf_negative_axis = constant_op.constant(-len(shape) + axis)\n gather = array_ops.gather(tf_params, tf_indices, axis=tf_axis)\n gather_negative_axis = array_ops.gather(\n tf_params, tf_indices, axis=tf_negative_axis)\n gather_value, gather_negative_axis_value = sess.run(\n [gather, gather_negative_axis])\n gather_np = np.take(params, indices, axis)\n self.assertAllEqual(gather_np, gather_value)\n self.assertAllEqual(gather_np, gather_negative_axis_value)\n expected_shape = (params.shape[:axis] + indices.shape +\n params.shape[axis + 1:])\n self.assertEqual(expected_shape, gather.shape)\n self.assertEqual(expected_shape, gather_negative_axis.shape)\n\n # Test gradients\n gather_grad = np.random.randn(\n *gather.get_shape().as_list()).astype(dtype.as_numpy_dtype)\n if dtype.is_complex:\n gather_grad -= 1j * gather_grad\n params_grad, indices_grad, axis_grad = gradients_impl.gradients(\n gather, [tf_params, tf_indices, tf_axis], gather_grad)\n self.assertEqual(indices_grad, None)\n self.assertEqual(axis_grad, None)\n if dtype.is_integer:\n self.assertEqual(params_grad, None)\n continue\n # For axis 0, we are able to create an efficient IndexedSlices for\n # the gradient.\n if axis == 0:\n self.assertEqual(type(params_grad), ops.IndexedSlices)\n params_grad = ops.convert_to_tensor(params_grad)\n correct_params_grad = np.zeros(shape).astype(dtype.as_numpy_dtype)\n outer_dims = axis\n inner_dims = len(shape) - axis - 1\n gather_grad = gather_grad.reshape(\n shape[:axis] + (indices.size,) + shape[axis + 1:])\n for source_index, dest_index in enumerate(indices.flat):\n dest_slice = ((slice(None),) * outer_dims + (dest_index,) +\n (slice(None),) * inner_dims)\n source_slice = ((slice(None),) * outer_dims + (source_index,) +\n (slice(None),) * inner_dims)\n correct_params_grad[dest_slice] += gather_grad[source_slice]\n self.assertAllClose(correct_params_grad, params_grad.eval(),\n atol=2e-6, rtol=2e-6)\n\n def testString(self):\n params = np.array([[b\"asdf\", b\"zxcv\"], [b\"qwer\", b\"uiop\"]])\n with self.cached_session():\n self.assertAllEqual([b\"qwer\", b\"uiop\"],\n array_ops.gather(params, 1, axis=0).eval())\n self.assertAllEqual([b\"asdf\", b\"qwer\"],\n array_ops.gather(params, 0, axis=1).eval())\n\n def testUInt32AndUInt64(self):\n for unsigned_type in (dtypes.uint32, dtypes.uint64):\n params = self._buildParams(\n np.array([[1, 2, 3], [7, 8, 9]]), unsigned_type)\n with self.cached_session():\n self.assertAllEqual([7, 8, 9],\n array_ops.gather(params, 1, axis=0).eval())\n self.assertAllEqual([1, 7], array_ops.gather(params, 0, axis=1).eval())\n\n def testUnknownIndices(self):\n params = constant_op.constant([[0, 1, 2]])\n indices = array_ops.placeholder(dtypes.int32)\n gather_t = array_ops.gather(params, indices)\n self.assertEqual(None, gather_t.get_shape())\n\n def testUnknownAxis(self):\n params = constant_op.constant([[0, 1, 2]])\n indices = constant_op.constant([[0, 0], [0, 0]])\n axis = array_ops.placeholder(dtypes.int32)\n gather_t = array_ops.gather(params, indices, axis=axis)\n # Rank 2 params with rank 2 indices results in a rank 3 shape.\n self.assertEqual([None, None, None], gather_t.shape.as_list())\n\n # If indices is also unknown the result rank is unknown.\n indices = array_ops.placeholder(dtypes.int32)\n gather_t = array_ops.gather(params, indices, axis=axis)\n self.assertEqual(None, gather_t.shape)\n\n def testBadIndicesCPU(self):\n with test_util.force_cpu():\n params = [[0, 1, 2], [3, 4, 5]]\n with self.assertRaisesOpError(r\"indices\\[0,0\\] = 7 is not in \\[0, 2\\)\"):\n self.evaluate(array_ops.gather(params, [[7]], axis=0))\n with self.assertRaisesOpError(r\"indices\\[0,0\\] = 7 is not in \\[0, 3\\)\"):\n self.evaluate(array_ops.gather(params, [[7]], axis=1))\n\n def _disabledTestBadIndicesGPU(self):\n # TODO disabled due to different behavior on GPU and CPU\n # On GPU the bad indices do not raise error but fetch 0 values\n if not test.is_gpu_available():\n return\n with self.test_session(use_gpu=True):\n params = [[0, 1, 2], [3, 4, 5]]\n with self.assertRaisesOpError(r\"indices\\[0,0\\] = 7 is not in \\[0, 2\\)\"):\n array_ops.gather(params, [[7]], axis=0).eval()\n with self.assertRaisesOpError(r\"indices\\[0,0\\] = 7 is not in \\[0, 3\\)\"):\n array_ops.gather(params, [[7]], axis=1).eval()\n\n def testBadAxis(self):\n with self.test_session(use_gpu=True):\n params = [0, 1, 2]\n params_ph = array_ops.placeholder(dtypes.int32)\n indices = 0\n for bad_axis in (1, 2, -2):\n # Shape inference can validate axis for known params rank.\n with self.assertRaisesWithPredicateMatch(\n ValueError, \"Shape must be at least rank . but is rank 1\"):\n array_ops.gather(params, indices, axis=bad_axis)\n # If params rank is unknown, an op error occurs.\n with self.assertRaisesOpError(\n r\"Expected axis in the range \\[-1, 1\\), but got %s\" % bad_axis):\n array_ops.gather(params_ph, indices, axis=bad_axis).eval(\n feed_dict={params_ph: params})\n\n def testEmptySlices(self):\n with self.test_session(use_gpu=True):\n for dtype in _TEST_TYPES:\n for itype in np.int32, np.int64:\n # Leading axis gather.\n params = np.zeros((7, 0, 0), dtype=dtype.as_numpy_dtype)\n indices = np.array([3, 4], dtype=itype)\n gather = array_ops.gather(params, indices, axis=0)\n self.assertAllEqual(gather.eval(), np.zeros((2, 0, 0)))\n\n # Middle axis gather.\n params = np.zeros((0, 7, 0), dtype=dtype.as_numpy_dtype)\n gather = array_ops.gather(params, indices, axis=1)\n self.assertAllEqual(gather.eval(), np.zeros((0, 2, 0)))\n\n # Trailing axis gather.\n params = np.zeros((0, 0, 7), dtype=dtype.as_numpy_dtype)\n gather = array_ops.gather(params, indices, axis=2)\n self.assertAllEqual(gather.eval(), np.zeros((0, 0, 2)))\n\n @parameterized.parameters([\n # batch_dims=0 (equivalent to tf.gather)\n dict( # 2D indices\n batch_dims=0,\n params=[6, 7, 8, 9],\n indices=[[2, 1], [0, 3]],\n expected=[[8, 7], [6, 9]]),\n dict( # 3D indices\n batch_dims=0,\n params=[6, 7, 8, 9],\n indices=[[[3, 1], [2, 0]], [[0, 3], [2, 2]]],\n expected=[[[9, 7], [8, 6]], [[6, 9], [8, 8]]]),\n dict( # 4D indices\n batch_dims=0,\n params=[8, 9],\n indices=[[[[0, 1], [1, 0]], [[0, 0], [1, 1]]],\n [[[1, 1], [0, 0]], [[0, 1], [1, 0]]]],\n expected=[[[[8, 9], [9, 8]], [[8, 8], [9, 9]]],\n [[[9, 9], [8, 8]], [[8, 9], [9, 8]]]]),\n\n # batch_dims=indices.shape.ndims - 1 (equivalent to tf.batch_gather)\n dict( # 2D indices (1 batch dim)\n batch_dims=1,\n params=[[10, 11, 12, 13], [20, 21, 22, 23]],\n indices=[[2, 1], [0, 3]],\n expected=[[12, 11], [20, 23]]),\n dict( # 3D indices (2 batch dims)\n batch_dims=2,\n params=[[[100, 101], [110, 111]], [[200, 201], [210, 211]]],\n indices=[[[0, 1], [1, 0]], [[0, 0], [1, 1]]],\n expected=[[[100, 101], [111, 110]], [[200, 200], [211, 211]]]),\n dict( # 2D indices (1 batch dim)\n batch_dims=-1,\n params=[[10, 11, 12, 13], [20, 21, 22, 23]],\n indices=[[2, 1], [0, 3]],\n expected=[[12, 11], [20, 23]]),\n dict( # 3D indices (2 batch dims)\n batch_dims=-1,\n params=[[[100, 101], [110, 111]], [[200, 201], [210, 211]]],\n indices=[[[0, 1], [1, 0]], [[0, 0], [1, 1]]],\n expected=[[[100, 101], [111, 110]], [[200, 200], [211, 211]]]),\n\n # 0 < batch_dims < indices.shape.ndims - 1\n dict( # 3D indices (1 batch dim)\n batch_dims=1,\n params=[[10, 11, 12, 13], [20, 21, 22, 23]],\n indices=[[[3, 1], [2, 0]], [[0, 3], [2, 2]]],\n expected=[[[13, 11], [12, 10]], [[20, 23], [22, 22]]]),\n dict( # 4D indices (1 batch dim)\n batch_dims=1,\n params=[[6, 7], [8, 9]],\n indices=[[[[0, 1], [1, 0]], [[0, 0], [1, 1]]],\n [[[1, 1], [0, 0]], [[0, 1], [1, 0]]]],\n expected=[[[[6, 7], [7, 6]], [[6, 6], [7, 7]]],\n [[[9, 9], [8, 8]], [[8, 9], [9, 8]]]]),\n dict( # 4D indices (2 batch dims)\n batch_dims=2,\n params=[[[2, 3], [4, 5]], [[6, 7], [8, 9]]],\n indices=[[[[0, 1], [1, 0]], [[0, 0], [1, 1]]],\n [[[1, 1], [0, 0]], [[0, 1], [1, 0]]]],\n expected=[[[[2, 3], [3, 2]], [[4, 4], [5, 5]]],\n [[[7, 7], [6, 6]], [[8, 9], [9, 8]]]]),\n\n # axis > 0\n dict( # 3D indices, batch_dims=1, axis=2\n # params.shape = [I1, J1, J2] = [2, 2, 3]\n # indices.shape = [I1, K1, K2] = [2, 1, 5]\n # result.shape = [I1, J1, K1, K2] = [2, 2, 1, 5]\n batch_dims=1,\n axis=2,\n params=[[[10, 11, 12], [13, 14, 15]], [[20, 21, 22], [23, 24, 25]]],\n indices=[[[0, 1, 2, 1, 0]], [[0, 1, 2, 1, 0]]],\n expected=[[[[10, 11, 12, 11, 10]], [[13, 14, 15, 14, 13]]],\n [[[20, 21, 22, 21, 20]], [[23, 24, 25, 24, 23]]]]),\n dict( # 3D indices, batch_dims=None, axis=1\n batch_dims=None,\n axis=1,\n params=[[10, 11, 12], [13, 14, 15]],\n indices=[1, 0],\n expected=[[11, 10], [14, 13]]),\n ])\n @test_util.run_in_graph_and_eager_modes\n def testBatchDims(self, params, indices, batch_dims, expected=None,\n axis=None):\n result = array_ops.gather(params, indices, axis=axis, batch_dims=batch_dims)\n self.assertAllEqual(expected, result)\n\n @parameterized.parameters([\n dict(\n params_shape=[2, 3, 4, 5, 6, 7],\n indices_shape=[2, 3, 8, 9, 10],\n batch_dims=2,\n axis=2,\n output_shape=[2, 3, 8, 9, 10, 5, 6, 7]\n # = params.shape[:2] + indices.shape[2:] + params.shape[3:]\n ),\n dict(\n params_shape=[2, 3, 4, 5, 6, 7],\n indices_shape=[2, 3, 8, 9, 10],\n batch_dims=2,\n axis=3,\n output_shape=[2, 3, 4, 8, 9, 10, 6, 7]\n # = params.shape[:3] + indices.shape[2:] + params.shape[4:]\n ),\n dict(\n params_shape=[2, 3, 4, 5, 6, 7],\n indices_shape=[2, 3, 8, 9, 10],\n batch_dims=2,\n axis=4,\n output_shape=[2, 3, 4, 5, 8, 9, 10, 7]\n # = params.shape[:4] + indices.shape[2:] + params.shape[5:]\n ),\n dict(\n params_shape=[2, 3, 4, 5, 6, 7],\n indices_shape=[2, 3, 8, 9, 10],\n batch_dims=2,\n axis=5,\n output_shape=[2, 3, 4, 5, 6, 8, 9, 10]\n # = params.shape[:5] + indices.shape[2:] + params.shape[6:]\n ),\n dict(\n params_shape=[2, 3, 4, 5, 6, 7],\n indices_shape=[2, 3, 8, 9, 10],\n batch_dims=2,\n axis=-4,\n output_shape=[2, 3, 8, 9, 10, 5, 6, 7]\n # = params.shape[:2] + indices.shape[2:] + params.shape[3:]\n ),\n dict(\n params_shape=[2, 3, 4, 5, 6, 7],\n indices_shape=[2, 3, 8, 9, 10],\n batch_dims=2,\n axis=-3,\n output_shape=[2, 3, 4, 8, 9, 10, 6, 7]\n # = params.shape[:3] + indices.shape[2:] + params.shape[4:]\n ),\n dict(\n params_shape=[2, 3, 4, 5, 6, 7],\n indices_shape=[2, 3, 8, 9, 10],\n batch_dims=2,\n axis=-2,\n output_shape=[2, 3, 4, 5, 8, 9, 10, 7]\n # = params.shape[:4] + indices.shape[2:] + params.shape[5:]\n ),\n dict(\n params_shape=[2, 3, 4, 5, 6, 7],\n indices_shape=[2, 3, 8, 9, 10],\n batch_dims=2,\n axis=-1,\n output_shape=[2, 3, 4, 5, 6, 8, 9, 10]\n # = params.shape[:5] + indices.shape[2:] + params.shape[6:]\n ),\n ])\n @test_util.run_in_graph_and_eager_modes\n def testBatchDimsMatchesPythonBatching(self, params_shape, indices_shape,\n batch_dims, axis, output_shape):\n \"\"\"Checks that batch_dims matches multiple calls to tf.gather().\"\"\"\n # Generate a `params` tensor with the indicated shape.\n params_size = np.prod(params_shape)\n params = np.reshape(np.arange(params_size), params_shape)\n\n # Generate an `indices` tensor with the indicated shape, where each index\n # is within the appropriate range.\n indices_size = np.prod(indices_shape)\n indices = np.reshape(np.arange(indices_size), indices_shape)\n indices = indices % params_shape[axis]\n\n # Perform repeated (batched) gather operations with numpy, to find the\n # expected result.\n expected = self._batchNumpyGather(params, indices, axis, batch_dims)\n\n # On Windows, we get an exception if we pass in the transformed numpy\n # arrays (\"Failed to convert numpy ndarray to a Tensor (Unsupported\n # feed type).\"); so convert them back to lists before calling tf.gather.\n params = params.tolist()\n indices = indices.tolist()\n\n result = array_ops.gather(params, indices, axis=axis, batch_dims=batch_dims)\n self.assertAllEqual(output_shape, result.shape.as_list())\n self.assertAllEqual(expected, result)\n\n def _batchNumpyGather(self, params, indices, axis, batch_dims):\n \"\"\"Performs a batch gather by making recursive calls to np.take().\n\n This is used by testBatchDims() to construct the expected value.\n\n Args:\n params: A numpy array\n indices: A numpy array\n axis: An integer\n batch_dims: An integer\n Returns:\n A numpy array\n \"\"\"\n if batch_dims == 0:\n return np.take(params, indices, axis=axis)\n self.assertEqual(params.shape[0], indices.shape[0])\n if axis > 0:\n axis -= 1\n return np.stack([\n self._batchNumpyGather(params[i], indices[i], axis, batch_dims - 1)\n for i in range(params.shape[0])\n ])\n\n def testSkipEagerErrors(self):\n if context.executing_eagerly():\n return\n with self.assertRaisesRegexp(ValueError, r\"tf\\.gather does not allow.*\"):\n array_ops.gather(\n params=[1, 2],\n batch_dims=1,\n indices=array_ops.placeholder(dtypes.int32))\n\n @test_util.run_in_graph_and_eager_modes\n def testErrors(self):\n\n with self.assertRaisesRegexp(\n ValueError, r\"batch_dims = 2 must be less than rank\\(indices\\) = 2\"):\n array_ops.gather(\n params=[[1, 2], [3, 4]], indices=[[1, 2], [3, 4]], batch_dims=2)\n\n with self.assertRaisesRegexp(\n ValueError, r\"batch_dims = 1 must be less than rank\\(params\\) = 1\"):\n array_ops.gather(\n params=[1, 2, 3, 4], indices=[[1, 2], [3, 4]], batch_dims=1)\n\n with self.assertRaisesRegexp(\n ValueError, r\"batch_dims = 1 must be less than or equal to axis = 0\"):\n array_ops.gather(\n params=[[1, 2], [3, 4]],\n indices=[[1, 2], [3, 4]],\n batch_dims=1,\n axis=0)\n\n one = array_ops.ones((), dtypes.int32)\n with self.assertRaisesRegexp(TypeError, \"batch_dims must be an int\"):\n array_ops.gather(params=[[1]], indices=[[1]], batch_dims=one)\n\n @test_util.run_v1_only(\"RefVariable is not supported in v2\")\n def testGatherRefVariable(self):\n with self.cached_session():\n v = variables.RefVariable(constant_op.constant([[1, 2], [3, 4], [5, 6]]))\n self.evaluate(variables.global_variables_initializer())\n gather = array_ops.gather(v, [0, 2])\n if not context.executing_eagerly(): # .op doesn't make sense in Eager\n self.assertEqual(\"GatherV2\", gather.op.name)\n self.assertAllEqual([[1, 2], [5, 6]], gather)\n\n @test_util.run_in_graph_and_eager_modes\n def testGatherResourceVariable(self):\n with self.cached_session():\n v = resource_variable_ops.ResourceVariable(\n constant_op.constant([[1, 2], [3, 4], [5, 6]]))\n self.evaluate(variables.global_variables_initializer())\n gather = array_ops.gather(v, [0, 2])\n if not context.executing_eagerly(): # .op doesn't make sense in Eager\n self.assertEqual(\"ResourceGather\", gather.op.inputs[0].op.type)\n self.assertAllEqual([[1, 2], [5, 6]], gather)\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\"\"\"Operations often used for initializing tensors.\n\nAll variable initializers returned by functions in this file should have the\nfollowing signature:\n\ndef _initializer(shape, dtype=dtypes.float32):\n Args:\n shape: List of `int` representing the shape of the output `Tensor`. Some\n initializers may also be able to accept a `Tensor`.\n dtype: (Optional) Type of the output `Tensor`.\n Returns:\n A `Tensor` of type `dtype` and `shape`.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\n\nimport numpy as np\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gen_linalg_ops\nfrom tensorflow.python.ops import linalg_ops_impl\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import stateless_random_ops\nfrom tensorflow.python.util.tf_export import tf_export\n\n\nclass Initializer(object):\n \"\"\"Initializer base class: all initializers inherit from this class.\n \"\"\"\n\n def __call__(self, shape, dtype=None):\n \"\"\"Returns a tensor object initialized as specified by the initializer.\n\n Args:\n shape: Shape of the tensor.\n dtype: Optional dtype of the tensor. If not provided will return tensor\n of `tf.float32`.\n \"\"\"\n raise NotImplementedError\n\n def get_config(self):\n \"\"\"Returns the configuration of the initializer as a JSON-serializable dict.\n\n Returns:\n A JSON-serializable Python dict.\n \"\"\"\n return {}\n\n @classmethod\n def from_config(cls, config):\n \"\"\"Instantiates an initializer from a configuration dictionary.\n\n Example:\n\n ```python\n initializer = RandomUniform(-1, 1)\n config = initializer.get_config()\n initializer = RandomUniform.from_config(config)\n ```\n\n Args:\n config: A Python dictionary.\n It will typically be the output of `get_config`.\n\n Returns:\n An Initializer instance.\n \"\"\"\n config.pop(\"dtype\", None)\n return cls(**config)\n\n\n@tf_export(\"zeros_initializer\", v1=[])\nclass Zeros(Initializer):\n \"\"\"Initializer that generates tensors initialized to 0.\"\"\"\n\n def __call__(self, shape, dtype=dtypes.float32):\n dtype = dtypes.as_dtype(dtype)\n return array_ops.zeros(shape, dtype)\n\n\n@tf_export(\"ones_initializer\", v1=[])\nclass Ones(Initializer):\n \"\"\"Initializer that generates tensors initialized to 1.\"\"\"\n\n def __call__(self, shape, dtype=dtypes.float32):\n \"\"\"Returns a tensor object initialized as specified by the initializer.\n\n Args:\n shape: Shape of the tensor.\n dtype: Optional dtype of the tensor. Only numeric or boolean dtypes are\n supported.\n\n Raises:\n ValuesError: If the dtype is not numeric or boolean.\n \"\"\"\n dtype = dtypes.as_dtype(dtype)\n if not dtype.is_numpy_compatible or dtype == dtypes.string:\n raise ValueError(\"Expected numeric or boolean dtype, got %s.\" % dtype)\n return array_ops.ones(shape, dtype)\n\n\n@tf_export(\"constant_initializer\", v1=[])\nclass Constant(Initializer):\n \"\"\"Initializer that generates tensors with constant values.\n\n The resulting tensor is populated with values of type `dtype`, as\n specified by arguments `value` following the desired `shape` of the\n new tensor (see examples below).\n\n The argument `value` can be a constant value, or a list of values of type\n `dtype`. If `value` is a list, then the length of the list must be less\n than or equal to the number of elements implied by the desired shape of the\n tensor. In the case where the total number of elements in `value` is less\n than the number of elements required by the tensor shape, the last element\n in `value` will be used to fill the remaining entries. If the total number of\n elements in `value` is greater than the number of elements required by the\n tensor shape, the initializer will raise a `ValueError`.\n\n Args:\n value: A Python scalar, list or tuple of values, or a N-dimensional numpy\n array. All elements of the initialized variable will be set to the\n corresponding value in the `value` argument.\n\n Raises:\n TypeError: If the input `value` is not one of the expected types.\n\n Examples:\n The following example can be rewritten using a numpy.ndarray instead\n of the `value` list, even reshaped, as shown in the two commented lines\n below the `value` list initialization.\n\n ```python\n >>> import numpy as np\n >>> import tensorflow as tf\n\n >>> value = [0, 1, 2, 3, 4, 5, 6, 7]\n >>> # value = np.array(value)\n >>> # value = value.reshape([2, 4])\n >>> init = tf.constant_initializer(value)\n\n >>> print('fitting shape:')\n >>> with tf.Session():\n >>> x = tf.get_variable('x', shape=[2, 4], initializer=init)\n >>> x.initializer.run()\n >>> print(x.eval())\n\n fitting shape:\n [[ 0. 1. 2. 3.]\n [ 4. 5. 6. 7.]]\n\n >>> print('larger shape:')\n >>> with tf.Session():\n >>> x = tf.get_variable('x', shape=[3, 4], initializer=init)\n >>> x.initializer.run()\n >>> print(x.eval())\n\n larger shape:\n [[ 0. 1. 2. 3.]\n [ 4. 5. 6. 7.]\n [ 7. 7. 7. 7.]]\n\n >>> print('smaller shape:')\n >>> with tf.Session():\n >>> x = tf.get_variable('x', shape=[2, 3], initializer=init)\n\n ValueError: Too many elements provided. Needed at most 6, but received 8\n ```\n \"\"\"\n\n def __init__(self, value=0):\n if not (np.isscalar(value) or isinstance(value, (list, tuple, np.ndarray))):\n raise TypeError(\n \"Invalid type for initial value: %s (expected Python scalar, list or \"\n \"tuple of values, or numpy.ndarray).\" % type(value))\n self.value = value\n\n def __call__(self, shape, dtype=None):\n \"\"\"Returns a tensor object initialized as specified by the initializer.\n\n Args:\n shape: Shape of the tensor.\n dtype: Optional dtype of the tensor. If not provided the dtype of the\n tensor created will be the type of the inital value.\n\n Raises:\n TypeError: If the initializer cannot create a tensor of the requested\n dtype.\n \"\"\"\n if dtype is not None:\n dtype = dtypes.as_dtype(dtype)\n return constant_op.constant(\n self.value, dtype=dtype, shape=shape)\n\n def get_config(self):\n return {\"value\": self.value}\n\n\n@tf_export(\"random_uniform_initializer\", v1=[])\nclass RandomUniform(Initializer):\n \"\"\"Initializer that generates tensors with a uniform distribution.\n\n Args:\n minval: A python scalar or a scalar tensor. Lower bound of the range\n of random values to generate.\n maxval: A python scalar or a scalar tensor. Upper bound of the range\n of random values to generate. Defaults to 1 for float types.\n seed: A Python integer. Used to create random seeds. See\n `tf.set_random_seed`\n for behavior.\n \"\"\"\n\n def __init__(self, minval=-0.05, maxval=0.05, seed=None):\n self.minval = minval\n self.maxval = maxval\n self.seed = seed\n self._random_generator = _RandomGenerator(seed)\n\n def __call__(self, shape, dtype=dtypes.float32):\n \"\"\"Returns a tensor object initialized as specified by the initializer.\n\n Args:\n shape: Shape of the tensor.\n dtype: Optional dtype of the tensor. Only floating point and integer\n types are supported.\n\n Raises:\n ValueError: If the dtype is not numeric.\n \"\"\"\n dtype = dtypes.as_dtype(dtype)\n if not dtype.is_floating and not dtype.is_integer:\n raise ValueError(\"Expected float or integer dtype, got %s.\" % dtype)\n return self._random_generator.random_uniform(shape, self.minval,\n self.maxval, dtype)\n\n def get_config(self):\n return {\n \"minval\": self.minval,\n \"maxval\": self.maxval,\n \"seed\": self.seed\n }\n\n\n@tf_export(\"random_normal_initializer\", v1=[])\nclass RandomNormal(Initializer):\n \"\"\"Initializer that generates tensors with a normal distribution.\n\n Args:\n mean: a python scalar or a scalar tensor. Mean of the random values\n to generate.\n stddev: a python scalar or a scalar tensor. Standard deviation of the\n random values to generate.\n seed: A Python integer. Used to create random seeds. See\n `tf.set_random_seed`\n for behavior.\n \"\"\"\n\n def __init__(self, mean=0.0, stddev=0.05, seed=None):\n self.mean = mean\n self.stddev = stddev\n self.seed = seed\n self._random_generator = _RandomGenerator(seed)\n\n def __call__(self, shape, dtype=dtypes.float32):\n \"\"\"Returns a tensor object initialized as specified by the initializer.\n\n Args:\n shape: Shape of the tensor.\n dtype: Optional dtype of the tensor. Only floating point types are\n supported.\n\n Raises:\n ValueError: If the dtype is not floating point\n \"\"\"\n dtype = _assert_float_dtype(dtype)\n return self._random_generator.random_normal(shape, self.mean, self.stddev,\n dtype)\n\n def get_config(self):\n return {\n \"mean\": self.mean,\n \"stddev\": self.stddev,\n \"seed\": self.seed\n }\n\n\nclass TruncatedNormal(Initializer):\n \"\"\"Initializer that generates a truncated normal distribution.\n\n These values are similar to values from a `random_normal_initializer`\n except that values more than two standard deviations from the mean\n are discarded and re-drawn. This is the recommended initializer for\n neural network weights and filters.\n\n Args:\n mean: a python scalar or a scalar tensor. Mean of the random values\n to generate.\n stddev: a python scalar or a scalar tensor. Standard deviation of the\n random values to generate.\n seed: A Python integer. Used to create random seeds. See\n `tf.set_random_seed`\n for behavior.\n \"\"\"\n\n def __init__(self, mean=0.0, stddev=0.05, seed=None):\n self.mean = mean\n self.stddev = stddev\n self.seed = seed\n self._random_generator = _RandomGenerator(seed)\n\n def __call__(self, shape, dtype=dtypes.float32):\n \"\"\"Returns a tensor object initialized as specified by the initializer.\n\n Args:\n shape: Shape of the tensor.\n dtype: Optional dtype of the tensor. Only floating point types are\n supported.\n\n Raises:\n ValueError: If the dtype is not floating point\n \"\"\"\n dtype = _assert_float_dtype(dtype)\n return self._random_generator.truncated_normal(shape, self.mean,\n self.stddev, dtype)\n\n def get_config(self):\n return {\n \"mean\": self.mean,\n \"stddev\": self.stddev,\n \"seed\": self.seed\n }\n\n\nclass VarianceScaling(Initializer):\n \"\"\"Initializer capable of adapting its scale to the shape of weights tensors.\n\n With `distribution=\"truncated_normal\" or \"untruncated_normal\"`,\n samples are drawn from a truncated/untruncated normal\n distribution with a mean of zero and a standard deviation (after truncation,\n if used) `stddev = sqrt(scale / n)`\n where n is:\n - number of input units in the weight tensor, if mode = \"fan_in\"\n - number of output units, if mode = \"fan_out\"\n - average of the numbers of input and output units, if mode = \"fan_avg\"\n\n With `distribution=\"uniform\"`, samples are drawn from a uniform distribution\n within [-limit, limit], with `limit = sqrt(3 * scale / n)`.\n\n Args:\n scale: Scaling factor (positive float).\n mode: One of \"fan_in\", \"fan_out\", \"fan_avg\".\n distribution: Random distribution to use. One of \"truncated_normal\",\n \"untruncated_normal\" and \"uniform\".\n seed: A Python integer. Used to create random seeds. See\n `tf.set_random_seed`\n for behavior.\n\n Raises:\n ValueError: In case of an invalid value for the \"scale\", mode\" or\n \"distribution\" arguments.\n \"\"\"\n\n def __init__(self,\n scale=1.0,\n mode=\"fan_in\",\n distribution=\"truncated_normal\",\n seed=None):\n if scale <= 0.:\n raise ValueError(\"`scale` must be positive float.\")\n if mode not in {\"fan_in\", \"fan_out\", \"fan_avg\"}:\n raise ValueError(\"Invalid `mode` argument:\", mode)\n distribution = distribution.lower()\n if distribution not in {\"uniform\", \"truncated_normal\",\n \"untruncated_normal\"}:\n raise ValueError(\"Invalid `distribution` argument:\", distribution)\n self.scale = scale\n self.mode = mode\n self.distribution = distribution\n self.seed = seed\n self._random_generator = _RandomGenerator(seed)\n\n def __call__(self, shape, dtype=dtypes.float32):\n \"\"\"Returns a tensor object initialized as specified by the initializer.\n\n Args:\n shape: Shape of the tensor.\n dtype: Optional dtype of the tensor. Only floating point types are\n supported.\n\n Raises:\n ValueError: If the dtype is not floating point\n \"\"\"\n partition_info = None # Keeps logic so can be readded later if necessary\n dtype = _assert_float_dtype(dtype)\n scale = self.scale\n scale_shape = shape\n if partition_info is not None:\n scale_shape = partition_info.full_shape\n fan_in, fan_out = _compute_fans(scale_shape)\n if self.mode == \"fan_in\":\n scale /= max(1., fan_in)\n elif self.mode == \"fan_out\":\n scale /= max(1., fan_out)\n else:\n scale /= max(1., (fan_in + fan_out) / 2.)\n if self.distribution == \"truncated_normal\":\n # constant from scipy.stats.truncnorm.std(a=-2, b=2, loc=0., scale=1.)\n stddev = math.sqrt(scale) / .87962566103423978\n return self._random_generator.truncated_normal(shape, 0.0, stddev, dtype)\n elif self.distribution == \"untruncated_normal\":\n stddev = math.sqrt(scale)\n return self._random_generator.random_normal(shape, 0.0, stddev, dtype)\n else:\n limit = math.sqrt(3.0 * scale)\n return self._random_generator.random_uniform(shape, -limit, limit, dtype)\n\n def get_config(self):\n return {\n \"scale\": self.scale,\n \"mode\": self.mode,\n \"distribution\": self.distribution,\n \"seed\": self.seed\n }\n\n\nclass Orthogonal(Initializer):\n \"\"\"Initializer that generates an orthogonal matrix.\n\n If the shape of the tensor to initialize is two-dimensional, it is initialized\n with an orthogonal matrix obtained from the QR decomposition of a matrix of\n random numbers drawn from a normal distribution.\n If the matrix has fewer rows than columns then the output will have orthogonal\n rows. Otherwise, the output will have orthogonal columns.\n\n If the shape of the tensor to initialize is more than two-dimensional,\n a matrix of shape `(shape[0] * ... * shape[n - 2], shape[n - 1])`\n is initialized, where `n` is the length of the shape vector.\n The matrix is subsequently reshaped to give a tensor of the desired shape.\n\n Args:\n gain: multiplicative factor to apply to the orthogonal matrix\n seed: A Python integer. Used to create random seeds. See\n `tf.set_random_seed`\n for behavior.\n\n References:\n [Saxe et al., 2014](https://openreview.net/forum?id=_wzZwKpTDF_9C)\n ([pdf](https://arxiv.org/pdf/1312.6120.pdf))\n \"\"\"\n\n def __init__(self, gain=1.0, seed=None):\n self.gain = gain\n self.seed = seed\n self._random_generator = _RandomGenerator(seed)\n\n def __call__(self, shape, dtype=dtypes.float32):\n \"\"\"Returns a tensor object initialized as specified by the initializer.\n\n Args:\n shape: Shape of the tensor.\n dtype: Optional dtype of the tensor. Only floating point types are\n supported.\n\n Raises:\n ValueError: If the dtype is not floating point or the input shape is not\n valid.\n \"\"\"\n dtype = _assert_float_dtype(dtype)\n # Check the shape\n if len(shape) < 2:\n raise ValueError(\"The tensor to initialize must be \"\n \"at least two-dimensional\")\n # Flatten the input shape with the last dimension remaining\n # its original shape so it works for conv2d\n num_rows = 1\n for dim in shape[:-1]:\n num_rows *= dim\n num_cols = shape[-1]\n flat_shape = (max(num_cols, num_rows), min(num_cols, num_rows))\n\n # Generate a random matrix\n a = self._random_generator.random_normal(flat_shape, dtype=dtype)\n # Compute the qr factorization\n q, r = gen_linalg_ops.qr(a, full_matrices=False)\n # Make Q uniform\n d = array_ops.diag_part(r)\n q *= math_ops.sign(d)\n if num_rows < num_cols:\n q = array_ops.matrix_transpose(q)\n return self.gain * array_ops.reshape(q, shape)\n\n def get_config(self):\n return {\"gain\": self.gain, \"seed\": self.seed}\n\n\nclass Identity(Initializer):\n \"\"\"Initializer that generates the identity matrix.\n\n Only use for 2D matrices.\n\n Args:\n gain: Multiplicative factor to apply to the identity matrix.\n \"\"\"\n\n def __init__(self, gain=1.0):\n self.gain = gain\n\n def __call__(self, shape, dtype=dtypes.float32):\n \"\"\"Returns a tensor object initialized as specified by the initializer.\n\n Args:\n shape: Shape of the tensor.\n dtype: Optional dtype of the tensor. Only floating point types are\n supported.\n\n Raises:\n ValueError: If the dtype is not floating point\n \"\"\"\n partition_info = None # Keeps logic so can be readded later if necessary\n dtype = _assert_float_dtype(dtype)\n full_shape = shape if partition_info is None else partition_info.full_shape\n if len(full_shape) != 2:\n raise ValueError(\n \"Identity matrix initializer can only be used for 2D matrices.\")\n initializer = linalg_ops_impl.eye(*full_shape, dtype=dtype)\n if partition_info is not None:\n initializer = array_ops.slice(initializer, partition_info.var_offset,\n shape)\n return self.gain * initializer\n\n def get_config(self):\n return {\"gain\": self.gain}\n\n\nclass GlorotUniform(VarianceScaling):\n \"\"\"The Glorot uniform initializer, also called Xavier uniform initializer.\n\n It draws samples from a uniform distribution within [-limit, limit]\n where `limit` is `sqrt(6 / (fan_in + fan_out))`\n where `fan_in` is the number of input units in the weight tensor\n and `fan_out` is the number of output units in the weight tensor.\n\n Args:\n seed: A Python integer. Used to create random seeds. See\n `tf.set_random_seed`\n for behavior.\n\n References:\n [Glorot et al., 2010](http://proceedings.mlr.press/v9/glorot10a.html)\n ([pdf](http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf))\n \"\"\"\n\n def __init__(self, seed=None):\n super(GlorotUniform, self).__init__(\n scale=1.0,\n mode=\"fan_avg\",\n distribution=\"uniform\",\n seed=seed)\n\n def get_config(self):\n return {\"seed\": self.seed}\n\n\nclass GlorotNormal(VarianceScaling):\n \"\"\"The Glorot normal initializer, also called Xavier normal initializer.\n\n It draws samples from a truncated normal distribution centered on 0\n with `stddev = sqrt(2 / (fan_in + fan_out))`\n where `fan_in` is the number of input units in the weight tensor\n and `fan_out` is the number of output units in the weight tensor.\n\n Args:\n seed: A Python integer. Used to create random seeds. See\n `tf.set_random_seed` for behavior.\n\n References:\n [Glorot et al., 2010](http://proceedings.mlr.press/v9/glorot10a.html)\n ([pdf](http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf))\n \"\"\"\n\n def __init__(self, seed=None):\n super(GlorotNormal, self).__init__(\n scale=1.0,\n mode=\"fan_avg\",\n distribution=\"truncated_normal\",\n seed=seed)\n\n def get_config(self):\n return {\"seed\": self.seed}\n\n\n# Aliases.\n\n# pylint: disable=invalid-name\nzeros_initializer = Zeros\nones_initializer = Ones\nconstant_initializer = Constant\nrandom_uniform_initializer = RandomUniform\nrandom_normal_initializer = RandomNormal\ntruncated_normal_initializer = TruncatedNormal\nvariance_scaling_initializer = VarianceScaling\nglorot_uniform_initializer = GlorotUniform\nglorot_normal_initializer = GlorotNormal\northogonal_initializer = Orthogonal\nidentity_initializer = Identity\n# pylint: enable=invalid-name\n\n\ndef lecun_normal(seed=None):\n \"\"\"LeCun normal initializer.\n\n It draws samples from a truncated normal distribution centered on 0\n with `stddev = sqrt(1 / fan_in)`\n where `fan_in` is the number of input units in the weight tensor.\n\n Arguments:\n seed: A Python integer. Used to seed the random generator.\n\n Returns:\n An initializer.\n\n References:\n - Self-Normalizing Neural Networks,\n [Klambauer et al., 2017]\n (https://papers.nips.cc/paper/6698-self-normalizing-neural-networks)\n ([pdf]\n (https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf))\n - Efficient Backprop,\n [Lecun et al., 1998](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf)\n \"\"\"\n return VarianceScaling(\n scale=1., mode=\"fan_in\", distribution=\"truncated_normal\", seed=seed)\n\n\ndef lecun_uniform(seed=None):\n \"\"\"LeCun uniform initializer.\n\n It draws samples from a uniform distribution within [-limit, limit]\n where `limit` is `sqrt(3 / fan_in)`\n where `fan_in` is the number of input units in the weight tensor.\n\n Arguments:\n seed: A Python integer. Used to seed the random generator.\n\n Returns:\n An initializer.\n\n References:\n - Self-Normalizing Neural Networks,\n [Klambauer et al., 2017](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks) # pylint: disable=line-too-long\n ([pdf](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf))\n - Efficient Backprop,\n [Lecun et al., 1998](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf)\n \"\"\"\n return VarianceScaling(\n scale=1., mode=\"fan_in\", distribution=\"uniform\", seed=seed)\n\n\ndef he_normal(seed=None):\n \"\"\"He normal initializer.\n\n It draws samples from a truncated normal distribution centered on 0\n with `stddev = sqrt(2 / fan_in)`\n where `fan_in` is the number of input units in the weight tensor.\n\n Arguments:\n seed: A Python integer. Used to seed the random generator.\n\n Returns:\n An initializer.\n\n References:\n [He et al., 2015](https://www.cv-foundation.org/openaccess/content_iccv_2015/html/He_Delving_Deep_into_ICCV_2015_paper.html) # pylint: disable=line-too-long\n ([pdf](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf))\n \"\"\"\n return VarianceScaling(\n scale=2., mode=\"fan_in\", distribution=\"truncated_normal\", seed=seed)\n\n\ndef he_uniform(seed=None):\n \"\"\"He uniform variance scaling initializer.\n\n It draws samples from a uniform distribution within [-limit, limit]\n where `limit` is `sqrt(6 / fan_in)`\n where `fan_in` is the number of input units in the weight tensor.\n\n Arguments:\n seed: A Python integer. Used to seed the random generator.\n\n Returns:\n An initializer.\n\n References:\n [He et al., 2015](https://www.cv-foundation.org/openaccess/content_iccv_2015/html/He_Delving_Deep_into_ICCV_2015_paper.html) # pylint: disable=line-too-long\n ([pdf](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf))\n \"\"\"\n return VarianceScaling(\n scale=2., mode=\"fan_in\", distribution=\"uniform\", seed=seed)\n\n\n# Utility functions.\n\n\ndef _compute_fans(shape):\n \"\"\"Computes the number of input and output units for a weight shape.\n\n Args:\n shape: Integer shape tuple or TF tensor shape.\n\n Returns:\n A tuple of scalars (fan_in, fan_out).\n \"\"\"\n if len(shape) < 1: # Just to avoid errors for constants.\n fan_in = fan_out = 1\n elif len(shape) == 1:\n fan_in = fan_out = shape[0]\n elif len(shape) == 2:\n fan_in = shape[0]\n fan_out = shape[1]\n else:\n # Assuming convolution kernels (2D, 3D, or more).\n # kernel shape: (..., input_depth, depth)\n receptive_field_size = 1.\n for dim in shape[:-2]:\n receptive_field_size *= dim\n fan_in = shape[-2] * receptive_field_size\n fan_out = shape[-1] * receptive_field_size\n return fan_in, fan_out\n\n\ndef _assert_float_dtype(dtype):\n \"\"\"Validate and return floating point type based on `dtype`.\n\n `dtype` must be a floating point type.\n\n Args:\n dtype: The data type to validate.\n\n Returns:\n Validated type.\n\n Raises:\n ValueError: if `dtype` is not a floating point type.\n \"\"\"\n dtype = dtypes.as_dtype(dtype)\n if not dtype.is_floating:\n raise ValueError(\"Expected floating point type, got %s.\" % dtype)\n return dtype\n\n\nclass _RandomGenerator(object):\n \"\"\"Random generator that selects appropriate random ops.\"\"\"\n\n def __init__(self, seed=None):\n super(_RandomGenerator, self).__init__()\n if seed is not None:\n # Stateless random ops requires 2-int seed.\n self.seed = [seed, 0]\n else:\n self.seed = None\n\n def random_normal(self, shape, mean=0.0, stddev=1, dtype=dtypes.float32):\n \"\"\"A deterministic random normal if seed is passed.\"\"\"\n if self.seed:\n op = stateless_random_ops.stateless_random_normal\n else:\n op = random_ops.random_normal\n return op(\n shape=shape, mean=mean, stddev=stddev, dtype=dtype, seed=self.seed)\n\n def random_uniform(self, shape, minval, maxval, dtype):\n \"\"\"A deterministic random uniform if seed is passed.\"\"\"\n if self.seed:\n op = stateless_random_ops.stateless_random_uniform\n else:\n op = random_ops.random_uniform\n return op(\n shape=shape, minval=minval, maxval=maxval, dtype=dtype, seed=self.seed)\n\n def truncated_normal(self, shape, mean, stddev, dtype):\n \"\"\"A deterministic truncated normal if seed is passed.\"\"\"\n if self.seed:\n op = stateless_random_ops.stateless_truncated_normal\n else:\n op = random_ops.truncated_normal\n return op(\n shape=shape, mean=mean, stddev=stddev, dtype=dtype, seed=self.seed)\n\n# Compatibility aliases\n\n# pylint: disable=invalid-name\nzero = zeros = Zeros\none = ones = Ones\nconstant = Constant\nuniform = random_uniform = RandomUniform\nnormal = random_normal = RandomNormal\ntruncated_normal = TruncatedNormal\nidentity = Identity\northogonal = Orthogonal\nglorot_normal = GlorotNormal\nglorot_uniform = GlorotUniform\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 Relu and ReluGrad.\"\"\"\n\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\n\nfrom tensorflow.python.compat import compat\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gradient_checker\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import variables\nimport tensorflow.python.ops.nn_grad # pylint: disable=unused-import\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.training import gradient_descent\n\n\ndef _elu_grad_grad(activation):\n if activation < 0:\n return np.exp(activation)\n return 0\n\n\nclass ReluTest(test.TestCase):\n\n def _npRelu(self, np_features):\n return np.maximum(np_features, np.zeros(np_features.shape))\n\n def testNpRelu(self):\n self.assertAllClose(\n np.array([[0.0, 0.7, 0.0, 0.3, 0.0], [0.1, 0.0, 0.5, 0.0, 0.9]]),\n self._npRelu(\n np.array([[-0.9, 0.7, -0.5, 0.3, -0.1], [0.1, -0.3, 0.5, -0.7,\n 0.9]])))\n\n def _testRelu(self, np_features, use_gpu=False):\n np_relu = self._npRelu(np_features)\n with self.test_session(use_gpu=use_gpu):\n relu = nn_ops.relu(np_features)\n tf_relu = relu.eval()\n self.assertAllClose(np_relu, tf_relu)\n self.assertShapeEqual(np_relu, relu)\n\n def testNumbers(self):\n for t in [np.int32, np.int64, np.float16, np.float32, np.float64]:\n self._testRelu(\n np.array([[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]]).astype(t),\n use_gpu=False)\n if t in [np.float16, np.float32, np.float64]:\n self._testRelu(\n np.array([[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]]).astype(t),\n use_gpu=True)\n\n def _testReluInt8x4(self, np_inputs):\n if not test.is_gpu_available(cuda_only=True):\n return\n np_relu = self._npRelu(np_inputs)\n with self.test_session(use_gpu=True):\n relu = nn_ops.relu(constant_op.constant(np_inputs, dtypes.qint8))\n if np_inputs.size % 4 == 0:\n tf_relu = relu.eval()\n self.assertAllClose(np_relu, tf_relu)\n self.assertShapeEqual(np_relu, relu)\n else:\n with self.assertRaisesRegexp(\n errors.InvalidArgumentError,\n \"Tensor size must be a multiple of 4 for Relu<qint8>. Got %d\" %\n np_inputs.size):\n tf_relu = relu.eval()\n\n def testReluInt8x4GoodShape(self):\n self._testReluInt8x4(np.array([[-50, 7, 23, 0], [-1, -5, 6, 11]]))\n\n @test_util.disable_xla(\"b/123338077\") # Passes with XLA\n def testReluInt8x4BadShape(self):\n np_inputs = np.array([[-50, 7, 23], [0, 1, -5], [6, -2, 11]])\n self.assertEqual(np_inputs.size, 9)\n self._testReluInt8x4(np_inputs)\n np_inputs = np.array(\n [1, -2, 3, -4, 5, -6, 7, -8, 9, -8, 7, -6, 5, -4, 3, -2, 1])\n self.assertEqual(np_inputs.size, 17)\n self._testReluInt8x4(np_inputs)\n\n # The gradient test for ReLU is a bit tricky as the derivative is not well\n # defined at around zero and we want to avoid that in terms of input values.\n def testGradientFloat32(self):\n with self.cached_session():\n x = constant_op.constant(\n [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9],\n shape=[2, 5],\n name=\"x\")\n y = nn_ops.relu(x, name=\"relu\")\n x_init = np.asarray(\n [[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]],\n dtype=np.float32,\n order=\"F\")\n err = gradient_checker.compute_gradient_error(\n x, [2, 5], y, [2, 5], x_init_value=x_init)\n print(\"relu (float32) gradient err = \", err)\n self.assertLess(err, 1e-4)\n\n # The gradient for fp16 is inaccurate due to the low-precision.\n # Instead of relying on compute_gradient_error, we compare the fp16 analytical\n # gradient against their fp32 counterpart.\n def testGradientFloat16(self):\n with self.test_session(use_gpu=True) as sess:\n # Randomly construct a 1D shape from [1, 40)\n shape = random_ops.random_uniform(\n [1], minval=1, maxval=40, dtype=dtypes.int32)\n\n # Construct the fp32 graph and its gradient.\n x = random_ops.random_uniform(shape, minval=-1, maxval=1, name=\"x\")\n y1 = nn_ops.relu(x, name=\"relu_fp32\")\n l1 = nn_ops.l2_loss(y1)\n dx_f32 = gradients_impl.gradients(l1, x)\n\n # Construct the fp16 graph and its gradient.\n # It starts with the same x, in fp32. But before it reaches Relu, it is\n # cast into fp16. So during backprop, the gradient computation is in fp16.\n x2 = math_ops.cast(x, dtype=dtypes.float16, name=\"cast\")\n y2 = nn_ops.relu(x2, name=\"relu_fp16\")\n l2 = nn_ops.l2_loss(y2)\n dx_f16 = gradients_impl.gradients(l2, x)\n\n # Repeat the experiment for 100 times. All tensor shapes and its tensor\n # values are randomly generated for each run.\n for _ in xrange(100):\n dx_f32_v, dx_f16_v = sess.run([dx_f32, dx_f16])\n self.assertAllClose(dx_f32_v, dx_f16_v, atol=3e-4)\n\n def testGradientFloat64(self):\n with self.cached_session():\n x = constant_op.constant(\n [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9],\n shape=[2, 5],\n dtype=dtypes.float64,\n name=\"x\")\n y = nn_ops.relu(x, name=\"relu\")\n x_init = np.asarray(\n [[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]],\n dtype=np.float64,\n order=\"F\")\n err = gradient_checker.compute_gradient_error(\n x, [2, 5], y, [2, 5], x_init_value=x_init)\n print(\"relu (float64) gradient err = \", err)\n self.assertLess(err, 1e-10)\n\n def testGradGradFloat32(self):\n with self.cached_session():\n x = constant_op.constant(\n [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9],\n shape=[2, 5],\n name=\"x\")\n y = nn_ops.relu(x, name=\"relu\")\n z = gradients_impl.gradients(y, x)\n x_init = np.asarray(\n [[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]],\n dtype=np.float32,\n order=\"F\")\n err = gradient_checker.compute_gradient_error(\n x, [2, 5], z[0], [2, 5], x_init_value=x_init)\n print(\"relu (float32) gradient of gradient err = \", err)\n self.assertLess(err, 1e-4)\n\n def testGradGradFloat64(self):\n with self.cached_session():\n x = constant_op.constant(\n [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9],\n shape=[2, 5],\n dtype=dtypes.float64,\n name=\"x\")\n y = nn_ops.relu(x, name=\"relu\")\n z = gradients_impl.gradients(y, x)\n x_init = np.asarray(\n [[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]],\n dtype=np.float64,\n order=\"F\")\n err = gradient_checker.compute_gradient_error(\n x, [2, 5], z[0], [2, 5], x_init_value=x_init)\n print(\"relu (float64) gradient of gradient err = \", err)\n self.assertLess(err, 1e-10)\n\n def testGradientScalar(self):\n with self.cached_session() as sess:\n x = variables.Variable(100.)\n y = nn_ops.relu(x)\n loss = y**2\n optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=0.25)\n train_op = optimizer.minimize(loss)\n sess.run(variables.global_variables_initializer())\n sess.run(train_op)\n self.assertAllClose(x.eval(), 50.0)\n\n\nclass Relu6Test(test.TestCase):\n\n def _npRelu6(self, np_features):\n sixes = np.copy(np_features)\n sixes.fill(6.0)\n return np.minimum(\n np.maximum(np_features, np.zeros(np_features.shape)), sixes)\n\n def testNpRelu6(self):\n self.assertAllClose(\n np.array([[0.0, 0.7, 0.0, 0.3, 6.0], [0.1, 0.0, 6.0, 0.0, 0.9]]),\n self._npRelu6(\n np.array([[-0.9, 0.7, -0.5, 0.3, 6.0], [0.1, -0.3, 6.5, -0.7,\n 0.9]])))\n\n def _testRelu6(self, np_features, use_gpu=False):\n np_relu6 = self._npRelu6(np_features)\n with self.test_session(use_gpu=use_gpu):\n relu6 = nn_ops.relu6(np_features)\n tf_relu6 = relu6.eval()\n self.assertAllClose(np_relu6, tf_relu6)\n self.assertShapeEqual(np_relu6, relu6)\n\n def testNumbers(self):\n for t in [np.int32, np.int64, np.float16, np.float32, np.float64]:\n self._testRelu6(\n np.array([[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]]).astype(t),\n use_gpu=False)\n if t in [np.float16, np.float, np.double]:\n self._testRelu6(\n np.array([[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]]).astype(t),\n use_gpu=True)\n\n # The gradient test for ReLU6 is a bit tricky as the derivative is\n # not well defined at around zero and six and we want to avoid that\n # in terms of input values.\n def testGradientFloat32(self):\n with self.cached_session():\n x = constant_op.constant(\n [-0.9, -0.7, -0.5, -0.3, -0.1, 6.1, 6.3, 6.5, 6.7, 6.9],\n shape=[2, 5],\n name=\"x\")\n y = nn_ops.relu6(x, name=\"relu6\")\n x_init = np.asarray(\n [[-0.9, -0.7, -0.5, -0.3, -0.1], [6.1, 6.3, 6.5, 6.7, 6.9]],\n dtype=np.float32,\n order=\"F\")\n err = gradient_checker.compute_gradient_error(\n x, [2, 5], y, [2, 5], x_init_value=x_init)\n print(\"relu6 (float32) gradient err = \", err)\n self.assertLess(err, 1e-4)\n\n def testGradientFloat64(self):\n with self.cached_session():\n x = constant_op.constant(\n [-0.9, -0.7, -0.5, -0.3, -0.1, 6.1, 6.3, 6.5, 6.7, 6.9],\n shape=[2, 5],\n dtype=dtypes.float64,\n name=\"x\")\n y = nn_ops.relu6(x, name=\"relu6\")\n x_init = np.asarray(\n [[-0.9, -0.7, -0.5, -0.3, -0.1], [6.1, 6.3, 6.5, 6.7, 6.9]],\n dtype=np.float64,\n order=\"F\")\n err = gradient_checker.compute_gradient_error(\n x, [2, 5], y, [2, 5], x_init_value=x_init)\n print(\"relu6 (float64) gradient err = \", err)\n self.assertLess(err, 1e-10)\n\n\nclass LeakyReluTest(test.TestCase):\n\n def _npLeakyRelu(self, np_features, alpha=0.1):\n return np.maximum(np_features, alpha * np_features)\n\n def testNpLeakyRelu(self):\n self.assertAllClose(\n np.array([[-0.09, 0.7, -0.05, 0.3, -0.01],\n [0.1, -0.03, 0.5, -0.07, 0.9]]),\n self._npLeakyRelu(\n np.array([[-0.9, 0.7, -0.5, 0.3, -0.1], [0.1, -0.3, 0.5, -0.7,\n 0.9]]),\n alpha=0.1))\n\n def _testLeakyRelu(self, np_features, alpha, use_gpu=False):\n np_leaky_relu = self._npLeakyRelu(np_features, alpha)\n with self.test_session(use_gpu=use_gpu):\n leaky_relu = nn_ops.leaky_relu(np_features, alpha)\n tf_leaky_relu = leaky_relu.eval()\n self.assertAllClose(np_leaky_relu, tf_leaky_relu)\n self.assertShapeEqual(np_leaky_relu, leaky_relu)\n\n def testNumbers(self):\n for t in [np.int32, np.int64, np.float16, np.float32, np.float64]:\n self._testLeakyRelu(\n np.array([[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]]).astype(t),\n alpha=0.2,\n use_gpu=False)\n if t in [np.float16, np.float32, np.float64]:\n self._testLeakyRelu(\n np.array([[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]]).astype(t),\n alpha=0.1,\n use_gpu=True)\n\n # The gradient test for Leaky ReLU is a bit tricky as the derivative is not\n # well defined at around zero and we want to avoid that in terms of input\n # values.\n def testGradientFloat32(self):\n with self.test_session():\n x = constant_op.constant(\n [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9],\n shape=[2, 5],\n name=\"x\")\n y = nn_ops.leaky_relu(x, alpha=0.1, name=\"leaky_relu\")\n x_init = np.asarray(\n [[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]],\n dtype=np.float32,\n order=\"F\")\n err = gradient_checker.compute_gradient_error(\n x, [2, 5], y, [2, 5], x_init_value=x_init)\n print(\"leaky_relu (float32) gradient err = \", err)\n self.assertLess(err, 1e-4)\n\n def testGradientFloat64(self):\n with self.test_session():\n x = constant_op.constant(\n [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9],\n shape=[2, 5],\n dtype=dtypes.float64,\n name=\"x\")\n y = nn_ops.leaky_relu(x, alpha=0.2, name=\"leaky_relu\")\n x_init = np.asarray(\n [[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]],\n dtype=np.float64,\n order=\"F\")\n err = gradient_checker.compute_gradient_error(\n x, [2, 5], y, [2, 5], x_init_value=x_init)\n print(\"leaky_relu (float64) gradient err = \", err)\n self.assertLess(err, 1e-10)\n\n def testGradGradFloat32(self):\n with compat.forward_compatibility_horizon(2018, 11, 2):\n with self.test_session():\n x = constant_op.constant(\n [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9],\n shape=[2, 5],\n name=\"x\")\n y = nn_ops.leaky_relu(x, alpha=0.1, name=\"leaky_relu\")\n z = gradients_impl.gradients(y, x)\n x_init = np.asarray(\n [[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]],\n dtype=np.float32,\n order=\"F\")\n err = gradient_checker.compute_gradient_error(\n x, [2, 5], z[0], [2, 5], x_init_value=x_init)\n print(\"leaky_relu (float32) gradient of gradient err = \", err)\n self.assertLess(err, 1e-4)\n\n def testGradGradFloat64(self):\n with compat.forward_compatibility_horizon(2018, 11, 2):\n with self.test_session():\n x = constant_op.constant(\n [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9],\n shape=[2, 5],\n dtype=dtypes.float64,\n name=\"x\")\n y = nn_ops.leaky_relu(x, alpha=0.02, name=\"leaky_relu\")\n z = gradients_impl.gradients(y, x)\n x_init = np.asarray(\n [[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]],\n dtype=np.float64,\n order=\"F\")\n err = gradient_checker.compute_gradient_error(\n x, [2, 5], z[0], [2, 5], x_init_value=x_init)\n print(\"leaky_relu (float64) gradient of gradient err = \", err)\n self.assertLess(err, 1e-10)\n\n def testGradientScalar(self):\n with self.test_session() as sess:\n x = variables.Variable(-100.)\n y = nn_ops.leaky_relu(x, 0.05)\n loss = y**2\n optimizer = gradient_descent.GradientDescentOptimizer(learning_rate=0.2)\n train_op = optimizer.minimize(loss)\n sess.run(variables.global_variables_initializer())\n sess.run(train_op)\n self.assertAllClose(x.eval(), -99.9)\n\n\nclass EluTest(test.TestCase):\n\n def _npElu(self, np_features):\n return np.where(np_features < 0, np.exp(np_features) - 1, np_features)\n\n def testNpElu(self):\n self.assertAllClose(\n np.array([[-0.59343034025, 0.7, -0.39346934028, 0.3, -0.09516258196],\n [0.1, -0.25918177931, 0.5, -0.5034146962, 0.9]]),\n self._npElu(\n np.array([[-0.9, 0.7, -0.5, 0.3, -0.1], [0.1, -0.3, 0.5, -0.7,\n 0.9]])))\n\n def _testElu(self, np_features, use_gpu=False):\n np_elu = self._npElu(np_features)\n with self.test_session(use_gpu=use_gpu):\n elu = nn_ops.elu(np_features)\n tf_elu = elu.eval()\n self.assertAllClose(np_elu, tf_elu)\n self.assertShapeEqual(np_elu, elu)\n\n def testNumbers(self):\n for t in [np.float16, np.float32, np.float64]:\n self._testElu(\n np.array([[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]]).astype(t),\n use_gpu=False)\n self._testElu(\n np.array([[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]]).astype(t),\n use_gpu=True)\n\n def testGradientFloat32(self):\n with self.cached_session():\n x_val = [[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]]\n x = constant_op.constant(x_val, name=\"x\")\n y = nn_ops.elu(x, name=\"elu\")\n x_init = np.asarray(x_val, dtype=np.float32, order=\"F\")\n err = gradient_checker.compute_gradient_error(\n x, [2, 5], y, [2, 5], x_init_value=x_init)\n print(\"elu (float32) gradient err = \", err)\n self.assertLess(err, 1e-4)\n\n def testGradientFloat64(self):\n with self.cached_session():\n x_val = [[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]]\n x = constant_op.constant(x_val, dtype=dtypes.float64, name=\"x\")\n y = nn_ops.elu(x, name=\"elu\")\n x_init = np.asarray(x_val, dtype=np.float64, order=\"F\")\n err = gradient_checker.compute_gradient_error(\n x, [2, 5], y, [2, 5], x_init_value=x_init)\n print(\"elu (float64) gradient err = \", err)\n self.assertLess(err, 1e-6)\n\n def testGradGrad(self):\n with self.cached_session():\n x = array_ops.placeholder(dtype=dtypes.float32)\n elu = nn_ops.elu(x)\n g, = gradients_impl.gradients(elu, x)\n gg, = gradients_impl.gradients(g, x)\n\n for x_val in [-1, -0.5, 0.5, 1]:\n err = np.abs(gg.eval(feed_dict={x: x_val}) - _elu_grad_grad(x_val))\n self.assertLess(err, 1e-4)\n\n def testGradGradFloat32(self):\n with self.cached_session():\n x = constant_op.constant(\n [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9],\n shape=[2, 5],\n name=\"x\")\n y = nn_ops.elu(x, name=\"elu\")\n z = gradients_impl.gradients(y, x)\n x_init = np.asarray(\n [[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]],\n dtype=np.float32,\n order=\"F\")\n err = gradient_checker.compute_gradient_error(\n x, [2, 5], z[0], [2, 5], x_init_value=x_init)\n print(\"elu (float32) gradient of gradient err = \", err)\n self.assertLess(err, 1e-4)\n\n def testGradGradFloat64(self):\n with self.cached_session():\n x = constant_op.constant(\n [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9],\n shape=[2, 5],\n dtype=dtypes.float64,\n name=\"x\")\n y = nn_ops.elu(x, name=\"elu\")\n z = gradients_impl.gradients(y, x)\n x_init = np.asarray(\n [[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]],\n dtype=np.float64,\n order=\"F\")\n err = gradient_checker.compute_gradient_error(\n x, [2, 5], z[0], [2, 5], x_init_value=x_init)\n print(\"elu (float64) gradient of gradient err = \", err)\n self.assertLess(err, 1e-6)\n\n\nclass SeluTest(test.TestCase):\n\n def _npSelu(self, np_features):\n scale = 1.0507009873554804934193349852946\n scale_alpha = 1.7580993408473768599402175208123\n return np.where(np_features < 0, scale_alpha * (np.exp(np_features) - 1),\n scale * np_features)\n\n def testNpSelu(self):\n self.assertAllClose(\n np.array([[-1.0433095, 0.73549069, -0.6917582, 0.3152103, -0.16730527],\n [0.1050701, -0.45566732, 0.5253505, -0.88505305, 0.9456309]]),\n self._npSelu(\n np.array([[-0.9, 0.7, -0.5, 0.3, -0.1], [0.1, -0.3, 0.5, -0.7,\n 0.9]])))\n\n def _testSelu(self, np_features, use_gpu=False):\n np_selu = self._npSelu(np_features)\n with self.test_session(use_gpu=use_gpu):\n selu = nn_ops.selu(np_features)\n tf_selu = selu.eval()\n self.assertAllClose(np_selu, tf_selu)\n self.assertShapeEqual(np_selu, selu)\n\n def testNumbers(self):\n for t in [np.float16, np.float32, np.float64]:\n self._testSelu(\n np.array([[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]]).astype(t))\n # Force executed on CPU in case GPU kernels are available.\n with ops.device(\"/device:CPU:0\"):\n self._testSelu(\n np.array([[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]]).astype(t))\n\n def testGradientFloat32(self):\n with self.cached_session():\n x_val = [[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]]\n x = constant_op.constant(x_val, name=\"x\")\n y = nn_ops.selu(x, name=\"selu\")\n x_init = np.asarray(x_val, dtype=np.float32, order=\"F\")\n err = gradient_checker.compute_gradient_error(\n x, [2, 5], y, [2, 5], x_init_value=x_init)\n print(\"selu (float32) gradient err = \", err)\n self.assertLess(err, 1e-4)\n\n def testGradientFloat64(self):\n with self.cached_session():\n x_val = [[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]]\n x = constant_op.constant(x_val, dtype=dtypes.float64, name=\"x\")\n y = nn_ops.selu(x, name=\"selu\")\n x_init = np.asarray(x_val, dtype=np.float64, order=\"F\")\n err = gradient_checker.compute_gradient_error(\n x, [2, 5], y, [2, 5], x_init_value=x_init)\n print(\"selu (float64) gradient err = \", err)\n self.assertLess(err, 1e-6)\n\n def testGradGradFloat32(self):\n with self.cached_session():\n x = constant_op.constant(\n [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9],\n shape=[2, 5],\n name=\"x\")\n y = nn_ops.selu(x, name=\"selu\")\n z = gradients_impl.gradients(y, x)\n x_init = np.asarray(\n [[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]],\n dtype=np.float32,\n order=\"F\")\n err = gradient_checker.compute_gradient_error(\n x, [2, 5], z[0], [2, 5], x_init_value=x_init)\n print(\"selu (float32) gradient of gradient err = \", err)\n self.assertLess(err, 1e-4)\n\n def testGradGradFloat64(self):\n with self.cached_session():\n x = constant_op.constant(\n [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9],\n shape=[2, 5],\n dtype=dtypes.float64,\n name=\"x\")\n y = nn_ops.selu(x, name=\"selu\")\n z = gradients_impl.gradients(y, x)\n x_init = np.asarray(\n [[-0.9, -0.7, -0.5, -0.3, -0.1], [0.1, 0.3, 0.5, 0.7, 0.9]],\n dtype=np.float64,\n order=\"F\")\n err = gradient_checker.compute_gradient_error(\n x, [2, 5], z[0], [2, 5], x_init_value=x_init)\n print(\"selu (float64) gradient of gradient err = \", err)\n self.assertLess(err, 1e-6)\n\n\nclass CreluTest(test.TestCase):\n\n def testCreluShape(self):\n f = random_ops.random_normal([50, 5, 7, 10])\n t = nn_ops.crelu(f)\n self.assertEqual([50, 5, 7, 20], t.get_shape())\n\n def _testCrelu(self, np_features, use_gpu=False):\n np_relu = np.maximum(np_features, np.zeros_like(np_features))\n np_neg_relu = np.maximum(-np_features, np.zeros_like(np_features))\n np_crelu = np.concatenate((np_relu, np_neg_relu),\n len(np_features.shape) - 1)\n\n with self.test_session(use_gpu=use_gpu):\n crelu = nn_ops.crelu(np_features)\n tf_relu = crelu.eval()\n\n self.assertAllClose(np_crelu, tf_relu)\n self.assertShapeEqual(np_crelu, crelu)\n\n def testNumbers(self):\n for t in [np.int32, np.int64, np.float16, np.float32, np.float64]:\n self._testCrelu(\n np.array([[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]]).astype(t),\n use_gpu=False)\n if t in [np.float16, np.float32, np.float64]:\n self._testCrelu(\n np.array([[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]]).astype(t),\n use_gpu=True)\n\n def testNumbersWithAxis0(self):\n with self.cached_session():\n crelu = nn_ops.crelu(\n np.array([[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]]), axis=0)\n tf_relu = crelu.eval()\n np_crelu = np.array([[0, 7, 0, 3, 0], [1, 0, 5, 0, 9], [9, 0, 5, 0, 1],\n [0, 3, 0, 7, 0]])\n self.assertAllEqual(np_crelu, tf_relu)\n\n def testNumbersWithAxis1(self):\n with self.cached_session():\n crelu = nn_ops.crelu(\n np.array([[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]]), axis=1)\n tf_relu = crelu.eval()\n np_crelu = np.array([[0, 7, 0, 3, 0, 9, 0, 5, 0, 1],\n [1, 0, 5, 0, 9, 0, 3, 0, 7, 0]])\n self.assertAllEqual(np_crelu, tf_relu)\n\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\"\"\"Functional tests for quantized convolutional operations.\"\"\"\n\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 constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.platform import test\n\n\nclass Conv2DTest(test.TestCase):\n\n def __init__(self, method_name=\"runTest\"):\n super(Conv2DTest, self).__init__(method_name)\n\n def _VerifyValues(self, tensor_in_sizes, filter_in_sizes, stride, padding,\n expected):\n \"\"\"Verifies the output values of the convolution function.\n\n Args:\n tensor_in_sizes: Input tensor dimensions in\n [batch, input_rows, input_cols, input_depth].\n filter_in_sizes: Filter tensor dimensions in\n [kernel_rows, kernel_cols, input_depth, output_depth].\n stride: Stride.\n padding: Padding type.\n expected: An array containing the expected operation outputs.\n \"\"\"\n total_size_1 = 1\n total_size_2 = 1\n for s in tensor_in_sizes:\n total_size_1 *= s\n for s in filter_in_sizes:\n total_size_2 *= s\n # Initializes the input tensor with array containing incrementing\n # numbers from 1.\n x1 = np.array([f for f in range(1, total_size_1 + 1)])\n x1 = x1.astype(np.uint8).reshape(tensor_in_sizes)\n x1_min = 0.0\n x1_max = 255.0\n x2 = np.array([f for f in range(1, total_size_2 + 1)]).astype(np.uint8)\n x2 = x2.astype(np.uint8).reshape(filter_in_sizes)\n x2_min = 0.0\n x2_max = 255.0\n with self.cached_session(use_gpu=False) as sess:\n t1 = constant_op.constant(x1, shape=tensor_in_sizes, dtype=dtypes.quint8)\n t2 = constant_op.constant(x2, shape=filter_in_sizes, dtype=dtypes.quint8)\n conv = nn_ops.quantized_conv2d(\n t1,\n t2,\n out_type=dtypes.qint32,\n strides=[1, stride, stride, 1],\n padding=padding,\n min_input=x1_min,\n max_input=x1_max,\n min_filter=x2_min,\n max_filter=x2_max)\n value = sess.run(conv)\n quantized_output = value[0]\n output_min = value[1]\n output_max = value[2]\n float_output = self._QuantizedOutputToFloat(quantized_output, output_min,\n output_max)\n self.assertArrayNear(expected, float_output.flatten(), 1.0)\n self.assertEqual(value[0].shape, conv[0].get_shape())\n\n def _assertQuantizedArrayEquals(self, iarray1, iarray2):\n for i1, i2 in zip(iarray1, iarray2):\n self.assertTrue(i1 == i2)\n\n def _QuantizedOutputToFloat(self, quantized, quantized_min, quantized_max):\n number_of_bits = 32\n number_of_steps = 1 << number_of_bits\n range_adjust = (number_of_steps / (number_of_steps - 1.0))\n quantized_range = ((quantized_max - quantized_min) * range_adjust)\n range_scale = (quantized_range / number_of_steps)\n lowest_quantized = -(1 << (number_of_bits - 1))\n result = np.array([(quantized_min +\n ((float(x) - lowest_quantized) * range_scale))\n for x in quantized.flatten()])\n return result\n\n def testConv2D1x1Filter(self):\n # Our generated input is [batch, rows, cols, depth], and looks like this:\n # (1,2,3) (4,5,6) (7,8,9)\n # (10,11,12) (13,14,15) (16,17,18)\n # The filter data is:\n # (1,4,7) (2,5,8) (3,6,9)\n # That means the calculations are:\n # 1*1+2*4+3*7=30\n # 1*2+2*5+3*8=36\n # 1*3+2*6+3*9=42\n # 4*1+5*4+6*7=66\n # 4*2+5*5+6*8=81\n # 4*3+5*6+6*9=96\n # 7*1+5*8+6*9=102\n # 7*2+8*5+9*8=126\n # 7*3+8*6+9*9=150\n # 10*1+11*4+12*7=138\n # 10*2+11*5+12*8=171\n # 10*3+11*6+12*9=204\n # 13*1+14*4+15*7=174\n # 13*2+14*5+15*8=216\n # 13*3+14*6+15*9=258, clamped to 255\n # 16*1+17*4+18*7=210\n # 16*2+17*5+18*8=261, clamped to 255\n # 16*3+17*6+18*9=312, clamped to 255\n # Because the output shift is zero, we call the non-optimized reference\n # path for the convolution.\n expected_output = [\n 30, 36, 42, 66, 81, 96, 102, 126, 150, 138, 171, 204, 174, 216, 258,\n 210, 261, 312\n ]\n self._VerifyValues(\n tensor_in_sizes=[1, 2, 3, 3],\n filter_in_sizes=[1, 1, 3, 3],\n stride=1,\n padding=\"VALID\",\n expected=expected_output)\n\n def testConv2D2x2Filter(self):\n # Our generated input is [batch, rows, cols, depth], and looks like this:\n # (1,2,3) (4,5,6) (7,8,9)\n # (10,11,12) (13,14,15) (16,17,18)\n # The filter data is [filter_height, filter_width, depth, filter_count]:\n # ( 1, 4, 7) (10, 13, 16)\n # (19,22,25) (28, 31, 34)\n # -\n # ( 2, 5, 8) (11, 14, 17)\n # (20,23,26) (29, 32, 35)\n # -\n # ( 3, 6, 9) (12, 15, 18)\n # (21,24,27) (30, 33, 36)\n # The raw accumulated totals are:\n # 1*1+2*4+3*7+4*10+5*13+6*16+10*19+11*22+12*25+13*28+14*31+15*34=2271\n # 1*2+2*5+3*8+4*11+5*14+6*17+10*20+11*23+12*26+13*29+14*32+15*35=2367\n # 1*3+2*6+3*9+4*12+5*15+6*18+10*21+11*24+12*27+13*30+14*33+15*36=2463\n # 4*1+5*4+6*7+7*10+8*13+9*16+13*19+14*22+15*25+16*28+17*31+18*34=2901\n # 4*2+5*5+6*8+7*11+8*14+9*17+13*20+14*23+15*26+16*29+17*32+18*35=3033\n # 4*3+5*6+6*9+7*12+8*15+9*18+13*21+14*24+15*27+16*30+17*33+18*36=3165\n # The expected values are taken from the raw totals and rescaled to fit into\n # eight bits.\n expected_output = [2271.0, 2367.0, 2463.0, 2901.0, 3033.0, 3165.0]\n self._VerifyValues(\n tensor_in_sizes=[1, 2, 3, 3],\n filter_in_sizes=[2, 2, 3, 3],\n stride=1,\n padding=\"VALID\",\n expected=expected_output)\n\n def testConv2D1x2Filter(self):\n # The outputs are computed using third_party/py/IPython/notebook.\n # With a shift of 21, we should execute the optimized path here.\n expected_output = [\n 231.0, 252.0, 273.0, 384.0, 423.0, 462.0, 690.0, 765.0, 840.0, 843.0,\n 936.0, 1029.0\n ]\n self._VerifyValues(\n tensor_in_sizes=[1, 2, 3, 3],\n filter_in_sizes=[1, 2, 3, 3],\n stride=1,\n padding=\"VALID\",\n expected=expected_output)\n\n def testConv2D2x2FilterStride2(self):\n # With a shift of 21, we should execute the optimized path here.\n expected_output = [2271.0, 2367.0, 2463.0]\n self._VerifyValues(\n tensor_in_sizes=[1, 2, 3, 3],\n filter_in_sizes=[2, 2, 3, 3],\n stride=2,\n padding=\"VALID\",\n expected=expected_output)\n\n def testConv2D2x2FilterStride2Same(self):\n # With a shift of 21, we should execute the optimized path here.\n expected_output = [2271.0, 2367.0, 2463.0, 1230.0, 1305.0, 1380.0]\n self._VerifyValues(\n tensor_in_sizes=[1, 2, 3, 3],\n filter_in_sizes=[2, 2, 3, 3],\n stride=2,\n padding=\"SAME\",\n expected=expected_output)\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# ==============================================================================\n\"\"\"Tests for the experimental input pipeline ops.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.data.experimental.ops import interleave_ops\nfrom tensorflow.python.data.kernel_tests import test_base\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import random_seed\nfrom tensorflow.python.platform import test\n\n\nclass DirectedInterleaveDatasetTest(test_base.DatasetTestBase):\n\n def testBasic(self):\n selector_dataset = dataset_ops.Dataset.range(10).repeat(100)\n input_datasets = [\n dataset_ops.Dataset.from_tensors(i).repeat(100) for i in range(10)\n ]\n dataset = interleave_ops._DirectedInterleaveDataset(selector_dataset,\n input_datasets)\n iterator = dataset.make_initializable_iterator()\n next_element = iterator.get_next()\n\n with self.cached_session() as sess:\n sess.run(iterator.initializer)\n for _ in range(100):\n for i in range(10):\n self.assertEqual(i, sess.run(next_element))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(next_element)\n\n def _normalize(self, vec):\n return vec / vec.sum()\n\n def _chi2(self, expected, actual):\n actual = np.asarray(actual)\n expected = np.asarray(expected)\n diff = actual - expected\n chi2 = np.sum(diff * diff / expected, axis=0)\n return chi2\n\n def _testSampleFromDatasetsHelper(self, weights, num_datasets, num_samples):\n # Create a dataset that samples each integer in `[0, num_datasets)`\n # with probability given by `weights[i]`.\n dataset = interleave_ops.sample_from_datasets([\n dataset_ops.Dataset.from_tensors(i).repeat(None)\n for i in range(num_datasets)\n ], weights)\n dataset = dataset.take(num_samples)\n iterator = dataset.make_one_shot_iterator()\n next_element = iterator.get_next()\n\n with self.cached_session() as sess:\n freqs = np.zeros([num_datasets])\n for _ in range(num_samples):\n freqs[sess.run(next_element)] += 1\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(next_element)\n\n return freqs\n\n def testSampleFromDatasets(self):\n random_seed.set_random_seed(1619)\n num_samples = 5000\n rand_probs = self._normalize(np.random.random_sample((15,)))\n\n # Use chi-squared test to assert that the observed distribution matches the\n # expected distribution. Based on the implementation in\n # \"third_party/tensorflow/python/kernel_tests/multinomial_op_test.py\".\n for probs in [[.85, .05, .1], rand_probs, [1.]]:\n probs = np.asarray(probs)\n classes = len(probs)\n freqs = self._testSampleFromDatasetsHelper(probs, classes, num_samples)\n self.assertLess(self._chi2(probs, freqs / num_samples), 1e-2)\n\n # Also check that `weights` as a dataset samples correctly.\n probs_ds = dataset_ops.Dataset.from_tensors(probs).repeat()\n freqs = self._testSampleFromDatasetsHelper(probs_ds, classes, num_samples)\n self.assertLess(self._chi2(probs, freqs / num_samples), 1e-2)\n\n def testSelectFromDatasets(self):\n words = [b\"foo\", b\"bar\", b\"baz\"]\n datasets = [dataset_ops.Dataset.from_tensors(w).repeat() for w in words]\n choice_array = np.random.randint(3, size=(15,), dtype=np.int64)\n choice_dataset = dataset_ops.Dataset.from_tensor_slices(choice_array)\n dataset = interleave_ops.choose_from_datasets(datasets, choice_dataset)\n iterator = dataset.make_one_shot_iterator()\n next_element = iterator.get_next()\n\n with self.cached_session() as sess:\n for i in choice_array:\n self.assertEqual(words[i], sess.run(next_element))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(next_element)\n\n def testErrors(self):\n with self.assertRaisesRegexp(ValueError,\n r\"vector of length `len\\(datasets\\)`\"):\n interleave_ops.sample_from_datasets(\n [dataset_ops.Dataset.range(10),\n dataset_ops.Dataset.range(20)],\n weights=[0.25, 0.25, 0.25, 0.25])\n\n with self.assertRaisesRegexp(TypeError, \"`tf.float32` or `tf.float64`\"):\n interleave_ops.sample_from_datasets(\n [dataset_ops.Dataset.range(10),\n dataset_ops.Dataset.range(20)],\n weights=[1, 1])\n\n with self.assertRaisesRegexp(TypeError, \"must have the same type\"):\n interleave_ops.sample_from_datasets([\n dataset_ops.Dataset.from_tensors(0),\n dataset_ops.Dataset.from_tensors(0.0)\n ])\n\n with self.assertRaisesRegexp(TypeError, \"tf.int64\"):\n interleave_ops.choose_from_datasets([\n dataset_ops.Dataset.from_tensors(0),\n dataset_ops.Dataset.from_tensors(1)\n ], choice_dataset=dataset_ops.Dataset.from_tensors(1.0))\n\n with self.assertRaisesRegexp(TypeError, \"scalar\"):\n interleave_ops.choose_from_datasets([\n dataset_ops.Dataset.from_tensors(0),\n dataset_ops.Dataset.from_tensors(1)\n ], choice_dataset=dataset_ops.Dataset.from_tensors([1.0]))\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# ==============================================================================\n\"\"\"Tests for experimental indexed dataset ops.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport unittest\n\nfrom tensorflow.python.data.experimental.ops import indexed_dataset_ops\nfrom tensorflow.python.data.kernel_tests import test_base\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops\nfrom tensorflow.python.platform import test\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass IndexedDatasetOpsTest(test_base.DatasetTestBase):\n\n def testLowLevelIndexedDatasetOps(self):\n identity = ged_ops.experimental_identity_indexed_dataset(\n ops.convert_to_tensor(16, dtype=dtypes.uint64))\n handle = ged_ops.experimental_materialized_index_dataset_handle(\n container=\"\",\n shared_name=\"\",\n output_types=[dtypes.uint64],\n output_shapes=[[]])\n materialize = ged_ops.experimental_indexed_dataset_materialize(\n identity, handle)\n get_op = ged_ops.experimental_indexed_dataset_get(\n handle, 3, output_types=[dtypes.uint64], output_shapes=[[]])\n\n self.evaluate(materialize)\n self.assertEqual([3], self.evaluate(get_op))\n\n # TODO(b/117581999): Eager mode not supported.\n @test_util.run_deprecated_v1\n def testSkipEagerIdentityIndexedDataset(self):\n ds = indexed_dataset_ops.IdentityIndexedDataset(16)\n materialized = ds.materialize()\n self.evaluate(materialized.initializer)\n for i in range(16):\n output = self.evaluate(materialized.get(i))\n self.assertEqual([i], output)\n with self.assertRaises(errors.InvalidArgumentError):\n self.evaluate(materialized.get(16))\n\n @unittest.skip(\"Requisite functionality currently unimplemented.\")\n def testIdentityIndexedDatasetIterator(self):\n ds = indexed_dataset_ops.IdentityIndexedDataset(16)\n n = self.getNext(ds)\n\n for i in range(16):\n output = self.evaluate(n())\n self.assertEqual(i, output)\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(n())\n\n\nif __name__ == \"__main__\":\n test.main()\n",
"# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Contains the loss scaling optimizer class.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.distribute import distribution_strategy_context\nfrom tensorflow.python.framework import smart_cond\nfrom tensorflow.python.keras.mixed_precision.experimental import loss_scale as loss_scale_module\nfrom tensorflow.python.keras.optimizer_v2 import optimizer_v2\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.util.tf_export import keras_export\n\n\nclass _UnwrapPreventer(object):\n \"\"\"Wrapper that DistributionStrategy will not unwrap.\n\n Typically, DistributionStrategy will unwrap values when going from a cross-\n replica context to a replica context via `call_for_each_replica`. This class\n is a wrapper that DistributionStrategy will not unwrap, so it can be used to\n prevent it from unwrapping a value.\n\n TODO(reedwm): Find/implement a better way of preventing values from being\n unwrapped by DistributionStrategy\n \"\"\"\n\n def __init__(self, value):\n self.value = value\n\n\n@keras_export('keras.mixed_precision.experimental.LossScaleOptimizer')\nclass LossScaleOptimizer(optimizer_v2.OptimizerV2):\n \"\"\"An optimizer that applies loss scaling.\n\n Loss scaling is a process that multiplies the loss by a multiplier called the\n loss scale, and divides each gradient by the same multiplier. The pseudocode\n for this process is:\n\n ```\n loss = ...\n loss *= loss_scale\n grads = gradients(loss, vars)\n grads /= loss_scale\n ```\n\n Mathematically, loss scaling has no effect, but can help avoid numerical\n underflow in intermediate gradients when float16 tensors are used. By\n multiplying the loss, each intermediate gradient will have the same multiplier\n applied.\n\n The loss scale can either be a fixed constant, chosen by the user, or be\n dynamically determined. Dynamically determining the loss scale is convenient\n as a loss scale does not have to be explicitly chosen. However it reduces\n performance.\n\n This optimizer wraps another optimizer and applies loss scaling to it via a\n `LossScale`. Loss scaling is applied whenever gradients are\n computed, either through `minimize()` or `get_gradients()`.\n \"\"\"\n\n def __init__(self, opt, loss_scale):\n \"\"\"Initializes this loss scale optimizer.\n\n Args:\n opt: The Optimizer instance to wrap.\n loss_scale: The loss scale to scale the loss and gradients. This can\n either be an int/float to use a fixed loss scale, the string \"dynamic\"\n to use dynamic loss scaling, or an instance of a LossScale. The string\n \"dynamic\" equivalent to passing `DynamicLossScale()`, and passing an\n int/float is equivalent to passing a FixedLossScale with the given loss\n scale.\n \"\"\"\n if not isinstance(opt, optimizer_v2.OptimizerV2):\n raise ValueError('\"opt\" must be an instance of OptimizerV2, but got: %s'\n % opt)\n if hasattr(opt, 'clipnorm'):\n raise ValueError('LossScaleOptimizer does not support wrapping '\n 'optimizers with a clipnorm. Optimizer %s has clipnorm '\n '%s' % (opt, opt.clipnorm))\n\n if hasattr(opt, 'clipvalue'):\n raise ValueError('LossScaleOptimizer does not support wrapping '\n 'optimizers with a clipvalue. Optimizer %s has '\n 'clipvalue %s' % (opt, opt.clipvalue))\n\n self._optimizer = opt\n self._loss_scale = loss_scale_module.get(loss_scale)\n self._track_trackable(self._loss_scale, 'loss_scale')\n\n def _compute_gradients(self, loss, var_list, grad_loss=None):\n loss = self._scale_loss(loss)\n grads_and_vars = self._optimizer._compute_gradients(loss, var_list, # pylint: disable=protected-access\n grad_loss)\n grads = [g for g, _ in grads_and_vars]\n variables = [v for _, v in grads_and_vars]\n scaled_grads = self._scale_grads(grads)\n return list(zip(scaled_grads, variables))\n\n def get_gradients(self, loss, params):\n loss = self._scale_loss(loss)\n grads = self._optimizer.get_gradients(loss, params)\n return self._scale_grads(grads)\n\n def _scale_loss(self, loss):\n # The loss is callable for `_compute_gradients`, but not `get_gradients`.\n loss_scale = self._loss_scale()\n if callable(loss):\n return lambda: loss() * loss_scale\n else:\n return loss * loss_scale\n\n def _scale_grads(self, grads):\n loss_scale = self._loss_scale()\n loss_scale_reciprocal = 1 / loss_scale\n return [None if g is None else g * loss_scale_reciprocal for g in grads]\n\n def apply_gradients(self, grads_and_vars, name=None):\n if distribution_strategy_context.in_cross_replica_context():\n raise ValueError('apply_gradients() must be called in a replica context.')\n return distribution_strategy_context.get_replica_context().merge_call(\n self._apply_gradients_cross_replica, args=(grads_and_vars, name))\n\n def _apply_gradients_cross_replica(self, distribution, grads_and_vars, name):\n grads = [g for g, _ in grads_and_vars]\n loss_scale_update_op, should_apply_grads = self._loss_scale.update(grads)\n\n def apply_fn():\n # We do not want DistributionStrategy to unwrap any MirroredVariables in\n # grads_and_vars, because even in a replica context, the wrapped optimizer\n # expects mirrored variables. So we wrap grads_and_vars with an\n # _UnwrapPreventer, preventing DistributionStrategy from unwrapping the\n # MirroredVariables.\n wrapped_grads_and_vars = _UnwrapPreventer(grads_and_vars)\n return distribution.extended.call_for_each_replica(\n self._apply_gradients, args=(wrapped_grads_and_vars, name))\n\n # Note: We must call this cond() in a cross-replica context.\n # DistributionStrategy does not support having a cond in a replica context\n # with a branch that calls `merge_call`, and self._optimizer.apply_gradients\n # calls `merge_call`.\n maybe_apply_op = smart_cond.smart_cond(should_apply_grads,\n apply_fn,\n control_flow_ops.no_op)\n return control_flow_ops.group(maybe_apply_op, loss_scale_update_op)\n\n def _apply_gradients(self, wrapped_grads_and_vars, name):\n grads_and_vars = wrapped_grads_and_vars.value\n return self._optimizer.apply_gradients(grads_and_vars, name)\n\n @property\n def learning_rate(self):\n return self._optimizer.learning_rate\n\n @learning_rate.setter\n def learning_rate(self, lr):\n self._optimizer.learning_rate = lr\n\n def get_slot_names(self):\n \"\"\"A list of names for this optimizer's slots.\"\"\"\n return self._optimizer.get_slot_names()\n\n # TODO(reedwm): Maybe merge this class's functionality into OptimizerV2.\n\n # TODO(reedwm): Maybe throw an error if mixed precision is used without this\n # optimizer being used.\n\n # TODO(reedwm): Define __getattr__ to delegate all methods/attributes to\n # self._optimizer. This is tricky because the super class overrides\n # __getattribute__.\n\n # TODO(reedwm): Implement get_config and from_config. This will first require\n # implementing deserialization support for OptimizerV2.\n def get_config(self):\n raise NotImplementedError('get_config() is not yet implemented for '\n 'LossScaleOptimizers')\n\n @classmethod\n def from_config(cls, config, custom_objects=None):\n raise NotImplementedError('from_config() is not yet implemented for '\n 'LossScaleOptimizers')\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 tf.layers.core.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\n\nimport numpy as np\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.layers import core as core_layers\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\n\n\nclass DenseTest(test.TestCase):\n\n @test_util.run_in_graph_and_eager_modes\n def testDenseProperties(self):\n dense = core_layers.Dense(2, activation=nn_ops.relu, name='my_dense')\n self.assertEqual(dense.units, 2)\n self.assertEqual(dense.activation, nn_ops.relu)\n self.assertEqual(dense.kernel_regularizer, None)\n self.assertEqual(dense.bias_regularizer, None)\n self.assertEqual(dense.activity_regularizer, None)\n self.assertEqual(dense.use_bias, True)\n\n # Test auto-naming\n dense = core_layers.Dense(2, activation=nn_ops.relu)\n dense.apply(random_ops.random_uniform((5, 2)))\n self.assertEqual(dense.name, 'dense_1')\n dense = core_layers.Dense(2, activation=nn_ops.relu)\n dense.apply(random_ops.random_uniform((5, 2)))\n self.assertEqual(dense.name, 'dense_2')\n\n def testVariableInput(self):\n with self.cached_session():\n v = variable_scope.get_variable(\n 'X', initializer=init_ops.zeros_initializer(), shape=(1, 1))\n x = core_layers.Dense(1)(v)\n variables.global_variables_initializer().run()\n self.assertAllEqual(x.eval(), [[0.0]])\n\n @test_util.run_in_graph_and_eager_modes(assert_no_eager_garbage=True)\n def testCall(self):\n dense = core_layers.Dense(2, activation=nn_ops.relu, name='my_dense')\n inputs = random_ops.random_uniform((5, 4), seed=1)\n outputs = dense(inputs)\n self.assertListEqual([5, 2], outputs.get_shape().as_list())\n self.assertListEqual(dense.variables, [dense.kernel, dense.bias])\n self.assertListEqual(dense.trainable_variables,\n [dense.kernel, dense.bias])\n self.assertListEqual(dense.non_trainable_variables, [])\n if not context.executing_eagerly():\n self.assertEqual(\n len(ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES)), 2)\n self.assertEqual(dense.kernel.name, 'my_dense/kernel:0')\n self.assertEqual(dense.bias.name, 'my_dense/bias:0')\n\n @test_util.assert_no_new_pyobjects_executing_eagerly\n def testNoEagerLeak(self):\n # Tests that repeatedly constructing and building a Layer does not leak\n # Python objects.\n inputs = random_ops.random_uniform((5, 4), seed=1)\n core_layers.Dense(5)(inputs)\n core_layers.Dense(2, activation=nn_ops.relu, name='my_dense')(inputs)\n\n @test_util.run_in_graph_and_eager_modes\n def testCallTensorDot(self):\n dense = core_layers.Dense(2, activation=nn_ops.relu, name='my_dense')\n inputs = random_ops.random_uniform((5, 4, 3), seed=1)\n outputs = dense(inputs)\n self.assertListEqual([5, 4, 2], outputs.get_shape().as_list())\n\n @test_util.run_in_graph_and_eager_modes\n def testNoBias(self):\n dense = core_layers.Dense(2, use_bias=False, name='my_dense')\n inputs = random_ops.random_uniform((5, 2), seed=1)\n _ = dense(inputs)\n self.assertListEqual(dense.variables, [dense.kernel])\n self.assertListEqual(dense.trainable_variables, [dense.kernel])\n self.assertListEqual(dense.non_trainable_variables, [])\n if not context.executing_eagerly():\n self.assertEqual(\n len(ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES)), 1)\n self.assertEqual(dense.kernel.name, 'my_dense/kernel:0')\n self.assertEqual(dense.bias, None)\n\n @test_util.run_in_graph_and_eager_modes\n def testNonTrainable(self):\n dense = core_layers.Dense(2, trainable=False, name='my_dense')\n inputs = random_ops.random_uniform((5, 2), seed=1)\n _ = dense(inputs)\n self.assertListEqual(dense.variables, [dense.kernel, dense.bias])\n self.assertListEqual(dense.non_trainable_variables,\n [dense.kernel, dense.bias])\n self.assertListEqual(dense.trainable_variables, [])\n if not context.executing_eagerly():\n self.assertEqual(\n len(ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES)), 0)\n\n @test_util.run_in_graph_and_eager_modes\n def testOutputShape(self):\n dense = core_layers.Dense(7, activation=nn_ops.relu, name='my_dense')\n inputs = random_ops.random_uniform((5, 3), seed=1)\n outputs = dense.apply(inputs)\n self.assertEqual(outputs.get_shape().as_list(), [5, 7])\n\n inputs = random_ops.random_uniform((5, 2, 3), seed=1)\n outputs = dense(inputs)\n self.assertEqual(outputs.get_shape().as_list(), [5, 2, 7])\n\n inputs = random_ops.random_uniform((1, 2, 4, 3), seed=1)\n outputs = dense.apply(inputs)\n self.assertEqual(outputs.get_shape().as_list(), [1, 2, 4, 7])\n\n def testCallOnPlaceHolder(self):\n inputs = array_ops.placeholder(dtype=dtypes.float32)\n dense = core_layers.Dense(4, name='my_dense')\n with self.assertRaises(ValueError):\n dense(inputs)\n\n inputs = array_ops.placeholder(dtype=dtypes.float32, shape=[None, None])\n dense = core_layers.Dense(4, name='my_dense')\n with self.assertRaises(ValueError):\n dense(inputs)\n\n inputs = array_ops.placeholder(\n dtype=dtypes.float32, shape=[None, None, None])\n dense = core_layers.Dense(4, name='my_dense')\n with self.assertRaises(ValueError):\n dense(inputs)\n\n inputs = array_ops.placeholder(dtype=dtypes.float32, shape=[None, 3])\n dense = core_layers.Dense(4, name='my_dense')\n dense(inputs)\n\n inputs = array_ops.placeholder(dtype=dtypes.float32, shape=[None, None, 3])\n dense = core_layers.Dense(4, name='my_dense')\n dense(inputs)\n\n @test_util.run_in_graph_and_eager_modes\n def testActivation(self):\n dense = core_layers.Dense(2, activation=nn_ops.relu, name='dense1')\n inputs = random_ops.random_uniform((5, 3), seed=1)\n outputs = dense(inputs)\n if not context.executing_eagerly():\n self.assertEqual(outputs.op.name, 'dense1/Relu')\n\n dense = core_layers.Dense(2, name='dense2')\n inputs = random_ops.random_uniform((5, 3), seed=1)\n outputs = dense(inputs)\n if not context.executing_eagerly():\n self.assertEqual(outputs.op.name, 'dense2/BiasAdd')\n\n def testActivityRegularizer(self):\n regularizer = lambda x: math_ops.reduce_sum(x) * 1e-3\n dense = core_layers.Dense(\n 2, name='my_dense', activity_regularizer=regularizer)\n inputs = random_ops.random_uniform((5, 3), seed=1)\n _ = dense(inputs)\n loss_keys = ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES)\n self.assertEqual(len(loss_keys), 1)\n self.assertListEqual(dense.losses, loss_keys)\n\n def testKernelRegularizer(self):\n regularizer = lambda x: math_ops.reduce_sum(x) * 1e-3\n dense = core_layers.Dense(\n 2, name='my_dense', kernel_regularizer=regularizer)\n inputs = random_ops.random_uniform((5, 3), seed=1)\n _ = dense(inputs)\n loss_keys = ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES)\n self.assertEqual(len(loss_keys), 1)\n self.evaluate([v.initializer for v in dense.variables])\n self.assertAllEqual(self.evaluate(dense.losses), self.evaluate(loss_keys))\n\n def testKernelRegularizerWithReuse(self):\n regularizer = lambda x: math_ops.reduce_sum(x) * 1e-3\n inputs = random_ops.random_uniform((5, 3), seed=1)\n _ = core_layers.dense(\n inputs, 2, name='my_dense', kernel_regularizer=regularizer)\n self.assertEqual(\n len(ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES)), 1)\n _ = core_layers.dense(\n inputs, 2, name='my_dense', kernel_regularizer=regularizer, reuse=True)\n self.assertEqual(\n len(ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES)), 1)\n\n def testBiasRegularizer(self):\n regularizer = lambda x: math_ops.reduce_sum(x) * 1e-3\n dense = core_layers.Dense(2, name='my_dense', bias_regularizer=regularizer)\n inputs = random_ops.random_uniform((5, 3), seed=1)\n _ = dense(inputs)\n loss_keys = ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES)\n self.assertEqual(len(loss_keys), 1)\n self.evaluate([v.initializer for v in dense.variables])\n self.assertAllEqual(self.evaluate(dense.losses), self.evaluate(loss_keys))\n\n def testFunctionalDense(self):\n with self.cached_session():\n inputs = random_ops.random_uniform((5, 3), seed=1)\n outputs = core_layers.dense(\n inputs, 2, activation=nn_ops.relu, name='my_dense')\n self.assertEqual(\n len(ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES)), 2)\n self.assertEqual(outputs.op.name, 'my_dense/Relu')\n\n def testFunctionalDenseTwice(self):\n inputs = random_ops.random_uniform((5, 3), seed=1)\n core_layers.dense(inputs, 2)\n vars1 = _get_variable_dict_from_varstore().values()\n core_layers.dense(inputs, 2)\n vars2 = _get_variable_dict_from_varstore().values()\n self.assertEqual(len(vars1), 2)\n self.assertEqual(len(vars2), 4)\n\n # TODO(alive): get this to work in eager mode.\n def testFunctionalDenseTwiceReuse(self):\n with self.cached_session():\n inputs = random_ops.random_uniform((5, 3), seed=1)\n core_layers.dense(inputs, 2, name='my_dense')\n vars1 = variables.trainable_variables()\n core_layers.dense(inputs, 2, name='my_dense', reuse=True)\n vars2 = variables.trainable_variables()\n self.assertEqual(vars1, vars2)\n\n # TODO(alive): get this to work in eager mode.\n def testFunctionalDenseTwiceReuseFromScope(self):\n with self.cached_session():\n with variable_scope.variable_scope('scope'):\n inputs = random_ops.random_uniform((5, 3), seed=1)\n core_layers.dense(inputs, 2, name='my_dense')\n vars1 = variables.trainable_variables()\n with variable_scope.variable_scope('scope', reuse=True):\n core_layers.dense(inputs, 2, name='my_dense')\n vars2 = variables.trainable_variables()\n self.assertEqual(vars1, vars2)\n\n def testFunctionalDenseInitializerFromScope(self):\n with variable_scope.variable_scope(\n 'scope',\n initializer=init_ops.ones_initializer()), self.cached_session():\n inputs = random_ops.random_uniform((5, 3), seed=1)\n core_layers.dense(inputs, 2)\n variables.global_variables_initializer().run()\n weights = _get_variable_dict_from_varstore()\n self.assertEqual(len(weights), 2)\n # Check that the matrix weights got initialized to ones (from scope).\n self.assertAllClose(weights['scope/dense/kernel'].read_value().eval(),\n np.ones((3, 2)))\n # Check that the bias still got initialized to zeros.\n self.assertAllClose(weights['scope/dense/bias'].read_value().eval(),\n np.zeros((2)))\n\n def testEagerExecution(self):\n with context.eager_mode():\n container = variable_scope.EagerVariableStore()\n x = constant_op.constant([[2.0]])\n with container.as_default():\n y = core_layers.dense(\n x, 1, name='my_dense',\n kernel_initializer=init_ops.ones_initializer())\n self.assertAllEqual(y, [[2.0]])\n self.assertEqual(len(container.variables()), 2)\n # Recreate the layer to test reuse.\n with container.as_default():\n core_layers.dense(\n x, 1, name='my_dense',\n kernel_initializer=init_ops.ones_initializer())\n self.assertEqual(len(container.variables()), 2)\n\n def testFunctionalDenseWithCustomGetter(self):\n called = [0]\n\n def custom_getter(getter, *args, **kwargs):\n called[0] += 1\n return getter(*args, **kwargs)\n\n with variable_scope.variable_scope('test', custom_getter=custom_getter):\n inputs = random_ops.random_uniform((5, 3), seed=1)\n core_layers.dense(inputs, 2)\n self.assertEqual(called[0], 2)\n\n def testFunctionalDenseInScope(self):\n with self.cached_session():\n with variable_scope.variable_scope('test'):\n inputs = random_ops.random_uniform((5, 3), seed=1)\n core_layers.dense(inputs, 2, name='my_dense')\n var_dict = _get_variable_dict_from_varstore()\n var_key = 'test/my_dense/kernel'\n self.assertEqual(var_dict[var_key].name, '%s:0' % var_key)\n with variable_scope.variable_scope('test1') as scope:\n inputs = random_ops.random_uniform((5, 3), seed=1)\n core_layers.dense(inputs, 2, name=scope)\n var_dict = _get_variable_dict_from_varstore()\n var_key = 'test1/kernel'\n self.assertEqual(var_dict[var_key].name, '%s:0' % var_key)\n with variable_scope.variable_scope('test2'):\n inputs = random_ops.random_uniform((5, 3), seed=1)\n core_layers.dense(inputs, 2)\n var_dict = _get_variable_dict_from_varstore()\n var_key = 'test2/dense/kernel'\n self.assertEqual(var_dict[var_key].name, '%s:0' % var_key)\n\n @test_util.run_in_graph_and_eager_modes\n def testComputeOutputShape(self):\n dense = core_layers.Dense(2, activation=nn_ops.relu, name='dense1')\n ts = tensor_shape.TensorShape\n # pylint: disable=protected-access\n with self.assertRaises(ValueError):\n dense.compute_output_shape(ts(None))\n with self.assertRaises(ValueError):\n dense.compute_output_shape(ts([]))\n with self.assertRaises(ValueError):\n dense.compute_output_shape(ts([1]))\n self.assertEqual(\n [None, 2],\n dense.compute_output_shape((None, 3)).as_list())\n self.assertEqual(\n [None, 2],\n dense.compute_output_shape(ts([None, 3])).as_list())\n self.assertEqual(\n [None, 4, 2],\n dense.compute_output_shape(ts([None, 4, 3])).as_list())\n # pylint: enable=protected-access\n\n @test_util.run_in_graph_and_eager_modes\n def testConstraints(self):\n k_constraint = lambda x: x / math_ops.reduce_sum(x)\n b_constraint = lambda x: x / math_ops.reduce_max(x)\n dense = core_layers.Dense(2,\n kernel_constraint=k_constraint,\n bias_constraint=b_constraint)\n inputs = random_ops.random_uniform((5, 3), seed=1)\n dense(inputs)\n self.assertEqual(dense.kernel_constraint, k_constraint)\n self.assertEqual(dense.bias_constraint, b_constraint)\n\n\ndef _get_variable_dict_from_varstore():\n var_dict = variable_scope._get_default_variable_store()._vars # pylint: disable=protected-access\n sorted_var_dict = collections.OrderedDict(\n sorted(var_dict.items(), key=lambda t: t[0]))\n return sorted_var_dict\n\n\nclass DropoutTest(test.TestCase):\n\n @test_util.run_in_graph_and_eager_modes\n def testDropoutProperties(self):\n dp = core_layers.Dropout(0.5, name='dropout')\n self.assertEqual(dp.rate, 0.5)\n self.assertEqual(dp.noise_shape, None)\n dp.apply(array_ops.ones(()))\n self.assertEqual(dp.name, 'dropout')\n\n @test_util.run_in_graph_and_eager_modes\n def testBooleanLearningPhase(self):\n dp = core_layers.Dropout(0.5)\n inputs = array_ops.ones((5, 3))\n dropped = dp.apply(inputs, training=True)\n if not context.executing_eagerly():\n self.evaluate(variables.global_variables_initializer())\n np_output = self.evaluate(dropped)\n self.assertAlmostEqual(0., np_output.min())\n dropped = dp.apply(inputs, training=False)\n np_output = self.evaluate(dropped)\n self.assertAllClose(np.ones((5, 3)), np_output)\n\n def testDynamicLearningPhase(self):\n with self.cached_session() as sess:\n dp = core_layers.Dropout(0.5, seed=1)\n inputs = array_ops.ones((5, 5))\n training = array_ops.placeholder(dtype='bool')\n dropped = dp.apply(inputs, training=training)\n self.evaluate(variables.global_variables_initializer())\n np_output = sess.run(dropped, feed_dict={training: True})\n self.assertAlmostEqual(0., np_output.min())\n np_output = sess.run(dropped, feed_dict={training: False})\n self.assertAllClose(np.ones((5, 5)), np_output)\n\n @test_util.run_in_graph_and_eager_modes\n def testDynamicNoiseShape(self):\n inputs = array_ops.ones((5, 3, 2))\n noise_shape = [None, 1, None]\n dp = core_layers.Dropout(0.5, noise_shape=noise_shape, seed=1)\n dropped = dp.apply(inputs, training=True)\n self.evaluate(variables.global_variables_initializer())\n np_output = self.evaluate(dropped)\n self.assertAlmostEqual(0., np_output.min())\n self.assertAllClose(np_output[:, 0, :], np_output[:, 1, :])\n\n def testCustomNoiseShape(self):\n inputs = array_ops.ones((5, 3, 2))\n noise_shape = [5, 1, 2]\n dp = core_layers.Dropout(0.5, noise_shape=noise_shape, seed=1)\n dropped = dp.apply(inputs, training=True)\n self.evaluate(variables.global_variables_initializer())\n np_output = self.evaluate(dropped)\n self.assertAlmostEqual(0., np_output.min())\n self.assertAllClose(np_output[:, 0, :], np_output[:, 1, :])\n\n def testFunctionalDropout(self):\n with self.cached_session():\n inputs = array_ops.ones((5, 5))\n dropped = core_layers.dropout(inputs, 0.5, training=True, seed=1)\n variables.global_variables_initializer().run()\n np_output = self.evaluate(dropped)\n self.assertAlmostEqual(0., np_output.min())\n dropped = core_layers.dropout(inputs, 0.5, training=False, seed=1)\n np_output = self.evaluate(dropped)\n self.assertAllClose(np.ones((5, 5)), np_output)\n\n def testDynamicRate(self):\n with self.cached_session() as sess:\n rate = array_ops.placeholder(dtype='float32', name='rate')\n dp = core_layers.Dropout(rate, name='dropout')\n inputs = array_ops.ones((5, 5))\n dropped = dp.apply(inputs, training=True)\n sess.run(variables.global_variables_initializer())\n np_output = sess.run(dropped, feed_dict={rate: 0.5})\n self.assertAlmostEqual(0., np_output.min())\n np_output = sess.run(dropped, feed_dict={rate: 0.0})\n self.assertAllClose(np.ones((5, 5)), np_output)\n\n\nclass FlattenTest(test.TestCase):\n\n def testCreateFlatten(self):\n with self.cached_session() as sess:\n x = array_ops.placeholder(shape=(None, 2, 3), dtype='float32')\n y = core_layers.Flatten()(x)\n np_output = sess.run(y, feed_dict={x: np.zeros((3, 2, 3))})\n self.assertEqual(list(np_output.shape), [3, 6])\n self.assertEqual(y.get_shape().as_list(), [None, 6])\n\n x = array_ops.placeholder(shape=(1, 2, 3, 2), dtype='float32')\n y = core_layers.Flatten()(x)\n np_output = sess.run(y, feed_dict={x: np.zeros((1, 2, 3, 2))})\n self.assertEqual(list(np_output.shape), [1, 12])\n self.assertEqual(y.get_shape().as_list(), [1, 12])\n\n def testComputeShape(self):\n shape = core_layers.Flatten().compute_output_shape((1, 2, 3, 2))\n self.assertEqual(shape.as_list(), [1, 12])\n\n shape = core_layers.Flatten().compute_output_shape((None, 3, 2))\n self.assertEqual(shape.as_list(), [None, 6])\n\n shape = core_layers.Flatten().compute_output_shape((None, 3, None))\n self.assertEqual(shape.as_list(), [None, None])\n\n def testDataFormat5d(self):\n np_input_channels_last = np.arange(\n 120, dtype='float32').reshape([1, 5, 4, 3, 2])\n\n with self.test_session() as sess:\n x = array_ops.placeholder(shape=(1, 5, 4, 3, 2), dtype='float32')\n y = core_layers.Flatten(data_format='channels_last')(x)\n np_output_cl = sess.run(y, feed_dict={x: np_input_channels_last})\n\n x = array_ops.placeholder(shape=(1, 2, 5, 4, 3), dtype='float32')\n y = core_layers.Flatten(data_format='channels_first')(x)\n np_input_channels_first = np.transpose(np_input_channels_last,\n [0, 4, 1, 2, 3])\n np_output_cf = sess.run(y, feed_dict={x: np_input_channels_first})\n\n self.assertAllEqual(np_output_cl, np_output_cf)\n\n def testDataFormat4d(self):\n np_input_channels_last = np.arange(\n 24, dtype='float32').reshape([1, 4, 3, 2])\n\n with self.test_session() as sess:\n x = array_ops.placeholder(shape=(1, 4, 3, 2), dtype='float32')\n y = core_layers.Flatten(data_format='channels_last')(x)\n np_output_cl = sess.run(y, feed_dict={x: np_input_channels_last})\n\n x = array_ops.placeholder(shape=(1, 2, 4, 3), dtype='float32')\n y = core_layers.Flatten(data_format='channels_first')(x)\n np_input_channels_first = np.transpose(np_input_channels_last,\n [0, 3, 1, 2])\n np_output_cf = sess.run(y, feed_dict={x: np_input_channels_first})\n\n self.assertAllEqual(np_output_cl, np_output_cf)\n\n def testFunctionalFlatten(self):\n x = array_ops.placeholder(shape=(None, 2, 3), dtype='float32')\n y = core_layers.flatten(x, name='flatten')\n self.assertEqual(y.get_shape().as_list(), [None, 6])\n\n def testFlattenValueError(self):\n x = array_ops.placeholder(shape=(None,), dtype='float32')\n with self.assertRaises(ValueError):\n core_layers.Flatten()(x)\n\n def testFlattenUnknownAxes(self):\n with self.cached_session() as sess:\n x = array_ops.placeholder(shape=(5, None, None), dtype='float32')\n y = core_layers.Flatten()(x)\n np_output = sess.run(y, feed_dict={x: np.zeros((5, 2, 3))})\n self.assertEqual(list(np_output.shape), [5, 6])\n self.assertEqual(y.get_shape().as_list(), [5, None])\n\n x = array_ops.placeholder(shape=(5, None, 2), dtype='float32')\n y = core_layers.Flatten()(x)\n np_output = sess.run(y, feed_dict={x: np.zeros((5, 3, 2))})\n self.assertEqual(list(np_output.shape), [5, 6])\n self.assertEqual(y.get_shape().as_list(), [5, None])\n\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\n\"\"\"Functional test for learning rate decay.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import test_util\n# Import resource_variable_ops for the variables-to-tensor implicit conversion.\nfrom tensorflow.python.ops import resource_variable_ops # pylint: disable=unused-import\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import googletest\nfrom tensorflow.python.training import learning_rate_decay\n\n\nclass LRDecayTest(test_util.TensorFlowTestCase):\n\n @test_util.run_in_graph_and_eager_modes\n def testContinuous(self):\n self.evaluate(variables.global_variables_initializer())\n step = 5\n decayed_lr = learning_rate_decay.exponential_decay(0.05, step, 10, 0.96)\n expected = .05 * 0.96**(5.0 / 10.0)\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n @test_util.run_in_graph_and_eager_modes\n def testStaircase(self):\n if context.executing_eagerly():\n step = resource_variable_ops.ResourceVariable(0)\n self.evaluate(variables.global_variables_initializer())\n decayed_lr = learning_rate_decay.exponential_decay(\n .1, step, 3, 0.96, staircase=True)\n\n # No change to learning rate due to staircase\n expected = .1\n self.evaluate(step.assign(1))\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n expected = .1\n self.evaluate(step.assign(2))\n self.assertAllClose(self.evaluate(decayed_lr), .1, 1e-6)\n\n # Decayed learning rate\n expected = .1 * 0.96 ** (100 // 3)\n self.evaluate(step.assign(100))\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n def testVariables(self):\n with self.cached_session():\n step = variables.VariableV1(1)\n assign_1 = step.assign(1)\n assign_2 = step.assign(2)\n assign_100 = step.assign(100)\n decayed_lr = learning_rate_decay.exponential_decay(.1, step, 3, 0.96,\n staircase=True)\n variables.global_variables_initializer().run()\n # No change to learning rate\n assign_1.op.run()\n self.assertAllClose(decayed_lr.eval(), .1, 1e-6)\n assign_2.op.run()\n self.assertAllClose(decayed_lr.eval(), .1, 1e-6)\n # Decayed learning rate\n assign_100.op.run()\n expected = .1 * 0.96 ** (100 // 3)\n self.assertAllClose(decayed_lr.eval(), expected, 1e-6)\n\n @test_util.run_in_graph_and_eager_modes\n def testPiecewiseConstant(self):\n x = resource_variable_ops.ResourceVariable(-999)\n decayed_lr = learning_rate_decay.piecewise_constant(\n x, [100, 110, 120], [1.0, 0.1, 0.01, 0.001])\n\n self.evaluate(variables.global_variables_initializer())\n\n self.assertAllClose(self.evaluate(decayed_lr), 1.0, 1e-6)\n self.evaluate(x.assign(100))\n self.assertAllClose(self.evaluate(decayed_lr), 1.0, 1e-6)\n self.evaluate(x.assign(105))\n self.assertAllClose(self.evaluate(decayed_lr), 0.1, 1e-6)\n self.evaluate(x.assign(110))\n self.assertAllClose(self.evaluate(decayed_lr), 0.1, 1e-6)\n self.evaluate(x.assign(120))\n self.assertAllClose(self.evaluate(decayed_lr), 0.01, 1e-6)\n self.evaluate(x.assign(999))\n self.assertAllClose(self.evaluate(decayed_lr), 0.001, 1e-6)\n\n @test_util.run_in_graph_and_eager_modes\n def testPiecewiseConstantEdgeCases(self):\n x_int = resource_variable_ops.ResourceVariable(\n 0, dtype=variables.dtypes.int32)\n boundaries, values = [-1.0, 1.0], [1, 2, 3]\n with self.assertRaises(ValueError):\n decayed_lr = learning_rate_decay.piecewise_constant(\n x_int, boundaries, values)\n if context.executing_eagerly():\n decayed_lr()\n\n x = resource_variable_ops.ResourceVariable(0.0)\n boundaries, values = [-1.0, 1.0], [1.0, 2, 3]\n with self.assertRaises(ValueError):\n decayed_lr = learning_rate_decay.piecewise_constant(\n x, boundaries, values)\n if context.executing_eagerly():\n decayed_lr()\n\n # Test that ref types are valid.\n if not context.executing_eagerly():\n x = variables.VariableV1(0.0)\n x_ref = x.op.outputs[0] # float32_ref tensor should be accepted\n boundaries, values = [1.0, 2.0], [1, 2, 3]\n learning_rate_decay.piecewise_constant(x_ref, boundaries, values)\n\n # Test casting boundaries from int32 to int64.\n x_int64 = resource_variable_ops.ResourceVariable(\n 0, dtype=variables.dtypes.int64)\n boundaries, values = [1, 2, 3], [0.4, 0.5, 0.6, 0.7]\n decayed_lr = learning_rate_decay.piecewise_constant(\n x_int64, boundaries, values)\n\n self.evaluate(variables.global_variables_initializer())\n self.assertAllClose(self.evaluate(decayed_lr), 0.4, 1e-6)\n self.evaluate(x_int64.assign(1))\n self.assertAllClose(self.evaluate(decayed_lr), 0.4, 1e-6)\n self.evaluate(x_int64.assign(2))\n self.assertAllClose(self.evaluate(decayed_lr), 0.5, 1e-6)\n self.evaluate(x_int64.assign(3))\n self.assertAllClose(self.evaluate(decayed_lr), 0.6, 1e-6)\n self.evaluate(x_int64.assign(4))\n self.assertAllClose(self.evaluate(decayed_lr), 0.7, 1e-6)\n\n\nclass LinearDecayTest(test_util.TensorFlowTestCase):\n\n @test_util.run_in_graph_and_eager_modes\n def testHalfWay(self):\n step = 5\n lr = 0.05\n end_lr = 0.0\n decayed_lr = learning_rate_decay.polynomial_decay(lr, step, 10, end_lr)\n expected = lr * 0.5\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n @test_util.run_in_graph_and_eager_modes\n def testEnd(self):\n step = 10\n lr = 0.05\n end_lr = 0.001\n decayed_lr = learning_rate_decay.polynomial_decay(lr, step, 10, end_lr)\n expected = end_lr\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n @test_util.run_in_graph_and_eager_modes\n def testHalfWayWithEnd(self):\n step = 5\n lr = 0.05\n end_lr = 0.001\n decayed_lr = learning_rate_decay.polynomial_decay(lr, step, 10, end_lr)\n expected = (lr + end_lr) * 0.5\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n @test_util.run_in_graph_and_eager_modes\n def testBeyondEnd(self):\n step = 15\n lr = 0.05\n end_lr = 0.001\n decayed_lr = learning_rate_decay.polynomial_decay(lr, step, 10, end_lr)\n expected = end_lr\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n @test_util.run_in_graph_and_eager_modes\n def testBeyondEndWithCycle(self):\n step = 15\n lr = 0.05\n end_lr = 0.001\n decayed_lr = learning_rate_decay.polynomial_decay(\n lr, step, 10, end_lr, cycle=True)\n expected = (lr - end_lr) * 0.25 + end_lr\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n\nclass SqrtDecayTest(test_util.TensorFlowTestCase):\n\n @test_util.run_in_graph_and_eager_modes\n def testHalfWay(self):\n step = 5\n lr = 0.05\n end_lr = 0.0\n power = 0.5\n decayed_lr = learning_rate_decay.polynomial_decay(\n lr, step, 10, end_lr, power=power)\n expected = lr * 0.5**power\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n @test_util.run_in_graph_and_eager_modes\n def testEnd(self):\n step = 10\n lr = 0.05\n end_lr = 0.001\n power = 0.5\n decayed_lr = learning_rate_decay.polynomial_decay(\n lr, step, 10, end_lr, power=power)\n expected = end_lr\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n @test_util.run_in_graph_and_eager_modes\n def testHalfWayWithEnd(self):\n step = 5\n lr = 0.05\n end_lr = 0.001\n power = 0.5\n decayed_lr = learning_rate_decay.polynomial_decay(\n lr, step, 10, end_lr, power=power)\n expected = (lr - end_lr) * 0.5**power + end_lr\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n @test_util.run_in_graph_and_eager_modes\n def testBeyondEnd(self):\n step = 15\n lr = 0.05\n end_lr = 0.001\n power = 0.5\n decayed_lr = learning_rate_decay.polynomial_decay(\n lr, step, 10, end_lr, power=power)\n expected = end_lr\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n @test_util.run_in_graph_and_eager_modes\n def testBeyondEndWithCycle(self):\n step = 15\n lr = 0.05\n end_lr = 0.001\n power = 0.5\n decayed_lr = learning_rate_decay.polynomial_decay(\n lr, step, 10, end_lr, power=power, cycle=True)\n expected = (lr - end_lr) * 0.25**power + end_lr\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n\nclass PolynomialDecayTest(test_util.TensorFlowTestCase):\n\n @test_util.run_in_graph_and_eager_modes\n def testBeginWithCycle(self):\n lr = 0.001\n decay_steps = 10\n step = 0\n decayed_lr = learning_rate_decay.polynomial_decay(\n lr, step, decay_steps, cycle=True)\n expected = lr\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n\nclass ExponentialDecayTest(test_util.TensorFlowTestCase):\n\n @test_util.run_in_graph_and_eager_modes\n def testDecay(self):\n initial_lr = 0.1\n k = 10\n decay_rate = 0.96\n step = resource_variable_ops.ResourceVariable(0)\n decayed_lr = learning_rate_decay.natural_exp_decay(initial_lr, step, k,\n decay_rate)\n\n self.evaluate(variables.global_variables_initializer())\n for i in range(k + 1):\n expected = initial_lr * math.exp(-i / k * decay_rate)\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n self.evaluate(step.assign_add(1))\n\n @test_util.run_in_graph_and_eager_modes\n def testStaircase(self):\n initial_lr = 0.1\n k = 10\n decay_rate = 0.96\n step = resource_variable_ops.ResourceVariable(0)\n decayed_lr = learning_rate_decay.natural_exp_decay(\n initial_lr, step, k, decay_rate, staircase=True)\n\n self.evaluate(variables.global_variables_initializer())\n for i in range(k + 1):\n expected = initial_lr * math.exp(-decay_rate * (i // k))\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n self.evaluate(step.assign_add(1))\n\n\nclass InverseDecayTest(test_util.TensorFlowTestCase):\n\n @test_util.run_in_graph_and_eager_modes\n def testDecay(self):\n initial_lr = 0.1\n k = 10\n decay_rate = 0.96\n step = resource_variable_ops.ResourceVariable(0)\n decayed_lr = learning_rate_decay.inverse_time_decay(initial_lr, step, k,\n decay_rate)\n\n self.evaluate(variables.global_variables_initializer())\n for i in range(k + 1):\n expected = initial_lr / (1 + i / k * decay_rate)\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n self.evaluate(step.assign_add(1))\n\n @test_util.run_in_graph_and_eager_modes\n def testStaircase(self):\n initial_lr = 0.1\n k = 10\n decay_rate = 0.96\n step = resource_variable_ops.ResourceVariable(0)\n decayed_lr = learning_rate_decay.inverse_time_decay(\n initial_lr, step, k, decay_rate, staircase=True)\n\n self.evaluate(variables.global_variables_initializer())\n for i in range(k + 1):\n expected = initial_lr / (1 + decay_rate * (i // k))\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n self.evaluate(step.assign_add(1))\n\n\nclass CosineDecayTest(test_util.TensorFlowTestCase):\n\n def np_cosine_decay(self, step, decay_steps, alpha=0.0):\n step = min(step, decay_steps)\n completed_fraction = step / decay_steps\n decay = 0.5 * (1.0 + math.cos(math.pi * completed_fraction))\n return (1.0 - alpha) * decay + alpha\n\n @test_util.run_in_graph_and_eager_modes\n def testDecay(self):\n num_training_steps = 1000\n initial_lr = 1.0\n for step in range(0, 1500, 250):\n decayed_lr = learning_rate_decay.cosine_decay(initial_lr, step,\n num_training_steps)\n expected = self.np_cosine_decay(step, num_training_steps)\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n @test_util.run_in_graph_and_eager_modes\n def testAlpha(self):\n num_training_steps = 1000\n initial_lr = 1.0\n alpha = 0.1\n for step in range(0, 1500, 250):\n decayed_lr = learning_rate_decay.cosine_decay(initial_lr, step,\n num_training_steps, alpha)\n expected = self.np_cosine_decay(step, num_training_steps, alpha)\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n\nclass CosineDecayRestartsTest(test_util.TensorFlowTestCase):\n\n def np_cosine_decay_restarts(self, step, decay_steps, t_mul=2.0, m_mul=1.0,\n alpha=0.0):\n fac = 1.0\n while step >= decay_steps:\n step -= decay_steps\n decay_steps *= t_mul\n fac *= m_mul\n\n completed_fraction = step / decay_steps\n decay = fac * 0.5 * (1.0 + math.cos(math.pi * completed_fraction))\n return (1.0 - alpha) * decay + alpha\n\n @test_util.run_in_graph_and_eager_modes\n def testDecay(self):\n num_training_steps = 1000\n initial_lr = 1.0\n for step in range(0, 1500, 250):\n decayed_lr = learning_rate_decay.cosine_decay_restarts(\n initial_lr, step, num_training_steps)\n expected = self.np_cosine_decay_restarts(step, num_training_steps)\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n @test_util.run_in_graph_and_eager_modes\n def testAlpha(self):\n num_training_steps = 1000\n initial_lr = 1.0\n alpha = 0.1\n for step in range(0, 1500, 250):\n decayed_lr = learning_rate_decay.cosine_decay_restarts(\n initial_lr, step, num_training_steps, alpha=alpha)\n expected = self.np_cosine_decay_restarts(\n step, num_training_steps, alpha=alpha)\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n @test_util.run_in_graph_and_eager_modes\n def testMMul(self):\n num_training_steps = 1000\n initial_lr = 1.0\n m_mul = 0.9\n for step in range(0, 1500, 250):\n decayed_lr = learning_rate_decay.cosine_decay_restarts(\n initial_lr, step, num_training_steps, m_mul=m_mul)\n expected = self.np_cosine_decay_restarts(\n step, num_training_steps, m_mul=m_mul)\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n @test_util.run_in_graph_and_eager_modes\n def testTMul(self):\n num_training_steps = 1000\n initial_lr = 1.0\n t_mul = 1.0\n for step in range(0, 1500, 250):\n decayed_lr = learning_rate_decay.cosine_decay_restarts(\n initial_lr, step, num_training_steps, t_mul=t_mul)\n expected = self.np_cosine_decay_restarts(\n step, num_training_steps, t_mul=t_mul)\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n\nclass LinearCosineDecayTest(test_util.TensorFlowTestCase):\n\n def np_linear_cosine_decay(self,\n step,\n decay_steps,\n alpha=0.0,\n beta=0.001,\n num_periods=0.5):\n step = min(step, decay_steps)\n linear_decayed = float(decay_steps - step) / decay_steps\n fraction = 2.0 * num_periods * step / float(decay_steps)\n cosine_decayed = 0.5 * (1.0 + math.cos(math.pi * fraction))\n return (alpha + linear_decayed) * cosine_decayed + beta\n\n @test_util.run_in_graph_and_eager_modes\n def testDefaultDecay(self):\n num_training_steps = 1000\n initial_lr = 1.0\n for step in range(0, 1500, 250):\n decayed_lr = learning_rate_decay.linear_cosine_decay(\n initial_lr, step, num_training_steps)\n expected = self.np_linear_cosine_decay(step, num_training_steps)\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n @test_util.run_in_graph_and_eager_modes\n def testNonDefaultDecay(self):\n num_training_steps = 1000\n initial_lr = 1.0\n for step in range(0, 1500, 250):\n decayed_lr = learning_rate_decay.linear_cosine_decay(\n initial_lr,\n step,\n num_training_steps,\n alpha=0.1,\n beta=1e-4,\n num_periods=5)\n expected = self.np_linear_cosine_decay(\n step, num_training_steps, alpha=0.1, beta=1e-4, num_periods=5)\n self.assertAllClose(self.evaluate(decayed_lr), expected, 1e-6)\n\n\nclass NoisyLinearCosineDecayTest(test_util.TensorFlowTestCase):\n\n @test_util.run_in_graph_and_eager_modes\n def testDefaultNoisyLinearCosine(self):\n num_training_steps = 1000\n initial_lr = 1.0\n for step in range(0, 1500, 250):\n # No numerical check because of noise\n decayed_lr = learning_rate_decay.noisy_linear_cosine_decay(\n initial_lr, step, num_training_steps)\n # Cannot be deterministically tested\n self.evaluate(decayed_lr)\n\n @test_util.run_in_graph_and_eager_modes\n def testNonDefaultNoisyLinearCosine(self):\n num_training_steps = 1000\n initial_lr = 1.0\n for step in range(0, 1500, 250):\n # No numerical check because of noise\n decayed_lr = learning_rate_decay.noisy_linear_cosine_decay(\n initial_lr,\n step,\n num_training_steps,\n initial_variance=0.5,\n variance_decay=0.1,\n alpha=0.1,\n beta=1e-4,\n num_periods=5)\n # Cannot be deterministically tested\n self.evaluate(decayed_lr)\n\n\nif __name__ == \"__main__\":\n googletest.main()\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\"\"\"Tests for Keras optimizers.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport gc\nimport weakref\n\nimport numpy as np\n\nfrom tensorflow.python import keras\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.keras import testing_utils\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.training.adam import AdamOptimizer\n\n\ndef _get_model(input_dim, num_hidden, output_dim):\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(num_hidden,\n activation='relu',\n input_shape=(input_dim,)))\n model.add(keras.layers.Dense(output_dim, activation='softmax'))\n return model\n\n\nclass KerasOptimizersTest(test.TestCase):\n\n def _test_optimizer(self, optimizer, target=0.75):\n np.random.seed(1337)\n (x_train, y_train), _ = testing_utils.get_test_data(\n train_samples=1000, test_samples=200, input_shape=(10,), num_classes=2)\n y_train = keras.utils.to_categorical(y_train)\n model = _get_model(x_train.shape[1], 20, y_train.shape[1])\n model.compile(\n loss='categorical_crossentropy', optimizer=optimizer, metrics=['acc'])\n np.testing.assert_equal(\n keras.backend.get_value(model.optimizer.iterations), 0)\n history = model.fit(x_train, y_train, epochs=2, batch_size=16, verbose=0)\n np.testing.assert_equal(\n keras.backend.get_value(model.optimizer.iterations),\n 126) # 63 steps per epoch\n self.assertGreaterEqual(history.history['acc'][-1], target)\n config = keras.optimizers.serialize(optimizer)\n optim = keras.optimizers.deserialize(config)\n new_config = keras.optimizers.serialize(optim)\n new_config['class_name'] = new_config['class_name'].lower()\n new_config['config'].pop('name', None)\n if 'amsgrad' not in config['config']:\n new_config['config'].pop('amsgrad', None)\n if 'decay' in new_config['config'] and 'schedule_decay' in config['config']:\n new_config['config']['schedule_decay'] = new_config['config'].pop('decay')\n if 'momentum' not in config['config']:\n new_config['config'].pop('momentum', None)\n if 'centered' not in config['config']:\n new_config['config'].pop('centered', None)\n self.assertDictEqual(config, new_config)\n\n # Test constraints.\n model = keras.models.Sequential()\n dense = keras.layers.Dense(\n 10,\n input_shape=(x_train.shape[1],),\n kernel_constraint=lambda x: 0. * x + 1.,\n bias_constraint=lambda x: 0. * x + 2.,\n activation='relu')\n model.add(dense)\n model.add(keras.layers.Dense(y_train.shape[1], activation='softmax'))\n model.compile(\n loss='categorical_crossentropy',\n optimizer=optimizer,\n metrics=['accuracy'])\n np.testing.assert_equal(\n keras.backend.get_value(model.optimizer.iterations),\n 126) # Using same optimizer from before\n model.train_on_batch(x_train[:10], y_train[:10])\n np.testing.assert_equal(\n keras.backend.get_value(model.optimizer.iterations), 127)\n kernel, bias = dense.get_weights()\n np.testing.assert_allclose(kernel, 1., atol=1e-3)\n np.testing.assert_allclose(bias, 2., atol=1e-3)\n\n def test_sgd(self):\n with self.cached_session():\n self._test_optimizer(keras.optimizers.SGD())\n\n def test_momentum(self):\n with self.cached_session():\n self._test_optimizer(\n keras.optimizers.SGD(lr=0.01, momentum=0.9, nesterov=True))\n\n def test_rmsprop(self):\n with self.cached_session():\n self._test_optimizer(keras.optimizers.RMSprop())\n self._test_optimizer(keras.optimizers.RMSprop(decay=1e-3))\n\n def test_adagrad(self):\n with self.cached_session():\n self._test_optimizer(keras.optimizers.Adagrad())\n self._test_optimizer(keras.optimizers.Adagrad(decay=1e-3))\n\n def test_adadelta(self):\n with self.cached_session():\n self._test_optimizer(keras.optimizers.Adadelta(), target=0.6)\n # Accuracy seems dependent on the initialization. Even adding tf.Print\n # nodes in the graph seemed to affect the initialization seed, and hence\n # the accuracy.\n self._test_optimizer(keras.optimizers.Adadelta(decay=1e-3), target=0.4)\n\n def test_adam(self):\n with self.cached_session():\n self._test_optimizer(keras.optimizers.Adam())\n # Accuracy seems dependent on the seed initialization.\n # TODO(b/121051441): fix test flakiness.\n self._test_optimizer(keras.optimizers.Adam(decay=1e-3), target=0.73)\n self._test_optimizer(keras.optimizers.Adam(amsgrad=True))\n\n def test_adamax(self):\n with self.cached_session():\n self._test_optimizer(keras.optimizers.Adamax())\n self._test_optimizer(keras.optimizers.Adamax(decay=1e-3))\n\n def test_nadam(self):\n with self.cached_session():\n self._test_optimizer(keras.optimizers.Nadam())\n\n def test_clipnorm(self):\n with self.cached_session():\n self._test_optimizer(\n keras.optimizers.SGD(lr=0.01, momentum=0.9, clipnorm=0.5))\n\n def test_clipvalue(self):\n with self.cached_session():\n self._test_optimizer(\n keras.optimizers.SGD(lr=0.01, momentum=0.9, clipvalue=0.5))\n\n def test_tf_optimizer(self):\n optimizer = keras.optimizers.TFOptimizer(AdamOptimizer(0.01))\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(\n 2, input_shape=(3,), kernel_constraint=keras.constraints.MaxNorm(1)))\n # This is possible\n model.compile(loss='mean_squared_error', optimizer=optimizer)\n keras.backend.track_tf_optimizer(optimizer)\n model.fit(np.random.random((5, 3)),\n np.random.random((5, 2)),\n epochs=1,\n batch_size=5,\n verbose=0)\n # not supported\n with self.assertRaises(NotImplementedError):\n _ = optimizer.weights\n with self.assertRaises(NotImplementedError):\n optimizer.get_config()\n with self.assertRaises(NotImplementedError):\n optimizer.from_config(None)\n\n def test_optimizer_garbage_collection(self):\n graph = ops.Graph()\n with graph.as_default():\n optimizer = keras.optimizers.TFOptimizer(AdamOptimizer(0.01))\n keras.backend.track_tf_optimizer(optimizer)\n optimizer_weak = weakref.ref(optimizer)\n graph_weak = weakref.ref(graph)\n del graph, optimizer\n gc.collect()\n # Check that the weak references are dead now.\n self.assertIs(graph_weak(), None)\n self.assertIs(optimizer_weak(), None)\n\n def test_tf_optimizer_iterations(self):\n with self.cached_session():\n optimizer = keras.optimizers.TFOptimizer(AdamOptimizer(0.01))\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(\n 2, input_shape=(3,), kernel_constraint=keras.constraints.MaxNorm(1)))\n model.compile(loss='mean_squared_error', optimizer=optimizer)\n keras.backend.track_tf_optimizer(optimizer)\n self.assertEqual(keras.backend.get_value(model.optimizer.iterations), 0)\n\n model.fit(np.random.random((55, 3)),\n np.random.random((55, 2)),\n epochs=1,\n batch_size=5,\n verbose=0)\n self.assertEqual(keras.backend.get_value(model.optimizer.iterations), 11)\n\n if not context.executing_eagerly():\n # TODO(kathywu): investigate why training with an array input and\n # setting the argument steps_per_epoch does not work in eager mode.\n model.fit(np.random.random((20, 3)),\n np.random.random((20, 2)),\n steps_per_epoch=8,\n verbose=0)\n self.assertEqual(\n keras.backend.get_value(model.optimizer.iterations), 19)\n\n def test_negative_clipvalue_or_clipnorm(self):\n with self.assertRaises(ValueError):\n _ = keras.optimizers.SGD(lr=0.01, clipvalue=-0.5)\n with self.assertRaises(ValueError):\n _ = keras.optimizers.Adam(clipnorm=-2.0)\n\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.session_ops.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\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 session_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\n\n\nclass SessionOpsTest(test.TestCase):\n\n def testHandleBasic(self):\n with self.cached_session() as sess:\n # Return a handle.\n a = constant_op.constant(10)\n b = constant_op.constant(5)\n c = math_ops.multiply(a, b)\n h = session_ops.get_session_handle(c)\n h = sess.run(h)\n\n # Feed a tensor handle.\n f, x = session_ops.get_session_tensor(h.handle, dtypes.int32)\n y = math_ops.multiply(x, 10)\n self.assertEqual(500, sess.run(y, feed_dict={f: h.handle}))\n\n def testHandleEval(self):\n with self.cached_session() as sess:\n # Return a handle.\n a = constant_op.constant(10)\n b = constant_op.constant(5)\n c = math_ops.multiply(a, b)\n h = session_ops.get_session_handle(c)\n h = sess.run(h)\n\n # Get the tensor from its handle.\n self.assertEqual(50, h.eval())\n\n def testHandleAndValue(self):\n with self.cached_session() as sess:\n # Return a handle and a value.\n a = constant_op.constant(10)\n b = constant_op.constant(5)\n c = math_ops.multiply(a, b)\n h = session_ops.get_session_handle(c)\n v = math_ops.multiply(a, c)\n h, v = sess.run([h, v])\n\n self.assertEqual(50, h.eval())\n self.assertEqual(500, v)\n\n def testHandleCond(self):\n with self.cached_session() as sess:\n # Return a handle and a value\n a = constant_op.constant(10)\n b = constant_op.constant(5)\n p = math_ops.less(a, b)\n c = math_ops.multiply(a, b)\n h = session_ops.get_session_handle(c)\n p, h = sess.run([p, h])\n\n # Run by feeding a tensor handle.\n f, x = session_ops.get_session_tensor(h.handle, dtypes.int32)\n if p:\n y = math_ops.multiply(x, 10)\n else:\n y = math_ops.multiply(x, 100)\n result = sess.run(y, feed_dict={f: h.handle})\n\n self.assertEqual(5000, result)\n\n def testHandleForLoop(self):\n with self.cached_session() as sess:\n # Initialize a handle.\n a = constant_op.constant(0)\n h = session_ops.get_session_handle(a)\n h = sess.run(h)\n\n # Do some computation.\n f, x = session_ops.get_session_tensor(h.handle, dtypes.int32)\n # Must define the loop body outside the loop.\n h_x = session_ops.get_session_handle(math_ops.add(x, 1))\n for _ in range(100):\n # This exercises garbage collection.\n h = sess.run(h_x, feed_dict={f: h.handle})\n\n self.assertEqual(100, h.eval())\n\n def testHandleWhileLoop(self):\n with self.cached_session() as sess:\n # Initialize a handle.\n a = constant_op.constant(0)\n h = session_ops.get_session_handle(a)\n h = sess.run(h)\n\n # Do some computation.\n f, x = session_ops.get_session_tensor(h.handle, dtypes.int32)\n b = constant_op.constant(100)\n p = math_ops.less(x, b)\n # Must define the loop body outside the loop.\n h_x = session_ops.get_session_handle(math_ops.add(x, 1))\n while True:\n rp, h = sess.run([p, h_x], feed_dict={f: h.handle})\n if not rp:\n break\n\n self.assertEqual(101, h.eval())\n\n def testHandleMover(self):\n with self.cached_session() as sess:\n # Return a handle.\n a = constant_op.constant(10)\n b = constant_op.constant(5)\n c = math_ops.multiply(a, b)\n h = session_ops.get_session_handle(c)\n h = sess.run(h)\n\n # Feed a tensor handle.\n f, x = session_ops.get_session_tensor(h.handle, dtypes.int32)\n y = math_ops.multiply(x, 10)\n self.assertEqual(500, sess.run(y, feed_dict={f: h.handle}))\n\n # Feed another tensor handle.\n with ops.device(test.gpu_device_name()):\n a = constant_op.constant(10)\n h = session_ops.get_session_handle(a)\n h = sess.run(h)\n self.assertEqual(100, sess.run(y, feed_dict={f: h.handle}))\n\n def testHandleDelete(self):\n with self.cached_session() as sess:\n # Return a handle.\n a = constant_op.constant(10)\n b = constant_op.constant(5)\n c = math_ops.multiply(a, b)\n h = session_ops.get_session_handle(c)\n sess.run(h).delete()\n\n def testHandleDeleteRaw(self):\n with self.cached_session() as sess:\n # Return a handle.\n a = constant_op.constant(10)\n b = constant_op.constant(5)\n c = math_ops.multiply(a, b)\n h = session_ops.get_session_handle(c)\n h = sess.run(h)\n\n # Delete using a raw tensor handle.\n raw_h = h.get_raw_handle()\n f, x = session_ops.delete_session_tensor(raw_h)\n sess.run(x, feed_dict={f: raw_h})\n\n def testMultiDevices(self):\n with self.cached_session() as sess:\n with ops.device(test.gpu_device_name()):\n a = constant_op.constant(1.0)\n a_handle = sess.run(session_ops.get_session_handle(a))\n with ops.device(\"/cpu:0\"):\n b = constant_op.constant(2.0)\n b_handle = sess.run(session_ops.get_session_handle(b))\n\n a_p, a_t = session_ops.get_session_tensor(a_handle.handle, dtypes.float32)\n b_p, b_t = session_ops.get_session_tensor(b_handle.handle, dtypes.float32)\n c = math_ops.add(a_t, b_t)\n c_handle = sess.run(\n session_ops.get_session_handle(c),\n feed_dict={a_p: a_handle.handle,\n b_p: b_handle.handle})\n self.assertEqual(3.0, c_handle.eval())\n\n def testHandleGC(self):\n with self.cached_session() as sess:\n # initial values live on CPU\n with ops.device(\"/cpu:0\"):\n one = constant_op.constant(1, dtype=dtypes.float32)\n one_handle = sess.run(session_ops.get_session_handle(one))\n x_handle = sess.run(session_ops.get_session_handle(one))\n\n # addition lives on GPU\n with ops.device(test.gpu_device_name()):\n add_h1, add_t1 = session_ops.get_session_tensor(one_handle.handle,\n dtypes.float32)\n add_h2, add_t2 = session_ops.get_session_tensor(x_handle.handle,\n dtypes.float32)\n add_op = math_ops.add(add_t1, add_t2)\n add_output = session_ops.get_session_handle(add_op)\n\n # add 1 to tensor 20 times\n for _ in range(20):\n x_handle = sess.run(\n add_output,\n feed_dict={add_h1: one_handle.handle,\n add_h2: x_handle.handle})\n\n def testHandlePlacement(self):\n with self.cached_session() as sess:\n a = constant_op.constant(1.0)\n a_handle_op = session_ops.get_session_handle(a)\n b = constant_op.constant(2.0)\n b_handle_op = session_ops.get_session_handle(b)\n\n a_handle = sess.run(a_handle_op)\n b_handle = sess.run(b_handle_op)\n\n a_p, a_t = session_ops.get_session_tensor(a_handle.handle, dtypes.float32)\n b_p, b_t = session_ops.get_session_tensor(b_handle.handle, dtypes.float32)\n\n c = math_ops.add(a_t, b_t)\n c_handle = sess.run(\n session_ops.get_session_handle(c),\n feed_dict={a_p: a_handle.handle,\n b_p: b_handle.handle})\n self.assertEqual(3.0, c_handle.eval())\n\n def testFeedOneHandleDirectly(self):\n with self.cached_session() as sess:\n a = constant_op.constant(10.0)\n b = constant_op.constant(5.0)\n c = math_ops.multiply(a, b)\n d = math_ops.multiply(c, c)\n\n h_c = sess.run(session_ops.get_session_handle(c))\n\n self.assertAllClose(2500.0, sess.run(d, feed_dict={c: h_c}))\n\n def testDirectHandleFeedOverlappingWithFetches(self):\n with self.cached_session() as sess:\n a = constant_op.constant(10.0)\n b = constant_op.constant(5.0)\n c = math_ops.multiply(a, b)\n h_c = sess.run(session_ops.get_session_handle(c))\n d = array_ops.identity(c)\n\n c_val = sess.run(c, feed_dict={c: h_c})\n self.assertAllClose(50.0, c_val)\n\n d_val = sess.run(d, feed_dict={c: h_c})\n self.assertAllClose(50.0, d_val)\n\n c_val, d_val = sess.run([c, d], feed_dict={c: h_c, d: 60.0})\n self.assertAllClose(50.0, c_val)\n self.assertAllClose(60.0, d_val)\n\n c_val, d_val = sess.run([c, d], feed_dict={c: 60.0, d: h_c})\n self.assertAllClose(60.0, c_val)\n self.assertAllClose(50.0, d_val)\n\n c_val, d_val = sess.run([c, d], feed_dict={c: h_c, d: h_c})\n self.assertAllClose(50.0, c_val)\n self.assertAllClose(50.0, d_val)\n\n def testFeedTwoHandlesDirectly(self):\n with self.cached_session() as sess:\n a = constant_op.constant(10.0)\n b = constant_op.constant(5.0)\n c = math_ops.multiply(a, b)\n d = math_ops.div(a, b)\n e = math_ops.subtract(c, d)\n\n h_c = sess.run(session_ops.get_session_handle(c))\n h_d = sess.run(session_ops.get_session_handle(d))\n\n self.assertAllClose(48.0, sess.run(e, feed_dict={c: h_c, d: h_d}))\n self.assertAllClose(-48.0, sess.run(e, feed_dict={c: h_d, d: h_c}))\n\n def testFeedHandleToVariableDirectly(self):\n with self.cached_session() as sess:\n a = variables.Variable(12.0)\n inc_a = state_ops.assign_add(a, 2.0)\n b = math_ops.add(a, 5.0)\n sess.run(a.initializer)\n\n h_a_read = sess.run(session_ops.get_session_handle(a.read_value()))\n self.assertAllClose(12.0, sess.run(a))\n\n self.assertAllClose(17.0, sess.run(b, feed_dict={a: h_a_read}))\n sess.run(inc_a)\n self.assertAllClose(19.0, sess.run(b, feed_dict={a: h_a_read}))\n\n\nif __name__ == \"__main__\":\n test.main()\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\"\"\"Functional tests for BatchToSpace op.\n\nAdditional tests are included in spacetobatch_op_test.py, where the BatchToSpace\nop is tested in tandem with its reverse SpaceToBatch op.\n\"\"\"\n\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 constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gen_array_ops\nfrom tensorflow.python.ops import gradient_checker\nfrom tensorflow.python.platform import test\n\n\nclass PythonOpImpl(object):\n\n @staticmethod\n def batch_to_space(*args, **kwargs):\n return array_ops.batch_to_space(*args, **kwargs)\n\n\nclass CppOpImpl(object):\n\n @staticmethod\n def batch_to_space(*args, **kwargs):\n return gen_array_ops.batch_to_space(*args, **kwargs)\n\n\nclass BatchToSpaceDepthToSpace(test.TestCase, PythonOpImpl):\n\n # Verifies that: batch_to_space(x) = transpose(depth_to_space(transpose(x)))\n def testDepthToSpaceTranspose(self):\n x = np.arange(20 * 5 * 8 * 7, dtype=np.float32).reshape([20, 5, 8, 7])\n block_size = 2\n for crops_dtype in [dtypes.int64, dtypes.int32]:\n crops = array_ops.zeros((2, 2), dtype=crops_dtype)\n y1 = self.batch_to_space(x, crops, block_size=block_size)\n y2 = array_ops.transpose(\n array_ops.depth_to_space(\n array_ops.transpose(x, [3, 1, 2, 0]), block_size=block_size),\n [3, 1, 2, 0])\n with self.cached_session():\n self.assertAllEqual(y1.eval(), y2.eval())\n\n\nclass BatchToSpaceDepthToSpaceCpp(BatchToSpaceDepthToSpace, CppOpImpl):\n pass\n\n\nclass BatchToSpaceErrorHandlingTest(test.TestCase, PythonOpImpl):\n\n def testInputWrongDimMissingBatch(self):\n # The input is missing the first dimension (\"batch\")\n x_np = [[[1], [2]], [[3], [4]]]\n crops = np.zeros((2, 2), dtype=np.int32)\n block_size = 2\n with self.assertRaises(ValueError):\n _ = self.batch_to_space(x_np, crops, block_size)\n\n def testBlockSize0(self):\n # The block size is 0.\n x_np = [[[[1], [2]], [[3], [4]]]]\n crops = np.zeros((2, 2), dtype=np.int32)\n block_size = 0\n with self.assertRaises(ValueError):\n out_tf = self.batch_to_space(x_np, crops, block_size)\n out_tf.eval()\n\n def testBlockSizeOne(self):\n # The block size is 1. The block size needs to be > 1.\n x_np = [[[[1], [2]], [[3], [4]]]]\n crops = np.zeros((2, 2), dtype=np.int32)\n block_size = 1\n with self.assertRaises(ValueError):\n out_tf = self.batch_to_space(x_np, crops, block_size)\n out_tf.eval()\n\n def testBlockSizeLarger(self):\n # The block size is too large for this input.\n x_np = [[[[1], [2]], [[3], [4]]]]\n crops = np.zeros((2, 2), dtype=np.int32)\n block_size = 10\n with self.assertRaises(ValueError):\n out_tf = self.batch_to_space(x_np, crops, block_size)\n out_tf.eval()\n\n def testBlockSizeSquaredNotDivisibleBatch(self):\n # The block size squared does not divide the batch.\n x_np = [[[[1], [2], [3]], [[3], [4], [7]]]]\n crops = np.zeros((2, 2), dtype=np.int32)\n block_size = 3\n with self.assertRaises(ValueError):\n _ = self.batch_to_space(x_np, crops, block_size)\n\n def testUnknownShape(self):\n t = self.batch_to_space(\n array_ops.placeholder(dtypes.float32),\n array_ops.placeholder(dtypes.int32),\n block_size=4)\n self.assertEqual(4, t.get_shape().ndims)\n\n\nclass BatchToSpaceErrorHandlingCppTest(BatchToSpaceErrorHandlingTest,\n CppOpImpl):\n pass\n\n\nclass BatchToSpaceNDErrorHandlingTest(test.TestCase):\n\n def _testStaticShape(self, input_shape, block_shape, paddings, error):\n block_shape = np.array(block_shape)\n paddings = np.array(paddings)\n\n # Try with sizes known at graph construction time.\n with self.assertRaises(error):\n _ = array_ops.batch_to_space_nd(\n np.zeros(input_shape, np.float32), block_shape, paddings)\n\n def _testDynamicShape(self, input_shape, block_shape, paddings):\n block_shape = np.array(block_shape)\n paddings = np.array(paddings)\n\n # Try with sizes unknown at graph construction time.\n input_placeholder = array_ops.placeholder(dtypes.float32)\n block_shape_placeholder = array_ops.placeholder(\n dtypes.int32, shape=block_shape.shape)\n paddings_placeholder = array_ops.placeholder(dtypes.int32)\n t = array_ops.batch_to_space_nd(input_placeholder, block_shape_placeholder,\n paddings_placeholder)\n\n with self.assertRaises(ValueError):\n _ = t.eval({\n input_placeholder: np.zeros(input_shape, np.float32),\n block_shape_placeholder: block_shape,\n paddings_placeholder: paddings\n })\n\n def _testShape(self, input_shape, block_shape, paddings, error):\n self._testStaticShape(input_shape, block_shape, paddings, error)\n self._testDynamicShape(input_shape, block_shape, paddings)\n\n def testInputWrongDimMissingBatch(self):\n self._testShape([2, 2], [2, 2], [[0, 0], [0, 0]], ValueError)\n self._testShape([2, 2, 3], [2, 2, 3], [[0, 0], [0, 0]], ValueError)\n\n def testBlockSize0(self):\n # The block size is 0.\n self._testShape([1, 2, 2, 1], [0, 1], [[0, 0], [0, 0]], ValueError)\n\n def testBlockSizeNegative(self):\n self._testShape([1, 2, 2, 1], [-1, 1], [[0, 0], [0, 0]], ValueError)\n\n def testNegativePadding(self):\n self._testShape([1, 2, 2], [1, 1], [[0, -1], [0, 0]], ValueError)\n\n def testCropTooLarge(self):\n # The amount to crop exceeds the padded size.\n self._testShape([1 * 2 * 2, 2, 3, 1], [2, 2], [[3, 2], [0, 0]], ValueError)\n\n def testBlockSizeSquaredNotDivisibleBatch(self):\n # The batch dimension is not divisible by the product of the block_shape.\n self._testShape([3, 1, 1, 1], [2, 3], [[0, 0], [0, 0]], ValueError)\n\n def testUnknownShape(self):\n # Verify that input shape and paddings shape can be unknown.\n _ = array_ops.batch_to_space_nd(\n array_ops.placeholder(dtypes.float32),\n array_ops.placeholder(\n dtypes.int32, shape=(2,)),\n array_ops.placeholder(dtypes.int32))\n\n # Only number of input dimensions is known.\n t = array_ops.batch_to_space_nd(\n array_ops.placeholder(\n dtypes.float32, shape=(None, None, None, None)),\n array_ops.placeholder(\n dtypes.int32, shape=(2,)),\n array_ops.placeholder(dtypes.int32))\n self.assertEqual(4, t.get_shape().ndims)\n\n # Dimensions are partially known.\n t = array_ops.batch_to_space_nd(\n array_ops.placeholder(\n dtypes.float32, shape=(None, None, None, 2)),\n array_ops.placeholder(\n dtypes.int32, shape=(2,)),\n array_ops.placeholder(dtypes.int32))\n self.assertEqual([None, None, None, 2], t.get_shape().as_list())\n\n # Dimensions are partially known.\n t = array_ops.batch_to_space_nd(\n array_ops.placeholder(\n dtypes.float32, shape=(3 * 2 * 3, None, None, 2)), [2, 3],\n array_ops.placeholder(dtypes.int32))\n self.assertEqual([3, None, None, 2], t.get_shape().as_list())\n\n # Dimensions are partially known.\n t = array_ops.batch_to_space_nd(\n array_ops.placeholder(\n dtypes.float32, shape=(3 * 2 * 3, None, 2, 2)), [2, 3],\n [[1, 1], [0, 1]])\n self.assertEqual([3, None, 5, 2], t.get_shape().as_list())\n\n # Dimensions are fully known.\n t = array_ops.batch_to_space_nd(\n array_ops.placeholder(\n dtypes.float32, shape=(3 * 2 * 3, 2, 1, 2)), [2, 3],\n [[1, 1], [0, 0]])\n self.assertEqual([3, 2, 3, 2], t.get_shape().as_list())\n\n\nclass BatchToSpaceGradientTest(test.TestCase, PythonOpImpl):\n\n # Check the gradients.\n def _checkGrad(self, x, crops, block_size):\n assert 4 == x.ndim\n with self.cached_session():\n tf_x = ops.convert_to_tensor(x)\n tf_y = self.batch_to_space(tf_x, crops, block_size)\n epsilon = 1e-5\n ((x_jacob_t, x_jacob_n)) = gradient_checker.compute_gradient(\n tf_x,\n x.shape,\n tf_y,\n tf_y.get_shape().as_list(),\n x_init_value=x,\n delta=epsilon)\n\n self.assertAllClose(x_jacob_t, x_jacob_n, rtol=1e-2, atol=epsilon)\n\n # Tests a gradient for batch_to_space of x which is a four dimensional\n # tensor of shape [b * block_size * block_size, h, w, d].\n def _compare(self, b, h, w, d, block_size, crop_beg, crop_end):\n block_size_sq = block_size * block_size\n x = np.random.normal(0, 1, b * h * w * d *\n block_size_sq).astype(np.float32).reshape(\n [b * block_size * block_size, h, w, d])\n crops = np.array(\n [[crop_beg, crop_end], [crop_beg, crop_end]], dtype=np.int32)\n\n self._checkGrad(x, crops, block_size)\n\n # Don't use very large numbers as dimensions here as the result is tensor\n # with cartesian product of the dimensions.\n def testSmall(self):\n block_size = 2\n crop_beg = 0\n crop_end = 0\n self._compare(1, 2, 3, 5, block_size, crop_beg, crop_end)\n\n def testSmall2(self):\n block_size = 2\n crop_beg = 0\n crop_end = 0\n self._compare(2, 4, 3, 2, block_size, crop_beg, crop_end)\n\n def testSmallCrop1x1(self):\n block_size = 2\n crop_beg = 1\n crop_end = 1\n self._compare(1, 2, 3, 5, block_size, crop_beg, crop_end)\n\n\nclass BatchToSpaceGradientCppTest(BatchToSpaceGradientTest, CppOpImpl):\n pass\n\n\nclass BatchToSpaceNDGradientTest(test.TestCase):\n\n # Check the gradients.\n def _checkGrad(self, x, block_shape, crops, crops_dtype):\n block_shape = np.array(block_shape)\n crops = constant_op.constant(\n np.array(crops).reshape((len(block_shape), 2)), crops_dtype)\n with self.cached_session():\n tf_x = ops.convert_to_tensor(x)\n tf_y = array_ops.batch_to_space_nd(tf_x, block_shape, crops)\n epsilon = 1e-5\n ((x_jacob_t, x_jacob_n)) = gradient_checker.compute_gradient(\n tf_x,\n x.shape,\n tf_y,\n tf_y.get_shape().as_list(),\n x_init_value=x,\n delta=epsilon)\n\n self.assertAllClose(x_jacob_t, x_jacob_n, rtol=1e-2, atol=epsilon)\n\n def _compare(self, input_shape, block_shape, crops, crops_dtype):\n input_shape = list(input_shape)\n input_shape[0] *= np.prod(block_shape)\n x = np.random.normal(\n 0, 1, np.prod(input_shape)).astype(np.float32).reshape(input_shape)\n self._checkGrad(x, block_shape, crops, crops_dtype)\n\n # Don't use very large numbers as dimensions here as the result is tensor\n # with cartesian product of the dimensions.\n def testSmall(self):\n for dtype in [dtypes.int64, dtypes.int32]:\n self._compare([1, 2, 3, 5], [2, 2], [[0, 0], [0, 0]], dtype)\n\n def testSmall2(self):\n for dtype in [dtypes.int64, dtypes.int32]:\n self._compare([2, 4, 3, 2], [2, 2], [[0, 0], [0, 0]], dtype)\n\n def testSmallCrop1x1(self):\n for dtype in [dtypes.int64, dtypes.int32]:\n self._compare([1, 2, 3, 5], [2, 2], [[1, 1], [1, 1]], dtype)\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\"\"\"Gather operations for RaggedTensors.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gen_ragged_array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops.ragged import ragged_array_ops\nfrom tensorflow.python.ops.ragged import ragged_conversion_ops\nfrom tensorflow.python.ops.ragged import ragged_tensor\n\n\n#===============================================================================\n# ragged_gather\n#===============================================================================\n# TODO(edloper): Add an `axis` argument\ndef gather(params, indices, validate_indices=None, axis=0, batch_dims=0,\n name=None):\n \"\"\"Gathers ragged slices from `params` axis `0` according to `indices`.\n\n Returns `RaggedTensor` output, such that:\n\n ```python\n output.shape = indices.shape + params.shape[1:]\n output.ragged_rank = indices.shape.ndims + params.ragged_rank\n output[i...j, d0...dn] = params[indices[i...j], d0...dn]\n ```\n\n `params` may be ragged. `indices` may be ragged.\n `indices` must have dtype `int32` or `int64`. If any index is out of bounds,\n then an error is returned.\n\n Examples:\n\n ```python\n >>> params = tf.constant(['a', 'b', 'c', 'd', 'e'])\n >>> indices = tf.constant([3, 1, 2, 1, 0])\n >>> ragged_params = tf.ragged.constant([['a', 'b', 'c'], ['d'], [], ['e']])\n >>> ragged_indices = tf.ragged.constant([[3, 1, 2], [1], [], [0]])\n\n >>> print ragged.gather(params, ragged_indices)\n [['d', 'b', 'c'], ['b'], [], ['a']]\n\n >>> print ragged.gather(ragged_params, indices)\n [['e'], ['d'], [], ['d'], ['a', 'b', 'c']]\n\n >>> print ragged.gather(ragged_params, ragged_indices)\n [[['e'], ['d'], []], [['d']], [], [['a', 'b', 'c']]]\n ```\n\n Args:\n params: The potentially ragged tensor from which to gather values. Must be\n at least rank 1.\n indices: The potentially ragged tensor indicating which values to gather.\n Must have dtype `int32` or `int64`. Values must be in the range `[0,\n params.shape[0]]`.\n validate_indices: Ignored.\n axis: Must be zero.\n batch_dims: Must be zero.\n name: A name for the operation (optional).\n\n Returns:\n A `RaggedTensor`, where `output.dtype=params.dtype` and\n `output.shape=indices.shape + params.shape[1:]` and\n `output.ragged_rank=indices.shape.ndims + params.ragged_rank`.\n\n Raises:\n ValueError: If indices.shape.ndims is not known statically.\n \"\"\"\n del validate_indices\n if not isinstance(axis, int) or axis != 0:\n raise ValueError('axis != 0 is not supported for ragged gather yet.')\n if not isinstance(batch_dims, int) or batch_dims != 0:\n raise ValueError('batch_dims != 0 is not supported for ragged gather yet.')\n with ops.name_scope(name, 'RaggedGather', [params, indices]):\n params = ragged_tensor.convert_to_tensor_or_ragged_tensor(\n params, name='params')\n indices = ragged_tensor.convert_to_tensor_or_ragged_tensor(\n indices, name='indices')\n\n if ragged_tensor.is_ragged(indices):\n return indices.with_values(gather(params, indices.values))\n\n if not ragged_tensor.is_ragged(params):\n return array_ops.gather(params, indices)\n\n indices = ops.convert_to_tensor(indices)\n if indices.shape.ndims is None:\n raise ValueError('indices.shape.ndims must be known statically')\n\n result = gen_ragged_array_ops.ragged_gather(\n indices=indices,\n params_dense_values=params.flat_values,\n params_nested_splits=params.nested_row_splits,\n OUTPUT_RAGGED_RANK=indices.shape.ndims + len(params.nested_row_splits) -\n 1)\n\n # Compose the RaggedTensor from splits & values.\n return ragged_tensor.RaggedTensor.from_nested_row_splits(\n result.output_dense_values, result.output_nested_splits)\n\n\n#===============================================================================\n# ragged.gather_nd\n#===============================================================================\ndef gather_nd(params, indices, batch_dims=0, name=None):\n \"\"\"Gather slices from `params` using `n`-dimensional indices.\n\n This operation is similar to `gather`, but it uses the innermost dimension\n of `indices` to define a slice into `params`. In particular, if:\n\n * `indices` has shape `[A1...AN, I]`\n * `params` has shape `[B1...BM]`\n\n Then:\n\n * `result` has shape `[A1...AN, B_{I+1}...BM]`.\n * `result[a1...aN] = params[indices[a1...aN, :]]`\n\n Args:\n params: A potentially ragged tensor with shape `[A1...AN, I]`.\n indices: A potentially ragged tensor with shape `[B1...BM]`.\n batch_dims: Must be zero.\n name: A name for the operation (optional).\n\n Returns:\n A potentially ragged tensor with shape `[A1...AN, B_{I+1}...BM]`.\n\n #### Examples:\n ```python\n >>> params = tf.ragged.constant_value(\n ... [ [ ['000', '001'], ['010' ] ],\n ... [ ['100' ], ['110', '111', '112'], ['120'] ],\n ... [ [ ], ['210' ] ] ])\n\n >>> # Gather 2D slices from a 3D tensor\n >>> ragged.gather_nd(params, [[2], [0]])\n [ [ [ ], ['210'] ]\n [ ['000', '001'], ['010'] ] ]\n\n >>> # Gather 1D slices from a 3D tensor\n >>> ragged.gather_nd(params, [[2, 1], [0, 0]])\n [['210'], ['000', '001']]\n\n >>> # Gather scalars from a 3D tensor\n >>> ragged.gather_nd(params, [[0, 0, 1], [1, 1, 2]])\n ['001', '112']\n ```\n \"\"\"\n if not isinstance(batch_dims, int) or batch_dims != 0:\n raise ValueError('batch_dims != 0 is not supported for ragged gather yet.')\n if not (ragged_tensor.is_ragged(params) or ragged_tensor.is_ragged(indices)):\n return array_ops.gather_nd(params, indices, name)\n\n with ops.name_scope(name, 'RaggedGatherNd', [params, indices]):\n\n params = ragged_tensor.convert_to_tensor_or_ragged_tensor(\n params, name='params')\n indices = ragged_tensor.convert_to_tensor_or_ragged_tensor(\n indices, name='indices')\n indices_shape = indices.shape\n indices_ndims = indices_shape.ndims\n if indices_ndims is None:\n raise ValueError('indices.rank be statically known.')\n if indices_ndims == 0:\n raise ValueError('indices.rank must be at least 1.')\n if (ragged_tensor.is_ragged(indices) and\n indices_ndims == indices.ragged_rank + 1):\n raise ValueError('The innermost dimension of indices may not be ragged')\n\n # `index_size` is the \"n\" in \"gather_nd\" -- i.e., the number of dimensions\n # that each index slices into.\n index_size = tensor_shape.dimension_value(indices_shape[-1])\n if index_size is None:\n raise ValueError('indices.shape[-1] must be statically known.')\n\n # If `indices` has more than 2 dimensions, then recurse. If `indices` is\n # dense, then we convert it to ragged before recursing, and then convert\n # the result back to `dense` if appropriate.\n if indices_ndims > 2:\n indices_is_dense = not ragged_tensor.is_ragged(indices)\n if indices_is_dense:\n indices = ragged_conversion_ops.from_tensor(\n indices, ragged_rank=indices_ndims - 2)\n result = indices.with_flat_values(gather_nd(params, indices.flat_values))\n if (indices_is_dense and ragged_tensor.is_ragged(result) and\n result.ragged_rank == indices_ndims - 2):\n result = ragged_conversion_ops.to_tensor(result)\n return result\n\n # indices_ndims <= 2, and the innermost dimension of indices may not be\n # ragged, so `indices` must not be ragged.\n assert not ragged_tensor.is_ragged(indices)\n assert ragged_tensor.is_ragged(params)\n\n # Handle corner case: An empty index tuple selects the entire `params`\n # value. So if `index_size` is zero, then tile `params`.\n if index_size == 0:\n params_ndims = params.ragged_rank + array_ops.rank(params.flat_values)\n for dim in range(indices_ndims - 1):\n params = ragged_array_ops.expand_dims(params, axis=0)\n multiples = array_ops.concat([\n array_ops.shape(indices)[:-1],\n array_ops.ones([params_ndims], dtypes.int32)\n ],\n axis=0)\n return ragged_array_ops.tile(params, multiples)\n\n # When index_size=1, we can just flatten the index tuples and use gather.\n elif index_size == 1:\n flattened_index_tuples = array_ops.reshape(indices, [-1])\n return gather(params, flattened_index_tuples)\n\n # Otherwise, params is a RaggedTensor, and indices is a 1D or 2D Tensor.\n # Flatten both the index tuples and the params, such that the flattened\n # index tuples point to the correct values in the flattened params; and\n # then use ragged.gather on the flattened index tuples & params.\n else:\n indices = math_ops.cast(indices, dtypes.int64)\n\n # Flatten the outermost 2 dimensions of the index tuples & params.\n flattened_index_tuples = array_ops.gather(params.row_splits,\n indices[..., 0])\n flattened_index_tuples += indices[..., 1]\n flattened_params = params.values\n\n # Flatten any remaining dimensions.\n for dim in range(2, index_size):\n if not ragged_tensor.is_ragged(flattened_params):\n flattened_index_tuples = array_ops.expand_dims(\n flattened_index_tuples, axis=1)\n flattened_index_tuples = array_ops.concat(\n [flattened_index_tuples, indices[..., dim:]], axis=1)\n return array_ops.gather_nd(flattened_params, flattened_index_tuples)\n\n flattened_index_tuples = array_ops.gather(\n flattened_params.row_starts(), flattened_index_tuples)\n flattened_index_tuples += indices[..., dim]\n flattened_params = flattened_params.values\n\n # Gather using the flattened index tuples and params.\n return gather(flattened_params, flattened_index_tuples)\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# ==============================================================================\n\"\"\"Tests for `tf.data.experimental.dense_to_sparse_batch().\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.data.experimental.ops import batching\nfrom tensorflow.python.data.kernel_tests import test_base\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.platform import test\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass DenseToSparseBatchTest(test_base.DatasetTestBase):\n\n def testDenseToSparseBatchDataset(self):\n components = np.random.randint(12, size=(100,)).astype(np.int32)\n dataset = dataset_ops.Dataset.from_tensor_slices(\n components).map(lambda x: array_ops.fill([x], x)).apply(\n batching.dense_to_sparse_batch(4, [12]))\n get_next = self.getNext(dataset)\n\n for start in range(0, len(components), 4):\n results = self.evaluate(get_next())\n self.assertAllEqual([[i, j]\n for i, c in enumerate(components[start:start + 4])\n for j in range(c)], results.indices)\n self.assertAllEqual(\n [c for c in components[start:start + 4] for _ in range(c)],\n results.values)\n self.assertAllEqual([min(4,\n len(components) - start), 12],\n results.dense_shape)\n\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n def testDenseToSparseBatchDatasetWithUnknownShape(self):\n components = np.random.randint(5, size=(40,)).astype(np.int32)\n dataset = dataset_ops.Dataset.from_tensor_slices(\n components).map(lambda x: array_ops.fill([x, x], x)).apply(\n batching.dense_to_sparse_batch(4, [5, None]))\n\n get_next = self.getNext(dataset)\n\n for start in range(0, len(components), 4):\n results = self.evaluate(get_next())\n self.assertAllEqual([[i, j, z]\n for i, c in enumerate(components[start:start + 4])\n for j in range(c)\n for z in range(c)], results.indices)\n self.assertAllEqual([\n c for c in components[start:start + 4] for _ in range(c)\n for _ in range(c)\n ], results.values)\n self.assertAllEqual([\n min(4,\n len(components) - start), 5,\n np.max(components[start:start + 4])\n ], results.dense_shape)\n\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n def testDenseToSparseBatchDatasetWithInvalidShape(self):\n input_tensor = array_ops.constant([[1]])\n with self.assertRaisesRegexp(ValueError, \"Dimension -2 must be >= 0\"):\n dataset_ops.Dataset.from_tensors(input_tensor).apply(\n batching.dense_to_sparse_batch(4, [-2]))\n\n def testDenseToSparseBatchDatasetShapeErrors(self):\n\n def dataset_fn(input_tensor):\n return dataset_ops.Dataset.from_tensors(input_tensor).apply(\n batching.dense_to_sparse_batch(4, [12]))\n\n # Initialize with an input tensor of incompatible rank.\n get_next = self.getNext(dataset_fn([[1]]))\n with self.assertRaisesRegexp(errors.InvalidArgumentError,\n \"incompatible with the row shape\"):\n self.evaluate(get_next())\n\n # Initialize with an input tensor that is larger than `row_shape`.\n get_next = self.getNext(dataset_fn(np.int32(range(13))))\n with self.assertRaisesRegexp(errors.DataLossError,\n \"larger than the row shape\"):\n self.evaluate(get_next())\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# pylint: disable=protected-access\n\"\"\"Utility functions to save/load keras Model to/from SavedModel.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport six\n\nfrom tensorflow.python.client import session\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras import optimizers\nfrom tensorflow.python.keras.optimizer_v2 import optimizer_v2\nfrom tensorflow.python.keras.saving import model_from_json\nfrom tensorflow.python.keras.saving import saving_utils\nfrom tensorflow.python.keras.utils import mode_keys\nfrom tensorflow.python.lib.io import file_io\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.saved_model import builder as saved_model_builder\nfrom tensorflow.python.saved_model import constants\nfrom tensorflow.python.saved_model import model_utils\nfrom tensorflow.python.saved_model import save as save_lib\nfrom tensorflow.python.saved_model import utils_impl as saved_model_utils\nfrom tensorflow.python.training import saver as saver_lib\nfrom tensorflow.python.training.tracking import graph_view\nfrom tensorflow.python.util import compat\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util.tf_export import keras_export\n\n\n@keras_export('keras.experimental.export_saved_model')\ndef export_saved_model(model,\n saved_model_path,\n custom_objects=None,\n as_text=False,\n input_signature=None,\n serving_only=False):\n \"\"\"Exports a `tf.keras.Model` as a Tensorflow SavedModel.\n\n Note that at this time, subclassed models can only be saved using\n `serving_only=True`.\n\n The exported `SavedModel` is a standalone serialization of Tensorflow objects,\n and is supported by TF language APIs and the Tensorflow Serving system.\n To load the model, use the function\n `tf.keras.experimental.load_from_saved_model`.\n\n The `SavedModel` contains:\n\n 1. a checkpoint containing the model weights.\n 2. a `SavedModel` proto containing the Tensorflow backend graph. Separate\n graphs are saved for prediction (serving), train, and evaluation. If\n the model has not been compiled, then only the graph computing predictions\n will be exported.\n 3. the model's json config. If the model is subclassed, this will only be\n included if the model's `get_config()` method is overwritten.\n\n Example:\n\n ```python\n import tensorflow as tf\n\n # Create a tf.keras model.\n model = tf.keras.Sequential()\n model.add(tf.keras.layers.Dense(1, input_shape=[10]))\n model.summary()\n\n # Save the tf.keras model in the SavedModel format.\n path = '/tmp/simple_keras_model'\n tf.keras.experimental.export_saved_model(model, path)\n\n # Load the saved keras model back.\n new_model = tf.keras.experimental.load_from_saved_model(path)\n new_model.summary()\n ```\n\n Args:\n model: A `tf.keras.Model` to be saved. If the model is subclassed, the flag\n `serving_only` must be set to True.\n saved_model_path: a string specifying the path to the SavedModel directory.\n custom_objects: Optional dictionary mapping string names to custom classes\n or functions (e.g. custom loss functions).\n as_text: bool, `False` by default. Whether to write the `SavedModel` proto\n in text format. Currently unavailable in serving-only mode.\n input_signature: A possibly nested sequence of `tf.TensorSpec` objects, used\n to specify the expected model inputs. See `tf.function` for more details.\n serving_only: bool, `False` by default. When this is true, only the\n prediction graph is saved.\n\n Raises:\n NotImplementedError: If the model is a subclassed model, and serving_only is\n False.\n ValueError: If the input signature cannot be inferred from the model.\n AssertionError: If the SavedModel directory already exists and isn't empty.\n \"\"\"\n if serving_only:\n save_lib.save(\n model,\n saved_model_path,\n signatures=saving_utils.trace_model_call(model, input_signature))\n else:\n _save_v1_format(model, saved_model_path, custom_objects, as_text,\n input_signature)\n\n try:\n _export_model_json(model, saved_model_path)\n except NotImplementedError:\n logging.warning('Skipped saving model JSON, subclassed model does not have '\n 'get_config() defined.')\n\n\ndef _export_model_json(model, saved_model_path):\n \"\"\"Saves model configuration as a json string under assets folder.\"\"\"\n model_json = model.to_json()\n model_json_filepath = os.path.join(\n saved_model_utils.get_or_create_assets_dir(saved_model_path),\n compat.as_text(constants.SAVED_MODEL_FILENAME_JSON))\n file_io.write_string_to_file(model_json_filepath, model_json)\n\n\ndef _export_model_variables(model, saved_model_path):\n \"\"\"Saves model weights in checkpoint format under variables folder.\"\"\"\n saved_model_utils.get_or_create_variables_dir(saved_model_path)\n checkpoint_prefix = saved_model_utils.get_variables_path(saved_model_path)\n model.save_weights(checkpoint_prefix, save_format='tf', overwrite=True)\n return checkpoint_prefix\n\n\ndef _save_v1_format(model, path, custom_objects, as_text, input_signature):\n \"\"\"Exports model to v1 SavedModel format.\"\"\"\n from tensorflow.python.keras.engine import sequential # pylint: disable=g-import-not-at-top\n\n if not model._is_graph_network:\n if isinstance(model, sequential.Sequential):\n # If input shape is not directly set in the model, the exported model\n # will infer the expected shapes of the input from the model.\n if not model.built and input_signature is None:\n raise ValueError(\n 'Sequential model\\'s input shape is unknown. Please build the '\n 'model, or use the input_signature argument to specify the '\n 'model inputs.')\n else:\n raise NotImplementedError(\n 'Subclassed models can only be exported for serving. Please set '\n 'argument serving_only=True.')\n\n builder = saved_model_builder._SavedModelBuilder(path)\n\n # Manually save variables to export them in an object-based checkpoint. This\n # skips the `builder.add_meta_graph_and_variables()` step, which saves a\n # named-based checkpoint.\n # TODO(b/113134168): Add fn to Builder to save with object-based saver.\n # TODO(b/113178242): This should only export the model json structure. Only\n # one save is needed once the weights can be copied from the model to clone.\n checkpoint_path = _export_model_variables(model, path)\n\n # Export each mode. Use ModeKeys enums defined for `Estimator` to ensure that\n # Keras models and `Estimator`s are exported with the same format.\n # Every time a mode is exported, the code checks to see if new variables have\n # been created (e.g. optimizer slot variables). If that is the case, the\n # checkpoint is re-saved to include the new variables.\n export_args = {'builder': builder,\n 'model': model,\n 'custom_objects': custom_objects,\n 'checkpoint_path': checkpoint_path,\n 'input_signature': input_signature}\n\n has_saved_vars = False\n if model.optimizer:\n if isinstance(model.optimizer, (optimizers.TFOptimizer,\n optimizer_v2.OptimizerV2)):\n _export_mode(mode_keys.ModeKeys.TRAIN, has_saved_vars, **export_args)\n has_saved_vars = True\n _export_mode(mode_keys.ModeKeys.TEST, has_saved_vars, **export_args)\n else:\n logging.warning(\n 'Model was compiled with an optimizer, but the optimizer is not from '\n '`tf.train` (e.g. `tf.train.AdagradOptimizer`). Only the serving '\n 'graph was exported. The train and evaluate graphs were not added to '\n 'the SavedModel.')\n _export_mode(mode_keys.ModeKeys.PREDICT, has_saved_vars, **export_args)\n\n builder.save(as_text)\n\n\ndef _get_var_list(model):\n \"\"\"Returns list of all checkpointed saveable objects in the model.\"\"\"\n var_list, _, _ = graph_view.ObjectGraphView(model).serialize_object_graph()\n return var_list\n\n\ndef create_placeholder(spec):\n return K.placeholder(shape=spec.shape, dtype=spec.dtype, name=spec.name)\n\n\ndef _export_mode(\n mode, has_saved_vars, builder, model, custom_objects, checkpoint_path,\n input_signature):\n \"\"\"Exports a model, and optionally saves new vars from the clone model.\n\n Args:\n mode: A `tf.estimator.ModeKeys` string.\n has_saved_vars: A `boolean` indicating whether the SavedModel has already\n exported variables.\n builder: A `SavedModelBuilder` object.\n model: A `tf.keras.Model` object.\n custom_objects: A dictionary mapping string names to custom classes\n or functions.\n checkpoint_path: String path to checkpoint.\n input_signature: Nested TensorSpec containing the expected inputs. Can be\n `None`, in which case the signature will be inferred from the model.\n\n Raises:\n ValueError: If the train/eval mode is being exported, but the model does\n not have an optimizer.\n \"\"\"\n from tensorflow.python.keras import models as models_lib # pylint: disable=g-import-not-at-top\n compile_clone = (mode != mode_keys.ModeKeys.PREDICT)\n if compile_clone and not model.optimizer:\n raise ValueError(\n 'Model does not have an optimizer. Cannot export mode %s' % mode)\n\n model_graph = ops.get_default_graph()\n with ops.Graph().as_default() as g, K.learning_phase_scope(\n mode == mode_keys.ModeKeys.TRAIN):\n\n if input_signature is None:\n input_tensors = None\n else:\n input_tensors = nest.map_structure(create_placeholder, input_signature)\n\n # Clone the model into blank graph. This will create placeholders for inputs\n # and targets.\n clone = models_lib.clone_and_build_model(\n model, input_tensors=input_tensors, custom_objects=custom_objects,\n compile_clone=compile_clone)\n\n # Make sure that iterations variable is added to the global step collection,\n # to ensure that, when the SavedModel graph is loaded, the iterations\n # variable is returned by `tf.train.get_global_step()`. This is required for\n # compatibility with the SavedModelEstimator.\n if compile_clone:\n g.add_to_collection(ops.GraphKeys.GLOBAL_STEP, clone.optimizer.iterations)\n\n # Extract update and train ops from train/test/predict functions.\n train_op = None\n if mode == mode_keys.ModeKeys.TRAIN:\n clone._make_train_function()\n train_op = clone.train_function.updates_op\n elif mode == mode_keys.ModeKeys.TEST:\n clone._make_test_function()\n else:\n clone._make_predict_function()\n g.get_collection_ref(ops.GraphKeys.UPDATE_OPS).extend(clone.state_updates)\n\n with session.Session().as_default():\n clone_var_list = _get_var_list(clone)\n if has_saved_vars:\n # Confirm all variables in the clone have an entry in the checkpoint.\n status = clone.load_weights(checkpoint_path)\n status.assert_existing_objects_matched()\n else:\n # Confirm that variables between the clone and model match up exactly,\n # not counting optimizer objects. Optimizer objects are ignored because\n # if the model has not trained, the slot variables will not have been\n # created yet.\n # TODO(b/113179535): Replace with trackable equivalence.\n _assert_same_non_optimizer_objects(model, model_graph, clone, g)\n\n # TODO(b/113178242): Use value transfer for trackable objects.\n clone.load_weights(checkpoint_path)\n\n # Add graph and variables to SavedModel.\n # TODO(b/113134168): Switch to add_meta_graph_and_variables.\n clone.save_weights(checkpoint_path, save_format='tf', overwrite=True)\n builder._has_saved_variables = True\n\n # Add graph to the SavedModel builder.\n builder.add_meta_graph(\n model_utils.EXPORT_TAG_MAP[mode],\n signature_def_map=_create_signature_def_map(clone, mode),\n saver=saver_lib.Saver(clone_var_list),\n init_op=variables.local_variables_initializer(),\n train_op=train_op)\n return None\n\n\ndef _create_signature_def_map(model, mode):\n \"\"\"Creates a SignatureDef map from a Keras model.\"\"\"\n inputs_dict = {name: x for name, x in zip(model.input_names, model.inputs)}\n if model.optimizer:\n targets_dict = {x.name.split(':')[0]: x\n for x in model.targets if x is not None}\n inputs_dict.update(targets_dict)\n outputs_dict = {name: x\n for name, x in zip(model.output_names, model.outputs)}\n metrics = saving_utils.extract_model_metrics(model)\n\n # Add metric variables to the `LOCAL_VARIABLES` collection. Metric variables\n # are by default not added to any collections. We are doing this here, so\n # that metric variables get initialized.\n local_vars = set(ops.get_collection(ops.GraphKeys.LOCAL_VARIABLES))\n vars_to_add = set()\n if metrics is not None:\n from tensorflow.python.keras.metrics import Metric # pylint: disable=g-import-not-at-top\n for key, value in six.iteritems(metrics):\n if isinstance(value, Metric):\n vars_to_add.update(value.variables)\n # Convert Metric instances to (value_tensor, update_op) tuple.\n metrics[key] = (value.result(), value.updates[0])\n # Remove variables that are in the local variables collection already.\n vars_to_add = vars_to_add.difference(local_vars)\n for v in vars_to_add:\n ops.add_to_collection(ops.GraphKeys.LOCAL_VARIABLES, v)\n\n export_outputs = model_utils.export_outputs_for_mode(\n mode,\n predictions=outputs_dict,\n loss=model.total_loss if model.optimizer else None,\n metrics=metrics)\n return model_utils.build_all_signature_defs(\n inputs_dict,\n export_outputs=export_outputs,\n serving_only=(mode == mode_keys.ModeKeys.PREDICT))\n\n\ndef _assert_same_non_optimizer_objects(model, model_graph, clone, clone_graph): # pylint: disable=unused-argument\n \"\"\"Asserts model and clone contain the same trackable objects.\"\"\"\n\n # TODO(fchollet, kathywu): make sure this works in eager mode.\n return True\n\n\n@keras_export('keras.experimental.load_from_saved_model')\ndef load_from_saved_model(saved_model_path, custom_objects=None):\n \"\"\"Loads a keras Model from a SavedModel created by `export_saved_model()`.\n\n This function reinstantiates model state by:\n 1) loading model topology from json (this will eventually come\n from metagraph).\n 2) loading model weights from checkpoint.\n\n Example:\n\n ```python\n import tensorflow as tf\n\n # Create a tf.keras model.\n model = tf.keras.Sequential()\n model.add(tf.keras.layers.Dense(1, input_shape=[10]))\n model.summary()\n\n # Save the tf.keras model in the SavedModel format.\n path = '/tmp/simple_keras_model'\n tf.keras.experimental.export_saved_model(model, path)\n\n # Load the saved keras model back.\n new_model = tf.keras.experimental.load_from_saved_model(path)\n new_model.summary()\n ```\n\n Args:\n saved_model_path: a string specifying the path to an existing SavedModel.\n custom_objects: Optional dictionary mapping names\n (strings) to custom classes or functions to be\n considered during deserialization.\n\n Returns:\n a keras.Model instance.\n \"\"\"\n # restore model topology from json string\n model_json_filepath = os.path.join(\n compat.as_bytes(saved_model_path),\n compat.as_bytes(constants.ASSETS_DIRECTORY),\n compat.as_bytes(constants.SAVED_MODEL_FILENAME_JSON))\n model_json = file_io.read_file_to_string(model_json_filepath)\n model = model_from_json(model_json, custom_objects=custom_objects)\n\n # restore model weights\n checkpoint_prefix = os.path.join(\n compat.as_text(saved_model_path),\n compat.as_text(constants.VARIABLES_DIRECTORY),\n compat.as_text(constants.VARIABLES_FILENAME))\n model.load_weights(checkpoint_prefix)\n return model\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\"\"\"Tests for Keras callbacks.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport csv\nimport os\nimport re\nimport shutil\nimport sys\nimport threading\nimport unittest\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python import keras\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import random_seed\nfrom tensorflow.python.keras import keras_parameterized\nfrom tensorflow.python.keras import testing_utils\nfrom tensorflow.python.keras.engine import base_layer\nfrom tensorflow.python.keras.engine import sequential\nfrom tensorflow.python.keras.optimizer_v2 import gradient_descent\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.summary import summary_iterator\nfrom tensorflow.python.training import adam\n\ntry:\n import h5py # pylint:disable=g-import-not-at-top\nexcept ImportError:\n h5py = None\n\ntry:\n import requests # pylint:disable=g-import-not-at-top\nexcept ImportError:\n requests = None\n\n\nTRAIN_SAMPLES = 10\nTEST_SAMPLES = 10\nNUM_CLASSES = 2\nINPUT_DIM = 3\nNUM_HIDDEN = 5\nBATCH_SIZE = 5\n\n\nclass Counter(keras.callbacks.Callback):\n \"\"\"Counts the number of times each callback method was run.\n\n Attributes:\n method_counts: dict. Contains the counts of time each callback method was\n run.\n \"\"\"\n\n def __init__(self):\n self.method_counts = collections.defaultdict(int)\n methods_to_count = [\n 'on_batch_begin', 'on_batch_end', 'on_epoch_begin', 'on_epoch_end',\n 'on_predict_batch_begin', 'on_predict_batch_end', 'on_predict_begin',\n 'on_predict_end', 'on_test_batch_begin', 'on_test_batch_end',\n 'on_test_begin', 'on_test_end', 'on_train_batch_begin',\n 'on_train_batch_end', 'on_train_begin', 'on_train_end'\n ]\n for method_name in methods_to_count:\n setattr(self, method_name,\n self.wrap_with_counts(method_name, getattr(self, method_name)))\n\n def wrap_with_counts(self, method_name, method):\n\n def _call_and_count(*args, **kwargs):\n self.method_counts[method_name] += 1\n return method(*args, **kwargs)\n\n return _call_and_count\n\n\ndef _get_numpy():\n return np.ones((10, 10)), np.ones((10, 1))\n\n\ndef _get_sequence():\n\n class MySequence(keras.utils.data_utils.Sequence):\n\n def __getitem__(self, _):\n return np.ones((2, 10)), np.ones((2, 1))\n\n def __len__(self):\n return 5\n\n return MySequence(), None\n\n\n@keras_parameterized.run_with_all_model_types\n@keras_parameterized.run_all_keras_modes\nclass CallbackCountsTest(keras_parameterized.TestCase):\n\n def _check_counts(self, counter, expected_counts):\n \"\"\"Checks that the counts registered by `counter` are those expected.\"\"\"\n for method_name, expected_count in expected_counts.items():\n self.assertEqual(\n counter.method_counts[method_name],\n expected_count,\n msg='For method {}: expected {}, got: {}'.format(\n method_name, expected_count, counter.method_counts[method_name]))\n\n def _get_model(self):\n layers = [\n keras.layers.Dense(10, activation='relu'),\n keras.layers.Dense(1, activation='sigmoid')\n ]\n model = testing_utils.get_model_from_layers(layers, input_shape=(10,))\n model.compile(\n adam.AdamOptimizer(0.001),\n 'binary_crossentropy',\n run_eagerly=testing_utils.should_run_eagerly())\n return model\n\n @parameterized.named_parameters(('with_numpy', _get_numpy()),\n ('with_sequence', _get_sequence()))\n def test_callback_hooks_are_called_in_fit(self, data):\n x, y = data\n val_x, val_y = np.ones((4, 10)), np.ones((4, 1))\n\n model = self._get_model()\n counter = Counter()\n model.fit(\n x,\n y,\n validation_data=(val_x, val_y),\n batch_size=2,\n epochs=5,\n callbacks=[counter])\n\n self._check_counts(\n counter, {\n 'on_batch_begin': 25,\n 'on_batch_end': 25,\n 'on_epoch_begin': 5,\n 'on_epoch_end': 5,\n 'on_predict_batch_begin': 0,\n 'on_predict_batch_end': 0,\n 'on_predict_begin': 0,\n 'on_predict_end': 0,\n 'on_test_batch_begin': 10,\n 'on_test_batch_end': 10,\n 'on_test_begin': 5,\n 'on_test_end': 5,\n 'on_train_batch_begin': 25,\n 'on_train_batch_end': 25,\n 'on_train_begin': 1,\n 'on_train_end': 1\n })\n\n @parameterized.named_parameters(('with_numpy', _get_numpy()),\n ('with_sequence', _get_sequence()))\n def test_callback_hooks_are_called_in_evaluate(self, data):\n x, y = data\n\n model = self._get_model()\n counter = Counter()\n model.evaluate(x, y, batch_size=2, callbacks=[counter])\n self._check_counts(\n counter, {\n 'on_test_batch_begin': 5,\n 'on_test_batch_end': 5,\n 'on_test_begin': 1,\n 'on_test_end': 1\n })\n\n @parameterized.named_parameters(('with_numpy', _get_numpy()),\n ('with_sequence', _get_sequence()))\n def test_callback_hooks_are_called_in_predict(self, data):\n x = data[0]\n\n model = self._get_model()\n counter = Counter()\n model.predict(x, batch_size=2, callbacks=[counter])\n self._check_counts(\n counter, {\n 'on_predict_batch_begin': 5,\n 'on_predict_batch_end': 5,\n 'on_predict_begin': 1,\n 'on_predict_end': 1\n })\n\n def test_callback_list_methods(self):\n counter = Counter()\n callback_list = keras.callbacks.CallbackList([counter])\n\n batch = 0\n callback_list.on_test_batch_begin(batch)\n callback_list.on_test_batch_end(batch)\n callback_list.on_predict_batch_begin(batch)\n callback_list.on_predict_batch_end(batch)\n\n self._check_counts(\n counter, {\n 'on_test_batch_begin': 1,\n 'on_test_batch_end': 1,\n 'on_predict_batch_begin': 1,\n 'on_predict_batch_end': 1\n })\n\n\nclass KerasCallbacksTest(keras_parameterized.TestCase):\n\n def _get_model(self, input_shape=None):\n layers = [\n keras.layers.Dense(3, activation='relu'),\n keras.layers.Dense(2, activation='softmax')\n ]\n model = testing_utils.get_model_from_layers(layers, input_shape=input_shape)\n model.compile(\n loss='mse',\n optimizer='rmsprop',\n metrics=[keras.metrics.CategoricalAccuracy(name='my_acc')],\n run_eagerly=testing_utils.should_run_eagerly())\n return model\n\n @keras_parameterized.run_with_all_model_types\n @keras_parameterized.run_all_keras_modes\n def test_progbar_logging(self):\n model = self._get_model(input_shape=(3,))\n\n x = array_ops.ones((50, 3))\n y = array_ops.zeros((50, 2))\n dataset = dataset_ops.Dataset.from_tensor_slices((x, y)).batch(10)\n expected_log = r'(.*- loss:.*- my_acc:.*)+'\n\n with self.captureWritesToStream(sys.stdout) as printed:\n model.fit(dataset, epochs=2, steps_per_epoch=10)\n self.assertRegexpMatches(printed.contents(), expected_log)\n\n @keras_parameterized.run_with_all_model_types(exclude_models='functional')\n @keras_parameterized.run_all_keras_modes\n def test_progbar_logging_deferred_model_build(self):\n model = self._get_model()\n self.assertFalse(model.built)\n\n x = array_ops.ones((50, 3))\n y = array_ops.zeros((50, 2))\n dataset = dataset_ops.Dataset.from_tensor_slices((x, y)).batch(10)\n expected_log = r'(.*- loss:.*- my_acc:.*)+'\n\n with self.captureWritesToStream(sys.stdout) as printed:\n model.fit(dataset, epochs=2, steps_per_epoch=10)\n self.assertRegexpMatches(printed.contents(), expected_log)\n\n @keras_parameterized.run_with_all_model_types\n def test_ModelCheckpoint(self):\n if h5py is None:\n return # Skip test if models cannot be saved.\n\n layers = [\n keras.layers.Dense(NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu'),\n keras.layers.Dense(NUM_CLASSES, activation='softmax')\n ]\n model = testing_utils.get_model_from_layers(layers, input_shape=(10,))\n model.compile(\n loss='categorical_crossentropy', optimizer='rmsprop', metrics=['acc'])\n\n temp_dir = self.get_temp_dir()\n self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True)\n\n filepath = os.path.join(temp_dir, 'checkpoint.h5')\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 y_test = keras.utils.to_categorical(y_test)\n y_train = keras.utils.to_categorical(y_train)\n # case 1\n monitor = 'val_loss'\n save_best_only = False\n mode = 'auto'\n\n model = keras.models.Sequential()\n model.add(\n keras.layers.Dense(\n NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu'))\n model.add(keras.layers.Dense(NUM_CLASSES, activation='softmax'))\n model.compile(\n loss='categorical_crossentropy', optimizer='rmsprop', metrics=['acc'])\n\n cbks = [\n keras.callbacks.ModelCheckpoint(\n filepath,\n monitor=monitor,\n save_best_only=save_best_only,\n mode=mode)\n ]\n model.fit(\n x_train,\n y_train,\n batch_size=BATCH_SIZE,\n validation_data=(x_test, y_test),\n callbacks=cbks,\n epochs=1,\n verbose=0)\n assert os.path.exists(filepath)\n os.remove(filepath)\n\n # case 2\n mode = 'min'\n cbks = [\n keras.callbacks.ModelCheckpoint(\n filepath,\n monitor=monitor,\n save_best_only=save_best_only,\n mode=mode)\n ]\n model.fit(\n x_train,\n y_train,\n batch_size=BATCH_SIZE,\n validation_data=(x_test, y_test),\n callbacks=cbks,\n epochs=1,\n verbose=0)\n assert os.path.exists(filepath)\n os.remove(filepath)\n\n # case 3\n mode = 'max'\n monitor = 'val_acc'\n cbks = [\n keras.callbacks.ModelCheckpoint(\n filepath,\n monitor=monitor,\n save_best_only=save_best_only,\n mode=mode)\n ]\n model.fit(\n x_train,\n y_train,\n batch_size=BATCH_SIZE,\n validation_data=(x_test, y_test),\n callbacks=cbks,\n epochs=1,\n verbose=0)\n assert os.path.exists(filepath)\n os.remove(filepath)\n\n # case 4\n save_best_only = True\n cbks = [\n keras.callbacks.ModelCheckpoint(\n filepath,\n monitor=monitor,\n save_best_only=save_best_only,\n mode=mode)\n ]\n model.fit(\n x_train,\n y_train,\n batch_size=BATCH_SIZE,\n validation_data=(x_test, y_test),\n callbacks=cbks,\n epochs=1,\n verbose=0)\n assert os.path.exists(filepath)\n os.remove(filepath)\n\n # Case: metric not available.\n cbks = [\n keras.callbacks.ModelCheckpoint(\n filepath,\n monitor='unknown',\n save_best_only=True)\n ]\n model.fit(\n x_train,\n y_train,\n batch_size=BATCH_SIZE,\n validation_data=(x_test, y_test),\n callbacks=cbks,\n epochs=1,\n verbose=0)\n # File won't be written.\n assert not os.path.exists(filepath)\n\n # case 5\n save_best_only = False\n period = 2\n mode = 'auto'\n\n filepath = os.path.join(temp_dir, 'checkpoint.{epoch:02d}.h5')\n cbks = [\n keras.callbacks.ModelCheckpoint(\n filepath,\n monitor=monitor,\n save_best_only=save_best_only,\n mode=mode,\n period=period)\n ]\n model.fit(\n x_train,\n y_train,\n batch_size=BATCH_SIZE,\n validation_data=(x_test, y_test),\n callbacks=cbks,\n epochs=4,\n verbose=1)\n assert os.path.exists(filepath.format(epoch=2))\n assert os.path.exists(filepath.format(epoch=4))\n os.remove(filepath.format(epoch=2))\n os.remove(filepath.format(epoch=4))\n assert not os.path.exists(filepath.format(epoch=1))\n assert not os.path.exists(filepath.format(epoch=3))\n\n # Invalid use: this will raise a warning but not an Exception.\n keras.callbacks.ModelCheckpoint(\n filepath,\n monitor=monitor,\n save_best_only=save_best_only,\n mode='unknown')\n\n # Case 6: `ModelCheckpoint` with a combination of `save_freq` and `period`.\n # Though `period` is deprecated, we're testing it for\n # backward-compatibility.\n filepath = os.path.join(temp_dir, 'checkpoint.epoch{epoch:02d}.h5')\n cbks = [\n keras.callbacks.ModelCheckpoint(\n filepath, monitor=monitor, mode=mode, save_freq='epoch', period=5)\n ]\n assert not os.path.exists(filepath.format(epoch=0))\n assert not os.path.exists(filepath.format(epoch=5))\n model.fit(\n x_train,\n y_train,\n batch_size=2,\n validation_data=(x_test, y_test),\n callbacks=cbks,\n epochs=10,\n verbose=1)\n assert not os.path.exists(filepath.format(epoch=1))\n assert not os.path.exists(filepath.format(epoch=2))\n assert not os.path.exists(filepath.format(epoch=3))\n assert not os.path.exists(filepath.format(epoch=4))\n assert os.path.exists(filepath.format(epoch=5))\n assert not os.path.exists(filepath.format(epoch=6))\n assert os.path.exists(filepath.format(epoch=10))\n os.remove(filepath.format(epoch=5))\n os.remove(filepath.format(epoch=10))\n\n # Case 7: `ModelCheckpoint` with an integer `save_freq`\n filepath = os.path.join(temp_dir, 'checkpoint.epoch{epoch:02d}.h5')\n cbks = [\n keras.callbacks.ModelCheckpoint(\n filepath,\n monitor=monitor,\n save_best_only=save_best_only,\n mode=mode,\n save_freq=30,\n period=100) # The period should be ignored (this test tests this).\n ]\n assert not os.path.exists(filepath.format(epoch=3))\n model.fit(\n x_train,\n y_train,\n batch_size=2,\n validation_data=(x_test, y_test),\n callbacks=cbks,\n epochs=10,\n verbose=1)\n assert not os.path.exists(filepath.format(epoch=1))\n assert not os.path.exists(filepath.format(epoch=2))\n assert os.path.exists(filepath.format(epoch=3))\n assert not os.path.exists(filepath.format(epoch=4))\n assert not os.path.exists(filepath.format(epoch=5))\n assert os.path.exists(filepath.format(epoch=6))\n assert not os.path.exists(filepath.format(epoch=7))\n assert not os.path.exists(filepath.format(epoch=8))\n assert os.path.exists(filepath.format(epoch=9))\n os.remove(filepath.format(epoch=3))\n os.remove(filepath.format(epoch=6))\n os.remove(filepath.format(epoch=9))\n\n # Case 8: `ModelCheckpoint` with valid and invalid save_freq argument.\n with self.assertRaisesRegexp(ValueError, 'Unrecognized save_freq'):\n keras.callbacks.ModelCheckpoint(\n filepath,\n monitor=monitor,\n save_best_only=save_best_only,\n mode=mode,\n save_freq='invalid_save_freq')\n # The following should not raise ValueError.\n keras.callbacks.ModelCheckpoint(\n filepath,\n monitor=monitor,\n save_best_only=save_best_only,\n mode=mode,\n save_freq='epoch')\n keras.callbacks.ModelCheckpoint(\n filepath,\n monitor=monitor,\n save_best_only=save_best_only,\n mode=mode,\n save_freq=3)\n\n def _run_load_weights_on_restart_test_common_iterations(self):\n\n def get_input_datasets():\n # Simple training input.\n train_input = [[1]] * 16\n train_label = [[0]] * 16\n ds = dataset_ops.Dataset.from_tensor_slices((train_input, train_label))\n return ds.batch(8, drop_remainder=True)\n\n class Bias(base_layer.Layer):\n\n def build(self, input_shape):\n self.bias = self.add_variable('bias', (1,), initializer='zeros')\n\n def call(self, inputs):\n return inputs + self.bias\n\n # Very simple bias model to eliminate randomness.\n optimizer = gradient_descent.SGD(0.1)\n model = sequential.Sequential()\n model.add(Bias(input_shape=(1,)))\n model.compile(loss='mae', optimizer=optimizer, metrics=['mae'])\n train_ds = get_input_datasets()\n\n filepath = os.path.join(self.get_temp_dir(), 'checkpoint.h5')\n\n # The filepath shouldn't exist at the beginning.\n self.assertFalse(os.path.exists(filepath))\n model.fit(\n train_ds,\n epochs=3,\n callbacks=[\n keras.callbacks.ModelCheckpoint(\n filepath=filepath, save_weights_only=True)\n ])\n\n # The filepath should exist after fitting with callback.\n self.assertTrue(os.path.exists(filepath))\n model.fit(train_ds, epochs=1)\n weights_after_one_more_epoch = model.get_weights()\n\n # The filepath should continue to exist after fitting without callback.\n self.assertTrue(os.path.exists(filepath))\n\n return model, train_ds, filepath, weights_after_one_more_epoch\n\n @staticmethod\n def get_ModelCheckpoint_load_weights_on_restart_true_test(save_weights_only):\n\n def func(self):\n (model, train_ds, filepath, weights_after_one_more_epoch\n ) = self._run_load_weights_on_restart_test_common_iterations()\n\n model.fit(\n train_ds,\n epochs=1,\n callbacks=[\n keras.callbacks.ModelCheckpoint(\n filepath=filepath,\n save_weights_only=save_weights_only,\n load_weights_on_restart=True)\n ])\n weights_after_model_restoring_and_one_more_epoch = model.get_weights()\n\n # Asserting the weights one epoch after initial fitting and another epoch\n # after that are closed, if a ModelCheckpoint with\n # load_weights_on_restart=True is given (so the model is restored at the\n # beginning of training).\n self.assertAllClose(weights_after_one_more_epoch,\n weights_after_model_restoring_and_one_more_epoch)\n\n return func\n\n @staticmethod\n def get_ModelCheckpoint_load_weights_on_restart_false_test(save_weights_only):\n\n def func(self):\n (model, train_ds, filepath, weights_after_one_more_epoch\n ) = self._run_load_weights_on_restart_test_common_iterations()\n\n model.fit(\n train_ds,\n epochs=1,\n callbacks=[\n keras.callbacks.ModelCheckpoint(\n filepath=filepath, save_weights_only=save_weights_only)\n ])\n weights_after_model_restoring_and_one_more_epoch = model.get_weights()\n\n # Asserting the weights one epoch after initial fitting and another epoch\n # after that are different, if a ModelCheckpoint with\n # load_weights_on_restart=False is given (so the model is not restored at\n # the beginning of training).\n self.assertNotAllClose(weights_after_one_more_epoch,\n weights_after_model_restoring_and_one_more_epoch)\n\n return func\n\n test_model_checkpoint_load_weights_on_restart_true_save_weights_only_true = \\\n get_ModelCheckpoint_load_weights_on_restart_true_test.__func__(True)\n\n test_model_checkpoint_load_weights_on_restart_true_save_weights_only_false = \\\n get_ModelCheckpoint_load_weights_on_restart_true_test.__func__(False)\n\n test_model_checkpoint_load_weights_on_restart_false_save_weights_only_true = \\\n get_ModelCheckpoint_load_weights_on_restart_false_test.__func__(True)\n\n test_model_checkpoint_load_weights_on_restart_false_save_weights_only_false \\\n = get_ModelCheckpoint_load_weights_on_restart_false_test.__func__(False)\n\n def test_ModelCheckpoint_override_if_file_exist(self):\n (model, train_ds, filepath,\n _) = self._run_load_weights_on_restart_test_common_iterations()\n\n model.load_weights(filepath)\n weights_before_additional_fit = model.get_weights()\n model.fit(\n train_ds,\n epochs=1,\n callbacks=[\n keras.callbacks.ModelCheckpoint(\n filepath=filepath, save_weights_only=True)\n ])\n model.load_weights(filepath)\n weights_after_additional_fit = model.get_weights()\n\n self.assertNotAllClose(weights_before_additional_fit,\n weights_after_additional_fit)\n\n def test_EarlyStopping(self):\n with self.cached_session():\n np.random.seed(123)\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 y_test = keras.utils.to_categorical(y_test)\n y_train = keras.utils.to_categorical(y_train)\n model = testing_utils.get_small_sequential_mlp(\n num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM)\n model.compile(\n loss='categorical_crossentropy', optimizer='rmsprop', metrics=['acc'])\n\n cases = [\n ('max', 'val_acc'),\n ('min', 'val_loss'),\n ('auto', 'val_acc'),\n ('auto', 'loss'),\n ('unknown', 'unknown')\n ]\n for mode, monitor in cases:\n patience = 0\n cbks = [\n keras.callbacks.EarlyStopping(\n patience=patience, monitor=monitor, mode=mode)\n ]\n model.fit(\n x_train,\n y_train,\n batch_size=BATCH_SIZE,\n validation_data=(x_test, y_test),\n callbacks=cbks,\n epochs=5,\n verbose=0)\n\n def test_EarlyStopping_reuse(self):\n with self.cached_session():\n np.random.seed(1337)\n patience = 3\n data = np.random.random((100, 1))\n labels = np.where(data > 0.5, 1, 0)\n model = keras.models.Sequential((keras.layers.Dense(\n 1, input_dim=1, activation='relu'), keras.layers.Dense(\n 1, activation='sigmoid'),))\n model.compile(\n optimizer='sgd', loss='binary_crossentropy', metrics=['accuracy'])\n weights = model.get_weights()\n\n stopper = keras.callbacks.EarlyStopping(monitor='acc', patience=patience)\n hist = model.fit(data, labels, callbacks=[stopper], verbose=0, epochs=20)\n assert len(hist.epoch) >= patience\n\n # This should allow training to go for at least `patience` epochs\n model.set_weights(weights)\n hist = model.fit(data, labels, callbacks=[stopper], verbose=0, epochs=20)\n assert len(hist.epoch) >= patience\n\n def test_EarlyStopping_with_baseline(self):\n with self.cached_session():\n np.random.seed(1337)\n baseline = 0.5\n (data, labels), _ = testing_utils.get_test_data(\n train_samples=100,\n test_samples=50,\n input_shape=(1,),\n num_classes=NUM_CLASSES)\n model = testing_utils.get_small_sequential_mlp(\n num_hidden=1, num_classes=1, input_dim=1)\n model.compile(\n optimizer='sgd', loss='binary_crossentropy', metrics=['acc'])\n\n stopper = keras.callbacks.EarlyStopping(monitor='acc',\n baseline=baseline)\n hist = model.fit(data, labels, callbacks=[stopper], verbose=0, epochs=20)\n assert len(hist.epoch) == 1\n\n patience = 3\n stopper = keras.callbacks.EarlyStopping(monitor='acc',\n patience=patience,\n baseline=baseline)\n hist = model.fit(data, labels, callbacks=[stopper], verbose=0, epochs=20)\n assert len(hist.epoch) >= patience\n\n def test_EarlyStopping_final_weights_when_restoring_model_weights(self):\n\n class DummyModel(object):\n\n def __init__(self):\n self.stop_training = False\n self.weights = -1\n\n def get_weights(self):\n return self.weights\n\n def set_weights(self, weights):\n self.weights = weights\n\n def set_weight_to_epoch(self, epoch):\n self.weights = epoch\n\n early_stop = keras.callbacks.EarlyStopping(monitor='val_loss',\n patience=2,\n restore_best_weights=True)\n early_stop.model = DummyModel()\n losses = [0.2, 0.15, 0.1, 0.11, 0.12]\n # The best configuration is in the epoch 2 (loss = 0.1000).\n epochs_trained = 0\n early_stop.on_train_begin()\n for epoch in range(len(losses)):\n epochs_trained += 1\n early_stop.model.set_weight_to_epoch(epoch=epoch)\n early_stop.on_epoch_end(epoch, logs={'val_loss': losses[epoch]})\n if early_stop.model.stop_training:\n break\n # The best configuration is in epoch 2 (loss = 0.1000),\n # and while patience = 2, we're restoring the best weights,\n # so we end up at the epoch with the best weights, i.e. epoch 2\n self.assertEqual(early_stop.model.get_weights(), 2)\n\n def test_RemoteMonitor(self):\n if requests is None:\n return\n\n monitor = keras.callbacks.RemoteMonitor()\n # This will raise a warning since the default address in unreachable:\n monitor.on_epoch_end(0, logs={'loss': 0.})\n\n def test_LearningRateScheduler(self):\n with self.cached_session():\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 y_test = keras.utils.to_categorical(y_test)\n y_train = keras.utils.to_categorical(y_train)\n model = testing_utils.get_small_sequential_mlp(\n num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM)\n model.compile(\n loss='categorical_crossentropy',\n optimizer='sgd',\n metrics=['accuracy'])\n\n cbks = [keras.callbacks.LearningRateScheduler(lambda x: 1. / (1. + x))]\n model.fit(\n x_train,\n y_train,\n batch_size=BATCH_SIZE,\n validation_data=(x_test, y_test),\n callbacks=cbks,\n epochs=5,\n verbose=0)\n assert (\n float(keras.backend.get_value(\n model.optimizer.lr)) - 0.2) < keras.backend.epsilon()\n\n cbks = [keras.callbacks.LearningRateScheduler(lambda x, lr: lr / 2)]\n model.compile(\n loss='categorical_crossentropy',\n optimizer='sgd',\n metrics=['accuracy'])\n model.fit(\n x_train,\n y_train,\n batch_size=BATCH_SIZE,\n validation_data=(x_test, y_test),\n callbacks=cbks,\n epochs=2,\n verbose=0)\n assert (\n float(keras.backend.get_value(\n model.optimizer.lr)) - 0.01 / 4) < keras.backend.epsilon()\n\n def test_ReduceLROnPlateau(self):\n with self.cached_session():\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 y_test = keras.utils.to_categorical(y_test)\n y_train = keras.utils.to_categorical(y_train)\n\n def make_model():\n random_seed.set_random_seed(1234)\n np.random.seed(1337)\n model = testing_utils.get_small_sequential_mlp(\n num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM)\n model.compile(\n loss='categorical_crossentropy',\n optimizer=keras.optimizers.SGD(lr=0.1),\n metrics=['accuracy'])\n return model\n\n # TODO(psv): Make sure the callback works correctly when min_delta is\n # set as 0. Test fails when the order of this callback and assertion is\n # interchanged.\n model = make_model()\n cbks = [\n keras.callbacks.ReduceLROnPlateau(\n monitor='val_loss',\n factor=0.1,\n min_delta=0,\n patience=1,\n cooldown=5)\n ]\n model.fit(\n x_train,\n y_train,\n batch_size=BATCH_SIZE,\n validation_data=(x_test, y_test),\n callbacks=cbks,\n epochs=2,\n verbose=0)\n self.assertAllClose(\n float(keras.backend.get_value(model.optimizer.lr)), 0.1, atol=1e-4)\n\n model = make_model()\n # This should reduce the LR after the first epoch (due to high epsilon).\n cbks = [\n keras.callbacks.ReduceLROnPlateau(\n monitor='val_loss',\n factor=0.1,\n min_delta=10,\n patience=1,\n cooldown=5)\n ]\n model.fit(\n x_train,\n y_train,\n batch_size=BATCH_SIZE,\n validation_data=(x_test, y_test),\n callbacks=cbks,\n epochs=2,\n verbose=2)\n self.assertAllClose(\n float(keras.backend.get_value(model.optimizer.lr)), 0.01, atol=1e-4)\n\n def test_ReduceLROnPlateau_patience(self):\n\n class DummyOptimizer(object):\n\n def __init__(self):\n self.lr = keras.backend.variable(1.0)\n\n class DummyModel(object):\n\n def __init__(self):\n self.optimizer = DummyOptimizer()\n\n reduce_on_plateau = keras.callbacks.ReduceLROnPlateau(\n monitor='val_loss', patience=2)\n reduce_on_plateau.model = DummyModel()\n\n losses = [0.0860, 0.1096, 0.1040]\n lrs = []\n\n for epoch in range(len(losses)):\n reduce_on_plateau.on_epoch_end(epoch, logs={'val_loss': losses[epoch]})\n lrs.append(keras.backend.get_value(reduce_on_plateau.model.optimizer.lr))\n\n # The learning rates should be 1.0 except the last one\n for lr in lrs[:-1]:\n self.assertEqual(lr, 1.0)\n self.assertLess(lrs[-1], 1.0)\n\n def test_ReduceLROnPlateau_backwards_compatibility(self):\n with test.mock.patch.object(logging, 'warning') as mock_log:\n reduce_on_plateau = keras.callbacks.ReduceLROnPlateau(epsilon=1e-13)\n self.assertRegexpMatches(\n str(mock_log.call_args), '`epsilon` argument is deprecated')\n self.assertFalse(hasattr(reduce_on_plateau, 'epsilon'))\n self.assertTrue(hasattr(reduce_on_plateau, 'min_delta'))\n self.assertEqual(reduce_on_plateau.min_delta, 1e-13)\n\n def test_CSVLogger(self):\n with self.cached_session():\n np.random.seed(1337)\n temp_dir = self.get_temp_dir()\n self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True)\n filepath = os.path.join(temp_dir, 'log.tsv')\n\n sep = '\\t'\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 y_test = keras.utils.to_categorical(y_test)\n y_train = keras.utils.to_categorical(y_train)\n\n def make_model():\n np.random.seed(1337)\n model = testing_utils.get_small_sequential_mlp(\n num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM)\n model.compile(\n loss='categorical_crossentropy',\n optimizer=keras.optimizers.SGD(lr=0.1),\n metrics=['accuracy'])\n return model\n\n # case 1, create new file with defined separator\n model = make_model()\n cbks = [keras.callbacks.CSVLogger(filepath, separator=sep)]\n model.fit(\n x_train,\n y_train,\n batch_size=BATCH_SIZE,\n validation_data=(x_test, y_test),\n callbacks=cbks,\n epochs=1,\n verbose=0)\n\n assert os.path.exists(filepath)\n with open(filepath) as csvfile:\n dialect = csv.Sniffer().sniff(csvfile.read())\n assert dialect.delimiter == sep\n del model\n del cbks\n\n # case 2, append data to existing file, skip header\n model = make_model()\n cbks = [keras.callbacks.CSVLogger(filepath, separator=sep, append=True)]\n model.fit(\n x_train,\n y_train,\n batch_size=BATCH_SIZE,\n validation_data=(x_test, y_test),\n callbacks=cbks,\n epochs=1,\n verbose=0)\n\n # case 3, reuse of CSVLogger object\n model.fit(\n x_train,\n y_train,\n batch_size=BATCH_SIZE,\n validation_data=(x_test, y_test),\n callbacks=cbks,\n epochs=2,\n verbose=0)\n\n with open(filepath) as csvfile:\n list_lines = csvfile.readlines()\n for line in list_lines:\n assert line.count(sep) == 4\n assert len(list_lines) == 5\n output = ' '.join(list_lines)\n assert len(re.findall('epoch', output)) == 1\n\n os.remove(filepath)\n\n def test_stop_training_csv(self):\n # Test that using the CSVLogger callback with the TerminateOnNaN callback\n # does not result in invalid CSVs.\n np.random.seed(1337)\n tmpdir = self.get_temp_dir()\n self.addCleanup(shutil.rmtree, tmpdir, ignore_errors=True)\n\n with self.cached_session():\n fp = os.path.join(tmpdir, 'test.csv')\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\n y_test = keras.utils.to_categorical(y_test)\n y_train = keras.utils.to_categorical(y_train)\n cbks = [keras.callbacks.TerminateOnNaN(), keras.callbacks.CSVLogger(fp)]\n model = keras.models.Sequential()\n for _ in range(5):\n model.add(keras.layers.Dense(2, input_dim=INPUT_DIM, activation='relu'))\n model.add(keras.layers.Dense(NUM_CLASSES, activation='linear'))\n model.compile(loss='mean_squared_error',\n optimizer='rmsprop')\n\n def data_generator():\n i = 0\n max_batch_index = len(x_train) // BATCH_SIZE\n tot = 0\n while 1:\n if tot > 3 * len(x_train):\n yield (np.ones([BATCH_SIZE, INPUT_DIM]) * np.nan,\n np.ones([BATCH_SIZE, NUM_CLASSES]) * np.nan)\n else:\n yield (x_train[i * BATCH_SIZE: (i + 1) * BATCH_SIZE],\n y_train[i * BATCH_SIZE: (i + 1) * BATCH_SIZE])\n i += 1\n tot += 1\n i %= max_batch_index\n\n history = model.fit_generator(data_generator(),\n len(x_train) // BATCH_SIZE,\n validation_data=(x_test, y_test),\n callbacks=cbks,\n epochs=20)\n loss = history.history['loss']\n assert len(loss) > 1\n assert loss[-1] == np.inf or np.isnan(loss[-1])\n\n values = []\n with open(fp) as f:\n for x in csv.reader(f):\n # In windows, due to \\r\\n line ends we may end up reading empty lines\n # after each line. Skip empty lines.\n if x:\n values.append(x)\n assert 'nan' in values[-1], 'The last epoch was not logged.'\n\n def test_TerminateOnNaN(self):\n with self.cached_session():\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\n y_test = keras.utils.to_categorical(y_test)\n y_train = keras.utils.to_categorical(y_train)\n cbks = [keras.callbacks.TerminateOnNaN()]\n model = keras.models.Sequential()\n initializer = keras.initializers.Constant(value=1e5)\n for _ in range(5):\n model.add(\n keras.layers.Dense(\n 2,\n input_dim=INPUT_DIM,\n activation='relu',\n kernel_initializer=initializer))\n model.add(keras.layers.Dense(NUM_CLASSES))\n model.compile(loss='mean_squared_error', optimizer='rmsprop')\n\n history = model.fit(\n x_train,\n y_train,\n batch_size=BATCH_SIZE,\n validation_data=(x_test, y_test),\n callbacks=cbks,\n epochs=20)\n loss = history.history['loss']\n assert len(loss) == 1\n assert loss[0] == np.inf\n\n @unittest.skipIf(\n os.name == 'nt',\n 'use_multiprocessing=True does not work on windows properly.')\n def test_LambdaCallback(self):\n with self.cached_session():\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 y_test = keras.utils.to_categorical(y_test)\n y_train = keras.utils.to_categorical(y_train)\n model = keras.models.Sequential()\n model.add(\n keras.layers.Dense(\n NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu'))\n model.add(keras.layers.Dense(NUM_CLASSES, activation='softmax'))\n model.compile(\n loss='categorical_crossentropy',\n optimizer='sgd',\n metrics=['accuracy'])\n\n # Start an arbitrary process that should run during model\n # training and be terminated after training has completed.\n e = threading.Event()\n\n def target():\n e.wait()\n\n t = threading.Thread(target=target)\n t.start()\n cleanup_callback = keras.callbacks.LambdaCallback(\n on_train_end=lambda logs: e.set())\n\n cbks = [cleanup_callback]\n model.fit(\n x_train,\n y_train,\n batch_size=BATCH_SIZE,\n validation_data=(x_test, y_test),\n callbacks=cbks,\n epochs=5,\n verbose=0)\n t.join()\n assert not t.is_alive()\n\n def test_RemoteMonitorWithJsonPayload(self):\n if requests is None:\n self.skipTest('`requests` required to run this test')\n with self.cached_session():\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 y_test = keras.utils.np_utils.to_categorical(y_test)\n y_train = keras.utils.np_utils.to_categorical(y_train)\n model = keras.models.Sequential()\n model.add(\n keras.layers.Dense(\n NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu'))\n model.add(keras.layers.Dense(NUM_CLASSES, activation='softmax'))\n model.compile(\n loss='categorical_crossentropy',\n optimizer='rmsprop',\n metrics=['accuracy'])\n cbks = [keras.callbacks.RemoteMonitor(send_as_json=True)]\n\n with test.mock.patch.object(requests, 'post'):\n model.fit(\n x_train,\n y_train,\n batch_size=BATCH_SIZE,\n validation_data=(x_test, y_test),\n callbacks=cbks,\n epochs=1)\n\n\n# A summary that was emitted during a test. Fields:\n# logdir: str. The logdir of the FileWriter to which the summary was\n# written.\n# tag: str. The name of the summary.\n_ObservedSummary = collections.namedtuple('_ObservedSummary', ('logdir', 'tag'))\n\n\nclass _SummaryFile(object):\n \"\"\"A record of summary tags and the files to which they were written.\n\n Fields `scalars`, `images`, `histograms`, and `tensors` are sets\n containing `_ObservedSummary` values.\n \"\"\"\n\n def __init__(self):\n self.scalars = set()\n self.images = set()\n self.histograms = set()\n self.tensors = set()\n\n\ndef list_summaries(logdir):\n \"\"\"Read all summaries under the logdir into a `_SummaryFile`.\n\n Args:\n logdir: A path to a directory that contains zero or more event\n files, either as direct children or in transitive subdirectories.\n Summaries in these events must only contain old-style scalars,\n images, and histograms. Non-summary events, like `graph_def`s, are\n ignored.\n\n Returns:\n A `_SummaryFile` object reflecting all summaries written to any\n event files in the logdir or any of its descendant directories.\n\n Raises:\n ValueError: If an event file contains an summary of unexpected kind.\n \"\"\"\n result = _SummaryFile()\n for (dirpath, dirnames, filenames) in os.walk(logdir):\n del dirnames # unused\n for filename in filenames:\n if not filename.startswith('events.out.'):\n continue\n path = os.path.join(dirpath, filename)\n for event in summary_iterator.summary_iterator(path):\n if not event.summary: # (e.g., it's a `graph_def` event)\n continue\n for value in event.summary.value:\n tag = value.tag\n # Case on the `value` rather than the summary metadata because\n # the Keras callback uses `summary_ops_v2` to emit old-style\n # summaries. See b/124535134.\n kind = value.WhichOneof('value')\n container = {\n 'simple_value': result.scalars,\n 'image': result.images,\n 'histo': result.histograms,\n 'tensor': result.tensors,\n }.get(kind)\n if container is None:\n raise ValueError(\n 'Unexpected summary kind %r in event file %s:\\n%r'\n % (kind, path, event))\n container.add(_ObservedSummary(logdir=dirpath, tag=tag))\n return result\n\n\n@keras_parameterized.run_with_all_model_types\n@keras_parameterized.run_all_keras_modes(always_skip_v1=True)\nclass TestTensorBoardV2(keras_parameterized.TestCase):\n\n def setUp(self):\n super(TestTensorBoardV2, self).setUp()\n self.logdir = os.path.join(self.get_temp_dir(), 'tb')\n self.train_dir = os.path.join(self.logdir, 'train')\n self.validation_dir = os.path.join(self.logdir, 'validation')\n\n def _get_model(self):\n layers = [\n keras.layers.Conv2D(8, (3, 3)),\n keras.layers.Flatten(),\n keras.layers.Dense(1)\n ]\n model = testing_utils.get_model_from_layers(layers, input_shape=(10, 10, 1))\n model.compile('sgd', 'mse', run_eagerly=testing_utils.should_run_eagerly())\n return model\n\n def test_TensorBoard_default_logdir(self):\n \"\"\"Regression test for cross-platform pathsep in default logdir.\"\"\"\n os.chdir(self.get_temp_dir())\n\n model = self._get_model()\n x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))\n tb_cbk = keras.callbacks.TensorBoard() # no logdir specified\n\n model.fit(\n x,\n y,\n batch_size=2,\n epochs=2,\n validation_data=(x, y),\n callbacks=[tb_cbk])\n\n summary_file = list_summaries(logdir='.')\n train_dir = os.path.join('.', 'logs', 'train')\n validation_dir = os.path.join('.', 'logs', 'validation')\n self.assertEqual(\n summary_file.scalars, {\n _ObservedSummary(logdir=train_dir, tag='epoch_loss'),\n _ObservedSummary(logdir=validation_dir, tag='epoch_loss'),\n })\n\n def test_TensorBoard_basic(self):\n model = self._get_model()\n x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))\n tb_cbk = keras.callbacks.TensorBoard(self.logdir)\n\n model.fit(\n x,\n y,\n batch_size=2,\n epochs=2,\n validation_data=(x, y),\n callbacks=[tb_cbk])\n\n summary_file = list_summaries(self.logdir)\n self.assertEqual(\n summary_file.scalars, {\n _ObservedSummary(logdir=self.train_dir, tag='epoch_loss'),\n _ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'),\n })\n\n def test_TensorBoard_across_invocations(self):\n \"\"\"Regression test for summary writer resource use-after-free.\n\n See: <https://github.com/tensorflow/tensorflow/issues/25707>\n \"\"\"\n model = self._get_model()\n x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))\n tb_cbk = keras.callbacks.TensorBoard(self.logdir)\n\n for _ in (1, 2):\n model.fit(\n x,\n y,\n batch_size=2,\n epochs=2,\n validation_data=(x, y),\n callbacks=[tb_cbk])\n\n summary_file = list_summaries(self.logdir)\n self.assertEqual(\n summary_file.scalars, {\n _ObservedSummary(logdir=self.train_dir, tag='epoch_loss'),\n _ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'),\n })\n\n def test_TensorBoard_no_spurious_event_files(self):\n model = self._get_model()\n x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))\n tb_cbk = keras.callbacks.TensorBoard(self.logdir)\n\n model.fit(\n x,\n y,\n batch_size=2,\n epochs=2,\n callbacks=[tb_cbk])\n\n events_file_run_basenames = set()\n for (dirpath, dirnames, filenames) in os.walk(self.logdir):\n del dirnames # unused\n if any(fn.startswith('events.out.') for fn in filenames):\n events_file_run_basenames.add(os.path.basename(dirpath))\n self.assertEqual(events_file_run_basenames, {'train'})\n\n def test_TensorBoard_batch_metrics(self):\n model = self._get_model()\n x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))\n tb_cbk = keras.callbacks.TensorBoard(self.logdir, update_freq=1)\n\n model.fit(\n x,\n y,\n batch_size=2,\n epochs=2,\n validation_data=(x, y),\n callbacks=[tb_cbk])\n\n summary_file = list_summaries(self.logdir)\n self.assertEqual(\n summary_file.scalars,\n {\n _ObservedSummary(logdir=self.train_dir, tag='batch_loss'),\n _ObservedSummary(logdir=self.train_dir, tag='epoch_loss'),\n _ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'),\n },\n )\n\n def test_TensorBoard_weight_histograms(self):\n model = self._get_model()\n x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))\n tb_cbk = keras.callbacks.TensorBoard(self.logdir, histogram_freq=1)\n model_type = testing_utils.get_model_type()\n\n model.fit(\n x,\n y,\n batch_size=2,\n epochs=2,\n validation_data=(x, y),\n callbacks=[tb_cbk])\n summary_file = list_summaries(self.logdir)\n\n self.assertEqual(\n summary_file.scalars,\n {\n _ObservedSummary(logdir=self.train_dir, tag='epoch_loss'),\n _ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'),\n },\n )\n self.assertEqual(\n self._strip_layer_names(summary_file.histograms, model_type),\n {\n _ObservedSummary(logdir=self.train_dir, tag='bias_0'),\n _ObservedSummary(logdir=self.train_dir, tag='kernel_0'),\n },\n )\n\n def test_TensorBoard_weight_images(self):\n model = self._get_model()\n x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))\n tb_cbk = keras.callbacks.TensorBoard(\n self.logdir, histogram_freq=1, write_images=True)\n model_type = testing_utils.get_model_type()\n\n model.fit(\n x,\n y,\n batch_size=2,\n epochs=2,\n validation_data=(x, y),\n callbacks=[tb_cbk])\n summary_file = list_summaries(self.logdir)\n\n self.assertEqual(\n summary_file.scalars,\n {\n _ObservedSummary(logdir=self.train_dir, tag='epoch_loss'),\n _ObservedSummary(logdir=self.validation_dir, tag='epoch_loss'),\n },\n )\n self.assertEqual(\n self._strip_layer_names(summary_file.histograms, model_type),\n {\n _ObservedSummary(logdir=self.train_dir, tag='bias_0'),\n _ObservedSummary(logdir=self.train_dir, tag='kernel_0'),\n },\n )\n self.assertEqual(\n self._strip_layer_names(summary_file.images, model_type),\n {\n _ObservedSummary(logdir=self.train_dir, tag='bias_0/image/0'),\n _ObservedSummary(logdir=self.train_dir, tag='kernel_0/image/0'),\n _ObservedSummary(logdir=self.train_dir, tag='kernel_0/image/1'),\n _ObservedSummary(logdir=self.train_dir, tag='kernel_0/image/2'),\n },\n )\n\n def _strip_layer_names(self, summaries, model_type):\n \"\"\"Deduplicate summary names modulo layer prefix.\n\n This removes the first slash-component of each tag name: for\n instance, \"foo/bar/baz\" becomes \"bar/baz\".\n\n Args:\n summaries: A `set` of `_ObservedSummary` values.\n model_type: The model type currently being tested.\n\n Returns:\n A new `set` of `_ObservedSummary` values with layer prefixes\n removed.\n \"\"\"\n result = set()\n for summary in summaries:\n if '/' not in summary.tag:\n raise ValueError('tag has no layer name: %r' % summary.tag)\n start_from = 2 if 'subclass' in model_type else 1\n new_tag = '/'.join(summary.tag.split('/')[start_from:])\n result.add(summary._replace(tag=new_tag))\n return result\n\n def test_TensorBoard_invalid_argument(self):\n with self.assertRaisesRegexp(ValueError, 'Unrecognized arguments'):\n keras.callbacks.TensorBoard(wwrite_images=True)\n\n\n# Note that this test specifies model_type explicitly.\n@keras_parameterized.run_all_keras_modes(always_skip_v1=True)\nclass TestTensorBoardV2NonParameterizedTest(keras_parameterized.TestCase):\n\n def setUp(self):\n super(TestTensorBoardV2NonParameterizedTest, self).setUp()\n self.logdir = os.path.join(self.get_temp_dir(), 'tb')\n self.train_dir = os.path.join(self.logdir, 'train')\n self.validation_dir = os.path.join(self.logdir, 'validation')\n\n def _get_seq_model(self):\n model = keras.models.Sequential([\n keras.layers.Conv2D(8, (3, 3), input_shape=(10, 10, 1)),\n keras.layers.Flatten(),\n keras.layers.Dense(1),\n ])\n model.compile('sgd', 'mse', run_eagerly=testing_utils.should_run_eagerly())\n return model\n\n def fitModelAndAssertKerasModelWritten(self, model):\n x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))\n tb_cbk = keras.callbacks.TensorBoard(self.logdir,\n write_graph=True,\n profile_batch=0)\n model.fit(\n x,\n y,\n batch_size=2,\n epochs=2,\n validation_data=(x, y),\n callbacks=[tb_cbk])\n summary_file = list_summaries(self.logdir)\n self.assertEqual(\n summary_file.tensors,\n {\n _ObservedSummary(logdir=self.train_dir, tag='keras'),\n },\n )\n\n def test_TensorBoard_writeSequentialModel_noInputShape(self):\n model = keras.models.Sequential([\n keras.layers.Conv2D(8, (3, 3)),\n keras.layers.Flatten(),\n keras.layers.Dense(1),\n ])\n model.compile('sgd', 'mse', run_eagerly=False)\n self.fitModelAndAssertKerasModelWritten(model)\n\n def test_TensorBoard_writeSequentialModel_withInputShape(self):\n model = keras.models.Sequential([\n keras.layers.Conv2D(8, (3, 3), input_shape=(10, 10, 1)),\n keras.layers.Flatten(),\n keras.layers.Dense(1),\n ])\n model.compile('sgd', 'mse', run_eagerly=False)\n self.fitModelAndAssertKerasModelWritten(model)\n\n def test_TensoriBoard_writeModel(self):\n inputs = keras.layers.Input([10, 10, 1])\n x = keras.layers.Conv2D(8, (3, 3), activation='relu')(inputs)\n x = keras.layers.Flatten()(x)\n x = keras.layers.Dense(1)(x)\n model = keras.models.Model(inputs=inputs, outputs=[x])\n model.compile('sgd', 'mse', run_eagerly=False)\n self.fitModelAndAssertKerasModelWritten(model)\n\n def test_TensorBoard_autoTrace(self):\n model = self._get_seq_model()\n x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))\n tb_cbk = keras.callbacks.TensorBoard(\n self.logdir, histogram_freq=1, profile_batch=1, write_graph=False)\n\n model.fit(\n x,\n y,\n batch_size=2,\n epochs=2,\n validation_data=(x, y),\n callbacks=[tb_cbk])\n summary_file = list_summaries(self.logdir)\n\n self.assertEqual(\n summary_file.tensors,\n {\n _ObservedSummary(logdir=self.train_dir, tag=u'batch_1'),\n },\n )\n\n def test_TensorBoard_autoTrace_tagNameWithBatchNum(self):\n model = self._get_seq_model()\n x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))\n tb_cbk = keras.callbacks.TensorBoard(\n self.logdir, histogram_freq=1, profile_batch=2, write_graph=False)\n\n model.fit(\n x,\n y,\n batch_size=2,\n epochs=2,\n validation_data=(x, y),\n callbacks=[tb_cbk])\n summary_file = list_summaries(self.logdir)\n\n self.assertEqual(\n summary_file.tensors,\n {\n _ObservedSummary(logdir=self.train_dir, tag=u'batch_2'),\n },\n )\n\n def test_TensorBoard_autoTrace_profile_batch_largerThanBatchCount(self):\n model = self._get_seq_model()\n x, y = np.ones((10, 10, 10, 1)), np.ones((10, 1))\n tb_cbk = keras.callbacks.TensorBoard(\n self.logdir, histogram_freq=1, profile_batch=10000, write_graph=False)\n\n model.fit(\n x,\n y,\n batch_size=2,\n epochs=2,\n validation_data=(x, y),\n callbacks=[tb_cbk])\n summary_file = list_summaries(self.logdir)\n\n # Enabled trace only on the 10000th batch, thus it should be empty.\n self.assertEmpty(summary_file.tensors)\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\"\"\"Kinesis Dataset.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.contrib.kinesis.python.ops import gen_dataset_ops\nfrom tensorflow.contrib.kinesis.python.ops import kinesis_op_loader # pylint: disable=unused-import\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\n\n\nclass KinesisDataset(dataset_ops.DatasetSource):\n \"\"\"A Kinesis Dataset that consumes the message.\n\n Kinesis is a managed service provided by AWS for data streaming.\n This dataset reads messages from Kinesis with each message presented\n as a `tf.string`.\n\n For example, we can construct and use the KinesisDataset as follows:\n ```python\n dataset = tf.contrib.kinesis.KinesisDataset(\n \"kinesis_stream_name\", read_indefinitely=False)\n next = dataset.make_one_shot_iterator().get_next()\n with tf.Session() as sess:\n while True:\n try:\n print(sess.run(nxt))\n except tf.errors.OutOfRangeError:\n break\n ```\n\n Since Kinesis is a data streaming service, data may not be available\n at the time it is being read. The argument `read_indefinitely` is\n used to control the behavior in this situation. If `read_indefinitely`\n is `True`, then `KinesisDataset` will keep retrying to retrieve data\n from the stream. If `read_indefinitely` is `False`, an `OutOfRangeError`\n is returned immediately instead.\n \"\"\"\n\n def __init__(self,\n stream,\n shard=\"\",\n read_indefinitely=True,\n interval=100000):\n \"\"\"Create a KinesisDataset.\n\n Args:\n stream: A `tf.string` tensor containing the name of the stream.\n shard: A `tf.string` tensor containing the id of the shard.\n read_indefinitely: If `True`, the Kinesis dataset will keep retry\n again on `EOF` after the `interval` period. If `False`, then\n the dataset will stop on `EOF`. The default value is `True`.\n interval: The interval for the Kinesis Client to wait before\n it tries to get records again (in millisecond).\n \"\"\"\n self._stream = ops.convert_to_tensor(\n stream, dtype=dtypes.string, name=\"stream\")\n self._shard = ops.convert_to_tensor(\n shard, dtype=dtypes.string, name=\"shard\")\n self._read_indefinitely = ops.convert_to_tensor(\n read_indefinitely, dtype=dtypes.bool, name=\"read_indefinitely\")\n self._interval = ops.convert_to_tensor(\n interval, dtype=dtypes.int64, name=\"interval\")\n super(KinesisDataset, self).__init__(self._as_variant_tensor())\n\n def _as_variant_tensor(self):\n return gen_dataset_ops.kinesis_dataset(\n self._stream, self._shard, self._read_indefinitely, self._interval)\n\n @property\n def output_classes(self):\n return ops.Tensor\n\n @property\n def output_shapes(self):\n return tensor_shape.scalar()\n\n @property\n def output_types(self):\n return dtypes.string\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# ==============================================================================\n\"\"\"Tests for wrap_py_func module.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.autograph.utils import py_func\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.platform import test\n\n\nclass PyFuncTest(test.TestCase):\n\n def test_wrap_py_func_simple(self):\n\n def test_fn(a, b, c):\n return a + b + c\n\n with self.cached_session() as sess:\n result = py_func.wrap_py_func(test_fn, dtypes.int64,\n (1, constant_op.constant(1), 1))\n self.assertEqual(3, sess.run(result))\n result = py_func.wrap_py_func(test_fn, dtypes.int64, (1, 1, 1))\n self.assertEqual(3, sess.run(result))\n result = py_func.wrap_py_func(\n test_fn, dtypes.int64,\n (constant_op.constant(1), 1, constant_op.constant(1)))\n self.assertEqual(3, sess.run(result))\n\n def test_wrap_py_func_complex_args(self):\n\n class TestClass(object):\n\n def __init__(self):\n self.foo = 5\n\n def test_fn(a, b):\n return a * b.foo\n\n with self.cached_session() as sess:\n result = py_func.wrap_py_func(test_fn, dtypes.int64, (7, TestClass()))\n self.assertEqual(35, sess.run(result))\n result = py_func.wrap_py_func(test_fn, dtypes.int64,\n (constant_op.constant(7), TestClass()))\n self.assertEqual(35, sess.run(result))\n\n def test_wrap_py_func_kwargs(self):\n\n class TestClass(object):\n\n def __init__(self, foo):\n self.foo = foo\n\n def test_fn(a, b, c, d):\n return a * b.foo + c * d.foo\n\n with self.cached_session() as sess:\n result = py_func.wrap_py_func(test_fn, dtypes.int64, (7, TestClass(5)), {\n 'c': 11,\n 'd': TestClass(13)\n })\n self.assertEqual(178, sess.run(result))\n result = py_func.wrap_py_func(test_fn, dtypes.int64,\n (constant_op.constant(7), TestClass(5)), {\n 'c': constant_op.constant(11),\n 'd': TestClass(13)\n })\n self.assertEqual(178, sess.run(result))\n\n def test_wrap_py_func_dummy_return(self):\n\n side_counter = [0]\n\n def test_fn(_):\n side_counter[0] += 1\n\n with self.cached_session() as sess:\n result = py_func.wrap_py_func(test_fn, None, (5,), use_dummy_return=True)\n self.assertEqual(1, sess.run(result))\n self.assertEqual([1], side_counter)\n result = py_func.wrap_py_func(\n test_fn, None, (constant_op.constant(5),), use_dummy_return=True)\n self.assertEqual(1, sess.run(result))\n self.assertEqual([2], side_counter)\n\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\"\"\"Device function for replicated training.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport six\n\nfrom tensorflow.core.framework import node_def_pb2\nfrom tensorflow.python.framework import device as pydev\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.training import server_lib\nfrom tensorflow.python.util.tf_export import tf_export\n\n# This is a tuple of PS ops used by tf.estimator.Estimator which should work in\n# almost all of cases.\nSTANDARD_PS_OPS = (\"Variable\", \"VariableV2\", \"AutoReloadVariable\",\n \"MutableHashTable\", \"MutableHashTableV2\",\n \"MutableHashTableOfTensors\", \"MutableHashTableOfTensorsV2\",\n \"MutableDenseHashTable\", \"MutableDenseHashTableV2\",\n \"VarHandleOp\", \"BoostedTreesEnsembleResourceHandleOp\")\n\n\nclass _RoundRobinStrategy(object):\n \"\"\"Returns the next ps task index for placement in round-robin order.\n\n This class is not to be used directly by users. See instead\n `replica_device_setter()` below.\n \"\"\"\n\n def __init__(self, num_tasks):\n \"\"\"Create a new `_RoundRobinStrategy`.\n\n Args:\n num_tasks: Number of ps tasks to cycle among.\n \"\"\"\n self._num_tasks = num_tasks\n self._next_task = 0\n\n def __call__(self, unused_op):\n \"\"\"Choose a ps task index for the given `Operation`.\n\n Args:\n unused_op: An `Operation` to be placed on ps.\n\n Returns:\n The next ps task index to use for the `Operation`. Returns the next\n index, in the range `[offset, offset + num_tasks)`.\n \"\"\"\n task = self._next_task\n self._next_task = (self._next_task + 1) % self._num_tasks\n return task\n\n\nclass _ReplicaDeviceChooser(object):\n \"\"\"Class to choose devices for Ops in a replicated training setup.\n\n This class is not to be used directly by users. See instead\n `replica_device_setter()` below.\n \"\"\"\n\n def __init__(self, ps_tasks, ps_device, worker_device, merge_devices, ps_ops,\n ps_strategy):\n \"\"\"Create a new `_ReplicaDeviceChooser`.\n\n Args:\n ps_tasks: Number of tasks in the `ps` job.\n ps_device: String. Name of the `ps` job.\n worker_device: String. Name of the `worker` job.\n merge_devices: Boolean. Set to True to allow merging of device specs.\n ps_ops: List of strings representing `Operation` types that need to be\n placed on `ps` devices.\n ps_strategy: A callable invoked for every ps `Operation` (i.e. matched by\n `ps_ops`), that takes the `Operation` and returns the ps task index to\n use.\n \"\"\"\n self._ps_tasks = ps_tasks\n self._ps_device = ps_device\n self._worker_device = worker_device\n self._merge_devices = merge_devices\n self._ps_ops = ps_ops\n self._ps_strategy = ps_strategy\n\n def device_function(self, op):\n \"\"\"Choose a device for `op`.\n\n Args:\n op: an `Operation`.\n\n Returns:\n The device to use for the `Operation`.\n \"\"\"\n # If we don't return early here, either merge_devices is True, or op.device\n # is empty (in which case merging is a no-op). So we can always merge below.\n if not self._merge_devices and op.device:\n return op.device\n\n current_device = pydev.DeviceSpec.from_string(op.device or \"\")\n\n # The ps_device will be used for specified ops (ps_ops) whenever it is\n # present and ps_tasks is non-zero. However, its task number will only be\n # set (using ps_strategy) if there is a job field in ps_device that won't be\n # changed by the job field (if present) in current_device.\n node_def = op if isinstance(op, node_def_pb2.NodeDef) else op.node_def\n if self._ps_tasks and self._ps_device and node_def.op in self._ps_ops:\n ps_device = pydev.DeviceSpec.from_string(self._ps_device)\n\n current_job, ps_job = current_device.job, ps_device.job\n if ps_job and (not current_job or current_job == ps_job):\n ps_device = ps_device.replace(task=self._ps_strategy(op))\n\n ps_device = ps_device.make_merged_spec(current_device)\n return ps_device.to_string()\n\n worker_device = pydev.DeviceSpec.from_string(self._worker_device or \"\")\n worker_device = worker_device.make_merged_spec(current_device)\n return worker_device.to_string()\n\n\n@tf_export(\"train.replica_device_setter\")\ndef replica_device_setter(ps_tasks=0, ps_device=\"/job:ps\",\n worker_device=\"/job:worker\", merge_devices=True,\n cluster=None, ps_ops=None, ps_strategy=None):\n \"\"\"Return a `device function` to use when building a Graph for replicas.\n\n Device Functions are used in `with tf.device(device_function):` statement to\n automatically assign devices to `Operation` objects as they are constructed,\n Device constraints are added from the inner-most context first, working\n outwards. The merging behavior adds constraints to fields that are yet unset\n by a more inner context. Currently the fields are (job, task, cpu/gpu).\n\n If `cluster` is `None`, and `ps_tasks` is 0, the returned function is a no-op.\n Otherwise, the value of `ps_tasks` is derived from `cluster`.\n\n By default, only Variable ops are placed on ps tasks, and the placement\n strategy is round-robin over all ps tasks. A custom `ps_strategy` may be used\n to do more intelligent placement, such as\n `tf.contrib.training.GreedyLoadBalancingStrategy`.\n\n For example,\n\n ```python\n # To build a cluster with two ps jobs on hosts ps0 and ps1, and 3 worker\n # jobs on hosts worker0, worker1 and worker2.\n cluster_spec = {\n \"ps\": [\"ps0:2222\", \"ps1:2222\"],\n \"worker\": [\"worker0:2222\", \"worker1:2222\", \"worker2:2222\"]}\n with tf.device(tf.train.replica_device_setter(cluster=cluster_spec)):\n # Build your graph\n v1 = tf.Variable(...) # assigned to /job:ps/task:0\n v2 = tf.Variable(...) # assigned to /job:ps/task:1\n v3 = tf.Variable(...) # assigned to /job:ps/task:0\n # Run compute\n ```\n\n Args:\n ps_tasks: Number of tasks in the `ps` job. Ignored if `cluster` is\n provided.\n ps_device: String. Device of the `ps` job. If empty no `ps` job is used.\n Defaults to `ps`.\n worker_device: String. Device of the `worker` job. If empty no `worker`\n job is used.\n merge_devices: `Boolean`. If `True`, merges or only sets a device if the\n device constraint is completely unset. merges device specification rather\n than overriding them.\n cluster: `ClusterDef` proto or `ClusterSpec`.\n ps_ops: List of strings representing `Operation` types that need to be\n placed on `ps` devices. If `None`, defaults to `STANDARD_PS_OPS`.\n ps_strategy: A callable invoked for every ps `Operation` (i.e. matched by\n `ps_ops`), that takes the `Operation` and returns the ps task index to\n use. If `None`, defaults to a round-robin strategy across all `ps`\n devices.\n\n Returns:\n A function to pass to `tf.device()`.\n\n Raises:\n TypeError if `cluster` is not a dictionary or `ClusterDef` protocol buffer,\n or if `ps_strategy` is provided but not a callable.\n \"\"\"\n if cluster is not None:\n if isinstance(cluster, server_lib.ClusterSpec):\n cluster_spec = cluster.as_dict()\n else:\n cluster_spec = server_lib.ClusterSpec(cluster).as_dict()\n # Get ps_job_name from ps_device by stripping \"/job:\".\n ps_job_name = pydev.DeviceSpec.from_string(ps_device).job\n if ps_job_name not in cluster_spec or cluster_spec[ps_job_name] is None:\n return None\n ps_tasks = len(cluster_spec[ps_job_name])\n\n if ps_tasks == 0:\n return None\n\n if ps_ops is None:\n # TODO(sherrym): Variables in the LOCAL_VARIABLES collection should not be\n # placed in the parameter server.\n ps_ops = list(STANDARD_PS_OPS)\n\n if not merge_devices:\n logging.warning(\n \"DEPRECATION: It is recommended to set merge_devices=true in \"\n \"replica_device_setter\")\n if ps_strategy is None:\n ps_strategy = _RoundRobinStrategy(ps_tasks)\n if not six.callable(ps_strategy):\n raise TypeError(\"ps_strategy must be callable\")\n chooser = _ReplicaDeviceChooser(\n ps_tasks, ps_device, worker_device, merge_devices, ps_ops, ps_strategy)\n return chooser.device_function\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 DecodeRaw op from parsing_ops.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport gzip\nimport zlib\n\nfrom six import BytesIO\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import parsing_ops\nfrom tensorflow.python.platform import test\n\n\nclass DecodeCompressedOpTest(test.TestCase):\n\n def _compress(self, bytes_in, compression_type):\n if not compression_type:\n return bytes_in\n elif compression_type == \"ZLIB\":\n return zlib.compress(bytes_in)\n else:\n out = BytesIO()\n with gzip.GzipFile(fileobj=out, mode=\"wb\") as f:\n f.write(bytes_in)\n return out.getvalue()\n\n def testDecompress(self):\n for compression_type in [\"ZLIB\", \"GZIP\", \"\"]:\n with self.cached_session():\n in_bytes = array_ops.placeholder(dtypes.string, shape=[2])\n decompressed = parsing_ops.decode_compressed(\n in_bytes, compression_type=compression_type)\n self.assertEqual([2], decompressed.get_shape().as_list())\n\n result = decompressed.eval(\n feed_dict={in_bytes: [self._compress(b\"AaAA\", compression_type),\n self._compress(b\"bBbb\", compression_type)]})\n self.assertAllEqual([b\"AaAA\", b\"bBbb\"], result)\n\n def testDecompressWithRaw(self):\n for compression_type in [\"ZLIB\", \"GZIP\", \"\"]:\n with self.cached_session():\n in_bytes = array_ops.placeholder(dtypes.string, shape=[None])\n decompressed = parsing_ops.decode_compressed(\n in_bytes, compression_type=compression_type)\n decode = parsing_ops.decode_raw(decompressed, out_type=dtypes.int16)\n\n result = decode.eval(\n feed_dict={in_bytes: [self._compress(b\"AaBC\", compression_type)]})\n self.assertAllEqual(\n [[ord(\"A\") + ord(\"a\") * 256, ord(\"B\") + ord(\"C\") * 256]], result)\n\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\"\"\"Optimizer ops for use in layers and tf.learn.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport six\n\nfrom tensorflow.contrib import framework as contrib_framework\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import clip_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import variable_scope as vs\nfrom tensorflow.python.ops import variables as vars_\nfrom tensorflow.python.summary import summary\nfrom tensorflow.python.training import moving_averages\nfrom tensorflow.python.training import optimizer as optimizer_\nfrom tensorflow.python.training import training as train\n\nOPTIMIZER_CLS_NAMES = {\n \"Adagrad\": train.AdagradOptimizer,\n \"Adam\": train.AdamOptimizer,\n \"Ftrl\": train.FtrlOptimizer,\n \"Momentum\": lambda learning_rate: train.MomentumOptimizer(learning_rate, momentum=0.9), # pylint: disable=line-too-long\n \"RMSProp\": train.RMSPropOptimizer,\n \"SGD\": train.GradientDescentOptimizer,\n}\n\nOPTIMIZER_SUMMARIES = [\n \"learning_rate\",\n \"loss\",\n \"gradients\",\n \"gradient_norm\",\n \"global_gradient_norm\",\n]\n\n\ndef optimize_loss(loss,\n global_step,\n learning_rate,\n optimizer,\n gradient_noise_scale=None,\n gradient_multipliers=None,\n clip_gradients=None,\n learning_rate_decay_fn=None,\n update_ops=None,\n variables=None,\n name=None,\n summaries=None,\n colocate_gradients_with_ops=False,\n increment_global_step=True):\n \"\"\"Given loss and parameters for optimizer, returns a training op.\n\n Various ways of passing optimizers include:\n\n - by string specifying the name of the optimizer. See OPTIMIZER_CLS_NAMES\n for full list. E.g. `optimize_loss(..., optimizer='Adam')`.\n - by function taking learning rate `Tensor` as argument and returning an\n `Optimizer` instance. E.g. `optimize_loss(...,\n optimizer=lambda lr: tf.train.MomentumOptimizer(lr, momentum=0.5))`.\n Alternatively, if `learning_rate` is `None`, the function takes no\n arguments. E.g. `optimize_loss(..., learning_rate=None,\n optimizer=lambda: tf.train.MomentumOptimizer(0.5, momentum=0.5))`.\n - by a subclass of `Optimizer` having a single-argument constructor\n (the argument is the learning rate), such as AdamOptimizer or\n AdagradOptimizer. E.g. `optimize_loss(...,\n optimizer=tf.train.AdagradOptimizer)`.\n - by an instance of a subclass of `Optimizer`.\n E.g., `optimize_loss(..., optimizer=tf.train.AdagradOptimizer(0.5))`.\n\n Args:\n loss: Scalar `Tensor`.\n global_step: Scalar int `Tensor`, step counter to update on each step\n unless `increment_global_step` is `False`. If not supplied,\n it will be fetched from the default graph (see\n `tf.train.get_global_step` for details). If it has\n not been created, no step will be incremented with each weight\n update. `learning_rate_decay_fn` requires `global_step`.\n learning_rate: float or `Tensor`, magnitude of update per each training\n step. Can be `None`.\n optimizer: string, class or optimizer instance, used as trainer.\n string should be name of optimizer, like 'SGD',\n 'Adam', 'Adagrad'. Full list in OPTIMIZER_CLS_NAMES constant.\n class should be sub-class of `tf.Optimizer` that implements\n `compute_gradients` and `apply_gradients` functions.\n optimizer instance should be instantiation of `tf.Optimizer`\n sub-class and have `compute_gradients` and `apply_gradients`\n functions.\n gradient_noise_scale: float or None, adds 0-mean normal noise scaled by this\n value.\n gradient_multipliers: dict of variables or variable names to floats.\n If present, gradients for specified\n variables will be multiplied by given constant.\n clip_gradients: float, callable or `None`. If a float is provided, a global\n clipping is applied to prevent the norm of the gradient from exceeding\n this value. Alternatively, a callable can be provided, e.g.,\n `adaptive_clipping_fn()`. This callable takes a list of \n `(gradients, variables)` tuples and returns the same thing with the \n gradients modified.\n learning_rate_decay_fn: function, takes `learning_rate` and `global_step`\n `Tensor`s, returns `Tensor`.\n Can be used to implement any learning rate decay\n functions.\n For example: `tf.train.exponential_decay`.\n Ignored if `learning_rate` is not supplied.\n update_ops: list of update `Operation`s to execute at each step. If `None`,\n uses elements of UPDATE_OPS collection. The order of execution\n between `update_ops` and `loss` is non-deterministic.\n variables: list of variables to optimize or\n `None` to use all trainable variables.\n name: The name for this operation is used to scope operations and summaries.\n summaries: List of internal quantities to visualize on tensorboard. If not\n set, the loss, the learning rate, and the global norm of the\n gradients will be reported. The complete list of possible values\n is in OPTIMIZER_SUMMARIES.\n colocate_gradients_with_ops: If True, try colocating gradients with the\n corresponding op.\n increment_global_step: Whether to increment `global_step`. If your model\n calls `optimize_loss` multiple times per training step (e.g. to optimize\n different parts of the model), use this arg to avoid incrementing\n `global_step` more times than necessary.\n\n Returns:\n Training op.\n\n Raises:\n ValueError: if:\n * `loss` is an invalid type or shape.\n * `global_step` is an invalid type or shape.\n * `learning_rate` is an invalid type or value.\n * `optimizer` has the wrong type.\n * `clip_gradients` is neither float nor callable.\n * `learning_rate` and `learning_rate_decay_fn` are supplied, but no\n `global_step` is available.\n * `gradients` is empty.\n \"\"\"\n loss = ops.convert_to_tensor(loss)\n contrib_framework.assert_scalar(loss)\n if global_step is None:\n global_step = train.get_global_step()\n else:\n train.assert_global_step(global_step)\n with vs.variable_scope(name, \"OptimizeLoss\", [loss, global_step]):\n # Update ops take UPDATE_OPS collection if not provided.\n if update_ops is None:\n update_ops = set(ops.get_collection(ops.GraphKeys.UPDATE_OPS))\n # Make sure update ops are ran before computing loss.\n if update_ops:\n loss = control_flow_ops.with_dependencies(list(update_ops), loss)\n\n # Learning rate variable, with possible decay.\n lr = None\n if learning_rate is not None:\n if (isinstance(learning_rate, ops.Tensor) and\n learning_rate.get_shape().ndims == 0):\n lr = learning_rate\n elif isinstance(learning_rate, float):\n if learning_rate < 0.0:\n raise ValueError(\"Invalid learning_rate %s.\", learning_rate)\n lr = vs.get_variable(\n \"learning_rate\", [],\n trainable=False,\n initializer=init_ops.constant_initializer(learning_rate))\n else:\n raise ValueError(\"Learning rate should be 0d Tensor or float. \"\n \"Got %s of type %s\" % (str(learning_rate),\n str(type(learning_rate))))\n if summaries is None:\n summaries = [\"loss\", \"learning_rate\", \"global_gradient_norm\"]\n else:\n for summ in summaries:\n if summ not in OPTIMIZER_SUMMARIES:\n raise ValueError(\"Summaries should be one of [%s], you provided %s.\" %\n (\", \".join(OPTIMIZER_SUMMARIES), summ))\n if learning_rate is not None and learning_rate_decay_fn is not None:\n if global_step is None:\n raise ValueError(\"global_step is required for learning_rate_decay_fn.\")\n lr = learning_rate_decay_fn(lr, global_step)\n if \"learning_rate\" in summaries:\n summary.scalar(\"learning_rate\", lr)\n\n # Create optimizer, given specified parameters.\n if isinstance(optimizer, six.string_types):\n if lr is None:\n raise ValueError(\"Learning rate is None, but should be specified if \"\n \"optimizer is string (%s).\" % optimizer)\n if optimizer not in OPTIMIZER_CLS_NAMES:\n raise ValueError(\n \"Optimizer name should be one of [%s], you provided %s.\" %\n (\", \".join(OPTIMIZER_CLS_NAMES), optimizer))\n opt = OPTIMIZER_CLS_NAMES[optimizer](learning_rate=lr)\n elif (isinstance(optimizer, type) and\n issubclass(optimizer, optimizer_.Optimizer)):\n if lr is None:\n raise ValueError(\"Learning rate is None, but should be specified if \"\n \"optimizer is class (%s).\" % optimizer)\n opt = optimizer(learning_rate=lr)\n elif isinstance(optimizer, optimizer_.Optimizer):\n opt = optimizer\n elif callable(optimizer):\n if learning_rate is not None:\n opt = optimizer(lr)\n else:\n opt = optimizer()\n if not isinstance(opt, optimizer_.Optimizer):\n raise ValueError(\"Unrecognized optimizer: function should return \"\n \"subclass of Optimizer. Got %s.\" % str(opt))\n else:\n raise ValueError(\"Unrecognized optimizer: should be string, \"\n \"subclass of Optimizer, instance of \"\n \"subclass of Optimizer or function with one argument. \"\n \"Got %s.\" % str(optimizer))\n\n # All trainable variables, if specific variables are not specified.\n if variables is None:\n variables = vars_.trainable_variables()\n\n # Compute gradients.\n gradients = opt.compute_gradients(\n loss,\n variables,\n colocate_gradients_with_ops=colocate_gradients_with_ops)\n\n # Optionally add gradient noise.\n if gradient_noise_scale is not None:\n gradients = _add_scaled_noise_to_gradients(gradients,\n gradient_noise_scale)\n\n # Multiply some gradients.\n if gradient_multipliers is not None:\n gradients = _multiply_gradients(gradients, gradient_multipliers)\n if not gradients:\n raise ValueError(\n \"Empty list of (gradient, var) pairs encountered. This is most \"\n \"likely to be caused by an improper value of gradient_multipliers.\")\n\n if \"global_gradient_norm\" in summaries or \"gradient_norm\" in summaries:\n summary.scalar(\"global_norm/gradient_norm\",\n clip_ops.global_norm(list(zip(*gradients))[0]))\n\n # Optionally clip gradients by global norm.\n if isinstance(clip_gradients, float):\n gradients = _clip_gradients_by_norm(gradients, clip_gradients)\n elif callable(clip_gradients):\n gradients = clip_gradients(gradients)\n elif clip_gradients is not None:\n raise ValueError(\n \"Unknown type %s for clip_gradients\" % type(clip_gradients))\n\n # Add scalar summary for loss.\n if \"loss\" in summaries:\n summary.scalar(\"loss\", loss)\n\n # Add histograms for variables, gradients and gradient norms.\n for gradient, variable in gradients:\n if isinstance(gradient, ops.IndexedSlices):\n grad_values = gradient.values\n else:\n grad_values = gradient\n\n if grad_values is not None:\n var_name = variable.name.replace(\":\", \"_\")\n if \"gradients\" in summaries:\n summary.histogram(\"gradients/%s\" % var_name, grad_values)\n if \"gradient_norm\" in summaries:\n summary.scalar(\"gradient_norm/%s\" % var_name,\n clip_ops.global_norm([grad_values]))\n\n if clip_gradients is not None and (\"global_gradient_norm\" in summaries or\n \"gradient_norm\" in summaries):\n summary.scalar(\"global_norm/clipped_gradient_norm\",\n clip_ops.global_norm(list(zip(*gradients))[0]))\n\n # Create gradient updates.\n grad_updates = opt.apply_gradients(\n gradients,\n global_step=global_step if increment_global_step else None,\n name=\"train\")\n\n # Ensure the train_tensor computes grad_updates.\n train_tensor = control_flow_ops.with_dependencies([grad_updates], loss)\n\n return train_tensor\n\n\ndef _clip_gradients_by_norm(grads_and_vars, clip_gradients):\n \"\"\"Clips gradients by global norm.\"\"\"\n gradients, variables = zip(*grads_and_vars)\n clipped_gradients, _ = clip_ops.clip_by_global_norm(gradients, clip_gradients)\n return list(zip(clipped_gradients, variables))\n\n\ndef _adaptive_max_norm(norm, std_factor, decay, global_step, epsilon, name):\n \"\"\"Find max_norm given norm and previous average.\"\"\"\n with vs.variable_scope(name, \"AdaptiveMaxNorm\", [norm]):\n log_norm = math_ops.log(norm + epsilon)\n\n def moving_average(name, value, decay):\n moving_average_variable = vs.get_variable(\n name,\n shape=value.get_shape(),\n dtype=value.dtype,\n initializer=init_ops.zeros_initializer(),\n trainable=False)\n return moving_averages.assign_moving_average(\n moving_average_variable, value, decay, zero_debias=False)\n\n # quicker adaptation at the beginning\n if global_step is not None:\n n = math_ops.cast(global_step, dtypes.float32)\n decay = math_ops.minimum(decay, n / (n + 1.))\n\n # update averages\n mean = moving_average(\"mean\", log_norm, decay)\n sq_mean = moving_average(\"sq_mean\", math_ops.square(log_norm), decay)\n\n variance = sq_mean - math_ops.square(mean)\n std = math_ops.sqrt(math_ops.maximum(epsilon, variance))\n max_norms = math_ops.exp(mean + std_factor * std)\n return max_norms, mean\n\n\ndef adaptive_clipping_fn(std_factor=2.,\n decay=0.95,\n static_max_norm=None,\n global_step=None,\n report_summary=False,\n epsilon=1e-8,\n name=None):\n \"\"\"Adapt the clipping value using statistics on the norms.\n\n Implement adaptive gradient as presented in section 3.2.1 of\n https://arxiv.org/abs/1412.1602.\n\n Keeps a moving average of the mean and std of the log(norm) of the gradient.\n If the norm exceeds `exp(mean + std_factor*std)` then all gradients will be\n rescaled such that the global norm becomes `exp(mean)`.\n\n Args:\n std_factor: Python scaler (or tensor).\n `max_norm = exp(mean + std_factor*std)`\n decay: The smoothing factor of the moving averages.\n static_max_norm: If provided, will threshold the norm to this value as an\n extra safety.\n global_step: Optional global_step. If provided, `decay = decay*n/(n+1)`.\n This provides a quicker adaptation of the mean for the first steps.\n report_summary: If `True`, will add histogram summaries of the `max_norm`.\n epsilon: Small value chosen to avoid zero variance.\n name: The name for this operation is used to scope operations and summaries.\n\n Returns:\n A function for applying gradient clipping.\n \"\"\"\n\n def gradient_clipping(grads_and_vars):\n \"\"\"Internal function for adaptive clipping.\"\"\"\n grads, variables = zip(*grads_and_vars)\n\n norm = clip_ops.global_norm(grads)\n\n max_norm, log_mean = _adaptive_max_norm(norm, std_factor, decay,\n global_step, epsilon, name)\n\n # reports the max gradient norm for debugging\n if report_summary:\n summary.scalar(\"global_norm/adaptive_max_gradient_norm\", max_norm)\n\n # factor will be 1. if norm is smaller than max_norm\n factor = array_ops.where(norm < max_norm,\n array_ops.ones_like(norm),\n math_ops.exp(log_mean) / norm)\n\n if static_max_norm is not None:\n factor = math_ops.minimum(static_max_norm / norm, factor)\n\n # apply factor\n clipped_grads = []\n for grad in grads:\n if grad is None:\n clipped_grads.append(None)\n elif isinstance(grad, ops.IndexedSlices):\n clipped_grads.append(\n ops.IndexedSlices(grad.values * factor, grad.indices,\n grad.dense_shape))\n else:\n clipped_grads.append(grad * factor)\n\n return list(zip(clipped_grads, variables))\n\n return gradient_clipping\n\n\ndef _add_scaled_noise_to_gradients(grads_and_vars, gradient_noise_scale):\n \"\"\"Adds scaled noise from a 0-mean normal distribution to gradients.\"\"\"\n gradients, variables = zip(*grads_and_vars)\n noisy_gradients = []\n for gradient in gradients:\n if gradient is None:\n noisy_gradients.append(None)\n continue\n if isinstance(gradient, ops.IndexedSlices):\n gradient_shape = gradient.dense_shape\n else:\n gradient_shape = gradient.get_shape()\n noise = random_ops.truncated_normal(gradient_shape) * gradient_noise_scale\n noisy_gradients.append(gradient + noise)\n return list(zip(noisy_gradients, variables))\n\n\ndef _multiply_gradients(grads_and_vars, gradient_multipliers):\n \"\"\"Multiply specified gradients.\"\"\"\n multiplied_grads_and_vars = []\n for grad, var in grads_and_vars:\n if (grad is not None and\n (var in gradient_multipliers or var.name in gradient_multipliers)):\n key = var if var in gradient_multipliers else var.name\n multiplier = gradient_multipliers[key]\n if isinstance(grad, ops.IndexedSlices):\n grad_values = grad.values * multiplier\n grad = ops.IndexedSlices(grad_values, grad.indices, grad.dense_shape)\n else:\n grad *= math_ops.cast(multiplier, grad.dtype)\n multiplied_grads_and_vars.append((grad, var))\n return multiplied_grads_and_vars\n"
] | [
[
"tensorflow.python.eager.context.executing_eagerly",
"numpy.take",
"tensorflow.python.ops.gradients_impl.gradients",
"numpy.arange",
"tensorflow.python.platform.test.is_gpu_available",
"tensorflow.python.ops.array_ops.placeholder",
"tensorflow.python.ops.array_ops.gather",
"tensorflow.python.platform.test.main",
"numpy.random.randint",
"numpy.prod",
"tensorflow.python.ops.array_ops.ones",
"numpy.random.randn",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.ops.variables.global_variables_initializer",
"numpy.array",
"numpy.zeros",
"tensorflow.python.framework.constant_op.constant"
],
[
"tensorflow.python.ops.array_ops.slice",
"tensorflow.python.ops.linalg_ops_impl.eye",
"tensorflow.python.util.tf_export.tf_export",
"tensorflow.python.ops.array_ops.matrix_transpose",
"tensorflow.python.framework.dtypes.as_dtype",
"tensorflow.python.ops.array_ops.reshape",
"tensorflow.python.ops.array_ops.zeros",
"tensorflow.python.ops.math_ops.sign",
"tensorflow.python.ops.gen_linalg_ops.qr",
"tensorflow.python.ops.array_ops.ones",
"numpy.isscalar",
"tensorflow.python.ops.array_ops.diag_part",
"tensorflow.python.framework.constant_op.constant"
],
[
"tensorflow.python.ops.nn_ops.crelu",
"numpy.asarray",
"tensorflow.python.ops.array_ops.placeholder",
"tensorflow.python.ops.variables.Variable",
"numpy.zeros_like",
"tensorflow.python.ops.gradients_impl.gradients",
"numpy.exp",
"tensorflow.python.ops.nn_ops.leaky_relu",
"tensorflow.python.ops.nn_ops.selu",
"numpy.copy",
"tensorflow.python.platform.test.main",
"numpy.zeros",
"tensorflow.python.ops.math_ops.cast",
"tensorflow.python.ops.gradient_checker.compute_gradient_error",
"tensorflow.python.platform.test.is_gpu_available",
"tensorflow.python.ops.nn_ops.l2_loss",
"tensorflow.python.compat.compat.forward_compatibility_horizon",
"numpy.array",
"tensorflow.python.training.gradient_descent.GradientDescentOptimizer",
"numpy.maximum",
"tensorflow.python.ops.nn_ops.relu6",
"tensorflow.python.ops.nn_ops.elu",
"tensorflow.python.ops.random_ops.random_normal",
"tensorflow.python.ops.nn_ops.relu",
"tensorflow.python.ops.variables.global_variables_initializer",
"tensorflow.python.ops.random_ops.random_uniform",
"tensorflow.python.framework.constant_op.constant"
],
[
"tensorflow.python.ops.nn_ops.quantized_conv2d",
"tensorflow.python.platform.test.main",
"tensorflow.python.framework.constant_op.constant"
],
[
"tensorflow.python.data.ops.dataset_ops.Dataset.from_tensors",
"tensorflow.python.data.ops.dataset_ops.Dataset.from_tensor_slices",
"numpy.asarray",
"tensorflow.python.data.experimental.ops.interleave_ops._DirectedInterleaveDataset",
"tensorflow.python.data.experimental.ops.interleave_ops.choose_from_datasets",
"numpy.random.random_sample",
"tensorflow.python.platform.test.main",
"tensorflow.python.data.ops.dataset_ops.Dataset.range",
"tensorflow.python.framework.random_seed.set_random_seed",
"numpy.sum",
"numpy.zeros",
"numpy.random.randint"
],
[
"tensorflow.python.ops.gen_experimental_dataset_ops.experimental_indexed_dataset_materialize",
"tensorflow.python.ops.gen_experimental_dataset_ops.experimental_indexed_dataset_get",
"tensorflow.python.platform.test.main",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.ops.gen_experimental_dataset_ops.experimental_materialized_index_dataset_handle",
"tensorflow.python.data.experimental.ops.indexed_dataset_ops.IdentityIndexedDataset"
],
[
"tensorflow.python.distribute.distribution_strategy_context.in_cross_replica_context",
"tensorflow.python.ops.control_flow_ops.group",
"tensorflow.python.util.tf_export.keras_export",
"tensorflow.python.keras.mixed_precision.experimental.loss_scale.get",
"tensorflow.python.framework.smart_cond.smart_cond",
"tensorflow.python.distribute.distribution_strategy_context.get_replica_context"
],
[
"tensorflow.python.framework.test_util.run_in_graph_and_eager_modes",
"tensorflow.python.ops.variable_scope.EagerVariableStore",
"tensorflow.python.ops.math_ops.reduce_max",
"tensorflow.python.ops.variable_scope._get_default_variable_store",
"tensorflow.python.ops.array_ops.placeholder",
"tensorflow.python.ops.variables.trainable_variables",
"tensorflow.python.layers.core.Dropout",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.layers.core.Dense",
"tensorflow.python.layers.core.dense",
"tensorflow.python.framework.ops.get_collection",
"numpy.arange",
"tensorflow.python.ops.init_ops.ones_initializer",
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.variable_scope.variable_scope",
"tensorflow.python.ops.array_ops.ones",
"numpy.zeros",
"tensorflow.python.eager.context.eager_mode",
"tensorflow.python.layers.core.dropout",
"numpy.transpose",
"tensorflow.python.layers.core.flatten",
"tensorflow.python.ops.init_ops.zeros_initializer",
"numpy.ones",
"tensorflow.python.layers.core.Flatten",
"tensorflow.python.ops.variables.global_variables_initializer",
"tensorflow.python.ops.random_ops.random_uniform",
"tensorflow.python.ops.math_ops.reduce_sum",
"tensorflow.python.framework.constant_op.constant"
],
[
"tensorflow.python.training.learning_rate_decay.cosine_decay_restarts",
"tensorflow.python.ops.resource_variable_ops.ResourceVariable",
"tensorflow.python.training.learning_rate_decay.natural_exp_decay",
"tensorflow.python.training.learning_rate_decay.polynomial_decay",
"tensorflow.python.training.learning_rate_decay.exponential_decay",
"tensorflow.python.training.learning_rate_decay.piecewise_constant",
"tensorflow.python.ops.variables.VariableV1",
"tensorflow.python.platform.googletest.main",
"tensorflow.python.training.learning_rate_decay.cosine_decay",
"tensorflow.python.training.learning_rate_decay.inverse_time_decay",
"tensorflow.python.training.learning_rate_decay.linear_cosine_decay",
"tensorflow.python.ops.variables.global_variables_initializer",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.training.learning_rate_decay.noisy_linear_cosine_decay"
],
[
"tensorflow.python.keras.constraints.MaxNorm",
"tensorflow.python.keras.optimizers.Nadam",
"tensorflow.python.keras.backend.track_tf_optimizer",
"tensorflow.python.keras.layers.Dense",
"tensorflow.python.keras.optimizers.deserialize",
"tensorflow.python.keras.optimizers.SGD",
"tensorflow.python.keras.optimizers.Adam",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.keras.optimizers.Adagrad",
"tensorflow.python.keras.optimizers.serialize",
"tensorflow.python.platform.test.main",
"tensorflow.python.keras.utils.to_categorical",
"tensorflow.python.keras.models.Sequential",
"tensorflow.python.keras.backend.get_value",
"tensorflow.python.training.adam.AdamOptimizer",
"tensorflow.python.keras.optimizers.Adadelta",
"numpy.testing.assert_allclose",
"tensorflow.python.keras.optimizers.Adamax",
"tensorflow.python.keras.testing_utils.get_test_data",
"numpy.random.random",
"numpy.random.seed",
"tensorflow.python.framework.ops.Graph",
"tensorflow.python.keras.optimizers.RMSprop"
],
[
"tensorflow.python.ops.math_ops.subtract",
"tensorflow.python.platform.test.gpu_device_name",
"tensorflow.python.ops.math_ops.less",
"tensorflow.python.ops.session_ops.delete_session_tensor",
"tensorflow.python.ops.session_ops.get_session_handle",
"tensorflow.python.ops.state_ops.assign_add",
"tensorflow.python.ops.math_ops.div",
"tensorflow.python.ops.variables.Variable",
"tensorflow.python.ops.math_ops.add",
"tensorflow.python.ops.math_ops.multiply",
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.session_ops.get_session_tensor",
"tensorflow.python.framework.ops.device",
"tensorflow.python.ops.array_ops.identity",
"tensorflow.python.framework.constant_op.constant"
],
[
"tensorflow.python.ops.array_ops.transpose",
"tensorflow.python.ops.gen_array_ops.batch_to_space",
"numpy.arange",
"tensorflow.python.ops.array_ops.batch_to_space_nd",
"tensorflow.python.ops.array_ops.placeholder",
"numpy.random.normal",
"tensorflow.python.ops.array_ops.zeros",
"tensorflow.python.platform.test.main",
"numpy.prod",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.ops.array_ops.batch_to_space",
"numpy.array",
"numpy.zeros"
],
[
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.ops.array_ops.gather_nd",
"tensorflow.python.ops.ragged.ragged_array_ops.expand_dims",
"tensorflow.python.ops.array_ops.rank",
"tensorflow.python.ops.array_ops.gather",
"tensorflow.python.framework.tensor_shape.dimension_value",
"tensorflow.python.ops.array_ops.ones",
"tensorflow.python.ops.ragged.ragged_conversion_ops.to_tensor",
"tensorflow.python.ops.ragged.ragged_tensor.convert_to_tensor_or_ragged_tensor",
"tensorflow.python.ops.math_ops.cast",
"tensorflow.python.ops.ragged.ragged_conversion_ops.from_tensor",
"tensorflow.python.ops.ragged.ragged_array_ops.tile",
"tensorflow.python.ops.ragged.ragged_tensor.is_ragged",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.ops.ragged.ragged_tensor.RaggedTensor.from_nested_row_splits",
"tensorflow.python.ops.array_ops.concat",
"tensorflow.python.framework.ops.name_scope",
"tensorflow.python.ops.array_ops.reshape",
"tensorflow.python.ops.array_ops.expand_dims"
],
[
"tensorflow.python.data.ops.dataset_ops.Dataset.from_tensors",
"tensorflow.python.ops.array_ops.constant",
"tensorflow.python.ops.array_ops.fill",
"tensorflow.python.data.ops.dataset_ops.Dataset.from_tensor_slices",
"numpy.max",
"tensorflow.python.platform.test.main",
"tensorflow.python.data.experimental.ops.batching.dense_to_sparse_batch",
"numpy.random.randint"
],
[
"tensorflow.python.saved_model.utils_impl.get_variables_path",
"tensorflow.python.keras.saving.saving_utils.extract_model_metrics",
"tensorflow.python.keras.backend.placeholder",
"tensorflow.python.util.compat.as_text",
"tensorflow.python.framework.ops.add_to_collection",
"tensorflow.python.keras.models.clone_and_build_model",
"tensorflow.python.saved_model.model_utils.export_outputs_for_mode",
"tensorflow.python.keras.backend.learning_phase_scope",
"tensorflow.python.framework.ops.get_collection",
"tensorflow.python.util.tf_export.keras_export",
"tensorflow.python.training.tracking.graph_view.ObjectGraphView",
"tensorflow.python.saved_model.builder._SavedModelBuilder",
"tensorflow.python.saved_model.utils_impl.get_or_create_assets_dir",
"tensorflow.python.saved_model.model_utils.build_all_signature_defs",
"tensorflow.python.util.nest.map_structure",
"tensorflow.python.platform.tf_logging.warning",
"tensorflow.python.lib.io.file_io.read_file_to_string",
"tensorflow.python.client.session.Session",
"tensorflow.python.framework.ops.Graph",
"tensorflow.python.lib.io.file_io.write_string_to_file",
"tensorflow.python.util.compat.as_bytes",
"tensorflow.python.framework.ops.get_default_graph",
"tensorflow.python.keras.saving.model_from_json",
"tensorflow.python.keras.saving.saving_utils.trace_model_call",
"tensorflow.python.ops.variables.local_variables_initializer",
"tensorflow.python.training.saver.Saver",
"tensorflow.python.saved_model.utils_impl.get_or_create_variables_dir"
],
[
"tensorflow.python.keras.engine.sequential.Sequential",
"tensorflow.python.keras.testing_utils.get_model_from_layers",
"tensorflow.python.keras.layers.Flatten",
"tensorflow.python.keras.callbacks.TensorBoard",
"tensorflow.python.keras.layers.Dense",
"tensorflow.python.keras.backend.variable",
"tensorflow.python.ops.array_ops.zeros",
"tensorflow.python.keras.optimizers.SGD",
"tensorflow.python.keras.layers.Conv2D",
"tensorflow.python.keras.utils.np_utils.to_categorical",
"numpy.where",
"tensorflow.python.keras.callbacks.LearningRateScheduler",
"tensorflow.python.keras.callbacks.EarlyStopping",
"tensorflow.python.keras.callbacks.ReduceLROnPlateau",
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.array_ops.ones",
"tensorflow.python.keras.testing_utils.get_model_type",
"tensorflow.python.keras.testing_utils.get_small_sequential_mlp",
"tensorflow.python.summary.summary_iterator.summary_iterator",
"tensorflow.python.keras.keras_parameterized.run_all_keras_modes",
"tensorflow.python.keras.utils.to_categorical",
"tensorflow.python.keras.optimizer_v2.gradient_descent.SGD",
"tensorflow.python.data.ops.dataset_ops.Dataset.from_tensor_slices",
"numpy.isnan",
"tensorflow.python.keras.models.Sequential",
"tensorflow.python.keras.callbacks.RemoteMonitor",
"tensorflow.python.training.adam.AdamOptimizer",
"tensorflow.python.keras.backend.get_value",
"tensorflow.python.keras.callbacks.ModelCheckpoint",
"tensorflow.python.keras.layers.Input",
"tensorflow.python.framework.random_seed.set_random_seed",
"tensorflow.python.keras.callbacks.TerminateOnNaN",
"tensorflow.python.keras.testing_utils.should_run_eagerly",
"tensorflow.python.keras.testing_utils.get_test_data",
"numpy.random.random",
"numpy.random.seed",
"tensorflow.python.keras.metrics.CategoricalAccuracy",
"tensorflow.python.keras.keras_parameterized.run_with_all_model_types",
"numpy.ones",
"tensorflow.python.keras.callbacks.CSVLogger",
"tensorflow.python.keras.initializers.Constant",
"tensorflow.python.keras.models.Model",
"tensorflow.python.platform.test.mock.patch.object",
"tensorflow.python.keras.backend.epsilon",
"tensorflow.python.keras.callbacks.CallbackList"
],
[
"tensorflow.python.framework.tensor_shape.scalar",
"tensorflow.contrib.kinesis.python.ops.gen_dataset_ops.kinesis_dataset",
"tensorflow.python.framework.ops.convert_to_tensor"
],
[
"tensorflow.python.autograph.utils.py_func.wrap_py_func",
"tensorflow.python.platform.test.main",
"tensorflow.python.framework.constant_op.constant"
],
[
"tensorflow.python.platform.tf_logging.warning",
"tensorflow.python.framework.device.DeviceSpec.from_string",
"tensorflow.python.training.server_lib.ClusterSpec",
"tensorflow.python.util.tf_export.tf_export"
],
[
"tensorflow.python.ops.array_ops.placeholder",
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.parsing_ops.decode_compressed",
"tensorflow.python.ops.parsing_ops.decode_raw"
],
[
"tensorflow.python.ops.math_ops.log",
"tensorflow.python.training.training.assert_global_step",
"tensorflow.python.summary.summary.scalar",
"tensorflow.python.ops.math_ops.exp",
"tensorflow.python.summary.summary.histogram",
"tensorflow.python.ops.variables.trainable_variables",
"tensorflow.python.ops.init_ops.constant_initializer",
"tensorflow.python.training.training.get_global_step",
"tensorflow.python.training.moving_averages.assign_moving_average",
"tensorflow.python.ops.control_flow_ops.with_dependencies",
"tensorflow.python.framework.ops.get_collection",
"tensorflow.contrib.framework.assert_scalar",
"tensorflow.python.framework.ops.IndexedSlices",
"tensorflow.python.ops.variable_scope.variable_scope",
"tensorflow.python.ops.math_ops.cast",
"tensorflow.python.ops.math_ops.minimum",
"tensorflow.python.ops.random_ops.truncated_normal",
"tensorflow.python.ops.math_ops.square",
"tensorflow.python.training.training.MomentumOptimizer",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.ops.clip_ops.clip_by_global_norm",
"tensorflow.python.ops.array_ops.ones_like",
"tensorflow.python.ops.clip_ops.global_norm",
"tensorflow.python.ops.init_ops.zeros_initializer",
"tensorflow.python.ops.math_ops.maximum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"1.10",
"1.12",
"2.7",
"2.6",
"1.13",
"2.3",
"2.4",
"2.9",
"1.7",
"2.5",
"2.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"1.4",
"2.2",
"1.13",
"2.3",
"2.4",
"2.6",
"2.9",
"1.5",
"1.7",
"2.5",
"1.0",
"2.8",
"1.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"1.10",
"1.12",
"2.7",
"2.6",
"1.13",
"2.3",
"2.4",
"2.9",
"2.5",
"2.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"1.10",
"1.12",
"2.7",
"2.6",
"1.4",
"1.13",
"2.3",
"2.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.2",
"1.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"1.12",
"2.6",
"2.7",
"1.13",
"2.3",
"2.4",
"2.9",
"2.5",
"2.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.13",
"1.12"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.3",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.13",
"1.7",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.13",
"2.2",
"1.12"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.13",
"2.3",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"1.4",
"2.6",
"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": [
"2.8",
"1.10",
"1.12",
"2.7",
"2.6",
"1.13",
"2.3",
"2.4",
"2.9",
"1.7",
"2.5",
"2.2",
"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": [
"2.8",
"1.12",
"2.6",
"2.7",
"1.13",
"2.3",
"2.4",
"2.9",
"2.5",
"2.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"2.7",
"2.6",
"2.4",
"2.3",
"2.9",
"2.5",
"2.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.13",
"1.10",
"1.12"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.13",
"1.10",
"1.12"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"2.9",
"2.5",
"2.8",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.5",
"1.7",
"1.4"
]
},
{
"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",
"2.8",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"0.12",
"1.0"
]
}
] |
gabrielliberato/game-of-life | [
"92d2c4b2760ef747a31a15b9c2740e51f6523c84"
] | [
"vida.py"
] | [
"#!/usr/bin/env python3\n\nfrom random import randint\nimport cv2\nimport numpy as np\nfrom time import sleep\n\n\ndef novoGrid(geracaoAtual):\n aux = []\n novaGeracao = []\n\n # Gera uma matriz vazia que sera atualizada depois de contar os vizinhos\n for k in range(0, quant_arrays):\n for j in range(0, quant_items_por_array):\n aux.append(0)\n novaGeracao.append(aux[:])\n aux.clear()\n\n # Recebe o numero de vizinhos do elemento e define o elemento da nova geracao\n l, e = 0, 0\n while l < quant_arrays:\n e = 0\n while e < quant_items_por_array:\n numViz = contaVizinhos(geracaoAtual, l, e)\n if geracaoAtual[l][e] == 1 and (numViz < 2 or numViz > 3) or (geracaoAtual[l][e] == 0 and (numViz != 3)):\n novaGeracao[l][e] = 0\n\n elif (geracaoAtual[l][e] == 1 and (numViz == 2 or numViz == 3)) or geracaoAtual[l][e] == 0 and numViz == 3:\n novaGeracao[l][e] = 1\n\n # else:\n # # print(f\"Erro. Numero de vizinhos nao foi valido no elemento ({l}, {e})\")\n\n e += 1\n l += 1\n\n # for line in gridNovo:\n # print(line)\n\n return novaGeracao\n\ndef jogoDaVida(principal, jgeracao=0):\n criaImagem(principal, jgeracao)\n jgeracao += 1\n atualizado = novoGrid(principal)[:]\n return atualizado\n\ndef criaImagem(vetor, gera):\n taxa_tamanho = 5\n vertical = 0\n image = np.zeros((alt, lar), np.uint8)\n horizontal = 0\n generation = \"Gen: \" + str(gera)\n cv2.putText(image, generation, (int(lar * 6/7), 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2, cv2.LINE_AA)\n\n for a in vetor:\n for b in a:\n if b == 0:\n cv2.rectangle(image, (horizontal, vertical), (horizontal + taxa_tamanho, vertical + taxa_tamanho),\n (256, 256, 256), -1)\n if b == 1:\n cv2.rectangle(image, (horizontal, vertical), (horizontal + taxa_tamanho, vertical + taxa_tamanho),\n (0, 0, 0), -1)\n horizontal += taxa_tamanho\n horizontal = 0\n vertical += taxa_tamanho\n\n cv2.imshow('JOGO DA VIDA', image)\n cv2.waitKey(20)\n\n\ndef geraModelo():\n modelo = []\n aux = []\n\n # Taxa 1/0 igualitaria\n\n # for k in range(0, quant_arrays):\n # for j in range(0, quant_items_por_array):\n # aux.append(randint(0, 1))\n # modelo.append(aux[:])\n # aux.clear()\n\n # Taxa 1/0 menor\n for k in range(0, quant_arrays):\n for j in range(0, quant_items_por_array):\n temp = randint(0, 100)\n if temp > 25:\n aux.append(0)\n else:\n aux.append(1)\n modelo.append(aux[:])\n aux.clear()\n\n # Modelo para testes\n\n # modelo = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n # ]\n\n return modelo\n\n\ndef defineAnalises(vetor, linhaElemento, colunaElemento): # Retorna uma TUPLA de INTEIROS com a coluna/linha certas\n maxLinhas = len(vetor) - 1\n maxColunas = len(vetor[0]) - 1\n\n # Define o primeiro elemento da contagem de vizinhos, baseando-se na posicao (0,0; 0,max; max,0; max,max)\n if linhaElemento == 0 and colunaElemento == 0:\n linha_analisada = linhaElemento\n coluna_analisada = colunaElemento\n\n elif linhaElemento == 0 and colunaElemento == maxColunas:\n linha_analisada = linhaElemento\n coluna_analisada = colunaElemento - 1\n\n elif linhaElemento == maxLinhas and colunaElemento == 0:\n linha_analisada = linhaElemento - 1\n coluna_analisada = colunaElemento\n\n elif linhaElemento == maxLinhas and colunaElemento == maxColunas:\n linha_analisada = linhaElemento - 1\n coluna_analisada = colunaElemento - 1\n\n return linha_analisada, coluna_analisada\n\n\ndef contaVizinhos(vetor, linhaElemento, colunaElemento): # Retorna um INTEIRO de vizinhos do elemento\n maxLinhas = len(vetor) - 1\n maxColunas = len(vetor[0]) - 1\n numVizinhos = 0\n\n # MEIOS - Unidades que possuem todos os 8 vizinhos\n if 0 < linhaElemento < maxLinhas and 0 < colunaElemento < maxColunas:\n listaV = []\n linhaSeguinte = linhaElemento + 1\n colunaSeguinte = colunaElemento + 1\n linha_analisada = linhaElemento - 1\n\n while linha_analisada <= linhaSeguinte:\n coluna_analisada = colunaElemento - 1\n while coluna_analisada <= colunaSeguinte:\n if linhaElemento != linha_analisada or colunaElemento != coluna_analisada:\n numVizinhos += vetor[linha_analisada][coluna_analisada]\n if vetor[linha_analisada][coluna_analisada] == 1 and (\n linhaElemento != linha_analisada or colunaElemento != coluna_analisada):\n listaV.append([linha_analisada, coluna_analisada])\n coluna_analisada += 1\n linha_analisada += 1\n\n # EXTREMOS - Unidades que so possuem 3 vizinhos\n elif (linhaElemento == 0 or linhaElemento == maxLinhas) and (colunaElemento == 0 or colunaElemento == maxColunas):\n listaV = []\n linha_analisada, coluna_analisada = defineAnalises(vetor, linhaElemento, colunaElemento)\n linhaSeguinte, colunaSeguinte = linha_analisada + 1, coluna_analisada + 1\n\n while linha_analisada <= linhaSeguinte:\n while coluna_analisada <= colunaSeguinte:\n if linhaElemento != linha_analisada or colunaElemento != coluna_analisada:\n numVizinhos += vetor[linha_analisada][coluna_analisada]\n if vetor[linha_analisada][coluna_analisada] == 1 and (\n linhaElemento != linha_analisada or colunaElemento != coluna_analisada):\n listaV.append([linha_analisada, coluna_analisada])\n coluna_analisada += 1\n coluna_analisada -= 2\n linha_analisada += 1\n\n # BORDAS - Unidades que possuem 5 vizinhos\n elif linhaElemento == 0 or linhaElemento == maxLinhas or colunaElemento == 0 or colunaElemento == maxColunas:\n listaV = []\n\n if linhaElemento == 0: # Cima\n linha_analisada = linhaElemento\n\n while linha_analisada < linhaElemento + 2:\n coluna_analisada = colunaElemento - 1\n while coluna_analisada < colunaElemento + 2:\n if linhaElemento != linha_analisada or colunaElemento != coluna_analisada:\n numVizinhos += vetor[linha_analisada][coluna_analisada]\n if vetor[linha_analisada][coluna_analisada] == 1 and (linhaElemento != linha_analisada or\n colunaElemento != coluna_analisada):\n listaV.append([linha_analisada, coluna_analisada])\n coluna_analisada += 1\n linha_analisada += 1\n\n elif linhaElemento == maxLinhas: # Baixo\n\n linha_analisada = linhaElemento - 1\n\n while linha_analisada <= linhaElemento:\n coluna_analisada = colunaElemento - 1\n while coluna_analisada < colunaElemento + 2:\n if linhaElemento != linha_analisada or colunaElemento != coluna_analisada:\n numVizinhos += vetor[linha_analisada][coluna_analisada]\n if vetor[linha_analisada][coluna_analisada] == 1 and (linhaElemento != linha_analisada or\n colunaElemento != coluna_analisada):\n listaV.append([linha_analisada, coluna_analisada])\n coluna_analisada += 1\n linha_analisada += 1\n\n elif colunaElemento == 0: # Esquerda\n linha_analisada = linhaElemento - 1\n\n while linha_analisada < linhaElemento + 2:\n coluna_analisada = colunaElemento - 1\n while coluna_analisada <= colunaElemento + 1:\n if linhaElemento != linha_analisada or colunaElemento != coluna_analisada:\n numVizinhos += vetor[linha_analisada][coluna_analisada]\n if vetor[linha_analisada][coluna_analisada] == 1 and (linhaElemento != linha_analisada or\n colunaElemento != coluna_analisada):\n listaV.append([linha_analisada, coluna_analisada])\n coluna_analisada += 1\n linha_analisada += 1\n\n elif colunaElemento == maxColunas: # Direita\n linha_analisada = linhaElemento - 1\n\n while linha_analisada < linhaElemento + 2:\n coluna_analisada = colunaElemento - 1\n while coluna_analisada <= colunaElemento:\n if linhaElemento != linha_analisada or colunaElemento != coluna_analisada:\n numVizinhos += vetor[linha_analisada][coluna_analisada]\n if vetor[linha_analisada][coluna_analisada] == 1 and (linhaElemento != linha_analisada or\n colunaElemento != coluna_analisada):\n listaV.append([linha_analisada, coluna_analisada])\n coluna_analisada += 1\n linha_analisada += 1\n else:\n print(\"\\nOcorreu um erro.\\n\")\n\n return numVizinhos\n\n\n# Declaracao das variaveis\nalt = 715\nlar = 1200\nfator = 6\nvivos, geracao, tempo, geras = 0, 0, 0, 10\nquant_arrays = int(alt / fator)\nquant_items_por_array = int(lar / fator)\n# print(quant_items_por_array, \"x\", quant_arrays)\ngrid = geraModelo()\natualiza = grid[:]\n\n# Inicio do jogo\nwhile True:\n grid = jogoDaVida(grid, geracao)\n geracao += 1\n"
] | [
[
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gcassella/pyqmc | [
"f7a6e1f656c8eab7ebd72132ee980f77275e3876",
"f7a6e1f656c8eab7ebd72132ee980f77275e3876",
"f7a6e1f656c8eab7ebd72132ee980f77275e3876"
] | [
"tests/integration/test_periodic.py",
"pyqmc/reblock.py",
"tests/unit/test_line_minimization.py"
] | [
"import numpy as np\nimport pyqmc\nimport pandas as pd\nfrom pyscf.pbc import gto, scf\nfrom pyqmc.reblock import reblock\nfrom pyqmc.supercell import get_supercell\nfrom pyscf.pbc.dft.multigrid import multigrid\nfrom pyscf.scf.addons import remove_linear_dep_\nimport time\nimport uuid\n\n\ndef cubic_with_ecp(kind=0, nk=(1, 1, 1)):\n from pyscf.pbc.dft.multigrid import multigrid\n\n start = time.time()\n L = 6.63\n mol = gto.Cell(\n atom=\"\"\"Li {0} {0} {0} \n Li {1} {1} {1}\"\"\".format(\n 0.0, L / 2\n ),\n basis=\"bfd-vdz\",\n ecp=\"bfd\",\n spin=0,\n unit=\"bohr\",\n )\n mol.exp_to_discard = 0.1\n mol.build(a=np.eye(3) * L)\n kpts = mol.make_kpts(nk)\n mf = scf.KUKS(mol, kpts)\n mf.xc = \"pbe\"\n # mf = mf.density_fit()\n mf = multigrid(mf)\n mf = mf.run()\n supercell = get_supercell(mol, np.diag(nk))\n runtest(supercell, mf, kind=kind)\n\n\ndef multislater(kind=0, nk=(1, 1, 1)):\n L = 3\n mol = gto.Cell(\n atom=\"\"\"H {0} {0} {0} \n H {1} {1} {1}\"\"\".format(\n 0.0, L / 2\n ),\n basis=\"cc-pvtz\",\n spin=0,\n unit=\"bohr\",\n )\n mol.exp_to_discard = 0.1\n mol.build(a=np.eye(3) * L)\n kpts = mol.make_kpts(nk)\n mf = scf.UKS(mol, (0, 0, 0))\n mf.xc = \"pbe\"\n mf = multigrid(mf)\n mf = remove_linear_dep_(mf)\n mf.chkfile = \"h_bcc.chkfile\"\n mf = mf.run()\n\n supercell = get_supercell(mol, np.diag(nk))\n runtest(supercell, mf, kind=kind, do_mc=True)\n\n\ndef test_RKS(kind=0, nk=(1, 1, 1)):\n L = 2\n mol = gto.M(\n atom=\"\"\"He {0} {0} {0}\"\"\".format(0.0),\n basis=\"sto-3g\",\n a=np.eye(3) * L,\n unit=\"bohr\",\n )\n kpts = mol.make_kpts(nk)\n mf = scf.KRKS(mol, kpts)\n mf.xc = \"pbe\"\n # mf = mf.density_fit()\n mf = mf.run()\n\n supercell = get_supercell(mol, np.diag(nk))\n runtest(supercell, mf, kind=kind)\n\n\ndef noncubic(kind=0, nk=(1, 1, 1)):\n L = 3\n mol = gto.M(\n atom=\"\"\"H {0} {0} {0} \n H {1} {1} {1}\"\"\".format(\n 0.0, L / 4\n ),\n basis=\"sto-3g\",\n a=(np.ones((3, 3)) - np.eye(3)) * L / 2,\n spin=0,\n unit=\"bohr\",\n )\n kpts = mol.make_kpts(nk)\n mf = scf.KUKS(mol, kpts)\n mf.xc = \"pbe\"\n # mf = mf.density_fit()\n mf = mf.run()\n supercell = get_supercell(mol, np.diag(nk))\n runtest(supercell, mf, kind=kind)\n\n\ndef runtest(mol, mf, kind=0, do_mc=False):\n if do_mc:\n from pyscf import mcscf\n\n mc = mcscf.CASCI(mf, ncas=4, nelecas=(1, 1))\n mc.kernel()\n wf = pyqmc.default_msj(mol, mf, mc)[0]\n kpt = mf.kpt\n dm = mc.make_rdm1()\n if len(dm.shape) == 4:\n dm = np.sum(dm, axis=0)\n else:\n kpt = mf.kpts[kind]\n wf = pyqmc.PySCFSlater(mol, mf)\n dm = mf.make_rdm1()\n print(\"original dm shape\", dm.shape)\n if len(dm.shape) == 4:\n dm = np.sum(dm, axis=0)\n dm = dm[kind]\n\n #####################################\n ## evaluate KE in PySCF\n #####################################\n ke_mat = mol.pbc_intor(\"int1e_kin\", hermi=1, kpts=np.array(kpt))\n print(\"ke_mat\", ke_mat.shape)\n print(\"dm\", dm.shape)\n pyscfke = np.real(np.einsum(\"ij,ji->\", ke_mat, dm))\n print(\"PySCF kinetic energy: {0}\".format(pyscfke))\n\n #####################################\n ## evaluate KE integral with VMC\n #####################################\n coords = pyqmc.initial_guess(mol, 1200, 0.7)\n warmup = 10\n start = time.time()\n df, coords = pyqmc.vmc(\n wf,\n coords,\n nsteps=100 + warmup,\n tstep=1,\n accumulators={\"energy\": pyqmc.accumulators.EnergyAccumulator(mol)},\n verbose=False,\n hdf_file=str(uuid.uuid4()),\n )\n print(\"VMC time\", time.time() - start)\n df = pd.DataFrame(df)\n dfke = reblock(df[\"energyke\"][warmup:], 10)\n dfke /= mol.scale\n vmcke, err = dfke.mean(), dfke.sem()\n print(\"VMC kinetic energy: {0} +- {1}\".format(vmcke, err))\n\n assert (\n np.abs(vmcke - pyscfke) < 5 * err\n ), \"energy diff not within 5 sigma ({0:.6f}): energies \\n{1} \\n{2}\".format(\n 5 * err, vmcke, pyscfke\n )\n\n\nif __name__ == \"__main__\":\n kind = 0\n nk = [1, 1, 1]\n # multislater(kind, nk)\n cubic_with_ecp(kind, nk)\n test_RKS(kind, nk)\n # noncubic(kind, nk)\n",
"import pandas as pd\nimport numpy as np\n\n\ndef reblock(df, nblocks):\n \"\"\"\n Reblock df into nblocks new blocks (nblocks is th length of the returned data)\n\n :param df: data to reblock\n :type df: pandas DataFrame, Series, or numpy array\n :param nblocks: number of resulting blocks\n :type nblocks: int\n :return: reblocked data\n :rtype: same as input df\n \"\"\"\n\n if isinstance(df, pd.Series):\n return pd.Series(_reblock(df.values, nblocks))\n elif isinstance(df, pd.DataFrame):\n rbdf = {col: _reblock(df[col].values, nblocks) for col in df.columns}\n return pd.DataFrame(rbdf)\n elif isinstance(df, np.ndarray):\n return np.stack(_reblock(df, nblocks), axis=0)\n else:\n print(\"WARNING: can't reblock data of type\", type(df), \"-- not reblocking.\")\n return df\n\n\ndef _reblock(array, nblocks):\n \"\"\"\n Helper function to reblock(); this function actually does the reblocking.\n \"\"\"\n vals = np.array_split(array, nblocks, axis=0)\n return [v.mean(axis=0) for v in vals]\n\n\ndef reblock_summary(df, nblocks):\n df = reblock(df, nblocks)\n serr = df.sem()\n d = {\n \"mean\": df.mean(axis=0),\n \"standard error\": serr,\n \"standard error error\": serr / np.sqrt(2 * (len(df) - 1)),\n \"n_blocks\": nblocks,\n }\n return pd.DataFrame(d)\n\n\ndef optimally_reblocked(data):\n \"\"\"\n Find optimal reblocking of input data. Takes in pandas\n DataFrame of raw data to reblock, returns DataFrame\n of reblocked data.\n \"\"\"\n opt = opt_block(data)\n n_reblock = int(np.amax(opt))\n rb_data = reblock_by2(data, n_reblock)\n serr = rb_data.sem(axis=0)\n d = {\n \"mean\": rb_data.mean(axis=0),\n \"standard error\": serr,\n \"standard error error\": serr / np.sqrt(2 * (len(rb_data) - 1)),\n \"reblocks\": n_reblock,\n }\n return pd.DataFrame(d)\n\n\ndef reblock_by2(df, ntimes, c=None):\n \"\"\"\n Reblocks data according to “Error estimates on averages of correlated data”,\n H. Flyvbjerg, H.G. Petersen, J. Chem. Phys. 91, 461 (1989).\n \"\"\"\n newdf = df.copy()\n if c is not None:\n newdf = newdf[c]\n for i in range(ntimes):\n m = newdf.shape[0]\n lasteven = m - int(m % 2 == 1)\n newdf = (newdf[:lasteven:2] + newdf[1::2].values) / 2\n return newdf\n\n\ndef opt_block(df):\n \"\"\"\n Finds optimal block size for each variable in a dataset\n df is a dataframe where each row is a sample and each column is a calculated quantity\n reblock each column over samples to find the best block size\n Returns optimal_block, a 1D array with the optimal size for each column in df\n \"\"\"\n newdf = df.copy()\n iblock = 0\n ndata, nvariables = tuple(df.shape[:2])\n optimal_block = np.array([float(\"NaN\")] * nvariables)\n serr0 = df.sem(axis=0).values\n statslist = []\n while newdf.shape[0] > 1:\n serr = newdf.sem(axis=0).values\n serrerr = serr / (2 * (newdf.shape[0] - 1)) ** 0.5\n statslist.append((iblock, serr.copy()))\n\n n = newdf.shape[0]\n lasteven = n - int(n % 2 == 1)\n newdf = (newdf[:lasteven:2] + newdf[1::2].values) / 2\n iblock += 1\n for iblock, serr in reversed(statslist):\n B3 = 2 ** (3 * iblock)\n inds = np.where(B3 >= 2 * ndata * (serr / serr0) ** 4)[0]\n optimal_block[inds] = iblock\n\n return optimal_block\n\n\ndef test_reblocking():\n \"\"\"\n Tests reblocking against known distribution.\n \"\"\"\n from scipy.stats import sem\n\n def corr_data(N, L):\n \"\"\"\n Creates correlated data. Taken from \n https://pyblock.readthedocs.io/en/latest/tutorial.html.\n \"\"\"\n return np.convolve(np.random.randn(2 ** N), np.ones(2 ** L) / 10, \"same\")\n\n n = 11\n cols = [\"test_data1\", \"test_data2\"]\n dat1 = corr_data(n, 4)\n dat2 = corr_data(n, 7)\n test_data = pd.DataFrame(data={cols[0]: dat1, cols[1]: dat2})\n reblocked_data = optimally_reblocked(test_data[cols])\n for c in cols:\n row = reblocked_data.loc[c]\n reblocks = reblocked_data[\"reblocks\"].values[0]\n std_err = sem(reblock_by2(test_data, reblocks, c))\n std_err_err = std_err / np.sqrt(2 * (2 ** (n - reblocks) - 1))\n\n assert np.isclose(\n row[\"mean\"], np.mean(test_data[c]), 1e-10, 1e-12\n ), \"Means are not equal\"\n assert np.isclose(\n row[\"standard error\"], std_err, 1e-10, 1e-12\n ), \"Standard errors are not equal\"\n assert np.isclose(\n row[\"standard error error\"], std_err_err, 1e-10, 1e-12\n ), \"Standard error errors are not equal\"\n\n statlist = [\"mean\", \"sem\", lambda x: x.sem() / np.sqrt(2 * (len(x) - 1))]\n rb1 = reblock(test_data, len(test_data) // 4).agg(statlist).T\n rb2 = reblock_by2(test_data, 2).agg(statlist).T\n for c in rb1.columns:\n assert np.isclose(rb1[c], rb2[c], 1e-10, 1e-12).all(), (c, rb1[c], rb2[c])\n\n\nif __name__ == \"__main__\":\n test_reblocking()\n",
"# This must be done BEFORE importing numpy or anything else.\n# Therefore it must be in your main script.\nimport os\n\nos.environ[\"MKL_NUM_THREADS\"] = \"1\"\nos.environ[\"NUMEXPR_NUM_THREADS\"] = \"1\"\nos.environ[\"OMP_NUM_THREADS\"] = \"1\"\nimport pandas as pd\nfrom pyscf import lib, gto, scf\nfrom pyqmc import default_sj, line_minimization, initial_guess, gradient_generator\nimport h5py\n\n\ndef test():\n \"\"\" Optimize a Helium atom's wave function and check that it's \n better than Hartree-Fock\"\"\"\n\n mol = gto.M(atom=\"He 0. 0. 0.\", basis=\"bfd_vdz\", ecp=\"bfd\", unit=\"bohr\")\n mf = scf.RHF(mol).run()\n wf, to_opt = default_sj(mol, mf)\n print(to_opt)\n nconf = 500\n wf, dfgrad = line_minimization(\n wf, initial_guess(mol, nconf), gradient_generator(mol, wf, to_opt)\n )\n\n dfgrad = pd.DataFrame(dfgrad)\n print(dfgrad)\n mfen = mf.energy_tot()\n enfinal = dfgrad[\"energy\"].values[-1]\n enfinal_err = dfgrad[\"energy_error\"].values[-1]\n assert mfen > enfinal\n\n\nif __name__ == \"__main__\":\n test()\n"
] | [
[
"numpy.diag",
"numpy.abs",
"numpy.einsum",
"numpy.eye",
"pandas.DataFrame",
"numpy.ones",
"numpy.array",
"numpy.sum"
],
[
"numpy.amax",
"numpy.sqrt",
"pandas.DataFrame",
"numpy.ones",
"numpy.random.randn",
"numpy.mean",
"numpy.array_split",
"numpy.where",
"numpy.isclose"
],
[
"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": []
},
{
"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": []
}
] |
tap222/tensorflow2.0-3dGAN | [
"cddb994d91e9dd126d5c66f9d382c67ce12385e3"
] | [
"gan.py"
] | [
"import tensorflow as tf\r\nimport numpy as np\r\n\r\ndef generator(project_shape, filters_list, name=\"generator\"):\r\n model = tf.keras.Sequential(name=name)\r\n model.add(tf.keras.layers.Dense(\r\n units=np.prod(project_shape),\r\n input_shape=[100],\r\n use_bias=False, \r\n kernel_initializer='glorot_normal'\r\n ))\r\n model.add(tf.keras.layers.BatchNormalization())\r\n model.add(tf.keras.layers.ReLU())\r\n model.add(tf.keras.layers.Reshape(target_shape=project_shape))\r\n for filters in filters_list[:-1]:\r\n model.add(tf.keras.layers.Conv3DTranspose(\r\n filters=filters,\r\n kernel_size=[4,4,4],\r\n strides=[2,2,2],\r\n padding=\"same\",\r\n use_bias=False,\r\n kernel_initializer='glorot_normal'\r\n ))\r\n model.add(tf.keras.layers.BatchNormalization())\r\n model.add(tf.keras.layers.ReLU())\r\n model.add(tf.keras.layers.Conv3DTranspose(\r\n filters=filters_list[-1],\r\n kernel_size=[4,4,4],\r\n strides=[1,1,1],\r\n padding=\"same\",\r\n activation=tf.nn.tanh,\r\n kernel_initializer='glorot_normal'\r\n ))\r\n\r\n return model\r\n\r\n\r\ndef discriminator(filters_list, name=\"discriminator\"):\r\n model = tf.keras.Sequential(name=name)\r\n model.add(tf.keras.Input(shape=[32,32,32,1]))\r\n for filters in filters_list:\r\n model.add(tf.keras.layers.Conv3D(\r\n filters=filters,\r\n kernel_size=[4, 4, 4],\r\n strides=[2,2,2],\r\n padding=\"same\",\r\n bias_initializer='zeros',\r\n kernel_initializer='glorot_normal'\r\n ))\r\n model.add(tf.keras.layers.BatchNormalization())\r\n model.add(tf.keras.layers.LeakyReLU(alpha=0.2))\r\n model.add(tf.keras.layers.Flatten())\r\n model.add(tf.keras.layers.Dense(\r\n units=1,\r\n activation=tf.nn.sigmoid,\r\n kernel_initializer='glorot_normal'\r\n ))\r\n\r\n return model\r\n\r\n\r\nclass ThreeDGAN(object):\r\n def __init__(\r\n self,\r\n project_shape,\r\n gen_filters_list,\r\n disc_filters_list\r\n ):\r\n self.project_shape = project_shape\r\n self.gen_filters_list = gen_filters_list\r\n self.disc_filters_list = disc_filters_list\r\n\r\n self.generator = generator(self.project_shape,self.gen_filters_list)\r\n self.discriminator = discriminator(self.disc_filters_list)\r\n \r\n def generator_loss(self, z):\r\n x_fake = self.generator(z, training=True)\r\n fake_score = self.discriminator(x_fake, training=True)\r\n\r\n loss = tf.keras.losses.binary_crossentropy(\r\n y_true=tf.ones_like(fake_score), y_pred=fake_score, from_logits=False\r\n )\r\n\r\n return loss\r\n \r\n def discriminator_loss(self, x, z):\r\n x_fake = self.generator(z, training=True)\r\n fake_score = self.discriminator(x_fake, training=True)\r\n true_score = self.discriminator(x, training=True)\r\n\r\n loss = tf.keras.losses.binary_crossentropy(\r\n y_true=tf.ones_like(true_score), y_pred=true_score, from_logits=False \r\n ) + tf.keras.losses.binary_crossentropy(\r\n y_true=tf.zeros_like(fake_score), y_pred=fake_score, from_logits=False\r\n )\r\n \r\n return loss"
] | [
[
"tensorflow.keras.layers.ReLU",
"tensorflow.keras.Input",
"tensorflow.keras.layers.LeakyReLU",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.Sequential",
"tensorflow.keras.layers.Conv3D",
"tensorflow.ones_like",
"tensorflow.keras.layers.Conv3DTranspose",
"tensorflow.zeros_like",
"tensorflow.keras.layers.BatchNormalization",
"numpy.prod",
"tensorflow.keras.layers.Reshape",
"tensorflow.keras.layers.Flatten"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
jiaqi-xi/slot_attention | [
"8420414eb261501e5b056e4d409c338d909397ef",
"8420414eb261501e5b056e4d409c338d909397ef"
] | [
"clevr_video/novel_view_train.py",
"clevr_video/model.py"
] | [
"import os\nimport importlib\nimport argparse\nimport numpy as np\nfrom typing import Optional\n\nfrom torchvision import transforms\nimport pytorch_lightning.loggers as pl_loggers\nfrom pytorch_lightning import Trainer\nfrom pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint\n\nfrom novel_view_data import CLEVRNovelViewImageDataModule\nfrom method import SlotAttentionVideoMethod as SlotAttentionMethod\nfrom utils import ImageLogCallback, rescale\nfrom model import SlotAttentionModel\nfrom params import SlotAttentionParams\n\n\ndef main(params: Optional[SlotAttentionParams] = None):\n if params is None:\n params = SlotAttentionParams()\n\n assert params.num_slots > 1, \"Must have at least 2 slots.\"\n\n if params.is_verbose:\n print(\"INFO: limiting the dataset to only images with \"\n f\"`num_slots - 1` ({params.num_slots - 1}) objects.\")\n if args.fp16:\n print('INFO: using FP16 training!')\n if args.weight:\n print(f'INFO: loading checkpoint {args.weight}')\n\n clevr_transforms = transforms.Compose([\n transforms.ToTensor(),\n transforms.Lambda(rescale), # rescale between -1 and 1\n # TODO: no center crop\n transforms.Resize(params.resolution),\n ])\n\n clevr_datamodule = CLEVRNovelViewImageDataModule(\n data_root=params.data_root,\n train_batch_size=params.batch_size,\n val_batch_size=params.val_batch_size,\n clevr_transforms=clevr_transforms,\n num_workers=params.num_workers,\n )\n\n print(\n f\"Training set size (images must have {params.num_slots - 1} \"\n \"objects):\", len(clevr_datamodule.train_dataset))\n\n model = SlotAttentionModel(\n resolution=params.resolution,\n num_slots=params.num_slots,\n num_iterations=params.num_iterations,\n empty_cache=params.empty_cache,\n use_relu=params.use_relu,\n slot_mlp_size=params.slot_mlp_size,\n learnable_slot=params.learnable_slot,\n slot_agnostic=params.slot_agnostic,\n random_slot=params.random_slot,\n use_entropy_loss=params.use_entropy_loss,\n )\n\n method = SlotAttentionMethod(\n model=model, datamodule=clevr_datamodule, params=params)\n\n # we want to also resume wandb log if restoring from previous training\n logger_name = f'{args.params}-fp16' if args.fp16 else args.params\n if SLURM_JOB_ID:\n logger_name = f'{logger_name}-{SLURM_JOB_ID}'\n logger = pl_loggers.WandbLogger(\n project=\"slot-attention-clevr6-video\",\n name=logger_name,\n id=logger_name) # we assume only run one exp per one params setting\n\n # saves a file like: 'path/to/ckp/CLEVRVideo001-val_loss=0.0032.ckpt'\n ckp_path = \"./checkpoint/\" \\\n f\"{args.params + '-fp16' if args.fp16 else args.params}/{SLURM_JOB_ID}\"\n checkpoint_callback = ModelCheckpoint(\n monitor=\"avg_val_loss\",\n dirpath=ckp_path,\n filename=\"CLEVRVideo{epoch:03d}-val_loss_{avg_val_loss:.4f}\",\n save_top_k=3,\n mode=\"min\",\n )\n\n # automatically detect previous checkpoint\n # because if SLURM_JOB_ID is equal, that should definitely be the case\n if os.path.exists(ckp_path):\n ckp_files = os.listdir(ckp_path)\n ckp_files = [ckp for ckp in ckp_files if ckp.startswith('CLEVRVideo')]\n epoch_num = [int(ckp[16:19]) for ckp in ckp_files]\n last_ckp = ckp_files[np.argmax(epoch_num)]\n print(f'INFO: automatically detect checkpoint {last_ckp}')\n args.weight = os.path.join(ckp_path, last_ckp)\n\n trainer = Trainer(\n logger=logger if params.is_logger_enabled else False,\n # TODO: 'ddp' doesn't work on Vector cluster!\n accelerator=\"dp\" if params.gpus > 1 else None,\n num_sanity_val_steps=params.num_sanity_val_steps,\n gpus=params.gpus,\n max_epochs=params.max_epochs,\n log_every_n_steps=50,\n val_check_interval=args.eval_interval,\n callbacks=[\n LearningRateMonitor(\"step\"),\n ImageLogCallback(),\n checkpoint_callback,\n ] if params.is_logger_enabled else [checkpoint_callback],\n precision=16 if args.fp16 else 32,\n resume_from_checkpoint=args.weight if args.weight else None,\n )\n trainer.fit(method, datamodule=clevr_datamodule)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Train Slot Attention')\n parser.add_argument('--params', type=str, default='novel_view_params')\n parser.add_argument('--sbatch', action='store_true')\n parser.add_argument('--fp16', action='store_true')\n parser.add_argument('--eval-interval', type=float, default=1.0)\n parser.add_argument('--weight', type=str, default='')\n args = parser.parse_args()\n if args.sbatch:\n assert os.environ.get('SLURM_JOB_ID') is not None, \\\n 'program not running in sbatch mode!'\n SLURM_JOB_ID = os.environ.get('SLURM_JOB_ID')\n else:\n SLURM_JOB_ID = ''\n if args.params.endswith('.py'):\n args.params = args.params[:-3]\n params = importlib.import_module(args.params)\n params = params.SlotAttentionParams()\n main(params)\n",
"from typing import Tuple\n\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom utils import Tensor, assert_shape, build_grid, conv_transpose_out_shape\n\n\nclass SlotAttention(nn.Module):\n \"\"\"Slot attention module that iteratively performs cross-attention.\n\n Args:\n slot_agnostic (bool): If True, all slots share trained embedding.\n If False, we train embeddings seperately for each slot.\n Defaults to True (as in the paper).\n random_slot (bool): If True, we train mu and sigma for slot embedding,\n and sample slot from the Gaussian when forward pass. If False, we\n train slot embedding itself (similar to the learnable positional\n embedding in DETR), so that we use the same embedding to interact\n with input image features. Defaults to True (as in the paper).\n \"\"\"\n\n def __init__(self,\n in_features,\n num_iterations,\n num_slots,\n slot_size,\n mlp_hidden_size,\n learnable_slot=False,\n slot_agnostic=True,\n random_slot=True,\n epsilon=1e-6):\n super().__init__()\n self.in_features = in_features\n self.num_iterations = num_iterations\n self.num_slots = num_slots\n self.slot_size = slot_size # number of hidden layers in slot dimensions\n self.mlp_hidden_size = mlp_hidden_size\n self.learnable_slot = learnable_slot\n self.slot_agnostic = slot_agnostic\n self.random_slot = random_slot\n self.epsilon = epsilon\n\n self.norm_inputs = nn.LayerNorm(self.in_features)\n # I guess this is layer norm across each slot? should look into this\n self.norm_slots = nn.LayerNorm(self.slot_size)\n self.norm_mlp = nn.LayerNorm(self.slot_size)\n\n # Linear maps for the attention module.\n self.project_q = nn.Linear(self.slot_size, self.slot_size, bias=False)\n self.project_k = nn.Linear(in_features, self.slot_size, bias=False)\n self.project_v = nn.Linear(in_features, self.slot_size, bias=False)\n\n # Slot update functions.\n self.gru = nn.GRUCell(self.slot_size, self.slot_size)\n self.mlp = nn.Sequential(\n nn.Linear(self.slot_size, self.mlp_hidden_size),\n nn.ReLU(),\n nn.Linear(self.mlp_hidden_size, self.slot_size),\n )\n\n trainable_slot_num = 1 if self.slot_agnostic else self.num_slots\n slot_init_func = self.register_parameter if \\\n learnable_slot else self.register_buffer\n if self.random_slot:\n # train the mean and std of slot embedding\n slot_init_func(\n \"slots_mu\",\n torch.nn.Parameter(\n nn.init.xavier_uniform_(\n torch.zeros((1, trainable_slot_num, self.slot_size)),\n gain=nn.init.calculate_gain(\"linear\"))),\n )\n slot_init_func(\n \"slots_log_sigma\",\n torch.nn.Parameter(\n nn.init.xavier_uniform_(\n torch.zeros((1, trainable_slot_num, self.slot_size)),\n gain=nn.init.calculate_gain(\"linear\"))),\n )\n else:\n # train slot embedding itself\n # should definitely be one trainable embedding for each slot\n assert not slot_agnostic, 'cannot use the same emb for each slot!'\n slot_init_func(\n \"slots_mu\",\n torch.nn.Parameter(\n nn.init.xavier_normal_( # TODO: mind the init method here?\n torch.zeros((1, self.num_slots, self.slot_size)),\n gain=nn.init.calculate_gain(\"linear\"))),\n )\n\n def forward(self, inputs: Tensor):\n # `inputs` has shape [batch_size, num_inputs, inputs_size].\n batch_size, num_inputs, inputs_size = inputs.shape\n inputs = self.norm_inputs(inputs) # Apply layer norm to the input.\n # Shape: [batch_size, num_inputs, slot_size].\n k = self.project_k(inputs)\n # Shape: [batch_size, num_inputs, slot_size].\n v = self.project_v(inputs)\n\n # Initialize the slots. Shape: [batch_size, num_slots, slot_size].\n if self.random_slot:\n # if in testing mode, fix random seed to get same slot embedding\n if not self.training:\n torch.manual_seed(0)\n torch.cuda.manual_seed_all(0)\n slots_init = torch.randn(\n (1, self.num_slots,\n self.slot_size)).repeat(batch_size, 1, 1)\n # in training mode, sample from Gaussian with learned mean and std\n else:\n slots_init = torch.randn(\n (batch_size, self.num_slots, self.slot_size))\n slots_init = slots_init.type_as(inputs)\n slots = self.slots_mu + self.slots_log_sigma.exp() * slots_init\n else:\n # use the learned embedding itself, no sampling, no randomness\n slots = self.slots_mu.repeat(batch_size, 1, 1)\n\n # Multiple rounds of attention.\n for _ in range(self.num_iterations):\n slots_prev = slots\n slots = self.norm_slots(slots)\n\n # Attention.\n q = self.project_q(\n slots) # Shape: [batch_size, num_slots, slot_size].\n\n attn_norm_factor = self.slot_size**-0.5\n attn_logits = attn_norm_factor * torch.matmul(k, q.transpose(2, 1))\n attn = F.softmax(attn_logits, dim=-1)\n # `attn` has shape: [batch_size, num_inputs, num_slots].\n\n # Weighted mean.\n attn = attn + self.epsilon\n attn = attn / torch.sum(attn, dim=1, keepdim=True)\n updates = torch.matmul(attn.transpose(1, 2), v)\n # `updates` has shape: [batch_size, num_slots, slot_size].\n\n # Slot update.\n # GRU is expecting inputs of size (N,H)\n # so flatten batch and slots dimension\n slots = self.gru(\n updates.view(batch_size * self.num_slots, self.slot_size),\n slots_prev.view(batch_size * self.num_slots, self.slot_size),\n )\n slots = slots.view(batch_size, self.num_slots, self.slot_size)\n slots = slots + self.mlp(self.norm_mlp(slots))\n\n return slots\n\n\nclass SlotAttentionModel(nn.Module):\n\n def __init__(\n self,\n resolution: Tuple[int, int],\n num_slots: int,\n num_iterations: int,\n in_channels: int = 3,\n kernel_size: int = 5,\n slot_size: int = 64,\n hidden_dims: Tuple[int, ...] = (64, 64, 64, 64),\n decoder_resolution: Tuple[int, int] = (8, 8),\n empty_cache: bool = False,\n use_relu: bool = False, # TODO: official code use ReLU\n slot_mlp_size: int = 128,\n learnable_slot: bool = False,\n slot_agnostic: bool = True,\n random_slot: bool = True,\n use_entropy_loss: bool = False,\n ):\n super().__init__()\n self.resolution = resolution\n self.num_slots = num_slots\n self.num_iterations = num_iterations\n self.in_channels = in_channels\n self.kernel_size = kernel_size\n self.slot_size = slot_size\n self.empty_cache = empty_cache\n self.hidden_dims = hidden_dims\n self.decoder_resolution = decoder_resolution\n self.out_features = self.hidden_dims[-1]\n\n modules = []\n channels = self.in_channels\n # Build Encoder\n for h_dim in self.hidden_dims:\n modules.append(\n nn.Sequential(\n nn.Conv2d(\n channels,\n out_channels=h_dim,\n kernel_size=self.kernel_size,\n stride=1,\n padding=self.kernel_size // 2,\n ),\n nn.ReLU() if use_relu else nn.LeakyReLU(),\n ))\n channels = h_dim\n\n self.encoder = nn.Sequential(*modules)\n self.encoder_pos_embedding = SoftPositionEmbed(self.in_channels,\n self.out_features,\n resolution)\n self.encoder_out_layer = nn.Sequential(\n nn.Linear(self.out_features, self.out_features),\n nn.ReLU() if use_relu else nn.LeakyReLU(),\n nn.Linear(self.out_features, self.out_features),\n )\n\n # Build Decoder\n modules = []\n\n in_size = decoder_resolution[0]\n out_size = in_size\n\n for i in range(len(self.hidden_dims) - 1, -1, -1):\n modules.append(\n nn.Sequential(\n nn.ConvTranspose2d(\n self.hidden_dims[i],\n self.hidden_dims[i - 1],\n kernel_size=5,\n stride=2,\n padding=2,\n output_padding=1,\n ),\n nn.ReLU() if use_relu else nn.LeakyReLU(),\n ))\n out_size = conv_transpose_out_shape(out_size, 2, 2, 5, 1)\n\n assert_shape(\n resolution,\n (out_size, out_size),\n message=\"Output shape of decoder did not match input resolution. \"\n \"Try changing `decoder_resolution`.\",\n )\n\n # same convolutions\n modules.append(\n nn.Sequential(\n nn.ConvTranspose2d(\n self.out_features,\n self.out_features,\n kernel_size=5,\n stride=1,\n padding=2,\n output_padding=0,\n ),\n nn.ReLU() if use_relu else nn.LeakyReLU(),\n nn.ConvTranspose2d(\n self.out_features,\n 4,\n kernel_size=3,\n stride=1,\n padding=1,\n output_padding=0,\n ),\n ))\n\n self.decoder = nn.Sequential(*modules)\n self.decoder_pos_embedding = SoftPositionEmbed(self.in_channels,\n self.out_features,\n self.decoder_resolution)\n\n self.slot_attention = SlotAttention(\n in_features=self.out_features,\n num_iterations=self.num_iterations,\n num_slots=self.num_slots,\n slot_size=self.slot_size,\n mlp_hidden_size=slot_mlp_size,\n learnable_slot=learnable_slot,\n slot_agnostic=slot_agnostic,\n random_slot=random_slot,\n )\n\n self.use_entropy_loss = use_entropy_loss # -p*log(p)\n\n def forward(self, x):\n if self.empty_cache:\n torch.cuda.empty_cache()\n\n batch_size, num_channels, height, width = x.shape\n encoder_out = self.encoder(x)\n encoder_out = self.encoder_pos_embedding(encoder_out)\n # `encoder_out` has shape: [batch_size, filter_size, height, width]\n encoder_out = torch.flatten(encoder_out, start_dim=2, end_dim=3)\n # `encoder_out` has shape: [batch_size, filter_size, height*width]\n encoder_out = encoder_out.permute(0, 2, 1)\n encoder_out = self.encoder_out_layer(encoder_out)\n # `encoder_out` has shape: [batch_size, height*width, filter_size]\n\n # (batch_size, self.num_slots, self.slot_size)\n slots = self.slot_attention(encoder_out)\n # `slots` has shape: [batch_size, num_slots, slot_size].\n batch_size, num_slots, slot_size = slots.shape\n\n # spatial broadcast\n slots = slots.view(batch_size * num_slots, slot_size, 1, 1)\n decoder_in = slots.repeat(1, 1, self.decoder_resolution[0],\n self.decoder_resolution[1])\n\n out = self.decoder_pos_embedding(decoder_in)\n out = self.decoder(out)\n # `out` has shape: [batch_size*num_slots, num_channels+1, height, width].\n\n out = out.view(batch_size, num_slots, num_channels + 1, height, width)\n recons = out[:, :, :num_channels, :, :]\n masks = out[:, :, -1:, :, :]\n masks = F.softmax(masks, dim=1)\n recon_combined = torch.sum(recons * masks, dim=1)\n return recon_combined, recons, masks, slots\n\n def loss_function(self, input):\n recon_combined, recons, masks, slots = self.forward(input)\n loss = F.mse_loss(recon_combined, input)\n loss_dict = {\n 'recon_loss': loss,\n }\n # masks: [B, num_slots, 1, H, W], apply entropy loss\n if self.use_entropy_loss:\n masks = masks[:, :, 0] # [B, num_slots, H, W]\n entropy_loss = (-masks * torch.log(masks + 1e-6)).sum(1).mean()\n loss_dict['entropy'] = entropy_loss\n return loss_dict\n\n\nclass SoftPositionEmbed(nn.Module):\n\n def __init__(self, num_channels: int, hidden_size: int,\n resolution: Tuple[int, int]):\n super().__init__()\n self.dense = nn.Linear(\n in_features=num_channels + 1, out_features=hidden_size)\n self.register_buffer(\"grid\", build_grid(resolution))\n\n def forward(self, inputs: Tensor):\n emb_proj = self.dense(self.grid).permute(0, 3, 1, 2)\n return inputs + emb_proj\n"
] | [
[
"numpy.argmax"
],
[
"torch.nn.functional.softmax",
"torch.zeros",
"torch.sum",
"torch.cuda.manual_seed_all",
"torch.flatten",
"torch.nn.init.calculate_gain",
"torch.randn",
"torch.nn.GRUCell",
"torch.nn.Sequential",
"torch.nn.ConvTranspose2d",
"torch.nn.Conv2d",
"torch.cuda.empty_cache",
"torch.nn.Linear",
"torch.nn.functional.mse_loss",
"torch.log",
"torch.nn.LeakyReLU",
"torch.manual_seed",
"torch.nn.LayerNorm",
"torch.nn.ReLU"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
PINTO0309/Fast_Seg | [
"82932e1c6cde11c7be720f689ae27a7476637a75"
] | [
"libs/models/MSFNet.py"
] | [
"# Author: Xiangtai Li\n# Email: [email protected]\n# Pytorch Implementation Of MSFNet: Real-Time Semantic Segmentation via Multiply Spatial Fusion Network(face++)\n# I didn't include the boundaries information\n\nimport torch\nimport torch.nn as nn\n\n\n\nclass MSFNet(nn.Module):\n def __init__(self):\n super(MSFNet, self).__init__()\n\n\n def forward(self, x):\n pass\n\n\n\nif __name__ == '__main__':\n i = torch.Tensor(1, 3, 512, 512).cuda()\n m = MSFNet().cuda()\n m.eval()\n o = m(i)\n print(o[0].size())\n print(\"output length: \", len(o))"
] | [
[
"torch.Tensor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jingyi7777/adapt-seq-design | [
"51a067752c889f7a0e930a5508a7417dae2cdacc"
] | [
"data/scripts/compute_regression_statistics_without_resampling.py"
] | [
"\"\"\"Compute regression statistics without measurement error.\n\nThe regression outputs include measurement error, which will pull\ndown correlation statistics.\n\"\"\"\n\nimport argparse\nfrom collections import defaultdict\nimport gzip\n\nimport numpy as np\nimport scipy.stats\n\n\ndef parse_args():\n \"\"\"Parse arguments.\n\n Returns:\n argument namespace\n \"\"\"\n # Parse arguments\n parser = argparse.ArgumentParser()\n parser.add_argument('regression_results_tsv',\n help=(\"Path to .tsv.gz file with regression results\"))\n args = parser.parse_args()\n\n return args\n\n\ndef read_results(fn):\n \"\"\"Read file of results.\n\n Args:\n fn: path to file with regression results (.tsv.gz)\n\n Returns:\n list of dict\n \"\"\"\n dp = []\n with gzip.open(fn, 'rt') as f:\n for i, line in enumerate(f):\n line = line.rstrip()\n ls = line.split('\\t')\n if i == 0:\n # Header\n header = ls\n continue\n row = {}\n for j, v in enumerate(ls):\n k = header[j]\n if k in ('true_activity', 'predicted_activity', 'crrna_pos'):\n v = float(v)\n row[k] = v\n dp += [row]\n return dp\n\n\ndef points_with_error(dp):\n \"\"\"Pull out all data points.\n\n Args:\n dp: list of dict, each giving information for a row\n\n Returns:\n tuple (list of true values, list of predicted values)\n \"\"\"\n true = []\n pred = []\n for p in dp:\n true += [p['true_activity']]\n pred += [p['predicted_activity']]\n return (true, pred)\n\n\ndef points_without_error(dp):\n \"\"\"Take summary statistic of true values -- i.e., remove error.\n\n Args:\n dp: list of dict, each giving information for a row\n\n Returns:\n tuple (list of true values, list of predicted values)\n \"\"\"\n # Group points by (target, guide) pair\n same = defaultdict(list)\n for p in dp:\n same[(p['target'], p['guide'])].append(p)\n\n # Check that predicted value is the same in each group\n # (it should be because the input is the same, but allow\n # some numerical tolerance)\n for _, ps in same.items():\n pred_values = [p['predicted_activity'] for p in ps]\n assert np.allclose(pred_values, [pred_values[0]]*len(pred_values))\n\n # Collapse groups\n true = []\n pred = []\n for _, ps in same.items():\n pred_values = [p['predicted_activity'] for p in ps]\n pred_value = np.mean(pred_values)\n\n true_values = [p['true_activity'] for p in ps]\n true_value = np.mean(true_values)\n \n true += [true_value]\n pred += [pred_value]\n\n return (true, pred)\n\n\ndef print_stats(true, pred):\n \"\"\"Print regression statistics.\n\n Args:\n true: list of true activity values\n pred: list of predicted activity values\n \"\"\"\n rho = scipy.stats.spearmanr(true, pred)\n print('Spearman:', rho)\n\n r = scipy.stats.pearsonr(true, pred)\n print('Pearson:', r)\n\n\nif __name__ == '__main__':\n args = parse_args()\n dp = read_results(args.regression_results_tsv)\n\n print('Including error')\n p_with_error_true, p_with_error_pred = points_with_error(dp)\n print_stats(p_with_error_true, p_with_error_pred)\n\n print()\n print('Without error')\n p_without_error_true, p_without_error_pred = points_without_error(dp)\n print_stats(p_without_error_true, p_without_error_pred)\n"
] | [
[
"numpy.mean"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
cm107/tianshou | [
"0febf4bc1dc1366d837bab4574664f8116b66819",
"0febf4bc1dc1366d837bab4574664f8116b66819",
"0febf4bc1dc1366d837bab4574664f8116b66819"
] | [
"tianshou/policy/modelfree/td3.py",
"examples/atari/runnable/pong_a2c.py",
"examples/atari/atari_qrdqn.py"
] | [
"import torch\nimport numpy as np\nfrom copy import deepcopy\nfrom typing import Any, Dict, Tuple, Optional\n\nfrom tianshou.policy import DDPGPolicy\nfrom tianshou.data import Batch, ReplayBuffer\nfrom tianshou.exploration import BaseNoise, GaussianNoise\n\n\nclass TD3Policy(DDPGPolicy):\n \"\"\"Implementation of TD3, arXiv:1802.09477.\n\n :param torch.nn.Module actor: the actor network following the rules in\n :class:`~tianshou.policy.BasePolicy`. (s -> logits)\n :param torch.optim.Optimizer actor_optim: the optimizer for actor network.\n :param torch.nn.Module critic1: the first critic network. (s, a -> Q(s,\n a))\n :param torch.optim.Optimizer critic1_optim: the optimizer for the first\n critic network.\n :param torch.nn.Module critic2: the second critic network. (s, a -> Q(s,\n a))\n :param torch.optim.Optimizer critic2_optim: the optimizer for the second\n critic network.\n :param action_range: the action range (minimum, maximum).\n :type action_range: Tuple[float, float]\n :param float tau: param for soft update of the target network, defaults to\n 0.005.\n :param float gamma: discount factor, in [0, 1], defaults to 0.99.\n :param float exploration_noise: the exploration noise, add to the action,\n defaults to ``GaussianNoise(sigma=0.1)``\n :param float policy_noise: the noise used in updating policy network,\n default to 0.2.\n :param int update_actor_freq: the update frequency of actor network,\n default to 2.\n :param float noise_clip: the clipping range used in updating policy\n network, default to 0.5.\n :param bool reward_normalization: normalize the reward to Normal(0, 1),\n defaults to False.\n :param bool ignore_done: ignore the done flag while training the policy,\n defaults to False.\n\n .. seealso::\n\n Please refer to :class:`~tianshou.policy.BasePolicy` for more detailed\n explanation.\n \"\"\"\n\n def __init__(\n self,\n actor: torch.nn.Module,\n actor_optim: torch.optim.Optimizer,\n critic1: torch.nn.Module,\n critic1_optim: torch.optim.Optimizer,\n critic2: torch.nn.Module,\n critic2_optim: torch.optim.Optimizer,\n action_range: Tuple[float, float],\n tau: float = 0.005,\n gamma: float = 0.99,\n exploration_noise: Optional[BaseNoise] = GaussianNoise(sigma=0.1),\n policy_noise: float = 0.2,\n update_actor_freq: int = 2,\n noise_clip: float = 0.5,\n reward_normalization: bool = False,\n ignore_done: bool = False,\n estimation_step: int = 1,\n **kwargs: Any,\n ) -> None:\n super().__init__(actor, actor_optim, None, None, action_range,\n tau, gamma, exploration_noise, reward_normalization,\n ignore_done, estimation_step, **kwargs)\n self.critic1, self.critic1_old = critic1, deepcopy(critic1)\n self.critic1_old.eval()\n self.critic1_optim = critic1_optim\n self.critic2, self.critic2_old = critic2, deepcopy(critic2)\n self.critic2_old.eval()\n self.critic2_optim = critic2_optim\n self._policy_noise = policy_noise\n self._freq = update_actor_freq\n self._noise_clip = noise_clip\n self._cnt = 0\n self._last = 0\n\n def train(self, mode: bool = True) -> \"TD3Policy\":\n self.training = mode\n self.actor.train(mode)\n self.critic1.train(mode)\n self.critic2.train(mode)\n return self\n\n def sync_weight(self) -> None:\n for o, n in zip(self.actor_old.parameters(), self.actor.parameters()):\n o.data.copy_(o.data * (1.0 - self._tau) + n.data * self._tau)\n for o, n in zip(\n self.critic1_old.parameters(), self.critic1.parameters()\n ):\n o.data.copy_(o.data * (1.0 - self._tau) + n.data * self._tau)\n for o, n in zip(\n self.critic2_old.parameters(), self.critic2.parameters()\n ):\n o.data.copy_(o.data * (1.0 - self._tau) + n.data * self._tau)\n\n def _target_q(\n self, buffer: ReplayBuffer, indice: np.ndarray\n ) -> torch.Tensor:\n batch = buffer[indice] # batch.obs: s_{t+n}\n a_ = self(batch, model=\"actor_old\", input=\"obs_next\").act\n dev = a_.device\n noise = torch.randn(size=a_.shape, device=dev) * self._policy_noise\n if self._noise_clip > 0.0:\n noise = noise.clamp(-self._noise_clip, self._noise_clip)\n a_ += noise\n a_ = a_.clamp(self._range[0], self._range[1])\n target_q = torch.min(\n self.critic1_old(batch.obs_next, a_),\n self.critic2_old(batch.obs_next, a_))\n return target_q\n\n def learn(self, batch: Batch, **kwargs: Any) -> Dict[str, float]:\n weight = batch.pop(\"weight\", 1.0)\n # critic 1\n current_q1 = self.critic1(batch.obs, batch.act).flatten()\n target_q = batch.returns.flatten()\n td1 = current_q1 - target_q\n critic1_loss = (td1.pow(2) * weight).mean()\n # critic1_loss = F.mse_loss(current_q1, target_q)\n self.critic1_optim.zero_grad()\n critic1_loss.backward()\n self.critic1_optim.step()\n # critic 2\n current_q2 = self.critic2(batch.obs, batch.act).flatten()\n td2 = current_q2 - target_q\n critic2_loss = (td2.pow(2) * weight).mean()\n # critic2_loss = F.mse_loss(current_q2, target_q)\n self.critic2_optim.zero_grad()\n critic2_loss.backward()\n self.critic2_optim.step()\n batch.weight = (td1 + td2) / 2.0 # prio-buffer\n if self._cnt % self._freq == 0:\n actor_loss = -self.critic1(\n batch.obs, self(batch, eps=0.0).act).mean()\n self.actor_optim.zero_grad()\n actor_loss.backward()\n self._last = actor_loss.item()\n self.actor_optim.step()\n self.sync_weight()\n self._cnt += 1\n return {\n \"loss/actor\": self._last,\n \"loss/critic1\": critic1_loss.item(),\n \"loss/critic2\": critic2_loss.item(),\n }\n",
"import os\nimport torch\nimport pprint\nimport argparse\nimport numpy as np\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom tianshou.policy import A2CPolicy\nfrom tianshou.env import SubprocVectorEnv\nfrom tianshou.utils.net.common import Net\nfrom tianshou.trainer import onpolicy_trainer\nfrom tianshou.data import Collector, ReplayBuffer\nfrom tianshou.utils.net.discrete import Actor, Critic\n\nfrom atari import create_atari_environment, preprocess_fn\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--task', type=str, default='Pong')\n parser.add_argument('--seed', type=int, default=1626)\n parser.add_argument('--buffer-size', type=int, default=20000)\n parser.add_argument('--lr', type=float, default=3e-4)\n parser.add_argument('--gamma', type=float, default=0.9)\n parser.add_argument('--epoch', type=int, default=100)\n parser.add_argument('--step-per-epoch', type=int, default=1000)\n parser.add_argument('--collect-per-step', type=int, default=10)\n parser.add_argument('--repeat-per-collect', type=int, default=1)\n parser.add_argument('--batch-size', type=int, default=64)\n parser.add_argument('--hidden-sizes', type=int,\n nargs='*', default=[128, 128, 128])\n parser.add_argument('--training-num', type=int, default=8)\n parser.add_argument('--test-num', type=int, default=8)\n parser.add_argument('--logdir', type=str, default='log')\n parser.add_argument('--render', type=float, default=0.)\n\n parser.add_argument(\n '--device', type=str,\n default='cuda' if torch.cuda.is_available() else 'cpu')\n # a2c special\n parser.add_argument('--vf-coef', type=float, default=0.5)\n parser.add_argument('--ent-coef', type=float, default=0.001)\n parser.add_argument('--max-grad-norm', type=float, default=None)\n parser.add_argument('--max-episode-steps', type=int, default=2000)\n return parser.parse_args()\n\n\ndef test_a2c(args=get_args()):\n env = create_atari_environment(args.task)\n args.state_shape = env.observation_space.shape or env.observation_space.n\n args.action_shape = env.env.action_space.shape or env.env.action_space.n\n # train_envs = gym.make(args.task)\n train_envs = SubprocVectorEnv(\n [lambda: create_atari_environment(args.task)\n for _ in range(args.training_num)])\n # test_envs = gym.make(args.task)\n test_envs = SubprocVectorEnv(\n [lambda: create_atari_environment(args.task)\n for _ in range(args.test_num)])\n # seed\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n train_envs.seed(args.seed)\n test_envs.seed(args.seed)\n # model\n net = Net(args.state_shape, hidden_sizes=args.hidden_sizes,\n device=args.device)\n actor = Actor(net, args.action_shape, device=args.device).to(args.device)\n critic = Critic(net, device=args.device).to(args.device)\n optim = torch.optim.Adam(set(\n actor.parameters()).union(critic.parameters()), lr=args.lr)\n dist = torch.distributions.Categorical\n policy = A2CPolicy(\n actor, critic, optim, dist, args.gamma, vf_coef=args.vf_coef,\n ent_coef=args.ent_coef, max_grad_norm=args.max_grad_norm)\n # collector\n train_collector = Collector(\n policy, train_envs, ReplayBuffer(args.buffer_size),\n preprocess_fn=preprocess_fn)\n test_collector = Collector(policy, test_envs, preprocess_fn=preprocess_fn)\n # log\n writer = SummaryWriter(os.path.join(args.logdir, args.task, 'a2c'))\n\n def stop_fn(mean_rewards):\n if env.env.spec.reward_threshold:\n return mean_rewards >= env.spec.reward_threshold\n else:\n return False\n\n # trainer\n result = onpolicy_trainer(\n policy, train_collector, test_collector, args.epoch,\n args.step_per_epoch, args.collect_per_step, args.repeat_per_collect,\n args.test_num, args.batch_size, stop_fn=stop_fn, writer=writer)\n if __name__ == '__main__':\n pprint.pprint(result)\n # Let's watch its performance!\n env = create_atari_environment(args.task)\n collector = Collector(policy, env, preprocess_fn=preprocess_fn)\n result = collector.collect(n_episode=1, render=args.render)\n print(f'Final reward: {result[\"rew\"]}, length: {result[\"len\"]}')\n\n\nif __name__ == '__main__':\n test_a2c()\n",
"import os\nimport torch\nimport pprint\nimport argparse\nimport numpy as np\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom tianshou.policy import QRDQNPolicy\nfrom tianshou.env import SubprocVectorEnv\nfrom tianshou.trainer import offpolicy_trainer\nfrom tianshou.data import Collector, ReplayBuffer\n\nfrom atari_network import QRDQN\nfrom atari_wrapper import wrap_deepmind\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--task', type=str, default='PongNoFrameskip-v4')\n parser.add_argument('--seed', type=int, default=0)\n parser.add_argument('--eps-test', type=float, default=0.005)\n parser.add_argument('--eps-train', type=float, default=1.)\n parser.add_argument('--eps-train-final', type=float, default=0.05)\n parser.add_argument('--buffer-size', type=int, default=100000)\n parser.add_argument('--lr', type=float, default=0.0001)\n parser.add_argument('--gamma', type=float, default=0.99)\n parser.add_argument('--num-quantiles', type=int, default=200)\n parser.add_argument('--n-step', type=int, default=3)\n parser.add_argument('--target-update-freq', type=int, default=500)\n parser.add_argument('--epoch', type=int, default=100)\n parser.add_argument('--step-per-epoch', type=int, default=10000)\n parser.add_argument('--collect-per-step', type=int, default=10)\n parser.add_argument('--batch-size', type=int, default=32)\n parser.add_argument('--training-num', type=int, default=16)\n parser.add_argument('--test-num', type=int, default=10)\n parser.add_argument('--logdir', type=str, default='log')\n parser.add_argument('--render', type=float, default=0.)\n parser.add_argument(\n '--device', type=str,\n default='cuda' if torch.cuda.is_available() else 'cpu')\n parser.add_argument('--frames-stack', type=int, default=4)\n parser.add_argument('--resume-path', type=str, default=None)\n parser.add_argument('--watch', default=False, action='store_true',\n help='watch the play of pre-trained policy only')\n return parser.parse_args()\n\n\ndef make_atari_env(args):\n return wrap_deepmind(args.task, frame_stack=args.frames_stack)\n\n\ndef make_atari_env_watch(args):\n return wrap_deepmind(args.task, frame_stack=args.frames_stack,\n episode_life=False, clip_rewards=False)\n\n\ndef test_qrdqn(args=get_args()):\n env = make_atari_env(args)\n args.state_shape = env.observation_space.shape or env.observation_space.n\n args.action_shape = env.env.action_space.shape or env.env.action_space.n\n # should be N_FRAMES x H x W\n print(\"Observations shape:\", args.state_shape)\n print(\"Actions shape:\", args.action_shape)\n # make environments\n train_envs = SubprocVectorEnv([lambda: make_atari_env(args)\n for _ in range(args.training_num)])\n test_envs = SubprocVectorEnv([lambda: make_atari_env_watch(args)\n for _ in range(args.test_num)])\n # seed\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n train_envs.seed(args.seed)\n test_envs.seed(args.seed)\n # define model\n net = QRDQN(*args.state_shape, args.action_shape,\n args.num_quantiles, args.device)\n optim = torch.optim.Adam(net.parameters(), lr=args.lr)\n # define policy\n policy = QRDQNPolicy(\n net, optim, args.gamma, args.num_quantiles,\n args.n_step, target_update_freq=args.target_update_freq\n ).to(args.device)\n # load a previous policy\n if args.resume_path:\n policy.load_state_dict(torch.load(\n args.resume_path, map_location=args.device\n ))\n print(\"Loaded agent from: \", args.resume_path)\n # replay buffer: `save_last_obs` and `stack_num` can be removed together\n # when you have enough RAM\n buffer = ReplayBuffer(args.buffer_size, ignore_obs_next=True,\n save_only_last_obs=True, stack_num=args.frames_stack)\n # collector\n train_collector = Collector(policy, train_envs, buffer)\n test_collector = Collector(policy, test_envs)\n # log\n log_path = os.path.join(args.logdir, args.task, 'qrdqn')\n writer = SummaryWriter(log_path)\n\n def save_fn(policy):\n torch.save(policy.state_dict(), os.path.join(log_path, 'policy.pth'))\n\n def stop_fn(mean_rewards):\n if env.env.spec.reward_threshold:\n return mean_rewards >= env.spec.reward_threshold\n elif 'Pong' in args.task:\n return mean_rewards >= 20\n else:\n return False\n\n def train_fn(epoch, env_step):\n # nature DQN setting, linear decay in the first 1M steps\n if env_step <= 1e6:\n eps = args.eps_train - env_step / 1e6 * \\\n (args.eps_train - args.eps_train_final)\n else:\n eps = args.eps_train_final\n policy.set_eps(eps)\n writer.add_scalar('train/eps', eps, global_step=env_step)\n\n def test_fn(epoch, env_step):\n policy.set_eps(args.eps_test)\n\n # watch agent's performance\n def watch():\n print(\"Testing agent ...\")\n policy.eval()\n policy.set_eps(args.eps_test)\n test_envs.seed(args.seed)\n test_collector.reset()\n result = test_collector.collect(n_episode=[1] * args.test_num,\n render=args.render)\n pprint.pprint(result)\n\n if args.watch:\n watch()\n exit(0)\n\n # test train_collector and start filling replay buffer\n train_collector.collect(n_step=args.batch_size * 4)\n # trainer\n result = offpolicy_trainer(\n policy, train_collector, test_collector, args.epoch,\n args.step_per_epoch, args.collect_per_step, args.test_num,\n args.batch_size, train_fn=train_fn, test_fn=test_fn,\n stop_fn=stop_fn, save_fn=save_fn, writer=writer, test_in_train=False)\n\n pprint.pprint(result)\n watch()\n\n\nif __name__ == '__main__':\n test_qrdqn(get_args())\n"
] | [
[
"torch.randn"
],
[
"torch.manual_seed",
"torch.cuda.is_available",
"numpy.random.seed"
],
[
"numpy.random.seed",
"torch.load",
"torch.manual_seed",
"torch.utils.tensorboard.SummaryWriter",
"torch.cuda.is_available"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lacava/sklearn-benchmarks | [
"a917336f6fd3ffb89efd94b1c7f60b3a05ba780f"
] | [
"model_code/random_search_preprocessing/GaussianNB.py"
] | [
"import sys\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.preprocessing import Binarizer, MaxAbsScaler, MinMaxScaler\nfrom sklearn.preprocessing import Normalizer, PolynomialFeatures, RobustScaler, StandardScaler\nfrom sklearn.decomposition import FastICA, PCA\nfrom sklearn.kernel_approximation import RBFSampler, Nystroem\nfrom sklearn.cluster import FeatureAgglomeration\nfrom sklearn.feature_selection import SelectFwe, SelectPercentile, VarianceThreshold\nfrom sklearn.feature_selection import SelectFromModel, RFE\nfrom sklearn.ensemble import ExtraTreesClassifier\n\nfrom sklearn.naive_bayes import GaussianNB\nfrom evaluate_model import evaluate_model\n\ndataset = sys.argv[1]\nnum_param_combinations = int(sys.argv[2])\nrandom_seed = int(sys.argv[3])\npreprocessor_num = int(sys.argv[4])\n\nnp.random.seed(random_seed)\n\npreprocessor_list = [Binarizer, MaxAbsScaler, MinMaxScaler, Normalizer,\n PolynomialFeatures, RobustScaler, StandardScaler,\n FastICA, PCA, RBFSampler, Nystroem, FeatureAgglomeration,\n SelectFwe, SelectPercentile, VarianceThreshold,\n SelectFromModel, RFE]\n\nchosen_preprocessor = preprocessor_list[preprocessor_num]\n\npipeline_components = [chosen_preprocessor, GaussianNB]\npipeline_parameters = {}\npipeline_parameters[GaussianNB] = [{}]\n\nif chosen_preprocessor is SelectFromModel:\n pipeline_parameters[SelectFromModel] = [{'estimator': ExtraTreesClassifier(n_estimators=100, random_state=324089)}]\nelif chosen_preprocessor is RFE:\n pipeline_parameters[RFE] = [{'estimator': ExtraTreesClassifier(n_estimators=100, random_state=324089)}]\n\nevaluate_model(dataset, pipeline_components, pipeline_parameters)\n"
] | [
[
"sklearn.ensemble.ExtraTreesClassifier",
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
rachelyou/CL-SGCN | [
"4430d32018c7da3eeb94ac29137ae23d14d90d8d"
] | [
"pGRACE/functional.py"
] | [
"import torch\nfrom torch_geometric.utils import degree, to_undirected\n\nfrom pGRACE.utils import compute_pr, eigenvector_centrality\n\n\ndef drop_feature(x, drop_prob):\n drop_mask = torch.empty((x.size(1),), dtype=torch.float32, device=x.device).uniform_(0, 1) < drop_prob\n x = x.clone()\n x[:, drop_mask] = 0\n\n return x\n\n\ndef drop_feature_weighted(x, w, p: float, threshold: float = 0.4):\n w = w / w.mean() * p\n w = w.where(w < threshold, torch.ones_like(w) * threshold)\n drop_prob = w.repeat(x.size(0)).view(x.size(0), -1)\n\n drop_mask = torch.bernoulli(drop_prob).to(torch.bool)\n\n x = x.clone()\n x[drop_mask] = 0.\n\n return x\n\n\ndef drop_feature_weighted_2(x, w, p: float, threshold: float = 0.7):\n w = w / w.mean() * p\n w = w.where(w < threshold, torch.ones_like(w) * threshold)\n drop_prob = w\n\n drop_mask = torch.bernoulli(drop_prob).to(torch.bool)\n\n x = x.clone()\n x[:, drop_mask] = 0.\n\n return x\n\n\ndef feature_drop_weights(x, node_c):\n x = x.to(torch.bool).to(torch.float32)\n w = x.t() @ node_c\n w = w.log()\n s = (w.max() - w) / (w.max() - w.mean())\n\n return s\n\n\ndef feature_drop_weights_dense(x, node_c):\n x = (x+1e-10).abs() #####change\n w = x.t() @ node_c\n w = w.log()\n s = (w.max() - w) / (w.max() - w.mean())\n\n return s\n\n\ndef drop_edge_weighted(edge_index, edge_weights, p: float, threshold: float = 1.):\n edge_weights = edge_weights / edge_weights.mean() * p\n edge_weights = edge_weights.where(edge_weights < threshold, torch.ones_like(edge_weights) * threshold)\n sel_mask = torch.bernoulli(1. - edge_weights).to(torch.bool)\n\n return edge_index[:, sel_mask]\n\n\ndef degree_drop_weights(edge_index):\n edge_index_ = to_undirected(edge_index)\n deg = degree(edge_index_[1])\n deg_col = deg[edge_index[1]].to(torch.float32)\n s_col = torch.log(deg_col)\n weights = (s_col.max() - s_col) / (s_col.max() - s_col.mean())\n\n return weights\n\n\ndef pr_drop_weights(edge_index, aggr: str = 'sink', k: int = 10):\n pv = compute_pr(edge_index, k=k)\n pv_row = pv[edge_index[0]].to(torch.float32)\n pv_col = pv[edge_index[1]].to(torch.float32)\n s_row = torch.log(pv_row)\n s_col = torch.log(pv_col)\n if aggr == 'sink':\n s = s_col\n elif aggr == 'source':\n s = s_row\n elif aggr == 'mean':\n s = (s_col + s_row) * 0.5\n else:\n s = s_col\n weights = (s.max() - s) / (s.max() - s.mean())\n\n return weights\n\n\ndef evc_drop_weights(data):\n evc = eigenvector_centrality(data)\n evc = evc.where(evc > 0, torch.zeros_like(evc))\n evc = evc + 1e-8\n s = evc.log()\n\n edge_index = data.edge_index\n s_row, s_col = s[edge_index[0]], s[edge_index[1]]\n s = s_col\n\n return (s.max() - s) / (s.max() - s.mean())"
] | [
[
"torch.zeros_like",
"torch.log",
"torch.ones_like",
"torch.bernoulli"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
adamshephard/tiatoolbox | [
"28c32648bc1f3e842c7b241637fd25af290386e6",
"28c32648bc1f3e842c7b241637fd25af290386e6"
] | [
"tests/test_stainnorm.py",
"tiatoolbox/tools/tissuemask.py"
] | [
"# skipcq: PTC-W6004\n\"\"\"Tests for stain normalization code.\"\"\"\n\nimport pathlib\n\nimport numpy as np\nimport pytest\nfrom click.testing import CliRunner\n\nfrom tiatoolbox import cli\nfrom tiatoolbox.data import _local_sample_path, stain_norm_target\nfrom tiatoolbox.tools import stainextract\nfrom tiatoolbox.tools.stainnorm import get_normalizer\nfrom tiatoolbox.utils.misc import imread\n\n\ndef test_stain_extract():\n \"\"\"Test stain extraction class.\"\"\"\n stain_matrix = np.array([0.65, 0.70, 0.29])\n with pytest.raises(ValueError):\n _ = stainextract.CustomExtractor(stain_matrix)\n\n\ndef test_vectors_in_right_direction():\n \"\"\"Test if eigenvectors are corrected in the right direction.\"\"\"\n e_vect = np.ones([2, 2])\n e_vect = stainextract.vectors_in_correct_direction(e_vectors=e_vect)\n assert np.all(e_vect == 1)\n\n e_vect = np.ones([2, 2])\n e_vect[0, 0] = -1\n e_vect = stainextract.vectors_in_correct_direction(e_vectors=e_vect)\n assert np.all(e_vect[:, 1] == 1)\n assert e_vect[0, 0] == 1\n assert e_vect[1, 0] == -1\n\n e_vect = np.ones([2, 2])\n e_vect[0, 1] = -1\n e_vect = stainextract.vectors_in_correct_direction(e_vectors=e_vect)\n assert np.all(e_vect[:, 0] == 1)\n assert e_vect[0, 1] == 1\n assert e_vect[1, 1] == -1\n\n\ndef test_h_e_in_correct_order():\n \"\"\"Test if H&E vectors are returned in the correct order.\"\"\"\n v1 = np.ones(3)\n v2 = np.zeros(3)\n he = stainextract.h_and_e_in_right_order(v1, v2)\n assert np.all(he == np.array([v1, v2]))\n\n he = stainextract.h_and_e_in_right_order(v2, v1)\n assert np.all(he == np.array([v1, v2]))\n\n\ndef test_dl_output_for_h_and_e():\n \"\"\"Test if correct value for H and E from dictionary learning output is returned.\"\"\"\n dictionary = np.zeros([20, 15])\n dictionary1 = stainextract.dl_output_for_h_and_e(dictionary=dictionary)\n\n assert np.all(dictionary1 == dictionary)\n dictionary[1, :] = 1\n dictionary2 = stainextract.dl_output_for_h_and_e(dictionary=dictionary)\n\n assert dictionary2.shape == (2, 15)\n assert np.all(dictionary2 == dictionary[[1, 0], :])\n\n\ndef test_reinhard_normalize(source_image, norm_reinhard):\n \"\"\"Test for Reinhard colour normalization.\"\"\"\n source_img = imread(pathlib.Path(source_image))\n target_img = stain_norm_target()\n reinhard_img = imread(pathlib.Path(norm_reinhard))\n\n norm = get_normalizer(\"reinhard\")\n norm.fit(target_img) # get stain information of target image\n transform = norm.transform(source_img) # transform source image\n\n assert np.shape(transform) == np.shape(source_img)\n assert np.mean(np.absolute(reinhard_img / 255.0 - transform / 255.0)) < 1e-2\n\n\ndef test_custom_normalize(source_image, norm_ruifrok):\n \"\"\"Test for stain normalization with user-defined stain matrix.\"\"\"\n source_img = imread(pathlib.Path(source_image))\n target_img = stain_norm_target()\n custom_img = imread(pathlib.Path(norm_ruifrok))\n\n # init class with custom method - test with ruifrok stain matrix\n stain_matrix = np.array([[0.65, 0.70, 0.29], [0.07, 0.99, 0.11]])\n norm = get_normalizer(\"custom\", stain_matrix=stain_matrix)\n norm.fit(target_img) # get stain information of target image\n transform = norm.transform(source_img) # transform source image\n\n assert np.shape(transform) == np.shape(source_img)\n assert np.mean(np.absolute(custom_img / 255.0 - transform / 255.0)) < 1e-2\n\n\ndef test_get_normalizer_assertion():\n \"\"\"Test get normalizer assertion error.\"\"\"\n stain_matrix = np.array([[0.65, 0.70, 0.29], [0.07, 0.99, 0.11]])\n with pytest.raises(ValueError):\n _ = get_normalizer(\"ruifrok\", stain_matrix)\n\n\ndef test_ruifrok_normalize(source_image, norm_ruifrok):\n \"\"\"Test for stain normalization with stain matrix from Ruifrok and Johnston.\"\"\"\n source_img = imread(pathlib.Path(source_image))\n target_img = stain_norm_target()\n ruifrok_img = imread(pathlib.Path(norm_ruifrok))\n\n # init class with Ruifrok & Johnston method\n norm = get_normalizer(\"ruifrok\")\n norm.fit(target_img) # get stain information of target image\n transform = norm.transform(source_img) # transform source image\n\n assert np.shape(transform) == np.shape(source_img)\n assert np.mean(np.absolute(ruifrok_img / 255.0 - transform / 255.0)) < 1e-2\n\n\ndef test_macenko_normalize(source_image, norm_macenko):\n \"\"\"Test for stain normalization with stain matrix from Macenko et al.\"\"\"\n source_img = imread(pathlib.Path(source_image))\n target_img = stain_norm_target()\n macenko_img = imread(pathlib.Path(norm_macenko))\n\n # init class with Macenko method\n norm = get_normalizer(\"macenko\")\n norm.fit(target_img) # get stain information of target image\n transform = norm.transform(source_img) # transform source image\n\n assert np.shape(transform) == np.shape(source_img)\n assert np.mean(np.absolute(macenko_img / 255.0 - transform / 255.0)) < 1e-2\n\n\ndef test_vahadane_normalize(source_image, norm_vahadane):\n \"\"\"Test for stain normalization with stain matrix from Vahadane et al.\"\"\"\n source_img = imread(pathlib.Path(source_image))\n target_img = stain_norm_target()\n vahadane_img = imread(pathlib.Path(norm_vahadane))\n\n # init class with Vahadane method\n norm = get_normalizer(\"vahadane\")\n norm.fit(target_img) # get stain information of target image\n transform = norm.transform(source_img) # transform source image\n\n assert np.shape(transform) == np.shape(source_img)\n assert np.mean(np.absolute(vahadane_img / 255.0 - transform / 255.0)) < 1e-1\n\n\n# -------------------------------------------------------------------------------------\n# Command Line Interface\n# -------------------------------------------------------------------------------------\n\n\ndef test_command_line_stainnorm(source_image, tmp_path):\n \"\"\"Test for the stain normalization CLI.\"\"\"\n source_img = pathlib.Path(source_image)\n target_img = _local_sample_path(\"target_image.png\")\n runner = CliRunner()\n stainnorm_result = runner.invoke(\n cli.main,\n [\n \"stain-norm\",\n \"--img-input\",\n source_img,\n \"--target-input\",\n target_img,\n \"--output-path\",\n str(tmp_path / \"stainnorm_output\"),\n \"--method\",\n \"reinhard\",\n ],\n )\n\n assert stainnorm_result.exit_code == 0\n\n stainnorm_result = runner.invoke(\n cli.main,\n [\n \"stain-norm\",\n \"--img-input\",\n source_img,\n \"--target-input\",\n target_img,\n \"--output-path\",\n str(tmp_path / \"stainnorm_output\"),\n \"--method\",\n \"ruifrok\",\n ],\n )\n\n assert stainnorm_result.exit_code == 0\n\n stainnorm_result = runner.invoke(\n cli.main,\n [\n \"stain-norm\",\n \"--img-input\",\n source_img,\n \"--target-input\",\n target_img,\n \"--output-path\",\n str(tmp_path / \"stainnorm_output\"),\n \"--method\",\n \"macenko\",\n ],\n )\n\n assert stainnorm_result.exit_code == 0\n\n stainnorm_result = runner.invoke(\n cli.main,\n [\n \"stain-norm\",\n \"--img-input\",\n source_img,\n \"--target-input\",\n target_img,\n \"--output-path\",\n str(tmp_path / \"stainnorm_output\"),\n \"--method\",\n \"vahadane\",\n ],\n )\n\n assert stainnorm_result.exit_code == 0\n\n\ndef test_cli_stainnorm_dir(source_image, tmp_path):\n \"\"\"Test directory input for the stain normalization CLI.\"\"\"\n source_img = source_image.parent\n target_img = _local_sample_path(\"target_image.png\")\n runner = CliRunner()\n stainnorm_result = runner.invoke(\n cli.main,\n [\n \"stain-norm\",\n \"--img-input\",\n str(source_img),\n \"--target-input\",\n target_img,\n \"--output-path\",\n str(tmp_path / \"stainnorm_ouput\"),\n \"--method\",\n \"vahadane\",\n ],\n )\n\n assert stainnorm_result.exit_code == 0\n\n\ndef test_cli_stainnorm_file_not_found_error(source_image, tmp_path):\n \"\"\"Test file not found error for the stain normalization CLI.\"\"\"\n source_img = pathlib.Path(source_image)\n target_img = stain_norm_target()\n runner = CliRunner()\n stainnorm_result = runner.invoke(\n cli.main,\n [\n \"stain-norm\",\n \"--img-input\",\n str(source_img)[:-1],\n \"--target-input\",\n target_img,\n \"--output-path\",\n str(tmp_path / \"stainnorm_output\"),\n \"--method\",\n \"vahadane\",\n ],\n )\n\n assert stainnorm_result.output == \"\"\n assert stainnorm_result.exit_code == 1\n assert isinstance(stainnorm_result.exception, FileNotFoundError)\n\n\ndef test_cli_stainnorm_method_not_supported(source_image, tmp_path):\n \"\"\"Test method not supported for the stain normalization CLI.\"\"\"\n source_img = pathlib.Path(source_image)\n target_img = stain_norm_target()\n runner = CliRunner()\n stainnorm_result = runner.invoke(\n cli.main,\n [\n \"stain-norm\",\n \"--img-input\",\n str(source_img),\n \"--target-input\",\n target_img,\n \"--output-path\",\n str(tmp_path / \"stainnorm_output\"),\n \"--method\",\n \"Test\",\n ],\n )\n\n assert \"Invalid value for '--method'\" in stainnorm_result.output\n assert stainnorm_result.exit_code != 0\n assert isinstance(stainnorm_result.exception, SystemExit)\n",
"\"\"\"Methods of masking tissue and background.\"\"\"\n\nfrom abc import ABC, abstractmethod\n\nimport cv2\nimport numpy as np\nfrom skimage.filters import threshold_otsu\n\nfrom tiatoolbox.utils.misc import objective_power2mpp\n\n\nclass TissueMasker(ABC):\n \"\"\"Base class for tissue maskers.\n\n Takes an image as in put and outputs a mask.\n\n \"\"\"\n\n def __init__(self) -> None:\n super().__init__()\n self.fitted = False\n\n @abstractmethod\n def fit(self, images: np.ndarray, masks=None) -> None:\n \"\"\"Fit the masker to the images and parameters.\n\n Args:\n images (:class:`numpy.ndarray`):\n List of images, usually WSI thumbnails. Expected shape is\n NHWC (number images, height, width, channels).\n masks (:class:`numpy.ndarray`):\n Target/ground-truth masks. Expected shape is NHW (n\n images, height, width).\n\n \"\"\"\n\n @abstractmethod\n def transform(self, images: np.ndarray) -> np.ndarray:\n \"\"\"Create and return a tissue mask.\n\n Args:\n images (:class:`numpy.ndarray`):\n RGB image, usually a WSI thumbnail.\n\n Returns:\n :class:`numpy.ndarray`:\n Map of semantic classes spatially over the WSI\n e.g. regions of tissue vs background.\n\n \"\"\"\n if not self.fitted:\n raise Exception(\"Fit must be called before transform.\")\n\n def fit_transform(self, images: np.ndarray, **kwargs) -> np.ndarray:\n \"\"\"Perform :func:`fit` then :func:`transform`.\n\n Sometimes it can be more optimal to perform both at the same\n time for a single sample. In this case the base implementation\n of :func:`fit` followed by :func:`transform` can be overridden.\n\n Args:\n images (:class:`numpy.ndarray`):\n Image to create mask from.\n **kwargs (dict):\n Other key word arguments passed to fit.\n \"\"\"\n self.fit(images, **kwargs)\n return self.transform(images)\n\n\nclass OtsuTissueMasker(TissueMasker):\n \"\"\"Tissue masker which uses Otsu's method to determine background.\n\n Otsu's method.\n\n Examples:\n >>> from tiatoolbox.tools.tissuemask import OtsuTissueMasker\n >>> masker = OtsuTissueMasker()\n >>> masker.fit(thumbnail)\n >>> masks = masker.transform([thumbnail])\n\n >>> from tiatoolbox.tools.tissuemask import OtsuTissueMasker\n >>> masker = OtsuTissueMasker()\n >>> masks = masker.fit_transform([thumbnail])\n\n \"\"\"\n\n def __init__(self) -> None:\n super().__init__()\n self.threshold = None\n\n def fit(self, images: np.ndarray, masks=None) -> None:\n \"\"\"Find a binary threshold using Otsu's method.\n\n Args:\n images (:class:`numpy.ndarray`):\n List of images with a length 4 shape (N, height, width,\n channels).\n masks (:class:`numpy.ndarray`):\n Unused here, for API consistency.\n\n \"\"\"\n images_shape = np.shape(images)\n if len(images_shape) != 4:\n raise ValueError(\n \"Expected 4 dimensional input shape (N, height, width, 3)\"\n f\" but received shape of {images_shape}.\"\n )\n\n # Convert RGB images to greyscale\n grey_images = [x[..., 0] for x in images]\n if images_shape[-1] == 3:\n grey_images = np.zeros(images_shape[:-1], dtype=np.uint8)\n for n, image in enumerate(images):\n grey_images[n] = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n\n pixels = np.concatenate([np.array(grey).flatten() for grey in grey_images])\n\n # Find Otsu's threshold for all pixels\n self.threshold = threshold_otsu(pixels)\n\n self.fitted = True\n\n def transform(self, images: np.ndarray) -> np.ndarray:\n \"\"\"Create masks using the threshold found during :func:`fit`.\n\n\n Args:\n images (:class:`numpy.ndarray`):\n List of images with a length 4 shape (N, height, width,\n channels).\n\n Returns:\n :class:`numpy.ndarray`:\n List of images with a length 4 shape (N, height, width,\n channels).\n\n \"\"\"\n super().transform(images)\n\n masks = []\n for image in images:\n grey = image[..., 0]\n if len(image.shape) == 3 and image.shape[-1] == 3:\n grey = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n mask = (grey < self.threshold).astype(bool)\n masks.append(mask)\n\n return [mask]\n\n\nclass MorphologicalMasker(OtsuTissueMasker):\n \"\"\"Tissue masker which uses a threshold and simple morphological operations.\n\n This method applies Otsu's threshold before a simple small region\n removal, followed by a morphological dilation. The kernel for the\n dilation is an ellipse of radius 64/mpp unless a value is given for\n kernel_size. MPP is estimated from objective power via\n func:`tiatoolbox.utils.misc.objective_power2mpp` if a power argument\n is given instead of mpp to the initialiser.\n\n For small region removal, the minimum area size defaults to the area\n of the kernel. If no mpp, objective power, or kernel_size arguments\n are given then the kernel defaults to a size of 1x1.\n\n The scale of the morphological operations can also be manually\n specified with the `kernel_size` argument, for example if the\n automatic scale from mpp or objective power is too large or small.\n\n Examples:\n >>> from tiatoolbox.tools.tissuemask import MorphologicalMasker\n >>> from tiatoolbox.wsicore.wsireader import get_wsireader\n >>> wsi = get_wsireader(\"slide.svs\")\n >>> thumbnail = wsi.slide_thumbnail(32, \"mpp\")\n >>> masker = MorphologicalMasker(mpp=32)\n >>> masks = masker.fit_transform([thumbnail])\n\n An example reading a thumbnail from a file where the objective power\n is known:\n\n >>> from tiatoolbox.tools.tissuemask import MorphologicalMasker\n >>> from tiatoolbox.utils.misc import imread\n >>> thumbnail = imread(\"thumbnail.png\")\n >>> masker = MorphologicalMasker(power=1.25)\n >>> masks = masker.fit_transform([thumbnail])\n\n \"\"\"\n\n def __init__(\n self, *, mpp=None, power=None, kernel_size=None, min_region_size=None\n ) -> None:\n \"\"\"Initialise a morphological masker.\n\n Args:\n mpp (float or tuple(float)):\n The microns per-pixel of the image to be masked. Used to\n calculate kernel_size a 64/mpp, optional.\n power (float or tuple(float)):\n The objective power of the image to be masked. Used to\n calculate kernel_size as 64/objective_power2mpp(power),\n optional.\n kernel_size (int or tuple(int)):\n Size of elliptical kernel in x and y, optional.\n min_region_size (int):\n Minimum region size in pixels to consider as foreground.\n Defaults to area of the kernel.\n\n \"\"\"\n super().__init__()\n\n self.min_region_size = min_region_size\n self.threshold = None\n\n # Check for conflicting arguments\n if sum(arg is not None for arg in [mpp, power, kernel_size]) > 1:\n raise ValueError(\"Only one of mpp, power, kernel_size can be given.\")\n\n # Default to kernel_size of (1, 1) if no arguments given\n if all(arg is None for arg in [mpp, power, kernel_size]):\n kernel_size = np.array([1, 1])\n\n # Convert (objective) power approximately to MPP to unify units\n if power is not None:\n mpp = objective_power2mpp(power)\n\n # Convert MPP to an integer kernel_size\n if mpp is not None:\n mpp = np.array(mpp)\n if mpp.size != 2:\n mpp = mpp.repeat(2)\n kernel_size = np.max([32 / mpp, [1, 1]], axis=0)\n\n # Ensure kernel_size is a length 2 numpy array\n kernel_size = np.array(kernel_size)\n if kernel_size.size != 2:\n kernel_size = kernel_size.repeat(2)\n\n # Convert to an integer double/ pair\n self.kernel_size = tuple(np.round(kernel_size).astype(int))\n\n # Create structuring element for morphological operations\n self.kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, self.kernel_size)\n\n # Set min region size to kernel area if None\n if self.min_region_size is None:\n self.min_region_size = np.sum(self.kernel)\n\n def transform(self, images: np.ndarray):\n \"\"\"Create masks using the found threshold followed by morphological operations.\n\n\n Args:\n images (:class:`numpy.ndarray`):\n List of images with a length 4 shape (N, height, width,\n channels).\n\n Returns:\n :class:`numpy.ndarray`:\n List of images with a length 4 shape (N, height, width,\n channels).\n\n \"\"\"\n super().transform(images)\n\n results = []\n for image in images:\n if len(image.shape) == 3 and image.shape[-1] == 3:\n gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n else:\n gray = image\n\n mask = (gray < self.threshold).astype(np.uint8)\n\n _, output, stats, _ = cv2.connectedComponentsWithStats(mask, connectivity=8)\n sizes = stats[1:, -1]\n for i, size in enumerate(sizes):\n if size < self.min_region_size:\n mask[output == i + 1] = 0\n\n mask = cv2.morphologyEx(mask, cv2.MORPH_DILATE, self.kernel)\n\n results.append(mask.astype(bool))\n return results\n"
] | [
[
"numpy.absolute",
"numpy.ones",
"numpy.all",
"numpy.shape",
"numpy.array",
"numpy.zeros"
],
[
"numpy.round",
"numpy.max",
"numpy.shape",
"numpy.array",
"numpy.zeros",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
martindurant/tiled | [
"79eef6fb60964a726c0b43a280c6343b94097640",
"79eef6fb60964a726c0b43a280c6343b94097640",
"79eef6fb60964a726c0b43a280c6343b94097640"
] | [
"tiled/server/router.py",
"tiled/server/core.py",
"tiled/structures/structured_array.py"
] | [
"import dataclasses\nimport inspect\nfrom datetime import datetime, timedelta\nfrom functools import lru_cache\nfrom hashlib import md5\nfrom typing import Any, List, Optional\n\nfrom fastapi import APIRouter, Depends, HTTPException, Query, Request, Response\nfrom pydantic import BaseSettings\n\nfrom .. import __version__\nfrom . import models\nfrom .authentication import (\n API_KEY_COOKIE_NAME,\n check_single_user_api_key,\n get_authenticator,\n)\nfrom .core import (\n APACHE_ARROW_FILE_MIME_TYPE,\n NoEntry,\n PatchedResponse,\n UnsupportedMediaTypes,\n WrongTypeForRoute,\n block,\n construct_data_response,\n construct_entries_response,\n construct_resource,\n entry,\n expected_shape,\n get_query_registry,\n get_serialization_registry,\n json_or_msgpack,\n reader,\n record_timing,\n slice_,\n)\nfrom .settings import get_settings\n\nDEFAULT_PAGE_SIZE = 100\n\n\nrouter = APIRouter()\n\n\[email protected](\"/\", response_model=models.About)\nasync def about(\n request: Request,\n has_single_user_api_key: str = Depends(check_single_user_api_key),\n settings: BaseSettings = Depends(get_settings),\n authenticator=Depends(get_authenticator),\n serialization_registry=Depends(get_serialization_registry),\n query_registry=Depends(get_query_registry),\n):\n # TODO The lazy import of reader modules and serializers means that the\n # lists of formats are not populated until they are first used. Not very\n # helpful for discovery! The registration can be made non-lazy, while the\n # imports of the underlying I/O libraries themselves (openpyxl, pillow,\n # etc.) can remain lazy.\n request.state.endpoint = \"about\"\n if (authenticator is None) and has_single_user_api_key:\n if request.cookies.get(API_KEY_COOKIE_NAME) != settings.single_user_api_key:\n request.state.cookies_to_set.append(\n {\"key\": API_KEY_COOKIE_NAME, \"value\": settings.single_user_api_key}\n )\n if authenticator is None:\n auth_type = \"api_key\"\n auth_endpoint = None\n else:\n if authenticator.handles_credentials:\n auth_type = \"password\"\n auth_endpoint = None\n else:\n auth_type = \"external\"\n auth_endpoint = authenticator.authorization_endpoint\n\n return json_or_msgpack(\n request,\n models.About(\n library_version=__version__,\n api_version=0,\n formats={\n structure_family: list(\n serialization_registry.media_types(structure_family)\n )\n for structure_family in serialization_registry.structure_families\n },\n aliases={\n structure_family: serialization_registry.aliases(structure_family)\n for structure_family in serialization_registry.structure_families\n },\n queries=list(query_registry.name_to_query_type),\n # documentation_url=\".../docs\", # TODO How to get the base URL?\n meta={\"root_path\": request.scope.get(\"root_path\") or \"/\"},\n authentication={\n \"type\": auth_type,\n \"required\": not settings.allow_anonymous_access,\n \"endpoint\": auth_endpoint,\n \"confirmation_message\": getattr(\n authenticator, \"confirmation_message\", None\n ),\n },\n ),\n expires=datetime.utcnow() + timedelta(seconds=600),\n )\n\n\n@lru_cache()\ndef prometheus_registry():\n \"\"\"\n Configure prometheus_client.\n\n This is run the first time the /metrics endpoint is used.\n \"\"\"\n # The multiprocess configuration makes it compatible with gunicorn.\n # https://github.com/prometheus/client_python/#multiprocess-mode-eg-gunicorn\n from prometheus_client import CollectorRegistry\n from prometheus_client.multiprocess import MultiProcessCollector\n\n registry = CollectorRegistry()\n MultiProcessCollector(registry) # This has a side effect, apparently.\n return registry\n\n\[email protected](\"/metrics\")\nasync def metrics(request: Request):\n \"\"\"\n Prometheus metrics\n \"\"\"\n from prometheus_client import CONTENT_TYPE_LATEST, generate_latest\n\n request.state.endpoint = \"metrics\"\n data = generate_latest(prometheus_registry())\n return Response(data, headers={\"Content-Type\": CONTENT_TYPE_LATEST})\n\n\ndef declare_search_router(query_registry):\n \"\"\"\n This is done dynamically at router startup.\n\n We check the registry of known search query types, which is user\n configurable, and use that to define the allowed HTTP query parameters for\n this route.\n \"\"\"\n\n async def search(\n request: Request,\n path: str,\n fields: Optional[List[models.EntryFields]] = Query(list(models.EntryFields)),\n offset: Optional[int] = Query(0, alias=\"page[offset]\"),\n limit: Optional[int] = Query(DEFAULT_PAGE_SIZE, alias=\"page[limit]\"),\n sort: Optional[str] = Query(None),\n entry: Any = Depends(entry),\n query_registry=Depends(get_query_registry),\n **filters,\n ):\n request.state.endpoint = \"search\"\n try:\n resource, metadata_stale_at, must_revalidate = construct_entries_response(\n query_registry,\n entry,\n \"/search\",\n path,\n offset,\n limit,\n fields,\n filters,\n sort,\n _get_base_url(request),\n )\n # We only get one Expires header, so if different parts\n # of this response become stale at different times, we\n # cite the earliest one.\n entries_stale_at = getattr(entry, \"entries_stale_at\", None)\n headers = {}\n if (metadata_stale_at is None) or (entries_stale_at is None):\n expires = None\n else:\n expires = min(metadata_stale_at, entries_stale_at)\n if must_revalidate:\n headers[\"Cache-Control\"] = \"must-revalidate\"\n return json_or_msgpack(\n request,\n resource,\n expires=expires,\n headers=headers,\n )\n except NoEntry:\n raise HTTPException(status_code=404, detail=\"No such entry.\")\n except WrongTypeForRoute as err:\n raise HTTPException(status_code=404, detail=err.args[0])\n\n # Black magic here! FastAPI bases its validation and auto-generated swagger\n # documentation on the signature of the route function. We do not know what\n # that signature should be at compile-time. We only know it once we have a\n # chance to check the user-configurable registry of query types. Therefore,\n # we modify the signature here, at runtime, just before handing it to\n # FastAPI in the usual way.\n\n # When FastAPI calls the function with these added parameters, they will be\n # accepted via **filters.\n\n # Make a copy of the original parameters.\n signature = inspect.signature(search)\n parameters = list(signature.parameters.values())\n # Drop the **filters parameter from the signature.\n del parameters[-1]\n # Add a parameter for each field in each type of query.\n for name, query in query_registry.name_to_query_type.items():\n for field in dataclasses.fields(query):\n # The structured \"alias\" here is based on\n # https://mglaman.dev/blog/using-json-router-query-your-search-router-indexes\n if getattr(field.type, \"__origin__\", None) is list:\n field_type = str\n else:\n field_type = field.type\n injected_parameter = inspect.Parameter(\n name=f\"filter___{name}___{field.name}\",\n kind=inspect.Parameter.POSITIONAL_OR_KEYWORD,\n default=Query(None, alias=f\"filter[{name}][condition][{field.name}]\"),\n annotation=Optional[List[field_type]],\n )\n parameters.append(injected_parameter)\n search.__signature__ = signature.replace(parameters=parameters)\n # End black magic\n\n # Register the search route.\n router = APIRouter()\n router.get(\"/search\", response_model=models.Response, include_in_schema=False)(\n search\n )\n router.get(\"/search/{path:path}\", response_model=models.Response)(search)\n return router\n\n\[email protected](\"/metadata/{path:path}\", response_model=models.Response)\nasync def metadata(\n request: Request,\n path: str,\n fields: Optional[List[models.EntryFields]] = Query(list(models.EntryFields)),\n entry: Any = Depends(entry),\n root_path: str = Query(None),\n settings: BaseSettings = Depends(get_settings),\n):\n \"Fetch the metadata for one Tree or Reader.\"\n\n request.state.endpoint = \"metadata\"\n base_url = _get_base_url(request)\n path_parts = [segment for segment in path.split(\"/\") if segment]\n resource = construct_resource(base_url, path_parts, entry, fields)\n meta = (\n {\"root_path\": request.scope.get(\"root_path\") or \"/\"}\n if (root_path is not None)\n else {}\n )\n return json_or_msgpack(\n request,\n models.Response(data=resource, meta=meta),\n expires=getattr(entry, \"metadata_stale_at\", None),\n )\n\n\[email protected](\"/entries/{path:path}\", response_model=models.Response)\nasync def entries(\n request: Request,\n path: Optional[str],\n offset: Optional[int] = Query(0, alias=\"page[offset]\"),\n limit: Optional[int] = Query(DEFAULT_PAGE_SIZE, alias=\"page[limit]\"),\n sort: Optional[str] = Query(None),\n fields: Optional[List[models.EntryFields]] = Query(list(models.EntryFields)),\n entry: Any = Depends(entry),\n query_registry=Depends(get_query_registry),\n):\n \"List the entries in a Tree, which may be sub-Trees or Readers.\"\n\n request.state.endpoint = \"entries\"\n try:\n resource, metadata_stale_at, must_revalidate = construct_entries_response(\n query_registry,\n entry,\n \"/entries\",\n path,\n offset,\n limit,\n fields,\n {},\n sort,\n _get_base_url(request),\n )\n # We only get one Expires header, so if different parts\n # of this response become stale at different times, we\n # cite the earliest one.\n entries_stale_at = getattr(entry, \"entries_stale_at\", None)\n if (metadata_stale_at is None) or (entries_stale_at is None):\n expires = None\n else:\n expires = min(metadata_stale_at, entries_stale_at)\n headers = {}\n if must_revalidate:\n headers[\"Cache-Control\"] = \"must-revalidate\"\n return json_or_msgpack(request, resource, expires=expires, headers=headers)\n except NoEntry:\n raise HTTPException(status_code=404, detail=\"No such entry.\")\n except WrongTypeForRoute as err:\n raise HTTPException(status_code=404, detail=err.args[0])\n\n\[email protected](\n \"/array/block/{path:path}\", response_model=models.Response, name=\"array block\"\n)\ndef array_block(\n request: Request,\n reader=Depends(reader),\n block=Depends(block),\n slice=Depends(slice_),\n expected_shape=Depends(expected_shape),\n format: Optional[str] = None,\n serialization_registry=Depends(get_serialization_registry),\n):\n \"\"\"\n Fetch a chunk of array-like data.\n \"\"\"\n if reader.structure_family != \"array\":\n raise HTTPException(\n status_code=404,\n detail=f\"Cannot read {reader.structure_family} structure with /array/block route.\",\n )\n if block == ():\n # Handle special case of numpy scalar.\n if reader.macrostructure().shape != ():\n raise HTTPException(\n status_code=400,\n detail=f\"Requested scalar but shape is {reader.macrostructure().shape}\",\n )\n with record_timing(request.state.metrics, \"read\"):\n array = reader.read()\n else:\n try:\n with record_timing(request.state.metrics, \"read\"):\n array = reader.read_block(block, slice=slice)\n except IndexError:\n raise HTTPException(status_code=400, detail=\"Block index out of range\")\n if (expected_shape is not None) and (expected_shape != array.shape):\n raise HTTPException(\n status_code=400,\n detail=f\"The expected_shape {expected_shape} does not match the actual shape {array.shape}\",\n )\n try:\n with record_timing(request.state.metrics, \"pack\"):\n return construct_data_response(\n \"array\",\n serialization_registry,\n array,\n reader.metadata,\n request,\n format,\n expires=getattr(reader, \"content_stale_at\", None),\n )\n except UnsupportedMediaTypes as err:\n # raise HTTPException(status_code=406, detail=\", \".join(err.supported))\n raise HTTPException(status_code=406, detail=err.args[0])\n\n\[email protected](\n \"/array/full/{path:path}\", response_model=models.Response, name=\"full array\"\n)\ndef array_full(\n request: Request,\n reader=Depends(reader),\n slice=Depends(slice_),\n expected_shape=Depends(expected_shape),\n format: Optional[str] = None,\n serialization_registry=Depends(get_serialization_registry),\n):\n \"\"\"\n Fetch a slice of array-like data.\n \"\"\"\n if reader.structure_family != \"array\":\n raise HTTPException(\n status_code=404,\n detail=f\"Cannot read {reader.structure_family} structure with /array/full route.\",\n )\n # Deferred import because this is not a required dependency of the server\n # for some use cases.\n import numpy\n\n try:\n with record_timing(request.state.metrics, \"read\"):\n array = reader.read(slice)\n array = numpy.asarray(array) # Force dask or PIMS or ... to do I/O.\n except IndexError:\n raise HTTPException(status_code=400, detail=\"Block index out of range\")\n if (expected_shape is not None) and (expected_shape != array.shape):\n raise HTTPException(\n status_code=400,\n detail=f\"The expected_shape {expected_shape} does not match the actual shape {array.shape}\",\n )\n try:\n with record_timing(request.state.metrics, \"pack\"):\n return construct_data_response(\n \"array\",\n serialization_registry,\n array,\n reader.metadata,\n request,\n format,\n expires=getattr(reader, \"content_stale_at\", None),\n )\n except UnsupportedMediaTypes as err:\n raise HTTPException(status_code=406, detail=err.args[0])\n\n\[email protected](\n \"/structured_array_generic/block/{path:path}\",\n response_model=models.Response,\n name=\"structured array (generic) block\",\n)\ndef structured_array_generic_block(\n request: Request,\n reader=Depends(reader),\n block=Depends(block),\n slice=Depends(slice_),\n expected_shape=Depends(expected_shape),\n format: Optional[str] = None,\n serialization_registry=Depends(get_serialization_registry),\n):\n \"\"\"\n Fetch a chunk of array-like data.\n \"\"\"\n if reader.structure_family != \"structured_array_generic\":\n raise HTTPException(\n status_code=404,\n detail=f\"Cannot read {reader.structure_family} structure with /structured_array_generic/block route.\",\n )\n if block == ():\n # Handle special case of numpy scalar.\n if reader.macrostructure().shape != ():\n raise HTTPException(\n status_code=400,\n detail=f\"Requested scalar but shape is {reader.macrostructure().shape}\",\n )\n array = reader.read()\n else:\n try:\n array = reader.read_block(block, slice=slice)\n except IndexError:\n raise HTTPException(status_code=400, detail=\"Block index out of range\")\n if (expected_shape is not None) and (expected_shape != array.shape):\n raise HTTPException(\n status_code=400,\n detail=f\"The expected_shape {expected_shape} does not match the actual shape {array.shape}\",\n )\n try:\n return construct_data_response(\n \"structured_array_generic\",\n serialization_registry,\n array,\n reader.metadata,\n request,\n format,\n expires=getattr(reader, \"content_stale_at\", None),\n )\n except UnsupportedMediaTypes as err:\n raise HTTPException(status_code=406, detail=err.args[0])\n\n\[email protected](\n \"/structured_array_tabular/block/{path:path}\",\n response_model=models.Response,\n name=\"structured array (tabular) block\",\n)\ndef structured_array_tabular_block(\n request: Request,\n reader=Depends(reader),\n block=Depends(block),\n slice=Depends(slice_),\n expected_shape=Depends(expected_shape),\n format: Optional[str] = None,\n serialization_registry=Depends(get_serialization_registry),\n):\n \"\"\"\n Fetch a chunk of array-like data.\n \"\"\"\n if reader.structure_family != \"structured_array_tabular\":\n raise HTTPException(\n status_code=404,\n detail=f\"Cannot read {reader.structure_family} structure with /structured_array_tabular/block route.\",\n )\n if block == ():\n # Handle special case of numpy scalar.\n if reader.macrostructure().shape != ():\n raise HTTPException(\n status_code=400,\n detail=f\"Requested scalar but shape is {reader.macrostructure().shape}\",\n )\n array = reader.read()\n else:\n try:\n array = reader.read_block(block, slice=slice)\n except IndexError:\n raise HTTPException(status_code=400, detail=\"Block index out of range\")\n if (expected_shape is not None) and (expected_shape != array.shape):\n raise HTTPException(\n status_code=400,\n detail=f\"The expected_shape {expected_shape} does not match the actual shape {array.shape}\",\n )\n try:\n return construct_data_response(\n \"structured_array_tabular\",\n serialization_registry,\n array,\n reader.metadata,\n request,\n format,\n expires=getattr(reader, \"content_stale_at\", None),\n )\n except UnsupportedMediaTypes as err:\n raise HTTPException(status_code=406, detail=err.args[0])\n\n\[email protected](\n \"/structured_array_tabular/full/{path:path}\",\n response_model=models.Response,\n name=\"structure array (tabular) full array\",\n)\ndef structured_array_tabular_full(\n request: Request,\n reader=Depends(reader),\n slice=Depends(slice_),\n expected_shape=Depends(expected_shape),\n format: Optional[str] = None,\n serialization_registry=Depends(get_serialization_registry),\n):\n \"\"\"\n Fetch a slice of array-like data.\n \"\"\"\n if reader.structure_family != \"structured_array_tabular\":\n raise HTTPException(\n status_code=404,\n detail=f\"Cannot read {reader.structure_family} structure with /structured_array_tabular/full route.\",\n )\n # Deferred import because this is not a required dependency of the server\n # for some use cases.\n import numpy\n\n try:\n array = reader.read()\n if slice:\n array = array[slice]\n array = numpy.asarray(array) # Force dask or PIMS or ... to do I/O.\n except IndexError:\n raise HTTPException(status_code=400, detail=\"Block index out of range\")\n if (expected_shape is not None) and (expected_shape != array.shape):\n raise HTTPException(\n status_code=400,\n detail=f\"The expected_shape {expected_shape} does not match the actual shape {array.shape}\",\n )\n try:\n return construct_data_response(\n \"structured_array_tabular\",\n serialization_registry,\n array,\n reader.metadata,\n request,\n format,\n expires=getattr(reader, \"content_stale_at\", None),\n )\n except UnsupportedMediaTypes as err:\n raise HTTPException(status_code=406, detail=err.args[0])\n\n\[email protected](\n \"/structured_array_generic/full/{path:path}\",\n response_model=models.Response,\n name=\"structured array (generic) full array\",\n)\ndef structured_array_generic_full(\n request: Request,\n reader=Depends(reader),\n slice=Depends(slice_),\n expected_shape=Depends(expected_shape),\n format: Optional[str] = None,\n serialization_registry=Depends(get_serialization_registry),\n):\n \"\"\"\n Fetch a slice of array-like data.\n \"\"\"\n if reader.structure_family != \"structured_array_generic\":\n raise HTTPException(\n status_code=404,\n detail=f\"Cannot read {reader.structure_family} structure with /structured_array_generic/full route.\",\n )\n # Deferred import because this is not a required dependency of the server\n # for some use cases.\n import numpy\n\n try:\n array = reader.read()\n if slice:\n array = array[slice]\n array = numpy.asarray(array) # Force dask or PIMS or ... to do I/O.\n except IndexError:\n raise HTTPException(status_code=400, detail=\"Block index out of range\")\n if (expected_shape is not None) and (expected_shape != array.shape):\n raise HTTPException(\n status_code=400,\n detail=f\"The expected_shape {expected_shape} does not match the actual shape {array.shape}\",\n )\n try:\n return construct_data_response(\n \"structured_array_generic\",\n serialization_registry,\n array,\n reader.metadata,\n request,\n format,\n expires=getattr(reader, \"content_stale_at\", None),\n )\n except UnsupportedMediaTypes as err:\n raise HTTPException(status_code=406, detail=err.args[0])\n\n\[email protected](\n \"/dataframe/meta/{path:path}\", response_model=models.Response, name=\"dataframe meta\"\n)\ndef dataframe_meta(\n request: Request,\n reader=Depends(reader),\n format: Optional[str] = None,\n serialization_registry=Depends(get_serialization_registry),\n):\n \"\"\"\n Fetch the Apache Arrow serialization of (an empty) DataFrame with this structure.\n \"\"\"\n request.state.endpoint = \"data\"\n if reader.structure_family != \"dataframe\":\n raise HTTPException(\n status_code=404,\n detail=f\"Cannot read {reader.structure_family} structure with /dataframe/meta route.\",\n )\n meta = reader.microstructure().meta\n with record_timing(request.state.metrics, \"pack\"):\n content = serialization_registry(\n \"dataframe\", APACHE_ARROW_FILE_MIME_TYPE, meta, {}\n )\n headers = {\"ETag\": md5(content).hexdigest()}\n return PatchedResponse(\n content, media_type=APACHE_ARROW_FILE_MIME_TYPE, headers=headers\n )\n\n\[email protected](\n \"/dataframe/divisions/{path:path}\",\n response_model=models.Response,\n name=\"dataframe divisions\",\n)\ndef dataframe_divisions(\n request: Request,\n reader=Depends(reader),\n format: Optional[str] = None,\n serialization_registry=Depends(get_serialization_registry),\n):\n \"\"\"\n Fetch the Apache Arrow serialization of the index values at the partition edges.\n \"\"\"\n request.state.endpoint = \"data\"\n if reader.structure_family != \"dataframe\":\n raise HTTPException(\n status_code=404,\n detail=f\"Cannot read {reader.structure_family} structure with /dataframe/division route.\",\n )\n import pandas\n\n divisions = reader.microstructure().divisions\n # divisions is a tuple. Wrap it in a DataFrame so\n # that we can easily serialize it with Arrow in the normal way.\n divisions_wrapped_in_df = pandas.DataFrame({\"divisions\": list(divisions)})\n with record_timing(request.state.metrics, \"pack\"):\n content = serialization_registry(\n \"dataframe\", APACHE_ARROW_FILE_MIME_TYPE, divisions_wrapped_in_df, {}\n )\n headers = {\"ETag\": md5(content).hexdigest()}\n return PatchedResponse(\n content, media_type=APACHE_ARROW_FILE_MIME_TYPE, headers=headers\n )\n\n\[email protected](\n \"/dataframe/partition/{path:path}\",\n response_model=models.Response,\n name=\"dataframe partition\",\n)\ndef dataframe_partition(\n request: Request,\n partition: int,\n reader=Depends(reader),\n column: Optional[List[str]] = Query(None, min_length=1),\n format: Optional[str] = None,\n serialization_registry=Depends(get_serialization_registry),\n):\n \"\"\"\n Fetch a partition (continuous block of rows) from a DataFrame.\n \"\"\"\n if reader.structure_family != \"dataframe\":\n raise HTTPException(\n status_code=404,\n detail=f\"Cannot read {reader.structure_family} structure with /dataframe/parition route.\",\n )\n try:\n # The singular/plural mismatch here of \"columns\" and \"column\" is\n # due to the ?column=A&column=B&column=C... encodes in a URL.\n with record_timing(request.state.metrics, \"read\"):\n df = reader.read_partition(partition, columns=column)\n except IndexError:\n raise HTTPException(status_code=400, detail=\"Partition out of range\")\n except KeyError as err:\n (key,) = err.args\n raise HTTPException(status_code=400, detail=f\"No such column {key}.\")\n try:\n with record_timing(request.state.metrics, \"pack\"):\n return construct_data_response(\n \"dataframe\",\n serialization_registry,\n df,\n reader.metadata,\n request,\n format,\n expires=getattr(reader, \"content_stale_at\", None),\n )\n except UnsupportedMediaTypes as err:\n raise HTTPException(status_code=406, detail=err.args[0])\n\n\[email protected](\n \"/dataframe/full/{path:path}\", response_model=models.Response, name=\"full dataframe\"\n)\ndef dataframe_full(\n request: Request,\n reader=Depends(reader),\n column: Optional[List[str]] = Query(None, min_length=1),\n format: Optional[str] = None,\n serialization_registry=Depends(get_serialization_registry),\n):\n \"\"\"\n Fetch all the rows of DataFrame.\n \"\"\"\n if reader.structure_family != \"dataframe\":\n raise HTTPException(\n status_code=404,\n detail=f\"Cannot read {reader.structure_family} structure with /dataframe/full route.\",\n )\n\n specs = getattr(reader, \"specs\", [])\n\n try:\n # The singular/plural mismatch here of \"columns\" and \"column\" is\n # due to the ?column=A&column=B&column=C... encodes in a URL.\n with record_timing(request.state.metrics, \"read\"):\n df = reader.read(columns=column)\n except KeyError as err:\n (key,) = err.args\n raise HTTPException(status_code=400, detail=f\"No such column {key}.\")\n try:\n with record_timing(request.state.metrics, \"pack\"):\n return construct_data_response(\n \"dataframe\",\n serialization_registry,\n df,\n reader.metadata,\n request,\n format,\n specs,\n expires=getattr(reader, \"content_stale_at\", None),\n )\n except UnsupportedMediaTypes as err:\n raise HTTPException(status_code=406, detail=err.args[0])\n\n\[email protected](\n \"/variable/block/{path:path}\",\n response_model=models.Response,\n name=\"xarray.Variable block\",\n)\ndef variable_block(\n request: Request,\n reader=Depends(reader),\n block=Depends(block),\n slice=Depends(slice_),\n expected_shape=Depends(expected_shape),\n format: Optional[str] = None,\n serialization_registry=Depends(get_serialization_registry),\n):\n \"\"\"\n Fetch a chunk of array-like data from an xarray.Variable.\n \"\"\"\n if reader.structure_family != \"variable\":\n raise HTTPException(\n status_code=404,\n detail=f\"Cannot read {reader.structure_family} structure with /variable/block route.\",\n )\n try:\n # Lookup block on the `data` attribute of the Variable.\n with record_timing(request.state.metrics, \"read\"):\n array = reader.read_block(block, slice=slice)\n if slice:\n array = array[slice]\n except IndexError:\n raise HTTPException(status_code=400, detail=\"Block index out of range\")\n if (expected_shape is not None) and (expected_shape != array.shape):\n raise HTTPException(\n status_code=400,\n detail=f\"The expected_shape {expected_shape} does not match the actual shape {array.shape}\",\n )\n try:\n with record_timing(request.state.metrics, \"pack\"):\n return construct_data_response(\n \"array\",\n serialization_registry,\n array,\n reader.metadata,\n request,\n format,\n expires=getattr(reader, \"content_stale_at\", None),\n )\n except UnsupportedMediaTypes as err:\n raise HTTPException(status_code=406, detail=err.args[0])\n\n\[email protected](\n \"/variable/full/{path:path}\",\n response_model=models.Response,\n name=\"full xarray.Variable\",\n)\ndef variable_full(\n request: Request,\n reader=Depends(reader),\n expected_shape=Depends(expected_shape),\n format: Optional[str] = None,\n serialization_registry=Depends(get_serialization_registry),\n):\n \"\"\"\n Fetch a full xarray.Variable.\n \"\"\"\n if reader.structure_family != \"variable\":\n raise HTTPException(\n status_code=404,\n detail=f\"Cannot read {reader.structure_family} structure with /variable/full route.\",\n )\n with record_timing(request.state.metrics, \"read\"):\n array = reader.read()\n if (expected_shape is not None) and (expected_shape != array.shape):\n raise HTTPException(\n status_code=400,\n detail=f\"The expected_shape {expected_shape} does not match the actual shape {array.shape}\",\n )\n try:\n with record_timing(request.state.metrics, \"pack\"):\n return construct_data_response(\n \"array\",\n serialization_registry,\n array,\n reader.metadata,\n request,\n format,\n expires=getattr(reader, \"content_stale_at\", None),\n )\n except UnsupportedMediaTypes as err:\n raise HTTPException(status_code=406, detail=err.args[0])\n\n\[email protected](\n \"/data_array/variable/full/{path:path}\",\n response_model=models.Response,\n name=\"full xarray.Variable from within an xarray.DataArray\",\n)\ndef data_array_variable_full(\n request: Request,\n reader=Depends(reader),\n coord: Optional[str] = Query(None, min_length=1),\n expected_shape=Depends(expected_shape),\n format: Optional[str] = None,\n serialization_registry=Depends(get_serialization_registry),\n):\n \"\"\"\n Fetch a chunk from an xarray.DataArray.\n \"\"\"\n if reader.structure_family != \"data_array\":\n raise HTTPException(\n status_code=404,\n detail=f\"Cannot read {reader.structure_family} structure with /data_array/variable/full route.\",\n )\n # TODO Should read() accept a `coord` argument?\n with record_timing(request.state.metrics, \"read\"):\n array = reader.read()\n if coord is not None:\n try:\n array = array.coords[coord]\n except KeyError:\n raise HTTPException(status_code=400, detail=f\"No such coordinate {coord}.\")\n if (expected_shape is not None) and (expected_shape != array.shape):\n raise HTTPException(\n status_code=400,\n detail=f\"The expected_shape {expected_shape} does not match the actual shape {array.shape}\",\n )\n try:\n with record_timing(request.state.metrics, \"pack\"):\n return construct_data_response(\n \"array\",\n serialization_registry,\n array,\n reader.metadata,\n request,\n format,\n expires=getattr(reader, \"content_stale_at\", None),\n )\n except UnsupportedMediaTypes as err:\n raise HTTPException(status_code=406, detail=err.args[0])\n\n\[email protected](\n \"/data_array/block/{path:path}\",\n response_model=models.Response,\n name=\"xarray.DataArray block\",\n)\ndef data_array_block(\n request: Request,\n reader=Depends(reader),\n block=Depends(block),\n coord: Optional[str] = Query(None, min_length=1),\n slice=Depends(slice_),\n expected_shape=Depends(expected_shape),\n format: Optional[str] = None,\n serialization_registry=Depends(get_serialization_registry),\n):\n \"\"\"\n Fetch a chunk from an xarray.DataArray.\n \"\"\"\n if reader.structure_family != \"data_array\":\n raise HTTPException(\n status_code=404,\n detail=f\"Cannot read {reader.structure_family} structure with /data_array/block route.\",\n )\n try:\n with record_timing(request.state.metrics, \"read\"):\n array = reader.read_block(block, coord, slice=slice)\n except IndexError:\n raise HTTPException(status_code=400, detail=\"Block index out of range\")\n except KeyError:\n if coord is not None:\n raise HTTPException(status_code=400, detail=f\"No such coordinate {coord}.\")\n else:\n raise\n if (expected_shape is not None) and (expected_shape != array.shape):\n raise HTTPException(\n status_code=400,\n detail=f\"The expected_shape {expected_shape} does not match the actual shape {array.shape}\",\n )\n try:\n with record_timing(request.state.metrics, \"pack\"):\n return construct_data_response(\n \"array\",\n serialization_registry,\n array,\n reader.metadata,\n request,\n format,\n expires=getattr(reader, \"content_stale_at\", None),\n )\n except UnsupportedMediaTypes as err:\n raise HTTPException(status_code=406, detail=err.args[0])\n\n\[email protected](\n \"/dataset/block/{path:path}\",\n response_model=models.Response,\n name=\"xarray.Dataset block\",\n)\ndef dataset_block(\n request: Request,\n reader=Depends(reader),\n block=Depends(block),\n variable: Optional[str] = Query(None, min_length=1),\n coord: Optional[str] = Query(None, min_length=1),\n slice=Depends(slice_),\n expected_shape=Depends(expected_shape),\n format: Optional[str] = None,\n serialization_registry=Depends(get_serialization_registry),\n):\n \"\"\"\n Fetch a chunk from an xarray.Dataset.\n \"\"\"\n if reader.structure_family != \"dataset\":\n raise HTTPException(\n status_code=404,\n detail=f\"Cannot read {reader.structure_family} structure with /dataset/block route.\",\n )\n try:\n with record_timing(request.state.metrics, \"read\"):\n array = reader.read_block(variable, block, coord, slice=slice)\n except IndexError:\n raise HTTPException(status_code=400, detail=\"Block index out of range\")\n except KeyError:\n if coord is None:\n raise HTTPException(status_code=400, detail=f\"No such variable {variable}.\")\n if variable is None:\n raise HTTPException(status_code=400, detail=f\"No such coordinate {coord}.\")\n raise HTTPException(\n status_code=400,\n detail=f\"No such coordinate {coord} and/or variable {variable}.\",\n )\n if (expected_shape is not None) and (expected_shape != array.shape):\n raise HTTPException(\n status_code=400,\n detail=f\"The expected_shape {expected_shape} does not match the actual shape {array.shape}\",\n )\n try:\n with record_timing(request.state.metrics, \"pack\"):\n return construct_data_response(\n \"array\",\n serialization_registry,\n array,\n reader.metadata,\n request,\n format,\n expires=getattr(reader, \"content_stale_at\", None),\n )\n except UnsupportedMediaTypes as err:\n raise HTTPException(status_code=406, detail=err.args[0])\n\n\[email protected](\n \"/dataset/data_var/full/{path:path}\",\n response_model=models.Response,\n name=\"full xarray.Dataset data variable\",\n)\ndef dataset_data_var_full(\n request: Request,\n reader=Depends(reader),\n variable: str = Query(..., min_length=1),\n coord: Optional[str] = Query(None, min_length=1),\n expected_shape=Depends(expected_shape),\n format: Optional[str] = None,\n serialization_registry=Depends(get_serialization_registry),\n):\n \"\"\"\n Fetch a full xarray.Variable from within an xarray.Dataset.\n \"\"\"\n if reader.structure_family != \"dataset\":\n raise HTTPException(\n status_code=404,\n detail=f\"Cannot read {reader.structure_family} structure with /dataset/data_var/full route.\",\n )\n try:\n with record_timing(request.state.metrics, \"read\"):\n array = reader.read_variable(variable).data\n except KeyError:\n raise HTTPException(status_code=400, detail=f\"No such variable {variable}.\")\n if coord is not None:\n try:\n array = array.coords[coord].data\n except KeyError:\n raise HTTPException(status_code=400, detail=f\"No such coordinate {coord}.\")\n if (expected_shape is not None) and (expected_shape != array.shape):\n raise HTTPException(\n status_code=400,\n detail=f\"The expected_shape {expected_shape} does not match the actual shape {array.shape}\",\n )\n try:\n with record_timing(request.state.metrics, \"pack\"):\n return construct_data_response(\n \"array\",\n serialization_registry,\n array,\n reader.metadata,\n request,\n format,\n expires=getattr(reader, \"content_stale_at\", None),\n )\n except UnsupportedMediaTypes as err:\n raise HTTPException(status_code=406, detail=err.args[0])\n\n\[email protected](\n \"/dataset/coord/full/{path:path}\",\n response_model=models.Response,\n name=\"full xarray.Dataset coordinate\",\n)\ndef dataset_coord_full(\n request: Request,\n reader=Depends(reader),\n coord: str = Query(..., min_length=1),\n expected_shape=Depends(expected_shape),\n format: Optional[str] = None,\n serialization_registry=Depends(get_serialization_registry),\n):\n \"\"\"\n Fetch a full coordinate from within an xarray.Dataset.\n \"\"\"\n if reader.structure_family != \"dataset\":\n raise HTTPException(\n status_code=404,\n detail=f\"Cannot read {reader.structure_family} structure with /dataset/coord/full route.\",\n )\n try:\n with record_timing(request.state.metrics, \"read\"):\n array = reader.read_variable(coord).data\n except KeyError:\n raise HTTPException(status_code=400, detail=f\"No such coordinate {coord}.\")\n if (expected_shape is not None) and (expected_shape != array.shape):\n raise HTTPException(\n status_code=400,\n detail=f\"The expected_shape {expected_shape} does not match the actual shape {array.shape}\",\n )\n try:\n with record_timing(request.state.metrics, \"pack\"):\n return construct_data_response(\n \"array\",\n serialization_registry,\n array,\n reader.metadata,\n request,\n format,\n expires=getattr(reader, \"content_stale_at\", None),\n )\n except UnsupportedMediaTypes as err:\n raise HTTPException(status_code=406, detail=err.args[0])\n\n\[email protected](\n \"/dataset/full/{path:path}\",\n response_model=models.Response,\n name=\"full xarray.Dataset\",\n)\ndef dataset_full(\n request: Request,\n reader=Depends(reader),\n variable: Optional[List[str]] = Query(None, min_length=1),\n format: Optional[str] = None,\n serialization_registry=Depends(get_serialization_registry),\n):\n \"\"\"\n Fetch a full coordinate from within an xarray.Dataset.\n \"\"\"\n if reader.structure_family != \"dataset\":\n raise HTTPException(\n status_code=404,\n detail=f\"Cannot read {reader.structure_family} structure with /dataset/full route.\",\n )\n try:\n # The singular/plural mismatch here of \"variables\" and \"variable\" is\n # due to the ?variable=A&variable=B&variable=C... encodes in a URL.\n with record_timing(request.state.metrics, \"read\"):\n dataset = reader.read(variables=variable)\n except KeyError as err:\n (key,) = err.args\n raise HTTPException(status_code=400, detail=f\"No such variable {key}.\")\n try:\n with record_timing(request.state.metrics, \"pack\"):\n return construct_data_response(\n \"dataset\",\n serialization_registry,\n dataset,\n reader.metadata,\n request,\n format,\n expires=getattr(reader, \"content_stale_at\", None),\n )\n except UnsupportedMediaTypes as err:\n raise HTTPException(status_code=406, detail=err.args[0])\n\n\ndef _get_base_url(request):\n # Confusing thing:\n # An httpx.URL treats netloc as bytes (in 0.18.2)\n # but starlette.datastructures.URL treats netloc as str.\n # It seems possible starlette could change their minds in\n # the future to align with httpx, so we will accept either\n # str or bytes here.\n client_specified_base_url = request.headers.get(\"x-base-url\")\n if client_specified_base_url is not None:\n return client_specified_base_url\n url = request.url\n root_path = request.scope.get(\"root_path\") or \"/\"\n if isinstance(url.netloc, bytes):\n netloc_str = url.netloc.decode()\n else:\n netloc_str = url.netloc\n return f\"{url.scheme}://{netloc_str}{root_path}\"\n",
"import abc\nimport collections.abc\nimport contextlib\nimport dataclasses\nimport itertools\nimport math\nimport operator\nimport re\nimport sys\nimport time\nfrom collections import defaultdict\nfrom datetime import datetime, timedelta\nfrom functools import lru_cache\nfrom hashlib import md5\nfrom typing import Any, Optional\n\nimport dateutil.tz\nimport msgpack\nimport orjson\nimport pydantic\nfrom fastapi import Depends, HTTPException, Query, Request, Response\nfrom starlette.responses import JSONResponse, Send, StreamingResponse\n\n# These modules are not directly used, but they register things on import.\nfrom .. import queries\nfrom ..media_type_registration import (\n serialization_registry as default_serialization_registry,\n)\nfrom ..queries import KeyLookup, QueryValueError\nfrom ..query_registration import query_registry as default_query_registry\nfrom ..trees.in_memory import Tree as TreeInMemory\nfrom ..utils import (\n APACHE_ARROW_FILE_MIME_TYPE,\n SerializationError,\n UnsupportedShape,\n modules_available,\n)\nfrom . import models\nfrom .authentication import get_current_user\nfrom .etag import tokenize\n\ndel queries\nif modules_available(\"numpy\", \"dask.array\"):\n from ..structures import array as _array # noqa: F401\n\n del _array\nif modules_available(\"pandas\", \"pyarrow\", \"dask.dataframe\"):\n from ..structures import dataframe as _dataframe # noqa: F401\n\n del _dataframe\nif modules_available(\"xarray\"):\n from ..structures import xarray as _xarray # noqa: F401\n\n del _xarray\n\n\n_FILTER_PARAM_PATTERN = re.compile(r\"filter___(?P<name>.*)___(?P<field>[^\\d\\W][\\w\\d]+)\")\n_LOCAL_TZINFO = dateutil.tz.gettz()\n\n\n@lru_cache(1)\ndef get_query_registry():\n \"This may be overridden via dependency_overrides.\"\n return default_query_registry\n\n\n@lru_cache(1)\ndef get_serialization_registry():\n \"This may be overridden via dependency_overrides.\"\n return default_serialization_registry\n\n\ndef get_root_tree():\n raise NotImplementedError(\n \"This should be overridden via dependency_overrides. \"\n \"See tiled.server.app.serve_tree().\"\n )\n\n\ndef entry(\n path: str,\n request: Request,\n current_user: str = Depends(get_current_user),\n root_tree: pydantic.BaseSettings = Depends(get_root_tree),\n):\n path_parts = [segment for segment in path.split(\"/\") if segment]\n entry = root_tree.authenticated_as(current_user)\n try:\n # Traverse into sub-tree(s).\n for segment in path_parts:\n try:\n with record_timing(request.state.metrics, \"acl\"):\n unauthenticated_entry = entry[segment]\n except (KeyError, TypeError):\n raise NoEntry(path_parts)\n # TODO Update this when Tree has structure_family == \"tree\".\n if not hasattr(unauthenticated_entry, \"structure_family\"):\n with record_timing(request.state.metrics, \"acl\"):\n entry = unauthenticated_entry.authenticated_as(current_user)\n else:\n entry = unauthenticated_entry\n return entry\n except NoEntry:\n raise HTTPException(status_code=404, detail=f\"No such entry: {path_parts}\")\n\n\ndef reader(\n entry: Any = Depends(entry),\n):\n \"Specify a path parameter and use it to look up a reader.\"\n if not isinstance(entry, DuckReader):\n raise HTTPException(status_code=404, detail=\"This is not a Reader.\")\n return entry\n\n\ndef block(\n # Ellipsis as the \"default\" tells FastAPI to make this parameter required.\n block: str = Query(..., regex=\"^[0-9]*(,[0-9]+)*$\"),\n):\n \"Specify and parse a block index parameter.\"\n if not block:\n return ()\n return tuple(map(int, block.split(\",\")))\n\n\ndef expected_shape(\n expected_shape: Optional[str] = Query(\n None, min_length=1, regex=\"^[0-9]+(,[0-9]+)*$|^scalar$\"\n ),\n):\n \"Specify and parse an expected_shape parameter.\"\n if expected_shape is None:\n return\n if expected_shape == \"scalar\":\n return ()\n return tuple(map(int, expected_shape.split(\",\")))\n\n\ndef slice_(\n slice: str = Query(None, regex=\"^[0-9,:]*$\"),\n):\n \"Specify and parse a block index parameter.\"\n import numpy\n\n # IMPORTANT We are eval-ing a user-provider string here so we need to be\n # very careful about locking down what can be in it. The regex above\n # excludes any letters or operators, so it is not possible to execute\n # functions or expensive arithmetic.\n return tuple(\n [\n eval(f\"numpy.s_[{dim!s}]\", {\"numpy\": numpy})\n for dim in (slice or \"\").split(\",\")\n if dim\n ]\n )\n\n\ndef len_or_approx(tree):\n \"\"\"\n Prefer approximate length if implemented. (It's cheaper.)\n \"\"\"\n try:\n return operator.length_hint(tree)\n except TypeError:\n return len(tree)\n\n\ndef pagination_links(route, path_parts, offset, limit, length_hint):\n path_str = \"/\".join(path_parts)\n links = {\n \"self\": f\"{route}/{path_str}?page[offset]={offset}&page[limit]={limit}\",\n # These are conditionally overwritten below.\n \"first\": None,\n \"last\": None,\n \"next\": None,\n \"prev\": None,\n }\n if limit:\n last_page = math.floor(length_hint / limit) * limit\n links.update(\n {\n \"first\": f\"{route}/{path_str}?page[offset]={0}&page[limit]={limit}\",\n \"last\": f\"{route}/{path_str}?page[offset]={last_page}&page[limit]={limit}\",\n }\n )\n if offset + limit < length_hint:\n links[\n \"next\"\n ] = f\"{route}/{path_str}?page[offset]={offset + limit}&page[limit]={limit}\"\n if offset > 0:\n links[\n \"prev\"\n ] = f\"{route}/{path_str}?page[offset]={max(0, offset - limit)}&page[limit]={limit}\"\n return links\n\n\nclass DuckReader(metaclass=abc.ABCMeta):\n \"\"\"\n Used for isinstance(obj, DuckReader):\n \"\"\"\n\n @classmethod\n def __subclasshook__(cls, candidate):\n # If the following condition is True, candidate is recognized\n # to \"quack\" like a Reader.\n EXPECTED_ATTRS = (\"read\", \"macrostructure\", \"microstructure\")\n return all(hasattr(candidate, attr) for attr in EXPECTED_ATTRS)\n\n\nclass DuckTree(metaclass=abc.ABCMeta):\n \"\"\"\n Used for isinstance(obj, DuckTree):\n \"\"\"\n\n @classmethod\n def __subclasshook__(cls, candidate):\n # If the following condition is True, candidate is recognized\n # to \"quack\" like a Tree.\n EXPECTED_ATTRS = (\"__getitem__\", \"__iter__\")\n return all(hasattr(candidate, attr) for attr in EXPECTED_ATTRS)\n\n\ndef construct_entries_response(\n query_registry, tree, route, path, offset, limit, fields, filters, sort, base_url\n):\n path_parts = [segment for segment in path.split(\"/\") if segment]\n if not isinstance(tree, DuckTree):\n raise WrongTypeForRoute(\"This is not a Tree.\")\n queries = defaultdict(\n dict\n ) # e.g. {\"text\": {\"text\": \"dog\"}, \"lookup\": {\"key\": \"...\"}}\n # Group the parameters by query type.\n for key, value in filters.items():\n if value is None:\n continue\n name, field = _FILTER_PARAM_PATTERN.match(key).groups()\n queries[name][field] = value\n sorting = []\n if sort is not None:\n for item in sort.split(\",\"):\n if item:\n if item.startswith(\"-\"):\n sorting.append((item[1:], -1))\n else:\n sorting.append((item, 1))\n if sorting:\n if not hasattr(tree, \"sort\"):\n raise HTTPException(\n status_code=400, detail=\"This Tree does not support sorting.\"\n )\n tree = tree.sort(sorting)\n # Apply the queries and obtain a narrowed tree.\n key_lookups = []\n for query_name, parameters_dict_of_lists in queries.items():\n for i in itertools.count(0):\n try:\n parameters = {\n field_name: parameters_list[i]\n for field_name, parameters_list in parameters_dict_of_lists.items()\n }\n except IndexError:\n break\n query_class = query_registry.name_to_query_type[query_name]\n # Special case:\n # List fields are serialized as comma-separated strings.\n for field in dataclasses.fields(query_class):\n if getattr(field.type, \"__origin__\", None) is list:\n (inner_type,) = field.type.__args__\n parameters[field.name] = [\n inner_type(item) for item in parameters[field.name].split(\",\")\n ]\n try:\n query = query_class(**parameters)\n # Special case: Do key-lookups at the end after all other filtering.\n # We do not require trees to implement this query; we implement it\n # directly here by just calling __getitem__.\n if isinstance(query, KeyLookup):\n key_lookups.append(query.key)\n continue\n tree = tree.search(query)\n except QueryValueError as err:\n raise HTTPException(status_code=400, detail=err.args[0])\n if key_lookups:\n # Duplicates are technically legal because *any* query can be given\n # with multiple parameters.\n unique_key_lookups = set(key_lookups)\n (key_lookup), *others = unique_key_lookups\n if others:\n # Two non-equal KeyLookup queries must return no results.\n tree = TreeInMemory({})\n else:\n try:\n tree = TreeInMemory(\n {key_lookup: tree[key_lookup]}, must_revalidate=False\n )\n except KeyError:\n tree = TreeInMemory({})\n count = len_or_approx(tree)\n links = pagination_links(route, path_parts, offset, limit, count)\n data = []\n if fields != [models.EntryFields.none]:\n # Pull a page of items into memory.\n items = tree.items_indexer[offset : offset + limit] # noqa: E203\n else:\n # Pull a page of just the keys, which is cheaper.\n items = (\n (key, None)\n for key in tree.keys_indexer[offset : offset + limit] # noqa: E203\n )\n # This value will not leak out. It just used to seed comparisons.\n metadata_stale_at = datetime.utcnow() + timedelta(days=1_000_000)\n must_revalidate = getattr(tree, \"must_revalidate\", True)\n for key, entry in items:\n resource = construct_resource(base_url, path_parts + [key], entry, fields)\n data.append(resource)\n # If any entry has emtry.metadata_stale_at = None, then there will\n # be no 'Expires' header. We will pessimistically assume the values\n # are immediately stale.\n if metadata_stale_at is not None:\n if getattr(entry, \"metadata_stale_at\", None) is None:\n metadata_stale_at = None\n else:\n metadata_stale_at = min(metadata_stale_at, entry.metadata_stale_at)\n return (\n models.Response(data=data, links=links, meta={\"count\": count}),\n metadata_stale_at,\n must_revalidate,\n )\n\n\nDEFAULT_MEDIA_TYPES = {\n \"array\": \"application/octet-stream\",\n \"dataframe\": APACHE_ARROW_FILE_MIME_TYPE,\n \"structured_array_tabular\": \"application/octet-stream\",\n \"structured_array_generic\": \"application/octet-stream\",\n \"variable\": \"application/octet-stream\",\n \"data_array\": \"application/octet-stream\",\n \"dataset\": \"application/netcdf\",\n}\n\n\ndef construct_data_response(\n structure_family,\n serialization_registry,\n payload,\n metadata,\n request,\n format=None,\n specs=None,\n expires=None,\n):\n request.state.endpoint = \"data\"\n if specs is None:\n specs = []\n default_media_type = DEFAULT_MEDIA_TYPES[structure_family]\n # Give priority to the `format` query parameter. Otherwise, consult Accept\n # header.\n if format is not None:\n media_types_or_aliases = format.split(\",\")\n # Resolve aliases, like \"csv\" -> \"text/csv\".\n media_types = [\n serialization_registry.resolve_alias(t) for t in media_types_or_aliases\n ]\n else:\n # The HTTP spec says these should be separated by \", \" but some\n # browsers separate with just \",\" (no space).\n # https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation/List_of_default_Accept_values#default_values # noqa\n # That variation is what we are handling below with lstrip.\n media_types = [\n s.lstrip(\" \")\n for s in request.headers.get(\"Accept\", default_media_type).split(\",\")\n ]\n\n # The client may give us a choice of media types. Find the first one\n # that we support.\n supported = set()\n for media_type in media_types:\n if media_type == \"*/*\":\n media_type = default_media_type\n # fall back to generic dataframe serializer if no specs present\n for spec in specs + [structure_family]:\n media_types_for_spec = serialization_registry.media_types(spec)\n if media_type in media_types_for_spec:\n break\n supported.update(media_types_for_spec)\n else:\n # None of the specs or the structure_family can serialize to this\n # media_type. Try the next one.\n continue\n # We found a match above. We have our media_type.\n break\n else:\n # We have checked each of the media_types, and we cannot serialize\n # to any of them.\n raise UnsupportedMediaTypes(\n f\"None of the media types requested by the client are supported. \"\n f\"Supported: {', '.join(supported)}. Requested: {', '.join(media_types)}.\",\n )\n with record_timing(request.state.metrics, \"tok\"):\n # Create an ETag that uniquely identifies this content and the media\n # type that it will be encoded as.\n etag = tokenize((payload, media_type))\n headers = {\"ETag\": etag}\n if expires is not None:\n headers[\"Expires\"] = expires.strftime(HTTP_EXPIRES_HEADER_FORMAT)\n if request.headers.get(\"If-None-Match\", \"\") == etag:\n # If the client already has this content, confirm that.\n return Response(status_code=304, headers=headers)\n # This is the expensive step: actually serialize.\n try:\n content = serialization_registry(\n structure_family, media_type, payload, metadata\n )\n except UnsupportedShape as err:\n raise UnsupportedMediaTypes(\n f\"The shape of this data {err.args[0]} is incompatible with the requested format ({media_type}). \"\n f\"Slice it or choose a different format.\",\n )\n except SerializationError:\n raise UnsupportedMediaTypes(\n \"This type is supported in general but there was an unknown error packing this specific data.\",\n )\n return PatchedResponse(\n content=content,\n media_type=media_type,\n headers=headers,\n )\n\n\ndef construct_resource(base_url, path_parts, entry, fields):\n path_str = \"/\".join(path_parts)\n attributes = {}\n if models.EntryFields.metadata in fields:\n attributes[\"metadata\"] = entry.metadata\n if models.EntryFields.specs in fields:\n attributes[\"specs\"] = getattr(entry, \"specs\", None)\n if isinstance(entry, DuckTree):\n if models.EntryFields.count in fields:\n attributes[\"count\"] = len_or_approx(entry)\n if hasattr(entry, \"sorting\"):\n attributes[\"sorting\"] = entry.sorting\n resource = models.TreeResource(\n **{\n \"id\": path_parts[-1] if path_parts else \"\",\n \"attributes\": models.TreeAttributes(**attributes),\n \"type\": models.EntryType.tree,\n \"links\": {\n \"self\": f\"{base_url}metadata/{path_str}\",\n \"search\": f\"{base_url}search/{path_str}\",\n },\n }\n )\n else:\n links = {\"self\": f\"{base_url}metadata/{path_str}\"}\n structure = {}\n if entry is not None:\n # entry is None when we are pulling just *keys* from the\n # Tree and not values.\n links.update(\n {\n link: template.format(base_url=base_url, path=path_str)\n for link, template in FULL_LINKS[entry.structure_family].items()\n }\n )\n if models.EntryFields.structure_family in fields:\n attributes[\"structure_family\"] = entry.structure_family\n if models.EntryFields.macrostructure in fields:\n macrostructure = entry.macrostructure()\n if macrostructure is not None:\n structure[\"macro\"] = dataclasses.asdict(macrostructure)\n if models.EntryFields.microstructure in fields:\n if entry.structure_family == \"dataframe\":\n # Special case: its microstructure is cannot be JSON-serialized\n # and is therefore available from separate routes. Sends links\n # instead of the actual payload.\n structure[\"micro\"] = {\n \"links\": {\n \"meta\": f\"{base_url}dataframe/meta/{path_str}\",\n \"divisions\": f\"{base_url}dataframe/divisions/{path_str}\",\n }\n }\n else:\n microstructure = entry.microstructure()\n if microstructure is not None:\n structure[\"micro\"] = dataclasses.asdict(microstructure)\n if entry.structure_family == \"array\":\n block_template = \",\".join(\n f\"{{index_{index}}}\"\n for index in range(len(structure[\"macro\"][\"shape\"]))\n )\n links[\n \"block\"\n ] = f\"{base_url}array/block/{path_str}?block={block_template}\"\n elif entry.structure_family == \"dataframe\":\n links[\n \"partition\"\n ] = f\"{base_url}dataframe/partition/{path_str}?partition={{index}}\"\n elif entry.structure_family == \"variable\":\n block_template = \",\".join(\n f\"{{index_{index}}}\"\n for index in range(\n len(structure[\"macro\"][\"data\"][\"macro\"][\"shape\"])\n )\n )\n links[\n \"block\"\n ] = f\"{base_url}variable/block/{path_str}?block={block_template}\"\n elif entry.structure_family == \"data_array\":\n block_template = \",\".join(\n f\"{{index_{index}}}\"\n for index in range(\n len(structure[\"macro\"][\"variable\"][\"macro\"][\"data\"])\n )\n )\n links[\n \"block\"\n ] = f\"{base_url}data_array/block/{path_str}?block={block_template}\"\n elif entry.structure_family == \"dataset\":\n links[\n \"block\"\n ] = f\"{base_url}dataset/block/{path_str}?variable={{variable}}&block={{block_indexes}}\"\n microstructure = entry.microstructure()\n attributes[\"structure\"] = structure\n resource = models.ReaderResource(\n **{\n \"id\": path_parts[-1],\n \"attributes\": models.ReaderAttributes(**attributes),\n \"type\": models.EntryType.reader,\n \"links\": links,\n }\n )\n return resource\n\n\nclass PatchedResponse(Response):\n \"Patch the render method to accept memoryview.\"\n\n def render(self, content: Any) -> bytes:\n if isinstance(content, memoryview):\n return content.cast(\"B\")\n return super().render(content)\n\n\nclass PatchedStreamingResponse(StreamingResponse):\n \"Patch the stream_response method to accept memoryview.\"\n\n async def stream_response(self, send: Send) -> None:\n await send(\n {\n \"type\": \"http.response.start\",\n \"status\": self.status_code,\n \"headers\": self.raw_headers,\n }\n )\n async for chunk in self.body_iterator:\n # BEGIN ALTERATION\n if not isinstance(chunk, (bytes, memoryview)):\n # END ALTERATION\n chunk = chunk.encode(self.charset)\n await send({\"type\": \"http.response.body\", \"body\": chunk, \"more_body\": True})\n\n await send({\"type\": \"http.response.body\", \"body\": b\"\", \"more_body\": False})\n\n\nclass NumpySafeJSONResponse(JSONResponse):\n def __init__(self, *args, metrics, **kwargs):\n self.__metrics = metrics\n super().__init__(*args, **kwargs)\n\n def render(self, content: Any) -> bytes:\n with record_timing(self.__metrics, \"pack\"):\n return orjson.dumps(content, option=orjson.OPT_SERIALIZE_NUMPY)\n\n\ndef _numpy_safe_msgpack_encoder(obj):\n # If numpy has not been imported yet, then we can be sure that obj\n # is not a numpy object, and we want to avoid triggering a numpy\n # import. (The server does not have a hard numpy dependency.)\n if \"numpy\" in sys.modules:\n import numpy\n\n if isinstance(obj, (numpy.generic, numpy.ndarray)):\n if numpy.isscalar(obj):\n return obj.item()\n return obj.tolist()\n return obj\n\n\ndef _patch_naive_datetimes(obj):\n \"\"\"\n If a naive datetime is found, attach local time.\n\n Msgpack can only serialize datetimes with tzinfo.\n \"\"\"\n if hasattr(obj, \"items\"):\n patched_obj = {}\n for k, v in obj.items():\n patched_obj[k] = _patch_naive_datetimes(v)\n elif (not isinstance(obj, str)) and isinstance(obj, collections.abc.Iterable):\n patched_obj = []\n for item in obj:\n patched_obj.append(_patch_naive_datetimes(item))\n elif isinstance(obj, datetime) and obj.tzinfo is None:\n patched_obj = obj.astimezone(_LOCAL_TZINFO)\n else:\n patched_obj = obj\n return patched_obj\n\n\nclass MsgpackResponse(Response):\n media_type = \"application/x-msgpack\"\n\n def __init__(self, *args, metrics, **kwargs):\n self.__metrics = metrics\n super().__init__(*args, **kwargs)\n\n def render(self, content: Any, _reentered=False) -> bytes:\n try:\n with record_timing(self.__metrics, \"pack\"):\n return msgpack.packb(\n content, default=_numpy_safe_msgpack_encoder, datetime=True\n )\n except TypeError as err:\n # msgpack tries to handle all datetimes, but if it\n # received a naive one (tzinfo=None) then it fails.\n # We cannot use the default hook to handle this because\n # it is not called.\n if err.args == (\"can not serialize 'datetime.datetime' object\",) and (\n not _reentered\n ):\n patched_content = _patch_naive_datetimes(content)\n return self.render(patched_content, _reentered=True)\n raise\n\n\nJSON_MIME_TYPE = \"application/json\"\nMSGPACK_MIME_TYPE = \"application/x-msgpack\"\n# This is a silly time format, but it is the HTTP standard.\nHTTP_EXPIRES_HEADER_FORMAT = \"%a, %d %b %Y %H:%M:%S GMT\"\n\n\ndef json_or_msgpack(request, content, expires=None, headers=None):\n media_types = request.headers.get(\"Accept\", JSON_MIME_TYPE).split(\", \")\n for media_type in media_types:\n if media_type == \"*/*\":\n media_type = JSON_MIME_TYPE\n break\n if media_type == MSGPACK_MIME_TYPE:\n break\n if media_type == JSON_MIME_TYPE:\n break\n else:\n # It is commmon in HTTP to fall back on a default representation if\n # none of the requested ones are available. We do not do this for\n # data payloads, but it makes some sense to do it for these metadata\n # messages.\n media_type = JSON_MIME_TYPE\n assert media_type in {JSON_MIME_TYPE, MSGPACK_MIME_TYPE}\n content_as_dict = content.dict()\n with record_timing(request.state.metrics, \"tok\"):\n etag = md5(str(content_as_dict).encode()).hexdigest()\n headers = headers or {}\n headers[\"ETag\"] = etag\n if expires is not None:\n headers[\"Expires\"] = expires.strftime(HTTP_EXPIRES_HEADER_FORMAT)\n if request.headers.get(\"If-None-Match\", \"\") == etag:\n # If the client already has this content, confirm that.\n return Response(status_code=304, headers=headers)\n if media_type == \"application/x-msgpack\":\n return MsgpackResponse(\n content_as_dict, headers=headers, metrics=request.state.metrics\n )\n return NumpySafeJSONResponse(\n content_as_dict, headers=headers, metrics=request.state.metrics\n )\n\n\nclass UnsupportedMediaTypes(Exception):\n pass\n\n\nclass NoEntry(KeyError):\n pass\n\n\nclass WrongTypeForRoute(Exception):\n pass\n\n\nFULL_LINKS = {\n \"array\": {\"full\": \"{base_url}array/full/{path}\"},\n \"structured_array_generic\": {\n \"full\": \"{base_url}structured_array_generic/full/{path}\"\n },\n \"structured_array_tabular\": {\n \"full\": \"{base_url}structured_array_tabular/full/{path}\"\n },\n \"dataframe\": {\"full\": \"{base_url}dataframe/full/{path}\"},\n \"variable\": {\"full\": \"{base_url}variable/full/{path}\"},\n \"data_array\": {\"full_variable\": \"{base_url}data_array/variable/full/{path}\"},\n \"dataset\": {\n \"full_variable\": \"{base_url}dataset/data_var/full/{path}?variable={{variable}}\",\n \"full_coordinate\": \"{base_url}dataset/coord/full/{path}?variable={{variable}}\",\n \"full_dataset\": \"{base_url}dataset/full/{path}\",\n },\n}\n\n\[email protected]\ndef record_timing(metrics, key):\n \"\"\"\n Set timings[key] equal to the run time (in milliseconds) of the context body.\n \"\"\"\n t0 = time.perf_counter()\n yield\n metrics[key][\"dur\"] += time.perf_counter() - t0 # Units: seconds\n",
"from dataclasses import dataclass\nfrom typing import List, Optional, Tuple, Union\n\nimport numpy\n\nfrom ..media_type_registration import serialization_registry\nfrom ..utils import modules_available\nfrom .array import ArrayMacroStructure\nfrom .array import MachineDataType as BuiltinType\n\n\n@dataclass\nclass Field:\n name: str\n dtype: Union[BuiltinType, \"StructDtype\"]\n shape: Optional[Tuple[int, ...]]\n\n @classmethod\n def from_numpy_descr(cls, field):\n name, *rest = field\n if name == \"\":\n raise ValueError(\n f\"You seem to have gotten descr of a base or subdtype: {field}\"\n )\n if len(rest) == 1:\n (f_type,) = rest\n shape = None\n else:\n f_type, shape = rest\n\n if isinstance(f_type, str):\n FType = BuiltinType.from_numpy_dtype(numpy.dtype(f_type))\n else:\n FType = StructDtype.from_numpy_dtype(numpy.dtype(f_type))\n return cls(name=name, dtype=FType, shape=shape)\n\n def to_numpy_descr(self):\n if isinstance(self.dtype, BuiltinType):\n base = [self.name, self.dtype.to_numpy_str()]\n else:\n base = [self.name, self.dtype.to_numpy_descr()]\n if self.shape is None:\n return tuple(base)\n else:\n return tuple(base + [self.shape])\n\n @classmethod\n def from_json(cls, structure):\n name = structure[\"name\"]\n if \"fields\" in structure[\"dtype\"]:\n ftype = StructDtype.from_json(structure[\"dtype\"])\n else:\n ftype = BuiltinType.from_json(structure[\"dtype\"])\n return cls(name=name, dtype=ftype, shape=structure[\"shape\"])\n\n\n@dataclass\nclass StructDtype:\n itemsize: int\n fields: List[Field]\n\n @classmethod\n def from_numpy_dtype(cls, dtype):\n # subdtypes push extra dimensions into arrays, we should handle these\n # a layer up and report an array with bigger dimensions.\n if dtype.subdtype is not None:\n raise ValueError(f\"We do not know how to encode subdtypes: {dtype}\")\n # If this is a builtin type, require the use of BuiltinType (nee .array.MachineDataType)\n if dtype.fields is None:\n raise ValueError(f\"You have a base type: {dtype}\")\n return cls(\n itemsize=dtype.itemsize,\n fields=[Field.from_numpy_descr(f) for f in dtype.descr],\n )\n\n def to_numpy_dtype(self):\n return numpy.dtype(self.to_numpy_descr())\n\n def to_numpy_descr(self):\n return [f.to_numpy_descr() for f in self.fields]\n\n def max_depth(self):\n return max(\n 1 if isinstance(f.dtype, BuiltinType) else 1 + f.dtype.max_depth()\n for f in self.fields\n )\n\n @classmethod\n def from_json(cls, structure):\n return cls(\n itemsize=structure[\"itemsize\"],\n fields=[Field.from_json(f) for f in structure[\"fields\"]],\n )\n\n\n@dataclass\nclass StructuredArrayGenericStructure:\n macro: ArrayMacroStructure\n micro: StructDtype\n\n @classmethod\n def from_json(cls, structure):\n return cls(\n macro=ArrayMacroStructure.from_json(structure[\"macro\"]),\n micro=StructDtype.from_json(structure[\"micro\"]),\n )\n\n\n@dataclass\nclass ArrayTabularMacroStructure:\n \"\"\"\n Similar to ArrayMacroStructure, but must be 1D\n\n This is distinct from DataFrameMacoStructure because it knows its length and\n chunk sizes. Dataframes only know number of partitions.\n \"\"\"\n\n chunks: Tuple[Tuple[int]]\n shape: Tuple[int]\n\n @classmethod\n def from_json(cls, structure):\n return cls(\n chunks=tuple(map(tuple, structure[\"chunks\"])),\n shape=tuple(structure[\"shape\"]),\n )\n\n\n@dataclass\nclass StructuredArrayTabularStructure:\n macro: ArrayTabularMacroStructure\n micro: StructDtype\n\n @classmethod\n def from_json(cls, structure):\n return cls(\n macro=ArrayMacroStructure.from_json(structure[\"macro\"]),\n micro=StructDtype.from_json(structure[\"micro\"]),\n )\n\n\nserialization_registry.register(\n \"structured_array_generic\",\n \"application/octet-stream\",\n lambda array, metadata: memoryview(numpy.ascontiguousarray(array)),\n)\nserialization_registry.register(\n \"structured_array_tabular\",\n \"application/octet-stream\",\n lambda array, metadata: memoryview(numpy.ascontiguousarray(array)),\n)\nif modules_available(\"orjson\"):\n import orjson\n\n serialization_registry.register(\n \"structured_array_generic\",\n \"application/json\",\n lambda array, metadata: orjson.dumps(array, option=orjson.OPT_SERIALIZE_NUMPY),\n )\n serialization_registry.register(\n \"structured_array_tabular\",\n \"application/json\",\n lambda array, metadata: orjson.dumps(array, option=orjson.OPT_SERIALIZE_NUMPY),\n )\n"
] | [
[
"numpy.asarray"
],
[
"numpy.isscalar"
],
[
"numpy.ascontiguousarray",
"numpy.dtype"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
DarkEnergySurvey/ugali | [
"82abffcc92bddf830d89f85cb3966870f7d9f720",
"82abffcc92bddf830d89f85cb3966870f7d9f720"
] | [
"ugali/observation/roi.py",
"ugali/scratch/simulation/validate_sim_population.py"
] | [
"\"\"\"\nDefine a region of interest (ROI) in color, magnitude, and direction space.\n\nThe ROI is divided into 3 regions:\n1) The 'target' region: The region occuping the likelihood-scale healpix\n pixel over which the likelihood is evaluated. (Size controlled by\n 'nside_likelihood')\n2) The 'interior' region: The region where objects are included into the\n likelihood fit.\n3) The 'annulus' region: The region where the background is fit.\n\n\"\"\"\n\nimport numpy as np\nimport healpy as hp\n\nimport ugali.utils.binning\nimport ugali.utils.projector\nimport ugali.utils.skymap\n\nfrom ugali.utils.logger import logger\nfrom ugali.utils.config import Config\nfrom ugali.utils.healpix import query_disc, ang2pix, pix2ang, ang2vec\n\n############################################################\n\n# ADW: Should really write some \"PixelSet\" object that contains the pixels for each region...\n\nclass PixelRegion(np.ndarray):\n # https://docs.scipy.org/doc/numpy-1.13.0/user/basics.subclassing.html\n\n def __new__(cls, nside, pixels):\n # Input array is an already formed ndarray instance\n # We first cast to be our class type\n obj = np.asarray(pixels).view(cls)\n # add the new attribute to the created instance\n obj._nside = nside\n obj._pix = pixels\n obj._lon,obj._lat = pix2ang(nside,pixels)\n # Finally, we must return the newly created object:\n return obj\n\n def __array_finalize__(self, obj):\n # see InfoArray.__array_finalize__ for comments\n if obj is None: return\n\n # NOTE: the _nside, _pix etc. attributes don't get set on\n # slicing because we are worried it will be too slow\n\n @property\n def lon(self):\n return self._lon\n\n @property\n def lat(self):\n return self._lat\n\n @property\n def nside(self):\n return self._nside\n\n @property\n def pix(self):\n return self._pix\n\nclass ROI(object):\n\n def __init__(self, config, lon, lat):\n\n self.config = Config(config)\n self.lon = lon\n self.lat = lat\n\n self.projector = ugali.utils.projector.Projector(self.lon, self.lat)\n\n self.vec = vec = ang2vec(self.lon, self.lat)\n self.pix = ang2pix(self.config['coords']['nside_likelihood'],self.lon,self.lat)\n\n # Pixels from the entire ROI disk\n pix = query_disc(self.config['coords']['nside_pixel'], vec, \n self.config['coords']['roi_radius'])\n self.pixels = PixelRegion(self.config['coords']['nside_pixel'],pix)\n\n # Pixels in the interior region\n pix = query_disc(self.config['coords']['nside_pixel'], vec, \n self.config['coords']['roi_radius_interior'])\n self.pixels_interior = PixelRegion(self.config['coords']['nside_pixel'],pix)\n\n # Pixels in the outer annulus\n pix = query_disc(self.config['coords']['nside_pixel'], vec, \n self.config['coords']['roi_radius_annulus'])\n pix = np.setdiff1d(self.pixels, pix)\n self.pixels_annulus = PixelRegion(self.config['coords']['nside_pixel'],pix)\n\n # Pixels within target healpix region\n pix = ugali.utils.skymap.subpixel(self.pix,self.config['coords']['nside_likelihood'],\n self.config['coords']['nside_pixel'])\n self.pixels_target = PixelRegion(self.config['coords']['nside_pixel'],pix)\n\n # Boolean arrays for selecting given pixels \n # (Careful, this works because pixels are pre-sorted by query_disc before in1d)\n self.pixel_interior_cut = np.in1d(self.pixels, self.pixels_interior)\n self.pixel_annulus_cut = np.in1d(self.pixels, self.pixels_annulus)\n\n # Some pixel properties\n self.area_pixel = hp.nside2pixarea(self.config.params['coords']['nside_pixel'],degrees=True) # deg^2\n self.max_pixrad = np.degrees(hp.max_pixrad(self.config['coords']['nside_pixel'])) # deg\n \n # ADW: These are really bin edges, should be careful and consistent\n # It would be cleaner to separate the CMD from ROI\n self.bins_mag = np.linspace(self.config.params['mag']['min'],\n self.config.params['mag']['max'],\n self.config.params['mag']['n_bins'] + 1)\n \n self.bins_color = np.linspace(self.config.params['color']['min'],\n self.config.params['color']['max'],\n self.config.params['color']['n_bins'] + 1)\n\n self.centers_mag = ugali.utils.binning.centers(self.bins_mag)\n self.centers_color = ugali.utils.binning.centers(self.bins_color)\n\n self.delta_mag = self.bins_mag[1] - self.bins_mag[0]\n self.delta_color = self.bins_color[1] - self.bins_color[0]\n\n def plot(self, value=None, pixel=None):\n \"\"\"\n Plot the ROI\n \"\"\"\n # DEPRECATED: ADW 2021-07-15\n DeprecationWarning(\"'roi.plot' is deprecated and will be removed.\")\n import ugali.utils.plotting\n\n map_roi = np.array(hp.UNSEEN \\\n * np.ones(hp.nside2npix(self.config.params['coords']['nside_pixel'])))\n \n if value is None:\n #map_roi[self.pixels] = ugali.utils.projector.angsep(self.lon, self.lat, self.centers_lon, self.centers_lat)\n map_roi[self.pixels] = 1\n map_roi[self.pixels_annulus] = 0\n map_roi[self.pixels_target] = 2\n elif value is not None and pixel is None:\n map_roi[self.pixels] = value\n elif value is not None and pixel is not None:\n map_roi[pixel] = value\n else:\n logger.error(\"Can't parse input\")\n \n ugali.utils.plotting.zoomedHealpixMap('Region of Interest',\n map_roi,\n self.lon, self.lat,\n self.config.params['coords']['roi_radius'])\n\n # ADW: Maybe these should be associated with the PixelRegion objects\n def inPixels(self,lon,lat,pixels):\n \"\"\" Function for testing if coordintes in set of ROI pixels. \"\"\"\n nside = self.config.params['coords']['nside_pixel']\n return ugali.utils.healpix.in_pixels(lon,lat,pixels,nside)\n \n def inROI(self,lon,lat):\n return self.inPixels(lon,lat,self.pixels)\n\n def inAnnulus(self,lon,lat):\n return self.inPixels(lon,lat,self.pixels_annulus)\n\n def inInterior(self,lon,lat):\n return self.inPixels(lon,lat,self.pixels_interior)\n\n def inTarget(self,lon,lat):\n return self.inPixels(lon,lat,self.pixels_target)\n\n def indexPixels(self,lon,lat,pixels):\n nside = self.config.params['coords']['nside_pixel']\n return ugali.utils.healpix.index_pixels(lon,lat,pixels,nside)\n\n def indexROI(self,lon,lat):\n return self.indexPixels(lon,lat,self.pixels)\n\n def indexAnnulus(self,lon,lat):\n return self.indexPixels(lon,lat,self.pixels_annulus)\n\n def indexInterior(self,lon,lat):\n return self.indexPixels(lon,lat,self.pixels_interior)\n\n def indexTarget(self,lon,lat):\n return self.indexPixels(lon,lat,self.pixels_target)\n \n def getCatalogPixels(self):\n \"\"\"\n Return the catalog pixels spanned by this ROI.\n \"\"\"\n filenames = self.config.getFilenames()\n\n nside_catalog = self.config.params['coords']['nside_catalog']\n nside_pixel = self.config.params['coords']['nside_pixel']\n # All possible catalog pixels spanned by the ROI\n superpix = ugali.utils.skymap.superpixel(self.pixels,nside_pixel,nside_catalog)\n superpix = np.unique(superpix)\n # Only catalog pixels that exist in catalog files\n pixels = np.intersect1d(superpix, filenames['pix'].compressed())\n return pixels\n \n############################################################\n\n",
"import os\nimport glob\nimport numpy as np\nimport astropy.io.fits as pyfits\nimport matplotlib.patches as patches\nimport pylab\n\npylab.ion()\n\n##########\n\ndef wrap(x):\n x_return = x\n x_return[x > 180.] = x[x > 180.] - 360.\n return x_return\n\n##########\n\ndef getCatalogFile(catalog_dir, mc_source_id):\n \"\"\"\n Inputs:\n catalog_dir = string corresponding to directory containing the stellar catalog infiles\n mc_source_id = integer corresponding the target MC_SOURCE_ID value\n Outputs:\n catalog_infile = string corresponding to filename of stellar catalog containing mc_source_id\n \"\"\"\n catalog_infiles = sorted(glob.glob(catalog_dir + '/*catalog*.fits'))\n mc_source_id_array = []\n catalog_infile_index_array = []\n for ii, catalog_infile in enumerate(catalog_infiles):\n mc_source_id_min = int(os.path.basename(catalog_infile).split('.')[0].split('mc_source_id_')[-1].split('-')[0])\n mc_source_id_max = int(os.path.basename(catalog_infile).split('.')[0].split('mc_source_id_')[-1].split('-')[1])\n assert (mc_source_id_max > mc_source_id_min) & (mc_source_id_min >= 1), 'Found invalue MC_SOURCE_ID values in filenames'\n mc_source_id_array.append(np.arange(mc_source_id_min, mc_source_id_max + 1))\n catalog_infile_index_array.append(np.tile(ii, 1 + (mc_source_id_max - mc_source_id_min)))\n\n mc_source_id_array = np.concatenate(mc_source_id_array)\n catalog_infile_index_array = np.concatenate(catalog_infile_index_array)\n\n assert len(mc_source_id_array) == len(np.unique(mc_source_id_array)), 'Found non-unique MC_SOURCE_ID values in filenames'\n assert np.in1d(mc_source_id, mc_source_id_array), 'Requested MC_SOURCE_ID value not among files'\n mc_source_id_index = np.nonzero(mc_source_id == mc_source_id_array)[0]\n return catalog_infiles[catalog_infile_index_array[mc_source_id_index]]\n\n##########\n\ndef getCatalog(catalog_dir):\n catalog_infiles = sorted(glob.glob(catalog_dir + '/*catalog*.fits'))\n data_array = []\n for catalog_infile in catalog_infiles:\n print(' Reading %s ...'%(catalog_infile))\n reader = pyfits.open(catalog_infile)\n data_array.append(reader[1].data)\n reader.close()\n print(' Merging ...')\n return np.concatenate(data_array)\n\n##########\n\nsave = False\ndpi = 150\n\n#infile_population = 'v3/sim_population_v3.fits'\ninfile_population = 'v4/sim_population_v4.fits'\nreader_population = pyfits.open(infile_population)\ndata_population = reader_population[1].data\nprint(len(data_population))\ndata_population = data_population #[0:500]\nreader_population.close()\n\n#catalog_dir = \n#glob.glob('*catalog*.fits')\n\n\n#infile_catalog = 'sim_catalog_v2_n_5000.fits.gz'\n#reader_catalog = pyfits.open(infile_catalog)\n#data_catalog = reader_catalog[1].data\n#reader_catalog.close()\n\n#data_catalog = getCatalog('v3')\ndata_catalog = getCatalog('v4')\n\n\"\"\"\npylab.figure()\npylab.scatter(wrap(data_catalog['RA']), data_catalog['DEC'], c=data_catalog['MC_SOURCE_ID'], s=1, cmap='jet')\ncolorbar = pylab.colorbar()\ncolorbar.set_label('MC Source ID')\npylab.xlabel('RA (deg)')\npylab.ylabel('Dec (deg)')\npylab.xlim(pylab.xlim()[::-1])\nif save:\n pylab.savefig('sim_population_coordinates.png', dpi=dpi)\n\"\"\"\n\"\"\"\npylab.figure()\n#pylab.yscale('log')\npylab.hist(data_catalog['PSF_MAG_SFD_G'], bins=np.arange(16., 30., 0.1), color='blue', alpha=0.5, label='g-band') # mag_g\npylab.hist(data_catalog['PSF_MAG_SFD_R'], bins=np.arange(16., 30., 0.1), color='green', alpha=0.5, label='r-band') # mag_r\npylab.xlabel('Magnitude')\npylab.ylabel('Counts')\npylab.legend(loc='upper left')\nif save:\n pylab.savefig('sim_population_magnitudes.png', dpi=dpi)\n\nfor band, color in zip(['g', 'r'], ['blue', 'green']):\n pylab.figure()\n pylab.yscale('log')\n #pylab.scatter(data_catalog['mag_g'], data_catalog['magerr_g'], color='blue', marker='.', s=1, label='g-band')\n #pylab.scatter(data_catalog['mag_r'], data_catalog['magerr_r'], color='green', marker='.', s=1, label='r-band')\n pylab.scatter(data_catalog['PSF_MAG_SFD_%s'%(band)], data_catalog['PSF_MAG_ERR_%s'%(band)], color=color, marker='.', s=1, alpha=0.1) # mag_%s\n pylab.xlabel('%s Magnitude'%(band))\n pylab.ylabel('%s Magnitude Uncertainty'%(band))\n pylab.legend(loc='upper left', scatterpoints=1, markerscale=10)\n if save:\n pylab.savefig('sim_population_magnitude_errors_%s.png'%(band), dpi=dpi)\n\n\"\"\"\n\npylab.figure()\npylab.xscale('log')\npylab.scatter(1.e3 * data_population['r_physical'], data_population['abs_mag'], c=data_population['surface_brightness'], s=10)\ncolorbar = pylab.colorbar()\ncolorbar.set_label('Surface Brightness (mag arcsec^-2)')\npylab.xlim(1., 3.e3)\npylab.ylim(2., -12.)\npylab.xlabel('Half-light Radius (pc)')\npylab.ylabel('M_V (mag)')\nif save:\n pylab.savefig('sim_population_coordinates_size_luminosity.png', dpi=dpi)\n\npylab.figure()\npylab.xscale('log')\npylab.scatter(data_population['distance'], data_population['abs_mag'], c=data_population['n_g24'], vmin=0, vmax=3.e2, s=10)\ncolorbar = pylab.colorbar()\ncolorbar.set_label('Number of Stars with g < 24 mag')\npylab.xlim(3., 1.e3)\npylab.ylim(2., -12.)\npylab.xlabel('Distance (kpc)')\npylab.ylabel('M_V (mag)')\nif save:\n pylab.savefig('sim_population_distance_luminosity.png', dpi=dpi)\n\npylab.figure()\npylab.xscale('log')\npylab.scatter(data_population['n_g24'], data_population['surface_brightness'], s=10)\npylab.xlim(0.1, 1.e6)\npylab.ylim(35., 25.)\npylab.xlabel('Number of Stars with g < 24 mag')\npylab.ylabel('Surface Brightness (mag arcsec^-2)')\nif save:\n pylab.savefig('sim_population_n_g24_surface_brightness.png', dpi=dpi)\n\n\"\"\"\npylab.figure()\ncounts_array = []\nfor index in data_population['MC_SOURCE_ID']:\n counts_array.append(np.sum(data_catalog['MC_SOURCE_ID'] == index))\npylab.scatter(counts_array, data_population['n_g24'])\n\"\"\"\n\"\"\"\ncut = (data_catalog['MC_SOURCE_ID'] == data_population['MC_SOURCE_ID'][np.argmax(data_population['n_g24'])])\n\npylab.figure()\npylab.scatter(data_catalog['PSF_MAG_SFD_G'][cut] - data_catalog['PSF_MAG_SFD_R'][cut], \n data_catalog['PSF_MAG_SFD_G'][cut],\n marker='.')\npylab.ylim(pylab.ylim()[::-1])\n\"\"\"\n\npylab.figure()\npylab.scatter(wrap(data_population['RA']), data_population['DEC'], c=data_population['FRACDET_WIDE'], vmin=0., vmax=1.)\ncolorbar = pylab.colorbar()\ncolorbar.set_label('Average Fracdet within Azimuthally Averaged Half-light Radius')\npylab.xlabel('RA (deg)')\npylab.ylabel('Dec (deg)')\npylab.xlim(pylab.xlim()[::-1])\n\npylab.figure()\npylab.scatter(wrap(data_population['RA']), data_population['DEC'], c=data_population['DENSITY'], vmax=1.)\ncolorbar = pylab.colorbar()\ncolorbar.set_label('Local Stellar Density (arcmin^-2)')\npylab.xlabel('RA (deg)')\npylab.ylabel('Dec (deg)')\npylab.xlim(pylab.xlim()[::-1])\n\npylab.figure()\npylab.scatter(wrap(data_population['RA']), data_population['DEC'], c=data_population['EBV'], vmax=0.05)\npylab.colorbar().set_label('E(B-V)')\n#colorbar.set_label('Local Stellar Density (arcmin^-2)')\npylab.xlabel('RA (deg)')\npylab.ylabel('Dec (deg)')\npylab.xlim(pylab.xlim()[::-1])\n\n##########\n\"\"\"\ncounts_mc_source_id = np.histogram(data_catalog['MC_SOURCE_ID'],bins=np.arange(np.max(data_catalog['MC_SOURCE_ID']) + 1))[0]\npylab.figure()\npylab.yscale('log', nonposy='clip')\ncounts, edges = pylab.hist(counts_mc_source_id, bins=np.linspace(0, np.max(counts_mc_source_id) + 1, 101))[0:2]\n\ncenters = 0.5 * (edges[:-1] + edges[1:])\npylab.xlabel('Catalog Stars per Satellite')\npylab.ylabel('Number of Satellites')\n\n#pylab.figure()\n#pylab.scatter(centers, centers * counts)\n\"\"\"\n##########\n\"\"\"\nprint(\"Machine learning\")\n\nsave = False\n\nimport sklearn.gaussian_process\nimport sklearn.neighbors\nimport sklearn.svm\n\nx = np.vstack([np.log10(data_population['distance']), data_population['abs_mag'], np.log10(data_population['r_physical'])]).T\ny = (data_population['surface_brightness'] < 29.) & (data_population['n_g24'] >= 10.)\n\n#classifier = sklearn.gaussian_process.GaussianProcessClassifier(1.0 * sklearn.gaussian_process.kernels.RBF(1.0))\nclassifier = sklearn.neighbors.KNeighborsClassifier(2, weights='uniform')\n#classifier = sklearn.neighbors.KNeighborsClassifier(2, weights='distance') \n#classifier = sklearn.svm.SVC(gamma=2, C=1)\n\nclassifier.fit(x, y)\n\ny_pred = classifier.predict_proba(x)\n\npylab.figure()\npylab.xscale('log')\npylab.scatter(1.e3 * data_population['r_physical'][y], data_population['abs_mag'][y], c='black', marker='x', label='Detected')\npylab.scatter(1.e3 * data_population['r_physical'], data_population['abs_mag'], c=y_pred[:,1], vmin=0., vmax=1., s=10)\ncolorbar = pylab.colorbar()\ncolorbar.set_label('ML Predicted Detection Probability')\npylab.xlim(1., 3.e3)\npylab.ylim(2., -12.)\npylab.xlabel('Half-light Radius (pc)')\npylab.ylabel('M_V (mag)')\npylab.legend(loc='upper left')\nif save:\n pylab.savefig('sim_population_coordinates_size_luminosity_prediction.png', dpi=dpi)\n\npylab.figure()\npylab.xscale('log')\npylab.scatter(data_population['distance'][y], data_population['abs_mag'][y], c='black', marker='x', label='Detected')\npylab.scatter(data_population['distance'], data_population['abs_mag'], c=y_pred[:,1], vmin=0., vmax=1., s=10)\ncolorbar = pylab.colorbar()\ncolorbar.set_label('ML Predicted Detection Probability')\npylab.xlim(3., 1.e3)\npylab.ylim(2., -12.)\npylab.xlabel('Distance (kpc)')\npylab.ylabel('M_V (mag)')\npylab.legend(loc='upper left')\nif save:\n pylab.savefig('sim_population_distance_luminosity_prediction.png', dpi=dpi)\n\npylab.figure()\npylab.xscale('log')\n#patches.Rectangle((10., 29.), 1.e2, -1., fc='black', alpha=0.1)\npylab.gca().add_patch(patches.Rectangle((10., 25.), 1.e6, 4., fc='black', alpha=0.2, zorder=-999, label='Detection Region'))\npylab.scatter(data_population['n_g24'][y], data_population['surface_brightness'][y], c='black', marker='x', label='Detected')\npylab.scatter(data_population['n_g24'], data_population['surface_brightness'], c=y_pred[:,1], vmin=0., vmax=1., s=10)\ncolorbar = pylab.colorbar()\ncolorbar.set_label('ML Predicted Detection Probability')\npylab.xlim(0.1, 1.e6)\npylab.ylim(35., 25.)\npylab.xlabel('Number of Stars with g < 24 mag')\npylab.ylabel('Surface Brightness (mag arcsec^-2)')\npylab.legend(loc='lower right')\nif save:\n pylab.savefig('sim_population_n_g24_surface_brightness_prediction.png', dpi=dpi)\n\nbins = np.linspace(0., 1., 10 + 1)\ncenters = np.empty(len(bins) - 1)\nbin_prob = np.empty(len(bins) - 1)\nfor ii in range(0, len(centers)):\n cut = (y_pred[:,1] > bins[ii]) & (y_pred[:,1] < bins[ii + 1])\n centers[ii] = np.mean(y_pred[:,1][cut])\n bin_prob[ii] = np.mean(y[cut].astype(float))\npylab.figure()\npylab.plot(centers, bin_prob, c='black')\npylab.scatter(centers, bin_prob, c='black')\npylab.xlabel('ML Predicted Detection Probability')\npylab.ylabel('Fraction Detected')\npylab.xlim(0., 1.)\npylab.ylim(0., 1.)\n\nbins = np.linspace(0., 1., 41.)\npylab.figure()\npylab.hist(y_pred[:,1][y], bins=bins, color='green', alpha=0.5, normed=True, label='Detected')\npylab.hist(y_pred[:,1][~y], bins=bins, color='red', alpha=0.5, normed=True, label='Not Detected')\npylab.xlabel('ML Predicted Detection Probability')\npylab.ylabel('PDF')\npylab.legend(loc='upper center')\n\"\"\"\n"
] | [
[
"numpy.linspace",
"numpy.unique",
"numpy.asarray",
"numpy.in1d",
"numpy.setdiff1d"
],
[
"numpy.nonzero",
"numpy.unique",
"numpy.arange",
"numpy.in1d",
"numpy.tile",
"numpy.concatenate"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
statphysandml/MCMCEvaluationLib | [
"f722b2c7df88b1b33cd29335a22eef53bdad9665",
"f722b2c7df88b1b33cd29335a22eef53bdad9665"
] | [
"mcmctools/loading/loading.py",
"mcmctools/modes/correlation_time.py"
] | [
"import pandas as pd\nimport numpy as np\nimport os\nimport glob\nimport math\n\n\nfrom pystatplottools.utils.multiple_inheritance_base_class import MHBC\n\n\nclass ConfigurationLoader(MHBC):\n def __init__(self, **kwargs):\n # For child classes with more than one parent class\n super().__init__(**kwargs)\n\n self.path = kwargs.pop('path')\n self.total_number_of_data_per_file = kwargs.pop(\"total_number_of_data_per_file\")\n self.identifier = kwargs.pop(\"identifier\", \"\")\n self.running_parameter = kwargs.pop(\"running_parameter\", \"default\")\n self.drop_last = kwargs.pop(\"drop_last\", False) # Should only be used if it is wanted that each chunk has the same length\n self.complex_number_format = kwargs.pop(\"complex_number_format\", \"complex\") # or \"plain\"\n self.skipcols = kwargs.pop(\"skipcols\", None)\n self.transformer = kwargs.pop(\"transformer\", None) # For passing functions\n self.transform = kwargs.pop(\"transform\", False) # Looks for transformer function in raw/transformer.py\n self.transformer_path = kwargs.pop(\"transformer_path\", self.path + \"/raw\")\n if self.transformer_path is not None:\n import sys\n sys.path.append(os.path.abspath(self.transformer_path))\n\n # Chunksize and total number of chunks\n self.chunksize = kwargs.pop(\"chunksize\", self.total_number_of_data_per_file)\n if self.drop_last:\n # Not working for resulting self.total_chunks = 1 since than all data is loaded at a later point\n self.total_chunks = math.floor(self.total_number_of_data_per_file * 1.0 / self.chunksize)\n else:\n self.total_chunks = math.ceil(self.total_number_of_data_per_file * 1.0 / self.chunksize)\n\n self.chunk_iterator = 0\n self.skiprows = 0\n\n # Enables to continue read the file from a given chunk iterator val -> not sure what it does , so far\n current_chunk_iterator_val = kwargs.pop(\"current_chunk_iterator_val\", None)\n if current_chunk_iterator_val is not None:\n self.skiprows = range(1, current_chunk_iterator_val * self.chunksize + 1)\n self.chunk_iterator = current_chunk_iterator_val\n\n # Assign a reader to each file\n self.readers, self.filenames = ConfigurationLoader.load_configuration_readers(\n path=self.path,\n nrows=self.total_number_of_data_per_file,\n chunksize=self.chunksize,\n skiprows=self.skiprows,\n identifier=self.identifier,\n skipcols=self.skipcols\n )\n\n if self.total_chunks == 1:\n # Used to store the data if only a single chunk is loaded\n self.data = None\n\n self.total_number_of_repeated_loading = 0\n\n def __len__(self):\n return self.total_number_of_data_per_file * len(self.filenames)\n\n def get_next_chunk_collection(self, resample=True):\n if self.total_chunks == 1:\n self.total_number_of_repeated_loading += 1\n return self.load_all_data(resample)\n\n if self.chunk_iterator >= self.total_chunks:\n self.total_number_of_repeated_loading += 1\n # Readers and filenames are reloaded for the next iteration\n self.readers, self.filenames = ConfigurationLoader.load_configuration_readers(\n path=self.path,\n nrows=self.total_number_of_data_per_file,\n chunksize=self.chunksize,\n identifier=self.identifier,\n skipcols=self.skipcols\n )\n self.chunk_iterator = 0\n\n data = []\n for idx, reader in enumerate(self.readers):\n chunk = next(reader)\n chunk = ConfigurationLoader.prepare_single_data_frame(\n dat=chunk, file=self.filenames[idx], running_parameter=self.running_parameter)\n data.append(chunk)\n\n data = ConfigurationLoader.merge_file_datastreams(data=data, resample=resample)\n data = ConfigurationLoader.transform_config_data(data=data, complex_number_format=self.complex_number_format)\n\n if self.transform:\n try:\n from raw_transformer import transformer\n except ModuleNotFoundError:\n import sys\n sys.exit(\"ModuleNotFoundError: raw_transformer.py module not found. Needs to be set via transformer_\"\n \"path or by adding path of raw_transformer.py to sys.path\")\n data = transformer(data)\n elif self.transformer is not None:\n data = self.transformer(data)\n\n if self.running_parameter == \"default\":\n del data[\"Default\"]\n\n self.chunk_iterator += 1\n\n return data\n\n def get_chunk_iterator(self):\n return self.chunk_iterator\n\n def load_all_data(self, resample=True):\n if self.data is None:\n # Load all data\n self.data = self.load_all_data_ordered_by_index()\n self.data = self.data.droplevel(0).reset_index(drop=True)\n self.chunk_iterator += 1\n if resample:\n self.data = self.data.sample(frac=1).reset_index(drop=True)\n return self.data\n\n def load_all_data_ordered_by_index(self):\n return ConfigurationLoader.load_all_configurations(\n path=self.path,\n identifier=self.identifier,\n running_parameter=self.running_parameter,\n nrows=self.total_number_of_data_per_file,\n complex_number_format=self.complex_number_format,\n transform=self.transform,\n transformer=self.transformer,\n transformer_path=None # Already added to sys.path in init function\n )[0]\n \n @staticmethod\n def load_configuration_readers(path, nrows, chunksize=100, skiprows=0, identifier=\"\", skipcols=None):\n readers = []\n filenames = []\n\n current_directory = os.path.abspath(os.getcwd())\n\n os.chdir(path)\n for file in glob.glob(identifier + \"*.dat\"):\n if skipcols is not None:\n with open(file) as f:\n header_line = f.readline()\n usecols = [item for item in header_line.split(\"\\t\") if item not in skipcols]\n else:\n usecols = None\n\n reader = pd.read_csv(file, delimiter=\"\\t\", header=0, chunksize=chunksize, skiprows=skiprows, index_col=False, nrows=nrows, usecols=usecols)\n readers.append(reader)\n filenames.append(file)\n\n os.chdir(current_directory)\n return readers, filenames # , chunk_order\n\n @staticmethod\n def load_all_configurations(path, identifier=\"None\", running_parameter=\"default\", skiprows=0, nrows=\"all\", complex_number_format=\"complex\", skipcols=None, transformer=None, transform=False, transformer_path=None):\n data = []\n filenames = []\n\n current_directory = os.path.abspath(os.getcwd())\n\n if transformer_path is not None:\n import sys\n sys.path.append(os.path.abspath(transformer_path + \"/raw\"))\n\n os.chdir(path)\n\n data_files = glob.glob(identifier + \"*.dat\")\n\n for file in data_files:\n if skipcols is not None:\n with open(file) as f:\n header_line = f.readline()\n header_line = header_line[:-1]\n usecols = [item for item in header_line.split(\"\\t\") if item not in skipcols]\n else:\n usecols = None\n\n if nrows == \"all\":\n dat = pd.read_csv(file, delimiter=\"\\t\", header=0, skiprows=skiprows, index_col=False, usecols=usecols)\n else:\n dat = pd.read_csv(file, delimiter=\"\\t\", header=0, skiprows=skiprows, index_col=False, nrows=nrows, usecols=usecols)\n dat = ConfigurationLoader.prepare_single_data_frame(dat=dat, file=file, running_parameter=running_parameter)\n\n data.append(dat)\n filenames.append(file)\n\n data = ConfigurationLoader.merge_file_datastreams_by_index(data=data, by_col_index=running_parameter)\n data = ConfigurationLoader.transform_config_data(data=data, complex_number_format=complex_number_format)\n\n if transform:\n try:\n from raw_transformer import transformer\n except ModuleNotFoundError:\n import sys\n sys.exit(\"ModuleNotFoundError: raw_transformer.py module not found. Needs to be set via transformer_\"\n \"path or by adding path of raw_transformer.py to sys.path\")\n data = transformer(data)\n elif transformer is not None:\n data = transformer(data)\n\n if running_parameter == \"default\":\n del data[\"Default\"]\n os.chdir(current_directory)\n\n return data, filenames # , chunk_order\n\n @staticmethod\n def prepare_single_data_frame(dat, file, running_parameter):\n if \"Unnamed\" in dat.columns[-1]:\n dat.drop(dat.columns[len(dat.columns) - 1], axis=1, inplace=True)\n\n # Multiple data files are loaded based on running parameter\n if running_parameter != \"default\":\n running_parameter_val = np.float32(file[file.find(\"=\") + 1:file.find(\".dat\")])\n # Load single data file -> only a single file is loaded\n else:\n running_parameter_val = running_parameter\n\n dat = dat.assign(**{running_parameter.capitalize(): running_parameter_val})\n return dat\n\n # Plain merge -> single-index data frame of the samples\n @staticmethod\n def merge_file_datastreams(data, resample=False):\n data = pd.concat(data)\n data = data.reset_index(drop=True)\n if resample:\n data = data.sample(frac=1).reset_index(drop=True)\n return data\n\n # Keeps by_col_index as upper level index -> multi-index data frame of the samples\n @staticmethod\n def merge_file_datastreams_by_index(data, by_col_index=None):\n # Loaded only one file - adds default as an index\n if isinstance(data[0].loc[0, by_col_index.capitalize()], str):\n keys = [data[0].loc[0, by_col_index.capitalize()]]\n # Loaded several files\n else:\n keys = [f\"{x.loc[0, by_col_index.capitalize()]:.6f}\" for x in data]\n data = pd.concat(data, keys=keys).sort_index(level=0)\n data.index.set_names([by_col_index, 'sample_num'], inplace=True)\n return data\n\n @staticmethod\n def transform_config_data(data, complex_number_format=\"complex\"):\n if \"Config\" in data and data[\"Config\"].dtype == object:\n if data[\"Config\"].iloc[0].find(\" i\") != -1:\n complex_num = True\n else:\n complex_num = False\n\n # Determine the number of sites\n n_sites = len(data[\"Config\"].iloc[0].split(\", \"))\n\n # Split everything\n data[\"Config\"] = data[\"Config\"].apply(\n lambda x: np.float32(x.replace(\" i\", \", \").replace(\", \", \" \").split(\" \")))\n\n if complex_num and complex_number_format == \"complex\":\n # Combine to a complex number\n data[\"Config\"] = data[\"Config\"].apply(lambda x: x[::2] + 1.0j * x[1::2])\n\n # Extract entry from array with single element\n if len(data[\"Config\"].iloc[0]) == 1:\n # Single-index\n data[\"Config\"] = data[\"Config\"].apply(lambda x: x[0])\n elif len(data[\"Config\"].iloc[0]) == n_sites:\n # Multi-index with config-elements\n column_index = pd.MultiIndex.from_product([[\"Config\"], range(0, n_sites)],\n names=[\"quantity\", \"elem\"])\n row_index = data.index\n configs_multi_index = pd.DataFrame(data=np.stack(data[\"Config\"].values, axis=0), index=row_index,\n columns=column_index)\n\n data = data.drop(\"Config\", axis=1)\n data.columns = pd.MultiIndex.from_tuples([(c, '') for c in data],\n names=[\"quantity\", \"elem\"])\n data = pd.concat([data, configs_multi_index], axis=1)\n else:\n # Multi-index with config-elements and components\n column_index = pd.MultiIndex.from_product([[\"Config\"], range(0, n_sites), range(0, int(len(data[\"Config\"].iloc[0]) / n_sites))],\n names=[\"quantity\", \"elem\", \"component\"])\n row_index = data.index\n configs_multi_index = pd.DataFrame(data=np.stack(data[\"Config\"].values, axis=0), index=row_index,\n columns=column_index)\n\n data = data.drop(\"Config\", axis=1)\n data.columns = pd.MultiIndex.from_tuples([(c, '', '') for c in data],\n names=[\"quantity\", \"elem\", \"component\"])\n data = pd.concat([data, configs_multi_index], axis=1)\n\n else:\n # Determine data column index in dependence of entry types\n for col in data.columns:\n if data[col].dtype != object or col == \"Config\" or col == \"Default\" or \"Default\" in col:\n continue\n\n # Determine number of components\n x = data[col].iloc[0]\n if x.find(\" i\") != -1:\n complex_num = True\n else:\n complex_num = False\n\n x = np.float32(x.replace(\" i\", \", \").replace(\", \", \" \").split(\" \"))\n if complex_num and complex_number_format == \"complex\":\n x = x[::2] + 1.0j * x[1::2]\n if len(x) != 1:\n data.columns = pd.MultiIndex.from_tuples([(c, '') for c in data],\n names=[\"quantity\", \"component\"])\n\n for col in data.columns:\n if data[col].dtype != object or col == \"Config\" or col == \"Default\" or \"Default\" in col:\n continue\n\n if data[col].iloc[0].find(\" i\") != -1:\n complex_num = True\n else:\n complex_num = False\n\n # Split everything\n data[col] = data[col].apply(lambda x: np.float32(x.replace(\" i\", \", \").replace(\", \", \" \").split(\" \")))\n\n if complex_num and complex_number_format == \"complex\":\n # Combine to a complex number\n data[col] = data[col].apply(lambda x: x[::2] + 1.0j * x[1::2])\n\n # Extract entry from array with single element\n if len(data[col].iloc[0]) == 1:\n # Single-index data frame\n data[col] = data[col].apply(lambda x: x[0])\n else:\n if data.columns.nlevels == 2:\n # Multi-index data frame with components\n column_index = pd.MultiIndex.from_product([[col[0]], range(0, len(data[col].iloc[0]))],\n names=[\"quantity\", \"component\"])\n else:\n # Multi-index data frame with config-elements and components\n column_index = pd.MultiIndex.from_product([[col[0]], [\"\"], range(0, len(data[col].iloc[0]))],\n names=[\"quantity\", \"elem\", \"component\"])\n\n row_index = data.index\n col_multi_index = pd.DataFrame(data=np.stack(data[col].values, axis=0), index=row_index,\n columns=column_index)\n data = data.drop(col, axis=1)\n data = pd.concat([data, col_multi_index], axis=1)\n\n return data\n\n\ndef load_data(files_dir, running_parameter, identifier, skipcols=None, complex_number_format=\"complex\", project_base_dir=None):\n if project_base_dir is None:\n data_path = os.getcwd() + \"/data/\" + files_dir\n else:\n data_path = project_base_dir + \"/data/\" + files_dir\n\n data, filenames = ConfigurationLoader.load_all_configurations(\n path=data_path,\n identifier=identifier,\n running_parameter=running_parameter,\n skipcols=skipcols,\n complex_number_format=complex_number_format\n )\n return data, filenames\n",
"from pystatplottools.pdf_env.loading_figure_mode import loading_figure_mode\nfma, plt = loading_figure_mode(develop=False)\n\nimport os\nimport sys\nimport numpy as np\nimport pandas as pd\n\nfrom mcmctools.utils.json import load_configs\nfrom mcmctools.loading.loading import load_data\n\n\ndef get_correlation_time(data, tau, running_parameter):\n # For one dataset\n # n_samples = len(data) - tau\n # c_tau = data.iloc[tau:].reset_index(drop=True)\n # c = data.iloc[:n_samples].reset_index(drop=True)\n # return c.multiply(c_tau).mean() - c.mean() * c_tau.mean()\n\n c_tau = data.groupby(running_parameter).apply(lambda x: x.iloc[tau:].reset_index(drop=True))\n c = data.groupby(running_parameter).apply(lambda x: x.iloc[:len(x) - tau].reset_index(drop=True))\n return c.multiply(c_tau).groupby(running_parameter).mean() - c.groupby(running_parameter).mean() * c_tau.groupby(running_parameter).mean()\n\n\ndef plot_correlation_time(corr_times, label, maximum_correlation_time, files_dir, filename):\n fig, ax = fma.newfig(1)\n\n ax.plot(corr_times, label=label)\n ax.plot([0, maximum_correlation_time], [np.exp(-1), np.exp(-1)])\n ax.set_xlabel(\"$\\\\tau$\")\n ax.set_ylabel(\"$c(\\\\tau)$\")\n ax.set_yscale('log')\n ax.legend(loc=\"upper right\")\n\n plt.tight_layout()\n\n fma.savefig(os.getcwd() + \"/results/\" + files_dir, filename)\n plt.close()\n\n\ndef correlation_time(files_dir, sim_root_dir=\"\", rel_path=\"./\"):\n # Load configs and data\n cwd = os.getcwd()\n\n sim_params, execution_params, running_parameter = load_configs(files_dir=files_dir, mode=\"correlation_time\", project_base_dir=cwd)\n data, filenames = load_data(files_dir=files_dir, running_parameter=running_parameter, identifier=\"correlation_time\")\n\n if running_parameter.capitalize() in data.columns:\n del data[running_parameter.capitalize()]\n\n correlation_times = np.array(\n [get_correlation_time(data, t, running_parameter).values for t in range(0, execution_params[\"maximum_correlation_time\"])])\n\n correlation_times = pd.DataFrame(data=correlation_times.reshape(execution_params[\"maximum_correlation_time\"], -1),\n columns=data.index.levels[0],\n index=pd.RangeIndex(start=0, stop=execution_params[\"maximum_correlation_time\"], step=1))\n correlation_times = correlation_times.div(correlation_times.iloc[0])\n\n taus = correlation_times.apply(lambda x: np.argmin(np.abs(x.values - np.exp(-1)), axis=0))\n taus = pd.DataFrame(data=taus + 1, columns=[\"CorrelationTime\"])\n\n if running_parameter != \"default\":\n for label, corr_times in correlation_times.items():\n plot_correlation_time(corr_times, running_parameter + \" = \" + label, execution_params[\"maximum_correlation_time\"], files_dir,\n \"correlation_time_\" + running_parameter + \"=\" + label)\n\n else:\n plot_correlation_time(correlation_times, \"$c(\\\\tau)$\", execution_params[\"maximum_correlation_time\"], files_dir,\n \"correlation_time\")\n\n if not os.path.isdir(os.getcwd() + \"/results/\" + files_dir):\n os.makedirs(os.getcwd() + \"/results/\" + files_dir)\n\n taus.to_json(os.getcwd() + \"/results/\" + files_dir + \"/correlation_time_results.json\", indent=4)\n\n os.chdir(cwd)\n\n\nif __name__ == '__main__':\n print(\"FilesDir:\", sys.argv[1]) # , \"SimRootDir:\", sys.argv[2], \"RelPath:\", sys.argv[3])\n correlation_time(sys.argv[1]) # , sys.argv[2], sys.argv[3])\n"
] | [
[
"pandas.concat",
"pandas.read_csv",
"pandas.MultiIndex.from_tuples",
"numpy.stack"
],
[
"pandas.RangeIndex",
"numpy.exp",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"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": []
}
] |
ktjack2009/MachineLearing | [
"fcb6e491f3f74ef1046d19e38af99b0973709b16"
] | [
"KerasLearning/__init__.py"
] | [
"import os\nimport cv2 as cv\nimport numpy as np\n\nDIR = os.path.dirname(os.path.abspath(__file__))\nDATA_PATH = os.path.join(os.path.dirname(DIR), 'Data', 'cats_and_dogs_small')\nmodel_path = os.path.join(DIR, 'models')\ntest_dir = os.path.join(DATA_PATH, 'test')\ni = 1500\nimage_1 = os.path.join(test_dir, 'cats', f'cat.{i}.jpg')\nimage_2 = os.path.join(test_dir, 'dogs', f'dog.{i}.jpg')\n\nimage_1 = cv.imread(image_1)\nimage_2 = cv.imread(image_2)\nimage_1 = cv.resize(image_1, (150, 150)) / 255.0\nimage_2 = cv.resize(image_2, (150, 150)) / 255.0\nimage_1 = np.reshape(image_1, (-1, 150, 150, 3))\nimage_2 = np.reshape(image_2, (-1, 150, 150, 3))\n\n# cv.imshow('1', image_1)\n# cv.imshow('2', image_2)\n# cv.waitKey(0)\n# cv.destroyAllWindows()\n\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.applications import VGG16\n\nconv_base = VGG16(weights='imagenet', include_top=False, input_shape=(150, 150, 3))\nfeatures_batch_1 = conv_base.predict(image_1)\nfeatures_batch_1 = np.reshape(features_batch_1, (1, -1))\nfeatures_batch_2 = conv_base.predict(image_2)\nfeatures_batch_2 = np.reshape(features_batch_2, (1, -1))\n\nmodel = load_model(os.path.join(model_path, 'cats_and_dogs_small_3.h5'))\ny1 = model.predict(features_batch_1)\ny2 = model.predict(features_batch_2)\nprint((y1[0], y2[0]))\n"
] | [
[
"numpy.reshape",
"tensorflow.keras.applications.VGG16"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
ashishpatel26/urban-sound-classification | [
"9f86ade6596a75a5d3f83e33ebe7209cb454ea63"
] | [
"src/utils_2d.py"
] | [
"# basic library imports\nimport glob\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom numpy import random\nfrom tqdm import tqdm\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\nfrom PIL import Image\nfrom multiprocessing import Pool\nimport random\nimport pickle\nimport gc\nimport librosa\nfrom sklearn.preprocessing import LabelEncoder\n\n# pandas setting\npd.set_option(\"display.max_columns\", None)\npd.set_option(\"display.expand_frame_repr\", False)\npd.set_option(\"max_colwidth\", -1)\npd.options.display.max_rows = 5000\n\n\nsample_rate = 16000\ninput_length = 16000 * 4\nbatch_size = 16\nn_mels = 320\n\n\ndef input_to_target(base_data_path=\"./data/\"):\n\n # audio files and their corresponding labels\n train_path = base_data_path + \"train/Train/*.wav\"\n train_label_path = base_data_path + \"train.csv\"\n test_path = base_data_path + \"test/Test/*.wav\"\n\n # input\n train_files = glob.glob(train_path)\n train_files = pd.DataFrame({\"train_file_paths\": train_files})\n train_files[\"ID\"] = train_files[\"train_file_paths\"].apply(\n lambda x: x.split(\"/\")[-1].split(\".\")[0]\n )\n train_files[\"ID\"] = train_files[\"ID\"].astype(int)\n train_files = train_files.sort_values(by=\"ID\")\n test_files = glob.glob(test_path)\n\n # target\n train_labels = pd.read_csv(train_label_path)\n train_file_to_label = train_files.merge(train_labels, on=\"ID\", how=\"inner\")\n\n # encoding the classes\n int_encode = LabelEncoder()\n train_file_to_label[\"class_int_encode\"] = int_encode.fit_transform(\n train_file_to_label[\"Class\"]\n )\n\n return train_file_to_label\n\n\ndef audio_normalization(data):\n\n max_data = np.max(data)\n min_data = np.min(data)\n data = (data - min_data) / (max_data - min_data + 0.0001)\n return data - 0.5\n\n\ndef mel_spectrum_db(\n audio,\n sample_rate=sample_rate,\n window_size=20, # log_specgram\n step_size=10,\n eps=1e-10,\n):\n\n mel_spec = librosa.feature.melspectrogram(y=audio, sr=sample_rate, n_mels=n_mels)\n mel_db = (librosa.power_to_db(mel_spec, ref=np.max) + 40) / 40\n\n return mel_db.T\n\n\ndef stretch(data, rate=1):\n\n data = librosa.effects.time_stretch(data, rate)\n if len(data) > input_length:\n data = data[:input_length]\n else:\n data = np.pad(data, (0, max(0, input_length - len(data))), \"constant\")\n\n return data\n\n\ndef pitch_shift(data, n_steps=3.0):\n\n data = librosa.effects.pitch_shift(data, sr=sample_rate, n_steps=n_steps)\n if len(data) > input_length:\n data = data[:input_length]\n else:\n data = np.pad(data, (0, max(0, input_length - len(data))), \"constant\")\n\n return data\n\n\ndef loguniform(low=0.00000001, high=0.01):\n return np.exp(np.random.uniform(np.log(low), np.log(high)))\n\n\ndef white(N, state=None):\n \"\"\"\n White noise.\n :param N: Amount of samples.\n :param state: State of PRNG.\n :type state: :class:`np.random.RandomState`\n White noise has a constant power density. It's narrowband spectrum is therefore flat.\n The power in white noise will increase by a factor of two for each octave band,\n and therefore increases with 3 dB per octave.\n \"\"\"\n state = np.random.RandomState() if state is None else state\n return state.randn(N)\n\n\ndef augment(data):\n if np.random.uniform(0, 1) > 0.95:\n wnoise = loguniform()\n data = data + wnoise * white(len(data))\n if np.random.uniform(0, 1) > 0.95:\n stretch_val = np.random.uniform(0.9, 1.1)\n data = stretch(data, stretch_val)\n if np.random.uniform(0, 1) > 0.95:\n pitch_shift_val = np.random.uniform(-6, 6)\n data = pitch_shift(data, n_steps=pitch_shift_val)\n return data\n\n\ndef load_audio_file(file_path, input_length=input_length):\n data = librosa.core.load(file_path, sr=sample_rate)[0] # , sr=16000\n if len(data) > input_length:\n\n max_offset = len(data) - input_length\n\n offset = np.random.randint(max_offset)\n\n data = data[offset : (input_length + offset)]\n\n else:\n if input_length > len(data):\n max_offset = input_length - len(data)\n\n offset = np.random.randint(max_offset)\n else:\n offset = 0\n\n data = np.pad(data, (offset, input_length - len(data) - offset), \"constant\")\n\n data = augment(data)\n data = mel_spectrum_db(data)\n\n return data\n\n\ndef chunker(seq, size):\n return (seq[pos : pos + size] for pos in range(0, len(seq), size))\n\n\ndef generator(file_paths, target_labels, batch_size=batch_size):\n while True:\n file_paths, target_labels = shuffle(file_paths, target_labels)\n\n for batch_files, batch_labels in zip(\n chunker(file_paths, size=batch_size),\n chunker(target_labels, size=batch_size),\n ):\n\n batch_data = [load_audio_file(fpath) for fpath in batch_files]\n batch_data = np.array(batch_data)[:, :, :, np.newaxis]\n\n yield batch_data, batch_labels\n"
] | [
[
"numpy.array",
"numpy.log",
"pandas.read_csv",
"numpy.min",
"sklearn.utils.shuffle",
"pandas.DataFrame",
"numpy.max",
"numpy.random.uniform",
"pandas.set_option",
"sklearn.preprocessing.LabelEncoder",
"numpy.random.RandomState",
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sparshpriyadarshi/demucs | [
"7c7f65401db654d750df2b6f4d5b82a0101500b1"
] | [
"demucs/repo.py"
] | [
"# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\"\"\"Represents a model repository, including pre-trained models and bags of models.\nA repo can either be the main remote repository stored in AWS, or a local repository\nwith your own models.\n\"\"\"\n\nfrom hashlib import sha256\nfrom pathlib import Path\nimport typing as tp\n\nimport torch\nimport yaml\n\nfrom .apply import BagOfModels, Model\nfrom .states import load_model\n\n\nAnyModel = tp.Union[Model, BagOfModels]\n\n\nclass ModelLoadingError(RuntimeError):\n pass\n\n\ndef check_checksum(path: Path, checksum: str):\n sha = sha256()\n with open(path, 'rb') as file:\n while True:\n buf = file.read(2**20)\n if not buf:\n break\n sha.update(buf)\n actual_checksum = sha.hexdigest()[:len(checksum)]\n if actual_checksum != checksum:\n raise ModelLoadingError(f'Invalid checksum for file {path}, '\n f'expected {checksum} but got {actual_checksum}')\n\n\nclass ModelOnlyRepo:\n \"\"\"Base class for all model only repos.\n \"\"\"\n def has_model(self, sig: str) -> bool:\n raise NotImplementedError()\n\n def get_model(self, sig: str) -> Model:\n raise NotImplementedError()\n\n\nclass RemoteRepo(ModelOnlyRepo):\n def __init__(self, root_url: str, remote_files: tp.List[str]):\n if not root_url.endswith('/'):\n root_url += '/'\n self._models: tp.Dict[str, str] = {}\n for file in remote_files:\n sig, checksum = file.split('.')[0].split('-')\n assert sig not in self._models\n self._models[sig] = root_url + file\n\n def has_model(self, sig: str) -> bool:\n return sig in self._models\n\n def get_model(self, sig: str) -> Model:\n try:\n url = self._models[sig]\n except KeyError:\n raise ModelLoadingError(f'Could not find a pre-trained model with signature {sig}.')\n pkg = torch.hub.load_state_dict_from_url(url, map_location='cpu', check_hash=True)\n return load_model(pkg)\n\n\nclass LocalRepo(ModelOnlyRepo):\n def __init__(self, root: Path):\n self.root = root\n self.scan()\n\n def scan(self):\n self._models = {}\n self._checksums = {}\n for file in self.root.iterdir():\n if file.suffix == '.th':\n if '-' in file.stem:\n xp_sig, checksum = file.stem.split('-')\n self._checksums[xp_sig] = checksum\n else:\n xp_sig = file.stem\n if xp_sig in self._models:\n raise ModelLoadingError(\n f'Duplicate pre-trained model exist for signature {xp_sig}. '\n 'Please delete all but one.')\n self._models[xp_sig] = file\n\n def has_model(self, sig: str) -> bool:\n return sig in self._models\n\n def get_model(self, sig: str) -> Model:\n try:\n file = self._models[sig]\n except KeyError:\n raise ModelLoadingError(f'Could not find pre-trained model with signature {sig}.')\n if sig in self._checksums:\n check_checksum(file, self._checksums[sig])\n return load_model(file)\n\n\nclass BagOnlyRepo:\n \"\"\"Handles only YAML files containing bag of models, leaving the actual\n model loading to some Repo.\n \"\"\"\n def __init__(self, root: Path, model_repo: ModelOnlyRepo):\n self.root = root\n self.model_repo = model_repo\n self.scan()\n\n def scan(self):\n self._bags = {}\n for file in self.root.iterdir():\n if file.suffix == '.yaml':\n self._bags[file.stem] = file\n\n def has_model(self, name: str) -> bool:\n return name in self._bags\n\n def get_model(self, name: str) -> BagOfModels:\n try:\n yaml_file = self._bags[name]\n except KeyError:\n raise ModelLoadingError(f'{name} is neither a single pre-trained model or '\n 'a bag of models.')\n bag = yaml.safe_load(open(yaml_file))\n signatures = bag['models']\n models = [self.model_repo.get_model(sig) for sig in signatures]\n weights = bag.get('weights')\n segment = bag.get('segment')\n return BagOfModels(models, weights, segment)\n\n\nclass AnyModelRepo:\n def __init__(self, model_repo: ModelOnlyRepo, bag_repo: BagOnlyRepo):\n self.model_repo = model_repo\n self.bag_repo = bag_repo\n\n def has_model(self, name_or_sig: str) -> bool:\n return self.model_repo.has_model(name_or_sig) or self.bag_repo.has_model(name_or_sig)\n\n def get_model(self, name_or_sig: str) -> AnyModel:\n if self.model_repo.has_model(name_or_sig):\n return self.model_repo.get_model(name_or_sig)\n else:\n return self.bag_repo.get_model(name_or_sig)\n"
] | [
[
"torch.hub.load_state_dict_from_url"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
philtsmith570/Machine_Learning_A-Z | [
"72fa2795a9d45802aa339347129d168c14aabb8a"
] | [
"Machine Learning A-Z Folder/Part 4 - Clustering/Section 24 - K-Means Clustering/K_Means/data_preprocessing_template.py"
] | [
"# Data Preprocessing Template\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_csv('Mall_Customers.csv')\nX = dataset.iloc[:, [3, 4]].values\n#y = dataset.iloc[:, 3].values\n\n# K-Means Clustering using sk-learn\nfrom sklearn.cluster import KMeans\nwcss = []\nfor i in range(1, 11):\n kmeans = KMeans(n_clusters=i, init='k-means++', max_iter=300, \n n_init=10, random_state=0) \n kmeans.fit(X)\n wcss.append(kmeans.inertia_)\n#\n#plt.plot(range(1, 11), wcss)\n#plt.title('The elbow Method')\n#plt.xlabel('Number of clusters')\n#plt.ylabel('WCSS')\n#plt.show()\n\n# Applying k-means to the mall dataset\nkmeans = KMeans(n_clusters=5, init='k-means++', max_iter=300, \n n_init=10, random_state=0)\ny_kmeans = kmeans.fit_predict(X)\n\n# Visualizing the clusters\nplt.scatter(X[y_kmeans == 0, 0], X[y_kmeans ==0, 1], s=100, c='red', \n label= 'Careful')\nplt.scatter(X[y_kmeans == 1, 0], X[y_kmeans ==1, 1], s=100, c='blue', \n label= 'Standard')\nplt.scatter(X[y_kmeans == 2, 0], X[y_kmeans ==2, 1], s=100, c='green', \n label= 'Target')\nplt.scatter(X[y_kmeans == 3, 0], X[y_kmeans ==3, 1], s=100, c='cyan', \n label= 'Careless')\nplt.scatter(X[y_kmeans == 4, 0], X[y_kmeans ==4, 1], s=100, c='magenta', \n label= 'Sensible')\nplt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=300, \n c='yellow', label='centriods')\nplt.title('Clusters of clients')\nplt.xlabel('Annual Income(K$)')\nplt.ylabel('Spending Score (1-100)')\nplt.legend()\nplt.show()\n\n\n# Splitting the dataset into the Training set and Test set\n#from sklearn.cross_validation import train_test_split\n#X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\n\n# Feature Scaling\n\"\"\"from sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.transform(X_test)\nsc_y = StandardScaler()\ny_train = sc_y.fit_transform(y_train)\"\"\""
] | [
[
"matplotlib.pyplot.legend",
"pandas.read_csv",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.title",
"sklearn.cluster.KMeans",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
StarGazer1995/FCN-CD-PyTorch | [
"17f33470000a9bab6c5ea98bd3eba38f87868b2f"
] | [
"src/data/common.py"
] | [
"import torch\nimport numpy as np\n\nfrom scipy.io import loadmat\nfrom skimage.io import imread\n\ndef default_loader(path_):\n return imread(path_)\n\ndef mat_loader(path_):\n return loadmat(path_)\n\ndef make_onehot(index_map, n):\n # Only deals with tensors with no batch dim\n old_size = index_map.size()\n z = torch.zeros(n, *old_size[-2:]).type_as(index_map)\n z.scatter_(0, index_map, 1)\n return z\n \ndef to_tensor(arr):\n if arr.ndim < 3:\n return torch.from_numpy(arr)\n elif arr.ndim == 3:\n return torch.from_numpy(np.ascontiguousarray(np.transpose(arr, (2,0,1))))\n else:\n raise NotImplementedError\n\ndef to_array(tensor):\n if tensor.ndimension() < 3:\n return tensor.data.cpu().numpy()\n elif tensor.ndimension() in (3, 4):\n return np.ascontiguousarray(np.moveaxis(tensor.data.cpu().numpy(), -3, -1))\n else:\n raise NotImplementedError"
] | [
[
"scipy.io.loadmat",
"torch.from_numpy",
"numpy.transpose",
"torch.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": []
}
] |
Jian137/mmediting-1 | [
"e1ac6c93441ec96696d0b530f040b91b809015b6",
"e1ac6c93441ec96696d0b530f040b91b809015b6",
"e1ac6c93441ec96696d0b530f040b91b809015b6",
"e1ac6c93441ec96696d0b530f040b91b809015b6"
] | [
"tests/test_models/test_restorers/test_glean.py",
"mmedit/models/backbones/sr_backbones/glean_styleganv2.py",
"tests/test_models/test_components/test_discriminators/test_deepfill_disc.py",
"tests/test_models/test_transformer/test_search_transformer.py"
] | [
"# Copyright (c) OpenMMLab. All rights reserved.\nimport mmcv\nimport pytest\nimport torch\n\nfrom mmedit.models import build_model\n\n\ndef test_glean():\n\n model_cfg = dict(\n type='GLEAN',\n generator=dict(\n type='GLEANStyleGANv2',\n in_size=16,\n out_size=64,\n style_channels=512),\n discriminator=dict(type='StyleGAN2Discriminator', in_size=64),\n pixel_loss=dict(type='L1Loss', loss_weight=1.0, reduction='mean'),\n gan_loss=dict(\n type='GANLoss',\n gan_type='vanilla',\n real_label_val=1.0,\n fake_label_val=0,\n loss_weight=5e-3))\n\n train_cfg = None\n test_cfg = mmcv.Config(dict(metrics=['PSNR'], crop_border=0))\n\n # build restorer\n restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)\n\n # prepare data\n inputs = torch.rand(1, 3, 16, 16)\n targets = torch.rand(1, 3, 64, 64)\n data_batch = {'lq': inputs, 'gt': targets}\n\n restorer = build_model(model_cfg, train_cfg=train_cfg, test_cfg=test_cfg)\n meta = [{'lq_path': ''}]\n\n # test forward_test (cpu)\n with pytest.raises(ValueError): # iteration is not None or number\n with torch.no_grad():\n restorer(\n **data_batch,\n test_mode=True,\n save_image=True,\n meta=meta,\n iteration='1')\n with pytest.raises(AssertionError): # test with metric but gt is None\n with torch.no_grad():\n data_batch.pop('gt')\n restorer(**data_batch, test_mode=True)\n\n # test forward_test (gpu)\n if torch.cuda.is_available():\n data_batch = {'lq': inputs.cuda(), 'gt': targets.cuda()}\n restorer = restorer.cuda()\n with pytest.raises(ValueError): # iteration is not None or number\n with torch.no_grad():\n restorer(\n **data_batch,\n test_mode=True,\n save_image=True,\n meta=meta,\n iteration='1')\n with pytest.raises(AssertionError): # test with metric but gt is None\n with torch.no_grad():\n data_batch.pop('gt')\n restorer(**data_batch, test_mode=True)\n",
"# Copyright (c) OpenMMLab. All rights reserved.\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom mmcv.runner import load_checkpoint\n\nfrom mmedit.models.backbones.sr_backbones.rrdb_net import RRDB\nfrom mmedit.models.builder import build_component\nfrom mmedit.models.common import PixelShufflePack, make_layer\nfrom mmedit.models.registry import BACKBONES\nfrom mmedit.utils import get_root_logger\n\n\[email protected]_module()\nclass GLEANStyleGANv2(nn.Module):\n r\"\"\"GLEAN (using StyleGANv2) architecture for super-resolution.\n\n Paper:\n GLEAN: Generative Latent Bank for Large-Factor Image Super-Resolution,\n CVPR, 2021\n\n This method makes use of StyleGAN2 and hence the arguments mostly follow\n that in 'StyleGAN2v2Generator'.\n\n In StyleGAN2, we use a static architecture composing of a style mapping\n module and number of covolutional style blocks. More details can be found\n in: Analyzing and Improving the Image Quality of StyleGAN CVPR2020.\n\n You can load pretrained model through passing information into\n ``pretrained`` argument. We have already offered official weights as\n follows:\n\n - styelgan2-ffhq-config-f: http://download.openmmlab.com/mmgen/stylegan2/official_weights/stylegan2-ffhq-config-f-official_20210327_171224-bce9310c.pth # noqa\n - stylegan2-horse-config-f: http://download.openmmlab.com/mmgen/stylegan2/official_weights/stylegan2-horse-config-f-official_20210327_173203-ef3e69ca.pth # noqa\n - stylegan2-car-config-f: http://download.openmmlab.com/mmgen/stylegan2/official_weights/stylegan2-car-config-f-official_20210327_172340-8cfe053c.pth # noqa\n - styelgan2-cat-config-f: http://download.openmmlab.com/mmgen/stylegan2/official_weights/stylegan2-cat-config-f-official_20210327_172444-15bc485b.pth # noqa\n - stylegan2-church-config-f: http://download.openmmlab.com/mmgen/stylegan2/official_weights/stylegan2-church-config-f-official_20210327_172657-1d42b7d1.pth # noqa\n\n If you want to load the ema model, you can just use following codes:\n\n .. code-block:: python\n\n # ckpt_http is one of the valid path from http source\n generator = StyleGANv2Generator(1024, 512,\n pretrained=dict(\n ckpt_path=ckpt_http,\n prefix='generator_ema'))\n\n Of course, you can also download the checkpoint in advance and set\n ``ckpt_path`` with local path. If you just want to load the original\n generator (not the ema model), please set the prefix with 'generator'.\n\n Note that our implementation allows to generate BGR image, while the\n original StyleGAN2 outputs RGB images by default. Thus, we provide\n ``bgr2rgb`` argument to convert the image space.\n\n Args:\n in_size (int): The size of the input image.\n out_size (int): The output size of the StyleGAN2 generator.\n img_channels (int): Number of channels of the input images. 3 for RGB\n image and 1 for grayscale image. Default: 3.\n rrdb_channels (int): Number of channels of the RRDB features.\n Default: 64.\n num_rrdbs (int): Number of RRDB blocks in the encoder. Default: 23.\n style_channels (int): The number of channels for style code.\n Default: 512.\n num_mlps (int, optional): The number of MLP layers. Defaults to 8.\n channel_multiplier (int, optional): The mulitiplier factor for the\n channel number. Defaults to 2.\n blur_kernel (list, optional): The blurry kernel. Defaults\n to [1, 3, 3, 1].\n lr_mlp (float, optional): The learning rate for the style mapping\n layer. Defaults to 0.01.\n default_style_mode (str, optional): The default mode of style mixing.\n In training, we defaultly adopt mixing style mode. However, in the\n evaluation, we use 'single' style mode. `['mix', 'single']` are\n currently supported. Defaults to 'mix'.\n eval_style_mode (str, optional): The evaluation mode of style mixing.\n Defaults to 'single'.\n mix_prob (float, optional): Mixing probability. The value should be\n in range of [0, 1]. Defaults to 0.9.\n pretrained (dict | None, optional): Information for pretained models.\n The necessary key is 'ckpt_path'. Besides, you can also provide\n 'prefix' to load the generator part from the whole state dict.\n Defaults to None.\n bgr2rgb (bool, optional): Whether to flip the image channel dimension.\n Defaults to False.\n \"\"\"\n\n def __init__(self,\n in_size,\n out_size,\n img_channels=3,\n rrdb_channels=64,\n num_rrdbs=23,\n style_channels=512,\n num_mlps=8,\n channel_multiplier=2,\n blur_kernel=[1, 3, 3, 1],\n lr_mlp=0.01,\n default_style_mode='mix',\n eval_style_mode='single',\n mix_prob=0.9,\n pretrained=None,\n bgr2rgb=False):\n\n super().__init__()\n\n # input size must be strictly smaller than output size\n if in_size >= out_size:\n raise ValueError('in_size must be smaller than out_size, but got '\n f'{in_size} and {out_size}.')\n\n # latent bank (StyleGANv2), with weights being fixed\n self.generator = build_component(\n dict(\n type='StyleGANv2Generator',\n out_size=out_size,\n style_channels=style_channels,\n num_mlps=num_mlps,\n channel_multiplier=channel_multiplier,\n blur_kernel=blur_kernel,\n lr_mlp=lr_mlp,\n default_style_mode=default_style_mode,\n eval_style_mode=eval_style_mode,\n mix_prob=mix_prob,\n pretrained=pretrained,\n bgr2rgb=bgr2rgb))\n self.generator.requires_grad_(False)\n\n self.in_size = in_size\n self.style_channels = style_channels\n channels = self.generator.channels\n\n # encoder\n num_styles = int(np.log2(out_size)) * 2 - 2\n encoder_res = [2**i for i in range(int(np.log2(in_size)), 1, -1)]\n self.encoder = nn.ModuleList()\n self.encoder.append(\n nn.Sequential(\n RRDBFeatureExtractor(\n img_channels, rrdb_channels, num_blocks=num_rrdbs),\n nn.Conv2d(\n rrdb_channels, channels[in_size], 3, 1, 1, bias=True),\n nn.LeakyReLU(negative_slope=0.2, inplace=True)))\n for res in encoder_res:\n in_channels = channels[res]\n if res > 4:\n out_channels = channels[res // 2]\n block = nn.Sequential(\n nn.Conv2d(in_channels, out_channels, 3, 2, 1, bias=True),\n nn.LeakyReLU(negative_slope=0.2, inplace=True),\n nn.Conv2d(out_channels, out_channels, 3, 1, 1, bias=True),\n nn.LeakyReLU(negative_slope=0.2, inplace=True))\n else:\n block = nn.Sequential(\n nn.Conv2d(in_channels, in_channels, 3, 1, 1, bias=True),\n nn.LeakyReLU(negative_slope=0.2, inplace=True),\n nn.Flatten(),\n nn.Linear(16 * in_channels, num_styles * style_channels))\n self.encoder.append(block)\n\n # additional modules for StyleGANv2\n self.fusion_out = nn.ModuleList()\n self.fusion_skip = nn.ModuleList()\n for res in encoder_res[::-1]:\n num_channels = channels[res]\n self.fusion_out.append(\n nn.Conv2d(num_channels * 2, num_channels, 3, 1, 1, bias=True))\n self.fusion_skip.append(\n nn.Conv2d(num_channels + 3, 3, 3, 1, 1, bias=True))\n\n # decoder\n decoder_res = [\n 2**i\n for i in range(int(np.log2(in_size)), int(np.log2(out_size) + 1))\n ]\n self.decoder = nn.ModuleList()\n for res in decoder_res:\n if res == in_size:\n in_channels = channels[res]\n else:\n in_channels = 2 * channels[res]\n\n if res < out_size:\n out_channels = channels[res * 2]\n self.decoder.append(\n PixelShufflePack(\n in_channels, out_channels, 2, upsample_kernel=3))\n else:\n self.decoder.append(\n nn.Sequential(\n nn.Conv2d(in_channels, 64, 3, 1, 1),\n nn.LeakyReLU(negative_slope=0.2, inplace=True),\n nn.Conv2d(64, img_channels, 3, 1, 1)))\n\n def forward(self, lq):\n \"\"\"Forward function.\n\n Args:\n lq (Tensor): Input LR image with shape (n, c, h, w).\n\n Returns:\n Tensor: Output HR image.\n \"\"\"\n\n h, w = lq.shape[2:]\n if h != self.in_size or w != self.in_size:\n raise AssertionError(\n f'Spatial resolution must equal in_size ({self.in_size}).'\n f' Got ({h}, {w}).')\n\n # encoder\n feat = lq\n encoder_features = []\n for block in self.encoder:\n feat = block(feat)\n encoder_features.append(feat)\n encoder_features = encoder_features[::-1]\n\n latent = encoder_features[0].view(lq.size(0), -1, self.style_channels)\n encoder_features = encoder_features[1:]\n\n # generator\n injected_noise = [\n getattr(self.generator, f'injected_noise_{i}')\n for i in range(self.generator.num_injected_noises)\n ]\n # 4x4 stage\n out = self.generator.constant_input(latent)\n out = self.generator.conv1(out, latent[:, 0], noise=injected_noise[0])\n skip = self.generator.to_rgb1(out, latent[:, 1])\n\n _index = 1\n\n # 8x8 ---> higher res\n generator_features = []\n for up_conv, conv, noise1, noise2, to_rgb in zip(\n self.generator.convs[::2], self.generator.convs[1::2],\n injected_noise[1::2], injected_noise[2::2],\n self.generator.to_rgbs):\n\n # feature fusion by channel-wise concatenation\n if out.size(2) <= self.in_size:\n fusion_index = (_index - 1) // 2\n feat = encoder_features[fusion_index]\n\n out = torch.cat([out, feat], dim=1)\n out = self.fusion_out[fusion_index](out)\n\n skip = torch.cat([skip, feat], dim=1)\n skip = self.fusion_skip[fusion_index](skip)\n\n # original StyleGAN operations\n out = up_conv(out, latent[:, _index], noise=noise1)\n out = conv(out, latent[:, _index + 1], noise=noise2)\n skip = to_rgb(out, latent[:, _index + 2], skip)\n\n # store features for decoder\n if out.size(2) > self.in_size:\n generator_features.append(out)\n\n _index += 2\n\n # decoder\n hr = encoder_features[-1]\n for i, block in enumerate(self.decoder):\n if i > 0:\n hr = torch.cat([hr, generator_features[i - 1]], dim=1)\n hr = block(hr)\n\n return hr\n\n def init_weights(self, pretrained=None, strict=True):\n \"\"\"Init weights for models.\n\n Args:\n pretrained (str, optional): Path for pretrained weights. If given\n None, pretrained weights will not be loaded. Defaults to None.\n strict (boo, optional): Whether strictly load the pretrained model.\n Defaults to True.\n \"\"\"\n if isinstance(pretrained, str):\n logger = get_root_logger()\n load_checkpoint(self, pretrained, strict=strict, logger=logger)\n elif pretrained is not None:\n raise TypeError(f'\"pretrained\" must be a str or None. '\n f'But received {type(pretrained)}.')\n\n\nclass RRDBFeatureExtractor(nn.Module):\n \"\"\"Feature extractor composed of Residual-in-Residual Dense Blocks (RRDBs).\n\n It is equivalent to ESRGAN with the upsampling module removed.\n\n Args:\n in_channels (int): Channel number of inputs.\n mid_channels (int): Channel number of intermediate features.\n Default: 64\n num_blocks (int): Block number in the trunk network. Default: 23\n growth_channels (int): Channels for each growth. Default: 32.\n \"\"\"\n\n def __init__(self,\n in_channels=3,\n mid_channels=64,\n num_blocks=23,\n growth_channels=32):\n\n super().__init__()\n\n self.conv_first = nn.Conv2d(in_channels, mid_channels, 3, 1, 1)\n self.body = make_layer(\n RRDB,\n num_blocks,\n mid_channels=mid_channels,\n growth_channels=growth_channels)\n self.conv_body = nn.Conv2d(mid_channels, mid_channels, 3, 1, 1)\n\n def forward(self, x):\n \"\"\"Forward function.\n\n Args:\n x (Tensor): Input tensor with shape (n, c, h, w).\n\n Returns:\n Tensor: Forward results.\n \"\"\"\n\n feat = self.conv_first(x)\n return feat + self.conv_body(self.body(feat))\n",
"# Copyright (c) OpenMMLab. All rights reserved.\nimport pytest\nimport torch\n\nfrom mmedit.models.components import (DeepFillv1Discriminators,\n MultiLayerDiscriminator)\n\n\ndef test_deepfillv1_disc():\n model_config = dict(\n global_disc_cfg=dict(\n type='MultiLayerDiscriminator',\n in_channels=3,\n max_channels=256,\n fc_in_channels=256 * 16 * 16,\n fc_out_channels=1,\n num_convs=4,\n norm_cfg=None,\n act_cfg=dict(type='ELU'),\n out_act_cfg=dict(type='LeakyReLU', negative_slope=0.2)),\n local_disc_cfg=dict(\n type='MultiLayerDiscriminator',\n in_channels=3,\n max_channels=512,\n fc_in_channels=512 * 8 * 8,\n fc_out_channels=1,\n num_convs=4,\n norm_cfg=None,\n act_cfg=dict(type='ELU'),\n out_act_cfg=dict(type='LeakyReLU', negative_slope=0.2)))\n disc = DeepFillv1Discriminators(**model_config)\n disc.init_weights()\n global_x = torch.rand((2, 3, 256, 256))\n local_x = torch.rand((2, 3, 128, 128))\n global_pred, local_pred = disc((global_x, local_x))\n assert global_pred.shape == (2, 1)\n assert local_pred.shape == (2, 1)\n assert isinstance(disc.global_disc, MultiLayerDiscriminator)\n assert isinstance(disc.local_disc, MultiLayerDiscriminator)\n\n with pytest.raises(TypeError):\n disc.init_weights(model_config)\n\n if torch.cuda.is_available():\n disc = DeepFillv1Discriminators(**model_config).cuda()\n disc.init_weights()\n global_x = torch.rand((2, 3, 256, 256)).cuda()\n local_x = torch.rand((2, 3, 128, 128)).cuda()\n global_pred, local_pred = disc((global_x, local_x))\n assert global_pred.shape == (2, 1)\n assert local_pred.shape == (2, 1)\n",
"# Copyright (c) OpenMMLab. All rights reserved.\nimport torch\n\nfrom mmedit.models.builder import build_component\n\n\ndef test_search_transformer():\n model_cfg = dict(type='SearchTransformer')\n model = build_component(model_cfg)\n\n lr_pad_level3 = torch.randn((2, 32, 32, 32))\n ref_pad_level3 = torch.randn((2, 32, 32, 32))\n ref_level3 = torch.randn((2, 32, 32, 32))\n ref_level2 = torch.randn((2, 16, 64, 64))\n ref_level1 = torch.randn((2, 8, 128, 128))\n\n s, textures = model(lr_pad_level3, ref_pad_level3,\n (ref_level3, ref_level2, ref_level1))\n t_level3, t_level2, t_level1 = textures\n\n assert s.shape == (2, 1, 32, 32)\n assert t_level3.shape == (2, 32, 32, 32)\n assert t_level2.shape == (2, 16, 64, 64)\n assert t_level1.shape == (2, 8, 128, 128)\n"
] | [
[
"torch.no_grad",
"torch.rand",
"torch.cuda.is_available"
],
[
"numpy.log2",
"torch.cat",
"torch.nn.ModuleList",
"torch.nn.Conv2d",
"torch.nn.Flatten",
"torch.nn.Linear",
"torch.nn.LeakyReLU"
],
[
"torch.rand",
"torch.cuda.is_available"
],
[
"torch.randn"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
MochiYoshi/fix_attempt_mplleaflet | [
"a6ffc379d1427bbd9e6905a47bb868afa2850043"
] | [
"mplleaflet/leaflet_renderer.py"
] | [
"from __future__ import absolute_import\n\nfrom functools import partial\n\nfrom jinja2 import Template\nfrom .mplexporter.renderers.base import Renderer\nimport numpy as np\n\nfrom .utils import iter_rings\n\n\nsvg_template = Template(\"\"\"<svg width=\"{{ width|int }}px\" height=\"{{ height|int }}px\" viewBox=\"{{ minx }} {{ miny }} {{ width }} {{ height }}\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <path d=\"{{ path }}\" {% for k, v in style.items() %}{{ k }}=\"{{ v }}\" {% endfor %}/></svg>\"\"\")\n\n_marker_inflation = 1.25\n\nclass LeafletRenderer(Renderer):\n def __init__(self, crs=None, epsg=None):\n if crs is not None and epsg is not None:\n raise ValueError('crs and epsg cannot both be specified')\n\n if epsg is not None:\n crs = 'epsg:{}'.format(epsg)\n if crs is not None:\n import pyproj\n crs_out = 'epsg:{}'.format(4326)\n\n # old code for pyproj 1.9.6 or below\n # proj_in = pyproj.Proj(crs)\n # proj_out = pyproj.Proj(crs_out)\n # self.transformfunc = partial(pyproj.transform, proj_in, proj_out)\n\n # new code for pyproj >= 2.0.0\n proj_in = pyproj.CRS(crs)\n proj_out = pyproj.CRS(crs_out)\n transformer = pyproj.Transformer.from_crs(proj_in, proj_out, always_xy=True)\n self.transformfunc = partial(transformer.transform)\n else:\n self.transformfunc = None\n\n self._features = []\n\n\n def geojson(self):\n fc = {\n \"type\": \"FeatureCollection\",\n \"features\": self._features,\n }\n return fc\n\n\n def _convert_style(self, style):\n leaflet_style = {\n 'color': style['edgecolor'],\n 'weight': style['edgewidth'],\n 'opacity': style['alpha'],\n 'fillOpacity': style['alpha'],\n }\n if style['facecolor'] != 'none':\n leaflet_style['fillColor'] = style['facecolor']\n if style['dasharray'] != 'none':\n leaflet_style['dashArray'] = style['dasharray']\n\n return leaflet_style\n\n def _convert_style_svg(self, style):\n svg_style = {\n 'stroke': style['edgecolor'],\n 'stroke-width': style['edgewidth'],\n 'stroke-opacity': style['alpha'],\n }\n if style['facecolor'] != 'none':\n svg_style['fill'] = style['facecolor']\n svg_style['fill-opacity'] = style['alpha']\n\n return svg_style\n\n def _svg_path(self, pathcodes, data):\n \"\"\"\n Return the SVG path's 'd' element.\n\n \"\"\"\n def gen_path_elements(pathcodes, data):\n counts = {'M': 1, 'L': 1, 'C': 3, 'Z': 0}\n it = iter(data)\n for code in pathcodes:\n yield code\n for _ in range(counts[code]):\n p = next(it)\n yield str(p[0])\n yield str(p[1])\n\n return ' '.join(gen_path_elements(pathcodes, data))\n\n\n def draw_path(self, data, coordinates, pathcodes, style,\n offset=None, offset_coordinates=\"data\", mplobj=None):\n properties = self._convert_style(style)\n if coordinates == 'points' or coordinates == 'display':\n # Flip the points about y-axis to align with SVG coordinate\n # system.\n path_points = data.copy()\n path_points[:,1] *= -1\n if offset_coordinates != 'data':\n pass # Don't know how to work with this yet\n if self.transformfunc:\n coords = self.transformfunc(*offset)\n else:\n coords = list(offset)\n geometry_type = 'Point'\n\n # Find the size of the path, and increase by inflation\n mx = np.max(path_points, axis=0)\n mn = np.min(path_points, axis=0)\n\n center = mn + (mx - mn) / 2.0\n size = np.ceil(_marker_inflation * (mx - mn))\n corner = center - size / 2.0\n svg = svg_template.render(\n path=self._svg_path(pathcodes, path_points),\n style=self._convert_style_svg(style),\n width=size[0],\n height=size[1],\n minx=corner[0],\n miny=corner[1],\n )\n properties = {'html': svg,\n 'anchor_x': -corner[0],\n 'anchor_y': -corner[1]}\n else:\n if self.transformfunc:\n data = [self.transformfunc(*c) for c in data]\n else:\n data = [c.tolist() for c in data]\n rings = list(iter_rings(data, pathcodes))\n\n if style['facecolor'] != 'none':\n # It's a polygon\n geometry_type = 'Polygon'\n coords = rings\n else:\n geometry_type = 'LineString'\n coords = rings[0]\n\n feature = {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": geometry_type,\n \"coordinates\": coords,\n },\n \"properties\": properties\n }\n\n self._features.append(feature)\n\n def draw_text(self, *args, **kwargs):\n \"\"\" Don't draw the text for now, but don't crash \"\"\"\n pass\n\n# old no longer used as replaced directly in leafletrenderer class initialisation\n# def _crs_from_epsg(epsg):\n# epsgstr = 'epsg:{}'.format(epsg)\n# crs = {'init': epsgstr, 'no_defs': True}\n# return crs"
] | [
[
"numpy.max",
"numpy.ceil",
"numpy.min"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
roy860328/VSGM | [
"3ec19f9cf1401cecf45527687936b8fe4167f672",
"3ec19f9cf1401cecf45527687936b8fe4167f672",
"3ec19f9cf1401cecf45527687936b8fe4167f672",
"3ec19f9cf1401cecf45527687936b8fe4167f672"
] | [
"alfworld/agents/semantic_graph/gcn.py",
"alfred/models/eval_moca/eval_semantic.py",
"alfred/models/model/gcn_depth_im.py",
"alfred/models/model/seq2seq_semantic.py"
] | [
"import torch\nimport torch.nn.functional as F\nfrom torch import nn\nfrom torch_geometric.nn import GCNConv\nfrom . import graph_embed\n\n\nclass Net(torch.nn.Module):\n \"\"\"docstring for Net\"\"\"\n def __init__(self, cfg, config=None, PRINT_DEBUG=False):\n super(Net, self).__init__()\n input_size = cfg.SCENE_GRAPH.NODE_FEATURE_SIZE\n middle_size = cfg.SCENE_GRAPH.NODE_MIDDEL_FEATURE_SIZE\n output_size = cfg.SCENE_GRAPH.NODE_OUT_FEATURE_SIZE\n # True => one of the variables needed for gradient computation has been modified by an inplace operation\n normalize = cfg.SCENE_GRAPH.NORMALIZATION\n self.cfg = cfg\n self.conv1 = GCNConv(input_size, middle_size, cached=True,\n normalize=normalize,\n # add_self_loops=False\n )\n self.conv2 = GCNConv(middle_size, output_size, cached=True,\n normalize=normalize,\n # add_self_loops=False\n )\n graph_embed_model = getattr(graph_embed, cfg.SCENE_GRAPH.EMBED_TYPE)\n NODE_FEATURE_SIZE = cfg.SCENE_GRAPH.NODE_OUT_FEATURE_SIZE\n EMBED_FEATURE_SIZE = cfg.SCENE_GRAPH.EMBED_FEATURE_SIZE\n self.final_mapping = graph_embed_model(\n INPUT_FEATURE_SIZE=NODE_FEATURE_SIZE,\n EMBED_FEATURE_SIZE=EMBED_FEATURE_SIZE\n )\n if cfg.SCENE_GRAPH.CHOSE_IMPORTENT_NODE:\n # nn.linear bert_hidden_size -> NODE_FEATURE_SIZE\n bert_hidden_size = config['general']['model']['block_hidden_dim']\n NODE_FEATURE_SIZE = cfg.SCENE_GRAPH.NODE_OUT_FEATURE_SIZE + cfg.SCENE_GRAPH.ATTRIBUTE_FEATURE_SIZE\n NUM_CHOSE_NODE = cfg.SCENE_GRAPH.NUM_CHOSE_NODE\n self.chose_node_module = graph_embed.DotAttnChoseImportentNode(\n bert_hidden_size,\n NODE_FEATURE_SIZE,\n NUM_CHOSE_NODE,\n PRINT_DEBUG=PRINT_DEBUG\n )\n\n def forward(self, data, *args):\n '''\n data.x\n tensor([[-0.0474, 0.0324, 0.1443, ..., 1.0000, 0.0000, 0.0000],\n [ 0.0440, -0.0058, 0.0014, ..., 1.0000, 0.0000, 0.0000],\n [ 0.0057, 0.0471, 0.0377, ..., 1.0000, 0.0000, 0.0000],\n [ 0.0724, -0.0065, -0.0210, ..., 0.0000, 0.0000, 0.0000],\n [-0.0474, 0.0324, 0.1443, ..., 1.0000, 0.0000, 0.0000]],\n grad_fn=<CatBackward>)\n data.edge_obj_to_obj\n tensor([[3, 0],\n [3, 1],\n [3, 2],\n [3, 4]])\n data.obj_cls_to_ind\n {64: [0, 4], 70: [1], 47: [2], 81: [3]}\n data.obj_id_to_ind\n {'Pillow|-02.89|+00.62|+00.82': 0, 'RemoteControl|-03.03|+00.56|+02.01': 1, 'Laptop|-02.81|+00.56|+01.81': 2, 'Sofa|-02.96|+00.08|+01.39': 3, 'Pillow|-02.89|+00.62|+01.19': 4}\n '''\n # import pdb; pdb.set_trace()\n # x, edge_obj_to_obj, edge_weight = data.x, data.edge_obj_to_obj, data.edge_attr\n x, edge_obj_to_obj, edge_weight = data.x, data.edge_obj_to_obj, data.edge_attr\n if edge_obj_to_obj is not None:\n x = x.clone().detach()\n edge_obj_to_obj = edge_obj_to_obj.clone().detach()\n x = F.relu(self.conv1(x, edge_obj_to_obj, edge_weight))\n x = F.dropout(x, training=self.training)\n x = F.relu(self.conv2(x, edge_obj_to_obj, edge_weight))\n # x = self.conv2(x, edge_obj_to_obj, edge_weight)\n if self.cfg.SCENE_GRAPH.CHOSE_IMPORTENT_NODE:\n chose_nodes = self.self.chose_node_module(x)\n x = self.final_mapping(x)\n x = torch.cat([x, chose_nodes], dim=1)\n else:\n x = torch.zeros((1, self.cfg.SCENE_GRAPH.RESULT_FEATURE))\n if self.cfg.SCENE_GRAPH.GPU:\n x = x.to('cuda')\n return x\n",
"import matplotlib\nmatplotlib.use('Agg')\nimport os\nimport sys\nsys.path.append(os.path.join(os.environ['ALFRED_ROOT']))\nsys.path.append(os.path.join(os.environ['ALFRED_ROOT'], 'gen'))\nsys.path.append(os.path.join(os.environ['ALFRED_ROOT'], 'models'))\nsys.path.append(os.path.join(os.environ['ALFWORLD_ROOT'], 'agents'))\nimport argparse\nimport torch.multiprocessing as mp\nfrom eval_task import EvalTask\nfrom eval_subgoals import EvalSubgoals\n\n\ndef load_config(args):\n import yaml\n import glob\n assert os.path.exists(args.config_file), \"Invalid config file \"\n with open(args.config_file) as reader:\n config = yaml.safe_load(reader)\n # Parse overriden params.\n for param in args.params:\n fqn_key, value = param.split(\"=\")\n entry_to_change = config\n keys = fqn_key.split(\".\")\n for k in keys[:-1]:\n entry_to_change = entry_to_change[k]\n entry_to_change[keys[-1]] = yaml.load(value)\n\n ### other ###\n if args.semantic_config_file is not None:\n sys.path.insert(0, os.path.join(os.environ['ALFWORLD_ROOT'], 'agents'))\n from config import cfg\n cfg.merge_from_file(args.semantic_config_file)\n cfg.GENERAL.save_path = cfg.GENERAL.save_path + sys.argv[0].split(\"/\")[-1] + \"_\"\n config['semantic_cfg'] = cfg\n config[\"general\"][\"save_path\"] = cfg.GENERAL.save_path\n config[\"vision_dagger\"][\"use_exploration_frame_feats\"] = cfg.GENERAL.use_exploration_frame_feats\n if args.sgg_config_file is not None:\n sys.path.insert(0, os.environ['GRAPH_RCNN_ROOT'])\n from lib.config import cfg\n cfg.merge_from_file(args.sgg_config_file)\n config['sgg_cfg'] = cfg\n # print(config)\n\n return config\n\n\nif __name__ == '__main__':\n # multiprocessing settings\n mp.set_start_method('spawn')\n manager = mp.Manager()\n\n # parser\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"config_file\", default=\"models/config/without_env_base.yaml\", help=\"path to config file\")\n parser.add_argument(\"--semantic_config_file\", default=\"models/config/mini_moca_graph_softmaxgcn.yaml\", help=\"path to config file\")\n parser.add_argument(\"--sgg_config_file\", default=None, help=\"path to config file $GRAPH_RCNN_ROOT/configs/attribute.yaml\")\n parser.add_argument(\"-p\", \"--params\", nargs=\"+\", metavar=\"my.setting=value\", default=[],\n help=\"override params of the config file,\"\n \" e.g. -p 'training.gamma=0.95'\")\n\n # settings\n parser.add_argument('--splits', type=str, default=\"data/splits/oct21.json\")\n parser.add_argument('--data', type=str, default=\"data/json_2.1.0\")\n parser.add_argument('--reward_config', default='models/config/rewards.json')\n parser.add_argument('--eval_split', type=str, default='valid_seen', choices=['train', 'valid_seen', 'valid_unseen', 'tests_seen', 'tests_unseen'])\n parser.add_argument('--model_path', type=str, default=\"model.pth\")\n parser.add_argument('--model', type=str, default='models.model.seq2seq_im_mask')\n parser.add_argument('--preprocess', dest='preprocess', action='store_true')\n parser.add_argument('--shuffle', dest='shuffle', action='store_true')\n parser.add_argument('--gpu', dest='gpu', action='store_true')\n parser.add_argument('--gpu_id', help='use gpu 0/1', default=1, type=int)\n parser.add_argument('--num_threads', type=int, default=1)\n parser.add_argument('--gcn_cat_visaul', help='use visual embedding to gcn', action='store_true')\n\n # eval params\n parser.add_argument('--max_steps', type=int, default=1000, help='max steps before episode termination')\n parser.add_argument('--max_fails', type=int, default=10, help='max API execution failures before episode termination')\n\n # eval settings\n parser.add_argument('--subgoals', type=str, help=\"subgoals to evaluate independently, eg:all or GotoLocation,PickupObject...\", default=\"\")\n parser.add_argument('--smooth_nav', dest='smooth_nav', action='store_true', help='smooth nav actions (might be required based on training data)')\n parser.add_argument('--skip_model_unroll_with_expert', action='store_true', help='forward model with expert actions')\n parser.add_argument('--no_teacher_force_unroll_with_expert', action='store_true', help='no teacher forcing with expert')\n\n # debug\n parser.add_argument('--debug', dest='debug', action='store_true')\n parser.add_argument('--fast_epoch', dest='fast_epoch', action='store_true')\n\n parser.add_argument('--task_types', type=str, help=\"task_types\", default=\"1,2,3,4,5,6\")\n # parse arguments\n args = parser.parse_args()\n config = load_config(args)\n args.config_file = config\n # import torch\n # device = torch.device(\"cuda:%d\" % args.gpu_id if args.gpu else \"cpu\")\n # if args.gpu and torch.cuda.is_available():\n # torch.cuda.set_device(device)\n # eval mode\n if args.subgoals:\n eval = EvalSubgoals(args, manager)\n else:\n eval = EvalTask(args, manager)\n\n # start threads\n eval.spawn_threads()",
"import os\nfrom sys import platform\nimport torch\nimport numpy as np\nimport nn.vnn as vnn\nimport collections\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence\nfrom model.seq2seq import Module as Base\nfrom model.gcn import GCN, GCNVisual\nfrom model.dgl_gcn_hete import NetGCN, HETLOWSG\nfrom models.utils.metric import compute_f1, compute_exact\nfrom gen.utils.image_util import decompress_mask\nimport cv2\n\n\nclass Module(Base):\n\n def __init__(self, args, vocab):\n '''\n Seq2Seq agent\n '''\n super().__init__(args, vocab)\n\n # encoder and self-attention\n # [batch, sentance, out_feat]\n self.enc = nn.LSTM(args.demb, args.dhid, bidirectional=True, batch_first=True)\n self.device = torch.device(\"cuda:%d\" % args.gpu_id if torch.cuda.is_available() and args.gpu else \"cpu\")\n self.enc_att = vnn.SelfAttn(args.dhid*2)\n self.enc = self.enc.to(device=self.device)\n\n # subgoal monitoring\n self.subgoal_monitoring = (self.args.pm_aux_loss_wt >\n 0 or self.args.subgoal_aux_loss_wt > 0)\n\n # gcn\n if \"model_hete_graph\" in args and args.model_hete_graph:\n if \"HETAttention\" not in self.args:\n self.args.HETAttention = False\n self.gcn = HETLOWSG(self.args.HETAttention, args.dgcnout, self.device) if \"HetLowSg\" in args and args.HetLowSg else NetGCN(self.args.HETAttention, args.dgcnout, self.device)\n else:\n self.gcn = GCNVisual(args.dgcnout) if args.gcn_cat_visaul else GCN(args.dgcnout)\n # self.gcn = self.gcn.to(device)\n self.enc_depth = vnn.VisualEncoder(args.dframe)\n # self.enc_depth = self.enc_depth.to(device)\n\n # frame mask decoder\n # decoder = vnn.ConvFrameMaskDecoderProgressMonitor if self.subgoal_monitoring else vnn.ConvFrameMaskDecoder\n decoder = vnn.DepthConvFrameMaskAttentionDecoderProgressMonitor if args.HETAttention else vnn.DepthConvFrameMaskDecoderProgressMonitor\n self.dec = decoder(self.emb_action_low, args.dframe, 2*args.dhid, args.dgcnout,\n args.dframedepth,\n pframe=args.pframe,\n attn_dropout=args.attn_dropout,\n hstate_dropout=args.hstate_dropout,\n actor_dropout=args.actor_dropout,\n input_dropout=args.input_dropout,\n teacher_forcing=args.dec_teacher_forcing)\n self.dec = self.dec.to(device=self.device)\n\n # dropouts\n self.vis_dropout = nn.Dropout(args.vis_dropout)\n self.lang_dropout = nn.Dropout(args.lang_dropout, inplace=True)\n self.input_dropout = nn.Dropout(args.input_dropout)\n\n # internal states\n self.state_t = None\n self.e_t = None\n self.test_mode = False\n\n # bce reconstruction loss\n self.bce_with_logits = torch.nn.BCEWithLogitsLoss(reduction='none')\n self.mse_loss = torch.nn.MSELoss(reduction='none')\n\n # paths\n self.root_path = os.getcwd()\n self.feat_pt = 'feat_conv.pt'\n self.feat_depth_pt = 'feat_depth.pt'\n self.feat_depth = 'depth_images'\n\n # params\n self.max_subgoals = 25\n\n # reset model\n self.reset()\n\n def featurize(self, batch, load_mask=True, load_frames=True):\n '''\n tensorize and pad batch input\n '''\n device = torch.device(\"cuda:%d\" % self.args.gpu_id) if self.args.gpu else torch.device('cpu')\n feat = collections.defaultdict(list)\n\n for ex in batch:\n ###########\n # auxillary\n ###########\n\n if not self.test_mode:\n # subgoal completion supervision\n if self.args.subgoal_aux_loss_wt > 0:\n feat['subgoals_completed'].append(\n np.array(ex['num']['low_to_high_idx']) / self.max_subgoals)\n\n # progress monitor supervision\n if self.args.pm_aux_loss_wt > 0:\n num_actions = len([a for sg in ex['num']['action_low'] for a in sg])\n subgoal_progress = [(i+1)/float(num_actions) for i in range(num_actions)]\n feat['subgoal_progress'].append(subgoal_progress)\n\n #########\n # inputs\n #########\n # serialize segments\n self.serialize_lang_action(ex)\n\n # goal and instr language\n lang_goal, lang_instr = ex['num']['lang_goal'], ex['num']['lang_instr']\n\n # zero inputs if specified\n lang_goal = self.zero_input(lang_goal) if self.args.zero_goal else lang_goal\n lang_instr = self.zero_input(lang_instr) if self.args.zero_instr else lang_instr\n\n # append goal + instr\n lang_goal_instr = lang_goal + lang_instr\n feat['lang_goal_instr'].append(lang_goal_instr)\n\n # load Resnet features from disk\n if load_frames and not self.test_mode:\n root = self.get_task_root(ex)\n im = torch.load(os.path.join(root, self.feat_pt))\n # depth\n path_img_depth = os.path.join(root, self.feat_depth)\n self._load_img(feat, path_img_depth, \"frames_depth\", ex[\"images\"])\n\n num_low_actions = len(ex['plan']['low_actions'])\n num_feat_frames = im.shape[0]\n\n if num_low_actions != num_feat_frames:\n keep = [None] * len(ex['plan']['low_actions'])\n for i, d in enumerate(ex['images']):\n # only add frames linked with low-level actions (i.e. skip filler frames like smooth rotations and dish washing)\n if keep[d['low_idx']] is None:\n keep[d['low_idx']] = im[i]\n keep.append(keep[-1]) # stop frame\n feat['frames'].append(torch.stack(keep, dim=0))\n else:\n feat['frames'].append(\n torch.cat([im, im[-1].unsqueeze(0)], dim=0)) # add stop frame\n # import pdb; pdb.set_trace()\n\n #########\n # outputs\n #########\n\n if not self.test_mode:\n # low-level action\n feat['action_low'].append([a['action'] for a in ex['num']['action_low']])\n\n # low-level action mask\n if load_mask:\n feat['action_low_mask'].append([self.decompress_mask(\n a['mask']) for a in ex['num']['action_low'] if a['mask'] is not None])\n\n # low-level valid interact\n feat['action_low_valid_interact'].append(\n [a['valid_interact'] for a in ex['num']['action_low']])\n\n # tensorization and padding\n for k, v in feat.items():\n if k in {'lang_goal_instr'}:\n # language embedding and padding\n # import pdb; pdb.set_trace()\n seqs = [torch.tensor(vv, device=device) for vv in v]\n pad_seq = pad_sequence(seqs, batch_first=True, padding_value=self.pad)\n seq_lengths = np.array(list(map(len, v)))\n import pdb; pdb.set_trace()\n embed_seq = self.emb_word(pad_seq)\n packed_input = pack_padded_sequence(\n embed_seq, seq_lengths, batch_first=True, enforce_sorted=False)\n feat[k] = packed_input\n elif k in {'action_low_mask'}:\n # mask padding\n seqs = [torch.tensor(vv, device=device, dtype=torch.float) for vv in v]\n feat[k] = seqs\n elif k in {'subgoal_progress', 'subgoals_completed'}:\n # auxillary padding\n seqs = [torch.tensor(vv, device=device, dtype=torch.float) for vv in v]\n pad_seq = pad_sequence(seqs, batch_first=True, padding_value=self.pad)\n feat[k] = pad_seq\n else:\n # default: tensorize and pad sequence\n seqs = [torch.tensor(vv, device=device, dtype=torch.float if (\n 'frames' in k) else torch.long) for vv in v]\n pad_seq = pad_sequence(seqs, batch_first=True, padding_value=self.pad)\n feat[k] = pad_seq\n\n # import pdb; pdb.set_trace()\n # len(feat['action_low'][0])\n # feat['frames'][0].shape\n return feat\n\n def serialize_lang_action(self, feat):\n '''\n append segmented instr language and low-level actions into single sequences\n '''\n is_serialized = not isinstance(feat['num']['lang_instr'][0], list)\n if not is_serialized:\n feat['num']['lang_instr'] = [word for desc in feat['num']['lang_instr']\n for word in desc]\n if not self.test_mode:\n feat['num']['action_low'] = [a for a_group in feat['num']['action_low']\n for a in a_group]\n\n def decompress_mask(self, compressed_mask):\n '''\n decompress mask from json files\n '''\n # import pdb; pdb.set_trace()\n mask = np.array(decompress_mask(compressed_mask))\n mask = np.expand_dims(mask, axis=0)\n return mask\n\n # according to traj.json to load depth image\n def _load_img(self, feat, root, key_name, list_img_traj):\n \"\"\"\n feat: for save image feature\n root: image path\n key_name: \"frames_depth\" or other\n list_img_traj: traj_data[\"images\"]. To chose feat[key_name] file\n \"\"\"\n def _load_with_path():\n frames_depth = None\n low_idx = -1\n for i, dict_frame in enumerate(list_img_traj):\n # 60 actions need 61 frames\n if low_idx != dict_frame[\"low_idx\"]:\n low_idx = dict_frame[\"low_idx\"]\n else:\n continue\n name_frame = dict_frame[\"image_name\"].split(\".\")[0]\n frame_path = os.path.join(path, name_frame + \".png\")\n # for debug\n if platform == \"win32\":\n frame_path = \"D:\\\\AI2\\\\homealfreddatafull_2.1.0trainpick_clean_then_place_in_recep-Lettuc\\\\000000160.jpg\"\n if os.path.isfile(frame_path):\n img_depth = cv2.imread(frame_path, 0)\n else:\n # print(\"file is not exist: {}\".format(frame_path))\n img_depth = np.zeros(img_depth.shape[1:])\n img_depth = torch.tensor(img_depth, dtype=torch.int).unsqueeze(0)\n\n if frames_depth is None:\n frames_depth = img_depth\n else:\n frames_depth = torch.cat([frames_depth, img_depth], dim=0)\n frames_depth = torch.cat([frames_depth, frames_depth[-1].unsqueeze(0)], dim=0)\n try:\n torch.save(frames_depth, os.path.join(root, self.feat_depth_pt))\n except Exception as e:\n print(\"No such path\")\n return frames_depth\n def _load_with_pt():\n frames_depth = torch.load(os.path.join(root, self.feat_depth_pt))\n return frames_depth\n path = os.path.join(os.getcwd(), root)\n path_feat_depth = os.path.join(path, \"feat_depth.pt\")\n if os.path.isfile(path_feat_depth):\n frames_depth = _load_with_pt()\n else:\n print(\"feat_depth.pt doesn't exist: {}\".format(path_feat_depth))\n frames_depth = _load_with_path()\n # feat[\"frames_depth\"]\n # import pdb; pdb.set_trace()\n feat[key_name].append(frames_depth)\n\n def forward(self, feat, max_decode=300):\n cont_lang, enc_lang = self.encode_lang(feat)\n state_0 = cont_lang, torch.zeros_like(cont_lang)\n # import pdb; pdb.set_trace()\n frames = self.vis_dropout(feat['frames'])\n frames_depth = self.enc_depth(feat['frames_depth'])\n gcn_embedding = self.gcn(frames)\n res = self.dec(enc_lang, frames, gcn_embedding, frames_depth, max_decode=max_decode,\n gold=feat['action_low'], state_0=state_0)\n feat.update(res)\n return feat\n\n def encode_lang(self, feat):\n '''\n encode goal+instr language\n '''\n emb_lang_goal_instr = feat['lang_goal_instr']\n self.lang_dropout(emb_lang_goal_instr.data)\n enc_lang_goal_instr, _ = self.enc(emb_lang_goal_instr)\n enc_lang_goal_instr, _ = pad_packed_sequence(enc_lang_goal_instr, batch_first=True)\n self.lang_dropout(enc_lang_goal_instr)\n cont_lang_goal_instr = self.enc_att(enc_lang_goal_instr)\n\n return cont_lang_goal_instr, enc_lang_goal_instr\n\n def reset(self):\n '''\n reset internal states (used for real-time execution during eval)\n '''\n self.r_state = {\n 'state_t': None,\n 'e_t': None,\n 'cont_lang': None,\n 'enc_lang': None\n }\n\n def step(self, feat, prev_action=None):\n '''\n forward the model for a single time-step (used for real-time execution during eval)\n '''\n\n # encode language features\n if self.r_state['cont_lang'] is None and self.r_state['enc_lang'] is None:\n self.r_state['cont_lang'], self.r_state['enc_lang'] = self.encode_lang(feat)\n\n # initialize embedding and hidden states\n if self.r_state['e_t'] is None and self.r_state['state_t'] is None:\n self.r_state['e_t'] = self.dec.go.repeat(self.r_state['enc_lang'].size(0), 1)\n self.r_state['state_t'] = self.r_state['cont_lang'], torch.zeros_like(\n self.r_state['cont_lang'])\n\n # previous action embedding\n e_t = self.embed_action(prev_action) if prev_action is not None else self.r_state['e_t']\n\n frames_depth = torch.tensor(feat['frames_depth'], dtype=torch.float, device=self.device)\n frames_depth = frames_depth.unsqueeze(0).unsqueeze(0)\n frames_depth = self.enc_depth(frames_depth)\n gcn_embedding = self.gcn(feat['frames'])\n # decode and save embedding and hidden states\n out_action_low, out_action_low_mask, state_t, * \\\n _ = self.dec.step(self.r_state['enc_lang'], feat['frames']\n [:, 0], e_t=e_t, state_tm1=self.r_state['state_t'], gcn_embedding=gcn_embedding, frames_depth=frames_depth[:, 0])\n\n # save states\n self.r_state['state_t'] = state_t\n self.r_state['e_t'] = self.dec.emb(out_action_low.max(1)[1])\n\n # output formatting\n feat['out_action_low'] = out_action_low.unsqueeze(0)\n feat['out_action_low_mask'] = out_action_low_mask.unsqueeze(0)\n return feat\n\n def extract_preds(self, out, batch, feat, clean_special_tokens=True):\n '''\n output processing\n '''\n pred = {}\n for ex, alow, alow_mask in zip(batch, feat['out_action_low'].max(2)[1].tolist(), feat['out_action_low_mask']):\n # remove padding tokens\n if self.pad in alow:\n pad_start_idx = alow.index(self.pad)\n alow = alow[:pad_start_idx]\n alow_mask = alow_mask[:pad_start_idx]\n\n if clean_special_tokens:\n # remove <<stop>> tokens\n if self.stop_token in alow:\n stop_start_idx = alow.index(self.stop_token)\n alow = alow[:stop_start_idx]\n alow_mask = alow_mask[:stop_start_idx]\n\n # index to API actions\n words = self.vocab['action_low'].index2word(alow)\n\n # sigmoid preds to binary mask\n alow_mask = F.sigmoid(alow_mask)\n p_mask = [(alow_mask[t] > 0.5).cpu().numpy() for t in range(alow_mask.shape[0])]\n # import pdb; pdb.set_trace()\n\n task_id_ann = self.get_task_and_ann_id(ex)\n pred[task_id_ann] = {\n 'action_low': ' '.join(words),\n 'action_low_mask': p_mask,\n }\n\n return pred\n\n def embed_action(self, action):\n '''\n embed low-level action\n '''\n device = torch.device(\"cuda:%d\" % self.args.gpu_id) if self.args.gpu else torch.device('cpu')\n action_num = torch.tensor(self.vocab['action_low'].word2index(action), device=device)\n action_emb = self.dec.emb(action_num).unsqueeze(0)\n return action_emb\n\n def compute_loss(self, out, batch, feat):\n '''\n loss function for Seq2Seq agent\n '''\n losses = dict()\n\n # GT and predictions\n p_alow = out['out_action_low'].view(-1, len(self.vocab['action_low']))\n l_alow = feat['action_low'].view(-1)\n # [2, 61, 1, 300, 300]\n p_alow_mask = out['out_action_low_mask']\n valid = feat['action_low_valid_interact']\n\n # action loss\n pad_valid = (l_alow != self.pad)\n alow_loss = F.cross_entropy(p_alow, l_alow, reduction='none')\n alow_loss *= pad_valid.float()\n alow_loss = alow_loss.mean()\n losses['action_low'] = alow_loss * self.args.action_loss_wt\n\n # mask loss\n valid_idxs = valid.view(-1).nonzero().view(-1)\n flat_p_alow_mask = p_alow_mask.view(\n p_alow_mask.shape[0]*p_alow_mask.shape[1], *p_alow_mask.shape[2:])[valid_idxs]\n flat_alow_mask = torch.cat(feat['action_low_mask'], dim=0)\n alow_mask_loss = self.weighted_mask_loss(flat_p_alow_mask, flat_alow_mask)\n losses['action_low_mask'] = alow_mask_loss * self.args.mask_loss_wt\n\n # subgoal completion loss\n if self.args.subgoal_aux_loss_wt > 0:\n p_subgoal = feat['out_subgoal'].squeeze(2)\n l_subgoal = feat['subgoals_completed']\n sg_loss = self.mse_loss(p_subgoal, l_subgoal)\n sg_loss = sg_loss.view(-1) * pad_valid.float()\n subgoal_loss = sg_loss.mean()\n losses['subgoal_aux'] = self.args.subgoal_aux_loss_wt * subgoal_loss\n\n # progress monitoring loss\n if self.args.pm_aux_loss_wt > 0:\n p_progress = feat['out_progress'].squeeze(2)\n l_progress = feat['subgoal_progress']\n pg_loss = self.mse_loss(p_progress, l_progress)\n pg_loss = pg_loss.view(-1) * pad_valid.float()\n progress_loss = pg_loss.mean()\n losses['progress_aux'] = self.args.pm_aux_loss_wt * progress_loss\n\n return losses\n\n def weighted_mask_loss(self, pred_masks, gt_masks):\n '''\n mask loss that accounts for weight-imbalance between 0 and 1 pixels\n '''\n bce = self.bce_with_logits(pred_masks, gt_masks)\n flipped_mask = self.flip_tensor(gt_masks)\n inside = (bce * gt_masks).sum() / (gt_masks).sum()\n outside = (bce * flipped_mask).sum() / (flipped_mask).sum()\n return inside + outside\n\n def flip_tensor(self, tensor, on_zero=1, on_non_zero=0):\n '''\n flip 0 and 1 values in tensor\n '''\n res = tensor.clone()\n res[tensor == 0] = on_zero\n res[tensor != 0] = on_non_zero\n return res\n\n def compute_metric(self, preds, data):\n '''\n compute f1 and extract match scores for output\n '''\n m = collections.defaultdict(list)\n for task in data:\n ex = self.load_task_json(task)\n i = self.get_task_and_ann_id(ex)\n label = ' '.join([a['discrete_action']['action'] for a in ex['plan']['low_actions']])\n m['action_low_f1'].append(compute_f1(label.lower(), preds[i]['action_low'].lower()))\n m['action_low_em'].append(compute_exact(label.lower(), preds[i]['action_low'].lower()))\n return {k: sum(v)/len(v) for k, v in m.items()}\n",
"import os\nimport random\nimport json\nimport torch\nimport pprint\nimport collections\nimport numpy as np\nfrom torch import nn\nfrom tensorboardX import SummaryWriter\nfrom tqdm import trange\nfrom sys import platform\n\nnot_perfect_list = [\n 'pick_and_place_simple-SprayBottle-None-Toilet-422/trial_T20190909_124852_071149',\n 'pick_heat_then_place_in_recep-PotatoSliced-None-SinkBasin-14/trial_T20190910_120350_730711',\n 'pick_heat_then_place_in_recep-PotatoSliced-None-SinkBasin-23/trial_T20190907_123248_978930',\n 'pick_heat_then_place_in_recep-Mug-None-CoffeeMachine-5/trial_T20190908_003714_311231',\n 'pick_two_obj_and_place-SoapBar-None-BathtubBasin-422/trial_T20190909_133405_341380',\n 'pick_two_obj_and_place-Candle-None-Shelf-422/trial_T20190906_192421_941599',\n]\n\nclass Module(nn.Module):\n\n def __init__(self, args, vocab):\n '''\n Base Seq2Seq agent with common train and val loops\n '''\n super().__init__()\n\n # sentinel tokens\n self.pad = 0\n self.seg = 1\n\n # args and vocab\n self.args = args\n self.vocab = vocab\n\n # emb modules\n self.emb_word = nn.Embedding(len(vocab['word']), args.demb)\n # self.vocab['action_low'].index2word(list(range(0, len(vocab['action_low']))))\n # self.vocab['action_high'].index2word(list(range(0, len(vocab['action_high']))))\n # self.vocab['word'].index2word(list(range(0, len(vocab['word']))))\n self.emb_action_low = nn.Embedding(len(vocab['action_low']), args.demb)\n\n # end tokens\n self.stop_token = self.vocab['action_low'].word2index(\"<<stop>>\", train=False)\n self.seg_token = self.vocab['action_low'].word2index(\"<<seg>>\", train=False)\n\n # set random seed (Note: this is not the seed used to initialize THOR object locations)\n random.seed(a=args.seed)\n\n # summary self.writer\n self.summary_writer = None\n\n def run_train(self, splits, args=None, optimizer=None):\n '''\n training loop\n '''\n\n # args\n args = args or self.args\n\n # splits\n train = splits['train']\n # import pdb; pdb.set_trace()\n # print(train)\n valid_seen = splits['valid_seen']\n valid_unseen = splits['valid_unseen']\n\n train = [t for t in train if not t['task'] in not_perfect_list]\n valid_seen = [t for t in valid_seen if not t['task'] in not_perfect_list]\n valid_unseen = [t for t in valid_unseen if not t['task'] in not_perfect_list]\n\n # debugging: chose a small fraction of the dataset\n if self.args.dataset_fraction > 0:\n small_train_size = int(self.args.dataset_fraction * 0.7)\n small_valid_size = int((self.args.dataset_fraction * 0.3) / 2)\n train = train[:small_train_size]\n valid_seen = valid_seen[:small_valid_size]\n valid_unseen = valid_unseen[:small_valid_size]\n\n # debugging: use to check if training loop works without waiting for full epoch\n if self.args.fast_epoch:\n train = train[:5]\n valid_seen = valid_seen[:5]\n valid_unseen = valid_unseen[:5]\n\n # initialize summary writer for tensorboardX\n self.summary_writer = SummaryWriter(log_dir=args.dout)\n\n # dump config\n fconfig = os.path.join(args.dout, 'config.json')\n with open(fconfig, 'wt') as f:\n json.dump(vars(args), f, indent=2)\n\n # optimizer\n optimizer = optimizer or torch.optim.Adam(self.parameters(), lr=args.lr)\n\n # display dout\n print(\"Saving to: %s\" % self.args.dout)\n best_loss = {'train': 1e10, 'valid_seen': 1e10, 'valid_unseen': 1e10}\n train_iter, valid_seen_iter, valid_unseen_iter = 0, 0, 0\n for epoch in trange(0, args.epoch, desc='epoch'):\n m_train = collections.defaultdict(list)\n self.train()\n self.adjust_lr(optimizer, args.lr, epoch, decay_epoch=args.decay_epoch)\n # p_train = {}\n total_train_loss = list()\n random.shuffle(train) # shuffle every epoch\n for batch, feat in self.iterate(train, args.batch):\n out = self.forward(feat)\n preds = self.extract_preds(out, batch, feat)\n # p_train.update(preds)\n loss = self.compute_loss(out, batch, feat)\n for k, v in loss.items():\n ln = 'loss_' + k\n m_train[ln].append(v.item())\n self.summary_writer.add_scalar('train/' + ln, v.item(), train_iter)\n\n # optimizer backward pass\n optimizer.zero_grad()\n sum_loss = sum(loss.values())\n sum_loss.backward()\n optimizer.step()\n\n self.summary_writer.add_scalar('train/loss', sum_loss, train_iter)\n sum_loss = sum_loss.detach().cpu()\n total_train_loss.append(float(sum_loss))\n train_iter += self.args.batch\n '''\n semantic\n '''\n self.finish_of_episode()\n\n ## compute metrics for train (too memory heavy!)\n # m_train = {k: sum(v) / len(v) for k, v in m_train.items()}\n # m_train.update(self.compute_metric(p_train, train))\n # m_train['total_loss'] = sum(total_train_loss) / len(total_train_loss)\n # self.summary_writer.add_scalar('train/total_loss', m_train['total_loss'], train_iter)\n\n # compute metrics for valid_seen\n p_valid_seen, valid_seen_iter, total_valid_seen_loss, m_valid_seen = self.run_pred(valid_seen, args=args, name='valid_seen', iter=valid_seen_iter)\n m_valid_seen.update(self.compute_metric(p_valid_seen, valid_seen))\n m_valid_seen['total_loss'] = float(total_valid_seen_loss)\n self.summary_writer.add_scalar('valid_seen/total_loss', m_valid_seen['total_loss'], valid_seen_iter)\n\n # compute metrics for valid_unseen\n p_valid_unseen, valid_unseen_iter, total_valid_unseen_loss, m_valid_unseen = self.run_pred(valid_unseen, args=args, name='valid_unseen', iter=valid_unseen_iter)\n m_valid_unseen.update(self.compute_metric(p_valid_unseen, valid_unseen))\n m_valid_unseen['total_loss'] = float(total_valid_unseen_loss)\n self.summary_writer.add_scalar('valid_unseen/total_loss', m_valid_unseen['total_loss'], valid_unseen_iter)\n\n stats = {'epoch': epoch,\n 'train': sum(total_train_loss)/len(total_train_loss),\n 'valid_seen': m_valid_seen,\n 'valid_unseen': m_valid_unseen}\n\n # new best valid_seen loss\n if total_valid_seen_loss < best_loss['valid_seen']:\n print('\\nFound new best valid_seen!! Saving...')\n fsave = os.path.join(args.dout, 'best_seen.pth')\n torch.save({\n 'metric': stats,\n 'model': self.state_dict(),\n 'optim': optimizer.state_dict(),\n 'args': self.args,\n 'vocab': self.vocab,\n }, fsave)\n fbest = os.path.join(args.dout, 'best_seen.json')\n with open(fbest, 'wt') as f:\n json.dump(stats, f, indent=2)\n\n fpred = os.path.join(args.dout, 'valid_seen.debug.preds.json')\n with open(fpred, 'wt') as f:\n json.dump(self.make_debug(p_valid_seen, valid_seen), f, indent=2)\n best_loss['valid_seen'] = total_valid_seen_loss\n\n # new best valid_unseen loss\n if total_valid_unseen_loss < best_loss['valid_unseen']:\n print('Found new best valid_unseen!! Saving...')\n fsave = os.path.join(args.dout, 'best_unseen.pth')\n torch.save({\n 'metric': stats,\n 'model': self.state_dict(),\n 'optim': optimizer.state_dict(),\n 'args': self.args,\n 'vocab': self.vocab,\n }, fsave)\n fbest = os.path.join(args.dout, 'best_unseen.json')\n with open(fbest, 'wt') as f:\n json.dump(stats, f, indent=2)\n\n fpred = os.path.join(args.dout, 'valid_unseen.debug.preds.json')\n with open(fpred, 'wt') as f:\n json.dump(self.make_debug(p_valid_unseen, valid_unseen), f, indent=2)\n\n best_loss['valid_unseen'] = total_valid_unseen_loss\n\n # save the latest checkpoint\n if args.save_every_epoch:\n fsave = os.path.join(args.dout, 'net_epoch_%d.pth' % epoch)\n else:\n fsave = os.path.join(args.dout, 'latest.pth')\n torch.save({\n 'metric': stats,\n 'model': self.state_dict(),\n 'optim': optimizer.state_dict(),\n 'args': self.args,\n 'vocab': self.vocab,\n }, fsave)\n\n ## debug action output json for train\n # fpred = os.path.join(args.dout, 'train.debug.preds.json')\n # with open(fpred, 'wt') as f:\n # json.dump(self.make_debug(p_train, train), f, indent=2)\n\n # write stats\n for split in stats.keys():\n if isinstance(stats[split], dict):\n for k, v in stats[split].items():\n self.summary_writer.add_scalar(split + '/' + k, v, train_iter)\n pprint.pprint(stats)\n\n def run_pred(self, dev, args=None, name='dev', iter=0):\n '''\n validation loop\n '''\n args = args or self.args\n m_dev = collections.defaultdict(list)\n p_dev = {}\n self.eval()\n total_loss = list()\n dev_iter = iter\n for batch, feat in self.iterate(dev, args.batch):\n out = self.forward(feat)\n preds = self.extract_preds(out, batch, feat)\n p_dev.update(preds)\n loss = self.compute_loss(out, batch, feat)\n for k, v in loss.items():\n ln = 'loss_' + k\n m_dev[ln].append(v.item())\n self.summary_writer.add_scalar(\"%s/%s\" % (name, ln), v.item(), dev_iter)\n sum_loss = sum(loss.values())\n self.summary_writer.add_scalar(\"%s/loss\" % (name), sum_loss, dev_iter)\n total_loss.append(float(sum_loss.detach().cpu()))\n dev_iter += len(batch)\n '''\n semantic\n '''\n self.finish_of_episode()\n\n m_dev = {k: sum(v) / len(v) for k, v in m_dev.items()}\n total_loss = sum(total_loss) / len(total_loss)\n return p_dev, dev_iter, total_loss, m_dev\n\n def finish_of_episode(self):\n raise NotImplementedError()\n\n def featurize(self, batch):\n raise NotImplementedError()\n\n def forward(self, feat, max_decode=100):\n raise NotImplementedError()\n\n def extract_preds(self, out, batch, feat):\n raise NotImplementedError()\n\n def compute_loss(self, out, batch, feat):\n raise NotImplementedError()\n\n def compute_metric(self, preds, data):\n raise NotImplementedError()\n\n def get_task_and_ann_id(self, ex):\n '''\n single string for task_id and annotation repeat idx\n '''\n return \"%s_%s\" % (ex['task_id'], str(ex['repeat_idx']))\n\n def make_debug(self, preds, data):\n '''\n readable output generator for debugging\n '''\n debug = {}\n for task in data:\n ex = self.load_task_json(task)\n i = self.get_task_and_ann_id(ex)\n debug[i] = {\n 'lang_goal': ex['turk_annotations']['anns'][ex['ann']['repeat_idx']]['task_desc'],\n 'action_low': [a['discrete_action']['action'] for a in ex['plan']['low_actions']],\n 'p_action_low': preds[i]['action_low'].split(),\n }\n return debug\n\n def load_task_json(self, task):\n '''\n load preprocessed json from disk\n '''\n json_path = os.path.join(self.args.data, task['task'], '%s' % self.args.pp_folder, 'ann_%d.json' % task['repeat_idx'])\n with open(json_path) as f:\n data = json.load(f)\n return data\n\n def get_task_root(self, ex):\n '''\n returns the folder path of a trajectory\n '''\n if platform == \"win32\":\n return os.path.join(self.args.data, ex['split'], ex['root'].split('\\\\')[-1])\n else:\n return os.path.join(self.args.data, ex['split'], *(ex['root'].split('/')[-2:]))\n\n def iterate(self, data, batch_size):\n '''\n breaks dataset into batch_size chunks for training\n '''\n for i in trange(0, len(data), batch_size, desc='batch'):\n tasks = data[i:i+batch_size]\n batch = [self.load_task_json(task) for task in tasks]\n feat = self.featurize(batch)\n yield batch, feat\n\n def zero_input(self, x, keep_end_token=True):\n '''\n pad input with zeros (used for ablations)\n '''\n end_token = [x[-1]] if keep_end_token else [self.pad]\n return list(np.full_like(x[:-1], self.pad)) + end_token\n\n def zero_input_list(self, x, keep_end_token=True):\n '''\n pad a list of input with zeros (used for ablations)\n '''\n end_token = [x[-1]] if keep_end_token else [self.pad]\n lz = [list(np.full_like(i, self.pad)) for i in x[:-1]] + end_token\n return lz\n\n @staticmethod\n def adjust_lr(optimizer, init_lr, epoch, decay_epoch=5):\n '''\n decay learning rate every decay_epoch\n '''\n lr = init_lr * (0.1 ** (epoch // decay_epoch))\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n @classmethod\n def load(cls, fsave, device=None, use_gpu=None, gpu_id=1):\n '''\n load pth model from disk\n '''\n save = torch.load(fsave, map_location=device)\n save['args'].gpu = use_gpu if use_gpu == False else save['args'].gpu\n save['args'].gpu_id = gpu_id\n # import pdb; pdb.set_trace()\n model = cls(save['args'], save['vocab'])\n model.load_state_dict(save['model'])\n model = model.to(device=device)\n optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)\n optimizer.load_state_dict(save['optim'])\n return model, optimizer\n\n @classmethod\n def has_interaction(cls, action):\n '''\n check if low-level action is interactive\n '''\n non_interact_actions = ['MoveAhead', 'Rotate', 'Look', '<<stop>>', '<<pad>>', '<<seg>>']\n if any(a in action for a in non_interact_actions):\n return False\n else:\n return True\n"
] | [
[
"torch.zeros",
"torch.cat",
"torch.nn.functional.dropout"
],
[
"matplotlib.use",
"torch.multiprocessing.Manager",
"torch.multiprocessing.set_start_method"
],
[
"torch.nn.Dropout",
"numpy.expand_dims",
"torch.nn.LSTM",
"torch.cat",
"torch.nn.functional.cross_entropy",
"torch.zeros_like",
"torch.nn.utils.rnn.pad_sequence",
"torch.nn.utils.rnn.pack_padded_sequence",
"torch.tensor",
"torch.nn.functional.sigmoid",
"torch.nn.BCEWithLogitsLoss",
"torch.nn.utils.rnn.pad_packed_sequence",
"torch.cuda.is_available",
"torch.device",
"numpy.array",
"numpy.zeros",
"torch.nn.MSELoss",
"torch.stack"
],
[
"numpy.full_like",
"torch.load"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AutonomousFieldRoboticsLab/jetyak_uav_utils | [
"7926df2cf34b0be2647b62896c98af82ca6f1e53"
] | [
"scripts/nodes/GPS_utils.py"
] | [
"'''\nMIT License\nCopyright (c) 2019 Michail Kalaitzakis\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n'''\n\nimport numpy as np\n\nclass GPS_utils:\n\t'''\n\t\tConverts a gps signal (longitude, latitude, height) to a local cartesian ENU system\n\t\t\n\t\tUse setENUorigin(lat, lon, height) to set the local ENU coordinate system\n\t\tUse geo2enu(lat, lon, height) to get position in the local ENU system\n\t'''\n\t\n\tdef __init__(self):\n\t\t# Geodetic System WGS 84 axes\n\t\tself.a = 6378137\n\t\tself.b = 6356752.314245\n\t\tself.a2 = self.a * self.a\n\t\tself.b2 = self.b * self.b\n\t\tself.e2 = 1 - (self.b2 / self.a2)\n\t\t\n\t\t# Local ENU Origin\n\t\tself.latZero = None\n\t\tself.lonZero = None\n\t\tself.hgtZero = None\n\t\tself.xZero = None\n\t\tself.yZero = None\n\t\tself.zZero = None\n\t\tself.R = np.asmatrix(np.eye(3))\n\n\tdef setENUorigin(self, lat, lon, height):\n\t\t# Save origin lat, lon, height\n\t\tself.latZero = lat\n\t\tself.lonZero = lon\n\t\tself.hgtZero = height\n\t\t\n\t\t# Get origin ECEF X,Y,Z\n\t\torigin = self.geo2ecef(self.latZero, self.lonZero, self.hgtZero)\t\t\n\t\tself.xZero = origin.item(0)\n\t\tself.yZero = origin.item(1)\n\t\tself.zZero = origin.item(2)\n\t\tself.oZero = np.array([[self.xZero], [self.yZero], [self.zZero]])\n\t\t\n\t\t# Build rotation matrix\n\t\tphi = np.deg2rad(self.latZero)\n\t\tlmd = np.deg2rad(self.lonZero)\n\t\t\n\t\tcPhi = np.cos(phi)\n\t\tcLmd = np.cos(lmd)\n\t\tsPhi = np.sin(phi)\n\t\tsLmd = np.sin(lmd)\n\t\t\n\t\tself.R[0, 0] = -sLmd\n\t\tself.R[0, 1] = cLmd\n\t\tself.R[0, 2] = 0\n\t\tself.R[1, 0] = -sPhi*cLmd\n\t\tself.R[1, 1] = -sPhi*sLmd\n\t\tself.R[1, 2] = cPhi\n\t\tself.R[2, 0] = cPhi*cLmd\n\t\tself.R[2, 1] = cPhi*sLmd\n\t\tself.R[2, 2] = sPhi\n\t\n\tdef geo2ecef(self, lat, lon, height):\n\t\tphi = np.deg2rad(lat)\n\t\tlmd = np.deg2rad(lon)\n\t\t\n\t\tcPhi = np.cos(phi)\n\t\tcLmd = np.cos(lmd)\n\t\tsPhi = np.sin(phi)\n\t\tsLmd = np.sin(lmd)\n\t\t\n\t\tN = self.a / (np.sqrt(1 - self.e2*sPhi*sPhi))\n\t\t\n\t\tx = (N + height)*cPhi*cLmd\n\t\ty = (N + height)*cPhi*sLmd\n\t\tz = ((self.b2 / self.a2)*N + height)*sPhi\n\t\t\n\t\treturn np.array([[x], [y], [z]])\n\t\n\tdef ecef2enu(self, x, y, z):\n\t\tecef = np.array([[x], [y], [z]])\n\t\t\n\t\treturn self.R * (ecef - self.oZero)\n\t\n\tdef geo2enu(self, lat, lon, height):\n\t\tecef = self.geo2ecef(lat, lon, height)\n\t\t\n\t\treturn self.ecef2enu(ecef.item(0), ecef.item(1), ecef.item(2))\n"
] | [
[
"numpy.sqrt",
"numpy.eye",
"numpy.cos",
"numpy.sin",
"numpy.deg2rad",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
IDEBench/IDEBench-public | [
"67339d9b81d0bcbb7b41ce6dc2e55918cf1c498f"
] | [
"workflowgen.py"
] | [
"import random\nimport numpy as np\nimport pprint\nimport json\nfrom workflowgen.vizaction import VizAction\nfrom workflowgen.linkaction import LinkAction\nfrom optparse import OptionParser\nimport pandas as pd\nfrom common.schema import Schema\nfrom common.vizgraph import VizGraph\n#from common.storage import Storage\nimport pandasql\n\n\nclass WorkflowGenerator:\n\n def __init__(self):\n\n parser = OptionParser()\n parser.add_option(\"-r\", \"--seed\", dest=\"seed\", action=\"store\", type=int, help=\"Random seed\", default=25000)\n parser.add_option(\"-d\", \"--dataset\", dest=\"data_folder\", action=\"store\", help=\"path to save the file\", default=\"flights\")\n parser.add_option(\"--debug\", dest=\"debug\", action=\"store_true\", help=\"creates a debug file\", default=False)\n parser.add_option(\"-n\", \"--num-operations\", dest=\"num_operations\", action=\"store\", type=int, help=\"Number of operations to generate\", default=20)\n parser.add_option(\"-c\", \"--workflow-type\", dest=\"config\", action=\"store\", help=\"path to config file\", default=\"data/flights/workflowtypes/sequential.json\")\n parser.add_option(\"-p\", \"--output\", dest=\"path\", action=\"store\", help=\"path to save the file\", default=\"workflow.json\")\n parser.add_option(\"-s\", \"--num-samples\", dest=\"numsamples\", action=\"store\", type=int, help=\"Number of samples to draw from the original dataset\", default=10000)\n (options, args) = parser.parse_args()\n self.options = options\n\n random.seed(options.seed)\n np.random.seed(seed=options.seed)\n\n print(\"data/\" + options.data_folder + \"/\" + options.config)\n with open(\"data/\" + options.data_folder + \"/workflowtypes/\" + options.config, \"r\") as fp:\n self.config = json.load(fp)\n\n schema = None\n with open(self.get_schema_path()) as f:\n schema = Schema(json.load(f))\n\n print(\"reading csv...\")\n # load sample data\n df = pd.read_csv(\"data/\" + options.data_folder + \"/sample.csv\", nrows=options.numsamples, header=0)\n \n #schema = {\"tables\": [{ \"name\": \"df\", \"dimensions\": []}]}\n sample_json = None\n with open(\"data/\" + options.data_folder + \"/sample.json\", \"r\") as f:\n sample_json = json.load(f)\n # for field in sample_json[\"tables\"][\"fact\"][\"fields\"]:\n # schema[\"tables\"][0][\"dimensions\"].append({\"name\": field[\"field\"]})\n\n\n #storage = Storage(schema)\n\n zero_qs_ratio = 100\n\n tries = -1\n while zero_qs_ratio > 0.15:\n tries += 1\n num_zeros_qs = 0\n num_qs = 0\n VizAction.VIZ_COUNTER = -1 \n LinkAction.FIRST_LINK = None\n LinkAction.LATEST_LINK = None\n LinkAction.LINKS = set()\n \n vizgraph = VizGraph()\n random.seed(options.seed + tries)\n root = VizAction(self.config, df, vizgraph, schema, sample_json)\n current = root\n states = []\n \n num_ops = 0\n \n debug_states = []\n while num_ops < options.num_operations:\n res = current.get_states()\n if res: \n affected_vizs = vizgraph.apply_interaction(res)\n if options.debug:\n nodes_dict = vizgraph.get_nodes_dict()\n states_dict = {}\n for n in nodes_dict.keys():\n states_dict[n] = {\n \"name\":n,\n \"source\" : nodes_dict[n].get_source(),\n \"binning\": nodes_dict[n].binning,\n \"agg\": nodes_dict[n].per_bin_aggregates,\n \"selection\": nodes_dict[n].get_selection(),\n \"filter\": nodes_dict[n].get_filter(),\n \"computed_filter\": nodes_dict[n].get_computed_filter_as_sql(schema),\n }\n debug_states.append(states_dict)\n \n for x in affected_vizs:\n sql = x.get_computed_filter_as_sql(schema).replace(\"FLOOR\", \"ROUND\").replace(schema.get_fact_table_name(), \"df\")\n r = pandasql.sqldf(sql, locals())\n num_qs += 1\n if len(r.index) == 0:\n num_zeros_qs += 1\n\n states.append(res.data)\n #if \"source\" not in res:\n num_ops += 1\n\n current = current.get_next()\n if current is None:\n zero_qs_ratio = num_zeros_qs/num_qs\n break\n zero_qs_ratio = num_zeros_qs/num_qs\n \n\n with open(\"data/\" + options.data_folder + \"/workflows/\" + options.path + \".json\", \"w\") as fp:\n fp.write(json.dumps({\"name\": \"generated\", \"dataset\": options.data_folder, \"seed\": options.seed, \"config\": options.config, \"interactions\": states}))\n\n print(\"done.\")\n #with open(\"workflowviewer/public/workflow.json\", \"w\") as fp:\n # fp.write(json.dumps({\"name\": \"generated\", \"dataset\": options.data_folder, \"seed\": options.seed, \"config\": options.config, \"interactions\": states}))\n\n #with open(\"workflowviewer/public/workflow_debug.json\", \"w\") as fp:\n # fp.write(json.dumps(debug_states))\n\n #if options.debug:\n # import webbrowser\n # url = \"http://localhost:3000\"\n # webbrowser.open(url)\n\n def get_schema_path(self):\n return \"data/%s/sample.json\" % (self.options.data_folder)\n\n def get_viz_name(self):\n return \"viz_%i\" % self.config[\"viz_counter\"]\n\nWorkflowGenerator()"
] | [
[
"pandas.read_csv",
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
zkdlfrlwl2/Classification-For-Everyone | [
"a99428080ef470a3270d3f4a6048df197216a050",
"a99428080ef470a3270d3f4a6048df197216a050",
"a99428080ef470a3270d3f4a6048df197216a050"
] | [
"models/AlexNet/lightning_model.py",
"models/MNASNet/blocks.py",
"models/WideResNet/models.py"
] | [
"from typing import *\n\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom models.LitBase import LitBase\n\nfrom .models import AlexNet\n\n\nclass LitAlexNet(LitBase):\n def __init__(self, args: Dict[str, Any]):\n super().__init__()\n self.save_hyperparameters(args)\n self.model = AlexNet(\n image_channels=self.hparams.image_channels,\n num_classes=self.hparams.num_classes,\n dropout_rate=self.hparams.dropout_rate,\n )\n self.loss = nn.CrossEntropyLoss()\n\n def configure_optimizers(self) -> optim.Optimizer:\n optimizer = optim.Adam(\n self.parameters(),\n lr=self.hparams.lr,\n weight_decay=self.hparams.weight_decay,\n )\n scheduler_dict = {\n \"scheduler\": optim.lr_scheduler.ReduceLROnPlateau(\n optimizer,\n mode=self.hparams.scheduler_mode,\n factor=self.hparams.scheduler_factor,\n patience=self.hparams.scheduler_patience,\n verbose=True,\n ),\n \"monitor\": self.hparams.scheduler_monitor,\n }\n return {\"optimizer\": optimizer, \"lr_scheduler\": scheduler_dict}\n",
"import torch\nimport torch.nn as nn\nfrom typing import List\n\n__all__ = [\"ConvBlock\", \"SepConvBlock\", \"SEBlock\", \"MBConvBlock\", \"Classifier\"]\n\n\nclass ConvBlock(nn.Module):\n\n def __init__(\n self,\n in_channels: int,\n out_channels: int,\n kernel_size: int,\n stride: int = 1,\n padding: int = 0,\n groups: int = 1,\n act: str = 'ReLU',\n bias: bool = False,\n ) -> None:\n super().__init__()\n\n layers = [\n nn.Conv2d(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n stride=stride,\n padding=padding,\n groups=groups,\n bias=bias,\n ),\n nn.BatchNorm2d(num_features=out_channels)\n ]\n\n if act == 'ReLU':\n layers.append(nn.ReLU(inplace=True))\n\n self.conv2d = nn.Sequential(*layers)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return self.conv2d(x)\n\n\nclass SepConvBlock(nn.Module):\n\n def __init__(\n self,\n dim: List[int],\n factor: float,\n stride: int,\n padding: int\n ) -> None:\n super().__init__()\n\n self.blocks = nn.Sequential(\n ConvBlock(\n in_channels=expand_width(dim[0], factor),\n out_channels=expand_width(dim[0], factor),\n kernel_size=3,\n stride=stride,\n padding=padding,\n groups=dim[0],\n ),\n ConvBlock(\n in_channels=expand_width(dim[0], factor),\n out_channels=expand_width(dim[1], factor),\n kernel_size=1,\n act='None'\n )\n )\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return self.blocks(x)\n\n\nclass SEBlock(nn.Module):\n\n def __init__(\n self,\n dim: List[int],\n factor: float,\n reduction_ratio: int = 4\n ) -> None:\n super().__init__()\n\n self.CE_block = nn.Sequential(\n nn.AdaptiveAvgPool2d(1),\n nn.Conv2d(\n in_channels=expand_width(dim[0], factor),\n out_channels=expand_width(\n dim=dim[0],\n factor=factor,\n ratio=reduction_ratio,\n use_ratio=True\n ),\n kernel_size=1\n ),\n nn.SiLU(inplace=True),\n nn.Conv2d(\n in_channels=expand_width(\n dim=dim[0],\n factor=factor,\n ratio=reduction_ratio,\n use_ratio=True\n ),\n out_channels=expand_width(dim[0], factor),\n kernel_size=1\n ),\n nn.Hardsigmoid(inplace=True)\n )\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return torch.mul(x, self.CE_block(x))\n\n\nclass MBConvBlock(nn.Module):\n\n def __init__(\n self,\n dim: List[int],\n factor: float,\n kernel: int,\n padding: int,\n stride: int,\n reduction_ratio: int = 4,\n use_se: bool = False,\n ) -> None:\n super().__init__()\n self.use_se = use_se\n self.use_res_connection = (stride == 1) and (dim[0] == dim[1])\n\n self.first_block = nn.Sequential(\n # Conv 1x1\n ConvBlock(\n in_channels=dim[0],\n out_channels=expand_width(dim[0], factor),\n kernel_size=1,\n ),\n # Dwise kernel x kennel\n ConvBlock(\n in_channels=expand_width(dim[0], factor),\n out_channels=expand_width(dim[0], factor),\n kernel_size=kernel,\n stride=stride,\n padding=padding,\n groups=expand_width(dim[0], factor),\n )\n )\n\n self.second_block = nn.Sequential(\n # Conv 1x1, linear act.\n ConvBlock(\n in_channels=expand_width(dim[0], factor),\n out_channels=dim[1],\n kernel_size=1,\n act='None'\n )\n )\n\n self.SEBlock = SEBlock(\n dim=dim,\n factor=factor,\n reduction_ratio=reduction_ratio\n )\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n\n if self.use_res_connection is True and self.use_se is True:\n identity = x\n x = self.first_block(x)\n x = self.SEBlock(x)\n\n return identity + self.second_block(x)\n\n elif self.use_res_connection is True and self.use_se is False:\n identity = x\n x = self.first_block(x)\n\n return identity + self.second_block(x)\n\n elif self.use_res_connection is False and self.use_se is True:\n x = self.first_block(x)\n x = self.SEBlock(x)\n\n return self.second_block(x)\n\n else:\n x = self.first_block(x)\n\n return self.second_block(x)\n\n\ndef expand_width(\n dim: int,\n factor: float,\n ratio: int = 4,\n use_ratio: bool = False,\n) -> int:\n if use_ratio is True:\n return int(dim//ratio)\n else:\n return int(dim*factor)\n\n\nclass Classifier(nn.Module):\n\n def __init__(\n self,\n in_features: int,\n out_features: int,\n dropout_rate: float,\n ) -> None:\n super().__init__()\n\n self.classifier = nn.Sequential(\n nn.Dropout(dropout_rate),\n nn.Linear(in_features, out_features),\n )\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return self.classifier(x)",
"import torch.nn as nn\nimport torch.nn.functional as F\nfrom .blocks import *\nimport torch\n\n__all__ = [\n \"WideResNet\",\n]\n\nNormalization = nn.BatchNorm2d\nActivation = nn.ReLU\n\n\nclass WideResNet(nn.Module):\n def __init__(\n self,\n image_channels: int,\n num_classes: int,\n depth: int = 40,\n K: int = 10,\n dropout_rate: int = 0.5,\n ):\n super().__init__()\n N = (depth - 4) // 6\n self.in_channels = 16\n\n self.conv1 = nn.Conv2d(image_channels, 16, 3, 1, 1)\n self.conv2 = self._make_layer(16 * K, N, 1, dropout_rate)\n self.conv3 = self._make_layer(32 * K, N, 2, dropout_rate)\n self.conv4 = self._make_layer(64 * K, N, 2, dropout_rate)\n self.bn = Normalization(self.in_channels)\n self.act = Activation(inplace=True)\n\n self.avg = nn.AdaptiveAvgPool2d(1)\n self.classifier = Classifier(inp=self.in_channels, outp=num_classes)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n x = self.conv1(x)\n x = self.conv2(x)\n x = self.conv3(x)\n x = self.conv4(x)\n x = self.bn(x)\n x = self.act(x)\n x = self.avg(x)\n return self.classifier(x)\n\n def _make_layer(self, out_channels: int, num_block: int, s: int, dr: float):\n layers = [WideResNetBlock(self.in_channels, out_channels, s, dr)]\n self.in_channels = out_channels\n\n layers += [\n WideResNetBlock(self.in_channels, out_channels, 1, dr)\n for _ in range(1, num_block)\n ]\n\n return nn.Sequential(*layers)\n"
] | [
[
"torch.nn.CrossEntropyLoss",
"torch.optim.lr_scheduler.ReduceLROnPlateau"
],
[
"torch.nn.Sequential",
"torch.nn.Dropout",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.AdaptiveAvgPool2d",
"torch.nn.BatchNorm2d",
"torch.nn.SiLU",
"torch.nn.Hardsigmoid"
],
[
"torch.nn.Sequential",
"torch.nn.Conv2d",
"torch.nn.AdaptiveAvgPool2d"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ganik/DeepSpeedExamples | [
"174ae3bc8dbb688cfaccb4afa15d6e2cdbe19ce5",
"174ae3bc8dbb688cfaccb4afa15d6e2cdbe19ce5",
"174ae3bc8dbb688cfaccb4afa15d6e2cdbe19ce5"
] | [
"Megatron-LM-v1.1.5-ZeRO3/megatron/initialize.py",
"pipeline_parallelism/alexnet.py",
"MoQ/huggingface-transformers/src/transformers/models/mobilebert/modeling_tf_mobilebert.py"
] | [
"# coding=utf-8\n# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Megatron initialization.\"\"\"\n\nimport random\nimport os\n\nimport numpy as np\nimport torch\n\nfrom megatron import get_adlr_autoresume\nfrom megatron import get_args\nfrom megatron import get_tensorboard_writer\nfrom megatron import mpu\nfrom megatron.global_vars import set_global_variables\nfrom megatron.mpu import set_model_parallel_rank, set_model_parallel_world_size\n\nimport deepspeed\n\n\ndef initialize_megatron(extra_args_provider=None, args_defaults={},\n ignore_unknown_args=False, allow_no_cuda=False):\n \"\"\"Set global variables, initialize distributed, and\n set autoresume and random seeds.\n `allow_no_cuda` should not be set unless using megatron for cpu only\n data processing. In general this arg should not be set unless you know\n what you are doing.\n Returns a function to finalize distributed env initialization\n (optionally, only when args.lazy_mpu_init == True)\n\n\"\"\"\n if not allow_no_cuda:\n # Make sure cuda is available.\n assert torch.cuda.is_available(), 'Megatron requires CUDA.'\n\n # Parse args, build tokenizer, and set adlr-autoresume,\n # tensorboard-writer, and timers.\n set_global_variables(extra_args_provider=extra_args_provider,\n args_defaults=args_defaults,\n ignore_unknown_args=ignore_unknown_args)\n\n # torch.distributed initialization\n def finish_mpu_init():\n args = get_args()\n # Pytorch distributed.\n _initialize_distributed()\n\n # Random seeds for reproducibility.\n if args.rank == 0:\n print('> setting random seeds to {} ...'.format(args.seed))\n _set_random_seed(args.seed)\n\n args = get_args()\n if args.lazy_mpu_init:\n args.use_cpu_initialization=True\n # delayed initialization of DDP-related stuff\n # We only set basic DDP globals\n set_model_parallel_world_size(args.model_parallel_size)\n # and return function for external DDP manager to call when it has DDP initialized\n set_model_parallel_rank(args.rank)\n return finish_mpu_init\n else:\n # Megatron's MPU is the master. Complete initialization right away.\n finish_mpu_init()\n\n # Initialize memory buffers.\n _initialize_mem_buffs()\n\n # Autoresume.\n _init_autoresume()\n\n # Write arguments to tensorboard.\n _write_args_to_tensorboard()\n # No continuation function\n return None\n\n\ndef setup_deepspeed_random_and_activation_checkpointing(args):\n '''Optional DeepSpeed Activation Checkpointing features.\n Gives access to partition activations, contiguous memory optimizations\n and cpu checkpointing.\n\n Activation checkpoint requires keep track of the random states\n and setting the random seed for each MP process. Megatron uses\n mpu.get_cuda_rng_tracker and mpu.model_parallel_cuda_manual_seed\n for keeping track of the random states and setting the random seeds.\n Since they are used in places outside of activation checkpointing,\n we overwrite them to maintain consistency.\n\n This must be called before all the calls to mpu.model_parallel_cuda_manual_seed\n '''\n num_layers = args.num_layers // args.checkpoint_num_layers\n num_layers = num_layers if args.num_layers % args.checkpoint_num_layers == 0 else num_layers + 1\n if args.split_transformers:\n num_layers *= 2\n\n deepspeed.checkpointing.configure(\n mpu,\n partition_activations=args.partition_activations,\n contiguous_checkpointing=args.contigious_checkpointing,\n num_checkpoints=num_layers,\n checkpoint_in_cpu=args.checkpoint_in_cpu,\n synchronize=args.synchronize_each_layer,\n profile=args.profile_backward)\n\n mpu.checkpoint = deepspeed.checkpointing.checkpoint\n mpu.get_cuda_rng_tracker = deepspeed.checkpointing.get_cuda_rng_tracker\n mpu.model_parallel_cuda_manual_seed = deepspeed.checkpointing.model_parallel_cuda_manual_seed\n\n\ndef _initialize_distributed():\n \"\"\"Initialize torch.distributed and mpu.\"\"\"\n args = get_args()\n\n device_count = torch.cuda.device_count()\n if torch.distributed.is_initialized():\n\n if args.rank == 0:\n print('torch distributed is already initialized, '\n 'skipping initialization ...', flush=True)\n args.rank = torch.distributed.get_rank()\n args.world_size = torch.distributed.get_world_size()\n\n else:\n\n if args.rank == 0:\n print('> initializing torch distributed ...', flush=True)\n # Manually set the device ids.\n if device_count > 0:\n device = args.rank % device_count\n if args.local_rank is not None:\n assert args.local_rank == device, \\\n 'expected local-rank to be the same as rank % device-count.'\n else:\n args.local_rank = device\n torch.cuda.set_device(device)\n # Call the init process\n init_method = 'tcp://'\n master_ip = os.getenv('MASTER_ADDR', 'localhost')\n master_port = os.getenv('MASTER_PORT', '6000')\n init_method += master_ip + ':' + master_port\n torch.distributed.init_process_group(\n backend=args.distributed_backend,\n world_size=args.world_size, rank=args.rank,\n init_method=init_method)\n\n # Set the model-parallel / data-parallel communicators.\n if device_count > 0:\n if mpu.model_parallel_is_initialized():\n print('model parallel is already initialized')\n else:\n mpu.initialize_model_parallel(args.model_parallel_size)\n\n # Optional DeepSpeed Activation Checkpointing Features\n #\n if args.deepspeed and args.deepspeed_activation_checkpointing:\n setup_deepspeed_random_and_activation_checkpointing(args)\n\ndef _init_autoresume():\n \"\"\"Set autoresume start time.\"\"\"\n autoresume = get_adlr_autoresume()\n if autoresume:\n torch.distributed.barrier()\n autoresume.init()\n torch.distributed.barrier()\n\n\ndef _set_random_seed(seed):\n \"\"\"Set random seed for reproducability.\"\"\"\n if seed is not None and seed > 0:\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n if torch.cuda.device_count() > 0:\n mpu.model_parallel_cuda_manual_seed(seed)\n else:\n raise ValueError('Seed ({}) should be a positive integer.'.format(seed))\n\n\ndef _write_args_to_tensorboard():\n \"\"\"Write arguments to tensorboard.\"\"\"\n args = get_args()\n writer = get_tensorboard_writer()\n if writer:\n for arg in vars(args):\n writer.add_text(arg, str(getattr(args, arg)))\n\n\ndef _initialize_mem_buffs():\n \"\"\"Initialize manually allocated static memory.\"\"\"\n args = get_args()\n\n # Initialize memory for checkpointed activations.\n if args.distribute_checkpointed_activations:\n mpu.init_checkpointed_activations_memory_buffer()\n",
"#\n# Implementation of AlexNet for illustrative purposes. The train.py driver\n# can import AlexNet from here or directly from torchvision.\n#\n# Taken from torchvision.models.alexnet:\n# https://pytorch.org/docs/1.6.0/_modules/torchvision/models/alexnet.html#alexnet\n\n\nimport torch\nimport torch.nn as nn\n\n\nclass AlexNet(nn.Module):\n def __init__(self, num_classes=1000):\n super(AlexNet, self).__init__()\n self.features = nn.Sequential(\n nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2),\n nn.Conv2d(64, 192, kernel_size=5, padding=2),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2),\n nn.Conv2d(192, 384, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(384, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=3, stride=2),\n )\n self.avgpool = nn.AdaptiveAvgPool2d((6, 6))\n self.classifier = nn.Sequential(\n nn.Dropout(),\n nn.Linear(256 * 6 * 6, 4096),\n nn.ReLU(inplace=True),\n nn.Dropout(),\n nn.Linear(4096, 4096),\n nn.ReLU(inplace=True),\n nn.Linear(4096, num_classes),\n )\n\n def forward(self, x):\n x = self.features(x)\n x = self.avgpool(x)\n x = torch.flatten(x, 1)\n x = self.classifier(x)\n return x\n",
"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.\n# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\" TF 2.0 MobileBERT model. \"\"\"\n\nimport warnings\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple\n\nimport tensorflow as tf\n\nfrom ...activations_tf import get_tf_activation\nfrom ...file_utils import (\n MULTIPLE_CHOICE_DUMMY_INPUTS,\n ModelOutput,\n add_code_sample_docstrings,\n add_start_docstrings,\n add_start_docstrings_to_model_forward,\n replace_return_docstrings,\n)\nfrom ...modeling_tf_outputs import (\n TFBaseModelOutput,\n TFBaseModelOutputWithPooling,\n TFMaskedLMOutput,\n TFMultipleChoiceModelOutput,\n TFNextSentencePredictorOutput,\n TFQuestionAnsweringModelOutput,\n TFSequenceClassifierOutput,\n TFTokenClassifierOutput,\n)\nfrom ...modeling_tf_utils import (\n TFMaskedLanguageModelingLoss,\n TFMultipleChoiceLoss,\n TFNextSentencePredictionLoss,\n TFPreTrainedModel,\n TFQuestionAnsweringLoss,\n TFSequenceClassificationLoss,\n TFTokenClassificationLoss,\n get_initializer,\n input_processing,\n keras_serializable,\n shape_list,\n)\nfrom ...utils import logging\nfrom .configuration_mobilebert import MobileBertConfig\n\n\nlogger = logging.get_logger(__name__)\n\n_CONFIG_FOR_DOC = \"MobileBertConfig\"\n_TOKENIZER_FOR_DOC = \"MobileBertTokenizer\"\n\nTF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST = [\n \"google/mobilebert-uncased\",\n # See all MobileBERT models at https://huggingface.co/models?filter=mobilebert\n]\n\n\nclass TFMobileBertIntermediate(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n\n self.dense = tf.keras.layers.Dense(config.intermediate_size, name=\"dense\")\n\n if isinstance(config.hidden_act, str):\n self.intermediate_act_fn = get_tf_activation(config.hidden_act)\n else:\n self.intermediate_act_fn = config.hidden_act\n\n def call(self, hidden_states):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.intermediate_act_fn(hidden_states)\n\n return hidden_states\n\n\nclass TFLayerNorm(tf.keras.layers.LayerNormalization):\n def __init__(self, feat_size, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n\nclass TFNoNorm(tf.keras.layers.Layer):\n def __init__(self, feat_size, epsilon=None, **kwargs):\n super().__init__(**kwargs)\n self.feat_size = feat_size\n\n def build(self, input_shape):\n self.bias = self.add_weight(\"bias\", shape=[self.feat_size], initializer=\"zeros\")\n self.weight = self.add_weight(\"weight\", shape=[self.feat_size], initializer=\"ones\")\n\n def call(self, inputs: tf.Tensor):\n return inputs * self.weight + self.bias\n\n\nNORM2FN = {\"layer_norm\": TFLayerNorm, \"no_norm\": TFNoNorm}\n\n\nclass TFMobileBertEmbeddings(tf.keras.layers.Layer):\n \"\"\"Construct the embeddings from word, position and token_type embeddings.\"\"\"\n\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n\n self.trigram_input = config.trigram_input\n self.embedding_size = config.embedding_size\n self.vocab_size = config.vocab_size\n self.hidden_size = config.hidden_size\n self.type_vocab_size = config.type_vocab_size\n self.max_position_embeddings = config.max_position_embeddings\n self.initializer_range = config.initializer_range\n self.embeddings_sum = tf.keras.layers.Add()\n self.embedding_transformation = tf.keras.layers.Dense(config.hidden_size, name=\"embedding_transformation\")\n\n # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load\n # any TensorFlow checkpoint file\n self.LayerNorm = NORM2FN[config.normalization_type](\n config.hidden_size, epsilon=config.layer_norm_eps, name=\"LayerNorm\"\n )\n self.dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)\n\n def build(self, input_shape):\n with tf.name_scope(\"word_embeddings\"):\n self.weight = self.add_weight(\n name=\"weight\",\n shape=[self.vocab_size, self.embedding_size],\n initializer=get_initializer(initializer_range=self.initializer_range),\n )\n\n with tf.name_scope(\"token_type_embeddings\"):\n self.token_type_embeddings = self.add_weight(\n name=\"embeddings\",\n shape=[self.type_vocab_size, self.hidden_size],\n initializer=get_initializer(initializer_range=self.initializer_range),\n )\n\n with tf.name_scope(\"position_embeddings\"):\n self.position_embeddings = self.add_weight(\n name=\"embeddings\",\n shape=[self.max_position_embeddings, self.hidden_size],\n initializer=get_initializer(initializer_range=self.initializer_range),\n )\n\n super().build(input_shape)\n\n def call(self, input_ids=None, position_ids=None, token_type_ids=None, inputs_embeds=None, training=False):\n \"\"\"\n Applies embedding based on inputs tensor.\n\n Returns:\n final_embeddings (:obj:`tf.Tensor`): output embedding tensor.\n \"\"\"\n assert not (input_ids is None and inputs_embeds is None)\n\n if input_ids is not None:\n inputs_embeds = tf.gather(params=self.weight, indices=input_ids)\n\n input_shape = shape_list(inputs_embeds)[:-1]\n\n if token_type_ids is None:\n token_type_ids = tf.fill(dims=input_shape, value=0)\n\n if self.trigram_input:\n # From the paper MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited\n # Devices (https://arxiv.org/abs/2004.02984)\n #\n # The embedding table in BERT models accounts for a substantial proportion of model size. To compress\n # the embedding layer, we reduce the embedding dimension to 128 in MobileBERT.\n # Then, we apply a 1D convolution with kernel size 3 on the raw token embedding to produce a 512\n # dimensional output.\n inputs_embeds = tf.concat(\n [\n tf.pad(inputs_embeds[:, 1:], ((0, 0), (0, 1), (0, 0))),\n inputs_embeds,\n tf.pad(inputs_embeds[:, :-1], ((0, 0), (1, 0), (0, 0))),\n ],\n axis=2,\n )\n\n if self.trigram_input or self.embedding_size != self.hidden_size:\n inputs_embeds = self.embedding_transformation(inputs_embeds)\n\n if position_ids is None:\n position_ids = tf.expand_dims(tf.range(start=0, limit=input_shape[-1]), axis=0)\n\n position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)\n position_embeds = tf.tile(input=position_embeds, multiples=(input_shape[0], 1, 1))\n token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids)\n final_embeddings = self.embeddings_sum(inputs=[inputs_embeds, position_embeds, token_type_embeds])\n final_embeddings = self.LayerNorm(inputs=final_embeddings)\n final_embeddings = self.dropout(inputs=final_embeddings, training=training)\n\n return final_embeddings\n\n\nclass TFMobileBertSelfAttention(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n if config.hidden_size % config.num_attention_heads != 0:\n raise ValueError(\n \"The hidden size (%d) is not a multiple of the number of attention \"\n \"heads (%d)\" % (config.hidden_size, config.num_attention_heads)\n )\n\n self.num_attention_heads = config.num_attention_heads\n self.output_attentions = config.output_attentions\n assert config.hidden_size % config.num_attention_heads == 0\n self.attention_head_size = int(config.true_hidden_size / config.num_attention_heads)\n self.all_head_size = self.num_attention_heads * self.attention_head_size\n\n self.query = tf.keras.layers.Dense(\n self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name=\"query\"\n )\n self.key = tf.keras.layers.Dense(\n self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name=\"key\"\n )\n self.value = tf.keras.layers.Dense(\n self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name=\"value\"\n )\n\n self.dropout = tf.keras.layers.Dropout(config.attention_probs_dropout_prob)\n\n def transpose_for_scores(self, x, batch_size):\n # Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]\n x = tf.reshape(x, (batch_size, -1, self.num_attention_heads, self.attention_head_size))\n return tf.transpose(x, perm=[0, 2, 1, 3])\n\n def call(\n self, query_tensor, key_tensor, value_tensor, attention_mask, head_mask, output_attentions, training=False\n ):\n batch_size = shape_list(attention_mask)[0]\n mixed_query_layer = self.query(query_tensor)\n mixed_key_layer = self.key(key_tensor)\n mixed_value_layer = self.value(value_tensor)\n query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)\n key_layer = self.transpose_for_scores(mixed_key_layer, batch_size)\n value_layer = self.transpose_for_scores(mixed_value_layer, batch_size)\n\n # Take the dot product between \"query\" and \"key\" to get the raw attention scores.\n attention_scores = tf.matmul(\n query_layer, key_layer, transpose_b=True\n ) # (batch size, num_heads, seq_len_q, seq_len_k)\n dk = tf.cast(shape_list(key_layer)[-1], dtype=attention_scores.dtype) # scale attention_scores\n attention_scores = attention_scores / tf.math.sqrt(dk)\n\n if attention_mask is not None:\n # Apply the attention mask is (precomputed for all layers in TFMobileBertModel call() function)\n attention_mask = tf.cast(attention_mask, dtype=attention_scores.dtype)\n attention_scores = attention_scores + attention_mask\n\n # Normalize the attention scores to probabilities.\n attention_probs = tf.nn.softmax(attention_scores, axis=-1)\n\n # This is actually dropping out entire tokens to attend to, which might\n # seem a bit unusual, but is taken from the original Transformer paper.\n attention_probs = self.dropout(attention_probs, training=training)\n\n # Mask heads if we want to\n if head_mask is not None:\n attention_probs = attention_probs * head_mask\n\n context_layer = tf.matmul(attention_probs, value_layer)\n\n context_layer = tf.transpose(context_layer, perm=[0, 2, 1, 3])\n context_layer = tf.reshape(\n context_layer, (batch_size, -1, self.all_head_size)\n ) # (batch_size, seq_len_q, all_head_size)\n\n outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)\n\n return outputs\n\n\nclass TFMobileBertSelfOutput(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n self.use_bottleneck = config.use_bottleneck\n self.dense = tf.keras.layers.Dense(\n config.true_hidden_size, kernel_initializer=get_initializer(config.initializer_range), name=\"dense\"\n )\n self.LayerNorm = NORM2FN[config.normalization_type](\n config.true_hidden_size, epsilon=config.layer_norm_eps, name=\"LayerNorm\"\n )\n if not self.use_bottleneck:\n self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob)\n\n def call(self, hidden_states, residual_tensor, training=False):\n hidden_states = self.dense(hidden_states)\n if not self.use_bottleneck:\n hidden_states = self.dropout(hidden_states, training=training)\n hidden_states = self.LayerNorm(hidden_states + residual_tensor)\n return hidden_states\n\n\nclass TFMobileBertAttention(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n self.self = TFMobileBertSelfAttention(config, name=\"self\")\n self.mobilebert_output = TFMobileBertSelfOutput(config, name=\"output\")\n\n def prune_heads(self, heads):\n raise NotImplementedError\n\n def call(\n self,\n query_tensor,\n key_tensor,\n value_tensor,\n layer_input,\n attention_mask,\n head_mask,\n output_attentions,\n training=False,\n ):\n self_outputs = self.self(\n query_tensor, key_tensor, value_tensor, attention_mask, head_mask, output_attentions, training=training\n )\n\n attention_output = self.mobilebert_output(self_outputs[0], layer_input, training=training)\n outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them\n return outputs\n\n\nclass TFOutputBottleneck(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n self.dense = tf.keras.layers.Dense(config.hidden_size, name=\"dense\")\n self.LayerNorm = NORM2FN[config.normalization_type](\n config.hidden_size, epsilon=config.layer_norm_eps, name=\"LayerNorm\"\n )\n self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob)\n\n def call(self, hidden_states, residual_tensor, training=False):\n layer_outputs = self.dense(hidden_states)\n layer_outputs = self.dropout(layer_outputs, training=training)\n layer_outputs = self.LayerNorm(layer_outputs + residual_tensor)\n return layer_outputs\n\n\nclass TFMobileBertOutput(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n self.use_bottleneck = config.use_bottleneck\n self.dense = tf.keras.layers.Dense(\n config.true_hidden_size, kernel_initializer=get_initializer(config.initializer_range), name=\"dense\"\n )\n self.LayerNorm = NORM2FN[config.normalization_type](\n config.true_hidden_size, epsilon=config.layer_norm_eps, name=\"LayerNorm\"\n )\n if not self.use_bottleneck:\n self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob)\n else:\n self.bottleneck = TFOutputBottleneck(config, name=\"bottleneck\")\n\n def call(self, hidden_states, residual_tensor_1, residual_tensor_2, training=False):\n hidden_states = self.dense(hidden_states)\n if not self.use_bottleneck:\n hidden_states = self.dropout(hidden_states, training=training)\n hidden_states = self.LayerNorm(hidden_states + residual_tensor_1)\n else:\n hidden_states = self.LayerNorm(hidden_states + residual_tensor_1)\n hidden_states = self.bottleneck(hidden_states, residual_tensor_2)\n return hidden_states\n\n\nclass TFBottleneckLayer(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n self.dense = tf.keras.layers.Dense(config.intra_bottleneck_size, name=\"dense\")\n self.LayerNorm = NORM2FN[config.normalization_type](\n config.intra_bottleneck_size, epsilon=config.layer_norm_eps, name=\"LayerNorm\"\n )\n\n def call(self, inputs):\n hidden_states = self.dense(inputs)\n hidden_states = self.LayerNorm(hidden_states)\n return hidden_states\n\n\nclass TFBottleneck(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n self.key_query_shared_bottleneck = config.key_query_shared_bottleneck\n self.use_bottleneck_attention = config.use_bottleneck_attention\n self.bottleneck_input = TFBottleneckLayer(config, name=\"input\")\n if self.key_query_shared_bottleneck:\n self.attention = TFBottleneckLayer(config, name=\"attention\")\n\n def call(self, hidden_states):\n # This method can return three different tuples of values. These different values make use of bottlenecks,\n # which are linear layers used to project the hidden states to a lower-dimensional vector, reducing memory\n # usage. These linear layer have weights that are learned during training.\n #\n # If `config.use_bottleneck_attention`, it will return the result of the bottleneck layer four times for the\n # key, query, value, and \"layer input\" to be used by the attention layer.\n # This bottleneck is used to project the hidden. This last layer input will be used as a residual tensor\n # in the attention self output, after the attention scores have been computed.\n #\n # If not `config.use_bottleneck_attention` and `config.key_query_shared_bottleneck`, this will return\n # four values, three of which have been passed through a bottleneck: the query and key, passed through the same\n # bottleneck, and the residual layer to be applied in the attention self output, through another bottleneck.\n #\n # Finally, in the last case, the values for the query, key and values are the hidden states without bottleneck,\n # and the residual layer will be this value passed through a bottleneck.\n\n bottlenecked_hidden_states = self.bottleneck_input(hidden_states)\n if self.use_bottleneck_attention:\n return (bottlenecked_hidden_states,) * 4\n elif self.key_query_shared_bottleneck:\n shared_attention_input = self.attention(hidden_states)\n return (shared_attention_input, shared_attention_input, hidden_states, bottlenecked_hidden_states)\n else:\n return (hidden_states, hidden_states, hidden_states, bottlenecked_hidden_states)\n\n\nclass TFFFNOutput(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n self.dense = tf.keras.layers.Dense(config.true_hidden_size, name=\"dense\")\n self.LayerNorm = NORM2FN[config.normalization_type](\n config.true_hidden_size, epsilon=config.layer_norm_eps, name=\"LayerNorm\"\n )\n\n def call(self, hidden_states, residual_tensor):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.LayerNorm(hidden_states + residual_tensor)\n return hidden_states\n\n\nclass TFFFNLayer(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n self.intermediate = TFMobileBertIntermediate(config, name=\"intermediate\")\n self.mobilebert_output = TFFFNOutput(config, name=\"output\")\n\n def call(self, hidden_states):\n intermediate_output = self.intermediate(hidden_states)\n layer_outputs = self.mobilebert_output(intermediate_output, hidden_states)\n return layer_outputs\n\n\nclass TFMobileBertLayer(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n self.use_bottleneck = config.use_bottleneck\n self.num_feedforward_networks = config.num_feedforward_networks\n self.attention = TFMobileBertAttention(config, name=\"attention\")\n self.intermediate = TFMobileBertIntermediate(config, name=\"intermediate\")\n self.mobilebert_output = TFMobileBertOutput(config, name=\"output\")\n\n if self.use_bottleneck:\n self.bottleneck = TFBottleneck(config, name=\"bottleneck\")\n if config.num_feedforward_networks > 1:\n self.ffn = [\n TFFFNLayer(config, name=\"ffn.{}\".format(i)) for i in range(config.num_feedforward_networks - 1)\n ]\n\n def call(self, hidden_states, attention_mask, head_mask, output_attentions, training=False):\n if self.use_bottleneck:\n query_tensor, key_tensor, value_tensor, layer_input = self.bottleneck(hidden_states)\n else:\n query_tensor, key_tensor, value_tensor, layer_input = [hidden_states] * 4\n\n attention_outputs = self.attention(\n query_tensor,\n key_tensor,\n value_tensor,\n layer_input,\n attention_mask,\n head_mask,\n output_attentions,\n training=training,\n )\n\n attention_output = attention_outputs[0]\n s = (attention_output,)\n\n if self.num_feedforward_networks != 1:\n for i, ffn_module in enumerate(self.ffn):\n attention_output = ffn_module(attention_output)\n s += (attention_output,)\n\n intermediate_output = self.intermediate(attention_output)\n layer_output = self.mobilebert_output(intermediate_output, attention_output, hidden_states, training=training)\n\n outputs = (\n (layer_output,)\n + attention_outputs[1:]\n + (\n tf.constant(0),\n query_tensor,\n key_tensor,\n value_tensor,\n layer_input,\n attention_output,\n intermediate_output,\n )\n + s\n ) # add attentions if we output them\n\n return outputs\n\n\nclass TFMobileBertEncoder(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n self.output_attentions = config.output_attentions\n self.output_hidden_states = config.output_hidden_states\n self.layer = [TFMobileBertLayer(config, name=\"layer_._{}\".format(i)) for i in range(config.num_hidden_layers)]\n\n def call(\n self,\n hidden_states,\n attention_mask,\n head_mask,\n output_attentions,\n output_hidden_states,\n return_dict,\n training=False,\n ):\n all_hidden_states = () if output_hidden_states else None\n all_attentions = () if output_attentions else None\n for i, layer_module in enumerate(self.layer):\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n layer_outputs = layer_module(\n hidden_states, attention_mask, head_mask[i], output_attentions, training=training\n )\n\n hidden_states = layer_outputs[0]\n\n if output_attentions:\n all_attentions = all_attentions + (layer_outputs[1],)\n\n # Add last layer\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if not return_dict:\n return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)\n return TFBaseModelOutput(\n last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions\n )\n\n\nclass TFMobileBertPooler(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n self.do_activate = config.classifier_activation\n if self.do_activate:\n self.dense = tf.keras.layers.Dense(\n config.hidden_size,\n kernel_initializer=get_initializer(config.initializer_range),\n activation=\"tanh\",\n name=\"dense\",\n )\n\n def call(self, hidden_states):\n # We \"pool\" the model by simply taking the hidden state corresponding\n # to the first token.\n first_token_tensor = hidden_states[:, 0]\n if not self.do_activate:\n return first_token_tensor\n else:\n pooled_output = self.dense(first_token_tensor)\n return pooled_output\n\n\nclass TFMobileBertPredictionHeadTransform(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n self.dense = tf.keras.layers.Dense(\n config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name=\"dense\"\n )\n if isinstance(config.hidden_act, str):\n self.transform_act_fn = get_tf_activation(config.hidden_act)\n else:\n self.transform_act_fn = config.hidden_act\n self.LayerNorm = NORM2FN[\"layer_norm\"](config.hidden_size, epsilon=config.layer_norm_eps, name=\"LayerNorm\")\n\n def call(self, hidden_states):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.transform_act_fn(hidden_states)\n hidden_states = self.LayerNorm(hidden_states)\n return hidden_states\n\n\nclass TFMobileBertLMPredictionHead(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n self.transform = TFMobileBertPredictionHeadTransform(config, name=\"transform\")\n self.vocab_size = config.vocab_size\n self.config = config\n\n def build(self, input_shape):\n self.bias = self.add_weight(shape=(self.vocab_size,), initializer=\"zeros\", trainable=True, name=\"bias\")\n self.dense = self.add_weight(\n shape=(self.config.hidden_size - self.config.embedding_size, self.vocab_size),\n initializer=\"zeros\",\n trainable=True,\n name=\"dense/weight\",\n )\n self.decoder = self.add_weight(\n shape=(self.config.vocab_size, self.config.embedding_size),\n initializer=\"zeros\",\n trainable=True,\n name=\"decoder/weight\",\n )\n super().build(input_shape)\n\n def get_output_embeddings(self):\n return self\n\n def set_output_embeddings(self, value):\n self.decoder = value\n self.vocab_size = shape_list(value)[0]\n\n def get_bias(self):\n return {\"bias\": self.bias}\n\n def set_bias(self, value):\n self.bias = value[\"bias\"]\n self.vocab_size = shape_list(value[\"bias\"])[0]\n\n def call(self, hidden_states):\n hidden_states = self.transform(hidden_states)\n hidden_states = tf.matmul(hidden_states, tf.concat([tf.transpose(self.decoder), self.dense], axis=0))\n hidden_states = hidden_states + self.bias\n return hidden_states\n\n\nclass TFMobileBertMLMHead(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n self.predictions = TFMobileBertLMPredictionHead(config, name=\"predictions\")\n\n def call(self, sequence_output):\n prediction_scores = self.predictions(sequence_output)\n return prediction_scores\n\n\n@keras_serializable\nclass TFMobileBertMainLayer(tf.keras.layers.Layer):\n config_class = MobileBertConfig\n\n def __init__(self, config, add_pooling_layer=True, **kwargs):\n super().__init__(**kwargs)\n\n self.config = config\n self.num_hidden_layers = config.num_hidden_layers\n self.output_attentions = config.output_attentions\n self.output_hidden_states = config.output_hidden_states\n self.return_dict = config.use_return_dict\n\n self.embeddings = TFMobileBertEmbeddings(config, name=\"embeddings\")\n self.encoder = TFMobileBertEncoder(config, name=\"encoder\")\n self.pooler = TFMobileBertPooler(config, name=\"pooler\") if add_pooling_layer else None\n\n def get_input_embeddings(self):\n return self.embeddings\n\n def set_input_embeddings(self, value):\n self.embeddings.weight = value\n self.embeddings.vocab_size = shape_list(value)[0]\n\n def _prune_heads(self, heads_to_prune):\n \"\"\"\n Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base\n class PreTrainedModel\n \"\"\"\n raise NotImplementedError\n\n def call(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n training=False,\n **kwargs,\n ):\n inputs = input_processing(\n func=self.call,\n config=self.config,\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n kwargs_call=kwargs,\n )\n\n if inputs[\"input_ids\"] is not None and inputs[\"inputs_embeds\"] is not None:\n raise ValueError(\"You cannot specify both input_ids and inputs_embeds at the same time\")\n elif inputs[\"input_ids\"] is not None:\n input_shape = shape_list(inputs[\"input_ids\"])\n elif inputs[\"inputs_embeds\"] is not None:\n input_shape = shape_list(inputs[\"inputs_embeds\"])[:-1]\n else:\n raise ValueError(\"You have to specify either input_ids or inputs_embeds\")\n\n if inputs[\"attention_mask\"] is None:\n inputs[\"attention_mask\"] = tf.fill(input_shape, 1)\n\n if inputs[\"token_type_ids\"] is None:\n inputs[\"token_type_ids\"] = tf.fill(input_shape, 0)\n\n embedding_output = self.embeddings(\n inputs[\"input_ids\"],\n inputs[\"position_ids\"],\n inputs[\"token_type_ids\"],\n inputs[\"inputs_embeds\"],\n training=inputs[\"training\"],\n )\n\n # We create a 3D attention mask from a 2D tensor mask.\n # Sizes are [batch_size, 1, 1, to_seq_length]\n # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]\n # this attention mask is more simple than the triangular masking of causal attention\n # used in OpenAI GPT, we just need to prepare the broadcast dimension here.\n extended_attention_mask = tf.reshape(inputs[\"attention_mask\"], (input_shape[0], 1, 1, input_shape[1]))\n\n # Since attention_mask is 1.0 for positions we want to attend and 0.0 for\n # masked positions, this operation will create a tensor which is 0.0 for\n # positions we want to attend and -10000.0 for masked positions.\n # Since we are adding it to the raw scores before the softmax, this is\n # effectively the same as removing these entirely.\n extended_attention_mask = tf.cast(extended_attention_mask, dtype=embedding_output.dtype)\n one_cst = tf.constant(1.0, dtype=embedding_output.dtype)\n ten_thousand_cst = tf.constant(-10000.0, dtype=embedding_output.dtype)\n extended_attention_mask = tf.multiply(tf.subtract(one_cst, extended_attention_mask), ten_thousand_cst)\n\n # Prepare head mask if needed\n # 1.0 in head_mask indicate we keep the head\n # attention_probs has shape bsz x n_heads x N x N\n # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]\n # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]\n if inputs[\"head_mask\"] is not None:\n raise NotImplementedError\n else:\n inputs[\"head_mask\"] = [None] * self.num_hidden_layers\n\n encoder_outputs = self.encoder(\n embedding_output,\n extended_attention_mask,\n inputs[\"head_mask\"],\n inputs[\"output_attentions\"],\n inputs[\"output_hidden_states\"],\n inputs[\"return_dict\"],\n training=inputs[\"training\"],\n )\n\n sequence_output = encoder_outputs[0]\n pooled_output = self.pooler(sequence_output) if self.pooler is not None else None\n\n if not inputs[\"return_dict\"]:\n return (\n sequence_output,\n pooled_output,\n ) + encoder_outputs[1:]\n\n return TFBaseModelOutputWithPooling(\n last_hidden_state=sequence_output,\n pooler_output=pooled_output,\n hidden_states=encoder_outputs.hidden_states,\n attentions=encoder_outputs.attentions,\n )\n\n\nclass TFMobileBertPreTrainedModel(TFPreTrainedModel):\n \"\"\"\n An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained\n models.\n \"\"\"\n\n config_class = MobileBertConfig\n base_model_prefix = \"mobilebert\"\n\n\n@dataclass\nclass TFMobileBertForPreTrainingOutput(ModelOutput):\n \"\"\"\n Output type of :class:`~transformers.TFMobileBertForPreTraining`.\n\n Args:\n prediction_logits (:obj:`tf.Tensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`):\n Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).\n seq_relationship_logits (:obj:`tf.Tensor` of shape :obj:`(batch_size, 2)`):\n Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation\n before SoftMax).\n hidden_states (:obj:`tuple(tf.Tensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):\n Tuple of :obj:`tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of\n shape :obj:`(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (:obj:`tuple(tf.Tensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):\n Tuple of :obj:`tf.Tensor` (one for each layer) of shape :obj:`(batch_size, num_heads, sequence_length,\n sequence_length)`.\n\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention\n heads.\n \"\"\"\n\n loss: Optional[tf.Tensor] = None\n prediction_logits: tf.Tensor = None\n seq_relationship_logits: tf.Tensor = None\n hidden_states: Optional[Tuple[tf.Tensor]] = None\n attentions: Optional[Tuple[tf.Tensor]] = None\n\n\nMOBILEBERT_START_DOCSTRING = r\"\"\"\n\n This model inherits from :class:`~transformers.TFPreTrainedModel`. Check the superclass documentation for the\n generic methods the library implements for all its model (such as downloading or saving, resizing the input\n embeddings, pruning heads etc.)\n\n This model is also a `tf.keras.Model <https://www.tensorflow.org/api_docs/python/tf/keras/Model>`__ subclass. Use\n it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage\n and behavior.\n\n .. note::\n\n TF 2.0 models accepts two formats as inputs:\n\n - having all inputs as keyword arguments (like PyTorch models), or\n - having all inputs as a list, tuple or dict in the first positional arguments.\n\n This second option is useful when using :meth:`tf.keras.Model.fit` method which currently requires having all\n the tensors in the first argument of the model call function: :obj:`model(inputs)`.\n\n If you choose this second option, there are three possibilities you can use to gather all the input Tensors in\n the first positional argument :\n\n - a single Tensor with :obj:`input_ids` only and nothing else: :obj:`model(inputs_ids)`\n - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:\n :obj:`model([input_ids, attention_mask])` or :obj:`model([input_ids, attention_mask, token_type_ids])`\n - a dictionary with one or several input Tensors associated to the input names given in the docstring:\n :obj:`model({\"input_ids\": input_ids, \"token_type_ids\": token_type_ids})`\n\n Parameters:\n config (:class:`~transformers.MobileBertConfig`): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model\n weights.\n\"\"\"\n\nMOBILEBERT_INPUTS_DOCSTRING = r\"\"\"\n Args:\n input_ids (:obj:`Numpy array` or :obj:`tf.Tensor` of shape :obj:`({0})`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using :class:`~transformers.MobileBertTokenizer`. See\n :func:`transformers.PreTrainedTokenizer.__call__` and :func:`transformers.PreTrainedTokenizer.encode` for\n details.\n\n `What are input IDs? <../glossary.html#input-ids>`__\n attention_mask (:obj:`Numpy array` or :obj:`tf.Tensor` of shape :obj:`({0})`, `optional`):\n Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n `What are attention masks? <../glossary.html#attention-mask>`__\n token_type_ids (:obj:`Numpy array` or :obj:`tf.Tensor` of shape :obj:`({0})`, `optional`):\n Segment token indices to indicate first and second portions of the inputs. Indices are selected in ``[0,\n 1]``:\n\n - 0 corresponds to a `sentence A` token,\n - 1 corresponds to a `sentence B` token.\n\n `What are token type IDs? <../glossary.html#token-type-ids>`__\n position_ids (:obj:`Numpy array` or :obj:`tf.Tensor` of shape :obj:`({0})`, `optional`):\n Indices of positions of each input sequence tokens in the position embeddings. Selected in the range ``[0,\n config.max_position_embeddings - 1]``.\n\n `What are position IDs? <../glossary.html#position-ids>`__\n head_mask (:obj:`Numpy array` or :obj:`tf.Tensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`):\n Mask to nullify selected heads of the self-attention modules. Mask values selected in ``[0, 1]``:\n\n - 1 indicates the head is **not masked**,\n - 0 indicates the head is **masked**.\n\n inputs_embeds (:obj:`tf.Tensor` of shape :obj:`({0}, hidden_size)`, `optional`):\n Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.\n This is useful if you want more control over how to convert :obj:`input_ids` indices into associated\n vectors than the model's internal embedding lookup matrix.\n output_attentions (:obj:`bool`, `optional`):\n Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under returned\n tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the\n config will be used instead.\n output_hidden_states (:obj:`bool`, `optional`):\n Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors for\n more detail. This argument can be used only in eager mode, in graph mode the value in the config will be\n used instead.\n return_dict (:obj:`bool`, `optional`):\n Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple. This\n argument can be used in eager mode, in graph mode the value will always be set to True.\n training (:obj:`bool`, `optional`, defaults to :obj:`False`):\n Whether or not to use the model in training mode (some modules like dropout modules have different\n behaviors between training and evaluation).\n\"\"\"\n\n\n@add_start_docstrings(\n \"The bare MobileBert Model transformer outputting raw hidden-states without any specific head on top.\",\n MOBILEBERT_START_DOCSTRING,\n)\nclass TFMobileBertModel(TFMobileBertPreTrainedModel):\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n self.mobilebert = TFMobileBertMainLayer(config, name=\"mobilebert\")\n\n @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n tokenizer_class=_TOKENIZER_FOR_DOC,\n checkpoint=\"google/mobilebert-uncased\",\n output_type=TFBaseModelOutputWithPooling,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n training=False,\n **kwargs,\n ):\n inputs = input_processing(\n func=self.call,\n config=self.config,\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n kwargs_call=kwargs,\n )\n outputs = self.mobilebert(\n input_ids=inputs[\"input_ids\"],\n attention_mask=inputs[\"attention_mask\"],\n token_type_ids=inputs[\"token_type_ids\"],\n position_ids=inputs[\"position_ids\"],\n head_mask=inputs[\"head_mask\"],\n inputs_embeds=inputs[\"inputs_embeds\"],\n output_attentions=inputs[\"output_attentions\"],\n output_hidden_states=inputs[\"output_hidden_states\"],\n return_dict=inputs[\"return_dict\"],\n training=inputs[\"training\"],\n )\n\n return outputs\n\n # Copied from transformers.models.bert.modeling_tf_bert.TFBertModel.serving_output\n def serving_output(self, output: TFBaseModelOutputWithPooling) -> TFBaseModelOutputWithPooling:\n hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None\n attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None\n\n return TFBaseModelOutputWithPooling(\n last_hidden_state=output.last_hidden_state,\n pooler_output=output.pooler_output,\n hidden_states=hs,\n attentions=attns,\n )\n\n\n@add_start_docstrings(\n \"\"\"\n MobileBert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a\n `next sentence prediction (classification)` head.\n \"\"\",\n MOBILEBERT_START_DOCSTRING,\n)\nclass TFMobileBertForPreTraining(TFMobileBertPreTrainedModel):\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n self.mobilebert = TFMobileBertMainLayer(config, name=\"mobilebert\")\n self.predictions = TFMobileBertMLMHead(config, name=\"predictions___cls\")\n self.seq_relationship = TFMobileBertOnlyNSPHead(2, name=\"seq_relationship___cls\")\n\n def get_lm_head(self):\n return self.predictions.predictions\n\n def get_prefix_bias_name(self):\n warnings.warn(\"The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.\", FutureWarning)\n return self.name + \"/\" + self.predictions.name + \"/\" + self.predictions.predictions.name\n\n @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=TFMobileBertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)\n def call(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n training=False,\n **kwargs,\n ):\n r\"\"\"\n Return:\n\n Examples::\n\n >>> import tensorflow as tf\n >>> from transformers import MobileBertTokenizer, TFMobileBertForPreTraining\n\n >>> tokenizer = MobileBertTokenizer.from_pretrained('google/mobilebert-uncased')\n >>> model = TFMobileBertForPreTraining.from_pretrained('google/mobilebert-uncased')\n >>> input_ids = tf.constant(tokenizer.encode(\"Hello, my dog is cute\"))[None, :] # Batch size 1\n >>> outputs = model(input_ids)\n >>> prediction_scores, seq_relationship_scores = outputs[:2]\n\n \"\"\"\n inputs = input_processing(\n func=self.call,\n config=self.config,\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n kwargs_call=kwargs,\n )\n outputs = self.mobilebert(\n inputs[\"input_ids\"],\n attention_mask=inputs[\"attention_mask\"],\n token_type_ids=inputs[\"token_type_ids\"],\n position_ids=inputs[\"position_ids\"],\n head_mask=inputs[\"head_mask\"],\n inputs_embeds=inputs[\"inputs_embeds\"],\n output_attentions=inputs[\"output_attentions\"],\n output_hidden_states=inputs[\"output_hidden_states\"],\n return_dict=inputs[\"return_dict\"],\n training=inputs[\"training\"],\n )\n\n sequence_output, pooled_output = outputs[:2]\n prediction_scores = self.predictions(sequence_output)\n seq_relationship_score = self.seq_relationship(pooled_output)\n\n if not inputs[\"return_dict\"]:\n return (prediction_scores, seq_relationship_score) + outputs[2:]\n\n return TFMobileBertForPreTrainingOutput(\n prediction_logits=prediction_scores,\n seq_relationship_logits=seq_relationship_score,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n def serving_output(self, output):\n hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None\n attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None\n\n return TFMobileBertForPreTrainingOutput(\n prediction_logits=output.prediction_logits,\n seq_relationship_logits=output.seq_relationship_logits,\n hidden_states=hs,\n attentions=attns,\n )\n\n\n@add_start_docstrings(\"\"\"MobileBert Model with a `language modeling` head on top. \"\"\", MOBILEBERT_START_DOCSTRING)\nclass TFMobileBertForMaskedLM(TFMobileBertPreTrainedModel, TFMaskedLanguageModelingLoss):\n # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model\n _keys_to_ignore_on_load_unexpected = [\n r\"pooler\",\n r\"seq_relationship___cls\",\n r\"cls.seq_relationship\",\n ]\n\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n\n self.mobilebert = TFMobileBertMainLayer(config, add_pooling_layer=False, name=\"mobilebert\")\n self.predictions = TFMobileBertMLMHead(config, name=\"predictions___cls\")\n\n def get_lm_head(self):\n return self.predictions.predictions\n\n def get_prefix_bias_name(self):\n warnings.warn(\"The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.\", FutureWarning)\n return self.name + \"/\" + self.mlm.name + \"/\" + self.mlm.predictions.name\n\n @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n tokenizer_class=_TOKENIZER_FOR_DOC,\n checkpoint=\"google/mobilebert-uncased\",\n output_type=TFMaskedLMOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n labels=None,\n training=False,\n **kwargs,\n ):\n r\"\"\"\n labels (:obj:`tf.Tensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):\n Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ...,\n config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored\n (masked), the loss is only computed for the tokens with labels\n \"\"\"\n inputs = input_processing(\n func=self.call,\n config=self.config,\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n labels=labels,\n training=training,\n kwargs_call=kwargs,\n )\n outputs = self.mobilebert(\n inputs[\"input_ids\"],\n attention_mask=inputs[\"attention_mask\"],\n token_type_ids=inputs[\"token_type_ids\"],\n position_ids=inputs[\"position_ids\"],\n head_mask=inputs[\"head_mask\"],\n inputs_embeds=inputs[\"inputs_embeds\"],\n output_attentions=inputs[\"output_attentions\"],\n output_hidden_states=inputs[\"output_hidden_states\"],\n return_dict=inputs[\"return_dict\"],\n training=inputs[\"training\"],\n )\n sequence_output = outputs[0]\n prediction_scores = self.predictions(sequence_output, training=inputs[\"training\"])\n\n loss = None if inputs[\"labels\"] is None else self.compute_loss(inputs[\"labels\"], prediction_scores)\n\n if not inputs[\"return_dict\"]:\n output = (prediction_scores,) + outputs[2:]\n return ((loss,) + output) if loss is not None else output\n\n return TFMaskedLMOutput(\n loss=loss,\n logits=prediction_scores,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n # Copied from transformers.models.bert.modeling_tf_bert.TFBertForMaskedLM.serving_output\n def serving_output(self, output: TFMaskedLMOutput) -> TFMaskedLMOutput:\n hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None\n attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None\n\n return TFMaskedLMOutput(logits=output.logits, hidden_states=hs, attentions=attns)\n\n\nclass TFMobileBertOnlyNSPHead(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n self.seq_relationship = tf.keras.layers.Dense(2, name=\"seq_relationship\")\n\n def call(self, pooled_output):\n seq_relationship_score = self.seq_relationship(pooled_output)\n return seq_relationship_score\n\n\n@add_start_docstrings(\n \"\"\"MobileBert Model with a `next sentence prediction (classification)` head on top. \"\"\",\n MOBILEBERT_START_DOCSTRING,\n)\nclass TFMobileBertForNextSentencePrediction(TFMobileBertPreTrainedModel, TFNextSentencePredictionLoss):\n # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model\n _keys_to_ignore_on_load_unexpected = [r\"predictions___cls\", r\"cls.predictions\"]\n\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n\n self.mobilebert = TFMobileBertMainLayer(config, name=\"mobilebert\")\n self.cls = TFMobileBertOnlyNSPHead(config, name=\"seq_relationship___cls\")\n\n @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @replace_return_docstrings(output_type=TFNextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)\n def call(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n next_sentence_label=None,\n training=False,\n **kwargs,\n ):\n r\"\"\"\n Return:\n\n Examples::\n\n >>> import tensorflow as tf\n >>> from transformers import MobileBertTokenizer, TFMobileBertForNextSentencePrediction\n\n >>> tokenizer = MobileBertTokenizer.from_pretrained('google/mobilebert-uncased')\n >>> model = TFMobileBertForNextSentencePrediction.from_pretrained('google/mobilebert-uncased')\n\n >>> prompt = \"In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced.\"\n >>> next_sentence = \"The sky is blue due to the shorter wavelength of blue light.\"\n >>> encoding = tokenizer(prompt, next_sentence, return_tensors='tf')\n\n >>> logits = model(encoding['input_ids'], token_type_ids=encoding['token_type_ids'])[0]\n \"\"\"\n inputs = input_processing(\n func=self.call,\n config=self.config,\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n next_sentence_label=next_sentence_label,\n training=training,\n kwargs_call=kwargs,\n )\n outputs = self.mobilebert(\n inputs[\"input_ids\"],\n attention_mask=inputs[\"attention_mask\"],\n token_type_ids=inputs[\"token_type_ids\"],\n position_ids=inputs[\"position_ids\"],\n head_mask=inputs[\"head_mask\"],\n inputs_embeds=inputs[\"inputs_embeds\"],\n output_attentions=inputs[\"output_attentions\"],\n output_hidden_states=inputs[\"output_hidden_states\"],\n return_dict=inputs[\"return_dict\"],\n training=inputs[\"training\"],\n )\n pooled_output = outputs[1]\n seq_relationship_scores = self.cls(pooled_output)\n\n next_sentence_loss = (\n None\n if inputs[\"next_sentence_label\"] is None\n else self.compute_loss(labels=inputs[\"next_sentence_label\"], logits=seq_relationship_scores)\n )\n\n if not inputs[\"return_dict\"]:\n output = (seq_relationship_scores,) + outputs[2:]\n return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output\n\n return TFNextSentencePredictorOutput(\n loss=next_sentence_loss,\n logits=seq_relationship_scores,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n # Copied from transformers.models.bert.modeling_tf_bert.TFBertForNextSentencePrediction.serving_output\n def serving_output(self, output: TFNextSentencePredictorOutput) -> TFNextSentencePredictorOutput:\n hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None\n attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None\n\n return TFNextSentencePredictorOutput(logits=output.logits, hidden_states=hs, attentions=attns)\n\n\n@add_start_docstrings(\n \"\"\"\n MobileBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the\n pooled output) e.g. for GLUE tasks.\n \"\"\",\n MOBILEBERT_START_DOCSTRING,\n)\nclass TFMobileBertForSequenceClassification(TFMobileBertPreTrainedModel, TFSequenceClassificationLoss):\n # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model\n _keys_to_ignore_on_load_unexpected = [\n r\"predictions___cls\",\n r\"seq_relationship___cls\",\n r\"cls.predictions\",\n r\"cls.seq_relationship\",\n ]\n _keys_to_ignore_on_load_missing = [r\"dropout\"]\n\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n self.num_labels = config.num_labels\n\n self.mobilebert = TFMobileBertMainLayer(config, name=\"mobilebert\")\n self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob)\n self.classifier = tf.keras.layers.Dense(\n config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name=\"classifier\"\n )\n\n @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n tokenizer_class=_TOKENIZER_FOR_DOC,\n checkpoint=\"google/mobilebert-uncased\",\n output_type=TFSequenceClassifierOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n labels=None,\n training=False,\n **kwargs,\n ):\n r\"\"\"\n labels (:obj:`tf.Tensor` of shape :obj:`(batch_size,)`, `optional`):\n Labels for computing the sequence classification/regression loss. Indices should be in :obj:`[0, ...,\n config.num_labels - 1]`. If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss),\n If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n \"\"\"\n inputs = input_processing(\n func=self.call,\n config=self.config,\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n labels=labels,\n training=training,\n kwargs_call=kwargs,\n )\n outputs = self.mobilebert(\n inputs[\"input_ids\"],\n attention_mask=inputs[\"attention_mask\"],\n token_type_ids=inputs[\"token_type_ids\"],\n position_ids=inputs[\"position_ids\"],\n head_mask=inputs[\"head_mask\"],\n inputs_embeds=inputs[\"inputs_embeds\"],\n output_attentions=inputs[\"output_attentions\"],\n output_hidden_states=inputs[\"output_hidden_states\"],\n return_dict=inputs[\"return_dict\"],\n training=inputs[\"training\"],\n )\n pooled_output = outputs[1]\n\n pooled_output = self.dropout(pooled_output, training=inputs[\"training\"])\n logits = self.classifier(pooled_output)\n\n loss = None if inputs[\"labels\"] is None else self.compute_loss(inputs[\"labels\"], logits)\n\n if not inputs[\"return_dict\"]:\n output = (logits,) + outputs[2:]\n return ((loss,) + output) if loss is not None else output\n\n return TFSequenceClassifierOutput(\n loss=loss,\n logits=logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n # Copied from transformers.models.bert.modeling_tf_bert.TFBertForSequenceClassification.serving_output\n def serving_output(self, output: TFSequenceClassifierOutput) -> TFSequenceClassifierOutput:\n hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None\n attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None\n\n return TFSequenceClassifierOutput(logits=output.logits, hidden_states=hs, attentions=attns)\n\n\n@add_start_docstrings(\n \"\"\"\n MobileBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a\n linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n \"\"\",\n MOBILEBERT_START_DOCSTRING,\n)\nclass TFMobileBertForQuestionAnswering(TFMobileBertPreTrainedModel, TFQuestionAnsweringLoss):\n # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model\n _keys_to_ignore_on_load_unexpected = [\n r\"pooler\",\n r\"predictions___cls\",\n r\"seq_relationship___cls\",\n r\"cls.predictions\",\n r\"cls.seq_relationship\",\n ]\n\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n self.num_labels = config.num_labels\n\n self.mobilebert = TFMobileBertMainLayer(config, add_pooling_layer=False, name=\"mobilebert\")\n self.qa_outputs = tf.keras.layers.Dense(\n config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name=\"qa_outputs\"\n )\n\n @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n tokenizer_class=_TOKENIZER_FOR_DOC,\n checkpoint=\"google/mobilebert-uncased\",\n output_type=TFQuestionAnsweringModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n start_positions=None,\n end_positions=None,\n training=False,\n **kwargs,\n ):\n r\"\"\"\n start_positions (:obj:`tf.Tensor` of shape :obj:`(batch_size,)`, `optional`):\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the\n sequence are not taken into account for computing the loss.\n end_positions (:obj:`tf.Tensor` of shape :obj:`(batch_size,)`, `optional`):\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the\n sequence are not taken into account for computing the loss.\n \"\"\"\n inputs = input_processing(\n func=self.call,\n config=self.config,\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n start_positions=start_positions,\n end_positions=end_positions,\n training=training,\n kwargs_call=kwargs,\n )\n outputs = self.mobilebert(\n inputs[\"input_ids\"],\n attention_mask=inputs[\"attention_mask\"],\n token_type_ids=inputs[\"token_type_ids\"],\n position_ids=inputs[\"position_ids\"],\n head_mask=inputs[\"head_mask\"],\n inputs_embeds=inputs[\"inputs_embeds\"],\n output_attentions=inputs[\"output_attentions\"],\n output_hidden_states=inputs[\"output_hidden_states\"],\n return_dict=inputs[\"return_dict\"],\n training=inputs[\"training\"],\n )\n sequence_output = outputs[0]\n\n logits = self.qa_outputs(sequence_output)\n start_logits, end_logits = tf.split(logits, 2, axis=-1)\n start_logits = tf.squeeze(start_logits, axis=-1)\n end_logits = tf.squeeze(end_logits, axis=-1)\n\n loss = None\n if inputs[\"start_positions\"] is not None and inputs[\"end_positions\"] is not None:\n labels = {\"start_position\": inputs[\"start_positions\"]}\n labels[\"end_position\"] = inputs[\"end_positions\"]\n loss = self.compute_loss(labels, (start_logits, end_logits))\n\n if not inputs[\"return_dict\"]:\n output = (start_logits, end_logits) + outputs[2:]\n return ((loss,) + output) if loss is not None else output\n\n return TFQuestionAnsweringModelOutput(\n loss=loss,\n start_logits=start_logits,\n end_logits=end_logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n # Copied from transformers.models.bert.modeling_tf_bert.TFBertForQuestionAnswering.serving_output\n def serving_output(self, output: TFQuestionAnsweringModelOutput) -> TFQuestionAnsweringModelOutput:\n hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None\n attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None\n\n return TFQuestionAnsweringModelOutput(\n start_logits=output.start_logits, end_logits=output.end_logits, hidden_states=hs, attentions=attns\n )\n\n\n@add_start_docstrings(\n \"\"\"\n MobileBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and\n a softmax) e.g. for RocStories/SWAG tasks.\n \"\"\",\n MOBILEBERT_START_DOCSTRING,\n)\nclass TFMobileBertForMultipleChoice(TFMobileBertPreTrainedModel, TFMultipleChoiceLoss):\n # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model\n _keys_to_ignore_on_load_unexpected = [\n r\"predictions___cls\",\n r\"seq_relationship___cls\",\n r\"cls.predictions\",\n r\"cls.seq_relationship\",\n ]\n _keys_to_ignore_on_load_missing = [r\"dropout\"]\n\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n\n self.mobilebert = TFMobileBertMainLayer(config, name=\"mobilebert\")\n self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob)\n self.classifier = tf.keras.layers.Dense(\n 1, kernel_initializer=get_initializer(config.initializer_range), name=\"classifier\"\n )\n\n @property\n def dummy_inputs(self):\n \"\"\"\n Dummy inputs to build the network.\n\n Returns:\n tf.Tensor with dummy inputs\n \"\"\"\n return {\"input_ids\": tf.constant(MULTIPLE_CHOICE_DUMMY_INPUTS)}\n\n @add_start_docstrings_to_model_forward(\n MOBILEBERT_INPUTS_DOCSTRING.format(\"batch_size, num_choices, sequence_length\")\n )\n @add_code_sample_docstrings(\n tokenizer_class=_TOKENIZER_FOR_DOC,\n checkpoint=\"google/mobilebert-uncased\",\n output_type=TFMultipleChoiceModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n labels=None,\n training=False,\n **kwargs,\n ):\n r\"\"\"\n labels (:obj:`tf.Tensor` of shape :obj:`(batch_size,)`, `optional`):\n Labels for computing the multiple choice classification loss. Indices should be in ``[0, ...,\n num_choices]`` where :obj:`num_choices` is the size of the second dimension of the input tensors. (See\n :obj:`input_ids` above)\n \"\"\"\n inputs = input_processing(\n func=self.call,\n config=self.config,\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n labels=labels,\n training=training,\n kwargs_call=kwargs,\n )\n\n if inputs[\"input_ids\"] is not None:\n num_choices = shape_list(inputs[\"input_ids\"])[1]\n seq_length = shape_list(inputs[\"input_ids\"])[2]\n else:\n num_choices = shape_list(inputs[\"inputs_embeds\"])[1]\n seq_length = shape_list(inputs[\"inputs_embeds\"])[2]\n\n flat_input_ids = tf.reshape(inputs[\"input_ids\"], (-1, seq_length)) if inputs[\"input_ids\"] is not None else None\n flat_attention_mask = (\n tf.reshape(inputs[\"attention_mask\"], (-1, seq_length)) if inputs[\"attention_mask\"] is not None else None\n )\n flat_token_type_ids = (\n tf.reshape(inputs[\"token_type_ids\"], (-1, seq_length)) if inputs[\"token_type_ids\"] is not None else None\n )\n flat_position_ids = (\n tf.reshape(inputs[\"position_ids\"], (-1, seq_length)) if inputs[\"position_ids\"] is not None else None\n )\n flat_inputs_embeds = (\n tf.reshape(inputs[\"inputs_embeds\"], (-1, seq_length, shape_list(inputs[\"inputs_embeds\"])[3]))\n if inputs[\"inputs_embeds\"] is not None\n else None\n )\n outputs = self.mobilebert(\n flat_input_ids,\n flat_attention_mask,\n flat_token_type_ids,\n flat_position_ids,\n inputs[\"head_mask\"],\n flat_inputs_embeds,\n inputs[\"output_attentions\"],\n inputs[\"output_hidden_states\"],\n return_dict=inputs[\"return_dict\"],\n training=inputs[\"training\"],\n )\n pooled_output = outputs[1]\n pooled_output = self.dropout(pooled_output, training=inputs[\"training\"])\n logits = self.classifier(pooled_output)\n reshaped_logits = tf.reshape(logits, (-1, num_choices))\n\n loss = None if inputs[\"labels\"] is None else self.compute_loss(inputs[\"labels\"], reshaped_logits)\n\n if not inputs[\"return_dict\"]:\n output = (reshaped_logits,) + outputs[2:]\n return ((loss,) + output) if loss is not None else output\n\n return TFMultipleChoiceModelOutput(\n loss=loss,\n logits=reshaped_logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n @tf.function(\n input_signature=[\n {\n \"input_ids\": tf.TensorSpec((None, None, None), tf.int32, name=\"input_ids\"),\n \"attention_mask\": tf.TensorSpec((None, None, None), tf.int32, name=\"attention_mask\"),\n \"token_type_ids\": tf.TensorSpec((None, None, None), tf.int32, name=\"token_type_ids\"),\n }\n ]\n )\n # Copied from transformers.models.bert.modeling_tf_bert.TFBertForMultipleChoice.serving\n def serving(self, inputs: Dict[str, tf.Tensor]):\n output = self.call(input_ids=inputs)\n\n return self.serving_output(output)\n\n # Copied from transformers.models.bert.modeling_tf_bert.TFBertForMultipleChoice.serving_output\n def serving_output(self, output: TFMultipleChoiceModelOutput) -> TFMultipleChoiceModelOutput:\n hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None\n attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None\n\n return TFMultipleChoiceModelOutput(logits=output.logits, hidden_states=hs, attentions=attns)\n\n\n@add_start_docstrings(\n \"\"\"\n MobileBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.\n for Named-Entity-Recognition (NER) tasks.\n \"\"\",\n MOBILEBERT_START_DOCSTRING,\n)\nclass TFMobileBertForTokenClassification(TFMobileBertPreTrainedModel, TFTokenClassificationLoss):\n # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model\n _keys_to_ignore_on_load_unexpected = [\n r\"pooler\",\n r\"predictions___cls\",\n r\"seq_relationship___cls\",\n r\"cls.predictions\",\n r\"cls.seq_relationship\",\n ]\n _keys_to_ignore_on_load_missing = [r\"dropout\"]\n\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n self.num_labels = config.num_labels\n\n self.mobilebert = TFMobileBertMainLayer(config, add_pooling_layer=False, name=\"mobilebert\")\n self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob)\n self.classifier = tf.keras.layers.Dense(\n config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name=\"classifier\"\n )\n\n @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n tokenizer_class=_TOKENIZER_FOR_DOC,\n checkpoint=\"google/mobilebert-uncased\",\n output_type=TFTokenClassifierOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n labels=None,\n training=False,\n **kwargs,\n ):\n r\"\"\"\n labels (:obj:`tf.Tensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):\n Labels for computing the token classification loss. Indices should be in ``[0, ..., config.num_labels -\n 1]``.\n \"\"\"\n inputs = input_processing(\n func=self.call,\n config=self.config,\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n labels=labels,\n training=training,\n kwargs_call=kwargs,\n )\n outputs = self.mobilebert(\n inputs[\"input_ids\"],\n attention_mask=inputs[\"attention_mask\"],\n token_type_ids=inputs[\"token_type_ids\"],\n position_ids=inputs[\"position_ids\"],\n head_mask=inputs[\"head_mask\"],\n inputs_embeds=inputs[\"inputs_embeds\"],\n output_attentions=inputs[\"output_attentions\"],\n output_hidden_states=inputs[\"output_hidden_states\"],\n return_dict=return_dict,\n training=inputs[\"training\"],\n )\n sequence_output = outputs[0]\n\n sequence_output = self.dropout(sequence_output, training=inputs[\"training\"])\n logits = self.classifier(sequence_output)\n\n loss = None if inputs[\"labels\"] is None else self.compute_loss(inputs[\"labels\"], logits)\n\n if not inputs[\"return_dict\"]:\n output = (logits,) + outputs[2:]\n return ((loss,) + output) if loss is not None else output\n\n return TFTokenClassifierOutput(\n loss=loss,\n logits=logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n # Copied from transformers.models.bert.modeling_tf_bert.TFBertForTokenClassification.serving_output\n def serving_output(self, output: TFTokenClassifierOutput) -> TFTokenClassifierOutput:\n hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None\n attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None\n\n return TFTokenClassifierOutput(logits=output.logits, hidden_states=hs, attentions=attns)\n"
] | [
[
"torch.distributed.init_process_group",
"numpy.random.seed",
"torch.cuda.set_device",
"torch.manual_seed",
"torch.distributed.is_initialized",
"torch.distributed.barrier",
"torch.cuda.is_available",
"torch.distributed.get_rank",
"torch.cuda.device_count",
"torch.distributed.get_world_size"
],
[
"torch.nn.Dropout",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.nn.Linear",
"torch.nn.AdaptiveAvgPool2d",
"torch.flatten",
"torch.nn.ReLU"
],
[
"tensorflow.convert_to_tensor",
"tensorflow.cast",
"tensorflow.pad",
"tensorflow.squeeze",
"tensorflow.subtract",
"tensorflow.gather",
"tensorflow.name_scope",
"tensorflow.keras.layers.Add",
"tensorflow.tile",
"tensorflow.matmul",
"tensorflow.fill",
"tensorflow.keras.layers.Dense",
"tensorflow.split",
"tensorflow.nn.softmax",
"tensorflow.transpose",
"tensorflow.constant",
"tensorflow.math.sqrt",
"tensorflow.range",
"tensorflow.reshape",
"tensorflow.keras.layers.Dropout",
"tensorflow.TensorSpec"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
kai-wen-yang/CD-VAE | [
"a33b5070d5d936396d51c8c2e7dedd62351ee5b2",
"a33b5070d5d936396d51c8c2e7dedd62351ee5b2"
] | [
"detection/lib/quilting_fast.py",
"detection/data_loader.py"
] | [
"#!/usr/bin/env python2\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport ctypes\nimport torch\nimport random\nimport numpy\nimport os\n\nimport pkgutil\nif pkgutil.find_loader(\"adversarial\") is not None:\n # If adversarial module is created by pip install\n QUILTING_LIB = ctypes.cdll.LoadLibrary(os.path.join(os.path.dirname(__file__), \"libquilting.so\"))\nelse:\n try:\n QUILTING_LIB = ctypes.cdll.LoadLibrary('libquilting.so')\n except ImportError:\n raise ImportError(\"libquilting.so not found. Check build script\")\n\n\ndef generate_patches(img, patch_size, overlap):\n assert torch.is_tensor(img) and img.dim() == 3\n assert type(patch_size) == int and patch_size > 0\n assert type(overlap) == int and overlap > 0\n assert patch_size > overlap\n\n y_range = range(0, img.size(1) - patch_size, patch_size - overlap)\n x_range = range(0, img.size(2) - patch_size, patch_size - overlap)\n num_patches = len(y_range) * len(x_range)\n patches = torch.FloatTensor(num_patches, 3 * patch_size * patch_size).zero_()\n\n QUILTING_LIB.generatePatches(\n ctypes.c_void_p(patches.data_ptr()),\n ctypes.c_void_p(img.data_ptr()),\n ctypes.c_uint(img.size(1)),\n ctypes.c_uint(img.size(2)),\n ctypes.c_uint(patch_size),\n ctypes.c_uint(overlap)\n )\n\n return patches\n\n\ndef generate_quilted_images(neighbors, patch_dict, img_h, img_w, patch_size,\n overlap, graphcut=False, random_stitch=False):\n assert torch.is_tensor(neighbors) and neighbors.dim() == 1\n assert torch.is_tensor(patch_dict) and patch_dict.dim() == 2\n assert type(img_h) == int and img_h > 0\n assert type(img_w) == int and img_w > 0\n assert type(patch_size) == int and patch_size > 0\n assert type(overlap) == int and overlap > 0\n assert patch_size > overlap\n\n result = torch.FloatTensor(3, img_h, img_w).zero_()\n\n QUILTING_LIB.generateQuiltedImages(\n ctypes.c_void_p(result.data_ptr()),\n ctypes.c_void_p(neighbors.data_ptr()),\n ctypes.c_void_p(patch_dict.data_ptr()),\n ctypes.c_uint(img_h),\n ctypes.c_uint(img_w),\n ctypes.c_uint(patch_size),\n ctypes.c_uint(overlap),\n ctypes.c_bool(graphcut)\n )\n\n return result\n\n\ndef select_random_neighbor(neighbors):\n if len(neighbors.shape) == 1:\n # If only 1 neighbor per path is available then return\n return neighbors\n else:\n # Pick a neighbor randomly from top k neighbors for all queries\n nrows = neighbors.shape[0]\n ncols = neighbors.shape[1]\n random_patched_neighbors = numpy.zeros(nrows).astype('int')\n for i in range(0, nrows):\n col = random.randint(0, ncols - 1)\n random_patched_neighbors[i] = neighbors[i, col]\n return random_patched_neighbors\n\n\n# main quilting function:\ndef quilting(img, faiss_index, patch_dict, patch_size=9, overlap=2,\n graphcut=False, k=1, random_stitch=False):\n\n # assertions:\n assert torch.is_tensor(img)\n assert torch.is_tensor(patch_dict) and patch_dict.dim() == 2\n assert type(patch_size) == int and patch_size > 0\n assert type(overlap) == int and overlap > 0\n assert patch_size > overlap\n\n # generate image patches\n patches = generate_patches(img, patch_size, overlap)\n\n # find nearest patches in faiss index:\n faiss_index.nprobe = 5\n # get top k neighbors of all queries\n _, neighbors = faiss_index.search(patches.numpy(), k)\n neighbors = select_random_neighbor(neighbors)\n neighbors = torch.LongTensor(neighbors).squeeze()\n if (neighbors == -1).any():\n print('WARNING: %d out of %d neighbor searches failed.' %\n ((neighbors == -1).sum(), neighbors.nelement()))\n\n # stitch nn patches in the dict\n quilted_img = generate_quilted_images(neighbors, patch_dict, img.size(1),\n img.size(2), patch_size, overlap,\n graphcut)\n\n return quilted_img\n",
"# original code is from https://github.com/aaron-xichen/pytorch-playground\n# modified by Kimin Lee\nimport torch\nfrom torchvision import datasets, transforms\nfrom torch.utils.data import DataLoader\nimport os\n\ndef getCIFAR10(batch_size, TF, data_root='/tmp/public_dataset/pytorch', train=True, val=True, **kwargs):\n kwargs.pop('input_size', None)\n ds = []\n if train:\n train_loader = torch.utils.data.DataLoader(\n datasets.CIFAR10(\n root=data_root, train=True, download=True,\n transform=TF),\n batch_size=batch_size, shuffle=True, **kwargs)\n ds.append(train_loader)\n if val:\n test_loader = torch.utils.data.DataLoader(\n datasets.CIFAR10(\n root=data_root, train=False, download=True,\n transform=TF),\n batch_size=batch_size, shuffle=False, **kwargs)\n ds.append(test_loader)\n ds = ds[0] if len(ds) == 1 else ds\n return ds\n\ndef getCIFAR100(batch_size, TF, data_root='/tmp/public_dataset/pytorch', train=True, val=True, **kwargs):\n data_root = os.path.expanduser(os.path.join(data_root, 'cifar100-data'))\n num_workers = kwargs.setdefault('num_workers', 1)\n kwargs.pop('input_size', None)\n ds = []\n if train:\n train_loader = torch.utils.data.DataLoader(\n datasets.CIFAR100(\n root=data_root, train=True, download=True,\n transform=TF),\n batch_size=batch_size, shuffle=True, **kwargs)\n ds.append(train_loader)\n\n if val:\n test_loader = torch.utils.data.DataLoader(\n datasets.CIFAR100(\n root=data_root, train=False, download=True,\n transform=TF),\n batch_size=batch_size, shuffle=False, **kwargs)\n ds.append(test_loader)\n ds = ds[0] if len(ds) == 1 else ds\n return ds\n\ndef getIMAGENET(batch_size, TF, data_root='/tmp/public_dataset/pytorch', train=True, val=True, **kwargs):\n traindir = os.path.join(data_root, 'train')\n valdir = os.path.join(data_root, 'val')\n num_workers = kwargs.setdefault('num_workers', 1)\n kwargs.pop('input_size', None)\n ds = []\n label_map = get_label_mapping('restricted_imagenet',\n constants.RESTRICTED_IMAGNET_RANGES)\n if train:\n train_dataset = folder.ImageFolder(root=traindir,\n transform=TF,\n label_mapping=label_map)\n train_loader = torch.utils.data.DataLoader(\n train_dataset, batch_size=batch_size, shuffle=True,\n num_workers=num_workers, pin_memory=True)\n ds.append(train_loader)\n if val:\n val_dataset = folder.ImageFolder(root=valdir,\n transform=TF,\n label_mapping=label_map)\n val_loader = torch.utils.data.DataLoader(\n val_dataset,\n batch_size=batch_size, shuffle=False,\n num_workers=num_workers, pin_memory=True,\n )\n ds.append(val_loader)\n ds = ds[0] if len(ds) == 1 else ds\n return ds\n\ndef getTargetDataSet(data_type, batch_size, input_TF, dataroot):\n if data_type == 'cifar10':\n train_loader, test_loader = getCIFAR10(batch_size=batch_size, TF=input_TF, data_root=dataroot, num_workers=1)\n elif data_type == 'imagenet':\n train_loader, test_loader = getIMAGENET(batch_size=batch_size, TF=input_TF, data_root=dataroot, num_workers=1)\n\n\n return train_loader, test_loader\n\ndef getNonTargetDataSet(data_type, batch_size, input_TF, dataroot):\n if data_type == 'cifar10':\n _, test_loader = getCIFAR10(batch_size=batch_size, TF=input_TF, data_root=dataroot, num_workers=1)\n elif data_type == 'svhn':\n _, test_loader = getSVHN(batch_size=batch_size, TF=input_TF, data_root=dataroot, num_workers=1)\n elif data_type == 'cifar100':\n _, test_loader = getCIFAR100(batch_size=batch_size, TF=input_TF, data_root=dataroot, num_workers=1)\n elif data_type == 'imagenet_resize':\n dataroot = os.path.expanduser(os.path.join(dataroot, 'Imagenet_resize'))\n testsetout = datasets.ImageFolder(dataroot, transform=input_TF)\n test_loader = torch.utils.data.DataLoader(testsetout, batch_size=batch_size, shuffle=False, num_workers=1)\n elif data_type == 'lsun_resize':\n dataroot = os.path.expanduser(os.path.join(dataroot, 'LSUN_resize'))\n testsetout = datasets.ImageFolder(dataroot, transform=input_TF)\n test_loader = torch.utils.data.DataLoader(testsetout, batch_size=batch_size, shuffle=False, num_workers=1)\n return test_loader\n\n\n"
] | [
[
"torch.LongTensor",
"torch.FloatTensor",
"torch.is_tensor",
"numpy.zeros"
],
[
"torch.utils.data.DataLoader"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ycl010203/PARL | [
"5fb7a5d2b5d0f0dac57fdf4acb9e79485c7efa96"
] | [
"examples/tutorials/parl2_dygraph/lesson4/policy_gradient/train.py"
] | [
"# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n#-*- coding: utf-8 -*-\n\n# 检查版本\nimport gym\nimport parl\nimport paddle\nassert paddle.__version__ == \"2.2.0\", \"[Version WARNING] please try `pip install paddlepaddle==2.2.0`\"\nassert parl.__version__ == \"2.0.3\", \"[Version WARNING] please try `pip install parl==2.0.1`\"\nassert gym.__version__ == \"0.18.0\", \"[Version WARNING] please try `pip install gym==0.18.0`\"\n\nimport os\nimport gym\nimport numpy as np\nimport parl\n\nfrom agent import Agent\nfrom model import Model\nfrom algorithm import PolicyGradient # from parl.algorithms import PolicyGradient\n\nfrom parl.utils import logger\n\nLEARNING_RATE = 1e-3\n\n\n# 训练一个episode\ndef run_train_episode(agent, env):\n obs_list, action_list, reward_list = [], [], []\n obs = env.reset()\n while True:\n obs_list.append(obs)\n action = agent.sample(obs)\n action_list.append(action)\n\n obs, reward, done, info = env.step(action)\n reward_list.append(reward)\n\n if done:\n break\n return obs_list, action_list, reward_list\n\n\n# 评估 agent, 跑 5 个episode,总reward求平均\ndef run_evaluate_episodes(agent, env, render=False):\n eval_reward = []\n for i in range(5):\n obs = env.reset()\n episode_reward = 0\n while True:\n action = agent.predict(obs)\n obs, reward, isOver, _ = env.step(action)\n episode_reward += reward\n if render:\n env.render()\n if isOver:\n break\n eval_reward.append(episode_reward)\n return np.mean(eval_reward)\n\n\ndef calc_reward_to_go(reward_list, gamma=1.0):\n for i in range(len(reward_list) - 2, -1, -1):\n # G_i = r_i + γ·G_i+1\n reward_list[i] += gamma * reward_list[i + 1] # Gt\n return np.array(reward_list)\n\n\ndef main():\n env = gym.make('CartPole-v0')\n # env = env.unwrapped # Cancel the minimum score limit\n obs_dim = env.observation_space.shape[0]\n act_dim = env.action_space.n\n logger.info('obs_dim {}, act_dim {}'.format(obs_dim, act_dim))\n\n # 根据parl框架构建agent\n model = Model(obs_dim=obs_dim, act_dim=act_dim)\n alg = PolicyGradient(model, lr=LEARNING_RATE)\n agent = Agent(alg)\n\n # 加载模型并评估\n # if os.path.exists('./model.ckpt'):\n # agent.restore('./model.ckpt')\n # run_evaluate_episodes(agent, env, render=True)\n # exit()\n\n for i in range(1000):\n obs_list, action_list, reward_list = run_train_episode(agent, env)\n if i % 10 == 0:\n logger.info(\"Episode {}, Reward Sum {}.\".format(\n i, sum(reward_list)))\n\n batch_obs = np.array(obs_list)\n batch_action = np.array(action_list)\n batch_reward = calc_reward_to_go(reward_list)\n\n agent.learn(batch_obs, batch_action, batch_reward)\n if (i + 1) % 100 == 0:\n # render=True 查看显示效果\n total_reward = run_evaluate_episodes(agent, env, render=False)\n logger.info('Test reward: {}'.format(total_reward))\n\n # save the parameters to ./model.ckpt\n agent.save('./model.ckpt')\n\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"numpy.array",
"numpy.mean"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
akkefa/bertserini | [
"bc3c8b20c256814dbe87ed7310dd4f2d10f304a0"
] | [
"bertserini/experiments/evaluate.py"
] | [
"import json\nimport argparse\nimport numpy as np\n\nfrom bertserini.utils.utils import choose_best_answer, weighted_score\n\nfrom bertserini.experiments.eval.evaluate_v1 import squad_v1_eval as squad_evaluation\nfrom bertserini.experiments.eval.evaluate_v1_drcd import evaluation as drcd_evaluation\nfrom bertserini.experiments.eval.evaluate_v1_cmrc import evaluate as cmrc_evaluation\n\n\ndef get_score_with_results(eval_data, predictions, mu, dataset):\n answers = {}\n score = {}\n\n for predict_id, predict in enumerate(predictions):\n\n try:\n if dataset == \"trivia\":\n id_ = predict[0]['id'].split(\"--\")[0]\n else:\n id_ = predict[0]['id']\n except IndexError as e:\n pass\n\n if not predict:\n continue\n\n best_answer = choose_best_answer(\n predict,\n weighted_score,\n 1 - mu, mu)\n\n answers[id_] = best_answer['answer'].replace(\"##\", \"\")\n\n score[id_] = best_answer[\"total_score\"]\n\n json.dump(answers, open(\"tmp.answer\", 'w'))\n json.dump(score, open(\"tmp.score\", 'w'))\n\n if dataset == \"squad\":\n eval_result = squad_evaluation(eval_data, \"tmp.answer\")\n elif dataset == \"cmrc\":\n eval_result = cmrc_evaluation(eval_data, \"tmp.answer\")\n eval_result = {\"f1_score\": eval_result[0],\n \"exact_match\": eval_result[1],\n \"total_count\": eval_result[2],\n \"skip_count\": eval_result[3]}\n elif args.dataset == \"drcd\":\n eval_result = drcd_evaluation(eval_data, \"tmp.answer\")\n else:\n eval_result = squad_evaluation(eval_data, \"tmp.answer\")\n\n print(\"mu:{}, result:{}\".format(mu, eval_result))\n return eval_result, answers\n\n\ndef get_best_mu_with_scores(eval_data, predictions, mu_range, dataset, output_path, metric=\"f1\"): \n # metric = \"f1\" or \"exact_match\"\n score_test = {}\n best_mu = 0\n best_score = 0\n for mu in mu_range:\n eval_result, answers = get_score_with_results(eval_data, predictions, mu, dataset)\n score_test[mu] = eval_result\n if eval_result[metric] > best_score:\n best_mu = mu\n best_score = eval_result[metric]\n json.dump(answers, open(output_path + \"/prediction.json\", 'w'))\n\n json.dump(score_test, open(output_path + \"/score.json\", 'w'))\n return best_mu, score_test[best_mu]\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--eval_data', type=str, default=\"\",\n help='Path to question data')\n parser.add_argument('--search_file', type=str, default=\"\",\n help='Path to bert output')\n parser.add_argument(\"--para_num\", type=int, default=100,\n help=\"top k paragraphs to eval\")\n parser.add_argument(\"--dataset\", type=str, default=\"squad\",\n help=\"\")\n parser.add_argument(\"--output_path\", type=str, default=\"\",\n help=\"\")\n parser.add_argument(\"--mu_min\", type=float, default=0)\n parser.add_argument(\"--mu_max\", type=float, default=1)\n parser.add_argument(\"--mu_interval\", type=float, default=0.1)\n args = parser.parse_args()\n print(args)\n\n predictions = json.load(open(args.search_file, 'r'))\n\n answers = {}\n cover = 0\n print(\"Total predictions:\", len(predictions))\n\n predictions = [p[:args.para_num] for p in predictions]\n\n print(get_best_mu_with_scores(args.eval_data, predictions,\n np.arange(args.mu_min, args.mu_max, args.mu_interval),\n args.dataset, args.output_path))\n"
] | [
[
"numpy.arange"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
barentsen/lightkurve | [
"5b1693832bc509e42742d1b6f20224d131e62d8c"
] | [
"lightkurve/collections.py"
] | [
"\"\"\"Defines collections of data products.\"\"\"\nimport logging\nimport warnings\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom astropy.table import vstack\n\nfrom . import MPLSTYLE\nfrom .targetpixelfile import TargetPixelFile\n\nlog = logging.getLogger(__name__)\n\n__all__ = ['LightCurveCollection', 'TargetPixelFileCollection']\n\n\nclass Collection(object):\n \"\"\"Base class for `LightCurveCollection` and `TargetPixelFileCollection`.\n\n Attributes\n ----------\n data: array-like\n List of data objects.\n \"\"\"\n def __init__(self, data):\n self.data = data\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, index):\n return self.data[index]\n\n def __setitem__(self, index, obj):\n self.data[index] = obj\n\n def append(self, obj):\n \"\"\"Appends a new object to the collection.\n\n Parameters\n ----------\n obj : object\n Typically a LightCurve or TargetPixelFile object\n \"\"\"\n self.data.append(obj)\n\n def __repr__(self):\n result = \"{} of {} objects:\\n\".format(self.__class__.__name__, len(self.data))\n if (isinstance(self[0], TargetPixelFile)):\n labels = np.asarray([tpf.targetid for tpf in self])\n else:\n labels = np.asarray([lc.meta.get('label') for lc in self])\n\n try:\n unique_labels = np.sort(np.unique(labels))\n except TypeError:\n unique_labels = [None]\n\n for idx, targetid in enumerate(unique_labels):\n jdxs = np.where(labels == targetid)[0]\n if not hasattr(jdxs, '__iter__'):\n jdxs = [jdxs]\n\n if hasattr(self[jdxs[0]], 'mission'):\n mission = self[jdxs[0]].mission\n if mission == 'Kepler':\n subtype = 'Quarters'\n elif mission == 'K2':\n subtype = 'Campaigns'\n elif mission == 'TESS':\n subtype = 'Sectors'\n else:\n subtype = None\n else:\n subtype = None\n objstr = str(type(self[0]))[8:-2].split('.')[-1]\n title = '\\t{} ({} {}s) {}: '.format(targetid, len(jdxs), objstr, subtype)\n result += title\n if subtype is not None:\n result += ','.join(['{}'.format(getattr(self[jdx], subtype[:-1].lower())) for jdx in jdxs])\n else:\n result += ','.join(['{}'.format(i) for i in np.arange(len(jdxs))])\n result += '\\n'\n return result\n\n\nclass LightCurveCollection(Collection):\n \"\"\"Class to hold a collection of LightCurve objects.\n\n Attributes\n ----------\n lightcurves : array-like\n List of LightCurve objects.\n \"\"\"\n def __init__(self, lightcurves):\n super(LightCurveCollection, self).__init__(lightcurves)\n\n\n def stitch(self, corrector_func=lambda x:x.normalize()):\n \"\"\" Stitch all light curves in the collection into a single lk.LightCurve\n\n Any function passed to `corrector_func` will be applied to each light curve\n before stitching. For example, passing \"lambda x: x.normalize().flatten()\"\n will normalize and flatten each light curve before stitching.\n\n Parameters\n ----------\n corrector_func : function\n Function that accepts and returns a `~lightkurve.lightcurve.LightCurve`.\n This function is applied to each light curve in the collection\n prior to stitching. The default is to normalize each light curve.\n\n Returns\n -------\n lc : `~lightkurve.lightcurve.LightCurve`\n Stitched light curve.\n \"\"\"\n if corrector_func is None:\n corrector_func = lambda x: x\n lcs = [corrector_func(lc) for lc in self]\n # Need `join_type='inner'` until AstroPy supports masked Quantities\n return vstack(lcs, join_type='inner', metadata_conflicts='silent')\n\n def plot(self, ax=None, offset=0., **kwargs) -> matplotlib.axes.Axes:\n \"\"\"Plots all light curves in the collection on a single plot.\n\n Parameters\n ----------\n ax : `~matplotlib.axes.Axes`\n A matplotlib axes object to plot into. If no axes is provided,\n a new one will be created.\n offset : float\n Offset to add to targets with different labels, to prevent light\n curves from being plotted on top of each other. For example, if\n the collection contains light curves with unique labels \"A\", \"B\",\n and \"C\", light curves \"A\" will have `0*offset` added to their flux,\n light curves \"B\" will have `1*offset` offset added, and \"C\" will\n have `2*offset` added.\n **kwargs : dict\n Dictionary of arguments to be passed to `LightCurve.plot`.\n\n Returns\n -------\n ax : `~matplotlib.axes.Axes`\n The matplotlib axes object.\n \"\"\"\n with plt.style.context(MPLSTYLE):\n if ax is None:\n _, ax = plt.subplots()\n for kwarg in ['c', 'color', 'label']:\n if kwarg in kwargs:\n kwargs.pop(kwarg)\n\n labels = np.asarray([lc.meta.get('label') for lc in self])\n try:\n unique_labels = np.sort(np.unique(labels))\n except TypeError: # sorting will fail if labels includes None\n unique_labels = [None]\n\n for idx, targetid in enumerate(unique_labels):\n jdxs = np.where(labels == targetid)[0]\n for jdx in np.atleast_1d(jdxs):\n if jdx != jdxs[0]: # Avoid multiple labels for same object\n kwargs['label'] = ''\n self[jdx].plot(ax=ax, c=f'C{idx}', offset=idx*offset, **kwargs)\n return ax\n\n\nclass TargetPixelFileCollection(Collection):\n \"\"\"Class to hold a collection of `~lightkurve.targetpixelfile.TargetPixelFile` objects.\n\n Parameters\n ----------\n tpfs : list or iterable\n List of `~lightkurve.targetpixelfile.TargetPixelFile` objects.\n \"\"\"\n def __init__(self, tpfs):\n super(TargetPixelFileCollection, self).__init__(tpfs)\n\n def plot(self, ax=None):\n \"\"\"Individually plots all TargetPixelFile objects in a single\n matplotlib axes object.\n\n Parameters\n ----------\n ax : `~matplotlib.axes.Axes`\n A matplotlib axes object to plot into. If no axes is provided,\n a new one will be created.\n\n Returns\n -------\n ax : `~matplotlib.axes.Axes`\n The matplotlib axes object.\n \"\"\"\n if ax is None:\n _, ax = plt.subplots(len(self.data), 1,\n figsize=(7, (7*len(self.data))))\n if len(self.data) == 1:\n self.data[0].plot(ax=ax)\n else:\n for i, tpf in enumerate(self.data):\n tpf.plot(ax=ax[i])\n return ax\n"
] | [
[
"numpy.unique",
"numpy.asarray",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.style.context",
"numpy.atleast_1d",
"numpy.where"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Hao-Kailong/Numerical-Information-Extraction | [
"b67487aabd64ed3852e564a1d14b7a244dcbbc0a"
] | [
"code/Bert/run_squad.py"
] | [
"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Run BERT on SQuAD 1.1 and SQuAD 2.0.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport json\nimport math\nimport os\nimport random\nfrom . import modeling\nfrom . import optimization\nfrom . import tokenization\nimport six\nimport tensorflow as tf\n\nflags = tf.flags\n\nFLAGS = flags.FLAGS\n\n## Required parameters\nflags.DEFINE_string(\n \"bert_config_file\", None,\n \"The config json file corresponding to the pre-trained BERT model. \"\n \"This specifies the model architecture.\")\n\nflags.DEFINE_string(\"vocab_file\", None,\n \"The vocabulary file that the BERT model was trained on.\")\n\nflags.DEFINE_string(\n \"output_dir\", None,\n \"The output directory where the model checkpoints will be written.\")\n\n## Other parameters\nflags.DEFINE_string(\"train_file\", None,\n \"SQuAD json for training. E.g., train-v1.1.json\")\n\nflags.DEFINE_string(\n \"predict_file\", None,\n \"SQuAD json for predictions. E.g., dev-v1.1.json or test-v1.1.json\")\n\nflags.DEFINE_string(\n \"init_checkpoint\", None,\n \"Initial checkpoint (usually from a pre-trained BERT model).\")\n\nflags.DEFINE_bool(\n \"do_lower_case\", True,\n \"Whether to lower case the input text. Should be True for uncased \"\n \"models and False for cased models.\")\n\nflags.DEFINE_integer(\n \"max_seq_length\", 384,\n \"The maximum total input sequence length after WordPiece tokenization. \"\n \"Sequences longer than this will be truncated, and sequences shorter \"\n \"than this will be padded.\")\n\nflags.DEFINE_integer(\n \"doc_stride\", 128,\n \"When splitting up a long document into chunks, how much stride to \"\n \"take between chunks.\")\n\nflags.DEFINE_integer(\n \"max_query_length\", 64,\n \"The maximum number of tokens for the question. Questions longer than \"\n \"this will be truncated to this length.\")\n\nflags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\")\n\nflags.DEFINE_bool(\"do_predict\", False, \"Whether to run eval on the dev set.\")\n\nflags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for training.\")\n\nflags.DEFINE_integer(\"predict_batch_size\", 8,\n \"Total batch size for predictions.\")\n\nflags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate for Adam.\")\n\nflags.DEFINE_float(\"num_train_epochs\", 3.0,\n \"Total number of training epochs to perform.\")\n\nflags.DEFINE_float(\n \"warmup_proportion\", 0.1,\n \"Proportion of training to perform linear learning rate warmup for. \"\n \"E.g., 0.1 = 10% of training.\")\n\nflags.DEFINE_integer(\"save_checkpoints_steps\", 1000,\n \"How often to save the model checkpoint.\")\n\nflags.DEFINE_integer(\"iterations_per_loop\", 1000,\n \"How many steps to make in each estimator call.\")\n\nflags.DEFINE_integer(\n \"n_best_size\", 20,\n \"The total number of n-best predictions to generate in the \"\n \"nbest_predictions.json output file.\")\n\nflags.DEFINE_integer(\n \"max_answer_length\", 30,\n \"The maximum length of an answer that can be generated. This is needed \"\n \"because the start and end predictions are not conditioned on one another.\")\n\nflags.DEFINE_bool(\"use_tpu\", False, \"Whether to use TPU or GPU/CPU.\")\n\ntf.flags.DEFINE_string(\n \"tpu_name\", None,\n \"The Cloud TPU to use for training. This should be either the name \"\n \"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 \"\n \"url.\")\n\ntf.flags.DEFINE_string(\n \"tpu_zone\", None,\n \"[Optional] GCE zone where the Cloud TPU is located in. If not \"\n \"specified, we will attempt to automatically detect the GCE project from \"\n \"metadata.\")\n\ntf.flags.DEFINE_string(\n \"gcp_project\", None,\n \"[Optional] Project name for the Cloud TPU-enabled project. If not \"\n \"specified, we will attempt to automatically detect the GCE project from \"\n \"metadata.\")\n\ntf.flags.DEFINE_string(\"master\", None, \"[Optional] TensorFlow master URL.\")\n\nflags.DEFINE_integer(\n \"num_tpu_cores\", 8,\n \"Only used if `use_tpu` is True. Total number of TPU cores to use.\")\n\nflags.DEFINE_bool(\n \"verbose_logging\", False,\n \"If true, all of the warnings related to data processing will be printed. \"\n \"A number of warnings are expected for a normal SQuAD evaluation.\")\n\nflags.DEFINE_bool(\n \"version_2_with_negative\", False,\n \"If true, the SQuAD examples contain some that do not have an answer.\")\n\nflags.DEFINE_float(\n \"null_score_diff_threshold\", 0.0,\n \"If null_score - best_non_null is greater than the threshold predict null.\")\n\n\nclass SquadExample(object):\n \"\"\"A single training/test example for simple sequence classification.\n\n For examples without an answer, the start and end position are -1.\n \"\"\"\n\n def __init__(self,\n qas_id,\n question_text,\n doc_tokens,\n orig_answer_text=None,\n start_position=None,\n end_position=None,\n is_impossible=False):\n self.qas_id = qas_id\n self.question_text = question_text\n self.doc_tokens = doc_tokens\n self.orig_answer_text = orig_answer_text\n self.start_position = start_position\n self.end_position = end_position\n self.is_impossible = is_impossible\n\n def __str__(self):\n return self.__repr__()\n\n def __repr__(self):\n s = \"\"\n s += \"qas_id: %s\" % (tokenization.printable_text(self.qas_id))\n s += \", question_text: %s\" % (\n tokenization.printable_text(self.question_text))\n s += \", doc_tokens: [%s]\" % (\" \".join(self.doc_tokens))\n if self.start_position:\n s += \", start_position: %d\" % (self.start_position)\n if self.start_position:\n s += \", end_position: %d\" % (self.end_position)\n if self.start_position:\n s += \", is_impossible: %r\" % (self.is_impossible)\n return s\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self,\n unique_id,\n example_index,\n doc_span_index,\n tokens,\n token_to_orig_map,\n token_is_max_context,\n input_ids,\n input_mask,\n segment_ids,\n start_position=None,\n end_position=None,\n is_impossible=None):\n self.unique_id = unique_id\n self.example_index = example_index\n self.doc_span_index = doc_span_index\n self.tokens = tokens\n self.token_to_orig_map = token_to_orig_map\n self.token_is_max_context = token_is_max_context\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.start_position = start_position\n self.end_position = end_position\n self.is_impossible = is_impossible\n\n\ndef read_squad_examples(input_file, is_training):\n \"\"\"Read a SQuAD json file into a list of SquadExample.\"\"\"\n with tf.gfile.Open(input_file, \"r\") as reader:\n input_data = json.load(reader)[\"data\"]\n\n def is_whitespace(c):\n if c == \" \" or c == \"\\t\" or c == \"\\r\" or c == \"\\n\" or ord(c) == 0x202F:\n return True\n return False\n\n examples = []\n for entry in input_data:\n for paragraph in entry[\"paragraphs\"]:\n paragraph_text = paragraph[\"context\"]\n doc_tokens = []\n char_to_word_offset = []\n prev_is_whitespace = True\n for c in paragraph_text:\n if is_whitespace(c):\n prev_is_whitespace = True\n else:\n if prev_is_whitespace:\n doc_tokens.append(c)\n else:\n doc_tokens[-1] += c\n prev_is_whitespace = False\n char_to_word_offset.append(len(doc_tokens) - 1)\n\n for qa in paragraph[\"qas\"]:\n qas_id = qa[\"id\"]\n question_text = qa[\"question\"]\n start_position = None\n end_position = None\n orig_answer_text = None\n is_impossible = False\n if is_training:\n\n if FLAGS.version_2_with_negative:\n is_impossible = qa[\"is_impossible\"]\n if (len(qa[\"answers\"]) != 1) and (not is_impossible):\n raise ValueError(\n \"For training, each question should have exactly 1 answer.\")\n if not is_impossible:\n answer = qa[\"answers\"][0]\n orig_answer_text = answer[\"text\"]\n answer_offset = answer[\"answer_start\"]\n answer_length = len(orig_answer_text)\n start_position = char_to_word_offset[answer_offset]\n end_position = char_to_word_offset[answer_offset + answer_length -\n 1]\n # Only add answers where the text can be exactly recovered from the\n # document. If this CAN'T happen it's likely due to weird Unicode\n # stuff so we will just skip the example.\n #\n # Note that this means for training mode, every example is NOT\n # guaranteed to be preserved.\n actual_text = \" \".join(\n doc_tokens[start_position:(end_position + 1)])\n cleaned_answer_text = \" \".join(\n tokenization.whitespace_tokenize(orig_answer_text))\n if actual_text.find(cleaned_answer_text) == -1:\n tf.logging.warning(\"Could not find answer: '%s' vs. '%s'\",\n actual_text, cleaned_answer_text)\n continue\n else:\n start_position = -1\n end_position = -1\n orig_answer_text = \"\"\n\n example = SquadExample(\n qas_id=qas_id,\n question_text=question_text,\n doc_tokens=doc_tokens,\n orig_answer_text=orig_answer_text,\n start_position=start_position,\n end_position=end_position,\n is_impossible=is_impossible)\n examples.append(example)\n\n return examples\n\n\ndef convert_examples_to_features(examples, tokenizer, max_seq_length,\n doc_stride, max_query_length, is_training,\n output_fn):\n \"\"\"Loads a data file into a list of `InputBatch`s.\"\"\"\n\n unique_id = 1000000000\n\n for (example_index, example) in enumerate(examples):\n query_tokens = tokenizer.tokenize(example.question_text)\n\n if len(query_tokens) > max_query_length:\n query_tokens = query_tokens[0:max_query_length]\n\n tok_to_orig_index = []\n orig_to_tok_index = []\n all_doc_tokens = []\n for (i, token) in enumerate(example.doc_tokens):\n orig_to_tok_index.append(len(all_doc_tokens))\n sub_tokens = tokenizer.tokenize(token)\n for sub_token in sub_tokens:\n tok_to_orig_index.append(i)\n all_doc_tokens.append(sub_token)\n\n tok_start_position = None\n tok_end_position = None\n if is_training and example.is_impossible:\n tok_start_position = -1\n tok_end_position = -1\n if is_training and not example.is_impossible:\n tok_start_position = orig_to_tok_index[example.start_position]\n if example.end_position < len(example.doc_tokens) - 1:\n tok_end_position = orig_to_tok_index[example.end_position + 1] - 1\n else:\n tok_end_position = len(all_doc_tokens) - 1\n (tok_start_position, tok_end_position) = _improve_answer_span(\n all_doc_tokens, tok_start_position, tok_end_position, tokenizer,\n example.orig_answer_text)\n\n # The -3 accounts for [CLS], [SEP] and [SEP]\n max_tokens_for_doc = max_seq_length - len(query_tokens) - 3\n\n # We can have documents that are longer than the maximum sequence length.\n # To deal with this we do a sliding window approach, where we take chunks\n # of the up to our max length with a stride of `doc_stride`.\n _DocSpan = collections.namedtuple( # pylint: disable=invalid-name\n \"DocSpan\", [\"start\", \"length\"])\n doc_spans = []\n start_offset = 0\n while start_offset < len(all_doc_tokens):\n length = len(all_doc_tokens) - start_offset\n if length > max_tokens_for_doc:\n length = max_tokens_for_doc\n doc_spans.append(_DocSpan(start=start_offset, length=length))\n if start_offset + length == len(all_doc_tokens):\n break\n start_offset += min(length, doc_stride)\n\n for (doc_span_index, doc_span) in enumerate(doc_spans):\n tokens = []\n token_to_orig_map = {}\n token_is_max_context = {}\n segment_ids = []\n tokens.append(\"[CLS]\")\n segment_ids.append(0)\n for token in query_tokens:\n tokens.append(token)\n segment_ids.append(0)\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n\n for i in range(doc_span.length):\n split_token_index = doc_span.start + i\n token_to_orig_map[len(tokens)] = tok_to_orig_index[split_token_index]\n\n is_max_context = _check_is_max_context(doc_spans, doc_span_index,\n split_token_index)\n token_is_max_context[len(tokens)] = is_max_context\n tokens.append(all_doc_tokens[split_token_index])\n segment_ids.append(1)\n tokens.append(\"[SEP]\")\n segment_ids.append(1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n while len(input_ids) < max_seq_length:\n input_ids.append(0)\n input_mask.append(0)\n segment_ids.append(0)\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n\n start_position = None\n end_position = None\n if is_training and not example.is_impossible:\n # For training, if our document chunk does not contain an annotation\n # we throw it out, since there is nothing to predict.\n doc_start = doc_span.start\n doc_end = doc_span.start + doc_span.length - 1\n out_of_span = False\n if not (tok_start_position >= doc_start and\n tok_end_position <= doc_end):\n out_of_span = True\n if out_of_span:\n start_position = 0\n end_position = 0\n else:\n doc_offset = len(query_tokens) + 2\n start_position = tok_start_position - doc_start + doc_offset\n end_position = tok_end_position - doc_start + doc_offset\n\n if is_training and example.is_impossible:\n start_position = 0\n end_position = 0\n\n if example_index < 20:\n tf.logging.info(\"*** Example ***\")\n tf.logging.info(\"unique_id: %s\" % (unique_id))\n tf.logging.info(\"example_index: %s\" % (example_index))\n tf.logging.info(\"doc_span_index: %s\" % (doc_span_index))\n tf.logging.info(\"tokens: %s\" % \" \".join(\n [tokenization.printable_text(x) for x in tokens]))\n tf.logging.info(\"token_to_orig_map: %s\" % \" \".join(\n [\"%d:%d\" % (x, y) for (x, y) in six.iteritems(token_to_orig_map)]))\n tf.logging.info(\"token_is_max_context: %s\" % \" \".join([\n \"%d:%s\" % (x, y) for (x, y) in six.iteritems(token_is_max_context)\n ]))\n tf.logging.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\n tf.logging.info(\n \"input_mask: %s\" % \" \".join([str(x) for x in input_mask]))\n tf.logging.info(\n \"segment_ids: %s\" % \" \".join([str(x) for x in segment_ids]))\n if is_training and example.is_impossible:\n tf.logging.info(\"impossible example\")\n if is_training and not example.is_impossible:\n answer_text = \" \".join(tokens[start_position:(end_position + 1)])\n tf.logging.info(\"start_position: %d\" % (start_position))\n tf.logging.info(\"end_position: %d\" % (end_position))\n tf.logging.info(\n \"answer: %s\" % (tokenization.printable_text(answer_text)))\n\n feature = InputFeatures(\n unique_id=unique_id,\n example_index=example_index,\n doc_span_index=doc_span_index,\n tokens=tokens,\n token_to_orig_map=token_to_orig_map,\n token_is_max_context=token_is_max_context,\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n start_position=start_position,\n end_position=end_position,\n is_impossible=example.is_impossible)\n\n # Run callback\n output_fn(feature)\n\n unique_id += 1\n\n\ndef _improve_answer_span(doc_tokens, input_start, input_end, tokenizer,\n orig_answer_text):\n \"\"\"Returns tokenized answer spans that better match the annotated answer.\"\"\"\n\n # The SQuAD annotations are character based. We first project them to\n # whitespace-tokenized words. But then after WordPiece tokenization, we can\n # often find a \"better match\". For example:\n #\n # Question: What year was John Smith born?\n # Context: The leader was John Smith (1895-1943).\n # Answer: 1895\n #\n # The original whitespace-tokenized answer will be \"(1895-1943).\". However\n # after tokenization, our tokens will be \"( 1895 - 1943 ) .\". So we can match\n # the exact answer, 1895.\n #\n # However, this is not always possible. Consider the following:\n #\n # Question: What country is the top exporter of electornics?\n # Context: The Japanese electronics industry is the lagest in the world.\n # Answer: Japan\n #\n # In this case, the annotator chose \"Japan\" as a character sub-span of\n # the word \"Japanese\". Since our WordPiece tokenizer does not split\n # \"Japanese\", we just use \"Japanese\" as the annotation. This is fairly rare\n # in SQuAD, but does happen.\n tok_answer_text = \" \".join(tokenizer.tokenize(orig_answer_text))\n\n for new_start in range(input_start, input_end + 1):\n for new_end in range(input_end, new_start - 1, -1):\n text_span = \" \".join(doc_tokens[new_start:(new_end + 1)])\n if text_span == tok_answer_text:\n return (new_start, new_end)\n\n return (input_start, input_end)\n\n\ndef _check_is_max_context(doc_spans, cur_span_index, position):\n \"\"\"Check if this is the 'max context' doc span for the token.\"\"\"\n\n # Because of the sliding window approach taken to scoring documents, a single\n # token can appear in multiple documents. E.g.\n # Doc: the man went to the store and bought a gallon of milk\n # Span A: the man went to the\n # Span B: to the store and bought\n # Span C: and bought a gallon of\n # ...\n #\n # Now the word 'bought' will have two scores from spans B and C. We only\n # want to consider the score with \"maximum context\", which we define as\n # the *minimum* of its left and right context (the *sum* of left and\n # right context will always be the same, of course).\n #\n # In the example the maximum context for 'bought' would be span C since\n # it has 1 left context and 3 right context, while span B has 4 left context\n # and 0 right context.\n best_score = None\n best_span_index = None\n for (span_index, doc_span) in enumerate(doc_spans):\n end = doc_span.start + doc_span.length - 1\n if position < doc_span.start:\n continue\n if position > end:\n continue\n num_left_context = position - doc_span.start\n num_right_context = end - position\n score = min(num_left_context, num_right_context) + 0.01 * doc_span.length\n if best_score is None or score > best_score:\n best_score = score\n best_span_index = span_index\n\n return cur_span_index == best_span_index\n\n\ndef create_model(bert_config, is_training, input_ids, input_mask, segment_ids,\n use_one_hot_embeddings):\n \"\"\"Creates a classification model.\"\"\"\n model = modeling.BertModel(\n config=bert_config,\n is_training=is_training,\n input_ids=input_ids,\n input_mask=input_mask,\n token_type_ids=segment_ids,\n use_one_hot_embeddings=use_one_hot_embeddings)\n\n final_hidden = model.get_sequence_output()\n\n final_hidden_shape = modeling.get_shape_list(final_hidden, expected_rank=3)\n batch_size = final_hidden_shape[0]\n seq_length = final_hidden_shape[1]\n hidden_size = final_hidden_shape[2]\n\n output_weights = tf.get_variable(\n \"cls/squad/output_weights\", [2, hidden_size],\n initializer=tf.truncated_normal_initializer(stddev=0.02))\n\n output_bias = tf.get_variable(\n \"cls/squad/output_bias\", [2], initializer=tf.zeros_initializer())\n\n final_hidden_matrix = tf.reshape(final_hidden,\n [batch_size * seq_length, hidden_size])\n logits = tf.matmul(final_hidden_matrix, output_weights, transpose_b=True)\n logits = tf.nn.bias_add(logits, output_bias)\n\n logits = tf.reshape(logits, [batch_size, seq_length, 2])\n logits = tf.transpose(logits, [2, 0, 1])\n\n unstacked_logits = tf.unstack(logits, axis=0)\n\n (start_logits, end_logits) = (unstacked_logits[0], unstacked_logits[1])\n\n return (start_logits, end_logits)\n\n\ndef model_fn_builder(bert_config, init_checkpoint, learning_rate,\n num_train_steps, num_warmup_steps, use_tpu,\n use_one_hot_embeddings):\n \"\"\"Returns `model_fn` closure for TPUEstimator.\"\"\"\n\n def model_fn(features, labels, mode, params): # pylint: disable=unused-argument\n \"\"\"The `model_fn` for TPUEstimator.\"\"\"\n\n tf.logging.info(\"*** Features ***\")\n for name in sorted(features.keys()):\n tf.logging.info(\" name = %s, shape = %s\" % (name, features[name].shape))\n\n unique_ids = features[\"unique_ids\"]\n input_ids = features[\"input_ids\"]\n input_mask = features[\"input_mask\"]\n segment_ids = features[\"segment_ids\"]\n\n is_training = (mode == tf.estimator.ModeKeys.TRAIN)\n\n (start_logits, end_logits) = create_model(\n bert_config=bert_config,\n is_training=is_training,\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n use_one_hot_embeddings=use_one_hot_embeddings)\n\n tvars = tf.trainable_variables()\n\n initialized_variable_names = {}\n scaffold_fn = None\n if init_checkpoint:\n (assignment_map, initialized_variable_names\n ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)\n if use_tpu:\n\n def tpu_scaffold():\n tf.train.init_from_checkpoint(init_checkpoint, assignment_map)\n return tf.train.Scaffold()\n\n scaffold_fn = tpu_scaffold\n else:\n tf.train.init_from_checkpoint(init_checkpoint, assignment_map)\n\n tf.logging.info(\"**** Trainable Variables ****\")\n for var in tvars:\n init_string = \"\"\n if var.name in initialized_variable_names:\n init_string = \", *INIT_FROM_CKPT*\"\n tf.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape,\n init_string)\n\n output_spec = None\n if mode == tf.estimator.ModeKeys.TRAIN:\n seq_length = modeling.get_shape_list(input_ids)[1]\n\n def compute_loss(logits, positions):\n one_hot_positions = tf.one_hot(\n positions, depth=seq_length, dtype=tf.float32)\n log_probs = tf.nn.log_softmax(logits, axis=-1)\n loss = -tf.reduce_mean(\n tf.reduce_sum(one_hot_positions * log_probs, axis=-1))\n return loss\n\n start_positions = features[\"start_positions\"]\n end_positions = features[\"end_positions\"]\n\n start_loss = compute_loss(start_logits, start_positions)\n end_loss = compute_loss(end_logits, end_positions)\n\n total_loss = (start_loss + end_loss) / 2.0\n\n train_op = optimization.create_optimizer(\n total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)\n\n output_spec = tf.contrib.tpu.TPUEstimatorSpec(\n mode=mode,\n loss=total_loss,\n train_op=train_op,\n scaffold_fn=scaffold_fn)\n elif mode == tf.estimator.ModeKeys.PREDICT:\n predictions = {\n \"unique_ids\": unique_ids,\n \"start_logits\": start_logits,\n \"end_logits\": end_logits,\n }\n output_spec = tf.contrib.tpu.TPUEstimatorSpec(\n mode=mode, predictions=predictions, scaffold_fn=scaffold_fn)\n else:\n raise ValueError(\n \"Only TRAIN and PREDICT modes are supported: %s\" % (mode))\n\n return output_spec\n\n return model_fn\n\n\ndef input_fn_builder(input_file, seq_length, is_training, drop_remainder):\n \"\"\"Creates an `input_fn` closure to be passed to TPUEstimator.\"\"\"\n\n name_to_features = {\n \"unique_ids\": tf.FixedLenFeature([], tf.int64),\n \"input_ids\": tf.FixedLenFeature([seq_length], tf.int64),\n \"input_mask\": tf.FixedLenFeature([seq_length], tf.int64),\n \"segment_ids\": tf.FixedLenFeature([seq_length], tf.int64),\n }\n\n if is_training:\n name_to_features[\"start_positions\"] = tf.FixedLenFeature([], tf.int64)\n name_to_features[\"end_positions\"] = tf.FixedLenFeature([], tf.int64)\n\n def _decode_record(record, name_to_features):\n \"\"\"Decodes a record to a TensorFlow example.\"\"\"\n example = tf.parse_single_example(record, name_to_features)\n\n # tf.Example only supports tf.int64, but the TPU only supports tf.int32.\n # So cast all int64 to int32.\n for name in list(example.keys()):\n t = example[name]\n if t.dtype == tf.int64:\n t = tf.to_int32(t)\n example[name] = t\n\n return example\n\n def input_fn(params):\n \"\"\"The actual input function.\"\"\"\n batch_size = params[\"batch_size\"]\n\n # For training, we want a lot of parallel reading and shuffling.\n # For eval, we want no shuffling and parallel reading doesn't matter.\n d = tf.data.TFRecordDataset(input_file)\n if is_training:\n d = d.repeat()\n d = d.shuffle(buffer_size=100)\n\n d = d.apply(\n tf.contrib.data.map_and_batch(\n lambda record: _decode_record(record, name_to_features),\n batch_size=batch_size,\n drop_remainder=drop_remainder))\n\n return d\n\n return input_fn\n\n\nRawResult = collections.namedtuple(\"RawResult\",\n [\"unique_id\", \"start_logits\", \"end_logits\"])\n\n\ndef write_predictions(all_examples, all_features, all_results, n_best_size,\n max_answer_length, do_lower_case, output_prediction_file,\n output_nbest_file, output_null_log_odds_file):\n \"\"\"Write final predictions to the json file and log-odds of null if needed.\"\"\"\n tf.logging.info(\"Writing predictions to: %s\" % (output_prediction_file))\n tf.logging.info(\"Writing nbest to: %s\" % (output_nbest_file))\n\n example_index_to_features = collections.defaultdict(list)\n for feature in all_features:\n example_index_to_features[feature.example_index].append(feature)\n\n unique_id_to_result = {}\n for result in all_results:\n unique_id_to_result[result.unique_id] = result\n\n _PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name\n \"PrelimPrediction\",\n [\"feature_index\", \"start_index\", \"end_index\", \"start_logit\", \"end_logit\"])\n\n all_predictions = collections.OrderedDict()\n all_nbest_json = collections.OrderedDict()\n scores_diff_json = collections.OrderedDict()\n\n for (example_index, example) in enumerate(all_examples):\n features = example_index_to_features[example_index]\n\n prelim_predictions = []\n # keep track of the minimum score of null start+end of position 0\n score_null = 1000000 # large and positive\n min_null_feature_index = 0 # the paragraph slice with min mull score\n null_start_logit = 0 # the start logit at the slice with min null score\n null_end_logit = 0 # the end logit at the slice with min null score\n for (feature_index, feature) in enumerate(features):\n result = unique_id_to_result[feature.unique_id]\n start_indexes = _get_best_indexes(result.start_logits, n_best_size)\n end_indexes = _get_best_indexes(result.end_logits, n_best_size)\n # if we could have irrelevant answers, get the min score of irrelevant\n if FLAGS.version_2_with_negative:\n feature_null_score = result.start_logits[0] + result.end_logits[0]\n if feature_null_score < score_null:\n score_null = feature_null_score\n min_null_feature_index = feature_index\n null_start_logit = result.start_logits[0]\n null_end_logit = result.end_logits[0]\n for start_index in start_indexes:\n for end_index in end_indexes:\n # We could hypothetically create invalid predictions, e.g., predict\n # that the start of the span is in the question. We throw out all\n # invalid predictions.\n if start_index >= len(feature.tokens):\n continue\n if end_index >= len(feature.tokens):\n continue\n if start_index not in feature.token_to_orig_map:\n continue\n if end_index not in feature.token_to_orig_map:\n continue\n if not feature.token_is_max_context.get(start_index, False):\n continue\n if end_index < start_index:\n continue\n length = end_index - start_index + 1\n if length > max_answer_length:\n continue\n prelim_predictions.append(\n _PrelimPrediction(\n feature_index=feature_index,\n start_index=start_index,\n end_index=end_index,\n start_logit=result.start_logits[start_index],\n end_logit=result.end_logits[end_index]))\n\n if FLAGS.version_2_with_negative:\n prelim_predictions.append(\n _PrelimPrediction(\n feature_index=min_null_feature_index,\n start_index=0,\n end_index=0,\n start_logit=null_start_logit,\n end_logit=null_end_logit))\n prelim_predictions = sorted(\n prelim_predictions,\n key=lambda x: (x.start_logit + x.end_logit),\n reverse=True)\n\n _NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name\n \"NbestPrediction\", [\"text\", \"start_logit\", \"end_logit\"])\n\n seen_predictions = {}\n nbest = []\n for pred in prelim_predictions:\n if len(nbest) >= n_best_size:\n break\n feature = features[pred.feature_index]\n if pred.start_index > 0: # this is a non-null prediction\n tok_tokens = feature.tokens[pred.start_index:(pred.end_index + 1)]\n orig_doc_start = feature.token_to_orig_map[pred.start_index]\n orig_doc_end = feature.token_to_orig_map[pred.end_index]\n orig_tokens = example.doc_tokens[orig_doc_start:(orig_doc_end + 1)]\n tok_text = \" \".join(tok_tokens)\n\n # De-tokenize WordPieces that have been split off.\n tok_text = tok_text.replace(\" ##\", \"\")\n tok_text = tok_text.replace(\"##\", \"\")\n\n # Clean whitespace\n tok_text = tok_text.strip()\n tok_text = \" \".join(tok_text.split())\n orig_text = \" \".join(orig_tokens)\n\n final_text = get_final_text(tok_text, orig_text, do_lower_case)\n if final_text in seen_predictions:\n continue\n\n seen_predictions[final_text] = True\n else:\n final_text = \"\"\n seen_predictions[final_text] = True\n\n nbest.append(\n _NbestPrediction(\n text=final_text,\n start_logit=pred.start_logit,\n end_logit=pred.end_logit))\n\n # if we didn't inlude the empty option in the n-best, inlcude it\n if FLAGS.version_2_with_negative:\n if \"\" not in seen_predictions:\n nbest.append(\n _NbestPrediction(\n text=\"\", start_logit=null_start_logit,\n end_logit=null_end_logit))\n # In very rare edge cases we could have no valid predictions. So we\n # just create a nonce prediction in this case to avoid failure.\n if not nbest:\n nbest.append(\n _NbestPrediction(text=\"empty\", start_logit=0.0, end_logit=0.0))\n\n assert len(nbest) >= 1\n\n total_scores = []\n best_non_null_entry = None\n for entry in nbest:\n total_scores.append(entry.start_logit + entry.end_logit)\n if not best_non_null_entry:\n if entry.text:\n best_non_null_entry = entry\n\n probs = _compute_softmax(total_scores)\n\n nbest_json = []\n for (i, entry) in enumerate(nbest):\n output = collections.OrderedDict()\n output[\"text\"] = entry.text\n output[\"probability\"] = probs[i]\n output[\"start_logit\"] = entry.start_logit\n output[\"end_logit\"] = entry.end_logit\n nbest_json.append(output)\n\n assert len(nbest_json) >= 1\n\n if not FLAGS.version_2_with_negative:\n all_predictions[example.qas_id] = nbest_json[0][\"text\"]\n else:\n # predict \"\" iff the null score - the score of best non-null > threshold\n score_diff = score_null - best_non_null_entry.start_logit - (\n best_non_null_entry.end_logit)\n scores_diff_json[example.qas_id] = score_diff\n if score_diff > FLAGS.null_score_diff_threshold:\n all_predictions[example.qas_id] = \"\"\n else:\n all_predictions[example.qas_id] = best_non_null_entry.text\n\n all_nbest_json[example.qas_id] = nbest_json\n\n with tf.gfile.GFile(output_prediction_file, \"w\") as writer:\n writer.write(json.dumps(all_predictions, indent=4) + \"\\n\")\n\n with tf.gfile.GFile(output_nbest_file, \"w\") as writer:\n writer.write(json.dumps(all_nbest_json, indent=4) + \"\\n\")\n\n if FLAGS.version_2_with_negative:\n with tf.gfile.GFile(output_null_log_odds_file, \"w\") as writer:\n writer.write(json.dumps(scores_diff_json, indent=4) + \"\\n\")\n\n\ndef get_final_text(pred_text, orig_text, do_lower_case):\n \"\"\"Project the tokenized prediction back to the original text.\"\"\"\n\n # When we created the data, we kept track of the alignment between original\n # (whitespace tokenized) tokens and our WordPiece tokenized tokens. So\n # now `orig_text` contains the span of our original text corresponding to the\n # span that we predicted.\n #\n # However, `orig_text` may contain extra characters that we don't want in\n # our prediction.\n #\n # For example, let's say:\n # pred_text = steve smith\n # orig_text = Steve Smith's\n #\n # We don't want to return `orig_text` because it contains the extra \"'s\".\n #\n # We don't want to return `pred_text` because it's already been normalized\n # (the SQuAD eval script also does punctuation stripping/lower casing but\n # our tokenizer does additional normalization like stripping accent\n # characters).\n #\n # What we really want to return is \"Steve Smith\".\n #\n # Therefore, we have to apply a semi-complicated alignment heruistic between\n # `pred_text` and `orig_text` to get a character-to-charcter alignment. This\n # can fail in certain cases in which case we just return `orig_text`.\n\n def _strip_spaces(text):\n ns_chars = []\n ns_to_s_map = collections.OrderedDict()\n for (i, c) in enumerate(text):\n if c == \" \":\n continue\n ns_to_s_map[len(ns_chars)] = i\n ns_chars.append(c)\n ns_text = \"\".join(ns_chars)\n return (ns_text, ns_to_s_map)\n\n # We first tokenize `orig_text`, strip whitespace from the result\n # and `pred_text`, and check if they are the same length. If they are\n # NOT the same length, the heuristic has failed. If they are the same\n # length, we assume the characters are one-to-one aligned.\n tokenizer = tokenization.BasicTokenizer(do_lower_case=do_lower_case)\n\n tok_text = \" \".join(tokenizer.tokenize(orig_text))\n\n start_position = tok_text.find(pred_text)\n if start_position == -1:\n if FLAGS.verbose_logging:\n tf.logging.info(\n \"Unable to find text: '%s' in '%s'\" % (pred_text, orig_text))\n return orig_text\n end_position = start_position + len(pred_text) - 1\n\n (orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text)\n (tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text)\n\n if len(orig_ns_text) != len(tok_ns_text):\n if FLAGS.verbose_logging:\n tf.logging.info(\"Length not equal after stripping spaces: '%s' vs '%s'\",\n orig_ns_text, tok_ns_text)\n return orig_text\n\n # We then project the characters in `pred_text` back to `orig_text` using\n # the character-to-character alignment.\n tok_s_to_ns_map = {}\n for (i, tok_index) in six.iteritems(tok_ns_to_s_map):\n tok_s_to_ns_map[tok_index] = i\n\n orig_start_position = None\n if start_position in tok_s_to_ns_map:\n ns_start_position = tok_s_to_ns_map[start_position]\n if ns_start_position in orig_ns_to_s_map:\n orig_start_position = orig_ns_to_s_map[ns_start_position]\n\n if orig_start_position is None:\n if FLAGS.verbose_logging:\n tf.logging.info(\"Couldn't map start position\")\n return orig_text\n\n orig_end_position = None\n if end_position in tok_s_to_ns_map:\n ns_end_position = tok_s_to_ns_map[end_position]\n if ns_end_position in orig_ns_to_s_map:\n orig_end_position = orig_ns_to_s_map[ns_end_position]\n\n if orig_end_position is None:\n if FLAGS.verbose_logging:\n tf.logging.info(\"Couldn't map end position\")\n return orig_text\n\n output_text = orig_text[orig_start_position:(orig_end_position + 1)]\n return output_text\n\n\ndef _get_best_indexes(logits, n_best_size):\n \"\"\"Get the n-best logits from a list.\"\"\"\n index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)\n\n best_indexes = []\n for i in range(len(index_and_score)):\n if i >= n_best_size:\n break\n best_indexes.append(index_and_score[i][0])\n return best_indexes\n\n\ndef _compute_softmax(scores):\n \"\"\"Compute softmax probability over raw logits.\"\"\"\n if not scores:\n return []\n\n max_score = None\n for score in scores:\n if max_score is None or score > max_score:\n max_score = score\n\n exp_scores = []\n total_sum = 0.0\n for score in scores:\n x = math.exp(score - max_score)\n exp_scores.append(x)\n total_sum += x\n\n probs = []\n for score in exp_scores:\n probs.append(score / total_sum)\n return probs\n\n\nclass FeatureWriter(object):\n \"\"\"Writes InputFeature to TF example file.\"\"\"\n\n def __init__(self, filename, is_training):\n self.filename = filename\n self.is_training = is_training\n self.num_features = 0\n self._writer = tf.python_io.TFRecordWriter(filename)\n\n def process_feature(self, feature):\n \"\"\"Write a InputFeature to the TFRecordWriter as a tf.train.Example.\"\"\"\n self.num_features += 1\n\n def create_int_feature(values):\n feature = tf.train.Feature(\n int64_list=tf.train.Int64List(value=list(values)))\n return feature\n\n features = collections.OrderedDict()\n features[\"unique_ids\"] = create_int_feature([feature.unique_id])\n features[\"input_ids\"] = create_int_feature(feature.input_ids)\n features[\"input_mask\"] = create_int_feature(feature.input_mask)\n features[\"segment_ids\"] = create_int_feature(feature.segment_ids)\n\n if self.is_training:\n features[\"start_positions\"] = create_int_feature([feature.start_position])\n features[\"end_positions\"] = create_int_feature([feature.end_position])\n impossible = 0\n if feature.is_impossible:\n impossible = 1\n features[\"is_impossible\"] = create_int_feature([impossible])\n\n tf_example = tf.train.Example(features=tf.train.Features(feature=features))\n self._writer.write(tf_example.SerializeToString())\n\n def close(self):\n self._writer.close()\n\n\ndef validate_flags_or_throw(bert_config):\n \"\"\"Validate the input FLAGS or throw an exception.\"\"\"\n tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case,\n FLAGS.init_checkpoint)\n\n if not FLAGS.do_train and not FLAGS.do_predict:\n raise ValueError(\"At least one of `do_train` or `do_predict` must be True.\")\n\n if FLAGS.do_train:\n if not FLAGS.train_file:\n raise ValueError(\n \"If `do_train` is True, then `train_file` must be specified.\")\n if FLAGS.do_predict:\n if not FLAGS.predict_file:\n raise ValueError(\n \"If `do_predict` is True, then `predict_file` must be specified.\")\n\n if FLAGS.max_seq_length > bert_config.max_position_embeddings:\n raise ValueError(\n \"Cannot use sequence length %d because the BERT model \"\n \"was only trained up to sequence length %d\" %\n (FLAGS.max_seq_length, bert_config.max_position_embeddings))\n\n if FLAGS.max_seq_length <= FLAGS.max_query_length + 3:\n raise ValueError(\n \"The max_seq_length (%d) must be greater than max_query_length \"\n \"(%d) + 3\" % (FLAGS.max_seq_length, FLAGS.max_query_length))\n\n\ndef main(_):\n tf.logging.set_verbosity(tf.logging.INFO)\n\n bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)\n\n validate_flags_or_throw(bert_config)\n\n tf.gfile.MakeDirs(FLAGS.output_dir)\n\n tokenizer = tokenization.FullTokenizer(\n vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)\n\n tpu_cluster_resolver = None\n if FLAGS.use_tpu and FLAGS.tpu_name:\n tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(\n FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)\n\n is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2\n run_config = tf.contrib.tpu.RunConfig(\n cluster=tpu_cluster_resolver,\n master=FLAGS.master,\n model_dir=FLAGS.output_dir,\n save_checkpoints_steps=FLAGS.save_checkpoints_steps,\n tpu_config=tf.contrib.tpu.TPUConfig(\n iterations_per_loop=FLAGS.iterations_per_loop,\n num_shards=FLAGS.num_tpu_cores,\n per_host_input_for_training=is_per_host))\n\n train_examples = None\n num_train_steps = None\n num_warmup_steps = None\n if FLAGS.do_train:\n train_examples = read_squad_examples(\n input_file=FLAGS.train_file, is_training=True)\n num_train_steps = int(\n len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)\n num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)\n\n # Pre-shuffle the input to avoid having to make a very large shuffle\n # buffer in in the `input_fn`.\n rng = random.Random(12345)\n rng.shuffle(train_examples)\n\n model_fn = model_fn_builder(\n bert_config=bert_config,\n init_checkpoint=FLAGS.init_checkpoint,\n learning_rate=FLAGS.learning_rate,\n num_train_steps=num_train_steps,\n num_warmup_steps=num_warmup_steps,\n use_tpu=FLAGS.use_tpu,\n use_one_hot_embeddings=FLAGS.use_tpu)\n\n # If TPU is not available, this will fall back to normal Estimator on CPU\n # or GPU.\n estimator = tf.contrib.tpu.TPUEstimator(\n use_tpu=FLAGS.use_tpu,\n model_fn=model_fn,\n config=run_config,\n train_batch_size=FLAGS.train_batch_size,\n predict_batch_size=FLAGS.predict_batch_size)\n\n if FLAGS.do_train:\n # We write to a temporary file to avoid storing very large constant tensors\n # in memory.\n train_writer = FeatureWriter(\n filename=os.path.join(FLAGS.output_dir, \"train.tf_record\"),\n is_training=True)\n convert_examples_to_features(\n examples=train_examples,\n tokenizer=tokenizer,\n max_seq_length=FLAGS.max_seq_length,\n doc_stride=FLAGS.doc_stride,\n max_query_length=FLAGS.max_query_length,\n is_training=True,\n output_fn=train_writer.process_feature)\n train_writer.close()\n\n tf.logging.info(\"***** Running training *****\")\n tf.logging.info(\" Num orig examples = %d\", len(train_examples))\n tf.logging.info(\" Num split examples = %d\", train_writer.num_features)\n tf.logging.info(\" Batch size = %d\", FLAGS.train_batch_size)\n tf.logging.info(\" Num steps = %d\", num_train_steps)\n del train_examples\n\n train_input_fn = input_fn_builder(\n input_file=train_writer.filename,\n seq_length=FLAGS.max_seq_length,\n is_training=True,\n drop_remainder=True)\n estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)\n\n if FLAGS.do_predict:\n eval_examples = read_squad_examples(\n input_file=FLAGS.predict_file, is_training=False)\n\n eval_writer = FeatureWriter(\n filename=os.path.join(FLAGS.output_dir, \"eval.tf_record\"),\n is_training=False)\n eval_features = []\n\n def append_feature(feature):\n eval_features.append(feature)\n eval_writer.process_feature(feature)\n\n convert_examples_to_features(\n examples=eval_examples,\n tokenizer=tokenizer,\n max_seq_length=FLAGS.max_seq_length,\n doc_stride=FLAGS.doc_stride,\n max_query_length=FLAGS.max_query_length,\n is_training=False,\n output_fn=append_feature)\n eval_writer.close()\n\n tf.logging.info(\"***** Running predictions *****\")\n tf.logging.info(\" Num orig examples = %d\", len(eval_examples))\n tf.logging.info(\" Num split examples = %d\", len(eval_features))\n tf.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size)\n\n all_results = []\n\n predict_input_fn = input_fn_builder(\n input_file=eval_writer.filename,\n seq_length=FLAGS.max_seq_length,\n is_training=False,\n drop_remainder=False)\n\n # If running eval on the TPU, you will need to specify the number of\n # steps.\n all_results = []\n for result in estimator.predict(\n predict_input_fn, yield_single_examples=True):\n if len(all_results) % 1000 == 0:\n tf.logging.info(\"Processing example: %d\" % (len(all_results)))\n unique_id = int(result[\"unique_ids\"])\n start_logits = [float(x) for x in result[\"start_logits\"].flat]\n end_logits = [float(x) for x in result[\"end_logits\"].flat]\n all_results.append(\n RawResult(\n unique_id=unique_id,\n start_logits=start_logits,\n end_logits=end_logits))\n\n output_prediction_file = os.path.join(FLAGS.output_dir, \"predictions.json\")\n output_nbest_file = os.path.join(FLAGS.output_dir, \"nbest_predictions.json\")\n output_null_log_odds_file = os.path.join(FLAGS.output_dir, \"null_odds.json\")\n\n write_predictions(eval_examples, eval_features, all_results,\n FLAGS.n_best_size, FLAGS.max_answer_length,\n FLAGS.do_lower_case, output_prediction_file,\n output_nbest_file, output_null_log_odds_file)\n\n\nif __name__ == \"__main__\":\n flags.mark_flag_as_required(\"vocab_file\")\n flags.mark_flag_as_required(\"bert_config_file\")\n flags.mark_flag_as_required(\"output_dir\")\n tf.app.run()\n"
] | [
[
"tensorflow.contrib.cluster_resolver.TPUClusterResolver",
"tensorflow.logging.warning",
"tensorflow.FixedLenFeature",
"tensorflow.nn.log_softmax",
"tensorflow.gfile.GFile",
"tensorflow.reduce_sum",
"tensorflow.train.init_from_checkpoint",
"tensorflow.gfile.MakeDirs",
"tensorflow.to_int32",
"tensorflow.contrib.tpu.TPUEstimatorSpec",
"tensorflow.contrib.tpu.TPUEstimator",
"tensorflow.data.TFRecordDataset",
"tensorflow.truncated_normal_initializer",
"tensorflow.python_io.TFRecordWriter",
"tensorflow.logging.set_verbosity",
"tensorflow.trainable_variables",
"tensorflow.parse_single_example",
"tensorflow.app.run",
"tensorflow.matmul",
"tensorflow.unstack",
"tensorflow.gfile.Open",
"tensorflow.zeros_initializer",
"tensorflow.logging.info",
"tensorflow.one_hot",
"tensorflow.contrib.tpu.TPUConfig",
"tensorflow.train.Features",
"tensorflow.nn.bias_add",
"tensorflow.train.Scaffold",
"tensorflow.transpose",
"tensorflow.flags.DEFINE_string",
"tensorflow.reshape"
]
] | [
{
"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"
]
}
] |
Michaelfonzolo/prednet | [
"ae09ebf77ab3b6f0d80faf490bb246972de2ddc2"
] | [
"kitti_extrap_finetune.py"
] | [
"'''\r\nFine-tune PredNet model trained for t+1 prediction for up to t+5 prediction.\r\n'''\r\n\r\nimport os\r\nimport numpy as np\r\nnp.random.seed(123)\r\n\r\nfrom keras import backend as K\r\nfrom keras.models import Model, model_from_json\r\nfrom keras.layers import Input\r\nfrom keras.callbacks import LearningRateScheduler, ModelCheckpoint\r\n\r\nfrom prednet import PredNet\r\nfrom data_utils import SequenceGenerator\r\nfrom kitti_settings import *\r\n\r\n# Define loss as MAE of frame predictions after t=0\r\n# It doesn't make sense to compute loss on error representation, since the error isn't wrt ground truth when extrapolating.\r\ndef extrap_loss(y_true, y_hat):\r\n y_true = y_true[:, 1:]\r\n y_hat = y_hat[:, 1:]\r\n return 0.5 * K.mean(K.abs(y_true - y_hat), axis=-1) # 0.5 to match scale of loss when trained in error mode (positive and negative errors split)\r\n\r\nnt = 15\r\nextrap_start_time = 10 # starting at this time step, the prediction from the previous time step will be treated as the actual input\r\norig_weights_file = os.path.join(WEIGHTS_DIR, 'prednet_kitti_weights.hdf5') # original t+1 weights\r\norig_json_file = os.path.join(WEIGHTS_DIR, 'prednet_kitti_model.json')\r\n\r\nsave_model = True\r\nextrap_weights_file = os.path.join(WEIGHTS_DIR, 'prednet_kitti_weights-extrapfinetuned.hdf5') # where new weights will be saved\r\nextrap_json_file = os.path.join(WEIGHTS_DIR, 'prednet_kitti_model-extrapfinetuned.json')\r\n\r\n# Data files\r\ntrain_file = os.path.join(DATA_DIR, 'X_train.hkl')\r\ntrain_sources = os.path.join(DATA_DIR, 'sources_train.hkl')\r\nval_file = os.path.join(DATA_DIR, 'X_val.hkl')\r\nval_sources = os.path.join(DATA_DIR, 'sources_val.hkl')\r\n\r\n# Training parameters\r\nnb_epoch = 150\r\nbatch_size = 4\r\nsamples_per_epoch = 500\r\nN_seq_val = 100 # number of sequences to use for validation\r\n\r\n# Load t+1 model\r\nf = open(orig_json_file, 'r')\r\njson_string = f.read()\r\nf.close()\r\norig_model = model_from_json(json_string, custom_objects = {'PredNet': PredNet})\r\norig_model.load_weights(orig_weights_file)\r\n\r\nlayer_config = orig_model.layers[1].get_config()\r\nlayer_config['output_mode'] = 'prediction'\r\nlayer_config['extrap_start_time'] = extrap_start_time\r\ndata_format = layer_config['data_format'] if 'data_format' in layer_config else layer_config['dim_ordering']\r\nprednet = PredNet(weights=orig_model.layers[1].get_weights(), **layer_config)\r\n\r\ninput_shape = list(orig_model.layers[0].batch_input_shape[1:])\r\ninput_shape[0] = nt\r\n\r\ninputs = Input(input_shape)\r\npredictions = prednet(inputs)\r\nmodel = Model(inputs=inputs, outputs=predictions)\r\nmodel.compile(loss=extrap_loss, optimizer='adam')\r\n\r\ntrain_generator = SequenceGenerator(train_file, train_sources, nt, batch_size=batch_size, shuffle=True, output_mode='prediction')\r\nval_generator = SequenceGenerator(val_file, val_sources, nt, batch_size=batch_size, N_seq=N_seq_val, output_mode='prediction')\r\n\r\nlr_schedule = lambda epoch: 0.001 if epoch < 75 else 0.0001 # start with lr of 0.001 and then drop to 0.0001 after 75 epochs\r\ncallbacks = [LearningRateScheduler(lr_schedule)]\r\nif save_model:\r\n if not os.path.exists(WEIGHTS_DIR): os.mkdir(WEIGHTS_DIR)\r\n callbacks.append(ModelCheckpoint(filepath=extrap_weights_file, monitor='val_loss', save_best_only=True))\r\nhistory = model.fit_generator(train_generator, samples_per_epoch / batch_size, nb_epoch, callbacks=callbacks,\r\n validation_data=val_generator, validation_steps=N_seq_val / batch_size)\r\n\r\nif save_model:\r\n json_string = model.to_json()\r\n with open(extrap_json_file, \"w\") as f:\r\n f.write(json_string)\r\n"
] | [
[
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ankurwasnik/LearnML | [
"6f45ef9c2f04734ee8f6e0e206356a7ee55983d2",
"6f45ef9c2f04734ee8f6e0e206356a7ee55983d2"
] | [
"4. Dimensionality Reduction/pca.py",
"2 Training Simple ML Algorithms for Classification/Adaline.py"
] | [
"import numpy as np\nimport pandas as pd\nimport os\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.decomposition import PCA\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score as accuracy\n#all required libraries are imported\n\n'''Author: Ankur W [LearnML} '''\ndef loadData():\t\n\tdf = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data' , header=None)\n\tdf.columns =['Class_label','Alcohol','Malic acid','Ash','Alkalinity of ash','Magnesium' , 'Total phenols' ,'Flavanoids','Nonflavanoids phenols','Proanthocyanins','Color Intensity','Hue','OD280/OD315 of diluted wines','Proline']\n\tX,y = df.iloc[:,1:].values , df.iloc[:,0].values\n\tXtrain ,Xtest , ytrain,ytest = train_test_split(X,y ,test_size=0.3 ,random_state=0,stratify=y)\n\treturn Xtrain,Xtest,ytrain,ytest\n\n\nif __name__=='__main__' :\n\tX_train , X_test , Y_train, Y_test = loadData()\n\t#initializing the pca analyzer\n\tpca = PCA(n_components=2)\n\t#logistic regressor estimator\n\tlog_reg = LogisticRegression(multi_class='ovr' , random_state=1 ) \n\t#dimensionality reduction\n\tX_train_pca = pca.fit_transform(X_train)\n\tX_test_pca = pca.transform(X_test)\n\t#fitting the logistic regressor on reduced data in terms of dimensionality\n\tlog_reg.fit(X_train_pca,Y_train)\n\t#predicting on reduced test data\n\tpredictions = log_reg.predict(X_test_pca)\n\t#evaluating reduced test data\n\tprint('Evaluation of PCA test dataset: ', accuracy(Y_test,predictions))\n\t\n",
"'''\nAuthor: Ankur Wasnik\nDate 6th Jan 2020 22:17pm IST\nAdaline means Adaptive linear neurons model\nDifference between Perceptron and Adaline \"\n\t1. Perceptron compares true labels with net input. While , Adaline compares the output of activation function .\n\t2. In Perceptron, weights are updated based on each training data. While, in adaline , weights are updated after each training sessions\n\n'''\nimport numpy as np\n\nclass MyAdalineModel(object):\n\t'''\n\tBuilding Adaptive linear neuron model from scratch.\n\t'''\n\tdef __init__(self, learning_rate=0.01 , epochs=10 , random_state=1):\n\t\tself.learning_rate=learning_rate\n\t\tself.epochs = epochs\n\t\tself.random_state=random_state\n\t\n\tdef fit(self,X,y):\n\t\trgen=np.random.RandomState(self.random_state)\n\t\tself.w_ = rgen.normal(loc=0.0,scale=0.01,size=1+X.shape[1])\n\t\tself.errors_ =[]\n\t\t\n\t\tfor _ in range(self.epochs):\n\t\t\tnet_input = self.net_input(X)\n\t\t\ty_hat = self.activation(net_input)\n\t\t\terrors = (y_hat - y)\n\t\t\tself.w_[0]+=self.learning_rate*(errors.sum())\n\t\t\tself.w_[1:]+= self.learning_rate*(np.dot(X.T,errors))\n\t\t\tcost = np.square(np.sum(errors))/2.0\n\t\t\tself.errors_.append(cost)\n\t\treturn self\n\t\n\tdef net_input(self,X):\n\t\treturn np.dot(X,self.w_[1:])+self.w_[0]\n\t\n\tdef activation(self,X):\n\t\treturn X\n\tdef predict(self,X,threshold=0.2):\n\t\treturn np.where( self.activation(self.net_input(X)) >= threshold , 1 , -1)\n\nif __name__=='__main__':\n\timport os \n\timport pandas as pd\n\ts=os.path.join('https://archive.ics.uci.edu','ml','machine-learning-databases','iris','iris.data')\n\tprint('Downloading Iris Dataset from :\\n',s)\n\tdf = pd.read_csv(s,header=None,encoding='utf-8')\n\ty=df.iloc[0:100,4].values\n\ty=np.where(y=='Iris-setosa',-1,1)\n\tX=df.iloc[0:100,[0,2]].values\n\tlearning_rate = float(input('Enter Learning Rate : '))\n\tepochs = int(input('Enter Epochs : '))\t\n\tAdalineModel = MyAdalineModel(learning_rate , epochs , random_state=69)\n\tAdalineModel.fit(X,y)\n\t#We are done with training and You can predict on our trained model.\n\t''' Testing our trained data with one of trained data sample \\nBut you are free to do on testing data.'''\n\ty_test = df.iloc[132 , 4]\n\ty_test = np.where(y_test=='Iris-setosa' , -1,1)\n\tX_test = df.iloc[132, [0,2] ].values\n\tprint('Predicted Label for Testing data: ' ,AdalineModel.predict(X_test,threshold=0.6 ))\n\tprint('True Label for Testing data : ' , y_test)\n\n\n"
] | [
[
"pandas.read_csv",
"sklearn.linear_model.LogisticRegression",
"sklearn.model_selection.train_test_split",
"sklearn.decomposition.PCA",
"sklearn.metrics.accuracy_score"
],
[
"numpy.dot",
"pandas.read_csv",
"numpy.random.RandomState",
"numpy.where",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
PierreRochard/pacioli | [
"4a66ed80b1e3408e19d81e0ce7cfa46e477f489e"
] | [
"pacioli/functions/investment_functions.py"
] | [
"import csv\nfrom datetime import datetime, timedelta\n\nfrom matplotlib.finance import fetch_historical_yahoo\nfrom sqlalchemy import inspect\nfrom sqlalchemy.exc import IntegrityError\n\nfrom pacioli import db\nfrom pacioli.views.ofx_views import Securities\nfrom pacioli.models import SecurityPrices\n\n\ndef update_ticker_prices():\n for ticker, in db.session.query(Securities.ticker).all():\n start_date = datetime.now() - timedelta(days=7)\n end_date = datetime.now()\n data = fetch_historical_yahoo(ticker, start_date, end_date)\n reader = csv.DictReader(data)\n for row in reader:\n new_record = SecurityPrices()\n for key in list(row.keys()):\n key_name = key.lower().replace('adj close', 'adjusted_close')\n row[key_name] = row.pop(key)\n for column in inspect(SecurityPrices).attrs:\n if column.key == 'id':\n continue\n elif column.key == 'ticker':\n setattr(new_record, column.key, ticker)\n else:\n setattr(new_record, column.key, row[column.key])\n try:\n db.session.add(new_record)\n db.session.commit()\n except IntegrityError:\n db.session.rollback()\n"
] | [
[
"matplotlib.finance.fetch_historical_yahoo"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
basiralab/FSSelect | [
"fc1a5706ac681bf6471ad07c67dff16b8647870f",
"fc1a5706ac681bf6471ad07c67dff16b8647870f"
] | [
"helpers/storage.py",
"helpers/simulateData.py"
] | [
"import pandas as pd\nfrom helpers.fs_methods import *\nfrom helpers.training import *\nimport os\n\ndef name_dataframe(X,cv_method):\n n,m=X.shape\n\n name1='df_accuracy_'\n name2='df_ranking_'\n name3='df_weights_'\n added_str='fold.pkl'\n num_splits =cv_method.get_n_splits(X)\n if num_splits!=n:\n name1=name1+str(num_splits)+added_str\n name2=name2+str(num_splits)+added_str\n name3=name3+str(num_splits)+added_str\n else:\n name1=name1+'LOO'\n name2=name2+'LOO'\n name3=name3+'LOO'\n return(name1,name2,name3)\n\ndef store(output_dir,cv_method):\n ''' INPUT\n\n output_dir: is the directory where to store the keymetrics (ranking, weights and accuracies dataframes)\n cv_method : 5_fold , 10_fold or LOO \n\n OUTPUT\n\n stored pickle dataframes in the given directory\n '''\n\n # Initialize empty dataframes\n pool_FS=[reliefF]#,lap_score,ll_l21,ls_l21,UDFS,fisher_score,chi_square,gini_index,SPEC]\n\n labels=['reliefF']#,'lap_score','ll_l21','ls_l21','UDFS','fisher_score','chi_square','gini_index','SPEC']#,'Boratapy']\n dataframe_ranking=pd.DataFrame(index=num_fea,columns=labels)\n dataframe_weights=pd.DataFrame(index=num_fea,columns=labels)\n dataframe_accuracies=pd.DataFrame(index=num_fea,columns=labels)\n\n #matrix_=np.zeros((50,589*3))\n for i in range(len(pool_FS)):\n for k in num_fea:\n ranking__,acc__,weight__=training(cv_method,k,pool_FS[i],X,y)\n #ranking__,acc__=training(kf5,k,pool_FS[i],X,y)\n #ranking__,acc__,=training(kf5,k,pool_FS[i])\n dataframe_ranking[labels[i]][k]=ranking__\n dataframe_weights[labels[i]][k]=weight__\n dataframe_accuracies[labels[i]][k]=acc__ \n\n #dataframe_ranking_5fold=dataframe_ranking.copy()\n #dataframe_weights_5fold=dataframe_weights.copy()\n #dataframe_accuracies_5fold=dataframe_accuracies.copy()\n\n name1,name2,name3=name_dataframe(X,cv_method)\n \n dataframe_accuracies.to_pickle(output_dir+name1)\n dataframe_ranking.to_pickle(output_dir+name2)\n dataframe_weights.to_pickle(output_dir+name3)",
"import numpy as np\r\nimport sys\r\nnp.set_printoptions(threshold=sys.maxsize)\r\nnp.set_printoptions(suppress=True)\r\n\r\ndef simulate_data(mu1,sigma1,mu2,sigma2):\r\n cont = True\r\n Labels = []\r\n X = []\r\n#* * (2.1) Sample number of Class-1 and Class-2 and Region of Interests are chosen by user.\r\n prompt = 'Select the number of class 1 graphs: '\r\n C1 = int(input(prompt))\r\n while C1==\"\":\r\n prompt = 'Please choose a number: '\r\n C1 = int(input(prompt))\r\n while (C1 < 10):\r\n prompt = 'Please choose a number >9: '\r\n C1 = int(input(prompt))\r\n\r\n prompt = 'Select the number of class 2 graphs: '\r\n C2 = int(input(prompt))\r\n while C2==\"\":\r\n prompt = 'Please choose a number: '\r\n C2 = int(input(prompt))\r\n while (C2 < 10):\r\n prompt = 'Please choose a number >9: '\r\n C2 = int(input(prompt))\r\n prompt = 'Select the number of nodes (i.e., ROIS for brain graphs): '\r\n m = int(input(prompt))\r\n while (m==\"\"):\r\n prompt = 'Please choose a number >20: '\r\n m = int(input(prompt))\r\n\r\n while ((m < 21)):\r\n prompt = 'Please choose a number >20: '\r\n m = int(input(prompt))\r\n\r\n# * *\r\n\r\n# * * (2.2) Matrixes are created as chosen numbers by user before which has random numbers.(not network atlasses yet.)\r\n\r\n N = C1 + C2 #total sample number\r\n dataC1 = np.random.normal(mu1, sigma1, [C1, m, m])\r\n dataC2 = np.random.normal(mu2, sigma2, [C2, m, m])\r\n data1 = np.append(dataC1,dataC2,axis=0) #main array which include random number matrixes of both classes\r\n\r\n# * *\r\n\r\n# * * (2.3) Matrixes with Random numbers are converted to Connectivity Matrixes\r\n for i in range(N):\r\n\r\n data1[i, :, :] = data1[i, :, :] - np.diag(np.diag(data1[i,:,:])) #Removing diagonal elements of each matrixes\r\n data1[i, :,:] = (data1[i, :,:] + data1[i, :,:].transpose())/2 #Converting each matrixes symetric connectivity matrixes\r\n t = np.triu(data1[i,:,:]) #Taking upper triangular part of each converted matrixes\r\n x=t[np.triu_indices(m,1)] #Creating 1xK matrixes which K is connectivity number of upper triangular part.\r\n x1=x.transpose()\r\n# * *\r\n\r\n# * * (2.4) All edited datas are added new arrays and these arrays are added in main array which called Data.\r\n if cont:\r\n Featurematrix = np.empty((0, x1.shape[0]), int)\r\n cont=False\r\n Featurematrix = np.append(Featurematrix, np.array([x1]), axis=0)\r\n #Every loop step , random matrixes fixed and updated.\r\n X=data1\r\n #Labels are created and added into Label array as one by one. So they correspond with datas which they belong.\r\n Label1 = np.ones((C1, 1))\r\n Label2 = np.ones((C2, 1))*-1\r\n Label=np.append(Label1,Label2,axis=0)\r\n Data=[Featurematrix,X,Label] #Feature Matrix-->Nx1xK\r\n# * * #X--->NxMxM\r\n return Data #Label-->Nx1x1\r\n\r\n\r\n\r\n\r\n"
] | [
[
"pandas.DataFrame"
],
[
"numpy.diag",
"numpy.triu_indices",
"numpy.set_printoptions",
"numpy.ones",
"numpy.random.normal",
"numpy.append",
"numpy.triu",
"numpy.array",
"numpy.empty"
]
] | [
{
"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": []
}
] |
GGarcia93/pycryptobot | [
"74b7d2dcbafd47419d02f179cbdc2d8086399b0f"
] | [
"models/PyCryptoBot.py"
] | [
"import json\nimport math\nimport random\nimport re\nfrom datetime import datetime, timedelta\nfrom typing import Union\n\nimport pandas as pd\nimport urllib3\nfrom urllib3.exceptions import ReadTimeoutError\n\nfrom models.BotConfig import BotConfig\nfrom models.Trading import TechnicalAnalysis\nfrom models.config import binanceParseMarket, coinbaseProParseMarket, kucoinParseMarket\nfrom models.exchange.Granularity import Granularity\nfrom models.exchange.ExchangesEnum import Exchange\nfrom models.exchange.binance import AuthAPI as BAuthAPI, PublicAPI as BPublicAPI\nfrom models.exchange.coinbase_pro import AuthAPI as CBAuthAPI, PublicAPI as CBPublicAPI\nfrom models.exchange.kucoin import AuthAPI as KAuthAPI, PublicAPI as KPublicAPI\nfrom models.helper.TextBoxHelper import TextBox\n\n# disable insecure ssl warning\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\npd.set_option('display.float_format', '{:.8f}'.format)\n\n\n# pylint: disable=unsubscriptable-object\ndef truncate(f: Union[int, float], n: Union[int, float]) -> str:\n \"\"\"\n Format a given number ``f`` with a given precision ``n``.\n \"\"\"\n\n if not isinstance(f, int) and not isinstance(f, float):\n return \"0.0\"\n\n if not isinstance(n, int) and not isinstance(n, float):\n return \"0.0\"\n\n if (f < 0.0001) and n >= 5:\n return f\"{f:.5f}\"\n\n # `{n}` inside the actual format honors the precision\n return f\"{math.floor(f * 10 ** n) / 10 ** n:.{n}f}\"\n\n\nclass PyCryptoBot(BotConfig):\n def __init__(self, config_file: str = None, exchange: Exchange = None):\n self.config_file = config_file or \"config.json\"\n self.exchange = exchange\n super(PyCryptoBot, self).__init__(\n filename=self.config_file, exchange=self.exchange\n )\n\n takerfee = 0.0\n\n extraCandlesFound = False\n\n trade_tracker = pd.DataFrame(\n columns=[\n \"Datetime\",\n \"Market\",\n \"Action\",\n \"Price\",\n \"Base\",\n \"Quote\",\n \"Margin\",\n \"Profit\",\n \"Fee\",\n \"DF_High\",\n \"DF_Low\",\n ]\n )\n\n def getConfig(self) -> dict:\n try:\n config = json.loads(open(self.config_file, \"r\", encoding=\"utf8\").read())\n\n if self.exchange.value in config:\n if \"config\" in config[self.exchange.value]:\n return config[self.exchange.value][\"config\"]\n else:\n return {}\n else:\n return {}\n except IOError:\n return {}\n\n def _isCurrencyValid(self, currency):\n if (\n self.exchange == Exchange.COINBASEPRO\n or self.exchange == Exchange.BINANCE\n or self.exchange == Exchange.KUCOIN\n ):\n p = re.compile(r\"^[0-9A-Z]{1,20}$\")\n return p.match(currency)\n\n return False\n\n def _isMarketValid(self, market):\n if self.exchange == Exchange.COINBASEPRO or self.exchange == Exchange.KUCOIN:\n p = re.compile(r\"^[0-9A-Z]{1,20}\\-[1-9A-Z]{2,5}$\")\n return p.match(market)\n elif self.exchange == Exchange.BINANCE:\n p = re.compile(r\"^[A-Z0-9]{4,25}$\")\n if p.match(market):\n return True\n p = re.compile(r\"^[0-9A-Z]{1,20}\\-[1-9A-Z]{2,5}$\")\n if p.match(market):\n return True\n return False\n\n return False\n\n def getRecvWindow(self):\n return self.recv_window\n\n def getLogFile(self):\n return self.logfile\n\n def getTradesFile(self):\n return self.tradesfile\n\n def getExchange(self) -> Exchange:\n return self.exchange\n\n def getChatClient(self):\n return self._chat_client\n\n def getAPIKey(self):\n return self.api_key\n\n def getAPISecret(self):\n return self.api_secret\n\n def getAPIPassphrase(self):\n return self.api_passphrase\n\n def getAPIURL(self):\n return self.api_url\n\n def getBaseCurrency(self):\n return self.base_currency\n\n def getQuoteCurrency(self):\n return self.quote_currency\n\n def getMarket(self):\n if self.exchange == Exchange.BINANCE:\n formatCheck = self.market.split(\"-\") if self.market.find(\"-\") != -1 else \"\"\n if not formatCheck == \"\":\n self.base_currency = formatCheck[0]\n self.quote_currency = formatCheck[1]\n self.market = self.base_currency + self.quote_currency\n\n # Logger.info(self.market)\n return self.market\n\n def getGranularity(self) -> Granularity:\n return self.granularity\n\n def getInterval(\n self, df: pd.DataFrame = pd.DataFrame(), iterations: int = 0\n ) -> pd.DataFrame:\n if len(df) == 0:\n return df\n\n if self.isSimulation() and iterations > 0:\n # with a simulation iterate through data\n return df.iloc[iterations - 1 : iterations]\n else:\n # most recent entry\n return df.tail(1)\n\n def printGranularity(self) -> str:\n if self.exchange == Exchange.KUCOIN:\n return self.granularity.to_medium\n if self.exchange == Exchange.BINANCE:\n return self.granularity.to_short\n if self.exchange == Exchange.COINBASEPRO:\n return str(self.granularity.to_integer)\n if self.exchange == Exchange.DUMMY:\n return str(self.granularity.to_integer)\n raise TypeError(f'Unknown exchange \"{self.exchange.name}\"')\n\n def getBuyPercent(self):\n try:\n return int(self.buypercent)\n except Exception: # pylint: disable=broad-except\n return 100\n\n def getSellPercent(self):\n try:\n return int(self.sellpercent)\n except Exception: # pylint: disable=broad-except\n return 100\n\n def getBuyMaxSize(self):\n try:\n return float(self.buymaxsize)\n except Exception: # pylint: disable=broad-except\n return None\n\n def getBuyMinSize(self):\n try:\n return float(self.buyminsize)\n except Exception: # pylint: disable=broad-except\n return None\n\n def buyLastSellSize(self) -> bool:\n return self.buylastsellsize\n\n def getTrailingBuyPcnt(self):\n try:\n return float(self.trailingbuypcnt)\n except Exception: # pylint: disable=broad-except\n return 0\n\n def trailingImmediateBuy(self) -> bool:\n return self.trailingimmediatebuy\n\n def marketMultiBuyCheck(self) -> bool:\n return self.marketmultibuycheck\n\n def getBuyNearHighPcnt(self):\n try:\n return float(self.nobuynearhighpcnt)\n except Exception: # pylint: disable=broad-except\n return None\n\n def getDateFromISO8601Str(self, date: str):\n # if date passed from datetime.now() remove milliseconds\n if date.find(\".\") != -1:\n dt = date.split(\".\")[0]\n date = dt\n\n date = date.replace(\"T\", \" \") if date.find(\"T\") != -1 else date\n # add time in case only a date is passed in\n new_date_str = f\"{date} 00:00:00\" if len(date) == 10 else date\n return datetime.strptime(new_date_str, \"%Y-%m-%d %H:%M:%S\")\n\n def getHistoricalData(\n self,\n market,\n granularity: Granularity,\n websocket,\n iso8601start=\"\",\n iso8601end=\"\",\n ):\n if self.exchange == Exchange.BINANCE:\n api = BPublicAPI(api_url=self.getAPIURL())\n\n if iso8601start != \"\" and iso8601end != \"\":\n return api.getHistoricalData(\n market,\n granularity,\n None,\n iso8601start,\n iso8601end,\n )\n else:\n return api.getHistoricalData(market, granularity, websocket)\n elif (\n self.exchange == Exchange.KUCOIN\n ): # returns data from coinbase if not specified\n api = KPublicAPI(api_url=self.getAPIURL())\n\n if iso8601start != \"\" and iso8601end == \"\":\n return api.getHistoricalData(\n market,\n granularity,\n None,\n iso8601start,\n )\n elif iso8601start != \"\" and iso8601end != \"\":\n return api.getHistoricalData(\n market,\n granularity,\n None,\n iso8601start,\n iso8601end,\n )\n else:\n return api.getHistoricalData(market, granularity, websocket)\n else: # returns data from coinbase if not specified\n api = CBPublicAPI()\n\n if iso8601start != \"\" and iso8601end == \"\":\n return api.getHistoricalData(\n market,\n granularity,\n None,\n iso8601start,\n )\n elif iso8601start != \"\" and iso8601end != \"\":\n return api.getHistoricalData(\n market,\n granularity,\n None,\n iso8601start,\n iso8601end,\n )\n else:\n return api.getHistoricalData(market, granularity, websocket)\n\n def getSmartSwitchDataFrame(\n self,\n df: pd.DataFrame,\n market,\n granularity: Granularity,\n simstart: str = \"\",\n simend: str = \"\",\n ) -> pd.DataFrame:\n if self.isSimulation():\n result_df_cache = df\n\n simstart = self.getDateFromISO8601Str(simstart)\n simend = self.getDateFromISO8601Str(simend)\n\n try:\n df_first = None\n df_last = None\n\n # logger.debug(\"Row Count (\" + str(granularity) + \"): \" + str(df.shape[0]))\n # if df already has data get first and last record date\n df_first = self.getDateFromISO8601Str(str(df.head(1).index.format()[0]))\n df_last = self.getDateFromISO8601Str(str(df.tail(1).index.format()[0]))\n\n except Exception: # pylint: disable=broad-except\n # if df = None create a new data frame\n result_df_cache = pd.DataFrame()\n\n if df_first is None and df_last is None:\n text_box = TextBox(80, 26)\n\n if not self.isSimulation() or (\n self.isSimulation() and not self.simResultOnly()\n ):\n text_box.singleLine()\n if self.smart_switch:\n text_box.center(\n f\"*** Getting smartswitch ({granularity.to_short}) market data ***\"\n )\n else:\n text_box.center(\n f\"*** Getting ({granularity.to_short}) market data ***\"\n )\n\n df_first = simend\n df_first -= timedelta(minutes=((granularity.to_integer / 60) * 200))\n df1 = self.getHistoricalData(\n market,\n granularity,\n None,\n str(df_first.isoformat()),\n str(simend.isoformat()),\n )\n\n result_df_cache = df1\n originalSimStart = self.getDateFromISO8601Str(str(simstart))\n addingExtraCandles = False\n while df_first.isoformat(timespec=\"milliseconds\") > simstart.isoformat(\n timespec=\"milliseconds\"\n ) or df_first.isoformat(\n timespec=\"milliseconds\"\n ) > originalSimStart.isoformat(\n timespec=\"milliseconds\"\n ):\n\n end_date = df_first\n df_first -= timedelta(minutes=(300 * (granularity.to_integer / 60)))\n\n if df_first.isoformat(timespec=\"milliseconds\") < simstart.isoformat(\n timespec=\"milliseconds\"\n ):\n df_first = self.getDateFromISO8601Str(str(simstart))\n\n df2 = self.getHistoricalData(\n market,\n granularity,\n None,\n str(df_first.isoformat()),\n str(end_date.isoformat()),\n )\n\n # check to see if there are an extra 300 candles available to be used, if not just use the original starting point\n if addingExtraCandles == True and len(df2) <= 0:\n self.extraCandlesFound = False\n simstart = originalSimStart\n else:\n result_df_cache = pd.concat(\n [df2.copy(), df1.copy()]\n ).drop_duplicates()\n df1 = result_df_cache\n\n # create df with 300 candles before the required startdate to match live\n if df_first.isoformat(\n timespec=\"milliseconds\"\n ) == simstart.isoformat(timespec=\"milliseconds\"):\n if addingExtraCandles == False:\n simstart -= timedelta(\n minutes=(300 * (granularity.to_integer / 60))\n )\n addingExtraCandles = True\n self.extraCandlesFound = True\n\n if not self.isSimulation() or (\n self.isSimulation() and not self.simResultOnly()\n ):\n text_box.doubleLine()\n\n if len(result_df_cache) > 0 and \"morning_star\" not in result_df_cache:\n result_df_cache.sort_values(by=[\"date\"], ascending=True, inplace=True)\n\n if self.smart_switch == False:\n if self.extraCandlesFound == False:\n text_box = TextBox(80, 26)\n text_box.singleLine()\n text_box.center(\n f\"{str(self.exchange.value)} is not returning data for the requested start date.\"\n )\n text_box.center(\n f\"Switching to earliest start date: {str(result_df_cache.head(1).index.format()[0])}\"\n )\n text_box.singleLine()\n self.simstartdate = str(result_df_cache.head(1).index.format()[0])\n\n return result_df_cache.copy()\n\n def getSmartSwitchHistoricalDataChained(\n self,\n market,\n granularity: Granularity,\n start: str = \"\",\n end: str = \"\",\n ) -> pd.DataFrame:\n\n if self.isSimulation():\n if self.getSellSmartSwitch() == 1:\n self.ema1226_5m_cache = self.getSmartSwitchDataFrame(\n self.ema1226_5m_cache, market, Granularity.FIVE_MINUTES, start, end\n )\n self.ema1226_15m_cache = self.getSmartSwitchDataFrame(\n self.ema1226_15m_cache, market, Granularity.FIFTEEN_MINUTES, start, end\n )\n self.ema1226_1h_cache = self.getSmartSwitchDataFrame(\n self.ema1226_1h_cache, market, Granularity.ONE_HOUR, start, end\n )\n self.ema1226_6h_cache = self.getSmartSwitchDataFrame(\n self.ema1226_6h_cache, market, Granularity.SIX_HOURS, start, end\n )\n\n if len(self.ema1226_15m_cache) == 0:\n raise Exception(\n f\"No data return for selected date range {start} - {end}\"\n )\n\n if not self.extraCandlesFound:\n if granularity == Granularity.FIVE_MINUTES:\n if (\n self.getDateFromISO8601Str(\n str(self.ema1226_5m_cache.index.format()[0])\n ).isoformat()\n != self.getDateFromISO8601Str(start).isoformat()\n ):\n text_box = TextBox(80, 26)\n text_box.singleLine()\n text_box.center(\n f\"{str(self.exchange.value)}is not returning data for the requested start date.\"\n )\n text_box.center(\n f\"Switching to earliest start date: {str(self.ema1226_5m_cache.head(1).index.format()[0])}\"\n )\n text_box.singleLine()\n self.simstartdate = str(\n self.ema1226_5m_cache.head(1).index.format()[0]\n )\n elif granularity == Granularity.FIFTEEN_MINUTES:\n if (\n self.getDateFromISO8601Str(\n str(self.ema1226_15m_cache.index.format()[0])\n ).isoformat()\n != self.getDateFromISO8601Str(start).isoformat()\n ):\n text_box = TextBox(80, 26)\n text_box.singleLine()\n text_box.center(\n f\"{str(self.exchange.value)}is not returning data for the requested start date.\"\n )\n text_box.center(\n f\"Switching to earliest start date: {str(self.ema1226_15m_cache.head(1).index.format()[0])}\"\n )\n text_box.singleLine()\n self.simstartdate = str(\n self.ema1226_15m_cache.head(1).index.format()[0]\n )\n else:\n if (\n self.getDateFromISO8601Str(\n str(self.ema1226_1h_cache.index.format()[0])\n ).isoformat()\n != self.getDateFromISO8601Str(start).isoformat()\n ):\n text_box = TextBox(80, 26)\n text_box.singleLine()\n text_box.center(\n f\"{str(self.exchange.value)} is not returning data for the requested start date.\"\n )\n text_box.center(\n f\"Switching to earliest start date: {str(self.ema1226_1h_cache.head(1).index.format()[0])}\"\n )\n text_box.singleLine()\n self.simstartdate = str(\n self.ema1226_1h_cache.head(1).index.format()[0]\n )\n\n if granularity == Granularity.FIFTEEN_MINUTES:\n return self.ema1226_15m_cache\n elif granularity == Granularity.FIVE_MINUTES:\n return self.ema1226_5m_cache\n else:\n return self.ema1226_1h_cache\n\n def getHistoricalDataChained(\n self, market, granularity: Granularity, max_iterations: int = 1\n ) -> pd.DataFrame:\n df1 = self.getHistoricalData(market, granularity, None)\n\n if max_iterations == 1:\n return df1\n\n def getPreviousDateRange(df: pd.DataFrame = None) -> tuple:\n end_date = df[\"date\"].min() - timedelta(\n seconds=(granularity.to_integer / 60)\n )\n new_start = df[\"date\"].min() - timedelta(hours=300)\n return (str(new_start).replace(\" \", \"T\"), str(end_date).replace(\" \", \"T\"))\n\n iterations = 0\n result_df = pd.DataFrame()\n while iterations < (max_iterations - 1):\n start_date, end_date = getPreviousDateRange(df1)\n df2 = self.getHistoricalData(\n market, granularity, None, start_date, end_date\n )\n result_df = pd.concat([df2, df1]).drop_duplicates()\n df1 = result_df\n iterations = iterations + 1\n\n if \"date\" in result_df:\n result_df.sort_values(by=[\"date\"], ascending=True, inplace=True)\n\n return result_df\n\n def getSmartSwitch(self):\n return self.smart_switch\n\n def getSellSmartSwitch(self):\n return self.sell_smart_switch\n\n def is1hEMA1226Bull(self, iso8601end: str = \"\", websocket=None):\n try:\n if self.isSimulation() and isinstance(self.ema1226_1h_cache, pd.DataFrame):\n df_data = self.ema1226_1h_cache.loc[\n self.ema1226_1h_cache[\"date\"] <= iso8601end\n ].copy()\n elif self.exchange == Exchange.COINBASEPRO:\n api = CBPublicAPI()\n df_data = api.getHistoricalData(\n self.market, Granularity.ONE_HOUR, websocket\n )\n self.ema1226_1h_cache = df_data\n elif self.exchange == Exchange.BINANCE:\n api = BPublicAPI(api_url=self.getAPIURL())\n df_data = api.getHistoricalData(\n self.market, Granularity.ONE_HOUR, websocket\n )\n self.ema1226_1h_cache = df_data\n elif self.exchange == Exchange.KUCOIN:\n api = KPublicAPI(api_url=self.getAPIURL())\n df_data = api.getHistoricalData(\n self.market, Granularity.ONE_HOUR, websocket\n )\n self.ema1226_1h_cache = df_data\n else:\n return False\n\n ta = TechnicalAnalysis(df_data)\n\n if \"ema12\" not in df_data:\n ta.addEMA(12)\n\n if \"ema26\" not in df_data:\n ta.addEMA(26)\n\n df_last = ta.getDataFrame().copy().iloc[-1, :]\n df_last[\"bull\"] = df_last[\"ema12\"] > df_last[\"ema26\"]\n\n return bool(df_last[\"bull\"])\n except Exception:\n return False\n\n def is1hSMA50200Bull(self, iso8601end: str = \"\", websocket=None):\n try:\n if self.isSimulation() and isinstance(self.sma50200_1h_cache, pd.DataFrame):\n df_data = self.sma50200_1h_cache.loc[\n self.sma50200_1h_cache[\"date\"] <= iso8601end\n ].copy()\n elif self.exchange == Exchange.COINBASEPRO:\n api = CBPublicAPI()\n df_data = api.getHistoricalData(\n self.market, Granularity.ONE_HOUR, websocket\n )\n self.sma50200_1h_cache = df_data\n elif self.exchange == Exchange.BINANCE:\n api = BPublicAPI(api_url=self.getAPIURL())\n df_data = api.getHistoricalData(\n self.market, Granularity.ONE_HOUR, websocket\n )\n self.sma50200_1h_cache = df_data\n elif self.exchange == Exchange.KUCOIN:\n api = KPublicAPI(api_url=self.getAPIURL())\n df_data = api.getHistoricalData(\n self.market, Granularity.ONE_HOUR, websocket\n )\n self.sma50200_1h_cache = df_data\n else:\n return False\n\n ta = TechnicalAnalysis(df_data)\n\n if \"sma50\" not in df_data:\n ta.addSMA(50)\n\n if \"sma200\" not in df_data:\n ta.addSMA(200)\n\n df_last = ta.getDataFrame().copy().iloc[-1, :]\n df_last[\"bull\"] = df_last[\"sma50\"] > df_last[\"sma200\"]\n\n return bool(df_last[\"bull\"])\n except Exception:\n return False\n\n def isCryptoRecession(self, websocket=None):\n try:\n if self.exchange == Exchange.COINBASEPRO:\n api = CBPublicAPI()\n df_data = api.getHistoricalData(\n self.market, Granularity.ONE_DAY, websocket\n )\n elif self.exchange == Exchange.BINANCE:\n api = BPublicAPI(api_url=self.getAPIURL())\n df_data = api.getHistoricalData(\n self.market, Granularity.ONE_DAY, websocket\n )\n elif self.exchange == Exchange.KUCOIN:\n api = KPublicAPI(api_url=self.getAPIURL())\n df_data = api.getHistoricalData(\n self.market, Granularity.ONE_DAY, websocket\n )\n else:\n return False # if there is an API issue, default to False to avoid hard sells\n\n if len(df_data) <= 200:\n return False # if there is insufficient data, default to False to avoid hard sells\n\n ta = TechnicalAnalysis(df_data)\n ta.addSMA(50)\n ta.addSMA(200)\n df_last = ta.getDataFrame().copy().iloc[-1, :]\n df_last[\"crypto_recession\"] = df_last[\"sma50\"] < df_last[\"sma200\"]\n\n return bool(df_last[\"crypto_recession\"])\n except Exception:\n return False\n\n def is6hEMA1226Bull(self, iso8601end: str = \"\", websocket=None):\n try:\n if self.isSimulation() and isinstance(self.ema1226_6h_cache, pd.DataFrame):\n df_data = self.ema1226_6h_cache[\n (self.ema1226_6h_cache[\"date\"] <= iso8601end)\n ].copy()\n elif self.exchange == Exchange.COINBASEPRO:\n api = CBPublicAPI()\n df_data = api.getHistoricalData(\n self.market, Granularity.SIX_HOURS, websocket\n )\n self.ema1226_6h_cache = df_data\n elif self.exchange == Exchange.BINANCE:\n api = BPublicAPI(api_url=self.getAPIURL())\n df_data = api.getHistoricalData(\n self.market, Granularity.SIX_HOURS, websocket\n )\n self.ema1226_6h_cache = df_data\n elif self.exchange == Exchange.KUCOIN:\n api = KPublicAPI(api_url=self.getAPIURL())\n df_data = api.getHistoricalData(\n self.market, Granularity.SIX_HOURS, websocket\n )\n self.ema1226_6h_cache = df_data\n else:\n return False\n\n ta = TechnicalAnalysis(df_data)\n\n if \"ema12\" not in df_data:\n ta.addEMA(12)\n\n if \"ema26\" not in df_data:\n ta.addEMA(26)\n\n df_last = ta.getDataFrame().copy().iloc[-1, :]\n df_last[\"bull\"] = df_last[\"ema12\"] > df_last[\"ema26\"]\n\n return bool(df_last[\"bull\"])\n except Exception:\n return False\n\n def is6hSMA50200Bull(self, websocket):\n try:\n if self.exchange == Exchange.COINBASEPRO:\n api = CBPublicAPI()\n df_data = api.getHistoricalData(\n self.market, Granularity.SIX_HOURS, websocket\n )\n elif self.exchange == Exchange.BINANCE:\n api = BPublicAPI(api_url=self.getAPIURL())\n df_data = api.getHistoricalData(\n self.market, Granularity.SIX_HOURS, websocket\n )\n elif self.exchange == Exchange.KUCOIN:\n api = KPublicAPI(api_url=self.getAPIURL())\n df_data = api.getHistoricalData(\n self.market, Granularity.SIX_HOURS, websocket\n )\n else:\n return False\n\n ta = TechnicalAnalysis(df_data)\n ta.addSMA(50)\n ta.addSMA(200)\n df_last = ta.getDataFrame().copy().iloc[-1, :]\n df_last[\"bull\"] = df_last[\"sma50\"] > df_last[\"sma200\"]\n return bool(df_last[\"bull\"])\n except Exception:\n return False\n\n def getTicker(self, market, websocket):\n if self.exchange == Exchange.BINANCE:\n api = BPublicAPI(api_url=self.getAPIURL())\n return api.getTicker(market, websocket)\n\n elif self.exchange == Exchange.KUCOIN:\n api = KPublicAPI(api_url=self.getAPIURL())\n return api.getTicker(market)\n else: # returns data from coinbase if not specified\n api = CBPublicAPI()\n return api.getTicker(market, websocket)\n\n def getTime(self):\n if self.exchange == Exchange.COINBASEPRO:\n return CBPublicAPI().getTime()\n elif self.exchange == Exchange.KUCOIN:\n return KPublicAPI().getTime()\n elif self.exchange == Exchange.BINANCE:\n try:\n return BPublicAPI().getTime()\n except ReadTimeoutError:\n return \"\"\n else:\n return \"\"\n\n def isLive(self) -> bool:\n return self.is_live == 1\n\n def isVerbose(self) -> bool:\n return self.is_verbose == 1\n\n def shouldSaveGraphs(self) -> bool:\n return self.save_graphs == 1\n\n def isSimulation(self) -> bool:\n return self.is_sim == 1\n\n def simuluationSpeed(self):\n return self.sim_speed\n\n def sellUpperPcnt(self):\n return self.sell_upper_pcnt\n\n def sellLowerPcnt(self):\n return self.sell_lower_pcnt\n\n def noSellMinPercent(self):\n return self.nosellminpcnt\n\n def noSellMaxPercent(self):\n return self.nosellmaxpcnt\n\n def trailingStopLoss(self):\n return self.trailing_stop_loss\n\n def noBuyNearHighPcnt(self) -> float:\n return self.nobuynearhighpcnt\n\n def trailingStopLossTrigger(self):\n return self.trailing_stop_loss_trigger\n\n def preventLoss(self):\n return self.preventloss\n\n def preventLossTrigger(self):\n return self.preventlosstrigger\n\n def preventLossMargin(self):\n return self.preventlossmargin\n\n def allowSellAtLoss(self) -> bool:\n return self.sell_at_loss == 1\n\n def simResultOnly(self) -> bool:\n return self.simresultonly\n\n def showConfigBuilder(self) -> bool:\n return self.configbuilder\n\n def sellAtResistance(self) -> bool:\n return self.sellatresistance\n\n def autoRestart(self) -> bool:\n return self.autorestart\n\n def getStats(self) -> bool:\n return self.stats\n\n def getLastAction(self):\n return self.last_action\n\n def disableBullOnly(self) -> bool:\n return self.disablebullonly\n\n def disableBuyNearHigh(self) -> bool:\n return self.disablebuynearhigh\n\n def disableBuyMACD(self) -> bool:\n return self.disablebuymacd\n\n def disableBuyEMA(self) -> bool:\n return self.disablebuyema\n\n def disableBuyOBV(self) -> bool:\n return self.disablebuyobv\n\n def disableBuyElderRay(self) -> bool:\n return self.disablebuyelderray\n \n def disableBuyAsm(self) -> bool:\n return self.disablebuyasm\n\n def disableFailsafeFibonacciLow(self) -> bool:\n return self.disablefailsafefibonaccilow\n\n def disableFailsafeLowerPcnt(self) -> bool:\n return self.disablefailsafelowerpcnt\n\n def disableProfitbankUpperPcnt(self) -> bool:\n return self.disableprofitbankupperpcnt\n\n def disableProfitbankReversal(self) -> bool:\n return self.disableprofitbankreversal\n\n def disableLog(self) -> bool:\n return self.disablelog\n\n def disableTracker(self) -> bool:\n return self.disabletracker\n\n def enableInsufficientFundsLogging(self) -> bool:\n return self.enableinsufficientfundslogging\n\n def enableTelegramBotControl(self) -> bool:\n return self.enabletelegrambotcontrol\n\n def enableImmediateBuy(self) -> bool:\n return self.enableimmediatebuy\n\n def telegramTradesOnly(self) -> bool:\n return self.telegramtradesonly\n\n def disableTelegramErrorMsgs(self) -> bool:\n return self.disabletelegramerrormsgs\n\n def enableML(self) -> bool:\n return self.enableml\n\n def enableWebsocket(self) -> bool:\n return self.websocket\n\n def enabledLogBuySellInJson(self) -> bool:\n return self.logbuysellinjson\n\n def setGranularity(self, granularity: Granularity):\n self.granularity = granularity\n\n def compare(self, val1, val2, label=\"\", precision=2):\n if val1 > val2:\n if label == \"\":\n return f\"{truncate(val1, precision)} > {truncate(val2, precision)}\"\n else:\n return f\"{label}: {truncate(val1, precision)} > {truncate(val2, precision)}\"\n if val1 < val2:\n if label == \"\":\n return f\"{truncate(val1, precision)} < {truncate(val2, precision)}\"\n else:\n return f\"{label}: {truncate(val1, precision)} < {truncate(val2, precision)}\"\n else:\n if label == \"\":\n return f\"{truncate(val1, precision)} = {truncate(val2, precision)}\"\n else:\n return f\"{label}: {truncate(val1, precision)} = {truncate(val2, precision)}\"\n\n def getLastBuy(self) -> dict:\n \"\"\"Retrieves the last exchange buy order and returns a dictionary\"\"\"\n\n try:\n if self.exchange == Exchange.COINBASEPRO:\n api = CBAuthAPI(\n self.getAPIKey(),\n self.getAPISecret(),\n self.getAPIPassphrase(),\n self.getAPIURL(),\n )\n orders = api.getOrders(self.getMarket(), \"\", \"done\")\n\n if len(orders) == 0:\n return None\n\n last_order = orders.tail(1)\n if last_order[\"action\"].values[0] != \"buy\":\n return None\n\n return {\n \"side\": \"buy\",\n \"market\": self.getMarket(),\n \"size\": float(last_order[\"size\"]),\n \"filled\": float(last_order[\"filled\"]),\n \"price\": float(last_order[\"price\"]),\n \"fee\": float(last_order[\"fees\"]),\n \"date\": str(\n pd.DatetimeIndex(\n pd.to_datetime(last_order[\"created_at\"]).dt.strftime(\n \"%Y-%m-%dT%H:%M:%S.%Z\"\n )\n )[0]\n ),\n }\n elif self.exchange == Exchange.KUCOIN:\n api = KAuthAPI(\n self.getAPIKey(),\n self.getAPISecret(),\n self.getAPIPassphrase(),\n self.getAPIURL(),\n )\n orders = api.getOrders(self.getMarket(), \"\", \"done\")\n\n if len(orders) == 0:\n return None\n\n last_order = orders.tail(1)\n if last_order[\"action\"].values[0] != \"buy\":\n return None\n\n return {\n \"side\": \"buy\",\n \"market\": self.getMarket(),\n \"size\": float(last_order[\"size\"]),\n \"filled\": float(last_order[\"filled\"]),\n \"price\": float(last_order[\"price\"]),\n \"fee\": float(last_order[\"fees\"]),\n \"date\": str(\n pd.DatetimeIndex(\n pd.to_datetime(last_order[\"created_at\"]).dt.strftime(\n \"%Y-%m-%dT%H:%M:%S.%Z\"\n )\n )[0]\n ),\n }\n elif self.exchange == Exchange.BINANCE:\n api = BAuthAPI(\n self.getAPIKey(),\n self.getAPISecret(),\n self.getAPIURL(),\n recv_window=self.recv_window,\n )\n orders = api.getOrders(self.getMarket())\n\n if len(orders) == 0:\n return None\n\n last_order = orders.tail(1)\n if last_order[\"action\"].values[0] != \"buy\":\n return None\n\n return {\n \"side\": \"buy\",\n \"market\": self.getMarket(),\n \"size\": float(last_order[\"size\"]),\n \"filled\": float(last_order[\"filled\"]),\n \"price\": float(last_order[\"price\"]),\n \"fees\": float(last_order[\"size\"] * 0.001),\n \"date\": str(\n pd.DatetimeIndex(\n pd.to_datetime(last_order[\"created_at\"]).dt.strftime(\n \"%Y-%m-%dT%H:%M:%S.%Z\"\n )\n )[0]\n ),\n }\n else:\n return None\n except Exception:\n return None\n\n def getTakerFee(self):\n if self.isSimulation() is True and self.exchange == Exchange.COINBASEPRO:\n return 0.005 # default lowest fee tier\n elif self.isSimulation() is True and self.exchange == Exchange.BINANCE:\n return 0.001 # default lowest fee tier\n elif self.isSimulation() is True and self.exchange == Exchange.KUCOIN:\n return 0.0015 # default lowest fee tier\n elif self.takerfee > 0.0:\n return self.takerfee\n elif self.exchange == Exchange.COINBASEPRO:\n api = CBAuthAPI(\n self.getAPIKey(),\n self.getAPISecret(),\n self.getAPIPassphrase(),\n self.getAPIURL(),\n )\n self.takerfee = api.getTakerFee()\n return self.takerfee\n elif self.exchange == Exchange.BINANCE:\n api = BAuthAPI(\n self.getAPIKey(),\n self.getAPISecret(),\n self.getAPIURL(),\n recv_window=self.recv_window,\n )\n self.takerfee = api.getTakerFee()\n return self.takerfee\n elif self.exchange == Exchange.KUCOIN:\n api = KAuthAPI(\n self.getAPIKey(),\n self.getAPISecret(),\n self.getAPIPassphrase(),\n self.getAPIURL(),\n )\n self.takerfee = api.getTakerFee()\n return self.takerfee\n else:\n return 0.005\n\n def getMakerFee(self):\n if self.exchange == Exchange.COINBASEPRO:\n api = CBAuthAPI(\n self.getAPIKey(),\n self.getAPISecret(),\n self.getAPIPassphrase(),\n self.getAPIURL(),\n )\n return api.getMakerFee()\n elif self.exchange == Exchange.BINANCE:\n api = BAuthAPI(\n self.getAPIKey(),\n self.getAPISecret(),\n self.getAPIURL(),\n recv_window=self.recv_window,\n )\n return api.getMakerFee()\n elif self.exchange == Exchange.KUCOIN:\n api = KAuthAPI(\n self.getAPIKey(),\n self.getAPISecret(),\n self.getAPIPassphrase(),\n self.getAPIURL(),\n )\n return api.getMakerFee()\n else:\n return 0.005\n\n def marketBuy(self, market, quote_currency, buy_percent=100):\n if self.is_live == 1:\n if isinstance(buy_percent, int):\n if buy_percent > 0 and buy_percent < 100:\n quote_currency = (buy_percent / 100) * quote_currency\n\n if self.exchange == Exchange.COINBASEPRO:\n api = CBAuthAPI(\n self.getAPIKey(),\n self.getAPISecret(),\n self.getAPIPassphrase(),\n self.getAPIURL(),\n )\n return api.marketBuy(market, float(truncate(quote_currency, 8)))\n elif self.exchange == Exchange.KUCOIN:\n api = KAuthAPI(\n self.getAPIKey(),\n self.getAPISecret(),\n self.getAPIPassphrase(),\n self.getAPIURL(),\n )\n return api.marketBuy(market, float(truncate(quote_currency, 8)))\n elif self.exchange == Exchange.BINANCE:\n api = BAuthAPI(\n self.getAPIKey(),\n self.getAPISecret(),\n self.getAPIURL(),\n recv_window=self.recv_window,\n )\n return api.marketBuy(market, quote_currency)\n else:\n return None\n\n def marketSell(self, market, base_currency, sell_percent=100):\n if self.is_live == 1:\n if isinstance(sell_percent, int):\n if sell_percent > 0 and sell_percent < 100:\n base_currency = (sell_percent / 100) * base_currency\n if self.exchange == Exchange.COINBASEPRO:\n api = CBAuthAPI(\n self.getAPIKey(),\n self.getAPISecret(),\n self.getAPIPassphrase(),\n self.getAPIURL(),\n )\n return api.marketSell(market, base_currency)\n elif self.exchange == Exchange.BINANCE:\n api = BAuthAPI(\n self.getAPIKey(),\n self.getAPISecret(),\n self.getAPIURL(),\n recv_window=self.recv_window,\n )\n return api.marketSell(market, base_currency)\n elif self.exchange == Exchange.KUCOIN:\n api = KAuthAPI(\n self.getAPIKey(),\n self.getAPISecret(),\n self.getAPIPassphrase(),\n self.getAPIURL(),\n )\n return api.marketSell(market, base_currency)\n else:\n return None\n\n def setMarket(self, market):\n if self.exchange == Exchange.BINANCE:\n self.market, self.base_currency, self.quote_currency = binanceParseMarket(\n market\n )\n\n elif self.exchange == Exchange.COINBASEPRO:\n (\n self.market,\n self.base_currency,\n self.quote_currency,\n ) = coinbaseProParseMarket(market)\n\n elif self.exchange == Exchange.KUCOIN:\n (self.market, self.base_currency, self.quote_currency) = kucoinParseMarket(\n market\n )\n\n return (self.market, self.base_currency, self.quote_currency)\n\n def setLive(self, flag):\n if isinstance(flag, int) and flag in [0, 1]:\n self.is_live = flag\n\n def setNoSellAtLoss(self, flag):\n if isinstance(flag, int) and flag in [0, 1]:\n self.sell_at_loss = flag\n\n def startApp(self, app, account, last_action=\"\", banner=True):\n if (\n banner\n and not self.isSimulation()\n or (self.isSimulation() and not self.simResultOnly())\n ):\n self._generate_banner()\n\n self.appStarted = True\n # run the first job immediately after starting\n if self.isSimulation():\n if self.simuluationSpeed() in [\"fast-sample\", \"slow-sample\"]:\n tradingData = pd.DataFrame()\n\n attempts = 0\n\n if self.simstartdate is not None and self.simenddate is not None:\n\n startDate = self.getDateFromISO8601Str(self.simstartdate)\n\n if self.simenddate == \"now\":\n endDate = self.getDateFromISO8601Str(str(datetime.now()))\n else:\n endDate = self.getDateFromISO8601Str(self.simenddate)\n\n elif self.simstartdate is not None and self.simenddate is None:\n # date = self.simstartdate.split('-')\n startDate = self.getDateFromISO8601Str(self.simstartdate)\n endDate = startDate + timedelta(\n minutes=(self.getGranularity().to_integer / 60) * 300\n )\n\n elif self.simenddate is not None and self.simstartdate is None:\n if self.simenddate == \"now\":\n endDate = self.getDateFromISO8601Str(str(datetime.now()))\n else:\n endDate = self.getDateFromISO8601Str(self.simenddate)\n\n startDate = endDate - timedelta(\n minutes=(self.getGranularity().to_integer / 60) * 300\n )\n\n else:\n endDate = self.getDateFromISO8601Str(\n str(pd.Series(datetime.now()).dt.round(freq=\"H\")[0])\n )\n if self.getExchange() == Exchange.COINBASEPRO:\n endDate -= timedelta(\n hours=random.randint(0, 8760 * 3)\n ) # 3 years in hours\n else:\n endDate -= timedelta(hours=random.randint(0, 8760 * 1))\n\n startDate = self.getDateFromISO8601Str(str(endDate))\n startDate -= timedelta(\n minutes=(self.getGranularity().to_integer / 60) * 300\n )\n\n while len(tradingData) < 300 and attempts < 10:\n if endDate.isoformat() > datetime.now().isoformat():\n endDate = datetime.now()\n if self.smart_switch == 1:\n tradingData = self.getSmartSwitchHistoricalDataChained(\n self.market,\n self.getGranularity(),\n str(startDate),\n str(endDate),\n )\n\n else:\n tradingData = self.getSmartSwitchDataFrame(\n tradingData,\n self.market,\n self.getGranularity(),\n startDate.isoformat(),\n endDate.isoformat(),\n )\n\n attempts += 1\n\n if self.extraCandlesFound:\n self.simstartdate = str(startDate)\n self.simenddate = str(endDate)\n\n self.extraCandlesFound = True\n\n if len(tradingData) < 300:\n raise Exception(\n \"Unable to retrieve 300 random sets of data between \"\n + str(startDate)\n + \" and \"\n + str(endDate)\n + \" in 10 attempts.\"\n )\n\n if banner:\n text_box = TextBox(80, 26)\n startDate = str(startDate.isoformat())\n endDate = str(endDate.isoformat())\n text_box.line(\"Sampling start\", str(startDate))\n text_box.line(\"Sampling end\", str(endDate))\n if self.simstartdate != None and len(tradingData) < 300:\n text_box.center(\"WARNING: Using less than 300 intervals\")\n text_box.line(\"Interval size\", str(len(tradingData)))\n text_box.doubleLine()\n\n else:\n tradingData = pd.DataFrame()\n\n startDate = self.getDateFromISO8601Str(str(datetime.now()))\n startDate -= timedelta(\n minutes=(self.getGranularity().to_integer / 60) * 2\n )\n endDate = startDate\n startDate = pd.Series(startDate).dt.round(freq=\"H\")[0]\n endDate = pd.Series(endDate).dt.round(freq=\"H\")[0]\n startDate -= timedelta(\n minutes=(self.getGranularity().to_integer / 60) * 300\n )\n\n if endDate.isoformat() > datetime.now().isoformat():\n endDate = datetime.now()\n\n if self.smart_switch == 1:\n tradingData = self.getSmartSwitchHistoricalDataChained(\n self.getMarket(),\n self.getGranularity(),\n str(startDate),\n str(endDate),\n )\n else:\n tradingData = self.getSmartSwitchDataFrame(\n tradingData,\n self.getMarket(),\n self.getGranularity(),\n self.getDateFromISO8601Str(str(startDate)).isoformat(),\n endDate.isoformat(),\n )\n\n if self.extraCandlesFound:\n self.simstartdate = str(pd.Series(startDate).dt.round(freq=\"H\")[0])\n self.simenddate = str(pd.Series(endDate).dt.round(freq=\"H\")[0])\n\n self.extraCandlesFound = True\n\n return tradingData\n\n def notifyTelegram(self, msg: str) -> None:\n \"\"\"\n Send a given message to preconfigured Telegram. If the telegram isn't enabled, e.g. via `--disabletelegram`,\n this method does nothing and returns immediately.\n \"\"\"\n\n if self.disabletelegram or not self.telegram:\n return\n\n assert self._chat_client is not None\n\n self._chat_client.send(msg)\n\n def _generate_banner(self) -> None:\n text_box = TextBox(80, 26)\n text_box.singleLine()\n text_box.center(\"Python Crypto Bot\")\n text_box.singleLine()\n text_box.line(\"Release\", self.getVersionFromREADME())\n text_box.singleLine()\n\n if self.isVerbose():\n text_box.line(\"Market\", self.getMarket())\n text_box.line(\"Granularity\", str(self.getGranularity()) + \" seconds\")\n text_box.singleLine()\n\n if self.isLive():\n text_box.line(\"Bot Mode\", \"LIVE - live trades using your funds!\")\n else:\n text_box.line(\"Bot Mode\", \"TEST - test trades using dummy funds :)\")\n\n text_box.line(\"Bot Started\", str(datetime.now()))\n text_box.line(\"Exchange\", str(self.exchange.value))\n text_box.doubleLine()\n\n if self.sellUpperPcnt() != None:\n text_box.line(\n \"Sell Upper\", str(self.sellUpperPcnt()) + \"% --sellupperpcnt <pcnt>\"\n )\n\n if self.sellLowerPcnt() != None:\n text_box.line(\n \"Sell Lower\", str(self.sellLowerPcnt()) + \"% --selllowerpcnt <pcnt>\"\n )\n\n if self.noSellMaxPercent() != None:\n text_box.line(\n \"No Sell Max\",\n str(self.noSellMaxPercent()) + \"% --nosellmaxpcnt <pcnt>\",\n )\n\n if self.noSellMinPercent() != None:\n text_box.line(\n \"No Sell Min\",\n str(self.noSellMinPercent()) + \"% --nosellminpcnt <pcnt>\",\n )\n\n if self.trailingStopLoss() != None:\n text_box.line(\n \"Trailing Stop Loss\",\n str(self.trailingStopLoss()) + \"% --trailingstoploss <pcnt>\",\n )\n\n if self.trailingStopLossTrigger() != None:\n text_box.line(\n \"Trailing Stop Loss Trg\",\n str(self.trailingStopLossTrigger()) + \"% --trailingstoplosstrigger\",\n )\n\n if self.preventLoss():\n text_box.line(\n \"Prevent Loss\",\n str(self.preventLoss()) + \" --preventloss\",\n )\n\n if self.preventLossTrigger() != None:\n text_box.line(\n \"Prevent Loss Trigger\",\n str(self.preventLossTrigger()) + \"% --preventlosstrigger\",\n )\n\n if self.preventLossMargin() != None:\n text_box.line(\n \"Prevent Loss Margin\",\n str(self.preventLossMargin()) + \"% --preventlossmargin\",\n )\n\n text_box.line(\"Sell At Loss\", str(self.allowSellAtLoss()) + \" --sellatloss \")\n text_box.line(\n \"Sell At Resistance\", str(self.sellAtResistance()) + \" --sellatresistance\"\n )\n text_box.line(\n \"Trade Bull Only\", str(not self.disableBullOnly()) + \" --disablebullonly\"\n )\n text_box.line(\n \"Allow Buy Near High\",\n str(not self.disableBuyNearHigh()) + \" --disablebuynearhigh\",\n )\n if self.disableBuyNearHigh():\n text_box.line(\n \"No Buy Near High Pcnt\",\n str(self.noBuyNearHighPcnt()) + \"% --nobuynearhighpcnt <pcnt>\",\n )\n text_box.line(\n \"Use Buy MACD\", str(not self.disableBuyMACD()) + \" --disablebuymacd\"\n )\n text_box.line(\n \"Use Buy EMA\", str(not self.disableBuyEMA()) + \" --disablebuyema\"\n )\n text_box.line(\n \"Use Buy OBV\", str(not self.disableBuyOBV()) + \" --disablebuyobv\"\n )\n text_box.line(\n \"Use Buy Elder-Ray\",\n str(not self.disableBuyElderRay()) + \" --disablebuyelderray\",\n )\n text_box.line(\n \"Use Buy ASM\", str(not self.disableBuyAsm()) + \" --disablebuyasm\"\n )\n text_box.line(\n \"Sell Fibonacci Low\",\n str(not self.disableFailsafeFibonacciLow())\n + \" --disablefailsafefibonaccilow\",\n )\n\n if self.sellLowerPcnt() != None:\n text_box.line(\n \"Sell Lower Pcnt\",\n str(not self.disableFailsafeLowerPcnt())\n + \" --disablefailsafelowerpcnt\",\n )\n\n if self.sellUpperPcnt() != None:\n text_box.line(\n \"Sell Upper Pcnt\",\n str(not self.disableFailsafeLowerPcnt())\n + \" --disableprofitbankupperpcnt\",\n )\n\n text_box.line(\n \"Candlestick Reversal\",\n str(not self.disableProfitbankReversal()) + \" --disableprofitbankreversal\",\n )\n text_box.line(\"Telegram\", str(not self.disabletelegram) + \" --disabletelegram\")\n\n if not self.disabletelegram:\n text_box.line(\n \"Telegram trades only\",\n str(self.telegramTradesOnly()) + \" --telegramtradesonly\",\n )\n\n if not self.disabletelegram:\n text_box.line(\n \"Telegram error msgs\",\n str(not self.disableTelegramErrorMsgs())\n + \" --disabletelegramerrormsgs\",\n )\n\n text_box.line(\"Log\", str(not self.disableLog()) + \" --disablelog\")\n text_box.line(\"Tracker\", str(not self.disableTracker()) + \" --disabletracker\")\n text_box.line(\"Auto restart Bot\", str(self.autoRestart()) + \" --autorestart\")\n text_box.line(\"Web Socket\", str(self.websocket) + \" --websocket\")\n text_box.line(\n \"Insufficient Funds Logging\",\n str(self.enableinsufficientfundslogging)\n + \" --enableinsufficientfundslogging\",\n )\n text_box.line(\n \"Log Buy and Sell orders in JSON\",\n str(self.logbuysellinjson) + \" --logbuysellinjson\",\n )\n\n if self.getBuyMaxSize():\n text_box.line(\n \"Max Buy Size\", str(self.getBuyMaxSize()) + \" --buymaxsize <size>\"\n )\n\n\n if self.getBuyMinSize():\n text_box.line(\n \"Min Buy Size\", str(self.getBuyMinSize()) + \" --buyminsize <size>\")\n\n if self.buyLastSellSize():\n text_box.line(\n \"Buy Last Sell Size\",\n str(self.buyLastSellSize()) + \" --buylastsellsize\",\n )\n\n if self.getTrailingBuyPcnt():\n text_box.line(\n \"Trailing Buy Percent\", str(self.getTrailingBuyPcnt()) + \" --trailingbuypcnt <size>\"\n )\n\n if self.trailingImmediateBuy():\n text_box.line(\n \"Immediate buy for trailingbuypcnt\",\n str(self.trailingImmediateBuy()) + \" --trailingImmediateBuy\",\n )\n\n if self.marketMultiBuyCheck():\n text_box.line(\n \"Check for Market Multiple Buys\",\n str(self.marketMultiBuyCheck()) + \" --marketmultibuycheck\",\n )\n\n if self.disablebuyema and self.disablebuymacd and self.disablebuyasm:\n text_box.center(\n \"WARNING : EMA, MACD, and ASM indicators disabled, no buy events will happen\"\n )\n\n text_box.doubleLine()\n"
] | [
[
"pandas.concat",
"pandas.to_datetime",
"pandas.Series",
"pandas.DataFrame",
"pandas.set_option"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ramchandracheke/self-supervised-3d-tasks | [
"dc184d5d29012fafb887402c5bc2ce74e4b0acdf"
] | [
"self_supervised_3d_tasks/data/numpy_3d_loader.py"
] | [
"import os\n\nimport numpy as np\nfrom self_supervised_3d_tasks.data.generator_base import DataGeneratorBase\n\n\nclass DataGeneratorUnlabeled3D(DataGeneratorBase):\n\n def __init__(self, data_path, file_list, batch_size=32, shuffle=True, pre_proc_func=None):\n self.path_to_data = data_path\n\n super().__init__(file_list, batch_size, shuffle, pre_proc_func)\n\n def data_generation(self, list_files_temp):\n data_x = []\n data_y = []\n\n for file_name in list_files_temp:\n path_to_image = \"{}/{}\".format(self.path_to_data, file_name)\n if os.path.isfile(path_to_image):\n img = np.load(path_to_image)\n img = (img - img.min()) / (img.max() - img.min())\n\n data_x.append(img)\n data_y.append(0) # just to keep the dims right\n\n data_x = np.stack(data_x)\n data_y = np.stack(data_y)\n\n return data_x, data_y\n\n\nclass PatchDataGeneratorUnlabeled3D(DataGeneratorBase):\n\n def __init__(self, data_path, file_list, batch_size=32, patch_size=(128, 128, 128), patches_per_scan=2,\n shuffle=True, pre_proc_func=None):\n self.path_to_data = data_path\n self.patch_size = patch_size\n self.patches_per_scan = patches_per_scan\n\n super().__init__(file_list, batch_size, shuffle, pre_proc_func)\n\n def data_generation(self, list_files_temp):\n data_x = []\n data_y = []\n\n for file_name in list_files_temp:\n path_to_image = \"{}/{}\".format(self.path_to_data, file_name)\n if os.path.isfile(path_to_image):\n img = np.load(path_to_image)\n img = (img - img.min()) / (img.max() - img.min())\n\n origin_row = np.random.randint(0, img.shape[0] - self.patch_size[0], self.patches_per_scan)\n origin_col = np.random.randint(0, img.shape[1] - self.patch_size[1], self.patches_per_scan)\n origin_dep = np.random.randint(0, img.shape[2] - self.patch_size[2], self.patches_per_scan)\n\n for o_r, o_c, o_d in zip(origin_row, origin_col, origin_dep):\n data_x.append(\n img[o_r:o_r + self.patch_size[0], o_c:o_c + self.patch_size[1], o_d:o_d + self.patch_size[2]])\n data_y.append(0) # just to keep the dims right\n\n data_x = np.stack(data_x)\n data_y = np.stack(data_y)\n\n return data_x, data_y\n"
] | [
[
"numpy.load",
"numpy.stack",
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
phunc20/rlcomp2020 | [
"c37f8f05cc86d55fca2648bf5491d6a2218c2cad",
"c37f8f05cc86d55fca2648bf5491d6a2218c2cad",
"c37f8f05cc86d55fca2648bf5491d6a2218c2cad",
"c37f8f05cc86d55fca2648bf5491d6a2218c2cad"
] | [
"round01/30_11_dDQN_light_tweak73.py",
"hint/01-theo-BTC/02_DQN-5-cations/02_closest-gold/Miner-Training-Local-CodeSample-Approach1/viz_utils.py",
"round02/02_dQN_6act_debug/22_5channel.py",
"round01/30_11_dDQN_light_tweak22.py"
] | [
"########################################\n# Changes compared to 30_11_dDQN_light_tweak71.py\n# 01. \n# lr_optimizer = 7.3e-4\n########################################\n\n\nimport sys\nimport numpy as np\n#import pandas as pd\nimport datetime\nimport json\nfrom array import *\nimport os\nimport math\nfrom random import randrange\nimport random\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.models import model_from_json\nfrom tensorflow.keras.layers import Dense, Activation\nfrom tensorflow.keras import optimizers\n\nimport tensorflow.keras as keras\n\n#import tensorflow.compat.v1 as tf\n#from tensorflow.compat.v1.keras import backend as K\n#tf.disable_v2_behavior()\nimport tensorflow as tf\nfrom tensorflow.keras import backend as K\n\nimport constants\nimport non_RL_agent\nimport non_RL_agent02\nimport non_RL_agent03\nimport non_RL_agent04\nimport non_RL_agent05\nimport non_RL_agent06\n\nn_episodes = 500_000\n#n_epsilon_decay = int(n_episodes*.6)\n#n_epsilon_decay = int(n_episodes*.805)\n#n_epsilon_decay = 10**6 / 0.99\nn_epsilon_decay = int(n_episodes // 50)\nn_episodes_buf_fill = 10_000\nbatch_size = 32\ndiscount_rate = 0.95\n#lr_optimizer = 2.5e-4\nlr_optimizer = 7.3e-4\n#loss_fn = keras.losses.mean_squared_error\nloss_fn = keras.losses.Huber()\nmax_replay_len = 50_000\n\n\n#Classes in GAME_SOCKET_DUMMY.py\nclass ObstacleInfo:\n # initial energy for obstacles: Land (key = 0): -1, Forest(key = -1): 0 (random), Trap(key = -2): -10, Swamp (key = -3): -5\n types = {0: -1, -1: 0, -2: -10, -3: -5}\n\n def __init__(self):\n self.type = 0\n self.posx = 0\n self.posy = 0\n self.value = 0\n \nclass GoldInfo:\n def __init__(self):\n self.posx = 0\n self.posy = 0\n self.amount = 0\n\n def loads(self, data):\n golds = []\n for gd in data:\n g = GoldInfo()\n g.posx = gd[\"posx\"]\n g.posy = gd[\"posy\"]\n g.amount = gd[\"amount\"]\n golds.append(g)\n return golds\n\nclass PlayerInfo:\n STATUS_PLAYING = 0\n STATUS_ELIMINATED_WENT_OUT_MAP = 1\n STATUS_ELIMINATED_OUT_OF_ENERGY = 2\n STATUS_ELIMINATED_INVALID_ACTION = 3\n STATUS_STOP_EMPTY_GOLD = 4\n STATUS_STOP_END_STEP = 5\n\n def __init__(self, id):\n self.playerId = id\n self.score = 0\n self.energy = 0\n self.posx = 0\n self.posy = 0\n self.lastAction = -1\n self.status = PlayerInfo.STATUS_PLAYING\n self.freeCount = 0\n\nclass GameInfo:\n def __init__(self):\n self.numberOfPlayers = 1\n self.width = 0\n self.height = 0\n self.steps = 100\n self.golds = []\n self.obstacles = []\n\n def loads(self, data):\n m = GameInfo()\n m.width = data[\"width\"]\n m.height = data[\"height\"]\n m.golds = GoldInfo().loads(data[\"golds\"])\n m.obstacles = data[\"obstacles\"]\n m.numberOfPlayers = data[\"numberOfPlayers\"]\n m.steps = data[\"steps\"]\n return m\n\nclass UserMatch:\n def __init__(self):\n self.playerId = 1\n self.posx = 0\n self.posy = 0\n self.energy = 50\n self.gameinfo = GameInfo()\n\n def to_json(self):\n return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4)\n\nclass StepState:\n def __init__(self):\n self.players = []\n self.golds = []\n self.changedObstacles = []\n\n def to_json(self):\n return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4)\n\n\n#Main class in GAME_SOCKET_DUMMY.py\nclass GameSocket:\n bog_energy_chain = {-5: -20, -20: -40, -40: -100, -100: -100}\n\n def __init__(self):\n self.stepCount = 0\n self.maxStep = 0\n self.mapdir = \"Maps\" # where to load all pre-defined maps\n self.mapid = \"\"\n self.userMatch = UserMatch()\n self.user = PlayerInfo(1)\n self.stepState = StepState()\n self.maps = {} # key: map file name, value: file content\n self.map = [] # running map info: 0->Land, -1->Forest, -2->Trap, -3:Swamp, >0:Gold\n self.energyOnMap = [] # self.energyOnMap[x][y]: <0, amount of energy which player will consume if it move into (x,y)\n self.E = 50\n self.resetFlag = True\n self.craftUsers = [] # players that craft at current step - for calculating amount of gold\n self.bots = []\n self.craftMap = {} # cells that players craft at current step, key: x_y, value: number of players that craft at (x,y)\n\n def init_bots(self):\n self.bots = [Bot1(2), Bot2(3), Bot3(4)] # use bot1(id=2), bot2(id=3), bot3(id=4)\n #for (bot) in self.bots: # at the beginning, all bots will have same position, energy as player\n for bot in self.bots: # at the beginning, all bots will have same position, energy as player\n bot.info.posx = self.user.posx\n bot.info.posy = self.user.posy\n bot.info.energy = self.user.energy\n bot.info.lastAction = -1\n bot.info.status = PlayerInfo.STATUS_PLAYING\n bot.info.score = 0\n self.stepState.players.append(bot.info)\n self.userMatch.gameinfo.numberOfPlayers = len(self.stepState.players)\n #print(\"numberOfPlayers: \", self.userMatch.gameinfo.numberOfPlayers)\n\n def reset(self, requests): # load new game by given request: [map id (filename), posx, posy, initial energy]\n # load new map\n self.reset_map(requests[0])\n self.userMatch.posx = int(requests[1])\n self.userMatch.posy = int(requests[2])\n self.userMatch.energy = int(requests[3])\n self.userMatch.gameinfo.steps = int(requests[4])\n self.maxStep = self.userMatch.gameinfo.steps\n\n # init data for players\n self.user.posx = self.userMatch.posx # in\n self.user.posy = self.userMatch.posy\n self.user.energy = self.userMatch.energy\n self.user.status = PlayerInfo.STATUS_PLAYING\n self.user.score = 0\n self.stepState.players = [self.user]\n self.E = self.userMatch.energy\n self.resetFlag = True\n self.init_bots()\n self.stepCount = 0\n\n def reset_map(self, id): # load map info\n self.mapId = id\n self.map = json.loads(self.maps[self.mapId])\n self.userMatch = self.map_info(self.map)\n self.stepState.golds = self.userMatch.gameinfo.golds\n self.map = json.loads(self.maps[self.mapId])\n self.energyOnMap = json.loads(self.maps[self.mapId])\n for x in range(len(self.map)):\n for y in range(len(self.map[x])):\n if self.map[x][y] > 0: # gold\n self.energyOnMap[x][y] = -4\n else: # obstacles\n self.energyOnMap[x][y] = ObstacleInfo.types[self.map[x][y]]\n\n def connect(self): # simulate player's connect request\n print(\"Connected to server.\")\n for mapid in range(len(Maps)):\n filename = \"map\" + str(mapid)\n print(\"Found: \" + filename)\n self.maps[filename] = str(Maps[mapid])\n\n def map_info(self, map): # get map info\n # print(map)\n userMatch = UserMatch()\n userMatch.gameinfo.height = len(map)\n userMatch.gameinfo.width = len(map[0])\n i = 0\n while i < len(map):\n j = 0\n while j < len(map[i]):\n if map[i][j] > 0: # gold\n g = GoldInfo()\n g.posx = j\n g.posy = i\n g.amount = map[i][j]\n userMatch.gameinfo.golds.append(g)\n else: # obstacles\n o = ObstacleInfo()\n o.posx = j\n o.posy = i\n o.type = -map[i][j]\n o.value = ObstacleInfo.types[map[i][j]]\n userMatch.gameinfo.obstacles.append(o)\n j += 1\n i += 1\n return userMatch\n\n def receive(self): # send data to player (simulate player's receive request)\n if self.resetFlag: # for the first time -> send game info\n self.resetFlag = False\n data = self.userMatch.to_json()\n for (bot) in self.bots:\n bot.new_game(data)\n # print(data)\n return data\n else: # send step state\n self.stepCount = self.stepCount + 1\n if self.stepCount >= self.maxStep:\n for player in self.stepState.players:\n player.status = PlayerInfo.STATUS_STOP_END_STEP\n data = self.stepState.to_json()\n #for (bot) in self.bots: # update bots' state\n for bot in self.bots: # update bots' state\n bot.new_state(data)\n # print(data)\n return data\n\n def send(self, message): # receive message from player (simulate send request from player)\n if message.isnumeric(): # player send action\n self.resetFlag = False\n self.stepState.changedObstacles = []\n action = int(message)\n # print(\"Action = \", action)\n self.user.lastAction = action\n self.craftUsers = []\n self.step_action(self.user, action)\n for bot in self.bots:\n if bot.info.status == PlayerInfo.STATUS_PLAYING:\n action = bot.next_action()\n bot.info.lastAction = action\n # print(\"Bot Action: \", action)\n self.step_action(bot.info, action)\n self.action_5_craft()\n for c in self.stepState.changedObstacles:\n self.map[c[\"posy\"]][c[\"posx\"]] = -c[\"type\"]\n self.energyOnMap[c[\"posy\"]][c[\"posx\"]] = c[\"value\"]\n\n else: # reset game\n requests = message.split(\",\")\n #print(\"Reset game: \", requests[:3], end='')\n self.reset(requests)\n\n def step_action(self, user, action):\n switcher = {\n 0: self.action_0_left,\n 1: self.action_1_right,\n 2: self.action_2_up,\n 3: self.action_3_down,\n 4: self.action_4_free,\n 5: self.action_5_craft_pre\n }\n func = switcher.get(action, self.invalidAction)\n func(user)\n\n def action_5_craft_pre(self, user): # collect players who craft at current step\n user.freeCount = 0\n if self.map[user.posy][user.posx] <= 0: # craft at the non-gold cell\n user.energy -= 10\n if user.energy <= 0:\n user.status = PlayerInfo.STATUS_ELIMINATED_OUT_OF_ENERGY\n user.lastAction = 6 #eliminated\n else:\n user.energy -= 5\n if user.energy > 0:\n self.craftUsers.append(user)\n key = str(user.posx) + \"_\" + str(user.posy)\n if key in self.craftMap:\n count = self.craftMap[key]\n self.craftMap[key] = count + 1\n else:\n self.craftMap[key] = 1\n else:\n user.status = PlayerInfo.STATUS_ELIMINATED_OUT_OF_ENERGY\n user.lastAction = 6 #eliminated\n\n def action_0_left(self, user): # user go left\n user.freeCount = 0\n user.posx = user.posx - 1\n if user.posx < 0:\n user.status = PlayerInfo.STATUS_ELIMINATED_WENT_OUT_MAP\n user.lastAction = 6 #eliminated\n else:\n self.go_to_pos(user)\n\n def action_1_right(self, user): # user go right\n user.freeCount = 0\n user.posx = user.posx + 1\n if user.posx >= self.userMatch.gameinfo.width:\n user.status = PlayerInfo.STATUS_ELIMINATED_WENT_OUT_MAP\n user.lastAction = 6 #eliminated\n else:\n self.go_to_pos(user)\n\n def action_2_up(self, user): # user go up\n user.freeCount = 0\n user.posy = user.posy - 1\n if user.posy < 0:\n user.status = PlayerInfo.STATUS_ELIMINATED_WENT_OUT_MAP\n user.lastAction = 6 #eliminated\n else:\n self.go_to_pos(user)\n\n def action_3_down(self, user): # user go right\n user.freeCount = 0\n user.posy = user.posy + 1\n if user.posy >= self.userMatch.gameinfo.height:\n user.status = PlayerInfo.STATUS_ELIMINATED_WENT_OUT_MAP\n user.lastAction = 6 #eliminated\n else:\n self.go_to_pos(user)\n\n def action_4_free(self, user): # user free\n user.freeCount += 1\n if user.freeCount == 1:\n user.energy += int(self.E / 4)\n elif user.freeCount == 2:\n user.energy += int(self.E / 3)\n elif user.freeCount == 3:\n user.energy += int(self.E / 2)\n else:\n user.energy = self.E\n if user.energy > self.E:\n user.energy = self.E\n\n def action_5_craft(self):\n craftCount = len(self.craftUsers)\n # print (\"craftCount\",craftCount)\n if (craftCount > 0):\n for user in self.craftUsers:\n x = user.posx\n y = user.posy\n key = str(user.posx) + \"_\" + str(user.posy)\n c = self.craftMap[key]\n m = min(math.ceil(self.map[y][x] / c), 50)\n user.score += m\n # print (\"user\", user.playerId, m)\n for user in self.craftUsers:\n x = user.posx\n y = user.posy\n key = str(user.posx) + \"_\" + str(user.posy)\n if key in self.craftMap:\n c = self.craftMap[key]\n del self.craftMap[key]\n m = min(math.ceil(self.map[y][x] / c), 50)\n self.map[y][x] -= m * c\n if self.map[y][x] < 0:\n self.map[y][x] = 0\n self.energyOnMap[y][x] = ObstacleInfo.types[0]\n for g in self.stepState.golds:\n if g.posx == x and g.posy == y:\n g.amount = self.map[y][x]\n if g.amount == 0:\n self.stepState.golds.remove(g)\n self.add_changed_obstacle(x, y, 0, ObstacleInfo.types[0])\n if len(self.stepState.golds) == 0:\n for player in self.stepState.players:\n player.status = PlayerInfo.STATUS_STOP_EMPTY_GOLD\n break;\n self.craftMap = {}\n\n def invalidAction(self, user):\n user.status = PlayerInfo.STATUS_ELIMINATED_INVALID_ACTION\n user.lastAction = 6 #eliminated\n\n def go_to_pos(self, user): # player move to cell(x,y)\n if self.map[user.posy][user.posx] == -1:\n user.energy -= randrange(16) + 5\n elif self.map[user.posy][user.posx] == 0:\n user.energy += self.energyOnMap[user.posy][user.posx]\n elif self.map[user.posy][user.posx] == -2:\n user.energy += self.energyOnMap[user.posy][user.posx]\n self.add_changed_obstacle(user.posx, user.posy, 0, ObstacleInfo.types[0])\n elif self.map[user.posy][user.posx] == -3:\n user.energy += self.energyOnMap[user.posy][user.posx]\n self.add_changed_obstacle(user.posx, user.posy, 3,\n self.bog_energy_chain[self.energyOnMap[user.posy][user.posx]])\n else:\n user.energy -= 4\n if user.energy <= 0:\n user.status = PlayerInfo.STATUS_ELIMINATED_OUT_OF_ENERGY\n user.lastAction = 6 #eliminated\n\n def add_changed_obstacle(self, x, y, t, v):\n added = False\n for o in self.stepState.changedObstacles:\n if o[\"posx\"] == x and o[\"posy\"] == y:\n added = True\n break\n if added == False:\n o = {}\n o[\"posx\"] = x\n o[\"posy\"] = y\n o[\"type\"] = t\n o[\"value\"] = v\n self.stepState.changedObstacles.append(o)\n\n def close(self):\n print(\"Close socket.\")\n\nclass Bot1:\n ACTION_GO_LEFT = 0\n ACTION_GO_RIGHT = 1\n ACTION_GO_UP = 2\n ACTION_GO_DOWN = 3\n ACTION_FREE = 4\n ACTION_CRAFT = 5\n\n def __init__(self, id):\n self.state = State()\n self.info = PlayerInfo(id)\n \n def get_state(self):\n view = np.zeros([self.state.mapInfo.max_y + 1, self.state.mapInfo.max_x + 1], dtype=int)\n for x in range(self.state.mapInfo.max_x + 1):\n for y in range(self.state.mapInfo.max_y + 1):\n if self.state.mapInfo.get_obstacle(x, y) == TreeID: # Tree\n view[y, x] = -TreeID\n if self.state.mapInfo.get_obstacle(x, y) == TrapID: # Trap\n view[y, x] = -TrapID\n if self.state.mapInfo.get_obstacle(x, y) == SwampID: # Swamp\n view[y, x] = -SwampID\n if self.state.mapInfo.gold_amount(x, y) > 0:\n view[y, x] = self.state.mapInfo.gold_amount(x, y)\n\n DQNState = view.flatten().tolist() #Flattening the map matrix to a vector\n \n #DQNState.append(self.state.x)\n #DQNState.append(self.state.y)\n #DQNState.append(self.state.energy)\n DQNState.append(self.info.posx)\n DQNState.append(self.info.posy)\n DQNState.append(self.info.energy)\n for player in self.state.players:\n # self.info.playerId is the id of the current bot\n if player[\"playerId\"] != self.info.playerId:\n DQNState.append(player[\"posx\"])\n DQNState.append(player[\"posy\"])\n \n DQNState = np.array(DQNState)\n\n return DQNState\n\n\n def next_action(self):\n s = self.get_state()\n #return int(greedy_policy(s))\n return int(non_RL_agent.greedy_policy(s))\n\n def get_score(self):\n return [player[\"score\"] for player in minerEnv.socket.bots[1].state.players if player[\"playerId\"] == self.info.playerId][0]\n\n def new_game(self, data):\n try:\n self.state.init_state(data)\n except Exception as e:\n import traceback\n traceback.print_exc()\n\n def new_state(self, data):\n # action = self.next_action();\n # self.socket.send(action)\n try:\n self.state.update_state(data)\n except Exception as e:\n import traceback\n traceback.print_exc()\n\nclass Bot2:\n ACTION_GO_LEFT = 0\n ACTION_GO_RIGHT = 1\n ACTION_GO_UP = 2\n ACTION_GO_DOWN = 3\n ACTION_FREE = 4\n ACTION_CRAFT = 5\n\n def __init__(self, id):\n self.state = State()\n self.info = PlayerInfo(id)\n \n def get_state(self):\n view = np.zeros([self.state.mapInfo.max_y + 1, self.state.mapInfo.max_x + 1], dtype=int)\n for x in range(self.state.mapInfo.max_x + 1):\n for y in range(self.state.mapInfo.max_y + 1):\n if self.state.mapInfo.get_obstacle(x, y) == TreeID: # Tree\n view[y, x] = -TreeID\n if self.state.mapInfo.get_obstacle(x, y) == TrapID: # Trap\n view[y, x] = -TrapID\n if self.state.mapInfo.get_obstacle(x, y) == SwampID: # Swamp\n view[y, x] = -SwampID\n if self.state.mapInfo.gold_amount(x, y) > 0:\n view[y, x] = self.state.mapInfo.gold_amount(x, y)\n\n DQNState = view.flatten().tolist() #Flattening the map matrix to a vector\n \n #DQNState.append(self.state.x)\n #DQNState.append(self.state.y)\n #DQNState.append(self.state.energy)\n DQNState.append(self.info.posx)\n DQNState.append(self.info.posy)\n DQNState.append(self.info.energy)\n for player in self.state.players:\n # self.info.playerId is the id of the current bot\n if player[\"playerId\"] != self.info.playerId:\n DQNState.append(player[\"posx\"])\n DQNState.append(player[\"posy\"])\n \n DQNState = np.array(DQNState)\n\n return DQNState\n\n\n\n\n def next_action(self):\n s = self.get_state()\n #return int(non_RL_agent03.greedy_policy(s))\n return int(non_RL_agent.greedy_policy(s, how_gold=non_RL_agent.find_worthiest_gold))\n \n #if self.state.mapInfo.gold_amount(self.info.posx, self.info.posy) > 0:\n # if self.info.energy >= 6:\n # return self.ACTION_CRAFT\n # else:\n # return self.ACTION_FREE\n #if self.info.energy < 5:\n # return self.ACTION_FREE\n #else:\n # action = np.random.randint(0, 4) \n # return action\n\n\n def new_game(self, data):\n try:\n self.state.init_state(data)\n except Exception as e:\n import traceback\n traceback.print_exc()\n\n def new_state(self, data):\n # action = self.next_action();\n # self.socket.send(action)\n try:\n self.state.update_state(data)\n except Exception as e:\n import traceback\n traceback.print_exc()\n \n def get_score(self):\n return [player[\"score\"] for player in minerEnv.socket.bots[1].state.players if player[\"playerId\"] == self.info.playerId][0]\n\nclass Bot3:\n ACTION_GO_LEFT = 0\n ACTION_GO_RIGHT = 1\n ACTION_GO_UP = 2\n ACTION_GO_DOWN = 3\n ACTION_FREE = 4\n ACTION_CRAFT = 5\n\n def __init__(self, id):\n self.state = State()\n self.info = PlayerInfo(id)\n\n def get_state(self):\n view = np.zeros([self.state.mapInfo.max_y + 1, self.state.mapInfo.max_x + 1], dtype=int)\n for x in range(self.state.mapInfo.max_x + 1):\n for y in range(self.state.mapInfo.max_y + 1):\n if self.state.mapInfo.get_obstacle(x, y) == TreeID: # Tree\n view[y, x] = -TreeID\n if self.state.mapInfo.get_obstacle(x, y) == TrapID: # Trap\n view[y, x] = -TrapID\n if self.state.mapInfo.get_obstacle(x, y) == SwampID: # Swamp\n view[y, x] = -SwampID\n if self.state.mapInfo.gold_amount(x, y) > 0:\n view[y, x] = self.state.mapInfo.gold_amount(x, y)\n\n DQNState = view.flatten().tolist() #Flattening the map matrix to a vector\n \n #DQNState.append(self.state.x)\n #DQNState.append(self.state.y)\n #DQNState.append(self.state.energy)\n DQNState.append(self.info.posx)\n DQNState.append(self.info.posy)\n DQNState.append(self.info.energy)\n for player in self.state.players:\n # self.info.playerId is the id of the current bot\n if player[\"playerId\"] != self.info.playerId:\n DQNState.append(player[\"posx\"])\n DQNState.append(player[\"posy\"])\n \n DQNState = np.array(DQNState)\n\n return DQNState\n\n\n def next_action(self):\n s = self.get_state()\n return int(non_RL_agent02.greedy_policy(s))\n #if self.state.mapInfo.gold_amount(self.info.posx, self.info.posy) > 0:\n # if self.info.energy >= 6:\n # return self.ACTION_CRAFT\n # else:\n # return self.ACTION_FREE\n #if self.info.energy < 5:\n # return self.ACTION_FREE\n #else:\n # action = self.ACTION_GO_LEFT\n # if self.info.posx % 2 == 0:\n # if self.info.posy < self.state.mapInfo.max_y:\n # action = self.ACTION_GO_DOWN\n # else:\n # if self.info.posy > 0:\n # action = self.ACTION_GO_UP\n # else:\n # action = self.ACTION_GO_RIGHT \n # return action\n\n def new_game(self, data):\n try:\n self.state.init_state(data)\n except Exception as e:\n import traceback\n traceback.print_exc()\n\n def new_state(self, data):\n # action = self.next_action();\n # self.socket.send(action)\n try:\n self.state.update_state(data)\n except Exception as e:\n import traceback\n traceback.print_exc()\n \n def get_score(self):\n return [player[\"score\"] for player in minerEnv.socket.bots[1].state.players if player[\"playerId\"] == self.info.playerId][0]\n\n\n#MinerState.py\ndef str_2_json(str):\n return json.loads(str, encoding=\"utf-8\")\n\n\nclass MapInfo:\n def __init__(self):\n self.max_x = 0 #Width of the map\n self.max_y = 0 #Height of the map\n self.golds = [] #List of the golds in the map\n self.obstacles = []\n self.numberOfPlayers = 0\n self.maxStep = 0 #The maximum number of step is set for this map\n\n def init_map(self, gameInfo):\n #Initialize the map at the begining of each episode\n self.max_x = gameInfo[\"width\"] - 1\n self.max_y = gameInfo[\"height\"] - 1\n self.golds = gameInfo[\"golds\"]\n self.obstacles = gameInfo[\"obstacles\"]\n self.maxStep = gameInfo[\"steps\"]\n self.numberOfPlayers = gameInfo[\"numberOfPlayers\"]\n\n def update(self, golds, changedObstacles):\n #Update the map after every step\n self.golds = golds\n for cob in changedObstacles:\n newOb = True\n for ob in self.obstacles:\n if cob[\"posx\"] == ob[\"posx\"] and cob[\"posy\"] == ob[\"posy\"]:\n newOb = False\n #print(\"cell(\", cob[\"posx\"], \",\", cob[\"posy\"], \") change type from: \", ob[\"type\"], \" -> \",\n # cob[\"type\"], \" / value: \", ob[\"value\"], \" -> \", cob[\"value\"])\n ob[\"type\"] = cob[\"type\"]\n ob[\"value\"] = cob[\"value\"]\n break\n if newOb:\n self.obstacles.append(cob)\n #print(\"new obstacle: \", cob[\"posx\"], \",\", cob[\"posy\"], \", type = \", cob[\"type\"], \", value = \",\n # cob[\"value\"])\n\n def get_min_x(self):\n return min([cell[\"posx\"] for cell in self.golds])\n\n def get_max_x(self):\n return max([cell[\"posx\"] for cell in self.golds])\n\n def get_min_y(self):\n return min([cell[\"posy\"] for cell in self.golds])\n\n def get_max_y(self):\n return max([cell[\"posy\"] for cell in self.golds])\n\n def is_row_has_gold(self, y):\n return y in [cell[\"posy\"] for cell in self.golds]\n\n def is_column_has_gold(self, x):\n return x in [cell[\"posx\"] for cell in self.golds]\n\n def gold_amount(self, x, y): #Get the amount of golds at cell (x,y)\n for cell in self.golds:\n if x == cell[\"posx\"] and y == cell[\"posy\"]:\n return cell[\"amount\"]\n return 0 \n\n def get_obstacle(self, x, y): # Get the kind of the obstacle at cell(x,y)\n for cell in self.obstacles:\n if x == cell[\"posx\"] and y == cell[\"posy\"]:\n return cell[\"type\"]\n return -1 # No obstacle at the cell (x,y)\n\n\nclass State:\n STATUS_PLAYING = 0\n STATUS_ELIMINATED_WENT_OUT_MAP = 1\n STATUS_ELIMINATED_OUT_OF_ENERGY = 2\n STATUS_ELIMINATED_INVALID_ACTION = 3\n STATUS_STOP_EMPTY_GOLD = 4\n STATUS_STOP_END_STEP = 5\n\n def __init__(self):\n self.end = False\n self.score = 0\n self.lastAction = None\n self.id = 0\n self.x = 0\n self.y = 0\n self.energy = 0\n self.energy_pre = 0\n self.mapInfo = MapInfo()\n self.players = []\n self.stepCount = 0\n self.status = State.STATUS_PLAYING\n\n def init_state(self, data): #parse data from server into object\n game_info = str_2_json(data)\n self.end = False\n self.score = 0\n self.lastAction = None\n self.id = game_info[\"playerId\"]\n self.x = game_info[\"posx\"]\n self.y = game_info[\"posy\"]\n self.energy = game_info[\"energy\"]\n self.mapInfo.init_map(game_info[\"gameinfo\"])\n self.stepCount = 0\n self.status = State.STATUS_PLAYING\n self.players = [{\"playerId\": 2, \"posx\": self.x, \"posy\": self.y},\n {\"playerId\": 3, \"posx\": self.x, \"posy\": self.y},\n {\"playerId\": 4, \"posx\": self.x, \"posy\": self.y}]\n\n def update_state(self, data):\n new_state = str_2_json(data)\n for player in new_state[\"players\"]:\n if player[\"playerId\"] == self.id:\n self.x = player[\"posx\"]\n self.y = player[\"posy\"]\n self.energy_pre = self.energy\n self.energy = player[\"energy\"]\n self.score = player[\"score\"]\n self.lastAction = player[\"lastAction\"]\n self.status = player[\"status\"]\n\n self.mapInfo.update(new_state[\"golds\"], new_state[\"changedObstacles\"])\n self.players = new_state[\"players\"]\n for i in range(len(self.players), 4, 1):\n self.players.append({\"playerId\": i, \"posx\": self.x, \"posy\": self.y})\n self.stepCount = self.stepCount + 1\n\n\n#MinerEnv.py\nTreeID = 1\nTrapID = 2\nSwampID = 3\nclass MinerEnv:\n def __init__(self):\n self.socket = GameSocket()\n self.state = State()\n self.score_pre = self.state.score\n\n def start(self): #connect to server\n self.socket.connect()\n\n def end(self): #disconnect server\n self.socket.close()\n\n def send_map_info(self, request):#tell server which map to run\n self.socket.send(request)\n\n def reset(self): #start new game\n try:\n message = self.socket.receive() #receive game info from server\n self.state.init_state(message) #init state\n except Exception as e:\n import traceback\n traceback.print_exc()\n\n def step(self, action): #step process\n self.socket.send(action) #send action to server\n try:\n message = self.socket.receive() #receive new state from server\n self.state.update_state(message) #update to local state\n except Exception as e:\n import traceback\n traceback.print_exc()\n\n def get_state(self):\n \"\"\"\n Fuse `view` and `energyOnMap` into a single matrix to have a simple and concise state/observation.\n\n We want a matrix showing the following:\n `gold`: The amount of gold\n `all the others`: The energy that each type of terrain is going to take if being stepped into, e.g.\n `land` => -1, `trap` => -10, etc.\n \"\"\"\n view = np.zeros([self.state.mapInfo.max_y + 1, self.state.mapInfo.max_x + 1], dtype=int)\n for x in range(self.state.mapInfo.max_x + 1):\n for y in range(self.state.mapInfo.max_y + 1):\n if self.state.mapInfo.get_obstacle(x, y) == TreeID: # Tree\n view[y, x] = -TreeID\n if self.state.mapInfo.get_obstacle(x, y) == TrapID: # Trap\n view[y, x] = -TrapID\n if self.state.mapInfo.get_obstacle(x, y) == SwampID: # Swamp\n view[y, x] = -SwampID\n if self.state.mapInfo.gold_amount(x, y) > 0:\n view[y, x] = self.state.mapInfo.gold_amount(x, y)\n energyOnMap = np.array(self.socket.energyOnMap)\n\n # `view` will contribute only to the type of terrain of `gold`\n view[view <= 0] = -9999 # Just a dummy large negative number to be got rid of later\n # `energyOnMap` will contribute to the types of terrain of `land`, `trap`, `forest` and `swamp`.\n # Recall. `forest` was designated by BTC to the value of 0, to mean random integer btw [5..20].\n energyOnMap[energyOnMap == 0] = - constants.forest_energy\n channel0 = np.maximum(view, energyOnMap)\n # Finish channel 0\n # Channel 1 will contain the position of the agent\n channel1 = np.zeros_like(channel0)\n x_agent_out_of_map = self.state.x < 0 or self.state.x >= constants.width\n y_agent_out_of_map = self.state.y < 0 or self.state.y >= constants.height\n if x_agent_out_of_map or y_agent_out_of_map:\n pass\n else:\n channel1[self.state.y, self.state.x] = self.state.energy\n state = np.stack((channel0, channel1), axis=-1)\n return state\n\n\n def get_reward(self):\n # Initialize reward\n reward = 0\n if self.state.status == constants.agent_state_str2id[\"out_of_MAP\"]:\n #if self.state.stepCount < 50:\n # reward += -5*(50 - self.state.stepCount)\n reward -= 1000\n #elif self.state.status == constants.agent_state_str2id[\"no_more_STEP\"]:\n # #reward += (self.state.score/total_gold) * 100\n # pass\n elif self.state.status == constants.agent_state_str2id[\"no_more_ENERGY\"]:\n reward -= 300\n #elif self.state.status == constants.agent_state_str2id[\"no_more_GOLD\"]:\n # pass\n #elif self.state.status == constants.agent_state_str2id[\"INVALID_action\"]:\n # pass\n else: # Here below: we are almost sure that agent is not out of map\n s = self.get_state()\n try:\n terrain_now = s[self.state.y, self.state.x, 0]\n except Exception as e:\n print(f\"{e}\")\n print(f\"self.state.x, self.state.y = {self.state.x}, {self.state.y} \")\n pos_now = np.array([self.state.x, self.state.y])\n reverse_mv = constants.action_id2ndarray[constants.reverse_action_id[self.state.lastAction]]\n pos_pre = pos_now + reverse_mv\n x_pre, y_pre = pos_pre\n terrain_pre = s[y_pre, x_pre, 0]\n\n # Punish `dig on obstacle`\n if self.state.lastAction == constants.dig:\n if terrain_now < 0:\n reward -= 100\n elif terrain_now > 0:\n score_action = self.state.score - self.score_pre\n reward += score_action\n self.score_pre = self.state.score\n if self.state.lastAction in (constants.up, constants.down, constants.left, constants.right,): # i.e. if agent moved\n if terrain_pre > 100: # punish leaving gold\n reward -= terrain_pre\n if terrain_now > 0: # entering gold\n if self.state.energy > constants.punishments[\"gold\"]:\n reward += 50\n else:\n reward -= 100\n if terrain_now < 0: # punish according to terrain_now\n reward += terrain_now\n if terrain_now == -100: # i.e. fatal swamp\n reward -= 500\n if self.state.lastAction == constants.rest:\n if self.state.energy_pre >= 40:\n reward -= 200\n if self.state.energy_pre <= 5:\n reward += 20\n if self.state.status == constants.agent_state_str2id[\"PLAYing\"]:\n reward += 1\n\n return reward\n\n def check_terminate(self):\n #Checking the status of the game\n #it indicates the game ends or is playing\n return self.state.status != State.STATUS_PLAYING\n\n\nMaps = [constants.maps[i] for i in range(1, 6)]\nenv = MinerEnv() # Creating a communication environment between the DQN model and the game environment\nenv.start() # Connect to the game\n\n\n\n#eliminated = []\n#def pictorial_state(obs):\n# pictorial = np.zeros((constants.height, constants.width, 1+4), dtype=np.float32)\n# # 1+4 is +1 for map and +1 for each of the players = 5 channels\n# # dtype=np.float32 because pictorial will later be carried into tensorflow CNN\n# pictorial[..., 0] = obs[:constants.n_px].reshape((constants.height, constants.width))\n# # position of agent: we put the energy value at the coordinate where stands the agent, the whole in channel 1, the channel for the agent.\n# x_agent, y_agent = obs[constants.n_px], obs[constants.n_px+1]\n# if x_agent >= constants.width or y_agent >= constants.height:\n# pass\n# else:\n# pictorial[y_agent, x_agent, 1] = obs[constants.n_px+2]\n# # position of bots: we put -1 on the coord of the bots\n# for i in range(1, 3+1):\n# if i in eliminated:\n# continue\n# y = obs[constants.n_px+(2*i+2)]\n# x = obs[constants.n_px+(2*i+1)]\n# if x >= constants.width or y >= constants.height:\n# eliminated.append(i)\n# continue\n# pictorial[y, x, i+1] = -1\n# return pictorial\n\n\n\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten\n\n\ntf.random.set_seed(42)\nnp.random.seed(42)\n\n#input_shape = [constants.height, constants.width, 1+4]\ninput_shape = [constants.height, constants.width, 1+1]\nn_outputs = 6\n\nmodel = keras.models.Sequential([\n Conv2D(4, 3, activation=\"relu\", padding=\"same\", input_shape=input_shape),\n #MaxPooling2D(2),\n Conv2D(8, 3, activation=\"relu\", padding=\"same\"),\n #Conv2D(128, 3, activation=\"relu\", padding=\"same\"),\n #MaxPooling2D(2),\n Flatten(),\n #Dense(128, activation=\"elu\"),\n Dense(128, activation=\"elu\"),\n Dense(64, activation=\"elu\"),\n Dense(32, activation=\"elu\"),\n Dense(n_outputs)\n])\n#h5 = \"models/30_11_dDQN_light_tweak14/avg-1785.00-episode-11155-30_11_dDQN_light_tweak14-gold-1800-step-100-20200827-0903.h5\"\n#model = keras.models.load_model(h5)\ntarget = keras.models.clone_model(model)\ntarget.set_weights(model.get_weights())\n\n\n\nfrom collections import deque\nreplay_memory = deque(maxlen=max_replay_len)\n\n\ndef sample_experiences(batch_size):\n indices = np.random.randint(len(replay_memory), size=batch_size)\n batch = [replay_memory[index] for index in indices]\n states, actions, rewards, next_states, dones = [\n np.array([experience[field_index] for experience in batch])\n for field_index in range(5)]\n return states, actions, rewards, next_states, dones\n\n\ndef epsilon_greedy_policy(state, epsilon=0, n_actions=6):\n if np.random.rand() < epsilon:\n return np.random.randint(n_actions)\n else:\n #pictorial = pictorial_state(state)\n #Q_values = model.predict(pictorial[np.newaxis])\n Q_values = model.predict(state[np.newaxis])\n return np.argmax(Q_values[0])\n\n\ndef play_one_step(env, state, epsilon):\n action = epsilon_greedy_policy(state, epsilon)\n #next_state, reward, done, info = env.step(action)\n env.step(str(action))\n next_state = env.get_state()\n reward = env.get_reward()\n done = env.check_terminate()\n replay_memory.append((state, action, reward, next_state, done))\n return next_state, reward, done\n\n\n#optimizer = keras.optimizers.Adam(lr=1e-3)\n#optimizer = keras.optimizers.Adam(lr=2.5e-4)\noptimizer = keras.optimizers.Adam(lr=lr_optimizer)\n\ndef training_step(batch_size):\n experiences = sample_experiences(batch_size)\n states, actions, rewards, next_states, dones = experiences\n #pictorials = np.array([pictorial_state(s) for s in states])\n #next_pictorials = np.array([pictorial_state(next_s) for next_s in next_states])\n #next_Q_values = model.predict(next_pictorials)\n next_Q_values = model.predict(next_states)\n #max_next_Q_values = np.max(next_Q_values, axis=1)\n best_next_actions = np.argmax(next_Q_values, axis=1)\n next_mask = tf.one_hot(best_next_actions, n_outputs).numpy()\n next_best_Q_values = (target.predict(next_states) * next_mask).sum(axis=1)\n #target_Q_values = rewards + (1 - dones) * discount_rate * max_next_Q_values\n target_Q_values = rewards + (1 - dones) * discount_rate * next_best_Q_values\n target_Q_values = target_Q_values.reshape(-1, 1)\n mask = tf.one_hot(actions, n_outputs)\n with tf.GradientTape() as tape:\n #all_Q_values = model(pictorials)\n all_Q_values = model(states)\n Q_values = tf.reduce_sum(all_Q_values * mask, axis=1, keepdims=True)\n loss = tf.reduce_mean(loss_fn(target_Q_values, Q_values))\n grads = tape.gradient(loss, model.trainable_variables)\n optimizer.apply_gradients(zip(grads, model.trainable_variables))\n\n\nnp.random.seed(42)\ntf.random.set_seed(42)\n\n\nfrom constants import n_allowed_steps\n\nnow = datetime.datetime.now()\nnow_str = now.strftime(\"%Y%m%d-%H%M\")\nscript_name = __file__.split('.')[0]\nsave_path = os.path.join(\"models\", script_name)\nos.makedirs(save_path, exist_ok=True)\n\n\nscores = [] \nscores_avg = [] \nbest_score = 0\nk = 10\nscores_k_most_recent = deque([0]*k, maxlen=k)\nbest_score_avg = 1400\n\nwith open(os.path.join(save_path, f\"log-{now_str}.txt\"), 'w') as log:\n for episode in range(n_episodes):\n eliminated = []\n mapID = np.random.randint(0, 5)\n posID_x = np.random.randint(constants.width) \n posID_y = np.random.randint(constants.height)\n request = \"map{},{},{},50,100\".format(mapID, posID_x, posID_y)\n env.send_map_info(request)\n env.reset()\n obs = env.get_state()\n undiscounted_return = 0\n for step in range(n_allowed_steps):\n epsilon = max(1 - episode / n_epsilon_decay, 0.01)\n obs, reward, done = play_one_step(env, obs, epsilon)\n undiscounted_return += reward\n if done:\n break\n score = env.state.score\n scores.append(score)\n scores_k_most_recent.append(score)\n #score_avg = np.mean(scores_k_most_recent)\n score_avg = round(np.mean(scores_k_most_recent), 1)\n scores_avg.append(score_avg)\n #if score > best_score:\n if score_avg > best_score_avg:\n #best_weights = model.get_weights()\n best_score_avg = score_avg \n #best_score = score\n #model.save(os.path.join(save_path, f\"episode-{episode+1}-gold-{env.state.score}-avg-{score_avg:4.2f}-step-{step+1}-{now_str}.h5\"))\n model.save(os.path.join(save_path, f\"avg-{score_avg:07.2f}-episode-{episode+1}-{__file__.split('.')[0]}-gold-{env.state.score}-step-{step+1}-{now_str}.h5\"))\n \n #message = \"(Episode {: 5d}/{}) Gold {: 4d} avg {: 8.2f} undisc_return {: 6d} step {: 3d} eps {:.2f} ({})\\n\".format(episode+1, n_episodes, env.state.score, score_avg, undiscounted_return, step + 1, epsilon, constants.agent_state_id2str[env.state.status])\n message = \"(Episode {: 5d}/{}) Gold {: 4d} avg {: 8.1f} undisc_return {: 6d} step {: 3d} eps: {:.2f} ({})\\n\".format(episode+1, n_episodes, env.state.score, score_avg, undiscounted_return, step + 1, epsilon, constants.agent_state_id2str[env.state.status])\n ##############################################\n #score = env.state.score*(n_allowed_steps - step)\n #score = env.state.score\n #scores.append(score)\n #if score > best_score:\n # #best_weights = model.get_weights()\n # best_score = score\n # model.save(os.path.join(save_path, f\"episode-{episode+1}-gold-{env.state.score}-step-{step+1}-{now_str}.h5\"))\n \n #message = \"(Episode {: 5d}/{}) Gold: {: 4d} undiscounted_return: {: 6d} Steps: {: 3d} eps: {:.3f} ({})\\n\".format(episode+1, n_episodes, env.state.score, undiscounted_return, step + 1, epsilon, constants.agent_state_id2str[env.state.status])\n print(message, end='')\n log.write(message)\n \n #if episode > 500:\n if episode > n_episodes_buf_fill:\n training_step(batch_size)\n if episode % n_episodes_buf_fill == 0:\n target.set_weights(model.get_weights())\n\n#np.save(f\"scores-{now_str}\", np.array(scores))\n#np.save(f\"scores-N-scores_avg-{now_str}\", np.array([scores, scores_avg]))\nnp.save(f\"scores-N-scores_avg-{__file__.split('.')[0]}-{now_str}\", np.array([scores, scores_avg]))\n",
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom constants import width, height, terrain_ids, n_px\n\n# in RGB format\n#gold = [99.3, 68.8, 1.0]\n#silver = [47.8, 47.8, 47.8]\n#blue = [8.2, 39.4, 95.6]\n#green = [4.6, 43.8, 2.5]\n#pink = [85.4, 47.7, 45.9]\n\n#gold = np.array([99.3, 68.8, 1.0])\n#silver = np.array([47.8, 47.8, 47.8])\n#blue = np.array([8.2, 39.4, 95.6])\n#green = np.array([4.6, 43.8, 2.5])\n#pink = np.array([85.4, 47.7, 45.9])\n\nsilver = np.array([183, 179, 150])\nblue = np.array([51, 147, 237])\ngreen = np.array([17, 111, 17])\npink = np.array([253, 179, 176])\ngold = np.array([242, 215, 35])\nwhite = np.ones((3,), dtype=np.uint8)*255\nblack = np.zeros((3,), dtype=np.uint8)\n\ndef imshow(image, figsize=(7,7)):\n plt.figure(figsize=figsize)\n plt.imshow(image);\n #plt.grid(True);\n plt.yticks(range(image.shape[0]));\n plt.xticks(range(image.shape[1]));\n\n\ndef render_state_image(s):\n numerical_image = s[:n_px].reshape((height, width))\n image = np.zeros((height, width, 3), dtype=np.uint8)\n image[numerical_image==-terrain_ids[\"forest\"]] = green\n image[numerical_image==-terrain_ids[\"trap\"]] = silver\n image[numerical_image==-terrain_ids[\"swamp\"]] = blue\n image[numerical_image>0] = gold\n image[numerical_image==0] = pink\n return image\n\ndef pos_3x(xy):\n \"\"\"\n args\n xy, ndarray\n shape = (2*k,)\n return\n xy_3x, ndarray\n shape = (2*k,)\n \"\"\"\n xy_3x = xy*3 + 1\n return xy_3x\n\ndef prettier_render(s):\n primitive = render_state_image(s)\n primitive_3x = np.kron(primitive, np.ones((3,3,1), dtype=np.uint8))\n #print(f\"primitive_3x.shape = {primitive_3x.shape}\")\n\n # draw bots' position\n # The positions might be overwritten one over another\n n_bots = s[n_px+3:].size // 2\n bots_xy = s[n_px+3:].reshape((n_bots,2))\n bots_xy_3x = pos_3x(bots_xy)\n for bot_id, coord in enumerate(bots_xy_3x):\n print(f\"bot {bot_id} at {bots_xy[bot_id]}\")\n try:\n primitive_3x[coord[1], coord[0]] = black\n except IndexError as e:\n print(f\"bot {bot_id} fell OUT OF MAP\")\n \n # draw agent's position\n agent_xy = s[n_px:n_px+2]\n agent_xy_3x = pos_3x(agent_xy)\n #print(f\"agent_xy_3x = {agent_xy_3x}\")\n primitive_3x[agent_xy_3x[1], agent_xy_3x[0]] = white\n return primitive_3x\n\n\ndef gold_total(map_):\n #map_ = np.array(map_)\n return map_[map_ > 0].sum()\n\n#def pictorial_state(obs):\n# pictorial = np.zeros((constants.height, constants.width, 2), dtype=np.float32)\n# # dtype=np.float32 because pictorial will later be carried into tensorflow CNN\n# pictorial[..., 0] = obs[:constants.n_px].reshape((constants.height, constants.width))\n# # position of agent: we put the energy value at the coordinate where stands the agent, the whole in the last channel.\n# pictorial[obs[constants.n_px], obs[constants.n_px+1], -1] = obs[constants.n_px+2]\n# # position of bots: we put -1 on the coord of the bots\n# for i in range(1, 3+1):\n# pictorial[obs[constants.n_px+(2*i+1)], obs[constants.n_px+(2*i+2)], -1] = -1\n# return pictorial\n\n\n",
"########################################\n# Changes compared to 20_5channel.py\n# 01. \n# CNN structure\n########################################\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport sys\nimport numpy as np\n#import pandas as pd\nimport datetime\nimport json\nfrom array import *\nimport os\nimport math\nfrom random import randrange\nimport random\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.models import model_from_json\nfrom tensorflow.keras.layers import Dense, Activation\nfrom tensorflow.keras import optimizers\n\nimport tensorflow.keras as keras\n\n#import tensorflow.compat.v1 as tf\n#from tensorflow.compat.v1.keras import backend as K\n#tf.disable_v2_behavior()\nimport tensorflow as tf\nfrom tensorflow.keras import backend as K\n\nimport logging\n#logging.basicConfig(level=logging.DEBUG)\n#logging.basicConfig(level=logging.INFO)\nlogging.basicConfig(filename=__file__.replace(\".py\", \".log\"), level=logging.DEBUG)\nimport os\nimport sys\nsys.path.append(os.path.abspath(os.path.pardir))\nimport constants02\nimport non_RL_agent\nimport non_RL_agent02\nimport non_RL_agent03\nimport non_RL_agent04\nimport non_RL_agent05\nimport non_RL_agent06\nfrom miner_env import MinerEnv\n\nseed = 30420\nn_episodes = 500_000\n#n_epsilon_decay = int(n_episodes*.6)\nn_epsilon_decay = int(n_episodes*.805)\n#n_epsilon_decay = 10**6 / 0.99\n#n_epsilon_decay = int(n_episodes // 50)\nn_episodes_buf_fill = 5_000\nbatch_size = 32\ndiscount_rate = 0.95\n#lr_optimizer = 2.5e-4\nlr_optimizer = 7.3e-4\n#loss_fn = keras.losses.mean_squared_error\nloss_fn = keras.losses.Huber()\nmax_replay_len = 50_000\n\n\nMaps = [constants02.maps[i] for i in range(1, 6)]\nenv = MinerEnv() # Creating a communication environment between the DQN model and the game environment\nenv.start() # Connect to the game\n\n\n\n\n\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten\n\n\ntf.random.set_seed(seed)\nnp.random.seed(seed)\n\ninput_shape = [constants02.height, constants02.width, 1+4]\n#input_shape = [constants02.height, constants02.width, 1+1]\nn_outputs = 6\n\nmodel = keras.models.Sequential([\n Conv2D(5, 3, activation=\"relu\", padding=\"same\", input_shape=input_shape),\n #MaxPooling2D(2),\n Conv2D(5, 3, activation=\"relu\", padding=\"same\"),\n Conv2D(5, 3, activation=\"relu\", padding=\"same\"),\n #Conv2D(128, 3, activation=\"relu\", padding=\"same\"),\n #MaxPooling2D(2),\n Flatten(),\n #Dense(128, activation=\"elu\"),\n Dense(32, activation=\"elu\"),\n Dense(32, activation=\"elu\"),\n Dense(32, activation=\"elu\"),\n Dense(n_outputs)\n])\n#h5 = \"models/30_11_dDQN_light_tweak14/avg-1785.00-episode-11155-30_11_dDQN_light_tweak14-gold-1800-step-100-20200827-0903.h5\"\n#model = keras.models.load_model(h5)\ntarget = keras.models.clone_model(model)\ntarget.set_weights(model.get_weights())\n\n\n\nfrom collections import deque\nreplay_memory = deque(maxlen=max_replay_len)\n\n\ndef sample_experiences(batch_size):\n indices = np.random.randint(len(replay_memory), size=batch_size)\n batch = [replay_memory[index] for index in indices]\n states, actions, rewards, next_states, dones = [\n np.array([experience[field_index] for experience in batch])\n for field_index in range(5)]\n return states, actions, rewards, next_states, dones\n\n\ndef epsilon_greedy_policy(state, epsilon=0, n_actions=6):\n if np.random.rand() < epsilon:\n return np.random.randint(n_actions)\n else:\n #pictorial = pictorial_state(state)\n #Q_values = model.predict(pictorial[np.newaxis])\n Q_values = model.predict(state[np.newaxis])\n return np.argmax(Q_values[0])\n\n\ndef play_one_step(env, state, epsilon):\n action = epsilon_greedy_policy(state, epsilon)\n #logging.debug(f\"pos=({env.state.x:2d},{env.state.y:2d}), terrain={state[...,0][env.state.y, env.state.x]}, action={constants02.action_id2str[action]}, energy={env.state.energy}, score={env.state.score}\")\n #next_state, reward, done, info = env.step(action)\n env.step(str(action))\n #next_state = env.get_9x21x2_state()\n next_state = env.get_view_9x21x5()\n reward = env.get_reward_6act_21()\n done = env.check_terminate()\n replay_memory.append((state, action, reward, next_state, done))\n try:\n logging.debug(f\"pos=({env.state.x:2d},{env.state.y:2d}), terrain={next_state[...,0][env.state.y, env.state.x]:4.1f}, lastAction={constants02.action_id2str[action]:>5}, energy={env.state.energy}, score={env.state.score}, reward={reward:.1f}\")\n except IndexError:\n logging.debug(f\"pos=({env.state.x:2d},{env.state.y:2d}), lastAction={constants02.action_id2str[action]:>5}, energy={env.state.energy}, score={env.state.score}, reward={reward:.1f}\")\n #next_state, reward, done, info = env.step(action)\n return next_state, reward, done\n\n\n#optimizer = keras.optimizers.Adam(lr=1e-3)\n#optimizer = keras.optimizers.Adam(lr=2.5e-4)\noptimizer = keras.optimizers.Adam(lr=lr_optimizer)\n\ndef training_step(batch_size):\n experiences = sample_experiences(batch_size)\n states, actions, rewards, next_states, dones = experiences\n #pictorials = np.array([pictorial_state(s) for s in states])\n #next_pictorials = np.array([pictorial_state(next_s) for next_s in next_states])\n #next_Q_values = model.predict(next_pictorials)\n next_Q_values = model.predict(next_states)\n #max_next_Q_values = np.max(next_Q_values, axis=1)\n best_next_actions = np.argmax(next_Q_values, axis=1)\n next_mask = tf.one_hot(best_next_actions, n_outputs).numpy()\n next_best_Q_values = (target.predict(next_states) * next_mask).sum(axis=1)\n #target_Q_values = rewards + (1 - dones) * discount_rate * max_next_Q_values\n target_Q_values = rewards + (1 - dones) * discount_rate * next_best_Q_values\n target_Q_values = target_Q_values.reshape(-1, 1)\n mask = tf.one_hot(actions, n_outputs)\n with tf.GradientTape() as tape:\n #all_Q_values = model(pictorials)\n all_Q_values = model(states)\n Q_values = tf.reduce_sum(all_Q_values * mask, axis=1, keepdims=True)\n loss = tf.reduce_mean(loss_fn(target_Q_values, Q_values))\n grads = tape.gradient(loss, model.trainable_variables)\n optimizer.apply_gradients(zip(grads, model.trainable_variables))\n\n\n#np.random.seed(42)\n#tf.random.set_seed(42)\n\n\nfrom constants02 import n_allowed_steps\n\nnow = datetime.datetime.now()\nnow_str = now.strftime(\"%Y%m%d-%H%M\")\nscript_name = __file__.split('.')[0]\nsave_path = os.path.join(\"models\", script_name)\nos.makedirs(save_path, exist_ok=True)\n\n\nscores = [] \nscores_avg = [] \nbest_score = 0\nk = 10\nscores_k_most_recent = deque([0]*k, maxlen=k)\nbest_score_avg = 1400\n\nwith open(os.path.join(save_path, f\"log-{now_str}.txt\"), 'w') as log:\n for episode in range(n_episodes):\n #mapID = np.random.randint(0, 5)\n mapID = np.random.randint(1,6)\n posID_x = np.random.randint(constants02.width) \n posID_y = np.random.randint(constants02.height)\n request = \"map{},{},{},50,100\".format(mapID, posID_x, posID_y)\n env.send_map_info(request)\n env.reset()\n #obs = env.get_9x21x2_state()\n obs = env.get_view_9x21x5()\n delimiter = \"===================================================\"\n logging.debug(f\"\\n{delimiter}\\nmapID {mapID}, start (x,y) = ({posID_x}, {posID_y}) on terrain {obs[...,0][posID_y, posID_x]} \\n{delimiter}\")\n undiscounted_return = 0\n for step in range(n_allowed_steps):\n logging.debug(f\"(step {step:3d})\")\n logging.debug(f\"obs[...,0] =\\n{obs[...,0]}\")\n #plt.imsave(f\"corbeille/map-{mapID}-step-{step:03d}.png\", obs[...,0], cmap=\"gray\")\n #plt.imsave(f\"corbeille/map-{mapID}-step-{step:03d}.png\", cv2.resize(obs[...,0], (210, 90)), cmap=\"gray\")\n epsilon = max(1 - episode / n_epsilon_decay, 0.01)\n obs, reward, done = play_one_step(env, obs, epsilon)\n undiscounted_return += reward\n if done:\n break\n score = env.state.score\n scores.append(score)\n scores_k_most_recent.append(score)\n #score_avg = np.mean(scores_k_most_recent)\n score_avg = round(np.mean(scores_k_most_recent), 1)\n scores_avg.append(score_avg)\n #if score > best_score:\n if score_avg > best_score_avg:\n #best_weights = model.get_weights()\n #best_score_avg = score_avg \n best_score_avg = min(1800, best_score_avg + 50)\n #best_score = score\n #model.save(os.path.join(save_path, f\"episode-{episode+1}-gold-{env.state.score}-avg-{score_avg:4.2f}-step-{step+1}-{now_str}.h5\"))\n model.save(os.path.join(save_path, f\"avg-{score_avg:07.2f}-episode-{episode+1}-{__file__.split('.')[0]}-gold-{env.state.score}-step-{step+1}-{now_str}.h5\"))\n \n #message = \"(Episode {: 5d}/{}) Gold {: 4d} avg {: 8.1f} undisc_return {: 6d} step {: 3d} eps: {:.2f} ({})\\n\".format(episode+1, n_episodes, env.state.score, score_avg, undiscounted_return, step + 1, epsilon, constants02.agent_state_id2str[env.state.status])\n message = \"(Episode {:6d}/{}) Gold {:4d} avg {:5.0f} undisc_return {:8.0f} step {:3d} eps: {:.2f} (map {}: {})\\n\".format(episode+1, n_episodes, env.state.score, score_avg, undiscounted_return, step + 1, epsilon, mapID, constants02.agent_state_id2str[env.state.status])\n\n print(message, end='')\n log.write(message)\n \n #if episode > 500:\n if episode > n_episodes_buf_fill:\n training_step(batch_size)\n if episode % n_episodes_buf_fill == 0:\n target.set_weights(model.get_weights())\n\n#np.save(f\"scores-{now_str}\", np.array(scores))\n#np.save(f\"scores-N-scores_avg-{now_str}\", np.array([scores, scores_avg]))\nnp.save(f\"scores-N-scores_avg-{__file__.split('.')[0]}-{now_str}\", np.array([scores, scores_avg]))\n",
"########################################\n# Changes compared to 30_05_CNN_revived_dDQN_light.py\n# 01. \n# n_epsilon_decay = int(n_episodes*.6)\n# as opposed to\n# n_epsilon_decay = int(n_episodes*.805)\n# Takes around 300_000 to get from epsilon=1 to epsilon=0.01\n# 02. shorter\n# n_episodes_buf_fill = 2_000\n# as opposed to\n# n_episodes_buf_fill = 5_000\n########################################\n\n\nimport sys\nimport numpy as np\n#import pandas as pd\nimport datetime\nimport json\nfrom array import *\nimport os\nimport math\nfrom random import randrange\nimport random\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.models import model_from_json\nfrom tensorflow.keras.layers import Dense, Activation\nfrom tensorflow.keras import optimizers\n\nimport tensorflow.keras as keras\n\n#import tensorflow.compat.v1 as tf\n#from tensorflow.compat.v1.keras import backend as K\n#tf.disable_v2_behavior()\nimport tensorflow as tf\nfrom tensorflow.keras import backend as K\n\nimport constants\nimport non_RL_agent\nimport non_RL_agent02\nimport non_RL_agent03\nimport non_RL_agent04\nimport non_RL_agent05\nimport non_RL_agent06\n\nn_episodes = 500_000\n#n_epsilon_decay = int(n_episodes*.805)\n#n_epsilon_decay = 10**6 / 0.99\nn_epsilon_decay = int(n_episodes*.6)\n#n_episodes_buf_fill = 5_000\nn_episodes_buf_fill = 2_000\nbatch_size = 32\ndiscount_rate = 0.95\n#lr_optimizer = 2.5e-4\nlr_optimizer = 7.3e-4\n#loss_fn = keras.losses.mean_squared_error\nloss_fn = keras.losses.Huber()\nmax_replay_len = 50_000\n\n\n#Classes in GAME_SOCKET_DUMMY.py\nclass ObstacleInfo:\n # initial energy for obstacles: Land (key = 0): -1, Forest(key = -1): 0 (random), Trap(key = -2): -10, Swamp (key = -3): -5\n types = {0: -1, -1: 0, -2: -10, -3: -5}\n\n def __init__(self):\n self.type = 0\n self.posx = 0\n self.posy = 0\n self.value = 0\n \nclass GoldInfo:\n def __init__(self):\n self.posx = 0\n self.posy = 0\n self.amount = 0\n\n def loads(self, data):\n golds = []\n for gd in data:\n g = GoldInfo()\n g.posx = gd[\"posx\"]\n g.posy = gd[\"posy\"]\n g.amount = gd[\"amount\"]\n golds.append(g)\n return golds\n\nclass PlayerInfo:\n STATUS_PLAYING = 0\n STATUS_ELIMINATED_WENT_OUT_MAP = 1\n STATUS_ELIMINATED_OUT_OF_ENERGY = 2\n STATUS_ELIMINATED_INVALID_ACTION = 3\n STATUS_STOP_EMPTY_GOLD = 4\n STATUS_STOP_END_STEP = 5\n\n def __init__(self, id):\n self.playerId = id\n self.score = 0\n self.energy = 0\n self.posx = 0\n self.posy = 0\n self.lastAction = -1\n self.status = PlayerInfo.STATUS_PLAYING\n self.freeCount = 0\n\nclass GameInfo:\n def __init__(self):\n self.numberOfPlayers = 1\n self.width = 0\n self.height = 0\n self.steps = 100\n self.golds = []\n self.obstacles = []\n\n def loads(self, data):\n m = GameInfo()\n m.width = data[\"width\"]\n m.height = data[\"height\"]\n m.golds = GoldInfo().loads(data[\"golds\"])\n m.obstacles = data[\"obstacles\"]\n m.numberOfPlayers = data[\"numberOfPlayers\"]\n m.steps = data[\"steps\"]\n return m\n\nclass UserMatch:\n def __init__(self):\n self.playerId = 1\n self.posx = 0\n self.posy = 0\n self.energy = 50\n self.gameinfo = GameInfo()\n\n def to_json(self):\n return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4)\n\nclass StepState:\n def __init__(self):\n self.players = []\n self.golds = []\n self.changedObstacles = []\n\n def to_json(self):\n return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4)\n\n\n#Main class in GAME_SOCKET_DUMMY.py\nclass GameSocket:\n bog_energy_chain = {-5: -20, -20: -40, -40: -100, -100: -100}\n\n def __init__(self):\n self.stepCount = 0\n self.maxStep = 0\n self.mapdir = \"Maps\" # where to load all pre-defined maps\n self.mapid = \"\"\n self.userMatch = UserMatch()\n self.user = PlayerInfo(1)\n self.stepState = StepState()\n self.maps = {} # key: map file name, value: file content\n self.map = [] # running map info: 0->Land, -1->Forest, -2->Trap, -3:Swamp, >0:Gold\n self.energyOnMap = [] # self.energyOnMap[x][y]: <0, amount of energy which player will consume if it move into (x,y)\n self.E = 50\n self.resetFlag = True\n self.craftUsers = [] # players that craft at current step - for calculating amount of gold\n self.bots = []\n self.craftMap = {} # cells that players craft at current step, key: x_y, value: number of players that craft at (x,y)\n\n def init_bots(self):\n self.bots = [Bot1(2), Bot2(3), Bot3(4)] # use bot1(id=2), bot2(id=3), bot3(id=4)\n #for (bot) in self.bots: # at the beginning, all bots will have same position, energy as player\n for bot in self.bots: # at the beginning, all bots will have same position, energy as player\n bot.info.posx = self.user.posx\n bot.info.posy = self.user.posy\n bot.info.energy = self.user.energy\n bot.info.lastAction = -1\n bot.info.status = PlayerInfo.STATUS_PLAYING\n bot.info.score = 0\n self.stepState.players.append(bot.info)\n self.userMatch.gameinfo.numberOfPlayers = len(self.stepState.players)\n #print(\"numberOfPlayers: \", self.userMatch.gameinfo.numberOfPlayers)\n\n def reset(self, requests): # load new game by given request: [map id (filename), posx, posy, initial energy]\n # load new map\n self.reset_map(requests[0])\n self.userMatch.posx = int(requests[1])\n self.userMatch.posy = int(requests[2])\n self.userMatch.energy = int(requests[3])\n self.userMatch.gameinfo.steps = int(requests[4])\n self.maxStep = self.userMatch.gameinfo.steps\n\n # init data for players\n self.user.posx = self.userMatch.posx # in\n self.user.posy = self.userMatch.posy\n self.user.energy = self.userMatch.energy\n self.user.status = PlayerInfo.STATUS_PLAYING\n self.user.score = 0\n self.stepState.players = [self.user]\n self.E = self.userMatch.energy\n self.resetFlag = True\n self.init_bots()\n self.stepCount = 0\n\n def reset_map(self, id): # load map info\n self.mapId = id\n self.map = json.loads(self.maps[self.mapId])\n self.userMatch = self.map_info(self.map)\n self.stepState.golds = self.userMatch.gameinfo.golds\n self.map = json.loads(self.maps[self.mapId])\n self.energyOnMap = json.loads(self.maps[self.mapId])\n for x in range(len(self.map)):\n for y in range(len(self.map[x])):\n if self.map[x][y] > 0: # gold\n self.energyOnMap[x][y] = -4\n else: # obstacles\n self.energyOnMap[x][y] = ObstacleInfo.types[self.map[x][y]]\n\n def connect(self): # simulate player's connect request\n print(\"Connected to server.\")\n for mapid in range(len(Maps)):\n filename = \"map\" + str(mapid)\n print(\"Found: \" + filename)\n self.maps[filename] = str(Maps[mapid])\n\n def map_info(self, map): # get map info\n # print(map)\n userMatch = UserMatch()\n userMatch.gameinfo.height = len(map)\n userMatch.gameinfo.width = len(map[0])\n i = 0\n while i < len(map):\n j = 0\n while j < len(map[i]):\n if map[i][j] > 0: # gold\n g = GoldInfo()\n g.posx = j\n g.posy = i\n g.amount = map[i][j]\n userMatch.gameinfo.golds.append(g)\n else: # obstacles\n o = ObstacleInfo()\n o.posx = j\n o.posy = i\n o.type = -map[i][j]\n o.value = ObstacleInfo.types[map[i][j]]\n userMatch.gameinfo.obstacles.append(o)\n j += 1\n i += 1\n return userMatch\n\n def receive(self): # send data to player (simulate player's receive request)\n if self.resetFlag: # for the first time -> send game info\n self.resetFlag = False\n data = self.userMatch.to_json()\n for (bot) in self.bots:\n bot.new_game(data)\n # print(data)\n return data\n else: # send step state\n self.stepCount = self.stepCount + 1\n if self.stepCount >= self.maxStep:\n for player in self.stepState.players:\n player.status = PlayerInfo.STATUS_STOP_END_STEP\n data = self.stepState.to_json()\n #for (bot) in self.bots: # update bots' state\n for bot in self.bots: # update bots' state\n bot.new_state(data)\n # print(data)\n return data\n\n def send(self, message): # receive message from player (simulate send request from player)\n if message.isnumeric(): # player send action\n self.resetFlag = False\n self.stepState.changedObstacles = []\n action = int(message)\n # print(\"Action = \", action)\n self.user.lastAction = action\n self.craftUsers = []\n self.step_action(self.user, action)\n for bot in self.bots:\n if bot.info.status == PlayerInfo.STATUS_PLAYING:\n action = bot.next_action()\n bot.info.lastAction = action\n # print(\"Bot Action: \", action)\n self.step_action(bot.info, action)\n self.action_5_craft()\n for c in self.stepState.changedObstacles:\n self.map[c[\"posy\"]][c[\"posx\"]] = -c[\"type\"]\n self.energyOnMap[c[\"posy\"]][c[\"posx\"]] = c[\"value\"]\n\n else: # reset game\n requests = message.split(\",\")\n #print(\"Reset game: \", requests[:3], end='')\n self.reset(requests)\n\n def step_action(self, user, action):\n switcher = {\n 0: self.action_0_left,\n 1: self.action_1_right,\n 2: self.action_2_up,\n 3: self.action_3_down,\n 4: self.action_4_free,\n 5: self.action_5_craft_pre\n }\n func = switcher.get(action, self.invalidAction)\n func(user)\n\n def action_5_craft_pre(self, user): # collect players who craft at current step\n user.freeCount = 0\n if self.map[user.posy][user.posx] <= 0: # craft at the non-gold cell\n user.energy -= 10\n if user.energy <= 0:\n user.status = PlayerInfo.STATUS_ELIMINATED_OUT_OF_ENERGY\n user.lastAction = 6 #eliminated\n else:\n user.energy -= 5\n if user.energy > 0:\n self.craftUsers.append(user)\n key = str(user.posx) + \"_\" + str(user.posy)\n if key in self.craftMap:\n count = self.craftMap[key]\n self.craftMap[key] = count + 1\n else:\n self.craftMap[key] = 1\n else:\n user.status = PlayerInfo.STATUS_ELIMINATED_OUT_OF_ENERGY\n user.lastAction = 6 #eliminated\n\n def action_0_left(self, user): # user go left\n user.freeCount = 0\n user.posx = user.posx - 1\n if user.posx < 0:\n user.status = PlayerInfo.STATUS_ELIMINATED_WENT_OUT_MAP\n user.lastAction = 6 #eliminated\n else:\n self.go_to_pos(user)\n\n def action_1_right(self, user): # user go right\n user.freeCount = 0\n user.posx = user.posx + 1\n if user.posx >= self.userMatch.gameinfo.width:\n user.status = PlayerInfo.STATUS_ELIMINATED_WENT_OUT_MAP\n user.lastAction = 6 #eliminated\n else:\n self.go_to_pos(user)\n\n def action_2_up(self, user): # user go up\n user.freeCount = 0\n user.posy = user.posy - 1\n if user.posy < 0:\n user.status = PlayerInfo.STATUS_ELIMINATED_WENT_OUT_MAP\n user.lastAction = 6 #eliminated\n else:\n self.go_to_pos(user)\n\n def action_3_down(self, user): # user go right\n user.freeCount = 0\n user.posy = user.posy + 1\n if user.posy >= self.userMatch.gameinfo.height:\n user.status = PlayerInfo.STATUS_ELIMINATED_WENT_OUT_MAP\n user.lastAction = 6 #eliminated\n else:\n self.go_to_pos(user)\n\n def action_4_free(self, user): # user free\n user.freeCount += 1\n if user.freeCount == 1:\n user.energy += int(self.E / 4)\n elif user.freeCount == 2:\n user.energy += int(self.E / 3)\n elif user.freeCount == 3:\n user.energy += int(self.E / 2)\n else:\n user.energy = self.E\n if user.energy > self.E:\n user.energy = self.E\n\n def action_5_craft(self):\n craftCount = len(self.craftUsers)\n # print (\"craftCount\",craftCount)\n if (craftCount > 0):\n for user in self.craftUsers:\n x = user.posx\n y = user.posy\n key = str(user.posx) + \"_\" + str(user.posy)\n c = self.craftMap[key]\n m = min(math.ceil(self.map[y][x] / c), 50)\n user.score += m\n # print (\"user\", user.playerId, m)\n for user in self.craftUsers:\n x = user.posx\n y = user.posy\n key = str(user.posx) + \"_\" + str(user.posy)\n if key in self.craftMap:\n c = self.craftMap[key]\n del self.craftMap[key]\n m = min(math.ceil(self.map[y][x] / c), 50)\n self.map[y][x] -= m * c\n if self.map[y][x] < 0:\n self.map[y][x] = 0\n self.energyOnMap[y][x] = ObstacleInfo.types[0]\n for g in self.stepState.golds:\n if g.posx == x and g.posy == y:\n g.amount = self.map[y][x]\n if g.amount == 0:\n self.stepState.golds.remove(g)\n self.add_changed_obstacle(x, y, 0, ObstacleInfo.types[0])\n if len(self.stepState.golds) == 0:\n for player in self.stepState.players:\n player.status = PlayerInfo.STATUS_STOP_EMPTY_GOLD\n break;\n self.craftMap = {}\n\n def invalidAction(self, user):\n user.status = PlayerInfo.STATUS_ELIMINATED_INVALID_ACTION\n user.lastAction = 6 #eliminated\n\n def go_to_pos(self, user): # player move to cell(x,y)\n if self.map[user.posy][user.posx] == -1:\n user.energy -= randrange(16) + 5\n elif self.map[user.posy][user.posx] == 0:\n user.energy += self.energyOnMap[user.posy][user.posx]\n elif self.map[user.posy][user.posx] == -2:\n user.energy += self.energyOnMap[user.posy][user.posx]\n self.add_changed_obstacle(user.posx, user.posy, 0, ObstacleInfo.types[0])\n elif self.map[user.posy][user.posx] == -3:\n user.energy += self.energyOnMap[user.posy][user.posx]\n self.add_changed_obstacle(user.posx, user.posy, 3,\n self.bog_energy_chain[self.energyOnMap[user.posy][user.posx]])\n else:\n user.energy -= 4\n if user.energy <= 0:\n user.status = PlayerInfo.STATUS_ELIMINATED_OUT_OF_ENERGY\n user.lastAction = 6 #eliminated\n\n def add_changed_obstacle(self, x, y, t, v):\n added = False\n for o in self.stepState.changedObstacles:\n if o[\"posx\"] == x and o[\"posy\"] == y:\n added = True\n break\n if added == False:\n o = {}\n o[\"posx\"] = x\n o[\"posy\"] = y\n o[\"type\"] = t\n o[\"value\"] = v\n self.stepState.changedObstacles.append(o)\n\n def close(self):\n print(\"Close socket.\")\n\nclass Bot1:\n ACTION_GO_LEFT = 0\n ACTION_GO_RIGHT = 1\n ACTION_GO_UP = 2\n ACTION_GO_DOWN = 3\n ACTION_FREE = 4\n ACTION_CRAFT = 5\n\n def __init__(self, id):\n self.state = State()\n self.info = PlayerInfo(id)\n \n def get_state(self):\n view = np.zeros([self.state.mapInfo.max_y + 1, self.state.mapInfo.max_x + 1], dtype=int)\n for x in range(self.state.mapInfo.max_x + 1):\n for y in range(self.state.mapInfo.max_y + 1):\n if self.state.mapInfo.get_obstacle(x, y) == TreeID: # Tree\n view[y, x] = -TreeID\n if self.state.mapInfo.get_obstacle(x, y) == TrapID: # Trap\n view[y, x] = -TrapID\n if self.state.mapInfo.get_obstacle(x, y) == SwampID: # Swamp\n view[y, x] = -SwampID\n if self.state.mapInfo.gold_amount(x, y) > 0:\n view[y, x] = self.state.mapInfo.gold_amount(x, y)\n\n DQNState = view.flatten().tolist() #Flattening the map matrix to a vector\n \n #DQNState.append(self.state.x)\n #DQNState.append(self.state.y)\n #DQNState.append(self.state.energy)\n DQNState.append(self.info.posx)\n DQNState.append(self.info.posy)\n DQNState.append(self.info.energy)\n for player in self.state.players:\n # self.info.playerId is the id of the current bot\n if player[\"playerId\"] != self.info.playerId:\n DQNState.append(player[\"posx\"])\n DQNState.append(player[\"posy\"])\n \n DQNState = np.array(DQNState)\n\n return DQNState\n\n\n def next_action(self):\n s = self.get_state()\n #return int(greedy_policy(s))\n return int(non_RL_agent.greedy_policy(s))\n\n def get_score(self):\n return [player[\"score\"] for player in minerEnv.socket.bots[1].state.players if player[\"playerId\"] == self.info.playerId][0]\n\n def new_game(self, data):\n try:\n self.state.init_state(data)\n except Exception as e:\n import traceback\n traceback.print_exc()\n\n def new_state(self, data):\n # action = self.next_action();\n # self.socket.send(action)\n try:\n self.state.update_state(data)\n except Exception as e:\n import traceback\n traceback.print_exc()\n\nclass Bot2:\n ACTION_GO_LEFT = 0\n ACTION_GO_RIGHT = 1\n ACTION_GO_UP = 2\n ACTION_GO_DOWN = 3\n ACTION_FREE = 4\n ACTION_CRAFT = 5\n\n def __init__(self, id):\n self.state = State()\n self.info = PlayerInfo(id)\n \n def get_state(self):\n view = np.zeros([self.state.mapInfo.max_y + 1, self.state.mapInfo.max_x + 1], dtype=int)\n for x in range(self.state.mapInfo.max_x + 1):\n for y in range(self.state.mapInfo.max_y + 1):\n if self.state.mapInfo.get_obstacle(x, y) == TreeID: # Tree\n view[y, x] = -TreeID\n if self.state.mapInfo.get_obstacle(x, y) == TrapID: # Trap\n view[y, x] = -TrapID\n if self.state.mapInfo.get_obstacle(x, y) == SwampID: # Swamp\n view[y, x] = -SwampID\n if self.state.mapInfo.gold_amount(x, y) > 0:\n view[y, x] = self.state.mapInfo.gold_amount(x, y)\n\n DQNState = view.flatten().tolist() #Flattening the map matrix to a vector\n \n #DQNState.append(self.state.x)\n #DQNState.append(self.state.y)\n #DQNState.append(self.state.energy)\n DQNState.append(self.info.posx)\n DQNState.append(self.info.posy)\n DQNState.append(self.info.energy)\n for player in self.state.players:\n # self.info.playerId is the id of the current bot\n if player[\"playerId\"] != self.info.playerId:\n DQNState.append(player[\"posx\"])\n DQNState.append(player[\"posy\"])\n \n DQNState = np.array(DQNState)\n\n return DQNState\n\n\n\n\n def next_action(self):\n s = self.get_state()\n #return int(non_RL_agent03.greedy_policy(s))\n return int(non_RL_agent.greedy_policy(s, how_gold=non_RL_agent.find_worthiest_gold))\n \n #if self.state.mapInfo.gold_amount(self.info.posx, self.info.posy) > 0:\n # if self.info.energy >= 6:\n # return self.ACTION_CRAFT\n # else:\n # return self.ACTION_FREE\n #if self.info.energy < 5:\n # return self.ACTION_FREE\n #else:\n # action = np.random.randint(0, 4) \n # return action\n\n\n def new_game(self, data):\n try:\n self.state.init_state(data)\n except Exception as e:\n import traceback\n traceback.print_exc()\n\n def new_state(self, data):\n # action = self.next_action();\n # self.socket.send(action)\n try:\n self.state.update_state(data)\n except Exception as e:\n import traceback\n traceback.print_exc()\n \n def get_score(self):\n return [player[\"score\"] for player in minerEnv.socket.bots[1].state.players if player[\"playerId\"] == self.info.playerId][0]\n\nclass Bot3:\n ACTION_GO_LEFT = 0\n ACTION_GO_RIGHT = 1\n ACTION_GO_UP = 2\n ACTION_GO_DOWN = 3\n ACTION_FREE = 4\n ACTION_CRAFT = 5\n\n def __init__(self, id):\n self.state = State()\n self.info = PlayerInfo(id)\n\n def get_state(self):\n view = np.zeros([self.state.mapInfo.max_y + 1, self.state.mapInfo.max_x + 1], dtype=int)\n for x in range(self.state.mapInfo.max_x + 1):\n for y in range(self.state.mapInfo.max_y + 1):\n if self.state.mapInfo.get_obstacle(x, y) == TreeID: # Tree\n view[y, x] = -TreeID\n if self.state.mapInfo.get_obstacle(x, y) == TrapID: # Trap\n view[y, x] = -TrapID\n if self.state.mapInfo.get_obstacle(x, y) == SwampID: # Swamp\n view[y, x] = -SwampID\n if self.state.mapInfo.gold_amount(x, y) > 0:\n view[y, x] = self.state.mapInfo.gold_amount(x, y)\n\n DQNState = view.flatten().tolist() #Flattening the map matrix to a vector\n \n #DQNState.append(self.state.x)\n #DQNState.append(self.state.y)\n #DQNState.append(self.state.energy)\n DQNState.append(self.info.posx)\n DQNState.append(self.info.posy)\n DQNState.append(self.info.energy)\n for player in self.state.players:\n # self.info.playerId is the id of the current bot\n if player[\"playerId\"] != self.info.playerId:\n DQNState.append(player[\"posx\"])\n DQNState.append(player[\"posy\"])\n \n DQNState = np.array(DQNState)\n\n return DQNState\n\n\n def next_action(self):\n s = self.get_state()\n return int(non_RL_agent02.greedy_policy(s))\n #if self.state.mapInfo.gold_amount(self.info.posx, self.info.posy) > 0:\n # if self.info.energy >= 6:\n # return self.ACTION_CRAFT\n # else:\n # return self.ACTION_FREE\n #if self.info.energy < 5:\n # return self.ACTION_FREE\n #else:\n # action = self.ACTION_GO_LEFT\n # if self.info.posx % 2 == 0:\n # if self.info.posy < self.state.mapInfo.max_y:\n # action = self.ACTION_GO_DOWN\n # else:\n # if self.info.posy > 0:\n # action = self.ACTION_GO_UP\n # else:\n # action = self.ACTION_GO_RIGHT \n # return action\n\n def new_game(self, data):\n try:\n self.state.init_state(data)\n except Exception as e:\n import traceback\n traceback.print_exc()\n\n def new_state(self, data):\n # action = self.next_action();\n # self.socket.send(action)\n try:\n self.state.update_state(data)\n except Exception as e:\n import traceback\n traceback.print_exc()\n \n def get_score(self):\n return [player[\"score\"] for player in minerEnv.socket.bots[1].state.players if player[\"playerId\"] == self.info.playerId][0]\n\n\n#MinerState.py\ndef str_2_json(str):\n return json.loads(str, encoding=\"utf-8\")\n\n\nclass MapInfo:\n def __init__(self):\n self.max_x = 0 #Width of the map\n self.max_y = 0 #Height of the map\n self.golds = [] #List of the golds in the map\n self.obstacles = []\n self.numberOfPlayers = 0\n self.maxStep = 0 #The maximum number of step is set for this map\n\n def init_map(self, gameInfo):\n #Initialize the map at the begining of each episode\n self.max_x = gameInfo[\"width\"] - 1\n self.max_y = gameInfo[\"height\"] - 1\n self.golds = gameInfo[\"golds\"]\n self.obstacles = gameInfo[\"obstacles\"]\n self.maxStep = gameInfo[\"steps\"]\n self.numberOfPlayers = gameInfo[\"numberOfPlayers\"]\n\n def update(self, golds, changedObstacles):\n #Update the map after every step\n self.golds = golds\n for cob in changedObstacles:\n newOb = True\n for ob in self.obstacles:\n if cob[\"posx\"] == ob[\"posx\"] and cob[\"posy\"] == ob[\"posy\"]:\n newOb = False\n #print(\"cell(\", cob[\"posx\"], \",\", cob[\"posy\"], \") change type from: \", ob[\"type\"], \" -> \",\n # cob[\"type\"], \" / value: \", ob[\"value\"], \" -> \", cob[\"value\"])\n ob[\"type\"] = cob[\"type\"]\n ob[\"value\"] = cob[\"value\"]\n break\n if newOb:\n self.obstacles.append(cob)\n #print(\"new obstacle: \", cob[\"posx\"], \",\", cob[\"posy\"], \", type = \", cob[\"type\"], \", value = \",\n # cob[\"value\"])\n\n def get_min_x(self):\n return min([cell[\"posx\"] for cell in self.golds])\n\n def get_max_x(self):\n return max([cell[\"posx\"] for cell in self.golds])\n\n def get_min_y(self):\n return min([cell[\"posy\"] for cell in self.golds])\n\n def get_max_y(self):\n return max([cell[\"posy\"] for cell in self.golds])\n\n def is_row_has_gold(self, y):\n return y in [cell[\"posy\"] for cell in self.golds]\n\n def is_column_has_gold(self, x):\n return x in [cell[\"posx\"] for cell in self.golds]\n\n def gold_amount(self, x, y): #Get the amount of golds at cell (x,y)\n for cell in self.golds:\n if x == cell[\"posx\"] and y == cell[\"posy\"]:\n return cell[\"amount\"]\n return 0 \n\n def get_obstacle(self, x, y): # Get the kind of the obstacle at cell(x,y)\n for cell in self.obstacles:\n if x == cell[\"posx\"] and y == cell[\"posy\"]:\n return cell[\"type\"]\n return -1 # No obstacle at the cell (x,y)\n\n\nclass State:\n STATUS_PLAYING = 0\n STATUS_ELIMINATED_WENT_OUT_MAP = 1\n STATUS_ELIMINATED_OUT_OF_ENERGY = 2\n STATUS_ELIMINATED_INVALID_ACTION = 3\n STATUS_STOP_EMPTY_GOLD = 4\n STATUS_STOP_END_STEP = 5\n\n def __init__(self):\n self.end = False\n self.score = 0\n self.lastAction = None\n self.id = 0\n self.x = 0\n self.y = 0\n self.energy = 0\n self.energy_pre = 0\n self.mapInfo = MapInfo()\n self.players = []\n self.stepCount = 0\n self.status = State.STATUS_PLAYING\n\n def init_state(self, data): #parse data from server into object\n game_info = str_2_json(data)\n self.end = False\n self.score = 0\n self.lastAction = None\n self.id = game_info[\"playerId\"]\n self.x = game_info[\"posx\"]\n self.y = game_info[\"posy\"]\n self.energy = game_info[\"energy\"]\n self.mapInfo.init_map(game_info[\"gameinfo\"])\n self.stepCount = 0\n self.status = State.STATUS_PLAYING\n self.players = [{\"playerId\": 2, \"posx\": self.x, \"posy\": self.y},\n {\"playerId\": 3, \"posx\": self.x, \"posy\": self.y},\n {\"playerId\": 4, \"posx\": self.x, \"posy\": self.y}]\n\n def update_state(self, data):\n new_state = str_2_json(data)\n for player in new_state[\"players\"]:\n if player[\"playerId\"] == self.id:\n self.x = player[\"posx\"]\n self.y = player[\"posy\"]\n self.energy_pre = self.energy\n self.energy = player[\"energy\"]\n self.score = player[\"score\"]\n self.lastAction = player[\"lastAction\"]\n self.status = player[\"status\"]\n\n self.mapInfo.update(new_state[\"golds\"], new_state[\"changedObstacles\"])\n self.players = new_state[\"players\"]\n for i in range(len(self.players), 4, 1):\n self.players.append({\"playerId\": i, \"posx\": self.x, \"posy\": self.y})\n self.stepCount = self.stepCount + 1\n\n\n#MinerEnv.py\nTreeID = 1\nTrapID = 2\nSwampID = 3\nclass MinerEnv:\n def __init__(self):\n self.socket = GameSocket()\n self.state = State()\n \n self.score_pre = self.state.score#Storing the last score for designing the reward function\n\n def start(self): #connect to server\n self.socket.connect()\n\n def end(self): #disconnect server\n self.socket.close()\n\n def send_map_info(self, request):#tell server which map to run\n self.socket.send(request)\n\n def reset(self): #start new game\n try:\n message = self.socket.receive() #receive game info from server\n self.state.init_state(message) #init state\n except Exception as e:\n import traceback\n traceback.print_exc()\n\n def step(self, action): #step process\n self.socket.send(action) #send action to server\n try:\n message = self.socket.receive() #receive new state from server\n self.state.update_state(message) #update to local state\n except Exception as e:\n import traceback\n traceback.print_exc()\n\n def get_state(self):\n \"\"\"\n Fuse `view` and `energyOnMap` into a single matrix to have a simple and concise state/observation.\n\n We want a matrix showing the following:\n `gold`: The amount of gold\n `all the others`: The energy that each type of terrain is going to take if being stepped into, e.g.\n `land` => -1, `trap` => -10, etc.\n \"\"\"\n view = np.zeros([self.state.mapInfo.max_y + 1, self.state.mapInfo.max_x + 1], dtype=int)\n for x in range(self.state.mapInfo.max_x + 1):\n for y in range(self.state.mapInfo.max_y + 1):\n if self.state.mapInfo.get_obstacle(x, y) == TreeID: # Tree\n view[y, x] = -TreeID\n if self.state.mapInfo.get_obstacle(x, y) == TrapID: # Trap\n view[y, x] = -TrapID\n if self.state.mapInfo.get_obstacle(x, y) == SwampID: # Swamp\n view[y, x] = -SwampID\n if self.state.mapInfo.gold_amount(x, y) > 0:\n view[y, x] = self.state.mapInfo.gold_amount(x, y)\n energyOnMap = np.array(self.socket.energyOnMap)\n\n # `view` will contribute only to the type of terrain of `gold`\n view[view <= 0] = -9999 # Just a dummy large negative number to be got rid of later\n # `energyOnMap` will contribute to the types of terrain of `land`, `trap`, `forest` and `swamp`.\n # Recall. `forest` was designated by BTC to the value of 0, to mean random integer btw [5..20].\n energyOnMap[energyOnMap == 0] = - constants.forest_energy\n channel0 = np.maximum(view, energyOnMap)\n # Finish channel 0\n # Channel 1 will contain the position of the agent\n channel1 = np.zeros_like(channel0)\n x_agent_out_of_map = self.state.x < 0 or self.state.x >= constants.width\n y_agent_out_of_map = self.state.y < 0 or self.state.y >= constants.height\n if x_agent_out_of_map or y_agent_out_of_map:\n pass\n else:\n channel1[self.state.y, self.state.x] = self.state.energy\n state = np.stack((channel0, channel1), axis=-1)\n return state\n\n\n def get_reward(self):\n # Initialize reward\n reward = 0\n score_action = self.state.score - self.score_pre\n self.score_pre = self.state.score\n if score_action > 0:\n #reward += score_action*(100 - self.state.stepCount)\n reward += score_action\n \n\n #if self.state.mapInfo.get_obstacle(self.state.x, self.state.y) == TreeID: # Tree\n # reward -= TreeID\n #if self.state.mapInfo.get_obstacle(self.state.x, self.state.y) == TrapID: # Trap\n # reward -= TrapID\n #if self.state.mapInfo.get_obstacle(self.state.x, self.state.y) == SwampID: # Swamp\n # reward -= SwampID\n # if self.state.lastAction == 4:\n # reward -= 40\n\n #if self.state.status == State.STATUS_ELIMINATED_WENT_OUT_MAP:\n if self.state.status == constants.agent_state_str2id[\"out_of_MAP\"]:\n #if self.state.stepCount < 50:\n # reward += -5*(50 - self.state.stepCount)\n reward -= 2000\n else:\n try:\n s = self.get_state()\n #print(f\"self.state.x, self.state.y = {self.state.x}, {self.state.y} \")\n terrain_now = s[self.state.y, self.state.x, 0]\n if terrain_now < 0 and self.state.lastAction != constants.rest:\n # This substract the same amount of reward as energy when the agent steps into terrain_now, except for gold\n reward += terrain_now\n except Exception:\n pass\n\n \n #if self.state.status == State.STATUS_STOP_END_STEP:\n if self.state.status == constants.agent_state_str2id[\"no_more_STEP\"]:\n #reward += (self.state.score/total_gold) * 100\n pass\n #if self.state.status == State.STATUS_ELIMINATED_OUT_OF_ENERGY:\n if self.state.status == constants.agent_state_str2id[\"no_more_ENERGY\"]:\n if self.state.lastAction != constants.rest:\n reward -= 500\n \n #if self.state.status == State.STATUS_PLAYING:\n if self.state.status == constants.agent_state_str2id[\"PLAYing\"]:\n reward += 1\n # We punish surplus `rest`\n if self.state.energy_pre == constants.max_energy and self.state.lastAction == constants.rest:\n reward -= 50\n\n return reward\n\n def check_terminate(self):\n #Checking the status of the game\n #it indicates the game ends or is playing\n return self.state.status != State.STATUS_PLAYING\n\n\nMaps = [constants.maps[i] for i in range(1, 6)]\nenv = MinerEnv() # Creating a communication environment between the DQN model and the game environment\nenv.start() # Connect to the game\n\n\n\n#eliminated = []\n#def pictorial_state(obs):\n# pictorial = np.zeros((constants.height, constants.width, 1+4), dtype=np.float32)\n# # 1+4 is +1 for map and +1 for each of the players = 5 channels\n# # dtype=np.float32 because pictorial will later be carried into tensorflow CNN\n# pictorial[..., 0] = obs[:constants.n_px].reshape((constants.height, constants.width))\n# # position of agent: we put the energy value at the coordinate where stands the agent, the whole in channel 1, the channel for the agent.\n# x_agent, y_agent = obs[constants.n_px], obs[constants.n_px+1]\n# if x_agent >= constants.width or y_agent >= constants.height:\n# pass\n# else:\n# pictorial[y_agent, x_agent, 1] = obs[constants.n_px+2]\n# # position of bots: we put -1 on the coord of the bots\n# for i in range(1, 3+1):\n# if i in eliminated:\n# continue\n# y = obs[constants.n_px+(2*i+2)]\n# x = obs[constants.n_px+(2*i+1)]\n# if x >= constants.width or y >= constants.height:\n# eliminated.append(i)\n# continue\n# pictorial[y, x, i+1] = -1\n# return pictorial\n\n\n\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten\n\n\ntf.random.set_seed(42)\nnp.random.seed(42)\n\n#input_shape = [constants.height, constants.width, 1+4]\ninput_shape = [constants.height, constants.width, 1+1]\nn_outputs = 6\n\nmodel = keras.models.Sequential([\n Conv2D(4, 3, activation=\"relu\", padding=\"same\", input_shape=input_shape),\n #MaxPooling2D(2),\n Conv2D(8, 3, activation=\"relu\", padding=\"same\"),\n #Conv2D(128, 3, activation=\"relu\", padding=\"same\"),\n #MaxPooling2D(2),\n Flatten(),\n #Dense(128, activation=\"elu\"),\n Dense(128, activation=\"elu\"),\n Dense(64, activation=\"elu\"),\n Dense(32, activation=\"elu\"),\n Dense(n_outputs)\n])\ntarget = keras.models.clone_model(model)\ntarget.set_weights(model.get_weights())\n\n\n\nfrom collections import deque\nreplay_memory = deque(maxlen=max_replay_len)\n\n\ndef sample_experiences(batch_size):\n indices = np.random.randint(len(replay_memory), size=batch_size)\n batch = [replay_memory[index] for index in indices]\n states, actions, rewards, next_states, dones = [\n np.array([experience[field_index] for experience in batch])\n for field_index in range(5)]\n return states, actions, rewards, next_states, dones\n\n\ndef epsilon_greedy_policy(state, epsilon=0, n_actions=6):\n if np.random.rand() < epsilon:\n return np.random.randint(n_actions)\n else:\n #pictorial = pictorial_state(state)\n #Q_values = model.predict(pictorial[np.newaxis])\n Q_values = model.predict(state[np.newaxis])\n return np.argmax(Q_values[0])\n\n\ndef play_one_step(env, state, epsilon):\n action = epsilon_greedy_policy(state, epsilon)\n #next_state, reward, done, info = env.step(action)\n env.step(str(action))\n next_state = env.get_state()\n reward = env.get_reward()\n done = env.check_terminate()\n replay_memory.append((state, action, reward, next_state, done))\n return next_state, reward, done\n\n\n#optimizer = keras.optimizers.Adam(lr=1e-3)\n#optimizer = keras.optimizers.Adam(lr=2.5e-4)\noptimizer = keras.optimizers.Adam(lr=lr_optimizer)\n\ndef training_step(batch_size):\n experiences = sample_experiences(batch_size)\n states, actions, rewards, next_states, dones = experiences\n #pictorials = np.array([pictorial_state(s) for s in states])\n #next_pictorials = np.array([pictorial_state(next_s) for next_s in next_states])\n #next_Q_values = model.predict(next_pictorials)\n next_Q_values = model.predict(next_states)\n #max_next_Q_values = np.max(next_Q_values, axis=1)\n best_next_actions = np.argmax(next_Q_values, axis=1)\n next_mask = tf.one_hot(best_next_actions, n_outputs).numpy()\n next_best_Q_values = (target.predict(next_states) * next_mask).sum(axis=1)\n #target_Q_values = rewards + (1 - dones) * discount_rate * max_next_Q_values\n target_Q_values = rewards + (1 - dones) * discount_rate * next_best_Q_values\n target_Q_values = target_Q_values.reshape(-1, 1)\n mask = tf.one_hot(actions, n_outputs)\n with tf.GradientTape() as tape:\n #all_Q_values = model(pictorials)\n all_Q_values = model(states)\n Q_values = tf.reduce_sum(all_Q_values * mask, axis=1, keepdims=True)\n loss = tf.reduce_mean(loss_fn(target_Q_values, Q_values))\n grads = tape.gradient(loss, model.trainable_variables)\n optimizer.apply_gradients(zip(grads, model.trainable_variables))\n\n\nnp.random.seed(42)\ntf.random.set_seed(42)\n\n\nfrom constants import n_allowed_steps\n\nnow = datetime.datetime.now()\nnow_str = now.strftime(\"%Y%m%d-%H%M\")\nscript_name = __file__.split('.')[0]\nsave_path = os.path.join(\"models\", script_name)\nos.makedirs(save_path, exist_ok=True)\n\n\nscores = [] \nscores_avg = [] \nbest_score = 0\nk = 10\nscores_k_most_recent = deque([0]*k, maxlen=k)\nbest_score_avg = 1400\n\nwith open(os.path.join(save_path, f\"log-{now_str}.txt\"), 'w') as log:\n for episode in range(n_episodes):\n eliminated = []\n mapID = np.random.randint(0, 5)\n posID_x = np.random.randint(constants.width) \n posID_y = np.random.randint(constants.height)\n request = \"map{},{},{},50,100\".format(mapID, posID_x, posID_y)\n env.send_map_info(request)\n env.reset()\n obs = env.get_state()\n undiscounted_return = 0\n for step in range(n_allowed_steps):\n epsilon = max(1 - episode / n_epsilon_decay, 0.01)\n obs, reward, done = play_one_step(env, obs, epsilon)\n undiscounted_return += reward\n if done:\n break\n score = env.state.score\n scores.append(score)\n scores_k_most_recent.append(score)\n #score_avg = np.mean(scores_k_most_recent) / k\n score_avg = round(np.mean(scores_k_most_recent), 1)\n scores_avg.append(score_avg)\n #if score > best_score:\n if score_avg > best_score_avg:\n #best_weights = model.get_weights()\n best_score_avg = score_avg \n #best_score = score\n #model.save(os.path.join(save_path, f\"episode-{episode+1}-gold-{env.state.score}-avg-{score_avg:4.2f}-step-{step+1}-{now_str}.h5\"))\n model.save(os.path.join(save_path, f\"avg-{score_avg:07.2f}-episode-{episode+1}-{__file__.split('.')[0]}-gold-{env.state.score}-step-{step+1}-{now_str}.h5\"))\n \n #message = \"(Episode {: 5d}/{}) Gold {: 4d} avg {: 8.2f} undisc_return {: 6d} step {: 3d} eps {:.2f} ({})\\n\".format(episode+1, n_episodes, env.state.score, score_avg, undiscounted_return, step + 1, epsilon, constants.agent_state_id2str[env.state.status])\n message = \"(Episode {: 5d}/{}) Gold {: 4d} avg {: 8.1f} undisc_return {: 6d} step {: 3d} eps: {:.2f} ({})\\n\".format(episode+1, n_episodes, env.state.score, score_avg, undiscounted_return, step + 1, epsilon, constants.agent_state_id2str[env.state.status])\n ##############################################\n #score = env.state.score*(n_allowed_steps - step)\n #score = env.state.score\n #scores.append(score)\n #if score > best_score:\n # #best_weights = model.get_weights()\n # best_score = score\n # model.save(os.path.join(save_path, f\"episode-{episode+1}-gold-{env.state.score}-step-{step+1}-{now_str}.h5\"))\n \n #message = \"(Episode {: 5d}/{}) Gold: {: 4d} undiscounted_return: {: 6d} Steps: {: 3d} eps: {:.3f} ({})\\n\".format(episode+1, n_episodes, env.state.score, undiscounted_return, step + 1, epsilon, constants.agent_state_id2str[env.state.status])\n print(message, end='')\n log.write(message)\n \n #if episode > 500:\n if episode > n_episodes_buf_fill:\n training_step(batch_size)\n if episode % n_episodes_buf_fill == 0:\n target.set_weights(model.get_weights())\n\n#np.save(f\"scores-{now_str}\", np.array(scores))\n#np.save(f\"scores-N-scores_avg-{now_str}\", np.array([scores, scores_avg]))\nnp.save(f\"scores-N-scores_avg-{__file__.split('.')[0]}-{now_str}\", np.array([scores, scores_avg]))\n"
] | [
[
"tensorflow.keras.models.clone_model",
"tensorflow.reduce_sum",
"numpy.zeros_like",
"numpy.mean",
"tensorflow.random.set_seed",
"numpy.random.randint",
"tensorflow.keras.layers.Conv2D",
"numpy.stack",
"numpy.argmax",
"tensorflow.keras.layers.Flatten",
"numpy.zeros",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.losses.Huber",
"tensorflow.one_hot",
"numpy.random.rand",
"numpy.array",
"tensorflow.GradientTape",
"numpy.maximum",
"numpy.random.seed",
"tensorflow.keras.optimizers.Adam"
],
[
"matplotlib.pyplot.imshow",
"numpy.ones",
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.figure"
],
[
"tensorflow.keras.models.clone_model",
"numpy.random.seed",
"tensorflow.keras.layers.Dense",
"tensorflow.reduce_sum",
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.losses.Huber",
"tensorflow.GradientTape",
"tensorflow.keras.optimizers.Adam",
"numpy.argmax",
"tensorflow.one_hot",
"numpy.random.rand",
"numpy.mean",
"numpy.array",
"tensorflow.keras.layers.Flatten",
"tensorflow.random.set_seed",
"numpy.random.randint"
],
[
"tensorflow.keras.models.clone_model",
"tensorflow.reduce_sum",
"numpy.zeros_like",
"numpy.mean",
"tensorflow.random.set_seed",
"numpy.random.randint",
"tensorflow.keras.layers.Conv2D",
"numpy.stack",
"numpy.argmax",
"tensorflow.keras.layers.Flatten",
"numpy.zeros",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.losses.Huber",
"tensorflow.one_hot",
"numpy.random.rand",
"numpy.array",
"tensorflow.GradientTape",
"numpy.maximum",
"numpy.random.seed",
"tensorflow.keras.optimizers.Adam"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
rkj26/mgplvm-pytorch | [
"7d082d92be4d82ae8ab978e774ce83429444c14b",
"7d082d92be4d82ae8ab978e774ce83429444c14b"
] | [
"mgplvm/crossval.py",
"examples/mouse/run_mouse.py"
] | [
"import os\nimport numpy as np\nimport mgplvm\nimport torch\nfrom mgplvm import kernels, rdist\nfrom mgplvm.manifolds import Torus, Euclid, So3\nfrom mgplvm.models import Core\nfrom mgplvm.training import train\nimport matplotlib.pyplot as plt\nimport pickle\nfrom scipy.stats import ttest_1samp\ntorch.set_default_dtype(torch.float64)\n\n\ndef initialize(Y,\n device,\n d,\n n,\n m,\n n_z,\n fit_manif=Torus,\n GPparams=None,\n Ntrain=None,\n Tfix=slice(0),\n sig0=1.5,\n ell0=2):\n\n if fit_manif == So3:\n sig0 = 0.4 # sqrt diagonal covariance matrix\n elif fit_manif == Torus:\n sig0 = np.pi / 2\n else:\n sig0 = 1\n\n if GPparams is None:\n\n gammas = None\n mu = None\n ell = np.ones(n) * ell0\n alpha = np.mean(np.std(Y, axis=1), axis=1)\n sigma = np.mean(np.std(Y, axis=1), axis=1) # initialize noise\n z = None\n else:\n # get raw params since we don't have inverse map\n mu = GPparams.manif.mu.data.cpu().numpy()\n\n # get .prms since we initialize with inv_transform\n gammas = GPparams.rdist.prms.data.cpu().numpy()\n alpha, ell = [\n prm.data.cpu().numpy()[Ntrain] for prm in GPparams.kernel.prms\n ]\n sigma, z = [prm.data.cpu()[Ntrain, :, :] for prm in GPparams.sgp.prms]\n sigma = sigma[:, 0, 0]\n\n # construct model\n manif = fit_manif(m, d, mu=mu, Tinds=Tfix)\n ref_dist = mgplvm.rdist.MVN(m, d, sigma=sig0, gammas=gammas, Tinds=Tfix)\n kernel = kernels.QuadExp(n, manif.distance, alpha=alpha, ell=ell)\n mod = Core(manif, n, m, n_z, kernel, ref_dist, sigma=sigma, z=z).to(device)\n\n return mod\n\n\ndef recover_model(fname, device):\n params = pickle.load(open(fname + '.pickled', 'rb'))\n manifdict = {'Torus': Torus, 'Euclid': Euclid, 'So3': So3}\n kerneldict = {'QuadExp': kernels.QuadExp}\n rdistdict = {'MVN': mgplvm.rdist.MVN}\n moddict = {'Core': Core}\n manif = params['manif'].split('(')[0]\n manif = 'So3' if manif == 'So' else manif\n m, n, d, n_z = [params[key] for key in ['m', 'n', 'd', 'n_z']]\n manif = manifdict[manif](m, d)\n kernel = kerneldict[params['kernel']](n, manif.distance)\n ref_dist = rdistdict[params['rdist']](m, d)\n mod = moddict[params['model']](manif, n, m, n_z, kernel, ref_dist)\n mod_params = torch.load(fname + '.torch')\n mod.load_state_dict(mod_params)\n mod.to(device)\n return mod, params\n\n\ndef train_cv(Y,\n manifs,\n n_z,\n device,\n callback=None,\n max_steps=500,\n n_b=128,\n lrate=5e-2,\n randN=True,\n frac=2,\n outname='test',\n sig0=1.5,\n ell0=2,\n burnin='default'):\n '''\n given a dataset Y and a set of manifolds, fit each manifold to the data\n manifs is a list of (manif, d)\n frac is the inverse fraction of neurons used in the test set\n '''\n\n def trainfunc(Y, mod, burnin, trainGP=True, Tfix=slice(0), callback=None):\n nbatch = 1\n nbatch_max = 100\n while nbatch < nbatch_max:\n if nbatch > 1:\n print('nbatch = ' + str(nbatch))\n try:\n return train(Y,\n mod,\n device,\n trainGP=trainGP,\n Tfix=Tfix,\n max_steps=max_steps,\n n_b=n_b,\n callback=callback,\n lrate=lrate,\n burnin=burnin,\n nbatch=nbatch)\n except RuntimeError:\n nbatch += 1\n\n raise RuntimeError('maximum batch size exceeded')\n\n try:\n os.mkdir(outname)\n except FileExistsError:\n print(outname, 'already exists')\n\n n, m = Y.shape[:2]\n m1, n1 = int(m - m / frac), int(n - n / frac) # 'test'\n\n # random shuffle of timepoints\n Tshuff = np.random.permutation(np.arange(m))\n T1, T2 = Tshuff[:m1], Tshuff[m1:]\n\n # random shuffle of neurons\n Nshuff = np.random.permutation(np.arange(n)) if randN else np.arange(n)\n N1, N2 = Nshuff[:n1], Nshuff[n1:]\n\n Y1, Y2, Y3 = Y[:, T1], Y[N1, :], Y[N2, :]\n\n params = {'Y': Y, 'N1': N1, 'N2': N2, 'T1': T1, 'T2': T2}\n for i, (fit_manif, d) in enumerate(manifs):\n\n print('\\nfitting manifold', fit_manif(m, d).name)\n\n if (burnin != 'default'):\n burn = int(round(burnin / 3))\n else:\n burn = burnin\n\n # fit all neurons half timepoints\n mod1 = initialize(Y1,\n device,\n d,\n n,\n m1,\n n_z,\n fit_manif=fit_manif,\n sig0=sig0,\n ell0=ell0)\n trainfunc(Y1, mod1, burn)\n mod1.store_model(outname + '/' + str(i) + '_mod1', extra_params=params)\n\n # fit all timepoints half neurons\n mod2 = initialize(Y2,\n device,\n d,\n n1,\n m,\n n_z,\n fit_manif=fit_manif,\n GPparams=mod1,\n Ntrain=N1,\n Tfix=T1,\n sig0=sig0,\n ell0=ell0)\n trainfunc(Y2, mod2, burn, trainGP=False, Tfix=T1, callback=callback)\n mod2.store_model(outname + '/' + str(i) + '_mod2')\n del mod2\n torch.cuda.empty_cache()\n\n # fit all timepoints half neurons reverse\n mod3 = initialize(Y3,\n device,\n d,\n n1,\n m,\n n_z,\n fit_manif=fit_manif,\n GPparams=mod1,\n Ntrain=N2,\n Tfix=T1,\n sig0=sig0,\n ell0=ell0)\n if frac == 2:\n trainfunc(Y3, mod3, burn, trainGP=False, Tfix=T1, callback=callback)\n\n mod3.store_model(outname + '/' + str(i) + '_mod3')\n\n del mod1\n del mod3\n\n torch.cuda.empty_cache()\n\n return params\n\n\ndef gen_cvmodels(fbase, device, Type='MSE'):\n\n mod1, params1 = recover_model(fbase + '1', device)\n mod2, params2 = recover_model(fbase + '2', device)\n mod3, params3 = recover_model(fbase + '3', device)\n\n T1, T2 = [params1[key] for key in ['T1', 'T2']]\n\n if Type == 'MSE':\n mus2_T2 = mod2.manif.prms[T2, ...].detach()\n mus3_T2 = mod3.manif.prms[T2, ...].detach()\n for mod in [mod2, mod3]:\n # change variational parameters mu, gamma to reference\n mod.manif.mu = torch.nn.Parameter(mod1.manif.mu.detach())\n mod.rdist.gamma = torch.nn.Parameter(mod1.rdist.gamma.detach())\n mod.rdist.m, mod.manif.m, mod.m, mod.sgp.m = [\n len(T1) for _ in range(4)\n ]\n\n return mod1, mod2, mod3, params1, mus2_T2, mus3_T2\n\n else:\n mus = [mod.manif.mu[T2, ...].detach() for mod in [mod3, mod2]]\n gammas = [mod.rdist.gamma[T2, ...].detach() for mod in [mod3, mod2]]\n\n # swap variational distributions\n for mod, mu, gamma in zip([mod2, mod3], mus, gammas):\n mod.manif.mu = torch.nn.Parameter(mu)\n mod.rdist.gamma = torch.nn.Parameter(gamma)\n mod.rdist.m, mod.manif.m, mod.m, mod.sgp.m = [\n len(T2) for _ in range(4)\n ]\n\n return mod1, mod2, mod3, params1\n\n\ndef calc_NLLs(fname, device=None, itermax='none', itermin=0, twoway=True):\n iterdirs = np.sort(os.listdir(fname))\n iterdirs = iterdirs if itermax == 'none' else iterdirs[:itermax]\n iterdirs = iterdirs[itermin:]\n niter = len(iterdirs)\n device = mgplvm.utils.get_device() if device is None else device\n print('\\ncomputing cross-validated log likelihoods')\n\n for (i_iter, iterdir) in enumerate(iterdirs):\n manifs = np.sort(os.listdir(fname + \"/\" + iterdir))\n nmanif = np.amax([int(f[0]) for f in manifs]) + 1\n\n if i_iter == 0:\n NLLs = np.zeros((niter, nmanif))\n print(niter, 'iterations &', nmanif, 'manifolds')\n\n for i_manif in range(nmanif):\n\n mod1, mod2, mod3, params = gen_cvmodels(fname + \"/\" + iterdir +\n '/' + str(i_manif) + '_mod',\n device,\n Type='LL')\n Y, N1, N2, T2 = [params[key] for key in ['Y', 'N1', 'N2', 'T2']]\n Y2, Y3 = Y[N1, :, :], Y[N2, :, :]\n data2, data3 = [\n torch.tensor(Ytest[:, T2, :], dtype=torch.get_default_dtype())\n for Ytest in [Y2, Y3]\n ]\n\n # calc LL and MSE\n LL2 = mod2.calc_LL(data2.to(device),\n 128).data.cpu().numpy() # trained on Y2\n LL3 = mod3.calc_LL(data3.to(device),\n 128).data.cpu().numpy() # trained on Y3\n\n if twoway:\n NLL = -(LL2 + LL3) / 2\n else:\n NLL = -LL2\n\n NLLs[i_iter, i_manif] = NLL\n print(str(i_iter) + ':', mod1.manif.name, 'NLL=' + str(NLL))\n\n return NLLs\n\n\ndef calc_MSEs(fname,\n device=None,\n itermax='none',\n iterp=100,\n itermin=0,\n twoway=True):\n\n print('\\ncomputing cross-validated mean squared errors')\n\n iterdirs = np.sort(os.listdir(fname))\n iterdirs = iterdirs if itermax == 'none' else iterdirs[:itermax]\n iterdirs = iterdirs[itermin:]\n niter = len(iterdirs)\n device = mgplvm.utils.get_device() if device is None else device\n\n for (i_iter, iterdir) in enumerate(iterdirs):\n manifs = np.sort(os.listdir(fname + \"/\" + iterdir))\n nmanif = np.amax([int(f[0]) for f in manifs]) + 1\n\n if i_iter == 0:\n MSEs = np.zeros((niter, nmanif))\n print(niter, 'iterations &', nmanif, 'manifolds')\n\n for i_manif in range(nmanif):\n\n mod1, mod2, mod3, params, mus2_T2, mus3_T2 = gen_cvmodels(\n fname + \"/\" + iterdir + '/' + str(i_manif) + '_mod',\n device,\n Type='MSE')\n\n Y, T1, T2, N1, N2 = [\n params[key] for key in ['Y', 'T1', 'T2', 'N1', 'N2']\n ]\n Y2, Y3 = Y[N1, :, :], Y[N2, :, :]\n\n data2, data3 = [\n torch.tensor(Ytrain[:, T1, :],\n dtype=torch.get_default_dtype()).to(device)\n for Ytrain in [Y2, Y3]\n ]\n\n # trained on T1 (data), predict on T2 (manif.mu)\n mus3_T2 = mus3_T2.to(device)\n fmean2, _ = mod2.predict(data2, mus3_T2, niter=iterp)\n fmean3, _ = mod3.predict(data3, mus2_T2, niter=iterp)\n MSE2 = np.mean((fmean2.cpu().numpy() - Y2[:, T2, :])**2)\n MSE3 = np.mean((fmean3.cpu().numpy() - Y3[:, T2, :])**2)\n\n var2 = np.mean(np.var(Y2[:, T2, 0], axis=1))\n var3 = np.mean(np.var(Y3[:, T2, 0], axis=1))\n\n if twoway:\n MSE = (MSE2 + MSE3) / 2\n else:\n MSE = MSE3\n\n MSEs[i_iter, i_manif] = MSE\n print(str(i_iter) + ':', mod1.manif.name, MSE, (var2 + var3) / 2)\n\n for mod in [mod1, mod2, mod3]:\n del mod\n torch.cuda.empty_cache()\n\n return MSEs\n",
"import numpy as np\nimport pickle\nimport matplotlib.pyplot as plt\nimport torch\nfrom torch import optim\n\nimport mgplvm\nfrom mgplvm import kernels, rdist\nfrom mgplvm.manifolds import Torus, Euclid, So3\nfrom mgplvm.models import Core\nfrom mgplvm.training import train\nfrom mgplvm.utils import get_device\n\ntorch.set_default_dtype(torch.float64)\nnp.random.seed(9310207)\ntorch.manual_seed(9310207)\n\n\ndef fit_th1(nbatch=2, epoch='wake', manif=Torus, d=1, n_z=10, ell0=1.5, sig0=2):\n '''epoch is wake or sleep\n manif is the latent topology, d is the dimensionality.\n nbatch can be increased in case in case of insufficien RAM.\n n_z is number of inducing points'''\n\n device = get_device()\n print(device)\n\n data = pickle.load(open('./binned_data.pickled', 'rb'))\n if epoch == 'wake':\n Y, zs = data['Y_wake'], data['hd_wake']\n else:\n Y, zs = data['Y_sleep'], data['hd_sleep']\n\n n, m = Y.shape\n\n # sqrt normalize to stabilize variance\n Y = np.sqrt(Y)\n Y = Y - np.mean(Y, axis=1, keepdims=True)\n\n n_z = 10 # number of inducing points\n alpha = np.std(Y, axis=1)\n sigma = np.std(Y, axis=1) # initialize noise\n\n manif = manif(m, d, mu=None) # initialize mean at identity\n ref_dist = mgplvm.rdist.MVN(m, d, sigma=sig0) # base distribution\n kernel = mgplvm.kernels.QuadExp(n,\n manif.distance,\n alpha=alpha,\n ell=np.ones(n) * ell0)\n mod = Core(manif, n, m, n_z, kernel, ref_dist, sigma=sigma).to(device)\n\n Y = Y.reshape(n, m, 1).astype(np.float64) # only one sample\n\n print('fitting', manif.name, 'to', epoch)\n print('neurons:', n, ' timepoints: ', m)\n\n def callback(model, i):\n ''' plot progress during optimization '''\n if i % 10 == 0:\n manifs = model.manif if type(model.manif) == list else [model.manif]\n plt.figure()\n msize = 3\n g_mus = model.manif.prms.data.cpu().numpy()[:, 0]\n if epoch == 'wake':\n plt.plot(zs[:], g_mus, \"ko\", markersize=msize)\n else:\n plt.plot(np.arange(len(g_mus)),\n np.sort(g_mus),\n \"ko\",\n markersize=msize)\n plt.xlabel('head direction')\n plt.ylabel('inferred latent')\n plt.title('i = ' + str(i))\n plt.savefig(\"yo\")\n plt.close()\n\n try:\n # train model\n trained_mod = train(Y,\n mod,\n device,\n optimizer=optim.Adam,\n outdir='none',\n max_steps=1000,\n burnin=200,\n n_b=128,\n lrate=5E-2,\n callback=callback,\n nbatch=nbatch)\n except RuntimeError:\n print('out of memory, consider increasing nbatch from', nbatch)\n return\n\n # save model\n trained_mod.store_model('mouse_' + epoch,\n extra_params={\n 'Y': Y,\n 'zs': zs\n })\n\n\nif __name__ == '__main__':\n print('running')\n fit_th1(manif=Torus, epoch='wake', d=1)\n"
] | [
[
"torch.nn.Parameter",
"torch.load",
"torch.set_default_dtype",
"numpy.arange",
"torch.cuda.empty_cache",
"numpy.ones",
"numpy.std",
"numpy.var",
"torch.get_default_dtype",
"numpy.zeros"
],
[
"numpy.sqrt",
"numpy.random.seed",
"torch.set_default_dtype",
"torch.manual_seed",
"matplotlib.pyplot.savefig",
"numpy.ones",
"matplotlib.pyplot.plot",
"numpy.sort",
"numpy.std",
"matplotlib.pyplot.ylabel",
"numpy.mean",
"matplotlib.pyplot.close",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
JanAlexanderZak/ml_cheatsheet | [
"92eef8c5a5c475fce956154a9169c60da61e5199"
] | [
"src/deep_learning/matrix_geometric_interpretation.py"
] | [
"import matplotlib.pyplot as plt\n\na = (0, 0, 0.5, 1)\nb = (0, 0, 1, 0.25)\narrow_a = plt.arrow(a[0], a[1], a[2], a[3])\narrow_b = plt.arrow(b[0], b[1], b[2], b[3])\nresult = plt.arrow(\n a[0] + b[0],\n a[1] + b[1],\n a[2] + b[2],\n a[3] + b[3],\n ec='green',\n head_width=0.02, )\nplt.legend([result, arrow_a, arrow_b], ['result', 'a', 'b'])\nplt.show()\n"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show",
"matplotlib.pyplot.arrow"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
LaudateCorpus1/benchmark | [
"2a8528f91dfbbd880e514b4deefa692a48c32af8",
"2a8528f91dfbbd880e514b4deefa692a48c32af8",
"2a8528f91dfbbd880e514b4deefa692a48c32af8"
] | [
"torchbenchmark/models/dcgan/__init__.py",
"torchbenchmark/util/framework/timm/timm_config.py",
"torchbenchmark/models/pyhpc_isoneutral_mixing/__init__.py"
] | [
"# Ported from pytorch example:\n# https://github.com/pytorch/examples/blob/master/dcgan/main.py\n\n\nfrom __future__ import print_function\nimport argparse\nimport os\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torch.utils.data\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport torchvision.utils as vutils\nimport numpy as np\n\nfrom pathlib import Path\n\nfrom ...util.model import BenchmarkModel\nfrom torchbenchmark.tasks import COMPUTER_VISION\n\nclass DCGAN:\n def __init__(self, bench):\n\n # Spatial size of training images. All images will be resized to this\n # size using a transformer.\n self.image_size = 64\n\n # Number of channels in the training images. For color images this is 3\n self.nc = 3\n\n # Size of z latent vector (i.e. size of generator input)\n self.nz = 100\n\n # Size of feature maps in generator\n self.ngf = 64\n\n # Size of feature maps in discriminator\n self.ndf = 64\n\n # Number of training epochs\n self.num_epochs = 5\n\n # Learning rate for optimizers\n self.lr = 0.0002\n\n # Beta1 hyperparam for Adam optimizers\n self.beta1 = 0.5\n\n # Number of GPUs available. Use 0 for CPU mode.\n self.ngpu = 1\n\n self.device = bench.device\n\n# custom weights initialization called on netG and netD\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n nn.init.normal_(m.weight.data, 0.0, 0.02)\n elif classname.find('BatchNorm') != -1:\n nn.init.normal_(m.weight.data, 1.0, 0.02)\n nn.init.constant_(m.bias.data, 0)\n\nclass Generator(nn.Module):\n def __init__(self, dcgan):\n super(Generator, self).__init__()\n self.ngpu = dcgan.ngpu\n self.main = nn.Sequential(\n # input is Z, going into a convolution\n nn.ConvTranspose2d( dcgan.nz, dcgan.ngf * 8, 4, 1, 0, bias=False),\n nn.BatchNorm2d(dcgan.ngf * 8),\n nn.ReLU(True),\n # state size. (dcgan.ngf*8) x 4 x 4\n nn.ConvTranspose2d(dcgan.ngf * 8, dcgan.ngf * 4, 4, 2, 1, bias=False),\n nn.BatchNorm2d(dcgan.ngf * 4),\n nn.ReLU(True),\n # state size. (dcgan.ngf*4) x 8 x 8\n nn.ConvTranspose2d( dcgan.ngf * 4, dcgan.ngf * 2, 4, 2, 1, bias=False),\n nn.BatchNorm2d(dcgan.ngf * 2),\n nn.ReLU(True),\n # state size. (dcgan.ngf*2) x 16 x 16\n nn.ConvTranspose2d( dcgan.ngf * 2, dcgan.ngf, 4, 2, 1, bias=False),\n nn.BatchNorm2d(dcgan.ngf),\n nn.ReLU(True),\n # state size. (dcgan.ngf) x 32 x 32\n nn.ConvTranspose2d( dcgan.ngf, dcgan.nc, 4, 2, 1, bias=False),\n nn.Tanh()\n # state size. (dcgan.nc) x 64 x 64\n )\n\n self.jt = None\n self.jitshape = None\n self.debug_print = False\n\n def forward(self, input):\n\n if self.debug_print:\n print(input.shape)\n\n return self.main(input)\n\nclass Discriminator(nn.Module):\n def __init__(self, ncgan):\n ngpu = ncgan.ngpu\n nc = ncgan.nc\n ndf = ncgan.ndf\n\n super(Discriminator, self).__init__()\n self.ngpu = ngpu\n self.main = nn.Sequential(\n # input is (nc) x 64 x 64\n nn.Conv2d(nc, ndf, 4, 2, 1, bias=False),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (ndf) x 32 x 32\n nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ndf * 2),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (ndf*2) x 16 x 16\n nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ndf * 4),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (ndf*4) x 8 x 8\n nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ndf * 8),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (ndf*8) x 4 x 4\n nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False),\n nn.Sigmoid()\n )\n self.jt = None\n self.jitshape = None\n\n def forward(self, input):\n return self.main(input)\n\nclass Model(BenchmarkModel):\n task = COMPUTER_VISION.GENERATION\n DEFAULT_TRAIN_BSIZE = 32\n DEFAULT_EVAL_BSIZE = 256\n\n def __init__(self, test, device, jit=False, batch_size=None, extra_args=[]):\n super().__init__(test=test, device=device, jit=jit, batch_size=batch_size, extra_args=extra_args)\n self.debug_print = False\n\n self.root = str(Path(__file__).parent)\n self.dcgan = DCGAN(self)\n\n dcgan = self.dcgan\n\n device = dcgan.device\n ngpu = dcgan.ngpu\n nz = dcgan.nz\n lr = dcgan.lr\n beta1 = dcgan.beta1\n num_epochs = dcgan.num_epochs\n\n # Create the generator\n self.netG = Generator(dcgan).to(device)\n\n # Handle multi-gpu if desired\n if (dcgan.device == 'cuda') and (ngpu > 1):\n self.netG = nn.DataParallel(self.netG, list(range(ngpu)))\n\n # Apply the weights_init function to randomly initialize all weights\n # to mean=0, stdev=0.2.\n self.netG.apply(weights_init)\n\n if self.debug_print:\n # Print the model\n print(self.netG)\n\n # Create the Discriminator\n netD = Discriminator(dcgan).to(device)\n\n # Handle multi-gpu if desired\n if (dcgan.device == 'cuda') and (ngpu > 1):\n netD = nn.DataParallel(self.netD, list(range(ngpu)))\n\n # Apply the weights_init function to randomly initialize all weights\n # to mean=0, stdev=0.2.\n netD.apply(weights_init)\n \n if self.debug_print:\n # Print the model\n print(netD)\n\n # Initialize BCELoss function\n self.criterion = nn.BCELoss()\n\n # Create batch of latent vectors that we will use to visualize\n # the progression of the generator\n self.fixed_noise = torch.randn(64, nz, 1, 1, device=device)\n\n # Establish convention for real and fake labels during training\n self.real_label = 1.\n self.fake_label = 0.\n\n # Random values as surrogate for batch of photos\n self.exmaple_inputs = torch.randn(self.batch_size, 3, 64, 64, device=self.device)\n self.model = netD\n if test == \"train\":\n # Setup Adam optimizers for both G and D\n self.optimizerD = optim.Adam(netD.parameters(), lr=lr, betas=(beta1, 0.999))\n self.optimizerG = optim.Adam(self.netG.parameters(), lr=lr, betas=(beta1, 0.999))\n elif test == \"eval\":\n # inference would just run descriminator so thats what we'll do too.\n self.inference_just_descriminator = True\n if False == self.inference_just_descriminator:\n self.eval_noise = torch.randn(self.batch_size, nz, 1, 1, device=self.device)\n\n def jit_callback(self):\n assert self.jit, \"Calling JIT callback without specifying the JIT option.\"\n self.model = torch.jit.trace(self.model,(self.exmaple_inputs,))\n if self.test == \"eval\" and False == self.inference_just_descriminator:\n self.netG = torch.jit.trace(self.netG,(self.eval_noise,))\n\n def get_module(self):\n return self.model, (self.exmaple_inputs,)\n\n def eval(self, niter=1):\n for _ in range(niter):\n\n if False == self.inference_just_descriminator:\n # Generate fake image batch with G\n self.eval_fake = self.netG(self.eval_noise)\n\n # Since we just updated D, perform another forward pass of all-fake batch through D\n output = self.model(self.exmaple_inputs).view(-1)\n return (output, )\n\n def train(self, niter=1):\n\n # Training Loop\n\n # Lists to keep track of progress\n img_list = []\n iters = 0\n\n dcgan = self.dcgan\n device = dcgan.device\n\n num_epochs = dcgan.num_epochs\n num_train_batch = niter\n\n lr = dcgan.lr\n nz = dcgan.nz\n beta1 = dcgan.beta1\n\n netD = self.model\n netG = self.netG\n\n criterion = self.criterion\n optimizerD = self.optimizerD\n optimizerG = self.optimizerG\n\n real_label = self.real_label\n fake_label = self.fake_label\n\n benchmark_pic = self.exmaple_inputs\n\n # For each epoch\n for epoch in range(num_epochs):\n\n for i in range(num_train_batch):\n\n ############################\n # (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))\n ###########################\n ## Train with all-real batch\n netD.zero_grad()\n # Format batch\n\n real_cpu = benchmark_pic\n b_size = real_cpu.size(0)\n\n label = torch.full((b_size,), real_label, dtype=torch.float, device=device)\n # Forward pass real batch through D\n output = netD(real_cpu).view(-1)\n # Calculate loss on all-real batch\n errD_real = criterion(output, label)\n # Calculate gradients for D in backward pass\n errD_real.backward()\n D_x = output.mean().item()\n\n ## Train with all-fake batch\n # Generate batch of latent vectors\n noise = torch.randn(b_size, nz, 1, 1, device=device)\n # Generate fake image batch with G\n fake = netG(noise)\n label.fill_(fake_label)\n # Classify all fake batch with D\n output = netD(fake.detach()).view(-1)\n # Calculate D's loss on the all-fake batch\n errD_fake = criterion(output, label)\n # Calculate the gradients for this batch, accumulated (summed) with previous gradients\n errD_fake.backward()\n D_G_z1 = output.mean().item()\n # Compute error of D as sum over the fake and the real batches\n errD = errD_real + errD_fake\n # Update D\n optimizerD.step()\n\n ############################\n # (2) Update G network: maximize log(D(G(z)))\n ###########################\n netG.zero_grad()\n label.fill_(real_label) # fake labels are real for generator cost\n # Since we just updated D, perform another forward pass of all-fake batch through D\n output = netD(fake).view(-1)\n # Calculate G's loss based on this output\n errG = criterion(output, label)\n # Calculate gradients for G\n errG.backward()\n D_G_z2 = output.mean().item()\n # Update G\n optimizerG.step()\n",
"import torch.nn as nn\nimport dataclasses\nfrom timm.optim import create_optimizer\n\[email protected]\nclass OptimizerOption:\n lr: float\n opt: str\n weight_decay: float\n momentum: float\n\nclass TimmConfig:\n def __init__(self, model, device):\n self.model = model\n self.device = device\n # Configurations\n self.num_classes = self.model.num_classes\n self.loss = nn.CrossEntropyLoss().to(self.device)\n self.target_shape = tuple()\n self.input_size = self.model.default_cfg[\"input_size\"]\n # Default optimizer configurations borrowed from:\n # https://github.com/rwightman/pytorch-image-models/blob/779107b693010934ac87c8cecbeb65796e218488/timm/optim/optim_factory.py#L78\n opt_args = OptimizerOption(lr=1e-4, opt=\"sgd\", weight_decay = 0.0001, momentum = 0.9)\n self.optimizer = create_optimizer(opt_args, self.model)\n",
"import torch\nfrom . import isoneutral_pytorch\nfrom torchbenchmark.tasks import OTHER\nfrom ...util.model import BenchmarkModel\nfrom typing import Tuple\n\ndef _generate_inputs(size):\n import math\n import numpy as np\n\n np.random.seed(17)\n\n shape = (\n math.ceil(2 * size ** (1 / 3)),\n math.ceil(2 * size ** (1 / 3)),\n math.ceil(0.25 * size ** (1 / 3)),\n )\n\n # masks\n maskT, maskU, maskV, maskW = (\n (np.random.rand(*shape) < 0.8).astype(\"float64\") for _ in range(4)\n )\n\n # 1d arrays\n dxt, dxu = (np.random.randn(shape[0]) for _ in range(2))\n dyt, dyu = (np.random.randn(shape[1]) for _ in range(2))\n dzt, dzw, zt = (np.random.randn(shape[2]) for _ in range(3))\n cost, cosu = (np.random.randn(shape[1]) for _ in range(2))\n\n # 3d arrays\n K_iso, K_iso_steep, K_11, K_22, K_33 = (np.random.randn(*shape) for _ in range(5))\n\n # 4d arrays\n salt, temp = (np.random.randn(*shape, 3) for _ in range(2))\n\n # 5d arrays\n Ai_ez, Ai_nz, Ai_bx, Ai_by = (np.zeros((*shape, 2, 2)) for _ in range(4))\n\n return (\n maskT,\n maskU,\n maskV,\n maskW,\n dxt,\n dxu,\n dyt,\n dyu,\n dzt,\n dzw,\n cost,\n cosu,\n salt,\n temp,\n zt,\n K_iso,\n K_11,\n K_22,\n K_33,\n Ai_ez,\n Ai_nz,\n Ai_bx,\n Ai_by,\n )\n\n\nclass IsoneutralMixing(torch.nn.Module):\n def __init__(self):\n super(IsoneutralMixing, self).__init__()\n\n def forward(\n self,\n maskT,\n maskU,\n maskV,\n maskW,\n dxt,\n dxu,\n dyt,\n dyu,\n dzt,\n dzw,\n cost,\n cosu,\n salt,\n temp,\n zt,\n K_iso,\n K_11,\n K_22,\n K_33,\n Ai_ez,\n Ai_nz,\n Ai_bx,\n Ai_by,\n ):\n return isoneutral_pytorch.isoneutral_diffusion_pre(\n maskT,\n maskU,\n maskV,\n maskW,\n dxt,\n dxu,\n dyt,\n dyu,\n dzt,\n dzw,\n cost,\n cosu,\n salt,\n temp,\n zt,\n K_iso,\n K_11,\n K_22,\n K_33,\n Ai_ez,\n Ai_nz,\n Ai_bx,\n Ai_by,\n )\n\nclass Model(BenchmarkModel):\n task = OTHER.OTHER_TASKS\n\n # Original input size: [2 ** i for i in range(12, 23, 2)]\n # Source: https://github.com/dionhaefner/pyhpc-benchmarks/blob/650ecc650e394df829944ffcf09e9d646ec69691/run.py#L25\n # Pick data-point when i = 20, size = 1048576\n DEFAULT_EVAL_BSIZE = 1048576\n\n def __init__(self, test, device, jit=False, batch_size=None, extra_args=[]):\n super().__init__(test=test, device=device, jit=jit, batch_size=batch_size, extra_args=extra_args)\n\n self.model = IsoneutralMixing().to(device=device)\n input_size = self.batch_size\n raw_inputs = _generate_inputs(input_size)\n if hasattr(isoneutral_pytorch, \"prepare_inputs\"):\n inputs = isoneutral_pytorch.prepare_inputs(*raw_inputs, device=device)\n self.example_inputs = inputs\n\n def get_module(self):\n return self.model, self.example_inputs\n\n def train(self, niter=1):\n raise NotImplementedError(\"Training not supported\")\n\n def eval(self, niter=1) -> Tuple[torch.Tensor]:\n model, example_inputs = self.get_module()\n with torch.no_grad():\n for i in range(niter):\n out = model(*example_inputs)\n return out\n"
] | [
[
"torch.jit.trace",
"torch.nn.ConvTranspose2d",
"torch.full",
"torch.nn.init.constant_",
"torch.randn",
"torch.nn.Conv2d",
"torch.nn.BCELoss",
"torch.nn.Tanh",
"torch.nn.Sigmoid",
"torch.nn.init.normal_",
"torch.nn.LeakyReLU",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
],
[
"torch.nn.CrossEntropyLoss"
],
[
"numpy.random.seed",
"torch.no_grad",
"numpy.random.rand",
"numpy.random.randn",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ZaneZh/IsaacGymEnvs | [
"adc20a5fbd70d77a716fefe86eb947f83d3efbd2",
"adc20a5fbd70d77a716fefe86eb947f83d3efbd2",
"adc20a5fbd70d77a716fefe86eb947f83d3efbd2",
"adc20a5fbd70d77a716fefe86eb947f83d3efbd2"
] | [
"isaacgymenvs/rl_games/algos_torch/models.py",
"isaacgymenvs/rl_games/algos_torch/moving_mean_std.py",
"isaacgymenvs/learning/amp_players.py",
"isaacgymenvs/rl_games/algos_torch/sac_helper.py"
] | [
"import rl_games.algos_torch.layers\nimport numpy as np\nimport torch.nn as nn\nimport torch\nimport torch.nn.functional as F\nimport rl_games.common.divergence as divergence\nfrom rl_games.algos_torch.torch_ext import CategoricalMasked\nfrom torch.distributions import Categorical\nfrom rl_games.algos_torch.sac_helper import SquashedNormal\nfrom rl_games.algos_torch.running_mean_std import RunningMeanStd, RunningMeanStdObs\n\n\nclass BaseModel():\n def __init__(self, model_class):\n self.model_class = model_class\n\n def is_rnn(self):\n return False\n\n def is_separate_critic(self):\n return False\n\n def build(self, config):\n obs_shape = config['input_shape']\n normalize_value = config.get('normalize_value', False)\n normalize_input = config.get('normalize_input', False)\n value_size = config.get('value_size', 1)\n return self.Network(self.network_builder.build(self.model_class, **config), obs_shape=obs_shape,\n normalize_value=normalize_value, normalize_input=normalize_input, value_size=value_size)\n\nclass BaseModelNetwork(nn.Module):\n def __init__(self, obs_shape, normalize_value, normalize_input, value_size):\n nn.Module.__init__(self)\n self.obs_shape = obs_shape\n self.normalize_value = normalize_value\n self.normalize_input = normalize_input\n self.value_size = value_size\n\n if normalize_value:\n self.value_mean_std = RunningMeanStd((self.value_size,))\n if normalize_input:\n if isinstance(obs_shape, dict):\n self.running_mean_std = RunningMeanStdObs(obs_shape)\n else:\n self.running_mean_std = RunningMeanStd(obs_shape)\n\n def norm_obs(self, observation):\n return self.running_mean_std(observation) if self.normalize_input else observation\n\n def unnorm_value(self, value):\n return self.value_mean_std(value, unnorm=True) if self.normalize_value else value\n\nclass ModelA2C(BaseModel):\n def __init__(self, network):\n BaseModel.__init__(self, 'a2c')\n self.network_builder = network\n\n class Network(BaseModelNetwork):\n def __init__(self, a2c_network, **kwargs):\n BaseModelNetwork.__init__(self,**kwargs)\n self.a2c_network = a2c_network\n\n def is_rnn(self):\n return self.a2c_network.is_rnn()\n \n def get_default_rnn_state(self):\n return self.a2c_network.get_default_rnn_state() \n\n def kl(self, p_dict, q_dict):\n p = p_dict['logits']\n q = q_dict['logits']\n return divergence.d_kl_discrete(p, q)\n\n def forward(self, input_dict):\n is_train = input_dict.get('is_train', True)\n action_masks = input_dict.get('action_masks', None)\n prev_actions = input_dict.get('prev_actions', None)\n input_dict['obs'] = self.norm_obs(input_dict['obs'])\n logits, value, states = self.a2c_network(input_dict)\n\n if is_train:\n categorical = CategoricalMasked(logits=logits, masks=action_masks)\n prev_neglogp = -categorical.log_prob(prev_actions)\n entropy = categorical.entropy()\n result = {\n 'prev_neglogp' : torch.squeeze(prev_neglogp),\n 'logits' : categorical.logits,\n 'values' : value,\n 'entropy' : entropy,\n 'rnn_states' : states\n }\n return result\n else:\n categorical = CategoricalMasked(logits=logits, masks=action_masks)\n selected_action = categorical.sample().long()\n neglogp = -categorical.log_prob(selected_action)\n result = {\n 'neglogpacs' : torch.squeeze(neglogp),\n 'values' : self.unnorm_value(value),\n 'actions' : selected_action,\n 'logits' : categorical.logits,\n 'rnn_states' : states\n }\n return result\n\nclass ModelA2CMultiDiscrete(BaseModel):\n def __init__(self, network):\n BaseModel.__init__(self, 'a2c')\n self.network_builder = network\n\n class Network(BaseModelNetwork):\n def __init__(self, a2c_network, **kwargs):\n BaseModelNetwork.__init__(self, **kwargs)\n self.a2c_network = a2c_network\n\n def is_rnn(self):\n return self.a2c_network.is_rnn()\n \n def get_default_rnn_state(self):\n return self.a2c_network.get_default_rnn_state()\n\n def kl(self, p_dict, q_dict):\n p = p_dict['logits']\n q = q_dict['logits']\n return divergence.d_kl_discrete_list(p, q)\n\n def forward(self, input_dict):\n is_train = input_dict.get('is_train', True)\n action_masks = input_dict.get('action_masks', None)\n prev_actions = input_dict.get('prev_actions', None)\n input_dict['obs'] = self.norm_obs(input_dict['obs'])\n logits, value, states = self.a2c_network(input_dict)\n if is_train:\n if action_masks is None:\n categorical = [Categorical(logits=logit) for logit in logits]\n else: \n categorical = [CategoricalMasked(logits=logit, masks=mask) for logit, mask in zip(logits, action_masks)]\n prev_actions = torch.split(prev_actions, 1, dim=-1)\n prev_neglogp = [-c.log_prob(a.squeeze()) for c,a in zip(categorical, prev_actions)]\n prev_neglogp = torch.stack(prev_neglogp, dim=-1).sum(dim=-1)\n entropy = [c.entropy() for c in categorical]\n entropy = torch.stack(entropy, dim=-1).sum(dim=-1)\n result = {\n 'prev_neglogp' : torch.squeeze(prev_neglogp),\n 'logits' : [c.logits for c in categorical],\n 'values' : value,\n 'entropy' : torch.squeeze(entropy),\n 'rnn_states' : states\n }\n return result\n else:\n if action_masks is None:\n categorical = [Categorical(logits=logit) for logit in logits]\n else: \n categorical = [CategoricalMasked(logits=logit, masks=mask) for logit, mask in zip(logits, action_masks)] \n \n selected_action = [c.sample().long() for c in categorical]\n neglogp = [-c.log_prob(a.squeeze()) for c,a in zip(categorical, selected_action)]\n selected_action = torch.stack(selected_action, dim=-1)\n neglogp = torch.stack(neglogp, dim=-1).sum(dim=-1)\n result = {\n 'neglogpacs' : torch.squeeze(neglogp),\n 'values' : self.unnorm_value(value),\n 'actions' : selected_action,\n 'logits' : [c.logits for c in categorical],\n 'rnn_states' : states\n }\n return result\n\nclass ModelA2CContinuous(BaseModel):\n def __init__(self, network):\n BaseModel.__init__(self, 'a2c')\n self.network_builder = network\n\n class Network(BaseModelNetwork):\n def __init__(self, a2c_network, **kwargs):\n BaseModelNetwork.__init__(self, **kwargs)\n self.a2c_network = a2c_network\n\n def is_rnn(self):\n return self.a2c_network.is_rnn()\n \n def get_default_rnn_state(self):\n return self.a2c_network.get_default_rnn_state()\n\n def kl(self, p_dict, q_dict):\n p = p_dict['mu'], p_dict['sigma']\n q = q_dict['mu'], q_dict['sigma']\n return divergence.d_kl_normal(p, q)\n\n def forward(self, input_dict):\n is_train = input_dict.get('is_train', True)\n prev_actions = input_dict.get('prev_actions', None)\n input_dict['obs'] = self.norm_obs(input_dict['obs'])\n mu, sigma, value, states = self.a2c_network(input_dict)\n distr = torch.distributions.Normal(mu, sigma)\n\n if is_train:\n entropy = distr.entropy().sum(dim=-1)\n prev_neglogp = -distr.log_prob(prev_actions).sum(dim=-1)\n result = {\n 'prev_neglogp' : torch.squeeze(prev_neglogp),\n 'value' : value,\n 'entropy' : entropy,\n 'rnn_states' : states,\n 'mus' : mu,\n 'sigmas' : sigma\n }\n return result\n else:\n selected_action = distr.sample().squeeze()\n neglogp = -distr.log_prob(selected_action).sum(dim=-1)\n result = {\n 'neglogpacs' : torch.squeeze(neglogp),\n 'values' : self.unnorm_value(value),\n 'actions' : selected_action,\n 'entropy' : entropy,\n 'rnn_states' : states,\n 'mus' : mu,\n 'sigmas' : sigma\n }\n return result \n\n\nclass ModelA2CContinuousLogStd(BaseModel):\n def __init__(self, network):\n BaseModel.__init__(self, 'a2c')\n self.network_builder = network\n\n class Network(BaseModelNetwork):\n def __init__(self, a2c_network, **kwargs):\n BaseModelNetwork.__init__(self, **kwargs)\n self.a2c_network = a2c_network\n\n def is_rnn(self):\n return self.a2c_network.is_rnn()\n \n def get_default_rnn_state(self):\n return self.a2c_network.get_default_rnn_state()\n\n def forward(self, input_dict):\n is_train = input_dict.get('is_train', True)\n prev_actions = input_dict.get('prev_actions', None)\n input_dict['obs'] = self.norm_obs(input_dict['obs'])\n mu, logstd, value, states = self.a2c_network(input_dict)\n sigma = torch.exp(logstd)\n distr = torch.distributions.Normal(mu, sigma)\n if is_train:\n entropy = distr.entropy().sum(dim=-1)\n prev_neglogp = self.neglogp(prev_actions, mu, sigma, logstd)\n result = {\n 'prev_neglogp' : torch.squeeze(prev_neglogp),\n 'values' : value,\n 'entropy' : entropy,\n 'rnn_states' : states,\n 'mus' : mu,\n 'sigmas' : sigma\n } \n return result\n else:\n selected_action = distr.sample()\n neglogp = self.neglogp(selected_action, mu, sigma, logstd)\n result = {\n 'neglogpacs' : torch.squeeze(neglogp),\n 'values' : self.unnorm_value(value),\n 'actions' : selected_action,\n 'rnn_states' : states,\n 'mus' : mu,\n 'sigmas' : sigma\n }\n return result\n\n def neglogp(self, x, mean, std, logstd):\n return 0.5 * (((x - mean) / std)**2).sum(dim=-1) \\\n + 0.5 * np.log(2.0 * np.pi) * x.size()[-1] \\\n + logstd.sum(dim=-1)\n\n\nclass ModelCentralValue(BaseModel):\n def __init__(self, network):\n BaseModel.__init__(self, 'a2c')\n self.network_builder = network\n\n class Network(BaseModelNetwork):\n def __init__(self, a2c_network, **kwargs):\n BaseModelNetwork.__init__(self, **kwargs)\n self.a2c_network = a2c_network\n\n def is_rnn(self):\n return self.a2c_network.is_rnn()\n\n def get_default_rnn_state(self):\n return self.a2c_network.get_default_rnn_state()\n\n def kl(self, p_dict, q_dict):\n return None # or throw exception?\n\n def forward(self, input_dict):\n is_train = input_dict.get('is_train', True)\n prev_actions = input_dict.get('prev_actions', None)\n input_dict['obs'] = self.norm_obs(input_dict['obs'])\n value, states = self.a2c_network(input_dict)\n if not is_train:\n value = self.unnorm_value(value)\n\n result = {\n 'values': value,\n 'rnn_states': states\n }\n return result\n\n\n\nclass ModelSACContinuous(BaseModel):\n\n def __init__(self, network):\n BaseModel.__init__(self, 'sac')\n self.network_builder = network\n \n class Network(BaseModelNetwork):\n def __init__(self, sac_network,**kwargs):\n BaseModelNetwork.__init__(self,**kwargs)\n self.sac_network = sac_network\n\n def critic(self, obs, action):\n return self.sac_network.critic(obs, action)\n\n def critic_target(self, obs, action):\n return self.sac_network.critic_target(obs, action)\n\n def actor(self, obs):\n return self.sac_network.actor(obs)\n \n def is_rnn(self):\n return False\n\n def forward(self, input_dict):\n is_train = input_dict.pop('is_train', True)\n mu, sigma = self.sac_network(input_dict)\n dist = SquashedNormal(mu, sigma)\n return dist\n\n\n\n",
"import torch\nimport torch.nn as nn\nimport numpy as np\nimport rl_games.algos_torch.torch_ext as torch_ext\n\n'''\nupdates moving statistics with momentum\n'''\nclass MovingMeanStd(nn.Module):\n def __init__(self, insize, momentum = 0.25, epsilon=1e-05, per_channel=False, norm_only=False):\n super(MovingMeanStd, self).__init__()\n self.insize = insize\n self.epsilon = epsilon\n self.momentum = momentum\n self.norm_only = norm_only\n self.per_channel = per_channel\n if per_channel:\n if len(self.insize) == 3:\n self.axis = [0,2,3]\n if len(self.insize) == 2:\n self.axis = [0,2]\n if len(self.insize) == 1:\n self.axis = [0]\n in_size = self.insize[0] \n else:\n self.axis = [0]\n in_size = insize\n\n self.register_buffer(\"moving_mean\", torch.zeros(in_size, dtype = torch.float64))\n self.register_buffer(\"moving_var\", torch.ones(in_size, dtype = torch.float64))\n\n def forward(self, input, mask=None, unnorm=False):\n if self.training:\n if mask is not None:\n mean, var = torch_ext.get_mean_std_with_masks(input, mask)\n else:\n mean = input.mean(self.axis) # along channel axis\n var = input.var(self.axis)\n \n self.moving_mean = self.moving_mean * self.momentum + mean * (1 - self.momentum)\n self.moving_var = self.moving_var * self.momentum + var * (1 - self.momentum)\n\n # change shape\n if self.per_channel:\n if len(self.insize) == 3:\n current_mean = self.moving_mean.view([1, self.insize[0], 1, 1]).expand_as(input)\n current_var = self.moving_var.view([1, self.insize[0], 1, 1]).expand_as(input)\n if len(self.insize) == 2:\n current_mean = self.moving_mean.view([1, self.insize[0], 1]).expand_as(input)\n current_var = self.moving_var.view([1, self.insize[0], 1]).expand_as(input)\n if len(self.insize) == 1:\n current_mean = self.moving_mean.view([1, self.insize[0]]).expand_as(input)\n current_var = self.moving_var.view([1, self.insize[0]]).expand_as(input) \n else:\n current_mean = self.moving_mean\n current_var = self.moving_var\n # get output\n if unnorm:\n y = torch.clamp(input, min=-5.0, max=5.0)\n y = torch.sqrt(current_var.float() + self.epsilon)*y + current_mean.float()\n else:\n y = (input - current_mean.float()) / torch.sqrt(current_var.float() + self.epsilon)\n y = torch.clamp(y, min=-5.0, max=5.0)\n return y",
"# Copyright (c) 2018-2022, NVIDIA Corporation\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, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor 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, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# 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 torch \n\nfrom rl_games.algos_torch import torch_ext\nfrom rl_games.algos_torch.running_mean_std import RunningMeanStd\nfrom rl_games.common.player import BasePlayer\n\nimport learning.common_player as common_player\n\n\nclass AMPPlayerContinuous(common_player.CommonPlayer):\n def __init__(self, config):\n self._normalize_amp_input = config.get('normalize_amp_input', True)\n self._disc_reward_scale = config['disc_reward_scale']\n self._print_disc_prediction = config.get('print_disc_prediction', False)\n \n super().__init__(config)\n return\n\n def restore(self, fn):\n super().restore(fn)\n if self._normalize_amp_input:\n checkpoint = torch_ext.load_checkpoint(fn)\n self._amp_input_mean_std.load_state_dict(checkpoint['amp_input_mean_std'])\n return\n \n def _build_net(self, config):\n super()._build_net(config)\n \n if self._normalize_amp_input:\n self._amp_input_mean_std = RunningMeanStd(config['amp_input_shape']).to(self.device)\n self._amp_input_mean_std.eval() \n \n return\n\n def _post_step(self, info):\n super()._post_step(info)\n if (self.env.viewer and self._print_disc_prediction):\n self._amp_debug(info)\n return\n\n def _build_net_config(self):\n config = super()._build_net_config()\n if (hasattr(self, 'env')):\n config['amp_input_shape'] = self.env.amp_observation_space.shape\n else:\n config['amp_input_shape'] = self.env_info['amp_observation_space']\n return config\n\n def _amp_debug(self, info):\n with torch.no_grad():\n amp_obs = info['amp_obs']\n amp_obs = amp_obs[0:1]\n disc_pred = self._eval_disc(amp_obs.to(self.device))\n amp_rewards = self._calc_amp_rewards(amp_obs.to(self.device))\n disc_reward = amp_rewards['disc_rewards']\n\n disc_pred = disc_pred.detach().cpu().numpy()[0, 0]\n disc_reward = disc_reward.cpu().numpy()[0, 0]\n print(\"disc_pred: \", disc_pred, disc_reward)\n\n return\n\n def _preproc_amp_obs(self, amp_obs):\n if self._normalize_amp_input:\n amp_obs = self._amp_input_mean_std(amp_obs)\n return amp_obs\n\n def _eval_disc(self, amp_obs):\n proc_amp_obs = self._preproc_amp_obs(amp_obs)\n return self.model.a2c_network.eval_disc(proc_amp_obs)\n\n def _calc_amp_rewards(self, amp_obs):\n disc_r = self._calc_disc_rewards(amp_obs)\n output = {\n 'disc_rewards': disc_r\n }\n return output\n\n def _calc_disc_rewards(self, amp_obs):\n with torch.no_grad():\n disc_logits = self._eval_disc(amp_obs)\n prob = 1.0 / (1.0 + torch.exp(-disc_logits)) \n disc_r = -torch.log(torch.maximum(1 - prob, torch.tensor(0.0001, device=self.device)))\n disc_r *= self._disc_reward_scale\n return disc_r\n",
"# from rl_games.algos_torch.network_builder import NetworkBuilder\nfrom torch import distributions as pyd\nimport torch\nimport torch.nn as nn\nimport math\nimport torch.nn.functional as F\nimport numpy as np\n\nclass TanhTransform(pyd.transforms.Transform):\n domain = pyd.constraints.real\n codomain = pyd.constraints.interval(-1.0, 1.0)\n bijective = True\n sign = +1\n\n def __init__(self, cache_size=1):\n super().__init__(cache_size=cache_size)\n\n @staticmethod\n def atanh(x):\n return 0.5 * (x.log1p() - (-x).log1p())\n\n def __eq__(self, other):\n return isinstance(other, TanhTransform)\n\n def _call(self, x):\n return x.tanh()\n\n def _inverse(self, y):\n # We do not clamp to the boundary here as it may degrade the performance of certain algorithms.\n # one should use `cache_size=1` instead\n return self.atanh(y)\n\n def log_abs_det_jacobian(self, x, y):\n # We use a formula that is more numerically stable, see details in the following link\n # https://github.com/tensorflow/probability/commit/ef6bb176e0ebd1cf6e25c6b5cecdd2428c22963f#diff-e120f70e92e6741bca649f04fcd907b7\n return 2. * (math.log(2.) - x - F.softplus(-2. * x))\n\nclass SquashedNormal(pyd.transformed_distribution.TransformedDistribution):\n def __init__(self, loc, scale):\n self.loc = loc\n self.scale = scale\n\n self.base_dist = pyd.Normal(loc, scale)\n transforms = [TanhTransform()]\n super().__init__(self.base_dist, transforms)\n\n @property\n def mean(self):\n mu = self.loc\n for tr in self.transforms:\n mu = tr(mu)\n return mu\n\n def entropy(self):\n return self.base_dist.entropy()\n\n\n\n"
] | [
[
"numpy.log",
"torch.nn.Module.__init__",
"torch.squeeze",
"torch.exp",
"torch.distributions.Categorical",
"torch.split",
"torch.stack",
"torch.distributions.Normal"
],
[
"torch.clamp",
"torch.ones",
"torch.zeros"
],
[
"torch.exp",
"torch.no_grad",
"torch.tensor"
],
[
"torch.nn.functional.softplus",
"torch.distributions.constraints.interval",
"torch.distributions.Normal"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
danielefdf/nene | [
"889f2fe88f5fea738a3a6ffa89a33c8d5dec8f97"
] | [
"src/datasetxy.py"
] | [
"# -*- coding: utf-8 -*-\r\n\r\nfrom enum import Enum\r\n\r\nimport numpy as np\r\n\r\n\r\nclass DatasetXY:\r\n\r\n class XType(Enum):\r\n ALL = 1 # all points of the plane\r\n RANDOM = 2 # random (gaussian distribution) selected points\r\n\r\n def __init__(self, t, x_lims, groups, traing_data_ratio, f):\r\n\r\n self.x_lims = x_lims\r\n self.groups = groups\r\n\r\n self.traing_data_ratio = traing_data_ratio\r\n\r\n ''' setting x '''\r\n\r\n self.x_range = range(self.x_lims[0], self.x_lims[1])\r\n self.x_range_len = self.x_lims[1] - self.x_lims[0]\r\n self.x_range_area = self.x_range_len ** 2\r\n\r\n if t == DatasetXY.XType.ALL:\r\n x = np.array([[[r, c] for c in self.x_range] \\\r\n for r in self.x_range])\r\n x = x.reshape((self.x_range_area, 2))\r\n\r\n elif t == DatasetXY.XType.RANDOM:\r\n x = np.random.randint(self.x_lims[0], self.x_lims[1], \\\r\n (self.x_range_area, 2))\r\n\r\n self.x_list = x.tolist()\r\n\r\n ''' setting y '''\r\n\r\n self.y_list = [f(e) for e in self.x_list]\r\n\r\n ''' splitting training and evaluation data '''\r\n\r\n self.traing_x_list = []\r\n self.traing_y_list = []\r\n self.evaltn_x_list = []\r\n self.evaltn_y_list = []\r\n for e in zip(self.x_list, self.y_list):\r\n e_x = e[0]\r\n e_y = e[1]\r\n if np.random.randint(1, self.traing_data_ratio + 1) == 1:\r\n self.evaltn_x_list.append(e_x)\r\n self.evaltn_y_list.append(e_y)\r\n else:\r\n self.traing_x_list.append(e_x)\r\n self.traing_y_list.append(e_y)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
] | [
[
"numpy.array",
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mintzer/pupillometry-rf-back | [
"cfa86fa984a49dce0123798f8de5b838c02e10d5",
"cfa86fa984a49dce0123798f8de5b838c02e10d5",
"cfa86fa984a49dce0123798f8de5b838c02e10d5",
"3dc84b260e5bced65ebc2c45c40c8fa65f9b5aa9",
"cfa86fa984a49dce0123798f8de5b838c02e10d5",
"cfa86fa984a49dce0123798f8de5b838c02e10d5",
"cfa86fa984a49dce0123798f8de5b838c02e10d5"
] | [
"venv/Lib/site-packages/psychopy/demos/coder/stimuli/clockface.py",
"venv/Lib/site-packages/psychopy/sound/audioclip.py",
"venv/Lib/site-packages/psychopy/visual/noise.py",
"venv/Lib/site-packages/moviepy/video/compositing/CompositeVideoClip.py",
"venv/Lib/site-packages/psychopy/tests/test_all_visual/test_color.py",
"venv/Lib/site-packages/psychopy/demos/coder/timing/timeByFrames.py",
"venv/Lib/site-packages/psychopy/data/base.py"
] | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nDemo of using ShapeStim to make a functioning visual clock.\n\"\"\"\n\nfrom __future__ import division\n\nfrom psychopy import visual, core, event\nimport numpy, time\nwin = visual.Window([800, 800], monitor='testMonitor')\n\n# vertices (using numpy means we can scale them easily)\nhandVerts = numpy.array([ [0, 0.8], [-0.05, 0], [0, -0.05], [0.05, 0] ])\n\nsecond = visual.ShapeStim(win, vertices=[[0, -0.1], [0.1, 0.8]],\n lineColor=[1, -1, -1], fillColor=None, lineWidth=2, autoLog=False)\nminute = visual.ShapeStim(win, vertices=handVerts,\n lineColor='white', fillColor=[0.8, 0.8, 0.8], autoLog=False)\nhour = visual.ShapeStim(win, vertices=handVerts/2.0,\n lineColor='black', fillColor=[-0.8, -0.8, -0.8], autoLog=False)\nclock = core.Clock()\n\nwhile not event.getKeys():\n t = time.localtime()\n\n minPos = numpy.floor(t[4]) * 360 / 60 # NB floor will round down\n minute.ori = minPos\n minute.draw()\n\n hourPos = (t[3]) * 360 / 12 # this one can be smooth\n hour.ori = hourPos\n hour.draw()\n\n secPos = numpy.floor(t[5]) * 360 / 60 # NB floor will round down\n second.ori = secPos\n second.draw()\n\n win.flip()\n event.clearEvents('mouse') # only really needed for pygame windows\n\nwin.close()\ncore.quit()\n\n# The contents of this file are in the public domain.\n",
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Classes and functions for working with audio data.\n\"\"\"\n\n# Part of the PsychoPy library\n# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2021 Open Science Tools Ltd.\n# Distributed under the terms of the GNU General Public License (GPL).\n\n__all__ = [\n 'AudioClip',\n 'load',\n 'save',\n 'AUDIO_SUPPORTED_CODECS',\n 'AUDIO_CHANNELS_MONO',\n 'AUDIO_CHANNELS_STEREO',\n 'AUDIO_CHANNEL_LEFT',\n 'AUDIO_EAR_LEFT',\n 'AUDIO_CHANNEL_RIGHT',\n 'AUDIO_EAR_RIGHT',\n 'AUDIO_CHANNEL_COUNT',\n 'AUDIO_EAR_COUNT'\n]\n\nimport numpy as np\nimport soundfile as sf\nfrom psychopy.tools.audiotools import *\nfrom .exceptions import *\n\n# supported formats for loading and saving audio samples to file\nAUDIO_SUPPORTED_CODECS = [s.lower() for s in sf.available_formats().keys()]\n\n# constants for specifying the number of channels\nAUDIO_CHANNELS_MONO = 1\nAUDIO_CHANNELS_STEREO = 2\n\n# constants for indexing channels\nAUDIO_CHANNEL_LEFT = AUDIO_EAR_LEFT = 0\nAUDIO_CHANNEL_RIGHT = AUDIO_EAR_RIGHT = 1\nAUDIO_CHANNEL_COUNT = AUDIO_EAR_COUNT = 2\n\n\nclass AudioClip(object):\n \"\"\"Class for storing audio clip data.\n\n This class is used to store and handle raw audio data, such as those\n obtained from microphone recordings or loaded from files. PsychoPy stores\n audio samples in contiguous arrays of 32-bit floating-point values ranging\n between -1 and 1.\n\n The `AudioClip` class provides basic audio editing capabilities too. You can\n use operators on `AudioClip` instances to combine audio clips together. For\n instance, the ``+`` operator will return a new `AudioClip` instance whose\n samples are the concatenation of the two operands::\n\n sndCombined = sndClip1 + sndClip2\n\n Note that audio clips must have the same sample rates in order to be joined\n using the addition operator. For online compatibility, use the `append()`\n method instead.\n\n There are also numerous static methods available to generate various tones\n (e.g., sine-, saw-, and square-waves). Audio samples can also be loaded and\n saved to files in various formats (e.g., WAV, FLAC, OGG, etc.)\n\n You can play `AudioClip` by directly passing instances of this object to\n the :class:`~psychopy.sound.Sound` class::\n\n inport psychopy.core as core\n import psyhcopy.sound as sound\n\n myTone = AudioClip.sine(duration=5.0) # generate a tone\n\n mySound = sound.Sound(myTone)\n mySound.play()\n core.wait(5.0) # wait for sound to finish playing\n core.quit()\n\n Parameters\n ----------\n samples : ArrayLike\n Nx1 or Nx2 array of audio samples for mono and stereo, respectively.\n Values in the array representing the amplitude of the sound waveform\n should vary between -1 and 1. If not, they will be clipped.\n sampleRateHz : int\n Sampling rate used to obtain `samples` in Hertz (Hz). The sample rate or\n frequency is related to the quality of the audio, where higher sample\n rates usually result in better sounding audio (albeit a larger memory\n footprint and file size). The value specified should match the frequency\n the clip was recorded at. If not, the audio may sound distorted when\n played back. Usually, a sample rate of 48kHz is acceptable for most\n applications (DVD audio quality). For convenience, module level\n constants with form ``SAMPLE_RATE_*`` are provided to specify many\n common samples rates.\n userData : dict or None\n Optional user data to associated with the audio clip.\n\n \"\"\"\n def __init__(self, samples, sampleRateHz=SAMPLE_RATE_48kHz, userData=None):\n # samples should be a 2D array where columns represent channels\n self._samples = np.atleast_2d(\n np.asarray(samples, dtype=np.float32, order='C'))\n self._samples.clip(-1, 1) # force values to be clipped\n\n # set the sample rate of the clip\n self._sampleRateHz = int(sampleRateHz)\n\n # the duration of the audio clip\n self._duration = len(self.samples) / float(self.sampleRateHz)\n\n # user data\n self._userData = userData if userData is not None else {}\n assert isinstance(self._userData, dict)\n\n # --------------------------------------------------------------------------\n # Loading and saving\n #\n # These static methods are related to loading and saving audio clips from\n # files. The file types supported are those that `libsoundfile` supports.\n #\n # Additional codecs such as `mp3` require the pydub package which is\n # optional.\n #\n\n @staticmethod\n def _checkCodecSupported(codec, raiseError=False):\n \"\"\"Check if the audio format string corresponds to a supported codec.\n Used internally to check if the user specified a valid codec identifier.\n\n Parameters\n ----------\n codec: str\n Codec identifier (e.g., 'wav', 'mp3', etc.)\n raiseError : bool\n Raise an error (``) instead of returning a value. Default is\n `False`.\n\n Returns\n -------\n bool\n `True` if the format is supported.\n\n \"\"\"\n if not isinstance(codec, str):\n raise ValueError('Codec identifier must be a string.')\n\n hasCodec = codec.lower() in AUDIO_SUPPORTED_CODECS\n\n if raiseError and not hasCodec:\n fmtList = [\"'{}'\".format(s) for s in AUDIO_SUPPORTED_CODECS]\n raise AudioUnsupportedCodecError(\n \"Unsupported audio codec specified, must be either: \" +\n \", \".join(fmtList))\n\n return hasCodec\n\n @staticmethod\n def load(filename, codec=None):\n \"\"\"Load audio samples from a file. Note that this is a static method!\n\n Parameters\n ----------\n filename : str\n File name to load.\n codec : str or None\n Codec to use. If `None`, the format will be implied from the file\n name.\n\n Returns\n -------\n AudioClip\n Audio clip containing samples loaded from the file.\n\n \"\"\"\n if codec is not None:\n AudioClip._checkCodecSupported(codec, raiseError=True)\n\n samples, sampleRateHz = sf.read(\n filename,\n dtype='float32',\n always_2d=True,\n format=codec)\n\n return AudioClip(\n samples=samples,\n sampleRateHz=sampleRateHz)\n\n def save(self, filename, codec=None):\n \"\"\"Save an audio clip to file.\n\n Parameters\n ----------\n filename : str\n File name to write audio clip to.\n codec : str or None\n Format to save audio clip data as. If `None`, the format will be\n implied from the extension at the end of `filename`.\n\n \"\"\"\n if codec is not None:\n AudioClip._checkCodecSupported(codec, raiseError=True)\n\n sf.write(\n filename,\n data=self._samples,\n samplerate=self._sampleRateHz,\n format=codec)\n\n # --------------------------------------------------------------------------\n # Tone and noise generation methods\n #\n # These static methods are used to generate audio samples, such as random\n # colored noise (e.g., white) and tones (e.g., sine, square, etc.)\n #\n # All of these methods return `AudioClip` objects containing the generated\n # samples.\n #\n\n @staticmethod\n def whiteNoise(duration=1.0, sampleRateHz=SAMPLE_RATE_48kHz, channels=2):\n \"\"\"Generate gaussian white noise.\n\n **New feature, use with caution.**\n\n Parameters\n ----------\n duration : float or int\n Length of the sound in seconds.\n sampleRateHz : int\n Samples rate of the audio for playback.\n channels : int\n Number of channels for the output.\n\n Returns\n -------\n AudioClip\n\n \"\"\"\n samples = whiteNoise(duration, sampleRateHz)\n\n if channels > 1:\n samples = np.tile(samples, (1, channels)).astype(np.float32)\n\n return AudioClip(samples, sampleRateHz=sampleRateHz)\n\n @staticmethod\n def silence(duration=1.0, sampleRateHz=SAMPLE_RATE_48kHz, channels=2):\n \"\"\"Generate audio samples for a silent period.\n\n This is used to create silent periods of a very specific duration\n between other audio clips.\n\n Parameters\n ----------\n duration : float or int\n Length of the sound in seconds.\n sampleRateHz : int\n Samples rate of the audio for playback.\n channels : int\n Number of channels for the output.\n\n Returns\n -------\n AudioClip\n\n Examples\n --------\n Generate 5 seconds of silence to enjoy::\n\n import psychopy.sound as sound\n silence = sound.AudioClip.silence(10.)\n\n Use the silence as a break between two audio clips when concatenating\n them::\n\n fullClip = clip1 + sound.AudioClip.silence(10.) + clip2\n\n \"\"\"\n samples = np.zeros(\n (int(duration * sampleRateHz), channels), dtype=np.float32)\n\n return AudioClip(samples, sampleRateHz=sampleRateHz)\n\n @staticmethod\n def sine(duration=1.0, freqHz=440, gain=0.8, sampleRateHz=SAMPLE_RATE_48kHz,\n channels=2):\n \"\"\"Generate audio samples for a tone with a sine waveform.\n\n Parameters\n ----------\n duration : float or int\n Length of the sound in seconds.\n freqHz : float or int\n Frequency of the tone in Hertz (Hz). Note that this differs from the\n `sampleRateHz`.\n gain : float\n Gain factor ranging between 0.0 and 1.0. Default is 0.8.\n sampleRateHz : int\n Samples rate of the audio for playback.\n channels : int\n Number of channels for the output.\n\n Returns\n -------\n AudioClip\n\n Examples\n --------\n Generate an audio clip of a tone 10 seconds long with a frequency of\n 400Hz::\n\n import psychopy.sound as sound\n tone400Hz = sound.AudioClip.sine(10., 400.)\n\n Create a marker/cue tone and append it to pre-recorded instructions::\n\n import psychopy.sound as sound\n voiceInstr = sound.AudioClip.load('/path/to/instructions.wav')\n markerTone = sound.AudioClip.sine(\n 1.0, 440., # duration and freq\n sampleRateHz=voiceInstr.sampleRateHz) # must be the same!\n\n fullInstr = voiceInstr + markerTone # create instructions with cue\n fullInstr.save('/path/to/instructions_with_tone.wav') # save it\n\n \"\"\"\n samples = sinetone(duration, freqHz, gain, sampleRateHz)\n\n if channels > 1:\n samples = np.tile(samples, (1, channels)).astype(np.float32)\n\n return AudioClip(samples, sampleRateHz=sampleRateHz)\n\n @staticmethod\n def square(duration=1.0, freqHz=440, dutyCycle=0.5, gain=0.8,\n sampleRateHz=SAMPLE_RATE_48kHz, channels=2):\n \"\"\"Generate audio samples for a tone with a square waveform.\n\n Parameters\n ----------\n duration : float or int\n Length of the sound in seconds.\n freqHz : float or int\n Frequency of the tone in Hertz (Hz). Note that this differs from the\n `sampleRateHz`.\n dutyCycle : float\n Duty cycle between 0.0 and 1.0.\n gain : float\n Gain factor ranging between 0.0 and 1.0. Default is 0.8.\n sampleRateHz : int\n Samples rate of the audio for playback.\n channels : int\n Number of channels for the output.\n\n Returns\n -------\n AudioClip\n\n \"\"\"\n samples = squaretone(duration, freqHz, dutyCycle, gain, sampleRateHz)\n\n if channels > 1:\n samples = np.tile(samples, (1, channels)).astype(np.float32)\n\n return AudioClip(samples, sampleRateHz=sampleRateHz)\n\n @staticmethod\n def sawtooth(duration=1.0, freqHz=440, peak=1.0, gain=0.8,\n sampleRateHz=SAMPLE_RATE_48kHz, channels=2):\n \"\"\"Generate audio samples for a tone with a sawtooth waveform.\n\n Parameters\n ----------\n duration : float or int\n Length of the sound in seconds.\n freqHz : float or int\n Frequency of the tone in Hertz (Hz). Note that this differs from the\n `sampleRateHz`.\n peak : float\n Location of the peak between 0.0 and 1.0. If the peak is at 0.5, the\n resulting wave will be triangular. A value of 1.0 will cause the\n peak to be located at the very end of a cycle.\n gain : float\n Gain factor ranging between 0.0 and 1.0. Default is 0.8.\n sampleRateHz : int\n Samples rate of the audio for playback.\n channels : int\n Number of channels for the output.\n\n Returns\n -------\n AudioClip\n\n \"\"\"\n samples = sawtone(duration, freqHz, peak, gain, sampleRateHz)\n\n if channels > 1:\n samples = np.tile(samples, (1, channels)).astype(np.float32)\n\n return AudioClip(samples, sampleRateHz=sampleRateHz)\n\n # --------------------------------------------------------------------------\n # Audio editing methods\n #\n # Methods related to basic editing of audio samples (operations such as\n # splicing clips and signal gain).\n #\n\n def __add__(self, other):\n \"\"\"Concatenate two audio clips.\"\"\"\n assert other.sampleRateHz == self._sampleRateHz\n assert other.channels == self.channels\n\n newSamples = np.ascontiguousarray(\n np.vstack((self._samples, other.samples)),\n dtype=np.float32)\n\n toReturn = AudioClip(\n samples=newSamples,\n sampleRateHz=self._sampleRateHz)\n\n return toReturn\n\n def __iadd__(self, other):\n \"\"\"Concatenate two audio clips inplace.\"\"\"\n assert other.sampleRateHz == self._sampleRateHz\n assert other.channels == self.channels\n\n self._samples = np.ascontiguousarray(\n np.vstack((self._samples, other.samples)),\n dtype=np.float32)\n\n return self\n\n def append(self, clip):\n \"\"\"Append samples from another sound clip to the end of this one.\n\n The `AudioClip` object must have the same sample rate and channels as\n this object.\n\n Parameters\n ----------\n clip : AudioClip\n Audio clip to append.\n\n Returns\n -------\n AudioClip\n This object with samples from `clip` appended.\n\n Examples\n --------\n Join two sound clips together::\n\n snd1.append(snd2)\n\n \"\"\"\n # if either clip is empty, just replace it\n if len(self.samples) == 0:\n return clip\n if len(clip.samples) == 0:\n return self\n\n assert self.channels == clip.channels\n assert self._sampleRateHz == clip.sampleRateHz\n\n self._samples = np.ascontiguousarray(\n np.vstack((self._samples, clip.samples)),\n dtype=np.float32)\n\n # recompute the duration of the new clip\n self._duration = len(self.samples) / float(self.sampleRateHz)\n\n return self\n\n def copy(self):\n \"\"\"Create an independent copy of this `AudioClip`.\n\n Returns\n -------\n AudioClip\n\n \"\"\"\n return AudioClip(\n samples=self._samples.copy(),\n sampleRateHz=self._sampleRateHz)\n\n def gain(self, factor, channel=None):\n \"\"\"Apply gain the audio samples.\n\n This will modify the internal store of samples inplace. Clipping is\n automatically applied to samples after applying gain.\n\n Parameters\n ----------\n factor : float or int\n Gain factor to multiply audio samples.\n channel : int or None\n Channel to apply gain to. If `None`, gain will be applied to all\n channels.\n\n \"\"\"\n try:\n arrview = self._samples[:, :] \\\n if channel is None else self._samples[:, channel]\n except IndexError:\n raise ValueError('Invalid value for `channel`.')\n\n # multiply and clip range\n arrview *= float(factor)\n arrview.clip(-1, 1)\n\n # --------------------------------------------------------------------------\n # Audio analysis methods\n #\n # Methods related to basic analysis of audio samples, nothing too advanced\n # but still useful.\n #\n\n def rms(self, channel=None):\n \"\"\"Compute the root mean square (RMS) of the samples to determine the\n average signal level.\n\n Parameters\n ----------\n channel : int or None\n Channel to compute RMS (zero-indexed). If `None`, the RMS of all\n channels will be computed.\n\n Returns\n -------\n ndarray or float\n An array of RMS values for each channel if ``channel=None`` (even if\n there is one channel an array is returned). If `channel` *was*\n specified, a `float` will be returned indicating the RMS of that\n single channel.\n\n \"\"\"\n if channel is not None:\n assert 0 < channel < self.channels\n\n arr = self._samples if channel is None else self._samples[:, channel]\n rms = np.sqrt(np.mean(np.square(arr), axis=0))\n\n return rms if len(rms) > 1 else rms[0]\n\n # --------------------------------------------------------------------------\n # Properties\n #\n\n @property\n def samples(self):\n \"\"\"Nx1 or Nx2 array of audio samples (`~numpy.ndarray`).\n\n Values must range from -1 to 1. Values outside that range will be\n clipped, possibly resulting in distortion.\n\n \"\"\"\n return self._samples\n\n @samples.setter\n def samples(self, value):\n self._samples = np.asarray(value, dtype=float) # convert to array\n self._samples.clip(-1., 1.) # do clipping to keep samples in range\n\n # recompute duration after updating samples\n self._duration = len(self._samples) / float(self._sampleRateHz)\n\n @property\n def sampleRateHz(self):\n \"\"\"Sample rate of the audio clip in Hz (`int`). Should be the same\n value as the rate `samples` was captured at.\n\n \"\"\"\n return self._sampleRateHz\n\n @sampleRateHz.setter\n def sampleRateHz(self, value):\n self._sampleRateHz = int(value)\n # recompute duration after updating sample rate\n self._duration = len(self._samples) / float(self._sampleRateHz)\n\n @property\n def duration(self):\n \"\"\"The duration of the audio in seconds (`float`).\n\n This value is computed using the specified sampling frequency and number\n of samples.\n\n \"\"\"\n return self._duration\n\n @property\n def channels(self):\n \"\"\"Number of audio channels in the clip (`int`).\n\n If `channels` > 1, the audio clip is in stereo.\n\n \"\"\"\n return self._samples.shape[1]\n\n @property\n def isStereo(self):\n \"\"\"`True` if there are two channels of audio samples.\n\n Usually one for each ear. The first channel is usually the left ear, and\n the second the right.\n\n \"\"\"\n return not self.isMono # are we moving in stereo? ;)\n\n @property\n def isMono(self):\n \"\"\"`True` if there is only one channel of audio data.\n\n \"\"\"\n return self._samples.shape[1] == 1\n\n @property\n def userData(self):\n \"\"\"User data associated with this clip (`dict`). Can be used for storing\n additional data related to the clip. Note that `userData` is not saved\n with audio files!\n\n Example\n -------\n Adding fields to `userData`. For instance, we want to associated the\n start time the clip was recorded at with it::\n\n myClip.userData['date_recorded'] = t_start\n\n We can access that field later by::\n\n thisRecordingStartTime = myClip.userData['date_recorded']\n\n \"\"\"\n return self._userData\n\n @userData.setter\n def userData(self, value):\n assert isinstance(value, dict)\n self._userData = value\n\n def convertToWAV(self):\n \"\"\"Get a copy of stored audio samples in WAV PCM format.\n\n Returns\n -------\n ndarray\n Array with the same shapes as `.samples` but in 16-bit WAV PCM\n format.\n\n \"\"\"\n return np.asarray(\n self._samples * ((1 << 15) - 1), dtype=np.int16).tobytes()\n\n def asMono(self, copy=True):\n \"\"\"Convert the audio clip to mono (single channel audio).\n\n Parameters\n ----------\n copy : bool\n If `True` an :class:`~psychopy.sound.AudioClip` containing a copy\n of the samples will be returned. If `False`, channels will be\n mixed inplace resulting a the same object being returned. User data\n is not copied.\n\n Returns\n -------\n :class:`~psychopy.sound.AudioClip`\n Mono version of this object.\n\n \"\"\"\n samples = np.atleast_2d(self._samples) # enforce 2D\n if samples.shape[1] > 1:\n samplesMixed = np.atleast_2d(\n np.sum(samples, axis=1, dtype=np.float32) / np.float32(2.)).T\n else:\n samplesMixed = samples.copy()\n\n if copy:\n return AudioClip(samplesMixed, self.sampleRateHz)\n\n self._samples = samplesMixed # overwrite\n\n return self\n\n def transcribe(self, engine='sphinx', language='en-US', expectedWords=None,\n config=None):\n \"\"\"Convert speech in audio to text.\n\n This feature passes the audio clip samples to a specified text-to-speech\n engine which will attempt to transcribe any speech within. The efficacy\n of the transcription depends on the engine selected, audio quality, and\n language support. By default, Pocket Sphinx is used which provides\n decent transcription capabilities offline for English and a few other\n languages. For more robust transcription capabilities with a greater\n range of language support, online providers such as Google may be used.\n\n Speech-to-text conversion blocks the main application thread when used\n on Python. Don't transcribe audio during time-sensitive parts of your\n experiment! This issue is known to the developers and will be fixed in a\n later release.\n\n Parameters\n ----------\n engine : str\n Speech-to-text engine to use. Can be one of 'sphinx' for CMU Pocket\n Sphinx or 'google' for Google Cloud.\n language : str\n BCP-47 language code (eg., 'en-US'). Note that supported languages\n vary between transcription engines.\n expectedWords : list or tuple\n List of strings representing expected words or phrases. This will\n constrain the possible output words to the ones specified. Note not\n all engines support this feature (only Sphinx and Google Cloud do at\n this time). A warning will be logged if the engine selected does not\n support this feature. CMU PocketSphinx has an additional feature\n where the sensitivity can be specified for each expected word. You\n can indicate the sensitivity level to use by putting a ``:`` (colon)\n after each word in the list (see the Example below). Sensitivity\n levels range between 0 and 100. A higher number results in the\n engine being more conservative, resulting in a higher likelihood of\n false rejections. The default sensitivity is 80% for words/phrases\n without one specified.\n config : dict or None\n Additional configuration options for the specified engine. These\n are specified using a dictionary (ex. `config={'pfilter': 1}` will\n enable the profanity filter when using the `'google'` engine).\n\n Returns\n -------\n :class:`~psychopy.sound.transcribe.TranscriptionResult`\n Transcription result.\n\n Notes\n -----\n * Online transcription services (eg., Google) provide robust and\n accurate speech recognition capabilities with broader language support\n than offline solutions. However, these services may require a paid\n subscription to use, reliable broadband internet connections, and may\n not respect the privacy of your participants as their responses are\n being sent to a third-party. Also consider that a track of audio data\n being sent over the network can be large, users on metered connections\n may incur additional costs to run your experiment.\n * If the audio clip has multiple channels, they will be combined prior\n to being passed to the transcription service if needed.\n\n \"\"\"\n # avoid circular import\n from psychopy.sound.transcribe import transcribe\n return transcribe(\n self,\n engine=engine,\n language=language,\n expectedWords=expectedWords,\n config=config)\n\n\ndef load(filename, codec=None):\n \"\"\"Load an audio clip from file.\n\n Parameters\n ----------\n filename : str\n File name to load.\n codec : str or None\n Codec to use. If `None`, the format will be implied from the file name.\n\n Returns\n -------\n AudioClip\n Audio clip containing samples loaded from the file.\n\n \"\"\"\n return AudioClip.load(filename, codec)\n\n\ndef save(filename, clip, codec=None):\n \"\"\"Save an audio clip to file.\n\n Parameters\n ----------\n filename : str\n File name to write audio clip to.\n clip : AudioClip\n The clip with audio samples to write.\n codec : str or None\n Format to save audio clip data as. If `None`, the format will be\n implied from the extension at the end of `filename`.\n\n \"\"\"\n clip.save(filename, codec)\n\n\nif __name__ == \"__main__\":\n pass\n",
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Stimulus object for drawing arbitrary bitmap carriers with an arbitrary\nsecond order envelope carrier and envelope can vary independently for\norientation, frequencyand phase. Also does beat stimuli. \"\"\"\n\n# Part of the PsychoPy library\n# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2021 Open Science Tools Ltd.\n# some code provided by Andrew Schofield\n# Distributed under the terms of the GNU General Public License (GPL).\n\n# Requires shaders if you don't have them it will just throw and error.\n# Ensure setting pyglet.options['debug_gl'] to False is done prior to any\n# other calls to pyglet or pyglet submodules, otherwise it may not get picked\n# up by the pyglet GL engine and have no effect.\n# Shaders will work but require OpenGL2.0 drivers AND PyOpenGL3.0+\n\nfrom __future__ import absolute_import, print_function, division\n\nimport pyglet\npyglet.options['debug_gl'] = False\nimport ctypes\nGL = pyglet.gl\ntry:\n from PIL import Image\nexcept ImportError:\n import Image\nimport psychopy # so we can get the __path__\nfrom psychopy import logging\nfrom psychopy.visual import filters\nfrom psychopy.tools.arraytools import val2array\nfrom psychopy.tools.attributetools import attributeSetter\nfrom .grating import GratingStim\nimport numpy\nfrom numpy import exp, sin, cos\nfrom numpy.fft import fft2, ifft2, fftshift, ifftshift\n\nfrom . import shaders as _shaders\n\n\nclass NoiseStim(GratingStim):\n \"\"\"A stimulus with 2 textures: a radom noise sample and a mask\n\n **Example**::\n\n noise1 = noise = visual.NoiseStim(\n win=win, name='noise',units='pix', \n noiseImage='testImg.jpg', mask='circle',\n ori=1.0, pos=(0, 0), size=(512, 512), sf=None, phase=0,\n color=[1,1,1], colorSpace='rgb', opacity=1, blendmode='add', contrast=1.0,\n texRes=512, filter='None', imageComponent='Phase'\n noiseType='Gabor', noiseElementSize=4, noiseBaseSf=32.0/512,\n noiseBW=1.0, noiseBWO=30, noiseFractalPower=-1,noiseFilterLower=3/512, noiseFilterUpper=8.0/512.0, \n noiseFilterOrder=3.0, noiseClip=3.0, filter=False, interpolate=False, depth=-1.0)\n \n # gives a circular patch of noise made up of scattered Gabor elements with peak frequency = 32.0/512 cycles per pixel, \n # orientation = 0 , frequency bandwidth = 1 octave and orientation bandwidth 30 degrees\n\n **Types of noise available**\n Binary, Normal, Uniform - pixel based noise samples drawn from a binary (blank and white), normal or uniform distribution respectively. Binary noise is always exactly zero mean, Normal and Uniform are approximately so.\n Parameters - noiseElementSize - (can be a tuple) defines the size of the noise elements in the components units.\n noiseClip the values in normally distributed noise are divided by noiseClip to limit excessively high or low values.\n However, values can still go out of range -1 to 1 whih will throw a soft error message high values of noiseClip are recommended if using 'Normal'\n \n Gabor, Isotropic - Effectively a dense scattering of Gabor elements with random amplitude and fixed orientation for Gabor or random orientation for Isotropic noise.\n Parameters - noiseBaseSf - centre spatial frequency in the component units. \n noiseBW - spatial frequency bandwidth full width half height in octaves.\n ori - center orientation for Gabor noise (works as for gratingStim so twists the final image at render time).\n noiseBWO - orientation bandwidth for Gabor noise full width half height in degrees.\n noiseOri - alternative center orientation for Gabor which sets the orientation during the image build rather than at render time.\n useful for setting the orientation of a filter to be applied to some other noise type with a different base orientation.\n\n In practice the desired amplitude spectrum for the noise is built in Fourier space with a random phase spectrum. DC term is set to zero - ie zero mean.\n \n Filtered - A white noise sample that has been filtered with a low, high or bandpass Butterworth filter. The initial sample can have its spectrum skewed towards low or high frequencies\n The contrast of the noise falls by half its maximum (3dB) at the cutoff frequencies.\n Parameters - noiseFilterUpper - upper cutoff frequency - if greater than texRes/2 cycles per image low pass filter used.\n noiseFilterLower - Lower cutoff frequency - if zero low pass filter used.\n noiseFilterOrder - The order of the filter controls the steepness of the falloff outside the passband is zero no filter is applied.\n noiseFractalPower - spectrum = f^noiseFractalPower - determines the spatial frequency bias of the initial noise sample. 0 = flat spectrum, negative = low frequency bias, positive = high frequency bias, -1 = fractal or brownian noise.\n noiseClip - determines clipping values and rescaling factor such that final rms contrast is close to that requested by contrast parameter while keeping pixel values in range -1, 1. \n\n White - A short cut to obtain noise with a flat, unfiltered spectrum\n noiseClip - determines clipping values and rescaling factor such that final rms contrast is close to that requested by contrast parameter while keeping pixel values in range -1, 1. \n\n In practice the desired amplitude spectrum is built in the Fourier Domain with a random phase spectrum. DC term is set to zero - ie zero mean\n Note despite name the noise contains all grey levels.\n\n Image - A noise sample whose spatial frequency spectrum is taken from the supplied image.\n Parameters - noiseImage name of nparray or image file from which to take spectrum - should be same size as largest side requested for component if units is pix or texRes x texRes otherwise\n imageComponent: 'Phase' ransomizes the phase spectrum leaving the amplitude spectrum untouched.\n 'Amplitude' randomizes the amplitude spectrum leaving the phase spectrum untouched - retains spatial structure of image.\n 'Neither' keeps the image as is - but you can now apply a spatial filter to the image.\n noiseClip - determines clipping values and rescaling factor such that final rms contrast is close to that requested by contrast parameter while keeping pixel values in range -1, 1. \n\n In practice the desired amplitude spectrum is taken from the image and paired with a random phase spectrum. DC term is set to zero - ie zero mean\n \n **filter parameter\n If the filter parameter = Butterworth then the a spectral filter defined by the filtered noise parameters will be applied to the other noise types.\n If the filter parameter = Gabor then the a spectral filter defined by the Gabor noise parameters will be applied to the other noise types.\n If the filter parameter = Isotropic then the a spectral filter defined by the Isotropic noise parameters will be applied to the other noise types.\n \n \n **Updating noise samples and timing**\n The noise is rebuilt at next call of the draw function whenever a parameter starting 'noise' is notionally changed even if the value does not actually change every time. eg. setting a parameter to update every frame will cause a new noise sample on every frame but see below.\n A rebuild can also be forced at any time using the buildNoise() function.\n The updateNoise() function can be used at any time to produce a new random saple of noise without doing a full build. ie it is quicker than a full build.\n Both buildNoise and updateNoise can be slow for large samples. \n Samples of Binary, Normal or Uniform noise can usually be made at frame rate using noiseUpdate. \n Updating or building other noise types at frame rate may result in dropped frames. \n An alternative is to build a large sample of noise at the start of the routien and place it off the screen then cut a samples out of this at random locations and feed that as a numpy array into the texture of a visible gratingStim.\n\n **Notes on size**\n If units = pix and noiseType = Binary, Normal or Uniform will make noise sample of requested size.\n If units = pix and noiseType is Gabor, Isotropic, Filtered, White, Coloured or Image will make square noise sample with side length equal that of the largest dimetions requested.\n if units is not pix will make square noise sample with side length equal to texRes then rescale to present.\n \n **Notes on interpolation**\n For pixel based noise interpolation = nearest is usually best.\n For other noise types linear is better if the size of the noise sample does not match the final size of the image well.\n \n **Notes on frequency**\n Frequencies for cutoffs etc are converted between units for you but can be counter intuitive. 1/size is always 1 cycle per image.\n For the sf (final spatial frequency) parameter itself 1/size (or None for units pix) will faithfully represent the image without further scaling.\n \n Filter cuttoff and Gabor/Isotropic base frequencies should not be too high you should aim to keep them below 0.5 c/pixel on the screen.\n The function will produce an error when it can't draw the stimulus in the buffer but it may still be wrong when displayed.\n \n **Notes on orientation and phase**\n The ori parameter twists the final image so the samples in noiseType Binary, Normal or Uniform will no longer be alighned to the sides of the monitor if ori is not a multiple of 90.\n Most other noise types look broadly the same for all values of ori but the specific sample shown can be made to rotate by changing ori.\n The dominant orientation for Gabor noise is determined by ori at render time, not before.\n \n The phase parameter similarly shifts the sample around within the display window at render time and will not choose new random phases for the noise sample.\n \"\"\"\n\n def __init__(self,\n win,\n mask=\"none\",\n units=\"\",\n pos=(0.0, 0.0),\n size=None,\n sf=None,\n ori=0.0,\n phase=(0.0, 0.0),\n noiseType=None,\n noiseElementSize=16,\n noiseBaseSf=1,\n noiseBW=1,\n noiseBWO=30,\n noiseOri=0,\n noiseFractalPower=0.0,\n noiseFilterUpper=50,\n noiseFilterLower=0,\n noiseFilterOrder=0.0,\n noiseClip=1,\n noiseImage=None,\n imageComponent='Phase',\n filter=None,\n texRes=128,\n rgb=None,\n dkl=None,\n lms=None,\n color=(1.0, 1.0, 1.0),\n colorSpace='rgb',\n contrast=0.5, # see doc\n opacity=1.0,\n depth=0,\n rgbPedestal=(0.0, 0.0, 0.0),\n interpolate=False,\n blendmode='avg',\n name=None,\n autoLog=None,\n autoDraw=False,\n maskParams=None):\n \"\"\" \"\"\" # Empty docstring. All doc is in attributes\n # what local vars are defined (these are the init params) for use by\n # __repr__\n\n self._initParams = dir()\n\n if noiseType is None:\n msg = ('noiseType not recognized. Valid types are: \\n'\n 'binary, uniform, normal, white, filtered, gabor, '\n 'isotropic, or image.')\n raise ValueError(msg)\n elif noiseType == 'image' and noiseImage is None:\n msg = ('You need to supply an image via the noiseImage keyword '\n 'argument.')\n raise ValueError(msg)\n\n for unecess in ['self', 'rgb', 'dkl', 'lms']:\n self._initParams.remove(unecess)\n # initialise parent class\n GratingStim.__init__(self, win, tex='sin',\n units=units, pos=pos, size=size, sf=sf,\n ori=ori, phase=phase,\n color=color, colorSpace=colorSpace,\n contrast=contrast, opacity=opacity,\n depth=depth, interpolate=interpolate,\n name=name, autoLog=autoLog, autoDraw=autoDraw,\n blendmode=blendmode,\n maskParams=None)\n # use shaders if available by default, this is a good thing\n self.__dict__['useShaders'] = win._haveShaders\n # UGLY HACK: Some parameters depend on each other for processing.\n # They are set \"superficially\" here.\n # TO DO: postpone calls to _createTexture, setColor and\n # _calcCyclesPerStim whin initiating stimulus\n\n self.__dict__['mask'] = mask\n self.__dict__['maskParams'] = maskParams\n\n self.blendmode=blendmode\n self.mask = mask\n self.texRes=int(texRes)\n self.noiseType=noiseType\n self.noiseImage=noiseImage\n self.imageComponent=imageComponent\n self.noiseElementSize=noiseElementSize\n self.noiseBaseSf=float(noiseBaseSf)\n self.noiseBW=float(noiseBW)\n self.noiseBWO=float(noiseBWO)\n self.noiseOri=float(noiseOri)\n self.noiseFractalPower=float(noiseFractalPower)\n self.noiseFilterUpper=float(noiseFilterUpper)\n self.noiseFilterLower=float(noiseFilterLower)\n self.noiseFilterOrder=float(noiseFilterOrder)\n if noiseClip != 'none':\n self.noiseClip=float(noiseClip)\n else:\n self.noiseClip=noiseClip\n self.filter = filter\n self.local = numpy.ones((texRes, texRes), dtype=numpy.ubyte)\n self.local_p = self.local.ctypes\n self._sideLength=1.0 \n self._size=512 # in unlikely case where it does not get set anywhere else before use.\n self.buildNoise()\n self._needBuild = False\n\n\n @attributeSetter\n def noiseType(self, value):\n \"\"\"Type of noise to generate\n 'Binary, Normal and Uniform' produce pixel based random samples from the indicated distribitions. \n Binary has zero mean lumiannce, Normal and Uniform approximate this.\n 'Gabor and Isotropic' produce dense, random scatterd Gabor elements with \n fixed (Gabor) or random (Isotropic) orientations. Zero mean lumiannce.\n 'White' produces white noise with a flat amplitude spectrum. Zero mean lumiannce.\n 'Filtered' Produces white noise filtered by a low-, high- or band-pass filter. Zero mean lumiannce.\n Use the noiseFractalPower attribute to skew the spectrum of filtered noise.\n 'Image' produces noise with the same spectrum as the supplied image but with mean lumiance set to zero.\n \n \"\"\"\n self.__dict__['noiseType'] = value\n self._needUpdate = True\n self._needBuild = True\n \n @attributeSetter\n def noiseImage(self, value):\n \"\"\"Image from which to derive the amplitude or phase spectrum of noise type Image. \n \"\"\"\n \n self.__dict__['noiseImage'] = value\n self._needUpdate = True\n self._needBuild = True\n \n @attributeSetter\n def imageCompoment(self, value):\n \"\"\"Which compoment of an image to randomise, amplitude or phase. \n \"\"\"\n \n self.__dict__['imageComponent'] = value\n self._needUpdate = True\n self._needBuild = True\n\n @attributeSetter\n def noiseElementSize(self, value):\n \"\"\"Noise element size for Binary, Normal or Uniform noise.\n In the units of the stimulus.\n \"\"\"\n \n self.__dict__['noiseElementSize'] = value\n self._needUpdate = True\n self._needBuild = True\n \n @attributeSetter\n def noiseBaseSf(self, value):\n \"\"\"Spatial frequency for Gabor or Isotropic noise in cycles per unit.\n Eg c/deg if units = degrees.\n \"\"\"\n \n self.__dict__['noiseBaseSf'] = value\n self._needUpdate = True\n self._needBuild = True\n \n @attributeSetter\n def noiseBW(self, value):\n \"\"\"Spatial frequency bandwidth for Gabor or Isotropic noise, full width at half height in octaves.\n \"\"\"\n \n self.__dict__['noiseBW'] = value\n self._needUpdate = True \n self._needBuild = True\n \n @attributeSetter\n def noiseBWO(self, value):\n \"\"\"Orientation bandwidth for Gabor noise, full width at half height in degrees\n \"\"\"\n \n self.__dict__['noiseBWO'] = value\n self._needUpdate = True\n self._needBuild = True\n \n @attributeSetter\n def noiseFractalPower(self, value):\n \"\"\"Exponent for 'coloured' noise. \n Amplitide spectrum = f^noiseFractalPower.\n -1 gives pink noise.\n Note power spectrum of a pink noise image should\n fall as f^-2. But as power spectrum = amplitude spectrum squared\n this is achived by setting amplitude spectrum to f^-1.\n \"\"\"\n \n self.__dict__['noiseFractalPower'] = value\n self._needUpdate = True\n self._needBuild = True\n \n @attributeSetter\n def noiseFilterUpper(self, value):\n \"\"\"Upper cuttoff for filtered noise. \n In cycles/unit eg c/deg when units is degrees.\n > size/2 creates high pass filter. \n \"\"\"\n \n self.__dict__['noiseFilterUpper'] = value\n self._needUpdate = True\n self._needBuild = True\n \n @attributeSetter\n def noiseFilterLower(self, value):\n \"\"\"Lower cuttoff for filtered noise. \n In cycles/unit eg c/deg when units is degrees.\n Zero creates low pass filter.\n \"\"\"\n \n self.__dict__['noiseFilterLower'] = value\n self._needUpdate = True\n self._needBuild = True\n \n @attributeSetter\n def noiseFilterOrder(self, value):\n \"\"\"Order of Butterworth filter for filtered noise. High = fast fall off withfrequency outside pass band.\n \"\"\"\n \n self.__dict__['noiseFilterOrder'] = value\n self._needUpdate = True\n self._needBuild = True\n \n @attributeSetter\n def noiseClip(self, value):\n \"\"\"Ignored for types 'Binary and Uniform'.\n For 'Normal' noise pixel values are divided by noiseClip \n to limit the standard deviation of the noise values.\n \n For all other noise types noiseClip determines the \n level at which pixel values are cliped and subsequently \n re-scaled so as to produce a final image appraching the \n desired RMS contrast.\n High values will tend to reduce the ultimate RMS \n contrast but increase fidelity of appearance.\n Low values prioritise accurate final contrast\n but result in a binarised or thresholded appearance.\n \n noiseClip is used to scale the luminance values as\n above whenever a filter is applied to the noise sample, \n regardless of the inital type of noise requested. \n \"\"\"\n \n self.__dict__['noiseClip'] = value\n self._needUpdate = True\n self._needBuild = True\n\n @attributeSetter\n def filter(self, value):\n \"\"\"If True apply spatial frequency filter to noise.\"\"\"\n \n self.__dict__['filter'] = value\n self._needUpdate = True\n self._needBuild = True\n\n @attributeSetter\n def texRes(self, value):\n \"\"\"Power-of-two int. Sets the resolution of the mask and texture.\n maybe used as the side length for generating the noise texture but is not used if units = pix.\n\n :ref:`Operations <attrib-operations>` supported.\n \"\"\"\n self.__dict__['texRes'] = value\n\n # ... now rebuild textures (call attributeSetters without logging).\n \n self._needUpdate = True \n self._needBuild = True\n \n if hasattr(self, 'tex'):\n self._set('tex', self.tex, log=False)\n if hasattr(self, 'mask'):\n self._set('mask', self.mask, log=False)\n\n def setTexRes(self, value, log=None):\n self._set('texRes', value, log=log)\n \n def setNoiseType(self, value, log=None):\n self._set('noiseType', value, log=log)\n \n def setNoiseImage(self, value, log=None):\n self._set('noiseImage', value, log=log)\n \n def setImageCompoment(self, value, log=None):\n self._set('imageCompoment',value, log=log)\n \n def setNoiseClip(self, value, log=None):\n self._set('noiseClip', value, log=log)\n \n def setFilter(self, value, log=None):\n self._set('filter', value, log=log)\n \n def setNoiseElementSize(self, value, log=None):\n self._set('noiseElementSize', value, log=log)\n \n def setNoiseBaseSf(self, value, log=None):\n self._set('noiseBaseSf', value, log=log)\n \n def setNoiseBW(self, value, log=None):\n self._set('noiseBW', value, log=log)\n \n def setNoiseBWO(self, value, log=None):\n self._set('noiseBWO', value, log=log)\n \n def setNoiseFractalPower(self, value, log=None):\n self._set('noiseFractalPower', value, log=log)\n \n def setNoiseFilterUpper(self, value, log=None):\n self._set('noiseFilterUpper', value, log=log)\n \n def setNoiseFilterLower(self, value, log=None):\n self._set('noiseFilterLower', value, log=log)\n \n def setNoiseFilterOrder(self, value, log=None):\n self._set('noiseFilterOrder', value, log=log)\n\n def setblendMode(self, value, log=None):\n self._set('blendMode', value, log=log)\n\n def draw(self, win=None):\n \"\"\"Draw the stimulus in its relevant window. You must call\n this method after every MyWin.flip() if you want the\n stimulus to appear on that frame and then update the screen\n again.\n \"\"\"\n if win is None:\n win = self.win\n saveBlendMode = win.blendMode\n win.setBlendMode(self.blendmode, log=False)\n self._selectWindow(win)\n\n #do scaling\n GL.glPushMatrix() # push before the list, pop after\n win.setScale('pix')\n #the list just does the texture mapping\n GL.glColor4f(*self._foreColor.render('rgba1'))\n\n # re-build the noise if not done so since last parameter update\n if self._needBuild:\n self.buildNoise()\n # remake textures if necessary\n if self._needTextureUpdate:\n self.setTex(value=self.tex, log=False)\n if self._needUpdate:\n self._updateList()\n GL.glCallList(self._listID)\n\n #return the view to previous state\n GL.glPopMatrix()\n win.setBlendMode(saveBlendMode, log=False)\n \n def _filter(self, FT):\n \"\"\" Helper function to apply Butterworth filter in \n frequensy domain.\n \"\"\"\n filterSize = numpy.max(self._size)\n pin=filters.makeRadialMatrix(matrixSize=filterSize, center=(0,0), radius=1.0)\n pin[int(filterSize / 2)][int(filterSize / 2)] = 0.00000001 # Prevents divide by zero error. This is DC and is set to zero later anyway.\n FT = numpy.multiply(FT,(pin) ** self.noiseFractalPower)\n if self.noiseFilterOrder > 0.01:\n if self._upsf<(filterSize/2.0):\n filter = filters.butter2d_lp_elliptic(size = [filterSize,filterSize], \n cutoff_x = self._upsf / filterSize, \n cutoff_y = self._upsf / filterSize, \n n=self.noiseFilterOrder, \n alpha=0, \n offset_x = 0.5/filterSize, #becuase FFTs are slightly off centred.\n offset_y = 0.5/filterSize)\n else:\n filter = numpy.ones((int(filterSize),int(filterSize)))\n if self._lowsf > 0:\n if self._lowsf > filterSize/2:\n msg = ('Lower cut off frequency for filtered '\n 'noise is too high (exceeds Nyquist limit).')\n raise Warning(msg)\n filter = filter-filters.butter2d_lp_elliptic(size = [filterSize,filterSize], \n cutoff_x = self._lowsf / filterSize, \n cutoff_y = self._lowsf / filterSize, \n n = self.noiseFilterOrder, \n alpha = 0, \n offset_x = 0.5/filterSize, #becuase FFTs are slightly off centred.\n offset_y = 0.5/filterSize)\n return FT * filter\n else:\n return FT\n \n def _isotropic(self, FT):\n \"\"\" Helper function to apply isotropic filter in \n frequensy domain.\n \"\"\"\n if self._sf > self._size / 2:\n msg = ('Base frequency for isotropic '\n 'noise is too high (exceeds Nyquist limit).')\n raise Warning(msg)\n localf = self._sf / self._size\n linbw = 2 ** self.noiseBW\n lowf = 2.0 * localf / (linbw+1.0)\n highf = linbw * lowf\n FWF = highf - lowf\n sigmaF = FWF / (2*numpy.sqrt(2*numpy.log(2)))\n pin = filters.makeRadialMatrix(matrixSize=self._size, center=(0,0), radius=2)\n filter = filters.makeGauss(pin, mean=localf, sd=sigmaF)\n return FT*filter\n \n def _gabor(self, FT):\n \"\"\" Helper function to apply Gabor filter in \n frequensy domain.\n \"\"\"\n if self._sf > self._size / 2:\n msg = ('Base frequency for Gabor '\n 'noise is too high (exceeds Nyquist limit).')\n raise Warning(msg)\n localf = self._sf / self._size\n linbw = 2 ** self.noiseBW\n lowf = 2.0 * localf / (linbw + 1.0)\n highf = linbw * lowf\n FWF = highf - lowf\n sigmaF = FWF/(2*numpy.sqrt(2*numpy.log(2)))\n FWO = 2.0*localf*numpy.tan(numpy.pi*self.noiseBWO/360.0)\n sigmaO = FWO/(2*numpy.sqrt(2*numpy.log(2)))\n yy, xx = numpy.mgrid[0:self._size, 0:self._size]\n xx = (0.5 - 1.0 / self._size * xx) \n yy = (0.5 - 1.0 / self._size * yy) \n filter=filters.make2DGauss(xx,yy,mean=(localf,0), sd=(sigmaF,sigmaO))\n filter=filter+filters.make2DGauss(xx,yy, mean=(-localf,0), sd=(sigmaF,sigmaO))\n filter = numpy.array(\n Image.fromarray(filter).rotate(\n self.noiseOri,\n Image.BICUBIC\n )\n )\n return FT*filter\n\n def updateNoise(self):\n \"\"\"Updates the noise sample. Does not change any of the noise parameters \n but choses a new random sample given the previously set parameters.\n \"\"\"\n\n if not(self.noiseType in ['binary','Binary','normal','Normal','uniform','Uniform']):\n if (self.noiseType in ['image', 'Image']) and (self.imageComponent in ['amplitude','Amplitude']):\n self.noiseTex = numpy.random.uniform(0,1,int(self._size**2))\n self.noiseTex = numpy.reshape(self.noiseTex,(int(self._size),int(self._size)))\n if self.filter in ['Butterworth','butterworth']:\n self.noiseTex = fftshift(self._filter(self.noiseTex))\n elif self.filter in ['Gabor','gabor']:\n self.noiseTex = fftshift(self._gabor(self.noiseTex))\n elif self.filter in ['Isotropic','isotropic']:\n self.noiseTex = fftshift(self._isotropic(self.noiseTex))\n self.noiseTex[0][0] = 0\n In = self.noiseTex * exp(1j*self.noisePh)\n Im = numpy.real(ifft2(In))\n else:\n Ph = numpy.random.uniform(0,2*numpy.pi,int(self._size**2))\n Ph = numpy.reshape(Ph,(int(self._size),int(self._size)))\n In = self.noiseTex * exp(1j*Ph)\n Im = numpy.real(ifft2(In))\n Im = ifftshift(Im)\n gsd = filters.getRMScontrast(Im)\n factor = gsd*self.noiseClip\n numpy.clip(Im, -factor, factor, Im)\n self.tex = Im / factor\n elif self.noiseType in ['normal','Normal']:\n self.noiseTex = numpy.random.randn(int(self._sideLength[1]),int(self._sideLength[0])) / self.noiseClip\n elif self.noiseType in ['uniform','Uniform']:\n self.noiseTex = 2.0 * numpy.random.rand(int(self._sideLength[1]),int(self._sideLength[0])) - 1.0\n else:\n numpy.random.shuffle(self.noiseTex) # pick random noise sample by shuffleing values\n self.noiseTex = numpy.reshape(self.noiseTex,(int(self._sideLength[1]),int(self._sideLength[0])))\n if self.noiseType in ['binary','Binary','normal','Normal','uniform','Uniform']:\n if self.filter in ['butterworth', 'Butterworth', 'Gabor','gabor','Isotropic','isotropic']:\n if self.units == 'pix':\n if self._size[0] == self._size[1]:\n baseImage = numpy.array(\n Image.fromarray(self.noiseTex).resize(\n (int(self._size[0]), int(self._size[1])),\n Image.NEAREST\n )\n )\n else:\n msg = ('NoiseStim can only apply filters to square noise images')\n raise ValueError(msg)\n else:\n baseImage = numpy.array(\n Image.fromarray(self.noiseTex).resize(\n (int(self._size), int(self._size)),\n Image.NEAREST\n )\n )\n baseImage = numpy.array(baseImage).astype(\n numpy.float32) * 0.0078431372549019607 - 1.0\n FT = fft2(baseImage)\n spectrum = numpy.absolute(fftshift(FT))\n angle = numpy.angle(FT)\n if self.filter in ['butterworth','Butterworth']:\n spectrum = fftshift(self._filter(spectrum))\n elif self.filter in ['isotropic','Isotropic']:\n spectrum = fftshift(self._isotropic(spectrum))\n elif self.filter in ['gabor','Gabor']:\n spectrum = fftshift(self._gabor(spectrum))\n spectrum[0][0] = 0 # set DC to zero\n FT = spectrum * exp(1j*angle)\n \n Im = numpy.real(ifft2(FT))\n gsd = filters.getRMScontrast(Im)\n factor = gsd*self.noiseClip\n numpy.clip(Im, -factor, factor, Im)\n self.tex = Im / factor\n else:\n if not(self.noiseType in ['image','Image']):\n self.tex = self.noiseTex\n \n \n \n def buildNoise(self):\n \"\"\"build a new noise sample. Required to act on changes to any noise parameters or texRes.\n \"\"\"\n\n if self.units == 'pix':\n if not (self.noiseType in ['Binary','binary','Normal','normal','uniform','Uniform']):\n mysize = numpy.max(self.size)\n else:\n mysize = self.size\n sampleSize = self.noiseElementSize\n mysf = self.__dict__['noiseBaseSf']*mysize\n lowsf = self.noiseFilterLower*numpy.max(mysize) # filter can only be applied to square images anyway\n upsf = self.noiseFilterUpper*numpy.max(mysize)\n else:\n mysize = self.texRes\n pixSize = self.size/self.texRes\n sampleSize = self.noiseElementSize/pixSize\n mysf = self.size[0]*self.noiseBaseSf\n lowsf = self.size[0]*self.noiseFilterLower\n upsf = self.size[0]*self.noiseFilterUpper\n \n self._size = mysize # store for use by updateNoise()\n self._sf = mysf\n self._lowsf = lowsf\n self._upsf = upsf\n if self.noiseType in ['binary','Binary','normal','Normal','uniform','Uniform']:\n self._sideLength = numpy.round(mysize/sampleSize) # dummy side length for use when unpacking noise samples in updateNoise()\n self._sideLength.astype(int)\n if ((self._sideLength[0] < 2) and (self._sideLength[1] < 2)):\n msg=('Noise sample size '\n 'must result in more than '\n '1 sample per image dimension.')\n raise ValueError(msg)\n totalSamples = self._sideLength[0]*self._sideLength[1]\n if self.noiseType in ['binary','Binary']:\n self.noiseTex=numpy.append(numpy.ones(int(numpy.round(totalSamples/2.0))),-1*numpy.ones(int(numpy.round(totalSamples/2.0))))\n elif self.noiseType in ['White','white','filtered','Filtered','isotropic','Isotropic','Gabor','gabor']:\n self.noiseTex = numpy.ones((int(mysize),int(mysize)))\n self.noiseTex = fftshift(self.noiseTex)\n elif self.noiseType in ['Image','image']:\n if not(self.noiseImage in ['None','none']): \n im = Image.open(self.noiseImage)\n im = im.transpose(Image.FLIP_TOP_BOTTOM)\n im = im.convert(\"L\") # FORCE TO LUMINANCE\n im = im.resize((int(self._size),int(self._size)),\n Image.BILINEAR)\n intensity = numpy.array(im).astype(\n numpy.float32) * 0.0078431372549019607 - 1.0\n if self.imageComponent in ['phase', 'Phase']:\n self.noiseTex = numpy.absolute(fftshift(fft2(intensity))) # fftshift here is undone later\n elif self.imageComponent in ['amplitude', 'Amplitude']:\n self.noisePh = numpy.angle((fft2(intensity))) # fftshift here is undone later\n self.noiseTex = numpy.random.uniform(0,1,int(self._size**2))\n self.noiseTex = numpy.reshape(self.noiseTex,(int(self._size),int(self._size)))\n else:\n raise ValueError(\"Unknown value for imageComponent in noiseStim\")\n else:\n self.noiseTex = numpy.ones((int(mysize),int(mysize))) # if image is 'None' will make white noise as temporary measure\n else:\n msg = ('Noise type not recognised. Valid types are Binary, Uniform, Normal,'\n 'White, Filtered, Gabor, Isotropic or Image')\n raise ValueError(msg)\n if not(self.noiseType in ['binary','Binary','normal','Normal','uniform','Uniform']):\n if (self.noiseType in ['filtered','Filtered']) or (self.filter in ['butterworth', 'Butterworth']):\n self.noiseTex=self._filter(self.noiseTex)\n elif (self.noiseType in ['Isotropic','isotropic']) or (self.filter in ['isotropic', 'Isotropic']):\n self.noiseTex = self._isotropic(self.noiseTex)\n elif (self.noiseType in ['Gabor','gabor']) or (self.filter in ['gabor', 'Gabor']):\n self.noiseTex = self._gabor(self.noiseTex)\n self.noiseTex = fftshift(self.noiseTex)\n self.noiseTex[0][0] = 0 # Set DC to zero\n \n self._needBuild = False # prevent noise from being re-built at next draw() unless a parameter is changed in the mean time.\n self.updateNoise() # now choose the initial random sample.\n\n",
"import numpy as np\n\nfrom moviepy.audio.AudioClip import CompositeAudioClip\nfrom moviepy.video.VideoClip import ColorClip, VideoClip\n\n# CompositeVideoClip\n\nclass CompositeVideoClip(VideoClip):\n\n \"\"\" \n \n A VideoClip made of other videoclips displayed together. This is the\n base class for most compositions.\n \n Parameters\n ----------\n\n size\n The size (height x width) of the final clip.\n\n clips\n A list of videoclips. Each clip of the list will\n be displayed below the clips appearing after it in the list.\n For each clip:\n \n - The attribute ``pos`` determines where the clip is placed.\n See ``VideoClip.set_pos``\n - The mask of the clip determines which parts are visible.\n \n Finally, if all the clips in the list have their ``duration``\n attribute set, then the duration of the composite video clip\n is computed automatically\n\n bg_color\n Color for the unmasked and unfilled regions. Set to None for these\n regions to be transparent (will be slower).\n\n use_bgclip\n Set to True if the first clip in the list should be used as the\n 'background' on which all other clips are blitted. That first clip must\n have the same size as the final clip. If it has no transparency, the final\n clip will have no mask. \n \n The clip with the highest FPS will be the FPS of the composite clip.\n\n \"\"\"\n\n def __init__(self, clips, size=None, bg_color=None, use_bgclip=False,\n ismask=False):\n\n if size is None:\n size = clips[0].size\n\n \n if use_bgclip and (clips[0].mask is None):\n transparent = False\n else:\n transparent = (bg_color is None)\n \n if bg_color is None:\n bg_color = 0.0 if ismask else (0, 0, 0)\n\n fpss = [c.fps for c in clips if getattr(c, 'fps', None)]\n self.fps = max(fpss) if fpss else None\n\n VideoClip.__init__(self)\n \n self.size = size\n self.ismask = ismask\n self.clips = clips\n self.bg_color = bg_color\n\n if use_bgclip:\n self.bg = clips[0]\n self.clips = clips[1:]\n self.created_bg = False\n else:\n self.clips = clips\n self.bg = ColorClip(size, color=self.bg_color)\n self.created_bg = True\n\n \n # compute duration\n ends = [c.end for c in self.clips]\n if None not in ends:\n duration = max(ends)\n self.duration = duration\n self.end = duration\n\n # compute audio\n audioclips = [v.audio for v in self.clips if v.audio is not None]\n if audioclips:\n self.audio = CompositeAudioClip(audioclips)\n\n # compute mask if necessary\n if transparent:\n maskclips = [(c.mask if (c.mask is not None) else\n c.add_mask().mask).set_position(c.pos)\n .set_end(c.end).set_start(c.start, change_end=False)\n for c in self.clips]\n\n self.mask = CompositeVideoClip(maskclips,self.size, ismask=True,\n bg_color=0.0)\n\n def make_frame(t):\n \"\"\" The clips playing at time `t` are blitted over one\n another. \"\"\"\n\n f = self.bg.get_frame(t)\n for c in self.playing_clips(t):\n f = c.blit_on(f, t)\n return f\n\n self.make_frame = make_frame\n\n def playing_clips(self, t=0):\n \"\"\" Returns a list of the clips in the composite clips that are\n actually playing at the given time `t`. \"\"\"\n return [c for c in self.clips if c.is_playing(t)]\n\n def close(self):\n if self.created_bg and self.bg:\n # Only close the background clip if it was locally created.\n # Otherwise, it remains the job of whoever created it.\n self.bg.close()\n self.bg = None\n if hasattr(self, \"audio\") and self.audio:\n self.audio.close()\n self.audio = None\n\n\n\ndef clips_array(array, rows_widths=None, cols_widths=None,\n bg_color = None):\n\n \"\"\"\n\n rows_widths\n widths of the different rows in pixels. If None, is set automatically.\n\n cols_widths\n widths of the different colums in pixels. If None, is set automatically.\n\n cols_widths\n \n bg_color\n Fill color for the masked and unfilled regions. Set to None for these\n regions to be transparent (will be slower).\n\n \"\"\"\n \n array = np.array(array)\n sizes_array = np.array([[c.size for c in line] for line in array])\n \n # find row width and col_widths automatically if not provided\n if rows_widths is None:\n rows_widths = sizes_array[:,:,1].max(axis=1)\n if cols_widths is None:\n cols_widths = sizes_array[:,:,0].max(axis=0)\n \n xx = np.cumsum([0]+list(cols_widths)) \n yy = np.cumsum([0]+list(rows_widths))\n \n for j, (x, cw) in enumerate(zip(xx[:-1], cols_widths)):\n for i, (y, rw) in enumerate(zip(yy[:-1], rows_widths)):\n clip = array[i, j]\n w, h = clip.size\n if (w < cw) or (h < rw):\n clip = (CompositeVideoClip([clip.set_position('center')],\n size = (cw,rw),\n bg_color = bg_color).\n set_duration(clip.duration))\n \n array[i, j] = clip.set_position((x, y))\n \n return CompositeVideoClip(array.flatten(), size=(xx[-1], yy[-1]), bg_color=bg_color)\n",
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"All tests in this file involve rapidly changing colours, do not run these\ntests in a setting where you can view the output if you have photosensitive\nepilepsy.\n\n\"\"\"\nfrom psychopy.alerts._errorHandler import _BaseErrorHandler\nfrom psychopy.tests import utils\nfrom psychopy import visual, colors\nimport numpy as np\n\n# Define expected values for different spaces\nexemplars = [\n {'rgb': ( 1.00, 1.00, 1.00), 'rgb255': (255, 255, 255), 'hsv': ( 0, 0.00, 1.00), 'hex': '#ffffff', 'named': 'white'}, # Pure white\n {'rgb': ( 0.00, 0.00, 0.00), 'rgb255': (128, 128, 128), 'hsv': ( 0, 0.00, 0.50), 'hex': '#808080', 'named': 'gray'}, # Mid grey\n {'rgb': (-1.00, -1.00, -1.00), 'rgb255': ( 0, 0, 0), 'hsv': ( 0, 0.00, 0.00), 'hex': '#000000', 'named': 'black'}, # Pure black\n {'rgb': ( 1.00, -1.00, -1.00), 'rgb255': (255, 0, 0), 'hsv': ( 0, 1.00, 1.00), 'hex': '#ff0000', 'named': 'red'}, # Pure red\n {'rgb': (-1.00, 1.00, -1.00), 'rgb255': ( 0, 255, 0), 'hsv': (120, 1.00, 1.00), 'hex': '#00ff00', 'named': 'lime'}, # Pure green\n {'rgb': (-1.00, -1.00, 1.00), 'rgb255': ( 0, 0, 255), 'hsv': (240, 1.00, 1.00), 'hex': '#0000ff', 'named': 'blue'}, # Pure blue\n # Psychopy colours\n {'rgb': (-0.20, -0.20, -0.14), 'rgb255': (102, 102, 110), 'hsv': (240, 0.07, 0.43), 'hex': '#66666e'}, # grey\n {'rgb': ( 0.35, 0.35, 0.38), 'rgb255': (172, 172, 176), 'hsv': (240, 0.02, 0.69), 'hex': '#acacb0'}, # light grey\n {'rgb': ( 0.90, 0.90, 0.90), 'rgb255': (242, 242, 242), 'hsv': ( 0, 0.00, 0.95), 'hex': '#f2f2f2'}, # offwhite\n {'rgb': ( 0.90, -0.34, -0.29), 'rgb255': (242, 84, 91), 'hsv': (357, 0.65, 0.95), 'hex': '#f2545b'}, # red\n {'rgb': (-0.98, 0.33, 0.84), 'rgb255': ( 2, 169, 234), 'hsv': (197, 0.99, 0.92), 'hex': '#02a9ea'}, # blue\n {'rgb': (-0.15, 0.60, -0.09), 'rgb255': (108, 204, 116), 'hsv': (125, 0.47, 0.80), 'hex': '#6ccc74'}, # green\n {'rgb': ( 0.85, 0.18, -0.98), 'rgb255': (236, 151, 3), 'hsv': ( 38, 0.99, 0.93), 'hex': '#ec9703'}, # orange\n {'rgb': ( 0.89, 0.65, -0.98), 'rgb255': (241, 211, 2), 'hsv': ( 52, 0.99, 0.95), 'hex': '#f1d302'}, # yellow\n {'rgb': ( 0.53, 0.49, 0.94), 'rgb255': (195, 190, 247), 'hsv': (245, 0.23, 0.97), 'hex': '#c3bef7'}, # violet\n]\n# A few values which are likely to mess things up\ntykes = [\n {'rgba': ( 1.00, 1.00, 1.00, 0.50), 'rgba255': (255, 255, 255, 0.50), 'hsva': ( 0, 0.00, 1.00, 0.50)}, # Make sure opacities work in every space\n {'rgba': \"white\", 'rgba255': \"white\", \"hsva\": \"white\", \"hex\": \"white\", \"rgb255\": \"#ffffff\"}, # Overriding colorSpace with hex or named values\n {'rgba': None, 'named': None, 'hex': None, 'hsva': None}, # None as a value\n]\n\nclass Test_Window(object):\n \"\"\"Some tests just for the window - we don't really care about what's drawn inside it\n \"\"\"\n @classmethod\n def setup_class(self):\n self.win = visual.Window([128,128], pos=[50,50], allowGUI=False, autoLog=False)\n self.error = _BaseErrorHandler()\n\n @classmethod\n def teardown_class(self):\n self.win.close()\n\n # Begin test\n def test_colors(self):\n for colorSet in exemplars + tykes:\n # Construct matrix of space pairs\n spaceMatrix = []\n for space1 in colorSet:\n spaceMatrix.extend([[space1, space2] for space2 in colorSet if space2 != space1])\n # Compare each space pair for consistency\n for space1, space2 in spaceMatrix:\n col1 = colors.Color(colorSet[space1], space1)\n col2 = colors.Color(colorSet[space2], space2)\n closeEnough = all(abs(col1.rgba[i]-col2.rgba[i])<0.02 for i in range(4))\n # Check that valid color has been created\n assert (bool(col1) and bool(col2))\n # Check setters\n assert (col1 == col2 or closeEnough)\n\n def test_window_colors(self):\n # Iterate through color sets\n for colorSet in exemplars + tykes:\n for space in colorSet:\n # Set window color\n self.win.colorSpace = space\n self.win.color = colorSet[space]\n self.win.flip()\n utils.comparePixelColor(self.win, colors.Color(colorSet[space], space))\n\n def test_shape_colors(self):\n # Create rectangle with chunky border\n obj = visual.Rect(self.win, units=\"pix\", pos=(0,0), size=(128, 128), lineWidth=10)\n # Iterate through color sets\n for colorSet in exemplars + tykes:\n for space in colorSet:\n # Check border color\n obj.colorSpace = space\n obj.borderColor = colorSet[space]\n obj.fillColor = 'white'\n obj.opacity = 1 # Fix opacity at full as this is not what we're testing\n self.win.flip()\n obj.draw()\n if colorSet[space]: # skip this comparison if color is None\n utils.comparePixelColor(self.win, colors.Color(colorSet[space], space), coord=(1, 1))\n utils.comparePixelColor(self.win, colors.Color('white'), coord=(50, 50))\n # Check fill color\n obj.colorSpace = space\n obj.fillColor = colorSet[space]\n obj.borderColor = 'white'\n obj.opacity = 1 # Fix opacity at full as this is not what we're testing\n self.win.flip()\n obj.draw()\n if colorSet[space]: # skip this comparison if color is None\n utils.comparePixelColor(self.win, colors.Color(colorSet[space], space), coord=(50, 50))\n utils.comparePixelColor(self.win, colors.Color('white'), coord=(1,1))\n\n # Testing foreColor is already done in test_textbox\n\n def test_element_array_colors(self):\n # Create element array with two elements covering the whole window in two block colours\n obj = visual.ElementArrayStim(self.win, units=\"pix\",\n fieldPos=(0, 0), fieldSize=(128, 128), fieldShape='square', nElements=2,\n sizes=[[64, 128], [64, 128]], xys=[[-32, 0], [32, 0]], elementMask=None, elementTex=None)\n # Iterate through color sets\n for colorSet in exemplars + tykes:\n for space in colorSet:\n if space not in colors.strSpaces and not isinstance(colorSet[space], (str, type(None))):\n # Check that setting color arrays renders correctly\n obj.colorSpace = space\n col1 = np.array(colorSet[space]).reshape((1, -1))\n col2 = getattr(colors.Color('black'), space).reshape((1, -1))\n obj.colors = np.append(col1, col2, 0) # Set first color to current color set, second to black in same color space\n obj.opacity = 1 # Fix opacity at full as this is not what we're testing\n self.win.flip()\n obj.draw()\n utils.comparePixelColor(self.win, colors.Color(colorSet[space], space), coord=(10, 10))\n utils.comparePixelColor(self.win, colors.Color('black'), coord=(10, 100))\n\n def test_visual_helper(self):\n # Create rectangle with chunky border\n obj = visual.Rect(self.win, units=\"pix\", pos=(0, 0), size=(128, 128), lineWidth=10)\n # Iterate through color sets\n for colorSet in exemplars + tykes:\n for space in colorSet:\n # Check border color\n visual.helpers.setColor(obj,\n color=colorSet[space], colorSpace=space,\n colorAttrib=\"borderColor\")\n obj.fillColor = 'white'\n obj.opacity = 1 # Fix opacity at full as this is not what we're testing\n self.win.flip()\n obj.draw()\n if colorSet[space]: # skip this comparison if color is None\n utils.comparePixelColor(self.win, colors.Color(colorSet[space], space), coord=(1, 1))\n utils.comparePixelColor(self.win, colors.Color('white'), coord=(50, 50))\n # Check fill color\n visual.helpers.setColor(obj,\n color=colorSet[space], colorSpace=space,\n colorAttrib=\"fillColor\")\n obj.borderColor = 'white'\n obj.opacity = 1 # Fix opacity at full as this is not what we're testing\n self.win.flip()\n obj.draw()\n if colorSet[space]: # skip this comparison if color is None\n utils.comparePixelColor(self.win, colors.Color(colorSet[space], space), coord=(50, 50))\n utils.comparePixelColor(self.win, colors.Color('white'), coord=(1, 1))\n # Check color addition\n obj.fillColor = 'white'\n visual.helpers.setColor(obj,\n color='black',\n colorAttrib='fillColor',\n operation='+')\n self.win.flip()\n obj.draw()\n utils.comparePixelColor(self.win, colors.Color('white') + colors.Color('black'), coord=(50, 50))\n # Check color subtraction\n obj.fillColor = 'grey'\n visual.helpers.setColor(obj,\n color='black',\n colorAttrib='fillColor',\n operation='-')\n self.win.flip()\n obj.draw()\n utils.comparePixelColor(self.win, colors.Color('grey') - colors.Color('black'), coord=(50, 50))\n\n # Check alerts\n visual.helpers.setColor(obj, color=\"white\", colorSpaceAttrib=\"fillColorSpace\", rgbAttrib=\"fillRGB\")\n assert any(err.code == 8105 for err in self.error.alerts), \"Alert 8105 not triggered\"\n assert any(err.code == 8110 for err in self.error.alerts), \"Alert 8110 not triggered\"\n\n def test_contrast(self):\n # Create rectangle with chunky border\n obj = visual.Rect(self.win, units=\"pix\", pos=(0, 0), size=(128, 128), lineWidth=10)\n # Set its colors to be rgb extremes\n obj.fillColor = 'red'\n obj.borderColor = 'blue'\n obj.opacity = 1 # Fix opacity at full as this is not what we're testing\n # Halve contrast\n obj.contrast = 0.5\n # Refresh\n self.win.flip()\n obj.draw()\n # Check rendered color\n utils.comparePixelColor(self.win, colors.Color(( 0.5, -0.5, -0.5), \"rgb\"), coord=(50, 50))\n utils.comparePixelColor(self.win, colors.Color((-0.5, -0.5, 0.5), \"rgb\"), coord=(1, 1))\n\n\ndef test_color_operators():\n \"\"\"Test for operators used to compare colors.\"\"\"\n red255 = colors.Color((255, 0, 0), space='rgb255')\n redRGB = colors.Color((1, -1, -1), space='rgb')\n redRGB1 = colors.Color((1, 0, 0), space='rgb1')\n\n assert (red255 == redRGB == redRGB1)\n",
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nThe most accurate way to time your stimulus presentation is to\npresent for a certain number of frames. For that to work you need\nyour window flips to synchronize to the monitor and not to drop\nany frames. This script examines the precision of your frame flips.\n\nShut down as many applications as possible, especially those that\nmight try to update\n\"\"\"\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom builtins import range\nfrom psychopy import visual, logging, core, event\nvisual.useFBO = True # if available (try without for comparison)\n\nimport matplotlib\nmatplotlib.use('Qt5Agg') # change this to control the plotting 'back end'\nimport pylab\n\nnIntervals = 500\nwin = visual.Window([1280, 1024], fullscr=True, allowGUI=False, waitBlanking=True)\nprogBar = visual.GratingStim(win, tex=None, mask=None,\n size=[0, 0.05], color='red', pos=[0, -0.9], autoLog=False)\nmyStim = visual.GratingStim(win, tex='sin', mask='gauss',\n size=300, sf=0.05, units='pix', autoLog=False)\n# logging.console.setLevel(logging.INFO)# uncomment to log every frame\n\nwin.recordFrameIntervals = True\nfor frameN in range(nIntervals + 1):\n progBar.setSize([2.0 * frameN/nIntervals, 0.05])\n progBar.draw()\n myStim.setPhase(0.1, '+')\n myStim.draw()\n if event.getKeys():\n print('stopped early')\n break\n win.logOnFlip(msg='frame=%i' %frameN, level=logging.EXP)\n win.flip()\nwin.fullscr = False\nwin.close()\n\n# calculate some values\nintervalsMS = pylab.array(win.frameIntervals) * 1000\nm = pylab.mean(intervalsMS)\nsd = pylab.std(intervalsMS)\n# se=sd/pylab.sqrt(len(intervalsMS)) # for CI of the mean\n\nmsg = \"Mean=%.1fms, s.d.=%.2f, 99%%CI(frame)=%.2f-%.2f\"\ndistString = msg % (m, sd, m - 2.58 * sd, m + 2.58 * sd)\nnTotal = len(intervalsMS)\nnDropped = sum(intervalsMS > (1.5 * m))\nmsg = \"Dropped/Frames = %i/%i = %.3f%%\"\ndroppedString = msg % (nDropped, nTotal, 100 * nDropped / float(nTotal))\n\n# plot the frameintervals\npylab.figure(figsize=[12, 8])\npylab.subplot(1, 2, 1)\npylab.plot(intervalsMS, '-')\npylab.ylabel('t (ms)')\npylab.xlabel('frame N')\npylab.title(droppedString)\n\npylab.subplot(1, 2, 2)\npylab.hist(intervalsMS, 50, histtype='stepfilled')\npylab.xlabel('t (ms)')\npylab.ylabel('n frames')\npylab.title(distString)\npylab.show()\n\nwin.close()\ncore.quit()\n\n# The contents of this file are in the public domain.\n",
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import, print_function\n\n# from future import standard_library\n# standard_library.install_aliases()\nfrom builtins import str\nfrom past.builtins import basestring\nfrom builtins import object\nimport weakref\nimport pickle\nimport os\nimport sys\nimport copy\nimport inspect\nimport codecs\nimport numpy as np\nimport pandas as pd\nimport json_tricks\nfrom pkg_resources import parse_version\n\nimport psychopy\nfrom psychopy import logging\nfrom psychopy.tools.filetools import (openOutputFile, genDelimiter,\n genFilenameFromDelimiter, pathToString)\nfrom psychopy.tools.fileerrortools import handleFileCollision\nfrom psychopy.tools.arraytools import extendArr\nfrom .utils import _getExcelCellName\n\ntry:\n import openpyxl\n if parse_version(openpyxl.__version__) >= parse_version('2.4.0'):\n # openpyxl moved get_column_letter to utils.cell\n from openpyxl.utils.cell import get_column_letter\n else:\n from openpyxl.cell import get_column_letter\n from openpyxl import load_workbook, Workbook\n haveOpenpyxl = True\nexcept ImportError:\n haveOpenpyxl = False\n\n_experiments = weakref.WeakValueDictionary()\n\n\nclass _ComparisonMixin(object):\n def __eq__(self, other):\n # NoneType and booleans, for example, don't have a .__dict__ attribute.\n try:\n getattr(other, '__dict__')\n except AttributeError:\n return False\n\n # Check if the dictionary keys are the same before proceeding.\n if set(self.__dict__.keys()) != set(other.__dict__.keys()):\n return False\n\n # Loop over all keys, implementing special handling for certain\n # data types.\n for key, val in self.__dict__.items():\n if isinstance(val, np.ma.core.MaskedArray):\n if not np.ma.allclose(val, getattr(other, key)):\n return False\n elif isinstance(val, np.ndarray):\n if not np.allclose(val, getattr(other, key)):\n return False\n elif isinstance(val, (pd.DataFrame, pd.Series)):\n if not val.equals(getattr(other, key)):\n return False\n else:\n if val != getattr(other, key):\n return False\n\n return True\n\n def __ne__(self, other):\n return not self == other\n\n\nclass _BaseTrialHandler(_ComparisonMixin):\n def setExp(self, exp):\n \"\"\"Sets the ExperimentHandler that this handler is attached to\n\n Do NOT attempt to set the experiment using::\n\n trials._exp = myExperiment\n\n because it needs to be performed using the `weakref` module.\n \"\"\"\n # need to use a weakref to avoid creating a circular reference that\n # prevents effective object deletion\n expId = id(exp)\n _experiments[expId] = exp\n self._exp = expId\n # origin will have been stored by the exp so don't store again:\n self.origin = None\n\n def getExp(self):\n \"\"\"Return the ExperimentHandler that this handler is attached to,\n if any. Returns None if not attached\n \"\"\"\n if self._exp is None or self._exp not in _experiments:\n return None\n else:\n return _experiments[self._exp]\n\n def _terminate(self):\n \"\"\"Remove references to ourself in experiments and terminate the loop\n \"\"\"\n # remove ourself from the list of unfinished loops in the experiment\n exp = self.getExp()\n if exp != None:\n exp.loopEnded(self)\n # and halt the loop\n raise StopIteration\n\n def saveAsPickle(self, fileName, fileCollisionMethod='rename'):\n \"\"\"Basically just saves a copy of the handler (with data) to a\n pickle file.\n\n This can be reloaded if necessary and further analyses carried out.\n\n :Parameters:\n\n fileCollisionMethod: Collision method passed to\n :func:`~psychopy.tools.fileerrortools.handleFileCollision`\n \"\"\"\n fileName = pathToString(fileName)\n\n if self.thisTrialN < 1 and self.thisRepN < 1:\n # if both are < 1 we haven't started\n if self.autoLog:\n logging.info('.saveAsPickle() called but no trials completed.'\n ' Nothing saved')\n return -1\n\n if not fileName.endswith('.psydat'):\n fileName += '.psydat'\n\n with openOutputFile(fileName=fileName, append=False,\n fileCollisionMethod=fileCollisionMethod) as f:\n pickle.dump(self, f)\n\n logging.info('saved data to %s' % f.name)\n\n def saveAsText(self, fileName,\n stimOut=None,\n dataOut=('n', 'all_mean', 'all_std', 'all_raw'),\n delim=None,\n matrixOnly=False,\n appendFile=True,\n summarised=True,\n fileCollisionMethod='rename',\n encoding='utf-8-sig'):\n \"\"\"\n Write a text file with the data and various chosen stimulus attributes\n\n :Parameters:\n\n fileName:\n will have .tsv appended and can include path info.\n\n stimOut:\n the stimulus attributes to be output. To use this you need to\n use a list of dictionaries and give here the names of dictionary\n keys that you want as strings\n\n dataOut:\n a list of strings specifying the dataType and the analysis to\n be performed,in the form `dataType_analysis`. The data can be\n any of the types that you added using trialHandler.data.add()\n and the analysis can be either 'raw' or most things in the\n numpy library, including; 'mean','std','median','max','min'...\n The default values will output the raw, mean and std of all\n datatypes found\n\n delim:\n allows the user to use a delimiter other than tab\n (\",\" is popular with file extension \".csv\")\n\n matrixOnly:\n outputs the data with no header row or extraInfo attached\n\n appendFile:\n will add this output to the end of the specified file if\n it already exists\n\n fileCollisionMethod:\n Collision method passed to\n :func:`~psychopy.tools.fileerrortools.handleFileCollision`\n\n encoding:\n The encoding to use when saving a the file. Defaults to `utf-8-sig`.\n\n \"\"\"\n fileName = pathToString(fileName)\n\n if stimOut is None:\n stimOut = []\n\n if self.thisTrialN < 1 and self.thisRepN < 1:\n # if both are < 1 we haven't started\n if self.autoLog:\n logging.info('TrialHandler.saveAsText called but no trials'\n ' completed. Nothing saved')\n return -1\n\n dataArray = self._createOutputArray(stimOut=stimOut,\n dataOut=dataOut,\n matrixOnly=matrixOnly)\n\n # set default delimiter if none given\n if delim is None:\n delim = genDelimiter(fileName)\n\n # create the file or send to stdout\n fileName = genFilenameFromDelimiter(fileName, delim)\n with openOutputFile(fileName=fileName, append=appendFile,\n fileCollisionMethod=fileCollisionMethod,\n encoding=encoding) as f:\n # loop through lines in the data matrix\n for line in dataArray:\n for cellN, entry in enumerate(line):\n # surround in quotes to prevent effect of delimiter\n if delim in str(entry):\n f.write(u'\"%s\"' % str(entry))\n else:\n f.write(str(entry))\n if cellN < (len(line) - 1):\n f.write(delim)\n f.write(\"\\n\") # add an EOL at end of each line\n\n if (fileName is not None) and (fileName != 'stdout') and self.autoLog:\n logging.info('saved data to %s' % f.name)\n\n def printAsText(self, stimOut=None,\n dataOut=('all_mean', 'all_std', 'all_raw'),\n delim='\\t',\n matrixOnly=False):\n \"\"\"Exactly like saveAsText() except that the output goes\n to the screen instead of a file\n \"\"\"\n if stimOut is None:\n stimOut = []\n self.saveAsText('stdout', stimOut, dataOut, delim, matrixOnly)\n\n def saveAsExcel(self, fileName, sheetName='rawData',\n stimOut=None,\n dataOut=('n', 'all_mean', 'all_std', 'all_raw'),\n matrixOnly=False,\n appendFile=True,\n fileCollisionMethod='rename'):\n \"\"\"\n Save a summary data file in Excel OpenXML format workbook\n (:term:`xlsx`) for processing in most spreadsheet packages.\n This format is compatible with versions of Excel (2007 or greater)\n and and with OpenOffice (>=3.0).\n\n It has the advantage over the simpler text files (see\n :func:`TrialHandler.saveAsText()` )\n that data can be stored in multiple named sheets within the file.\n So you could have a single file named after your experiment and\n then have one worksheet for each participant. Or you could have\n one file for each participant and then multiple sheets for\n repeated sessions etc.\n\n The file extension `.xlsx` will be added if not given already.\n\n :Parameters:\n\n fileName: string\n the name of the file to create or append. Can include\n relative or absolute path\n\n sheetName: string\n the name of the worksheet within the file\n\n stimOut: list of strings\n the attributes of the trial characteristics to be output.\n To use this you need to have provided a list of dictionaries\n specifying to trialList parameter of the TrialHandler and\n give here the names of strings specifying entries in that\n dictionary\n\n dataOut: list of strings\n specifying the dataType and the analysis to\n be performed, in the form `dataType_analysis`. The data\n can be any of the types that you added using\n trialHandler.data.add() and the analysis can be either\n 'raw' or most things in the numpy library, including\n 'mean','std','median','max','min'. e.g. `rt_max` will give\n a column of max reaction times across the trials assuming\n that `rt` values have been stored. The default values will\n output the raw, mean and std of all datatypes found.\n\n appendFile: True or False\n If False any existing file with this name will be\n kept and a new file will be created with a slightly different\n name. If you want to overwrite the old file, pass 'overwrite'\n to ``fileCollisionMethod``.\n If True then a new worksheet will be appended.\n If a worksheet already exists with that name a number will\n be added to make it unique.\n\n fileCollisionMethod: string\n Collision method (``rename``,``overwrite``, ``fail``) passed to\n :func:`~psychopy.tools.fileerrortools.handleFileCollision`\n This is ignored if ``append`` is ``True``.\n\n \"\"\"\n fileName = pathToString(fileName)\n\n if stimOut is None:\n stimOut = []\n\n if self.thisTrialN < 1 and self.thisRepN < 1:\n # if both are < 1 we haven't started\n if self.autoLog:\n logging.info('TrialHandler.saveAsExcel called but no '\n 'trials completed. Nothing saved')\n return -1\n\n # NB this was based on the limited documentation (1 page wiki) for\n # openpyxl v1.0\n if not haveOpenpyxl:\n raise ImportError('openpyxl is required for saving files in'\n ' Excel (xlsx) format, but was not found.')\n # return -1\n\n # create the data array to be sent to the Excel file\n dataArray = self._createOutputArray(stimOut=stimOut,\n dataOut=dataOut,\n matrixOnly=matrixOnly)\n\n if not fileName.endswith('.xlsx'):\n fileName += '.xlsx'\n # create or load the file\n if appendFile and os.path.isfile(fileName):\n wb = load_workbook(fileName)\n newWorkbook = False\n else:\n if not appendFile:\n # the file exists but we're not appending, a new file will\n # be saved with a slightly different name, unless \n # fileCollisionMethod = ``overwrite``\n fileName = handleFileCollision(fileName,\n fileCollisionMethod)\n wb = Workbook() # create new workbook\n wb.properties.creator = 'PsychoPy' + psychopy.__version__\n newWorkbook = True\n\n if newWorkbook:\n ws = wb.worksheets[0]\n ws.title = sheetName\n else:\n ws = wb.create_sheet()\n ws.title = sheetName\n\n # loop through lines in the data matrix\n for lineN, line in enumerate(dataArray):\n if line is None:\n continue\n for colN, entry in enumerate(line):\n if entry is None:\n entry = ''\n try:\n # if it can convert to a number (from numpy) then do it\n val = float(entry)\n except Exception:\n val = u\"{}\".format(entry)\n ws.cell(column=colN+1, row=lineN+1, value=val)\n\n wb.save(filename=fileName)\n\n def saveAsJson(self,\n fileName=None,\n encoding='utf-8-sig',\n fileCollisionMethod='rename'):\n \"\"\"\n Serialize the object to the JSON format.\n\n Parameters\n ----------\n fileName: string, or None\n the name of the file to create or append. Can include a relative or\n absolute path. If `None`, will not write to a file, but return an\n in-memory JSON object.\n\n encoding : string, optional\n The encoding to use when writing the file.\n\n fileCollisionMethod : string\n Collision method passed to\n :func:`~psychopy.tools.fileerrortools.handleFileCollision`. Can be\n either of `'rename'`, `'overwrite'`, or `'fail'`.\n\n Notes\n -----\n Currently, a copy of the object is created, and the copy's .origin\n attribute is set to an empty string before serializing\n because loading the created JSON file would sometimes fail otherwise.\n\n \"\"\"\n fileName = pathToString(fileName)\n\n self_copy = copy.deepcopy(self)\n self_copy.origin = ''\n msg = ('Setting attribute .origin to empty string during JSON '\n 'serialization.')\n logging.warn(msg)\n\n if (fileName is None) or (fileName == 'stdout'):\n return json_tricks.dumps(self_copy)\n else:\n with openOutputFile(fileName=fileName,\n fileCollisionMethod=fileCollisionMethod,\n encoding=encoding) as f:\n json_tricks.dump(self_copy, f)\n\n logging.info('Saved JSON data to %s' % f.name)\n\n def getOriginPathAndFile(self, originPath=None):\n \"\"\"Attempts to determine the path of the script that created this\n data file and returns both the path to that script and its contents.\n Useful to store the entire experiment with the data.\n\n If originPath is provided (e.g. from Builder) then this is used\n otherwise the calling script is the originPath (fine from a\n standard python script).\n \"\"\"\n # self.originPath and self.origin (the contents of the origin file)\n if originPath == -1:\n return -1, None # the user wants to avoid storing this\n elif originPath is None or not os.path.isfile(originPath):\n try:\n originPath = inspect.getouterframes(\n inspect.currentframe())[2][1]\n if self.autoLog:\n logging.debug(\"Using %s as origin file\" % originPath)\n except Exception:\n if self.autoLog:\n logging.debug(\"Failed to find origin file using \"\n \"inspect.getouterframes\")\n return '', ''\n if os.path.isfile(originPath): # do we NOW have a path?\n with codecs.open(originPath, \"r\", encoding=\"utf-8-sig\") as f:\n origin = f.read()\n else:\n origin = None\n return originPath, origin\n\n\nclass DataHandler(_ComparisonMixin, dict):\n \"\"\"For handling data (used by TrialHandler, principally, rather than\n by users directly)\n\n Numeric data are stored as numpy masked arrays where the mask is set\n True for missing entries. When any non-numeric data (string, list or\n array) get inserted using DataHandler.add(val) the array is converted\n to a standard (not masked) numpy array with dtype='O' and where missing\n entries have value = \"--\".\n\n Attributes:\n - ['key']=data arrays containing values for that key\n (e.g. data['accuracy']=...)\n - dataShape=shape of data (x,y,...z,nReps)\n - dataTypes=list of keys as strings\n\n \"\"\"\n def __init__(self, dataTypes=None, trials=None, dataShape=None):\n self.trials = trials\n self.dataTypes = [] # names will be added during addDataType\n self.isNumeric = {}\n # if given dataShape use it - otherwise guess!\n if dataShape:\n self.dataShape = dataShape\n elif self.trials:\n self.dataShape = list(np.asarray(trials.trialList, 'O').shape)\n self.dataShape.append(trials.nReps)\n\n # initialise arrays now if poss\n if dataTypes and self.dataShape:\n for thisType in dataTypes:\n self.addDataType(thisType)\n\n def __eq__(self, other):\n # We ignore an attached TrialHandler object, otherwise we will end up\n # in an infinite loop, as this DataHandler is attached to the\n # TrialHandler!\n\n from psychopy.data import TrialHandler\n\n if isinstance(self.trials, TrialHandler):\n self_copy = copy.deepcopy(self)\n other_copy = copy.deepcopy(other)\n del self_copy.trials, other_copy.trials\n result = super(DataHandler, self_copy).__eq__(other_copy)\n\n msg = ('TrialHandler object detected in .trials. Excluding it from '\n 'comparison.')\n logging.warning(msg)\n else:\n result = super(DataHandler, self).__eq__(other)\n\n return result\n\n def addDataType(self, names, shape=None):\n \"\"\"Add a new key to the data dictionary of particular shape if\n specified (otherwise the shape of the trial matrix in the trial\n handler. Data are initialised to be zero everywhere. Not needed\n by user: appropriate types will be added during initialisation\n and as each xtra type is needed.\n \"\"\"\n if not shape:\n shape = self.dataShape\n if not isinstance(names, basestring):\n # recursively call this function until we have a string\n for thisName in names:\n self.addDataType(thisName)\n else:\n # create the appropriate array in the dict\n # initially use numpy masked array of floats with mask=True\n # for missing vals. convert to a numpy array with dtype='O'\n # if non-numeric data given. NB don't use masked array with\n # dytpe='O' together - they don't unpickle\n self[names] = np.ma.zeros(shape, 'f') # masked array of floats\n self[names].mask = True\n # add the name to the list\n self.dataTypes.append(names)\n self.isNumeric[names] = True # until we need otherwise\n\n def add(self, thisType, value, position=None):\n \"\"\"Add data to an existing data type (and add a new one if necess)\n \"\"\"\n if not thisType in self:\n self.addDataType(thisType)\n if position is None:\n # 'ran' is always the first thing to update\n repN = sum(self['ran'][self.trials.thisIndex])\n if thisType != 'ran':\n # because it has already been updated\n repN -= 1\n # make a list where 1st digit is trial number\n position = [self.trials.thisIndex]\n position.append(repN)\n\n # check whether data falls within bounds\n posArr = np.asarray(position)\n shapeArr = np.asarray(self.dataShape)\n if not np.alltrue(posArr < shapeArr):\n # array isn't big enough\n logging.warning('need a bigger array for: ' + thisType)\n # not implemented yet!\n self[thisType] = extendArr(self[thisType], posArr)\n # check for ndarrays with more than one value and for non-numeric data\n if (self.isNumeric[thisType] and\n ((type(value) == np.ndarray and len(value) > 1) or\n (type(value) not in [float, int]))):\n self._convertToObjectArray(thisType)\n # insert the value\n self[thisType][position[0], int(position[1])] = value\n\n def _convertToObjectArray(self, thisType):\n \"\"\"Convert this datatype from masked numeric array to unmasked\n object array\n \"\"\"\n dat = self[thisType]\n # create an array of Object type\n self[thisType] = np.array(dat.data, dtype='O')\n # masked vals should be \"--\", others keep data\n # we have to repeat forcing to 'O' or text gets truncated to 4chars\n self[thisType] = np.where(dat.mask, '--', dat).astype('O')\n self.isNumeric[thisType] = False\n"
] | [
[
"numpy.array",
"numpy.floor"
],
[
"numpy.square",
"numpy.asarray",
"numpy.tile",
"numpy.atleast_2d",
"numpy.float32",
"numpy.sum",
"numpy.vstack"
],
[
"numpy.fft.fft2",
"numpy.array",
"numpy.log",
"numpy.fft.ifft2",
"numpy.multiply",
"numpy.clip",
"numpy.fft.fftshift",
"numpy.ones",
"numpy.tan",
"numpy.max",
"numpy.round",
"numpy.fft.ifftshift",
"numpy.random.shuffle",
"numpy.angle",
"numpy.exp"
],
[
"numpy.array"
],
[
"numpy.append",
"numpy.array"
],
[
"matplotlib.use"
],
[
"numpy.asarray",
"numpy.alltrue",
"numpy.ma.zeros",
"numpy.array",
"numpy.where"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lidija-jovanovska/HAMR-2020 | [
"795bb3c467fbcd7a26ca3a26ac26791e7cccb1ae"
] | [
"generate_progressions.py"
] | [
"import networkx as nx\r\nimport numpy as np\r\nfrom cdlib import algorithms\r\n\r\n\r\ndef random_walk(chord_graph, start_chord=None, progression_length=4):\r\n chord_path = []\r\n current_chord = start_chord\r\n\r\n if current_chord == None:\r\n pagerank = list(nx.get_node_attributes(chord_graph, \"pagerank\").values())\r\n pagerank = np.array(pagerank) / sum(pagerank) # normalizing pagerank values to get probability distr.\r\n current_chord = np.random.choice(a=list(chord_graph.nodes), p=pagerank)\r\n neighboring_chords = list(chord_graph.neighbors(current_chord))\r\n\r\n for chord_step in range(progression_length):\r\n chord_path.append(current_chord)\r\n weights = [chord_graph[current_chord][neighboring_chord]['weight']\r\n for neighboring_chord in list(neighboring_chords)]\r\n weights = np.array(weights) / sum(weights)\r\n current_chord = np.random.choice(a=neighboring_chords, p=weights)\r\n neighboring_chords = list(chord_graph.neighbors(current_chord))\r\n\r\n return chord_path\r\n\r\n\r\ndef smart_walk(chord_graph, start_chord=None, progression_length=4, out_threshold=0.85):\r\n communities = algorithms.louvain(chord_graph.to_undirected())\r\n chord_path = []\r\n visited_chords = []\r\n current_chord = start_chord\r\n \r\n if current_chord == None:\r\n pagerank = np.array(list(nx.get_node_attributes(chord_graph, \"pagerank\", ).values()))\r\n pagerank = np.array(pagerank) / sum(pagerank) # normalizing pagerank values to get probability distr.\r\n current_chord = np.random.choice(a=list(chord_graph.nodes), p=pagerank)\r\n\r\n for chord_step in range(progression_length):\r\n chord_path.append(current_chord)\r\n visited_chords.append(current_chord)\r\n neighboring_chords = list(chord_graph.neighbors(current_chord))\r\n probabilities = []\r\n possible_next_chords = []\r\n rand = np.random.uniform(0, 1)\r\n if rand < out_threshold:\r\n community_index = [True if current_chord in community else False for community in\r\n communities.communities].index(True)\r\n possible_next_chords = [chord for chord in neighboring_chords\r\n if chord in communities.communities[community_index]]\r\n if len(possible_next_chords) == 0:\r\n possible_next_chords = neighboring_chords\r\n else:\r\n possible_next_chords = neighboring_chords + visited_chords\r\n\r\n for chord in possible_next_chords:\r\n probabilities.append(int(chord_graph.in_degree(chord, weight='weight')))\r\n\r\n probabilities = np.array(probabilities) / sum(probabilities)\r\n current_chord = np.random.choice(possible_next_chords, p=probabilities)\r\n\r\n return chord_path"
] | [
[
"numpy.random.uniform",
"numpy.array",
"numpy.random.choice"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sfiligoi/scikit-bio | [
"e5f18fa33c8e834283de85faac30836793ebefd7"
] | [
"skbio/stats/distance/_base.py"
] | [
"# ----------------------------------------------------------------------------\n# Copyright (c) 2013--, scikit-bio development team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n# ----------------------------------------------------------------------------\n\nimport itertools\nfrom copy import deepcopy\n\nfrom IPython.core.pylabtools import print_figure\nfrom IPython.core.display import Image, SVG\nimport numpy as np\nimport pandas as pd\nfrom scipy.spatial.distance import squareform\n\nfrom skbio._base import SkbioObject\nfrom skbio.stats._misc import _pprint_strs\nfrom skbio.util import find_duplicates\nfrom skbio.util._decorator import experimental, classonlymethod\nfrom skbio.util._misc import resolve_key\n\nfrom ._utils import is_symmetric_and_hollow\nfrom ._utils import distmat_reorder, distmat_reorder_condensed\n\n\nclass DissimilarityMatrixError(Exception):\n \"\"\"General error for dissimilarity matrix validation failures.\"\"\"\n pass\n\n\nclass DistanceMatrixError(DissimilarityMatrixError):\n \"\"\"General error for distance matrix validation failures.\"\"\"\n pass\n\n\nclass MissingIDError(DissimilarityMatrixError):\n \"\"\"Error for ID lookup that doesn't exist in the dissimilarity matrix.\"\"\"\n\n def __init__(self, missing_id):\n super(MissingIDError, self).__init__()\n self.args = (\"The ID '%s' is not in the dissimilarity matrix.\" %\n missing_id,)\n\n\nclass DissimilarityMatrix(SkbioObject):\n \"\"\"Store dissimilarities between objects.\n\n A `DissimilarityMatrix` instance stores a square, hollow, two-dimensional\n matrix of dissimilarities between objects. Objects could be, for example,\n samples or DNA sequences. A sequence of IDs accompanies the\n dissimilarities.\n\n Methods are provided to load and save dissimilarity matrices from/to disk,\n as well as perform common operations such as extracting dissimilarities\n based on object ID.\n\n Parameters\n ----------\n data : array_like or DissimilarityMatrix\n Square, hollow, two-dimensional ``numpy.ndarray`` of dissimilarities\n (floats), or a structure that can be converted to a ``numpy.ndarray``\n using ``numpy.asarray`` or a one-dimensional vector of dissimilarities\n (floats), as defined by `scipy.spatial.distance.squareform`. Can\n instead be a `DissimilarityMatrix` (or subclass) instance,\n in which case the instance's data will be used.\n Data will be converted to a float ``dtype`` if necessary. A copy will\n *not* be made if already a ``numpy.ndarray`` with a float ``dtype``.\n ids : sequence of str, optional\n Sequence of strings to be used as object IDs. Must match the number of\n rows/cols in `data`. If ``None`` (the default), IDs will be\n monotonically-increasing integers cast as strings, with numbering\n starting from zero, e.g., ``('0', '1', '2', '3', ...)``.\n validate : bool, optional\n If `validate` is ``True`` (the default) and data is not a\n DissimilarityMatrix object, the input data will be validated.\n\n See Also\n --------\n DistanceMatrix\n scipy.spatial.distance.squareform\n\n Notes\n -----\n The dissimilarities are stored in redundant (square-form) format [1]_.\n\n The data are not checked for symmetry, nor guaranteed/assumed to be\n symmetric.\n\n References\n ----------\n .. [1] http://docs.scipy.org/doc/scipy/reference/spatial.distance.html\n\n \"\"\"\n default_write_format = 'lsmat'\n # Used in __str__\n _matrix_element_name = 'dissimilarity'\n\n @experimental(as_of=\"0.4.0\")\n def __init__(self, data, ids=None, validate=True):\n validate_full = validate\n validate_shape = False\n validate_ids = False\n\n if isinstance(data, DissimilarityMatrix):\n if isinstance(data, self.__class__):\n # Never validate when copying from an object\n # of the same type\n # We should be able to assume it is already\n # in a good state.\n validate_full = False\n validate_shape = False\n # but do validate ids, if redefining them\n validate_ids = False if ids is None else True\n ids = data.ids if ids is None else ids\n data = data.data\n\n # It is necessary to standardize the representation of the .data\n # attribute of this object. The input types might be list, tuple,\n # np.array, or possibly some other object type. Generally, this\n # normalization of type will require a copy of data. For example,\n # moving from a Python type representation (e.g., [[0, 1], [1, 0]])\n # requires casting all of the values to numpy types, which is handled\n # as an implicit copy via np.asarray. However, these copies are\n # unnecessary if the data object is already a numpy array. np.asarray\n # is smart enough to not copy the data, however if a dtype change is\n # requested it will. The following block of code limits the use of\n # np.asarray to situations where the data are (a) not already a numpy\n # array or (b) the data are not a single or double precision numpy\n # data type.\n _issue_copy = True\n if isinstance(data, np.ndarray):\n if data.dtype in (np.float32, np.float64):\n _issue_copy = False\n\n if _issue_copy:\n data = np.asarray(data, dtype='float')\n\n if data.ndim == 1:\n # We can assume squareform will return a symmetric square matrix\n # so no need for full validation.\n # Still do basic checks (e.g. zero length)\n # and id validation\n data = squareform(data, force='tomatrix', checks=False)\n validate_full = False\n validate_shape = True\n validate_ids = True\n\n if ids is None:\n ids = (str(i) for i in range(data.shape[0]))\n # I just created the ids, so no need to re-validate them\n validate_ids = False\n ids = tuple(ids)\n\n if validate_full:\n self._validate(data, ids)\n else:\n if validate_shape:\n self._validate_shape(data)\n if validate_ids:\n self._validate_ids(data, ids)\n\n self._data = data\n self._ids = ids\n self._id_index = self._index_list(self._ids)\n\n @classonlymethod\n @experimental(as_of=\"0.5.1\")\n def from_iterable(cls, iterable, metric, key=None, keys=None):\n \"\"\"Create DissimilarityMatrix from an iterable given a metric.\n\n Parameters\n ----------\n iterable : iterable\n Iterable containing objects to compute pairwise dissimilarities on.\n metric : callable\n A function that takes two arguments and returns a float\n representing the dissimilarity between the two arguments.\n key : callable or metadata key, optional\n A function that takes one argument and returns a string\n representing the id of the element in the dissimilarity matrix.\n Alternatively, a key to a `metadata` property if it exists for\n each element in the `iterable`. If None, then default ids will be\n used.\n keys : iterable, optional\n An iterable of the same length as `iterable`. Each element will be\n used as the respective key.\n\n Returns\n -------\n DissimilarityMatrix\n The `metric` applied to all pairwise elements in the `iterable`.\n\n Raises\n ------\n ValueError\n If `key` and `keys` are both provided.\n\n \"\"\"\n iterable = list(iterable)\n if key is not None and keys is not None:\n raise ValueError(\"Cannot use both `key` and `keys` at the same\"\n \" time.\")\n\n keys_ = None\n if key is not None:\n keys_ = [resolve_key(e, key) for e in iterable]\n elif keys is not None:\n keys_ = keys\n\n dm = np.empty((len(iterable),) * 2)\n for i, a in enumerate(iterable):\n for j, b in enumerate(iterable):\n dm[i, j] = metric(a, b)\n\n return cls(dm, keys_)\n\n @property\n @experimental(as_of=\"0.4.0\")\n def data(self):\n \"\"\"Array of dissimilarities.\n\n A square, hollow, two-dimensional ``numpy.ndarray`` of dissimilarities\n (floats). A copy is *not* returned.\n\n Notes\n -----\n This property is not writeable.\n\n \"\"\"\n return self._data\n\n @property\n @experimental(as_of=\"0.4.0\")\n def ids(self):\n \"\"\"Tuple of object IDs.\n\n A tuple of strings, one for each object in the dissimilarity matrix.\n\n Notes\n -----\n This property is writeable, but the number of new IDs must match the\n number of objects in `data`.\n\n \"\"\"\n return self._ids\n\n @ids.setter\n def ids(self, ids_):\n ids_ = tuple(ids_)\n self._validate_ids(self.data, ids_)\n self._ids = ids_\n self._id_index = self._index_list(self._ids)\n\n @property\n @experimental(as_of=\"0.4.0\")\n def dtype(self):\n \"\"\"Data type of the dissimilarities.\"\"\"\n return self.data.dtype\n\n @property\n @experimental(as_of=\"0.4.0\")\n def shape(self):\n \"\"\"Two-element tuple containing the dissimilarity matrix dimensions.\n\n Notes\n -----\n As the dissimilarity matrix is guaranteed to be square, both tuple\n entries will always be equal.\n\n \"\"\"\n return self.data.shape\n\n @property\n @experimental(as_of=\"0.4.0\")\n def size(self):\n \"\"\"Total number of elements in the dissimilarity matrix.\n\n Notes\n -----\n Equivalent to ``self.shape[0] * self.shape[1]``.\n\n \"\"\"\n return self.data.size\n\n @property\n @experimental(as_of=\"0.4.0\")\n def T(self):\n \"\"\"Transpose of the dissimilarity matrix.\n\n See Also\n --------\n transpose\n\n \"\"\"\n return self.transpose()\n\n @experimental(as_of=\"0.4.0\")\n def transpose(self):\n \"\"\"Return the transpose of the dissimilarity matrix.\n\n Notes\n -----\n A deep copy is returned.\n\n Returns\n -------\n DissimilarityMatrix\n Transpose of the dissimilarity matrix. Will be the same type as\n `self`.\n\n \"\"\"\n # Note: Skip validation, since we assume self was already validated\n return self.__class__(self.data.T.copy(),\n deepcopy(self.ids),\n validate=False)\n\n @experimental(as_of=\"0.4.0\")\n def index(self, lookup_id):\n \"\"\"Return the index of the specified ID.\n\n Parameters\n ----------\n lookup_id : str\n ID whose index will be returned.\n\n Returns\n -------\n int\n Row/column index of `lookup_id`.\n\n Raises\n ------\n MissingIDError\n If `lookup_id` is not in the dissimilarity matrix.\n\n \"\"\"\n if lookup_id in self:\n return self._id_index[lookup_id]\n else:\n raise MissingIDError(lookup_id)\n\n @experimental(as_of=\"0.4.0\")\n def redundant_form(self):\n \"\"\"Return an array of dissimilarities in redundant format.\n\n As this is the native format that the dissimilarities are stored in,\n this is simply an alias for `data`.\n\n Returns\n -------\n ndarray\n Two-dimensional ``numpy.ndarray`` of dissimilarities in redundant\n format.\n\n Notes\n -----\n Redundant format is described in [1]_.\n\n Does *not* return a copy of the data.\n\n References\n ----------\n .. [1] http://docs.scipy.org/doc/scipy/reference/spatial.distance.html\n\n \"\"\"\n return self.data\n\n @experimental(as_of=\"0.4.0\")\n def copy(self):\n \"\"\"Return a deep copy of the dissimilarity matrix.\n\n Returns\n -------\n DissimilarityMatrix\n Deep copy of the dissimilarity matrix. Will be the same type as\n `self`.\n\n \"\"\"\n # We deepcopy IDs in case the tuple contains mutable objects at some\n # point in the future.\n # Note: Skip validation, since we assume self was already validated\n return self.__class__(self.data.copy(),\n deepcopy(self.ids),\n validate=False)\n\n @experimental(as_of=\"0.4.0\")\n def filter(self, ids, strict=True):\n \"\"\"Filter the dissimilarity matrix by IDs.\n\n Parameters\n ----------\n ids : iterable of str\n IDs to retain. May not contain duplicates or be empty. Each ID must\n be present in the dissimilarity matrix.\n strict : bool, optional\n If `strict` is ``True`` and an ID that is not found in the distance\n matrix is found in `ids`, a ``MissingIDError`` exception will be\n raised, otherwise the ID will be ignored.\n\n Returns\n -------\n DissimilarityMatrix\n Filtered dissimilarity matrix containing only the IDs specified in\n `ids`. IDs will be in the same order as they appear in `ids`.\n\n Raises\n ------\n MissingIDError\n If an ID in `ids` is not in the object's list of IDs.\n \"\"\"\n if tuple(self._ids) == tuple(ids):\n return self.__class__(self._data, self._ids)\n\n if strict:\n idxs = [self.index(id_) for id_ in ids]\n else:\n # get the indices to slice the inner numpy array\n idxs = []\n # save the IDs that were found in the distance matrix\n found_ids = []\n for id_ in ids:\n try:\n idxs.append(self.index(id_))\n found_ids.append(id_)\n except MissingIDError:\n pass\n ids = found_ids\n\n # Note: Skip validation, since we assume self was already validated\n # But ids are new, so validate them explicitly\n filtered_data = distmat_reorder(self._data, idxs)\n self._validate_ids(filtered_data, ids)\n return self.__class__(filtered_data, ids, validate=False)\n\n def _stable_order(self, ids):\n \"\"\"Obtain a stable ID order with respect to self\n\n Parameters\n ----------\n ids : Iterable of ids\n The IDs to establish a stable ordering for.\n\n Returns\n -------\n np.array, dtype=int\n The corresponding index values\n \"\"\"\n id_order = sorted(self._id_index[i] for i in ids)\n return np.array(id_order, dtype=int)\n\n @experimental(as_of=\"0.5.5\")\n def within(self, ids):\n \"\"\"Obtain all the distances among the set of IDs\n\n Parameters\n ----------\n ids : Iterable of str\n The IDs to obtain distances for. All pairs of distances are\n returned such that, if provided ['a', 'b', 'c'], the distances\n for [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'),\n ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')] are gathered.\n\n Returns\n -------\n pd.DataFrame\n (i, j, value) representing the source ID (\"i\"), the target ID (\"j\")\n and the distance (\"value\").\n\n Raises\n ------\n MissingIDError\n If an ID(s) specified is not in the dissimilarity matrix.\n\n Notes\n -----\n Order of the return items is stable, meaning that requesting IDs\n ['a', 'b'] is equivalent to ['b', 'a']. The order is with respect\n to the order of the .ids attribute of self.\n\n Example\n -------\n >>> from skbio.stats.distance import DissimilarityMatrix\n >>> dm = DissimilarityMatrix([[0, 1, 2, 3, 4], [1, 0, 1, 2, 3],\n ... [2, 1, 0, 1, 2], [3, 2, 1, 0, 1],\n ... [4, 3, 2, 1, 0]],\n ... ['A', 'B', 'C', 'D', 'E'])\n >>> dm.within(['A', 'B', 'C'])\n i j value\n 0 A A 0.0\n 1 A B 1.0\n 2 A C 2.0\n 3 B A 1.0\n 4 B B 0.0\n 5 B C 1.0\n 6 C A 2.0\n 7 C B 1.0\n 8 C C 0.0\n \"\"\"\n ids = set(ids)\n not_present = ids - set(self._id_index)\n if not_present:\n raise MissingIDError(\"At least one ID (e.g., '%s') was not \"\n \"found.\" % not_present.pop())\n\n return self._subset_to_dataframe(ids, ids)\n\n @experimental(as_of=\"0.5.5\")\n def between(self, from_, to_, allow_overlap=False):\n \"\"\"Obtain the distances between the two groups of IDs\n\n Parameters\n ----------\n from_ : Iterable of str\n The IDs to obtain distances from. Distances from all pairs of IDs\n in from and to will be obtained.\n to_ : Iterable of str\n The IDs to obtain distances to. Distances from all pairs of IDs\n in to and from will be obtained.\n\n allow_overlap : bool, optional\n If True, allow overlap in the IDs of from and to (which would in\n effect be collecting the within distances). Default is False.\n\n Returns\n -------\n pd.DataFrame\n (i, j, value) representing the source ID (\"i\"), the target ID (\"j\")\n and the distance (\"value\").\n\n Raises\n ------\n MissingIDError\n If an ID(s) specified is not in the dissimilarity matrix.\n\n Notes\n -----\n Order of the return items is stable, meaning that requesting IDs\n ['a', 'b'] is equivalent to ['b', 'a']. The order is with respect to\n the .ids attribute of self.\n\n Example\n -------\n >>> from skbio.stats.distance import DissimilarityMatrix\n >>> dm = DissimilarityMatrix([[0, 1, 2, 3, 4], [1, 0, 1, 2, 3],\n ... [2, 1, 0, 1, 2], [3, 2, 1, 0, 1],\n ... [4, 3, 2, 1, 0]],\n ... ['A', 'B', 'C', 'D', 'E'])\n >>> dm.between(['A', 'B'], ['C', 'D', 'E'])\n i j value\n 0 A C 2.0\n 1 A D 3.0\n 2 A E 4.0\n 3 B C 1.0\n 4 B D 2.0\n 5 B E 3.0\n \"\"\"\n from_ = set(from_)\n to_ = set(to_)\n\n all_ids = from_ | to_\n not_present = all_ids - set(self._id_index)\n if not_present:\n raise MissingIDError(\"At least one ID (e.g., '%s') was not \"\n \"found.\" % not_present.pop())\n\n overlapping = from_ & to_\n if not allow_overlap and overlapping:\n raise KeyError(\"At least one ID overlaps in from_ and to_ \"\n \"(e.g., '%s'). This constraint can removed with \"\n \"allow_overlap=True.\" % overlapping.pop())\n\n return self._subset_to_dataframe(from_, to_)\n\n def _subset_to_dataframe(self, i_ids, j_ids):\n \"\"\"Extract a subset of self and express as a DataFrame\n\n Parameters\n ----------\n i_order : Iterable of str\n The \"from\" IDs.\n j_order : Iterable of str\n The \"to\" IDs.\n\n Notes\n -----\n ID membership is not tested by this private method, and it is assumed\n the caller has asserted the IDs are present.\n\n Returns\n -------\n pd.DataFrame\n (i, j, value) representing the source ID (\"i\"), the target ID (\"j\")\n and the distance (\"value\").\n \"\"\"\n i_indices = self._stable_order(i_ids)\n j_indices = self._stable_order(j_ids)\n\n j_length = len(j_indices)\n j_labels = tuple([self.ids[j] for j in j_indices])\n\n i = []\n j = []\n\n # np.hstack([]) throws a ValueError. However, np.hstack([np.array([])])\n # is valid and returns an empty array. Accordingly, an empty array is\n # included here so that np.hstack works in the event that either i_ids\n # or j_ids is empty.\n values = [np.array([])]\n for i_idx in i_indices:\n i.extend([self.ids[i_idx]] * j_length)\n j.extend(j_labels)\n\n subset = self._data[i_idx, j_indices]\n values.append(subset)\n\n i = pd.Series(i, name='i')\n j = pd.Series(j, name='j')\n values = pd.Series(np.hstack(values), name='value')\n\n return pd.concat([i, j, values], axis=1)\n\n @experimental(as_of=\"0.4.0\")\n def plot(self, cmap=None, title=\"\"):\n \"\"\"Creates a heatmap of the dissimilarity matrix\n\n Parameters\n ----------\n cmap: str or matplotlib.colors.Colormap, optional\n Sets the color scheme of the heatmap\n If ``None``, defaults to the colormap specified in the matplotlib\n rc file.\n\n title: str, optional\n Sets the title label of the heatmap\n (Default is blank)\n\n Returns\n -------\n matplotlib.figure.Figure\n Figure containing the heatmap and colorbar of the plotted\n dissimilarity matrix.\n\n Examples\n --------\n .. plot::\n\n Define a dissimilarity matrix with five objects labeled A-E:\n\n >>> from skbio.stats.distance import DissimilarityMatrix\n >>> dm = DissimilarityMatrix([[0, 1, 2, 3, 4], [1, 0, 1, 2, 3],\n ... [2, 1, 0, 1, 2], [3, 2, 1, 0, 1],\n ... [4, 3, 2, 1, 0]],\n ... ['A', 'B', 'C', 'D', 'E'])\n\n Plot the dissimilarity matrix as a heatmap:\n\n >>> fig = dm.plot(cmap='Reds', title='Example heatmap')\n\n \"\"\"\n import matplotlib.pyplot as plt\n # based on http://stackoverflow.com/q/14391959/3776794\n fig, ax = plt.subplots()\n\n # use pcolormesh instead of pcolor for performance\n heatmap = ax.pcolormesh(self.data, cmap=cmap)\n fig.colorbar(heatmap)\n\n # center labels within each cell\n ticks = np.arange(0.5, self.shape[0])\n ax.set_xticks(ticks, minor=False)\n ax.set_yticks(ticks, minor=False)\n\n # Ensure there is no white border around the heatmap by manually\n # setting the limits\n ax.set_ylim(0, len(self.ids))\n ax.set_xlim(0, len(self.ids))\n\n # display data as it is stored in the dissimilarity matrix\n # (default is to have y-axis inverted)\n ax.invert_yaxis()\n\n ax.set_xticklabels(self.ids, rotation=90, minor=False)\n ax.set_yticklabels(self.ids, minor=False)\n\n ax.set_title(title)\n\n return fig\n\n def _repr_png_(self):\n return self._figure_data('png')\n\n def _repr_svg_(self):\n return self._figure_data('svg')\n\n @property\n @experimental(as_of=\"0.4.0\")\n def png(self):\n \"\"\"Display heatmap in IPython Notebook as PNG.\n\n \"\"\"\n return Image(self._repr_png_(), embed=True)\n\n @property\n @experimental(as_of=\"0.4.0\")\n def svg(self):\n \"\"\"Display heatmap in IPython Notebook as SVG.\n\n \"\"\"\n return SVG(self._repr_svg_())\n\n def _figure_data(self, format):\n import matplotlib.pyplot as plt\n fig = self.plot()\n data = print_figure(fig, format)\n # We MUST close the figure, otherwise IPython's display machinery\n # will pick it up and send it as output, resulting in a double display\n plt.close(fig)\n return data\n\n @experimental(as_of=\"0.4.1\")\n def to_data_frame(self):\n \"\"\"Create a ``pandas.DataFrame`` from this ``DissimilarityMatrix``.\n\n Returns\n -------\n pd.DataFrame\n ``pd.DataFrame`` with IDs on index and columns.\n\n Examples\n --------\n >>> from skbio import DistanceMatrix\n >>> dm = DistanceMatrix([[0, 1, 2],\n ... [1, 0, 3],\n ... [2, 3, 0]], ids=['a', 'b', 'c'])\n >>> df = dm.to_data_frame()\n >>> df\n a b c\n a 0.0 1.0 2.0\n b 1.0 0.0 3.0\n c 2.0 3.0 0.0\n\n \"\"\"\n return pd.DataFrame(data=self.data, index=self.ids, columns=self.ids)\n\n @experimental(as_of=\"0.4.0\")\n def __str__(self):\n \"\"\"Return a string representation of the dissimilarity matrix.\n\n Summary includes matrix dimensions, a (truncated) list of IDs, and\n (truncated) array of dissimilarities.\n\n Returns\n -------\n str\n String representation of the dissimilarity matrix.\n\n \"\"\"\n return '%dx%d %s matrix\\nIDs:\\n%s\\nData:\\n' % (\n self.shape[0], self.shape[1], self._matrix_element_name,\n _pprint_strs(self.ids)) + str(self.data)\n\n @experimental(as_of=\"0.4.0\")\n def __eq__(self, other):\n \"\"\"Compare this dissimilarity matrix to another for equality.\n\n Two dissimilarity matrices are equal if they have the same shape, IDs\n (in the same order!), and have data arrays that are equal.\n\n Checks are *not* performed to ensure that `other` is a\n `DissimilarityMatrix` instance.\n\n Parameters\n ----------\n other : DissimilarityMatrix\n Dissimilarity matrix to compare to for equality.\n\n Returns\n -------\n bool\n ``True`` if `self` is equal to `other`, ``False`` otherwise.\n\n \"\"\"\n equal = True\n\n # The order these checks are performed in is important to be as\n # efficient as possible. The check for shape equality is not strictly\n # necessary as it should be taken care of in np.array_equal, but I'd\n # rather explicitly bail before comparing IDs or data. Use array_equal\n # instead of (a == b).all() because of this issue:\n # http://stackoverflow.com/a/10582030\n try:\n if self.shape != other.shape:\n equal = False\n elif self.ids != other.ids:\n equal = False\n elif not np.array_equal(self.data, other.data):\n equal = False\n except AttributeError:\n equal = False\n\n return equal\n\n @experimental(as_of=\"0.4.0\")\n def __ne__(self, other):\n \"\"\"Determine whether two dissimilarity matrices are not equal.\n\n Parameters\n ----------\n other : DissimilarityMatrix\n Dissimilarity matrix to compare to.\n\n Returns\n -------\n bool\n ``True`` if `self` is not equal to `other`, ``False`` otherwise.\n\n See Also\n --------\n __eq__\n\n \"\"\"\n return not self == other\n\n @experimental(as_of=\"0.4.0\")\n def __contains__(self, lookup_id):\n \"\"\"Check if the specified ID is in the dissimilarity matrix.\n\n Parameters\n ----------\n lookup_id : str\n ID to search for.\n\n Returns\n -------\n bool\n ``True`` if `lookup_id` is in the dissimilarity matrix, ``False``\n otherwise.\n\n See Also\n --------\n index\n\n \"\"\"\n return lookup_id in self._id_index\n\n @experimental(as_of=\"0.4.0\")\n def __getitem__(self, index):\n \"\"\"Slice into dissimilarity data by object ID or numpy indexing.\n\n Extracts data from the dissimilarity matrix by object ID, a pair of\n IDs, or numpy indexing/slicing.\n\n Parameters\n ----------\n index : str, two-tuple of str, or numpy index\n `index` can be one of the following forms: an ID, a pair of IDs, or\n a numpy index.\n\n If `index` is a string, it is assumed to be an ID and a\n ``numpy.ndarray`` row vector is returned for the corresponding ID.\n Note that the ID's row of dissimilarities is returned, *not* its\n column. If the matrix is symmetric, the two will be identical, but\n this makes a difference if the matrix is asymmetric.\n\n If `index` is a two-tuple of strings, each string is assumed to be\n an ID and the corresponding matrix element is returned that\n represents the dissimilarity between the two IDs. Note that the\n order of lookup by ID pair matters if the matrix is asymmetric: the\n first ID will be used to look up the row, and the second ID will be\n used to look up the column. Thus, ``dm['a', 'b']`` may not be the\n same as ``dm['b', 'a']`` if the matrix is asymmetric.\n\n Otherwise, `index` will be passed through to\n ``DissimilarityMatrix.data.__getitem__``, allowing for standard\n indexing of a ``numpy.ndarray`` (e.g., slicing).\n\n Returns\n -------\n ndarray or scalar\n Indexed data, where return type depends on the form of `index` (see\n description of `index` for more details).\n\n Raises\n ------\n MissingIDError\n If the ID(s) specified in `index` are not in the dissimilarity\n matrix.\n\n Notes\n -----\n The lookup based on ID(s) is quick.\n\n \"\"\"\n if isinstance(index, str):\n return self.data[self.index(index)]\n elif self._is_id_pair(index):\n return self.data[self.index(index[0]), self.index(index[1])]\n else:\n return self.data.__getitem__(index)\n\n def _validate_ids(self, data, ids):\n \"\"\"Validate the IDs.\n\n Checks that IDs are unique and that the\n number of IDs matches the number of rows/cols in the data array.\n\n Subclasses can override this method to perform different/more specific\n validation.\n\n Notes\n -----\n Accepts arguments instead of inspecting instance attributes to avoid\n creating an invalid dissimilarity matrix before raising an error.\n Otherwise, the invalid dissimilarity matrix could be used after the\n exception is caught and handled.\n\n \"\"\"\n duplicates = find_duplicates(ids)\n if duplicates:\n formatted_duplicates = ', '.join(repr(e) for e in duplicates)\n raise DissimilarityMatrixError(\"IDs must be unique. Found the \"\n \"following duplicate IDs: %s\" %\n formatted_duplicates)\n if 0 == len(ids):\n raise DissimilarityMatrixError(\"IDs must be at least 1 in \"\n \"size.\")\n if len(ids) != data.shape[0]:\n raise DissimilarityMatrixError(\"The number of IDs (%d) must match \"\n \"the number of rows/columns in the \"\n \"data (%d).\" %\n (len(ids), data.shape[0]))\n\n def _validate_shape(self, data):\n \"\"\"Validate the data array shape.\n\n Checks that the data is at least 1x1 in size, 2D, square, and\n contains only floats.\n\n Notes\n -----\n Accepts arguments instead of inspecting instance attributes to avoid\n creating an invalid dissimilarity matrix before raising an error.\n Otherwise, the invalid dissimilarity matrix could be used after the\n exception is caught and handled.\n\n \"\"\"\n if 0 in data.shape:\n raise DissimilarityMatrixError(\"Data must be at least 1x1 in \"\n \"size.\")\n if len(data.shape) != 2:\n raise DissimilarityMatrixError(\"Data must have exactly two \"\n \"dimensions.\")\n if data.shape[0] != data.shape[1]:\n raise DissimilarityMatrixError(\"Data must be square (i.e., have \"\n \"the same number of rows and \"\n \"columns).\")\n if data.dtype not in (np.float32, np.float64):\n raise DissimilarityMatrixError(\"Data must contain only floating \"\n \"point values.\")\n\n def _validate(self, data, ids):\n \"\"\"Validate the data array and IDs.\n\n Checks that the data is at least 1x1 in size, 2D, square, and\n contains only floats. Also checks that IDs are unique and that the\n number of IDs matches the number of rows/cols in the data array.\n\n Subclasses can override this method to perform different/more specific\n validation (e.g., see `DistanceMatrix`).\n\n Notes\n -----\n Accepts arguments instead of inspecting instance attributes to avoid\n creating an invalid dissimilarity matrix before raising an error.\n Otherwise, the invalid dissimilarity matrix could be used after the\n exception is caught and handled.\n\n \"\"\"\n self._validate_shape(data)\n self._validate_ids(data, ids)\n\n def _index_list(self, list_):\n return {id_: idx for idx, id_ in enumerate(list_)}\n\n def _is_id_pair(self, index):\n return (isinstance(index, tuple) and\n len(index) == 2 and\n all(map(lambda e: isinstance(e, str), index)))\n\n\nclass DistanceMatrix(DissimilarityMatrix):\n \"\"\"Store distances between objects.\n\n A `DistanceMatrix` is a `DissimilarityMatrix` with the additional\n requirement that the matrix data is symmetric. There are additional methods\n made available that take advantage of this symmetry.\n\n See Also\n --------\n DissimilarityMatrix\n\n Notes\n -----\n The distances are stored in redundant (square-form) format [1]_. To\n facilitate use with other scientific Python routines (e.g., scipy), the\n distances can be retrieved in condensed (vector-form) format using\n `condensed_form`.\n\n `DistanceMatrix` only requires that the distances it stores are symmetric.\n Checks are *not* performed to ensure the other three metric properties\n hold (non-negativity, identity of indiscernibles, and triangle inequality)\n [2]_. Thus, a `DistanceMatrix` instance can store distances that are not\n metric.\n\n References\n ----------\n .. [1] http://docs.scipy.org/doc/scipy/reference/spatial.distance.html\n .. [2] http://planetmath.org/metricspace\n\n \"\"\"\n\n # Override here, used in superclass __str__\n _matrix_element_name = 'distance'\n\n @classonlymethod\n @experimental(as_of=\"0.4.1\")\n def from_iterable(cls, iterable, metric, key=None, keys=None,\n validate=True):\n \"\"\"Create DistanceMatrix from all pairs in an iterable given a metric.\n\n Parameters\n ----------\n iterable : iterable\n Iterable containing objects to compute pairwise distances on.\n metric : callable\n A function that takes two arguments and returns a float\n representing the distance between the two arguments.\n key : callable or metadata key, optional\n A function that takes one argument and returns a string\n representing the id of the element in the distance matrix.\n Alternatively, a key to a `metadata` property if it exists for\n each element in the `iterable`. If None, then default ids will be\n used.\n keys : iterable, optional\n An iterable of the same length as `iterable`. Each element will be\n used as the respective key.\n validate : boolean, optional\n If ``True``, all pairwise distances are computed, including upper\n and lower triangles and the diagonal, and the resulting matrix is\n validated for symmetry and hollowness. If ``False``, `metric` is\n assumed to be hollow and symmetric and only the lower triangle\n (excluding the diagonal) is computed. Pass ``validate=False`` if\n you are sure `metric` is hollow and symmetric for improved\n performance.\n\n Returns\n -------\n DistanceMatrix\n The `metric` applied to pairwise elements in the `iterable`.\n\n Raises\n ------\n ValueError\n If `key` and `keys` are both provided.\n\n \"\"\"\n if validate:\n return super(DistanceMatrix, cls).from_iterable(iterable, metric,\n key, keys)\n\n iterable = list(iterable)\n if key is not None and keys is not None:\n raise ValueError(\"Cannot use both `key` and `keys` at the same\"\n \" time.\")\n\n keys_ = None\n if key is not None:\n keys_ = [resolve_key(e, key) for e in iterable]\n elif keys is not None:\n keys_ = keys\n\n dm = np.zeros((len(iterable),) * 2)\n for i, a in enumerate(iterable):\n for j, b in enumerate(iterable[:i]):\n dm[i, j] = dm[j, i] = metric(a, b)\n\n return cls(dm, keys_)\n\n @experimental(as_of=\"0.4.0\")\n def condensed_form(self):\n \"\"\"Return an array of distances in condensed format.\n\n Returns\n -------\n ndarray\n One-dimensional ``numpy.ndarray`` of distances in condensed format.\n\n Notes\n -----\n Condensed format is described in [1]_.\n\n The conversion is not a constant-time operation, though it should be\n relatively quick to perform.\n\n References\n ----------\n .. [1] http://docs.scipy.org/doc/scipy/reference/spatial.distance.html\n\n \"\"\"\n return squareform(self._data, force='tovector', checks=False)\n\n @experimental(as_of=\"0.4.0\")\n def permute(self, condensed=False):\n \"\"\"Randomly permute both rows and columns in the matrix.\n\n Randomly permutes the ordering of rows and columns in the matrix. The\n same permutation is applied to both rows and columns in order to\n maintain symmetry and hollowness. Only the rows/columns in the distance\n matrix are permuted; the IDs are *not* permuted.\n\n Parameters\n ----------\n condensed : bool, optional\n If ``True``, return the permuted distance matrix in condensed\n format. Otherwise, return the permuted distance matrix as a new\n ``DistanceMatrix`` instance.\n\n Returns\n -------\n DistanceMatrix or ndarray\n Permuted distances as a new ``DistanceMatrix`` or as a ``ndarray``\n in condensed format.\n\n See Also\n --------\n condensed_form\n\n Notes\n -----\n This method does not modify the distance matrix that it is called on.\n It is more efficient to pass ``condensed=True`` than permuting the\n distance matrix and then converting to condensed format.\n\n \"\"\"\n order = np.random.permutation(self.shape[0])\n\n if condensed:\n permuted_condensed = distmat_reorder_condensed(self._data, order)\n return permuted_condensed\n else:\n # Note: Skip validation, since we assume self was already validated\n permuted = distmat_reorder(self._data, order)\n return self.__class__(permuted, self.ids, validate=False)\n\n def _validate(self, data, ids):\n \"\"\"Validate the data array and IDs.\n\n Overrides the superclass `_validate`. Performs a check for symmetry in\n addition to the checks performed in the superclass.\n\n \"\"\"\n super(DistanceMatrix, self)._validate(data, ids)\n\n data_sym, data_hol = is_symmetric_and_hollow(data)\n\n if not data_sym:\n raise DistanceMatrixError(\n \"Data must be symmetric and cannot contain NaNs.\")\n\n if not data_hol:\n raise DistanceMatrixError(\"Data must be hollow (i.e., the diagonal\"\n \" can only contain zeros).\")\n\n @experimental(as_of=\"0.5.1\")\n def to_series(self):\n \"\"\"Create a ``pandas.Series`` from this ``DistanceMatrix``.\n\n The series will contain distances in condensed form: only distances\n from one matrix triangle are included, and the diagonal is excluded.\n The series' index will be a ``pd.MultiIndex`` relating pairs of IDs to\n distances. The pairs of IDs will be in row-major order with respect to\n the upper matrix triangle.\n\n To obtain all distances (i.e. both upper and lower matrix triangles and\n the diagonal), use ``DistanceMatrix.to_data_frame``. To obtain *only*\n the distances in condensed form (e.g. for use with SciPy), use\n ``DistanceMatrix.condensed_form``.\n\n Returns\n -------\n pd.Series\n ``pd.Series`` with pairs of IDs on the index.\n\n See Also\n --------\n to_data_frame\n condensed_form\n scipy.spatial.distance.squareform\n\n Examples\n --------\n >>> from skbio import DistanceMatrix\n >>> dm = DistanceMatrix([[0, 1, 2, 3],\n ... [1, 0, 4, 5],\n ... [2, 4, 0, 6],\n ... [3, 5, 6, 0]], ids=['a', 'b', 'c', 'd'])\n >>> dm.to_series()\n a b 1.0\n c 2.0\n d 3.0\n b c 4.0\n d 5.0\n c d 6.0\n dtype: float64\n\n \"\"\"\n distances = self.condensed_form()\n # `id_pairs` will not be interpreted as a `pd.MultiIndex` if it is an\n # iterable returned by `itertools.combinations`.\n id_pairs = list(itertools.combinations(self.ids, 2))\n index = pd.Index(id_pairs, tupleize_cols=True)\n return pd.Series(data=distances, index=index, dtype=float)\n\n\n@experimental(as_of=\"0.4.0\")\ndef randdm(num_objects, ids=None, constructor=None, random_fn=None):\n \"\"\"Generate a distance matrix populated with random distances.\n\n Using the default `random_fn`, distances are randomly drawn from a uniform\n distribution over ``[0, 1)``.\n\n Regardless of `random_fn`, the resulting distance matrix is guaranteed to\n be symmetric and hollow.\n\n Parameters\n ----------\n num_objects : int\n The number of objects in the resulting distance matrix. For example, if\n `num_objects` is 3, a 3x3 distance matrix will be returned.\n ids : sequence of str or None, optional\n A sequence of strings to be used as IDs. ``len(ids)`` must be equal to\n `num_objects`. If not provided, IDs will be monotonically-increasing\n integers cast as strings (numbering starts at 1). For example,\n ``('1', '2', '3')``.\n constructor : type, optional\n `DissimilarityMatrix` or subclass constructor to use when creating the\n random distance matrix. The returned distance matrix will be of this\n type. If ``None`` (the default), a `DistanceMatrix` instance will be\n returned.\n random_fn : function, optional\n Function to generate random values. `random_fn` must accept two\n arguments (number of rows and number of columns) and return a 2D\n ``numpy.ndarray`` of floats (or something that can be cast to float).\n If ``None`` (the default), ``numpy.random.rand`` will be used.\n\n Returns\n -------\n DissimilarityMatrix\n `DissimilarityMatrix` (or subclass) instance of random distances. Type\n depends on `constructor`.\n\n See Also\n --------\n numpy.random.rand\n\n \"\"\"\n if constructor is None:\n constructor = DistanceMatrix\n if random_fn is None:\n random_fn = np.random.rand\n\n data = np.tril(random_fn(num_objects, num_objects), -1)\n data = data + data.T\n\n if not ids:\n ids = map(str, range(1, num_objects + 1))\n\n return constructor(data, ids)\n\n\n# helper functions for anosim and permanova\n\ndef _preprocess_input_sng(distance_matrix, grouping, column):\n \"\"\"Compute intermediate results not affected by permutations.\n\n These intermediate results can be computed a single time for efficiency,\n regardless of grouping vector permutations (i.e., when calculating the\n p-value). These intermediate results are used by both ANOSIM and PERMANOVA.\n\n Also validates and normalizes input (e.g., converting ``DataFrame`` column\n into grouping vector).\n\n \"\"\"\n if not isinstance(distance_matrix, DistanceMatrix):\n raise TypeError(\"Input must be a DistanceMatrix.\")\n\n if isinstance(grouping, pd.DataFrame):\n if column is None:\n raise ValueError(\n \"Must provide a column name if supplying a DataFrame.\")\n else:\n grouping = _df_to_vector(distance_matrix, grouping, column)\n elif column is not None:\n raise ValueError(\n \"Must provide a DataFrame if supplying a column name.\")\n\n sample_size = distance_matrix.shape[0]\n if len(grouping) != sample_size:\n raise ValueError(\n \"Grouping vector size must match the number of IDs in the \"\n \"distance matrix.\")\n\n # Find the group labels and convert grouping to an integer vector\n # (factor).\n groups, grouping = np.unique(grouping, return_inverse=True)\n num_groups = len(groups)\n\n if num_groups == len(grouping):\n raise ValueError(\n \"All values in the grouping vector are unique. This method cannot \"\n \"operate on a grouping vector with only unique values (e.g., \"\n \"there are no 'within' distances because each group of objects \"\n \"contains only a single object).\")\n if num_groups == 1:\n raise ValueError(\n \"All values in the grouping vector are the same. This method \"\n \"cannot operate on a grouping vector with only a single group of \"\n \"objects (e.g., there are no 'between' distances because there is \"\n \"only a single group).\")\n\n return sample_size, num_groups, grouping\n\n\ndef _preprocess_input(distance_matrix, grouping, column):\n \"\"\"Compute intermediate results not affected by permutations.\n\n These intermediate results can be computed a single time for efficiency,\n regardless of grouping vector permutations (i.e., when calculating the\n p-value). These intermediate results are used by both ANOSIM and PERMANOVA.\n\n Also validates and normalizes input (e.g., converting ``DataFrame`` column\n into grouping vector).\n\n \"\"\"\n sample_size, num_groups, grouping = _preprocess_input_sng(distance_matrix,\n grouping, column)\n\n tri_idxs = np.triu_indices(sample_size, k=1)\n distances = distance_matrix.condensed_form()\n\n return sample_size, num_groups, grouping, tri_idxs, distances\n\n\ndef _df_to_vector(distance_matrix, df, column):\n \"\"\"Return a grouping vector from a ``DataFrame`` column.\n\n Parameters\n ----------\n distance_marix : DistanceMatrix\n Distance matrix whose IDs will be mapped to group labels.\n df : pandas.DataFrame\n ``DataFrame`` (indexed by distance matrix ID).\n column : str\n Column name in `df` containing group labels.\n\n Returns\n -------\n list\n Grouping vector (vector of labels) based on the IDs in\n `distance_matrix`. Each ID's label is looked up in the ``DataFrame``\n under the column specified by `column`.\n\n Raises\n ------\n ValueError\n If `column` is not in the ``DataFrame``, or a distance matrix ID is\n not in the ``DataFrame``.\n\n \"\"\"\n if column not in df:\n raise ValueError(\"Column '%s' not in DataFrame.\" % column)\n\n grouping = df.reindex(distance_matrix.ids, axis=0).loc[:, column]\n if grouping.isnull().any():\n raise ValueError(\n \"One or more IDs in the distance matrix are not in the data \"\n \"frame.\")\n return grouping.tolist()\n\n\ndef _run_monte_carlo_stats(test_stat_function, grouping, permutations):\n \"\"\"Run stat test and compute significance with Monte Carlo permutations.\"\"\"\n if permutations < 0:\n raise ValueError(\n \"Number of permutations must be greater than or equal to zero.\")\n\n stat = test_stat_function(grouping)\n\n p_value = np.nan\n if permutations > 0:\n perm_stats = np.empty(permutations, dtype=np.float64)\n\n for i in range(permutations):\n perm_grouping = np.random.permutation(grouping)\n perm_stats[i] = test_stat_function(perm_grouping)\n\n p_value = ((perm_stats >= stat).sum() + 1) / (permutations + 1)\n\n return stat, p_value\n\n\ndef _build_results(method_name, test_stat_name, sample_size, num_groups, stat,\n p_value, permutations):\n \"\"\"Return ``pandas.Series`` containing results of statistical test.\"\"\"\n return pd.Series(\n data=[method_name, test_stat_name, sample_size, num_groups, stat,\n p_value, permutations],\n index=['method name', 'test statistic name', 'sample size',\n 'number of groups', 'test statistic', 'p-value',\n 'number of permutations'],\n name='%s results' % method_name)\n"
] | [
[
"numpy.hstack",
"pandas.concat",
"pandas.Series",
"numpy.array_equal",
"numpy.triu_indices",
"numpy.unique",
"numpy.arange",
"numpy.asarray",
"matplotlib.pyplot.subplots",
"pandas.DataFrame",
"pandas.Index",
"numpy.random.permutation",
"matplotlib.pyplot.close",
"scipy.spatial.distance.squareform",
"numpy.array",
"numpy.empty"
]
] | [
{
"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": [
"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": []
}
] |
sujitpal/sherpa | [
"95cda5a3d150e19b6038c445352454e1ebbdc45e"
] | [
"scripts/submissions_over_time.py"
] | [
"# Run from Django shell (python manage.py shell) using following call.\n# >>> exec(open(\"scripts/submissions_over_time.py\").read())\n\nimport datetime\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom apps.models import Paper\n\nCFP_OPEN_DATE = datetime.date(2021, 4, 1)\nCFP_CLOSE_DATE = datetime.date(2021, 5, 28)\nCFP_EXTN_DATE = datetime.date(2021, 6, 11)\n\npapers = Paper.objects.all()\nsubmission_elapsed_days = sorted(\n [(p.submitted_at.date() - CFP_OPEN_DATE).days for p in papers])\n# print(submission_elapsed_days)\n\ncumulative_submission_counts = np.cumsum(np.ones(len(submission_elapsed_days)))\n# print(cumulative_submission_counts)\n\nplt.plot(submission_elapsed_days, cumulative_submission_counts)\nplt.xlabel(\"number of days after CFP opened\")\nplt.ylabel(\"total number of submissions\")\n\nplt.axvline(0, ymin=0, ymax=max(cumulative_submission_counts),\n color='g', linestyle='--', label=\"CFP open\")\n\ncfp_close = (CFP_CLOSE_DATE - CFP_OPEN_DATE).days\nplt.axvline(cfp_close, ymin=0, ymax=max(cumulative_submission_counts),\n color='r', linestyle='--', label=\"CFP close\")\n\ncfp_extn = (CFP_EXTN_DATE - CFP_OPEN_DATE).days\nplt.axvline(cfp_extn, ymin=0, ymax=max(cumulative_submission_counts),\n color='orange', linestyle='--', label=\"CFP extn\")\n\nplt.legend(loc=\"best\")\n\nplt.savefig(\"scripts/submissions_over_time.png\")\n"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
LEOCUIZHIHAO/kpmask | [
"73fe907b2359b7ddc2927cd325bbbb686eb62ffd"
] | [
"mmdet/models/detectors/base.py"
] | [
"from abc import ABCMeta, abstractmethod\nfrom collections import OrderedDict\n\nimport mmcv\nimport numpy as np\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nfrom mmcv.utils import print_log\n\nfrom mmdet.core import auto_fp16\nfrom mmdet.utils import get_root_logger\n\n\nclass BaseDetector(nn.Module, metaclass=ABCMeta):\n \"\"\"Base class for detectors.\"\"\"\n\n def __init__(self):\n super(BaseDetector, self).__init__()\n self.fp16_enabled = False\n\n @property\n def with_neck(self):\n \"\"\"bool: whether the detector has a neck\"\"\"\n return hasattr(self, 'neck') and self.neck is not None\n\n # TODO: these properties need to be carefully handled\n # for both single stage & two stage detectors\n @property\n def with_shared_head(self):\n \"\"\"bool: whether the detector has a shared head in the RoI Head\"\"\"\n return hasattr(self.roi_head,\n 'shared_head') and self.roi_head.shared_head is not None\n\n @property\n def with_bbox(self):\n \"\"\"bool: whether the detector has a bbox head\"\"\"\n return ((hasattr(self.roi_head, 'bbox_head')\n and self.roi_head.bbox_head is not None)\n or (hasattr(self, 'bbox_head') and self.bbox_head is not None))\n\n @property\n def with_mask(self):\n \"\"\"bool: whether the detector has a mask head\"\"\"\n return ((hasattr(self.roi_head, 'mask_head')\n and self.roi_head.mask_head is not None)\n or (hasattr(self, 'mask_head') and self.mask_head is not None))\n\n @abstractmethod\n def extract_feat(self, imgs):\n \"\"\"Extract features from images.\"\"\"\n pass\n\n def extract_feats(self, imgs):\n \"\"\"Extract features from multiple images.\n\n Args:\n imgs (list[torch.Tensor]): A list of images. The images are\n augmented from the same image but in different ways.\n\n Returns:\n list[torch.Tensor]: Features of different images\n \"\"\"\n assert isinstance(imgs, list)\n return [self.extract_feat(img) for img in imgs]\n\n @abstractmethod\n def forward_train(self, imgs, img_metas, **kwargs):\n \"\"\"\n Args:\n img (list[Tensor]): List of tensors of shape (1, C, H, W).\n Typically these should be mean centered and std scaled.\n img_metas (list[dict]): List of image info dict where each dict\n has: 'img_shape', 'scale_factor', 'flip', and my also contain\n 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.\n For details on the values of these keys, see\n :class:`mmdet.datasets.pipelines.Collect`.\n kwargs (keyword arguments): Specific to concrete implementation.\n \"\"\"\n pass\n\n async def async_simple_test(self, img, img_metas, **kwargs):\n raise NotImplementedError\n\n @abstractmethod\n def simple_test(self, img, img_metas, **kwargs):\n pass\n\n @abstractmethod\n def aug_test(self, imgs, img_metas, **kwargs):\n \"\"\"Test function with test time augmentation.\"\"\"\n pass\n\n def init_weights(self, pretrained=None):\n \"\"\"Initialize the weights in detector.\n\n Args:\n pretrained (str, optional): Path to pre-trained weights.\n Defaults to None.\n \"\"\"\n if pretrained is not None:\n logger = get_root_logger()\n print_log(f'load model from: {pretrained}', logger=logger)\n\n async def aforward_test(self, *, img, img_metas, **kwargs):\n for var, name in [(img, 'img'), (img_metas, 'img_metas')]:\n if not isinstance(var, list):\n raise TypeError(f'{name} must be a list, but got {type(var)}')\n\n num_augs = len(img)\n if num_augs != len(img_metas):\n raise ValueError(f'num of augmentations ({len(img)}) '\n f'!= num of image metas ({len(img_metas)})')\n # TODO: remove the restriction of samples_per_gpu == 1 when prepared\n samples_per_gpu = img[0].size(0)\n assert samples_per_gpu == 1\n\n if num_augs == 1:\n return await self.async_simple_test(img[0], img_metas[0], **kwargs)\n else:\n raise NotImplementedError\n\n def forward_test(self, imgs, img_metas, **kwargs):\n \"\"\"\n Args:\n imgs (List[Tensor]): the outer list indicates test-time\n augmentations and inner Tensor should have a shape NxCxHxW,\n which contains all images in the batch.\n img_metas (List[List[dict]]): the outer list indicates test-time\n augs (multiscale, flip, etc.) and the inner list indicates\n images in a batch.\n \"\"\"\n for var, name in [(imgs, 'imgs'), (img_metas, 'img_metas')]:\n if not isinstance(var, list):\n raise TypeError(f'{name} must be a list, but got {type(var)}')\n\n num_augs = len(imgs)\n if num_augs != len(img_metas):\n raise ValueError(f'num of augmentations ({len(imgs)}) '\n f'!= num of image meta ({len(img_metas)})')\n # TODO: remove the restriction of samples_per_gpu == 1 when prepared\n samples_per_gpu = imgs[0].size(0)\n assert samples_per_gpu == 1\n\n if num_augs == 1:\n # proposals (List[List[Tensor]]): the outer list indicates\n # test-time augs (multiscale, flip, etc.) and the inner list\n # indicates images in a batch.\n # The Tensor should have a shape Px4, where P is the number of\n # proposals.\n if 'proposals' in kwargs:\n kwargs['proposals'] = kwargs['proposals'][0]\n return self.simple_test(imgs[0], img_metas[0], **kwargs)\n else:\n # TODO: support test augmentation for predefined proposals\n assert 'proposals' not in kwargs\n return self.aug_test(imgs, img_metas, **kwargs)\n\n @auto_fp16(apply_to=('img', ))\n def forward(self, img, img_metas, return_loss=True, **kwargs):\n \"\"\"Calls either :func:`forward_train` or :func:`forward_test` depending\n on whether ``return_loss`` is ``True``.\n\n Note this setting will change the expected inputs. When\n ``return_loss=True``, img and img_meta are single-nested (i.e. Tensor\n and List[dict]), and when ``resturn_loss=False``, img and img_meta\n should be double nested (i.e. List[Tensor], List[List[dict]]), with\n the outer list indicating test time augmentations.\n \"\"\"\n if return_loss:\n return self.forward_train(img, img_metas, **kwargs)\n else:\n return self.forward_test(img, img_metas, **kwargs)\n\n def _parse_losses(self, losses):\n \"\"\"Parse the raw outputs (losses) of the network.\n\n Args:\n losses (dict): Raw output of the network, which usually contain\n losses and other necessary infomation.\n\n Returns:\n tuple[Tensor, dict]: (loss, log_vars), loss is the loss tensor\n which may be a weighted sum of all losses, log_vars contains\n all the variables to be sent to the logger.\n \"\"\"\n log_vars = OrderedDict()\n for loss_name, loss_value in losses.items():\n if isinstance(loss_value, torch.Tensor):\n log_vars[loss_name] = loss_value.mean()\n elif isinstance(loss_value, list):\n log_vars[loss_name] = sum(_loss.mean() for _loss in loss_value)\n else:\n raise TypeError(\n f'{loss_name} is not a tensor or list of tensors')\n\n loss = sum(_value for _key, _value in log_vars.items()\n if 'loss' in _key)\n\n log_vars['loss'] = loss\n for loss_name, loss_value in log_vars.items():\n # reduce loss when distributed training\n if dist.is_available() and dist.is_initialized():\n loss_value = loss_value.data.clone()\n dist.all_reduce(loss_value.div_(dist.get_world_size()))\n log_vars[loss_name] = loss_value.item()\n\n return loss, log_vars\n\n def train_step(self, data, optimizer):\n \"\"\"The iteration step during training.\n\n This method defines an iteration step during training, except for the\n back propagation and optimizer updating, which are done in an optimizer\n hook. Note that in some complicated cases or models, the whole process\n including back propagation and optimizer updating is also defined in\n this method, such as GAN.\n\n Args:\n data (dict): The output of dataloader.\n optimizer (:obj:`torch.optim.Optimizer` | dict): The optimizer of\n runner is passed to ``train_step()``. This argument is unused\n and reserved.\n\n Returns:\n dict: It should contain at least 3 keys: ``loss``, ``log_vars``,\n ``num_samples``.\n ``loss`` is a tensor for back propagation, which can be a\n weighted sum of multiple losses.\n ``log_vars`` contains all the variables to be sent to the\n logger.\n ``num_samples`` indicates the batch size (when the model is\n DDP, it means the batch size on each GPU), which is used for\n averaging the logs.\n \"\"\"\n losses = self(**data)\n loss, log_vars = self._parse_losses(losses)\n\n outputs = dict(\n loss=loss, log_vars=log_vars, num_samples=len(data['img_metas']))\n\n return outputs\n\n def val_step(self, data, optimizer):\n \"\"\"The iteration step during validation.\n\n This method shares the same signature as :func:`train_step`, but used\n during val epochs. Note that the evaluation after training epochs is\n not implemented with this method, but an evaluation hook.\n \"\"\"\n losses = self(**data)\n loss, log_vars = self._parse_losses(losses)\n\n outputs = dict(\n loss=loss, log_vars=log_vars, num_samples=len(data['img_metas']))\n\n return outputs\n\n def show_result(self,\n img,\n result,\n score_thr=0.3,\n bbox_color='green',\n text_color='green',\n thickness=1,\n font_scale=0.5,\n win_name='',\n show=False,\n wait_time=0,\n out_file=None):\n \"\"\"Draw `result` over `img`.\n\n Args:\n img (str or Tensor): The image to be displayed.\n result (Tensor or tuple): The results to draw over `img`\n bbox_result or (bbox_result, segm_result).\n score_thr (float, optional): Minimum score of bboxes to be shown.\n Default: 0.3.\n bbox_color (str or tuple or :obj:`Color`): Color of bbox lines.\n text_color (str or tuple or :obj:`Color`): Color of texts.\n thickness (int): Thickness of lines.\n font_scale (float): Font scales of texts.\n win_name (str): The window name.\n wait_time (int): Value of waitKey param.\n Default: 0.\n show (bool): Whether to show the image.\n Default: False.\n out_file (str or None): The filename to write the image.\n Default: None.\n\n Returns:\n img (Tensor): Only if not `show` or `out_file`\n \"\"\"\n img = mmcv.imread(img)\n img = img.copy()\n if isinstance(result, tuple):\n bbox_result, segm_result = result\n if isinstance(segm_result, tuple):\n segm_result = segm_result[0] # ms rcnn\n else:\n bbox_result, segm_result = result, None\n bboxes = np.vstack(bbox_result)\n labels = [\n np.full(bbox.shape[0], i, dtype=np.int32)\n for i, bbox in enumerate(bbox_result)\n ]\n labels = np.concatenate(labels)\n # draw segmentation masks\n if segm_result is not None and len(labels) > 0: # non empty\n segms = mmcv.concat_list(segm_result)\n inds = np.where(bboxes[:, -1] > score_thr)[0]\n np.random.seed(42)\n color_masks = [\n np.random.randint(0, 256, (1, 3), dtype=np.uint8)\n for _ in range(max(labels) + 1)\n # for _ in range(len(labels) + 1)\n ]\n for i in inds:\n i = int(i)\n # color_mask = color_masks[i]\n color_mask = color_masks[labels[i]]\n mask = segms[i]\n img[mask] = img[mask] * 0.5 + color_mask * 0.5\n # if out_file specified, do not show image in window\n if out_file is not None:\n show = False\n # draw bounding boxes\n mmcv.imshow_det_bboxes(\n img,\n bboxes,\n labels,\n class_names=self.CLASSES,\n score_thr=score_thr,\n bbox_color=bbox_color,\n text_color=text_color,\n thickness=thickness,\n font_scale=font_scale,\n win_name=win_name,\n show=show,\n wait_time=wait_time,\n out_file=out_file)\n\n if not (show or out_file):\n return img\n"
] | [
[
"numpy.random.seed",
"torch.distributed.is_initialized",
"numpy.full",
"numpy.concatenate",
"torch.distributed.is_available",
"torch.distributed.get_world_size",
"numpy.where",
"numpy.vstack",
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
KAUST-NetLab/AirDL | [
"f63285117a081681b4aa0e2ac6cf16c0bb270f48"
] | [
"demos/model/traffic.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport numpy as np\nimport pandas as pd\n\nimport torch.optim as optim\n\nimport torchvision\nfrom torchvision import transforms\nfrom torch.optim.lr_scheduler import StepLR\n\nimport random\n\n\nimport ns.distributedml as dml\nimport time\n\n\nfrom model import TaskBase\n\n\"\"\"\n Build Neural network\n\"\"\"\nfrom torch.autograd import Variable\n\nclass args:\n\tinput_dim = 1\n\thidden_dim = 32\n\tnum_layers = 2\n\tout_dim = 1\n\tlr = 0.05\n\tgpu = False\n\tfile_path = './data/demo_data.h5'\n\twindow_size = 5\n\ttest_days = 7\n\n\n\n\nclass LSTM(nn.Module):\n\tdef __init__(self):\n\t\tsuper(LSTM, self).__init__()\n\t\tself.criterion = nn.MSELoss()\n\t\tself.input_dim = args.input_dim\n\t\tself.hidden_dim = args.hidden_dim\n\t\tself.out_dim = args.out_dim\n\t\tself.num_layers = args.num_layers\n\t\tself.device = 'cuda' if args.gpu else 'cpu'\n\n\t\tself.lstm_layer = nn.LSTM(input_size=self.input_dim,\n\t\t hidden_size=self.hidden_dim,\n\t\t num_layers=self.num_layers, batch_first=True)\n\n\t\tself.linear_layer = nn.Linear(self.hidden_dim, self.out_dim)\n\n\tdef forward(self, x):\n\t\tbz = x.size(0)\n\t\th0 = Variable(torch.zeros(self.num_layers * 1, bz, self.hidden_dim)).to(self.device)\n\t\tc0 = Variable(torch.zeros(self.num_layers * 1, bz, self.hidden_dim)).to(self.device)\n\n\t\tself.lstm_layer.flatten_parameters()\n\t\tlstm_out, hn = self.lstm_layer(x, (h0, c0))\n\t\ty_pred = self.linear_layer(lstm_out[:, -1, :])\n\t\treturn y_pred\n\n\n\n\nclass AirTask(TaskBase):\n\tdef __init__(self, global_rank=0, global_size=1, log=\"tf_\", \\\n\t\t\t\t\t\tlocal_epochs=1, \\\n\t\t\t\t\t\tactive_ratio=1, \\\n\t\t\t\t\t\tsleeping_time=0, \\\n\t\t\t\t\t\tnoise_ratio=0, \\\n\t\t\t\t\t\tnoise_type=\"add\", \\\n\t\t\t\t\t\tbatch_size=8, \\\n\t\t\t\t\t\tpart_ratio=[1,1,1,1]):\n\n\t\tsuper(AirTask, self).__init__(log=log)\n\n\t\tself.global_rank = global_rank\n\t\tself.global_size = global_size\n\t\tself.batch_size = batch_size\n\t\tself.local_epochs = local_epochs\n\n\t\tself.active_ratio = active_ratio\n\t\tself.sleeping_time = sleeping_time\n\t\tself.noise_ratio = noise_ratio\n\t\tself.noise_type = noise_type\n\n\t\tself.part_ratio = part_ratio\n\n\t\tself.model = LSTM()\n\t\t\n\t\tself.initialize()\n\n\t\t\n\tdef __noise(self):\n\t\tif self.noise_type == \"add\":\n\t\t\treturn self.add_noise(self.noise_ratio)\n\t\telif self.noise_type == \"multi\":\n\t\t\treturn self.multi_noise(self.noise_ratio)\n\t\telse:\n\t\t\tprint(\"Currently we only implemented add-noise and multi_noise, uses can implement their own noises by themself.\")\n\n\n\n\tdef get_dataset(self):\n\t\tdf = pd.read_csv(args.file_path, header=0, index_col=0)\n\t\tdf.fillna(0.0, inplace=True)\n\n\t\ttrain_cells = df.columns[0: self.global_size*3]\n\t\tdf_train_cells = df[train_cells]\n\n\n\t\ttest_cells = df.columns[-4:]\n\t\tdf_test_cells = df[test_cells]\n\n\n\t\ttrain_data = df_train_cells.iloc[:]\n\t\ttest_data = df_test_cells.iloc[:]\n\n\t\t# normalize the data to zero mean and unit deviation using only train data\n\t\tmean_train = train_data.mean(axis=0)\n\t\tstd_train = train_data.std(axis=0)\n\t\ttrain_data = (train_data - mean_train) / std_train\n\n\t\tmean_test = test_data.mean(axis=0)\n\t\tstd_test = test_data.std(axis=0)\n\t\ttest_data = (test_data - mean_test) / std_test\n\n\t\ttrain_x, train_y = [], []\n\t\tfor cell in train_cells:\n\t\t\tcell_data = train_data.loc[:, cell]\n\t\t\tx, y = self.get_data(cell_data)\n\t\t\ttrain_x.append(x)\n\t\t\ttrain_y.append(y)\n\t\t\n\t\ttrain_x, train_y = torch.cat(train_x, dim=0), torch.cat(train_y, dim=0)\n\n\t\ttest_x, test_y = [], []\n\t\tfor cell in test_cells:\n\t\t\tcell_data = test_data.loc[:, cell]\n\t\t\tx, y = self.get_data(cell_data)\n\t\t\ttest_x.append(x)\n\t\t\ttest_y.append(y)\n\t\t\n\t\ttest_x, test_y = torch.cat(test_x, dim=0), torch.cat(test_y, dim=0)\n\t\t\n\n\t\ttrain_dataset = list(zip(train_x, train_y))\n\t\ttest_dataset = list(zip(test_x, test_y))\n\n\t\treturn train_dataset, test_dataset\n\n\n\tdef get_data(self, dataset):\n\t\ttrain_shifts = [dataset.shift(i) for i in range(1 - args.out_dim, args.window_size + 1, 1)]\n\n\t\tdf_train = pd.concat(train_shifts, axis=1, ignore_index=True)\n\t\tdf_train.dropna(inplace=True)\n\n\t\tx, y = df_train.iloc[:, args.out_dim:].values[:, :, np.newaxis], df_train.iloc[:, :args.out_dim].values\n\n\t\tX = torch.from_numpy(x).type(torch.Tensor)\n\t\tY = torch.from_numpy(y).type(torch.Tensor)\n\n\t\t\n\t\treturn X, Y\n\n\n\tdef initialize(self):\n\n\t\ttrain_dataset, test_dataset = self.get_dataset()\n\n\t\tif self.rank>0 and self.world_size>=1:\n\t\t\ttrain_dataset = self.uniform_partition(train_dataset, self.global_size)[self.global_rank]\n\n\t\t\t# train_dataset = self.partition(train_dataset, self.global_size, part_ratio=self.part_ratio)[self.global_rank]\n\n\n\t\ttrain_kwargs = {'batch_size': self.batch_size, 'drop_last': True}\n\n\t\tself.train_loader = torch.utils.data.DataLoader(train_dataset, **train_kwargs)\n\n\t\tif self.rank == 0:\n\t\t\tself.test_loader = torch.utils.data.DataLoader(test_dataset, **train_kwargs)\n\n\t\t\t\t\n\t\tself.optimizer = optim.Adadelta(self.model.parameters(), lr=args.lr*self.active_ratio*self.global_size)\n\t\tself.scheduler = StepLR(self.optimizer, step_size=5, gamma=0.9)\n\t\n\n\n\tdef train(self):\n\t\tself.__noise()\n\t\tself.model.train()\n\t\tfor i in range(self.local_epochs):\n\t\t\tfor batch_idx, (data, target) in enumerate(self.train_loader):\n\t\t\t\tself.optimizer.zero_grad()\n\t\t\t\toutput = self.model(data)\n\n\t\t\t\tloss = self.model.criterion(output, target)\n\t\t\t\tloss.backward()\n\t\t\t\t\n\t\t\t\tself.optimizer.step()\n\n\t\t\tself.scheduler.step()\n\n\t\tself.global_step += 1\t\t\n\n\n\tdef evaluate(self):\n\t\tself.model.eval()\n\t\ttest_loss, mse = 0.0, 0.0\n\t\twith torch.no_grad():\n\t\t\tfor batch_idx, (data, target) in enumerate(self.test_loader):\n\t\t\t\toutput = self.model(data)\n\t\t\t\ttest_loss += self.model.criterion(output, target).item() # sum up batch loss\n\t\t\t\tmse += torch.sum((output - target) ** 2).item()\n\n\n\t\t\ttest_loss = test_loss / (batch_idx+1)\n\t\t\tmse = mse / (batch_idx+1)\n\t\t\n\t\t\n\t\tif self.rank == 0:\n\t\t\tprint(\"writing into tb_writer... curret time: {}, wall-clock: {}\".format(dml.PyTimer.now(\"s\"), self.wall_clock))\n\t\t\tself.tb_writer.add_scalar('loss', test_loss, self.global_step)\n\t\t\tself.tb_writer.add_scalar('mse', mse, self.global_step)\n\t\t\t\n\t\t\twith open(self.output, 'a+') as f:\n\t\t\t\tout_str = \"EVAL:: epoch: {} curret time: {}, wall-clock: {}, loss: {}, mse: {}\\n\".format(self.global_step, dml.PyTimer.now(\"s\"), self.wall_clock, test_loss, mse)\n\t\t\t\tprint(out_str)\n\t\t\t\tf.write(out_str)\n\n\t\t\tself.tb_writer.flush()\n\n\t\t# with open(self.output, 'a+') as f:\n\t\t# \tout_str = \"EVAL:: epoch: {} curret time: {}, wall-clock: {}, loss: {}, mse: {}\\n\".format(self.global_step, dml.PyTimer.now(\"s\"), self.wall_clock, test_loss, mse)\n\t\t# \tprint(out_str)\n\t\t# \tf.write(out_str)\n\t\tself.global_step += 1\n\n\t\n\n\n\n\t\t\n\n\t"
] | [
[
"pandas.concat",
"pandas.read_csv",
"torch.nn.LSTM",
"torch.cat",
"torch.zeros",
"torch.utils.data.DataLoader",
"torch.from_numpy",
"torch.sum",
"torch.nn.Linear",
"torch.no_grad",
"torch.nn.MSELoss",
"torch.optim.lr_scheduler.StepLR"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
slavesocieties/ssda-nlp | [
"8764d2f928ca0fe4e5737fbea4dcd518b8b804f6"
] | [
"ssda_nlp/model_performance_utils.py"
] | [
"# AUTOGENERATED! DO NOT EDIT! File to edit: 42-initial-model.ipynb (unless otherwise specified).\n\n__all__ = ['model_meta_training', 'get_ner_df', 'get_corrects_df', 'get_fns_df', 'get_fps_df']\n\n# Cell\n#export\n#data structure imports\nimport pandas as pd\nimport numpy as np\n\n#python imports\nimport random\n\n#modeling imports\nfrom spacy.util import fix_random_seed\nfrom .collate import *\n#from ssda.entity_corpus import *\n#from ssda.xml_parser import *\nfrom .split_data import *\nfrom .modeling import *\n\n# Cell\ndef model_meta_training(mdl, train_spacy, valid_df, eval_metric = 'f_score', patience_max = 5, save_dir = None, verbose=False, **kwargs):\n '''\n Function model_meta_training: a model wrapping function which implements early stopping based on model improvement on the validation set.\n Inputs: mdl: Spacy model, blank or pretrained\n train_spacy: training data in Spacy format\n valid_df: dataframe of validation data split\n eval_metric: metric on which the validation performance should be evaluated. Can be `f_score`, `precision` or `recall`.\n patience_max (default 5): Number of iterations to wait for the model performance to improve\n save_dir (default None): String of data directory. Use this parameter if you want the best model and its performance to be saved to disk.\n verbose (default False): Boolean indicating whether you want to print the performance after every *iterations* iterations.\n **kwargs: keyword arguments which will be passed directly to `train_model`. You should include at least the parameter n_iter and set it low\n to something like 10.\n Returns: mdl: Spacy model, although the original variable you passed in will still be a valid reference. NOTE THAT THIS MODEL WILL BE OVERTRAINED BY\n PATIENCE CYCLES. If you want the \"best\" model back, you'll need to load it from the saved directory.\n perf_df: pandas dataframe with the training performance (avg_cycle_loss) and validation performance (precision, recall, f_score) at every\n n_iter iterations, including the patience cycles.\n '''\n\n #loop parameters\n keep_training = True\n old_metric_val = -1\n cycle_no = 1\n patience = patience_max\n\n #output datafarme\n df_cols = ['cycle_no', 'avg_cycle_loss', 'precision', 'recall', 'f_score']\n perf_df = pd.DataFrame(columns = df_cols)\n\n #training loop\n while keep_training is True:\n\n # Train for the number of desired iterations\n mdl, loss_df = train_model(mdl, train_spacy, **kwargs)\n\n # Test based on the validation set to get performance and log\n ent_preds_df, metrics_df, per_ent_metrics = test_model(mdl, valid_df, 'entry_no', 'text')\n cycle_df_0 = pd.DataFrame(np.array([[cycle_no, loss_df['epoch_loss'].mean()]]), columns=df_cols[:2])\n cycle_df = pd.concat([cycle_df_0, metrics_df], axis=1)\n perf_df = pd.concat([perf_df, cycle_df])\n\n #print if desired\n if verbose: display(cycle_df)\n\n # If the performance is *strictly* better than previous performance (sometimes the performance is the same), save the model and performance\n if metrics_df.loc[0, eval_metric] > old_metric_val:\n old_metric_val = metrics_df.loc[0, eval_metric]\n if save_dir is not None:\n save_model(mdl, save_dir)\n\n #modify looping parameters\n cycle_no += 1\n patience = patience_max\n else:\n # If the performance isn't better, wait patience cycles\n patience -= 1\n if verbose: print(\"Performance hasn't improved for {0} cycles...\".format(patience_max - patience))\n cycle_no += 1\n\n #If you've exhausted the patience, end training\n if patience==0:\n\n #Stop training loop\n keep_training=False\n\n #Save performance\n perf_df.reset_index(drop=True, inplace=True)\n if save_dir is not None:\n perf_df.to_csv(save_dir + '/perf_df.csv', index=False)\n if verbose:\n print('Done training after {0} meta cycles.'.format(cycle_no-1))\n\n return mdl, perf_df\n\n# Cell\ndef get_ner_df(split_df, ent_df, verbose=True):\n '''\n Function get_ner_df: create joined dataframe of the ground truth dataframe and the prediction dataframe (from Spacy)\n Inputs: split_df: dataframe of split data (e.g., train, test, or validation)\n ent_df: dataframe of entities predicted from the data (e.g., from ssda.modeling: test_model)\n verbose (default True): True if you want to print shape information about the dataframes created.\n Returns: dataframe of fully joined results (an outer join so all rows are reported, regardless of whether they have matches)\n '''\n\n #join original dataframe df with entities recognized df\n ner_df = pd.merge(split_df, ent_df, left_on=['entry_no', 'entity', 'start', 'end'],\n right_on =['entry_no', 'pred_entity', 'pred_start', 'pred_end'], how='outer')\n\n #print if verbose\n if verbose: print('Fully joined results size: ', len(ner_df))\n\n return ner_df\n\n# Cell\ndef get_corrects_df(ner_df, split_df, verbose=True):\n '''\n Function get_corrects_df: get dataframe of entities which were correctly identified\n Inputs: ner_df: fully joined dataframe of entity ground truth and prediction results (e.g., from `get_ner_df`)\n split_df: dataframe of split data (e.g., train, test, or validation)\n verbose (default True): True if you want to print shape information about the dataframes created.\n Returns: dataframe of correctly identified entities with metadata\n '''\n corrs_df = ner_df.dropna().sort_values(['vol_id', 'entry_no'])\n if verbose: print(\"Number correctly identified: \", corrs_df.shape[0], \" of \", split_df.shape[0])\n\n return corrs_df\n\n# Cell\ndef get_fns_df(ner_df, split_df, verbose=True):\n '''\n Function get_fns_df: get dataframe of ground truth entities which were not predicted by the model\n Inputs: ner_df: fully joined dataframe of entity ground truth and prediction results (e.g., from `get_ner_df`)\n split_df: dataframe of split data (e.g., train, test, or validation)\n verbose (default True): True if you want to print shape information about the dataframes created.\n Returns: dataframe of false negatives (ground truth entities which were not predicted)\n '''\n\n #get predictions that were missed\n fn_df = ner_df[ner_df[['pred_entity', 'pred_start', 'pred_end']].isna().any(axis=1)]\n\n #cleanup for easy viewing\n fn_df = fn_df.copy().drop(['vol_titl', 'fol_id', 'pred_entity', 'pred_label', 'pred_start', 'pred_end'], axis=1)\n fn_df.sort_values(['vol_id','entry_no'], inplace=True)\n\n #print if verbose\n if verbose: print(\"Number not identified: \", fn_df.shape[0], \" of \", split_df.shape[0])\n\n return fn_df\n\n# Cell\ndef get_fps_df(ner_df, split_df, ent_df, verbose=True):\n '''\n Function get_fps_df: get dataframe of entities predicted by the model that were not in the ground truth dataframe\n Inputs: ner_df: fully joined dataframe of entity ground truth and prediction results (e.g., from `get_ner_df`)\n split_df: dataframe of split data (e.g., train, test, or validation)\n ent_df: dataframe of entities predicted from the data (e.g., from ssda.modeling: test_model)\n verbose (default True): True if you want to print shape information about the dataframes created.\n Returns: dataframe of false negatives (ground truth entities which were not predicted)\n '''\n\n #get incorrect identifications of entities in the texts\n fp_df = ner_df[ner_df[['entity', 'start', 'end']].isna().any(axis=1)]\n\n #cleanup for easy viewing\n fp_df = fp_df.copy().drop(['vol_id', 'vol_titl', 'fol_id', 'entity', 'label', 'start', 'end'], axis=1)\n\n #insert texts and vol_id in the dataframe\n fp_df = pd.merge(fp_df, split_df[['vol_id','entry_no', 'text']], on='entry_no').drop(['text_x'], axis=1)\n fp_df.rename(columns={'text_y':'text'}, inplace=True)\n\n #reorder columns\n col_order = ['vol_id', 'entry_no', 'text'] + list(fp_df.columns.drop(['vol_id', 'entry_no', 'text']))\n fp_df = fp_df[col_order]\n fp_df.sort_values(['vol_id','entry_no'], inplace=True)\n\n #I get duplicates because NaNs\n fp_df.drop_duplicates(inplace=True)\n\n #print info\n if verbose:\n print('False positive entities that were not correctly identified in the texts:')\n print(\"Number not correctly identified: \", fp_df.shape[0], \" of \", ent_df.shape[0])\n\n return fp_df"
] | [
[
"pandas.merge",
"pandas.concat",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
B-C-WANG/ReinforcementLearningInAutoPilot | [
"8d3c0b81e3db2fb4be0e52e25b700c54f5e569dc"
] | [
"src/ReinforcementLearning/train/archive_bad/ddpg_train_waypoints_GAL_v1.py"
] | [
"# coding:utf-8\n# Type: Private Author: BaoChuan Wang\n\n\n\n'''\nFIXME ddpg 需要全为负的reward,waypoints环境暂时没有提供!\n\n描述:\n和local模型相同,训练得不到较好的结果\n\n'''\n\nimport numpy as np\nfrom ReinforcementLearning.Modules.Agents.DDPG_Agent import DDPG_Agent_GAL_v1\nfrom ReinforcementLearning.Modules.Environments.Environments_waypointTarget import CarlaConsecutiveWaypointsTargetEnv_v1\nfrom ReinforcementLearning.Modules.Environments.Actions import ContinuousSteeringVelocityBrakeAction_v1\n\n# 关于以下设置,参考A3c train waypoints global and local\nserver_config = {\n\n \"10.10.9.128\": [2000],\n}\nn_workers_in_each_port = 1\n\nspawn_index_for_each_car_in_worker = (0, 10, 20, 30, 40, 50, 60, 70, 80)\n# 用随机数,扩大搜索\nspawn_index_for_each_car_in_worker = np.random.randint(0, 100, size=100)\n\nimport tensorflow as tf\n\ntf.random.set_random_seed(123)\nnp.random.seed(123)\n\nenv_dict = {}\nworker_kwargs = {}\nmodel_kwargs = {}\nfor ip in server_config:\n for port in server_config[ip]:\n for i in range(n_workers_in_each_port):\n name = 'W_%s' % (str(ip) + \"_\" + str(port) + \"_\" + str(i)) # worker name\n\n env = CarlaConsecutiveWaypointsTargetEnv_v1(\n carla_egg_path=\"/home/wang/Desktop/carla/PythonAPI/carla/dist/carla-0.9.5-py2.7-linux-x86_64.egg\",\n carla_pythonAPI_path=\"/home/wang/Desktop/carla/PythonAPI/carla\",\n carla_UE_ip=ip,\n carla_UE_port=port,\n n_waypoint=100,\n # DDPG没有IL相对难训练,所以间隔小一些!\n waypoint_spacing=3,\n vehicle_start_point_index=spawn_index_for_each_car_in_worker[i],\n wait_time_after_apply_action=0.1,\n ratio_of_reaching=0.3,\n add_center_lane_state=True,\n # 这里是DDPG和A3C算法的区别,使用连续空间的action\n action_replace=ContinuousSteeringVelocityBrakeAction_v1(),\n # 实测DDPG和A3C表现差异很大,因此单独设计它的reward试试?\n #reward_replace=\n )\n env_dict[name] = env\n\n worker_kwargs[name] = {\n \"start_variance\": 0.0,# debug时方差小一些,便于观察走势\n \"variance_decay\": 0.99,\n \"debug\":True\n }\n # model_kwargs[name] = {\n # }\n\nDDPG_Agent_GAL_v1(env_prototype_dict_for_workers=env_dict, save_dir=\"./a3c_gal_ckpt/\",\n kwargs_for_worker_dict=worker_kwargs,\n ).start()\n"
] | [
[
"numpy.random.seed",
"tensorflow.random.set_random_seed",
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mokochin/detectron2 | [
"64b3f71df890fc4f9da8be1dbfb636bd90f59873"
] | [
"detectron2/modeling/backbone/shufflenet_oringin2.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom collections import OrderedDict\nfrom torch.nn import init\nimport math\n\n\ndef conv_bn(inp, oup, stride):\n return nn.Sequential(\n nn.Conv2d(inp, oup, 3, stride, 1, bias=False),\n nn.BatchNorm2d(oup),\n nn.ReLU(inplace=True)\n )\n\n\ndef conv_1x1_bn(inp, oup):\n return nn.Sequential(\n nn.Conv2d(inp, oup, 1, 1, 0, bias=False),\n nn.BatchNorm2d(oup),\n nn.ReLU(inplace=True)\n )\n\n\ndef channel_shuffle(x, groups):\n batchsize, num_channels, height, width = x.data.size()\n\n channels_per_group = num_channels // groups\n\n # reshape\n x = x.view(batchsize, groups,\n channels_per_group, height, width)\n\n x = torch.transpose(x, 1, 2).contiguous()\n\n # flatten\n x = x.view(batchsize, -1, height, width)\n\n return x\n\n\nclass InvertedResidual(nn.Module):\n def __init__(self, inp, oup, stride, benchmodel):\n super(InvertedResidual, self).__init__()\n self.benchmodel = benchmodel\n self.stride = stride\n assert stride in [1, 2]\n\n oup_inc = oup // 2\n\n if self.benchmodel == 1:\n # assert inp == oup_inc\n self.banch2 = nn.Sequential(\n # pw\n nn.Conv2d(oup_inc, oup_inc, 1, 1, 0, bias=False),\n nn.BatchNorm2d(oup_inc),\n nn.ReLU(inplace=True),\n # dw\n nn.Conv2d(oup_inc, oup_inc, 3, stride, 1, groups=oup_inc, bias=False),\n nn.BatchNorm2d(oup_inc),\n # pw-linear\n nn.Conv2d(oup_inc, oup_inc, 1, 1, 0, bias=False),\n nn.BatchNorm2d(oup_inc),\n nn.ReLU(inplace=True),\n )\n else:\n self.banch1 = nn.Sequential(\n # dw\n nn.Conv2d(inp, inp, 3, stride, 1, groups=inp, bias=False),\n nn.BatchNorm2d(inp),\n # pw-linear\n nn.Conv2d(inp, oup_inc, 1, 1, 0, bias=False),\n nn.BatchNorm2d(oup_inc),\n nn.ReLU(inplace=True),\n )\n\n self.banch2 = nn.Sequential(\n # pw\n nn.Conv2d(inp, oup_inc, 1, 1, 0, bias=False),\n nn.BatchNorm2d(oup_inc),\n nn.ReLU(inplace=True),\n # dw\n nn.Conv2d(oup_inc, oup_inc, 3, stride, 1, groups=oup_inc, bias=False),\n nn.BatchNorm2d(oup_inc),\n # pw-linear\n nn.Conv2d(oup_inc, oup_inc, 1, 1, 0, bias=False),\n nn.BatchNorm2d(oup_inc),\n nn.ReLU(inplace=True),\n )\n\n @staticmethod\n def _concat(x, out):\n # concatenate along channel axis\n return torch.cat((x, out), 1)\n\n def forward(self, x):\n if 1 == self.benchmodel:\n x1 = x[:, :(x.shape[1] // 2), :, :]\n x2 = x[:, (x.shape[1] // 2):, :, :]\n out = self._concat(x1, self.banch2(x2))\n elif 2 == self.benchmodel:\n out = self._concat(self.banch1(x), self.banch2(x))\n\n return channel_shuffle(out, 2)\n\n\nclass ShuffleNetV2(nn.Module):\n def __init__(self, n_class=1000, input_size=224, width_mult=1.):\n super(ShuffleNetV2, self).__init__()\n\n assert input_size % 32 == 0\n\n self.stage_repeats = [4, 8, 4]\n # index 0 is invalid and should never be called.\n # only used for indexing convenience.\n if width_mult == 0.5:\n self.stage_out_channels = [-1, 24, 48, 96, 192, 1024]\n elif width_mult == 1.0:\n self.stage_out_channels = [-1, 24, 116, 232, 464, 1024]\n elif width_mult == 1.5:\n self.stage_out_channels = [-1, 24, 176, 352, 704, 1024]\n elif width_mult == 2.0:\n self.stage_out_channels = [-1, 24, 224, 488, 976, 2048]\n else:\n raise ValueError(\n \"\"\"{} groups is not supported for\n 1x1 Grouped Convolutions\"\"\".format(num_groups))\n\n # building first layer\n input_channel = self.stage_out_channels[1]\n self.conv1 = conv_bn(3, input_channel, 2)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n\n self.features = []\n # building inverted residual blocks\n for idxstage in range(len(self.stage_repeats)):\n numrepeat = self.stage_repeats[idxstage]\n output_channel = self.stage_out_channels[idxstage + 2]\n for i in range(numrepeat):\n if i == 0:\n # inp, oup, stride, benchmodel):\n self.features.append(InvertedResidual(input_channel, output_channel, 2, 2))\n else:\n self.features.append(InvertedResidual(input_channel, output_channel, 1, 1))\n input_channel = output_channel\n\n # make it nn.Sequential\n self.features = nn.Sequential(*self.features)\n\n # building last several layers\n self.conv_last = conv_1x1_bn(input_channel, self.stage_out_channels[-1])\n self.globalpool = nn.Sequential(nn.AvgPool2d(int(input_size / 32)))\n\n # building classifier\n self.classifier = nn.Sequential(nn.Linear(self.stage_out_channels[-1], n_class))\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.maxpool(x)\n x = self.features(x)\n x = self.conv_last(x)\n x = self.globalpool(x)\n x = x.view(-1, self.stage_out_channels[-1])\n x = self.classifier(x)\n return x\n\n\ndef shufflenetv2(width_mult=1.):\n model = ShuffleNetV2(width_mult=width_mult)\n return model\n\n\n\nmodel = ShuffleNetV2()\nprint(model)\n"
] | [
[
"torch.nn.Sequential",
"torch.transpose",
"torch.cat",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.nn.Linear",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
DinghaiZ/fastai2 | [
"7b5dd5e4e12a6f31c69bbeec0235103915beec2a"
] | [
"fastai2/vision/augment.py"
] | [
"# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/09_vision.augment.ipynb (unless otherwise specified).\n\n__all__ = ['RandTransform', 'TensorTypes', 'FlipItem', 'DihedralItem', 'PadMode', 'CropPad', 'RandomCrop',\n 'OldRandomCrop', 'ResizeMethod', 'Resize', 'RandomResizedCrop', 'AffineCoordTfm', 'RandomResizedCropGPU',\n 'affine_mat', 'mask_tensor', 'flip_mat', 'Flip', 'DeterministicDraw', 'DeterministicFlip', 'dihedral_mat',\n 'Dihedral', 'DeterministicDihedral', 'rotate_mat', 'Rotate', 'zoom_mat', 'Zoom', 'find_coeffs',\n 'apply_perspective', 'Warp', 'LightingTfm', 'Brightness', 'Contrast', 'cutout_gaussian', 'norm_apply_denorm',\n 'RandomErasing', 'setup_aug_tfms', 'aug_transforms']\n\n# Cell\nfrom ..data.all import *\nfrom .core import *\nfrom .data import *\n\n# Cell\nfrom torch import stack, zeros_like as t0, ones_like as t1\nfrom torch.distributions.bernoulli import Bernoulli\n\n# Cell\nclass RandTransform(Transform):\n \"A transform that before_call its state at each `__call__`\"\n do,nm,supports,split_idx = True,None,[],0\n def __init__(self, p=1., nm=None, before_call=None, **kwargs):\n super().__init__(**kwargs)\n self.p,self.before_call = p,ifnone(before_call,self.before_call)\n\n def before_call(self, b, split_idx):\n \"before_call the state for input `b`\"\n self.do = self.p==1. or random.random() < self.p\n\n def __call__(self, b, split_idx=None, **kwargs):\n self.before_call(b, split_idx=split_idx)\n return super().__call__(b, split_idx=split_idx, **kwargs) if self.do else b\n\n# Cell\ndef _neg_axis(x, axis):\n x[...,axis] = -x[...,axis]\n return x\n\nTensorTypes = (TensorImage,TensorMask,TensorPoint,TensorBBox)\n\n# Cell\n@patch\ndef flip_lr(x:Image.Image): return x.transpose(Image.FLIP_LEFT_RIGHT)\n@patch\ndef flip_lr(x:TensorImageBase): return x.flip(-1)\n@patch\ndef flip_lr(x:TensorPoint): return TensorPoint(_neg_axis(x.clone(), 0))\n@patch\ndef flip_lr(x:TensorBBox): return TensorBBox(TensorPoint(x.view(-1,2)).flip_lr().view(-1,4))\n\n# Cell\nclass FlipItem(RandTransform):\n \"Randomly flip with probability `p`\"\n def __init__(self, p=0.5): super().__init__(p=p)\n def encodes(self, x:(Image.Image,*TensorTypes)): return x.flip_lr()\n\n# Cell\n@patch\ndef dihedral(x:PILImage, k): return x if k==0 else x.transpose(k-1)\n@patch\ndef dihedral(x:TensorImage, k):\n if k in [1,3,4,7]: x = x.flip(-1)\n if k in [2,4,5,7]: x = x.flip(-2)\n if k in [3,5,6,7]: x = x.transpose(-1,-2)\n return x\n@patch\ndef dihedral(x:TensorPoint, k):\n if k in [1,3,4,7]: x = _neg_axis(x, 0)\n if k in [2,4,5,7]: x = _neg_axis(x, 1)\n if k in [3,5,6,7]: x = x.flip(1)\n return x\n@patch\ndef dihedral(x:TensorBBox, k):\n pnts = TensorPoint(x.view(-1,2)).dihedral(k).view(-1,2,2)\n tl,br = pnts.min(dim=1)[0],pnts.max(dim=1)[0]\n return TensorBBox(torch.cat([tl, br], dim=1), img_size=x.get_meta('img_size'))\n\n# Cell\nclass DihedralItem(RandTransform):\n \"Randomly flip with probability `p`\"\n def __init__(self, p=0.5): super().__init__(p=p)\n\n def before_call(self, b, split_idx):\n super().before_call(b, split_idx)\n self.k = random.randint(0,7)\n\n def encodes(self, x:(Image.Image,*TensorTypes)): return x.dihedral(self.k)\n\n# Cell\nfrom torchvision.transforms.functional import pad as tvpad\n\n# Cell\nmk_class('PadMode', **{o:o.lower() for o in ['Zeros', 'Border', 'Reflection']},\n doc=\"All possible padding mode as attributes to get tab-completion and typo-proofing\")\n\n# Cell\n_pad_modes = {'zeros': 'constant', 'border': 'edge', 'reflection': 'reflect'}\n\n@patch\ndef _do_crop_pad(x:Image.Image, sz, tl, orig_sz,\n pad_mode=PadMode.Zeros, resize_mode=Image.BILINEAR, resize_to=None):\n if any(tl.ge(0)):\n # At least one dim is inside the image, so needs to be cropped\n c = tl.max(0)\n x = x.crop((*c, *c.add(sz).min(orig_sz)))\n if any(tl.lt(0)):\n # At least one dim is outside the image, so needs to be padded\n p = (-tl).max(0)\n f = (sz-orig_sz-p).max(0)\n x = tvpad(x, (*p, *f), padding_mode=_pad_modes[pad_mode])\n if resize_to is not None: x = x.resize(resize_to, resize_mode)\n return x\n\n@patch\ndef _do_crop_pad(x:TensorPoint, sz, tl, orig_sz, pad_mode=PadMode.Zeros, resize_to=None, **kwargs):\n #assert pad_mode==PadMode.Zeros,\"Only zero padding is supported for `TensorPoint` and `TensorBBox`\"\n orig_sz,sz,tl = map(FloatTensor, (orig_sz,sz,tl))\n return TensorPoint((x+1)*orig_sz/sz - tl*2/sz - 1, sz=sz if resize_to is None else resize_to)\n\n@patch\ndef _do_crop_pad(x:TensorBBox, sz, tl, orig_sz, pad_mode=PadMode.Zeros, resize_to=None, **kwargs):\n bbox = TensorPoint._do_crop_pad(x.view(-1,2), sz, tl, orig_sz, pad_mode, resize_to).view(-1,4)\n return TensorBBox(bbox, img_size=x.get_meta('img_size'))\n\n@patch\ndef crop_pad(x:(TensorBBox,TensorPoint,Image.Image),\n sz, tl=None, orig_sz=None, pad_mode=PadMode.Zeros, resize_mode=Image.BILINEAR, resize_to=None):\n if isinstance(sz,int): sz = (sz,sz)\n orig_sz = Tuple(x.size if orig_sz is None else orig_sz)\n sz,tl = Tuple(sz),Tuple(((x.size-sz)//2) if tl is None else tl)\n return x._do_crop_pad(sz, tl, orig_sz=orig_sz, pad_mode=pad_mode, resize_mode=resize_mode, resize_to=resize_to)\n\n# Cell\ndef _process_sz(size):\n if isinstance(size,int): size=(size,size)\n return Tuple(size[1],size[0])\n\ndef _get_sz(x):\n if isinstance(x, tuple): x = x[0]\n if not isinstance(x, Tensor): return Tuple(x.size)\n return Tuple(x.get_meta('img_size', (x.shape[-1], x.shape[-2])))\n\n# Cell\n@delegates()\nclass CropPad(Transform):\n \"Center crop or pad an image to `size`\"\n order=5\n def __init__(self, size, pad_mode=PadMode.Zeros, **kwargs):\n super().__init__(**kwargs)\n self.size,self.pad_mode = _process_sz(size),pad_mode\n\n def encodes(self, x:(Image.Image,TensorBBox,TensorPoint)):\n orig_sz = _get_sz(x)\n tl = (orig_sz-self.size)//2\n return x.crop_pad(self.size, tl, orig_sz=orig_sz, pad_mode=self.pad_mode)\n\n# Cell\n@delegates()\nclass RandomCrop(RandTransform):\n \"Randomly crop an image to `size`\"\n split_idx = None\n order = 6\n def __init__(self, size, **kwargs):\n super().__init__(**kwargs)\n self.size = _process_sz(size)\n\n def before_call(self, b, split_idx):\n self.orig_sz = _get_sz(b)\n if split_idx: self.tl = (self.orig_sz-self.size)//2\n else: self.tl = Tuple(random.randint(0,self.orig_sz[0]-self.size[0]), random.randint(0,self.orig_sz[1]-self.size[1]))\n\n def encodes(self, x:(Image.Image,TensorBBox,TensorPoint)):\n return x.crop_pad(self.size, self.tl, orig_sz=self.orig_sz)\n\n# Cell\nclass OldRandomCrop(CropPad):\n \"Randomly crop an image to `size`\"\n def before_call(self, b, split_idx):\n super().before_call(b, split_idx)\n w,h = self.orig_sz\n if not split_idx: self.tl = (random.randint(0,w-self.cp_size[0]), random.randint(0,h-self.cp_size[1]))\n\n# Cell\nmk_class('ResizeMethod', **{o:o.lower() for o in ['Squish', 'Crop', 'Pad']},\n doc=\"All possible resize method as attributes to get tab-completion and typo-proofing\")\n\n# Cell\n@delegates()\nclass Resize(RandTransform):\n split_idx = None\n mode,mode_mask,order,final_size = Image.BILINEAR,Image.NEAREST,10,None\n \"Resize image to `size` using `method`\"\n def __init__(self, size, method=ResizeMethod.Squish, pad_mode=PadMode.Reflection,\n resamples=(Image.BILINEAR, Image.NEAREST), **kwargs):\n super().__init__(**kwargs)\n self.size,self.pad_mode,self.method = _process_sz(size),pad_mode,method\n self.mode,self.mode_mask = resamples\n\n def before_call(self, b, split_idx):\n if self.method==ResizeMethod.Squish: return\n self.pcts = (0.5,0.5) if split_idx else (random.random(),random.random())\n\n def encodes(self, x:(Image.Image,TensorBBox,TensorPoint)):\n orig_sz = _get_sz(x)\n self.final_size = self.size\n if self.method==ResizeMethod.Squish:\n return x.crop_pad(orig_sz, Tuple(0,0), orig_sz=orig_sz, pad_mode=self.pad_mode,\n resize_mode=self.mode_mask if isinstance(x,PILMask) else self.mode, resize_to=self.size)\n\n w,h = orig_sz\n op = (operator.lt,operator.gt)[self.method==ResizeMethod.Pad]\n m = w/self.size[0] if op(w/self.size[0],h/self.size[1]) else h/self.size[1]\n cp_sz = (int(m*self.size[0]),int(m*self.size[1]))\n tl = Tuple(int(self.pcts[0]*(w-cp_sz[0])), int(self.pcts[1]*(h-cp_sz[1])))\n return x.crop_pad(cp_sz, tl, orig_sz=orig_sz, pad_mode=self.pad_mode,\n resize_mode=self.mode_mask if isinstance(x,PILMask) else self.mode, resize_to=self.size)\n\n# Cell\n@delegates()\nclass RandomResizedCrop(RandTransform):\n \"Picks a random scaled crop of an image and resize it to `size`\"\n split_idx = None\n def __init__(self, size, min_scale=0.08, ratio=(3/4, 4/3), resamples=(Image.BILINEAR, Image.NEAREST),\n val_xtra=0.14, **kwargs):\n super().__init__(**kwargs)\n self.size = _process_sz(size)\n store_attr(self, 'min_scale,ratio,val_xtra')\n self.mode,self.mode_mask = resamples\n\n def before_call(self, b, split_idx):\n w,h = self.orig_sz = _get_sz(b)\n if split_idx:\n xtra = math.ceil(max(*self.size[:2])*self.val_xtra/8)*8\n self.final_size = (self.size[0]+xtra, self.size[1]+xtra)\n self.tl,self.cp_size = (0,0),self.orig_sz\n return\n self.final_size = self.size\n for attempt in range(10):\n area = random.uniform(self.min_scale,1.) * w * h\n ratio = math.exp(random.uniform(math.log(self.ratio[0]), math.log(self.ratio[1])))\n nw = int(round(math.sqrt(area * ratio)))\n nh = int(round(math.sqrt(area / ratio)))\n if nw <= w and nh <= h:\n self.cp_size = (nw,nh)\n self.tl = random.randint(0,w-nw), random.randint(0,h - nh)\n return\n if w/h < self.ratio[0]: self.cp_size = (w, int(w/self.ratio[0]))\n elif w/h > self.ratio[1]: self.cp_size = (int(h*self.ratio[1]), h)\n else: self.cp_size = (w, h)\n self.tl = ((w-self.cp_size[0])//2, (h-self.cp_size[1])//2)\n\n def encodes(self, x:(Image.Image,TensorBBox,TensorPoint)):\n res = x.crop_pad(self.cp_size, self.tl, orig_sz=self.orig_sz,\n resize_mode=self.mode_mask if isinstance(x,PILMask) else self.mode, resize_to=self.final_size)\n if self.final_size != self.size: res = res.crop_pad(self.size) #Validation set: one final center crop\n return res\n\n# Cell\ndef _init_mat(x):\n mat = torch.eye(3, device=x.device).float()\n return mat.unsqueeze(0).expand(x.size(0), 3, 3).contiguous()\n\n# Cell\nwarnings.filterwarnings(\"ignore\", category=UserWarning, module=\"torch.nn.functional\")\ndef _grid_sample(x, coords, mode='bilinear', padding_mode='reflection'):\n \"Resample pixels in `coords` from `x` by `mode`, with `padding_mode` in ('reflection','border','zeros').\"\n #coords = coords.permute(0, 3, 1, 2).contiguous().permute(0, 2, 3, 1) # optimize layout for grid_sample\n if mode=='bilinear': # hack to get smoother downwards resampling\n mn,mx = coords.min(),coords.max()\n # max amount we're affine zooming by (>1 means zooming in)\n z = 1/(mx-mn).item()*2\n # amount we're resizing by, with 100% extra margin\n d = min(x.shape[-2]/coords.shape[-2], x.shape[-1]/coords.shape[-1])/2\n # If we're resizing up by >200%, and we're zooming less than that, interpolate first\n if d>1 and d>z:\n x = F.interpolate(x, scale_factor=1/d, mode='area')\n with warnings.catch_warnings():\n #To avoid the warning that come from grid_sample.\n warnings.simplefilter(\"ignore\")\n return F.grid_sample(x, coords, mode=mode, padding_mode=padding_mode)\n\n# Cell\n@patch\ndef affine_coord(x: TensorImage, mat=None, coord_tfm=None, sz=None, mode='bilinear', pad_mode=PadMode.Reflection):\n if mat is None and coord_tfm is None and sz is None: return x\n size = tuple(x.shape[-2:]) if sz is None else (sz,sz) if isinstance(sz,int) else tuple(sz)\n if mat is None: mat = _init_mat(x)[:,:2]\n coords = F.affine_grid(mat, x.shape[:2] + size)\n if coord_tfm is not None: coords = coord_tfm(coords)\n return TensorImage(_grid_sample(x, coords, mode=mode, padding_mode=pad_mode))\n\n@patch\ndef affine_coord(x: TensorMask, mat=None, coord_tfm=None, sz=None, mode='nearest', pad_mode=PadMode.Reflection):\n add_dim = (x.ndim==3)\n if add_dim: x = x[:,None]\n res = TensorImage.affine_coord(x.float(), mat, coord_tfm, sz, mode, pad_mode).long()\n if add_dim: res = res[:,0]\n return TensorMask(res)\n\n@patch\ndef affine_coord(x: TensorPoint, mat=None, coord_tfm=None, sz=None, mode='nearest', pad_mode=PadMode.Zeros):\n #assert pad_mode==PadMode.Zeros, \"Only zero padding is supported for `TensorPoint` and `TensorBBox`\"\n if sz is None: sz = x.get_meta('img_size')\n if coord_tfm is not None: x = coord_tfm(x, invert=True)\n if mat is not None: x = (x - mat[:,:,2].unsqueeze(1)) @ torch.inverse(mat[:,:,:2].transpose(1,2))\n return TensorPoint(x, sz=sz)\n\n@patch\ndef affine_coord(x: TensorBBox, mat=None, coord_tfm=None, sz=None, mode='nearest', pad_mode=PadMode.Zeros):\n if mat is None and coord_tfm is None: return x\n if sz is None: sz = x.get_meta('img_size')\n bs,n = x.shape[:2]\n pnts = stack([x[...,:2], stack([x[...,0],x[...,3]],dim=2),\n stack([x[...,2],x[...,1]],dim=2), x[...,2:]], dim=2)\n pnts = TensorPoint(pnts.view(bs, 4*n, 2), img_size=sz).affine_coord(mat, coord_tfm, sz, mode, pad_mode)\n pnts = pnts.view(bs, n, 4, 2)\n tl,dr = pnts.min(dim=2)[0],pnts.max(dim=2)[0]\n return TensorBBox(torch.cat([tl, dr], dim=2), img_size=sz)\n\n# Cell\ndef _prepare_mat(x, mat):\n h,w = x.get_meta('img_size', x.shape[-2:])\n mat[:,0,1] *= h/w\n mat[:,1,0] *= w/h\n return mat[:,:2]\n\n# Cell\nclass AffineCoordTfm(RandTransform):\n \"Combine and apply affine and coord transforms\"\n order,split_idx = 30,None\n def __init__(self, aff_fs=None, coord_fs=None, size=None, mode='bilinear', pad_mode=PadMode.Reflection, mode_mask='nearest'):\n self.aff_fs,self.coord_fs = L(aff_fs),L(coord_fs)\n store_attr(self, 'size,mode,pad_mode,mode_mask')\n self.cp_size = None if size is None else (size,size) if isinstance(size, int) else tuple(size)\n\n def before_call(self, b, split_idx):\n if isinstance(b, tuple): b = b[0]\n self.split_idx = split_idx\n self.do,self.mat = True,self._get_affine_mat(b)\n for t in self.coord_fs: t.before_call(b)\n\n def compose(self, tfm):\n \"Compose `self` with another `AffineCoordTfm` to only do the interpolation step once\"\n self.aff_fs += tfm.aff_fs\n self.coord_fs += tfm.coord_fs\n\n def _get_affine_mat(self, x):\n aff_m = _init_mat(x)\n if self.split_idx: return _prepare_mat(x, aff_m)\n ms = [f(x) for f in self.aff_fs]\n ms = [m for m in ms if m is not None]\n for m in ms: aff_m = aff_m @ m\n return _prepare_mat(x, aff_m)\n\n def _encode(self, x, mode, reverse=False):\n coord_func = None if len(self.coord_fs)==0 or self.split_idx else partial(compose_tfms, tfms=self.coord_fs, reverse=reverse)\n return x.affine_coord(self.mat, coord_func, sz=self.size, mode=mode, pad_mode=self.pad_mode)\n\n def encodes(self, x:TensorImage): return self._encode(x, self.mode)\n def encodes(self, x:TensorMask): return self._encode(x, self.mode_mask)\n def encodes(self, x:(TensorPoint, TensorBBox)): return self._encode(x, self.mode, reverse=True)\n\n# Cell\nclass RandomResizedCropGPU(RandTransform):\n \"Picks a random scaled crop of an image and resize it to `size`\"\n split_idx,order = None,30\n def __init__(self, size, min_scale=0.08, ratio=(3/4, 4/3), mode='bilinear', valid_scale=1., **kwargs):\n super().__init__(**kwargs)\n self.size = (size,size) if isinstance(size, int) else size\n store_attr(self, 'min_scale,ratio,mode,valid_scale')\n\n def before_call(self, b, split_idx):\n self.do = True\n h,w = Tuple((b[0] if isinstance(b, tuple) else b).shape[-2:])\n for attempt in range(10):\n if split_idx: break\n area = random.uniform(self.min_scale,1.) * w * h\n ratio = math.exp(random.uniform(math.log(self.ratio[0]), math.log(self.ratio[1])))\n nw = int(round(math.sqrt(area * ratio)))\n nh = int(round(math.sqrt(area / ratio)))\n if nw <= w and nh <= h:\n self.cp_size = (nh,nw)\n self.tl = random.randint(0,h - nh),random.randint(0,w-nw)\n return\n if w/h < self.ratio[0]: self.cp_size = (int(w/self.ratio[0]), w)\n elif w/h > self.ratio[1]: self.cp_size = (h, int(h*self.ratio[1]))\n else: self.cp_size = (h, w)\n if split_idx: self.cp_size = (int(self.cp_size[0]*self.valid_scale), int(self.cp_size[1]*self.valid_scale))\n self.tl = ((h-self.cp_size[0])//2,(w-self.cp_size[1])//2)\n\n def encodes(self, x:TensorImage):\n x = x[...,self.tl[0]:self.tl[0]+self.cp_size[0], self.tl[1]:self.tl[1]+self.cp_size[1]]\n return TensorImage(x).affine_coord(sz=self.size, mode=self.mode)\n\n# Cell\ndef affine_mat(*ms):\n \"Restructure length-6 vector `ms` into an affine matrix with 0,0,1 in the last line\"\n return stack([stack([ms[0], ms[1], ms[2]], dim=1),\n stack([ms[3], ms[4], ms[5]], dim=1),\n stack([t0(ms[0]), t0(ms[0]), t1(ms[0])], dim=1)], dim=1)\n\n# Cell\ndef mask_tensor(x, p=0.5, neutral=0., batch=False):\n \"Mask elements of `x` with `neutral` with probability `1-p`\"\n if p==1.: return x\n if batch: return x if random.random() < p else x.new_zeros(*x.size()) + neutral\n if neutral != 0: x.add_(-neutral)\n mask = x.new_empty(*x.size()).bernoulli_(p)\n x.mul_(mask)\n return x.add_(neutral) if neutral != 0 else x\n\n# Cell\ndef _draw_mask(x, def_draw, draw=None, p=0.5, neutral=0., batch=False):\n if draw is None: draw=def_draw\n if callable(draw): res=draw(x)\n elif is_listy(draw):\n test_eq(len(draw), x.size(0))\n res = tensor(draw, dtype=x.dtype, device=x.device)\n else: res = x.new_zeros(x.size(0)) + draw\n return mask_tensor(res, p=p, neutral=neutral, batch=batch)\n\n# Cell\ndef flip_mat(x, p=0.5, draw=None, batch=False):\n \"Return a random flip matrix\"\n def _def_draw(x): return x.new_ones(x.size(0))\n mask = x.new_ones(x.size(0)) - 2*_draw_mask(x, _def_draw, draw=draw, p=p, batch=batch)\n #mask = mask_tensor(-x.new_ones(x.size(0)), p=p, neutral=1.)\n return affine_mat(mask, t0(mask), t0(mask),\n t0(mask), t1(mask), t0(mask))\n\n# Cell\ndef _get_default(x, mode=None, pad_mode=None):\n if mode is None: mode='bilinear' if isinstance(x, TensorMask) else 'bilinear'\n if pad_mode is None: pad_mode=PadMode.Zeros if isinstance(x, (TensorPoint, TensorBBox)) else PadMode.Reflection\n x0 = x[0] if isinstance(x, tuple) else x\n return x0,mode,pad_mode\n\n# Cell\n@patch\ndef flip_batch(x: (TensorImage,TensorMask,TensorPoint,TensorBBox), p=0.5, draw=None, size=None,\n mode=None, pad_mode=None, batch=False):\n x0,mode,pad_mode = _get_default(x, mode, pad_mode)\n mat=flip_mat(x0, p=p, draw=draw, batch=batch)\n return x.affine_coord(mat=mat[:,:2], sz=size, mode=mode, pad_mode=pad_mode)\n\n# Cell\ndef Flip(p=0.5, draw=None, size=None, mode='bilinear', pad_mode=PadMode.Reflection, batch=False):\n \"Randomly flip a batch of images with a probability `p`\"\n return AffineCoordTfm(aff_fs=partial(flip_mat, p=p, draw=draw, batch=batch), size=size, mode=mode, pad_mode=pad_mode)\n\n# Cell\nclass DeterministicDraw():\n def __init__(self, vals):\n store_attr(self, 'vals')\n self.count=-1\n\n def __call__(self, x):\n self.count += 1\n return x.new_zeros(x.size(0)) + self.vals[self.count%len(self.vals)]\n\n# Cell\ndef DeterministicFlip(size=None, mode='bilinear', pad_mode=PadMode.Reflection):\n \"Flip the batch every other call\"\n return Flip(p=1., draw=DeterministicDraw([0,1]))\n\n# Cell\ndef dihedral_mat(x, p=0.5, draw=None, batch=False):\n \"Return a random dihedral matrix\"\n def _def_draw(x): return torch.randint(0,8, (x.size(0),), device=x.device)\n def _def_draw_b(x): return random.randint(0,7) + x.new_zeros((x.size(0),)).long()\n idx = _draw_mask(x, _def_draw_b if batch else _def_draw, draw=draw, p=p, batch=batch).long()\n xs = tensor([1,-1,1,-1,-1,1,1,-1], device=x.device).gather(0, idx)\n ys = tensor([1,1,-1,1,-1,-1,1,-1], device=x.device).gather(0, idx)\n m0 = tensor([1,1,1,0,1,0,0,0], device=x.device).gather(0, idx)\n m1 = tensor([0,0,0,1,0,1,1,1], device=x.device).gather(0, idx)\n return affine_mat(xs*m0, xs*m1, t0(xs),\n ys*m1, ys*m0, t0(xs)).float()\n\n# Cell\n@patch\ndef dihedral_batch(x: (TensorImage,TensorMask,TensorPoint,TensorBBox), p=0.5, draw=None, size=None,\n mode=None, pad_mode=None, batch=False):\n x0,mode,pad_mode = _get_default(x, mode, pad_mode)\n mat = _prepare_mat(x, dihedral_mat(x0, p=p, draw=draw, batch=batch))\n return x.affine_coord(mat=mat, sz=size, mode=mode, pad_mode=pad_mode)\n\n# Cell\ndef Dihedral(p=0.5, draw=None, size=None, mode='bilinear', pad_mode=PadMode.Reflection, batch=False):\n \"Apply a random dihedral transformation to a batch of images with a probability `p`\"\n f = partial(dihedral_mat, p=p, draw=draw, batch=batch)\n return AffineCoordTfm(aff_fs=f, size=size, mode=mode, pad_mode=pad_mode)\n\n# Cell\ndef DeterministicDihedral(size=None, mode='bilinear', pad_mode=PadMode.Reflection):\n \"Flip the batch every other call\"\n return Dihedral(p=1., draw=DeterministicDraw(list(range(8))))\n\n# Cell\ndef rotate_mat(x, max_deg=10, p=0.5, draw=None, batch=False):\n \"Return a random rotation matrix with `max_deg` and `p`\"\n def _def_draw(x): return x.new(x.size(0)).uniform_(-max_deg, max_deg)\n def _def_draw_b(x): return x.new_zeros(x.size(0)) + random.uniform(-max_deg, max_deg)\n thetas = _draw_mask(x, _def_draw_b if batch else _def_draw, draw=draw, p=p, batch=batch) * math.pi/180\n return affine_mat(thetas.cos(), thetas.sin(), t0(thetas),\n -thetas.sin(), thetas.cos(), t0(thetas))\n\n# Cell\n@delegates(rotate_mat)\n@patch\ndef rotate(x: (TensorImage,TensorMask,TensorPoint,TensorBBox), size=None, mode=None, pad_mode=None, **kwargs):\n x0,mode,pad_mode = _get_default(x, mode, pad_mode)\n mat = _prepare_mat(x, rotate_mat(x0, **kwargs))\n return x.affine_coord(mat=mat, sz=size, mode=mode, pad_mode=pad_mode)\n\n# Cell\ndef Rotate(max_deg=10, p=0.5, draw=None, size=None, mode='bilinear', pad_mode=PadMode.Reflection, batch=False):\n \"Apply a random rotation of at most `max_deg` with probability `p` to a batch of images\"\n return AffineCoordTfm(partial(rotate_mat, max_deg=max_deg, p=p, draw=draw, batch=batch),\n size=size, mode=mode, pad_mode=pad_mode)\n\n# Cell\ndef zoom_mat(x, max_zoom=1.1, p=0.5, draw=None, draw_x=None, draw_y=None, batch=False):\n \"Return a random zoom matrix with `max_zoom` and `p`\"\n def _def_draw(x): return x.new(x.size(0)).uniform_(1, max_zoom)\n def _def_draw_b(x): return x.new_zeros(x.size(0)) + random.uniform(1, max_zoom)\n def _def_draw_ctr(x): return x.new(x.size(0)).uniform_(0,1)\n def _def_draw_ctr_b(x): return x.new_zeros(x.size(0)) + random.uniform(0,1)\n s = 1/_draw_mask(x, _def_draw_b if batch else _def_draw, draw=draw, p=p, neutral=1., batch=batch)\n def_draw_c = _def_draw_ctr_b if batch else _def_draw_ctr\n col_pct = _draw_mask(x, def_draw_c, draw=draw_x, p=1., batch=batch)\n row_pct = _draw_mask(x, def_draw_c, draw=draw_y, p=1., batch=batch)\n col_c = (1-s) * (2*col_pct - 1)\n row_c = (1-s) * (2*row_pct - 1)\n return affine_mat(s, t0(s), col_c,\n t0(s), s, row_c)\n\n# Cell\n@delegates(zoom_mat)\n@patch\ndef zoom(x: (TensorImage,TensorMask,TensorPoint,TensorBBox), size=None, mode='bilinear', pad_mode=PadMode.Reflection, **kwargs):\n x0,mode,pad_mode = _get_default(x, mode, pad_mode)\n return x.affine_coord(mat=zoom_mat(x0, **kwargs)[:,:2], sz=size, mode=mode, pad_mode=pad_mode)\n\n# Cell\ndef Zoom(max_zoom=1.1, p=0.5, draw=None, draw_x=None, draw_y=None, size=None, mode='bilinear',\n pad_mode=PadMode.Reflection, batch=False):\n \"Apply a random zoom of at most `max_zoom` with probability `p` to a batch of images\"\n return AffineCoordTfm(partial(zoom_mat, max_zoom=max_zoom, p=p, draw=draw, draw_x=draw_x, draw_y=draw_y, batch=batch),\n size=size, mode=mode, pad_mode=pad_mode)\n\n# Cell\ndef find_coeffs(p1, p2):\n \"Find coefficients for warp tfm from `p1` to `p2`\"\n m = []\n p = p1[:,0,0]\n #The equations we'll need to solve.\n for i in range(p1.shape[1]):\n m.append(stack([p2[:,i,0], p2[:,i,1], t1(p), t0(p), t0(p), t0(p), -p1[:,i,0]*p2[:,i,0], -p1[:,i,0]*p2[:,i,1]]))\n m.append(stack([t0(p), t0(p), t0(p), p2[:,i,0], p2[:,i,1], t1(p), -p1[:,i,1]*p2[:,i,0], -p1[:,i,1]*p2[:,i,1]]))\n #The 8 scalars we seek are solution of AX = B\n A = stack(m).permute(2, 0, 1)\n B = p1.view(p1.shape[0], 8, 1)\n return torch.solve(B,A)[0]\n\n# Cell\ndef apply_perspective(coords, coeffs):\n \"Apply perspective tranfom on `coords` with `coeffs`\"\n sz = coords.shape\n coords = coords.view(sz[0], -1, 2)\n coeffs = torch.cat([coeffs, t1(coeffs[:,:1])], dim=1).view(coeffs.shape[0], 3,3)\n coords = coords @ coeffs[...,:2].transpose(1,2) + coeffs[...,2].unsqueeze(1)\n coords = coords/coords[...,2].unsqueeze(-1)\n return coords[...,:2].view(*sz)\n\n# Cell\nclass _WarpCoord():\n def __init__(self, magnitude=0.2, p=0.5, draw_x=None, draw_y=None, batch=False):\n store_attr(self, \"magnitude,p,draw_x,draw_y,batch\")\n self.coeffs = None\n\n def _def_draw(self, x):\n if not self.batch: return x.new(x.size(0)).uniform_(-self.magnitude, self.magnitude)\n return x.new_zeros(x.size(0)) + random.uniform(-self.magnitude, self.magnitude)\n\n def before_call(self, x):\n x_t = _draw_mask(x, self._def_draw, self.draw_x, p=self.p, batch=self.batch)\n y_t = _draw_mask(x, self._def_draw, self.draw_y, p=self.p, batch=self.batch)\n orig_pts = torch.tensor([[-1,-1], [-1,1], [1,-1], [1,1]], dtype=x.dtype, device=x.device)\n self.orig_pts = orig_pts.unsqueeze(0).expand(x.size(0),4,2)\n targ_pts = stack([stack([-1-y_t, -1-x_t]), stack([-1+y_t, 1+x_t]),\n stack([ 1+y_t, -1+x_t]), stack([ 1-y_t, 1-x_t])])\n self.targ_pts = targ_pts.permute(2,0,1)\n\n def __call__(self, x, invert=False):\n coeffs = find_coeffs(self.targ_pts, self.orig_pts) if invert else find_coeffs(self.orig_pts, self.targ_pts)\n return apply_perspective(x, coeffs)\n\n# Cell\n@delegates(_WarpCoord.__init__)\n@patch\ndef warp(x:(TensorImage,TensorMask,TensorPoint,TensorBBox), size=None, mode='bilinear',\n pad_mode=PadMode.Reflection, **kwargs):\n x0,mode,pad_mode = _get_default(x, mode, pad_mode)\n coord_tfm = _WarpCoord(**kwargs)\n coord_tfm.before_call(x0)\n return x.affine_coord(coord_tfm=coord_tfm, sz=size, mode=mode, pad_mode=pad_mode)\n\n# Cell\ndef Warp(magnitude=0.2, p=0.5, draw_x=None, draw_y=None,size=None, mode='bilinear',\n pad_mode=PadMode.Reflection, batch=False):\n \"Apply perspective warping with `magnitude` and `p` on a batch of matrices\"\n return AffineCoordTfm(coord_fs=_WarpCoord(magnitude=magnitude, p=p, draw_x=draw_x, draw_y=draw_y, batch=batch),\n size=size, mode=mode, pad_mode=pad_mode)\n\n# Cell\n@patch\ndef lighting(x: TensorImage, func):\n return TensorImage(torch.sigmoid(func(logit(x))))\n\n# Cell\nclass LightingTfm(RandTransform):\n \"Apply `fs` to the logits\"\n order = 40\n def __init__(self, fs): self.fs=L(fs)\n def before_call(self, b, split_idx):\n self.do = True\n if isinstance(b, tuple): b = b[0]\n for t in self.fs: t.before_call(b)\n\n def compose(self, tfm):\n \"Compose `self` with another `LightingTransform`\"\n self.fs += tfm.fs\n\n def encodes(self,x:TensorImage): return x.lighting(partial(compose_tfms, tfms=self.fs))\n\n# Cell\nclass _BrightnessLogit():\n def __init__(self, max_lighting=0.2, p=0.75, draw=None, batch=False):\n store_attr(self, 'max_lighting,p,draw,batch')\n\n def _def_draw(self, x):\n if not self.batch: return x.new(x.size(0)).uniform_(0.5*(1-self.max_lighting), 0.5*(1+self.max_lighting))\n return x.new_zeros(x.size(0)) + random.uniform(0.5*(1-self.max_lighting), 0.5*(1+self.max_lighting))\n\n def before_call(self, x):\n self.change = _draw_mask(x, self._def_draw, draw=self.draw, p=self.p, neutral=0.5, batch=self.batch)\n\n def __call__(self, x): return x.add_(logit(self.change[:,None,None,None]))\n\n# Cell\n@delegates(_BrightnessLogit.__init__)\n@patch\ndef brightness(x: TensorImage, **kwargs):\n func = _BrightnessLogit(**kwargs)\n func.before_call(x)\n return x.lighting(func)\n\n# Cell\ndef Brightness(max_lighting=0.2, p=0.75, draw=None, batch=False):\n \"Apply change in brightness of `max_lighting` to batch of images with probability `p`.\"\n return LightingTfm(_BrightnessLogit(max_lighting, p, draw, batch))\n\n# Cell\nclass _ContrastLogit():\n def __init__(self, max_lighting=0.2, p=0.75, draw=None, batch=False):\n store_attr(self, 'max_lighting,p,draw,batch')\n\n def _def_draw(self, x):\n if not self.batch: res = x.new(x.size(0)).uniform_(math.log(1-self.max_lighting), -math.log(1-self.max_lighting))\n else: res = x.new_zeros(x.size(0)) + random.uniform(math.log(1-self.max_lighting), -math.log(1-self.max_lighting))\n return torch.exp(res)\n\n def before_call(self, x):\n self.change = _draw_mask(x, self._def_draw, draw=self.draw, p=self.p, neutral=1., batch=self.batch)\n\n def __call__(self, x): return x.mul_(self.change[:,None,None,None])\n\n# Cell\n@delegates(_ContrastLogit.__init__)\n@patch\ndef contrast(x: TensorImage, **kwargs):\n func = _ContrastLogit(**kwargs)\n func.before_call(x)\n return x.lighting(func)\n\n# Cell\ndef Contrast(max_lighting=0.2, p=0.75, draw=None, batch=False):\n \"Apply change in contrast of `max_lighting` to batch of images with probability `p`.\"\n return LightingTfm(_ContrastLogit(max_lighting, p, draw, batch))\n\n# Cell\ndef cutout_gaussian(x, areas):\n \"Replace all `areas` in `x` with N(0,1) noise\"\n chan,img_h,img_w = x.shape[-3:]\n for rl,rh,cl,ch in areas: x[..., rl:rh, cl:ch].normal_()\n return x\n\n# Cell\ndef norm_apply_denorm(x, f, nrm):\n \"Normalize `x` with `nrm`, then apply `f`, then denormalize\"\n y = f(nrm(x.clone()))\n return nrm.decode(y).clamp(0,1)\n\n# Cell\ndef _slice(area, sz):\n bound = int(round(math.sqrt(area)))\n loc = random.randint(0, max(sz-bound, 0))\n return loc,loc+bound\n\n# Cell\nclass RandomErasing(RandTransform):\n \"Randomly selects a rectangle region in an image and randomizes its pixels.\"\n order = 100 # After Normalize\n def __init__(self, p=0.5, sl=0., sh=0.3, min_aspect=0.3, max_count=1):\n super().__init__(p=p)\n log_ratio = (math.log(min_aspect), math.log(1/min_aspect))\n store_attr(self, 'sl,sh,log_ratio,max_count')\n\n def _bounds(self, area, img_h, img_w):\n r_area = random.uniform(self.sl,self.sh) * area\n aspect = math.exp(random.uniform(*self.log_ratio))\n return _slice(r_area*aspect, img_h) + _slice(r_area/aspect, img_w)\n\n def encodes(self,x:TensorImage):\n count = random.randint(1, self.max_count)\n _,img_h,img_w = x.shape[-3:]\n area = img_h*img_w/count\n areas = [self._bounds(area, img_h, img_w) for _ in range(count)]\n return cutout_gaussian(x, areas)\n\n# Cell\ndef _compose_same_tfms(tfms):\n tfms = L(tfms)\n if len(tfms) == 0: return None\n res = tfms[0]\n for tfm in tfms[1:]: res.compose(tfm)\n return res\n\n# Cell\ndef setup_aug_tfms(tfms):\n \"Go through `tfms` and combines together affine/coord or lighting transforms\"\n aff_tfms = [tfm for tfm in tfms if isinstance(tfm, AffineCoordTfm)]\n lig_tfms = [tfm for tfm in tfms if isinstance(tfm, LightingTfm)]\n others = [tfm for tfm in tfms if tfm not in aff_tfms+lig_tfms]\n aff_tfm,lig_tfm = _compose_same_tfms(aff_tfms),_compose_same_tfms(lig_tfms)\n res = [aff_tfm] if aff_tfm is not None else []\n if lig_tfm is not None: res.append(lig_tfm)\n return res + others\n\n# Cell\ndef aug_transforms(do_flip=True, flip_vert=False, max_rotate=10., max_zoom=1.1, max_lighting=0.2,\n max_warp=0.2, p_affine=0.75, p_lighting=0.75, xtra_tfms=None,\n size=None, mode='bilinear', pad_mode=PadMode.Reflection, batch=False):\n \"Utility func to easily create a list of flip, rotate, zoom, warp, lighting transforms.\"\n res,tkw = [],dict(size=size, mode=mode, pad_mode=pad_mode, batch=batch)\n if do_flip: res.append(Dihedral(p=0.5, **tkw) if flip_vert else Flip(p=0.5, **tkw))\n if max_warp: res.append(Warp(magnitude=max_warp, p=p_affine, **tkw))\n if max_rotate: res.append(Rotate(max_deg=max_rotate, p=p_affine, **tkw))\n if max_zoom>1: res.append(Zoom(max_zoom=max_zoom, p=p_affine, **tkw))\n if max_lighting:\n res.append(Brightness(max_lighting=max_lighting, p=p_lighting, batch=batch))\n res.append(Contrast(max_lighting=max_lighting, p=p_lighting, batch=batch))\n return setup_aug_tfms(res + L(xtra_tfms))"
] | [
[
"torch.stack",
"torch.zeros_like",
"torch.ones_like"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
telesto-ai/telesto-base | [
"6ce673d30212f060a6778d1bf3b3d3fadc8ef738"
] | [
"telesto/utils.py"
] | [
"from dataclasses import dataclass\nfrom typing import Dict, List, Tuple\nimport base64\nimport io\n\nimport PIL.Image\nimport numpy as np\n\n\n@dataclass\nclass BBox:\n \"\"\"Bounding box dataclass.\n\n (x1, y1) - top left corner, (x2, y2) - bottom right one\n \"\"\"\n\n x1: int\n y1: int\n x2: int\n y2: int\n\n\nclass BaseObject:\n\n def asdict(self, *args, **kwargs) -> Dict:\n raise NotImplementedError\n\n\ndef convert_base64_images_to_arrays(doc: Dict) -> Tuple[List[str], List[np.ndarray]]:\n image_ids, input_list = [], []\n for image_doc in doc[\"images\"]:\n image_ids.append(image_doc.get(\"id\", \"\"))\n\n image_bytes = base64.b64decode(image_doc[\"content\"])\n image = PIL.Image.open(io.BytesIO(image_bytes))\n expected_modes = [\"RGB\", \"L\"]\n if image.mode not in expected_modes:\n raise ValueError(f\"Wrong image mode: {image.mode}. Expected: {expected_modes}\")\n\n input_list.append(np.asarray(image))\n return image_ids, input_list\n\n\ndef preprocess_base64_images(doc: Dict, max_images: int = 32) -> Tuple[List[str], List[np.ndarray]]:\n image_ids, input_list = convert_base64_images_to_arrays(doc)\n if not (0 < len(input_list) <= max_images):\n raise ValueError(f\"Wrong number of images: {len(input_list)}. Expected: 1 - {max_images}\")\n\n return image_ids, input_list\n"
] | [
[
"numpy.asarray"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
nholtz/structural-analysis | [
"246d6358355bd9768e30075d1f6af282ceb995be"
] | [
"matrix-methods/frame2d/Frame2D/NodeLoads.py"
] | [
"## Compiled from NodeLoads.ipynb on Sun Dec 10 12:51:11 2017\n## DO NOT EDIT THIS FILE. YOUR CHANGES WILL BE LOST!!\n\n## In [1]:\nimport numpy as np\nfrom salib import extend\n\n## In [9]:\nclass NodeLoad(object):\n \n def __init__(self,fx=0.,fy=0.,mz=0.):\n if np.isscalar(fx):\n self.forces = np.matrix([fx,fy,mz],dtype=np.float64).T\n else:\n self.forces= fx.copy()\n \n def __mul__(self,scale):\n if scale == 1.0:\n return self\n return self.__class__(self.forces*scale)\n \n __rmul__ = __mul__\n \n def __repr__(self):\n return \"{}({},{},{})\".format(self.__class__.__name__,*list(np.array(self.forces.T)[0]))\n \n def __getitem__(self,ix):\n return self.forces[ix,0]\n\n## In [11]:\ndef makeNodeLoad(data):\n G = data.get\n return NodeLoad(G('FX',0),G('FY',0),G('MZ',0))\n\n## In [13]:\nid(NodeLoad)\n\n## In [17]:\n@extend\nclass NodeLoad:\n \n @property\n def fx(self):\n return self.forces[0,0]\n \n @fx.setter\n def fx(self,v):\n self.forces[0,0] = v\n \n @property\n def fy(self):\n return self.forces[1,0]\n \n @fy.setter\n def fy(self,v):\n self.forces[1,0] = v\n \n @property\n def mz(self):\n return self.forces[2,0]\n \n @mz.setter\n def mz(self,v):\n self.forces[2,0] = v \n\n## In [ ]:\n\n"
] | [
[
"numpy.matrix",
"numpy.array",
"numpy.isscalar"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
akhilesh1311/Graph_Peeling | [
"cf4bcf74d894b91c4ce3402d593cbb683d5b46b4"
] | [
"degree.py"
] | [
"#!/usr/bin/python2.7\n\nimport os\n# from graph_tool.all import *\nimport bisect\nimport matplotlib.pyplot as plt\n\n# edge = 28280084\nnode = 1559667\n# node = 13\n\nsize, md, d = 0, 0, 0\ngraph = [[] for x in xrange(node)]\nvertices = [0]*node\ndeg = [0]*node\nwith open(\"/home/akhil/Documents/hadoop_project/graph_ab_ba_all_edges_python.txt\", \"r\") as f:\n for line in f:\n size = size + 1\n\ni = 1\nwith open(\"/home/akhil/Documents/hadoop_project/graph_ab_ba_all_edges_python.txt\", \"r\") as f:\n for line in f:\n d = 0\n line = line.strip(\"\\n\")\n line = line.split(\",\")\n for u in range(0, len(line)):\n d = d + 1\n graph[i].append(int(u))\n vertices[i] = int(line[0])\n deg[i] = d - 1\n i = i + 1\n if d > md: md = d\n\nf = open(\"/home/akhil/Documents/hadoop_project/degree.txt\", \"w\")\nfor i in range(1, node):\n f.write(str(i) + \",\" + str(vertices[i]) + \",\" + str(deg[i]) + \"\\n\")\nf.close()\n\nplt.plot(range(0,node), deg, 'ro')\nplt.axis([0, node, 0, 2500])\nplt.show()\n"
] | [
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.axis"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
wephy/project-euler | [
"cc4824478282d3e1514a1bf7a1821b938db5bfcb"
] | [
"python/p066.py"
] | [
"# Diophantine equation\n\nimport numpy as np\nfrom fractions import Fraction\n\nLIMIT = 1000\n\n\ndef solve():\n def minimal_solution(D):\n if np.sqrt(D) % 1 == 0:\n return 0\n\n a0 = int(np.floor(np.sqrt(D)))\n a = a0\n m = 0\n d = 1\n\n n = Fraction(0, 1)\n denominators = []\n while n.numerator**2 - (D * n.denominator**2) != 1:\n m = (d * a) - m\n d = (D - (m**2)) / d\n a = int(np.floor((a0 + m) / d))\n denominators += [a]\n\n n = 0\n for den in denominators[::-1]:\n n = Fraction(1, den + n)\n n += a0\n return n.numerator\n\n return max(range(LIMIT + 1), key=minimal_solution)\n\n\nif __name__ == \"__main__\":\n print(solve())\n"
] | [
[
"numpy.sqrt",
"numpy.floor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jdkent/pybids | [
"1431df11a7748848f6c4170f19211321ab0c4b9f"
] | [
"bids/variables/io.py"
] | [
"from os.path import join\nimport warnings\nimport json\n\nimport numpy as np\nimport pandas as pd\n\nfrom bids.utils import listify\nfrom .entities import NodeIndex\nfrom .variables import SparseRunVariable, DenseRunVariable, SimpleVariable\n\n\nBASE_ENTITIES = ['subject', 'session', 'task', 'run']\nALL_ENTITIES = BASE_ENTITIES + ['datatype', 'suffix', 'acquisition']\n\n\ndef load_variables(layout, types=None, levels=None, skip_empty=True,\n dataset=None, scope='all', **kwargs):\n ''' A convenience wrapper for one or more load_*_variables() calls.\n\n Args:\n layout (BIDSLayout): BIDSLayout containing variable files.\n types (str, list): Types of variables to retrieve. All valid values\n reflect the filename stipulated in the BIDS spec for each kind of\n variable. Valid values include: 'events', 'physio', 'stim',\n 'scans', 'participants', 'sessions', and 'regressors'.\n levels (str, list): Optional level(s) of variables to load. Valid\n values are 'run', 'session', 'subject', or 'dataset'. This is\n simply a shorthand way to specify types--e.g., 'run' will be\n converted to types=['events', 'physio', 'stim', 'regressors'].\n skip_empty (bool): Whether or not to skip empty Variables (i.e.,\n where there are no rows/records in a file after applying any\n filtering operations like dropping NaNs).\n dataset (NodeIndex): An existing NodeIndex container to store the\n loaded data in. Can be used to iteratively construct a dataset\n that contains otherwise heterogeneous sets of variables. If None,\n a new NodeIndex is used.\n scope (str, list): The scope of the space to search for variables. See\n docstring for BIDSLayout for details and valid predefined values.\n kwargs: Optional keyword arguments to pass onto the individual\n load_*_variables() calls.\n\n Returns:\n A NodeIndex instance.\n\n Example:\n >>> load_variables(layout, ['events', 'physio'], subject='01')\n # returns all variables stored in _events.tsv and _physio.tsv.gz files\n # for runs that belong to subject with id '01'.\n '''\n\n TYPES = ['events', 'physio', 'stim', 'scans', 'participants', 'sessions',\n 'regressors']\n\n types = listify(types)\n\n if types is None:\n if levels is not None:\n types = []\n lev_map = {\n 'run': ['events', 'physio', 'stim', 'regressors'],\n 'session': ['scans'],\n 'subject': ['sessions'],\n 'dataset': ['participants']\n }\n [types.extend(lev_map[l.lower()]) for l in listify(levels)]\n else:\n types = TYPES\n\n bad_types = set(types) - set(TYPES)\n if bad_types:\n raise ValueError(\"Invalid variable types: %s\" % bad_types)\n\n dataset = dataset or NodeIndex()\n\n run_types = list({'events', 'physio', 'stim', 'regressors'} - set(types))\n type_flags = {t: False for t in run_types}\n if len(type_flags) < 4:\n _kwargs = kwargs.copy()\n _kwargs.update(type_flags)\n dataset = _load_time_variables(layout, dataset, scope=scope, **_kwargs)\n\n for t in ({'scans', 'sessions', 'participants'} & set(types)):\n kwargs.pop('suffix', None) # suffix is always one of values aboves\n dataset = _load_tsv_variables(layout, t, dataset, scope=scope,\n **kwargs)\n\n return dataset\n\n\ndef _load_time_variables(layout, dataset=None, columns=None, scan_length=None,\n drop_na=True, events=True, physio=True, stim=True,\n regressors=True, skip_empty=True, scope='all',\n **selectors):\n ''' Loads all variables found in *_events.tsv files and returns them as a\n BIDSVariableCollection.\n\n Args:\n layout (BIDSLayout): A BIDSLayout to scan.\n dataset (NodeIndex): A BIDS NodeIndex container. If None, a new one is\n initialized.\n columns (list): Optional list of names specifying which columns in the\n event files to read. By default, reads all columns found.\n scan_length (float): Optional duration of runs (in seconds). By\n default, this will be extracted from the BOLD image. However, in\n cases where the user doesn't have access to the images (e.g.,\n because only file handles are locally available), a fixed duration\n can be manually specified as a fallback.\n drop_na (bool): If True, removes all events where amplitude is n/a. If\n False, leaves n/a values intact. Note that in the latter case,\n transformations that requires numeric values may fail.\n events (bool): If True, extracts variables from events.tsv\n files.\n physio (bool): If True, extracts variables from _physio files.\n stim (bool): If True, extracts variables from _stim files.\n skip_empty (bool): Whether or not to skip empty Variables (i.e.,\n where there are no rows/records in a file, or all onsets,\n durations, and amplitudes are 0).\n scope (str, list): The scope of the space to search for variables. See\n docstring for BIDSLayout for details and valid predefined values.\n selectors (dict): Optional keyword arguments passed onto the\n BIDSLayout instance's get() method; can be used to constrain\n which data are loaded.\n\n Returns: A NodeIndex instance.\n '''\n\n # Extract any non-keyword arguments\n selectors = selectors.copy()\n\n if dataset is None:\n dataset = NodeIndex()\n\n selectors['datatype'] = 'func'\n selectors['suffix'] = 'bold'\n images = layout.get(return_type='object', extension='nii.gz',\n scope=scope, **selectors)\n\n if not images:\n raise ValueError(\"No functional images that match criteria found.\")\n\n # Main loop over images\n for img_obj in images:\n\n entities = img_obj.entities\n img_f = img_obj.path\n\n # Run is not mandatory, but we need a default for proper indexing\n if 'run' in entities:\n entities['run'] = int(entities['run'])\n\n tr = layout.get_metadata(img_f, scope=scope)['RepetitionTime']\n\n # Get duration of run: first try to get it directly from the image\n # header; if that fails, try to get NumberOfVolumes from the\n # run metadata; if that fails, look for a scan_length argument.\n try:\n import nibabel as nb\n img = nb.load(img_f)\n duration = img.shape[3] * tr\n except Exception as e:\n if scan_length is not None:\n duration = scan_length\n else:\n msg = (\"Unable to extract scan duration from one or more \"\n \"BOLD runs, and no scan_length argument was provided \"\n \"as a fallback. Please check that the image files are \"\n \"available, or manually specify the scan duration.\")\n raise ValueError(msg)\n\n # We don't want to pass all the image file's entities onto get_node(),\n # as there can be unhashable nested slice timing values, and this also\n # slows down querying unnecessarily. Instead, pick out files only based\n # on the core BIDS entities and any entities explicitly passed as\n # selectors.\n # TODO: one downside of this approach is the stripped entities also\n # won't be returned in the resulting node due to the way things are\n # implemented. Consider adding a flag to control this.\n select_on = {k: v for (k, v) in entities.items()\n if k in BASE_ENTITIES or k in selectors}\n\n # If a matching node already exists, return it\n result = dataset.get_nodes('run', select_on)\n\n if result:\n if len(result) > 1:\n raise ValueError(\"More than one existing Node matches the \"\n \"specified entities! You may need to pass \"\n \"additional selectors to narrow the search.\")\n return result[0]\n\n # Otherwise create a new node and use that.\n # We first convert any entity values that are currently collections to\n # JSON strings to prevent nasty hashing problems downstream. Note that\n # isinstance() isn't as foolproof as actually trying to hash the\n # value, but the latter is likely to be slower, and since values are\n # coming from JSON or filenames, there's no real chance of encountering\n # anything but a list or dict.\n entities = {\n k: (json.dumps(v) if isinstance(v, (list, dict)) else v)\n for (k, v) in entities.items()\n }\n\n run = dataset.create_node('run', entities, image_file=img_f,\n duration=duration, repetition_time=tr)\n run_info = run.get_info()\n\n # Process event files\n if events:\n dfs = layout.get_nearest(\n img_f, extension='tsv', suffix='events', all_=True,\n full_search=True, ignore_strict_entities=['suffix', 'extension'])\n for _data in dfs:\n _data = pd.read_csv(_data, sep='\\t')\n if 'amplitude' in _data.columns:\n if (_data['amplitude'].astype(int) == 1).all() and \\\n 'trial_type' in _data.columns:\n msg = (\"Column 'amplitude' with constant value 1 \"\n \"is unnecessary in event files; ignoring it.\")\n _data = _data.drop('amplitude', axis=1)\n else:\n msg = (\"Column name 'amplitude' is reserved; \"\n \"renaming it to 'amplitude_'.\")\n _data = _data.rename(\n columns={'amplitude': 'amplitude_'})\n warnings.warn(msg)\n\n _data = _data.replace('n/a', np.nan) # Replace BIDS' n/a\n _data = _data.apply(pd.to_numeric, errors='ignore')\n\n _cols = columns or list(set(_data.columns.tolist()) -\n {'onset', 'duration'})\n\n # Construct a DataFrame for each extra column\n for col in _cols:\n df = _data[['onset', 'duration']].copy()\n df['amplitude'] = _data[col].values\n\n # Add in all of the run's entities as new columns for\n # index\n for entity, value in entities.items():\n if entity in ALL_ENTITIES:\n df[entity] = value\n\n if drop_na:\n df = df.dropna(subset=['amplitude'])\n\n if df.empty:\n continue\n\n var = SparseRunVariable(\n name=col, data=df, run_info=run_info, source='events')\n run.add_variable(var)\n\n # Process confound files\n if regressors:\n sub_ents = {k: v for k, v in entities.items()\n if k in BASE_ENTITIES}\n confound_files = layout.get(suffix='regressors', scope=scope,\n **sub_ents)\n for cf in confound_files:\n _data = pd.read_csv(cf.path, sep='\\t', na_values='n/a')\n if columns is not None:\n conf_cols = list(set(_data.columns) & set(columns))\n _data = _data.loc[:, conf_cols]\n for col in _data.columns:\n sr = 1. / run.repetition_time\n var = DenseRunVariable(name=col, values=_data[[col]],\n run_info=run_info, source='regressors',\n sampling_rate=sr)\n run.add_variable(var)\n\n # Process recordinging files\n rec_types = []\n if physio:\n rec_types.append('physio')\n if stim:\n rec_types.append('stim')\n\n if rec_types:\n rec_files = layout.get_nearest(\n img_f, extension='tsv.gz', all_=True, suffix=rec_types,\n ignore_strict_entities=['suffix', 'extension'], full_search=True)\n for rf in rec_files:\n metadata = layout.get_metadata(rf)\n if not metadata:\n raise ValueError(\"No .json sidecar found for '%s'.\" % rf)\n data = pd.read_csv(rf, sep='\\t')\n freq = metadata['SamplingFrequency']\n st = metadata['StartTime']\n rf_cols = metadata['Columns']\n data.columns = rf_cols\n\n # Filter columns if user passed names\n if columns is not None:\n rf_cols = list(set(rf_cols) & set(columns))\n data = data.loc[:, rf_cols]\n\n n_cols = len(rf_cols)\n if not n_cols:\n continue\n\n # Keep only in-scan samples\n if st < 0:\n start_ind = np.floor(-st * freq)\n values = data.values[start_ind:, :]\n else:\n values = data.values\n\n if st > 0:\n n_pad = int(freq * st)\n pad = np.zeros((n_pad, n_cols))\n values = np.r_[pad, values]\n\n n_rows = int(run.duration * freq)\n if len(values) > n_rows:\n values = values[:n_rows, :]\n elif len(values) < n_rows:\n pad = np.zeros((n_rows - len(values), n_cols))\n values = np.r_[values, pad]\n\n df = pd.DataFrame(values, columns=rf_cols)\n source = 'physio' if '_physio.tsv' in rf else 'stim'\n for col in df.columns:\n var = DenseRunVariable(name=col, values=df[[col]], run_info=run_info,\n source=source, sampling_rate=freq)\n run.add_variable(var)\n return dataset\n\n\ndef _load_tsv_variables(layout, suffix, dataset=None, columns=None,\n prepend_type=False, scope='all', **selectors):\n ''' Reads variables from scans.tsv, sessions.tsv, and participants.tsv.\n\n Args:\n layout (BIDSLayout): The BIDSLayout to use.\n suffix (str): The suffix of file to read from. Must be one of 'scans',\n 'sessions', or 'participants'.\n dataset (NodeIndex): A BIDS NodeIndex container. If None, a new one is\n initialized.\n columns (list): Optional list of names specifying which columns in the\n files to return. If None, all columns are returned.\n prepend_type (bool): If True, variable names are prepended with the\n type name (e.g., 'age' becomes 'participants.age').\n scope (str, list): The scope of the space to search for variables. See\n docstring for BIDSLayout for details and valid predefined values.\n selectors (dict): Optional keyword arguments passed onto the\n BIDSLayout instance's get() method; can be used to constrain\n which data are loaded.\n\n Returns: A NodeIndex instance.\n '''\n\n # Sanitize the selectors: only keep entities at current level or above\n remap = {'scans': 'run', 'sessions': 'session', 'participants': 'subject'}\n level = remap[suffix]\n valid_entities = BASE_ENTITIES[:BASE_ENTITIES.index(level)]\n layout_kwargs = {k: v for k, v in selectors.items() if k in valid_entities}\n\n if dataset is None:\n dataset = NodeIndex()\n\n files = layout.get(extension='tsv', suffix=suffix, scope=scope,\n **layout_kwargs)\n\n for f in files:\n\n _data = f.get_df(include_timing=False)\n\n # Entities can be defined either within the first column of the .tsv\n # file (for entities that vary by row), or from the full file path\n # (for entities constant over all rows in the file). We extract both\n # and store them in the main DataFrame alongside other variables (as\n # they'll be extracted when the BIDSVariable is initialized anyway).\n for ent_name, ent_val in f.entities.items():\n if ent_name in ALL_ENTITIES:\n _data[ent_name] = ent_val\n\n # Handling is a bit more convoluted for scans.tsv, because the first\n # column contains the run filename, which we also need to parse.\n if suffix == 'scans':\n\n # Suffix is guaranteed to be present in each filename, so drop the\n # constant column with value 'scans' to make way for it and prevent\n # two 'suffix' columns.\n _data.drop(columns=['suffix'], inplace=True)\n\n image = _data['filename']\n _data = _data.drop('filename', axis=1)\n dn = f.dirname\n paths = [join(dn, p) for p in image.values]\n ent_recs = [dict(layout.files[p].entities) for p in paths\n if p in layout.files]\n ent_cols = pd.DataFrame.from_records(ent_recs)\n\n # Remove entity columns found in both DFs\n dupes = list(set(ent_cols.columns) & set(_data.columns))\n to_drop = ['extension'] + dupes\n ent_cols.drop(columns=to_drop, inplace=True)\n\n _data = pd.concat([_data, ent_cols], axis=1, sort=True)\n\n # The BIDS spec requires ID columns to be named 'session_id', 'run_id',\n # etc., and IDs begin with entity prefixes (e.g., 'sub-01'). To ensure\n # consistent internal handling, we strip these suffixes and prefixes.\n elif suffix == 'sessions':\n _data = _data.rename(columns={'session_id': 'session'})\n _data['session'] = _data['session'].str.replace('ses-', '')\n elif suffix == 'participants':\n _data = _data.rename(columns={'participant_id': 'subject'})\n _data['subject'] = _data['subject'].str.replace('sub-', '')\n\n def make_patt(x, regex_search=False):\n patt = '%s' % x\n if isinstance(x, (int, float)):\n # allow for leading zeros if a number was specified\n # regardless of regex_search\n patt = '0*' + patt\n if not regex_search:\n patt = '^%s$' % patt\n return patt\n\n # Filter rows on all selectors\n comm_cols = list(set(_data.columns) & set(selectors.keys()))\n for col in comm_cols:\n ent_patts = [make_patt(x, regex_search=layout.regex_search)\n for x in listify(selectors.get(col))]\n patt = '|'.join(ent_patts)\n\n _data = _data[_data[col].str.contains(patt)]\n\n level = {'scans': 'session', 'sessions': 'subject',\n 'participants': 'dataset'}[suffix]\n\n node = dataset.get_or_create_node(level, f.entities)\n\n ent_cols = list(set(ALL_ENTITIES) & set(_data.columns))\n amp_cols = list(set(_data.columns) - set(ent_cols))\n\n if columns is not None:\n amp_cols = list(set(amp_cols) & set(columns))\n\n for col_name in amp_cols:\n\n # Rename colummns: values must be in 'amplitude'\n df = _data.loc[:, [col_name] + ent_cols]\n df.columns = ['amplitude'] + ent_cols\n\n if prepend_type:\n col_name = '%s.%s' % (suffix, col_name)\n\n node.add_variable(SimpleVariable(name=col_name, data=df, source=suffix))\n\n return dataset\n"
] | [
[
"pandas.concat",
"pandas.read_csv",
"pandas.DataFrame",
"numpy.floor",
"pandas.DataFrame.from_records",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
xiangsheng1325/GraphGenerator | [
"0164c7c1ba14fface015425a619053585f471ef3"
] | [
"GraphGenerator/models/bigg_ops/tensor_ops.py"
] | [
"# coding=utf-8\n# Copyright 2020 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n# pylint: skip-file\n\nimport torch\nfrom torch.nn import Module\nfrom torch.nn.parameter import Parameter\nfrom torch.autograd import Function\nimport numpy as np\n# from bigg.common.consts import t_float\nt_float = torch.float32\n\n\nclass MultiIndexSelectFunc(Function):\n @staticmethod\n def forward(ctx, idx_froms, idx_tos, *mats):\n assert len(idx_tos) == len(idx_froms) == len(mats)\n cols = mats[0].shape[1]\n assert all([len(x.shape) == 2 for x in mats])\n assert all([x.shape[1] == cols for x in mats])\n\n num_rows = sum([len(x) for x in idx_tos])\n out = mats[0].new(num_rows, cols)\n\n for i, mat in enumerate(mats):\n x_from = idx_froms[i]\n x_to = idx_tos[i]\n if x_from is None:\n out[x_to] = mat.detach()\n else:\n assert len(x_from) == len(x_to)\n out[x_to] = mat[x_from].detach()\n\n ctx.idx_froms = idx_froms\n ctx.idx_tos = idx_tos\n ctx.shapes = [x.shape for x in mats]\n return out\n\n @staticmethod\n def backward(ctx, grad_output):\n idx_froms, idx_tos = ctx.idx_froms, ctx.idx_tos\n\n list_grad_mats = [None, None]\n for i in range(len(idx_froms)):\n x_from = idx_froms[i]\n x_to = idx_tos[i]\n if x_from is None:\n grad_mat = grad_output[x_to].detach()\n else:\n grad_mat = grad_output.new(ctx.shapes[i]).zero_()\n grad_mat[x_from] = grad_output[x_to].detach()\n list_grad_mats.append(grad_mat)\n\n return tuple(list_grad_mats)\n\n\nclass MultiIndexSelect(Module):\n def forward(self, idx_froms, idx_tos, *mats):\n return MultiIndexSelectFunc.apply(idx_froms, idx_tos, *mats)\n\nmulti_index_select = MultiIndexSelect()\n\ndef test_multi_select():\n a = Parameter(torch.randn(4, 2))\n b = Parameter(torch.randn(3, 2))\n d = Parameter(torch.randn(5, 2))\n\n idx_froms = [[0, 1], [1, 2], [3, 4]]\n idx_tos = [[4, 5], [0, 1], [2, 3]]\n c = multi_index_select(idx_froms, idx_tos, a, b, d)\n print('===a===')\n print(a)\n print('===b===')\n print(b)\n print('===d===')\n print(d)\n print('===c===')\n print(c)\n\n t = torch.sum(c)\n t.backward()\n print(a.grad)\n print(b.grad)\n print(d.grad)\n\n\nclass PosEncoding(Module):\n def __init__(self, dim, device, base=10000, bias=0):\n super(PosEncoding, self).__init__()\n\n p = []\n sft = []\n for i in range(dim):\n b = (i - i % 2) / dim\n p.append(base ** -b)\n if i % 2:\n sft.append(np.pi / 2.0 + bias)\n else:\n sft.append(bias)\n self.device = device\n self.sft = torch.tensor(sft, dtype=t_float).view(1, -1).to(device)\n self.base = torch.tensor(p, dtype=t_float).view(1, -1).to(device)\n\n def forward(self, pos):\n with torch.no_grad():\n if isinstance(pos, list):\n pos = torch.tensor(pos, dtype=t_float).to(self.device)\n pos = pos.view(-1, 1)\n x = pos / self.base + self.sft\n return torch.sin(x)\n\n\nif __name__ == '__main__':\n # test_multi_select()\n\n pos_enc = PosEncoding(128, 'cpu')\n print(pos_enc([1, 2, 3]))\n"
] | [
[
"torch.sin",
"torch.randn",
"torch.sum",
"torch.tensor",
"torch.no_grad"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mihdalal/raps | [
"4818769adc7496f60f819c875a9995950bd5ed19",
"4818769adc7496f60f819c875a9995950bd5ed19"
] | [
"rlkit/rlkit/data_management/obs_dict_replay_buffer.py",
"d4rl/d4rl/pointmaze/maze_model.py"
] | [
"import numpy as np\nfrom gym.spaces import Dict, Discrete\n\nfrom rlkit.data_management.replay_buffer import ReplayBuffer\n\n\nclass ObsDictRelabelingBuffer(ReplayBuffer):\n \"\"\"\n Replay buffer for environments whose observations are dictionaries, such as\n - OpenAI Gym GoalEnv environments.\n https://blog.openai.com/ingredients-for-robotics-research/\n - multiworld MultitaskEnv. https://github.com/vitchyr/multiworld/\n\n Implementation details:\n - Only add_path is implemented.\n - Image observations are presumed to start with the 'image_' prefix\n - Every sample from [0, self._size] will be valid.\n - Observation and next observation are saved separately. It's a memory\n inefficient to save the observations twice, but it makes the code\n *much* easier since you no longer have to worry about termination\n conditions.\n \"\"\"\n\n def __init__(\n self,\n max_size,\n env,\n fraction_goals_rollout_goals=1.0,\n fraction_goals_env_goals=0.0,\n internal_keys=None,\n goal_keys=None,\n observation_key=\"observation\",\n desired_goal_key=\"desired_goal\",\n achieved_goal_key=\"achieved_goal\",\n ):\n if internal_keys is None:\n internal_keys = []\n self.internal_keys = internal_keys\n if goal_keys is None:\n goal_keys = []\n if desired_goal_key not in goal_keys:\n goal_keys.append(desired_goal_key)\n self.goal_keys = goal_keys\n assert isinstance(env.observation_space, Dict)\n assert 0 <= fraction_goals_rollout_goals\n assert 0 <= fraction_goals_env_goals\n assert 0 <= fraction_goals_rollout_goals + fraction_goals_env_goals\n assert fraction_goals_rollout_goals + fraction_goals_env_goals <= 1\n self.max_size = max_size\n self.env = env\n self.fraction_goals_rollout_goals = fraction_goals_rollout_goals\n self.fraction_goals_env_goals = fraction_goals_env_goals\n self.ob_keys_to_save = [\n observation_key,\n desired_goal_key,\n achieved_goal_key,\n ]\n self.observation_key = observation_key\n self.desired_goal_key = desired_goal_key\n self.achieved_goal_key = achieved_goal_key\n if isinstance(self.env.action_space, Discrete):\n self._action_dim = env.action_space.n\n else:\n self._action_dim = env.action_space.low.size\n\n self._actions = np.zeros((max_size, self._action_dim))\n # self._terminals[i] = a terminal was received at time i\n self._terminals = np.zeros((max_size, 1), dtype=\"uint8\")\n # self._obs[key][i] is the value of observation[key] at time i\n self._obs = {}\n self._next_obs = {}\n self.ob_spaces = self.env.observation_space.spaces\n for key in self.ob_keys_to_save + internal_keys:\n assert key in self.ob_spaces, (\n \"Key not found in the observation space: %s\" % key\n )\n type = np.float64\n if key.startswith(\"image\"):\n type = np.uint8\n self._obs[key] = np.zeros(\n (max_size, self.ob_spaces[key].low.size), dtype=type\n )\n self._next_obs[key] = np.zeros(\n (max_size, self.ob_spaces[key].low.size), dtype=type\n )\n\n self._top = 0\n self._size = 0\n\n # Let j be any index in self._idx_to_future_obs_idx[i]\n # Then self._next_obs[j] is a valid next observation for observation i\n self._idx_to_future_obs_idx = [None] * max_size\n\n def add_sample(\n self, observation, action, reward, terminal, next_observation, **kwargs\n ):\n raise NotImplementedError(\"Only use add_path\")\n\n def terminate_episode(self):\n pass\n\n def num_steps_can_sample(self):\n return self._size\n\n def add_path(self, path):\n obs = path[\"observations\"]\n actions = path[\"actions\"]\n rewards = path[\"rewards\"]\n next_obs = path[\"next_observations\"]\n terminals = path[\"terminals\"]\n path_len = len(rewards)\n\n actions = flatten_n(actions)\n if isinstance(self.env.action_space, Discrete):\n actions = np.eye(self._action_dim)[actions]\n actions = actions.reshape((-1, self._action_dim))\n obs = flatten_dict(obs, self.ob_keys_to_save + self.internal_keys)\n next_obs = flatten_dict(\n next_obs,\n self.ob_keys_to_save + self.internal_keys,\n )\n obs = preprocess_obs_dict(obs)\n next_obs = preprocess_obs_dict(next_obs)\n\n if self._top + path_len >= self.max_size:\n \"\"\"\n All of this logic is to handle wrapping the pointer when the\n replay buffer gets full.\n \"\"\"\n num_pre_wrap_steps = self.max_size - self._top\n # numpy slice\n pre_wrap_buffer_slice = np.s_[self._top : self._top + num_pre_wrap_steps, :]\n pre_wrap_path_slice = np.s_[0:num_pre_wrap_steps, :]\n\n num_post_wrap_steps = path_len - num_pre_wrap_steps\n post_wrap_buffer_slice = slice(0, num_post_wrap_steps)\n post_wrap_path_slice = slice(num_pre_wrap_steps, path_len)\n for buffer_slice, path_slice in [\n (pre_wrap_buffer_slice, pre_wrap_path_slice),\n (post_wrap_buffer_slice, post_wrap_path_slice),\n ]:\n self._actions[buffer_slice] = actions[path_slice]\n self._terminals[buffer_slice] = terminals[path_slice]\n for key in self.ob_keys_to_save + self.internal_keys:\n self._obs[key][buffer_slice] = obs[key][path_slice]\n self._next_obs[key][buffer_slice] = next_obs[key][path_slice]\n # Pointers from before the wrap\n for i in range(self._top, self.max_size):\n self._idx_to_future_obs_idx[i] = np.hstack(\n (\n # Pre-wrap indices\n np.arange(i, self.max_size),\n # Post-wrap indices\n np.arange(0, num_post_wrap_steps),\n )\n )\n # Pointers after the wrap\n for i in range(0, num_post_wrap_steps):\n self._idx_to_future_obs_idx[i] = np.arange(\n i,\n num_post_wrap_steps,\n )\n else:\n slc = np.s_[self._top : self._top + path_len, :]\n self._actions[slc] = actions\n self._terminals[slc] = terminals\n for key in self.ob_keys_to_save + self.internal_keys:\n self._obs[key][slc] = obs[key]\n self._next_obs[key][slc] = next_obs[key]\n for i in range(self._top, self._top + path_len):\n self._idx_to_future_obs_idx[i] = np.arange(i, self._top + path_len)\n self._top = (self._top + path_len) % self.max_size\n self._size = min(self._size + path_len, self.max_size)\n\n def _sample_indices(self, batch_size):\n return np.random.randint(0, self._size, batch_size)\n\n def random_batch(self, batch_size):\n indices = self._sample_indices(batch_size)\n resampled_goals = self._next_obs[self.desired_goal_key][indices]\n\n num_env_goals = int(batch_size * self.fraction_goals_env_goals)\n num_rollout_goals = int(batch_size * self.fraction_goals_rollout_goals)\n num_future_goals = batch_size - (num_env_goals + num_rollout_goals)\n new_obs_dict = self._batch_obs_dict(indices)\n new_next_obs_dict = self._batch_next_obs_dict(indices)\n\n if num_env_goals > 0:\n env_goals = self.env.sample_goals(num_env_goals)\n env_goals = preprocess_obs_dict(env_goals)\n last_env_goal_idx = num_rollout_goals + num_env_goals\n resampled_goals[num_rollout_goals:last_env_goal_idx] = env_goals[\n self.desired_goal_key\n ]\n for goal_key in self.goal_keys:\n new_obs_dict[goal_key][num_rollout_goals:last_env_goal_idx] = env_goals[\n goal_key\n ]\n new_next_obs_dict[goal_key][\n num_rollout_goals:last_env_goal_idx\n ] = env_goals[goal_key]\n if num_future_goals > 0:\n future_indices = indices[-num_future_goals:]\n possible_future_obs_lens = np.array(\n [len(self._idx_to_future_obs_idx[i]) for i in future_indices]\n )\n # Faster than a naive for-loop.\n # See https://github.com/vitchyr/rlkit/pull/112 for details.\n next_obs_idxs = (\n np.random.random(num_future_goals) * possible_future_obs_lens\n ).astype(np.int)\n future_obs_idxs = np.array(\n [\n self._idx_to_future_obs_idx[ids][next_obs_idxs[i]]\n for i, ids in enumerate(future_indices)\n ]\n )\n\n resampled_goals[-num_future_goals:] = self._next_obs[\n self.achieved_goal_key\n ][future_obs_idxs]\n for goal_key in self.goal_keys:\n new_obs_dict[goal_key][-num_future_goals:] = self._next_obs[goal_key][\n future_obs_idxs\n ]\n new_next_obs_dict[goal_key][-num_future_goals:] = self._next_obs[\n goal_key\n ][future_obs_idxs]\n\n new_obs_dict[self.desired_goal_key] = resampled_goals\n new_next_obs_dict[self.desired_goal_key] = resampled_goals\n new_obs_dict = postprocess_obs_dict(new_obs_dict)\n new_next_obs_dict = postprocess_obs_dict(new_next_obs_dict)\n # resampled_goals must be postprocessed as well\n resampled_goals = new_next_obs_dict[self.desired_goal_key]\n\n new_actions = self._actions[indices]\n \"\"\"\n For example, the environments in this repo have batch-wise\n implementations of computing rewards:\n\n https://github.com/vitchyr/multiworld\n \"\"\"\n\n if hasattr(self.env, \"compute_rewards\"):\n new_rewards = self.env.compute_rewards(\n new_actions,\n new_next_obs_dict,\n )\n else: # Assuming it's a (possibly wrapped) gym GoalEnv\n new_rewards = np.ones((batch_size, 1))\n for i in range(batch_size):\n new_rewards[i] = self.env.compute_reward(\n new_next_obs_dict[self.achieved_goal_key][i],\n new_next_obs_dict[self.desired_goal_key][i],\n None,\n )\n new_rewards = new_rewards.reshape(-1, 1)\n\n new_obs = new_obs_dict[self.observation_key]\n new_next_obs = new_next_obs_dict[self.observation_key]\n batch = {\n \"observations\": new_obs,\n \"actions\": new_actions,\n \"rewards\": new_rewards,\n \"terminals\": self._terminals[indices],\n \"next_observations\": new_next_obs,\n \"resampled_goals\": resampled_goals,\n \"indices\": np.array(indices).reshape(-1, 1),\n }\n return batch\n\n def _batch_obs_dict(self, indices):\n return {key: self._obs[key][indices] for key in self.ob_keys_to_save}\n\n def _batch_next_obs_dict(self, indices):\n return {key: self._next_obs[key][indices] for key in self.ob_keys_to_save}\n\n\ndef flatten_n(xs):\n xs = np.asarray(xs)\n return xs.reshape((xs.shape[0], -1))\n\n\ndef flatten_dict(dicts, keys):\n \"\"\"\n Turns list of dicts into dict of np arrays\n \"\"\"\n return {key: flatten_n([d[key] for d in dicts]) for key in keys}\n\n\ndef preprocess_obs_dict(obs_dict):\n \"\"\"\n Apply internal replay buffer representation changes: save images as bytes\n \"\"\"\n for obs_key, obs in obs_dict.items():\n if \"image\" in obs_key and obs is not None:\n obs_dict[obs_key] = unnormalize_image(obs)\n return obs_dict\n\n\ndef postprocess_obs_dict(obs_dict):\n \"\"\"\n Undo internal replay buffer representation changes: save images as bytes\n \"\"\"\n for obs_key, obs in obs_dict.items():\n if \"image\" in obs_key and obs is not None:\n obs_dict[obs_key] = normalize_image(obs)\n return obs_dict\n\n\ndef normalize_image(image):\n assert image.dtype == np.uint8\n return np.float64(image) / 255.0\n\n\ndef unnormalize_image(image):\n assert image.dtype != np.uint8\n return np.uint8(image * 255.0)\n",
"\"\"\" A pointmass maze env.\"\"\"\nimport random\n\nimport numpy as np\nfrom gym import utils\nfrom gym.envs.mujoco import mujoco_env\n\nfrom d4rl import offline_env\nfrom d4rl.pointmaze.dynamic_mjc import MJCModel\n\nWALL = 10\nEMPTY = 11\nGOAL = 12\n\n\ndef parse_maze(maze_str):\n lines = maze_str.strip().split(\"\\\\\")\n width, height = len(lines), len(lines[0])\n maze_arr = np.zeros((width, height), dtype=np.int32)\n for w in range(width):\n for h in range(height):\n tile = lines[w][h]\n if tile == \"#\":\n maze_arr[w][h] = WALL\n elif tile == \"G\":\n maze_arr[w][h] = GOAL\n elif tile == \" \" or tile == \"O\" or tile == \"0\":\n maze_arr[w][h] = EMPTY\n else:\n raise ValueError(\"Unknown tile type: %s\" % tile)\n return maze_arr\n\n\ndef point_maze(maze_str):\n maze_arr = parse_maze(maze_str)\n\n mjcmodel = MJCModel(\"point_maze\")\n mjcmodel.root.compiler(inertiafromgeom=\"true\", angle=\"radian\", coordinate=\"local\")\n mjcmodel.root.option(\n timestep=\"0.01\", gravity=\"0 0 0\", iterations=\"20\", integrator=\"Euler\"\n )\n default = mjcmodel.root.default()\n default.joint(damping=1, limited=\"false\")\n default.geom(\n friction=\".5 .1 .1\",\n density=\"1000\",\n margin=\"0.002\",\n condim=\"1\",\n contype=\"2\",\n conaffinity=\"1\",\n )\n\n asset = mjcmodel.root.asset()\n asset.texture(\n type=\"2d\",\n name=\"groundplane\",\n builtin=\"checker\",\n rgb1=\"0.2 0.3 0.4\",\n rgb2=\"0.1 0.2 0.3\",\n width=100,\n height=100,\n )\n asset.texture(\n name=\"skybox\",\n type=\"skybox\",\n builtin=\"gradient\",\n rgb1=\".4 .6 .8\",\n rgb2=\"0 0 0\",\n width=\"800\",\n height=\"800\",\n mark=\"random\",\n markrgb=\"1 1 1\",\n )\n asset.material(name=\"groundplane\", texture=\"groundplane\", texrepeat=\"20 20\")\n asset.material(name=\"wall\", rgba=\".7 .5 .3 1\")\n asset.material(name=\"target\", rgba=\".6 .3 .3 1\")\n\n visual = mjcmodel.root.visual()\n visual.headlight(ambient=\".4 .4 .4\", diffuse=\".8 .8 .8\", specular=\"0.1 0.1 0.1\")\n visual.map(znear=0.01)\n visual.quality(shadowsize=2048)\n\n worldbody = mjcmodel.root.worldbody()\n worldbody.geom(\n name=\"ground\",\n size=\"40 40 0.25\",\n pos=\"0 0 -0.1\",\n type=\"plane\",\n contype=1,\n conaffinity=0,\n material=\"groundplane\",\n )\n\n particle = worldbody.body(name=\"particle\", pos=[1.2, 1.2, 0])\n particle.geom(\n name=\"particle_geom\", type=\"sphere\", size=0.1, rgba=\"0.0 0.0 1.0 0.0\", contype=1\n )\n particle.site(\n name=\"particle_site\", pos=[0.0, 0.0, 0], size=0.2, rgba=\"0.3 0.6 0.3 1\"\n )\n particle.joint(name=\"ball_x\", type=\"slide\", pos=[0, 0, 0], axis=[1, 0, 0])\n particle.joint(name=\"ball_y\", type=\"slide\", pos=[0, 0, 0], axis=[0, 1, 0])\n\n worldbody.site(name=\"target_site\", pos=[0.0, 0.0, 0], size=0.2, material=\"target\")\n\n width, height = maze_arr.shape\n for w in range(width):\n for h in range(height):\n if maze_arr[w, h] == WALL:\n worldbody.geom(\n conaffinity=1,\n type=\"box\",\n name=\"wall_%d_%d\" % (w, h),\n material=\"wall\",\n pos=[w + 1.0, h + 1.0, 0],\n size=[0.5, 0.5, 0.2],\n )\n\n actuator = mjcmodel.root.actuator()\n actuator.motor(joint=\"ball_x\", ctrlrange=[-1.0, 1.0], ctrllimited=True, gear=100)\n actuator.motor(joint=\"ball_y\", ctrlrange=[-1.0, 1.0], ctrllimited=True, gear=100)\n\n return mjcmodel\n\n\nLARGE_MAZE = (\n \"############\\\\\"\n + \"#OOOO#OOOOO#\\\\\"\n + \"#O##O#O#O#O#\\\\\"\n + \"#OOOOOO#OOO#\\\\\"\n + \"#O####O###O#\\\\\"\n + \"#OO#O#OOOOO#\\\\\"\n + \"##O#O#O#O###\\\\\"\n + \"#OO#OOO#OGO#\\\\\"\n + \"############\"\n)\n\nLARGE_MAZE_EVAL = (\n \"############\\\\\"\n + \"#OO#OOO#OGO#\\\\\"\n + \"##O###O#O#O#\\\\\"\n + \"#OO#O#OOOOO#\\\\\"\n + \"#O##O#OO##O#\\\\\"\n + \"#OOOOOO#OOO#\\\\\"\n + \"#O##O#O#O###\\\\\"\n + \"#OOOO#OOOOO#\\\\\"\n + \"############\"\n)\n\nMEDIUM_MAZE = (\n \"########\\\\\"\n + \"#OO##OO#\\\\\"\n + \"#OO#OOO#\\\\\"\n + \"##OOO###\\\\\"\n + \"#OO#OOO#\\\\\"\n + \"#O#OO#O#\\\\\"\n + \"#OOO#OG#\\\\\"\n + \"########\"\n)\n\nMEDIUM_MAZE_EVAL = (\n \"########\\\\\"\n + \"#OOOOOG#\\\\\"\n + \"#O#O##O#\\\\\"\n + \"#OOOO#O#\\\\\"\n + \"###OO###\\\\\"\n + \"#OOOOOO#\\\\\"\n + \"#OO##OO#\\\\\"\n + \"########\"\n)\n\nSMALL_MAZE = \"######\\\\\" + \"#OOOO#\\\\\" + \"#O##O#\\\\\" + \"#OOOO#\\\\\" + \"######\"\n\nU_MAZE = \"#####\\\\\" + \"#GOO#\\\\\" + \"###O#\\\\\" + \"#OOO#\\\\\" + \"#####\"\n\nU_MAZE_EVAL = \"#####\\\\\" + \"#OOG#\\\\\" + \"#O###\\\\\" + \"#OOO#\\\\\" + \"#####\"\n\nOPEN = \"#######\\\\\" + \"#OOOOO#\\\\\" + \"#OOGOO#\\\\\" + \"#OOOOO#\\\\\" + \"#######\"\n\n\nclass MazeEnv(mujoco_env.MujocoEnv, utils.EzPickle, offline_env.OfflineEnv):\n def __init__(\n self, maze_spec=U_MAZE, reward_type=\"dense\", reset_target=False, **kwargs\n ):\n offline_env.OfflineEnv.__init__(self, **kwargs)\n\n self.reset_target = reset_target\n self.str_maze_spec = maze_spec\n self.maze_arr = parse_maze(maze_spec)\n self.reward_type = reward_type\n self.reset_locations = list(zip(*np.where(self.maze_arr == EMPTY)))\n self.reset_locations.sort()\n\n self._target = np.array([0.0, 0.0])\n\n model = point_maze(maze_spec)\n with model.asfile() as f:\n mujoco_env.MujocoEnv.__init__(self, model_path=f.name, frame_skip=1)\n utils.EzPickle.__init__(self)\n\n # Set the default goal (overriden by a call to set_target)\n # Try to find a goal if it exists\n self.goal_locations = list(zip(*np.where(self.maze_arr == GOAL)))\n if len(self.goal_locations) == 1:\n self.set_target(self.goal_locations[0])\n elif len(self.goal_locations) > 1:\n raise ValueError(\"More than 1 goal specified!\")\n else:\n # If no goal, use the first empty tile\n self.set_target(\n np.array(self.reset_locations[0]).astype(self.observation_space.dtype)\n )\n self.empty_and_goal_locations = self.reset_locations + self.goal_locations\n\n def step(self, action):\n action = np.clip(action, -1.0, 1.0)\n self.clip_velocity()\n self.do_simulation(action, self.frame_skip)\n self.set_marker()\n ob = self._get_obs()\n if self.reward_type == \"sparse\":\n reward = 1.0 if np.linalg.norm(ob[0:2] - self._target) <= 0.5 else 0.0\n elif self.reward_type == \"dense\":\n reward = np.exp(-np.linalg.norm(ob[0:2] - self._target))\n else:\n raise ValueError(\"Unknown reward type %s\" % self.reward_type)\n done = False\n return ob, reward, done, {}\n\n def _get_obs(self):\n return np.concatenate([self.sim.data.qpos, self.sim.data.qvel]).ravel()\n\n def get_target(self):\n return self._target\n\n def set_target(self, target_location=None):\n if target_location is None:\n idx = self.np_random.choice(len(self.empty_and_goal_locations))\n reset_location = np.array(self.empty_and_goal_locations[idx]).astype(\n self.observation_space.dtype\n )\n target_location = reset_location + self.np_random.uniform(\n low=-0.1, high=0.1, size=self.model.nq\n )\n self._target = target_location\n\n def set_marker(self):\n self.data.site_xpos[self.model.site_name2id(\"target_site\")] = np.array(\n [self._target[0] + 1, self._target[1] + 1, 0.0]\n )\n\n def clip_velocity(self):\n qvel = np.clip(self.sim.data.qvel, -5.0, 5.0)\n self.set_state(self.sim.data.qpos, qvel)\n\n def reset_model(self):\n idx = self.np_random.choice(len(self.empty_and_goal_locations))\n reset_location = np.array(self.empty_and_goal_locations[idx]).astype(\n self.observation_space.dtype\n )\n qpos = reset_location + self.np_random.uniform(\n low=-0.1, high=0.1, size=self.model.nq\n )\n qvel = self.init_qvel + self.np_random.randn(self.model.nv) * 0.1\n self.set_state(qpos, qvel)\n if self.reset_target:\n self.set_target()\n return self._get_obs()\n\n def reset_to_location(self, location):\n self.sim.reset()\n reset_location = np.array(location).astype(self.observation_space.dtype)\n qpos = reset_location + self.np_random.uniform(\n low=-0.1, high=0.1, size=self.model.nq\n )\n qvel = self.init_qvel + self.np_random.randn(self.model.nv) * 0.1\n self.set_state(qpos, qvel)\n return self._get_obs()\n\n def viewer_setup(self):\n pass\n"
] | [
[
"numpy.random.random",
"numpy.asarray",
"numpy.uint8",
"numpy.eye",
"numpy.arange",
"numpy.ones",
"numpy.float64",
"numpy.array",
"numpy.zeros",
"numpy.random.randint"
],
[
"numpy.clip",
"numpy.linalg.norm",
"numpy.concatenate",
"numpy.array",
"numpy.zeros",
"numpy.where"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gear/lab | [
"ad1c5838acbcc98abb5d5d93d5c7a6c2b74bdfa2"
] | [
"lab/logger/indicators.py"
] | [
"from collections import deque\nfrom typing import Dict, Optional\n\nimport numpy as np\n\ntry:\n import torch\nexcept ImportError:\n torch = None\n\n\ndef _to_numpy(value):\n type_ = type(value)\n\n if type_ == float or type_ == int:\n return value\n\n if type_ == np.ndarray:\n return value\n\n if torch is not None:\n if type_ == torch.nn.parameter.Parameter:\n return value.data.cpu().numpy()\n if type_ == torch.Tensor:\n return value.data.cpu().numpy()\n\n assert False, f\"Unknown type {type_}\"\n\n\nclass Indicator:\n def __init__(self, *, name: str, is_print: bool):\n self.is_print = is_print\n self.name = name\n\n def clear(self):\n pass\n\n def is_empty(self) -> bool:\n raise NotImplementedError()\n\n def to_dict(self) -> Dict:\n return dict(class_name=self.__class__.__name__,\n name=self.name,\n is_print=self.is_print)\n\n def collect_value(self, value):\n raise NotImplementedError()\n\n def get_mean(self) -> Optional[float]:\n return None\n\n def get_histogram(self):\n return None\n\n @property\n def mean_key(self):\n return f'{self.name}'\n\n def get_index_mean(self):\n return None, None\n\n\nclass Queue(Indicator):\n def __init__(self, name: str, queue_size=10, is_print=False):\n super().__init__(name=name, is_print=is_print)\n self._values = deque(maxlen=queue_size)\n\n def collect_value(self, value):\n self._values.append(_to_numpy(value))\n\n def to_dict(self) -> Dict:\n res = super().to_dict().copy()\n res.update({'queue_size': self._values.maxlen})\n return res\n\n def is_empty(self) -> bool:\n return len(self._values) == 0\n\n def get_mean(self) -> float:\n return float(np.mean(self._values))\n\n def get_histogram(self):\n return self._values\n\n @property\n def mean_key(self):\n return f'{self.name}.mean'\n\n\nclass _Collection(Indicator):\n def __init__(self, name: str, is_print=False):\n super().__init__(name=name, is_print=is_print)\n self._values = []\n\n def collect_value(self, value):\n self._values.append(_to_numpy(value))\n\n def clear(self):\n self._values = []\n\n def is_empty(self) -> bool:\n return len(self._values) == 0\n\n def get_mean(self) -> float:\n return float(np.mean(self._values))\n\n def get_histogram(self):\n return self._values\n\n\nclass Histogram(_Collection):\n @property\n def mean_key(self):\n return f'{self.name}.mean'\n\n\nclass Scalar(_Collection):\n def get_histogram(self):\n return None\n\n\nclass _IndexedCollection(Indicator):\n def __init__(self, name: str):\n super().__init__(name=name, is_print=False)\n self._values = []\n self._indexes = []\n\n def clear(self):\n self._values = []\n self._indexes = []\n\n def collect_value(self, value):\n if type(value) == tuple:\n assert len(value) == 2\n if type(value[0]) == int:\n self._indexes.append(value[0])\n self._values.append(value[1])\n else:\n assert type(value[0]) == list\n assert len(value[0]) == len(value[1])\n self._indexes += value[0]\n self._values += value[1]\n else:\n assert type(value) == list\n self._indexes += [v[0] for v in value]\n self._values += [v[1] for v in value]\n\n def is_empty(self) -> bool:\n return len(self._values) == 0\n\n def get_mean(self) -> float:\n return float(np.mean(self._values))\n\n def get_index_mean(self):\n summary = {}\n for ind, values in zip(self._indexes, self._values):\n if ind not in summary:\n summary[ind] = []\n summary[ind].append(values)\n\n indexes = []\n means = []\n for ind, values in summary.items():\n indexes.append(ind)\n means.append(float(np.mean(values)))\n\n return indexes, means\n\n\nclass IndexedScalar(_IndexedCollection):\n def get_histogram(self):\n return None\n"
] | [
[
"numpy.mean"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ascendancy09/CoSpar | [
"791b320e4f7722d7fc3a61c5ff7d45f23db7af91",
"791b320e4f7722d7fc3a61c5ff7d45f23db7af91"
] | [
"cospar/tmap/map_reconstruction.py",
"cospar/help_functions/_help_functions_CoSpar.py"
] | [
"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport os\nimport pandas as pd\nimport time\nimport scanpy as sc\nimport scipy.sparse as ssp \n\nfrom .. import help_functions as hf\nfrom .. import plotting as CSpl\nfrom .optimal_transport import *\nfrom .. import settings\nfrom .. import logging as logg\n\n\n####################\n\n# Constructing the similarity matrix (similarity matrix)\n\n####################\n\n\ndef generate_similarity_matrix(adata,file_name,round_of_smooth=10,neighbor_N=20,beta=0.1,truncation_threshold=0.001,save_subset=True,compute_new_Smatrix=False):\n \"\"\"\n Generate similarity matrix (Smatrix) through graph diffusion\n\n It generates the similarity matrix via iteratively graph diffusion. \n Similarity matrix from each round of diffusion will be saved, after truncation \n to promote sparsity and save space. If save_subset is activated, only save \n Smatrix for smooth round [5,10,15,...]. If a Smatrix is pre-computed, \n it will be loaded directly if compute_new_Smatrix=Flase. \n\n Parameters\n ----------\n adata: :class:`~anndata.AnnData` object\n file_name: str \n file name to load pre-computed similarity matrix or save the newly \n computed similarity matrix \n round_of_smooth: `int`, optional (default: 10)\n The rounds of graph diffusion.\n neighbor_N: `int`, optional (default: 20)\n Neighber number for constructing the KNN graph, using the UMAP method. \n beta: `float`, option (default: 0.1)\n Probability to stay at origin in a unit diffusion step, in the range [0,1]\n truncation_threshold: `float`, optional (default: 0.001)\n At each iteration, truncate the similarity matrix (the similarity) using \n truncation_threshold. This promotes the sparsity of the matrix, \n thus the speed of computation. We set the truncation threshold to be small, \n to guarantee accracy.\n save_subset: `bool`, optional (default: True)\n If true, save only Smatrix at smooth round [5,10,15,...]\n Else, save Smatrix at each round. \n compute_new_Smatrix: `bool`, optional (default: False)\n If true, compute new Smatrix, even if there is pre-computed Smatrix with the \n same parameterization. \n\n Returns\n -------\n similarity_matrix: `sp.spmatrix` \n \"\"\"\n\n if os.path.exists(file_name+f'_SM{round_of_smooth}.npz') and (not compute_new_Smatrix):\n \n logg.info(\"Compute similarity matrix: load existing data\")\n similarity_matrix=ssp.load_npz(file_name+f'_SM{round_of_smooth}.npz')\n else: # compute now\n \n logg.info(f\"Compute similarity matrix: computing new; beta={beta}\")\n\n # add a step to compute PCA in case this is not computed \n\n # here, we assume that adata already has pre-computed PCA\n sc.pp.neighbors(adata, n_neighbors=neighbor_N)\n\n ## compute the similarity matrix (smooth matrix)\n \n #nrow = adata.shape[0]\n #initial_clones = ssp.lil_matrix((nrow, nrow))\n #initial_clones.setdiag(np.ones(nrow))\n #similarity_matrix=hf.get_smooth_values_SW(initial_clones, adata_sp.uns['neighbors']['connectivities'], beta=0, n_rounds=round_of_smooth)\n #similarity_matrix=get_smooth_values_sparseMatrixForm(initial_clones, adata.uns['neighbors']['connectivities'], beta=0, n_rounds=round_of_smooth)\n # this similarity_matrix is column-normalized, our B here\n\n \n #adjacency_matrix=adata.uns['neighbors']['connectivities'];\n adjacency_matrix=adata.obsp['connectivities'];\n\n ############## The new method\n adjacency_matrix=(adjacency_matrix+adjacency_matrix.T)/2\n ############## \n\n adjacency_matrix = hf.sparse_rowwise_multiply(adjacency_matrix, 1 / adjacency_matrix.sum(1).A.squeeze())\n nrow = adata.shape[0]\n similarity_matrix = ssp.lil_matrix((nrow, nrow))\n similarity_matrix.setdiag(np.ones(nrow))\n transpose_A=adjacency_matrix.T\n for iRound in range(round_of_smooth):\n SM=iRound+1\n \n logg.info(\"Smooth round:\",SM)\n t=time.time()\n similarity_matrix =beta*similarity_matrix+(1-beta)*transpose_A*similarity_matrix\n #similarity_matrix =beta*similarity_matrix+(1-beta)*similarity_matrix*adjacency_matrix\n #similarity_matrix_array.append(similarity_matrix)\n \n logg.hint(\"Time elapsed:\",time.time()-t)\n\n t=time.time()\n sparsity_frac=(similarity_matrix>0).sum()/(similarity_matrix.shape[0]*similarity_matrix.shape[1])\n if sparsity_frac>=0.1:\n #similarity_matrix_truncate=similarity_matrix\n #similarity_matrix_truncate_array.append(similarity_matrix_truncate)\n \n logg.hint(f\"Orignal sparsity={sparsity_frac}, Thresholding\")\n similarity_matrix=hf.matrix_row_or_column_thresholding(similarity_matrix,truncation_threshold)\n sparsity_frac_2=(similarity_matrix>0).sum()/(similarity_matrix.shape[0]*similarity_matrix.shape[1])\n #similarity_matrix_truncate_array.append(similarity_matrix_truncate)\n \n logg.hint(f\"Final sparsity={sparsity_frac_2}\")\n \n logg.info(f\"similarity matrix truncated (Smooth round={SM}): \", time.time()-t)\n\n #logg.info(\"Save the matrix\")\n #file_name=f'data/20200221_truncated_similarity_matrix_SM{round_of_smooth}_kNN{neighbor_N}_Truncate{str(truncation_threshold)[2:]}.npz'\n similarity_matrix=ssp.csr_matrix(similarity_matrix)\n\n\n ############## The new method\n #similarity_matrix=similarity_matrix.T.copy() \n ##############\n\n\n if save_subset: \n if SM%5==0: # save when SM=5,10,15,20,...\n \n logg.info(\"Save the matrix~~~\")\n ssp.save_npz(file_name+f'_SM{SM}.npz',similarity_matrix)\n else: # save all\n \n logg.info(\"Save the matrix\")\n ssp.save_npz(file_name+f'_SM{SM}.npz',similarity_matrix)\n \n\n return similarity_matrix\n\n\n\n\ndef generate_initial_similarity(similarity_matrix,initial_index_0,initial_index_1):\n \"\"\"\n Extract Smatrix at t1 from the full Smatrix\n\n Parameters\n ----------\n similarity_matrix: `np.array` or `sp.spmatrix`\n full Smatrix\n initial_index_0: `list`\n list of selected t1-cell id among all cells (t1+t2)\n initial_index_1: `list`\n list of selected t1-cell id among all cells (t1+t2)\n It can be the same as initial_index_0. In the case that they are different, \n initial_index_1 is a subset of cells that correspond to multi-time clones,\n while initial_index_0 may be all cells at t1. \n\n Returns\n -------\n initial Smatrix: `np.array`\n \"\"\"\n \n t=time.time()\n initial_similarity=similarity_matrix[initial_index_0][:,initial_index_1];\n #initial_similarity=hf.sparse_column_multiply(initial_similarity,1/(resol+initial_similarity.sum(0)))\n if ssp.issparse(initial_similarity): initial_similarity=initial_similarity.A\n \n logg.hint(\"Time elapsed: \", time.time()-t)\n return initial_similarity \n\n\ndef generate_final_similarity(similarity_matrix,final_index_0,final_index_1):\n \"\"\"\n Extract Smatrix at t2 from the full Smatrix\n\n Parameters\n ----------\n similarity_matrix: `np.array` or `sp.spmatrix`\n full Smatrix\n final_index_0: `list`\n list of selected t2-cell id among all cells (t1+t2)\n final_index_1: `list`\n list of selected t2-cell id among all cells (t1+t2)\n It can be the same as final_index_0. In the case that they are different, \n initial_index_0 is a subset of cells that correspond to multi-time clones,\n while initial_index_1 may be all cells at t2. \n\n Returns\n -------\n initial Smatrix: `np.array`\n \"\"\"\n \n t=time.time()\n final_similarity=similarity_matrix.T[final_index_0][:,final_index_1];\n if ssp.issparse(final_similarity):final_similarity=final_similarity.A\n #final_similarity=hf.sparse_rowwise_multiply(final_similarity,1/(resol+final_similarity.sum(1)))\n \n logg.hint(\"Time elapsed: \", time.time()-t)\n return final_similarity\n\n\n\ndef select_time_points(adata_orig,time_point=['day_1','day_2'],use_all_cells=False):\n \"\"\"\n Select barcoded cells at given time points for Tmap inference\n\n Select cells at given time points, and prepare the right data structure \n for running core cospar function to infer the Tmap. \n \n Parameters\n ----------\n adata_orig: original :class:`~anndata.AnnData` object\n time_point: `list` optional (default: ['day_1','day_2'])\n Require at least two time points, arranged in ascending order.\n use_all_cells: `bool` optional (default: `False`)\n If true, all cells at selected time points will be used for computing Tmap\n If false, only cells belonging to multi-time clones will be used for computing Tmap.\n The latter case usually speed up the computation, which is recommended. \n\n Returns\n -------\n Subsampled :class:`~anndata.AnnData` object\n \"\"\"\n \n #x_emb_orig=adata_orig.obsm['X_emb'][:,0]\n #y_emb_orig=adata_orig.obsm['X_emb'][:,1]\n time_info_orig=np.array(adata_orig.obs['time_info'])\n clone_annot_orig=adata_orig.obsm['X_clone']\n if len(time_point)==0: # use all clonally labelled cell states \n time_point=np.sort(list(set(time_info_orig)))\n\n if (len(time_point)<2):\n logg.error(\"Must select more than 1 time point!\")\n else:\n\n At=[]\n for j, time_0 in enumerate(time_point):\n At.append(ssp.csr_matrix(clone_annot_orig[time_info_orig==time_0]))\n\n ### Day t - t+1\n Clonal_cell_ID_FOR_t=[]\n for j in range(len(time_point)-1):\n idx_t=np.array((At[j]*At[j+1].T).sum(1)>0).flatten()\n time_index_t=time_info_orig==time_point[j]\n temp=np.nonzero(time_index_t)[0][idx_t]\n Clonal_cell_ID_FOR_t.append(temp) # this index is in the original space, without sampling etc\n \n logg.hint(f\"Clonal cell fraction (day {time_point[j]}-{time_point[j+1]}):\",len(temp)/np.sum(time_index_t))\n\n ### Day t+1 - t\n Clonal_cell_ID_BACK_t=[]\n for j in range(len(time_point)-1):\n idx_t=np.array((At[j+1]*At[j].T).sum(1)>0).flatten()\n time_index_t=time_info_orig==time_point[j+1]\n temp=np.nonzero(time_index_t)[0][idx_t]\n Clonal_cell_ID_BACK_t.append(temp) # this index is in the original space, without sampling etc\n \n logg.hint(f\"Clonal cell fraction (day {time_point[j+1]}-{time_point[j]}):\",len(temp)/np.sum(time_index_t))\n\n \n for j in range(len(time_point)-1): \n logg.hint(f\"Numer of cells that are clonally related -- day {time_point[j]}: {len(Clonal_cell_ID_FOR_t[j])} and day {time_point[j+1]}: {len(Clonal_cell_ID_BACK_t[j])}\")\n\n proportion=np.ones(len(time_point))\n # flatten the list\n flatten_clonal_cell_ID_FOR=np.array([sub_item for item in Clonal_cell_ID_FOR_t for sub_item in item])\n flatten_clonal_cell_ID_BACK=np.array([sub_item for item in Clonal_cell_ID_BACK_t for sub_item in item])\n valid_clone_N_FOR=np.sum(clone_annot_orig[flatten_clonal_cell_ID_FOR].A.sum(0)>0)\n valid_clone_N_BACK=np.sum(clone_annot_orig[flatten_clonal_cell_ID_BACK].A.sum(0)>0)\n\n \n logg.info(\"Valid clone number 'FOR' post selection\",valid_clone_N_FOR)\n #logg.info(\"Valid clone number 'BACK' post selection\",valid_clone_N_BACK)\n\n\n ###################### select initial and later cell states\n\n if use_all_cells:\n old_Tmap_cell_id_t1=[]\n for t_temp in time_point[:-1]:\n old_Tmap_cell_id_t1=old_Tmap_cell_id_t1+list(np.nonzero(time_info_orig==t_temp)[0])\n old_Tmap_cell_id_t1=np.array(old_Tmap_cell_id_t1)\n\n ########\n old_Tmap_cell_id_t2=[]\n for t_temp in time_point[1:]:\n old_Tmap_cell_id_t2=old_Tmap_cell_id_t2+list(np.nonzero(time_info_orig==t_temp)[0])\n old_Tmap_cell_id_t2=np.array(old_Tmap_cell_id_t2)\n\n else:\n old_Tmap_cell_id_t1=flatten_clonal_cell_ID_FOR\n old_Tmap_cell_id_t2=flatten_clonal_cell_ID_BACK\n\n\n old_clonal_cell_id_t1=flatten_clonal_cell_ID_FOR\n old_clonal_cell_id_t2=flatten_clonal_cell_ID_BACK\n ########################\n\n sp_id=np.sort(list(set(list(old_Tmap_cell_id_t1)+list(old_Tmap_cell_id_t2))))\n sp_idx=np.zeros(clone_annot_orig.shape[0],dtype=bool)\n sp_idx[sp_id]=True\n\n Tmap_cell_id_t1=hf.converting_id_from_fullSpace_to_subSpace(old_Tmap_cell_id_t1,sp_id)[0]\n clonal_cell_id_t1=hf.converting_id_from_fullSpace_to_subSpace(old_clonal_cell_id_t1,sp_id)[0]\n clonal_cell_id_t2=hf.converting_id_from_fullSpace_to_subSpace(old_clonal_cell_id_t2,sp_id)[0]\n Tmap_cell_id_t2=hf.converting_id_from_fullSpace_to_subSpace(old_Tmap_cell_id_t2,sp_id)[0]\n\n Clonal_cell_ID_FOR_t_new=[]\n for temp_id_list in Clonal_cell_ID_FOR_t:\n convert_list=hf.converting_id_from_fullSpace_to_subSpace(temp_id_list,sp_id)[0]\n Clonal_cell_ID_FOR_t_new.append(convert_list)\n\n Clonal_cell_ID_BACK_t_new=[]\n for temp_id_list in Clonal_cell_ID_BACK_t:\n convert_list=hf.converting_id_from_fullSpace_to_subSpace(temp_id_list,sp_id)[0]\n Clonal_cell_ID_BACK_t_new.append(convert_list)\n\n\n sp_id_0=np.sort(list(old_clonal_cell_id_t1)+list(old_clonal_cell_id_t2))\n sp_idx_0=np.zeros(clone_annot_orig.shape[0],dtype=bool)\n sp_idx_0[sp_id_0]=True\n\n barcode_id=np.nonzero(clone_annot_orig[sp_idx_0].A.sum(0).flatten()>0)[0]\n #sp_id=np.nonzero(sp_idx)[0]\n clone_annot=clone_annot_orig[sp_idx][:,barcode_id]\n\n adata=sc.AnnData(adata_orig.X[sp_idx]);\n adata.var_names=adata_orig.var_names\n adata.obsm['X_pca']=adata_orig.obsm['X_pca'][sp_idx]\n adata.obsm['X_emb']=adata_orig.obsm['X_emb'][sp_idx]\n adata.obs['state_info']=pd.Categorical(adata_orig.obs['state_info'][sp_idx])\n adata.obs['time_info']=pd.Categorical(adata_orig.obs['time_info'][sp_idx])\n \n \n\n adata.obsm['X_clone']=clone_annot\n adata.uns['clonal_cell_id_t1']=clonal_cell_id_t1\n adata.uns['clonal_cell_id_t2']=clonal_cell_id_t2\n adata.uns['Tmap_cell_id_t1']=Tmap_cell_id_t1\n adata.uns['Tmap_cell_id_t2']=Tmap_cell_id_t2\n adata.uns['multiTime_cell_id_t1']=Clonal_cell_ID_FOR_t_new\n adata.uns['multiTime_cell_id_t2']=Clonal_cell_ID_BACK_t_new\n adata.uns['proportion']=np.ones(len(time_point)-1)\n adata.uns['sp_idx']=sp_idx\n\n data_des_orig=adata_orig.uns['data_des'][0]\n data_des_0=adata_orig.uns['data_des'][-1]\n time_label='t'\n for x in time_point:\n time_label=time_label+f'*{x}'\n\n data_des=data_des_0+f'_TwoTimeClone_{time_label}'\n adata.uns['data_des']=[data_des_orig,data_des]\n\n if logg._settings_verbosity_greater_or_equal_than(2):\n N_cell,N_clone=clone_annot.shape;\n logg.info(f\"Cell number={N_cell}, Clone number={N_clone}\")\n x_emb=adata.obsm['X_emb'][:,0]\n y_emb=adata.obsm['X_emb'][:,1]\n CSpl.customized_embedding(x_emb,y_emb,-x_emb)\n\n return adata \n\n\n\n####################\n\n# CoSpar: two-time points\n\n####################\n\n\ndef refine_Tmap_through_cospar(MultiTime_cell_id_array_t1,MultiTime_cell_id_array_t2,\n proportion,transition_map,X_clone,initial_similarity,final_similarity,\n noise_threshold=0.1,normalization_mode=1):\n \"\"\"\n This performs one iteration of coherent sparsity optimization\n\n This is our core algorithm for coherent sparsity optimization for multi-time\n clones. It upates a map by considering clones spanning multiple time points.\n\n Parameters\n ----------\n MultiTime_cell_id_array_t1: `np.array`\n an array of cell id sub_array, where each sub_array consists of \n clonally-related cell id's at different time points\n MultiTime_cell_id_array_t2: `np.array`\n an corresponding array of sub_array, where each sub_array are id's of \n cells that are clonally related to the corresponding sub_array at \n MultiTime_cell_id_array_t1.\n proportion: `list`\n A weight factor for each time point.\n transition_map: `np.array` or `sp.spmatrix`\n initialized transition map, or map from a previous iteration.\n X_clone: `sp.spmatrix`\n clonal matrix\n initial_similarity: `np.array`\n similarity matrix for all cells belonging \n to MultiTime_cell_id_array_t1\n final_similarity: `np.array`\n similarity matrix for all cells belonging \n to MultiTime_cell_id_array_t2\n noise_threshold: `float`, optional (default: 0.1)\n noise threshold to remove noises in the updated transition map,\n in the range [0,1]\n normalization_mode: `int`, optional (default: 1)\n Method for normalization. Choice: [0,1]\n 0, single-cell normalization\n 1, Clone normalization\n\n Returns\n -------\n smoothed_new_transition_map: `np.array`\n un_SM_transition_map: `np.array`\n \"\"\"\n\n resol=10**(-10)\n\n transition_map=hf.matrix_row_or_column_thresholding(transition_map,noise_threshold,row_threshold=True)\n\n \n if normalization_mode==0: logg.info(\"Single-cell normalization\")\n if normalization_mode==1: logg.info(\"Clone normalization\")\n\n if ssp.issparse(X_clone):\n X_clone=ssp.csr_matrix(X_clone)\n\n cell_N,clone_N=X_clone.shape\n N1,N2=transition_map.shape\n new_coupling_matrix=ssp.lil_matrix((N1,N2))\n\n # cell id order in the similarity matrix is obtained by concatenating the cell id \n # list in MultiTime_cell_id_array_t1. So, we need to offset the id if we move to the next list\n offset_N1=0; \n offset_N2=0;\n for j in range(len(MultiTime_cell_id_array_t1)):\n \n logg.hint(\"Relative time point pair index:\",j)\n cell_id_array_t1=MultiTime_cell_id_array_t1[j]\n cell_id_array_t2=MultiTime_cell_id_array_t2[j]\n\n\n for clone_id in range(clone_N):\n #pdb.set_trace()\n \n if clone_id%1000==0: logg.hint(\"Clone id:\",clone_id)\n idx1=X_clone[cell_id_array_t1,clone_id].A.flatten()\n idx2=X_clone[cell_id_array_t2,clone_id].A.flatten()\n if idx1.sum()>0 and idx2.sum()>0:\n ## update the new_coupling matrix\n id_1=offset_N1+np.nonzero(idx1)[0]\n id_2=offset_N2+np.nonzero(idx2)[0]\n prob=transition_map[id_1][:,id_2]\n \n\n ## try row normalization\n if normalization_mode==0:\n prob=hf.sparse_rowwise_multiply(prob,1/(resol+np.sum(prob,1))) # cell-level normalization\n else:\n prob=prob/(resol+np.sum(prob)) # clone level normalization, account for proliferation\n\n weight_factor=np.sqrt(np.mean(idx1[idx1>0])*np.mean(idx2[idx2>0])) # the contribution of a particular clone can be tuned by its average entries\n if (weight_factor>1):\n logg.hint(\"marker gene weight\",weight_factor)\n\n #Use the add mode, add up contributions from each clone\n new_coupling_matrix[id_1[:,np.newaxis],id_2]=new_coupling_matrix[id_1[:,np.newaxis],id_2]+proportion[j]*prob*weight_factor \n\n ## update offset\n offset_N1=offset_N1+len(cell_id_array_t1)\n offset_N2=offset_N2+len(cell_id_array_t2)\n \n\n ## rescale\n new_coupling_matrix=new_coupling_matrix/(new_coupling_matrix.A.max())\n\n ## convert to sparse matrix form\n new_coupling_matrix=new_coupling_matrix.tocsr()\n\n \n logg.info(\"Start to smooth the refined clonal map\")\n t=time.time()\n temp=new_coupling_matrix*final_similarity\n \n logg.info(\"Phase I: time elapsed -- \", time.time()-t)\n smoothed_new_transition_map=initial_similarity.dot(temp)\n \n logg.info(\"Phase II: time elapsed -- \", time.time()-t)\n\n # both return are numpy array\n un_SM_transition_map=new_coupling_matrix.A\n return smoothed_new_transition_map, un_SM_transition_map\n\n\n\n\ndef refine_Tmap_through_cospar_noSmooth(MultiTime_cell_id_array_t1,\n MultiTime_cell_id_array_t2,proportion,transition_map,\n X_clone,noise_threshold=0.1,normalization_mode=1):\n \"\"\"\n This performs one iteration of coherent sparsity optimization\n\n This is the same as 'refine_Tmap_through_cospar', except that \n there is no smoothing afterwards for demultiplexing.\n\n Parameters\n ----------\n MultiTime_cell_id_array_t1: `np.array`\n an array of cell id sub_array, where each sub_array consists of \n clonally-related cell id's at different time points\n MultiTime_cell_id_array_t2: `np.array`\n an corresponding array of sub_array, where each sub_array are id's of \n cells that are clonally related to the corresponding sub_array at \n MultiTime_cell_id_array_t1.\n proportion: `list`\n A weight factor for each time point.\n transition_map: `np.array` or `sp.spmatrix`\n initialized transition map, or map from a previous iteration.\n X_clone: `sp.spmatrix`\n clonal matrix\n initial_similarity: `np.array`\n similarity matrix for all cells belonging \n to MultiTime_cell_id_array_t1\n final_similarity: `np.array`\n similarity matrix for all cells belonging \n to MultiTime_cell_id_array_t2\n noise_threshold: `float`, optional (default: 0.1)\n noise threshold to remove noises in the updated transition map,\n in the range [0,1]\n normalization_mode: `int`, optional (default: 1)\n Method for normalization. Choice: [0,1]\n 0, single-cell normalization\n 1, Clone normalization\n\n Returns\n -------\n un_SM_transition_map: `np.array`\n \"\"\"\n\n if not isinstance(X_clone[0,0], bool):\n X_clone=X_clone.astype(bool)\n\n resol=10**(-10)\n \n if normalization_mode==0: logg.info(\"Single-cell normalization\")\n if normalization_mode==1: logg.info(\"Clone normalization\")\n\n transition_map=hf.matrix_row_or_column_thresholding(transition_map,noise_threshold,row_threshold=True)\n \n if not ssp.issparse(transition_map): transition_map=ssp.csr_matrix(transition_map)\n if not ssp.issparse(X_clone): X_clone=ssp.csr_matrix(X_clone)\n\n cell_N,clone_N=X_clone.shape\n N1,N2=transition_map.shape\n new_coupling_matrix=ssp.lil_matrix((N1,N2))\n\n # cell id order in the similarity matrix is obtained by concatenating the cell id \n # list in MultiTime_cell_id_array_t1. So, we need to offset the id if we move to the next list\n offset_N1=0; \n offset_N2=0;\n for j in range(len(MultiTime_cell_id_array_t1)):\n \n logg.hint(\"Relative time point pair index:\",j)\n cell_id_array_t1=MultiTime_cell_id_array_t1[j]\n cell_id_array_t2=MultiTime_cell_id_array_t2[j]\n\n\n for clone_id in range(clone_N):\n \n if clone_id%1000==0: logg.hint(\"Clone id:\",clone_id)\n idx1=X_clone[cell_id_array_t1,clone_id].A.flatten()\n idx2=X_clone[cell_id_array_t2,clone_id].A.flatten()\n if idx1.sum()>0 and idx2.sum()>0:\n ## update the new_coupling matrix\n id_1=offset_N1+np.nonzero(idx1)[0]\n id_2=offset_N2+np.nonzero(idx2)[0]\n prob=transition_map[id_1][:,id_2].A\n \n\n ## try row normalization\n if normalization_mode==0:\n prob=hf.sparse_rowwise_multiply(prob,1/(resol+np.sum(prob,1))) # cell-level normalization\n else:\n prob=prob/(resol+np.sum(prob)) # clone level normalization, account for proliferation\n\n\n weight_factor=np.sqrt(np.mean(idx1[idx1>0])*np.mean(idx2[idx2>0])) # the contribution of a particular clone can be tuned by its average entries\n if (weight_factor>1):\n logg.hint(\"marker gene weight\",weight_factor)\n\n #Use the add mode, add up contributions from each clone\n new_coupling_matrix[id_1[:,np.newaxis],id_2]=new_coupling_matrix[id_1[:,np.newaxis],id_2]+proportion[j]*prob*weight_factor \n\n ## update offset\n offset_N1=offset_N1+len(cell_id_array_t1)\n offset_N2=offset_N2+len(cell_id_array_t2)\n \n\n ## convert to sparse matrix form\n new_coupling_matrix=new_coupling_matrix.tocsr()\n #\n un_SM_transition_map=new_coupling_matrix\n return un_SM_transition_map\n\n\n###############\n\ndef infer_Tmap_from_multitime_clones(adata_orig,selected_clonal_time_points,\n smooth_array=[15,10,5],CoSpar_KNN=20,noise_threshold=0.1,demulti_threshold=0.05,\n normalization_mode=1,use_all_cells=False,save_subset=True,use_full_Smatrix=False,\n trunca_threshold=0.001,compute_new=False):\n \"\"\"\n Infer Tmap for clonal data with multiple time points.\n\n It prepares adata object for cells of targeted time points by \n :func:`.select_time_points`, generate the similarity matrix \n via :func:`.generate_similarity_matrix`, and iterately calls \n the core function :func:`.refine_Tmap_through_cospar` to update \n the transition map. \n\n The inferred map allows transitions between neighboring time points. \n For example, if selected_clonal_time_points=['day1','day2','day3'], \n then it computes transitions for pairs (day1, day2) and (day2, day3), \n but not (day1, day3).\n\n Parameters\n ----------\n adata_orig: :class:`~anndata.AnnData` object\n Should be prepared from our anadata initialization.\n selected_clonal_time_points: `list` of `str`\n List of time points to be included for analysis. \n We assume that each selected time point has clonal measurement. \n It should be in ascending order: 'day_1','day_2'.... \n smooth_array: `list`, optional (default: [15,10,5])\n List of smooth rounds at each iteration. \n The n-th entry determines the smooth round for the Smatrix \n at the n-th iteration. Its length determins the number of\n iteration. It is better to use a number at the multiple of \n 5, i.e., 5, 10, 15, 20,...\n CoSpar_KNN: `int`, optional (default: 20)\n the number of neighbors for KNN graph used for computing the \n similarity matrix.\n trunca_threshold: `float`, optional (default: 0.001)\n We set entries to zero in the computed similarity matrix that \n are smaller than this threshold. This is to promote the Smatrix \n sparsity, which leads to faster computation, and smaller file size. \n This threshld should be small, but not too small. \n noise_threshold: `float`, optional (default: 0.1)\n noise threshold to remove noises in the updated transition map,\n in the range [0,1]\n demulti_threshold: `float`, optional (default: 0.05)\n noise threshold to remove noises in demultiplexed (un-smoothed) map,\n in the range [0,1]\n normalization_mode: `int`, optional (default: 1)\n Method for normalization. Choice: [0,1]\n 0, single-cell normalization\n 1, Clone normalization\n use_all_cells: `bool` optional (default: `False`)\n If true, all cells at selected time points will be used for computing \n Tmap. If false, only cells belonging to multi-time clones will be used \n for computing Tmap. The latter case usually speed up the computation, \n which is recommended. \n save_subset: `bool`, optional (default: True)\n If true, save only Smatrix at smooth round [5,10,15,...].\n Else, save Smatrix at each round. \n use_full_Smatrix: `bool`, optional (default: False)\n use the Smatrix as defined by all cells, whether they are clonally \n barcoded or not. We sub-sample cell states relevant for downstream \n analysis from this full Smatrix. This may refine the Smatrix. \n But will also increase the computation time significantly.\n Compute_new: `bool`, optional (default: False)\n If True, compute Smatrix from scratch, whether it was \n computed and saved before or not. This is activated only when\n `use_full_Smatrix=False`.\n\n Returns\n -------\n adata: :class:`~anndata.AnnData` object\n Store results at adata.uns['transition_map'] \n and adata.uns['intraclone_transition_map']. This adata is different \n from the input adata_orig due to subsampling cells. \n\n \"\"\"\n\n t0=time.time()\n hf.check_available_clonal_info(adata_orig)\n for xx in selected_clonal_time_points:\n if xx not in adata_orig.uns['clonal_time_points']:\n logg.error(f\"'selected_clonal_time_points' contain time points without clonal information. Please set clonal_time_point to be at least two of {adata_orig.uns['clonal_time_points']}. If there is only one clonal time point, plesae run ----cospar.tmap.infer_Tmap_from_one_time_clones----\")\n return adata_orig\n\n\n \n logg.info(\"-------Step 1: Select time points---------\")\n data_path=settings.data_path\n adata=select_time_points(adata_orig,time_point=selected_clonal_time_points,use_all_cells=use_all_cells)\n\n \n logg.info(\"-------Step 2: Compute the full Similarity matrix if necessary---------\")\n\n if use_full_Smatrix: # prepare the similarity matrix with all state info, all subsequent similarity will be down-sampled from this one.\n\n temp_str='0'+str(trunca_threshold)[2:]\n round_of_smooth=np.max(smooth_array)\n data_des=adata.uns['data_des'][0]\n similarity_file_name=f'{data_path}/{data_des}_Similarity_matrix_with_all_cell_states_kNN{CoSpar_KNN}_Truncate{temp_str}'\n if not (os.path.exists(similarity_file_name+f'_SM{round_of_smooth}.npz') and (not compute_new)):\n similarity_matrix_full=generate_similarity_matrix(adata_orig,similarity_file_name,round_of_smooth=round_of_smooth,\n neighbor_N=CoSpar_KNN,truncation_threshold=trunca_threshold,save_subset=True,compute_new_Smatrix=compute_new)\n \n logg.info(\"-------Step 3: Optimize the transition map recursively---------\")\n\n infer_Tmap_from_multitime_clones_private(adata,smooth_array=smooth_array,neighbor_N=CoSpar_KNN,noise_threshold=noise_threshold,demulti_threshold=demulti_threshold,normalization_mode=normalization_mode,\n save_subset=save_subset,use_full_Smatrix=use_full_Smatrix,trunca_threshold=trunca_threshold,compute_new_Smatrix=compute_new)\n\n logg.info(f\"-----------Total used time: {time.time()-t0} s ------------\")\n return adata\n \n\ndef infer_Tmap_from_multitime_clones_private(adata,smooth_array=[15,10,5],neighbor_N=20,noise_threshold=0.1,demulti_threshold=0.05,normalization_mode=1,save_subset=True,use_full_Smatrix=False,trunca_threshold=0.001,compute_new_Smatrix=False):\n \"\"\"\n Internal function for Tmap inference from multiTime clonal data.\n\n Same as :func:`.infer_Tmap_from_multitime_clones` except that it \n assumes that the adata object has been prepared for targeted \n time points. It generate the similarity matrix \n via :func:`.generate_similarity_matrix`, and iterately calls \n the core function :func:`.refine_Tmap_through_cospar` to update \n the transition map. \n\n Parameters\n ----------\n adata: :class:`~anndata.AnnData` object\n Should be prepared by :func:`.select_time_points`\n smooth_array: `list`, optional (default: [15,10,5])\n List of smooth rounds at each iteration. \n The n-th entry determines the smooth round for the Smatrix \n at the n-th iteration. Its length determins the number of\n iteration. It is better to use a number at the multiple of \n 5, i.e., 5, 10, 15, 20,... \n neighbor_N: `int`, optional (default: 20)\n the number of neighbors for KNN graph used for computing the similarity matrix.\n trunca_threshold: `float`, optional (default: 0.001)\n We set entries to zero in the computed similarity matrix that \n are smaller than this threshold. This is to promote the Smatrix sparsity, which\n leads to faster computation, and smaller file size. \n This threshld should be small, but not too small. \n noise_threshold: `float`, optional (default: 0.1)\n noise threshold to remove noises in the updated transition map,\n in the range [0,1]\n demulti_threshold: `float`, optional (default: 0.05)\n noise threshold to remove noises in demultiplexed (un-smoothed) map,\n in the range [0,1]\n normalization_mode: `int`, optional (default: 1)\n Method for normalization. Choice: [0,1]\n 0, single-cell normalization\n 1, Clone normalization\n save_subset: `bool`, optional (default: True)\n If true, save only Smatrix at smooth round [5,10,15,...].\n Else, save Smatrix at each round. \n use_full_Smatrix: `bool`, optional (default: False)\n use the Smatrix as defined by all cells, whether they are clonally \n barcoded or not. We sub-sample cell states relevant for downstream \n analysis from this full Smatrix. This may refine the Smatrix. \n But will also increase the computation time significantly.\n compute_new_Smatrix: `bool`, optional (default: False)\n If True, compute Smatrix from scratch, whether it was \n computed and saved before or not. This is activated only when\n `use_full_Smatrix=False`.\n\n Returns\n -------\n None. Inferred transition map updated at adata.uns['transition_map']\n and adata.uns['intraclone_transition_map']\n\n \"\"\"\n\n\n ########## extract data\n clone_annot=adata.obsm['X_clone']\n clonal_cell_id_t1=adata.uns['clonal_cell_id_t1']\n clonal_cell_id_t2=adata.uns['clonal_cell_id_t2']\n Tmap_cell_id_t1=adata.uns['Tmap_cell_id_t1']\n Tmap_cell_id_t2=adata.uns['Tmap_cell_id_t2']\n sp_idx=adata.uns['sp_idx']\n data_des=adata.uns['data_des'][0] # original label\n data_des_1=adata.uns['data_des'][-1] # current label, sensitive to selected time points\n multiTime_cell_id_t1=adata.uns['multiTime_cell_id_t1']\n multiTime_cell_id_t2=adata.uns['multiTime_cell_id_t2']\n proportion=adata.uns['proportion']\n data_path=settings.data_path\n\n #########\n\n \n ########################### Compute the transition map \n \n logg.info(\"---------Compute the transition map-----------\")\n\n #trunca_threshold=0.001 # this value is only for reducing the computed matrix size for saving\n temp_str='0'+str(trunca_threshold)[2:]\n\n if use_full_Smatrix:\n similarity_file_name=f'{data_path}/{data_des}_Similarity_matrix_with_all_cell_states_kNN{neighbor_N}_Truncate{temp_str}'\n for round_of_smooth in smooth_array:\n if not os.path.exists(similarity_file_name+f'_SM{round_of_smooth}.npz'):\n logg.error(f\"Similarity matrix at given parameters have not been computed before! Name: {similarity_file_name}\") \n return \n\n else:\n similarity_file_name=f'{data_path}/{data_des_1}_Similarity_matrix_with_selected_states_kNN{neighbor_N}_Truncate{temp_str}'\n\n initial_similarity_array=[]\n final_similarity_array=[]\n initial_similarity_array_ext=[]\n final_similarity_array_ext=[]\n\n for round_of_smooth in smooth_array:\n # we cannot force it to compute new at this time. Otherwise, if we use_full_Smatrix, the resulting similarity is actually from adata, thus not full similarity. \n\n re_compute=(not use_full_Smatrix) and (compute_new_Smatrix) # re-compute only when not using full similarity \n similarity_matrix_full=generate_similarity_matrix(adata,similarity_file_name,round_of_smooth=round_of_smooth,\n neighbor_N=neighbor_N,truncation_threshold=trunca_threshold,save_subset=save_subset,compute_new_Smatrix=re_compute)\n\n if use_full_Smatrix:\n #pdb.set_trace()\n similarity_matrix_full_sp=similarity_matrix_full[sp_idx][:,sp_idx]\n\n #pdb.set_trace()\n ### extended similarity matrix\n initial_similarity_ext=generate_initial_similarity(similarity_matrix_full_sp,Tmap_cell_id_t1,clonal_cell_id_t1)\n final_similarity_ext=generate_final_similarity(similarity_matrix_full_sp,clonal_cell_id_t2,Tmap_cell_id_t2)\n \n ### minimum similarity matrix that only involves the multi-time clones\n initial_similarity=generate_initial_similarity(similarity_matrix_full_sp,clonal_cell_id_t1,clonal_cell_id_t1)\n final_similarity=generate_final_similarity(similarity_matrix_full_sp,clonal_cell_id_t2,clonal_cell_id_t2)\n else:\n initial_similarity_ext=generate_initial_similarity(similarity_matrix_full,Tmap_cell_id_t1,clonal_cell_id_t1)\n final_similarity_ext=generate_final_similarity(similarity_matrix_full,clonal_cell_id_t2,Tmap_cell_id_t2)\n initial_similarity=generate_initial_similarity(similarity_matrix_full,clonal_cell_id_t1,clonal_cell_id_t1)\n final_similarity=generate_final_similarity(similarity_matrix_full,clonal_cell_id_t2,clonal_cell_id_t2)\n\n\n initial_similarity_array.append(initial_similarity)\n final_similarity_array.append(final_similarity)\n initial_similarity_array_ext.append(initial_similarity_ext)\n final_similarity_array_ext.append(final_similarity_ext)\n\n\n #### Compute the core of the transition map that involve multi-time clones, then extend to other cell states\n clonal_coupling_v1=np.ones((len(clonal_cell_id_t1),len(clonal_cell_id_t2)))\n transition_map_array=[clonal_coupling_v1]\n\n\n\n X_clone=clone_annot.copy()\n if not ssp.issparse(X_clone):\n X_clone=ssp.csr_matrix(X_clone)\n\n CoSpar_iter_N=len(smooth_array)\n for j in range(CoSpar_iter_N):\n \n logg.info(\"Current iteration:\",j)\n transition_map=transition_map_array[j]\n if j<len(smooth_array):\n \n logg.info(f\"Use smooth_round={smooth_array[j]}\")\n used_initial_similarity=initial_similarity_array[j]\n used_final_similarity=final_similarity_array[j]\n else:\n \n logg.info(f\"Use smooth_round={smooth_array[-1]}\")\n used_initial_similarity=initial_similarity_array[-1]\n used_final_similarity=final_similarity_array[-1]\n\n # clonal_coupling, unSM_sc_coupling=refine_transition_map_by_integrating_clonal_info(clonal_cell_id_t1,clonal_cell_id_t2,\n # transition_map,X_clone,used_initial_similarity,used_final_similarity,noise_threshold,row_normalize=True,normalization_mode=normalization_mode)\n\n \n clonal_coupling, unSM_sc_coupling=refine_Tmap_through_cospar(multiTime_cell_id_t1,multiTime_cell_id_t2,\n proportion,transition_map,X_clone,used_initial_similarity,used_final_similarity,noise_threshold=noise_threshold,normalization_mode=normalization_mode)\n\n\n transition_map_array.append(clonal_coupling)\n\n\n\n ### expand the map to other cell states\n ratio_t1=np.sum(np.in1d(Tmap_cell_id_t1,clonal_cell_id_t1))/len(Tmap_cell_id_t1)\n ratio_t2=np.sum(np.in1d(Tmap_cell_id_t2,clonal_cell_id_t2))/len(Tmap_cell_id_t2)\n if (ratio_t1==1) and (ratio_t2==1): # no need to SM the map\n \n logg.info(\"No need for Final Smooth (i.e., clonally states are the final state space for Tmap)\")\n \n adata.uns['transition_map']=ssp.csr_matrix(clonal_coupling)\n else:\n \n logg.info(\"Final round of Smooth (to expand the state space of Tmap to include non-clonal states)\")\n\n if j<len(smooth_array):\n used_initial_similarity_ext=initial_similarity_array_ext[j]\n used_final_similarity_ext=final_similarity_array_ext[j]\n else:\n used_initial_similarity_ext=initial_similarity_array_ext[-1]\n used_final_similarity_ext=final_similarity_array_ext[-1]\n\n unSM_sc_coupling=ssp.csr_matrix(unSM_sc_coupling)\n t=time.time()\n temp=unSM_sc_coupling*used_final_similarity_ext\n \n logg.info(\"Phase I: time elapsed -- \", time.time()-t)\n transition_map_1=used_initial_similarity_ext.dot(temp)\n \n logg.info(\"Phase II: time elapsed -- \", time.time()-t)\n\n\n adata.uns['transition_map']=ssp.csr_matrix(transition_map_1)\n #adata.uns['transition_map_unExtended']=ssp.csr_matrix(clonal_coupling)\n\n\n \n logg.info(\"----Demultiplexed transition map----\")\n\n #pdb.set_trace()\n demultiplexed_map_0=refine_Tmap_through_cospar_noSmooth(multiTime_cell_id_t1,multiTime_cell_id_t2,proportion,clonal_coupling,\n X_clone,noise_threshold=demulti_threshold,normalization_mode=normalization_mode)\n\n idx_t1=hf.converting_id_from_fullSpace_to_subSpace(clonal_cell_id_t1,Tmap_cell_id_t1)[0]\n idx_t2=hf.converting_id_from_fullSpace_to_subSpace(clonal_cell_id_t2,Tmap_cell_id_t2)[0]\n demultiplexed_map=np.zeros((len(Tmap_cell_id_t1),len(Tmap_cell_id_t2)))\n demultiplexed_map[idx_t1[:,np.newaxis],idx_t2]=demultiplexed_map_0.A\n adata.uns['intraclone_transition_map']=ssp.csr_matrix(demultiplexed_map)\n\n\n\ndef infer_intraclone_Tmap(adata,demulti_threshold=0.05,normalization_mode=1):\n \"\"\"\n Infer intra-clone transition map.\n\n Parameters\n ----------\n adata: :class:`~anndata.AnnData` object\n Should be prepared by :func:`.select_time_points`\n demulti_threshold: `float`, optional (default: 0.05)\n noise threshold to remove noises in transition_map,\n in the range [0,1]\n normalization_mode: `int`, optional (default: 1)\n Method for normalization. Choice: [0,1]\n 0, single-cell normalization\n 1, Clone normalization\n\n Returns\n -------\n None. Update/generate adata.uns['intraclone_transition_map']\n\n \"\"\"\n\n ########## extract data\n if 'transition_map' not in adata.uns.keys():\n logg.error(\"Please run ---- CS.tmap.infer_Tmap_from_multitime_clones ---- first\")\n\n else:\n\n clone_annot=adata.obsm['X_clone']\n\n multiTime_cell_id_t1=[adata.uns['Tmap_cell_id_t1']]\n multiTime_cell_id_t2=[adata.uns['Tmap_cell_id_t2']]\n proportion=adata.uns['proportion']\n\n transition_map=adata.uns['transition_map']\n\n X_clone=clone_annot.copy()\n if not ssp.issparse(X_clone):\n X_clone=ssp.csr_matrix(X_clone)\n\n demultiplexed_map=refine_Tmap_through_cospar_noSmooth(multiTime_cell_id_t1,multiTime_cell_id_t2,proportion,transition_map,\n X_clone,noise_threshold=demulti_threshold,normalization_mode=normalization_mode)\n\n adata.uns['intraclone_transition_map']=ssp.csr_matrix(demultiplexed_map)\n\n\n# v0: avoid cells that are already selected. We tested, this is better than not avoiding...\ndef Tmap_from_highly_variable_genes(adata,min_counts=3,min_cells=3,\n min_gene_vscore_pctl=85,smooth_array=[15,10,5],neighbor_N=20,\n noise_threshold=0.2,normalization_mode=1,use_full_Smatrix=False,\n trunca_threshold=0.001,compute_new_Smatrix=True,\n save_subset=True):\n \"\"\"\n Generate Tmap based on state info using HighVar.\n\n We convert differentially expressed genes into `pseudo-clones`,\n and run cospar to infer the transition map. Each clone occupies \n a different set of cells. \n\n Parameters\n ----------\n adata: :class:`~anndata.AnnData` object\n assumed to be preprocessed, only has two time points.\n min_counts: int, optional (default: 3) \n Minimum number of UMIs per cell to be considered for selecting highly variable genes. \n min_cells: int, optional (default: 3)\n Minimum number of cells per gene to be considered for selecting highly variable genes. \n min_gene_vscore_pctl: int, optional (default: 85)\n Genes wht a variability percentile higher than this threshold are marked as \n highly variable genes for dimension reduction. Range: [0,100]\n \n smooth_array: `list`, optional (default: [15,10,5])\n List of smooth rounds at each iteration. \n The n-th entry determines the smooth round for the Smatrix \n at the n-th iteration. Its length determins the number of\n iteration. \n neighbor_N: `int`, optional (default: 20)\n the number of neighbors for KNN graph used for computing the similarity matrix.\n trunca_threshold: `float`, optional (default: 0.001)\n We set entries to zero in the computed similarity matrix that \n are smaller than this threshold. This is to promote the Smatrix sparsity, which\n leads to faster computation, and smaller file size. \n This threshld should be small, but not too small. \n noise_threshold: `float`, optional (default: 0.1)\n noise threshold to remove noises in the updated transition map,\n in the range [0,1]\n normalization_mode: `int`, optional (default: 2)\n Method for normalization. Choice: [0,1,2]\n 0, single-cell normalization\n 1, Clone normalization: N2/N1 (this one does not make sense)\n 2, Clone normalization\n save_subset: `bool`, optional (default: True)\n If true, save only Smatrix at smooth round [5,10,15,...].\n Else, save Smatrix at each round. \n use_full_Smatrix: `bool`, optional (default: False)\n use the Smatrix as defined by all cells, whether they are clonally \n barcoded or not. We sub-sample cell states relevant for downstream \n analysis from this full Smatrix. This may refine the Smatrix. \n But will also increase the computation time significantly.\n compute_new_Smatrix: `bool`, optional (default: False)\n If True, compute Smatrix from scratch, whether it was \n computed and saved before or not.\n\n Returns\n -------\n None. Results are stored at adata.uns['HighVar_transition_map']. \n \"\"\"\n logg.info(\"HighVar-v0: avoid cells that have been selected\")\n weight=1 # wehight of each gene. \n\n cell_id_array_t1=adata.uns['Tmap_cell_id_t1']\n cell_id_array_t2=adata.uns['Tmap_cell_id_t2']\n real_clone_annot=adata.obsm['X_clone']\n\n time_info=np.array(adata.obs['time_info'])\n selected_time_points=[time_info[cell_id_array_t1][0],time_info[cell_id_array_t2][0]]\n\n\n \n logg.info(\"----------------\")\n logg.info('Step a: find the commonly shared highly variable genes')\n adata_t1=sc.AnnData(adata.X[cell_id_array_t1]);\n adata_t2=sc.AnnData(adata.X[cell_id_array_t2]);\n\n ## use marker genes\n gene_list=adata.var_names\n\n verbose=logg._settings_verbosity_greater_or_equal_than(2)\n\n highvar_genes_t1 = gene_list[hf.filter_genes(\n adata_t1.X, \n min_counts=min_counts, \n min_cells=min_cells, \n min_vscore_pctl=min_gene_vscore_pctl, \n show_vscore_plot=verbose)]\n\n highvar_genes_t2 = gene_list[hf.filter_genes(\n adata_t2.X, \n min_counts=min_counts, \n min_cells=min_cells, \n min_vscore_pctl=min_gene_vscore_pctl, \n show_vscore_plot=verbose)]\n\n common_gene=list(set(highvar_genes_t1).intersection(highvar_genes_t2))\n \n logg.info(f\"Highly varable gene number at t1 is {len(highvar_genes_t1)}, Highly varable gene number at t2 is {len(highvar_genes_t2)}\")\n logg.info(f\"Common gene set is {len(common_gene)}\")\n\n logg.info(\"----------------\")\n logg.info('Step b: convert the shared highly variable genes into clonal info')\n\n sel_marker_gene_list=common_gene.copy()\n clone_annot_gene=np.zeros((adata.shape[0],len(sel_marker_gene_list)))\n N_t1=len(cell_id_array_t1)\n N_t2=len(cell_id_array_t2)\n cumu_sel_idx_t1=np.zeros(N_t1,dtype=bool)\n cumu_sel_idx_t2=np.zeros(N_t2,dtype=bool)\n cell_fraction_per_gene=1/len(sel_marker_gene_list) # fraction of cells as clonally related by this gene\n for j,gene_id in enumerate(sel_marker_gene_list): \n temp_t1=adata.obs_vector(gene_id)[cell_id_array_t1]\n temp_t1[cumu_sel_idx_t1]=0 # set selected cell id to have zero expression\n cutoff_t1=int(np.ceil(len(cell_id_array_t1)*cell_fraction_per_gene))\n sel_id_t1=np.argsort(temp_t1,kind='stable')[::-1][:cutoff_t1]\n clone_annot_gene[cell_id_array_t1[sel_id_t1],j]=weight\n cumu_sel_idx_t1[sel_id_t1]=True \n #logg.info(f\"Gene id {gene_id}, cell number at t1 is {sel_id_t1.shape[0]}, fraction at t1: {sel_id_t1.shape[0]/len(cell_id_array_t1)}\")\n\n temp_t2=adata.obs_vector(gene_id)[cell_id_array_t2]\n temp_t2[cumu_sel_idx_t2]=0 # set selected cell id to have zero expression\n cutoff_t2=int(np.ceil(len(cell_id_array_t2)*cell_fraction_per_gene))\n sel_id_t2=np.argsort(temp_t2,kind='stable')[::-1][:cutoff_t2]\n clone_annot_gene[cell_id_array_t2[sel_id_t2],j]=weight\n cumu_sel_idx_t2[sel_id_t2]=True \n #logg.info(f\"Gene id {gene_id}, cell number at t2 is {sel_id_t2.shape[0]}, fraction at t2: {sel_id_t2.shape[0]/len(cell_id_array_t2)}\")\n \n if (np.sum(~cumu_sel_idx_t1)==0) or (np.sum(~cumu_sel_idx_t2)==0):\n logg.info(f'No cells left for assignment, total used genes={j}')\n break\n\n #logg.info(f\"Selected cell fraction: t1 -- {np.sum(cumu_sel_idx_t1)/len(cell_id_array_t1)}; t2 -- {np.sum(cumu_sel_idx_t2)/len(cell_id_array_t2)}\")\n\n\n \n logg.info(\"----------------\")\n logg.info(\"Step c: compute the transition map based on clonal info from highly variable genes\")\n \n adata.obsm['X_clone']=ssp.csr_matrix(clone_annot_gene)\n adata.uns['multiTime_cell_id_t1']=[cell_id_array_t1]\n adata.uns['multiTime_cell_id_t2']=[cell_id_array_t2]\n adata.uns['proportion']=[1]\n data_des_0=adata.uns['data_des'][-1]\n data_des_orig=adata.uns['data_des'][0]\n data_des_1=data_des_0+'_HighVar0' # to distinguish Similarity matrix for this step and the next step of CoSpar (use _HighVar0, instead of _HighVar1)\n adata.uns['data_des']=[data_des_orig,data_des_1]\n\n infer_Tmap_from_multitime_clones_private(adata,smooth_array=smooth_array,neighbor_N=neighbor_N,noise_threshold=noise_threshold,\n normalization_mode=normalization_mode,save_subset=save_subset,use_full_Smatrix=use_full_Smatrix,\n trunca_threshold=trunca_threshold,compute_new_Smatrix=compute_new_Smatrix)\n\n adata.uns['HighVar_transition_map']=adata.uns['transition_map']\n adata.obsm['X_clone']=real_clone_annot # This entry has been changed previously. Note correct the clonal matrix\n data_des_1=data_des_0+'_HighVar1' # to record which initialization is used\n adata.uns['data_des']=[data_des_orig,data_des_1]\n\n\n\n# this is the new version: v1\ndef compute_custom_OT_transition_map(adata,OT_epsilon=0.02,OT_dis_KNN=5,\n OT_solver='duality_gap',OT_cost='SPD',compute_new=True):\n \"\"\"\n Compute Tmap from state info using optimal transport (OT).\n\n We provide the options for the OT solver, and also the cost function. \n The OT solver does not seem to matter, although 'duality_gap' is faster.\n The cost function could affect the OT map results. Using shortest path\n distance ('SPD') is slower but more accurate, while using gene expression\n distance ('GED') is faster but less accurate. The performance of cospar \n is robust to the initialized map (this is especially so in terms of fate\n bias, not so much for the fate map alone)\n\n Parameters\n ----------\n adata: :class:`~anndata.AnnData` object\n Assumed to be preprocessed, only has two time points.\n OT_epsilon: `float`, optional (default: 0.02) \n The entropic regularization, >0, a larger one increases \n uncertainty of the transition\n OT_dis_KNN: `int`, optional (default: 5)\n Number of nearest neighbors to construct the KNN graph for\n computing the shortest path distance. \n OT_solver: `str`, optional (default: `duality_gap`)\n The method used to compute the optimal transport map. Availabel choice: \n {'duality_gap','fixed_iters'}. Our test shows that they produce the same \n results, while 'duality_gap' is almost twice faster. \n OT_cost: `str`, optional (default: `SPD`), options {'GED','SPD'}\n The cost metric. We provide gene expression distance (GED), and also\n shortest path distance (SPD). GED is much faster, but SPD is more accurate.\n However, cospar is robust to the initialization. \n compute_new: `bool`, optional (default: False)\n If True, compute OT_map and also the shortest path distance from scratch, \n whether it was computed and saved before or not.\n\n Returns\n -------\n None. Results are stored at adata.uns['OT_transition_map'].\n \"\"\"\n\n cell_id_array_t1=adata.uns['Tmap_cell_id_t1']\n cell_id_array_t2=adata.uns['Tmap_cell_id_t2']\n data_des=adata.uns['data_des'][-1]\n data_path=settings.data_path\n\n\n ############ Compute shorted-path distance\n # use sklearn KNN graph construction method and select the connectivity option, not related to UMAP\n # use the mode 'distance' to obtain the shortest-path *distance*, rather than 'connectivity'\n if OT_cost=='SPD':\n SPD_file_name=f'{data_path}/{data_des}_ShortestPathDistanceMatrix_t0t1_KNN{OT_dis_KNN}.npy'\n if os.path.exists(SPD_file_name) and (not compute_new):\n\n logg.info(\"Load pre-computed shortest path distance matrix\")\n OT_cost_matrix=np.load(SPD_file_name)\n\n else:\n\n logg.info(\"Compute new shortest path distance matrix\")\n t=time.time() \n #data_matrix=adata.obsm['X_pca']\n #ShortPath_dis=hf.compute_shortest_path_distance_from_raw_matrix(data_matrix,num_neighbors_target=OT_dis_KNN,mode='distance')\n ShortPath_dis=hf.compute_shortest_path_distance(adata,num_neighbors_target=OT_dis_KNN,mode='distances',method='umap')\n \n idx0=cell_id_array_t1\n idx1=cell_id_array_t2\n ShortPath_dis_t0t1=ShortPath_dis[idx0[:,np.newaxis],idx1]; \n OT_cost_matrix=ShortPath_dis_t0t1/ShortPath_dis_t0t1.max()\n\n\n np.save(SPD_file_name,OT_cost_matrix)\n\n\n logg.info(f\"Finishing computing shortest-path distance, used time {time.time()-t}\")\n else:\n t=time.time()\n pc_n=adata.obsm['X_pca'].shape[1]\n OT_cost_matrix=hf.compute_gene_exp_distance(adata,cell_id_array_t1,cell_id_array_t2,pc_n=pc_n)\n logg.info(f\"Finishing computing gene expression distance, used time {time.time()-t}\") \n \n\n ######## apply optimal transport\n CustomOT_file_name=f'{data_path}/{data_des}_CustomOT_map_epsilon{OT_epsilon}_KNN{OT_dis_KNN}.npy'\n if os.path.exists(CustomOT_file_name) and (not compute_new):\n\n logg.info(\"Load pre-computed custon OT matrix\")\n OT_transition_map=np.load(CustomOT_file_name)\n\n else:\n logg.info(\"Compute new custon OT matrix\")\n\n t=time.time()\n mu1=np.ones(len(cell_id_array_t1));\n nu1=np.ones(len(cell_id_array_t2));\n input_mu=mu1 # initial distribution\n input_nu=nu1 # final distribution\n\n ######### We have tested that it is at least 3 times slower than WOT's builtin method, \n #### although the results are the same\n # # This taks 170s for the subsampled hematopoietic data\n# logg.info(\"Use sinkhorn solver solver\")\n# OT_transition_map=otb.sinkhorn_stabilized(input_mu,input_nu,ShortPath_dis_t0t1,OT_epsilon,numItermax=OT_max_iter,stopThr=OT_stopThr)\n\n #############\n\n OT_solver='duality_gap'\n logg.info(f\"OT solver: {OT_solver}\")\n if OT_solver == 'fixed_iters': # This takes 50s for the subsampled hematopoietic data. The result is the same.\n ot_config = {'C':OT_cost_matrix,'G':mu1, 'epsilon': OT_epsilon, 'lambda1': 1, 'lambda2': 50,\n 'epsilon0': 1, 'scaling_iter': 3000,'tau': 10000, 'inner_iter_max': 50, 'extra_iter': 1000}\n \n OT_transition_map=transport_stablev2(**ot_config)\n \n elif OT_solver == 'duality_gap': # This takes 30s for the subsampled hematopoietic data. The result is the same.\n ot_config = {'C':OT_cost_matrix,'G':mu1, 'epsilon': OT_epsilon, 'lambda1': 1, 'lambda2': 50,\n 'epsilon0': 1, 'tau': 10000, 'tolerance': 1e-08,\n 'max_iter': 1e7, 'batch_size': 5}\n \n OT_transition_map=optimal_transport_duality_gap(**ot_config)\n \n else:\n raise ValueError('Unknown solver')\n\n np.save(CustomOT_file_name,OT_transition_map)\n\n logg.info(f\"Finishing computing optial transport map, used time {time.time()-t}\")\n\n\n adata.uns['OT_transition_map']=ssp.csr_matrix(OT_transition_map)\n data_des_0=adata.uns['data_des'][-1]\n data_des_orig=adata.uns['data_des'][0]\n data_des_1=data_des_0+'_OT' # to record which initialization is used\n adata.uns['data_des']=[data_des_orig,data_des_1]\n\n\n\n\n# We tested that, for clones of all different sizes, where np.argsort gives unique results, \n# this method reproduces the v01, v1 results, when use_fixed_clonesize_t1=True, and when change\n# sort_clone=0,1,-1.\ndef infer_Tmap_from_one_time_clones_private(adata,initialized_map,Clone_update_iter_N=1,\n smooth_array=[15,10,5],CoSpar_KNN=20,normalization_mode=1,noise_threshold=0.2,\n use_full_Smatrix=False,trunca_threshold=0.001,compute_new=True,\n use_fixed_clonesize_t1=False,sort_clone=1):\n \"\"\"\n Infer Tmap from clones with a single time point\n\n Starting from an initialized transitin map from state information,\n we jointly infer the initial clonal states and the transition map.\n\n This method has been optimized to be very fast. Besides, it is\n deterministic. \n\n Parameters\n ----------\n adata: :class:`~anndata.AnnData` object\n Should have only two time points. \n initialized_map: `sp.spmatrix`\n Initialized transition map based on state information alone.\n Clone_update_iter_N: `int`, optional (default: 1)\n Number of iteration for the joint optimization.\n normalization_mode: `int`, optional (default: 1)\n Method for normalization. Choice: [0,1]\n 0, single-cell normalization\n 1, Clone normalization\n smooth_array: `list`, optional (default: [15,10,5])\n List of smooth rounds at each iteration. \n The n-th entry determines the smooth round for the Smatrix \n at the n-th iteration. Its length determins the number of\n iteration. It is better to use a number at the multiple of \n 5, i.e., 5, 10, 15, 20,... \n CoSpar_KNN: `int`, optional (default: 20)\n the number of neighbors for KNN graph used for computing the similarity matrix.\n trunca_threshold: `float`, optional (default: 0.001)\n We set entries to zero in the computed similarity matrix that \n are smaller than this threshold. This is to promote the Smatrix sparsity, which\n leads to faster computation, and smaller file size. \n This threshld should be small, but not too small. \n noise_threshold: `float`, optional (default: 0.1)\n threshold to remove noises in the updated transition map,\n in the range [0,1]\n save_subset: `bool`, optional (default: True)\n If true, save only Smatrix at smooth round [5,10,15,...].\n Else, save Smatrix at each round. \n use_full_Smatrix: `bool`, optional (default: False)\n use the Smatrix as defined by all cells, whether they are clonally \n barcoded or not. We sub-sample cell states relevant for downstream \n analysis from this full Smatrix. This may refine the Smatrix. \n But will also increase the computation time significantly.\n use_fixed_clonesize_t1: `bool`, optional (default: False)\n If true, fix the number of initial states as the same for all clones\n sort_clone: `int`, optional (default: 1)\n The order to infer initial states for each clone: {1,-1,others}\n 1, sort clones by size from small to large\n -1,sort clones by size from large to small\n others, do not sort. \n compute_new: `bool`, optional (default: False)\n If True, compute everthing (ShortestPathDis,OT_map etc.) from scratch, \n whether it was computed and saved before or not.\n\n Returns\n ------\n None. Update adata.obsm['X_clone'] and adata.uns['transition_map'],\n as well as adata.uns['OT_transition_map'] or \n adata.uns['intraclone_transition_map'], depending on the initialization.\n \"\"\"\n\n # I found the error: 1) we should use clonally related cell number at t2 as a factor to determine the clonally cell number at t1\n # 2) update the whole t2 clonal info at once\n\n logg.info(\"Joint optimization that consider possibility of clonal overlap: v2\")\n\n cell_id_array_t1=adata.uns['Tmap_cell_id_t1']\n cell_id_array_t2=adata.uns['Tmap_cell_id_t2']\n data_des=adata.uns['data_des'][-1]\n data_path=settings.data_path\n X_clone=adata.obsm['X_clone']\n if not ssp.issparse(X_clone): X_clone=ssp.csr_matrix(X_clone) \n\n time_info=np.array(adata.obs['time_info'])\n time_index_t1=time_info==(time_info[cell_id_array_t1[0]])\n time_index_t2=time_info==(time_info[cell_id_array_t2[0]])\n\n if not ssp.issparse(initialized_map):\n map_temp=ssp.csr_matrix(initialized_map)\n else:\n map_temp=initialized_map\n\n\n # a clone must has at least 2 cells, to be updated later. \n valid_clone_id=np.nonzero(X_clone[cell_id_array_t2].sum(0).A.flatten()>0)[0]\n X_clone_temp=X_clone[:,valid_clone_id]\n clonal_cells_t2=np.sum(X_clone_temp[cell_id_array_t2].sum(1).flatten())\n\n logg.hint(f\"original clone shape: {X_clone.shape}\")\n logg.hint(f\"After excluding zero-sized clones at t2: {X_clone_temp.shape}\")\n\n\n flag=True # to check whether overlapping clones are found or not\n if use_fixed_clonesize_t1:\n logg.info(\"Use fixed clone size at t1\")\n\n ##### Partition cells into non-overlapping, combinatorial BC_id. \n # ---------------------------------\n # find the combinatorial barcodes\n clone_idx=np.nonzero(X_clone_temp.A)\n dic=[[] for j in range(X_clone_temp.shape[0])] # a list of list\n for j in range(clone_idx[0].shape[0]):\n dic[clone_idx[0][j]].append(clone_idx[1][j])\n\n BC_id=[tuple(x) for x in dic] # a BC_id is a unique barcode combination, does not change the ordering of cells\n\n\n # --------------------\n # construct the new X_clone_temp matrix, and the clone_mapping\n unique_BC_id=list(set(BC_id))\n if () in unique_BC_id: # () is resulted from cells without any barcodes\n unique_BC_id.remove(())\n\n # construct a X_clone_newBC for the new BC_id\n # also record how the new BC_id is related to the old barcode\n\n X_clone_newBC=np.zeros((X_clone_temp.shape[0],len(unique_BC_id)))\n for i, BC_0 in enumerate(BC_id):\n for j, BC_1 in enumerate(unique_BC_id):\n if BC_1==BC_0:\n X_clone_newBC[i,j]=1 # does not change the ordering of cells\n\n clone_mapping=np.zeros((X_clone_temp.shape[1],X_clone_newBC.shape[1]))\n for j, BC_1 in enumerate(unique_BC_id):\n for k in BC_1:\n clone_mapping[k,j]=1\n\n X_clone_newBC=ssp.csr_matrix(X_clone_newBC)\n clone_mapping=ssp.csr_matrix(clone_mapping)\n # To recover the original X_clone_temp, use 'X_clone_newBC*(clone_mapping.T)'\n # howver, clone_mapping is not invertible. We cannot get from X_clone_temp to \n # X_clone_newBC using matrix multiplification.\n\n\n\n ### select the early states using the grouped distribution of a clone\n ### clones are not overlapping, and all early states should be attached to clones at the end\n\n # we sort clones according to their sizes. The order of cells are not affected. So, it should not affect downstream analysis\n # small clones tend to be the ones that are barcoded/mutated later, while large clones tend to be early mutations...\n clone_size_t2_temp=X_clone_newBC[cell_id_array_t2].sum(0).A.flatten()\n\n\n if sort_clone==1:\n logg.info(\"Sort clones by size (small to large)\")\n\n sort_clone_id=np.argsort(clone_size_t2_temp,kind='stable')\n clone_size_t2=clone_size_t2_temp[sort_clone_id]\n X_clone_sort=X_clone_newBC[:,sort_clone_id]\n clone_mapping_sort=clone_mapping[:,sort_clone_id]\n\n elif sort_clone==-1:\n logg.info(\"Sort clones by size (large to small)\")\n\n sort_clone_id=np.argsort(clone_size_t2_temp,kind='stable')[::-1]\n clone_size_t2=clone_size_t2_temp[sort_clone_id]\n X_clone_sort=X_clone_newBC[:,sort_clone_id]\n clone_mapping_sort=clone_mapping[:,sort_clone_id]\n\n else:\n logg.info(\"Do not order clones by size \")\n clone_size_t2=clone_size_t2_temp\n X_clone_sort=X_clone_newBC\n clone_mapping_sort=clone_mapping\n\n\n logg.info(\"Infer the number of initial cells to extract for each clone in advance\")\n clone_N1=X_clone_sort.shape[1]\n ave_clone_size_t1=int(np.ceil(len(cell_id_array_t1)/clone_N1));\n cum_cell_N=np.ceil(np.cumsum(clone_size_t2)*len(cell_id_array_t1)/clonal_cells_t2)\n cell_N_to_extract=np.zeros(len(cum_cell_N),dtype=int)\n if use_fixed_clonesize_t1:\n cell_N_to_extract += ave_clone_size_t1\n else:\n cell_N_to_extract[0]=cum_cell_N[0]\n cell_N_to_extract[1:]=np.diff(cum_cell_N)\n\n\n for x0 in range(Clone_update_iter_N):\n\n\n # update initial state probability matrix based on the current map \n initial_prob_matrix=(map_temp*X_clone_sort[cell_id_array_t2]).A # a initial probability matrix for t1 cells, shape (n_t1_cell,n_clone)\n \n\n ########## begin: update clones\n remaining_ids_t1=list(np.arange(len(cell_id_array_t1),dtype=int))\n\n X_clone_new=np.zeros(X_clone_sort.shape,dtype=bool)\n X_clone_new[cell_id_array_t2]=X_clone_sort[cell_id_array_t2].A.astype(bool) # update the whole t2 clones at once\n\n for j in range(clone_N1):\n if (j%100==0):\n #pdb.set_trace()\n logg.hint(f\"Inferring early clonal states: current clone id {j}\")\n\n\n\n # infer the earlier clonal states for each clone\n ### select the early states using the grouped distribution of a clone\n sorted_id_array=np.argsort(initial_prob_matrix[remaining_ids_t1,j],kind='stable')[::-1]\n\n sel_id_t1=sorted_id_array[:cell_N_to_extract[j]]\n temp_t1_idx=np.zeros(len(cell_id_array_t1),dtype=bool)\n temp_t1_idx[np.array(remaining_ids_t1)[sel_id_t1]]=True\n X_clone_new[cell_id_array_t1,j]=temp_t1_idx\n for kk in np.array(remaining_ids_t1)[sel_id_t1]:\n remaining_ids_t1.remove(kk)\n\n if (len(remaining_ids_t1)==0) and ((j+1)<clone_N1): \n logg.hint(f'Early break; current clone id: {j+1}')\n break\n\n ########### end: update clones\n cell_id_array_t1_new=np.nonzero((X_clone_new.sum(1)>0) & (time_index_t1))[0]\n cell_id_array_t2_new=np.nonzero((X_clone_new.sum(1)>0) & (time_index_t2))[0]\n\n adata.obsm['X_clone']=ssp.csr_matrix(X_clone_new)*(clone_mapping_sort.T) # convert back to the original clone structure\n adata.uns['multiTime_cell_id_t1']=[cell_id_array_t1_new] # For CoSpar, clonally-related states\n adata.uns['multiTime_cell_id_t2']=[cell_id_array_t2_new]\n adata.uns['clonal_cell_id_t1']=cell_id_array_t1_new # for prepare the similarity matrix with same cell states\n adata.uns['clonal_cell_id_t2']=cell_id_array_t2_new\n adata.uns['proportion']=[1]\n\n infer_Tmap_from_multitime_clones_private(adata,smooth_array=smooth_array,neighbor_N=CoSpar_KNN,noise_threshold=noise_threshold,\n normalization_mode=normalization_mode,save_subset=True,use_full_Smatrix=use_full_Smatrix,\n trunca_threshold=trunca_threshold,compute_new_Smatrix=compute_new)\n\n # update, for the next iteration\n map_temp=adata.uns['transition_map']\n\n\n\n\ndef infer_Tmap_from_one_time_clones(adata_orig,initial_time_points,clonal_time_point,\n initialize_method='OT',OT_epsilon=0.02,OT_dis_KNN=5,OT_cost='SPD',\n HighVar_gene_pctl=85,Clone_update_iter_N=1,normalization_mode=1,\n noise_threshold=0.2,CoSpar_KNN=20,use_full_Smatrix=False,smooth_array=[15,10,5],\n trunca_threshold=0.001,compute_new=False,\n use_fixed_clonesize_t1=False,sort_clone=1,save_subset=True):\n \"\"\"\n Infer transition map from clones with a single time point\n\n We iteratively infer transition map between each of the initial \n time points ['day_1','day_2',...,] and the time point with clonal \n observation. Given the two time points, after initializing the map \n by either OT method or HighVar method, we jointly infer the likely \n initial clonal cells and the transition map between cell states \n in these two time points. \n\n **Summary**\n \n * Parameters relevant for cell state selection: initial_time_points, \n clonal_time_point, use_full_Smatrix.\n\n * Choose the initialization method, and set the corresponding parameters. \n\n * 'OT': tend to be more accurate, but not reliable \n under batch effect. Key parameters: `OT_epsilon, OT_dis_KNN`. \n \n * 'HighVar': is robust to batch effect, but not as accurate.\n Key parameter: `HighVar_gene_pctl`.\n\n * Key parameters relevant for CoSpar itself: `smooth_array, normalization_mode, \n CoSpar_KNN, noise_threshold, Clone_update_iter_N`.\n\n Parameters\n ----------\n adata_orig: :class:`~anndata.AnnData` object\n assumed to be preprocessed, can have multiple time points.\n initial_time_points: `list` \n List of initial time points to be included for the transition map. \n Like ['day_1','day_2']. Entries consistent with adata.obs['time_info']. \n clonal_time_point: `str` \n The time point with clonal observation. Its value should be \n consistent with adata.obs['time_info']. \n initialize_method: `str`, optional (default 'OT') \n Method to initialize the transition map from state information. \n Choice: {'OT', 'HighVar'}.\n OT_epsilon: `float`, optional (default: 0.02) \n The entropic regularization, >0, a larger one increases \n uncertainty of the transition. Relevant when `initialize_method='OT'`.\n OT_dis_KNN: `int`, optional (default: 5)\n Number of nearest neighbors to construct the KNN graph for\n computing the shortest path distance. Relevant when `initialize_method='OT'`. \n OT_cost: `str`, optional (default: `SPD`), options {'GED','SPD'}\n The cost metric. We provide gene expression distance (GED), and also\n shortest path distance (SPD). GED is much faster, but SPD is more accurate.\n However, cospar is robust to the initialization. \n HighVar_gene_pctl: `int`, optional (default: 85)\n percentile threshold to select highly variable genes. Range: [0,100]. \n A higher value selects more variable genes.\n Relevant when `initialize_method='HighVar'`.\n Clone_update_iter_N: `int`, optional (default: 1)\n Number of iteration for the joint optimization\n normalization_mode: `int`, optional (default: 1)\n Method for normalization. Choice: [0,1]\n 0, single-cell normalization\n 1, Clone normalization\n smooth_array: `list`, optional (default: [15,10,5])\n List of smooth rounds at each iteration. \n The n-th entry determines the smooth round for the Smatrix \n at the n-th iteration. Its length determins the number of\n iteration. It is better to use a number at the multiple of \n 5, i.e., 5, 10, 15, 20,... \n CoSpar_KNN: `int`, optional (default: 20)\n the number of neighbors for KNN graph used for computing the similarity matrix.\n trunca_threshold: `float`, optional (default: 0.001)\n We set entries to zero in the computed similarity matrix that \n are smaller than this threshold. This is to promote the Smatrix sparsity, which\n leads to faster computation, and smaller file size. \n This threshld should be small, but not too small. \n noise_threshold: `float`, optional (default: 0.1)\n noise threshold to remove noises in the updated transition map,\n in the range [0,1]\n save_subset: `bool`, optional (default: True)\n If true, save only Smatrix at smooth round [5,10,15,...].\n Else, save Smatrix at each round. \n use_full_Smatrix: `bool`, optional (default: False)\n use the Smatrix as defined by all cells, whether they are clonally \n barcoded or not. We sub-sample cell states relevant for downstream \n analysis from this full Smatrix. This may refine the Smatrix. \n But will also increase the computation time significantly.\n use_fixed_clonesize_t1: `bool`, optional (default: False)\n If true, fix the number of initial states as the same for all clones\n sort_clone: `int`, optional (default: 1)\n The order to infer initial states for each clone: {1,-1,others}\n 1, sort clones by size from small to large\n -1,sort clones by size from large to small\n others, do not sort. \n compute_new: `bool`, optional (default: False)\n If True, compute everthing (ShortestPathDis,OT_map etc.) from scratch, \n whether it was computed and saved before or not. Regarding the Smatrix, it is \n recomputed only when `use_full_Smatrix=False`.\n\n Returns\n -------\n adata: :class:`~anndata.AnnData` object\n Update adata.obsm['X_clone'] and adata.uns['transition_map'],\n as well as adata.uns['OT_transition_map'] or \n adata.uns['intraclone_transition_map'], depending on the initialization.\n \"\"\"\n\n t0=time.time()\n\n for xx in initial_time_points:\n if xx not in list(set(adata_orig.obs['time_info'])):\n logg.error(f\"the 'initial_time_points' are not valid. Please select from {list(set(adata_orig.obs['time_info']))}\")\n return adata_orig\n\n hf.check_available_clonal_info(adata_orig)\n with_clonal_info=(clonal_time_point in adata_orig.uns['clonal_time_points'])\n if not with_clonal_info:\n logg.warn(f\"'clonal_time_point' do not contain clonal information. Please set clonal_time_point to be one of {adata_orig.uns['clonal_time_points']}\")\n #logg.info(\"Consider run ----cs.tmap.CoSpar_NoClonalInfo------\")\n logg.warn(\"Keep running but without clonal information\")\n #return adata_orig\n\n sp_idx=np.zeros(adata_orig.shape[0],dtype=bool)\n time_info_orig=np.array(adata_orig.obs['time_info'])\n all_time_points=initial_time_points+[clonal_time_point]\n label='t'\n for xx in all_time_points:\n id_array=np.nonzero(time_info_orig==xx)[0]\n sp_idx[id_array]=True\n label=label+'*'+str(xx)\n\n adata=sc.AnnData(adata_orig.X[sp_idx]);\n adata.var_names=adata_orig.var_names\n adata.obsm['X_pca']=adata_orig.obsm['X_pca'][sp_idx]\n adata.obsm['X_emb']=adata_orig.obsm['X_emb'][sp_idx]\n adata.obs['state_info']=pd.Categorical(adata_orig.obs['state_info'][sp_idx])\n adata.obs['time_info']=pd.Categorical(adata_orig.obs['time_info'][sp_idx])\n \n data_des_orig=adata_orig.uns['data_des'][0]\n data_des_0=adata_orig.uns['data_des'][-1]\n data_des=data_des_0+f'_OneTimeClone_{label}'\n adata.uns['data_des']=[data_des_orig,data_des]\n\n \n\n\n clone_annot_orig=adata_orig.obsm['X_clone'] \n clone_annot=clone_annot_orig[sp_idx]\n adata.obsm['X_clone']=clone_annot\n\n time_info=np.array(adata.obs['time_info'])\n time_index_t2=time_info==clonal_time_point\n time_index_t1=~time_index_t2\n\n #### used for similarity matrix generation\n Tmap_cell_id_t1=np.nonzero(time_index_t1)[0]\n Tmap_cell_id_t2=np.nonzero(time_index_t2)[0]\n adata.uns['Tmap_cell_id_t1']=Tmap_cell_id_t1\n adata.uns['Tmap_cell_id_t2']=Tmap_cell_id_t2\n adata.uns['clonal_cell_id_t1']=Tmap_cell_id_t1\n adata.uns['clonal_cell_id_t2']=Tmap_cell_id_t2\n adata.uns['sp_idx']=sp_idx\n data_path=settings.data_path\n\n transition_map=np.zeros((len(Tmap_cell_id_t1),len(Tmap_cell_id_t2)))\n ini_transition_map=np.zeros((len(Tmap_cell_id_t1),len(Tmap_cell_id_t2)))\n\n\n for yy in initial_time_points:\n \n logg.info(\"-------------------------------New Start--------------------------------------------------\")\n logg.info(f\"Current time point: {yy}\")\n\n adata_temp=infer_Tmap_from_one_time_clones_twoTime(adata_orig,selected_two_time_points=[yy,clonal_time_point],\n initialize_method=initialize_method,OT_epsilon=OT_epsilon,OT_dis_KNN=OT_dis_KNN,\n OT_cost=OT_cost,HighVar_gene_pctl=HighVar_gene_pctl,\n Clone_update_iter_N=Clone_update_iter_N,normalization_mode=normalization_mode,\n noise_threshold=noise_threshold,CoSpar_KNN=CoSpar_KNN,use_full_Smatrix=use_full_Smatrix,smooth_array=smooth_array,\n trunca_threshold=trunca_threshold,compute_new=compute_new,\n use_fixed_clonesize_t1=use_fixed_clonesize_t1,sort_clone=sort_clone,save_subset=save_subset)\n\n temp_id_t1=np.nonzero(time_info==yy)[0]\n sp_id_t1=hf.converting_id_from_fullSpace_to_subSpace(temp_id_t1,Tmap_cell_id_t1)[0]\n \n if with_clonal_info:\n transition_map_temp=adata_temp.uns['transition_map'].A\n transition_map[sp_id_t1,:]=transition_map_temp\n\n if initialize_method=='OT':\n transition_map_ini_temp=adata_temp.uns['OT_transition_map']\n else:\n transition_map_ini_temp=adata_temp.uns['HighVar_transition_map']\n\n ini_transition_map[sp_id_t1,:]=transition_map_ini_temp.A\n\n if with_clonal_info:\n adata.uns['transition_map']=ssp.csr_matrix(transition_map)\n \n if initialize_method=='OT':\n adata.uns['OT_transition_map']=ssp.csr_matrix(ini_transition_map)\n else:\n adata.uns['HighVar_transition_map']=ssp.csr_matrix(ini_transition_map)\n\n\n logg.info(f\"-----------Total used time: {time.time()-t0} s ------------\")\n return adata\n\n\n\ndef infer_Tmap_from_state_info_alone(adata_orig,initial_time_points,target_time_point,\n method='OT',OT_epsilon=0.02,OT_dis_KNN=5,OT_cost='SPD',\n HighVar_gene_pctl=85,normalization_mode=1,noise_threshold=0.2,\n CoSpar_KNN=20,use_full_Smatrix=False,smooth_array=[15,10,5],\n trunca_threshold=0.001,compute_new=False,save_subset=True):\n \"\"\"\n Infer transition map from state information alone.\n\n We iteratively infer transition map between each of the initial \n time points ['day_1','day_2',...,] and the targeted time point.\n Given each two-time pair, we infer the map by either OT method \n or HighVar method:\n\n * 'OT': tend to be more accurate, but not reliable \n under batch effect. Key parameters: `OT_epsilon, OT_dis_KNN`. \n\n * 'HighVar': is robust to batch effect, but not as accurate.\n Key parameter: `HighVar_gene_pctl`.\n\n Parameters\n ----------\n adata_orig: :class:`~anndata.AnnData` object\n assumed to be preprocessed, can have multiple time points.\n initial_time_points: `list` \n List of initial time points to be included for the transition map. \n Like ['day_1','day_2']. Entries consistent with adata.obs['time_info']. \n clonal_time_point: `str` \n The time point with clonal observation. Its value should be \n consistent with adata.obs['time_info']. \n method: `str`, optional (default 'OT') \n Method to initialize the transition map from state information. \n Choice: {'OT', 'HighVar'}.\n OT_epsilon: `float`, optional (default: 0.02) \n The entropic regularization, >0, a larger one increases \n uncertainty of the transition. Relevant when `method='OT'`.\n OT_dis_KNN: `int`, optional (default: 5)\n Number of nearest neighbors to construct the KNN graph for\n computing the shortest path distance. Relevant when `method='OT'`. \n OT_cost: `str`, optional (default: `SPD`), options {'GED','SPD'}\n The cost metric. We provide gene expression distance (GED), and also\n shortest path distance (SPD). GED is much faster, but SPD is more accurate.\n However, cospar is robust to the initialization. \n HighVar_gene_pctl: `int`, optional (default: 85)\n Genes wht a variability percentile higher than this threshold are marked as \n highly variable genes for dimension reduction. Range: [0,100]. \n Relevant when `method='HighVar'`.\n normalization_mode: `int`, optional (default: 1)\n Method for normalization. Choice: [0,1]\n 0, single-cell normalization\n 1, Clone normalization\n smooth_array: `list`, optional (default: [15,10,5])\n List of smooth rounds at each iteration. \n The n-th entry determines the smooth round for the Smatrix \n at the n-th iteration. Its length determins the number of\n iteration. It is better to use a number at the multiple of \n 5, i.e., 5, 10, 15, 20,... \n CoSpar_KNN: `int`, optional (default: 20)\n the number of neighbors for KNN graph used for computing the similarity matrix.\n trunca_threshold: `float`, optional (default: 0.001)\n We set entries to zero in the computed similarity matrix that \n are smaller than this threshold. This is to promote the Smatrix sparsity, which\n leads to faster computation, and smaller file size. \n This threshld should be small, but not too small. \n noise_threshold: `float`, optional (default: 0.1)\n noise threshold to remove noises in the updated transition map,\n in the range [0,1]\n save_subset: `bool`, optional (default: True)\n If true, save only Smatrix at smooth round [5,10,15,...].\n Else, save Smatrix at each round. \n use_full_Smatrix: `bool`, optional (default: False)\n use the Smatrix as defined by all cells, whether they are clonally \n barcoded or not. We sub-sample cell states relevant for downstream \n analysis from this full Smatrix. This may refine the Smatrix. \n But will also increase the computation time significantly.\n compute_new: `bool`, optional (default: False)\n If True, compute everthing (ShortestPathDis,OT_map etc.) from scratch, \n whether it was computed and saved before or not. Regarding the Smatrix, it is \n recomputed only when `use_full_Smatrix=False`.\n\n Returns\n -------\n adata: :class:`~anndata.AnnData` object\n Update adata.uns['OT_transition_map'] or adata.uns['intraclone_transition_map'], \n depending on the initialization.\n \"\"\"\n\n t0=time.time()\n\n for xx in initial_time_points:\n if xx not in list(set(adata_orig.obs['time_info'])):\n print(f\"the 'initial_time_points' are not valid. Please select from {list(set(adata_orig.obs['time_info']))}\")\n return adata_orig\n\n sp_idx=np.zeros(adata_orig.shape[0],dtype=bool)\n time_info_orig=np.array(adata_orig.obs['time_info'])\n all_time_points=initial_time_points+[target_time_point]\n label='t'\n for xx in all_time_points:\n id_array=np.nonzero(time_info_orig==xx)[0]\n sp_idx[id_array]=True\n label=label+'*'+str(xx)\n\n adata=sc.AnnData(adata_orig.X[sp_idx]);\n adata.var_names=adata_orig.var_names\n adata.obsm['X_pca']=adata_orig.obsm['X_pca'][sp_idx]\n adata.obsm['X_emb']=adata_orig.obsm['X_emb'][sp_idx]\n adata.obs['state_info']=pd.Categorical(adata_orig.obs['state_info'][sp_idx])\n adata.obs['time_info']=pd.Categorical(adata_orig.obs['time_info'][sp_idx])\n \n data_des_orig=adata_orig.uns['data_des'][0]\n data_des_0=adata_orig.uns['data_des'][-1]\n data_des=data_des_0+f'_stateInfo_{label}'\n adata.uns['data_des']=[data_des_orig,data_des]\n \n\n\n clone_annot_orig=adata_orig.obsm['X_clone'] \n clone_annot=clone_annot_orig[sp_idx]\n adata.obsm['X_clone']=clone_annot\n\n time_info=np.array(adata.obs['time_info'])\n time_index_t2=time_info==target_time_point\n time_index_t1=~time_index_t2\n\n #### used for similarity matrix generation\n Tmap_cell_id_t1=np.nonzero(time_index_t1)[0]\n Tmap_cell_id_t2=np.nonzero(time_index_t2)[0]\n adata.uns['Tmap_cell_id_t1']=Tmap_cell_id_t1\n adata.uns['Tmap_cell_id_t2']=Tmap_cell_id_t2\n adata.uns['clonal_cell_id_t1']=Tmap_cell_id_t1\n adata.uns['clonal_cell_id_t2']=Tmap_cell_id_t2\n adata.uns['sp_idx']=sp_idx\n #data_path=settings.data_path\n\n ini_transition_map=np.zeros((len(Tmap_cell_id_t1),len(Tmap_cell_id_t2)))\n\n\n for yy in initial_time_points:\n \n print(\"-------------------------------New Start--------------------------------------------------\")\n print(f\"Current time point: {yy}\")\n\n # inactive the joint optimization by setting joint_optimization=False\n adata_temp=infer_Tmap_from_one_time_clones_twoTime(adata_orig,selected_two_time_points=[yy,target_time_point],\n initialize_method=method,OT_epsilon=OT_epsilon,OT_dis_KNN=OT_dis_KNN,\n OT_cost=OT_cost,HighVar_gene_pctl=HighVar_gene_pctl,normalization_mode=normalization_mode,\n noise_threshold=noise_threshold,CoSpar_KNN=CoSpar_KNN,use_full_Smatrix=use_full_Smatrix,smooth_array=smooth_array,\n trunca_threshold=trunca_threshold,compute_new=compute_new,joint_optimization=False,save_subset=save_subset)\n\n temp_id_t1=np.nonzero(time_info==yy)[0]\n sp_id_t1=hf.converting_id_from_fullSpace_to_subSpace(temp_id_t1,Tmap_cell_id_t1)[0]\n \n\n if method=='OT':\n transition_map_ini_temp=adata_temp.uns['OT_transition_map']\n else:\n transition_map_ini_temp=adata_temp.uns['HighVar_transition_map']\n\n ini_transition_map[sp_id_t1,:]=transition_map_ini_temp.A\n\n \n if method=='OT':\n adata.uns['OT_transition_map']=ssp.csr_matrix(ini_transition_map)\n else:\n adata.uns['HighVar_transition_map']=ssp.csr_matrix(ini_transition_map)\n\n logg.info(f\"-----------Total used time: {time.time()-t0} s ------------\")\n\n return adata\n\n\ndef infer_Tmap_from_one_time_clones_twoTime(adata_orig,selected_two_time_points=['1','2'],\n initialize_method='OT',OT_epsilon=0.02,OT_dis_KNN=5,OT_cost='SPD',HighVar_gene_pctl=80,\n Clone_update_iter_N=1,normalization_mode=1,noise_threshold=0.2,CoSpar_KNN=20,\n use_full_Smatrix=False,smooth_array=[15,10,5],\n trunca_threshold=0.001,compute_new=True,use_fixed_clonesize_t1=False,\n sort_clone=1,save_subset=True,joint_optimization=True):\n \"\"\"\n Infer transition map from clones with a single time point\n\n It is the same as :func:`.infer_Tmap_from_one_time_clones`, except that\n it assumes that the input adata_orig has only two time points. \n\n joint_optimization: `bool`, optional (default: True). \n \"\"\"\n\n time_info_orig=np.array(adata_orig.obs['time_info'])\n sort_time_point=np.sort(list(set(time_info_orig)))\n N_valid_time=np.sum(np.in1d(sort_time_point,selected_two_time_points))\n if (N_valid_time!=2): \n logg.error(f\"Must select only two time points among the list {sort_time_point}\")\n #The second time point in this list (not necessarily later time point) is assumed to have clonal data.\")\n else:\n ####################################\n \n logg.info(\"-----------Pre-processing and sub-sampling cells------------\")\n # select cells from the two time points, and sub-sampling, create the new adata object with these cell states\n sp_idx=(time_info_orig==selected_two_time_points[0]) | (time_info_orig==selected_two_time_points[1])\n \n adata=sc.AnnData(adata_orig.X[sp_idx]);\n adata.var_names=adata_orig.var_names\n adata.obsm['X_pca']=adata_orig.obsm['X_pca'][sp_idx]\n adata.obsm['X_emb']=adata_orig.obsm['X_emb'][sp_idx]\n adata.obs['state_info']=pd.Categorical(adata_orig.obs['state_info'][sp_idx])\n adata.obs['time_info']=pd.Categorical(adata_orig.obs['time_info'][sp_idx])\n \n data_des_0=adata_orig.uns['data_des'][-1]\n data_des_orig=adata_orig.uns['data_des'][0]\n data_des=data_des_0+f'_OneTimeClone_t*{selected_two_time_points[0]}*{selected_two_time_points[1]}'\n adata.uns['data_des']=[data_des_orig,data_des]\n \n\n\n clone_annot_orig=adata_orig.obsm['X_clone'] \n barcode_id=np.nonzero(clone_annot_orig[sp_idx].A.sum(0).flatten()>0)[0]\n clone_annot=clone_annot_orig[sp_idx][:,barcode_id]\n adata.obsm['X_clone']=clone_annot\n\n time_info=np.array(adata.obs['time_info'])\n time_index_t1=time_info==selected_two_time_points[0]\n time_index_t2=time_info==selected_two_time_points[1]\n\n #### used for similarity matrix generation\n Tmap_cell_id_t1=np.nonzero(time_index_t1)[0]\n Tmap_cell_id_t2=np.nonzero(time_index_t2)[0]\n adata.uns['Tmap_cell_id_t1']=Tmap_cell_id_t1\n adata.uns['Tmap_cell_id_t2']=Tmap_cell_id_t2\n adata.uns['clonal_cell_id_t1']=Tmap_cell_id_t1\n adata.uns['clonal_cell_id_t2']=Tmap_cell_id_t2\n adata.uns['sp_idx']=sp_idx\n data_path=settings.data_path\n\n\n cell_id_array_t1=Tmap_cell_id_t1\n cell_id_array_t2=Tmap_cell_id_t2\n\n ###############################\n # prepare the similarity matrix with all state info, all subsequent similarity will be down-sampled from this one.\n if use_full_Smatrix: \n\n temp_str='0'+str(trunca_threshold)[2:]\n round_of_smooth=np.max(smooth_array)\n data_des=adata_orig.uns['data_des'][0]\n similarity_file_name=f'{data_path}/{data_des}_Similarity_matrix_with_all_cell_states_kNN{CoSpar_KNN}_Truncate{temp_str}'\n if not (os.path.exists(similarity_file_name+f'_SM{round_of_smooth}.npz') and (not compute_new)):\n similarity_matrix_full=generate_similarity_matrix(adata_orig,similarity_file_name,round_of_smooth=round_of_smooth,\n neighbor_N=CoSpar_KNN,truncation_threshold=trunca_threshold,save_subset=save_subset,compute_new_Smatrix=compute_new)\n\n \n\n if initialize_method=='OT':\n \n logg.info(\"----------------\")\n logg.info(\"Step 1: Use OT method for initialization\")\n\n compute_custom_OT_transition_map(adata,OT_epsilon=OT_epsilon,OT_cost=OT_cost,OT_dis_KNN=OT_dis_KNN,compute_new=compute_new)\n OT_transition_map=adata.uns['OT_transition_map']\n initialized_map=OT_transition_map\n\n \n else:\n \n logg.info(\"----------------\")\n logg.info(\"Step 1: Use highly variable genes to construct pseudo-clones, and apply CoSpar to generate initialized map!\")\n\n t=time.time()\n Tmap_from_highly_variable_genes(adata,min_counts=3,min_cells=3,min_gene_vscore_pctl=HighVar_gene_pctl,noise_threshold=noise_threshold,neighbor_N=CoSpar_KNN,\n normalization_mode=normalization_mode,use_full_Smatrix=use_full_Smatrix,smooth_array=smooth_array,trunca_threshold=trunca_threshold,\n compute_new_Smatrix=compute_new)\n\n HighVar_transition_map=adata.uns['HighVar_transition_map']\n initialized_map=HighVar_transition_map\n\n \n logg.info(f\"Finishing computing transport map from highly variable genes, used time {time.time()-t}\")\n\n\n if joint_optimization:\n ########### Jointly optimize the transition map and the initial clonal states\n if selected_two_time_points[1] in adata_orig.uns['clonal_time_points']:\n \n logg.info(\"----------------\")\n logg.info(\"Step 2: Jointly optimize the transition map and the initial clonal states!\")\n\n t=time.time()\n\n infer_Tmap_from_one_time_clones_private(adata,initialized_map,Clone_update_iter_N=Clone_update_iter_N,normalization_mode=normalization_mode,noise_threshold=noise_threshold,\n CoSpar_KNN=CoSpar_KNN,use_full_Smatrix=use_full_Smatrix,smooth_array=smooth_array,trunca_threshold=trunca_threshold,\n compute_new=compute_new,use_fixed_clonesize_t1=use_fixed_clonesize_t1,sort_clone=sort_clone)\n\n\n \n logg.info(f\"Finishing computing transport map from CoSpar using inferred clonal data, used time {time.time()-t}\")\n else:\n logg.warn(\"No clonal information available. Skip the joint optimization of clone and scRNAseq data\")\n\n\n return adata\n\ndef infer_Tmap_from_clonal_info_alone(adata,method='naive'):\n \"\"\"\n Compute transition map using only the lineage information\n\n We simply average transitions across all clones, assuming that\n the intra-clone transition is uniform within the same clone. \n\n Parameters\n ----------\n adata: :class:`~anndata.AnnData` object\n It should have been preprocessed by :func:`.select_time_points`\n\n method: `str`, optional (default: 'naive')\n Method used to compute the transition map. Choice: {'naive', \n 'weinreb'}. For the naive method, we simply average transitions \n across all clones, assuming that the intra-clone transition is \n uniform within the same clone. For the 'weinreb' method, we first \n find uni-potent clones, then compute the transition map by simply \n averaging across all clonal transitions as the naive method. \n\n Returns\n -------\n Update `adata` with the attributes adata.uns['naive_transition_map']\n \"\"\"\n\n cell_id_t2=adata.uns['Tmap_cell_id_t2']\n cell_id_t1=adata.uns['Tmap_cell_id_t1']\n clone_annot=adata.obsm['X_clone']\n\n if method=='naive':\n T_map=clone_annot[cell_id_t1]*clone_annot[cell_id_t2].T\n\n else:\n state_annote=np.array(adata.obs['state_info'])\n fate_array=list(set(state_annote))\n potential_vector_clone, fate_entropy_clone=hf.compute_state_potential(clone_annot[cell_id_t2].T,state_annote[cell_id_t2],fate_array,fate_count=True)\n\n sel_unipotent_clone_id=np.array(list(set(np.nonzero(fate_entropy_clone==1)[0])))\n clone_annot_unipotent=clone_annot[:,sel_unipotent_clone_id]\n T_map=clone_annot_unipotent[cell_id_t1]*clone_annot_unipotent[cell_id_t2].T\n logg.info(f\"Used uni-potent clone fraction {len(sel_unipotent_clone_id)/clone_annot.shape[1]}\")\n \n T_map=T_map.astype(int)\n adata.uns['clonal_transition_map']=ssp.csr_matrix(T_map)\n\n\n\n# def infer_weinreb_Tmap(adata):\n# \"\"\"\n# Compute transition map using only the lineage information\n\n# Find uni-potent clones, then compute the transition map by simply \n# averaging across all clonal transitions as in :func:`.infer_naive_Tmap`.\n# The intra-clone transition is uniform within the same clone. \n\n# Parameters\n# ----------\n# adata: :class:`~anndata.AnnData` object\n# It should have been preprocessed by :func:`.select_time_points`\n\n# Returns\n# -------\n# Update `adata` with the attributes adata.uns['weinreb_transition_map']\n# \"\"\"\n\n# logg.info(\"This method works when there are only time points and all datasets\")\n# cell_id_t2=adata.uns['Tmap_cell_id_t2']\n# cell_id_t1=adata.uns['Tmap_cell_id_t1']\n# clone_annot=adata.obsm['X_clone']\n# state_annote=np.array(adata.obs['state_info'])\n\n# fate_array=list(set(state_annote))\n\n# potential_vector_clone, fate_entropy_clone=hf.compute_state_potential(clone_annot[cell_id_t2].T,state_annote[cell_id_t2],fate_array,fate_count=True)\n\n\n# sel_unipotent_clone_id=np.array(list(set(np.nonzero(fate_entropy_clone==1)[0])))\n# clone_annot_unipotent=clone_annot[:,sel_unipotent_clone_id]\n# weinreb_map=clone_annot_unipotent[cell_id_t1]*clone_annot_unipotent[cell_id_t2].T\n# weinreb_map=weinreb_map.astype(int)\n# logg.info(f\"Used clone fraction {len(sel_unipotent_clone_id)/clone_annot.shape[1]}\")\n# adata.uns['weinreb_transition_map']=ssp.csr_matrix(weinreb_map)\n",
"import numpy as np\nimport scipy\nimport os\nimport scipy.stats\nfrom sklearn.decomposition import PCA,TruncatedSVD\nfrom sklearn.neighbors import NearestNeighbors\nfrom scipy.sparse.csgraph import dijkstra\nfrom sklearn.neighbors import kneighbors_graph\nfrom sklearn.metrics import pairwise\nimport scipy.sparse as ssp\nimport scanpy as sc\nimport pandas as pd\nfrom scanpy import read\nimport statsmodels.sandbox.stats.multicomp\nfrom scipy.spatial.distance import pdist\nfrom fastcluster import linkage\nfrom .. import settings\nfrom .. import logging as logg\n\n#import scipy.stats\n\ndef get_dge_SW(ad, mask1, mask2, min_frac_expr=0.05, pseudocount=1):\n \"\"\"\n Perform differential gene expression analysis.\n\n Parameters\n ----------\n ad: :class:`~anndata.AnnData` object\n mask1: `np.array`\n A np.array of `bool` for selecting group_1 cells.\n mask2: `np.array`\n A np.array of `bool` for selecting group_2 cells.\n min_frac_expr: `float`, optional (default: 0.05)\n Minimum expression fraction among selected states for a \n gene to be considered for DGE analysis.\n pseudocount: `int`, optional (default: 1)\n pseudo count for taking the gene expression ratio between the two groups\n\n Returns\n -------\n df: :class:`pandas.DataFrame`\n A pandas dataFrame, with columns: `gene`, `pv`, `mean_1`, `mean_2`, `ratio`\n \"\"\"\n\n \n gene_mask = ((ad.X[mask1,:]>0).sum(0).A.squeeze()/mask1.sum() > min_frac_expr) | ((ad.X[mask2,:]>0).sum(0).A.squeeze()/mask2.sum() > min_frac_expr)\n #print(gene_mask.sum())\n E1 = ad.X[mask1,:][:,gene_mask].toarray()\n E2 = ad.X[mask2,:][:,gene_mask].toarray()\n \n m1 = E1.mean(0) + pseudocount\n m2 = E2.mean(0) + pseudocount\n r = np.log2(m1 / m2)\n \n pv = np.zeros(gene_mask.sum())\n for ii,iG in enumerate(np.nonzero(gene_mask)[0]):\n pv[ii] = scipy.stats.ranksums(E1[:,ii], E2[:,ii])[1]\n pv = statsmodels.sandbox.stats.multicomp.multipletests(pv, alpha=0.05, method='fdr_bh',)[1]\n sort_idx=np.argsort(pv)\n \n df = pd.DataFrame({\n 'gene': ad.var_names.values.astype(str)[gene_mask][sort_idx],\n 'pv': pv[sort_idx],\n 'mean_1': m1[sort_idx] - pseudocount, \n 'mean_2': m2[sort_idx] - pseudocount, \n 'ratio': r[sort_idx]\n })\n \n return df\n\n\n########## USEFUL SPARSE FUNCTIONS\n\ndef sparse_var(E, axis=0):\n \"\"\" calculate variance across the specified axis of a sparse matrix\"\"\"\n\n mean_gene = E.mean(axis=axis).A.squeeze()\n tmp = E.copy()\n tmp.data **= 2\n return tmp.mean(axis=axis).A.squeeze() - mean_gene ** 2\n\ndef mean_center(E, column_means=None):\n \"\"\" mean-center columns of a sparse matrix \"\"\"\n\n if column_means is None:\n column_means = E.mean(axis=0)\n return E - column_means\n\ndef normalize_variance(E, column_stdevs=None):\n \"\"\" variance-normalize columns of a sparse matrix \"\"\"\n\n if column_stdevs is None:\n column_stdevs = np.sqrt(sparse_var(E, axis=0))\n return sparse_rowwise_multiply(E.T, 1 / column_stdevs).T\n\n# this is not working well\ndef sparse_zscore(E, gene_mean=None, gene_stdev=None):\n \"\"\" z-score normalize each column of a sparse matrix \"\"\"\n if gene_mean is None:\n gene_mean = E.mean(0)\n if gene_stdev is None:\n gene_stdev = np.sqrt(sparse_var(E))\n return sparse_rowwise_multiply((E - gene_mean).T, 1/gene_stdev).T\n\n\ndef corr2_coeff(A,B):\n '''\n This method does not work if A and B are constituted of constant row vectors,\n in which case the standard deviation becomes zero. \n '''\n resol=10**(-15)\n # Rowwise mean of input arrays & subtract from input arrays themeselves\n A_mA = A - A.mean(1)[:,None]\n B_mB = B - B.mean(1)[:,None]\n\n # Sum of squares across rows\n ssA = (A_mA**2).sum(1);\n ssB = (B_mB**2).sum(1);\n\n # Finally get corr coeff\n return np.dot(A_mA,B_mB.T)/(np.sqrt(np.dot(ssA[:,None],ssB[None]))+resol)\n\n\ndef sparse_rowwise_multiply(E, a):\n \"\"\" \n multiply each row of sparse matrix by a scalar \n\n Parameters\n ----------\n E: `np.array` or `sp.spmatrix`\n a: `np.array`\n A scalar vector. \n\n Returns\n -------\n Rescaled sparse matrix \n \"\"\"\n\n nrow = E.shape[0]\n if nrow!=a.shape[0]:\n logg.error(\"Dimension mismatch, multiplication failed\")\n return E\n else:\n w = ssp.lil_matrix((nrow, nrow))\n w.setdiag(a)\n return w * E\n\n\ndef sparse_column_multiply(E, a):\n \"\"\" \n multiply each columns of sparse matrix by a scalar \n\n Parameters\n ----------\n E: `np.array` or `sp.spmatrix`\n a: `np.array`\n A scalar vector. \n\n Returns\n -------\n Rescaled sparse matrix \n \"\"\"\n\n ncol = E.shape[1]\n if ncol!=a.shape[0]:\n logg.error(\"Dimension mismatch, multiplication failed\")\n return E\n else:\n w = ssp.lil_matrix((ncol, ncol))\n w.setdiag(a)\n return (ssp.csr_matrix(E)*w)\n\n\ndef matrix_row_or_column_thresholding(input_matrix,threshold=0.1,row_threshold=True):\n \"\"\" \n Row or column-wise thresholding a matrix\n\n Set entries in a given row (column) to be zero, if its value is below threshold*max(row_vector).\n\n Parameters\n ----------\n input_matrix: `np.array`\n threshold: `float`, optional (default: 0.1)\n row_threshold: `bool`, optional (default: True)\n If true, perform row-wise thresholding; otherwise, column-wise.\n\n Returns\n -------\n Rescaled np.array matrix \n \"\"\"\n\n if ssp.issparse(input_matrix): input_matrix=input_matrix.A\n\n output_matrix=input_matrix.copy()\n max_vector=np.max(input_matrix,int(row_threshold))\n for j in range(len(max_vector)):\n #if j%2000==0: logg.hint(j)\n if row_threshold:\n idx=input_matrix[j,:]<threshold*max_vector[j]\n output_matrix[j,idx]=0\n else:\n idx=input_matrix[:,j]<threshold*max_vector[j]\n output_matrix[idx,j]=0\n\n return output_matrix\n\n\ndef get_pca(E, base_ix=[], numpc=50, keep_sparse=False, normalize=True, random_state=0):\n \"\"\"\n Run PCA on the counts matrix E, gene-level normalizing if desired.\n\n By default, it performs z-score transformation for each gene across all cells, i.e., \n a gene normalization, before computing PCA. (There is currently no concensus on doing \n this or not. In scanpy, after count normalization (a per-cell normalization), it assumes \n that the individual gene counts in a cell is log-normally distributed, and performs a \n log-transformation before computing PCA. The z-score transformation is gene-specific, \n while the log-transformation is not.)\n\n Parameters\n ----------\n E: `sp.spmatrix`\n sparse count matrix\n base_ix: `np.array`\n List of column id's to sub-sample the matrix\n numpc: `int`, optional (default: 50)\n Number of principle components to keep\n keep_sparse: `bool`, optional (default: False)\n If true, do not substract the mean, but just divide by \n standard deviation, before running PCA. \n If false, substract the mean and then divide by standard deviation, \n thus performing Zscore transformation, before running PCA\n normalize: `bool`, optional (default: True)\n Perform Zscore transformation if keep_sparse=True, \n Otherwise, only rescale by the standard deviation.\n random_state: `int`, optional (default: 0)\n Random seed for PCA\n\n Returns\n ------- \n PCA coordinates\n \"\"\"\n\n # If keep_sparse is True, gene-level normalization maintains sparsity\n # (no centering) and TruncatedSVD is used instead of normal PCA.\n\n if len(base_ix) == 0:\n base_ix = np.arange(E.shape[0])\n\n if keep_sparse:\n if normalize: # normalize variance\n zstd = np.sqrt(sparse_var(E[base_ix,:]))\n Z = sparse_rowwise_multiply(E.T, 1 / zstd).T\n else:\n Z = E\n pca = TruncatedSVD(n_components=numpc, random_state=random_state)\n\n else:\n if normalize:\n zmean = E[base_ix,:].mean(0)\n zstd = np.sqrt(sparse_var(E[base_ix,:]))\n Z = sparse_rowwise_multiply((E - zmean).T, 1/zstd).T\n else:\n Z = E\n pca = PCA(n_components=numpc, random_state=random_state)\n\n pca.fit(Z[base_ix,:])\n return pca.transform(Z)\n\n\n\n########## GENE FILTERING\n\ndef runningquantile(x, y, p, nBins):\n \"\"\" calculate the quantile of y in bins of x \"\"\"\n\n ind = np.argsort(x)\n x = x[ind]\n y = y[ind]\n\n dx = (x[-1] - x[0]) / nBins\n xOut = np.linspace(x[0]+dx/2, x[-1]-dx/2, nBins)\n\n yOut = np.zeros(xOut.shape)\n\n for i in range(len(xOut)):\n ind = np.nonzero((x >= xOut[i]-dx/2) & (x < xOut[i]+dx/2))[0]\n if len(ind) > 0:\n yOut[i] = np.percentile(y[ind], p)\n else:\n if i > 0:\n yOut[i] = yOut[i-1]\n else:\n yOut[i] = np.nan\n\n return xOut, yOut\n\n\ndef get_vscores(E, min_mean=0, nBins=50, fit_percentile=0.1, error_wt=1):\n \"\"\"\n Calculate v-score (above-Poisson noise statistic) for genes in the input sparse counts matrix\n Return v-scores and other stats\n \"\"\"\n\n ncell = E.shape[0]\n\n mu_gene = E.mean(axis=0).A.squeeze()\n gene_ix = np.nonzero(mu_gene > min_mean)[0]\n mu_gene = mu_gene[gene_ix]\n\n tmp = E[:,gene_ix]\n tmp.data **= 2\n var_gene = tmp.mean(axis=0).A.squeeze() - mu_gene ** 2\n del tmp\n FF_gene = var_gene / mu_gene\n\n data_x = np.log(mu_gene)\n data_y = np.log(FF_gene / mu_gene)\n\n x, y = runningquantile(data_x, data_y, fit_percentile, nBins)\n x = x[~np.isnan(y)]\n y = y[~np.isnan(y)]\n\n gLog = lambda input: np.log(input[1] * np.exp(-input[0]) + input[2])\n h,b = np.histogram(np.log(FF_gene[mu_gene>0]), bins=200)\n b = b[:-1] + np.diff(b)/2\n max_ix = np.argmax(h)\n c = np.max((np.exp(b[max_ix]), 1))\n errFun = lambda b2: np.sum(abs(gLog([x,c,b2])-y) ** error_wt)\n b0 = 0.1\n b = scipy.optimize.fmin(func = errFun, x0=[b0], disp=False)\n a = c / (1+b) - 1\n\n\n v_scores = FF_gene / ((1+a)*(1+b) + b * mu_gene);\n CV_eff = np.sqrt((1+a)*(1+b) - 1);\n CV_input = np.sqrt(b);\n\n return v_scores, CV_eff, CV_input, gene_ix, mu_gene, FF_gene, a, b\n\ndef filter_genes(E, base_ix = [], min_vscore_pctl = 85, min_counts = 3, min_cells = 3, show_vscore_plot = False, sample_name = ''):\n \"\"\" \n Filter genes by expression level and variability\n\n Parameters\n ----------\n E: `sp.spmatrix`\n sparse count matrix\n base_ix: `np.array`\n List of column id's to sub-sample the matrix\n min_counts: int, optional (default: 3) \n Minimum number of UMIs per cell to be considered for selecting highly variable genes. \n min_cells: int, optional (default: 3)\n Minimum number of cells per gene to be considered for selecting highly variable genes. \n min_vscore_pctl: int, optional (default: 85)\n Genes wht a variability percentile higher than this threshold are marked as \n highly variable genes for dimension reduction. Range: [0,100]\n show_vscore_plot: `bool`, optional (default: False)\n If true, show the vscore plot for all genes\n sample_name: `str`, optional (default: '')\n Name of the plot title. \n\n Returns\n -------\n List of filtered gene indices (id's)\n \"\"\"\n\n if len(base_ix) == 0:\n base_ix = np.arange(E.shape[0])\n\n Vscores, CV_eff, CV_input, gene_ix, mu_gene, FF_gene, a, b = get_vscores(E[base_ix, :])\n ix2 = Vscores>0\n Vscores = Vscores[ix2]\n gene_ix = gene_ix[ix2]\n mu_gene = mu_gene[ix2]\n FF_gene = FF_gene[ix2]\n min_vscore = np.percentile(Vscores, min_vscore_pctl)\n ix = (((E[:,gene_ix] >= min_counts).sum(0).A.squeeze() >= min_cells) & (Vscores >= min_vscore))\n \n if show_vscore_plot:\n import matplotlib.pyplot as plt\n x_min = 0.5*np.min(mu_gene)\n x_max = 2*np.max(mu_gene)\n xTh = x_min * np.exp(np.log(x_max/x_min)*np.linspace(0,1,100))\n yTh = (1 + a)*(1+b) + b * xTh\n plt.figure(figsize=(4, 3));\n plt.scatter(np.log10(mu_gene), np.log10(FF_gene), c = [[.8,.8,.8]], alpha = 0.3, s = 3);\n plt.scatter(np.log10(mu_gene)[ix], np.log10(FF_gene)[ix], c = [[0,0,0]], alpha = 0.3, s= 3);\n plt.plot(np.log10(xTh),np.log10(yTh));\n plt.title(sample_name)\n plt.xlabel('log10(mean)');\n plt.ylabel('log10(Fano factor)');\n plt.show()\n\n return gene_ix[ix]\n\n# We found that this does not work\ndef remove_corr_genes(E, gene_list, exclude_corr_genes_list, test_gene_idx, min_corr = 0.1):\n \"\"\" \n Remove signature-correlated genes from a list of test genes \n \n Parameters\n ----------\n E: ssp.csc_matrix, shape (n_cells, n_genes)\n full counts matrix\n gene_list: numpy array, shape (n_genes,)\n full gene list\n exclude_corr_genes_list: list of list(s)\n Each sublist is used to build a signature. Test genes correlated\n with this signature will be removed\n test_gene_idx: 1-D numpy array\n indices of genes to test for correlation with the \n gene signatures from exclude_corr_genes_list\n min_corr: float (default=0.1)\n Test genes with a Pearson correlation of min_corr or higher \n with any of the gene sets from exclude_corr_genes_list will\n be excluded\n\n Returns\n -------\n numpy array of gene indices (subset of test_gene_idx) that are not correlated with any of the gene signatures\n \"\"\"\n\n seed_ix_list = []\n for l in exclude_corr_genes_list:\n seed_ix_list.append(np.array([i for i in range(len(gene_list)) if gene_list[i] in l], dtype=int))\n\n exclude_ix = []\n for iSet in range(len(seed_ix_list)):\n seed_ix = seed_ix_list[iSet][E[:,seed_ix_list[iSet]].sum(axis=0).A.squeeze() > 0]\n if type(seed_ix) is int:\n seed_ix = np.array([seed_ix], dtype=int)\n elif type(seed_ix[0]) is not int:\n seed_ix = seed_ix[0]\n indat = E[:, seed_ix]\n tmp = sparse_zscore(indat)\n tmp = tmp.sum(1).A.squeeze()\n\n c = np.zeros(len(test_gene_idx))\n for iG in range(len(c)):\n c[iG],_ = scipy.stats.pearsonr(tmp, E[:,test_gene_idx[iG]].A.squeeze())\n\n exclude_ix.extend([test_gene_idx[i] for i in range(len(test_gene_idx)) if (c[i]) >= min_corr])\n exclude_ix = np.array(exclude_ix)\n\n return np.array([g for g in test_gene_idx if g not in exclude_ix], dtype=int)\n\n\n\n\n#################################################################\n\n# check if a given id is in the list L2 (day 24 or 46), or L4 (day26)\n# a conversion algorithm \ndef converting_id_from_fullSpace_to_subSpace(query_id_array_fullSpace,subSpace_id_array_inFull):\n \"\"\"\n Convert indices in the full space to those in the subspace.\n\n Parameters\n ----------\n query_id_array_fullSpace: `np.array` or `list`\n Indices in the full space\n subSpace_id_array_inFull: `np.array` or `list`\n Indices of a targeted sub population in the full space\n \n Returns\n -------\n np.array(query_id_inSub): `np.array`\n A converted np.array of indices in the subspace\n\n query_success: `np.array`\n A bool array of conversion success\n\n \"\"\"\n\n id_sub=np.array(subSpace_id_array_inFull);\n query_id_inSub=[]\n query_success=np.zeros(len(query_id_array_fullSpace),dtype=bool)\n # check one by one\n for j,id_full in enumerate(query_id_array_fullSpace):\n temp=np.nonzero(id_sub==id_full)[0]\n if len(temp)>0:\n query_success[j]=True\n query_id_inSub.append(temp[0])\n \n return np.array(query_id_inSub), query_success\n \n\n\ndef converting_id_from_subSpace_to_fullSpace(query_id_array_subSpace,subSpace_id_array_inFull):\n \"\"\"\n Convert indices in the subspace to those in the full space.\n\n Parameters\n ----------\n query_id_array_subSpace: `np.array` or `list`\n Indices in the sub space\n subSpace_id_array_inFull: `np.array` or `list`\n Indices of a targeted sub population in the full space\n \n Returns\n -------\n A converted np.array of indices in the sfull space\n \"\"\"\n\n return np.array(subSpace_id_array_inFull)[query_id_array_subSpace]\n\n\n\n\ndef compute_state_potential(transition_map,state_annote,fate_array,\n fate_count=False,map_backwards=True):\n \"\"\"\n Compute state probability towards/from given clusters\n\n Before any calculation, we row-normalize the transition map. \n If map_backwards=True, compute the fate map towards given \n clusters. Otherwise, compute the ancestor map, the probabilities \n of a state to originate from given clusters. \n\n Parameters\n ----------\n transition_map: `sp.spmatrix` (also accept `np.array`)\n Transition map of the shape: (n_t1_cells, n_t2_cells). \n state_annote: `np.array`\n Annotation for each cell state.\n fate_array: `np.array` or `list`\n List of targeted clusters, consistent with state_annote.\n fate_count: `bool`, optional (default: False)\n Relevant for compute the fate_entropy. If true, just count \n the number of possible (Prob>0) fate outcomes for each state;\n otherwise, compute the shannon entropy of fate outcome for each state\n map_backwards: `bool`, optional (default: True)\n If `map_backwards=True`, compute for initial cell states (rows of Tmap, at t1);\n else, for later cell states (columns of Tmap, at t2)\n \n Returns\n -------\n fate_map: `np.array`, shape (n_cells, n_fates)\n A matrix of fate potential for each state\n fate_entropy: `np.array`, shape (n_fates,)\n A vector of fate entropy for each state\n \"\"\"\n \n if not ssp.issparse(transition_map): transition_map=ssp.csr_matrix(transition_map).copy()\n resol=10**(-10)\n transition_map=sparse_rowwise_multiply(transition_map,1/(resol+np.sum(transition_map,1).A.flatten()))\n fate_N=len(fate_array)\n N1,N2=transition_map.shape\n\n if map_backwards:\n idx_array=np.zeros((N2,fate_N),dtype=bool)\n for k in range(fate_N):\n idx_array[:,k]=(state_annote==fate_array[k])\n\n fate_map=np.zeros((N1,fate_N))\n fate_entropy=np.zeros(N1)\n\n for k in range(fate_N):\n fate_map[:,k]=np.sum(transition_map[:,idx_array[:,k]],1).A.flatten()\n\n for j in range(N1):\n ### compute the \"fate-entropy\" for each state\n if fate_count:\n p0=fate_map[j,:]\n fate_entropy[j]=np.sum(p0>0)\n else:\n p0=fate_map[j,:]\n p0=p0/(resol+np.sum(p0))+resol\n for k in range(fate_N):\n fate_entropy[j]=fate_entropy[j]-p0[k]*np.log(p0[k])\n\n ### forward map\n else:\n idx_array=np.zeros((N1,fate_N),dtype=bool)\n for k in range(fate_N):\n idx_array[:,k]=(state_annote==fate_array[k])\n\n fate_map=np.zeros((N2,fate_N))\n fate_entropy=np.zeros(N2)\n\n for k in range(fate_N):\n fate_map[:,k]=np.sum(transition_map[idx_array[:,k],:],0).A.flatten()\n\n\n for j in range(N1):\n \n ### compute the \"fate-entropy\" for each state\n if fate_count:\n p0=fate_map[j,:]\n fate_entropy[j]=np.sum(p0>0)\n else:\n p0=fate_map[j,:]\n p0=p0/(resol+np.sum(p0))+resol\n for k in range(fate_N):\n fate_entropy[j]=fate_entropy[j]-p0[k]*np.log(p0[k])\n\n return fate_map, fate_entropy\n\n\n\ndef compute_fate_probability_map(adata,fate_array=[],used_map_name='transition_map',map_backwards=True):\n \"\"\"\n Compute fate map from the adata object\n\n Parameters\n ----------\n adata: :class:`~anndata.AnnData` object\n Assume to contain transition maps at adata.uns.\n fate_array: `list`, optional (default: all)\n List of targeted clusters, consistent with adata.obs['state_info'].\n If set to be [], use all fate clusters in adata.obs['state_info'].\n used_map_name: `str`\n The transition map to be used for plotting: {'transition_map',\n 'intraclone_transition_map','weinreb_transition_map','naive_transition_map',\n 'OT_transition_map','HighVar_transition_map'}. The actual available\n map depends on adata itself, which can be accessed at adata.uns['available_map']\n map_backwards: `bool`, optional (default: True)\n If `map_backwards=True`, compute for initial cell states (rows of Tmap, at t1);\n else, compute for later cell states (columns of Tmap, at t2)\n\n Returns\n -------\n Update `fate_array`, `fate_map`, `fate_entropy` as a dictionary in adata.uns['fate_map']. \n \"\"\"\n \n #transition_map=adata.uns['transition_map']\n #demultiplexed_map=adata.uns['demultiplexed_map']\n state_annote_0=adata.obs['state_info']\n if map_backwards:\n cell_id_t1=adata.uns['Tmap_cell_id_t1']\n cell_id_t2=adata.uns['Tmap_cell_id_t2']\n\n else:\n cell_id_t2=adata.uns['Tmap_cell_id_t1']\n cell_id_t1=adata.uns['Tmap_cell_id_t2']\n\n x_emb=adata.obsm['X_emb'][:,0]\n y_emb=adata.obsm['X_emb'][:,1]\n data_des=adata.uns['data_des'][-1]\n \n if len(fate_array)==0: fate_array=list(set(state_annote_0))\n \n\n state_annote_BW=state_annote_0[cell_id_t2]\n \n if used_map_name in adata.uns.keys():\n used_map=adata.uns[used_map_name]\n\n potential_vector, fate_entropy=compute_state_potential(used_map,state_annote_BW,fate_array,fate_count=True,map_backwards=map_backwards)\n\n adata.uns['fate_map']={'fate_array':fate_array,'fate_map':potential_vector,'fate_entropy':fate_entropy}\n\n else:\n logg.error(f\"used_map_name should be among adata.uns.keys(), with _transition_map as suffix\")\n\n \ndef compute_fate_map_and_intrinsic_bias(adata,selected_fates=[],used_map_name='transition_map',map_backwards=True):\n \"\"\"\n Compute fate map and the relative bias compared to expectation.\n \n `selected_fates` could contain a nested list of clusters. If so, we combine each sub list \n into a mega-fate cluster and combine the fate map correspondingly. \n\n The relative bias is obtained by comparing the fate_prob with the \n expected_prob from targeted cluster size. It ranges from [0,1], \n with 0.5 being the point that the fate_prob agrees with expected_prob. \n 1 is extremely biased. \n\n Parameters\n ----------\n adata: :class:`~anndata.AnnData` object\n Assume to contain transition maps at adata.uns.\n selected_fates: `list`, optional (default: all)\n List of targeted clusters, consistent with adata.obs['state_info'].\n If set to be [], use all fate clusters in adata.obs['state_info'].\n used_map_name: `str`\n The transition map to be used for plotting: {'transition_map',\n 'intraclone_transition_map','weinreb_transition_map','naive_transition_map',\n 'OT_transition_map','HighVar_transition_map'}. The actual available\n map depends on adata itself, which can be accessed at adata.uns['available_map']\n map_backwards: `bool`, optional (default: True)\n If `map_backwards=True`, compute for initial cell states (rows of Tmap, at t1);\n else, compute for later cell states (columns of Tmap, at t2)\n\n Returns\n -------\n Store `fate_array`, `fate_map`, `fate_entropy` in adata.uns['fate_map']. \n\n fate_map: `np.array`, shape (n_cell, n_fate)\n n_fate is the number of mega cluster, equals len(selected_fates).\n mega_cluster_list: `list`, shape (n_fate)\n The list of names for the mega cluster. This is relevant when \n `selected_fates` is a list of list.\n relative_bias: `np.array`, shape (n_cell, n_fate)\n expected_prob: `np.array`, shape (n_fate,)\n valid_fate_list: `list`, shape (n_fate)\n It is basically the same as selected_fates, could contain a nested list\n of fate clusters. It screens for valid fates, though. \n \"\"\"\n\n state_annote=adata.obs['state_info']\n valid_state_annot=list(set(np.array(state_annote)))\n if map_backwards:\n cell_id_t2=adata.uns['Tmap_cell_id_t2']\n else:\n cell_id_t2=adata.uns['Tmap_cell_id_t1']\n\n if len(selected_fates)==0: selected_fates=list(set(state_annote))\n\n fate_array_flat=[] # a flatten list of cluster names\n valid_fate_list=[] # a list of cluster lists, each cluster list is a macro cluster\n mega_cluster_list=[] # a list of string description for the macro cluster\n for xx in selected_fates:\n if type(xx) is list:\n valid_fate_list.append(xx)\n des_temp=''\n for zz in xx:\n if zz in valid_state_annot:\n fate_array_flat.append(zz)\n des_temp=des_temp+str(zz)+'_'\n else:\n logg.error(f'{zz} is not a valid cluster name. Please select from: {valid_state_annot}')\n mega_cluster_list.append(des_temp)\n else:\n if xx in valid_state_annot:\n valid_fate_list.append([xx])\n\n fate_array_flat.append(xx)\n mega_cluster_list.append(str(xx))\n else:\n logg.error(f'{xx} is not a valid cluster name. Please select from: {valid_state_annot}')\n mega_cluster_list.append('')\n\n compute_fate_probability_map(adata,fate_array=fate_array_flat,used_map_name=used_map_name,map_backwards=map_backwards)\n fate_map_0=adata.uns['fate_map']['fate_map']\n\n N_macro=len(valid_fate_list)\n fate_map=np.zeros((fate_map_0.shape[0],N_macro))\n relative_bias=np.zeros((fate_map_0.shape[0],N_macro))\n expected_prob=np.zeros(N_macro)\n for jj in range(N_macro):\n idx=np.in1d(fate_array_flat,valid_fate_list[jj])\n fate_map[:,jj]=fate_map_0[:,idx].sum(1)\n\n for yy in valid_fate_list[jj]:\n expected_prob[jj]=expected_prob[jj]+np.sum(state_annote[cell_id_t2]==yy)/len(cell_id_t2)\n\n # transformation\n temp_idx=fate_map[:,jj]<expected_prob[jj]\n temp_diff=fate_map[:,jj]-expected_prob[jj]\n relative_bias[temp_idx,jj]=temp_diff[temp_idx]/expected_prob[jj]\n relative_bias[~temp_idx,jj]=temp_diff[~temp_idx]/(1-expected_prob[jj])\n\n relative_bias[:,jj]=(relative_bias[:,jj]+1)/2 # rescale to the range [0,1]\n\n return fate_map,mega_cluster_list,relative_bias,expected_prob,valid_fate_list\n \n\n \n\ndef mapout_trajectories(transition_map,state_prob_t2,threshold=0.1,cell_id_t1=[],cell_id_t2=[]):\n \"\"\"\n map out the ancestor probability for a given later state distribution.\n\n We assume that transition_map is a normalized probablistic map from \n t1-state to t2-states. Given a distribution of states at t2, we find \n and return the initial state distribution. \n\n Although it is designed to map trajectories backwards, one can simply \n tanspose the Tmap, and swap everything related to t1 and t2, to map forward. \n\n Parameters\n ----------\n transition_map: `np.array` (also accept `sp.spsparse`), shape (n_t1, n_t2)\n A transition matrix that is properly normalized. \n state_prob_t2: `np.array`, shape (n_t2,)\n A continuous-valued vector that defines the probability of the final states.\n threshold: `float`, optional (default: 0.1), range ([0,1])\n We set to zero entries < threshold * max(state_prob_t1).\n cell_id_t1: `np.array` (also accept `list`)\n The id array for cell states at t1 in the full space\n cell_id_t2: `np.array` (also accept `list`)\n The id array for cell states at t2 in the full space\n\n Returns\n -------\n state_prob_t1_truc: `np.array`, shape (n_t1,)\n The fate probability of each t1-cell state to enter the soft \n t2-cluster as defined by state_prob_t2.\n \"\"\"\n\n ########## We assume that the transition_map has been properly normalized. \n # if not ssp.issparse(transition_map): transition_map=ssp.csr_matrix(transition_map).copy()\n # resol=10**(-10)\n # transition_map=sparse_rowwise_multiply(transition_map,1/(resol+np.sum(transition_map,1).A.flatten()))\n\n if ssp.issparse(transition_map): transition_map=transition_map.A\n\n N1,N2=transition_map.shape\n if len(cell_id_t1)==0 and N1==N2: # cell_id_t1 and cell_id_t2 live in the same state space\n state_prob_t1=transition_map.dot(state_prob_t2)\n state_prob_t1_idx=state_prob_t1>threshold*np.max(state_prob_t1)\n state_prob_t1_id=np.nonzero(state_prob_t1_idx)[0]\n\n state_prob_t1_truc=np.zeros(len(state_prob_t1))\n state_prob_t1_truc[state_prob_t1_id]=state_prob_t1[state_prob_t1_id]\n else:\n # both cell_id_t1 and cell_id_t2 are id's in the full space\n # selected_cell_id is also in the full space\n cell_id_t1=np.array(cell_id_t1)\n cell_id_t2=np.array(cell_id_t2)\n state_prob_t2_subspace=state_prob_t2[cell_id_t2]\n\n state_prob_t1=transition_map.dot(state_prob_t2_subspace)\n state_prob_t1_idx=state_prob_t1>threshold*np.max(state_prob_t1)\n state_prob_t1_id=np.nonzero(state_prob_t1_idx)[0] # id in t1 subspace\n #state_prob_t1_truc=state_prob_t1[state_prob_t1_id]\n state_prob_t1_truc=np.zeros(len(state_prob_t1))\n state_prob_t1_truc[state_prob_t1_id]=state_prob_t1[state_prob_t1_id]\n\n return state_prob_t1_truc\n\n\n\n# v1, the new methods, more options.\ndef compute_shortest_path_distance(adata,num_neighbors_target=5,mode='distances',limit=np.inf, method='umap'):\n \"\"\"\n Compute shortest path distance from raw data.\n\n The distance matrix has two mode: 'connectivity' or 'distance'.\n We found that the 'connectivity' version is sensitive to local cell \n density heterogeneity, and the 'distance' version is more robust.\n This discrepancy might be due to that the KNN graph construction does not\n direclty take into account of local density heterogeneity. \n\n The default is the UMAP method, which takes into account of local \n density heterogeneity into account when constructing the KNN graph.\n\n Parameters\n ----------\n adata: :class:`~anndata.AnnaData` object\n num_neighbors_target: `int`, optional (default: 5)\n Used to construct the KNN graph.\n mode: `str`, optional (default: 'distance')\n Options: {'distance','connectivity')\n limit: `float`, optional (default: np.inf)\n If the distance is about this, stop computation, and set \n the distance beyong this limist by `limit`. This can speed up computation.\n method: `str`, optional (default: 'umap')\n The method to construct the KNN graph. Options: {'umap','gauss','others'}. \n The frist two methods are based on sc.pp.neighbors, while the last is from \n kneighbors_graph.\n\n Returns\n -------\n The normaized distance matrix is returned.\n \"\"\"\n \n if mode!='connectivities':\n mode='distances'\n\n logg.hint(f\"Chosen mode is {mode}\")\n if method=='umap':\n sc.pp.neighbors(adata, n_neighbors=num_neighbors_target,method='umap')\n adj_matrix=adata.obsp[mode].A.copy()\n\n elif method=='gauss':\n sc.pp.neighbors(adata, n_neighbors=num_neighbors_target,method='gauss')\n adj_matrix=adata.obsp[mode].A.copy() \n\n else:\n if mode=='distances': \n mode='distance'\n else:\n mode='connectivity'\n data_matrix=adata.obsm['X_pca']\n adj_matrix = kneighbors_graph(data_matrix, num_neighbors_target, mode=mode, include_self=True)\n\n\n ShortPath_dis = dijkstra(csgraph = ssp.csr_matrix(adj_matrix), directed = False,return_predecessors = False)\n ShortPath_dis_max = np.nanmax(ShortPath_dis[ShortPath_dis != np.inf])\n ShortPath_dis[ShortPath_dis > ShortPath_dis_max] = ShortPath_dis_max #set threshold for shortest paths\n\n # Set normalized cost matrices based on shortest paths matrices at target and source spaces\n return ShortPath_dis / ShortPath_dis.max()\n\n\n# v0, the new methods, more options.\ndef compute_shortest_path_distance_from_raw_matrix(data_matrix,num_neighbors_target=5,mode='distance',limit=np.inf):\n \"\"\"\n Compute shortest path distance from raw data.\n\n The distance matrix has two mode: 'connectivity' or 'distance'.\n We found that the 'connectivity' version is sensitive to local cell \n density heterogeneity, and the 'distance' version is more robust.\n This discrepancy might be due to that the KNN graph construction does not\n direclty take into account of local density heterogeneity. \n\n Parameters\n ----------\n data_matrix: `np.array`\n num_neighbors_target: `int`, optional (default: 5)\n Used to construct the KNN graph.\n mode: `str`, optional (default: 'distance')\n Options: {'distance','connectivity')\n limit: `float`, optional (default: np.inf)\n If the distance is about this, stop computation, and set \n the distance beyong this limist by `limit`. This can speed up computation.\n\n Returns\n -------\n The normaized distance matrix is returned.\n \"\"\"\n\n adj_matrix = kneighbors_graph(data_matrix, num_neighbors_target, mode=mode, include_self=True)\n ShortPath_dis = dijkstra(csgraph = ssp.csr_matrix(adj_matrix), directed = False,return_predecessors = False,limit=limit)\n ShortPath_dis_max = np.nanmax(ShortPath_dis[ShortPath_dis != np.inf])\n ShortPath_dis[ShortPath_dis > ShortPath_dis_max] = ShortPath_dis_max #set threshold for shortest paths\n\n # Set normalized cost matrices based on shortest paths matrices at target and source spaces\n return ShortPath_dis / ShortPath_dis.max()\n\n\ndef add_neighboring_cells_to_a_map(initial_idx,adata,neighbor_N=5):\n \"\"\"\n Add neighboring cells to an initially selected population\n\n Parameters\n ----------\n initial_idx: `np.array`, shape (n_cell,)\n A boolean array for state selection. \n adata: :class:`~anndata.AnnData` object, shape (n_cell, n_genes)\n neighbor_N: `int`, optional (default: 5)\n Number of neighbors for KNN graph construction.\n\n Returns\n -------\n post_idx: `np.array`, shape (n_cell,)\n A boolean array of selected cell states post expansion. \n \"\"\"\n\n initial_idx=initial_idx>0\n #print(f\"Initial: {np.sum(initial_idx)}\")\n# if (np.sum(initial_idx)<size_thresh) & (np.sum(initial_idx)>0):\n# #n0=np.round(size_thresh/np.sum(initial_idx))\n# #sc.pp.neighbors(adata, n_neighbors=int(n0)) #,method='gauss')\n# output_idx=adata.uns['neighbors']['connectivities'][initial_idx].sum(0).A.flatten()>0\n# initial_idx=initial_idx | output_idx\n\n sc.pp.neighbors(adata, n_neighbors=neighbor_N) #,method='gauss')\n output_idx=adata.obsp['connectivities'][initial_idx].sum(0).A.flatten()>0\n post_idx=initial_idx | output_idx\n #print(f\"Final: {np.sum(post_idx)}\")\n\n return post_idx\n\n\ndef get_hierch_order(hm, dist_metric='euclidean', linkage_method='ward'):\n \"\"\"\n This is used to order the barcode in generating the barcode heatmap. \n \"\"\"\n np.random.seed(0)\n D = pdist(hm, dist_metric)\n Z = linkage(D, linkage_method)\n n = len(Z) + 1\n cache = dict()\n for k in range(len(Z)):\n c1, c2 = int(Z[k][0]), int(Z[k][1])\n c1 = [c1] if c1 < n else cache.pop(c1)\n c2 = [c2] if c2 < n else cache.pop(c2)\n cache[n+k] = c1 + c2\n o = np.array(cache[2*len(Z)])\n return o\n\n\ndef get_normalized_covariance(data,method='Weinreb'):\n \"\"\"\n Compute the normalized correlation of the data matrix.\n\n This is used to compute the fate coupling. \n Two methods are provided, `Weinreb` method and 'SW'.\n The `Weinreb` method perform normalization against the mean observation\n for each fate; while the `SW` method normalizes against the square root of \n the self coupling, brining the self coupling to 1 after normalization.\n\n Parameters\n ----------\n data: `np.array`, shape (n_obs, n_fates)\n A observation matrix for the fate distribution. The observable\n could be the number of barcodes in each fate, or the probability\n of a cell to enter a fate. \n method: `str`, optional (default: 'Weinreb')\n Method for computing the normalized covariance. Choice: {'Weinreb','SW'}\n\n Returns\n -------\n Normalized covariance matrix.\n \"\"\"\n\n if method=='Weinreb':\n cc = np.cov(data.T)\n mm = np.mean(data,axis=0) + .0001\n X,Y = np.meshgrid(mm,mm)\n cc = cc / X / Y\n return cc#/np.max(cc)\n else:\n resol=10**(-10)\n \n # No normalization performs better. Not all cell states contribute equally to lineage coupling\n # Some cell states are in the progenitor regime, most ambiguous. They have a larger probability to remain in the progenitor regime, rather than differentiate.\n # Normalization would force these cells to make early choices, which could add noise to the result. \n # data=core.sparse_rowwise_multiply(data,1/(resol+np.sum(data,1)))\n \n X=data.T.dot(data)\n diag_temp=np.sqrt(np.diag(X))\n for j in range(len(diag_temp)):\n for k in range(len(diag_temp)):\n X[j,k]=X[j,k]/(diag_temp[j]*diag_temp[k])\n return X#/np.max(X)\n \n\n\ndef above_the_line(x_array,x1,x2):\n \"\"\"\n Return states above a specified line defined by (x1, x2).\n\n We assume that a state has only two coordiates. \n\n Parameters\n ----------\n x_array: `np.array`\n A 2-d matrix. Usually, an embedding for data points. \n x1: `np.array`\n A list or array of two entries. \n x2: `np.array`\n A list or array of two entries. \n\n Returns\n -------\n A boolean array.\n\n \"\"\"\n return (x_array[:,1]-x1[1])>((x2[1]-x1[1])/(x2[0]-x1[0]))*(x_array[:,0]-x1[0])\n\n\ndef save_map(adata):\n \"\"\"\n Save the adata and print file name prefix. \n\n The file name prefix `data_des` will be printed, and \n the saved file can be accessed again using this prefix.\n \"\"\"\n\n data_des=adata.uns['data_des'][-1]\n #data_path=adata.uns['data_path'][0]\n data_path=settings.data_path\n\n\n # need to remove these, otherwise, it does not work\n for xx in ['fate_trajectory', 'multiTime_cell_id_t1', 'multiTime_cell_id_t2', 'fate_map']:\n if xx in adata.uns.keys():\n adata.uns.pop(xx)\n\n file_name=f'{data_path}/{data_des}_adata_with_transition_map.h5ad'\n adata.write_h5ad(file_name, compression='gzip')\n print(f\"Saved file: data_des='{data_des}'\")\n\n\n\ndef check_adata_structure(adata):\n \"\"\"\n Check whether the adata has the right structure. \n \"\"\"\n\n flag=True\n if not ('X_pca' in adata.obsm.keys()):\n logg.error('*X_pca* missing from adata.obsm')\n flag=False\n\n if not ('X_emb' in adata.obsm.keys()):\n logg.error('*X_emb* missing from adata.obsm')\n flag=False\n\n if not ('X_clone' in adata.obsm.keys()):\n logg.error('*X_clone* missing from adata.obsm')\n flag=False\n\n if not ('time_info' in adata.obs.keys()):\n logg.error('*time_info* missing from adata.obs')\n flag=False\n\n if not ('state_info' in adata.obs.keys()):\n logg.error('*state_info* missing from adata.obs')\n flag=False\n\n if flag:\n print(\"The adata structure looks fine!\")\n\ndef save_preprocessed_adata(adata,data_des=''):\n \"\"\"\n Save preprocessed adata.\n\n It will remove un-needed entries, and use the default\n key to save the results if a new data_des is not provided. \n \"\"\"\n\n if len(data_des)==0:\n data_des=adata.uns['data_des'][-1]\n data_path=settings.data_path\n\n check_list=list(adata.uns.keys())\n for xx in check_list:\n if xx not in ['data_des','clonal_time_points']:\n adata.uns.pop(xx)\n\n check_list=list(adata.obsm.keys())\n for xx in check_list:\n if xx not in ['X_clone', 'X_emb', 'X_pca']:\n adata.obsm.pop(xx)\n\n check_list=list(adata.obs.keys())\n for xx in check_list:\n if xx not in ['state_info', 'time_info']:\n adata.obs.pop(xx)\n\n adata.write_h5ad(f'{data_path}/{data_des}_adata_preprocessed.h5ad', compression='gzip')\n print(f\"Saved file: data_des='{data_des}'\")\n\ndef load_saved_adata_with_key(data_des):\n \"\"\"\n Load pre-saved adata based on the prefix 'data_des'\n \"\"\"\n\n data_path=settings.data_path\n #print(f\"Load data: data_des='{data_des}'\")\n file_name=f'{data_path}/{data_des}_adata_with_transition_map.h5ad'\n if os.path.exists(file_name):\n adata=sc.read(file_name)\n return adata\n else:\n logg.error(f\"The file does not existed yet\")\n\ndef check_available_map(adata):\n \"\"\"\n Check available transition map. \n\n Update adata.uns['available_map'].\n \"\"\"\n\n available_map=[]\n for xx in adata.uns.keys():\n if 'transition_map' in xx:\n available_map.append(xx)\n adata.uns['available_map']=available_map\n\ndef switch_adata_representation(adata,to_new=True):\n if to_new:\n adata.obsm['X_clone']=adata.obsm['cell_by_clone_matrix']\n adata.obs['state_info']=adata.obs['state_annotation']\n #adata.uns['data_des']=['paper_OneTimeClone_t*pos_17*pos_21*D27']\n adata.obsm.pop('cell_by_clone_matrix')\n adata.obs.pop('state_annotation')\n else:\n adata.obsm['cell_by_clone_matrix']=adata.obsm['X_clone']\n adata.obs['state_annotation']=adata.obs['state_info']\n #adata.uns['data_des']=['paper_OneTimeClone_t*pos_17*pos_21*D27']\n adata.obsm.pop('X_clone')\n adata.obs.pop('state_info')\n\n\ndef check_available_clonal_info(adata):\n\n X_clone=adata.obsm['X_clone']\n time_info=adata.obs['time_info']\n\n # record time points with clonal information\n if ssp.issparse(X_clone):\n clone_N_per_cell=X_clone.sum(1).A.flatten()\n else:\n clone_N_per_cell=X_clone.sum(1)\n\n clonal_time_points=[]\n for xx in list(set(time_info)):\n idx=np.array(time_info)==xx\n if np.sum(clone_N_per_cell[idx])>0:\n clonal_time_points.append(xx)\n adata.uns['clonal_time_points']=clonal_time_points\n\n\ndef check_available_choices(adata):\n \"\"\"\n Check available parameter choices.\n\n Also update adata.uns['available_map'] and adata.uns['clonal_time_points'].\n \"\"\"\n\n check_available_map(adata)\n available_map=adata.uns['available_map']\n\n check_available_clonal_info(adata)\n clonal_time_points=adata.uns['clonal_time_points']\n\n print(\"Available transition maps:\",available_map)\n print(\"Availabel clusters:\", list(set(adata.obs['state_info'])))\n print(\"Availabel time points:\", list(set(adata.obs['time_info'])))\n print(\"Clonal time points:\",clonal_time_points)\n\ndef compute_pca(m1, m2, n_components):\n matrices = list()\n matrices.append(m1 if not scipy.sparse.isspmatrix(m1) else m1.toarray())\n matrices.append(m2 if not scipy.sparse.isspmatrix(m2) else m2.toarray())\n x = np.vstack(matrices)\n mean_shift = x.mean(axis=0)\n x = x - mean_shift\n n_components = min(n_components, x.shape[0]) # n_components must be <= ncells\n pca = PCA(n_components=n_components, random_state=58951)\n pca.fit(x.T)\n comp = pca.components_.T\n m1_len = m1.shape[0]\n m2_len = m2.shape[0]\n pca_1 = comp[0:m1_len]\n pca_2 = comp[m1_len:(m1_len + m2_len)]\n return pca_1, pca_2, pca, mean_shift\n\ndef compute_default_cost_matrix(a, b, eigenvals=None):\n\n if eigenvals is not None:\n a = a.dot(eigenvals)\n b = b.dot(eigenvals)\n\n cost_matrix = pairwise.pairwise_distances(a.toarray() if scipy.sparse.isspmatrix(a) else a,\n b.toarray() if scipy.sparse.isspmatrix(b) else b,\n metric='sqeuclidean', n_jobs=-1)\n cost_matrix = cost_matrix / np.median(cost_matrix)\n return cost_matrix\n\ndef compute_gene_exp_distance(adata,p0_indices,p1_indices,pc_n=30):\n '''\n Compute the gene expression distance between t0 and t1 states.\n\n p0_indices could be either a boolean array or index array\n '''\n p0=adata[p0_indices,:]\n p1=adata[p1_indices,:]\n p0_x, p1_x, pca, mean = compute_pca(p0.X, p1.X, pc_n)\n eigenvals = np.diag(pca.singular_values_)\n #gene_exp_dis_t0 = compute_default_cost_matrix(p0_x, p0_x, eigenvals)\n #gene_exp_dis_t1 = compute_default_cost_matrix(p1_x, p1_x, eigenvals)\n gene_exp_dis_t0t1 = compute_default_cost_matrix(p0_x, p1_x, eigenvals)\n return gene_exp_dis_t0t1\n\n"
] | [
[
"numpy.in1d",
"scipy.sparse.load_npz",
"numpy.cumsum",
"numpy.max",
"numpy.mean",
"scipy.sparse.issparse",
"numpy.save",
"numpy.diff",
"numpy.load",
"numpy.zeros",
"numpy.nonzero",
"pandas.Categorical",
"scipy.sparse.csr_matrix",
"numpy.argsort",
"scipy.sparse.save_npz",
"numpy.array",
"numpy.sum",
"numpy.ones",
"scipy.sparse.lil_matrix"
],
[
"numpy.nanmax",
"numpy.diag",
"numpy.dot",
"numpy.sqrt",
"numpy.linspace",
"numpy.in1d",
"numpy.max",
"scipy.optimize.fmin",
"numpy.mean",
"numpy.exp",
"scipy.sparse.issparse",
"numpy.arange",
"numpy.argmax",
"numpy.diff",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.log",
"numpy.nonzero",
"matplotlib.pyplot.title",
"numpy.min",
"sklearn.neighbors.kneighbors_graph",
"numpy.median",
"numpy.isnan",
"scipy.sparse.csr_matrix",
"numpy.cov",
"numpy.log10",
"scipy.stats.ranksums",
"numpy.argsort",
"numpy.array",
"matplotlib.pyplot.show",
"sklearn.decomposition.PCA",
"numpy.meshgrid",
"matplotlib.pyplot.ylabel",
"sklearn.decomposition.TruncatedSVD",
"numpy.sum",
"scipy.sparse.isspmatrix",
"numpy.log2",
"numpy.random.seed",
"numpy.percentile",
"scipy.spatial.distance.pdist",
"matplotlib.pyplot.xlabel",
"numpy.vstack",
"scipy.sparse.lil_matrix"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [
"1.6",
"1.10",
"1.4",
"1.9",
"0.19",
"1.5",
"1.2",
"1.7",
"1.0",
"1.3",
"1.8"
],
"tensorflow": []
},
{
"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": []
}
] |
sudarshan85/task_utils | [
"d79467293ca43ba93c95415d3d4ef25199bd5bea"
] | [
"metrics.py"
] | [
"#!/usr/bin/env python\n\nimport numpy as np\nimport pandas as pd\npd.set_option('display.max_colwidth', -1)\n\nfrom functools import partial\nfrom typing import List\nfrom sklearn.metrics import confusion_matrix, roc_auc_score, precision_score, f1_score, recall_score\nfrom scipy import stats\n\ndef _mean_confidence_interval(data, conf=0.95, decimal=3):\n assert(conf > 0 and conf < 1), f\"Confidence interval must be within (0, 1). It is {conf}\"\n a = 1.0 * np.array(data)\n n = len(a)\n m, se = np.mean(a, axis=0), stats.sem(a, axis=0)\n h = se * stats.t.ppf((1 + conf) / 2., n-1)\n return np.round(m, decimal), np.round(m-h, decimal), np.round(m+h, decimal)\n\nclass MultiAvgMetrics(object):\n def __init__(self, n_classes: int, targs: List[int], preds: List[int], decimal=3) -> None:\n assert (len(targs) == len(preds)), f\"Target list (length = {len(targets)}) and predictions list (length = {len(predictions)}) must be of the same length!))\"\n self.targs = targs\n self.n_runs = len(self.targs)\n self.preds = preds\n self.decimal = decimal\n self.n_classes = n_classes\n \n self.cms = np.zeros((len(self.targs), n_classes, n_classes), dtype=np.int64) \n \n for i, (targ, pred) in enumerate(zip(self.targs, self.preds)):\n self.cms[i] = confusion_matrix(targ, pred)\n \n @property\n def tps(self):\n \"\"\"\n All diagonal elements of CM\n \"\"\"\n tp = np.zeros((self.n_runs, self.n_classes))\n for i in range(self.n_runs):\n tp[i] = np.diag(self.cms[i])\n return tp\n \n @property\n def fns(self):\n \"\"\"\n Sum of values of class's row excluding TP\n \"\"\"\n fn = np.zeros((self.n_runs, self.n_classes))\n for i in range(self.n_runs):\n fn[i] = self.cms[i].sum(axis=1) - np.diag(self.cms[i])\n return fn\n \n @property\n def fps(self):\n \"\"\"\n Sum of values of class's column excluding TP\n \"\"\"\n fp = np.zeros((self.n_runs, self.n_classes))\n for i in range(self.n_runs):\n fp[i] = self.cms[i].sum(axis=0) - np.diag(self.cms[i])\n return fp\n \n @property\n def tns(self):\n \"\"\"\n Sum of all values of excluding elements from class's row and column\n \"\"\"\n tn = np.zeros((self.n_runs, self.n_classes))\n for i in range(self.n_runs):\n tn[i] = self.cms[i].sum() - (self.cms[i].sum(axis=1) + self.cms[i].sum(axis=0) - np.diag(self.cms[i]))\n return tn\n \n @property\n def prevalence_avg(self):\n return np.round(((self.fns + self.tps) / (self.tns + self.fps + self.fns + self.tps)).mean(axis=0), self.decimal)\n \n @property\n def sensitivities(self):\n return self.tps / (self.tps + self.fns)\n \n @property\n def specificities(self):\n return self.tns / (self.tns + self.fps) \n \n @property\n def ppvs(self):\n return self.tps / (self.tps + self.fps)\n \n @property\n def npvs(self):\n return self.tns / (self.tns + self.fns)\n \n @property\n def f1s(self):\n return (2 * self.sensitivities() * self.ppvs()) / (self.sensitivities() + self.ppvs()) \n \n def sensitivity_avg(self, conf=None):\n se = (self.tps / (self.tps + self.fns))\n if conf is not None:\n return _mean_confidence_interval(se, conf)\n\n return np.round(se.mean(axis=0), self.decimal,) \n \n def specificity_avg(self, conf=None):\n sp = (self.tns / (self.tns + self.fps))\n if conf is not None:\n return _mean_confidence_interval(sp, conf)\n\n return np.round(sp.mean(axis=0), self.decimal)\n \n def ppv_avg(self, conf=None):\n ppv = (self.tps / (self.tps + self.fps))\n if conf is not None:\n return _mean_confidence_interval(ppv, conf)\n\n return np.round(ppv.mean(axis=0), self.decimal) \n \n def npv_avg(self, conf=None):\n npv = (self.tns / (self.tns + self.fns))\n if conf is not None:\n return _mean_confidence_interval(npv, conf)\n\n return np.round(npv.mean(axis=0), self.decimal) \n \n def f1_avg(self, conf=None):\n se = (self.tps / (self.tps + self.fns))\n ppv = (self.tps / (self.tps + self.fps))\n f1 = (2 * se * ppv) / (se + ppv)\n if conf is not None:\n return _mean_confidence_interval(f1, conf)\n\n return np.round(f1.mean(axis=0), self.decimal)\n \n def get_class_metrics(self, class_names=None):\n if not class_names:\n class_names = list(range(self.n_classes))\n \n metrics = {\n 'sensitivity': list(self.sensitivity_avg()),\n 'specificity': list(self.specificity_avg()),\n 'ppv': list(self.ppv_avg()),\n 'npv': list(self.npv_avg()),\n 'f1': list(self.f1_avg()),\n }\n \n return pd.DataFrame(metrics.values(), index=metrics.keys(), columns=class_names)\n \n def get_weighted_metrics(self):\n sensitivity = np.array([recall_score(targ, pred, average='weighted') for targ, pred in zip(self.targs, self.preds)]).mean()\n ppv = np.array([precision_score(targ, pred, average='weighted') for targ, pred in zip(self.targs, self.preds)]).mean()\n f1 = np.array([f1_score(targ, pred, average='weighted') for targ, pred in zip(self.targs, self.preds)]).mean()\n \n metrics = {\n 'sensitivity': np.round((sensitivity), self.decimal),\n 'ppv': np.round((ppv), self.decimal),\n 'f1': np.round((f1), self.decimal),\n }\n \n return pd.DataFrame(metrics.values(), index=metrics.keys(), columns=['Value']) \n\nclass BinaryAvgMetrics(object):\n def __init__(self, targets: List[int], predictions: List[int], pos_probs: List[float], decimal=3) -> None:\n assert (len(targets) == len(predictions) == len(pos_probs)), f\"Target list (length = {len(targets)}), predictions list (length = {len(predictions)}) and probabilities list (length = {len(pos_probs)}) must all be of the same length!))\"\n self.targs = targets\n self.n_runs = len(self.targs)\n self.preds = predictions\n self.pos_probs = pos_probs\n self.decimal = 3\n \n self.cms = np.zeros((len(self.targs), 2, 2), dtype=np.int64)\n\n for i, (targ, pred) in enumerate(zip(self.targs, self.preds)):\n self.cms[i] = confusion_matrix(targ, pred) \n\n @property\n def tns(self):\n return self.cms[:, 0, 0]\n \n @property\n def fps(self):\n return self.cms[:, 0, 1]\n \n @property\n def fns(self):\n return self.cms[:, 1, 0]\n \n @property\n def tps(self):\n return self.cms[:, 1, 1]\n \n @property\n def cm_avg(self):\n return np.ceil(np.array([[self.tns.mean(), self.fps.mean()], [self.fns.mean(), self.tps.mean()]])).astype(np.int64)\n \n @property\n def prevalence_avg(self):\n return np.round(((self.fns + self.tps) / (self.tns + self.fps + self.fns + self.tps)).mean(), self.decimal)\n\n def sensitivities(self):\n return self.tps / (self.tps + self.fns)\n \n def sensitivity_avg(self, conf=None):\n se = (self.tps / (self.tps + self.fns))\n if conf is not None:\n return _mean_confidence_interval(se, conf)\n\n return np.round(se.mean(), self.decimal,)\n\n def specificities(self):\n return self.tns / (self.tns + self.fps)\n \n def specificity_avg(self, conf=None):\n sp = (self.tns / (self.tns + self.fps))\n if conf is not None:\n return _mean_confidence_interval(sp, conf)\n\n return np.round(sp.mean(), self.decimal)\n\n def ppvs(self):\n return self.tps / (self.tps + self.fps)\n \n def ppv_avg(self, conf=None):\n ppv = (self.tps / (self.tps + self.fps))\n if conf is not None:\n return _mean_confidence_interval(ppv, conf)\n\n return np.round(ppv.mean(), self.decimal) \n\n def npvs(self):\n return self.tns / (self.tns + self.fns)\n \n def npv_avg(self, conf=None):\n npv = (self.tns / (self.tns + self.fns))\n if conf is not None:\n return _mean_confidence_interval(npv, conf)\n\n return np.round(npv.mean(), self.decimal)\n \n def f1s(self):\n return (2 * self.sensitivities() * self.ppvs()) / (self.sensitivities() + self.ppvs())\n\n def f1_avg(self, conf=None):\n se = (self.tps / (self.tps + self.fns))\n ppv = (self.tps / (self.tps + self.fps))\n f1 = (2 * se * ppv) / (se + ppv)\n if conf is not None:\n return _mean_confidence_interval(f1, conf)\n\n return np.round(f1.mean(), self.decimal)\n\n def aurocs(self):\n return np.array([roc_auc_score(targ, prob) for targ, prob in zip(self.targs, self.pos_probs)])\n\n def auroc_avg(self, conf=None):\n auroc = np.array([roc_auc_score(targ, prob) for targ, prob in zip(self.targs, self.pos_probs)])\n if conf is not None:\n return _mean_confidence_interval(auroc, conf)\n\n return np.round(auroc.mean(), self.decimal)\n\n def get_all_avg_metrics(self, conf=None, defn=False):\n definitions = {\n 'sensitivity': \"When it's ACTUALLY YES, how often does it PREDICT YES?\",\n 'specificity': \"When it's ACTUALLY NO, how often does it PREDICT NO?\",\n 'ppv': \"When it PREDICTS YES, how often is it correct?\",\n 'auroc': \"Indicates how well the model is capable of distinguishing between classes\",\n 'npv': \"When it PREDICTS NO, how often is it correct?\",\n 'f1': \"Harmonic mean of sensitivity and ppv\",\n }\n if conf is None:\n metrics = {\n 'sensitivity': [self.sensitivity_avg()],\n 'specificity': [self.specificity_avg()],\n 'ppv': [self.ppv_avg()],\n 'auroc': [self.auroc_avg()],\n 'npv': [self.npv_avg()],\n 'f1': [self.f1_avg()],\n }\n\n if defn:\n for metric, value in metrics.items():\n value.append(definitions[metric])\n d = pd.DataFrame(metrics.values(), index=metrics.keys(), columns=['Value', 'Definition'])\n else:\n d = pd.DataFrame(metrics.values(), index=metrics.keys(), columns=['Value'])\n\n return d\n\n else:\n metrics = {\n 'sensitivity': [*[value for value in self.sensitivity_avg(conf)]], \n 'specificity': [*[value for value in self.specificity_avg(conf)]],\n 'ppv': [*[value for value in self.ppv_avg(conf)]],\n 'auroc': [*[value for value in self.auroc_avg(conf)]], \n 'npv': [*[value for value in self.npv_avg(conf)]],\n 'f1': [*[value for value in self.f1_avg(conf)]], \n }\n\n if defn:\n for metric, value in metrics.items():\n value.append(definitions[metric])\n d = pd.DataFrame(metrics.values(), index=metrics.keys(), columns=['Mean', 'Lower', 'Upper', 'Definition'])\n else:\n d = pd.DataFrame(metrics.values(), index=metrics.keys(), columns=['Mean', 'Lower', 'Upper'])\n\n return d\n\n def get_main_avg_metrics(self, conf=None, defn=False):\n definitions = {\n 'sensitivity': \"When it's ACTUALLY YES, how often does it PREDICT YES?\",\n 'specificity': \"When it's ACTUALLY NO, how often does it PREDICT NO?\",\n 'ppv': \"When it PREDICTS YES, how often is it correct?\",\n 'auroc': \"Indicates how well the model is capable of distinguishing between classes\",\n }\n if conf is None:\n metrics = {\n 'sensitivity': [self.sensitivity_avg()],\n 'specificity': [self.specificity_avg()],\n 'ppv': [self.ppv_avg()],\n 'auroc': [self.auroc_avg()],\n }\n\n if defn:\n for metric, value in metrics.items():\n value.append(definitions[metric])\n d = pd.DataFrame(metrics.values(), index=metrics.keys(), columns=['Value', 'Definition'])\n else:\n d = pd.DataFrame(metrics.values(), index=metrics.keys(), columns=['Value'])\n\n return d\n\n else:\n metrics = {\n 'sensitivity': [*[value for value in self.sensitivity_avg(conf)]], \n 'specificity': [*[value for value in self.specificity_avg(conf)]],\n 'ppv': [*[value for value in self.ppv_avg(conf)]],\n 'auroc': [*[value for value in self.auroc_avg(conf)]], \n }\n\n if defn:\n for metric, value in metrics.items():\n value.append(definitions[metric])\n d = pd.DataFrame(metrics.values(), index=metrics.keys(), columns=['Mean', 'Lower', 'Upper', 'Definition'])\n else:\n d = pd.DataFrame(metrics.values(), index=metrics.keys(), columns=['Mean', 'Lower', 'Upper'])\n\n return d\n\n\n def yield_metrics(self):\n yield ('Sensitivity', self.sensitivities())\n yield ('Specificity', self.specificities())\n yield ('PPV', self.ppvs())\n yield ('AUC', self.aurocs())\n yield ('NPV', self.npvs())\n yield ('F1', self.f1s())\n \n def __repr__(self):\n s = f\"Number of Runs: {self.n_runs}\\n\"\n return s\n \n def __len__(self):\n return len(self.targs)\n\ndef get_best_model(bam: BinaryAvgMetrics, fnames: List[str]):\n best_se, best_se_model = 0, None\n best_sp, best_sp_model = 0, None\n best_ppv, best_ppv_model = 0, None\n best_auroc, best_auroc_model = 0, None\n best_npv, best_npv_model = 0, None\n best_f1, best_f1_model = 0, None\n\n for i in range(bam.n_runs):\n se = bam.tps[i] / (bam.tps[i] + bam.fns[i])\n sp = bam.tns[i] / (bam.tns[i] + bam.fps[i])\n ppv = bam.tps[i] / (bam.tps[i] + bam.fps[i])\n npv = bam.tns[i] / (bam.tns[i] + bam.fns[i])\n f1 = (2 * se * ppv) / (se + ppv)\n\n if best_se < se:\n best_se = se\n best_se_model = fnames[i] \n if best_sp < sp:\n best_sp = sp\n best_sp_model = fnames[i] \n if best_ppv < ppv:\n best_ppv = ppv\n best_ppv_model = fnames[i] \n if best_npv < npv:\n best_npv = npv\n best_npv_model = fnames[i] \n if best_f1 < f1:\n best_f1 = f1\n best_f1_model = fnames[i] \n\n for i, (targ, prob) in enumerate(zip(bam.targs, bam.pos_probs)):\n auroc = roc_auc_score(targ, prob)\n if best_auroc < auroc:\n best_auroc = auroc\n best_auroc_model = fnames[i]\n\n d = {\n 'sensitivity': [best_se, best_se_model],\n 'specificity': [best_sp, best_sp_model],\n 'ppv': [best_ppv, best_ppv_model],\n 'auroc': [best_auroc, best_auroc_model],\n 'npv': [best_npv, best_npv_model],\n 'f1': [best_f1, best_f1_model],\n }\n\n return pd.DataFrame(d.values(), index=d.keys(), columns=['Value', 'Model File'])\n"
] | [
[
"numpy.diag",
"sklearn.metrics.roc_auc_score",
"sklearn.metrics.recall_score",
"sklearn.metrics.precision_score",
"sklearn.metrics.confusion_matrix",
"scipy.stats.t.ppf",
"numpy.round",
"numpy.mean",
"sklearn.metrics.f1_score",
"pandas.set_option",
"scipy.stats.sem",
"numpy.array",
"numpy.zeros"
]
] | [
{
"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": []
}
] |
joshcarty/dgl | [
"4464b9734c1061bd84325a54883c5046031def37",
"4464b9734c1061bd84325a54883c5046031def37",
"4464b9734c1061bd84325a54883c5046031def37"
] | [
"benchmarks/benchmarks/model_speed/bench_gat.py",
"tests/compute/test_heterograph.py",
"examples/pytorch/GATNE-T/src/utils.py"
] | [
"import time\nimport dgl\nfrom dgl.nn.pytorch import GATConv\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom .. import utils\n\nclass GAT(nn.Module):\n def __init__(self,\n num_layers,\n in_dim,\n num_hidden,\n num_classes,\n heads,\n activation,\n feat_drop,\n attn_drop,\n negative_slope,\n residual):\n super(GAT, self).__init__()\n self.num_layers = num_layers\n self.gat_layers = nn.ModuleList()\n self.activation = activation\n # input projection (no residual)\n self.gat_layers.append(GATConv(\n in_dim, num_hidden, heads[0],\n feat_drop, attn_drop, negative_slope, False, self.activation))\n # hidden layers\n for l in range(1, num_layers):\n # due to multi-head, the in_dim = num_hidden * num_heads\n self.gat_layers.append(GATConv(\n num_hidden * heads[l-1], num_hidden, heads[l],\n feat_drop, attn_drop, negative_slope, residual, self.activation))\n # output projection\n self.gat_layers.append(GATConv(\n num_hidden * heads[-2], num_classes, heads[-1],\n feat_drop, attn_drop, negative_slope, residual, None))\n\n def forward(self, g, inputs):\n h = inputs\n for l in range(self.num_layers):\n h = self.gat_layers[l](g, h).flatten(1)\n # output projection\n logits = self.gat_layers[-1](g, h).mean(1)\n return logits\n\[email protected]('time')\[email protected]('data', ['cora', 'pubmed'])\ndef track_time(data):\n data = utils.process_data(data)\n device = utils.get_bench_device()\n num_epochs = 200\n\n g = data[0].to(device)\n\n features = g.ndata['feat']\n labels = g.ndata['label']\n train_mask = g.ndata['train_mask']\n val_mask = g.ndata['val_mask']\n test_mask = g.ndata['test_mask']\n\n in_feats = features.shape[1]\n n_classes = data.num_labels\n\n g = dgl.remove_self_loop(g)\n g = dgl.add_self_loop(g)\n\n # create model\n model = GAT(1, in_feats, 8, n_classes, [8, 1], F.elu,\n 0.6, 0.6, 0.2, False)\n loss_fcn = torch.nn.CrossEntropyLoss()\n\n model = model.to(device)\n model.train()\n\n # optimizer\n optimizer = torch.optim.Adam(model.parameters(),\n lr=1e-2,\n weight_decay=5e-4)\n\n # dry run\n for epoch in range(10):\n logits = model(g, features)\n loss = loss_fcn(logits[train_mask], labels[train_mask])\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # timing\n t0 = time.time()\n for epoch in range(num_epochs):\n logits = model(g, features)\n loss = loss_fcn(logits[train_mask], labels[train_mask])\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n t1 = time.time()\n\n return (t1 - t0) / num_epochs\n",
"import dgl\nimport dgl.function as fn\nfrom collections import Counter\nimport numpy as np\nimport scipy.sparse as ssp\nimport itertools\nimport backend as F\nimport networkx as nx\nimport unittest, pytest\nfrom dgl import DGLError\nimport test_utils\nfrom test_utils import parametrize_dtype, get_cases\nfrom scipy.sparse import rand\n\ndef create_test_heterograph(idtype):\n # test heterograph from the docstring, plus a user -- wishes -- game relation\n # 3 users, 2 games, 2 developers\n # metagraph:\n # ('user', 'follows', 'user'),\n # ('user', 'plays', 'game'),\n # ('user', 'wishes', 'game'),\n # ('developer', 'develops', 'game')])\n\n g = dgl.heterograph({\n ('user', 'follows', 'user'): ([0, 1], [1, 2]),\n ('user', 'plays', 'game'): ([0, 1, 2, 1], [0, 0, 1, 1]),\n ('user', 'wishes', 'game'): ([0, 2], [1, 0]),\n ('developer', 'develops', 'game'): ([0, 1], [0, 1])\n }, idtype=idtype, device=F.ctx())\n assert g.idtype == idtype\n assert g.device == F.ctx()\n return g\n\ndef create_test_heterograph1(idtype):\n edges = []\n edges.extend([(0, 1), (1, 2)]) # follows\n edges.extend([(0, 3), (1, 3), (2, 4), (1, 4)]) # plays\n edges.extend([(0, 4), (2, 3)]) # wishes\n edges.extend([(5, 3), (6, 4)]) # develops\n edges = tuple(zip(*edges))\n ntypes = F.tensor([0, 0, 0, 1, 1, 2, 2])\n etypes = F.tensor([0, 0, 1, 1, 1, 1, 2, 2, 3, 3])\n g0 = dgl.graph(edges, idtype=idtype, device=F.ctx())\n g0.ndata[dgl.NTYPE] = ntypes\n g0.edata[dgl.ETYPE] = etypes\n return dgl.to_heterogeneous(g0, ['user', 'game', 'developer'],\n ['follows', 'plays', 'wishes', 'develops'])\n\ndef create_test_heterograph2(idtype):\n g = dgl.heterograph({\n ('user', 'follows', 'user'): ([0, 1], [1, 2]),\n ('user', 'plays', 'game'): ([0, 1, 2, 1], [0, 0, 1, 1]),\n ('user', 'wishes', 'game'): ([0, 2], [1, 0]),\n ('developer', 'develops', 'game'): ([0, 1], [0, 1]),\n }, idtype=idtype, device=F.ctx())\n assert g.idtype == idtype\n assert g.device == F.ctx()\n return g\n\ndef create_test_heterograph3(idtype):\n g = dgl.heterograph({\n ('user', 'plays', 'game'): (F.tensor([0, 1, 1, 2], dtype=idtype),\n F.tensor([0, 0, 1, 1], dtype=idtype)),\n ('developer', 'develops', 'game'): (F.tensor([0, 1], dtype=idtype),\n F.tensor([0, 1], dtype=idtype))},\n idtype=idtype, device=F.ctx())\n\n g.nodes['user'].data['h'] = F.copy_to(F.tensor([1, 1, 1], dtype=idtype), ctx=F.ctx())\n g.nodes['game'].data['h'] = F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx())\n g.nodes['developer'].data['h'] = F.copy_to(F.tensor([3, 3], dtype=idtype), ctx=F.ctx())\n g.edges['plays'].data['h'] = F.copy_to(F.tensor([1, 1, 1, 1], dtype=idtype), ctx=F.ctx())\n return g\n\ndef create_test_heterograph4(idtype):\n g = dgl.heterograph({\n ('user', 'follows', 'user'): (F.tensor([0, 1, 1, 2, 2, 2], dtype=idtype),\n F.tensor([0, 0, 1, 1, 2, 2], dtype=idtype)),\n ('user', 'plays', 'game'): (F.tensor([0, 1], dtype=idtype),\n F.tensor([0, 1], dtype=idtype))},\n idtype=idtype, device=F.ctx())\n g.nodes['user'].data['h'] = F.copy_to(F.tensor([1, 1, 1], dtype=idtype), ctx=F.ctx())\n g.nodes['game'].data['h'] = F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx())\n g.edges['follows'].data['h'] = F.copy_to(F.tensor([1, 2, 3, 4, 5, 6], dtype=idtype), ctx=F.ctx())\n g.edges['plays'].data['h'] = F.copy_to(F.tensor([1, 2], dtype=idtype), ctx=F.ctx())\n return g\n\ndef create_test_heterograph5(idtype):\n g = dgl.heterograph({\n ('user', 'follows', 'user'): (F.tensor([1, 2], dtype=idtype),\n F.tensor([0, 1], dtype=idtype)),\n ('user', 'plays', 'game'): (F.tensor([0, 1], dtype=idtype),\n F.tensor([0, 1], dtype=idtype))},\n idtype=idtype, device=F.ctx())\n g.nodes['user'].data['h'] = F.copy_to(F.tensor([1, 1, 1], dtype=idtype), ctx=F.ctx())\n g.nodes['game'].data['h'] = F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx())\n g.edges['follows'].data['h'] = F.copy_to(F.tensor([1, 2], dtype=idtype), ctx=F.ctx())\n g.edges['plays'].data['h'] = F.copy_to(F.tensor([1, 2], dtype=idtype), ctx=F.ctx())\n return g\n\ndef get_redfn(name):\n return getattr(F, name)\n\n@parametrize_dtype\ndef test_create(idtype):\n device = F.ctx()\n g0 = create_test_heterograph(idtype)\n g1 = create_test_heterograph1(idtype)\n g2 = create_test_heterograph2(idtype)\n assert set(g0.ntypes) == set(g1.ntypes) == set(g2.ntypes)\n assert set(g0.canonical_etypes) == set(g1.canonical_etypes) == set(g2.canonical_etypes)\n\n # Create a bipartite graph from a SciPy matrix\n src_ids = np.array([2, 3, 4])\n dst_ids = np.array([1, 2, 3])\n eweight = np.array([0.2, 0.3, 0.5])\n sp_mat = ssp.coo_matrix((eweight, (src_ids, dst_ids)))\n g = dgl.bipartite_from_scipy(sp_mat, utype='user', etype='plays',\n vtype='game', idtype=idtype, device=device)\n assert g.idtype == idtype\n assert g.device == device\n assert g.num_src_nodes() == 5\n assert g.num_dst_nodes() == 4\n assert g.num_edges() == 3\n src, dst = g.edges()\n assert F.allclose(src, F.tensor([2, 3, 4], dtype=idtype))\n assert F.allclose(dst, F.tensor([1, 2, 3], dtype=idtype))\n g = dgl.bipartite_from_scipy(sp_mat, utype='_U', etype='_E', vtype='_V',\n eweight_name='w', idtype=idtype, device=device)\n assert F.allclose(g.edata['w'], F.tensor(eweight))\n\n # Create a bipartite graph from a NetworkX graph\n nx_g = nx.DiGraph()\n nx_g.add_nodes_from([1, 3], bipartite=0, feat1=np.zeros((2)), feat2=np.ones((2)))\n nx_g.add_nodes_from([2, 4, 5], bipartite=1, feat3=np.zeros((3)))\n nx_g.add_edge(1, 4, weight=np.ones((1)), eid=np.array([1]))\n nx_g.add_edge(3, 5, weight=np.ones((1)), eid=np.array([0]))\n g = dgl.bipartite_from_networkx(nx_g, utype='user', etype='plays',\n vtype='game', idtype=idtype, device=device)\n assert g.idtype == idtype\n assert g.device == device\n assert g.num_src_nodes() == 2\n assert g.num_dst_nodes() == 3\n assert g.num_edges() == 2\n src, dst = g.edges()\n assert F.allclose(src, F.tensor([0, 1], dtype=idtype))\n assert F.allclose(dst, F.tensor([1, 2], dtype=idtype))\n g = dgl.bipartite_from_networkx(nx_g, utype='_U', etype='_E', vtype='V',\n u_attrs=['feat1', 'feat2'],\n e_attrs = ['weight'], v_attrs = ['feat3'])\n assert F.allclose(g.srcdata['feat1'], F.tensor(np.zeros((2, 2))))\n assert F.allclose(g.srcdata['feat2'], F.tensor(np.ones((2, 2))))\n assert F.allclose(g.dstdata['feat3'], F.tensor(np.zeros((3, 3))))\n assert F.allclose(g.edata['weight'], F.tensor(np.ones((2, 1))))\n g = dgl.bipartite_from_networkx(nx_g, utype='_U', etype='_E', vtype='V',\n edge_id_attr_name='eid', idtype=idtype, device=device)\n src, dst = g.edges()\n assert F.allclose(src, F.tensor([1, 0], dtype=idtype))\n assert F.allclose(dst, F.tensor([2, 1], dtype=idtype))\n\n # create from scipy\n spmat = ssp.coo_matrix(([1,1,1], ([0, 0, 1], [2, 3, 2])), shape=(4, 4))\n g = dgl.from_scipy(spmat, idtype=idtype, device=device)\n assert g.num_nodes() == 4\n assert g.num_edges() == 3\n assert g.idtype == idtype\n assert g.device == device\n\n # test inferring number of nodes for heterograph\n g = dgl.heterograph({\n ('l0', 'e0', 'l1'): ([0, 0], [1, 2]),\n ('l0', 'e1', 'l2'): ([2], [2]),\n ('l2', 'e2', 'l2'): ([1, 3], [1, 3])\n }, idtype=idtype, device=device)\n assert g.num_nodes('l0') == 3\n assert g.num_nodes('l1') == 3\n assert g.num_nodes('l2') == 4\n assert g.idtype == idtype\n assert g.device == device\n\n # test if validate flag works\n # homo graph\n with pytest.raises(DGLError):\n g = dgl.graph(\n ([0, 0, 0, 1, 1, 2], [0, 1, 2, 0, 1, 2]),\n num_nodes=2,\n idtype=idtype, device=device\n )\n # bipartite graph\n def _test_validate_bipartite(card):\n with pytest.raises(DGLError):\n g = dgl.heterograph({\n ('_U', '_E', '_V'): ([0, 0, 1, 1, 2], [1, 1, 2, 2, 3])\n }, {'_U': card[0], '_V': card[1]}, idtype=idtype, device=device)\n\n _test_validate_bipartite((3, 3))\n _test_validate_bipartite((2, 4))\n\n # test from_scipy\n num_nodes = 10\n density = 0.25\n for fmt in ['csr', 'coo', 'csc']:\n adj = rand(num_nodes, num_nodes, density=density, format=fmt)\n g = dgl.from_scipy(adj, eweight_name='w', idtype=idtype)\n assert g.idtype == idtype\n assert g.device == F.cpu()\n assert F.array_equal(g.edata['w'], F.copy_to(F.tensor(adj.data), F.cpu()))\n\n@parametrize_dtype\ndef test_query(idtype):\n g = create_test_heterograph(idtype)\n\n ntypes = ['user', 'game', 'developer']\n canonical_etypes = [\n ('user', 'follows', 'user'),\n ('user', 'plays', 'game'),\n ('user', 'wishes', 'game'),\n ('developer', 'develops', 'game')]\n etypes = ['follows', 'plays', 'wishes', 'develops']\n\n # node & edge types\n assert set(ntypes) == set(g.ntypes)\n assert set(etypes) == set(g.etypes)\n assert set(canonical_etypes) == set(g.canonical_etypes)\n\n # metagraph\n mg = g.metagraph()\n assert set(g.ntypes) == set(mg.nodes)\n etype_triplets = [(u, v, e) for u, v, e in mg.edges(keys=True)]\n assert set([\n ('user', 'user', 'follows'),\n ('user', 'game', 'plays'),\n ('user', 'game', 'wishes'),\n ('developer', 'game', 'develops')]) == set(etype_triplets)\n for i in range(len(etypes)):\n assert g.to_canonical_etype(etypes[i]) == canonical_etypes[i]\n\n def _test(g):\n # number of nodes\n assert [g.num_nodes(ntype) for ntype in ntypes] == [3, 2, 2]\n\n # number of edges\n assert [g.num_edges(etype) for etype in etypes] == [2, 4, 2, 2]\n\n # has_node & has_nodes\n for ntype in ntypes:\n n = g.number_of_nodes(ntype)\n for i in range(n):\n assert g.has_node(i, ntype)\n assert not g.has_node(n, ntype)\n assert np.array_equal(\n F.asnumpy(g.has_nodes([0, n], ntype)).astype('int32'), [1, 0])\n\n assert not g.is_multigraph\n\n for etype in etypes:\n srcs, dsts = edges[etype]\n for src, dst in zip(srcs, dsts):\n assert g.has_edges_between(src, dst, etype)\n assert F.asnumpy(g.has_edges_between(srcs, dsts, etype)).all()\n\n srcs, dsts = negative_edges[etype]\n for src, dst in zip(srcs, dsts):\n assert not g.has_edges_between(src, dst, etype)\n assert not F.asnumpy(g.has_edges_between(srcs, dsts, etype)).any()\n\n srcs, dsts = edges[etype]\n n_edges = len(srcs)\n\n # predecessors & in_edges & in_degree\n pred = [s for s, d in zip(srcs, dsts) if d == 0]\n assert set(F.asnumpy(g.predecessors(0, etype)).tolist()) == set(pred)\n u, v = g.in_edges([0], etype=etype)\n assert F.asnumpy(v).tolist() == [0] * len(pred)\n assert set(F.asnumpy(u).tolist()) == set(pred)\n assert g.in_degrees(0, etype) == len(pred)\n\n # successors & out_edges & out_degree\n succ = [d for s, d in zip(srcs, dsts) if s == 0]\n assert set(F.asnumpy(g.successors(0, etype)).tolist()) == set(succ)\n u, v = g.out_edges([0], etype=etype)\n assert F.asnumpy(u).tolist() == [0] * len(succ)\n assert set(F.asnumpy(v).tolist()) == set(succ)\n assert g.out_degrees(0, etype) == len(succ)\n\n # edge_id & edge_ids\n for i, (src, dst) in enumerate(zip(srcs, dsts)):\n assert g.edge_ids(src, dst, etype=etype) == i\n _, _, eid = g.edge_ids(src, dst, etype=etype, return_uv=True)\n assert eid == i\n assert F.asnumpy(g.edge_ids(srcs, dsts, etype=etype)).tolist() == list(range(n_edges))\n u, v, e = g.edge_ids(srcs, dsts, etype=etype, return_uv=True)\n u, v, e = F.asnumpy(u), F.asnumpy(v), F.asnumpy(e)\n assert u[e].tolist() == srcs\n assert v[e].tolist() == dsts\n\n # find_edges\n for eid in [list(range(n_edges)), np.arange(n_edges), F.astype(F.arange(0, n_edges), g.idtype)]:\n u, v = g.find_edges(eid, etype)\n assert F.asnumpy(u).tolist() == srcs\n assert F.asnumpy(v).tolist() == dsts\n\n # all_edges.\n for order in ['eid']:\n u, v, e = g.edges('all', order, etype)\n assert F.asnumpy(u).tolist() == srcs\n assert F.asnumpy(v).tolist() == dsts\n assert F.asnumpy(e).tolist() == list(range(n_edges))\n\n # in_degrees & out_degrees\n in_degrees = F.asnumpy(g.in_degrees(etype=etype))\n out_degrees = F.asnumpy(g.out_degrees(etype=etype))\n src_count = Counter(srcs)\n dst_count = Counter(dsts)\n utype, _, vtype = g.to_canonical_etype(etype)\n for i in range(g.number_of_nodes(utype)):\n assert out_degrees[i] == src_count[i]\n for i in range(g.number_of_nodes(vtype)):\n assert in_degrees[i] == dst_count[i]\n\n edges = {\n 'follows': ([0, 1], [1, 2]),\n 'plays': ([0, 1, 2, 1], [0, 0, 1, 1]),\n 'wishes': ([0, 2], [1, 0]),\n 'develops': ([0, 1], [0, 1]),\n }\n # edges that does not exist in the graph\n negative_edges = {\n 'follows': ([0, 1], [0, 1]),\n 'plays': ([0, 2], [1, 0]),\n 'wishes': ([0, 1], [0, 1]),\n 'develops': ([0, 1], [1, 0]),\n }\n g = create_test_heterograph(idtype)\n _test(g)\n g = create_test_heterograph1(idtype)\n _test(g)\n if F._default_context_str != 'gpu':\n # XXX: CUDA COO operators have not been live yet.\n g = create_test_heterograph2(idtype)\n _test(g)\n\n etypes = canonical_etypes\n edges = {\n ('user', 'follows', 'user'): ([0, 1], [1, 2]),\n ('user', 'plays', 'game'): ([0, 1, 2, 1], [0, 0, 1, 1]),\n ('user', 'wishes', 'game'): ([0, 2], [1, 0]),\n ('developer', 'develops', 'game'): ([0, 1], [0, 1]),\n }\n # edges that does not exist in the graph\n negative_edges = {\n ('user', 'follows', 'user'): ([0, 1], [0, 1]),\n ('user', 'plays', 'game'): ([0, 2], [1, 0]),\n ('user', 'wishes', 'game'): ([0, 1], [0, 1]),\n ('developer', 'develops', 'game'): ([0, 1], [1, 0]),\n }\n g = create_test_heterograph(idtype)\n _test(g)\n g = create_test_heterograph1(idtype)\n _test(g)\n if F._default_context_str != 'gpu':\n # XXX: CUDA COO operators have not been live yet.\n g = create_test_heterograph2(idtype)\n _test(g)\n\n # test repr\n print(g)\n\n@parametrize_dtype\ndef test_empty_query(idtype):\n g = dgl.graph(([1, 2, 3], [0, 4, 5]), idtype=idtype, device=F.ctx())\n g.add_nodes(0)\n g.add_edges([], [])\n g.remove_edges([])\n g.remove_nodes([])\n assert F.shape(g.has_nodes([])) == (0,)\n assert F.shape(g.has_edges_between([], [])) == (0,)\n g.edge_ids([], [])\n g.edge_ids([], [], return_uv=True)\n g.find_edges([])\n\n assert F.shape(g.in_edges([], form='eid')) == (0,)\n u, v = g.in_edges([], form='uv')\n assert F.shape(u) == (0,)\n assert F.shape(v) == (0,)\n u, v, e = g.in_edges([], form='all')\n assert F.shape(u) == (0,)\n assert F.shape(v) == (0,)\n assert F.shape(e) == (0,)\n\n assert F.shape(g.out_edges([], form='eid')) == (0,)\n u, v = g.out_edges([], form='uv')\n assert F.shape(u) == (0,)\n assert F.shape(v) == (0,)\n u, v, e = g.out_edges([], form='all')\n assert F.shape(u) == (0,)\n assert F.shape(v) == (0,)\n assert F.shape(e) == (0,)\n\n assert F.shape(g.in_degrees([])) == (0,)\n assert F.shape(g.out_degrees([])) == (0,)\n\[email protected](F._default_context_str == 'gpu', reason=\"GPU does not have COO impl.\")\ndef _test_hypersparse():\n N1 = 1 << 50 # should crash if allocated a CSR\n N2 = 1 << 48\n\n g = dgl.heterograph({\n ('user', 'follows', 'user'): (F.tensor([0], F.int64), F.tensor([1], F.int64)),\n ('user', 'plays', 'game'): (F.tensor([0], F.int64), F.tensor([N2], F.int64))},\n {'user': N1, 'game': N1},\n device=F.ctx())\n assert g.number_of_nodes('user') == N1\n assert g.number_of_nodes('game') == N1\n assert g.number_of_edges('follows') == 1\n assert g.number_of_edges('plays') == 1\n\n assert g.has_edges_between(0, 1, 'follows')\n assert not g.has_edges_between(0, 0, 'follows')\n mask = F.asnumpy(g.has_edges_between([0, 0], [0, 1], 'follows')).tolist()\n assert mask == [0, 1]\n\n assert g.has_edges_between(0, N2, 'plays')\n assert not g.has_edges_between(0, 0, 'plays')\n mask = F.asnumpy(g.has_edges_between([0, 0], [0, N2], 'plays')).tolist()\n assert mask == [0, 1]\n\n assert F.asnumpy(g.predecessors(0, 'follows')).tolist() == []\n assert F.asnumpy(g.successors(0, 'follows')).tolist() == [1]\n assert F.asnumpy(g.predecessors(1, 'follows')).tolist() == [0]\n assert F.asnumpy(g.successors(1, 'follows')).tolist() == []\n\n assert F.asnumpy(g.predecessors(0, 'plays')).tolist() == []\n assert F.asnumpy(g.successors(0, 'plays')).tolist() == [N2]\n assert F.asnumpy(g.predecessors(N2, 'plays')).tolist() == [0]\n assert F.asnumpy(g.successors(N2, 'plays')).tolist() == []\n\n assert g.edge_ids(0, 1, etype='follows') == 0\n assert g.edge_ids(0, N2, etype='plays') == 0\n\n u, v = g.find_edges([0], 'follows')\n assert F.asnumpy(u).tolist() == [0]\n assert F.asnumpy(v).tolist() == [1]\n u, v = g.find_edges([0], 'plays')\n assert F.asnumpy(u).tolist() == [0]\n assert F.asnumpy(v).tolist() == [N2]\n u, v, e = g.all_edges('all', 'eid', 'follows')\n assert F.asnumpy(u).tolist() == [0]\n assert F.asnumpy(v).tolist() == [1]\n assert F.asnumpy(e).tolist() == [0]\n u, v, e = g.all_edges('all', 'eid', 'plays')\n assert F.asnumpy(u).tolist() == [0]\n assert F.asnumpy(v).tolist() == [N2]\n assert F.asnumpy(e).tolist() == [0]\n\n assert g.in_degrees(0, 'follows') == 0\n assert g.in_degrees(1, 'follows') == 1\n assert F.asnumpy(g.in_degrees([0, 1], 'follows')).tolist() == [0, 1]\n assert g.in_degrees(0, 'plays') == 0\n assert g.in_degrees(N2, 'plays') == 1\n assert F.asnumpy(g.in_degrees([0, N2], 'plays')).tolist() == [0, 1]\n assert g.out_degrees(0, 'follows') == 1\n assert g.out_degrees(1, 'follows') == 0\n assert F.asnumpy(g.out_degrees([0, 1], 'follows')).tolist() == [1, 0]\n assert g.out_degrees(0, 'plays') == 1\n assert g.out_degrees(N2, 'plays') == 0\n assert F.asnumpy(g.out_degrees([0, N2], 'plays')).tolist() == [1, 0]\n\ndef _test_edge_ids():\n N1 = 1 << 50 # should crash if allocated a CSR\n N2 = 1 << 48\n\n g = dgl.heterograph({\n ('user', 'follows', 'user'): (F.tensor([0], F.int64), F.tensor([1], F.int64)),\n ('user', 'plays', 'game'): (F.tensor([0], F.int64), F.tensor([N2], F.int64))},\n {'user': N1, 'game': N1})\n with pytest.raises(DGLError):\n eid = g.edge_ids(0, 0, etype='follows')\n\n g2 = dgl.heterograph({\n ('user', 'follows', 'user'): (F.tensor([0, 0], F.int64), F.tensor([1, 1], F.int64)),\n ('user', 'plays', 'game'): (F.tensor([0], F.int64), F.tensor([N2], F.int64))},\n {'user': N1, 'game': N1}, device=F.cpu())\n\n eid = g2.edge_ids(0, 1, etype='follows')\n assert eid == 0\n\n@parametrize_dtype\ndef test_adj(idtype):\n g = create_test_heterograph(idtype)\n adj = F.sparse_to_numpy(g.adj(transpose=False, etype='follows'))\n assert np.allclose(\n adj,\n np.array([[0., 0., 0.],\n [1., 0., 0.],\n [0., 1., 0.]]))\n adj = F.sparse_to_numpy(g.adj(transpose=True, etype='follows'))\n assert np.allclose(\n adj,\n np.array([[0., 1., 0.],\n [0., 0., 1.],\n [0., 0., 0.]]))\n adj = F.sparse_to_numpy(g.adj(transpose=False, etype='plays'))\n assert np.allclose(\n adj,\n np.array([[1., 1., 0.],\n [0., 1., 1.]]))\n adj = F.sparse_to_numpy(g.adj(transpose=True, etype='plays'))\n assert np.allclose(\n adj,\n np.array([[1., 0.],\n [1., 1.],\n [0., 1.]]))\n\n adj = g.adj(transpose=False, scipy_fmt='csr', etype='follows')\n assert np.allclose(\n adj.todense(),\n np.array([[0., 0., 0.],\n [1., 0., 0.],\n [0., 1., 0.]]))\n adj = g.adj(transpose=False, scipy_fmt='coo', etype='follows')\n assert np.allclose(\n adj.todense(),\n np.array([[0., 0., 0.],\n [1., 0., 0.],\n [0., 1., 0.]]))\n adj = g.adj(transpose=False, scipy_fmt='csr', etype='plays')\n assert np.allclose(\n adj.todense(),\n np.array([[1., 1., 0.],\n [0., 1., 1.]]))\n adj = g.adj(transpose=False, scipy_fmt='coo', etype='plays')\n assert np.allclose(\n adj.todense(),\n np.array([[1., 1., 0.],\n [0., 1., 1.]]))\n adj = F.sparse_to_numpy(g['follows'].adj(transpose=False))\n assert np.allclose(\n adj,\n np.array([[0., 0., 0.],\n [1., 0., 0.],\n [0., 1., 0.]]))\n\n@parametrize_dtype\ndef test_inc(idtype):\n g = create_test_heterograph(idtype)\n adj = F.sparse_to_numpy(g['follows'].inc('in'))\n assert np.allclose(\n adj,\n np.array([[0., 0.],\n [1., 0.],\n [0., 1.]]))\n adj = F.sparse_to_numpy(g['follows'].inc('out'))\n assert np.allclose(\n adj,\n np.array([[1., 0.],\n [0., 1.],\n [0., 0.]]))\n adj = F.sparse_to_numpy(g['follows'].inc('both'))\n assert np.allclose(\n adj,\n np.array([[-1., 0.],\n [1., -1.],\n [0., 1.]]))\n adj = F.sparse_to_numpy(g.inc('in', etype='plays'))\n assert np.allclose(\n adj,\n np.array([[1., 1., 0., 0.],\n [0., 0., 1., 1.]]))\n adj = F.sparse_to_numpy(g.inc('out', etype='plays'))\n assert np.allclose(\n adj,\n np.array([[1., 0., 0., 0.],\n [0., 1., 0., 1.],\n [0., 0., 1., 0.]]))\n adj = F.sparse_to_numpy(g.inc('both', etype='follows'))\n assert np.allclose(\n adj,\n np.array([[-1., 0.],\n [1., -1.],\n [0., 1.]]))\n\n@parametrize_dtype\ndef test_view(idtype):\n # test single node type\n g = dgl.heterograph({\n ('user', 'follows', 'user'): ([0, 1], [1, 2])\n }, idtype=idtype, device=F.ctx())\n f1 = F.randn((3, 6))\n g.ndata['h'] = f1\n f2 = g.nodes['user'].data['h']\n assert F.array_equal(f1, f2)\n fail = False\n try:\n g.ndata['h'] = {'user' : f1}\n except Exception:\n fail = True\n assert fail\n\n # test single edge type\n f3 = F.randn((2, 4))\n g.edata['h'] = f3\n f4 = g.edges['follows'].data['h']\n assert F.array_equal(f3, f4)\n fail = False\n try:\n g.edata['h'] = {'follows' : f3}\n except Exception:\n fail = True\n assert fail\n\n # test data view\n g = create_test_heterograph(idtype)\n\n f1 = F.randn((3, 6))\n g.nodes['user'].data['h'] = f1 # ok\n f2 = g.nodes['user'].data['h']\n assert F.array_equal(f1, f2)\n assert F.array_equal(g.nodes('user'), F.arange(0, 3, idtype))\n g.nodes['user'].data.pop('h')\n\n # multi type ndata\n f1 = F.randn((3, 6))\n f2 = F.randn((2, 6))\n fail = False\n try:\n g.ndata['h'] = f1\n except Exception:\n fail = True\n assert fail\n\n f3 = F.randn((2, 4))\n g.edges['user', 'follows', 'user'].data['h'] = f3\n f4 = g.edges['user', 'follows', 'user'].data['h']\n f5 = g.edges['follows'].data['h']\n assert F.array_equal(f3, f4)\n assert F.array_equal(f3, f5)\n assert F.array_equal(g.edges(etype='follows', form='eid'), F.arange(0, 2, idtype))\n g.edges['follows'].data.pop('h')\n\n f3 = F.randn((2, 4))\n fail = False\n try:\n g.edata['h'] = f3\n except Exception:\n fail = True\n assert fail\n\n # test srcdata\n f1 = F.randn((3, 6))\n g.srcnodes['user'].data['h'] = f1 # ok\n f2 = g.srcnodes['user'].data['h']\n assert F.array_equal(f1, f2)\n assert F.array_equal(g.srcnodes('user'), F.arange(0, 3, idtype))\n g.srcnodes['user'].data.pop('h')\n\n # test dstdata\n f1 = F.randn((3, 6))\n g.dstnodes['user'].data['h'] = f1 # ok\n f2 = g.dstnodes['user'].data['h']\n assert F.array_equal(f1, f2)\n assert F.array_equal(g.dstnodes('user'), F.arange(0, 3, idtype))\n g.dstnodes['user'].data.pop('h')\n\n@parametrize_dtype\ndef test_view1(idtype):\n # test relation view\n HG = create_test_heterograph(idtype)\n ntypes = ['user', 'game', 'developer']\n canonical_etypes = [\n ('user', 'follows', 'user'),\n ('user', 'plays', 'game'),\n ('user', 'wishes', 'game'),\n ('developer', 'develops', 'game')]\n etypes = ['follows', 'plays', 'wishes', 'develops']\n\n def _test_query():\n for etype in etypes:\n utype, _, vtype = HG.to_canonical_etype(etype)\n g = HG[etype]\n srcs, dsts = edges[etype]\n for src, dst in zip(srcs, dsts):\n assert g.has_edges_between(src, dst)\n assert F.asnumpy(g.has_edges_between(srcs, dsts)).all()\n\n srcs, dsts = negative_edges[etype]\n for src, dst in zip(srcs, dsts):\n assert not g.has_edges_between(src, dst)\n assert not F.asnumpy(g.has_edges_between(srcs, dsts)).any()\n\n srcs, dsts = edges[etype]\n n_edges = len(srcs)\n\n # predecessors & in_edges & in_degree\n pred = [s for s, d in zip(srcs, dsts) if d == 0]\n assert set(F.asnumpy(g.predecessors(0)).tolist()) == set(pred)\n u, v = g.in_edges([0])\n assert F.asnumpy(v).tolist() == [0] * len(pred)\n assert set(F.asnumpy(u).tolist()) == set(pred)\n assert g.in_degrees(0) == len(pred)\n\n # successors & out_edges & out_degree\n succ = [d for s, d in zip(srcs, dsts) if s == 0]\n assert set(F.asnumpy(g.successors(0)).tolist()) == set(succ)\n u, v = g.out_edges([0])\n assert F.asnumpy(u).tolist() == [0] * len(succ)\n assert set(F.asnumpy(v).tolist()) == set(succ)\n assert g.out_degrees(0) == len(succ)\n\n # edge_id & edge_ids\n for i, (src, dst) in enumerate(zip(srcs, dsts)):\n assert g.edge_ids(src, dst, etype=etype) == i\n _, _, eid = g.edge_ids(src, dst, etype=etype, return_uv=True)\n assert eid == i\n assert F.asnumpy(g.edge_ids(srcs, dsts)).tolist() == list(range(n_edges))\n u, v, e = g.edge_ids(srcs, dsts, return_uv=True)\n u, v, e = F.asnumpy(u), F.asnumpy(v), F.asnumpy(e)\n assert u[e].tolist() == srcs\n assert v[e].tolist() == dsts\n\n # find_edges\n u, v = g.find_edges(list(range(n_edges)))\n assert F.asnumpy(u).tolist() == srcs\n assert F.asnumpy(v).tolist() == dsts\n\n # all_edges.\n for order in ['eid']:\n u, v, e = g.all_edges(form='all', order=order)\n assert F.asnumpy(u).tolist() == srcs\n assert F.asnumpy(v).tolist() == dsts\n assert F.asnumpy(e).tolist() == list(range(n_edges))\n\n # in_degrees & out_degrees\n in_degrees = F.asnumpy(g.in_degrees())\n out_degrees = F.asnumpy(g.out_degrees())\n src_count = Counter(srcs)\n dst_count = Counter(dsts)\n for i in range(g.number_of_nodes(utype)):\n assert out_degrees[i] == src_count[i]\n for i in range(g.number_of_nodes(vtype)):\n assert in_degrees[i] == dst_count[i]\n\n edges = {\n 'follows': ([0, 1], [1, 2]),\n 'plays': ([0, 1, 2, 1], [0, 0, 1, 1]),\n 'wishes': ([0, 2], [1, 0]),\n 'develops': ([0, 1], [0, 1]),\n }\n # edges that does not exist in the graph\n negative_edges = {\n 'follows': ([0, 1], [0, 1]),\n 'plays': ([0, 2], [1, 0]),\n 'wishes': ([0, 1], [0, 1]),\n 'develops': ([0, 1], [1, 0]),\n }\n _test_query()\n etypes = canonical_etypes\n edges = {\n ('user', 'follows', 'user'): ([0, 1], [1, 2]),\n ('user', 'plays', 'game'): ([0, 1, 2, 1], [0, 0, 1, 1]),\n ('user', 'wishes', 'game'): ([0, 2], [1, 0]),\n ('developer', 'develops', 'game'): ([0, 1], [0, 1]),\n }\n # edges that does not exist in the graph\n negative_edges = {\n ('user', 'follows', 'user'): ([0, 1], [0, 1]),\n ('user', 'plays', 'game'): ([0, 2], [1, 0]),\n ('user', 'wishes', 'game'): ([0, 1], [0, 1]),\n ('developer', 'develops', 'game'): ([0, 1], [1, 0]),\n }\n _test_query()\n\n # test features\n HG.nodes['user'].data['h'] = F.ones((HG.number_of_nodes('user'), 5))\n HG.nodes['game'].data['m'] = F.ones((HG.number_of_nodes('game'), 3)) * 2\n\n # test only one node type\n g = HG['follows']\n assert g.number_of_nodes() == 3\n\n # test ndata and edata\n f1 = F.randn((3, 6))\n g.ndata['h'] = f1 # ok\n f2 = HG.nodes['user'].data['h']\n assert F.array_equal(f1, f2)\n assert F.array_equal(g.nodes(), F.arange(0, 3, g.idtype))\n\n f3 = F.randn((2, 4))\n g.edata['h'] = f3\n f4 = HG.edges['follows'].data['h']\n assert F.array_equal(f3, f4)\n assert F.array_equal(g.edges(form='eid'), F.arange(0, 2, g.idtype))\n\n@parametrize_dtype\ndef test_flatten(idtype):\n def check_mapping(g, fg):\n if len(fg.ntypes) == 1:\n SRC = DST = fg.ntypes[0]\n else:\n SRC = fg.ntypes[0]\n DST = fg.ntypes[1]\n\n etypes = F.asnumpy(fg.edata[dgl.ETYPE]).tolist()\n eids = F.asnumpy(fg.edata[dgl.EID]).tolist()\n\n for i, (etype, eid) in enumerate(zip(etypes, eids)):\n src_g, dst_g = g.find_edges([eid], g.canonical_etypes[etype])\n src_fg, dst_fg = fg.find_edges([i])\n # TODO(gq): I feel this code is quite redundant; can we just add new members (like\n # \"induced_srcid\") to returned heterograph object and not store them as features?\n assert F.asnumpy(src_g) == F.asnumpy(F.gather_row(fg.nodes[SRC].data[dgl.NID], src_fg)[0])\n tid = F.asnumpy(F.gather_row(fg.nodes[SRC].data[dgl.NTYPE], src_fg)).item()\n assert g.canonical_etypes[etype][0] == g.ntypes[tid]\n assert F.asnumpy(dst_g) == F.asnumpy(F.gather_row(fg.nodes[DST].data[dgl.NID], dst_fg)[0])\n tid = F.asnumpy(F.gather_row(fg.nodes[DST].data[dgl.NTYPE], dst_fg)).item()\n assert g.canonical_etypes[etype][2] == g.ntypes[tid]\n\n # check for wildcard slices\n g = create_test_heterograph(idtype)\n g.nodes['user'].data['h'] = F.ones((3, 5))\n g.nodes['game'].data['i'] = F.ones((2, 5))\n g.edges['plays'].data['e'] = F.ones((4, 4))\n g.edges['wishes'].data['e'] = F.ones((2, 4))\n g.edges['wishes'].data['f'] = F.ones((2, 4))\n\n fg = g['user', :, 'game'] # user--plays->game and user--wishes->game\n assert len(fg.ntypes) == 2\n assert fg.ntypes == ['user', 'game']\n assert fg.etypes == ['plays+wishes']\n assert fg.idtype == g.idtype\n assert fg.device == g.device\n etype = fg.etypes[0]\n assert fg[etype] is not None # Issue #2166\n\n assert F.array_equal(fg.nodes['user'].data['h'], F.ones((3, 5)))\n assert F.array_equal(fg.nodes['game'].data['i'], F.ones((2, 5)))\n assert F.array_equal(fg.edata['e'], F.ones((6, 4)))\n assert 'f' not in fg.edata\n\n etypes = F.asnumpy(fg.edata[dgl.ETYPE]).tolist()\n eids = F.asnumpy(fg.edata[dgl.EID]).tolist()\n assert set(zip(etypes, eids)) == set([(3, 0), (3, 1), (2, 1), (2, 0), (2, 3), (2, 2)])\n\n check_mapping(g, fg)\n\n fg = g['user', :, 'user']\n assert fg.idtype == g.idtype\n assert fg.device == g.device\n # NOTE(gq): The node/edge types from the parent graph is returned if there is only one\n # node/edge type. This differs from the behavior above.\n assert fg.ntypes == ['user']\n assert fg.etypes == ['follows']\n u1, v1 = g.edges(etype='follows', order='eid')\n u2, v2 = fg.edges(etype='follows', order='eid')\n assert F.array_equal(u1, u2)\n assert F.array_equal(v1, v2)\n\n fg = g['developer', :, 'game']\n assert fg.idtype == g.idtype\n assert fg.device == g.device\n assert fg.ntypes == ['developer', 'game']\n assert fg.etypes == ['develops']\n u1, v1 = g.edges(etype='develops', order='eid')\n u2, v2 = fg.edges(etype='develops', order='eid')\n assert F.array_equal(u1, u2)\n assert F.array_equal(v1, v2)\n\n fg = g[:, :, :]\n assert fg.idtype == g.idtype\n assert fg.device == g.device\n assert fg.ntypes == ['developer+user', 'game+user']\n assert fg.etypes == ['develops+follows+plays+wishes']\n check_mapping(g, fg)\n\n # Test another heterograph\n g = dgl.heterograph({\n ('user', 'follows', 'user'): ([0, 1, 2], [1, 2, 3]),\n ('user', 'knows', 'user'): ([0, 2], [2, 3])\n }, idtype=idtype, device=F.ctx())\n g.nodes['user'].data['h'] = F.randn((4, 3))\n g.edges['follows'].data['w'] = F.randn((3, 2))\n g.nodes['user'].data['hh'] = F.randn((4, 5))\n g.edges['knows'].data['ww'] = F.randn((2, 10))\n\n fg = g['user', :, 'user']\n assert fg.idtype == g.idtype\n assert fg.device == g.device\n assert fg.ntypes == ['user']\n assert fg.etypes == ['follows+knows']\n check_mapping(g, fg)\n\n fg = g['user', :, :]\n assert fg.idtype == g.idtype\n assert fg.device == g.device\n assert fg.ntypes == ['user']\n assert fg.etypes == ['follows+knows']\n check_mapping(g, fg)\n\[email protected](F._default_context_str == 'cpu', reason=\"Need gpu for this test\")\n@parametrize_dtype\ndef test_to_device(idtype):\n # TODO: rewrite this test case to accept different graphs so we\n # can test reverse graph and batched graph\n g = create_test_heterograph(idtype)\n g.nodes['user'].data['h'] = F.ones((3, 5))\n g.nodes['game'].data['i'] = F.ones((2, 5))\n g.edges['plays'].data['e'] = F.ones((4, 4))\n assert g.device == F.ctx()\n g = g.to(F.cpu())\n assert g.device == F.cpu()\n assert F.context(g.nodes['user'].data['h']) == F.cpu()\n assert F.context(g.nodes['game'].data['i']) == F.cpu()\n assert F.context(g.edges['plays'].data['e']) == F.cpu()\n for ntype in g.ntypes:\n assert F.context(g.batch_num_nodes(ntype)) == F.cpu()\n for etype in g.canonical_etypes:\n assert F.context(g.batch_num_edges(etype)) == F.cpu()\n\n if F.is_cuda_available():\n g1 = g.to(F.cuda())\n assert g1.device == F.cuda()\n assert F.context(g1.nodes['user'].data['h']) == F.cuda()\n assert F.context(g1.nodes['game'].data['i']) == F.cuda()\n assert F.context(g1.edges['plays'].data['e']) == F.cuda()\n for ntype in g1.ntypes:\n assert F.context(g1.batch_num_nodes(ntype)) == F.cuda()\n for etype in g1.canonical_etypes:\n assert F.context(g1.batch_num_edges(etype)) == F.cuda()\n assert F.context(g.nodes['user'].data['h']) == F.cpu()\n assert F.context(g.nodes['game'].data['i']) == F.cpu()\n assert F.context(g.edges['plays'].data['e']) == F.cpu()\n for ntype in g.ntypes:\n assert F.context(g.batch_num_nodes(ntype)) == F.cpu()\n for etype in g.canonical_etypes:\n assert F.context(g.batch_num_edges(etype)) == F.cpu()\n with pytest.raises(DGLError):\n g1.nodes['user'].data['h'] = F.copy_to(F.ones((3, 5)), F.cpu())\n with pytest.raises(DGLError):\n g1.edges['plays'].data['e'] = F.copy_to(F.ones((4, 4)), F.cpu())\n\[email protected](F._default_context_str == 'cpu', reason=\"Need gpu for this test\")\n@parametrize_dtype\[email protected]('g', get_cases(['block']))\ndef test_to_device2(g, idtype):\n g = g.astype(idtype)\n g = g.to(F.cpu())\n assert g.device == F.cpu()\n if F.is_cuda_available():\n g1 = g.to(F.cuda())\n assert g1.device == F.cuda()\n assert g1.ntypes == g.ntypes\n assert g1.etypes == g.etypes\n assert g1.canonical_etypes == g.canonical_etypes\n\n@parametrize_dtype\ndef test_convert_bound(idtype):\n def _test_bipartite_bound(data, card):\n with pytest.raises(DGLError):\n dgl.heterograph({\n ('_U', '_E', '_V'): data\n }, {'_U': card[0], '_V': card[1]}, idtype=idtype, device=F.ctx())\n\n def _test_graph_bound(data, card):\n with pytest.raises(DGLError):\n dgl.graph(data, num_nodes=card, idtype=idtype, device=F.ctx())\n\n _test_bipartite_bound(([1, 2], [1, 2]), (2, 3))\n _test_bipartite_bound(([0, 1], [1, 4]), (2, 3))\n _test_graph_bound(([1, 3], [1, 2]), 3)\n _test_graph_bound(([0, 1], [1, 3]), 3)\n\n\n@parametrize_dtype\ndef test_convert(idtype):\n hg = create_test_heterograph(idtype)\n hs = []\n for ntype in hg.ntypes:\n h = F.randn((hg.number_of_nodes(ntype), 5))\n hg.nodes[ntype].data['h'] = h\n hs.append(h)\n hg.nodes['user'].data['x'] = F.randn((3, 3))\n ws = []\n for etype in hg.canonical_etypes:\n w = F.randn((hg.number_of_edges(etype), 5))\n hg.edges[etype].data['w'] = w\n ws.append(w)\n hg.edges['plays'].data['x'] = F.randn((4, 3))\n\n g = dgl.to_homogeneous(hg, ndata=['h'], edata=['w'])\n assert g.idtype == idtype\n assert g.device == hg.device\n assert F.array_equal(F.cat(hs, dim=0), g.ndata['h'])\n assert 'x' not in g.ndata\n assert F.array_equal(F.cat(ws, dim=0), g.edata['w'])\n assert 'x' not in g.edata\n\n src, dst = g.all_edges(order='eid')\n src = F.asnumpy(src)\n dst = F.asnumpy(dst)\n etype_id, eid = F.asnumpy(g.edata[dgl.ETYPE]), F.asnumpy(g.edata[dgl.EID])\n ntype_id, nid = F.asnumpy(g.ndata[dgl.NTYPE]), F.asnumpy(g.ndata[dgl.NID])\n for i in range(g.number_of_edges()):\n srctype = hg.ntypes[ntype_id[src[i]]]\n dsttype = hg.ntypes[ntype_id[dst[i]]]\n etype = hg.etypes[etype_id[i]]\n src_i, dst_i = hg.find_edges([eid[i]], (srctype, etype, dsttype))\n assert np.asscalar(F.asnumpy(src_i)) == nid[src[i]]\n assert np.asscalar(F.asnumpy(dst_i)) == nid[dst[i]]\n\n mg = nx.MultiDiGraph([\n ('user', 'user', 'follows'),\n ('user', 'game', 'plays'),\n ('user', 'game', 'wishes'),\n ('developer', 'game', 'develops')])\n\n for _mg in [None, mg]:\n hg2 = dgl.to_heterogeneous(\n g, hg.ntypes, hg.etypes,\n ntype_field=dgl.NTYPE, etype_field=dgl.ETYPE, metagraph=_mg)\n assert hg2.idtype == hg.idtype\n assert hg2.device == hg.device\n assert set(hg.ntypes) == set(hg2.ntypes)\n assert set(hg.canonical_etypes) == set(hg2.canonical_etypes)\n for ntype in hg.ntypes:\n assert hg.number_of_nodes(ntype) == hg2.number_of_nodes(ntype)\n assert F.array_equal(hg.nodes[ntype].data['h'], hg2.nodes[ntype].data['h'])\n for canonical_etype in hg.canonical_etypes:\n src, dst = hg.all_edges(etype=canonical_etype, order='eid')\n src2, dst2 = hg2.all_edges(etype=canonical_etype, order='eid')\n assert F.array_equal(src, src2)\n assert F.array_equal(dst, dst2)\n assert F.array_equal(hg.edges[canonical_etype].data['w'], hg2.edges[canonical_etype].data['w'])\n\n # hetero_from_homo test case 2\n g = dgl.graph(([0, 1, 2, 0], [2, 2, 3, 3]), idtype=idtype, device=F.ctx())\n g.ndata[dgl.NTYPE] = F.tensor([0, 0, 1, 2])\n g.edata[dgl.ETYPE] = F.tensor([0, 0, 1, 2])\n hg = dgl.to_heterogeneous(g, ['l0', 'l1', 'l2'], ['e0', 'e1', 'e2'])\n assert hg.idtype == idtype\n assert hg.device == g.device\n assert set(hg.canonical_etypes) == set(\n [('l0', 'e0', 'l1'), ('l1', 'e1', 'l2'), ('l0', 'e2', 'l2')])\n assert hg.number_of_nodes('l0') == 2\n assert hg.number_of_nodes('l1') == 1\n assert hg.number_of_nodes('l2') == 1\n assert hg.number_of_edges('e0') == 2\n assert hg.number_of_edges('e1') == 1\n assert hg.number_of_edges('e2') == 1\n assert F.array_equal(hg.ndata[dgl.NID]['l0'], F.tensor([0, 1], F.int64))\n assert F.array_equal(hg.ndata[dgl.NID]['l1'], F.tensor([2], F.int64))\n assert F.array_equal(hg.ndata[dgl.NID]['l2'], F.tensor([3], F.int64))\n assert F.array_equal(hg.edata[dgl.EID][('l0', 'e0', 'l1')], F.tensor([0, 1], F.int64))\n assert F.array_equal(hg.edata[dgl.EID][('l0', 'e2', 'l2')], F.tensor([3], F.int64))\n assert F.array_equal(hg.edata[dgl.EID][('l1', 'e1', 'l2')], F.tensor([2], F.int64))\n\n # hetero_from_homo test case 3\n mg = nx.MultiDiGraph([\n ('user', 'movie', 'watches'),\n ('user', 'TV', 'watches')])\n g = dgl.graph(((0, 0), (1, 2)), idtype=idtype, device=F.ctx())\n g.ndata[dgl.NTYPE] = F.tensor([0, 1, 2])\n g.edata[dgl.ETYPE] = F.tensor([0, 0])\n for _mg in [None, mg]:\n hg = dgl.to_heterogeneous(g, ['user', 'TV', 'movie'], ['watches'], metagraph=_mg)\n assert hg.idtype == g.idtype\n assert hg.device == g.device\n assert set(hg.canonical_etypes) == set(\n [('user', 'watches', 'movie'), ('user', 'watches', 'TV')])\n assert hg.number_of_nodes('user') == 1\n assert hg.number_of_nodes('TV') == 1\n assert hg.number_of_nodes('movie') == 1\n assert hg.number_of_edges(('user', 'watches', 'TV')) == 1\n assert hg.number_of_edges(('user', 'watches', 'movie')) == 1\n assert len(hg.etypes) == 2\n\n # hetero_to_homo test case 2\n hg = dgl.heterograph({\n ('_U', '_E', '_V'): ([0, 1], [0, 1])\n }, {'_U': 2, '_V': 3}, idtype=idtype, device=F.ctx())\n g = dgl.to_homogeneous(hg)\n assert hg.idtype == g.idtype\n assert hg.device == g.device\n assert g.number_of_nodes() == 5\n\n@parametrize_dtype\ndef test_metagraph_reachable(idtype):\n g = create_test_heterograph(idtype)\n x = F.randn((3, 5))\n g.nodes['user'].data['h'] = x\n\n new_g = dgl.metapath_reachable_graph(g, ['follows', 'plays'])\n assert new_g.idtype == idtype\n assert new_g.ntypes == ['game', 'user']\n assert new_g.number_of_edges() == 3\n assert F.asnumpy(new_g.has_edges_between([0, 0, 1], [0, 1, 1])).all()\n\n new_g = dgl.metapath_reachable_graph(g, ['follows'])\n assert new_g.idtype == idtype\n assert new_g.ntypes == ['user']\n assert new_g.number_of_edges() == 2\n assert F.asnumpy(new_g.has_edges_between([0, 1], [1, 2])).all()\n\[email protected](dgl.backend.backend_name == \"mxnet\", reason=\"MXNet doesn't support bool tensor\")\n@parametrize_dtype\ndef test_subgraph_mask(idtype):\n g = create_test_heterograph(idtype)\n g_graph = g['follows']\n g_bipartite = g['plays']\n\n x = F.randn((3, 5))\n y = F.randn((2, 4))\n g.nodes['user'].data['h'] = x\n g.edges['follows'].data['h'] = y\n\n def _check_subgraph(g, sg):\n assert sg.idtype == g.idtype\n assert sg.device == g.device\n assert sg.ntypes == g.ntypes\n assert sg.etypes == g.etypes\n assert sg.canonical_etypes == g.canonical_etypes\n assert F.array_equal(F.tensor(sg.nodes['user'].data[dgl.NID]),\n F.tensor([1, 2], idtype))\n assert F.array_equal(F.tensor(sg.nodes['game'].data[dgl.NID]),\n F.tensor([0], idtype))\n assert F.array_equal(F.tensor(sg.edges['follows'].data[dgl.EID]),\n F.tensor([1], idtype))\n assert F.array_equal(F.tensor(sg.edges['plays'].data[dgl.EID]),\n F.tensor([1], idtype))\n assert F.array_equal(F.tensor(sg.edges['wishes'].data[dgl.EID]),\n F.tensor([1], idtype))\n assert sg.number_of_nodes('developer') == 0\n assert sg.number_of_edges('develops') == 0\n assert F.array_equal(sg.nodes['user'].data['h'], g.nodes['user'].data['h'][1:3])\n assert F.array_equal(sg.edges['follows'].data['h'], g.edges['follows'].data['h'][1:2])\n\n sg1 = g.subgraph({'user': F.tensor([False, True, True], dtype=F.bool),\n 'game': F.tensor([True, False, False, False], dtype=F.bool)})\n _check_subgraph(g, sg1)\n if F._default_context_str != 'gpu':\n # TODO(minjie): enable this later\n sg2 = g.edge_subgraph({'follows': F.tensor([False, True], dtype=F.bool),\n 'plays': F.tensor([False, True, False, False], dtype=F.bool),\n 'wishes': F.tensor([False, True], dtype=F.bool)})\n _check_subgraph(g, sg2)\n\n@parametrize_dtype\ndef test_subgraph(idtype):\n g = create_test_heterograph(idtype)\n g_graph = g['follows']\n g_bipartite = g['plays']\n\n x = F.randn((3, 5))\n y = F.randn((2, 4))\n g.nodes['user'].data['h'] = x\n g.edges['follows'].data['h'] = y\n\n def _check_subgraph(g, sg):\n assert sg.idtype == g.idtype\n assert sg.device == g.device\n assert sg.ntypes == g.ntypes\n assert sg.etypes == g.etypes\n assert sg.canonical_etypes == g.canonical_etypes\n assert F.array_equal(F.tensor(sg.nodes['user'].data[dgl.NID]),\n F.tensor([1, 2], g.idtype))\n assert F.array_equal(F.tensor(sg.nodes['game'].data[dgl.NID]),\n F.tensor([0], g.idtype))\n assert F.array_equal(F.tensor(sg.edges['follows'].data[dgl.EID]),\n F.tensor([1], g.idtype))\n assert F.array_equal(F.tensor(sg.edges['plays'].data[dgl.EID]),\n F.tensor([1], g.idtype))\n assert F.array_equal(F.tensor(sg.edges['wishes'].data[dgl.EID]),\n F.tensor([1], g.idtype))\n assert sg.number_of_nodes('developer') == 0\n assert sg.number_of_edges('develops') == 0\n assert F.array_equal(sg.nodes['user'].data['h'], g.nodes['user'].data['h'][1:3])\n assert F.array_equal(sg.edges['follows'].data['h'], g.edges['follows'].data['h'][1:2])\n\n sg1 = g.subgraph({'user': [1, 2], 'game': [0]})\n _check_subgraph(g, sg1)\n if F._default_context_str != 'gpu':\n # TODO(minjie): enable this later\n sg2 = g.edge_subgraph({'follows': [1], 'plays': [1], 'wishes': [1]})\n _check_subgraph(g, sg2)\n\n # backend tensor input\n sg1 = g.subgraph({'user': F.tensor([1, 2], dtype=idtype),\n 'game': F.tensor([0], dtype=idtype)})\n _check_subgraph(g, sg1)\n if F._default_context_str != 'gpu':\n # TODO(minjie): enable this later\n sg2 = g.edge_subgraph({'follows': F.tensor([1], dtype=idtype),\n 'plays': F.tensor([1], dtype=idtype),\n 'wishes': F.tensor([1], dtype=idtype)})\n _check_subgraph(g, sg2)\n\n # numpy input\n sg1 = g.subgraph({'user': np.array([1, 2]),\n 'game': np.array([0])})\n _check_subgraph(g, sg1)\n if F._default_context_str != 'gpu':\n # TODO(minjie): enable this later\n sg2 = g.edge_subgraph({'follows': np.array([1]),\n 'plays': np.array([1]),\n 'wishes': np.array([1])})\n _check_subgraph(g, sg2)\n\n def _check_subgraph_single_ntype(g, sg, preserve_nodes=False):\n assert sg.idtype == g.idtype\n assert sg.device == g.device\n assert sg.ntypes == g.ntypes\n assert sg.etypes == g.etypes\n assert sg.canonical_etypes == g.canonical_etypes\n\n if not preserve_nodes:\n assert F.array_equal(F.tensor(sg.nodes['user'].data[dgl.NID]),\n F.tensor([1, 2], g.idtype))\n else:\n for ntype in sg.ntypes:\n assert g.number_of_nodes(ntype) == sg.number_of_nodes(ntype)\n\n assert F.array_equal(F.tensor(sg.edges['follows'].data[dgl.EID]),\n F.tensor([1], g.idtype))\n\n if not preserve_nodes:\n assert F.array_equal(sg.nodes['user'].data['h'], g.nodes['user'].data['h'][1:3])\n assert F.array_equal(sg.edges['follows'].data['h'], g.edges['follows'].data['h'][1:2])\n\n def _check_subgraph_single_etype(g, sg, preserve_nodes=False):\n assert sg.ntypes == g.ntypes\n assert sg.etypes == g.etypes\n assert sg.canonical_etypes == g.canonical_etypes\n\n if not preserve_nodes:\n assert F.array_equal(F.tensor(sg.nodes['user'].data[dgl.NID]),\n F.tensor([0, 1], g.idtype))\n assert F.array_equal(F.tensor(sg.nodes['game'].data[dgl.NID]),\n F.tensor([0], g.idtype))\n else:\n for ntype in sg.ntypes:\n assert g.number_of_nodes(ntype) == sg.number_of_nodes(ntype)\n\n assert F.array_equal(F.tensor(sg.edges['plays'].data[dgl.EID]),\n F.tensor([0, 1], g.idtype))\n\n sg1_graph = g_graph.subgraph([1, 2])\n _check_subgraph_single_ntype(g_graph, sg1_graph)\n if F._default_context_str != 'gpu':\n # TODO(minjie): enable this later\n sg1_graph = g_graph.edge_subgraph([1])\n _check_subgraph_single_ntype(g_graph, sg1_graph)\n sg1_graph = g_graph.edge_subgraph([1], preserve_nodes=True)\n _check_subgraph_single_ntype(g_graph, sg1_graph, True)\n sg2_bipartite = g_bipartite.edge_subgraph([0, 1])\n _check_subgraph_single_etype(g_bipartite, sg2_bipartite)\n sg2_bipartite = g_bipartite.edge_subgraph([0, 1], preserve_nodes=True)\n _check_subgraph_single_etype(g_bipartite, sg2_bipartite, True)\n\n def _check_typed_subgraph1(g, sg):\n assert g.idtype == sg.idtype\n assert g.device == sg.device\n assert set(sg.ntypes) == {'user', 'game'}\n assert set(sg.etypes) == {'follows', 'plays', 'wishes'}\n for ntype in sg.ntypes:\n assert sg.number_of_nodes(ntype) == g.number_of_nodes(ntype)\n for etype in sg.etypes:\n src_sg, dst_sg = sg.all_edges(etype=etype, order='eid')\n src_g, dst_g = g.all_edges(etype=etype, order='eid')\n assert F.array_equal(src_sg, src_g)\n assert F.array_equal(dst_sg, dst_g)\n assert F.array_equal(sg.nodes['user'].data['h'], g.nodes['user'].data['h'])\n assert F.array_equal(sg.edges['follows'].data['h'], g.edges['follows'].data['h'])\n g.nodes['user'].data['h'] = F.scatter_row(g.nodes['user'].data['h'], F.tensor([2]), F.randn((1, 5)))\n g.edges['follows'].data['h'] = F.scatter_row(g.edges['follows'].data['h'], F.tensor([1]), F.randn((1, 4)))\n assert F.array_equal(sg.nodes['user'].data['h'], g.nodes['user'].data['h'])\n assert F.array_equal(sg.edges['follows'].data['h'], g.edges['follows'].data['h'])\n\n def _check_typed_subgraph2(g, sg):\n assert set(sg.ntypes) == {'developer', 'game'}\n assert set(sg.etypes) == {'develops'}\n for ntype in sg.ntypes:\n assert sg.number_of_nodes(ntype) == g.number_of_nodes(ntype)\n for etype in sg.etypes:\n src_sg, dst_sg = sg.all_edges(etype=etype, order='eid')\n src_g, dst_g = g.all_edges(etype=etype, order='eid')\n assert F.array_equal(src_sg, src_g)\n assert F.array_equal(dst_sg, dst_g)\n\n sg3 = g.node_type_subgraph(['user', 'game'])\n _check_typed_subgraph1(g, sg3)\n sg4 = g.edge_type_subgraph(['develops'])\n _check_typed_subgraph2(g, sg4)\n sg5 = g.edge_type_subgraph(['follows', 'plays', 'wishes'])\n _check_typed_subgraph1(g, sg5)\n\n@parametrize_dtype\ndef test_apply(idtype):\n def node_udf(nodes):\n return {'h': nodes.data['h'] * 2}\n def node_udf2(nodes):\n return {'h': F.sum(nodes.data['h'], dim=1, keepdims=True)}\n def edge_udf(edges):\n return {'h': edges.data['h'] * 2 + edges.src['h']}\n\n g = create_test_heterograph(idtype)\n g.nodes['user'].data['h'] = F.ones((3, 5))\n g.apply_nodes(node_udf, ntype='user')\n assert F.array_equal(g.nodes['user'].data['h'], F.ones((3, 5)) * 2)\n\n g['plays'].edata['h'] = F.ones((4, 5))\n g.apply_edges(edge_udf, etype=('user', 'plays', 'game'))\n assert F.array_equal(g['plays'].edata['h'], F.ones((4, 5)) * 4)\n\n # test apply on graph with only one type\n g['follows'].apply_nodes(node_udf)\n assert F.array_equal(g.nodes['user'].data['h'], F.ones((3, 5)) * 4)\n\n g['plays'].apply_edges(edge_udf)\n assert F.array_equal(g['plays'].edata['h'], F.ones((4, 5)) * 12)\n\n # Test the case that feature size changes\n g.nodes['user'].data['h'] = F.ones((3, 5))\n g.apply_nodes(node_udf2, ntype='user')\n assert F.array_equal(g.nodes['user'].data['h'], F.ones((3, 1)) * 5)\n\n # test fail case\n # fail due to multiple types\n with pytest.raises(DGLError):\n g.apply_nodes(node_udf)\n\n with pytest.raises(DGLError):\n g.apply_edges(edge_udf)\n\n@parametrize_dtype\ndef test_level2(idtype):\n #edges = {\n # 'follows': ([0, 1], [1, 2]),\n # 'plays': ([0, 1, 2, 1], [0, 0, 1, 1]),\n # 'wishes': ([0, 2], [1, 0]),\n # 'develops': ([0, 1], [0, 1]),\n #}\n g = create_test_heterograph(idtype)\n def rfunc(nodes):\n return {'y': F.sum(nodes.mailbox['m'], 1)}\n def rfunc2(nodes):\n return {'y': F.max(nodes.mailbox['m'], 1)}\n def mfunc(edges):\n return {'m': edges.src['h']}\n def afunc(nodes):\n return {'y' : nodes.data['y'] + 1}\n\n #############################################################\n # send_and_recv\n #############################################################\n\n g.nodes['user'].data['h'] = F.ones((3, 2))\n g.send_and_recv([2, 3], mfunc, rfunc, etype='plays')\n y = g.nodes['game'].data['y']\n assert F.array_equal(y, F.tensor([[0., 0.], [2., 2.]]))\n\n # only one type\n g['plays'].send_and_recv([2, 3], mfunc, rfunc)\n y = g.nodes['game'].data['y']\n assert F.array_equal(y, F.tensor([[0., 0.], [2., 2.]]))\n\n # test fail case\n # fail due to multiple types\n with pytest.raises(DGLError):\n g.send_and_recv([2, 3], mfunc, rfunc)\n\n g.nodes['game'].data.clear()\n\n #############################################################\n # pull\n #############################################################\n\n g.nodes['user'].data['h'] = F.ones((3, 2))\n g.pull(1, mfunc, rfunc, etype='plays')\n y = g.nodes['game'].data['y']\n assert F.array_equal(y, F.tensor([[0., 0.], [2., 2.]]))\n\n # only one type\n g['plays'].pull(1, mfunc, rfunc)\n y = g.nodes['game'].data['y']\n assert F.array_equal(y, F.tensor([[0., 0.], [2., 2.]]))\n\n # test fail case\n with pytest.raises(DGLError):\n g.pull(1, mfunc, rfunc)\n\n g.nodes['game'].data.clear()\n\n #############################################################\n # update_all\n #############################################################\n\n g.nodes['user'].data['h'] = F.ones((3, 2))\n g.update_all(mfunc, rfunc, etype='plays')\n y = g.nodes['game'].data['y']\n assert F.array_equal(y, F.tensor([[2., 2.], [2., 2.]]))\n\n # only one type\n g['plays'].update_all(mfunc, rfunc)\n y = g.nodes['game'].data['y']\n assert F.array_equal(y, F.tensor([[2., 2.], [2., 2.]]))\n\n # test fail case\n # fail due to multiple types\n with pytest.raises(DGLError):\n g.update_all(mfunc, rfunc)\n\n # test multi\n g.multi_update_all(\n {'plays' : (mfunc, rfunc),\n ('user', 'wishes', 'game'): (mfunc, rfunc2)},\n 'sum')\n assert F.array_equal(g.nodes['game'].data['y'], F.tensor([[3., 3.], [3., 3.]]))\n\n # test multi\n g.multi_update_all(\n {'plays' : (mfunc, rfunc, afunc),\n ('user', 'wishes', 'game'): (mfunc, rfunc2)},\n 'sum', afunc)\n assert F.array_equal(g.nodes['game'].data['y'], F.tensor([[5., 5.], [5., 5.]]))\n\n # test cross reducer\n g.nodes['user'].data['h'] = F.randn((3, 2))\n for cred in ['sum', 'max', 'min', 'mean', 'stack']:\n g.multi_update_all(\n {'plays' : (mfunc, rfunc, afunc),\n 'wishes': (mfunc, rfunc2)},\n cred, afunc)\n y = g.nodes['game'].data['y']\n g['plays'].update_all(mfunc, rfunc, afunc)\n y1 = g.nodes['game'].data['y']\n g['wishes'].update_all(mfunc, rfunc2)\n y2 = g.nodes['game'].data['y']\n if cred == 'stack':\n # stack has an internal order by edge type id\n yy = F.stack([y1, y2], 1)\n yy = yy + 1 # final afunc\n assert F.array_equal(y, yy)\n else:\n yy = get_redfn(cred)(F.stack([y1, y2], 0), 0)\n yy = yy + 1 # final afunc\n assert F.array_equal(y, yy)\n\n # test fail case\n # fail because cannot infer ntype\n with pytest.raises(DGLError):\n g.update_all(\n {'plays' : (mfunc, rfunc),\n 'follows': (mfunc, rfunc2)},\n 'sum')\n\n g.nodes['game'].data.clear()\n\n@parametrize_dtype\ndef test_updates(idtype):\n def msg_func(edges):\n return {'m': edges.src['h']}\n def reduce_func(nodes):\n return {'y': F.sum(nodes.mailbox['m'], 1)}\n def apply_func(nodes):\n return {'y': nodes.data['y'] * 2}\n g = create_test_heterograph(idtype)\n x = F.randn((3, 5))\n g.nodes['user'].data['h'] = x\n\n for msg, red, apply in itertools.product(\n [fn.copy_u('h', 'm'), msg_func], [fn.sum('m', 'y'), reduce_func],\n [None, apply_func]):\n multiplier = 1 if apply is None else 2\n\n g['user', 'plays', 'game'].update_all(msg, red, apply)\n y = g.nodes['game'].data['y']\n assert F.array_equal(y[0], (x[0] + x[1]) * multiplier)\n assert F.array_equal(y[1], (x[1] + x[2]) * multiplier)\n del g.nodes['game'].data['y']\n\n g['user', 'plays', 'game'].send_and_recv(([0, 1, 2], [0, 1, 1]), msg, red, apply)\n y = g.nodes['game'].data['y']\n assert F.array_equal(y[0], x[0] * multiplier)\n assert F.array_equal(y[1], (x[1] + x[2]) * multiplier)\n del g.nodes['game'].data['y']\n\n # pulls from destination (game) node 0\n g['user', 'plays', 'game'].pull(0, msg, red, apply)\n y = g.nodes['game'].data['y']\n assert F.array_equal(y[0], (x[0] + x[1]) * multiplier)\n del g.nodes['game'].data['y']\n\n # pushes from source (user) node 0\n g['user', 'plays', 'game'].push(0, msg, red, apply)\n y = g.nodes['game'].data['y']\n assert F.array_equal(y[0], x[0] * multiplier)\n del g.nodes['game'].data['y']\n\n\n@parametrize_dtype\ndef test_backward(idtype):\n g = create_test_heterograph(idtype)\n x = F.randn((3, 5))\n F.attach_grad(x)\n g.nodes['user'].data['h'] = x\n with F.record_grad():\n g.multi_update_all(\n {'plays' : (fn.copy_u('h', 'm'), fn.sum('m', 'y')),\n 'wishes': (fn.copy_u('h', 'm'), fn.sum('m', 'y'))},\n 'sum')\n y = g.nodes['game'].data['y']\n F.backward(y, F.ones(y.shape))\n print(F.grad(x))\n assert F.array_equal(F.grad(x), F.tensor([[2., 2., 2., 2., 2.],\n [2., 2., 2., 2., 2.],\n [2., 2., 2., 2., 2.]]))\n\n\n@parametrize_dtype\ndef test_empty_heterograph(idtype):\n def assert_empty(g):\n assert g.number_of_nodes('user') == 0\n assert g.number_of_edges('plays') == 0\n assert g.number_of_nodes('game') == 0\n\n # empty src-dst pair\n assert_empty(dgl.heterograph({('user', 'plays', 'game'): ([], [])}))\n\n g = dgl.heterograph({('user', 'follows', 'user'): ([], [])}, idtype=idtype, device=F.ctx())\n assert g.idtype == idtype\n assert g.device == F.ctx()\n assert g.number_of_nodes('user') == 0\n assert g.number_of_edges('follows') == 0\n\n # empty relation graph with others\n g = dgl.heterograph({('user', 'plays', 'game'): ([], []), ('developer', 'develops', 'game'):\n ([0, 1], [0, 1])}, idtype=idtype, device=F.ctx())\n assert g.idtype == idtype\n assert g.device == F.ctx()\n assert g.number_of_nodes('user') == 0\n assert g.number_of_edges('plays') == 0\n assert g.number_of_nodes('game') == 2\n assert g.number_of_edges('develops') == 2\n assert g.number_of_nodes('developer') == 2\n\n@parametrize_dtype\ndef test_types_in_function(idtype):\n def mfunc1(edges):\n assert edges.canonical_etype == ('user', 'follow', 'user')\n return {}\n\n def rfunc1(nodes):\n assert nodes.ntype == 'user'\n return {}\n\n def filter_nodes1(nodes):\n assert nodes.ntype == 'user'\n return F.zeros((3,))\n\n def filter_edges1(edges):\n assert edges.canonical_etype == ('user', 'follow', 'user')\n return F.zeros((2,))\n\n def mfunc2(edges):\n assert edges.canonical_etype == ('user', 'plays', 'game')\n return {}\n\n def rfunc2(nodes):\n assert nodes.ntype == 'game'\n return {}\n\n def filter_nodes2(nodes):\n assert nodes.ntype == 'game'\n return F.zeros((3,))\n\n def filter_edges2(edges):\n assert edges.canonical_etype == ('user', 'plays', 'game')\n return F.zeros((2,))\n\n g = dgl.heterograph({('user', 'follow', 'user'): ((0, 1), (1, 2))},\n idtype=idtype, device=F.ctx())\n g.apply_nodes(rfunc1)\n g.apply_edges(mfunc1)\n g.update_all(mfunc1, rfunc1)\n g.send_and_recv([0, 1], mfunc1, rfunc1)\n g.push([0], mfunc1, rfunc1)\n g.pull([1], mfunc1, rfunc1)\n g.filter_nodes(filter_nodes1)\n g.filter_edges(filter_edges1)\n\n g = dgl.heterograph({('user', 'plays', 'game'): ([0, 1], [1, 2])}, idtype=idtype, device=F.ctx())\n g.apply_nodes(rfunc2, ntype='game')\n g.apply_edges(mfunc2)\n g.update_all(mfunc2, rfunc2)\n g.send_and_recv([0, 1], mfunc2, rfunc2)\n g.push([0], mfunc2, rfunc2)\n g.pull([1], mfunc2, rfunc2)\n g.filter_nodes(filter_nodes2, ntype='game')\n g.filter_edges(filter_edges2)\n\n@parametrize_dtype\ndef test_stack_reduce(idtype):\n #edges = {\n # 'follows': ([0, 1], [1, 2]),\n # 'plays': ([0, 1, 2, 1], [0, 0, 1, 1]),\n # 'wishes': ([0, 2], [1, 0]),\n # 'develops': ([0, 1], [0, 1]),\n #}\n g = create_test_heterograph(idtype)\n g.nodes['user'].data['h'] = F.randn((3, 200))\n def rfunc(nodes):\n return {'y': F.sum(nodes.mailbox['m'], 1)}\n def rfunc2(nodes):\n return {'y': F.max(nodes.mailbox['m'], 1)}\n def mfunc(edges):\n return {'m': edges.src['h']}\n g.multi_update_all(\n {'plays' : (mfunc, rfunc),\n 'wishes': (mfunc, rfunc2)},\n 'stack')\n assert g.nodes['game'].data['y'].shape == (g.number_of_nodes('game'), 2, 200)\n # only one type-wise update_all, stack still adds one dimension\n g.multi_update_all(\n {'plays' : (mfunc, rfunc)},\n 'stack')\n assert g.nodes['game'].data['y'].shape == (g.number_of_nodes('game'), 1, 200)\n\n@parametrize_dtype\ndef test_isolated_ntype(idtype):\n g = dgl.heterograph({\n ('A', 'AB', 'B'): ([0, 1, 2], [1, 2, 3])},\n num_nodes_dict={'A': 3, 'B': 4, 'C': 4},\n idtype=idtype, device=F.ctx())\n assert g.number_of_nodes('A') == 3\n assert g.number_of_nodes('B') == 4\n assert g.number_of_nodes('C') == 4\n\n g = dgl.heterograph({\n ('A', 'AC', 'C'): ([0, 1, 2], [1, 2, 3])},\n num_nodes_dict={'A': 3, 'B': 4, 'C': 4},\n idtype=idtype, device=F.ctx())\n assert g.number_of_nodes('A') == 3\n assert g.number_of_nodes('B') == 4\n assert g.number_of_nodes('C') == 4\n\n G = dgl.graph(([0, 1, 2], [4, 5, 6]), num_nodes=11, idtype=idtype, device=F.ctx())\n G.ndata[dgl.NTYPE] = F.tensor([0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2], dtype=F.int64)\n G.edata[dgl.ETYPE] = F.tensor([0, 0, 0], dtype=F.int64)\n g = dgl.to_heterogeneous(G, ['A', 'B', 'C'], ['AB'])\n assert g.number_of_nodes('A') == 3\n assert g.number_of_nodes('B') == 4\n assert g.number_of_nodes('C') == 4\n\n\n@parametrize_dtype\ndef test_ismultigraph(idtype):\n g1 = dgl.heterograph({('A', 'AB', 'B'): ([0, 0, 1, 2], [1, 2, 5, 5])},\n {'A': 6, 'B': 6}, idtype=idtype, device=F.ctx())\n assert g1.is_multigraph == False\n g2 = dgl.heterograph({('A', 'AC', 'C'): ([0, 0, 0, 1], [1, 1, 2, 5])},\n {'A': 6, 'C': 6}, idtype=idtype, device=F.ctx())\n assert g2.is_multigraph == True\n g3 = dgl.graph(((0, 1), (1, 2)), num_nodes=6, idtype=idtype, device=F.ctx())\n assert g3.is_multigraph == False\n g4 = dgl.graph(([0, 0, 1], [1, 1, 2]), num_nodes=6, idtype=idtype, device=F.ctx())\n assert g4.is_multigraph == True\n g = dgl.heterograph({\n ('A', 'AB', 'B'): ([0, 0, 1, 2], [1, 2, 5, 5]),\n ('A', 'AA', 'A'): ([0, 1], [1, 2])},\n {'A': 6, 'B': 6}, idtype=idtype, device=F.ctx())\n assert g.is_multigraph == False\n g = dgl.heterograph({\n ('A', 'AB', 'B'): ([0, 0, 1, 2], [1, 2, 5, 5]),\n ('A', 'AC', 'C'): ([0, 0, 0, 1], [1, 1, 2, 5])},\n {'A': 6, 'B': 6, 'C': 6}, idtype=idtype, device=F.ctx())\n assert g.is_multigraph == True\n g = dgl.heterograph({\n ('A', 'AB', 'B'): ([0, 0, 1, 2], [1, 2, 5, 5]),\n ('A', 'AA', 'A'): ([0, 0, 1], [1, 1, 2])},\n {'A': 6, 'B': 6}, idtype=idtype, device=F.ctx())\n assert g.is_multigraph == True\n g = dgl.heterograph({\n ('A', 'AC', 'C'): ([0, 0, 0, 1], [1, 1, 2, 5]),\n ('A', 'AA', 'A'): ([0, 1], [1, 2])},\n {'A': 6, 'C': 6}, idtype=idtype, device=F.ctx())\n assert g.is_multigraph == True\n\n@parametrize_dtype\ndef test_bipartite(idtype):\n g1 = dgl.heterograph({('A', 'AB', 'B'): ([0, 0, 1], [1, 2, 5])},\n idtype=idtype, device=F.ctx())\n assert g1.is_unibipartite\n assert len(g1.ntypes) == 2\n assert g1.etypes == ['AB']\n assert g1.srctypes == ['A']\n assert g1.dsttypes == ['B']\n assert g1.number_of_nodes('A') == 2\n assert g1.number_of_nodes('B') == 6\n assert g1.number_of_src_nodes('A') == 2\n assert g1.number_of_src_nodes() == 2\n assert g1.number_of_dst_nodes('B') == 6\n assert g1.number_of_dst_nodes() == 6\n assert g1.number_of_edges() == 3\n g1.srcdata['h'] = F.randn((2, 5))\n assert F.array_equal(g1.srcnodes['A'].data['h'], g1.srcdata['h'])\n assert F.array_equal(g1.nodes['A'].data['h'], g1.srcdata['h'])\n assert F.array_equal(g1.nodes['SRC/A'].data['h'], g1.srcdata['h'])\n g1.dstdata['h'] = F.randn((6, 3))\n assert F.array_equal(g1.dstnodes['B'].data['h'], g1.dstdata['h'])\n assert F.array_equal(g1.nodes['B'].data['h'], g1.dstdata['h'])\n assert F.array_equal(g1.nodes['DST/B'].data['h'], g1.dstdata['h'])\n\n # more complicated bipartite\n g2 = dgl.heterograph({\n ('A', 'AB', 'B'): ([0, 0, 1], [1, 2, 5]),\n ('A', 'AC', 'C'): ([1, 0], [0, 0])\n }, idtype=idtype, device=F.ctx())\n\n assert g2.is_unibipartite\n assert g2.srctypes == ['A']\n assert set(g2.dsttypes) == {'B', 'C'}\n assert g2.number_of_nodes('A') == 2\n assert g2.number_of_nodes('B') == 6\n assert g2.number_of_nodes('C') == 1\n assert g2.number_of_src_nodes('A') == 2\n assert g2.number_of_src_nodes() == 2\n assert g2.number_of_dst_nodes('B') == 6\n assert g2.number_of_dst_nodes('C') == 1\n g2.srcdata['h'] = F.randn((2, 5))\n assert F.array_equal(g2.srcnodes['A'].data['h'], g2.srcdata['h'])\n assert F.array_equal(g2.nodes['A'].data['h'], g2.srcdata['h'])\n assert F.array_equal(g2.nodes['SRC/A'].data['h'], g2.srcdata['h'])\n\n g3 = dgl.heterograph({\n ('A', 'AB', 'B'): ([0, 0, 1], [1, 2, 5]),\n ('A', 'AC', 'C'): ([1, 0], [0, 0]),\n ('A', 'AA', 'A'): ([0, 1], [0, 1])\n }, idtype=idtype, device=F.ctx())\n assert not g3.is_unibipartite\n\n g4 = dgl.heterograph({\n ('A', 'AB', 'B'): ([0, 0, 1], [1, 2, 5]),\n ('C', 'CA', 'A'): ([1, 0], [0, 0])\n }, idtype=idtype, device=F.ctx())\n\n assert not g4.is_unibipartite\n\n@parametrize_dtype\ndef test_dtype_cast(idtype):\n g = dgl.graph(([0, 1, 0, 2], [0, 1, 1, 0]), idtype=idtype, device=F.ctx())\n assert g.idtype == idtype\n g.ndata[\"feat\"] = F.tensor([3, 4, 5])\n g.edata[\"h\"] = F.tensor([3, 4, 5, 6])\n if idtype == \"int32\":\n g_cast = g.long()\n assert g_cast.idtype == F.int64\n else:\n g_cast = g.int()\n assert g_cast.idtype == F.int32\n test_utils.check_graph_equal(g, g_cast, check_idtype=False)\n\n@parametrize_dtype\ndef test_format(idtype):\n # single relation\n g = dgl.graph(([0, 1, 0, 2], [0, 1, 1, 0]), idtype=idtype, device=F.ctx())\n assert g.formats()['created'] == ['coo']\n g1 = g.formats(['coo', 'csr', 'csc'])\n assert len(g1.formats()['created']) + len(g1.formats()['not created']) == 3\n g1.create_formats_()\n assert len(g1.formats()['created']) == 3\n assert g.formats()['created'] == ['coo']\n\n # multiple relation\n g = dgl.heterograph({\n ('user', 'follows', 'user'): ([0, 1], [1, 2]),\n ('user', 'plays', 'game'): ([0, 1, 1, 2], [0, 0, 1, 1]),\n ('developer', 'develops', 'game'): ([0, 1], [0, 1])\n }, idtype=idtype, device=F.ctx())\n user_feat = F.randn((g['follows'].number_of_src_nodes(), 5))\n g['follows'].srcdata['h'] = user_feat\n g1 = g.formats('csc')\n # test frame\n assert F.array_equal(g1['follows'].srcdata['h'], user_feat)\n # test each relation graph\n assert g1.formats()['created'] == ['csc']\n assert len(g1.formats()['not created']) == 0\n\n@parametrize_dtype\ndef test_edges_order(idtype):\n # (0, 2), (1, 2), (0, 1), (0, 1), (2, 1)\n g = dgl.graph((\n np.array([0, 1, 0, 0, 2]),\n np.array([2, 2, 1, 1, 1])\n ), idtype=idtype, device=F.ctx())\n\n print(g.formats())\n src, dst = g.all_edges(order='srcdst')\n assert F.array_equal(src, F.tensor([0, 0, 0, 1, 2], dtype=idtype))\n assert F.array_equal(dst, F.tensor([1, 1, 2, 2, 1], dtype=idtype))\n\n@parametrize_dtype\ndef test_reverse(idtype):\n g = dgl.heterograph({\n ('user', 'follows', 'user'): ([0, 1, 2, 4, 3 ,1, 3], [1, 2, 3, 2, 0, 0, 1]),\n }, idtype=idtype, device=F.ctx())\n gidx = g._graph\n r_gidx = gidx.reverse()\n\n assert gidx.number_of_nodes(0) == r_gidx.number_of_nodes(0)\n assert gidx.number_of_edges(0) == r_gidx.number_of_edges(0)\n g_s, g_d, _ = gidx.edges(0)\n rg_s, rg_d, _ = r_gidx.edges(0)\n assert F.array_equal(g_s, rg_d)\n assert F.array_equal(g_d, rg_s)\n\n # force to start with 'csr'\n gidx = gidx.formats('csr')\n gidx = gidx.formats(['coo', 'csr', 'csc'])\n r_gidx = gidx.reverse()\n assert 'csr' in gidx.formats()['created']\n assert 'csc' in r_gidx.formats()['created']\n assert gidx.number_of_nodes(0) == r_gidx.number_of_nodes(0)\n assert gidx.number_of_edges(0) == r_gidx.number_of_edges(0)\n g_s, g_d, _ = gidx.edges(0)\n rg_s, rg_d, _ = r_gidx.edges(0)\n assert F.array_equal(g_s, rg_d)\n assert F.array_equal(g_d, rg_s)\n\n # force to start with 'csc'\n gidx = gidx.formats('csc')\n gidx = gidx.formats(['coo', 'csr', 'csc'])\n r_gidx = gidx.reverse()\n assert 'csc' in gidx.formats()['created']\n assert 'csr' in r_gidx.formats()['created']\n assert gidx.number_of_nodes(0) == r_gidx.number_of_nodes(0)\n assert gidx.number_of_edges(0) == r_gidx.number_of_edges(0)\n g_s, g_d, _ = gidx.edges(0)\n rg_s, rg_d, _ = r_gidx.edges(0)\n assert F.array_equal(g_s, rg_d)\n assert F.array_equal(g_d, rg_s)\n\n g = dgl.heterograph({\n ('user', 'follows', 'user'): ([0, 1, 2, 4, 3 ,1, 3], [1, 2, 3, 2, 0, 0, 1]),\n ('user', 'plays', 'game'): ([0, 0, 2, 3, 3, 4, 1], [1, 0, 1, 0, 1, 0, 0]),\n ('developer', 'develops', 'game'): ([0, 1, 1, 2], [0, 0, 1, 1]),\n }, idtype=idtype, device=F.ctx())\n gidx = g._graph\n r_gidx = gidx.reverse()\n\n # metagraph\n mg = gidx.metagraph\n r_mg = r_gidx.metagraph\n for etype in range(3):\n assert mg.find_edge(etype) == r_mg.find_edge(etype)[::-1]\n\n # three node types and three edge types\n assert gidx.number_of_nodes(0) == r_gidx.number_of_nodes(0)\n assert gidx.number_of_nodes(1) == r_gidx.number_of_nodes(1)\n assert gidx.number_of_nodes(2) == r_gidx.number_of_nodes(2)\n assert gidx.number_of_edges(0) == r_gidx.number_of_edges(0)\n assert gidx.number_of_edges(1) == r_gidx.number_of_edges(1)\n assert gidx.number_of_edges(2) == r_gidx.number_of_edges(2)\n g_s, g_d, _ = gidx.edges(0)\n rg_s, rg_d, _ = r_gidx.edges(0)\n assert F.array_equal(g_s, rg_d)\n assert F.array_equal(g_d, rg_s)\n g_s, g_d, _ = gidx.edges(1)\n rg_s, rg_d, _ = r_gidx.edges(1)\n assert F.array_equal(g_s, rg_d)\n assert F.array_equal(g_d, rg_s)\n g_s, g_d, _ = gidx.edges(2)\n rg_s, rg_d, _ = r_gidx.edges(2)\n assert F.array_equal(g_s, rg_d)\n assert F.array_equal(g_d, rg_s)\n\n # force to start with 'csr'\n gidx = gidx.formats('csr')\n gidx = gidx.formats(['coo', 'csr', 'csc'])\n r_gidx = gidx.reverse()\n # three node types and three edge types\n assert 'csr' in gidx.formats()['created']\n assert 'csc' in r_gidx.formats()['created']\n assert gidx.number_of_nodes(0) == r_gidx.number_of_nodes(0)\n assert gidx.number_of_nodes(1) == r_gidx.number_of_nodes(1)\n assert gidx.number_of_nodes(2) == r_gidx.number_of_nodes(2)\n assert gidx.number_of_edges(0) == r_gidx.number_of_edges(0)\n assert gidx.number_of_edges(1) == r_gidx.number_of_edges(1)\n assert gidx.number_of_edges(2) == r_gidx.number_of_edges(2)\n g_s, g_d, _ = gidx.edges(0)\n rg_s, rg_d, _ = r_gidx.edges(0)\n assert F.array_equal(g_s, rg_d)\n assert F.array_equal(g_d, rg_s)\n g_s, g_d, _ = gidx.edges(1)\n rg_s, rg_d, _ = r_gidx.edges(1)\n assert F.array_equal(g_s, rg_d)\n assert F.array_equal(g_d, rg_s)\n g_s, g_d, _ = gidx.edges(2)\n rg_s, rg_d, _ = r_gidx.edges(2)\n assert F.array_equal(g_s, rg_d)\n assert F.array_equal(g_d, rg_s)\n\n # force to start with 'csc'\n gidx = gidx.formats('csc')\n gidx = gidx.formats(['coo', 'csr', 'csc'])\n r_gidx = gidx.reverse()\n # three node types and three edge types\n assert 'csc' in gidx.formats()['created']\n assert 'csr' in r_gidx.formats()['created']\n assert gidx.number_of_nodes(0) == r_gidx.number_of_nodes(0)\n assert gidx.number_of_nodes(1) == r_gidx.number_of_nodes(1)\n assert gidx.number_of_nodes(2) == r_gidx.number_of_nodes(2)\n assert gidx.number_of_edges(0) == r_gidx.number_of_edges(0)\n assert gidx.number_of_edges(1) == r_gidx.number_of_edges(1)\n assert gidx.number_of_edges(2) == r_gidx.number_of_edges(2)\n g_s, g_d, _ = gidx.edges(0)\n rg_s, rg_d, _ = r_gidx.edges(0)\n assert F.array_equal(g_s, rg_d)\n assert F.array_equal(g_d, rg_s)\n g_s, g_d, _ = gidx.edges(1)\n rg_s, rg_d, _ = r_gidx.edges(1)\n assert F.array_equal(g_s, rg_d)\n assert F.array_equal(g_d, rg_s)\n g_s, g_d, _ = gidx.edges(2)\n rg_s, rg_d, _ = r_gidx.edges(2)\n assert F.array_equal(g_s, rg_d)\n assert F.array_equal(g_d, rg_s)\n\n@parametrize_dtype\ndef test_clone(idtype):\n g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())\n g.ndata['h'] = F.copy_to(F.tensor([1, 1, 1], dtype=idtype), ctx=F.ctx())\n g.edata['h'] = F.copy_to(F.tensor([1, 1], dtype=idtype), ctx=F.ctx())\n\n new_g = g.clone()\n assert g.number_of_nodes() == new_g.number_of_nodes()\n assert g.number_of_edges() == new_g.number_of_edges()\n assert g.device == new_g.device\n assert g.idtype == new_g.idtype\n assert F.array_equal(g.ndata['h'], new_g.ndata['h'])\n assert F.array_equal(g.edata['h'], new_g.edata['h'])\n # data change\n new_g.ndata['h'] = F.copy_to(F.tensor([2, 2, 2], dtype=idtype), ctx=F.ctx())\n assert (F.array_equal(g.ndata['h'], new_g.ndata['h']) == False)\n g.edata['h'] = F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx())\n assert (F.array_equal(g.edata['h'], new_g.edata['h']) == False)\n # graph structure change\n g.add_nodes(1)\n assert g.number_of_nodes() != new_g.number_of_nodes()\n new_g.add_edges(1, 1)\n assert g.number_of_edges() != new_g.number_of_edges()\n\n # zero data graph\n g = dgl.graph(([], []), num_nodes=0, idtype=idtype, device=F.ctx())\n new_g = g.clone()\n assert g.number_of_nodes() == new_g.number_of_nodes()\n assert g.number_of_edges() == new_g.number_of_edges()\n\n # heterograph\n g = create_test_heterograph3(idtype)\n g.edges['plays'].data['h'] = F.copy_to(F.tensor([1, 2, 3, 4], dtype=idtype), ctx=F.ctx())\n new_g = g.clone()\n assert g.number_of_nodes('user') == new_g.number_of_nodes('user')\n assert g.number_of_nodes('game') == new_g.number_of_nodes('game')\n assert g.number_of_nodes('developer') == new_g.number_of_nodes('developer')\n assert g.number_of_edges('plays') == new_g.number_of_edges('plays')\n assert g.number_of_edges('develops') == new_g.number_of_edges('develops')\n assert F.array_equal(g.nodes['user'].data['h'], new_g.nodes['user'].data['h'])\n assert F.array_equal(g.nodes['game'].data['h'], new_g.nodes['game'].data['h'])\n assert F.array_equal(g.edges['plays'].data['h'], new_g.edges['plays'].data['h'])\n assert g.device == new_g.device\n assert g.idtype == new_g.idtype\n u, v = g.edges(form='uv', order='eid', etype='plays')\n nu, nv = new_g.edges(form='uv', order='eid', etype='plays')\n assert F.array_equal(u, nu)\n assert F.array_equal(v, nv)\n # graph structure change\n u = F.tensor([0, 4], dtype=idtype)\n v = F.tensor([2, 6], dtype=idtype)\n g.add_edges(u, v, etype='plays')\n u, v = g.edges(form='uv', order='eid', etype='plays')\n assert u.shape[0] != nu.shape[0]\n assert v.shape[0] != nv.shape[0]\n assert g.nodes['user'].data['h'].shape[0] != new_g.nodes['user'].data['h'].shape[0]\n assert g.nodes['game'].data['h'].shape[0] != new_g.nodes['game'].data['h'].shape[0]\n assert g.edges['plays'].data['h'].shape[0] != new_g.edges['plays'].data['h'].shape[0]\n\n\n@parametrize_dtype\ndef test_add_edges(idtype):\n # homogeneous graph\n g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())\n u = 0\n v = 1\n g.add_edges(u, v)\n assert g.device == F.ctx()\n assert g.number_of_nodes() == 3\n assert g.number_of_edges() == 3\n u = [0]\n v = [1]\n g.add_edges(u, v)\n assert g.device == F.ctx()\n assert g.number_of_nodes() == 3\n assert g.number_of_edges() == 4\n u = F.tensor(u, dtype=idtype)\n v = F.tensor(v, dtype=idtype)\n g.add_edges(u, v)\n assert g.device == F.ctx()\n assert g.number_of_nodes() == 3\n assert g.number_of_edges() == 5\n u, v = g.edges(form='uv', order='eid')\n assert F.array_equal(u, F.tensor([0, 1, 0, 0, 0], dtype=idtype))\n assert F.array_equal(v, F.tensor([1, 2, 1, 1, 1], dtype=idtype))\n\n # node id larger than current max node id\n g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())\n u = F.tensor([0, 1], dtype=idtype)\n v = F.tensor([2, 3], dtype=idtype)\n g.add_edges(u, v)\n assert g.number_of_nodes() == 4\n assert g.number_of_edges() == 4\n u, v = g.edges(form='uv', order='eid')\n assert F.array_equal(u, F.tensor([0, 1, 0, 1], dtype=idtype))\n assert F.array_equal(v, F.tensor([1, 2, 2, 3], dtype=idtype))\n\n # has data\n g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())\n g.ndata['h'] = F.copy_to(F.tensor([1, 1, 1], dtype=idtype), ctx=F.ctx())\n g.edata['h'] = F.copy_to(F.tensor([1, 1], dtype=idtype), ctx=F.ctx())\n u = F.tensor([0, 1], dtype=idtype)\n v = F.tensor([2, 3], dtype=idtype)\n e_feat = {'h' : F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx()),\n 'hh' : F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx())}\n g.add_edges(u, v, e_feat)\n assert g.number_of_nodes() == 4\n assert g.number_of_edges() == 4\n u, v = g.edges(form='uv', order='eid')\n assert F.array_equal(u, F.tensor([0, 1, 0, 1], dtype=idtype))\n assert F.array_equal(v, F.tensor([1, 2, 2, 3], dtype=idtype))\n assert F.array_equal(g.ndata['h'], F.tensor([1, 1, 1, 0], dtype=idtype))\n assert F.array_equal(g.edata['h'], F.tensor([1, 1, 2, 2], dtype=idtype))\n assert F.array_equal(g.edata['hh'], F.tensor([0, 0, 2, 2], dtype=idtype))\n\n # zero data graph\n g = dgl.graph(([], []), num_nodes=0, idtype=idtype, device=F.ctx())\n u = F.tensor([0, 1], dtype=idtype)\n v = F.tensor([2, 2], dtype=idtype)\n e_feat = {'h' : F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx()),\n 'hh' : F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx())}\n g.add_edges(u, v, e_feat)\n assert g.number_of_nodes() == 3\n assert g.number_of_edges() == 2\n u, v = g.edges(form='uv', order='eid')\n assert F.array_equal(u, F.tensor([0, 1], dtype=idtype))\n assert F.array_equal(v, F.tensor([2, 2], dtype=idtype))\n assert F.array_equal(g.edata['h'], F.tensor([2, 2], dtype=idtype))\n assert F.array_equal(g.edata['hh'], F.tensor([2, 2], dtype=idtype))\n\n # bipartite graph\n g = dgl.heterograph({('user', 'plays', 'game'): ([0, 1], [1, 2])},\n idtype=idtype, device=F.ctx())\n u = 0\n v = 1\n g.add_edges(u, v)\n assert g.device == F.ctx()\n assert g.number_of_nodes('user') == 2\n assert g.number_of_nodes('game') == 3\n assert g.number_of_edges() == 3\n u = [0]\n v = [1]\n g.add_edges(u, v)\n assert g.device == F.ctx()\n assert g.number_of_nodes('user') == 2\n assert g.number_of_nodes('game') == 3\n assert g.number_of_edges() == 4\n u = F.tensor(u, dtype=idtype)\n v = F.tensor(v, dtype=idtype)\n g.add_edges(u, v)\n assert g.device == F.ctx()\n assert g.number_of_nodes('user') == 2\n assert g.number_of_nodes('game') == 3\n assert g.number_of_edges() == 5\n u, v = g.edges(form='uv')\n assert F.array_equal(u, F.tensor([0, 1, 0, 0, 0], dtype=idtype))\n assert F.array_equal(v, F.tensor([1, 2, 1, 1, 1], dtype=idtype))\n\n # node id larger than current max node id\n g = dgl.heterograph({('user', 'plays', 'game'): ([0, 1], [1, 2])},\n idtype=idtype, device=F.ctx())\n u = F.tensor([0, 2], dtype=idtype)\n v = F.tensor([2, 3], dtype=idtype)\n g.add_edges(u, v)\n assert g.device == F.ctx()\n assert g.number_of_nodes('user') == 3\n assert g.number_of_nodes('game') == 4\n assert g.number_of_edges() == 4\n u, v = g.edges(form='uv', order='eid')\n assert F.array_equal(u, F.tensor([0, 1, 0, 2], dtype=idtype))\n assert F.array_equal(v, F.tensor([1, 2, 2, 3], dtype=idtype))\n\n # has data\n g = dgl.heterograph({\n ('user', 'plays', 'game'): ([0, 1], [1, 2])\n }, idtype=idtype, device=F.ctx())\n g.nodes['user'].data['h'] = F.copy_to(F.tensor([1, 1], dtype=idtype), ctx=F.ctx())\n g.nodes['game'].data['h'] = F.copy_to(F.tensor([2, 2, 2], dtype=idtype), ctx=F.ctx())\n g.edata['h'] = F.copy_to(F.tensor([1, 1], dtype=idtype), ctx=F.ctx())\n u = F.tensor([0, 2], dtype=idtype)\n v = F.tensor([2, 3], dtype=idtype)\n e_feat = {'h' : F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx()),\n 'hh' : F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx())}\n g.add_edges(u, v, e_feat)\n assert g.number_of_nodes('user') == 3\n assert g.number_of_nodes('game') == 4\n assert g.number_of_edges() == 4\n u, v = g.edges(form='uv', order='eid')\n assert F.array_equal(u, F.tensor([0, 1, 0, 2], dtype=idtype))\n assert F.array_equal(v, F.tensor([1, 2, 2, 3], dtype=idtype))\n assert F.array_equal(g.nodes['user'].data['h'], F.tensor([1, 1, 0], dtype=idtype))\n assert F.array_equal(g.nodes['game'].data['h'], F.tensor([2, 2, 2, 0], dtype=idtype))\n assert F.array_equal(g.edata['h'], F.tensor([1, 1, 2, 2], dtype=idtype))\n assert F.array_equal(g.edata['hh'], F.tensor([0, 0, 2, 2], dtype=idtype))\n\n # heterogeneous graph\n g = create_test_heterograph3(idtype)\n u = F.tensor([0, 2], dtype=idtype)\n v = F.tensor([2, 3], dtype=idtype)\n g.add_edges(u, v, etype='plays')\n assert g.number_of_nodes('user') == 3\n assert g.number_of_nodes('game') == 4\n assert g.number_of_nodes('developer') == 2\n assert g.number_of_edges('plays') == 6\n assert g.number_of_edges('develops') == 2\n u, v = g.edges(form='uv', order='eid', etype='plays')\n assert F.array_equal(u, F.tensor([0, 1, 1, 2, 0, 2], dtype=idtype))\n assert F.array_equal(v, F.tensor([0, 0, 1, 1, 2, 3], dtype=idtype))\n assert F.array_equal(g.nodes['user'].data['h'], F.tensor([1, 1, 1], dtype=idtype))\n assert F.array_equal(g.nodes['game'].data['h'], F.tensor([2, 2, 0, 0], dtype=idtype))\n assert F.array_equal(g.edges['plays'].data['h'], F.tensor([1, 1, 1, 1, 0, 0], dtype=idtype))\n\n # add with feature\n e_feat = {'h': F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx())}\n u = F.tensor([0, 2], dtype=idtype)\n v = F.tensor([2, 3], dtype=idtype)\n g.nodes['game'].data['h'] = F.copy_to(F.tensor([2, 2, 1, 1], dtype=idtype), ctx=F.ctx())\n g.add_edges(u, v, data=e_feat, etype='develops')\n assert g.number_of_nodes('user') == 3\n assert g.number_of_nodes('game') == 4\n assert g.number_of_nodes('developer') == 3\n assert g.number_of_edges('plays') == 6\n assert g.number_of_edges('develops') == 4\n u, v = g.edges(form='uv', order='eid', etype='develops')\n assert F.array_equal(u, F.tensor([0, 1, 0, 2], dtype=idtype))\n assert F.array_equal(v, F.tensor([0, 1, 2, 3], dtype=idtype))\n assert F.array_equal(g.nodes['developer'].data['h'], F.tensor([3, 3, 0], dtype=idtype))\n assert F.array_equal(g.nodes['game'].data['h'], F.tensor([2, 2, 1, 1], dtype=idtype))\n assert F.array_equal(g.edges['develops'].data['h'], F.tensor([0, 0, 2, 2], dtype=idtype))\n\n@parametrize_dtype\ndef test_add_nodes(idtype):\n # homogeneous Graphs\n g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())\n g.ndata['h'] = F.copy_to(F.tensor([1,1,1], dtype=idtype), ctx=F.ctx())\n g.add_nodes(1)\n assert g.number_of_nodes() == 4\n assert F.array_equal(g.ndata['h'], F.tensor([1, 1, 1, 0], dtype=idtype))\n\n # zero node graph\n g = dgl.graph(([], []), num_nodes=3, idtype=idtype, device=F.ctx())\n g.ndata['h'] = F.copy_to(F.tensor([1,1,1], dtype=idtype), ctx=F.ctx())\n g.add_nodes(1, data={'h' : F.copy_to(F.tensor([2], dtype=idtype), ctx=F.ctx())})\n assert g.number_of_nodes() == 4\n assert F.array_equal(g.ndata['h'], F.tensor([1, 1, 1, 2], dtype=idtype))\n\n # bipartite graph\n g = dgl.heterograph({('user', 'plays', 'game'): ([0, 1], [1, 2])},\n idtype=idtype, device=F.ctx())\n g.add_nodes(2, data={'h' : F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx())}, ntype='user')\n assert g.number_of_nodes('user') == 4\n assert F.array_equal(g.nodes['user'].data['h'], F.tensor([0, 0, 2, 2], dtype=idtype))\n g.add_nodes(2, ntype='game')\n assert g.number_of_nodes('game') == 5\n\n # heterogeneous graph\n g = create_test_heterograph3(idtype)\n g.add_nodes(1, ntype='user')\n g.add_nodes(2, data={'h' : F.copy_to(F.tensor([2, 2], dtype=idtype), ctx=F.ctx())}, ntype='game')\n g.add_nodes(0, ntype='developer')\n assert g.number_of_nodes('user') == 4\n assert g.number_of_nodes('game') == 4\n assert g.number_of_nodes('developer') == 2\n assert F.array_equal(g.nodes['user'].data['h'], F.tensor([1, 1, 1, 0], dtype=idtype))\n assert F.array_equal(g.nodes['game'].data['h'], F.tensor([2, 2, 2, 2], dtype=idtype))\n\[email protected](dgl.backend.backend_name == \"mxnet\", reason=\"MXNet has error with (0,) shape tensor.\")\n@parametrize_dtype\ndef test_remove_edges(idtype):\n # homogeneous Graphs\n g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())\n e = 0\n g.remove_edges(e)\n assert g.number_of_edges() == 1\n u, v = g.edges(form='uv', order='eid')\n assert F.array_equal(u, F.tensor([1], dtype=idtype))\n assert F.array_equal(v, F.tensor([2], dtype=idtype))\n g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())\n e = [0]\n g.remove_edges(e)\n assert g.number_of_edges() == 1\n u, v = g.edges(form='uv', order='eid')\n assert F.array_equal(u, F.tensor([1], dtype=idtype))\n assert F.array_equal(v, F.tensor([2], dtype=idtype))\n e = F.tensor([0], dtype=idtype)\n g.remove_edges(e)\n assert g.number_of_edges() == 0\n\n # has node data\n g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())\n g.ndata['h'] = F.copy_to(F.tensor([1, 2, 3], dtype=idtype), ctx=F.ctx())\n g.remove_edges(1)\n assert g.number_of_edges() == 1\n assert F.array_equal(g.ndata['h'], F.tensor([1, 2, 3], dtype=idtype))\n\n # has edge data\n g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())\n g.edata['h'] = F.copy_to(F.tensor([1, 2], dtype=idtype), ctx=F.ctx())\n g.remove_edges(0)\n assert g.number_of_edges() == 1\n assert F.array_equal(g.edata['h'], F.tensor([2], dtype=idtype))\n\n # invalid eid\n assert_fail = False\n try:\n g.remove_edges(1)\n except:\n assert_fail = True\n assert assert_fail\n\n # bipartite graph\n g = dgl.heterograph({\n ('user', 'plays', 'game'): ([0, 1], [1, 2])\n }, idtype=idtype, device=F.ctx())\n e = 0\n g.remove_edges(e)\n assert g.number_of_edges() == 1\n u, v = g.edges(form='uv', order='eid')\n assert F.array_equal(u, F.tensor([1], dtype=idtype))\n assert F.array_equal(v, F.tensor([2], dtype=idtype))\n g = dgl.heterograph(\n {('user', 'plays', 'game'): ([0, 1], [1, 2])}, idtype=idtype, device=F.ctx())\n e = [0]\n g.remove_edges(e)\n assert g.number_of_edges() == 1\n u, v = g.edges(form='uv', order='eid')\n assert F.array_equal(u, F.tensor([1], dtype=idtype))\n assert F.array_equal(v, F.tensor([2], dtype=idtype))\n e = F.tensor([0], dtype=idtype)\n g.remove_edges(e)\n assert g.number_of_edges() == 0\n\n # has data\n g = dgl.heterograph(\n {('user', 'plays', 'game'): ([0, 1], [1, 2])}, idtype=idtype, device=F.ctx())\n g.nodes['user'].data['h'] = F.copy_to(F.tensor([1, 1], dtype=idtype), ctx=F.ctx())\n g.nodes['game'].data['h'] = F.copy_to(F.tensor([2, 2, 2], dtype=idtype), ctx=F.ctx())\n g.edata['h'] = F.copy_to(F.tensor([1, 2], dtype=idtype), ctx=F.ctx())\n g.remove_edges(1)\n assert g.number_of_edges() == 1\n assert F.array_equal(g.nodes['user'].data['h'], F.tensor([1, 1], dtype=idtype))\n assert F.array_equal(g.nodes['game'].data['h'], F.tensor([2, 2, 2], dtype=idtype))\n assert F.array_equal(g.edata['h'], F.tensor([1], dtype=idtype))\n\n # heterogeneous graph\n g = create_test_heterograph3(idtype)\n g.edges['plays'].data['h'] = F.copy_to(F.tensor([1, 2, 3, 4], dtype=idtype), ctx=F.ctx())\n g.remove_edges(1, etype='plays')\n assert g.number_of_edges('plays') == 3\n u, v = g.edges(form='uv', order='eid', etype='plays')\n assert F.array_equal(u, F.tensor([0, 1, 2], dtype=idtype))\n assert F.array_equal(v, F.tensor([0, 1, 1], dtype=idtype))\n assert F.array_equal(g.edges['plays'].data['h'], F.tensor([1, 3, 4], dtype=idtype))\n # remove all edges of 'develops'\n g.remove_edges([0, 1], etype='develops')\n assert g.number_of_edges('develops') == 0\n assert F.array_equal(g.nodes['user'].data['h'], F.tensor([1, 1, 1], dtype=idtype))\n assert F.array_equal(g.nodes['game'].data['h'], F.tensor([2, 2], dtype=idtype))\n assert F.array_equal(g.nodes['developer'].data['h'], F.tensor([3, 3], dtype=idtype))\n\n@parametrize_dtype\ndef test_remove_nodes(idtype):\n # homogeneous Graphs\n g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())\n n = 0\n g.remove_nodes(n)\n assert g.number_of_nodes() == 2\n assert g.number_of_edges() == 1\n u, v = g.edges(form='uv', order='eid')\n assert F.array_equal(u, F.tensor([0], dtype=idtype))\n assert F.array_equal(v, F.tensor([1], dtype=idtype))\n g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())\n n = [1]\n g.remove_nodes(n)\n assert g.number_of_nodes() == 2\n assert g.number_of_edges() == 0\n g = dgl.graph(([0, 1], [1, 2]), idtype=idtype, device=F.ctx())\n n = F.tensor([2], dtype=idtype)\n g.remove_nodes(n)\n assert g.number_of_nodes() == 2\n assert g.number_of_edges() == 1\n u, v = g.edges(form='uv', order='eid')\n assert F.array_equal(u, F.tensor([0], dtype=idtype))\n assert F.array_equal(v, F.tensor([1], dtype=idtype))\n\n # invalid nid\n assert_fail = False\n try:\n g.remove_nodes(3)\n except:\n assert_fail = True\n assert assert_fail\n\n # has node and edge data\n g = dgl.graph(([0, 0, 2], [0, 1, 2]), idtype=idtype, device=F.ctx())\n g.ndata['hv'] = F.copy_to(F.tensor([1, 2, 3], dtype=idtype), ctx=F.ctx())\n g.edata['he'] = F.copy_to(F.tensor([1, 2, 3], dtype=idtype), ctx=F.ctx())\n g.remove_nodes(F.tensor([0], dtype=idtype))\n assert g.number_of_nodes() == 2\n assert g.number_of_edges() == 1\n u, v = g.edges(form='uv', order='eid')\n assert F.array_equal(u, F.tensor([1], dtype=idtype))\n assert F.array_equal(v, F.tensor([1], dtype=idtype))\n assert F.array_equal(g.ndata['hv'], F.tensor([2, 3], dtype=idtype))\n assert F.array_equal(g.edata['he'], F.tensor([3], dtype=idtype))\n\n # node id larger than current max node id\n g = dgl.heterograph(\n {('user', 'plays', 'game'): ([0, 1], [1, 2])}, idtype=idtype, device=F.ctx())\n n = 0\n g.remove_nodes(n, ntype='user')\n assert g.number_of_nodes('user') == 1\n assert g.number_of_nodes('game') == 3\n assert g.number_of_edges() == 1\n u, v = g.edges(form='uv', order='eid')\n assert F.array_equal(u, F.tensor([0], dtype=idtype))\n assert F.array_equal(v, F.tensor([2], dtype=idtype))\n g = dgl.heterograph(\n {('user', 'plays', 'game'): ([0, 1], [1, 2])}, idtype=idtype, device=F.ctx())\n n = [1]\n g.remove_nodes(n, ntype='user')\n assert g.number_of_nodes('user') == 1\n assert g.number_of_nodes('game') == 3\n assert g.number_of_edges() == 1\n u, v = g.edges(form='uv', order='eid')\n assert F.array_equal(u, F.tensor([0], dtype=idtype))\n assert F.array_equal(v, F.tensor([1], dtype=idtype))\n g = dgl.heterograph(\n {('user', 'plays', 'game'): ([0, 1], [1, 2])}, idtype=idtype, device=F.ctx())\n n = F.tensor([0], dtype=idtype)\n g.remove_nodes(n, ntype='game')\n assert g.number_of_nodes('user') == 2\n assert g.number_of_nodes('game') == 2\n assert g.number_of_edges() == 2\n u, v = g.edges(form='uv', order='eid')\n assert F.array_equal(u, F.tensor([0, 1], dtype=idtype))\n assert F.array_equal(v, F.tensor([0 ,1], dtype=idtype))\n\n # heterogeneous graph\n g = create_test_heterograph3(idtype)\n g.edges['plays'].data['h'] = F.copy_to(F.tensor([1, 2, 3, 4], dtype=idtype), ctx=F.ctx())\n g.remove_nodes(0, ntype='game')\n assert g.number_of_nodes('user') == 3\n assert g.number_of_nodes('game') == 1\n assert g.number_of_nodes('developer') == 2\n assert g.number_of_edges('plays') == 2\n assert g.number_of_edges('develops') == 1\n assert F.array_equal(g.nodes['user'].data['h'], F.tensor([1, 1, 1], dtype=idtype))\n assert F.array_equal(g.nodes['game'].data['h'], F.tensor([2], dtype=idtype))\n assert F.array_equal(g.nodes['developer'].data['h'], F.tensor([3, 3], dtype=idtype))\n u, v = g.edges(form='uv', order='eid', etype='plays')\n assert F.array_equal(u, F.tensor([1, 2], dtype=idtype))\n assert F.array_equal(v, F.tensor([0, 0], dtype=idtype))\n assert F.array_equal(g.edges['plays'].data['h'], F.tensor([3, 4], dtype=idtype))\n u, v = g.edges(form='uv', order='eid', etype='develops')\n assert F.array_equal(u, F.tensor([1], dtype=idtype))\n assert F.array_equal(v, F.tensor([0], dtype=idtype))\n\n@parametrize_dtype\ndef test_frame(idtype):\n g = dgl.graph(([0, 1, 2], [1, 2, 3]), idtype=idtype, device=F.ctx())\n g.ndata['h'] = F.copy_to(F.tensor([0, 1, 2, 3], dtype=idtype), ctx=F.ctx())\n g.edata['h'] = F.copy_to(F.tensor([0, 1, 2], dtype=idtype), ctx=F.ctx())\n\n # remove nodes\n sg = dgl.remove_nodes(g, [3])\n # check for lazy update\n assert F.array_equal(sg._node_frames[0]._columns['h'].storage, g.ndata['h'])\n assert F.array_equal(sg._edge_frames[0]._columns['h'].storage, g.edata['h'])\n assert sg.ndata['h'].shape[0] == 3\n assert sg.edata['h'].shape[0] == 2\n # update after read\n assert F.array_equal(sg._node_frames[0]._columns['h'].storage, F.tensor([0, 1, 2], dtype=idtype))\n assert F.array_equal(sg._edge_frames[0]._columns['h'].storage, F.tensor([0, 1], dtype=idtype))\n\n ng = dgl.add_nodes(sg, 1)\n assert ng.ndata['h'].shape[0] == 4\n assert F.array_equal(ng._node_frames[0]._columns['h'].storage, F.tensor([0, 1, 2, 0], dtype=idtype))\n ng = dgl.add_edges(ng, [3], [1])\n assert ng.edata['h'].shape[0] == 3\n assert F.array_equal(ng._edge_frames[0]._columns['h'].storage, F.tensor([0, 1, 0], dtype=idtype))\n\n # multi level lazy update\n sg = dgl.remove_nodes(g, [3])\n assert F.array_equal(sg._node_frames[0]._columns['h'].storage, g.ndata['h'])\n assert F.array_equal(sg._edge_frames[0]._columns['h'].storage, g.edata['h'])\n ssg = dgl.remove_nodes(sg, [1])\n assert F.array_equal(ssg._node_frames[0]._columns['h'].storage, g.ndata['h'])\n assert F.array_equal(ssg._edge_frames[0]._columns['h'].storage, g.edata['h'])\n # ssg is changed\n assert ssg.ndata['h'].shape[0] == 2\n assert ssg.edata['h'].shape[0] == 0\n assert F.array_equal(ssg._node_frames[0]._columns['h'].storage, F.tensor([0, 2], dtype=idtype))\n # sg still in lazy model\n assert F.array_equal(sg._node_frames[0]._columns['h'].storage, g.ndata['h'])\n assert F.array_equal(sg._edge_frames[0]._columns['h'].storage, g.edata['h'])\n\[email protected](dgl.backend.backend_name == \"tensorflow\", reason=\"TensorFlow always create a new tensor\")\[email protected](F._default_context_str == 'cpu', reason=\"cpu do not have context change problem\")\n@parametrize_dtype\ndef test_frame_device(idtype):\n g = dgl.graph(([0,1,2], [2,3,1]))\n g.ndata['h'] = F.copy_to(F.tensor([1,1,1,2], dtype=idtype), ctx=F.cpu())\n g.ndata['hh'] = F.copy_to(F.ones((4,3), dtype=idtype), ctx=F.cpu())\n g.edata['h'] = F.copy_to(F.tensor([1,2,3], dtype=idtype), ctx=F.cpu())\n\n g = g.to(F.ctx())\n # lazy device copy\n assert F.context(g._node_frames[0]._columns['h'].storage) == F.cpu()\n assert F.context(g._node_frames[0]._columns['hh'].storage) == F.cpu()\n print(g.ndata['h'])\n assert F.context(g._node_frames[0]._columns['h'].storage) == F.ctx()\n assert F.context(g._node_frames[0]._columns['hh'].storage) == F.cpu()\n assert F.context(g._edge_frames[0]._columns['h'].storage) == F.cpu()\n\n # lazy device copy in subgraph\n sg = dgl.node_subgraph(g, [0,1,2])\n assert F.context(sg._node_frames[0]._columns['h'].storage) == F.ctx()\n assert F.context(sg._node_frames[0]._columns['hh'].storage) == F.cpu()\n assert F.context(sg._edge_frames[0]._columns['h'].storage) == F.cpu()\n print(sg.ndata['hh'])\n assert F.context(sg._node_frames[0]._columns['hh'].storage) == F.ctx()\n assert F.context(sg._edge_frames[0]._columns['h'].storage) == F.cpu()\n\n # back to cpu\n sg = sg.to(F.cpu())\n assert F.context(sg._node_frames[0]._columns['h'].storage) == F.ctx()\n assert F.context(sg._node_frames[0]._columns['hh'].storage) == F.ctx()\n assert F.context(sg._edge_frames[0]._columns['h'].storage) == F.cpu()\n print(sg.ndata['h'])\n print(sg.ndata['hh'])\n print(sg.edata['h'])\n assert F.context(sg._node_frames[0]._columns['h'].storage) == F.cpu()\n assert F.context(sg._node_frames[0]._columns['hh'].storage) == F.cpu()\n assert F.context(sg._edge_frames[0]._columns['h'].storage) == F.cpu()\n\n # set some field\n sg = sg.to(F.ctx())\n assert F.context(sg._node_frames[0]._columns['h'].storage) == F.cpu()\n sg.ndata['h'][0] = 5\n assert F.context(sg._node_frames[0]._columns['h'].storage) == F.ctx()\n assert F.context(sg._node_frames[0]._columns['hh'].storage) == F.cpu()\n assert F.context(sg._edge_frames[0]._columns['h'].storage) == F.cpu()\n\n # add nodes\n ng = dgl.add_nodes(sg, 3)\n assert F.context(ng._node_frames[0]._columns['h'].storage) == F.ctx()\n assert F.context(ng._node_frames[0]._columns['hh'].storage) == F.ctx()\n assert F.context(ng._edge_frames[0]._columns['h'].storage) == F.cpu()\n\n\n\nif __name__ == '__main__':\n # test_create()\n # test_query()\n # test_hypersparse()\n # test_adj(\"int32\")\n # test_inc()\n # test_view(\"int32\")\n # test_view1(\"int32\")\n # test_flatten(F.int32)\n # test_convert_bound()\n # test_convert()\n # test_to_device(\"int32\")\n # test_transform(\"int32\")\n # test_subgraph(\"int32\")\n # test_subgraph_mask(\"int32\")\n # test_apply()\n # test_level1()\n # test_level2()\n # test_updates()\n # test_backward()\n # test_empty_heterograph('int32')\n # test_types_in_function()\n # test_stack_reduce()\n # test_isolated_ntype()\n # test_bipartite()\n # test_dtype_cast()\n # test_reverse(\"int32\")\n # test_format()\n #test_add_edges(F.int32)\n #test_add_nodes(F.int32)\n #test_remove_edges(F.int32)\n #test_remove_nodes(F.int32)\n #test_clone(F.int32)\n #test_frame(F.int32)\n #test_frame_device(F.int32)\n #test_empty_query(F.int32)\n pass\n",
"import argparse\nfrom collections import defaultdict\n\nimport networkx as nx\nimport numpy as np\nfrom gensim.models.keyedvectors import Vocab\nfrom six import iteritems\nfrom sklearn.metrics import auc, f1_score, precision_recall_curve, roc_auc_score\nimport torch\n\nimport time\nimport multiprocessing\nfrom functools import partial, reduce, wraps\n\nimport torch.multiprocessing as mp\nfrom _thread import start_new_thread\nimport traceback\n\n\ndef thread_wrapped_func(func):\n \"\"\"\n Wraps a process entry point to make it work with OpenMP.\n \"\"\"\n\n @wraps(func)\n def decorated_function(*args, **kwargs):\n queue = mp.Queue()\n\n def _queue_result():\n exception, trace, res = None, None, None\n try:\n res = func(*args, **kwargs)\n except Exception as e:\n exception = e\n trace = traceback.format_exc()\n queue.put((res, exception, trace))\n\n start_new_thread(_queue_result, ())\n result, exception, trace = queue.get()\n if exception is None:\n return result\n else:\n assert isinstance(exception, Exception)\n raise exception.__class__(trace)\n\n return decorated_function\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n \"--input\", type=str, default=\"data/amazon\", help=\"Input dataset path\"\n )\n\n parser.add_argument(\n \"--features\", type=str, default=None, help=\"Input node features\"\n )\n\n parser.add_argument(\n \"--epoch\", type=int, default=100, help=\"Number of epoch. Default is 100.\"\n )\n\n parser.add_argument(\n \"--batch-size\",\n type=int,\n default=64,\n help=\"Number of batch_size. Default is 64.\",\n )\n\n parser.add_argument(\n \"--eval-type\", type=str, default=\"all\", help=\"The edge type(s) for evaluation.\"\n )\n\n parser.add_argument(\n \"--schema\",\n type=str,\n default=None,\n help=\"The metapath schema (e.g., U-I-U,I-U-I).\",\n )\n\n parser.add_argument(\n \"--dimensions\",\n type=int,\n default=200,\n help=\"Number of dimensions. Default is 200.\",\n )\n\n parser.add_argument(\n \"--edge-dim\",\n type=int,\n default=10,\n help=\"Number of edge embedding dimensions. Default is 10.\",\n )\n\n parser.add_argument(\n \"--att-dim\",\n type=int,\n default=20,\n help=\"Number of attention dimensions. Default is 20.\",\n )\n\n parser.add_argument(\n \"--walk-length\",\n type=int,\n default=10,\n help=\"Length of walk per source. Default is 10.\",\n )\n\n parser.add_argument(\n \"--num-walks\",\n type=int,\n default=20,\n help=\"Number of walks per source. Default is 20.\",\n )\n\n parser.add_argument(\n \"--window-size\",\n type=int,\n default=5,\n help=\"Context size for optimization. Default is 5.\",\n )\n\n parser.add_argument(\n \"--negative-samples\",\n type=int,\n default=5,\n help=\"Negative samples for optimization. Default is 5.\",\n )\n\n parser.add_argument(\n \"--neighbor-samples\",\n type=int,\n default=10,\n help=\"Neighbor samples for aggregation. Default is 10.\",\n )\n\n parser.add_argument(\n \"--patience\", type=int, default=5, help=\"Early stopping patience. Default is 5.\"\n )\n\n parser.add_argument(\n \"--gpu\", type=str, default=None, help=\"Comma separated list of GPU device IDs.\"\n )\n\n parser.add_argument(\n \"--workers\", type=int, default=4, help=\"Number of workers.\",\n )\n\n return parser.parse_args()\n\n\n# for each line, the data is [edge_type, node, node]\ndef load_training_data(f_name):\n print(\"We are loading data from:\", f_name)\n edge_data_by_type = dict()\n all_nodes = list()\n with open(f_name, \"r\") as f:\n for line in f:\n words = line[:-1].split(\" \") # line[-1] == '\\n'\n if words[0] not in edge_data_by_type:\n edge_data_by_type[words[0]] = list()\n x, y = words[1], words[2]\n edge_data_by_type[words[0]].append((x, y))\n all_nodes.append(x)\n all_nodes.append(y)\n all_nodes = list(set(all_nodes))\n print(\"Total training nodes: \" + str(len(all_nodes)))\n return edge_data_by_type\n\n\n# for each line, the data is [edge_type, node, node, true_or_false]\ndef load_testing_data(f_name):\n print(\"We are loading data from:\", f_name)\n true_edge_data_by_type = dict()\n false_edge_data_by_type = dict()\n all_edges = list()\n all_nodes = list()\n with open(f_name, \"r\") as f:\n for line in f:\n words = line[:-1].split(\" \")\n x, y = words[1], words[2]\n if int(words[3]) == 1:\n if words[0] not in true_edge_data_by_type:\n true_edge_data_by_type[words[0]] = list()\n true_edge_data_by_type[words[0]].append((x, y))\n else:\n if words[0] not in false_edge_data_by_type:\n false_edge_data_by_type[words[0]] = list()\n false_edge_data_by_type[words[0]].append((x, y))\n all_nodes.append(x)\n all_nodes.append(y)\n all_nodes = list(set(all_nodes))\n return true_edge_data_by_type, false_edge_data_by_type\n\n\ndef load_node_type(f_name):\n print(\"We are loading node type from:\", f_name)\n node_type = {}\n with open(f_name, \"r\") as f:\n for line in f:\n items = line.strip().split()\n node_type[items[0]] = items[1]\n return node_type\n\n\ndef generate_pairs_parallel(walks, skip_window=None, layer_id=None):\n pairs = []\n for walk in walks:\n walk = walk.tolist()\n for i in range(len(walk)):\n for j in range(1, skip_window + 1):\n if i - j >= 0:\n pairs.append((walk[i], walk[i - j], layer_id))\n if i + j < len(walk):\n pairs.append((walk[i], walk[i + j], layer_id))\n return pairs\n\n\ndef generate_pairs(all_walks, window_size, num_workers):\n # for each node, choose the first neighbor and second neighbor of it to form pairs\n # Get all worker processes\n start_time = time.time()\n print(\"We are generating pairs with {} cores.\".format(num_workers))\n\n # Start all worker processes\n pool = multiprocessing.Pool(processes=num_workers)\n pairs = []\n skip_window = window_size // 2\n for layer_id, walks in enumerate(all_walks):\n block_num = len(walks) // num_workers\n if block_num > 0:\n walks_list = [\n walks[i * block_num : min((i + 1) * block_num, len(walks))]\n for i in range(num_workers)\n ]\n else:\n walks_list = [walks]\n tmp_result = pool.map(\n partial(\n generate_pairs_parallel, skip_window=skip_window, layer_id=layer_id\n ),\n walks_list,\n )\n pairs += reduce(lambda x, y: x + y, tmp_result)\n\n pool.close()\n end_time = time.time()\n print(\"Generate pairs end, use {}s.\".format(end_time - start_time))\n return np.array([list(pair) for pair in set(pairs)])\n\n\ndef generate_vocab(network_data):\n nodes, index2word = [], []\n for edge_type in network_data:\n node1, node2 = zip(*network_data[edge_type])\n index2word = index2word + list(node1) + list(node2)\n\n index2word = list(set(index2word))\n vocab = {}\n i = 0\n for word in index2word:\n vocab[word] = i\n i = i + 1\n\n for edge_type in network_data:\n node1, node2 = zip(*network_data[edge_type])\n tmp_nodes = list(set(list(node1) + list(node2)))\n tmp_nodes = [vocab[word] for word in tmp_nodes]\n nodes.append(tmp_nodes)\n\n return index2word, vocab, nodes\n\n\ndef get_score(local_model, edge):\n node1, node2 = str(edge[0]), str(edge[1])\n try:\n vector1 = local_model[node1]\n vector2 = local_model[node2]\n return np.dot(vector1, vector2) / (\n np.linalg.norm(vector1) * np.linalg.norm(vector2)\n )\n except Exception as e:\n pass\n\n\ndef evaluate(model, true_edges, false_edges, num_workers):\n true_list = list()\n prediction_list = list()\n true_num = 0\n\n # Start all worker processes\n pool = multiprocessing.Pool(processes=num_workers)\n tmp_true_score_list = pool.map(partial(get_score, model), true_edges)\n tmp_false_score_list = pool.map(partial(get_score, model), false_edges)\n pool.close()\n\n prediction_list += [\n tmp_score for tmp_score in tmp_true_score_list if tmp_score is not None\n ]\n true_num = len(prediction_list)\n true_list += [1] * true_num\n\n prediction_list += [\n tmp_score for tmp_score in tmp_false_score_list if tmp_score is not None\n ]\n true_list += [0] * (len(prediction_list) - true_num)\n\n sorted_pred = prediction_list[:]\n sorted_pred.sort()\n threshold = sorted_pred[-true_num]\n\n y_pred = np.zeros(len(prediction_list), dtype=np.int32)\n for i in range(len(prediction_list)):\n if prediction_list[i] >= threshold:\n y_pred[i] = 1\n\n y_true = np.array(true_list)\n y_scores = np.array(prediction_list)\n ps, rs, _ = precision_recall_curve(y_true, y_scores)\n return roc_auc_score(y_true, y_scores), f1_score(y_true, y_pred), auc(rs, ps)\n"
] | [
[
"torch.nn.CrossEntropyLoss",
"torch.nn.ModuleList"
],
[
"scipy.sparse.coo_matrix",
"numpy.arange",
"scipy.sparse.rand",
"numpy.ones",
"numpy.array",
"numpy.zeros"
],
[
"sklearn.metrics.roc_auc_score",
"numpy.dot",
"torch.multiprocessing.Queue",
"numpy.linalg.norm",
"sklearn.metrics.precision_recall_curve",
"sklearn.metrics.auc",
"sklearn.metrics.f1_score",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"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": []
}
] |
m-wessler/nbm-pqpf-deploy | [
"ccc7a95d1e1cf7b264fafdc0da2bc1a2bc86f839"
] | [
"scraps/scripts_all/nbm_archive_updater.py"
] | [
"import shutil\nimport shlex\nimport subprocess\nimport sys, os, gc\nimport numpy as np\nimport xarray as xr\nimport pandas as pd\nimport multiprocessing as mp\n\nfrom glob import glob\nfrom io import StringIO\nfrom datetime import datetime, timedelta\n\ncore_limit = 8\n\nnbm_dir = '/scratch/general/lustre/u1070830/nbm/'\n# urma_dir = '/scratch/general/lustre/u1070830/urma/'\n\ndef unpack_fhr(nbm_file):\n import pygrib\n \n nlat, xlat = 30, 50\n nlon, xlon = -130, -100\n\n if os.path.isfile(nbm_file):\n\n with pygrib.open(nbm_file) as grb:\n\n try:\n lats, lons = grb.message(1).latlons()\n except:\n data = None\n else:\n idx = np.where(\n (lats >= nlat) & (lats <= xlat) &\n (lons >= nlon) & (lons <= xlon))\n\n init_time = nbm_file.split('/')[-2:]\n init_time = init_time[0] + init_time[1].split('.')[1][1:3]\n init_time = datetime.strptime(init_time, '%Y%m%d%H')\n valid_fhr = int(os.path.basename(nbm_file).split('/')[-1].split('.')[3][1:])\n\n # Check if nbm3.2\n if init_time.hour in [1, 7, 13, 19]:\n init_time -= timedelta(hours=1)\n valid_fhr += 1\n\n valid_time = init_time + timedelta(hours=valid_fhr)\n #print(init_time, valid_fhr, valid_time)\n #print('\\t', valid_fhr, valid_time)\n\n percentile, probability, deterministic = [], [], []\n percentile_labels, probability_labels, deterministic_labels = [], [], []\n\n data = []\n for msg in grb.read():\n\n interval = msg['stepRange'].split('-')\n interval = int(interval[1]) - int(interval[0])\n\n if interval == 24:\n\n if 'Probability of event' in str(msg):\n\n threshold = round(msg['upperLimit']/25.4, 2)\n\n if threshold in [0.01, 0.10, 0.25, 0.50, 1.00, 2.00]:\n\n idata = xr.DataArray(msg.data()[0].astype(np.float32), name='probx',\n dims=('y', 'x'), \n coords={'lat':(('y', 'x'), lats), \n 'lon':(('y', 'x'), lons)})\n\n idata['init'] = init_time\n idata['valid'] = valid_time\n idata['fhr'] = valid_fhr\n idata['interval'] = interval\n idata['threshold'] = threshold\n\n data.append(idata)\n\n gc.collect()\n\n try:\n data = xr.concat(data, dim='threshold')\n\n except:\n return None\n\n else:\n data_slice = data.isel(x=slice(idx[1].min(), idx[1].max()), \n y=slice(idx[0].min(), idx[0].max()))\n\n return data_slice\n\n else:\n return None\n \ndef combine_nbm_old_new(fhr): \n\n fhr_agg_old_file = sorted(glob(nbm_dir + 'extract/' + '*fhr%03d.nc'%fhr))[0]\n fhr_agg_new_file = sorted(glob(nbm_dir + 'extract_new/' + '*fhr%03d.new.nc'%fhr))[0]\n \n fhr_agg_old = xr.open_dataset(fhr_agg_old_file)\n fhr_agg_new = xr.open_dataset(fhr_agg_new_file)\n\n not_duplicated = np.array([t for t in fhr_agg_new.valid.values if t not in fhr_agg_old.valid.values])\n fhr_agg_new = fhr_agg_new.sel(valid=not_duplicated)\n \n print('Combining new FHR%03d data...'%fhr)\n \n fhr_agg = xr.concat([fhr_agg_old, fhr_agg_new], dim='valid')\n \n fhr_agg_output_file = nbm_dir + 'extract_new/' + os.path.basename(fhr_agg_old_file)\n fhr_agg.to_netcdf(fhr_agg_output_file)\n print('Saved: %s'%fhr_agg_output_file)\n \n return None\n \nif __name__ == '__main__':\n\n # urma_raw = np.array(sorted(glob(urma_dir + '*.grib2')))\n # urma_agg = xr.open_dataset(glob(urma_dir + 'agg/*')[0])\n\n nbm_raw = np.array(sorted([f for f in sorted(glob(nbm_dir + '*/*.grib2')) if 'extract' not in f]))\n nbm_agg = np.array(sorted(glob(nbm_dir + 'extract/*')))\n\n # # Last complete URMA aggregated\n # last_urma_agg = urma_agg.valid[-1].values\n # last_urma_agg\n\n # # Last complete URMA downloaded\n # last_urma_download = xr.open_dataset(urma_raw[-1], engine='cfgrib').valid_time.values\n # last_urma_download\n\n # Last complete run aggregated\n nbm_agg_file = nbm_agg[0]\n last_nbm_agg = xr.open_dataset(nbm_agg_file).init[-1].values\n\n # Last complete run downloaded\n nbm_f024 = np.array(sorted([f for f in nbm_raw if 'f024' in f]))[-1]\n last_nbm_download = xr.open_dataset(nbm_f024, engine='cfgrib').valid_time.values\n\n # # Since we want this to update as soon as possible, use the 24h time mark\n # # But we can't produce anything unless URMA is updated as well\n # newest_time_match = np.min([last_nbm_download, last_urma_download])\n # newest_time_match\n\n # # Figure out how many missing inits between newest available data and last aggregate\n # newest_agg_time_match = np.min([last_nbm_agg, last_urma_agg])\n # newest_agg_time_match\n\n nbm_upload_lag = 6\n most_recent_time = datetime.utcnow() #+ timedelta(hours=4, minutes=10)\n\n roundUp = True if most_recent_time.minute < 30 else False\n\n most_recent_time = most_recent_time.replace(minute=0, second=0, microsecond=0)\n\n if roundUp:\n most_recent_time += timedelta(hours=1)\n\n # Round down to nearest 0, 6, 12, 18, then grab the run prior\n most_recent_time -= timedelta(hours=(most_recent_time.hour%6)+6)\n\n # if last_nbm_download > last_nbm_agg:\n if np.datetime64(most_recent_time) > last_nbm_agg:\n\n print('Newer NBM Available\\n') \n # fill_runs = pd.date_range(last_nbm_agg, last_nbm_download, freq='6H')\n fill_runs = pd.date_range(last_nbm_agg, most_recent_time, freq='6H')[1:]\n\n print('Runs to fill: %s'%fill_runs)\n\n # Call the NBM download here\n python = '/uufs/chpc.utah.edu/common/home/u1070830/anaconda3/envs/xlab/bin/python '\n dl_script = '/uufs/chpc.utah.edu/common/home/u1070830/code/model-tools/nbm/get_nbm_gribs_aws.py ' \n\n dl_start, dl_end = pd.to_datetime(fill_runs[0]), pd.to_datetime(fill_runs[-1])\n dl_start, dl_end = [datetime.strftime(t, '%Y%m%d%H%M') for t in [dl_start, dl_end]]\n\n cmd = python + dl_script + '%s %s'%(dl_start, dl_end)\n \n subprocess.run(shlex.split(cmd), stderr=sys.stderr, stdout=sys.stdout)\n \n for forecast_hour in np.arange(24, 168+1, 24):\n\n outdir = nbm_dir + 'extract_new/'\n os.makedirs(outdir, exist_ok=True)\n outfile = 'nbm_probx_fhr%03d.new.nc'%forecast_hour\n\n if not os.path.isfile(outdir+outfile):\n\n flist = []\n for init in fill_runs:\n\n search_str = nbm_dir + '%s/*t%02dz*f%03d*WR.grib2'%(\n init.strftime('%Y%m%d'), init.hour, forecast_hour)\n search = glob(search_str)\n\n if len(search) > 0:\n flist.append(search[0])\n\n flist = np.array(sorted(flist))\n print('nfiles: ', len(flist))\n\n ncores = np.min([core_limit, len(flist)])\n with mp.get_context('fork').Pool(ncores) as p:\n returns = p.map(unpack_fhr, flist, chunksize=1)\n p.close()\n p.join()\n\n returns = [item for item in returns if item is not None]\n returns = xr.concat(returns, dim='valid')\n\n returns.to_netcdf(outdir + outfile)\n print('Saved %s'%(outdir + outfile))\n\n del returns\n gc.collect()\n \n nbm_agg_new = np.array(sorted(glob(nbm_dir + 'extract_new/*')))\n\n ncores = np.min([core_limit, len(np.arange(24, 168.1, 24))])\n with mp.get_context('fork').Pool(ncores) as p:\n returns = p.map(combine_nbm_old_new, np.arange(24, 168.1, 24), chunksize=1)\n p.close()\n p.join()\n \n # Verify that the new file didn't corrupt the existing data!\n new_agg_temp = sorted([f for f in glob(nbm_dir + 'extract_new/*.nc') if '.new.' in f])\n new_agg_check = sorted([f for f in glob(nbm_dir + 'extract_new/*.nc') if '.new.' not in f])\n old_agg_check = sorted(glob(nbm_dir + 'extract/*.nc'))\n\n for temp_file, new_file, old_file in zip(new_agg_temp, new_agg_check, old_agg_check):\n\n try:\n new = xr.open_dataset(new_file)\n old = xr.open_dataset(old_file)\n\n except:\n pass\n\n else:\n if new.valid[-1] > old.valid[-1]:\n print('New aggregate %s updated, check...'%os.path.basename(new_file))\n\n try:\n os.remove(temp_file)\n print(temp_file, '-->', 'deleted')\n except:\n pass\n\n try:\n shutil.move(old_file, old_file.replace('.nc', '.old.nc'))\n print(old_file, '-->', old_file.replace('.nc', '.old.nc'))\n except:\n pass\n\n try:\n shutil.move(new_file, new_file.replace('extract_new', 'extract'))\n print(new_file, '-->', new_file.replace('extract_new', 'extract'))\n except:\n pass\n \n try:\n os.remove(old_file.replace('.nc', '.old.nc'))\n print(old_file.replace('.nc', '.old.nc'), '-->', 'deleted')\n except:\n pass\n\n else:\n print('New aggregate %s failed, follow up...'%os.path.basename(new_file))\n\n print()\n \n print('\\nDone...')"
] | [
[
"pandas.to_datetime",
"numpy.arange",
"numpy.datetime64",
"pandas.date_range",
"numpy.array",
"numpy.where"
]
] | [
{
"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": []
}
] |
zhoufengfan/MMT-plus | [
"e95db1452d3480518a851dd7ffa07208522f2614"
] | [
"visda/sda/models/networks.py"
] | [
"import torch\nimport torch.nn as nn\nfrom torch.nn import init\nfrom torch.nn import utils\nimport torch.nn.functional as F\nimport functools\nfrom torch.optim import lr_scheduler\n\n\n###############################################################################\n# Helper Functions\n###############################################################################\n\n\nclass Identity(nn.Module):\n def forward(self, x):\n return x\n\n\ndef get_norm_layer(norm_type='instance'):\n \"\"\"Return a normalization layer\n\n Parameters:\n norm_type (str) -- the name of the normalization layer: batch | instance | none\n\n For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev).\n For InstanceNorm, we do not use learnable affine parameters. We do not track running statistics.\n \"\"\"\n if norm_type == 'batch':\n norm_layer = functools.partial(nn.BatchNorm2d, affine=True, track_running_stats=True)\n elif norm_type == 'instance':\n norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False)\n elif norm_type == 'none':\n norm_layer = lambda x: Identity()\n else:\n raise NotImplementedError('normalization layer [%s] is not found' % norm_type)\n return norm_layer\n\n\ndef get_scheduler(optimizer, opt):\n \"\"\"Return a learning rate scheduler\n\n Parameters:\n optimizer -- the optimizer of the network\n opt (option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions. \n opt.lr_policy is the name of learning rate policy: linear | step | plateau | cosine\n\n For 'linear', we keep the same learning rate for the first <opt.niter> epochs\n and linearly decay the rate to zero over the next <opt.niter_decay> epochs.\n For other schedulers (step, plateau, and cosine), we use the default PyTorch schedulers.\n See https://pytorch.org/docs/stable/optim.html for more details.\n \"\"\"\n if opt.lr_policy == 'linear':\n def lambda_rule(epoch):\n lr_l = 1.0 - max(0, epoch + opt.epoch_count - opt.niter) / float(opt.niter_decay + 1)\n return lr_l\n scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule)\n elif opt.lr_policy == 'step':\n scheduler = lr_scheduler.StepLR(optimizer, step_size=opt.lr_decay_iters, gamma=0.1)\n elif opt.lr_policy == 'plateau':\n scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.2, threshold=0.01, patience=5)\n elif opt.lr_policy == 'cosine':\n scheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=opt.niter, eta_min=0)\n else:\n return NotImplementedError('learning rate policy [%s] is not implemented', opt.lr_policy)\n return scheduler\n\n\ndef init_weights(net, init_type='normal', init_gain=0.02):\n \"\"\"Initialize network weights.\n\n Parameters:\n net (network) -- network to be initialized\n init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal\n init_gain (float) -- scaling factor for normal, xavier and orthogonal.\n\n We use 'normal' in the original pix2pix and CycleGAN paper. But xavier and kaiming might\n work better for some applications. Feel free to try yourself.\n \"\"\"\n def init_func(m): # define the initialization function\n classname = m.__class__.__name__\n if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):\n if init_type == 'normal':\n init.normal_(m.weight.data, 0.0, init_gain)\n elif init_type == 'xavier':\n init.xavier_normal_(m.weight.data, gain=init_gain)\n elif init_type == 'kaiming':\n init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')\n elif init_type == 'orthogonal':\n init.orthogonal_(m.weight.data, gain=init_gain)\n else:\n raise NotImplementedError('initialization method [%s] is not implemented' % init_type)\n if hasattr(m, 'bias') and m.bias is not None:\n init.constant_(m.bias.data, 0.0)\n elif classname.find('BatchNorm2d') != -1: # BatchNorm Layer's weight is not a matrix; only normal distribution applies.\n init.normal_(m.weight.data, 1.0, init_gain)\n init.constant_(m.bias.data, 0.0)\n\n print('initialize network with %s' % init_type)\n net.apply(init_func) # apply the initialization function <init_func>\n\n\ndef init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]):\n \"\"\"Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights\n Parameters:\n net (network) -- the network to be initialized\n init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal\n gain (float) -- scaling factor for normal, xavier and orthogonal.\n gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2\n\n Return an initialized network.\n \"\"\"\n if len(gpu_ids) > 0:\n assert(torch.cuda.is_available())\n net.cuda()\n net = torch.nn.DataParallel(net) # multi-GPUs\n # net.to(gpu_ids[0])\n # net = torch.nn.DataParallel(net, gpu_ids) # multi-GPUs\n init_weights(net, init_type, init_gain=init_gain)\n return net\n\n\ndef define_G(input_nc, output_nc, ngf, netG, norm='batch', use_dropout=False, init_type='normal', init_gain=0.02, gpu_ids=[]):\n \"\"\"Create a generator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n output_nc (int) -- the number of channels in output images\n ngf (int) -- the number of filters in the last conv layer\n netG (str) -- the architecture's name: resnet_9blocks | resnet_6blocks | unet_256 | unet_128\n norm (str) -- the name of normalization layers used in the network: batch | instance | none\n use_dropout (bool) -- if use dropout layers.\n init_type (str) -- the name of our initialization method.\n init_gain (float) -- scaling factor for normal, xavier and orthogonal.\n gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2\n\n Returns a generator\n\n Our current implementation provides two types of generators:\n U-Net: [unet_128] (for 128x128 input images) and [unet_256] (for 256x256 input images)\n The original U-Net paper: https://arxiv.org/abs/1505.04597\n\n Resnet-based generator: [resnet_6blocks] (with 6 Resnet blocks) and [resnet_9blocks] (with 9 Resnet blocks)\n Resnet-based generator consists of several Resnet blocks between a few downsampling/upsampling operations.\n We adapt Torch code from Justin Johnson's neural style transfer project (https://github.com/jcjohnson/fast-neural-style).\n\n\n The generator has been initialized by <init_net>. It uses RELU for non-linearity.\n \"\"\"\n net = None\n norm_layer = get_norm_layer(norm_type=norm)\n\n if netG == 'resnet_9blocks':\n net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=9)\n elif netG == 'resnet_6blocks':\n net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=6)\n elif netG == 'unet_128':\n net = UnetGenerator(input_nc, output_nc, 7, ngf, norm_layer=norm_layer, use_dropout=use_dropout)\n elif netG == 'unet_256':\n net = UnetGenerator(input_nc, output_nc, 8, ngf, norm_layer=norm_layer, use_dropout=use_dropout)\n else:\n raise NotImplementedError('Generator model name [%s] is not recognized' % netG)\n return init_net(net, init_type, init_gain, gpu_ids)\n\n\ndef define_D(input_nc, ndf, netD, n_layers_D=3, norm='batch', init_type='normal', init_gain=0.02, gpu_ids=[]):\n \"\"\"Create a discriminator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n ndf (int) -- the number of filters in the first conv layer\n netD (str) -- the architecture's name: basic | n_layers | pixel\n n_layers_D (int) -- the number of conv layers in the discriminator; effective when netD=='n_layers'\n norm (str) -- the type of normalization layers used in the network.\n init_type (str) -- the name of the initialization method.\n init_gain (float) -- scaling factor for normal, xavier and orthogonal.\n gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2\n\n Returns a discriminator\n\n Our current implementation provides three types of discriminators:\n [basic]: 'PatchGAN' classifier described in the original pix2pix paper.\n It can classify whether 70×70 overlapping patches are real or fake.\n Such a patch-level discriminator architecture has fewer parameters\n than a full-image discriminator and can work on arbitrarily-sized images\n in a fully convolutional fashion.\n\n [n_layers]: With this mode, you cna specify the number of conv layers in the discriminator\n with the parameter <n_layers_D> (default=3 as used in [basic] (PatchGAN).)\n\n [pixel]: 1x1 PixelGAN discriminator can classify whether a pixel is real or not.\n It encourages greater color diversity but has no effect on spatial statistics.\n\n The discriminator has been initialized by <init_net>. It uses Leakly RELU for non-linearity.\n \"\"\"\n net = None\n norm_layer = get_norm_layer(norm_type=norm)\n\n if netD == 'basic': # default PatchGAN classifier\n net = NLayerDiscriminator(input_nc, ndf, n_layers=3, norm_layer=norm_layer)\n elif netD == 'n_layers': # more options\n net = NLayerDiscriminator(input_nc, ndf, n_layers_D, norm_layer=norm_layer)\n elif netD == 'pixel': # classify if each pixel is real or fake\n net = PixelDiscriminator(input_nc, ndf, norm_layer=norm_layer)\n elif netD == 'n_layers_proj':\n net = NLayerProjDiscriminator(input_nc, ndf, n_layers=n_layers_D, norm_layer=norm_layer)\n elif netD == 'fc':\n net = FCDiscriminator(input_nc, ndf)\n else:\n raise NotImplementedError('Discriminator model name [%s] is not recognized' % netD)\n return init_net(net, init_type, init_gain, gpu_ids)\n\n\n##############################################################################\n# Classes\n##############################################################################\n# class GANLoss(nn.Module):\n# \"\"\"Define different GAN objectives.\n#\n# The GANLoss class abstracts away the need to create the target label tensor\n# that has the same size as the input.\n# \"\"\"\n#\n# def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):\n# \"\"\" Initialize the GANLoss class.\n#\n# Parameters:\n# gan_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp.\n# target_real_label (bool) - - label for a real image\n# target_fake_label (bool) - - label of a fake image\n#\n# Note: Do not use sigmoid as the last layer of Discriminator.\n# LSGAN needs no sigmoid. vanilla GANs will handle it with BCEWithLogitsLoss.\n# \"\"\"\n# super(GANLoss, self).__init__()\n# self.register_buffer('real_label', torch.tensor(target_real_label))\n# self.register_buffer('fake_label', torch.tensor(target_fake_label))\n# self.gan_mode = gan_mode\n# if gan_mode == 'lsgan':\n# self.loss = nn.MSELoss()\n# elif gan_mode == 'vanilla':\n# self.loss = nn.BCEWithLogitsLoss()\n# elif gan_mode in ['wgangp']:\n# self.loss = None\n# else:\n# raise NotImplementedError('gan mode %s not implemented' % gan_mode)\n#\n# def get_target_tensor(self, prediction, target_is_real):\n# \"\"\"Create label tensors with the same size as the input.\n#\n# Parameters:\n# prediction (tensor) - - tpyically the prediction from a discriminator\n# target_is_real (bool) - - if the ground truth label is for real images or fake images\n#\n# Returns:\n# A label tensor filled with ground truth label, and with the size of the input\n# \"\"\"\n#\n# if target_is_real:\n# target_tensor = self.real_label\n# else:\n# target_tensor = self.fake_label\n# return target_tensor.expand_as(prediction)\n#\n# def __call__(self, prediction, target_is_real):\n# \"\"\"Calculate loss given Discriminator's output and grount truth labels.\n#\n# Parameters:\n# prediction (tensor) - - tpyically the prediction output from a discriminator\n# target_is_real (bool) - - if the ground truth label is for real images or fake images\n#\n# Returns:\n# the calculated loss.\n# \"\"\"\n# if self.gan_mode in ['lsgan', 'vanilla']:\n# target_tensor = self.get_target_tensor(prediction, target_is_real)\n# loss = self.loss(prediction, target_tensor)\n# elif self.gan_mode == 'wgangp':\n# if target_is_real:\n# loss = -prediction.mean()\n# else:\n# loss = prediction.mean()\n# return loss\n\n# Defines the GAN loss which uses either LSGAN or the regular GAN.\n# When LSGAN is used, it is basically same as MSELoss,\n# but it abstracts away the need to create the target label tensor\n# that has the same size as the input\nclass GANLoss(nn.Module):\n def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0,\n tensor=torch.FloatTensor, opt=None):\n super(GANLoss, self).__init__()\n self.real_label = target_real_label\n self.fake_label = target_fake_label\n self.real_label_tensor = None\n self.fake_label_tensor = None\n self.zero_tensor = None\n self.Tensor = tensor\n self.gan_mode = gan_mode\n self.opt = opt\n if gan_mode == 'lsgan':\n pass\n elif gan_mode == 'vanilla':\n pass\n elif gan_mode == 'wgangp':\n pass\n elif gan_mode == 'hinge':\n pass\n else:\n raise ValueError('Unexpected gan_mode {}'.format(gan_mode))\n\n def get_target_tensor(self, input, target_is_real):\n if target_is_real:\n if self.real_label_tensor is None:\n self.real_label_tensor = self.Tensor(1).fill_(self.real_label)\n self.real_label_tensor.requires_grad_(False)\n return self.real_label_tensor.expand_as(input).cuda()\n else:\n if self.fake_label_tensor is None:\n self.fake_label_tensor = self.Tensor(1).fill_(self.fake_label)\n self.fake_label_tensor.requires_grad_(False)\n return self.fake_label_tensor.expand_as(input).cuda()\n\n def get_zero_tensor(self, input):\n if self.zero_tensor is None:\n self.zero_tensor = self.Tensor(1).fill_(0)\n self.zero_tensor.requires_grad_(False)\n return self.zero_tensor.expand_as(input).cuda()\n\n def loss(self, input, target_is_real, for_discriminator=True):\n if self.gan_mode == 'vanilla': # cross entropy loss\n target_tensor = self.get_target_tensor(input, target_is_real)\n loss = F.binary_cross_entropy_with_logits(input, target_tensor)\n return loss\n elif self.gan_mode == 'lsgan':\n target_tensor = self.get_target_tensor(input, target_is_real)\n return F.mse_loss(input, target_tensor)\n elif self.gan_mode == 'hinge':\n if for_discriminator:\n if target_is_real:\n minval = torch.min(input - 1, self.get_zero_tensor(input))\n loss = -torch.mean(minval)\n else:\n minval = torch.min(-input - 1, self.get_zero_tensor(input))\n loss = -torch.mean(minval)\n else:\n assert target_is_real, \"The generator's hinge loss must be aiming for real\"\n loss = -torch.mean(input)\n return loss\n else:\n # wgan\n if target_is_real:\n return -input.mean()\n else:\n return input.mean()\n\n def __call__(self, input, target_is_real, for_discriminator=True):\n # computing loss is a bit complicated because |input| may not be\n # a tensor, but list of tensors in case of multiscale discriminator\n if isinstance(input, list):\n loss = 0\n for pred_i in input:\n if isinstance(pred_i, list):\n pred_i = pred_i[-1]\n loss_tensor = self.loss(pred_i, target_is_real, for_discriminator)\n bs = 1 if len(loss_tensor.size()) == 0 else loss_tensor.size(0)\n new_loss = torch.mean(loss_tensor.view(bs, -1), dim=1)\n loss += new_loss\n return loss / len(input)\n else:\n return self.loss(input, target_is_real, for_discriminator)\n\nclass MMD_loss(nn.Module):\n def __init__(self, kernel_mul = 2.0, kernel_num = 5):\n super(MMD_loss, self).__init__()\n self.kernel_num = kernel_num\n self.kernel_mul = kernel_mul\n self.fix_sigma = None\n\n def guassian_kernel(self, source, target, kernel_mul=2.0, kernel_num=5, fix_sigma=None):\n n_samples = int(source.size(0))+int(target.size(0))\n total = torch.cat([source, target], dim=0)\n\n total0 = total.unsqueeze(0).expand(int(total.size(0)), int(total.size(0)), int(total.size(1)))\n total1 = total.unsqueeze(1).expand(int(total.size(0)), int(total.size(0)), int(total.size(1)))\n L2_distance = ((total0-total1)**2).sum(2)\n if fix_sigma:\n bandwidth = fix_sigma\n else:\n bandwidth = torch.sum(L2_distance.data) / (n_samples**2-n_samples)\n bandwidth /= kernel_mul ** (kernel_num // 2)\n bandwidth_list = [bandwidth * (kernel_mul**i) for i in range(kernel_num)]\n kernel_val = [torch.exp(-L2_distance / bandwidth_temp) for bandwidth_temp in bandwidth_list]\n return sum(kernel_val)\n\n def forward(self, source, target):\n batch_size = int(source.size(0))\n kernels = self.guassian_kernel(source, target, kernel_mul=self.kernel_mul, kernel_num=self.kernel_num, fix_sigma=self.fix_sigma)\n XX = kernels[:batch_size, :batch_size]\n YY = kernels[batch_size:, batch_size:]\n XY = kernels[:batch_size, batch_size:]\n YX = kernels[batch_size:, :batch_size]\n loss = torch.mean(XX + YY - XY -YX)\n return loss\n\ndef cal_gradient_penalty(netD, real_data, fake_data, device, type='mixed', constant=1.0, lambda_gp=10.0):\n \"\"\"Calculate the gradient penalty loss, used in WGAN-GP paper https://arxiv.org/abs/1704.00028\n\n Arguments:\n netD (network) -- discriminator network\n real_data (tensor array) -- real images\n fake_data (tensor array) -- generated images from the generator\n device (str) -- GPU / CPU: from torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device('cpu')\n type (str) -- if we mix real and fake data or not [real | fake | mixed].\n constant (float) -- the constant used in formula ( | |gradient||_2 - constant)^2\n lambda_gp (float) -- weight for this loss\n\n Returns the gradient penalty loss\n \"\"\"\n if lambda_gp > 0.0:\n if type == 'real': # either use real images, fake images, or a linear interpolation of two.\n interpolatesv = real_data\n elif type == 'fake':\n interpolatesv = fake_data\n elif type == 'mixed':\n alpha = torch.rand(real_data.shape[0], 1, device=device)\n alpha = alpha.expand(real_data.shape[0], real_data.nelement() // real_data.shape[0]).contiguous().view(*real_data.shape)\n interpolatesv = alpha * real_data + ((1 - alpha) * fake_data)\n else:\n raise NotImplementedError('{} not implemented'.format(type))\n interpolatesv.requires_grad_(True)\n disc_interpolates = netD(interpolatesv)\n gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolatesv,\n grad_outputs=torch.ones(disc_interpolates.size()).to(device),\n create_graph=True, retain_graph=True, only_inputs=True)\n gradients = gradients[0].view(real_data.size(0), -1) # flat the data\n gradient_penalty = (((gradients + 1e-16).norm(2, dim=1) - constant) ** 2).mean() * lambda_gp # added eps\n return gradient_penalty, gradients\n else:\n return 0.0, None\n\nclass ResnetGenerator(nn.Module):\n \"\"\"Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations.\n\n We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style)\n \"\"\"\n\n def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, padding_type='reflect'):\n \"\"\"Construct a Resnet-based generator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n output_nc (int) -- the number of channels in output images\n ngf (int) -- the number of filters in the last conv layer\n norm_layer -- normalization layer\n use_dropout (bool) -- if use dropout layers\n n_blocks (int) -- the number of ResNet blocks\n padding_type (str) -- the name of padding layer in conv layers: reflect | replicate | zero\n \"\"\"\n assert(n_blocks >= 0)\n super(ResnetGenerator, self).__init__()\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n\n model = [nn.ReflectionPad2d(3),\n nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0, bias=use_bias),\n norm_layer(ngf),\n nn.ReLU(True)]\n\n n_downsampling = 2\n for i in range(n_downsampling): # add downsampling layers\n mult = 2 ** i\n model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1, bias=use_bias),\n norm_layer(ngf * mult * 2),\n nn.ReLU(True)]\n\n mult = 2 ** n_downsampling\n for i in range(n_blocks): # add ResNet blocks\n\n model += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias)]\n\n for i in range(n_downsampling): # add upsampling layers\n mult = 2 ** (n_downsampling - i)\n model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2),\n kernel_size=3, stride=2,\n padding=1, output_padding=1,\n bias=use_bias),\n norm_layer(int(ngf * mult / 2)),\n nn.ReLU(True)]\n model += [nn.ReflectionPad2d(3)]\n model += [nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)]\n # model += [nn.Tanh()]\n model += [nn.Sigmoid()]\n\n self.model = nn.Sequential(*model)\n\n def forward(self, input):\n \"\"\"Standard forward\"\"\"\n return self.model(input)\n\n\nclass ResnetBlock(nn.Module):\n \"\"\"Define a Resnet block\"\"\"\n\n def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias):\n \"\"\"Initialize the Resnet block\n\n A resnet block is a conv block with skip connections\n We construct a conv block with build_conv_block function,\n and implement skip connections in <forward> function.\n Original Resnet paper: https://arxiv.org/pdf/1512.03385.pdf\n \"\"\"\n super(ResnetBlock, self).__init__()\n self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout, use_bias)\n\n def build_conv_block(self, dim, padding_type, norm_layer, use_dropout, use_bias):\n \"\"\"Construct a convolutional block.\n\n Parameters:\n dim (int) -- the number of channels in the conv layer.\n padding_type (str) -- the name of padding layer: reflect | replicate | zero\n norm_layer -- normalization layer\n use_dropout (bool) -- if use dropout layers.\n use_bias (bool) -- if the conv layer uses bias or not\n\n Returns a conv block (with a conv layer, a normalization layer, and a non-linearity layer (ReLU))\n \"\"\"\n conv_block = []\n p = 0\n if padding_type == 'reflect':\n conv_block += [nn.ReflectionPad2d(1)]\n elif padding_type == 'replicate':\n conv_block += [nn.ReplicationPad2d(1)]\n elif padding_type == 'zero':\n p = 1\n else:\n raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n\n conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim), nn.ReLU(True)]\n if use_dropout:\n conv_block += [nn.Dropout(0.5)]\n\n p = 0\n if padding_type == 'reflect':\n conv_block += [nn.ReflectionPad2d(1)]\n elif padding_type == 'replicate':\n conv_block += [nn.ReplicationPad2d(1)]\n elif padding_type == 'zero':\n p = 1\n else:\n raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim)]\n\n return nn.Sequential(*conv_block)\n\n def forward(self, x):\n \"\"\"Forward function (with skip connections)\"\"\"\n out = x + self.conv_block(x) # add skip connections\n return out\n\n\nclass UnetGenerator(nn.Module):\n \"\"\"Create a Unet-based generator\"\"\"\n\n def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False):\n \"\"\"Construct a Unet generator\n Parameters:\n input_nc (int) -- the number of channels in input images\n output_nc (int) -- the number of channels in output images\n num_downs (int) -- the number of downsamplings in UNet. For example, # if |num_downs| == 7,\n image of size 128x128 will become of size 1x1 # at the bottleneck\n ngf (int) -- the number of filters in the last conv layer\n norm_layer -- normalization layer\n\n We construct the U-Net from the innermost layer to the outermost layer.\n It is a recursive process.\n \"\"\"\n super(UnetGenerator, self).__init__()\n # construct unet structure\n unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) # add the innermost layer\n for i in range(num_downs - 5): # add intermediate layers with ngf * 8 filters\n unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout)\n # gradually reduce the number of filters from ngf * 8 to ngf\n unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n self.model = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer) # add the outermost layer\n\n def forward(self, input):\n \"\"\"Standard forward\"\"\"\n return self.model(input)\n\n\nclass UnetSkipConnectionBlock(nn.Module):\n \"\"\"Defines the Unet submodule with skip connection.\n X -------------------identity----------------------\n |-- downsampling -- |submodule| -- upsampling --|\n \"\"\"\n\n def __init__(self, outer_nc, inner_nc, input_nc=None,\n submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False):\n \"\"\"Construct a Unet submodule with skip connections.\n\n Parameters:\n outer_nc (int) -- the number of filters in the outer conv layer\n inner_nc (int) -- the number of filters in the inner conv layer\n input_nc (int) -- the number of channels in input images/features\n submodule (UnetSkipConnectionBlock) -- previously defined submodules\n outermost (bool) -- if this module is the outermost module\n innermost (bool) -- if this module is the innermost module\n norm_layer -- normalization layer\n user_dropout (bool) -- if use dropout layers.\n \"\"\"\n super(UnetSkipConnectionBlock, self).__init__()\n self.outermost = outermost\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n if input_nc is None:\n input_nc = outer_nc\n downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4,\n stride=2, padding=1, bias=use_bias)\n downrelu = nn.LeakyReLU(0.2, True)\n downnorm = norm_layer(inner_nc)\n uprelu = nn.ReLU(True)\n upnorm = norm_layer(outer_nc)\n\n if outermost:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1)\n down = [downconv]\n up = [uprelu, upconv, nn.Tanh()]\n model = down + [submodule] + up\n elif innermost:\n upconv = nn.ConvTranspose2d(inner_nc, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n down = [downrelu, downconv]\n up = [uprelu, upconv, upnorm]\n model = down + up\n else:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n down = [downrelu, downconv, downnorm]\n up = [uprelu, upconv, upnorm]\n\n if use_dropout:\n model = down + [submodule] + up + [nn.Dropout(0.5)]\n else:\n model = down + [submodule] + up\n\n self.model = nn.Sequential(*model)\n\n def forward(self, x):\n if self.outermost:\n return self.model(x)\n else: # add skip connections\n return torch.cat([x, self.model(x)], 1)\n\n\nclass NLayerDiscriminator(nn.Module):\n \"\"\"Defines a PatchGAN discriminator\"\"\"\n\n def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d):\n \"\"\"Construct a PatchGAN discriminator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n ndf (int) -- the number of filters in the last conv layer\n n_layers (int) -- the number of conv layers in the discriminator\n norm_layer -- normalization layer\n \"\"\"\n super(NLayerDiscriminator, self).__init__()\n if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n\n kw = 4\n padw = 1\n sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]\n nf_mult = 1\n nf_mult_prev = 1\n for n in range(1, n_layers): # gradually increase the number of filters\n nf_mult_prev = nf_mult\n nf_mult = min(2 ** n, 8)\n sequence += [\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias),\n norm_layer(ndf * nf_mult),\n nn.LeakyReLU(0.2, True)\n ]\n\n nf_mult_prev = nf_mult\n nf_mult = min(2 ** n_layers, 8)\n sequence += [\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias),\n norm_layer(ndf * nf_mult),\n nn.LeakyReLU(0.2, True)\n ]\n\n sequence += [nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)] # output 1 channel prediction map\n self.model = nn.Sequential(*sequence)\n\n def forward(self, input):\n \"\"\"Standard forward.\"\"\"\n return self.model(input)\n\nclass NLayerProjDiscriminator(nn.Module):\n \"\"\"Defines a PatchGAN discriminator\"\"\"\n\n def __init__(self, input_nc, ndf=64, n_layers=3, num_classes=2, norm_layer=nn.BatchNorm2d, activation=F.relu):\n \"\"\"Construct a PatchGAN discriminator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n ndf (int) -- the number of filters in the last conv layer\n n_layers (int) -- the number of conv layers in the discriminator\n norm_layer -- normalization layer\n \"\"\"\n super(NLayerProjDiscriminator, self).__init__()\n if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n self.activation = activation\n\n kw = 4\n padw = 1\n sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]\n nf_mult = 1\n nf_mult_prev = 1\n for n in range(1, n_layers): # gradually increase the number of filters\n nf_mult_prev = nf_mult\n nf_mult = min(2 ** n, 8)\n sequence += [\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias),\n norm_layer(ndf * nf_mult),\n nn.LeakyReLU(0.2, True)\n ]\n\n nf_mult_prev = nf_mult\n nf_mult = min(2 ** n_layers, 8)\n sequence += [\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias),\n norm_layer(ndf * nf_mult),\n nn.LeakyReLU(0.2, True)\n ]\n\n self.model = nn.Sequential(*sequence)\n self.l_h = nn.Conv2d(ndf * nf_mult, 1, kernel_size=1, stride=1, padding=0) # output 1 channel prediction map\n\n if num_classes > 0:\n self.l_y = nn.Embedding(num_classes, ndf * nf_mult)\n\n def forward(self, x, y=None):\n \"\"\"Standard forward.\"\"\"\n h = self.model(x)\n output = self.l_h(h)\n if y is not None:\n output += torch.sum(self.l_y(y).unsqueeze(-1).unsqueeze(-1) * h, dim=1, keepdim=True)\n return output\n\n\nclass FCDiscriminator(nn.Module):\n\n\tdef __init__(self, feature_dim=2048, ndf = 64):\n\t\tsuper(FCDiscriminator, self).__init__()\n\n\t\tself.fc1 = nn.Linear(feature_dim, ndf)\n\t\tself.fc2 = nn.Linear(ndf, ndf*2)\n\t\tself.fc3 = nn.Linear(ndf*2, ndf*4)\n\t\tself.fc4 = nn.Linear(ndf*4, ndf*8)\n\t\tself.classifier = nn.Linear(ndf*8, 1)\n\n\t\tself.leaky_relu = nn.LeakyReLU(negative_slope=0.2, inplace=True)\n\n\n\tdef forward(self, x):\n\t\tx = self.fc1(x)\n\t\tx = self.leaky_relu(x)\n\t\tx = self.fc2(x)\n\t\tx = self.leaky_relu(x)\n\t\tx = self.fc3(x)\n\t\tx = self.leaky_relu(x)\n\t\tx = self.fc4(x)\n\t\tx = self.leaky_relu(x)\n\t\tx = self.classifier(x)\n\n\t\treturn x\n\n\nclass PixelDiscriminator(nn.Module):\n \"\"\"Defines a 1x1 PatchGAN discriminator (pixelGAN)\"\"\"\n\n def __init__(self, input_nc, ndf=64, norm_layer=nn.BatchNorm2d):\n \"\"\"Construct a 1x1 PatchGAN discriminator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n ndf (int) -- the number of filters in the last conv layer\n norm_layer -- normalization layer\n \"\"\"\n super(PixelDiscriminator, self).__init__()\n if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n\n self.net = [\n nn.Conv2d(input_nc, ndf, kernel_size=1, stride=1, padding=0),\n nn.LeakyReLU(0.2, True),\n nn.Conv2d(ndf, ndf * 2, kernel_size=1, stride=1, padding=0, bias=use_bias),\n norm_layer(ndf * 2),\n nn.LeakyReLU(0.2, True),\n nn.Conv2d(ndf * 2, 1, kernel_size=1, stride=1, padding=0, bias=use_bias)]\n\n self.net = nn.Sequential(*self.net)\n\n def forward(self, input):\n \"\"\"Standard forward.\"\"\"\n return self.net(input)\n"
] | [
[
"torch.mean",
"torch.optim.lr_scheduler.LambdaLR",
"torch.optim.lr_scheduler.CosineAnnealingLR",
"torch.cat",
"torch.sum",
"torch.nn.Embedding",
"torch.cuda.is_available",
"torch.nn.ReplicationPad2d",
"torch.nn.Dropout",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"torch.nn.Sigmoid",
"torch.rand",
"torch.optim.lr_scheduler.StepLR",
"torch.nn.Sequential",
"torch.nn.ConvTranspose2d",
"torch.nn.init.constant_",
"torch.nn.functional.binary_cross_entropy_with_logits",
"torch.nn.Conv2d",
"torch.nn.init.xavier_normal_",
"torch.exp",
"torch.nn.Linear",
"torch.nn.DataParallel",
"torch.nn.functional.mse_loss",
"torch.nn.init.normal_",
"torch.nn.LeakyReLU",
"torch.nn.ReflectionPad2d",
"torch.nn.Tanh",
"torch.nn.init.orthogonal_",
"torch.nn.ReLU",
"torch.nn.init.kaiming_normal_"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kimdonggyun/OCEANpy | [
"afab9867eaad1ae56e70beaca4463493f4ee2efb",
"afab9867eaad1ae56e70beaca4463493f4ee2efb"
] | [
"scripts/graphcre.py",
"scripts/data_export_func.py"
] | [
"# any functions for plots\n\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\nfrom matplotlib import dates as mdates\nfrom matplotlib.ticker import FormatStrFormatter\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nimport glob, os\nimport datetime\n\ndef deployment_constancy (df, title):\n '''\n create a plot to check weather LOKI was deployed constantly with depth\n '''\n depth = df['Depth (m)'].tolist()\n time = [datetime.datetime.strptime(x, '%Y-%m-%d %H:%M:%S') for x in df['Time_Loki (UTC)'].tolist()]\n\n fig, [ax1, ax2] = plt.subplots(2,1)\n\n # plot depth vs time\n ax1.scatter(time, depth, color='black', s=3)\n #ax1.set_xlabel('time (UTC)')\n ax1.set_ylabel('depth (m)')\n ax1.invert_yaxis()\n ax1.set_title(str(title+' (depth vs time)'), fontsize =10)\n ax1.xaxis.set_major_locator(mdates.MinuteLocator(interval=5)) # modify the date time x ticker frequency with interval(min) =5min\n ax1.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) # modify the datetime dicker format\n \n # plot velocity vs time\n velocity = []\n vel_time = []\n for i in range(0, len(time)-1):\n if time[i] != time[i+1]:\n each_vel = abs((depth[i]-depth[i+1])/((time[i]-time[i+1])/datetime.timedelta(seconds=1)))\n velocity.append(each_vel)\n vel_time.append(time[i])\n else:\n pass\n\n ax2.scatter(vel_time, velocity, color='black', s=3)\n ax2.set_xlabel('time (UTC)')\n ax2.set_ylabel('velocity (m/s)')\n ax2.set_title(str(title+' (velocity vs time)'), fontsize =10)\n ax2.xaxis.set_major_locator(mdates.MinuteLocator(interval=5)) # modify the date time x ticker frequency with interval(min) =5min\n ax2.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) # modify the datetime dicker format\n\n fig.tight_layout() #adjust subplots space\n \n os.chdir('/Users/dong/Library/Mobile Documents/com~apple~CloudDocs/Work/github/LOKIpy/plots')\n fig_name = str('dist_vel_'+title+'.pdf')\n plt.savefig(fig_name)\n plt.close()\n\ndef vertical_distribution_old (count_dict, title, min_depth, max_depth, depth_interval, water_vol):\n '''\n bins describes the depth interval\n density describes ratio, default: False\n align describes the location of histogram, default: right\n '''\n for org, count in count_dict.items():\n bins=np.arange(min_depth,max_depth, depth_interval)\n count_vol = [x/((max_depth/depth_interval)*depth_interval) for x in count]\n plt.barh(bins[:len(count_vol)], count_vol, align='edge', color='black', height = 10) # horizontal bar plot\n plt.xlabel('concentration (n/m3)')\n plt.ylabel('depth (m)')\n plt.gca().invert_yaxis()\n plt.title(org)\n \n os.chdir('/Users/dong/Library/Mobile Documents/com~apple~CloudDocs/Work/github/LOKIpy/plots')\n fig_name = str('concent_'+org+'_'+title+'.pdf')\n plt.savefig(fig_name)\n plt.close()\n\n\ndef vertical_each_org_distribution (each_df, count_dict, title, min_depth, max_depth, depth_interval, water_vol):\n '''\n bins describes the depth interval\n density describes ratio, default: False\n align describes the location of histogram, default: right\n work with dictionary\n this function works for station level\n '''\n # organize environmental data e.g. depth, temperature, salinity, oxygen\n depth = each_df['Depth (m)'].tolist()\n temperature = each_df['Temperature (°C)'].tolist()\n salinity = each_df['Salinity (psu)'].tolist()\n oxygen = each_df['Oxygen concentration (µM)'].tolist()\n\n fig, axs = plt.subplots(2,3, figsize = (15, 10))\n axs = axs.ravel()\n\n i = 0\n for org, count in count_dict.items():\n # add target data\n bins=np.arange(min_depth,max_depth, depth_interval)\n count_vol = [x/((max_depth/depth_interval)*depth_interval) for x in count]\n\n axs[i].barh(bins[:len(count_vol)], count_vol, align='edge', color='black', height = 10) # horizontal bar plot\n axs[i].set_xlabel('concentration (n/m3)')\n axs[i].set_ylabel('depth (m)')\n axs[i].invert_yaxis()\n axs[i].set_title(org, y =1.0) # subplot title\n axs[i].xaxis.set_major_formatter(FormatStrFormatter('%.2f'))\n\n # add environmental data\n temp_ax = axs[i].twiny()\n temp_ax.plot(temperature, depth, color='red')\n temp_ax.set_xlabel('temperature', color='red')\n \n sal_ax = axs[i].twiny()\n sal_ax.plot(salinity, depth, color='green')\n sal_ax.xaxis.set_ticks_position('bottom')\n sal_ax.xaxis.set_label_position('bottom')\n sal_ax.spines['bottom'].set_position(('outward', 40))\n sal_ax.set_xlabel('salinity (PSU)', color = 'green')\n \n # change tick and colors\n axs[i].xaxis.set_ticks_position('top') # change the position of each spines of axis\n axs[i].xaxis.set_label_position('top')\n temp_ax.xaxis.set_ticks_position('bottom')\n temp_ax.xaxis.set_label_position('bottom')\n\n temp_ax.spines['bottom'].set_color('red') # change the location color of spines and ticks\n temp_ax.tick_params(axis='x', color='red')\n sal_ax.spines['bottom'].set_color('green')\n sal_ax.tick_params(axis='x', color='green')\n\n axs[i].set_xticks(np.arange(0, max(count_vol) + 0.05, 0.05))\n\n i += 1\n \n fig.tight_layout(pad=3) # adjust layout of subplots\n plt.suptitle(title, y = 0.99) # main title\n os.chdir('/Users/dong/Library/Mobile Documents/com~apple~CloudDocs/Work/github/LOKIpy/plots')\n fig_name = str('concent_'+title+'.pdf')\n plt.savefig(fig_name)\n plt.close()\n\n\ndef stacked_vertical_distribution (mask_dict, title, min_depth, max_depth, depth_interval, water_vol):\n i = False\n bins=np.arange(min_depth,max_depth, depth_interval)\n\n org_list = []\n\n fig, ax = plt.subplots()\n for org, count in mask_dict.items():\n org_list.append(org)\n # sum each element in count to botton in bar\n count_vol = [x/((max_depth/depth_interval)*depth_interval) for x in count]\n\n if i == False:\n bar_bottom = [0]*len(count)\n i = True\n \n ax.barh(bins[:len(count_vol)], count_vol, height = 10, align='edge', left=np.array(bar_bottom)) # horizontal bar plot\n bar_bottom = [a+b for a, b in zip(bar_bottom, count_vol)]\n\n ax.invert_yaxis()\n ax.set_title(title)\n ax.set_xlabel('concentration (n/m3)')\n ax.set_ylabel('depth (m)')\n ax.legend(org_list, loc ='upper right')\n ax.xaxis.set_major_formatter(FormatStrFormatter('%.2f'))\n\n os.chdir('/Users/dong/Library/Mobile Documents/com~apple~CloudDocs/Work/github/LOKIpy/plots')\n fig_name = str('stacked_'+title+'.pdf')\n plt.savefig(fig_name)\n plt.close()\n\n\ndef comp_vertical_distribution (ecotaxa_df, min_depth, max_depth, depth_interval):\n '''\n create a plot with two vertical profile to compare between them\n '''\n left_depth = np.asarray(ecotaxa_df['Depth (m)'])\n right_depth = np.asarray(ecotaxa_df['Depth (m)'])\n\n fig, [ax1, ax2] = plt.subplots(1,2)\n ax1.hist(left_depth, bins=np.arange(min_depth,max_depth, depth_interval), orientation='horizontal', color='black')\n ax1.invert_yaxis() # invert axis subplot level\n ax1.invert_xaxis()\n ax1.set_xlabel('counts') # add label on subplot level\n ax1.set_ylabel('depth [m]')\n\n ax2.hist(left_depth, bins=np.arange(min_depth,max_depth, depth_interval), orientation='horizontal', color='black')\n ax2.invert_yaxis()\n ax2.set_xlabel('counts')\n #ax2.set_ylabel('depth [m]')\n\n plt.show()\n plt.close()\n",
"'''\nThis function includes three separate definitions\n1. Export and adjust data from LOKI_browser to Zoomie\n2. Export and adjust data from Zoomie to EcoTaxa\n3. Export and adjust data from EcoTaxa to Data storage\n\nCreated by : Dong-gyun KIM\nContact : [email protected]\nCreation date : 02.07.2020\n'''\nfrom tkinter.filedialog import askdirectory, askopenfilename\nfrom pathlib import Path\nimport pandas as pd\nimport os\nimport numpy as np\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as md\nimport re\nimport glob\nimport psycopg2 as pgsql\nimport pandas.io.sql as sql\nfrom sqlalchemy import create_engine\nfrom tkinter import Tk\nimport sqlalchemy\n\ndef Browser_to_Zoomie():\n '''\n This function is created to modify the metadata from LOKI_browser for the later use of Zoomie\n As a return, a CSV file will be generated on the working dir\n '''\n # set the working directory\n #path_to_data = input('type path of the data: ')\n Tk().withdraw()\n print('choose project directory')\n path_to_data = askdirectory()\n work_dir = Path(path_to_data).expanduser()\n os.chdir(work_dir)\n \n # conmbine all *_Export.txt files in one dataframe and sort it by 'img_file_name'\n export_df = []\n for export_filename in work_dir.glob('*_Export.txt'):\n if '._' not in str(export_filename):\n print(export_filename)\n datdf = pd.read_csv(export_filename, sep='\\t', engine='python', decimal=',')\n datdf = datdf.loc[datdf['Index'] != 'Evaluation']\n export_df.append(datdf)\n export_df = pd.concat(export_df)\n export_df.columns = ['object_index','object_cruise',\n 'object_vessel_name','object_station','object_haul',\n 'object_date','object_time','object_lat','object_lon','object_bottom_depth',\n 'object_depth_min','object_pressure','object_temperature','object_salinity',\n 'object_conductivity','object_oxygen_concentration','object_temperature_oxsens',\n 'object_oxygen_saturation','object_chlorophyll_a','object_light','object_speed',\n 'object_Dr._Haardt_fluorescence_channel_A','object_Dr._Haardt_fluorescence_channel_B',\n 'object_Dr._Haardt_fluorescence_channel_C','object_Dr._Haardt_fluorescence_channel_D',\n 'object_speed_over_ground','object_speed_in_water','object_frames',\n 'object_automatic_classification','object_manual_classification','object_area_px',\n 'object_form','object_area','object_lenght','object_width','object_convexity',\n 'object_structure','object_graymean','object_kurtosis','object_skewness',\n 'object_Hu_moment_1','object_Hu_moment_2','object_Hu_moment_3','object_Hu_moment_4',\n 'object_Hu_moment_5','object_Hu_moment_6','object_Hu_moment_7',\n 'object_fourier_descriptor_01','object_fourier_descriptor_02',\n 'object_fourier_descriptor_03','object_fourier_descriptor_04',\n 'object_fourier_descriptor_05','object_fourier_descriptor_06',\n 'object_fourier_descriptor_07','object_fourier_descriptor_08',\n 'object_fourier_descriptor_09','object_fourier_descriptor_10',\n 'img_file_name']\n\n export_df.sort_values(by=['img_file_name'])\n export_df.reset_index(drop=True, inplace=True)\n\n\n # create same table as export_df but with columns for zoomie (old:new)\n zoomie_cols_name_dict = {'object_lenght':'Length', 'object_width':'Width', 'object_area_px':'Areapix', 'object_form':'Form','object_area':'Area', 'object_convexity':'Convex', 'object_structure':'Structure', 'object_graymean':'Gray', 'object_kurtosis':'Kurtosis', 'object_skewness':'Skew',\n 'object_Hu_moment_1':'Hu1', 'object_Hu_moment_2':'Hu2', 'object_Hu_moment_3':'Hu3', 'object_Hu_moment_4':'Hu4', 'object_Hu_moment_5':'Hu5', 'object_Hu_moment_6':'Hu6', 'object_Hu_moment_7':'Hu7', \n 'object_fourier_descriptor_01':'Fodec01', 'object_fourier_descriptor_02':'Fodec02', 'object_fourier_descriptor_03':'Fodec03', 'object_fourier_descriptor_04':'Fodec04', 'object_fourier_descriptor_05':'Fodec05', 'object_fourier_descriptor_06':'Fodec06', 'object_fourier_descriptor_07':'Fodec07', 'object_fourier_descriptor_08':'Fodec08', 'object_fourier_descriptor_09':'Fodec09', 'object_fourier_descriptor_10':'Fodec10',\n 'img_file_name':' Image ', 'object_index':'ObjNoBrowser', 'object_cruise':'Cruise', 'object_station':'Station', 'object_haul':'Haul', 'object_date':'Date','object_time':'Time', 'object_pressure':' Pressure ', 'object_depth_min':'Depth', 'object_salinity':' Salinity', 'object_conductivity':' Conductivity ', 'object_oxygen_concentration':' Oxygenconc', 'object_temperature_oxsens':' Tempoxy', 'object_oxygen_saturation':' Oxysat ', 'object_Dr._Haardt_fluorescence_channel_A':'FLuoa ', 'object_manual_classification':'Manuclass '}\n \n zoomie_df = export_df.rename(columns=zoomie_cols_name_dict)\n zoomie_df = zoomie_df.assign(manualLength2=np.nan, manualWidth2=np.nan, posx=np.nan, posy=np.nan, milliseconds=np.nan, timestamp=np.nan, state=np.nan, id=np.nan, processed=np.nan, group_id=np.nan, deleted=np.nan)\n # modify the file format from .bmp to .png on ' Image ' and datatype of certain columns\n zoomie_df[' Image '] = zoomie_df[' Image '].apply(lambda x: x.replace('.bmp', '.png')) \n\n # remain only necessary columns\n zoomie_df = zoomie_df[['Length','Width','Areapix','Form','Area','Convex','Structure','Gray','Kurtosis','Skew','Hu1','Hu2','Hu3','Hu4','Hu5','Hu6','Hu7',\n 'Fodec01','Fodec02','Fodec03','Fodec04','Fodec05','Fodec06','Fodec07','Fodec08','Fodec09','Fodec10',' Image ',\n 'ObjNoBrowser','Cruise','Station','Haul','Date','Time',' Pressure ','Depth',' Salinity',' Conductivity ',' Oxygenconc',' Tempoxy',' Oxysat ',\n 'FLuoa ','Manuclass ','manualLength2','manualWidth2','posx','posy','milliseconds','timestamp','state','id','processed','group_id','deleted']]\n\n # save the file as CSV\n zoomie_df['Station'] = input('type Cruise-station-haul (e.g PS107-22-5):')\n\n meta_file_name = str(zoomie_df.loc[1, 'Station'])+'_Zoomie.csv'\n zoomie_df.to_csv(meta_file_name, sep=',', index=False)\n print('Zoomie.csv created')\n\n\n\n\ndef Zoomie_to_Ecotaxa():\n '''\n This function is created to modify the results from Zoomie for the later use of Ecotaxa\n As a return, a txt file will be generated on the working dir\n '''\n # set the working directory\n # path_to_data = input('type path of the data: ')\n Tk().withdraw()\n print('choose project directory')\n path_to_data = askopenfilename()\n work_dir = os.path.dirname(path_to_data)\n os.chdir(work_dir)\n\n zoomie_cols = ['object_length','object_width','object_area_px','object_form','object_area','object_convexity',\n 'object_structure','object_graymean','object_kurtosis','object_skewness','object_Hu_moment_1',\n 'object_Hu_moment_2','object_Hu_moment_3','object_Hu_moment_4','object_Hu_moment_5','object_Hu_moment_6',\n 'object_Hu_moment_7','object_fourier_descriptor_01','object_fourier_descriptor_02',\n 'object_fourier_descriptor_03','object_fourier_descriptor_04','object_fourier_descriptor_05',\n 'object_fourier_descriptor_06','object_fourier_descriptor_07','object_fourier_descriptor_08',\n 'object_fourier_descriptor_09','object_fourier_descriptor_10','img_file_name','object_index',\n 'object_cruise','object_station','object_haul','object_date','object_time','object_pressure',\n 'object_depth_min','object_salinity','object_conductivity','object_oxygen_concentration',\n 'object_temperature_oxsens','object_oxygen_saturation','object_Dr._Haardt_fluorescence_channel_A',\n 'object_manual_classification','object_manual_length','object_manual_width','object_posx','object_posy','object_milliseconds',\n 'object_timestamp','object_zoomie_state','object_zoomie_deleted','object_zoomie_id','object_zoomie_proc','object_zoomie_group_id']\n \n zoomiedf = pd.read_csv(path_to_data, names=zoomie_cols ,sep='\";\"|;\"|;', header=None, engine='python') #### edited 'sep' part\n\n ########################################################################################################################\n zoomiedf = zoomiedf.replace('\"', '', regex=True) ##### added\n zoomiedf['object_Hu_moment_5'] = zoomiedf['object_Hu_moment_5'].replace(',', '.', regex=True) ##### added\n zoomiedf['object_Hu_moment_7'] = zoomiedf['object_Hu_moment_7'].replace(',', '.', regex=True) ##### added\n zoomiedf['object_zoomie_group_id'] = zoomiedf['object_zoomie_group_id'].replace(',', '', regex=True) ##### added\n zoomiedf['object_station'] = zoomiedf['object_station'].replace('_', '-', regex=True) ##### added\n zoomiedf['object_cruise'] = zoomiedf['object_cruise'].replace(' data', '', regex=True) ##### added\n \n ###### bad image to 0 #######\n if 0 in zoomiedf['object_zoomie_deleted'].values:\n pass\n else:\n zoomiedf['object_zoomie_deleted'] = 0 ## added set all 0 which is considered as real data\n \n bad_dir = os.path.join(work_dir, 'bad')\n bad_img_list = os.listdir(bad_dir)\n for img in bad_img_list:\n index = zoomiedf.loc[zoomiedf['img_file_name'] == img].index[0]\n zoomiedf['object_zoomie_deleted'].iloc[index] = 1 # convert 0 to 1 for bad images\n\n ########################################################################################################################\n\n # modifing object_Hu_moment_* columns\n object_Hu_moment_col_list = [col for col in zoomiedf.columns if 'object_Hu_moment' in col]\n for object_Hu_moment_col in object_Hu_moment_col_list:\n zoomiedf[object_Hu_moment_col] = zoomiedf['object_Hu_moment_1']\n\n # remove duplicated images and empty images estimated by zoomie\n zoomiedf = zoomiedf[~zoomiedf['object_zoomie_state'].str.contains('double')]\n zoomiedf = zoomiedf[zoomiedf['object_zoomie_deleted'] != 1]\n\n # Replace extension (.bmp to .png)\n zoomiedf['img_file_name'] = zoomiedf['img_file_name'].apply(lambda x:x.replace('bmp', 'png'))\n\n # Add Date and Time information from file name\n zoomiedf['object_date'] = zoomiedf['img_file_name'].apply(lambda x: str(x.split(' ')[0]))\n zoomiedf['object_time'] = zoomiedf['img_file_name'].apply(lambda x: str(x.split(' ')[1]))\n\n # sort dataframe by img_file_name\n zoomiedf.sort_values(by = ['img_file_name'], inplace=True)\n\n # Adding new columns and correcting haul information\n vessel, gear, lat, lon, haul = 'Polarstern', 'LOKI', '79.033598', '6.999869', '6'\n zoomiedf['object_vessel_name'], zoomiedf['acq_instrument'], zoomiedf['object_lat'], zoomiedf['object_lon'], zoomiedf['object_haul'] = vessel, gear, lat, lon, haul\n zoomiedf['object_id'] = zoomiedf['img_file_name'].apply(lambda x:str(x)[0:37])\n zoomiedf['acq_id'] = 'NA'\n\n # remain necessary columns\n zoomiedf = zoomiedf[['object_length','object_width','object_area_px','object_form','object_area','object_convexity','object_structure','object_graymean','object_kurtosis','object_skewness',\n 'object_Hu_moment_1','object_Hu_moment_2','object_Hu_moment_3','object_Hu_moment_4','object_Hu_moment_5','object_Hu_moment_6','object_Hu_moment_7','object_fourier_descriptor_01',\n 'object_fourier_descriptor_02','object_fourier_descriptor_03','object_fourier_descriptor_04','object_fourier_descriptor_05','object_fourier_descriptor_06','object_fourier_descriptor_07',\n 'object_fourier_descriptor_08','object_fourier_descriptor_09','object_fourier_descriptor_10','img_file_name','object_index','object_cruise','object_station','object_haul','object_date',\n 'object_time','object_pressure','object_depth_min','object_salinity','object_conductivity','object_oxygen_concentration','object_temperature_oxsens','object_oxygen_saturation',\n 'object_Dr._Haardt_fluorescence_channel_A','object_manual_classification','object_posx','object_posy','object_milliseconds','object_timestamp','object_zoomie_state','object_id','object_vessel_name',\n 'acq_instrument','object_lat','object_lon', 'acq_id']]\n\n # insert data type info at the first row and change data type\n zoomiedf_col_list = list(zoomiedf)\n dtype = ['[f]','[f]','[f]','[f]','[f]','[f]','[f]','[f]','[f]','[f]',\n '[f]','[f]','[f]','[f]','[f]','[f]','[f]','[f]',\n '[f]','[f]','[f]','[f]','[f]','[f]','[f]','[f]','[f]','[t]','[f]','[t]','[t]','[f]','[f]',\n '[f]','[f]','[f]','[f]','[f]','[f]','[f]','[f]',\n '[f]','[t]','[f]','[f]','[f]','[f]','[t]','[t]','[t]',\n '[t]','[f]','[f]','[t]']\n \n zoomiedf = pd.DataFrame(np.insert(zoomiedf.values, 0, values=dtype, axis =0), columns = zoomiedf_col_list)\n for col_name in zoomiedf_col_list:\n if (col_name == 'object_date') | (col_name == 'object_time'):\n #zoomiedf[col_name].iloc[1:] = pd.to_datetime(zoomiedf[col_name].iloc[1:])\n continue\n elif str(zoomiedf[col_name].iloc[0]) == '[f]':\n zoomiedf[col_name].iloc[1:] = pd.to_numeric(zoomiedf[col_name].iloc[1:])\n elif str(zoomiedf[col_name].iloc[0]) == '[t]':\n zoomiedf[col_name].iloc[1:] = zoomiedf[col_name].iloc[1:].astype(str)\n print(zoomiedf)\n # save as table\n meta_file_name = 'ecotaxa.'+str(zoomiedf.loc[2, 'object_station'])+'.txt'\n zoomiedf.to_csv(meta_file_name, sep='\\t', index=False, decimal='.')\n print('ecotaxa.txt created')\n\n\ndef Ecotaxa_to_Storage():\n '''\n This function is created to modify the results from Ecotaxa for the later use of Data storage\n As a return, a txt file will be generated on the working dir\n '''\n\n # set the working directory\n path_to_data = input('type path of the data: ')\n work_dir = Path(path_to_data).expanduser()\n os.chdir(work_dir)\n\n # Add missing data\n haul, region, detail_location, bottom_depth = 'Type Haul', 'Type Region', 'Type location detail', 'Type bottom depth'\n\n\n # Reading in Ecotada file\n for ecotaxa_export in work_dir.glob('*Ecotaxa_Export.tsv'):\n ecotaxadf = pd.read_csv(ecotaxa_export, sep='\\t', encoding= 'unicode_escape', dtype={'complement_info':'string'})\n\n # create new df for data storage with new column names (old:new)\n datastorage_cols_name_dict = {'object_vessel_name':'Vessel', 'object_cruise':'Cruise', 'object_station':'Station', 'object_date':'Date (UTC)', 'object_time':'Time LOKI (UTC)', 'object_lat':'Latitude', 'object_lon':'Longitude',\n 'object_depth_min':'Depth (m)', 'object_temperature_oxsens':'Temperature (°C)', 'object_salinity':'Salinity (psu)', 'object_conductivity':'Conductivity (mS cm-1)', 'object_oxygen_concentration':'Oxygen concentration (µM)',\n 'object_oxygen_saturation':'Oxygen saturation (%)', 'object_dr._haardt_fluorescence_channel_a':'Fluorescence', 'object_annotation_category':'Classif', 'object_area_px':'Area (pixels)', 'object_area':'Area (mm2)', 'object_length':'Length (mm)', 'object_width':'Width (mm)',\n 'object_id':'Image file name', 'object_annotation_person_name':'Scientist'} \n datastorage_df = ecotaxadf.rename(columns=datastorage_cols_name_dict)\n datastorage_df['Haul'] = haul\n datastorage_df['Region'] = region\n datastorage_df['Detail_Location'] = detail_location\n datastorage_df['Bottom depth (m)'] = bottom_depth\n\n # add and modify the columns (consider 'assign' function here later)\n datastorage_df['Manual classification'], datastorage_df['Developmental stage'] = '', ''\n datastorage_df['Image file name'] = datastorage_df['Image file name'].apply(lambda x: str(x)+'.png')\n\n # date and time format modification\n datastorage_df['Time LOKI (UTC)'] = datastorage_df['Image file name'].apply(lambda x: pd.to_datetime(x.split(' ')[1], format='%H%M%S').strftime('%H:%M:%S'))\n datastorage_df['Date (UTC)'] = datastorage_df['Image file name'].apply(lambda x: pd.to_datetime(x.split(' ')[0], format='%Y%m%d').strftime('%d.%m.%Y'))\n\n # classification\n # correct 'like' for normal description\n datastorage_df['Classif'] = datastorage_df['Classif'].apply(lambda x: str(x.replace('like<','')+' like') if 'like' in x else x)\n # Manual and parent columns modification (separate Classsif to parent category and manual classification)\n exception_list = ['Ctenophora<Metazoa','egg<other'] # if the lower cat should go to manual classification, add the variable of corresponding Classif here\n for df_index, df_line in datastorage_df.iterrows():\n if '<' not in df_line['Classif']:\n datastorage_df.loc[df_index, 'Manual classification'] = df_line['Classif']\n else:\n lower_cat = df_line['Classif'].split('<')[0]\n higher_cat = df_line['Classif'].split('<')[1]\n if any(x in df_line['Classif'] for x in exception_list):\n datastorage_df.loc[df_index, 'Manual classification'] = lower_cat\n elif 'artefact' in df_line['Classif']:\n datastorage_df.drop(df_index, axis=1)\n else:\n datastorage_df.loc[df_index, 'Manual classification'] = higher_cat\n datastorage_df.loc[df_index, 'Developmental stage'] = lower_cat\n\n datastorage_df.reset_index(drop=True, inplace=True)\n\n #datastorage_df['Manual classification'] = datastorage_df['Classif'].apply(lambda x:x.split('<')[0] if '<' in x else x)\n #datastorage_df['Developmental stage'] = datastorage_df['Classif'].apply(lambda x:x.split('<')[1] if '<' in x else '')\n # Extract developmental stages and correct the manual classification (needed to further modify column :targetParCat)\n mask_dict = {'female':'female', 'male':'male', 'female+male':'female+male', 'CIstage':'CI', 'CIIstage':'CII', 'CIIIstage':'CIII',\n 'CIVstage':'CIV','CVstage':'CV', 'head':'head', 'middle':'middle','tail':'tail', 'nauplii':'NI-NVI', 'larvae':'larvae',\n 'calyptopsis':'calyptopis', 'female/eggs':'female with eggs', 'female with ectoparasites':'female with ectoparasites',\n 'calyptopis':'calyptopis', 'CVstage with ectoparasites':'CV with ectoparasites', 'antenna':'antenna', 'transparent':'Exuvia'}\n for old_anot, new_anot in mask_dict.items():\n if old_anot == 'transparent':\n datastorage_df.loc[datastorage_df['Manual classification'] == old_anot, 'Manual classification'] = new_anot\n else:\n datastorage_df.loc[datastorage_df['Developmental stage'] == old_anot, 'Developmental stage'] = new_anot\n\n # remain necessary columns\n datastorage_df = datastorage_df[['Vessel','Cruise','Station','Haul','Region','Detail_Location','Date (UTC)','Time LOKI (UTC)','Latitude','Longitude',\n \t'Bottom depth (m)',\t'Depth (m)','Temperature (°C)','Salinity (psu)','Conductivity (mS cm-1)','Oxygen concentration (µM)',\n 'Oxygen saturation (%)','Fluorescence','Manual classification','Developmental stage','Area (pixels)','Area (mm2)','Length (mm)',\n 'Width (mm)','Image file name','Scientist']]\n\n # save file to xlsx format\n meta_file_name = str('LOKI_'+datastorage_df['Station'].iloc[2]+'_'+datastorage_df['Haul'].iloc[2]+'.xlsx').replace('-', '_')\n datastorage_df.to_excel(meta_file_name, index=False)\n\n \n\ndef Merge_Telemetry():\n # merge telemetry data on telemetrie file as one .txt file\n #path_to_data = input('Type full path to telemetrie:')\n path_to_data = '/Users/dong/Library/Mobile Documents/com~apple~CloudDocs/Work/LOKI/Cruises/0022_PS107-22'\n work_dir = Path(path_to_data).expanduser()\n \n # loop through all Haul in one project\n for telemetrie in os.walk(work_dir):\n if 'Telemetrie' in telemetrie[1]:\n telemetrie_path = Path(os.path.join(telemetrie[0], 'Telemetrie'))\n os.chdir(telemetrie_path)\n\n # combine all .tmd files to one data frame\n Telemetry_df = pd.DataFrame()\n for tmd in glob.glob(str(Path(telemetrie_path)/'*.tmd')):\n tmddf = pd.read_csv(tmd, sep=';', header=None, decimal='.').iloc[:,1] # only use second column\n tmddf.loc[-1] = str(tmd).split(os.sep)[-1].split('.')[0] # add filename (= datetime) on the last row\n tmddf.sort_index(inplace=True)\n Telemetry_df = pd.concat([Telemetry_df, tmddf], axis=1)\n\n # Transposing row <> column and reset index\n Telemetry_df = Telemetry_df.T\n Telemetry_df = Telemetry_df.reset_index(drop=True)\n\n # Set column names and sort by file value (datetime)\n Telemetry_df.columns = ['file', 'DEVICE', 'GPS_LONG', 'GPS_LAT', 'PRESS', 'TEMP', 'OXY_CON', 'OXY_SAT',\n 'OXY_TEMP','COND_COND', 'COND_TEMP', 'COND_SALY', 'COND_DENS', \n 'COND_SSPEED', 'FLOUR_1', 'LOKI_REC', 'LOKI_PIC', \n 'LOKI_FRAME', 'CAM_STAT', 'HOUSE_STAT', 'HOUSE_T1', 'HOUSE_T2', 'HOUSE_VOLT']\n Telemetry_df = Telemetry_df.sort_values('file')\n\n # replace comma to point\n Telemetry_df = Telemetry_df.apply(lambda x:x.str.replace(',', '.'))\n\n # add Nan to empty columns\n empty_cols = [col for col in Telemetry_df.columns if Telemetry_df[col].isnull().all()]\n for col in empty_cols:\n Telemetry_df[col] = np.nan\n\n # save file with cruise and haul info\n cruise_name, haul_number = str(telemetrie_path).split(os.sep)[-4], re.findall('\\d+', str(telemetrie_path).split(os.sep)[-3])[0]\n Telemetry_df.to_csv('%s-%s_telemetry.tsv'%(cruise_name, haul_number,), sep='\\t', index=False)\n\n # show to result as plot\n #time = dates.date2num(Telemetry_df['Date/Time'].tolist())\n\n #plt.plot('PRESS', data=Telemetry_df)\n #plt.ylabel('pressure')\n #plt.xlabel('time')\n #plt.show()\n #plt.close()\n\nif __name__ == \"__main__\":\n pass"
] | [
[
"matplotlib.pyplot.gca",
"matplotlib.dates.DateFormatter",
"matplotlib.dates.MinuteLocator",
"matplotlib.pyplot.title",
"numpy.asarray",
"numpy.arange",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.close",
"matplotlib.ticker.FormatStrFormatter",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.suptitle",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
],
[
"pandas.concat",
"pandas.read_csv",
"pandas.DataFrame",
"numpy.insert",
"pandas.to_numeric"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
mahnooranjum/Programming_DataScience | [
"f7a4215d4615b3f8460c3a1944a585628cf6930d",
"f7a4215d4615b3f8460c3a1944a585628cf6930d",
"f7a4215d4615b3f8460c3a1944a585628cf6930d"
] | [
"DataGeneration_DataScience/G6_XXC_circle.py",
"MachineLearningPyFiles_DataScience/demo33_adaboostclassificationspamdetection.py",
"FeatureEngineeringPy_DataScience/demo153_rarecategories.py"
] | [
"from sklearn.datasets.samples_generator import make_moons\nfrom sklearn.datasets.samples_generator import make_circles\nfrom sklearn.datasets.samples_generator import make_blobs\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\n\n###### CIRCLES #########\n# generate 2d classification dataset\nn = 10000\nX, y = make_circles(n_samples=n, noise=0.05)\n# scatter plot, dots colored by class value\ndf = pd.DataFrame(dict(x=X[:,0], y=X[:,1], label=y))\ncolors = {0:'red', 1:'blue'}\nfig, ax = plt.subplots()\ngrouped = df.groupby('label')\nfor key, group in grouped:\n group.plot(ax=ax, kind='scatter', x='x', y='y', label=key, color=colors[key])\nplt.show()\ndatadict = {'X1': X[:,0],'X2' : X[:,1], 'target': y}\ndf = pd.DataFrame(data=datadict)\ndf.to_csv('G6.csv')",
"\n\n# Dataset by : https://www.kaggle.com/venky73/spam-mails-dataset\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nsns.set_style('whitegrid')\n\ndef evaluate(y_test,y_pred):\n # Making the Confusion Matrix\n from sklearn.metrics import confusion_matrix\n con_mat = confusion_matrix(y_test, y_pred)\n print(\"===================================================\")\n print(con_mat)\n from sklearn.metrics import classification_report\n print(\"===================================================\")\n print(classification_report(y_test, y_pred))\n print(\"===================================================\")\n\n # Get accuracy\n from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n print('Accuracy score: ', format(accuracy_score(y_test, y_pred)))\n print('Precision score: ', format(precision_score(y_test, y_pred)))\n print('Recall score: ', format(recall_score(y_test, y_pred)))\n print('F1 score: ', format(f1_score(y_test, y_pred)))\n\n\"\"\"## Get the dataset\"\"\"\n\nimport pandas as pd\ndata = pd.read_csv('sample_data/spam_ham_dataset.csv')\ndata.head()\n\ny = data.label_num.values\n\nX = data.text\n\nsns.countplot(data = data, x = 'label');\n\nimport nltk\nfrom nltk.corpus import stopwords \nfrom nltk.tokenize import word_tokenize\nnltk.download('punkt')\nnltk.download('stopwords')\n\n# STEP 1 : REMOVE STOP WORDS\nstop_words = set(stopwords.words('english')) \nX = X.apply(lambda email: ' '.join([ word for word in word_tokenize(email) if not word in stop_words]))\n\n# STEP 2 : REMOVE SUBJECT\nX = X.apply(lambda email: ' '.join([ word for word in word_tokenize(email) if not word in [\"Subject\"]]))\n\n# STEP 2 : REMOVE NUMBERS\nX = X.apply(lambda email: ' '.join([ word for word in word_tokenize(email) if not word.isdigit()]))\n\n# punctuations = list('!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~')\n# punctuations\n\n# STEP 3 : REMOVE PUNCTUATIONS\n# X = X.apply(lambda email: ' '.join([ word for word in word_tokenize(email) if not word in punctuations]))\n\nX\n\nfrom sklearn.feature_extraction.text import CountVectorizer\ncount_vector = CountVectorizer()\nX_bow = count_vector.fit_transform(X.astype(str))\n#count_vector.get_feature_names()\n\nX_bow = X_bow.toarray()\n\nX_bow\n\nX_bow = pd.DataFrame(X_bow, columns = count_vector.get_feature_names())\n\nX_bow['hey'].count()\n\n# TRAIN TEST SPLIT\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X_bow, y, test_size = 0.2)\n\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)\n\nX_train = X_train.values\nX_test = X_test.values\n\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nclassifier = AdaBoostClassifier(base_estimator = DecisionTreeClassifier(max_depth = 10), n_estimators = 50)\nclassifier.fit(X_train,y_train)\ny_pred = classifier.predict(X_test)\ny_pred = np.round(y_pred).flatten()\n\n\n\n# Let's see how many spam emails we have \nprint(str(y_train.sum()) + \" out of \" + str(len(y_train)) + \" were spam\")\n\nevaluate(y_test,y_pred)\n\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nclassifier = AdaBoostClassifier()\nclassifier.fit(X_train,y_train)\ny_pred = classifier.predict(X_test)\ny_pred = np.round(y_pred).flatten()\nevaluate(y_test,y_pred)",
"# -*- coding: utf-8 -*-\n\"\"\"Demo153_RareCategories.ipynb\n\n## Rare Categories\n\n- Labels \n\n- The number of labels in the dataset are different \n\n- __high cardinality__ refers to uniqueness of data values \n\n- The lower the cardinality, the more duplicated elements in a column\n\n- A column with the lowest possible cardinality would have the same value for every row\n\n- Highly cardinal variables dominate tree based algorithms\n\n- Labels may only be present in the training data set, but not in the test data set\n\n- Labels may appear in the test set that were not present in the training set\n\n\n__Tree methods are biased towards variables with many labels__\n\"\"\"\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\n\nfrom google.colab import drive\ndrive.mount('/content/gdrive')\ndata = pd.read_csv(\"gdrive/My Drive/Colab Notebooks/FeatureEngineering/train.csv\")\n\ncat_cols = ['Name', 'Sex', 'Ticket', 'Cabin', 'Embarked']\n\nfor i in cat_cols:\n print('Number of categories in the variable {}: {}'.format(i,len(data[i].unique())))\n\nprint('Total rows: {}'.format(len(data)))\n\ndata['Sex'].value_counts()\n\ndata['Cabin_processed'] = data['Cabin'].astype(str).str[0]\ndata['Cabin_processed_X'] = data['Cabin'].astype(str).str[1]\ncat_cols = [ 'Sex', 'Embarked', 'Cabin_processed']\n\nfor i in cat_cols:\n sns.catplot(x=i, kind='count', data=data)\n\ndata['Cabin_processed'].value_counts() / len(data)\n\n\n\nfor i in cat_cols:\n sns.catplot(x=i,data=data, hue='Survived', kind='count', palette=\"ch:.25\")\n\n\"\"\"### Transform Rare Labels\"\"\"\n\n_temp = pd.Series(data['Cabin_processed'].value_counts() / len(data))\n_temp.sort_values(ascending=False)\n_temp\n\n_temp = pd.Series(data['Cabin_processed'].value_counts() / len(data))\n_temp\n\nfor i in _labels:\n data['Cabin_processed'].replace(i, 'rare', inplace=True)\n\n_temp = pd.Series(data['Cabin_processed'].value_counts() / len(data))\n_temp"
] | [
[
"sklearn.datasets.samples_generator.make_circles",
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplots",
"pandas.DataFrame"
],
[
"pandas.read_csv",
"sklearn.metrics.recall_score",
"sklearn.metrics.precision_score",
"sklearn.metrics.confusion_matrix",
"sklearn.model_selection.train_test_split",
"numpy.round",
"sklearn.feature_extraction.text.CountVectorizer",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.ensemble.AdaBoostClassifier",
"sklearn.metrics.f1_score",
"sklearn.metrics.classification_report",
"sklearn.metrics.accuracy_score"
],
[
"pandas.read_csv"
]
] | [
{
"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": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
thatch/mlflow-extend | [
"08cf76db3ba787f396b922d27877db43c2881a91"
] | [
"mlflow_extend/logging.py"
] | [
"import json\nimport os\nimport pickle\nimport tempfile\nfrom contextlib import contextmanager\nfrom typing import Any, Generator, Optional, Union\n\nimport mlflow\nimport numpy as np\nimport pandas as pd\nimport plotly\nimport yaml\nfrom matplotlib import pyplot as plt\nfrom plotly import graph_objects as go\n\nfrom mlflow_extend import plotting as mplt\nfrom mlflow_extend.typing import ArrayLike\nfrom mlflow_extend.utils import flatten_dict\n\n__all__ = [\n \"log_params_flatten\",\n \"log_metrics_flatten\",\n \"log_figure\",\n \"log_dict\",\n \"log_df\",\n \"log_text\",\n \"log_numpy\",\n \"log_confusion_matrix\",\n \"log_feature_importance\",\n \"log_roc_curve\",\n \"log_pr_curve\",\n]\n\n\n@contextmanager\ndef _artifact_context(path: str) -> Generator[str, None, None]:\n with tempfile.TemporaryDirectory() as tmpdir:\n path = os.path.normpath(path)\n dirname = os.path.dirname(path)\n filename = os.path.basename(path)\n artifact_path = None if dirname == filename else dirname\n path = os.path.join(tmpdir, filename)\n yield path\n mlflow.log_artifact(path, artifact_path)\n\n\ndef log_params_flatten(params: dict, parent_key: str = \"\", sep: str = \".\") -> None:\n \"\"\"\n Log a batch of params after flattening.\n\n Parameters\n ----------\n params : dict\n Dictionary of parameters to log.\n parent_key : str, default \"\"\n Parent key.\n sep : str, default \".\"\n Key separator.\n\n Examples\n --------\n >>> with mlflow.start_run() as run:\n ... params = {\"a\": {\"b\": 0}}\n ... mlflow.log_params_flatten(params)\n ... mlflow.log_params_flatten(params, parent_key=\"d\")\n ... mlflow.log_params_flatten(params, sep=\"_\")\n >>> r = mlflow.get_run(run.info.run_id)\n >>> sorted(r.data.params.items())\n [('a.b', '0'), ('a_b', '0'), ('d.a.b', '0')]\n\n \"\"\"\n mlflow.log_params(flatten_dict(params, parent_key, sep))\n\n\ndef log_metrics_flatten(\n metrics: dict, step: Optional[int] = None, parent_key: str = \"\", sep: str = \".\",\n) -> None:\n \"\"\"\n Log a batch of metrics after flattening.\n\n Parameters\n ----------\n metrics : dict\n Dictionary of metrics to log.\n step : int, default None\n Metric step. Defaults to zero if unspecified.\n parent_key : str, default \"\"\n Parent key.\n sep : str, default \".\"\n Key separator.\n\n Examples\n --------\n >>> with mlflow.start_run() as run:\n ... metrics = {\"a\": {\"b\": 0.0}}\n ... mlflow.log_metrics_flatten(metrics)\n ... mlflow.log_metrics_flatten(metrics, parent_key=\"d\")\n ... mlflow.log_metrics_flatten(metrics, sep=\"_\")\n >>> r = mlflow.get_run(run.info.run_id)\n >>> sorted(r.data.metrics.items())\n [('a.b', 0.0), ('a_b', 0.0), ('d.a.b', 0.0)]\n\n \"\"\"\n mlflow.log_metrics(flatten_dict(metrics, parent_key, sep), step)\n\n\ndef log_figure(fig: Union[plt.Figure, go.Figure], path: str) -> None:\n \"\"\"\n Log a matplotlib figure as an artifact.\n\n Parameters\n ----------\n fig : matplotlib.pyplot.Figure or plotly.graph_objects.Figure\n Figure to log.\n path : str\n Path in the artifact store.\n\n Returns\n -------\n None\n\n Examples\n --------\n Matplotlib\n\n >>> with mlflow.start_run():\n ... fig, ax = plt.subplots()\n ... _ = ax.plot([0, 1], [0, 1])\n ... mlflow.log_figure(fig, 'figure.png')\n\n Plotly\n\n >>> with mlflow.start_run():\n ... fig = go.Figure(data=[go.Bar(x=[1, 2, 3], y=[1, 3, 2])])\n ... mlflow.log_figure(fig, 'figure.html') # Must be an HTML file.\n\n \"\"\"\n with _artifact_context(path) as tmp_path:\n if isinstance(fig, plt.Figure):\n fig.savefig(tmp_path)\n plt.close(fig)\n elif isinstance(fig, go.Figure):\n if not tmp_path.endswith(\"html\"):\n raise ValueError(\n '\"{}\" is not an HTML file.'.format(os.path.basename(tmp_path))\n )\n plotly.offline.plot(\n fig, filename=tmp_path, include_plotlyjs=\"cdn\", auto_open=False\n )\n else:\n raise TypeError('Invalid figure type \"{}\".'.format(type(fig)))\n\n\ndef log_dict(dct: dict, path: str, fmt: Optional[str] = None) -> None:\n \"\"\"\n Log a dictionary as an artifact.\n\n Parameters\n ----------\n dct : dict\n Dictionary to log.\n path : str\n Path in the artifact store.\n fmt : str, default None\n File format to save dict in. If None, file format is inferred from `path`.\n\n Returns\n -------\n None\n\n Examples\n --------\n >>> with mlflow.start_run():\n ... d = {'a': 0}\n ... mlflow.log_dict(d, 'dict.json')\n ... mlflow.log_dict(d, 'dict.yaml')\n ... mlflow.log_dict(d, 'dict.yml')\n\n \"\"\"\n fmt = os.path.splitext(path)[-1] if fmt is None else fmt\n fmt = fmt.lstrip(\".\")\n\n with _artifact_context(path) as tmp_path:\n with open(tmp_path, \"w\") as f:\n if fmt == \"json\":\n json.dump(dct, f, indent=2)\n elif fmt in [\"yaml\", \"yml\"]:\n yaml.dump(dct, f, default_flow_style=False)\n else:\n raise ValueError(\"Invalid file format: {}.\".format(fmt))\n\n\ndef log_pickle(obj: Any, path: str) -> None:\n \"\"\"\n Log a pickled object as an artifact.\n\n Parameters\n ----------\n obj : object\n Picklable object.\n path : str\n Path in the artifact store.\n\n \"\"\"\n with _artifact_context(path) as tmp_path:\n with open(tmp_path, mode=\"wb\") as f:\n pickle.dump(obj, f)\n\n\ndef log_df(df: pd.DataFrame, path: str, fmt: str = \"csv\") -> None:\n \"\"\"\n Log a dataframe as an artifact.\n\n Parameters\n ----------\n df : dict\n Dataframe to log.\n path : str\n Path in the artifact store.\n fmt : str, default \"csv\"\n File format to save the dataframe in.\n\n Returns\n -------\n None\n\n Examples\n --------\n >>> with mlflow.start_run():\n ... mlflow.log_df(pd.DataFrame({'a': [0]}), 'df.csv')\n\n \"\"\"\n with _artifact_context(path) as tmp_path:\n if fmt == \"csv\":\n df.to_csv(tmp_path, index=False)\n elif fmt == \"feather\":\n df.to_feather(tmp_path)\n else:\n raise ValueError(\"Invalid file format: {}.\".format(fmt))\n\n\ndef log_text(text: str, path: str) -> None:\n \"\"\"\n Log a text as an artifact.\n\n Parameters\n ----------\n text : str\n Text to log.\n path : str\n Path in the artifact store.\n\n Returns\n -------\n None\n\n Examples\n --------\n >>> with mlflow.start_run():\n ... mlflow.log_text('text', 'text.txt')\n\n \"\"\"\n with _artifact_context(path) as tmp_path:\n with open(tmp_path, \"w\") as f:\n f.write(text)\n\n\ndef log_numpy(arr: np.ndarray, path: str) -> None:\n \"\"\"\n Log a numpy array as an artifact.\n\n Parameters\n ----------\n arr : numpy.ndarray\n Numpy array to log.\n path : str\n Path in the artifact store.\n\n Returns\n -------\n None\n\n Examples\n --------\n >>> with mlflow.start_run():\n ... mlflow.log_numpy(np.array([0]), 'array.npy')\n\n \"\"\"\n with _artifact_context(path) as tmp_path:\n np.save(tmp_path, arr)\n\n\ndef log_confusion_matrix(cm: ArrayLike, path: str = \"confusion_matrix.png\") -> None:\n \"\"\"\n Log a confusion matrix as an artifact.\n\n Parameters\n ----------\n cm : array-like\n Confusion matrix to log.\n path : str, default \"confusion_matrix.png\"\n Path in the artifact store.\n\n Returns\n -------\n None\n\n Examples\n --------\n >>> with mlflow.start_run():\n ... mlflow.log_confusion_matrix([[1, 2], [3, 4]])\n\n \"\"\"\n fig = mplt.confusion_matrix(cm)\n log_figure(fig, path)\n\n\ndef log_feature_importance(\n features: ArrayLike,\n importances: ArrayLike,\n importance_type: str,\n limit: Optional[int] = None,\n normalize: bool = False,\n path: str = \"feature_importance.png\",\n) -> None:\n \"\"\"\n Log feature importance as an artifact.\n\n Parameters\n ----------\n features : array-like\n Feature names.\n importances : array-like\n Importance of each feature.\n importance_type : str\n Importance type (e.g. \"gain\").\n path : str, default \"feature_importance.png\"\n Path in the artifact store.\n **kwargs : dict\n Keyword arguments passed to mlflow.plotting.feature_importance.\n\n Returns\n -------\n None\n\n Examples\n --------\n >>> with mlflow.start_run():\n ... features = ['a', 'b', 'c']\n ... importances = [1, 2, 3]\n ... mlflow.log_feature_importance(features, importances, 'gain')\n\n \"\"\"\n fig = mplt.feature_importance(\n features, importances, importance_type, limit, normalize\n )\n log_figure(fig, path)\n\n\ndef log_roc_curve(\n fpr: ArrayLike,\n tpr: ArrayLike,\n auc: Optional[float] = None,\n path: str = \"roc_curve.png\",\n) -> None:\n \"\"\"\n Log ROC curve as an artifact.\n\n Parameters\n ----------\n fpr : array-like\n False positive rate.\n tpr : array-like\n True positive rate.\n auc : float, default None\n Area under the curve.\n path : str, default \"roc_curve.png\"\n Path in the artifact store.\n\n Returns\n -------\n None\n\n Examples\n --------\n >>> with mlflow.start_run():\n ... mlflow.log_roc_curve([0, 1], [0, 1])\n\n \"\"\"\n fig = mplt.roc_curve(fpr, tpr, auc)\n log_figure(fig, path)\n\n\ndef log_pr_curve(\n pre: ArrayLike,\n rec: ArrayLike,\n auc: Optional[float] = None,\n path: str = \"pr_curve.png\",\n) -> None:\n \"\"\"\n Log precision-recall curve as an artifact.\n\n Parameters\n ----------\n pre : array-like\n Precision.\n rec : array-like\n Recall.\n auc : float, default None\n Area under the curve.\n path : str, default \"pr_curve.png\"\n Path in the artifact store.\n\n Returns\n -------\n None\n\n Examples\n --------\n >>> with mlflow.start_run():\n ... mlflow.log_pr_curve([1, 0], [1, 0])\n\n \"\"\"\n fig = mplt.pr_curve(pre, rec, auc)\n log_figure(fig, path)\n"
] | [
[
"matplotlib.pyplot.close",
"numpy.save"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
evil-panda-team/photohack_v2 | [
"be47765f61772a68b646f3b7ecb4db1483b9907a"
] | [
"icface/run.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 22 16:54:36 2019\n\n@author: kenny\n\"\"\"\nimport sys\nsys.path.insert(0, './icface')\n\n#from imutils.face_utils import FaceAligner\nfrom imutils.face_utils import rect_to_bb\nimport imutils\nimport dlib\nimport cv2\nimport numpy as np\nfrom PIL import Image\nimport os\nfrom options.test_options import TestOptions\nfrom data.data_loader import CreateDataLoader\nfrom models.models import create_model\n\ndef create_mp4(input_img_path, csv_path):\n \n opt = TestOptions().parse()\n opt.input_img = input_img_path\n opt.csv_path = csv_path\n opt.nThreads = 1 # test code only supports nThreads = 1\n opt.batchSize = 1 # test code only supports batchSize = 1\n opt.serial_batches = True # no shuffle\n opt.no_flip = True # no flip\n \n ###### PART 1 \n detector = dlib.get_frontal_face_detector()\n \n name = opt.input_img\n cap = cv2.imread(name) # add your image here\n# image= cv2.resize(cap, (400, 400))\n \n RGB = cv2.cvtColor(cap, cv2.COLOR_BGR2RGB) \n \n rects = detector(RGB, 1)\n \n for rect in rects:\n c1=rect.dcenter()\n (x, y, w, h) = rect_to_bb(rect)\n w=np.int(w*1.6) \n h=np.int(h*1.6) \n x=c1.x-np.int(w/2.0)\n y=c1.y-np.int(h/2.0)\n if y<0:\n y=0\n if x<0:\n x=0\n \n faceOrig = imutils.resize(RGB[y:y+h, x:x+w], height=256) #y=10,h+60,W+40\n d_num = np.asarray(faceOrig)\n f_im = Image.fromarray(d_num)\n f_im.save('./temp.png')\n \n \n #### PART 2\n data_loader = CreateDataLoader(opt)\n dataset = data_loader.load_data()\n model = create_model(opt)\n for i, data in enumerate(dataset): \n if i >= opt.how_many:\n break \n model.set_input(data)\n model.test()\n \n os.system('rm temp.png')\n print(\"Done!\")\n"
] | [
[
"numpy.asarray",
"numpy.int"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Shigangli/tf-models | [
"9817cf0c087e4d7a3c7439789c5ff05388493347"
] | [
"official/resnet/cifar10_main.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\"\"\"Runs a ResNet model on the CIFAR-10 dataset.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nfrom absl import app as absl_app\nfrom absl import flags\nimport tensorflow as tf # pylint: disable=g-bad-import-order\n\nfrom official.utils.flags import core as flags_core\nfrom official.utils.logs import logger\nfrom official.resnet import resnet_model\nfrom official.resnet import resnet_run_loop\n\n_HEIGHT = 32\n_WIDTH = 32\n_NUM_CHANNELS = 3\n_DEFAULT_IMAGE_BYTES = _HEIGHT * _WIDTH * _NUM_CHANNELS\n# The record is the image plus a one-byte label\n_RECORD_BYTES = _DEFAULT_IMAGE_BYTES + 1\n_NUM_CLASSES = 10\n_NUM_DATA_FILES = 5\n\n_NUM_IMAGES = {\n 'train': 50000,\n 'validation': 10000,\n}\n\nDATASET_NAME = 'CIFAR-10'\n\n\n###############################################################################\n# Data processing\n###############################################################################\ndef get_filenames(is_training, data_dir):\n \"\"\"Returns a list of filenames.\"\"\"\n data_dir = os.path.join(data_dir, 'cifar-10-batches-bin')\n\n assert os.path.exists(data_dir), (\n 'Run cifar10_download_and_extract.py first to download and extract the '\n 'CIFAR-10 data.')\n\n if is_training:\n return [\n os.path.join(data_dir, 'data_batch_%d.bin' % i)\n for i in range(1, _NUM_DATA_FILES + 1)\n ]\n else:\n return [os.path.join(data_dir, 'test_batch.bin')]\n\n\ndef parse_record(raw_record, is_training, batchaug_m):\n \"\"\"Parse CIFAR-10 image and label from a raw record.\"\"\"\n # Convert bytes to a vector of uint8 that is record_bytes long.\n record_vector = tf.decode_raw(raw_record, tf.uint8)\n\n # The first byte represents the label, which we convert from uint8 to int32\n # and then to one-hot.\n label = tf.cast(record_vector[0], tf.int32)\n\n # The remaining bytes after the label represent the image, which we reshape\n # from [depth * height * width] to [depth, height, width].\n depth_major = tf.reshape(record_vector[1:_RECORD_BYTES],\n [_NUM_CHANNELS, _HEIGHT, _WIDTH])\n\n # Convert from [depth, height, width] to [height, width, depth], and cast as\n # float32.\n image = tf.cast(tf.transpose(depth_major, [1, 2, 0]), tf.float32)\n\n if is_training and batchaug_m > 1:\n dup_image = tf.tile(tf.expand_dims(image, 0), [batchaug_m, 1, 1, 1])\n dup_label = tf.tile(tf.expand_dims(label, 0), [batchaug_m])\n\n return dup_image, dup_label\n else:\n return image, label\n\n\ndef preprocess_image(data, is_training):\n \"\"\"Preprocess a single image of layout [height, width, depth].\"\"\"\n\n images, labels = data\n\n # Reshape to concatenate duplicated batches\n if is_training and len(images.shape) > 4:\n images = tf.reshape(images, [images.shape[0] * images.shape[1], images.shape[2], images.shape[3], images.shape[4]])\n labels = tf.reshape(labels, [labels.shape[0] * labels.shape[1]])\n \n def per_image_preprocess(image):\n if is_training:\n # Resize the image to add four extra pixels on each side.\n image = tf.image.resize_image_with_crop_or_pad(\n image, _HEIGHT + 8, _WIDTH + 8)\n\n # Randomly crop a [_HEIGHT, _WIDTH] section of the image.\n image = tf.random_crop(image, [_HEIGHT, _WIDTH, _NUM_CHANNELS])\n\n # Randomly flip the image horizontally.\n image = tf.image.random_flip_left_right(image)\n\n # Subtract off the mean and divide by the variance of the pixels.\n image = tf.image.per_image_standardization(image)\n return image\n\n # Apply on the entire batch\n images = tf.map_fn(per_image_preprocess, images)\n return images, labels\n\n\ndef input_fn(is_training, data_dir, batch_size, num_epochs=1, num_gpus=None, batchaug_m=1, num_workers=1):\n \"\"\"Input_fn using the tf.data input pipeline for CIFAR-10 dataset.\n\n Args:\n is_training: A boolean denoting whether the input is for training.\n data_dir: The directory containing the input data.\n batch_size: The number of samples per batch.\n num_epochs: The number of epochs to repeat the dataset.\n num_gpus: The number of gpus used for training.\n\n Returns:\n A dataset that can be used for iteration.\n \"\"\"\n filenames = get_filenames(is_training, data_dir)\n dataset = tf.data.FixedLengthRecordDataset(filenames, _RECORD_BYTES)\n\n return resnet_run_loop.process_record_dataset(\n dataset=dataset,\n is_training=is_training,\n batch_size=batch_size,\n shuffle_buffer=_NUM_IMAGES['train'],\n parse_record_fn=parse_record,\n preprocess_fn=preprocess_image,\n num_epochs=num_epochs,\n num_gpus=num_gpus,\n examples_per_epoch=_NUM_IMAGES['train'] if is_training else None,\n batchaug_m=batchaug_m,\n num_workers=num_workers\n )\n\n\ndef get_synth_input_fn():\n return resnet_run_loop.get_synth_input_fn(\n _HEIGHT, _WIDTH, _NUM_CHANNELS, _NUM_CLASSES)\n\n\n###############################################################################\n# Running the model\n###############################################################################\nclass Cifar10Model(resnet_model.Model):\n \"\"\"Model class with appropriate defaults for CIFAR-10 data.\"\"\"\n\n def __init__(self, resnet_size, data_format=None, num_classes=_NUM_CLASSES,\n resnet_version=resnet_model.DEFAULT_VERSION,\n dtype=resnet_model.DEFAULT_DTYPE):\n \"\"\"These are the parameters that work for CIFAR-10 data.\n\n Args:\n resnet_size: The number of convolutional layers needed in the model.\n data_format: Either 'channels_first' or 'channels_last', specifying which\n data format to use when setting up the model.\n num_classes: The number of output classes needed from the model. This\n enables users to extend the same model to their own datasets.\n resnet_version: Integer representing which version of the ResNet network\n to use. See README for details. Valid values: [1, 2]\n dtype: The TensorFlow dtype to use for calculations.\n\n Raises:\n ValueError: if invalid resnet_size is chosen\n \"\"\"\n if resnet_size % 6 != 2:\n raise ValueError('resnet_size must be 6n + 2:', resnet_size)\n\n num_blocks = (resnet_size - 2) // 6\n\n super(Cifar10Model, self).__init__(\n resnet_size=resnet_size,\n bottleneck=False,\n num_classes=num_classes,\n num_filters=16,\n kernel_size=3,\n conv_stride=1,\n first_pool_size=None,\n first_pool_stride=None,\n block_sizes=[num_blocks] * 3,\n block_strides=[1, 2, 2],\n final_size=64,\n resnet_version=resnet_version,\n data_format=data_format,\n dtype=dtype\n )\n\n\ndef cifar10_model_fn(features, labels, mode, params):\n \"\"\"Model function for CIFAR-10.\"\"\"\n features = tf.reshape(features, [-1, _HEIGHT, _WIDTH, _NUM_CHANNELS])\n\n learning_rate_fn = resnet_run_loop.learning_rate_with_decay(\n batch_size=params['batch_size'], batch_denom=128,\n num_images=_NUM_IMAGES['train'], boundary_epochs=[100, 150, 200],\n decay_rates=[1, 0.1, 0.01, 0.001])\n\n # We use a weight decay of 0.0002, which performs better\n # than the 0.0001 that was originally suggested.\n weight_decay = 2e-4\n\n # Empirical testing showed that including batch_normalization variables\n # in the calculation of regularized loss helped validation accuracy\n # for the CIFAR-10 dataset, perhaps because the regularization prevents\n # overfitting on the small data set. We therefore include all vars when\n # regularizing and computing loss during training.\n def loss_filter_fn(_):\n return True\n\n return resnet_run_loop.resnet_model_fn(\n features=features,\n labels=labels,\n mode=mode,\n model_class=Cifar10Model,\n resnet_size=params['resnet_size'],\n weight_decay=weight_decay,\n learning_rate_fn=learning_rate_fn,\n batch_size=params['batch_size'],\n momentum=0.9,\n data_format=params['data_format'],\n resnet_version=params['resnet_version'],\n loss_scale=params['loss_scale'],\n loss_filter_fn=loss_filter_fn,\n dtype=params['dtype'],\n fine_tune=params['fine_tune']\n )\n\n\ndef define_cifar_flags():\n resnet_run_loop.define_resnet_flags()\n flags.adopt_module_key_flags(resnet_run_loop)\n flags_core.set_defaults(data_dir='/tmp/cifar10_data',\n model_dir='/tmp/cifar10_model',\n resnet_size='32',\n train_epochs=250,\n epochs_between_evals=10,\n batch_size=128)\n\n\ndef run_cifar(flags_obj):\n \"\"\"Run ResNet CIFAR-10 training and eval loop.\n\n Args:\n flags_obj: An object containing parsed flag values.\n \"\"\"\n input_function = (flags_obj.use_synthetic_data and get_synth_input_fn()\n or input_fn)\n resnet_run_loop.resnet_main(\n flags_obj, cifar10_model_fn, input_function, DATASET_NAME,\n shape=[_HEIGHT, _WIDTH, _NUM_CHANNELS])\n\n\ndef main(_):\n with logger.benchmark_context(flags.FLAGS):\n run_cifar(flags.FLAGS)\n\n\nif __name__ == '__main__':\n tf.logging.set_verbosity(tf.logging.INFO)\n define_cifar_flags()\n absl_app.run(main)\n"
] | [
[
"tensorflow.image.resize_image_with_crop_or_pad",
"tensorflow.transpose",
"tensorflow.image.random_flip_left_right",
"tensorflow.decode_raw",
"tensorflow.reshape",
"tensorflow.cast",
"tensorflow.expand_dims",
"tensorflow.data.FixedLengthRecordDataset",
"tensorflow.random_crop",
"tensorflow.map_fn",
"tensorflow.image.per_image_standardization",
"tensorflow.logging.set_verbosity"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
songlinhou/pytools | [
"b990672fd9287da4fe57350bed28958ac261df81"
] | [
"statslib.py"
] | [
"import scipy.stats as st\nimport numpy as np\nimport pandas as pd\n\nclass CI:\n def one_proportion(self, n, phat, conf):\n z_val = st.norm.ppf(1 - (1 - conf) / 2) # this is two-side\n # z_val = st.norm.ppf(1 - (1 - conf)) # this is one-side\n se = np.sqrt(phat*(1-phat)/n)\n print('z-value=', z_val, \"se=\", se)\n ci = (phat - z_val * se, phat + z_val * se)\n print(ci)\n\n def one_proportion_conserv(self, n, phat, conf):\n # we center at phat, and try to estimate the margin of errors\n # use normal-dist (z-value)\n z_val = st.norm.ppf(1 - (1 - conf) / 2) # this is two-side\n # z_val = st.norm.ppf(1 - (1 - conf)) # this is one-side\n\n se = 1 / (2 * np.sqrt(n))\n print('z-value=', z_val, \"se=\", se)\n ci = (phat - z_val * se, phat + z_val * se)\n print(ci)\n\n def two_proportions(self, pos_num1, pos_num2, total_num1, total_num2, conf):\n m1, m2 = pos_num1, pos_num2 # positive numbers\n n1, n2 = total_num1, total_num2 # total numbers\n\n p1, p2 = m1 / n1, m2 / n2\n phat = p1 - p2\n # phat *= -1\n z_val = st.norm.ppf(1 - (1 - conf) / 2) # this is two-side\n se = np.sqrt(p1 * (1 - p1) / n1 + p2 * (1 - p2) / n2)\n print('z-value=', z_val, \"se=\", se)\n print(f'{phat} +/- {z_val * se}')\n ci = (phat - z_val * se, phat + z_val * se)\n print(ci)\n\n def one_mean(self, mu, n, sd, conf):\n dof = n - 1\n se = sd / np.sqrt(n)\n t = st.t.ppf(1 - (1 - conf) / 2, df = dof)\n\n print('t-value=', t, \"se=\", se)\n print(f'{mu} +/- {t * se}')\n ci = (mu - t * se, mu + t * se)\n print(ci)\n\n def two_mean_paired(self, mu_diff, sd, n, conf):\n dof = n - 1\n mu = mu_diff\n se = sd / np.sqrt(n)\n t = st.t.ppf(1 - (1 - conf) / 2, df = dof)\n print('t-value=', t, \"se=\", se)\n print(f'{mu} +/- {t * se}')\n ci = (mu - t * se, mu + t * se)\n print(ci)\n\n if ci[0] <= 0 <= ci[1]:\n print('0 is included. maybe no difference')\n else:\n print('0 is NOT included. some difference')\n\n def two_means_independent_unpooled(self, mu1, mu2, sd1, sd2, n1, n2, conf):\n dof = np.min([n1 - 1, n2 - 1])\n mu_hat = mu1 - mu2\n se = np.sqrt(sd1**2 / n1 + sd2**2 / n2)\n t = st.t.ppf(1 - (1 - conf) / 2, df = dof)\n print('DOF=', dof)\n print('t-value=', t, \"se=\", se)\n\n print(f'{mu_hat} +/- {t * se}')\n ci = (mu_hat - t * se, mu_hat + t * se)\n print(ci)\n\n def two_means_independent_pooled(self, mu1, mu2, sd1, sd2, n1, n2, conf):\n dof = n1 + n2 - 2\n mu_hat = mu1 - mu2\n se = np.sqrt(((n1 - 1) * sd1**2 + (n2 - 1) * sd2**2)/ (n1 + n2 - 2)) * np.sqrt(1/n1 + 1/n2)\n t = st.t.ppf(1 - (1 - conf) / 2, df = dof)\n print('DOF=', dof)\n print('t-value=', t, \"se=\", se)\n\n print(f'{mu_hat} +/- {t * se}')\n ci = (mu_hat - t * se, mu_hat + t * se)\n print(ci)\n\n\nclass HT:\n def one_proportion_two_sides(self, p0, phat, n, alpha):\n # check for assumption\n if (n * p0 >= 10 and n * (1 - p0) >= 10):\n print('sample size is large enough')\n else:\n print('sample size is NOT large enough')\n\n se = np.sqrt(p0 * (1 - p0) / n)\n z = abs(phat - p0) / se\n print(f'z-value is {z}')\n print(f'which means our observed sample proportion is {z} null SE above our hypothesized population proportion ABS value')\n p_val = (1 - st.norm.cdf(z)) * 2\n print(f'p-value is {p_val}')\n\n print(f'reject if p_value {p_val} < alpha {alpha}')\n if p_val < alpha:\n print('Reject!')\n else:\n print('Cannot reject.')\n\n def one_proportion_phat_larger(self, p0, phat, n, alpha):\n # check for assumption\n if (n * p0 >= 10 and n * (1 - p0) >= 10):\n print('sample size is large enough')\n else:\n print('sample size is NOT large enough')\n\n se = np.sqrt(p0 * (1 - p0) / n)\n z = (phat - p0) / se\n print(f'z-value is {z}')\n print(f'which means our observed sample proportion is {z} null SE above our hypothesized population proportion')\n p_val = 1 - st.norm.cdf(z)\n print(f'p-value is {p_val}')\n\n print(f'reject if p_value {p_val} < alpha {alpha}')\n if p_val < alpha:\n print('Reject!')\n else:\n print('Cannot reject.')\n\n def one_proportion_phat_smaller(self, p0, phat, n, alpha):\n # check for assumption\n if (n * p0 >= 10 and n * (1 - p0) >= 10):\n print('sample size is large enough')\n else:\n print('sample size is NOT large enough')\n\n se = np.sqrt(p0 * (1 - p0) / n)\n z = (p0 - phat) / se\n print(f'z-value is {z}')\n print(f'which means our observed sample proportion is {z} null SE above our hypothesized population proportion')\n p_val = 1 - st.norm.cdf(z)\n print(f'p-value is {p_val}')\n\n print(f'reject if p_value {p_val} < alpha {alpha}')\n if p_val < alpha:\n print('Reject!')\n else:\n print('Cannot reject.')\n\n def two_proportion_two_sides(self, pos1_num, pos2_num, n1, n2, alpha):\n m1, m2 = pos1_num, pos2_num # positive numbers\n # check for assumption\n phat = (m1 + m2) / (n1 + n2)\n print('phat=', phat)\n if (n1 * phat >= 10 and n1 * (1 - phat) >= 10 and n2 * phat >= 10 and n2 * (1 - phat) >= 10):\n print('sample size is large enough')\n else:\n print('sample size is NOT large enough, should not use this method')\n\n p1, p2 = m1 / n1, m2 / n2\n se = np.sqrt(phat * (1 - phat) * (1 / n1 + 1 / n2))\n z = (p1 - p2 - 0) / se\n print(f'z-stat is {z}')\n\n p_val = (1 - st.norm.cdf(abs(z))) * 2\n print(f'p-value is {p_val}')\n\n print(f'reject if p_value {p_val} < alpha {alpha}')\n if p_val < alpha:\n print('Reject!')\n else:\n print('Cannot reject.')\n\n def two_proportion_pos1_larger(self, pos1_num, pos2_num, n1, n2, alpha):\n m1, m2 = pos1_num, pos2_num # positive numbers\n # check for assumption\n phat = (m1 + m2) / (n1 + n2)\n print('phat=', phat)\n if (n1 * phat >= 10 and n1 * (1 - phat) >= 10 and n2 * phat >= 10 and n2 * (1 - phat) >= 10):\n print('sample size is large enough')\n else:\n print('sample size is NOT large enough, should not use this method')\n\n # p1, p2 = m1 / n1, m2 / n2\n p1, p2 = 0.52, 0.35\n # se = np.sqrt(phat * (1 - phat) * (1 / n1 + 1 / n2))\n se = 0.0338\n z = (p1 - p2 - 0) / se\n print(f'p1={p1} and p2={p2}')\n print(f'z-stat is {z}')\n # assert z > 0, \"p1 > p2\"\n\n p_val = (1 - st.norm.cdf(abs(z)))\n print(f'p-value is {p_val}')\n\n print(f'reject if p_value {p_val} < alpha {alpha}')\n if p_val < alpha:\n print('Reject!')\n else:\n print('Cannot reject.')\n\n def two_proportion_pos1_smaller(self, pos1_num, pos2_num, n1, n2, alpha):\n m1, m2 = pos1_num, pos2_num # positive numbers\n # check for assumption\n phat = (m1 + m2) / (n1 + n2)\n print('phat=', phat)\n if (n1 * phat >= 10 and n1 * (1 - phat) >= 10 and n2 * phat >= 10 and n2 * (1 - phat) >= 10):\n print('sample size is large enough')\n else:\n print('sample size is NOT large enough, should not use this method')\n\n p1, p2 = m1 / n1, m2 / n2\n se = np.sqrt(phat * (1 - phat) * (1 / n1 + 1 / n2))\n z = (p2 - p1 - 0) / se\n print(f'p1={p1} and p2={p2}')\n print(f'z-stat is {z}')\n # assert z > 0, \"p1 > p2\"\n\n p_val = (1 - st.norm.cdf(abs(z)))\n print(f'p-value is {p_val}')\n\n print(f'reject if p_value {p_val} < alpha {alpha}')\n if p_val < alpha:\n print('Reject!')\n else:\n print('Cannot reject.')\n\n def one_mean_two_sides(self, mu0, mu_hat, n, sd, alpha):\n dof = n - 1\n se = sd / np.sqrt(n)\n t = (mu_hat - mu0) / se\n print(f't-stat is {t}')\n p_val = (1 - st.t.cdf(abs(t), df = dof)) * 2\n print(f'p-value is {p_val}')\n\n print(f'reject if p_value {p_val} < alpha {alpha}')\n if p_val < alpha:\n print('Reject!')\n else:\n print('Cannot reject.')\n\n # confidence\n conf = 1 - alpha\n t_conf = st.t.ppf(1 - (1 - conf) / 2, df=dof)\n ci = (mu_hat - t_conf * se, mu_hat + t_conf * se)\n print('0 exist in the CI?')\n print(f'CI with {conf} confidence level = ', ci)\n\n def one_mean_mu_hat_larger(self, mu0, mu_hat, n, sd, alpha):\n dof = n - 1\n se = sd / np.sqrt(n)\n t = (mu_hat - mu0) / se\n print(f't-stat is {t}')\n p_val = (1 - st.t.cdf(abs(t), df = dof)) * 1\n print(f'p-value is {p_val}')\n\n print(f'reject if p_value {p_val} < alpha {alpha}')\n if p_val < alpha:\n print('Reject!')\n else:\n print('Cannot reject.')\n\n # confidence\n conf = 1 - alpha\n t_conf = st.t.ppf(1 - (1 - conf), df=dof)\n ci = (mu_hat - t_conf * se, mu_hat + t_conf * se)\n print('0 exist in the CI?')\n print(f'CI with {conf} confidence level = ', ci)\n\n def one_mean_mu_hat_smaller(self, mu0, mu_hat, n, sd, alpha):\n dof = n - 1\n se = sd / np.sqrt(n)\n t = (mu0 - mu_hat) / se\n print(f't-stat is {t}')\n p_val = (1 - st.t.cdf(abs(t), df = dof)) * 1\n print(f'p-value is {p_val}')\n\n print(f'reject if p_value {p_val} < alpha {alpha}')\n if p_val < alpha:\n print('Reject!')\n else:\n print('Cannot reject.')\n\n # confidence\n conf = 1 - alpha\n t_conf = st.t.ppf(1 - (1 - conf), df=dof)\n ci = (mu_hat - t_conf * se, mu_hat + t_conf * se)\n print('0 exist in the CI?')\n print(f'CI with {conf} confidence level = ', ci)\n\n def two_means_paired_two_sides(self, mu, sd, n, alpha):\n dof = n - 1\n se = sd / np.sqrt(n)\n t = (mu - 0) / se\n p_val = (1 - st.t.cdf(t, df= dof)) * 2\n print(f't-val = ', t)\n print(f'Our observed mean difference is {t} (estimated) SE above our null value of 0')\n print(f'reject if p_value {p_val} < alpha {alpha}')\n if p_val < alpha:\n print('Reject!')\n else:\n print('Cannot reject.')\n\n # confidence\n conf = 1 - alpha\n t_conf = st.t.ppf(1 - (1 - conf)/2, df=dof)\n ci = (mu - t_conf * se, mu + t_conf * se)\n print('0 exist in the CI?')\n print(f'CI with {conf} confidence level = ', ci)\n\n def two_means_independent_unpooled(self, mu1, mu2, sd1, sd2, n1, n2, alpha):\n dof = np.min([n1-1, n2-1])\n se = np.sqrt(sd1**2 / n1 + sd2**2 / n2)\n # se = 11.8831\n t = abs((mu1 - mu2) / se) # pay attention here\n print('dof=', dof)\n print('t-value=', t, 'se=', se)\n p_val = (1 - st.t.cdf(t, df = dof)) * 2 # if two sides\n # p_val = (1 - st.t.cdf(t, df = dof)) # if one sides\n print(f'reject if p_value {p_val} < alpha {alpha}')\n if p_val < alpha:\n print('Reject!')\n else:\n print('Cannot reject.')\n\n # using CI (two side)\n conf = 1 - alpha\n t_conf = st.t.ppf(1 - (1 - conf)/2, df=dof)\n ci = (mu1 - mu2 - t_conf * se, mu1 - mu2 + t_conf * se)\n print('0 exist in the CI?')\n print(f'CI with {conf} confidence level = ', ci)\n\n def two_means_independent_pooled(self, mu1, mu2, sd1, sd2, n1, n2, alpha):\n dof = n1 + n2 - 2\n sp = np.sqrt(((n1 - 1) * sd1**2 + (n2 - 1) * sd2**2)/(n1 + n2 - 2))\n se = sp * np.sqrt(1/n1 + 1/n2)\n t = abs((mu1 - mu2) / se) # pay attention here\n print('dof=', dof)\n print('t-value=', t, 'se=', se)\n p_val = (1 - st.t.cdf(t, df = dof)) * 2 # if two sides\n # p_val = (1 - st.t.cdf(t, df = dof)) # if one sides\n print(f'reject if p_value {p_val} < alpha {alpha}')\n if p_val < alpha:\n print('Reject!')\n else:\n print('Cannot reject.')\n\n # using CI (two side)\n conf = 1 - alpha\n t_conf = st.t.ppf(1 - (1 - conf)/2, df=dof)\n ci = (mu1 - mu2 - t_conf * se, mu1 - mu2 + t_conf * se)\n print('0 exist in the CI?')\n print(f'CI with {conf} confidence level = ', ci)\n\n def chi_squared_homogeneity(self, df, alpha):\n col_sum = df.sum(axis = 0)\n row_sum = df.sum(axis = 1)\n df_sum = df.values.sum()\n\n df_vis = df.copy()\n df_vis['total'] = row_sum\n df_vis.loc['total'] = col_sum\n df_vis.iloc[-1,-1] = df_sum\n # df_vis\n\n df_expected = df.copy()\n\n if 1 in df.shape:\n for i in range(df.shape[0]):\n for j in range(df.shape[1]):\n df_expected.iloc[i,j] = df_sum / np.multiply(*df.shape)\n else:\n for i in range(df.shape[0]):\n for j in range(df.shape[1]):\n # df_expected.iloc[i,j] = (row_sum[i] / df_sum) * (col_sum[j] / df_sum) * df_sum\n df_expected.iloc[i,j] = (row_sum[i] / df_sum) * col_sum[j]\n\n # df_expected\n\n if np.all(df_expected.values.flatten() >= 5):\n print('assumption is ok: every expected value is at least 5')\n else:\n print('assumption is NOT ok')\n\n if 1 in df.shape:\n ddof = len(df.values.flatten()) - 1\n else:\n ddof = (df.shape[0] - 1) * (df.shape[1] - 1)\n df_e_flat = df_expected.values.flatten()\n df_flat = df.values.flatten()\n print(f'DOF = {ddof}')\n chi2 = np.sum((df_flat - df_e_flat) **2 / (df_e_flat))\n print(f'chi2 = {chi2}')\n\n p_val = 1 - st.chi2.cdf(chi2, df = ddof)\n print(f'p-value = {p_val}')\n\n print(f'reject if p_value {p_val} < alpha {alpha}')\n if p_val < alpha:\n print('Reject!')\n else:\n print('Cannot reject.')\n return {'vis': df_vis, 'expected': df_expected}"
] | [
[
"scipy.stats.norm.ppf",
"numpy.sqrt",
"scipy.stats.norm.cdf",
"numpy.min",
"numpy.multiply",
"scipy.stats.t.ppf",
"scipy.stats.t.cdf",
"scipy.stats.chi2.cdf",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jainsee24/Automatic-Number-Plate-Recognition | [
"2fd2a4545fc310cc22b9df9fb51135953fb86cfb"
] | [
"tensorflow_yolov4_tflite/detect_video.py"
] | [
"import time\r\nimport tensorflow as tf\r\nphysical_devices = tf.config.experimental.list_physical_devices('GPU')\r\nif len(physical_devices) > 0:\r\n tf.config.experimental.set_memory_growth(physical_devices[0], True)\r\nfrom absl import app, flags, logging\r\nfrom absl.flags import FLAGS\r\nimport core.utils as utils\r\nfrom core.yolov4 import filter_boxes\r\nfrom tensorflow.python.saved_model import tag_constants\r\nfrom PIL import Image\r\nimport cv2\r\nimport numpy as np\r\nfrom tensorflow.compat.v1 import ConfigProto\r\nfrom tensorflow.compat.v1 import InteractiveSession\r\n\r\nflags.DEFINE_string('framework', 'tf', '(tf, tflite, trt')\r\nflags.DEFINE_string('weights', './checkpoints/yolov4-416',\r\n 'path to weights file')\r\nflags.DEFINE_integer('size', 416, 'resize images to')\r\nflags.DEFINE_boolean('tiny', False, 'yolo or yolo-tiny')\r\nflags.DEFINE_string('model', 'yolov4', 'yolov3 or yolov4')\r\nflags.DEFINE_string('video', './data/video/video.mp4', 'path to input video or set to 0 for webcam')\r\nflags.DEFINE_string('output', None, 'path to output video')\r\nflags.DEFINE_string('output_format', 'XVID', 'codec used in VideoWriter when saving video to file')\r\nflags.DEFINE_float('iou', 0.45, 'iou threshold')\r\nflags.DEFINE_float('score', 0.25, 'score threshold')\r\n\r\ndef main(_argv):\r\n config = ConfigProto()\r\n config.gpu_options.allow_growth = True\r\n session = InteractiveSession(config=config)\r\n STRIDES, ANCHORS, NUM_CLASS, XYSCALE = utils.load_config(FLAGS)\r\n input_size = FLAGS.size\r\n video_path = FLAGS.video\r\n\r\n if FLAGS.framework == 'tflite':\r\n interpreter = tf.lite.Interpreter(model_path=FLAGS.weights)\r\n interpreter.allocate_tensors()\r\n input_details = interpreter.get_input_details()\r\n output_details = interpreter.get_output_details()\r\n print(input_details)\r\n print(output_details)\r\n else:\r\n saved_model_loaded = tf.saved_model.load(FLAGS.weights, tags=[tag_constants.SERVING])\r\n infer = saved_model_loaded.signatures['serving_default']\r\n\r\n # begin video capture\r\n try:\r\n vid = cv2.VideoCapture(int(video_path))\r\n except:\r\n vid = cv2.VideoCapture(video_path)\r\n\r\n out = None\r\n\r\n if FLAGS.output:\r\n # by default VideoCapture returns float instead of int\r\n width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH))\r\n height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))\r\n fps = int(vid.get(cv2.CAP_PROP_FPS))\r\n codec = cv2.VideoWriter_fourcc(*FLAGS.output_format)\r\n out = cv2.VideoWriter(FLAGS.output, codec, fps, (width, height))\r\n\r\n while True:\r\n return_value, frame = vid.read()\r\n if return_value:\r\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\r\n image = Image.fromarray(frame)\r\n else:\r\n print('Video has ended or failed, try a different video format!')\r\n break\r\n \r\n frame_size = frame.shape[:2]\r\n image_data = cv2.resize(frame, (input_size, input_size))\r\n image_data = image_data / 255.\r\n image_data = image_data[np.newaxis, ...].astype(np.float32)\r\n start_time = time.time()\r\n\r\n if FLAGS.framework == 'tflite':\r\n interpreter.set_tensor(input_details[0]['index'], image_data)\r\n interpreter.invoke()\r\n pred = [interpreter.get_tensor(output_details[i]['index']) for i in range(len(output_details))]\r\n if FLAGS.model == 'yolov3' and FLAGS.tiny == True:\r\n boxes, pred_conf = filter_boxes(pred[1], pred[0], score_threshold=0.25,\r\n input_shape=tf.constant([input_size, input_size]))\r\n else:\r\n boxes, pred_conf = filter_boxes(pred[0], pred[1], score_threshold=0.25,\r\n input_shape=tf.constant([input_size, input_size]))\r\n else:\r\n batch_data = tf.constant(image_data)\r\n pred_bbox = infer(batch_data)\r\n for key, value in pred_bbox.items():\r\n boxes = value[:, :, 0:4]\r\n pred_conf = value[:, :, 4:]\r\n\r\n boxes, scores, classes, valid_detections = tf.image.combined_non_max_suppression(\r\n boxes=tf.reshape(boxes, (tf.shape(boxes)[0], -1, 1, 4)),\r\n scores=tf.reshape(\r\n pred_conf, (tf.shape(pred_conf)[0], -1, tf.shape(pred_conf)[-1])),\r\n max_output_size_per_class=50,\r\n max_total_size=50,\r\n iou_threshold=FLAGS.iou,\r\n score_threshold=FLAGS.score\r\n )\r\n pred_bbox = [boxes.numpy(), scores.numpy(), classes.numpy(), valid_detections.numpy()]\r\n image = utils.draw_bbox(frame, pred_bbox)\r\n fps = 1.0 / (time.time() - start_time)\r\n print(\"FPS: %.2f\" % fps)\r\n result = np.asarray(image)\r\n cv2.namedWindow(\"result\", cv2.WINDOW_AUTOSIZE)\r\n result = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\r\n cv2.imshow(\"result\", result)\r\n \r\n if FLAGS.output:\r\n out.write(result)\r\n if cv2.waitKey(1) & 0xFF == ord('q'): break\r\n cv2.destroyAllWindows()\r\n\r\nif __name__ == '__main__':\r\n try:\r\n app.run(main)\r\n except SystemExit:\r\n pass\r\n"
] | [
[
"tensorflow.compat.v1.ConfigProto",
"tensorflow.constant",
"tensorflow.saved_model.load",
"tensorflow.config.experimental.set_memory_growth",
"numpy.asarray",
"tensorflow.lite.Interpreter",
"tensorflow.config.experimental.list_physical_devices",
"tensorflow.shape",
"tensorflow.compat.v1.InteractiveSession"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dingmyu/mmdetection | [
"705dc91ca43ea62f4f69355a81271d5bd81268ca"
] | [
"old_version/mmdet_apis_env_7ef08d32c0e2f8585b07423c9e027338ca16486f.py"
] | [
"import logging\nimport os\nimport random\nimport subprocess\n\nimport numpy as np\nimport torch\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nfrom mmcv.runner import get_dist_info\n\n\ndef init_dist(launcher, backend='nccl', **kwargs):\n if mp.get_start_method(allow_none=True) is None:\n mp.set_start_method('spawn')\n if launcher == 'pytorch':\n _init_dist_pytorch(backend, **kwargs)\n elif launcher == 'mpi':\n _init_dist_mpi(backend, **kwargs)\n elif launcher == 'slurm':\n _init_dist_slurm(backend, **kwargs)\n else:\n raise ValueError('Invalid launcher type: {}'.format(launcher))\n\n\ndef _init_dist_pytorch(backend, **kwargs):\n # TODO: use local_rank instead of rank % num_gpus\n rank = int(os.environ['RANK'])\n num_gpus = torch.cuda.device_count()\n torch.cuda.set_device(rank % num_gpus)\n dist.init_process_group(backend=backend, **kwargs)\n\n\ndef _init_dist_mpi(backend, **kwargs):\n raise NotImplementedError\n\n\ndef _init_dist_slurm(backend, port=29500, **kwargs):\n proc_id = int(os.environ['SLURM_PROCID'])\n ntasks = int(os.environ['SLURM_NTASKS'])\n node_list = os.environ['SLURM_NODELIST']\n num_gpus = torch.cuda.device_count()\n torch.cuda.set_device(proc_id % num_gpus)\n addr = subprocess.getoutput(\n 'scontrol show hostname {} | head -n1'.format(node_list))\n os.environ['MASTER_PORT'] = str(port)\n os.environ['MASTER_ADDR'] = addr\n os.environ['WORLD_SIZE'] = str(ntasks)\n os.environ['RANK'] = str(proc_id)\n dist.init_process_group(backend=backend)\n\n\ndef set_random_seed(seed):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n\n\ndef get_root_logger(log_level=logging.INFO):\n logger = logging.getLogger()\n if not logger.hasHandlers():\n logging.basicConfig(\n format='%(asctime)s - %(levelname)s - %(message)s',\n level=log_level)\n rank, _ = get_dist_info()\n if rank != 0:\n logger.setLevel('ERROR')\n return logger"
] | [
[
"torch.multiprocessing.set_start_method",
"torch.distributed.init_process_group",
"numpy.random.seed",
"torch.cuda.set_device",
"torch.manual_seed",
"torch.multiprocessing.get_start_method",
"torch.cuda.manual_seed_all",
"torch.cuda.device_count"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jhnnsrs/xarray-multiscale | [
"cb4e08bc21db9cfaae5aa096683c91d40acd79c0"
] | [
"src/xarray_multiscale/reducers.py"
] | [
"from typing import Any, Sequence, Tuple, cast, TypeVar, Dict\nfrom scipy.stats import mode\nfrom numpy.typing import NDArray\n\n\ndef windowed_mean(\n array: NDArray[Any], window_size: Tuple[int, ...], **kwargs: Dict[Any, Any]\n) -> NDArray[Any]:\n \"\"\"\n Compute the windowed mean of an array.\n \"\"\"\n reshaped = reshape_with_windows(array, window_size)\n result = reshaped.mean(axis=tuple(range(1, reshaped.ndim, 2)), **kwargs)\n cast(NDArray[Any], result)\n return result\n\n\ndef windowed_mode(array: NDArray[Any], window_size: Tuple[int, ...]) -> NDArray[Any]:\n \"\"\"\n Coarsening by computing the n-dimensional mode.\n \"\"\"\n reshaped = reshape_with_windows(array, window_size)\n transposed_shape = tuple(range(0, reshaped.ndim, 2)) + tuple(\n range(1, reshaped.ndim, 2)\n )\n transposed = reshaped.transpose(transposed_shape)\n collapsed = transposed.reshape(tuple(reshaped.shape[slice(0, None, 2)]) + (-1,))\n result = mode(collapsed, axis=collapsed.ndim - 1).mode.squeeze(axis=-1)\n return result\n\n\ndef reshape_with_windows(\n array: NDArray[Any], window_size: Sequence[int]\n) -> NDArray[Any]:\n new_shape = ()\n for s, f in zip(array.shape, window_size):\n new_shape += (s // f, f)\n return array.reshape(new_shape)\n"
] | [
[
"scipy.stats.mode"
]
] | [
{
"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": []
}
] |
ENOT-AutoDL/onnx2torch | [
"2391987b3349bed1670ac3c1bc9062a37323abe3"
] | [
"onnx2torch/node_converters/cumsum.py"
] | [
"from copy import deepcopy\n\nimport torch\nfrom torch import nn\n\nfrom onnx2torch.node_converters.registry import add_converter\nfrom onnx2torch.onnx_graph import OnnxGraph\nfrom onnx2torch.onnx_node import OnnxNode\nfrom onnx2torch.utils.common import OnnxToTorchModule\nfrom onnx2torch.utils.common import OperationConverterResult\nfrom onnx2torch.utils.common import onnx_mapping_from_node\n\n\ndef _arbitrary_dim_shift_and_insert_zero(\n input_tensor: torch.Tensor,\n insert_dim: int,\n) -> torch.Tensor:\n\n # single item shift\n slice_index, insertion = [[slice(None)] * len(input_tensor.shape)] * 2\n insert_dim_size = input_tensor.shape[insert_dim]\n\n slice_index[insert_dim] = slice(0, -1)\n slice_index = tuple(slice_index)\n tensor_slice = input_tensor[slice_index]\n\n insert_index = torch.arange(start=1, end=insert_dim_size, dtype=torch.int64, device=input_tensor.device)\n index_shape = [1] * len(input_tensor.shape)\n index_shape[insert_dim] = insert_dim_size - 1\n\n insert_index = torch.reshape(insert_index, index_shape)\n insert_index = insert_index + torch.zeros_like(tensor_slice, dtype=torch.int64, device=input_tensor.device)\n\n input_tensor = torch.scatter(\n input=input_tensor,\n dim=insert_dim,\n index=insert_index,\n src=tensor_slice,\n )\n\n insertion[insert_dim] = slice(0, 1)\n insertion = tuple(insertion)\n input_tensor[insertion] = 0\n\n return input_tensor\n\n\nclass OnnxCumSum(nn.Module, OnnxToTorchModule):\n def __init__(\n self,\n exclusive: bool = False,\n reverse: bool = False,\n ):\n super().__init__()\n self.exclusive = exclusive\n self.reverse = reverse\n\n def forward(self, input_tensor: torch.Tensor, axis: torch.Tensor) -> torch.Tensor:\n axis = axis.item()\n if self.reverse:\n input_tensor = torch.flip(input_tensor, dims=(axis,))\n\n if self.exclusive:\n input_tensor = _arbitrary_dim_shift_and_insert_zero(input_tensor, insert_dim=axis)\n\n input_tensor = torch.cumsum(input_tensor, dim=axis)\n\n if self.reverse:\n input_tensor = torch.flip(input_tensor, dims=(axis,))\n\n return input_tensor\n\n\n@add_converter(operation_type='CumSum', version=11)\n@add_converter(operation_type='CumSum', version=14)\ndef _(node: OnnxNode, graph: OnnxGraph) -> OperationConverterResult: # pylint: disable=unused-argument\n node_attributes = node.attributes\n exclusive = bool(node_attributes.get('exclusive', 0))\n reverse = bool(node_attributes.get('reverse', 1))\n\n return OperationConverterResult(\n torch_module=OnnxCumSum(exclusive, reverse),\n onnx_mapping=onnx_mapping_from_node(node),\n )\n"
] | [
[
"torch.reshape",
"torch.zeros_like",
"torch.scatter",
"torch.arange",
"torch.flip",
"torch.cumsum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
JuanDavidPiscoJaimes/DeepLearningClassifier | [
"7ba3b022498e5d2ce0a3cfc3987f11415763312f"
] | [
"train.py"
] | [
"import numpy as np\nimport torch\nfrom torch import nn, optim\nfrom torchvision import datasets, transforms, models\nimport argparse\n\nresnet50 = models.resnet50(pretrained=True)\nalexnet = models.alexnet(pretrained=True)\nvgg16 = models.vgg16(pretrained=True)\n\nmodels = {'resnet': resnet50, 'alexnet': alexnet, 'vgg': vgg16}\n\n\ndef get_args():\n \n parser = argparse.ArgumentParser()\n \n parser.add_argument('data_directory', action=\"store\")\n \n parser.add_argument('--save_dir', type = str, default = '/', \n help = 'path to the checkpoints.pth') \n parser.add_argument('--arch', type = str, default = 'resnet50', \n help = 'choose the CNN model you want to use') \n parser.add_argument('--learning_rate', type = float, default = 0.01, \n help = 'learning rate value') \n parser.add_argument('--hidden_units', type = int, default = 1024, \n help = 'hidden units number') \n parser.add_argument('--epochs', type = int, default = 20, \n help = 'number of epochs') \n parser.add_argument('--gpu', action='store_true',\n default=False,\n dest='gpu',\n help='set gpu usage to true')\n in_args = parser.parse_args()\n \n return in_args\n\n\n\ndef training(hidden_units, arch, datadir, epochs, gpu_b, lrv, saving):\n \n train_dir = datadir + '/train'\n \n valid_dir = datadir + '/valid'\n \n \n train_transforms = transforms.Compose([transforms.RandomRotation(45),\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485,0.456,0.406],\n [0.229,0.224,0.225])])\n\n valid_transforms = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485,0.456,0.406],\n [0.229,0.224,0.225])])\n\n\n\n train_data = datasets.ImageFolder(train_dir, transform = train_transforms)\n\n valid_data = datasets.ImageFolder(valid_dir, transform = valid_transforms)\n \n\n train_loader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)\n\n valid_loader = torch.utils.data.DataLoader(valid_data, batch_size = 64)\n \n model = models[arch]\n \n device = 'cuda' if gpu_b == True else 'cpu'\n \n for param in model.parameters():\n param.requires_grad = False\n \n if models[arch] == resnet50:\n input_units = 2048\n \n model.fc = nn.Sequential(\n nn.Linear(input_units, hidden_units),\n nn.ReLU(),\n nn.Dropout(p = 0.2),\n nn.Linear(hidden_units, 102),\n nn.LogSoftmax(dim=1))\n optimizer = optim.Adam(model.fc.parameters(), lr=lrv)\n \n elif models[arch] == alexnet:\n input_units = 9216\n \n model.classifier = nn.Sequential(\n nn.Linear(input_units, hidden_units),\n nn.ReLU(),\n nn.Dropout(p = 0.2),\n nn.Linear(hidden_units, 102),\n nn.LogSoftmax(dim=1))\n optimizer = optim.Adam(model.classifier.parameters(), lr=lrv)\n \n else:\n input_units = 25088\n \n model.classifier = nn.Sequential(\n nn.Linear(input_units, hidden_units),\n nn.ReLU(),\n nn.Dropout(p = 0.2),\n nn.Linear(hidden_units, 102),\n nn.LogSoftmax(dim=1))\n optimizer = optim.Adam(model.classifier.parameters(), lr=lrv)\n \n criterion = nn.NLLLoss()\n\n model.to(device)\n \n running_loss = 0\n\n steps = 0\n\n for e in range(epochs):\n print('Epoch number: ', e+1)\n for inputs, labels in train_loader:\n\n #Training Loop\n\n inputs, labels = inputs.to(device), labels.to(device)\n optimizer.zero_grad()\n outputs = model.forward(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n\n steps += 1\n\n if steps == 5:\n model.eval()\n accuracy = 0\n valid_loss = 0\n\n with torch.no_grad():\n\n for inputs, labels in valid_loader:\n\n #Validation Loop\n\n inputs, labels = inputs.to(device), labels.to(device)\n outputs = model.forward(inputs)\n ps = torch.exp(outputs)\n top_p, top_class = ps.topk(1, dim=1)\n loss_valid = criterion(outputs, labels)\n valid_loss += loss_valid.item()\n\n equals = top_class == labels.view(*top_class.shape)\n accuracy += torch.mean(equals.type(torch.FloatTensor)).item()\n\n print(\n f\"Train loss: {running_loss/steps:.3f}.. \"\n f\"Validation loss: {valid_loss/len(valid_loader):.3f}.. \"\n f\"Validation accuracy: {accuracy/len(valid_loader):.3f}\")\n\n running_loss = 0 \n steps = 0 \n model.train()\n \n \n model.class_to_idx = train_data.class_to_idx\n\n checkpoint = {'input_size': input_units,\n 'model': models[arch],\n 'output_size': 102,\n 'hidden_layers': hidden_units,\n 'state_dict': model.state_dict(),\n 'epochs': epochs,\n 'optimizer_state': optimizer.state_dict,\n 'mapping_classes': model.class_to_idx}\n\n torch.save(checkpoint, saving + '/training.pth')\n print(model)\n print('Training finished!')\n\n\ndef main():\n in_args = get_args()\n print('Training Started!')\n training(hidden_units = in_args.hidden_units, arch = in_args.arch, datadir = in_args.data_directory, epochs = in_args.epochs, gpu_b = in_args.gpu, lrv = in_args.learning_rate, saving = in_args.save_dir)\n \n \nif __name__ == '__main__':\n main()"
] | [
[
"torch.nn.NLLLoss",
"torch.nn.Dropout",
"torch.nn.LogSoftmax",
"torch.utils.data.DataLoader",
"torch.exp",
"torch.nn.Linear",
"torch.no_grad",
"torch.nn.ReLU",
"torch.save"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
seanjunheng2/PlasmaPy | [
"6df9583cc47375687a07300c0aa11ba31634d770",
"7b4e4aaf8b03d88b654456bca881329ade09e377",
"7b4e4aaf8b03d88b654456bca881329ade09e377"
] | [
"plasmapy/formulary/tests/test_magnetostatics.py",
"plasmapy/formulary/radiation.py",
"plasmapy/formulary/quantum.py"
] | [
"import numpy as np\nimport pytest\n\nfrom astropy import constants\nfrom astropy import units as u\n\nfrom plasmapy.formulary.magnetostatics import (\n CircularWire,\n FiniteStraightWire,\n GeneralWire,\n InfiniteStraightWire,\n MagneticDipole,\n)\n\nmu0_4pi = constants.mu0 / 4 / np.pi\n\n\nclass Test_MagneticDipole:\n def setup_method(self):\n self.moment = np.array([0, 0, 1]) * u.A * u.m * u.m\n self.p0 = np.array([0, 0, 0]) * u.m\n\n def test_value1(self):\n \"Test a known solution\"\n p = np.array([1, 0, 0])\n B1 = MagneticDipole(self.moment, self.p0).magnetic_field(p)\n B1_expected = np.array([0, 0, -1]) * 1e-7 * u.T\n assert np.all(np.isclose(B1.value, B1_expected.value))\n assert B1.unit == u.T\n\n def test_value2(self):\n \"Test a known solution\"\n p = np.array([0, 0, 1])\n B2 = MagneticDipole(self.moment, self.p0).magnetic_field(p)\n B2_expected = np.array([0, 0, 2]) * 1e-7 * u.T\n assert np.all(np.isclose(B2.value, B2_expected.value))\n assert B2.unit == u.T\n\n def test_repr(self):\n \"Test __repr__ function\"\n B1 = MagneticDipole(self.moment, self.p0)\n assert repr(B1) == r\"MagneticDipole(moment=[0. 0. 1.]A m2, p0=[0. 0. 0.]m)\"\n\n\nclass Test_GeneralWire:\n def setup_method(self):\n self.cw = CircularWire(\n np.array([0, 0, 1]), np.array([0, 0, 0]) * u.m, 1 * u.m, 1 * u.A\n )\n p1 = np.array([0.0, 0.0, 0.0]) * u.m\n p2 = np.array([0.0, 0.0, 1.0]) * u.m\n self.fw = FiniteStraightWire(p1, p2, 1 * u.A)\n\n def test_not_callable(self):\n \"Test that `GeneralWire` raises `ValueError` if its first argument is not callale\"\n with pytest.raises(ValueError):\n GeneralWire(\"wire\", 0, 1, 1 * u.A)\n\n def test_close_cw(self):\n \"Test if the GeneralWire is close to the CircularWire it converted from\"\n gw_cw = self.cw.to_GeneralWire()\n p = np.array([0, 0, 0])\n B_cw = self.cw.magnetic_field(p)\n B_gw_cw = gw_cw.magnetic_field(p)\n\n assert np.all(np.isclose(B_cw.value, B_gw_cw.value))\n assert B_cw.unit == B_gw_cw.unit\n\n def test_repr(self):\n \"Test __repr__ function\"\n gw_cw = self.cw.to_GeneralWire()\n # round numbers to avoid calculation accuracy mismatch\n gw_cw.t1 = -3.1516\n gw_cw.t2 = +3.1516\n assert (\n repr(gw_cw)\n == r\"GeneralWire(parametric_eq=curve, t1=-3.1516, t2=3.1516, current=1.0A)\"\n )\n\n def test_close_fw(self):\n \"Test if the GeneralWire is close to the FiniteWire it converted from\"\n gw_fw = self.fw.to_GeneralWire()\n p = np.array([1, 0, 0])\n B_fw = self.fw.magnetic_field(p)\n B_gw_fw = gw_fw.magnetic_field(p)\n\n assert np.all(np.isclose(B_fw.value, B_gw_fw.value))\n assert B_fw.unit == B_gw_fw.unit\n\n def test_value_error(self):\n \"Test GeneralWire raise ValueError when argument t1>t2\"\n with pytest.raises(ValueError):\n gw_cw = GeneralWire(lambda t: [0, 0, t], 2, 1, 1.0 * u.A)\n\n\nclass Test_FiniteStraightWire:\n def setup_method(self):\n self.p1 = np.array([0.0, 0.0, -1.0]) * u.m\n self.p2 = np.array([0.0, 0.0, 1.0]) * u.m\n self.current = 1 * u.A\n\n def test_same_point(self):\n \"Test that `FintiteStraightWire` raises `ValueError` if p1 == p2\"\n with pytest.raises(ValueError):\n FiniteStraightWire(self.p1, self.p1, self.current)\n\n def test_value1(self):\n \"Test a known solution\"\n fw = FiniteStraightWire(self.p1, self.p2, self.current)\n B1 = fw.magnetic_field([1, 0, 0])\n B1_expected = np.array([0, np.sqrt(2), 0]) * 1e-7 * u.T\n assert np.all(np.isclose(B1.value, B1_expected.value))\n assert B1.unit == u.T\n\n def test_repr(self):\n \"Test __repr__ function\"\n fw = FiniteStraightWire(self.p1, self.p2, self.current)\n assert (\n repr(fw)\n == r\"FiniteStraightWire(p1=[ 0. 0. -1.]m, p2=[0. 0. 1.]m, current=1.0A)\"\n )\n\n\nclass Test_InfiniteStraightWire:\n def setup_method(self):\n self.direction = np.array([0, 1, 0])\n self.p0 = np.array([0, 0, 0]) * u.m\n self.current = 1 * u.A\n\n def test_value1(self):\n \"Test a known solution\"\n iw = InfiniteStraightWire(self.direction, self.p0, self.current)\n B1 = iw.magnetic_field([1, 0, 0])\n B1_expected = np.array([0, 0, -2]) * 1e-7 * u.T\n assert np.all(np.isclose(B1.value, B1_expected.value))\n assert B1.unit == u.T\n\n def test_repr(self):\n \"Test __repr__ function\"\n iw = InfiniteStraightWire(self.direction, self.p0, self.current)\n assert (\n repr(iw)\n == r\"InfiniteStraightWire(direction=[0. 1. 0.], p0=[0. 0. 0.]m, current=1.0A)\"\n )\n\n\nclass Test_CircularWire:\n def setup_method(self):\n self.normalz = np.array([0, 0, 1])\n self.normalx = np.array([1, 0, 0])\n self.center = np.array([0, 0, 0]) * u.m\n self.radius = 1 * u.m\n self.current = 1 * u.A\n\n def test_negative_radius(self):\n \"Test that `FintiteStraightWire` raises `ValueError` if radius < 0\"\n with pytest.raises(ValueError):\n CircularWire(self.normalz, self.center, -1.0 * u.m, self.current)\n\n def test_value1(self):\n \"Test a known solution\"\n cw = CircularWire(self.normalz, self.center, self.radius, self.current)\n B1 = cw.magnetic_field([0, 0, 1])\n B1_expected = np.array([0, 0, 1]) * 2 * np.pi / 2 ** 1.5 * 1e-7 * u.T\n assert np.all(np.isclose(B1.value, B1_expected.value))\n assert B1.unit == u.T\n\n def test_value2(self):\n \"Test a known solution\"\n cw = CircularWire(self.normalx, self.center, self.radius, self.current)\n B2 = cw.magnetic_field([1, 0, 0])\n B2_expected = np.array([1, 0, 0]) * 2 * np.pi / 2 ** 1.5 * 1e-7 * u.T\n assert np.all(np.isclose(B2.value, B2_expected.value))\n assert B2.unit == u.T\n\n def test_repr(self):\n \"Test __repr__ function\"\n cw = CircularWire(self.normalz, self.center, self.radius, self.current)\n assert (\n repr(cw)\n == r\"CircularWire(normal=[0. 0. 1.], center=[0. 0. 0.]m, radius=1.0m, current=1.0A)\"\n )\n",
"\"\"\"\nFunctions for calculating quantities associated with electromagnetic\nradiation.\n\"\"\"\n\n__all__ = [\n \"thermal_bremsstrahlung\",\n]\n\nimport astropy.constants as const\nimport astropy.units as u\nimport numpy as np\n\nfrom scipy.special import exp1\n\nfrom plasmapy.formulary.parameters import plasma_frequency\nfrom plasmapy.particles import Particle, particle_input\nfrom plasmapy.utils.decorators import validate_quantities\nfrom plasmapy.utils.exceptions import PhysicsError\n\n\n@validate_quantities(\n frequencies={\"can_be_negative\": False},\n n_e={\"can_be_negative\": False},\n n_i={\"can_be_negative\": False},\n T_e={\"can_be_negative\": False, \"equivalencies\": u.temperature_energy()},\n)\n@particle_input\ndef thermal_bremsstrahlung(\n frequencies: u.Hz,\n n_e: u.m ** -3,\n T_e: u.K,\n n_i: u.m ** -3 = None,\n ion_species: Particle = \"H+\",\n kmax: u.m = None,\n) -> np.ndarray:\n r\"\"\"\n Calculate the bremsstrahlung emission spectrum for a Maxwellian plasma\n in the Rayleigh-Jeans limit :math:`ℏ ω ≪ k_B T_e`\n\n .. math::\n \\frac{dP}{dω} = \\frac{8 \\sqrt{2}}{3\\sqrt{π}}\n \\bigg ( \\frac{e^2}{4 π ε_0} \\bigg )^3\n \\bigg ( m_e c^2 \\bigg )^{-\\frac{3}{2}}\n \\bigg ( 1 - \\frac{ω_{pe}^2}{ω^2} \\bigg )^\\frac{1}{2}\n \\frac{Z_i^2 n_i n_e}{\\sqrt(k_B T_e)}\n E_1(y)\n\n where :math:`E_1` is the exponential integral\n\n .. math::\n E_1 (y) = - \\int_{-y}^∞ \\frac{e^{-t}}{t}dt\n\n and :math:`y` is the dimensionless argument\n\n .. math::\n y = \\frac{1}{2} \\frac{ω^2 m_e}{k_{max}^2 k_B T_e}\n\n where :math:`k_{max}` is a maximum wavenumber approximated here as\n :math:`k_{max} = 1/λ_B` where :math:`λ_B` is the electron\n de Broglie wavelength.\n\n Parameters\n ----------\n frequencies : `~astropy.units.Quantity`\n Array of frequencies over which the bremsstrahlung spectrum will be\n calculated (convertible to Hz).\n\n n_e : `~astropy.units.Quantity`\n Electron number density in the plasma (convertible to m\\ :sup:`-3`\\ ).\n\n T_e : `~astropy.units.Quantity`\n Temperature of the electrons (in K or convertible to eV).\n\n n_i : `~astropy.units.Quantity`, optional\n Ion number density in the plasma (convertible to m\\ :sup:`-3`\\ ). Defaults\n to the quasi-neutral condition :math:`n_i = n_e / Z`\\ .\n\n ion : `str` or `~plasmapy.particles.Particle`, optional\n An instance of `~plasmapy.particles.Particle`, or a string\n convertible to `~plasmapy.particles.Particle`.\n\n kmax : `~astropy.units.Quantity`\n Cutoff wavenumber (convertible to radians per meter). Defaults\n to the inverse of the electron de Broglie wavelength.\n\n Returns\n -------\n spectrum : `~astropy.units.Quantity`\n Computed bremsstrahlung spectrum over the frequencies provided.\n\n Notes\n -----\n For details, see \"Radiation Processes in Plasmas\" by\n Bekefi. `ISBN 978\\\\-0471063506`_.\n\n .. _`ISBN 978\\\\-0471063506`: https://ui.adsabs.harvard.edu/abs/1966rpp..book.....B/abstract\n \"\"\"\n\n # Default n_i is n_e/Z:\n if n_i is None:\n n_i = n_e / ion_species.charge_number\n\n # Default value of kmax is the electrom thermal de Broglie wavelength\n if kmax is None:\n kmax = (np.sqrt(const.m_e.si * const.k_B.si * T_e) / const.hbar.si).to(1 / u.m)\n\n # Convert frequencies to angular frequencies\n ω = (frequencies * 2 * np.pi * u.rad).to(u.rad / u.s)\n\n # Calculate the electron plasma frequency\n ω_pe = plasma_frequency(n=n_e, particle=\"e-\")\n\n # Check that all ω < wpe (this formula is only valid in this limit)\n if np.min(ω) < ω_pe:\n raise PhysicsError(\n \"Lowest frequency must be larger than the electron \"\n f\"plasma frequency {ω_pe:.1e}, but min(ω) = {np.min(ω):.1e}\"\n )\n\n # Check that the parameters given fall within the Rayleigh-Jeans limit\n # hω << kT_e\n rj_const = (\n np.max(ω) * const.hbar.si / (2 * np.pi * u.rad * const.k_B.si * T_e)\n ).to(u.dimensionless_unscaled)\n if rj_const.value > 0.1:\n\n raise PhysicsError(\n \"Rayleigh-Jeans limit not satisfied: \"\n f\"ℏω/kT_e = {rj_const.value:.2e} > 0.1. \"\n \"Try lower ω or higher T_e.\"\n )\n\n # Calculate the bremsstrahlung power spectral density in several steps\n c1 = (\n (8 / 3)\n * np.sqrt(2 / np.pi)\n * (const.e.si ** 2 / (4 * np.pi * const.eps0.si)) ** 3\n * 1\n / (const.m_e.si * const.c.si ** 2) ** 1.5\n )\n\n Zi = ion_species.charge_number\n c2 = (\n np.sqrt(1 - ω_pe ** 2 / ω ** 2)\n * Zi ** 2\n * n_i\n * n_e\n / np.sqrt(const.k_B.si * T_e)\n )\n\n # Dimensionless argument for exponential integral\n arg = 0.5 * ω ** 2 * const.m_e.si / (kmax ** 2 * const.k_B.si * T_e) / u.rad ** 2\n # Remove units, get ndarray of values\n arg = (arg.to(u.dimensionless_unscaled)).value\n\n return c1 * c2 * exp1(arg)\n",
"\"\"\"\nFunctions for quantum parameters, including electron degenerate\ngases and warm dense matter.\n\n\"\"\"\n__all__ = [\n \"chemical_potential\",\n \"deBroglie_wavelength\",\n \"Fermi_energy\",\n \"Thomas_Fermi_length\",\n \"thermal_deBroglie_wavelength\",\n \"Wigner_Seitz_radius\",\n]\n__aliases__ = [\"Ef_\", \"lambdaDB_\", \"lambdaDB_th_\"]\n\nimport astropy.units as u\nimport numpy as np\n\nfrom astropy.constants.si import c, e, eps0, h, hbar, k_B, m_e\n\nfrom plasmapy import particles\nfrom plasmapy.formulary import mathematics\nfrom plasmapy.formulary.relativity import Lorentz_factor\nfrom plasmapy.utils import RelativityError\nfrom plasmapy.utils.decorators import validate_quantities\n\n__all__ += __aliases__\n\n\n# TODO: Use @check_relativistic and @particle_input\n@validate_quantities(\n V={\"can_be_negative\": True}, validations_on_return={\"can_be_negative\": False}\n)\ndef deBroglie_wavelength(V: u.m / u.s, particle) -> u.m:\n r\"\"\"\n Return the de Broglie wavelength.\n\n The de Broglie wavelength (:math:`λ_{dB}`) of a particle is defined by\n\n .. math::\n\n λ_{dB} = \\frac{h}{p} = \\frac{h}{γ m V}\n\n where :math:`h` is the Planck constant, :math:`p` is the\n relativistic momentum of the particle, :math:`γ` is the\n Lorentz factor, :math:`m` is the mass of the particle, and\n :math:`V` is the velocity of the particle.\n\n **Aliases:** `lambdaDB_`\n\n Parameters\n ----------\n V : `~astropy.units.Quantity`\n Particle velocity in units convertible to meters per second.\n\n particle : `str`, `~plasmapy.particles.Particle`, or `~astropy.units.Quantity`\n An instance of `~plasmapy.particles.particle_class.Particle`, or\n an equvalent representation (e.g., ``'e'``, ``'p'``, ``'D+'``, or\n ``'He-4 1+'``), for the particle of interest, or the particle\n mass in units convertible to kg. If a\n `~plasmapy.particles.particle_class.Particle` instance is given, then the\n particle mass is retrieved from the object.\n\n Returns\n -------\n lambda_dB : `~astropy.units.Quantity`\n The de Broglie wavelength in units of meters.\n\n Raises\n ------\n `TypeError`\n If the velocity is not a `~astropy.units.Quantity` and cannot be\n converted into a `~astropy.units.Quantity`.\n\n `~astropy.units.UnitConversionError`\n If the velocity is not in appropriate units.\n\n `~plasmapy.utils.exceptions.RelativityError`\n If the magnitude of ``V`` is larger than the speed of light.\n\n Warns\n -----\n : `~astropy.units.UnitsWarning`\n If units are not provided, SI units are assumed.\n\n Examples\n --------\n >>> from astropy import units as u\n >>> velocity = 1.4e7 * u.m / u.s\n >>> deBroglie_wavelength(velocity, 'e')\n <Quantity 5.18997095e-11 m>\n >>> deBroglie_wavelength(V = 0 * u.m / u.s, particle = 'D+')\n <Quantity inf m>\n \"\"\"\n\n V = np.abs(V)\n\n if np.any(V >= c):\n raise RelativityError(\n \"Velocity input in deBroglie_wavelength cannot \"\n \"be greater than or equal to the speed of \"\n \"light.\"\n )\n\n if not isinstance(particle, u.Quantity):\n try:\n # TODO: Replace with more general routine!\n m = particles.particle_mass(particle)\n except Exception:\n raise ValueError(\"Unable to find particle mass.\")\n else:\n try:\n m = particle.to(u.kg)\n except Exception:\n raise u.UnitConversionError(\n \"The second argument for deBroglie_wavelength must be either a \"\n \"representation of a particle or a\"\n \" Quantity with units of mass.\"\n )\n\n if V.size > 1:\n\n lambda_dBr = np.ones(V.shape) * np.inf * u.m\n indices = V.value != 0\n lambda_dBr[indices] = h / (m * V[indices] * Lorentz_factor(V[indices]))\n\n else:\n\n if V == 0 * u.m / u.s:\n lambda_dBr = np.inf * u.m\n else:\n lambda_dBr = h / (Lorentz_factor(V) * m * V)\n\n return lambda_dBr\n\n\nlambdaDB_ = deBroglie_wavelength\n\"\"\"Alias to `~plasmapy.formulary.quantum.deBroglie_wavelength`.\"\"\"\n\n\n@validate_quantities(\n T_e={\"can_be_negative\": False, \"equivalencies\": u.temperature_energy()},\n validations_on_return={\"can_be_negative\": False},\n)\ndef thermal_deBroglie_wavelength(T_e: u.K) -> u.m:\n r\"\"\"\n Calculate the thermal de Broglie wavelength for electrons.\n\n **Aliases:** `lambdaDB_th_`\n\n Parameters\n ----------\n T_e : `~astropy.units.Quantity`\n Electron temperature.\n\n Returns\n -------\n lambda_dbTh : `~astropy.units.Quantity`\n The thermal de Broglie wavelength for electrons in meters.\n\n Raises\n ------\n `TypeError`\n If argument is not a `~astropy.units.Quantity`.\n\n `~astropy.units.UnitConversionError`\n If argument is in incorrect units.\n\n `ValueError`\n If argument contains invalid values.\n\n Warns\n -----\n : `~astropy.units.UnitsWarning`\n If units are not provided, SI units are assumed.\n\n Notes\n -----\n The thermal de Broglie wavelength is approximately the average de Broglie\n wavelength for electrons in an ideal gas and is given by\n\n .. math::\n\n λ_{dbTh} = \\frac{h}{\\sqrt{2 π m_e k_B T_e}}\n\n Examples\n --------\n >>> from astropy import units as u\n >>> thermal_deBroglie_wavelength(1 * u.eV)\n <Quantity 6.9193675e-10 m>\n \"\"\"\n lambda_dbTh = h / np.sqrt(2 * np.pi * m_e * k_B * T_e)\n return lambda_dbTh\n\n\nlambdaDB_th_ = thermal_deBroglie_wavelength\n\"\"\"Alias to `~plasmapy.formulary.quantum.thermal_deBroglie_wavelength`.\"\"\"\n\n\n@validate_quantities(\n n_e={\"can_be_negative\": False}, validations_on_return={\"can_be_negative\": False}\n)\ndef Fermi_energy(n_e: u.m ** -3) -> u.J:\n r\"\"\"\n Calculate the kinetic energy in a degenerate electron gas.\n\n **Aliases:** `Ef_`\n\n Parameters\n ----------\n n_e : ~astropy.units.Quantity\n Electron number density.\n\n Returns\n -------\n energy_F : `~astropy.units.Quantity`\n The Fermi energy in joules.\n\n Raises\n ------\n `TypeError`\n If argument is not a `~astropy.units.Quantity`.\n\n `~astropy.units.UnitConversionError`\n If argument is in incorrect units.\n\n `ValueError`\n If argument contains invalid values.\n\n Warns\n -----\n : `~astropy.units.UnitsWarning`\n If units are not provided, SI units are assumed.\n\n Notes\n -----\n The Fermi energy is the kinetic energy in a degenerate electron gas\n and is given by\n\n .. math::\n\n E_F = \\frac{π^2 ℏ^2}{2 m_e}\n \\left( \\frac{3 n_e}{π} \\right)^{2/3}\n\n This quantity is often used in place of thermal energy for analysis\n of cold, dense plasmas (e.g. warm dense matter, condensed matter).\n\n See Also\n --------\n Thomas_Fermi_length\n\n Examples\n --------\n >>> from astropy import units as u\n >>> Fermi_energy(1e23 * u.cm**-3)\n <Quantity 1.2586761e-18 J>\n \"\"\"\n coeff = (np.pi * hbar) ** 2 / (2 * m_e)\n energy_F = coeff * (3 * n_e / np.pi) ** (2 / 3)\n return energy_F\n\n\nEf_ = Fermi_energy\n\"\"\"Alias to `~plasmapy.formulary.quantum.Fermi_energy`.\"\"\"\n\n\n@validate_quantities(\n n_e={\"can_be_negative\": False}, validations_on_return={\"can_be_negative\": False}\n)\ndef Thomas_Fermi_length(n_e: u.m ** -3) -> u.m:\n r\"\"\"\n Calculate the exponential scale length for charge screening\n for cold and dense plasmas.\n\n Parameters\n ----------\n n_e : `~astropy.units.Quantity`\n Electron number density.\n\n Returns\n -------\n lambda_TF : `~astropy.units.Quantity`\n The Thomas-Fermi screening length in meters.\n\n Raises\n ------\n `TypeError`\n If argument is not a `~astropy.units.Quantity`.\n\n `~astropy.units.UnitConversionError`\n If argument is in incorrect units.\n\n `ValueError`\n If argument contains invalid values.\n\n Warns\n -----\n : `~astropy.units.UnitsWarning`\n If units are not provided, SI units are assumed.\n\n Notes\n -----\n The Thomas-Fermi screening length is the exponential scale length for\n charge screening and is given by\n\n .. math::\n\n λ_{TF} = \\sqrt{\\frac{2 ε_0 E_F}{3 n_e e^2}}\n\n for an electron degenerate gas.\n\n This quantity is often used in place of the Debye length for analysis\n of cold, dense plasmas (e.g. warm dense matter, condensed matter).\n\n The electrical potential will drop by a factor of :math:`1/e` every\n Thomas-Fermi screening length.\n\n Plasmas will generally be quasineutral on length scales significantly\n larger than the Thomas-Fermi screening length.\n\n See Also\n --------\n Fermi_energy\n plasmapy.formulary.Debye_length\n\n Examples\n --------\n >>> from astropy import units as u\n >>> Thomas_Fermi_length(1e23 * u.cm**-3)\n <Quantity 5.37991409e-11 m>\n\n \"\"\"\n energy_F = Fermi_energy(n_e)\n lambda_TF = np.sqrt(2 * eps0 * energy_F / (3 * n_e * e ** 2))\n return lambda_TF\n\n\n@validate_quantities(\n n={\"can_be_negative\": False}, validations_on_return={\"can_be_negative\": False}\n)\ndef Wigner_Seitz_radius(n: u.m ** -3) -> u.m:\n r\"\"\"\n Calculate the Wigner-Seitz radius, which approximates the inter-particle\n spacing.\n\n This function returns the radius of a sphere whose volume is\n equal to the mean volume per atom in a solid. This parameter is\n often used to calculate the coupling parameter.\n When ion density is used, this is the ion sphere radius, i.e., the\n space occupied by a single ion with no other ions in that space. Higher\n density means less space for each ion, so the radius is smaller.\n\n Parameters\n ----------\n n : `~astropy.units.Quantity`\n Particle number density.\n\n Returns\n -------\n radius : `~astropy.units.Quantity`\n The Wigner-Seitz radius in meters.\n\n Raises\n ------\n `TypeError`\n If argument is not a ~astropy.units.Quantity.\n\n `~astropy.units.UnitConversionError`\n If argument is in incorrect units.\n\n `ValueError`\n If argument contains invalid values.\n\n Warns\n -----\n : `~astropy.units.UnitsWarning`\n If units are not provided, SI units are assumed.\n\n Notes\n -----\n The Wigner-Seitz radius approximates the interparticle spacing.\n It is the radius of a sphere whose volume is equal to the mean\n volume per atom in a solid:\n\n .. math::\n r = \\left(\\frac{3}{4 π n}\\right)^{1/3}\n\n See Also\n --------\n Fermi_energy\n\n Examples\n --------\n >>> from astropy import units as u\n >>> Wigner_Seitz_radius(1e29 * u.m**-3)\n <Quantity 1.33650462e-10 m>\n\n \"\"\"\n radius = (3 / (4 * np.pi * n)) ** (1 / 3)\n return radius\n\n\n# TODO: remove NotImplementedError and 'doctest: +SKIP' when the following issues are addressed...\n# https://github.com/PlasmaPy/PlasmaPy/issues/726\n# https://github.com/astropy/astropy/issues/9721\n@validate_quantities(\n n_e={\"can_be_negative\": False},\n T={\"can_be_negative\": False, \"equivalencies\": u.temperature_energy()},\n)\ndef chemical_potential(n_e: u.m ** -3, T: u.K) -> u.dimensionless_unscaled:\n r\"\"\"\n Calculate the ideal chemical potential.\n\n Parameters\n ----------\n n_e : `~astropy.units.Quantity`\n Electron number density.\n\n T : ~astropy.units.Quantity\n The temperature.\n\n Returns\n -------\n beta_mu : `~astropy.units.Quantity`\n The dimensionless ideal chemical potential. That is the ratio of\n the ideal chemical potential to the thermal energy.\n\n Raises\n ------\n `TypeError`\n If argument is not a `~astropy.units.Quantity`.\n\n `~astropy.units.UnitConversionError`\n If argument is in incorrect units.\n\n `ValueError`\n If argument contains invalid values.\n\n Warns\n -----\n : `~astropy.units.UnitsWarning`\n If units are not provided, SI units are assumed.\n\n Notes\n -----\n The ideal chemical potential is given by [1]_:\n\n .. math::\n χ_a = I_{1/2}(β μ_a^{ideal})\n\n where :math:`χ` is the degeneracy parameter, :math:`I_{1/2}` is the\n Fermi integral with order 1/2, :math:`β` is the inverse thermal\n energy :math:`β = 1/(k_B T)`, and :math:`μ_a^{ideal}`\n is the ideal chemical potential.\n\n The definition for the ideal chemical potential is implicit, so it must\n be obtained numerically by solving for the Fermi integral for values\n of chemical potential approaching the degeneracy parameter. Since values\n returned from the Fermi_integral are complex, a nonlinear\n Levenberg-Marquardt least squares method is used to iteratively approach\n a value of :math:`μ` which minimizes\n :math:`I_{1/2}(β μ_a^{ideal}) - χ_a`\n\n This function returns :math:`β μ^{ideal}` the dimensionless\n ideal chemical potential.\n\n Warning: at present this function is limited to relatively small\n arguments due to limitations in the `~mpmath` package's implementation\n of `~mpmath.polylog`, which PlasmaPy uses in calculating the Fermi\n integral.\n\n References\n ----------\n .. [1] Bonitz, Michael. Quantum kinetic theory. Stuttgart: Teubner, 1998.\n\n Examples\n --------\n >>> from astropy import units as u\n >>> chemical_potential(n_e=1e21*u.cm**-3,T=11000*u.K) # doctest: +SKIP\n <Quantity 2.00039985e-12>\n\n \"\"\"\n\n raise NotImplementedError(\n \"This function has been temporarily disabled due to a bug.\\n\"\n \"Please refer to https://github.com/PlasmaPy/PlasmaPy/issues/726 \\n\"\n \"and https://github.com/astropy/astropy/issues/9721 \"\n \"for progress in fixing it.\"\n )\n # deBroglie wavelength\n lambdaDB = thermal_deBroglie_wavelength(T)\n # degeneracy parameter\n degen = (n_e * lambdaDB ** 3).to(u.dimensionless_unscaled)\n\n def residual(params, data, eps_data):\n \"\"\"Residual function for fitting parameters to Fermi_integral.\"\"\"\n alpha = params[\"alpha\"].value\n # note that alpha = mu / (k_B * T)\n model = mathematics.Fermi_integral(alpha, 0.5)\n complexResidue = (data - model) / eps_data\n return complexResidue.view(np.float)\n\n # setting parameters for fitting along with bounds\n alphaGuess = 1 * u.dimensionless_unscaled\n try:\n from lmfit import minimize, Parameters\n except (ImportError, ModuleNotFoundError) as e:\n from plasmapy.optional_deps import lmfit_import_error\n\n raise lmfit_import_error from e\n\n params = Parameters()\n params.add(\"alpha\", value=alphaGuess, min=0.0)\n # calling minimize function from lmfit to fit by minimizing the residual\n data = np.array([degen]) # result of Fermi_integral - degen should be zero\n eps_data = np.array([1e-15]) # numerical error\n minFit = minimize(residual, params, args=(data, eps_data))\n beta_mu = minFit.params[\"alpha\"].value * u.dimensionless_unscaled\n return beta_mu\n\n\n# TODO: decorate with validate_quantities\n# TODO: remove NotImplementedError and 'doctest: +SKIP' when the following issues are addressed...\n# https://github.com/PlasmaPy/PlasmaPy/issues/726\n# https://github.com/astropy/astropy/issues/9721\ndef _chemical_potential_interp(n_e, T):\n r\"\"\"\n Fitting formula for interpolating chemical potential between classical\n and quantum regimes.\n\n See [1]_, [2]_ for more information.\n\n Parameters\n ----------\n n_e : `~astropy.units.Quantity`\n Electron number density.\n\n T : `~astropy.units.Quantity`\n Temperature in units of temperature or energy.\n\n Returns\n -------\n beta_mu : `~astropy.units.Quantity`\n The dimensionless chemical potential, which is a ratio of\n chemical potential energy to thermal kinetic energy.\n\n Raises\n ------\n `TypeError`\n If argument is not a `~astropy.units.Quantity`.\n\n `~astropy.units.UnitConversionError`\n If argument is in incorrect units.\n\n `ValueError`\n If argument contains invalid values.\n\n Warns\n -----\n : `~astropy.units.UnitsWarning`\n If units are not provided, SI units are assumed.\n\n Notes\n -----\n The ideal chemical potential is given by [1]_:\n\n .. math::\n \\frac{μ}{k_B T_e} = - \\frac{3}{2} \\ln Θ + \\ln\n \\frac{4}{3 \\sqrt{π}} +\n \\frac{A Θ^{-b - 1} + B Θ^{-(b + 1) / 2}}{1 + A Θ^{-b}}\n\n where\n\n .. math::\n Θ = \\frac{k_B T_e}{E_F}\n\n is the degeneracy parameter, comparing the thermal energy to the\n Fermi energy, and the coefficients for the fitting formula are\n :math:`A = 0.25945`\\ , :math:`B = 0.0072`\\ , and :math:`b = 0.858`\\ .\n\n References\n ----------\n .. [1] Ichimaru, Statistical Plasma Physics Addison-Wesley,\n Reading, MA, 1991.\n\n .. [2] Gregori, G., et al. \"Theoretical model of x-ray scattering as a\n dense matter probe.\" Physical Review E 67.2 (2003): 026412.\n\n Examples\n --------\n >>> from astropy import units as u\n >>> _chemical_potential_interp(n_e=1e23*u.cm**-3, T=11000*u.K) # doctest: +SKIP\n <Quantity 8.17649>\n\n \"\"\"\n raise NotImplementedError(\n \"This function has been temporarily disabled due to a bug.\\n\"\n \"Please refer to https://github.com/PlasmaPy/PlasmaPy/issues/726 \\n\"\n \"and https://github.com/astropy/astropy/issues/9721 \"\n \"for progress in fixing it.\"\n )\n A = 0.25945\n B = 0.072\n b = 0.858\n theta = k_B * T / Fermi_energy(n_e)\n term1 = -3 / 2 * np.log(theta)\n term2 = np.log(4 / (3 * np.sqrt(np.pi)))\n term3num = A * theta ** (-b - 1) + B * theta ** (-(b + 1) / 2)\n term3den = 1 + A * theta ** (-b)\n term3 = term3num / term3den\n beta_mu = term1 + term2 + term3\n return beta_mu.to(u.dimensionless_unscaled)\n"
] | [
[
"numpy.array",
"numpy.sqrt",
"numpy.isclose"
],
[
"numpy.max",
"numpy.sqrt",
"scipy.special.exp1",
"numpy.min"
],
[
"numpy.log",
"numpy.sqrt",
"numpy.abs",
"numpy.ones",
"numpy.any",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
qpython-android/QPypi-numpy | [
"4e5fa5c2e01bb6250537fe44f426f878a240bcc7"
] | [
"numpy/core/tests/test_umath.py"
] | [
"from numpy.testing import *\nimport numpy.core.umath as ncu\nimport numpy as np\n\nclass TestDivision(TestCase):\n def test_division_int(self):\n # int division should return the floor of the result, a la Python\n x = np.array([5, 10, 90, 100, -5, -10, -90, -100, -120])\n assert_equal(x / 100, [0, 0, 0, 1, -1, -1, -1, -1, -2])\n assert_equal(x // 100, [0, 0, 0, 1, -1, -1, -1, -1, -2])\n assert_equal(x % 100, [5, 10, 90, 0, 95, 90, 10, 0, 80])\n\nclass TestPower(TestCase):\n def test_power_float(self):\n x = np.array([1., 2., 3.])\n assert_equal(x**0, [1., 1., 1.])\n assert_equal(x**1, x)\n assert_equal(x**2, [1., 4., 9.])\n y = x.copy()\n y **= 2\n assert_equal(y, [1., 4., 9.])\n assert_almost_equal(x**(-1), [1., 0.5, 1./3])\n assert_almost_equal(x**(0.5), [1., ncu.sqrt(2), ncu.sqrt(3)])\n\n def test_power_complex(self):\n x = np.array([1+2j, 2+3j, 3+4j])\n assert_equal(x**0, [1., 1., 1.])\n assert_equal(x**1, x)\n assert_equal(x**2, [-3+4j, -5+12j, -7+24j])\n assert_equal(x**3, [(1+2j)**3, (2+3j)**3, (3+4j)**3])\n assert_equal(x**4, [(1+2j)**4, (2+3j)**4, (3+4j)**4])\n assert_almost_equal(x**(-1), [1/(1+2j), 1/(2+3j), 1/(3+4j)])\n assert_almost_equal(x**(-2), [1/(1+2j)**2, 1/(2+3j)**2, 1/(3+4j)**2])\n assert_almost_equal(x**(-3), [(-11+2j)/125, (-46-9j)/2197,\n (-117-44j)/15625])\n assert_almost_equal(x**(0.5), [ncu.sqrt(1+2j), ncu.sqrt(2+3j),\n ncu.sqrt(3+4j)])\n assert_almost_equal(x**14, [-76443+16124j, 23161315+58317492j,\n 5583548873 + 2465133864j])\n\n # Ticket #836\n def assert_complex_equal(x, y):\n assert_array_equal(x.real, y.real)\n assert_array_equal(x.imag, y.imag)\n \n for z in [complex(0, np.inf), complex(1, np.inf)]:\n z = np.array([z], dtype=np.complex_)\n assert_complex_equal(z**1, z)\n assert_complex_equal(z**2, z*z)\n assert_complex_equal(z**3, z*z*z)\n\nclass TestLog2(TestCase):\n def test_log2_values(self) :\n x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]\n y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n for dt in ['f','d','g'] :\n xf = np.array(x, dtype=dt)\n yf = np.array(y, dtype=dt)\n assert_almost_equal(np.log2(xf), yf)\n\nclass TestExp2(TestCase):\n def test_exp2_values(self) :\n x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]\n y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n for dt in ['f','d','g'] :\n xf = np.array(x, dtype=dt)\n yf = np.array(y, dtype=dt)\n assert_almost_equal(np.exp2(yf), xf)\n\nclass TestLogAddExp2(object):\n # Need test for intermediate precisions\n def test_logaddexp2_values(self) :\n x = [1, 2, 3, 4, 5]\n y = [5, 4, 3, 2, 1]\n z = [6, 6, 6, 6, 6]\n for dt, dec in zip(['f','d','g'],[6, 15, 15]) :\n xf = np.log2(np.array(x, dtype=dt))\n yf = np.log2(np.array(y, dtype=dt))\n zf = np.log2(np.array(z, dtype=dt))\n assert_almost_equal(np.logaddexp2(xf, yf), zf, decimal=dec)\n\n def test_logaddexp2_range(self) :\n x = [1000000, -1000000, 1000200, -1000200]\n y = [1000200, -1000200, 1000000, -1000000]\n z = [1000200, -1000000, 1000200, -1000000]\n for dt in ['f','d','g'] :\n logxf = np.array(x, dtype=dt)\n logyf = np.array(y, dtype=dt)\n logzf = np.array(z, dtype=dt)\n assert_almost_equal(np.logaddexp(logxf, logyf), logzf)\n\nclass TestLog(TestCase):\n def test_log_values(self) :\n x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]\n y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n for dt in ['f','d','g'] :\n log2_ = 0.69314718055994530943\n xf = np.array(x, dtype=dt)\n yf = np.array(y, dtype=dt)*log2_\n assert_almost_equal(np.log(xf), yf)\n\nclass TestExp(TestCase):\n def test_exp_values(self) :\n x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]\n y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n for dt in ['f','d','g'] :\n log2_ = 0.69314718055994530943\n xf = np.array(x, dtype=dt)\n yf = np.array(y, dtype=dt)*log2_\n assert_almost_equal(np.exp(yf), xf)\n\nclass TestLogAddExp(object):\n def test_logaddexp_values(self) :\n x = [1, 2, 3, 4, 5]\n y = [5, 4, 3, 2, 1]\n z = [6, 6, 6, 6, 6]\n for dt, dec in zip(['f','d','g'],[6, 15, 15]) :\n xf = np.log(np.array(x, dtype=dt))\n yf = np.log(np.array(y, dtype=dt))\n zf = np.log(np.array(z, dtype=dt))\n assert_almost_equal(np.logaddexp(xf, yf), zf, decimal=dec)\n\n def test_logaddexp_range(self) :\n x = [1000000, -1000000, 1000200, -1000200]\n y = [1000200, -1000200, 1000000, -1000000]\n z = [1000200, -1000000, 1000200, -1000000]\n for dt in ['f','d','g'] :\n logxf = np.array(x, dtype=dt)\n logyf = np.array(y, dtype=dt)\n logzf = np.array(z, dtype=dt)\n assert_almost_equal(np.logaddexp(logxf, logyf), logzf)\n\nclass TestLog1p(TestCase):\n def test_log1p(self):\n assert_almost_equal(ncu.log1p(0.2), ncu.log(1.2))\n assert_almost_equal(ncu.log1p(1e-6), ncu.log(1+1e-6))\n\nclass TestExpm1(TestCase):\n def test_expm1(self):\n assert_almost_equal(ncu.expm1(0.2), ncu.exp(0.2)-1)\n assert_almost_equal(ncu.expm1(1e-6), ncu.exp(1e-6)-1)\n\nclass TestMaximum(TestCase):\n def test_reduce_complex(self):\n assert_equal(np.maximum.reduce([1,2j]),1)\n assert_equal(np.maximum.reduce([1+3j,2j]),1+3j)\n\n def test_float_nans(self):\n nan = np.nan\n arg1 = np.array([0, nan, nan])\n arg2 = np.array([nan, 0, nan])\n out = np.array([nan, nan, nan])\n assert_equal(np.maximum(arg1, arg2), out)\n\n def test_complex_nans(self):\n nan = np.nan\n for cnan in [nan, nan*1j, nan + nan*1j] :\n arg1 = np.array([0, cnan, cnan], dtype=np.complex)\n arg2 = np.array([cnan, 0, cnan], dtype=np.complex)\n out = np.array([nan, nan, nan], dtype=np.complex)\n assert_equal(np.maximum(arg1, arg2), out)\n\nclass TestMinimum(TestCase):\n def test_reduce_complex(self):\n assert_equal(np.minimum.reduce([1,2j]),2j)\n assert_equal(np.minimum.reduce([1+3j,2j]),2j)\n\n def test_float_nans(self):\n nan = np.nan\n arg1 = np.array([0, nan, nan])\n arg2 = np.array([nan, 0, nan])\n out = np.array([nan, nan, nan])\n assert_equal(np.minimum(arg1, arg2), out)\n\n def test_complex_nans(self):\n nan = np.nan\n for cnan in [nan, nan*1j, nan + nan*1j] :\n arg1 = np.array([0, cnan, cnan], dtype=np.complex)\n arg2 = np.array([cnan, 0, cnan], dtype=np.complex)\n out = np.array([nan, nan, nan], dtype=np.complex)\n assert_equal(np.minimum(arg1, arg2), out)\n\nclass TestFmax(TestCase):\n def test_reduce_complex(self):\n assert_equal(np.fmax.reduce([1,2j]),1)\n assert_equal(np.fmax.reduce([1+3j,2j]),1+3j)\n\n def test_float_nans(self):\n nan = np.nan\n arg1 = np.array([0, nan, nan])\n arg2 = np.array([nan, 0, nan])\n out = np.array([0, 0, nan])\n assert_equal(np.fmax(arg1, arg2), out)\n\n def test_complex_nans(self):\n nan = np.nan\n for cnan in [nan, nan*1j, nan + nan*1j] :\n arg1 = np.array([0, cnan, cnan], dtype=np.complex)\n arg2 = np.array([cnan, 0, cnan], dtype=np.complex)\n out = np.array([0, 0, nan], dtype=np.complex)\n assert_equal(np.fmax(arg1, arg2), out)\n\nclass TestFmin(TestCase):\n def test_reduce_complex(self):\n assert_equal(np.fmin.reduce([1,2j]),2j)\n assert_equal(np.fmin.reduce([1+3j,2j]),2j)\n\n def test_float_nans(self):\n nan = np.nan\n arg1 = np.array([0, nan, nan])\n arg2 = np.array([nan, 0, nan])\n out = np.array([0, 0, nan])\n assert_equal(np.fmin(arg1, arg2), out)\n\n def test_complex_nans(self):\n nan = np.nan\n for cnan in [nan, nan*1j, nan + nan*1j] :\n arg1 = np.array([0, cnan, cnan], dtype=np.complex)\n arg2 = np.array([cnan, 0, cnan], dtype=np.complex)\n out = np.array([0, 0, nan], dtype=np.complex)\n assert_equal(np.fmin(arg1, arg2), out)\n\nclass TestFloatingPoint(TestCase):\n def test_floating_point(self):\n assert_equal(ncu.FLOATING_POINT_SUPPORT, 1)\n\nclass TestDegrees(TestCase):\n def test_degrees(self):\n assert_almost_equal(ncu.degrees(np.pi), 180.0)\n assert_almost_equal(ncu.degrees(-0.5*np.pi), -90.0)\n\nclass TestRadians(TestCase):\n def test_radians(self):\n assert_almost_equal(ncu.radians(180.0), np.pi)\n assert_almost_equal(ncu.radians(-90.0), -0.5*np.pi)\n\nclass TestSpecialMethods(TestCase):\n def test_wrap(self):\n class with_wrap(object):\n def __array__(self):\n return np.zeros(1)\n def __array_wrap__(self, arr, context):\n r = with_wrap()\n r.arr = arr\n r.context = context\n return r\n a = with_wrap()\n x = ncu.minimum(a, a)\n assert_equal(x.arr, np.zeros(1))\n func, args, i = x.context\n self.failUnless(func is ncu.minimum)\n self.failUnlessEqual(len(args), 2)\n assert_equal(args[0], a)\n assert_equal(args[1], a)\n self.failUnlessEqual(i, 0)\n\n def test_wrap_with_iterable(self):\n # test fix for bug #1026:\n class with_wrap(np.ndarray):\n __array_priority__ = 10\n def __new__(cls):\n return np.asarray(1).view(cls).copy()\n def __array_wrap__(self, arr, context):\n return arr.view(type(self))\n a = with_wrap()\n x = ncu.multiply(a, (1, 2, 3))\n self.failUnless(isinstance(x, with_wrap))\n assert_array_equal(x, np.array((1, 2, 3)))\n\n def test_priority_with_scalar(self):\n # test fix for bug #826:\n class A(np.ndarray):\n __array_priority__ = 10\n def __new__(cls):\n return np.asarray(1.0, 'float64').view(cls).copy()\n a = A()\n x = np.float64(1)*a\n self.failUnless(isinstance(x, A))\n assert_array_equal(x, np.array(1))\n\n def test_old_wrap(self):\n class with_wrap(object):\n def __array__(self):\n return np.zeros(1)\n def __array_wrap__(self, arr):\n r = with_wrap()\n r.arr = arr\n return r\n a = with_wrap()\n x = ncu.minimum(a, a)\n assert_equal(x.arr, np.zeros(1))\n\n def test_priority(self):\n class A(object):\n def __array__(self):\n return np.zeros(1)\n def __array_wrap__(self, arr, context):\n r = type(self)()\n r.arr = arr\n r.context = context\n return r\n class B(A):\n __array_priority__ = 20.\n class C(A):\n __array_priority__ = 40.\n x = np.zeros(1)\n a = A()\n b = B()\n c = C()\n f = ncu.minimum\n self.failUnless(type(f(x,x)) is np.ndarray)\n self.failUnless(type(f(x,a)) is A)\n self.failUnless(type(f(x,b)) is B)\n self.failUnless(type(f(x,c)) is C)\n self.failUnless(type(f(a,x)) is A)\n self.failUnless(type(f(b,x)) is B)\n self.failUnless(type(f(c,x)) is C)\n\n self.failUnless(type(f(a,a)) is A)\n self.failUnless(type(f(a,b)) is B)\n self.failUnless(type(f(b,a)) is B)\n self.failUnless(type(f(b,b)) is B)\n self.failUnless(type(f(b,c)) is C)\n self.failUnless(type(f(c,b)) is C)\n self.failUnless(type(f(c,c)) is C)\n\n self.failUnless(type(ncu.exp(a) is A))\n self.failUnless(type(ncu.exp(b) is B))\n self.failUnless(type(ncu.exp(c) is C))\n\n def test_failing_wrap(self):\n class A(object):\n def __array__(self):\n return np.zeros(1)\n def __array_wrap__(self, arr, context):\n raise RuntimeError\n a = A()\n self.failUnlessRaises(RuntimeError, ncu.maximum, a, a)\n\n def test_array_with_context(self):\n class A(object):\n def __array__(self, dtype=None, context=None):\n func, args, i = context\n self.func = func\n self.args = args\n self.i = i\n return np.zeros(1)\n class B(object):\n def __array__(self, dtype=None):\n return np.zeros(1, dtype)\n class C(object):\n def __array__(self):\n return np.zeros(1)\n a = A()\n ncu.maximum(np.zeros(1), a)\n self.failUnless(a.func is ncu.maximum)\n assert_equal(a.args[0], 0)\n self.failUnless(a.args[1] is a)\n self.failUnless(a.i == 1)\n assert_equal(ncu.maximum(a, B()), 0)\n assert_equal(ncu.maximum(a, C()), 0)\n\n\nclass TestChoose(TestCase):\n def test_mixed(self):\n c = np.array([True,True])\n a = np.array([True,True])\n assert_equal(np.choose(c, (a, 1)), np.array([1,1]))\n\n\ndef is_longdouble_finfo_bogus():\n info = np.finfo(np.longcomplex)\n return not np.isfinite(np.log10(info.tiny/info.eps))\n\nclass TestComplexFunctions(object):\n funcs = [np.arcsin, np.arccos, np.arctan, np.arcsinh, np.arccosh,\n np.arctanh, np.sin, np.cos, np.tan, np.exp,\n np.exp2, np.log, np.sqrt, np.log10, np.log2,\n np.log1p]\n\n def test_it(self):\n for f in self.funcs:\n if f is np.arccosh :\n x = 1.5\n else :\n x = .5\n fr = f(x)\n fz = f(np.complex(x))\n assert_almost_equal(fz.real, fr, err_msg='real part %s'%f)\n assert_almost_equal(fz.imag, 0., err_msg='imag part %s'%f)\n\n def test_precisions_consistent(self) :\n z = 1 + 1j\n for f in self.funcs :\n fcf = f(np.csingle(z))\n fcd = f(np.cdouble(z))\n fcl = f(np.clongdouble(z))\n assert_almost_equal(fcf, fcd, decimal=6, err_msg='fch-fcd %s'%f)\n assert_almost_equal(fcl, fcd, decimal=15, err_msg='fch-fcl %s'%f)\n\n def test_branch_cuts(self):\n # check branch cuts and continuity on them\n yield _check_branch_cut, np.log, -0.5, 1j, 1, -1\n yield _check_branch_cut, np.log2, -0.5, 1j, 1, -1\n yield _check_branch_cut, np.log10, -0.5, 1j, 1, -1\n yield _check_branch_cut, np.log1p, -1.5, 1j, 1, -1\n yield _check_branch_cut, np.sqrt, -0.5, 1j, 1, -1\n\n yield _check_branch_cut, np.arcsin, [ -2, 2], [1j, -1j], 1, -1\n yield _check_branch_cut, np.arccos, [ -2, 2], [1j, -1j], 1, -1\n yield _check_branch_cut, np.arctan, [-2j, 2j], [1, -1 ], -1, 1\n\n yield _check_branch_cut, np.arcsinh, [-2j, 2j], [-1, 1], -1, 1\n yield _check_branch_cut, np.arccosh, [ -1, 0.5], [1j, 1j], 1, -1\n yield _check_branch_cut, np.arctanh, [ -2, 2], [1j, -1j], 1, -1\n\n # check against bogus branch cuts: assert continuity between quadrants\n yield _check_branch_cut, np.arcsin, [-2j, 2j], [ 1, 1], 1, 1\n yield _check_branch_cut, np.arccos, [-2j, 2j], [ 1, 1], 1, 1\n yield _check_branch_cut, np.arctan, [ -2, 2], [1j, 1j], 1, 1\n\n yield _check_branch_cut, np.arcsinh, [ -2, 2, 0], [1j, 1j, 1 ], 1, 1\n yield _check_branch_cut, np.arccosh, [-2j, 2j, 2], [1, 1, 1j], 1, 1\n yield _check_branch_cut, np.arctanh, [-2j, 2j, 0], [1, 1, 1j], 1, 1\n\n @dec.knownfailureif(True, \"These branch cuts are known to fail\")\n def test_branch_cuts_failing(self):\n # XXX: signed zero not OK with ICC on 64-bit platform for log, see\n # http://permalink.gmane.org/gmane.comp.python.numeric.general/25335\n yield _check_branch_cut, np.log, -0.5, 1j, 1, -1, True\n yield _check_branch_cut, np.log2, -0.5, 1j, 1, -1, True\n yield _check_branch_cut, np.log10, -0.5, 1j, 1, -1, True\n yield _check_branch_cut, np.log1p, -1.5, 1j, 1, -1, True\n # XXX: signed zeros are not OK for sqrt or for the arc* functions\n yield _check_branch_cut, np.sqrt, -0.5, 1j, 1, -1, True\n yield _check_branch_cut, np.arcsin, [ -2, 2], [1j, -1j], 1, -1, True\n yield _check_branch_cut, np.arccos, [ -2, 2], [1j, -1j], 1, -1, True\n yield _check_branch_cut, np.arctan, [-2j, 2j], [1, -1 ], -1, 1, True\n yield _check_branch_cut, np.arcsinh, [-2j, 2j], [-1, 1], -1, 1, True\n yield _check_branch_cut, np.arccosh, [ -1, 0.5], [1j, 1j], 1, -1, True\n yield _check_branch_cut, np.arctanh, [ -2, 2], [1j, -1j], 1, -1, True\n\n def test_against_cmath(self):\n import cmath, sys\n\n # cmath.asinh is broken in some versions of Python, see\n # http://bugs.python.org/issue1381\n broken_cmath_asinh = False\n if sys.version_info < (2,6):\n broken_cmath_asinh = True\n\n points = [-1-1j, -1+1j, +1-1j, +1+1j]\n name_map = {'arcsin': 'asin', 'arccos': 'acos', 'arctan': 'atan',\n 'arcsinh': 'asinh', 'arccosh': 'acosh', 'arctanh': 'atanh'}\n atol = 4*np.finfo(np.complex).eps\n for func in self.funcs:\n fname = func.__name__.split('.')[-1]\n cname = name_map.get(fname, fname)\n try:\n cfunc = getattr(cmath, cname)\n except AttributeError:\n continue\n for p in points:\n a = complex(func(np.complex_(p)))\n b = cfunc(p)\n\n if cname == 'asinh' and broken_cmath_asinh:\n continue\n\n assert abs(a - b) < atol, \"%s %s: %s; cmath: %s\"%(fname,p,a,b)\n\n def check_loss_of_precision(self, dtype):\n \"\"\"Check loss of precision in complex arc* functions\"\"\"\n\n # Check against known-good functions\n\n info = np.finfo(dtype)\n real_dtype = dtype(0.).real.dtype\n eps = info.eps\n\n def check(x, rtol):\n x = x.astype(real_dtype)\n\n z = x.astype(dtype)\n d = np.absolute(np.arcsinh(x)/np.arcsinh(z).real - 1)\n assert np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(),\n 'arcsinh')\n\n z = (1j*x).astype(dtype)\n d = np.absolute(np.arcsinh(x)/np.arcsin(z).imag - 1)\n assert np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(),\n 'arcsin')\n\n z = x.astype(dtype)\n d = np.absolute(np.arctanh(x)/np.arctanh(z).real - 1)\n assert np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(),\n 'arctanh')\n\n z = (1j*x).astype(dtype)\n d = np.absolute(np.arctanh(x)/np.arctan(z).imag - 1)\n assert np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(),\n 'arctan')\n\n # The switchover was chosen as 1e-3; hence there can be up to\n # ~eps/1e-3 of relative cancellation error before it\n\n x_series = np.logspace(-20, -3.001, 200)\n x_basic = np.logspace(-2.999, 0, 10, endpoint=False)\n\n if dtype is np.longcomplex:\n # It's not guaranteed that the system-provided arc functions\n # are accurate down to a few epsilons. (Eg. on Linux 64-bit)\n # So, give more leeway for long complex tests here:\n check(x_series, 50*eps)\n else:\n check(x_series, 2*eps)\n check(x_basic, 2*eps/1e-3)\n\n # Check a few points\n\n z = np.array([1e-5*(1+1j)], dtype=dtype)\n p = 9.999999999333333333e-6 + 1.000000000066666666e-5j\n d = np.absolute(1-np.arctanh(z)/p)\n assert np.all(d < 1e-15)\n\n p = 1.0000000000333333333e-5 + 9.999999999666666667e-6j\n d = np.absolute(1-np.arcsinh(z)/p)\n assert np.all(d < 1e-15)\n\n p = 9.999999999333333333e-6j + 1.000000000066666666e-5\n d = np.absolute(1-np.arctan(z)/p)\n assert np.all(d < 1e-15)\n\n p = 1.0000000000333333333e-5j + 9.999999999666666667e-6\n d = np.absolute(1-np.arcsin(z)/p)\n assert np.all(d < 1e-15)\n\n # Check continuity across switchover points\n\n def check(func, z0, d=1):\n z0 = np.asarray(z0, dtype=dtype)\n zp = z0 + abs(z0) * d * eps * 2\n zm = z0 - abs(z0) * d * eps * 2\n assert np.all(zp != zm), (zp, zm)\n\n # NB: the cancellation error at the switchover is at least eps\n good = (abs(func(zp) - func(zm)) < 2*eps)\n assert np.all(good), (func, z0[~good])\n\n for func in (np.arcsinh,np.arcsinh,np.arcsin,np.arctanh,np.arctan):\n pts = [rp+1j*ip for rp in (-1e-3,0,1e-3) for ip in(-1e-3,0,1e-3)\n if rp != 0 or ip != 0]\n check(func, pts, 1)\n check(func, pts, 1j)\n check(func, pts, 1+1j)\n\n def test_loss_of_precision(self):\n for dtype in [np.complex64, np.complex_]:\n yield self.check_loss_of_precision, dtype\n\n @dec.knownfailureif(is_longdouble_finfo_bogus(), \"Bogus long double finfo\")\n def test_loss_of_precision_longcomplex(self):\n self.check_loss_of_precision(np.longcomplex)\n\nclass TestAttributes(TestCase):\n def test_attributes(self):\n add = ncu.add\n assert_equal(add.__name__, 'add')\n assert add.__doc__.startswith('add(x1, x2[, out])\\n\\n')\n self.failUnless(add.ntypes >= 18) # don't fail if types added\n self.failUnless('ii->i' in add.types)\n assert_equal(add.nin, 2)\n assert_equal(add.nout, 1)\n assert_equal(add.identity, 0)\n\nclass TestSubclass(TestCase):\n def test_subclass_op(self):\n class simple(np.ndarray):\n def __new__(subtype, shape):\n self = np.ndarray.__new__(subtype, shape, dtype=object)\n self.fill(0)\n return self\n a = simple((3,4))\n assert_equal(a+a, a)\n\ndef _check_branch_cut(f, x0, dx, re_sign=1, im_sign=-1, sig_zero_ok=False,\n dtype=np.complex):\n \"\"\"\n Check for a branch cut in a function.\n\n Assert that `x0` lies on a branch cut of function `f` and `f` is\n continuous from the direction `dx`.\n\n Parameters\n ----------\n f : func\n Function to check\n x0 : array-like\n Point on branch cut\n dx : array-like\n Direction to check continuity in\n re_sign, im_sign : {1, -1}\n Change of sign of the real or imaginary part expected\n sig_zero_ok : bool\n Whether to check if the branch cut respects signed zero (if applicable)\n dtype : dtype\n Dtype to check (should be complex)\n\n \"\"\"\n x0 = np.atleast_1d(x0).astype(dtype)\n dx = np.atleast_1d(dx).astype(dtype)\n\n scale = np.finfo(dtype).eps * 1e3\n atol = 1e-4\n\n y0 = f(x0)\n yp = f(x0 + dx*scale*np.absolute(x0)/np.absolute(dx))\n ym = f(x0 - dx*scale*np.absolute(x0)/np.absolute(dx))\n\n assert np.all(np.absolute(y0.real - yp.real) < atol), (y0, yp)\n assert np.all(np.absolute(y0.imag - yp.imag) < atol), (y0, yp)\n assert np.all(np.absolute(y0.real - ym.real*re_sign) < atol), (y0, ym)\n assert np.all(np.absolute(y0.imag - ym.imag*im_sign) < atol), (y0, ym)\n\n if sig_zero_ok:\n # check that signed zeros also work as a displacement\n jr = (x0.real == 0) & (dx.real != 0)\n ji = (x0.imag == 0) & (dx.imag != 0)\n\n x = -x0\n x.real[jr] = 0.*dx.real\n x.imag[ji] = 0.*dx.imag\n x = -x\n ym = f(x)\n ym = ym[jr | ji]\n y0 = y0[jr | ji]\n assert np.all(np.absolute(y0.real - ym.real*re_sign) < atol), (y0, ym)\n assert np.all(np.absolute(y0.imag - ym.imag*im_sign) < atol), (y0, ym)\n\ndef test_pos_nan():\n \"\"\"Check np.nan is a positive nan.\"\"\"\n assert np.signbit(np.nan) == 0\n\nif __name__ == \"__main__\":\n run_module_suite()\n"
] | [
[
"numpy.exp2",
"numpy.minimum",
"numpy.arctanh",
"numpy.arctan",
"numpy.core.umath.minimum",
"numpy.core.umath.log",
"numpy.asarray",
"numpy.ndarray.__new__",
"numpy.fmin.reduce",
"numpy.all",
"numpy.fmax.reduce",
"numpy.csingle",
"numpy.core.umath.expm1",
"numpy.complex_",
"numpy.clongdouble",
"numpy.exp",
"numpy.arcsin",
"numpy.finfo",
"numpy.core.umath.radians",
"numpy.atleast_1d",
"numpy.choose",
"numpy.argmax",
"numpy.zeros",
"numpy.core.umath.exp",
"numpy.signbit",
"numpy.log",
"numpy.logspace",
"numpy.core.umath.sqrt",
"numpy.cdouble",
"numpy.minimum.reduce",
"numpy.fmax",
"numpy.log10",
"numpy.array",
"numpy.core.umath.multiply",
"numpy.arcsinh",
"numpy.fmin",
"numpy.maximum.reduce",
"numpy.logaddexp",
"numpy.absolute",
"numpy.maximum",
"numpy.log2",
"numpy.complex",
"numpy.core.umath.degrees",
"numpy.float64",
"numpy.logaddexp2",
"numpy.core.umath.log1p"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jjhenkel/dockerizeme | [
"eaa4fe5366f6b9adf74399eab01c712cacaeb279",
"eaa4fe5366f6b9adf74399eab01c712cacaeb279",
"eaa4fe5366f6b9adf74399eab01c712cacaeb279",
"eaa4fe5366f6b9adf74399eab01c712cacaeb279",
"eaa4fe5366f6b9adf74399eab01c712cacaeb279"
] | [
"hard-gists/2f1b9a255993bf9b2629/snippet.py",
"hard-gists/3fdd80a08808bd275142d46863e92d68/snippet.py",
"hard-gists/d97eb37da84ce7329de6/snippet.py",
"hard-gists/8663d3bbfd586bffecf6a0094cd116f2/snippet.py",
"hard-gists/e37a85fb0258b045c005ca3db9cbc7f6/snippet.py"
] | [
"import PIL.Image\nfrom cStringIO import StringIO\nimport IPython.display\nimport numpy as np\ndef showarray(a, fmt='png'):\n a = np.uint8(a)\n f = StringIO()\n PIL.Image.fromarray(a).save(f, fmt)\n IPython.display.display(IPython.display.Image(data=f.getvalue()))",
"#!/usr/bin/env python\nfrom __future__ import print_function\nfrom keras.models import Sequential\nfrom keras.layers import TimeDistributed\nfrom keras.layers.core import Dense, Activation, Dropout, RepeatVector, TimeDistributedDense\nfrom keras.layers.recurrent import LSTM\nfrom keras.utils.data_utils import get_file\nimport numpy as np\nimport random,string\nimport sys\n\npath = get_file('nietzsche.txt', origin=\"https://s3.amazonaws.com/text-datasets/nietzsche.txt\")\n\ntry: \n text = open(path).read().lower()\nexcept UnicodeDecodeError:\n import codecs\n text = codecs.open(path, encoding='utf-8').read().lower()\n\nprint('corpus length:', len(text))\n\nchars = set(text)\nprint('total chars:', len(chars))\nchar_indices = dict((c, i) for i, c in enumerate(chars))\nindices_char = dict((i, c) for i, c in enumerate(chars))\n\nmaxlen = 4 # might be much easier with 3 or 2...\nnbatch = 32\n\nprint('Vectorization...')\nX = np.zeros((len(text), len(chars)), dtype=np.bool)\nfor t, char in enumerate(text):\n X[t, char_indices[char]] = 1\n\n\n# build the model: 2 stacked LSTM\nprint('Build model...')\nmodel = Sequential()\nmodel.add(LSTM(512, stateful=True, return_sequences=False, batch_input_shape=(nbatch, maxlen, len(chars))))\nmodel.add(Dense(256, activation='relu'))\nmodel.add(RepeatVector(maxlen))\nmodel.add(LSTM(512, stateful=True, return_sequences=True))\nmodel.add(TimeDistributed(Dense(len(chars))))\nmodel.add(Activation('softmax'))\n\nmodel.compile(loss='categorical_crossentropy', optimizer='adam')\n\n\ndef sample(a, temperature=1.0):\n # helper function to sample an index from a probability array\n a = np.log(a) / temperature\n a = np.exp(a) / np.sum(np.exp(a))\n return np.argmax(np.random.multinomial(1, a, 1))\n\n# start with a small sample that increases each iteration\nnumsamps = len(X)/100\nnumsampinc = len(X)/100\n\n# train the model, output generated text after each iteration\nfor iteration in range(1, 100):\n print()\n print('-' * 50)\n print('Iteration', iteration)\n\n # get consecutive sequences for each \"lane\" by breaking the dataset\n # into 'nbatch' regions\n # X[0] X[s] X[2*s] ... X[(nbatch-1)*s] X[1] X[s+1] X[2*s+1] ...\n numsamps = min(len(X), numsamps)\n numsamps += numsampinc\n\n stride = int((numsamps-maxlen)/nbatch)\n sampsperbatch = int(stride/maxlen)\n totalsamps = sampsperbatch*nbatch\n XXs = np.zeros((totalsamps, maxlen, len(chars)), dtype=np.bool)\n YYs = np.zeros((totalsamps, maxlen, len(chars)), dtype=np.bool)\n for i in range(0,sampsperbatch):\n for j in range(0,nbatch):\n ofs = j*stride+i*maxlen\n XX = X[ofs:ofs+maxlen]\n YY = X[ofs+maxlen:ofs+maxlen*2]\n XXs[i*nbatch+j] = XX\n YYs[i*nbatch+j] = YY\n \n model.reset_states()\n model.fit(XXs, YYs, batch_size=nbatch, nb_epoch=3, shuffle=False)\n\n start_index = random.randint(0, len(text) - maxlen - 1)\n\n for diversity in [0.2, 0.5, 1.0, 1.2]:\n print()\n print('----- diversity:', diversity)\n\n generated = ''\n sentence = text[start_index: start_index + maxlen]\n generated += sentence\n print('----- Generating with seed: \"' + sentence + '\"')\n sys.stdout.write(generated)\n\n model.reset_states()\n for i in range(400/maxlen):\n x = np.zeros((nbatch, maxlen, len(chars)))\n for t, char in enumerate(sentence):\n x[0, t, char_indices[char]] = 1.\n\n # just get prediction from 1st batch\n preds_seq = model.predict(x, verbose=0)[0]\n \n # don't know if this is correct since each successive sample\n # doesn't take into account the prior...\n next_indices = [sample(preds, diversity) for preds in preds_seq]\n next_chars = string.join([indices_char[next_index] for next_index in next_indices],'')\n\n generated += next_chars\n sentence = next_chars\n\n sys.stdout.write(next_chars)\n sys.stdout.flush()\n print()\n",
"from fipy import Grid1D, CellVariable, FaceVariable, TransientTerm, DiffusionTerm, ExponentialConvectionTerm, ImplicitSourceTerm, Viewer\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nL = 10.0\nnx = 100\ndx = L/nx\ntimeStep = dx/10.0\n\nsteps = 150\nphim = 0.10 # mobile zone porosity\nphiim = 0.05 # immobile zone porosity\nbeta = 0.05 # mobile/immobile domain transfer rate\nD = 1.0E-1 # mobile domain diffusion coeff\nRm = 1.0 # mobile domain retardation coefficient\nRim = 1.0 # immobile domain retardation coefficient\n\nbetaT = phiim*Rim/(phim*Rm)\nDR = D/Rm\n\nm = Grid1D(dx=dx, nx=nx)\nc0 = np.zeros(nx, 'd')\nc0[20:50] = 1.0\n\n# mobile domain concentration\ncm = CellVariable(name=\"$c_m$\", mesh=m, value=c0)\n\n# immobile domain concentration\ncim = CellVariable(name=\"$c_{im}$\", mesh=m, value=0.0)\n\ncm.constrain(0, m.facesLeft)\ncm.constrain(0, m.facesRight)\n\ncim.constrain(0, m.facesLeft)\ncim.constrain(0, m.facesRight)\n\n# advective flow velocity \nu = FaceVariable(mesh=m, value=(0.0,), rank=1)\n\n# 1D convection diffusion equation (mobile domain)\n# version with \\frac{\\partial c_{im}}{\\partial t}\neqM = (TransientTerm(1.0,var=cm) + TransientTerm(betaT,var=cim) == \n DiffusionTerm(DR,var=cm) - ExponentialConvectionTerm(u/(Rm*phim),var=cm))\n\n# immobile domain (lumped approach)\neqIM = TransientTerm(Rim*phiim,var=cim) == beta/Rim*(cm - ImplicitSourceTerm(1.0,var=cim))\n\n# couple equations\neqn = eqM & eqIM\n\nviewer = Viewer(vars=(cm,cim), datamin=0.0, datamax=1.0)\nviewer.plot()\ntime = 0.0\n\nfor step in range(steps):\n time += timeStep\n\n if time < 0.5:\n u.setValue((1.0,))\n elif time < 1.0:\n u.setValue((0.0,))\n else:\n u.setValue((-1.0,))\n\n eqn.solve(dt=timeStep)\n viewer.plot()\n\n\n",
"# Working example for my blog post at:\n# https://danijar.github.io/structuring-your-tensorflow-models\nimport functools\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n\ndef doublewrap(function):\n \"\"\"\n A decorator decorator, allowing to use the decorator to be used without\n parentheses if not arguments are provided. All arguments must be optional.\n \"\"\"\n @functools.wraps(function)\n def decorator(*args, **kwargs):\n if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):\n return function(args[0])\n else:\n return lambda wrapee: function(wrapee, *args, **kwargs)\n return decorator\n\n\n@doublewrap\ndef define_scope(function, scope=None, *args, **kwargs):\n \"\"\"\n A decorator for functions that define TensorFlow operations. The wrapped\n function will only be executed once. Subsequent calls to it will directly\n return the result so that operations are added to the graph only once.\n\n The operations added by the function live within a tf.variable_scope(). If\n this decorator is used with arguments, they will be forwarded to the\n variable scope. The scope name defaults to the name of the wrapped\n function.\n \"\"\"\n attribute = '_cache_' + function.__name__\n name = scope or function.__name__\n @property\n @functools.wraps(function)\n def decorator(self):\n if not hasattr(self, attribute):\n with tf.variable_scope(name, *args, **kwargs):\n setattr(self, attribute, function(self))\n return getattr(self, attribute)\n return decorator\n\n\nclass Model:\n\n def __init__(self, image, label):\n self.image = image\n self.label = label\n self.prediction\n self.optimize\n self.error\n\n @define_scope(initializer=tf.contrib.slim.xavier_initializer())\n def prediction(self):\n x = self.image\n x = tf.contrib.slim.fully_connected(x, 200)\n x = tf.contrib.slim.fully_connected(x, 200)\n x = tf.contrib.slim.fully_connected(x, 10, tf.nn.softmax)\n return x\n\n @define_scope\n def optimize(self):\n logprob = tf.log(self.prediction + 1e-12)\n cross_entropy = -tf.reduce_sum(self.label * logprob)\n optimizer = tf.train.RMSPropOptimizer(0.03)\n return optimizer.minimize(cross_entropy)\n\n @define_scope\n def error(self):\n mistakes = tf.not_equal(\n tf.argmax(self.label, 1), tf.argmax(self.prediction, 1))\n return tf.reduce_mean(tf.cast(mistakes, tf.float32))\n\n\ndef main():\n mnist = input_data.read_data_sets('./mnist/', one_hot=True)\n image = tf.placeholder(tf.float32, [None, 784])\n label = tf.placeholder(tf.float32, [None, 10])\n model = Model(image, label)\n sess = tf.Session()\n sess.run(tf.initialize_all_variables())\n\n for _ in range(10):\n images, labels = mnist.test.images, mnist.test.labels\n error = sess.run(model.error, {image: images, label: labels})\n print('Test error {:6.2f}%'.format(100 * error))\n for _ in range(60):\n images, labels = mnist.train.next_batch(100)\n sess.run(model.optimize, {image: images, label: labels})\n\n\nif __name__ == '__main__':\n main()",
"import os, argparse\n\nimport tensorflow as tf\nfrom tensorflow.python.framework import graph_util\n\ndir = os.path.dirname(os.path.realpath(__file__))\n\ndef freeze_graph(model_folder, output_nodes='y_hat', \n output_filename='frozen-graph.pb', \n rename_outputs=None):\n\n #Load checkpoint \n checkpoint = tf.train.get_checkpoint_state(model_folder)\n input_checkpoint = checkpoint.model_checkpoint_path\n \n output_graph = output_filename\n\n #Devices should be cleared to allow Tensorflow to control placement of \n #graph when loading on different machines\n saver = tf.train.import_meta_graph(input_checkpoint + '.meta', \n clear_devices=True)\n\n graph = tf.get_default_graph()\n\n onames = output_nodes.split(',')\n\n #https://stackoverflow.com/a/34399966/4190475\n if rename_outputs is not None:\n nnames = rename_outputs.split(',')\n with graph.as_default():\n for o, n in zip(onames, nnames):\n _out = tf.identity(graph.get_tensor_by_name(o+':0'), name=n)\n onames=nnames\n\n input_graph_def = graph.as_graph_def()\n\n # fix batch norm nodes\n for node in input_graph_def.node:\n if node.op == 'RefSwitch':\n node.op = 'Switch'\n for index in xrange(len(node.input)):\n if 'moving_' in node.input[index]:\n node.input[index] = node.input[index] + '/read'\n elif node.op == 'AssignSub':\n node.op = 'Sub'\n if 'use_locking' in node.attr: del node.attr['use_locking']\n\n with tf.Session(graph=graph) as sess:\n saver.restore(sess, input_checkpoint)\n\n # In production, graph weights no longer need to be updated\n # graph_util provides utility to change all variables to constants\n output_graph_def = graph_util.convert_variables_to_constants(\n sess, input_graph_def, \n onames # unrelated nodes will be discarded\n ) \n\n # Serialize and write to file\n with tf.gfile.GFile(output_graph, \"wb\") as f:\n f.write(output_graph_def.SerializeToString())\n print(\"%d ops in the final graph.\" % len(output_graph_def.node))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description='Prune and freeze weights from checkpoints into production models')\n parser.add_argument(\"--checkpoint_path\", \n default='ckpt',\n type=str, help=\"Path to checkpoint files\")\n parser.add_argument(\"--output_nodes\", \n default='y_hat',\n type=str, help=\"Names of output node, comma seperated\")\n parser.add_argument(\"--output_graph\", \n default='frozen-graph.pb',\n type=str, help=\"Output graph filename\")\n parser.add_argument(\"--rename_outputs\",\n default=None,\n type=str, help=\"Rename output nodes for better \\\n readability in production graph, to be specified in \\\n the same order as output_nodes\")\n args = parser.parse_args()\n\n freeze_graph(args.checkpoint_path, args.output_nodes, args.output_graph, args.rename_outputs)\n"
] | [
[
"numpy.uint8"
],
[
"numpy.random.multinomial",
"numpy.log",
"numpy.exp"
],
[
"numpy.zeros"
],
[
"tensorflow.train.RMSPropOptimizer",
"tensorflow.reduce_sum",
"tensorflow.cast",
"tensorflow.placeholder",
"tensorflow.contrib.slim.fully_connected",
"tensorflow.initialize_all_variables",
"tensorflow.log",
"tensorflow.Session",
"tensorflow.variable_scope",
"tensorflow.argmax",
"tensorflow.examples.tutorials.mnist.input_data.read_data_sets",
"tensorflow.contrib.slim.xavier_initializer"
],
[
"tensorflow.train.get_checkpoint_state",
"tensorflow.gfile.GFile",
"tensorflow.train.import_meta_graph",
"tensorflow.python.framework.graph_util.convert_variables_to_constants",
"tensorflow.Session",
"tensorflow.get_default_graph"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
wangyuyue/oneflow | [
"0a71c22fe8355392acc8dc0e301589faee4c4832",
"0a71c22fe8355392acc8dc0e301589faee4c4832",
"0a71c22fe8355392acc8dc0e301589faee4c4832",
"0a71c22fe8355392acc8dc0e301589faee4c4832",
"0a71c22fe8355392acc8dc0e301589faee4c4832",
"0a71c22fe8355392acc8dc0e301589faee4c4832",
"0a71c22fe8355392acc8dc0e301589faee4c4832",
"0a71c22fe8355392acc8dc0e301589faee4c4832",
"0a71c22fe8355392acc8dc0e301589faee4c4832",
"0a71c22fe8355392acc8dc0e301589faee4c4832",
"0a71c22fe8355392acc8dc0e301589faee4c4832"
] | [
"python/oneflow/compatible/single_client/test/ops/test_mseloss.py",
"python/oneflow/compatible/single_client/test/ops/test_hardsigmoid.py",
"python/oneflow/compatible/single_client/test/xrt/test_reshape_like.py",
"python/oneflow/compatible/single_client/test/xrt/test_layer_norm_param_grad.py",
"python/oneflow/test/modules/test_where.py",
"python/oneflow/compatible/single_client/test/ops/test_batch_gather.py",
"python/oneflow/compatible/single_client/test/ops/test_optimizers.py",
"python/oneflow/compatible/single_client/test/ops/test_clip_by_value.py",
"python/oneflow/ops/array_ops.py",
"python/oneflow/compatible/single_client/test/xrt/test_matmul.py",
"python/oneflow/test/modules/test_ones_like.py"
] | [
"\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport os\nimport unittest\nfrom collections import OrderedDict\nfrom typing import Dict\n\nimport numpy as np\nfrom test_util import GenArgList\n\nimport oneflow.compatible.single_client.unittest\nfrom oneflow.compatible import single_client as flow\nfrom oneflow.compatible.single_client import typing as tp\n\n\ndef _compare_mseloss_with_np(\n input_shape, target_shape, device_type, machine_ids, device_counts\n):\n input = np.random.random(size=input_shape).astype(np.float32)\n target = np.random.random(size=target_shape).astype(np.float32)\n assert device_type in [\"cpu\", \"gpu\"]\n flow.clear_default_session()\n if device_type == \"cpu\":\n flow.config.cpu_device_num(device_counts)\n else:\n flow.config.gpu_device_num(device_counts)\n func_config = flow.FunctionConfig()\n\n def np_mseloss(np_input, np_target):\n np_mse = np.square(np_target - np_input)\n np_mse_mean = np.mean(np_mse)\n np_mse_sum = np.sum(np_mse)\n return {\n \"np_mse_loss\": np_mse,\n \"np_mse_loss_mean\": np_mse_mean,\n \"np_mse_loss_sum\": np_mse_sum,\n }\n\n def np_mseloss_grad(np_input, np_target):\n elem_cnt = np_input.size\n np_mse_grad_mean = -2 * (np_target - np_input) / elem_cnt\n return {\"np_mse_grad_mean\": np_mse_grad_mean}\n\n np_out_mseloss_dict = np_mseloss(input, target)\n np_grad_dict = np_mseloss_grad(input, target)\n\n def assert_prediction_grad(blob: tp.Numpy):\n assert np.allclose(blob, np_grad_dict[\"np_mse_grad_mean\"])\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def oneflow_mseloss(\n of_input: tp.Numpy.Placeholder(shape=input.shape),\n of_target: tp.Numpy.Placeholder(shape=target.shape),\n ) -> Dict[str, tp.Numpy]:\n with flow.scope.placement(device_type, \"0:0\"):\n v = flow.get_variable(\n shape=input.shape,\n dtype=flow.float32,\n initializer=flow.zeros_initializer(),\n name=\"x_var\",\n )\n x_var = of_input + v\n flow.watch_diff(x_var, assert_prediction_grad)\n mseloss = flow.nn.MSELoss(x_var, of_target, reduction=\"none\", name=\"of_mseloss\")\n mseloss_mean = flow.nn.MSELoss(\n x_var, of_target, reduction=\"mean\", name=\"of_mseloss_reduce_mean\"\n )\n mseloss_sum = flow.nn.MSELoss(\n x_var, of_target, reduction=\"sum\", name=\"of_mseloss_reduce_sum\"\n )\n with flow.scope.placement(device_type, \"0:0\"):\n flow.optimizer.SGD(\n flow.optimizer.PiecewiseConstantScheduler([], [0.001]), momentum=0\n ).minimize(mseloss_mean)\n return {\n \"of_mse_loss\": mseloss,\n \"of_mse_loss_mean\": mseloss_mean,\n \"of_mse_loss_sum\": mseloss_sum,\n }\n\n of_out_mseloss_dict = oneflow_mseloss(input, target)\n assert np.allclose(\n of_out_mseloss_dict[\"of_mse_loss\"], np_out_mseloss_dict[\"np_mse_loss\"]\n )\n assert np.allclose(\n of_out_mseloss_dict[\"of_mse_loss_mean\"], np_out_mseloss_dict[\"np_mse_loss_mean\"]\n )\n assert np.allclose(\n of_out_mseloss_dict[\"of_mse_loss_sum\"], np_out_mseloss_dict[\"np_mse_loss_sum\"]\n )\n\n\ndef _gen_arg_dict(shape, device_type, machine_ids, device_counts):\n arg_dict = OrderedDict()\n arg_dict[\"input_shape\"] = [shape]\n arg_dict[\"target_shape\"] = [shape]\n arg_dict[\"device_type\"] = [device_type]\n arg_dict[\"machine_ids\"] = [machine_ids]\n arg_dict[\"device_counts\"] = [device_counts]\n return arg_dict\n\n\[email protected]_unless_1n1d()\nclass Testmseloss1n1d(flow.unittest.TestCase):\n def test_mseloss_cpu(test_case):\n arg_dict = _gen_arg_dict(\n shape=(3, 16), device_type=\"cpu\", machine_ids=\"0:0\", device_counts=1\n )\n for arg in GenArgList(arg_dict):\n _compare_mseloss_with_np(*arg)\n\n @unittest.skipIf(os.getenv(\"ONEFLOW_TEST_CPU_ONLY\"), \"only test cpu cases\")\n def test_mseloss_gpu(test_case):\n arg_dict = _gen_arg_dict(\n shape=(3, 16, 32), device_type=\"gpu\", machine_ids=\"0:0\", device_counts=1\n )\n for arg in GenArgList(arg_dict):\n _compare_mseloss_with_np(*arg)\n\n\[email protected]_unless_1n2d()\nclass Testmseloss1n2d(flow.unittest.TestCase):\n @unittest.skipIf(os.getenv(\"ONEFLOW_TEST_CPU_ONLY\"), \"only test cpu cases\")\n def test_mseloss_gpu_1n2d(test_case):\n arg_dict = _gen_arg_dict(\n shape=(3, 16, 16), device_type=\"gpu\", machine_ids=\"0:0-1\", device_counts=2\n )\n for arg in GenArgList(arg_dict):\n _compare_mseloss_with_np(*arg)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n",
"\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport os\nimport random\nimport unittest\nfrom collections import OrderedDict\nfrom typing import Dict\n\nimport numpy as np\nfrom test_util import GenArgList\n\nimport oneflow.compatible.single_client.unittest\nfrom oneflow.compatible import single_client as flow\nfrom oneflow.compatible.single_client import typing as tp\n\n\ndef _compare_hardsigmoid_with_np(\n input_shape, device_type, value_type, machine_ids, device_counts\n):\n if value_type[1] == flow.float16:\n input_1 = np.random.uniform(-3.5, 3.5, size=input_shape).astype(np.float16)\n input_1 += np.random.randn(*input_shape).astype(np.float16)\n input_1 = np.array(input_1, dtype=value_type[0])\n else:\n input_1 = np.random.uniform(-3.5, 3.5, size=input_shape).astype(value_type[0])\n input_1 += np.random.randn(*input_shape).astype(value_type[0])\n assert device_type in [\"cpu\", \"gpu\"]\n flow.clear_default_session()\n if device_type == \"cpu\":\n flow.config.cpu_device_num(device_counts)\n else:\n flow.config.gpu_device_num(device_counts)\n func_config = flow.FunctionConfig()\n func_config.default_placement_scope(flow.scope.placement(device_type, machine_ids))\n if value_type[1] == flow.float16:\n func_config.default_data_type(flow.float32)\n else:\n func_config.default_data_type(value_type[1])\n\n def np_hardsigmoid(input):\n input_shape = input.shape\n input = input.flatten()\n elem_cnt = input.size\n _zero = np.zeros_like(input)\n for i in range(elem_cnt):\n if input[i] >= 3:\n _zero[i] = 1\n elif input[i] <= -3:\n _zero[i] = 0\n else:\n _zero[i] = input[i] / 6 + 0.5\n np_hsigmoid_out = np.reshape(_zero, newshape=input_shape)\n return np.array(np_hsigmoid_out).astype(value_type[0])\n\n np_out_hardsigmoid = np_hardsigmoid(input_1)\n\n def np_diff(input):\n input_shape = input.shape\n input = input.flatten()\n elem_cnt = input.size\n diff = np.zeros(shape=(elem_cnt,), dtype=value_type[0])\n for i in range(elem_cnt):\n if input[i] > -3 and input[i] < 3:\n diff[i] = 1 / 6\n diff = np.reshape(diff, newshape=input_shape)\n return diff\n\n _np_grad = np_diff(input_1)\n\n def assert_prediction_grad(blob: tp.Numpy):\n if value_type[1] == flow.float16:\n assert np.allclose(blob, _np_grad, atol=0.001)\n else:\n assert np.allclose(blob, _np_grad, atol=1e-05)\n\n if value_type[1] == flow.float16:\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def oneflow_hardsigmoid(\n of_input_1: tp.Numpy.Placeholder(shape=input_1.shape, dtype=flow.float32)\n ) -> tp.Numpy:\n with flow.scope.placement(device_type, \"0:0\"):\n v = flow.get_variable(\n shape=input_1.shape,\n dtype=flow.float32,\n initializer=flow.zeros_initializer(),\n name=\"x_var\",\n )\n x_var = of_input_1 + v\n x_f16 = flow.cast(x_var, flow.float16)\n of_hardsigmoid_out_f16 = flow.nn.hardsigmoid(x_f16)\n of_hardsigmoid_out_f32 = flow.cast(of_hardsigmoid_out_f16, flow.float32)\n with flow.scope.placement(device_type, \"0:0\"):\n flow.optimizer.SGD(\n flow.optimizer.PiecewiseConstantScheduler([], [0.001]), momentum=0\n ).minimize(of_hardsigmoid_out_f32)\n flow.watch_diff(x_var, assert_prediction_grad)\n return of_hardsigmoid_out_f32\n\n else:\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def oneflow_hardsigmoid(\n of_input_1: tp.Numpy.Placeholder(shape=input_1.shape, dtype=value_type[1])\n ) -> tp.Numpy:\n with flow.scope.placement(device_type, \"0:0\"):\n v = flow.get_variable(\n shape=input_1.shape,\n dtype=value_type[1],\n initializer=flow.zeros_initializer(),\n name=\"x_var\",\n )\n x_var = of_input_1 + v\n flow.watch_diff(x_var, assert_prediction_grad)\n of_hardsigmoid_out = flow.nn.hardsigmoid(x_var)\n with flow.scope.placement(device_type, \"0:0\"):\n flow.optimizer.SGD(\n flow.optimizer.PiecewiseConstantScheduler([], [0.001]), momentum=0\n ).minimize(of_hardsigmoid_out)\n return of_hardsigmoid_out\n\n of_out_hardsigmoid = oneflow_hardsigmoid(input_1)\n if value_type[1] == flow.float16:\n assert np.allclose(of_out_hardsigmoid, np_out_hardsigmoid, atol=0.01)\n else:\n assert np.allclose(of_out_hardsigmoid, np_out_hardsigmoid, atol=1e-05)\n\n\ndef _gen_arg_dict(shape, device_type, value_type, machine_ids, device_counts):\n arg_dict = OrderedDict()\n arg_dict[\"input_shape\"] = [shape]\n arg_dict[\"device_type\"] = [device_type]\n if value_type == \"float\" and device_type == \"cpu\":\n arg_dict[\"value_type\"] = [\n (np.float32, flow.float32),\n (np.float64, flow.float64),\n ]\n else:\n arg_dict[\"value_type\"] = [\n (np.float32, flow.float16),\n (np.float32, flow.float32),\n (np.float64, flow.float64),\n ]\n arg_dict[\"machine_ids\"] = [machine_ids]\n arg_dict[\"device_counts\"] = [device_counts]\n return arg_dict\n\n\[email protected]_unless_1n1d()\nclass Testhardsigmoid1n1d(flow.unittest.TestCase):\n def test_hardsigmoid_cpu(test_case):\n arg_dict = _gen_arg_dict(\n shape=(3, 16),\n device_type=\"cpu\",\n value_type=\"float\",\n machine_ids=\"0:0\",\n device_counts=1,\n )\n for arg in GenArgList(arg_dict):\n _compare_hardsigmoid_with_np(*arg)\n\n @unittest.skipIf(os.getenv(\"ONEFLOW_TEST_CPU_ONLY\"), \"only test cpu cases\")\n def test_hardsigmoid_gpu(test_case):\n arg_dict = _gen_arg_dict(\n shape=(16, 16),\n device_type=\"gpu\",\n value_type=\"float\",\n machine_ids=\"0:0\",\n device_counts=1,\n )\n for arg in GenArgList(arg_dict):\n _compare_hardsigmoid_with_np(*arg)\n\n\[email protected]_unless_1n2d()\nclass Testhardsigmoid1n2d(flow.unittest.TestCase):\n @unittest.skipIf(os.getenv(\"ONEFLOW_TEST_CPU_ONLY\"), \"only test cpu cases\")\n def test_hardsigmoid_gpu_1n2d(test_case):\n arg_dict = _gen_arg_dict(\n shape=(4, 8, 16),\n device_type=\"gpu\",\n value_type=\"float\",\n machine_ids=\"0:0-1\",\n device_counts=2,\n )\n for arg in GenArgList(arg_dict):\n _compare_hardsigmoid_with_np(*arg)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n",
"\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport unittest\n\nimport numpy as np\n\nimport oneflow.compatible.single_client.unittest\nfrom oneflow.compatible import single_client as flow\n\nconfig = flow.function_config()\n\n\ndef make_job(x_shape, like_shape, dtype=flow.float32):\n config.use_xla_jit(False)\n config.use_tensorrt(False)\n\n @flow.global_function(config)\n def reshape_like_job(\n x=flow.FixedTensorDef(x_shape, dtype=dtype),\n like=flow.FixedTensorDef(like_shape, dtype=dtype),\n ):\n return flow.reshape_like(x, like)\n\n return reshape_like_job\n\n\ndef make_xla_job(x_shape, like_shape, dtype=flow.float32):\n config.use_xla_jit(True)\n config.use_tensorrt(False)\n\n @flow.global_function(config)\n def xla_reshape_like_job(\n x=flow.FixedTensorDef(x_shape, dtype=dtype),\n like=flow.FixedTensorDef(like_shape, dtype=dtype),\n ):\n return flow.reshape_like(x, like)\n\n return xla_reshape_like_job\n\n\ndef make_trt_job(x_shape, like_shape, dtype=flow.float32):\n config.use_xla_jit(False)\n config.use_tensorrt(True)\n\n @flow.global_function(config)\n def trt_reshape_like_job(\n x=flow.FixedTensorDef(x_shape, dtype=dtype),\n like=flow.FixedTensorDef(like_shape, dtype=dtype),\n ):\n return flow.reshape_like(x, like)\n\n return trt_reshape_like_job\n\n\nclass TestReshapeLike(unittest.TestCase):\n def _test_body(self, x, like, dtype=np.float32):\n f1 = make_job(x.shape, like.shape, dtype=flow.float32)\n f2 = make_xla_job(x.shape, like.shape, dtype=flow.float32)\n a = f1(x, like).get()\n b = f2(x, like).get()\n print(\"without xla: \", a)\n print(\"with xla: \", b)\n self.assertTrue(a.shape == b.shape)\n self.assertTrue(np.allclose(a.numpy(), b.numpy(), rtol=0.001, atol=1e-05))\n flow.clear_default_session()\n f3 = make_trt_job(x.shape, like.shape, dtype=flow.float32)\n c = f3(x, like).get()\n print(\"with tensorrt: \", c)\n self.assertTrue(a.shape == c.shape)\n self.assertTrue(np.allclose(a.numpy(), c.numpy(), rtol=0.001, atol=1e-05))\n flow.clear_default_session()\n\n def _test_ones_body(self, x_shape, like_shape, dtype=np.float32):\n x = np.ones(x_shape, dtype=dtype)\n like = np.ones(like_shape, dtype=dtype)\n self._test_body(x, like, dtype=dtype)\n\n def _test_random_body(self, x_shape, like_shape, dtype=np.float32):\n x = np.random.random(x_shape).astype(dtype)\n like = np.random.random(like_shape).astype(dtype)\n self._test_body(x, like, dtype=dtype)\n\n def test_ones_input(self):\n self._test_ones_body((1, 10), (10,))\n self._test_ones_body((2, 10, 2), (4, 10))\n self._test_ones_body((2, 5, 2, 2), (2, 5, 4))\n\n def test_random_input(self):\n self._test_random_body((1, 10), (10,))\n self._test_random_body((2, 10, 2), (4, 10))\n self._test_random_body((2, 5, 2, 2), (2, 5, 4))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n",
"\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport os\nimport unittest\n\nimport numpy as np\n\nimport oneflow.compatible.single_client.unittest\nfrom oneflow.compatible import single_client as flow\n\nconfig = flow.function_config()\n\n\ndef make_job(shape, gamma_shape, params_axis, dtype=flow.float32):\n config.use_xla_jit(False)\n config.use_tensorrt(False)\n\n @flow.global_function(config)\n def layer_norm_param_grad_job(\n dy=flow.FixedTensorDef(shape, dtype=dtype),\n norm=flow.FixedTensorDef(shape, dtype=dtype),\n gamma=flow.FixedTensorDef(gamma_shape, dtype=dtype),\n ):\n return flow.layers.layer_norm_param_grad(\n dy, norm, gamma, begin_params_axis=params_axis\n )\n\n return layer_norm_param_grad_job\n\n\ndef make_xla_job(shape, gamma_shape, params_axis, dtype=flow.float32):\n config.use_xla_jit(True)\n config.use_tensorrt(False)\n\n @flow.global_function(config)\n def xla_layer_norm_param_grad_job(\n dy=flow.FixedTensorDef(shape, dtype=dtype),\n norm=flow.FixedTensorDef(shape, dtype=dtype),\n gamma=flow.FixedTensorDef(gamma_shape, dtype=dtype),\n ):\n return flow.layers.layer_norm_param_grad(\n dy, norm, gamma, begin_params_axis=params_axis\n )\n\n return xla_layer_norm_param_grad_job\n\n\[email protected](os.getenv(\"ONEFLOW_TEST_CPU_ONLY\"), \"only test cpu cases\")\nclass TestLayerNormParamGrad(unittest.TestCase):\n def _test_body(self, dy, norm, gamma, params_axis, dtype=np.float32):\n f1 = make_job(dy.shape, gamma.shape, params_axis, dtype=flow.float32)\n f2 = make_xla_job(dy.shape, gamma.shape, params_axis, dtype=flow.float32)\n (d_norm1, d_beta1, d_gamma1) = f1(dy, norm, gamma).get()\n (d_norm2, d_beta2, d_gamma2) = f2(dy, norm, gamma).get()\n print(\"normalize diff:\")\n print(\" without xla: \", d_norm1)\n print(\" with xla: \", d_norm2)\n print(\"beta diff:\")\n print(\" without xla: \", d_beta1)\n print(\" with xla: \", d_beta2)\n print(\"gamma diff:\")\n print(\" without xla: \", d_gamma1)\n print(\" with xla: \", d_gamma2)\n self.assertTrue(d_norm1.shape, d_norm2.shape)\n self.assertTrue(d_beta1.shape, d_beta2.shape)\n self.assertTrue(d_gamma1.shape, d_gamma2.shape)\n self.assertTrue(\n np.allclose(d_norm1.numpy(), d_norm2.numpy(), rtol=0.001, atol=1e-05)\n )\n self.assertTrue(\n np.allclose(d_beta1.numpy(), d_beta2.numpy(), rtol=0.001, atol=1e-05)\n )\n self.assertTrue(\n np.allclose(d_gamma1.numpy(), d_gamma2.numpy(), rtol=0.001, atol=1e-05)\n )\n flow.clear_default_session()\n\n def _test_ones_body(self, shape, params_axis=-1, dtype=np.float32):\n dy = np.ones(shape, dtype=dtype)\n norm = np.ones(shape, dtype=dtype)\n if params_axis < 0:\n params_axis += len(shape)\n gamma_shape = shape[params_axis:]\n if len(gamma_shape) == 0:\n gamma_shape = [1]\n gamma = np.ones(gamma_shape, dtype=dtype)\n self._test_body(dy, norm, gamma, params_axis, dtype=dtype)\n\n def _test_random_body(self, shape, params_axis=-1, dtype=np.float32):\n dy = np.random.random(shape).astype(dtype)\n norm = np.random.random(shape).astype(dtype)\n if params_axis < 0:\n params_axis += len(shape)\n gamma_shape = shape[params_axis:]\n if len(gamma_shape) == 0:\n gamma_shape = [1]\n gamma = np.random.random(gamma_shape).astype(dtype)\n self._test_body(dy, norm, gamma, params_axis, dtype=dtype)\n\n def test_ones_input(self):\n self._test_ones_body((1, 10))\n self._test_ones_body((2, 10, 2))\n self._test_ones_body((2, 5, 2, 2))\n\n def test_random_input(self):\n self._test_random_body((1, 10))\n self._test_random_body((2, 10, 2))\n self._test_random_body((2, 5, 2, 2))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n",
"\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport unittest\nfrom collections import OrderedDict\n\nimport numpy as np\nfrom automated_test_util import *\nfrom test_util import GenArgList\n\nimport oneflow as flow\nimport oneflow.unittest\n\n\ndef _test_where(test_case, device):\n x = flow.Tensor(\n np.array([[-0.462, 0.3139], [0.3898, -0.7197], [0.0478, -0.1657]]),\n dtype=flow.float32,\n device=flow.device(device),\n )\n y = flow.Tensor(\n np.ones(shape=(3, 2)), dtype=flow.float32, device=flow.device(device)\n )\n condition = flow.Tensor(\n np.array([[0, 1], [1, 0], [1, 0]]), dtype=flow.int32, device=flow.device(device)\n )\n of_out = flow.where(condition, x, y)\n np_out = np.array([[1.0, 0.3139], [0.3898, 1.0], [0.0478, 1.0]])\n test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-05, 1e-05))\n\n\ndef _test_where_broadcast(test_case, device):\n x = flow.Tensor(\n np.array([[[-0.462, 0.3139], [0.3898, -0.7197], [0.0478, -0.1657]]]),\n dtype=flow.float32,\n device=flow.device(device),\n )\n y = flow.Tensor(\n np.ones(shape=(3, 3, 2)), dtype=flow.float32, device=flow.device(device)\n )\n condition = flow.Tensor(\n np.array([[[0, 1], [1, 0], [1, 0]]]),\n dtype=flow.int32,\n device=flow.device(device),\n )\n of_out = flow.where(condition, x, y)\n np_out = np.array(\n [\n [[1.0, 0.3139], [0.3898, 1.0], [0.0478, 1.0]],\n [[1.0, 0.3139], [0.3898, 1.0], [0.0478, 1.0]],\n [[1.0, 0.3139], [0.3898, 1.0], [0.0478, 1.0]],\n ]\n )\n test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-05, 1e-05))\n\n\ndef _test_where_scalar(test_case, device):\n x = 0.5\n y = 2.0\n condition = flow.Tensor(np.array([1]), dtype=flow.int32)\n of_out = flow.where(condition, x, y)\n np_out = np.array([0.5])\n test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-05, 1e-05))\n\n\ndef _test_where_dim4(test_case, device):\n x = flow.Tensor(\n np.array([[[[-0.462, 0.3139], [0.3898, -0.7197], [0.0478, -0.1657]]]]),\n dtype=flow.float32,\n device=flow.device(device),\n )\n y = flow.Tensor(\n np.ones(shape=(1, 1, 3, 2)), dtype=flow.float32, device=flow.device(device)\n )\n condition = flow.Tensor(\n np.array([[[[0, 1], [1, 0], [1, 0]]]]),\n dtype=flow.int32,\n device=flow.device(device),\n )\n of_out = flow.where(condition, x, y)\n np_out = np.array([[[[1.0, 0.3139], [0.3898, 1.0], [0.0478, 1.0]]]])\n test_case.assertTrue(np.allclose(of_out.numpy(), np_out, 1e-05, 1e-05))\n\n\ndef _test_where_backward(test_case, device):\n x = flow.Tensor(\n np.array([[-0.462, 0.3139], [0.3898, -0.7197], [0.0478, -0.1657]]),\n dtype=flow.float32,\n device=flow.device(device),\n requires_grad=True,\n )\n y = flow.Tensor(\n np.ones(shape=(3, 2)),\n dtype=flow.float32,\n device=flow.device(device),\n requires_grad=True,\n )\n condition = flow.Tensor(\n np.array([[0, 1], [1, 0], [1, 0]]), dtype=flow.int32, device=flow.device(device)\n )\n of_out = flow.where(condition, x, y)\n of_out = of_out.sum()\n of_out.backward()\n test_case.assertTrue(\n np.allclose(x.grad.numpy(), condition.numpy() == 1, 1e-05, 1e-05)\n )\n test_case.assertTrue(\n np.allclose(y.grad.numpy(), condition.numpy() == 0, 1e-05, 1e-05)\n )\n\n\ndef _test_where_broadcast_backward(test_case, device):\n x = flow.Tensor(\n np.array([[[-0.462, 0.3139], [0.3898, -0.7197], [0.0478, -0.1657]]]),\n dtype=flow.float32,\n device=flow.device(device),\n requires_grad=True,\n )\n y = flow.Tensor(\n np.ones(shape=(3, 3, 2)),\n dtype=flow.float32,\n device=flow.device(device),\n requires_grad=True,\n )\n condition = flow.Tensor(\n np.array([[[0, 1], [1, 0], [1, 0]]]),\n dtype=flow.int32,\n device=flow.device(device),\n )\n of_out = flow.where(condition, x, y)\n of_out = of_out.sum()\n of_out.backward()\n x_grad = [[[0.0, 3.0], [3.0, 0.0], [3.0, 0.0]]]\n test_case.assertTrue(np.allclose(x.grad.numpy(), x_grad, 1e-05, 1e-05))\n y_grad = [\n [[1.0, 0.0], [0.0, 1.0], [0.0, 1.0]],\n [[1.0, 0.0], [0.0, 1.0], [0.0, 1.0]],\n [[1.0, 0.0], [0.0, 1.0], [0.0, 1.0]],\n ]\n test_case.assertTrue(np.allclose(y.grad.numpy(), y_grad, 1e-05, 1e-05))\n\n\ndef _test_where_broadcast_x_backward(test_case, device):\n x = flow.Tensor(\n np.array([[[-0.462, 0.3139], [0.3898, -0.7197], [0.0478, -0.1657]]]),\n dtype=flow.float32,\n device=flow.device(device),\n requires_grad=True,\n )\n y = flow.Tensor(\n np.ones(shape=(3, 3, 2)), dtype=flow.float32, device=flow.device(device)\n )\n condition = flow.Tensor(\n np.array([[[0, 1], [1, 0], [1, 0]]]),\n dtype=flow.int32,\n device=flow.device(device),\n )\n of_out = flow.where(condition, x, y)\n of_out = of_out.sum()\n of_out.backward()\n x_grad = [[[0.0, 3.0], [3.0, 0.0], [3.0, 0.0]]]\n test_case.assertTrue(np.allclose(x.grad.numpy(), x_grad, 1e-05, 1e-05))\n\n\ndef _test_where_x_y_none(test_case, device):\n condition = flow.Tensor(\n np.array([[[-0.462, 0.3139], [0.3898, -0.7197], [0.0478, -0.1657]]]),\n dtype=flow.float32,\n device=flow.device(device),\n requires_grad=True,\n )\n of_out = flow.where(condition)\n of_nonzero = flow.nonzero(condition, as_tuple=True)\n for i in range(len(of_out)):\n test_case.assertTrue(\n np.allclose(of_out[i].numpy(), of_nonzero[i].numpy(), 1e-05, 1e-05)\n )\n\n\[email protected]_unless_1n1d()\nclass TestWhere(flow.unittest.TestCase):\n def test_where(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"test_fun\"] = [\n _test_where,\n _test_where_broadcast,\n _test_where_scalar,\n _test_where_dim4,\n _test_where_backward,\n _test_where_broadcast_backward,\n _test_where_broadcast_x_backward,\n _test_where_x_y_none,\n ]\n arg_dict[\"device\"] = [\"cpu\", \"cuda\"]\n for arg in GenArgList(arg_dict):\n arg[0](test_case, *arg[1:])\n\n @autotest()\n def test_flow_where_tensor_with_random_data(test_case):\n k1 = random(2, 6)\n k2 = random(2, 6)\n device = random_device()\n cond = random_pytorch_tensor(ndim=2, dim0=k1, dim1=k2).to(device)\n x = random_pytorch_tensor(ndim=2, dim0=k1, dim1=k2).to(device)\n y = random_pytorch_tensor(ndim=2, dim0=k1, dim1=k2).to(device)\n return torch.where(cond > 0, x, y)\n\n @autotest()\n def test_flow_where_tensor_broadcast_with_random_data(test_case):\n k1 = random(2, 6)\n k2 = random(2, 6)\n device = random_device()\n cond = random_pytorch_tensor(ndim=2, dim0=k1, dim1=k2).to(device)\n x = random_pytorch_tensor(ndim=2, dim0=1, dim1=k2).to(device)\n y = random_pytorch_tensor(ndim=2, dim0=k1, dim1=1).to(device)\n return torch.where(cond > 0, x, y)\n\n @autotest()\n def test_flow_where_scalar_x_with_random_data(test_case):\n k1 = random(2, 6)\n k2 = random(2, 6)\n device = random_device()\n cond = random_pytorch_tensor(ndim=2, dim0=k1, dim1=k2).to(device)\n x = random().to(float)\n y = random_pytorch_tensor(ndim=2, dim0=k1, dim1=k2, dtype=float).to(\n device=device, dtype=torch.float64\n )\n return torch.where(cond > 0, x, y)\n\n @autotest()\n def test_flow_where_scalar_x_broadcast_with_random_data(test_case):\n k1 = random(2, 6)\n k2 = random(2, 6)\n device = random_device()\n cond = random_pytorch_tensor(ndim=2, dim0=1, dim1=k2).to(device)\n x = random().to(float)\n y = random_pytorch_tensor(ndim=2, dim0=k1, dim1=1, dtype=float).to(\n device=device, dtype=torch.float64\n )\n return torch.where(cond > 0, x, y)\n\n @autotest(auto_backward=False)\n def test_flow_where_scalar_x_int_with_random_data(test_case):\n k1 = random(2, 6)\n k2 = random(2, 6)\n device = random_device()\n cond = random_pytorch_tensor(ndim=2, dim0=k1, dim1=k2).to(device)\n x = random().to(int)\n y = random_pytorch_tensor(ndim=2, dim0=k1, dim1=k2, dtype=int).to(device)\n return torch.where(cond > 0, x, y)\n\n @autotest()\n def test_flow_where_scalar_y_with_random_data(test_case):\n k1 = random(2, 6)\n k2 = random(2, 6)\n device = random_device()\n cond = random_pytorch_tensor(ndim=2, dim0=k1, dim1=k2).to(device)\n x = random_pytorch_tensor(ndim=2, dim0=k1, dim1=k2, dtype=float).to(\n device=device, dtype=torch.float64\n )\n y = random().to(float)\n return torch.where(cond > 0, x, y)\n\n @autotest()\n def test_flow_where_scalar_y_broadcast_with_random_data(test_case):\n k1 = random(2, 6)\n k2 = random(2, 6)\n device = random_device()\n cond = random_pytorch_tensor(ndim=2, dim0=1, dim1=k2).to(device)\n x = random_pytorch_tensor(ndim=2, dim0=k1, dim1=1, dtype=float).to(\n device=device, dtype=torch.float64\n )\n y = random().to(float)\n return torch.where(cond > 0, x, y)\n\n @autotest(auto_backward=False)\n def test_flow_where_scalar_y_int_with_random_data(test_case):\n k1 = random(2, 6)\n k2 = random(2, 6)\n device = random_device()\n cond = random_pytorch_tensor(ndim=2, dim0=k1, dim1=k2).to(device)\n x = random_pytorch_tensor(ndim=2, dim0=k1, dim1=k2, dtype=int).to(device)\n y = random().to(int)\n return torch.where(cond > 0, x, y)\n\n @autotest(auto_backward=False)\n def test_flow_where_scalar_xy_with_random_data(test_case):\n k1 = random(2, 6)\n k2 = random(2, 6)\n device = random_device()\n cond = random_pytorch_tensor(ndim=2, dim0=k1, dim1=k2).to(device)\n x = random().to(float)\n y = random().to(float)\n return torch.where(cond > 0, x, y)\n\n @autotest(auto_backward=False)\n def test_flow_where_scalar_xy_int_with_random_data(test_case):\n k1 = random(2, 6)\n k2 = random(2, 6)\n device = random_device()\n cond = random_pytorch_tensor(ndim=2, dim0=k1, dim1=k2).to(device)\n x = random().to(int)\n y = random().to(int)\n return torch.where(cond > 0, x, y)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n",
"\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport unittest\nfrom collections import OrderedDict\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.ops import gen_math_ops\nfrom test_util import GenArgList\n\nimport oneflow.compatible.single_client.unittest\nfrom oneflow.compatible import single_client as flow\nfrom oneflow.compatible.single_client import typing as oft\n\ngpus = tf.config.experimental.list_physical_devices(\"GPU\")\nfor gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\n\n\ndef _random_inputs(params_shape, indices_shape):\n params = np.random.rand(*params_shape).astype(np.float32)\n indices = np.random.randint(\n low=0,\n high=params_shape[len(indices_shape) - 1],\n size=indices_shape,\n dtype=np.int32,\n )\n return (params, indices)\n\n\ndef _make_gather_fn(\n params, indices, axis, batch_dims, device_type, mirrored, compare_fn\n):\n flow.clear_default_session()\n flow.config.enable_debug_mode(True)\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float)\n if mirrored:\n func_config.default_logical_view(flow.scope.mirrored_view())\n else:\n func_config.default_logical_view(flow.scope.consistent_view())\n\n def do_gather(x_blob, i_blob):\n with flow.scope.placement(device_type, \"0:0\"):\n x = flow.get_variable(\n \"params\",\n shape=params.shape,\n dtype=flow.float32,\n initializer=flow.constant_initializer(0),\n )\n x = x + x_blob\n y = flow.gather(x, i_blob, axis=axis, batch_dims=batch_dims)\n lr_scheduler = flow.optimizer.PiecewiseConstantScheduler([], [0.001])\n flow.optimizer.SGD(lr_scheduler, momentum=0).minimize(y)\n flow.watch_diff(x, compare_fn)\n return y\n\n if mirrored:\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def gather_fn(\n params_def: oft.ListNumpy.Placeholder(params.shape, dtype=flow.float32),\n indices_def: oft.ListNumpy.Placeholder(indices.shape, dtype=flow.int32),\n ):\n return do_gather(params_def, indices_def)\n\n else:\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def gather_fn(\n params_def: oft.Numpy.Placeholder(params.shape, dtype=flow.float32),\n indices_def: oft.Numpy.Placeholder(indices.shape, dtype=flow.int32),\n ):\n return do_gather(params_def, indices_def)\n\n return gather_fn\n\n\ndef _compare_gather_with_tf(\n test_case,\n device_type,\n params_shape,\n indices_shape,\n axis,\n batch_dims,\n mirrored=False,\n):\n (params, indices) = _random_inputs(params_shape, indices_shape)\n i = tf.constant(indices.astype(np.int32))\n with tf.GradientTape() as t:\n x = tf.Variable(params.astype(np.float32))\n y = tf.gather(x, i, axis=axis, batch_dims=axis)\n dy = t.gradient(y, x)\n if mirrored:\n\n def compare_dy(params_grad):\n test_case.assertTrue(\n np.allclose(dy, params_grad.numpy_list()[0], atol=1e-05, rtol=1e-05)\n )\n\n else:\n\n def compare_dy(params_grad):\n test_case.assertTrue(\n np.allclose(dy, params_grad.numpy(), atol=1e-05, rtol=1e-05)\n )\n\n gather_fn = _make_gather_fn(\n params, indices, axis, batch_dims, device_type, mirrored, compare_dy\n )\n if mirrored:\n of_y = gather_fn([params], [indices]).get().numpy_list()[0]\n else:\n of_y = gather_fn(params, indices).get().numpy()\n test_case.assertTrue(np.array_equal(y.numpy(), of_y))\n\n\[email protected]_unless_1n1d()\nclass TestBatchGather(flow.unittest.TestCase):\n def test_batch_gather(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"gpu\", \"cpu\"]\n arg_dict[\"params_shape\"] = [(2, 8, 4)]\n arg_dict[\"indices_shape\"] = [(2, 1)]\n arg_dict[\"axis\"] = [1]\n arg_dict[\"batch_dims\"] = [1]\n for arg in GenArgList(arg_dict):\n _compare_gather_with_tf(test_case, *arg)\n\n def test_batch_gather_case_1(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"gpu\"]\n arg_dict[\"params_shape\"] = [(20, 10, 200)]\n arg_dict[\"indices_shape\"] = [(20, 10)]\n arg_dict[\"axis\"] = [1]\n arg_dict[\"batch_dims\"] = [1]\n for arg in GenArgList(arg_dict):\n _compare_gather_with_tf(test_case, *arg)\n\n def test_batch_gather_case_2(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"cpu\", \"gpu\"]\n arg_dict[\"params_shape\"] = [(20, 80, 30, 5)]\n arg_dict[\"indices_shape\"] = [(20, 40)]\n arg_dict[\"axis\"] = [1]\n arg_dict[\"batch_dims\"] = [1]\n arg_dict[\"mirrored\"] = [True]\n for arg in GenArgList(arg_dict):\n _compare_gather_with_tf(test_case, *arg)\n\n def test_batch_gather_case_3(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"cpu\", \"gpu\"]\n arg_dict[\"params_shape\"] = [(20, 80, 30, 5)]\n arg_dict[\"indices_shape\"] = [(20, 80, 20)]\n arg_dict[\"axis\"] = [2]\n arg_dict[\"batch_dims\"] = [2]\n arg_dict[\"mirrored\"] = [True]\n for arg in GenArgList(arg_dict):\n _compare_gather_with_tf(test_case, *arg)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n",
"\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport os\nimport unittest\nfrom collections import OrderedDict\n\nimport numpy as np\nimport tensorflow as tf\nimport test_global_storage\nfrom test_util import GenArgList\n\nimport oneflow.compatible.single_client.unittest\nfrom oneflow.compatible import single_client as flow\n\ngpus = tf.config.experimental.list_physical_devices(\"GPU\")\nfor gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\n\n\ndef compare_with_tensorflow_rmsprop(\n device_type, x_shape, centered, decay_rate, learning_rate, train_iters\n):\n assert device_type in [\"gpu\", \"cpu\"]\n flow.clear_default_session()\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float32)\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def testRmsprop(\n random_mask: flow.typing.Numpy.Placeholder(x_shape, dtype=flow.float32)\n ) -> flow.typing.Numpy:\n with flow.scope.placement(device_type, \"0:0-0\"):\n x = flow.get_variable(\n name=\"x\",\n shape=x_shape,\n dtype=flow.float32,\n initializer=flow.random_uniform_initializer(minval=0, maxval=100),\n trainable=True,\n )\n loss = flow.math.reduce_mean(x * random_mask)\n flow.optimizer.RMSProp(\n flow.optimizer.PiecewiseConstantScheduler([], [learning_rate]),\n decay_rate=decay_rate,\n epsilon=0,\n centered=centered,\n ).minimize(loss)\n return x\n\n random_masks_seq = []\n for i in range(train_iters + 1):\n random_masks_seq.append(np.random.uniform(size=x_shape).astype(np.float32))\n init_value = None\n for i in range(train_iters + 1):\n x = testRmsprop(random_masks_seq[i])\n if i == 0:\n init_value = np.copy(x)\n var = tf.Variable(init_value)\n opt = tf.keras.optimizers.RMSprop(\n learning_rate=learning_rate,\n rho=decay_rate,\n momentum=0.0,\n epsilon=0,\n centered=centered,\n )\n for i in range(train_iters):\n with tf.GradientTape() as tape:\n random_mask = tf.Variable(random_masks_seq[i])\n loss = tf.reduce_mean(var * random_mask)\n gradients = tape.gradient(loss, var)\n opt.apply_gradients(zip([gradients], [var]))\n assert np.allclose(x.flatten(), var.numpy().flatten(), rtol=0.1, atol=0.1), (\n x.flatten() - var.numpy().flatten()\n )\n\n\ndef compare_with_tensorflow_adam(\n device_type, x_shape, beta1, beta2, epsilon, learning_rate, train_iters\n):\n assert device_type in [\"gpu\", \"cpu\"]\n flow.clear_default_session()\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float32)\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def testAdam(\n random_mask: flow.typing.Numpy.Placeholder(x_shape, dtype=flow.float32)\n ) -> flow.typing.Numpy:\n with flow.scope.placement(device_type, \"0:0-0\"):\n x = flow.get_variable(\n name=\"x\",\n shape=x_shape,\n dtype=flow.float32,\n initializer=flow.random_uniform_initializer(minval=0, maxval=100),\n trainable=True,\n )\n loss = flow.math.reduce_mean(x * random_mask)\n flow.optimizer.Adam(\n flow.optimizer.PiecewiseConstantScheduler([], [learning_rate]),\n beta1=beta1,\n beta2=beta2,\n epsilon=epsilon,\n do_bias_correction=True,\n ).minimize(loss)\n return x\n\n random_masks_seq = []\n for i in range(train_iters + 1):\n random_masks_seq.append(np.random.uniform(size=x_shape).astype(np.float32))\n init_value = None\n for i in range(train_iters + 1):\n x = testAdam(random_masks_seq[i])\n if i == 0:\n init_value = np.copy(x)\n var = tf.Variable(init_value)\n opt = tf.keras.optimizers.Adam(\n learning_rate=learning_rate,\n beta_1=beta1,\n beta_2=beta2,\n epsilon=epsilon,\n amsgrad=False,\n )\n for i in range(train_iters):\n with tf.GradientTape() as tape:\n random_mask = tf.Variable(random_masks_seq[i])\n loss = tf.reduce_mean(var * random_mask)\n gradients = tape.gradient(loss, var)\n opt.apply_gradients(zip([gradients], [var]))\n assert np.allclose(x.flatten(), var.numpy().flatten(), rtol=0.0001, atol=0.0001)\n\n\ndef compare_with_numpy_adamw(\n device_type,\n x_shape,\n beta1,\n beta2,\n epsilon,\n weight_decay,\n learning_rate,\n train_iters,\n):\n assert device_type in [\"gpu\", \"cpu\"]\n flow.clear_default_session()\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float32)\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def testAdamW(\n random_mask: flow.typing.Numpy.Placeholder(x_shape, dtype=flow.float32)\n ) -> flow.typing.Numpy:\n with flow.scope.placement(device_type, \"0:0-0\"):\n x = flow.get_variable(\n name=\"x\",\n shape=x_shape,\n dtype=flow.float32,\n initializer=flow.random_uniform_initializer(minval=0, maxval=100),\n trainable=True,\n )\n loss = flow.math.reduce_mean(x * random_mask)\n flow.optimizer.AdamW(\n flow.optimizer.PiecewiseConstantScheduler([], [learning_rate]),\n beta1=beta1,\n beta2=beta2,\n epsilon=epsilon,\n weight_decay=weight_decay,\n do_bias_correction=True,\n ).minimize(loss)\n return x\n\n random_masks_seq = []\n for i in range(train_iters + 1):\n random_masks_seq.append(np.random.uniform(size=x_shape).astype(np.float32))\n init_value = None\n for i in range(train_iters + 1):\n x = testAdamW(random_masks_seq[i])\n if i == 0:\n init_value = np.copy(x)\n\n def adamw_update_numpy(\n param,\n gradient,\n iter,\n m,\n v,\n lr=0.001,\n beta1=0.9,\n beta2=0.999,\n epsilon=1e-07,\n weight_decay=0.9,\n ):\n lr_t = lr * np.sqrt(1 - beta2 ** (iter + 1)) / (1 - beta1 ** (iter + 1))\n m_t = beta1 * m + (1 - beta1) * gradient\n v_t = beta2 * v + (1 - beta2) * gradient * gradient\n param_t = param - lr_t * (m_t / (np.sqrt(v_t) + epsilon) + weight_decay * param)\n return (param_t, m_t, v_t)\n\n param = init_value\n gradient = np.full(param.shape, 1.0 / np.prod(param.shape))\n m = np.zeros(param.shape)\n v = np.zeros(param.shape)\n for i in range(train_iters):\n (param, m, v) = adamw_update_numpy(\n param,\n gradient * random_masks_seq[i],\n i,\n m,\n v,\n learning_rate,\n beta1,\n beta2,\n epsilon,\n weight_decay,\n )\n assert np.allclose(x.flatten(), param.flatten(), rtol=0.0001, atol=0.0001)\n\n\ndef compare_with_numpy_lazy_adam(\n device_type, x_shape, beta1, beta2, epsilon, learning_rate, train_iters\n):\n assert device_type in [\"gpu\", \"cpu\"]\n flow.clear_default_session()\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float32)\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def testLazyAdam() -> flow.typing.Numpy:\n with flow.scope.placement(device_type, \"0:0-0\"):\n x = flow.get_variable(\n name=\"x\",\n shape=x_shape,\n dtype=flow.float32,\n initializer=flow.random_uniform_initializer(minval=0, maxval=100),\n trainable=True,\n )\n loss = flow.math.reduce_mean(x)\n flow.optimizer.LazyAdam(\n flow.optimizer.PiecewiseConstantScheduler([], [learning_rate]),\n beta1=beta1,\n beta2=beta2,\n epsilon=epsilon,\n ).minimize(loss)\n return x\n\n init_value = None\n for i in range(train_iters + 1):\n x = testLazyAdam()\n if i == 0:\n init_value = np.copy(x)\n\n def lazy_adam_update_numpy(\n param, gradient, iter, m, v, lr=0.001, beta1=0.9, beta2=0.999, epsilon=1e-07\n ):\n lr_t = lr * np.sqrt(1 - beta2 ** (iter + 1)) / (1 - beta1 ** (iter + 1))\n m_t = np.copy(m)\n v_t = np.copy(v)\n m_t_o = beta1 * m + (1 - beta1) * gradient\n v_t_o = beta2 * v + (1 - beta2) * gradient * gradient\n m_t = m_t_o\n v_t = v_t_o\n param_t = np.copy(param)\n param_t_o = param - lr_t * m_t / (np.sqrt(v_t) + epsilon)\n param_t = param_t_o\n return (param_t, m_t, v_t)\n\n param = init_value\n gradient = np.full(param.shape, 1.0 / np.prod(param.shape))\n m = np.zeros(param.shape)\n v = np.zeros(param.shape)\n for i in range(train_iters):\n (param, m, v) = lazy_adam_update_numpy(\n param, gradient, i, m, v, learning_rate, beta1, beta2, epsilon\n )\n assert np.allclose(x.flatten(), param.flatten(), rtol=0.0001, atol=0.0001)\n\n\ndef compare_with_numpy_lars(\n device_type,\n x_shape,\n momentum_beta,\n epsilon,\n lars_coefficient,\n learning_rate,\n weight_decay,\n train_iters,\n):\n assert device_type in [\"gpu\", \"cpu\"]\n flow.clear_default_session()\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float32)\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def testLars(\n random_mask: flow.typing.Numpy.Placeholder(x_shape, dtype=flow.float32)\n ) -> flow.typing.Numpy:\n with flow.scope.placement(device_type, \"0:0-0\"):\n x = flow.get_variable(\n name=\"x\",\n shape=x_shape,\n dtype=flow.float32,\n initializer=flow.random_uniform_initializer(minval=0, maxval=100),\n trainable=True,\n )\n loss = flow.math.reduce_mean(x * random_mask)\n flow.optimizer.LARS(\n flow.optimizer.PiecewiseConstantScheduler([], [learning_rate]),\n momentum_beta=momentum_beta,\n epsilon=epsilon,\n lars_coefficient=lars_coefficient,\n weight_decay=weight_decay,\n ).minimize(loss)\n return x\n\n random_masks_seq = []\n for i in range(train_iters + 1):\n random_masks_seq.append(np.random.uniform(size=x_shape).astype(np.float32))\n init_value = None\n for i in range(train_iters + 1):\n x = testLars(random_masks_seq[i])\n if i == 0:\n init_value = np.copy(x)\n\n def lars_update_numpy(\n param,\n gradient,\n momentum,\n learning_rate,\n momentum_beta,\n weight_decay,\n epsilon,\n lars_coefficient,\n ):\n import math\n\n model_norm = math.sqrt(np.sum(param * param))\n model_diff_norm = math.sqrt(np.sum(gradient * gradient))\n if model_norm > 0 and model_diff_norm > 0:\n lars = (\n lars_coefficient\n * model_norm\n / (model_diff_norm + weight_decay * model_norm + epsilon)\n )\n else:\n lars = 1.0\n local_learning_rate = learning_rate * lars\n momentum_t = momentum_beta * momentum - local_learning_rate * gradient\n param_t = param + momentum_t - local_learning_rate * weight_decay * param\n return (param_t, momentum_t)\n\n param = init_value\n gradient = np.full(param.shape, 1.0 / np.prod(param.shape))\n momentum = np.zeros(param.shape)\n for i in range(train_iters):\n (param, momentum) = lars_update_numpy(\n param,\n gradient * random_masks_seq[i],\n momentum,\n learning_rate,\n momentum_beta,\n weight_decay,\n epsilon,\n lars_coefficient,\n )\n assert np.allclose(x.flatten(), param.flatten(), rtol=0.0001, atol=0.0001)\n\n\ndef compare_with_tensorflow_sgd(\n device_type, x_shape, momentum, learning_rate, train_iters\n):\n assert device_type in [\"gpu\", \"cpu\"]\n flow.clear_default_session()\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float32)\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def testSGD(\n random_mask: flow.typing.Numpy.Placeholder(x_shape, dtype=flow.float32)\n ) -> flow.typing.Numpy:\n with flow.scope.placement(device_type, \"0:0-0\"):\n x = flow.get_variable(\n name=\"x\",\n shape=x_shape,\n dtype=flow.float32,\n initializer=flow.random_uniform_initializer(minval=0, maxval=100),\n trainable=True,\n )\n loss = flow.math.reduce_mean(x * random_mask)\n flow.optimizer.SGD(\n flow.optimizer.PiecewiseConstantScheduler([], [learning_rate]),\n momentum=momentum,\n ).minimize(loss)\n return x\n\n random_masks_seq = []\n for i in range(train_iters + 1):\n random_masks_seq.append(np.random.uniform(size=x_shape).astype(np.float32))\n init_value = None\n for i in range(train_iters + 1):\n x = testSGD(random_masks_seq[i])\n if i == 0:\n init_value = np.copy(x)\n var = tf.Variable(init_value)\n opt = tf.keras.optimizers.SGD(\n learning_rate=learning_rate, momentum=momentum, nesterov=False\n )\n for i in range(train_iters):\n with tf.GradientTape() as tape:\n random_mask = tf.Variable(random_masks_seq[i])\n loss = tf.reduce_mean(var * random_mask)\n gradients = tape.gradient(loss, var)\n opt.apply_gradients(zip([gradients], [var]))\n assert np.allclose(x.flatten(), var.numpy().flatten(), rtol=0.0001, atol=0.0001)\n\n\ndef unique_grads(sparse_ids, sparse_grads):\n num_ids = np.prod(sparse_ids.shape)\n sparse_grads_shape = (num_ids,) + sparse_grads.shape[len(sparse_ids.shape) :]\n sparse_grads = sparse_grads.reshape(sparse_grads_shape)\n sparse_ids = sparse_ids.flatten()\n unique_dict = {}\n for i in range(num_ids):\n if sparse_ids[i] in unique_dict:\n unique_dict[sparse_ids[i]] += sparse_grads[i].copy()\n else:\n unique_dict[sparse_ids[i]] = sparse_grads[i].copy()\n return unique_dict\n\n\ndef compare_with_numpy_indexed_slices_sgd(\n device_type,\n model_shape,\n ids_shape,\n grad_shape,\n momentum_beta,\n learning_rate,\n train_iters,\n mul_scalar,\n):\n assert device_type in [\"gpu\", \"cpu\"]\n flow.clear_default_session()\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float32)\n func_config.indexed_slices_optimizer_conf(\n dict(include_op_names=dict(op_name=[\"embeddings\"]))\n )\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def testIndexedSlicesSGD(\n sparse_ids: flow.typing.Numpy.Placeholder(ids_shape, dtype=flow.int32)\n ) -> flow.typing.Numpy:\n with flow.scope.placement(device_type, \"0:0\"):\n embedding_table = flow.get_variable(\n name=\"embeddings\",\n shape=model_shape,\n initializer=flow.random_uniform_initializer(minval=0, maxval=100),\n )\n embedding = flow.gather(\n params=embedding_table * mul_scalar, indices=sparse_ids\n )\n loss = flow.math.reduce_mean(embedding)\n flow.optimizer.SGD(\n flow.optimizer.PiecewiseConstantScheduler([], [learning_rate]),\n momentum=momentum_beta,\n ).minimize(loss)\n return embedding_table\n\n sparse_ids = np.random.randint(model_shape[0], size=ids_shape).astype(np.int32)\n init_value = None\n for i in range(train_iters + 1):\n x = testIndexedSlicesSGD(sparse_ids)\n if i == 0:\n init_value = np.copy(x)\n\n def indexed_slices_update_numpy(\n param, unique_dict, iter, momentum, lr=0.001, momentum_beta=0\n ):\n param_t = np.copy(param)\n momentum_t = np.copy(momentum)\n for ids in unique_dict.keys():\n next_momentum = momentum_beta * momentum_t[ids] - lr * unique_dict[ids]\n momentum_t[ids] = next_momentum\n param_t_o = param[ids] + next_momentum\n param_t[ids] = param_t_o\n return (param_t, momentum_t)\n\n param = init_value\n gradient = np.full(grad_shape, float(mul_scalar) / np.prod(grad_shape))\n momentum = np.zeros(param.shape)\n unique_dict = unique_grads(sparse_ids, gradient)\n for i in range(train_iters):\n (param, momentum) = indexed_slices_update_numpy(\n param, unique_dict, i, momentum, learning_rate, momentum_beta\n )\n assert np.allclose(x.flatten(), param.flatten(), rtol=0.0001, atol=0.0001)\n\n\ndef compare_with_numpy_indexed_slices_sgdw(\n device_type,\n model_shape,\n ids_shape,\n grad_shape,\n momentum_beta,\n learning_rate,\n train_iters,\n mul_scalar,\n weight_decay,\n):\n assert device_type in [\"gpu\", \"cpu\"]\n flow.clear_default_session()\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float32)\n func_config.indexed_slices_optimizer_conf(\n dict(include_op_names=dict(op_name=[\"embeddings\"]))\n )\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def testIndexedSlicesSGDW(\n sparse_ids: flow.typing.Numpy.Placeholder(ids_shape, dtype=flow.int32)\n ) -> flow.typing.Numpy:\n with flow.scope.placement(device_type, \"0:0\"):\n embedding_table = flow.get_variable(\n name=\"embeddings\",\n shape=model_shape,\n initializer=flow.random_uniform_initializer(minval=0, maxval=100),\n )\n embedding = flow.gather(\n params=embedding_table * mul_scalar, indices=sparse_ids\n )\n loss = flow.math.reduce_mean(embedding)\n flow.optimizer.SGDW(\n flow.optimizer.PiecewiseConstantScheduler([], [learning_rate]),\n momentum=momentum_beta,\n weight_decay=weight_decay,\n ).minimize(loss)\n return embedding_table\n\n sparse_ids = np.random.randint(model_shape[0], size=ids_shape).astype(np.int32)\n init_value = None\n for i in range(train_iters + 1):\n x = testIndexedSlicesSGDW(sparse_ids)\n if i == 0:\n init_value = np.copy(x)\n\n def indexed_slices_update_numpy(\n param, unique_dict, iter, momentum, lr=0.001, momentum_beta=0, weight_decay=0.9\n ):\n param_t = np.copy(param)\n momentum_t = np.copy(momentum)\n for ids in unique_dict.keys():\n next_momentum = momentum_beta * momentum_t[ids] - lr * unique_dict[ids]\n momentum_t[ids] = next_momentum\n param_t_o = param[ids] + next_momentum - lr * weight_decay * param[ids]\n param_t[ids] = param_t_o\n return (param_t, momentum_t)\n\n param = init_value\n gradient = np.full(grad_shape, float(mul_scalar) / np.prod(grad_shape))\n momentum = np.zeros(param.shape)\n unique_dict = unique_grads(sparse_ids, gradient)\n for i in range(train_iters):\n (param, momentum) = indexed_slices_update_numpy(\n param, unique_dict, i, momentum, learning_rate, momentum_beta, weight_decay\n )\n assert np.allclose(x.flatten(), param.flatten(), rtol=0.0001, atol=0.0001)\n\n\ndef compare_with_numpy_indexed_slices_adam(\n device_type,\n model_shape,\n ids_shape,\n grad_shape,\n beta1,\n beta2,\n epsilon,\n learning_rate,\n train_iters,\n mul_scalar,\n):\n assert device_type in [\"gpu\", \"cpu\"]\n flow.clear_default_session()\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float32)\n func_config.indexed_slices_optimizer_conf(\n dict(include_op_names=dict(op_name=[\"embeddings\"]))\n )\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def testIndexedSlicesAdam(\n sparse_ids: flow.typing.Numpy.Placeholder(ids_shape, dtype=flow.int32)\n ) -> flow.typing.Numpy:\n with flow.scope.placement(device_type, \"0:0\"):\n embedding_table = flow.get_variable(\n name=\"embeddings\",\n shape=model_shape,\n initializer=flow.random_uniform_initializer(minval=0, maxval=100),\n )\n embedding = flow.gather(\n params=embedding_table * mul_scalar, indices=sparse_ids\n )\n loss = flow.math.reduce_mean(embedding)\n flow.optimizer.Adam(\n flow.optimizer.PiecewiseConstantScheduler([], [learning_rate]),\n beta1=beta1,\n beta2=beta2,\n epsilon=epsilon,\n do_bias_correction=True,\n ).minimize(loss)\n return embedding_table\n\n sparse_ids = np.random.randint(model_shape[0], size=ids_shape).astype(np.int32)\n init_value = None\n for i in range(train_iters + 1):\n x = testIndexedSlicesAdam(sparse_ids)\n if i == 0:\n init_value = np.copy(x)\n\n def indexed_slices_update_numpy(\n param, unique_dict, iter, m, v, lr=0.001, beta1=0.9, beta2=0.999, epsilon=1e-07\n ):\n param_t = np.copy(param)\n m_t = np.copy(m)\n v_t = np.copy(v)\n for ids in unique_dict.keys():\n lr_t = lr * np.sqrt(1 - beta2 ** (iter + 1)) / (1 - beta1 ** (iter + 1))\n m_t_o = beta1 * m[ids] + (1 - beta1) * unique_dict[ids]\n v_t_o = beta2 * v[ids] + (1 - beta2) * unique_dict[ids] * unique_dict[ids]\n m_t[ids] = m_t_o\n v_t[ids] = v_t_o\n param_t_o = param[ids] - lr_t * m_t[ids] / (np.sqrt(v_t[ids]) + epsilon)\n param_t[ids] = param_t_o\n return (param_t, m_t, v_t)\n\n param = init_value\n gradient = np.full(grad_shape, float(mul_scalar) / np.prod(grad_shape))\n m = np.zeros(param.shape)\n v = np.zeros(param.shape)\n unique_dict = unique_grads(sparse_ids, gradient)\n for i in range(train_iters):\n (param, m, v) = indexed_slices_update_numpy(\n param, unique_dict, i, m, v, learning_rate, beta1, beta2, epsilon\n )\n assert np.allclose(x.flatten(), param.flatten(), rtol=0.0001, atol=0.0001)\n\n\ndef compare_with_numpy_indexed_slices_adamw(\n device_type,\n model_shape,\n ids_shape,\n grad_shape,\n beta1,\n beta2,\n epsilon,\n learning_rate,\n train_iters,\n mul_scalar,\n weight_decay,\n):\n assert device_type in [\"gpu\", \"cpu\"]\n flow.clear_default_session()\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float32)\n func_config.indexed_slices_optimizer_conf(\n dict(include_op_names=dict(op_name=[\"embeddings\"]))\n )\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def testIndexedSlicesAdamW(\n sparse_ids: flow.typing.Numpy.Placeholder(ids_shape, dtype=flow.int32)\n ) -> flow.typing.Numpy:\n with flow.scope.placement(device_type, \"0:0\"):\n embedding_table = flow.get_variable(\n name=\"embeddings\",\n shape=model_shape,\n initializer=flow.random_uniform_initializer(minval=0, maxval=100),\n )\n embedding = flow.gather(\n params=embedding_table * mul_scalar, indices=sparse_ids\n )\n loss = flow.math.reduce_mean(embedding)\n flow.optimizer.AdamW(\n flow.optimizer.PiecewiseConstantScheduler([], [learning_rate]),\n beta1=beta1,\n beta2=beta2,\n epsilon=epsilon,\n do_bias_correction=True,\n weight_decay=weight_decay,\n ).minimize(loss)\n return embedding_table\n\n sparse_ids = np.random.randint(model_shape[0], size=ids_shape).astype(np.int32)\n init_value = None\n for i in range(train_iters + 1):\n x = testIndexedSlicesAdamW(sparse_ids)\n if i == 0:\n init_value = np.copy(x)\n\n def indexed_slices_update_numpy(\n param,\n unique_dict,\n iter,\n m,\n v,\n lr=0.001,\n beta1=0.9,\n beta2=0.999,\n epsilon=1e-07,\n weight_decay=0.9,\n ):\n param_t = np.copy(param)\n m_t = np.copy(m)\n v_t = np.copy(v)\n for ids in unique_dict.keys():\n lr_t = lr * np.sqrt(1 - beta2 ** (iter + 1)) / (1 - beta1 ** (iter + 1))\n m_t_o = beta1 * m[ids] + (1 - beta1) * unique_dict[ids]\n v_t_o = beta2 * v[ids] + (1 - beta2) * unique_dict[ids] * unique_dict[ids]\n m_t[ids] = m_t_o\n v_t[ids] = v_t_o\n param_t_o = param[ids] - lr_t * (\n m_t[ids] / (np.sqrt(v_t[ids]) + epsilon) + weight_decay * param[ids]\n )\n param_t[ids] = param_t_o\n return (param_t, m_t, v_t)\n\n param = init_value\n gradient = np.full(grad_shape, float(mul_scalar) / np.prod(grad_shape))\n m = np.zeros(param.shape)\n v = np.zeros(param.shape)\n unique_dict = unique_grads(sparse_ids, gradient)\n for i in range(train_iters):\n (param, m, v) = indexed_slices_update_numpy(\n param,\n unique_dict,\n i,\n m,\n v,\n learning_rate,\n beta1,\n beta2,\n epsilon,\n weight_decay,\n )\n assert np.allclose(x.flatten(), param.flatten(), rtol=0.0001, atol=0.0001)\n\n\ndef compare_with_flow_job_fused_sgd_model_update(\n device_type, x_shape, momentum, learning_rate, train_iters\n):\n assert device_type in [\"gpu\", \"cpu\"]\n flow.clear_default_session()\n\n def flow_net(var_name, random_mask):\n with flow.scope.placement(device_type, \"0:0-0\"):\n x = flow.get_variable(\n name=var_name,\n shape=x_shape,\n dtype=flow.float32,\n initializer=flow.ones_initializer(),\n trainable=True,\n )\n constant_val = flow.constant(3.0, dtype=flow.float32, shape=(1,))\n x = x * constant_val\n x = x * 2.0\n if device_type == \"gpu\":\n x = flow.cast(x, flow.float16)\n x = flow.math.relu(x)\n x = flow.cast(x, flow.float)\n loss = flow.math.reduce_mean(x * random_mask)\n flow.optimizer.SGD(\n flow.optimizer.PiecewiseConstantScheduler([], [learning_rate]),\n momentum=momentum,\n ).minimize(loss)\n return x\n\n def make_sgd_job():\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float32)\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def testSGD(\n random_mask: flow.typing.Numpy.Placeholder(x_shape, dtype=flow.float32)\n ) -> flow.typing.Numpy:\n return flow_net(\"x1\", random_mask)\n\n return testSGD\n\n def make_fused_sgd_job():\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float32)\n func_config.enable_fuse_model_update_ops(True)\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def testFusedSGD(\n random_mask: flow.typing.Numpy.Placeholder(x_shape, dtype=flow.float32)\n ) -> flow.typing.Numpy:\n return flow_net(\"x2\", random_mask)\n\n return testFusedSGD\n\n sgd_job = make_sgd_job()\n fused_sgd_job = make_fused_sgd_job()\n random_masks_seq = []\n for i in range(train_iters + 1):\n random_masks_seq.append(np.random.uniform(size=x_shape).astype(np.float32))\n for i in range(train_iters + 1):\n var1 = sgd_job(random_masks_seq[i])\n for i in range(train_iters + 1):\n var2 = fused_sgd_job(random_masks_seq[i])\n assert np.allclose(var1.flatten(), var2.flatten(), rtol=0.0001, atol=0.0001)\n\n\ndef compare_with_flow_job_fused_adam_model_update(\n device_type, x_shape, beta1, beta2, epsilon, learning_rate, train_iters\n):\n assert device_type in [\"gpu\", \"cpu\"]\n flow.clear_default_session()\n\n def flow_net(var_name, random_mask):\n with flow.scope.placement(device_type, \"0:0-0\"):\n x = flow.get_variable(\n name=var_name,\n shape=x_shape,\n dtype=flow.float32,\n initializer=flow.ones_initializer(),\n trainable=True,\n )\n constant_val = flow.constant(3.0, dtype=flow.float32, shape=(1,))\n x = x * constant_val\n x = x * 2.0\n if device_type == \"gpu\":\n x = flow.cast(x, flow.float16)\n x = flow.math.relu(x)\n x = flow.cast(x, flow.float)\n loss = flow.math.reduce_mean(x * random_mask)\n flow.optimizer.Adam(\n flow.optimizer.PiecewiseConstantScheduler([], [learning_rate]),\n beta1=beta1,\n beta2=beta2,\n epsilon=epsilon,\n do_bias_correction=True,\n ).minimize(loss)\n return x\n\n def make_adam_job():\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float32)\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def testAdam(\n random_mask: flow.typing.Numpy.Placeholder(x_shape, dtype=flow.float32)\n ) -> flow.typing.Numpy:\n return flow_net(\"x1\", random_mask)\n\n return testAdam\n\n def make_fused_adam_job():\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float32)\n func_config.enable_fuse_model_update_ops(True)\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def testFusedAdam(\n random_mask: flow.typing.Numpy.Placeholder(x_shape, dtype=flow.float32)\n ) -> flow.typing.Numpy:\n return flow_net(\"x2\", random_mask)\n\n return testFusedAdam\n\n adam_job = make_adam_job()\n fused_adam_job = make_fused_adam_job()\n random_masks_seq = []\n for i in range(train_iters + 1):\n random_masks_seq.append(np.random.uniform(size=x_shape).astype(np.float32))\n for i in range(train_iters + 1):\n var1 = adam_job(random_masks_seq[i])\n for i in range(train_iters + 1):\n var2 = fused_adam_job(random_masks_seq[i])\n assert np.allclose(var1.flatten(), var2.flatten(), rtol=0.0001, atol=0.0001)\n\n\[email protected]_unless_1n1d()\nclass TestOptimizers(flow.unittest.TestCase):\n def test_rmsprop(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"cpu\", \"gpu\"]\n arg_dict[\"x_shape\"] = [(10,)]\n arg_dict[\"centered\"] = [True, False]\n arg_dict[\"decay_rate\"] = [0.9]\n arg_dict[\"learning_rate\"] = [1]\n arg_dict[\"train_iters\"] = [10]\n for arg in GenArgList(arg_dict):\n compare_with_tensorflow_rmsprop(*arg)\n\n def test_adam(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"cpu\", \"gpu\"]\n arg_dict[\"x_shape\"] = [(10,)]\n arg_dict[\"beta1\"] = [0.9]\n arg_dict[\"beta2\"] = [0.99]\n arg_dict[\"epsilon\"] = [1e-09]\n arg_dict[\"learning_rate\"] = [1]\n arg_dict[\"train_iters\"] = [10]\n for arg in GenArgList(arg_dict):\n compare_with_tensorflow_adam(*arg)\n\n def test_lazy_adam(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"cpu\", \"gpu\"]\n arg_dict[\"x_shape\"] = [(10,)]\n arg_dict[\"beta1\"] = [0.9]\n arg_dict[\"beta2\"] = [0.99]\n arg_dict[\"epsilon\"] = [1e-09]\n arg_dict[\"learning_rate\"] = [1]\n arg_dict[\"train_iters\"] = [10]\n for arg in GenArgList(arg_dict):\n compare_with_numpy_lazy_adam(*arg)\n\n def test_adamw(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"cpu\", \"gpu\"]\n arg_dict[\"x_shape\"] = [(10,)]\n arg_dict[\"beta1\"] = [0.9]\n arg_dict[\"beta2\"] = [0.99]\n arg_dict[\"epsilon\"] = [1e-09]\n arg_dict[\"weight_decay\"] = [0.9]\n arg_dict[\"learning_rate\"] = [1]\n arg_dict[\"train_iters\"] = [10]\n for arg in GenArgList(arg_dict):\n compare_with_numpy_adamw(*arg)\n\n def test_lars(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"cpu\", \"gpu\"]\n arg_dict[\"x_shape\"] = [(10,)]\n arg_dict[\"momentum_beta\"] = [0.9]\n arg_dict[\"epsilon\"] = [1e-09]\n arg_dict[\"lars_coefficient\"] = [0.0001]\n arg_dict[\"learning_rate\"] = [1]\n arg_dict[\"weight_decay\"] = [0.9]\n arg_dict[\"train_iters\"] = [10]\n for arg in GenArgList(arg_dict):\n compare_with_numpy_lars(*arg)\n\n def test_sgd(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"cpu\", \"gpu\"]\n arg_dict[\"x_shape\"] = [(10,)]\n arg_dict[\"momentum\"] = [0.9, 0.0]\n arg_dict[\"learning_rate\"] = [1]\n arg_dict[\"train_iters\"] = [10]\n for arg in GenArgList(arg_dict):\n compare_with_tensorflow_sgd(*arg)\n\n def test_indexed_slices_sgd(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"gpu\", \"cpu\"]\n arg_dict[\"model_shape\"] = [(200, 2)]\n arg_dict[\"ids\"] = [(10, 4)]\n arg_dict[\"grad_shape\"] = [(10, 4, 2)]\n arg_dict[\"momentum_beta\"] = [0, 0.9]\n arg_dict[\"learning_rate\"] = [1]\n arg_dict[\"train_iters\"] = [10]\n arg_dict[\"mul_scalar\"] = [1, 2]\n for arg in GenArgList(arg_dict):\n compare_with_numpy_indexed_slices_sgd(*arg)\n\n @unittest.skipIf(\n flow.unittest.env.eager_execution_enabled(),\n \"indexed slices sgdw doesn't work in eager mode\",\n )\n def test_indexed_slices_sgdw(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"gpu\", \"cpu\"]\n arg_dict[\"model_shape\"] = [(200, 2)]\n arg_dict[\"ids\"] = [(10, 4)]\n arg_dict[\"grad_shape\"] = [(10, 4, 2)]\n arg_dict[\"momentum_beta\"] = [0, 0.9]\n arg_dict[\"learning_rate\"] = [1]\n arg_dict[\"train_iters\"] = [10]\n arg_dict[\"mul_scalar\"] = [2]\n arg_dict[\"weight_decay\"] = [0.5, 0.3]\n for arg in GenArgList(arg_dict):\n compare_with_numpy_indexed_slices_sgdw(*arg)\n\n def test_indexed_slices_adam(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"gpu\", \"cpu\"]\n arg_dict[\"model_shape\"] = [(200, 2)]\n arg_dict[\"ids\"] = [(10, 4)]\n arg_dict[\"grad_shape\"] = [(10, 4, 2)]\n arg_dict[\"beta1\"] = [0.9]\n arg_dict[\"beta2\"] = [0.99]\n arg_dict[\"epsilon\"] = [1e-09]\n arg_dict[\"learning_rate\"] = [1]\n arg_dict[\"train_iters\"] = [10]\n arg_dict[\"mul_scalar\"] = [1, 2]\n for arg in GenArgList(arg_dict):\n compare_with_numpy_indexed_slices_adam(*arg)\n\n @unittest.skipIf(\n flow.unittest.env.eager_execution_enabled(),\n \"indexed slices adamw doesn't work in eager mode\",\n )\n def test_indexed_slices_adamw(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"gpu\", \"cpu\"]\n arg_dict[\"model_shape\"] = [(200, 2)]\n arg_dict[\"ids\"] = [(10, 4)]\n arg_dict[\"grad_shape\"] = [(10, 4, 2)]\n arg_dict[\"beta1\"] = [0.9]\n arg_dict[\"beta2\"] = [0.99]\n arg_dict[\"epsilon\"] = [1e-09]\n arg_dict[\"learning_rate\"] = [1]\n arg_dict[\"train_iters\"] = [10]\n arg_dict[\"mul_scalar\"] = [2]\n arg_dict[\"weight_decay\"] = [0.5, 0.3]\n for arg in GenArgList(arg_dict):\n compare_with_numpy_indexed_slices_adamw(*arg)\n\n def test_fused_sgd(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"cpu\", \"gpu\"]\n arg_dict[\"x_shape\"] = [(10,)]\n arg_dict[\"momentum\"] = [0.9, 0.0]\n arg_dict[\"learning_rate\"] = [1]\n arg_dict[\"train_iters\"] = [10]\n for arg in GenArgList(arg_dict):\n compare_with_flow_job_fused_sgd_model_update(*arg)\n\n def test_fused_adam(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"cpu\", \"gpu\"]\n arg_dict[\"x_shape\"] = [(10,)]\n arg_dict[\"beta1\"] = [0.9]\n arg_dict[\"beta2\"] = [0.99]\n arg_dict[\"epsilon\"] = [1e-09]\n arg_dict[\"learning_rate\"] = [1]\n arg_dict[\"train_iters\"] = [10]\n for arg in GenArgList(arg_dict):\n compare_with_flow_job_fused_adam_model_update(*arg)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n",
"\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport unittest\nfrom collections import OrderedDict\n\nimport numpy as np\nimport tensorflow as tf\nfrom test_util import GenArgList\n\nimport oneflow.compatible.single_client.unittest\nfrom oneflow.compatible import single_client as flow\nfrom oneflow.compatible.single_client import typing as oft\n\ngpus = tf.config.experimental.list_physical_devices(\"GPU\")\nfor gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\n\n\ndef _np_dtype_to_of_dtype(np_dtype):\n if np_dtype == np.float32:\n return flow.float\n else:\n raise NotImplementedError\n\n\ndef _of_clip_by_value(values, min, max, device_type=\"gpu\", dynamic=False, grad_cb=None):\n data_type = _np_dtype_to_of_dtype(values.dtype)\n if callable(grad_cb):\n\n def clip(values_blob):\n with flow.scope.placement(device_type, \"0:0\"):\n x = flow.get_variable(\n \"values\",\n shape=values.shape,\n dtype=data_type,\n initializer=flow.constant_initializer(0),\n )\n x = flow.cast_to_current_logical_view(x)\n x = x + values_blob\n y = flow.clip_by_value(x, min, max)\n flow.optimizer.SGD(\n flow.optimizer.PiecewiseConstantScheduler([], [0.001]), momentum=0\n ).minimize(y)\n flow.watch_diff(x, grad_cb)\n return y\n\n else:\n\n def clip(values_blob):\n with flow.scope.placement(device_type, \"0:0\"):\n return flow.clip_by_value(values_blob, min, max, name=\"Clip\")\n\n flow.clear_default_session()\n func_config = flow.FunctionConfig()\n func_config.default_data_type(data_type)\n if grad_cb is not None:\n func_config_type = \"train\"\n else:\n func_config_type = \"predict\"\n if dynamic:\n func_config.default_logical_view(flow.scope.mirrored_view())\n\n @flow.global_function(type=func_config_type, function_config=func_config)\n def clip_fn(\n values_def: oft.ListNumpy.Placeholder(values.shape, dtype=data_type)\n ):\n return clip(values_def)\n\n return clip_fn([values]).get().numpy_list()[0]\n else:\n func_config.default_logical_view(flow.scope.consistent_view())\n\n @flow.global_function(type=func_config_type, function_config=func_config)\n def clip_fn(values_def: oft.Numpy.Placeholder(values.shape, dtype=data_type)):\n return clip(values_def)\n\n return clip_fn(values).get().numpy()\n\n\ndef _compare_with_tf(test_case, values, min, max, device_type, dynamic):\n with tf.GradientTape() as t:\n x = tf.Variable(values)\n y = tf.clip_by_value(x, min, max)\n dy = t.gradient(y, x)\n\n def compare_dy(dy_blob):\n test_case.assertTrue(\n np.array_equal(\n dy.numpy(), dy_blob.numpy_list()[0] if dynamic else dy_blob.numpy()\n )\n )\n\n of_y = _of_clip_by_value(\n values=values,\n min=min,\n max=max,\n device_type=device_type,\n dynamic=dynamic,\n grad_cb=compare_dy,\n )\n test_case.assertTrue(np.array_equal(y.numpy(), of_y))\n\n\[email protected]_unless_1n1d()\nclass TestClipByValue(flow.unittest.TestCase):\n def test_clip_by_value(test_case):\n values = np.random.randint(low=-100, high=100, size=(8, 512, 4)).astype(\n np.float32\n )\n np_out = np.clip(values, -50, 50)\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"cpu\", \"gpu\"]\n arg_dict[\"dynamic\"] = [True, False]\n for arg in GenArgList(arg_dict):\n of_out = _of_clip_by_value(values, -50, 50, *arg)\n test_case.assertTrue(np.array_equal(np_out, of_out))\n\n def test_clip_by_min(test_case):\n values = np.random.standard_normal((100, 30)).astype(np.float32)\n np_out = np.clip(values, a_min=0, a_max=None)\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"cpu\", \"gpu\"]\n arg_dict[\"dynamic\"] = [True, False]\n for arg in GenArgList(arg_dict):\n of_out = _of_clip_by_value(values, 0, None, *arg)\n test_case.assertTrue(np.array_equal(np_out, of_out))\n\n def test_clip_by_max(test_case):\n values = np.random.standard_normal((2, 64, 800, 1088)).astype(np.float32)\n np_out = np.clip(values, a_min=None, a_max=0.2)\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"cpu\", \"gpu\"]\n arg_dict[\"dynamic\"] = [True, False]\n for arg in GenArgList(arg_dict):\n of_out = _of_clip_by_value(values, None, 0.2, *arg)\n test_case.assertTrue(np.allclose(np_out, of_out))\n\n def test_clip_by_value_grad(test_case):\n values = np.random.standard_normal(1024).astype(np.float32)\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"cpu\", \"gpu\"]\n arg_dict[\"dynamic\"] = [True, False]\n for arg in GenArgList(arg_dict):\n _compare_with_tf(test_case, values, 0, 0.5, *arg)\n\n def test_clip_by_value_grad_case_1(test_case):\n values = np.random.standard_normal((128, 10, 27)).astype(np.float32)\n arg_dict = OrderedDict()\n arg_dict[\"device_type\"] = [\"cpu\", \"gpu\"]\n arg_dict[\"dynamic\"] = [True, False]\n for arg in GenArgList(arg_dict):\n _compare_with_tf(test_case, values, -0.2, 0.2, *arg)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n",
"\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport numpy as np\n\n\ndef check_slice_tup_list(slice_tup_list, shape):\n ndim = len(shape)\n if not isinstance(slice_tup_list, (list, tuple)) or len(slice_tup_list) > ndim:\n raise ValueError(\n \"slice_tup_list must be a list or tuple with length less than or equal to number of dimensions of input tensor\"\n )\n if len(slice_tup_list) < ndim:\n slice_tup_list += type(slice_tup_list)(\n [(None, None, None)] * (ndim - len(slice_tup_list))\n )\n start_list = []\n stop_list = []\n step_list = []\n for (slice_tup, dim_size) in zip(slice_tup_list, shape):\n if not isinstance(slice_tup, (tuple, list)) or len(slice_tup) != 3:\n raise ValueError(\n \"element of slice_tup_list must be a list or tuple with form (start, stop, step)\"\n )\n if not all((isinstance(idx, int) or idx is None for idx in slice_tup)):\n raise ValueError(\"element of slice tuple must int or None\")\n (start, stop, step) = slice_tup\n if step is None:\n step = 1\n if step == 0:\n raise ValueError(\"slice step can't be 0\")\n if start is None:\n start = 0 if step > 0 else np.iinfo(np.int64).max\n elif start < -dim_size or start >= dim_size:\n start, stop, step = 0, 0, 1\n if stop is None:\n stop = np.iinfo(np.int64).max if step > 0 else np.iinfo(np.int64).min\n elif stop < -dim_size - 1 or stop > dim_size:\n raise ValueError(\"slice start must be in range [-size-1, size]\")\n start_list.append(start)\n stop_list.append(stop)\n step_list.append(step)\n return (start_list, stop_list, step_list)\n\n\ndef GetSliceAttrs(slice_tup_list, input_shape):\n ndim = len(input_shape)\n if not (isinstance(slice_tup_list, (list, tuple)) and len(slice_tup_list) <= ndim):\n raise ValueError(\n \"slice_tup_list must be a list or tuple with length less than or equal to number of dimensions of input tensor\"\n )\n if len(slice_tup_list) < ndim:\n slice_tup_list += type(slice_tup_list)(\n [(None, None, None)] * (ndim - len(slice_tup_list))\n )\n start_list = []\n stop_list = []\n step_list = []\n for (slice_tup, dim_size) in zip(slice_tup_list, input_shape):\n if not (isinstance(slice_tup, (tuple, list)) and len(slice_tup) == 3):\n raise ValueError(\n \"element of slice_tup_list must be a list or tuple with form (start, stop, step)\"\n )\n if not all((isinstance(idx, int) or idx is None for idx in slice_tup)):\n raise ValueError(\"element of slice tuple must int or None\")\n (start, stop, step) = slice_tup\n if step is None:\n step = 1\n if step <= 0:\n raise ValueError(\"slice_assign/logical_slice step must be greater than 0\")\n if start is None:\n start = 0\n elif start < -dim_size or start >= dim_size:\n raise ValueError(\n \"slice_assign/logical_slice start must be in range [-size, size)\"\n )\n elif start < 0:\n start += dim_size\n if stop is None:\n stop = dim_size\n elif stop < -dim_size or stop > dim_size:\n raise ValueError(\n \"slice_assign/logical_slice start must be in range [-size, size]\"\n )\n elif stop < 0:\n stop += dim_size\n start_list.append(start)\n stop_list.append(stop)\n step_list.append(step)\n return (start_list, stop_list, step_list)\n",
"\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport unittest\n\nimport numpy as np\n\nimport oneflow.compatible.single_client.unittest\nfrom oneflow.compatible import single_client as flow\n\nconfig = flow.function_config()\n\n\ndef make_job(a_shape, b_shape, trans_a=False, trans_b=False, dtype=flow.float32):\n config.use_xla_jit(False)\n config.use_tensorrt(False)\n\n @flow.global_function(config)\n def matmul_job(\n a=flow.FixedTensorDef(a_shape, dtype=dtype),\n b=flow.FixedTensorDef(b_shape, dtype=dtype),\n ):\n return flow.matmul(a, b, transpose_a=trans_a, transpose_b=trans_b)\n\n return matmul_job\n\n\ndef make_xla_job(a_shape, b_shape, trans_a=False, trans_b=False, dtype=flow.float32):\n config.use_xla_jit(True)\n config.use_tensorrt(False)\n\n @flow.global_function(config)\n def xla_matmul_job(\n a=flow.FixedTensorDef(a_shape, dtype=dtype),\n b=flow.FixedTensorDef(b_shape, dtype=dtype),\n ):\n return flow.matmul(a, b, transpose_a=trans_a, transpose_b=trans_b)\n\n return xla_matmul_job\n\n\ndef make_trt_job(a_shape, b_shape, trans_a=False, trans_b=False, dtype=flow.float32):\n config.use_xla_jit(False)\n config.use_tensorrt(True)\n\n @flow.global_function(config)\n def trt_matmul_job(\n a=flow.FixedTensorDef(a_shape, dtype=dtype),\n b=flow.FixedTensorDef(b_shape, dtype=dtype),\n ):\n return flow.matmul(a, b, transpose_a=trans_a, transpose_b=trans_b)\n\n return trt_matmul_job\n\n\nclass TestMatmul(unittest.TestCase):\n def make_shape(self, m, n, transpose):\n if transpose:\n return (n, m)\n else:\n return (m, n)\n\n def _test_body(self, a, b, trans_a, trans_b, dtype=np.float32):\n f1 = make_job(a.shape, b.shape, trans_a, trans_b)\n f2 = make_xla_job(a.shape, b.shape, trans_a, trans_b)\n f3 = make_trt_job(a.shape, b.shape, trans_a, trans_b)\n x = f1(a, b).get()\n y = f2(a, b).get()\n z = f3(a, b).get()\n print(\"without xla: \", x)\n print(\"with xla: \", y)\n print(\"with tensorrt: \", y)\n self.assertTrue(np.allclose(x.numpy(), y.numpy(), rtol=0.001, atol=1e-05))\n self.assertTrue(np.allclose(x.numpy(), z.numpy(), rtol=0.001, atol=1e-05))\n flow.clear_default_session()\n\n def _test_ones_body(self, m, k, n, trans_a, trans_b, dtype=np.float32):\n shape_a = self.make_shape(m, k, trans_a)\n shape_b = self.make_shape(k, n, trans_b)\n a = np.ones(shape_a, dtype=dtype)\n b = np.ones(shape_b, dtype=dtype)\n self._test_body(a, b, trans_a, trans_b, dtype=dtype)\n\n def _test_random_body(self, m, k, n, trans_a, trans_b, dtype=np.float32):\n shape_a = self.make_shape(m, k, trans_a)\n shape_b = self.make_shape(k, n, trans_b)\n a = np.random.random(shape_a).astype(dtype)\n b = np.random.random(shape_b).astype(dtype)\n self._test_body(a, b, trans_a, trans_b, dtype=dtype)\n\n def test_ones1x1x1_input(self):\n print(\"run test_ones1x1x1_input: \")\n self._test_ones_body(1, 1, 1, False, False)\n self._test_ones_body(1, 1, 1, False, True)\n self._test_ones_body(1, 1, 1, True, False)\n self._test_ones_body(1, 1, 1, True, True)\n\n def test_random1x1x1_input(self):\n print(\"test_random1x1x1_input: \")\n self._test_random_body(1, 1, 1, False, False)\n self._test_random_body(1, 1, 1, False, True)\n self._test_random_body(1, 1, 1, True, False)\n self._test_random_body(1, 1, 1, True, True)\n\n def test_ones1x10x1_input(self):\n print(\"test_ones1x10x1_input: \")\n self._test_ones_body(1, 10, 1, False, False)\n self._test_ones_body(1, 10, 1, False, True)\n self._test_ones_body(1, 10, 1, True, False)\n self._test_ones_body(1, 10, 1, True, True)\n\n def test_random1x10x1_input(self):\n print(\"test_random1x10x1_input: \")\n self._test_random_body(1, 10, 1, False, False)\n self._test_random_body(1, 10, 1, False, True)\n self._test_random_body(1, 10, 1, True, False)\n self._test_random_body(1, 10, 1, True, True)\n\n def test_ones10x10x2_input(self):\n print(\"test_ones10x10x2_input: \")\n self._test_ones_body(10, 10, 2, False, False)\n self._test_ones_body(10, 10, 2, False, True)\n self._test_ones_body(10, 10, 2, True, False)\n self._test_ones_body(10, 10, 2, True, True)\n\n def test_random10x10x2_input(self):\n print(\"run test_random10x10x2_input: \")\n self._test_random_body(10, 10, 2, False, False)\n self._test_random_body(10, 10, 2, False, True)\n self._test_random_body(10, 10, 2, True, False)\n self._test_random_body(10, 10, 2, True, True)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n",
"\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport unittest\nfrom collections import OrderedDict\n\nimport numpy as np\nfrom test_util import GenArgList\n\nimport oneflow as flow\nimport oneflow.unittest\n\n\ndef _test_ones_like_float(test_case, shape, device):\n x = flow.Tensor(np.random.randn(*shape), device=flow.device(device))\n y = flow.ones_like(x)\n test_case.assertTrue(y.dtype is flow.float32)\n test_case.assertTrue(y.shape == x.shape)\n test_case.assertTrue(y.device == x.device)\n y_numpy = np.ones_like(x.numpy())\n test_case.assertTrue(np.array_equal(y.numpy(), y_numpy))\n\n\ndef _test_ones_like_int(test_case, shape, device):\n x = flow.Tensor(np.random.randn(*shape), dtype=flow.int, device=flow.device(device))\n y = flow.ones_like(x)\n test_case.assertTrue(y.dtype is flow.int)\n test_case.assertTrue(y.shape == x.shape)\n test_case.assertTrue(y.device == x.device)\n y_numpy = np.ones_like(x.numpy())\n test_case.assertTrue(np.array_equal(y.numpy(), y_numpy))\n\n\[email protected]_unless_1n1d()\nclass TestModule(flow.unittest.TestCase):\n def test_ones_like(test_case):\n arg_dict = OrderedDict()\n arg_dict[\"test_fun\"] = [_test_ones_like_float, _test_ones_like_int]\n arg_dict[\"shape\"] = [(2, 3), (2, 3, 4), (2, 4, 5, 6)]\n arg_dict[\"device\"] = [\"cpu\", \"cuda\"]\n for arg in GenArgList(arg_dict):\n arg[0](test_case, *arg[1:])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] | [
[
"numpy.square",
"numpy.random.random",
"numpy.allclose",
"numpy.mean",
"numpy.sum"
],
[
"numpy.allclose",
"numpy.reshape",
"numpy.zeros_like",
"numpy.random.randn",
"numpy.random.uniform",
"numpy.array",
"numpy.zeros"
],
[
"numpy.random.random",
"numpy.ones"
],
[
"numpy.random.random",
"numpy.ones"
],
[
"numpy.array",
"numpy.ones"
],
[
"tensorflow.config.experimental.set_memory_growth",
"tensorflow.config.experimental.list_physical_devices",
"tensorflow.gather",
"numpy.random.rand",
"tensorflow.GradientTape"
],
[
"numpy.sqrt",
"tensorflow.Variable",
"tensorflow.config.experimental.set_memory_growth",
"tensorflow.reduce_mean",
"tensorflow.config.experimental.list_physical_devices",
"tensorflow.keras.optimizers.RMSprop",
"numpy.copy",
"tensorflow.keras.optimizers.Adam",
"tensorflow.GradientTape",
"numpy.random.randint",
"numpy.prod",
"numpy.random.uniform",
"numpy.zeros",
"numpy.sum",
"tensorflow.keras.optimizers.SGD"
],
[
"tensorflow.clip_by_value",
"numpy.allclose",
"tensorflow.Variable",
"tensorflow.config.experimental.set_memory_growth",
"numpy.clip",
"numpy.array_equal",
"tensorflow.config.experimental.list_physical_devices",
"numpy.random.standard_normal",
"numpy.random.randint",
"tensorflow.GradientTape"
],
[
"numpy.iinfo"
],
[
"numpy.random.random",
"numpy.ones"
],
[
"numpy.random.randn"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.13",
"1.10",
"1.12"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"2.9",
"2.5",
"2.8",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
cclauss/loss-landscape | [
"35a4c9bcabdefdcaf1e3d7266da878205bfca2a0"
] | [
"dataloader.py"
] | [
"import torch\nimport torchvision\nfrom torchvision import transforms\nimport os\nimport numpy as np\nimport argparse\n\ndef get_relative_path(file):\n script_dir = os.path.dirname(__file__) # <-- absolute dir the script is in\n return os.path.join(script_dir, file)\n\n\ndef load_dataset(dataset='cifar10', datapath='cifar10/data', batch_size=128, \\\n threads=2, raw_data=False, data_split=1, split_idx=0, \\\n trainloader_path=\"\", testloader_path=\"\"):\n \"\"\"\n Setup dataloader. The data is not randomly cropped as in training because of\n we want to esimate the loss value with a fixed dataset.\n\n Args:\n raw_data: raw images, no data preprocessing\n data_split: the number of splits for the training dataloader\n split_idx: the index for the split of the dataloader, starting at 0\n\n Returns:\n train_loader, test_loader\n \"\"\"\n\n # use specific dataloaders\n if trainloader_path and testloader_path:\n assert os.path.exists(trainloader_path), 'trainloader does not exist'\n assert os.path.exists(testloader_path), 'testloader does not exist'\n train_loader = torch.load(trainloader_path)\n test_loader = torch.load(testloader_path)\n return train_loader, test_loader\n\n assert split_idx < data_split, 'the index of data partition should be smaller than the total number of split'\n\n if dataset == 'cifar10':\n normalize = transforms.Normalize(mean=[x/255.0 for x in [125.3, 123.0, 113.9]],\n std=[x/255.0 for x in [63.0, 62.1, 66.7]])\n\n data_folder = get_relative_path(datapath)\n if raw_data:\n transform = transforms.Compose([\n transforms.ToTensor()\n ])\n else:\n transform = transforms.Compose([\n transforms.ToTensor(),\n normalize,\n ])\n\n trainset = torchvision.datasets.CIFAR10(root=data_folder, train=True,\n download=True, transform=transform)\n if data_split > 1:\n indices = torch.tensor(np.arange(len(trainset)))\n data_num = len(trainset) // data_split\n ind_start = data_num*split_idx\n ind_end = min(data_num*(split_idx + 1), len(trainset))\n train_indices = indices[ind_start:ind_end]\n train_sampler = torch.utils.data.sampler.SubsetRandomSampler(train_indices)\n train_loader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,\n sampler=train_sampler,\n shuffle=False, num_workers=threads)\n else:\n kwargs = {'num_workers': 2, 'pin_memory': True}\n train_loader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,\n shuffle=False, **kwargs)\n testset = torchvision.datasets.CIFAR10(root=data_folder, train=False,\n download=False, transform=transform)\n test_loader = torch.utils.data.DataLoader(testset, batch_size=batch_size,\n shuffle=False, num_workers=threads)\n\n return train_loader, test_loader\n\n\n###############################################################\n#### MAIN\n###############################################################\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training')\n parser.add_argument('--mpi', '-m', action='store_true', help='use mpi')\n parser.add_argument('--cuda', '-c', action='store_true', help='use cuda')\n parser.add_argument('--threads', default=2, type=int, help='number of threads')\n parser.add_argument('--batch_size', default=128, type=int, help='minibatch size')\n parser.add_argument('--dataset', default='cifar10', help='cifar10 | imagenet')\n parser.add_argument('--datapath', default='cifar10/data', metavar='DIR', help='path to the dataset')\n parser.add_argument('--raw_data', action='store_true', default=False, help='do not normalize data')\n parser.add_argument('--data_split', default=1, type=int, help='the number of splits for the dataloader')\n parser.add_argument('--split_idx', default=0, type=int, help='the index of data splits for the dataloader')\n parser.add_argument('--trainloader', default='', help='path to the dataloader with random labels')\n parser.add_argument('--testloader', default='', help='path to the testloader with random labels')\n\n args = parser.parse_args()\n\n trainloader, testloader = load_dataset(args.dataset, args.datapath,\n args.batch_size, args.threads, args.raw_data,\n args.data_split, args.split_idx,\n args.trainloader, args.testloader)\n\n print('num of batches: %d' % len(trainloader))\n for batch_idx, (inputs, targets) in enumerate(trainloader):\n print('batch_idx: %d batch_size: %d'%(batch_idx, len(inputs)))\n"
] | [
[
"torch.utils.data.sampler.SubsetRandomSampler",
"torch.utils.data.DataLoader",
"torch.load"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tarasowski/machine-learning-plagiarism-detector | [
"d499883af3a8968e1f96d730dfd3b4dfe1d1d50f"
] | [
"get_predictions.py"
] | [
"import boto3\nimport pandas as pd\nimport numpy as np\nimport os\nimport pickle\nfrom sklearn.metrics import accuracy_score\nimport json\n\nclient = boto3.client('sagemaker-runtime')\n\nENDPOINT_NAME = os.environ.get('ENDPOINT_NAME') \nCONTENT_TYPE = 'application/python-pickle'\n\ntest_data = pd.read_csv('./models/test.csv', header=None, names=None)\ntest_y = test_data.iloc[:,0]\ntest_x = test_data.iloc[:, 1:]\n\nresponse = client.invoke_endpoint(\n EndpointName=ENDPOINT_NAME,\n ContentType=CONTENT_TYPE,\n Body=pickle.dumps(test_x)\n )\n\ntest_y_preds = json.loads(response['Body'].read().decode('utf-8'))\n\nprint('Accuracy Score: ', accuracy_score(test_y, test_y_preds))\n"
] | [
[
"pandas.read_csv",
"sklearn.metrics.accuracy_score"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
nathanbraun/BAP | [
"0aa549dd1da4c4cb545d8929197684aaad77739e"
] | [
"code/Chp2/problem5.py"
] | [
"\"\"\"\nModify the tips example to make it robust to outliers. Try with one shared for\nall groups and also with one per group. Run posterior predictive checks to\nassess these three models.\n\"\"\"\nimport pandas as pd\nimport random\nfrom pandas import DataFrame, Series\nimport matplotlib.pyplot as plt\nimport arviz as az\nimport pymc3 as pm\nimport numpy as np\n\ntips = pd.read_csv('../data/tips.csv')\n\ntip = tips['tip'].values\nidx = pd.Categorical(tips['day'], categories=['Thur', 'Fri', 'Sat', 'Sun']).codes\ngroups = len(np.unique(idx))\n\n# original version\nwith pm.Model() as model:\n mu = pm.Normal('mu', mu=0, sd=10, shape=groups)\n sigma = pm.HalfNormal('sigma', sd=10, shape=groups)\n y = pm.Normal('y', mu=mu[idx], sd=sigma[idx], observed=tip)\n trace = pm.sample(5000)\n\n\"\"\"\n- apparently in pymc can only index groups by numbers (0-3) not other things\n(thu-sun)\n- need to pass mu=mu[idx] to llh\n\n\"\"\"\n\n# robust to outliers version\n\"\"\"\n- let's set it as an exponential distribution with a mean of 30\n- allows for many small values up through 120 ish\n\"\"\"\n\nwith pm.Model() as model1:\n mu = pm.Normal('mu', mu=0, sd=10, shape=groups)\n sigma = pm.HalfNormal('sigma', sd=10, shape=groups)\n v = pm.Exponential('v', 1/30)\n y = pm.StudentT('y', mu=mu[idx], sd=sigma[idx], nu=v, observed=tip)\n trace1 = pm.sample(5000)\n\n\n# outliers, but own can vary\nwith pm.Model() as model2:\n mu = pm.Normal('mu', mu=0, sd=10, shape=groups)\n sigma = pm.HalfNormal('sigma', sd=10, shape=groups)\n v = pm.Exponential('v', 1/30, shape=groups)\n y = pm.StudentT('y', mu=mu[idx], sd=sigma[idx], nu=v[idx], observed=tip)\n trace2 = pm.sample(5000)\n\ny_pred = pm.sample_posterior_predictive(trace, 100, model)\ndata_ppc = az.from_pymc3(trace=trace, posterior_predictive=y_pred)\nax0 = az.plot_ppc(data_ppc, kind='kde', mean=False)\nplt.xlim(-2, 8)\n\ny_pred1 = pm.sample_posterior_predictive(trace1, 100, model1)\ndata_ppc1 = az.from_pymc3(trace=trace, posterior_predictive=y_pred1)\naz.plot_ppc(data_ppc1, kind='kde', mean=False)\nplt.xlim(-2, 8)\n\n# works best by far\ny_pred2 = pm.sample_posterior_predictive(trace2, 100, model2)\ndata_ppc2 = az.from_pymc3(trace=trace, posterior_predictive=y_pred2)\naz.plot_ppc(data_ppc2, kind='kde', mean=False)\nplt.xlim(-2, 8)\n\n\"\"\"\nCompute the probability of superiority directly from the posterior (without\ncomputing Cohen's d first). You can use the pm.sample_posterior_predictive()\nfunction to take a sample from each group. Is it really different from the\ncalculation assuming normality? Can you explain the result?\n\"\"\"\n\ndf = DataFrame(y_pred2['y'].T)\n\nthu = df.loc[tips['day'] == 'Thur']\nfri = df.loc[tips['day'] == 'Fri']\nsat = df.loc[tips['day'] == 'Sat']\nsun = df.loc[tips['day'] == 'Sun']\n\ndef compare2(df1, df2):\n nrows = min(len(df1), len(df2))\n return (df1.sample(nrows).reset_index(drop=True) >\n df2.sample(nrows).reset_index(drop=True)).mean().mean()\n\ncompare2(thu, fri)\ncompare2(thu, sat)\ncompare2(thu, sun)\n\ncompare2(fri, sat)\ncompare2(fri, sun)\n\ncompare2(sat, sun)\n\n\"\"\"\nCreate a hierarchical version of the tips example by partially pooling across\nthe days of the week. Compare the results to those obtained without the\nhierarchical structure.\n\"\"\"\n\nwith pm.Model() as model_h:\n # hyper_priors\n mu_mu = pm.Normal('mu_mu', mu=0, sd=10)\n sigma_mu = pm.HalfNormal('sigma_mu', 10)\n\n # priors\n mu = pm.Normal('mu', mu=mu_mu, sd=sigma_mu, shape=groups)\n sigma = pm.HalfNormal('sigma', sd=10, shape=groups)\n\n y = pm.Normal('y', mu=mu[idx], sd=sigma[idx], observed=tip)\n trace = pm.sample(5000)\n\n# with pm.Model() as model_h:\n# # hyper_priors\n# mu_mu = pm.Normal('mu_mu', mu=0, sd=10)\n# sigma_mu = pm.HalfNormal('sigma_mu', 10)\n\n# # priors\n# mu = pm.Normal('mu', mu=mu_mu, sd=sigma_mu, shape=groups)\n# sigma = pm.HalfNormal('sigma', sd=10, shape=groups)\n\n# y = pm.Normal('y', mu=mu[idx], sd=sigma[idx], observed=diff)\n\n# trace_cs_h = pm.sample(1000)\n\ny_pred3 = pm.sample_posterior_predictive(trace, 100, model_h)\ndata_ppc3 = az.from_pymc3(trace=trace, posterior_predictive=y_pred3)\naz.plot_ppc(data_ppc3, kind='kde', mean=False)\nplt.xlim(-2, 8)\n\nwith pm.Model() as model4:\n # hyper_priors\n mu_mu = pm.Normal('mu_mu', mu=0, sd=10)\n sigma_mu = pm.HalfNormal('sigma_mu', 10)\n\n # priors\n mu = pm.Normal('mu', mu=mu_mu, sd=sigma_mu, shape=groups)\n sigma = pm.HalfNormal('sigma', sd=10, shape=groups)\n v = pm.Exponential('v', 1/30, shape=groups)\n\n y = pm.StudentT('y', mu=mu[idx], sd=sigma[idx], nu=v[idx], observed=tip)\n trace4 = pm.sample(5000)\n\n# with pm.Model() as model_h:\n# # hyper_priors\n# mu_mu = pm.Normal('mu_mu', mu=0, sd=10)\n# sigma_mu = pm.HalfNormal('sigma_mu', 10)\n\n# # priors\n# mu = pm.Normal('mu', mu=mu_mu, sd=sigma_mu, shape=groups)\n# sigma = pm.HalfNormal('sigma', sd=10, shape=groups)\n\n# y = pm.Normal('y', mu=mu[idx], sd=sigma[idx], observed=diff)\n\n# trace_cs_h = pm.sample(1000)\n\ny_pred4 = pm.sample_posterior_predictive(trace, 100, model_h)\ndata_ppc4 = az.from_pymc3(trace=trace, posterior_predictive=y_pred4)\naz.plot_ppc(data_ppc4, kind='kde', mean=False)\nplt.xlim(-2, 8)\n\nwith pm.Model() as model5:\n alpha = pm.Exponential('alpha', 1/30, shape=groups)\n beta = pm.Exponential('beta', 1/30, shape=groups)\n y = pm.Gamma('y', alpha=alpha[idx], beta=beta[idx], observed=tip)\n trace5 = pm.sample(5000)\n\ny_pred5 = pm.sample_posterior_predictive(trace, 100, model5)\ndata_ppc5 = az.from_pymc3(trace=trace5, posterior_predictive=y_pred5)\naz.plot_ppc(data_ppc5, kind='kde', mean=False)\nplt.xlim(0, 8)\n"
] | [
[
"pandas.read_csv",
"numpy.unique",
"pandas.Categorical",
"pandas.DataFrame",
"matplotlib.pyplot.xlim"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
Diyago/ML-DL-scripts | [
"eeb5c3c7c5841eb4cdb272690e14d6718f3685b2",
"eeb5c3c7c5841eb4cdb272690e14d6718f3685b2",
"eeb5c3c7c5841eb4cdb272690e14d6718f3685b2",
"eeb5c3c7c5841eb4cdb272690e14d6718f3685b2"
] | [
"DEEP LEARNING/segmentation/Kaggle TGS Salt Identification Challenge/v2/common_blocks/loaders.py",
"DEEP LEARNING/segmentation/Kaggle TGS Salt Identification Challenge/v1/utils.py",
"time series regression/autocorelation, mov avg etc/simpleExponentialSmoothing.py",
"DEEP LEARNING/segmentation/Severstal-Steel-Defect-Detection-master/model_resnet.py"
] | [
"import numpy as np\nimport torch\nimport torchvision.transforms as transforms\nfrom PIL import Image\nfrom attrdict import AttrDict\nfrom sklearn.externals import joblib\nfrom torch.utils.data import Dataset, DataLoader\nfrom imgaug import augmenters as iaa\nfrom functools import partial\nfrom itertools import product\nimport multiprocessing as mp\nfrom scipy.stats import gmean\nfrom tqdm import tqdm\nimport json\nfrom steppy.base import BaseTransformer\n\nfrom .utils import from_pil, to_pil, binary_from_rle, ImgAug\n\n\nclass ImageReader(BaseTransformer):\n def __init__(self, train_mode, x_columns, y_columns, target_format=\"png\"):\n self.train_mode = train_mode\n self.x_columns = x_columns\n self.y_columns = y_columns\n self.target_format = target_format\n\n def transform(self, meta):\n X_ = meta[self.x_columns].values\n\n X = self.load_images(X_, filetype=\"png\", grayscale=False)\n if self.train_mode:\n y_ = meta[self.y_columns].values\n y = self.load_images(y_, filetype=self.target_format, grayscale=True)\n else:\n y = None\n\n return {\"X\": X, \"y\": y}\n\n def load_images(self, filepaths, filetype, grayscale=False):\n X = []\n for i in range(filepaths.shape[1]):\n column = filepaths[:, i]\n X.append([])\n for filepath in tqdm(column):\n if filetype == \"png\":\n data = self.load_image(filepath, grayscale=grayscale)\n elif filetype == \"json\":\n data = self.read_json(filepath)\n else:\n raise Exception(\"files must be png or json\")\n X[i].append(data)\n return X\n\n def load_image(self, img_filepath, grayscale):\n image = Image.open(img_filepath, \"r\")\n if not grayscale:\n image = image.convert(\"RGB\")\n else:\n image = image.convert(\"L\").point(lambda x: 0 if x < 128 else 255, \"1\")\n return image\n\n def read_json(self, path):\n with open(path, \"r\") as file:\n data = json.load(file)\n masks = [to_pil(binary_from_rle(rle)) for rle in data]\n return masks\n\n\nclass XYSplit(BaseTransformer):\n def __init__(self, train_mode, x_columns, y_columns):\n self.train_mode = train_mode\n super().__init__()\n self.x_columns = x_columns\n self.y_columns = y_columns\n self.columns_to_get = None\n self.target_columns = None\n\n def transform(self, meta):\n X = meta[self.x_columns[0]].values\n if self.train_mode:\n y = meta[self.y_columns[0]].values\n else:\n y = None\n\n return {\"X\": X, \"y\": y}\n\n\nclass ImageSegmentationBaseDataset(Dataset):\n def __init__(\n self,\n X,\n y,\n train_mode,\n image_transform,\n image_augment_with_target,\n mask_transform,\n image_augment,\n image_source=\"memory\",\n ):\n super().__init__()\n self.X = X\n if y is not None:\n self.y = y\n else:\n self.y = None\n\n self.train_mode = train_mode\n self.image_transform = image_transform\n self.mask_transform = mask_transform\n self.image_augment = (\n image_augment if image_augment is not None else ImgAug(iaa.Noop())\n )\n self.image_augment_with_target = (\n image_augment_with_target\n if image_augment_with_target is not None\n else ImgAug(iaa.Noop())\n )\n\n self.image_source = image_source\n\n def __len__(self):\n if self.image_source == \"memory\":\n return len(self.X[0])\n elif self.image_source == \"disk\":\n return self.X.shape[0]\n\n def __getitem__(self, index):\n if self.image_source == \"memory\":\n load_func = self.load_from_memory\n elif self.image_source == \"disk\":\n load_func = self.load_from_disk\n else:\n raise NotImplementedError(\"Possible loading options: 'memory' and 'disk'!\")\n\n Xi = load_func(self.X, index, filetype=\"png\", grayscale=False)\n\n if self.y is not None:\n Mi = self.load_target(self.y, index, load_func)\n Xi, *Mi = from_pil(Xi, *Mi)\n Xi, *Mi = self.image_augment_with_target(Xi, *Mi)\n Xi = self.image_augment(Xi)\n Xi, *Mi = to_pil(Xi, *Mi)\n\n if self.mask_transform is not None:\n Mi = [self.mask_transform(m) for m in Mi]\n\n if self.image_transform is not None:\n Xi = self.image_transform(Xi)\n\n Mi = torch.cat(Mi, dim=0)\n return Xi, Mi\n else:\n Xi = from_pil(Xi)\n Xi = self.image_augment(Xi)\n Xi = to_pil(Xi)\n\n if self.image_transform is not None:\n Xi = self.image_transform(Xi)\n return Xi\n\n def load_from_memory(self, data_source, index, **kwargs):\n return data_source[0][index]\n\n def load_from_disk(self, data_source, index, *, filetype, grayscale=False):\n if filetype == \"png\":\n img_filepath = data_source[index]\n return self.load_image(img_filepath, grayscale=grayscale)\n elif filetype == \"json\":\n json_filepath = data_source[index]\n return self.read_json(json_filepath)\n else:\n raise Exception(\"files must be png or json\")\n\n def load_image(self, img_filepath, grayscale):\n image = Image.open(img_filepath, \"r\")\n if not grayscale:\n image = image.convert(\"RGB\")\n else:\n image = image.convert(\"L\").point(lambda x: 0 if x < 128 else 1)\n return image\n\n def read_json(self, path):\n with open(path, \"r\") as file:\n data = json.load(file)\n masks = [to_pil(binary_from_rle(rle)) for rle in data]\n return masks\n\n def load_target(self, data_source, index, load_func):\n raise NotImplementedError\n\n\nclass ImageSegmentationJsonDataset(ImageSegmentationBaseDataset):\n def load_target(self, data_source, index, load_func):\n Mi = load_func(data_source, index, filetype=\"json\")\n return Mi\n\n\nclass ImageSegmentationPngDataset(ImageSegmentationBaseDataset):\n def load_target(self, data_source, index, load_func):\n Mi = load_func(data_source, index, filetype=\"png\", grayscale=True)\n Mi = from_pil(Mi)\n target = [to_pil(Mi == class_nr) for class_nr in [0, 1]]\n return target\n\n\nclass ImageSegmentationTTADataset(ImageSegmentationBaseDataset):\n def __init__(self, tta_params, tta_transform, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.tta_params = tta_params\n self.tta_transform = tta_transform\n\n def __getitem__(self, index):\n if self.image_source == \"memory\":\n load_func = self.load_from_memory\n elif self.image_source == \"disk\":\n load_func = self.load_from_disk\n else:\n raise NotImplementedError(\"Possible loading options: 'memory' and 'disk'!\")\n\n Xi = load_func(self.X, index, filetype=\"png\", grayscale=False)\n Xi = from_pil(Xi)\n\n if self.image_augment is not None:\n Xi = self.image_augment(Xi)\n\n if self.tta_params is not None:\n tta_transform_specs = self.tta_params[index]\n Xi = self.tta_transform(Xi, tta_transform_specs)\n Xi = to_pil(Xi)\n\n if self.image_transform is not None:\n Xi = self.image_transform(Xi)\n\n return Xi\n\n\nclass ImageSegmentationLoaderBasic(BaseTransformer):\n def __init__(self, train_mode, loader_params, dataset_params, augmentation_params):\n super().__init__()\n self.train_mode = train_mode\n self.loader_params = AttrDict(loader_params)\n self.dataset_params = AttrDict(dataset_params)\n self.augmentation_params = AttrDict(augmentation_params)\n\n self.mask_transform = None\n self.image_transform = None\n\n self.image_augment_train = None\n self.image_augment_inference = None\n self.image_augment_with_target_train = None\n self.image_augment_with_target_inference = None\n\n self.dataset = None\n\n def transform(self, X, y, X_valid=None, y_valid=None, **kwargs):\n if self.train_mode and y is not None:\n flow, steps = self.get_datagen(X, y, True, self.loader_params.training)\n else:\n flow, steps = self.get_datagen(X, None, False, self.loader_params.inference)\n\n if X_valid is not None and y_valid is not None:\n valid_flow, valid_steps = self.get_datagen(\n X_valid, y_valid, False, self.loader_params.inference\n )\n else:\n valid_flow = None\n valid_steps = None\n\n return {\n \"datagen\": (flow, steps),\n \"validation_datagen\": (valid_flow, valid_steps),\n }\n\n def get_datagen(self, X, y, train_mode, loader_params):\n if train_mode:\n dataset = self.dataset(\n X,\n y,\n train_mode=True,\n image_augment=self.image_augment_train,\n image_augment_with_target=self.image_augment_with_target_train,\n mask_transform=self.mask_transform,\n image_transform=self.image_transform,\n image_source=self.dataset_params.image_source,\n )\n else:\n dataset = self.dataset(\n X,\n y,\n train_mode=False,\n image_augment=self.image_augment_inference,\n image_augment_with_target=self.image_augment_with_target_inference,\n mask_transform=self.mask_transform,\n image_transform=self.image_transform,\n image_source=self.dataset_params.image_source,\n )\n\n datagen = DataLoader(dataset, **loader_params)\n steps = len(datagen)\n return datagen, steps\n\n def load(self, filepath):\n params = joblib.load(filepath)\n self.loader_params = params[\"loader_params\"]\n return self\n\n def save(self, filepath):\n params = {\"loader_params\": self.loader_params}\n joblib.dump(params, filepath)\n\n\nclass ImageSegmentationLoaderBasicTTA(ImageSegmentationLoaderBasic):\n def __init__(self, loader_params, dataset_params, augmentation_params):\n self.loader_params = AttrDict(loader_params)\n self.dataset_params = AttrDict(dataset_params)\n self.augmentation_params = AttrDict(augmentation_params)\n\n self.mask_transform = None\n self.image_transform = None\n\n self.image_augment_train = None\n self.image_augment_inference = None\n self.image_augment_with_target_train = None\n self.image_augment_with_target_inference = None\n\n self.dataset = None\n\n def transform(self, X, tta_params, **kwargs):\n flow, steps = self.get_datagen(X, tta_params, self.loader_params.inference)\n valid_flow = None\n valid_steps = None\n return {\n \"datagen\": (flow, steps),\n \"validation_datagen\": (valid_flow, valid_steps),\n }\n\n def get_datagen(self, X, tta_params, loader_params):\n dataset = self.dataset(\n tta_params=tta_params,\n tta_transform=self.augmentation_params.tta_transform,\n X=X,\n y=None,\n train_mode=False,\n image_augment=self.image_augment_inference,\n image_augment_with_target=self.image_augment_with_target_inference,\n mask_transform=self.mask_transform,\n image_transform=self.image_transform,\n image_source=self.dataset_params.image_source,\n )\n\n datagen = DataLoader(dataset, **loader_params)\n steps = len(datagen)\n return datagen, steps\n\n\nclass ImageSegmentationLoaderResizePad(ImageSegmentationLoaderBasic):\n def __init__(self, train_mode, loader_params, dataset_params, augmentation_params):\n super().__init__(train_mode, loader_params, dataset_params, augmentation_params)\n\n self.image_transform = transforms.Compose(\n [\n transforms.Grayscale(num_output_channels=3),\n transforms.ToTensor(),\n transforms.Normalize(\n mean=self.dataset_params.MEAN, std=self.dataset_params.STD\n ),\n ]\n )\n self.mask_transform = transforms.Compose(\n [transforms.Lambda(to_array), transforms.Lambda(to_tensor)]\n )\n\n self.image_augment_train = ImgAug(\n self.augmentation_params[\"image_augment_train\"]\n )\n self.image_augment_with_target_train = ImgAug(\n self.augmentation_params[\"image_augment_with_target_train\"]\n )\n self.image_augment_inference = ImgAug(\n self.augmentation_params[\"image_augment_inference\"]\n )\n self.image_augment_with_target_inference = ImgAug(\n self.augmentation_params[\"image_augment_with_target_inference\"]\n )\n\n if self.dataset_params.target_format == \"png\":\n self.dataset = ImageSegmentationPngDataset\n elif self.dataset_params.target_format == \"json\":\n self.dataset = ImageSegmentationJsonDataset\n else:\n raise Exception(\"files must be png or json\")\n\n\nclass ImageSegmentationLoaderPadTTA(ImageSegmentationLoaderBasicTTA):\n def __init__(self, loader_params, dataset_params, augmentation_params):\n super().__init__(loader_params, dataset_params, augmentation_params)\n\n self.image_transform = transforms.Compose(\n [\n transforms.Grayscale(num_output_channels=3),\n transforms.ToTensor(),\n transforms.Normalize(\n mean=self.dataset_params.MEAN, std=self.dataset_params.STD\n ),\n ]\n )\n self.mask_transform = transforms.Compose(\n [transforms.Lambda(to_array), transforms.Lambda(to_tensor)]\n )\n\n self.image_augment_inference = ImgAug(\n self.augmentation_params[\"image_augment_inference\"]\n )\n self.image_augment_with_target_inference = ImgAug(\n self.augmentation_params[\"image_augment_with_target_inference\"]\n )\n self.dataset = ImageSegmentationTTADataset\n\n\nclass ImageSegmentationLoaderResize(ImageSegmentationLoaderBasic):\n def __init__(self, train_mode, loader_params, dataset_params, augmentation_params):\n super().__init__(train_mode, loader_params, dataset_params, augmentation_params)\n\n self.image_transform = transforms.Compose(\n [\n transforms.Resize((self.dataset_params.h, self.dataset_params.w)),\n transforms.Grayscale(num_output_channels=3),\n transforms.ToTensor(),\n transforms.Normalize(\n mean=self.dataset_params.MEAN, std=self.dataset_params.STD\n ),\n ]\n )\n self.mask_transform = transforms.Compose(\n [\n transforms.Resize(\n (self.dataset_params.h, self.dataset_params.w), interpolation=0\n ),\n transforms.Lambda(to_array),\n transforms.Lambda(to_tensor),\n ]\n )\n\n self.image_augment_train = ImgAug(\n self.augmentation_params[\"image_augment_train\"]\n )\n self.image_augment_with_target_train = ImgAug(\n self.augmentation_params[\"image_augment_with_target_train\"]\n )\n\n if self.dataset_params.target_format == \"png\":\n self.dataset = ImageSegmentationPngDataset\n elif self.dataset_params.target_format == \"json\":\n self.dataset = ImageSegmentationJsonDataset\n else:\n raise Exception(\"files must be png or json\")\n\n\nclass ImageSegmentationLoaderResizeTTA(ImageSegmentationLoaderBasicTTA):\n def __init__(self, loader_params, dataset_params, augmentation_params):\n super().__init__(loader_params, dataset_params, augmentation_params)\n\n self.image_transform = transforms.Compose(\n [\n transforms.Resize((self.dataset_params.h, self.dataset_params.w)),\n transforms.Grayscale(num_output_channels=3),\n transforms.ToTensor(),\n transforms.Normalize(\n mean=self.dataset_params.MEAN, std=self.dataset_params.STD\n ),\n ]\n )\n self.mask_transform = transforms.Compose(\n [\n transforms.Resize(\n (self.dataset_params.h, self.dataset_params.w), interpolation=0\n ),\n transforms.Lambda(to_array),\n transforms.Lambda(to_tensor),\n ]\n )\n\n self.dataset = ImageSegmentationTTADataset\n\n\nclass MetaTestTimeAugmentationGenerator(BaseTransformer):\n def __init__(self, **kwargs):\n self.tta_transformations = AttrDict(kwargs)\n\n def transform(self, X, **kwargs):\n X_tta_rows, tta_params, img_ids = [], [], []\n for i in range(len(X)):\n rows, params, ids = self._get_tta_data(i, X[i])\n tta_params.extend(params)\n img_ids.extend(ids)\n X_tta_rows.extend(rows)\n X_tta = np.array(X_tta_rows)\n return {\"X_tta\": X_tta, \"tta_params\": tta_params, \"img_ids\": img_ids}\n\n def _get_tta_data(self, i, row):\n original_specs = {\n \"ud_flip\": False,\n \"lr_flip\": False,\n \"rotation\": 0,\n \"color_shift\": False,\n }\n tta_specs = [original_specs]\n\n ud_options = [True, False] if self.tta_transformations.flip_ud else [False]\n lr_options = [True, False] if self.tta_transformations.flip_lr else [False]\n rot_options = [0, 90, 180, 270] if self.tta_transformations.rotation else [0]\n if self.tta_transformations.color_shift_runs:\n color_shift_options = list(\n range(1, self.tta_transformations.color_shift_runs + 1, 1)\n )\n else:\n color_shift_options = [False]\n\n for ud, lr, rot, color in product(\n ud_options, lr_options, rot_options, color_shift_options\n ):\n if ud is False and lr is False and rot == 0 and color is False:\n continue\n else:\n tta_specs.append(\n {\n \"ud_flip\": ud,\n \"lr_flip\": lr,\n \"rotation\": rot,\n \"color_shift\": color,\n }\n )\n\n img_ids = [i] * len(tta_specs)\n X_rows = [row] * len(tta_specs)\n return X_rows, tta_specs, img_ids\n\n\nclass TestTimeAugmentationGenerator(BaseTransformer):\n def __init__(self, **kwargs):\n self.tta_transformations = AttrDict(kwargs)\n\n def transform(self, X, **kwargs):\n X_tta, tta_params, img_ids = [], [], []\n X = X[0]\n for i in range(len(X)):\n images, params, ids = self._get_tta_data(i, X[i])\n tta_params.extend(params)\n img_ids.extend(ids)\n X_tta.extend(images)\n return {\"X_tta\": [X_tta], \"tta_params\": tta_params, \"img_ids\": img_ids}\n\n def _get_tta_data(self, i, row):\n original_specs = {\n \"ud_flip\": False,\n \"lr_flip\": False,\n \"rotation\": 0,\n \"color_shift\": False,\n }\n tta_specs = [original_specs]\n\n ud_options = [True, False] if self.tta_transformations.flip_ud else [False]\n lr_options = [True, False] if self.tta_transformations.flip_lr else [False]\n rot_options = [0, 90, 180, 270] if self.tta_transformations.rotation else [0]\n if self.tta_transformations.color_shift_runs:\n color_shift_options = list(\n range(1, self.tta_transformations.color_shift_runs + 1, 1)\n )\n else:\n color_shift_options = [False]\n\n for ud, lr, rot, color in product(\n ud_options, lr_options, rot_options, color_shift_options\n ):\n if ud is False and lr is False and rot == 0 and color is False:\n continue\n else:\n tta_specs.append(\n {\n \"ud_flip\": ud,\n \"lr_flip\": lr,\n \"rotation\": rot,\n \"color_shift\": color,\n }\n )\n\n img_ids = [i] * len(tta_specs)\n X_rows = [row] * len(tta_specs)\n return X_rows, tta_specs, img_ids\n\n\nclass TestTimeAugmentationAggregator(BaseTransformer):\n def __init__(self, tta_inverse_transform, method, nthreads):\n self.tta_inverse_transform = tta_inverse_transform\n self.method = method\n self.nthreads = nthreads\n\n @property\n def agg_method(self):\n methods = {\"mean\": np.mean, \"max\": np.max, \"min\": np.min, \"gmean\": gmean}\n return partial(methods[self.method], axis=-1)\n\n def transform(self, images, tta_params, img_ids, **kwargs):\n _aggregate_augmentations = partial(\n aggregate_augmentations,\n images=images,\n tta_params=tta_params,\n tta_inverse_transform=self.tta_inverse_transform,\n img_ids=img_ids,\n agg_method=self.agg_method,\n )\n unique_img_ids = set(img_ids)\n threads = min(self.nthreads, len(unique_img_ids))\n with mp.pool.ThreadPool(threads) as executor:\n averages_images = executor.map(_aggregate_augmentations, unique_img_ids)\n return {\"aggregated_prediction\": averages_images}\n\n\ndef aggregate_augmentations(\n img_id, images, tta_params, tta_inverse_transform, img_ids, agg_method\n):\n tta_predictions_for_id = []\n for image, tta_param, ids in zip(images, tta_params, img_ids):\n if ids == img_id:\n tta_prediction = tta_inverse_transform(image, tta_param)\n tta_predictions_for_id.append(tta_prediction)\n else:\n continue\n tta_averaged = agg_method(np.stack(tta_predictions_for_id, axis=-1))\n return tta_averaged\n\n\ndef to_array(x):\n x_ = x.convert(\"L\") # convert image to monochrome\n x_ = np.array(x_)\n x_ = x_.astype(np.float32)\n return x_\n\n\ndef to_tensor(x):\n x_ = np.expand_dims(x, axis=0)\n x_ = torch.from_numpy(x_)\n return x_\n",
"import logging\nimport os\n\n# import pathlib\nimport random\nimport sys\nimport time\nfrom itertools import chain\nfrom collections import Iterable\n\n# from deepsense import neptune\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom PIL import Image\nimport yaml\nfrom imgaug import augmenters as iaa\nimport imgaug as ia\n\n\ndef do_length_encode(x):\n bs = np.where(x.T.flatten())[0]\n\n rle = []\n prev = -2\n for b in bs:\n if b > prev + 1:\n rle.extend((b + 1, 0))\n rle[-1] += 1\n prev = b\n\n # https://www.kaggle.com/c/data-science-bowl-2018/discussion/48561#\n # if len(rle)!=0 and rle[-1]+rle[-2] == x.size:\n # rle[-2] = rle[-2] -1\n\n rle = \" \".join([str(r) for r in rle])\n return rle\n\n\nfrom math import isnan\n\n\ndef do_length_decode(rle, H, W, fill_value=255):\n mask = np.zeros((H, W), np.uint8)\n if type(rle).__name__ == \"float\":\n return mask\n\n mask = mask.reshape(-1)\n rle = np.array([int(s) for s in rle.split(\" \")]).reshape(-1, 2)\n for r in rle:\n start = r[0] - 1\n end = start + r[1]\n mask[start:end] = fill_value\n mask = mask.reshape(W, H).T # H, W need to swap as transposing.\n return mask\n\n\ndef decode_csv(csv_name):\n import pandas as pd\n\n data = pd.read_csv(csv_name)\n id = data[\"id\"]\n rle_mask = data[\"rle_mask\"]\n\n dict = {}\n for id, rle in zip(id, rle_mask):\n tmp = do_length_decode(rle, 101, 101, fill_value=1)\n dict[id] = tmp\n\n return dict\n\n\ndef save_id_fea(predict_dict, save_dir):\n for id in predict_dict:\n output_mat = predict_dict[id].astype(np.float32)\n np.save(os.path.join(save_dir, id), output_mat)\n\n\ndef state_dict_remove_moudle(moudle_state_dict, model):\n state_dict = model.state_dict()\n keys = list(moudle_state_dict.keys())\n for key in keys:\n print(key + \" loaded\")\n new_key = key.replace(r\"module.\", r\"\")\n print(new_key)\n state_dict[new_key] = moudle_state_dict[key]\n\n return state_dict\n\n\nfrom matplotlib import pyplot as plt\n\n\ndef write_and_plot(name, aver_num, logits, max_y=1.0, color=\"blue\"):\n def moving_average(a, n=aver_num):\n ret = np.cumsum(a, dtype=float)\n ret[n:] = ret[n:] - ret[:-n]\n return ret[n - 1 :] / n\n\n # ===========================================================\n moving_plot = moving_average(np.array(logits))\n x = range(moving_plot.shape[0])\n # plt.close()\n plt.plot(x, moving_plot, color=color)\n plt.ylim(0, max_y)\n plt.savefig(name)\n\n\ndef decompose(labeled):\n nr_true = labeled.max()\n masks = []\n for i in range(1, nr_true + 1):\n msk = labeled.copy()\n msk[msk != i] = 0.0\n msk[msk == i] = 255.0\n masks.append(msk)\n\n if not masks:\n return [labeled]\n else:\n return masks\n\n\ndef encode_rle(predictions):\n return [run_length_encoding(mask) for mask in predictions]\n\n\ndef create_submission(predictions):\n output = []\n for image_id, mask in predictions:\n # print(image_id)\n\n rle_encoded = \" \".join(str(rle) for rle in run_length_encoding(mask))\n output.append([image_id, rle_encoded])\n\n submission = pd.DataFrame(output, columns=[\"id\", \"rle_mask\"]).astype(str)\n return submission\n\n\ndef run_length_encoding(x):\n # https://www.kaggle.com/c/data-science-bowl-2018/discussion/48561#\n bs = np.where(x.T.flatten())[0]\n\n rle = []\n prev = -2\n for b in bs:\n if b > prev + 1:\n rle.extend((b + 1, 0))\n rle[-1] += 1\n prev = b\n\n if len(rle) != 0 and rle[-1] + rle[-2] > (x.size + 1):\n rle[-2] = rle[-2] - 1\n\n return rle\n\n\ndef run_length_decoding(mask_rle, shape):\n \"\"\"\n Based on https://www.kaggle.com/msl23518/visualize-the-stage1-test-solution and modified\n Args:\n mask_rle: run-length as string formatted (start length)\n shape: (height, width) of array to return\n\n Returns:\n numpy array, 1 - mask, 0 - background\n\n \"\"\"\n s = mask_rle.split()\n starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]\n starts -= 1\n ends = starts + lengths\n img = np.zeros(shape[1] * shape[0], dtype=np.uint8)\n for lo, hi in zip(starts, ends):\n img[lo:hi] = 1\n return img.reshape((shape[1], shape[0])).T\n\n\ndef sigmoid(x):\n return 1.0 / (1 + np.exp(-x))\n\n\ndef softmax(X, theta=1.0, axis=None):\n \"\"\"\n https://nolanbconaway.github.io/blog/2017/softmax-numpy\n Compute the softmax of each element along an axis of X.\n\n Parameters\n ----------\n X: ND-Array. Probably should be floats.\n theta (optional): float parameter, used as a multiplier\n prior to exponentiation. Default = 1.0\n axis (optional): axis to compute values along. Default is the\n first non-singleton axis.\n\n Returns an array the same size as X. The result will sum to 1\n along the specified axis.\n \"\"\"\n\n # make X at least 2d\n y = np.atleast_2d(X)\n\n # find axis\n if axis is None:\n axis = next(j[0] for j in enumerate(y.shape) if j[1] > 1)\n\n # multiply y against the theta parameter,\n y = y * float(theta)\n\n # subtract the max for numerical stability\n y = y - np.expand_dims(np.max(y, axis=axis), axis)\n\n # exponentiate y\n y = np.exp(y)\n\n # take the sum along the specified axis\n ax_sum = np.expand_dims(np.sum(y, axis=axis), axis)\n\n # finally: divide elementwise\n p = y / ax_sum\n\n # flatten if X was 1D\n if len(X.shape) == 1:\n p = p.flatten()\n\n return p\n\n\ndef from_pil(*images):\n images = [np.array(image) for image in images]\n if len(images) == 1:\n return images[0]\n else:\n return images\n\n\ndef to_pil(*images):\n images = [Image.fromarray((image).astype(np.uint8)) for image in images]\n if len(images) == 1:\n return images[0]\n else:\n return images\n\n\ndef binary_from_rle(rle):\n return cocomask.decode(rle)\n\n\ndef get_crop_pad_sequence(vertical, horizontal):\n top = int(vertical / 2)\n bottom = vertical - top\n right = int(horizontal / 2)\n left = horizontal - right\n return (top, right, bottom, left)\n\n\ndef get_list_of_image_predictions(batch_predictions):\n image_predictions = []\n for batch_pred in batch_predictions:\n image_predictions.extend(list(batch_pred))\n return image_predictions\n\n\ndef set_seed(seed):\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\n\nclass ImgAug:\n def __init__(self, augmenters):\n if not isinstance(augmenters, list):\n augmenters = [augmenters]\n self.augmenters = augmenters\n self.seq_det = None\n\n def _pre_call_hook(self):\n seq = iaa.Sequential(self.augmenters)\n seq = reseed(seq, deterministic=True)\n self.seq_det = seq\n\n def transform(self, *images):\n images = [self.seq_det.augment_image(image) for image in images]\n if len(images) == 1:\n return images[0]\n else:\n return images\n\n def __call__(self, *args):\n self._pre_call_hook()\n return self.transform(*args)\n\n\ndef get_seed():\n seed = int(time.time()) + int(os.getpid())\n return seed\n\n\ndef reseed(augmenter, deterministic=True):\n augmenter.random_state = ia.new_random_state(get_seed())\n if deterministic:\n augmenter.deterministic = True\n\n for lists in augmenter.get_children_lists():\n for aug in lists:\n aug = reseed(aug, deterministic=True)\n return augmenter\n",
"# Load modules\nfrom __future__ import print_function\nimport os\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\n# Load Dataset\nibm_df = pd.read_csv(\"datasets/ibm-common-stock-closing-prices.csv\")\nibm_df.head()\n\n# Rename the second column\nibm_df.rename(columns={\"IBM common stock closing prices\": \"Close_Price\"}, inplace=True)\nibm_df.head()\n\n# Function for Sigle exponential smoothing\ndef single_exp_smoothing(x, alpha):\n F = [x[0]] # first value is same as series\n for t in range(1, len(x)):\n F.append(alpha * x[t] + (1 - alpha) * F[t - 1])\n return F\n\n\nibm_df[\"SES\"] = single_exp_smoothing(ibm_df[\"Close_Price\"], 0.8)\n\n\n### Plot Single Exponential Smoothing forecasted value\nfig = plt.figure(figsize=(5.5, 5.5))\nax = fig.add_subplot(2, 1, 1)\nibm_df[\"Close_Price\"].plot(ax=ax)\nax.set_title(\"IBM Common Stock Close Prices during 1962-1965\")\nax = fig.add_subplot(2, 1, 2)\nibm_df[\"SES\"].plot(ax=ax, color=\"r\")\nax.set_title(\"Single Exponential Smoothing\")\nplt.savefig(\"plots/ch2/B07887_02_14.png\", format=\"png\", dpi=300)\n\n\n# Plot the forecasted values using multiple alpha values\n# Calculate the moving averages using 'rolling' and 'mean' functions\nibm_df[\"SES2\"] = single_exp_smoothing(ibm_df[\"Close_Price\"], 0.2)\nibm_df[\"SES6\"] = single_exp_smoothing(ibm_df[\"Close_Price\"], 0.6)\nibm_df[\"SES8\"] = single_exp_smoothing(ibm_df[\"Close_Price\"], 0.8)\n\n# Plot the curves\nf, axarr = plt.subplots(3, sharex=True)\nf.set_size_inches(5.5, 5.5)\n\nibm_df[\"Close_Price\"].iloc[:45].plot(color=\"b\", linestyle=\"-\", ax=axarr[0])\nibm_df[\"SES2\"].iloc[:45].plot(color=\"r\", linestyle=\"--\", ax=axarr[0])\naxarr[0].set_title(\"Alpha 0.2\")\n\nibm_df[\"Close_Price\"].iloc[:45].plot(color=\"b\", linestyle=\"-\", ax=axarr[1])\nibm_df[\"SES6\"].iloc[:45].plot(color=\"r\", linestyle=\"--\", ax=axarr[1])\naxarr[1].set_title(\"Alpha 0.6\")\n\nibm_df[\"Close_Price\"].iloc[:45].plot(color=\"b\", linestyle=\"-\", ax=axarr[2])\nibm_df[\"SES8\"].iloc[:45].plot(color=\"r\", linestyle=\"--\", ax=axarr[2])\naxarr[2].set_title(\"Alpha 0.8\")\nplt.savefig(\"plots/ch2/B07887_02_15.png\", format=\"png\", dpi=300)\n",
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\nfrom torch.nn import init\nfrom cbam import *\nfrom bam import *\n\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"3x3 convolution with padding\"\n return nn.Conv2d(\n in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False\n )\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, use_cbam=False):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm2d(planes)\n self.downsample = downsample\n self.stride = stride\n\n if use_cbam:\n self.cbam = CBAM(planes, 16)\n else:\n self.cbam = None\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n if not self.cbam is None:\n out = self.cbam(out)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, use_cbam=False):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(\n planes, planes, kernel_size=3, stride=stride, padding=1, bias=False\n )\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes * 4)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n if use_cbam:\n self.cbam = CBAM(planes * 4, 16)\n else:\n self.cbam = None\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n if not self.cbam is None:\n out = self.cbam(out)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n def __init__(self, block, layers, network_type, num_classes, att_type=None):\n self.inplanes = 64\n super(ResNet, self).__init__()\n self.network_type = network_type\n # different model config between ImageNet and CIFAR\n if network_type == \"ImageNet\":\n self.conv1 = nn.Conv2d(\n 3, 64, kernel_size=7, stride=2, padding=3, bias=False\n )\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.avgpool = nn.AvgPool2d(7)\n else:\n self.conv1 = nn.Conv2d(\n 3, 64, kernel_size=3, stride=1, padding=1, bias=False\n )\n\n self.bn1 = nn.BatchNorm2d(64)\n self.relu = nn.ReLU(inplace=True)\n\n if att_type == \"BAM\":\n self.bam1 = BAM(64 * block.expansion)\n self.bam2 = BAM(128 * block.expansion)\n self.bam3 = BAM(256 * block.expansion)\n else:\n self.bam1, self.bam2, self.bam3 = None, None, None\n\n self.layer1 = self._make_layer(block, 64, layers[0], att_type=att_type)\n self.layer2 = self._make_layer(\n block, 128, layers[1], stride=2, att_type=att_type\n )\n self.layer3 = self._make_layer(\n block, 256, layers[2], stride=2, att_type=att_type\n )\n self.layer4 = self._make_layer(\n block, 512, layers[3], stride=2, att_type=att_type\n )\n\n self.fc = nn.Linear(512 * block.expansion, num_classes)\n\n init.kaiming_normal(self.fc.weight)\n for key in self.state_dict():\n if key.split(\".\")[-1] == \"weight\":\n if \"conv\" in key:\n init.kaiming_normal(self.state_dict()[key], mode=\"fan_out\")\n if \"bn\" in key:\n if \"SpatialGate\" in key:\n self.state_dict()[key][...] = 0\n else:\n self.state_dict()[key][...] = 1\n elif key.split(\".\")[-1] == \"bias\":\n self.state_dict()[key][...] = 0\n\n def _make_layer(self, block, planes, blocks, stride=1, att_type=None):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(\n self.inplanes,\n planes * block.expansion,\n kernel_size=1,\n stride=stride,\n bias=False,\n ),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(\n block(\n self.inplanes, planes, stride, downsample, use_cbam=att_type == \"CBAM\"\n )\n )\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes, use_cbam=att_type == \"CBAM\"))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n if self.network_type == \"ImageNet\":\n x = self.maxpool(x)\n\n x = self.layer1(x)\n if not self.bam1 is None:\n x = self.bam1(x)\n\n x = self.layer2(x)\n if not self.bam2 is None:\n x = self.bam2(x)\n\n x = self.layer3(x)\n if not self.bam3 is None:\n x = self.bam3(x)\n\n x = self.layer4(x)\n\n if self.network_type == \"ImageNet\":\n x = self.avgpool(x)\n else:\n x = F.avg_pool2d(x, 4)\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n return x\n\n\ndef ResidualNet(network_type, depth, num_classes, att_type):\n\n assert network_type in [\n \"ImageNet\",\n \"CIFAR10\",\n \"CIFAR100\",\n ], \"network type should be ImageNet or CIFAR10 / CIFAR100\"\n assert depth in [18, 34, 50, 101], \"network depth should be 18, 34, 50 or 101\"\n\n if depth == 18:\n model = ResNet(BasicBlock, [2, 2, 2, 2], network_type, num_classes, att_type)\n\n elif depth == 34:\n model = ResNet(BasicBlock, [3, 4, 6, 3], network_type, num_classes, att_type)\n\n elif depth == 50:\n model = ResNet(Bottleneck, [3, 4, 6, 3], network_type, num_classes, att_type)\n\n elif depth == 101:\n model = ResNet(Bottleneck, [3, 4, 23, 3], network_type, num_classes, att_type)\n\n return model\n"
] | [
[
"sklearn.externals.joblib.dump",
"numpy.expand_dims",
"sklearn.externals.joblib.load",
"torch.cat",
"torch.utils.data.DataLoader",
"torch.from_numpy",
"numpy.stack",
"numpy.array"
],
[
"pandas.read_csv",
"numpy.random.seed",
"numpy.asarray",
"matplotlib.pyplot.ylim",
"torch.manual_seed",
"numpy.cumsum",
"matplotlib.pyplot.savefig",
"pandas.DataFrame",
"matplotlib.pyplot.plot",
"numpy.atleast_2d",
"numpy.max",
"torch.cuda.is_available",
"torch.cuda.manual_seed_all",
"numpy.array",
"numpy.exp",
"numpy.zeros",
"numpy.sum"
],
[
"pandas.read_csv",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.figure"
],
[
"torch.nn.init.kaiming_normal",
"torch.nn.Sequential",
"torch.nn.functional.avg_pool2d",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.MaxPool2d",
"torch.nn.AvgPool2d",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Sayam753/Theano-PyMC | [
"02378861f1a77135f2556018630092a09262ea76",
"f9a85474509ea02647771ad6540b11f02fab59a8"
] | [
"tests/tensor/random/test_type.py",
"tests/tensor/test_extra_ops.py"
] | [
"import pickle\nimport sys\n\nimport numpy as np\nimport pytest\n\nfrom aesara import shared\nfrom aesara.compile.ops import ViewOp\nfrom aesara.tensor.random.type import RandomStateType, random_state_type\n\n\n# @pytest.mark.skipif(\n# not config.cxx, reason=\"G++ not available, so we need to skip this test.\"\n# )\ndef test_view_op_c_code():\n # TODO: It might be good to make sure that the registered C code works\n # (even though it's basically copy-paste from other registered `Op`s).\n # from aesara.compile.ops import view_op\n # from aesara.link.c.basic import CLinker\n # rng_var = random_state_type()\n # rng_view = view_op(rng_var)\n # function(\n # [rng_var],\n # rng_view,\n # mode=Mode(optimizer=None, linker=CLinker()),\n # )\n\n assert ViewOp.c_code_and_version[RandomStateType]\n\n\nclass TestRandomStateType:\n def test_pickle(self):\n rng_r = random_state_type()\n\n rng_pkl = pickle.dumps(rng_r)\n rng_unpkl = pickle.loads(rng_pkl)\n\n assert isinstance(rng_unpkl, type(rng_r))\n assert isinstance(rng_unpkl.type, type(rng_r.type))\n\n def test_repr(self):\n assert repr(random_state_type) == \"RandomStateType\"\n\n def test_filter(self):\n\n rng_type = random_state_type\n\n rng = np.random.RandomState()\n assert rng_type.filter(rng) is rng\n\n with pytest.raises(TypeError):\n rng_type.filter(1)\n\n rng = rng.get_state(legacy=False)\n assert rng_type.is_valid_value(rng, strict=False)\n\n rng[\"state\"] = {}\n\n assert rng_type.is_valid_value(rng, strict=False) is False\n\n rng = {}\n assert rng_type.is_valid_value(rng, strict=False) is False\n\n def test_values_eq(self):\n\n rng_type = random_state_type\n\n rng_a = np.random.RandomState(12)\n rng_b = np.random.RandomState(12)\n rng_c = np.random.RandomState(123)\n\n bg = np.random.PCG64()\n rng_d = np.random.RandomState(bg)\n rng_e = np.random.RandomState(bg)\n\n bg_2 = np.random.Philox()\n rng_f = np.random.RandomState(bg_2)\n rng_g = np.random.RandomState(bg_2)\n\n assert rng_type.values_eq(rng_a, rng_b)\n assert not rng_type.values_eq(rng_a, rng_c)\n\n assert not rng_type.values_eq(rng_a, rng_d)\n assert not rng_type.values_eq(rng_d, rng_a)\n\n assert not rng_type.values_eq(rng_a, rng_d)\n assert rng_type.values_eq(rng_d, rng_e)\n\n assert rng_type.values_eq(rng_f, rng_g)\n assert not rng_type.values_eq(rng_g, rng_a)\n assert not rng_type.values_eq(rng_e, rng_g)\n\n def test_get_shape_info(self):\n rng = np.random.RandomState(12)\n rng_a = shared(rng)\n\n assert isinstance(\n random_state_type.get_shape_info(rng_a), np.random.RandomState\n )\n\n def test_get_size(self):\n rng = np.random.RandomState(12)\n rng_a = shared(rng)\n shape_info = random_state_type.get_shape_info(rng_a)\n size = random_state_type.get_size(shape_info)\n assert size == sys.getsizeof(rng.get_state(legacy=False))\n\n def test_may_share_memory(self):\n rng_a = np.random.RandomState(12)\n bg = np.random.PCG64()\n rng_b = np.random.RandomState(bg)\n\n rng_var_a = shared(rng_a, borrow=True)\n rng_var_b = shared(rng_b, borrow=True)\n shape_info_a = random_state_type.get_shape_info(rng_var_a)\n shape_info_b = random_state_type.get_shape_info(rng_var_b)\n\n assert random_state_type.may_share_memory(shape_info_a, shape_info_b) is False\n\n rng_c = np.random.RandomState(bg)\n rng_var_c = shared(rng_c, borrow=True)\n shape_info_c = random_state_type.get_shape_info(rng_var_c)\n\n assert random_state_type.may_share_memory(shape_info_b, shape_info_c) is True\n",
"import numpy as np\nimport pytest\n\nimport aesara\nfrom aesara import function\nfrom aesara import tensor as aet\nfrom aesara.assert_op import Assert\nfrom aesara.compile.mode import Mode\nfrom aesara.configdefaults import config\nfrom aesara.gradient import grad\nfrom aesara.graph.basic import applys_between\nfrom aesara.graph.optdb import OptimizationQuery\nfrom aesara.tensor.elemwise import DimShuffle\nfrom aesara.tensor.extra_ops import (\n Bartlett,\n BroadcastTo,\n CpuContiguous,\n CumOp,\n DiffOp,\n FillDiagonal,\n FillDiagonalOffset,\n RavelMultiIndex,\n Repeat,\n SearchsortedOp,\n Unique,\n UnravelIndex,\n bartlett,\n bincount,\n broadcast_arrays,\n broadcast_shape,\n broadcast_to,\n compress,\n cpu_contiguous,\n cumprod,\n cumsum,\n diff,\n fill_diagonal,\n fill_diagonal_offset,\n ravel_multi_index,\n repeat,\n searchsorted,\n squeeze,\n to_one_hot,\n unravel_index,\n)\nfrom aesara.tensor.math import sum as aet_sum\nfrom aesara.tensor.subtensor import AdvancedIncSubtensor1\nfrom aesara.tensor.type import (\n TensorType,\n dmatrix,\n dscalar,\n dtensor3,\n fmatrix,\n fvector,\n integer_dtypes,\n iscalar,\n ivector,\n lscalar,\n matrix,\n scalar,\n tensor,\n tensor3,\n vector,\n)\nfrom aesara.utils import LOCAL_BITWIDTH, PYTHON_INT_BITWIDTH\nfrom tests import unittest_tools as utt\n\n\ndef test_cpu_contiguous():\n a = fmatrix(\"a\")\n i = iscalar(\"i\")\n a_val = np.asarray(np.random.rand(4, 5), dtype=\"float32\")\n f = aesara.function([a, i], cpu_contiguous(a.reshape((5, 4))[::i]))\n topo = f.maker.fgraph.toposort()\n assert any([isinstance(node.op, CpuContiguous) for node in topo])\n assert f(a_val, 1).flags[\"C_CONTIGUOUS\"]\n assert f(a_val, 2).flags[\"C_CONTIGUOUS\"]\n assert f(a_val, 3).flags[\"C_CONTIGUOUS\"]\n # Test the grad:\n\n utt.verify_grad(cpu_contiguous, [np.random.rand(5, 7, 2)])\n\n\nclass TestSearchsortedOp(utt.InferShapeTester):\n def setup_method(self):\n super().setup_method()\n self.op_class = SearchsortedOp\n self.op = SearchsortedOp()\n\n self.x = vector(\"x\")\n self.v = tensor3(\"v\")\n\n self.a = 30 * np.random.random(50).astype(config.floatX)\n self.b = 30 * np.random.random((8, 10, 5)).astype(config.floatX)\n self.idx_sorted = np.argsort(self.a).astype(\"int32\")\n\n def test_searchsortedOp_on_sorted_input(self):\n f = aesara.function([self.x, self.v], searchsorted(self.x, self.v))\n assert np.allclose(\n np.searchsorted(self.a[self.idx_sorted], self.b),\n f(self.a[self.idx_sorted], self.b),\n )\n\n sorter = vector(\"sorter\", dtype=\"int32\")\n f = aesara.function(\n [self.x, self.v, sorter],\n self.x.searchsorted(self.v, sorter=sorter, side=\"right\"),\n )\n assert np.allclose(\n self.a.searchsorted(self.b, sorter=self.idx_sorted, side=\"right\"),\n f(self.a, self.b, self.idx_sorted),\n )\n\n sa = self.a[self.idx_sorted]\n f = aesara.function([self.x, self.v], self.x.searchsorted(self.v, side=\"right\"))\n assert np.allclose(sa.searchsorted(self.b, side=\"right\"), f(sa, self.b))\n\n def test_searchsortedOp_wrong_side_kwd(self):\n with pytest.raises(ValueError):\n searchsorted(self.x, self.v, side=\"asdfa\")\n\n def test_searchsortedOp_on_no_1d_inp(self):\n no_1d = dmatrix(\"no_1d\")\n with pytest.raises(ValueError):\n searchsorted(no_1d, self.v)\n with pytest.raises(ValueError):\n searchsorted(self.x, self.v, sorter=no_1d)\n\n def test_searchsortedOp_on_float_sorter(self):\n sorter = vector(\"sorter\", dtype=\"float32\")\n with pytest.raises(TypeError):\n searchsorted(self.x, self.v, sorter=sorter)\n\n def test_searchsortedOp_on_int_sorter(self):\n compatible_types = (\"int8\", \"int16\", \"int32\")\n if PYTHON_INT_BITWIDTH == 64:\n compatible_types += (\"int64\",)\n # 'uint8', 'uint16', 'uint32', 'uint64')\n for dtype in compatible_types:\n sorter = vector(\"sorter\", dtype=dtype)\n f = aesara.function(\n [self.x, self.v, sorter],\n searchsorted(self.x, self.v, sorter=sorter),\n allow_input_downcast=True,\n )\n assert np.allclose(\n np.searchsorted(self.a, self.b, sorter=self.idx_sorted),\n f(self.a, self.b, self.idx_sorted),\n )\n\n def test_searchsortedOp_on_right_side(self):\n f = aesara.function(\n [self.x, self.v], searchsorted(self.x, self.v, side=\"right\")\n )\n assert np.allclose(\n np.searchsorted(self.a, self.b, side=\"right\"), f(self.a, self.b)\n )\n\n def test_infer_shape(self):\n # Test using default parameters' value\n self._compile_and_check(\n [self.x, self.v],\n [searchsorted(self.x, self.v)],\n [self.a[self.idx_sorted], self.b],\n self.op_class,\n )\n\n # Test parameter ``sorter``\n sorter = vector(\"sorter\", dtype=\"int32\")\n self._compile_and_check(\n [self.x, self.v, sorter],\n [searchsorted(self.x, self.v, sorter=sorter)],\n [self.a, self.b, self.idx_sorted],\n self.op_class,\n )\n\n # Test parameter ``side``\n la = np.ones(10).astype(config.floatX)\n lb = np.ones(shape=(1, 2, 3)).astype(config.floatX)\n self._compile_and_check(\n [self.x, self.v],\n [searchsorted(self.x, self.v, side=\"right\")],\n [la, lb],\n self.op_class,\n )\n\n def test_grad(self):\n utt.verify_grad(self.op, [self.a[self.idx_sorted], self.b])\n\n\nclass TestCumOp(utt.InferShapeTester):\n def setup_method(self):\n super().setup_method()\n self.op_class = CumOp\n self.op = CumOp()\n\n def test_cum_op(self):\n x = tensor3(\"x\")\n a = np.random.random((3, 5, 2)).astype(config.floatX)\n\n # Test axis out of bounds\n with pytest.raises(ValueError):\n cumsum(x, axis=3)\n with pytest.raises(ValueError):\n cumsum(x, axis=-4)\n with pytest.raises(ValueError):\n cumprod(x, axis=3)\n with pytest.raises(ValueError):\n cumprod(x, axis=-4)\n\n f = aesara.function([x], [cumsum(x), cumprod(x)])\n s, p = f(a)\n assert np.allclose(np.cumsum(a), s) # Test axis=None\n assert np.allclose(np.cumprod(a), p) # Test axis=None\n\n for axis in range(-len(a.shape), len(a.shape)):\n f = aesara.function([x], [cumsum(x, axis=axis), cumprod(x, axis=axis)])\n s, p = f(a)\n assert np.allclose(np.cumsum(a, axis=axis), s)\n assert np.allclose(np.cumprod(a, axis=axis), p)\n\n def test_infer_shape(self):\n x = tensor3(\"x\")\n a = np.random.random((3, 5, 2)).astype(config.floatX)\n\n # Test axis=None\n self._compile_and_check([x], [self.op(x)], [a], self.op_class)\n\n for axis in range(-len(a.shape), len(a.shape)):\n self._compile_and_check([x], [cumsum(x, axis=axis)], [a], self.op_class)\n\n def test_grad(self):\n a = np.random.random((3, 5, 2)).astype(config.floatX)\n\n utt.verify_grad(self.op_class(mode=\"add\"), [a]) # Test axis=None\n utt.verify_grad(self.op_class(mode=\"mul\"), [a]) # Test axis=None\n\n for axis in range(-len(a.shape), len(a.shape)):\n utt.verify_grad(self.op_class(axis=axis, mode=\"add\"), [a], eps=4e-4)\n utt.verify_grad(self.op_class(axis=axis, mode=\"mul\"), [a], eps=4e-4)\n\n\nclass TestBinCount(utt.InferShapeTester):\n def test_bincountFn(self):\n w = vector(\"w\")\n\n def ref(data, w=None, minlength=None):\n size = int(data.max() + 1)\n if minlength:\n size = max(size, minlength)\n if w is not None:\n out = np.zeros(size, dtype=w.dtype)\n for i in range(data.shape[0]):\n out[data[i]] += w[i]\n else:\n out = np.zeros(size, dtype=a.dtype)\n for i in range(data.shape[0]):\n out[data[i]] += 1\n return out\n\n for dtype in (\n \"int8\",\n \"int16\",\n \"int32\",\n \"int64\",\n \"uint8\",\n \"uint16\",\n \"uint32\",\n \"uint64\",\n ):\n x = vector(\"x\", dtype=dtype)\n\n a = np.random.randint(1, 51, size=(25)).astype(dtype)\n weights = np.random.random((25,)).astype(config.floatX)\n\n f1 = aesara.function([x], bincount(x))\n f2 = aesara.function([x, w], bincount(x, weights=w))\n\n assert (ref(a) == f1(a)).all()\n assert np.allclose(ref(a, weights), f2(a, weights))\n f3 = aesara.function([x], bincount(x, minlength=55))\n f4 = aesara.function([x], bincount(x, minlength=5))\n assert (ref(a, minlength=55) == f3(a)).all()\n assert (ref(a, minlength=5) == f4(a)).all()\n # skip the following test when using unsigned ints\n if not dtype.startswith(\"u\"):\n a[0] = -1\n f5 = aesara.function([x], bincount(x, assert_nonneg=True))\n with pytest.raises(AssertionError):\n f5(a)\n\n\nclass TestDiffOp(utt.InferShapeTester):\n nb = 10 # Number of time iterating for n\n\n def setup_method(self):\n super().setup_method()\n self.op_class = DiffOp\n self.op = DiffOp()\n\n def test_diffOp(self):\n x = matrix(\"x\")\n a = np.random.random((30, 50)).astype(config.floatX)\n\n f = aesara.function([x], diff(x))\n assert np.allclose(np.diff(a), f(a))\n\n for axis in range(len(a.shape)):\n for k in range(TestDiffOp.nb):\n g = aesara.function([x], diff(x, n=k, axis=axis))\n assert np.allclose(np.diff(a, n=k, axis=axis), g(a))\n\n def test_infer_shape(self):\n x = matrix(\"x\")\n a = np.random.random((30, 50)).astype(config.floatX)\n\n self._compile_and_check([x], [self.op(x)], [a], self.op_class)\n\n for axis in range(len(a.shape)):\n for k in range(TestDiffOp.nb):\n self._compile_and_check(\n [x], [diff(x, n=k, axis=axis)], [a], self.op_class\n )\n\n def test_grad(self):\n x = vector(\"x\")\n a = np.random.random(50).astype(config.floatX)\n\n aesara.function([x], grad(aet_sum(diff(x)), x))\n utt.verify_grad(self.op, [a])\n\n for k in range(TestDiffOp.nb):\n aesara.function([x], grad(aet_sum(diff(x, n=k)), x))\n utt.verify_grad(DiffOp(n=k), [a], eps=7e-3)\n\n\nclass TestSqueeze(utt.InferShapeTester):\n shape_list = [(1, 3), (1, 2, 3), (1, 5, 1, 1, 6)]\n broadcast_list = [\n [True, False],\n [True, False, False],\n [True, False, True, True, False],\n ]\n\n def setup_method(self):\n super().setup_method()\n self.op = squeeze\n\n def test_op(self):\n for shape, broadcast in zip(self.shape_list, self.broadcast_list):\n data = np.random.random(size=shape).astype(config.floatX)\n variable = TensorType(config.floatX, broadcast)()\n\n f = aesara.function([variable], self.op(variable))\n\n expected = np.squeeze(data)\n tested = f(data)\n\n assert tested.shape == expected.shape\n assert np.allclose(tested, expected)\n\n def test_infer_shape(self):\n for shape, broadcast in zip(self.shape_list, self.broadcast_list):\n data = np.random.random(size=shape).astype(config.floatX)\n variable = TensorType(config.floatX, broadcast)()\n\n self._compile_and_check(\n [variable], [self.op(variable)], [data], DimShuffle, warn=False\n )\n\n def test_grad(self):\n for shape, broadcast in zip(self.shape_list, self.broadcast_list):\n data = np.random.random(size=shape).astype(config.floatX)\n\n utt.verify_grad(self.op, [data])\n\n def test_var_interface(self):\n # same as test_op, but use a_aesara_var.squeeze.\n for shape, broadcast in zip(self.shape_list, self.broadcast_list):\n data = np.random.random(size=shape).astype(config.floatX)\n variable = TensorType(config.floatX, broadcast)()\n\n f = aesara.function([variable], variable.squeeze())\n\n expected = np.squeeze(data)\n tested = f(data)\n\n assert tested.shape == expected.shape\n assert np.allclose(tested, expected)\n\n def test_axis(self):\n variable = TensorType(config.floatX, [False, True, False])()\n res = squeeze(variable, axis=1)\n\n assert res.broadcastable == (False, False)\n\n variable = TensorType(config.floatX, [False, True, False])()\n res = squeeze(variable, axis=(1,))\n\n assert res.broadcastable == (False, False)\n\n variable = TensorType(config.floatX, [False, True, False, True])()\n res = squeeze(variable, axis=(1, 3))\n\n assert res.broadcastable == (False, False)\n\n\nclass TestCompress(utt.InferShapeTester):\n axis_list = [None, -1, 0, 0, 0, 1]\n cond_list = [\n [1, 0, 1, 0, 0, 1],\n [0, 1, 1, 0],\n [0, 1, 1, 0],\n [],\n [0, 0, 0, 0],\n [1, 1, 0, 1, 0],\n ]\n shape_list = [(2, 3), (4, 3), (4, 3), (4, 3), (4, 3), (3, 5)]\n\n def setup_method(self):\n super().setup_method()\n self.op = compress\n\n def test_op(self):\n for axis, cond, shape in zip(self.axis_list, self.cond_list, self.shape_list):\n cond_var = ivector()\n data = np.random.random(size=shape).astype(config.floatX)\n data_var = matrix()\n\n f = aesara.function(\n [cond_var, data_var], self.op(cond_var, data_var, axis=axis)\n )\n\n expected = np.compress(cond, data, axis=axis)\n tested = f(cond, data)\n\n assert tested.shape == expected.shape\n assert np.allclose(tested, expected)\n\n\nclass TestRepeat(utt.InferShapeTester):\n def _possible_axis(self, ndim):\n return [None] + list(range(ndim)) + [-i for i in range(ndim)]\n\n def setup_method(self):\n super().setup_method()\n self.op_class = Repeat\n self.op = Repeat()\n # uint64 always fails\n # int64 and uint32 also fail if python int are 32-bit\n if LOCAL_BITWIDTH == 64:\n self.numpy_unsupported_dtypes = (\"uint64\",)\n if LOCAL_BITWIDTH == 32:\n self.numpy_unsupported_dtypes = (\"uint32\", \"int64\", \"uint64\")\n\n def test_basic(self):\n for ndim in [1, 3]:\n x = TensorType(config.floatX, [False] * ndim)()\n a = np.random.random((10,) * ndim).astype(config.floatX)\n\n for axis in self._possible_axis(ndim):\n for dtype in integer_dtypes:\n r_var = scalar(dtype=dtype)\n r = np.asarray(3, dtype=dtype)\n if dtype == \"uint64\" or (\n dtype in self.numpy_unsupported_dtypes and r_var.ndim == 1\n ):\n with pytest.raises(TypeError):\n repeat(x, r_var, axis=axis)\n else:\n f = aesara.function([x, r_var], repeat(x, r_var, axis=axis))\n assert np.allclose(np.repeat(a, r, axis=axis), f(a, r))\n\n r_var = vector(dtype=dtype)\n if axis is None:\n r = np.random.randint(1, 6, size=a.size).astype(dtype)\n else:\n r = np.random.randint(1, 6, size=(10,)).astype(dtype)\n\n if dtype in self.numpy_unsupported_dtypes and r_var.ndim == 1:\n with pytest.raises(TypeError):\n repeat(x, r_var, axis=axis)\n else:\n f = aesara.function([x, r_var], repeat(x, r_var, axis=axis))\n assert np.allclose(np.repeat(a, r, axis=axis), f(a, r))\n\n # check when r is a list of single integer, e.g. [3].\n r = np.random.randint(1, 11, size=()).astype(dtype) + 2\n f = aesara.function([x], repeat(x, [r], axis=axis))\n assert np.allclose(np.repeat(a, r, axis=axis), f(a))\n assert not np.any(\n [\n isinstance(n.op, Repeat)\n for n in f.maker.fgraph.toposort()\n ]\n )\n\n # check when r is aesara tensortype that broadcastable is (True,)\n r_var = TensorType(broadcastable=(True,), dtype=dtype)()\n r = np.random.randint(1, 6, size=(1,)).astype(dtype)\n f = aesara.function([x, r_var], repeat(x, r_var, axis=axis))\n assert np.allclose(np.repeat(a, r[0], axis=axis), f(a, r))\n assert not np.any(\n [\n isinstance(n.op, Repeat)\n for n in f.maker.fgraph.toposort()\n ]\n )\n\n @pytest.mark.slow\n def test_infer_shape(self):\n for ndim in [1, 3]:\n x = TensorType(config.floatX, [False] * ndim)()\n shp = (np.arange(ndim) + 1) * 3\n a = np.random.random(shp).astype(config.floatX)\n\n for axis in self._possible_axis(ndim):\n for dtype in [\"int8\", \"uint8\", \"uint64\"]:\n r_var = scalar(dtype=dtype)\n r = np.asarray(3, dtype=dtype)\n if dtype in self.numpy_unsupported_dtypes:\n r_var = vector(dtype=dtype)\n with pytest.raises(TypeError):\n repeat(x, r_var)\n else:\n self._compile_and_check(\n [x, r_var],\n [Repeat(axis=axis)(x, r_var)],\n [a, r],\n self.op_class,\n )\n\n r_var = vector(dtype=dtype)\n if axis is None:\n r = np.random.randint(1, 6, size=a.size).astype(dtype)\n elif a.size > 0:\n r = np.random.randint(1, 6, size=a.shape[axis]).astype(\n dtype\n )\n else:\n r = np.random.randint(1, 6, size=(10,)).astype(dtype)\n\n self._compile_and_check(\n [x, r_var],\n [Repeat(axis=axis)(x, r_var)],\n [a, r],\n self.op_class,\n )\n\n def test_grad(self):\n for ndim in range(3):\n a = np.random.random((10,) * ndim).astype(config.floatX)\n\n for axis in self._possible_axis(ndim):\n utt.verify_grad(lambda x: Repeat(axis=axis)(x, 3), [a])\n\n def test_broadcastable(self):\n x = TensorType(config.floatX, [False, True, False])()\n r = Repeat(axis=1)(x, 2)\n assert r.broadcastable == (False, False, False)\n r = Repeat(axis=1)(x, 1)\n assert r.broadcastable == (False, True, False)\n r = Repeat(axis=0)(x, 2)\n assert r.broadcastable == (False, True, False)\n\n\nclass TestBartlett(utt.InferShapeTester):\n def setup_method(self):\n super().setup_method()\n self.op_class = Bartlett\n self.op = bartlett\n\n def test_perform(self):\n x = lscalar()\n f = function([x], self.op(x))\n M = np.random.randint(3, 51, size=())\n assert np.allclose(f(M), np.bartlett(M))\n assert np.allclose(f(0), np.bartlett(0))\n assert np.allclose(f(-1), np.bartlett(-1))\n b = np.array([17], dtype=\"uint8\")\n assert np.allclose(f(b[0]), np.bartlett(b[0]))\n\n def test_infer_shape(self):\n x = lscalar()\n self._compile_and_check(\n [x], [self.op(x)], [np.random.randint(3, 51, size=())], self.op_class\n )\n self._compile_and_check([x], [self.op(x)], [0], self.op_class)\n self._compile_and_check([x], [self.op(x)], [1], self.op_class)\n\n\nclass TestFillDiagonal(utt.InferShapeTester):\n\n rng = np.random.RandomState(43)\n\n def setup_method(self):\n super().setup_method()\n self.op_class = FillDiagonal\n self.op = fill_diagonal\n\n def test_perform(self):\n x = matrix()\n y = scalar()\n f = function([x, y], fill_diagonal(x, y))\n for shp in [(8, 8), (5, 8), (8, 5)]:\n a = np.random.rand(*shp).astype(config.floatX)\n val = np.cast[config.floatX](np.random.rand())\n out = f(a, val)\n # We can't use np.fill_diagonal as it is bugged.\n assert np.allclose(np.diag(out), val)\n assert (out == val).sum() == min(a.shape)\n\n # test for 3dtt\n a = np.random.rand(3, 3, 3).astype(config.floatX)\n x = tensor3()\n y = scalar()\n f = function([x, y], fill_diagonal(x, y))\n val = np.cast[config.floatX](np.random.rand() + 10)\n out = f(a, val)\n # We can't use np.fill_diagonal as it is bugged.\n assert out[0, 0, 0] == val\n assert out[1, 1, 1] == val\n assert out[2, 2, 2] == val\n assert (out == val).sum() == min(a.shape)\n\n @pytest.mark.slow\n def test_gradient(self):\n utt.verify_grad(\n fill_diagonal,\n [np.random.rand(5, 8), np.random.rand()],\n n_tests=1,\n rng=TestFillDiagonal.rng,\n )\n utt.verify_grad(\n fill_diagonal,\n [np.random.rand(8, 5), np.random.rand()],\n n_tests=1,\n rng=TestFillDiagonal.rng,\n )\n\n def test_infer_shape(self):\n z = dtensor3()\n x = dmatrix()\n y = dscalar()\n self._compile_and_check(\n [x, y],\n [self.op(x, y)],\n [np.random.rand(8, 5), np.random.rand()],\n self.op_class,\n )\n self._compile_and_check(\n [z, y],\n [self.op(z, y)],\n # must be square when nd>2\n [np.random.rand(8, 8, 8), np.random.rand()],\n self.op_class,\n warn=False,\n )\n\n\nclass TestFillDiagonalOffset(utt.InferShapeTester):\n\n rng = np.random.RandomState(43)\n\n def setup_method(self):\n super().setup_method()\n self.op_class = FillDiagonalOffset\n self.op = fill_diagonal_offset\n\n def test_perform(self):\n x = matrix()\n y = scalar()\n z = iscalar()\n\n f = function([x, y, z], fill_diagonal_offset(x, y, z))\n for test_offset in (-5, -4, -1, 0, 1, 4, 5):\n for shp in [(8, 8), (5, 8), (8, 5), (5, 5)]:\n a = np.random.rand(*shp).astype(config.floatX)\n val = np.cast[config.floatX](np.random.rand())\n out = f(a, val, test_offset)\n # We can't use np.fill_diagonal as it is bugged.\n assert np.allclose(np.diag(out, test_offset), val)\n if test_offset >= 0:\n assert (out == val).sum() == min(\n min(a.shape), a.shape[1] - test_offset\n )\n else:\n assert (out == val).sum() == min(\n min(a.shape), a.shape[0] + test_offset\n )\n\n def test_gradient(self):\n for test_offset in (-5, -4, -1, 0, 1, 4, 5):\n # input 'offset' will not be tested\n def fill_diagonal_with_fix_offset(a, val):\n return fill_diagonal_offset(a, val, test_offset)\n\n utt.verify_grad(\n fill_diagonal_with_fix_offset,\n [np.random.rand(5, 8), np.random.rand()],\n n_tests=1,\n rng=TestFillDiagonalOffset.rng,\n )\n utt.verify_grad(\n fill_diagonal_with_fix_offset,\n [np.random.rand(8, 5), np.random.rand()],\n n_tests=1,\n rng=TestFillDiagonalOffset.rng,\n )\n utt.verify_grad(\n fill_diagonal_with_fix_offset,\n [np.random.rand(5, 5), np.random.rand()],\n n_tests=1,\n rng=TestFillDiagonalOffset.rng,\n )\n\n def test_infer_shape(self):\n x = dmatrix()\n y = dscalar()\n z = iscalar()\n for test_offset in (-5, -4, -1, 0, 1, 4, 5):\n self._compile_and_check(\n [x, y, z],\n [self.op(x, y, z)],\n [np.random.rand(8, 5), np.random.rand(), test_offset],\n self.op_class,\n )\n self._compile_and_check(\n [x, y, z],\n [self.op(x, y, z)],\n [np.random.rand(5, 8), np.random.rand(), test_offset],\n self.op_class,\n )\n\n\ndef test_to_one_hot():\n v = ivector()\n o = to_one_hot(v, 10)\n f = aesara.function([v], o)\n out = f([1, 2, 3, 5, 6])\n assert out.dtype == config.floatX\n assert np.allclose(\n out,\n [\n [0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0],\n ],\n )\n\n v = ivector()\n o = to_one_hot(v, 10, dtype=\"int32\")\n f = aesara.function([v], o)\n out = f([1, 2, 3, 5, 6])\n assert out.dtype == \"int32\"\n assert np.allclose(\n out,\n [\n [0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0],\n ],\n )\n\n\nclass TestUnique(utt.InferShapeTester):\n def setup_method(self):\n super().setup_method()\n self.op_params = [\n (False, False, False),\n (True, False, False),\n (False, True, False),\n (True, True, False),\n (False, False, True),\n (True, False, True),\n (False, True, True),\n (True, True, True),\n ]\n\n @pytest.mark.parametrize(\n (\"x\", \"inp\", \"axis\"),\n [\n (vector(), np.asarray([2, 1, 3, 2], dtype=config.floatX), None),\n (matrix(), np.asarray([[2, 1], [3, 2], [2, 1]], dtype=config.floatX), None),\n (vector(), np.asarray([2, 1, 3, 2], dtype=config.floatX), 0),\n (matrix(), np.asarray([[2, 1], [3, 2], [2, 1]], dtype=config.floatX), 0),\n (vector(), np.asarray([2, 1, 3, 2], dtype=config.floatX), -1),\n (matrix(), np.asarray([[2, 1], [3, 2], [2, 1]], dtype=config.floatX), -1),\n ],\n )\n def test_basic_vector(self, x, inp, axis):\n list_outs_expected = [\n np.unique(inp, axis=axis),\n np.unique(inp, True, axis=axis),\n np.unique(inp, False, True, axis=axis),\n np.unique(inp, True, True, axis=axis),\n np.unique(inp, False, False, True, axis=axis),\n np.unique(inp, True, False, True, axis=axis),\n np.unique(inp, False, True, True, axis=axis),\n np.unique(inp, True, True, True, axis=axis),\n ]\n for params, outs_expected in zip(self.op_params, list_outs_expected):\n out = aet.unique(x, *params, axis=axis)\n f = aesara.function(inputs=[x], outputs=out)\n outs = f(inp)\n for out, out_exp in zip(outs, outs_expected):\n utt.assert_allclose(out, out_exp)\n\n @pytest.mark.parametrize(\n (\"x\", \"inp\", \"axis\"),\n [\n (vector(), np.asarray([2, 1, 3, 2], dtype=config.floatX), None),\n (matrix(), np.asarray([[2, 1], [3, 2], [2, 1]], dtype=config.floatX), None),\n (vector(), np.asarray([2, 1, 3, 2], dtype=config.floatX), 0),\n (matrix(), np.asarray([[2, 1], [3, 2], [2, 1]], dtype=config.floatX), 0),\n (vector(), np.asarray([2, 1, 3, 2], dtype=config.floatX), -1),\n (matrix(), np.asarray([[2, 1], [3, 2], [2, 1]], dtype=config.floatX), -1),\n ],\n )\n def test_infer_shape(self, x, inp, axis):\n for params in self.op_params:\n if not params[1]:\n continue\n if params[0]:\n f = aet.unique(x, *params, axis=axis)[2]\n else:\n f = aet.unique(x, *params, axis=axis)[1]\n self._compile_and_check(\n [x],\n [f],\n [inp],\n Unique,\n )\n\n\nclass TestUnravelIndex(utt.InferShapeTester):\n def test_unravel_index(self):\n def check(shape, index_ndim, order):\n indices = np.arange(np.product(shape))\n # test with scalars and higher-dimensional indices\n if index_ndim == 0:\n indices = indices[-1]\n elif index_ndim == 2:\n indices = indices[:, np.newaxis]\n indices_symb = aesara.shared(indices)\n\n # reference result\n ref = np.unravel_index(indices, shape, order=order)\n\n def fn(i, d):\n return function([], unravel_index(i, d, order=order))\n\n # shape given as a tuple\n f_array_tuple = fn(indices, shape)\n f_symb_tuple = fn(indices_symb, shape)\n np.testing.assert_equal(ref, f_array_tuple())\n np.testing.assert_equal(ref, f_symb_tuple())\n\n # shape given as an array\n shape_array = np.array(shape)\n f_array_array = fn(indices, shape_array)\n np.testing.assert_equal(ref, f_array_array())\n\n # shape given as an Aesara variable\n shape_symb = aesara.shared(shape_array)\n f_array_symb = fn(indices, shape_symb)\n np.testing.assert_equal(ref, f_array_symb())\n\n # shape given as a Shape op (unravel_index will use get_vector_length\n # to infer the number of dimensions)\n indexed_array = aesara.shared(np.random.uniform(size=shape_array))\n f_array_shape = fn(indices, indexed_array.shape)\n np.testing.assert_equal(ref, f_array_shape())\n\n # shape testing\n self._compile_and_check(\n [],\n unravel_index(indices, shape_symb, order=order),\n [],\n UnravelIndex,\n )\n\n for order in (\"C\", \"F\"):\n for index_ndim in (0, 1, 2):\n check((3,), index_ndim, order)\n check((3, 4), index_ndim, order)\n check((3, 4, 5), index_ndim, order)\n\n # must specify ndim if length of dims is not fixed\n with pytest.raises(ValueError):\n unravel_index(ivector(), ivector())\n\n # must provide integers\n with pytest.raises(TypeError):\n unravel_index(fvector(), (3, 4))\n with pytest.raises(TypeError):\n unravel_index((3, 4), (3.4, 3.2))\n\n # dims must be a 1D sequence\n with pytest.raises(TypeError):\n unravel_index((3, 4), 3)\n with pytest.raises(TypeError):\n unravel_index((3, 4), ((3, 4),))\n\n\nclass TestRavelMultiIndex(utt.InferShapeTester):\n def test_ravel_multi_index(self):\n def check(shape, index_ndim, mode, order):\n multi_index = np.unravel_index(\n np.arange(np.product(shape)), shape, order=order\n )\n # create some invalid indices to test the mode\n if mode in (\"wrap\", \"clip\"):\n multi_index = (multi_index[0] - 1,) + multi_index[1:]\n # test with scalars and higher-dimensional indices\n if index_ndim == 0:\n multi_index = tuple(i[-1] for i in multi_index)\n elif index_ndim == 2:\n multi_index = tuple(i[:, np.newaxis] for i in multi_index)\n multi_index_symb = [aesara.shared(i) for i in multi_index]\n\n # reference result\n ref = np.ravel_multi_index(multi_index, shape, mode, order)\n\n def fn(mi, s):\n return function([], ravel_multi_index(mi, s, mode, order))\n\n # shape given as a tuple\n f_array_tuple = fn(multi_index, shape)\n f_symb_tuple = fn(multi_index_symb, shape)\n np.testing.assert_equal(ref, f_array_tuple())\n np.testing.assert_equal(ref, f_symb_tuple())\n\n # shape given as an array\n shape_array = np.array(shape)\n f_array_array = fn(multi_index, shape_array)\n np.testing.assert_equal(ref, f_array_array())\n\n # shape given as an Aesara variable\n shape_symb = aesara.shared(shape_array)\n f_array_symb = fn(multi_index, shape_symb)\n np.testing.assert_equal(ref, f_array_symb())\n\n # shape testing\n self._compile_and_check(\n [],\n [ravel_multi_index(multi_index, shape_symb, mode, order)],\n [],\n RavelMultiIndex,\n )\n\n for mode in (\"raise\", \"wrap\", \"clip\"):\n for order in (\"C\", \"F\"):\n for index_ndim in (0, 1, 2):\n check((3,), index_ndim, mode, order)\n check((3, 4), index_ndim, mode, order)\n check((3, 4, 5), index_ndim, mode, order)\n\n # must provide integers\n with pytest.raises(TypeError):\n ravel_multi_index((fvector(), ivector()), (3, 4))\n with pytest.raises(TypeError):\n ravel_multi_index(((3, 4), ivector()), (3.4, 3.2))\n\n # dims must be a 1D sequence\n with pytest.raises(TypeError):\n ravel_multi_index(((3, 4),), ((3, 4),))\n\n\ndef test_broadcast_shape():\n def shape_tuple(x, use_bcast=True):\n if use_bcast:\n return tuple(\n s if not bcast else 1\n for s, bcast in zip(tuple(x.shape), x.broadcastable)\n )\n else:\n return tuple(s for s in tuple(x.shape))\n\n x = np.array([[1], [2], [3]])\n y = np.array([4, 5, 6])\n b = np.broadcast(x, y)\n x_aet = aet.as_tensor_variable(x)\n y_aet = aet.as_tensor_variable(y)\n b_aet = broadcast_shape(x_aet, y_aet)\n assert np.array_equal([z.eval() for z in b_aet], b.shape)\n # Now, we try again using shapes as the inputs\n #\n # This case also confirms that a broadcast dimension will\n # broadcast against a non-broadcast dimension when they're\n # both symbolic (i.e. we couldn't obtain constant values).\n b_aet = broadcast_shape(\n shape_tuple(x_aet, use_bcast=False),\n shape_tuple(y_aet, use_bcast=False),\n arrays_are_shapes=True,\n )\n assert any(\n isinstance(node.op, Assert) for node in applys_between([x_aet, y_aet], b_aet)\n )\n assert np.array_equal([z.eval() for z in b_aet], b.shape)\n b_aet = broadcast_shape(\n shape_tuple(x_aet), shape_tuple(y_aet), arrays_are_shapes=True\n )\n assert np.array_equal([z.eval() for z in b_aet], b.shape)\n # These are all constants, so there shouldn't be any asserts in the\n # resulting graph.\n assert not any(\n isinstance(node.op, Assert) for node in applys_between([x_aet, y_aet], b_aet)\n )\n\n x = np.array([1, 2, 3])\n y = np.array([4, 5, 6])\n b = np.broadcast(x, y)\n x_aet = aet.as_tensor_variable(x)\n y_aet = aet.as_tensor_variable(y)\n b_aet = broadcast_shape(x_aet, y_aet)\n assert np.array_equal([z.eval() for z in b_aet], b.shape)\n b_aet = broadcast_shape(\n shape_tuple(x_aet), shape_tuple(y_aet), arrays_are_shapes=True\n )\n assert np.array_equal([z.eval() for z in b_aet], b.shape)\n # TODO: This will work when/if we use a more sophisticated `is_same_graph`\n # implementation.\n # assert not any(\n # isinstance(node.op, Assert)\n # for node in graph_ops([x_aet, y_aet], b_aet)\n # )\n\n x = np.empty((1, 2, 3))\n y = np.array(1)\n b = np.broadcast(x, y)\n x_aet = aet.as_tensor_variable(x)\n y_aet = aet.as_tensor_variable(y)\n b_aet = broadcast_shape(x_aet, y_aet)\n assert b_aet[0].value == 1\n assert np.array_equal([z.eval() for z in b_aet], b.shape)\n assert not any(\n isinstance(node.op, Assert) for node in applys_between([x_aet, y_aet], b_aet)\n )\n b_aet = broadcast_shape(\n shape_tuple(x_aet), shape_tuple(y_aet), arrays_are_shapes=True\n )\n assert np.array_equal([z.eval() for z in b_aet], b.shape)\n\n x = np.empty((2, 1, 3))\n y = np.empty((2, 1, 1))\n b = np.broadcast(x, y)\n x_aet = aet.as_tensor_variable(x)\n y_aet = aet.as_tensor_variable(y)\n b_aet = broadcast_shape(x_aet, y_aet)\n assert b_aet[1].value == 1\n assert np.array_equal([z.eval() for z in b_aet], b.shape)\n # TODO: This will work when/if we use a more sophisticated `is_same_graph`\n # implementation.\n # assert not any(\n # isinstance(node.op, Assert)\n # for node in graph_ops([x_aet, y_aet], b_aet)\n # )\n b_aet = broadcast_shape(\n shape_tuple(x_aet), shape_tuple(y_aet), arrays_are_shapes=True\n )\n assert np.array_equal([z.eval() for z in b_aet], b.shape)\n\n x1_shp_aet = iscalar(\"x1\")\n x2_shp_aet = iscalar(\"x2\")\n y1_shp_aet = iscalar(\"y1\")\n x_shapes = (1, x1_shp_aet, x2_shp_aet)\n x_aet = aet.ones(x_shapes)\n y_shapes = (y1_shp_aet, 1, x2_shp_aet)\n y_aet = aet.ones(y_shapes)\n b_aet = broadcast_shape(x_aet, y_aet)\n # TODO: This will work when/if we use a more sophisticated `is_same_graph`\n # implementation.\n # assert not any(\n # isinstance(node.op, Assert)\n # for node in graph_ops([x_aet, y_aet], b_aet)\n # )\n res = aet.as_tensor(b_aet).eval(\n {\n x1_shp_aet: 10,\n x2_shp_aet: 4,\n y1_shp_aet: 2,\n }\n )\n assert np.array_equal(res, (2, 10, 4))\n\n y_shapes = (y1_shp_aet, 1, y1_shp_aet)\n y_aet = aet.ones(y_shapes)\n b_aet = broadcast_shape(x_aet, y_aet)\n assert isinstance(b_aet[-1].owner.op, Assert)\n\n\nclass TestBroadcastTo(utt.InferShapeTester):\n\n rng = np.random.RandomState(43)\n\n def setup_method(self):\n super().setup_method()\n self.op_class = BroadcastTo\n self.op = broadcast_to\n\n @config.change_flags(compute_test_value=\"raise\")\n def test_perform(self):\n a = scalar()\n a.tag.test_value = 5\n\n s_1 = iscalar(\"s_1\")\n s_1.tag.test_value = 4\n shape = (s_1, 1)\n\n bcast_res = broadcast_to(a, shape)\n\n assert bcast_res.broadcastable == (False, True)\n\n bcast_np = np.broadcast_to(5, (4, 1))\n bcast_aet = bcast_res.get_test_value()\n\n assert np.array_equal(bcast_aet, bcast_np)\n assert np.shares_memory(bcast_aet, a.get_test_value())\n\n @pytest.mark.parametrize(\n \"fn,input_dims\",\n [\n [lambda x: broadcast_to(x, (1,)), (1,)],\n [lambda x: broadcast_to(x, (6, 2, 5, 3)), (1,)],\n [lambda x: broadcast_to(x, (6, 2, 5, 3)), (5, 1)],\n [lambda x: broadcast_to(x, (6, 2, 1, 3)), (2, 1, 3)],\n ],\n )\n def test_gradient(self, fn, input_dims):\n utt.verify_grad(\n fn,\n [np.random.rand(*input_dims).astype(config.floatX)],\n n_tests=1,\n rng=self.rng,\n )\n\n def test_infer_shape(self):\n a = tensor(config.floatX, [False, True, False])\n shape = list(a.shape)\n out = self.op(a, shape)\n\n self._compile_and_check(\n [a] + shape,\n [out],\n [np.random.rand(2, 1, 3).astype(config.floatX), 2, 1, 3],\n self.op_class,\n )\n\n a = tensor(config.floatX, [False, True, False])\n shape = [iscalar() for i in range(4)]\n self._compile_and_check(\n [a] + shape,\n [self.op(a, shape)],\n [np.random.rand(2, 1, 3).astype(config.floatX), 6, 2, 5, 3],\n self.op_class,\n )\n\n def test_inplace(self):\n \"\"\"Make sure that in-place optimizations are *not* performed on the output of a ``BroadcastTo``.\"\"\"\n a = aet.zeros((5,))\n d = aet.vector(\"d\")\n c = aet.set_subtensor(a[np.r_[0, 1, 3]], d)\n b = broadcast_to(c, (5,))\n q = b[np.r_[0, 1, 3]]\n e = aet.set_subtensor(q, np.r_[0, 0, 0])\n\n opts = OptimizationQuery(include=[\"inplace\"])\n py_mode = Mode(\"py\", opts)\n e_fn = function([d], e, mode=py_mode)\n\n advincsub_node = e_fn.maker.fgraph.outputs[0].owner\n assert isinstance(advincsub_node.op, AdvancedIncSubtensor1)\n assert isinstance(advincsub_node.inputs[0].owner.op, BroadcastTo)\n\n assert advincsub_node.op.inplace is False\n\n\ndef test_broadcast_arrays():\n x, y = aet.dvector(), aet.dmatrix()\n x_bcast, y_bcast = broadcast_arrays(x, y)\n\n py_mode = Mode(\"py\", None)\n bcast_fn = function([x, y], [x_bcast, y_bcast], mode=py_mode)\n\n x_val = np.array([1.0], dtype=np.float64)\n y_val = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float64)\n x_bcast_val, y_bcast_val = bcast_fn(x_val, y_val)\n x_bcast_exp, y_bcast_exp = np.broadcast_arrays(x_val, y_val)\n\n assert np.array_equal(x_bcast_val, x_bcast_exp)\n assert np.array_equal(y_bcast_val, y_bcast_exp)\n"
] | [
[
"numpy.random.RandomState",
"numpy.random.PCG64",
"numpy.random.Philox"
],
[
"numpy.diag",
"numpy.product",
"numpy.asarray",
"numpy.squeeze",
"numpy.cumsum",
"numpy.broadcast",
"numpy.searchsorted",
"numpy.ravel_multi_index",
"numpy.random.randint",
"numpy.allclose",
"numpy.unique",
"numpy.arange",
"numpy.diff",
"numpy.repeat",
"numpy.unravel_index",
"numpy.zeros",
"numpy.bartlett",
"numpy.cumprod",
"numpy.random.rand",
"numpy.broadcast_arrays",
"numpy.argsort",
"numpy.array",
"numpy.random.RandomState",
"numpy.random.random",
"numpy.array_equal",
"numpy.compress",
"numpy.ones",
"numpy.broadcast_to",
"numpy.random.uniform",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
happyCoderJDFJJ/pyrfuniverse | [
"8ddb6e0d8f113015ba820a327388a528a8b215c7"
] | [
"pyrfuniverse/actions/single_transport.py"
] | [
"from pyrfuniverse.actions import BaseAction\nfrom pyrfuniverse.envs import ToborRobotiq85ManipulationEnv\nimport numpy as np\n\n\nclass SingleTransport(BaseAction):\n \"\"\"\n To transfer or convey an object from one place to another.\n \"\"\"\n def __init__(\n self,\n env: ToborRobotiq85ManipulationEnv,\n used_arm='left',\n ):\n super().__init__(env)\n self.used_arm = used_arm\n\n # For heuristic only\n self._heuristic = False\n self._next_action_position = np.array([0, 0, 0])\n self._next_action_orientation = None\n\n def heuristics(self, position, orientation=None):\n self._heuristic = True\n self._next_action_position = position\n self._next_action_orientation = orientation\n\n def set_wavepoints(self, wave_points: list):\n self._pre_movement_wavepoints = wave_points.copy()\n\n def _check_pre_conditions(self):\n return True\n\n def _predict_contact_pose(self):\n if self._heuristic:\n self._heuristic = False\n return self._next_action_position, self._next_action_orientation\n return np.array([0, 0, 0]), None\n\n def _pre_movement(self, position=np.array([0, 0, 0]), orientation=None):\n for wave_point in self._pre_movement_wavepoints:\n self.env.step(\n mode=self.used_arm,\n position=wave_point,\n orientation=orientation\n )\n\n def _gripper_movement(self):\n return\n\n def _post_movement(self):\n return\n\n def _effect(self):\n self.synchronize_status()\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
pilillo/nilmtk | [
"00bb1f948b6de1cc5c891102728c19b9bfc7c739"
] | [
"nilmtk/electric.py"
] | [
"import pandas as pd\nfrom .timeframe import TimeFrame\n\nclass Electric(object):\n \"\"\"Common implementations of methods shared by ElecMeter and MeterGroup.\n \"\"\"\n \n def when_on(self, **load_kwargs):\n \"\"\"Are the connected appliances appliance is on (True) or off (False)?\n\n Uses `self.min_on_power_threshold()` if `on_power_threshold` not provided.\n\n Parameters\n ----------\n on_power_threshold : number, optional\n **load_kwargs : key word arguments\n Passed to self.power_series()\n\n Returns\n -------\n generator of pd.Series\n index is the same as for chunk returned by `self.power_series()`\n values are booleans\n \"\"\"\n on_power_threshold = load_kwargs.pop('on_power_threshold', \n self.min_on_power_threshold())\n for chunk in self.power_series(**load_kwargs):\n yield chunk > on_power_threshold\n \n def min_on_power_threshold(self):\n \"\"\"Returns the minimum `on_power_threshold` across all appliances \n immediately downstream of this meter. If any appliance \n does not have an `on_power_threshold` then default to 10 watts.\"\"\"\n DEFAULT_ON_POWER_THRESHOLD = 10\n on_power_thresholds = [\n appl.metadata.get('on_power_threshold', DEFAULT_ON_POWER_THRESHOLD)\n for appl in self.appliances]\n if on_power_thresholds:\n return min(on_power_thresholds)\n else:\n return DEFAULT_ON_POWER_THRESHOLD\n\n def matches_appliances(self, key):\n \"\"\"\n Parameters\n ----------\n key : dict\n\n Returns\n -------\n True if all key:value pairs in `key` match any appliance\n in `self.appliances`.\n \"\"\"\n for appliance in self.appliances:\n if appliance.matches(key):\n return True\n return False\n\n def power_series_all_data(self, **kwargs):\n chunks = [] \n for series in self.power_series(**kwargs):\n chunks.append(series)\n return pd.concat(chunks)\n\n def plot(self, **loader_kwargs):\n all_data = self.power_series_all_data(**loader_kwargs)\n all_data.plot()\n \"\"\" TODO:\n Parameters\n ----------\n stacked : {'stacked', 'heatmap', 'lines', 'snakey'}\n\n pretty snakey:\n http://www.cl.cam.ac.uk/research/srg/netos/c-aware/joule/V4.00/\n \"\"\"\n\n # def activity_distribution(self):\n # * activity distribution:\n # - use ElecMeter.get_timeframe() to get start and end\n # - use pd.period_range to make daily period index\n # - load daily chunks\n # - downsample using Apply\n # - when_on\n # - answers = zeros(n_timeslices_per_chunk)\n # - add each chunk to answers\n # - answer is now the histogram!\n\n\n\ndef align_two_meters(master, slave, func='power_series'):\n \"\"\"Returns a generator of 2-column pd.DataFrames. The first column is from\n `master`, the second from `slave`.\n\n Takes the sample rate and good_periods of `master` and applies to `slave`.\n\n Parameters\n ----------\n master, slave : ElecMeter or MeterGroup instances\n \"\"\"\n sample_period = master.sample_period()\n period_alias = '{:d}S'.format(sample_period)\n sections = master.good_sections()\n master_generator = getattr(master, func)(sections=sections)\n for master_chunk in master_generator:\n if len(master_chunk) < 2:\n return\n chunk_timeframe = TimeFrame(master_chunk.index[0],\n master_chunk.index[-1])\n slave_generator = getattr(slave, func)(sections=[chunk_timeframe],\n chunksize=1E9)\n slave_chunk = next(slave_generator)\n\n # TODO: do this resampling in the pipeline?\n slave_chunk = slave_chunk.resample(period_alias)\n master_chunk = master_chunk.resample(period_alias)\n\n yield pd.DataFrame({'master': master_chunk, 'slave': slave_chunk})\n\n"
] | [
[
"pandas.concat",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
Jean1995/Bachelorarbeit | [
"42f7abd089a1cba29136a19445d90c5e49964998"
] | [
"pycode_ARCHIV/params.py"
] | [
"import numpy as np\nimport scipy.constants as const\nfrom table import (\n make_SI,\n write,\n)\nfrom uncertainties import ufloat\n\n#\nN1 = 3 #Parameter f+\nN2 = 3 #Parameter f0\n\nplot_difwq = 1 # entscheide, ob der differentielle WQ geplottet werden soll (zeitlicher Aufwand von ca. einer Minute)\n### Konstanten\n\nm_b = 5279.26 *10**(-3) #* 10**6 * const.electron_volt#/const.c**2\nm_b_s = 0.17 * 10**(-3)\n#^ Quelle: PDG '14\nm_d = 1869.61*10**(-3) #* 10**6 * const.electron_volt#/const.c**2\nm_d_s = 0.10 * 10**(-3)\n#^ Quelle: PDG '14\n\nm_p = 6329*10**(-3) #* 10**6 * const.electron_volt#/const.c**2 # Richtige Resonanzmasse hier einfügen. Ist bisher nur eine zufällige aus 1606.08030, S. 5\nm_p_s = 3 * 10**(-3)\nm_0 = 6716*10**(-3) #* 10**6 * const.electron_volt#/const.c**2\n#m_0 = 6329*10**(-3) #* 10**6 * const.electron_volt#/const.c**2\nm_0_s = 0\n#^ Quelle 1606.08030\n\nwrite('mp.tex', make_SI(ufloat(m_p,m_p_s), r'\\mega\\electronvolt', figures=1))\nwrite('m0.tex', make_SI(m_0, r'\\mega\\electronvolt', figures=3))\n\n\nm_e = 0.510998928 * 10 **(-3)\nm_e_s = 0.000000011 * 10**(-3)\nm_tau = 1776.82 * 10**(-3)\nm_tau_s = 0.16 * 10**(-3)\nm_mu = 105.6583715 * 10**(-3)\nm_mu_s = 0.0000035 * 10**(-3)\n\nm_bottom = 4180 * 10**(-3)\nm_bottom_s = 10 * 10**(-3)\nm_charm = 1275 * 10**(-3)\nm_charm_s = 25 * 10**(-3)\n#^ Quelle PDG (alles obrigen leptonen/quarks)\n\neta = 1.0066 #src https://arxiv.org/pdf/1606.08030.pdf\nG_f = 1.1663787*10**(-5) #* 1/(10**9 * const.electron_volt)**2 #* (const.hbar * const.c)**3\nV_cb = 40.49*10**(-3)\nV_cb_s = 0.97*10**(-3)\n#^ Quelle: 1703.06124\nwrite('V_cb.tex', make_SI(ufloat(V_cb,V_cb_s)*1000, r'','e-3', figures=2))\n\n\n### Gesamtdaten\n\nw_roh = np.array([1, 1.08, 1.16]) # Werte für w\nlattice_roh = np.array([1.1994, 1.0941, 1.0047, 0.9026, 0.8609, 0.8254]) # Latticewerte\ns_l = np.array([0.0095, 0.0104, 0.0123, 0.0072, 0.0077, 0.0094]) # Abweichungen Lattice\n\n#corr_mat = np.array([[1, 0, 0, 0, 0, 0],[0, 1, 0, 0, 0, 0],[0, 0, 1, 0, 0, 0],[0, 0, 0, 1, 0, 0],[0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1]])\ncorr_mat = np.array([[1, 0.9674, 0.8812, 0.8290, 0.8533, 0.8032],[0.9674, 1, 0.9523, 0.8241, 0.8992, 0.8856],[0.8812, 0.9523, 1, 0.7892, 0.8900, 0.9530],[0.8290, 0.8241, 0.7892, 1, 0.9650, 0.8682],[0.8533, 0.8992, 0.8900, 0.9650, 1, 0.9519], [0.8032, 0.8856, 0.9530, 0.8682, 0.9519, 1]]) #Korellationsmatrix\nV = np.zeros((len(lattice_roh), len(lattice_roh))) # Kovarianzmatrix\nfor i in range(len(lattice_roh)):\n for j in range(len(lattice_roh)):\n V[i,j] = corr_mat[i,j] * s_l[i] * s_l[j]\n\n\n\n### Weitere Daten\n\n\nR_exp = 0.406\nR_exp_s = 0.05\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
fhamborg/NewsMTSC | [
"5a8f88d7fbb921090e984cc378b02d75524c1025"
] | [
"NewsSentiment/models/singletarget/lcf2.py"
] | [
"# adapted from https://github.com/yangheng95/LC-ABSA/blob/c945a94e0f86116c5578245aa9ad36c46c7b9c4a/models/lc_apc/lcf_bert.py\n# according to\nimport copy\nfrom argparse import Namespace\nfrom typing import Dict\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom transformers.modeling_bert import BertPooler, BertSelfAttention\n\nfrom NewsSentiment.consts import *\nfrom NewsSentiment.dataset import FXDataset\nfrom NewsSentiment.layers.attention import FXBertSelfAttention\nfrom NewsSentiment.models.FXBaseModel import FXBaseModel\n\n\nclass GlobalContext(nn.Module):\n def __init__(self, global_context_seqs_per_doc):\n super(GlobalContext, self).__init__()\n self.global_context_seqs_per_doc = global_context_seqs_per_doc\n\n def forward(self, inputs):\n pass\n\n\nclass SelfAttention(nn.Module):\n def __init__(self, config, opt):\n super(SelfAttention, self).__init__()\n self.opt = opt\n self.config = config\n self.SA = FXBertSelfAttention(\n hidden_size=config.hidden_size,\n num_attention_heads=config.num_attention_heads,\n attention_probs_dropout_prob=0.1,\n )\n self.tanh = torch.nn.Tanh()\n\n def forward(self, inputs):\n zero_tensor = torch.tensor(\n np.zeros((inputs.size(0), 1, 1, self.opt.max_seq_len), dtype=np.float32),\n dtype=torch.float32,\n ).to(self.opt.device)\n SA_out = self.SA(inputs, zero_tensor)\n return self.tanh(SA_out[0])\n\n\nclass LCF_BERT2Dual(FXBaseModel):\n \"\"\"\n While lcf.py:LCF_BERT is the implementation as implemented in PyTorch-ABSA repository, this implementation here\n (LCF_BERT2Dual) is following the implementation as in the author's repository, which according to\n https://github.com/yangheng95/LC-ABSA/issues/10#issuecomment-670301603 has seen some more improvements compared to\n the version from PyTorch-ABSA\n \"\"\"\n\n @staticmethod\n def get_language_models():\n return (get_default_lm(),)\n\n @staticmethod\n def get_input_field_ids():\n return [\n (get_default_lm(), FIELD_TEXT_THEN_TARGET_IDS_WITH_SPECIAL_TOKENS),\n (\n get_default_lm(),\n FIELD_TEXT_THEN_TARGET_IDS_WITH_SPECIAL_TOKENS_SEGMENT_IDS,\n ),\n (get_default_lm(), FIELD_TEXT_IDS_WITH_SPECIAL_TOKENS),\n (get_default_lm(), FIELD_TARGET_IDS_WITH_SPECIAL_TOKENS),\n (get_default_lm(), FIELD_TEXT_IDS_WITH_SPECIAL_TOKENS_TARGET_MASK),\n ]\n\n def __init__(self, transformer_models: Dict, opt: Namespace):\n super(LCF_BERT2Dual, self).__init__()\n\n bert = transformer_models[get_default_lm()]\n\n self.bert4global = bert\n # note that we use a second bert here, which should slightly improve performance\n # cf. https://github.com/yangheng95/LC-ABSA/#tips\n # self.bert4local = copy.deepcopy(bert)\n # we can't do this on scc because even for batch size = only 16 we run out of\n # memory. because of that, we use the same bert for both local and global\n # (just as in lcf.py)\n self.bert4local = bert\n self.opt = opt\n self.dropout = nn.Dropout(self.opt.dropout)\n self.bert_SA = SelfAttention(bert.config, self.opt)\n self.linear2 = nn.Linear(bert.config.hidden_size * 2, bert.config.hidden_size)\n # self.linear3 = nn.Linear(bert.config.hidden_size * 3, bert.config.hidden_size)\n self.bert_pooler = BertPooler(bert.config)\n self.dense = nn.Linear(bert.config.hidden_size, self.opt.polarities_dim)\n\n def feature_dynamic_mask(self, text_local_indices, aspect_indices):\n texts = text_local_indices.cpu().numpy()\n asps = aspect_indices.cpu().numpy()\n mask_len = self.opt.SRD\n masked_text_raw_indices = np.ones(\n (\n text_local_indices.size(0),\n self.opt.max_seq_len,\n self.bert4local.config.hidden_size,\n ),\n dtype=np.float32,\n )\n for text_i, asp_i in zip(range(len(texts)), range(len(asps))):\n asp_len = np.count_nonzero(asps[asp_i]) - 2\n try:\n asp_begin = np.argwhere(texts[text_i] == asps[asp_i][1])[0][0]\n except:\n continue\n if asp_begin >= mask_len:\n mask_begin = asp_begin - mask_len\n else:\n mask_begin = 0\n for i in range(mask_begin):\n masked_text_raw_indices[text_i][i] = np.zeros(\n (self.bert4local.config.hidden_size), dtype=np.float\n )\n for j in range(asp_begin + asp_len + mask_len, self.opt.max_seq_len):\n masked_text_raw_indices[text_i][j] = np.zeros(\n (self.bert4local.config.hidden_size), dtype=np.float\n )\n masked_text_raw_indices = torch.from_numpy(masked_text_raw_indices)\n return masked_text_raw_indices.to(self.opt.device)\n\n def feature_dynamic_weighted(self, text_local_indices, aspect_indices):\n texts = text_local_indices.cpu().numpy()\n asps = aspect_indices.cpu().numpy()\n masked_text_raw_indices = np.ones(\n (\n text_local_indices.size(0),\n self.opt.max_seq_len,\n self.bert4local.config.hidden_size,\n ),\n dtype=np.float32,\n )\n for text_i, asp_i in zip(range(len(texts)), range(len(asps))):\n asp_len = np.count_nonzero(asps[asp_i]) - 2\n try:\n asp_begin = np.argwhere(texts[text_i] == asps[asp_i][1])[0][0]\n asp_avg_index = (asp_begin * 2 + asp_len) / 2\n except:\n continue\n distances = np.zeros(np.count_nonzero(texts[text_i]), dtype=np.float32)\n for i in range(1, np.count_nonzero(texts[text_i]) - 1):\n if abs(i - asp_avg_index) + asp_len / 2 > self.opt.SRD:\n distances[i] = 1 - (\n abs(i - asp_avg_index) + asp_len / 2 - self.opt.SRD\n ) / np.count_nonzero(texts[text_i])\n else:\n distances[i] = 1\n for i in range(len(distances)):\n masked_text_raw_indices[text_i][i] = (\n masked_text_raw_indices[text_i][i] * distances[i]\n )\n masked_text_raw_indices = torch.from_numpy(masked_text_raw_indices)\n return masked_text_raw_indices.to(self.opt.device)\n\n def forward(self, inputs):\n text_target_bert_indices = FXDataset.get_input_by_params(\n inputs, get_default_lm(), FIELD_TEXT_THEN_TARGET_IDS_WITH_SPECIAL_TOKENS,\n )\n text_target_bert_segments_ids = FXDataset.get_input_by_params(\n inputs,\n get_default_lm(),\n FIELD_TEXT_THEN_TARGET_IDS_WITH_SPECIAL_TOKENS_SEGMENT_IDS,\n )\n text_local_indices = FXDataset.get_input_by_params(\n inputs, get_default_lm(), FIELD_TEXT_IDS_WITH_SPECIAL_TOKENS\n )\n aspect_indices = FXDataset.get_input_by_params(\n inputs, get_default_lm(), FIELD_TARGET_IDS_WITH_SPECIAL_TOKENS\n )\n\n # bert\n global_context_features = self.invoke_language_model(\n self.bert4global,\n input_ids=text_target_bert_indices,\n token_type_ids=text_target_bert_segments_ids,\n )\n local_context_features = self.invoke_language_model(\n self.bert4local, text_local_indices\n )\n\n # mask\n if self.opt.local_context_focus == \"cdm\":\n lcf_matrix = self.feature_dynamic_mask(text_local_indices, aspect_indices)\n elif self.opt.local_context_focus == \"cdw\":\n lcf_matrix = self.feature_dynamic_weighted(\n text_local_indices, aspect_indices\n )\n\n # LCF layer\n lcf_features = torch.mul(local_context_features, lcf_matrix)\n lcf_features = self.bert_SA(lcf_features)\n\n cat_features = torch.cat((lcf_features, global_context_features), dim=-1)\n cat_features = self.linear2(cat_features)\n cat_features = self.dropout(cat_features)\n\n pooled_out = self.bert_pooler(cat_features)\n dense_out = self.dense(pooled_out)\n\n return dense_out\n"
] | [
[
"torch.nn.Dropout",
"torch.cat",
"torch.from_numpy",
"torch.nn.Tanh",
"numpy.argwhere",
"torch.nn.Linear",
"torch.mul",
"numpy.count_nonzero",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
hoburg/pyxfoil | [
"aa089c3bbd0c0911400b1d525d544b796dc1253d"
] | [
"woodys_old_python_code/genpolars.py"
] | [
"#! /usr/bin/env python\n\nimport pyxfoil as px\nimport numpy as np\n\nxf = px.session(logfile='sweeptest')\nRes = np.logspace(5,7,21)\n#Res = np.logspace(4.5,5,5)\nnacacodes = range(8,17,1)\nadders = [0, 2400]\nxf.naca('0010')\nxf.set_panels(200)\nfor a in adders:\n for nacacode in nacacodes:\n xf.naca('%04d' % (nacacode + a))\n for re in Res:\n xf.set_re(re)\n xf.generate_polar()\nxf.quit()\n\n\n#s = px.session()\n#s.naca(2416)\n#s.set_panels(200)\n#s.set_re(32000)\n#s.generate_polar()\n#s.quit()\n\n#import numpy as np\n#\n#xf = px.session(blog=True)\n#xf.naca(2412) #needed to set panels in next line\n#xf.set_panels(200)\n#Res = [32000, 56000]\n##Res = np.logspace(4.5,7,21)\n#nacacodes = range(8,17,1)\n##nacacodes = [11]\n##nacacodes = [x + 2400 for x in nacacodes]\n##nacacodes = [15]\n#adders = [0, 1400, 2400, 3400, 4400]\n#for a in adders:\n# for nacacode in nacacodes:\n# xf.naca(nacacode + a)\n# for re in Res:\n# xf.set_re(re)\n# xf.generate_polar(alfa_step=0.2)\n#xf.quit()\n\n\n"
] | [
[
"numpy.logspace"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
courtois-neuromod/movie_decoding_sa | [
"ca937cb676bf5828841ed332556257df3f91702a",
"ca937cb676bf5828841ed332556257df3f91702a"
] | [
"Temporarily/Data_PCA/Bootstrap_Ridge.py",
"Temporarily/Subject3/Important/Sub3_T2.py"
] | [
"import numpy as np\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\n\ny= np.load('fMRI_PCA.npy', allow_pickle=True)\nX= np.load('Movie_PCA_1200.npy', allow_pickle=True)\n\nx_train,x_test, y_train, y_test = train_test_split(X, y, test_size=0.1)\n\nprint(x_train.shape, x_test.shape, y_train.shape, y_test.shape)\n\n\n########################################################################\n\nfrom ridge import bootstrap_ridge\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\n\nalphas = np.logspace(0, 3, 10) # Equally log-spaced alphas between 10 and 1000\n\nwt, corr, alphas, bscorrs, valinds = bootstrap_ridge(x_train, y_train, \n x_test, y_test,\n alphas, nboots=1, chunklen=40, nchunks=20,\n singcutoff=1e-10, single_alpha=True)\n\n\n#################################################################################\n\nprint(wt.shape)\n\npred_test = x_test.dot(wt)\n\nimport npp\n\nRidge_correlations = npp.mcorr(y_test, pred_test)\n\nprint(Ridge_correlations.shape)\n\nplt.hist(Ridge_correlations, 50)\nplt.xlim(-1, 1)\nplt.xlabel(\"PCA_Ridge Correlation_1200\")\nplt.ylabel(\"Num. Parcels\");\n\nplt.savefig('PCA_Ridge_Correlation_1200.png')\nnp.save('PCA_Ridge_correlations_1200.npy', Ridge_correlations)\n",
"import numpy as np\nimport npp\nimport matplotlib.pyplot as plt\nfrom nilearn.plotting import view_img \nfrom nilearn.input_data import NiftiLabelsMasker\n\nfMRI_Data1= np.load('fMRI_label1.npy', allow_pickle=True)\nfMRI_Data2= np.load('fMRI_label2.npy', allow_pickle=True)\nfMRI_Data3= np.load('fMRI_label3.npy', allow_pickle=True)\nfMRI_Data4= np.load('fMRI_label4.npy', allow_pickle=True)\nfMRI_Data5= np.load('fMRI_label5.npy', allow_pickle=True)\nfMRI_Data6= np.load('fMRI_label6.npy', allow_pickle=True)\n\nMovie_Data1= np.load('Xx1.npy', allow_pickle=True)\nMovie_Data2= np.load('Xx2.npy', allow_pickle=True)\nMovie_Data3= np.load('Xx3.npy', allow_pickle=True)\nMovie_Data4= np.load('Xx4.npy', allow_pickle=True)\nMovie_Data5= np.load('Xx5.npy', allow_pickle=True)\nMovie_Data6= np.load('Xx6.npy', allow_pickle=True)\n\nXx_T=np.vstack((Movie_Data1,Movie_Data2,Movie_Data3,Movie_Data4,Movie_Data5,Movie_Data6))\n\nprint('Xx_T.shape', Xx_T.shape)\n\n#################################################\n\nLabel_T=np.vstack((fMRI_Data1,fMRI_Data2,fMRI_Data3,fMRI_Data4,fMRI_Data5,fMRI_Data6))\nprint('Label_T.shape', Label_T.shape)\n\n###############################################################################################\n\n\nMovie_PCA=np.load('x_test.npy', allow_pickle=True)\ny_test=np.load('y_test.npy', allow_pickle=True)\n\nMovie_Data= Movie_PCA\n\nT1=[]\nT2=[]\nT3=[]\nT4=[]\nT5=[]\nT6=[]\nT7=[]\nT8=[]\n\n\n\nfor i in range(len(Movie_Data)):\n\n if i % 6==0:\n T1.append(Movie_Data[i,:])\n\n if i % 6==1:\n T2.append(Movie_Data[i,:])\n\n if i % 6==2:\n T3.append(Movie_Data[i,:])\n\n if i % 6==3:\n T4.append(Movie_Data[i,:] )\n\n\n if i % 6==4:\n T5.append(Movie_Data[i,:])\n\n if i % 6==5:\n T6.append(Movie_Data[i,:])\n\nT1_D= np.array(T1[0:733])\nT2_D= np.array(T2[0:733])\nT3_D= np.array(T3)\nT4_D= np.array(T4)\nT5_D= np.array(T5)\nT6_D= np.array(T6)\n\nprint(T1_D.shape, T2_D.shape, T3_D.shape,T4_D.shape,T5_D.shape, T6_D.shape)\n\nXx_test=np.hstack((T1_D,T2_D,T3_D,T4_D,T5_D,T6_D))\n\n##########################################################################\n\nfMRI_Data= y_test\n\nfMRI_label=[]\n\n###\n\nfor i in range(len(fMRI_Data)):\n\n\n if i % 6==5:\n fMRI_label.append(fMRI_Data[i,:])\n\n\nlabel_test= np.array(fMRI_label)\n\n#############################################################################\n\nprint('Xx_test.shape and label_test.shape', Xx_test.shape, label_test.shape)\n\nfrom ridge import bootstrap_ridge\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\n\n\nalphas = np.logspace(0, 3, 10) # Equally log-spaced alphas between 10 and 1000\n\nwt, corr, alphas, bscorrs, valinds = bootstrap_ridge(Xx_T[0:5000], Label_T[0:5000],\n Xx_test, label_test,\n alphas, nboots=1, chunklen=40, nchunks=20,\n singcutoff=1e-10, single_alpha=True)\n\n\n#np.save('wt.npy', wt)\n\n#print('wt.shape', wt.shape)\n\n\n###########################################################################\n\n\n\npred_test = Xx_test.dot(wt)\n\n#np.save('pred_test.npy', pred_test)\n#np.save('label_test.npy',label_test )\n#print(pred_test.shape, label_test.shape)\n\nRidge_correlations = npp.mcorr(label_test, pred_test)\n\nprint('Ridge_correlations.shape', Ridge_correlations.shape)\n\nnp.save('Ridge_correlations.npy', Ridge_correlations)\n\n\nplt.hist(Ridge_correlations, 50)\nplt.xlim(-1, 1)\nplt.xlabel(\"PCA_Ridge Correlation_1200\")\nplt.ylabel(\"Num. Parcels\")\nplt.savefig('Sub3.png')\n"
] | [
[
"numpy.logspace",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.savefig",
"numpy.save",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.xlabel",
"numpy.load",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel"
],
[
"numpy.hstack",
"numpy.logspace",
"numpy.save",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.xlabel",
"numpy.load",
"numpy.array",
"matplotlib.pyplot.hist",
"numpy.vstack",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kwyoke/cogdl | [
"df919b4fc7db40f8b035665edbcc7ed59f9d448e",
"df919b4fc7db40f8b035665edbcc7ed59f9d448e"
] | [
"cogdl/tasks/link_prediction.py",
"cogdl/datasets/pyg_strategies_data.py"
] | [
"import random\n\nimport os\nimport logging\nimport json\nimport copy\nimport networkx as nx\nimport numpy as np\nimport torch\nfrom torch import mode\nfrom torch.optim import Adam, Adagrad, SGD\nfrom torch.optim.lr_scheduler import StepLR\nfrom torch.utils.data import DataLoader, Dataset\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn import CrossEntropyLoss, MSELoss, NLLLoss, BCELoss, KLDivLoss\nfrom torch.utils.data import WeightedRandomSampler\nfrom gensim.models.keyedvectors import Vocab\nfrom six import iteritems\nfrom sklearn.metrics import auc, f1_score, precision_recall_curve, roc_auc_score\nfrom tqdm import tqdm\n\nfrom cogdl import options\nfrom cogdl.datasets import build_dataset\nfrom cogdl.models import build_model\n\nfrom . import BaseTask, register_task\n\nfrom cogdl.datasets.kg_data import KnowledgeGraphDataset, BidirectionalOneShotIterator, TrainDataset\n\ndef save_model(model, optimizer, save_variable_list, args):\n '''\n Save the parameters of the model and the optimizer,\n as well as some other variables such as step and learning_rate\n '''\n \n argparse_dict = vars(args)\n with open(os.path.join(args.save_path, 'config.json'), 'w') as fjson:\n json.dump(argparse_dict, fjson)\n\n torch.save({\n **save_variable_list,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict()},\n os.path.join(args.save_path, 'checkpoint')\n )\n \n entity_embedding = model.entity_embedding.detach().cpu().numpy()\n np.save(\n os.path.join(args.save_path, 'entity_embedding'), \n entity_embedding\n )\n \n relation_embedding = model.relation_embedding.detach().cpu().numpy()\n np.save(\n os.path.join(args.save_path, 'relation_embedding'), \n relation_embedding\n )\n\ndef set_logger(args):\n '''\n Write logs to checkpoint and console\n '''\n\n if args.do_train:\n log_file = os.path.join(args.save_path or args.init_checkpoint, 'train.log')\n else:\n log_file = os.path.join(args.save_path or args.init_checkpoint, 'test.log')\n\n logging.basicConfig(\n format='%(asctime)s %(levelname)-8s %(message)s',\n level=logging.INFO,\n datefmt='%Y-%m-%d %H:%M:%S',\n filename=log_file,\n filemode='w'\n )\n console = logging.StreamHandler()\n console.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')\n console.setFormatter(formatter)\n logging.getLogger('').addHandler(console)\n\ndef log_metrics(mode, step, metrics):\n '''\n Print the evaluation logs\n '''\n for metric in metrics:\n logging.info('%s %s at step %d: %f' % (mode, metric, step, metrics[metric]))\n\n\ndef divide_data(input_list, division_rate):\n local_division = len(input_list) * np.cumsum(np.array(division_rate))\n random.shuffle(input_list)\n return [\n input_list[\n int(round(local_division[i - 1]))\n if i > 0\n else 0 : int(round(local_division[i]))\n ]\n for i in range(len(local_division))\n ]\n\n\ndef randomly_choose_false_edges(nodes, true_edges, num):\n true_edges_set = set(true_edges)\n tmp_list = list()\n all_flag = False\n for _ in range(num):\n trial = 0\n while True:\n x = nodes[random.randint(0, len(nodes) - 1)]\n y = nodes[random.randint(0, len(nodes) - 1)]\n trial += 1\n if trial >= 1000:\n all_flag = True\n break\n if x != y and (x, y) not in true_edges_set and (y, x) not in true_edges_set:\n tmp_list.append((x, y))\n break\n if all_flag:\n break\n return tmp_list\n\n\ndef gen_node_pairs(train_data, test_data, negative_ratio=5):\n G = nx.Graph()\n G.add_edges_from(train_data)\n\n training_nodes = set(list(G.nodes()))\n test_true_data = []\n for u, v in test_data:\n if u in training_nodes and v in training_nodes:\n test_true_data.append((u, v))\n test_false_data = randomly_choose_false_edges(\n list(training_nodes), train_data, len(test_data) * negative_ratio\n )\n return (test_true_data, test_false_data)\n\n\ndef get_score(embs, node1, node2):\n vector1 = embs[int(node1)]\n vector2 = embs[int(node2)]\n return np.dot(vector1, vector2) / (\n np.linalg.norm(vector1) * np.linalg.norm(vector2)\n )\n\n\ndef evaluate(embs, true_edges, false_edges):\n true_list = list()\n prediction_list = list()\n for edge in true_edges:\n true_list.append(1)\n prediction_list.append(get_score(embs, edge[0], edge[1]))\n\n for edge in false_edges:\n true_list.append(0)\n prediction_list.append(get_score(embs, edge[0], edge[1]))\n\n sorted_pred = prediction_list[:]\n sorted_pred.sort()\n threshold = sorted_pred[-len(true_edges)]\n\n y_pred = np.zeros(len(prediction_list), dtype=np.int32)\n for i in range(len(prediction_list)):\n if prediction_list[i] >= threshold:\n y_pred[i] = 1\n\n y_true = np.array(true_list)\n y_scores = np.array(prediction_list)\n ps, rs, _ = precision_recall_curve(y_true, y_scores)\n return roc_auc_score(y_true, y_scores), f1_score(y_true, y_pred), auc(rs, ps)\n\n\ndef select_task(model_name=None, model=None):\n assert model_name is not None or model is not None\n if model_name is not None:\n if model_name in [\"rgcn\", \"compgcn\"]:\n return \"KGLinkPrediction\"\n if model_name in [\"distmult\", \"transe\", \"rotate\", \"complex\"]:\n return \"TripleLinkPrediction\"\n else:\n return \"HomoLinkPrediction\"\n else:\n from cogdl.models.nn import rgcn, compgcn\n from cogdl.models.emb import distmult, rotate, transe, complex\n if type(model) in [rgcn.LinkPredictRGCN, compgcn.LinkPredictCompGCN]:\n return \"KGLinkPrediction\"\n if type(model) in [distmult.DistMult, rotate.RotatE, transe.TransE, complex.ComplEx]:\n return \"TripleLinkPrediction\"\n else:\n return \"HomoLinkPrediction\"\n\nclass HomoLinkPrediction(nn.Module):\n def __init__(self, args, dataset=None, model=None):\n super(HomoLinkPrediction, self).__init__()\n dataset = build_dataset(args) if dataset is None else dataset\n data = dataset[0]\n self.data = data\n if hasattr(dataset, \"num_features\"):\n args.num_features = dataset.num_features\n model = build_model(args) if model is None else model\n self.model = model\n self.patience = args.patience\n self.max_epoch = args.max_epoch\n\n edge_list = self.data.edge_index.numpy()\n edge_list = list(zip(edge_list[0], edge_list[1]))\n edge_set = set()\n for edge in edge_list:\n if (edge[0], edge[1]) not in edge_set and (edge[1], edge[0]) not in edge_set:\n edge_set.add(edge)\n edge_list = list(edge_set)\n self.train_data, self.test_data = divide_data(\n edge_list, [0.90, 0.10]\n )\n\n self.test_data = gen_node_pairs(\n self.train_data, self.test_data, args.negative_ratio\n )\n\n def train(self):\n G = nx.Graph()\n G.add_edges_from(self.train_data)\n embeddings = self.model.train(G)\n\n embs = dict()\n for vid, node in enumerate(G.nodes()):\n embs[node] = embeddings[vid]\n\n roc_auc, f1_score, pr_auc = evaluate(embs, self.test_data[0], self.test_data[1])\n print(\n f\"Test ROC-AUC = {roc_auc:.4f}, F1 = {f1_score:.4f}, PR-AUC = {pr_auc:.4f}\"\n )\n return dict(ROC_AUC=roc_auc, PR_AUC=pr_auc, F1=f1_score)\n\nclass TripleLinkPrediction(nn.Module):\n \"\"\"\n Training process borrowed from `KnowledgeGraphEmbedding<https://github.com/DeepGraphLearning/KnowledgeGraphEmbedding>`\n \"\"\"\n def __init__(self, args, dataset=None, model=None):\n super(TripleLinkPrediction, self).__init__()\n self.dataset = build_dataset(args) if dataset is None else dataset\n args.nentity = self.dataset.num_entities\n args.nrelation = self.dataset.num_relations\n self.model = build_model(args) if model is None else model\n self.args = args\n set_logger(args)\n logging.info('Model: %s' % args.model)\n logging.info('#entity: %d' % args.nentity)\n logging.info('#relation: %d' % args.nrelation)\n\n def train(self):\n\n train_triples = self.dataset.triples[self.dataset.train_start_idx:self.dataset.valid_start_idx]\n logging.info('#train: %d' % len(train_triples))\n valid_triples = self.dataset.triples[self.dataset.valid_start_idx:self.dataset.test_start_idx]\n logging.info('#valid: %d' % len(valid_triples))\n test_triples = self.dataset.triples[self.dataset.test_start_idx:]\n logging.info('#test: %d' % len(test_triples))\n\n all_true_triples = train_triples + valid_triples + test_triples\n nentity, nrelation = self.args.nentity, self.args.nrelation\n\n if torch.cuda.is_available():\n self.args.cuda = True\n self.model = self.model.cuda()\n\n if self.args.do_train:\n # Set training dataloader iterator\n train_dataloader_head = DataLoader(\n TrainDataset(train_triples, nentity, nrelation, self.args.negative_sample_size, 'head-batch'), \n batch_size=self.args.batch_size,\n shuffle=True, \n collate_fn=TrainDataset.collate_fn\n )\n \n train_dataloader_tail = DataLoader(\n TrainDataset(train_triples, nentity, nrelation, self.args.negative_sample_size, 'tail-batch'), \n batch_size=self.args.batch_size,\n shuffle=True, \n collate_fn=TrainDataset.collate_fn\n )\n \n train_iterator = BidirectionalOneShotIterator(train_dataloader_head, train_dataloader_tail)\n \n # Set training configuration\n current_learning_rate = self.args.learning_rate\n optimizer = torch.optim.Adam(\n filter(lambda p: p.requires_grad, self.model.parameters()), \n lr=current_learning_rate\n )\n if self.args.warm_up_steps:\n warm_up_steps = self.args.warm_up_steps\n else:\n warm_up_steps = self.args.max_steps // 2\n\n if self.args.init_checkpoint:\n # Restore model from checkpoint directory\n logging.info('Loading checkpoint %s...' % self.args.init_checkpoint)\n checkpoint = torch.load(os.path.join(self.args.init_checkpoint, 'checkpoint'))\n init_step = checkpoint['step']\n self.model.load_state_dict(checkpoint['model_state_dict'])\n if self.args.do_train:\n current_learning_rate = checkpoint['current_learning_rate']\n warm_up_steps = checkpoint['warm_up_steps']\n optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n else:\n logging.info('Ramdomly Initializing %s Model...' % self.args.model)\n init_step = 0\n \n step = init_step\n \n logging.info('Start Training...')\n logging.info('init_step = %d' % init_step)\n logging.info('batch_size = %d' % self.args.batch_size)\n logging.info('negative_adversarial_sampling = %d' % self.args.negative_adversarial_sampling)\n logging.info('hidden_dim = %d' % self.args.embedding_size)\n logging.info('gamma = %f' % self.args.gamma)\n logging.info('negative_adversarial_sampling = %s' % str(self.args.negative_adversarial_sampling))\n if self.args.negative_adversarial_sampling:\n logging.info('adversarial_temperature = %f' % self.args.adversarial_temperature)\n \n # Set valid dataloader as it would be evaluated during training\n \n if self.args.do_train:\n logging.info('learning_rate = %d' % current_learning_rate)\n\n training_logs = []\n \n #Training Loop\n for step in range(init_step, self.args.max_steps):\n \n log = self.model.train_step(self.model, optimizer, train_iterator, self.args)\n \n training_logs.append(log)\n \n if step >= warm_up_steps:\n current_learning_rate = current_learning_rate / 10\n logging.info('Change learning_rate to %f at step %d' % (current_learning_rate, step))\n optimizer = torch.optim.Adam(\n filter(lambda p: p.requires_grad, self.model.parameters()), \n lr=current_learning_rate\n )\n warm_up_steps = warm_up_steps * 3\n \n if step % self.args.save_checkpoint_steps == 0:\n save_variable_list = {\n 'step': step, \n 'current_learning_rate': current_learning_rate,\n 'warm_up_steps': warm_up_steps\n }\n save_model(self.model, optimizer, save_variable_list, self.args)\n \n if step % self.args.log_steps == 0:\n metrics = {}\n for metric in training_logs[0].keys():\n metrics[metric] = sum([log[metric] for log in training_logs])/len(training_logs)\n log_metrics('Training average', step, metrics)\n training_logs = []\n \n if self.args.do_valid and step % self.args.valid_steps == 0:\n logging.info('Evaluating on Valid Dataset...')\n metrics = self.model.test_step(self.model, valid_triples, all_true_triples, self.args)\n log_metrics('Valid', step, metrics)\n \n save_variable_list = {\n 'step': step, \n 'current_learning_rate': current_learning_rate,\n 'warm_up_steps': warm_up_steps\n }\n save_model(self.model, optimizer, save_variable_list, self.args)\n \n if self.args.do_valid:\n logging.info('Evaluating on Valid Dataset...')\n metrics = self.model.test_step(self.model, valid_triples, all_true_triples, self.args)\n log_metrics('Valid', step, metrics)\n\n logging.info('Evaluating on Test Dataset...')\n return self.model.test_step(self.model, test_triples, all_true_triples, self.args)\n\nclass KGLinkPrediction(nn.Module):\n def __init__(self, args, dataset=None, model=None):\n super(KGLinkPrediction, self).__init__()\n self.device = torch.device('cpu' if args.cpu else 'cuda')\n self.evaluate_interval = args.evaluate_interval\n dataset = build_dataset(args) if dataset is None else dataset\n self.data = dataset[0]\n self.data.apply(lambda x: x.to(self.device))\n args.num_entities = len(torch.unique(self.data.edge_index))\n args.num_rels = len(torch.unique(self.data.edge_attr))\n model = build_model(args) if model is None else model\n self.model = model.to(self.device)\n self.max_epoch = args.max_epoch\n self.patience = min(args.patience, 20)\n self.grad_norm = 1.0\n self.optimizer = torch.optim.AdamW(\n self.model.parameters(), lr=args.lr,\n weight_decay=args.weight_decay\n )\n\n def train(self):\n epoch_iter = tqdm(range(self.max_epoch))\n patience = 0\n best_mrr = 0\n best_model = None\n val_mrr = 0\n\n for epoch in epoch_iter:\n loss_n = self._train_step()\n if (epoch + 1) % self.evaluate_interval == 0:\n torch.cuda.empty_cache()\n val_mrr, _ = self._test_step(\"val\")\n if val_mrr > best_mrr:\n best_mrr = val_mrr\n best_model = copy.deepcopy(self.model)\n patience = 0\n else:\n patience += 1\n if patience == self.patience:\n self.model = best_model\n epoch_iter.close()\n break\n epoch_iter.set_description(\n f\"Epoch: {epoch:03d}, TrainLoss: {loss_n: .4f}, Val MRR: {val_mrr: .4f}, Best MRR: {best_mrr: .4f}\"\n )\n self.model = best_model\n test_mrr, test_hits = self._test_step(\"test\")\n print(\n f\"Test MRR:{test_mrr}, Hits@1/3/10: {test_hits}\"\n )\n return dict(MRR=test_mrr, HITS1=test_hits[0], HITS3=test_hits[1], HITS10=test_hits[2])\n\n def _train_step(self, split=\"train\"):\n self.model.train()\n self.optimizer.zero_grad()\n loss_n = self.model.loss(self.data)\n loss_n.backward()\n torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.grad_norm)\n self.optimizer.step()\n return loss_n.item()\n \n def _test_step(self, split=\"val\"):\n self.model.eval()\n if split == \"train\":\n mask = self.data.train_mask\n elif split == \"val\":\n mask = self.data.val_mask\n else:\n mask = self.data.test_mask\n edge_index = self.data.edge_index[:, mask]\n edge_attr = self.data.edge_attr[mask]\n mrr, hits = self.model.predict(edge_index, edge_attr)\n return mrr, hits\n\n@register_task(\"link_prediction\")\nclass LinkPrediction(BaseTask):\n @staticmethod\n def add_args(parser):\n # fmt: off\n parser.add_argument(\"--evaluate-interval\", type=int, default=30)\n parser.add_argument(\"--max-epoch\", type=int, default=3000)\n parser.add_argument(\"--patience\", type=int, default=10)\n parser.add_argument(\"--lr\", type=float, default=0.001)\n parser.add_argument(\"--weight-decay\", type=float, default=0)\n \n parser.add_argument(\"--hidden-size\", type=int, default=200) # KG\n parser.add_argument(\"--negative-ratio\", type=int, default=5)\n \n # some arguments for triple-based knowledge graph embedding\n parser.add_argument('--cuda', action='store_true', help='use GPU')\n parser.add_argument('--do_train', action='store_true')\n parser.add_argument('--do_valid', action='store_true')\n parser.add_argument('-de', '--double_entity_embedding', action='store_true')\n parser.add_argument('-dr', '--double_relation_embedding', action='store_true')\n \n parser.add_argument('-n', '--negative_sample_size', default=128, type=int)\n parser.add_argument('-d', '--embedding_size', default=500, type=int)\n parser.add_argument('-init', '--init_checkpoint', default=None, type=str)\n parser.add_argument('-g', '--gamma', default=12.0, type=float)\n parser.add_argument('-adv', '--negative_adversarial_sampling', action='store_true')\n parser.add_argument('-a', '--adversarial_temperature', default=1.0, type=float)\n parser.add_argument('-b', '--batch_size', default=1024, type=int)\n parser.add_argument('-r', '--regularization', default=0.0, type=float)\n parser.add_argument('--test_batch_size', default=4, type=int, help='valid/test batch size')\n parser.add_argument('--uni_weight', action='store_true', \n help='Otherwise use subsampling weighting like in word2vec')\n \n parser.add_argument('-lr', '--learning_rate', default=0.0001, type=float)\n parser.add_argument('-save', '--save_path', default=None, type=str)\n parser.add_argument('--max_steps', default=100000, type=int)\n parser.add_argument('--warm_up_steps', default=None, type=int)\n \n parser.add_argument('--save_checkpoint_steps', default=1000, type=int)\n parser.add_argument('--valid_steps', default=10000, type=int)\n parser.add_argument('--log_steps', default=100, type=int, help='train log every xx steps')\n parser.add_argument('--test_log_steps', default=1000, type=int, help='valid/test log every xx steps')\n # fmt: on\n\n def __init__(self, args, dataset=None, model=None):\n super(LinkPrediction, self).__init__(args)\n\n task_type = select_task(args.model, model)\n if task_type == \"HomoLinkPrediction\":\n self.task = HomoLinkPrediction(args, dataset, model)\n elif task_type == \"KGLinkPrediction\":\n self.task = KGLinkPrediction(args, dataset, model)\n elif task_type == \"TripleLinkPrediction\":\n self.task = TripleLinkPrediction(args, dataset, model)\n \n def train(self):\n return self.task.train()\n",
"\"\"\"\n This file is borrowed from https://github.com/snap-stanford/pretrain-gnns/\n\"\"\"\nfrom cogdl.datasets import register_dataset\nimport random\nimport zipfile\nimport networkx as nx\nimport numpy as np\n\nimport torch\nfrom torch_geometric.data import InMemoryDataset, Data, Batch\nfrom cogdl.data import download_url\nimport os.path as osp\nfrom itertools import repeat, product, chain\n\n# ================\n# Dataset utils\n# ================\n\ndef nx_to_graph_data_obj(g, center_id, allowable_features_downstream=None,\n allowable_features_pretrain=None,\n node_id_to_go_labels=None):\n n_nodes = g.number_of_nodes()\n n_edges = g.number_of_edges()\n\n # nodes\n nx_node_ids = [n_i for n_i in g.nodes()] # contains list of nx node ids\n # in a particular ordering. Will be used as a mapping to convert\n # between nx node ids and data obj node indices\n\n x = torch.tensor(np.ones(n_nodes).reshape(-1, 1), dtype=torch.float)\n # we don't have any node labels, so set to dummy 1. dim n_nodes x 1\n\n center_node_idx = nx_node_ids.index(center_id)\n center_node_idx = torch.tensor([center_node_idx], dtype=torch.long)\n\n # edges\n edges_list = []\n edge_features_list = []\n for node_1, node_2, attr_dict in g.edges(data=True):\n edge_feature = [attr_dict['w1'], attr_dict['w2'], attr_dict['w3'],\n attr_dict['w4'], attr_dict['w5'], attr_dict['w6'],\n attr_dict['w7'], 0, 0] # last 2 indicate self-loop\n # and masking\n edge_feature = np.array(edge_feature, dtype=int)\n # convert nx node ids to data obj node index\n i = nx_node_ids.index(node_1)\n j = nx_node_ids.index(node_2)\n edges_list.append((i, j))\n edge_features_list.append(edge_feature)\n edges_list.append((j, i))\n edge_features_list.append(edge_feature)\n\n # data.edge_index: Graph connectivity in COO format with shape [2, num_edges]\n edge_index = torch.tensor(np.array(edges_list).T, dtype=torch.long)\n\n # data.edge_attr: Edge feature matrix with shape [num_edges, num_edge_features]\n edge_attr = torch.tensor(np.array(edge_features_list),\n dtype=torch.float)\n\n try:\n species_id = int(nx_node_ids[0].split('.')[0]) # nx node id is of the form:\n # species_id.protein_id\n species_id = torch.tensor([species_id], dtype=torch.long)\n except: # occurs when nx node id has no species id info. For the extract\n # substructure context pair transform, where we convert a data obj to\n # a nx graph obj (which does not have original node id info)\n species_id = torch.tensor([0], dtype=torch.long) # dummy species\n # id is 0\n\n # construct data obj\n data = Data(x=x, edge_index=edge_index, edge_attr=edge_attr)\n data.species_id = species_id\n data.center_node_idx = center_node_idx\n\n if node_id_to_go_labels: # supervised case with go node labels\n # Construct a dim n_pretrain_go_classes tensor and a\n # n_downstream_go_classes tensor for the center node. 0 is no data\n # or negative, 1 is positive.\n downstream_go_node_feature = [0] * len(allowable_features_downstream)\n pretrain_go_node_feature = [0] * len(allowable_features_pretrain)\n if center_id in node_id_to_go_labels:\n go_labels = node_id_to_go_labels[center_id]\n # get indices of allowable_features_downstream that match with elements\n # in go_labels\n _, node_feature_indices, _ = np.intersect1d(\n allowable_features_downstream, go_labels, return_indices=True)\n for idx in node_feature_indices:\n downstream_go_node_feature[idx] = 1\n # get indices of allowable_features_pretrain that match with\n # elements in go_labels\n _, node_feature_indices, _ = np.intersect1d(\n allowable_features_pretrain, go_labels, return_indices=True)\n for idx in node_feature_indices:\n pretrain_go_node_feature[idx] = 1\n data.go_target_downstream = torch.tensor(np.array(downstream_go_node_feature),\n dtype=torch.long)\n data.go_target_pretrain = torch.tensor(np.array(pretrain_go_node_feature),\n dtype=torch.long)\n return data\n\n\ndef graph_data_obj_to_nx(data):\n G = nx.Graph()\n\n # edges\n edge_index = data.edge_index.cpu().numpy()\n edge_attr = data.edge_attr.cpu().numpy()\n n_edges = edge_index.shape[1]\n for j in range(0, n_edges, 2):\n begin_idx = int(edge_index[0, j])\n end_idx = int(edge_index[1, j])\n w1, w2, w3, w4, w5, w6, w7, _, _ = edge_attr[j].astype(bool)\n if not G.has_edge(begin_idx, end_idx):\n G.add_edge(begin_idx, end_idx, w1=w1, w2=w2, w3=w3, w4=w4, w5=w5,\n w6=w6, w7=w7)\n return G\n\ndef graph_data_obj_to_nx_simple(data):\n \"\"\"\n Converts graph Data object required by the pytorch geometric package to\n network x data object. NB: Uses simplified atom and bond features,\n and represent as indices. NB: possible issues with recapitulating relative\n stereochemistry since the edges in the nx object are unordered.\n :param data: pytorch geometric Data object\n :return: network x object\n \"\"\"\n G = nx.Graph()\n\n # atoms\n atom_features = data.x.cpu().numpy()\n num_atoms = atom_features.shape[0]\n for i in range(num_atoms):\n atomic_num_idx, chirality_tag_idx = atom_features[i]\n G.add_node(i, atom_num_idx=atomic_num_idx, chirality_tag_idx=chirality_tag_idx)\n pass\n\n # bonds\n edge_index = data.edge_index.cpu().numpy()\n edge_attr = data.edge_attr.cpu().numpy()\n num_bonds = edge_index.shape[1]\n for j in range(0, num_bonds, 2):\n begin_idx = int(edge_index[0, j])\n end_idx = int(edge_index[1, j])\n bond_type_idx, bond_dir_idx = edge_attr[j]\n if not G.has_edge(begin_idx, end_idx):\n G.add_edge(begin_idx, end_idx, bond_type_idx=bond_type_idx,\n bond_dir_idx=bond_dir_idx)\n\n return G\n\ndef nx_to_graph_data_obj_simple(G):\n \"\"\"\n Converts nx graph to pytorch geometric Data object. Assume node indices\n are numbered from 0 to num_nodes - 1. NB: Uses simplified atom and bond\n features, and represent as indices. NB: possible issues with\n recapitulating relative stereochemistry since the edges in the nx\n object are unordered.\n :param G: nx graph obj\n :return: pytorch geometric Data object\n \"\"\"\n # atoms\n num_atom_features = 2 # atom type, chirality tag\n atom_features_list = []\n for _, node in G.nodes(data=True):\n atom_feature = [node['atom_num_idx'], node['chirality_tag_idx']]\n atom_features_list.append(atom_feature)\n x = torch.tensor(np.array(atom_features_list), dtype=torch.long)\n\n # bonds\n num_bond_features = 2 # bond type, bond direction\n if len(G.edges()) > 0: # mol has bonds\n edges_list = []\n edge_features_list = []\n for i, j, edge in G.edges(data=True):\n edge_feature = [edge['bond_type_idx'], edge['bond_dir_idx']]\n edges_list.append((i, j))\n edge_features_list.append(edge_feature)\n edges_list.append((j, i))\n edge_features_list.append(edge_feature)\n\n # data.edge_index: Graph connectivity in COO format with shape [2, num_edges]\n edge_index = torch.tensor(np.array(edges_list).T, dtype=torch.long)\n\n # data.edge_attr: Edge feature matrix with shape [num_edges, num_edge_features]\n edge_attr = torch.tensor(np.array(edge_features_list),\n dtype=torch.long)\n else: # mol has no bonds\n edge_index = torch.empty((2, 0), dtype=torch.long)\n edge_attr = torch.empty((0, num_bond_features), dtype=torch.long)\n\n data = Data(x=x, edge_index=edge_index, edge_attr=edge_attr)\n\n return data\n\n\nclass NegativeEdge:\n \"\"\"Borrowed from https://github.com/snap-stanford/pretrain-gnns/\"\"\"\n def __init__(self):\n \"\"\"\n Randomly sample negative edges\n \"\"\"\n pass\n\n def __call__(self, data):\n num_nodes = data.num_nodes\n num_edges = data.num_edges\n\n edge_set = set([str(data.edge_index[0,i].cpu().item()) + \",\" + str(data.edge_index[1,i].cpu().item()) for i in range(data.edge_index.shape[1])])\n\n redandunt_sample = torch.randint(0, num_nodes, (2,5*num_edges))\n sampled_ind = []\n sampled_edge_set = set([])\n for i in range(5*num_edges):\n node1 = redandunt_sample[0,i].cpu().item()\n node2 = redandunt_sample[1,i].cpu().item()\n edge_str = str(node1) + \",\" + str(node2)\n if not edge_str in edge_set and not edge_str in sampled_edge_set and not node1 == node2:\n sampled_edge_set.add(edge_str)\n sampled_ind.append(i)\n if len(sampled_ind) == num_edges/2:\n break\n\n data.negative_edge_index = redandunt_sample[:,sampled_ind]\n \n return data\n\n\nclass MaskEdge:\n \"\"\"Borrowed from https://github.com/snap-stanford/pretrain-gnns/\"\"\"\n def __init__(self, mask_rate):\n \"\"\"\n Assume edge_attr is of the form:\n [w1, w2, w3, w4, w5, w6, w7, self_loop, mask]\n :param mask_rate: % of edges to be masked\n \"\"\"\n self.mask_rate = mask_rate\n\n def __call__(self, data, masked_edge_indices=None):\n if masked_edge_indices == None:\n # sample x distinct edges to be masked, based on mask rate. But\n # will sample at least 1 edge\n num_edges = int(data.edge_index.size()[1] / 2) # num unique edges\n sample_size = int(num_edges * self.mask_rate + 1)\n # during sampling, we only pick the 1st direction of a particular\n # edge pair\n masked_edge_indices = [2 * i for i in random.sample(range(\n num_edges), sample_size)]\n\n data.masked_edge_idx = torch.tensor(np.array(masked_edge_indices))\n\n # create ground truth edge features for the edges that correspond to\n # the masked indices\n mask_edge_labels_list = []\n for idx in masked_edge_indices:\n mask_edge_labels_list.append(data.edge_attr[idx].view(1, -1))\n data.mask_edge_label = torch.cat(mask_edge_labels_list, dim=0)\n\n # created new masked edge_attr, where both directions of the masked\n # edges have masked edge type. For message passing in gcn\n\n # append the 2nd direction of the masked edges\n all_masked_edge_indices = masked_edge_indices + [i + 1 for i in\n masked_edge_indices]\n for idx in all_masked_edge_indices:\n data.edge_attr[idx] = torch.tensor(np.array([0, 0, 0, 0, 0,\n 0, 0, 0, 1]),\n dtype=torch.float)\n\n return data\n\nclass MaskAtom:\n \"\"\"Borrowed from https://github.com/snap-stanford/pretrain-gnns/\"\"\"\n def __init__(self, num_atom_type, num_edge_type, mask_rate, mask_edge=True):\n \"\"\"\n Randomly masks an atom, and optionally masks edges connecting to it.\n The mask atom type index is num_possible_atom_type\n The mask edge type index in num_possible_edge_type\n :param num_atom_type:\n :param num_edge_type:\n :param mask_rate: % of atoms to be masked\n :param mask_edge: If True, also mask the edges that connect to the\n masked atoms\n \"\"\"\n self.num_atom_type = num_atom_type\n self.num_edge_type = num_edge_type\n self.mask_rate = mask_rate\n self.mask_edge = mask_edge\n\n def __call__(self, data, masked_atom_indices=None):\n \"\"\"\n :param data: pytorch geometric data object. Assume that the edge\n ordering is the default pytorch geometric ordering, where the two\n directions of a single edge occur in pairs.\n Eg. data.edge_index = tensor([[0, 1, 1, 2, 2, 3],\n [1, 0, 2, 1, 3, 2]])\n :param masked_atom_indices: If None, then randomly samples num_atoms\n * mask rate number of atom indices\n Otherwise a list of atom idx that sets the atoms to be masked (for\n debugging only)\n :return: None, Creates new attributes in original data object:\n data.mask_node_idx\n data.mask_node_label\n data.mask_edge_idx\n data.mask_edge_label\n \"\"\"\n\n if masked_atom_indices == None:\n # sample x distinct atoms to be masked, based on mask rate. But\n # will sample at least 1 atom\n num_atoms = data.x.size()[0]\n sample_size = int(num_atoms * self.mask_rate + 1)\n masked_atom_indices = random.sample(range(num_atoms), sample_size)\n\n # create mask node label by copying atom feature of mask atom\n mask_node_labels_list = []\n for atom_idx in masked_atom_indices:\n mask_node_labels_list.append(data.x[atom_idx].view(1, -1))\n data.mask_node_label = torch.cat(mask_node_labels_list, dim=0)\n data.masked_atom_indices = torch.tensor(masked_atom_indices)\n\n # modify the original node feature of the masked node\n for atom_idx in masked_atom_indices:\n data.x[atom_idx] = torch.tensor([self.num_atom_type, 0])\n\n if self.mask_edge:\n # create mask edge labels by copying edge features of edges that are bonded to\n # mask atoms\n connected_edge_indices = []\n for bond_idx, (u, v) in enumerate(data.edge_index.cpu().numpy().T):\n for atom_idx in masked_atom_indices:\n if atom_idx in set((u, v)) and \\\n bond_idx not in connected_edge_indices:\n connected_edge_indices.append(bond_idx)\n\n if len(connected_edge_indices) > 0:\n # create mask edge labels by copying bond features of the bonds connected to\n # the mask atoms\n mask_edge_labels_list = []\n for bond_idx in connected_edge_indices[::2]: # because the\n # edge ordering is such that two directions of a single\n # edge occur in pairs, so to get the unique undirected\n # edge indices, we take every 2nd edge index from list\n mask_edge_labels_list.append(\n data.edge_attr[bond_idx].view(1, -1))\n\n data.mask_edge_label = torch.cat(mask_edge_labels_list, dim=0)\n # modify the original bond features of the bonds connected to the mask atoms\n for bond_idx in connected_edge_indices:\n data.edge_attr[bond_idx] = torch.tensor(\n [self.num_edge_type, 0])\n\n data.connected_edge_indices = torch.tensor(\n connected_edge_indices[::2])\n else:\n data.mask_edge_label = torch.empty((0, 2)).to(torch.int64)\n data.connected_edge_indices = torch.tensor(\n connected_edge_indices).to(torch.int64)\n\n return data\n\n def __repr__(self):\n return '{}(num_atom_type={}, num_edge_type={}, mask_rate={}, mask_edge={})'.format(\n self.__class__.__name__, self.num_atom_type, self.num_edge_type,\n self.mask_rate, self.mask_edge)\n\ndef reset_idxes(G):\n \"\"\"\n Resets node indices such that they are numbered from 0 to num_nodes - 1\n :param G:\n :return: copy of G with relabelled node indices, mapping\n \"\"\"\n mapping = {}\n for new_idx, old_idx in enumerate(G.nodes()):\n mapping[old_idx] = new_idx\n new_G = nx.relabel_nodes(G, mapping, copy=True)\n return new_G, mapping\n\n\nclass ExtractSubstructureContextPair:\n def __init__(self, l1, center=True):\n self.center = center\n self.l1 = l1\n \n if self.l1 == 0:\n self.l1 = -1\n\n def __call__(self, data, root_idx=None):\n num_atoms = data.x.size()[0]\n G = graph_data_obj_to_nx(data)\n\n if root_idx == None:\n if self.center == True:\n root_idx = data.center_node_idx.item()\n else:\n root_idx = random.sample(range(num_atoms), 1)[0]\n\n # in the PPI case, the subgraph is the entire PPI graph\n data.x_substruct = data.x\n data.edge_attr_substruct = data.edge_attr\n data.edge_index_substruct = data.edge_index\n data.center_substruct_idx = data.center_node_idx\n\n\n # Get context that is between l1 and the max diameter of the PPI graph\n l1_node_idxes = nx.single_source_shortest_path_length(G, root_idx,\n self.l1).keys()\n # l2_node_idxes = nx.single_source_shortest_path_length(G, root_idx,\n # self.l2).keys()\n l2_node_idxes = range(num_atoms)\n context_node_idxes = set(l1_node_idxes).symmetric_difference(\n set(l2_node_idxes))\n if len(context_node_idxes) > 0:\n context_G = G.subgraph(context_node_idxes)\n context_G, context_node_map = reset_idxes(context_G) # need to\n # reset node idx to 0 -> num_nodes - 1, other data obj does not\n # make sense\n context_data = nx_to_graph_data_obj(context_G, 0) # use a dummy\n # center node idx\n data.x_context = context_data.x\n data.edge_attr_context = context_data.edge_attr\n data.edge_index_context = context_data.edge_index\n\n # Get indices of overlapping nodes between substruct and context,\n # WRT context ordering\n context_substruct_overlap_idxes = list(context_node_idxes)\n if len(context_substruct_overlap_idxes) > 0:\n context_substruct_overlap_idxes_reorder = [context_node_map[old_idx]\n for\n old_idx in\n context_substruct_overlap_idxes]\n data.overlap_context_substruct_idx = \\\n torch.tensor(context_substruct_overlap_idxes_reorder)\n\n return data\n\n def __repr__(self):\n return '{}(l1={}, center={})'.format(self.__class__.__name__,\n self.l1, self.center)\n\nclass ChemExtractSubstructureContextPair:\n def __init__(self, k, l1, l2):\n \"\"\"\n Randomly selects a node from the data object, and adds attributes\n that contain the substructure that corresponds to k hop neighbours\n rooted at the node, and the context substructures that corresponds to\n the subgraph that is between l1 and l2 hops away from the\n root node.\n :param k:\n :param l1:\n :param l2:\n \"\"\"\n self.k = k\n self.l1 = l1\n self.l2 = l2\n # for the special case of 0, addresses the quirk with\n # single_source_shortest_path_length\n if self.k == 0:\n self.k = -1\n if self.l1 == 0:\n self.l1 = -1\n if self.l2 == 0:\n self.l2 = -1\n\n def __call__(self, data, root_idx=None):\n \"\"\"\n :param data: pytorch geometric data object\n :param root_idx: If None, then randomly samples an atom idx.\n Otherwise sets atom idx of root (for debugging only)\n :return: None. Creates new attributes in original data object:\n data.center_substruct_idx\n data.x_substruct\n data.edge_attr_substruct\n data.edge_index_substruct\n data.x_context\n data.edge_attr_context\n data.edge_index_context\n data.overlap_context_substruct_idx\n \"\"\"\n num_atoms = data.x.size()[0]\n if root_idx == None:\n root_idx = random.sample(range(num_atoms), 1)[0]\n\n G = graph_data_obj_to_nx_simple(data) # same ordering as input data obj\n\n # Get k-hop subgraph rooted at specified atom idx\n substruct_node_idxes = nx.single_source_shortest_path_length(G,\n root_idx,\n self.k).keys()\n if len(substruct_node_idxes) > 0:\n substruct_G = G.subgraph(substruct_node_idxes)\n substruct_G, substruct_node_map = reset_idxes(substruct_G) # need\n # to reset node idx to 0 -> num_nodes - 1, otherwise data obj does not\n # make sense, since the node indices in data obj must start at 0\n substruct_data = nx_to_graph_data_obj_simple(substruct_G)\n data.x_substruct = substruct_data.x\n data.edge_attr_substruct = substruct_data.edge_attr\n data.edge_index_substruct = substruct_data.edge_index\n data.center_substruct_idx = torch.tensor([substruct_node_map[\n root_idx]]) # need\n # to convert center idx from original graph node ordering to the\n # new substruct node ordering\n\n # Get subgraphs that is between l1 and l2 hops away from the root node\n l1_node_idxes = nx.single_source_shortest_path_length(G, root_idx,\n self.l1).keys()\n l2_node_idxes = nx.single_source_shortest_path_length(G, root_idx,\n self.l2).keys()\n context_node_idxes = set(l1_node_idxes).symmetric_difference(\n set(l2_node_idxes))\n if len(context_node_idxes) == 0:\n l2_node_idxes = range(num_atoms)\n context_node_idxes = set(l1_node_idxes).symmetric_difference(\n set(l2_node_idxes))\n\n if len(context_node_idxes) > 0:\n context_G = G.subgraph(context_node_idxes)\n context_G, context_node_map = reset_idxes(context_G) # need to\n # reset node idx to 0 -> num_nodes - 1, otherwise data obj does not\n # make sense, since the node indices in data obj must start at 0\n context_data = nx_to_graph_data_obj_simple(context_G)\n data.x_context = context_data.x\n data.edge_attr_context = context_data.edge_attr\n data.edge_index_context = context_data.edge_index\n\n # Get indices of overlapping nodes between substruct and context,\n # WRT context ordering\n context_substruct_overlap_idxes = list(set(\n context_node_idxes).intersection(set(substruct_node_idxes)))\n if len(context_substruct_overlap_idxes) <= 0:\n context_substruct_overlap_idxes = list(context_node_idxes)\n if len(context_substruct_overlap_idxes) > 0:\n context_substruct_overlap_idxes_reorder = [context_node_map[old_idx]\n for\n old_idx in\n context_substruct_overlap_idxes]\n # need to convert the overlap node idxes, which is from the\n # original graph node ordering to the new context node ordering\n data.overlap_context_substruct_idx = \\\n torch.tensor(context_substruct_overlap_idxes_reorder)\n\n return data\n\n # ### For debugging ###\n # if len(substruct_node_idxes) > 0:\n # substruct_mol = graph_data_obj_to_mol_simple(data.x_substruct,\n # data.edge_index_substruct,\n # data.edge_attr_substruct)\n # print(AllChem.MolToSmiles(substruct_mol))\n # if len(context_node_idxes) > 0:\n # context_mol = graph_data_obj_to_mol_simple(data.x_context,\n # data.edge_index_context,\n # data.edge_attr_context)\n # print(AllChem.MolToSmiles(context_mol))\n #\n # print(list(context_node_idxes))\n # print(list(substruct_node_idxes))\n # print(context_substruct_overlap_idxes)\n # ### End debugging ###\n\n def __repr__(self):\n return '{}(k={},l1={}, l2={})'.format(self.__class__.__name__, self.k,\n self.l1, self.l2)\n\n\n# ==================\n# DataLoader utils\n# ==================\n\n\nclass BatchFinetune(Data):\n def __init__(self, batch=None, **kwargs):\n super(BatchMasking, self).__init__(**kwargs)\n self.batch = batch\n\n @staticmethod\n def from_data_list(data_list):\n r\"\"\"Constructs a batch object from a python list holding\n :class:`torch_geometric.data.Data` objects.\n The assignment vector :obj:`batch` is created on the fly.\"\"\"\n keys = [set(data.keys) for data in data_list]\n keys = list(set.union(*keys))\n assert 'batch' not in keys\n\n batch = BatchMasking()\n\n for key in keys:\n batch[key] = []\n batch.batch = []\n\n cumsum_node = 0\n cumsum_edge = 0\n\n for i, data in enumerate(data_list):\n num_nodes = data.num_nodes\n batch.batch.append(torch.full((num_nodes, ), i, dtype=torch.long))\n for key in data.keys:\n item = data[key]\n if key in ['edge_index', 'center_node_idx']:\n item = item + cumsum_node\n batch[key].append(item)\n\n cumsum_node += num_nodes\n cumsum_edge += data.edge_index.shape[1]\n\n for key in keys:\n batch[key] = torch.cat(\n batch[key], dim=data_list[0].__cat_dim__(key, batch[key][0]))\n batch.batch = torch.cat(batch.batch, dim=-1)\n return batch.contiguous()\n\n @property\n def num_graphs(self):\n \"\"\"Returns the number of graphs in the batch.\"\"\"\n return self.batch[-1].item() + 1\n\n\nclass BatchMasking(Data):\n def __init__(self, batch=None, **kwargs):\n super(BatchMasking, self).__init__(**kwargs)\n self.batch = batch\n\n @staticmethod\n def from_data_list(data_list):\n r\"\"\"Constructs a batch object from a python list holding\n :class:`torch_geometric.data.Data` objects.\n The assignment vector :obj:`batch` is created on the fly.\"\"\"\n keys = [set(data.keys) for data in data_list]\n keys = list(set.union(*keys))\n assert 'batch' not in keys\n\n batch = BatchMasking()\n\n for key in keys:\n batch[key] = []\n batch.batch = []\n\n cumsum_node = 0\n cumsum_edge = 0\n\n for i, data in enumerate(data_list):\n num_nodes = data.num_nodes\n batch.batch.append(torch.full((num_nodes, ), i, dtype=torch.long))\n for key in data.keys:\n item = data[key]\n if key in ['edge_index']:\n item = item + cumsum_node\n elif key == 'masked_edge_idx':\n item = item + cumsum_edge\n batch[key].append(item)\n\n cumsum_node += num_nodes\n cumsum_edge += data.edge_index.shape[1]\n\n for key in keys:\n batch[key] = torch.cat(\n batch[key], dim=data_list[0].__cat_dim__(key, batch[key][0]))\n batch.batch = torch.cat(batch.batch, dim=-1)\n return batch.contiguous()\n\n def cumsum(self, key, item):\n r\"\"\"If :obj:`True`, the attribute :obj:`key` with content :obj:`item`\n should be added up cumulatively before concatenated together.\n .. note::\n This method is for internal use only, and should only be overridden\n if the batch concatenation process is corrupted for a specific data\n attribute.\n \"\"\"\n return key in ['edge_index', 'face', 'masked_atom_indices', 'connected_edge_indices']\n\n @property\n def num_graphs(self):\n \"\"\"Returns the number of graphs in the batch.\"\"\"\n return self.batch[-1].item() + 1\n\n\nclass BatchAE(Data):\n def __init__(self, batch=None, **kwargs):\n super(BatchAE, self).__init__(**kwargs)\n self.batch = batch\n\n @staticmethod\n def from_data_list(data_list):\n r\"\"\"Constructs a batch object from a python list holding\n :class:`torch_geometric.data.Data` objects.\n The assignment vector :obj:`batch` is created on the fly.\"\"\"\n keys = [set(data.keys) for data in data_list]\n keys = list(set.union(*keys))\n assert 'batch' not in keys\n\n batch = BatchAE()\n\n for key in keys:\n batch[key] = []\n batch.batch = []\n\n cumsum_node = 0\n\n for i, data in enumerate(data_list):\n num_nodes = data.num_nodes\n batch.batch.append(torch.full((num_nodes, ), i, dtype=torch.long))\n for key in data.keys:\n item = data[key]\n if key in ['edge_index', 'negative_edge_index']:\n item = item + cumsum_node\n batch[key].append(item)\n\n cumsum_node += num_nodes\n\n for key in keys:\n batch[key] = torch.cat(\n batch[key], dim=batch.cat_dim(key))\n batch.batch = torch.cat(batch.batch, dim=-1)\n return batch.contiguous()\n\n @property\n def num_graphs(self):\n \"\"\"Returns the number of graphs in the batch.\"\"\"\n return self.batch[-1].item() + 1\n\n def cat_dim(self, key):\n return -1 if key in [\"edge_index\", \"negative_edge_index\"] else 0\n\n\nclass BatchSubstructContext(Data):\n def __init__(self, batch=None, **kwargs):\n super(BatchSubstructContext, self).__init__(**kwargs)\n self.batch = batch\n\n @staticmethod\n def from_data_list(data_list):\n r\"\"\"Constructs a batch object from a python list holding\n :class:`torch_geometric.data.Data` objects.\n The assignment vector :obj:`batch` is created on the fly.\"\"\"\n batch = BatchSubstructContext()\n keys = [\"center_substruct_idx\", \"edge_attr_substruct\", \"edge_index_substruct\", \"x_substruct\", \"overlap_context_substruct_idx\", \"edge_attr_context\", \"edge_index_context\", \"x_context\"]\n for key in keys:\n batch[key] = []\n\n #used for pooling the context\n batch.batch_overlapped_context = []\n batch.overlapped_context_size = []\n\n cumsum_main = 0\n cumsum_substruct = 0\n cumsum_context = 0\n\n i = 0\n\n for data in data_list:\n #If there is no context, just skip!!\n if hasattr(data, \"x_context\"):\n num_nodes = data.num_nodes\n num_nodes_substruct = len(data.x_substruct)\n num_nodes_context = len(data.x_context)\n\n #batch.batch.append(torch.full((num_nodes, ), i, dtype=torch.long))\n batch.batch_overlapped_context.append(torch.full((len(data.overlap_context_substruct_idx), ), i, dtype=torch.long))\n batch.overlapped_context_size.append(len(data.overlap_context_substruct_idx))\n\n ###batching for the substructure graph\n for key in [\"center_substruct_idx\", \"edge_attr_substruct\", \"edge_index_substruct\", \"x_substruct\"]:\n item = data[key]\n item = item + cumsum_substruct if batch.cumsum(key, item) else item\n batch[key].append(item)\n\n ###batching for the context graph\n for key in [\"overlap_context_substruct_idx\", \"edge_attr_context\", \"edge_index_context\", \"x_context\"]:\n item = data[key]\n item = item + cumsum_context if batch.cumsum(key, item) else item\n batch[key].append(item)\n\n cumsum_main += num_nodes\n cumsum_substruct += num_nodes_substruct\n cumsum_context += num_nodes_context\n i += 1\n\n for key in keys:\n batch[key] = torch.cat(\n batch[key], dim=batch.cat_dim(key))\n #batch.batch = torch.cat(batch.batch, dim=-1)\n batch.batch_overlapped_context = torch.cat(batch.batch_overlapped_context, dim=-1)\n batch.overlapped_context_size = torch.LongTensor(batch.overlapped_context_size)\n\n return batch.contiguous()\n\n def cat_dim(self, key):\n return -1 if key in [\"edge_index\", \"edge_index_substruct\", \"edge_index_context\"] else 0\n\n def cumsum(self, key, item):\n r\"\"\"If :obj:`True`, the attribute :obj:`key` with content :obj:`item`\n should be added up cumulatively before concatenated together.\n .. note::\n This method is for internal use only, and should only be overridden\n if the batch concatenation process is corrupted for a specific data\n attribute.\n \"\"\"\n return key in [\"edge_index\", \"edge_index_substruct\", \"edge_index_context\", \"overlap_context_substruct_idx\", \"center_substruct_idx\"]\n\n @property\n def num_graphs(self):\n \"\"\"Returns the number of graphs in the batch.\"\"\"\n return self.batch[-1].item() + 1\n\n\nclass DataLoaderFinetune(torch.utils.data.DataLoader):\n def __init__(self, dataset, batch_size=1, shuffle=True, **kwargs):\n super(DataLoaderFinetune, self).__init__(\n dataset,\n batch_size,\n shuffle,\n collate_fn=lambda data_list: BatchFinetune.from_data_list(data_list),\n **kwargs)\n\n\nclass DataLoaderMasking(torch.utils.data.DataLoader):\n def __init__(self, dataset, batch_size=1, shuffle=True, **kwargs):\n super(DataLoaderMasking, self).__init__(\n dataset,\n batch_size,\n shuffle,\n collate_fn=lambda data_list: BatchMasking.from_data_list(data_list),\n **kwargs)\n\n\nclass DataLoaderAE(torch.utils.data.DataLoader):\n def __init__(self, dataset, batch_size=1, shuffle=True, **kwargs):\n super(DataLoaderAE, self).__init__(\n dataset,\n batch_size,\n shuffle,\n collate_fn=lambda data_list: BatchAE.from_data_list(data_list),\n **kwargs)\n\n\nclass DataLoaderSubstructContext(torch.utils.data.DataLoader):\n def __init__(self, dataset, batch_size=1, shuffle=True, **kwargs):\n super(DataLoaderSubstructContext, self).__init__(\n dataset,\n batch_size,\n shuffle,\n collate_fn=lambda data_list: BatchSubstructContext.from_data_list(data_list),\n **kwargs)\n\n\n# ==========\n# Dataset\n# ==========\n\n\n@register_dataset(\"test_bio\")\nclass TestBioDataset(InMemoryDataset):\n def __init__(self,\n data_type=\"unsupervised\",\n root=None,\n transform=None,\n pre_transform=None,\n pre_filter=None):\n super(TestBioDataset, self).__init__(root, transform, pre_transform, pre_filter)\n num_nodes = 10\n num_edges = 10\n num_graphs = 100\n\n def cycle_index(num, shift):\n arr = torch.arange(num) + shift\n arr[-shift:] = torch.arange(shift)\n return arr\n\n upp = torch.cat([torch.arange(0, num_nodes)] * num_graphs)\n dwn = torch.cat([cycle_index(num_nodes, 1)] * num_graphs)\n edge_index = torch.stack([upp, dwn])\n\n edge_attr = torch.zeros(num_edges * num_graphs, 9)\n for idx, val in enumerate(torch.randint(0, 9, size=(num_edges * num_graphs,))):\n edge_attr[idx][val] = 1.\n self.data = Data(\n x=torch.ones(num_graphs * num_nodes, 1),\n edge_index=edge_index,\n edge_attr=edge_attr,\n )\n self.data.center_node_idx = torch.randint(0, num_nodes, size=(num_graphs,))\n self.slices = {\n \"x\": torch.arange(0, (num_graphs + 1) * num_nodes, num_nodes),\n \"edge_index\": torch.arange(0, (num_graphs + 1) * num_edges, num_edges),\n \"edge_attr\": torch.arange(0, (num_graphs + 1) * num_edges, num_edges),\n \"center_node_idx\": torch.arange(num_graphs+1),\n }\n\n if data_type == \"supervised\":\n pretrain_tasks = 10\n downstream_tasks = 5\n go_target_pretrain = torch.zeros(pretrain_tasks * num_graphs)\n go_target_downstream = torch.zeros(downstream_tasks * num_graphs)\n go_target_pretrain[torch.arange(0, pretrain_tasks*num_graphs, pretrain_tasks)] = 1\n go_target_downstream[torch.arange(0, downstream_tasks*num_graphs, downstream_tasks)] = 1\n self.data.go_target_downstream = go_target_downstream\n self.data.go_target_pretrain = go_target_pretrain\n self.slices[\"go_target_pretrain\"] = torch.arange(0, (num_graphs + 1) * pretrain_tasks)\n self.slices[\"go_target_downstream\"] = torch.arange(0, (num_graphs + 1) * downstream_tasks)\n\n@register_dataset(\"test_chem\")\nclass TestChemDataset(InMemoryDataset):\n def __init__(self,\n data_type=\"unsupervised\",\n root=None,\n transform=None,\n pre_transform=None,\n pre_filter=None):\n super(TestChemDataset, self).__init__(root, transform, pre_transform, pre_filter)\n num_nodes = 10\n num_edges = 10\n num_graphs = 100\n\n def cycle_index(num, shift):\n arr = torch.arange(num) + shift\n arr[-shift:] = torch.arange(shift)\n return arr\n\n upp = torch.cat([torch.arange(0, num_nodes)] * num_graphs)\n dwn = torch.cat([cycle_index(num_nodes, 1)] * num_graphs)\n edge_index = torch.stack([upp, dwn])\n\n edge_attr = torch.zeros(num_edges * num_graphs, 2)\n x = torch.zeros(num_graphs * num_nodes, 2)\n for idx, val in enumerate(torch.randint(0, 6, size=(num_edges * num_graphs,))):\n edge_attr[idx][0] = val\n for idx, val in enumerate(torch.randint(0, 3, size=(num_edges * num_graphs,))):\n edge_attr[idx][1] = val\n for idx, val in enumerate(torch.randint(0, 120, size=(num_edges * num_graphs,))):\n x[idx][0] = val\n for idx, val in enumerate(torch.randint(0, 3, size=(num_edges * num_graphs,))):\n x[idx][1] = val\n\n self.data = Data(\n x=x.to(torch.long),\n edge_index=edge_index.to(torch.long),\n edge_attr=edge_attr.to(torch.long),\n )\n\n self.slices = {\n \"x\": torch.arange(0, (num_graphs + 1) * num_nodes, num_nodes),\n \"edge_index\": torch.arange(0, (num_graphs + 1) * num_edges, num_edges),\n \"edge_attr\": torch.arange(0, (num_graphs + 1) * num_edges, num_edges),\n }\n\n if data_type == \"supervised\":\n pretrain_tasks = 10\n go_target_pretrain = torch.zeros(pretrain_tasks * num_graphs) - 1\n for i in range(num_graphs):\n val = np.random.randint(0, pretrain_tasks)\n go_target_pretrain[i * pretrain_tasks + val] = 1\n self.data.y = go_target_pretrain\n self.slices[\"y\"] = torch.arange(0, (num_graphs + 1) * pretrain_tasks, pretrain_tasks)\n \n def get(self, idx):\n data = Data()\n for key in self.data.keys:\n item, slices = self.data[key], self.slices[key]\n s = list(repeat(slice(None), item.dim()))\n s[data.__cat_dim__(key, item)] = slice(slices[idx],\n slices[idx + 1])\n data[key] = item[s]\n return data\n\n\n@register_dataset(\"bio\")\nclass BioDataset(InMemoryDataset):\n def __init__(self,\n data_type=\"unsupervised\",\n empty=False,\n transform=None,\n pre_transform=None,\n pre_filter=None):\n self.data_type = data_type\n self.url = \"https://cloud.tsinghua.edu.cn/f/c865b1d61348489e86ac/?dl=1\"\n self.root = osp.join(osp.dirname(osp.realpath(__file__)), \"../..\", \"data\", \"BIO\")\n super(BioDataset, self).__init__(self.root, transform, pre_transform, pre_filter)\n if not empty:\n if data_type == \"unsupervised\":\n self.data, self.slices = torch.load(self.processed_paths[1])\n else:\n self.data, self.slices = torch.load(self.processed_paths[0])\n\n @property\n def raw_file_names(self):\n return ['processed.zip']\n\n @property\n def processed_file_names(self):\n return ['supervised_data_processed.pt', 'unsupervised_data_processed.pt']\n\n def download(self):\n download_url(self.url, self.raw_dir, name=\"processed.zip\")\n\n def process(self):\n zfile = zipfile.ZipFile(osp.join(self.raw_dir, self.raw_file_names[0]),'r')\n for filename in zfile.namelist():\n print(\"unzip file: \" + filename)\n zfile.extract(filename, osp.join(self.processed_dir))\n\n@register_dataset(\"chem\")\nclass MoleculeDataset(InMemoryDataset):\n def __init__(self,\n data_type=\"unsupervised\",\n transform=None,\n pre_transform=None,\n pre_filter=None,\n empty=False):\n self.data_type = data_type\n self.url = \"https://cloud.tsinghua.edu.cn/f/2cac04ee904e4b54b4b2/?dl=1\"\n self.root = osp.join(osp.dirname(osp.realpath(__file__)), \"../..\", \"data\", \"CHEM\")\n\n super(MoleculeDataset, self).__init__(self.root, transform, pre_transform,\n pre_filter)\n self.transform, self.pre_transform, self.pre_filter = transform, pre_transform, pre_filter\n\n if not empty:\n if data_type == \"unsupervised\":\n self.data, self.slices = torch.load(self.processed_paths[1])\n else:\n self.data, self.slices = torch.load(self.processed_paths[0])\n\n def get(self, idx):\n data = Data()\n for key in self.data.keys:\n item, slices = self.data[key], self.slices[key]\n s = list(repeat(slice(None), item.dim()))\n s[data.__cat_dim__(key, item)] = slice(slices[idx],\n slices[idx + 1])\n data[key] = item[s]\n return data\n\n\n @property\n def raw_file_names(self):\n return ['processed.zip']\n\n @property\n def processed_file_names(self):\n return ['supervised_data_processed.pt', 'unsupervised_data_processed.pt']\n\n def download(self):\n download_url(self.url, self.raw_dir, name=\"processed.zip\")\n\n def process(self):\n zfile = zipfile.ZipFile(osp.join(self.raw_dir, self.raw_file_names[0]),'r')\n for filename in zfile.namelist():\n print(\"unzip file: \" + filename)\n zfile.extract(filename, osp.join(self.processed_dir))\n\n# ==========\n# Dataset for finetuning\n# ==========\n\n@register_dataset(\"bace\")\nclass BACEDataset(InMemoryDataset):\n def __init__(self,\n transform=None,\n pre_transform=None,\n pre_filter=None,\n empty=False):\n self.url = \"https://cloud.tsinghua.edu.cn/f/253270b278f4465380f1/?dl=1\"\n self.root = osp.join(osp.dirname(osp.realpath(__file__)), \"../..\", \"data\", \"BACE\")\n\n super(BACEDataset, self).__init__(self.root, transform, pre_transform,\n pre_filter)\n self.transform, self.pre_transform, self.pre_filter = transform, pre_transform, pre_filter\n\n if not empty:\n self.data, self.slices = torch.load(self.processed_paths[0])\n\n\n def get(self, idx):\n data = Data()\n for key in self.data.keys:\n item, slices = self.data[key], self.slices[key]\n s = list(repeat(slice(None), item.dim()))\n s[data.__cat_dim__(key, item)] = slice(slices[idx],\n slices[idx + 1])\n data[key] = item[s]\n return data\n\n\n @property\n def raw_file_names(self):\n return ['processed.zip']\n\n @property\n def processed_file_names(self):\n return ['geometric_data_processed.pt']\n\n def download(self):\n download_url(self.url, self.raw_dir, name=\"processed.zip\")\n\n def process(self):\n zfile = zipfile.ZipFile(osp.join(self.raw_dir, self.raw_file_names[0]),'r')\n for filename in zfile.namelist():\n print(\"unzip file: \" + filename)\n zfile.extract(filename, osp.join(self.processed_dir))\n\n@register_dataset(\"bbbp\")\nclass BBBPDataset(InMemoryDataset):\n def __init__(self,\n transform=None,\n pre_transform=None,\n pre_filter=None,\n empty=False):\n self.url = \"https://cloud.tsinghua.edu.cn/f/ab8ff4d0a68c40a38956/?dl=1\"\n self.root = osp.join(osp.dirname(osp.realpath(__file__)), \"../..\", \"data\", \"BBBP\")\n\n super(BBBPDataset, self).__init__(self.root, transform, pre_transform,\n pre_filter)\n self.transform, self.pre_transform, self.pre_filter = transform, pre_transform, pre_filter\n\n if not empty:\n self.data, self.slices = torch.load(self.processed_paths[0])\n\n\n def get(self, idx):\n data = Data()\n for key in self.data.keys:\n item, slices = self.data[key], self.slices[key]\n s = list(repeat(slice(None), item.dim()))\n s[data.__cat_dim__(key, item)] = slice(slices[idx],\n slices[idx + 1])\n data[key] = item[s]\n return data\n\n\n @property\n def raw_file_names(self):\n return ['processed.zip']\n\n @property\n def processed_file_names(self):\n return ['geometric_data_processed.pt']\n\n def download(self):\n download_url(self.url, self.raw_dir, name=\"processed.zip\")\n\n def process(self):\n zfile = zipfile.ZipFile(osp.join(self.raw_dir, self.raw_file_names[0]),'r')\n for filename in zfile.namelist():\n print(\"unzip file: \" + filename)\n zfile.extract(filename, osp.join(self.processed_dir))\n"
] | [
[
"numpy.dot",
"sklearn.metrics.roc_auc_score",
"numpy.linalg.norm",
"sklearn.metrics.precision_recall_curve",
"torch.cuda.empty_cache",
"torch.unique",
"torch.cuda.is_available",
"torch.device",
"sklearn.metrics.auc",
"sklearn.metrics.f1_score",
"numpy.array"
],
[
"torch.LongTensor",
"torch.randint",
"torch.empty",
"torch.full",
"torch.cat",
"torch.zeros",
"torch.load",
"torch.ones",
"torch.tensor",
"numpy.ones",
"numpy.intersect1d",
"torch.arange",
"torch.stack",
"numpy.array",
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
cbworden/shakemap | [
"f0a49317ce3e98d8cce5ba148797ace47dd1d898",
"f0a49317ce3e98d8cce5ba148797ace47dd1d898",
"a0130bf03645cc635d48606560309bf65310506a",
"f0a49317ce3e98d8cce5ba148797ace47dd1d898",
"f0a49317ce3e98d8cce5ba148797ace47dd1d898",
"f0a49317ce3e98d8cce5ba148797ace47dd1d898",
"f0a49317ce3e98d8cce5ba148797ace47dd1d898"
] | [
"tests/shakelib/gmpe/nga_east_test.py",
"utils/get_sm_stations.py",
"shakemap/coremods/model.py",
"shakemap/coremods/info.py",
"utils/json2dict.py",
"shakelib/gmice/ak07.py",
"tests/shakelib/correlation/dummy_test.py"
] | [
"#!/usr/bin/env python\n\nimport os\nimport pickle\n\nimport numpy as np\n\nfrom openquake.hazardlib.gsim import base\nimport openquake.hazardlib.imt as imt\nfrom openquake.hazardlib.const import StdDev\n\nfrom shakelib.gmpe.nga_east import NGAEast\nfrom shakelib.multigmpe import stuff_context\n\nhome_dir = os.path.dirname(os.path.abspath(__file__))\ndata_dir = os.path.join(home_dir, \"nga_east_data\")\n\nstddev_types = [StdDev.TOTAL]\ngmpe = NGAEast()\n\ndx = base.DistancesContext()\ndx.rrup = np.logspace(-1, np.log10(2000), 100)\n\nrx = base.RuptureContext()\nsx = base.SitesContext()\n\nIMTS = [imt.PGA(), imt.PGV(), imt.SA(0.3), imt.SA(1.0), imt.SA(3.0)]\n\nMAGS = [3, 5, 6, 7]\n\nVS30 = [180, 380, 760, 2000]\n\n\ndef update_results():\n # To build the data for testing\n result = {}\n for i in IMTS:\n ikey = i.__str__()\n result[ikey] = {}\n for mag in MAGS:\n rx.mag = mag\n result[ikey][str(mag)] = {}\n for vs30 in VS30:\n sx.vs30 = np.full_like(dx.rrup, vs30)\n sx.sids = np.array(list(range(len(sx.vs30))))\n result[ikey][str(mag)][str(vs30)] = {}\n ctx = stuff_context(sx, rx, dx)\n lmean, lsd = gmpe.get_mean_and_stddevs(ctx, ctx, ctx, i, stddev_types)\n result[ikey][str(mag)][str(vs30)][\"lmean\"] = lmean.tolist()\n result[ikey][str(mag)][str(vs30)][\"lsd\"] = lsd[0].tolist()\n # Save results\n pkl_file = os.path.join(data_dir, \"nga_east_data.pkl\")\n fh = open(pkl_file, \"wb\")\n pickle.dump(result, fh)\n fh.close()\n\n\ndef test_nga_east():\n # Load test data\n pkl_file = os.path.join(data_dir, \"nga_east_data.pkl\")\n fh = open(pkl_file, \"rb\")\n target = pickle.load(fh)\n fh.close()\n for i in IMTS:\n ikey = i.__str__()\n for mag in MAGS:\n rx.mag = mag\n for vs30 in VS30:\n sx.vs30 = np.full_like(dx.rrup, vs30)\n sx.sids = np.array(list(range(len(sx.vs30))))\n ctx = stuff_context(sx, rx, dx)\n lmean, lsd = gmpe.get_mean_and_stddevs(ctx, ctx, ctx, i, stddev_types)\n tmean = np.array(target[ikey][str(mag)][str(vs30)][\"lmean\"])\n np.testing.assert_allclose(lmean, tmean, rtol=1e-6, atol=1e-6)\n tsd = np.array(target[ikey][str(mag)][str(vs30)][\"lsd\"])\n np.testing.assert_allclose(lsd[0], tsd, rtol=1e-6, atol=1e-6)\n\n\nif __name__ == \"__main__\":\n test_nga_east()\n",
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport json\nfrom collections import OrderedDict\nimport pandas as pd\n\nfrom libcomcat.search import get_event_by_id\n\n\ndef main():\n desc = \"Program to get CSV file of station data from ShakeMap.\"\n parser = argparse.ArgumentParser(description=desc)\n parser.add_argument(\"eventid\", help=\"Comcat event ID.\")\n args = parser.parse_args()\n evid = args.eventid\n\n # Download stationlist\n event = get_event_by_id(evid)\n shakemap = event.getProducts(\"shakemap\")[0]\n json_file = evid + \"_stationlist.json\"\n shakemap.getContent(\"stationlist.json\", json_file)\n with open(json_file) as f:\n station_dict = json.load(f)\n\n # Extract info in tabular form\n out_dict = OrderedDict()\n out_dict[\"lat\"] = []\n out_dict[\"lon\"] = []\n out_dict[\"rjb\"] = []\n out_dict[\"repi\"] = []\n out_dict[\"pga_percent_g\"] = []\n out_dict[\"pgv_cm_s\"] = []\n for f in station_dict[\"features\"]:\n if f[\"properties\"][\"station_type\"] == \"seismic\":\n out_dict[\"lon\"].append(f[\"geometry\"][\"coordinates\"][0])\n out_dict[\"lat\"].append(f[\"geometry\"][\"coordinates\"][1])\n out_dict[\"rjb\"].append(f[\"properties\"][\"distances\"][\"rjb\"])\n out_dict[\"repi\"].append(f[\"properties\"][\"distances\"][\"repi\"])\n out_dict[\"pga_percent_g\"].append(f[\"properties\"][\"pga\"])\n out_dict[\"pgv_cm_s\"].append(f[\"properties\"][\"pgv\"])\n\n out_file = evid + \"_stationlist.csv\"\n out_df = pd.DataFrame(out_dict)\n out_df.to_csv(out_file, index=False)\n\n\nif __name__ == \"__main__\":\n main()\n",
"\"\"\"\nProcess a ShakeMap, based on the configuration and data found in\nshake_data.hdf, and produce output in shake_result.hdf.\n\"\"\"\nimport os\nimport argparse\nimport inspect\nimport os.path\nimport time as time\nimport copy\nfrom time import gmtime, strftime\nimport shutil\nfrom datetime import date\nimport json\n\nimport numpy as np\nimport numpy.ma as ma\nfrom openquake.hazardlib import imt\nimport openquake.hazardlib.const as oqconst\nimport fiona\nimport cartopy.io.shapereader as shpreader\nfrom shapely.geometry import shape\n\nimport concurrent.futures as cf\n\n# local imports\nfrom mapio.geodict import GeoDict\nfrom mapio.grid2d import Grid2D\nfrom .base import CoreModule, Contents\nfrom shakelib.rupture.point_rupture import PointRupture\nfrom shakelib.sites import Sites\nfrom shakelib.distance import Distance, get_distance, get_distance_measures\nfrom shakelib.multigmpe import MultiGMPE\nfrom shakelib.virtualipe import VirtualIPE\nfrom shakelib.utils.utils import get_extent, thirty_sec_min, thirty_sec_max\nfrom shakelib.utils.imt_string import oq_to_file\nfrom shakelib.utils.containers import ShakeMapInputContainer\nfrom impactutils.io.smcontainers import ShakeMapOutputContainer\nfrom shakelib.rupture import constants\n\nfrom shakemap.utils.config import get_config_paths\nfrom shakemap.utils.utils import get_object_from_config\nfrom shakemap._version import get_versions\nfrom shakemap.utils.generic_amp import get_generic_amp_factors\nfrom shakemap.c.clib import make_sigma_matrix, geodetic_distance_fast, make_sd_array\n\n# from shakemap.utils.exception import TerminateShakeMap\n\nfrom shakelib.directivity.rowshandel2013 import Rowshandel2013\n\n#\n# default_stddev_inter: This is a stand-in for tau when the gmpe set\n# doesn't provide it. It is an educated guess based\n# on the NGA-west, Akkar et al, and BC Hydro gmpes.\n# It's not perfect, but probably isn't too far off.\n# It is only used when the GMPE(s) don't provide a\n# breakdown of the uncertainty terms. When used,\n# this value is multiplied by the total standard\n# deviation to get tau. The square of tau is then\n# subtracted from the squared total stddev and the\n# square root of the result is then used as the\n# within-event stddev (phi).\n#\nSM_CONSTS = {\"default_stddev_inter\": 0.55, \"default_stddev_inter_mmi\": 0.55}\n\n\nclass DataFrame:\n def __init__(self):\n df = None # noqa\n imts = None # noqa\n sx = None # noqa\n dx = None # noqa\n\n\nclass ModelModule(CoreModule):\n \"\"\"\n model -- Interpolate ground motions to a grid or list of locations.\n \"\"\"\n\n command_name = \"model\"\n targets = [r\"products/shake_result\\.hdf\"]\n dependencies = [(\"shake_data.hdf\", True)]\n\n no_seismic = False\n no_macroseismic = False\n no_rupture = False\n use_simulations = False\n\n rock_vs30 = 760.0\n soil_vs30 = 180.0\n\n def __init__(self, eventid):\n super(ModelModule, self).__init__(eventid)\n self.contents = Contents(None, None, eventid)\n #\n # Set up a bunch of dictionaries that will be keyed to IMTs\n #\n self.nominal_bias = {} # holds an average bias for each IMT\n self.psd_raw = {} # raw phi (intra-event stddev) of the output points\n self.psd = {} # phi (intra-event stddev) of the output points\n self.tsd = {} # tau (inter-event stddev) of the output points\n #\n # These are arrays (keyed by IMT) of the station data that will be\n # used to compute the bias and do the interpolation, they are filled\n # in the _fillDataArrays method\n #\n self.sta_per_ix = {}\n self.sta_lons_rad = {}\n self.sta_lats_rad = {}\n self.sta_resids = {}\n self.sta_phi = {}\n self.sta_tau = {}\n self.sta_sig_extra = {}\n self.sta_rrups = {}\n #\n # These are useful matrices that we compute in the bias function\n # that we can reuse in the MVN function\n #\n self.T_D = {}\n self.cov_WD_WD_inv = {}\n self.mu_H_yD = {}\n self.cov_HH_yD = {}\n #\n # Some variables and arrays used in both the bias and MVN functions\n #\n self.no_native_flag = {}\n self.imt_types = {}\n self.len_types = {}\n self.imt_Y_ind = {}\n #\n # These hold the main outputs of the MVN\n #\n self.outgrid = {} # Holds the interpolated output arrays keyed by IMT\n self.outsd = {} # Holds the standard deviation arrays keyed by IMT\n self.outphi = {} # Holds the intra-event standard deviation arrays\n self.outtau = {} # Holds the inter-event standard deviation arrays\n #\n # Places to put the results for the attenuation plots\n #\n self.atten_rock_mean = {}\n self.atten_soil_mean = {}\n self.atten_rock_sd = {}\n self.atten_soil_sd = {}\n\n def parseArgs(self, arglist):\n \"\"\"\n Set up the object to accept the --no_seismic, --no_macroseismic,\n and --no_rupture flags.\n \"\"\"\n parser = argparse.ArgumentParser(\n prog=self.__class__.command_name, description=inspect.getdoc(self.__class__)\n )\n parser.add_argument(\n \"-s\",\n \"--no_seismic\",\n action=\"store_true\",\n help=\"Exclude instrumental seismic data from \"\n \"the processing, ignoring any that may exist in \"\n \"the input directory.\",\n )\n parser.add_argument(\n \"-m\",\n \"--no_macroseismic\",\n action=\"store_true\",\n help=\"Exclude macroseismic data from the \"\n \"processing, ignoring any that may exist in the \"\n \"input directory.\",\n )\n parser.add_argument(\n \"-r\",\n \"--no_rupture\",\n action=\"store_true\",\n help=\"Exclude a rupture model from the \"\n \"processing, ignoring any that may exist in the \"\n \"input directory.\",\n )\n #\n # This line should be in any modules that overrides this\n # one. It will collect up everything after the current\n # modules options in args.rem, which should be returned\n # by this function. Note: doing parser.parse_known_args()\n # will not work as it will suck up any later modules'\n # options that are the same as this one's.\n #\n parser.add_argument(\"rem\", nargs=argparse.REMAINDER, help=argparse.SUPPRESS)\n args = parser.parse_args(arglist)\n if args.no_seismic:\n self.no_seismic = True\n if args.no_macroseismic:\n self.no_macroseismic = True\n if args.no_rupture:\n self.no_rupture = True\n return args.rem\n\n def execute(self):\n \"\"\"\n Interpolate ground motions to a grid or list of locations.\n\n Raises:\n NotADirectoryError: When the event data directory does not exist.\n FileNotFoundError: When the the shake_data HDF file does not exist.\n \"\"\"\n self.logger.debug(\"Starting model...\")\n # ---------------------------------------------------------------------\n # Make the input container and extract the config\n # ---------------------------------------------------------------------\n self._setInputContainer()\n self.config = self.ic.getConfig()\n\n self.sim_imt_paths = [x for x in self.ic.getArrays() if \"simulations\" in x]\n if len(self.sim_imt_paths):\n self.use_simulations = True\n\n self.config[\"use_simulations\"] = self.use_simulations\n\n # ---------------------------------------------------------------------\n # Clear away results from previous runs\n # ---------------------------------------------------------------------\n self._clearProducts()\n\n # ---------------------------------------------------------------------\n # Retrieve a bunch of config options and set them as attributes\n # ---------------------------------------------------------------------\n self._setConfigOptions()\n\n # ---------------------------------------------------------------------\n # Instantiate the gmpe, gmice, and ipe\n # Here we make a placeholder gmpe so that we can make the\n # rupture and distance contexts; later we'll make the\n # IMT-specific gmpes\n # ---------------------------------------------------------------------\n self.default_gmpe = MultiGMPE.__from_config__(self.config)\n\n self.gmice = get_object_from_config(\"gmice\", \"modeling\", self.config)\n\n if (\n self.config[\"ipe_modules\"][self.config[\"modeling\"][\"ipe\"]][0]\n == \"VirtualIPE\"\n ):\n pgv_imt = imt.from_string(\"PGV\")\n ipe_gmpe = MultiGMPE.__from_config__(self.config, filter_imt=pgv_imt)\n self.ipe = VirtualIPE.__fromFuncs__(ipe_gmpe, self.gmice)\n else:\n ipe = get_object_from_config(\"ipe\", \"modeling\", self.config)\n if \"vs30\" not in ipe.REQUIRES_SITES_PARAMETERS:\n # REQUIRES_SITES_PARAMETERS is now a frozen set so we have to\n # work around it\n tmpset = set(ipe.REQUIRES_SITES_PARAMETERS)\n tmpset.add(\"vs30\")\n ipe.REQUIRES_SITES_PARAMETERS = frozenset(tmpset)\n ipe.DEFINED_FOR_INTENSITY_MEASURE_COMPONENT = (\n oqconst.IMC.GREATER_OF_TWO_HORIZONTAL\n )\n self.ipe = MultiGMPE.__from_list__([ipe], [1.0])\n\n ipe_sd_types = self.ipe.DEFINED_FOR_STANDARD_DEVIATION_TYPES\n if len(ipe_sd_types) == 1:\n self.ipe_total_sd_only = True\n self.ipe_stddev_types = [oqconst.StdDev.TOTAL]\n else:\n self.ipe_total_sd_only = False\n self.ipe_stddev_types = [\n oqconst.StdDev.TOTAL,\n oqconst.StdDev.INTER_EVENT,\n oqconst.StdDev.INTRA_EVENT,\n ]\n\n # ---------------------------------------------------------------------\n # Get the rupture object and rupture context\n # ---------------------------------------------------------------------\n self.rupture_obj = self.ic.getRuptureObject()\n # If the --no_rupture flag is used, switch to a PointRupture\n if self.no_rupture:\n self.rupture_obj = PointRupture(self.rupture_obj._origin)\n if self.config[\"modeling\"][\"mechanism\"] is not None:\n self.rupture_obj._origin.setMechanism(\n mech=self.config[\"modeling\"][\"mechanism\"]\n )\n self.rx = self.rupture_obj.getRuptureContext([self.default_gmpe])\n # TODO: figure out how to not have to do this\n if self.rx.rake is None:\n self.rx.rake = 0\n\n #\n # Set up the coordinates for the attenuation curves\n #\n repi = np.logspace(-1, 3, 200)\n pt = self.rupture_obj._origin.getHypo()\n self.atten_coords = {\n \"lons\": np.full_like(repi, pt.x),\n \"lats\": np.array([pt.y + x / 111.0 for x in repi]),\n }\n self.point_source = PointRupture(self.rupture_obj._origin)\n\n # ---------------------------------------------------------------------\n # The output locations: either a grid or a list of points\n # ---------------------------------------------------------------------\n self.logger.debug(\"Setting output params...\")\n self._setOutputParams()\n\n landmask = self._getLandMask()\n # We used to do this, but we've decided not to. Leaving the code\n # in place in case we change our minds.\n # if landmask is not None and np.all(landmask):\n # raise TerminateShakeMap(\"Mapped area is entirely water\")\n\n # ---------------------------------------------------------------------\n # If the gmpe doesn't break down its stardard deviation into\n # within- and between-event terms, we need to handle things\n # somewhat differently.\n # ---------------------------------------------------------------------\n gmpe_sd_types = self.default_gmpe.DEFINED_FOR_STANDARD_DEVIATION_TYPES\n if len(gmpe_sd_types) == 1:\n self.gmpe_total_sd_only = True\n self.gmpe_stddev_types = [oqconst.StdDev.TOTAL]\n else:\n self.gmpe_total_sd_only = False\n self.gmpe_stddev_types = [\n oqconst.StdDev.TOTAL,\n oqconst.StdDev.INTER_EVENT,\n oqconst.StdDev.INTRA_EVENT,\n ]\n\n # ---------------------------------------------------------------------\n # Are we going to include directivity?\n # ---------------------------------------------------------------------\n # Config option?\n dir_conf = self.config[\"modeling\"][\"directivity\"]\n\n # Is the rupture not a point source?\n rup_check = not isinstance(self.rupture_obj, PointRupture)\n\n if dir_conf and rup_check:\n self.do_directivity = True\n # The following attribute will be used to store a list of tuples,\n # where each tuple will contain the 1) result of the directivity\n # model (for the periods defined by Rowshandel2013) and 2) the\n # associated distance context. The distance context is needed\n # within the _gmas function for figuring out which of the results\n # should be used when combining it with the GMPE result. We store\n # the pre-defined period first and interpolate later because there\n # is some optimization to doing it this way (some of the\n # calculation is period independent).\n self.dir_results = []\n # But if we want to save the results that were actually used for\n # each IMT, so we use a dictionary. This uses keys that are\n # the same as self.outgrid.\n self.dir_output = {}\n else:\n self.do_directivity = False\n\n # ---------------------------------------------------------------------\n # Station data: Create DataFrame(s) with the input data:\n # df1 for instrumented data\n # df2 for non-instrumented data\n # ---------------------------------------------------------------------\n self.logger.debug(\"Setting data frames...\")\n self._setDataFrames()\n\n # ---------------------------------------------------------------------\n # Add the predictions, etc. to the data frames\n # ---------------------------------------------------------------------\n self.logger.debug(\"Populating data frames...\")\n self._populateDataFrames()\n\n # ---------------------------------------------------------------------\n # Try to make all the derived IMTs possible from MMI (if we have MMI)\n # ---------------------------------------------------------------------\n self._deriveIMTsFromMMI()\n # ---------------------------------------------------------------------\n # Now make MMI from the station data where possible\n # ---------------------------------------------------------------------\n self._deriveMMIFromIMTs()\n\n self.logger.debug(\"Getting combined IMTs\")\n\n # ---------------------------------------------------------------------\n # Get the combined set of input and output IMTs, their periods,\n # and an index dictionary, then make the cross-correlation function\n # ---------------------------------------------------------------------\n if self.use_simulations:\n #\n # Ignore what is in the configuration and make maps only for the\n # IMTs that are in the set of simulations (and MMI).\n #\n self.combined_imt_set = set([x.split(\"/\")[-1] for x in self.sim_imt_paths])\n self.sim_df = {}\n for imtstr in self.combined_imt_set:\n dset, _ = self.ic.getArray([\"simulations\"], imtstr)\n self.sim_df[imtstr] = dset\n self.combined_imt_set |= set([\"MMI\"])\n else:\n self.combined_imt_set = self.imt_out_set.copy()\n for ndf in self.dataframes:\n self.combined_imt_set |= getattr(self, ndf).imts\n\n self.imt_per, self.imt_per_ix = _get_period_arrays(self.combined_imt_set)\n self.ccf = get_object_from_config(\"ccf\", \"modeling\", self.config, self.imt_per)\n\n self.logger.debug(\"Doing bias\")\n\n # ---------------------------------------------------------------------\n # Do the bias for all of the input and output IMTs. Hold on\n # to some of the products that will be used for the interpolation.\n # The \"raw\" values are the stddevs that have not been inflated by\n # the additional sigma (if any) of the point-source to finite\n # rupture approximation.\n # ---------------------------------------------------------------------\n\n # ---------------------------------------------------------------------\n # Do some prep, the bias, and the directivity prep\n # ---------------------------------------------------------------------\n self._fillDataArrays()\n\n self._computeBias()\n\n self._computeDirectivityPredictionLocations()\n\n # ---------------------------------------------------------------------\n # Now do the MVN with the intra-event residuals\n # ---------------------------------------------------------------------\n self.logger.debug(\"Doing MVN...\")\n if self.max_workers > 0:\n with cf.ThreadPoolExecutor(max_workers=self.max_workers) as ex:\n results = ex.map(self._computeMVN, self.imt_out_set)\n list(results) # Check threads for possible exceptions, etc.\n else:\n for imt_str in self.imt_out_set:\n self._computeMVN(imt_str)\n\n self._applyCustomMask()\n\n # ---------------------------------------------------------------------\n # Output the data and metadata\n # ---------------------------------------------------------------------\n product_path = os.path.join(self.datadir, \"products\")\n if not os.path.isdir(product_path):\n os.mkdir(product_path)\n oc = ShakeMapOutputContainer.create(\n os.path.join(product_path, \"shake_result.hdf\")\n )\n\n # ---------------------------------------------------------------------\n # Might as well stick the whole config in the result\n # ---------------------------------------------------------------------\n oc.setConfig(self.config)\n\n # ---------------------------------------------------------------------\n # We're going to need masked arrays of the output grids later, so\n # make them now.\n # ---------------------------------------------------------------------\n moutgrid = self._getMaskedGrids(landmask)\n\n # ---------------------------------------------------------------------\n # Get the info dictionary that will become info.json, and\n # store it in the output container\n # ---------------------------------------------------------------------\n info = self._getInfo(moutgrid)\n oc.setMetadata(info)\n\n # ---------------------------------------------------------------------\n # Add the rupture JSON as a text string\n # ---------------------------------------------------------------------\n oc.setRuptureDict(self.rupture_obj._geojson)\n\n # ---------------------------------------------------------------------\n # Fill the station dictionary for stationlist.json and add it to\n # the output container\n # ---------------------------------------------------------------------\n sjdict = self._fillStationJSON()\n oc.setStationDict(sjdict)\n\n # ---------------------------------------------------------------------\n # Add the output grids or points to the output; include some\n # metadata.\n # ---------------------------------------------------------------------\n if self.do_grid:\n self._storeGriddedData(oc)\n else:\n self._storePointData(oc)\n\n self._storeAttenuationData(oc)\n\n oc.close()\n self.ic.close()\n\n self.contents.addFile(\n \"shakemapHDF\",\n \"Comprehensive ShakeMap HDF Data File\",\n \"HDF file containing all ShakeMap results.\",\n \"shake_result.hdf\",\n \"application/x-bag\",\n )\n\n # -------------------------------------------------------------------------\n # End execute()\n # -------------------------------------------------------------------------\n\n def _setInputContainer(self):\n \"\"\"\n Open the input container and set\n the event's current data directory.\n\n Raises:\n NotADirectoryError: When the event data directory does not exist.\n FileNotFoundError: When the the shake_data HDF file does not exist.\n \"\"\"\n #\n # Find the shake_data.hdf file\n #\n _, data_path = get_config_paths()\n datadir = os.path.join(data_path, self._eventid, \"current\")\n if not os.path.isdir(datadir):\n raise NotADirectoryError(f\"{datadir} is not a valid directory.\")\n\n datafile = os.path.join(datadir, \"shake_data.hdf\")\n if not os.path.isfile(datafile):\n raise FileNotFoundError(f\"{datafile} does not exist.\")\n self.datadir = datadir\n self.ic = ShakeMapInputContainer.load(datafile)\n\n def _clearProducts(self):\n \"\"\"\n Function to delete an event's products directory if it exists.\n\n Returns:\n nothing\n \"\"\"\n products_path = os.path.join(self.datadir, \"products\")\n if os.path.isdir(products_path):\n shutil.rmtree(products_path, ignore_errors=True)\n pdl_path = os.path.join(self.datadir, \"pdl\")\n if os.path.isdir(pdl_path):\n shutil.rmtree(pdl_path, ignore_errors=True)\n\n def _setConfigOptions(self):\n \"\"\"\n Pull various useful configuration options out of the config\n dictionary.\n\n Returns:\n nothing\n \"\"\"\n # ---------------------------------------------------------------------\n # Processing parameters\n # ---------------------------------------------------------------------\n self.max_workers = self.config[\"system\"][\"max_workers\"]\n\n # ---------------------------------------------------------------------\n # Do we apply the generic amplification factors?\n # ---------------------------------------------------------------------\n self.apply_gafs = self.config[\"modeling\"][\"apply_generic_amp_factors\"]\n\n # ---------------------------------------------------------------------\n # Bias parameters\n # ---------------------------------------------------------------------\n self.do_bias = self.config[\"modeling\"][\"bias\"][\"do_bias\"]\n self.bias_max_range = self.config[\"modeling\"][\"bias\"][\"max_range\"]\n self.bias_max_mag = self.config[\"modeling\"][\"bias\"][\"max_mag\"]\n self.bias_max_dsigma = self.config[\"modeling\"][\"bias\"][\"max_delta_sigma\"]\n\n # ---------------------------------------------------------------------\n # Outlier parameters\n # ---------------------------------------------------------------------\n self.do_outliers = self.config[\"data\"][\"outlier\"][\"do_outliers\"]\n self.outlier_deviation_level = self.config[\"data\"][\"outlier\"][\"max_deviation\"]\n self.outlier_max_mag = self.config[\"data\"][\"outlier\"][\"max_mag\"]\n self.outlier_valid_stations = self.config[\"data\"][\"outlier\"][\"valid_stations\"]\n\n # ---------------------------------------------------------------------\n # These are the IMTs we want to make\n # ---------------------------------------------------------------------\n self.imt_out_set = set(self.config[\"interp\"][\"imt_list\"])\n\n # ---------------------------------------------------------------------\n # The x and y resolution of the output grid\n # ---------------------------------------------------------------------\n self.smdx = self.config[\"interp\"][\"prediction_location\"][\"xres\"]\n self.smdy = self.config[\"interp\"][\"prediction_location\"][\"yres\"]\n self.nmax = self.config[\"interp\"][\"prediction_location\"][\"nmax\"]\n\n # ---------------------------------------------------------------------\n # Get the Vs30 file name\n # ---------------------------------------------------------------------\n self.vs30default = self.config[\"data\"][\"vs30default\"]\n self.vs30_file = self.config[\"data\"][\"vs30file\"]\n if not self.vs30_file:\n self.vs30_file = None\n self.mask_file = self.config[\"data\"][\"maskfile\"]\n if not self.mask_file:\n self.mask_file = None\n\n def _setOutputParams(self):\n \"\"\"\n Set variables dealing with the output grid or points\n\n Returns:\n nothing\n \"\"\"\n if self.use_simulations:\n self.do_grid = True\n imt_grp = self.sim_imt_paths[0]\n groups = imt_grp.split(\"/\")\n myimt = groups[-1]\n del groups[-1]\n data, geodict = self.ic.getArray(groups, myimt)\n self.W = geodict[\"xmin\"]\n self.E = geodict[\"xmax\"]\n self.S = geodict[\"ymin\"]\n self.N = geodict[\"ymax\"]\n self.smdx = geodict[\"dx\"]\n self.smdy = geodict[\"dy\"]\n\n self.sites_obj_out = Sites.fromBounds(\n self.W,\n self.E,\n self.S,\n self.N,\n self.smdx,\n self.smdy,\n defaultVs30=self.vs30default,\n vs30File=self.vs30_file,\n padding=True,\n resample=True,\n )\n self.smnx, self.smny = self.sites_obj_out.getNxNy()\n self.sx_out = self.sites_obj_out.getSitesContext()\n lons, lats = np.meshgrid(self.sx_out.lons, self.sx_out.lats)\n self.sx_out.lons = lons.copy()\n self.sx_out.lats = lats.copy()\n self.lons = lons.flatten()\n self.lats = lats.flatten()\n self.depths = np.zeros_like(lats)\n dist_obj_out = Distance.fromSites(\n self.default_gmpe, self.sites_obj_out, self.rupture_obj\n )\n elif (\n self.config[\"interp\"][\"prediction_location\"][\"file\"]\n and self.config[\"interp\"][\"prediction_location\"][\"file\"] != \"None\"\n ):\n #\n # FILE: Open the file and get the output points\n #\n self.do_grid = False\n in_sites = np.genfromtxt(\n self.config[\"interp\"][\"prediction_location\"][\"file\"],\n autostrip=True,\n unpack=True,\n dtype=[np.double, np.double, np.double, \"<U80\"],\n )\n if np.size(in_sites) == 0:\n self.logger.info(\"Points file is empty; nothing to do\")\n return\n elif np.size(in_sites) == 1:\n lons, lats, vs30, idents = in_sites.item()\n self.idents = [idents]\n else:\n try:\n lons, lats, vs30, self.idents = zip(*in_sites)\n except Exception:\n lons, lats, vs30, self.idents = zip(in_sites)\n self.lons = np.array(lons).reshape(1, -1)\n self.lats = np.array(lats).reshape(1, -1)\n self.vs30 = np.array(vs30).reshape(1, -1)\n self.depths = np.zeros_like(self.lats)\n self.W = thirty_sec_min(np.min(self.lons))\n self.E = thirty_sec_max(np.max(self.lons))\n self.S = thirty_sec_min(np.min(self.lats))\n self.N = thirty_sec_max(np.max(self.lats))\n self.smnx = np.size(self.lons)\n self.smny = 1\n dist_obj_out = Distance(\n self.default_gmpe, self.lons, self.lats, self.depths, self.rupture_obj\n )\n\n self.sites_obj_out = Sites.fromBounds(\n self.W,\n self.E,\n self.S,\n self.N,\n self.smdx,\n self.smdy,\n defaultVs30=self.vs30default,\n vs30File=self.vs30_file,\n padding=True,\n resample=True,\n )\n\n self.sx_out = self.sites_obj_out.getSitesContext(\n {\"lats\": self.lats, \"lons\": self.lons}\n )\n # Replace the Vs30 from the grid (or default) with the Vs30\n # provided with the site list.\n if np.any(self.vs30 > 0):\n self.sx_out.vs30 = self.vs30\n Sites._addDepthParameters(self.sx_out)\n else:\n #\n # GRID: Figure out the grid parameters and get output points\n #\n self.do_grid = True\n\n if self.config[\"interp\"][\"prediction_location\"][\"extent\"]:\n self.W, self.S, self.E, self.N = self.config[\"interp\"][\n \"prediction_location\"\n ][\"extent\"]\n else:\n self.W, self.E, self.S, self.N = get_extent(\n self.rupture_obj, config=self.config\n )\n\n # Adjust resolution to be under nmax\n self._adjustResolution()\n\n self.sites_obj_out = Sites.fromBounds(\n self.W,\n self.E,\n self.S,\n self.N,\n self.smdx,\n self.smdy,\n defaultVs30=self.vs30default,\n vs30File=self.vs30_file,\n padding=True,\n resample=True,\n )\n self.smnx, self.smny = self.sites_obj_out.getNxNy()\n self.sx_out = self.sites_obj_out.getSitesContext()\n lons, lats = np.meshgrid(self.sx_out.lons, self.sx_out.lats)\n self.sx_out.lons = lons.copy()\n self.sx_out.lats = lats.copy()\n self.lons = lons.flatten()\n self.lats = lats.flatten()\n self.depths = np.zeros_like(lats)\n dist_obj_out = Distance.fromSites(\n self.default_gmpe, self.sites_obj_out, self.rupture_obj\n )\n\n #\n # TODO: This will break if the IPE needs distance measures\n # that the GMPE doesn't; should make this a union of the\n # requirements of both\n #\n self.dx_out = dist_obj_out.getDistanceContext()\n #\n # Set up the sites and distance contexts for the attenuation curves\n #\n self.atten_sx_rock = self.sites_obj_out.getSitesContext(\n self.atten_coords, rock_vs30=self.rock_vs30\n )\n self.atten_sx_soil = self.sites_obj_out.getSitesContext(\n self.atten_coords, rock_vs30=self.soil_vs30\n )\n self.atten_dx = Distance(\n self.default_gmpe,\n self.atten_coords[\"lons\"],\n self.atten_coords[\"lats\"],\n np.zeros_like(self.atten_coords[\"lons\"]),\n rupture=self.point_source,\n ).getDistanceContext()\n\n self.lons_out_rad = np.radians(self.lons).flatten()\n self.lats_out_rad = np.radians(self.lats).flatten()\n self.flip_lons = False\n if self.W > 0 and self.E < 0:\n self.flip_lons = True\n self.lons_out_rad[self.lons_out_rad < 0] += 2 * np.pi\n\n def _setDataFrames(self):\n \"\"\"\n Extract the StationList object from the input container and\n fill the DataFrame class and keep a list of dataframes.\n\n - df1 holds the instrumented data (PGA, PGV, SA)\n - df2 holds the non-instrumented data (MMI)\n \"\"\"\n self.dataframes = []\n try:\n self.stations = self.ic.getStationList()\n except AttributeError:\n return\n if self.stations is None:\n return\n for dfid, val in ((\"df1\", True), (\"df2\", False)):\n if dfid == \"df1\" and self.no_seismic:\n continue\n if dfid == \"df2\" and self.no_macroseismic:\n continue\n sdf, imts = self.stations.getStationDictionary(instrumented=val)\n if sdf is not None:\n df = DataFrame()\n df.df = sdf\n df.imts = imts\n setattr(self, dfid, df)\n self.dataframes.append(dfid)\n\n # Flag the stations in the bad stations list from the config\n if not hasattr(self, \"df1\"):\n return\n evdt = date(\n self.rupture_obj._origin.time.year,\n self.rupture_obj._origin.time.month,\n self.rupture_obj._origin.time.day,\n )\n nostart = date(1970, 1, 1)\n self.df1.df[\"flagged\"] = np.full_like(self.df1.df[\"lon\"], 0, dtype=np.bool)\n if \"bad_stations\" not in self.config[\"data\"]:\n return\n for sid, dates in self.config[\"data\"][\"bad_stations\"].items():\n ondate, offdate = dates.split(\":\")\n year, month, day = map(int, ondate.split(\"-\"))\n ondt = date(year, month, day)\n if offdate:\n year, month, day = map(int, offdate.split(\"-\"))\n offdt = date(year, month, day)\n else:\n offdt = None\n bad = False\n if (ondt == nostart or ondt <= evdt) and (offdt is None or offdt >= evdt):\n bad = True\n if bad:\n self.df1.df[\"flagged\"] |= self.df1.df[\"id\"] == sid\n\n def _populateDataFrames(self):\n \"\"\"\n Make the sites and distance contexts for each dataframe then\n compute the predictions for the IMTs in that dataframe.\n \"\"\"\n for dfid in self.dataframes:\n dfn = getattr(self, dfid)\n df = dfn.df\n # -----------------------------------------------------------------\n # Get the sites and distance contexts\n # -----------------------------------------------------------------\n df[\"depth\"] = np.zeros_like(df[\"lon\"])\n lldict = {\"lons\": df[\"lon\"], \"lats\": df[\"lat\"]}\n dfn.sx = self.sites_obj_out.getSitesContext(lldict)\n dfn.sx_rock = copy.deepcopy(dfn.sx)\n dfn.sx_rock.vs30 = np.full_like(dfn.sx.vs30, self.rock_vs30)\n dfn.sx_soil = copy.deepcopy(dfn.sx)\n dfn.sx_soil.vs30 = np.full_like(dfn.sx.vs30, self.soil_vs30)\n dist_obj = Distance(\n self.default_gmpe, df[\"lon\"], df[\"lat\"], df[\"depth\"], self.rupture_obj\n )\n dfn.dx = dist_obj.getDistanceContext()\n\n # -----------------------------------------------------------------\n # Are we doing directivity?\n # -----------------------------------------------------------------\n if self.do_directivity is True:\n self.logger.info(f\"Directivity for {dfid}...\")\n time1 = time.time()\n dir_df = Rowshandel2013(\n self.rupture_obj._origin,\n self.rupture_obj,\n df[\"lat\"].reshape((1, -1)),\n df[\"lon\"].reshape((1, -1)),\n df[\"depth\"].reshape((1, -1)),\n dx=1.0,\n T=Rowshandel2013.getPeriods(),\n a_weight=0.5,\n mtype=1,\n )\n self.dir_results.append((dir_df, dfn.dx))\n directivity_time = time.time() - time1\n self.logger.debug(\n f\"Directivity {dfid} evaluation time: {directivity_time:f} sec\"\n )\n\n # -----------------------------------------------------------------\n # Do the predictions and other bookkeeping for each IMT\n # -----------------------------------------------------------------\n imt_set = self.imt_out_set | set(dfn.imts)\n for imtstr in imt_set:\n oqimt = imt.from_string(imtstr)\n gmpe = None\n not_supported = False\n if imtstr != \"MMI\":\n try:\n gmpe = MultiGMPE.__from_config__(self.config, filter_imt=oqimt)\n except KeyError:\n self.logger.warn(\n f\"Input IMT {imtstr} not supported by GMPE: ignoring\"\n )\n not_supported = True\n if not_supported:\n pmean = np.full_like(df[imtstr], np.nan)\n pmean_rock = np.full_like(df[imtstr], np.nan)\n pmean_soil = np.full_like(df[imtstr], np.nan)\n pstddev = [None] * 3\n pstddev[0] = np.full_like(df[imtstr], np.nan)\n pstddev[1] = np.full_like(df[imtstr], np.nan)\n pstddev[2] = np.full_like(df[imtstr], np.nan)\n pstddev_rock = [None] * 1\n pstddev_soil = [None] * 1\n pstddev_rock[0] = np.full_like(df[imtstr], np.nan)\n pstddev_soil[0] = np.full_like(df[imtstr], np.nan)\n else:\n pmean, pstddev = self._gmas(\n gmpe, dfn.sx, dfn.dx, oqimt, self.apply_gafs\n )\n pmean_rock, pstddev_rock = self._gmas(\n gmpe, dfn.sx_rock, dfn.dx, oqimt, self.apply_gafs\n )\n pmean_soil, pstddev_soil = self._gmas(\n gmpe, dfn.sx_soil, dfn.dx, oqimt, self.apply_gafs\n )\n df[imtstr + \"_pred\"] = pmean\n df[imtstr + \"_pred_sigma\"] = pstddev[0]\n df[imtstr + \"_pred_rock\"] = pmean_rock\n df[imtstr + \"_pred_sigma_rock\"] = pstddev_rock[0]\n df[imtstr + \"_pred_soil\"] = pmean_soil\n df[imtstr + \"_pred_sigma_soil\"] = pstddev_soil[0]\n\n if imtstr != \"MMI\":\n total_only = self.gmpe_total_sd_only\n tau_guess = SM_CONSTS[\"default_stddev_inter\"]\n else:\n total_only = self.ipe_total_sd_only\n tau_guess = SM_CONSTS[\"default_stddev_inter_mmi\"]\n if total_only:\n df[imtstr + \"_pred_tau\"] = tau_guess * pstddev[0]\n df[imtstr + \"_pred_phi\"] = np.sqrt(\n pstddev[0] ** 2 - df[imtstr + \"_pred_tau\"] ** 2\n )\n else:\n df[imtstr + \"_pred_tau\"] = pstddev[1]\n df[imtstr + \"_pred_phi\"] = pstddev[2]\n #\n # If we're just computing the predictions of an output\n # IMT, then we can skip the residual and outlier stuff\n #\n if imtstr not in df:\n continue\n #\n # Compute the total residual\n #\n df[imtstr + \"_residual\"] = df[imtstr] - df[imtstr + \"_pred\"]\n # -------------------------------------------------------------\n # Do the outlier flagging if we have a fault, or we don't\n # have a fault but the event magnitude is under the limit\n # -------------------------------------------------------------\n if self.do_outliers and (\n not isinstance(self.rupture_obj, PointRupture)\n or self.rx.mag <= self.outlier_max_mag\n ):\n #\n # Make a boolean array of stations that have been\n # manually rehabilitated by the operator\n #\n is_valid = np.full(np.shape(df[\"id\"]), False, dtype=bool)\n for valid in self.outlier_valid_stations:\n is_valid |= valid == df[\"id\"]\n #\n # turn off nan warnings for this statement\n #\n np.seterr(invalid=\"ignore\")\n flagged = (\n np.abs(df[imtstr + \"_residual\"])\n > self.outlier_deviation_level * df[imtstr + \"_pred_sigma\"]\n ) & (~is_valid)\n np.seterr(invalid=\"warn\")\n #\n # Add NaN values to the list of outliers\n #\n flagged |= np.isnan(df[imtstr + \"_residual\"])\n\n self.logger.debug(\n \"IMT: %s, flagged: %d\" % (imtstr, np.sum(flagged))\n )\n df[imtstr + \"_outliers\"] = flagged\n else:\n #\n # Not doing outliers, but should still flag NaNs\n #\n flagged = np.isnan(df[imtstr + \"_residual\"])\n df[imtstr + \"_outliers\"] = flagged\n #\n # If uncertainty hasn't been set for MMI, give it\n # the default value\n #\n if imtstr == \"MMI\" and all(df[\"MMI_sd\"] == 0):\n df[\"MMI_sd\"][:] = self.config[\"data\"][\"default_mmi_stddev\"]\n #\n # Get the lons/lats in radians while we're at it\n #\n df[\"lon_rad\"] = np.radians(df[\"lon\"])\n df[\"lat_rad\"] = np.radians(df[\"lat\"])\n if self.flip_lons:\n df[\"lon_rad\"][df[\"lon_rad\"] < 0] += 2 * np.pi\n #\n # It will be handy later on to have the rupture distance\n # in the dataframes\n #\n dd = get_distance(\n [\"rrup\"], df[\"lat\"], df[\"lon\"], df[\"depth\"], self.rupture_obj\n )\n df[\"rrup\"] = dd[\"rrup\"]\n if dd[\"rrup_var\"] is not None:\n df[\"rrup_var\"] = dd[\"rrup_var\"]\n else:\n df[\"rrup_var\"] = np.zeros_like(dd[\"rrup\"])\n\n def _deriveIMTsFromMMI(self):\n \"\"\"\n Compute all the IMTs possible from MMI\n TODO: This logic needs to be revisited. We should probably make what\n we have to to do the CMS to make the needed output IMTs, but\n for now, we're just going to use what we have and the ccf.\n \"\"\"\n if \"df2\" not in self.dataframes:\n return\n\n df2 = self.df2.df\n for gmice_imt in self.gmice.DEFINED_FOR_INTENSITY_MEASURE_TYPES:\n if imt.SA == gmice_imt:\n iterlist = self.gmice.DEFINED_FOR_SA_PERIODS\n else:\n iterlist = [None]\n for period in iterlist:\n if period:\n oqimt = gmice_imt(period)\n else:\n oqimt = gmice_imt()\n imtstr = str(oqimt)\n\n np.seterr(invalid=\"ignore\")\n df2[imtstr], _ = self.gmice.getGMfromMI(\n df2[\"MMI\"], oqimt, dists=df2[\"rrup\"], mag=self.rx.mag\n )\n df2[imtstr][\n df2[\"MMI\"] < self.config[\"data\"][\"min_mmi_convert\"]\n ] = np.nan\n np.seterr(invalid=\"warn\")\n df2[imtstr + \"_sd\"] = np.full_like(\n df2[\"MMI\"], self.gmice.getMI2GMsd()[oqimt]\n )\n self.df2.imts.add(imtstr)\n #\n # Get the predictions and stddevs\n #\n not_supported = False\n try:\n gmpe = MultiGMPE.__from_config__(self.config, filter_imt=oqimt)\n except KeyError:\n self.logger.warn(\n f\"Input IMT {imtstr} not supported by GMPE: ignoring\"\n )\n not_supported = True\n if not_supported:\n pmean = np.full_like(df2[\"MMI\"], np.nan)\n pstddev = [None] * 3\n pstddev[0] = np.full_like(df2[\"MMI\"], np.nan)\n pstddev[1] = np.full_like(df2[\"MMI\"], np.nan)\n pstddev[2] = np.full_like(df2[\"MMI\"], np.nan)\n else:\n pmean, pstddev = self._gmas(\n gmpe, self.df2.sx, self.df2.dx, oqimt, self.apply_gafs\n )\n pmean_rock, pstddev_rock = self._gmas(\n gmpe, self.df2.sx_rock, self.df2.dx, oqimt, self.apply_gafs\n )\n pmean_soil, pstddev_soil = self._gmas(\n gmpe, self.df2.sx_soil, self.df2.dx, oqimt, self.apply_gafs\n )\n df2[imtstr + \"_pred\"] = pmean\n df2[imtstr + \"_pred_sigma\"] = pstddev[0]\n df2[imtstr + \"_pred_rock\"] = pmean_rock\n df2[imtstr + \"_pred_sigma_rock\"] = pstddev_rock[0]\n df2[imtstr + \"_pred_soil\"] = pmean_soil\n df2[imtstr + \"_pred_sigma_soil\"] = pstddev_soil[0]\n if imtstr != \"MMI\":\n total_only = self.gmpe_total_sd_only\n tau_guess = SM_CONSTS[\"default_stddev_inter\"]\n else:\n total_only = self.ipe_total_sd_only\n tau_guess = SM_CONSTS[\"default_stddev_inter_mmi\"]\n if total_only:\n df2[imtstr + \"_pred_tau\"] = tau_guess * pstddev[0]\n df2[imtstr + \"_pred_phi\"] = np.sqrt(\n pstddev[0] ** 2 - df2[imtstr + \"_pred_tau\"] ** 2\n )\n else:\n df2[imtstr + \"_pred_tau\"] = pstddev[1]\n df2[imtstr + \"_pred_phi\"] = pstddev[2]\n df2[imtstr + \"_residual\"] = df2[imtstr] - pmean\n df2[imtstr + \"_outliers\"] = np.isnan(df2[imtstr + \"_residual\"])\n df2[imtstr + \"_outliers\"] |= df2[\"MMI_outliers\"]\n\n def _deriveMMIFromIMTs(self):\n \"\"\"\n Make derived MMI from each of the IMTs in the input (for\n which the GMICE is defined; then select the best MMI for\n each station based on a list of \"preferred\" IMTs; also\n calculate the predicted MMI and the residual.\n \"\"\"\n if \"df1\" not in self.dataframes:\n return\n df1 = self.df1.df\n gmice_imts = [\n imt.__name__ for imt in self.gmice.DEFINED_FOR_INTENSITY_MEASURE_TYPES\n ]\n gmice_pers = self.gmice.DEFINED_FOR_SA_PERIODS\n np.seterr(invalid=\"ignore\")\n df1[\"MMI\"] = self.gmice.getPreferredMI(df1, dists=df1[\"rrup\"], mag=self.rx.mag)\n np.seterr(invalid=\"warn\")\n df1[\"MMI_sd\"] = self.gmice.getPreferredSD()\n if df1[\"MMI_sd\"] is not None:\n df1[\"MMI_sd\"] = np.full_like(df1[\"lon\"], df1[\"MMI_sd\"])\n for imtstr in self.df1.imts:\n oqimt = imt.from_string(imtstr)\n if not oqimt.string in gmice_imts:\n continue\n if \"SA\" in oqimt.string and oqimt.period not in gmice_pers:\n continue\n\n np.seterr(invalid=\"ignore\")\n df1[\"derived_MMI_from_\" + imtstr], _ = self.gmice.getMIfromGM(\n df1[imtstr], oqimt, dists=df1[\"rrup\"], mag=self.rx.mag\n )\n np.seterr(invalid=\"warn\")\n df1[\"derived_MMI_from_\" + imtstr + \"_sd\"] = np.full_like(\n df1[imtstr], self.gmice.getGM2MIsd()[oqimt]\n )\n\n preferred_imts = [\"PGV\", \"PGA\", \"SA(1.0)\", \"SA(0.3)\", \"SA(3.0\"]\n if df1[\"MMI\"] is None:\n df1[\"MMI\"] = np.full_like(df1[\"lon\"], np.nan)\n df1[\"MMI_sd\"] = np.full_like(df1[\"lon\"], np.nan)\n df1[\"MMI_outliers\"] = np.full_like(df1[\"lon\"], True, dtype=np.bool)\n for imtstr in preferred_imts:\n if \"derived_MMI_from_\" + imtstr in df1:\n ixx = (np.isnan(df1[\"MMI\"]) | df1[\"MMI_outliers\"]) & ~(\n np.isnan(df1[\"derived_MMI_from_\" + imtstr])\n | df1[imtstr + \"_outliers\"]\n )\n df1[\"MMI\"][ixx] = df1[\"derived_MMI_from_\" + imtstr][ixx]\n df1[\"MMI_sd\"][ixx] = df1[\"derived_MMI_from_\" + imtstr + \"_sd\"][ixx]\n df1[\"MMI_outliers\"][ixx] = False\n self.df1.imts.add(\"MMI\")\n #\n # Get the prediction and stddevs\n #\n gmpe = None\n pmean, pstddev = self._gmas(\n gmpe, self.df1.sx, self.df1.dx, imt.from_string(\"MMI\"), self.apply_gafs\n )\n pmean_rock, pstddev_rock = self._gmas(\n gmpe, self.df1.sx_rock, self.df1.dx, imt.from_string(\"MMI\"), self.apply_gafs\n )\n pmean_soil, pstddev_soil = self._gmas(\n gmpe, self.df1.sx_soil, self.df1.dx, imt.from_string(\"MMI\"), self.apply_gafs\n )\n df1[\"MMI\" + \"_pred\"] = pmean\n df1[\"MMI\" + \"_pred_sigma\"] = pstddev[0]\n df1[\"MMI\" + \"_pred_rock\"] = pmean_rock\n df1[\"MMI\" + \"_pred_sigma_rock\"] = pstddev_rock[0]\n df1[\"MMI\" + \"_pred_soil\"] = pmean_soil\n df1[\"MMI\" + \"_pred_sigma_soil\"] = pstddev_soil[0]\n if self.ipe_total_sd_only:\n tau_guess = SM_CONSTS[\"default_stddev_inter_mmi\"]\n df1[\"MMI\" + \"_pred_tau\"] = tau_guess * pstddev[0]\n df1[\"MMI\" + \"_pred_phi\"] = np.sqrt(\n pstddev[0] ** 2 - df1[\"MMI\" + \"_pred_tau\"] ** 2\n )\n else:\n df1[\"MMI\" + \"_pred_tau\"] = pstddev[1]\n df1[\"MMI\" + \"_pred_phi\"] = pstddev[2]\n df1[\"MMI\" + \"_residual\"] = df1[\"MMI\"] - pmean\n df1[\"MMI\" + \"_outliers\"] |= np.isnan(df1[\"MMI\" + \"_residual\"])\n\n def _fillDataArrays(self):\n \"\"\"\n For each IMT get lists of the amplitudes that can contribute\n to the bias and the interpolation. Keep lists of IMT, period\n index, lons, lats, residuals, tau, phi, additional uncertainty,\n and rupture distance.\n \"\"\"\n imtsets = {}\n sasets = {}\n for ndf in (\"df1\", \"df2\"):\n df = getattr(self, ndf, None)\n if df is None:\n continue\n imtsets[ndf], sasets[ndf] = _get_imt_lists(df)\n\n for imtstr in self.imt_out_set:\n #\n # Fill the station arrays; here we use lists and append to\n # them because it is much faster than appending to a numpy\n # array; after the loop, the lists are converted to numpy\n # arrays:\n #\n lons_rad = [] # longitude (in radians) of the input station\n lats_rad = [] # latitude (in radians) of the input station\n resids = [] # The residual of the input IMT\n tau = [] # The between-event stddev of the input IMT\n phi = [] # The within-event stddev of the input IMT\n sig_extra = [] # Additional stddev of the input IMT\n rrups = [] # The rupture distance of the input station\n per_ix = []\n for ndf in (\"df1\", \"df2\"):\n tdf = getattr(self, ndf, None)\n if tdf is None:\n continue\n sdf = tdf.df\n for i in range(np.size(sdf[\"lon\"])):\n #\n # Each station can provide 0, 1, or 2 IMTs:\n #\n for imtin in _get_nearest_imts(\n imtstr, imtsets[ndf][i], sasets[ndf][i]\n ):\n per_ix.append(self.imt_per_ix[imtin])\n lons_rad.append(sdf[\"lon_rad\"][i])\n lats_rad.append(sdf[\"lat_rad\"][i])\n resids.append(sdf[imtin + \"_residual\"][i])\n tau.append(sdf[imtin + \"_pred_tau\"][i])\n phi.append(sdf[imtin + \"_pred_phi\"][i])\n sig_extra.append(sdf[imtin + \"_sd\"][i])\n rrups.append(sdf[\"rrup\"][i])\n\n self.sta_per_ix[imtstr] = np.array(per_ix)\n self.sta_lons_rad[imtstr] = np.array(lons_rad)\n self.sta_lats_rad[imtstr] = np.array(lats_rad)\n if self.flip_lons:\n self.sta_lons_rad[imtstr][self.sta_lons_rad[imtstr] < 0] += 2 * np.pi\n self.sta_resids[imtstr] = np.array(resids).reshape((-1, 1))\n self.sta_tau[imtstr] = np.array(tau).reshape((-1, 1))\n self.sta_phi[imtstr] = np.array(phi).reshape((-1, 1))\n self.sta_sig_extra[imtstr] = np.array(sig_extra)\n self.sta_rrups[imtstr] = np.array(rrups)\n\n def _computeBias(self):\n \"\"\"\n Compute a bias for all of the IMTs in the outputs\n \"\"\"\n for imtstr in self.imt_out_set:\n time1 = time.time()\n #\n # Get the index of the (pseudo-) period of the output IMT\n #\n outperiod_ix = self.imt_per_ix[imtstr]\n #\n # Get the data and distance-limited residuals for computing\n # the bias\n #\n sta_per_ix = self.sta_per_ix[imtstr]\n sta_lons_rad = self.sta_lons_rad[imtstr]\n sta_lats_rad = self.sta_lats_rad[imtstr]\n sta_tau = self.sta_tau[imtstr]\n sta_phi = self.sta_phi[imtstr]\n sta_sig_extra = self.sta_sig_extra[imtstr]\n\n dix = self.sta_rrups[imtstr] > self.bias_max_range\n sta_resids_dl = self.sta_resids[imtstr].copy()\n if len(dix) > 0:\n sta_resids_dl[dix] = 0.0\n #\n # If there are no stations, bail out\n #\n nsta = np.size(sta_lons_rad)\n if nsta == 0:\n self.mu_H_yD[imtstr] = 0.0\n self.cov_HH_yD[imtstr] = 0.0\n self.nominal_bias[imtstr] = 0.0\n nom_variance = 0.0\n bias_time = time.time() - time1\n #\n # Write the nominal values of the bias and its stddev to log\n #\n self.logger.debug(\n \"%s: nom bias %f nom stddev %f; %d stations (time=%f sec)\"\n % (\n imtstr,\n self.nominal_bias[imtstr],\n np.sqrt(nom_variance),\n nsta,\n bias_time,\n )\n )\n continue\n #\n # Set up the IMT indices\n #\n imt_types = np.sort(np.unique(sta_per_ix))\n len_types = len(imt_types)\n self.imt_types[imtstr] = imt_types\n self.len_types[imtstr] = len_types\n sa_inds = {}\n for i in range(len_types):\n sa_inds[imt_types[i]] = np.where(sta_per_ix == imt_types[i])[0]\n\n if outperiod_ix not in imt_types:\n self.no_native_flag[imtstr] = True\n imt_types_alt = np.sort(\n np.concatenate([imt_types, np.array([outperiod_ix])])\n )\n self.imt_Y_ind[imtstr] = np.where(outperiod_ix == imt_types_alt)[0][0]\n else:\n self.no_native_flag[imtstr] = False\n #\n # Build T_D and corr_HH_D\n #\n if self.no_native_flag[imtstr] is False:\n T_D = np.zeros((nsta, len_types))\n for i in range(len_types):\n T_D[sa_inds[imt_types[i]], i] = sta_tau[sa_inds[imt_types[i]], 0]\n corr_HH_D = np.zeros((len_types, len_types))\n ones = np.ones(len_types, dtype=np.long).reshape((-1, 1))\n t1 = imt_types.reshape((1, -1)) * ones\n t2 = imt_types.reshape((-1, 1)) * ones.T\n self.ccf.getCorrelation(t1, t2, corr_HH_D)\n else:\n T_D = np.zeros((nsta, len_types + 1))\n for i in range(len_types + 1):\n if i == self.imt_Y_ind[imtstr]:\n continue\n if i < self.imt_Y_ind[imtstr]:\n T_D[sa_inds[imt_types[i]], i] = sta_tau[\n sa_inds[imt_types[i]], 0\n ]\n else:\n T_D[sa_inds[imt_types[i - 1]], i] = sta_tau[\n sa_inds[imt_types[i - 1]], 0\n ]\n corr_HH_D = np.zeros((len_types + 1, len_types + 1))\n ones = np.ones(len_types + 1, dtype=np.long).reshape((-1, 1))\n t1 = imt_types_alt.reshape((1, -1)) * ones\n t2 = imt_types_alt.reshape((-1, 1)) * ones.T\n self.ccf.getCorrelation(t1, t2, corr_HH_D)\n #\n # Make cov_WD_WD_inv (Sigma_22_inv)\n #\n matrix22 = np.empty((nsta, nsta), dtype=np.double)\n geodetic_distance_fast(\n sta_lons_rad, sta_lats_rad, sta_lons_rad, sta_lats_rad, matrix22\n )\n ones = np.ones(nsta, dtype=np.long).reshape((-1, 1))\n t1_22 = sta_per_ix.reshape((1, -1)) * ones\n t2_22 = sta_per_ix.reshape((-1, 1)) * ones.T\n self.ccf.getCorrelation(t1_22, t2_22, matrix22)\n sta_phi_flat = sta_phi.flatten()\n make_sigma_matrix(matrix22, sta_phi_flat, sta_phi_flat)\n np.fill_diagonal(matrix22, np.diag(matrix22) + sta_sig_extra ** 2)\n cov_WD_WD_inv = np.linalg.pinv(matrix22)\n #\n # Hold on to some things we'll need later\n #\n self.T_D[imtstr] = T_D\n self.cov_WD_WD_inv[imtstr] = cov_WD_WD_inv\n #\n # Compute the bias mu_H_yD and cov_HH_yD pieces\n #\n cov_HH_yD = np.linalg.pinv(\n np.linalg.multi_dot([T_D.T, cov_WD_WD_inv, T_D])\n + np.linalg.pinv(corr_HH_D)\n )\n mu_H_yD = np.linalg.multi_dot(\n [cov_HH_yD, T_D.T, cov_WD_WD_inv, sta_resids_dl]\n )\n if self.do_bias and (\n not isinstance(self.rupture_obj, PointRupture)\n or self.rx.mag <= self.bias_max_mag\n ):\n self.mu_H_yD[imtstr] = mu_H_yD\n self.cov_HH_yD[imtstr] = cov_HH_yD\n else:\n self.mu_H_yD[imtstr] = np.zeros_like(mu_H_yD)\n self.cov_HH_yD[imtstr] = np.zeros_like(cov_HH_yD)\n #\n # Get the nominal bias and variance\n #\n delta_B_yD = T_D.dot(mu_H_yD)\n self.nominal_bias[imtstr] = np.mean(delta_B_yD)\n sig_B_yD = np.sqrt(np.diag(np.linalg.multi_dot([T_D, cov_HH_yD, T_D.T])))\n nom_variance = np.mean(sig_B_yD)\n\n bias_time = time.time() - time1\n #\n # Write the nominal values of the bias and its stddev to log\n #\n self.logger.debug(\n \"%s: nom bias %f nom stddev %f; %d stations (time=%f sec)\"\n % (\n imtstr,\n self.nominal_bias[imtstr],\n np.sqrt(nom_variance),\n nsta,\n bias_time,\n )\n )\n\n def _computeDirectivityPredictionLocations(self):\n \"\"\"\n Figure out if we need the directivity factors, and if so, pre-calculate\n them. These will be used later in _computeMVN.\n \"\"\"\n if self.do_directivity is True:\n self.logger.info(\"Directivity for prediction locations...\")\n time1 = time.time()\n\n # Precompute directivity at all periods\n dir_out = Rowshandel2013(\n self.rupture_obj._origin,\n self.rupture_obj,\n self.lats.reshape((1, -1)),\n self.lons.reshape((1, -1)),\n np.zeros_like((len(self.lats), 1)),\n dx=1.0,\n T=Rowshandel2013.getPeriods(),\n a_weight=0.5,\n mtype=1,\n )\n self.dir_results.append((dir_out, self.dx_out))\n # Precompute directivity for the attenuation curves\n dir_out = Rowshandel2013(\n self.rupture_obj._origin,\n self.rupture_obj,\n self.atten_coords[\"lats\"].reshape((1, -1)),\n self.atten_coords[\"lons\"].reshape((1, -1)),\n np.zeros_like((len(self.atten_coords[\"lats\"]), 1)),\n dx=1.0,\n T=Rowshandel2013.getPeriods(),\n a_weight=0.5,\n mtype=1,\n )\n self.dir_results.append((dir_out, self.atten_dx))\n directivity_time = time.time() - time1\n self.logger.debug(\n f\"Directivity prediction evaluation time: {directivity_time:f} sec\"\n )\n else:\n self.directivity = None\n\n def _computeMVN(self, imtstr):\n \"\"\"\n Do the MVN computations\n \"\"\"\n self.logger.debug(f\"computeMVN: doing IMT {imtstr}\")\n time1 = time.time()\n #\n # Get the index of the (pesudo-) period of the output IMT\n #\n outperiod_ix = self.imt_per_ix[imtstr]\n #\n # Get the predictions at the output points\n #\n oqimt = imt.from_string(imtstr)\n if imtstr != \"MMI\":\n gmpe = MultiGMPE.__from_config__(self.config, filter_imt=oqimt)\n else:\n gmpe = self.ipe\n\n pout_mean, pout_sd = self._gmas(\n gmpe, self.sx_out, self.dx_out, oqimt, self.apply_gafs\n )\n\n if self.use_simulations:\n if imtstr == \"MMI\":\n pout_mean = self.gmice.getPreferredMI(\n self.sim_df, dists=self.dx_out.rrup, mag=self.rx.mag\n )\n else:\n pout_mean = self.sim_df[imtstr]\n #\n # While we have the gmpe for this IMT, we should make\n # the attenuation curves\n #\n x_mean, x_sd = self._gmas(\n gmpe, self.atten_sx_rock, self.atten_dx, oqimt, self.apply_gafs\n )\n self.atten_rock_mean[imtstr] = x_mean\n self.atten_rock_sd[imtstr] = x_sd[0]\n x_mean, x_sd = self._gmas(\n gmpe, self.atten_sx_soil, self.atten_dx, oqimt, self.apply_gafs\n )\n self.atten_soil_mean[imtstr] = x_mean\n self.atten_soil_sd[imtstr] = x_sd[0]\n #\n # Get an array of the within-event standard deviations for the\n # output IMT at the output points\n #\n if imtstr != \"MMI\":\n total_only = self.gmpe_total_sd_only\n tau_guess = SM_CONSTS[\"default_stddev_inter\"]\n else:\n total_only = self.ipe_total_sd_only\n tau_guess = SM_CONSTS[\"default_stddev_inter_mmi\"]\n if total_only:\n self.tsd[imtstr] = tau_guess * pout_sd[0]\n self.psd[imtstr] = np.sqrt(pout_sd[0] ** 2 - self.tsd[imtstr] ** 2)\n self.psd_raw[imtstr] = np.sqrt(pout_sd[1] ** 2 - self.tsd[imtstr] ** 2)\n else:\n self.tsd[imtstr] = pout_sd[1]\n self.psd[imtstr] = pout_sd[2]\n self.psd_raw[imtstr] = pout_sd[5]\n #\n # If there are no data, just use the unbiased prediction\n # and the stddev\n #\n nsta = np.size(self.sta_lons_rad[imtstr])\n if nsta == 0:\n self.outgrid[imtstr] = pout_mean\n self.outsd[imtstr] = pout_sd[0]\n self.outphi[imtstr] = self.psd[imtstr]\n self.outtau[imtstr] = self.tsd[imtstr]\n return\n\n pout_sd2_phi = np.power(self.psd[imtstr], 2.0)\n\n sta_per_ix = self.sta_per_ix[imtstr]\n sta_phi = self.sta_phi[imtstr]\n sta_lons_rad = self.sta_lons_rad[imtstr]\n sta_lats_rad = self.sta_lats_rad[imtstr]\n\n len_output = np.size(self.tsd[imtstr])\n if self.no_native_flag[imtstr] is False:\n T_Y0 = np.zeros((len_output, self.len_types[imtstr]))\n T_Y0[:, np.where(outperiod_ix == self.imt_types[imtstr])[0][0]] = self.tsd[\n imtstr\n ].ravel()\n else:\n T_Y0 = np.zeros((len_output, self.len_types[imtstr] + 1))\n T_Y0[:, self.imt_Y_ind[imtstr]] = self.tsd[imtstr].ravel()\n\n T_D = self.T_D[imtstr]\n cov_WD_WD_inv = self.cov_WD_WD_inv[imtstr]\n #\n # Now do the MVN itself...\n #\n dtime = mtime = ddtime = ctime = stime = atime = 0\n\n C = np.empty_like(T_Y0[0 : self.smnx, :])\n C_tmp1 = np.empty_like(C)\n C_tmp2 = np.empty_like(C)\n s_tmp1 = np.empty((self.smnx), dtype=np.float64).reshape((-1, 1))\n s_tmp2 = np.empty((self.smnx), dtype=np.float64).reshape((-1, 1))\n s_tmp3 = np.empty((self.smnx), dtype=np.float64)\n ampgrid = np.zeros_like(pout_mean)\n cov_WY_WY_WD = np.zeros_like(pout_mean)\n sdgrid_tau = np.zeros_like(pout_mean)\n # Stuff that doesn't change within the loop:\n lons_out_rad = self.lons_out_rad\n lats_out_rad = self.lats_out_rad\n d12_cols = self.smnx\n ones = np.ones(d12_cols, dtype=np.long).reshape((-1, 1))\n t1_12 = sta_per_ix.reshape((1, -1)) * ones\n t2_12 = np.full((d12_cols, nsta), outperiod_ix, dtype=np.long)\n # sdsta is the standard deviation of the stations\n sdsta_phi = sta_phi.flatten()\n matrix12_phi = np.empty(t2_12.shape, dtype=np.double)\n rcmatrix_phi = np.empty(t2_12.shape, dtype=np.double)\n for iy in range(self.smny):\n ss = iy * self.smnx\n se = (iy + 1) * self.smnx\n time4 = time.time()\n geodetic_distance_fast(\n sta_lons_rad,\n sta_lats_rad,\n lons_out_rad[ss:se],\n lats_out_rad[ss:se],\n matrix12_phi,\n )\n ddtime += time.time() - time4\n time4 = time.time()\n self.ccf.getCorrelation(t1_12, t2_12, matrix12_phi)\n ctime += time.time() - time4\n time4 = time.time()\n # sdarr_phi is the standard deviation of the within-event\n # residuals at the output sites\n sdarr_phi = self.psd[imtstr][iy, :]\n make_sigma_matrix(matrix12_phi, sdsta_phi, sdarr_phi)\n stime += time.time() - time4\n time4 = time.time()\n #\n # Sigma12 * Sigma22^-1 is known as the 'regression\n # coefficient' matrix (rcmatrix)\n #\n np.dot(matrix12_phi, cov_WD_WD_inv, out=rcmatrix_phi)\n dtime += time.time() - time4\n time4 = time.time()\n #\n # We only want the diagonal elements of the conditional\n # covariance matrix, so there is no point in doing the\n # full solution with the dot product, e.g.:\n # sdgrid[ss:se] = pout_sd2[ss:se] -\n # np.diag(rcmatrix.dot(sigma21))\n #\n # make_sd_array is a Cython function that is optimized to find\n # the diagonal of the covariance matrix.\n #\n make_sd_array(cov_WY_WY_WD, pout_sd2_phi, iy, rcmatrix_phi, matrix12_phi)\n #\n # Equation B32 of Engler et al. (2021)\n #\n C = T_Y0[ss:se, :] - np.dot(rcmatrix_phi, T_D, out=C_tmp1)\n #\n # This is the MVN solution for the conditional mean\n # It is an implementation of the equation just below\n # equation B25 in Engler et al. (2021):\n #\n # mu_Y_yD = mu_Y + C mu_H_yD + cov_WY_WD cov_WD_WD^-1 zeta\n #\n # but we break it up for efficiency.\n #\n s_tmp1r = np.dot(C, self.mu_H_yD[imtstr], out=s_tmp1).reshape((-1,))\n s_tmp2r = np.dot(rcmatrix_phi, self.sta_resids[imtstr], out=s_tmp2).reshape(\n (-1,)\n )\n ampgrid[iy, :] = np.add(\n np.add(pout_mean[iy, :], s_tmp1r, out=s_tmp1r), s_tmp2r, out=s_tmp2r\n )\n atime += time.time() - time4\n time4 = time.time()\n #\n # We're doing this:\n #\n # sdgrid_tau[iy, :] = np.diag(\n # C.dot(self.cov_HH_yD[imtstr].dot(C.T)))\n #\n # to find the between-event part of the diagonal of the conditional\n # covariance. This is the second term of equation B27 of Engler\n # et al. (2021). The code below is faster and uses less memory than\n # actually implementing the above equation.\n #\n np.dot(C, self.cov_HH_yD[imtstr], C_tmp1)\n sdgrid_tau[iy, :] = np.sum(\n np.multiply(C_tmp1, C, out=C_tmp2), out=s_tmp3, axis=1\n )\n\n mtime += time.time() - time4\n #\n # This processing can result in MMI values that go beyond\n # the 1 to 10 bounds of MMI, so we apply that constraint again\n # here\n #\n if imtstr == \"MMI\":\n ampgrid = np.clip(ampgrid, 1.0, 10.0)\n #\n # The conditional mean\n #\n self.outgrid[imtstr] = ampgrid\n #\n # The outputs are the conditional total stddev, the conditional\n # between-event stddev (tau), and the prior within-event stddev (phi)\n #\n self.outsd[imtstr] = np.sqrt(\n np.add(cov_WY_WY_WD, sdgrid_tau, out=cov_WY_WY_WD), out=cov_WY_WY_WD\n )\n # self.outphi[imtstr] = np.sqrt(cov_WY_WY_WD)\n self.outphi[imtstr] = self.psd[imtstr]\n self.outtau[imtstr] = np.sqrt(sdgrid_tau, out=sdgrid_tau)\n\n self.logger.debug(f\"\\ttime for {imtstr} distance={ddtime:f}\")\n self.logger.debug(f\"\\ttime for {imtstr} correlation={ctime:f}\")\n self.logger.debug(f\"\\ttime for {imtstr} sigma={stime:f}\")\n self.logger.debug(f\"\\ttime for {imtstr} rcmatrix={dtime:f}\")\n self.logger.debug(f\"\\ttime for {imtstr} amp calc={atime:f}\")\n self.logger.debug(f\"\\ttime for {imtstr} sd calc={mtime:f}\")\n self.logger.debug(f\"total time for {imtstr}={time.time() - time1:f}\")\n\n def _applyCustomMask(self):\n \"\"\"Apply custom masks to IMT grid outputs.\"\"\"\n if self.mask_file:\n mask = self._getMask(self.mask_file)\n for grid in self.outgrid.values():\n grid[~mask] = np.nan\n\n def _getLandMask(self):\n \"\"\"\n Get the landmask for this map. Land will be False, water will\n be True (because of the way masked arrays work).\n \"\"\"\n if \"CALLED_FROM_PYTEST\" in os.environ:\n oceans = None\n else:\n oceans = shpreader.natural_earth(\n category=\"physical\", name=\"ocean\", resolution=\"10m\"\n )\n return self._getMask(oceans)\n\n def _getMask(self, vector=None):\n \"\"\"\n Get a masked array for this map corresponding to the given vector\n feature.\n \"\"\"\n if not self.do_grid:\n return None\n gd = GeoDict.createDictFromBox(\n self.W, self.E, self.S, self.N, self.smdx, self.smdy\n )\n bbox = (gd.xmin, gd.ymin, gd.xmax, gd.ymax)\n if vector is None:\n return np.zeros((gd.ny, gd.nx), dtype=np.bool)\n\n with fiona.open(vector) as c:\n tshapes = list(c.items(bbox=bbox))\n shapes = []\n for tshp in tshapes:\n shapes.append(shape(tshp[1][\"geometry\"]))\n if len(shapes):\n grid = Grid2D.rasterizeFromGeometry(shapes, gd, fillValue=0.0)\n return grid.getData().astype(np.bool)\n else:\n return np.zeros((gd.ny, gd.nx), dtype=np.bool)\n\n def _getMaskedGrids(self, bmask):\n \"\"\"\n For each grid in the output, generate a grid with the water areas\n masked out.\n \"\"\"\n moutgrid = {}\n if not self.do_grid:\n for imtout in self.imt_out_set:\n moutgrid[imtout] = self.outgrid[imtout]\n return moutgrid\n for imtout in self.imt_out_set:\n moutgrid[imtout] = ma.masked_array(self.outgrid[imtout], mask=bmask)\n return moutgrid\n\n def _getInfo(self, moutgrid):\n \"\"\"\n Create an info dictionary that can be made into the info.json file.\n \"\"\"\n #\n # Get the map grade\n #\n mean_rat, mygrade = _get_map_grade(\n self.do_grid, self.outsd, self.psd_raw, moutgrid\n )\n # ---------------------------------------------------------------------\n # This is the metadata for creating info.json\n # ---------------------------------------------------------------------\n st = \"strec\"\n ip = \"input\"\n ei = \"event_information\"\n op = \"output\"\n gm = \"ground_motions\"\n mi = \"map_information\"\n un = \"uncertainty\"\n pp = \"processing\"\n gmm = \"ground_motion_modules\"\n ms = \"miscellaneous\"\n sv = \"shakemap_versions\"\n sr = \"site_response\"\n info = self._info\n info[ip] = {}\n info[ip][ei] = {}\n info[ip][ei][\"depth\"] = str(self.rx.hypo_depth)\n info[ip][ei][\"event_id\"] = self._eventid\n\n # look for the presence of a strec_results file and read it in\n _, data_path = get_config_paths()\n datadir = os.path.join(data_path, self._eventid, \"current\")\n strecfile = os.path.join(datadir, \"strec_results.json\")\n if os.path.isfile(strecfile):\n strec_results = json.load(open(strecfile, \"rt\"))\n info[st] = strec_results\n\n # the following items are primarily useful for PDL\n origin = self.rupture_obj._origin\n info[ip][ei][\"eventsource\"] = origin.netid\n info[ip][ei][\"netid\"] = origin.netid\n # The netid could be a valid part of the eventsourcecode, so we have\n # to check here if it ***starts with*** the netid\n if origin.id.startswith(origin.netid):\n eventsourcecode = origin.id.replace(origin.netid, \"\", 1)\n else:\n eventsourcecode = origin.id\n info[ip][ei][\"eventsourcecode\"] = eventsourcecode\n info[ip][ei][\"id\"] = origin.id\n info[ip][ei][\"productcode\"] = origin.productcode\n info[ip][ei][\"productsource\"] = self.config[\"system\"][\"source_network\"]\n info[ip][ei][\"producttype\"] = self.config[\"system\"][\"product_type\"]\n\n info[ip][ei][\"event_ref\"] = getattr(origin, \"reference\", None)\n info[ip][ei][\"fault_ref\"] = self.rupture_obj.getReference()\n if \"df2\" in self.dataframes:\n info[ip][ei][\"intensity_observations\"] = str(np.size(self.df2.df[\"lon\"]))\n else:\n info[ip][ei][\"intensity_observations\"] = \"0\"\n info[ip][ei][\"latitude\"] = str(self.rx.hypo_lat)\n info[ip][ei][\"longitude\"] = str(self.rx.hypo_lon)\n info[ip][ei][\"location\"] = origin.locstring\n info[ip][ei][\"magnitude\"] = str(self.rx.mag)\n info[ip][ei][\"origin_time\"] = origin.time.strftime(constants.TIMEFMT)\n if \"df1\" in self.dataframes:\n info[ip][ei][\"seismic_stations\"] = str(np.size(self.df1.df[\"lon\"]))\n else:\n info[ip][ei][\"seismic_stations\"] = \"0\"\n info[ip][ei][\"src_mech\"] = origin.mech\n if self.config[\"system\"][\"source_description\"] != \"\":\n info[ip][ei][\"event_description\"] = self.config[\"system\"][\n \"source_description\"\n ]\n else:\n info[ip][ei][\"event_description\"] = origin.locstring\n # This AND src_mech?\n # look at the origin information for indications that this\n # event is a scenario\n condition1 = (\n hasattr(origin, \"event_type\") and origin.event_type.lower() == \"scenario\"\n )\n condition2 = origin.id.endswith(\"_se\")\n if condition1 or condition2:\n info[ip][ei][\"event_type\"] = \"SCENARIO\"\n else:\n info[ip][ei][\"event_type\"] = \"ACTUAL\"\n\n info[op] = {}\n info[op][gm] = {}\n for myimt in self.imt_out_set:\n info[op][gm][myimt] = {}\n if myimt == \"MMI\":\n units = \"intensity\"\n elif myimt == \"PGV\":\n units = \"cms\"\n else:\n units = \"g\"\n info[op][gm][myimt][\"units\"] = units\n if myimt in self.nominal_bias:\n info[op][gm][myimt][\"bias\"] = _string_round(self.nominal_bias[myimt], 3)\n else:\n info[op][gm][myimt][\"bias\"] = None\n if myimt == \"MMI\":\n info[op][gm][myimt][\"max_grid\"] = _string_round(\n np.max(self.outgrid[myimt]), 3\n )\n info[op][gm][myimt][\"max\"] = _string_round(np.max(moutgrid[myimt]), 3)\n else:\n info[op][gm][myimt][\"max_grid\"] = _string_round(\n np.exp(np.max(self.outgrid[myimt])), 3\n )\n info[op][gm][myimt][\"max\"] = _string_round(\n np.exp(np.max(moutgrid[myimt])), 3\n )\n\n info[op][mi] = {}\n info[op][mi][\"grid_points\"] = {}\n info[op][mi][\"grid_points\"][\"longitude\"] = str(self.smnx)\n info[op][mi][\"grid_points\"][\"latitude\"] = str(self.smny)\n info[op][mi][\"grid_points\"][\"units\"] = \"\"\n info[op][mi][\"grid_spacing\"] = {}\n info[op][mi][\"grid_spacing\"][\"longitude\"] = _string_round(self.smdx, 7)\n info[op][mi][\"grid_spacing\"][\"latitude\"] = _string_round(self.smdy, 7)\n info[op][mi][\"grid_spacing\"][\"units\"] = \"degrees\"\n info[op][mi][\"grid_span\"] = {}\n if self.E <= 0 and self.W >= 0:\n info[op][mi][\"grid_span\"][\"longitude\"] = _string_round(\n self.E + 360.0 - self.W, 3\n )\n else:\n info[op][mi][\"grid_span\"][\"longitude\"] = _string_round(self.E - self.W, 3)\n info[op][mi][\"grid_span\"][\"latitude\"] = _string_round(self.N - self.S, 3)\n info[op][mi][\"grid_span\"][\"units\"] = \"degrees\"\n info[op][mi][\"min\"] = {}\n info[op][mi][\"max\"] = {}\n min_long = self.W\n max_long = self.E\n if self.rx.hypo_lon < 0:\n if min_long > 0: # Crossing the 180 from the negative side\n min_long = min_long - 360\n else:\n if max_long < 0: # Crossing the 180 from the positive side\n max_long = max_long + 360\n info[op][mi][\"min\"][\"longitude\"] = _string_round(min_long, 3)\n info[op][mi][\"max\"][\"longitude\"] = _string_round(max_long, 3)\n info[op][mi][\"min\"][\"latitude\"] = _string_round(self.S, 3)\n info[op][mi][\"max\"][\"latitude\"] = _string_round(self.N, 3)\n info[op][mi][\"min\"][\"units\"] = \"degrees\"\n info[op][mi][\"max\"][\"units\"] = \"degrees\"\n info[op][un] = {}\n info[op][un][\"grade\"] = mygrade\n info[op][un][\"mean_uncertainty_ratio\"] = _string_round(mean_rat, 3)\n if \"df2\" in self.dataframes:\n info[op][un][\"total_flagged_mi\"] = str(\n np.sum(self.df2.df[\"MMI_outliers\"] | np.isnan(self.df2.df[\"MMI\"]))\n )\n else:\n info[op][un][\"total_flagged_mi\"] = \"0\"\n if \"df1\" in self.dataframes:\n all_flagged = np.full(self.df1.df[\"lon\"].shape, False, dtype=np.bool)\n for imtstr in self.df1.imts:\n if \"MMI\" in imtstr:\n continue\n all_flagged |= self.df1.df[imtstr + \"_outliers\"] | np.isnan(\n self.df1.df[imtstr]\n )\n all_flagged |= self.df1.df[\"flagged\"]\n info[op][un][\"total_flagged_pgm\"] = str(np.sum(all_flagged))\n else:\n info[op][un][\"total_flagged_pgm\"] = \"0\"\n info[pp] = {}\n info[pp][gmm] = {}\n info[pp][gmm][\"gmpe\"] = {}\n info[pp][gmm][\"gmpe\"][\"module\"] = str(self.config[\"modeling\"][\"gmpe\"])\n info[pp][gmm][\"gmpe\"][\"reference\"] = \"\"\n info[pp][gmm][\"ipe\"] = {}\n info[pp][gmm][\"ipe\"][\"module\"] = str(\n self.config[\"ipe_modules\"][self.config[\"modeling\"][\"ipe\"]][0]\n )\n info[pp][gmm][\"ipe\"][\"reference\"] = \"\"\n info[pp][gmm][\"gmice\"] = {}\n info[pp][gmm][\"gmice\"][\"module\"] = str(\n self.config[\"gmice_modules\"][self.config[\"modeling\"][\"gmice\"]][0]\n )\n info[pp][gmm][\"gmice\"][\"reference\"] = \"\"\n info[pp][gmm][\"ccf\"] = {}\n info[pp][gmm][\"ccf\"][\"module\"] = str(\n self.config[\"ccf_modules\"][self.config[\"modeling\"][\"ccf\"]][0]\n )\n info[pp][gmm][\"ccf\"][\"reference\"] = \"\"\n info[pp][gmm][\"basin_correction\"] = {}\n info[pp][gmm][\"basin_correction\"][\"module\"] = \"None\"\n info[pp][gmm][\"basin_correction\"][\"reference\"] = \"\"\n info[pp][gmm][\"directivity\"] = {}\n info[pp][gmm][\"directivity\"][\"module\"] = \"None\"\n info[pp][gmm][\"directivity\"][\"reference\"] = \"\"\n info[pp][ms] = {}\n info[pp][ms][\"bias_max_dsigma\"] = str(self.bias_max_dsigma)\n info[pp][ms][\"bias_max_mag\"] = str(self.bias_max_mag)\n info[pp][ms][\"bias_max_range\"] = str(self.bias_max_range)\n info[pp][ms][\"median_dist\"] = \"True\"\n info[pp][ms][\"do_outliers\"] = self.do_outliers\n info[pp][ms][\"outlier_deviation_level\"] = str(self.outlier_deviation_level)\n info[pp][ms][\"outlier_max_mag\"] = str(self.outlier_max_mag)\n info[pp][sv] = {}\n info[pp][sv][\"shakemap_revision\"] = get_versions()[\"version\"]\n info[pp][sv][\"shakemap_revision_id\"] = get_versions()[\"full-revisionid\"]\n info[pp][sv][\"process_time\"] = strftime(constants.ALT_TIMEFMT, gmtime())\n info[pp][sv][\"map_version\"] = self.ic.getVersionHistory()[\"history\"][-1][2]\n info[pp][sv][\"map_comment\"] = self.ic.getVersionHistory()[\"history\"][-1][3]\n info[pp][sv][\"map_data_history\"] = self.ic.getVersionHistory()[\"history\"]\n info[pp][sv][\"map_status\"] = self.config[\"system\"][\"map_status\"]\n info[pp][sr] = {}\n info[pp][sr][\"vs30default\"] = str(self.vs30default)\n info[pp][sr][\"site_correction\"] = \"GMPE native\"\n return info\n\n def _fillStationJSON(self):\n \"\"\"\n Get the station JSON dictionary and then add a bunch of stuff to it.\n \"\"\"\n if not hasattr(self, \"stations\") or self.stations is None:\n return {\"eventid\": self._eventid, \"features\": []}\n sjdict = {}\n # ---------------------------------------------------------------------\n # Compute a bias for all the output IMTs in the data frames\n # ---------------------------------------------------------------------\n for ndf in self.dataframes:\n sdf = getattr(self, ndf).df\n for myimt in self.imt_out_set:\n if type(self.mu_H_yD[myimt]) is float:\n mybias = sdf[myimt + \"_pred_tau\"] * self.mu_H_yD[myimt]\n mybias_sig = np.sqrt(\n sdf[myimt + \"_pred_tau\"] ** 2 * self.cov_HH_yD[myimt]\n )\n else:\n mybias = sdf[myimt + \"_pred_tau\"] * self.mu_H_yD[myimt][0]\n mybias_sig = np.sqrt(\n sdf[myimt + \"_pred_tau\"] ** 2 * self.cov_HH_yD[myimt][0, 0]\n )\n sdf[myimt + \"_bias\"] = mybias.flatten()\n sdf[myimt + \"_bias_sigma\"] = mybias_sig.flatten()\n\n # ---------------------------------------------------------------------\n # Add the station data. The stationlist object has the original\n # data and produces a GeoJSON object (a dictionary, really), but\n # we need to add peak values and flagging that has been done here.\n # ---------------------------------------------------------------------\n #\n # First make a dictionary of distances\n #\n dist_dict = {\"df1\": {}, \"df2\": {}}\n for ndf in self.dataframes:\n dx = getattr(self, ndf).dx\n for dm in get_distance_measures():\n dm_arr = getattr(dx, dm, None)\n if dm_arr is not None:\n dist_dict[ndf][dm] = dm_arr\n else:\n continue\n if dm in (\"rrup\", \"rjb\"):\n dm_var = getattr(dx, dm + \"_var\", None)\n if dm_var is not None:\n dist_dict[ndf][dm + \"_var\"] = dm_var\n else:\n dist_dict[ndf][dm + \"_var\"] = np.zeros_like(dm_arr)\n #\n # Get the index for each station ID\n #\n sjdict = self.stations.getGeoJson()\n sta_ix = {\"df1\": {}, \"df2\": {}}\n for ndf in self.dataframes:\n sdf = getattr(self, ndf).df\n sta_ix[ndf] = dict(zip(sdf[\"id\"], range(len(sdf[\"id\"]))))\n #\n # Now go through the GeoJSON and add various properties and\n # amps from the df_dict dictionaries\n #\n sjdict_copy = copy.copy(sjdict[\"features\"])\n for station in sjdict_copy:\n if station[\"id\"] in sta_ix[\"df1\"]:\n ndf = \"df1\"\n station[\"properties\"][\"station_type\"] = \"seismic\"\n elif station[\"id\"] in sta_ix[\"df2\"]:\n ndf = \"df2\"\n station[\"properties\"][\"station_type\"] = \"macroseismic\"\n else:\n # We're probably using --no_seismic or --no_macroseismic\n if self.no_seismic or self.no_macroseismic:\n sjdict[\"features\"].remove(station)\n continue\n else:\n raise ValueError(f\"Unknown station {station['id']} in stationlist\")\n dfx = getattr(self, ndf)\n sdf = dfx.df\n six = sta_ix[ndf][station[\"id\"]]\n #\n # Set the 'intensity', 'pga', and 'pga' peak properties\n #\n if (\n \"MMI\" in sdf\n and not sdf[\"MMI_outliers\"][six]\n and not np.isnan(sdf[\"MMI\"][six])\n ):\n station[\"properties\"][\"intensity\"] = float(f\"{sdf['MMI'][six]:.1f}\")\n station[\"properties\"][\"intensity_stddev\"] = sdf[\"MMI_sd\"][six]\n if \"MMI_nresp\" in sdf:\n station[\"properties\"][\"nresp\"] = int(sdf[\"MMI_nresp\"][six])\n else:\n station[\"properties\"][\"nresp\"] = \"null\"\n else:\n station[\"properties\"][\"intensity\"] = \"null\"\n station[\"properties\"][\"intensity_stddev\"] = \"null\"\n station[\"properties\"][\"nresp\"] = \"null\"\n\n if (\n \"PGA\" in sdf\n and not sdf[\"PGA_outliers\"][six]\n and not np.isnan(sdf[\"PGA\"][six])\n and (ndf != \"df1\" or not sdf[\"flagged\"][six])\n ):\n station[\"properties\"][\"pga\"] = _round_float(\n np.exp(sdf[\"PGA\"][six]) * 100, 4\n )\n else:\n station[\"properties\"][\"pga\"] = \"null\"\n\n if (\n \"PGV\" in sdf\n and not sdf[\"PGV_outliers\"][six]\n and not np.isnan(sdf[\"PGV\"][six])\n and (ndf != \"df1\" or not sdf[\"flagged\"][six])\n ):\n station[\"properties\"][\"pgv\"] = _round_float(np.exp(sdf[\"PGV\"][six]), 4)\n else:\n station[\"properties\"][\"pgv\"] = \"null\"\n #\n # Add vs30\n #\n station[\"properties\"][\"vs30\"] = _round_float(dfx.sx.vs30[six], 2)\n #\n # Add the predictions so we can plot residuals\n #\n station[\"properties\"][\"predictions\"] = []\n for key in sdf.keys():\n if not key.endswith(\"_pred\"):\n continue\n myamp = sdf[key][six]\n myamp_rock = sdf[key + \"_rock\"][six]\n myamp_soil = sdf[key + \"_soil\"][six]\n tau_str = \"ln_tau\"\n phi_str = \"ln_phi\"\n sigma_str = \"ln_sigma\"\n sigma_str_rock = \"ln_sigma_rock\"\n sigma_str_soil = \"ln_sigma_soil\"\n bias_str = \"ln_bias\"\n bias_sigma_str = \"ln_bias_sigma\"\n if key.startswith(\"PGV\"):\n value = np.exp(myamp)\n value_rock = np.exp(myamp_rock)\n value_soil = np.exp(myamp_soil)\n units = \"cm/s\"\n elif key.startswith(\"MMI\"):\n value = myamp\n value_rock = myamp_rock\n value_soil = myamp_soil\n units = \"intensity\"\n tau_str = \"tau\"\n phi_str = \"phi\"\n sigma_str = \"sigma\"\n sigma_str_rock = \"sigma_rock\"\n sigma_str_soil = \"sigma_soil\"\n bias_str = \"bias\"\n bias_sigma_str = \"bias_sigma\"\n else:\n value = np.exp(myamp) * 100\n value_rock = np.exp(myamp_rock) * 100\n value_soil = np.exp(myamp_soil) * 100\n units = \"%g\"\n if self.gmpe_total_sd_only:\n mytau = 0\n else:\n mytau = sdf[key + \"_tau\"][six]\n myphi = sdf[key + \"_phi\"][six]\n mysigma = np.sqrt(mytau ** 2 + myphi ** 2)\n mysigma_rock = sdf[key + \"_sigma_rock\"][six]\n mysigma_soil = sdf[key + \"_sigma_soil\"][six]\n imt_name = key.lower().replace(\"_pred\", \"\")\n if imt_name.upper() in self.imt_out_set:\n mybias = sdf[imt_name.upper() + \"_bias\"][six]\n mybias_sigma = sdf[imt_name.upper() + \"_bias_sigma\"][six]\n else:\n mybias = \"null\"\n mybias_sigma = \"null\"\n station[\"properties\"][\"predictions\"].append(\n {\n \"name\": imt_name,\n \"value\": _round_float(value, 4),\n \"value_rock\": _round_float(value_rock, 4),\n \"value_soil\": _round_float(value_soil, 4),\n \"units\": units,\n tau_str: _round_float(mytau, 4),\n phi_str: _round_float(myphi, 4),\n sigma_str: _round_float(mysigma, 4),\n sigma_str_rock: _round_float(mysigma_rock, 4),\n sigma_str_soil: _round_float(mysigma_soil, 4),\n bias_str: _round_float(mybias, 4),\n bias_sigma_str: _round_float(mybias_sigma, 4),\n }\n )\n #\n # For df1 stations, add the MMIs comverted from PGM\n #\n if ndf == \"df1\":\n station[\"properties\"][\"mmi_from_pgm\"] = []\n for myimt in getattr(self, ndf).imts:\n if myimt == \"MMI\":\n continue\n dimtstr = \"derived_MMI_from_\" + myimt\n if dimtstr not in sdf:\n continue\n imt_name = myimt.lower()\n myamp = sdf[dimtstr][six]\n mysd = sdf[dimtstr + \"_sd\"][six]\n if np.isnan(myamp):\n myamp = \"null\"\n mysd = \"null\"\n flag = \"0\"\n else:\n if sdf[myimt + \"_outliers\"][six] == 1:\n flag = \"Outlier\"\n else:\n flag = \"0\"\n station[\"properties\"][\"mmi_from_pgm\"].append(\n {\n \"name\": imt_name,\n \"value\": _round_float(myamp, 2),\n \"sigma\": _round_float(mysd, 2),\n \"flag\": flag,\n }\n )\n\n #\n # For df2 stations, add the PGMs converted from MMI\n #\n if ndf == \"df2\":\n station[\"properties\"][\"pgm_from_mmi\"] = []\n for myimt in getattr(self, ndf).imts:\n if myimt == \"MMI\":\n continue\n imt_name = myimt.lower()\n myamp = sdf[myimt][six]\n mysd = sdf[myimt + \"_sd\"][six]\n if myimt == \"PGV\":\n value = np.exp(myamp)\n units = \"cm/s\"\n else:\n value = np.exp(myamp) * 100\n units = \"%g\"\n if np.isnan(value):\n value = \"null\"\n mysd = \"null\"\n flag = \"0\"\n else:\n if sdf[myimt + \"_outliers\"][six] == 1:\n flag = \"Outlier\"\n else:\n flag = \"0\"\n station[\"properties\"][\"pgm_from_mmi\"].append(\n {\n \"name\": imt_name,\n \"value\": _round_float(value, 4),\n \"units\": units,\n \"ln_sigma\": _round_float(mysd, 4),\n \"flag\": flag,\n }\n )\n #\n # Set the generic distance property (this is rrup)\n #\n station[\"properties\"][\"distance\"] = _round_float(sdf[\"rrup\"][six], 3)\n station[\"properties\"][\"distance_stddev\"] = _round_float(\n np.sqrt(sdf[\"rrup_var\"][six]), 3\n )\n #\n # Set the specific distances properties\n #\n station[\"properties\"][\"distances\"] = {}\n for dm, dm_arr in dist_dict[ndf].items():\n station[\"properties\"][\"distances\"][dm] = _round_float(dm_arr[six], 3)\n #\n # Set the outlier flags\n #\n mflag = \"0\"\n if ndf == \"df1\" and sdf[\"flagged\"][six]:\n mflag = \"ManuallyFlagged\"\n for channel in station[\"properties\"][\"channels\"]:\n for amp in channel[\"amplitudes\"]:\n if amp[\"flag\"] != \"0\":\n amp[\"flag\"] += \",\" + mflag\n else:\n amp[\"flag\"] = mflag\n Name = amp[\"name\"].upper()\n if sdf[Name + \"_outliers\"][six]:\n if amp[\"flag\"] == \"0\":\n amp[\"flag\"] = \"Outlier\"\n else:\n amp[\"flag\"] += \",Outlier\"\n sjdict[\"metadata\"] = {\"eventid\": self._eventid}\n return sjdict\n\n def _storeGriddedData(self, oc):\n \"\"\"\n Store gridded data in the output container.\n \"\"\"\n metadata = {}\n min_long = self.W\n max_long = self.E\n if self.rx.hypo_lon < 0:\n if min_long > 0: # Crossing the 180 from the negative side\n min_long = min_long - 360\n else:\n if max_long < 0: # Crossing the 180 from the positive side\n max_long = max_long + 360\n metadata[\"xmin\"] = min_long\n metadata[\"xmax\"] = max_long\n metadata[\"ymin\"] = self.S\n metadata[\"ymax\"] = self.N\n metadata[\"nx\"] = self.smnx\n metadata[\"ny\"] = self.smny\n metadata[\"dx\"] = self.smdx\n metadata[\"dy\"] = self.smdy\n #\n # Put the Vs30 grid in the output container\n #\n _, units, digits = _get_layer_info(\"vs30\")\n metadata[\"units\"] = units\n metadata[\"digits\"] = digits\n oc.setArray([], \"vs30\", self.sx_out.vs30, metadata=metadata)\n #\n # Now do the distance grids\n #\n metadata[\"units\"] = \"km\"\n metadata[\"digits\"] = 4\n for dm in get_distance_measures():\n dm_arr = getattr(self.dx_out, dm, None)\n if dm_arr is None:\n continue\n oc.setArray([\"distances\"], dm, dm_arr, metadata=metadata)\n if dm in (\"rrup\", \"rjb\"):\n dm_var = getattr(self.dx_out, dm + \"_var\", None)\n if dm_var is None:\n dm_var = np.zeros_like(dm_arr)\n dm_std = np.sqrt(dm_var)\n oc.setArray([\"distances\"], dm + \"_std\", dm_std, metadata=metadata)\n\n #\n # Output the data and uncertainty grids\n #\n component = self.config[\"interp\"][\"component\"]\n std_metadata = copy.copy(metadata)\n for key, value in self.outgrid.items():\n # set the data grid\n _, units, digits = _get_layer_info(key)\n metadata[\"units\"] = units\n metadata[\"digits\"] = digits\n\n # set the mean and uncertainty grids\n std_layername, units, digits = _get_layer_info(key + \"_sd\")\n std_metadata[\"units\"] = units\n std_metadata[\"digits\"] = digits\n oc.setIMTGrids(\n key,\n component,\n value,\n metadata,\n self.outsd[key],\n std_metadata,\n self.outphi[key],\n self.outtau[key],\n )\n #\n # Directivity\n #\n del metadata[\"units\"]\n del metadata[\"digits\"]\n if self.do_directivity is True:\n for k, v in self.dir_output.items():\n imtstr, _, _ = _get_layer_info(k)\n oc.setArray([\"directivity\"], imtstr, v, metadata=metadata)\n\n def _storePointData(self, oc):\n \"\"\"\n Store point data in the output container.\n \"\"\"\n #\n # Store the Vs30\n #\n vs30_metadata = {\"units\": \"m/s\", \"digits\": 4}\n oc.setArray([], \"vs30\", self.sx_out.vs30.flatten(), metadata=vs30_metadata)\n #\n # Store the distances\n #\n distance_metadata = {\"units\": \"km\", \"digits\": 4}\n for dm in get_distance_measures():\n dm_arr = getattr(self.dx_out, dm, None)\n if dm_arr is None:\n continue\n oc.setArray([\"distances\"], dm, dm_arr.flatten(), metadata=distance_metadata)\n if dm in (\"rrup\", \"rjb\"):\n dm_var = getattr(self.dx_out, dm + \"_var\", None)\n if dm_var is None:\n dm_var = np.zeros_like(dm_arr)\n oc.setArray(\n [\"distances\"],\n dm + \"_std\",\n np.sqrt(dm_var).flatten(),\n metadata=distance_metadata,\n )\n #\n # Store the IMTs\n #\n ascii_ids = np.array(\n [np.char.encode(x, encoding=\"ascii\") for x in self.idents]\n ).flatten()\n component = self.config[\"interp\"][\"component\"]\n for key, value in self.outgrid.items():\n # set the data grid\n _, units, digits = _get_layer_info(key)\n mean_metadata = {\"units\": units, \"digits\": digits}\n # set the uncertainty grid\n std_layername, units, digits = _get_layer_info(key + \"_sd\")\n std_metadata = {\"units\": units, \"digits\": digits}\n oc.setIMTArrays(\n key,\n component,\n self.sx_out.lons.flatten(),\n self.sx_out.lats.flatten(),\n ascii_ids,\n value.flatten(),\n mean_metadata,\n self.outsd[key].flatten(),\n std_metadata,\n self.outphi[key].flatten(),\n self.outtau[key].flatten(),\n )\n\n def _storeAttenuationData(self, oc):\n \"\"\"\n Output arrays of rock and soil attenuation curves\n \"\"\"\n\n for dist_type in [\"repi\", \"rhypo\", \"rrup\", \"rjb\"]:\n oc.setArray(\n [\"attenuation\", \"distances\"],\n dist_type,\n getattr(self.atten_dx, dist_type, None),\n )\n\n imtstrs = self.atten_rock_mean.keys()\n for imtstr in imtstrs:\n oc.setArray(\n [\"attenuation\", \"rock\", imtstr], \"mean\", self.atten_rock_mean[imtstr]\n )\n oc.setArray(\n [\"attenuation\", \"soil\", imtstr], \"mean\", self.atten_soil_mean[imtstr]\n )\n oc.setArray(\n [\"attenuation\", \"rock\", imtstr], \"std\", self.atten_rock_sd[imtstr]\n )\n oc.setArray(\n [\"attenuation\", \"soil\", imtstr], \"std\", self.atten_soil_sd[imtstr]\n )\n return\n\n #\n # Helper function to call get_mean_and_stddevs for the\n # appropriate object given the IMT and describe the\n # MultiGMPE structure.\n #\n def _gmas(self, gmpe, sx, dx, oqimt, apply_gafs):\n \"\"\"\n This is a helper function to call get_mean_and_stddevs for the\n appropriate object given the IMT.\n\n Args:\n gmpe:\n A GMPE instance.\n sx:\n Sites context.\n dx:\n Distance context.\n oqimt:\n List of OpenQuake IMTs.\n apply_gafs (boolean):\n Whether or not to apply the generic\n amplification factors to the GMPE output.\n\n Returns:\n tuple: Tuple of two items:\n\n - Numpy array of means,\n - List of numpy array of standard deviations corresponding to\n therequested stddev_types.\n\n \"\"\"\n if \"MMI\" in oqimt:\n pe = self.ipe\n sd_types = self.ipe_stddev_types\n\n if not self.use_simulations:\n if not hasattr(self, \"_info\"):\n self._info = {\"multigmpe\": {}}\n else:\n self._info = {}\n else:\n pe = gmpe\n sd_types = self.gmpe_stddev_types\n\n if not self.use_simulations:\n # --------------------------------------------------------------------\n # Describe the MultiGMPE\n # --------------------------------------------------------------------\n if not hasattr(self, \"_info\"):\n self._info = {\"multigmpe\": {}}\n self._info[\"multigmpe\"][str(oqimt)] = gmpe.__describe__()\n else:\n self._info = {}\n\n mean, stddevs = pe.get_mean_and_stddevs(\n copy.deepcopy(sx), self.rx, copy.deepcopy(dx), oqimt, sd_types\n )\n\n # Include generic amp factors?\n if apply_gafs:\n gafs = get_generic_amp_factors(sx, str(oqimt))\n if gafs is not None:\n mean += gafs\n\n # Does directivity apply to this imt?\n row_pers = Rowshandel2013.getPeriods()\n\n if oqimt.string == \"PGA\":\n imt_ok = False\n elif oqimt.string == \"PGV\" or oqimt.string == \"MMI\":\n tper = 1.0\n imt_ok = True\n elif \"SA\" in oqimt.string:\n tper = oqimt.period\n min_per = np.min(row_pers)\n max_per = np.max(row_pers)\n if (tper >= min_per) and (tper <= max_per):\n imt_ok = True\n else:\n imt_ok = False\n else:\n imt_ok = False\n\n # Did we calculate directivity?\n calc_dir = self.do_directivity\n\n if calc_dir and imt_ok:\n # Use distance context to figure out which directivity result\n # we need to use.\n all_fd = None\n for dirdf, tmpdx in self.dir_results:\n if dx == tmpdx:\n all_fd = dirdf.getFd()\n break\n if all_fd is None:\n raise RuntimeError(\n \"Failed to detect dataframe for directivity calculation.\"\n )\n\n # Does oqimt match any of those periods?\n if tper in row_pers:\n fd = all_fd[row_pers.index(tper)]\n else:\n # Log(period) interpolation.\n apers = np.array(row_pers)\n per_below = np.max(apers[apers < tper])\n per_above = np.min(apers[apers > tper])\n fd_below = all_fd[row_pers.index(per_below)]\n fd_above = all_fd[row_pers.index(per_above)]\n x1 = np.log(per_below)\n x2 = np.log(per_above)\n fd = fd_below + (np.log(tper) - x1) * (fd_above - fd_below) / (x2 - x1)\n # Reshape to match the mean\n fd = fd.reshape(mean.shape)\n # Store the interpolated grid\n imtstr = str(oqimt)\n self.dir_output[imtstr] = fd\n if oqimt.string == \"MMI\":\n mean *= np.exp(fd)\n else:\n mean += fd\n\n return mean, stddevs\n\n def _adjustResolution(self):\n \"\"\"\n This is a helper function to adjust the resolution to be under\n the maximum value specified in the config.\n \"\"\"\n # We want to only use resolutions that are multiples of 1 minute or\n # an integer division of 1 minute.\n one_minute = 1 / 60\n multiples = np.arange(1, 11)\n divisions = 1 / multiples\n factors = np.sort(np.unique(np.concatenate((divisions, multiples))))\n ok_res = one_minute * factors\n latspan = self.N - self.S\n\n # Deal with possible 180 longitude disontinuity\n if self.E > self.W:\n lonspan = self.E - self.W\n else:\n xmax = self.E + 360\n lonspan = xmax - self.W\n nx = np.floor(lonspan / self.smdx) + 1\n ny = np.floor(latspan / self.smdy) + 1\n ngrid = nx * ny\n nmax = self.nmax\n if ngrid > nmax:\n self.logger.info(\n \"Extent and resolution of shakemap results in \"\n \"too many grid points. Adjusting resolution...\"\n )\n self.logger.info(f\"Longitude span: {lonspan:f}\")\n self.logger.info(f\"Latitude span: {latspan:f}\")\n self.logger.info(f\"Current dx: {self.smdx:f}\")\n self.logger.info(f\"Current dy: {self.smdy:f}\")\n self.logger.info(\"Current number of grid points: %i\" % ngrid)\n self.logger.info(\"Max grid points allowed: %i\" % nmax)\n target_res = (\n -(latspan + lonspan)\n - np.sqrt(\n latspan ** 2 + lonspan ** 2 + 2 * latspan * lonspan * (2 * nmax - 1)\n )\n ) / (2 * (1 - nmax))\n\n if np.any(ok_res > target_res):\n sel_res = np.min(ok_res[ok_res > target_res])\n else:\n sel_res = np.max(ok_res)\n self.smdx = sel_res\n self.smdy = sel_res\n self.logger.info(f\"Updated dx: {self.smdx:f}\")\n self.logger.info(f\"Updatd dy: {self.smdy:f}\")\n nx = np.floor(lonspan / self.smdx) + 1\n ny = np.floor(latspan / self.smdy) + 1\n self.logger.info(\"Updated number of grid points: %i\" % (nx * ny))\n\n\ndef _round_float(val, digits):\n if ma.is_masked(val) or val == \"--\" or val == \"null\" or np.isnan(val):\n return None\n return float((\"%.\" + str(digits) + \"f\") % val)\n\n\ndef _string_round(val, digits):\n if ma.is_masked(val) or val == \"--\" or val == \"null\" or np.isnan(val):\n return None\n return str(_round_float(val, digits))\n\n\ndef _get_period_arrays(*args):\n \"\"\"\n Return 1) a sorted array of the periods represented by the IMT list(s)\n in the input, and 2) a dictionary of the IMTs and their indices.\n\n Args:\n *args (list): One or more lists of IMTs.\n\n Returns:\n array, dict: Numpy array of the (sorted) periods represented by the\n IMTs in the input list(s), and a dictionary of the IMTs and their\n indices into the period array.\n \"\"\"\n imt_per = set()\n imt_per_ix = {}\n for imt_list in args:\n if imt_list is None:\n continue\n for imtstr in imt_list:\n if imtstr == \"PGA\":\n period = 0.01\n elif imtstr in (\"PGV\", \"MMI\"):\n period = 1.0\n else:\n period = _get_period_from_imt(imtstr)\n imt_per.add(period)\n imt_per_ix[imtstr] = period\n imt_per = sorted(imt_per)\n for imtstr, period in imt_per_ix.items():\n imt_per_ix[imtstr] = imt_per.index(period)\n return np.array(imt_per), imt_per_ix\n\n\ndef _get_period_from_imt(imtstr):\n \"\"\"\n Return a float representing the period of the SA IMT in the input.\n\n Args:\n imtstr (str): A string representing an SA IMT.\n\n Returns:\n float: The period of the SA IMT as a float.\n \"\"\"\n return float(imtstr.replace(\"SA(\", \"\").replace(\")\", \"\"))\n\n\ndef _get_nearest_imts(imtstr, imtset, saset):\n \"\"\"\n Return the input IMT, or it's closest surrogarte (or bracket) found\n in imtset.\n\n Args:\n imtstr (str): An (OQ-style) IMT string.\n imtset (list): A list of IMTs to search for imtstr or its closest\n surrogate (or bracket).\n saset (list): The SA IMTs found in imtset.\n\n Returns:\n tuple: The IMT, it's closest surrogate, or a bracket of SAs with\n periods on either side of the IMT's period, from the IMTs in intset.\n \"\"\"\n if imtstr in imtset:\n return (imtstr,)\n #\n # If we're here, then we know that IMT isn't in the inputs. Try\n # some alternatives.\n #\n if imtstr == \"PGA\":\n #\n # Use the highest frequency in the inputs\n #\n if len(saset):\n return (sorted(saset, key=_get_period_from_imt)[0],)\n else:\n return ()\n elif imtstr == \"PGV\":\n #\n # PGV has no surrogate\n #\n return ()\n elif imtstr == \"MMI\":\n #\n # MMI has no surrogate\n #\n return ()\n elif imtstr.startswith(\"SA(\"):\n #\n # We know the actual IMT isn't here, so get the bracket\n #\n return _get_sa_bracket(imtstr, saset)\n else:\n raise ValueError(f\"Unknown IMT {imtstr} in get_imt_bracket\")\n\n\ndef _get_sa_bracket(myimt, saset):\n \"\"\"\n For a given SA IMT, look through the input SAs and return a tuple of\n a) a pair of IMT strings representing the periods bracketing the given\n period; or b) the single IMT representing the first or last period in\n the input list if the given period is off the end of the list.\n\n Args:\n myper (float): The period to search for in the input lists.\n saset (list): A list of SA IMTs.\n\n Returns:\n tuple: One or two strings representing the IMTs closest to or\n bracketing the input IMT.\n\n \"\"\"\n if not len(saset):\n return ()\n #\n # Stick the target IMT into a copy of the list of SAs, then sort\n # the list by period.\n #\n ss = saset.copy()\n ss.append(myimt)\n tmplist = sorted(ss, key=_get_period_from_imt)\n nimt = len(tmplist)\n #\n # Get the index of the target IMT in the sorted list\n #\n myix = tmplist.index(myimt)\n #\n # If the target IMT is off the end of the list, return the\n # appropriate endpoint; else return the pair of IMTs that\n # bracket the target.\n #\n if myix == 0:\n return (tmplist[1],)\n elif myix == nimt - 1:\n return (tmplist[-2],)\n else:\n return (tmplist[myix - 1], tmplist[myix + 1])\n\n\ndef _get_imt_lists(df):\n \"\"\"\n Given a data frame, return a list of lists of valid IMTS for\n each station in the dataframe; also return a list of the valid\n SA IMTs for each station.\n\n Args:\n df (DataFrame): A DataFrame.\n\n Returns:\n list, list: Two lists of lists: each list contains lists\n corresponding to the stations in the data frame: the first\n list contains all of the valid IMTs for that station, the\n second list contains just the valid SA IMTs for the station.\n \"\"\"\n imtlist = []\n salist = []\n nlist = np.size(df.df[\"lon\"])\n for ix in range(nlist):\n valid_imts = []\n sa_imts = []\n if \"flagged\" not in df.df or not df.df[\"flagged\"][ix]:\n for this_imt in df.imts:\n if (\n not np.isnan(df.df[this_imt + \"_residual\"][ix])\n and not df.df[this_imt + \"_outliers\"][ix]\n ):\n valid_imts.append(this_imt)\n if this_imt.startswith(\"SA(\"):\n sa_imts.append(this_imt)\n imtlist.append(valid_imts)\n salist.append(sa_imts)\n return imtlist, salist\n\n\ndef _get_map_grade(do_grid, outsd, psd, moutgrid):\n \"\"\"\n Computes a 'grade' for the map. Essentially looks at the ratio of\n the computed PGA uncertainty to the predicted PGA uncertainty for\n the area inside the MMI 6 contour. If the maximum MMI is less than\n 6, or the map is not a grid, the grade and mean ratio are set to '--'.\n\n Args:\n do_grid (bool): Is the map a grid (True) or a list of points\n (False)?\n\n outsd (dict): A dictionary of computed uncertainty arrays.\n\n psd (dict): A dictionary of predicted uncertainty arrays.\n\n moutgrid (dict): A dictionary of landmasked output ground\n motion arrays.\n\n Returns:\n tuple: The mean uncertainty ratio and the letter grade.\n \"\"\"\n mean_rat = \"--\"\n mygrade = \"--\"\n if not do_grid or \"PGA\" not in outsd or \"PGA\" not in psd or \"MMI\" not in moutgrid:\n return mean_rat, mygrade\n sd_rat = outsd[\"PGA\"] / psd[\"PGA\"]\n mmimasked = ma.masked_less(moutgrid[\"MMI\"], 6.0)\n mpgasd_rat = ma.masked_array(sd_rat, mask=mmimasked.mask)\n if not np.all(mpgasd_rat.mask):\n gvals = [0.96, 0.98, 1.05, 1.25]\n grades = [\"A\", \"B\", \"C\", \"D\", \"F\"]\n mean_rat = mpgasd_rat.mean()\n for ix, val in enumerate(gvals):\n if mean_rat <= val:\n mygrade = grades[ix]\n break\n if mygrade == \"--\":\n mygrade = \"F\"\n return mean_rat, mygrade\n\n\ndef _get_layer_info(layer):\n \"\"\"\n We need a way to get units information about intensity measure types\n and translate between OpenQuake naming convention and ShakeMap grid naming\n convention.\n\n Args:\n layer (str): ShakeMap grid name.\n\n Returns:\n tuple: Tuple including:\n\n - OpenQuake naming convention,\n - units,\n - significant digits.\n\n \"\"\"\n layer_out = layer\n layer_units = \"\"\n layer_digits = 4 # number of significant digits\n\n if layer.endswith(\"_sd\"):\n layer_out = oq_to_file(layer.replace(\"_sd\", \"\"))\n layer_out = layer_out + \"_sd\"\n else:\n layer_out = oq_to_file(layer)\n if layer.startswith(\"SA\"):\n layer_units = \"ln(g)\"\n elif layer.startswith(\"PGA\"):\n layer_units = \"ln(g)\"\n elif layer.startswith(\"PGV\"):\n layer_units = \"ln(cm/s)\"\n elif layer.startswith(\"MMI\"):\n layer_units = \"intensity\"\n layer_digits = 2\n elif layer.startswith(\"vs30\"):\n layer_units = \"m/s\"\n else:\n raise ValueError(f\"Unknown layer type: {layer}\")\n\n return (layer_out, layer_units, layer_digits)\n",
"# stdlib imports\nimport os.path\nimport json\n\n# third party imports\nimport numpy as np\nfrom impactutils.io.smcontainers import ShakeMapOutputContainer\n\n# local imports\nfrom .base import CoreModule, Contents\nfrom shakemap.utils.config import get_config_paths\n\n\nclass InfoModule(CoreModule):\n \"\"\"\n info -- Extract info.json from shake_result.hdf and write it as a file.\n \"\"\"\n\n command_name = \"info\"\n targets = [r\"products/info\\.json\"]\n dependencies = [(\"products/shake_result.hdf\", True)]\n\n def __init__(self, eventid):\n super(InfoModule, self).__init__(eventid)\n self.contents = Contents(None, None, eventid)\n\n def execute(self):\n \"\"\"\n Write info.json metadata file.\n\n Raises:\n NotADirectoryError: When the event data directory does not exist.\n FileNotFoundError: When the the shake_result HDF file does not\n exist.\n \"\"\"\n install_path, data_path = get_config_paths()\n datadir = os.path.join(data_path, self._eventid, \"current\", \"products\")\n if not os.path.isdir(datadir):\n raise NotADirectoryError(\"%s is not a valid directory.\" % datadir)\n datafile = os.path.join(datadir, \"shake_result.hdf\")\n if not os.path.isfile(datafile):\n raise FileNotFoundError(\"%s does not exist.\" % datafile)\n\n # Open the ShakeMapOutputContainer and extract the data\n container = ShakeMapOutputContainer.load(datafile)\n\n # Create ShakeMap metadata file\n self.logger.debug(\"Writing info.json file...\")\n info = container.getMetadata()\n\n # Clean up strec results to be valid json\n if \"strec\" in info:\n for k, v in info[\"strec\"].items():\n if isinstance(v, float):\n if not np.isfinite(v):\n info[\"strec\"][k] = None\n\n infostring = json.dumps(info, allow_nan=False)\n info_file = os.path.join(datadir, \"info.json\")\n f = open(info_file, \"wt\")\n f.write(infostring)\n f.close()\n container.close()\n cap = \"ShakeMap processing parameters and map summary information.\"\n self.contents.addFile(\n \"supplementalInformation\",\n \"Supplemental Information\",\n cap,\n \"info.json\",\n \"application/json\",\n )\n",
"#! /usr/bin/env python\n\nimport json\nimport numpy as np\n\n#\n# You can use this file in two ways: You can call it as a program from\n# a directory with a \"stationlist.json\" file in it, and it will spit out\n# some slightly interesting information. You might do that as a test. Or\n# you can put it in a directory with your code and do:\n#\n# from json2dict import get_station_dict\n#\n# and then call get_station_dict() with the path to a stationlist.json file\n# as an argument, and it will return a dictionary with stuff in it.\n#\n\n\ndef get_station_dict(filename):\n \"\"\"\n This function is called with the path to a stationlist.json file. It\n returns a dictionary with the following keys:\n 'lons': An array of station longitudes\n 'lats': An array of station latitudes\n 'intensity': An array of observed intensities\n 'residuals': An array of residuals (observed - predicted) (not\n including bias)\n 'phi': An array of within-event stddev of the predictions\n 'tau': An array of between-event stddev of the predictions\n 'extra_sigma': An array of the additional stddev of the observations\n 'bias': An array of the bias of the data at the observation points\n 'bias_stddev': An array of the stddev of the bias at the observation\n points\n \"\"\"\n lonlist = []\n latlist = []\n intensitylist = []\n residuallist = []\n philist = []\n taulist = []\n extra_sigma_list = []\n bias_list = []\n bias_sigma_list = []\n with open(filename) as f:\n sdata = json.load(f)\n\n for station in sdata[\"features\"]:\n properties = station[\"properties\"]\n if not properties[\"source\"] == \"DYFI\":\n continue\n if not properties[\"intensity_flag\"] == \"0\":\n continue\n intensity = properties[\"intensity\"]\n if intensity is None or intensity == \"null\":\n continue\n intensitylist.append(float(intensity))\n extra_sigma_list.append(float(properties[\"intensity_stddev\"]))\n for pred in properties[\"predictions\"]:\n if not pred[\"name\"] == \"mmi\":\n continue\n residuallist.append(float(intensity) - float(pred[\"value\"]))\n philist.append(float(pred[\"phi\"]))\n taulist.append(float(pred[\"tau\"]))\n bias_list.append(float(pred[\"bias\"]))\n bias_sigma_list.append(float(pred[\"bias_sigma\"]))\n break\n lonlist.append(float(station[\"geometry\"][\"coordinates\"][0]))\n latlist.append(float(station[\"geometry\"][\"coordinates\"][1]))\n\n sdict = {\n \"lons\": np.array(lonlist),\n \"lats\": np.array(latlist),\n \"intensity\": np.array(intensitylist),\n \"residuals\": np.array(residuallist),\n \"phi\": np.array(philist),\n \"tau\": np.array(taulist),\n \"extra_sigma\": np.array(extra_sigma_list),\n \"bias\": np.array(bias_list),\n \"bias_sigma\": np.array(bias_sigma_list),\n }\n\n return sdict\n\n\nif __name__ == \"__main__\":\n\n sdict = get_station_dict(\"stationlist.json\")\n\n print(\"sdict keys: \", sdict.keys())\n print()\n print(\"Number of stations:\")\n nsta = len(sdict[\"lons\"])\n print(nsta)\n print()\n print(\"Min lon, Max lon, Min lat, Max lat:\")\n if nsta > 0:\n print(\n np.min(sdict[\"lons\"]),\n np.max(sdict[\"lons\"]),\n np.min(sdict[\"lats\"]),\n np.max(sdict[\"lats\"]),\n )\n else:\n print(\"No data\")\n",
"# third party imports\nimport numpy as np\n\n# stdlib imports\nfrom openquake.hazardlib.imt import PGA, PGV, SA\nfrom shakelib.gmice.gmice import GMICE\n\n\nclass AK07(GMICE):\n \"\"\"\n Implements the ground motion intensity conversion equations (GMICE) of\n Atkinson and Kaka (2007). This module implements a simplified version.\n\n References:\n Atkinson, Gail & Kaka, SanLinn. (2007). Relationships between\n Felt Intensity and Instrumental Ground Motion in the Central\n United States and California. Bulletin of The Seismological\n Society of America - BULL SEISMOL SOC AMER.\n 97. 497-510. 10.1785/0120060154.\n \"\"\"\n\n # -----------------------------------------------------------------------\n #\n # MMI = C1 + C2 * log(Y) for c2->T1 < log(Y) <= T1\n # MMI = C3 + C4 * log(Y) for log(Y) > T1\n #\n # or\n #\n # MMI = c2->C1 + c2->C2 * log(Y) + C5 + C6 * M + C7 * log(D)\n # for log(Y) <= c2->T1\n # MMI = C1 + C2 * log(Y) + C5 + C6 * log(D) + C7 * M\n # for c2->T1 < log(Y) <= T1\n # MMI = C3 + C4 * log(Y) + C5 + C6 * M + C7 * log(D)\n # for log(Y) > T1\n #\n # Limit the distance residuals to between 10 and 300 km.\n # Limit the magnitude residuals to between M3.0 and M7.3.\n #\n # Constants taken from Table 4 and 5 in the reference material\n #\n # -----------------------------------------------------------------------\n def __init__(self):\n super().__init__()\n self.min_max = (1.0, 10.0)\n self.name = \"Atkinson and Kaka (2007)\"\n self.scale = \"scale_ak07.ps\"\n self._constants = {\n self._pga: {\n \"C1\": 2.65,\n \"C2\": 1.39,\n \"C3\": -1.91,\n \"C4\": 4.09,\n \"C5\": -1.96,\n \"C6\": 0.02,\n \"C7\": 0.98,\n \"T1\": 1.69,\n \"T2\": 5,\n \"SMMI\": 0.89,\n },\n self._pgv: {\n \"C1\": 4.37,\n \"C2\": 1.32,\n \"C3\": 3.54,\n \"C4\": 3.03,\n \"C5\": 0.47,\n \"C6\": -0.19,\n \"C7\": 0.26,\n \"T1\": 0.48,\n \"T2\": 5,\n \"SMMI\": 0.76,\n },\n self._sa03: {\n \"C1\": 2.4,\n \"C2\": 1.36,\n \"C3\": -1.83,\n \"C4\": 3.56,\n \"C5\": -0.11,\n \"C6\": -0.2,\n \"C7\": 0.64,\n \"T1\": 1.92,\n \"T2\": 5,\n \"SMMI\": 0.79,\n },\n self._sa10: {\n \"C1\": 3.23,\n \"C2\": 1.18,\n \"C3\": 0.57,\n \"C4\": 2.95,\n \"C5\": 1.92,\n \"C6\": -0.39,\n \"C7\": 0.04,\n \"T1\": 1.5,\n \"T2\": 5,\n \"SMMI\": 0.73,\n },\n self._sa30: {\n \"C1\": 3.72,\n \"C2\": 1.29,\n \"C3\": 1.99,\n \"C4\": 3.0,\n \"C5\": 2.24,\n \"C6\": -0.33,\n \"C7\": -0.31,\n \"T1\": 1,\n \"T2\": 5,\n \"SMMI\": 0.72,\n },\n }\n\n self.DEFINED_FOR_INTENSITY_MEASURE_TYPES = set([PGA, PGV, SA])\n\n self.DEFINED_FOR_SA_PERIODS = set([0.3, 1.0, 3.0])\n\n def getMIfromGM(self, amps, imt, dists=None, mag=None):\n \"\"\"\n Function to compute macroseismic intensity from ground-motion\n intensity. Supported ground-motion IMTs are PGA, PGV and PSA\n at 0.3, 1.0, and 2.0 sec periods.\n\n Args:\n amps (ndarray):\n Ground motion amplitude; natural log units; g for PGA and\n PSA, cm/s for PGV.\n imt (OpenQuake IMT):\n Type the input amps (must be one of PGA, PGV, or SA).\n Supported SA periods are 0.3, 1.0, and 3.0 sec.\n `[link] <http://docs.openquake.org/oq-hazardlib/master/imt.html>`\n dists (ndarray):\n Numpy array of distances from rupture (km).\n mag (float):\n Earthquake magnitude.\n\n Returns:\n ndarray of Modified Mercalli Intensity and ndarray of\n dMMI / dln(amp) (i.e., the slope of the relationship at the\n point in question).\n \"\"\"\n lfact = np.log10(np.e)\n c = self._getConsts(imt)\n if dists is not None and mag is not None:\n doresid = True\n # Limit distances and take the log10\n ldd = np.log10(np.clip(dists, 10, 300))\n # Llimit magnitudes\n lmm = np.clip(mag, 3.0, 7.3)\n else:\n doresid = False\n\n # Account for ln form of amplitudes\n # Convert (for accelerations) from ln(g) to cm/s^2\n # then take the log10\n #\n if imt != self._pgv:\n units = 981.0\n else:\n units = 1.0\n #\n # Math: log10(981 * exp(amps)) = log10(981) + log10(exp(amps))\n # = log10(981) + amps * log10(e)\n # For PGV, just convert ln(amp) to log10(amp) by multiplying\n # by log10(e)\n #\n lamps = np.log10(units) + amps * lfact\n mmi = np.zeros_like(amps)\n dmmi_damp = np.zeros_like(amps)\n #\n # This is the lower segment of the bi-linear fit\n # where log(Y) is less than T1\n #\n idx = lamps < c[\"T1\"]\n mmi[idx] = c[\"C1\"] + c[\"C2\"] * lamps[idx]\n dmmi_damp[idx] = c[\"C2\"] * lfact\n #\n # This is the upper segment of the bi-linear fit\n # where log(Y) is greater than or equal to T1\n #\n idx = lamps >= c[\"T1\"]\n mmi[idx] = c[\"C3\"] + c[\"C4\"] * lamps[idx]\n dmmi_damp[idx] = c[\"C4\"] * lfact\n\n # Inclusion of residuals if magnitude and\n # distance information is available\n if doresid:\n mmi += c[\"C5\"] + c[\"C6\"] * lmm + c[\"C7\"] * ldd\n\n # Limit mmi values\n mmi = np.clip(mmi, 1.0, 10.0)\n return mmi, dmmi_damp\n\n def getGMfromMI(self, mmi, imt, dists=None, mag=None):\n \"\"\"\n Function to tcompute ground-motion intensity from macroseismic\n intensity. Supported IMTs are PGA, PGV and PSA for 0.3, 1.0, and\n 3.0 sec periods.\n\n Args:\n mmi (ndarray):\n Macroseismic intensity.\n imt (OpenQuake IMT):\n IMT of the requested ground-motions intensities (must be\n one of PGA, PGV, or SA).\n `[link] <http://docs.openquake.org/oq-hazardlib/master/imt.html>`\n dists (ndarray):\n Rupture distances (km) to the corresponding MMIs.\n mag (float):\n Earthquake magnitude.\n\n Returns:\n Ndarray of ground motion intensity in natural log of g for PGA\n and PSA, and natural log cm/s for PGV; ndarray of dln(amp) / dMMI\n (i.e., the slope of the relationship at the point in question).\n \"\"\"\n lfact = np.log10(np.e)\n c = self._getConsts(imt)\n mmi = mmi.copy()\n # Set nan values to 1\n ix_nan = np.isnan(mmi)\n mmi[ix_nan] = 1.0\n\n if dists is not None and mag is not None:\n doresid = True\n # Limit distances and take the log10\n ldd = np.log10(np.clip(dists, 10, 300))\n # Limit magnitudes\n lmm = np.clip(mag, 3.0, 7.3)\n else:\n doresid = False\n\n # Inclusion of residuals if magnitude and\n # distance information is available\n if doresid:\n mmi -= c[\"C5\"] + c[\"C6\"] * lmm + c[\"C7\"] * ldd\n\n pgm = np.zeros_like(mmi)\n dpgm_dmmi = np.zeros_like(mmi)\n #\n # This is the lower segment of the bi-linear fit\n # where MMI is less than I5\n #\n idx = mmi < c[\"T2\"]\n pgm[idx] = np.power(10, (mmi[idx] - c[\"C1\"]) / c[\"C2\"])\n dpgm_dmmi[idx] = 1.0 / (c[\"C2\"] * lfact)\n #\n # This is the upper segment of the bi-linear fit\n # where MMI is greater than or equal to I5\n #\n idx = mmi >= c[\"T2\"]\n pgm[idx] = np.power(10, (mmi[idx] - c[\"C3\"]) / c[\"C4\"])\n dpgm_dmmi[idx] = 1.0 / (c[\"C4\"] * lfact)\n\n if imt != self._pgv:\n units = 981.0\n else:\n units = 1.0\n\n # Return a ln(amp) value. Convert PGA to from cm/s^2 to g\n pgm /= units\n pgm = np.log(pgm)\n\n # Set nan values back from 1 to nan\n pgm[ix_nan] = np.nan\n dpgm_dmmi[ix_nan] = np.nan\n\n return pgm, dpgm_dmmi\n\n def getGM2MIsd(self):\n \"\"\"\n Return a dictionary of standard deviations for the ground-motion\n to MMI conversion. The keys are the ground motion types.\n\n Returns:\n Dictionary of GM to MI sigmas (in MMI units).\n \"\"\"\n return {\n self._pga: self._constants[self._pga][\"SMMI\"],\n self._pgv: self._constants[self._pgv][\"SMMI\"],\n self._sa03: self._constants[self._sa03][\"SMMI\"],\n self._sa10: self._constants[self._sa10][\"SMMI\"],\n self._sa30: self._constants[self._sa30][\"SMMI\"],\n }\n\n def getMI2GMsd(self):\n \"\"\"\n Return a dictionary of standard deviations for the MMI\n to ground-motion conversion. The keys are the ground motion\n types.\n\n Returns:\n Dictionary of MI to GM sigmas (ln(PGM) units).\n \"\"\"\n #\n # Need to convert log10 to ln units\n #\n lfact = np.log(10.0)\n return {\n self._pga: lfact * 0.57,\n self._pgv: lfact * 0.52,\n self._sa03: lfact * 0.63,\n self._sa10: lfact * 0.57,\n self._sa30: lfact * 0.81,\n }\n\n def _getConsts(self, imt):\n \"\"\"\n Helper function to get the constants.\n \"\"\"\n\n if (\n imt != self._pga\n and imt != self._pgv\n and imt != self._sa03\n and imt != self._sa10\n and imt != self._sa30\n ):\n raise ValueError(\"Invalid IMT \" + str(imt))\n c = self._constants[imt]\n return c\n",
"#!/usr/bin/env python\n\nimport numpy as np\nimport pytest\n\nfrom shakelib.correlation.dummy import DummyCorrelation\n\n\ndef test_dummy_correlation():\n #\n # Pick some common periods\n #\n t1 = np.array([0.01, 0.3, 1.0, 2.0, 3.0])\n dummy = DummyCorrelation(t1)\n #\n # Distances from 0 to 400\n #\n d = np.linspace(0.0, 400.0, 201)\n #\n # Random cross correlations to the periods in t1\n #\n ix1 = np.array(\n [\n 0,\n 2,\n 1,\n 0,\n 1,\n 1,\n 2,\n 0,\n 3,\n 4,\n 1,\n 0,\n 2,\n 1,\n 2,\n 2,\n 2,\n 2,\n 0,\n 0,\n 2,\n 1,\n 1,\n 3,\n 0,\n 1,\n 1,\n 0,\n 3,\n 1,\n 3,\n 4,\n 3,\n 4,\n 1,\n 0,\n 1,\n 1,\n 3,\n 3,\n 4,\n 1,\n 0,\n 4,\n 0,\n 1,\n 1,\n 3,\n 3,\n 2,\n 0,\n 1,\n 1,\n 0,\n 2,\n 3,\n 2,\n 0,\n 1,\n 4,\n 2,\n 4,\n 4,\n 4,\n 3,\n 2,\n 1,\n 1,\n 3,\n 2,\n 4,\n 4,\n 3,\n 1,\n 3,\n 1,\n 3,\n 1,\n 4,\n 1,\n 4,\n 2,\n 3,\n 2,\n 0,\n 4,\n 2,\n 1,\n 0,\n 1,\n 2,\n 1,\n 2,\n 2,\n 0,\n 2,\n 0,\n 4,\n 4,\n 3,\n 0,\n 4,\n 4,\n 0,\n 4,\n 0,\n 0,\n 3,\n 1,\n 3,\n 1,\n 3,\n 1,\n 0,\n 3,\n 3,\n 1,\n 1,\n 4,\n 0,\n 1,\n 2,\n 4,\n 1,\n 3,\n 4,\n 1,\n 0,\n 3,\n 4,\n 1,\n 4,\n 2,\n 4,\n 4,\n 4,\n 2,\n 4,\n 2,\n 2,\n 0,\n 3,\n 2,\n 3,\n 2,\n 4,\n 3,\n 4,\n 4,\n 0,\n 1,\n 1,\n 1,\n 0,\n 3,\n 2,\n 0,\n 0,\n 3,\n 4,\n 3,\n 0,\n 3,\n 4,\n 2,\n 3,\n 2,\n 4,\n 2,\n 4,\n 1,\n 3,\n 0,\n 0,\n 3,\n 4,\n 2,\n 0,\n 3,\n 2,\n 2,\n 0,\n 2,\n 2,\n 0,\n 2,\n 4,\n 2,\n 0,\n 0,\n 0,\n 1,\n 1,\n 2,\n 3,\n 2,\n 0,\n 3,\n 0,\n 1,\n 4,\n ]\n )\n ix2 = np.array(\n [\n 2,\n 4,\n 0,\n 2,\n 3,\n 1,\n 3,\n 1,\n 3,\n 2,\n 1,\n 0,\n 3,\n 2,\n 4,\n 3,\n 2,\n 3,\n 1,\n 4,\n 3,\n 4,\n 1,\n 0,\n 2,\n 1,\n 1,\n 3,\n 0,\n 1,\n 2,\n 0,\n 3,\n 2,\n 1,\n 1,\n 2,\n 1,\n 2,\n 1,\n 4,\n 4,\n 1,\n 0,\n 3,\n 3,\n 0,\n 4,\n 4,\n 0,\n 1,\n 1,\n 0,\n 2,\n 3,\n 0,\n 1,\n 4,\n 1,\n 3,\n 4,\n 3,\n 4,\n 2,\n 3,\n 4,\n 3,\n 4,\n 0,\n 0,\n 2,\n 2,\n 1,\n 3,\n 3,\n 3,\n 0,\n 0,\n 2,\n 0,\n 4,\n 3,\n 2,\n 4,\n 4,\n 1,\n 3,\n 2,\n 3,\n 2,\n 1,\n 2,\n 2,\n 3,\n 3,\n 1,\n 4,\n 2,\n 0,\n 2,\n 4,\n 0,\n 1,\n 3,\n 3,\n 3,\n 1,\n 3,\n 2,\n 3,\n 2,\n 1,\n 0,\n 3,\n 3,\n 0,\n 1,\n 2,\n 0,\n 1,\n 3,\n 3,\n 2,\n 4,\n 0,\n 2,\n 0,\n 1,\n 2,\n 4,\n 4,\n 2,\n 3,\n 4,\n 2,\n 2,\n 4,\n 2,\n 3,\n 0,\n 3,\n 3,\n 2,\n 4,\n 3,\n 2,\n 2,\n 4,\n 1,\n 2,\n 1,\n 2,\n 2,\n 1,\n 3,\n 1,\n 2,\n 1,\n 3,\n 2,\n 1,\n 3,\n 0,\n 0,\n 3,\n 0,\n 0,\n 2,\n 3,\n 2,\n 2,\n 1,\n 2,\n 4,\n 0,\n 2,\n 2,\n 3,\n 2,\n 1,\n 0,\n 3,\n 0,\n 3,\n 1,\n 0,\n 2,\n 1,\n 4,\n 2,\n 4,\n 2,\n 3,\n 4,\n 4,\n 3,\n 2,\n 0,\n 1,\n 4,\n 1,\n ]\n )\n cor = dummy.getCorrelation(ix1, ix2, d)\n cor_target = np.array(\n [\n 1.00000000e-02,\n 2.72910251e-01,\n 2.23440015e-02,\n 5.48811636e-03,\n 6.73993446e-02,\n 3.67879441e-01,\n 1.50597106e-01,\n 8.21989880e-03,\n 2.01896518e-01,\n 5.50996294e-02,\n 1.35335283e-01,\n 1.10803158e-01,\n 4.53589766e-02,\n 2.22820735e-02,\n 2.02700209e-02,\n 2.48935342e-02,\n 4.07622040e-02,\n 1.66866350e-02,\n 9.10790748e-04,\n 7.45692395e-05,\n 9.15781944e-03,\n 1.49955768e-03,\n 1.22773399e-02,\n 5.02591787e-05,\n 8.22974705e-05,\n 6.73794700e-03,\n 5.51656442e-03,\n 2.25829047e-05,\n 1.84893186e-05,\n 3.02755475e-03,\n 1.23937609e-03,\n 6.76476879e-06,\n 1.66155727e-03,\n 4.53456013e-04,\n 1.11377515e-03,\n 3.03960655e-05,\n 2.23975743e-04,\n 6.11252761e-04,\n 2.50225717e-04,\n 6.14602468e-05,\n 3.35462628e-04,\n 2.74653570e-05,\n 7.49557747e-06,\n 6.13685979e-07,\n 7.53665375e-07,\n 1.85114706e-05,\n 3.36798006e-06,\n 5.51493770e-05,\n 4.51524910e-05,\n 5.54515994e-07,\n 1.51333099e-06,\n 3.71703187e-05,\n 1.01441610e-06,\n 2.49160097e-07,\n 1.01997517e-05,\n 8.35085040e-08,\n 4.10225882e-06,\n 3.73182828e-08,\n 9.16608774e-06,\n 5.00303861e-06,\n 2.04807078e-06,\n 3.35363707e-06,\n 4.11858871e-06,\n 1.12400508e-06,\n 2.76077257e-06,\n 7.53443136e-07,\n 2.77590180e-07,\n 1.51514411e-07,\n 6.20247540e-09,\n 1.01563147e-08,\n 2.77176240e-07,\n 2.26932711e-07,\n 8.36085554e-08,\n 6.84528955e-08,\n 3.73629938e-07,\n 4.58853481e-08,\n 1.25225819e-09,\n 6.83508192e-09,\n 5.59609177e-08,\n 4.58169243e-09,\n 1.12535175e-07,\n 4.60680042e-08,\n 3.77172917e-08,\n 2.05868711e-08,\n 1.68551045e-10,\n 4.13993772e-09,\n 1.69474716e-08,\n 8.32524973e-09,\n 1.13602300e-10,\n 5.58058178e-09,\n 4.56899392e-09,\n 3.74077584e-09,\n 1.02089607e-08,\n 4.17919505e-09,\n 3.42163551e-11,\n 1.68083893e-09,\n 1.52906058e-11,\n 1.25188892e-09,\n 1.02495996e-11,\n 1.25874936e-09,\n 6.87051207e-12,\n 5.62509953e-12,\n 1.38163259e-10,\n 5.65592546e-12,\n 6.17424015e-10,\n 3.79128021e-12,\n 2.06935847e-11,\n 5.08274226e-10,\n 1.24841922e-10,\n 3.40706402e-10,\n 8.36840428e-11,\n 3.42573497e-11,\n 6.23278793e-12,\n 7.65446274e-13,\n 1.25338881e-10,\n 5.13093982e-13,\n 8.40171644e-11,\n 2.06362309e-11,\n 1.87727965e-13,\n 1.53698658e-12,\n 5.66270182e-12,\n 1.54540937e-11,\n 8.43516121e-12,\n 2.07183777e-12,\n 8.48138647e-14,\n 4.62931462e-12,\n 3.79016225e-13,\n 3.10312239e-13,\n 3.81093260e-12,\n 6.24025543e-12,\n 5.10908903e-13,\n 1.39432277e-12,\n 1.71236240e-12,\n 2.80392751e-12,\n 7.65220560e-13,\n 6.26509606e-13,\n 5.12942681e-13,\n 4.19961948e-13,\n 5.15753642e-13,\n 8.44526736e-15,\n 3.45720005e-15,\n 5.66103201e-13,\n 4.63486100e-13,\n 2.52980216e-13,\n 1.55342012e-13,\n 8.47888549e-14,\n 1.04128865e-13,\n 1.70507007e-13,\n 1.39599331e-14,\n 1.14294265e-15,\n 9.35762297e-14,\n 2.29841211e-14,\n 1.88178068e-14,\n 1.71185746e-15,\n 4.20465104e-14,\n 1.03274313e-14,\n 2.81846188e-16,\n 7.69187138e-16,\n 1.88927149e-14,\n 5.15601558e-15,\n 1.89962483e-15,\n 5.18427090e-17,\n 4.24452202e-17,\n 2.31674714e-17,\n 2.84518819e-15,\n 2.32944307e-17,\n 3.81437336e-17,\n 1.04098159e-15,\n 1.27842546e-15,\n 6.97790829e-16,\n 5.14172529e-16,\n 2.10484431e-16,\n 1.14886718e-17,\n 3.13537630e-18,\n 3.85054350e-18,\n 2.10170559e-16,\n 5.16219299e-16,\n 2.11322308e-18,\n 1.73016072e-16,\n 8.49921475e-17,\n 2.31952283e-18,\n 9.49532337e-19,\n 1.55482265e-18,\n 6.36490560e-17,\n 3.47409597e-18,\n 8.53304763e-19,\n 2.32875617e-17,\n 1.71596186e-17,\n 1.56101194e-19,\n 3.83414545e-19,\n 1.04637760e-19,\n 7.71031366e-18,\n 3.15633546e-18,\n 5.74264201e-18,\n 9.40335524e-18,\n 5.77411209e-18,\n 9.45488627e-20,\n 3.87050308e-20,\n 2.11259993e-19,\n 5.18895161e-19,\n 4.24835426e-19,\n ]\n )\n np.testing.assert_allclose(cor, cor_target)\n\n #\n # Test error checks\n #\n ix3 = ix2[1:-1]\n with pytest.raises(ValueError) as e:\n cor = dummy.getCorrelation(ix1, ix3, d)\n\n d = np.linspace(-1.0, 400.0, 201)\n with pytest.raises(ValueError) as e:\n cor = dummy.getCorrelation(ix1, ix2, d)\n\n t1 = np.array([0.001, 0.3, 1.0, 2.0, 3.0])\n with pytest.raises(ValueError) as e:\n dummy = DummyCorrelation(t1)\n\n t1 = np.array([0.01, 0.3, 1.0, 2.0, 3.0, 20.0])\n with pytest.raises(ValueError) as e: # noqa\n dummy = DummyCorrelation(t1)\n\n\nif __name__ == \"__main__\":\n test_dummy_correlation()\n"
] | [
[
"numpy.full_like",
"numpy.log10",
"numpy.testing.assert_allclose"
],
[
"pandas.DataFrame"
],
[
"numpy.diag",
"numpy.dot",
"numpy.ma.masked_less",
"numpy.radians",
"numpy.sqrt",
"numpy.all",
"numpy.seterr",
"numpy.max",
"numpy.concatenate",
"numpy.zeros_like",
"numpy.mean",
"numpy.any",
"numpy.exp",
"numpy.ma.is_masked",
"numpy.where",
"numpy.char.encode",
"numpy.clip",
"numpy.unique",
"numpy.empty_like",
"numpy.arange",
"numpy.linalg.multi_dot",
"numpy.full",
"numpy.size",
"numpy.zeros",
"numpy.log",
"numpy.multiply",
"numpy.power",
"numpy.logspace",
"numpy.isnan",
"numpy.min",
"numpy.genfromtxt",
"numpy.full_like",
"numpy.floor",
"numpy.meshgrid",
"numpy.array",
"numpy.sum",
"numpy.abs",
"numpy.ones",
"numpy.linalg.pinv",
"numpy.shape",
"numpy.ma.masked_array",
"numpy.add",
"numpy.empty"
],
[
"numpy.isfinite"
],
[
"numpy.max",
"numpy.array",
"numpy.min"
],
[
"numpy.log",
"numpy.power",
"numpy.isnan",
"numpy.clip",
"numpy.log10",
"numpy.zeros_like"
],
[
"numpy.array",
"numpy.linspace",
"numpy.testing.assert_allclose"
]
] | [
{
"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": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
paavalipopov/introspection | [
"ee486a9e8c8b6ddb7ab257eae9e14aac5d637527"
] | [
"src/scripts/tune_ts_mlp_oasis_cv.py"
] | [
"# pylint: disable-all\nimport argparse\n\nfrom animus import EarlyStoppingCallback, IExperiment\nfrom animus.torch.callbacks import TorchCheckpointerCallback\nfrom apto.utils.report import get_classification_report\nfrom catalyst import utils\nimport numpy as np\nimport optuna\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import StratifiedKFold\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader, TensorDataset\nfrom tqdm.auto import tqdm\n\nfrom src.settings import LOGS_ROOT, UTCNOW\nfrom src.ts import load_balanced_OASIS, TSQuantileTransformer\n\nimport wandb\n\n\nclass ResidualBlock(nn.Module):\n def __init__(self, block):\n super().__init__()\n self.block = block\n\n def forward(self, x: torch.Tensor):\n return self.block(x) + x\n\n\nclass MLP(nn.Module):\n def __init__(\n self,\n input_size: int,\n output_size: int,\n dropout: float = 0.5,\n hidden_size: int = 128,\n num_layers: int = 0,\n ):\n super(MLP, self).__init__()\n layers = [\n nn.LayerNorm(input_size),\n nn.Dropout(p=dropout),\n nn.Linear(input_size, hidden_size),\n nn.ReLU(),\n ]\n for _ in range(num_layers):\n layers.append(\n ResidualBlock(\n nn.Sequential(\n nn.LayerNorm(hidden_size),\n nn.Dropout(p=dropout),\n nn.Linear(hidden_size, hidden_size),\n nn.ReLU(),\n )\n )\n )\n layers.append(\n nn.Sequential(\n nn.LayerNorm(hidden_size),\n nn.Dropout(p=dropout),\n nn.Linear(hidden_size, output_size),\n )\n )\n\n self.fc = nn.Sequential(*layers)\n\n def forward(self, x):\n bs, ln, fs = x.shape\n fc_output = self.fc(x.reshape(-1, fs))\n fc_output = fc_output.reshape(bs, ln, -1).mean(1) # .squeeze(1)\n return fc_output\n\n\nclass Experiment(IExperiment):\n def __init__(self, quantile: bool, max_epochs: int, logdir: str) -> None:\n super().__init__()\n assert not quantile, \"Not implemented yet\"\n self._quantile: bool = quantile\n self._trial: optuna.Trial = None\n self.max_epochs = max_epochs\n self.logdir = logdir\n\n def on_tune_start(self, trial, k):\n self.k = k\n self.trial = trial\n features, labels = load_balanced_OASIS()\n\n skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42 + trial)\n skf.get_n_splits(features, labels)\n\n train_index, test_index = list(skf.split(features, labels))[self.k]\n\n X_train, X_test = features[train_index], features[test_index]\n y_train, y_test = labels[train_index], labels[test_index]\n\n X_train = np.swapaxes(X_train, 1, 2) # [n_samples; seq_len; n_features]\n X_test = np.swapaxes(X_test, 1, 2)\n\n self._train_ds = TensorDataset(\n torch.tensor(X_train, dtype=torch.float32),\n torch.tensor(y_train, dtype=torch.int64),\n )\n self._valid_ds = TensorDataset(\n torch.tensor(X_test, dtype=torch.float32),\n torch.tensor(y_test, dtype=torch.int64),\n )\n\n def on_experiment_start(self, exp: \"IExperiment\"):\n # init wandb logger\n self.wandb_logger: wandb.run = wandb.init(\n project=\"mlp_oasis_cv_1\", name=f\"{UTCNOW}-k_{self.k}-trial_{self.trial}\"\n )\n\n super().on_experiment_start(exp)\n # # setup experiment\n # self.num_epochs = self._trial.suggest_int(\"exp.num_epochs\", 20, self.max_epochs)\n # # setup data\n # self.batch_size = self._trial.suggest_int(\"data.batch_size\", 4, 32, log=True)\n # self.datasets = {\n # \"train\": DataLoader(\n # self._train_ds, batch_size=self.batch_size, num_workers=0, shuffle=True\n # ),\n # \"valid\": DataLoader(\n # self._valid_ds, batch_size=self.batch_size, num_workers=0, shuffle=False\n # ),\n # }\n # # setup model\n # hidden_size = self._trial.suggest_int(\"mlp.hidden_size\", 32, 256, log=True)\n # num_layers = self._trial.suggest_int(\"mlp.num_layers\", 0, 4)\n # dropout = self._trial.suggest_uniform(\"mlp.dropout\", 0.1, 0.9)\n # self.model = MLP(\n # input_size=53, # PRIOR\n # output_size=2, # PRIOR\n # hidden_size=hidden_size,\n # num_layers=num_layers,\n # dropout=dropout,\n # )\n\n # best tune\n # model = MLP(\n # input_size=53, # PRIOR\n # output_size=2, # PRIOR\n # hidden_size=997,\n # num_layers=4,\n # dropout=0.20352535084272705,\n # )\n\n # best cv\n self.num_epochs = 32\n # setup data\n self.batch_size = 6\n self.datasets = {\n \"train\": DataLoader(\n self._train_ds, batch_size=self.batch_size, num_workers=0, shuffle=True\n ),\n \"valid\": DataLoader(\n self._valid_ds, batch_size=self.batch_size, num_workers=0, shuffle=False\n ),\n }\n # setup model\n hidden_size = 142\n num_layers = 2\n dropout = 0.15847198018446662\n self.model = MLP(\n input_size=53, # PRIOR\n output_size=2, # PRIOR\n hidden_size=hidden_size,\n num_layers=num_layers,\n dropout=dropout,\n )\n\n # lr = self._trial.suggest_float(\"adam.lr\", 1e-5, 1e-3, log=True)\n lr = 0.0002222585782420201\n self.criterion = nn.CrossEntropyLoss()\n self.optimizer = optim.Adam(\n self.model.parameters(),\n lr=lr,\n )\n # setup callbacks\n self.callbacks = {\n \"early-stop\": EarlyStoppingCallback(\n minimize=False,\n patience=5,\n dataset_key=\"valid\",\n metric_key=\"score\",\n min_delta=0.001,\n ),\n \"checkpointer\": TorchCheckpointerCallback(\n exp_attr=\"model\",\n logdir=f\"{self.logdir}/{self._trial.number:04d}\",\n dataset_key=\"valid\",\n metric_key=\"score\",\n minimize=False,\n ),\n }\n\n self.wandb_logger.config.update(\n {\n \"num_epochs\": self.num_epochs,\n \"batch_size\": self.batch_size,\n \"hidden_size\": hidden_size,\n \"num_layers\": num_layers,\n \"dropout\": dropout,\n \"lr\": lr,\n }\n )\n\n def run_dataset(self) -> None:\n all_scores, all_targets = [], []\n total_loss = 0.0\n self.model.train(self.is_train_dataset)\n\n with torch.set_grad_enabled(self.is_train_dataset):\n for self.dataset_batch_step, (data, target) in enumerate(tqdm(self.dataset)):\n self.optimizer.zero_grad()\n logits = self.model(data)\n loss = self.criterion(logits, target)\n score = torch.softmax(logits, dim=-1)\n\n all_scores.append(score.cpu().detach().numpy())\n all_targets.append(target.cpu().detach().numpy())\n total_loss += loss.sum().item()\n if self.is_train_dataset:\n loss.backward()\n self.optimizer.step()\n\n total_loss /= self.dataset_batch_step\n\n y_test = np.hstack(all_targets)\n y_score = np.vstack(all_scores)\n y_pred = np.argmax(y_score, axis=-1).astype(np.int32)\n report = get_classification_report(y_true=y_test, y_pred=y_pred, y_score=y_score, beta=0.5)\n for stats_type in [0, 1, \"macro\", \"weighted\"]:\n stats = report.loc[stats_type]\n for key, value in stats.items():\n if \"support\" not in key:\n self._trial.set_user_attr(f\"{key}_{stats_type}\", float(value))\n\n self.dataset_metrics = {\n \"score\": report[\"auc\"].loc[\"weighted\"],\n \"loss\": total_loss,\n }\n\n def on_epoch_end(self, exp: \"IExperiment\") -> None:\n super().on_epoch_end(self)\n self.wandb_logger.log(\n {\n \"train_score\": self.epoch_metrics[\"train\"][\"score\"],\n \"train_loss\": self.epoch_metrics[\"train\"][\"loss\"],\n \"valid_score\": self.epoch_metrics[\"valid\"][\"score\"],\n \"valid_loss\": self.epoch_metrics[\"valid\"][\"loss\"],\n },\n )\n\n def on_experiment_end(self, exp: \"IExperiment\") -> None:\n super().on_experiment_end(exp)\n self._score = self.callbacks[\"early-stop\"].best_score\n\n wandb.summary[\"valid_score\"] = self._score\n self.wandb_logger.finish()\n\n def _objective(self, trial) -> float:\n self._trial = trial\n self.run()\n\n return self._score\n\n def tune(self, n_trials: int):\n for trial in range(n_trials):\n for k in range(5):\n self.on_tune_start(trial, k)\n self.study = optuna.create_study(direction=\"maximize\")\n self.study.optimize(self._objective, n_trials=1, n_jobs=1)\n logfile = f\"{self.logdir}/optuna.csv\"\n df = self.study.trials_dataframe()\n df.to_csv(logfile, index=False)\n\n\nif __name__ == \"__main__\":\n import warnings\n\n warnings.filterwarnings(\"ignore\")\n\n parser = argparse.ArgumentParser()\n utils.boolean_flag(parser, \"quantile\", default=False)\n parser.add_argument(\"--max-epochs\", type=int, default=1)\n parser.add_argument(\"--num-trials\", type=int, default=1)\n args = parser.parse_args()\n Experiment(\n quantile=args.quantile,\n max_epochs=args.max_epochs,\n logdir=f\"{LOGS_ROOT}/{UTCNOW}-ts-mlp-oasis-q{args.quantile}/\",\n ).tune(n_trials=args.num_trials)\n"
] | [
[
"torch.nn.Sequential",
"torch.nn.CrossEntropyLoss",
"numpy.swapaxes",
"numpy.hstack",
"torch.nn.Dropout",
"torch.softmax",
"torch.utils.data.DataLoader",
"sklearn.model_selection.StratifiedKFold",
"torch.nn.LayerNorm",
"torch.tensor",
"torch.nn.Linear",
"torch.set_grad_enabled",
"numpy.argmax",
"torch.nn.ReLU",
"numpy.vstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Unknown-Data/QGCN | [
"e074ada31c13b6de6eabba2b2ebce90e88fdfdbf",
"e074ada31c13b6de6eabba2b2ebce90e88fdfdbf"
] | [
"graph-measures/measure_tests/test_graph.py",
"graph-measures/features_algorithms/accelerated_graph_features/bfs_moments.py"
] | [
"import os\r\n\r\nimport functools\r\nimport pandas as pd\r\nimport networkx as nx\r\n\r\nfrom loggers import EmptyLogger\r\n\r\n\r\nclass TestData:\r\n def __init__(self, logger=None):\r\n if logger is None:\r\n logger = EmptyLogger()\r\n self._logger = logger\r\n self._data_dir = os.path.dirname(os.path.realpath(__file__))\r\n df1 = pd.read_csv(os.path.join(self._data_dir, \"test_undirected\"))\r\n self._ugnx = nx.from_pandas_edgelist(df1, \"n1\", \"n2\", [\"weight\"], create_using=nx.Graph())\r\n\r\n df2 = pd.read_csv(os.path.join(self._data_dir, \"test_directed\"))\r\n self._gnx = nx.from_pandas_edgelist(df2, \"n1\", \"n2\", [\"weight\"], create_using=nx.DiGraph())\r\n\r\n def get_graph(self, is_directed):\r\n return self._gnx if is_directed else self._ugnx\r\n\r\n @staticmethod\r\n def _specific_feature_processing(feature_name, res):\r\n if \"motifs\" in feature_name:\r\n for key, val in res.items():\r\n fixed = {i: int(x) for i, x in enumerate(val[1:])}\r\n fixed[None] = int(val[0])\r\n res[key] = fixed\r\n if feature_name in [\"louvain\"]:\r\n for key, val in res.items():\r\n res[key] = int(val)\r\n return res\r\n\r\n @staticmethod\r\n def feature_name(feature):\r\n if isinstance(feature, functools.partial):\r\n return feature.func.print_name(*feature.args, **feature.keywords)\r\n return feature.print_name()\r\n\r\n def load_feature(self, feature, is_directed):\r\n base_dir = os.path.join(self._data_dir, \"%sdirected\" % (\"\" if is_directed else \"un\"))\r\n feature_name = self.feature_name(feature)\r\n feature_path = os.path.join(base_dir, feature_name + \".txt\")\r\n if not os.path.exists(feature_path):\r\n self._logger.info(\"Feature %s - %s doesn't exists\" % (feature_name, \"directed\" if is_directed else \"undirected\"))\r\n return None\r\n df = pd.read_csv(feature_path, header=None)\r\n res = {int(row[0]): list(map(float, row[1:])) if df.shape[1] > 2 else float(row[1]) for _, row in df.iterrows()}\r\n return self._specific_feature_processing(feature_name, res)\r\n\r\n\r\ndef get_di_graph():\r\n gnx = nx.DiGraph()\r\n gnx.add_edges_from([(12, 1), (1, 12), (2, 3), (3, 4), (5, 2), (2, 6), (4, 7),\r\n (4, 8), (9, 6), (7, 10), (11, 7), (10, 11), (10, 13), (10, 14),\r\n (14, 10), (15, 12), (12, 16), (16, 12), (16, 15)])\r\n # gnx.add_edges_from([(1, 2), (2, 4), (3, 1), (3, 4)])\r\n return gnx\r\n\r\n\r\ndef get_graph():\r\n gnx = nx.Graph()\r\n gnx.add_edges_from([(1, 2), (2, 3), (3, 4), (3, 7), (4, 8), (5, 6), (7, 8),\r\n (5, 10), (7, 10), (7, 11), (11, 12), (10, 13), (9, 14),\r\n (11, 15), (15, 16)])\r\n return gnx\r\n",
"import os\r\nimport sys\r\nimport numpy as np\r\nsys.path.append(os.path.abspath('.'))\r\nsys.path.append(os.path.abspath('..'))\r\nsys.path.append(os.path.abspath('../..'))\r\nsys.path.append(os.path.abspath('../../..'))\r\nsys.path.append(os.path.abspath('src'))\r\nsys.path.append(os.path.abspath('src/accelerated_graph_features'))\r\n\r\nfrom features_infra.feature_calculators import NodeFeatureCalculator, FeatureMeta\r\nfrom features_algorithms.accelerated_graph_features.src import bfs_moments\r\n\r\n\r\nclass BfsMomentsCalculator(NodeFeatureCalculator):\r\n def is_relevant(self):\r\n return True\r\n\r\n def _calculate(self, include: set):\r\n self._features = bfs_moments(self._gnx)\r\n\r\n def _get_feature(self, element):\r\n return np.array(self._features[element])\r\n\r\n\r\nfeature_entry = {\r\n \"bfs_moments\": FeatureMeta(BfsMomentsCalculator, {\"bfs\"}),\r\n}\r\n"
] | [
[
"pandas.read_csv"
],
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
chaitanya2334/lsm | [
"504c732238b419cd77e7e0a97af040778ee9c7dd",
"504c732238b419cd77e7e0a97af040778ee9c7dd"
] | [
"src/evaluator/re.py",
"src/pytorch_models/pos_ffn.py"
] | [
"import itertools as it\nfrom collections import defaultdict\nfrom typing import Dict, List\n\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom pytorch_lightning.metrics import Metric\nfrom sklearn.metrics import accuracy_score, precision_recall_fscore_support\nfrom src import utils as sutils\nfrom src.postprocessing.tensorboard import plot_confusion_matrix\nfrom src.pytorch_models import utils as putils\nfrom torch import Tensor\nfrom torch.nn import functional as F\n\n### EvalRE(pred, true, top_span_mask)\n\n\nclass EvalRE(Metric):\n def __init__(\n self,\n classes_set: Dict[str, List[str]],\n id2label: Dict[int, str],\n neg_class: str,\n compute_on_step: bool,\n prefix: str\n ):\n \"\"\"\n Used to evaluate relations. The result is broken down into:\n 1. Full Relation Eval\n 2. IAP\n 3. CAP - Intra (or within) Sentence\n 4. CAP - Inter (or cross) Sentence\n\n It can be used to evaluate relation predictions based on gold or \n non-gold entities by correctly passing the `pred_span_mask` in \n `update()` function. Ths `pred_span_masks` must be of size \n (batch_size, max_num_spans) where each row represents all spans for \n that sentence. \n\n Args:\n full_classes (List[str]): [description]\n iap_classes (List[str]): [description]\n cap_classes (List[str]): [description]\n id2label (Dict[int, str]): [description]\n neg_class (str): [description]\n compute_on_step (bool): [description]\n prefix (str): [description]\n \"\"\"\n super().__init__(compute_on_step=compute_on_step)\n\n self.neg_class = neg_class\n self.classes = classes_set\n self.id2label = id2label\n self.label2id = {v: k for k, v in id2label.items()}\n self.prefix = prefix\n self.neg_class_id = self.label2id[self.neg_class]\n self.max_step_gap = 5\n self.print_errors = False\n\n states = [\n 'full_preds',\n 'full_target',\n # 'iap_preds',\n # 'iap_target',\n # 'cap_intra_preds',\n # 'cap_intra_target',\n # 'cap_inter_preds',\n # 'cap_inter_target'\n ]\n\n for state in states:\n self.add_state(state, default=[])\n\n def predict(self, rels, ents_df, cross_sentence=True):\n # TODO optimize\n if rels.shape[0] == 0:\n # no predictions to be made\n pred_df = pd.DataFrame(\n {\n 'span1': [], 'span2': [], 'pred_label': []\n },\n columns=['span1', 'span2', 'pred_label']\n )\n return pred_df\n\n if cross_sentence:\n pred_spans = ents_df.values\n span1, span2 = zip(*it.product(pred_spans, repeat=2))\n else:\n spans_by_sents = ents_df.groupby('step_idx')\n span_pairs = spans_by_sents.apply(\n lambda x: list(it.product(x.values, repeat=2))\n ).values.tolist()\n # remove self loops\n span_pairs = [\n (s1, s2)\n for s1,\n s2 in it.chain.from_iterable(span_pairs)\n if not np.array_equal(s1, s2)\n ]\n if len(span_pairs) > 0:\n span1, span2 = zip(*span_pairs)\n else:\n span1 = []\n span2 = []\n\n span1 = np.array(span1)\n span2 = np.array(span2)\n # to list of tuples\n\n if span1.size != 0 and span2.size != 0:\n span1 = list(zip(span1[:, 0], span1[:, 1], span1[:, 2]))\n span2 = list(zip(span2[:, 0], span2[:, 1], span2[:, 2]))\n else:\n span1 = []\n span2 = []\n\n pred_rels = F.softmax(rels, dim=-1)\n pred_rels = torch.argmax(pred_rels, dim=-1)\n pred_rels = pred_rels.view(-1).cpu().detach().numpy()\n pred_df = pd.DataFrame(\n {\n 'span1': span1, 'span2': span2, 'pred_label': pred_rels\n },\n columns=['span1', 'span2', 'pred_label']\n )\n\n # dont store negative samples (memory and time complexity optimization)\n pred_df = pred_df[pred_df.pred_label != self.neg_class_id]\n\n return pred_df\n\n def update(self, pred_df: Tensor, true_df: Tensor):\n \"\"\"\n Update preds and target lists for relation evaluation based on spans to \n keep in `pred_span_mask`.\n\n Args:\n pred (Tensor): 3d tensor of size (max_n_spans, max_n_spans, nb_rels)\n containing predicted relation unnormalized scores. \n true (Tensor): 2d tensor of size (max_n_spans, max_n_spans) \n containing ground truth relation label ids for each span pair.\n pred_span_mask (Tensor): 2d tensor of size (batch_size, num_spans) \n containing boolean values of whether to keep or ignore spans in\n each sentence in the batch. \n spans (Tensor): 3d tensor of size (batch_size, num_spans, 2) the \n exact spans defined by their start and end indices. Useful to\n figure out if a relation is IAP, CAP-inter, or CAP-intra.\n\n \"\"\"\n\n merged = pred_df.set_index(\n ['span1', 'span2']\n ).join(true_df.set_index(['span1', 'span2']), how='outer')\n\n merged = merged.fillna(self.neg_class_id)\n\n pred_labels = merged.pred_label.values.astype(int)\n true_labels = merged.true_label.values.astype(int)\n # pred_rels -> (max_n_spans, max_n_spans)\n\n self.full_preds.append(pred_labels)\n self.full_target.append(true_labels)\n\n if self.print_errors:\n print(merged[merged.pred_label != merged.true_label])\n\n # TODO implement\n # # eval iap\n # self.iap_preds.append(self.make_iap(pred_rels, spans))\n # self.iap_target.append(self.make_iap(true, spans))\n\n # # eval csr intra\n # self.csr_intra_preds.append(self.make_csr_intra(pred_rels, spans))\n # self.csr_intra_target.append(self.make_csr_intra(true, spans))\n\n # # eval csr inter\n # self.csr_inter_preds.append(self.make_csr_inter(pred_rels, spans))\n # self.csr_inter_target.append(self.make_csr_inter(true, spans))\n\n def compute_by_type(self, preds, target, eval_type):\n preds = np.concatenate(preds)\n target = np.concatenate(target)\n\n preds = [self.id2label[t] for t in preds.tolist()]\n target = [self.id2label[t] for t in target.tolist()]\n p, r, f1, _ = precision_recall_fscore_support(\n y_pred=preds,\n y_true=target,\n average='micro',\n labels=self.classes[eval_type]\n )\n acc = accuracy_score(y_pred=preds, y_true=target)\n p_class, r_class, f1_class, _ = precision_recall_fscore_support(\n y_true=target,\n y_pred=preds,\n average=None,\n labels=self.classes[eval_type]\n )\n image = plot_confusion_matrix(\n true=target,\n pred=preds,\n classes=self.classes[eval_type] + [self.neg_class],\n title='Confusion matrix for Relations'\n )\n\n return sutils.flatten_dict(\n {\n f'{self.prefix}_{eval_type}_rel':\n {\n f'{self.prefix}_{eval_type}_rel_acc': acc,\n f'{self.prefix}_{eval_type}_rel_p': p,\n f'{self.prefix}_{eval_type}_rel_r': r,\n f'{self.prefix}_{eval_type}_rel_f1': f1\n },\n f\"{self.prefix}_{eval_type}_rel_per_class\":\n {\n label: {\n \"P\": p_class[i],\n \"R\": r_class[i],\n \"F1\": f1_class[i],\n }\n for i,\n label in enumerate(self.classes[eval_type])\n }\n }\n ), image\n\n def compute(self):\n coll = [\n (\"full\", self.full_preds, self.full_target),\n # (\"iap\", self.iap_preds, self.iap_target),\n # (\"cap_inter\", self.cap_inter_preds, self.cap_inter_target),\n # (\"cap_intra\", self.cap_intra_preds, self.cap_intra_target)\n ]\n ret = dict()\n for eval_type, preds, target in coll:\n ret[eval_type] = self.compute_by_type(preds, target, eval_type)\n\n return ret\n",
"from torch import nn\n\n\nclass posFFN1d(nn.Module):\n def __init__(self, d_hid, d_inner_hid, window=1, dropout=0.1):\n super().__init__()\n self.w_1 = nn.Conv1d(d_hid, d_inner_hid, kernel_size=window)\n self.relu = nn.ReLU()\n self.w_2 = nn.Conv1d(d_inner_hid, d_hid, kernel_size=window)\n self.layer_norm = nn.LayerNorm(d_hid)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, x):\n out = self.w_1(x)\n out = self.relu(out)\n out = self.w_2(out)\n out = self.dropout(out)\n return self.layer_norm(out + x)\n\n\nclass posFFN2d(nn.Module):\n def __init__(self, d_hid, d_inner_hid, window=1, dropout=0.1):\n super().__init__()\n self.w_1 = nn.Conv2d(d_hid, d_inner_hid, kernel_size=window, padding=1)\n self.relu = nn.ReLU()\n self.w_2 = nn.Conv2d(d_inner_hid, d_hid, kernel_size=window, padding=1)\n self.layer_norm = nn.LayerNorm(d_hid)\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, x):\n # -> (N x N x d_hid)\n x = x.permute(2, 0, 1)\n # -> (d_hid x N x N)\n x = x.unsqueeze(0)\n # -> (1 x d_hid x N x N)\n out = self.w_1(x)\n out = self.relu(out)\n out = self.w_2(out)\n out = self.dropout(out)\n # -> (1 x d_hid x N x N)\n out = out.squeeze(0)\n # -> (d_hid x N x N)\n\n x = x.squeeze(0).permute(1, 2, 0)\n # -> (N x N x d_hid)\n\n out = out.permute(1, 2, 0)\n # -> (N x N x d_hid)\n out = self.layer_norm(out + x)\n # -> (N x N x d_hid)\n return out"
] | [
[
"torch.nn.functional.softmax",
"numpy.array_equal",
"sklearn.metrics.accuracy_score",
"pandas.DataFrame",
"numpy.concatenate",
"sklearn.metrics.precision_recall_fscore_support",
"numpy.array",
"torch.argmax"
],
[
"torch.nn.Dropout",
"torch.nn.Conv2d",
"torch.nn.LayerNorm",
"torch.nn.Conv1d",
"torch.nn.ReLU"
]
] | [
{
"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": []
}
] |
hidecharo/Blueqat | [
"8094f45e53da8317193ed3845dbd02e3a82fc06c"
] | [
"blueqat/backends/numpy_backend.py"
] | [
"# Copyright 2019 The Blueqat Developers\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 collections import Counter\nimport math\nimport random\nimport warnings\n\nimport numpy as np\n\nfrom ..gate import *\nfrom ..utils import ignore_global_phase\nfrom .backendbase import Backend\n\nDEFAULT_DTYPE = np.complex128\n\n\nclass _NumPyBackendContext:\n \"\"\"This class is internally used in NumPyBackend\"\"\"\n\n def __init__(self, n_qubits):\n self.n_qubits = n_qubits\n self.qubits = np.zeros(2**n_qubits, dtype=DEFAULT_DTYPE)\n self.qubits_buf = np.zeros(2**n_qubits, dtype=DEFAULT_DTYPE)\n self.indices = np.arange(2**n_qubits, dtype=np.uint32)\n self.save_cache = True\n self.shots_result = Counter()\n self.cregs = None\n\n def prepare(self, cache):\n \"\"\"Prepare to run next shot.\"\"\"\n if cache is not None:\n np.copyto(self.qubits, cache)\n else:\n self.qubits.fill(0.0)\n self.qubits[0] = 1.0\n self.cregs = [0] * self.n_qubits\n\n def store_shot(self):\n \"\"\"Store current cregs to shots_result\"\"\"\n def to_str(cregs):\n return ''.join(str(b) for b in cregs)\n key = to_str(self.cregs)\n self.shots_result[key] = self.shots_result.get(key, 0) + 1\n\n\nclass NumPyBackend(Backend):\n \"\"\"Simulator backend which uses numpy. This backend is Blueqat's default backend.\"\"\"\n __return_type = {\n \"statevector\": lambda ctx: ctx.qubits,\n \"shots\": lambda ctx: ctx.shots_result,\n \"statevector_and_shots\": lambda ctx: (ctx.qubits, ctx.shots_result),\n \"_inner_ctx\": lambda ctx: ctx,\n }\n DEFAULT_SHOTS = 1024\n\n def __init__(self):\n self.cache = None\n self.cache_idx = -1\n\n def __clear_cache(self):\n self.cache = None\n self.cache_idx = -1\n\n def __clear_cache_if_invalid(self, n_qubits, dtype):\n if self.cache is None:\n self.__clear_cache()\n return\n if len(self.cache) != 2**n_qubits:\n self.__clear_cache()\n return\n if self.cache.dtype != dtype:\n self.__clear_cache()\n return\n\n def run(self, gates, n_qubits, *args, **kwargs):\n def __parse_run_args(shots=None, returns=None, ignore_global=True, **_kwargs):\n if returns is None:\n if shots is None:\n returns = \"statevector\"\n else:\n returns = \"shots\"\n if returns not in self.__return_type.keys():\n raise ValueError(f\"Unknown returns type '{returns}'\")\n if shots is None:\n if returns in (\"statevector\", \"_inner_ctx\"):\n shots = 1\n else:\n shots = self.DEFAULT_SHOTS\n if returns == \"statevector\" and shots > 1:\n warnings.warn(\"When `returns` = 'statevector', `shots` = 1 is enough.\")\n return shots, returns, ignore_global\n\n shots, returns, ignore_global = __parse_run_args(*args, **kwargs)\n\n self.__clear_cache_if_invalid(n_qubits, DEFAULT_DTYPE)\n ctx = _NumPyBackendContext(n_qubits)\n\n def run_single_gate(gate):\n nonlocal ctx\n action = self._get_action(gate)\n if action is not None:\n ctx = action(gate, ctx)\n else:\n for g in gate.fallback(n_qubits):\n run_single_gate(g)\n\n for _ in range(shots):\n ctx.prepare(self.cache)\n for gate in gates[self.cache_idx + 1:]:\n run_single_gate(gate)\n if ctx.save_cache:\n self.cache = ctx.qubits.copy()\n self.cache_idx += 1\n if ctx.cregs:\n ctx.store_shot()\n\n if ignore_global:\n ignore_global_phase(ctx.qubits)\n return self.__return_type[returns](ctx)\n\n def make_cache(self, gates, n_qubits):\n self.run(gates, n_qubits)\n\n def gate_x(self, gate, ctx):\n qubits = ctx.qubits\n newq = ctx.qubits_buf\n n_qubits = ctx.n_qubits\n i = ctx.indices\n for target in gate.target_iter(n_qubits):\n t0 = (i & (1 << target)) == 0\n t1 = (i & (1 << target)) != 0\n newq[t0] = qubits[t1]\n newq[t1] = qubits[t0]\n qubits, newq = newq, qubits\n ctx.qubits = qubits\n ctx.qubits_buf = newq\n return ctx\n\n def gate_y(self, gate, ctx):\n qubits = ctx.qubits\n newq = ctx.qubits_buf\n n_qubits = ctx.n_qubits\n i = ctx.indices\n for target in gate.target_iter(n_qubits):\n t0 = (i & (1 << target)) == 0\n t1 = (i & (1 << target)) != 0\n newq[t0] = -1.0j * qubits[t1]\n newq[t1] = 1.0j * qubits[t0]\n qubits, newq = newq, qubits\n ctx.qubits = qubits\n ctx.qubits_buf = newq\n return ctx\n\n def gate_z(self, gate, ctx):\n qubits = ctx.qubits\n n_qubits = ctx.n_qubits\n i = ctx.indices\n for target in gate.target_iter(n_qubits):\n qubits[(i & (1 << target)) != 0] *= -1\n return ctx\n\n def gate_h(self, gate, ctx):\n qubits = ctx.qubits\n newq = ctx.qubits_buf\n n_qubits = ctx.n_qubits\n i = ctx.indices\n for target in gate.target_iter(n_qubits):\n t0 = (i & (1 << target)) == 0\n t1 = (i & (1 << target)) != 0\n newq[t0] = qubits[t0] + qubits[t1]\n newq[t1] = qubits[t0] - qubits[t1]\n newq *= 1 / np.sqrt(2)\n qubits, newq = newq, qubits\n ctx.qubits = qubits\n ctx.qubits_buf = newq\n return ctx\n\n def gate_rx(self, gate, ctx):\n qubits = ctx.qubits\n newq = ctx.qubits_buf\n n_qubits = ctx.n_qubits\n i = ctx.indices\n halftheta = gate.theta * 0.5\n a00 = a11 = np.cos(halftheta)\n a01 = a10 = -1j * np.sin(halftheta)\n for target in gate.target_iter(n_qubits):\n t0 = (i & (1 << target)) == 0\n t1 = (i & (1 << target)) != 0\n newq[t0] = a00 * qubits[t0] + a01 * qubits[t1]\n newq[t1] = a10 * qubits[t0] + a11 * qubits[t1]\n qubits, newq = newq, qubits\n ctx.qubits = qubits\n ctx.qubits_buf = newq\n return ctx\n\n def gate_ry(self, gate, ctx):\n qubits = ctx.qubits\n newq = ctx.qubits_buf\n n_qubits = ctx.n_qubits\n i = ctx.indices\n halftheta = gate.theta * 0.5\n a00 = a11 = np.cos(halftheta)\n a10 = np.sin(halftheta)\n a01 = -a10\n for target in gate.target_iter(n_qubits):\n t0 = (i & (1 << target)) == 0\n t1 = (i & (1 << target)) != 0\n newq[t0] = a00 * qubits[t0] + a01 * qubits[t1]\n newq[t1] = a10 * qubits[t0] + a11 * qubits[t1]\n qubits, newq = newq, qubits\n ctx.qubits = qubits\n ctx.qubits_buf = newq\n return ctx\n\n def gate_rz(self, gate, ctx):\n qubits = ctx.qubits\n n_qubits = ctx.n_qubits\n i = ctx.indices\n halftheta = gate.theta * 0.5\n a0 = complex(math.cos(halftheta), -math.sin(halftheta))\n a1 = complex(math.cos(halftheta), math.sin(halftheta))\n for target in gate.target_iter(n_qubits):\n qubits[(i & (1 << target)) == 0] *= a0\n qubits[(i & (1 << target)) != 0] *= a1\n return ctx\n\n def gate_phase(self, gate, ctx):\n qubits = ctx.qubits\n n_qubits = ctx.n_qubits\n i = ctx.indices\n theta = gate.theta\n a = complex(math.cos(theta), math.sin(theta))\n for target in gate.target_iter(n_qubits):\n qubits[(i & (1 << target)) != 0] *= a\n return ctx\n\n def gate_t(self, gate, ctx):\n qubits = ctx.qubits\n n_qubits = ctx.n_qubits\n i = ctx.indices\n\n sqrt2_inv = 1 / np.sqrt(2)\n factor = complex(sqrt2_inv, sqrt2_inv)\n for target in gate.target_iter(n_qubits):\n qubits[(i & (1 << target)) != 0] *= factor\n return ctx\n\n def gate_s(self, gate, ctx):\n qubits = ctx.qubits\n n_qubits = ctx.n_qubits\n i = ctx.indices\n for target in gate.target_iter(n_qubits):\n qubits[(i & (1 << target)) != 0] *= 1.j\n return ctx\n\n def gate_cz(self, gate, ctx):\n qubits = ctx.qubits\n n_qubits = ctx.n_qubits\n i = ctx.indices\n for control, target in gate.control_target_iter(n_qubits):\n qubits[((i & (1 << control)) != 0) & ((i & (1 << target)) != 0)] *= -1\n return ctx\n\n def gate_cx(self, gate, ctx):\n qubits = ctx.qubits\n newq = ctx.qubits_buf\n n_qubits = ctx.n_qubits\n i = ctx.indices\n for control, target in gate.control_target_iter(n_qubits):\n np.copyto(newq, qubits)\n c1 = (i & (1 << control)) != 0\n t0 = (i & (1 << target)) == 0\n t1 = (i & (1 << target)) != 0\n newq[c1 & t0] = qubits[c1 & t1]\n newq[c1 & t1] = qubits[c1 & t0]\n qubits, newq = newq, qubits\n ctx.qubits = qubits\n ctx.qubits_buf = newq\n return ctx\n\n def gate_crx(self, gate, ctx):\n qubits = ctx.qubits\n newq = ctx.qubits_buf\n n_qubits = ctx.n_qubits\n i = ctx.indices\n halftheta = gate.theta * 0.5\n a00 = a11 = np.cos(halftheta)\n a01 = a10 = -1j * np.sin(halftheta)\n for control, target in gate.control_target_iter(n_qubits):\n np.copyto(newq, qubits)\n c1 = (i & (1 << control)) != 0\n c1t0 = ((i & (1 << target)) == 0) & c1\n c1t1 = ((i & (1 << target)) != 0) & c1\n newq[c1t0] = a00 * qubits[c1t0] + a01 * qubits[c1t1]\n newq[c1t1] = a10 * qubits[c1t0] + a11 * qubits[c1t1]\n qubits, newq = newq, qubits\n ctx.qubits = qubits\n ctx.qubits_buf = newq\n return ctx\n\n def gate_cry(self, gate, ctx):\n qubits = ctx.qubits\n newq = ctx.qubits_buf\n n_qubits = ctx.n_qubits\n i = ctx.indices\n halftheta = gate.theta * 0.5\n a00 = a11 = np.cos(halftheta)\n a10 = np.sin(halftheta)\n a01 = -a10\n for control, target in gate.control_target_iter(n_qubits):\n np.copyto(newq, qubits)\n c1 = (i & (1 << control)) != 0\n c1t0 = ((i & (1 << target)) == 0) & c1\n c1t1 = ((i & (1 << target)) != 0) & c1\n newq[c1t0] = a00 * qubits[c1t0] + a01 * qubits[c1t1]\n newq[c1t1] = a10 * qubits[c1t0] + a11 * qubits[c1t1]\n qubits, newq = newq, qubits\n ctx.qubits = qubits\n ctx.qubits_buf = newq\n return ctx\n\n def gate_crz(self, gate, ctx):\n qubits = ctx.qubits\n n_qubits = ctx.n_qubits\n i = ctx.indices\n halftheta = gate.theta * 0.5\n a0 = complex(math.cos(halftheta), -math.sin(halftheta))\n a1 = complex(math.cos(halftheta), math.sin(halftheta))\n for control, target in gate.control_target_iter(n_qubits):\n c1t0 = ((i & (1 << control)) != 0) & ((i & (1 << target)) == 0)\n c1t1 = ((i & (1 << control)) != 0) & ((i & (1 << target)) != 0)\n qubits[c1t0] *= a0\n qubits[c1t1] *= a1\n return ctx\n\n def gate_cphase(self, gate, ctx):\n qubits = ctx.qubits\n n_qubits = ctx.n_qubits\n i = ctx.indices\n theta = gate.theta\n a = complex(math.cos(theta), math.sin(theta))\n for control, target in gate.control_target_iter(n_qubits):\n c1t1 = ((i & (1 << control)) != 0) & ((i & (1 << target)) != 0)\n qubits[c1t1] *= a\n return ctx\n\n def gate_ccz(self, gate, ctx):\n c1, c2, t = gate.targets\n qubits = ctx.qubits\n n_qubits = ctx.n_qubits\n i = ctx.indices\n indices = (i & (1 << c1)) != 0\n indices &= (i & (1 << c2)) != 0\n indices &= (i & (1 << t)) != 0\n qubits[indices] *= -1\n return ctx\n\n def gate_ccx(self, gate, ctx):\n c1, c2, t = gate.targets\n ctx = self.gate_h(HGate(t), ctx)\n ctx = self.gate_ccz(CCZGate(gate.targets), ctx)\n ctx = self.gate_h(HGate(t), ctx)\n return ctx\n\n def gate_u1(self, gate, ctx):\n qubits = ctx.qubits\n n_qubits = ctx.n_qubits\n i = ctx.indices\n halflambda = gate.lambd * 0.5\n a0 = complex(math.cos(halflambda), -math.sin(halflambda))\n a1 = complex(math.cos(halflambda), math.sin(halflambda))\n for target in gate.target_iter(n_qubits):\n qubits[(i & (1 << target)) == 0] *= a0\n qubits[(i & (1 << target)) != 0] *= a1\n return ctx\n\n def gate_u3(self, gate, ctx):\n qubits = ctx.qubits\n newq = ctx.qubits_buf\n n_qubits = ctx.n_qubits\n i = ctx.indices\n theta = gate.theta\n phi = gate.phi\n lambd = gate.lambd\n globalphase = complex(math.cos((-phi - lambd) * 0.5), math.sin((-phi - lambd) * 0.5))\n a00 = math.cos(theta * 0.5) * globalphase\n a11 = a00 * complex(math.cos(phi + lambd), math.sin(phi + lambd))\n a01 = a10 = math.sin(theta * 0.5) * globalphase\n a01 *= complex(math.cos(lambd), math.sin(lambd))\n a10 *= complex(math.cos(phi), math.sin(phi))\n for target in gate.target_iter(n_qubits):\n np.copyto(newq, qubits)\n t0 = (i & (1 << target)) == 0\n t1 = (i & (1 << target)) != 0\n newq[t0] = qubits[t0] * a00\n newq[t0] -= qubits[t1] * a01\n newq[t1] = qubits[t0] * a10\n newq[t1] += qubits[t1] * a11\n qubits, newq = newq, qubits\n ctx.qubits = qubits\n ctx.qubits_buf = newq\n return ctx\n\n def gate_measure(self, gate, ctx):\n qubits = ctx.qubits\n n_qubits = ctx.n_qubits\n i = ctx.indices\n for target in gate.target_iter(n_qubits):\n p_zero = np.linalg.norm(qubits[(i & (1 << target)) == 0]) ** 2\n rand = random.random()\n if rand < p_zero:\n qubits[(i & (1 << target)) != 0] = 0.0\n qubits /= np.sqrt(p_zero)\n ctx.cregs[target] = 0\n else:\n qubits[(i & (1 << target)) == 0] = 0.0\n qubits /= np.sqrt(1.0 - p_zero)\n ctx.cregs[target] = 1\n ctx.save_cache = False\n return ctx\n"
] | [
[
"numpy.sqrt",
"numpy.arange",
"numpy.cos",
"numpy.linalg.norm",
"numpy.sin",
"numpy.copyto",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
transcendentsky/ssd_pytorch | [
"f1e20318d37b11f99c207d5e19f49ec662bf80f9",
"f1e20318d37b11f99c207d5e19f49ec662bf80f9"
] | [
"lib/utils/data_augment.py",
"lib/dataset/voc.py"
] | [
"\"\"\"Data augmentation functionality. Passed as callable transformations to\r\nDataset classes.\r\n\r\nThe data augmentation procedures were interpreted from @weiliu89's SSD paper\r\nhttp://arxiv.org/abs/1512.02325\r\n\r\nEllis Brown, Max deGroot\r\n\"\"\"\r\n\r\nimport torch\r\nimport cv2\r\nimport numpy as np\r\nimport random\r\nimport math\r\nfrom lib.utils.box_utils import matrix_iou\r\n\r\ndef _crop(image, boxes, labels):\r\n height, width, _ = image.shape\r\n\r\n if len(boxes)== 0:\r\n return image, boxes, labels\r\n\r\n while True:\r\n mode = random.choice((\r\n None,\r\n (0.1, None),\r\n (0.3, None),\r\n (0.5, None),\r\n (0.7, None),\r\n (0.9, None),\r\n (None, None),\r\n ))\r\n\r\n if mode is None:\r\n return image, boxes, labels\r\n\r\n min_iou, max_iou = mode\r\n if min_iou is None:\r\n min_iou = -999999.0 # float('-inf')\r\n # min_iou = -np.inf\r\n if max_iou is None:\r\n max_iou = 999999.0# float('inf')\r\n # max_iou = np.inf\r\n\r\n for _ in range(50):\r\n scale = random.uniform(0.3,1.)\r\n min_ratio = max(0.5, scale*scale)\r\n max_ratio = min(2, 1. / scale / scale)\r\n ratio = math.sqrt(random.uniform(min_ratio, max_ratio))\r\n w = int(scale * ratio * width)\r\n h = int((scale / ratio) * height)\r\n\r\n\r\n l = random.randrange(width - w)\r\n t = random.randrange(height - h)\r\n roi = np.array((l, t, l + w, t + h))\r\n\r\n iou = matrix_iou(boxes, roi[np.newaxis])\r\n \r\n if not (min_iou <= iou.min() and iou.max() <= max_iou):\r\n continue\r\n\r\n image_t = image[roi[1]:roi[3], roi[0]:roi[2]]\r\n\r\n centers = (boxes[:, :2] + boxes[:, 2:]) / 2\r\n mask = np.logical_and(roi[:2] < centers, centers < roi[2:]) \\\r\n .all(axis=1)\r\n boxes_t = boxes[mask].copy()\r\n labels_t = labels[mask].copy()\r\n if len(boxes_t) == 0:\r\n continue\r\n\r\n boxes_t[:, :2] = np.maximum(boxes_t[:, :2], roi[:2])\r\n boxes_t[:, :2] -= roi[:2]\r\n boxes_t[:, 2:] = np.minimum(boxes_t[:, 2:], roi[2:])\r\n boxes_t[:, 2:] -= roi[:2]\r\n\r\n return image_t, boxes_t,labels_t\r\n\r\n\r\ndef _distort(image):\r\n def _convert(image, alpha=1, beta=0):\r\n tmp = image.astype(float) * alpha + beta\r\n tmp[tmp < 0] = 0\r\n tmp[tmp > 255] = 255\r\n image[:] = tmp\r\n\r\n image = image.copy()\r\n\r\n if random.randrange(2):\r\n _convert(image, beta=random.uniform(-32, 32))\r\n\r\n if random.randrange(2):\r\n _convert(image, alpha=random.uniform(0.5, 1.5))\r\n\r\n image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\r\n\r\n if random.randrange(2):\r\n tmp = image[:, :, 0].astype(int) + random.randint(-18, 18)\r\n tmp %= 180\r\n image[:, :, 0] = tmp\r\n\r\n if random.randrange(2):\r\n _convert(image[:, :, 1], alpha=random.uniform(0.5, 1.5))\r\n\r\n image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)\r\n\r\n return image\r\n\r\n\r\ndef _expand(image, boxes, fill, p):\r\n if random.random() > p:\r\n return image, boxes\r\n\r\n height, width, depth = image.shape\r\n for _ in range(50):\r\n scale = random.uniform(1,4)\r\n\r\n min_ratio = max(0.5, 1./scale/scale)\r\n max_ratio = min(2, scale*scale)\r\n ratio = math.sqrt(random.uniform(min_ratio, max_ratio))\r\n ws = scale*ratio\r\n hs = scale/ratio\r\n if ws < 1 or hs < 1:\r\n continue\r\n w = int(ws * width)\r\n h = int(hs * height)\r\n\r\n left = random.randint(0, w - width)\r\n top = random.randint(0, h - height)\r\n\r\n boxes_t = boxes.copy()\r\n boxes_t[:, :2] += (left, top)\r\n boxes_t[:, 2:] += (left, top)\r\n\r\n\r\n expand_image = np.empty(\r\n (h, w, depth),\r\n dtype=image.dtype)\r\n expand_image[:, :] = fill\r\n expand_image[top:top + height, left:left + width] = image\r\n image = expand_image\r\n\r\n return image, boxes_t\r\n\r\n\r\ndef _mirror(image, boxes):\r\n _, width, _ = image.shape\r\n if random.randrange(2):\r\n image = image[:, ::-1]\r\n boxes = boxes.copy()\r\n boxes[:, 0::2] = width - boxes[:, 2::-2]\r\n return image, boxes\r\n\r\n\r\ndef _elastic(image, p, alpha=None, sigma=None, random_state=None):\r\n \"\"\"Elastic deformation of images as described in [Simard2003]_ (with modifications).\r\n .. [Simard2003] Simard, Steinkraus and Platt, \"Best Practices for\r\n Convolutional Neural Networks applied to Visual Document Analysis\", in\r\n Proc. of the International Conference on Document Analysis and\r\n Recognition, 2003.\r\n Based on https://gist.github.com/erniejunior/601cdf56d2b424757de5\r\n From: \r\n https://www.kaggle.com/bguberfain/elastic-transform-for-data-augmentation\r\n \"\"\"\r\n if random.random() > p:\r\n return image\r\n if alpha == None:\r\n alpha = image.shape[0] * random.uniform(0.5,2)\r\n if sigma == None:\r\n sigma = int(image.shape[0] * random.uniform(0.5,1))\r\n if random_state is None:\r\n random_state = np.random.RandomState(None)\r\n\r\n shape = image.shape[:2]\r\n \r\n dx, dy = [cv2.GaussianBlur((random_state.rand(*shape) * 2 - 1) * alpha, (sigma|1, sigma|1), 0) for _ in range(2)]\r\n x, y = np.meshgrid(np.arange(shape[1]), np.arange(shape[0]))\r\n x, y = np.clip(x+dx, 0, shape[1]-1).astype(np.float32), np.clip(y+dy, 0, shape[0]-1).astype(np.float32)\r\n return cv2.remap(image, x, y, interpolation=cv2.INTER_LINEAR, borderValue= 0, borderMode=cv2.BORDER_REFLECT)\r\n\r\n\r\ndef preproc_for_test(image, insize, mean):\r\n interp_methods = [cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_NEAREST, cv2.INTER_LANCZOS4]\r\n interp_method = interp_methods[random.randrange(5)]\r\n image = cv2.resize(image, (insize[0], insize[1]),interpolation=interp_method)\r\n image = image.astype(np.float32)\r\n image -= mean\r\n return image.transpose(2, 0, 1)\r\n\r\ndef draw_bbox(image, bbxs, color=(0, 255, 0)):\r\n img = image.copy()\r\n bbxs = np.array(bbxs).astype(np.int32)\r\n for bbx in bbxs:\r\n cv2.rectangle(img, (bbx[0], bbx[1]), (bbx[2], bbx[3]), color, 5)\r\n return img\r\n\r\nclass preproc(object):\r\n\r\n def __init__(self, resize, rgb_means, p, writer=None):\r\n self.means = rgb_means\r\n self.resize = resize\r\n self.p = p\r\n self.writer = writer # writer used for tensorboard visualization\r\n self.epoch = 0\r\n\r\n def __call__(self, image, targets=None):\r\n # some bugs \r\n if self.p == -2: # abs_test\r\n targets = np.zeros((1,5))\r\n targets[0] = image.shape[0]\r\n targets[0] = image.shape[1]\r\n image = preproc_for_test(image, self.resize, self.means)\r\n return torch.from_numpy(image), targets\r\n\r\n boxes = targets[:,:-1].copy()\r\n labels = targets[:,-1].copy()\r\n if len(boxes) == 0:\r\n targets = np.zeros((1,5))\r\n image = preproc_for_test(image, self.resize, self.means) # some ground truth in coco do not have bounding box! weird!\r\n return torch.from_numpy(image), targets\r\n if self.p == -1: # eval\r\n height, width, _ = image.shape\r\n boxes[:, 0::2] /= width\r\n boxes[:, 1::2] /= height\r\n labels = np.expand_dims(labels,1)\r\n targets = np.hstack((boxes,labels))\r\n image = preproc_for_test(image, self.resize, self.means)\r\n return torch.from_numpy(image), targets\r\n\r\n image_o = image.copy()\r\n targets_o = targets.copy()\r\n height_o, width_o, _ = image_o.shape\r\n boxes_o = targets_o[:,:-1]\r\n labels_o = targets_o[:,-1]\r\n boxes_o[:, 0::2] /= width_o\r\n boxes_o[:, 1::2] /= height_o\r\n labels_o = np.expand_dims(labels_o,1)\r\n targets_o = np.hstack((boxes_o,labels_o))\r\n\r\n if self.writer is not None:\r\n image_show = draw_bbox(image, boxes)\r\n self.writer.add_image('preprocess/input_image', image_show, self.epoch)\r\n\r\n image_t, boxes, labels = _crop(image, boxes, labels)\r\n if self.writer is not None:\r\n image_show = draw_bbox(image_t, boxes)\r\n self.writer.add_image('preprocess/crop_image', image_show, self.epoch)\r\n\r\n image_t = _distort(image_t)\r\n if self.writer is not None:\r\n image_show = draw_bbox(image_t, boxes)\r\n self.writer.add_image('preprocess/distort_image', image_show, self.epoch)\r\n \r\n # image_t = _elastic(image_t, self.p)\r\n # if self.writer is not None:\r\n # image_show = draw_bbox(image_t, boxes)\r\n # self.writer.add_image('preprocess/elastic_image', image_show, self.epoch)\r\n\r\n image_t, boxes = _expand(image_t, boxes, self.means, self.p)\r\n if self.writer is not None:\r\n image_show = draw_bbox(image_t, boxes)\r\n self.writer.add_image('preprocess/expand_image', image_show, self.epoch)\r\n\r\n image_t, boxes = _mirror(image_t, boxes)\r\n if self.writer is not None:\r\n image_show = draw_bbox(image_t, boxes)\r\n self.writer.add_image('preprocess/mirror_image', image_show, self.epoch)\r\n\r\n # only write the preprocess step for the first image\r\n if self.writer is not None:\r\n # print('image adding')\r\n self.release_writer()\r\n\r\n height, width, _ = image_t.shape\r\n image_t = preproc_for_test(image_t, self.resize, self.means)\r\n boxes = boxes.copy()\r\n boxes[:, 0::2] /= width\r\n boxes[:, 1::2] /= height\r\n b_w = (boxes[:, 2] - boxes[:, 0])*1.\r\n b_h = (boxes[:, 3] - boxes[:, 1])*1.\r\n mask_b= np.minimum(b_w, b_h) > 0.01\r\n boxes_t = boxes[mask_b]\r\n labels_t = labels[mask_b].copy()\r\n\r\n if len(boxes_t)==0:\r\n image = preproc_for_test(image_o, self.resize, self.means)\r\n return torch.from_numpy(image),targets_o\r\n\r\n labels_t = np.expand_dims(labels_t,1)\r\n targets_t = np.hstack((boxes_t,labels_t))\r\n\r\n return torch.from_numpy(image_t), targets_t\r\n \r\n def add_writer(self, writer, epoch=None):\r\n self.writer = writer\r\n self.epoch = epoch if epoch is not None else self.epoch + 1\r\n \r\n def release_writer(self):\r\n self.writer = None\r\n",
"import os\r\nimport pickle\r\nimport os.path\r\nimport sys\r\nimport torch\r\nimport torch.utils.data as data\r\nimport torchvision.transforms as transforms\r\nfrom PIL import Image, ImageDraw, ImageFont\r\nimport cv2\r\nimport numpy as np\r\nfrom .voc_eval import voc_eval\r\nif sys.version_info[0] == 2:\r\n import xml.etree.cElementTree as ET\r\nelse:\r\n import xml.etree.ElementTree as ET\r\n\r\n\r\nVOC_CLASSES = ( '__background__', # always index 0\r\n 'aeroplane', 'bicycle', 'bird', 'boat',\r\n 'bottle', 'bus', 'car', 'cat', 'chair',\r\n 'cow', 'diningtable', 'dog', 'horse',\r\n 'motorbike', 'person', 'pottedplant',\r\n 'sheep', 'sofa', 'train', 'tvmonitor')\r\n\r\n# for making bounding boxes pretty\r\nCOLORS = ((255, 0, 0, 128), (0, 255, 0, 128), (0, 0, 255, 128),\r\n (0, 255, 255, 128), (255, 0, 255, 128), (255, 255, 0, 128))\r\n\r\n\r\nclass VOCSegmentation(data.Dataset):\r\n\r\n \"\"\"VOC Segmentation Dataset Object\r\n input and target are both images\r\n\r\n NOTE: need to address https://github.com/pytorch/vision/issues/9\r\n\r\n Arguments:\r\n root (string): filepath to VOCdevkit folder.\r\n image_set (string): imageset to use (eg: 'train', 'val', 'test').\r\n transform (callable, optional): transformation to perform on the\r\n input image\r\n target_transform (callable, optional): transformation to perform on the\r\n target image\r\n dataset_name (string, optional): which dataset to load\r\n (default: 'VOC2007')\r\n \"\"\"\r\n\r\n def __init__(self, root, image_set, transform=None, target_transform=None,\r\n dataset_name='VOC2007'):\r\n self.root = root\r\n self.image_set = image_set\r\n self.transform = transform\r\n self.target_transform = target_transform\r\n\r\n self._annopath = os.path.join(\r\n self.root, dataset_name, 'SegmentationClass', '%s.png')\r\n self._imgpath = os.path.join(\r\n self.root, dataset_name, 'JPEGImages', '%s.jpg')\r\n self._imgsetpath = os.path.join(\r\n self.root, dataset_name, 'ImageSets', 'Segmentation', '%s.txt')\r\n\r\n with open(self._imgsetpath % self.image_set) as f:\r\n self.ids = f.readlines()\r\n self.ids = [x.strip('\\n') for x in self.ids]\r\n\r\n def __getitem__(self, index):\r\n img_id = self.ids[index]\r\n\r\n target = Image.open(self._annopath % img_id).convert('RGB')\r\n img = Image.open(self._imgpath % img_id).convert('RGB')\r\n\r\n if self.transform is not None:\r\n img = self.transform(img)\r\n\r\n if self.target_transform is not None:\r\n target = self.target_transform(target)\r\n\r\n return img, target\r\n\r\n def __len__(self):\r\n return len(self.ids)\r\n\r\n\r\nclass AnnotationTransform(object):\r\n\r\n \"\"\"Transforms a VOC annotation into a Tensor of bbox coords and label index\r\n Initilized with a dictionary lookup of classnames to indexes\r\n\r\n Arguments:\r\n class_to_ind (dict, optional): dictionary lookup of classnames -> indexes\r\n (default: alphabetic indexing of VOC's 20 classes)\r\n keep_difficult (bool, optional): keep difficult instances or not\r\n (default: False)\r\n height (int): height\r\n width (int): width\r\n \"\"\"\r\n\r\n def __init__(self, class_to_ind=None, keep_difficult=True):\r\n self.class_to_ind = class_to_ind or dict(\r\n zip(VOC_CLASSES, range(len(VOC_CLASSES))))\r\n self.keep_difficult = keep_difficult\r\n\r\n def __call__(self, target):\r\n \"\"\"\r\n Arguments:\r\n target (annotation) : the target annotation to be made usable\r\n will be an ET.Element\r\n Returns:\r\n a list containing lists of bounding boxes [bbox coords, class name]\r\n \"\"\"\r\n res = np.empty((0,5)) \r\n for obj in target.iter('object'):\r\n difficult = int(obj.find('difficult').text) == 1\r\n if not self.keep_difficult and difficult:\r\n continue\r\n name = obj.find('name').text.lower().strip()\r\n bbox = obj.find('bndbox')\r\n\r\n pts = ['xmin', 'ymin', 'xmax', 'ymax']\r\n bndbox = []\r\n for i, pt in enumerate(pts):\r\n cur_pt = int(bbox.find(pt).text) - 1\r\n # scale height or width\r\n #cur_pt = cur_pt / width if i % 2 == 0 else cur_pt / height\r\n bndbox.append(cur_pt)\r\n label_idx = self.class_to_ind[name]\r\n bndbox.append(label_idx)\r\n res = np.vstack((res,bndbox)) # [xmin, ymin, xmax, ymax, label_ind]\r\n # img_id = target.find('filename').text[:-4]\r\n\r\n return res # [[xmin, ymin, xmax, ymax, label_ind], ... ]\r\n\r\n\r\nclass VOCDetection(data.Dataset):\r\n\r\n \"\"\"VOC Detection Dataset Object\r\n\r\n input is image, target is annotation\r\n\r\n Arguments:\r\n root (string): filepath to VOCdevkit folder.\r\n image_set (string): imageset to use (eg. 'train', 'val', 'test')\r\n transform (callable, optional): transformation to perform on the\r\n input image\r\n target_transform (callable, optional): transformation to perform on the\r\n target `annotation`\r\n (eg: take in caption string, return tensor of word indices)\r\n dataset_name (string, optional): which dataset to load\r\n (default: 'VOC2007')\r\n \"\"\"\r\n\r\n def __init__(self, root, image_sets, preproc=None, target_transform=AnnotationTransform(),\r\n dataset_name='VOC0712'):\r\n self.root = root\r\n self.image_set = image_sets\r\n self.preproc = preproc\r\n self.target_transform = target_transform\r\n self.name = dataset_name\r\n self._annopath = os.path.join('%s', 'Annotations', '%s.xml')\r\n self._imgpath = os.path.join('%s', 'JPEGImages', '%s.jpg')\r\n self.ids = list()\r\n for (year, name) in image_sets:\r\n self._year = year\r\n rootpath = os.path.join(self.root, 'VOC' + year)\r\n for line in open(os.path.join(rootpath, 'ImageSets', 'Main', name + '.txt')):\r\n self.ids.append((rootpath, line.strip()))\r\n\r\n def __getitem__(self, index):\r\n img_id = self.ids[index]\r\n target = ET.parse(self._annopath % img_id).getroot()\r\n img = cv2.imread(self._imgpath % img_id, cv2.IMREAD_COLOR)\r\n height, width, _ = img.shape\r\n\r\n if self.target_transform is not None:\r\n target = self.target_transform(target)\r\n\r\n\r\n if self.preproc is not None:\r\n img, target = self.preproc(img, target)\r\n #print(img.size())\r\n\r\n # target = self.target_transform(target, width, height)\r\n # print(target.shape)\r\n assert img is not None, \"Img Error\"\r\n return img, target\r\n\r\n def __len__(self):\r\n return len(self.ids)\r\n\r\n def pull_image(self, index):\r\n '''Returns the original image object at index in PIL form\r\n\r\n Note: not using self.__getitem__(), as any transformations passed in\r\n could mess up this functionality.\r\n\r\n Argument:\r\n index (int): index of img to show\r\n Return:\r\n PIL img\r\n '''\r\n img_id = self.ids[index]\r\n return cv2.imread(self._imgpath % img_id, cv2.IMREAD_COLOR)\r\n\r\n def pull_anno(self, index):\r\n '''Returns the original annotation of image at index\r\n\r\n Note: not using self.__getitem__(), as any transformations passed in\r\n could mess up this functionality.\r\n\r\n Argument:\r\n index (int): index of img to get annotation of\r\n Return:\r\n list: [img_id, [(label, bbox coords),...]]\r\n eg: ('001718', [('dog', (96, 13, 438, 332))])\r\n '''\r\n img_id = self.ids[index]\r\n anno = ET.parse(self._annopath % img_id).getroot()\r\n # gt = self.target_transform(anno, 1, 1)\r\n # gt = self.target_transform(anno)\r\n # return img_id[1], gt\r\n if self.target_transform is not None:\r\n anno = self.target_transform(anno)\r\n return anno\r\n \r\n\r\n def pull_img_anno(self, index):\r\n '''Returns the original annotation of image at index\r\n\r\n Note: not using self.__getitem__(), as any transformations passed in\r\n could mess up this functionality.\r\n\r\n Argument:\r\n index (int): index of img to get annotation of\r\n Return:\r\n list: [img_id, [(label, bbox coords),...]]\r\n eg: ('001718', [('dog', (96, 13, 438, 332))])\r\n '''\r\n img_id = self.ids[index]\r\n img = cv2.imread(self._imgpath % img_id, cv2.IMREAD_COLOR)\r\n anno = ET.parse(self._annopath % img_id).getroot()\r\n gt = self.target_transform(anno)\r\n height, width, _ = img.shape\r\n boxes = gt[:,:-1]\r\n labels = gt[:,-1]\r\n boxes[:, 0::2] /= width\r\n boxes[:, 1::2] /= height\r\n labels = np.expand_dims(labels,1)\r\n targets = np.hstack((boxes,labels))\r\n \r\n return img, targets\r\n\r\n def pull_tensor(self, index):\r\n '''Returns the original image at an index in tensor form\r\n\r\n Note: not using self.__getitem__(), as any transformations passed in\r\n could mess up this functionality.\r\n\r\n Argument:\r\n index (int): index of img to show\r\n Return:\r\n tensorized version of img, squeezed\r\n '''\r\n to_tensor = transforms.ToTensor()\r\n return torch.Tensor(self.pull_image(index)).unsqueeze_(0).cpu()\r\n # trans Fixed randperm Problem\r\n\r\n def evaluate_detections(self, all_boxes, output_dir=None):\r\n \"\"\"\r\n all_boxes is a list of length number-of-classes.\r\n Each list element is a list of length number-of-images.\r\n Each of those list elements is either an empty list []\r\n or a numpy array of detection.\r\n\r\n all_boxes[class][image] = [] or np.array of shape #dets x 5\r\n \"\"\"\r\n self._write_voc_results_file(all_boxes)\r\n aps,map = self._do_python_eval(output_dir)\r\n return aps,map\r\n\r\n def _get_voc_results_file_template(self):\r\n filename = 'comp4_det_test' + '_{:s}.txt'\r\n filedir = os.path.join(\r\n self.root, 'results', 'VOC' + self._year, 'Main')\r\n if not os.path.exists(filedir):\r\n os.makedirs(filedir)\r\n path = os.path.join(filedir, filename)\r\n return path\r\n\r\n def _write_voc_results_file(self, all_boxes):\r\n for cls_ind, cls in enumerate(VOC_CLASSES):\r\n cls_ind = cls_ind \r\n if cls == '__background__':\r\n continue\r\n print('Writing {} VOC results file'.format(cls))\r\n filename = self._get_voc_results_file_template().format(cls)\r\n with open(filename, 'wt') as f:\r\n for im_ind, index in enumerate(self.ids):\r\n index = index[1]\r\n dets = all_boxes[cls_ind][im_ind]\r\n if dets == []:\r\n continue\r\n for k in range(dets.shape[0]):\r\n f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\\n'.\r\n format(index, dets[k, -1],\r\n dets[k, 0] + 1, dets[k, 1] + 1,\r\n dets[k, 2] + 1, dets[k, 3] + 1))\r\n\r\n def _do_python_eval(self, output_dir='output'):\r\n rootpath = os.path.join(self.root, 'VOC' + self._year)\r\n name = self.image_set[0][1]\r\n annopath = os.path.join(\r\n rootpath,\r\n 'Annotations',\r\n '{:s}.xml')\r\n imagesetfile = os.path.join(\r\n rootpath,\r\n 'ImageSets',\r\n 'Main',\r\n name+'.txt')\r\n cachedir = os.path.join(self.root, 'annotations_cache')\r\n aps = []\r\n # The PASCAL VOC metric changed in 2010\r\n use_07_metric = True if int(self._year) < 2010 else False\r\n print('VOC07 metric? ' + ('Yes' if use_07_metric else 'No'))\r\n if output_dir is not None and not os.path.isdir(output_dir):\r\n os.mkdir(output_dir)\r\n for i, cls in enumerate(VOC_CLASSES):\r\n\r\n if cls == '__background__':\r\n continue\r\n\r\n filename = self._get_voc_results_file_template().format(cls)\r\n rec, prec, ap = voc_eval(\r\n filename, annopath, imagesetfile, cls, cachedir, ovthresh=0.5,\r\n use_07_metric=use_07_metric)\r\n aps += [ap]\r\n print('AP for {} = {:.4f}'.format(cls, ap))\r\n if output_dir is not None:\r\n with open(os.path.join(output_dir, cls + '_pr.pkl'), 'wb') as f:\r\n pickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f)\r\n print('Mean AP = {:.4f}'.format(np.mean(aps)))\r\n print('~~~~~~~~')\r\n print('Results:')\r\n for ap in aps:\r\n print('{:.3f}'.format(ap))\r\n print('{:.3f}'.format(np.mean(aps)))\r\n print('~~~~~~~~')\r\n print('')\r\n print('--------------------------------------------------------------')\r\n print('Results computed with the **unofficial** Python eval code.')\r\n print('Results should be very close to the official MATLAB eval code.')\r\n print('Recompute with `./tools/reval.py --matlab ...` for your paper.')\r\n print('-- Thanks, The Management')\r\n print('--------------------------------------------------------------')\r\n return aps,np.mean(aps)\r\n\r\n def show(self, index):\r\n img, target = self.__getitem__(index)\r\n for obj in target:\r\n obj = obj.astype(np.int)\r\n cv2.rectangle(img, (obj[0], obj[1]), (obj[2], obj[3]), (255,0,0), 3)\r\n cv2.imwrite('./image.jpg', img)\r\n\r\n\r\n\r\n\r\n## test\r\n# if __name__ == '__main__':\r\n# ds = VOCDetection('../../../../../dataset/VOCdevkit/', [('2012', 'train')],\r\n# None, AnnotationTransform())\r\n# print(len(ds))\r\n# img, target = ds[0]\r\n# print(target)\r\n# ds.show(1)"
] | [
[
"numpy.hstack",
"numpy.expand_dims",
"numpy.maximum",
"numpy.minimum",
"numpy.logical_and",
"numpy.clip",
"numpy.arange",
"torch.from_numpy",
"numpy.array",
"numpy.random.RandomState",
"numpy.zeros",
"numpy.empty"
],
[
"numpy.hstack",
"numpy.expand_dims",
"numpy.empty",
"numpy.mean",
"numpy.vstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.