repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
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.Linear",
"torch.cat",
"torch.nn.BatchNorm2d",
"torch.nn.AdaptiveAvgPool1d",
"torch.nn.MaxPool2d",
"torch.nn.init.constant_",
"torch.nn.AvgPool2d",
"torch.nn.functional.adaptive_avg_pool2d",
"numpy.nonzero",
"torch.unsqueeze",
"torch.nn.functional.sigmoid",
"torch.nn.Sequential",
"torch.clamp",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.nn.functional.softmax",
"torch.nn.AdaptiveAvgPool3d",
"torch.matmul",
"torch.nn.Sigmoid",
"numpy.sum",
"torch.nn.AdaptiveAvgPool2d",
"torch.nn.Dropout2d"
]
] |
fraudies/tensorflow
|
[
"a42423e302b71893bbd24aa896869941013c07fb",
"3e21fe5faedab3a8258d344c8ad1cec2612a8aa8",
"a42423e302b71893bbd24aa896869941013c07fb",
"a42423e302b71893bbd24aa896869941013c07fb",
"a42423e302b71893bbd24aa896869941013c07fb",
"6aa83398ab03bfae822f36772757097bcb98b6ed",
"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"
] |
[
"# 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"
] |
[
[
"numpy.array",
"numpy.zeros",
"tensorflow.python.ops.array_ops.gather",
"tensorflow.python.ops.array_ops.ones",
"tensorflow.python.framework.constant_op.constant",
"numpy.random.randn",
"tensorflow.python.platform.test.is_gpu_available",
"numpy.take",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.ops.array_ops.placeholder",
"numpy.prod",
"numpy.arange",
"numpy.random.randint",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.ops.gradients_impl.gradients",
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.variables.global_variables_initializer"
],
[
"tensorflow.python.ops.gen_linalg_ops.qr",
"tensorflow.python.ops.array_ops.matrix_transpose",
"tensorflow.python.ops.math_ops.sign",
"tensorflow.python.ops.linalg_ops_impl.eye",
"tensorflow.python.framework.dtypes.as_dtype",
"tensorflow.python.ops.array_ops.ones",
"tensorflow.python.framework.constant_op.constant",
"tensorflow.python.ops.array_ops.zeros",
"numpy.isscalar",
"tensorflow.python.ops.array_ops.reshape",
"tensorflow.python.ops.array_ops.diag_part",
"tensorflow.python.util.tf_export.tf_export",
"tensorflow.python.ops.array_ops.slice"
],
[
"tensorflow.python.ops.variables.Variable",
"tensorflow.python.ops.nn_ops.leaky_relu",
"tensorflow.python.ops.nn_ops.l2_loss",
"numpy.copy",
"numpy.exp",
"tensorflow.python.ops.random_ops.random_normal",
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.math_ops.cast",
"numpy.zeros_like",
"tensorflow.python.ops.gradient_checker.compute_gradient_error",
"tensorflow.python.ops.array_ops.placeholder",
"tensorflow.python.ops.gradients_impl.gradients",
"tensorflow.python.ops.nn_ops.crelu",
"tensorflow.python.ops.random_ops.random_uniform",
"tensorflow.python.ops.variables.global_variables_initializer",
"numpy.array",
"numpy.zeros",
"tensorflow.python.ops.nn_ops.elu",
"tensorflow.python.platform.test.is_gpu_available",
"tensorflow.python.training.gradient_descent.GradientDescentOptimizer",
"numpy.asarray",
"tensorflow.python.ops.nn_ops.relu6",
"tensorflow.python.ops.nn_ops.relu",
"tensorflow.python.framework.constant_op.constant",
"tensorflow.python.ops.nn_ops.selu",
"tensorflow.python.compat.compat.forward_compatibility_horizon",
"numpy.maximum"
],
[
"tensorflow.python.platform.test.main",
"tensorflow.python.framework.constant_op.constant",
"tensorflow.python.ops.nn_ops.quantized_conv2d"
],
[
"numpy.asarray",
"numpy.zeros",
"numpy.sum",
"tensorflow.python.data.ops.dataset_ops.Dataset.range",
"numpy.random.random_sample",
"tensorflow.python.data.ops.dataset_ops.Dataset.from_tensors",
"tensorflow.python.data.ops.dataset_ops.Dataset.from_tensor_slices",
"numpy.random.randint",
"tensorflow.python.data.experimental.ops.interleave_ops._DirectedInterleaveDataset",
"tensorflow.python.framework.random_seed.set_random_seed",
"tensorflow.python.data.experimental.ops.interleave_ops.choose_from_datasets",
"tensorflow.python.platform.test.main"
],
[
"tensorflow.python.ops.gen_experimental_dataset_ops.experimental_indexed_dataset_get",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.data.experimental.ops.indexed_dataset_ops.IdentityIndexedDataset",
"tensorflow.python.ops.gen_experimental_dataset_ops.experimental_materialized_index_dataset_handle",
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.gen_experimental_dataset_ops.experimental_indexed_dataset_materialize"
],
[
"tensorflow.python.util.tf_export.keras_export",
"tensorflow.python.ops.control_flow_ops.group",
"tensorflow.python.framework.smart_cond.smart_cond",
"tensorflow.python.distribute.distribution_strategy_context.in_cross_replica_context",
"tensorflow.python.distribute.distribution_strategy_context.get_replica_context",
"tensorflow.python.keras.mixed_precision.experimental.loss_scale.get"
],
[
"tensorflow.python.ops.variable_scope.variable_scope",
"tensorflow.python.layers.core.dropout",
"tensorflow.python.layers.core.flatten",
"tensorflow.python.layers.core.Dropout",
"tensorflow.python.ops.array_ops.ones",
"tensorflow.python.ops.variable_scope.EagerVariableStore",
"tensorflow.python.ops.math_ops.reduce_sum",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.framework.ops.get_collection",
"tensorflow.python.eager.context.eager_mode",
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.init_ops.ones_initializer",
"tensorflow.python.layers.core.Flatten",
"tensorflow.python.layers.core.dense",
"tensorflow.python.ops.array_ops.placeholder",
"numpy.transpose",
"numpy.arange",
"tensorflow.python.ops.variables.trainable_variables",
"tensorflow.python.framework.test_util.run_in_graph_and_eager_modes",
"tensorflow.python.ops.random_ops.random_uniform",
"tensorflow.python.ops.variables.global_variables_initializer",
"tensorflow.python.ops.init_ops.zeros_initializer",
"numpy.zeros",
"tensorflow.python.layers.core.Dense",
"tensorflow.python.ops.math_ops.reduce_max",
"numpy.ones",
"tensorflow.python.framework.constant_op.constant",
"tensorflow.python.ops.variable_scope._get_default_variable_store"
],
[
"tensorflow.python.training.learning_rate_decay.piecewise_constant",
"tensorflow.python.platform.googletest.main",
"tensorflow.python.ops.variables.VariableV1",
"tensorflow.python.training.learning_rate_decay.noisy_linear_cosine_decay",
"tensorflow.python.training.learning_rate_decay.linear_cosine_decay",
"tensorflow.python.ops.resource_variable_ops.ResourceVariable",
"tensorflow.python.training.learning_rate_decay.inverse_time_decay",
"tensorflow.python.training.learning_rate_decay.natural_exp_decay",
"tensorflow.python.training.learning_rate_decay.polynomial_decay",
"tensorflow.python.training.learning_rate_decay.cosine_decay",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.training.learning_rate_decay.cosine_decay_restarts",
"tensorflow.python.training.learning_rate_decay.exponential_decay",
"tensorflow.python.ops.variables.global_variables_initializer"
],
[
"numpy.testing.assert_allclose",
"tensorflow.python.keras.backend.track_tf_optimizer",
"tensorflow.python.keras.testing_utils.get_test_data",
"tensorflow.python.keras.optimizers.serialize",
"tensorflow.python.keras.layers.Dense",
"tensorflow.python.keras.optimizers.Adam",
"tensorflow.python.eager.context.executing_eagerly",
"numpy.random.random",
"tensorflow.python.platform.test.main",
"tensorflow.python.keras.constraints.MaxNorm",
"tensorflow.python.keras.models.Sequential",
"tensorflow.python.keras.optimizers.Nadam",
"tensorflow.python.framework.ops.Graph",
"tensorflow.python.keras.optimizers.Adadelta",
"tensorflow.python.keras.optimizers.Adamax",
"tensorflow.python.keras.optimizers.deserialize",
"tensorflow.python.keras.optimizers.Adagrad",
"tensorflow.python.keras.utils.to_categorical",
"tensorflow.python.keras.optimizers.SGD",
"numpy.random.seed",
"tensorflow.python.training.adam.AdamOptimizer",
"tensorflow.python.keras.backend.get_value",
"tensorflow.python.keras.optimizers.RMSprop"
],
[
"tensorflow.python.ops.math_ops.div",
"tensorflow.python.ops.variables.Variable",
"tensorflow.python.ops.array_ops.identity",
"tensorflow.python.ops.math_ops.less",
"tensorflow.python.ops.session_ops.delete_session_tensor",
"tensorflow.python.ops.state_ops.assign_add",
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.session_ops.get_session_tensor",
"tensorflow.python.framework.constant_op.constant",
"tensorflow.python.platform.test.gpu_device_name",
"tensorflow.python.ops.math_ops.subtract",
"tensorflow.python.ops.math_ops.multiply",
"tensorflow.python.framework.ops.device",
"tensorflow.python.ops.math_ops.add",
"tensorflow.python.ops.session_ops.get_session_handle"
]
] |
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"
]
] |
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.array",
"pandas.DataFrame",
"numpy.sum",
"numpy.ones",
"numpy.eye",
"numpy.einsum",
"numpy.abs",
"numpy.diag"
],
[
"numpy.isclose",
"pandas.DataFrame",
"numpy.ones",
"numpy.random.randn",
"numpy.mean",
"numpy.where",
"numpy.amax",
"numpy.sqrt",
"numpy.array_split"
],
[
"pandas.DataFrame"
]
] |
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.Flatten",
"tensorflow.keras.layers.Conv3D",
"tensorflow.ones_like",
"tensorflow.keras.layers.Reshape",
"tensorflow.keras.Sequential",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.keras.layers.LeakyReLU",
"numpy.prod",
"tensorflow.zeros_like",
"tensorflow.keras.Input",
"tensorflow.keras.layers.Conv3DTranspose",
"tensorflow.keras.layers.ReLU"
]
] |
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.Linear",
"torch.nn.LeakyReLU",
"torch.sum",
"torch.nn.LayerNorm",
"torch.nn.ConvTranspose2d",
"torch.manual_seed",
"torch.nn.init.calculate_gain",
"torch.zeros",
"torch.cuda.manual_seed_all",
"torch.nn.Sequential",
"torch.nn.ReLU",
"torch.cuda.empty_cache",
"torch.nn.Conv2d",
"torch.nn.functional.softmax",
"torch.log",
"torch.nn.GRUCell",
"torch.nn.functional.mse_loss",
"torch.flatten",
"torch.randn"
]
] |
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"
]
] |
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"
]
] |
cm107/tianshou
|
[
"0febf4bc1dc1366d837bab4574664f8116b66819"
] |
[
"tianshou/policy/modelfree/td3.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"
] |
[
[
"torch.randn"
]
] |
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"
] |
[
[
"numpy.random.seed",
"sklearn.ensemble.ExtraTreesClassifier"
]
] |
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.bernoulli",
"torch.ones_like"
]
] |
adamshephard/tiatoolbox
|
[
"28c32648bc1f3e842c7b241637fd25af290386e6"
] |
[
"tests/test_stainnorm.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"
] |
[
[
"numpy.array",
"numpy.zeros",
"numpy.ones",
"numpy.shape",
"numpy.absolute",
"numpy.all"
]
] |
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"
]
] |
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.asarray",
"numpy.setdiff1d",
"numpy.in1d",
"numpy.linspace",
"numpy.unique"
],
[
"numpy.concatenate",
"numpy.tile",
"numpy.nonzero",
"numpy.arange",
"numpy.in1d",
"numpy.unique"
]
] |
statphysandml/MCMCEvaluationLib
|
[
"f722b2c7df88b1b33cd29335a22eef53bdad9665"
] |
[
"mcmctools/loading/loading.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"
] |
[
[
"pandas.read_csv",
"numpy.stack",
"pandas.MultiIndex.from_tuples",
"pandas.concat"
]
] |
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"
] |
[
[
"tensorflow.keras.applications.VGG16",
"numpy.reshape"
]
] |
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.max",
"sklearn.preprocessing.LabelEncoder",
"numpy.array",
"pandas.set_option",
"numpy.random.RandomState",
"numpy.log",
"pandas.DataFrame",
"numpy.min",
"numpy.random.uniform",
"numpy.random.randint",
"pandas.read_csv",
"sklearn.utils.shuffle"
]
] |
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"
]
] |
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.xlabel",
"sklearn.cluster.KMeans",
"matplotlib.pyplot.title",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.scatter",
"pandas.read_csv"
]
] |
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"
] |
[
[
"torch.zeros",
"scipy.io.loadmat",
"numpy.transpose",
"torch.from_numpy"
]
] |
Jian137/mmediting-1
|
[
"e1ac6c93441ec96696d0b530f040b91b809015b6",
"e1ac6c93441ec96696d0b530f040b91b809015b6"
] |
[
"tests/test_models/test_restorers/test_glean.py",
"mmedit/models/backbones/sr_backbones/glean_styleganv2.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"
] |
[
[
"torch.rand",
"torch.no_grad",
"torch.cuda.is_available"
],
[
"torch.nn.Linear",
"torch.cat",
"torch.nn.ModuleList",
"torch.nn.LeakyReLU",
"torch.nn.Conv2d",
"numpy.log2",
"torch.nn.Flatten"
]
] |
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"
]
] |
roy860328/VSGM
|
[
"3ec19f9cf1401cecf45527687936b8fe4167f672",
"3ec19f9cf1401cecf45527687936b8fe4167f672"
] |
[
"alfworld/agents/semantic_graph/gcn.py",
"alfred/models/eval_moca/eval_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()"
] |
[
[
"torch.zeros",
"torch.nn.functional.dropout",
"torch.cat"
],
[
"matplotlib.use",
"torch.multiprocessing.Manager",
"torch.multiprocessing.set_start_method"
]
] |
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.array",
"numpy.sin",
"numpy.eye",
"numpy.cos",
"numpy.sqrt",
"numpy.deg2rad"
]
] |
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()"
] |
[
[
"numpy.random.seed",
"pandas.read_csv"
]
] |
zkdlfrlwl2/Classification-For-Everyone
|
[
"a99428080ef470a3270d3f4a6048df197216a050"
] |
[
"models/AlexNet/lightning_model.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"
] |
[
[
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"torch.nn.CrossEntropyLoss"
]
] |
ganik/DeepSpeedExamples
|
[
"174ae3bc8dbb688cfaccb4afa15d6e2cdbe19ce5",
"174ae3bc8dbb688cfaccb4afa15d6e2cdbe19ce5"
] |
[
"Megatron-LM-v1.1.5-ZeRO3/megatron/initialize.py",
"pipeline_parallelism/alexnet.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"
] |
[
[
"torch.distributed.get_world_size",
"torch.distributed.init_process_group",
"numpy.random.seed",
"torch.cuda.device_count",
"torch.manual_seed",
"torch.distributed.is_initialized",
"torch.cuda.set_device",
"torch.cuda.is_available",
"torch.distributed.get_rank",
"torch.distributed.barrier"
],
[
"torch.nn.Linear",
"torch.nn.Dropout",
"torch.flatten",
"torch.nn.MaxPool2d",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.nn.AdaptiveAvgPool2d"
]
] |
kai-wen-yang/CD-VAE
|
[
"a33b5070d5d936396d51c8c2e7dedd62351ee5b2"
] |
[
"detection/lib/quilting_fast.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"
] |
[
[
"torch.is_tensor",
"torch.FloatTensor",
"torch.LongTensor",
"numpy.zeros"
]
] |
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"
]
] |
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"
]
] |
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"
] |
[
[
"matplotlib.pyplot.style.context",
"numpy.asarray",
"matplotlib.pyplot.subplots",
"numpy.where",
"numpy.atleast_1d",
"numpy.unique"
]
] |
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.tpu.TPUEstimatorSpec",
"tensorflow.data.TFRecordDataset",
"tensorflow.train.Features",
"tensorflow.contrib.tpu.TPUEstimator",
"tensorflow.matmul",
"tensorflow.reshape",
"tensorflow.one_hot",
"tensorflow.logging.warning",
"tensorflow.parse_single_example",
"tensorflow.trainable_variables",
"tensorflow.flags.DEFINE_string",
"tensorflow.contrib.tpu.TPUConfig",
"tensorflow.FixedLenFeature",
"tensorflow.logging.info",
"tensorflow.transpose",
"tensorflow.gfile.MakeDirs",
"tensorflow.contrib.cluster_resolver.TPUClusterResolver",
"tensorflow.app.run",
"tensorflow.nn.bias_add",
"tensorflow.nn.log_softmax",
"tensorflow.logging.set_verbosity",
"tensorflow.python_io.TFRecordWriter",
"tensorflow.gfile.GFile",
"tensorflow.reduce_sum",
"tensorflow.train.init_from_checkpoint",
"tensorflow.to_int32",
"tensorflow.unstack",
"tensorflow.zeros_initializer",
"tensorflow.gfile.Open",
"tensorflow.train.Scaffold",
"tensorflow.truncated_normal_initializer"
]
] |
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"
]
] |
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"
] |
[
[
"sklearn.metrics.accuracy_score",
"sklearn.linear_model.LogisticRegression",
"sklearn.model_selection.train_test_split",
"pandas.read_csv",
"sklearn.decomposition.PCA"
],
[
"numpy.dot",
"numpy.random.RandomState",
"numpy.sum",
"numpy.where",
"pandas.read_csv"
]
] |
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"
]
] |
basiralab/FSSelect
|
[
"fc1a5706ac681bf6471ad07c67dff16b8647870f"
] |
[
"helpers/storage.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)"
] |
[
[
"pandas.DataFrame"
]
] |
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.to_datetime",
"pandas.set_option",
"pandas.concat",
"pandas.DataFrame",
"pandas.Series"
]
] |
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.random.randint",
"numpy.stack",
"numpy.load"
]
] |
phunc20/rlcomp2020
|
[
"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"
] |
[
"########################################\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"
] |
[
[
"numpy.random.rand",
"numpy.mean",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.models.clone_model",
"tensorflow.one_hot",
"numpy.zeros_like",
"tensorflow.GradientTape",
"tensorflow.random.set_seed",
"tensorflow.keras.layers.Conv2D",
"numpy.argmax",
"numpy.random.randint",
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.losses.Huber",
"numpy.array",
"numpy.zeros",
"numpy.stack",
"tensorflow.reduce_sum",
"numpy.random.seed",
"tensorflow.keras.layers.Flatten",
"numpy.maximum"
],
[
"numpy.array",
"numpy.zeros",
"numpy.ones",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.imshow"
],
[
"tensorflow.keras.losses.Huber",
"numpy.array",
"numpy.random.rand",
"tensorflow.GradientTape",
"tensorflow.random.set_seed",
"numpy.random.seed",
"tensorflow.keras.layers.Flatten",
"numpy.mean",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.Conv2D",
"numpy.argmax",
"numpy.random.randint",
"tensorflow.reduce_sum",
"tensorflow.keras.models.clone_model",
"tensorflow.one_hot",
"tensorflow.keras.optimizers.Adam"
]
] |
rkj26/mgplvm-pytorch
|
[
"7d082d92be4d82ae8ab978e774ce83429444c14b"
] |
[
"mgplvm/crossval.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"
] |
[
[
"torch.get_default_dtype",
"numpy.zeros",
"numpy.ones",
"torch.nn.Parameter",
"numpy.std",
"torch.cuda.empty_cache",
"numpy.arange",
"torch.load",
"torch.set_default_dtype",
"numpy.var"
]
] |
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.show",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.arrow"
]
] |
LaudateCorpus1/benchmark
|
[
"2a8528f91dfbbd880e514b4deefa692a48c32af8",
"2a8528f91dfbbd880e514b4deefa692a48c32af8"
] |
[
"torchbenchmark/models/dcgan/__init__.py",
"torchbenchmark/util/framework/timm/timm_config.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"
] |
[
[
"torch.nn.init.constant_",
"torch.nn.Sigmoid",
"torch.nn.Tanh",
"torch.nn.BatchNorm2d",
"torch.nn.ConvTranspose2d",
"torch.nn.LeakyReLU",
"torch.nn.ReLU",
"torch.nn.init.normal_",
"torch.nn.Conv2d",
"torch.full",
"torch.jit.trace",
"torch.nn.BCELoss",
"torch.randn"
],
[
"torch.nn.CrossEntropyLoss"
]
] |
ZaneZh/IsaacGymEnvs
|
[
"adc20a5fbd70d77a716fefe86eb947f83d3efbd2"
] |
[
"isaacgymenvs/rl_games/algos_torch/models.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"
] |
[
[
"torch.distributions.Categorical",
"torch.stack",
"numpy.log",
"torch.distributions.Normal",
"torch.split",
"torch.nn.Module.__init__",
"torch.squeeze",
"torch.exp"
]
] |
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"
]
] |
mintzer/pupillometry-rf-back
|
[
"cfa86fa984a49dce0123798f8de5b838c02e10d5",
"cfa86fa984a49dce0123798f8de5b838c02e10d5"
] |
[
"venv/Lib/site-packages/psychopy/demos/coder/stimuli/clockface.py",
"venv/Lib/site-packages/psychopy/sound/audioclip.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"
] |
[
[
"numpy.array",
"numpy.floor"
],
[
"numpy.square",
"numpy.asarray",
"numpy.sum",
"numpy.tile",
"numpy.float32",
"numpy.vstack",
"numpy.atleast_2d"
]
] |
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.array",
"numpy.random.uniform",
"numpy.random.choice"
]
] |
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.array",
"pandas.Index",
"numpy.triu_indices",
"numpy.empty",
"numpy.asarray",
"numpy.array_equal",
"pandas.DataFrame",
"numpy.random.permutation",
"scipy.spatial.distance.squareform",
"matplotlib.pyplot.close",
"matplotlib.pyplot.subplots",
"numpy.arange",
"pandas.concat",
"numpy.hstack",
"pandas.Series",
"numpy.unique"
]
] |
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.savefig",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.ylabel"
]
] |
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.concatenate",
"numpy.full",
"torch.distributed.is_available",
"torch.distributed.get_world_size",
"numpy.random.seed",
"torch.distributed.is_initialized",
"numpy.where",
"numpy.random.randint",
"numpy.vstack"
]
] |
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"
] |
[
[
"torch.nn.Linear",
"torch.zeros",
"torch.cat",
"torch.nn.LSTM",
"torch.nn.MSELoss",
"torch.optim.lr_scheduler.StepLR",
"torch.no_grad",
"torch.from_numpy",
"torch.utils.data.DataLoader",
"pandas.concat",
"pandas.read_csv",
"torch.sum"
]
] |
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.DataFrame",
"pandas.merge",
"pandas.concat"
]
] |
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"
]
] |
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.Linear",
"torch.cat",
"torch.nn.MaxPool2d",
"torch.nn.Sequential",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.transpose"
]
] |
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.zeros_like",
"torch.stack",
"torch.ones_like"
]
] |
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"
]
] |
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.array",
"numpy.matrix",
"numpy.isscalar"
]
] |
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"
]
] |
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"
]
] |
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.DataFrame.from_records",
"numpy.zeros",
"pandas.DataFrame",
"pandas.concat",
"pandas.read_csv",
"numpy.floor"
]
] |
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.no_grad",
"torch.tensor",
"torch.randn",
"torch.sum"
]
] |
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.uint8",
"numpy.array",
"numpy.asarray",
"numpy.zeros",
"numpy.ones",
"numpy.eye",
"numpy.float64",
"numpy.random.randint",
"numpy.arange",
"numpy.random.random"
],
[
"numpy.concatenate",
"numpy.array",
"numpy.linalg.norm",
"numpy.zeros",
"numpy.where",
"numpy.clip"
]
] |
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"
]
] |
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.load",
"numpy.mean",
"numpy.cumsum",
"numpy.max",
"scipy.sparse.load_npz",
"numpy.nonzero",
"numpy.save",
"numpy.in1d",
"scipy.sparse.csr_matrix",
"scipy.sparse.issparse",
"numpy.array",
"numpy.zeros",
"numpy.diff",
"numpy.argsort",
"numpy.sum",
"numpy.ones",
"pandas.Categorical",
"scipy.sparse.lil_matrix",
"scipy.sparse.save_npz"
],
[
"numpy.dot",
"numpy.meshgrid",
"numpy.median",
"numpy.exp",
"numpy.min",
"numpy.mean",
"numpy.max",
"scipy.sparse.isspmatrix",
"numpy.log",
"numpy.nonzero",
"scipy.optimize.fmin",
"numpy.argmax",
"numpy.arange",
"numpy.sqrt",
"scipy.stats.ranksums",
"sklearn.decomposition.TruncatedSVD",
"numpy.in1d",
"numpy.nanmax",
"sklearn.decomposition.PCA",
"scipy.sparse.csr_matrix",
"numpy.vstack",
"numpy.log10",
"scipy.sparse.issparse",
"numpy.array",
"numpy.zeros",
"numpy.percentile",
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"numpy.diff",
"numpy.argsort",
"matplotlib.pyplot.show",
"numpy.log2",
"scipy.spatial.distance.pdist",
"numpy.cov",
"numpy.isnan",
"numpy.random.seed",
"matplotlib.pyplot.xlabel",
"numpy.sum",
"sklearn.neighbors.kneighbors_graph",
"matplotlib.pyplot.ylabel",
"scipy.sparse.lil_matrix",
"numpy.linspace",
"numpy.diag"
]
] |
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.array",
"sklearn.metrics.confusion_matrix",
"pandas.set_option",
"numpy.zeros",
"numpy.round",
"numpy.mean",
"numpy.diag",
"scipy.stats.sem",
"sklearn.metrics.precision_score",
"sklearn.metrics.f1_score",
"sklearn.metrics.roc_auc_score",
"scipy.stats.t.ppf",
"sklearn.metrics.recall_score"
]
] |
joshcarty/dgl
|
[
"4464b9734c1061bd84325a54883c5046031def37",
"4464b9734c1061bd84325a54883c5046031def37"
] |
[
"benchmarks/benchmarks/model_speed/bench_gat.py",
"tests/compute/test_heterograph.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"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.nn.ModuleList"
],
[
"scipy.sparse.coo_matrix",
"numpy.array",
"numpy.zeros",
"numpy.ones",
"scipy.sparse.rand",
"numpy.arange"
]
] |
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.array",
"pandas.date_range",
"numpy.where",
"numpy.arange",
"numpy.datetime64"
]
] |
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.nn.Linear",
"torch.cat",
"torch.optim.lr_scheduler.StepLR",
"torch.optim.lr_scheduler.CosineAnnealingLR",
"torch.nn.LeakyReLU",
"torch.nn.init.kaiming_normal_",
"torch.cuda.is_available",
"torch.exp",
"torch.nn.DataParallel",
"torch.sum",
"torch.nn.init.constant_",
"torch.nn.ConvTranspose2d",
"torch.nn.init.normal_",
"torch.nn.ReflectionPad2d",
"torch.nn.init.orthogonal_",
"torch.nn.init.xavier_normal_",
"torch.nn.functional.binary_cross_entropy_with_logits",
"torch.nn.ReplicationPad2d",
"torch.nn.Sequential",
"torch.nn.Tanh",
"torch.nn.ReLU",
"torch.nn.Conv2d",
"torch.mean",
"torch.rand",
"torch.nn.Dropout",
"torch.nn.Sigmoid",
"torch.nn.functional.mse_loss",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"torch.optim.lr_scheduler.LambdaLR",
"torch.nn.Embedding"
]
] |
kimdonggyun/OCEANpy
|
[
"afab9867eaad1ae56e70beaca4463493f4ee2efb"
] |
[
"scripts/graphcre.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"
] |
[
[
"numpy.array",
"matplotlib.dates.MinuteLocator",
"numpy.asarray",
"matplotlib.pyplot.savefig",
"matplotlib.dates.DateFormatter",
"matplotlib.pyplot.suptitle",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.close",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.title",
"matplotlib.ticker.FormatStrFormatter",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.gca"
]
] |
mahnooranjum/Programming_DataScience
|
[
"f7a4215d4615b3f8460c3a1944a585628cf6930d"
] |
[
"DataGeneration_DataScience/G6_XXC_circle.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')"
] |
[
[
"matplotlib.pyplot.show",
"sklearn.datasets.samples_generator.make_circles",
"matplotlib.pyplot.subplots",
"pandas.DataFrame"
]
] |
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"
]
] |
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.int",
"numpy.asarray"
]
] |
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.data.FixedLengthRecordDataset",
"tensorflow.logging.set_verbosity",
"tensorflow.decode_raw",
"tensorflow.image.random_flip_left_right",
"tensorflow.expand_dims",
"tensorflow.reshape",
"tensorflow.map_fn",
"tensorflow.transpose",
"tensorflow.image.resize_image_with_crop_or_pad",
"tensorflow.image.per_image_standardization",
"tensorflow.random_crop",
"tensorflow.cast"
]
] |
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.sum",
"numpy.min",
"scipy.stats.norm.cdf",
"numpy.multiply",
"numpy.sqrt",
"scipy.stats.chi2.cdf",
"scipy.stats.t.cdf",
"scipy.stats.t.ppf"
]
] |
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.shape",
"numpy.asarray",
"tensorflow.compat.v1.ConfigProto",
"tensorflow.compat.v1.InteractiveSession",
"tensorflow.config.experimental.set_memory_growth",
"tensorflow.lite.Interpreter",
"tensorflow.constant",
"tensorflow.config.experimental.list_physical_devices",
"tensorflow.saved_model.load"
]
] |
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.cuda.manual_seed_all",
"torch.distributed.init_process_group",
"numpy.random.seed",
"torch.multiprocessing.set_start_method",
"torch.multiprocessing.get_start_method",
"torch.cuda.device_count",
"torch.manual_seed",
"torch.cuda.set_device"
]
] |
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"
]
] |
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.arange",
"torch.scatter",
"torch.zeros_like",
"torch.flip",
"torch.cumsum"
]
] |
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.Linear",
"torch.nn.Dropout",
"torch.nn.LogSoftmax",
"torch.save",
"torch.no_grad",
"torch.nn.ReLU",
"torch.utils.data.DataLoader",
"torch.exp"
]
] |
seanjunheng2/PlasmaPy
|
[
"6df9583cc47375687a07300c0aa11ba31634d770",
"7b4e4aaf8b03d88b654456bca881329ade09e377"
] |
[
"plasmapy/formulary/tests/test_magnetostatics.py",
"plasmapy/formulary/radiation.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"
] |
[
[
"numpy.array",
"numpy.isclose",
"numpy.sqrt"
],
[
"numpy.max",
"numpy.min",
"numpy.sqrt",
"scipy.special.exp1"
]
] |
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.core.umath.radians",
"numpy.minimum",
"numpy.core.umath.expm1",
"numpy.signbit",
"numpy.exp",
"numpy.finfo",
"numpy.complex",
"numpy.logspace",
"numpy.log",
"numpy.arcsin",
"numpy.fmax",
"numpy.minimum.reduce",
"numpy.core.umath.exp",
"numpy.core.umath.sqrt",
"numpy.core.umath.multiply",
"numpy.argmax",
"numpy.logaddexp",
"numpy.clongdouble",
"numpy.log10",
"numpy.arctanh",
"numpy.csingle",
"numpy.array",
"numpy.core.umath.degrees",
"numpy.zeros",
"numpy.exp2",
"numpy.complex_",
"numpy.float64",
"numpy.arctan",
"numpy.fmin.reduce",
"numpy.absolute",
"numpy.ndarray.__new__",
"numpy.log2",
"numpy.fmax.reduce",
"numpy.logaddexp2",
"numpy.maximum.reduce",
"numpy.cdouble",
"numpy.core.umath.minimum",
"numpy.asarray",
"numpy.choose",
"numpy.core.umath.log1p",
"numpy.core.umath.log",
"numpy.atleast_1d",
"numpy.all",
"numpy.arcsinh",
"numpy.fmin",
"numpy.maximum"
]
] |
jjhenkel/dockerizeme
|
[
"eaa4fe5366f6b9adf74399eab01c712cacaeb279",
"eaa4fe5366f6b9adf74399eab01c712cacaeb279",
"eaa4fe5366f6b9adf74399eab01c712cacaeb279"
] |
[
"hard-gists/2f1b9a255993bf9b2629/snippet.py",
"hard-gists/3fdd80a08808bd275142d46863e92d68/snippet.py",
"hard-gists/d97eb37da84ce7329de6/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"
] |
[
[
"numpy.uint8"
],
[
"numpy.random.multinomial",
"numpy.exp",
"numpy.log"
],
[
"numpy.zeros"
]
] |
wangyuyue/oneflow
|
[
"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"
] |
[
"\"\"\"\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"
] |
[
[
"numpy.square",
"numpy.sum",
"numpy.mean",
"numpy.allclose",
"numpy.random.random"
],
[
"numpy.zeros_like",
"numpy.array",
"numpy.reshape",
"numpy.zeros",
"numpy.random.randn",
"numpy.allclose",
"numpy.random.uniform"
],
[
"numpy.random.random",
"numpy.ones"
],
[
"numpy.random.random",
"numpy.ones"
],
[
"numpy.array",
"numpy.ones"
]
] |
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"
]
] |
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"
]
] |
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"
] |
[
[
"matplotlib.pyplot.xlim",
"pandas.DataFrame",
"pandas.Categorical",
"pandas.read_csv",
"numpy.unique"
]
] |
Diyago/ML-DL-scripts
|
[
"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"
] |
[
"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"
] |
[
[
"numpy.array",
"torch.cat",
"sklearn.externals.joblib.dump",
"torch.from_numpy",
"sklearn.externals.joblib.load",
"numpy.stack",
"torch.utils.data.DataLoader",
"numpy.expand_dims"
],
[
"numpy.max",
"numpy.array",
"torch.cuda.manual_seed_all",
"numpy.asarray",
"numpy.zeros",
"numpy.random.seed",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.plot",
"numpy.sum",
"numpy.exp",
"pandas.DataFrame",
"torch.manual_seed",
"torch.cuda.is_available",
"numpy.cumsum",
"pandas.read_csv",
"numpy.atleast_2d"
]
] |
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.PCG64",
"numpy.random.Philox",
"numpy.random.RandomState"
],
[
"numpy.product",
"numpy.compress",
"numpy.array_equal",
"numpy.random.rand",
"numpy.cumsum",
"numpy.random.random",
"numpy.broadcast_to",
"numpy.empty",
"numpy.unravel_index",
"numpy.random.randint",
"numpy.arange",
"numpy.array",
"numpy.zeros",
"numpy.diff",
"numpy.allclose",
"numpy.argsort",
"numpy.searchsorted",
"numpy.ravel_multi_index",
"numpy.squeeze",
"numpy.cumprod",
"numpy.asarray",
"numpy.broadcast",
"numpy.random.RandomState",
"numpy.broadcast_arrays",
"numpy.ones",
"numpy.random.uniform",
"numpy.bartlett",
"numpy.repeat",
"numpy.diag",
"numpy.unique"
]
] |
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"
]
] |
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.DataFrame",
"pandas.concat"
]
] |
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"
]
] |
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.Linear",
"torch.nn.Dropout",
"torch.mul",
"torch.cat",
"numpy.count_nonzero",
"numpy.zeros",
"torch.nn.Tanh",
"torch.from_numpy",
"numpy.argwhere"
]
] |
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"
]
] |
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"
] |
[
[
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig",
"numpy.load",
"numpy.save",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel",
"sklearn.model_selection.train_test_split",
"numpy.logspace"
],
[
"numpy.array",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig",
"numpy.load",
"numpy.save",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel",
"numpy.hstack",
"numpy.logspace",
"numpy.vstack"
]
] |
kwyoke/cogdl
|
[
"df919b4fc7db40f8b035665edbcc7ed59f9d448e"
] |
[
"cogdl/tasks/link_prediction.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"
] |
[
[
"torch.device",
"numpy.array",
"numpy.dot",
"numpy.linalg.norm",
"torch.unique",
"sklearn.metrics.precision_recall_curve",
"torch.cuda.empty_cache",
"torch.cuda.is_available",
"sklearn.metrics.auc",
"sklearn.metrics.f1_score",
"sklearn.metrics.roc_auc_score"
]
] |
cbworden/shakemap
|
[
"f0a49317ce3e98d8cce5ba148797ace47dd1d898",
"f0a49317ce3e98d8cce5ba148797ace47dd1d898"
] |
[
"tests/shakelib/gmpe/nga_east_test.py",
"utils/get_sm_stations.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"
] |
[
[
"numpy.testing.assert_allclose",
"numpy.log10",
"numpy.full_like"
],
[
"pandas.DataFrame"
]
] |
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.Linear",
"torch.nn.Dropout",
"torch.nn.LayerNorm",
"sklearn.model_selection.StratifiedKFold",
"torch.nn.Sequential",
"torch.set_grad_enabled",
"torch.softmax",
"torch.nn.ReLU",
"numpy.swapaxes",
"torch.tensor",
"torch.utils.data.DataLoader",
"numpy.argmax",
"numpy.hstack",
"torch.nn.CrossEntropyLoss",
"numpy.vstack"
]
] |
Unknown-Data/QGCN
|
[
"e074ada31c13b6de6eabba2b2ebce90e88fdfdbf"
] |
[
"graph-measures/measure_tests/test_graph.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"
] |
[
[
"pandas.read_csv"
]
] |
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"
] |
[
[
"numpy.concatenate",
"numpy.array",
"numpy.array_equal",
"pandas.DataFrame",
"sklearn.metrics.precision_recall_fscore_support",
"sklearn.metrics.accuracy_score",
"torch.nn.functional.softmax",
"torch.argmax"
],
[
"torch.nn.Dropout",
"torch.nn.LayerNorm",
"torch.nn.Conv1d",
"torch.nn.ReLU",
"torch.nn.Conv2d"
]
] |
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.sin",
"numpy.copyto",
"numpy.linalg.norm",
"numpy.zeros",
"numpy.arange",
"numpy.cos",
"numpy.sqrt"
]
] |
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.array",
"numpy.empty",
"numpy.zeros",
"numpy.random.RandomState",
"numpy.minimum",
"numpy.logical_and",
"torch.from_numpy",
"numpy.arange",
"numpy.clip",
"numpy.hstack",
"numpy.expand_dims",
"numpy.maximum"
],
[
"numpy.empty",
"numpy.mean",
"numpy.expand_dims",
"numpy.hstack",
"numpy.vstack"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.